@konstit/dne 0.0.2 → 0.1.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.
Files changed (44) hide show
  1. package/README.md +215 -13
  2. package/data/dne.bin +0 -0
  3. package/dist/bairro.d.ts +27 -0
  4. package/dist/bairro.js +9 -0
  5. package/dist/bairro.js.map +1 -0
  6. package/dist/binary-db-errors.d.ts +56 -0
  7. package/dist/binary-db-errors.js +68 -0
  8. package/dist/binary-db-errors.js.map +1 -0
  9. package/dist/binary-db-format.d.ts +192 -0
  10. package/dist/binary-db-format.js +250 -0
  11. package/dist/binary-db-format.js.map +1 -0
  12. package/dist/binary-db-reader.d.ts +114 -0
  13. package/dist/binary-db-reader.js +700 -0
  14. package/dist/binary-db-reader.js.map +1 -0
  15. package/dist/cep.d.ts +50 -0
  16. package/dist/cep.js +184 -0
  17. package/dist/cep.js.map +1 -0
  18. package/dist/errors.d.ts +14 -0
  19. package/dist/errors.js +21 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/index.js +55 -33
  22. package/dist/index.js.map +29 -16
  23. package/dist/library.d.ts +10 -0
  24. package/dist/library.js +8 -0
  25. package/dist/library.js.map +1 -0
  26. package/dist/schema.d.ts +88 -0
  27. package/dist/schema.js +233 -0
  28. package/dist/schema.js.map +1 -0
  29. package/dist/settings.d.ts +34 -0
  30. package/dist/settings.js +35 -0
  31. package/dist/settings.js.map +1 -0
  32. package/dist/sqlite-db-errors.d.ts +40 -0
  33. package/dist/sqlite-db-errors.js +54 -0
  34. package/dist/sqlite-db-errors.js.map +1 -0
  35. package/dist/sqlite-db-reader.d.ts +130 -0
  36. package/dist/sqlite-db-reader.js +307 -0
  37. package/dist/sqlite-db-reader.js.map +1 -0
  38. package/dist/sqlite-db-schema.d.ts +49 -0
  39. package/dist/sqlite-db-schema.js +115 -0
  40. package/dist/sqlite-db-schema.js.map +1 -0
  41. package/dist/types.d.ts +90 -0
  42. package/dist/types.js +49 -0
  43. package/dist/types.js.map +1 -0
  44. package/package.json +17 -4
package/dist/index.js CHANGED
@@ -1,47 +1,69 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{a as S,c as A,d as U,e as L,f as be,o as w}from"./chunks/index-s0h4vdva.js";var gn=Object.freeze(["bash","zsh","fish","powershell"]);import{Database as qr}from"bun:sqlite";import{copyFile as Hr,mkdir as Gr,rename as Zr,rm as X}from"fs/promises";import{basename as zr,dirname as Qr,join as Wr}from"path";class p extends Error{code;exitCode;details;constructor(e,t,n=1,r){super(t);this.code=e;this.exitCode=n;this.details=r;this.name="UserError"}}var bn=/^(?:\d{8}|\d{5}-\d{3})$/,hn=/[\s,;]/;function he(e){let t=e.trim();if(!bn.test(t))throw new p("invalid-cep",`CEP inv\xE1lido '${e}'. Use 01001000 ou 01001-000.`,2,{input:e});return t.replace("-","")}async function*je(e,t,n=process.stdin.isTTY===!0){let r=t?t==="-"?Bun.stdin:Bun.file(t):null;if(t&&t!=="-"&&r&&!await r.exists())throw new p("input-file-not-found",`Arquivo de entrada com CEPs n\xE3o encontrado: ${t}`);for(let o of e)yield o;if(r){yield*Ue(r.stream());return}if(!e.length&&!n)yield*Ue(Bun.stdin.stream())}async function*Ue(e){let t=new TextDecoder,n="";for await(let r of e){let o=n+t.decode(r,{stream:!0}),a=0;for(let i=0;i<o.length;i++){if(!hn.test(o[i]??""))continue;if(i>a)yield o.slice(a,i);a=i+1}n=o.slice(a)}if(n+=t.decode(),n)yield n}import{mkdirSync as In,readFileSync as yt,renameSync as Dn,rmSync as re,statSync as vn,writeFileSync as Nn}from"fs";import{homedir as gt}from"os";import{join as G,resolve as Se}from"path";import{stat as Rn}from"fs/promises";import{resolve as Ln}from"path";import{Database as J}from"bun:sqlite";var yn=[{name:"log_localidade",originalName:"log_localidade",sourceFields:{locNu:0,uf:1,nome:2,cep:3,locNuSub:6,munNu:8},columns:[]},{name:"log_bairro",originalName:"log_bairro",sourceFields:{baiNu:0,uf:1,locNu:2,bairro:3},columns:[]},{name:"log_cpc",originalName:"log_cpc",sourceFields:{uf:1,locNu:2,nome:3,endereco:4,cep:5},columns:[]},{name:"log_logradouro",originalName:"log_logradouro",fileGlob:"LOG_LOGRADOURO_*.TXT",sourceFields:{uf:1,locNu:2,baiNuIni:3,logNo:5,cep:7,tloTx:8,logStaTlo:9},columns:[]},{name:"log_grande_usuario",originalName:"log_grande_usuario",sourceFields:{uf:1,locNu:2,baiNu:3,nome:5,endereco:6,cep:7},columns:[]},{name:"log_unid_oper",originalName:"log_unid_oper",sourceFields:{uf:1,locNu:2,baiNu:3,nome:5,endereco:6,cep:7},columns:[]},{name:"cep_unificado",originalName:"cep_unificado",fileGlob:null,unifiedTable:!0,columns:[{name:"cep",type:"TEXT",primaryKey:!0,comment:"Cont\xE9m somente os oito d\xEDgitos do CEP, sem separadores."},{name:"logradouro",type:"TEXT"},{name:"complemento",type:"TEXT"},{name:"bairro",type:"TEXT"},{name:"municipio",type:"TEXT",notNull:!0},{name:"municipio_cod_ibge",type:"INTEGER",notNull:!0},{name:"uf",type:"TEXT",notNull:!0},{name:"nome",type:"TEXT"}]}];function qe(e={}){return yn.map((t)=>({...t,name:e[t.originalName]??t.name,columns:t.columns.map((n)=>({...n})),sourceFields:t.sourceFields?{...t.sourceFields}:void 0}))}function O(e){let t=e.find((n)=>n.unifiedTable);if(!t)throw Error("Unified schema table not found");return t}function j(e){if(e.unifiedTable)return null;return e.fileGlob??`${e.originalName.toUpperCase()}.TXT`}function F(e,t){if(!e.sourceFields)throw Error(`Source fields for table '${e.originalName}' not found`);return t.map((n)=>{let r=e.sourceFields?.[n];if(r===void 0)throw Error(`Source field '${n}' for table '${e.originalName}' not found`);return r})}var He="dne",Ge="dne.db",E="dne",T="edne_metadata",Ze=32768,ze=-200000,Qe=1000,C="https://www2.correios.com.br/sistemas/edne/download/eDNE_Basico.zip",We=8,K=2097152,Xe=30000,Ye=2,Ke=100,Ve=1000,Je=2000;class k extends Error{constructor(e){super(e);this.name="DneSourceQualityError"}}class ee{db;constructor(e){this.db=new J(e,{readonly:!0}),this.db.run("PRAGMA busy_timeout = 30000")}close(){this.db.close()}hasTable(e){return Boolean(this.db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(e))}metadata(){if(!this.hasTable(T))return null;let e=this.db.query(`SELECT key, value FROM ${g(T)}`).all();return Object.fromEntries(e.map((t)=>[t.key,t.value]))}queryCep(e,t){return this.db.query(`SELECT * FROM ${g(e)} WHERE cep = ?`).get(t)}rowCount(e){return this.db.query(`SELECT count(*) AS count FROM ${g(e)}`).get().count}tableSchema(e){return this.db.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)?.sql??null}querySql(e,t){let n=[],r=this.db.query(e);try{for(let o of r.iterate())if(n.push(o),n.length>t)break}finally{r.finalize()}return{rows:n.slice(0,t),truncated:n.length>t}}}class at{stages=new Map;counter(e,t){let n=this.stage(e),r=this.file(e,t);return{read(){n.read++,r.read++},accept(){n.accepted++,r.accepted++},reject(o){n.rejected++,r.rejected++,nt(n.rejectionReasons,o),nt(r.rejectionReasons,o)}}}assertValid(){let e=Array.from(this.stages.values()).reduce((r,o)=>r+o.rejected,0);if(!e)return;let t=new Map;for(let r of this.stages.values())for(let[o,a]of r.rejectionReasons)t.set(o,(t.get(o)??0)+a);let n=Array.from(t).map(([r,o])=>`${r}=${o}`).join(", ");throw new k(`DNE source quality validation failed: ${e} rejected row(s) (${n})`)}report(e){let t={read:0,accepted:0,rejected:0},n={};for(let[r,o]of this.stages){t.read+=o.read,t.accepted+=o.accepted,t.rejected+=o.rejected;let a={};for(let[i,s]of o.files)a[i]=rt(s);n[r]={...rt(o),files:a}}return{version:1,status:"passed",output_rows:e,totals:t,stages:n}}stage(e){let t=this.stages.get(e);if(!t)t={...tt(),files:new Map},this.stages.set(e,t);return t}file(e,t){let n=this.stage(e),r=n.files.get(t);if(!r)r=tt(),n.files.set(t,r);return r}}class it{db;tableName;batchSize;rows=[];statements=new Map;constructor(e,t,n){this.db=e;this.tableName=t;this.batchSize=n}run(...e){if(this.rows.push(e),this.rows.length>=this.batchSize)this.flush()}flush(){if(!this.rows.length)return;let e=this.rows;this.rows=[];let t=Array.from({length:e.length*8},()=>null);for(let n=0;n<e.length;n++){let r=e[n];if(!r)throw Error(`Missing row at index ${n}`);let o=n*8;t[o]=r[0],t[o+1]=r[1],t[o+2]=r[2],t[o+3]=r[3],t[o+4]=r[4],t[o+5]=r[5],t[o+6]=r[6],t[o+7]=r[7]}this.statementFor(e.length).run(...t)}finalize(){for(let e of this.statements.values())e.finalize();this.statements.clear()}statementFor(e){let t=this.statements.get(e);if(t)return t;let n=Array.from({length:e},()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ");return t=this.db.prepare(`
4
- INSERT INTO ${g(this.tableName)}
5
- (cep, logradouro, complemento, bairro, municipio, municipio_cod_ibge, uf, nome)
3
+ import{a as C,c as F,d as _e,e as O,f as Dt,o as R}from"./chunks/index-s0h4vdva.js";var ai=Object.freeze(["bash","zsh","fish","powershell"]);import{Database as sa}from"bun:sqlite";import{copyFile as ca,mkdir as la,rename as ua,rm as ue}from"fs/promises";import{basename as da,dirname as fa,join as ma}from"path";import{Database as ci}from"bun:sqlite";import{open as li}from"fs/promises";function B(e){return Number.isInteger(e)&&e>0&&e<=4294967295}var me=1,v=256,X=16,Q=Uint8Array.from([68,78,69,66,73,78,0,0]),gn=4294967295,hn=1e5,Ie=100001,Se=10,De=32,P=3,pe=8,Ae=8,K=256,je=32,k=["metadata","cepPrefixOffsets","cepSuffixes","logradouroIds","complementoBitmap","complementoRanks","complementoIds","bairroIds","municipalityIds","nomeBitmap","nomeRanks","nomeIds","municipalities","logradouroDictionary","complementoDictionary","bairroDictionary","municipioDictionary","ufDictionary","nomeDictionary","localidadeFlags","bairros","bairroFaixaOffsets","bairroFaixas","bairroAbreviadoDictionary","localidadeNomeBitmap","localidadeNomeRanks","localidadeNomeIds"];function At(e){return Math.ceil(e/8)*8}function z(e){return Math.ceil(e/8)}function Ge(e,t){return Math.ceil(e*t/8)}function Qe(){let e=new Uint8Array(256);for(let t=1;t<e.length;t++)e[t]=(e[t>>>1]??0)+(t&1);return e}function M(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;return 4}function be(e,t){if(e!==1&&e!==2&&e!==3&&e!==4)throw Error(`Unsupported binary ${t} width: ${e}`);return e}function Te(e){return e===4?4294967295:2**(e*8)-1}function Tt(e,t,n){if(!Number.isSafeInteger(e)||e<0||e>Te(t))throw Error(`Binary ${n} exceeds the ${t}-byte unsigned integer limit: ${e}`)}function q(e,t,n){switch(n){case 1:return e.getUint8(t);case 2:return e.getUint16(t,!0);case 3:return e.getUint8(t)|e.getUint8(t+1)<<8|e.getUint8(t+2)<<16;case 4:return e.getUint32(t,!0)}}function D(e,t,n,r){if(Tt(n,r,"column value"),e[t]=n&255,r>1)e[t+1]=n>>>8&255;if(r>2)e[t+2]=n>>>16&255;if(r>3)e[t+3]=n>>>24&255}function yn(e){if(e.byteLength!==Q.length)return!1;return Q.every((t,n)=>e[n]===t)}function En(e,t,n){if(n<0||n>=1024)throw Error(`CEP suffix exceeds 10 bits: ${n}`);let r=t*10,i=r>>>3,o=r&7,a=n<<o;if(e[i]=(e[i]??0)|a&255,i+1<e.byteLength)e[i+1]=(e[i+1]??0)|a>>>8&255;if(i+2<e.byteLength)e[i+2]=(e[i+2]??0)|a>>>16&255}var Re="4",ge=["M","D","P"],ze=["municipio","distrito","povoado"],Ze=["sem_codificacao_por_logradouro","codificada_por_logradouro","inserida_na_codificacao_por_logradouro","em_codificacao_por_logradouro"],si=[{name:"log_localidade",originalName:"log_localidade",sourceFields:{locNu:0,uf:1,nome:2,cep:3,situacao:4,tipo:5,locNuSub:6,munNu:8},columns:[]},{name:"log_bairro",originalName:"log_bairro",sourceFields:{baiNu:0,uf:1,locNu:2,bairro:3,abreviado:4},columns:[]},{name:"log_faixa_bairro",originalName:"log_faixa_bairro",sourceFields:{baiNu:0,cepInicial:1,cepFinal:2},columns:[]},{name:"log_cpc",originalName:"log_cpc",sourceFields:{uf:1,locNu:2,nome:3,endereco:4,cep:5},columns:[]},{name:"log_logradouro",originalName:"log_logradouro",fileGlob:"LOG_LOGRADOURO_*.TXT",sourceFields:{uf:1,locNu:2,baiNuIni:3,logNo:5,cep:7,tloTx:8,logStaTlo:9},columns:[]},{name:"log_grande_usuario",originalName:"log_grande_usuario",sourceFields:{uf:1,locNu:2,baiNu:3,nome:5,endereco:6,cep:7},columns:[]},{name:"log_unid_oper",originalName:"log_unid_oper",sourceFields:{uf:1,locNu:2,baiNu:3,nome:5,endereco:6,cep:7},columns:[]},{name:"bairros",originalName:"bairros",fileGlob:null,columns:[{name:"bairro_id",type:"INTEGER",primaryKey:!0,check:"bairro_id > 0"},{name:"localidade_id",type:"INTEGER",notNull:!0,check:"localidade_id > 0"},{name:"uf",type:"TEXT",notNull:!0},{name:"nome",type:"TEXT",notNull:!0},{name:"nome_abreviado",type:"TEXT"}]},{name:"bairro_faixas",originalName:"bairro_faixas",fileGlob:null,withoutRowid:!0,columns:[{name:"bairro_id",type:"INTEGER",primaryKey:!0,references:{table:"bairros",column:"bairro_id"}},{name:"cep_inicial",type:"TEXT",primaryKey:!0,check:"length(cep_inicial) = 8 AND cep_inicial NOT GLOB '*[^0-9]*'"},{name:"cep_final",type:"TEXT",primaryKey:!0,check:"length(cep_final) = 8 AND cep_final NOT GLOB '*[^0-9]*' AND cep_inicial <= cep_final"}]},{name:"cep_unificado",originalName:"cep_unificado",fileGlob:null,unifiedTable:!0,columns:[{name:"cep",type:"TEXT",primaryKey:!0,comment:"Cont\xE9m somente os oito d\xEDgitos do CEP, sem separadores."},{name:"logradouro",type:"TEXT"},{name:"complemento",type:"TEXT"},{name:"bairro_id",type:"INTEGER",references:{table:"bairros",column:"bairro_id"}},{name:"localidade_nome",type:"TEXT",comment:"Original district or village name for a locality-wide CEP.",check:"localidade_nome IS NULL OR (bairro_id IS NULL AND localidade_tipo IN ('D', 'P'))"},{name:"municipio",type:"TEXT",notNull:!0},{name:"municipio_cod_ibge",type:"INTEGER",notNull:!0},{name:"uf",type:"TEXT",notNull:!0},{name:"nome",type:"TEXT"},{name:"localidade_situacao",type:"INTEGER",notNull:!0,check:"localidade_situacao IN (0, 1, 2, 3)"},{name:"localidade_tipo",type:"TEXT",notNull:!0,check:"localidade_tipo IN ('M', 'D', 'P')"}]}];function wn(e={}){return si.map((t)=>({...t,name:e[t.originalName]??t.name,columns:t.columns.map((n)=>({...n,...n.references?{references:{...n.references,table:e[n.references.table]??n.references.table}}:{}})),sourceFields:t.sourceFields?{...t.sourceFields}:void 0}))}function J(e){let t=e.find((n)=>n.unifiedTable);if(!t)throw Error("Unified schema table not found");return t}function Ne(e){return e.filter((t)=>t.columns.length>0)}function xe(e){if(e.unifiedTable||e.fileGlob===null)return null;return e.fileGlob??`${e.originalName.toUpperCase()}.TXT`}function ee(e,t){if(!e.sourceFields)throw Error(`Source fields for table '${e.originalName}' not found`);return t.map((n)=>{let r=e.sourceFields?.[n];if(r===void 0)throw Error(`Source field '${n}' for table '${e.originalName}' not found`);return r})}var _n="dne",In="dne.db",T="dne",te="bairros",Ye="bairro_faixas",A="edne_metadata",Sn=32768,Dn=-200000,An=1000,Z="https://www2.correios.com.br/sistemas/edne/download/eDNE_Basico.zip",Tn=8,Ve=2097152,Rn=30000,Nn=2,xn=100,Cn=1000,Ln=2000;var xt=new TextEncoder,ui=Qe();async function vn(e,t,n=T){Ii();let r=new ci(e,{readonly:!0});try{r.run("BEGIN");let i=yi(r,n);if(Lt(i,"row count"),!i)throw Error("Cannot create a binary database without rows");let o=r.query(`SELECT bairro_id, localidade_id, uf, nome, nome_abreviado
4
+ FROM ${Le(te)} ORDER BY bairro_id`).all(),a=new Map(o.map((_,L)=>[_.bairro_id,L+1])),s=M(o.length),l=di(r,n,o),c=fi(l),u=[...l.municipalitiesByIbge.entries()].sort(([_],[L])=>_-L),d=u.length,f=M(d),m=new Map;for(let[_,[L]]of u.entries())m.set(L,_+1);let b=new Uint32Array(Ie),g=new Uint8Array(Ge(i,Se)),w=new Uint8Array(i*c.logradouro.idWidth),h=new Uint8Array(z(i)),I=new Uint8Array(l.complementoCount*c.complemento.idWidth),S=new Uint8Array(i*s),N=new Uint8Array(z(i)),an=new Uint8Array(l.localidadeNomeCount*c.bairro.idWidth),sn=new Uint8Array(i*f),cn=new Uint8Array(i),ln=new Uint8Array(z(i)),un=new Uint8Array(l.nomeCount*c.nome.idWidth),ht=0,yt=0,Et=0,fe=0,dn=-1,x=0;for(let _ of Mn(r,n)){let L=Ct(_.cep);if(L<=dn)throw Error("CEP rows must be unique and ordered");dn=L;let pn=ge.indexOf(_.localidade_tipo);if(pn===-1||![0,1,2,3].includes(_.localidade_situacao))throw Error(`Invalid locality indicators for CEP: ${_.cep}`);cn[x]=pn<<2|_.localidade_situacao;let oi=Math.floor(L/1000);while(fe<=oi)b[fe]=x,fe++;if(En(g,x,L%1000),D(w,x*c.logradouro.idWidth,$n(c.logradouro,_.logradouro),c.logradouro.idWidth),_.complemento!==null)Nt(h,x),D(I,ht*c.complemento.idWidth,Y(c.complemento,_.complemento,"complemento"),c.complemento.idWidth),ht++;let St=_.bairro_id===null?0:a.get(_.bairro_id);if(St===void 0)throw Error(`Unknown bairro_id for CEP: ${_.cep}`);if(D(S,x*s,St,s),_.localidade_nome!==null){if(St!==0||_.localidade_tipo==="M")throw Error(`Invalid subordinate locality name for CEP: ${_.cep}`);Nt(N,x),D(an,Et*c.bairro.idWidth,Y(c.bairro,_.localidade_nome,"localidade_nome"),c.bairro.idWidth),Et++}let bn=m.get(_.municipio_cod_ibge);if(bn===void 0)throw Error(`Missing municipality for IBGE code: ${_.municipio_cod_ibge}`);if(D(sn,x*f,bn,f),_.nome!==null)Nt(ln,x),D(un,yt*c.nome.idWidth,Y(c.nome,_.nome,"nome"),c.nome.idWidth),yt++;x++}if(x!==i)throw Error(`SQLite row count changed while exporting: expected ${i}, got ${x}`);if(ht!==l.complementoCount||yt!==l.nomeCount||Et!==l.localidadeNomeCount)throw Error("SQLite nullable field counts changed while exporting");while(fe<Ie)b[fe]=i,fe++;let fn=M(i),wt=Rt(h,I,i),_t=Rt(ln,un,i),It=Rt(N,an,i),mn=bi(r,a),ni=xt.encode(JSON.stringify(Ei(r))),ri=mi(u,c),ii={bairroDictionary:c.bairro.bytes,bairroAbreviadoDictionary:c.bairroAbreviado.bytes,bairroIds:S,bairros:pi(o,c),bairroFaixaOffsets:mn.offsets,bairroFaixas:mn.ranges,cepPrefixOffsets:_i(b,fn),cepSuffixes:g,complementoBitmap:wt.bitmap,complementoDictionary:c.complemento.bytes,complementoIds:wt.ids,complementoRanks:wt.ranks,localidadeFlags:cn,localidadeNomeBitmap:It.bitmap,localidadeNomeRanks:It.ranks,localidadeNomeIds:It.ids,logradouroDictionary:c.logradouro.bytes,logradouroIds:w,metadata:ni,municipalities:ri,municipalityIds:sn,municipioDictionary:c.municipio.bytes,nomeBitmap:_t.bitmap,nomeDictionary:c.nome.bytes,nomeIds:_t.ids,nomeRanks:_t.ranks,ufDictionary:c.uf.bytes};return await gi(t,i,d,f,fn,ii),r.run("COMMIT"),i}finally{r.close()}}function di(e,t,n){let r={complementoCount:0,localidadeNomeCount:0,municipalitiesByIbge:new Map,nomeCount:0,strings:{bairro:new Set,bairroAbreviado:new Set,complemento:new Set,logradouro:new Set,municipio:new Set,nome:new Set,uf:new Set}};for(let i of n){if(!B(i.bairro_id)||!B(i.localidade_id)||!i.nome||!i.uf)throw Error(`Invalid neighborhood: ${i.bairro_id}`);r.strings.bairro.add(i.nome),Ce(r.strings.bairroAbreviado,i.nome_abreviado),r.strings.uf.add(i.uf)}for(let i of Mn(e,t)){if(Ce(r.strings.logradouro,i.logradouro),Ce(r.strings.complemento,i.complemento),Ce(r.strings.bairro,i.localidade_nome),r.strings.municipio.add(i.municipio),r.strings.uf.add(i.uf),Ce(r.strings.nome,i.nome),i.complemento!==null)r.complementoCount++;if(i.nome!==null)r.nomeCount++;if(i.localidade_nome!==null)r.localidadeNomeCount++;Tt(i.municipio_cod_ibge,3,"municipio_cod_ibge");let o=r.municipalitiesByIbge.get(i.municipio_cod_ibge);if(o&&(o.municipio!==i.municipio||o.uf!==i.uf))throw Error(`IBGE code maps to multiple municipalities: ${i.municipio_cod_ibge}`);r.municipalitiesByIbge.set(i.municipio_cod_ibge,{municipio:i.municipio,uf:i.uf})}return r}function fi(e){return{bairro:ne(e.strings.bairro),bairroAbreviado:ne(e.strings.bairroAbreviado),complemento:ne(e.strings.complemento),logradouro:ne(e.strings.logradouro),municipio:ne(e.strings.municipio),nome:ne(e.strings.nome),uf:ne(e.strings.uf)}}function ne(e){let t=[...e].sort(),n=t.length,r=Math.ceil(n/pe),i=new Uint32Array(r),o=new Uint8Array(n),a=new Uint8Array(n),s=new Map,l=new Uint8Array,c=0;for(let[h,I]of t.entries()){let S=xt.encode(I);if(S.byteLength>255)throw Error(`Binary string exceeds 255 UTF-8 bytes: ${I}`);let N=h%pe===0?0:wi(l,S);if(h%pe===0)i[h>>>P]=c;o[h]=S.byteLength,a[h]=N,c+=S.byteLength-N,Lt(c,"dictionary suffix data length"),s.set(I,h+1),l=S}let u=De,d=u+i.byteLength,f=d+o.byteLength,m=f+a.byteLength,b=new Uint8Array(m+c),g=new DataView(b.buffer);g.setUint32(0,n,!0),g.setUint32(4,r,!0),g.setUint32(8,u,!0),g.setUint32(12,d,!0),g.setUint32(16,f,!0),g.setUint32(20,m,!0),g.setUint32(24,c,!0),g.setUint8(28,M(n)),g.setUint8(29,P),b.set(Ot(i),u),b.set(o,d),b.set(a,f);let w=m;for(let[h,I]of t.entries()){let S=xt.encode(I),N=a[h]??0;b.set(S.subarray(N),w),w+=S.byteLength-N}return{bytes:b,count:n,ids:s,idWidth:M(n)}}function mi(e,t){let n=3+t.municipio.idWidth+t.uf.idWidth,r=new Uint8Array(e.length*n);for(let[i,[o,a]]of e.entries()){let s=i*n;D(r,s,o,3),D(r,s+3,Y(t.municipio,a.municipio,"municipio"),t.municipio.idWidth),D(r,s+3+t.municipio.idWidth,Y(t.uf,a.uf,"uf"),t.uf.idWidth)}return r}function Rt(e,t,n){let r=Math.ceil(n/K),i=new Uint32Array(r+1),o=0;for(let a=0;a<r;a++){i[a]=o;let s=a*(K>>>3),l=Math.min(s+(K>>>3),e.byteLength);for(let c=s;c<l;c++)o+=ui[e[c]??0]??0}return i[r]=o,{bitmap:e,ids:t,ranks:Ot(i)}}function pi(e,t){let n=M(e.at(-1)?.bairro_id??0),r=M(e.reduce((s,l)=>Math.max(s,l.localidade_id),0)),i=n+r+t.bairro.idWidth+t.bairroAbreviado.idWidth+t.uf.idWidth,o=new Uint8Array(X+e.length*i),a=new DataView(o.buffer);a.setUint32(0,e.length,!0),a.setUint8(4,n),a.setUint8(5,r);for(let[s,l]of e.entries()){let c=X+s*i;D(o,c,l.bairro_id,n),c+=n,D(o,c,l.localidade_id,r),c+=r,D(o,c,Y(t.bairro,l.nome,"bairro"),t.bairro.idWidth),c+=t.bairro.idWidth,D(o,c,$n(t.bairroAbreviado,l.nome_abreviado),t.bairroAbreviado.idWidth),c+=t.bairroAbreviado.idWidth,D(o,c,Y(t.uf,l.uf,"uf"),t.uf.idWidth)}return o}function bi(e,t){let n=e.query(`SELECT bairro_id, cep_inicial, cep_final FROM ${Le(Ye)}
5
+ ORDER BY bairro_id, cep_inicial, cep_final`).all(),r=new Uint32Array(t.size+1),i=new Uint8Array(n.length*8),o=new DataView(i.buffer),a=0,s;for(let[l,c]of n.entries()){let u=t.get(c.bairro_id);if(u===void 0)throw Error(`Unknown neighborhood in CEP range: ${c.bairro_id}`);let d=Ct(c.cep_inicial),f=Ct(c.cep_final);if(d>f)throw Error(`Reversed neighborhood CEP range: ${c.bairro_id}`);if(s?.bairro_id===c.bairro_id&&s.cep_inicial===c.cep_inicial&&s.cep_final===c.cep_final)throw Error(`Duplicate neighborhood CEP range: ${c.bairro_id}`);while(a<u)r[a++]=l;o.setUint32(l*8,d,!0),o.setUint32(l*8+4,f,!0),s=c}while(a<r.length)r[a++]=n.length;return{offsets:Ot(r),ranges:i}}async function gi(e,t,n,r,i,o){let a={},s=v;for(let d of k)s=At(s),a[d]={length:o[d].byteLength,offset:s},s+=o[d].byteLength;let l=At(s);Lt(l,"file size");let c=hi({cepPrefixOffsetWidth:i,fileSize:l,municipalityCount:n,municipalityIdWidth:r,rowCount:t,sections:a}),u=await li(e,"w");try{await On(u,c);let d=c.byteLength;for(let f of k){let m=a[f];await Bn(u,m.offset-d),await On(u,o[f]),d=m.offset+m.length}await Bn(u,l-d)}finally{await u.close()}}function hi(e){let t=new Uint8Array(v);t.set(Q,0);let n=new DataView(t.buffer);n.setUint16(8,me,!0),n.setUint16(10,v,!0),n.setUint32(12,e.rowCount,!0),n.setUint32(16,e.fileSize,!0),n.setUint8(20,e.cepPrefixOffsetWidth),n.setUint8(21,e.municipalityIdWidth),n.setUint8(22,Ae),n.setUint8(23,P),n.setUint16(24,k.length,!0),n.setUint32(28,e.municipalityCount,!0);for(let[r,i]of k.entries()){let o=e.sections[i],a=je+r*8;n.setUint32(a,o.offset,!0),n.setUint32(a+4,o.length,!0)}return t}function yi(e,t){return e.query(`SELECT count(*) AS count FROM ${Le(t)}`).get().count}function*Mn(e,t){let n=e.query(`
6
+ SELECT cep, logradouro, complemento, bairro_id, localidade_nome, municipio, municipio_cod_ibge, uf, nome, localidade_situacao, localidade_tipo
7
+ FROM ${Le(t)}
8
+ ORDER BY cep
9
+ `);try{for(let r of n.iterate())yield r}finally{n.finalize()}}function Ei(e){if(!e.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(A))return{};let n=e.query(`SELECT key, value FROM ${Le(A)}`).all();return Object.fromEntries(n.map((r)=>[r.key,r.value]))}function $n(e,t){return t===null?0:Y(e,t,"string")}function Y(e,t,n){let r=e.ids.get(t);if(r===void 0)throw Error(`Missing binary ${n} dictionary value: ${t}`);return r}function Ce(e,t){if(t!==null)e.add(t)}function wi(e,t){let n=Math.min(e.byteLength,t.byteLength),r=0;while(r<n&&e[r]===t[r])r++;return r}function Nt(e,t){let n=t>>>3;e[n]=(e[n]??0)|1<<(t&7)}function _i(e,t){let n=new Uint8Array(e.length*t);for(let r=0;r<e.length;r++)D(n,r*t,e[r]??0,t);return n}function Ct(e){if(!/^\d{8}$/.test(e))throw Error(`Invalid CEP in SQLite database: ${e}`);return Number(e)}function Ii(){let e=new Uint16Array([1]);if(new Uint8Array(e.buffer)[0]!==1)throw Error("Binary database generation requires a little-endian platform")}function Lt(e,t){if(!Number.isSafeInteger(e)||e<0||e>gn)throw Error(`Binary ${t} exceeds the uint32 limit: ${e}`)}function Ot(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}async function On(e,t){await e.write(t)}async function Bn(e,t){if(t>0)await e.write(new Uint8Array(t))}function Le(e){return`"${e.replaceAll('"','""')}"`}class E extends Error{code;exitCode;details;constructor(e,t,n=1,r){super(t);this.code=e;this.exitCode=n;this.details=r;this.name="UserError"}}var Si=/[\s,;]/;function he(e){let t=e.length;if(t!==8&&t!==9)return Number.NaN;if(t===9&&e.charCodeAt(5)!==45)return Number.NaN;let n=e.charCodeAt(0)-48,r=e.charCodeAt(1)-48,i=e.charCodeAt(2)-48,o=e.charCodeAt(3)-48,a=e.charCodeAt(4)-48,s=e.charCodeAt(t-3)-48,l=e.charCodeAt(t-2)-48,c=e.charCodeAt(t-1)-48;if((n|r|i|o|a|s|l|c|9-n|9-r|9-i|9-o|9-a|9-s|9-l|9-c)<0)return Number.NaN;return n*1e7+r*1e6+i*1e5+o*1e4+a*1000+s*100+l*10+c}function Fn(e){let t=e.trim(),n=he(t);if(Number.isNaN(n))return;return String(n).padStart(8,"0")}async function*Pn(e,t,n=process.stdin.isTTY===!0){let r=t?t==="-"?Bun.stdin:Bun.file(t):null;if(t&&t!=="-"&&r&&!await r.exists())throw new E("input-file-not-found",`Arquivo de entrada com CEPs n\xE3o encontrado: ${t}`);for(let i of e)yield i;if(r){yield*Un(r.stream());return}if(!e.length&&!n)yield*Un(Bun.stdin.stream())}async function*Un(e){let t=new TextDecoder,n="";for await(let r of e){let i=n+t.decode(r,{stream:!0}),o=0;for(let a=0;a<i.length;a++){if(!Si.test(i[a]??""))continue;if(a>o)yield i.slice(o,a);o=a+1}n=i.slice(o)}if(n+=t.decode(),n)yield n}import{mkdirSync as Fi,readFileSync as Xn,renameSync as Pi,rmSync as at,statSync as ki,writeFileSync as qi}from"fs";import{homedir as Zn}from"os";import{join as $e,resolve as Ft}from"path";import{stat as Mi}from"fs/promises";import{extname as $i,resolve as Ui}from"path";import{fileURLToPath as Di}from"url";class W extends Error{constructor(e,t){super(e,t);this.name=new.target.name}}class Oe extends W{path;code="IO_ERROR";constructor(e,t){super(`Unable to read binary database: ${e}`,t);this.path=e}}class p extends W{code="INVALID_FORMAT";constructor(e,t){super(e,t)}}class Xe extends W{actualVersion;supportedVersion;code="UNSUPPORTED_VERSION";constructor(e,t){super(`Unsupported binary database version: ${e}. Rebuild the database with build --force.`);this.actualVersion=e;this.supportedVersion=t}}class Be extends W{code="READER_CLOSED";constructor(){super("Binary database is closed")}}var kn={RO:11,AC:12,AM:13,RR:14,PA:15,AP:16,TO:17,MA:21,PI:22,CE:23,RN:24,PB:25,PE:26,AL:27,SE:28,BA:29,MG:31,ES:32,RJ:33,SP:35,PR:41,SC:42,RS:43,MS:50,MT:51,GO:52,DF:53},Ss=Object.keys(kn).map(Ke);function Ke(e){let t=e.trim().toUpperCase();if(!Object.hasOwn(kn,t))throw Error(`Unknown UF: ${e}`);return t}var Wn=new TextDecoder,qn=Qe();async function vt(e){try{if(!await Bun.file(e).exists())return!1;let t=new Uint8Array(await Bun.file(e).slice(0,Q.length).arrayBuffer());return yn(t)}catch(t){throw new Oe(e,{cause:t})}}class ye{bairroCache;data;decodeScratch=new Uint8Array(255);dictionaries;bairros;header;mapped;metadataValue;municipalityCache;constructor(e=Di(new URL("../data/dne.bin",import.meta.url))){let t;try{t=Bun.mmap(e,{shared:!1})}catch(n){throw new Oe(e,{cause:n})}try{let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=Ai(n);Ti(n,r);let i=Ri(n,r),o=Ni(n,r,i);Ci(n,r,i,o);let a=Li(t,r.sections.metadata);this.mapped=t,this.data=n,this.header=r,this.dictionaries=i,this.bairros=o,this.metadataValue=a,this.bairroCache=Array.from({length:i.bairro.count+1}),this.municipalityCache=Array.from({length:r.municipalityCount+1})}catch(n){if(this.mapped=null,this.data=null,n instanceof W)throw n;throw new p("Unable to decode binary database",{cause:n})}}close(){this.bairroCache=[],this.data=null,this.mapped=null,this.municipalityCache=[]}metadata(){return this.metadataValue}queryCep(e){return this.readSafely(()=>{let t=this.findCepIndex(e);return t===-1?void 0:this.readRow(t,e.replace("-",""))})}queryNeighborhood(e){return this.readSafely(()=>{let t=this.findNeighborhoodIndex(e);return t===0?void 0:this.readNeighborhood(t)})}queryNeighborhoodByCep(e){return this.readSafely(()=>{let t=this.findCepIndex(e);if(t===-1)return;let n=this.readNeighborhoodIndex(t);return n===0?void 0:this.readNeighborhood(n)})}queryNeighborhoodCepRanges(e){return this.readSafely(()=>{let t=this.findNeighborhoodIndex(e);if(t===0)return[];let{bairroFaixaOffsets:n,bairroFaixas:r}=this.header.sections,i=this.readUint32(n.offset+(t-1)*4),o=this.readUint32(n.offset+t*4);if(i>o||o>r.length/8)throw new p("Invalid binary neighborhood range offsets");let a=[];for(let s=i;s<o;s++){let l=this.readUint32(r.offset+s*8),c=this.readUint32(r.offset+s*8+4);if(l>c||c>99999999)throw new p("Invalid binary neighborhood CEP range");a.push({cep_inicial:String(l).padStart(8,"0"),cep_final:String(c).padStart(8,"0")})}return a})}rowCount(){return this.header.rowCount}readSafely(e){try{return this.requireData(),e()}catch(t){if(t instanceof W)throw t;throw new p("Unable to decode binary database record",{cause:t})}}findCepIndex(e){let t=he(e);if(Number.isNaN(t))return-1;let n=Math.floor(t/1000),r=t%1000,i=this.header.sections.cepPrefixOffsets,o=this.header.cepPrefixOffsetWidth,a=this.readPackedInteger(i.offset+n*o,o),s=this.readPackedInteger(i.offset+(n+1)*o,o),l=s;if(a>s||s>this.header.rowCount)throw new p(`Invalid binary CEP prefix range: ${n}`);while(a<l){let c=a+(l-a>>>1);if(this.readPacked10(c)<r)a=c+1;else l=c}if(a>=s||this.readPacked10(a)!==r)return-1;return a}findNeighborhoodIndex(e){if(!B(e))return 0;let t=0,n=this.bairros.count;while(t<n){let i=t+(n-t>>>1);if(this.readPackedInteger(this.bairros.recordsOffset+i*this.bairros.recordWidth,this.bairros.originalIdWidth)<e)t=i+1;else n=i}if(t===this.bairros.count)return 0;return this.readPackedInteger(this.bairros.recordsOffset+t*this.bairros.recordWidth,this.bairros.originalIdWidth)===e?t+1:0}readNeighborhoodIndex(e){let t=this.readPackedInteger(this.header.sections.bairroIds.offset+e*this.bairros.idWidth,this.bairros.idWidth);if(t>this.bairros.count)throw new p(`Invalid binary neighborhood index: ${t}`);return t}readNeighborhood(e){let{originalIdWidth:t,localidadeIdWidth:n,recordsOffset:r,recordWidth:i}=this.bairros,o=r+(e-1)*i,a=this.readPackedInteger(o,t);o+=t;let s=this.readPackedInteger(o,n);o+=n;let l=this.readRequiredDictionaryString(this.dictionaries.bairro,this.readPackedInteger(o,this.dictionaries.bairro.idWidth),"bairro");o+=this.dictionaries.bairro.idWidth;let c=this.readDictionaryString(this.dictionaries.bairroAbreviado,this.readPackedInteger(o,this.dictionaries.bairroAbreviado.idWidth));o+=this.dictionaries.bairroAbreviado.idWidth;let u=Ke(this.readRequiredDictionaryString(this.dictionaries.uf,this.readPackedInteger(o,this.dictionaries.uf.idWidth),"uf"));return{bairro_id:a,localidade_id:s,nome:l,nome_abreviado:c,uf:u}}readRow(e,t){let n=this.header.sections,r=this.readPackedInteger(n.municipalityIds.offset+e*this.header.municipalityIdWidth,this.header.municipalityIdWidth);if(r===0||r>this.header.municipalityCount)throw new p(`Invalid binary municipality id: ${r}`);let i=this.readMunicipality(r),o=this.requireData().getUint8(n.localidadeFlags.offset+e),a=Ze[o&3],s=ze[o>>>2];if(a===void 0||s===void 0)throw new p(`Invalid binary locality indicators: ${o}`);let l=this.readNeighborhoodIndex(e),c=this.readSparseId(n.localidadeNomeBitmap,n.localidadeNomeRanks,n.localidadeNomeIds,e,this.dictionaries.bairro.idWidth);if(c!==0&&(l!==0||s==="municipio"))throw new p("Invalid binary subordinate locality name");let u=l===0?c:this.readPackedInteger(this.bairros.recordsOffset+(l-1)*this.bairros.recordWidth+this.bairros.originalIdWidth+this.bairros.localidadeIdWidth,this.dictionaries.bairro.idWidth);if(l!==0&&u===0)throw new p("Null binary neighborhood name");return{bairro:this.readCachedDictionaryString(this.dictionaries.bairro,u,this.bairroCache),cep:t,complemento:this.readDictionaryString(this.dictionaries.complemento,this.readSparseId(n.complementoBitmap,n.complementoRanks,n.complementoIds,e,this.dictionaries.complemento.idWidth)),localidade_situacao:a,localidade_tipo:s,logradouro:this.readDictionaryString(this.dictionaries.logradouro,this.readPackedInteger(n.logradouroIds.offset+e*this.dictionaries.logradouro.idWidth,this.dictionaries.logradouro.idWidth)),municipio:i.municipio,municipio_cod_ibge:i.codigoIbge,nome:this.readDictionaryString(this.dictionaries.nome,this.readSparseId(n.nomeBitmap,n.nomeRanks,n.nomeIds,e,this.dictionaries.nome.idWidth)),uf:i.uf}}readMunicipality(e){let t=this.municipalityCache[e];if(t)return t;let n=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,r=this.header.sections.municipalities.offset+(e-1)*n,i=this.readPackedInteger(r+3,this.dictionaries.municipio.idWidth),o=this.readPackedInteger(r+3+this.dictionaries.municipio.idWidth,this.dictionaries.uf.idWidth),a={codigoIbge:this.readPackedInteger(r,3),municipio:this.readRequiredDictionaryString(this.dictionaries.municipio,i,"municipio"),uf:Ke(this.readRequiredDictionaryString(this.dictionaries.uf,o,"uf"))};return this.municipalityCache[e]=a,a}readSparseId(e,t,n,r,i){let o=this.requireMapped(),a=r>>>3,s=o[e.offset+a]??0,l=r&7;if((s&1<<l)===0)return 0;let c=r>>>Ae,u=this.readUint32(t.offset+c*4),d=c*(K>>>3);for(let f=d;f<a;f++)u+=qn[o[e.offset+f]??0]??0;if(u+=qn[s&(1<<l)-1]??0,(u+1)*i>n.length)throw new p(`Invalid binary sparse id index: ${u}`);return this.readPackedInteger(n.offset+u*i,i)}readDictionaryString(e,t){if(t===0)return null;if(t>e.count)throw new p(`Invalid binary string id: ${t}`);let n=this.requireMapped(),r=t-1,i=r>>>P,o=i<<P,a=this.readUint32(e.blockOffsetsOffset+i*4);if(a>e.suffixDataLength)throw new p(`Invalid binary string block offset: ${a}`);let s=e.suffixDataOffset+a,l=this.decodeScratch,c=0;for(let u=o;u<=r;u++){let d=n[e.lengthsOffset+u]??0,f=n[e.prefixesOffset+u]??0;if(u===o&&f!==0||f>c||f>d)throw new p(`Invalid binary front-coded string: ${t}`);let m=d-f;if(s<e.suffixDataOffset||s+m>e.suffixDataOffset+e.suffixDataLength)throw new p(`Invalid binary string suffix: ${t}`);l.set(n.subarray(s,s+m),f),s+=m,c=d}return Wn.decode(l.subarray(0,c))}readCachedDictionaryString(e,t,n){if(t===0)return null;let r=n[t];if(r!==void 0)return r;let i=this.readDictionaryString(e,t);if(i!==null)n[t]=i;return i}readRequiredDictionaryString(e,t,n){let r=this.readDictionaryString(e,t);if(r===null)throw new p(`Binary database has a null required field: ${n}`);return r}readPacked10(e){let t=this.requireMapped(),n=this.header.sections.cepSuffixes,r=e*Se,i=r>>>3,o=r&7,a=n.offset+i;return((t[a]??0)|(t[a+1]??0)<<8|(t[a+2]??0)<<16)>>>o&1023}readPackedInteger(e,t){return q(this.requireData(),e,t)}readUint32(e){return this.requireData().getUint32(e,!0)}requireData(){if(!this.data)throw new Be;return this.data}requireMapped(){if(!this.mapped)throw new Be;return this.mapped}}function Ai(e){if(e.byteLength<v)throw new p("Binary database header is truncated");for(let r=0;r<Q.length;r++)if(e.getUint8(r)!==Q[r])throw new p("Invalid binary database magic");let t=e.getUint16(8,!0);if(t!==me)throw new Xe(t,me);if(e.getUint16(10,!0)!==v)throw new p("Unsupported binary database header size");if(e.getUint8(22)!==Ae||e.getUint8(23)!==P)throw new p("Unsupported binary database block layout");if(e.getUint16(24,!0)!==k.length)throw new p("Unsupported binary database section table");let n={};for(let[r,i]of k.entries()){let o=je+r*8;n[i]={length:e.getUint32(o+4,!0),offset:e.getUint32(o,!0)}}return{cepPrefixOffsetWidth:be(e.getUint8(20),"CEP prefix offset"),fileSize:e.getUint32(16,!0),municipalityCount:e.getUint32(28,!0),municipalityIdWidth:be(e.getUint8(21),"municipality id"),rowCount:e.getUint32(12,!0),sections:n}}function Ti(e,t){if(t.fileSize!==e.byteLength)throw new p(`Binary database size mismatch: header=${t.fileSize}, actual=${e.byteLength}`);if(!t.rowCount||!t.municipalityCount)throw new p("Binary database must contain rows and municipalities");if(t.rowCount>Te(t.cepPrefixOffsetWidth))throw new p("Binary row count does not fit the CEP prefix offset width");if(t.municipalityCount>Te(t.municipalityIdWidth))throw new p("Binary municipality count does not fit its id width");let n=v;for(let i of k){let o=t.sections[i];if(Oi(e.byteLength,o,i),o.offset<n)throw new p(`Binary section is out of order or overlaps: ${i}`);n=o.offset+o.length}if(t.sections.cepPrefixOffsets.length!==Ie*t.cepPrefixOffsetWidth)throw new p("Binary CEP prefix directory has an invalid length");if(t.sections.cepSuffixes.length!==Ge(t.rowCount,Se))throw new p("Binary CEP suffix column has an invalid length");if(t.sections.complementoBitmap.length!==z(t.rowCount)||t.sections.nomeBitmap.length!==z(t.rowCount)||t.sections.localidadeNomeBitmap.length!==z(t.rowCount))throw new p("Binary nullable bitmap has an invalid length");let r=(Math.ceil(t.rowCount/K)+1)*4;if(t.sections.complementoRanks.length!==r||t.sections.nomeRanks.length!==r||t.sections.localidadeNomeRanks.length!==r)throw new p("Binary sparse rank index has an invalid length")}function Ri(e,t){return{bairro:re(e,t.sections.bairroDictionary,"bairro"),bairroAbreviado:re(e,t.sections.bairroAbreviadoDictionary,"bairro abbreviation"),complemento:re(e,t.sections.complementoDictionary,"complemento"),logradouro:re(e,t.sections.logradouroDictionary,"logradouro"),municipio:re(e,t.sections.municipioDictionary,"municipio"),nome:re(e,t.sections.nomeDictionary,"nome"),uf:re(e,t.sections.ufDictionary,"uf")}}function re(e,t,n){if(t.length<De)throw new p(`Binary ${n} dictionary is truncated`);let r=e.getUint32(t.offset,!0),i=e.getUint32(t.offset+4,!0),o=e.getUint32(t.offset+8,!0),a=e.getUint32(t.offset+12,!0),s=e.getUint32(t.offset+16,!0),l=e.getUint32(t.offset+20,!0),c=e.getUint32(t.offset+24,!0),u=be(e.getUint8(t.offset+28),`${n} dictionary id`);if(e.getUint8(t.offset+29)!==P)throw new p(`Unsupported binary ${n} dictionary block size`);if(i!==Math.ceil(r/pe))throw new p(`Binary ${n} dictionary has an invalid block count`);if(r>Te(u))throw new p(`Binary ${n} dictionary does not fit its id width`);if(o!==De||a!==o+i*4||s!==a+r||l!==s+r||l>t.length||c!==t.length-l)throw new p(`Binary ${n} dictionary has an invalid layout`);let d={blockCount:i,blockOffsetsOffset:t.offset+o,count:r,idWidth:u,lengthsOffset:t.offset+a,prefixesOffset:t.offset+s,region:t,suffixDataLength:c,suffixDataOffset:t.offset+l};if(i&&e.getUint32(d.blockOffsetsOffset,!0)!==0)throw new p(`Binary ${n} dictionary has an invalid first block offset`);return d}function Ni(e,t,n){let r=t.sections.bairros;if(r.length<X)throw new p("Binary neighborhood table is truncated");let i=e.getUint32(r.offset,!0),o=be(e.getUint8(r.offset+4),"original neighborhood id"),a=be(e.getUint8(r.offset+5),"original locality id"),s=o+a+n.bairro.idWidth+n.bairroAbreviado.idWidth+n.uf.idWidth;ie(r,X+i*s,"neighborhood table");let l=r.offset+X,c=0;for(let u=0;u<i;u++){let d=l+u*s,f=q(e,d,o);d+=o;let m=q(e,d,a);d+=a;let b=q(e,d,n.bairro.idWidth);d+=n.bairro.idWidth;let g=q(e,d,n.bairroAbreviado.idWidth);d+=n.bairroAbreviado.idWidth;let w=q(e,d,n.uf.idWidth);if(f<=c||m===0||b===0||b>n.bairro.count||g>n.bairroAbreviado.count||w===0||w>n.uf.count)throw new p(`Invalid binary neighborhood record: ${u}`);c=f}return{count:i,idWidth:M(i),originalIdWidth:o,localidadeIdWidth:a,recordsOffset:l,recordWidth:s}}function xi(e,t,n){let{bairroFaixaOffsets:r,bairroFaixas:i}=t.sections;if(ie(r,(n.count+1)*4,"neighborhood range offsets"),i.length%8!==0||e.getUint32(r.offset,!0)!==0)throw new p("Invalid binary neighborhood range layout");let o=i.length/8,a=0;for(let s=0;s<n.count;s++){let l=e.getUint32(r.offset+(s+1)*4,!0);if(l<a||l>o)throw new p("Invalid binary neighborhood range offsets");let c=-1,u=-1;for(let d=a;d<l;d++){let f=e.getUint32(i.offset+d*8,!0),m=e.getUint32(i.offset+d*8+4,!0);if(f>m||m>99999999||f<c||f===c&&m<=u)throw new p("Invalid binary neighborhood CEP range");c=f,u=m}a=l}if(a!==o)throw new p("Unreferenced binary neighborhood CEP ranges")}function Ci(e,t,n,r){let i=t.sections;ie(i.localidadeFlags,t.rowCount,"locality indicators"),ie(i.logradouroIds,t.rowCount*n.logradouro.idWidth,"logradouro ids"),ie(i.bairroIds,t.rowCount*r.idWidth,"bairro indexes"),ie(i.municipalityIds,t.rowCount*t.municipalityIdWidth,"municipality ids");let o=3+n.municipio.idWidth+n.uf.idWidth;ie(i.municipalities,t.municipalityCount*o,"municipalities"),Bt(e,i.complementoRanks,i.complementoIds,n.complemento.idWidth,"complemento"),Bt(e,i.nomeRanks,i.nomeIds,n.nome.idWidth,"nome"),Bt(e,i.localidadeNomeRanks,i.localidadeNomeIds,n.bairro.idWidth,"localidade_nome"),xi(e,t,r);let a=q(e,i.cepPrefixOffsets.offset,t.cepPrefixOffsetWidth),s=q(e,i.cepPrefixOffsets.offset+hn*t.cepPrefixOffsetWidth,t.cepPrefixOffsetWidth);if(a!==0||s!==t.rowCount)throw new p("Binary CEP prefix directory has invalid boundaries")}function Bt(e,t,n,r,i){let o=e.getUint32(t.offset+t.length-4,!0);if(n.length!==o*r)throw new p(`Binary ${i} sparse ids have an invalid length`)}function Li(e,t){let n=Wn.decode(e.subarray(t.offset,t.offset+t.length)),r;try{r=JSON.parse(n)}catch(i){throw new p("Binary database metadata is invalid JSON",{cause:i})}if(!r||typeof r!=="object"||Array.isArray(r))throw new p("Binary database metadata must be an object");return r}function Oi(e,t,n){if(t.offset<v||t.offset>e||t.length>e-t.offset)throw new p(`Binary ${n} region is outside the file`)}function ie(e,t,n){if(e.length!==t)throw new p(`Binary ${n} region has an invalid length`)}import{Database as vi}from"bun:sqlite";class H extends Error{constructor(e,t){super(e,t);this.name=new.target.name}}class ve extends H{path;code="IO_ERROR";constructor(e,t){super(`Unable to access SQLite database: ${e}`,t);this.path=e}}class Me extends H{code="INVALID_SCHEMA";constructor(e,t){super(e,t)}}class Je extends H{code="INVALID_DATA";constructor(e,t){super(e,t)}}class et extends H{code="QUERY_ERROR";constructor(e,t){super(e,t)}}class tt extends H{code="READER_CLOSED";constructor(){super("SQLite database is closed")}}function Bi(e){return jn(e,", ")}function Hn(e){return jn(e,`,
10
+ `)}function jn(e,t){let n=e.columns.filter((o)=>o.primaryKey).map((o)=>y(o.name)),r=e.columns.map((o)=>{let a=[y(o.name),o.type];if(o.notNull||o.primaryKey)a.push("NOT NULL");if(o.check)a.push(`CHECK (${o.check})`);if(o.references)a.push(`REFERENCES ${y(o.references.table)} (${y(o.references.column)})`);if(o.comment)a.push(`/* ${o.comment} */`);return a.join(" ")});if(n.length)r.push(`PRIMARY KEY (${n.join(", ")})`);let i=e.withoutRowid??e.unifiedTable?" WITHOUT ROWID":"";if(t.includes(`
11
+ `))return`CREATE TABLE IF NOT EXISTS ${y(e.name)} (
12
+ ${r.join(t)}
13
+ )${i}`;return`CREATE TABLE IF NOT EXISTS ${y(e.name)} (${r.join(t)})${i}`}function oe(e){return`${e}_consulta`}function Mt(e,t=te){return`CREATE VIEW ${y(oe(e))} AS
14
+ SELECT d.cep, d.logradouro, d.complemento, COALESCE(b.nome, d.localidade_nome) AS bairro,
15
+ d.municipio, d.municipio_cod_ibge, d.uf, d.nome, d.localidade_situacao, d.localidade_tipo
16
+ FROM ${y(e)} d
17
+ LEFT JOIN ${y(t)} b ON b.bairro_id = d.bairro_id`}function nt(e,t){let n=J(t),r=t.find((o)=>o.originalName==="bairros");if(!r)throw Error("Neighborhood table definition is missing");let i=Ne(t);e.run(`DROP VIEW IF EXISTS main.${y(oe(n.name))}`);for(let o of[...i].reverse())e.run(`DROP TABLE IF EXISTS main.${y(o.name)}`);for(let o of i)e.run(Bi(o));e.run(Mt(n.name,r.name))}function y(e){return`"${e.replaceAll('"','""')}"`}class rt{databasePath;db;closed=!1;normalizedSchemaReady=!1;constructor(e){this.databasePath=e;let t;try{t=new vi(e,{readonly:!0}),t.run("PRAGMA busy_timeout = 30000"),this.db=t}catch(n){try{t?.close()}catch{}throw new ve(e,{cause:n})}}close(){if(this.closed)return;try{this.db.close(),this.closed=!0}catch(e){throw new ve(this.databasePath,{cause:e})}}hasTable(e){return this.readSafely(()=>Boolean(this.db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)))}metadata(){return this.readSafely(()=>{if(!this.hasTable(A))return;let e=this.db.query(`SELECT key, value FROM ${y(A)}`).all();return Object.fromEntries(e.map((t)=>[t.key,t.value]))})}queryCep(e){return this.readSafely(()=>{let t=he(e);if(Number.isNaN(t))return;this.requireCurrentSchema();let n=this.db.query(`SELECT * FROM ${y(oe(T))} WHERE cep = ?`).get(e.length===8?e:`${e.slice(0,5)}${e.slice(6)}`);if(!n)return;if(n.localidade_situacao===void 0||n.localidade_tipo===void 0)throw new Me("Database schema lacks locality indicators. Rebuild the database with build --force.");let r=Ze[n.localidade_situacao],i=ze[ge.indexOf(n.localidade_tipo)];if(r===void 0||i===void 0)throw new Je("Database contains invalid locality indicators. Rebuild the database with build --force.");return{...n,localidade_situacao:r,localidade_tipo:i}})}queryNeighborhood(e){return this.readSafely(()=>{if(!B(e))return;return this.requireCurrentSchema(),this.db.query(`SELECT * FROM ${y(te)} WHERE bairro_id = ?`).get(e)??void 0})}queryNeighborhoodByCep(e){return this.readSafely(()=>{if(Number.isNaN(he(e)))return;return this.requireCurrentSchema(),this.db.query(`
18
+ SELECT b.* FROM ${y(T)} d
19
+ JOIN ${y(te)} b ON b.bairro_id = d.bairro_id
20
+ WHERE d.cep = ?
21
+ `).get(e.replace("-",""))??void 0})}queryNeighborhoodCepRanges(e){return this.readSafely(()=>{if(!B(e))return[];return this.requireCurrentSchema(),this.db.query(`
22
+ SELECT cep_inicial, cep_final FROM ${y(Ye)}
23
+ WHERE bairro_id = ? ORDER BY cep_inicial, cep_final
24
+ `).all(e)})}requireCurrentSchema(){if(!this.normalizedSchemaReady)this.normalizedSchemaReady=Boolean(this.db.query("SELECT 1 FROM sqlite_master WHERE type = 'view' AND name = ?").get(oe(T)));if(!this.normalizedSchemaReady)throw new Me("Database schema lacks normalized neighborhoods. Rebuild the database with build --force.")}rowCount(e){return this.readSafely(()=>this.db.query(`SELECT count(*) AS count FROM ${y(e)}`).get().count)}tableSchema(e){return this.readSafely(()=>this.db.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)?.sql??void 0)}querySql(e,t){return this.readSafely(()=>{let n=[],r=this.db.query(e);try{for(let i of r.iterate())if(n.push(i),n.length>t)break}finally{r.finalize()}return{rows:n.slice(0,t),truncated:n.length>t}})}readSafely(e){if(this.closed)throw new tt;try{return e()}catch(t){if(t instanceof H)throw t;throw new et(t instanceof Error?t.message:String(t),{cause:t})}}}function Gn(e){if(!e.startsWith("sqlite:///")){if(e.includes("://"))throw Error("Only sqlite:/// database URLs are supported");return e}return e.slice(10)}function j(e,t){let n=Gn(e);if(n===":memory:")return n;return Ui(t==="binary"?`${n.slice(0,n.length-$i(n).length)}.bin`:n)}async function it(e,t=T){if(e===":memory:"||!await Bun.file(e).exists())throw new E("database-not-found",`Base n\xE3o encontrada: ${e}`);let n;try{n=await vt(e)?new ye(e):new rt(e)}catch(i){throw new E("database-invalid",`N\xE3o foi poss\xEDvel abrir a base '${e}': ${zn(i)}`)}if(!(n instanceof ye?t===T:n.hasTable(t)))throw n.close(),new E("database-not-ready",`A base '${e}' n\xE3o cont\xE9m a tabela '${t}'. Execute bunx @konstit/dne build primeiro.`);return n}async function ae(e,t=T){if(e===":memory:"||!await Bun.file(e).exists())return $t(e);let n=null;try{n=(await Mi(e)).size}catch{}try{let r=await vt(e),i=r?new ye(e):new rt(e);try{let o=i instanceof ye,a=o?t===T:i.hasTable(t);return{exists:!0,format:r?"binary":"sqlite",metadata:i.metadata()??null,path:e,ready:a,row_count:a?o?i.rowCount():i.rowCount(t):null,schema:a&&!o?i.tableSchema(t)??null:null,size_bytes:n}}finally{i.close()}}catch(r){return{...$t(e),error:zn(r),exists:!0,size_bytes:n}}}function Qn(e){return{...$t(":memory:"),row_count:e}}function $t(e){return{exists:!1,format:null,metadata:null,path:e,ready:!1,row_count:null,schema:null,size_bytes:null}}function zn(e){return e instanceof Error?e.message:String(e)}async function Kn(e){let t=Pt(e.database),n=nr(t),r=Gi(e.source??n?.source??Z),i=Wi(e.expression,t,r,e.packageVersion),o=e.dryRun?"preview":n?"updated":"installed";if(!e.dryRun)await Hi(i,n);return{...i,next_run:rr(i.expression),status:o}}function Jn(e){let t=Pt(e),n=tr(t),r=nr(t);return{command:r?.command??null,database:t,expression:r?.expression??null,id:n,installed:r!==null,next_run:r?rr(r.expression):null,package_version:r?.package_version??null,runner:r?.runner??null,source:r?.source??null,title:n}}async function er(e){let t=Pt(e),n=st(t),r=se(n.metadata)||se(n.runner);try{await Bun.cron.remove(n.title)}catch(i){throw new E("cron-remove-failed",`N\xE3o foi poss\xEDvel remover o agendamento: ${ir(i)}`)}return at(n.metadata,{force:!0}),at(n.runner,{force:!0}),{database:t,id:n.title,removed:r,title:n.title}}function Wi(e,t,n,r){let i=Bun.which("bunx");if(!i)throw new E("bunx-not-found","O execut\xE1vel bunx n\xE3o foi encontrado. Instale o Bun antes de criar o agendamento.");if(/[\r\n\0]/.test(e)||/[\r\n\0]/.test(i))throw new E("invalid-cron-value","A express\xE3o cron e o caminho do bunx n\xE3o podem conter quebras de linha ou bytes nulos.",2);let o=st(t),a=Ft(i),s=`@konstit/dne@${r}`;return{command:[ot(a),ot(s),"build","--db",ot(t),"--source",ot(n),"--quiet"].join(" "),database:t,expression:e,id:o.title,package_version:r,runner:o.runner,source:n,title:o.title}}async function Hi(e,t){let n=st(e.database);Fi(n.directory,{mode:448,recursive:!0});let r=Yn(n.runner),i=Yn(n.metadata);try{Ut(n.runner,ji(e)),await Bun.cron(n.runner,e.expression,e.title),Ut(n.metadata,`${JSON.stringify(e,null,2)}
25
+ `)}catch(o){Vn(n.runner,r),Vn(n.metadata,i);try{if(t)await Bun.cron(t.runner,t.expression,t.title);else await Bun.cron.remove(e.title)}catch{}throw new E("cron-install-failed",`N\xE3o foi poss\xEDvel instalar o agendamento: ${ir(o)}`)}}function ji(e){let t=[Bun.which("bunx"),`@konstit/dne@${e.package_version}`,"build","--db",e.database,"--source",e.source,"--quiet"];if(t[0]===null)throw new E("bunx-not-found","O execut\xE1vel bunx n\xE3o foi encontrado.");return[`const command = ${JSON.stringify(t)};`,"","export default {"," async scheduled() {"," const child = Bun.spawn(command, { stderr: 'inherit', stdout: 'ignore' });"," const exitCode = await child.exited;"," if (exitCode !== 0) {"," throw new Error('@konstit/dne build failed with exit code ' + exitCode);"," }"," },","};",""].join(`
26
+ `)}function Pt(e){let t=j(e);if(t===":memory:")throw new E("invalid-cron-database","O agendamento exige um caminho persistente para a base.",2);if(/[\r\n\0]/.test(t))throw new E("invalid-cron-database","O caminho da base n\xE3o pode conter quebras de linha ou bytes nulos.",2);return t}function Gi(e){if(/[\r\n\0]/.test(e))throw new E("invalid-cron-source","A fonte n\xE3o pode conter quebras de linha ou bytes nulos.",2);return Qi(e)?e:Ft(e)}function tr(e){return`konstit-dne-${new Bun.CryptoHasher("sha256").update(e).digest("hex").slice(0,32)}`}function st(e){let t=tr(e),n=Bun.env.XDG_STATE_HOME?Ft(Bun.env.XDG_STATE_HOME):process.platform==="darwin"?$e(Zn(),"Library","Application Support"):$e(Zn(),".local","state"),r=$e(n,"konstit-dne","cron");return{directory:r,metadata:$e(r,`${t}.json`),runner:$e(r,`${t}.mjs`),title:t}}function nr(e){let t=st(e);if(!se(t.metadata)&&!se(t.runner))return null;if(!se(t.metadata)||!se(t.runner))throw new E("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${t.title}' est\xE1 incompleta.`);try{let n=JSON.parse(Xn(t.metadata,"utf8"));if(n.database!==e||n.id!==t.title||n.title!==t.title||n.runner!==t.runner||typeof n.command!=="string"||typeof n.expression!=="string"||typeof n.package_version!=="string")throw Error("invalid cron metadata");return Bun.cron.parse(n.expression),{...n,source:typeof n.source==="string"?n.source:Z}}catch{throw new E("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${t.title}' \xE9 inv\xE1lida.`)}}function rr(e){return Bun.cron.parse(e)?.toISOString()??null}function Ut(e,t){let n=`${e}.${process.pid}.${crypto.randomUUID()}.tmp`;try{qi(n,t,{mode:384}),Pi(n,e)}finally{at(n,{force:!0})}}function Yn(e){return se(e)?Xn(e,"utf8"):null}function Vn(e,t){if(t===null)at(e,{force:!0});else Ut(e,t)}function se(e){try{return ki(e),!0}catch(t){if(t&&typeof t==="object"&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function ot(e){return`'${e.replaceAll("'","'\\''")}'`}function Qi(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function ir(e){return e instanceof Error?e.message:String(e)}class ce extends Error{constructor(e){super(e);this.name="DneSourceQualityError"}}class kt{stages;constructor(){this.stages=new Map}counter(e,t){let n=this.stage(e),r=this.file(e,t);return{read(){n.read++,r.read++},accept(){n.accepted++,r.accepted++},reject(i){n.rejected++,r.rejected++,ar(n.rejectionReasons,i),ar(r.rejectionReasons,i)}}}assertValid(){let e=Array.from(this.stages.values()).reduce((r,i)=>r+i.rejected,0);if(!e)return;let t=new Map;for(let r of this.stages.values())for(let[i,o]of r.rejectionReasons)t.set(i,(t.get(i)??0)+o);let n=Array.from(t).map(([r,i])=>`${r}=${i}`).join(", ");throw new ce(`DNE source quality validation failed: ${e} rejected row(s) (${n})`)}report(e){let t={read:0,accepted:0,rejected:0},n={};for(let[r,i]of this.stages){t.read+=i.read,t.accepted+=i.accepted,t.rejected+=i.rejected;let o={};for(let[a,s]of i.files)o[a]=sr(s);n[r]={...sr(i),files:o}}return{version:1,status:"passed",output_rows:e,totals:t,stages:n}}stage(e){let t=this.stages.get(e);if(!t)t={...or(),files:new Map},this.stages.set(e,t);return t}file(e,t){let n=this.stage(e),r=n.files.get(t);if(!r)r=or(),n.files.set(t,r);return r}}function or(){return{read:0,accepted:0,rejected:0,rejectionReasons:new Map}}function ar(e,t){e.set(t,(e.get(t)??0)+1)}function sr(e){return{read:e.read,accepted:e.accepted,rejected:e.rejected,rejection_reasons:Object.fromEntries(e.rejectionReasons)}}import{Database as zi}from"bun:sqlite";import{mkdirSync as Wt,readFileSync as Zi,renameSync as Yi,rmSync as ct,statSync as Ht,writeFileSync as lr}from"fs";import{tmpdir as Vi}from"os";import{basename as Xi,dirname as qt,join as Fe}from"path";var Ki=30000,Ji=50,eo=["SIGHUP","SIGINT","SIGTERM"];async function ur(e,t){let n=to(e),r=Fe(qt(e),`.${Xi(e)}.fetch.lock`),i={pid:process.pid,token:crypto.randomUUID()},o=performance.now()+Ki,a=!1;Wt(qt(e),{recursive:!0}),Wt(qt(n),{mode:448,recursive:!0});while(no(r)){if(cr(r))continue;await u()}while(!ro(n,i)){if(cr(n))continue;await u()}if(a)t.finish();let s=!1,l=()=>{if(s)return;s=!0,c(),ao(n,i.token)},c=so(l);return{release:l};async function u(){if(!a)t("Aguardando outra atualiza\xE7\xE3o da base"),a=!0;if(performance.now()>=o)throw new E("update-in-progress",`Outra execu\xE7\xE3o de build j\xE1 est\xE1 atualizando a base '${e}'.`);await Bun.sleep(Ji)}}function to(e){let t=new Bun.CryptoHasher("sha256").update(e).digest("hex");return Fe(Vi(),`konstit-dne-${process.getuid?.()??"unknown"}`,`fetch-${t}.lock`)}function no(e){try{return Ht(e),!0}catch(t){if(Ue(t))return!1;throw t}}function ro(e,t){let n=`${e}.${t.pid}.${t.token}.tmp`;Wt(n);try{return lr(Fe(n,"owner.json"),JSON.stringify(t),{flag:"wx"}),Yi(n,e),!0}catch(r){if(jt(r))return!1;throw r}finally{ct(n,{force:!0,recursive:!0})}}function cr(e){let t;try{t=Ht(e)}catch(r){if(Ue(r))return!0;throw r}if(!t.isDirectory())return io(e);let n=dr(e);if(n&&oo(n.pid))return!1;try{lr(Fe(e,"reaper.json"),JSON.stringify({pid:process.pid,token:crypto.randomUUID()}),{flag:"wx"})}catch(r){if(jt(r))return!1;if(Ue(r))return!0;throw r}return ct(e,{force:!0,recursive:!0}),!0}function io(e){let t=new zi(e);try{t.run("PRAGMA busy_timeout = 0"),t.run("BEGIN IMMEDIATE"),t.run("ROLLBACK")}catch(n){if(co(n))return!1;throw n}finally{t.close()}try{return ct(e,{force:!0}),!0}catch(n){if(Ue(n))return!0;if(jt(n))return!1;try{if(Ht(e).isDirectory())return!1}catch(r){if(Ue(r))return!0;throw r}throw n}}function dr(e){try{let t=JSON.parse(Zi(Fe(e,"owner.json"),"utf8"));return Number.isInteger(t.pid)&&Number(t.pid)>0&&typeof t.token==="string"?{pid:Number(t.pid),token:t.token}:null}catch{return null}}function oo(e){try{return process.kill(e,0),!0}catch(t){return!(t&&typeof t==="object"&&("code"in t)&&t.code==="ESRCH")}}function ao(e,t){if(dr(e)?.token===t)ct(e,{force:!0,recursive:!0})}function so(e){let t=()=>e(),n=eo.map((r)=>{let i=()=>{e(),process.kill(process.pid,r)};return process.once(r,i),{handler:i,signal:r}});return process.once("exit",t),()=>{process.off("exit",t);for(let{handler:r,signal:i}of n)process.off(i,r)}}function jt(e){return Gt(e,"EACCES","EEXIST","ENOTEMPTY","EPERM")}function Ue(e){return Gt(e,"ENOENT")}function Gt(e,...t){return Boolean(e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&t.includes(e.code))}function co(e){if(Gt(e,"SQLITE_BUSY","SQLITE_LOCKED"))return!0;let t=e instanceof Error?e.message:String(e);return/database is locked|database table is locked/i.test(t)}async function fr(){let e=await Bun.file(new URL("../package.json",import.meta.url)).json();if(typeof e.version!=="string"||!e.version)throw Error("package.json has no valid version");return e.version}import{mkdtemp as Yo,rm as Vo}from"fs/promises";import{tmpdir as Xo}from"os";import{join as Yt}from"path";import{mkdir as lo,rename as uo,rm as fo}from"fs/promises";import{basename as ut,dirname as mo,join as hr}from"path";var yr="Delimitado",Er="latin1",Ic=new TextDecoder(Er),po=32,bo=20,go=10,ho=16,yo=30,Eo=28,lt=46,wo=33639248,_o=42,Io=24,So=0,Do=8,Zt=22,Ao=101010256,To=65535,wr=Zt+To,Ro=16,No=12,xo=28,Co=26,mr=30,Lo=67324752;class Qt{path;files;constructor(e){this.path=e;this.files=Array.from(new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0})).sort()}matchingFiles(e){return Dr(this.files,e)}async*readLines(e){yield*Tr(Bun.file(hr(this.path,e)).stream())}}class _r{path;files;entriesByFile;constructor(e,t){this.path=e;this.files=t.map((n)=>ut(n.name)).sort(),this.entriesByFile=new Map(t.map((n)=>[ut(n.name),n]))}matchingFiles(e){return Dr(this.files,e)}async*readLines(e){let t=this.entriesByFile.get(e);if(!t)throw Error(`DNE data file not found: ${e}`);yield*Tr(Ar(this.path,t))}}function Ir(e,t){if(!br(e))return null;let n=new Qt(e);if(!zt(n,t))return n;let r=hr(e,yr);if(!br(r))return null;let i=new Qt(r);return zt(i,t)?null:i}async function Sr(e,t,n){let r=await gr(e),i=vo(r);if(i)return await Fo(e,i,n),pr(n,await gr(n),t);return pr(e,r,t)}function pr(e,t,n){let r=Oo(t,n),i=new _r(e,r);return Bo(i,r,n),i}function Oo(e,t){return e.filter((n)=>Mo(n.name,t))}function Bo(e,t,n){if(!t.length)throw Error("ZIP file does not contain DNE Basico files");let r=zt(e,n);if(r)throw Error(`DNE data file not found: ${r}`)}function vo(e){return e.find((t)=>{let n=ut(t.name).toLowerCase();return n.startsWith("edne_basico_")&&n.endsWith(".zip")})}function br(e){try{return new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0}).next(),!0}catch{return!1}}function zt(e,t){for(let n of t){let r=xe(n);if(r&&e.matchingFiles(r).length===0)return r}return null}function Dr(e,t){if(!t.includes("*"))return e.filter((i)=>i===t);let[n="",r=""]=t.split("*",2);return e.filter((i)=>i.startsWith(n)&&i.endsWith(r))}function Mo(e,t){let n=e.toLowerCase();if(!n.startsWith(`${yr.toLowerCase()}/`))return!1;let r=ut(n);return t.some((i)=>{let o=xe(i)?.toLowerCase();if(!o)return!1;if(!o.includes("*"))return r===o;let[a="",s=""]=o.split("*",2);return r.startsWith(a)&&r.endsWith(s)})}async function gr(e){let t=Bun.file(e),n=t.size;if(n<Zt)throw Error("Source is not a valid ZIP file");let r=Math.max(0,n-wr),i=Buffer.from(await t.slice(r,n).arrayBuffer()),o=Uo(i),a=i.readUInt32LE(o+No),s=i.readUInt32LE(o+Ro),l=s+a;if(l>n)throw Error("Invalid ZIP central directory range");let c=Buffer.from(await t.slice(s,l).arrayBuffer());return $o(c)}function $o(e){let t=[],n=0;while(n<e.length){if(n+lt>e.length||e.readUInt32LE(n)!==wo)throw Error("Invalid ZIP central directory entry");let r=e.readUInt16LE(n+go),i=e.readUInt32LE(n+ho),o=e.readUInt32LE(n+bo),a=e.readUInt32LE(n+Io),s=e.readUInt16LE(n+Eo),l=e.readUInt16LE(n+yo),c=e.readUInt16LE(n+po),u=e.readUInt32LE(n+_o),d=lt+s+l+c;if(n+d>e.length)throw Error("Invalid ZIP central directory entry size");let f=e.subarray(n+lt,n+lt+s).toString("utf8");if(!f.endsWith("/"))t.push({name:f,compression:r,crc32:i,compressedSize:o,uncompressedSize:a,localHeaderOffset:u});n+=d}return t}function Uo(e){for(let t=e.length-Zt;t>=Math.max(0,e.length-wr);t--)if(e.readUInt32LE(t)===Ao)return t;throw Error("Source is not a valid ZIP file")}async function*Ar(e,t){let n=Bun.file(e),r=t.localHeaderOffset+mr,i=Buffer.from(await n.slice(t.localHeaderOffset,r).arrayBuffer());if(i.length!==mr||i.readUInt32LE(0)!==Lo)throw Error(`Invalid ZIP local header for ${t.name}`);let o=i.readUInt16LE(Co),a=i.readUInt16LE(xo),s=r+o+a,l=s+t.compressedSize;if(l>n.size)throw Error(`Invalid ZIP data range for ${t.name}`);let c=n.slice(s,l).stream(),u;if(t.compression===So)u=c;else if(t.compression===Do)u=c.pipeThrough(new DecompressionStream("deflate-raw"));else throw Error(`Unsupported ZIP compression method ${t.compression} for ${t.name}`);let d=0,f=0;for await(let m of u)d+=m.byteLength,f=Bun.hash.crc32(m,f),yield m;if(t.uncompressedSize&&d!==t.uncompressedSize)throw Error(`Invalid decompressed size for ${t.name}`);Po(t,f)}async function Fo(e,t,n){if(await Bun.file(n).exists())return;await lo(mo(n),{recursive:!0});let r=`${n}.${process.pid}.${crypto.randomUUID()}.tmp`,i=Bun.file(r).writer(),o=!1;try{for await(let a of Ar(e,t))await i.write(a);await i.end(),o=!0;try{await uo(r,n)}catch(a){if(!await Bun.file(n).exists())throw a}}finally{if(!o)await Promise.resolve(i.end()).catch(()=>{});await fo(r,{force:!0})}}async function*Tr(e){let t=new TextDecoder(Er),n="";for await(let r of e){let i=n+t.decode(r,{stream:!0}),o=0,a=i.indexOf(`
27
+ `);while(a!==-1){let s=a>o&&i.charCodeAt(a-1)===13?a-1:a;if(s>o)yield i.slice(o,s);o=a+1,a=i.indexOf(`
28
+ `,o)}n=i.slice(o)}if(n+=t.decode(),n.endsWith("\r"))n=n.slice(0,-1);if(n)yield n}function Po(e,t){if(t!==e.crc32)throw Error(`CRC32 mismatch for ${e.name}`)}import{open as xr}from"fs/promises";class Pe extends Error{constructor(e){super(e)}}async function Cr(e,t,n,r={}){let i=Ho(n.contentLength);if(!Wo(n.acceptRanges)||i===null){await Rr(e,t,r);return}try{await ko(e,t,i,r)}catch(o){if(!(o instanceof Pe))throw o;await Rr(e,t,r)}}async function ko(e,t,n,r){let i=Math.ceil(n/Ve),o=await xr(t,"w"),a=new AbortController,s=Or(r.signal,a.signal);try{await o.truncate(n);let l=0,c=Array.from({length:Math.min(i,Tn)},async()=>{while(!0){let u=l++;if(u>=i)return;let d=u*Ve,f=Math.min(d+Ve,n)-1;await qo(e,o,{start:d,end:f},n,{...r,signal:s})}});try{await Promise.all(c)}catch(u){throw a.abort(),await Promise.allSettled(c),u}}finally{await o.close()}}async function qo(e,t,n,r,i){await ke(e,{headers:{"accept-encoding":"identity",range:`bytes=${n.start}-${n.end}`}},async(o)=>{if(o.status!==206){if(await o.body?.cancel(),o.ok)throw new Pe(`Server ignored byte range ${n.start}-${n.end}`);throw Error(`Failed to download ${e}: ${o.status}`)}let a=jo(o.headers.get("content-range"));if(!a||a.start!==n.start||a.end!==n.end||a.length!==r)throw await o.body?.cancel(),new Pe(`Server returned an invalid Content-Range for ${n.start}-${n.end}`);let s=new Uint8Array(await o.arrayBuffer()),l=n.end-n.start+1;if(s.byteLength!==l)throw new Pe(`Server returned ${s.byteLength} bytes for range ${n.start}-${n.end}; expected ${l}`);await Lr(t,s,n.start)},i)}async function Rr(e,t,n){let r=await xr(t,"w");try{await ke(e,{},async(i)=>{if(!i.ok)throw await i.body?.cancel(),Error(`Failed to download ${e}: ${i.status}`);if(!i.body)throw Error(`Failed to stream ${e}: empty response body`);await r.truncate(0);let o=i.body.getReader(),a=0;try{while(!0){let s=await o.read();if(s.done)break;await Lr(r,s.value,a),a+=s.value.byteLength}}catch(s){throw await o.cancel().catch(()=>{}),s}finally{o.releaseLock()}},n)}finally{await r.close()}}async function ke(e,t,n,r={}){let i=r.timeoutMs??Rn,o=r.maxRetries??Nn,a=r.retryBaseDelayMs??xn,s=r.retryMaxDelayMs??Cn,l=r.retryAfterMaxMs??Ln,c;for(let u=0;;u++){Br(r.signal);let d=AbortSignal.timeout(i),f=Or(r.signal,d);try{let m=await fetch(e,{...t,signal:f,verbose:!1});if(Go(m.status)&&u<o){let b=zo(m.headers.get("retry-after"),u,a,s,l);await m.body?.cancel(),await Nr(b,r.signal);continue}c=await n(m);break}catch(m){if(r.signal?.aborted)throw r.signal.reason??m;if(u>=o||!Qo(m))throw m;let b=Math.min(a*2**u,s);await Nr(b,r.signal)}}return c}async function Lr(e,t,n){let r=0;while(r<t.byteLength){let i=await e.write(t,r,t.byteLength-r,n+r);if(!i.bytesWritten)throw Error("Failed to write downloaded content");r+=i.bytesWritten}}function Wo(e){return e?.split(",").some((t)=>t.trim().toLowerCase()==="bytes")??!1}function Ho(e){if(e===null||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function jo(e){let t=e?/^bytes (\d+)-(\d+)\/(\d+)$/i.exec(e):null;if(!t?.[1]||!t[2]||!t[3])return null;return{start:Number(t[1]),end:Number(t[2]),length:Number(t[3])}}function Go(e){return e===408||e===425||e===429||e>=500&&e<=599}function Qo(e){if(!(e instanceof Error))return!1;if(e.name==="AbortError"||e.name==="TimeoutError"||e instanceof TypeError)return!0;let t="code"in e&&typeof e.code==="string"?e.code:void 0;return t==="ECONNRESET"||t==="ECONNREFUSED"||t==="EHOSTUNREACH"||t==="ENETUNREACH"||t==="ETIMEDOUT"||t==="EAI_AGAIN"}function zo(e,t,n,r,i){let o=Zo(e);if(o!==null)return Math.min(o,i);return Math.min(n*2**t,r)}function Zo(e){if(e===null)return null;let t=e.trim();if(/^\d+(?:\.\d+)?$/.test(t))return Number(t)*1000;let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}function Or(e,t){return e?AbortSignal.any([e,t]):t}function Br(e){if(e?.aborted)throw e.reason??new DOMException("The operation was aborted","AbortError")}async function Nr(e,t){if(e<=0){Br(t);return}await new Promise((n,r)=>{let o=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e),a=()=>{clearTimeout(o),r(t?.reason??new DOMException("The operation was aborted","AbortError"))};if(t?.addEventListener("abort",a,{once:!0}),t?.aborted)a()})}class dt{source;options;tempDir;constructor(e,t={}){this.source=e;this.options=t}async resolve(e){try{return await this.resolveSource(this.source??Z,e)}catch(t){throw await this.cleanup(),t}}async cleanup(){if(this.tempDir)await Vo(this.tempDir,{recursive:!0,force:!0}),this.tempDir=void 0}async getTempDir(){return this.tempDir??=await Yo(Yt(Xo(),"edne")),this.tempDir}async resolveSource(e,t){let n=e;if(Jo(e))n=await this.download(e);if(await Bun.file(n).exists()){this.progress("Preparando a fonte ZIP");let i=Yt(await this.getTempDir(),"edne-inner.zip"),o=await Sr(n,t,i);return this.progress("Fonte ZIP pronta"),o}this.progress("Lendo a fonte do diret\xF3rio");let r=Ir(n,t);if(r)return this.progress("Fonte do diret\xF3rio pronta"),r;throw Error(`DNE source not found: ${n}`)}async download(e){let t=this.options.remoteInfo??await ft(e),n=await this.getTempDir(),r=Yt(n,"edne-download.zip");return this.progress("Baixando o arquivo DNE"),await Cr(e,r,t),r}progress(e){this.options.onProgress?.(e)}}async function ft(e,t={}){try{return await ke(e,{method:"HEAD"},async(n)=>{if(!n.ok)throw Error(`Failed to inspect DNE from ${e}: ${n.status}`);return vr(e,n.headers)},t)}catch{return await ke(e,{headers:{"accept-encoding":"identity",range:"bytes=0-0"}},async(n)=>{let r=Ko(e,n);if(await n.body?.cancel(),!n.ok)throw Error(`Failed to inspect DNE from ${e}: ${n.status}`);return r},t)}}function vr(e,t){return{url:e,lastModified:t.get("last-modified"),etag:t.get("etag"),contentLength:t.get("content-length"),acceptRanges:t.get("accept-ranges")}}function Ko(e,t){let n=vr(e,t.headers);if(t.status!==206)return n;let r=/^bytes 0-0\/(\d+)$/i.exec(t.headers.get("content-range")??"");return{...n,contentLength:r?.[1]??null,acceptRanges:n.acceptRanges??"bytes"}}function Jo(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}import{Database as ra}from"bun:sqlite";async function le(e,t,n,r,i){let o=xe(e);if(!o)return;let a=t.matchingFiles(o);if(!a.length)throw Error(`DNE data file not found: ${o}`);for(let s of a){let l=r.counter(e.originalName,s);if(t.readText){let c=await t.readText(s);ta(c,(u,d)=>{l.read(),i($r(c,u,d,n),s,l)});continue}for await(let c of t.readLines(s))l.read(),i(ea(c,n),s,l)}}function ea(e,t){return $r(e,0,e.length,t)}function $r(e,t,n,r){let i=Array.from({length:r.length},()=>null),o=0,a=0,s=t;for(let l=t;l<=n;l++){if(l!==n&&e.charCodeAt(l)!==64)continue;if(a===r[o]){if(i[o]=na(e,s,l),o++,o===r.length)break}a++,s=l+1}return i}function ta(e,t){let n=0;for(let r=0;r<=e.length;r++){if(r!==e.length&&e.charCodeAt(r)!==10)continue;let i=r;if(i>n&&e.charCodeAt(i-1)===13)i--;if(i>n)t(n,i);n=r+1}}function na(e,t,n){if(t===n)return null;let r=e.charCodeAt(t),i=e.charCodeAt(n-1),o=Mr(r)||Mr(i)?e.slice(t,n).trim():e.slice(t,n);return o===""?null:o}function Mr(e){return e<=32||e===160}class Vt{db;tableName;batchSize;rows=[];statements=new Map;constructor(e,t,n){this.db=e;this.tableName=t;this.batchSize=n}run(...e){if(this.rows.push(e),this.rows.length>=this.batchSize)this.flush()}flush(){if(!this.rows.length)return;let e=this.rows;this.rows=[];let t=Array.from({length:e.length*11},()=>null);for(let n=0;n<e.length;n++){let r=e[n];if(!r)throw Error(`Missing row at index ${n}`);let i=n*11;for(let o=0;o<r.length;o++)t[i+o]=r[o]??null}this.statementFor(e.length).run(...t)}finalize(){for(let e of this.statements.values())e.finalize();this.statements.clear()}statementFor(e){let t=this.statements.get(e);if(t)return t;let n=Array.from({length:e},()=>"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").join(", ");return t=this.db.prepare(`
29
+ INSERT INTO ${y(this.tableName)}
30
+ (cep, logradouro, complemento, bairro_id, localidade_nome, municipio, municipio_cod_ibge, uf, nome, localidade_situacao, localidade_tipo)
6
31
  VALUES ${n}
7
- `),this.statements.set(e,t),t}}class Ee{db;tableByOriginalName;unifiedTable;constructor(e,t){this.db=new J(e),this.tableByOriginalName=new Map(t.map((n)=>[n.originalName,n])),this.unifiedTable=O(t)}close(){this.db.run("PRAGMA locking_mode = NORMAL"),this.db.run("PRAGMA wal_checkpoint(TRUNCATE);"),this.db.close()}async loadFromSource(e,t={},n=()=>{}){let r=this.unifiedTable,o=new at;return this.configureBulkLoad(),await this.transaction(async()=>{this.db.run(we(r)),this.createMetadataTable(),this.db.run(`DELETE FROM ${g(r.name)}`),this.db.run(`DELETE FROM ${g(T)}`),n("Lendo munic\xEDpios");let a=await this.readLocalidades(e,o);n("Lendo bairros");let i=await this.readBairros(e,a,o),s=this.prepareUnifiedInsert(r.name);try{if(n("Carregando logradouros"),await this.insertLogradouros(e,s,a,i,o),n("Carregando munic\xEDpios"),this.insertLocalidades(s,a),this.insertLocalidadesSubordinadas(s,a),n("Carregando endere\xE7os especiais"),await this.insertCpcs(e,s,a,o),await this.insertGrandesUsuarios(e,s,a,i,o),await this.insertUnidadesOperacionais(e,s,a,i,o),o.assertValid(),!a.size)throw new k("DNE source quality validation failed: no accepted localidade rows");s.flush();let c=this.rowCount(r.name);if(!c)throw new k("DNE source quality validation failed: no CEP rows produced");let l=o.report(c);this.writeMetadata({...t,quality_report:JSON.stringify(l),quality_rows_accepted:String(l.totals.accepted),quality_rows_read:String(l.totals.read),quality_rows_rejected:String(l.totals.rejected)})}finally{s.finalize()}}),this.rowCount(r.name)}async readLocalidades(e,t){let n=this.originalTable("log_localidade"),r=new Map;await this.forEachSelectedRow(n,e,F(n,["locNu","uf","nome","cep","locNuSub","munNu"]),t,(a,i,s)=>{let[c=null,l=null,u=null,f=null,d=null,m=null]=a,b=H([["locNu",c],["uf",l],["nome",u]]);if(b||!c||!l||!u){s.reject(b??"invalid_structure");return}if(!q(l)){s.reject("invalid_uf");return}if(f!==null&&!V(f)){s.reject("invalid_cep");return}if(m!==null&&!wn(m)){s.reject("invalid_ibge");return}if(r.has(c)){s.reject("duplicate_localidade");return}r.set(c,{uf:l,nome:u,cep:f,locNuSub:d,munNu:m===null?null:Number(m),quality:s})});let o=new Map;for(let[a,i]of r){let s=i.locNuSub?r.get(i.locNuSub):void 0;if(i.locNuSub&&(!s||s.munNu===null)){i.quality.reject("missing_parent_localidade");continue}if(s&&s.uf!==i.uf){i.quality.reject("localidade_uf_mismatch");continue}if(!i.locNuSub&&i.munNu===null){i.quality.reject("missing_ibge");continue}o.set(a,i),i.quality.accept()}return o}async readBairros(e,t,n){let r=this.originalTable("log_bairro"),o=new Map;return await this.forEachSelectedRow(r,e,F(r,["baiNu","uf","locNu","bairro"]),n,(a,i,s)=>{let[c=null,l=null,u=null,f=null]=a,d=H([["baiNu",c],["uf",l],["locNu",u],["bairro",f]]);if(d||!c||!l||!u||!f){s.reject(d??"invalid_structure");return}if(!q(l)){s.reject("invalid_uf");return}let m=t.get(u);if(!m){s.reject("missing_localidade");return}if(m.uf!==l){s.reject("bairro_uf_mismatch");return}if(o.has(c)){s.reject("duplicate_bairro");return}o.set(c,{uf:l,locNu:u,nome:f}),s.accept()}),o}prepareUnifiedInsert(e){return new it(this.db,e,Qe)}rowCount(e){return this.db.query(`SELECT count(*) AS count FROM ${g(e)}`).get().count}async insertLogradouros(e,t,n,r,o){let a=this.originalTable("log_logradouro");await this.forEachSelectedRow(a,e,F(a,["uf","locNu","baiNuIni","logNo","cep","tloTx","logStaTlo"]),o,(i,s,c)=>{let[l=null,u=null,f=null,d=null,m=null,b=null,_=null]=i,y=H([["uf",l],["locNu",u],["baiNuIni",f],["logNo",d],["cep",m]]);if(y||!l||!u||!f||!d||!m){c.reject(y??"invalid_structure");return}if(!q(l)){c.reject("invalid_uf");return}if(!V(m)){c.reject("invalid_cep");return}if(_==="S"&&!b){c.reject("missing_tloTx");return}let h=n.get(u);if(!h){c.reject("missing_localidade");return}let R=r.get(f);if(!R){c.reject("missing_bairro");return}if(h.uf!==l||R.uf!==l){c.reject("logradouro_uf_mismatch");return}if(R.locNu!==u){c.reject("bairro_localidade_mismatch");return}let N=ye(h,n);if(!N){c.reject("missing_municipality");return}t.run(m,_==="S"?`${b} ${d}`:d,null,R.nome,N.nome,N.munNu,l,null),c.accept()})}insertLocalidades(e,t){for(let n of t.values())if(n.cep&&n.locNuSub===null&&n.munNu!==null)e.run(n.cep,null,null,null,n.nome,n.munNu,n.uf,null)}insertLocalidadesSubordinadas(e,t){for(let n of t.values()){let r=n.locNuSub?t.get(n.locNuSub):void 0;if(n.cep&&r?.munNu!==null&&r?.munNu!==void 0)e.run(n.cep,null,null,n.nome,r.nome,r.munNu,n.uf,null)}}async insertCpcs(e,t,n,r){let o=this.originalTable("log_cpc");await this.forEachSelectedRow(o,e,F(o,["uf","locNu","nome","endereco","cep"]),r,(a,i,s)=>{let[c=null,l=null,u=null,f=null,d=null]=a,m=H([["uf",c],["locNu",l],["nome",u],["endereco",f],["cep",d]]);if(m||!c||!l||!u||!f||!d){s.reject(m??"invalid_structure");return}if(!q(c)){s.reject("invalid_uf");return}if(!V(d)){s.reject("invalid_cep");return}let b=n.get(l);if(!b){s.reject("missing_localidade");return}if(b.uf!==c){s.reject("cpc_uf_mismatch");return}let _=ye(b,n);if(!_){s.reject("missing_municipality");return}let[y,h]=et(f);t.run(d,y,h,null,_.nome,_.munNu,c,u),s.accept()})}async insertGrandesUsuarios(e,t,n,r,o){await this.insertNamedAddresses(this.originalTable("log_grande_usuario"),e,t,n,r,o)}async insertUnidadesOperacionais(e,t,n,r,o){await this.insertNamedAddresses(this.originalTable("log_unid_oper"),e,t,n,r,o)}async insertNamedAddresses(e,t,n,r,o,a){await this.forEachSelectedRow(e,t,F(e,["uf","locNu","baiNu","nome","endereco","cep"]),a,(i,s,c)=>{let[l=null,u=null,f=null,d=null,m=null,b=null]=i,_=H([["uf",l],["locNu",u],["baiNu",f],["nome",d],["endereco",m],["cep",b]]);if(_||!l||!u||!f||!d||!m||!b){c.reject(_??"invalid_structure");return}if(!q(l)){c.reject("invalid_uf");return}if(!V(b)){c.reject("invalid_cep");return}let y=r.get(u);if(!y){c.reject("missing_localidade");return}let h=o.get(f);if(!h){c.reject("missing_bairro");return}if(y.uf!==l||h.uf!==l){c.reject("address_uf_mismatch");return}if(h.locNu!==u){c.reject("bairro_localidade_mismatch");return}let R=ye(y,r);if(!R){c.reject("missing_municipality");return}let[N,ge]=et(m);n.run(b,N,ge,h.nome,R.nome,R.munNu,l,d),c.accept()})}async forEachSelectedRow(e,t,n,r,o){let a=j(e);if(!a)return;let i=t.matchingFiles(a);if(!i.length)throw Error(`DNE data file not found: ${a}`);for(let s of i){let c=r.counter(e.originalName,s);if(t.readText){let l=await t.readText(s);_n(l,(u,f)=>{c.read(),o(lt(l,u,f,n),s,c)});continue}for await(let l of t.readLines(s))c.read(),o(Tn(l,n),s,c)}}originalTable(e){let t=this.tableByOriginalName.get(e);if(!t)throw Error(`Table with original name '${e}' not found`);return t}configureBulkLoad(){this.db.run(`PRAGMA page_size = ${Ze}`),this.db.run("PRAGMA journal_mode = OFF"),this.db.run("PRAGMA synchronous = OFF"),this.db.run("PRAGMA temp_store = MEMORY"),this.db.run("PRAGMA locking_mode = EXCLUSIVE"),this.db.run(`PRAGMA cache_size = ${ze}`)}createMetadataTable(){this.db.run(`
8
- CREATE TABLE IF NOT EXISTS ${g(T)} (
32
+ `),this.statements.set(e,t),t}}class Kt{schema;db;tableByOriginalName;unifiedTable;constructor(e,t){this.schema=t;this.db=new ra(e),this.tableByOriginalName=new Map(t.map((n)=>[n.originalName,n])),this.unifiedTable=J(t)}close(){this.db.run("PRAGMA locking_mode = NORMAL"),this.db.run("PRAGMA wal_checkpoint(TRUNCATE);"),this.db.close()}compact(){this.db.run("VACUUM")}async loadFromSource(e,t={},n=()=>{}){let r=this.unifiedTable,i=new kt;return this.configureBulkLoad(),await this.transaction(async()=>{nt(this.db,this.schema),this.createMetadataTable(),this.db.run(`DELETE FROM ${y(A)}`),n("Lendo munic\xEDpios");let o=await this.readLocalidades(e,i);n("Lendo bairros");let a=await this.readBairros(e,o,i);this.insertBairros(a),n("Carregando faixas de CEP dos bairros"),await this.insertFaixasBairro(e,a,i);let s=this.prepareUnifiedInsert(r.name);try{if(n("Carregando logradouros"),await this.insertLogradouros(e,s,o,a,i),n("Carregando munic\xEDpios"),this.insertLocalidades(s,o),this.insertLocalidadesSubordinadas(s,o),n("Carregando endere\xE7os especiais"),await this.insertCpcs(e,s,o,i),await this.insertGrandesUsuarios(e,s,o,a,i),await this.insertUnidadesOperacionais(e,s,o,a,i),i.assertValid(),!o.size)throw new ce("DNE source quality validation failed: no accepted localidade rows");s.flush();let l=this.rowCount(r.name);if(!l)throw new ce("DNE source quality validation failed: no CEP rows produced");let c=i.report(l);this.writeMetadata({...t,schema_version:Re,quality_report:JSON.stringify(c),quality_rows_accepted:String(c.totals.accepted),quality_rows_read:String(c.totals.read),quality_rows_rejected:String(c.totals.rejected)})}finally{s.finalize()}}),this.rowCount(r.name)}async readLocalidades(e,t){let n=this.originalTable("log_localidade"),r=new Map;await le(n,e,ee(n,["locNu","uf","nome","cep","situacao","tipo","locNuSub","munNu"]),t,(o,a,s)=>{let[l=null,c=null,u=null,d=null,f=null,m=null,b=null,g=null]=o,w=We([["locNu",l],["uf",c],["nome",u],["situacao",f],["tipo",m]]);if(w||!l||!c||!u){s.reject(w??"invalid_structure");return}if(!qe(c)){s.reject("invalid_uf");return}if(d!==null&&!Ee(d)){s.reject("invalid_cep");return}if(g!==null&&!oa(g)){s.reject("invalid_ibge");return}if(f!=="0"&&f!=="1"&&f!=="2"&&f!=="3"){s.reject("invalid_localidade_situacao");return}let h=ge.find((I)=>I===m);if(!h){s.reject("invalid_localidade_tipo");return}if(r.has(l)){s.reject("duplicate_localidade");return}r.set(l,{uf:c,nome:u,cep:d,locNuSub:b,munNu:g===null?null:Number(g),situacao:Number(f),tipo:h,quality:s})});let i=new Map;for(let[o,a]of r){let s=a.locNuSub?r.get(a.locNuSub):void 0;if(a.locNuSub&&(!s||s.munNu===null)){a.quality.reject("missing_parent_localidade");continue}if(s&&s.uf!==a.uf){a.quality.reject("localidade_uf_mismatch");continue}if(!a.locNuSub&&a.munNu===null){a.quality.reject("missing_ibge");continue}i.set(o,a),a.quality.accept()}return i}async readBairros(e,t,n){let r=this.originalTable("log_bairro"),i=new Map;return await le(r,e,ee(r,["baiNu","uf","locNu","bairro","abreviado"]),n,(o,a,s)=>{let[l=null,c=null,u=null,d=null,f=null]=o,m=We([["baiNu",l],["uf",c],["locNu",u],["bairro",d]]);if(m||!l||!c||!u||!d){s.reject(m??"invalid_structure");return}let b=Fr(l);if(b===null||Fr(u)===null){s.reject("invalid_bairro_identifier");return}if(!qe(c)){s.reject("invalid_uf");return}let g=t.get(u);if(!g){s.reject("missing_localidade");return}if(g.uf!==c){s.reject("bairro_uf_mismatch");return}if(i.has(l)){s.reject("duplicate_bairro");return}i.set(l,{id:b,uf:c,locNu:u,nome:d,abreviado:f}),s.accept()}),i}insertBairros(e){let t=this.originalTable("bairros"),n=this.db.prepare(`
33
+ INSERT INTO ${y(t.name)} (bairro_id, localidade_id, uf, nome, nome_abreviado) VALUES (?, ?, ?, ?, ?)
34
+ `);try{for(let r of e.values())n.run(r.id,Number(r.locNu),r.uf,r.nome,r.abreviado)}finally{n.finalize()}}async insertFaixasBairro(e,t,n){let r=this.originalTable("log_faixa_bairro"),i=this.originalTable("bairro_faixas"),o=new Set,a=this.db.prepare(`INSERT INTO ${y(i.name)} (bairro_id, cep_inicial, cep_final) VALUES (?, ?, ?)`);try{await le(r,e,ee(r,["baiNu","cepInicial","cepFinal"]),n,(s,l,c)=>{let[u=null,d=null,f=null]=s,m=u===null?void 0:t.get(u);if(!m){c.reject("missing_bairro");return}if(!Ee(d)||!Ee(f)){c.reject("invalid_cep_range");return}if(d>f){c.reject("reversed_cep_range");return}let b=`${m.id}:${d}:${f}`;if(o.has(b)){c.reject("duplicate_cep_range");return}o.add(b),a.run(m.id,d,f),c.accept()})}finally{a.finalize()}}prepareUnifiedInsert(e){return new Vt(this.db,e,An)}rowCount(e){return this.db.query(`SELECT count(*) AS count FROM ${y(e)}`).get().count}async insertLogradouros(e,t,n,r,i){let o=this.originalTable("log_logradouro");await le(o,e,ee(o,["uf","locNu","baiNuIni","logNo","cep","tloTx","logStaTlo"]),i,(a,s,l)=>{let[c=null,u=null,d=null,f=null,m=null,b=null,g=null]=a,w=We([["uf",c],["locNu",u],["baiNuIni",d],["logNo",f],["cep",m]]);if(w||!c||!u||!d||!f||!m){l.reject(w??"invalid_structure");return}if(!qe(c)){l.reject("invalid_uf");return}if(!Ee(m)){l.reject("invalid_cep");return}if(g==="S"&&!b){l.reject("missing_tloTx");return}let h=n.get(u);if(!h){l.reject("missing_localidade");return}let I=r.get(d);if(!I){l.reject("missing_bairro");return}if(h.uf!==c||I.uf!==c){l.reject("logradouro_uf_mismatch");return}if(I.locNu!==u){l.reject("bairro_localidade_mismatch");return}let S=Xt(h,n);if(!S){l.reject("missing_municipality");return}t.run(m,g==="S"?`${b} ${f}`:f,null,I.id,null,S.nome,S.munNu,c,null,h.situacao,h.tipo),l.accept()})}insertLocalidades(e,t){for(let n of t.values())if(n.cep&&n.locNuSub===null&&n.munNu!==null)e.run(n.cep,null,null,null,null,n.nome,n.munNu,n.uf,null,n.situacao,n.tipo)}insertLocalidadesSubordinadas(e,t){for(let n of t.values()){let r=n.locNuSub?t.get(n.locNuSub):void 0;if(n.cep&&r?.munNu!==null&&r?.munNu!==void 0)e.run(n.cep,null,null,null,n.nome,r.nome,r.munNu,n.uf,null,n.situacao,n.tipo)}}async insertCpcs(e,t,n,r){let i=this.originalTable("log_cpc");await le(i,e,ee(i,["uf","locNu","nome","endereco","cep"]),r,(o,a,s)=>{let[l=null,c=null,u=null,d=null,f=null]=o,m=We([["uf",l],["locNu",c],["nome",u],["endereco",d],["cep",f]]);if(m||!l||!c||!u||!d||!f){s.reject(m??"invalid_structure");return}if(!qe(l)){s.reject("invalid_uf");return}if(!Ee(f)){s.reject("invalid_cep");return}let b=n.get(c);if(!b){s.reject("missing_localidade");return}if(b.uf!==l){s.reject("cpc_uf_mismatch");return}let g=Xt(b,n);if(!g){s.reject("missing_municipality");return}let[w,h]=Ur(d);t.run(f,w,h,null,null,g.nome,g.munNu,l,u,b.situacao,b.tipo),s.accept()})}async insertGrandesUsuarios(e,t,n,r,i){await this.insertNamedAddresses(this.originalTable("log_grande_usuario"),e,t,n,r,i)}async insertUnidadesOperacionais(e,t,n,r,i){await this.insertNamedAddresses(this.originalTable("log_unid_oper"),e,t,n,r,i)}async insertNamedAddresses(e,t,n,r,i,o){await le(e,t,ee(e,["uf","locNu","baiNu","nome","endereco","cep"]),o,(a,s,l)=>{let[c=null,u=null,d=null,f=null,m=null,b=null]=a,g=We([["uf",c],["locNu",u],["baiNu",d],["nome",f],["endereco",m],["cep",b]]);if(g||!c||!u||!d||!f||!m||!b){l.reject(g??"invalid_structure");return}if(!qe(c)){l.reject("invalid_uf");return}if(!Ee(b)){l.reject("invalid_cep");return}let w=r.get(u);if(!w){l.reject("missing_localidade");return}let h=i.get(d);if(!h){l.reject("missing_bairro");return}if(w.uf!==c||h.uf!==c){l.reject("address_uf_mismatch");return}if(h.locNu!==u){l.reject("bairro_localidade_mismatch");return}let I=Xt(w,r);if(!I){l.reject("missing_municipality");return}let[S,N]=Ur(m);n.run(b,S,N,h.id,null,I.nome,I.munNu,c,f,w.situacao,w.tipo),l.accept()})}originalTable(e){let t=this.tableByOriginalName.get(e);if(!t)throw Error(`Table with original name '${e}' not found`);return t}configureBulkLoad(){this.db.run(`PRAGMA page_size = ${Sn}`),this.db.run("PRAGMA journal_mode = MEMORY"),this.db.run("PRAGMA foreign_keys = ON"),this.db.run("PRAGMA synchronous = OFF"),this.db.run("PRAGMA temp_store = MEMORY"),this.db.run("PRAGMA locking_mode = EXCLUSIVE"),this.db.run(`PRAGMA cache_size = ${Dn}`)}createMetadataTable(){this.db.run(`
35
+ CREATE TABLE IF NOT EXISTS ${y(A)} (
9
36
  key TEXT PRIMARY KEY NOT NULL,
10
37
  value TEXT NOT NULL
11
38
  )
12
- `)}writeMetadata(e){let t=this.db.prepare(`INSERT INTO ${g(T)} (key, value) VALUES (?, ?)`);try{for(let[n,r]of Object.entries(e))t.run(n,r)}finally{t.finalize()}}async transaction(e){this.db.run("BEGIN");try{await e(),this.db.run("COMMIT")}catch(t){throw this.db.run("ROLLBACK"),t}}}function we(e){return ct(e,", ")}function st(e){return ct(e,`,
13
- `)}function ct(e,t){let n=e.columns.filter((a)=>a.primaryKey).map((a)=>g(a.name)),r=e.columns.map((a)=>{let i=[g(a.name),a.type];if(a.notNull||a.primaryKey)i.push("NOT NULL");if(a.comment)i.push(`/* ${a.comment} */`);return i.join(" ")});if(n.length)r.push(`PRIMARY KEY (${n.join(", ")})`);let o=e.unifiedTable?" WITHOUT ROWID":"";if(t.includes(`
14
- `))return`CREATE TABLE IF NOT EXISTS ${g(e.name)} (
15
- ${r.join(t)}
16
- )${o}`;return`CREATE TABLE IF NOT EXISTS ${g(e.name)} (${r.join(t)})${o}`}function et(e){let t=e.indexOf(",");if(t===-1)return[e.trim(),null];return[e.slice(0,t).trim(),e.slice(t+1).trim()]}var En=new Set(["AC","AL","AM","AP","BA","CE","DF","ES","GO","MA","MG","MS","MT","PA","PB","PE","PI","PR","RJ","RN","RO","RR","RS","SC","SE","SP","TO"]);function q(e){return e!==null&&En.has(e)}function V(e){return e!==null&&/^\d{8}$/.test(e)}function wn(e){if(!/^\d{7}$/.test(e))return!1;let t=Number(e);return Number.isSafeInteger(t)&&t>0}function H(e){let t=e.find(([,n])=>n===null);return t?`missing_${t[0]}`:null}function ye(e,t){let n=e.locNuSub?t.get(e.locNuSub):e;if(!n||n.munNu===null)return null;return{nome:n.nome,munNu:n.munNu}}function tt(){return{read:0,accepted:0,rejected:0,rejectionReasons:new Map}}function nt(e,t){e.set(t,(e.get(t)??0)+1)}function rt(e){return{read:e.read,accepted:e.accepted,rejected:e.rejected,rejection_reasons:Object.fromEntries(e.rejectionReasons)}}function Tn(e,t){return lt(e,0,e.length,t)}function lt(e,t,n,r){let o=Array.from({length:r.length},()=>null),a=0,i=0,s=t;for(let c=t;c<=n;c++){if(c!==n&&e.charCodeAt(c)!==64)continue;if(i===r[a]){if(o[a]=Sn(e,s,c),a++,a===r.length)break}i++,s=c+1}return o}function _n(e,t){let n=0;for(let r=0;r<=e.length;r++){if(r!==e.length&&e.charCodeAt(r)!==10)continue;let o=r;if(o>n&&e.charCodeAt(o-1)===13)o--;if(o>n)t(n,o);n=r+1}}function Sn(e,t,n){if(t===n)return null;let r=e.charCodeAt(t),o=e.charCodeAt(n-1),a=ot(r)||ot(o)?e.slice(t,n).trim():e.slice(t,n);return a===""?null:a}function ot(e){return e<=32||e===160}function g(e){return`"${e.replaceAll('"','""')}"`}function ut(e){if(!e.startsWith("sqlite:///")){if(e.includes("://"))throw Error("Only sqlite:/// database URLs are supported");return e}return e.slice(10)}async function dt(e){if(e!==":memory:"&&!await Bun.file(e).exists())return null;let t=new J(e,{readonly:!0});try{if(!t.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(T))return null;let r=t.query(`SELECT key, value FROM ${g(T)}`).all();return Object.fromEntries(r.map((o)=>[o.key,o.value]))}finally{t.close()}}async function ft(e,t){if(e!==":memory:"&&!await Bun.file(e).exists())return!1;let n=new J(e,{readonly:!0});try{return Boolean(n.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t))}finally{n.close()}}function D(e){let t=ut(e);return t===":memory:"?t:Ln(t)}async function te(e,t=E){if(e===":memory:"||!await Bun.file(e).exists())throw new p("database-not-found",`Base n\xE3o encontrada: ${e}`);let n;try{n=new ee(e)}catch(r){throw new p("database-invalid",`N\xE3o foi poss\xEDvel abrir a base '${e}': ${pt(r)}`)}if(!n.hasTable(t))throw n.close(),new p("database-not-ready",`A base '${e}' n\xE3o cont\xE9m a tabela '${t}'. Execute bunx @konstit/dne build primeiro.`);return n}async function P(e,t=E){if(e===":memory:"||!await Bun.file(e).exists())return Te(e);let n=null;try{n=(await Rn(e)).size}catch{}try{let r=new ee(e);try{let o=r.hasTable(t);return{exists:!0,metadata:r.metadata(),path:e,ready:o,row_count:o?r.rowCount(t):null,schema:o?r.tableSchema(t):null,size_bytes:n}}finally{r.close()}}catch(r){return{...Te(e),error:pt(r),exists:!0,size_bytes:n}}}function mt(e){return{...Te(":memory:"),row_count:e}}function Te(e){return{exists:!1,metadata:null,path:e,ready:!1,row_count:null,schema:null,size_bytes:null}}function pt(e){return e instanceof Error?e.message:String(e)}async function Et(e){let t=Re(e.database),n=St(t),r=$n(e.source??n?.source??C),o=An(e.expression,t,r,e.packageVersion),a=e.dryRun?"preview":n?"updated":"installed";if(!e.dryRun)await Cn(o,n);return{...o,next_run:Rt(o.expression),status:a}}function wt(e){let t=Re(e),n=_t(t),r=St(t);return{command:r?.command??null,database:t,expression:r?.expression??null,id:n,installed:r!==null,next_run:r?Rt(r.expression):null,package_version:r?.package_version??null,runner:r?.runner??null,source:r?.source??null,title:n}}async function Tt(e){let t=Re(e),n=oe(t),r=M(n.metadata)||M(n.runner);try{await Bun.cron.remove(n.title)}catch(o){throw new p("cron-remove-failed",`N\xE3o foi poss\xEDvel remover o agendamento: ${Lt(o)}`)}return re(n.metadata,{force:!0}),re(n.runner,{force:!0}),{database:t,id:n.title,removed:r,title:n.title}}function An(e,t,n,r){let o=Bun.which("bunx");if(!o)throw new p("bunx-not-found","O execut\xE1vel bunx n\xE3o foi encontrado. Instale o Bun antes de criar o agendamento.");if(/[\r\n\0]/.test(e)||/[\r\n\0]/.test(o))throw new p("invalid-cron-value","A express\xE3o cron e o caminho do bunx n\xE3o podem conter quebras de linha ou bytes nulos.",2);let a=oe(t),i=Se(o),s=`@konstit/dne@${r}`;return{command:[ne(i),ne(s),"build","--db",ne(t),"--source",ne(n),"--quiet"].join(" "),database:t,expression:e,id:a.title,package_version:r,runner:a.runner,source:n,title:a.title}}async function Cn(e,t){let n=oe(e.database);In(n.directory,{mode:448,recursive:!0});let r=bt(n.runner),o=bt(n.metadata);try{_e(n.runner,xn(e)),await Bun.cron(n.runner,e.expression,e.title),_e(n.metadata,`${JSON.stringify(e,null,2)}
17
- `)}catch(a){ht(n.runner,r),ht(n.metadata,o);try{if(t)await Bun.cron(t.runner,t.expression,t.title);else await Bun.cron.remove(e.title)}catch{}throw new p("cron-install-failed",`N\xE3o foi poss\xEDvel instalar o agendamento: ${Lt(a)}`)}}function xn(e){let t=[Bun.which("bunx"),`@konstit/dne@${e.package_version}`,"build","--db",e.database,"--source",e.source,"--quiet"];if(t[0]===null)throw new p("bunx-not-found","O execut\xE1vel bunx n\xE3o foi encontrado.");return[`const command = ${JSON.stringify(t)};`,"","export default {"," async scheduled() {"," const child = Bun.spawn(command, { stderr: 'inherit', stdout: 'ignore' });"," const exitCode = await child.exited;"," if (exitCode !== 0) {"," throw new Error('@konstit/dne build failed with exit code ' + exitCode);"," }"," },","};",""].join(`
18
- `)}function Re(e){let t=D(e);if(t===":memory:")throw new p("invalid-cron-database","O agendamento exige um caminho persistente para a base.",2);if(/[\r\n\0]/.test(t))throw new p("invalid-cron-database","O caminho da base n\xE3o pode conter quebras de linha ou bytes nulos.",2);return t}function $n(e){if(/[\r\n\0]/.test(e))throw new p("invalid-cron-source","A fonte n\xE3o pode conter quebras de linha ou bytes nulos.",2);return Mn(e)?e:Se(e)}function _t(e){return`konstit-dne-${new Bun.CryptoHasher("sha256").update(e).digest("hex").slice(0,32)}`}function oe(e){let t=_t(e),n=Bun.env.XDG_STATE_HOME?Se(Bun.env.XDG_STATE_HOME):process.platform==="darwin"?G(gt(),"Library","Application Support"):G(gt(),".local","state"),r=G(n,"konstit-dne","cron");return{directory:r,metadata:G(r,`${t}.json`),runner:G(r,`${t}.mjs`),title:t}}function St(e){let t=oe(e);if(!M(t.metadata)&&!M(t.runner))return null;if(!M(t.metadata)||!M(t.runner))throw new p("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${t.title}' est\xE1 incompleta.`);try{let n=JSON.parse(yt(t.metadata,"utf8"));if(n.database!==e||n.id!==t.title||n.title!==t.title||n.runner!==t.runner||typeof n.command!=="string"||typeof n.expression!=="string"||typeof n.package_version!=="string")throw Error("invalid cron metadata");return Bun.cron.parse(n.expression),{...n,source:typeof n.source==="string"?n.source:C}}catch{throw new p("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${t.title}' \xE9 inv\xE1lida.`)}}function Rt(e){return Bun.cron.parse(e)?.toISOString()??null}function _e(e,t){let n=`${e}.${process.pid}.${crypto.randomUUID()}.tmp`;try{Nn(n,t,{mode:384}),Dn(n,e)}finally{re(n,{force:!0})}}function bt(e){return M(e)?yt(e,"utf8"):null}function ht(e,t){if(t===null)re(e,{force:!0});else _e(e,t)}function M(e){try{return vn(e),!0}catch(t){if(t&&typeof t==="object"&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function ne(e){return`'${e.replaceAll("'","'\\''")}'`}function Mn(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Lt(e){return e instanceof Error?e.message:String(e)}import{Database as On}from"bun:sqlite";import{mkdirSync as Ie,readFileSync as Fn,renameSync as kn,rmSync as ae,statSync as De,writeFileSync as Dt}from"fs";import{tmpdir as Pn}from"os";import{basename as Bn,dirname as Le,join as z}from"path";var Un=30000,jn=50,qn=["SIGHUP","SIGINT","SIGTERM"];async function vt(e,t){let n=Hn(e),r=z(Le(e),`.${Bn(e)}.fetch.lock`),o={pid:process.pid,token:crypto.randomUUID()},a=performance.now()+Un,i=!1;Ie(Le(e),{recursive:!0}),Ie(Le(n),{mode:448,recursive:!0});while(Gn(r)){if(It(r))continue;await u()}while(!Zn(n,o)){if(It(n))continue;await u()}if(i)t.finish();let s=!1,c=()=>{},l=()=>{if(s)return;s=!0,c(),Wn(n,o.token)};return c=Xn(l),{release:l};async function u(){if(!i)t("Aguardando outra atualiza\xE7\xE3o da base"),i=!0;if(performance.now()>=a)throw new p("update-in-progress",`Outra execu\xE7\xE3o de build j\xE1 est\xE1 atualizando a base '${e}'.`);await Bun.sleep(jn)}}function Hn(e){let t=new Bun.CryptoHasher("sha256").update(e).digest("hex");return z(Pn(),`konstit-dne-${process.getuid?.()??"unknown"}`,`fetch-${t}.lock`)}function Gn(e){try{return De(e),!0}catch(t){if(Z(t))return!1;throw t}}function Zn(e,t){let n=`${e}.${t.pid}.${t.token}.tmp`;Ie(n);try{return Dt(z(n,"owner.json"),JSON.stringify(t),{flag:"wx"}),kn(n,e),!0}catch(r){if(ve(r))return!1;throw r}finally{ae(n,{force:!0,recursive:!0})}}function It(e){let t;try{t=De(e)}catch(r){if(Z(r))return!0;throw r}if(!t.isDirectory())return zn(e);let n=Nt(e);if(n&&Qn(n.pid))return!1;try{Dt(z(e,"reaper.json"),JSON.stringify({pid:process.pid,token:crypto.randomUUID()}),{flag:"wx"})}catch(r){if(ve(r))return!1;if(Z(r))return!0;throw r}return ae(e,{force:!0,recursive:!0}),!0}function zn(e){let t=new On(e);try{t.run("PRAGMA busy_timeout = 0"),t.run("BEGIN IMMEDIATE"),t.run("ROLLBACK")}catch(n){if(Yn(n))return!1;throw n}finally{t.close()}try{return ae(e,{force:!0}),!0}catch(n){if(Z(n))return!0;if(ve(n))return!1;try{if(De(e).isDirectory())return!1}catch(r){if(Z(r))return!0;throw r}throw n}}function Nt(e){try{let t=JSON.parse(Fn(z(e,"owner.json"),"utf8"));return Number.isInteger(t.pid)&&Number(t.pid)>0&&typeof t.token==="string"?{pid:Number(t.pid),token:t.token}:null}catch{return null}}function Qn(e){try{return process.kill(e,0),!0}catch(t){return!(t&&typeof t==="object"&&("code"in t)&&t.code==="ESRCH")}}function Wn(e,t){if(Nt(e)?.token===t)ae(e,{force:!0,recursive:!0})}function Xn(e){let t=()=>e(),n=qn.map((r)=>{let o=()=>{e(),process.kill(process.pid,r)};return process.once(r,o),{handler:o,signal:r}});return process.once("exit",t),()=>{process.off("exit",t);for(let{handler:r,signal:o}of n)process.off(o,r)}}function ve(e){return Ne(e,"EACCES","EEXIST","ENOTEMPTY","EPERM")}function Z(e){return Ne(e,"ENOENT")}function Ne(e,...t){return Boolean(e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&t.includes(e.code))}function Yn(e){if(Ne(e,"SQLITE_BUSY","SQLITE_LOCKED"))return!0;let t=e instanceof Error?e.message:String(e);return/database is locked|database table is locked/i.test(t)}import{mkdtemp as Fr,rm as kr}from"fs/promises";import{tmpdir as Pr}from"os";import{join as $e}from"path";import{mkdir as Kn,rename as Vn,rm as Jn}from"fs/promises";import{basename as se,dirname as er,join as Mt}from"path";var Ot="Delimitado",Ft="latin1",Sa=new TextDecoder(Ft),tr=32,nr=20,rr=10,or=16,ar=30,ir=28,ie=46,sr=33639248,cr=42,lr=24,ur=0,dr=8,xe=22,fr=101010256,mr=65535,kt=xe+mr,pr=16,gr=12,br=28,hr=26,At=30,yr=67324752;class Ae{path;files;constructor(e){this.path=e;this.files=Array.from(new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0})).sort()}matchingFiles(e){return jt(this.files,e)}async*readLines(e){yield*Ht(Bun.file(Mt(this.path,e)).stream())}}class Pt{path;files;entriesByFile;constructor(e,t){this.path=e;this.files=t.map((n)=>se(n.name)).sort(),this.entriesByFile=new Map(t.map((n)=>[se(n.name),n]))}matchingFiles(e){return jt(this.files,e)}async*readLines(e){let t=this.entriesByFile.get(e);if(!t)throw Error(`DNE data file not found: ${e}`);yield*Ht(qt(this.path,t))}}function Bt(e,t){if(!xt(e))return null;let n=new Ae(e);if(!Ce(n,t))return n;let r=Mt(e,Ot);if(!xt(r))return null;let o=new Ae(r);return Ce(o,t)?null:o}async function Ut(e,t,n){let r=await $t(e),o=Tr(r);if(o)return await Lr(e,o,n),Ct(n,await $t(n),t);return Ct(e,r,t)}function Ct(e,t,n){let r=Er(t,n),o=new Pt(e,r);return wr(o,r,n),o}function Er(e,t){return e.filter((n)=>_r(n.name,t))}function wr(e,t,n){if(!t.length)throw Error("ZIP file does not contain DNE Basico files");let r=Ce(e,n);if(r)throw Error(`DNE data file not found: ${r}`)}function Tr(e){return e.find((t)=>{let n=se(t.name).toLowerCase();return n.startsWith("edne_basico_")&&n.endsWith(".zip")})}function xt(e){try{return new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0}).next(),!0}catch{return!1}}function Ce(e,t){for(let n of t){let r=j(n);if(r&&e.matchingFiles(r).length===0)return r}return null}function jt(e,t){if(!t.includes("*"))return e.filter((o)=>o===t);let[n="",r=""]=t.split("*",2);return e.filter((o)=>o.startsWith(n)&&o.endsWith(r))}function _r(e,t){let n=e.toLowerCase();if(!n.startsWith(`${Ot.toLowerCase()}/`))return!1;let r=se(n);return t.some((o)=>{let a=j(o)?.toLowerCase();if(!a)return!1;if(!a.includes("*"))return r===a;let[i="",s=""]=a.split("*",2);return r.startsWith(i)&&r.endsWith(s)})}async function $t(e){let t=Bun.file(e),n=t.size;if(n<xe)throw Error("Source is not a valid ZIP file");let r=Math.max(0,n-kt),o=Buffer.from(await t.slice(r,n).arrayBuffer()),a=Rr(o),i=o.readUInt32LE(a+gr),s=o.readUInt32LE(a+pr),c=s+i;if(c>n)throw Error("Invalid ZIP central directory range");let l=Buffer.from(await t.slice(s,c).arrayBuffer());return Sr(l)}function Sr(e){let t=[],n=0;while(n<e.length){if(n+ie>e.length||e.readUInt32LE(n)!==sr)throw Error("Invalid ZIP central directory entry");let r=e.readUInt16LE(n+rr),o=e.readUInt32LE(n+or),a=e.readUInt32LE(n+nr),i=e.readUInt32LE(n+lr),s=e.readUInt16LE(n+ir),c=e.readUInt16LE(n+ar),l=e.readUInt16LE(n+tr),u=e.readUInt32LE(n+cr),f=ie+s+c+l;if(n+f>e.length)throw Error("Invalid ZIP central directory entry size");let d=e.subarray(n+ie,n+ie+s).toString("utf8");if(!d.endsWith("/"))t.push({name:d,compression:r,crc32:o,compressedSize:a,uncompressedSize:i,localHeaderOffset:u});n+=f}return t}function Rr(e){for(let t=e.length-xe;t>=Math.max(0,e.length-kt);t--)if(e.readUInt32LE(t)===fr)return t;throw Error("Source is not a valid ZIP file")}async function*qt(e,t){let n=Bun.file(e),r=t.localHeaderOffset+At,o=Buffer.from(await n.slice(t.localHeaderOffset,r).arrayBuffer());if(o.length!==At||o.readUInt32LE(0)!==yr)throw Error(`Invalid ZIP local header for ${t.name}`);let a=o.readUInt16LE(hr),i=o.readUInt16LE(br),s=r+a+i,c=s+t.compressedSize;if(c>n.size)throw Error(`Invalid ZIP data range for ${t.name}`);let l=n.slice(s,c).stream(),u;if(t.compression===ur)u=l;else if(t.compression===dr)u=l.pipeThrough(new DecompressionStream("deflate-raw"));else throw Error(`Unsupported ZIP compression method ${t.compression} for ${t.name}`);let f=0,d=0;for await(let m of u)f+=m.byteLength,d=Bun.hash.crc32(m,d),yield m;if(t.uncompressedSize&&f!==t.uncompressedSize)throw Error(`Invalid decompressed size for ${t.name}`);Ir(t,d)}async function Lr(e,t,n){if(await Bun.file(n).exists())return;await Kn(er(n),{recursive:!0});let r=`${n}.${process.pid}.${crypto.randomUUID()}.tmp`,o=Bun.file(r).writer(),a=!1;try{for await(let i of qt(e,t))await o.write(i);await o.end(),a=!0;try{await Vn(r,n)}catch(i){if(!await Bun.file(n).exists())throw i}}finally{if(!a)await Promise.resolve(o.end()).catch(()=>{});await Jn(r,{force:!0})}}async function*Ht(e){let t=new TextDecoder(Ft),n="";for await(let r of e){let o=n+t.decode(r,{stream:!0}),a=0,i=o.indexOf(`
19
- `);while(i!==-1){let s=i>a&&o.charCodeAt(i-1)===13?i-1:i;if(s>a)yield o.slice(a,s);a=i+1,i=o.indexOf(`
20
- `,a)}n=o.slice(a)}if(n+=t.decode(),n.endsWith("\r"))n=n.slice(0,-1);if(n)yield n}function Ir(e,t){if(t!==e.crc32)throw Error(`CRC32 mismatch for ${e.name}`)}import{open as zt}from"fs/promises";class Q extends Error{constructor(e){super(e)}}async function Qt(e,t,n,r={}){let o=Ar(n.contentLength);if(!Nr(n.acceptRanges)||o===null){await Gt(e,t,r);return}try{await Dr(e,t,o,r)}catch(a){if(!(a instanceof Q))throw a;await Gt(e,t,r)}}async function Dr(e,t,n,r){let o=Math.ceil(n/K),a=await zt(t,"w"),i=new AbortController,s=Xt(r.signal,i.signal);try{await a.truncate(n);let c=0,l=Array.from({length:Math.min(o,We)},async()=>{while(!0){let u=c++;if(u>=o)return;let f=u*K,d=Math.min(f+K,n)-1;await vr(e,a,{start:f,end:d},n,{...r,signal:s})}});try{await Promise.all(l)}catch(u){throw i.abort(),await Promise.allSettled(l),u}}finally{await a.close()}}async function vr(e,t,n,r,o){await W(e,{headers:{"accept-encoding":"identity",range:`bytes=${n.start}-${n.end}`}},async(a)=>{if(a.status!==206){if(await a.body?.cancel(),a.ok)throw new Q(`Server ignored byte range ${n.start}-${n.end}`);throw Error(`Failed to download ${e}: ${a.status}`)}let i=Cr(a.headers.get("content-range"));if(!i||i.start!==n.start||i.end!==n.end||i.length!==r)throw await a.body?.cancel(),new Q(`Server returned an invalid Content-Range for ${n.start}-${n.end}`);let s=new Uint8Array(await a.arrayBuffer()),c=n.end-n.start+1;if(s.byteLength!==c)throw new Q(`Server returned ${s.byteLength} bytes for range ${n.start}-${n.end}; expected ${c}`);await Wt(t,s,n.start)},o)}async function Gt(e,t,n){let r=await zt(t,"w");try{await W(e,{},async(o)=>{if(!o.ok)throw await o.body?.cancel(),Error(`Failed to download ${e}: ${o.status}`);if(!o.body)throw Error(`Failed to stream ${e}: empty response body`);await r.truncate(0);let a=o.body.getReader(),i=0;try{while(!0){let s=await a.read();if(s.done)break;await Wt(r,s.value,i),i+=s.value.byteLength}}catch(s){throw await a.cancel().catch(()=>{}),s}finally{a.releaseLock()}},n)}finally{await r.close()}}async function W(e,t,n,r={}){let o=r.timeoutMs??Xe,a=r.maxRetries??Ye,i=r.retryBaseDelayMs??Ke,s=r.retryMaxDelayMs??Ve,c=r.retryAfterMaxMs??Je;for(let l=0;;l++){Yt(r.signal);let u=AbortSignal.timeout(o),f=Xt(r.signal,u);try{let d=await fetch(e,{...t,signal:f,verbose:!1});if(xr(d.status)&&l<a){let m=Mr(d.headers.get("retry-after"),l,i,s,c);await d.body?.cancel(),await Zt(m,r.signal);continue}return await n(d)}catch(d){if(r.signal?.aborted)throw r.signal.reason??d;if(l>=a||!$r(d))throw d;let m=Math.min(i*2**l,s);await Zt(m,r.signal)}}}async function Wt(e,t,n){let r=0;while(r<t.byteLength){let o=await e.write(t,r,t.byteLength-r,n+r);if(!o.bytesWritten)throw Error("Failed to write downloaded content");r+=o.bytesWritten}}function Nr(e){return e?.split(",").some((t)=>t.trim().toLowerCase()==="bytes")??!1}function Ar(e){if(e===null||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function Cr(e){let t=e?/^bytes (\d+)-(\d+)\/(\d+)$/i.exec(e):null;if(!t?.[1]||!t[2]||!t[3])return null;return{start:Number(t[1]),end:Number(t[2]),length:Number(t[3])}}function xr(e){return e===408||e===425||e===429||e>=500&&e<=599}function $r(e){if(!(e instanceof Error))return!1;if(e.name==="AbortError"||e.name==="TimeoutError"||e instanceof TypeError)return!0;let t="code"in e&&typeof e.code==="string"?e.code:void 0;return t==="ECONNRESET"||t==="ECONNREFUSED"||t==="EHOSTUNREACH"||t==="ENETUNREACH"||t==="ETIMEDOUT"||t==="EAI_AGAIN"}function Mr(e,t,n,r,o){let a=Or(e);if(a!==null)return Math.min(a,o);return Math.min(n*2**t,r)}function Or(e){if(e===null)return null;let t=e.trim();if(/^\d+(?:\.\d+)?$/.test(t))return Number(t)*1000;let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}function Xt(e,t){return e?AbortSignal.any([e,t]):t}function Yt(e){if(e?.aborted)throw e.reason??new DOMException("The operation was aborted","AbortError")}async function Zt(e,t){if(e<=0){Yt(t);return}await new Promise((n,r)=>{let a=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e),i=()=>{clearTimeout(a),r(t?.reason??new DOMException("The operation was aborted","AbortError"))};if(t?.addEventListener("abort",i,{once:!0}),t?.aborted)i()})}class ce{source;options;tempDir;constructor(e,t={}){this.source=e;this.options=t}async resolve(e){try{return await this.resolveSource(this.source??C,e)}catch(t){throw await this.cleanup(),t}}async cleanup(){if(this.tempDir)await kr(this.tempDir,{recursive:!0,force:!0}),this.tempDir=void 0}async getTempDir(){return this.tempDir??=await Fr($e(Pr(),"edne")),this.tempDir}async resolveSource(e,t){let n=e;if(Ur(e))n=await this.download(e);if(await Bun.file(n).exists()){this.progress("Preparando a fonte ZIP");let o=$e(await this.getTempDir(),"edne-inner.zip"),a=await Ut(n,t,o);return this.progress("Fonte ZIP pronta"),a}this.progress("Lendo a fonte do diret\xF3rio");let r=Bt(n,t);if(r)return this.progress("Fonte do diret\xF3rio pronta"),r;throw Error(`DNE source not found: ${n}`)}async download(e){let t=this.options.remoteInfo??await le(e),n=await this.getTempDir(),r=$e(n,"edne-download.zip");return this.progress("Baixando o arquivo DNE"),await Qt(e,r,t),r}progress(e){this.options.onProgress?.(e)}}async function le(e,t={}){try{return await W(e,{method:"HEAD"},async(n)=>{if(!n.ok)throw Error(`Failed to inspect DNE from ${e}: ${n.status}`);return Kt(e,n.headers)},t)}catch{return await W(e,{headers:{"accept-encoding":"identity",range:"bytes=0-0"}},async(n)=>{let r=Br(e,n);if(await n.body?.cancel(),!n.ok)throw Error(`Failed to inspect DNE from ${e}: ${n.status}`);return r},t)}}function Kt(e,t){return{url:e,lastModified:t.get("last-modified"),etag:t.get("etag"),contentLength:t.get("content-length"),acceptRanges:t.get("accept-ranges")}}function Br(e,t){let n=Kt(e,t.headers);if(t.status!==206)return n;let r=/^bytes 0-0\/(\d+)$/i.exec(t.headers.get("content-range")??"");return{...n,contentLength:r?.[1]??null,acceptRanges:n.acceptRanges??"bytes"}}function Ur(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Vt(e,t){if(e.source_kind!=="remote"||e.source_url!==t.url)return!1;let n=[Me(e.source_etag,t.etag),Me(e.source_last_modified,t.lastModified),Me(e.source_content_length,t.contentLength)].filter((r)=>r!==null);return n.length>0&&n.every(Boolean)}function Jt(e,t,n){let r={loaded_at:new Date().toISOString(),package_version:n,source_input:e,source_kind:t||jr(e)?"remote":"local"};if(t)r.source_url=t.url,r.source_last_modified=t.lastModified??"",r.source_etag=t.etag??"",r.source_content_length=t.contentLength??"";return r}function Me(e,t){if(!t)return null;return e===t}function jr(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}var Xr="0 0 * * 5",Oe="\x1B[0m",Yr="\x1B[1m",Kr="\x1B[36m",Vr="\x1B[90m",Jr=/(--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$)|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:]]|[^\]])*]|\b(?:CREATE|TABLE|IF|NOT|EXISTS|TEXT|INTEGER|NULL|PRIMARY|KEY|WITHOUT|ROWID)\b)/gi,me="pt-BR",eo=new Intl.NumberFormat(me),to=new Intl.NumberFormat(me,{maximumFractionDigits:1,minimumFractionDigits:1}),no=new Intl.NumberFormat(me,{maximumFractionDigits:1}),on=1,de=2,ro=3,pe=await No(),an=A("db",S.string,{default:Ge,describe:"Caminho da base SQLite.",global:!0,valueHint:"file",valueName:"CAMINHO"}),sn=L("json",{describe:"Gravar um envelope JSON est\xE1vel em stdout.",global:!0}),cn=L("quiet",{describe:"Ocultar mensagens de progresso.",global:!0,short:"q"}),ln=be("color"),oo=w(He,{about:"Criar e consultar uma base SQLite local com os CEPs do Brasil.",afterHelp:["Exemplos:"," bunx @konstit/dne build --db ./dne.db"," bunx @konstit/dne get 01001-000 --db ./dne.db"," bunx @konstit/dne status --db ./dne.db"," bunx @konstit/dne cron install --db ./dne.db"].join(`
21
- `),args:[an,sn,cn,ln],version:pe,subcommands:[w("build",{args:[A("source",S.string,{default:C,describe:"Diret\xF3rio DNE, arquivo ZIP ou URL.",valueName:"CAMINHO|URL"}),L("force",{describe:"Ignorar metadados de atualiza\xE7\xE3o e recriar a base."}),L("check",{describe:"Verificar a atualiza\xE7\xE3o da fonte sem alterar a base."})],about:"Criar ou atualizar a base SQLite",conflicts:[["force","check"]],handler:(e,t)=>co(e,v(t))}),w("get",{args:[U("input",S.string,{describe:"Um ou mais CEPs.",repeatable:!0,valueName:"CEP"}),A("file",S.string,{describe:"Ler CEPs de um arquivo. Use - para stdin.",valueHint:"file",valueName:"CAMINHO"}),L("jsonl",{describe:"Gravar um resultado JSON por linha."})],about:"Consultar um ou mais CEPs",handler:(e,t)=>uo(e,v(t))}),w("status",{about:"Exibir tamanho, registros, estado do esquema e metadados da fonte",handler:(e,t)=>fo(v(t))}),w("schema",{args:[L("expected",{describe:"Exibir o esquema declarado pela CLI em vez do esquema da base."})],about:"Exibir o esquema atual ou esperado da tabela de CEPs",handler:(e,t)=>mo(e,v(t))}),w("doctor",{args:[L("offline",{describe:"N\xE3o verificar a fonte remota."}),A("source",S.string,{default:C,describe:"URL da fonte remota que ser\xE1 verificada.",valueName:"URL"})],about:"Verificar Bun, configura\xE7\xE3o da base e acesso \xE0 fonte",handler:(e,t)=>po(e,v(t))}),w("sql",{args:[U("query",S.string,{describe:"Instru\xE7\xE3o SELECT, WITH, PRAGMA ou EXPLAIN somente leitura.",required:!0,valueName:"CONSULTA"}),A("limit",S.range(1,1e4),{default:100,describe:"Quantidade m\xE1xima de registros retornados.",valueName:"REGISTROS"})],about:"Executar uma consulta SQL somente leitura com limite",handler:(e,t)=>go(e,v(t))}),w("cron",{about:"Gerenciar a atualiza\xE7\xE3o autom\xE1tica da base no sistema operacional",subcommands:[w("install",{args:[U("expression",S.cron,{default:Xr,describe:"Express\xE3o cron. O padr\xE3o executa \xE0 meia-noite de sexta-feira.",valueName:"EXPRESS\xC3O"}),L("dry-run",{describe:"Exibir o agendamento sem alterar o sistema."}),A("source",S.string,{describe:"Diret\xF3rio DNE, arquivo ZIP ou URL usado pelo agendamento.",valueName:"CAMINHO|URL"})],about:"Instalar ou substituir o agendamento desta base",handler:(e,t)=>ao(e,v(t))}),w("status",{about:"Exibir o agendamento desta base",handler:(e,t)=>io(v(t))}),w("remove",{about:"Remover o agendamento desta base",handler:(e,t)=>so(v(t))})],subcommandRequired:!0,defaultToHelp:!0})],subcommandRequired:!0,defaultToHelp:!0});async function un(e=Bun.argv.slice(2)){let t=e.includes("--json")||e.includes("--jsonl"),n=process.stdout.isTTY===!0&&Bun.env.TERM!=="dumb";try{return await oo.run({argv:e,color:n,stdout:(r)=>console.log(Fe(r).trimEnd()),...t?{stderr:(r)=>dn(new p("invalid-arguments",Fe(Lo(Bun.stripANSI(r))),de),!0)}:{stderr:(r)=>console.error(Fe(r).trimEnd())}})}catch(r){return yo(r,t)}}function v(e){return{color:e.global(ln),database:e.global(an),json:e.global(sn),quiet:e.global(cn)}}async function ao(e,t){let n=await Et({database:t.database,dryRun:e["dry-run"],expression:e.expression,packageVersion:pe,source:e.source});if(t.json)I(n);else{let r=n.status==="preview"?"Agendamento que seria instalado":n.status==="updated"?"Agendamento atualizado":"Agendamento instalado";console.log(`${r}: ${n.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${B(n.next_run??void 0)}`),console.log(`Base: ${n.database}`),console.log(`Fonte: ${n.source}`),console.log(`Comando: ${n.command}`)}return 0}function io(e){let t=wt(e.database);if(e.json)I(t);else if(t.installed)console.log(`Agendamento instalado: ${t.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${B(t.next_run??void 0)}`),console.log(`Base: ${t.database}`),console.log(`Fonte: ${t.source}`),console.log(`Pacote: @konstit/dne@${t.package_version}`),console.log(`Comando: ${t.command}`);else console.log(`Nenhum agendamento instalado para a base: ${t.database}`);return 0}async function so(e){let t=await Tt(e.database);if(e.json)I(t);else if(t.removed)console.log(`Agendamento removido para a base: ${t.database}`);else console.log(`Nenhum agendamento instalado para a base: ${t.database}`);return 0}async function co(e,t){let n=ho(t.quiet);try{return await lo(e,t,n)}finally{n.finish()}}async function lo(e,t,n){let r=performance.now(),o=D(t.database);if(e.check||o===":memory:")return en(e,t,n,r,o);let a=await vt(o,n);try{return await en(e,t,n,r,o)}finally{a.release()}}async function en(e,t,n,r,o){let a=mn(),i=e.source,s=pn(i)?await bo(i,n):null;if(n.finish(),e.check){if(!s){let N=new ce(i,{onProgress:n});try{await N.resolve(a)}catch(ge){throw new p("source-unavailable",Y(ge))}finally{await N.cleanup(),n.finish()}}let y=await P(o),h=s&&y.ready?await rn(o,E,s):null,R={database:y,source:ue(i,s),status:h===null?"unknown":h?"current":"update-available",up_to_date:h};return Eo(R,t.json),0}if(!e.force&&s&&await rn(o,E,s)){let h={database:await P(o),elapsed_ms:Pe(r),source:ue(i,s),status:"unchanged"};return tn(h,t.json),0}let c=o!==":memory:"&&await Bun.file(o).exists(),l=new ce(i,{onProgress:n,remoteInfo:s??void 0}),u=await Fo(o),f=new Ee(u.path,a),d=!1,m=0;try{let y=await l.resolve(a);if(n("Carregando a base SQLite"),m=await f.loadFromSource(y,Jt(i,s,pe),n),f.close(),d=!0,n("Confirmando a base SQLite"),c)await Ao(o,u.path,a);else await u.commit();n.finish()}finally{if(!d)f.close();await u.cleanup(),await l.cleanup()}let _={database:o===":memory:"?mt(m):await P(o),elapsed_ms:Pe(r),source:ue(i,s),status:c?"updated":"created"};return tn(_,t.json),0}async function uo(e,t){if(t.json&&e.jsonl)throw new p("output-conflict","--json e --jsonl n\xE3o podem ser usados juntos.",de);let r=je(e.input,e.file)[Symbol.asyncIterator](),o=await r.next();if(o.done)throw new p("missing-input","Informe um CEP, --file CAMINHO ou uma entrada em stdin.",de);let a={input:o.value,cep:he(o.value)},i=D(t.database),s=await te(i),c=[],l=0,u=!1;try{f(a);while(!0){let d=await r.next();if(d.done)break;f({input:d.value,cep:he(d.value)})}}finally{s.close()}if(t.json)I({count:l,database:i,results:c});else if(!e.jsonl)wo(c);return u?ro:0;function f(d){let m=s.queryCep(E,d.cep),b={address:m,cep:d.cep,found:m!==null,input:d.input};if(l++,u||=!b.found,e.jsonl){process.stdout.write(`${JSON.stringify({ok:!0,data:{database:i,result:b}})}
22
- `);return}c.push(b)}}async function fo(e){let t=await P(D(e.database));if(e.json)I(t);else To(t);return t.ready?0:on}async function mo(e,t){let n=mn(),r=O(n),o=null,a="declared",i=st(r);if(!e.expected){o=D(t.database);let s=await te(o);try{i=s.tableSchema(E)??(()=>{throw new p("schema-not-found",`A tabela '${E}' n\xE3o possui um esquema armazenado.`)})(),i=xo(i),a="database"}finally{s.close()}}if(t.json)I({database:o,source:a,sql:i,table:E});else console.log(Mo(i,t.color));return 0}async function po(e,t){let n=await P(D(t.database)),r=vo(Bun.version),o={checked:!1,reachable:null,url:e.source};if(!e.offline)try{let s=await le(e.source);o={...ue(e.source,s),checked:!0,reachable:!0}}catch(s){o={checked:!0,error:Y(s),reachable:!1,url:e.source}}let a=r&&n.ready&&o.reachable!==!1,i={auth:{required:!1,source:"not-required"},database:n,healthy:a,runtime:{compatible:r,minimum_version:"1.4.0",name:"bun",version:Bun.version},setup:n.ready?null:`Execute bunx @konstit/dne build --db ${Do(n.path)}`,source:o,version:pe};if(t.json)I(i);else _o(i);return a?0:on}async function go(e,t){if(!/^\s*(?:SELECT|WITH|PRAGMA|EXPLAIN)\b/i.test(e.query))throw new p("write-query-denied","O comando sql permite somente instru\xE7\xF5es SELECT, WITH, PRAGMA e EXPLAIN.",de);let n=D(t.database),r=await te(n);try{let o=r.querySql(e.query,e.limit),a={columns:o.rows[0]?Object.keys(o.rows[0]):[],database:n,limit:e.limit,...o};if(t.json)I(a);else console.log(JSON.stringify(a,null,2))}finally{r.close()}return 0}async function bo(e,t){t("Inspecionando a fonte DNE remota");try{return await le(e)}catch(n){throw new p("source-unavailable",Y(n))}}function ue(e,t){return t?{accept_ranges:t.acceptRanges,content_length:t.contentLength,etag:t.etag,kind:"remote",last_modified:t.lastModified,url:t.url}:{input:e,kind:pn(e)?"remote":"local"}}function ho(e){let t=null,n=()=>{if(t!==null)process.stderr.write(` (${Be(Pe(t))})
23
- `),t=null},r=(o)=>{if(n(),!e)t=performance.now(),process.stderr.write(o)};return r.finish=n,r}function I(e){process.stdout.write(`${JSON.stringify({ok:!0,data:e},null,2)}
24
- `)}function dn(e,t){if(t){process.stderr.write(`${JSON.stringify({error:{code:e.code,...e.details?{details:e.details}:{},message:e.message},ok:!1})}
25
- `);return}console.error(`erro: ${e.message}`)}function yo(e,t){let n=e instanceof p?e:e instanceof k?new p("source-quality-failed",Y(e)):new p("internal-error",Y(e));return dn(n,t),n.exitCode}function Eo(e,t){if(t){I(e);return}console.log(`Estado: ${Io(e.status)}`),console.log(`Base: ${e.database.path}`),console.log(`Fonte: ${ke(e.source.url??e.source.input)}`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${B(ke(e.source.last_modified))}`)}function tn(e,t){if(t){I(e);return}let n=e.database.row_count===null?"quantidade desconhecida de registros":`${x(e.database.row_count)} registros`,r=e.database.size_bytes===null?"tamanho desconhecido":fn(e.database.size_bytes);if(e.status==="unchanged"){let a=e.database.row_count===null?"quantidade desconhecida de registros":`${x(e.database.row_count)} registros`;console.log(`A base DNE j\xE1 est\xE1 atualizada: ${e.database.path} (${a}, ${r}).`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${B(ke(e.source.last_modified))}`),console.log(`Verifica\xE7\xE3o conclu\xEDda em ${Be(e.elapsed_ms)}.`);return}let o=e.status==="updated"?"Base atualizada":"Base criada";console.log(`${o}: ${e.database.path} (${n}, ${r}, ${Be(e.elapsed_ms)}).`)}function wo(e){if(e.length===1){let t=e[0];if(!t?.address){console.error(`CEP n\xE3o encontrado: ${t?.cep??""}`);return}console.log(t.address);return}console.log("cep\tencontrado\tlogradouro\tbairro\tmunic\xEDpio\tuf");for(let t of e)console.log([t.cep,fe(t.found),t.address?.logradouro??"",t.address?.bairro??"",t.address?.municipio??"",t.address?.uf??""].join("\t"))}function To(e){if(console.log(`Base: ${e.path}`),console.log(`Existe: ${fe(e.exists)}`),console.log(`Pronta: ${fe(e.ready)}`),console.log(`Registros: ${e.row_count===null?"-":x(e.row_count)}`),console.log(`Tamanho: ${e.size_bytes===null?"-":fn(e.size_bytes)}`),console.log(`Carregada em: ${B(e.metadata?.loaded_at)}`),console.log(`Pacote: @konstit/dne@${e.metadata?.package_version??"-"}`),console.log(`Fonte: ${e.metadata?.source_url??e.metadata?.source_input??"-"}`),console.log(`\xDAltima modifica\xE7\xE3o da fonte: ${B(e.metadata?.source_last_modified)}`),e.error)console.log(`Erro: ${e.error}`)}function _o(e){if(console.log(`CLI: dne ${e.version}`),console.log(`Ambiente: ${e.runtime.name} ${e.runtime.version} (${e.runtime.compatible?"compat\xEDvel":"n\xE3o compat\xEDvel"})`),console.log(`Base: ${e.database.ready?"pronta":"configura\xE7\xE3o necess\xE1ria"} (${e.database.path})`),console.log(`Fonte: ${e.source.reachable===null?"n\xE3o verificada":e.source.reachable?"acess\xEDvel":"inacess\xEDvel"}`),console.log(`Saud\xE1vel: ${fe(e.healthy)}`),e.setup)console.log(`Configura\xE7\xE3o: ${e.setup}`)}function So(e){return e instanceof Error?e.message:String(e)}function Y(e){return Ro(So(e))}function Ro(e){let n={"Failed to write downloaded content":"Falha ao gravar o conte\xFAdo baixado","Invalid ZIP central directory entry":"Entrada inv\xE1lida no diret\xF3rio central do ZIP","Invalid ZIP central directory entry size":"Tamanho inv\xE1lido de entrada no diret\xF3rio central do ZIP","Invalid ZIP central directory range":"Intervalo inv\xE1lido do diret\xF3rio central do ZIP","Only sqlite:/// database URLs are supported":"Somente URLs de base no formato sqlite:/// s\xE3o aceitas","package.json has no valid version":"package.json n\xE3o cont\xE9m uma vers\xE3o v\xE1lida","Source is not a valid ZIP file":"A fonte n\xE3o \xE9 um arquivo ZIP v\xE1lido","Unified schema table not found":"Tabela unificada n\xE3o encontrada no schema","ZIP file does not contain DNE Basico files":"O arquivo ZIP n\xE3o cont\xE9m arquivos do DNE B\xE1sico"}[e];if(n)return n;return e.replace(/^Failed to download (.+): (\d+)$/,"Falha ao baixar $1: $2").replace(/^Failed to stream (.+): empty response body$/,"Falha ao transmitir $1: corpo da resposta vazio").replace(/^Failed to inspect DNE from (.+): (\d+)$/,"Falha ao inspecionar o DNE em $1: $2").replace(/^DNE source not found: (.+)$/,"Fonte DNE n\xE3o encontrada: $1").replace(/^DNE source quality validation failed: (.+)$/,"A valida\xE7\xE3o de qualidade da fonte DNE falhou: $1").replace(/^DNE data file not found: (.+)$/,"Arquivo de dados DNE n\xE3o encontrado: $1").replace(/^Invalid ZIP local header for (.+)$/,"Cabe\xE7alho local ZIP inv\xE1lido para $1").replace(/^Invalid ZIP data range for (.+)$/,"Intervalo de dados ZIP inv\xE1lido para $1").replace(/^Invalid decompressed size for (.+)$/,"Tamanho descompactado inv\xE1lido para $1").replace(/^Unsupported ZIP compression method (\d+) for (.+)$/,"M\xE9todo de compacta\xE7\xE3o ZIP $1 n\xE3o aceito para $2").replace(/^CRC32 mismatch for (.+)$/,"CRC32 divergente para $1").replace(/^Server ignored byte range (.+)$/,"O servidor ignorou o intervalo de bytes $1").replace(/^Server returned an invalid Content-Range for (.+)$/,"O servidor retornou um Content-Range inv\xE1lido para $1").replace(/^Server returned (\d+) bytes for range (.+); expected (\d+)$/,"O servidor retornou $1 bytes para o intervalo $2; eram esperados $3").replace(/^Missing row at index (\d+)$/,"Registro ausente no \xEDndice $1").replace(/^Table with original name '(.+)' not found$/,"Tabela com nome original '$1' n\xE3o encontrada")}function Fe(e){return e.replaceAll("Usage:","Uso:").replaceAll("Arguments:","Argumentos:").replaceAll("Commands:","Comandos:").replaceAll("Options:","Op\xE7\xF5es:").replaceAll("Print help for a subcommand","Exibir ajuda de um subcomando").replaceAll("Print help","Exibir ajuda").replaceAll("Print version","Exibir vers\xE3o").replaceAll("Enable or disable color output","Ativar ou desativar cores na sa\xEDda").replaceAll("expected a schedulable Bun cron expression","esperada uma express\xE3o cron v\xE1lida").replaceAll("[env:","[vari\xE1vel:").replaceAll("[default:","[padr\xE3o:").replaceAll("For more information, try '--help'.","Para mais informa\xE7\xF5es, use '--help'.").replaceAll("error:","erro:").replace(/invalid value (.+?) for (.+?): expected value matching (.+)/g,"valor inv\xE1lido $1 para $2: esperado valor compat\xEDvel com $3").replace(/invalid value (.+?) for (.+?): expected a number from (.+?) to (.+)/g,"valor inv\xE1lido $1 para $2: esperado n\xFAmero entre $3 e $4").replace(/invalid value (.+?) for (.+?): (.+)/g,"valor inv\xE1lido $1 para $2: $3").replace(/unexpected argument (.+)/g,"argumento inesperado $1").replace(/arguments (.+?) and (.+?) cannot be used together/g,"os argumentos $1 e $2 n\xE3o podem ser usados juntos").replace(/argument (.+?) requires at least (\d+) value\(s\)/g,"o argumento $1 exige pelo menos $2 valor(es)").replace(/the following required arguments were not provided:/g,"os seguintes argumentos obrigat\xF3rios n\xE3o foram informados:").replace(/a similar argument exists:/g,"existe um argumento semelhante:")}function ke(e){return typeof e==="string"?e:""}function Lo(e){return e.split(`
26
- `).map((t)=>t.trim()).find(Boolean)?.replace(/^error:\s*/i,"")??"Argumentos inv\xE1lidos."}function Pe(e){return Math.max(0,Math.round(performance.now()-e))}function x(e){return eo.format(e)}function nn(e){return to.format(e)}function B(e){if(!e)return"-";let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(me)}function Be(e){let t=Math.max(0,Math.round(e));if(t<1000)return`${x(t)} ms`;let n=Math.round(t/1000);if(n<60){let i=Math.round(t/100)/10;return`${no.format(i)} s`}let r=Math.floor(n/3600),o=Math.floor(n%3600/60),a=n%60;return[r?`${x(r)} h`:"",o?`${x(o)} min`:"",a?`${x(a)} s`:""].filter(Boolean).join(" ")}function fn(e){if(e<1024)return`${x(e)} B`;if(e<1048576)return`${nn(e/1024)} KiB`;return`${nn(e/1048576)} MiB`}function fe(e){return e?"sim":"n\xE3o"}function Io(e){return{current:"atualizada",unknown:"desconhecido","update-available":"atualiza\xE7\xE3o dispon\xEDvel"}[e]??e}function Do(e){return`'${e.replaceAll("'","'\\''")}'`}function vo(e){let[t=0,n=0]=e.split(".").map(Number);return t>1||t===1&&n>=4}async function No(){let e=await Bun.file(new URL("../package.json",import.meta.url)).json();if(typeof e.version!=="string"||!e.version)throw Error("package.json has no valid version");return e.version}function mn(){let e=qe();return O(e).name=E,e}async function Ao(e,t,n){let r=O(n),o=r.columns.map((s)=>g(s.name)).join(", "),a=`${t}.attach`;await X(a,{force:!0}),await Hr(t,a);let i=new qr(e);try{i.run("PRAGMA busy_timeout = 30000"),i.run("PRAGMA journal_mode = WAL"),i.run("PRAGMA synchronous = NORMAL"),i.run(`ATTACH DATABASE ${Co(a)} AS fresh`),i.run("BEGIN IMMEDIATE");try{i.run(we(r)),i.run(`
27
- CREATE TABLE IF NOT EXISTS ${g(T)} (
39
+ `)}writeMetadata(e){let t=this.db.prepare(`INSERT INTO ${y(A)} (key, value) VALUES (?, ?)`);try{for(let[n,r]of Object.entries(e))t.run(n,r)}finally{t.finalize()}}async transaction(e){this.db.run("BEGIN");try{await e(),this.db.run("COMMIT")}catch(t){throw this.db.run("ROLLBACK"),t}}}function Ur(e){let t=e.indexOf(",");if(t===-1)return[e.trim(),null];return[e.slice(0,t).trim(),e.slice(t+1).trim()]}function Fr(e){return/^\d{1,8}$/.test(e)&&B(Number(e))?Number(e):null}var ia=new Set(["AC","AL","AM","AP","BA","CE","DF","ES","GO","MA","MG","MS","MT","PA","PB","PE","PI","PR","RJ","RN","RO","RR","RS","SC","SE","SP","TO"]);function qe(e){return e!==null&&ia.has(e)}function Ee(e){return e!==null&&/^\d{8}$/.test(e)}function oa(e){if(!/^\d{7}$/.test(e))return!1;let t=Number(e);return Number.isSafeInteger(t)&&t>0}function We(e){let t=e.find(([,n])=>n===null);return t?`missing_${t[0]}`:null}function Xt(e,t){let n=e.locNuSub?t.get(e.locNuSub):e;if(!n||n.munNu===null)return null;return{nome:n.nome,munNu:n.munNu}}function Pr(e,t){if(e.schema_version!==Re||e.source_kind!=="remote"||e.source_url!==t.url)return!1;let n=[Jt(e.source_etag,t.etag),Jt(e.source_last_modified,t.lastModified),Jt(e.source_content_length,t.contentLength)].filter((r)=>r!==null);return n.length>0&&n.every(Boolean)}function kr(e,t,n){let r={loaded_at:new Date().toISOString(),package_version:n,schema_version:Re,source_input:e,source_kind:t||aa(e)?"remote":"local"};if(t)r.source_url=t.url,r.source_last_modified=t.lastModified??"",r.source_etag=t.etag??"",r.source_content_length=t.contentLength??"";return r}function Jt(e,t){if(!t)return null;return e===t}function aa(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}var pa="0 0 * * 5",en="\x1B[0m",ba="\x1B[1m",ga="\x1B[36m",ha="\x1B[90m",ya=/(--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$)|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:]]|[^\]])*]|\b(?:CREATE|TABLE|IF|NOT|EXISTS|TEXT|INTEGER|NULL|PRIMARY|KEY|WITHOUT|ROWID)\b)/gi,bt="pt-BR",Ea=new Intl.NumberFormat(bt),wa=new Intl.NumberFormat(bt,{maximumFractionDigits:1,minimumFractionDigits:1}),_a=new Intl.NumberFormat(bt,{maximumFractionDigits:1}),Gr=1,de=2,Ia=3,gt=await fr(),Qr=F("db",C.string,{default:In,describe:"Caminho da base; build bin\xE1rio usa a extens\xE3o .bin.",global:!0,valueHint:"file",valueName:"CAMINHO"}),zr=O("json",{describe:"Gravar um envelope JSON est\xE1vel em stdout.",global:!0}),Zr=O("quiet",{describe:"Ocultar mensagens de progresso.",global:!0,short:"q"}),Yr=Dt("color"),Sa=R(_n,{about:"Criar e consultar uma base local com os CEPs do Brasil.",afterHelp:["Exemplos:"," bunx @konstit/dne build --db ./dne.db"," bunx @konstit/dne build --format binary"," bunx @konstit/dne get 01001-000 --db ./dne.db"," bunx @konstit/dne status --db ./dne.db"," bunx @konstit/dne cron install --db ./dne.db"].join(`
40
+ `),args:[Qr,zr,Zr,Yr],version:gt,subcommands:[R("build",{args:[F("format",C.enum(["sqlite","binary"]),{default:"sqlite",describe:"Formato da base de sa\xEDda.",valueName:"sqlite|binary"}),F("source",C.string,{default:Z,describe:"Diret\xF3rio DNE, arquivo ZIP ou URL.",valueName:"CAMINHO|URL"}),O("force",{describe:"Ignorar metadados de atualiza\xE7\xE3o e recriar a base."}),O("check",{describe:"Verificar a atualiza\xE7\xE3o da fonte sem alterar a base."})],about:"Criar ou atualizar a base SQLite ou bin\xE1ria",conflicts:[["force","check"]],handler:(e,t)=>Ra(e,G(t))}),R("get",{args:[_e("input",C.string,{describe:"Um ou mais CEPs.",repeatable:!0,valueName:"CEP"}),F("file",C.string,{describe:"Ler CEPs de um arquivo. Use - para stdin.",valueHint:"file",valueName:"CAMINHO"}),O("jsonl",{describe:"Gravar um resultado JSON por linha."})],about:"Consultar um ou mais CEPs",handler:(e,t)=>xa(e,G(t))}),R("status",{about:"Exibir tamanho, registros, estado do esquema e metadados da fonte",handler:(e,t)=>Ca(G(t))}),R("schema",{args:[O("expected",{describe:"Exibir o esquema declarado pela CLI em vez do esquema da base."})],about:"Exibir o esquema atual ou esperado da tabela de CEPs",handler:(e,t)=>La(e,G(t))}),R("doctor",{args:[O("offline",{describe:"N\xE3o verificar a fonte remota."}),F("source",C.string,{default:Z,describe:"URL da fonte remota que ser\xE1 verificada.",valueName:"URL"})],about:"Verificar Bun, configura\xE7\xE3o da base e acesso \xE0 fonte",handler:(e,t)=>Oa(e,G(t))}),R("sql",{args:[_e("query",C.string,{describe:"Instru\xE7\xE3o SELECT, WITH, PRAGMA ou EXPLAIN somente leitura.",required:!0,valueName:"CONSULTA"}),F("limit",C.range(1,1e4),{default:100,describe:"Quantidade m\xE1xima de registros retornados.",valueName:"REGISTROS"})],about:"Executar uma consulta SQL somente leitura com limite",handler:(e,t)=>Ba(e,G(t))}),R("cron",{about:"Gerenciar a atualiza\xE7\xE3o autom\xE1tica da base no sistema operacional",subcommands:[R("install",{args:[_e("expression",C.cron,{default:pa,describe:"Express\xE3o cron. O padr\xE3o executa \xE0 meia-noite de sexta-feira.",valueName:"EXPRESS\xC3O"}),O("dry-run",{describe:"Exibir o agendamento sem alterar o sistema."}),F("source",C.string,{describe:"Diret\xF3rio DNE, arquivo ZIP ou URL usado pelo agendamento.",valueName:"CAMINHO|URL"})],about:"Instalar ou substituir o agendamento desta base",handler:(e,t)=>Da(e,G(t))}),R("status",{about:"Exibir o agendamento desta base",handler:(e,t)=>Aa(G(t))}),R("remove",{about:"Remover o agendamento desta base",handler:(e,t)=>Ta(G(t))})],subcommandRequired:!0,defaultToHelp:!0})],subcommandRequired:!0,defaultToHelp:!0});async function Vr(e=Bun.argv.slice(2)){let t=e.includes("--json")||e.includes("--jsonl"),n=process.stdout.isTTY===!0&&Bun.env.TERM!=="dumb";try{return await Sa.run({argv:e,color:n,stdout:(r)=>console.log(tn(r).trimEnd()),...t?{stderr:(r)=>Xr(new E("invalid-arguments",tn(Ha(Bun.stripANSI(r))),de),!0)}:{stderr:(r)=>console.error(tn(r).trimEnd())}})}catch(r){return $a(r,t)}}function G(e){return{color:e.global(Yr),database:e.global(Qr),json:e.global(zr),quiet:e.global(Zr)}}async function Da(e,t){let n=await Kn({database:t.database,dryRun:e["dry-run"],expression:e.expression,packageVersion:gt,source:e.source});if(t.json)U(n);else{let r=n.status==="preview"?"Agendamento que seria instalado":n.status==="updated"?"Agendamento atualizado":"Agendamento instalado";console.log(`${r}: ${n.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${we(n.next_run??void 0)}`),console.log(`Base: ${n.database}`),console.log(`Fonte: ${n.source}`),console.log(`Comando: ${n.command}`)}return 0}function Aa(e){let t=Jn(e.database);if(e.json)U(t);else if(t.installed)console.log(`Agendamento instalado: ${t.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${we(t.next_run??void 0)}`),console.log(`Base: ${t.database}`),console.log(`Fonte: ${t.source}`),console.log(`Pacote: @konstit/dne@${t.package_version}`),console.log(`Comando: ${t.command}`);else console.log(`Nenhum agendamento instalado para a base: ${t.database}`);return 0}async function Ta(e){let t=await er(e.database);if(e.json)U(t);else if(t.removed)console.log(`Agendamento removido para a base: ${t.database}`);else console.log(`Nenhum agendamento instalado para a base: ${t.database}`);return 0}async function Ra(e,t){let n=Ma(t.quiet);try{return await Na(e,t,n)}finally{n.finish()}}async function Na(e,t,n){let r=performance.now(),i=j(t.database,e.format);if(e.format==="binary"&&i===":memory:")throw new E("invalid-format","O formato bin\xE1rio exige um caminho de arquivo.",de);if(e.check||i===":memory:")return qr(e,t,n,r,i);let o=await ur(i,n);try{return await qr(e,t,n,r,i)}finally{o.release()}}async function qr(e,t,n,r,i){let o=Jr(),a=e.source,s=ei(a)?await va(a,n):null;if(n.finish(),e.check){if(!s){let S=new dt(a,{onProgress:n});try{await S.resolve(o)}catch(N){throw new E("source-unavailable",He(N))}finally{await S.cleanup(),n.finish()}}let w=await ae(i),h=s&&w.ready?await jr(i,e.format,s):null,I={database:w,source:mt(a,s),status:h===null?"unknown":h?"current":"update-available",up_to_date:h};return Ua(I,t.json),0}if(!e.force&&s&&await jr(i,e.format,s)){let h={database:await ae(i),elapsed_ms:rn(r),source:mt(a,s),status:"unchanged"};return Wr(h,t.json),0}let l=i!==":memory:"&&await Bun.file(i).exists(),c=new dt(a,{onProgress:n,remoteInfo:s??void 0}),u=await Ka(i),d=new Kt(u.path,o),f=!1,m=0;try{let w=await c.resolve(o);if(n(e.format==="binary"?"Carregando a base bin\xE1ria":"Carregando a base SQLite"),m=await d.loadFromSource(w,kr(a,s,gt),n),e.format==="sqlite"&&i!==":memory:")n("Compactando a base SQLite"),d.compact();d.close(),f=!0;let h=u.path;if(e.format==="binary")h=`${u.path}.bin`,n("Compactando a base bin\xE1ria"),await vn(u.path,h),await ue(u.path,{force:!0});if(n(e.format==="binary"?"Confirmando a base bin\xE1ria":"Confirmando a base SQLite"),e.format==="sqlite"&&l)await za(i,u.path,o);else await u.commit(h);n.finish()}finally{if(!f)d.close();await u.cleanup(),await c.cleanup()}let g={database:i===":memory:"?Qn(m):await ae(i),elapsed_ms:rn(r),source:mt(a,s),status:l?"updated":"created"};return Wr(g,t.json),0}async function xa(e,t){if(t.json&&e.jsonl)throw new E("output-conflict","--json e --jsonl n\xE3o podem ser usados juntos.",de);let r=Pn(e.input,e.file)[Symbol.asyncIterator](),i=await r.next();if(i.done)throw new E("missing-input","Informe um CEP, --file CAMINHO ou uma entrada em stdin.",de);let o=d(i.value),a=j(t.database),s=await it(a),l=[],c=0,u=!1;try{f(o);while(!0){let m=await r.next();if(m.done)break;f(d(m.value))}}finally{s.close()}if(t.json)U({count:c,database:a,results:l});else if(!e.jsonl)Fa(l);return u?Ia:0;function d(m){let b=Fn(m);if(b===void 0)throw new E("invalid-cep",`CEP inv\xE1lido '${m}'. Use 01001000 ou 01001-000.`,de,{input:m});return{cep:b,input:m}}function f(m){let b=s.queryCep(m.cep)??null,g={address:b,cep:m.cep,found:b!==null,input:m.input};if(c++,u||=!g.found,e.jsonl){process.stdout.write(`${JSON.stringify({ok:!0,data:{database:a,result:g}})}
41
+ `);return}l.push(g)}}async function Ca(e){let t=await ae(j(e.database));if(e.json)U(t);else Pa(t);return t.ready?0:Gr}async function La(e,t){let n=Jr(),r=J(n),i=null,o="declared",a=Ne(n),s=`${[...a.map(Hn),Mt(r.name)].join(`;
42
+
43
+ `)};`;if(!e.expected){i=j(t.database);let l=await it(i);try{if(!("tableSchema"in l))o="binary";else{let c=a.map((d)=>l.tableSchema(d.name)).filter((d)=>d!==void 0).map(Za),u=l.querySql(`SELECT sql FROM sqlite_master WHERE type = 'view' AND name = ${ti(oe(r.name))}`,1).rows[0]?.sql;if(typeof u==="string")c.push(u);if(c.length)s=`${c.join(`;
44
+
45
+ `)};`,o="database"}}finally{l.close()}}if(t.json)U({database:i,source:o,sql:s,table:T});else console.log(Va(s,t.color));return 0}async function Oa(e,t){let n=await ae(j(t.database)),r=Qa(Bun.version),i={checked:!1,reachable:null,url:e.source};if(!e.offline)try{let s=await ft(e.source);i={...mt(e.source,s),checked:!0,reachable:!0}}catch(s){i={checked:!0,error:He(s),reachable:!1,url:e.source}}let o=r&&n.ready&&i.reachable!==!1,a={auth:{required:!1,source:"not-required"},database:n,healthy:o,runtime:{compatible:r,minimum_version:"1.4.0",name:"bun",version:Bun.version},setup:n.ready?null:`Execute bunx @konstit/dne build --db ${Ga(n.path)}`,source:i,version:gt};if(t.json)U(a);else ka(a);return o?0:Gr}async function Ba(e,t){if(!/^\s*(?:SELECT|WITH|PRAGMA|EXPLAIN)\b/i.test(e.query))throw new E("write-query-denied","O comando sql permite somente instru\xE7\xF5es SELECT, WITH, PRAGMA e EXPLAIN.",de);let n=j(t.database),r=await it(n);try{if(!("querySql"in r))throw new E("sql-unsupported","O comando sql exige uma base SQLite.",de);let i=r.querySql(e.query,e.limit),o={columns:i.rows[0]?Object.keys(i.rows[0]):[],database:n,limit:e.limit,...i};if(t.json)U(o);else console.log(JSON.stringify(o,null,2))}finally{r.close()}return 0}async function va(e,t){t("Inspecionando a fonte DNE remota");try{return await ft(e)}catch(n){throw new E("source-unavailable",He(n))}}function mt(e,t){return t?{accept_ranges:t.acceptRanges,content_length:t.contentLength,etag:t.etag,kind:"remote",last_modified:t.lastModified,url:t.url}:{input:e,kind:ei(e)?"remote":"local"}}function Ma(e){let t=null,n=()=>{if(t!==null)process.stderr.write(` (${on(rn(t))})
46
+ `),t=null},r=(i)=>{if(n(),!e)t=performance.now(),process.stderr.write(i)};return r.finish=n,r}function U(e){process.stdout.write(`${JSON.stringify({ok:!0,data:e},null,2)}
47
+ `)}function Xr(e,t){if(t){process.stderr.write(`${JSON.stringify({error:{code:e.code,...e.details?{details:e.details}:{},message:e.message},ok:!1})}
48
+ `);return}console.error(`erro: ${e.message}`)}function $a(e,t){let n=e instanceof E?e:e instanceof ce?new E("source-quality-failed",He(e)):new E("internal-error",He(e));return Xr(n,t),n.exitCode}function Ua(e,t){if(t){U(e);return}console.log(`Estado: ${ja(e.status)}`),console.log(`Base: ${e.database.path}`),console.log(`Fonte: ${nn(e.source.url??e.source.input)}`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${we(nn(e.source.last_modified))}`)}function Wr(e,t){if(t){U(e);return}let n=e.database.row_count===null?"quantidade desconhecida de registros":`${V(e.database.row_count)} registros`,r=e.database.size_bytes===null?"tamanho desconhecido":Kr(e.database.size_bytes);if(e.status==="unchanged"){let o=e.database.row_count===null?"quantidade desconhecida de registros":`${V(e.database.row_count)} registros`;console.log(`A base DNE j\xE1 est\xE1 atualizada: ${e.database.path} (${o}, ${r}).`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${we(nn(e.source.last_modified))}`),console.log(`Verifica\xE7\xE3o conclu\xEDda em ${on(e.elapsed_ms)}.`);return}let i=e.status==="updated"?"Base atualizada":"Base criada";console.log(`${i}: ${e.database.path} (${n}, ${r}, ${on(e.elapsed_ms)}).`)}function Fa(e){if(e.length===1){let t=e[0];if(!t?.address){console.error(`CEP n\xE3o encontrado: ${t?.cep??""}`);return}console.log(t.address);return}console.log("cep\tencontrado\tlogradouro\tbairro\tmunic\xEDpio\tuf");for(let t of e)console.log([t.cep,pt(t.found),t.address?.logradouro??"",t.address?.bairro??"",t.address?.municipio??"",t.address?.uf??""].join("\t"))}function Pa(e){if(console.log(`Base: ${e.path}`),console.log(`Formato: ${e.format??"-"}`),console.log(`Existe: ${pt(e.exists)}`),console.log(`Pronta: ${pt(e.ready)}`),console.log(`Registros: ${e.row_count===null?"-":V(e.row_count)}`),console.log(`Tamanho: ${e.size_bytes===null?"-":Kr(e.size_bytes)}`),console.log(`Carregada em: ${we(e.metadata?.loaded_at)}`),console.log(`Pacote: @konstit/dne@${e.metadata?.package_version??"-"}`),console.log(`Fonte: ${e.metadata?.source_url??e.metadata?.source_input??"-"}`),console.log(`\xDAltima modifica\xE7\xE3o da fonte: ${we(e.metadata?.source_last_modified)}`),e.error)console.log(`Erro: ${e.error}`)}function ka(e){if(console.log(`CLI: dne ${e.version}`),console.log(`Ambiente: ${e.runtime.name} ${e.runtime.version} (${e.runtime.compatible?"compat\xEDvel":"n\xE3o compat\xEDvel"})`),console.log(`Base: ${e.database.ready?"pronta":"configura\xE7\xE3o necess\xE1ria"} (${e.database.path})`),console.log(`Fonte: ${e.source.reachable===null?"n\xE3o verificada":e.source.reachable?"acess\xEDvel":"inacess\xEDvel"}`),console.log(`Saud\xE1vel: ${pt(e.healthy)}`),e.setup)console.log(`Configura\xE7\xE3o: ${e.setup}`)}function qa(e){return e instanceof Error?e.message:String(e)}function He(e){return Wa(qa(e))}function Wa(e){let n={"Failed to write downloaded content":"Falha ao gravar o conte\xFAdo baixado","Invalid ZIP central directory entry":"Entrada inv\xE1lida no diret\xF3rio central do ZIP","Invalid ZIP central directory entry size":"Tamanho inv\xE1lido de entrada no diret\xF3rio central do ZIP","Invalid ZIP central directory range":"Intervalo inv\xE1lido do diret\xF3rio central do ZIP","Only sqlite:/// database URLs are supported":"Somente URLs de base no formato sqlite:/// s\xE3o aceitas","package.json has no valid version":"package.json n\xE3o cont\xE9m uma vers\xE3o v\xE1lida","Source is not a valid ZIP file":"A fonte n\xE3o \xE9 um arquivo ZIP v\xE1lido","Unified schema table not found":"Tabela unificada n\xE3o encontrada no schema","ZIP file does not contain DNE Basico files":"O arquivo ZIP n\xE3o cont\xE9m arquivos do DNE B\xE1sico"}[e];if(n)return n;return e.replace(/^Failed to download (.+): (\d+)$/,"Falha ao baixar $1: $2").replace(/^Failed to stream (.+): empty response body$/,"Falha ao transmitir $1: corpo da resposta vazio").replace(/^Failed to inspect DNE from (.+): (\d+)$/,"Falha ao inspecionar o DNE em $1: $2").replace(/^DNE source not found: (.+)$/,"Fonte DNE n\xE3o encontrada: $1").replace(/^DNE source quality validation failed: (.+)$/,"A valida\xE7\xE3o de qualidade da fonte DNE falhou: $1").replace(/^DNE data file not found: (.+)$/,"Arquivo de dados DNE n\xE3o encontrado: $1").replace(/^Invalid ZIP local header for (.+)$/,"Cabe\xE7alho local ZIP inv\xE1lido para $1").replace(/^Invalid ZIP data range for (.+)$/,"Intervalo de dados ZIP inv\xE1lido para $1").replace(/^Invalid decompressed size for (.+)$/,"Tamanho descompactado inv\xE1lido para $1").replace(/^Unsupported ZIP compression method (\d+) for (.+)$/,"M\xE9todo de compacta\xE7\xE3o ZIP $1 n\xE3o aceito para $2").replace(/^CRC32 mismatch for (.+)$/,"CRC32 divergente para $1").replace(/^Server ignored byte range (.+)$/,"O servidor ignorou o intervalo de bytes $1").replace(/^Server returned an invalid Content-Range for (.+)$/,"O servidor retornou um Content-Range inv\xE1lido para $1").replace(/^Server returned (\d+) bytes for range (.+); expected (\d+)$/,"O servidor retornou $1 bytes para o intervalo $2; eram esperados $3").replace(/^Missing row at index (\d+)$/,"Registro ausente no \xEDndice $1").replace(/^Table with original name '(.+)' not found$/,"Tabela com nome original '$1' n\xE3o encontrada")}function tn(e){return e.replaceAll("Usage:","Uso:").replaceAll("Arguments:","Argumentos:").replaceAll("Commands:","Comandos:").replaceAll("Options:","Op\xE7\xF5es:").replaceAll("Print help for a subcommand","Exibir ajuda de um subcomando").replaceAll("Print help","Exibir ajuda").replaceAll("Print version","Exibir vers\xE3o").replaceAll("Enable or disable color output","Ativar ou desativar cores na sa\xEDda").replaceAll("expected a schedulable Bun cron expression","esperada uma express\xE3o cron v\xE1lida").replaceAll("[env:","[vari\xE1vel:").replaceAll("[default:","[padr\xE3o:").replaceAll("For more information, try '--help'.","Para mais informa\xE7\xF5es, use '--help'.").replaceAll("error:","erro:").replace(/invalid value (.+?) for (.+?): expected value matching (.+)/g,"valor inv\xE1lido $1 para $2: esperado valor compat\xEDvel com $3").replace(/invalid value (.+?) for (.+?): expected a number from (.+?) to (.+)/g,"valor inv\xE1lido $1 para $2: esperado n\xFAmero entre $3 e $4").replace(/invalid value (.+?) for (.+?): (.+)/g,"valor inv\xE1lido $1 para $2: $3").replace(/unexpected argument (.+)/g,"argumento inesperado $1").replace(/arguments (.+?) and (.+?) cannot be used together/g,"os argumentos $1 e $2 n\xE3o podem ser usados juntos").replace(/argument (.+?) requires at least (\d+) value\(s\)/g,"o argumento $1 exige pelo menos $2 valor(es)").replace(/the following required arguments were not provided:/g,"os seguintes argumentos obrigat\xF3rios n\xE3o foram informados:").replace(/a similar argument exists:/g,"existe um argumento semelhante:")}function nn(e){return typeof e==="string"?e:""}function Ha(e){return e.split(`
49
+ `).map((t)=>t.trim()).find(Boolean)?.replace(/^error:\s*/i,"")??"Argumentos inv\xE1lidos."}function rn(e){return Math.max(0,Math.round(performance.now()-e))}function V(e){return Ea.format(e)}function Hr(e){return wa.format(e)}function we(e){if(!e)return"-";let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(bt)}function on(e){let t=Math.max(0,Math.round(e));if(t<1000)return`${V(t)} ms`;let n=Math.round(t/1000);if(n<60){let a=Math.round(t/100)/10;return`${_a.format(a)} s`}let r=Math.floor(n/3600),i=Math.floor(n%3600/60),o=n%60;return[r?`${V(r)} h`:"",i?`${V(i)} min`:"",o?`${V(o)} s`:""].filter(Boolean).join(" ")}function Kr(e){if(e<1024)return`${V(e)} B`;if(e<1048576)return`${Hr(e/1024)} KiB`;return`${Hr(e/1048576)} MiB`}function pt(e){return e?"sim":"n\xE3o"}function ja(e){return{current:"atualizada",unknown:"desconhecido","update-available":"atualiza\xE7\xE3o dispon\xEDvel"}[e]??e}function Ga(e){return`'${e.replaceAll("'","'\\''")}'`}function Qa(e){let[t=0,n=0]=e.split(".").map(Number);return t>1||t===1&&n>=4}function Jr(){let e=wn();return J(e).name=T,e}async function za(e,t,n){let r=Ne(n),i=`${t}.attach`;await ue(i,{force:!0}),await ca(t,i);let o=new sa(e);try{o.run("PRAGMA busy_timeout = 30000"),o.run("PRAGMA journal_mode = WAL"),o.run("PRAGMA synchronous = NORMAL"),o.run("PRAGMA foreign_keys = ON"),o.run(`ATTACH DATABASE ${ti(i)} AS fresh`),o.run("BEGIN IMMEDIATE");try{nt(o,n),o.run(`
50
+ CREATE TABLE IF NOT EXISTS ${y(A)} (
28
51
  key TEXT PRIMARY KEY NOT NULL,
29
52
  value TEXT NOT NULL
30
53
  )
31
- `),i.run(`DELETE FROM main.${g(E)}`),i.run(`
32
- INSERT INTO main.${g(E)} (${o})
33
- SELECT ${o}
34
- FROM fresh.${g(E)}
35
- `),i.run(`DELETE FROM main.${g(T)}`),i.run(`
36
- INSERT INTO main.${g(T)} (key, value)
54
+ `);for(let a of r){let s=a.columns.map((l)=>y(l.name)).join(", ");o.run(`
55
+ INSERT INTO main.${y(a.name)} (${s})
56
+ SELECT ${s} FROM fresh.${y(a.name)}
57
+ `)}o.run(`DELETE FROM main.${y(A)}`),o.run(`
58
+ INSERT INTO main.${y(A)} (key, value)
37
59
  SELECT key, value
38
- FROM fresh.${g(T)}
39
- `),i.run("COMMIT")}catch(s){throw i.run("ROLLBACK"),s}finally{i.run("DETACH DATABASE fresh")}}finally{i.close(),await X(a,{force:!0})}}async function rn(e,t,n){if(!await ft(e,t))return!1;let r=await dt(e);if(!r)return!1;return Vt(r,n)}function pn(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Co(e){return`'${e.replaceAll("'","''")}'`}function xo(e){let t=e.indexOf("("),n=e.lastIndexOf(")");if(t===-1||n<=t)return e;let r=$o(e.slice(t+1,n));if(!r.length)return e;let o=e.slice(0,t+1).trimEnd(),a=e.slice(n).trimStart();return`${o}
60
+ FROM fresh.${y(A)}
61
+ `),o.run("COMMIT")}catch(a){throw o.run("ROLLBACK"),a}finally{o.run("DETACH DATABASE fresh")}}finally{o.close(),await ue(i,{force:!0})}}async function jr(e,t,n){let r=await ae(e);if(!r.ready||r.format!==t||!r.metadata)return!1;return Pr(r.metadata,n)}function ei(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function ti(e){return`'${e.replaceAll("'","''")}'`}function Za(e){let t=e.indexOf("("),n=e.lastIndexOf(")");if(t===-1||n<=t)return e;let r=Ya(e.slice(t+1,n));if(!r.length)return e;let i=e.slice(0,t+1).trimEnd(),o=e.slice(n).trimStart();return`${i}
40
62
  ${r.join(`,
41
63
  `)}
42
- ${a}`}function $o(e){let t=[],n=0,r=0,o=null,a=null;for(let i=0;i<e.length;i++){let s=e[i];if(a==="line"){if(s===`
43
- `||s==="\r")a=null;continue}if(a==="block"){if(s==="*"&&e[i+1]==="/")a=null,i++;continue}if(o){if(s===o)if(e[i+1]===o)i++;else o=null;continue}if(s==="-"&&e[i+1]==="-")a="line",i++;else if(s==="/"&&e[i+1]==="*")a="block",i++;else if(s==="'"||s==='"'||s==="`")o=s;else if(s==="[")o="]";else if(s==="(")r++;else if(s===")")r--;else if(s===","&&r===0)t.push(e.slice(n,i).trim()),n=i+1}return t.push(e.slice(n).trim()),t.filter(Boolean)}function Mo(e,t){return Bun.markdown.render(`\`\`\`sql
64
+ ${o}`}function Ya(e){let t=[],n=0,r=0,i=null,o=null;for(let a=0;a<e.length;a++){let s=e[a];if(o==="line"){if(s===`
65
+ `||s==="\r")o=null;continue}if(o==="block"){if(s==="*"&&e[a+1]==="/")o=null,a++;continue}if(i){if(s===i)if(e[a+1]===i)a++;else i=null;continue}if(s==="-"&&e[a+1]==="-")o="line",a++;else if(s==="/"&&e[a+1]==="*")o="block",a++;else if(s==="'"||s==='"'||s==="`")i=s;else if(s==="[")i="]";else if(s==="(")r++;else if(s===")")r--;else if(s===","&&r===0)t.push(e.slice(n,a).trim()),n=a+1}return t.push(e.slice(n).trim()),t.filter(Boolean)}function Va(e,t){return Bun.markdown.render(`\`\`\`sql
44
66
  ${e}
45
- \`\`\``,{code:(n)=>Oo(n,t)}).trimEnd()}function Oo(e,t){if(!t)return e;return e.replaceAll(Jr,(n)=>{if(n.startsWith("--")||n.startsWith("/*"))return`${Vr}${n}${Oe}`;if(n.startsWith('"')||n.startsWith("`")||n.startsWith("["))return`${Kr}${n}${Oe}`;if(n.startsWith("'"))return n;return`${Yr}${n}${Oe}`})}async function Fo(e){if(e===":memory:")return{path:e,commit:async()=>{},cleanup:async()=>{}};let t=Qr(e),n=Wr(t,`.${zr(e)}.${process.pid}.${Date.now()}.tmp`);await Gr(t,{recursive:!0}),await X(n,{force:!0});let r=!1;return{path:n,commit:async()=>{await Zr(n,e),r=!0},cleanup:async()=>{if(!r)await X(n,{force:!0});await X(`${n}-journal`,{force:!0})}}}process.exitCode=await un();
67
+ \`\`\``,{code:(n)=>Xa(n,t)}).trimEnd()}function Xa(e,t){if(!t)return e;return e.replaceAll(ya,(n)=>{if(n.startsWith("--")||n.startsWith("/*"))return`${ha}${n}${en}`;if(n.startsWith('"')||n.startsWith("`")||n.startsWith("["))return`${ga}${n}${en}`;if(n.startsWith("'"))return n;return`${ba}${n}${en}`})}async function Ka(e){if(e===":memory:")return{path:e,commit:async(i)=>{},cleanup:async()=>{}};let t=fa(e),n=ma(t,`.${da(e)}.${process.pid}.${Date.now()}.tmp`);await la(t,{recursive:!0}),await ue(n,{force:!0});let r=!1;return{path:n,commit:async(i=n)=>{await ua(i,e),r=!0},cleanup:async()=>{if(!r)await ue(n,{force:!0});await ue(`${n}.bin`,{force:!0}),await ue(`${n}-journal`,{force:!0})}}}process.exitCode=await Vr();
46
68
 
47
- //# debugId=91E7237A17C1CEB164756E2164756E21
69
+ //# debugId=1E5DEF2E51CCBE6764756E2164756E21