diff --git a/dist-back/index.js b/dist-back/index.js index 821a29e..487f583 100644 --- a/dist-back/index.js +++ b/dist-back/index.js @@ -31,6 +31,7 @@ __reExport(index_exports, require("./testes-de-variaveis"), module.exports); __reExport(index_exports, require("./texto_busca"), module.exports); __reExport(index_exports, require("./tipagemRotas"), module.exports); __reExport(index_exports, require("./tipagemRotas"), module.exports); +__reExport(index_exports, require("./tipoFiltro.26"), module.exports); __reExport(index_exports, require("./unidades_medida"), module.exports); __reExport(index_exports, require("./uuid"), module.exports); __reExport(index_exports, require("./variaveisComuns"), module.exports); @@ -52,6 +53,7 @@ __reExport(index_exports, require("./variaveisComuns"), module.exports); ...require("./texto_busca"), ...require("./tipagemRotas"), ...require("./tipagemRotas"), + ...require("./tipoFiltro.26"), ...require("./unidades_medida"), ...require("./uuid"), ...require("./variaveisComuns") diff --git a/dist-back/tipoFiltro.26.js b/dist-back/tipoFiltro.26.js new file mode 100644 index 0000000..c4356ce --- /dev/null +++ b/dist-back/tipoFiltro.26.js @@ -0,0 +1,49 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var tipoFiltro_26_exports = {}; +__export(tipoFiltro_26_exports, { + zFiltro26: () => zFiltro26 +}); +module.exports = __toCommonJS(tipoFiltro_26_exports); +var import_zod = require("zod"); +const zOperadores = import_zod.z.enum(["=", "!=", ">", ">=", "<", "<=", "like", "in"]); +const zValor = import_zod.z.any(); +const zCondicao = import_zod.z.record(zOperadores, zValor); +const zFiltro26 = import_zod.z.lazy( + () => import_zod.z.object({ + E: import_zod.z.array(zFiltro26).optional(), + OU: import_zod.z.array(zFiltro26).optional() + }).catchall(import_zod.z.union([zCondicao, zFiltro26])) +); +const _filtro = { + idade: { ">=": 18 }, + OU: [ + { nome: { like: "%pa%" } }, + { + E: [ + { carro: { ano: { "=": 2020 } } }, + { carro: { modelo: { in: ["Civic", "Corolla"] } } } + ] + } + ] +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + zFiltro26 +}); diff --git a/dist-front/index.d.mts b/dist-front/index.d.mts index 0c0d61c..51be5b5 100644 --- a/dist-front/index.d.mts +++ b/dist-front/index.d.mts @@ -1,4 +1,4 @@ -import z from 'zod'; +import z, { z as z$1 } from 'zod'; export { Dayjs, ManipulateType, default as dayjsbr } from 'dayjs'; export { default as duration } from 'dayjs/plugin/duration'; export { default as isSameOrAfter } from 'dayjs/plugin/isSameOrAfter'; @@ -259,6 +259,141 @@ declare class TipagemRotas; } +/** + * ============================================================================= + * tipoFiltro26 + * ============================================================================= + * + * OBJETIVO + * ----------------------------------------------------------------------------- + * Gerar automaticamente a tipagem de filtros compatíveis com operadores + * padrão do PostgreSQL, a partir de um tipo base T. + * + * Este tipo foi projetado para: + * - Construção de filtros dinâmicos + * - Geração posterior de WHERE (Knex / SQL) + * - Uso seguro por IA (evita filtros inválidos em nível de tipo) + * + * + * FORMATO DO FILTRO + * ----------------------------------------------------------------------------- + * 1) Campos simples: + * + * { + * idade: { ">=": 18 } + * } + * + * 2) Campos aninhados: + * + * { + * carro: { + * ano: { "=": 2020 } + * } + * } + * + * 3) Operador E (AND): + * + * { + * E: [ + * { idade: { ">=": 18 } }, + * { nome: { like: "%pa%" } } + * ] + * } + * + * 4) Operador OU (OR): + * + * { + * OU: [ + * { idade: { "<": 18 } }, + * { idade: { ">=": 60 } } + * ] + * } + * + * 5) Combinação complexa: + * + * { + * idade: { ">=": 18 }, + * OU: [ + * { nome: { like: "%pa%" } }, + * { + * E: [ + * { carro: { ano: { "=": 2020 } } }, + * { carro: { modelo: { in: ["Civic"] } } } + * ] + * } + * ] + * } + * + * + * REGRAS IMPORTANTES (PARA IA) + * ----------------------------------------------------------------------------- + * - Apenas campos existentes em T podem ser usados. + * - Operadores são restritos por tipo do campo. + * - Objetos são tratados recursivamente. + * - Arrays NÃO são tratados como objeto recursivo. + * - Funções NÃO são consideradas campos filtráveis. + * + * + * OPERADORES SUPORTADOS + * ----------------------------------------------------------------------------- + * number: + * =, !=, >, >=, <, <=, in + * + * string: + * =, !=, like, in + * + * boolean: + * =, !=, in + * + * Não há suporte automático a: + * - null + * - date + * - jsonb + * - arrays + * + * Essas extensões devem ser adicionadas explicitamente. + * + * ============================================================================= + */ +type PgOpsNumber = { + "="?: number; + "!="?: number; + ">"?: number; + ">="?: number; + "<"?: number; + "<="?: number; + in?: number[]; +}; +type PgOpsString = { + "="?: string; + "!="?: string; + like?: string; + in?: string[]; +}; +type PgOpsBoolean = { + "="?: boolean; + "!="?: boolean; + in?: boolean[]; +}; +type PgOpsFor = V extends number ? PgOpsNumber : V extends string ? PgOpsString : V extends boolean ? PgOpsBoolean : never; +type IsPlainObject = T extends object ? T extends Function ? false : T extends readonly any[] ? false : true : false; +type FiltroCampos = { + [K in keyof T]?: IsPlainObject extends true ? tipoFiltro26 : PgOpsFor; +}; +type tipoFiltro26 = FiltroCampos & { + /** + * E => AND lógico + * Todos os filtros dentro do array devem ser verdadeiros. + */ + E?: tipoFiltro26[]; + /** + * OU => OR lógico + * Pelo menos um filtro dentro do array deve ser verdadeiro. + */ + OU?: tipoFiltro26[]; +}; +declare const zFiltro26: z$1.ZodType; + /** * Essa variável se conecta a tabela_lidades * @@ -327,4 +462,4 @@ declare const nomeVariavel: (v: { [key: string]: any; }) => string; -export { Produtos, TipagemRotas, aleatorio, cacheM, cacheMFixo, cacheMemoria, camposComuns, erUuid, esperar, extensoes, type interfaceConsulta, link_paiol, localValor, nomeVariavel, objetoPg, operadores, paraObjetoRegistroPg, pgObjeto, siglas_unidades_medida, texto_busca, tipoArquivo, type tipoFiltro, tipoUsuarioResiduos, tiposSituacoesElicencie, tx, umaFuncao, umaVariavel, unidades_medida, uuid, uuidV3, uuidV4, uuid_null, validarUuid, verCacheM, zFiltro, zOperadores }; +export { Produtos, TipagemRotas, aleatorio, cacheM, cacheMFixo, cacheMemoria, camposComuns, erUuid, esperar, extensoes, type interfaceConsulta, link_paiol, localValor, nomeVariavel, objetoPg, operadores, paraObjetoRegistroPg, pgObjeto, siglas_unidades_medida, texto_busca, tipoArquivo, type tipoFiltro, type tipoFiltro26, tipoUsuarioResiduos, tiposSituacoesElicencie, tx, umaFuncao, umaVariavel, unidades_medida, uuid, uuidV3, uuidV4, uuid_null, validarUuid, verCacheM, zFiltro, zFiltro26, zOperadores }; diff --git a/dist-front/index.mjs b/dist-front/index.mjs index b7ec4e7..38d22d7 100644 --- a/dist-front/index.mjs +++ b/dist-front/index.mjs @@ -1 +1 @@ -var s="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),K=o=>`eli-${Array.from({length:o||8}).map(()=>s[(999*Math.random()|0)%s.length]).join("")}`;var f={};globalThis.cacheMemoria_cache=f;var u=(o,a,r)=>{let n=typeof o=="string"?o:typeof o=="number"?String(o):encodeURIComponent(JSON.stringify(o)),t=r&&new Date().getTime()+r*1e3;a!==void 0&&(f[n]={valor:a,validade:t});let m=f[n];if(!(m?.validade&&m.validadef,D=u,R=o=>a=>u(o,a);var B="00000000-0000-0000-0000-000000000000",c=(i=>(i.codigo="codigo",i.excluido="excluido",i.data_hora_criacao="data_hora_criacao",i.data_hora_atualizacao="data_hora_atualizacao",i.codigo_usuario_criacao="codigo_usuario_criacao",i.codigo_usuario_atualizacao="codigo_usuario_atualizacao",i.versao="versao",i))(c||{}),_=(a=>(a.token="token",a))(_||{}),v=(r=>(r.Usuario="usuario",r.Fornecedor="fornecedor",r))(v||{});import l from"zod";var h=(n=>(n["="]="=",n["!="]="!=",n[">"]=">",n[">="]=">=",n["<"]="<",n["<="]="<=",n.like="like",n.in="in",n.isNull="isNull",n))(h||{}),y=l.enum(["=","!=",">",">=","<","<=","like","in","isNull"]),H=l.object({coluna:l.string(),valor:l.any(),operador:y,ou:l.boolean().optional()});import d from"dayjs";import b from"dayjs/plugin/duration";import T from"dayjs/plugin/isSameOrAfter";import w from"dayjs/plugin/isSameOrBefore";import z from"dayjs/plugin/minMax";import O from"dayjs/plugin/relativeTime";import j from"dayjs/plugin/timezone";import k from"dayjs/plugin/utc";import N from"dayjs/plugin/weekOfYear";import"dayjs/locale/pt-br";d.locale("pt-br");d.extend(k);d.extend(j);d.extend(N);d.extend(w);d.extend(T);d.extend(z);d.extend(O);d.extend(b);var io="https://paiol.idz.one";var M=[{ext:"gif",tipo:"imagem",mime:"image/gif"},{ext:"jpg",tipo:"imagem",mime:"image/jpeg"},{ext:"jpeg",tipo:"imagem",mime:"image/jpeg"},{ext:"png",tipo:"imagem",mime:"image/png"},{ext:"bmp",tipo:"imagem",mime:"image/bmp"},{ext:"webp",tipo:"imagem",mime:"image/webp"},{ext:"tiff",tipo:"imagem",mime:"image/tiff"},{ext:"svg",tipo:"imagem",mime:"image/svg+xml"},{ext:"ico",tipo:"imagem",mime:"image/x-icon"},{ext:"pdf",tipo:"documento",mime:"application/pdf"},{ext:"doc",tipo:"documento",mime:"application/msword"},{ext:"docx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},{ext:"xls",tipo:"documento",mime:"application/vnd.ms-excel"},{ext:"xlsx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},{ext:"ppt",tipo:"documento",mime:"application/vnd.ms-powerpoint"},{ext:"pptx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"},{ext:"txt",tipo:"documento",mime:"text/plain"},{ext:"odt",tipo:"documento",mime:"application/vnd.oasis.opendocument.text"},{ext:"ods",tipo:"documento",mime:"application/vnd.oasis.opendocument.spreadsheet"},{ext:"rtf",tipo:"documento",mime:"application/rtf"},{ext:"csv",tipo:"documento",mime:"text/csv"},{ext:"mp4",tipo:"v\xEDdeo",mime:"video/mp4"},{ext:"avi",tipo:"v\xEDdeo",mime:"video/x-msvideo"},{ext:"mkv",tipo:"v\xEDdeo",mime:"video/x-matroska"},{ext:"mov",tipo:"v\xEDdeo",mime:"video/quicktime"},{ext:"wmv",tipo:"v\xEDdeo",mime:"video/x-ms-wmv"},{ext:"flv",tipo:"v\xEDdeo",mime:"video/x-flv"},{ext:"webm",tipo:"v\xEDdeo",mime:"video/webm"},{ext:"3gp",tipo:"v\xEDdeo",mime:"video/3gpp"},{ext:"mpeg",tipo:"v\xEDdeo",mime:"video/mpeg"}],so=o=>{let a=String(o||"").toLocaleLowerCase().split(".").pop();return M.find(n=>n.ext===a)?.tipo||"outros"};var go=(o,a)=>{let r="localStorage"in globalThis?globalThis.localStorage:void 0;if(typeof r>"u")return null;let n=typeof o=="string"?o:encodeURIComponent(JSON.stringify(o));try{a!==void 0&&r.setItem(n,JSON.stringify(a));let t=r.getItem(n);if(t===null)return null;try{return JSON.parse(t)}catch{return t}}catch{return null}};var g=o=>{try{return Object.fromEntries(Object.entries(o).map(([a,r])=>[a,r===void 0||r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?r:JSON.stringify(r,null,2)]))}catch(a){throw new Error(`Erro na fun\xE7\xE3o paraObjetoRegistroPg: ${a.message} ${a.stack}`)}},co=g,_o=g;var L=(o=>(o["e-licencie"]="e-licencie",o["gov.e-licencie"]="gov.e-licencie",o))(L||{});var q=(e=>(e.modelo="000_modelo",e.vencida="100_vencida",e.expirado="200_expirado",e.alerta="300_alerta",e.protocoladafora="350_protocoladafora",e.protocolada="400_protocolada",e.protocoladaApenas="430_protocolada",e.protocolada_alteracao="450_protocolada",e.prazo="500_prazo",e.emitida="515_emitida",e.valida="518_valida",e.novo="520_novo",e.recebido="521_recebido",e.em_andamento="530_em_andamento",e.aguardando="530_aguardando",e.aguardandoresposta="540_aguardandoresposta",e.suspensaotemporaria="540_suspensaotemporaria",e.cancelada="550_cancelada",e.execucao="560_execucao",e.pendente="570_pendente",e.executadafora="600_executadafora",e.executada="700_executada",e.naoexecutada="701_naoexecutada",e.concluida="730_concluida",e.respondido_negado="740_respondido_negado",e.respondido_aceito="741_respondido_aceito",e.atendidoparcial="742_atendidoparcial",e.naoatendido="743_naoatendido",e.atendido="744_atendido",e.renovada="760_renovada",e.finalizada="800_finalizada",e.emitirnota="101_emitirnota",e.faturaatrasada="301_faturaatrasada",e.pagarfatura="302_pagarfatura",e.aguardandoconfirmacao="531_aguardandoconfirmacao",e.agendado="701_agendado",e.faturapaga="801_faturapaga",e.excluida="999_excluida",e.requerida="401_requerida",e.vigente="516_vigente",e.emrenovacao="402_emrenovacao",e.arquivada="801_arquivada",e.aguardando_sincronizacao="999_aguardando_sincronizacao",e.nao_conforme="710_nao_conforme",e.conforme="720_conforme",e.nao_aplicavel="730_nao_aplicavel",e.parcial="715_parcial",e))(q||{});var bo=()=>"Ol\xE1 Mundo! (fun\xE7\xE3o)";var wo="Ol\xE1 Mundo! (vari\xE1vel)";var No=(...o)=>o.map(a=>a==null?"":String(a).normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s+/g," ").toLowerCase()).join(" ");var x=class{constructor({caminho:a,acaoIr:r,rotulo:n}){this._partesCaminho=[];this._acaoIr=r,this._partesCaminho=(Array.isArray(a)?a:[a]).filter(Boolean).map(t=>String(t)).flatMap(t=>t.split("/")).filter(Boolean),this.rotulo=n}get caminho(){return`/${this._partesCaminho.join("/")}`}set caminho(a){this._partesCaminho=a.split("/").filter(r=>r)}endereco(a,r){let n=typeof globalThis<"u"&&globalThis.window||void 0,t=new URL(n?n.location.href:"http://localhost");t.pathname=this.caminho,t.search="";let m=Object.entries(a);for(let[p,i]of m)t.searchParams.set(String(p),JSON.stringify(i));return t.hash="",r&&(t.hash=`#${t.search}`,t.search=""),t.href}ir(a){if(this._acaoIr)this._acaoIr(this.endereco({...a}));else{let r=typeof globalThis<"u"&&globalThis.window||void 0;r&&(r.location.href=this.endereco({...a}))}}parametros(a){let r=a?new URL(a):new URL(typeof globalThis<"u"&&globalThis.window?globalThis.window.location.href:"http://localhost"),n=r.searchParams,t=Object.fromEntries(n.entries()),m=r.hash;if(m){let p=Object.fromEntries(new URLSearchParams(m.slice(1)).entries());t={...t,...p}}for(let p in t)try{t[p]=JSON.parse(t[p])}catch{console.log(`[${p}|${t[p]}] n\xE3o \xE9 um json v\xE1lido.`)}return t}};var U=(m=>(m.UN="UN",m.KG="KG",m.TON="TON",m.g="g",m["M\xB3"]="M\xB3",m.Lt="Lt",m))(U||{}),qo=[{sigla_unidade:"KG",nome:"Quilograma",sigla_normalizada:"KG",normalizar:o=>o,tipo:"massa"},{sigla_unidade:"g",nome:"Grama",sigla_normalizada:"KG",normalizar:o=>o/1e3,tipo:"massa"},{sigla_unidade:"TON",nome:"Tonelada",sigla_normalizada:"KG",normalizar:o=>o*1e3,tipo:"massa"},{sigla_unidade:"Lt",nome:"Litro",sigla_normalizada:"Lt",normalizar:o=>o,tipo:"volume"},{sigla_unidade:"M\xB3",nome:"Metro C\xFAbico",sigla_normalizada:"Lt",normalizar:o=>o*1e3,tipo:"volume"},{sigla_unidade:"UN",nome:"Unidade",sigla_normalizada:"UN",normalizar:o=>o,tipo:"unidade"}];import{NIL as A,v3 as I,v4 as J}from"uuid";var C=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Io=o=>C.test(String(o||"")),F=(o,a)=>I(typeof o=="string"?o:typeof o=="number"?String(o):JSON.stringify(o),a?F(a):A),G=J,Jo=G;var Fo=o=>new Promise(a=>setTimeout(()=>a(!0),o)),Go=o=>Object.keys(o).join("/");export{L as Produtos,x as TipagemRotas,K as aleatorio,u as cacheM,R as cacheMFixo,D as cacheMemoria,c as camposComuns,d as dayjsbr,b as duration,C as erUuid,Fo as esperar,M as extensoes,T as isSameOrAfter,w as isSameOrBefore,io as link_paiol,go as localValor,z as minMax,Go as nomeVariavel,_o as objetoPg,h as operadores,g as paraObjetoRegistroPg,co as pgObjeto,O as relativeTime,U as siglas_unidades_medida,No as texto_busca,j as timezone,so as tipoArquivo,v as tipoUsuarioResiduos,q as tiposSituacoesElicencie,_ as tx,bo as umaFuncao,wo as umaVariavel,qo as unidades_medida,k as utc,Jo as uuid,F as uuidV3,G as uuidV4,B as uuid_null,Io as validarUuid,$ as verCacheM,N as weekOfYear,H as zFiltro,y as zOperadores}; +var g="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),D=o=>`eli-${Array.from({length:o||8}).map(()=>g[(999*Math.random()|0)%g.length]).join("")}`;var f={};globalThis.cacheMemoria_cache=f;var x=(o,a,r)=>{let n=typeof o=="string"?o:typeof o=="number"?String(o):encodeURIComponent(JSON.stringify(o)),t=r&&new Date().getTime()+r*1e3;a!==void 0&&(f[n]={valor:a,validade:t});let i=f[n];if(!(i?.validade&&i.validadef,Y=x,Z=o=>a=>x(o,a);var W="00000000-0000-0000-0000-000000000000",b=(m=>(m.codigo="codigo",m.excluido="excluido",m.data_hora_criacao="data_hora_criacao",m.data_hora_atualizacao="data_hora_atualizacao",m.codigo_usuario_criacao="codigo_usuario_criacao",m.codigo_usuario_atualizacao="codigo_usuario_atualizacao",m.versao="versao",m))(b||{}),y=(a=>(a.token="token",a))(y||{}),v=(r=>(r.Usuario="usuario",r.Fornecedor="fornecedor",r))(v||{});import s from"zod";var h=(n=>(n["="]="=",n["!="]="!=",n[">"]=">",n[">="]=">=",n["<"]="<",n["<="]="<=",n.like="like",n.in="in",n.isNull="isNull",n))(h||{}),T=s.enum(["=","!=",">",">=","<","<=","like","in","isNull"]),E=s.object({coluna:s.string(),valor:s.any(),operador:T,ou:s.boolean().optional()});import d from"dayjs";import O from"dayjs/plugin/duration";import z from"dayjs/plugin/isSameOrAfter";import w from"dayjs/plugin/isSameOrBefore";import j from"dayjs/plugin/minMax";import k from"dayjs/plugin/relativeTime";import N from"dayjs/plugin/timezone";import P from"dayjs/plugin/utc";import F from"dayjs/plugin/weekOfYear";import"dayjs/locale/pt-br";d.locale("pt-br");d.extend(P);d.extend(N);d.extend(F);d.extend(w);d.extend(z);d.extend(j);d.extend(k);d.extend(O);var uo="https://paiol.idz.one";var M=[{ext:"gif",tipo:"imagem",mime:"image/gif"},{ext:"jpg",tipo:"imagem",mime:"image/jpeg"},{ext:"jpeg",tipo:"imagem",mime:"image/jpeg"},{ext:"png",tipo:"imagem",mime:"image/png"},{ext:"bmp",tipo:"imagem",mime:"image/bmp"},{ext:"webp",tipo:"imagem",mime:"image/webp"},{ext:"tiff",tipo:"imagem",mime:"image/tiff"},{ext:"svg",tipo:"imagem",mime:"image/svg+xml"},{ext:"ico",tipo:"imagem",mime:"image/x-icon"},{ext:"pdf",tipo:"documento",mime:"application/pdf"},{ext:"doc",tipo:"documento",mime:"application/msword"},{ext:"docx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},{ext:"xls",tipo:"documento",mime:"application/vnd.ms-excel"},{ext:"xlsx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},{ext:"ppt",tipo:"documento",mime:"application/vnd.ms-powerpoint"},{ext:"pptx",tipo:"documento",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"},{ext:"txt",tipo:"documento",mime:"text/plain"},{ext:"odt",tipo:"documento",mime:"application/vnd.oasis.opendocument.text"},{ext:"ods",tipo:"documento",mime:"application/vnd.oasis.opendocument.spreadsheet"},{ext:"rtf",tipo:"documento",mime:"application/rtf"},{ext:"csv",tipo:"documento",mime:"text/csv"},{ext:"mp4",tipo:"v\xEDdeo",mime:"video/mp4"},{ext:"avi",tipo:"v\xEDdeo",mime:"video/x-msvideo"},{ext:"mkv",tipo:"v\xEDdeo",mime:"video/x-matroska"},{ext:"mov",tipo:"v\xEDdeo",mime:"video/quicktime"},{ext:"wmv",tipo:"v\xEDdeo",mime:"video/x-ms-wmv"},{ext:"flv",tipo:"v\xEDdeo",mime:"video/x-flv"},{ext:"webm",tipo:"v\xEDdeo",mime:"video/webm"},{ext:"3gp",tipo:"v\xEDdeo",mime:"video/3gpp"},{ext:"mpeg",tipo:"v\xEDdeo",mime:"video/mpeg"}],_o=o=>{let a=String(o||"").toLocaleLowerCase().split(".").pop();return M.find(n=>n.ext===a)?.tipo||"outros"};var yo=(o,a)=>{let r="localStorage"in globalThis?globalThis.localStorage:void 0;if(typeof r>"u")return null;let n=typeof o=="string"?o:encodeURIComponent(JSON.stringify(o));try{a!==void 0&&r.setItem(n,JSON.stringify(a));let t=r.getItem(n);if(t===null)return null;try{return JSON.parse(t)}catch{return t}}catch{return null}};var c=o=>{try{return Object.fromEntries(Object.entries(o).map(([a,r])=>[a,r===void 0||r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?r:JSON.stringify(r,null,2)]))}catch(a){throw new Error(`Erro na fun\xE7\xE3o paraObjetoRegistroPg: ${a.message} ${a.stack}`)}},ho=c,To=c;var U=(o=>(o["e-licencie"]="e-licencie",o["gov.e-licencie"]="gov.e-licencie",o))(U||{});var L=(e=>(e.modelo="000_modelo",e.vencida="100_vencida",e.expirado="200_expirado",e.alerta="300_alerta",e.protocoladafora="350_protocoladafora",e.protocolada="400_protocolada",e.protocoladaApenas="430_protocolada",e.protocolada_alteracao="450_protocolada",e.prazo="500_prazo",e.emitida="515_emitida",e.valida="518_valida",e.novo="520_novo",e.recebido="521_recebido",e.em_andamento="530_em_andamento",e.aguardando="530_aguardando",e.aguardandoresposta="540_aguardandoresposta",e.suspensaotemporaria="540_suspensaotemporaria",e.cancelada="550_cancelada",e.execucao="560_execucao",e.pendente="570_pendente",e.executadafora="600_executadafora",e.executada="700_executada",e.naoexecutada="701_naoexecutada",e.concluida="730_concluida",e.respondido_negado="740_respondido_negado",e.respondido_aceito="741_respondido_aceito",e.atendidoparcial="742_atendidoparcial",e.naoatendido="743_naoatendido",e.atendido="744_atendido",e.renovada="760_renovada",e.finalizada="800_finalizada",e.emitirnota="101_emitirnota",e.faturaatrasada="301_faturaatrasada",e.pagarfatura="302_pagarfatura",e.aguardandoconfirmacao="531_aguardandoconfirmacao",e.agendado="701_agendado",e.faturapaga="801_faturapaga",e.excluida="999_excluida",e.requerida="401_requerida",e.vigente="516_vigente",e.emrenovacao="402_emrenovacao",e.arquivada="801_arquivada",e.aguardando_sincronizacao="999_aguardando_sincronizacao",e.nao_conforme="710_nao_conforme",e.conforme="720_conforme",e.nao_aplicavel="730_nao_aplicavel",e.parcial="715_parcial",e))(L||{});var jo=()=>"Ol\xE1 Mundo! (fun\xE7\xE3o)";var No="Ol\xE1 Mundo! (vari\xE1vel)";var Lo=(...o)=>o.map(a=>a==null?"":String(a).normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s+/g," ").toLowerCase()).join(" ");var _=class{constructor({caminho:a,acaoIr:r,rotulo:n}){this._partesCaminho=[];this._acaoIr=r,this._partesCaminho=(Array.isArray(a)?a:[a]).filter(Boolean).map(t=>String(t)).flatMap(t=>t.split("/")).filter(Boolean),this.rotulo=n}get caminho(){return`/${this._partesCaminho.join("/")}`}set caminho(a){this._partesCaminho=a.split("/").filter(r=>r)}endereco(a,r){let n=typeof globalThis<"u"&&globalThis.window||void 0,t=new URL(n?n.location.href:"http://localhost");t.pathname=this.caminho,t.search="";let i=Object.entries(a);for(let[p,m]of i)t.searchParams.set(String(p),JSON.stringify(m));return t.hash="",r&&(t.hash=`#${t.search}`,t.search=""),t.href}ir(a){if(this._acaoIr)this._acaoIr(this.endereco({...a}));else{let r=typeof globalThis<"u"&&globalThis.window||void 0;r&&(r.location.href=this.endereco({...a}))}}parametros(a){let r=a?new URL(a):new URL(typeof globalThis<"u"&&globalThis.window?globalThis.window.location.href:"http://localhost"),n=r.searchParams,t=Object.fromEntries(n.entries()),i=r.hash;if(i){let p=Object.fromEntries(new URLSearchParams(i.slice(1)).entries());t={...t,...p}}for(let p in t)try{t[p]=JSON.parse(t[p])}catch{console.log(`[${p}|${t[p]}] n\xE3o \xE9 um json v\xE1lido.`)}return t}};import{z as l}from"zod";var q=l.enum(["=","!=",">",">=","<","<=","like","in"]),C=l.any(),I=l.record(q,C),u=l.lazy(()=>l.object({E:l.array(u).optional(),OU:l.array(u).optional()}).catchall(l.union([I,u])));var K=(i=>(i.UN="UN",i.KG="KG",i.TON="TON",i.g="g",i["M\xB3"]="M\xB3",i.Lt="Lt",i))(K||{}),Ao=[{sigla_unidade:"KG",nome:"Quilograma",sigla_normalizada:"KG",normalizar:o=>o,tipo:"massa"},{sigla_unidade:"g",nome:"Grama",sigla_normalizada:"KG",normalizar:o=>o/1e3,tipo:"massa"},{sigla_unidade:"TON",nome:"Tonelada",sigla_normalizada:"KG",normalizar:o=>o*1e3,tipo:"massa"},{sigla_unidade:"Lt",nome:"Litro",sigla_normalizada:"Lt",normalizar:o=>o,tipo:"volume"},{sigla_unidade:"M\xB3",nome:"Metro C\xFAbico",sigla_normalizada:"Lt",normalizar:o=>o*1e3,tipo:"volume"},{sigla_unidade:"UN",nome:"Unidade",sigla_normalizada:"UN",normalizar:o=>o,tipo:"unidade"}];import{NIL as A,v3 as V,v4 as J}from"uuid";var G=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Go=o=>G.test(String(o||"")),$=(o,a)=>V(typeof o=="string"?o:typeof o=="number"?String(o):JSON.stringify(o),a?$(a):A),B=J,$o=B;var Do=o=>new Promise(a=>setTimeout(()=>a(!0),o)),Ro=o=>Object.keys(o).join("/");export{U as Produtos,_ as TipagemRotas,D as aleatorio,x as cacheM,Z as cacheMFixo,Y as cacheMemoria,b as camposComuns,d as dayjsbr,O as duration,G as erUuid,Do as esperar,M as extensoes,z as isSameOrAfter,w as isSameOrBefore,uo as link_paiol,yo as localValor,j as minMax,Ro as nomeVariavel,To as objetoPg,h as operadores,c as paraObjetoRegistroPg,ho as pgObjeto,k as relativeTime,K as siglas_unidades_medida,Lo as texto_busca,N as timezone,_o as tipoArquivo,v as tipoUsuarioResiduos,L as tiposSituacoesElicencie,y as tx,jo as umaFuncao,No as umaVariavel,Ao as unidades_medida,P as utc,$o as uuid,$ as uuidV3,B as uuidV4,W as uuid_null,Go as validarUuid,Q as verCacheM,F as weekOfYear,E as zFiltro,u as zFiltro26,T as zOperadores}; diff --git a/package.json b/package.json index c69ee09..f4b9a82 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "p-comuns", - "version": "0.304.0", + "version": "0.307.0", "description": "", "main": "./dist-front/index.mjs", "module": "./dist-front/index.mjs", diff --git a/pacote.tgz b/pacote.tgz index 682bc9e..3ce4852 100644 Binary files a/pacote.tgz and b/pacote.tgz differ diff --git a/src/index.ts b/src/index.ts index 989c6ad..eaa0800 100755 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,7 @@ export * from "./testes-de-variaveis" export * from "./texto_busca" export * from "./tipagemRotas" export * from "./tipagemRotas" +export * from "./tipoFiltro.26" export * from "./unidades_medida" export * from "./uuid" export * from "./variaveisComuns" diff --git a/src/tipoFiltro.26.ts b/src/tipoFiltro.26.ts index 7313f03..44a60d1 100644 --- a/src/tipoFiltro.26.ts +++ b/src/tipoFiltro.26.ts @@ -1,3 +1,5 @@ +import { z } from "zod" + /** * ============================================================================= * tipoFiltro26 @@ -95,7 +97,6 @@ * ============================================================================= */ - /* ============================================================================= OPERADORES POSTGRESQL POR TIPO ============================================================================= */ @@ -123,29 +124,29 @@ type PgOpsBoolean = { in?: boolean[] } - /* ============================================================================= SELEÇÃO AUTOMÁTICA DE OPERADORES BASEADA NO TIPO DO CAMPO ============================================================================= */ -type PgOpsFor = - V extends number ? PgOpsNumber : - V extends string ? PgOpsString : - V extends boolean ? PgOpsBoolean : - never - +type PgOpsFor = V extends number + ? PgOpsNumber + : V extends string + ? PgOpsString + : V extends boolean + ? PgOpsBoolean + : never /* ============================================================================= UTILITÁRIO: DETECTAR OBJETO PLANO ============================================================================= */ -type IsPlainObject = - T extends object - ? T extends Function ? false - : T extends readonly any[] ? false +type IsPlainObject = T extends object + ? T extends Function + ? false + : T extends readonly any[] + ? false : true - : false - + : false /* ============================================================================= FILTRO RECURSIVO POR CAMPOS @@ -157,7 +158,6 @@ type FiltroCampos = { : PgOpsFor } - /* ============================================================================= TIPO PRINCIPAL EXPORTADO ============================================================================= */ @@ -176,7 +176,22 @@ export type tipoFiltro26 = FiltroCampos & { OU?: tipoFiltro26[] } +/* ============================================================================= + VALIDAÇÃO ESTRUTURAL (ZOD) +============================================================================= */ +const zOperadores = z.enum(["=", "!=", ">", ">=", "<", "<=", "like", "in"]) +const zValor = z.any() +const zCondicao = z.record(zOperadores, zValor) + +export const zFiltro26: z.ZodType = z.lazy(() => + z + .object({ + E: z.array(zFiltro26).optional(), + OU: z.array(zFiltro26).optional(), + }) + .catchall(z.union([zCondicao, zFiltro26])), +) /* ============================================================================= EXEMPLO DE USO