@forgenex/cli 0.4.1 → 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/GUIA-IA.md +84 -5
- package/README.md +83 -40
- package/REFERENCIA.md +196 -0
- package/dist/forgenex.js +55 -19
- package/dist/locales/ca.js +1 -1
- package/dist/locales/en.js +1 -1
- package/dist/locales/es.js +1 -1
- package/ejemplos/escuela-natacion/README.md +26 -0
- package/ejemplos/escuela-natacion/extension.json +83 -0
- package/ejemplos/escuela-natacion/funciones/opciones.js +3 -0
- package/ejemplos/escuela-natacion/interfaz/agenda.html +5 -0
- package/ejemplos/escuela-natacion/interfaz/alta.html +2 -0
- package/ejemplos/escuela-natacion/interfaz/alta.js +31 -0
- package/ejemplos/escuela-natacion/interfaz/horario.js +64 -0
- package/ejemplos/escuela-natacion/interfaz/inscripcion.html +4 -0
- package/ejemplos/escuela-natacion/interfaz/inscripcion.js +29 -0
- package/ejemplos/escuela-natacion/interfaz/panel.html +7 -0
- package/ejemplos/escuela-natacion/interfaz/panel.js +103 -0
- package/ejemplos/escuela-natacion/interfaz/piscina.html +5 -0
- package/ejemplos/escuela-natacion/solucion.json +399 -0
- package/ejemplos/hola-alpine/interfaz/index.html +4 -1
- package/ejemplos/kit-visual/extension.json +13 -0
- package/ejemplos/kit-visual/interfaz/galeria.js +71 -0
- package/ejemplos/kit-visual/interfaz/index.html +9 -0
- package/kit/pantalla.mjs +980 -0
- package/licencias.txt +1 -1
- package/package.json +2 -1
package/dist/forgenex.js
CHANGED
|
@@ -1,45 +1,81 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __fgxRequire } from "node:module"; const require = __fgxRequire(import.meta.url);
|
|
3
|
-
var Qg=Object.defineProperty;var m=(e,o,t)=>()=>{if(t)throw t[0];try{return e&&(o=e(e=0)),o}catch(n){throw t=[n],n}};var Gg=(e,o)=>{for(var t in o)Qg(e,t,{get:o[t],enumerable:!0})};import{AsyncLocalStorage as Hg}from"node:async_hooks";import{readdirSync as Xg}from"node:fs";import{createRequire as Yg}from"node:module";import{fileURLToPath as Kg}from"node:url";function io(e,o){let n=Gc[e]?.[o];if(n!==void 0)return n;for(let r of ob[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 Zg,eb,Gc,ob,tb,Mo,an=m(()=>{Zg=Xg(new URL("./locales/",import.meta.url)).filter(e=>/\.(?:ts|js)$/.test(e)&&!e.endsWith(".d.ts")),eb=Yg(import.meta.url),Gc=Object.fromEntries(Zg.map(e=>[e.replace(/\.(?:ts|js)$/,""),eb(Kg(new URL(`./locales/${e}`,import.meta.url))).default])),ob=Object.fromEntries(Object.entries(Gc).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)])),tb=new Hg,Mo=()=>tb.getStore()?.idioma??"es"});var L,i,E=m(()=>{an();L=class extends Error{constructor(t,n,r,a=!0,s){super(a?io(Mo(),r):r);this.estado=t;this.codigo=n;this.datos=s}estado;codigo;datos},i=(e,o=!0)=>new L(400,"peticion_invalida",e,o)});function Hc(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 Xc=m(()=>{E()});var Q,rb,Yc,Kc=m(()=>{Q={id:"Id del registro."},rb=[{nombre:"contacto.creado",descripcion:"Se ha creado un contacto.",datos:Q},{nombre:"contacto.actualizado",descripcion:"Han cambiado datos de un contacto.",datos:{...Q,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:{...Q,fusionado_en:"Si se fusion\xF3: en cu\xE1l."}},{nombre:"empresa.creada",descripcion:"Se ha creado una empresa.",datos:Q},{nombre:"empresa.actualizada",descripcion:"Han cambiado datos de una empresa.",datos:{...Q,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"empresa.borrada",descripcion:"Se ha borrado una empresa.",datos:Q},{nombre:"contacto.fusionado",descripcion:"Un contacto se ha fusionado en otro: quien guarde su id, que lo cambie por el que queda.",datos:{...Q,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:{...Q,se_va:"La que se fue.",queda:"La que queda (= id)."}},{nombre:"oportunidad.creada",descripcion:"Se ha creado una oportunidad.",datos:Q},{nombre:"oportunidad.actualizada",descripcion:"Han cambiado datos de una oportunidad (no la etapa).",datos:{...Q,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"oportunidad.etapa_cambiada",descripcion:"Una oportunidad ha cambiado de etapa.",datos:{...Q,de:"Etapa anterior.",a:"Etapa nueva."}},{nombre:"oportunidad.ganada",descripcion:"Una oportunidad ha pasado a ganada (adem\xE1s de etapa_cambiada).",datos:{...Q,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:{...Q,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:Q},{nombre:"oportunidad.borrada",descripcion:"Se ha borrado una oportunidad.",datos:Q},{nombre:"nota.creada",descripcion:"Nueva nota en el hilo de un contacto o de una oportunidad.",datos:{...Q,contacto_id:"Si es de un contacto.",oportunidad_id:"Si es de una oportunidad."}},{nombre:"nota.actualizada",descripcion:"Se ha editado una nota.",datos:Q},{nombre:"nota.borrada",descripcion:"Se ha borrado una nota.",datos:Q},{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:{...Q,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:{...Q,contacto_id:"Su contacto."}},{nombre:"tarea.actualizada",descripcion:"Ha cambiado una tarea (o se ha reabierto).",datos:{...Q,campos:"Qu\xE9 columnas (si se sabe)."}},{nombre:"tarea.completada",descripcion:"Se ha completado una tarea.",datos:Q},{nombre:"tarea.borrada",descripcion:"Se ha borrado una tarea.",datos:Q},{nombre:"contacto.etiquetado",descripcion:"Una Persona ha recibido una etiqueta (una vez por etiqueta a\xF1adida, venga de donde venga).",datos:{...Q,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:{...Q,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:{...Q,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:{...Q,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:{...Q,modulo:"La clave del m\xF3dulo.",campos:"Qu\xE9 campos."}},{nombre:"registro.borrado",descripcion:"Se ha borrado un registro de un m\xF3dulo.",datos:{...Q,modulo:"La clave del m\xF3dulo."}}],Yc=rb.map(e=>e.nombre)});function ib(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 Zc(e){let o=e.trim().split(/\s+/);if(o.length!==5)return null;let t=o.map((r,a)=>ib(r,nb[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 el(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 nb,R_,ol=m(()=>{nb=[[0,59],[0,23],[1,31],[1,12],[0,7]];R_=new Intl.DateTimeFormat("en-GB",{timeZone:"Europe/Madrid",hourCycle:"h23",minute:"numeric",hour:"numeric",day:"numeric",month:"numeric",weekday:"short"})});function tl(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,z.ms),memoriaMb:o(e?.tope?.memoria_mb,z.memoriaMb)}}var z,gr=m(()=>{z={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 rl(e){if(!e.startsWith("*."))return!1;let o=e.slice(2).toLowerCase();if(sb.has(o)||cb.test(o))return!0;let t=o.split(".");return t.length===2&&t[1].length===2&&ab.has(t[0])}var ab,sb,cb,nl=m(()=>{ab=new Set(["co","com","net","org","gov","gob","edu","ac","nom","mil","ltd","plc","me","or","ne","go","info","biz","int"]),sb=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"]),cb=/^(s3([.-][a-z0-9-]+)?\.amazonaws\.com|blogspot\.[a-z]{2,3}(\.[a-z]{2})?)$/});function Vi(e,o=0){if(o>20)throw i("El manifiesto anida demasiado.");if(Array.isArray(e))return e.forEach(t=>Vi(t,o+1));if(pe(e))for(let t of Object.keys(e)){if(lb.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);Vi(e[t],o+1)}}function ye(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 gb(e,o,t={}){return fb.test(e.replace(hb,""))?`\xAB${o}\xBB: lleva caracteres de control, invisibles o de direcci\xF3n del texto.`:t.reservar&&!t.firmada&&Ji(e)?`\xAB${o}\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.`:null}function V(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=gb(r,o);if(a)throw i(a);return r}function vb(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(Ui).filter(Boolean)}function bl(e,o,t){let n=X(e,o,ml,t);if(rl(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 X(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 ge(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 Wi(e,o){let t=V(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||!ml.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 yb(e){let[o,t]=e.split(".");return Ui(o??"")==="forgenex"||Ui(t??"")==="forgenex"}function ao(e){if(Object.hasOwn(Do,e))return e;let o=e.startsWith("mod_")?e.slice(4):e;return pb.test(o)?`mod_${o}`:null}function ul(e,o,t){if(!pe(e))throw i(`\xAB${o}\xBB: un nombre de contrato, o { contrato, modulos, eventos, herramientas }.`);ye(e,["contrato","titulo","modulos","eventos","herramientas",...t],o);let n=X(e.contrato,`${o}.contrato`,Bi,"un nombre de contrato (\xABtaller.vehiculos\xBB)"),r=e.titulo===void 0?null:V(e.titulo,`${o}.titulo`,80),a={};if(e.modulos!==void 0){if(!pe(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 f=ao(u);if(!f)throw i(`\xAB${o}.modulos\xBB: \xAB${u.slice(0,60)}\xBB no es un m\xF3dulo (min\xFAsculas, n\xFAmeros y _).`);if(a[f])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"||!Lo.includes(y)))throw i(`\xAB${o}.modulos.${u}\xBB: operaciones ${Lo.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[f]=Lo.filter(y=>b.has(y))}}let s=ge(ce(e.eventos,`${o}.eventos`,3).map((d,u)=>{if(typeof d!="string"||!il.includes(d))throw i(`\xAB${o}.eventos[${u}]\xBB: ${il.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=ge(ce(e.herramientas,`${o}.herramientas`,20).map((d,u)=>X(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 _b(e){if(e===void 0)return{modulos:{},almacen:!1,red_hacia:[],eventos:[],archivos:[]};if(!pe(e))throw i("\xABpermisos\xBB: un objeto.");ye(e,["modulos","almacen","red_hacia","eventos","archivos"],"Permisos");let o={};if(e.modulos!==void 0){if(!pe(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=ao(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=Do[d]?.ops??Lo,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 f=new Set(p);if((f.has("editar")||f.has("borrar"))&&!f.has("ver"))throw i(`\xABpermisos.modulos.${s}\xBB: para \xABeditar\xBB o \xABborrar\xBB hace falta \xABver\xBB.`);o[d]=Lo.filter(h=>f.has(h))}}if(e.almacen!==void 0&&typeof e.almacen!="boolean")throw i("\xABpermisos.almacen\xBB: s\xED o no (true/false).");let t=ge(ce(e.red_hacia,"permisos.red_hacia",20).map((a,s)=>bl(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=ge(ce(e.eventos,"permisos.eventos",40).map((a,s)=>{if(typeof a!="string"||!Yc.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"||!al.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:al.filter(a=>r.includes(a))}}function dl(e,o){let t=o.lastIndexOf(".");if(t<1)return!1;let n=ao(o.slice(0,t));return!!n&&(e.modulos[n]??[]).includes(o.slice(t+1))}function pl(e,o){let t={};if(e===void 0)return t;if(!pe(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(X(n,o,Io,"nombres de campo en min\xFAsculas y _"),!pe(r))throw i(`\xAB${o}.${n}\xBB: { tipo, desc }.`);ye(r,["tipo","desc","requerido"],`${o}.${n}`);let a=V(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:V(r.desc,`${o}.${n}.desc`,200),requerido:r.requerido===!0}}return t}function zo(e,o={}){if(typeof e=="string"){if(e.length>cn)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>cn)throw i("El manifiesto pasa de 256 KB.");if(!pe(e))throw i("El manifiesto tiene que ser un objeto.");if(Vi(e),e.formato!==nt)throw i(`No es una app (formato \xAB${nt}\xBB).`);if(ye(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>dn)throw i("La app es de una versi\xF3n del formato m\xE1s nueva que este CRM.");let t=X(e.id,"id",sn,"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&&yb(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=V(e.nombre,"nombre",80),r=X(e.version,"version",ub,"versi\xF3n semver (\xAB1.0.0\xBB)"),a;if(typeof e.autor=="string")a={nombre:V(e.autor,"autor",120)};else if(pe(e.autor))ye(e.autor,["nombre","web"],"Autor"),a={nombre:V(e.autor.nombre,"autor.nombre",120),...e.autor.web!==void 0?{web:Wi(e.autor.web,"autor.web")}:{}};else throw i("Falta \xABautor\xBB (un nombre, o { nombre, web }).");if(!o.firmada){if(Ji(n))throw i("\xABnombre\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.");if(Ji(a.nombre))throw i("\xABautor\xBB: \xABForgeNEX\xBB est\xE1 reservado a lo que publica ForgeNEX.")}let s=e.icono===void 0?"puzzle":X(e.icono,"icono",cl,"un icono de lucide (\xABpuzzle\xBB)"),c=ge(ce(e.idiomas,"idiomas",30).map(($,M)=>X($,`idiomas[${M}]`,db,"un c\xF3digo de idioma (\xABes\xBB, \xABen\xBB, \xABpt-BR\xBB)")),$=>$,"idiomas"),d=null;if(e.compatible_crm!==void 0){let M=V(e.compatible_crm,"compatible_crm",80).split(/\s+/);if(M.length>2||!M.every(g=>sl.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=M.join(" ")}let u=e.licencia===void 0?null:V(e.licencia,"licencia",40),p=e.politica_datos===void 0?{}:{politica_datos:Wi(e.politica_datos,"politica_datos")},f=ge(ce(e.depende_de,"depende_de",20).map(($,M)=>{if(typeof $=="string")return{id:X($,`depende_de[${M}]`,sn,"el id de otra app"),version:null};if(!pe($))throw i(`\xABdepende_de[${M}]\xBB: el id de otra app, o { id, version }.`);ye($,["id","version"],`depende_de[${M}]`);let g=$.version===void 0?null:V($.version,`depende_de[${M}].version`,80);if(g!==null&&!g.split(/\s+/).every(x=>sl.test(x)))throw i(`\xABdepende_de[${M}].version\xBB: un rango (\xAB>=1.0.0\xBB).`);return{id:X($.id,`depende_de[${M}].id`,sn,"el id de otra app"),version:g}}),$=>$.id,"depende_de");if(f.some($=>$.id===t))throw i("\xABdepende_de\xBB: una app no depende de s\xED misma.");let h=_b(e.permisos),b=ge(ce(e.usa,"usa",20).map(($,M)=>{let g=`usa[${M}]`;if(typeof $=="string")return{...ll(X($,g,Bi,"un nombre de contrato (\xABtaller.citas\xBB)")),de:null};let x=ul($,g,["de"]),A=X($.de,`${g}.de`,sn,"el id de la app que lo ofrece (\xABcom.taller.vehiculos\xBB)");if(A===t)throw i(`\xAB${g}.de\xBB: una app no se usa a s\xED misma.`);return{...x,de:A}}),$=>`${$.de??""}/${$.contrato}`,"usa"),y=e.solucion===void 0||e.solucion===null?null:X(e.solucion,"solucion",Fi,"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=ge(ce(e.montajes,"montajes",20).map(($,M)=>{let g=`montajes[${M}]`;if(!pe($))throw i(`\xAB${g}\xBB: un objeto.`);ye($,["id","punto","entrada","titulo","icono","modulo","permiso","funciones"],g);let x=V($.punto,`${g}.punto`,20);if(!kt.includes(x))throw i(`\xAB${g}.punto\xBB: ${kt.join(", ")}.`);let A=null;if(br.has(x)){if(A=ao(V($.modulo,`${g}.modulo`,64)),!A)throw i(`\xAB${g}.modulo\xBB: el m\xF3dulo donde se cuelga.`);if(!(h.modulos[A]??[]).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 ${[...br].join(", ")}.`);let k=$.permiso===void 0?null:V($.permiso,`${g}.permiso`,80);if(k!==null&&!dl(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 J;if(x==="publica")J=ge(ce($.funciones,`${g}.funciones`,10).map((F,G)=>X(F,`${g}.funciones[${G}]`,Io,"el nombre de una funci\xF3n")),F=>F,`${g}.funciones`);else if($.funciones!==void 0)throw i(`\xAB${g}.funciones\xBB: solo en el montaje \xABpublica\xBB.`);return{id:X($.id,`${g}.id`,/^[a-z][a-z0-9_-]{0,40}$/,"min\xFAsculas, n\xFAmeros, _ y -"),punto:x,entrada:X($.entrada,`${g}.entrada`,Fi,"un fichero del paquete (\xABinterfaz/index.html\xBB)"),titulo:V($.titulo,`${g}.titulo`,60),icono:$.icono===void 0?null:X($.icono,`${g}.icono`,cl,"un icono de lucide"),modulo:A,permiso:k,...J?{funciones:J}:{}}}),$=>$.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=ge(ce(e.funciones,"funciones",20).map(($,M)=>{let g=`funciones[${M}]`;if(!pe($))throw i(`\xAB${g}\xBB: un objeto.`);if(ye($,["nombre","titulo","descripcion","entrada","disparador","tope","red","parametros","salida"],g),!pe($.disparador))throw i(`\xAB${g}.disparador\xBB: { tipo, \u2026 }.`);ye($.disparador,["tipo","evento","cron"],`${g}.disparador`);let x=V($.disparador.tipo,`${g}.disparador.tipo`,20);if(!ln.includes(x))throw i(`\xAB${g}.disparador.tipo\xBB: ${ln.join(", ")}.`);let A={tipo:x};if(x==="evento"){let H=V($.disparador.evento,`${g}.disparador.evento`,80);if(!h.eventos.includes(H)&&!b.some(Qe=>Qe.eventos.includes(H)))throw i(`\xAB${g}.disparador.evento\xBB: \xAB${H}\xBB tiene que estar en \xABpermisos.eventos\xBB (o en los \xABeventos\xBB de un contrato de \xABusa\xBB).`);A.evento=H}if(x==="programada"){A.cron=X($.disparador.cron,`${g}.disparador.cron`,mb,"un cron de 5 campos (\xAB0 7 * * 1-5\xBB)");let H=Zc(A.cron);if(!H)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(el(H)<z.cronMinutos)throw i(`\xAB${g}.disparador.cron\xBB: como mucho una vez cada ${z.cronMinutos} minutos.`)}let k=pe($.tope)?$.tope:{};$.tope!==void 0&&ye(k,["ms","memoria_mb"],`${g}.tope`);let J=k.ms===void 0?5e3:Number(k.ms),F=k.memoria_mb===void 0?64:Number(k.memoria_mb);if(!Number.isInteger(J)||J<z.ms.min||J>z.ms.max)throw i(`\xAB${g}.tope.ms\xBB: de ${z.ms.min} a ${z.ms.max}.`);if(!Number.isInteger(F)||F<z.memoriaMb.min||F>z.memoriaMb.max)throw i(`\xAB${g}.tope.memoria_mb\xBB: de ${z.memoriaMb.min} a ${z.memoriaMb.max}.`);let G=ce($.red,`${g}.red`,10).map((H,Qe)=>bl(H,`${g}.red[${Qe}]`,"un dominio"));for(let H of G)if(!Nb(h.red_hacia,H))throw i(`\xAB${g}.red\xBB: \xAB${H}\xBB tiene que estar en \xABpermisos.red_hacia\xBB.`);let Je=pl($.parametros,`${g}.parametros`),tt={},rt=ge(ce($.salida,`${g}.salida`,30).map((H,Qe)=>{let Ce=`${g}.salida[${Qe}]`;if(!pe(H))return X(H,Ce,Io,"nombres en min\xFAsculas y _ (o { clave, titulo })");ye(H,["clave","titulo"],Ce);let De=X(H.clave,`${Ce}.clave`,Io,"nombres en min\xFAsculas y _");return H.titulo!==void 0&&(tt[De]=V(H.titulo,`${Ce}.titulo`,60)),De}),H=>H,`${g}.salida`);if(x==="publica"&&G.length)throw i(`\xAB${g}.red\xBB: una funci\xF3n \xABpublica\xBB no sale a la red (solo lee el CRM).`);if(Object.keys(Je).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:X($.nombre,`${g}.nombre`,Io,"min\xFAsculas, n\xFAmeros y _"),titulo:$.titulo===void 0?null:V($.titulo,`${g}.titulo`,80),descripcion:$.descripcion===void 0?null:V($.descripcion,`${g}.descripcion`,300,!1),entrada:X($.entrada,`${g}.entrada`,Fi,"un fichero del paquete (\xABfunciones/calcular.js\xBB)"),disparador:A,tope:{ms:J,memoria_mb:F},red:G,parametros:Je,salida:rt,titulos_salida:tt}}),$=>$.nombre,"funciones"),_=null;if(e.servidor!==void 0&&e.servidor!==null){if(!pe(e.servidor))throw i("\xABservidor\xBB: { url, webhooks }.");ye(e.servidor,["url","webhooks"],"Servidor");let $=ge(ce(e.servidor.webhooks,"servidor.webhooks",40).map((M,g)=>{if(typeof M!="string"||!h.eventos.includes(M))throw i(`\xABservidor.webhooks[${g}]\xBB: un evento que est\xE9 en \xABpermisos.eventos\xBB.`);return M}),M=>M,"servidor.webhooks");_={url:Wi(e.servidor.url,"servidor.url"),webhooks:$}}let C=new Set(w.map($=>$.nombre));for(let $ of v)for(let[M,g]of($.funciones??[]).entries()){let x=w.find(A=>A.nombre===g);if(!x)throw i(`\xABmontajes\xBB.\xAB${$.id}\xBB.funciones[${M}]: \xAB${g}\xBB tiene que estar en \xABfunciones\xBB.`);if(x.disparador.tipo!=="publica")throw i(`\xABmontajes\xBB.\xAB${$.id}\xBB.funciones[${M}]: \xAB${g}\xBB tiene que ser de disparador \xABpublica\xBB.`)}let S=ge(ce(e.herramientas_ia,"herramientas_ia",20).map(($,M)=>{let g=`herramientas_ia[${M}]`;if(!pe($))throw i(`\xAB${g}\xBB: un objeto.`);ye($,["nombre","descripcion","entrada","salida","riesgo","funcion","escribe","permiso"],g);let x=pl($.entrada,`${g}.entrada`),A=V($.riesgo,`${g}.riesgo`,10);if(!["bajo","medio","alto"].includes(A))throw i(`\xAB${g}.riesgo\xBB: bajo, medio o alto.`);let k=V($.funcion,`${g}.funcion`,41);if(!C.has(k))throw i(`\xAB${g}.funcion\xBB: \xAB${k}\xBB tiene que estar en \xABfunciones\xBB.`);if(!["herramienta","calculo"].includes(w.find(F=>F.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 J=null;if($.permiso!==void 0){let F=V($.permiso,`${g}.permiso`,80),G=F.lastIndexOf("."),Je=G>0?ao(F.slice(0,G)):null;if(!Je||!dl(h,F))throw i(`\xAB${g}.permiso\xBB: \xAB${F}\xBB no est\xE1 en \xABpermisos.modulos\xBB.`);J=`${Je}.${F.slice(G+1)}`}return{nombre:X($.nombre,`${g}.nombre`,/^[a-z][a-z0-9_]{2,40}$/,"min\xFAsculas, n\xFAmeros y _ (3 a 41)"),descripcion:V($.descripcion,`${g}.descripcion`,500),entrada:x,salida:ge(ce($.salida,`${g}.salida`,30).map((F,G)=>X(F,`${g}.salida[${G}]`,Io,"nombres de campo")),F=>F,`${g}.salida`),riesgo:A,funcion:k,escribe:$.escribe===!0,permiso:J}}),$=>$.nombre,"herramientas_ia"),P=ge(ce(e.ofrece,"ofrece",20).map(($,M)=>{let g=`ofrece[${M}]`;if(typeof $=="string")return ll(X($,g,Bi,"un nombre de contrato (\xABtaller.citas\xBB)"));let x=ul($,g,[]);for(let[A,k]of Object.entries(x.modulos)){if(!A.startsWith("mod_"))throw i(`\xAB${g}.modulos\xBB: \xAB${A}\xBB es de serie; un contrato solo comparte m\xF3dulos de la soluci\xF3n de la app.`);let J=h.modulos[A]??[],F=k.find(G=>!J.includes(G));if(F)throw i(`\xAB${g}.modulos.${A.slice(4)}\xBB: ofrece \xAB${F}\xBB y \xABpermisos.modulos\xBB no lo pide (nadie da lo que no tiene).`)}for(let A of x.eventos)if(!h.eventos.includes(A))throw i(`\xAB${g}.eventos\xBB: \xAB${A}\xBB tiene que estar en \xABpermisos.eventos\xBB.`);for(let A of x.herramientas){let k=S.find(J=>J.nombre===A);if(!k)throw i(`\xAB${g}.herramientas\xBB: \xAB${A}\xBB tiene que estar en \xABherramientas_ia\xBB.`);if(k.escribe)throw i(`\xAB${g}.herramientas\xBB: \xAB${A}\xBB escribe; un contrato solo comparte herramientas que consultan.`)}return x}),$=>$.contrato,"ofrece"),Z=ge(ce(e.ajustes,"ajustes",40).map(($,M)=>{let g=`ajustes[${M}]`;if(!pe($))throw i(`\xAB${g}\xBB: un objeto.`);ye($,["clave","etiqueta","tipo","opciones","requerido"],g);let x=V($.tipo,`${g}.tipo`,10);if(!un.includes(x))throw i(`\xAB${g}.tipo\xBB: ${un.join(", ")}.`);let A=ce($.opciones,`${g}.opciones`,50).map((k,J)=>{if(!pe(k))throw i(`\xAB${g}.opciones[${J}]\xBB: { valor, etiqueta }.`);return ye(k,["valor","etiqueta"],`${g}.opciones[${J}]`),{valor:V(k.valor,`${g}.opciones[${J}].valor`,60),etiqueta:V(k.etiqueta,`${g}.opciones[${J}].etiqueta`,80)}});if(x==="opcion"&&!A.length)throw i(`\xAB${g}.opciones\xBB: un ajuste de tipo opci\xF3n necesita sus opciones.`);if(x!=="opcion"&&A.length)throw i(`\xAB${g}.opciones\xBB: solo en los de tipo opci\xF3n.`);return{clave:X($.clave,`${g}.clave`,Io,"min\xFAsculas, n\xFAmeros y _"),etiqueta:V($.etiqueta,`${g}.etiqueta`,80),tipo:x,opciones:ge(A,k=>k.valor,`${g}.opciones`),requerido:$.requerido===!0}}),$=>$.clave,"ajustes"),we=ge(ce(e.secretos,"secretos",10).map(($,M)=>{let g=`secretos[${M}]`;if(!pe($))throw i(`\xAB${g}\xBB: un objeto.`);return ye($,["clave","etiqueta","descripcion"],g),{clave:X($.clave,`${g}.clave`,Io,"min\xFAsculas, n\xFAmeros y _"),etiqueta:V($.etiqueta,`${g}.etiqueta`,80),descripcion:V($.descripcion,`${g}.descripcion`,300,!1)}}),$=>$.clave,"secretos");return{formato:nt,formato_version:e.formato_version,id:t,nombre:n,descripcion:V(e.descripcion,"descripcion",500,!1),version:r,autor:a,icono:s,idiomas:c,compatible_crm:d,licencia:u,...p,depende_de:f,ofrece:P,usa:b,solucion:y,montajes:v,funciones:w,servidor:_,herramientas_ia:S,ajustes:Z,secretos:we,...e.conexiones!==void 0?{conexiones:Hc(e.conexiones)}:{},permisos:h}}var nt,dn,cn,Do,Lo,kt,pn,br,ln,un,il,al,lb,sn,ub,sl,cl,db,Bi,Io,pb,Fi,ml,mb,pe,fl,fb,W_,hb,hl,gl,bb,wb,Ui,Ji,ll,Nb,Pt=m(()=>{Xc();E();Kc();ol();gr();nl();nt="forgenex.extension",dn=1,cn=256e3,Do={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"]}},Lo=["ver","crear","editar","borrar"],kt=["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"],pn=new Set(["pagina","ficha_pestana","ficha_bloque","inicio_bloque","accion_ficha","accion_tabla","vista","ajustes","publica"]),br=new Set(["ficha_pestana","ficha_bloque","accion_ficha","accion_tabla","vista"]),ln=["evento","programada","webhook","automatizacion","calculo","herramienta","publica"],un=["texto","numero","si_no","opcion","modulo","campo"],il=["registro.creado","registro.actualizado","registro.borrado"],al=["leer","escribir"],lb=new Set(["__proto__","constructor","prototype"]),sn=/^[a-z][a-z0-9-]{0,62}(\.[a-z0-9][a-z0-9-]{0,62}){1,6}$/,ub=/^(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=/^(>=|<=|>|<|=|\^|~)?(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})?$/,cl=/^[a-z0-9-]{1,40}$/,db=/^[a-z]{2,3}(-[A-Z]{2})?$/,Bi=/^[a-z][a-z0-9_.-]{0,79}$/,Io=/^[a-z][a-z0-9_]{0,40}$/,pb=/^[a-z][a-z0-9_]{0,59}$/,Fi=/^(?!\/)(?!.*\/\/)(?!.*(^|\/)\.\.?(\/|$))[A-Za-z0-9_.\/-]{1,200}$/,ml=/^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,mb=/^[0-9*,\/-]+( [0-9*,\/-]+){4}$/,pe=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)`,fb=new RegExp(fl,"u"),W_=new RegExp(fl,"gu"),hb=new RegExp("(?<=\\p{Extended_Pictographic}[\\uFE0F\\p{Emoji_Modifier}]?)\\u200D(?=\\p{Extended_Pictographic})","gu");hl={\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"},gl={\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"},bb=new RegExp(`[${Object.keys(hl).join("")}]`,"gu"),wb=new RegExp(`[${Object.keys(gl).join("")}]`,"gu"),Ui=e=>e.normalize("NFKC").replace(bb,o=>hl[o]).toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"").replace(wb,o=>gl[o]).replace(/[^\p{L}\p{N}]/gu,"");Ji=e=>{let o=vb(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};ll=e=>({contrato:e,titulo:null,modulos:{},eventos:[],herramientas:[]});Nb=(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 U(e){return typeof e=="string"}function so(e){return typeof e=="number"}function it(e){return typeof e=="boolean"}function at(e){return e===null}function Qi(e){return e instanceof Date}function st(e){return typeof e=="bigint"}function wl(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 wr(e){return qe(e)?e:[e]}function qe(e){return Array.isArray(e)}function vl(e){return e instanceof Error?e.message:String(e)}var N=m(()=>{});var J_,yl=m(()=>{N();J_=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 T,ne=m(()=>{N();T=l({is(e){return e.kind==="IdentifierNode"},create(e){return l({kind:"IdentifierNode",name:e})}})});var K_,_l=m(()=>{N();ne();K_=l({is(e){return e.kind==="CreateIndexNode"},create(e){return l({kind:"CreateIndexNode",name:T.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var t0,Nl=m(()=>{N();ne();t0=l({is(e){return e.kind==="CreateSchemaNode"},create(e,o){return l({kind:"CreateSchemaNode",schema:T.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var i0,$l=m(()=>{N();i0=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 Ge,ct=m(()=>{N();ne();Ge=l({is(e){return e.kind==="SchemableIdentifierNode"},create(e){return l({kind:"SchemableIdentifierNode",identifier:T.create(e)})},createWithSchema(e,o){return l({kind:"SchemableIdentifierNode",schema:T.create(e),identifier:T.create(o)})}})});var p0,xl=m(()=>{N();ct();p0=l({is(e){return e.kind==="DropIndexNode"},create(e,o){return l({kind:"DropIndexNode",name:Ge.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var g0,Cl=m(()=>{N();ne();g0=l({is(e){return e.kind==="DropSchemaNode"},create(e,o){return l({kind:"DropSchemaNode",schema:T.create(e),...o})},cloneWith(e,o){return l({...e,...o})}})});var v0,jl=m(()=>{N();v0=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 Re,No=m(()=>{N();Re=l({is(e){return e.kind==="AliasNode"},create(e,o){return l({kind:"AliasNode",node:e,alias:o})}})});var Fo,vr=m(()=>{N();ct();Fo=l({is(e){return e.kind==="TableNode"},create(e){return l({kind:"TableNode",table:Ge.create(e)})},createWithSchema(e,o){return l({kind:"TableNode",table:Ge.createWithSchema(e,o)})}})});function ie(e){return je(e)&&_e(e.toOperationNode)}var ze=m(()=>{N()});function mn(e){return je(e)&&"expressionType"in e&&ie(e)}function Sl(e){return je(e)&&"expression"in e&&U(e.alias)&&ie(e)}var fn=m(()=>{ze();N()});var co,Gi=m(()=>{N();co=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 ke,Wo=m(()=>{N();ke=l({is(e){return e.kind==="AndNode"},create(e,o){return l({kind:"AndNode",left:e,right:o})}})});var He,lt=m(()=>{N();He=l({is(e){return e.kind==="OrNode"},create(e,o){return l({kind:"OrNode",left:e,right:o})}})});var hn,Hi=m(()=>{N();Wo();lt();hn=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"?ke.create(e.on,t):He.create(e.on,t)})}})});var $o,yr=m(()=>{N();Hi();$o=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:hn.create(t)})},cloneWithOn(e,o){return l({...e,on:e.on?hn.cloneWithOperation(e.on,"And",o):hn.create(o)})}})});var Bo,gn=m(()=>{N();Bo=l({is(e){return e.kind==="BinaryOperationNode"},create(e,o,t){return l({kind:"BinaryOperationNode",leftOperand:e,operator:o,rightOperand:t})}})});function Pl(e){return U(e)&&ql[e]}function Tl(e){return U(e)&&El[e]}function Ml(e){return U(e)&&kl[e]}var Ol,Q0,Al,G0,El,$b,ql,xb,Rl,H0,kl,Cb,X0,Xe,Tt=m(()=>{N();Ol=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}),Q0=Object.keys(Ol),Al=l({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),G0=Object.keys(Al),El=l({"->":!0,"->>":!0}),$b=Object.keys(El),ql=l({...Ol,...Al,"||":!0}),xb=Object.keys(ql),Rl=l({exists:!0,"not exists":!0}),H0=Object.keys(Rl),kl=l({...Rl,"-":!0,not:!0}),Cb=Object.keys(kl),X0=[...xb,...$b,...Cb,"between","between symmetric"],Xe=l({is(e){return e.kind==="OperatorNode"},create(e){return l({kind:"OperatorNode",operator:e})}})});var le,Ye=m(()=>{N();ne();le=l({is(e){return e.kind==="ColumnNode"},create(e){return l({kind:"ColumnNode",column:T.create(e)})}})});var bn,wn=m(()=>{N();bn=l({is(e){return e.kind==="SelectAllNode"},create(){return l({kind:"SelectAllNode"})}})});var Mt,vn=m(()=>{wn();N();Mt=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:bn.create()})}})});function yn(e){return je(e)&&ie(e)&&U(e.dynamicReference)}var _n=m(()=>{ze();N()});var Ke,Nn=m(()=>{N();Ke=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 ue,ut=m(()=>{N();ue=l({is(e){return e.kind==="RawNode"},create(e,o){return l({kind:"RawNode",sqlFragments:l(e),parameters:l(o)})},createWithSql(e){return ue.create([e],[])},createWithChild(e){return ue.create(["",""],[e])},createWithChildren(e){return ue.create(new Array(e.length+1).fill(""),e)}})});var Il,Xi=m(()=>{N();ne();Il=l({is(e){return e.kind==="CollateNode"},create(e){return l({kind:"CollateNode",collation:T.create(e)})}})});var $n,Yi=m(()=>{Xi();Nn();ut();N();$n=class e{#e;constructor(o){this.#e=l(o)}desc(){return new e({node:Ke.cloneWith(this.#e.node,{direction:ue.createWithSql("desc")})})}asc(){return new e({node:Ke.cloneWith(this.#e.node,{direction:ue.createWithSql("asc")})})}nullsLast(){return new e({node:Ke.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new e({node:Ke.cloneWith(this.#e.node,{nulls:"first"})})}collate(o){return new e({node:Ke.cloneWith(this.#e.node,{collation:Il.create(o)})})}toOperationNode(){return this.#e.node}}});function It(e){Ll.has(e)||(Ll.add(e),console.log(e))}var Ll,Ki=m(()=>{Ll=new Set});function jb(e){return e==="asc"||e==="desc"}function Ze(e){if(e.length===2)return[Zi(e[0],e[1])];if(e.length===1){let[o]=e;return Array.isArray(o)?(It("orderBy(array) is deprecated, use multiple orderBy calls instead."),o.map(t=>Zi(t))):[Zi(o)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function Zi(e,o){let t=Sb(e);if(Ke.is(t)){if(o)throw new Error("Cannot specify direction twice!");return t}return Dl(t,o)}function Sb(e){if(dt(e))return Vo(e);if(yn(e))return e.toOperationNode();let[o,t]=e.split(" ");return t?(It("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),Dl(Fe(o),t)):Fe(e)}function Dl(e,o){if(typeof o=="string"){if(!jb(o))throw new Error(`Invalid order by direction: ${o}`);return Ke.create(e,ue.createWithSql(o))}if(mn(o))return It("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),Ke.create(e,o.toOperationNode());let t=Ke.create(e);return o?o(new $n({node:t})).toOperationNode():t}var Lt=m(()=>{_n();fn();Nn();ut();Yi();Ki();pt();Pe()});var Dt,xn=m(()=>{N();Dt=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 Cn,jn=m(()=>{N();Cn=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 Uo,_r=m(()=>{N();Uo=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 Ob(e){return U(e)?Fe(e):e.toOperationNode()}function xo(e){return qe(e)?e.map(o=>me(o)):[me(e)]}function me(e){return dt(e)?Vo(e):Ob(e)}function zl(e,o){if(Tl(o))return Dt.create(Fe(e),Cn.create(Xe.create(o)));if(o==="->$"||o==="->>$")return Dt.create(Fe(e),Uo.create(Xe.create(o.slice(0,-1))));throw new Error(`Invalid JSON operator: ${o}`)}function Fe(e){if(!e.includes("."))return Mt.create(le.create(e));let t=e.split(".").map(Wl);if(t.length===3)return Ab(t);if(t.length===2)return Eb(t);throw new Error(`invalid column reference ${e}`)}function Fl(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(Wl);return Re.create(Fe(t),T.create(n))}else return Fe(e)}function Ab(e){let[o,t,n]=e;return Mt.create(le.create(n),Fo.createWithSchema(o,t))}function Eb(e){let[o,t]=e;return Mt.create(le.create(t),Fo.create(o))}function Wl(e){return e.trim()}var Pe=m(()=>{No();Ye();vn();vr();N();pt();ne();Tt();xn();jn();_r()});var Bl,ea=m(()=>{N();Bl=l({is(e){return e.kind==="PrimitiveValueListNode"},create(e){return l({kind:"PrimitiveValueListNode",values:l([...e])})}})});var Sn,On=m(()=>{N();Sn=l({is(e){return e.kind==="ValueListNode"},create(e){return l({kind:"ValueListNode",values:l(e)})}})});var Se,Jo=m(()=>{N();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 Vl(e){return qe(e)?qb(e):Y(e)}function Y(e){return dt(e)?Vo(e):Se.create(e)}function An(e){return so(e)||it(e)||at(e)}function Nr(e){if(!An(e))throw new Error(`unsafe immediate value ${JSON.stringify(e)}`);return Se.createImmediate(e)}function qb(e){return e.some(dt)?Sn.create(e.map(o=>Y(o))):Bl.create(e)}var Co=m(()=>{ea();On();Jo();N();pt()});var Qo,$r=m(()=>{N();Qo=l({is(e){return e.kind==="ParensNode"},create(e){return l({kind:"ParensNode",node:e})}})});function de(e){if(e.length===3)return En(e[0],e[1],e[2]);if(e.length===1)return Y(e[0]);throw new Error(`invalid arguments: ${JSON.stringify(e)}`)}function En(e,o,t){return Rb(o)&&Jl(t)?Bo.create(me(e),oa(o),Se.createImmediate(t)):Bo.create(me(e),oa(o),Vl(t))}function Ne(e,o,t){return Bo.create(me(e),oa(o),me(t))}function ta(e,o){return qn(Object.entries(e).filter(([,t])=>!_o(t)).map(([t,n])=>En(t,Jl(n)?"is":"=",n)),o)}function qn(e,o,t=!0){let n=o==="and"?ke.create:He.create;if(e.length===0)return Bo.create(Se.createImmediate(1),Xe.create("="),Se.createImmediate(o==="and"?1:0));let r=Ul(e[0]);for(let a=1;a<e.length;++a)r=n(r,Ul(e[a]));return e.length>1&&t?Qo.create(r):r}function Rb(e){return e==="is"||e==="is not"}function Jl(e){return at(e)||it(e)}function oa(e){if(Pl(e))return Xe.create(e);if(ie(e))return e.toOperationNode();throw new Error(`invalid operator ${JSON.stringify(e)}`)}function Ul(e){return ie(e)?e.toOperationNode():e}var lo=m(()=>{gn();N();ze();Tt();Pe();Co();Jo();Wo();$r();lt()});var jo,xr=m(()=>{N();jo=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 ra,na=m(()=>{N();ra=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 Cr,Rn=m(()=>{N();xr();na();Cr=l({is(e){return e.kind==="OverNode"},create(){return l({kind:"OverNode"})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?jo.cloneWithItems(e.orderBy,o):jo.create(o)})},cloneWithPartitionByItems(e,o){return l({...e,partitionBy:e.partitionBy?ra.cloneWithItems(e.partitionBy,o):ra.create(o)})}})});var mt,jr=m(()=>{N();mt=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 ia,aa=m(()=>{N();ia=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 sa,ca=m(()=>{N();Wo();lt();sa=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"?ke.create(e.having,t):He.create(e.having,t)})}})});var Ql,la=m(()=>{N();Ql=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 Gl,ua=m(()=>{N();Gl=l({is(e){return e.kind==="ListNode"},create(e){return l({kind:"ListNode",items:l(e)})}})});var zt,kn=m(()=>{N();jr();ua();zt=l({is(e){return e.kind==="UpdateQueryNode"},create(e,o){return l({kind:"UpdateQueryNode",table:e.length===1?e[0]:Gl.create(e),...o&&{with:o}})},createWithoutTable(){return l({kind:"UpdateQueryNode"})},cloneWithFromItems(e,o){return l({...e,from:e.from?mt.cloneWithFroms(e.from,o):mt.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 da,pa=m(()=>{N();da=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 Ft,Pn=m(()=>{N();jr();pa();So();Ft=l({is(e){return e.kind==="DeleteQueryNode"},create(e,o){return l({kind:"DeleteQueryNode",from:mt.create(e),...o&&{with:o}})},cloneWithOrderByItems:(e,o)=>q.cloneWithOrderByItems(e,o),cloneWithoutOrderBy:e=>q.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?da.cloneWithTables(e.using,o):da.create(o)})}})});var ve,Sr=m(()=>{N();Wo();lt();ve=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"?ke.create(e.where,t):He.create(e.where,t)})}})});var ma,fa=m(()=>{N();ma=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 Hl,ha=m(()=>{N();Hl=l({is(e){return e.kind==="ExplainNode"},create(e,o){return l({kind:"ExplainNode",format:e,options:o})}})});var Oo,Or=m(()=>{N();Oo=l({is(e){return e.kind==="WhenNode"},create(e){return l({kind:"WhenNode",condition:e})},cloneWithResult(e,o){return l({...e,result:o})}})});var Xl,ga=m(()=>{N();Or();Xl=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),Oo.cloneWithResult(e.whens[e.whens.length-1],o)]):void 0})}})});var ba,wa=m(()=>{N();ba=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 q,So=m(()=>{la();Ar();kn();Pn();Sr();N();fa();ha();ga();wa();xr();q=l({is(e){return K.is(e)||Ql.is(e)||zt.is(e)||Ft.is(e)||Xl.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?ve.cloneWithOperation(e.where,"And",o):ve.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?ma.cloneWithSelections(e.returning,o):ma.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:Hl.create(o,t?.toOperationNode())})},cloneWithTop(e,o){return l({...e,top:o})},cloneWithOutput(e,o){return l({...e,output:e.output?ba.cloneWithSelections(e.output,o):ba.create(o)})},cloneWithOrderByItems(e,o){return l({...e,orderBy:e.orderBy?jo.cloneWithItems(e.orderBy,o):jo.create(o)})},cloneWithoutOrderBy(e){return l({...e,orderBy:void 0})}})});var K,Ar=m(()=>{N();jr();aa();ca();So();K=l({is(e){return e.kind==="SelectQueryNode"},create(e){return l({kind:"SelectQueryNode",...e&&{with:e}})},createFrom(e,o){return l({kind:"SelectQueryNode",from:mt.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)=>q.cloneWithOrderByItems(e,o),cloneWithGroupByItems(e,o){return l({...e,groupBy:e.groupBy?ia.cloneWithItems(e.groupBy,o):ia.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?sa.cloneWithOperation(e.having,"And",o):sa.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=>q.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return l({...e,groupBy:void 0})}})});var Tn,va=m(()=>{yr();ut();lo();N();Tn=class e{#e;constructor(o){this.#e=l(o)}on(...o){return new e({...this.#e,joinNode:$o.cloneWithOn(this.#e.joinNode,de(o))})}onRef(o,t,n){return new e({...this.#e,joinNode:$o.cloneWithOn(this.#e.joinNode,Ne(o,t,n))})}onTrue(){return new e({...this.#e,joinNode:$o.cloneWithOn(this.#e.joinNode,ue.createWithSql("true"))})}$call(o){return o(this)}toOperationNode(){return this.#e.joinNode}}});var Yl,ya=m(()=>{N();Yl=l({is(e){return e.kind==="PartitionByItemNode"},create(e){return l({kind:"PartitionByItemNode",partitionBy:e})}})});function Kl(e){return xo(e).map(Yl.create)}var Zl=m(()=>{ya();Pe()});var Mn,eu=m(()=>{Rn();So();Lt();Zl();N();Mn=class e{#e;constructor(o){this.#e=l(o)}orderBy(...o){return new e({overNode:Cr.cloneWithOrderByItems(this.#e.overNode,Ze(o))})}clearOrderBy(){return new e({overNode:q.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(o){return new e({overNode:Cr.cloneWithPartitionByItems(this.#e.overNode,Kl(o))})}$call(o){return o(this)}toOperationNode(){return this.#e.overNode}}});var Wt,_a=m(()=>{N();vn();wn();Wt=l({is(e){return e.kind==="SelectionNode"},create(e){return l({kind:"SelectionNode",selection:e})},createSelectAll(){return l({kind:"SelectionNode",selection:bn.create()})},createSelectAllFromTable(e){return l({kind:"SelectionNode",selection:Mt.createSelectAll(e)})}})});function Ao(e){return _e(e)?Ao(e(Eo())):qe(e)?e.map(o=>ou(o)):[ou(e)]}function ou(e){return U(e)?Wt.create(Fl(e)):yn(e)?Wt.create(e.toOperationNode()):Wt.create(In(e))}function uo(e){return e?Array.isArray(e)?e.map(tu):[tu(e)]:[Wt.createSelectAll()]}function tu(e){if(U(e))return Wt.createSelectAllFromTable($e(e));throw new Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var Er=m(()=>{N();_a();Pe();_n();pt();po();Bt()});var iC,ru=m(()=>{N();iC=l({is(e){return e.kind==="ValuesNode"},create(e){return l({kind:"ValuesNode",values:l(e)})}})});var cC,nu=m(()=>{N();cC=l({is(e){return e.kind==="DefaultInsertValueNode"},create(){return l({kind:"DefaultInsertValueNode"})}})});var Na,$a=m(()=>{N();Na=l({is(e){return e.kind==="ColumnUpdateNode"},create(e,o){return l({kind:"ColumnUpdateNode",column:e,value:o})}})});function iu(...e){return e.length===2?[Na.create(me(e[0]),Y(e[1]))]:kb(e[0])}function kb(e){let o=_e(e)?e(Eo()):e;return Object.entries(o).filter(([t,n])=>n!==void 0).map(([t,n])=>Na.create(le.create(t),Y(n)))}var au=m(()=>{Ye();$a();Bt();N();Co();Pe()});var yC,su=m(()=>{N();yC=l({is(e){return e.kind==="OnDuplicateKeyNode"},create(e){return l({kind:"OnDuplicateKeyNode",updates:e})}})});var cu=m(()=>{});function Vt(e){return Object.prototype.hasOwnProperty.call(e,"prototype")}var Go,qr=m(()=>{Go=class extends Error{node;constructor(o){super("no result"),this.node=o}}});var jC,lu=m(()=>{N();Sr();jC=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?ve.cloneWithOperation(e.indexWhere,"And",o):ve.create(o)})},cloneWithIndexOrWhere(e,o){return l({...e,indexWhere:e.indexWhere?ve.cloneWithOperation(e.indexWhere,"Or",o):ve.create(o)})},cloneWithUpdateWhere(e,o){return l({...e,updateWhere:e.updateWhere?ve.cloneWithOperation(e.updateWhere,"And",o):ve.create(o)})},cloneWithUpdateOrWhere(e,o){return l({...e,updateWhere:e.updateWhere?ve.cloneWithOperation(e.updateWhere,"Or",o):ve.create(o)})},cloneWithoutIndexWhere(e){return l({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return l({...e,updateWhere:void 0})}})});var uu=m(()=>{});var du,xa=m(()=>{N();du=l({is(e){return e.kind==="TopNode"},create(e,o){return l({kind:"TopNode",expression:e,modifiers:o})}})});function Ut(e,o){if(!so(e)&&!st(e))throw new Error(`Invalid top expression: ${e}`);if(!_o(o)&&!Pb(o))throw new Error(`Invalid top modifiers: ${o}`);return du.create(e,o)}function Pb(e){return e==="percent"||e==="with ties"||e==="percent with ties"}var Ln=m(()=>{xa();N()});var TC,pu=m(()=>{N();TC=l({is(e){return e.kind==="OrActionNode"},create(e){return l({kind:"OrActionNode",action:e})}})});var mu=m(()=>{});var Dn,Ca=m(()=>{Dn=class{numDeletedRows;constructor(o){this.numDeletedRows=o}}});var Jt,Rr=m(()=>{N();Jt=l({is(e){return e.kind==="LimitNode"},create(e){return l({kind:"LimitNode",limit:e})}})});var ae,ja,fu=m(()=>{zn();po();Er();So();N();qr();Ca();Pn();Rr();Lt();lo();Co();Ln();ja=class{#e;constructor(o){this.#e=l(o)}where(...o){return new ae({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,de(o))})}whereRef(o,t,n){return new ae({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,Ne(o,t,n))})}clearWhere(){return new ae({...this.#e,queryNode:q.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new ae({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,Ut(o,t))})}using(o){return new ae({...this.#e,queryNode:Ft.cloneWithUsing(this.#e.queryNode,ft(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:q.cloneWithJoin(this.#e.queryNode,Qt(o,t))})}returning(o){return new ae({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,Ao(o))})}returningAll(o){return new ae({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,uo(o))})}output(o){return new ae({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,Ao(o))})}outputAll(o){return new ae({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,uo(o))})}clearReturning(){return new ae({...this.#e,queryNode:q.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new ae({...this.#e,queryNode:Ft.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...o){return new ae({...this.#e,queryNode:q.cloneWithOrderByItems(this.#e.queryNode,Ze(o))})}clearOrderBy(){return new ae({...this.#e,queryNode:q.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new ae({...this.#e,queryNode:Ft.cloneWithLimit(this.#e.queryNode,Jt.create(Y(o)))})}modifyEnd(o){return new ae({...this.#e,queryNode:q.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 Dn(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??Go;throw Vt(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:q.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};ae=ja});var Fn,Sa=m(()=>{Fn=class{numUpdatedRows;numChangedRows;constructor(o,t){this.numUpdatedRows=o,this.numChangedRows=t}}});var se,Oa,hu=m(()=>{zn();po();Er();So();kn();au();N();Sa();qr();lo();Co();Rr();Ln();Lt();Oa=class{#e;constructor(o){this.#e=l(o)}where(...o){return new se({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,de(o))})}whereRef(o,t,n){return new se({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,Ne(o,t,n))})}clearWhere(){return new se({...this.#e,queryNode:q.cloneWithoutWhere(this.#e.queryNode)})}top(o,t){return new se({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,Ut(o,t))})}from(o){return new se({...this.#e,queryNode:zt.cloneWithFromItems(this.#e.queryNode,ft(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:q.cloneWithJoin(this.#e.queryNode,Qt(o,t))})}orderBy(...o){return new se({...this.#e,queryNode:q.cloneWithOrderByItems(this.#e.queryNode,Ze(o))})}clearOrderBy(){return new se({...this.#e,queryNode:q.cloneWithoutOrderBy(this.#e.queryNode)})}limit(o){return new se({...this.#e,queryNode:zt.cloneWithLimit(this.#e.queryNode,Jt.create(Y(o)))})}set(...o){return new se({...this.#e,queryNode:zt.cloneWithUpdates(this.#e.queryNode,iu(...o))})}returning(o){return new se({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,Ao(o))})}returningAll(o){return new se({...this.#e,queryNode:q.cloneWithReturning(this.#e.queryNode,uo(o))})}output(o){return new se({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,Ao(o))})}outputAll(o){return new se({...this.#e,queryNode:q.cloneWithOutput(this.#e.queryNode,uo(o))})}modifyEnd(o){return new se({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,o.toOperationNode())})}clearReturning(){return new se({...this.#e,queryNode:q.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 Fn(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??Go;throw Vt(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:q.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};se=Oa});var yj,gu=m(()=>{N();Ye();vr();yj=l({is(e){return e.kind==="CommonTableExpressionNameNode"},create(e,o){return l({kind:"CommonTableExpressionNameNode",table:Fo.create(e),columns:o?l(o.map(le.create)):void 0})}})});var $j,bu=m(()=>{N();$j=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 jj,wu=m(()=>{N();jj=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 Wn(e){let o="";for(let t=0;t<e;++t)o+=Tb();return o}function Tb(){return vu[~~(Math.random()*vu.length)]}var vu,Aa=m(()=>{vu=["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 Te(){return new Ea}var Ea,Bn=m(()=>{Aa();Ea=class{#e;get queryId(){return this.#e===void 0&&(this.#e=Wn(8)),this.#e}}});var yu=m(()=>{});var _u=m(()=>{});var Pj,Nu=m(()=>{N();Pj=l({is(e){return e.kind==="MatchedNode"},create(e,o=!1){return l({kind:"MatchedNode",not:e,bySource:o})}})});var Oe,kr=m(()=>{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 Vn(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 $u=m(()=>{kr();N()});function Cu(e="ignore query",o,t){if(e!=="ignore query"){if(e==="cancel query"){let n=o.cancelQuery;return n||(t(),xu(e,o.killSession?"kill session":void 0)),n.bind(o)}if(e==="kill session"){let n=o.killSession;return n||(t(),xu(e,o.cancelQuery?"cancel query":void 0)),n.bind(o)}throw t(),new Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function xu(e,o){throw new Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${o?` or "${o}"`:""} instead.`)}function ht(e,o,t){e?.aborted&&(t?.(),gt(e.reason,o))}function gt(e,o){throw Mb(e,o),e}function bt(e){return o=>console.error(`\`${e}\` failed in the background after abortion: ${vl(o)}`)}function Mb(e,o){e!==null&&typeof e=="object"&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:o,writable:!1})}var mo,ju=m(()=>{N();mo={}});var Ib,Un,Su=m(()=>{N();$u();ju();kr();Ib=l([]),Un=class{#e;constructor(o=Ib){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 f=await this.provideConnection(async h=>await h.executeQuery(o),t);return await this.#o(f,o.queryId)}ht(r,"before query execution"),t=l({signal:r});let{connection:a,release:s}=await Vn(this,t),c=this.provideConnection.bind(this),{promise:d,resolve:u}=new Oe,p=()=>u(mo);r.addEventListener("abort",p,{once:!0});try{ht(r,"before query execution",s);let f=Cu(n,a,s);if(f&&a.collectSessionInfo){ht(r,"before query execution",s);let w=a.collectSessionInfo();await Promise.race([d,w]).catch(C=>{throw s(),C})===mo&&(w.catch(bt("collectSessionInfo")).finally(s),gt(r.reason,"before query execution"))}let h=a.executeQuery(o,t),b=await Promise.race([d,h]).catch(w=>{throw s(),w});b===mo?(Promise.allSettled([h.catch(bt("query")),f?.(c).catch(bt("inflightQueryAbortHandler"))]).finally(s),gt(r.reason,"during query execution")):s();let y=this.#o(b,o.queryId,t),v=await Promise.race([d,y]);return v===mo&&(y.catch(bt("plugins.transformResult")),gt(r.reason,"during result transformation")),v}finally{u(mo),r.removeEventListener("abort",p)}}async*stream(o,t,n){let{signal:r}=n||{};if(!r){let{connection:b,release:y}=await Vn(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}),ht(r,"before connection acquisition");let{connection:a,release:s}=await Vn(this,n),{promise:c,resolve:d}=new Oe,u=()=>d(mo);r.addEventListener("abort",u,{once:!0});let p,f;ht(r,"before query streaming",s);let{queryId:h}=o;try{for(p=a.streamQuery(o,t,n);;){ht(r,"during query streaming");let b=p.next(),y=await Promise.race([c,b]);if(y===mo&&(f=b.catch(bt("iterator.next")),gt(r.reason,"during query streaming")),y.done)break;let v=this.#o(y.value,h,n),w=await Promise.race([c,v]);w===mo&&(f=v.catch(bt("plugins.transformResult")),gt(r.reason,"during result transformation")),yield w}}finally{d(mo),r.removeEventListener("abort",u);let b=(p?.return?.()||Promise.resolve()).finally(()=>f).finally(s);f||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 qa,Jn,Qn=m(()=>{Su();qa=class e extends Un{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([])}},Jn=new qa});var Ou=m(()=>{});var Au=m(()=>{});var Eu=m(()=>{});function qu(e,o){return new Tn({joinNode:$o.create(e,wt(o))})}function Ru(){return new Mn({overNode:Cr.create()})}var Ra=m(()=>{yr();Rn();va();eu();po()});function Qt(e,o){if(o.length===3)return Db(e,o[0],o[1],o[2]);if(o.length===2)return Lb(e,o[0],o[1]);if(o.length===1)return zb(e,o[0]);throw new Error("not implemented")}function Lb(e,o,t){return t(qu(e,o)).toOperationNode()}function Db(e,o,t,n){return $o.createWithOn(e,wt(o),Ne(t,"=",n))}function zb(e,o){return $o.create(e,wt(o))}var zn=m(()=>{yr();lo();Ra();po()});var ku,ka=m(()=>{N();ku=l({is(e){return e.kind==="OffsetNode"},create(e){return l({kind:"OffsetNode",offset:e})}})});var Pu,Pa=m(()=>{N();Pu=l({is(e){return e.kind==="GroupByItemNode"},create(e){return l({kind:"GroupByItemNode",groupBy:e})}})});function Tu(e){return e=_e(e)?e(Eo()):e,xo(e).map(Pu.create)}var Mu=m(()=>{Pa();Bt();N();Pe()});var Iu,Ta=m(()=>{N();Iu=l({is(e){return e.kind==="SetOperationNode"},create(e,o,t){return l({kind:"SetOperationNode",operator:e,expression:o,all:t})}})});function vt(e,o,t){return _e(o)&&(o=o(Ma())),qe(o)||(o=[o]),o.map(n=>Iu.create(e,Vo(n),t))}var Lu=m(()=>{Bt();Ta();N();pt()});var B,Pr,Ia,La,Gt=m(()=>{No();Wo();ne();ze();lt();$r();lo();B=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Pr(this,o)}or(...o){return new Ia(He.create(this.#e,de(o)))}and(...o){return new La(ke.create(this.#e,de(o)))}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Pr=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Re.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():T.create(this.#o))}},Ia=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Pr(this,o)}or(...o){return new e(He.create(this.#e,de(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Qo.create(this.#e)}},La=class e{#e;constructor(o){this.#e=o}get expressionType(){}as(o){return new Pr(this,o)}and(...o){return new e(ke.create(this.#e,de(o)))}$castTo(){return new e(this.#e)}toOperationNode(){return Qo.create(this.#e)}}});var Du,Da=m(()=>{N();Jo();Du=l({is(e){return e.kind==="FetchNode"},create(e,o){return{kind:"FetchNode",rowCount:Se.create(e),modifier:o}}})});function zu(e,o){if(!so(e)&&!st(e))throw new Error(`Invalid fetch row count: ${e}`);if(!Fb(o))throw new Error(`Invalid fetch modifier: ${o}`);return Du.create(e,o)}function Fb(e){return e==="only"||e==="with ties"}var Fu=m(()=>{Da();N()});function Wu(e){return new Gn(e)}var I,Gn,za,Fa=m(()=>{No();Gi();zn();po();Er();Pe();Ar();So();Lt();Rr();ka();N();Mu();qr();ne();Lu();lo();Gt();Co();Fu();Ln();Gn=class{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...o){return new I({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,de(o))})}whereRef(o,t,n){return new I({...this.#e,queryNode:q.cloneWithWhere(this.#e.queryNode,Ne(o,t,n))})}having(...o){return new I({...this.#e,queryNode:K.cloneWithHaving(this.#e.queryNode,de(o))})}havingRef(o,t,n){return new I({...this.#e,queryNode:K.cloneWithHaving(this.#e.queryNode,Ne(o,t,n))})}select(o){return new I({...this.#e,queryNode:K.cloneWithSelections(this.#e.queryNode,Ao(o))})}distinctOn(o){return new I({...this.#e,queryNode:K.cloneWithDistinctOn(this.#e.queryNode,xo(o))})}modifyFront(o){return new I({...this.#e,queryNode:K.cloneWithFrontModifier(this.#e.queryNode,co.createWithExpression(o.toOperationNode()))})}modifyEnd(o){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.createWithExpression(o.toOperationNode()))})}distinct(){return new I({...this.#e,queryNode:K.cloneWithFrontModifier(this.#e.queryNode,co.create("Distinct"))})}forUpdate(o){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("ForUpdate",o?wr(o).map($e):void 0))})}forShare(o){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("ForShare",o?wr(o).map($e):void 0))})}forKeyShare(o){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("ForKeyShare",o?wr(o).map($e):void 0))})}forNoKeyUpdate(o){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("ForNoKeyUpdate",o?wr(o).map($e):void 0))})}skipLocked(){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("SkipLocked"))})}noWait(){return new I({...this.#e,queryNode:q.cloneWithEndModifier(this.#e.queryNode,co.create("NoWait"))})}selectAll(o){return new I({...this.#e,queryNode:K.cloneWithSelections(this.#e.queryNode,uo(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 I({...this.#e,queryNode:q.cloneWithJoin(this.#e.queryNode,Qt(o,t))})}orderBy(...o){return new I({...this.#e,queryNode:q.cloneWithOrderByItems(this.#e.queryNode,Ze(o))})}groupBy(o){return new I({...this.#e,queryNode:K.cloneWithGroupByItems(this.#e.queryNode,Tu(o))})}limit(o){return new I({...this.#e,queryNode:K.cloneWithLimit(this.#e.queryNode,Jt.create(Y(o)))})}offset(o){return new I({...this.#e,queryNode:K.cloneWithOffset(this.#e.queryNode,ku.create(Y(o)))})}fetch(o,t="only"){return new I({...this.#e,queryNode:K.cloneWithFetch(this.#e.queryNode,zu(o,t))})}top(o,t){return new I({...this.#e,queryNode:q.cloneWithTop(this.#e.queryNode,Ut(o,t))})}union(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("union",o,!1))})}unionAll(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("union",o,!0))})}intersect(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("intersect",o,!1))})}intersectAll(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("intersect",o,!0))})}except(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("except",o,!1))})}exceptAll(o){return new I({...this.#e,queryNode:K.cloneWithSetOperations(this.#e.queryNode,vt("except",o,!0))})}as(o){return new za(this,o)}clearSelect(){return new I({...this.#e,queryNode:K.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new I({...this.#e,queryNode:q.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new I({...this.#e,queryNode:K.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new I({...this.#e,queryNode:K.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new I({...this.#e,queryNode:q.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new I({...this.#e,queryNode:K.cloneWithoutGroupBy(this.#e.queryNode)})}$call(o){return o(this)}$if(o,t){return o?t(this):new I({...this.#e})}$castTo(){return new I(this.#e)}$narrowType(){return new I(this.#e)}$assertType(){return new I(this.#e)}$asTuple(){return new B(this.toOperationNode())}$asScalar(){return new B(this.toOperationNode())}withPlugin(o){return new I({...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??Go;throw Vt(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 I({...this.#e,queryNode:q.cloneWithExplain(this.#e.queryNode,o,t)}).execute()}};I=Gn;za=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 Re.create(this.#e.toOperationNode(),T.create(this.#o))}}});var fo,Hn=m(()=>{N();Sr();xr();fo=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]?jo.cloneWithItems(e[n],o):jo.create(o)})},cloneWithFilter(e,o){return l({...e,filter:e.filter?ve.cloneWithOperation(e.filter,"And",o):ve.create(o)})},cloneWithOrFilter(e,o){return l({...e,filter:e.filter?ve.cloneWithOperation(e.filter,"Or",o):ve.create(o)})},cloneWithOver(e,o){return l({...e,over:o})}})});var Wa,Ba=m(()=>{N();Wa=l({is(e){return e.kind==="FunctionNode"},create(e,o){return l({kind:"FunctionNode",func:e,arguments:o})}})});var Ht,Va,Ua=m(()=>{N();Hn();No();ne();Ra();lo();Lt();So();Ht=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}as(o){return new Va(this,o)}distinct(){return new e({...this.#e,aggregateFunctionNode:fo.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...o){return new e({...this.#e,aggregateFunctionNode:q.cloneWithOrderByItems(this.#e.aggregateFunctionNode,Ze(o))})}clearOrderBy(){return new e({...this.#e,aggregateFunctionNode:q.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...o){return new e({...this.#e,aggregateFunctionNode:fo.cloneWithOrderBy(this.#e.aggregateFunctionNode,Ze(o),!0)})}filterWhere(...o){return new e({...this.#e,aggregateFunctionNode:fo.cloneWithFilter(this.#e.aggregateFunctionNode,de(o))})}filterWhereRef(o,t,n){return new e({...this.#e,aggregateFunctionNode:fo.cloneWithFilter(this.#e.aggregateFunctionNode,Ne(o,t,n))})}over(o){let t=Ru();return new e({...this.#e,aggregateFunctionNode:fo.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}},Va=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Re.create(this.#e.toOperationNode(),T.create(this.#o))}}});function Bu(){let e=(t,n)=>new B(Wa.create(t,xo(n??[]))),o=(t,n)=>new Ht({aggregateFunctionNode:fo.create(t,n?xo(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 Ht({aggregateFunctionNode:fo.create("count",uo(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 Ht({aggregateFunctionNode:fo.create("json_agg",[U(t)?$e(t):t.toOperationNode()])})},toJson(t){return new B(Wa.create("to_json",[U(t)?$e(t):t.toOperationNode()]))}})}var Ja=m(()=>{Gt();Hn();Ba();Pe();Er();Ua();N();po()});var Vu,Qa=m(()=>{N();Vu=l({is(e){return e.kind==="UnaryOperationNode"},create(e,o){return l({kind:"UnaryOperationNode",operator:e,operand:o})}})});function Uu(e,o){if(Ml(e))return Vu.create(Xe.create(e),me(o));throw new Error(`invalid unary operator ${JSON.stringify(e)}`)}var Ju=m(()=>{Tt();Qa();Pe()});var Ae,Xn=m(()=>{N();Or();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),Oo.cloneWithResult(e.when[e.when.length-1],o)]):void 0})},cloneWith(e,o){return l({...e,...o})}})});var Yn,Xt,Kn,Zn,Ga=m(()=>{Gt();N();Pe();Xn();Or();lo();Co();Yn=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Xt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Oo.create(de(o)))})}whenRef(o,t,n){return new Xt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Oo.create(Ne(o,t,n)))})}},Xt=class{#e;constructor(o){this.#e=l(o)}then(o){return new Kn({...this.#e,node:Ae.cloneWithThen(this.#e.node,An(o)?Nr(o):Y(o))})}thenRef(o){return new Kn({...this.#e,node:Ae.cloneWithThen(this.#e.node,me(o))})}},Kn=class{#e;constructor(o){this.#e=l(o)}when(...o){return new Xt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Oo.create(de(o)))})}whenRef(o,t,n){return new Xt({...this.#e,node:Ae.cloneWithWhen(this.#e.node,Oo.create(Ne(o,t,n)))})}else(o){return new Zn({...this.#e,node:Ae.cloneWith(this.#e.node,{else:An(o)?Nr(o):Y(o)})})}elseRef(o){return new Zn({...this.#e,node:Ae.cloneWith(this.#e.node,{else:me(o)})})}end(){return new B(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new B(Ae.cloneWith(this.#e.node,{isStatement:!0}))}},Zn=class{#e;constructor(o){this.#e=l(o)}end(){return new B(Ae.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new B(Ae.cloneWith(this.#e.node,{isStatement:!0}))}}});var Ha,Xa=m(()=>{N();Ha=l({is(e){return e.kind==="JSONPathLegNode"},create(e,o){return l({kind:"JSONPathLegNode",type:e,value:o})}})});var Wb,Yt,ei,Ya,Ka=m(()=>{No();ne();jn();Xa();_r();xn();ze();Jo();Wb=/^#-\d+$/,Yt=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"&&!Wb.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 Dt.is(this.#e)?new ei(Dt.cloneWithTraversal(this.#e,Uo.is(this.#e.traversal)?Uo.cloneWithLeg(this.#e.traversal,Ha.create(o,t)):Cn.cloneWithValue(this.#e.traversal,Se.createImmediate(t)))):new ei(Uo.cloneWithLeg(this.#e,Ha.create(o,t)))}},ei=class e extends Yt{#e;constructor(o){super(o),this.#e=o}get expressionType(){}as(o){return new Ya(this,o)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Ya=class{#e;#o;constructor(o,t){this.#e=o,this.#o=t}get expression(){return this.#e}get alias(){return this.#o}toOperationNode(){return Re.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():T.create(this.#o))}}});var Za,es=m(()=>{N();Za=l({is(e){return e.kind==="TupleNode"},create(e){return l({kind:"TupleNode",values:l(e)})}})});function Gu(e){return Bb[e]||Vb.some(o=>o.test(e))}var Bb,Vb,Qu,os=m(()=>{N();Bb=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}),Vb=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+\)$/]),Qu=l({is(e){return e.kind==="DataTypeNode"},create(e){return l({kind:"DataTypeNode",dataType:e})}})});function Hu(e){if(ie(e))return e.toOperationNode();if(Gu(e))return Qu.create(e);throw new Error(`invalid column data type ${JSON.stringify(e)}`)}var Xu=m(()=>{os();ze()});var Yu,ts=m(()=>{N();Yu=l({is(e){return e.kind==="CastNode"},create(e,o){return l({kind:"CastNode",expression:e,dataType:o})}})});function Ma(e=Jn){function o(r,a,s){return new B(En(r,a,s))}function t(r,a){return new B(Uu(r,a))}let n=Object.assign(o,{fn:void 0,eb:void 0,selectFrom(r){return Wu({queryId:Te(),executor:e,queryNode:K.createFrom(ft(r))})},case(r){return new Yn({node:Ae.create(_o(r)?void 0:me(r))})},ref(r,a){return _o(a)?new B(Fe(r)):new Yt(zl(r,a))},jsonPath(){return new Yt(Uo.create())},table(r){return new B($e(r))},val(r){return new B(Y(r))},refTuple(...r){return new B(Za.create(r.map(me)))},tuple(...r){return new B(Za.create(r.map(Y)))},lit(r){return new B(Nr(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 B(Bo.create(me(r),Xe.create("between"),ke.create(Y(a),Y(s))))},betweenSymmetric(r,a,s){return new B(Bo.create(me(r),Xe.create("between symmetric"),ke.create(Y(a),Y(s))))},and(r){return qe(r)?new B(qn(r,"and")):new B(ta(r,"and"))},or(r){return qe(r)?new B(qn(r,"or")):new B(ta(r,"or"))},parens(...r){let a=de(r);return Qo.is(a)?new B(a):new B(Qo.create(a))},cast(r,a){return new B(Yu.create(me(r),Hu(a)))}});return n.fn=Bu(),n.eb=n,n}function Eo(e){return Ma()}var Bt=m(()=>{Fa();Ar();po();Bn();Ja();Pe();lo();$r();Gt();Tt();Ju();Co();Qn();Ga();Xn();N();Ka();gn();Wo();es();_r();Xu();ts()});function Vo(e){if(ie(e))return e.toOperationNode();if(_e(e))return e(Eo()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify(e)}`)}function In(e){if(ie(e))return e.toOperationNode();if(_e(e))return e(Eo()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function dt(e){return mn(e)||Sl(e)||_e(e)}var pt=m(()=>{fn();ze();Bt();N()});function Ku(e){return je(e)&&ie(e)&&U(e.table)&&U(e.alias)}var rs=m(()=>{ze();N()});function ft(e){return qe(e)?e.map(o=>wt(o)):[wt(e)]}function wt(e){return U(e)?Ub(e):Ku(e)?e.toOperationNode():In(e)}function Ub(e){let o=" as ";if(e.includes(o)){let[t,n]=e.split(o).map(Zu);return Re.create($e(t),T.create(n))}else return $e(e)}function $e(e){if(e.includes(".")){let[t,n]=e.split(".").map(Zu);return Fo.createWithSchema(t,n)}else return Fo.create(e)}function Zu(e){return e.trim()}var po=m(()=>{N();No();vr();pt();ne();rs()});var eE,ed=m(()=>{N();eE=l({is(e){return e.kind==="AddColumnNode"},create(e){return l({kind:"AddColumnNode",column:e})}})});var nE,od=m(()=>{N();Ye();nE=l({is(e){return e.kind==="ColumnDefinitionNode"},create(e,o){return l({kind:"ColumnDefinitionNode",column:le.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 cE,td=m(()=>{N();Ye();cE=l({is(e){return e.kind==="DropColumnNode"},create(e){return l({kind:"DropColumnNode",column:le.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var pE,rd=m(()=>{N();Ye();pE=l({is(e){return e.kind==="RenameColumnNode"},create(e,o){return l({kind:"RenameColumnNode",column:le.create(e),renameTo:le.create(o)})}})});var gE,nd=m(()=>{N();ne();gE=l({is(e){return e.kind==="CheckConstraintNode"},create(e,o){return l({kind:"CheckConstraintNode",expression:e,name:o?T.create(o):void 0})}})});var Jb,vE,id,ns=m(()=>{N();Jb=l({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),vE=Object.keys(Jb),id=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 NE,ad=m(()=>{N();NE=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 CE,sd=m(()=>{N();CE=l({is(e){return e.kind==="DefaultValueNode"},create(e){return l({kind:"DefaultValueNode",defaultValue:e})}})});var cd=m(()=>{});var AE,ld=m(()=>{N();AE=l({is(e){return e.kind==="ModifyColumnNode"},create(e){return l({kind:"ModifyColumnNode",column:e})}})});var PE,ud=m(()=>{N();ne();ns();PE=l({is(e){return e.kind==="ForeignKeyConstraintNode"},create(e,o,t,n){return l({kind:"ForeignKeyConstraintNode",columns:e,references:id.create(o,t),name:n?T.create(n):void 0})},cloneWith(e,o){return l({...e,...o})}})});var dd=m(()=>{});var LE,pd=m(()=>{N();LE=l({is(e){return e.kind==="AddConstraintNode"},create(e){return l({kind:"AddConstraintNode",constraint:e})}})});var VE,md=m(()=>{Ki();N();Ye();ne();VE=l({is(e){return e.kind==="UniqueConstraintNode"},create(e,o,t){return U(e.at(0))&&(It("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(le.create)),l({kind:"UniqueConstraintNode",columns:l(e),name:o?T.create(o):void 0,nullsNotDistinct:t})},cloneWith(e,o){return l({...e,...o})}})});var GE,fd=m(()=>{N();ne();GE=l({is(e){return e.kind==="DropConstraintNode"},create(e){return l({kind:"DropConstraintNode",constraintName:T.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var KE,hd=m(()=>{N();Ye();KE=l({is(e){return e.kind==="AlterColumnNode"},create(e,o,t){return l({kind:"AlterColumnNode",column:le.create(e),[o]:t})}})});var gd=m(()=>{});var nq,bd=m(()=>{N();Ye();ne();nq=l({is(e){return e.kind==="PrimaryKeyConstraintNode"},create(e,o){return l({kind:"PrimaryKeyConstraintNode",columns:l(e.map(le.create)),name:o?T.create(o):void 0})},cloneWith(e,o){return l({...e,...o})}})});var cq,wd=m(()=>{N();ne();cq=l({is(e){return e.kind==="AddIndexNode"},create(e){return l({kind:"AddIndexNode",name:T.create(e)})},cloneWith(e,o){return l({...e,...o})},cloneWithColumns(e,o){return l({...e,columns:[...e.columns||[],...o]})}})});var pq,vd=m(()=>{N();ne();pq=l({is(e){return e.kind==="RenameConstraintNode"},create(e,o){return l({kind:"RenameConstraintNode",oldName:T.create(e),newName:T.create(o)})}})});var yd=m(()=>{});var _d=m(()=>{});var Nd=m(()=>{});var $d=m(()=>{});var xd=m(()=>{});var Cd=m(()=>{});var jd=m(()=>{});var Sd=m(()=>{});var xq,Od=m(()=>{N();ct();xq=l({is(e){return e.kind==="CreateViewNode"},create(e){return l({kind:"CreateViewNode",name:Ge.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var Ad=m(()=>{});var Aq,Ed=m(()=>{N();ct();Aq=l({is(e){return e.kind==="DropViewNode"},create(e){return l({kind:"DropViewNode",name:Ge.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var qd=m(()=>{});var Tq,Rd=m(()=>{N();On();Jo();Tq=l({is(e){return e.kind==="CreateTypeNode"},create(e){return l({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,o){return l({...e,enum:Sn.create(o.map(Se.createImmediate))})}})});var kd=m(()=>{});var Dq,Pd=m(()=>{N();Dq=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 Td=m(()=>{});var Vq,Md=m(()=>{N();ct();Vq=l({is(e){return e.kind==="RefreshMaterializedViewNode"},create(e){return l({kind:"RefreshMaterializedViewNode",name:Ge.create(e)})},cloneWith(e,o){return l({...e,...o})}})});var Id=m(()=>{});var Gq,Ld=m(()=>{N();Gq=l({is(e){return e.kind==="AlterTypeNode"},create(e){return l({kind:"AlterTypeNode",name:e})},cloneWith(e,o){return l({...e,...o})}})});var Yq,Dd=m(()=>{N();Yq=l({is(e){return e.kind==="AddValueNode"},create(e){return l({kind:"AddValueNode",value:e})},cloneWith(e,o){return l({...e,...o})}})});var zd=m(()=>{});var oR,Fd=m(()=>{N();oR=l({is(e){return e.kind==="RenameValueNode"},create(e,o){return l({kind:"RenameValueNode",oldValue:e,newValue:o})}})});var Wd=m(()=>{});var Bd=m(()=>{});var Vd=m(()=>{});var Ud=m(()=>{});var Jd=m(()=>{});var Qd=m(()=>{});var Qb,uR,Gd=m(()=>{N();Qb=["query","error"],uR=l(Qb)});var Hd=m(()=>{});var Xd=m(()=>{Symbol.asyncDispose??=Symbol("Symbol.asyncDispose")});function qo(e){return new is(e)}var is,as,ss=m(()=>{No();N();Qn();ne();ze();is=class e{#e;constructor(o){this.#e=l(o)}get expressionType(){}get isRawBuilder(){return!0}as(o){return new as(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():Jn;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)}};as=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 Re.create(this.#e.toOperationNode(),ie(this.#o)?this.#o.toOperationNode():T.create(this.#o))}}});function Yd(e){return ie(e)?e.toOperationNode():Y(e)}var O,Kd=m(()=>{ne();ze();ut();Jo();Pe();po();Co();Bn();ss();O=Object.assign((e,...o)=>qo({queryId:Te(),rawNode:ue.create(e,o?.map(Yd)??[])}),{ref(e){return qo({queryId:Te(),rawNode:ue.createWithChild(Fe(e))})},val(e){return qo({queryId:Te(),rawNode:ue.createWithChild(Y(e))})},table(e){return qo({queryId:Te(),rawNode:ue.createWithChild($e(e))})},id(...e){let o=new Array(e.length+1).fill(".");return o[0]="",o[o.length-1]="",qo({queryId:Te(),rawNode:ue.create(o,e.map(T.create))})},lit(e){return qo({queryId:Te(),rawNode:ue.createWithChild(Se.createImmediate(e))})},raw(e){return qo({queryId:Te(),rawNode:ue.createWithSql(e)})},join(e,o=O`, `){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]=Yd(e[r]),r!==e.length-1&&(t[2*r+1]=n);return qo({queryId:Te(),rawNode:ue.createWithChildren(t)})}})});var Zd=m(()=>{});var RR,kR,PR,cs=m(()=>{N();RR=l({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),kR=l({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),PR=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 yt,Tr=m(()=>{ut();N();Bn();yt=l({raw(e,o=[]){return l({sql:e,query:ue.createWithSql(e),parameters:l(o),queryId:Te()})}})});var ep=m(()=>{});var op=m(()=>{});var tp=m(()=>{});var rp=m(()=>{});var np=m(()=>{});var ip=m(()=>{});var ap=m(()=>{});function Ho(e,o){if(Gb(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 Gb(e){return je(e)&&U(e.stack)}var Mr=m(()=>{N()});function Xb(e){return je(e)&&"insertId"in e&&"affectedRows"in e}var Hb,sp,cp=m(()=>{Tr();N();Mr();Hb=Symbol();sp=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(yt.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(!Xb(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 Ho(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}}[Hb](){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(yt.raw(o,[]))});let{clientFlags:a,maxPacketSize:s,...c}=n,d=this.#o(c);try{await new Promise((u,p)=>{d.connect(f=>{if(f)return p(f);if(r.queryId!==this.#t?.queryId)return u();d.query(o,[],h=>{if(h)return p(h);u()})})})}finally{d.destroy()}}}});var lp=m(()=>{});var up=m(()=>{});var dp=m(()=>{});var pp=m(()=>{});var Yb,mp,fp=m(()=>{Tr();Mr();Yb=Symbol(),mp=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 Ho(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}}[Yb](){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(yt.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 hp=m(()=>{});var gp=m(()=>{});var ck,lk,bp=m(()=>{ck=BigInt("3853314791062309107"),lk=3600*1e3});var wp=m(()=>{});var vp=m(()=>{});var Kb,Zb,ew,yp,Ir,_p=m(()=>{N();Tr();Mr();Aa();kr();Kb=Symbol(),Zb=Symbol(),ew=Symbol(),yp=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?Wn(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 Ir({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 Ho(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 Ir({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}[Zb](){return"closed"in this.#e&&this.#e.closed?Promise.resolve():new Promise(o=>{this.#e.once("end",o),this.#e.close()})}async[Kb](){await new Promise((o,t)=>{this.#e.reset(n=>{if(n)return t(n);o()})})}async[ew](){if(this.#o||this.#i())return!1;try{let o=new Oe,t=new Ir({compiledQuery:yt.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}},Ir=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 at(o)||_o(o)||U(o)?this.#n.TYPES.NVarChar:st(o)||so(o)&&o%1===0?o<-2147483648||o>2147483647?this.#n.TYPES.BigInt:this.#n.TYPES.Int:so(o)?this.#n.TYPES.Float:it(o)?this.#n.TYPES.Bit:Qi(o)?this.#n.TYPES.DateTime:wl(o)?this.#n.TYPES.VarBinary:this.#n.TYPES.NVarChar}}});var Np=m(()=>{});var $p=m(()=>{});var xp=m(()=>{});var Cp=m(()=>{});var ow,tw,rw,jp,Sp=m(()=>{kr();Mr();ow=Symbol(),tw=Symbol(),rw=Symbol(),jp=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 Ho(t,new Error)}}async*streamQuery(){throw new Error("Streaming is not supported by PGlite.")}async[ow](){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[tw](){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 Op=m(()=>{});var Ap=m(()=>{});var Ep=m(()=>{});var qp=m(()=>{});var Rp=m(()=>{});var kp=m(()=>{});var Pp=m(()=>{});var Tp=m(()=>{});var Mp=m(()=>{});var oi=m(()=>{Xd();Eu();zd();fn();Gt();Fa();mu();hu();fu();qr();va();Ja();cu();Ca();Sa();uu();Ua();Ga();Ka();Au();Ou();Yi();ss();Kd();Ud();Qn();cs();Tr();Wd();xd();kd();Sd();Td();Nd();Cd();$d();jd();cd();dd();_d();Ad();Id();qd();gd();yd();Bd();_n();rs();Qd();Vd();Jd();ep();op();ap();tp();rp();np();ip();pp();cp();lp();up();dp();fp();wp();gp();hp();bp();vp();xp();_p();Np();$p();Cp();Sp();Op();cs();Ap();Ep();_u();qp();Rp();kp();Pp();ed();pd();wd();Hn();No();hd();yl();Wo();gn();Xn();ts();nd();Xi();od();Ye();$a();gu();bu();Tp();_l();Nl();$l();Rd();Od();Md();os();nu();sd();Pn();td();fd();xl();Cl();jl();Pd();Ed();ha();Da();ud();jr();Ba();ad();Pa();aa();ca();ne();la();yr();jn();Xa();_r();xn();Rr();ua();Nu();ga();ld();ka();lu();su();Hi();ze();yu();Zd();Tt();pu();lt();Nn();xr();wa();Rn();$r();ya();na();bd();ea();So();ut();vn();ns();rd();vd();fa();ct();wn();Gi();Ar();_a();Ta();Mp();vr();xa();es();Qa();md();kn();pa();On();Jo();ru();Or();Sr();wu();Ld();Dd();Fd();Hd();Gd()});import{BlockList as Ip,isIP as nw}from"node:net";var Lp,Dp,zp,Fp=m(()=>{Lp=new Ip,Dp=new Ip;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]])Lp.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]])Dp.addSubnet(e,o,"ipv6");zp=e=>{let o=nw(e);return o===4?Lp.check(e,"ipv4"):o===6?Dp.check(e,"ipv6"):!0}});function Lr(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||!ls(c))throw i(`El elemento ${a+1} no tiene una clave v\xE1lida.`);if(!d||d.length>80||!ls(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"||!sw.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,cw(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 iw){let a=n.find(s=>s.value===r);if(!a)throw new L(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden quitar; se pueden renombrar.");if(a.archivado)throw new L(400,"etapa_fija","Las etapas \xABGanada\xBB y \xABPerdida\xBB no se pueden archivar; se pueden renombrar.")}if(e==="contactTypes"){for(let s of Wp){let c=n.find(d=>d.value===s);if(!c)throw new L(400,"tipo_fijo","Los tipos \xABCliente\xBB y \xABProveedor\xBB no se pueden quitar; se pueden renombrar.");if(c.archivado)throw new L(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&&Wp.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 cw(e,o){let t=typeof e.plural=="string"&&e.plural.trim()?e.plural.trim():o;if(t.length>80||!ls(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"||!aw.test(e.icono))throw i(`El icono de \xAB${o}\xBB no es v\xE1lido.`);n.icono=e.icono}return n}var iw,Wp,aw,ls,sw,ds=m(()=>{E();iw=["won","lost"],Wp=["cliente","proveedor"],aw=/^[a-z0-9-]{1,40}$/,ls=e=>!/[\u0000-\u001f\u007f]/.test(e),sw=/^#[0-9a-fA-F]{3,8}$|^[a-z]{3,20}$/});function Bp(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 ps(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 ps,Vp=m(()=>{E();ps=e=>e.completarDesde?[e.completarDesde,...e.completarDesde.alternativa?[e.completarDesde.alternativa]:[]]:[]});function Up(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&&!lw(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.");Lr("legalForms",[{value:s,label:ms(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(ms(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 Jp(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:ms(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 Lr("legalForms",[...r.values()])}function Qp(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 lw,ms,Gp=m(()=>{E();ds();Dr();lw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);ms=(e,o)=>e.opciones?.find(t=>t.valor===o)?.etiqueta??e.etiqueta});var j,Hp,Xp=m(()=>{j=(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}),Hp=[{clave:"companies",icono:"building-2",campoTitulo:"name",campos:[j("name","texto",{enTabla:!0,ancho:240}),j("website","url",{enTabla:!0,ancho:200}),j("sector","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:companySectors"}),j("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"companies",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),j("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}),j("city","texto",{enTabla:!0,ancho:140}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("nb_contacts","contador",{enTabla:!0,ancho:110}),j("nb_deals","contador",{enTabla:!0,ancho:130}),j("created_at","fecha_hora",{enTabla:!0,ancho:140}),j("proveedor","booleano",{filtrable:!0,ancho:110}),j("has_newsletter","booleano",{etiqueta:"Comunicaciones",filtrable:!0,migracion:"0490_comunicaciones_empresa.sql"}),j("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),j("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),j("phone_number","telefono",{ancho:150}),j("country","texto",{ancho:130}),j("address","texto"),j("state_abbr","texto",{soloFicha:!0,etiqueta:"Provincia"}),j("zipcode","texto",{ancho:110}),j("linkedin_url","url"),j("revenue","texto",{ancho:130}),j("tax_identifier","texto",{ancho:140}),j("razon_social","texto",{ancho:220,migracion:"0440_datos_fiscales.sql"}),j("forma_juridica","seleccion",{filtrable:!0,opciones:"config:legalForms",ancho:160,migracion:"0440_datos_fiscales.sql"}),j("correo_facturacion","correo",{ancho:220,migracion:"0440_datos_fiscales.sql"}),j("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"}),j("description","texto_largo",{ancho:260})]},{clave:"contacts",icono:"users",campoTitulo:"first_name",camposTitulo:["first_name","last_name"],campos:[j("ubicacion","ubicacion",{etiqueta:"Ubicaci\xF3n",editable:!1,ordenable:!1,migracion:"0452_ubicacion_nativa.sql"}),j("first_name","texto",{enTabla:!0,ancho:220}),j("last_name","texto",{ancho:150}),j("title","texto",{enTabla:!0,ancho:150}),j("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),j("email_jsonb","correos",{enTabla:!0,ordenable:!1,editable:!0,ancho:220}),j("phone_jsonb","telefonos",{enTabla:!0,ordenable:!1,editable:!0,ancho:150}),j("status","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:noteStatuses",ancho:130}),j("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"contacts",ancho:160}),j("tipos","seleccion_multiple",{enTabla:!0,ordenable:!1,editable:!1,opciones:"config:contactTypes",ancho:170,migracion:"0439_tipos_contactos.sql"}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("last_seen","fecha_hora",{enTabla:!0,ancho:140}),j("nb_tasks","contador",{ancho:110}),j("first_seen","fecha_hora",{ancho:140}),j("linkedin_url","url"),j("background","texto_largo",{ancho:260}),j("nif","texto",{soloFicha:!0,sensible:!0,etiqueta:"Identificador fiscal",migracion:"0005_datos_es.sql"}),j("iban","texto",{soloFicha:!0,sensible:!0,etiqueta:"IBAN",migracion:"0005_datos_es.sql"}),j("birthday","fecha",{soloFicha:!0,etiqueta:"Fecha de nacimiento",migracion:"0005_datos_es.sql"}),j("address","texto",{soloFicha:!0,etiqueta:"Direcci\xF3n",migracion:"0005_datos_es.sql"}),j("zipcode","texto",{soloFicha:!0,etiqueta:"C\xF3digo postal",migracion:"0005_datos_es.sql"}),j("city","texto",{soloFicha:!0,etiqueta:"Ciudad",migracion:"0005_datos_es.sql"}),j("province","texto",{soloFicha:!0,etiqueta:"Provincia",migracion:"0005_datos_es.sql"}),j("country","texto",{soloFicha:!0,etiqueta:"Pa\xEDs",migracion:"0005_datos_es.sql"}),j("has_newsletter","booleano",{soloFicha:!0,migracion:"0005_datos_es.sql"}),j("pais_fiscal","texto",{filtrable:!0,editable:!1,ancho:90,migracion:"0440_datos_fiscales.sql"})]},{clave:"deals",icono:"handshake",campoTitulo:"name",campos:[j("name","texto",{enTabla:!0,ancho:240}),j("company_id","relacion",{enTabla:!0,relacion:"companies",ancho:180}),j("stage","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealStages",ancho:160}),j("amount","importe",{enTabla:!0,ancho:120}),j("expected_closing_date","fecha",{enTabla:!0,ancho:140}),j("category","seleccion",{enTabla:!0,filtrable:!0,opciones:"config:dealCategories",ancho:150}),j("tags","etiquetas",{enTabla:!0,ordenable:!1,editable:!0,filtrable:!0,relacion:"tags",objetoEtiquetas:"deals",ancho:160,migracion:"0466_etiquetas_por_objeto.sql"}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("origen_lead","texto",{etiqueta:"Origen",filtrable:!0,editable:!1,ancho:170,migracion:"0467_oportunidades_origen_actividad.sql"}),j("ultima_actividad","fecha_hora",{etiqueta:"\xDAltima actividad",editable:!1,ancho:150,migracion:"0467_oportunidades_origen_actividad.sql"}),j("created_at","fecha_hora",{ancho:140}),j("updated_at","fecha_hora",{ancho:140}),j("description","texto_largo",{ancho:260})]},{clave:"proyectos",icono:"folder-kanban",campoTitulo:"nombre",campos:[j("nombre","texto",{enTabla:!0,ancho:220}),j("clave","texto",{enTabla:!0,ancho:110,editable:!1}),j("estado","seleccion",{enTabla:!0,filtrable:!0,opciones:[{valor:"activo",etiqueta:"Activo"},{valor:"en_pausa",etiqueta:"En pausa"},{valor:"archivado",etiqueta:"Archivado"}],ancho:120}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("fecha_inicio","fecha",{enTabla:!0,ancho:130}),j("fecha_fin","fecha",{enTabla:!0,ancho:130}),j("requiere_aceptacion","booleano",{ancho:120}),j("color","texto",{ancho:100}),j("icono","texto",{ancho:100}),j("descripcion","texto_largo",{ancho:260}),j("creado","fecha_hora",{ancho:140}),j("actualizado","fecha_hora",{ancho:140})]},{clave:"tareas",icono:"check-square",campoTitulo:"titulo",campos:[j("titulo","texto",{enTabla:!0,ancho:240}),j("codigo_corto","texto",{enTabla:!0,ancho:110,editable:!1}),j("proyecto_id","relacion",{enTabla:!0,filtrable:!0,relacion:"proyectos",ancho:170,editable:!1}),j("columna_id","texto",{enTabla:!0,filtrable:!0,ancho:130}),j("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}),j("sales_id","relacion",{enTabla:!0,filtrable:!0,relacion:"sales",ancho:170}),j("fecha_entrega","fecha",{enTabla:!0,ancho:130}),j("fecha_inicio","fecha",{ancho:130}),j("estimacion_minutos","numero",{ancho:110}),j("hecho","fecha_hora",{enTabla:!0,editable:!0,marca:!0,ancho:120}),j("contact_id","relacion",{filtrable:!0,relacion:"contacts",ancho:160}),j("descripcion","texto_largo",{ancho:260}),j("creado","fecha_hora",{ancho:140}),j("actualizado","fecha_hora",{ancho:140})]}]});function fs(e){return/^funciones\.([a-z0-9][a-z0-9-]{0,59})\.[a-z][a-z0-9_]{0,40}$/.exec(e)?.[1]}function dw(e,o){return e==="contacts"&&/^(correo|telefono)(_(trabajo|personal))?$/.test(o)?o.startsWith("correo")?"email_jsonb":"phone_jsonb":uw[e].includes(o)||/^datos\.[a-z][a-z0-9_]{0,40}$/.test(o)||fs(o)?o:null}function Yp(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=dw(r,c);if(!u||fs(u)&&fs(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 uw,Kp=m(()=>{E();uw={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 Zp(e){if(e==null)return;let o=ti(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:Me(o.anterior),ciclo:Me(o.ciclo),copiar:Object.fromEntries(Object.entries(o.copiar).map(([n,r])=>[Me(n),Me(r)])),fechas:o.fechas.map(n=>{let r=ti(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:Me(r.campo),desde:Me(r.desde),meses:r.meses}})};if(o.destino!==void 0&&(t.destino=Me(o.destino)),o.estado){let n=ti(o.estado,["campo","valor"]);if(typeof n.valor!="string"||n.valor.length>100)throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");t.estado={campo:Me(n.campo),valor:n.valor}}if(o.precios){let n=ti(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:Me(n.tabla),fecha:Me(n.fecha),claves:n.claves.map(Me),valor:Me(n.valor),destino:Me(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 Me,ti,em=m(()=>{E();Me=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,40}$/.test(e))throw i("Sucesi\xF3n: configuraci\xF3n inv\xE1lida.");return e},ti=(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 zr,CI,pw,om=m(()=>{zr=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 pw(this.centimos())}},CI=new zr(0n),pw=e=>`${e<0n?"-":""}${(e<0n?-e:e)/100n}.${String((e<0n?-e:e)%100n).padStart(2,"0")}`});function rm(e,o){if(e==null)return;let t=be(e,["version","beneficiariosPeriodo","origen","fecha","importe","moneda","unidad","grupo","mantenimiento","ciclo","recuperacion","beneficiarios","motor","documento","cuentan","precios","unidad_recuento","componentes"]),n=be(t.motor,["reglas","combinar","margenNegativo","equipoPropio","principal","minimo","objetivo","fijoPeriodo"]),r=be(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 _=te(v);if(!o.some(C=>C.clave===_&&!C.archivado&&C.tipo===w))throw i("Liquidaci\xF3n v2: campo de documento inv\xE1lido.");return _},s=Object.fromEntries(Object.entries(be(t.beneficiarios)).map(([v,w])=>{let _=be(w,["tipo","campo"]);return[te(v),{tipo:Nt(_.tipo,["miembro","contacts","companies","registro"]),campo:_.campo==="_dueno"?"_dueno":te(_.campo)}]}));if(!Object.keys(s).length||Object.keys(s).length>20)throw i("Liquidaci\xF3n v2: beneficiarios inv\xE1lidos.");let c=v=>{let w=be(v,["clave","beneficiario","fijo","porcentaje","resto","equipo","minimo"]),_=te(w.beneficiario);if(!s[_])throw i("Liquidaci\xF3n v2: beneficiario desconocido.");return{clave:te(w.clave),beneficiario:_,...w.fijo!==void 0?{fijo:_t(w.fijo)}:{},...w.porcentaje!==void 0?{porcentaje:hs(w.porcentaje)}:{},...w.resto===!0?{resto:!0}:{},...w.equipo===!0?{equipo:!0}:{},...typeof w.minimo=="boolean"?{minimo:w.minimo}:{}}},d=Xo(n.reglas).map(v=>{let w=be(v,["clave","prioridad","modo","desde","hasta","moneda","unidad","si","bolsa","retencion","receptores"]);if(!tm(w.desde)||w.hasta!==void 0&&(!tm(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 _=w.si===void 0?void 0:be(w.si,["campo","valores"]);return{clave:te(w.clave),prioridad:ri(w.prioridad),modo:Nt(w.modo,["exclusiva","acumulable"]),desde:w.desde,...w.hasta?{hasta:w.hasta}:{},moneda:w.moneda,unidad:w.unidad,receptores:Xo(w.receptores).map(c),...w.bolsa!==void 0?{bolsa:_t(w.bolsa)}:{},...w.retencion!==void 0?{retencion:_t(w.retencion)}:{},..._?{si:{campo:te(_.campo),valores:Xo(_.valores).map(C=>String(C).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=be(n.objetivo,["beneficiario","medida","modo","tramos","consumirBolsa"]),w=Xo(v.tramos).map(_=>{let C=be(_,["desde","tasa","garantia","bonus"]);return{desde:ri(C.desde),tasa:v.medida==="recuento"?_t(C.tasa):hs(C.tasa),...C.garantia!==void 0?{garantia:_t(C.garantia)}:{},...C.bonus!==void 0?{bonus:_t(C.bonus)}:{}}});if(!w.length||w[0].desde!==0||w.some((_,C)=>C>0&&_.desde<=w[C-1].desde))throw i("Liquidaci\xF3n v2: umbrales inv\xE1lidos.");u={beneficiario:te(v.beneficiario),medida:Nt(v.medida,["recuento","importe"]),modo:Nt(v.modo,["alcanzado","marginal"]),tramos:w,consumirBolsa:v.consumirBolsa===!0}}let p=n.minimo?be(n.minimo,["cantidad","modo"]):void 0,f=n.fijoPeriodo?Xo(n.fijoPeriodo).map(v=>{let w=be(v,["beneficiario","importe"]);return{beneficiario:te(w.beneficiario),importe:_t(w.importe)}}):void 0;if(f&&new Set(f.map(v=>v.beneficiario)).size!==f.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:ri(p.cantidad),modo:Nt(p.modo,["umbral","franquicia"])}}:{},...u?{objetivo:u}:{},...f?{fijoPeriodo:f}:{}},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=Xo(t.beneficiariosPeriodo,1e4).map(v=>{let w=be(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 _=Object.fromEntries(Object.entries(be(w.beneficiarios)).map(([C,S])=>{if(!s[C]||typeof S!="number"||!Number.isSafeInteger(S)||S<1)throw i("Liquidaci\xF3n v2: beneficiario de periodo inv\xE1lido.");return[C,S]}));return{grupo:w.grupo,beneficiarios:_}}),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=be(t.cuentan,["campo","valores"]);h.cuentan={campo:te(v.campo),valores:Xo(v.valores).map(String)}}if(t.unidad_recuento&&(h.unidad_recuento=te(t.unidad_recuento)),t.componentes){let v=be(t.componentes,["modo","campo"]);h.componentes={modo:Nt(v.modo,["todos","principal"]),campo:te(v.campo)}}if(t.precios){let v=be(t.precios,["tabla","fecha","claves","valor"]);if(h.precios={tabla:te(v.tabla),fecha:te(v.fecha),claves:Xo(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=be(t.recuperacion,["modo","plazo"]);if(h.recuperacion={modo:Nt(v.modo,["total","proporcional_dias"]),plazo:ri(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 be,tm,te,hs,_t,Xo,Nt,ri,nm=m(()=>{E();om();be=(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},tm=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},hs=e=>{if(typeof e!="string")throw i("Liquidaci\xF3n v2: decimal como cadena.");try{if(zr.leer(e).n<0n)throw new Error("negativo")}catch{throw i("Liquidaci\xF3n v2: decimal inv\xE1lido.")}return e},_t=e=>{let o=hs(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},Xo=(e,o=20)=>{if(!Array.isArray(e)||e.length>o)throw i("Liquidaci\xF3n v2: lista inv\xE1lida.");return e},Nt=(e,o)=>{if(!o.includes(e))throw i("Liquidaci\xF3n v2: opci\xF3n inv\xE1lida.");return e},ri=e=>{if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw i("Liquidaci\xF3n v2: entero inv\xE1lido.");return e}});function im(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 am=m(()=>{E()});var sm,mw,RI,cm,lm=m(()=>{sm=new Set(["texto","texto_largo","numero","importe","porcentaje","fecha","fecha_hora","hora","duracion","booleano","seleccion","seleccion_multiple","url","correo","telefono","color","codigo","valoracion","autonumero"]),mw=new Set([...sm,"relacion"]),RI=new Set([...sm,"relacion"]),cm=new Set([...mw,"busqueda"])});function ii(e,o){if(e==null)return;if(!Fr(e))throw i("\xABrecurso\xBB: un objeto.");ni(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 ai(e,o){if(e==null)return;if(!Fr(e))throw i("\xABreserva\xBB: un objeto.");ni(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=f=>o.find(h=>h.clave===f&&!h.archivado),n=(f,h,b)=>{let y=t(f);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:um(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 f=n(e.dia,["seleccion"],"dia");if(!(f.opciones??[]).length||(f.opciones??[]).some(h=>fw(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=f.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(f=>f!=null&&f!=="").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 f=Number(e.duracion_fija);if(!Number.isInteger(f)||f<1||f>1440)throw i("\xABreserva.duracion_fija\xBB: de 1 a 1440 minutos.");c.duracion_fija=f}let u=f=>t(f)?.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 f=Number(e.margen);if(!Number.isInteger(f)||f<0||f>240)throw i("\xABreserva.margen\xBB: de 0 a 240 minutos.");f&&(c.margen=f)}function p(f,h){let b=Fr(f)?f:{},y=n(b.campo,["seleccion"],`${h}.campo`),v=Array.isArray(b.valores)?b.valores:[];if(!y||!v.length||v.some(w=>!y.opciones?.some(_=>_.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(!Fr(e.acceso))throw i("\xABreserva.acceso\xBB: un objeto.");ni(e.acceso,["antes","despues","bloqueado","puerta_extra_obligatoria"],"reserva.acceso");let f=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:f(e.acceso.antes),despues:f(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(!Fr(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(ni(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 fw(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 Fr,ni,gs=m(()=>{E();dm();Fr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ni=(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 gw(e){let o=[],t=0;for(;t<e.length;){let n=e[t];if(/\s/.test(n)){t++;continue}if(o.length>=pm)throw i(`F\xF3rmula demasiado larga: como mucho ${pm} 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=hw.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 ww(e){let o=gw(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>mm)throw i(`F\xF3rmula: como mucho ${mm} niveles de anidaci\xF3n.`);try{return w()}finally{n--}},d=(w,_,C=!1)=>()=>{let S=_();for(;r().t==="op"&&w.includes(r().v)&&(S={k:"bin",op:o[t++].v,a:S,b:_()},!C););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 _=y();return s(")"),_}if(w.t==="id"){t++;let _=bw(w.v);if(!a("(")){if(_==="VERDADERO"||_==="TRUE")return{k:"bool",v:!0};if(_==="FALSO"||_==="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 C=[];if(!a(")"))for(;;){if(C.push(y()),C.length>hm)throw i(`F\xF3rmula: como mucho ${hm} argumentos.`);if(a(",")){t++;continue}break}return s(")"),{k:"fn",f:_,args:C}}throw i(w.t==="fin"?"F\xF3rmula incompleta.":"F\xF3rmula: algo sobra o falta.")}),p=d(["*","/"],u),f=d(["+","-"],p),h=d(["&"],f),b=d(["=","<>","<","<=",">",">="],h,!0),y=()=>c(b),v=y();if(r().t!=="fin")throw i("F\xF3rmula: algo sobra al final.");return v}function bs(e){if(!eo(e,0))throw i("F\xF3rmula: A\xD1O, MES y DIA necesitan una fecha.");return"numero"}function bm(e){let o=e[0];for(let t of e.slice(1))o=Zt(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 Zt(e,o){if(e===o)return e;if(eo([e,o],0)&&eo([e,o],1))return"fecha_hora";throw i(`F\xF3rmula: no se mezclan ${xt[e]} y ${xt[o]}.`)}function si(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 ws(e,o){let t=$s(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 vs(e,o,t){if(!o.includes("."))return null;let n=o.trim().toLowerCase();if($s(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 _w(e){let o=e.saltos.at(-1).modulo;if(ym[o]){let t=Ee(e.campo)?e.campos.find(r=>r.clave===e.campo&&!r.archivado):void 0,n=t?Ns[t.tipo]:wm[Br(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 vm({campos:e.campos},yw(e),[])}function vm(e,o,t){if(o.tipo==="formula")return _m(e,o,t).tipo;let n=o.tipo==="busqueda"||o.tipo==="resumen"?o.origen?.tipo??"":o.tipo,r=Ns[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"&&Nw(e,o),r}function Nw(e,o){let t=$s(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??"")||$w.has(o.origen?.tipo??""))throw i(`F\xF3rmula: la b\xFAsqueda \xAB${o.etiqueta}\xBB no es v\xE1lida.`)}else{let n=Br(t.relacion).find(r=>r.clave===o.campo)??(Ee(o.campo)&&o.origen?{tipo:o.origen.tipo}:void 0);if(!n||!(Ee(o.campo)?Ns[n.tipo]:wm[n.tipo])||!ym[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 _m(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 xw(e,o.formula??"",[...t,o.clave],o.origen?.rutas)}function xw(e,o,t,n){if(typeof o!="string"||!o.trim())throw i("F\xF3rmula vac\xEDa.");if(o.length>oo)throw i(`F\xF3rmula de como mucho ${oo} caracteres.`);let r=ww(o),a=new Map,s=u=>{let p=d(u);return a.set(u,p),p},c=(u,p,f)=>{let h=s(u);if(h!==p){if(u.k==="campo"){let y=vs(e,u.v,n)?u.v:ws(e,u.v).etiqueta;throw i(`F\xF3rmula: \xAB${y}\xBB no es ${xt[p]}, es ${xt[h]} (${f} necesita ${xt[p]}).`)}throw i(`F\xF3rmula: ${f} necesita ${xt[p]} y hay ${xt[h]}.`)}},d=u=>{switch(u.k){case"num":return"numero";case"txt":return"texto";case"bool":return"booleano";case"campo":{let p=vs(e,u.v,n);return p?_w(p):vm(e,ws(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"):(Zt(s(u.a),s(u.b)),"booleano");case"fn":{let p=vw[u.f]??u.f,f=_s[p];if(!f)throw i(`F\xF3rmula: la funci\xF3n \xAB${u.f}\xBB no existe.`);if(p==="REDONDEAR"&&si(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=f.args.length-(f.opcionales??0);if(u.args.length<Math.max(h,f.resto?1:0)||!f.resto&&u.args.length>f.args.length)throw i(`F\xF3rmula: ${p} no lleva ${u.args.length} argumentos.`);let b=u.args.map((y,v)=>{let w=f.args[v]??f.resto;return w==="cualquiera"?s(y):(c(y,w,p),w)});return f.tipo(b)}}};return{tipo:s(r),arbol:r,tipos:a,...n?{rutas:n}:{}}}function ci(e){let o={campos:e};return e.map(t=>{if(t.tipo!=="formula"||t.archivado)return t;let n=_m(o,t,[]),r=t.origen?.rutas&&Object.keys(t.origen.rutas).length?t.origen.rutas:void 0;return{...t,formula:Cw(o,t.formula,r),origen:{tipo:n.tipo,...r?{rutas:r}:{}}}})}function Cw(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+=`{${vs(e,c,t)?c:ws(e,c).clave}}`,r=s+1;continue}n+=a,r++}return n}var oo,pm,mm,fm,hm,ys,hw,bw,eo,$t,gm,Kt,_s,vw,FI,xt,Ns,wm,WI,$s,yw,$w,ym,li=m(()=>{Dr();oi();E();ui();oo=1e3,pm=300,mm=20,fm=5,hm=20,ys="Europe/Madrid",hw=["<>","!=","<=",">=","=","<",">","+","-","*","/","&","(",")",",",";"];bw=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toUpperCase();eo=(e,o)=>e[o]==="fecha"||e[o]==="fecha_hora",$t=(e,o)=>o==="fecha_hora"?O`(${e} at time zone ${ys})::date`:e,gm=e=>O`(${e})::text`,Kt=(e,o)=>O`(least(greatest(${e}, ${-o}::numeric), ${o}::numeric))::int`,_s={PRECIO_VIGENTE:{args:["texto","fecha","texto","cualquiera"],resto:"cualquiera",tipo:()=>"numero",sql:e=>O`((crm_precio_formula(${e[0]}, ${e[1]}::date, jsonb_build_array(${O.join(e.slice(3).map(o=>O`(${o})::text`),O`, `)}))->'valores'->>${e[2]})::numeric)`},SI:{args:["booleano","cualquiera","cualquiera"],opcionales:1,tipo:e=>Zt(e[1],e[2]??e[1]),sql:e=>e[2]?O`(case when ${e[0]} then ${e[1]} else ${e[2]} end)`:O`(case when ${e[0]} then ${e[1]} end)`},Y:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>O`(${O.join(e,O` and `)})`},O:{args:[],resto:"booleano",tipo:()=>"booleano",sql:e=>O`(${O.join(e,O` or `)})`},NO:{args:["booleano"],tipo:()=>"booleano",sql:e=>O`(not ${e[0]})`},VACIO:{args:["cualquiera"],tipo:()=>"booleano",sql:(e,o)=>o[0]==="texto"?O`(${e[0]} is null or ${e[0]} = '')`:O`(${e[0]} is null)`},REDONDEAR:{args:["numero","numero"],opcionales:1,tipo:()=>"numero",sql:(e,o,t)=>O`round(${e[0]}, ${si(t[1])}::int)`},ABS:{args:["numero"],tipo:()=>"numero",sql:e=>O`abs(${e[0]})`},MIN:{args:["cualquiera"],resto:"cualquiera",tipo:e=>bm(e),sql:e=>O`least(${O.join(e)})`},MAX:{args:["cualquiera"],resto:"cualquiera",tipo:e=>bm(e),sql:e=>O`greatest(${O.join(e)})`},CONCAT:{args:[],resto:"cualquiera",tipo:()=>"texto",sql:e=>O`concat(${O.join(e.map(gm))})`},MAYUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>O`upper(${e[0]})`},MINUSCULAS:{args:["texto"],tipo:()=>"texto",sql:e=>O`lower(${e[0]})`},IZQUIERDA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>O`left(${e[0]}, ${Kt(e[1],1e4)})`},DERECHA:{args:["texto","numero"],tipo:()=>"texto",sql:e=>O`right(${e[0]}, ${Kt(e[1],1e4)})`},LARGO:{args:["texto"],tipo:()=>"numero",sql:e=>O`(length(${e[0]}))::numeric`},RECORTAR:{args:["texto"],tipo:()=>"texto",sql:e=>O`btrim(${e[0]})`},TEXTO:{args:["cualquiera"],tipo:()=>"texto",sql:e=>gm(e[0])},HOY:{args:[],tipo:()=>"fecha",sql:()=>O`(now() at time zone ${ys})::date`},AHORA:{args:[],tipo:()=>"fecha_hora",sql:()=>O`now()`},DIAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!eo(e,0)||!eo(e,1))throw i("F\xF3rmula: DIAS_ENTRE necesita dos fechas.");return"numero"},sql:(e,o)=>O`((${$t(e[1],o[1])}) - (${$t(e[0],o[0])}))::numeric`},ANADIR_DIAS:{args:["cualquiera","numero"],tipo:e=>{if(!eo(e,0))throw i("F\xF3rmula: A\xD1ADIR_DIAS necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?O`(${e[0]} + ${Kt(e[1],1e5)})`:O`(${e[0]} + make_interval(days => ${Kt(e[1],1e5)}))`},ANO:{args:["cualquiera"],tipo:e=>bs(e),sql:(e,o)=>O`(extract(year from ${$t(e[0],o[0])}))::numeric`},MES:{args:["cualquiera"],tipo:e=>bs(e),sql:(e,o)=>O`(extract(month from ${$t(e[0],o[0])}))::numeric`},DIA:{args:["cualquiera"],tipo:e=>bs(e),sql:(e,o)=>O`(extract(day from ${$t(e[0],o[0])}))::numeric`},POTENCIA:{args:["numero","numero"],tipo:()=>"numero",sql:e=>O`(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
|
-
else power((${e[0]})::numeric, (${e[1]})::numeric) end)`},PAGO:{args:["numero","numero","numero"],tipo:()=>"numero",sql:e=>
|
|
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(_s,{RESTO:{args:["numero","numero"],tipo:()=>"numero",sql:e=>O`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?(Zt(e[0],e[t]),o=o?Zt(o,e[t+1]):e[t+1]):o=o?Zt(o,e[t]):e[t];return o},sql:e=>{let o=[];for(let n=1;n+1<e.length;n+=2)o.push(O`when ${e[0]} = ${e[n]} then ${e[n+1]}`);let t=(e.length-1)%2===1?O`else ${e[e.length-1]}`:O``;return O`(case ${O.join(o,O` `)} ${t} end)`}},CONTIENE:{args:["texto","texto"],tipo:()=>"booleano",sql:e=>O`(strpos(lower(${e[0]}), lower(${e[1]})) > 0)`},SUSTITUIR:{args:["texto","texto","texto"],tipo:()=>"texto",sql:e=>O`replace(${e[0]}, ${e[1]}, coalesce(${e[2]}, ''))`},ANADIR_MESES:{args:["cualquiera","numero"],tipo:e=>{if(!eo(e,0))throw i("F\xF3rmula: A\xD1ADIR_MESES necesita una fecha.");return e[0]},sql:(e,o)=>o[0]==="fecha"?O`((${e[0]} + make_interval(months => ${Kt(e[1],12e3)}))::date)`:O`(${e[0]} + make_interval(months => ${Kt(e[1],12e3)}))`},HORAS_ENTRE:{args:["cualquiera","cualquiera"],tipo:e=>{if(!eo(e,0)||!eo(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"?O`((${n})::timestamp at time zone ${ys})`:n;return O`round((extract(epoch from (${t(e[1],o[1])} - ${t(e[0],o[0])})) / 3600)::numeric, 6)`}}});vw={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"},FI=Object.keys(_s);xt={numero:"un n\xFAmero",texto:"un texto",fecha:"una fecha",fecha_hora:"una fecha y hora",booleano:"un s\xED/no"};Ns={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"},wm={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"},WI={numero:O`numeric`,texto:O`text`,fecha:O`date`,fecha_hora:O`timestamptz`,booleano:O`boolean`},$s=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};$w=new Set(["creado_el","creado_por","modificado_el","modificado_por","autonumero"]),ym={companies:"companies_summary",contacts:"contacts_summary",deals:"deals"}});function Nm(e,o){if(e==null)return;if(!Vr(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(!Vr(r)||!Vr(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(f=>f.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(!Vr(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(!Vr(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 Vr,$m=m(()=>{E();Vr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function jm(e,o){if(e==null)return;if(!Ro(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=Ur(r,o)??{},s=or(n,"El texto del documento",Sm);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 er(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 or(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 Ct(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 xm(e,o){if(e===void 0)return;if(!Ro(e))throw i("La condici\xF3n de ficha necesita un campo y un valor.");er(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 di(e,o){if(e==null)return;if(!Ro(e))throw i("\xABficha\xBB: un objeto.");er(e,["cabecera","columnas","pestanas","grupos","relacionadas","erp","sin_conexion","rapido","duplicados","tarjeta","en_crear","filtros","principal","plegar_vacios"],"Ficha");let t={},n=Ct(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((f,h)=>{if(!Ro(f))throw i(`Pesta\xF1a ${h+1}: un objeto.`);er(f,["titulo","secciones","artefacto","cuando"],`Pesta\xF1a ${h+1}`);let b=or(f.titulo,`Pesta\xF1a ${h+1}`,40);if(!b)throw i(`Pesta\xF1a ${h+1}: falta el t\xEDtulo.`);let y=xm(f.cuando,o);if(f.artefacto!==void 0){let v=Number(f.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(f.secciones)||f.secciones.length>20||!f.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(f.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??"")),f=new Set,h=e.grupos.map(b=>{if(!Ro(b))throw i("Grupo de ficha: un objeto.");if(er(b,["seccion","cuando","plegado"],"Grupo de ficha"),typeof b.seccion!="string"||!p.has(b.seccion)||f.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.");f.add(b.seccion);let y=xm(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=Nm(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=Ct(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=Ct(e.duplicados,o,3,"Los campos de duplicados",p=>jw.includes(p.tipo));s?.length&&(t.duplicados=s);let c=Ct(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=Ct(e.filtros,o,4,"Los filtros de arriba",p=>Sw.includes(p.tipo));d?.length&&(t.filtros=d);let u=Ct(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 Ur(e,o){if(e==null)return;if(!Ro(e))throw i("\xABimpresion\xBB: un objeto.");er(e,["titulo","campos","subtabla","subtablaVacia","pie","logo","orientacion","cuerpo","color","firmas"],"Impresi\xF3n");let t={},n=or(e.titulo,"El t\xEDtulo de la impresi\xF3n",80);n&&(t.titulo=n);let r=Ct(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=or(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=or(e.cuerpo,"El texto del documento",Sm);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 xs(e,o=0){return o>10?!1:Array.isArray(e)?e.every(t=>xs(t,o+1)):Ro(e)?Object.keys(e).every(t=>!Ow.has(t)&&xs(e[t],o+1)):!0}function Om(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(!Ro(n))throw i(`Vista ${r+1}: un objeto.`);er(n,["nombre","tipo","config"],`Vista ${r+1}`);let a=or(n.nombre,`Vista ${r+1}`,60);if(!a)throw i(`Vista ${r+1}: falta el nombre.`);if(typeof n.tipo!="string"||!Cm.includes(n.tipo))throw i(`Vista ${r+1}: tipo ${Cm.join(", ")}.`);if(n.config!==void 0&&(!Ro(n.config)||!xs(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 Ro,jw,Sw,Sm,Cm,Ow,Cs=m(()=>{E();$m();Ro=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);jw=["texto","correo","telefono","codigo","url"],Sw=["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"];Sm=12e3;Cm=["kanban","calendario","linea","mapa","galeria","tablero","cuadrante","dia"],Ow=new Set(["__proto__","constructor","prototype"])});var Jr,Am=m(()=>{Jr=e=>e==="@contacts"||e==="@companies"});function fi(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>pi)throw i(`\xABrelacionadas\xBB: hasta ${pi} columnas.`);if(!e.length)return;let t=new Set;return e.map((n,r)=>{let a=`Columna relacionada ${r+1}`;if(!Ss(n))throw i(`${a}: un objeto.`);qm(n,["clave","etiqueta","via","campo","de","calculo","filtro","siVacio"],a);let s=jt(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=Jr(String(n.de))&&typeof n.via=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.via)?n.via:jt(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"&&Jr(n.de)?n.de:jt(n.de,`${a}.de`);if(typeof n.calculo!="string"||!Em.includes(n.calculo))throw i(`${a}: \xABcalculo\xBB, uno de ${Em.join(", ")}.`);let p=n.calculo,f=p==="recuento"?void 0:Jr(u)&&typeof n.campo=="string"&&/^datos\.[a-z][a-z0-9_]{0,40}$/.test(n.campo)?n.campo:jt(n.campo,`${a}.campo`),h=Qr(n.filtro,a,Jr(u));return{clave:s,etiqueta:n.etiqueta.trim(),via:c,de:u,calculo:p,...f?{campo:f}:{},...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:jt(n.siVacio,`${a}.siVacio`)}:{}}})}function hi(e){if(e==null)return;if(!Array.isArray(e)||e.length>mi)throw i(`\xABsiguientes\xBB: hasta ${mi} pasos.`);if(!e.length)return;let o=new Set;return e.map((t,n)=>{let r=`Siguiente paso ${n+1}`;if(!Ss(t))throw i(`${r}: un objeto.`);qm(t,["clave","nombre","destino","enlace","campos"],r);let a=jt(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=jt(t.enlace,`${r}.enlace`),c;if(t.campos!==void 0&&t.campos!==null){if(!Ss(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(!js.test(d)||typeof u!="string"||!js.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 Em,pi,mi,js,Ss,qm,jt,gi=m(()=>{Am();E();Gr();Em=["recuento","suma","minimo","maximo","ultimo","media"],pi=20,mi=5,js=/^[a-z][a-z0-9_]{0,40}$/,Ss=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qm=(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.`)},jt=(e,o)=>{if(typeof e!="string"||!js.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e}});function Os(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"?di(c,o):s==="impresion"?Ur(c,o):s==="relacionadas"?fi(c,o):s==="recurso"?ii(c,o):s==="reserva"?ai(c,o):hi(c))??null})}t[n]=a}return t}var km=m(()=>{gs();E();Cs();gi()});function Pm(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=>!As.includes(n)))throw i("Un ajuste nativo no cambia la identidad de la relaci\xF3n.");return structuredClone(e)}}var As,Es=m(()=>{E();As=["etiqueta","ayuda","enTabla","obligatorio","visibleSi","obligatorioSi","permisos","siVacio","completarDesde"]});function Tm(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(qs,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(qs,a))continue;let s=qs[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,Lr(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 qs,Mm=m(()=>{E();ds();qs={sector:"companySectors",forma_juridica:"legalForms"}});function ks(e,o){if(e===void 0)return;if(!ko(e))throw i("\xABpersonas\xBB: un objeto.");if(Rs(e,["objeto","tipo","de","campoNif","etiqueta","plural","icono","campos","conversiones","alternativa","clasificacion","configuracion"],"\xABpersonas\xBB"),e.alternativa!==void 0||e.clasificacion!==void 0)return Ew(e,o);if(e.objeto==="deals"&&o.some(f=>f.tipo==="autonumero"))throw i("Los auton\xFAmeros propios no est\xE1n disponibles en Oportunidades.");if(e.objeto==="deals"&&o.some(f=>f.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=bi(e.tipo,"tipo",60);if(!Aw.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=bi(e.icono,"icono",40);if(!/^[a-z0-9-]+$/.test(n))throw i("\xABpersonas.icono\xBB: una clave de icono.");if(!ko(e.campos))throw i("\xABpersonas.campos\xBB: un mapa expl\xEDcito de campos nativos.");let r={},a=new Map;for(let[f,h]of Object.entries(e.campos)){let b=o.find(w=>w.clave===f&&!w.archivado),y=typeof h=="string"&&Object.hasOwn(Lm[e.objeto],h)?Lm[e.objeto][h]:void 0,v=Ee(h);if(!b||!(v?cm.has(b.tipo):y?.includes(b.tipo)))throw i(`\xABpersonas.campos.${f.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,f),r[f]=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(f=>!f.archivado);for(let f of c)if(!Object.hasOwn(r,f.clave)&&f.tipo!=="resumen"&&f.tipo!=="formula")throw i(`\xABpersonas.campos\xBB: falta destino para \xAB${f.clave}\xBB; no se puede perder un campo.`);if(e.conversiones!==void 0&&!ko(e.conversiones))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");let d={};for(let[f,h]of Object.entries(e.conversiones??{})){if(!ko(h)||Object.values(h).some(b=>typeof b!="string"))throw i("Las conversiones nativas necesitan un mapa de selecciones completo.");Object.defineProperty(d,f,{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(f=>f.clave===u&&["texto","codigo"].includes(f.tipo))))throw i("\xABpersonas.campoNif\xBB: elige un campo propio de texto de Personas.");zm(o,r,t),Tm(o,r,d);let p=Os(e.configuracion,o);if(p&&Object.keys(p).some(f=>f!==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:bi(e.etiqueta,"etiqueta",60),plural:bi(e.plural,"plural",60),icono:n,campos:r,...e.conversiones!==void 0?{conversiones:d}:{}}}function Ew(e,o){let t=e.alternativa,n=e.clasificacion;if(e.objeto!=="contacts"||!ko(t)||t.objeto!=="companies"||!ko(t.campos)||!ko(n))throw i("Los destinos dobles necesitan Persona, Empresa y clasificaci\xF3n expl\xEDcita.");Rs(t,["objeto","campos","conversiones"],"\xABpersonas.alternativa\xBB"),Rs(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)||!ko(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=Up(n,r,n.valores),c={campo:r.clave,valores:{...n.valores},...n.vacio?{vacio:n.vacio}:{},...s},{alternativa:d,clasificacion:u,configuracion:p,...f}=e,h=v=>ks(v,Qp(o,c,v.objeto).filter(w=>ko(v.campos)&&Object.hasOwn(v.campos,w.clave)||w.tipo==="resumen"||w.tipo==="formula")),b=h(f),y=h({...f,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 Jp(o,c),{...b,alternativa:{objeto:"companies",campos:y.campos,...y.conversiones?{conversiones:y.conversiones}:{}},clasificacion:c,...e.configuracion!==void 0?{configuracion:Os(e.configuracion,o)}:{}}}var Im,Lm,ko,Aw,bi,Rs,Dm=m(()=>{Dr();lm();km();E();Gp();Mm();Im={ubicacion:["ubicacion"],address:["texto","texto_largo"],zipcode:["texto","codigo"],city:["texto"],country:["texto"],pais_fiscal:["texto","seleccion"],iban:["texto"]},Lm={contacts:{...Im,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:{...Im,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"]}},ko=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Aw=/^[a-z0-9][a-z0-9-]{0,59}$/,bi=(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()},Rs=(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 qw,Script as Rw}from"node:vm";function wi(e,o){if(e!=null){if(!Array.isArray(e)||e.length>Fm)throw i(`\xAB${o}\xBB: como mucho ${Fm} 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(!kw.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(!Pw(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 Jm(e,o){if(!(e==null||e==="")){if(typeof e!="string"||e.length>Wm)throw i(`\xAB${o}\xBB: el patr\xF3n, hasta ${Wm} caracteres.`);if(/\\[1-9]|\\k<|\(\?<[=!]/.test(e))throw i(`\xAB${o}\xBB: el patr\xF3n no admite retroreferencias ni lookbehind.`);if(Tw(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 Tw(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 Qm(e,o){if(e==null)return;let t=e,n=t?.tipo;if(typeof t!="object"||!Bm[n])throw i(`\xAB${o.etiqueta}\xBB: valor por defecto no v\xE1lido.`);if(!Bm[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 kw,Fm,Wm,Vm,Um,Bm,Pw,_1,N1,Gm=m(()=>{E();kw=["igual","distinto","vacio","lleno","uno_de"],Fm=10,Wm=200,Vm=["texto","correo","telefono","url","codigo"],Um=["texto","correo","telefono","url","codigo","numero","importe"],Bm={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"]},Pw=e=>typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean";_1=qw({p:"",v:""}),N1=new Rw("new RegExp(p, 'u').test(v)")});function Xm(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>Hm)throw i(`\xABvalidaciones\xBB: hasta ${Hm}.`);let t=[];for(let[n,r]of e.entries()){if(!Iw(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>oo)throw i(`Validaci\xF3n ${n+1}: la f\xF3rmula, de 1 a ${oo} 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=ci([...o,Lw(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 Hm,Iw,Lw,Ym=m(()=>{E();li();Hm=20,Iw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lw=(e,o)=>({clave:`validacion_${e}`,etiqueta:`Validaci\xF3n ${e+1}`,tipo:"formula",formula:o})});function ef(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(!Zm(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"||!Km.test(e.campo))throw i(`${t}: \xBFde qu\xE9 campo depende?`);if(o.tipo==="seleccion"){if(!Zm(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"||!Km.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 of(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 Km,Zm,tf=m(()=>{E();Km=/^[a-z][a-z0-9_]{0,39}$/,Zm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function nf(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=Ps(r.papeles,30,/^(titular|administrador|miembro|lectura|p_[a-z]{1,12})$/),s.pide=Ps(r.pide,30,/^[a-z][a-z0-9_]{0,40}$/),s.acciones=Ps(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 af(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,Ps,sf=m(()=>{E();rf=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ps=(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 cf(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 k1,lf=m(()=>{oi();E();k1=O`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 df(e,o,t){if(e.requisito!==void 0&&e.requisito!==null){let n=e.requisito;if(!Dw(n)||typeof n.formula!="string"||!n.formula.trim()||n.formula.length>oo||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>uf||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 ${uf} campos.`);e.pide.length&&(o.pide=[...new Set(e.pide)])}if(cf(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 pf(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=ci([...o,zw(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 uf,Dw,zw,mf=m(()=>{E();li();lf();uf=5,Dw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zw=(e,o,t)=>({clave:`etapa_${e}_${o}`,etiqueta:`Requisito ${o+1}`,tipo:"formula",formula:t})});function gf(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(!vi(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"||!St.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"||!(Fw.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:hf(n.campos,a)};for(let c of["enlaceDestino","enlaceOrigen"])if(!(n[c]===void 0||n[c]===null||n[c]==="")){if(typeof n[c]!="string"||!St.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(!vi(c)||typeof c.desde!="string"||!St.test(c.desde)||typeof c.a!="string"||!St.test(c.a))throw i(`${a}: cada \xABlineas\xBB, {desde, a, campos}.`);return{desde:c.desde,a:c.a,campos:hf(c.campos,a)}})}if(n.etapa!==void 0&&n.etapa!==null){if(!vi(n.etapa)||typeof n.etapa.campo!="string"||!St.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,St,Fw,vi,hf,bf=m(()=>{E();ff=5,St=/^[a-z][a-z0-9_]{0,40}$/,Fw=["contacts","companies","deals"],vi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hf=(e,o)=>{if(e===void 0)return{};if(!vi(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(!St.test(t)||typeof n!="string"||!St.test(n))throw i(`${o}: el campo \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}});function yf(e,o){if(e==null)return;if(!Array.isArray(e)||e.length>wf)throw i(`\xABencadenar\xBB: hasta ${wf}.`);let t=new Set,n=e.map((r,a)=>{let s=`\xABencadenar\xBB ${a+1}`;if(!Ot(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=Yo(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(!Ot(r.lineas))throw i(`${s}: \xABlineas\xBB {desde, a, cantidad: {origen, destino}}.`);let d=r.lineas,u=Yo(d.desde,`${s}.lineas.desde`),p=Bw(o,u);if(!p)throw i(`${s}: \xAB${u}\xBB no es una subtabla de este m\xF3dulo.`);if(!Ot(d.cantidad))throw i(`${s}: \xABlineas.cantidad\xBB {origen, destino}.`);let f=Yo(d.cantidad.origen,`${s}.lineas.cantidad.origen`),h=(p.columnas??[]).find(w=>w.clave===f&&!w.archivado);if(!h||!(Ww.includes(h.tipo)||h.tipo==="formula"&&h.origen?.tipo==="numero"))throw i(`${s}: la cantidad \xAB${f}\xBB tiene que ser una columna num\xE9rica de \xAB${u}\xBB.`);let b={clave:c,nombre:r.nombre.trim(),destino:r.destino,enlace:Yo(r.enlace,`${s}.enlace`),lineas:{desde:u,a:Yo(d.a,`${s}.lineas.a`),cantidad:{origen:f,destino:Yo(d.cantidad.destino,`${s}.lineas.cantidad.destino`)}}},y=vf(d.campos,`${s}.lineas.campos`);if(y){for(let w of Object.values(y))if(!(p.columnas??[]).some(_=>_.clave===w&&!_.archivado))throw i(`${s}: \xAB${w}\xBB no es una columna de \xAB${u}\xBB.`);b.lineas.campos=y}let v=vf(r.campos,`${s}.campos`);if(v){for(let w of Object.values(v))if(!o.some(_=>_.clave===w&&!_.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(!Ot(w))throw i(`${s}: \xABestado\xBB {campo, parcial, completo, pendiente?}.`);let _=o.find(S=>S.clave===w.campo&&S.tipo==="seleccion"&&!S.archivado);if(!_)throw i(`${s}: \xABestado.campo\xBB tiene que ser una selecci\xF3n de este m\xF3dulo.`);let C=new Set((_.opciones??[]).map(S=>S.valor));for(let S of["parcial","completo","pendiente"]){let P=w[S];if(!(P===void 0&&S==="pendiente")&&(typeof P!="string"||!C.has(P)))throw i(`${s}: \xABestado.${S}\xBB tiene que ser una opci\xF3n de \xAB${_.etiqueta}\xBB.`)}b.estado={campo:_.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(!Ot(w)||!Array.isArray(w.valores)||w.valores.length>20||!w.valores.every(_=>typeof _=="string"&&_.length<=60))throw i(`${s}: \xABno_cuentan\xBB {campo, valores}.`);b.no_cuentan={campo:Yo(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(!Ot(w))throw i(`${s}: \xABjuntar\xBB {iguales?, enlace_varios?}.`);for(let C of Object.keys(w))if(!["iguales","enlace_varios"].includes(C))throw i(`${s}: \xABjuntar\xBB: clave no admitida \xAB${C.slice(0,40)}\xBB.`);let _=w.iguales===void 0?[]:w.iguales;if(!Array.isArray(_)||_.length>10||!_.every(C=>typeof C=="string"&&o.some(S=>S.clave===C&&!S.archivado)))throw i(`${s}: \xABjuntar.iguales\xBB, campos de este m\xF3dulo (hasta 10).`);b.juntar={..._.length?{iguales:_}:{},...w.enlace_varios?{enlace_varios:Yo(w.enlace_varios,`${s}.juntar.enlace_varios`)}:{}}}return b});return n.length?n:void 0}var wf,Ts,Ww,Ot,vf,Yo,Bw,_f=m(()=>{E();wf=5,Ts=/^[a-z][a-z0-9_]{0,40}$/,Ww=["numero","importe","duracion","porcentaje"],Ot=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vf=(e,o)=>{if(e!=null){if(!Ot(e)||Object.keys(e).length>60)throw i(`${o}: un objeto destino \u2192 origen.`);for(let[t,n]of Object.entries(e))if(!Ts.test(t)||typeof n!="string"||!Ts.test(n))throw i(`${o}: \xAB${t.slice(0,40)}\xBB no es v\xE1lido.`);return e}},Yo=(e,o)=>{if(typeof e!="string"||!Ts.test(e))throw i(`${o}: falta o no es v\xE1lido.`);return e},Bw=(e,o)=>e.find(t=>t.clave===o&&t.tipo==="subtabla"&&!t.archivado)});function xf(e){if(e==null)return;if(!Array.isArray(e)||e.length>Nf)throw i(`\xABplantillas_hijos\xBB: hasta ${Nf}.`);let o=new Set,t=e.map((n,r)=>{let a=`Plantilla de hijos ${r+1}`;if(!Ms(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"||!yi.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(!Ms(d)||typeof d.campo!="string"||!yi.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(!yi.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"||!yi.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>$f)throw i(`${a}: \xABregistros\xBB, de 1 a ${$f}.`);return c.registros=n.registros.map(d=>{if(!Ms(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 Nf,$f,yi,Ms,Cf=m(()=>{E();Nf=10,$f=50,yi=/^[a-z][a-z0-9_]{0,40}$/,Ms=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Sf(e,o){if(e==null)return;if(!ho(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:Vw(e.correccion_dias)}:{}}}function Of(e,o){if(e==null)return;if(!ho(e))throw i("\xABasignacion\xBB: un objeto.");if(typeof e.oferta!="string"||!Ni.test(e.oferta))throw i("\xABasignacion.oferta\xBB: la clave del m\xF3dulo de la oferta.");let t=e.destino,n;if(ho(t)&&t.forma==="pertenencia"&&typeof t.modulo=="string"&&Ni.test(t.modulo))n={forma:"pertenencia",modulo:t.modulo};else if(ho(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"||!Ni.test(e.cupo))throw i("\xABasignacion.cupo\xBB: un campo num\xE9rico de la oferta.");return{oferta:e.oferta,destino:n,...Jw({...e,cupo_fijo:void 0},o),cupo:e.cupo}}function Jw(e,o,t=!1){let n=(p,f,h)=>{let b=o.find(y=>y.clave===p&&!y.archivado);if(!b||h&&!h.includes(b.tipo))throw i(`\xABasignacion\xBB: ${f}, ${h?h.join(" o "):"un campo"} de este m\xF3dulo.`);return b.clave},r=(p,f)=>{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(`${f}: campo de oferta no v\xE1lido.`);return p}return Uw(p,f)},a=t?jf:Ni,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(!ho(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(!ho(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>_i||u.length>_i)throw i(`\xABasignacion\xBB: hasta ${_i} filtros y ${_i} puntos.`);if(c.filtros=d.map((p,f)=>{let h=`Filtro ${f+1}`;if(!ho(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,f)=>{let h=`Punto ${f+1}`;if(!ho(p))throw i(`${h}: un objeto.`);switch(p.tipo){case"base":case"carga":return{tipo:p.tipo,peso:At(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:At(p.peso,h)};case"igual":case"contiene":return{tipo:p.tipo,demanda:n(p.demanda,`${h}, \xABdemanda\xBB`),oferta:r(p.oferta,h),peso:At(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:At(p.misma,h),...ho(y)?{mismo_campo:{oferta:r(y.oferta,h),peso:At(y.peso,h)}}:{},...p.mismo_valor!==void 0?{mismo_valor:At(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:At(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(!ho(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 ho,Ni,jf,_i,Vw,At,Uw,Af=m(()=>{E();ho=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ni=/^[a-z][a-z0-9_]{0,40}$/,jf=/^[a-z][a-z0-9_]{0,40}(\.[a-z][a-z0-9_]{0,40})?$/,_i=20,Vw=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};At=(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},Uw=(e,o)=>{if(typeof e!="string"||!jf.test(e))throw i(`${o}: un campo de la oferta (\xABcampo\xBB o \xABrelacion.campo\xBB).`);return e}});function Ef(e,o){if(e==null)return;if(!$i(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(Gw.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(!$i(a)||typeof a.clave!="string"||!Qw.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(f=>f.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=$i(u)?t(u.subtabla):void 0,f=p?.tipo==="subtabla"?(p.columnas??[]).find(h=>h.clave===u.columna&&!h.archivado):void 0;if(f?.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:f.clave}}if(a.firma!==void 0&&a.firma!==null&&a.firma!==!1){let u=a.firma===!0?{}:a.firma;if(!$i(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 Qw,$i,Gw,qf=m(()=>{E();Qw=/^[a-z][a-z0-9_]{0,40}$/,$i=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gw=["secreto","boton","firma"]});function Pf(e,o){if(fe(e))return;if(!go(e))throw i("\xABstock\xBB: un objeto {articulo?, ubicacion?, movimiento?}.");Ko(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(!fe(e.articulo)){let s=e.articulo;if(!go(s))throw i("\xABstock.articulo\xBB: un objeto.");Ko(s,["minimo","reponer","proveedor","permitir_negativo","lotes"],"stock.articulo");let c={};if(fe(s.minimo)||(c.minimo=n(s.minimo,"articulo.minimo",d=>d.tipo==="numero","un n\xFAmero")),fe(s.reponer)||(c.reponer=n(s.reponer,"articulo.reponer",d=>d.tipo==="numero","un n\xFAmero")),fe(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(!fe(s.permitir_negativo)&&s.permitir_negativo!==!1)throw i("\xABstock.articulo.permitir_negativo\xBB: true o un s\xED/no del art\xEDculo.");if(!fe(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(!fe(e.ubicacion)){let s=e.ubicacion;if(!go(s))throw i("\xABstock.ubicacion\xBB: un objeto.");Ko(s,["almacen"],"stock.ubicacion"),a.ubicacion=fe(s.almacen)?{}:{almacen:n(s.almacen,"ubicacion.almacen",r,"una relaci\xF3n simple a otro m\xF3dulo")}}if(!fe(e.movimiento)){let s=e.movimiento;if(!go(s))throw i("\xABstock.movimiento\xBB: un objeto.");if(Ko(s,["tipo","lineas","ubicacion","ubicacion_destino","cuando"],"stock.movimiento"),!Rf.includes(s.tipo))throw i(`\xABstock.movimiento.tipo\xBB: ${Rf.join(", ")}.`);if(!go(s.lineas))throw i("\xABstock.movimiento.lineas\xBB: {subtabla, articulo, cantidad, ubicacion?, coste?}.");let c=s.lineas;Ko(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,_,C)=>{let S=u.find(P=>P.clave===v);if(!S||!_(S))throw i(`\xABstock.movimiento.lineas.${w}\xBB: ${C} de \xAB${d.etiqueta}\xBB.`);return S.clave},f={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(fe(c.ubicacion)||(f.lineas.ubicacion=p(c.ubicacion,"ubicacion",r,"una relaci\xF3n simple")),fe(c.coste)||(f.lineas.coste=p(c.coste,"coste",v=>kf.includes(v.tipo),"una columna num\xE9rica")),fe(c.lote)||(f.lineas.lote=p(c.lote,"lote",v=>v.tipo==="texto"||v.tipo==="codigo","una columna de texto")),fe(c.caducidad)||(f.lineas.caducidad=p(c.caducidad,"caducidad",v=>v.tipo==="fecha","una columna de fecha")),fe(s.ubicacion)||(f.ubicacion=n(s.ubicacion,"movimiento.ubicacion",r,"una relaci\xF3n simple")),!f.lineas.ubicacion&&!f.ubicacion)throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n, en la l\xEDnea (\xABlineas.ubicacion\xBB) o en el documento (\xABubicacion\xBB).");if(fe(c.ubicacion_destino)||(f.lineas.ubicacion_destino=p(c.ubicacion_destino,"ubicacion_destino",r,"una relaci\xF3n simple")),fe(s.ubicacion_destino)||(f.ubicacion_destino=n(s.ubicacion_destino,"movimiento.ubicacion_destino",r,"una relaci\xF3n simple")),f.tipo==="traspaso"&&!f.lineas.ubicacion_destino&&!f.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(f.tipo!=="traspaso"&&(f.lineas.ubicacion_destino||f.ubicacion_destino))throw i("\xABstock.movimiento\xBB: la ubicaci\xF3n de destino es solo de un traspaso.");if(!go(s.cuando))throw i("\xABstock.movimiento.cuando\xBB: {campo, valor} o {campo, valores}.");Ko(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.`);f.cuando={campo:h.clave,valores:[...new Set(b)]},a.movimiento=f}if(!fe(e.reponer)){let s=e.reponer;if(!go(s))throw i("\xABstock.reponer\xBB: {destino, proveedor, lineas: {subtabla, articulo, cantidad}, estado?}.");if(Ko(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"||!Is.test(s.proveedor))throw i("\xABstock.reponer.proveedor\xBB: la relaci\xF3n de las compras al proveedor.");if(!go(s.lineas))throw i("\xABstock.reponer.lineas\xBB: {subtabla, articulo, cantidad}.");Ko(s.lineas,["subtabla","articulo","cantidad"],"stock.reponer.lineas");for(let d of["subtabla","articulo","cantidad"])if(typeof s.lineas[d]!="string"||!Is.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(!fe(s.estado)){if(!go(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(!fe(s.en_camino)){let d=s.en_camino;if(!go(d)||typeof d.campo!="string"||!Is.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 Rf,go,Ko,kf,fe,Is,Tf=m(()=>{E();Rf=["entrada","salida","ajuste","traspaso","recuento","reserva"],go=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ko=(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"],fe=e=>e==null||e==="";Is=/^[a-z][a-z0-9_]{0,40}$/});function Xw(e,o){let t=`liquidacion.reglas[${o}]`;if(!Zo(e))throw i(`\xAB${t}\xBB: un objeto.`);if(et(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(Et(e.si)||(n.si=Lf(e.si,`${t}.si`)),Et(e.tramos))n.valor=zs(e.valor,`${t}.valor`);else{let r=e.tramos;if(!Zo(r))throw i(`\xAB${t}.tramos\xBB: {por, lista}.`);if(et(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>If)throw i(`\xAB${t}.tramos.lista\xBB: de 1 a ${If} tramos {desde, valor}.`);let a=r.lista.map((s,c)=>{if(!Zo(s))throw i(`\xAB${t}.tramos.lista[${c}]\xBB: {desde, valor}.`);return et(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},!Et(e.valor))throw i(`\xAB${t}\xBB: con tramos, el valor va en cada tramo.`)}return n}function Df(e,o){if(Et(e))return;if(!Zo(e))throw i("\xABliquidacion\xBB: un objeto {origen, importe, fecha, agente, campos, estados, lineas, reglas}.");if(et(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":xi(e.agente,"liquidacion.agente"),n=_=>o.find(C=>C.clave===_&&!C.archivado),r=(_,C,S,P)=>{let Z=n(_);if(!Z||!S(Z))throw i(`\xABliquidacion.${C}\xBB: ${P} de este m\xF3dulo.`);return Z.clave},a=_=>_.tipo==="relacion"&&!_.multiple&&!!_.relacion?.startsWith("mod_"),s=_=>a(_)||_.tipo==="relacion"&&!_.multiple&&["contacts","companies"].includes(_.relacion??"");if(!Zo(e.campos))throw i("\xABliquidacion.campos\xBB: {agente?, periodo, estado, total}.");et(e.campos,["agente","periodo","estado","total"],"liquidacion.campos");let c={periodo:r(e.campos.periodo,"campos.periodo",_=>_.tipo==="texto","un texto"),estado:r(e.campos.estado,"campos.estado",_=>_.tipo==="seleccion","una selecci\xF3n"),total:r(e.campos.total,"campos.total",_=>Ds.includes(_.tipo),"un n\xFAmero o importe")};if(Et(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(_=>_.valor));if(!Zo(e.estados))throw i("\xABliquidacion.estados\xBB: {borrador, aprobada, cerrada, pagada} con opciones de su selecci\xF3n.");et(e.estados,[...Ls],"liquidacion.estados");let p={};for(let _ of Ls){let C=e.estados[_];if(typeof C!="string"||!u.has(C))throw i(`\xABliquidacion.estados.${_}\xBB: una opci\xF3n de \xAB${d.etiqueta}\xBB.`);p[_]=C}if(new Set(Object.values(p)).size!==Ls.length)throw i("\xABliquidacion.estados\xBB: una opci\xF3n distinta para cada estado.");if(!Zo(e.lineas))throw i("\xABliquidacion.lineas\xBB: {subtabla, origen, base, comision, regla?}.");et(e.lineas,["subtabla","origen","base","comision","regla"],"liquidacion.lineas");let f=n(e.lineas.subtabla);if(f?.tipo!=="subtabla")throw i("\xABliquidacion.lineas.subtabla\xBB: una subtabla de este m\xF3dulo.");let h=(f.columnas??[]).filter(_=>!_.archivado),b=(_,C,S,P)=>{let Z=h.find(we=>we.clave===_);if(!Z||!S(Z))throw i(`\xABliquidacion.lineas.${C}\xBB: ${P} de \xAB${f.etiqueta}\xBB.`);return Z.clave},y={subtabla:f.clave,origen:b(e.lineas.origen,"origen",_=>a(_)&&_.relacion===e.origen,`la relaci\xF3n simple a ${String(e.origen)}`),base:b(e.lineas.base,"base",_=>Ds.includes(_.tipo),"una columna num\xE9rica"),comision:b(e.lineas.comision,"comision",_=>Ds.includes(_.tipo),"una columna num\xE9rica")};if(Et(e.lineas.regla)||(y.regla=b(e.lineas.regla,"regla",_=>_.tipo==="texto","una columna de texto")),!Array.isArray(e.reglas)||!e.reglas.length||e.reglas.length>Mf)throw i(`\xABliquidacion.reglas\xBB: de 1 a ${Mf}.`);let v=e.reglas.map(Xw),w={origen:e.origen,importe:xi(e.importe,"liquidacion.importe"),fecha:xi(e.fecha,"liquidacion.fecha"),agente:t,campos:c,estados:p,lineas:y,reglas:v};return Et(e.cuentan)||(w.cuentan=Lf(e.cuentan,"liquidacion.cuentan")),w}var Ls,Mf,If,Ds,Hw,Zo,Et,et,xi,Lf,zs,zf=m(()=>{E();Ls=["borrador","aprobada","cerrada","pagada"],Mf=20,If=20,Ds=["numero","importe","porcentaje"],Hw=/^[a-z][a-z0-9_]{0,40}$/,Zo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Et=e=>e==null||e==="",et=(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.`)},xi=(e,o)=>{if(typeof e!="string"||!Hw.test(e))throw i(`\xAB${o}\xBB: falta o no es v\xE1lido.`);return e},Lf=(e,o)=>{if(!Zo(e))throw i(`\xAB${o}\xBB: {campo, valores}.`);if(et(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:xi(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 Wf(e,o){if(Ff(e))return;if(!Fs(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(!Hr.includes(e.periodicidad))throw i(`\xABcuota.periodicidad\xBB: ${Hr.join(", ")} (o {campo, valores}).`);r.periodicidad=e.periodicidad}else if(Fs(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(!Fs(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(!Hr.includes(u))throw i(`\xABcuota.periodicidad.valores.${d.slice(0,40)}\xBB: ${Hr.join(", ")}.`)}r.periodicidad={campo:s.clave,valores:a.valores}}else throw i(`\xABcuota.periodicidad\xBB: ${Hr.join(", ")} o {campo, valores}.`);if(!Ff(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 Hr,Fs,Ff,Bf=m(()=>{E();Hr=["semanal","quincenal","mensual","bimestral","trimestral","semestral","anual"],Fs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ff=e=>e==null||e===""});function Jf(e,o){if(e==null)return;if(!Uf(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"?Ws[e.tipo]:void 0;if(!n||!Object.hasOwn(Ws,e.tipo))throw i(`\xABpapel.tipo\xBB: uno de ${Object.keys(Ws).join(", ")}.`);let r=e.campos??{};if(!Uf(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(f=>f.clave===d&&!f.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=Kw(n,e.atributos,o);return s?{tipo:e.tipo,campos:a,atributos:s}:{tipo:e.tipo,campos:a}}function Kw(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 Vf,Yw,Ws,Uf,Qf=m(()=>{E();Vf={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"]}},Yw={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"]}},Ws={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:Vf},proveedores:{etiqueta:"Proveedores",campos:Vf},catalogo:{etiqueta:"Cat\xE1logo",campos:Yw,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"]}}}},Uf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Qr(e,o,t=!1){if(e!=null){if(!Array.isArray(e)||e.length>Hf)throw i(`${o}: el filtro, una lista de hasta ${Hf} 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"||!(We.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"||!Gf.includes(s.op))throw i(`${a}: \xABop\xBB, una de ${Gf.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 th(e,o=!1){if(typeof e=="string"&&(eh.has(e)||rv.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 Qs(e,o,t=!1){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let n=e,r=th(n.clave,t);if(!Array.isArray(n.campos))throw i("Faltan los campos.");let a=n.campos.map((s,c)=>rr(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 nh(e,o){if(typeof e!="object"||e===null||Array.isArray(e))throw i("Definici\xF3n no v\xE1lida.");let t=e,n=th(t.clave,o.interno===!0),r=ot(t.nombre,"el nombre",60),a=ot(t.nombre_plural??t.nombre,"el nombre en plural",60),s=ot(t.descripcion??"","la descripci\xF3n",500,!0),c=typeof t.icono=="string"&&Js.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=ih(Qs(t,o.modulosDelEspacio,o.interno),n,o.camposRelacion);if(u.filter(R=>!R.archivado&&R.opciones?.some(D=>D.hecho)).length>1)throw i("Solo una selecci\xF3n puede marcar estados como \xABhechos\xBB.");if(u.filter(R=>!R.archivado&&R.proximaAccion).length>1)throw i("Solo una fecha puede ser la de la pr\xF3xima acci\xF3n.");let p=new Set;for(let R of u){if(p.has(R.clave))throw i(`El campo \xAB${R.clave}\xBB est\xE1 repetido.`);p.add(R.clave)}let f=u.filter(R=>!R.archivado);for(let R of f)for(let D of ps(R)){let oe=f.find(Rt=>Rt.clave===D.relacion);if(!oe||oe.clave===R.clave||oe.tipo!=="relacion"||oe.multiple&&!R.multiple)throw i(`\xAB${R.etiqueta}\xBB: un origen m\xFAltiple necesita tambi\xE9n un destino m\xFAltiple.`)}if(Bp(f),f.length===0)throw i("El m\xF3dulo necesita al menos un campo.");for(let R of f.filter(D=>D.tipo==="busqueda")){let D=f.find(oe=>oe.clave===R.desde);if(!D||D.tipo!=="relacion")throw i(`\xAB${R.etiqueta}\xBB: tiene que salir de un campo de relaci\xF3n de este m\xF3dulo.`)}for(let R of f.filter(D=>D.tipo==="qr"&&D.destino==="campo"&&D.campo))if(!f.find(oe=>oe.clave===R.campo))throw i(`\xAB${R.etiqueta}\xBB: el campo \xAB${R.campo}\xBB no existe en este m\xF3dulo.`);if(f.length>o.topeCampos)throw new L(400,"tope_campos",`Como mucho ${o.topeCampos} campos por m\xF3dulo en tu plan.`,!0,{topePlan:{clave:"campos",tope:o.topeCampos,solicitado:f.length}});for(let R of o.anterior??[]){let D=u.find(oe=>oe.clave===R.clave);if(!D)throw i(`El campo \xAB${R.etiqueta}\xBB no se quita: se archiva.`);if(D.tipo!==R.tipo&&!dv(R.tipo,D.tipo))throw i(`\xAB${R.etiqueta}\xBB no puede pasar de ${R.tipo} a ${D.tipo}.`)}let h=t.articulo==="un"||t.articulo==="una"?t.articulo:null,b=di(t.ficha,u),y=Ur(t.impresion,u),v=Xm(t.validaciones,u.filter(R=>!R.archivado));of(u);for(let R of u){if(R.tipo!=="contador"||!R.alMarcar)continue;let D=u.find(oe=>oe.clave===R.alMarcar&&!oe.archivado);if(D?.tipo!=="booleano"&&D?.tipo!=="hecho")throw i(`\xAB${R.etiqueta}\xBB: \xABal marcar\xBB tiene que ser un s\xED/no o un \xABhecho\xBB de este m\xF3dulo.`)}let w=Om(t.vistas,u),_=gf(t.conversiones),C=yf(t.encadenar,u),S=xf(t.plantillas_hijos),P=lv(t.campo_ambito,u),Z=Ef(t.publico,u),we=ii(t.recurso,u),$=ai(t.reserva,u),M=Of(t.asignacion,u),g=Sf(t.pertenencia,u),x=Pf(t.stock,u),A=Df(t.liquidacion,u),k=Zp(t.sucesion),J=rm(t.liquidacion_v2,u);if(A&&J)throw i("Elige una versi\xF3n de liquidaci\xF3n por m\xF3dulo.");let F=Wf(t.cuota,u),G=im(t.precios,u),Je=fi(t.relacionadas,u),tt=hi(t.siguientes),rt=Jf(t.papel,u),H=ks(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 Qe=t.portal??void 0,Ce;if(t.portal_campos!==void 0&&t.portal_campos!==null){let R=t.portal_campos;if(!Qe)throw i("\xABportal_campos\xBB va con \xABportal\xBB.");if(typeof R!="object"||Array.isArray(R)||Object.keys(R).length>u.length)throw i("\xABportal_campos\xBB: clave del campo \u2192 rellenar, ver o no.");for(let[D,oe]of Object.entries(R)){if(!u.some(Rt=>Rt.clave===D))throw i(`\xABportal_campos\xBB: el m\xF3dulo no tiene el campo \xAB${D.slice(0,40)}\xBB.`);if(oe!=="rellenar"&&oe!=="ver"&&oe!=="no")throw i(`\xABportal_campos.${D.slice(0,40)}\xBB: rellenar, ver o no.`)}Ce={...R}}let De;if(t.funcionesNativas!==void 0){if(!t.funcionesNativas||typeof t.funcionesNativas!="object"||Array.isArray(t.funcionesNativas)||Object.entries(t.funcionesNativas).some(([R,D])=>!["relacionadas","siguientes"].includes(R)||!Array.isArray(D)||D.length>(R==="relacionadas"?20:5)))throw i("Las funciones nativas necesitan relacionadas o siguientes declarados.");De=structuredClone(t.funcionesNativas)}return{clave:n,nombre:r,nombre_plural:a,articulo:h,descripcion:s,icono:c,...d!==void 0?{color:d}:{},campos:af(pf(u)).map(R=>{if(R.tipo!=="busqueda")return R;let{origen:D,...oe}=R;return oe}),paginas:t.paginas===!0,...b?{ficha:b}:{},...y?{impresion:y}:{},...v?{validaciones:v}:{},...w?{vistas:w}:{},..._?{conversiones:_}:{},...C?{encadenar:C}:{},...S?{plantillas_hijos:S}:{},...P?{campo_ambito:P}:{},...Z?{publico:Z}:{},...we?{recurso:we}:{},...$?{reserva:$}:{},...M?{asignacion:M}:{},...g?{pertenencia:g}:{},...x?{stock:x}:{},...A?{liquidacion:A}:{},...k?{sucesion:k}:{},...J?{liquidacion_v2:J}:{},...F?{cuota:F}:{},...G?{precios:G}:{},...Je?{relacionadas:Je}:{},...tt?{siguientes:tt}:{},...rt?{papel:rt}:{},...H?{personas:H}:{},...Qe?{portal:Qe}:{},...Ce&&Object.keys(Ce).length?{portal_campos:Ce}:{},...De?{funcionesNativas:De}:{}}}function lv(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 rr(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:f,alBorrar:h,...b}=r;return rr({...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>=Bs)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:f,alBorrar:h,multiple:b,...y}=r;return rr({...y,tipo:"subtabla",vinculo:!0,columnas:[{clave:"destino",etiqueta:r.etiqueta,tipo:"relacion",relacion:p,tipoContacto:f,alBorrar:h,obligatorio:!0},...u]},o,t,n)}if(typeof r.clave=="string"&&eh.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"||!We.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(!Vs.includes(a))throw i(`Tipo de campo no v\xE1lido: ${String(r.tipo)}.`);let s={clave:r.clave,etiqueta:ot(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=Pm(r.ajustesNativos);for(let u of Object.values(s.ajustesNativos??{})){let p={...r,...u,ajustesNativos:void 0};for(let[f,h]of Object.entries(u))h===null&&delete p[f];rr(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>oo||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=ot(r.seccion,"la secci\xF3n",60)),r.ayuda!==void 0&&r.ayuda!==""&&(s.ayuda=ot(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 f=typeof p=="string"?{valor:p,etiqueta:p}:p,h=ot(f.valor??f.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:ot(f.etiqueta??h,"una opci\xF3n",80)};return typeof f.color=="string"&&nv.test(f.color)&&(b.color=f.color),a==="seleccion"&&f.hecho===!0&&(b.hecho=!0),a==="seleccion"&&r.embudo===!0&&df(f,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=nf(r.transiciones,s)}}if(a==="relacion"){let u=r.relacion;if(!(typeof u=="string"&&(ev.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"||!pv.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(f=>!["relacion","campo","alternativa"].includes(f))||typeof u.relacion!="string"||!We.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 f=u.alternativa;if(!f||typeof f!="object"||Array.isArray(f)||Object.keys(f).some(h=>h!=="relacion"&&h!=="campo")||typeof f.relacion!="string"||!We.test(f.relacion)||typeof f.campo!="string"||!/^[a-z][a-z0-9_.]{0,80}$/.test(f.campo))throw i("La alternativa de autocompletado necesita relacion y campo.");p={relacion:f.relacion,campo:f.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=rr({...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(!We.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"||!We.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"||!We.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(!Zw.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(Zf.includes(a)&&delete s.obligatorio,a==="subtabla"){if(!Array.isArray(r.columnas)||r.columnas.length===0||r.columnas.length>Bs)throw i(`\xAB${s.etiqueta}\xBB: entre 1 y ${Bs} columnas.`);let u=new Set(["padre"]);if(s.columnas=r.columnas.map((h,b)=>{let y=rr(h,b,t,n);if(!cv.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+rh(y)>Yf)throw i(`\xAB${s.etiqueta}\xBB: como mucho ${Yf} 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>Xf)throw i(`${v}: \xABcopiar\xBB, un objeto columna \u2192 campo (hasta ${Xf}).`);for(let[w,_]of Object.entries(y)){let C=s.columnas.find(S=>S.clave===w);if(!C||C.tipo==="relacion"||C.tipo==="formula")throw i(`${v}: \xAB${w.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(typeof _!="string"||!We.test(_))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>Kf.length*2)throw i(`${v}: \xABrellenar\xBB, un objeto columna \u2192 dato del art\xEDculo.`);for(let[w,_]of Object.entries(y)){let C=s.columnas.find(S=>S.clave===w);if(!C||["relacion","articulo","formula","subtabla","resumen"].includes(C.tipo))throw i(`${v}: \xAB${w.slice(0,40)}\xBB no es una columna que se pueda rellenar.`);if(!Kf.includes(_))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"&&sv.test(r.hijo)&&(s.hijo=r.hijo);let f=jm(r.impresion,s.columnas);f&&(s.impresion=f),delete s.obligatorio}if(a==="autonumero"){let u=wi(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u)}if(!Rm({tipo:a})){let u=wi(r.visibleSi,s.etiqueta);u&&(s.visibleSi=u);let p=wi(r.obligatorioSi,s.etiqueta);if(p&&(s.obligatorioSi=p),r.patron!==void 0&&r.patron!==null&&r.patron!==""){if(!Vm.includes(a))throw i(`\xAB${s.etiqueta}\xBB: un patr\xF3n solo vale para textos, correos, tel\xE9fonos, webs y c\xF3digos.`);let h=Jm(r.patron,s.etiqueta);h&&(s.patron=h)}if(r.unico===!0){if(!Um.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 f=Qm(r.porDefecto,s);f&&(s.porDefecto=f)}let c=sh(r.permisos,s.etiqueta);if(c&&(s.permisos=c),r.grupo!==void 0&&r.grupo!==null&&r.grupo!==""){if(typeof r.grupo!="string"||!iv.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(!av.includes(a))throw i(`\xAB${s.etiqueta}\xBB: solo se enmascaran textos, correos, tel\xE9fonos y c\xF3digos.`);s.enmascarado=!0}let d=ef(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>oo)throw i(`\xAB${s.etiqueta}\xBB: escribe la f\xF3rmula (hasta ${oo} 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"||!We.test(r.via)||!Us.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"||!We.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"||!We.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=Qr(r.filtro,`\xAB${s.etiqueta}\xBB`);p?s.filtro=p:delete s.filtro,delete s.obligatorio}if(a==="dispositivo"){if(!ov.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"||!We.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 Vs,Zf,Us,Gf,Hf,Zw,ev,ov,tv,eh,rv,Js,We,oh,nv,iv,av,ot,sv,cv,Xf,Yf,rh,Kf,Bs,uv,dv,pv,Rm,Gr=m(()=>{em();nm();am();Dm();Es();Vp();E();li();Gm();ch();Cs();Ym();tf();sf();mf();bf();_f();Cf();qf();gs();Af();Tf();zf();Bf();gi();Qf();ah();Vs=["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"],Zf=["creado_el","creado_por","modificado_el","modificado_por","autonumero"],Us=["recuento","suma","minimo","maximo","ultimo","media","media_ponderada"],Gf=["igual","distinto","en","no_en","vacio","no_vacio","mayor","menor"],Hf=5;Zw=["avisar","desvincular","impedir"],ev=["companies","contacts","deals"],ov=["ttlock","shelly"],tv=["id","numero","sales_id","creado","actualizado","espacio_id","modulo_id","datos"],eh=new Set([...tv,"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"]),rv=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"]),Js=["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"],We=/^[a-z][a-z0-9_]{0,40}$/,oh=/^[a-z][a-z_]{1,30}$/,nv=/^#[0-9a-fA-F]{6}$/,iv=/^[a-z][a-z_]{0,29}$/,av=["texto","correo","telefono","codigo"],ot=(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};sv=/^sub_[a-z]{8}$/,cv=["texto","texto_largo","numero","importe","fecha","fecha_hora","booleano","seleccion","url","correo","telefono","duracion","porcentaje","valoracion","color","codigo","formula","hora","relacion","articulo","subtabla","resumen"],Xf=20,Yf=3,rh=e=>e.tipo!=="subtabla"?0:1+Math.max(0,...(e.columnas??[]).map(o=>rh(o))),Kf=["nombre","referencia","codigo","precio","iva_pct"],Bs=30;uv=[["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"]],dv=(e,o)=>uv.some(([t,n])=>t===e&&n===o),pv=/^[a-z0-9][a-z0-9-]{0,59}$/;Rm=e=>e.tipo==="busqueda"||e.tipo==="resumen"||e.tipo==="formula"||e.tipo==="subtabla"||e.tipo==="boton"||e.tipo==="qr"||e.tipo==="archivo"||Zf.includes(e.tipo)});function lh(e){let o=Mo(),t=(e==="contacts"?mv:fv).map(([n,r])=>({clave:n,etiqueta:io(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",...hv(e).has(n)?{}:{permisos:{administrador:"lectura",miembro:"lectura",lectura:"lectura"}}}));return{id:0,clave:`@${e}`,nombre:io(o,e==="contacts"?"Persona":"Empresa"),nombre_plural:io(o,e==="contacts"?"Personas":"Empresas"),descripcion:"",icono:e==="contacts"?"users":"building-2",estado:"publicado",campos:t}}var Ci,mv,fv,hv,uh=m(()=>{an();Ci=[["address","Direcci\xF3n"],["zipcode","C\xF3digo postal"],["city","Ciudad"],["country","Pa\xEDs"]],mv=[["first_name","Nombre"],["last_name","Apellidos"],["title","Cargo"],["correo","Correo"],["telefono","Tel\xE9fono"],...Ci,["background","Contexto"],["nif","Identificador fiscal"],["pais_fiscal","Pa\xEDs fiscal"]],fv=[["name","Nombre"],["phone_number","Tel\xE9fono"],["website","Web"],...Ci,["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"]],hv=e=>new Set(e==="contacts"?["first_name","last_name","title","telefono",...Ci.map(([o])=>o),"background"]:["name","phone_number","website",...Ci.map(([o])=>o),"description","persona_first_name"])});function Br(e){let o=new Map(Wr(e)?lh(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=(Hp.find(a=>a.clave===e)?.campos??[]).map(a=>({...a,...o.has(a.clave)?{etiqueta:o.get(a.clave)}:Object.hasOwn(t,a.clave)?{etiqueta:io(Mo(),t[a.clave])}:{}})),r=Wr(e)?vv(e).map(a=>({...a,etiqueta:io(Mo(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[];return[...n,...r,...e==="companies"?bv.map(a=>({...a,etiqueta:io(Mo(),a.etiqueta),editable:!1,ordenable:!1,filtrable:!1,enTabla:!1})):[]]}var Wr,gv,bv,wv,vv,ui=m(()=>{Xp();uh();an();Wr=e=>e==="contacts"||e==="companies",gv=[{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"}],bv=[{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"}],wv=[{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"}],vv=e=>[...gv.filter(o=>e==="contacts"||["nombre","direccion"].includes(o.clave)),...e==="companies"?wv:[]]});function ih(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 f=p.relacion,h;if(f.startsWith("mod_")){let b=f.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=Br(f).find(y=>y.clave===a.campo)??t?.get(`@${f}`)?.find(y=>y.clave===a.campo&&!y.archivado);if(!b&&Ee(a.campo)&&!t?.has(`@${f}`))return a;if(!b)throw i(`\xAB${a.etiqueta}\xBB: ese campo no existe en ${f}.`);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 ah=m(()=>{Dr();E();ui()});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 zm(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 Dr=m(()=>{E()});function sh(e,o){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new L(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(!$v(n))throw new L(400,"peticion_invalida",`\xAB${o}\xBB: el papel \xAB${n.slice(0,30)}\xBB no se puede restringir.`);if(!_v.includes(r))throw new L(400,"peticion_invalida",`\xAB${o}\xBB: nivel de permiso no v\xE1lido.`);t[n]=r}return Object.keys(t).length?t:void 0}var _v,Nv,$v,UL,Gs,JL,ch=m(()=>{oi();E();_v=["oculto","lectura"],Nv=["administrador","miembro","lectura"],$v=e=>Nv.includes(e)||/^p_[a-z]{1,12}$/.test(e),UL=O`coalesce(current_setting('app.extension', true), '') <> ''`,Gs=class extends Map{get(){return"no"}},JL=new Gs});function um(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"&&xv.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"&&Cv.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 xv,Cv,dm=m(()=>{E();xv=/^mod_[a-z][a-z0-9_]{0,40}$/,Cv=/^[a-z0-9][a-z0-9-]{0,59}$/});var Hs,dh=m(()=>{Hs=["nada","recientes","vistas"]});function ph(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(!Xs(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!==""&&!ji(r.filas)||!Xs(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&&Sv(p))||!ji(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||!ji(r.id_externo)||!Xs(r.cursor)||!ji(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 jv,ji,Xs,Sv,mh=m(()=>{E();jv=new Set(["texto","texto_largo","correo","telefono","codigo","numero","importe","fecha","fecha_hora","booleano","seleccion"]),ji=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),Xs=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Sv=e=>!e.archivado&&jv.has(e.tipo)});function fh(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(!Ov(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 Ov,hh=m(()=>{E();Ov=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function Si(e){return typeof e=="number"?Number.isInteger(e)&&e>=1&&e<=2147483647:typeof e=="string"&&e.length<=120&&gh.test(e)}function bh(e,o){let t=c=>gh.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),f=/^\d+$/.test(u);return p&&f?BigInt(d)>BigInt(u)?1:-1:p!==f?p?-1:1:d>u?1:-1}return a.length-s.length}var gh,Ys=m(()=>{gh=/^(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 wh(e,o){if(e===void 0)return;if(!Ks(e)||Object.keys(e).some(r=>r!=="desde"&&r!=="pasos")||!Si(e.desde)||bh(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(!Ks(r)||Object.keys(r).some(f=>!["tipo","modulo","origen","destino","conversion","equivalencias"].includes(f))||r.tipo!=="renombrar"&&r.tipo!=="convertir"&&r.tipo!=="mover"||!Zs(r.modulo)||!Zs(r.origen)||!Zs(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"||!Av.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"?!Ks(p)||!Object.keys(p).length||Object.values(p).some(f=>typeof f!="string"||!f):p!==void 0)throw i("La conversi\xF3n a selecci\xF3n necesita una tabla de equivalencias.");for(let f of new Set([c,d])){let h=`${s}:${f}`;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 Ks,Zs,Av,vh=m(()=>{E();Ys();Ks=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Zs=e=>typeof e=="string"&&/^[a-z][a-z0-9_]{0,59}$/.test(e),Av=new Set(["numero","seleccion","fecha"])});function yh(e){let o=nr(e,["version","origen","entidades"]);if(o.version!==1)throw i("Perfil relacional inv\xE1lido.");let t=Xr(o.entidades,60).map(r=>{let a=nr(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(nr(a.campos)).map(([b,y])=>(ec(b),[b,ir(y)])));if(Object.keys(s).length>100)throw i("Perfil relacional inv\xE1lido.");let c=Xr(a.referencias??[],30).map(b=>{let y=nr(b,["campo","entidad","clave","obligatoria"]);if(y.obligatoria!==void 0&&typeof y.obligatoria!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:ec(y.campo),entidad:Oi(y.entidad),clave:oc(y.clave),obligatoria:y.obligatoria===!0}}),d=a.archivos===void 0?void 0:Xr(a.archivos,20).map(b=>{let y=nr(b,["campo","columna","obligatorio"]);if(y.obligatorio!==void 0&&typeof y.obligatorio!="boolean")throw i("Perfil relacional inv\xE1lido.");return{campo:ec(y.campo),columna:ir(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(nr(a.procedencia,["autor","creado","actualizado"])).map(([b,y])=>[b,ir(y)])),f=a.responsable===void 0?void 0:oc(a.responsable),h=a.tipos===void 0?void 0:Xr(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:Oi(a.clave),...a.acl!==void 0?{acl:ir(a.acl)}:{},...d?{archivos:d}:{},destino:a.destino,...p?{procedencia:p}:{},...f?{responsable:f}:{},...h?{tipos:h}:{},...a.tiposColumna!==void 0?{tiposColumna:ir(a.tiposColumna)}:{},clave_externa:oc(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:Oi(o.origen),entidades:t}}var Oi,ec,ir,nr,Xr,oc,_h=m(()=>{E();Oi=e=>{if(typeof e!="string"||!/^[a-z][a-z0-9_]{0,60}$/.test(e))throw i("Perfil relacional inv\xE1lido.");return e},ec=e=>{let o=typeof e=="string"&&/^datos\.[a-z][a-z0-9_]{0,60}$/.test(e)?e:Oi(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},ir=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},nr=(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},Xr=(e,o)=>{if(!Array.isArray(e)||e.length>o)throw i("Perfil relacional inv\xE1lido.");return e},oc=e=>{let o=Xr(e,3).map(ir);if(!o.length||new Set(o).size!==o.length)throw i("Perfil relacional inv\xE1lido.");return o}});function Nh(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:yh(n.perfil)}})}var $h=m(()=>{E();_h()});function xh(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 Ch=m(()=>{E()});function jh(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)||!Us.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.");Qr(o.filtro,"Resumen")}var Sh=m(()=>{E();Gr()});function Oh(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 Ah=m(()=>{E()});var Eh,qh=m(()=>{Eh=/^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(!Po(t)||Object.keys(t).some(r=>!["fuente","filtro","campos"].includes(r))||typeof t.fuente!="string"||!qv.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&&(!Po(t.filtro)||JSON.stringify(t.filtro).length>4e3))throw i("Filtro de origen no v\xE1lido.");if(!Po(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(!Ev.test(r)||["id","objeto"].includes(r)||!Po(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&&(!Po(a.condicion)||JSON.stringify(a.condicion).length>4e3)||a.conversiones!==void 0&&(!Po(a.conversiones)||!Array.isArray(a.alternativas)||Object.entries(a.conversiones).some(([c,d])=>!a.alternativas.includes(c)||!Po(d)||Object.keys(d).length>100||Object.values(d).some(u=>typeof u!="string")))||a.permiso!==void 0&&(typeof a.permiso!="string"||!Eh.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&&(!Po(a.opciones)||Object.keys(a.opciones).length>100||Object.values(a.opciones).some(c=>typeof c!="string"))||a.equivalencias!==void 0&&(!Po(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&&jh(a.resumen);let s=a.formula===void 0?void 0:xh(a.formula);if(a.casos!==void 0)Oh(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 Po,Ev,qv,Ai=m(()=>{Ch();Sh();Ah();E();qh();Po=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ev=/^[a-z][a-z0-9_]{0,40}$/,qv=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{0,40})$/});function Rh(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 kh=m(()=>{E()});function Th(e){let o=xe(e,"definici\xF3n");Be(o,["titulo","fuente","origenes","metrica","agrupar","dividir","filtro","periodo","grafico","top","comparar","meta"],"definici\xF3n");let t=Ie(o.fuente,"fuente",60),n=ar(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!rc.includes(t)&&!/^mod_(?!sub_)[a-z][a-z0-9_]{0,40}$/.test(t))throw i("\xABfuente\xBB no v\xE1lida.");let r=xe(o.metrica,"metrica");Be(r,["tipo","campo","por","filtro_a","filtro_b"],"metrica");let a=to(r.tipo,tc,"metrica.tipo"),s={tipo:a,...r.campo!==void 0?{campo:Ie(r.campo,"metrica.campo",60)}:{},...r.por!==void 0?{por:Ie(r.por,"metrica.por",60)}:{},...r.filtro_a!==void 0&&r.filtro_a!==null?{filtro_a:xe(r.filtro_a,"metrica.filtro_a")}:{},...r.filtro_b!==void 0&&r.filtro_b!==null?{filtro_b:xe(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 w=xe(o.agrupar,"agrupar");Be(w,["campo","paso"],"agrupar"),c={campo:Ie(w.campo,"agrupar.campo",60),...w.paso!==void 0?{paso:to(w.paso,sr,"agrupar.paso")}:{}}}let d;if(o.dividir!==void 0&&o.dividir!==null){let w=xe(o.dividir,"dividir");Be(w,["campo","paso"],"dividir"),d={campo:Ie(w.campo,"dividir.campo",60),...w.paso!==void 0?{paso:to(w.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?nc(o.periodo):void 0,f=to(o.grafico,Rv,"grafico"),h=["numero","medidor","numero_tendencia"],b=["barras","barras_horizontales","lineas","area","dona","tabla","embudo","tarta","radar","dispersion"],y=["barras_apiladas","barras_agrupadas","varias_lineas","tabla_dinamica","mapa_calor","combinado"];if(h.includes(f)){if(c)throw i("Un n\xFAmero no se agrupa.");if(d)throw i("Un n\xFAmero no se divide.");if(f==="medidor"&&u===void 0)throw i("El medidor necesita una \xABmeta\xBB num\xE9rica.");if(f==="numero_tendencia"&&(!p||!o.comparar))throw i("\xABnumero_tendencia\xBB necesita un periodo con comparaci\xF3n.")}else if(b.includes(f)){if(!c)throw i("Ese gr\xE1fico necesita \xABagrupar\xBB.");if(d)throw i("Ese gr\xE1fico no admite \xABdividir por\xBB.")}else if(y.includes(f)){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(o.top!==void 0&&(!Number.isSafeInteger(o.top)||o.top<1||o.top>Ph))throw i(`\xABtop\xBB: de 1 a ${Ph}.`);if(o.comparar!==void 0&&typeof o.comparar!="boolean")throw i("\xABcomparar\xBB: s\xED o no.");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(o.comparar&&p?.preset)throw i("\xABpreset\xBB no se compara (todav\xEDa no se ha acabado).");let v=o.filtro===void 0||o.filtro===null?void 0:xe(o.filtro,"filtro");if(v&&JSON.stringify(v).length>4e3)throw i("\xABfiltro\xBB demasiado grande.");return{titulo:Ie(o.titulo??"","titulo"),fuente:t,...n?{origenes:n}:{},metrica:s,...c?{agrupar:c}:{},...d?{dividir:d}:{},...u!==void 0?{meta:u}:{},...v?{filtro:v}:{},...p?{periodo:p}:{},grafico:f,...o.top!==void 0?{top:o.top}:{},...o.comparar?{comparar:!0}:{}}}function nc(e){let o=xe(e,"periodo");Be(o,["campo","ultimos","proximos","preset","desde","hasta"],"periodo");let t={campo:Ie(o.campo,"periodo.campo",60)};if(o.preset!==void 0&&(t.preset=to(o.preset,kv,"periodo.preset")),o.ultimos!==void 0){let r=xe(o.ultimos,"periodo.ultimos");if(Be(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:to(r.unidad,sr,"periodo.ultimos.unidad")}}for(let r of["desde","hasta"])if(o[r]!==void 0){if(typeof o[r]!="string"||!Pv.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=xe(o.proximos,"periodo.proximos");if(Be(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:to(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 tc,Rv,sr,rc,kv,Ph,Pv,xe,Be,to,Ie,ic=m(()=>{Ai();E();tc=["recuento","suma","media","min","max","minimo","maximo","mediana","porcentaje_total","acumulado","tasa_conversion","media_por","valor_medio_por"],Rv=["numero","barras","lineas","dona","tabla","barras_horizontales","barras_apiladas","barras_agrupadas","area","varias_lineas","embudo","medidor","numero_tendencia","tabla_dinamica","mapa_calor","tarta","radar","dispersion","combinado"],sr=["dia","semana","mes","anio"],rc=["companies","contacts","deals"],kv=["hoy","semana","mes","trimestre","anio"],Ph=50,Pv=/^\d{4}-\d{2}-\d{2}$/,xe=(e,o)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw i(`\xAB${o}\xBB tiene que ser un objeto.`);return e},Be=(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.`)},to=(e,o,t)=>{if(typeof e!="string"||!o.includes(e))throw i(`\xAB${t}\xBB no v\xE1lido.`);return e},Ie=(e,o,t=80)=>{if(typeof e!="string"||e.length>t)throw i(`\xAB${o}\xBB no v\xE1lido.`);return e}});function zh(e,o){if(e===null)return null;if(!To(e))throw i("La disposici\xF3n no es v\xE1lida.");if(!Lv.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(!To(e.zonas))throw Dh();let t=e.zonas,n=To(e.widgets)?e.widgets:{};for(let d of Object.keys(t))if(!Mh.includes(d))throw i("Zona no v\xE1lida.");let r={},a=new Set;for(let d of Mh){let u=t[d]??[];if(!Array.isArray(u))throw i("Zona no v\xE1lida.");r[d]=u.map(p=>{if(typeof p!="string"||p!==ac&&!Iv.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(ac))throw Dh();if(r.arriba.length>Lh)throw i(`Arriba caben como mucho ${Lh} bloques.`);let s={};for(let[d,u]of Object.entries(n)){if(!a.has(d))continue;if(!To(u))throw i("Widget no v\xE1lido.");let p=Th(u.definicion);if(u.via!==void 0&&(typeof u.via!="string"||!Dv.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!==ac&&!s[d])throw i("Falta la definici\xF3n de un widget.");if(Object.keys(s).length>Ih)throw i(`Como mucho ${Ih} 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 zv(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 Fh(e){if(!To(e))throw i("La vista no es v\xE1lida.");let o=To(e.pref)?Object.fromEntries(Object.entries(e.pref).filter(([d])=>Tv.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&&!Mv.has(String(o.vista)))throw i("El tipo de vista no es v\xE1lido.");let t=To(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(To(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)||!To(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=zv(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 Tv,Mv,Mh,ac,Iv,Ih,Lh,Lv,Dv,Dh,To,Wh=m(()=>{Ai();E();ic();Tv=new Set(["vistaOrigen","vista","visibles","orden","anchos","fijadas","calculos","agrupar","grupo","vistas","separar"]),Mv=new Set(["tabla","lista","kanban","calendario","galeria","linea","mapa"]),Mh=["arriba","izquierda","centro","derecha","abajo"],ac="tabla",Iv=/^w_[a-z0-9]{1,24}$/,Ih=24,Lh=6,Lv=/^(contacts|companies|deals|mod_(?!sub_)[a-z][a-z0-9_]{1,40})$/,Dv=/^[a-z][a-z0-9_]{0,59}$/,Dh=()=>new L(400,"tabla_obligatoria","La tabla no se puede quitar de la vista: mu\xE9vela, pero d\xE9jala.");To=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function Bh(e){let o=new Set,t=n=>{typeof n=="string"&&n.startsWith("mod_")&&o.add(n.slice(4))};if(sc(e.personas)&&t(e.personas.modulo),Array.isArray(e.secciones)){for(let n of e.secciones)if(sc(n)&&(t(n.modulo),Array.isArray(n.camino)))for(let r of n.camino)sc(r)&&t(r.modulo)}return o}var sc,Vh=m(()=>{sc=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});function Bv(e){if(typeof e!="string"||!Wv.test(e))throw i("\xABrecurso\xBB: contacts, companies, deals o mod_<clave>.");return e}function Vv(e){if(!Fv.includes(e))throw i("\xABcanal\xBB: whatsapp o correo.");return e}function Uh(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=Bv(t.recurso);if(t.tipoContacto!==void 0&&t.tipoContacto!==null&&(!Wr(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=Vv(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 Fv,Ei,Wv,cc,lc=m(()=>{ui();E();Fv=["whatsapp","correo"],Ei=50,Wv=/^(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 Gh(e){let o=xe(e,"informe");Be(o,["fuente","origenes","filtro","periodo","columnas","agrupar","agregados","orden"],"informe");let t=Ie(o.fuente,"fuente",60),n=ar(o.origenes);if(t==="combinada"!=!!n)throw i("La fuente combinada necesita sus or\xEDgenes.");if(t!=="combinada"&&!rc.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=xe(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=nc(o.periodo)),o.columnas!==void 0&&o.columnas!==null){if(!Array.isArray(o.columnas)||o.columnas.length>Jh)throw i(`\xABcolumnas\xBB: una lista de hasta ${Jh}.`);r.columnas=[...new Set(o.columnas.map((a,s)=>Ie(a,`columnas[${s}]`,60)))]}if(o.agrupar!==void 0&&o.agrupar!==null){let a=xe(o.agrupar,"agrupar");Be(a,["campo","paso"],"agrupar"),r.agrupar={campo:Ie(a.campo,"agrupar.campo",60),...a.paso!==void 0?{paso:to(a.paso,sr,"agrupar.paso")}:{}}}if(o.agregados!==void 0&&o.agregados!==null){if(!Array.isArray(o.agregados)||o.agregados.length>Qh)throw i(`\xABagregados\xBB: una lista de hasta ${Qh}.`);r.agregados=o.agregados.map((a,s)=>{let c=xe(a,`agregados[${s}]`);Be(c,["tipo","campo"],`agregados[${s}]`);let d=to(c.tipo,tc,`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:Ie(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=xe(o.orden,"orden");Be(a,["por","sentido"],"orden"),r.orden={por:Ie(a.por,"orden.por",60),sentido:to(a.sentido??"asc",["asc","desc"],"orden.sentido")}}return r}var Jh,Qh,Hh=m(()=>{Ai();E();ic();Jh=30,Qh=6});var uc,Uv,Xh,Yh=m(()=>{uc=[{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"}],Uv=e=>`pix.agente_${e}`,Xh=e=>uc.some(o=>Uv(o.clave)===e)});var Kh,Zh=m(()=>{Kh=["contacts","companies","deals","tareas","proyectos"]});function eg(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 og(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:eg(n.nombre,"pix.personalidad.nombre",Qv),instrucciones:eg(n.instrucciones,"pix.personalidad.instrucciones",Jv)}}}var Jv,Qv,tg=m(()=>{E();Jv=2e3,Qv=60});function rg(e,o){if(e===void 0)return[];if(!Array.isArray(e)||e.length>Yr)throw i(`\xABinformes\xBB: una lista de hasta ${Yr}.`);let t=new Set;return e.map((n,r)=>{if(!Gv(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=Gh(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 Yr,Gv,dc=m(()=>{E();Hh();Yr=30,Gv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var ng,bo,cr,lr,ee,pc,ur,hz,Hv,qi,Xv,Yv,gz,bz,ig=m(()=>{Yh();ng={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"]},bo=["si","no","suyos"],cr=["si","no","suyos","equipo","jerarquia"],lr=["si","no","suyos","jerarquia"],ee=["si","no"],pc=(e,o,t=!0)=>[{clave:`${e}.ver`,descripcion:`Ver ${o}`,valores:lr},{clave:`${e}.crear`,descripcion:`Dar de alta ${o}`,valores:lr},{clave:`${e}.editar`,descripcion:`Editar ${o}`,valores:lr},{clave:`${e}.reasignar`,descripcion:`Cambiar el responsable de ${o}`,valores:lr},...t?[{clave:`${e}.estado`,descripcion:`Cambiar el estado de ${o}`,valores:lr}]:[],{clave:`${e}.descargar`,descripcion:`Bajar los ficheros de ${o}`,valores:ee},{clave:`${e}.borrar`,descripcion:`Borrar ${o}`,valores:lr},{clave:`${e}.exportar`,descripcion:`Exportar ${o}`,valores:bo},{clave:`${e}.importar`,descripcion:`Importar ${o} desde una hoja`,valores:ee}],ur=[...pc("contactos","contactos"),...pc("empresas","empresas",!1),...pc("oportunidades","oportunidades"),{clave:"proyectos.ver",descripcion:"Ver proyectos",valores:cr},{clave:"proyectos.editar",descripcion:"Editar los datos del proyecto",valores:cr},{clave:"proyectos.borrar",descripcion:"Borrar proyectos",valores:cr},{clave:"proyectos.exportar",descripcion:"Exportar proyectos",valores:bo},{clave:"proyectos.crear",descripcion:"Crear proyectos",valores:ee},{clave:"proyectos.gestionar",descripcion:"Cambiar el estado, el responsable, los participantes, las columnas y los ajustes de los proyectos, y gestionar plantillas",valores:ee},{clave:"tareas.ver",descripcion:"Ver tareas",valores:cr},{clave:"tareas.crear",descripcion:"Crear tareas",valores:ee},{clave:"tareas.editar",descripcion:"Editar y completar tareas",valores:cr},{clave:"tareas.borrar",descripcion:"Borrar tareas",valores:cr},{clave:"tareas.exportar",descripcion:"Exportar tareas visibles",valores:bo},{clave:"notas.ver",descripcion:"Ver notas",valores:bo},{clave:"notas.editar",descripcion:"Escribir, editar y borrar notas",valores:bo},{clave:"adjuntos.ver",descripcion:"Ver y descargar adjuntos",valores:bo},{clave:"adjuntos.subir",descripcion:"Subir adjuntos",valores:bo},{clave:"miembros.gestionar",descripcion:"Invitar, cambiar el papel y desactivar miembros",valores:ee},{clave:"conectores.accionar",descripcion:"Ejecutar acciones f\xEDsicas de conectores",valores:ee},{clave:"configuracion.gestionar",descripcion:"Cambiar la configuraci\xF3n del espacio y los permisos",valores:ee},{clave:"formularios.gestionar",descripcion:"Crear, editar y borrar formularios (y sus respuestas)",valores:ee},{clave:"formularios.ver_respuestas",descripcion:"Ver las respuestas de los formularios",valores:bo},{clave:"modulos.configurar",descripcion:"Dise\xF1ar, publicar y archivar m\xF3dulos",valores:ee},{clave:"paneles.ver",descripcion:"Ver los paneles de m\xE9tricas",valores:ee},{clave:"paneles.editar",descripcion:"Crear, cambiar y borrar paneles de m\xE9tricas",valores:ee},{clave:"paneles.compartir",descripcion:"Compartir paneles con el equipo y cambiar o borrar los de equipo",valores:ee},{clave:"automatizaciones.gestionar",descripcion:"Crear y cambiar automatizaciones, y ver sus ejecuciones",valores:ee},{clave:"campanas.gestionar",descripcion:"Crear y enviar campa\xF1as de correo, y gestionar consentimientos y supresiones",valores:ee},{clave:"agenda.ver",descripcion:"Ver las citas de la agenda",valores:bo},{clave:"agenda.editar",descripcion:"Crear, mover y cancelar citas",valores:bo},{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:ee},{clave:"analisis.ver",descripcion:"Usar An\xE1lisis: informes de lo que ya puede ver",valores:ee},{clave:"analisis.compartir",descripcion:"Compartir informes con el equipo y cambiar o borrar los de equipo",valores:ee},{clave:"secretos.ver",descripcion:"Ver los campos secretos (cada vez queda registrado qui\xE9n lo vio)",valores:ee},{clave:"liquidaciones.gestionar",descripcion:"Generar, aprobar, cerrar, pagar y reabrir liquidaciones de comisiones",valores:ee},{clave:"portales.gestionar",descripcion:"Configurar los portales, invitar a ellos y revocar el acceso",valores:ee},{clave:"auditoria.ver",descripcion:"Ver la auditor\xEDa del espacio (qui\xE9n hizo qu\xE9 y cu\xE1ndo)",valores:ee},{clave:"publico.compartir",descripcion:"Compartir la p\xE1gina p\xFAblica de un registro (un enlace que caduca)",valores:ee},{clave:"pix.memoria_espacio",descripcion:"Escribir lo que Pix recuerda para todo el espacio",valores:ee},...uc.map(e=>({clave:`pix.agente_${e.clave}`,descripcion:`Usar a ${e.nombre} (${e.puesto}) del Equipo IA`,valores:ee}))],hz=new Set(ur.map(e=>e.clave)),Hv=e=>/\.(exportar|importar)$/.test(e),qi=e=>Object.fromEntries(ur.map(o=>[o.clave,e(o)])),Xv=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"||Xh(e.clave),Yv={titular:qi(()=>"si"),administrador:qi(e=>e.clave==="conectores.accionar"?"no":"si"),miembro:qi(e=>Xv(e)||e.clave==="conectores.accionar"||e.clave==="secretos.ver"||Hv(e.clave)?"no":"si"),lectura:qi(e=>e.clave.endsWith(".ver")&&e.clave!=="secretos.ver"&&e.clave!=="auditoria.ver"||e.clave.endsWith(".descargar")?"si":e.clave.endsWith(".reasignar")?"suyos":"no")},gz=ur.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")&&Yv.miembro[e.clave]!=="no").map(e=>e.clave),bz=ur.filter(e=>/^((contactos|empresas|oportunidades|proyectos|tareas|notas|adjuntos)\.|agenda\.(ver|editar)$)/.test(e.clave)&&e.valores.includes("suyos")).map(e=>e.clave)});function cg(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>ag)throw i(`\xAB${r.slice(0,20)}\u2026\xBB: como mucho ${ag} caracteres.`);if(!mc(r))throw i(`\xAB${r}\xBB no es una palabra.`);t.has(mc(r))||(t.add(mc(r)),o.push(r))}}if(o.length>fc)throw i(`Como mucho ${fc} sin\xF3nimos por m\xF3dulo.`);return o}var sg,fc,ag,mc,lg=m(()=>{E();sg=["contacts","companies","deals","tasks"],fc=20,ag=40,mc=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9ñ\s-]/g," ").replace(/\s+/g," ").trim()});function ey(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=wo(o.nombre,"nombre de la conexi\xF3n",80,!1)||o.conector;return{clave:o.conector,nombre:t,tipo:"conector",conector:o.conector}})}function ty(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=ey(e.filter(o)),n=fh(e.filter(s=>!o(s))),r=0,a=0;return e.map(s=>o(s)?t[r++]:n[a++])}function ny(e){if(e==null)return null;if(!re(e))throw i("\xABagenda\xBB: un objeto.");Ve(e,["tipos"],"Agenda");let o=new Set,t=ro(e.tipos,ry,"agenda.tipos").map((n,r)=>{let a=`Tipo de cita ${r+1}`;if(!re(n))throw i(`${a}: un objeto.`);Ve(n,["nombre","duracion","color","reserva_publica","quien_atiende","cambio_horas","crear_persona"],a);let s=wo(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 iy(e,o){return ro(e,bc,"vistasTabla").map((t,n)=>{let r=`Vista de tabla ${n+1}`;if(!re(t))throw i(`${r}: un objeto.`);Ve(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=zh(t.disposicion??null,a),c=Rh(a,t.tipoContacto);return{objeto:a,...c?{tipoContacto:c}:{},nombre:wo(t.nombre,`nombre de la ${r.toLowerCase()}`,60),...t.config!==void 0?{config:Fh(t.config)}:{},disposicion:s}})}function ly(e,o,t=[]){let n=new Set;return ro(e,vc,"papeles").map((r,a)=>{let s=`Papel ${a+1}`;if(!re(r))throw i(`${s}: un objeto.`);Ve(r,["nombre","base","permisos","ocultos","lectura","identidades"],s);let c=wo(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"||!sy.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=cy.exec(b),w=ur.find(C=>C.clave===b);if(v?!o.includes(v[1]):!w)throw i(`${s}: permiso desconocido \xAB${b.slice(0,60)}\xBB.`);let _=w?w.valores:ng[v[2]];if(typeof y!="string"||!_.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"?ay.exec(v):null,_=w?t.find(C=>C.clave===w[1]):void 0;if(!w||!_||!_.campos.some(C=>C.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"),f=u(r.lectura,"lectura"),h=Yp(r.identidades);return{nombre:c,base:r.base,...Object.keys(d).length?{permisos:d}:{},...p.length?{ocultos:p}:{},...f.length?{lectura:f}:{},...h.length?{identidades:h}:{}}})}function hc(e,o=0){if(o>30)throw i("La soluci\xF3n anida demasiado.");if(Array.isArray(e))return e.forEach(t=>hc(t,o+1));if(re(e))for(let t of Object.keys(e)){if(Zv.has(t))throw i(`Clave no admitida \xAB${t}\xBB.`);hc(e[t],o+1)}}function Ve(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 wo(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 Kr(e,o){if(typeof e=="string"){if(e.length>ki)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>ki)throw i("La soluci\xF3n pasa de 1 MB.");if(!re(e))throw i("La soluci\xF3n tiene que ser un objeto.");hc(e),Ve(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(Ve(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(!Si(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 A=wh(g.migracion,g.version);t={...A?{migracion:A}:{},id:g.id,version:g.version,sector:g.sector,...x?{dependencias:x}:{},...g.nivel==="basica"?{nivel:"basica"}:{}}}if(e.formato!==qt)throw i(`No es una soluci\xF3n (formato \xAB${qt}\xBB).`);if(!Number.isInteger(e.version)||e.version<1)throw i("\xABversion\xBB: un entero.");if(e.version>dr)throw i("La soluci\xF3n es de una versi\xF3n m\xE1s nueva del CRM.");let n=wo(e.icono,"icono",40,!1)||"boxes";if(!ug.test(n))throw i("\xABicono\xBB: un icono de lucide.");if(!Array.isArray(e.modulos)||e.modulos.length<1||e.modulos.length>Ri)throw i(`Una soluci\xF3n lleva de 1 a ${Ri} 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],Qs(g,s)])]),d=e.modulos.map(g=>{let x=nh(g,{topeCampos:o.topeCampos,modulosDelEspacio:s,camposRelacion:c}),A=re(g)?g.sin_coste:void 0;if(A!==void 0&&A!==!0)throw i(`\xAB${x.nombre_plural}\xBB: \xABsin_coste\xBB solo puede ser true.`);return A===!0?{...x,sin_coste:!0}:x}),u=ro(e.paneles,gc,"paneles").map((g,x)=>{if(!re(g))throw i(`Panel ${x+1}: un objeto.`);if(Ve(g,["nombre","icono","widgets"],`Panel ${x+1}`),!Array.isArray(g.widgets)||g.widgets.length>20)throw i(`Panel ${x+1}: hasta 20 widgets.`);let A=wo(g.icono,"icono",40,!1);if(A&&!ug.test(A))throw i(`Panel ${x+1}: icono no v\xE1lido.`);return{nombre:wo(g.nombre,"nombre del panel",60),...A?{icono:A}:{},widgets:g.widgets}}),p=ro(e.automatizaciones,wc,"automatizaciones").map((g,x)=>{if(!re(g))throw i(`Automatizaci\xF3n ${x+1}: un objeto.`);if(Ve(g,["nombre","definicion"],`Automatizaci\xF3n ${x+1}`),!re(g.definicion))throw i(`Automatizaci\xF3n ${x+1}: falta su definici\xF3n.`);return{nombre:wo(g.nombre,"nombre de la automatizaci\xF3n",80),definicion:g.definicion}}),f=ro(e.senales,20,"senales").map((g,x)=>{if(!re(g))throw i(`Se\xF1al ${x+1}: un objeto.`);Ve(g,["fuente","regla"],`Se\xF1al ${x+1}`);let A=typeof g.fuente=="string"?g.fuente:"";if(!(A.startsWith("mod_")?r.includes(A.slice(4)):Kh.includes(A)))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:A,regla:g.regla}}),h=og(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=ro(e.mensajes,Ei,"mensajes").map((g,x)=>{let A=Uh(g,`Mensaje ${x+1}`);if(A.recurso.startsWith("mod_")&&!r.includes(A.recurso.slice(4)))throw i(`Mensaje ${x+1}: de un m\xF3dulo que no est\xE1 en la soluci\xF3n.`);return A}),v=ly(e.papeles,r,d),w=dy(e.portales,r),_=ny(e.agenda),C=iy(e.vistasTabla,r),S=ro(e.separadores??[],yc,"separadores").map((g,x)=>{if(!re(g))throw i(`Separador ${x+1}: un objeto.`);if(Ve(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}}),P=ro(e.menu??[],100,"menu").map((g,x)=>{if(!re(g))throw i(`Men\xFA ${x+1}: un objeto.`);if(Ve(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"||!Hs.includes(g.despliega)))throw i(`Men\xFA ${x+1}: \xABdespliega\xBB, ${Hs.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 P)if(g.padre&&(P.some(x=>x.entrada===g.padre&&x.padre)||P.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(P.map(g=>g.entrada)).size!==P.length)throw i("Men\xFA: cada m\xF3dulo, una vez.");let Z={};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 A=new Set;Z[g]=ro(x,Pi,`ejemplos de ${g}`).map((k,J)=>{if(!re(k))throw i(`Ejemplo ${J+1} de ${g}: un objeto.`);if(k._ref!==void 0&&!Number.isSafeInteger(k._ref))throw i(`Ejemplo ${J+1} de ${g}: \xAB_ref\xBB es un entero.`);if(typeof k._ref=="number"){if(A.has(k._ref))throw i(`\xAB${g}\xBB: referencia de ejemplo repetida.`);A.add(k._ref)}if((d.find(G=>G.clave===g)?.campos??[]).filter(G=>G.tipo==="secreto").map(G=>G.clave).some(G=>G in k))throw i(`Ejemplo ${J+1} de ${g}: un ejemplo no lleva el valor de un campo secreto.`);return k})}}let we=ty(e.conexiones),$=ph(e.fuentesExternas,d,we.filter(oy));if($.some(g=>g.modo==="vivo"&&Z[g.modulo]?.length))throw i("Un m\xF3dulo con fuente en vivo no puede tener ejemplos.");let M=Nh(e.perfilesImportacion);if(M.some(g=>g.perfil.entidades.some(x=>x.destino.startsWith("mod_")&&!d.some(A=>`mod_${A.clave}`===x.destino))))throw i("El perfil apunta fuera de la soluci\xF3n.");return{formato:qt,...M.length?{perfilesImportacion:M}:{},...we.length?{conexiones:we}:{},...$.length?{fuentesExternas:$}:{},version:e.version,...t?{plantilla:t}:{},nombre:wo(e.nombre,"nombre",80),descripcion:wo(e.descripcion,"descripcion",500,!1),icono:n,modulos:d,paneles:u,automatizaciones:p,ejemplos:Z,...f.length?{senales:f}:{},...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}:{},..._?{agenda:_}:{},...C.length?{vistasTabla:C}:{},...S.length?{separadores:S}:{},...P.length?{menu:P}:{},...uy(e.sinonimos,d.map(g=>g.clave))}}function uy(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=cg(r);a.length&&(t[n]=a)}return Object.keys(t).length?{sinonimos:t}:{}}function dy(e,o){return ro(e,_c,"portales").map((t,n)=>{let r=`Portal ${n+1}`;if(!re(t))throw i(`${r}: un objeto.`);Ve(t,["clave","nombre","activo","personas","secciones","textos","marca"],r);let a=[...Bh(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 ro(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 qt,dr,Ri,gc,bc,wc,Pi,ki,ug,Zv,oy,ry,vc,ay,sy,cy,re,yc,_c,Nc=m(()=>{mh();hh();vh();Ys();$h();Kp();Vh();kh();lc();E();Zh();tg();dc();Gr();dh();ig();Wh();lg();qt="forgenex.solucion",dr=2,Ri=30,gc=10,bc=20,wc=40,Pi=50,ki=1e6,ug=/^[a-z0-9-]{1,40}$/,Zv=new Set(["__proto__","constructor","prototype"]);oy=e=>e.tipo!=="conector";ry=10;vc=10,ay=/^mod_([a-z][a-z0-9_]{0,40})\.([a-z][a-z0-9_]{0,40})$/,sy=["administrador","miembro","lectura"],cy=/^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);yc=20,_c=10});function pg(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 L(422,"build_app",`${o}${t?`:${t}`:""}: ${n}`,!1,{errores:e})}var mg=m(()=>{E()});import{inflateRawSync as py}from"node:zlib";function my(e){let o=Buffer.from(e.buffer,e.byteOffset,e.byteLength);if(o.length>$c)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>hg)throw i(`El paquete trae m\xE1s de ${hg} 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),f=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 _=o.readUInt32LE(c+42);if(c+46+b+y+v>t)throw i("El .zip est\xE1 da\xF1ado.");let C=o.subarray(c+46,c+46+b),S=C.toString("utf8");if(c+=46+b+y+v,!S.endsWith("/")){if(!S||S.includes("\\")||S.startsWith("/")||S.split("/").some(P=>P===".."||P==="."||P==="")||/[\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>fg)throw i(`\xAB${S}\xBB pasa de 2 MB.`);if(_+30>o.length||o.readUInt32LE(_)!==67324752)throw i("El .zip est\xE1 da\xF1ado.");let P=o.readUInt16LE(_+26),Z=_+30+P+o.readUInt16LE(_+28);if(Z>r||Z+f>r||o.readUInt16LE(_+6)!==u||o.readUInt16LE(_+8)!==p||!o.subarray(_+30,_+30+P).equals(C))throw i("El .zip est\xE1 da\xF1ado.");let we=o.subarray(Z,Z+f);if(we.length!==f)throw i("El .zip est\xE1 da\xF1ado.");let $;if(p===0)$=we;else if(p===8)try{$=py(we,{maxOutputLength:fg})}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 pr(e){let o=new Map,t=0;for(let[n,r]of my(e)){let a=r();if(t+=a.length,t>fy)throw i("Los ficheros del paquete pasan de 10 MB al descomprimirlos.");o.set(n,a)}return o}var $c,fg,hg,fy,Ti=m(()=>{E();$c=5*1024*1024,fg=2*1024*1024,hg=500;fy=10*1024*1024});import{createHash as gg,createPublicKey as hy,sign as gy,verify as rF}from"node:crypto";function by(e){let o=hy(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:gg("sha256").update(t).digest("hex")}}function wy(e){return Buffer.from(JSON.stringify(["forgenex.fgx.v1",[...e].filter(([o])=>o!==Zr).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>[o,gg("sha256").update(t).digest("hex")])]))}function bg(e,o,t){let{id:n}=by(t);return Buffer.from(JSON.stringify({formato:"forgenex.firma",version:1,clave:n,firma:gy(null,wy(e),o).toString("base64")}))}var Zr,xc=m(()=>{E();Zr="firma.json"});function Cc(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 f=Buffer.alloc(30),h=Buffer.alloc(46);f.writeUInt32LE(67324752),f.writeUInt16LE(20,4),f.writeUInt16LE(2048,6),f.writeUInt32LE(p,14),f.writeUInt32LE(d.length,18),f.writeUInt32LE(d.length,22),f.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(f,u,d),n.push(h,u),r+=f.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 wg=m(()=>{});import{existsSync as vy,copyFileSync as en,mkdirSync as jc,readFileSync as on,readdirSync as tn,realpathSync as vg,writeFileSync as yg}from"node:fs";import{dirname as yy,join as W,resolve as _y,sep as Ny}from"node:path";import{fileURLToPath as $y}from"node:url";import{createRequire as Mi}from"node:module";function _g(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"].includes(o))throw new Error("Plantilla: html, react o archivos.");let n=W(t,e);jc(n);for(let c of["interfaz","funciones"])jc(W(n,c));let r=(c,d)=>yg(W(n,c),typeof d=="string"?d:JSON.stringify(d,null,2)+`
|
|
22
|
-
|
|
23
|
-
`),r(".
|
|
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/
|
|
24
37
|
*.fgx
|
|
25
38
|
*.pem
|
|
26
39
|
.keys/
|
|
27
|
-
`),
|
|
40
|
+
`),Fe(n),n}r("extension.json",{formato:"forgenex.extension",formato_version:1,id:`com.ejemplo.${e}`,nombre:e,version:"1.0.0",autor:{nombre:"Mi empresa"},solucion:"solucion.json",permisos:{modulos:{[a]:["ver","crear","editar"],contactos:["ver"],empresas:["ver"]},almacen:!0},montajes:[{id:"pagina",punto:"pagina",entrada:"interfaz/index.html",titulo:e}],funciones:[{nombre:"resumir",entrada:"funciones/resumir.js",disparador:{tipo:"webhook"}}]}),r("solucion.json",{formato:"forgenex.solucion",version:2,nombre:e,plantilla:{id:a,version:1,sector:"general"},modulos:[{clave:a,nombre:"Encargo",nombre_plural:"Encargos",icono:"clipboard-list",campos:[{clave:"titulo",etiqueta:"T\xEDtulo",tipo:"texto",obligatorio:!0,enTabla:!0},{clave:"persona",etiqueta:"Persona",tipo:"relacion",relacion:"contacts",enTabla:!0},{clave:"empresa",etiqueta:"Empresa",tipo:"relacion",relacion:"companies",enTabla:!0}]}]}),r("funciones/resumir.js",`export default async function (entrada) {
|
|
28
41
|
const resumen = { mensaje: String(entrada.cuerpo?.mensaje ?? "Hola"), total: 1 };
|
|
29
42
|
await crm.almacen.guardar("ultimo_resumen", resumen);
|
|
30
43
|
return resumen;
|
|
31
44
|
}
|
|
32
|
-
`)
|
|
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";
|
|
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 } } } });
|
|
35
67
|
`)),r(".gitignore",`node_modules/
|
|
36
68
|
*.fgx
|
|
37
69
|
*.pem
|
|
38
70
|
.keys/
|
|
39
|
-
`),
|
|
40
|
-
`)+[...u.matchAll(/\sstyle\s*=\s*"([^"]*)"/gi)].map(
|
|
41
|
-
`);if(p.trim()){s=!0;for(let[f,h]of Iy(My(p))){let b=f.trim().replace(/\s+/g," "),y=null,v=null;for(let w of h.matchAll(/(?:^|;)\s*(color|background-color|background)\s*:\s*([^;]+)/gi)){let _=Ty(w[2]);_.tema&&(a=!0),w[1].toLowerCase()==="color"?y=_:v=_,!_.tema&&!_.neutro&&_.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=Py(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."),[Le("forja","Forja: colores del tema",t,n,c?"Toma los colores del tema del CRM.":"No trae interfaz."),Le("contraste","Contraste del texto (\u2265 4,5:1)",r,[],"Los colores fijos que se pueden medir tienen contraste suficiente.")]}function no(e,o){for(let t=0;t<3;t++)if((e[t]??0)!==o[t])return(e[t]??0)<o[t];return!1}function Wy(e,o,t){let n=[],r=new Set,a=(c,d,u)=>{let p=c.toLowerCase().replace(/\.js$/,"");r.add(`${p} ${d}`);let f=d.split(".").map(Number);for(let h of zy)h.nombre.test(p)&&h.malas(f)&&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(Fy))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 Le("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 By(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 Le("codigo","C\xF3digo para la revisi\xF3n humana",[],o,"Nada que marcar.")}function Rc(e){let o=[...e.recursos.keys()].sort(),t=o.filter(p=>xy.test(p)).map(p=>[p,e.recursos.get(p).toString("utf8")]),{red:n,usaRed:r}=Ry(e.ext,t),a=r||!!e.ext.conexiones?.length||e.ext.servidor!==null,s=By(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,f])=>/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|sendBeacon|importScripts)\b|\bimport\s*\(/.test(f)?[`${p} intenta usar una conexi\xF3n fuera del puente del CRM.`]:[]),...n.estado==="aviso"?n.detalles:[]]:[],d=[Le("esquema","Manifiesto y soluci\xF3n v\xE1lidos",[],[],"El manifiesto y su soluci\xF3n pasan el validador del CRM."),e.dePix?Le("firma","Montada por el CRM",[],[],"La ha montado el CRM en este espacio: no viaja a otros ni a la tienda."):Le("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."),Le("tamano","Tama\xF1o",e.bytes>$c?["El paquete pasa de 5 MB."]:[],[],`${(e.bytes/1024).toFixed(0)} KB de 5 MB.`),Oy(e.ext,t),...Dy(e.ext,t),c.length?Le("red",n.titulo,c):n,Le("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."),Wy(e.ext,o,t),e.sinRed&&s.estado==="aviso"?Le("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 xy,Ac,$g,Le,Ec,Cy,jy,xg,Cg,Ay,Ey,qy,qc,jg,ky,Sg,Py,zy,Fy,Og=m(()=>{Pt();Ti();xy=/\.(m?js|cjs|jsx|html?|css|svg)$/i,Ac=12,$g=e=>{let o=[...new Set(e)];return o.length>Ac?[...o.slice(0,Ac),`\u2026 y ${o.length-Ac} m\xE1s`]:o},Le=(e,o,t,n=[],r="")=>({clave:e,titulo:o,estado:t.length?"falla":n.length?"aviso":"ok",detalles:t.length?$g(t):n.length?$g(n):r?[r]:[]}),Ec={buscar:"ver",ver:"ver",listar:"ver",obtener:"ver",pdf:"ver",crear:"crear",actualizar:"editar",mover:"editar",completar:"editar",borrar:"borrar"},Cy=new Set(["contexto.actual","publica.llamar","app.ajustes","extensiones.calcular"]),jy=new Set(["registros.relacionadas","registros.historial","registros.opciones","registros.adjuntar","mensajes.proponer","metricas.calcular"]);xg={ver:"ver",crear:"crear",editar:"cambiar",borrar:"borrar",almacen:"guardar datos",leer:"leer",escribir:"vincular"},Cg=e=>Object.hasOwn(Do,e)?Do[e].nombre:`\xAB${e.replace(/^mod_/,"")}\xBB`;Ay=/(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,Ey=new Set(["www.w3.org","w3.org"]),qy=/(?:\.min\.(?:m?js|css)$)|(?:^|\/)(?:jquery|lodash|alpine|react|vue|preact|chart|d3|moment|axios|dompurify|underscore|bootstrap|handlebars)[^/]*\.m?js$/i,qc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1)));jg={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]},ky=/^(transparent|inherit|initial|unset|revert|currentcolor|none)$/i;Sg=([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)},Py=(e,o)=>{let[t,n]=[Sg(e),Sg(o)].sort((r,a)=>a-r);return(t+.05)/(n+.05)};zy=[{nombre:/^jquery$/i,etiqueta:"jQuery",malas:e=>no(e,[3,5,0]),arreglo:"3.5.0 (CVE-2020-11022)"},{nombre:/^lodash$/i,etiqueta:"Lodash",malas:e=>no(e,[4,17,21]),arreglo:"4.17.21 (CVE-2021-23337)"},{nombre:/^moment$/i,etiqueta:"Moment.js",malas:e=>no(e,[2,29,4]),arreglo:"2.29.4 (CVE-2022-31129)"},{nombre:/^handlebars$/i,etiqueta:"Handlebars",malas:e=>no(e,[4,7,7]),arreglo:"4.7.7 (CVE-2021-23369)"},{nombre:/^bootstrap$/i,etiqueta:"Bootstrap",malas:e=>no(e,[3,4,1])||e[0]===4&&no(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?no(e,[2,5,4]):no(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?no(e,[0,28,0]):no(e,[1,6,0]),arreglo:"0.28.0 o 1.6.0 (CVE-2023-45857)"},{nombre:/^underscore$/i,etiqueta:"Underscore",malas:e=>no(e,[1,12,1]),arreglo:"1.12.1 (CVE-2021-23358)"}];Fy=/\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 Vy}from"node:worker_threads";var Uy,kc,Li,Ag=m(()=>{gr();Uy=new URL(import.meta.url.endsWith(".ts")?"./caja.ts":"./caja.js",import.meta.url),kc=class{w=null;ocupada=!1;worker(){return this.w?this.w:(this.w=new Vy(Uy,{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(f),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>z.llamadaCaracteres||s>=z.llamadasEnVuelo){n.postMessage({tipo:"respuesta",n:b.n,ok:!1,valor:typeof b.datos=="string"&&b.datos.length<=z.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),f=setTimeout(()=>c({ok:!1,corte:"tiempo",clase:"InternalError",mensaje:"interrupted",ms:Date.now()-t},!0),o.ms+z.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:z.pilaBytes,salidaBytes:z.salidaBytes,llamadaCaracteres:z.llamadaCaracteres,enVuelo:z.llamadasEnVuelo};n.postMessage(h)})}cerrar(){this.matar()}},Li=class{ranuras;cola=[];constructor(o=z.simultaneas){this.ranuras=Array.from({length:Math.max(1,o)},()=>new kc)}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 Jy}from"node:dns/promises";import{request as Qy}from"node:https";import{isIP as Gy}from"node:net";async function Tc(e,o,t={}){let n;try{n=new URL(e.url)}catch{throw new he("direcci\xF3n no v\xE1lida")}if(n.protocol!=="https:")throw new he("solo https");if(n.username||n.password)throw new he("sin usuario ni clave en la direcci\xF3n");if(n.port&&n.port!=="443")throw new he("solo al puerto 443");let r=n.hostname.toLowerCase().replace(/\.$/,"");if(Gy(r.replace(/^\[|\]$/g,""))||!Pc(o,r))throw new he("el dominio no est\xE1 entre los dominios aceptados");let a=String(e.metodo||"GET").toUpperCase();if(!Eg.has(a))throw new he("m\xE9todo no admitido");let s={};if(e.cabeceras&&typeof e.cabeceras=="object")for(let[f,h]of Object.entries(e.cabeceras).slice(0,30)){let b=f.toLowerCase();if(!Xy.test(f)||Hy.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)>z.red.cuerpoBytes)throw new he(`el cuerpo pasa de ${z.red.cuerpoBytes/1024} KB`);if(c!==null&&(a==="GET"||a==="HEAD"))throw new he("GET y HEAD no llevan cuerpo");let d=await(t.resolver??(f=>Jy(f,{all:!0,verbatim:!0})))(r).catch(()=>[]);if(!d.length)throw new he(`${r.slice(0,80)} no resuelve`);if(d.some(f=>zp(f.address)))throw new he(`${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??Ky)(u,{metodo:a,cabeceras:s,cuerpo:c});return{host:r,respuesta:p}}function Ky(e,o){return new Promise((t,n)=>{let r={...o.cabeceras,...o.cuerpo!==null?{"content-length":String(Buffer.byteLength(o.cuerpo))}:{}},a=Qy({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:z.red.plazoMs,agent:!1},c=>{let d=[],u=0;c.on("data",p=>{if(u+=p.length,u>z.red.respuestaBytes){c.destroy(),n(new he(`la respuesta pasa de ${z.red.respuestaBytes/1024/1024} MB`));return}d.push(p)}),c.on("end",()=>{clearTimeout(s);let p={};for(let f of Yy){let h=c.headers[f];typeof h=="string"&&(p[f]=h.slice(0,2e3))}t({status:c.statusCode??0,headers:p,cuerpo:Buffer.concat(d).toString("utf8")})}),c.on("error",()=>n(new he("la respuesta se cort\xF3")))}),s=setTimeout(()=>a.destroy(new he("sin respuesta a tiempo")),z.red.plazoMs);a.on("timeout",()=>a.destroy(new he("sin respuesta a tiempo"))),a.on("error",c=>{clearTimeout(s),n(c instanceof he?c:new he("no se ha podido conectar"))}),a.end(o.cuerpo??void 0)})}var he,Eg,Hy,Xy,Yy,Pc,Mc=m(()=>{Fp();gr();he=class extends Error{constructor(t){super(`fetch: ${t}`);this.motivo=t}motivo},Eg=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD"]),Hy=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"]),Xy=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/,Yy=["content-type","location","retry-after","etag","last-modified"],Pc=(e,o)=>e.some(t=>t===o||t.startsWith("*.")&&o.endsWith(t.slice(1))&&o.length>t.length-1)});function Rg(e,o){if(typeof o!="string"||typeof e!="string")return null;let n=(Object.hasOwn(qg,o)?qg[o]:null)??ao(o);if(!n)return null;let r=n.startsWith("mod_");switch(e){case"ver":return r?`${n}.ver`:Zy[n]??`${n}.ver`;case"buscar":return r?`${n}.listar`:e_[n]??`${n}.buscar`;case"crear":return`${n}.crear`;case"actualizar":return`${n}.actualizar`;default:return null}}function kg(e,o){return e.filter(t=>Pc(o,t.startsWith("*.")?`x${t.slice(1)}`:t)&&(!t.startsWith("*.")||o.includes(t)))}var qg,Zy,e_,Pg=m(()=>{Pt();Mc();qg={contactos:"contactos",contacts:"contactos",empresas:"empresas",companies:"empresas",oportunidades:"oportunidades",deals:"oportunidades",tareas:"tareas",tasks:"tareas",notas:"notas"},Zy={tareas:"tareas.obtener"},e_={tareas:"tareas.listar",notas:"notas.listar"}});var Ig={};Gg(Ig,{iniciarDev:()=>a_});import{createServer as o_}from"node:http";import{randomBytes as Tg}from"node:crypto";import{readFileSync as t_,realpathSync as Mg,watch as r_}from"node:fs";import{join as n_,sep as i_}from"node:path";async function a_(e){let o=hr(e),t=Number(Ue(e,"puerto")??5173),n=Mg(process.cwd());if(!Number.isInteger(t)||t<1||t>65535)throw new Error("Puerto no v\xE1lido.");let r=yo(n),a=(_,C)=>fr(o.api,o.clave,"/api/desarrollador/desarrollo",{espacio:o.espacio,ext_id:r.id,pase:_,funcion:C}),s=await a();await mr(n);let c=new Li(1),d=Tg(24).toString("hex"),u=1,p=null,f,h=r_(n,{recursive:!0},(_,C)=>{let S=String(C??"");/node_modules|\.fgx$|\.pem|^\.git[\/\\]/.test(S)||S==="interfaz/app.js"||(clearTimeout(f),f=setTimeout(()=>{p=mr(n).then(()=>{yo(n),u++,console.log("App actualizada.")}).catch(P=>console.error("Error de desarrollo:",P.message)).finally(()=>{p=null})},100))}),b=o_(async(_,C)=>{let S=(P,Z)=>{C.writeHead(P,{"content-type":"application/json","cache-control":"no-store"}),C.end(JSON.stringify(Z))};try{if(![`127.0.0.1:${t}`,`localhost:${t}`].includes(_.headers.host??""))return S(403,{error:"host_no_permitido"});let P=_.headers.origin;if(P&&P!==o.api)return S(403,{error:"origen_no_permitido"});if(P===o.api&&(C.setHeader("access-control-allow-origin",o.api),C.setHeader("vary","origin")),C.setHeader("access-control-allow-methods","GET, POST, OPTIONS"),C.setHeader("access-control-allow-headers","content-type, authorization"),_.method==="OPTIONS"){C.writeHead(204),C.end();return}let Z=new URL(_.url??"/",`http://127.0.0.1:${t}`),we=decodeURIComponent(Z.pathname);if(!we.startsWith(`/${d}/`))return S(404,{error:"no_encontrado"});let $=we.slice(d.length+2);if($==="__forgenex/version"&&_.method==="GET")return S(200,{version:u});if($.startsWith("__forgenex/funcion/")&&_.method==="POST"){if(P!==o.api)return S(403,{error:"origen_no_permitido"});let x=(_.headers.authorization??"").replace(/^Bearer /,"");if(!x.startsWith("crmui_"))return S(401,{error:"falta_pase"});if(!c.libres)return S(429,{error:"funcion_ocupada"});let A=$.slice(19),k=await a(x,A),F=yo(n).funciones.find(De=>De.nombre===A),G=k.manifiesto.funciones.find(De=>De.nombre===A);if(!F||!G)return S(403,{error:"funcion_no_instalada"});let Je=await fetch(`${o.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${x}`,"x-espacio":String(o.espacio)}});if(!Je.ok)return S(Je.status,{error:"pase_revocado"});let tt=await s_(_),rt=Tg(12).toString("hex"),H=0,Qe=0,Ce=await c.correr({codigo:y(F.entrada).toString("utf8"),fichero:F.entrada,entrada:tt,contexto:{extension:r.id,version:r.version,funcion:A,disparo:"desarrollo",ejecucion:rt},...tl(F),manejar:async(De,R)=>{if(De==="red"){if(++Qe>z.llamadasRed)throw new Error("Demasiadas peticiones de red.");return(await Tc(R,kg(G.red,k.aceptados.red_hacia))).respuesta}if(++H>z.llamadasApi)throw new Error("Demasiadas llamadas al CRM.");let D=R,oe=D.op??Rg(D.accion,D.modulo);if(!oe||!/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/.test(oe))throw new Error("Operaci\xF3n no v\xE1lida.");let Rt=await fetch(`${o.api}/api/v1/capabilities`,{redirect:"error",headers:{authorization:`Bearer ${x}`,"x-espacio":String(o.espacio)}});if(!Rt.ok)throw new Error("Pase caducado o revocado.");let Bc=await Rt.json(),Vc=(Bc.data?.operaciones??Bc.operaciones??[]).find(zi=>zi.id===oe);if(!Vc)throw new Error("Operaci\xF3n no aceptada por el administrador.");let Di=Vc.metodo,Uc=D.args??{},Ug=Di==="GET"?`?${new URLSearchParams(Object.entries(Uc).map(([zi,Jg])=>[zi,String(Jg)]))}`:"",Jc=await fetch(`${o.api}/api/v1/op/${oe}${Ug}`,{method:Di,redirect:"error",headers:{authorization:`Bearer ${x}`,"x-espacio":String(o.espacio),"content-type":"application/json","idempotency-key":`dev-${rt}-${H}`},...Di==="POST"?{body:JSON.stringify(Uc)}:{}}),Qc=await Jc.json();if(!Jc.ok)throw new Error(Qc.error?.mensaje??"El CRM rechaz\xF3 la operaci\xF3n.");return Qc.data}});return Ce.ok||console.error(`Funci\xF3n ${A}: ${Ce.clase}: ${Ce.mensaje}`),S(Ce.ok?200:422,Ce)}if(_.method!=="GET")return S(405,{error:"metodo_no_permitido"});if(await p,!$.startsWith("interfaz/"))return S(404,{error:"no_encontrado"});let M=y($),g=$.endsWith(".html")?"text/html":$.endsWith(".js")?"text/javascript":$.endsWith(".css")?"text/css":"application/octet-stream";C.writeHead(200,{"content-type":g,"cache-control":"no-store"}),C.end(M)}catch(P){console.error("Error de desarrollo:",P.message),S(400,{error:"desarrollo_error",mensaje:P.message})}});function y(_){if(_.includes("\\")||_.split("/").some(P=>P===".."||P==="."||!P))throw new Error("Ruta no admitida.");let C=Mg(n_(n,_));if(!C.startsWith(n+i_))throw new Error("Ruta fuera del proyecto.");let S=t_(C);if(S.length>2*1024*1024)throw new Error("Recurso demasiado grande.");return S}let v=()=>{clearTimeout(f),h.close(),c.cerrar(),b.closeAllConnections(),b.close()};b.on("error",_=>{console.error(_.message),v(),process.exitCode=1}),process.once("SIGINT",v),process.once("SIGTERM",v),await new Promise((_,C)=>{b.once("error",C),b.listen(t,"127.0.0.1",_)});let w=`http://127.0.0.1:${t}/${d}`;console.log(`Desarrollo: ${w}
|
|
42
|
-
Abrir CRM: ${
|
|
43
|
-
Recarga al guardar. Funciones: crm.pedir("desarrollo.funcion", { nombre, entrada }, { metodo: "POST", idempotencia: crypto.randomUUID() }).`)}async function
|
|
44
|
-
`)}function
|
|
45
|
-
P\xFAblica: ${t}.pub`),0}if(e==="registrar-clave"){let t=hr(o),n=nn(Lc(o),"utf8");return console.log(JSON.stringify(await fr(t.api,t.clave,"/api/desarrollador/claves",{espacio:t.espacio,publica:Dg(n).export({type:"spki",format:"pem"}).toString()}))),0}if(e==="revocar-clave"){let t=hr(o),n=Ue(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 fr(t.api,t.clave,"/api/desarrollador/revocar-clave",{espacio:t.espacio,id:n}))),0}if(e==="empaquetar"){if(o.includes("--sin-firmar")){let n=await Oc(process.cwd());return console.log(`${n} \xB7 Para \xABSubir paquete\xBB con el modo desarrollador encendido.`),0}let t=nn(Lc(o),"utf8");return console.log(await Oc(process.cwd(),t,Dg(t).export({type:"spki",format:"pem"}).toString())),0}if(e==="instalar"){let t=hr(o),n=Ue(o,"paquete"),r=Ue(o,"app"),a=Ue(o,"version");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:nn(n).toString("base64")},c=await fr(t.api,t.clave,"/api/desarrollador/instalar",s);return console.log(JSON.stringify(c)),c?.pendiente_permisos!==!1&&console.log("El administrador debe aceptar los permisos en Ajustes \u203A Apps."),0}if(e==="revisar"){let t=Ue(o,"paquete"),n;if(t){let r=nn(t),a=pr(r),s=a.get("extension.json");if(!s)throw new Error("Al paquete le falta \xABextension.json\xBB.");n=Rc({ext:zo(s.toString("utf8")),recursos:a,firmada:a.has(Zr),bytes:r.length,enLocal:!0})}else{let r=process.cwd();await mr(r);let a=Sc(r),s=zo(a.get("extension.json").toString("utf8"));n=Rc({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):Dc(n)),n.ok?0:1}if(e==="publicar"){let t=hr(o),n=Ue(o,"paquete"),r=o.includes("--tienda");if(!n)throw new Error("Falta --paquete <archivo.fgx> (lo hace `forgenex empaquetar`).");let a=await fr(t.api,t.clave,"/api/desarrollador/publicar",{espacio:t.espacio,paquete:nn(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(Dc(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==="dev"){let{iniciarDev:t}=await Promise.resolve().then(()=>(Lg(),Ig));return await t(o),0}return null}var p_,Ic=m(()=>{Ii();Pt();Ti();xc();Og();p_={ok:"\u2713",aviso:"!",falla:"\u2717"}});Ic();Ii();Gr();Es();Nc();dc();gi();lc();Pt();import{readFileSync as zc,statSync as m_}from"node:fs";import{join as f_}from"node:path";var Fc=200;function h_(e,o){try{return{archivo:e,ok:!0,solucion:Kr(o,{topeCampos:Fc})}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function g_(e){try{let o=JSON.parse(e);return typeof o=="object"&&o!==null&&o.formato===nt}catch{return!1}}function b_(e,o){try{return{archivo:e,ok:!0,extension:zo(o)}}catch(t){return{archivo:e,ok:!1,error:t instanceof Error?t.message:String(t)}}}function w_(){let e=n=>n.length>1?`${n.slice(0,-1).join(", ")} y ${n.at(-1)}`:n[0]??"",o=kt.filter(n=>pn.has(n)).map(n=>`\xAB${n}\xBB`),t=kt.filter(n=>!pn.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 v_(){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${nt}\xBB, versi\xF3n ${dn}. 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:nt},formato_version:{type:"integer",minimum:1,maximum:dn,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:w_(),items:{type:"object",additionalProperties:!1,required:["id","punto","entrada","titulo"],properties:{id:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,40}$"},punto:{enum:[...kt]},entrada:t,titulo:e(60),icono:{type:"string"},modulo:{type:"string",description:`Solo en ${[...br].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:[...br]}},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:[...ln]},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:[...un]},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(Do).map(([c,d])=>`${c} (${d.ops.join(", ")})`).join("; ")}. Los de su soluci\xF3n o del espacio, por su clave: ${Lo.join(", ")}.`,additionalProperties:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{enum:[...Lo]}}},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:cn}}}function Vg(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 y_(){let e=o=>({type:"string",maxLength:o});return{$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://forgenex.com/sdk/solucion-v${dr}.schema.json`,title:"Soluci\xF3n del CRM ForgeNEX",description:`Formato \xAB${qt}\xBB, versi\xF3n ${dr}. 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:qt},version:{type:"integer",minimum:1,maximum:dr,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:Ri,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:[...Js]},campos:{type:"array",maxItems:Fc,items:{type:"object",required:["clave","etiqueta","tipo"],properties:{clave:{type:"string"},etiqueta:e(80),tipo:{enum:[...Vs]},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(As.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:pi,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:mi,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:bc,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:yc,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:gc,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:wc,description:"Se instalan APAGADAS: una persona las revisa y las enciende."},ejemplos:{type:"object",description:`Datos de ejemplo por clave de m\xF3dulo (hasta ${Pi} cada uno).`,additionalProperties:{type:"array",maxItems:Pi}},informes:{type:"array",maxItems:Yr,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:Ei,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:vc,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:_c,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:ki,topeCampos:Fc}}}async function Wc(e){let[o,...t]=e,n=await Bg(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(`${qt} v${dr}`),0;if(o==="esquema")return console.log(JSON.stringify(y_(),null,2)),0;if(o==="esquema-extension")return console.log(JSON.stringify(v_(),null,2)),0;if((o==="validar"||o==="previsualizar")&&a.length){let s=a.map(c=>{let d;try{m_(c).isDirectory()?(yo(c),d=zc(f_(c,"extension.json"),"utf8")):o==="validar"&&c.toLowerCase().endsWith(".fgx")?d=Ng(zc(c)):d=zc(c,"utf8")}catch(u){return{archivo:c,ok:!1,error:u instanceof Error?u.message:String(u)}}return g_(d)?b_(c,d):h_(c,d)});if(r)console.log(JSON.stringify(s.map(c=>c.ok?"extension"in c?{archivo:c.archivo,ok:!0,extension:c.extension}:{archivo:c.archivo,ok:!0,resumen:Vg(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;console.log(`\u2713 ${c.archivo}: app \xAB${d.nombre}\xBB ${d.version} (${d.id})`);for(let[f,h]of Object.entries(d.permisos.modulos))console.log(` \xB7 pide ${f}: ${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(f=>!pn.has(f.punto)).map(f=>`montajes.${f.punto}`))];for(let f of d.funciones)console.log(` \xB7 funci\xF3n ${f.nombre} (${f.disparador.tipo}${f.disparador.evento?`: ${f.disparador.evento}`:f.disparador.cron?`: ${f.disparador.cron}`:""})`);for(let f of d.permisos.red_hacia)console.log(` \xB7 se conecta a ${f}`);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=Vg(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 crear-app <nombre> [--plantilla html|react|archivos] \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")&&Wc(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});Wc(process.argv.slice(2)).then(e=>{process.exitCode=e}).catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
|
|
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(`
|
|
72
|
+
`)+[...u.matchAll(/\sstyle\s*=\s*"([^"]*)"/gi)].map(m=>`x{${m[1]}}`).join(`
|
|
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});
|