@konstit/dne 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -35
- package/dist/address-search-index.d.ts +34 -0
- package/dist/address-search-index.js +326 -0
- package/dist/address-search-index.js.map +1 -0
- package/dist/address-search-pool-errors.d.ts +15 -0
- package/dist/address-search-pool-errors.js +25 -0
- package/dist/address-search-pool-errors.js.map +1 -0
- package/dist/address-search-pool.d.ts +40 -0
- package/dist/address-search-pool.js +215 -0
- package/dist/address-search-pool.js.map +1 -0
- package/dist/address-search-rank.d.ts +5 -0
- package/dist/address-search-rank.js +89 -0
- package/dist/address-search-rank.js.map +1 -0
- package/dist/address-search-text.d.ts +6 -0
- package/dist/address-search-text.js +16 -0
- package/dist/address-search-text.js.map +1 -0
- package/dist/address-search-worker-runtime.d.ts +41 -0
- package/dist/address-search-worker-runtime.js +38 -0
- package/dist/address-search-worker-runtime.js.map +1 -0
- package/dist/address-search-worker-source.d.ts +2 -0
- package/dist/address-search-worker-source.js +5 -0
- package/dist/address-search-worker-source.js.map +1 -0
- package/dist/address-search.d.ts +31 -0
- package/dist/address-search.js +152 -0
- package/dist/address-search.js.map +1 -0
- package/dist/binary-db-errors.d.ts +1 -1
- package/dist/binary-db-errors.js +1 -1
- package/dist/binary-db-errors.js.map +1 -1
- package/dist/binary-db-reader.d.ts +18 -12
- package/dist/binary-db-reader.js +64 -43
- package/dist/binary-db-reader.js.map +1 -1
- package/dist/binary-db-validator.js +3 -6
- package/dist/binary-db-validator.js.map +1 -1
- package/dist/chunks/dynamic-completion-wbp85hh9-cytdw6ns.js +7 -0
- package/dist/chunks/dynamic-completion-wbp85hh9-cytdw6ns.js.map +10 -0
- package/dist/chunks/index-338dn00y.js +18 -0
- package/dist/chunks/index-338dn00y.js.map +10 -0
- package/dist/expand.d.ts +8 -0
- package/dist/expand.js +1484 -0
- package/dist/expand.js.map +1 -0
- package/dist/fsst.d.ts +1 -1
- package/dist/index.js +48 -48
- package/dist/index.js.map +25 -20
- package/dist/library.d.ts +9 -2
- package/dist/library.js +9 -2
- package/dist/library.js.map +1 -1
- package/dist/settings.d.ts +0 -2
- package/dist/settings.js +0 -2
- package/dist/settings.js.map +1 -1
- package/dist/shared-file.d.ts +2 -0
- package/dist/shared-file.js +35 -0
- package/dist/shared-file.js.map +1 -0
- package/dist/sqlite-db-reader.d.ts +13 -4
- package/dist/sqlite-db-reader.js +39 -17
- package/dist/sqlite-db-reader.js.map +1 -1
- package/dist/types.d.ts +29 -4
- package/dist/types.js +73 -4
- package/dist/types.js.map +1 -1
- package/package.json +13 -10
- package/data/dne.bin +0 -0
- package/dist/chunks/dynamic-completion-403da357-4jc4w04x.js +0 -7
- package/dist/chunks/dynamic-completion-403da357-4jc4w04x.js.map +0 -10
- package/dist/chunks/index-s0h4vdva.js +0 -17
- package/dist/chunks/index-s0h4vdva.js.map +0 -10
package/dist/index.js
CHANGED
|
@@ -1,69 +1,69 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{a as v,c as Z,d as ze,e as V,f as Zt,o as N}from"./chunks/index-s0h4vdva.js";var zi=Object.freeze(["bash","zsh","fish","powershell"]);import{Database as Fs}from"bun:sqlite";import{copyFile as $s,mkdir as ks,rename as Ps,rm as Ie}from"fs/promises";import{basename as Ws,dirname as Hs,join as qs}from"path";import{Database as Mo}from"bun:sqlite";class ee extends Error{constructor(e,t){super(e,t);this.name=new.target.name}}class Ye extends ee{path;code="IO_ERROR";constructor(e,t){super(`Unable to read binary database: ${e}`,t);this.path=e}}class p extends ee{code="INVALID_FORMAT";constructor(e,t){super(e,t)}}class pt extends ee{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 bt extends ee{code="READER_CLOSED";constructor(){super("Binary database is closed")}}var te=5,O=256,P=32,G=16,k=Uint8Array.from([68,78,69,66,73,78,0,0]),$n=4294967295,Qt=1e5,ue=100001,ne=10,Be=32,ht=0,re=2,ie=255,de=2295,x=3,M=8,fe=8,W=256,xe=32,F=["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 Ze(e){return Math.ceil(e/8)*8}function Oe(e){return Math.ceil(e/8)}function Ce(e,t){return Math.ceil(e*t/8)}function Le(){let e=new Uint8Array(256);for(let t=1;t<e.length;t++)e[t]=(e[t>>>1]??0)+(t&1);return e}function B(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;return 4}function Ne(e,t){if(e!==1&&e!==2&&e!==3&&e!==4)throw Error(`Unsupported binary ${t} width: ${e}`);return e}function Qe(e){return e===4?4294967295:2**(e*8)-1}function Xt(e,t,n){if(!Number.isSafeInteger(e)||e<0||e>Qe(t))throw Error(`Binary ${n} exceeds the ${t}-byte unsigned integer limit: ${e}`)}function R(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 T(e,t,n,r){if(Xt(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 kn(e){if(e.byteLength!==k.length)return!1;return k.every((t,n)=>e[n]===t)}function Pn(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 Xe=8,Ue=3,ve=1<<Ue,Yi=Le();function Hn(e,t,n){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=[],o=[],a=-1;for(let D=0;D<t;D++){let H=R(r,D*n,n);if(H!==a)i.push(D),o.push(H),a=H}let s=i.length,c=Math.floor(Math.log2(t/s)),l=2**c,u=Math.ceil(t/l),d=u+s,f=Math.ceil(s*c/8),m=Math.ceil(d/8),b=Math.ceil(u/ve),h=Xe+f,y=h+m,g=y+b*4,w=new Uint8Array(g+s*n),E=new DataView(w.buffer);E.setUint32(0,s,!0),E.setUint8(4,c),E.setUint8(5,Ue),E.setUint8(6,n);for(let D=0;D<s;D++){let H=i[D]??0;Zi(w,Xe,D*c,c,H%l);let le=Math.floor(H/l)+D,q=h+(le>>>3);w[q]=(w[q]??0)|1<<(le&7),T(w,g+D*n,o[D]??0,n)}let I=0;for(let D=0;D<d;D++)if(((w[h+(D>>>3)]??0)&1<<(D&7))===0){if(I%ve===0)E.setUint32(y+(I>>>Ue)*4,D,!0);I++}return w}function qn(e,t,n,r){let i=e.getUint32(t.offset,!0),o=e.getUint8(t.offset+4),a=Math.ceil(n/2**o),s=a+i,c=t.offset+Xe,l=c+Math.ceil(i*o/8),u=l+Math.ceil(s/8),d=u+Math.ceil(a/ve)*4;return{highBitCount:s,highOffset:l,idWidth:r,idsOffset:d,lowBits:o,lowOffset:c,runCount:i,samplesOffset:u,zeroCount:a}}function jn(e,t,n,r,i){if(t.length<Xe)throw new p("Binary neighborhood runs are truncated");let o=e.getUint32(t.offset,!0),a=e.getUint8(t.offset+4);if(o<1||o>n||a>31||e.getUint8(t.offset+5)!==Ue||e.getUint8(t.offset+6)!==r||e.getUint8(t.offset+7)!==0)throw new p("Invalid binary neighborhood run header");let s=2**a,c=Math.ceil(n/s),l=c+o,u=Math.ceil(o*a/8),d=Math.ceil(l/8),f=Math.ceil(c/ve),m=t.offset+Xe,b=m+u,h=b+d,y=h+f*4;if(y+o*r!==t.offset+t.length)throw new p("Invalid binary neighborhood run length");let g=0,w=0,E=-1,I=-1;for(let D=0;D<l;D++){if((e.getUint8(b+(D>>>3))&1<<(D&7))===0){if(g>=c)throw new p("Invalid binary neighborhood run bitmap");if(g%ve===0&&e.getUint32(h+(g>>>Ue)*4,!0)!==D)throw new p("Invalid binary neighborhood run samples");g++;continue}if(w>=o)throw new p("Invalid binary neighborhood run bitmap");let le=Gn(e,m,w*a,a),q=g*s+le,Re=R(e,y+w*r,r);if(w===0&&q!==0||q<=E||q>=n||Re>i||Re===I)throw new p("Invalid binary neighborhood run");E=q,I=Re,w++}if(l%8!==0){let D=255<<(l&7);if((e.getUint8(b+(l>>>3))&D)!==0)throw new p("Invalid binary neighborhood run padding")}return{highBitCount:l,highOffset:b,idWidth:r,idsOffset:y,lowBits:a,lowOffset:m,runCount:o,samplesOffset:h,zeroCount:c}}function Vn(e,t,n){let r=2**t.lowBits,i=Math.floor(n/r),o=Wn(e,t,i)-i,a=i===0?0:Wn(e,t,i-1)-(i-1),s=n%r,c=a,l=o;while(c<l){let d=c+(l-c>>>1);if(Gn(e,t.lowOffset,d*t.lowBits,t.lowBits)<=s)c=d+1;else l=d}let u=c-1;return R(e,t.idsOffset+u*t.idWidth,t.idWidth)}function Wn(e,t,n){let r=n>>>Ue,i=e.getUint32(t.samplesOffset+r*4,!0),o=n-r*ve;if(o===0)return i;i++;while(o>0){let a=i&7,s=8-a,c=(1<<s)-1,l=~(e.getUint8(t.highOffset+(i>>>3))>>>a)&c,u=Yi[l]??0;if(u>=o)for(let d=0;o>0;d++){if(l&1<<d)o--;i++}else o-=u,i+=s}return i-1}function Gn(e,t,n,r){let i=0;for(let o=0;o<r;o++){let a=n+o;if(e.getUint8(t+(a>>>3))&1<<(a&7))i+=2**o}return i}function Zi(e,t,n,r,i){for(let o=0;o<r;o++)if(Math.floor(i/2**o)%2){let a=n+o,s=t+(a>>>3);e[s]=(e[s]??0)|1<<(a&7)}}function z(e){return Number.isInteger(e)&&e>0&&e<=4294967295}var Me=8,Kt=8,Fe=1<<Kt;function zn(e,t,n){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=[],o=[],a=[],s=-1,c=-1;for(let y=0;y<t.length;y++){let g=R(r,y*n,n),w=t[y]??0;if(g!==s||w!==c)i.push(y),o.push(g),a.push(w),s=g,c=w}let l=i.length,u=Math.ceil(t.length/Fe),d=Me+(u+1)*4,f=d+l*4,m=new Uint8Array(f+l*n),b=new DataView(m.buffer);b.setUint32(0,l,!0),b.setUint8(4,Kt);let h=0;for(let y=0;y<u;y++){while(h+1<l&&(i[h+1]??0)<=y*Fe)h++;b.setUint32(Me+y*4,h,!0)}b.setUint32(Me+u*4,l,!0);for(let y=0;y<l;y++)b.setUint32(d+y*4,i[y]??0,!0),T(m,f+y*n,o[y]??0,n);return{ids:m,flags:Uint8Array.from(a)}}function Yn(e,t,n){let r=e.getUint32(t.offset,!0),i=t.offset+Me,o=i+(Math.ceil(n/Fe)+1)*4;return{count:r,directoryOffset:i,startsOffset:o,idsOffset:o+r*4}}function Zn(e,t,n,r){if(t.length<Me)throw new p("Binary locality runs are truncated");let i=e.getUint32(t.offset,!0);if(i===0||i>n||e.getUint32(t.offset+4,!0)!==Kt)throw new p("Invalid binary locality run header");let o=Math.ceil(n/Fe),a=t.offset+Me,s=a+(o+1)*4,c=s+i*4;if(c+i*r!==t.offset+t.length)throw new p("Invalid binary locality run length");let l=-1;for(let d=0;d<i;d++){let f=e.getUint32(s+d*4,!0);if(d===0&&f!==0||f<=l||f>=n)throw new p("Invalid binary locality run boundary");l=f}let u=0;for(let d=0;d<o;d++){while(u+1<i&&e.getUint32(s+(u+1)*4,!0)<=d*Fe)u++;if(e.getUint32(a+d*4,!0)!==u)throw new p("Invalid binary locality run directory")}if(e.getUint32(a+o*4,!0)!==i)throw new p("Invalid binary locality run sentinel");return{count:i,directoryOffset:a,startsOffset:s,idsOffset:c}}function Qn(e,t,n){let r=Math.floor(n/Fe),i=e.getUint32(t.directoryOffset+r*4,!0),o=Math.min(t.count,e.getUint32(t.directoryOffset+(r+1)*4,!0)+1);while(i+1<o){let a=i+(o-i>>>1);if(e.getUint32(t.startsOffset+a*4,!0)<=n)i=a;else o=a}return i}function $e(e){return Math.max(1,Math.ceil(Math.log2(e+1)))}function yt(e,t,n,r){let i=n*r,o=t+Math.floor(i/8),a=i&7,s=a+r,c=e.getUint8(o);if(s>8)c|=e.getUint8(o+1)<<8;if(s>16)c|=e.getUint8(o+2)<<16;if(s>24)c|=e.getUint8(o+3)<<24;let l=c>>>a&4294967295>>>32-r;if(s>32)l+=(e.getUint8(o+4)&(1<<s-32)-1)*2**(32-a);return l>>>0}function Xn(e,t,n,r){if(!Number.isInteger(r)||r<0||r>=2**n||n<1||n>32)throw Error(`Invalid ${n}-bit column value: ${r}`);let i=t*n,o=Math.floor(i/8),a=i&7,s=r*2**a,c=Math.ceil((a+n)/8);for(let l=0;l<c;l++)e[o+l]=(e[o+l]??0)|Math.floor(s/2**(l*8))&255}var Ke="4",ke=["M","D","P"],Pe=["municipio","distrito","povoado"],We=["sem_codificacao_por_logradouro","codificada_por_logradouro","inserida_na_codificacao_por_logradouro","em_codificacao_por_logradouro"],Qi=[{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 Kn(e={}){return Qi.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 me(e){let t=e.find((n)=>n.unifiedTable);if(!t)throw Error("Unified schema table not found");return t}function Je(e){return e.filter((t)=>t.columns.length>0)}function et(e){if(e.unifiedTable||e.fileGlob===null)return null;return e.fileGlob??`${e.originalName.toUpperCase()}.TXT`}function pe(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 oe={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},Zc=Object.keys(oe).map(Jt);function Jt(e){let t=e.trim().toUpperCase();if(!Object.hasOwn(oe,t))throw Error(`Unknown UF: ${e}`);return t}var Jn=new TextDecoder("utf-8",{fatal:!0});function er(e){try{if(!(e instanceof Uint8Array))throw new p("Binary database bytes must be a Uint8Array");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=Xi(t);Ki(e,n);let r=Ji(e,t,n);eo(r.uf);let i=io(e,t,n,r),o=oo(t,n,r),a=ao(e,t,n,r),s=jn(t,n.sections.bairroIds,n.rowCount,i.idWidth,i.count),c=Zn(t,n.sections.municipalityIds,n.rowCount,n.municipalityIdWidth);co(t,n,s,c),fo(t,n,i),mo(e,t,n),po(e,t,n,r.logradouro),bo(t,n,r,i,s,c,a,o),wo(e,n.sections.metadata)}catch(t){if(t instanceof p)throw t;let n=t instanceof Error?t.message:String(t);throw new p(`Unable to validate binary database: ${n}`,{cause:t})}}function Xi(e){if(e.byteLength<O+P)throw new p("Binary database header is truncated");for(let n=0;n<k.length;n++)if(e.getUint8(n)!==k[n])throw new p("Invalid binary database magic");if(e.getUint16(8,!0)!==te)throw new p("Unsupported binary database version");if(e.getUint16(10,!0)!==O)throw new p("Unsupported binary database header size");if(e.getUint8(22)!==fe||e.getUint8(23)!==x)throw new p("Unsupported binary database block layout");if(e.getUint16(24,!0)!==F.length)throw new p("Unsupported binary database section table");let t={};for(let[n,r]of F.entries()){let i=xe+n*8;t[r]={length:e.getUint32(i+4,!0),offset:e.getUint32(i,!0)}}return{cepPrefixOffsetWidth:Ne(e.getUint8(20),"CEP prefix offset"),fileSize:e.getUint32(16,!0),municipalityCount:e.getUint32(28,!0),municipalityIdWidth:Ne(e.getUint8(21),"municipality id"),rowCount:e.getUint32(12,!0),sections:t}}function Ki(e,t){let n=e.byteLength-P;if(t.fileSize!==e.byteLength)throw new p(`Binary database size mismatch: header=${t.fileSize}, actual=${e.byteLength}`);if(n<O||n%8!==0)throw new p("Binary database payload has an invalid alignment");if(!t.rowCount||!t.municipalityCount)throw new p("Binary database must contain rows and municipalities");if(t.rowCount>Qe(t.cepPrefixOffsetWidth))throw new p("Binary row count does not fit the CEP prefix offset width");if(t.municipalityCount>Qe(t.municipalityIdWidth))throw new p("Binary municipality count does not fit its id width");if(t.cepPrefixOffsetWidth!==B(t.rowCount)||t.municipalityIdWidth!==B(t.municipalityCount))throw new p("Binary database uses a noncanonical integer width");He(e,26,28,"binary header reserved bytes"),He(e,248,O,"binary header reserved bytes");let r=O;for(let o of F){let a=t.sections[o];if(Eo(n,a,o),a.offset%8!==0||a.offset<r)throw new p(`Binary section is out of order or unaligned: ${o}`);He(e,r,a.offset,`${o} section padding`),r=a.offset+a.length}if(He(e,r,n,"final binary section padding"),Ze(r)!==n)throw new p("Binary database footer is not after aligned section data");Q(t.sections.cepPrefixOffsets,ue*t.cepPrefixOffsetWidth,"CEP prefix directory"),Q(t.sections.cepSuffixes,Ce(t.rowCount,ne),"CEP suffix column");for(let o of["complementoBitmap","nomeBitmap","localidadeNomeBitmap"])Q(t.sections[o],Oe(t.rowCount),"nullable bitmap");let i=(Math.ceil(t.rowCount/W)+1)*4;for(let o of["complementoRanks","nomeRanks","localidadeNomeRanks"])Q(t.sections[o],i,"sparse rank index")}function Ji(e,t,n){return{bairro:be(e,t,n.sections.bairroDictionary,"bairro",!1),bairroAbreviado:be(e,t,n.sections.bairroAbreviadoDictionary,"bairro abbreviation",!1),complemento:be(e,t,n.sections.complementoDictionary,"complemento",!1),logradouro:be(e,t,n.sections.logradouroDictionary,"logradouro",!0),municipio:be(e,t,n.sections.municipioDictionary,"municipio",!1),nome:be(e,t,n.sections.nomeDictionary,"nome",!1),uf:be(e,t,n.sections.ufDictionary,"uf",!1)}}function eo(e){for(let[t,n]of e.values.entries())en(n,t)}function en(e,t){let n;try{n=Jt(e)}catch(r){throw new p(`Invalid binary UF dictionary entry: ${t}`,{cause:r})}if(e!==n)throw new p(`Binary UF dictionary entry is not canonical: ${t}`);return n}function be(e,t,n,r,i){if(n.length<Be)throw new p(`Binary ${r} dictionary is truncated`);let o=t.getUint32(n.offset,!0),a=t.getUint32(n.offset+4,!0),s=t.getUint32(n.offset+8,!0),c=t.getUint32(n.offset+12,!0),l=t.getUint32(n.offset+16,!0),u=t.getUint32(n.offset+20,!0),d=t.getUint32(n.offset+24,!0),f=Ne(t.getUint8(n.offset+28),`${r} dictionary id`),m=t.getUint8(n.offset+30),b=t.getUint8(n.offset+31);if(m!==ht&&(m!==re||!i)||(m===ht?b!==0:b!==1&&b!==2))throw new p(`Unsupported binary ${r} dictionary codec or length width`);if(t.getUint8(n.offset+29)!==x)throw new p(`Unsupported binary ${r} dictionary block size`);let h=Math.ceil(o/M);if(a!==h||o>Qe(f))throw new p(`Binary ${r} dictionary has an invalid count or id width`);let y=b===2?2:1,g=m===re?de:0;if(s!==Be||c!==s+a*4||l!==c+o*y||u!==l+o+g||u>n.length||d!==n.length-u||f!==B(o))throw new p(`Binary ${r} dictionary has an invalid layout`);let w={blockCount:a,blockOffsetsOffset:n.offset+s,codec:m,count:o,idWidth:f,lengthWidth:y,lengthsOffset:n.offset+c,prefixesOffset:n.offset+l,region:n,suffixDataLength:d,suffixDataOffset:n.offset+u,symbolsOffset:n.offset+l+o,values:[]};return to(e,t,w,r),w.values=no(e,t,w,r),w}function to(e,t,n,r){if(n.blockCount&&t.getUint32(n.blockOffsetsOffset,!0)!==0)throw new p(`Binary ${r} dictionary has an invalid first block offset`);let i=0;for(let o=0;o<n.blockCount;o++){let a=t.getUint32(n.blockOffsetsOffset+o*4,!0);if(a<i||a>n.suffixDataLength)throw new p(`Binary ${r} dictionary has invalid block offsets`);i=a}if(n.codec===re)for(let o=0;o<ie;o++){let a=e[n.symbolsOffset+o]??0;if(a>8)throw new p(`Invalid binary ${r} FSST symbol length`);let s=n.symbolsOffset+ie+o*8;He(e,s+a,s+8,`binary ${r} FSST symbol padding`)}if(n.blockCount===0&&n.suffixDataLength!==0)throw new p(`Binary ${r} dictionary has unexpected payload`)}function no(e,t,n,r){let i=[],o=r==="bairro"||r==="municipio"||r==="uf",a;for(let s=0;s<n.blockCount;s++){let c=s*M,l=Math.min(n.count,c+M),u=t.getUint32(n.blockOffsetsOffset+s*4,!0),d=s+1<n.blockCount?t.getUint32(n.blockOffsetsOffset+(s+1)*4,!0):n.suffixDataLength,f=n.suffixDataOffset+u,m=n.suffixDataOffset+d,b=new Uint8Array;for(let h=c;h<l;h++){let y=e[n.prefixesOffset+h]??0;if(h===c&&y!==0||y>b.byteLength)throw new p(`Invalid binary ${r} dictionary prefix: ${h}`);let g;if(n.codec===ht){let E=e[n.lengthsOffset+h]??0;if(y>E)throw new p(`Invalid binary ${r} dictionary length: ${h}`);let I=E-y;if(f<n.suffixDataOffset||f+I>m)throw new p(`Invalid binary ${r} dictionary suffix: ${h}`);g=new Uint8Array(E),g.set(b.subarray(0,y)),g.set(e.subarray(f,f+I),y),f+=I}else{let E=n.lengthWidth===1?e[n.lengthsOffset+h]??0:t.getUint16(n.lengthsOffset+h*2,!0);if(f<n.suffixDataOffset||f+E>m)throw new p(`Invalid binary ${r} FSST suffix: ${h}`);if(E>510)throw new p(`Binary ${r} FSST suffix is too long: ${h}`);g=ro(e,n,f,E,b,y,r,h),f+=E}let w;try{w=Jn.decode(g)}catch(E){throw new p(`Invalid UTF-8 in binary ${r} dictionary entry: ${h}`,{cause:E})}if(a!==void 0&&a>=w)throw new p(`Binary ${r} dictionary is not strictly sorted: ${h}`);if(o)i.push(w);a=w,b=g}if(f!==m)throw new p(`Binary ${r} dictionary block length mismatch`)}return i}function ro(e,t,n,r,i,o,a,s){let c=new Uint8Array(255);c.set(i.subarray(0,o));let l=o,u=n,d=n+r;while(u<d){let f=e[u++]??0;if(f===255){if(u>=d||l>=255)throw new p(`Invalid binary ${a} FSST escape: ${s}`);c[l++]=e[u++]??0;continue}let m=e[t.symbolsOffset+f]??0;if(!m||m>8||l+m>255)throw new p(`Invalid binary ${a} FSST symbol: ${s}`);let b=t.symbolsOffset+ie+f*8;c.set(e.subarray(b,b+m),l),l+=m}return c.slice(0,l)}function io(e,t,n,r){let i=n.sections.bairros;if(i.length<G)throw new p("Binary neighborhood table is truncated");let o=t.getUint32(i.offset,!0),a=Ne(t.getUint8(i.offset+4),"original neighborhood id"),s=Ne(t.getUint8(i.offset+5),"original locality id"),c=a+s+r.bairro.idWidth+r.bairroAbreviado.idWidth+r.uf.idWidth;Q(i,G+o*c,"neighborhood table"),He(e,i.offset+6,i.offset+G,"neighborhood table reserved bytes");let l=i.offset+G,u=0,d=0,f=0;for(let m=0;m<o;m++){let b=l+m*c,h=R(t,b,a);b+=a;let y=R(t,b,s);b+=s;let g=R(t,b,r.bairro.idWidth);b+=r.bairro.idWidth;let w=R(t,b,r.bairroAbreviado.idWidth);b+=r.bairroAbreviado.idWidth;let E=R(t,b,r.uf.idWidth);if(h<=u||y===0||g===0||g>r.bairro.count||w>r.bairroAbreviado.count||E===0||E>r.uf.count)throw new p(`Invalid binary neighborhood record: ${m}`);if(!r.bairro.values[g-1])throw new p(`Binary neighborhood has an empty name: ${m}`);en(r.uf.values[E-1]??"",m),u=h,d=Math.max(d,h),f=Math.max(f,y)}if(a!==B(d)||s!==B(f))throw new p("Binary neighborhood table uses a noncanonical integer width");return{count:o,idWidth:B(o),localidadeIdWidth:s,originalIdWidth:a,recordWidth:c,recordsOffset:l}}function oo(e,t,n){let r=3+n.municipio.idWidth+n.uf.idWidth,i=t.sections.municipalities;Q(i,t.municipalityCount*r,"municipalities");let o=new Uint32Array(t.municipalityCount+1),a=0;for(let s=0;s<t.municipalityCount;s++){let c=i.offset+s*r,l=R(e,c,3),u=R(e,c+3,n.municipio.idWidth),d=R(e,c+3+n.municipio.idWidth,n.uf.idWidth);if(l<1e6||l>9999999||l<=a)throw new p(`Invalid binary IBGE municipality code: ${l}`);if(u===0||u>n.municipio.count||d===0||d>n.uf.count)throw new p(`Invalid binary municipality record: ${s}`);if(!n.municipio.values[u-1])throw new p(`Binary municipality has an empty name: ${s}`);let f=en(n.uf.values[d-1]??"",s);if(Math.floor(l/1e5)!==oe[f])throw new p(`IBGE municipality code does not match UF: ${l} (${f}, ${oe[f]})`);o[s+1]=d,a=l}return{ufIds:o}}function ao(e,t,n,r){let i=new Uint32Array(n.rowCount);for(let[o,a,s]of[["complemento",r.complemento,void 0],["nome",r.nome,void 0],["localidadeNome",r.bairro,i]])so(e,t,n.rowCount,n.sections[`${o}Bitmap`],n.sections[`${o}Ranks`],n.sections[`${o}Ids`],a.idWidth,a.count,o,s);return{localidadeNome:i}}function so(e,t,n,r,i,o,a,s,c,l){if(o.length%a!==0)throw new p(`Binary ${c} sparse ids have an invalid length`);let u=Math.ceil(n/W),d=0;for(let m=0;m<u;m++){let b=d;if(t.getUint32(i.offset+m*4,!0)!==b)throw new p(`Binary ${c} sparse rank mismatch: ${m}`);let y=m*W,g=Math.min(n,y+W);for(let w=y;w<g;w++){if(((e[r.offset+(w>>>3)]??0)&1<<(w&7))===0)continue;if(d>=o.length/a)throw new p(`Binary ${c} sparse id index is outside the column`);let I=R(t,o.offset+d*a,a);if(I===0||I>s)throw new p(`Invalid binary ${c} sparse id: ${I}`);if(l)l[w]=I;d++}}if(t.getUint32(i.offset+u*4,!0)!==d||o.length!==d*a)throw new p(`Binary ${c} sparse column has an invalid final rank`);_o(e,r,n,c)}function co(e,t,n,r){Q(t.sections.localidadeFlags,r.count,"locality indicators"),lo(e,n),uo(e,t.sections.localidadeFlags,t,r)}function lo(e,t){let n=t.runCount*t.lowBits;if(n%8!==0&&(e.getUint8(t.lowOffset+Math.floor(n/8))&255<<(n&7))!==0)throw new p("Invalid binary neighborhood run low-bit padding")}function uo(e,t,n,r){let i=-1,o=-1;for(let a=0;a<r.count;a++){let s=R(e,r.idsOffset+a*n.municipalityIdWidth,n.municipalityIdWidth),c=e.getUint8(t.offset+a);if(s===0||s>n.municipalityCount||(c&3)>=We.length||c>>>2>=Pe.length||s===i&&c===o)throw new p(`Invalid binary locality run: ${a}`);i=s,o=c}}function fo(e,t,n){let{bairroFaixaOffsets:r,bairroFaixas:i}=t.sections;if(Q(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 c=e.getUint32(r.offset+(s+1)*4,!0);if(c<a||c>o)throw new p("Invalid binary neighborhood range offsets");let l=-1,u=-1;for(let d=a;d<c;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<l||f===l&&m<=u)throw new p("Invalid binary neighborhood CEP range");l=f,u=m}a=c}if(a!==o)throw new p("Unreferenced binary neighborhood CEP ranges")}function mo(e,t,n){let r=n.sections.cepPrefixOffsets,i=new Uint32Array(ue),o=0;for(let s=0;s<ue;s++){let c=R(t,r.offset+s*n.cepPrefixOffsetWidth,n.cepPrefixOffsetWidth);if(c<o||c>n.rowCount)throw new p(`Invalid binary CEP prefix boundary: ${s}`);i[s]=c,o=c}if(i[0]!==0||i[Qt]!==n.rowCount)throw new p("Binary CEP prefix directory has invalid boundaries");for(let s=0;s<Qt;s++){let c=i[s]??0,l=i[s+1]??0,u=-1;for(let d=c;d<l;d++){let f=So(e,n.sections.cepSuffixes.offset,d);if(f>999||f<=u)throw new p(`Binary CEP suffixes are not strictly ordered: ${d}`);u=f}}let a=n.rowCount*ne;if(a%8!==0){if(((e[n.sections.cepSuffixes.offset+n.sections.cepSuffixes.length-1]??0)&255<<(a&7))!==0)throw new p("Invalid binary CEP suffix padding")}}function po(e,t,n,r){let i=n.sections.logradouroIds,o=$e(r.count);Q(i,Ce(n.rowCount,o),"logradouro ids");for(let s=0;s<n.rowCount;s++){let c=yt(t,i.offset,s,o);if(c>r.count)throw new p(`Invalid binary logradouro id: ${c}`)}let a=n.rowCount*o;if(a%8!==0){if(((e[i.offset+i.length-1]??0)&255<<(a&7))!==0)throw new p("Invalid binary logradouro id padding")}}function bo(e,t,n,r,i,o,a,s){let c=yo(e,i),l=go(e,t,o),u=0,d=0;for(let f=0;f<t.rowCount;f++){while(u+1<c.starts.length&&(c.starts[u+1]??0)<=f)u++;while(d+1<l.starts.length&&(l.starts[d+1]??0)<=f)d++;let m=c.ids[u]??0,b=l.ids[d]??0,y=(l.flags[d]??0)>>>2;if((a.localidadeNome[f]??0)!==0&&(m!==0||y===0))throw new p(`Invalid binary subordinate locality name: ${f}`);if(m!==0){if(ho(e,r,n,m)!==s.ufIds[b])throw new p(`Neighborhood and municipality UFs differ: ${f}`)}}}function ho(e,t,n,r){let i=t.recordsOffset+(r-1)*t.recordWidth+t.originalIdWidth+t.localidadeIdWidth+n.bairro.idWidth+n.bairroAbreviado.idWidth;return R(e,i,n.uf.idWidth)}function yo(e,t){let n=new Uint32Array(t.runCount),r=new Uint32Array(t.runCount),i=2**t.lowBits,o=0,a=0;for(let s=0;s<t.highBitCount;s++){if((e.getUint8(t.highOffset+(s>>>3))&1<<(s&7))===0){o++;continue}let l=Do(e,t.lowOffset,a*t.lowBits,t.lowBits);n[a]=o*i+l,r[a]=R(e,t.idsOffset+a*t.idWidth,t.idWidth),a++}return{ids:r,starts:n}}function go(e,t,n){let r=new Uint32Array(n.count),i=new Uint32Array(n.count),o=new Uint8Array(n.count);for(let a=0;a<n.count;a++)r[a]=e.getUint32(n.startsOffset+a*4,!0),i[a]=R(e,n.idsOffset+a*t.municipalityIdWidth,t.municipalityIdWidth),o[a]=e.getUint8(t.sections.localidadeFlags.offset+a);return{flags:o,ids:i,starts:r}}function wo(e,t){let n=e.subarray(t.offset,t.offset+t.length);if(n[0]===239&&n[1]===187&&n[2]===191)throw new p("Binary database metadata must not contain a UTF-8 BOM");let r;try{r=JSON.parse(Jn.decode(n))}catch(i){throw new p("Binary database metadata is invalid JSON or UTF-8",{cause:i})}if(!r||typeof r!=="object"||Array.isArray(r))throw new p("Binary database metadata must be an object");for(let i of Object.values(r))if(typeof i!=="string")throw new p("Binary database metadata values must be strings")}function Eo(e,t,n){if(t.offset<O||t.offset>e||t.length>e-t.offset)throw new p(`Binary ${n} region is outside the payload`)}function Q(e,t,n){if(e.length!==t)throw new p(`Binary ${n} region has an invalid length`)}function He(e,t,n,r){for(let i=t;i<n;i++)if((e[i]??0)!==0)throw new p(`Invalid ${r}`)}function _o(e,t,n,r){if(n%8!==0){if(((e[t.offset+t.length-1]??0)&255<<(n&7))!==0)throw new p(`Invalid binary ${r} bitmap padding`)}}function So(e,t,n){let r=n*ne,i=t+Math.floor(r/8),o=r&7;return((e[i]??0)|(e[i+1]??0)<<8|(e[i+2]??0)<<16)>>>o&1023}function Do(e,t,n,r){let i=0;for(let o=0;o<r;o++){let a=n+o;if(e.getUint8(t+(a>>>3))&1<<(a&7))i+=2**o}return i}function tr(e){er(e);let t=e.byteLength-P;e.set(new Bun.CryptoHasher("sha256").update(e.subarray(0,t)).digest(),t)}function nr(e){let t=e.byteLength-P,n=new Bun.CryptoHasher("sha256").update(e.subarray(0,t)).digest();for(let r=0;r<P;r++)if(e[t+r]!==n[r])throw new p("Binary database SHA-256 checksum mismatch")}var tt=255,Io=255,wt=8,rr=510,gt=65536,Ao=[64,128,160,192,224];function ar(e){if(!e.count)throw Error("Cannot train FSST with an empty dictionary");let t=Ro(e),n=xo(To(t),Bo(t),t),r=Co(e,n);return{compressedLengths:r.maxLength<=255?Uint8Array.from(r.lengths):vo(r.lengths),lengthWidth:r.maxLength<=255?1:2,payload:r.payload,symbols:n.symbols}}function Ro(e){let t=e.totalBytes,n=[],r=Math.min(e.count,gt,Math.ceil(gt/Math.max(1,t/e.count))),i=e.count/Math.max(1,r),o=2654435769,a=0;for(let s=0;s<r&&a<gt;s++){o=Math.imul(o,1664525)+1013904223>>>0;let c=Math.floor(o/4294967296*Math.max(1,i)),l=Math.min(e.count-1,Math.floor(s*i)+c),u=e.get(l);if(!u?.byteLength)continue;let d=gt-a;n.push(u.byteLength<=d?u:u.subarray(0,d)),a+=Math.min(u.byteLength,d)}return n}function To(e){let t=new Map;for(let r of e)for(let i=0;i+1<r.byteLength;i++){let o="",a=Math.min(r.byteLength,i+wt);for(let s=i;s<a;s++)if(o+=String.fromCharCode(r[s]??0),s-i+1>=2)t.set(o,(t.get(o)??0)+1)}let n=[];for(let[r,i]of t){let o=r.length;n.push({key:r,length:o,score:i*(o-1)})}return n.sort(Uo),n.slice(0,4096)}function Bo(e){let t=new Uint32Array(256);for(let n of e)for(let r of n)t[r]=(t[r]??0)+1;return Array.from({length:256},(n,r)=>r).filter((n)=>(t[n]??0)>0).sort((n,r)=>(t[r]??0)-(t[n]??0)||n-r)}function xo(e,t,n){let r=ir(t.slice(0,tt).map((o)=>Uint8Array.of(o))),i={table:r,size:or(n,r).size};for(let o of Ao){let a=e.slice(0,o),s=a.length,c=t.slice(0,tt-a.length).map((l)=>Uint8Array.of(l));for(let l=0;l<4;l++){let u=a.map((b)=>No(b.key)).concat(c),d=ir(u),f=or(n,d);if(f.size<i.size)i={table:d,size:f.size};let m=a.filter((b,h)=>(f.uses[h]??0)>0);if(m.length===a.length||s===e.length)break;while(m.length<o&&s<e.length){let b=e[s++];if(b)m.push(b)}a=m}}return i.table}function ir(e){let t=new Uint8Array(de),n=sr();for(let[r,i]of e.entries()){if(r>=tt||i.byteLength<1||i.byteLength>wt)break;t[r]=i.byteLength,t.set(i,tt+r*wt),Oo(n,i,r)}return{symbols:t,trie:n}}function sr(){return{code:-1,children:new Map}}function Oo(e,t,n){let r=e;for(let i of t){let o=r.children.get(i);if(!o)o=sr(),r.children.set(i,o);r=o}r.code=n}function or(e,t){let n=0,r=new Uint32Array(tt);for(let i of e){let o=0;while(o<i.byteLength){let a=cr(i,o,t.trie);if(a)n++,r[a.code]=(r[a.code]??0)+1,o+=a.length;else n+=2,o++}}return{size:n,uses:r}}function Co(e,t){let n=new Uint32Array(e.count),r=e.totalBytes*2,i=new Uint8Array(r),o=0,a=0;for(let s=0;s<e.count;s++){let c=e.get(s),l=o;o=Lo(c,t,i,o);let u=o-l;if(n[s]=u,a=Math.max(a,u),u>rr)throw Error(`FSST compressed suffix exceeds ${rr} bytes: ${u}`)}return{lengths:n,maxLength:a,payload:i.slice(0,o)}}function Lo(e,t,n,r){let i=0,o=r;while(i<e.byteLength){let a=cr(e,i,t.trie);if(a)n[o++]=a.code,i+=a.length;else n[o++]=Io,n[o++]=e[i++]??0}return o}function cr(e,t,n){let r=n,i=-1,o=0,a=Math.min(e.byteLength,t+wt);for(let s=t;s<a;s++){let c=r.children.get(e[s]??0);if(!c)break;if(r=c,r.code>=0)i=r.code,o=s-t+1}return i<0?void 0:{code:i,length:o}}function No(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function Uo(e,t){return t.score-e.score||t.length-e.length||(e.key<t.key?-1:e.key>t.key?1:0)}function vo(e){let t=new Uint8Array(e.length*2),n=new DataView(t.buffer);for(let r=0;r<e.length;r++)n.setUint16(r*2,e[r]??0,!0);return t}var lr="dne",ur="dne.db",L="dne",he="bairros",Et="bairro_faixas",C="edne_metadata",dr=32768,fr=-200000,mr=1000,ae="https://www2.correios.com.br/sistemas/edne/download/eDNE_Basico.zip",pr=8,_t=2097152,br=30000,hr=2,yr=100,gr=1000,wr=2000;var rn=new TextEncoder,Fo=Le();async function Er(e,t,n=L){Jo();let r=new Mo(e,{readonly:!0});try{r.run("BEGIN");let i=Zo(r,n);if(St(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 ${
|
|
5
|
-
ORDER BY bairro_id, cep_inicial, cep_final`).all(),
|
|
3
|
+
import{t,o,s,a,f,r}from"./chunks/index-338dn00y.js";var go=Object.freeze(["bash","zsh","fish","powershell"]);import{Database as kc}from"bun:sqlite";import{statSync as io}from"fs";import{copyFile as Hc,mkdir as uo,mkdtemp as Wc,rename as lo,rm as ge}from"fs/promises";import{basename as jc,dirname as jn,extname as qc,join as qn,resolve as Zc}from"path";import{createHash as ko}from"crypto";var Do={ACAMPAMENTO:["ACAMP"],"ACESSO A AVENIDA":["AC AV"],"ACESSO DE PEDESTRE":["AC PED"],"ACESSO ESTADUAL":["AC ESTD"],"ACESSO LOCAL":["AC LOCAL"],"ACESSO PARA RUA":["AC R"],ADRO:["AD"],AEROPORTO:["AER"],ALCA:[],"ALCA DE ACESSO":["ALC ACES"],ALDEIA:["ALD"],"ALDEIA INDIGENA":["ALD IND"],ALTO:["AT"],ANEL:["AN"],"ANEL VIARIO":["AN VR"],"ANTIGA ESTACAO":["ANT ETC"],"ANTIGA ESTRADA":["ANT EST"],AREA:[],"AREA ESPECIAL":["AE"],"AREA VERDE":["A VERDE"],ARTERIA:["ART"],ATALHO:["ATL"],"AVENIDA CENTRAL":["AV CENT"],"AVENIDA CIRCULAR":["AV CIRC"],"AVENIDA CONTORNO":["AV CONT"],"AVENIDA ESPLANADA":["AV ESP"],"AVENIDA EXPRESSA":["AV EXP"],"AVENIDA INDUSTRIAL":["AV IND"],"AVENIDA INTEGRACAO":["AV INT"],"AVENIDA MARGINAL DIREITA":["AV MARG DIR"],"AVENIDA MARGINAL ESQUERDA":["AV MARG ESQ"],"AVENIDA MARGINAL NORTE":["AV MARG NORTE"],"AVENIDA NORTE SUL":["AV NORTE SUL"],"AVENIDA PERIMETRAL":["AV PER"],"AVENIDA VELHA":["AV VA"],BAIXA:["BX"],BALAO:["BLO"],BALNEARIO:["BALN"],"BECO 1":["BC 1"],"BECO 2":["BC 2"],"BECO 3":["BC 3"],BELVEDERE:["BELV"],BLOCO:["BL"],BLOCOS:["BLS"],BOSQUE:["BSQ"],BOULEVARD:["BVD"],BULEVAR:["BLV"],BURACO:[],CAIS:[],CALCADAO:[],CALCADINHO:["CALCNHO"],"CAMINHO DE SERVIDAO":["CAM SERV"],CAMPO:["CPO"],CAMPUS:[],CANAL:["CAN"],CENTRO:["CENTR"],"CENTRO ADMINISTRATIVO":["CENTR ADMIN"],"CENTRO COMERCIAL":["CENTR COMERC"],CHACARAS:["CHS"],CHAPADAO:["CHAP"],CICLOVIA:["CICL"],CIRCULAR:["CIRC"],COLINA:["CLNA"],COLONIA:["COL"],"COMPLEXO VIARIO":["CMP VR"],COMUNIDADE:["COM"],"COMUNIDADE QUILOMBOLA":["COM QUILOMB"],"COMUNIDADE RURAL":["COM RURA"],"COMUNIDADE SITIO":["COM SIT"],"COMUNIDADE URBANA":["COM URBA"],CONDOMINIO:["COND"],"CONDOMINIO RESIDENCIAL":["COND RES"],"CONJUNTO HABITACIONAL":["CJ HAB"],"CONJUNTO MUTIRAO":["CJ MUT"],"CONJUNTO RESIDENCIAL":["CJ RES"],CONTORNO:["CONT"],"CONTORNO VIARIO":["CONT VR"],CORREDOR:[],CORREGO:["CRG"],DESCIDA:["DSC"],DESVIO:["DSV"],DIAGONAL:["DIAG"],DISTRITO:[],EDIFICIO:["ED"],EIXO:["EX"],"EIXO INDUSTRIAL":["EX IND"],"EIXO PRINCIPAL":["EX PRINC"],ELEVADA:["EVD"],ELEVADO:["EVDO"],ENSEADA:["ENS"],ENTRADA:["ENT"],"ENTRADA PARTICULAR":["ENT PART"],"ENTRE BLOCO":["EBL"],"ENTRE QUADRA":["EQ"],ESCADA:["ESC"],"ESCADA DE PEDRA":["ESC PEDRA"],ESCADAO:["ESCO"],ESCADARIA:["ESCAD"],ESPLANADA:["ESP"],ESTACAO:["ETC"],"ESTACAO TRANSFORMADORA":["ECT TRANS"],ESTACIONAMENTO:["ESTC"],ESTADIO:["ETD"],ESTANCIA:["ETN"],"ESTRADA ANTIGA":["EST ANT"],"ESTRADA DE FERRO":["EST FER"],"ESTRADA DE LIGACAO":["EST LIG"],"ESTRADA DE SERVIDAO":["EST SRV"],"ESTRADA ECOTURISTICA":["EST ECOT"],"ESTRADA ESTADUAL":["EST ESTD"],"ESTRADA FEDERAL":["EST FED"],"ESTRADA INTERMUNICIPAL":["EST INTERM"],"ESTRADA MARGINAL":["EST MARG"],"ESTRADA MUNICIPAL":["EST MUN"],"ESTRADA MUNICIPAL PARA":["EST MUN PRA"],"ESTRADA NOVA":["EST N"],"ESTRADA PARA":["EST PRA"],"ESTRADA PARTICULAR":["EST PART"],"ESTRADA PRINCIPAL":["EST PRINC"],"ESTRADA REAL":["EST REAL"],"ESTRADA VELHA":["EST VELHA"],"ESTRADA VICINAL":["EST VIC"],"ESTRADA VICINAL MUNICIPAL":["EST VIC MUN"],EXPANSAO:["EXPAN"],FAIXA:["FX"],FAVELA:["FAV"],FAZENDA:["FAZ"],FEIRA:["FRA"],FERROVIA:["FER"],FOLHA:["FL"],FONTE:["FNT"],FORTE:["FTE"],GALERIA:[],GLEBA:["GLB"],GRANJA:["GJA"],ILHA:["IA"],ILHOTA:["IOA"],"JARDIM PUBLICO":["JD PUB"],"JARDIM RESIDENCIAL":["JD RES"],JARDINETE:["JDE"],LAGO:[],LAGOA:["LGA"],LARGO:["LRG"],"LARGO DA BASILICA":["LRG BAS"],LIGACAO:["LIG"],LOCALIDADE:["LOC"],LOTE:["LT"],MARGEM:["MRG"],MARGINAL:["MARG"],MARINA:["MNA"],MERCADO:["MERC"],MIRANTE:["MT"],MODULO:["MOD"],"MODULO COMERCIAL":["MC"],MONTE:["MTE"],MORRO:["MRO"],"NOVA AVENIDA":["N AV"],"NUCLEO HABITACIONAL":["NUC HAB"],"NUCLEO RURAL":["NUC RURAL"],OCUPACAO:["OCUP"],"ORLA FLUVIAL":["OR FL"],OUTEIRO:["OUT"],PARADOURO:["PDO"],PARALELA:["PAR"],PARCELAMENTO:["PARC"],"PARQUE MUNICIPAL":["PRQ MUNIC"],"PARQUE RESIDENCIAL":["PRQ RES"],"PASSAGEM DE PEDESTRES":["PSG PED"],"PASSAGEM PARTICULAR":["PSG PART"],"PASSAGEM SUBTERRANEA":["PSG SUB"],PASSARELA:["PSA"],PASSEIO:["PAS"],"PASSEIO PUBLICO":["PAS PUB"],PATIO:["PAT"],PEDESTRE:["PED"],"PISTA LATERAL":["PTA LAT"],PONTA:["PTA"],PONTE:["PTE"],PONTILHAO:["PNTL"],PORTO:[],POVOADO:["POV"],"PRACA DA MATRIZ":["PC MATRIZ"],"PRACA DE ESPORTES":["PC ESP"],"PRACA E CAMPO":["PC CPO"],"PRACA GIRATORIA":["PRCA GIRT"],"PRACA ROTATORIA":["PCA ROT"],PRACINHA:[],PRAIA:[],PROJECAO:[],"PROLONGAMENTO DA AVENIDA":["PRL AV"],"PROLONGAMENTO DA RUA":["PRL R"],QUADRA:[],"QUARTA LADEIRA":["4 LD"],"QUINTA LADEIRA":["5 LD"],QUINTAS:["QTAS"],RAMAL:["RAM"],RAMPA:["RMP"],RECANTO:["REC"],RECREIO:["RCR"],RETA:[],RETIRO:["RER"],RETORNO:["RTN"],"RODO ANEL":["ROD AN"],"RODOVIA DE ACESSO":["ROD AC"],"RODOVIA ESTADUAL":["ROD ESTD"],"RODOVIA MUNICIPAL":["ROD MUN"],"RODOVIA VICINAL":["ROD VIC"],ROTATORIA:["RTT"],ROTULA:[],"RUA CIRCULAR":["R CIRC"],"RUA CONTORNO":["R CONT"],"RUA DE LIGACAO":["R LIG"],"RUA DE PEDESTRE":["R PED"],"RUA FERROVIARIA":["R FERR"],"RUA INDUSTRIAL":["R IND"],"RUA INTEGRACAO":["R INTEG"],"RUA MARGINAL":[],"RUA PEDESTRE":["RPED"],"RUA PERIMETRAL":[],"RUA PRINCIPAL":["R PRINC"],"RUA PROJETADA":[],"RUA TRANSVERSAL":["R TRANSV"],"RUA VELHA":["R VELHA"],"RUA VICINAL":["R VIC"],RUELA:["RLA"],"SEGUNDA AVENIDA":["SEG AV"],"SEMI ANEL VIARIO":["S AN V"],SERVIDAO:["SRV"],"SERVIDAO DE PASSAGEM":["SRV PSG"],SETOR:[],"SISTEMA VIARIO":["SIS VR"],SUBIDA:["SUB"],TEMPORARIO:["TEMP"],"TERCEIRA AVENIDA":["TERC AV"],TERMINAL:["TER"],TIFA:["TF"],"TRAVESSA DA RUA":["TV DA RUA"],"TRAVESSA DE PEDESTRE":["TV PED"],"TRAVESSA I":["TV I"],"TRAVESSA II":["TV II"],"TRAVESSA III":["TV III"],"TRAVESSA PARTICULAR":["TV PART"],"TRAVESSA PROJETADA":["TV PROJ"],"TRAVESSA VELHA":["TV VELHA"],TRAVESSIA:["TRAVESS"],TRECHO:[],TREVO:[],"TREVO ROTATORIO":["TRV RTTO"],TRILHA:["TL"],"TRILHA DE ACESSO":["TL DE AC"],TRINCHEIRA:["TCH"],TUNEL:["TUN"],UNIDADE:["UNID"],VALA:["VAL"],VALE:["VLE"],VARIANTE:["VRTE"],"VARIANTE DA ESTRADA":["VRTE EST"],VEREDA:[],"VIA CIRCULAR":["V CIRCU"],"VIA COLETORA":["V COLET"],"VIA COSTEIRA":["V COST"],"VIA CULTURAL":["V CULT"],"VIA DE ACESSO":["V AC"],"VIA DE CIRCULACAO":["V CIRC"],"VIA DE PEDESTRE":["V PED"],"VIA DE PEDESTRES":["V PEDS"],"VIA DIRETRIZ":["VL DIR"],"VIA ELEVADO":["V EVD"],"VIA ESTRADA MUNICIPAL":["V EST MUN"],"VIA EXPRESSA":["V EXP"],"VIA LATERAL":["V LAT"],"VIA LITORANEA":["V LIT"],"VIA LOCAL":["V LOCAL"],"VIA MARGINAL":["V MARG"],"VIA MUNICIPAL":["V MUN"],"VIA PEDESTRE":["VPED"],"VIA PRINCIPAL":["V PRINC"],VICINAL:["VC"],"VICINAL MUNICIPAL":["VC MUN"],"VIELA DA RUA":[],"VIELA DE ACESSO":[],"VIELA MUNICIPAL":[],"VILA RURAL":["VL R"],"ZIGUE ZAGUE":["ZIG ZAG"],"ZONA RURAL":["Z R"],"1 ACESSO":["1 AC"],"1 ALTO":["1 AT"],"1 AVENIDA":["1 AV"],"1 BECO":["1 BC"],"1 ESCADA":["1 ESC"],"1 ESCADARIA":["1 ESCAD"],"1 LADEIRA":["1 LD"],"1 PARALELA":["1 PAR"],"1 PARQUE":["1 PRQ"],"1 RUA":["1 R"],"1 SUBIDA":["1 SUB"],"1 TRAVESSA":["1 TV"],"1 TRAVESSA DA AVENIDA":["1 TV DA AV"],"1 TRAVESSA DA RODOVIA":["1 TV DA ROD"],"1 TRAVESSA DA RUA":["1 TV DA R"],"1 VIA COLETORA":["1 V COLET"],"1 VIELA":["1 VLA"],"1 VILA":["1 VL"],"10 AVENIDA":["10 AV"],"10 ESCADARIA":["10 ESCAD"],"10 RUA":["10 R"],"10 TRAVESSA":["10 TV"],"11 AVENIDA":["11 AV"],"11 RUA":["11 R"],"11 TRAVESSA":["11 TV"],"12 RUA":["12 R"],"12 TRAVESSA":["12 TV"],"13 TRAVESSA":["13 TV"],"14 TRAVESSA":["14 TV"],"15 TRAVESSA":["15 TV"],"16 TRAVESSA":["16 TV"],"17 TRAVESSA":["17 TV"],"18 TRAVESSA":["18 TV"],"19 TRAVESSA":["19 TV"],"2 ACESSO":["2 AC"],"2 ALAMEDA":["2 AL"],"2 ALTO":["2 AT"],"2 AVENIDA":["2 AV"],"2 BECO":["2 BC"],"2 ESCADA":["2 ESC"],"2 ESCADARIA":["2 ESCAD"],"2 LADEIRA":["2 LD"],"2 PARALELA":["2 PAR"],"2 PARQUE":["2 PRQ"],"2 RUA":["2 R"],"2 SUBIDA":["2 SUB"],"2 TRAVESSA":["2 TV"],"2 TRAVESSA DA RODOVIA":["2 TV ROD"],"2 TRAVESSA DA RUA":["2 TV DA R"],"2 VIA":["2 V"],"2 VIA COLETORA":["2 V COLET"],"2 VIELA":["2 VLA"],"2 VILA":["2 VL"],"20 TRAVESSA":["20 TV"],"21 TRAVESSA":["21 TV"],"22 TRAVESSA":["22 TV"],"26 TRAVESSA":["26 TV"],"3 ACESSO":["3 AC"],"3 ALTO":["3 AT"],"3 AVENIDA":["3 AV"],"3 BECO":["3 BC"],"3 ESCADARIA":["3 ESCAD"],"3 LADEIRA":["3 LD"],"3 PARALELA":["3 PAR"],"3 PARQUE":["3 PRQ"],"3 RUA":["3 R"],"3 SUBIDA":["3 SUB"],"3 TRAVESSA":["3 TV"],"3 TRAVESSA DA RUA":["3 TV DA R"],"3 VILA":["3 VL"],"4 ALTO":["4 AT"],"4 AVENIDA":["4 AV"],"4 BECO":["4 BC"],"4 ESCADARIA":["4 ESCAD"],"4 PARALELA":["4 PAR"],"4 RUA":["4 R"],"4 SUBIDA":["4 SUB"],"4 TRAVESSA":["4 TV"],"4 TRAVESSA DA RUA":["4 TV DA R"],"4 VILA":["4 VL"],"5 ALTO":["5 AT"],"5 AVENIDA":["5 AV"],"5 BECO":["5 BC"],"5 ESCADARIA":["5 ESCAD"],"5 PARALELA":["5 PAR"],"5 RUA":["5 R"],"5 SUBIDA":["5 SUB"],"5 TRAVESSA":["5 TV"],"5 TRAVESSA DA RUA":["5 TV DA R"],"5 VILA":["5 VL"],"6 AVENIDA":["6 AV"],"6 BECO":["6 BC"],"6 ESCADARIA":["6 ESCAD"],"6 RUA":["6 R"],"6 SUBIDA":["6 SUB"],"6 TRAVESSA":["6 TV"],"6 VILA":["6 VL"],"7 AVENIDA":["7 AV"],"7 ESCADARIA":["7 ESCAD"],"7 RUA":["7 R"],"7 TRAVESSA":["7 TV"],"8 AVENIDA":["8 AV"],"8 ESCADARIA":["8 ESCAD"],"8 RUA":["8 R"],"8 TRAVESSA":["8 TV"],"9 AVENIDA":["9 AV"],"9 ESCADARIA":["9 ESCAD"],"9 RUA":["9 R"],"9 TRAVESSA":["9 TV"]},yo={ABADE:["AB"],ABADESSA:["ABS"],ABOLICIONISTA:["ABOLIC"],ACADEMICA:["ACDA"],ACADEMICO:["ACDO"],ADMINISTRADOR:["ADM"],ADVOGADA:[],"ADVOGADO DOUTOR":["ADV DR"],AGENTE:["AG"],"AGENTE ADMINISTRATIVO":["AG ADM"],"AGENTE DE ESTACAO":["AG EST"],"AGENTE DE INVESTIGACAO":["AG INV"],"AGENTE FISCAL":["AG FISC"],"AGENTE POLICIAL":["AG POL"],"AGENTE POSTAL":["AG POS"],AGRICULTOR:[],AGRICULTORA:[],AGRIMENSOR:["AGRIM"],AGRONOMA:[],AGRONOMO:[],AGROPECUARISTA:["AGROP"],AJUDANTE:["AJ"],"ALCAIDE MOR":["ALC MOR"],ALFAIATE:["ALFT"],"ALMIRANTE MARQUES":["ALM MQ"],"ALMIRANTE PADRE":["ALM PE"],ALMOCREVE:["ALMOC"],ALMOTACEL:["ALMOT"],ALUNA:[],ALUNO:[],AMBIENTALISTA:["AMB"],ANALISTA:["ANL"],ANCIAO:["ANC"],ANJO:[],ANSPECADA:["ANSP"],ANTROPOLOGO:["ANT"],APICULTOR:["APIC"],APOSENTADA:[],APOSENTADO:[],APOSTOLO:["APOST"],"APOSTOLO SANTO":["APOST STO"],"APOSTOLO SAO":["APOST S"],APRENDIZ:["APDZ"],APRESENTADOR:["APRES"],ARCANJO:["ARCJ"],ARCEBISPO:["ARC"],"ARCEBISPO DOM":["ARC D"],ARQUEOLOGA:[],ARQUEOLOGO:[],ARQUITETA:[],"ARQUITETO PROFESSOR":["ARQ PRF"],ARQUIVISTA:["ARQVA"],ARTESA:["ARTSA"],ARTESAO:["ARTS"],ARTIFICE:["ARTF"],ARTISTA:["ART"],"ARTISTA PLASTICA":["ART PLSTA"],"ARTISTA PLASTICO":["ART PLSTO"],ARTISTAS:["ARTIS"],ASPIRANTE:["ASP"],"ASSISTENTE SOCIAL":["ASS SOC"],ASTROLOGO:["ASTL"],ASTRONAUTA:["ASTN"],ASTRONOMO:["ASTR"],ATENDENTE:["ATDE"],ATIRADOR:["ATDOR"],ATLETA:["ATL"],ATOR:[],ATRIZ:["ATZ"],AUDITOR:[],"AUDITOR FISCAL":["AUD FISC"],AUDITORA:[],AUTOR:["ATR"],AUTORA:[],"AUXILIAR DE ESCRITORIO":["AUX ESC"],AVIADOR:[],"AVIADOR MARQUES":["AV MQ"],"AVIADOR MILITAR":["AV MIL"],AVIADORA:[],AVO:[],BABALORIXA:["BORIXA"],BACAMARTEIRO:[],BACHAREL:["BEL"],BAILARINA:["BAILA"],"BAILARINA ESPECIAL":["BAILA ESP"],BAILARINO:["BAIL"],BALCONISTA:["BAL"],BANCARIA:["BANCA"],BANCARIO:["BANC"],BANDEIRANTE:["BANTE"],BANDEIREIRO:["BEIRO"],BANDEIRINHA:["BINHA"],BANDEIRISTA:["BISTA"],BARBEIRO:["BARB"],BARONESA:["BRA"],BARONEZA:["BRZA"],BEATA:["BTA"],"BEATA MADRE":["BTA ME"],BEATO:["BTO"],"BEATO FREI":["BTO FR"],"BEATO MONSENHOR":["BTO MNS"],"BEATO PADRE":["BTO PE"],"BEM AVENTURADO":["B AVENT"],BENEMERITA:["BENA"],BENEMERITO:["BEN"],BENFEITOR:["BENF"],"BENFEITOR JOVEM":["BENF JOV"],BENZEDEIRA:["BENZ"],BIBLIOTECARIA:["BIBL"],BILHETEIRA:["BILHET"],BIOLOGA:["BIOLA"],BIOLOGO:["BIOL"],"BISPO DOM":["BPO D"],BOMBEIRA:["BOMBR"],BOMBEIRO:["BOMB"],BOTANICO:["BOT"],"BRIGADEIRO DO AR":["BRG AR"],CABELEIREIRA:["CABELA"],CABO:["CB"],"CABO FREI":["CB FR"],"CABO POLICIA MILITAR":["CB PM"],CADETE:["CAD"],CAFEICULTOR:["CAF"],CAMAREIRA:["CAR"],CAMARISTA:["CAT"],CAMINHONEIRO:["CAMHRO"],CANTOR:["CT"],"CANTOR E COMPOSITOR":["CT E CPTO"],"CANTOR SERTANEJO":["CT SERT"],CANTORA:["CTA"],CAPATAZ:["CAPZ"],CAPELAO:["CAPL"],"CAPELAO MILITAR":["CAPL MIL"],CAPITA:[],"CAPITAO AVIADOR":["CAP AV"],"CAPITAO BARAO":["CAP BR"],"CAPITAO CAPELAO":["CAP CAPL"],"CAPITAO DOUTOR":["CAP DR"],"CAPITAO FREI":["CAP FR"],"CAPITAO INDIO":["CAP ID"],"CAPITAO MEDICO":["CAP MED"],"CAPITAO MOR":["CAP MOR"],"CAPITAO PRIMO":["CAP PRIM"],"CAPITAO POLICIA MILITAR":["CAP PM"],CARCEREIRO:["CARC"],"CARDEAL BISPO DOM":["CARD BPO D"],"CARDEAL DOM":["CARD D"],CARNAVALESCO:["CARNAV"],CARPINTEIRO:["CARP"],CARRETEIRO:["CARR"],CARROCEIRO:["CARROC"],CARTEIRO:["CART"],CARTORARIO:["CRTO"],CARTUNISTA:["CARTUN"],CATEQUISTA:["CATQ"],CAVALHEIRO:["CAV"],CEGO:[],CENOTECNICO:["CEN"],CENTENARIA:["CENTIA"],CENTENARIO:["CENT"],CERAMISTA:["CER"],CHANCELER:[],CHEFE:[],CHOFER:["CHOF"],CICLISTA:["CICL"],CIDADA:[],"CIDADA EMERITA DOUTORA":["CID EMTA DRA"],CIDADAO:[],"CIDADAO PRESTANTE":["CID PREST"],CIENTISTA:["CIENT"],CINEASTA:["CINET"],CINEGRAFISTA:["CINEG"],CIRURGIAO:["CIRURG"],COLETOR:["COL"],COLETORA:["COLRA"],COLONIZADOR:["COLON"],COLUNISTA:["COLU"],"COLUNISTA SOCIAL":["COLU SOC"],COMADRE:["CME"],COMANDANTE:["CMTE"],"COMANDANTE AVIADOR":["CMTE AV"],COMBATENTE:["CBTE"],COMEDIANTE:["COMED"],COMENDADOR:["CDOR"],"COMENDADOR CAPITAO":["CDOR CAP"],"COMENDADOR DOUTOR":["CDOR DR"],"COMENDADOR PROFESSOR":["CDOR PRF"],COMENDADORA:["CDORA"],COMERCIANTE:["COTE"],COMERCIARIO:["COMERC"],COMISSARIA:["CMISA"],COMISSARIO:["CMISO"],"COMISSARIO DE POLICIA":["CMISO POL"],COMODORO:["CDRO"],COMPADRE:["COPE"],COMPANHEIRA:["COMPA"],"COMPANHEIRA LEAO":["COMPA LEAO"],COMPANHEIRO:["COMPO"],COMPOSITOR:["CPTO"],COMPOSITORA:["CPTA"],COMUNITARIA:["CMTA"],COMUNITARIO:["CMTO"],CONDE:["CD"],CONDESSA:["CDA"],CONEGO:["CON"],"CONEGO DOUTOR":["CON DR"],CONFRADE:["COFE"],CONSELHEIRA:["CNSA"],"CONSELHEIRA TUTELAR":[],CONSELHEIRO:["CNSO"],"CONSELHEIRO DOUTOR":["CNSO DR"],"CONSELHEIRO TUTELAR":[],CONSTRUTOR:["CONST"],CONSUL:["CSL"],CONSULESA:["CSLA"],CONTABILISTA:["CONTAB"],CONTADOR:["CONT"],CONTADORA:["CONTA"],COOPERADOR:["COOP"],CORNETEIRO:["CORN"],"CORONEL AVIADOR":["CEL AV"],"CORONEL BOMBEIRO":["CEL BOMB"],"CORONEL DOUTOR":["CEL DR"],"CORONEL POLICIA MILITAR":["CEL PM"],CORREDOR:["CRDR"],CORRETOR:["CORT"],"CORRETOR CONEGO":["CORT CON"],COSTUREIRA:["COST"],CRONISTA:["CRTA"],CRUZADOR:["CRUZ"],DELEGADA:["DELA"],DELEGADO:["DEL"],"DELEGADO DOUTOR":["DEL DR"],DENTISTA:["DENT"],DEPUTADA:["DEPA"],"DEPUTADO DOUTOR":["DEP DR"],"DEPUTADO ESTADUAL":["DEP EST"],"DEPUTADO FEDERAL":["DEP FED"],"DEPUTADO FEDERAL DOUTOR":["DEP FED DR"],DESBRAVADOR:["DESB"],"DESEMBARGADOR DOUTOR":["DES DR"],DESENHISTA:["DENH"],DESPACHANTE:["DECH"],DESPORTISTA:["DESP"],DETETIVE:["DET"],DIACONISA:[],DICIONARISTA:["DIC"],DIPLOMATA:["DIPL"],DIRETOR:["DIR"],"DIRETOR PUBLICITARIO":["DIR PUBL"],DIRETORA:["DIRA"],DISCIPULO:["DISCI"],DISTRIBUIDOR:["DIST"],DIVULGADOR:["DIVU"],DOADORA:["DOA"],"DOM ABADE":["D AB"],"DOM BISPO":["D BPO"],"DOM FREI":["D FR"],"DOM INFANTE":["D INF"],DOMESTICA:["DOME"],"DONA SANTA":["DA STA"],"DONA SINHA":["DA SINHA"],DONATARIO:["DONT"],"DOUTOR DEPUTADO":["DR DEP"],"DOUTOR INFANTE":["DR INF"],"DOUTOR PROFESSOR":["DR PRF"],"DOUTOR VEREADOR":["DR VER"],DOUTORES:["DRS"],"DUQUE ENGENHEIRO AGRONOMO":["DQ ENG AGRON"],ECOLOGISTA:["ECOL"],ECONOMISTA:["ECON"],EDITOR:["ED"],EDUCADOR:[],EDUCADORA:[],ELETRICISTA:["ELETR"],EMANCIPADOR:["EMANC"],"EMANCIPADORA PROFESSORA":["EMANC PRFA"],EMBAIXATRIZ:["EMBZ"],EMBOLADOR:["EMBL"],EMPRESARIA:["EMPA"],EMPRESARIO:["EMP"],ENCONTRISTA:["ENC"],"ENGENHEIRA QUIMICA":["ENGA QUIMA"],"ENGENHEIRO AGRIMENSOR":["ENG AGRIM"],"ENGENHEIRO AGRONOMO":["ENG AGRON"],"ENGENHEIRO ARQUITETO":["ENG ARQ"],"ENGENHEIRO CIVIL":["ENG CIV"],"ENGENHEIRO DOUTOR":["ENG DR"],"ENGENHEIRO QUIMICO":["ENG QUIM"],ENGRAXATE:["ENGX"],ENXADRISTA:["ENX"],ESCOTEIRO:["ESCT"],ESCRAVA:["EVA"],ESCRAVO:["EVO"],ESCREVENTE:["ESCREV"],ESCRITOR:["ESC"],ESCRITORA:["ESCA"],ESCRIVA:["ESCR"],ESCRIVAO:["EVAO"],ESCULTOR:["ETOR"],ESCULTORA:["ETORA"],ESPERANTISTA:["ESPTA"],ESPORTISTA:["ESP"],ESTATISTICA:["ESTA"],ESTATISTICO:["ESTO"],ESTIVADOR:["ESTV"],ESTUDANTE:["ESTUD"],EVANGELICA:["EVGCA"],EVANGELICO:["EVGCO"],EVANGELISTA:["EVGTA"],EVANGELIZADORA:["EVGDRA"],EXATOR:["EXT"],"EX COMBATENTE":["EX COMB"],EXPEDICIONARIO:["EXP"],"EXPEDICIONARIO CABO":["EXP CB"],"EXPEDICIONARIO SOLDADO":["EXP SD"],"EXPEDICIONARIO TENENTE":["EXP TEN"],EXPEDICIONARIOS:["EXPS"],"EX PREFEITO":["EX PREF"],"EX PREFEITO DOUTOR":["EX PREF DR"],"EX VEREADOR":["EX VER"],FARMACEUTICA:["FARMAC"],FARMACEUTICO:["FARM"],FAZENDEIRO:["FZDRO"],FEIRANTE:["FEI"],FERROVIARIA:["FRVA"],FERROVIARIO:["FRO"],FILANTROPO:["FTPO"],FILOSOFO:["FIL"],FISCAL:["FISC"],"FISCAL DE TRANSITO":["FISC TRANS"],"FISCAL MUNICIPAL":["FISC MUN"],FISICO:["FIS"],FOLCLORISTA:["FOLC"],FOLIAO:["FLO"],FORROZEIRO:["FORR"],FOTOGRAFA:[],FOTOGRAFO:[],"FOTOGRAFO JORNALISTICO":["FOT JORN"],FRADE:["FDE"],"FREI MADRE":["FR ME"],"FREI SANTA":["FR STA"],"FREI SAO":["FR S"],FREIRA:["FRA"],FUNCIONARIA:[],"FUNCIONARIA PUBLICA":[],FUNCIONARIO:[],"FUNCIONARIO PUBLICO":[],FUNDADOR:["FUND"],FUNILEIRO:["FUNIL"],FURRIEL:["FURR"],FUZILEIRO:["FUZ"],"FUZILEIRO NAVAL":["FUZ NAVAL"],GARCOM:["GAR"],GAZETEIRO:["GAZET"],"GENERAL DE BRIGADA":["GEN BRIG"],"GENERAL DE DIVISAO":["GEN DIV"],"GENERAL DE EXERCITO":["GEN EX"],"GENERAL DOUTOR":["GEN DR"],GENERALISSIMO:["GENRL"],GEOGRAFO:["GEOGR"],GEOLOGO:["GEOL"],GOLEIRO:["GOL"],"GOVERNADOR DOUTOR":["GOV DR"],"GOVERNADOR GENERAL":["GOV GEN"],"GRA DUQUESA":["GR DQA"],GRAFICO:["GRAF"],GRAO:["GR"],"GRAO MESTRE":["GR MTE"],GUARDA:["GDA"],"GUARDA CIVIL METROPOLITANO":["GDA CIV METR"],"GUARDA CIVIL MUNICIPAL":["GDA CIV MUN"],"GUARDA DE TRANSITO":["GDA TRANS"],"GUARDA MUNICIPAL":["GDA MUN"],"GUARDA TERRITORIAL":["GT"],"GUARDA CIVIL":["GDA CIV"],"GUARDA MARINHA":["GDA M"],"GUARDA MOR":["GDA MOR"],GUARDIAO:["GDAO"],GUERREIRA:[],GUERREIRO:[],HEROI:["HRO"],HEROINA:["HRA"],HEROIS:["HRIS"],HIDROGRAFO:["HIDGO"],HISTORIADOR:["HISTO"],HISTORIADORA:["HISTA"],HUMORISTA:["HUM"],ILUSTRADOR:["ILUST"],IMACULADA:["IMAC"],IMIGRANTE:["IMIG"],IMIGRANTES:["IMIGS"],IMPERADOR:["IMP"],"IMPERADOR DOM":["IMP D"],IMPERATRIZ:["IMPZ"],"IMPERATRIZ DONA":["IMPZ DA"],INDIA:["IDA"],INDIO:["ID"],INDUSTRIAL:["IND"],"INFANTE DOM":["INF D"],INSPETOR:["INSP"],INSPETORA:["INSPA"],INTENDENTE:["INT"],"INTENDENTE CORONEL":["INT CEL"],"INTENDENTE DOUTOR":["INT DR"],"INTERDISTRITAL COMENDADOR":["INTR CDOR"],INTERVENTOR:["INVO"],INVENTOR:["INV"],INVESTIGADOR:["INTGO"],"INVESTIGADOR DE POLICIA":["INTGO POL"],INVESTIGADORA:["INTGA"],IRMANDADE:["IRMD"],IRMAOS:["IMOS"],IRMAS:["IMAS"],JANGADEIRO:["JAN"],JARDINEIRA:["JARDA"],JARDINEIRO:["JARD"],JOGADOR:["JOG"],JORNALISTA:["JORN"],"JORNALISTA DOUTOR":["JORN DR"],"JORNALISTA PROFESSOR":["JORN PRF"],JOVEM:["JOV"],JOVENS:["JOVS"],"JUIZ DE DIREITO":["JZ DIR"],"JUIZ DE DIREITO DOUTOR":["JZ DIR DR"],"JUIZ DE ORFAO CAPITAO":["JUIZ DE O CAP"],"JUIZ DE PAZ":["JZ PZ"],"JUIZ DOUTOR":["JZ DR"],"JUIZ ORDINARIO":["JUIZ ORD"],JUIZA:["JZA"],JURISTA:["JUR"],LABORATORISTA:["LAB"],LAVADEIRA:["LAVAD"],LAVRADOR:["LAV"],LEGIONARIO:["LEG"],LEILOEIRO:["LEIL"],LIBERTADOR:["LIB"],"LIBERTADOR DOM":["LIB D"],"LIDER COMUNITARIA":["LID COMA"],"LIDER COMUNITARIO":["LID COM"],LIVREIRO:["LIV"],LOCUTOR:["LOC"],LORD:[],MACOM:["MAC"],MADAME:["MME"],"MADRE ABADESSA":["ME ABS"],MADRINHA:["MAD"],MADRINHEIRO:["MADO"],MAE:[],MAESTRINA:["MCA"],"MAESTRO CAPITAO":["MTO CAP"],"MAESTRO PROFESSOR":["MTO PRF"],"MAESTRO REVERENDO":["MTO REV"],"MAESTRO TENENTE":["MTO TEN"],MAGICO:["MAGI"],MAGISTRADO:["MAG"],"MAJOR AVIADOR":["MAJ AV"],"MAJOR DE EXERCITO":["MAJ EX"],"MAJOR DOUTOR":["MAJ DR"],"MAJOR MEDICO":["MAJ MED"],"MAJOR BRIGADEIRO":["MAJ BRG"],"MAJOR BRIGADEIRO DO AR":["MAJ BRG AR"],"MAJOR POLICIA MILITAR":["MAJ PM"],MAQUINISTA:["MAQ"],MARCENEIRO:["MARC"],MARCHANTE:["MARCH"],"MARECHAL DOUTOR":["MAL DR"],"MARECHAL DO AR":["MAL AR"],MARINHEIRO:[],MARQUESA:["MQA"],MECANICO:["MEC"],MEDICA:[],"MEDICO INDUSTRIAL":["MED IND"],MEDIUM:["MEDM"],MENINA:[],MENINO:[],MENSAGEIRO:["MENS"],MERGULHADOR:["MRG"],"MESTRA DE REISADO":["MTA REISADO"],MESTRE:["MTE"],"MESTRE DE GUERREIRO":["MTE GERR"],"MESTRE DE OBRA":["MTE OBRA"],"MESTRE PROFESSOR":["MTE PRF"],MESTRES:["MTES"],METALURGICO:["MET"],MINEIRO:["MNO"],"MINISTRO DOUTOR":["MIN DR"],MIRANTE:["MIRA"],MISS:[],MISSIONARIA:["MISA"],MISSIONARIO:["MIS"],MISTER:["MR"],MONGE:["MGE"],MONITOR:["MON"],MONSENHOR:["MNS"],"MONSENHOR DOM":["MNS D"],"MONSENHOR DOUTOR":["MNS DR"],MONSIEUR:["MSR"],MOTORISTA:["MOT"],MOTOTAXISTA:["MTAX"],MUNICIPALISTA:["MUN"],"MUNICIPALISTA DOUTOR":["MUN DR"],MUSEOLOGA:["MUSEOL"],MUSICISTA:["MUSIC"],MUSICO:["MUS"],"MUSICO E COMPOSITOR":["MUS E CPTO"],NATURALISTA:["NAT"],NAVEGADOR:["NAV"],NONO:[],NORMALISTA:["NOR"],"NOSSA SENHORA IMACULADA":["N SRA IMAC"],"NOSSO SENHOR":["N SR"],NUNCIO:["NCO"],NUTRICIONISTA:["NUTRA"],OBREIRO:["OBRE"],ODONTOLOGA:["ODONTA"],ODONTOLOGO:["ODONT"],OFICIAL:["OF"],"OFICIAL DE JUSTICA":["OF JUST"],"OFICIAL POLICIAL MILITAR":["OF POL MIL"],OGUM:["OG"],OPERADOR:["OPE"],OPERARIA:["OPA"],OPERARIO:["OP"],ORGANISTA:["ORG"],OUVIDOR:["OUV"],OXOSSI:["OX"],PADEIRO:["PDO"],"PADRE CONEGO":["PE CON"],"PADRE DOM":["PE D"],"PADRE FREI":["PE FR"],"PADRE SANTO":["PE STO"],"PADRE SEGUNDO":["PE SEG"],PADRES:["PES"],PADRINHO:["PAD"],PADROEIRO:["PADR"],PAI:[],PAISAGISTA:["PAISAG"],PAPA:[],"PAPA SANTO":["PAPA STO"],"PAPA SAO":["PAPA S"],PARTEIRA:[],"PARTEIRA DONA":["PART DA"],"PARTEIRA MAE":["PART MAE"],PASSISTA:["PAS"],PASTOR:["PST"],"PASTOR DOUTOR":["PST DR"],"PASTOR TENENTE":["PAST TEN"],PASTORA:["PSTA"],PATRAO:["PAT"],"PATRAO MOR":["PAT MOR"],PATRIARCA:["PTCA"],PATRIOTA:["PATR"],PATRONO:["PTNO"],PATRULHEIRA:["PTRA"],PATRULHEIRO:["PTRO"],PEDESTRE:["PED"],PEDREIRO:["PEDR"],PERITO:["PER"],PESCADOR:["PESC"],PIANISTA:["PNTA"],PILOTO:["PIL"],PINTOR:[],PINTORA:["PTA"],PIONEIRA:["PIONA"],PIONEIRO:["PION"],"PIONEIRO SANTO":["PIO STO"],POCEIRO:["POC"],POETA:["POE"],"POETA DOUTOR":["POE DR"],"POETA ESCRITOR":["POE ESC"],"POETA PRUDENTINO":["POE PRUD"],POETISA:["POT"],"POETISA DONA":["POT DA"],POLICIAL:["POL"],"POLICIAL CIVIL":["POL CIV"],"POLICIAL MILITAR":["POL MIL"],"POLICIAL PENAL":["POL PENAL"],PORTUARIO:["PORT"],POSTALISTA:["POST"],PRACA:["PRC"],PRACINHA:["PRAC"],PREFEITA:["PREFA"],"PREFEITA SANTA":["PREFA STA"],"PREFEITO CORONEL":["PREF CEL"],"PREFEITO DOUTOR":["PREF DR"],PREGADOR:["PRG"],PRESBITERO:["PRESB"],"PRESIDENTE BARAO":["PRES BR"],"PRESIDENTE DOUTOR":["PRES DR"],"PRESIDENTE GENERAL":["PRES GEN"],"PRESIDENTE MARECHAL":["PRES MAL"],PRIMA:["PMA"],"PRIMEIRA DAMA":["PRI DAM"],"PRIMEIRO MINISTRO":["P MIN"],"PRIMEIRO SARGENTO":["P SRG"],"PRIMEIRO SARGENTO POLICIA MILITAR":["P SRG PM"],"PRIMEIRO TENENTE":["P TEN"],"PRIMEIRO TENENTE AVIADOR":["P TEN AV"],PRIMO:["PMO"],PRINCESA:["PRCA"],"PRINCESA DONA":["PRCA DA"],PRINCEZA:["PRZA"],PRINCIPE:["PRCE"],"PRINCIPE DOM":["PRCE D"],PROCURADOR:["PROC"],PROFESSOR:["PRF"],"PROFESSOR CAPITAO":["PRF CAP"],"PROFESSOR DOUTOR":["PRF DR"],"PROFESSOR DOUTOR ENGENHEIRO":["PRF DR ENG"],"PROFESSOR E ENGENHEIRO DOUTOR":["PRF ENG DR"],"PROFESSOR E JORNALISTA":["PRF E JORN"],"PROFESSOR ENGENHEIRO":["PRF ENG"],"PROFESSOR INDIO":["PRF ID"],"PROFESSOR IRMAO":["PRF IRMO"],"PROFESSOR PADRE":["PRF PE"],"PROFESSOR VELHO":["PRF VO"],PROFESSORA:["PRFA"],"PROFESSORA DONA":["PRFA DA"],"PROFESSORA DOUTORA":["PRFA DRA"],"PROFESSORA MADRE":["PRFA ME"],"PROFESSORA SENHORINHA":["PRFA SNR"],"PROFESSORA SINHA":["PRFA SINHA"],PROFETA:["PRTA"],PROGRAMADOR:["PROG"],PROJETISTA:[],PROMOTOR:["PROM"],"PROMOTOR DE JUSTICA":["PROM JUST"],PROMOTORA:["PROMA"],PROTETICO:[],PROTETOR:["PROTE"],PROTETORA:[],PROVEDOR:["PROV"],"PROVEDOR MARQUES":["PROV MQ"],"PROVEDOR CONSELHEIRO":["PROV CNSO"],PSICANALISTA:["PSICAN"],PSICOLOGA:[],PSICOLOGO:[],PUBLICITARIO:["PUBL"],QUADRINHISTA:["QUADRIN"],QUIMICO:["QUIM"],QUITANDEIRO:["QITAN"],RABINO:["RAB"],RADIALISTA:["RAD"],"RADIALISTA DOUTOR":["RAD DR"],"RADIO AMADOR":["RAD AM"],RADIOTELEGRAFISTA:["RADIOTELEG"],RAINHA:["RNH"],"RAINHA DONA":["RNH DA"],"RAINHA GINGA":["RNH GINGA"],REGENTE:["REG"],REI:[],REITOR:["RTO"],RELIGIOSA:["RELIG"],REMADOR:["REM"],REPENTISTA:["REPENT"],REPORTER:["REP"],"REPORTER CINEMATOGRAFICO":["REP CINEM"],"REVERENDISSIMO PADRE":["REVMO PE"],REVERENDO:["REV"],"REVERENDO DOUTOR":["REV DR"],"REVERENDO PROFESSOR":["REV PRF"],RITMISTA:["RITM"],ROTARIANA:["ROTR"],ROTARIANO:[],SACERDOTE:["SAC"],SAMBISTA:["SAMB"],SANFONEIRO:["SANF"],"SANTA MADRE":["STA ME"],SANTISSIMA:["STMA"],SANTISSIMO:["STMO"],"SANTO BEATO":["STO BTO"],"SANTO PAPA":["STO PAPA"],SANTOS:["STOS"],"SAO FREI":["S FR"],"SAO PAPA":["S PAPA"],SAPATEIRO:["SAPTO"],SARGENTO:["SRG"],"SARGENTO DA AERONAUTICA":["SRG AER"],"SARGENTO POLICIA MILITAR":["SRG PM"],"SARGENTO AVIADOR":["SRG AV"],"SARGENTO BOMBEIRO":["SRG BOMB"],"SARGENTO EXPEDICIONARIO":["SRG EXP"],"SARGENTO MOR":["SRG MOR"],"SARGENTO RODOVIARIO":["SRG ROD"],"SEGUNDO SARGENTO":["S SRG"],"SEGUNDO SARGENTO POLICIA MILITAR":["S SRG PM"],"SEGUNDO TENENTE":["S TEN"],"SEGUNDO TENENTE AVIADOR":["S TEN AV"],SEMINARISTA:["SEMIN"],SENADORA:["SENA"],"SENHOR MESTRE":["SR MTE"],"SENHORA DONA":["SRA DA"],SENHORINHA:["SRHA"],SERESTEIRO:["SEREST"],SERINGUEIRO:["SERING"],SERRALHEIRO:["SERR"],SERTANISTA:["SERT"],SERVENTUARIA:["SERVTUA"],SERVENTUARIO:["SERVT"],SERVIDOR:[],"SERVIDOR MUNICIPAL":["SERV MUN"],"SERVIDOR PUBLICO":[],"SERVIDOR PUBLICO MUNICIPAL":["SERV PUB MUN"],SERVIDORA:[],"SERVIDORA PUBLICA":[],SEU:[],SIA:[],SINALEIRO:["SIN"],SINDICALISTA:["SIND"],SINHA:["SNH"],SINHAZINHA:["SNHZ"],SINHO:["SINH"],SIR:[],SOCIOLOGO:["SOC"],SOCORRISTA:["SOCORR"],SOLDADO:["SD"],"SOLDADO BOMBEIRO":["SD BOMB"],"SOLDADO CONSTITUCIONALISTA":["SD CONST"],"SOLDADO DO EXERCITO":["SD EX"],"SOLDADO EXPEDICIONARIO":["SD EXP"],"SOLDADO POLICIA MILITAR":["SD PM"],SOLICITADOR:["SOLIC"],SOROR:["SRO"],SUBDELEGADO:["SUBDEL"],SUBOFICIAL:["SO"],SUBPREFEITO:["SUBPREF"],SUBTENENTE:["SUBTEN"],"SUBTENENTE AVIADOR":["SUBTEN AV"],"SUBTENENTE POLICIA MILITAR":["SUBTEN PM"],SULTAO:["SUL"],SUPERVISOR:["SUP"],TABELIA:[],TABELIAO:[],"TABELIAO PUBLICO":["TAB PUBL"],TABERNEIRO:["TBRO"],TAIFEIRO:["TAF"],TAXISTA:["TAX"],TEATROLOGO:["TEAT"],TECELA:["TECEL"],TECNICO:["TEC"],"TECNICO AGRICOLA":["TEC AGR"],TELEFONISTA:["TELF"],TELEGRAFISTA:["TELG"],"TENENTE ENFERMEIRA":["TEN ENFA"],"TENENTE JOVEM":["TEN JOV"],"TENENTE MAESTRO":["TEN MTO"],"TENENTE AVIADOR":["TEN AV"],"TENENTE BRIGADEIRO":["TEN BRG"],"TENENTE CORONEL EB":["TEN CEL EB"],"TENENTE CORONEL AVIADOR":["TEN CEL AV"],"TENENTE CORONEL POLICIA MILITAR":["TEN CEL PM"],"TENENTE GENERAL":["TEN GEN"],"TENENTE POLICIA MILITAR":["TEN PM"],TENISTA:["TNIS"],TENOR:["TNR"],"TERCEIRO SARGENTO":["T SRG"],"TERCEIRO SARGENTO AERONAUTICA":["T SRG AER"],"TERCEIRO SARGENTO POLICIA MILITAR":["T SRG PM"],TERRITORIO:["TRT"],TIA:[],TIO:[],TIPOGRAFO:["TIP"],TONELEIRO:["TON"],TOPOGRAFO:["TOP"],TRABALHADOR:["TRAB"],TRADICIONALISTA:["TRAD"],TRATORISTA:["TRAT"],TREINADOR:["TRN"],TROPEIRO:["TROP"],TROVADOR:[],TROVADORA:[],UNIVERSITARIA:["UNIVA"],UNIVERSITARIO:["UNIV"],USINEIRO:["USI"],VAQUEIRO:["VAQ"],VELHA:["VA"],VELHO:[],VENERAVEL:["VEN"],"VEREADOR CACIQUE":["VER CAC"],"VEREADOR DOUTOR":["VER DR"],"VEREADOR ENGENHEIRO":["VER ENG"],"VEREADOR IRMAO":["VER IMO"],"VEREADOR PROFESSOR":["VER PRF"],VEREADORA:["VERA"],VETERANO:["VET"],"VETERANOS CONSTITUCIONALISTAS":["VET CONST"],VETERINARIA:["VETA"],VETERINARIO:["VETO"],"VICE CONSUL":["V CSL"],"VICE GOVERNADOR":["V GOV"],VICENTINO:["VIC"],"VICE PREFEITO":["V PREF"],"VICE PRESIDENTE":["V PRES"],"VICE REI":["V REI"],VIGIA:["VGA"],VIGILANTE:["VGTE"],"VIGILANTE RODOVIARIO":["VGTE ROD"],VIOLEIRO:["VIOL"],VIOLINISTA:["VIOLIN"],VIOLONCELISTA:["VCTA"],VIOLONISTA:["VIOLON"],VIRGEM:["VIR"],VISCONDE:["VSC"],VISCONDESSA:["VSCA"],VIUVA:["VVA"],VO:[],VOLUNTARIA:["VLTA"],VOLUNTARIO:["VLTO"],VOLUNTARIOS:["VLTOS"],VOVO:[],"2 TENENTE PM":["2 TPM"]};function Yn(e,n){let i={...e};for(let[c,u]of Object.entries(n))i[c]=[...new Set([...e[c]??[],...u])];return i}var No=Yn({ACESSO:[],ALAMEDA:["AL","ALAM"],AUTOESTRADA:["AUTO ESTRADA","AUTO ESTR","AUTOESTR"],AVENIDA:["AV","AVA","AVE","AVEN"],"AVENIDA MARGINAL":["AVE MARG","AV MARG","AVA MARG","AVENIDA MARG"],AZINHAGA:["AZ"],BECO:["BC","BCO"],CALCADA:["CC"],CALCADINHA:["CACLCADINHA","CCNH"],CAMINHO:["CAM","CAMNO"],"CONJUNTO HABITACIONAL":["CONJ HAB"],ESTRADA:["ES","EST","ESTR"],"ESTRADA MARGINAL":["ESTR MARG","ESTRADA MARG"],"ESTRADA MUNICIPAL":["EM","E M","ESTR M","ESTRADA M"],"ESTRADA NACIONAL":["EN","E N","ESTR N","ESTRADA N"],"ESTRADA REGIONAL":["ER","E R","ESTR R","ESTRADA R"],ITINERARIO:[],"ITINERARIO COMPLEMENTAR":["IC","I C"],"ITINERARIO PRINCIPAL":["IP","I P"],LARGO:["LG","LGO","L"],LADEIRA:["LD","LAD"],PARADA:["PDA"],PASSAGEM:["PSG"],PRACA:["PC","PCA","PR"],PRACETA:["PCT","PCTA"],RAMPA:[],RETORNO:["RET"],RODOVIA:["ROD","RVIA","RDVIA"],RODOANEL:[],ROTUNDA:["ROT"],RUA:["R"],"RUA PARTICULAR":["R PART","RPART"],RUAS:["RS"],RUELA:[],TRANSVERSAL:["TRANSV"],TRAVESSA:["TV","TRAV","TR","TRV"],TUNEL:[],VIA:["V"],VIADUTO:["VD","VDTO"],VIELA:["VE"],VOLTA:[]},Do),Co={BAIRRO:["B","BO","BR","BRO"],CHACARA:["CH","CHAC"],CONJUNTO:["CJ","CONJ"],LUGAR:["LUG"],PARQUE:["PQ","PRQ","PARQ"],QUINTA:["QU","QTA"],SITIO:["SIT"],URBANIZACAO:["URB"],VILA:["VL","VLA"],ZONA:["ZN"]},Lo={"CAMARA MUNICIPAL":["CM","C M"]},wo={DIREITO:["DTO","DT"],ESQUERDO:["ESQ"],FRENTE:["FT"],PARTICULAR:["PART"],PONTO:["PTO","PNTO"],PROJECTADA:["PROJ"],PROLONGAMENTO:["PROLNG","PRL"]},Kn={ADVOGADO:["ADVO","ADV.O"],ALFERES:["ALF"],ALMIRANTE:["ALM"],ARCEBISPO:["ARCO","ARC.O"],ARQUITETO:["ARQ"],BARAO:["BAR"],BARONESA:[],BISPO:["BPO","B.PO"],BRIGADEIRO:["BRG","BRIG"],CACIQUE:["CAC"],CAPITAO:["CAP","CAPT"],"CAPITAO DE CORVETA":["CAP CORV"],"CAPITAO DE FRAGATA":["CAP FRAG"],"CAPITAO DE MAR E GUERRA":["CAP M G","CAP MG"],"CAPITAO TENENTE":["CAP TEN","CAP TTE"],CARDEAL:["CARD"],COMANDANTE:["CMDT"],COMENDADOR:["COMEND","CMDR","COMOR","COM.OR"],CONDE:["CDE"],CONDESSA:["CDESSA"],CONSELHEIRO:["CONS"],CORONEL:["COR","CEL"],"CONTRA ALMIRANTE":["C ALM"],DEPUTADO:["DEP"],DESEMBARGADOR:["DES"],DESEMBARGADORA:["DESA","DES.A"],DIACONO:["DIAC"],DIACONA:["DIACA"],DOM:[],DONA:["D\xAA","D.\xAA","D.A"],DOUTOR:["DR"],DOUTORA:["DR\xAA","DRA","D.R\xAA","D.RA"],DUQUE:["DQ"],DUQUESA:["DQSA","DQA"],EMBAIXADOR:["EMB"],EMINENCIA:["EMA","EM.A"],EMINENTISSIMO:["EMMO","EM.MO"],ENFERMEIRA:["ENF\xAA","ENFA","ENF.\xAA","ENF.A"],ENFERMEIRO:["ENF\xBA","ENF\xB0","ENFO","ENF","ENF.\xBA","ENF.\xB0","ENF.O"],ENGENHEIRA:["ENG\xAA","ENGA","ENG.\xAA","ENG.A"],ENGENHEIRO:["ENG\xBA","ENG\xB0","ENG.\xBA","ENG.\xB0","ENG","ENGO","ENG.O"],EXCELENCIA:["EX\xAA","EXA","EX.\xAA","EX.A"],EXCELENTISSIMA:["EXM\xAA","EXMA","EX.M\xAA","EX.MA"],EXCELENTISSIMO:["EXM\xBA","EXM\xB0","EXMO","EX.M\xBA","EX.M\xB0","EX.MO"],FREI:["FR"],GENERAL:["GEN","GAL","G.AL"],GOVERNADOR:["GOV","GOVDOR","GOVD.OR","GOV.DOR"],ILUSTRISSIMA:["ILM\xAA","ILMA","IL.M\xAA","IL.MA"],ILUSTRISSIMO:["ILM\xBA","ILM\xB0","ILMO","IL.M\xBA","IL.M\xB0","IL.MO"],INFANTE:["INF"],IRMA:["IM\xAA","IMA"],IRMAO:["IM\xBA","IM\xB0","IMO"],JUIZ:["JZ"],MAESTRA:["MTA","MTRA","MSTRA"],MAESTRO:["MTO","MTRO","MSTRO"],MAJOR:["MAJ"],"MAJOR BRIGADEIRO":["MAJ BRIG"],MARECHAL:["MAR","MAL","M.AL"],MARQUES:["MQ","MARQ"],MARQUESA:["MQSA","MARQA"],MADRE:[],MEDICO:["MED"],MESTRA:["M\xAA","MA","M.\xAA","M.A"],MESTRE:[],MINISTERIO:[],MINISTRO:["MIN"],MONSENHOR:["MONS"],"NOSSA SENHORA":["NSRA","NSA","N\xAA S\xAA","N\xAAS\xAA","N SR\xAA","N\xAA SR\xAA","N SA","N SRA","N.S.A.","N.S.A"],"NOSSO SENHOR":["NS","N.S.","N.S","N S"],PADRE:["PDE","PE","P.E"],PASTOR:["PR"],PREFEITO:["PREF"],PRESIDENTE:["PRESID","PRES"],PROFESSOR:["PROF","PROF\xBA","PROF\xB0"],PROFESSORA:["PROFA","PROF.A","PROF\xAA","PROF.\xAA"],PROFESSORAS:["PROFAS"],PROFESSORES:["PROFS"],REVERENDA:["REVDA","REV.DA"],REVERENDO:["REVDO","REV.DO"],REVERENDISSIMA:["REVMA","REV.MA"],REVERENDISSIMO:["REVMO","REV.MO"],SANTA:["ST\xAA","STA","ST.\xAA","ST.A"],SANTO:["ST\xBA","ST\xB0","STO","ST","ST.\xBA","ST.\xB0","ST.O"],SAO:[],SARGENTO:["SGT","SARG","SGTO","SARGTO"],"SARGENTO AJUDANTE":["SARG AJTE","SARG AJ.TE"],SECRETARIA:["SEC.A","SECR.A","SECRA"],SECRETARIO:["SEC","SECR"],SENADOR:["SEN"],SENHOR:["SR","S.R"],SENHORES:["SRS","S.RS"],SENHORA:["S\xAA","SA","SR\xAA","SRA","SR.\xAA","SR.A","S.RA","S.R\xAA"],SENHORAS:["SRAS","S.RAS"],SENHORITA:["SRTA","SR.TA"],SENHORITAS:["SRTAS","SR.TAS"],TENENTE:["TEN","TTE","T.TE"],"TENENTE CORONEL":["TEN C.EL","TEN CEL","TTE CEL","T.TE C.EL"],TESOUREIRO:["TES"],VEREADOR:["VER"],"VICE ALMIRANTE":["V ALM"],VIGARIO:["VIG","VIGO","VIG.O"],VISCONDE:["VISC","VDE","V.DE"],VISCONDESA:["VDESSA","V.DESSA"]};function Mo(e){let n=e.replaceAll(".","").replaceAll("\xAA","A").replace(/[\u00BA\u00B0]/g,"O");return n==="DA"?"DONA":n}var er=Object.fromEntries(Object.values(Kn).flatMap((e)=>e.flatMap((n)=>n.split(" "))).filter((e)=>/[.\u00AA\u00BA\u00B0]/.test(e)).map((e)=>[e.replace(/\.$/,""),Mo(e)])),tr=Yn(Object.fromEntries(Object.entries(Kn).map(([e,n])=>[e,[...new Set(n.map((i)=>i.split(" ").map((c)=>er[c.replace(/\.$/,"")]??c).join(" ")))]])),yo),Uo={JARDIM:["JD","JDM"],JARDINS:["JDS"],VILA:["VL","VLA"],HABITACIONAL:["HAB"],RESIDENCIAL:["RES"],CIDADE:["CID"],LOTEAMENTO:["LOT"],NUCLEO:["NUC"]};function ln(e){let n=new Map;for(let[i,c]of Object.entries(e))for(let u of c)if(!n.has(u))n.set(u,i);return n}var dn={...No,...Co,...Lo},Po=ln(dn),Jn=ln(wo),nr=ln(tr);nr.delete("ED");var Bo=new Set(Object.entries({...dn,...Uo}).flatMap(([e,n])=>[e,...n])),_o=Object.entries(dn).flatMap(([e,n])=>n.filter((i)=>i.includes(" ")).map((i)=>({alias:i,name:e}))).sort((e,n)=>n.alias.length-e.alias.length),xo=Object.entries(tr).flatMap(([e,n])=>[e,...n]).filter((e)=>e.includes(" ")).sort((e,n)=>n.length-e.length),Vo=new RegExp(`\\b(?:${xo.join("|")}|[A-Z0-9]+)\\b`,"g");function Fo(e){let n=e.normalize("NFD").replace(/\p{M}/gu,"").replace(/[a-z\u0080-\u{10FFFF}]/gu,(i)=>{let c=i.toUpperCase();return c.length===i.length?c:i});if(/[.\u00AA\u00BA\u00B0]/.test(e))n=(n.match(/[A-Z0-9\u00AA\u00BA\u00B0]+(?:\.[A-Z0-9\u00AA\u00BA\u00B0]+)*/g)??[]).map((i)=>er[i]??i).join(" ");return n.replace(/[^A-Z0-9]+/g," ").trim()}function vo(e){for(let{alias:n,name:i}of _o)if(e.startsWith(`${n} `))return i+e.slice(n.length);return e}function rr(e){let n=vo(Fo(e)).match(Vo)??[];return n.map((i,c)=>{if(c===n.length-1)return Jn.get(i)??i;let u=c===0?Po.get(i):void 0;if(u!==void 0)return u;let l=Jn.get(i)??nr.get(i);if(l!==void 0)return l;if(i==="D"&&(c===0||c===1&&Bo.has(n[0]??"")))return"DOM";return i}).join(" ")}function Vt(e){return rr(e).toLowerCase().match(/[a-z0-9]+/g)??[]}var Oe=5,q=256,X=32,re=16,K=Uint8Array.from([68,78,69,66,73,78,0,0]),ir=4294967295,fn=1e5,Me=100001,pe=10,Ze=32,Ft=0,Ie=2,me=255,Ue=2295,H=3,J=8,Pe=8,ee=256,ze=32,Y=["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 ft(e){return Math.ceil(e/8)*8}function Qe(e){return Math.ceil(e/8)}function Xe(e,n){return Math.ceil(e*n/8)}function Je(){let e=new Uint8Array(256);for(let n=1;n<e.length;n++)e[n]=(e[n>>>1]??0)+(n&1);return e}function v(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;return 4}function ie(e,n){if(e!==1&&e!==2&&e!==3&&e!==4)throw Error(`Unsupported binary ${n} width: ${e}`);return e}function At(e){return e===4?4294967295:2**(e*8)-1}function An(e,n,i){if(!Number.isSafeInteger(e)||e<0||e>At(n))throw Error(`Binary ${i} exceeds the ${n}-byte unsigned integer limit: ${e}`)}function _(e,n,i){switch(i){case 1:return e.getUint8(n);case 2:return e.getUint16(n,!0);case 3:return e.getUint8(n)|e.getUint8(n+1)<<8|e.getUint8(n+2)<<16;case 4:return e.getUint32(n,!0)}}function F(e,n,i,c){if(An(i,c,"column value"),e[n]=i&255,c>1)e[n+1]=i>>>8&255;if(c>2)e[n+2]=i>>>16&255;if(c>3)e[n+3]=i>>>24&255}function or(e){if(e.byteLength!==K.length)return!1;return K.every((n,i)=>e[i]===n)}function ar(e,n,i){if(i<0||i>=1024)throw Error(`CEP suffix exceeds 10 bits: ${i}`);let c=n*10,u=c>>>3,l=c&7,d=i<<l;if(e[u]=(e[u]??0)|d&255,u+1<e.byteLength)e[u+1]=(e[u+1]??0)|d>>>8&255;if(u+2<e.byteLength)e[u+2]=(e[u+2]??0)|d>>>16&255}var de={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},vt=Object.keys(de),Go={RO:"Rond\xF4nia",AC:"Acre",AM:"Amazonas",RR:"Roraima",PA:"Par\xE1",AP:"Amap\xE1",TO:"Tocantins",MA:"Maranh\xE3o",PI:"Piau\xED",CE:"Cear\xE1",RN:"Rio Grande do Norte",PB:"Para\xEDba",PE:"Pernambuco",AL:"Alagoas",SE:"Sergipe",BA:"Bahia",MG:"Minas Gerais",ES:"Esp\xEDrito Santo",RJ:"Rio de Janeiro",SP:"S\xE3o Paulo",PR:"Paran\xE1",SC:"Santa Catarina",RS:"Rio Grande do Sul",MS:"Mato Grosso do Sul",MT:"Mato Grosso",GO:"Goi\xE1s",DF:"Distrito Federal"},Yu=new Map(vt.map((e)=>[$o(Go[e]),e])),Ku=new Map(vt.map((e)=>[de[e],e]));function sr(e){let n=e.trim().toUpperCase();if(!Object.hasOwn(de,n))return;return n}function $o(e){return e.trim().normalize("NFD").replace(/\p{M}/gu,"").toUpperCase()}var cr="DNESRCH1",ur=2,Et=80,Be=32;function lr(e){let n=e.checksum(),i=e.rowCount(),c=new Uint32Array(i),u=new Uint32Array(i),l=new Uint32Array(i*4),d=[],A=new Map,E=[],R=new Map,O=[],p=[[]],I=new Map([["",0]]),m=new Map,S=(N)=>{let P=m.get(N);if(!P)P=Vt(N),m.set(N,P);return P},h=0;for(let N of e.entries()){c[h]=Number(N.cep);let P=A.get(N.municipio_cod_ibge);if(P===void 0)P=d.length,A.set(N.municipio_cod_ibge,P),d.push({code:N.municipio_cod_ibge,uf:N.uf});u[h]=P;let le=new Set,xt=[Vt(N.logradouro??""),Vt(N.nome??""),S(N.bairro??""),S(N.municipio)];for(let[dt,B]of xt.entries()){let Q=B.join(" "),Ee=I.get(Q);if(Ee===void 0)Ee=p.length,I.set(Q,Ee),p.push(B.map((we)=>{let Re=R.get(we);if(Re===void 0)Re=E.length,R.set(we,Re),E.push(we),O.push([]);return Re}));l[h*4+dt]=Ee;for(let we of p[Ee])le.add(we)}for(let dt of le)O[dt].push(h);h++}let b=[...E.keys()].sort((N,P)=>E[N]<E[P]?-1:1),g=new Uint32Array(E.length);for(let[N,P]of b.entries())g[P]=N;let D=new TextEncoder().encode(JSON.stringify(b.map((N)=>E[N]))),y=[0],U=b.map((N)=>{let P=qo(O[N]);return y.push(y[y.length-1]+P.length),P}),L=y[y.length-1],V=v(p.length-1),W=v(E.length-1),C=v(d.length-1),x=p.reduce((N,P)=>N+P.length,0),j=Et+i*4,qe=j+i*C,ye=qe+i*4*V,Ne=ye+d.length*6,ue=Ne+(p.length+1)*4,lt=ue+x*W,k=lt+y.length*4,G=new Uint8Array(k+D.length+L+Be),ne=new DataView(G.buffer);G.set(new TextEncoder().encode(cr));for(let[N,P]of[[8,ur],[12,i],[16,D.length],[20,E.length],[24,L],[28,p.length],[64,x],[68,d.length]])ne.setUint32(N,P,!0);G.set(Buffer.from(n,"hex"),32),G.set([V,W,C],72);for(let N=0;N<i;N++){ne.setUint32(Et+N*4,c[N],!0),F(G,j+N*C,u[N],C);for(let P=0;P<4;P++)F(G,qe+(N*4+P)*V,l[N*4+P],V)}for(let[N,{code:P,uf:le}]of d.entries())ne.setUint32(ye+N*6,P,!0),G.set([le.charCodeAt(0),le.charCodeAt(1)],ye+N*6+4);let Ce=0;for(let[N,P]of p.entries()){ne.setUint32(Ne+N*4,Ce,!0);for(let le of P)F(G,ue+Ce++*W,g[le],W)}ne.setUint32(Ne+p.length*4,Ce,!0);for(let[N,P]of y.entries())ne.setUint32(lt+N*4,P,!0);G.set(D,k);let Le=k+D.length;for(let N of U)G.set(N,Le),Le+=N.length;return G.set(dr(G.subarray(0,-Be)),Le),Ho(G,n,i),G}function Ho(e,n,i){if(e.length<Et+Be||new TextDecoder().decode(e.subarray(0,8))!==cr)throw Error("Invalid address search index header");let c=new DataView(e.buffer,e.byteOffset,e.byteLength);if(c.getUint32(8,!0)!==ur)throw Error("Unsupported address search index version; rebuild the search index");if(!dr(e.subarray(0,-Be)).equals(e.subarray(-Be)))throw Error("Invalid address search index checksum");if(Buffer.from(e.subarray(32,64)).toString("hex")!==n||c.getUint32(12,!0)!==i)throw Error("Address search index belongs to a different database");let u=c.getUint32(16,!0),l=c.getUint32(20,!0),d=c.getUint32(24,!0),A=c.getUint32(28,!0),E=c.getUint32(64,!0),R=c.getUint32(68,!0),O=ie(c.getUint8(72),"search field"),p=ie(c.getUint8(73),"search token"),I=ie(c.getUint8(74),"search municipality"),m=Et+i*4,S=m+i*I,h=S+i*4*O,b=h+R*6,g=b+(A+1)*4,D=g+E*p,y=D+(l+1)*4,U=y+u;if(!A||!R||c.getUint8(75)!==0||c.getUint32(76,!0)!==0||U+d+Be!==e.length)throw Error("Invalid address search index size");let L=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.subarray(y,U)));if(!Array.isArray(L)||L.length!==l||L.some((C,x)=>typeof C!=="string"||!/^[a-z0-9]+$/.test(C)||x>0&&L[x-1]>=C))throw Error("Invalid address search vocabulary");let V={data:c,terms:L,offsets:D,postings:e.subarray(U,-Be),rowCount:i,rowMunicipalities:m,rowFields:S,fieldOffsets:b,fieldCount:A,fieldTokens:g,fieldWidth:O,tokenWidth:p,municipalityWidth:I,municipalityCodes:[],municipalityUfs:[],municipalityByCode:new Map};for(let C=0;C<R;C++){let x=c.getUint32(h+C*6,!0),j=String.fromCharCode(c.getUint8(h+C*6+4),c.getUint8(h+C*6+5));if(x<1e6||x>9999999||!vt.includes(j)||V.municipalityByCode.has(x))throw Error("Invalid address search municipality");V.municipalityCodes.push(x),V.municipalityUfs.push(j),V.municipalityByCode.set(x,C)}let W=-1;for(let C=0;C<i;C++){let x=c.getUint32(Et+C*4,!0);if(x<=W||x>99999999)throw Error("Invalid address search CEP");if(W=x,jo(V,C)>=R)throw Error("Invalid address search municipality reference");for(let j=0;j<4;j++)if(_(c,S+(C*4+j)*O,O)>=A)throw Error("Invalid address search field reference")}if(c.getUint32(b,!0)!==0||c.getUint32(b+A*4,!0)!==E)throw Error("Invalid address search field offsets");for(let C=0;C<A;C++){let x=c.getUint32(b+C*4,!0),j=c.getUint32(b+(C+1)*4,!0);if(j<x||j>E)throw Error("Invalid address search field range")}for(let C=0;C<E;C++)if(_(c,g+C*p,p)>=l)throw Error("Invalid address search field token");if(c.getUint32(D,!0)!==0||c.getUint32(D+l*4,!0)!==d)throw Error("Invalid address search posting offsets");for(let C=0;C<l;C++)Wo(V,C);return V}function Wo(e,n,i){let c=e.data.getUint32(e.offsets+n*4,!0),u=e.data.getUint32(e.offsets+(n+1)*4,!0);if(u<=c||u>e.postings.length)throw Error("Invalid address search posting range");let l=-1;while(c<u){let d=0,A=1,E;do{if(c>=u||A>268435456)throw Error("Invalid address search posting encoding");E=e.postings[c++],d+=(E&127)*A,A*=128}while(E&128);let R=l+d;if(d===0||R>=e.rowCount)throw Error("Invalid address search posting row");i?.(R),l=R}}function jo(e,n){return _(e.data,e.rowMunicipalities+n*e.municipalityWidth,e.municipalityWidth)}function qo(e){let n=[],i=-1;for(let c of e){let u=c-i;while(u>=128)n.push(u%128|128),u=Math.floor(u/128);n.push(u),i=c}return new Uint8Array(n)}function dr(e){return ko("sha256").update(e).digest()}import{readFileSync as Ma}from"fs";class Se extends Error{constructor(e,n){super(e,n);this.name=new.target.name}}class Rt extends Se{path;code="IO_ERROR";constructor(e,n){super(`Unable to read binary database: ${e}`,n);this.path=e}}class T extends Se{code="INVALID_FORMAT";constructor(e,n){super(e,n)}}class Gt extends Se{actualVersion;supportedVersion;code="UNSUPPORTED_VERSION";constructor(e,n){super(`Unsupported binary database version: ${e}. Rebuild the database with build --force.`);this.actualVersion=e;this.supportedVersion=n}}class $t extends Se{code="READER_CLOSED";constructor(){super("Binary database is closed")}}var Ot=8,Ye=3,Ke=1<<Ye,Zo=Je();function Ar(e,n,i){let c=new DataView(e.buffer,e.byteOffset,e.byteLength),u=[],l=[],d=-1;for(let L=0;L<n;L++){let V=_(c,L*i,i);if(V!==d)u.push(L),l.push(V),d=V}let A=u.length,E=Math.floor(Math.log2(n/A)),R=2**E,O=Math.ceil(n/R),p=O+A,I=Math.ceil(A*E/8),m=Math.ceil(p/8),S=Math.ceil(O/Ke),h=Ot+I,b=h+m,g=b+S*4,D=new Uint8Array(g+A*i),y=new DataView(D.buffer);y.setUint32(0,A,!0),y.setUint8(4,E),y.setUint8(5,Ye),y.setUint8(6,i);for(let L=0;L<A;L++){let V=u[L]??0;zo(D,Ot,L*E,E,V%R);let W=Math.floor(V/R)+L,C=h+(W>>>3);D[C]=(D[C]??0)|1<<(W&7),F(D,g+L*i,l[L]??0,i)}let U=0;for(let L=0;L<p;L++)if(((D[h+(L>>>3)]??0)&1<<(L&7))===0){if(U%Ke===0)y.setUint32(b+(U>>>Ye)*4,L,!0);U++}return D}function Er(e,n,i,c){let u=e.getUint32(n.offset,!0),l=e.getUint8(n.offset+4),d=Math.ceil(i/2**l),A=d+u,E=n.offset+Ot,R=E+Math.ceil(u*l/8),O=R+Math.ceil(A/8),p=O+Math.ceil(d/Ke)*4;return{highBitCount:A,highOffset:R,idWidth:c,idsOffset:p,lowBits:l,lowOffset:E,runCount:u,samplesOffset:O,zeroCount:d}}function Rr(e,n,i,c,u){if(n.length<Ot)throw new T("Binary neighborhood runs are truncated");let l=e.getUint32(n.offset,!0),d=e.getUint8(n.offset+4);if(l<1||l>i||d>31||e.getUint8(n.offset+5)!==Ye||e.getUint8(n.offset+6)!==c||e.getUint8(n.offset+7)!==0)throw new T("Invalid binary neighborhood run header");let A=2**d,E=Math.ceil(i/A),R=E+l,O=Math.ceil(l*d/8),p=Math.ceil(R/8),I=Math.ceil(E/Ke),m=n.offset+Ot,S=m+O,h=S+p,b=h+I*4;if(b+l*c!==n.offset+n.length)throw new T("Invalid binary neighborhood run length");let g=0,D=0,y=-1,U=-1;for(let L=0;L<R;L++){if((e.getUint8(S+(L>>>3))&1<<(L&7))===0){if(g>=E)throw new T("Invalid binary neighborhood run bitmap");if(g%Ke===0&&e.getUint32(h+(g>>>Ye)*4,!0)!==L)throw new T("Invalid binary neighborhood run samples");g++;continue}if(D>=l)throw new T("Invalid binary neighborhood run bitmap");let W=pr(e,m,D*d,d),C=g*A+W,x=_(e,b+D*c,c);if(D===0&&C!==0||C<=y||C>=i||x>u||x===U)throw new T("Invalid binary neighborhood run");y=C,U=x,D++}if(R%8!==0){let L=255<<(R&7);if((e.getUint8(S+(R>>>3))&L)!==0)throw new T("Invalid binary neighborhood run padding")}return{highBitCount:R,highOffset:S,idWidth:c,idsOffset:b,lowBits:d,lowOffset:m,runCount:l,samplesOffset:h,zeroCount:E}}function Or(e,n,i){let c=2**n.lowBits,u=Math.floor(i/c),l=fr(e,n,u)-u,d=u===0?0:fr(e,n,u-1)-(u-1),A=i%c,E=d,R=l;while(E<R){let p=E+(R-E>>>1);if(pr(e,n.lowOffset,p*n.lowBits,n.lowBits)<=A)E=p+1;else R=p}let O=E-1;return _(e,n.idsOffset+O*n.idWidth,n.idWidth)}function fr(e,n,i){let c=i>>>Ye,u=e.getUint32(n.samplesOffset+c*4,!0),l=i-c*Ke;if(l===0)return u;u++;while(l>0){let d=u&7,A=8-d,E=(1<<A)-1,R=~(e.getUint8(n.highOffset+(u>>>3))>>>d)&E,O=Zo[R]??0;if(O>=l)for(let p=0;l>0;p++){if(R&1<<p)l--;u++}else l-=O,u+=A}return u-1}function pr(e,n,i,c){let u=0;for(let l=0;l<c;l++){let d=i+l;if(e.getUint8(n+(d>>>3))&1<<(d&7))u+=2**l}return u}function zo(e,n,i,c,u){for(let l=0;l<c;l++)if(Math.floor(u/2**l)%2){let d=i+l,A=n+(d>>>3);e[A]=(e[A]??0)|1<<(d&7)}}function oe(e){return Number.isInteger(e)&&e>0&&e<=4294967295}var et=8,En=8,tt=1<<En;function Ir(e,n,i){let c=new DataView(e.buffer,e.byteOffset,e.byteLength),u=[],l=[],d=[],A=-1,E=-1;for(let b=0;b<n.length;b++){let g=_(c,b*i,i),D=n[b]??0;if(g!==A||D!==E)u.push(b),l.push(g),d.push(D),A=g,E=D}let R=u.length,O=Math.ceil(n.length/tt),p=et+(O+1)*4,I=p+R*4,m=new Uint8Array(I+R*i),S=new DataView(m.buffer);S.setUint32(0,R,!0),S.setUint8(4,En);let h=0;for(let b=0;b<O;b++){while(h+1<R&&(u[h+1]??0)<=b*tt)h++;S.setUint32(et+b*4,h,!0)}S.setUint32(et+O*4,R,!0);for(let b=0;b<R;b++)S.setUint32(p+b*4,u[b]??0,!0),F(m,I+b*i,l[b]??0,i);return{ids:m,flags:Uint8Array.from(d)}}function mr(e,n,i){let c=e.getUint32(n.offset,!0),u=n.offset+et,l=u+(Math.ceil(i/tt)+1)*4;return{count:c,directoryOffset:u,startsOffset:l,idsOffset:l+c*4}}function Sr(e,n,i,c){if(n.length<et)throw new T("Binary locality runs are truncated");let u=e.getUint32(n.offset,!0);if(u===0||u>i||e.getUint32(n.offset+4,!0)!==En)throw new T("Invalid binary locality run header");let l=Math.ceil(i/tt),d=n.offset+et,A=d+(l+1)*4,E=A+u*4;if(E+u*c!==n.offset+n.length)throw new T("Invalid binary locality run length");let R=-1;for(let p=0;p<u;p++){let I=e.getUint32(A+p*4,!0);if(p===0&&I!==0||I<=R||I>=i)throw new T("Invalid binary locality run boundary");R=I}let O=0;for(let p=0;p<l;p++){while(O+1<u&&e.getUint32(A+(O+1)*4,!0)<=p*tt)O++;if(e.getUint32(d+p*4,!0)!==O)throw new T("Invalid binary locality run directory")}if(e.getUint32(d+l*4,!0)!==u)throw new T("Invalid binary locality run sentinel");return{count:u,directoryOffset:d,startsOffset:A,idsOffset:E}}function hr(e,n,i){let c=Math.floor(i/tt),u=e.getUint32(n.directoryOffset+c*4,!0),l=Math.min(n.count,e.getUint32(n.directoryOffset+(c+1)*4,!0)+1);while(u+1<l){let d=u+(l-u>>>1);if(e.getUint32(n.startsOffset+d*4,!0)<=i)u=d;else l=d}return u}function nt(e){return Math.max(1,Math.ceil(Math.log2(e+1)))}function kt(e,n,i,c){let u=i*c,l=n+Math.floor(u/8),d=u&7,A=d+c,E=e.getUint8(l);if(A>8)E|=e.getUint8(l+1)<<8;if(A>16)E|=e.getUint8(l+2)<<16;if(A>24)E|=e.getUint8(l+3)<<24;let R=E>>>d&4294967295>>>32-c;if(A>32)R+=(e.getUint8(l+4)&(1<<A-32)-1)*2**(32-d);return R>>>0}function Tr(e,n,i,c){if(!Number.isInteger(c)||c<0||c>=2**i||i<1||i>32)throw Error(`Invalid ${i}-bit column value: ${c}`);let u=n*i,l=Math.floor(u/8),d=u&7,A=c*2**d,E=Math.ceil((d+i)/8);for(let R=0;R<E;R++)e[l+R]=(e[l+R]??0)|Math.floor(A/2**(R*8))&255}var pt="4",rt=["M","D","P"],it=["municipio","distrito","povoado"],ot=["sem_codificacao_por_logradouro","codificada_por_logradouro","inserida_na_codificacao_por_logradouro","em_codificacao_por_logradouro"],Qo=[{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 br(e={}){return Qo.map((n)=>({...n,name:e[n.originalName]??n.name,columns:n.columns.map((i)=>({...i,...i.references?{references:{...i.references,table:e[i.references.table]??i.references.table}}:{}})),sourceFields:n.sourceFields?{...n.sourceFields}:void 0}))}function _e(e){let n=e.find((i)=>i.unifiedTable);if(!n)throw Error("Unified schema table not found");return n}function It(e){return e.filter((n)=>n.columns.length>0)}function mt(e){if(e.unifiedTable||e.fileGlob===null)return null;return e.fileGlob??`${e.originalName.toUpperCase()}.TXT`}function xe(e,n){if(!e.sourceFields)throw Error(`Source fields for table '${e.originalName}' not found`);return n.map((i)=>{let c=e.sourceFields?.[i];if(c===void 0)throw Error(`Source field '${i}' for table '${e.originalName}' not found`);return c})}var gr=new TextDecoder("utf-8",{fatal:!0});function Dr(e){try{if(!(e instanceof Uint8Array))throw new T("Binary database bytes must be a Uint8Array");let n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=Xo(n);Jo(e,i);let c=Yo(e,n,i);Ko(c.uf);let u=ra(e,n,i,c),l=ia(n,i,c),d=oa(e,n,i,c),A=Rr(n,i.sections.bairroIds,i.rowCount,u.idWidth,u.count),E=Sr(n,i.sections.municipalityIds,i.rowCount,i.municipalityIdWidth);sa(n,i,A,E),la(n,i,u),da(e,n,i),fa(e,n,i,c.logradouro),Aa(n,i,c,u,A,E,d,l),pa(e,i.sections.metadata)}catch(n){if(n instanceof T)throw n;let i=n instanceof Error?n.message:String(n);throw new T(`Unable to validate binary database: ${i}`,{cause:n})}}function Xo(e){if(e.byteLength<q+X)throw new T("Binary database header is truncated");for(let i=0;i<K.length;i++)if(e.getUint8(i)!==K[i])throw new T("Invalid binary database magic");if(e.getUint16(8,!0)!==Oe)throw new T("Unsupported binary database version");if(e.getUint16(10,!0)!==q)throw new T("Unsupported binary database header size");if(e.getUint8(22)!==Pe||e.getUint8(23)!==H)throw new T("Unsupported binary database block layout");if(e.getUint16(24,!0)!==Y.length)throw new T("Unsupported binary database section table");let n={};for(let[i,c]of Y.entries()){let u=ze+i*8;n[c]={length:e.getUint32(u+4,!0),offset:e.getUint32(u,!0)}}return{cepPrefixOffsetWidth:ie(e.getUint8(20),"CEP prefix offset"),fileSize:e.getUint32(16,!0),municipalityCount:e.getUint32(28,!0),municipalityIdWidth:ie(e.getUint8(21),"municipality id"),rowCount:e.getUint32(12,!0),sections:n}}function Jo(e,n){let i=e.byteLength-X;if(n.fileSize!==e.byteLength)throw new T(`Binary database size mismatch: header=${n.fileSize}, actual=${e.byteLength}`);if(i<q||i%8!==0)throw new T("Binary database payload has an invalid alignment");if(!n.rowCount||!n.municipalityCount)throw new T("Binary database must contain rows and municipalities");if(n.rowCount>At(n.cepPrefixOffsetWidth))throw new T("Binary row count does not fit the CEP prefix offset width");if(n.municipalityCount>At(n.municipalityIdWidth))throw new T("Binary municipality count does not fit its id width");if(n.cepPrefixOffsetWidth!==v(n.rowCount)||n.municipalityIdWidth!==v(n.municipalityCount))throw new T("Binary database uses a noncanonical integer width");at(e,26,28,"binary header reserved bytes"),at(e,248,q,"binary header reserved bytes");let c=q;for(let l of Y){let d=n.sections[l];if(Ia(i,d,l),d.offset%8!==0||d.offset<c)throw new T(`Binary section is out of order or unaligned: ${l}`);at(e,c,d.offset,`${l} section padding`),c=d.offset+d.length}if(at(e,c,i,"final binary section padding"),ft(c)!==i)throw new T("Binary database footer is not after aligned section data");fe(n.sections.cepPrefixOffsets,Me*n.cepPrefixOffsetWidth,"CEP prefix directory"),fe(n.sections.cepSuffixes,Xe(n.rowCount,pe),"CEP suffix column");for(let l of["complementoBitmap","nomeBitmap","localidadeNomeBitmap"])fe(n.sections[l],Qe(n.rowCount),"nullable bitmap");let u=(Math.ceil(n.rowCount/ee)+1)*4;for(let l of["complementoRanks","nomeRanks","localidadeNomeRanks"])fe(n.sections[l],u,"sparse rank index")}function Yo(e,n,i){return{bairro:Ve(e,n,i.sections.bairroDictionary,"bairro",!1),bairroAbreviado:Ve(e,n,i.sections.bairroAbreviadoDictionary,"bairro abbreviation",!1),complemento:Ve(e,n,i.sections.complementoDictionary,"complemento",!1),logradouro:Ve(e,n,i.sections.logradouroDictionary,"logradouro",!0),municipio:Ve(e,n,i.sections.municipioDictionary,"municipio",!1),nome:Ve(e,n,i.sections.nomeDictionary,"nome",!1),uf:Ve(e,n,i.sections.ufDictionary,"uf",!1)}}function Ko(e){for(let[n,i]of e.values.entries())Rn(i,n)}function Rn(e,n){let i=sr(e);if(i===void 0)throw new T(`Invalid binary UF dictionary entry: ${n}`);if(e!==i)throw new T(`Binary UF dictionary entry is not canonical: ${n}`);return i}function Ve(e,n,i,c,u){if(i.length<Ze)throw new T(`Binary ${c} dictionary is truncated`);let l=n.getUint32(i.offset,!0),d=n.getUint32(i.offset+4,!0),A=n.getUint32(i.offset+8,!0),E=n.getUint32(i.offset+12,!0),R=n.getUint32(i.offset+16,!0),O=n.getUint32(i.offset+20,!0),p=n.getUint32(i.offset+24,!0),I=ie(n.getUint8(i.offset+28),`${c} dictionary id`),m=n.getUint8(i.offset+30),S=n.getUint8(i.offset+31);if(m!==Ft&&(m!==Ie||!u)||(m===Ft?S!==0:S!==1&&S!==2))throw new T(`Unsupported binary ${c} dictionary codec or length width`);if(n.getUint8(i.offset+29)!==H)throw new T(`Unsupported binary ${c} dictionary block size`);let h=Math.ceil(l/J);if(d!==h||l>At(I))throw new T(`Binary ${c} dictionary has an invalid count or id width`);let b=S===2?2:1,g=m===Ie?Ue:0;if(A!==Ze||E!==A+d*4||R!==E+l*b||O!==R+l+g||O>i.length||p!==i.length-O||I!==v(l))throw new T(`Binary ${c} dictionary has an invalid layout`);let D={blockCount:d,blockOffsetsOffset:i.offset+A,codec:m,count:l,idWidth:I,lengthWidth:b,lengthsOffset:i.offset+E,prefixesOffset:i.offset+R,region:i,suffixDataLength:p,suffixDataOffset:i.offset+O,symbolsOffset:i.offset+R+l,values:[]};return ea(e,n,D,c),D.values=ta(e,n,D,c),D}function ea(e,n,i,c){if(i.blockCount&&n.getUint32(i.blockOffsetsOffset,!0)!==0)throw new T(`Binary ${c} dictionary has an invalid first block offset`);let u=0;for(let l=0;l<i.blockCount;l++){let d=n.getUint32(i.blockOffsetsOffset+l*4,!0);if(d<u||d>i.suffixDataLength)throw new T(`Binary ${c} dictionary has invalid block offsets`);u=d}if(i.codec===Ie)for(let l=0;l<me;l++){let d=e[i.symbolsOffset+l]??0;if(d>8)throw new T(`Invalid binary ${c} FSST symbol length`);let A=i.symbolsOffset+me+l*8;at(e,A+d,A+8,`binary ${c} FSST symbol padding`)}if(i.blockCount===0&&i.suffixDataLength!==0)throw new T(`Binary ${c} dictionary has unexpected payload`)}function ta(e,n,i,c){let u=[],l=c==="bairro"||c==="municipio"||c==="uf",d;for(let A=0;A<i.blockCount;A++){let E=A*J,R=Math.min(i.count,E+J),O=n.getUint32(i.blockOffsetsOffset+A*4,!0),p=A+1<i.blockCount?n.getUint32(i.blockOffsetsOffset+(A+1)*4,!0):i.suffixDataLength,I=i.suffixDataOffset+O,m=i.suffixDataOffset+p,S=new Uint8Array;for(let h=E;h<R;h++){let b=e[i.prefixesOffset+h]??0;if(h===E&&b!==0||b>S.byteLength)throw new T(`Invalid binary ${c} dictionary prefix: ${h}`);let g;if(i.codec===Ft){let y=e[i.lengthsOffset+h]??0;if(b>y)throw new T(`Invalid binary ${c} dictionary length: ${h}`);let U=y-b;if(I<i.suffixDataOffset||I+U>m)throw new T(`Invalid binary ${c} dictionary suffix: ${h}`);g=new Uint8Array(y),g.set(S.subarray(0,b)),g.set(e.subarray(I,I+U),b),I+=U}else{let y=i.lengthWidth===1?e[i.lengthsOffset+h]??0:n.getUint16(i.lengthsOffset+h*2,!0);if(I<i.suffixDataOffset||I+y>m)throw new T(`Invalid binary ${c} FSST suffix: ${h}`);if(y>510)throw new T(`Binary ${c} FSST suffix is too long: ${h}`);g=na(e,i,I,y,S,b,c,h),I+=y}let D;try{D=gr.decode(g)}catch(y){throw new T(`Invalid UTF-8 in binary ${c} dictionary entry: ${h}`,{cause:y})}if(d!==void 0&&d>=D)throw new T(`Binary ${c} dictionary is not strictly sorted: ${h}`);if(l)u.push(D);d=D,S=g}if(I!==m)throw new T(`Binary ${c} dictionary block length mismatch`)}return u}function na(e,n,i,c,u,l,d,A){let E=new Uint8Array(255);E.set(u.subarray(0,l));let R=l,O=i,p=i+c;while(O<p){let I=e[O++]??0;if(I===255){if(O>=p||R>=255)throw new T(`Invalid binary ${d} FSST escape: ${A}`);E[R++]=e[O++]??0;continue}let m=e[n.symbolsOffset+I]??0;if(!m||m>8||R+m>255)throw new T(`Invalid binary ${d} FSST symbol: ${A}`);let S=n.symbolsOffset+me+I*8;E.set(e.subarray(S,S+m),R),R+=m}return E.slice(0,R)}function ra(e,n,i,c){let u=i.sections.bairros;if(u.length<re)throw new T("Binary neighborhood table is truncated");let l=n.getUint32(u.offset,!0),d=ie(n.getUint8(u.offset+4),"original neighborhood id"),A=ie(n.getUint8(u.offset+5),"original locality id"),E=d+A+c.bairro.idWidth+c.bairroAbreviado.idWidth+c.uf.idWidth;fe(u,re+l*E,"neighborhood table"),at(e,u.offset+6,u.offset+re,"neighborhood table reserved bytes");let R=u.offset+re,O=0,p=0,I=0;for(let m=0;m<l;m++){let S=R+m*E,h=_(n,S,d);S+=d;let b=_(n,S,A);S+=A;let g=_(n,S,c.bairro.idWidth);S+=c.bairro.idWidth;let D=_(n,S,c.bairroAbreviado.idWidth);S+=c.bairroAbreviado.idWidth;let y=_(n,S,c.uf.idWidth);if(h<=O||b===0||g===0||g>c.bairro.count||D>c.bairroAbreviado.count||y===0||y>c.uf.count)throw new T(`Invalid binary neighborhood record: ${m}`);if(!c.bairro.values[g-1])throw new T(`Binary neighborhood has an empty name: ${m}`);Rn(c.uf.values[y-1]??"",m),O=h,p=Math.max(p,h),I=Math.max(I,b)}if(d!==v(p)||A!==v(I))throw new T("Binary neighborhood table uses a noncanonical integer width");return{count:l,idWidth:v(l),localidadeIdWidth:A,originalIdWidth:d,recordWidth:E,recordsOffset:R}}function ia(e,n,i){let c=3+i.municipio.idWidth+i.uf.idWidth,u=n.sections.municipalities;fe(u,n.municipalityCount*c,"municipalities");let l=new Uint32Array(n.municipalityCount+1),d=0;for(let A=0;A<n.municipalityCount;A++){let E=u.offset+A*c,R=_(e,E,3),O=_(e,E+3,i.municipio.idWidth),p=_(e,E+3+i.municipio.idWidth,i.uf.idWidth);if(R<1e6||R>9999999||R<=d)throw new T(`Invalid binary IBGE municipality code: ${R}`);if(O===0||O>i.municipio.count||p===0||p>i.uf.count)throw new T(`Invalid binary municipality record: ${A}`);if(!i.municipio.values[O-1])throw new T(`Binary municipality has an empty name: ${A}`);let I=Rn(i.uf.values[p-1]??"",A);if(Math.floor(R/1e5)!==de[I])throw new T(`IBGE municipality code does not match UF: ${R} (${I}, ${de[I]})`);l[A+1]=p,d=R}return{ufIds:l}}function oa(e,n,i,c){let u=new Uint32Array(i.rowCount);for(let[l,d,A]of[["complemento",c.complemento,void 0],["nome",c.nome,void 0],["localidadeNome",c.bairro,u]])aa(e,n,i.rowCount,i.sections[`${l}Bitmap`],i.sections[`${l}Ranks`],i.sections[`${l}Ids`],d.idWidth,d.count,l,A);return{localidadeNome:u}}function aa(e,n,i,c,u,l,d,A,E,R){if(l.length%d!==0)throw new T(`Binary ${E} sparse ids have an invalid length`);let O=Math.ceil(i/ee),p=0;for(let m=0;m<O;m++){let S=p;if(n.getUint32(u.offset+m*4,!0)!==S)throw new T(`Binary ${E} sparse rank mismatch: ${m}`);let b=m*ee,g=Math.min(i,b+ee);for(let D=b;D<g;D++){if(((e[c.offset+(D>>>3)]??0)&1<<(D&7))===0)continue;if(p>=l.length/d)throw new T(`Binary ${E} sparse id index is outside the column`);let U=_(n,l.offset+p*d,d);if(U===0||U>A)throw new T(`Invalid binary ${E} sparse id: ${U}`);if(R)R[D]=U;p++}}if(n.getUint32(u.offset+O*4,!0)!==p||l.length!==p*d)throw new T(`Binary ${E} sparse column has an invalid final rank`);ma(e,c,i,E)}function sa(e,n,i,c){fe(n.sections.localidadeFlags,c.count,"locality indicators"),ca(e,i),ua(e,n.sections.localidadeFlags,n,c)}function ca(e,n){let i=n.runCount*n.lowBits;if(i%8!==0&&(e.getUint8(n.lowOffset+Math.floor(i/8))&255<<(i&7))!==0)throw new T("Invalid binary neighborhood run low-bit padding")}function ua(e,n,i,c){let u=-1,l=-1;for(let d=0;d<c.count;d++){let A=_(e,c.idsOffset+d*i.municipalityIdWidth,i.municipalityIdWidth),E=e.getUint8(n.offset+d);if(A===0||A>i.municipalityCount||(E&3)>=ot.length||E>>>2>=it.length||A===u&&E===l)throw new T(`Invalid binary locality run: ${d}`);u=A,l=E}}function la(e,n,i){let{bairroFaixaOffsets:c,bairroFaixas:u}=n.sections;if(fe(c,(i.count+1)*4,"neighborhood range offsets"),u.length%8!==0||e.getUint32(c.offset,!0)!==0)throw new T("Invalid binary neighborhood range layout");let l=u.length/8,d=0;for(let A=0;A<i.count;A++){let E=e.getUint32(c.offset+(A+1)*4,!0);if(E<d||E>l)throw new T("Invalid binary neighborhood range offsets");let R=-1,O=-1;for(let p=d;p<E;p++){let I=e.getUint32(u.offset+p*8,!0),m=e.getUint32(u.offset+p*8+4,!0);if(I>m||m>99999999||I<R||I===R&&m<=O)throw new T("Invalid binary neighborhood CEP range");R=I,O=m}d=E}if(d!==l)throw new T("Unreferenced binary neighborhood CEP ranges")}function da(e,n,i){let c=i.sections.cepPrefixOffsets,u=new Uint32Array(Me),l=0;for(let A=0;A<Me;A++){let E=_(n,c.offset+A*i.cepPrefixOffsetWidth,i.cepPrefixOffsetWidth);if(E<l||E>i.rowCount)throw new T(`Invalid binary CEP prefix boundary: ${A}`);u[A]=E,l=E}if(u[0]!==0||u[fn]!==i.rowCount)throw new T("Binary CEP prefix directory has invalid boundaries");for(let A=0;A<fn;A++){let E=u[A]??0,R=u[A+1]??0,O=-1;for(let p=E;p<R;p++){let I=Sa(e,i.sections.cepSuffixes.offset,p);if(I>999||I<=O)throw new T(`Binary CEP suffixes are not strictly ordered: ${p}`);O=I}}let d=i.rowCount*pe;if(d%8!==0){if(((e[i.sections.cepSuffixes.offset+i.sections.cepSuffixes.length-1]??0)&255<<(d&7))!==0)throw new T("Invalid binary CEP suffix padding")}}function fa(e,n,i,c){let u=i.sections.logradouroIds,l=nt(c.count);fe(u,Xe(i.rowCount,l),"logradouro ids");for(let A=0;A<i.rowCount;A++){let E=kt(n,u.offset,A,l);if(E>c.count)throw new T(`Invalid binary logradouro id: ${E}`)}let d=i.rowCount*l;if(d%8!==0){if(((e[u.offset+u.length-1]??0)&255<<(d&7))!==0)throw new T("Invalid binary logradouro id padding")}}function Aa(e,n,i,c,u,l,d,A){let E=Ra(e,u),R=Oa(e,n,l),O=0,p=0;for(let I=0;I<n.rowCount;I++){while(O+1<E.starts.length&&(E.starts[O+1]??0)<=I)O++;while(p+1<R.starts.length&&(R.starts[p+1]??0)<=I)p++;let m=E.ids[O]??0,S=R.ids[p]??0,b=(R.flags[p]??0)>>>2;if((d.localidadeNome[I]??0)!==0&&(m!==0||b===0))throw new T(`Invalid binary subordinate locality name: ${I}`);if(m!==0){if(Ea(e,c,i,m)!==A.ufIds[S])throw new T(`Neighborhood and municipality UFs differ: ${I}`)}}}function Ea(e,n,i,c){let u=n.recordsOffset+(c-1)*n.recordWidth+n.originalIdWidth+n.localidadeIdWidth+i.bairro.idWidth+i.bairroAbreviado.idWidth;return _(e,u,i.uf.idWidth)}function Ra(e,n){let i=new Uint32Array(n.runCount),c=new Uint32Array(n.runCount),u=2**n.lowBits,l=0,d=0;for(let A=0;A<n.highBitCount;A++){if((e.getUint8(n.highOffset+(A>>>3))&1<<(A&7))===0){l++;continue}let R=ha(e,n.lowOffset,d*n.lowBits,n.lowBits);i[d]=l*u+R,c[d]=_(e,n.idsOffset+d*n.idWidth,n.idWidth),d++}return{ids:c,starts:i}}function Oa(e,n,i){let c=new Uint32Array(i.count),u=new Uint32Array(i.count),l=new Uint8Array(i.count);for(let d=0;d<i.count;d++)c[d]=e.getUint32(i.startsOffset+d*4,!0),u[d]=_(e,i.idsOffset+d*n.municipalityIdWidth,n.municipalityIdWidth),l[d]=e.getUint8(n.sections.localidadeFlags.offset+d);return{flags:l,ids:u,starts:c}}function pa(e,n){let i=e.subarray(n.offset,n.offset+n.length);if(i[0]===239&&i[1]===187&&i[2]===191)throw new T("Binary database metadata must not contain a UTF-8 BOM");let c;try{c=JSON.parse(gr.decode(i))}catch(u){throw new T("Binary database metadata is invalid JSON or UTF-8",{cause:u})}if(!c||typeof c!=="object"||Array.isArray(c))throw new T("Binary database metadata must be an object");for(let u of Object.values(c))if(typeof u!=="string")throw new T("Binary database metadata values must be strings")}function Ia(e,n,i){if(n.offset<q||n.offset>e||n.length>e-n.offset)throw new T(`Binary ${i} region is outside the payload`)}function fe(e,n,i){if(e.length!==n)throw new T(`Binary ${i} region has an invalid length`)}function at(e,n,i,c){for(let u=n;u<i;u++)if((e[u]??0)!==0)throw new T(`Invalid ${c}`)}function ma(e,n,i,c){if(i%8!==0){if(((e[n.offset+n.length-1]??0)&255<<(i&7))!==0)throw new T(`Invalid binary ${c} bitmap padding`)}}function Sa(e,n,i){let c=i*pe,u=n+Math.floor(c/8),l=c&7;return((e[u]??0)|(e[u+1]??0)<<8|(e[u+2]??0)<<16)>>>l&1023}function ha(e,n,i,c){let u=0;for(let l=0;l<c;l++){let d=i+l;if(e.getUint8(n+(d>>>3))&1<<(d&7))u+=2**l}return u}function yr(e){Dr(e);let n=e.byteLength-X;e.set(new Bun.CryptoHasher("sha256").update(e.subarray(0,n)).digest(),n)}function Nr(e){let n=e.byteLength-X,i=new Bun.CryptoHasher("sha256").update(e.subarray(0,n)).digest();for(let c=0;c<X;c++)if(e[n+c]!==i[c])throw new T("Binary database SHA-256 checksum mismatch")}class w extends Error{code;exitCode;details;constructor(e,n,i=1,c){super(n);this.code=e;this.exitCode=i;this.details=c;this.name="UserError"}}var Ta=/[\s,;]/;function st(e){let n=e.length;if(n!==8&&n!==9)return Number.NaN;if(n===9&&e.charCodeAt(5)!==45)return Number.NaN;let i=e.charCodeAt(0)-48,c=e.charCodeAt(1)-48,u=e.charCodeAt(2)-48,l=e.charCodeAt(3)-48,d=e.charCodeAt(4)-48,A=e.charCodeAt(n-3)-48,E=e.charCodeAt(n-2)-48,R=e.charCodeAt(n-1)-48;if((i|c|u|l|d|A|E|R|9-i|9-c|9-u|9-l|9-d|9-A|9-E|9-R)<0)return Number.NaN;return i*1e7+c*1e6+u*1e5+l*1e4+d*1000+A*100+E*10+R}function Lr(e){let n=e.trim(),i=st(n);if(Number.isNaN(i))return;return String(i).padStart(8,"0")}async function*wr(e,n,i=process.stdin.isTTY===!0){let c=n?n==="-"?Bun.stdin:Bun.file(n):null;if(n&&n!=="-"&&c&&!await c.exists())throw new w("input-file-not-found",`Arquivo de entrada com CEPs n\xE3o encontrado: ${n}`);for(let u of e)yield u;if(c){yield*Cr(c.stream());return}if(!e.length&&!i)yield*Cr(Bun.stdin.stream())}async function*Cr(e){let n=new TextDecoder,i="";for await(let c of e){let u=i+n.decode(c,{stream:!0}),l=0;for(let d=0;d<u.length;d++){if(!Ta.test(u[d]??""))continue;if(d>l)yield u.slice(l,d);l=d+1}i=u.slice(l)}if(i+=n.decode(),i)yield i}import{Buffer as ba}from"buffer";var Mr=new WeakMap,ga=new TextDecoder;function Da(e,n){let i=new Uint8Array(me),c=new Uint32Array(me*2);for(let d=0;d<i.length;d++)i[d]=e.getUint8(n.symbolsOffset+d);for(let d=0;d<c.length;d++)c[d]=e.getUint32(n.symbolsOffset+me+d*4,!0);let u=ba.alloc(272),l={lengths:i,words:c,output:u,view:new DataView(u.buffer,u.byteOffset,u.byteLength)};return Mr.set(n,l),l}function Ur(e,n,i,c){let{lengths:u,words:l,output:d,view:A}=Mr.get(i)??Da(n,i),E=c-1,R=E>>>H,O=i.suffixDataOffset+n.getUint32(i.blockOffsetsOffset+R*4,!0),p=0;for(let I=R*J;I<=E;I++){let m=i.lengthWidth===1?e[i.lengthsOffset+I]:n.getUint16(i.lengthsOffset+I*2,!0),S=O+m,h=e[i.prefixesOffset+I];while(O<S){let b=e[O++];if(b===255)d[h++]=e[O++];else A.setUint32(h,l[b*2],!0),A.setUint32(h+4,l[b*2+1],!0),h+=u[b]}p=h}return ga.decode(d.subarray(0,p))}import{closeSync as ya,fstatSync as Na,openSync as Ca,readFileSync as La,readSync as wa}from"fs";function Pr(e){let n;try{n=Ca(e,"r")}catch(i){if(i.code!=="ENOENT")throw i;let c=La(e),u=new SharedArrayBuffer(c.byteLength);return new Uint8Array(u).set(c),u}try{let i=new SharedArrayBuffer(Na(n).size),c=new Uint8Array(i),u=0;while(u<c.byteLength){let l=wa(n,c,u,c.byteLength-u,u);if(l===0)throw Error(`File ended while loading shared snapshot: ${e}`);u+=l}return i}finally{ya(n)}}var _r=new TextDecoder,Br=Je();async function On(e){try{if(!await Bun.file(e).exists())return!1;let n=new Uint8Array(await Bun.file(e).slice(0,K.length).arrayBuffer());return or(n)}catch(n){throw new Rt(e,{cause:n})}}class he{bairroCache;data;decodeScratch=new Uint8Array(255);dictionaries;bairros;bairroRuns;localityRuns;logradouroIdBits;header;bytes;metadataValue;municipalityCache;constructor(e){let n=e instanceof SharedArrayBuffer?new Uint8Array(e):Ua(e);try{let i=new DataView(n.buffer,n.byteOffset,n.byteLength);Pa(i),Nr(n);let c=Ba(i),u=_a(i,c),l=xa(i,c,u),d=Er(i,c.sections.bairroIds,c.rowCount,l.idWidth),A=mr(i,c.sections.municipalityIds,c.rowCount),E=Va(n,c.sections.metadata);this.bytes=n,this.data=i,this.header=c,this.dictionaries=u,this.bairros=l,this.bairroRuns=d,this.localityRuns=A,this.logradouroIdBits=nt(u.logradouro.count),this.metadataValue=Object.freeze(E),this.bairroCache=Array.from({length:u.bairro.count+1}),this.municipalityCache=Array.from({length:c.municipalityCount+1})}catch(i){if(this.bytes=null,this.data=null,i instanceof Se)throw i;throw new T("Unable to decode binary database",{cause:i})}}close(){this.bairroCache=[],this.data=null,this.bytes=null,this.municipalityCache=[]}[Symbol.dispose](){this.close()}metadata(){return this.metadataValue}queryCep(e){this.assertOpen();let n=this.findCepIndex(e);return n===-1?void 0:this.readRow(n,e.replace("-",""))}queryMunicipality(e){if(this.assertOpen(),!Number.isInteger(e)||e<1e6||e>9999999)return;let n=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,i=this.header.sections.municipalities.offset,c=0,u=this.header.municipalityCount-1;while(c<=u){let l=c+(u-c>>>1),d=this.readPackedInteger(i+l*n,3);if(d<e)c=l+1;else if(d>e)u=l-1;else{let{municipio:A,uf:E}=this.readMunicipality(l+1);return{municipio:A,uf:E}}}return}queryMunicipalityCodesByUf(e){if(this.assertOpen(),!Object.hasOwn(de,e))return[];let n=de[e]*1e5,i=n+1e5,c=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,u=this.header.sections.municipalities.offset,l=0,d=this.header.municipalityCount;while(l<d){let E=l+(d-l>>>1);if(this.readPackedInteger(u+E*c,3)<n)l=E+1;else d=E}let A=[];for(let E=l;E<this.header.municipalityCount;E++){let R=this.readPackedInteger(u+E*c,3);if(R>=i)break;A.push(R)}return A}queryNeighborhood(e){this.assertOpen();let n=this.findNeighborhoodIndex(e);return n===0?void 0:this.readNeighborhood(n)}queryNeighborhoodByCep(e){this.assertOpen();let n=this.findCepIndex(e);if(n===-1)return;let i=this.readNeighborhoodIndex(n);return i===0?void 0:this.readNeighborhood(i)}queryNeighborhoodCepRanges(e){this.assertOpen();let n=this.findNeighborhoodIndex(e);if(n===0)return[];let{bairroFaixaOffsets:i,bairroFaixas:c}=this.header.sections,u=this.readUint32(i.offset+(n-1)*4),l=this.readUint32(i.offset+n*4),d=[];for(let A=u;A<l;A++){let E=this.readUint32(c.offset+A*8),R=this.readUint32(c.offset+A*8+4);d.push({cep_inicial:String(E).padStart(8,"0"),cep_final:String(R).padStart(8,"0")})}return d}rowCount(){return this.header.rowCount}checksum(){return this.assertOpen(),Buffer.from(this.bytes.subarray(-X)).toString("hex")}*entries(){this.assertOpen();let e=this.header.sections.cepPrefixOffsets,n=this.header.cepPrefixOffsetWidth,i=0;for(let c=0;c<this.header.rowCount;c++){while(c>=this.readPackedInteger(e.offset+(i+1)*n,n))i++;let u=String(i*1000+this.readPacked10(c)).padStart(8,"0");yield this.readRow(c,u),this.assertOpen()}}assertOpen(){if(this.data===null)throw new $t}findCepIndex(e){let n=st(e);if(Number.isNaN(n))return-1;let i=Math.floor(n/1000),c=n%1000,u=this.header.sections.cepPrefixOffsets,l=this.header.cepPrefixOffsetWidth,d=this.readPackedInteger(u.offset+i*l,l),A=this.readPackedInteger(u.offset+(i+1)*l,l),E=A;while(d<E){let R=d+(E-d>>>1);if(this.readPacked10(R)<c)d=R+1;else E=R}if(d>=A||this.readPacked10(d)!==c)return-1;return d}findNeighborhoodIndex(e){if(!oe(e))return 0;let n=0,i=this.bairros.count;while(n<i){let u=n+(i-n>>>1);if(this.readPackedInteger(this.bairros.recordsOffset+u*this.bairros.recordWidth,this.bairros.originalIdWidth)<e)n=u+1;else i=u}if(n===this.bairros.count)return 0;return this.readPackedInteger(this.bairros.recordsOffset+n*this.bairros.recordWidth,this.bairros.originalIdWidth)===e?n+1:0}readNeighborhoodIndex(e){return Or(this.data,this.bairroRuns,e)}readNeighborhood(e){let{originalIdWidth:n,localidadeIdWidth:i,recordsOffset:c,recordWidth:u}=this.bairros,l=c+(e-1)*u,d=this.readPackedInteger(l,n);l+=n;let A=this.readPackedInteger(l,i);l+=i;let E=this.readRequiredDictionaryString(this.dictionaries.bairro,this.readPackedInteger(l,this.dictionaries.bairro.idWidth));l+=this.dictionaries.bairro.idWidth;let R=this.readDictionaryString(this.dictionaries.bairroAbreviado,this.readPackedInteger(l,this.dictionaries.bairroAbreviado.idWidth));l+=this.dictionaries.bairroAbreviado.idWidth;let O=this.readRequiredDictionaryString(this.dictionaries.uf,this.readPackedInteger(l,this.dictionaries.uf.idWidth));return{bairro_id:d,localidade_id:A,nome:E,nome_abreviado:R,uf:O}}readRow(e,n){let i=this.header.sections,c=hr(this.data,this.localityRuns,e),u=this.readPackedInteger(this.localityRuns.idsOffset+c*this.header.municipalityIdWidth,this.header.municipalityIdWidth),l=this.readMunicipality(u),d=this.data.getUint8(i.localidadeFlags.offset+c),A=ot[d&3],E=it[d>>>2],R=this.readNeighborhoodIndex(e),O=this.readSparseId(i.localidadeNomeBitmap,i.localidadeNomeRanks,i.localidadeNomeIds,e,this.dictionaries.bairro.idWidth),p=R===0?O:this.readPackedInteger(this.bairros.recordsOffset+(R-1)*this.bairros.recordWidth+this.bairros.originalIdWidth+this.bairros.localidadeIdWidth,this.dictionaries.bairro.idWidth);return{bairro:this.readCachedDictionaryString(this.dictionaries.bairro,p,this.bairroCache),cep:n,complemento:this.readDictionaryString(this.dictionaries.complemento,this.readSparseId(i.complementoBitmap,i.complementoRanks,i.complementoIds,e,this.dictionaries.complemento.idWidth)),localidade_situacao:A,localidade_tipo:E,logradouro:this.readDictionaryString(this.dictionaries.logradouro,kt(this.data,i.logradouroIds.offset,e,this.logradouroIdBits)),municipio:l.municipio,municipio_cod_ibge:l.codigoIbge,nome:this.readDictionaryString(this.dictionaries.nome,this.readSparseId(i.nomeBitmap,i.nomeRanks,i.nomeIds,e,this.dictionaries.nome.idWidth)),uf:l.uf}}readMunicipality(e){let n=this.municipalityCache[e];if(n)return n;let i=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,c=this.header.sections.municipalities.offset+(e-1)*i,u=this.readPackedInteger(c+3,this.dictionaries.municipio.idWidth),l=this.readPackedInteger(c+3+this.dictionaries.municipio.idWidth,this.dictionaries.uf.idWidth),d={codigoIbge:this.readPackedInteger(c,3),municipio:this.readRequiredDictionaryString(this.dictionaries.municipio,u),uf:this.readRequiredDictionaryString(this.dictionaries.uf,l)};return this.municipalityCache[e]=d,d}readSparseId(e,n,i,c,u){let l=this.bytes,d=c>>>3,A=l[e.offset+d],E=c&7;if((A&1<<E)===0)return 0;let R=c>>>Pe,O=this.readUint32(n.offset+R*4),p=R*(ee>>>3);for(let I=p;I<d;I++)O+=Br[l[e.offset+I]];return O+=Br[A&(1<<E)-1],this.readPackedInteger(i.offset+O*u,u)}readDictionaryString(e,n){if(n===0)return null;let i=this.bytes;if(e.codec===Ie)return Ur(i,this.data,e,n);let c=n-1,u=c>>>H,l=u<<H,d=this.readUint32(e.blockOffsetsOffset+u*4),A=e.suffixDataOffset+d,E=this.decodeScratch,R=0;for(let O=l;O<=c;O++){let p=i[e.lengthsOffset+O],I=i[e.prefixesOffset+O],m=p-I;E.set(i.subarray(A,A+m),I),A+=m,R=p}return _r.decode(E.subarray(0,R))}readCachedDictionaryString(e,n,i){if(n===0)return null;let c=i[n];if(c!==void 0)return c;let u=this.readRequiredDictionaryString(e,n);return i[n]=u,u}readRequiredDictionaryString(e,n){return this.readDictionaryString(e,n)}readPacked10(e){let n=this.bytes,i=this.header.sections.cepSuffixes,c=e*pe,u=c>>>3,l=c&7,d=i.offset+u;return(n[d]|n[d+1]<<8|n[d+2]<<16)>>>l&1023}readPackedInteger(e,n){return _(this.data,e,n)}readUint32(e){return this.data.getUint32(e,!0)}}function Ua(e,n=!1){try{return n?new Uint8Array(Pr(e)):Ma(e)}catch(i){throw new Rt(e,{cause:i})}}function Pa(e){if(e.byteLength<q+X)throw new T("Binary database header is truncated");for(let i=0;i<K.length;i++)if(e.getUint8(i)!==K[i])throw new T("Invalid binary database magic");let n=e.getUint16(8,!0);if(n!==Oe)throw new Gt(n,Oe);if(e.getUint16(10,!0)!==q)throw new T("Unsupported binary database header size");if(e.getUint8(22)!==Pe||e.getUint8(23)!==H)throw new T("Unsupported binary database block layout");if(e.getUint16(24,!0)!==Y.length)throw new T("Unsupported binary database section table");if(e.getUint32(16,!0)!==e.byteLength)throw new T(`Binary database size mismatch: header=${e.getUint32(16,!0)}, actual=${e.byteLength}`)}function Ba(e){let n={};for(let[i,c]of Y.entries()){let u=ze+i*8;n[c]={length:e.getUint32(u+4,!0),offset:e.getUint32(u,!0)}}return{cepPrefixOffsetWidth:e.getUint8(20),fileSize:e.getUint32(16,!0),municipalityCount:e.getUint32(28,!0),municipalityIdWidth:e.getUint8(21),rowCount:e.getUint32(12,!0),sections:n}}function _a(e,n){return{bairro:Fe(e,n.sections.bairroDictionary),bairroAbreviado:Fe(e,n.sections.bairroAbreviadoDictionary),complemento:Fe(e,n.sections.complementoDictionary),logradouro:Fe(e,n.sections.logradouroDictionary),municipio:Fe(e,n.sections.municipioDictionary),nome:Fe(e,n.sections.nomeDictionary),uf:Fe(e,n.sections.ufDictionary)}}function Fe(e,n){let i=e.getUint32(n.offset,!0),c=n.offset+e.getUint32(n.offset+16,!0);return{blockCount:e.getUint32(n.offset+4,!0),blockOffsetsOffset:n.offset+e.getUint32(n.offset+8,!0),count:i,codec:e.getUint8(n.offset+30),idWidth:e.getUint8(n.offset+28),lengthsOffset:n.offset+e.getUint32(n.offset+12,!0),lengthWidth:e.getUint8(n.offset+31)===2?2:1,prefixesOffset:c,region:n,suffixDataLength:e.getUint32(n.offset+24,!0),suffixDataOffset:n.offset+e.getUint32(n.offset+20,!0),symbolsOffset:c+i}}function xa(e,n,i){let c=n.sections.bairros,u=e.getUint32(c.offset,!0),l=e.getUint8(c.offset+4),d=e.getUint8(c.offset+5),A=l+d+i.bairro.idWidth+i.bairroAbreviado.idWidth+i.uf.idWidth;return{count:u,idWidth:v(u),originalIdWidth:l,localidadeIdWidth:d,recordsOffset:c.offset+re,recordWidth:A}}function Va(e,n){return JSON.parse(_r.decode(e.subarray(n.offset,n.offset+n.length)))}import{Database as Xa}from"bun:sqlite";var Wt=255,Fa=255,pn=8,xr=510,Ht=65536,va=[64,128,160,192,224];function vr(e){if(!e.count)throw Error("Cannot train FSST with an empty dictionary");let n=Ga(e),i=Ha($a(n),ka(n),n),c=ja(e,i);return{compressedLengths:c.maxLength<=255?Uint8Array.from(c.lengths):Qa(c.lengths),lengthWidth:c.maxLength<=255?1:2,payload:c.payload,symbols:i.symbols}}function Ga(e){let n=e.totalBytes,i=[],c=Math.min(e.count,Ht,Math.ceil(Ht/Math.max(1,n/e.count))),u=e.count/Math.max(1,c),l=2654435769,d=0;for(let A=0;A<c&&d<Ht;A++){l=Math.imul(l,1664525)+1013904223>>>0;let E=Math.floor(l/4294967296*Math.max(1,u)),R=Math.min(e.count-1,Math.floor(A*u)+E),O=e.get(R);if(!O?.byteLength)continue;let p=Ht-d;i.push(O.byteLength<=p?O:O.subarray(0,p)),d+=Math.min(O.byteLength,p)}return i}function $a(e){let n=new Map;for(let c of e)for(let u=0;u+1<c.byteLength;u++){let l="",d=Math.min(c.byteLength,u+pn);for(let A=u;A<d;A++)if(l+=String.fromCharCode(c[A]??0),A-u+1>=2)n.set(l,(n.get(l)??0)+1)}let i=[];for(let[c,u]of n){let l=c.length;i.push({key:c,length:l,score:u*(l-1)})}return i.sort(za),i.slice(0,4096)}function ka(e){let n=new Uint32Array(256);for(let i of e)for(let c of i)n[c]=(n[c]??0)+1;return Array.from({length:256},(i,c)=>c).filter((i)=>(n[i]??0)>0).sort((i,c)=>(n[c]??0)-(n[i]??0)||i-c)}function Ha(e,n,i){let c=Vr(n.slice(0,Wt).map((l)=>Uint8Array.of(l))),u={table:c,size:Fr(i,c).size};for(let l of va){let d=e.slice(0,l),A=d.length,E=n.slice(0,Wt-d.length).map((R)=>Uint8Array.of(R));for(let R=0;R<4;R++){let O=d.map((S)=>Za(S.key)).concat(E),p=Vr(O),I=Fr(i,p);if(I.size<u.size)u={table:p,size:I.size};let m=d.filter((S,h)=>(I.uses[h]??0)>0);if(m.length===d.length||A===e.length)break;while(m.length<l&&A<e.length){let S=e[A++];if(S)m.push(S)}d=m}}return u.table}function Vr(e){let n=new Uint8Array(Ue),i=Gr();for(let[c,u]of e.entries())n[c]=u.byteLength,n.set(u,Wt+c*pn),Wa(i,u,c);return{symbols:n,trie:i}}function Gr(){return{code:-1,children:new Map}}function Wa(e,n,i){let c=e;for(let u of n){let l=c.children.get(u);if(!l)l=Gr(),c.children.set(u,l);c=l}c.code=i}function Fr(e,n){let i=0,c=new Uint32Array(Wt);for(let u of e){let l=0;while(l<u.byteLength){let d=$r(u,l,n.trie);if(d)i++,c[d.code]=(c[d.code]??0)+1,l+=d.length;else i+=2,l++}}return{size:i,uses:c}}function ja(e,n){let i=new Uint32Array(e.count),c=e.totalBytes*2,u=new Uint8Array(c),l=0,d=0;for(let A=0;A<e.count;A++){let E=e.get(A),R=l;l=qa(E,n,u,l);let O=l-R;if(i[A]=O,d=Math.max(d,O),O>xr)throw Error(`FSST compressed suffix exceeds ${xr} bytes: ${O}`)}return{lengths:i,maxLength:d,payload:u.slice(0,l)}}function qa(e,n,i,c){let u=0,l=c;while(u<e.byteLength){let d=$r(e,u,n.trie);if(d)i[l++]=d.code,u+=d.length;else i[l++]=Fa,i[l++]=e[u++]??0}return l}function $r(e,n,i){let c=i,u=-1,l=0,d=Math.min(e.byteLength,n+pn);for(let A=n;A<d;A++){let E=c.children.get(e[A]??0);if(!E)break;if(c=E,c.code>=0)u=c.code,l=A-n+1}return u<0?void 0:{code:u,length:l}}function Za(e){let n=new Uint8Array(e.length);for(let i=0;i<e.length;i++)n[i]=e.charCodeAt(i);return n}function za(e,n){return n.score-e.score||n.length-e.length||(e.key<n.key?-1:e.key>n.key?1:0)}function Qa(e){let n=new Uint8Array(e.length*2),i=new DataView(n.buffer);for(let c=0;c<e.length;c++)i.setUint16(c*2,e[c]??0,!0);return n}var kr="dne",Hr="dne.db",z="dne",Te="bairros",St="bairro_faixas",Z="edne_metadata",Wr=32768,jr=-200000,qr=1000,Zr=8,jt=2097152,zr=30000,Qr=2,Xr=100,Jr=1000,Yr=2000;var Sn=new TextEncoder,Ja=Je();async function Kr(e,n,i=z){As();let c=new Xa(e,{readonly:!0});try{c.run("BEGIN");let u=us(c,i);if(qt(u,"row count"),!u)throw Error("Cannot create a binary database without rows");let l=c.query(`SELECT bairro_id, localidade_id, uf, nome, nome_abreviado
|
|
4
|
+
FROM ${Tt(Te)} ORDER BY bairro_id`).all(),d=new Map(l.map((B,Q)=>[B.bairro_id,Q+1])),A=v(l.length),E=Ya(c,i,l),R=Ka(E);R.logradouro=es(R.logradouro);let O=[...E.municipalitiesByIbge.entries()].sort(([B],[Q])=>B-Q),p=O.length,I=v(p),m=new Map;for(let[B,[Q]]of O.entries())m.set(Q,B+1);let S=new Uint32Array(Me),h=new Uint8Array(Xe(u,pe)),b=nt(R.logradouro.count),g=new Uint8Array(Xe(u,b)),D=new Uint8Array(Qe(u)),y=new Uint8Array(E.complementoCount*R.complemento.idWidth),U=new Uint8Array(u*A),L=new Uint8Array(Qe(u)),V=new Uint8Array(E.localidadeNomeCount*R.bairro.idWidth),W=new Uint8Array(u*I),C=new Uint8Array(u),x=new Uint8Array(Qe(u)),j=new Uint8Array(E.nomeCount*R.nome.idWidth),qe=0,ye=0,Ne=0,ue=0,lt=-1,k=0;for(let B of ei(c,i)){let Q=hn(B.cep);if(Q<=lt)throw Error("CEP rows must be unique and ordered");lt=Q;let Ee=rt.indexOf(B.localidade_tipo);if(Ee===-1||![0,1,2,3].includes(B.localidade_situacao))throw Error(`Invalid locality indicators for CEP: ${B.cep}`);C[k]=Ee<<2|B.localidade_situacao;let we=Math.floor(Q/1000);while(ue<=we)S[ue]=k,ue++;if(ar(h,k,Q%1000),Tr(g,k,b,ti(R.logradouro,B.logradouro)),B.complemento!==null)mn(D,k),F(y,qe*R.complemento.idWidth,be(R.complemento,B.complemento,"complemento"),R.complemento.idWidth),qe++;let Re=B.bairro_id===null?0:d.get(B.bairro_id);if(Re===void 0)throw Error(`Unknown bairro_id for CEP: ${B.cep}`);if(F(U,k*A,Re,A),B.localidade_nome!==null){if(Re!==0||B.localidade_tipo==="M")throw Error(`Invalid subordinate locality name for CEP: ${B.cep}`);mn(L,k),F(V,Ne*R.bairro.idWidth,be(R.bairro,B.localidade_nome,"localidade_nome"),R.bairro.idWidth),Ne++}let Xn=m.get(B.municipio_cod_ibge);if(Xn===void 0)throw Error(`Missing municipality for IBGE code: ${B.municipio_cod_ibge}`);if(F(W,k*I,Xn,I),B.nome!==null)mn(x,k),F(j,ye*R.nome.idWidth,be(R.nome,B.nome,"nome"),R.nome.idWidth),ye++;k++}if(k!==u)throw Error(`SQLite row count changed while exporting: expected ${u}, got ${k}`);if(qe!==E.complementoCount||ye!==E.nomeCount||Ne!==E.localidadeNomeCount)throw Error("SQLite nullable field counts changed while exporting");while(ue<Me)S[ue]=u,ue++;let G=v(u),ne=In(D,y,u),Ce=In(x,j,u),Le=In(L,V,u),N=as(c,d),P=Sn.encode(JSON.stringify(ls(c))),le=is(O,R),xt=Ir(W,C,I),dt={bairroDictionary:R.bairro.bytes,bairroAbreviadoDictionary:R.bairroAbreviado.bytes,bairroIds:Ar(U,u,A),bairros:os(l,R),bairroFaixaOffsets:N.offsets,bairroFaixas:N.ranges,cepPrefixOffsets:fs(S,G),cepSuffixes:h,complementoBitmap:ne.bitmap,complementoDictionary:R.complemento.bytes,complementoIds:ne.ids,complementoRanks:ne.ranks,localidadeFlags:xt.flags,localidadeNomeBitmap:Le.bitmap,localidadeNomeRanks:Le.ranks,localidadeNomeIds:Le.ids,logradouroDictionary:R.logradouro.bytes,logradouroIds:g,metadata:P,municipalities:le,municipalityIds:xt.ids,municipioDictionary:R.municipio.bytes,nomeBitmap:Ce.bitmap,nomeDictionary:R.nome.bytes,nomeIds:Ce.ids,nomeRanks:Ce.ranks,ufDictionary:R.uf.bytes};return await ss(n,u,p,I,G,dt),c.run("COMMIT"),u}finally{c.close()}}function Ya(e,n,i){let c={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 u of i){if(!oe(u.bairro_id)||!oe(u.localidade_id)||!u.nome||!u.uf)throw Error(`Invalid neighborhood: ${u.bairro_id}`);c.strings.bairro.add(u.nome),ht(c.strings.bairroAbreviado,u.nome_abreviado),c.strings.uf.add(u.uf)}for(let u of ei(e,n)){if(ht(c.strings.logradouro,u.logradouro),ht(c.strings.complemento,u.complemento),ht(c.strings.bairro,u.localidade_nome),c.strings.municipio.add(u.municipio),c.strings.uf.add(u.uf),ht(c.strings.nome,u.nome),u.complemento!==null)c.complementoCount++;if(u.nome!==null)c.nomeCount++;if(u.localidade_nome!==null)c.localidadeNomeCount++;An(u.municipio_cod_ibge,3,"municipio_cod_ibge");let l=c.municipalitiesByIbge.get(u.municipio_cod_ibge);if(l&&(l.municipio!==u.municipio||l.uf!==u.uf))throw Error(`IBGE code maps to multiple municipalities: ${u.municipio_cod_ibge}`);c.municipalitiesByIbge.set(u.municipio_cod_ibge,{municipio:u.municipio,uf:u.uf})}return c}function Ka(e){return{bairro:ve(e.strings.bairro),bairroAbreviado:ve(e.strings.bairroAbreviado),complemento:ve(e.strings.complemento),logradouro:ve(e.strings.logradouro),municipio:ve(e.strings.municipio),nome:ve(e.strings.nome),uf:ve(e.strings.uf)}}function ve(e){let n=[...e].sort(),i=n.length,c=Math.ceil(i/J),u=new Uint32Array(c),l=new Uint8Array(i),d=new Uint8Array(i),A=new Map,E=new Uint8Array,R=0;for(let[g,D]of n.entries()){let y=Sn.encode(D);if(y.byteLength>255)throw Error(`Binary string exceeds 255 UTF-8 bytes: ${D}`);let U=g%J===0?0:ds(E,y);if(g%J===0)u[g>>>H]=R;l[g]=y.byteLength,d[g]=U,R+=y.byteLength-U,qt(R,"dictionary suffix data length"),A.set(D,g+1),E=y}let O=Ze,p=O+u.byteLength,I=p+l.byteLength,m=I+d.byteLength,S=new Uint8Array(m+R),h=new DataView(S.buffer);h.setUint32(0,i,!0),h.setUint32(4,c,!0),h.setUint32(8,O,!0),h.setUint32(12,p,!0),h.setUint32(16,I,!0),h.setUint32(20,m,!0),h.setUint32(24,R,!0),h.setUint8(28,v(i)),h.setUint8(29,H),S.set(Zt(u),O),S.set(l,p),S.set(d,I);let b=m;for(let[g,D]of n.entries()){let y=Sn.encode(D),U=d[g]??0;S.set(y.subarray(U),b),b+=y.byteLength-U}return{bytes:S,count:i,ids:A,idWidth:v(i)}}function es(e){let n=ts(e);if(!n.count||n.suffixDataLength<=Ue)return e;let i=vr(n.source),c=ns(e,n,i.compressedLengths,i.lengthWidth,i.symbols,i.payload);return c.byteLength<e.bytes.byteLength?{...e,bytes:c}:e}function ts(e){let n=new DataView(e.bytes.buffer,e.bytes.byteOffset,e.bytes.byteLength),i=n.getUint32(0,!0),c=n.getUint32(4,!0),u=e.bytes.subarray(n.getUint32(8,!0),n.getUint32(12,!0)),l=new DataView(u.buffer,u.byteOffset,u.byteLength),d=e.bytes.subarray(n.getUint32(12,!0),n.getUint32(16,!0)),A=e.bytes.subarray(n.getUint32(16,!0),n.getUint32(20,!0)),E=n.getUint32(20,!0),R=n.getUint32(24,!0);return{blockCount:c,blockOffsets:u,count:i,lengths:d,prefixes:A,source:{count:i,totalBytes:R,get(p){let I=p>>>H,m=E+l.getUint32(I*4,!0),S=I*J;for(let b=S;b<p;b++)m+=(d[b]??0)-(A[b]??0);let h=(d[p]??0)-(A[p]??0);return e.bytes.subarray(m,m+h)}},suffixDataLength:R}}function ns(e,n,i,c,u,l){let d=n.blockCount,A=new Uint32Array(d),E=0;for(let b=0;b<n.count;b++){if(b%J===0)A[b>>>H]=E;E+=rs(i,c,b),qt(E,"FSST dictionary suffix data length")}if(E!==l.byteLength||u.byteLength!==Ue)throw Error("Invalid FSST encoder result");let R=Ze,O=R+A.byteLength,p=O+i.byteLength,I=p+n.count,m=I+u.byteLength,S=new Uint8Array(m+l.byteLength),h=new DataView(S.buffer);return h.setUint32(0,n.count,!0),h.setUint32(4,d,!0),h.setUint32(8,R,!0),h.setUint32(12,O,!0),h.setUint32(16,p,!0),h.setUint32(20,m,!0),h.setUint32(24,l.byteLength,!0),h.setUint8(28,e.idWidth),h.setUint8(29,H),h.setUint8(30,Ie),h.setUint8(31,c),S.set(Zt(A),R),S.set(i,O),S.set(n.prefixes,p),S.set(u,I),S.set(l,m),S}function rs(e,n,i){if(n===1)return e[i]??0;let c=i*2;return(e[c]??0)|(e[c+1]??0)<<8}function is(e,n){let i=3+n.municipio.idWidth+n.uf.idWidth,c=new Uint8Array(e.length*i);for(let[u,[l,d]]of e.entries()){let A=u*i;F(c,A,l,3),F(c,A+3,be(n.municipio,d.municipio,"municipio"),n.municipio.idWidth),F(c,A+3+n.municipio.idWidth,be(n.uf,d.uf,"uf"),n.uf.idWidth)}return c}function In(e,n,i){let c=Math.ceil(i/ee),u=new Uint32Array(c+1),l=0;for(let d=0;d<c;d++){u[d]=l;let A=d*(ee>>>3),E=Math.min(A+(ee>>>3),e.byteLength);for(let R=A;R<E;R++)l+=Ja[e[R]??0]??0}return u[c]=l,{bitmap:e,ids:n,ranks:Zt(u)}}function os(e,n){let i=v(e.at(-1)?.bairro_id??0),c=v(e.reduce((A,E)=>Math.max(A,E.localidade_id),0)),u=i+c+n.bairro.idWidth+n.bairroAbreviado.idWidth+n.uf.idWidth,l=new Uint8Array(re+e.length*u),d=new DataView(l.buffer);d.setUint32(0,e.length,!0),d.setUint8(4,i),d.setUint8(5,c);for(let[A,E]of e.entries()){let R=re+A*u;F(l,R,E.bairro_id,i),R+=i,F(l,R,E.localidade_id,c),R+=c,F(l,R,be(n.bairro,E.nome,"bairro"),n.bairro.idWidth),R+=n.bairro.idWidth,F(l,R,ti(n.bairroAbreviado,E.nome_abreviado),n.bairroAbreviado.idWidth),R+=n.bairroAbreviado.idWidth,F(l,R,be(n.uf,E.uf,"uf"),n.uf.idWidth)}return l}function as(e,n){let i=e.query(`SELECT bairro_id, cep_inicial, cep_final FROM ${Tt(St)}
|
|
5
|
+
ORDER BY bairro_id, cep_inicial, cep_final`).all(),c=new Uint32Array(n.size+1),u=new Uint8Array(i.length*8),l=new DataView(u.buffer),d=0,A;for(let[E,R]of i.entries()){let O=n.get(R.bairro_id);if(O===void 0)throw Error(`Unknown neighborhood in CEP range: ${R.bairro_id}`);let p=hn(R.cep_inicial),I=hn(R.cep_final);if(p>I)throw Error(`Reversed neighborhood CEP range: ${R.bairro_id}`);if(A?.bairro_id===R.bairro_id&&A.cep_inicial===R.cep_inicial&&A.cep_final===R.cep_final)throw Error(`Duplicate neighborhood CEP range: ${R.bairro_id}`);while(d<O)c[d++]=E;l.setUint32(E*8,p,!0),l.setUint32(E*8+4,I,!0),A=R}while(d<c.length)c[d++]=i.length;return{offsets:Zt(c),ranges:u}}async function ss(e,n,i,c,u,l){let d={},A=q;for(let p of Y)A=ft(A),d[p]={length:l[p].byteLength,offset:A},A+=l[p].byteLength;let E=ft(A)+X;qt(E,"file size");let R=cs({cepPrefixOffsetWidth:u,fileSize:E,municipalityCount:i,municipalityIdWidth:c,rowCount:n,sections:d}),O=new Uint8Array(E);O.set(R);for(let p of Y)O.set(l[p],d[p].offset);yr(O),await Bun.write(e,O)}function cs(e){let n=new Uint8Array(q);n.set(K,0);let i=new DataView(n.buffer);i.setUint16(8,Oe,!0),i.setUint16(10,q,!0),i.setUint32(12,e.rowCount,!0),i.setUint32(16,e.fileSize,!0),i.setUint8(20,e.cepPrefixOffsetWidth),i.setUint8(21,e.municipalityIdWidth),i.setUint8(22,Pe),i.setUint8(23,H),i.setUint16(24,Y.length,!0),i.setUint32(28,e.municipalityCount,!0);for(let[c,u]of Y.entries()){let l=e.sections[u],d=ze+c*8;i.setUint32(d,l.offset,!0),i.setUint32(d+4,l.length,!0)}return n}function us(e,n){return e.query(`SELECT count(*) AS count FROM ${Tt(n)}`).get().count}function*ei(e,n){let i=e.query(`
|
|
6
6
|
SELECT cep, logradouro, complemento, bairro_id, localidade_nome, municipio, municipio_cod_ibge, uf, nome, localidade_situacao, localidade_tipo
|
|
7
|
-
FROM ${
|
|
7
|
+
FROM ${Tt(n)}
|
|
8
8
|
ORDER BY cep
|
|
9
|
-
`);try{for(let r of n.iterate())yield r}finally{n.finalize()}}function Qo(e){if(!e.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(C))return{};let n=e.query(`SELECT key, value FROM ${rt(C)}`).all();return Object.fromEntries(n.map((r)=>[r.key,r.value]))}function Sr(e,t){return t===null?0:se(e,t,"string")}function se(e,t,n){let r=e.ids.get(t);if(r===void 0)throw Error(`Missing binary ${n} dictionary value: ${t}`);return r}function nt(e,t){if(t!==null)e.add(t)}function Xo(e,t){let n=Math.min(e.byteLength,t.byteLength),r=0;while(r<n&&e[r]===t[r])r++;return r}function nn(e,t){let n=t>>>3;e[n]=(e[n]??0)|1<<(t&7)}function Ko(e,t){let n=new Uint8Array(e.length*t);for(let r=0;r<e.length;r++)T(n,r*t,e[r]??0,t);return n}function on(e){if(!/^\d{8}$/.test(e))throw Error(`Invalid CEP in SQLite database: ${e}`);return Number(e)}function Jo(){let e=new Uint16Array([1]);if(new Uint8Array(e.buffer)[0]!==1)throw Error("Binary database generation requires a little-endian platform")}function St(e,t){if(!Number.isSafeInteger(e)||e<0||e>$n)throw Error(`Binary ${t} exceeds the uint32 limit: ${e}`)}function Dt(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function rt(e){return`"${e.replaceAll('"','""')}"`}class S 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 ea=/[\s,;]/;function qe(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,c=e.charCodeAt(t-2)-48,l=e.charCodeAt(t-1)-48;if((n|r|i|o|a|s|c|l|9-n|9-r|9-i|9-o|9-a|9-s|9-c|9-l)<0)return Number.NaN;return n*1e7+r*1e6+i*1e5+o*1e4+a*1000+s*100+c*10+l}function Ir(e){let t=e.trim(),n=qe(t);if(Number.isNaN(n))return;return String(n).padStart(8,"0")}async function*Ar(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 S("input-file-not-found",`Arquivo de entrada com CEPs n\xE3o encontrado: ${t}`);for(let i of e)yield i;if(r){yield*Dr(r.stream());return}if(!e.length&&!n)yield*Dr(Bun.stdin.stream())}async function*Dr(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(!ea.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 ba,readFileSync as $r,renameSync as ha,rmSync as Ct,statSync as ya,writeFileSync as ga}from"fs";import{homedir as vr}from"os";import{join as at,resolve as un}from"path";import{stat as fa}from"fs/promises";import{extname as ma,resolve as pa}from"path";import{fileURLToPath as ia}from"url";import{Buffer as ta}from"buffer";var Rr=new WeakMap,na=new TextDecoder;function ra(e,t){let n=new Uint8Array(ie),r=new Uint32Array(ie*2);for(let a=0;a<n.length;a++)n[a]=e.getUint8(t.symbolsOffset+a);for(let a=0;a<r.length;a++)r[a]=e.getUint32(t.symbolsOffset+ie+a*4,!0);let i=ta.alloc(272),o={lengths:n,words:r,output:i,view:new DataView(i.buffer,i.byteOffset,i.byteLength)};return Rr.set(t,o),o}function Tr(e,t,n,r){let{lengths:i,words:o,output:a,view:s}=Rr.get(n)??ra(t,n),c=r-1,l=c>>>x,u=n.suffixDataOffset+t.getUint32(n.blockOffsetsOffset+l*4,!0),d=0;for(let f=l*M;f<=c;f++){let m=n.lengthWidth===1?e[n.lengthsOffset+f]:t.getUint16(n.lengthsOffset+f*2,!0),b=u+m,h=e[n.prefixesOffset+f];while(u<b){let y=e[u++];if(y===255)a[h++]=e[u++];else s.setUint32(h,o[y*2],!0),s.setUint32(h+4,o[y*2+1],!0),h+=i[y]}d=h}return na.decode(a.subarray(0,d))}var xr=new TextDecoder,Br=Le();async function an(e){try{if(!await Bun.file(e).exists())return!1;let t=new Uint8Array(await Bun.file(e).slice(0,k.length).arrayBuffer());return kn(t)}catch(t){throw new Ye(e,{cause:t})}}class je{bairroCache;data;decodeScratch=new Uint8Array(255);dictionaries;bairros;bairroRuns;localityRuns;logradouroIdBits;header;mapped;metadataValue;municipalityCache;constructor(e=ia(new URL("../data/dne.bin",import.meta.url))){let t;try{t=Bun.mmap(e,{shared:!1})}catch(n){throw new Ye(e,{cause:n})}try{let n=new DataView(t.buffer,t.byteOffset,t.byteLength);oa(n),nr(t);let r=aa(n),i=sa(n,r),o=ca(n,r,i),a=qn(n,r.sections.bairroIds,r.rowCount,o.idWidth),s=Yn(n,r.sections.municipalityIds,r.rowCount),c=la(t,r.sections.metadata);this.mapped=t,this.data=n,this.header=r,this.dictionaries=i,this.bairros=o,this.bairroRuns=a,this.localityRuns=s,this.logradouroIdBits=$e(i.logradouro.count),this.metadataValue=Object.freeze(c),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 ee)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){this.assertOpen();let t=this.findCepIndex(e);return t===-1?void 0:this.readRow(t,e.replace("-",""))}queryMunicipality(e){if(this.assertOpen(),!Number.isInteger(e)||e<1e6||e>9999999)return;let t=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,n=this.header.sections.municipalities.offset,r=0,i=this.header.municipalityCount-1;while(r<=i){let o=r+(i-r>>>1),a=this.readPackedInteger(n+o*t,3);if(a<e)r=o+1;else if(a>e)i=o-1;else{let{municipio:s,uf:c}=this.readMunicipality(o+1);return{municipio:s,uf:c}}}return}queryMunicipalityCodesByUf(e){if(this.assertOpen(),!Object.hasOwn(oe,e))return[];let t=oe[e]*1e5,n=t+1e5,r=3+this.dictionaries.municipio.idWidth+this.dictionaries.uf.idWidth,i=this.header.sections.municipalities.offset,o=0,a=this.header.municipalityCount;while(o<a){let c=o+(a-o>>>1);if(this.readPackedInteger(i+c*r,3)<t)o=c+1;else a=c}let s=[];for(let c=o;c<this.header.municipalityCount;c++){let l=this.readPackedInteger(i+c*r,3);if(l>=n)break;s.push(l)}return s}queryNeighborhood(e){this.assertOpen();let t=this.findNeighborhoodIndex(e);return t===0?void 0:this.readNeighborhood(t)}queryNeighborhoodByCep(e){this.assertOpen();let t=this.findCepIndex(e);if(t===-1)return;let n=this.readNeighborhoodIndex(t);return n===0?void 0:this.readNeighborhood(n)}queryNeighborhoodCepRanges(e){this.assertOpen();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),a=[];for(let s=i;s<o;s++){let c=this.readUint32(r.offset+s*8),l=this.readUint32(r.offset+s*8+4);a.push({cep_inicial:String(c).padStart(8,"0"),cep_final:String(l).padStart(8,"0")})}return a}rowCount(){return this.header.rowCount}assertOpen(){if(this.data===null)throw new bt}findCepIndex(e){let t=qe(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),c=s;while(a<c){let l=a+(c-a>>>1);if(this.readPacked10(l)<r)a=l+1;else c=l}if(a>=s||this.readPacked10(a)!==r)return-1;return a}findNeighborhoodIndex(e){if(!z(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){return Vn(this.data,this.bairroRuns,e)}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 c=this.readRequiredDictionaryString(this.dictionaries.bairro,this.readPackedInteger(o,this.dictionaries.bairro.idWidth));o+=this.dictionaries.bairro.idWidth;let l=this.readDictionaryString(this.dictionaries.bairroAbreviado,this.readPackedInteger(o,this.dictionaries.bairroAbreviado.idWidth));o+=this.dictionaries.bairroAbreviado.idWidth;let u=this.readRequiredDictionaryString(this.dictionaries.uf,this.readPackedInteger(o,this.dictionaries.uf.idWidth));return{bairro_id:a,localidade_id:s,nome:c,nome_abreviado:l,uf:u}}readRow(e,t){let n=this.header.sections,r=Qn(this.data,this.localityRuns,e),i=this.readPackedInteger(this.localityRuns.idsOffset+r*this.header.municipalityIdWidth,this.header.municipalityIdWidth),o=this.readMunicipality(i),a=this.data.getUint8(n.localidadeFlags.offset+r),s=We[a&3],c=Pe[a>>>2],l=this.readNeighborhoodIndex(e),u=this.readSparseId(n.localidadeNomeBitmap,n.localidadeNomeRanks,n.localidadeNomeIds,e,this.dictionaries.bairro.idWidth),d=l===0?u:this.readPackedInteger(this.bairros.recordsOffset+(l-1)*this.bairros.recordWidth+this.bairros.originalIdWidth+this.bairros.localidadeIdWidth,this.dictionaries.bairro.idWidth);return{bairro:this.readCachedDictionaryString(this.dictionaries.bairro,d,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:s,localidade_tipo:c,logradouro:this.readDictionaryString(this.dictionaries.logradouro,yt(this.data,n.logradouroIds.offset,e,this.logradouroIdBits)),municipio:o.municipio,municipio_cod_ibge:o.codigoIbge,nome:this.readDictionaryString(this.dictionaries.nome,this.readSparseId(n.nomeBitmap,n.nomeRanks,n.nomeIds,e,this.dictionaries.nome.idWidth)),uf:o.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),uf:this.readRequiredDictionaryString(this.dictionaries.uf,o)};return this.municipalityCache[e]=a,a}readSparseId(e,t,n,r,i){let o=this.mapped,a=r>>>3,s=o[e.offset+a],c=r&7;if((s&1<<c)===0)return 0;let l=r>>>fe,u=this.readUint32(t.offset+l*4),d=l*(W>>>3);for(let f=d;f<a;f++)u+=Br[o[e.offset+f]];return u+=Br[s&(1<<c)-1],this.readPackedInteger(n.offset+u*i,i)}readDictionaryString(e,t){if(t===0)return null;let n=this.mapped;if(e.codec===re)return Tr(n,this.data,e,t);let r=t-1,i=r>>>x,o=i<<x,a=this.readUint32(e.blockOffsetsOffset+i*4),s=e.suffixDataOffset+a,c=this.decodeScratch,l=0;for(let u=o;u<=r;u++){let d=n[e.lengthsOffset+u],f=n[e.prefixesOffset+u],m=d-f;c.set(n.subarray(s,s+m),f),s+=m,l=d}return xr.decode(c.subarray(0,l))}readCachedDictionaryString(e,t,n){if(t===0)return null;let r=n[t];if(r!==void 0)return r;let i=this.readRequiredDictionaryString(e,t);return n[t]=i,i}readRequiredDictionaryString(e,t){return this.readDictionaryString(e,t)}readPacked10(e){let t=this.mapped,n=this.header.sections.cepSuffixes,r=e*ne,i=r>>>3,o=r&7,a=n.offset+i;return(t[a]|t[a+1]<<8|t[a+2]<<16)>>>o&1023}readPackedInteger(e,t){return R(this.data,e,t)}readUint32(e){return this.data.getUint32(e,!0)}}function oa(e){if(e.byteLength<O+P)throw new p("Binary database header is truncated");for(let n=0;n<k.length;n++)if(e.getUint8(n)!==k[n])throw new p("Invalid binary database magic");let t=e.getUint16(8,!0);if(t!==te)throw new pt(t,te);if(e.getUint16(10,!0)!==O)throw new p("Unsupported binary database header size");if(e.getUint8(22)!==fe||e.getUint8(23)!==x)throw new p("Unsupported binary database block layout");if(e.getUint16(24,!0)!==F.length)throw new p("Unsupported binary database section table");if(e.getUint32(16,!0)!==e.byteLength)throw new p(`Binary database size mismatch: header=${e.getUint32(16,!0)}, actual=${e.byteLength}`)}function aa(e){let t={};for(let[n,r]of F.entries()){let i=xe+n*8;t[r]={length:e.getUint32(i+4,!0),offset:e.getUint32(i,!0)}}return{cepPrefixOffsetWidth:e.getUint8(20),fileSize:e.getUint32(16,!0),municipalityCount:e.getUint32(28,!0),municipalityIdWidth:e.getUint8(21),rowCount:e.getUint32(12,!0),sections:t}}function sa(e,t){return{bairro:ge(e,t.sections.bairroDictionary),bairroAbreviado:ge(e,t.sections.bairroAbreviadoDictionary),complemento:ge(e,t.sections.complementoDictionary),logradouro:ge(e,t.sections.logradouroDictionary),municipio:ge(e,t.sections.municipioDictionary),nome:ge(e,t.sections.nomeDictionary),uf:ge(e,t.sections.ufDictionary)}}function ge(e,t){let n=e.getUint32(t.offset,!0),r=t.offset+e.getUint32(t.offset+16,!0);return{blockCount:e.getUint32(t.offset+4,!0),blockOffsetsOffset:t.offset+e.getUint32(t.offset+8,!0),count:n,codec:e.getUint8(t.offset+30),idWidth:e.getUint8(t.offset+28),lengthsOffset:t.offset+e.getUint32(t.offset+12,!0),lengthWidth:e.getUint8(t.offset+31)===2?2:1,prefixesOffset:r,region:t,suffixDataLength:e.getUint32(t.offset+24,!0),suffixDataOffset:t.offset+e.getUint32(t.offset+20,!0),symbolsOffset:r+n}}function ca(e,t,n){let r=t.sections.bairros,i=e.getUint32(r.offset,!0),o=e.getUint8(r.offset+4),a=e.getUint8(r.offset+5),s=o+a+n.bairro.idWidth+n.bairroAbreviado.idWidth+n.uf.idWidth;return{count:i,idWidth:B(i),originalIdWidth:o,localidadeIdWidth:a,recordsOffset:r.offset+G,recordWidth:s}}function la(e,t){return JSON.parse(xr.decode(e.subarray(t.offset,t.offset+t.length)))}import{Database as da}from"bun:sqlite";class X extends Error{constructor(e,t){super(e,t);this.name=new.target.name}}class it extends X{path;code="IO_ERROR";constructor(e,t){super(`Unable to access SQLite database: ${e}`,t);this.path=e}}class ot extends X{code="INVALID_SCHEMA";constructor(e,t){super(e,t)}}class It extends X{code="INVALID_DATA";constructor(e,t){super(e,t)}}class At extends X{code="QUERY_ERROR";constructor(e,t){super(e,t)}}class Rt extends X{code="READER_CLOSED";constructor(){super("SQLite database is closed")}}function ua(e){return Cr(e,", ")}function Or(e){return Cr(e,`,
|
|
10
|
-
`)}function
|
|
11
|
-
`))return`CREATE TABLE IF NOT EXISTS ${
|
|
12
|
-
${
|
|
13
|
-
)${
|
|
9
|
+
`);try{for(let c of i.iterate())yield c}finally{i.finalize()}}function ls(e){if(!e.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(Z))return{};let i=e.query(`SELECT key, value FROM ${Tt(Z)}`).all();return Object.fromEntries(i.map((c)=>[c.key,c.value]))}function ti(e,n){return n===null?0:be(e,n,"string")}function be(e,n,i){let c=e.ids.get(n);if(c===void 0)throw Error(`Missing binary ${i} dictionary value: ${n}`);return c}function ht(e,n){if(n!==null)e.add(n)}function ds(e,n){let i=Math.min(e.byteLength,n.byteLength),c=0;while(c<i&&e[c]===n[c])c++;return c}function mn(e,n){let i=n>>>3;e[i]=(e[i]??0)|1<<(n&7)}function fs(e,n){let i=new Uint8Array(e.length*n);for(let c=0;c<e.length;c++)F(i,c*n,e[c]??0,n);return i}function hn(e){if(!/^\d{8}$/.test(e))throw Error(`Invalid CEP in SQLite database: ${e}`);return Number(e)}function As(){let e=new Uint16Array([1]);if(new Uint8Array(e.buffer)[0]!==1)throw Error("Binary database generation requires a little-endian platform")}function qt(e,n){if(!Number.isSafeInteger(e)||e<0||e>ir)throw Error(`Binary ${n} exceeds the uint32 limit: ${e}`)}function Zt(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Tt(e){return`"${e.replaceAll('"','""')}"`}import{mkdirSync as ms,readFileSync as li,renameSync as Ss,rmSync as Kt,statSync as hs,writeFileSync as Ts}from"fs";import{homedir as si}from"os";import{join as Nt,resolve as Dn}from"path";import{stat as Os}from"fs/promises";import{extname as ps,resolve as Is}from"path";import{Database as Rs}from"bun:sqlite";class Ae extends Error{constructor(e,n){super(e,n);this.name=new.target.name}}class bt extends Ae{path;code="IO_ERROR";constructor(e,n){super(`Unable to access SQLite database: ${e}`,n);this.path=e}}class gt extends Ae{code="INVALID_SCHEMA";constructor(e,n){super(e,n)}}class zt extends Ae{code="INVALID_DATA";constructor(e,n){super(e,n)}}class Dt extends Ae{code="QUERY_ERROR";constructor(e,n){super(e,n)}}class Qt extends Ae{code="READER_CLOSED";constructor(){super("SQLite database is closed")}}function Es(e){return ri(e,", ")}function ni(e){return ri(e,`,
|
|
10
|
+
`)}function ri(e,n){let i=e.columns.filter((l)=>l.primaryKey).map((l)=>M(l.name)),c=e.columns.map((l)=>{let d=[M(l.name),l.type];if(l.notNull||l.primaryKey)d.push("NOT NULL");if(l.check)d.push(`CHECK (${l.check})`);if(l.references)d.push(`REFERENCES ${M(l.references.table)} (${M(l.references.column)})`);if(l.comment)d.push(`/* ${l.comment} */`);return d.join(" ")});if(i.length)c.push(`PRIMARY KEY (${i.join(", ")})`);let u=e.withoutRowid??e.unifiedTable?" WITHOUT ROWID":"";if(n.includes(`
|
|
11
|
+
`))return`CREATE TABLE IF NOT EXISTS ${M(e.name)} (
|
|
12
|
+
${c.join(n)}
|
|
13
|
+
)${u}`;return`CREATE TABLE IF NOT EXISTS ${M(e.name)} (${c.join(n)})${u}`}function Ge(e){return`${e}_consulta`}function Tn(e,n=Te){return`CREATE VIEW ${M(Ge(e))} AS
|
|
14
14
|
SELECT d.cep, d.logradouro, d.complemento, COALESCE(b.nome, d.localidade_nome) AS bairro,
|
|
15
15
|
d.municipio, d.municipio_cod_ibge, d.uf, d.nome, d.localidade_situacao, d.localidade_tipo
|
|
16
|
-
FROM ${
|
|
17
|
-
LEFT JOIN ${
|
|
18
|
-
SELECT b.* FROM ${
|
|
19
|
-
JOIN ${
|
|
16
|
+
FROM ${M(e)} d
|
|
17
|
+
LEFT JOIN ${M(n)} b ON b.bairro_id = d.bairro_id`}function Xt(e,n){let i=_e(n),c=n.find((l)=>l.originalName==="bairros");if(!c)throw Error("Neighborhood table definition is missing");let u=It(n);e.run(`DROP VIEW IF EXISTS main.${M(Ge(i.name))}`);for(let l of[...u].reverse())e.run(`DROP TABLE IF EXISTS main.${M(l.name)}`);for(let l of u)e.run(Es(l));e.run(Tn(i.name,c.name))}function M(e){return`"${e.replaceAll('"','""')}"`}class Jt{databasePath;db;closed=!1;normalizedSchemaReady=!1;cepStatement;neighborhoodStatement;neighborhoodByCepStatement;neighborhoodCepRangesStatement;constructor(e){this.databasePath=e;let n;try{n=new Rs(e,{readonly:!0}),n.run("PRAGMA busy_timeout = 30000"),this.db=n}catch(i){try{n?.close()}catch{}throw new bt(e,{cause:i})}}close(){if(this.closed)return;try{this.db.close(!0),this.cepStatement=void 0,this.neighborhoodStatement=void 0,this.neighborhoodByCepStatement=void 0,this.neighborhoodCepRangesStatement=void 0,this.closed=!0}catch(e){throw new bt(this.databasePath,{cause:e})}}[Symbol.dispose](){this.close()}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(Z))return;let e=this.db.query(`SELECT key, value FROM ${M(Z)}`).all();return Object.fromEntries(e.map((n)=>[n.key,n.value]))})}queryCep(e){return this.readSafely(()=>{let n=st(e);if(Number.isNaN(n))return;this.requireCurrentSchema(),this.cepStatement??=this.db.prepare(`SELECT * FROM ${M(Ge(z))} WHERE cep = ?`);let i=this.cepStatement.get(e.length===8?e:`${e.slice(0,5)}${e.slice(6)}`);if(!i)return;if(i.localidade_situacao===void 0||i.localidade_tipo===void 0)throw new gt("Database schema lacks locality indicators. Rebuild the database with build --force.");let c=ot[i.localidade_situacao],u=it[rt.indexOf(i.localidade_tipo)];if(c===void 0||u===void 0)throw new zt("Database contains invalid locality indicators. Rebuild the database with build --force.");return{...i,localidade_situacao:c,localidade_tipo:u}})}queryNeighborhood(e){return this.readSafely(()=>{if(!oe(e))return;return this.requireCurrentSchema(),this.neighborhoodStatement??=this.db.prepare(`SELECT * FROM ${M(Te)} WHERE bairro_id = ?`),this.neighborhoodStatement.get(e)??void 0})}queryNeighborhoodByCep(e){return this.readSafely(()=>{if(Number.isNaN(st(e)))return;return this.requireCurrentSchema(),this.neighborhoodByCepStatement??=this.db.prepare(`
|
|
18
|
+
SELECT b.* FROM ${M(z)} d
|
|
19
|
+
JOIN ${M(Te)} b ON b.bairro_id = d.bairro_id
|
|
20
20
|
WHERE d.cep = ?
|
|
21
|
-
`).get(e.replace("-",""))??void 0})}queryNeighborhoodCepRanges(e){return this.readSafely(()=>{if(!
|
|
22
|
-
SELECT cep_inicial, cep_final FROM ${
|
|
21
|
+
`),this.neighborhoodByCepStatement.get(e.replace("-",""))??void 0})}queryNeighborhoodCepRanges(e){return this.readSafely(()=>{if(!oe(e))return[];return this.requireCurrentSchema(),this.neighborhoodCepRangesStatement??=this.db.prepare(`
|
|
22
|
+
SELECT cep_inicial, cep_final FROM ${M(St)}
|
|
23
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(
|
|
25
|
-
`)}catch(
|
|
26
|
-
`)}function dn(e){let t=K(e);if(t===":memory:")throw new S("invalid-cron-database","O agendamento exige um caminho persistente para a base.",2);if(/[\r\n\0]/.test(t))throw new S("invalid-cron-database","O caminho da base n\xE3o pode conter quebras de linha ou bytes nulos.",2);return t}function Sa(e){if(/[\r\n\0]/.test(e))throw new S("invalid-cron-source","A fonte n\xE3o pode conter quebras de linha ou bytes nulos.",2);return Da(e)?e:un(e)}function Hr(e){return`konstit-dne-${new Bun.CryptoHasher("sha256").update(e).digest("hex").slice(0,32)}`}function Lt(e){let t=Hr(e),n=Bun.env.XDG_STATE_HOME?un(Bun.env.XDG_STATE_HOME):process.platform==="darwin"?at(vr(),"Library","Application Support"):at(vr(),".local","state"),r=at(n,"konstit-dne","cron");return{directory:r,metadata:at(r,`${t}.json`),runner:at(r,`${t}.mjs`),title:t}}function qr(e){let t=Lt(e);if(!_e(t.metadata)&&!_e(t.runner))return null;if(!_e(t.metadata)||!_e(t.runner))throw new S("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${t.title}' est\xE1 incompleta.`);try{let n=JSON.parse($r(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:ae}}catch{throw new S("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${t.title}' \xE9 inv\xE1lida.`)}}function jr(e){return Bun.cron.parse(e)?.toISOString()??null}function ln(e,t){let n=`${e}.${process.pid}.${crypto.randomUUID()}.tmp`;try{ga(n,t,{mode:384}),ha(n,e)}finally{Ct(n,{force:!0})}}function Mr(e){return _e(e)?$r(e,"utf8"):null}function Fr(e,t){if(t===null)Ct(e,{force:!0});else ln(e,t)}function _e(e){try{return ya(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 Da(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Vr(e){return e instanceof Error?e.message:String(e)}class Se extends Error{constructor(e){super(e);this.name="DneSourceQualityError"}}class fn{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++,zr(n.rejectionReasons,i),zr(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 Se(`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]=Yr(s);n[r]={...Yr(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={...Gr(),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=Gr(),n.files.set(t,r);return r}}function Gr(){return{read:0,accepted:0,rejected:0,rejectionReasons:new Map}}function zr(e,t){e.set(t,(e.get(t)??0)+1)}function Yr(e){return{read:e.read,accepted:e.accepted,rejected:e.rejected,rejection_reasons:Object.fromEntries(e.rejectionReasons)}}import{Database as Ia}from"bun:sqlite";import{mkdirSync as pn,readFileSync as Aa,renameSync as Ra,rmSync as Nt,statSync as bn,writeFileSync as Qr}from"fs";import{tmpdir as Ta}from"os";import{basename as Ba,dirname as mn,join as ct}from"path";var xa=30000,Oa=50,Ca=["SIGHUP","SIGINT","SIGTERM"];async function Xr(e,t){let n=La(e),r=ct(mn(e),`.${Ba(e)}.fetch.lock`),i={pid:process.pid,token:crypto.randomUUID()},o=performance.now()+xa,a=!1;pn(mn(e),{recursive:!0}),pn(mn(n),{mode:448,recursive:!0});while(Na(r)){if(Zr(r))continue;await u()}while(!Ua(n,i)){if(Zr(n))continue;await u()}if(a)t.finish();let s=!1,c=()=>{if(s)return;s=!0,l(),Fa(n,i.token)},l=$a(c);return{release:c};async function u(){if(!a)t("Aguardando outra atualiza\xE7\xE3o da base"),a=!0;if(performance.now()>=o)throw new S("update-in-progress",`Outra execu\xE7\xE3o de build j\xE1 est\xE1 atualizando a base '${e}'.`);await Bun.sleep(Oa)}}function La(e){let t=new Bun.CryptoHasher("sha256").update(e).digest("hex");return ct(Ta(),`konstit-dne-${process.getuid?.()??"unknown"}`,`fetch-${t}.lock`)}function Na(e){try{return bn(e),!0}catch(t){if(st(t))return!1;throw t}}function Ua(e,t){let n=`${e}.${t.pid}.${t.token}.tmp`;pn(n);try{return Qr(ct(n,"owner.json"),JSON.stringify(t),{flag:"wx"}),Ra(n,e),!0}catch(r){if(hn(r))return!1;throw r}finally{Nt(n,{force:!0,recursive:!0})}}function Zr(e){let t;try{t=bn(e)}catch(r){if(st(r))return!0;throw r}if(!t.isDirectory())return va(e);let n=Kr(e);if(n&&Ma(n.pid))return!1;try{Qr(ct(e,"reaper.json"),JSON.stringify({pid:process.pid,token:crypto.randomUUID()}),{flag:"wx"})}catch(r){if(hn(r))return!1;if(st(r))return!0;throw r}return Nt(e,{force:!0,recursive:!0}),!0}function va(e){let t=new Ia(e);try{t.run("PRAGMA busy_timeout = 0"),t.run("BEGIN IMMEDIATE"),t.run("ROLLBACK")}catch(n){if(ka(n))return!1;throw n}finally{t.close()}try{return Nt(e,{force:!0}),!0}catch(n){if(st(n))return!0;if(hn(n))return!1;try{if(bn(e).isDirectory())return!1}catch(r){if(st(r))return!0;throw r}throw n}}function Kr(e){try{let t=JSON.parse(Aa(ct(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 Ma(e){try{return process.kill(e,0),!0}catch(t){return!(t&&typeof t==="object"&&("code"in t)&&t.code==="ESRCH")}}function Fa(e,t){if(Kr(e)?.token===t)Nt(e,{force:!0,recursive:!0})}function $a(e){let t=()=>e(),n=Ca.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 hn(e){return yn(e,"EACCES","EEXIST","ENOTEMPTY","EPERM")}function st(e){return yn(e,"ENOENT")}function yn(e,...t){return Boolean(e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&t.includes(e.code))}function ka(e){if(yn(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 Jr(){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 As,rm as Rs}from"fs/promises";import{tmpdir as Ts}from"os";import{join as _n}from"path";import{mkdir as Pa,rename as Wa,rm as Ha}from"fs/promises";import{basename as vt,dirname as qa,join as ii}from"path";var oi="Delimitado",ai="latin1",Lu=new TextDecoder(ai),ja=32,Va=20,Ga=10,za=16,Ya=30,Za=28,Ut=46,Qa=33639248,Xa=42,Ka=24,Ja=0,es=8,En=22,ts=101010256,ns=65535,si=En+ns,rs=16,is=12,os=28,as=26,ei=30,ss=67324752;class gn{path;files;constructor(e){this.path=e;this.files=Array.from(new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0})).sort()}matchingFiles(e){return di(this.files,e)}async*readLines(e){yield*mi(Bun.file(ii(this.path,e)).stream())}}class ci{path;files;entriesByFile;constructor(e,t){this.path=e;this.files=t.map((n)=>vt(n.name)).sort(),this.entriesByFile=new Map(t.map((n)=>[vt(n.name),n]))}matchingFiles(e){return di(this.files,e)}async*readLines(e){let t=this.entriesByFile.get(e);if(!t)throw Error(`DNE data file not found: ${e}`);yield*mi(fi(this.path,t))}}function li(e,t){if(!ni(e))return null;let n=new gn(e);if(!wn(n,t))return n;let r=ii(e,oi);if(!ni(r))return null;let i=new gn(r);return wn(i,t)?null:i}async function ui(e,t,n){let r=await ri(e),i=us(r);if(i)return await ps(e,i,n),ti(n,await ri(n),t);return ti(e,r,t)}function ti(e,t,n){let r=cs(t,n),i=new ci(e,r);return ls(i,r,n),i}function cs(e,t){return e.filter((n)=>ds(n.name,t))}function ls(e,t,n){if(!t.length)throw Error("ZIP file does not contain DNE Basico files");let r=wn(e,n);if(r)throw Error(`DNE data file not found: ${r}`)}function us(e){return e.find((t)=>{let n=vt(t.name).toLowerCase();return n.startsWith("edne_basico_")&&n.endsWith(".zip")})}function ni(e){try{return new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0}).next(),!0}catch{return!1}}function wn(e,t){for(let n of t){let r=et(n);if(r&&e.matchingFiles(r).length===0)return r}return null}function di(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 ds(e,t){let n=e.toLowerCase();if(!n.startsWith(`${oi.toLowerCase()}/`))return!1;let r=vt(n);return t.some((i)=>{let o=et(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 ri(e){let t=Bun.file(e),n=t.size;if(n<En)throw Error("Source is not a valid ZIP file");let r=Math.max(0,n-si),i=Buffer.from(await t.slice(r,n).arrayBuffer()),o=ms(i),a=i.readUInt32LE(o+is),s=i.readUInt32LE(o+rs),c=s+a;if(c>n)throw Error("Invalid ZIP central directory range");let l=Buffer.from(await t.slice(s,c).arrayBuffer());return fs(l)}function fs(e){let t=[],n=0;while(n<e.length){if(n+Ut>e.length||e.readUInt32LE(n)!==Qa)throw Error("Invalid ZIP central directory entry");let r=e.readUInt16LE(n+Ga),i=e.readUInt32LE(n+za),o=e.readUInt32LE(n+Va),a=e.readUInt32LE(n+Ka),s=e.readUInt16LE(n+Za),c=e.readUInt16LE(n+Ya),l=e.readUInt16LE(n+ja),u=e.readUInt32LE(n+Xa),d=Ut+s+c+l;if(n+d>e.length)throw Error("Invalid ZIP central directory entry size");let f=e.subarray(n+Ut,n+Ut+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 ms(e){for(let t=e.length-En;t>=Math.max(0,e.length-si);t--)if(e.readUInt32LE(t)===ts)return t;throw Error("Source is not a valid ZIP file")}async function*fi(e,t){let n=Bun.file(e),r=t.localHeaderOffset+ei,i=Buffer.from(await n.slice(t.localHeaderOffset,r).arrayBuffer());if(i.length!==ei||i.readUInt32LE(0)!==ss)throw Error(`Invalid ZIP local header for ${t.name}`);let o=i.readUInt16LE(as),a=i.readUInt16LE(os),s=r+o+a,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===Ja)u=l;else if(t.compression===es)u=l.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}`);bs(t,f)}async function ps(e,t,n){if(await Bun.file(n).exists())return;await Pa(qa(n),{recursive:!0});let r=`${n}.${process.pid}.${crypto.randomUUID()}.tmp`,i=Bun.file(r).writer(),o=!1;try{for await(let a of fi(e,t))await i.write(a);await i.end(),o=!0;try{await Wa(r,n)}catch(a){if(!await Bun.file(n).exists())throw a}}finally{if(!o)await Promise.resolve(i.end()).catch(()=>{});await Ha(r,{force:!0})}}async function*mi(e){let t=new TextDecoder(ai),n="";for await(let r of e){let i=n+t.decode(r,{stream:!0}),o=0,a=i.indexOf(`
|
|
27
|
-
`);while(
|
|
28
|
-
`,o)}n=i.slice(o)}if(n+=t.decode(),n.endsWith("\r"))n=n.slice(0,-1);if(n)yield n}function bs(e,t){if(t!==e.crc32)throw Error(`CRC32 mismatch for ${e.name}`)}import{open as hi}from"fs/promises";class lt extends Error{constructor(e){super(e)}}async function yi(e,t,n,r={}){let i=ws(n.contentLength);if(!gs(n.acceptRanges)||i===null){await pi(e,t,r);return}try{await hs(e,t,i,r)}catch(o){if(!(o instanceof lt))throw o;await pi(e,t,r)}}async function hs(e,t,n,r){let i=Math.ceil(n/_t),o=await hi(t,"w"),a=new AbortController,s=wi(r.signal,a.signal);try{await o.truncate(n);let c=0,l=Array.from({length:Math.min(i,pr)},async()=>{while(!0){let u=c++;if(u>=i)return;let d=u*_t,f=Math.min(d+_t,n)-1;await ys(e,o,{start:d,end:f},n,{...r,signal:s})}});try{await Promise.all(l)}catch(u){throw a.abort(),await Promise.allSettled(l),u}}finally{await o.close()}}async function ys(e,t,n,r,i){await ut(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 lt(`Server ignored byte range ${n.start}-${n.end}`);throw Error(`Failed to download ${e}: ${o.status}`)}let a=Es(o.headers.get("content-range"));if(!a||a.start!==n.start||a.end!==n.end||a.length!==r)throw await o.body?.cancel(),new lt(`Server returned an invalid Content-Range for ${n.start}-${n.end}`);let s=new Uint8Array(await o.arrayBuffer()),c=n.end-n.start+1;if(s.byteLength!==c)throw new lt(`Server returned ${s.byteLength} bytes for range ${n.start}-${n.end}; expected ${c}`);await gi(t,s,n.start)},i)}async function pi(e,t,n){let r=await hi(t,"w");try{await ut(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 gi(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 ut(e,t,n,r={}){let i=r.timeoutMs??br,o=r.maxRetries??hr,a=r.retryBaseDelayMs??yr,s=r.retryMaxDelayMs??gr,c=r.retryAfterMaxMs??wr,l;for(let u=0;;u++){Ei(r.signal);let d=AbortSignal.timeout(i),f=wi(r.signal,d);try{let m=await fetch(e,{...t,signal:f,verbose:!1});if(_s(m.status)&&u<o){let b=Ds(m.headers.get("retry-after"),u,a,s,c);await m.body?.cancel(),await bi(b,r.signal);continue}l=await n(m);break}catch(m){if(r.signal?.aborted)throw r.signal.reason??m;if(u>=o||!Ss(m))throw m;let b=Math.min(a*2**u,s);await bi(b,r.signal)}}return l}async function gi(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 gs(e){return e?.split(",").some((t)=>t.trim().toLowerCase()==="bytes")??!1}function ws(e){if(e===null||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function Es(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 _s(e){return e===408||e===425||e===429||e>=500&&e<=599}function Ss(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 Ds(e,t,n,r,i){let o=Is(e);if(o!==null)return Math.min(o,i);return Math.min(n*2**t,r)}function Is(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 wi(e,t){return e?AbortSignal.any([e,t]):t}function Ei(e){if(e?.aborted)throw e.reason??new DOMException("The operation was aborted","AbortError")}async function bi(e,t){if(e<=0){Ei(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 Mt{source;options;tempDir;constructor(e,t={}){this.source=e;this.options=t}async resolve(e){try{return await this.resolveSource(this.source??ae,e)}catch(t){throw await this.cleanup(),t}}async cleanup(){if(this.tempDir)await Rs(this.tempDir,{recursive:!0,force:!0}),this.tempDir=void 0}async getTempDir(){return this.tempDir??=await As(_n(Ts(),"edne")),this.tempDir}async resolveSource(e,t){let n=e;if(xs(e))n=await this.download(e);if(await Bun.file(n).exists()){this.progress("Preparando a fonte ZIP");let i=_n(await this.getTempDir(),"edne-inner.zip"),o=await ui(n,t,i);return this.progress("Fonte ZIP pronta"),o}this.progress("Lendo a fonte do diret\xF3rio");let r=li(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=_n(n,"edne-download.zip");return this.progress("Baixando o arquivo DNE"),await yi(e,r,t),r}progress(e){this.options.onProgress?.(e)}}async function Ft(e,t={}){try{return await ut(e,{method:"HEAD"},async(n)=>{if(!n.ok)throw Error(`Failed to inspect DNE from ${e}: ${n.status}`);return _i(e,n.headers)},t)}catch{return await ut(e,{headers:{"accept-encoding":"identity",range:"bytes=0-0"}},async(n)=>{let r=Bs(e,n);if(await n.body?.cancel(),!n.ok)throw Error(`Failed to inspect DNE from ${e}: ${n.status}`);return r},t)}}function _i(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 Bs(e,t){let n=_i(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 xs(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}import{Database as Ns}from"bun:sqlite";async function De(e,t,n,r,i){let o=et(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 c=r.counter(e.originalName,s);if(t.readText){let l=await t.readText(s);Cs(l,(u,d)=>{c.read(),i(Di(l,u,d,n),s,c)});continue}for await(let l of t.readLines(s))c.read(),i(Os(l,n),s,c)}}function Os(e,t){return Di(e,0,e.length,t)}function Di(e,t,n,r){let i=Array.from({length:r.length},()=>null),o=0,a=0,s=t;for(let c=t;c<=n;c++){if(c!==n&&e.charCodeAt(c)!==64)continue;if(a===r[o]){if(i[o]=Ls(e,s,c),o++,o===r.length)break}a++,s=c+1}return i}function Cs(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 Ls(e,t,n){if(t===n)return null;let r=e.charCodeAt(t),i=e.charCodeAt(n-1),o=Si(r)||Si(i)?e.slice(t,n).trim():e.slice(t,n);return o===""?null:o}function Si(e){return e<=32||e===160}class Sn{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 ${
|
|
24
|
+
`),this.neighborhoodCepRangesStatement.all(e)})}requireCurrentSchema(){if(!this.normalizedSchemaReady)this.normalizedSchemaReady=Boolean(this.db.query("SELECT 1 FROM sqlite_master WHERE type = 'view' AND name = ?").get(Ge(z)))&&this.hasTable(Te)&&this.hasTable(St);if(!this.normalizedSchemaReady)throw new gt("Database schema lacks normalized neighborhoods. Rebuild the database with build --force.")}rowCount(e){return this.readSafely(()=>this.db.query(`SELECT count(*) AS count FROM ${M(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,n){return this.readSafely(()=>{if(!Number.isSafeInteger(n)||n<=0)throw new Dt("SQL row limit must be a positive safe integer.");let i=[],c=!1,u=this.db.query(e);try{for(let l of u.iterate()){if(i.length===n){c=!0;break}i.push(l)}}finally{u.finalize()}return{rows:i,truncated:c}})}readSafely(e){if(this.closed)throw new Qt;try{return e()}catch(n){if(n instanceof Ae)throw n;throw new Dt(n instanceof Error?n.message:String(n),{cause:n})}}}function ii(e){if(!e.startsWith("sqlite:///")){if(e.includes("://"))throw Error("Only sqlite:/// database URLs are supported");return e}return e.slice(10)}function ae(e,n){let i=ii(e);if(i===":memory:")return i;return Is(n==="binary"?`${i.slice(0,i.length-ps(i).length)}.bin`:i)}async function yt(e,n=z){if(e===":memory:"||!await Bun.file(e).exists())throw new w("database-not-found",`Base n\xE3o encontrada: ${e}`);let i;try{i=await On(e)?new he(e):new Jt(e)}catch(u){throw new w("database-invalid",`N\xE3o foi poss\xEDvel abrir a base '${e}': ${ai(u)}`)}if(!(i instanceof he?n===z:i.hasTable(n)))throw i.close(),new w("database-not-ready",`A base '${e}' n\xE3o cont\xE9m a tabela '${n}'. Execute bunx @konstit/dne build --source CAMINHO_OU_URL primeiro.`);return i}async function $e(e,n=z){if(e===":memory:"||!await Bun.file(e).exists())return bn(e);let i=null;try{i=(await Os(e)).size}catch{}try{let c=await On(e),u=c?new he(e):new Jt(e);try{let l=u instanceof he,d=l?n===z:u.hasTable(n);return{exists:!0,format:c?"binary":"sqlite",metadata:u.metadata()??null,path:e,ready:d,row_count:d?l?u.rowCount():u.rowCount(n):null,schema:d&&!l?u.tableSchema(n)??null:null,size_bytes:i}}finally{u.close()}}catch(c){return{...bn(e),error:ai(c),exists:!0,size_bytes:i}}}function oi(e){return{...bn(":memory:"),row_count:e}}function bn(e){return{exists:!1,format:null,metadata:null,path:e,ready:!1,row_count:null,schema:null,size_bytes:null}}function ai(e){return e instanceof Error?e.message:String(e)}async function di(e){let n=yn(e.database),i=Ri(n),c=ys(e.source),u=bs(e.expression,n,c,e.packageVersion),l=e.dryRun?"preview":i?"updated":"installed";if(!e.dryRun)await gs(u,i);return{...u,next_run:Oi(u.expression),status:l}}function fi(e){let n=yn(e),i=Ei(n),c=Ri(n);return{command:c?.command??null,database:n,expression:c?.expression??null,id:i,installed:c!==null,next_run:c?Oi(c.expression):null,package_version:c?.package_version??null,runner:c?.runner??null,source:c?.source??null,title:i}}async function Ai(e){let n=yn(e),i=en(n),c=ke(i.metadata)||ke(i.runner);try{await Bun.cron.remove(i.title)}catch(u){throw new w("cron-remove-failed",`N\xE3o foi poss\xEDvel remover o agendamento: ${pi(u)}`)}return Kt(i.metadata,{force:!0}),Kt(i.runner,{force:!0}),{database:n,id:i.title,removed:c,title:i.title}}function bs(e,n,i,c){let u=Bun.which("bunx");if(!u)throw new w("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(u))throw new w("invalid-cron-value","A express\xE3o cron e o caminho do bunx n\xE3o podem conter quebras de linha ou bytes nulos.",2);let l=en(n),d=Dn(u),A=`@konstit/dne@${c}`;return{command:[Yt(d),Yt(A),"build","--db",Yt(n),"--source",Yt(i),"--quiet"].join(" "),database:n,expression:e,id:l.title,package_version:c,runner:l.runner,source:i,title:l.title}}async function gs(e,n){let i=en(e.database);ms(i.directory,{mode:448,recursive:!0});let c=ci(i.runner),u=ci(i.metadata);try{gn(i.runner,Ds(e)),await Bun.cron(i.runner,e.expression,e.title),gn(i.metadata,`${JSON.stringify(e,null,2)}
|
|
25
|
+
`)}catch(l){ui(i.runner,c),ui(i.metadata,u);try{if(n)await Bun.cron(n.runner,n.expression,n.title);else await Bun.cron.remove(e.title)}catch{}throw new w("cron-install-failed",`N\xE3o foi poss\xEDvel instalar o agendamento: ${pi(l)}`)}}function Ds(e){let n=[Bun.which("bunx"),`@konstit/dne@${e.package_version}`,"build","--db",e.database,"--source",e.source,"--quiet"];if(n[0]===null)throw new w("bunx-not-found","O execut\xE1vel bunx n\xE3o foi encontrado.");return[`const command = ${JSON.stringify(n)};`,"","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 yn(e){let n=ae(e);if(n===":memory:")throw new w("invalid-cron-database","O agendamento exige um caminho persistente para a base.",2);if(/[\r\n\0]/.test(n))throw new w("invalid-cron-database","O caminho da base n\xE3o pode conter quebras de linha ou bytes nulos.",2);return n}function ys(e){if(/[\r\n\0]/.test(e))throw new w("invalid-cron-source","A fonte n\xE3o pode conter quebras de linha ou bytes nulos.",2);return Ns(e)?e:Dn(e)}function Ei(e){return`konstit-dne-${new Bun.CryptoHasher("sha256").update(e).digest("hex").slice(0,32)}`}function en(e){let n=Ei(e),i=Bun.env.XDG_STATE_HOME?Dn(Bun.env.XDG_STATE_HOME):process.platform==="darwin"?Nt(si(),"Library","Application Support"):Nt(si(),".local","state"),c=Nt(i,"konstit-dne","cron");return{directory:c,metadata:Nt(c,`${n}.json`),runner:Nt(c,`${n}.mjs`),title:n}}function Ri(e){let n=en(e);if(!ke(n.metadata)&&!ke(n.runner))return null;if(!ke(n.metadata)||!ke(n.runner))throw new w("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${n.title}' est\xE1 incompleta.`);try{let i=JSON.parse(li(n.metadata,"utf8"));if(i.database!==e||i.id!==n.title||i.title!==n.title||i.runner!==n.runner||typeof i.command!=="string"||typeof i.expression!=="string"||typeof i.package_version!=="string")throw Error("invalid cron metadata");return Bun.cron.parse(i.expression),{...i,source:typeof i.source==="string"?i.source:null}}catch{throw new w("cron-config-invalid",`A configura\xE7\xE3o do agendamento '${n.title}' \xE9 inv\xE1lida.`)}}function Oi(e){return Bun.cron.parse(e)?.toISOString()??null}function gn(e,n){let i=`${e}.${process.pid}.${crypto.randomUUID()}.tmp`;try{Ts(i,n,{mode:384}),Ss(i,e)}finally{Kt(i,{force:!0})}}function ci(e){return ke(e)?li(e,"utf8"):null}function ui(e,n){if(n===null)Kt(e,{force:!0});else gn(e,n)}function ke(e){try{return hs(e),!0}catch(n){if(n&&typeof n==="object"&&"code"in n&&n.code==="ENOENT")return!1;throw n}}function Yt(e){return`'${e.replaceAll("'","'\\''")}'`}function Ns(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function pi(e){return e instanceof Error?e.message:String(e)}class He extends Error{constructor(e){super(e);this.name="DneSourceQualityError"}}class Nn{stages;constructor(){this.stages=new Map}counter(e,n){let i=this.stage(e),c=this.file(e,n);return{read(){i.read++,c.read++},accept(){i.accepted++,c.accepted++},reject(u){i.rejected++,c.rejected++,mi(i.rejectionReasons,u),mi(c.rejectionReasons,u)}}}assertValid(){let e=Array.from(this.stages.values()).reduce((c,u)=>c+u.rejected,0);if(!e)return;let n=new Map;for(let c of this.stages.values())for(let[u,l]of c.rejectionReasons)n.set(u,(n.get(u)??0)+l);let i=Array.from(n).map(([c,u])=>`${c}=${u}`).join(", ");throw new He(`DNE source quality validation failed: ${e} rejected row(s) (${i})`)}report(e){let n={read:0,accepted:0,rejected:0},i={};for(let[c,u]of this.stages){n.read+=u.read,n.accepted+=u.accepted,n.rejected+=u.rejected;let l={};for(let[d,A]of u.files)l[d]=Si(A);i[c]={...Si(u),files:l}}return{version:1,status:"passed",output_rows:e,totals:n,stages:i}}stage(e){let n=this.stages.get(e);if(!n)n={...Ii(),files:new Map},this.stages.set(e,n);return n}file(e,n){let i=this.stage(e),c=i.files.get(n);if(!c)c=Ii(),i.files.set(n,c);return c}}function Ii(){return{read:0,accepted:0,rejected:0,rejectionReasons:new Map}}function mi(e,n){e.set(n,(e.get(n)??0)+1)}function Si(e){return{read:e.read,accepted:e.accepted,rejected:e.rejected,rejection_reasons:Object.fromEntries(e.rejectionReasons)}}import{Database as Cs}from"bun:sqlite";import{mkdirSync as Ln,readFileSync as Ls,renameSync as ws,rmSync as tn,statSync as wn,writeFileSync as Ti}from"fs";import{tmpdir as Ms}from"os";import{basename as Us,dirname as Cn,join as Lt}from"path";var Ps=30000,Bs=50,_s=["SIGHUP","SIGINT","SIGTERM"];async function bi(e,n){let i=xs(e),c=Lt(Cn(e),`.${Us(e)}.fetch.lock`),u={pid:process.pid,token:crypto.randomUUID()},l=performance.now()+Ps,d=!1;Ln(Cn(e),{recursive:!0}),Ln(Cn(i),{mode:448,recursive:!0});while(Vs(c)){if(hi(c))continue;await O()}while(!Fs(i,u)){if(hi(i))continue;await O()}if(d)n.finish();let A=!1,E=()=>{if(A)return;A=!0,R(),$s(i,u.token)},R=ks(E);return{release:E};async function O(){if(!d)n("Aguardando outra atualiza\xE7\xE3o da base"),d=!0;if(performance.now()>=l)throw new w("update-in-progress",`Outra execu\xE7\xE3o de build j\xE1 est\xE1 atualizando a base '${e}'.`);await Bun.sleep(Bs)}}function xs(e){let n=new Bun.CryptoHasher("sha256").update(e).digest("hex");return Lt(Ms(),`konstit-dne-${process.getuid?.()??"unknown"}`,`fetch-${n}.lock`)}function Vs(e){try{return wn(e),!0}catch(n){if(Ct(n))return!1;throw n}}function Fs(e,n){let i=`${e}.${n.pid}.${n.token}.tmp`;Ln(i);try{return Ti(Lt(i,"owner.json"),JSON.stringify(n),{flag:"wx"}),ws(i,e),!0}catch(c){if(Mn(c))return!1;throw c}finally{tn(i,{force:!0,recursive:!0})}}function hi(e){let n;try{n=wn(e)}catch(c){if(Ct(c))return!0;throw c}if(!n.isDirectory())return vs(e);let i=gi(e);if(i&&Gs(i.pid))return!1;try{Ti(Lt(e,"reaper.json"),JSON.stringify({pid:process.pid,token:crypto.randomUUID()}),{flag:"wx"})}catch(c){if(Mn(c))return!1;if(Ct(c))return!0;throw c}return tn(e,{force:!0,recursive:!0}),!0}function vs(e){let n=new Cs(e);try{n.run("PRAGMA busy_timeout = 0"),n.run("BEGIN IMMEDIATE"),n.run("ROLLBACK")}catch(i){if(Hs(i))return!1;throw i}finally{n.close()}try{return tn(e,{force:!0}),!0}catch(i){if(Ct(i))return!0;if(Mn(i))return!1;try{if(wn(e).isDirectory())return!1}catch(c){if(Ct(c))return!0;throw c}throw i}}function gi(e){try{let n=JSON.parse(Ls(Lt(e,"owner.json"),"utf8"));return Number.isInteger(n.pid)&&Number(n.pid)>0&&typeof n.token==="string"?{pid:Number(n.pid),token:n.token}:null}catch{return null}}function Gs(e){try{return process.kill(e,0),!0}catch(n){return!(n&&typeof n==="object"&&("code"in n)&&n.code==="ESRCH")}}function $s(e,n){if(gi(e)?.token===n)tn(e,{force:!0,recursive:!0})}function ks(e){let n=()=>e(),i=_s.map((c)=>{let u=()=>{e(),process.kill(process.pid,c)};return process.once(c,u),{handler:u,signal:c}});return process.once("exit",n),()=>{process.off("exit",n);for(let{handler:c,signal:u}of i)process.off(u,c)}}function Mn(e){return Un(e,"EACCES","EEXIST","ENOTEMPTY","EPERM")}function Ct(e){return Un(e,"ENOENT")}function Un(e,...n){return Boolean(e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&n.includes(e.code))}function Hs(e){if(Un(e,"SQLITE_BUSY","SQLITE_LOCKED"))return!0;let n=e instanceof Error?e.message:String(e);return/database is locked|database table is locked/i.test(n)}async function Di(){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{mkdir as Ws,rename as js,rm as qs}from"fs/promises";import{basename as rn,dirname as Zs,join as wi}from"path";var Mi="Delimitado",Ui="latin1",Kd=new TextDecoder(Ui),zs=32,Qs=20,Xs=10,Js=16,Ys=30,Ks=28,nn=46,ec=33639248,tc=42,nc=24,rc=0,ic=8,_n=22,oc=101010256,ac=65535,Pi=_n+ac,sc=16,cc=12,uc=28,lc=26,yi=30,dc=67324752;class Pn{path;files;constructor(e){this.path=e;this.files=Array.from(new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0})).sort()}matchingFiles(e){return vi(this.files,e)}async*readLines(e){yield*$i(Bun.file(wi(this.path,e)).stream())}}class Bi{path;files;entriesByFile;constructor(e,n){this.path=e;this.files=n.map((i)=>rn(i.name)).sort(),this.entriesByFile=new Map(n.map((i)=>[rn(i.name),i]))}matchingFiles(e){return vi(this.files,e)}async*readLines(e){let n=this.entriesByFile.get(e);if(!n)throw Error(`DNE data file not found: ${e}`);yield*$i(Gi(this.path,n))}}function _i(e,n){if(!Ci(e))return null;let i=new Pn(e);if(!Bn(i,n))return i;let c=wi(e,Mi);if(!Ci(c))return null;let u=new Pn(c);return Bn(u,n)?null:u}async function xi(e,n,i){let c=await Li(e),u=Fi(c),l;if(u)await Rc(e,u,i),l=Ni(i,await Li(i),n);else l=Ni(e,c,n);return l.zipEntries=xn(c,n),l}function Ni(e,n,i){let c=Vi(n,i),u=new Bi(e,c);return fc(u,c,i),u}function Vi(e,n){return e.filter((i)=>Ac(i.name,n))}function fc(e,n,i){if(!n.length)throw Error("ZIP file does not contain DNE Basico files");let c=Bn(e,i);if(c)throw Error(`DNE data file not found: ${c}`)}function Fi(e){return e.find((n)=>{let i=rn(n.name).toLowerCase();return i.startsWith("edne_basico_")&&i.endsWith(".zip")})}function xn(e,n){let i=Fi(e);return(i?[i]:Vi(e,n)).map((c)=>({name:c.name,size:c.uncompressedSize,crc32:c.crc32.toString(16).padStart(8,"0")})).sort((c,u)=>c.name<u.name?-1:c.name>u.name?1:0)}function Ci(e){try{return new Bun.Glob("*").scanSync({cwd:e,onlyFiles:!0}).next(),!0}catch{return!1}}function Bn(e,n){for(let i of n){let c=mt(i);if(c&&e.matchingFiles(c).length===0)return c}return null}function vi(e,n){if(!n.includes("*"))return e.filter((u)=>u===n);let[i="",c=""]=n.split("*",2);return e.filter((u)=>u.startsWith(i)&&u.endsWith(c))}function Ac(e,n){let i=e.toLowerCase();if(!i.startsWith(`${Mi.toLowerCase()}/`))return!1;let c=rn(i);return n.some((u)=>{let l=mt(u)?.toLowerCase();if(!l)return!1;if(!l.includes("*"))return c===l;let[d="",A=""]=l.split("*",2);return c.startsWith(d)&&c.endsWith(A)})}async function Li(e){let n=Bun.file(e),i=n.size;if(i<_n)throw Error("Source is not a valid ZIP file");let c=Math.max(0,i-Pi),u=Buffer.from(await n.slice(c,i).arrayBuffer()),l=Ec(u),d=u.readUInt32LE(l+cc),A=u.readUInt32LE(l+sc),E=A+d;if(E>i)throw Error("Invalid ZIP central directory range");let R=Buffer.from(await n.slice(A,E).arrayBuffer());return Vn(R)}function Vn(e,n){let i=[],c=0,u=0;while(c<e.length){if(c+nn>e.length||e.readUInt32LE(c)!==ec)throw Error("Invalid ZIP central directory entry");let l=e.readUInt16LE(c+Xs),d=e.readUInt32LE(c+Js),A=e.readUInt32LE(c+Qs),E=e.readUInt32LE(c+nc),R=e.readUInt16LE(c+Ks),O=e.readUInt16LE(c+Ys),p=e.readUInt16LE(c+zs),I=e.readUInt32LE(c+tc),m=nn+R+O+p;if(c+m>e.length)throw Error("Invalid ZIP central directory entry size");let S=e.subarray(c+nn,c+nn+R).toString("utf8");if(!S.endsWith("/"))i.push({name:S,flags:e.readUInt16LE(c+8),disk:e.readUInt16LE(c+34),compression:l,crc32:d,compressedSize:A,uncompressedSize:E,localHeaderOffset:I});c+=m,u++}if(n!==void 0&&u!==n)throw Error("Invalid ZIP central directory entry count");return i}function Ec(e){for(let n=e.length-_n;n>=Math.max(0,e.length-Pi);n--)if(e.readUInt32LE(n)===oc)return n;throw Error("Source is not a valid ZIP file")}async function*Gi(e,n){let i=Bun.file(e),c=n.localHeaderOffset+yi,u=Buffer.from(await i.slice(n.localHeaderOffset,c).arrayBuffer());if(u.length!==yi||u.readUInt32LE(0)!==dc)throw Error(`Invalid ZIP local header for ${n.name}`);let l=u.readUInt16LE(lc),d=u.readUInt16LE(uc),A=c+l+d,E=A+n.compressedSize;if(E>i.size)throw Error(`Invalid ZIP data range for ${n.name}`);let R=i.slice(A,E).stream(),O;if(n.compression===rc)O=R;else if(n.compression===ic)O=R.pipeThrough(new DecompressionStream("deflate-raw"));else throw Error(`Unsupported ZIP compression method ${n.compression} for ${n.name}`);let p=0,I=0;for await(let m of O)p+=m.byteLength,I=Bun.hash.crc32(m,I),yield m;if(n.uncompressedSize&&p!==n.uncompressedSize)throw Error(`Invalid decompressed size for ${n.name}`);Oc(n,I)}async function Rc(e,n,i){if(await Bun.file(i).exists())return;await Ws(Zs(i),{recursive:!0});let c=`${i}.${process.pid}.${crypto.randomUUID()}.tmp`,u=Bun.file(c).writer(),l=!1;try{for await(let d of Gi(e,n))await u.write(d);await u.end(),l=!0;try{await js(c,i)}catch(d){if(!await Bun.file(i).exists())throw d}}finally{if(!l)await Promise.resolve(u.end()).catch(()=>{});await qs(c,{force:!0})}}async function*$i(e){let n=new TextDecoder(Ui),i="";for await(let c of e){let u=i+n.decode(c,{stream:!0}),l=0,d=u.indexOf(`
|
|
27
|
+
`);while(d!==-1){let A=d>l&&u.charCodeAt(d-1)===13?d-1:d;if(A>l)yield u.slice(l,A);l=d+1,d=u.indexOf(`
|
|
28
|
+
`,l)}i=u.slice(l)}if(i+=n.decode(),i.endsWith("\r"))i=i.slice(0,-1);if(i)yield i}function Oc(e,n){if(n!==e.crc32)throw Error(`CRC32 mismatch for ${e.name}`)}import{open as Wi}from"fs/promises";class wt extends Error{constructor(e){super(e)}}async function ji(e,n,i,c={}){let u=Sc(i.contentLength);if(!mc(i.acceptRanges)||u===null){await ki(e,n,c);return}try{await pc(e,n,u,c)}catch(l){if(!(l instanceof wt))throw l;await ki(e,n,c)}}async function pc(e,n,i,c){let u=Math.ceil(i/jt),l=await Wi(n,"w"),d=new AbortController,A=Zi(c.signal,d.signal);try{await l.truncate(i);let E=0,R=Array.from({length:Math.min(u,Zr)},async()=>{while(!0){let O=E++;if(O>=u)return;let p=O*jt,I=Math.min(p+jt,i)-1;await Ic(e,l,{start:p,end:I},i,{...c,signal:A})}});try{await Promise.all(R)}catch(O){throw d.abort(),await Promise.allSettled(R),O}}finally{await l.close()}}async function Ic(e,n,i,c,u){await We(e,{headers:{"accept-encoding":"identity",range:`bytes=${i.start}-${i.end}`}},async(l)=>{if(l.status!==206){if(await l.body?.cancel(),l.ok)throw new wt(`Server ignored byte range ${i.start}-${i.end}`);throw Error(`Failed to download ${e}: ${l.status}`)}let d=hc(l.headers.get("content-range"));if(!d||d.start!==i.start||d.end!==i.end||d.length!==c)throw await l.body?.cancel(),new wt(`Server returned an invalid Content-Range for ${i.start}-${i.end}`);let A=new Uint8Array(await l.arrayBuffer()),E=i.end-i.start+1;if(A.byteLength!==E)throw new wt(`Server returned ${A.byteLength} bytes for range ${i.start}-${i.end}; expected ${E}`);await qi(n,A,i.start)},u)}async function ki(e,n,i){let c=await Wi(n,"w");try{await We(e,{},async(u)=>{if(!u.ok)throw await u.body?.cancel(),Error(`Failed to download ${e}: ${u.status}`);if(!u.body)throw Error(`Failed to stream ${e}: empty response body`);await c.truncate(0);let l=u.body.getReader(),d=0;try{while(!0){let A=await l.read();if(A.done)break;await qi(c,A.value,d),d+=A.value.byteLength}}catch(A){throw await l.cancel().catch(()=>{}),A}finally{l.releaseLock()}},i)}finally{await c.close()}}async function We(e,n,i,c={}){let u=c.timeoutMs??zr,l=c.maxRetries??Qr,d=c.retryBaseDelayMs??Xr,A=c.retryMaxDelayMs??Jr,E=c.retryAfterMaxMs??Yr,R;for(let O=0;;O++){zi(c.signal);let p=AbortSignal.timeout(u),I=Zi(c.signal,p);try{let m=await fetch(e,{...n,signal:I,verbose:!1});if(Tc(m.status)&&O<l){let S=gc(m.headers.get("retry-after"),O,d,A,E);await m.body?.cancel(),await Hi(S,c.signal);continue}R=await i(m);break}catch(m){if(c.signal?.aborted)throw c.signal.reason??m;if(O>=l||!bc(m))throw m;let S=Math.min(d*2**O,A);await Hi(S,c.signal)}}return R}async function qi(e,n,i){let c=0;while(c<n.byteLength){let u=await e.write(n,c,n.byteLength-c,i+c);if(!u.bytesWritten)throw Error("Failed to write downloaded content");c+=u.bytesWritten}}function mc(e){return e?.split(",").some((n)=>n.trim().toLowerCase()==="bytes")??!1}function Sc(e){if(e===null||!/^\d+$/.test(e))return null;let n=Number(e);return Number.isSafeInteger(n)?n:null}function hc(e){let n=e?/^bytes (\d+)-(\d+)\/(\d+)$/i.exec(e):null;if(!n?.[1]||!n[2]||!n[3])return null;return{start:Number(n[1]),end:Number(n[2]),length:Number(n[3])}}function Tc(e){return e===408||e===425||e===429||e>=500&&e<=599}function bc(e){if(!(e instanceof Error))return!1;if(e.name==="AbortError"||e.name==="TimeoutError"||e instanceof TypeError)return!0;let n="code"in e&&typeof e.code==="string"?e.code:void 0;return n==="ECONNRESET"||n==="ECONNREFUSED"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="ETIMEDOUT"||n==="EAI_AGAIN"}function gc(e,n,i,c,u){let l=Dc(e);if(l!==null)return Math.min(l,u);return Math.min(i*2**n,c)}function Dc(e){if(e===null)return null;let n=e.trim();if(/^\d+(?:\.\d+)?$/.test(n))return Number(n)*1000;let i=Date.parse(n);return Number.isNaN(i)?null:Math.max(0,i-Date.now())}function Zi(e,n){return e?AbortSignal.any([e,n]):n}function zi(e){if(e?.aborted)throw e.reason??new DOMException("The operation was aborted","AbortError")}async function Hi(e,n){if(e<=0){zi(n);return}await new Promise((i,c)=>{let l=setTimeout(()=>{n?.removeEventListener("abort",d),i()},e),d=()=>{clearTimeout(l),c(n?.reason??new DOMException("The operation was aborted","AbortError"))};if(n?.addEventListener("abort",d,{once:!0}),n?.aborted)d()})}import{mkdtemp as yc,rm as Nc}from"fs/promises";import{tmpdir as Cc}from"os";import{join as Fn}from"path";class on{source;options;tempDir;constructor(e,n={}){this.source=e;this.options=n}async resolve(e){try{return await this.resolveSource(this.source,e)}catch(n){throw await this.cleanup(),n}}async cleanup(){if(this.tempDir)await Nc(this.tempDir,{recursive:!0,force:!0}),this.tempDir=void 0}async getTempDir(){return this.tempDir??=await yc(Fn(Cc(),"edne")),this.tempDir}async resolveSource(e,n){let i=e;if(wc(e))i=await this.download(e);if(await Bun.file(i).exists()){this.progress("Preparando a fonte ZIP");let u=Fn(await this.getTempDir(),"edne-inner.zip"),l=await xi(i,n,u);return this.progress("Fonte ZIP pronta"),l}this.progress("Lendo a fonte do diret\xF3rio");let c=_i(i,n);if(c)return this.progress("Fonte do diret\xF3rio pronta"),c;throw Error(`DNE source not found: ${i}`)}async download(e){let n=this.options.remoteInfo??await Mt(e),i=await this.getTempDir(),c=Fn(i,"edne-download.zip");return this.progress("Baixando o arquivo DNE"),await ji(e,c,n),c}progress(e){this.options.onProgress?.(e)}}async function Mt(e,n={}){try{return await We(e,{method:"HEAD"},async(i)=>{if(!i.ok)throw Error(`Failed to inspect DNE from ${e}: ${i.status}`);return Qi(e,i.headers)},n)}catch{return await We(e,{headers:{"accept-encoding":"identity",range:"bytes=0-0"}},async(i)=>{let c=Lc(e,i);if(await i.body?.cancel(),!i.ok)throw Error(`Failed to inspect DNE from ${e}: ${i.status}`);return c},n)}}function Qi(e,n){return{url:e,lastModified:n.get("last-modified"),etag:n.get("etag"),contentLength:n.get("content-length"),acceptRanges:n.get("accept-ranges")}}function Lc(e,n){let i=Qi(e,n.headers);if(n.status!==206)return i;let c=/^bytes 0-0\/(\d+)$/i.exec(n.headers.get("content-range")??"");return{...i,contentLength:c?.[1]??null,acceptRanges:i.acceptRanges??"bytes"}}function wc(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}var Ut=22,Mc=Ut+65535,Uc=4194304;async function Ji(e,n,i={}){try{return await Pc(e,n,i)}catch(c){if(i.signal?.aborted)throw i.signal.reason??c;return{...await Mt(e,i),acceptRanges:null,zipEntries:null}}}async function Pc(e,n,i){let c=await vn(e,{suffix:Ut},i),u=Xi(c.bytes);if(u<0)c=await vn(e,{suffix:Mc},i),u=Xi(c.bytes);if(u<0)throw Error("Missing ZIP central directory trailer");let l=c.bytes.subarray(u),d=l.readUInt16LE(10),A=l.readUInt32LE(12),E=l.readUInt32LE(16),R=c.start+u;if(l.readUInt16LE(4)!==0||l.readUInt16LE(6)!==0||l.readUInt16LE(8)!==d||d===0||d===65535||A===0||A>Uc||E===4294967295||E+A!==R)throw Error("Unsupported ZIP central directory layout");let O=E>=c.start?c.bytes.subarray(E-c.start,E-c.start+A):(await vn(e,{start:E,end:E+A-1,total:c.total},i)).bytes,p=Vn(O,d);if(p.some((m)=>m.disk!==0||(m.flags&8257)!==0||m.compressedSize===4294967295||m.uncompressedSize===4294967295||m.localHeaderOffset+30+m.compressedSize>E||m.compression!==0&&m.compression!==8))throw Error("Unsupported ZIP entry layout");let I=xn(p,n);if(I.length===0||new Set(I.map((m)=>m.name)).size!==I.length)throw Error("Missing or ambiguous DNE ZIP entries");return{...c.info,zipEntries:I}}function Xi(e){for(let n=e.length-Ut;n>=0;n--)if(e.readUInt32LE(n)===101010256&&n+Ut+e.readUInt16LE(n+20)===e.length)return n;return-1}async function vn(e,n,i){let c="suffix"in n?`bytes=-${n.suffix}`:`bytes=${n.start}-${n.end}`;return We(e,{headers:{range:c,"accept-encoding":"identity"}},async(u)=>{try{let l=/^bytes (\d+)-(\d+)\/(\d+)$/i.exec(u.headers.get("content-range")??"");if(u.status!==206||!l)throw Error("ZIP range inspection is not supported");let d=Number(l[1]),A=Number(l[2]),E=Number(l[3]),R="suffix"in n?Math.max(0,E-n.suffix):n.start,O="suffix"in n?E-1:n.end,p=u.headers.get("content-encoding"),I=u.headers.get("content-length");if(!Number.isSafeInteger(E)||E<Ut||d!==R||A!==O||!("suffix"in n)&&E!==n.total||p!==null&&p!=="identity"||I!==null&&Number(I)!==A-d+1)throw Error("Invalid ZIP range response");let m=await Bc(u,A-d+1),S={url:e,etag:u.headers.get("etag"),lastModified:u.headers.get("last-modified"),contentLength:String(E),acceptRanges:"bytes"};return{bytes:m,start:d,total:E,info:S}}finally{await u.body?.cancel()}},i)}async function Bc(e,n){if(!e.body)throw Error("Empty ZIP range response");let i=e.body.getReader(),c=Buffer.alloc(n),u=0;try{while(!0){let l=await i.read();if(l.done)break;if(u+l.value.length>n)throw Error("Oversized ZIP range response");c.set(l.value,u),u+=l.value.length}if(u!==n)throw Error("Truncated ZIP range response");return c}finally{i.releaseLock()}}import{Database as Fc}from"bun:sqlite";async function je(e,n,i,c,u){let l=mt(e);if(!l)return;let d=n.matchingFiles(l);if(!d.length)throw Error(`DNE data file not found: ${l}`);for(let A of d){let E=c.counter(e.originalName,A);if(n.readText){let R=await n.readText(A);xc(R,(O,p)=>{E.read(),u(Ki(R,O,p,i),A,E)});continue}for await(let R of n.readLines(A))E.read(),u(_c(R,i),A,E)}}function _c(e,n){return Ki(e,0,e.length,n)}function Ki(e,n,i,c){let u=Array.from({length:c.length},()=>null),l=0,d=0,A=n;for(let E=n;E<=i;E++){if(E!==i&&e.charCodeAt(E)!==64)continue;if(d===c[l]){if(u[l]=Vc(e,A,E),l++,l===c.length)break}d++,A=E+1}return u}function xc(e,n){let i=0;for(let c=0;c<=e.length;c++){if(c!==e.length&&e.charCodeAt(c)!==10)continue;let u=c;if(u>i&&e.charCodeAt(u-1)===13)u--;if(u>i)n(i,u);i=c+1}}function Vc(e,n,i){if(n===i)return null;let c=e.charCodeAt(n),u=e.charCodeAt(i-1),l=Yi(c)||Yi(u)?e.slice(n,i).trim():e.slice(n,i);return l===""?null:l}function Yi(e){return e<=32||e===160}class Gn{db;tableName;batchSize;rows=[];statements=new Map;constructor(e,n,i){this.db=e;this.tableName=n;this.batchSize=i}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 n=Array.from({length:e.length*11},()=>null);for(let[i,c]of e.entries()){let u=i*11;for(let l=0;l<c.length;l++)n[u+l]=c[l]??null}this.statementFor(e.length).run(...n)}finalize(){for(let e of this.statements.values())e.finalize();this.statements.clear()}statementFor(e){let n=this.statements.get(e);if(n)return n;let i=Array.from({length:e},()=>"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").join(", ");return n=this.db.prepare(`
|
|
29
|
+
INSERT INTO ${M(this.tableName)}
|
|
30
30
|
(cep, logradouro, complemento, bairro_id, localidade_nome, municipio, municipio_cod_ibge, uf, nome, localidade_situacao, localidade_tipo)
|
|
31
|
-
VALUES ${
|
|
32
|
-
`),this.statements.set(e,
|
|
33
|
-
INSERT INTO ${
|
|
34
|
-
`);try{for(let
|
|
35
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
31
|
+
VALUES ${i}
|
|
32
|
+
`),this.statements.set(e,n),n}}class kn{schema;db;tableByOriginalName;unifiedTable;constructor(e,n){this.schema=n;this.db=new Fc(e),this.tableByOriginalName=new Map(n.map((i)=>[i.originalName,i])),this.unifiedTable=_e(n)}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,n={},i=()=>{}){let c=this.unifiedTable,u=new Nn;return this.configureBulkLoad(),await this.transaction(async()=>{Xt(this.db,this.schema),this.createMetadataTable(),this.db.run(`DELETE FROM ${M(Z)}`),i("Lendo munic\xEDpios");let l=await this.readLocalidades(e,u);i("Lendo bairros");let d=await this.readBairros(e,l,u);this.insertBairros(d),i("Carregando faixas de CEP dos bairros"),await this.insertFaixasBairro(e,d,u);let A=this.prepareUnifiedInsert(c.name);try{if(i("Carregando logradouros"),await this.insertLogradouros(e,A,l,d,u),i("Carregando munic\xEDpios"),this.insertLocalidades(A,l),this.insertLocalidadesSubordinadas(A,l),i("Carregando endere\xE7os especiais"),await this.insertCpcs(e,A,l,u),await this.insertGrandesUsuarios(e,A,l,d,u),await this.insertUnidadesOperacionais(e,A,l,d,u),u.assertValid(),!l.size)throw new He("DNE source quality validation failed: no accepted localidade rows");A.flush();let E=this.rowCount(c.name);if(!E)throw new He("DNE source quality validation failed: no CEP rows produced");let R=u.report(E);this.writeMetadata({...n,schema_version:pt,quality_report:JSON.stringify(R),quality_rows_accepted:String(R.totals.accepted),quality_rows_read:String(R.totals.read),quality_rows_rejected:String(R.totals.rejected)})}finally{A.finalize()}}),this.rowCount(c.name)}async readLocalidades(e,n){let i=this.originalTable("log_localidade"),c=new Map;await je(i,e,xe(i,["locNu","uf","nome","cep","situacao","tipo","locNuSub","munNu"]),n,(l,d,A)=>{let[E=null,R=null,O=null,p=null,I=null,m=null,S=null,h=null]=l,b=Bt([["locNu",E],["uf",R],["nome",O],["situacao",I],["tipo",m]]);if(b||!E||!R||!O){A.reject(b??"invalid_structure");return}if(!Pt(R)){A.reject("invalid_uf");return}if(p!==null&&!ct(p)){A.reject("invalid_cep");return}if(h!==null&&!Gc(h)){A.reject("invalid_ibge");return}if(I!=="0"&&I!=="1"&&I!=="2"&&I!=="3"){A.reject("invalid_localidade_situacao");return}let g=rt.find((D)=>D===m);if(!g){A.reject("invalid_localidade_tipo");return}if(c.has(E)){A.reject("duplicate_localidade");return}c.set(E,{uf:R,nome:O,cep:p,locNuSub:S,munNu:h===null?null:Number(h),situacao:Number(I),tipo:g,quality:A})});let u=new Map;for(let[l,d]of c){let A=d.locNuSub?c.get(d.locNuSub):void 0;if(d.locNuSub&&(!A||A.munNu===null)){d.quality.reject("missing_parent_localidade");continue}if(A&&A.uf!==d.uf){d.quality.reject("localidade_uf_mismatch");continue}if(!d.locNuSub&&d.munNu===null){d.quality.reject("missing_ibge");continue}u.set(l,d),d.quality.accept()}return u}async readBairros(e,n,i){let c=this.originalTable("log_bairro"),u=new Map;return await je(c,e,xe(c,["baiNu","uf","locNu","bairro","abreviado"]),i,(l,d,A)=>{let[E=null,R=null,O=null,p=null,I=null]=l,m=Bt([["baiNu",E],["uf",R],["locNu",O],["bairro",p]]);if(m||!E||!R||!O||!p){A.reject(m??"invalid_structure");return}let S=to(E);if(S===null||to(O)===null){A.reject("invalid_bairro_identifier");return}if(!Pt(R)){A.reject("invalid_uf");return}let h=n.get(O);if(!h){A.reject("missing_localidade");return}if(h.uf!==R){A.reject("bairro_uf_mismatch");return}if(u.has(E)){A.reject("duplicate_bairro");return}u.set(E,{id:S,uf:R,locNu:O,nome:p,abreviado:I}),A.accept()}),u}insertBairros(e){let n=this.originalTable("bairros"),i=this.db.prepare(`
|
|
33
|
+
INSERT INTO ${M(n.name)} (bairro_id, localidade_id, uf, nome, nome_abreviado) VALUES (?, ?, ?, ?, ?)
|
|
34
|
+
`);try{for(let c of e.values())i.run(c.id,Number(c.locNu),c.uf,c.nome,c.abreviado)}finally{i.finalize()}}async insertFaixasBairro(e,n,i){let c=this.originalTable("log_faixa_bairro"),u=this.originalTable("bairro_faixas"),l=new Set,d=this.db.prepare(`INSERT INTO ${M(u.name)} (bairro_id, cep_inicial, cep_final) VALUES (?, ?, ?)`);try{await je(c,e,xe(c,["baiNu","cepInicial","cepFinal"]),i,(A,E,R)=>{let[O=null,p=null,I=null]=A,m=O===null?void 0:n.get(O);if(!m){R.reject("missing_bairro");return}if(!ct(p)||!ct(I)){R.reject("invalid_cep_range");return}if(p>I){R.reject("reversed_cep_range");return}let S=`${m.id}:${p}:${I}`;if(l.has(S)){R.reject("duplicate_cep_range");return}l.add(S),d.run(m.id,p,I),R.accept()})}finally{d.finalize()}}prepareUnifiedInsert(e){return new Gn(this.db,e,qr)}rowCount(e){return this.db.query(`SELECT count(*) AS count FROM ${M(e)}`).get().count}async insertLogradouros(e,n,i,c,u){let l=this.originalTable("log_logradouro");await je(l,e,xe(l,["uf","locNu","baiNuIni","logNo","cep","tloTx","logStaTlo"]),u,(d,A,E)=>{let[R=null,O=null,p=null,I=null,m=null,S=null,h=null]=d,b=Bt([["uf",R],["locNu",O],["baiNuIni",p],["logNo",I],["cep",m]]);if(b||!R||!O||!p||!I||!m){E.reject(b??"invalid_structure");return}if(!Pt(R)){E.reject("invalid_uf");return}if(!ct(m)){E.reject("invalid_cep");return}if(h==="S"&&!S){E.reject("missing_tloTx");return}let g=i.get(O);if(!g){E.reject("missing_localidade");return}let D=c.get(p);if(!D){E.reject("missing_bairro");return}if(g.uf!==R||D.uf!==R){E.reject("logradouro_uf_mismatch");return}if(D.locNu!==O){E.reject("bairro_localidade_mismatch");return}let y=$n(g,i);if(!y){E.reject("missing_municipality");return}n.run(m,h==="S"?`${S} ${I}`:I,null,D.id,null,y.nome,y.munNu,R,null,g.situacao,g.tipo),E.accept()})}insertLocalidades(e,n){for(let i of n.values())if(i.cep&&i.locNuSub===null&&i.munNu!==null)e.run(i.cep,null,null,null,null,i.nome,i.munNu,i.uf,null,i.situacao,i.tipo)}insertLocalidadesSubordinadas(e,n){for(let i of n.values()){let c=i.locNuSub?n.get(i.locNuSub):void 0;if(i.cep&&c?.munNu!==null&&c?.munNu!==void 0)e.run(i.cep,null,null,null,i.nome,c.nome,c.munNu,i.uf,null,i.situacao,i.tipo)}}async insertCpcs(e,n,i,c){let u=this.originalTable("log_cpc");await je(u,e,xe(u,["uf","locNu","nome","endereco","cep"]),c,(l,d,A)=>{let[E=null,R=null,O=null,p=null,I=null]=l,m=Bt([["uf",E],["locNu",R],["nome",O],["endereco",p],["cep",I]]);if(m||!E||!R||!O||!p||!I){A.reject(m??"invalid_structure");return}if(!Pt(E)){A.reject("invalid_uf");return}if(!ct(I)){A.reject("invalid_cep");return}let S=i.get(R);if(!S){A.reject("missing_localidade");return}if(S.uf!==E){A.reject("cpc_uf_mismatch");return}let h=$n(S,i);if(!h){A.reject("missing_municipality");return}let[b,g]=eo(p);n.run(I,b,g,null,null,h.nome,h.munNu,E,O,S.situacao,S.tipo),A.accept()})}async insertGrandesUsuarios(e,n,i,c,u){await this.insertNamedAddresses(this.originalTable("log_grande_usuario"),e,n,i,c,u)}async insertUnidadesOperacionais(e,n,i,c,u){await this.insertNamedAddresses(this.originalTable("log_unid_oper"),e,n,i,c,u)}async insertNamedAddresses(e,n,i,c,u,l){await je(e,n,xe(e,["uf","locNu","baiNu","nome","endereco","cep"]),l,(d,A,E)=>{let[R=null,O=null,p=null,I=null,m=null,S=null]=d,h=Bt([["uf",R],["locNu",O],["baiNu",p],["nome",I],["endereco",m],["cep",S]]);if(h||!R||!O||!p||!I||!m||!S){E.reject(h??"invalid_structure");return}if(!Pt(R)){E.reject("invalid_uf");return}if(!ct(S)){E.reject("invalid_cep");return}let b=c.get(O);if(!b){E.reject("missing_localidade");return}let g=u.get(p);if(!g){E.reject("missing_bairro");return}if(b.uf!==R||g.uf!==R){E.reject("address_uf_mismatch");return}if(g.locNu!==O){E.reject("bairro_localidade_mismatch");return}let D=$n(b,c);if(!D){E.reject("missing_municipality");return}let[y,U]=eo(m);i.run(S,y,U,g.id,null,D.nome,D.munNu,R,I,b.situacao,b.tipo),E.accept()})}originalTable(e){let n=this.tableByOriginalName.get(e);if(!n)throw Error(`Table with original name '${e}' not found`);return n}configureBulkLoad(){this.db.run(`PRAGMA page_size = ${Wr}`),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 = ${jr}`)}createMetadataTable(){this.db.run(`
|
|
35
|
+
CREATE TABLE IF NOT EXISTS ${M(Z)} (
|
|
36
36
|
key TEXT PRIMARY KEY NOT NULL,
|
|
37
37
|
value TEXT NOT NULL
|
|
38
38
|
)
|
|
39
|
-
`)}writeMetadata(e){let
|
|
40
|
-
`),args:[
|
|
41
|
-
`);return}
|
|
39
|
+
`)}writeMetadata(e){let n=this.db.prepare(`INSERT INTO ${M(Z)} (key, value) VALUES (?, ?)`);try{for(let[i,c]of Object.entries(e))n.run(i,c)}finally{n.finalize()}}async transaction(e){this.db.run("BEGIN");try{await e(),this.db.run("COMMIT")}catch(n){throw this.db.run("ROLLBACK"),n}}}function eo(e){let n=e.indexOf(",");if(n===-1)return[e.trim(),null];return[e.slice(0,n).trim(),e.slice(n+1).trim()]}function to(e){return/^\d{1,8}$/.test(e)&&oe(Number(e))?Number(e):null}var vc=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 Pt(e){return e!==null&&vc.has(e)}function ct(e){return e!==null&&/^\d{8}$/.test(e)}function Gc(e){if(!/^\d{7}$/.test(e))return!1;let n=Number(e);return Number.isSafeInteger(n)&&n>0}function Bt(e){let n=e.find(([,i])=>i===null);return n?`missing_${n[0]}`:null}function $n(e,n){let i=e.locNuSub?n.get(e.locNuSub):e;if(!i||i.munNu===null)return null;return{nome:i.nome,munNu:i.munNu}}function no(e,n){if(e.schema_version!==pt||e.source_kind!=="remote"||e.source_url!==n.url||!n.zipEntries?.length)return!1;return e.source_zip_entries===JSON.stringify(n.zipEntries)}function ro(e,n,i){let c={loaded_at:new Date().toISOString(),package_version:i,schema_version:pt,source_input:e,source_kind:n||$c(e)?"remote":"local"};if(n){if(c.source_url=n.url,c.source_last_modified=n.lastModified??"",c.source_etag=n.etag??"",c.source_content_length=n.contentLength??"",n.zipEntries?.length)c.source_zip_entries=JSON.stringify(n.zipEntries)}return c}function $c(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}var zc="0 0 * * 5",Hn="\x1B[0m",Qc="\x1B[1m",Xc="\x1B[36m",Jc="\x1B[90m",Yc=/(--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$)|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:]]|[^\]])*]|\b(?:CREATE|TABLE|IF|NOT|EXISTS|TEXT|INTEGER|NULL|PRIMARY|KEY|WITHOUT|ROWID)\b)/gi,cn="pt-BR",Kc=new Intl.NumberFormat(cn),eu=new Intl.NumberFormat(cn,{maximumFractionDigits:1,minimumFractionDigits:1}),tu=new Intl.NumberFormat(cn,{maximumFractionDigits:1}),fo=1,ce=2,nu=3,un=await Di(),Ao=o("db",t.string,{default:Hr,describe:"Caminho da base; build bin\xE1rio usa a extens\xE3o .bin.",global:!0,valueHint:"file",valueName:"CAMINHO"}),Eo=a("json",{describe:"Gravar um envelope JSON est\xE1vel em stdout.",global:!0}),Ro=a("quiet",{describe:"Ocultar mensagens de progresso.",global:!0,short:"q"}),Oo=f("color"),ru=r(kr,{about:"Criar e consultar uma base local com os CEPs do Brasil.",afterHelp:["Exemplos:"," bunx @konstit/dne build --db ./dne.db --source ./eDNE_Basico.zip"," bunx @konstit/dne build --format binary --source ./eDNE_Basico.zip"," bunx @konstit/dne build-search-index --db ./dne.bin"," bunx @konstit/dne get 01001-000 --db ./dne.db"," bunx @konstit/dne status --db ./dne.db"," bunx @konstit/dne cron install --db ./dne.db --source https://example.com/eDNE_Basico.zip"].join(`
|
|
40
|
+
`),args:[Ao,Eo,Ro,Oo],version:un,subcommands:[r("build",{args:[o("format",t.enum(["sqlite","binary"]),{default:"sqlite",describe:"Formato da base de sa\xEDda.",valueName:"sqlite|binary"}),o("source",t.string,{required:!0,describe:"Diret\xF3rio DNE, arquivo ZIP ou URL.",valueName:"CAMINHO|URL",env:"EDNE_SOURCE_URL"}),a("force",{describe:"Ignorar metadados de atualiza\xE7\xE3o e recriar a base."}),a("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,n)=>su(e,se(n))}),r("build-search-index",{about:"Construir o \xEDndice de autocomplete de uma base bin\xE1ria existente",args:[o("output",t.string,{describe:"Caminho do \xEDndice; padr\xE3o: <base>.search.bin, ao lado da base.",valueName:"CAMINHO",valueHint:"file"})],handler:(e,n)=>lu(e,se(n))}),r("get",{args:[s("input",t.string,{describe:"Um ou mais CEPs.",repeatable:!0,valueName:"CEP"}),o("file",t.string,{describe:"Ler CEPs de um arquivo. Use - para stdin.",valueHint:"file",valueName:"CAMINHO"}),a("jsonl",{describe:"Gravar um resultado JSON por linha."})],about:"Consultar um ou mais CEPs",handler:(e,n)=>uu(e,se(n))}),r("status",{about:"Exibir tamanho, registros, estado do esquema e metadados da fonte",handler:(e,n)=>du(se(n))}),r("schema",{args:[a("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,n)=>fu(e,se(n))}),r("doctor",{args:[a("offline",{describe:"N\xE3o verificar a fonte remota."}),o("source",t.string,{describe:"URL da fonte remota. Obrigat\xF3ria sem --offline.",valueName:"URL",env:"EDNE_SOURCE_URL"})],about:"Verificar Bun, configura\xE7\xE3o da base e acesso \xE0 fonte",handler:(e,n)=>Au(e,se(n))}),r("sql",{args:[s("query",t.string,{describe:"Instru\xE7\xE3o SELECT, WITH, PRAGMA ou EXPLAIN somente leitura.",required:!0,valueName:"CONSULTA"}),o("limit",t.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,n)=>Eu(e,se(n))}),r("cron",{about:"Gerenciar a atualiza\xE7\xE3o autom\xE1tica da base no sistema operacional",subcommands:[r("install",{args:[s("expression",t.cron,{default:zc,describe:"Express\xE3o cron. O padr\xE3o executa \xE0 meia-noite de sexta-feira.",valueName:"EXPRESS\xC3O"}),a("dry-run",{describe:"Exibir o agendamento sem alterar o sistema."}),o("source",t.string,{required:!0,describe:"Diret\xF3rio DNE, arquivo ZIP ou URL usado pelo agendamento.",valueName:"CAMINHO|URL",env:"EDNE_SOURCE_URL"})],about:"Instalar ou substituir o agendamento desta base",handler:(e,n)=>iu(e,se(n))}),r("status",{about:"Exibir o agendamento desta base",handler:(e,n)=>ou(se(n))}),r("remove",{about:"Remover o agendamento desta base",handler:(e,n)=>au(se(n))})],subcommandRequired:!0,defaultToHelp:!0})],subcommandRequired:!0,defaultToHelp:!0});async function po(e=Bun.argv.slice(2)){let n=e.includes("--json")||e.includes("--jsonl"),i=process.stdout.isTTY===!0&&Bun.env.TERM!=="dumb";try{return await ru.run({argv:e,color:i,stdout:(c)=>console.log(Wn(c).trimEnd()),...n?{stderr:(c)=>mo(new w("invalid-arguments",Wn(bu(Bun.stripANSI(c))),ce),!0)}:{stderr:(c)=>console.error(Wn(c).trimEnd())}})}catch(c){return Ou(c,n)}}function se(e){return{color:e.global(Oo),database:e.global(Ao),json:e.global(Eo),quiet:e.global(Ro)}}async function iu(e,n){let i=await di({database:n.database,dryRun:e["dry-run"],expression:e.expression,packageVersion:un,source:e.source});if(n.json)te(i);else{let c=i.status==="preview"?"Agendamento que seria instalado":i.status==="updated"?"Agendamento atualizado":"Agendamento instalado";console.log(`${c}: ${i.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${ut(i.next_run??void 0)}`),console.log(`Base: ${i.database}`),console.log(`Fonte: ${i.source}`),console.log(`Comando: ${i.command}`)}return 0}function ou(e){let n=fi(e.database);if(e.json)te(n);else if(n.installed)console.log(`Agendamento instalado: ${n.expression}`),console.log(`Pr\xF3xima execu\xE7\xE3o: ${ut(n.next_run??void 0)}`),console.log(`Base: ${n.database}`),console.log(`Fonte: ${n.source}`),console.log(`Pacote: @konstit/dne@${n.package_version}`),console.log(`Comando: ${n.command}`);else console.log(`Nenhum agendamento instalado para a base: ${n.database}`);return 0}async function au(e){let n=await Ai(e.database);if(e.json)te(n);else if(n.removed)console.log(`Agendamento removido para a base: ${n.database}`);else console.log(`Nenhum agendamento instalado para a base: ${n.database}`);return 0}async function su(e,n){let i=Io(n.quiet);try{return await cu(e,n,i)}finally{i.finish()}}async function cu(e,n,i){let c=performance.now(),u=ae(n.database,e.format);if(e.format==="binary"&&u===":memory:")throw new w("invalid-format","O formato bin\xE1rio exige um caminho de arquivo.",ce);if(e.check||u===":memory:")return oo(e,n,i,c,u);let l=await bi(u,i);try{return await oo(e,n,i,c,u)}finally{l.release()}}async function oo(e,n,i,c,u){let l=ho(),d=e.source,A=To(d)?await Ru(d,i,l,!e.check):null;if(i.finish(),e.check){if(!A){let y=new on(d,{onProgress:i});try{await y.resolve(l)}catch(U){throw new w("source-unavailable",_t(U))}finally{await y.cleanup(),i.finish()}}let b=await $e(u),g=A&&b.ready?await co(u,e.format,A):null,D={database:b,source:an(d,A),status:g===null?"unknown":g?"current":"update-available",up_to_date:g};return pu(D,n.json),0}if(!e.force&&A&&await co(u,e.format,A)){let g={database:await $e(u),elapsed_ms:zn(c),source:an(d,A),status:"unchanged"};return ao(g,n.json),0}let E=u!==":memory:"&&await Bun.file(u).exists(),R=new on(d,{onProgress:i,remoteInfo:A??void 0}),O=await Uu(u),p=new kn(O.path,l),I=!1,m=0;try{let b=await R.resolve(l);if(A)A.zipEntries=b.zipEntries??null;if(i(e.format==="binary"?"Carregando a base bin\xE1ria":"Carregando a base SQLite"),m=await p.loadFromSource(b,ro(d,A,un),i),e.format==="sqlite"&&u!==":memory:")i("Compactando a base SQLite"),p.compact();p.close(),I=!0;let g=O.path;if(e.format==="binary")g=`${O.path}.bin`,i("Compactando a base bin\xE1ria"),await Kr(O.path,g),await ge(O.path,{force:!0});if(i(e.format==="binary"?"Confirmando a base bin\xE1ria":"Confirmando a base SQLite"),e.format==="sqlite"&&E)await Nu(u,O.path,l);else await O.commit(g);i.finish()}finally{if(!I)p.close();await O.cleanup(),await R.cleanup()}let h={database:u===":memory:"?oi(m):await $e(u),elapsed_ms:zn(c),source:an(d,A),status:E?"updated":"created"};return ao(h,n.json),0}async function uu(e,n){if(n.json&&e.jsonl)throw new w("output-conflict","--json e --jsonl n\xE3o podem ser usados juntos.",ce);let c=wr(e.input,e.file)[Symbol.asyncIterator](),u=await c.next();if(u.done)throw new w("missing-input","Informe um CEP, --file CAMINHO ou uma entrada em stdin.",ce);let l=p(u.value),d=ae(n.database),A=await yt(d),E=[],R=0,O=!1;try{I(l);while(!0){let m=await c.next();if(m.done)break;I(p(m.value))}}finally{A.close()}if(n.json)te({count:R,database:d,results:E});else if(!e.jsonl)Iu(E);return O?nu:0;function p(m){let S=Lr(m);if(S===void 0)throw new w("invalid-cep",`CEP inv\xE1lido '${m}'. Use 01001000 ou 01001-000.`,ce,{input:m});return{cep:S,input:m}}function I(m){let S=A.queryCep(m.cep)??null,h={address:S,cep:m.cep,found:S!==null,input:m.input};if(R++,O||=!h.found,e.jsonl){process.stdout.write(`${JSON.stringify({ok:!0,data:{database:d,result:h}})}
|
|
41
|
+
`);return}E.push(h)}}async function lu(e,n){let i=performance.now(),c=ae(n.database),u=await yt(c),l=Io(n.quiet);try{if(!(u instanceof he))throw new w("invalid-format","O \xEDndice de busca exige uma base bin\xE1ria. Use build --format binary primeiro.",ce);let d=Zc(e.output??`${c.slice(0,c.length-qc(c).length)}.search.bin`),A=io(c),E=io(d,{throwIfNoEntry:!1});if(E?.dev===A.dev&&E?.ino===A.ino)throw new w("invalid-output","O caminho do \xEDndice deve ser diferente do caminho da base.",ce);await uo(jn(d),{recursive:!0}),l("Construindo o \xEDndice de busca");let R=lr(u),O=await Wc(qn(jn(d),".dne-search-"));try{let I=qn(O,"index.bin");await Bun.write(I,R),await lo(I,d)}finally{await ge(O,{recursive:!0,force:!0})}l.finish();let p={database:c,index:d,row_count:u.rowCount(),size_bytes:R.length,elapsed_ms:performance.now()-i};if(n.json)te(p);else console.log(`\xCDndice de busca criado: ${d} (${p.row_count} registros, ${p.size_bytes} bytes)`);return 0}finally{u.close(),l.finish()}}async function du(e){let n=await $e(ae(e.database));if(e.json)te(n);else mu(n);return n.ready?0:fo}async function fu(e,n){let i=ho(),c=_e(i),u=null,l="declared",d=It(i),A=`${[...d.map(ni),Tn(c.name)].join(`;
|
|
42
42
|
|
|
43
|
-
`)};`;if(!e.expected){
|
|
43
|
+
`)};`;if(!e.expected){u=ae(n.database);let E=await yt(u);try{if(!("tableSchema"in E))l="binary";else{let R=d.map((p)=>E.tableSchema(p.name)).filter((p)=>p!==void 0).map(Cu),O=E.querySql(`SELECT sql FROM sqlite_master WHERE type = 'view' AND name = ${bo(Ge(c.name))}`,1).rows[0]?.sql;if(typeof O==="string")R.push(O);if(R.length)A=`${R.join(`;
|
|
44
44
|
|
|
45
|
-
`)};`,
|
|
46
|
-
`),
|
|
47
|
-
`)}function
|
|
48
|
-
`);return}console.error(`erro: ${e.message}`)}function
|
|
49
|
-
`).map((
|
|
50
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
45
|
+
`)};`,l="database"}}finally{E.close()}}if(n.json)te({database:u,source:l,sql:A,table:z});else console.log(wu(A,n.color));return 0}async function Au(e,n){if(!e.offline&&!e.source)throw new w("invalid-arguments","Informe --source URL ou use --offline.",ce);let i=await $e(ae(n.database)),c=yu(Bun.version),u={checked:!1,reachable:null,url:e.source??null};if(!e.offline&&e.source)try{let A=await Mt(e.source);u={...an(e.source,A),checked:!0,reachable:!0}}catch(A){u={checked:!0,error:_t(A),reachable:!1,url:e.source}}let l=c&&i.ready&&u.reachable!==!1,d={auth:{required:!1,source:"not-required"},database:i,healthy:l,runtime:{compatible:c,minimum_version:"1.4.0",name:"bun",version:Bun.version},setup:i.ready?null:`Execute bunx @konstit/dne build --db ${Du(i.path)} --source CAMINHO_OU_URL`,source:u,version:un};if(n.json)te(d);else Su(d);return l?0:fo}async function Eu(e,n){if(!/^\s*(?:SELECT|WITH|PRAGMA|EXPLAIN)\b/i.test(e.query))throw new w("write-query-denied","O comando sql permite somente instru\xE7\xF5es SELECT, WITH, PRAGMA e EXPLAIN.",ce);let i=ae(n.database),c=await yt(i);try{if(!("querySql"in c))throw new w("sql-unsupported","O comando sql exige uma base SQLite.",ce);let u=c.querySql(e.query,e.limit),l={columns:u.rows[0]?Object.keys(u.rows[0]):[],database:i,limit:e.limit,...u};if(n.json)te(l);else console.log(JSON.stringify(l,null,2))}finally{c.close()}return 0}async function Ru(e,n,i,c){n("Inspecionando a fonte DNE remota");try{return await Ji(e,i)}catch(u){if(c)return{url:e,etag:null,lastModified:null,contentLength:null,acceptRanges:null,zipEntries:null};throw new w("source-unavailable",_t(u))}}function an(e,n){return n?{accept_ranges:n.acceptRanges,content_length:n.contentLength,etag:n.etag,kind:"remote",last_modified:n.lastModified,url:n.url,zip_entries:n.zipEntries??null}:{input:e,kind:To(e)?"remote":"local"}}function Io(e){let n=null,i=()=>{if(n!==null)process.stderr.write(` (${Qn(zn(n))})
|
|
46
|
+
`),n=null},c=(u)=>{if(i(),!e)n=performance.now(),process.stderr.write(u)};return c.finish=i,c}function te(e){process.stdout.write(`${JSON.stringify({ok:!0,data:e},null,2)}
|
|
47
|
+
`)}function mo(e,n){if(n){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 Ou(e,n){let i=e instanceof w?e:e instanceof He?new w("source-quality-failed",_t(e)):new w("internal-error",_t(e));return mo(i,n),i.exitCode}function pu(e,n){if(n){te(e);return}console.log(`Estado: ${gu(e.status)}`),console.log(`Base: ${e.database.path}`),console.log(`Fonte: ${Zn(e.source.url??e.source.input)}`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${ut(Zn(e.source.last_modified))}`)}function ao(e,n){if(n){te(e);return}let i=e.database.row_count===null?"quantidade desconhecida de registros":`${De(e.database.row_count)} registros`,c=e.database.size_bytes===null?"tamanho desconhecido":So(e.database.size_bytes);if(e.status==="unchanged"){let l=e.database.row_count===null?"quantidade desconhecida de registros":`${De(e.database.row_count)} registros`;console.log(`A base DNE j\xE1 est\xE1 atualizada: ${e.database.path} (${l}, ${c}).`),console.log(`\xDAltima modifica\xE7\xE3o na fonte: ${ut(Zn(e.source.last_modified))}`),console.log(`Verifica\xE7\xE3o conclu\xEDda em ${Qn(e.elapsed_ms)}.`);return}let u=e.status==="updated"?"Base atualizada":"Base criada";console.log(`${u}: ${e.database.path} (${i}, ${c}, ${Qn(e.elapsed_ms)}).`)}function Iu(e){if(e.length===1){let n=e[0];if(!n?.address){console.error(`CEP n\xE3o encontrado: ${n?.cep??""}`);return}console.log(n.address);return}console.log("cep\tencontrado\tlogradouro\tbairro\tmunic\xEDpio\tuf");for(let n of e)console.log([n.cep,sn(n.found),n.address?.logradouro??"",n.address?.bairro??"",n.address?.municipio??"",n.address?.uf??""].join("\t"))}function mu(e){if(console.log(`Base: ${e.path}`),console.log(`Formato: ${e.format??"-"}`),console.log(`Existe: ${sn(e.exists)}`),console.log(`Pronta: ${sn(e.ready)}`),console.log(`Registros: ${e.row_count===null?"-":De(e.row_count)}`),console.log(`Tamanho: ${e.size_bytes===null?"-":So(e.size_bytes)}`),console.log(`Carregada em: ${ut(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: ${ut(e.metadata?.source_last_modified)}`),e.error)console.log(`Erro: ${e.error}`)}function Su(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: ${sn(e.healthy)}`),e.setup)console.log(`Configura\xE7\xE3o: ${e.setup}`)}function hu(e){return e instanceof Error?e.message:String(e)}function _t(e){return Tu(hu(e))}function Tu(e){let i={"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(i)return i;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 Wn(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 Zn(e){return typeof e==="string"?e:""}function bu(e){return e.split(`
|
|
49
|
+
`).map((n)=>n.trim()).find(Boolean)?.replace(/^error:\s*/i,"")??"Argumentos inv\xE1lidos."}function zn(e){return Math.max(0,Math.round(performance.now()-e))}function De(e){return Kc.format(e)}function so(e){return eu.format(e)}function ut(e){if(!e)return"-";let n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString(cn)}function Qn(e){let n=Math.max(0,Math.round(e));if(n<1000)return`${De(n)} ms`;let i=Math.round(n/1000);if(i<60){let d=Math.round(n/100)/10;return`${tu.format(d)} s`}let c=Math.floor(i/3600),u=Math.floor(i%3600/60),l=i%60;return[c?`${De(c)} h`:"",u?`${De(u)} min`:"",l?`${De(l)} s`:""].filter(Boolean).join(" ")}function So(e){if(e<1024)return`${De(e)} B`;if(e<1048576)return`${so(e/1024)} KiB`;return`${so(e/1048576)} MiB`}function sn(e){return e?"sim":"n\xE3o"}function gu(e){return{current:"atualizada",unknown:"desconhecido","update-available":"atualiza\xE7\xE3o dispon\xEDvel"}[e]??e}function Du(e){return`'${e.replaceAll("'","'\\''")}'`}function yu(e){let[n=0,i=0]=e.split(".").map(Number);return n>1||n===1&&i>=4}function ho(){let e=br();return _e(e).name=z,e}async function Nu(e,n,i){let c=It(i),u=`${n}.attach`;await ge(u,{force:!0}),await Hc(n,u);let l=new kc(e);try{l.run("PRAGMA busy_timeout = 30000"),l.run("PRAGMA journal_mode = WAL"),l.run("PRAGMA synchronous = NORMAL"),l.run("PRAGMA foreign_keys = ON"),l.run(`ATTACH DATABASE ${bo(u)} AS fresh`),l.run("BEGIN IMMEDIATE");try{Xt(l,i),l.run(`
|
|
50
|
+
CREATE TABLE IF NOT EXISTS ${M(Z)} (
|
|
51
51
|
key TEXT PRIMARY KEY NOT NULL,
|
|
52
52
|
value TEXT NOT NULL
|
|
53
53
|
)
|
|
54
|
-
`);for(let
|
|
55
|
-
INSERT INTO main.${
|
|
56
|
-
SELECT ${
|
|
57
|
-
`)}
|
|
58
|
-
INSERT INTO main.${
|
|
54
|
+
`);for(let d of c){let A=d.columns.map((E)=>M(E.name)).join(", ");l.run(`
|
|
55
|
+
INSERT INTO main.${M(d.name)} (${A})
|
|
56
|
+
SELECT ${A} FROM fresh.${M(d.name)}
|
|
57
|
+
`)}l.run(`DELETE FROM main.${M(Z)}`),l.run(`
|
|
58
|
+
INSERT INTO main.${M(Z)} (key, value)
|
|
59
59
|
SELECT key, value
|
|
60
|
-
FROM fresh.${
|
|
61
|
-
`),
|
|
62
|
-
${
|
|
60
|
+
FROM fresh.${M(Z)}
|
|
61
|
+
`),l.run("COMMIT")}catch(d){throw l.run("ROLLBACK"),d}finally{l.run("DETACH DATABASE fresh")}}finally{l.close(),await ge(u,{force:!0})}}async function co(e,n,i){let c=await $e(e);if(!c.ready||c.format!==n||!c.metadata)return!1;return no(c.metadata,i)}function To(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function bo(e){return`'${e.replaceAll("'","''")}'`}function Cu(e){let n=e.indexOf("("),i=e.lastIndexOf(")");if(n===-1||i<=n)return e;let c=Lu(e.slice(n+1,i));if(!c.length)return e;let u=e.slice(0,n+1).trimEnd(),l=e.slice(i).trimStart();return`${u}
|
|
62
|
+
${c.join(`,
|
|
63
63
|
`)}
|
|
64
|
-
${
|
|
65
|
-
`||
|
|
64
|
+
${l}`}function Lu(e){let n=[],i=0,c=0,u=null,l=null;for(let d=0;d<e.length;d++){let A=e[d];if(l==="line"){if(A===`
|
|
65
|
+
`||A==="\r")l=null;continue}if(l==="block"){if(A==="*"&&e[d+1]==="/")l=null,d++;continue}if(u){if(A===u)if(e[d+1]===u)d++;else u=null;continue}if(A==="-"&&e[d+1]==="-")l="line",d++;else if(A==="/"&&e[d+1]==="*")l="block",d++;else if(A==="'"||A==='"'||A==="`")u=A;else if(A==="[")u="]";else if(A==="(")c++;else if(A===")")c--;else if(A===","&&c===0)n.push(e.slice(i,d).trim()),i=d+1}return n.push(e.slice(i).trim()),n.filter(Boolean)}function wu(e,n){return Bun.markdown.render(`\`\`\`sql
|
|
66
66
|
${e}
|
|
67
|
-
\`\`\``,{code:(
|
|
67
|
+
\`\`\``,{code:(i)=>Mu(i,n)}).trimEnd()}function Mu(e,n){if(!n)return e;return e.replaceAll(Yc,(i)=>{if(i.startsWith("--")||i.startsWith("/*"))return`${Jc}${i}${Hn}`;if(i.startsWith('"')||i.startsWith("`")||i.startsWith("["))return`${Xc}${i}${Hn}`;if(i.startsWith("'"))return i;return`${Qc}${i}${Hn}`})}async function Uu(e){if(e===":memory:")return{path:e,commit:async(u)=>{},cleanup:async()=>{}};let n=jn(e),i=qn(n,`.${jc(e)}.${process.pid}.${Date.now()}.tmp`);await uo(n,{recursive:!0}),await ge(i,{force:!0});let c=!1;return{path:i,commit:async(u=i)=>{await lo(u,e),c=!0},cleanup:async()=>{if(!c)await ge(i,{force:!0});await ge(`${i}.bin`,{force:!0}),await ge(`${i}-journal`,{force:!0})}}}process.exitCode=await po();
|
|
68
68
|
|
|
69
|
-
//# debugId=
|
|
69
|
+
//# debugId=0B29B0764C76F3BB64756E2164756E21
|