import{mkdirSync as S,createWriteStream as O,readdirSync as m,statSync as D,rmSync as x,copyFileSync as v,readFileSync as I,writeFileSync as E,existsSync as T,unlinkSync as $}from"fs";import{unlink as k}from"fs/promises";import{join as o}from"path";import{resolveUserDataDir as f}from"./constants-DED7MIJj.mjs";import{R as z,a as A}from"./logger-D_9t6p_W.mjs";(function(){try{var c=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};c.SENTRY_RELEASE={id:"4.2.860"}}catch{}})();try{(function(){var c=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new c.Error().stack;e&&(c._sentryDebugIds=c._sentryDebugIds||{},c._sentryDebugIds[e]="7e4df949-6edc-4040-8e5c-4494147edea9",c._sentryDebugIdIdentifier="sentry-dbid-7e4df949-6edc-4040-8e5c-4494147edea9")})()}catch{}process.env.BEEPER_BENCH;class a{constructor(e){this.options=e,this.index=0,this.size=0,this.segments=new Map,this.pendingEntries=[],this.drainScheduled=!1,this.buddyOriginOverride=null,this.silently={info:this.push.bind(this,"info",!0),error:this.push.bind(this,"error",!0),warn:this.push.bind(this,"warn",!0),debug:this.push.bind(this,"debug",!0),log:this.push.bind(this,"log",!0),trace:this.push.bind(this,"trace",!0)},this.boundDrain=()=>this.drain(),this.path=o(f(),"logs",this.options.name),console.log("[RollingLogger]",this.options.name,this.path),S(this.path,{recursive:!0}),this.initializeLogs(),this.stream=a.createStream(this.computeFilePath(this.index)),a.instances.add(this)}static{this.instances=new Set}static createStream(e){const t=O(e,{flags:"a"});return t.on("error",s=>console.error("There was an error writing to a logfile",s)),t}static{this.buddyOriginOverride=Symbol.for("buddyOriginOverride")}initializeLogs(){const e=s=>{try{const i=s.lastIndexOf("-");return parseInt(s.substring(i+1,s.length-4),10)}catch(i){return this.error("Error getting index for file name when initializing RollingLogger logs:",i),0}},t=m(this.path,{withFileTypes:!0});if(t?.length>this.index){const s=t[t.length-1];this.index=e(s.name)}t.forEach(s=>{const i=D(o(this.path,s.name));this.size+=i.size,this.segments.set(e(s.name),i.size)})}info(...e){this.push("info",!1,...e)}error(...e){this.push("error",!1,...e)}warn(...e){this.push("warn",!1,...e)}debug(...e){this.push("debug",!1,...e)}log(...e){this.push("log",!1,...e)}trace(){this.push("trace",!1)}push(e,t,...s){const{prefix:i}=this.options;this.pendingEntries.push({level:e,silently:t,args:s,computedPrefix:(typeof i=="function"?i():i)??null,timestamp:Date.now(),instanceBuddyOrigin:this.buddyOriginOverride}),this.drainScheduled||(this.drainScheduled=!0,setImmediate(this.boundDrain))}drain(){if(this.drainScheduled=!1,this.pendingEntries.length===0)return;const e=this.pendingEntries;this.pendingEntries=[],this.stream.cork();try{for(const t of e)try{this.formatAndWriteEntry(t)}catch(s){console.error("Error processing log entry",s)}}finally{process.nextTick(()=>this.stream.uncork())}}formatAndWriteEntry(e){const{level:t,silently:s,args:i,computedPrefix:h,timestamp:r,instanceBuddyOrigin:l}=e,d=[],u=[];for(const n of i){if(typeof n=="object"&&n!=null&&a.buddyOriginOverride in n){n[a.buddyOriginOverride];continue}n instanceof z?(d.push(n.toRedactedString()),u.push(n.toOriginal())):(d.push(n),u.push(n))}const p=d.map(n=>typeof n!="string"?A(n):n).join(" "),g=h?`[${t}] [${h}] ${p}`:`[${t}] ${p}`;if(!s&&!1)try{}catch(n){}this.writeToDisk(g+`
`)}writePreformatted(e,t,s){const{prefix:i}=this.options;s?.buddyOrigin??this.buddyOriginOverride;const h=typeof i=="function"?i():i,r=h?`[${e}] [${h}] ${t}
`:`[${e}] ${t}
`;this.writeToDisk(r)}writeToDisk(e){const{segmentCount:t,byteLimit:s}=this.options,i=Buffer.byteLength(e,"utf8"),r=(this.segments.get(this.index)??0)+i;if(this.size+=i,this.segments.set(this.index,r),this.stream.write(e),r>s/t&&(this.index++,this.stream.end(),this.stream=a.createStream(this.computeFilePath(this.index))),this.size>s){const l=this.index-t,d=this.segments.get(l);d!==void 0&&(k(this.computeFilePath(l)).catch(u=>{console.error("Failed to remove old log segment",u)}),this.size-=d,this.segments.delete(l))}}flush(){return this.drain(),new Promise((e,t)=>{if(this.stream.writableFinished||this.stream.destroyed){e();return}this.stream.write("",s=>{s?t(s):e()})})}close(){return this.drain(),a.instances.delete(this),new Promise(e=>{this.stream.end(e)})}static async flushAll(){await Promise.all(Array.from(a.instances).map(e=>e.flush()))}static async closeAll(){await Promise.all(Array.from(a.instances).map(e=>e.close()))}static async snapshot(){await a.flushAll();const e=o(f(),"logs"),t=o(f(),"dumps");try{const s=m(e,{withFileTypes:!0}),i=o(t,`dump-${new Date().getTime()}`);S(i,{recursive:!0});const h=m(t,{withFileTypes:!0}).filter(r=>r.isDirectory());if(h.length>5){const r=h.sort((d,u)=>d.name.localeCompare(u.name))[0],l=o(t,r.name);x(l,{recursive:!0})}for(const r of s)if(r.isFile()&&r.name.endsWith(".log"))v(o(e,r.name),o(i,r.name));else if(r.isDirectory()){const l=o(e,r.name),d=o(i,`${r.name}.log`),p=m(l).sort((n,y)=>{const w=n.split("-"),b=y.split("-"),F=w[w.length-1].split(".")[0],P=b[b.length-1].split(".")[0];return parseInt(F,10)-parseInt(P,10)});let g="";for(const n of p){const y=I(o(l,n),"utf-8");g+=y}E(d,g)}return i}catch(s){console.error("Failed to dump a compressed snapshot of logs:",s)}}computeFilePath(e){const{name:t}=this.options;return o(this.path,`${t}-${e}.log`)}static nuke(){const e=o(f(),"logs"),t=m(e,{withFileTypes:!0}).filter(s=>s.isDirectory());for(const s of t)x(o(e,s.name),{recursive:!0})}static redactSQL(e){return e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,"[REDACTED]")}static markGracefulExit(){E(o(f(),"logs",".exited"),new Uint8Array(0))}static wasGracefulExit(){const e=o(f(),"logs",".exited");if(T(e))try{return $(e),!0}catch(t){console.error("Error removing .exited file:",t)}return!1}}const W=c=>new a({name:c,byteLimit:5*1024*1024,segmentCount:5,prefix:()=>new Date().toISOString()});export{a as R,W as c};
//# sourceMappingURL=rolling-logger-H_IO3gVC.mjs.map
