@konstit/dne 0.0.2 → 0.2.0

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