import{n as e}from"./chunk-DR8-3Aex.js";import{Ct as t,cn as n}from"./state-sIHsFpDu.js";import{Uc as r,zc as i}from"./paths-Ci1iwL5Y.js";import{E as a,J as o,O as s,U as c,_ as l,h as u,l as d,p as f}from"./debug-otxXY3j-.js";import{n as p,r as m}from"./analytics-DqMQntaB.js";import{o as h,s as g}from"./log-DSV4Ht5l.js";import{join as _}from"path";import{createWriteStream as v,writeFileSync as y}from"fs";import{readFile as b,readdir as x,writeFile as S}from"fs/promises";import{pipeline as C}from"stream/promises";import{getHeapSnapshot as w,getHeapSpaceStatistics as T,getHeapStatistics as E}from"v8";async function D(e,n=0){let r=process.memoryUsage(),i=E(),a=process.resourceUsage(),o=process.uptime(),s;try{s=T()}catch{}let c=process._getActiveHandles().length,l=process._getActiveRequests().length,u;try{u=(await x(`/proc/self/fd`)).length}catch{}let d;try{d=await b(`/proc/self/smaps_rollup`,`utf8`)}catch{}let f=r.rss-r.heapUsed,p=o>0?r.rss/o:0,m=p*3600/(1024*1024),h=[];return i.number_of_detached_contexts>0&&h.push(`${i.number_of_detached_contexts} detached context(s) - possible iframe/context leak`),c>100&&h.push(`${c} active handles - possible timer/socket leak`),f>r.heapUsed&&h.push(`Native memory > heap - leak may be in native addons (node-pty, sharp, etc.)`),m>100&&h.push(`High memory growth rate: ${m.toFixed(1)} MB/hour`),u&&u>500&&h.push(`${u} open file descriptors - possible file/socket leak`),{timestamp:new Date().toISOString(),sessionId:t(),trigger:e,dumpNumber:n,uptimeSeconds:o,memoryUsage:{heapUsed:r.heapUsed,heapTotal:r.heapTotal,external:r.external,arrayBuffers:r.arrayBuffers,rss:r.rss},memoryGrowthRate:{bytesPerSecond:p,mbPerHour:m},v8HeapStats:{heapSizeLimit:i.heap_size_limit,mallocedMemory:i.malloced_memory,peakMallocedMemory:i.peak_malloced_memory,detachedContexts:i.number_of_detached_contexts,nativeContexts:i.number_of_native_contexts},v8HeapSpaces:s?.map(e=>({name:e.space_name,size:e.space_size,used:e.space_used_size,available:e.space_available_size})),resourceUsage:{maxRSS:a.maxRSS*1024,userCPUTime:a.userCPUTime,systemCPUTime:a.systemCPUTime},activeHandles:c,activeRequests:l,openFileDescriptors:u,analysis:{potentialLeaks:h,recommendation:h.length>0?`WARNING: ${h.length} potential leak indicator(s) found. See potentialLeaks array.`:`No obvious leak indicators. Check heap snapshot for retained objects.`},smapsRollup:d,platform:process.platform,nodeVersion:process.version,ccVersion:`2.7.1`}}async function O(e=`manual`,n=0){try{let r=t(),a=await D(e,n),o=e=>(e/1024/1024/1024).toFixed(3);f(`[HeapDump] Memory state:
  heapUsed: ${o(a.memoryUsage.heapUsed)} GB (in snapshot)
  external: ${o(a.memoryUsage.external)} GB (NOT in snapshot)
  rss: ${o(a.memoryUsage.rss)} GB (total process)
  ${a.analysis.recommendation}`);let c=i();await u().mkdir(c);let l=n>0?`-dump${n}`:``,d=`${r}${l}.heapsnapshot`,p=`${r}${l}-diagnostics.json`,h=_(c,d),g=_(c,p);return await S(g,s(a,null,2),{mode:384}),f(`[HeapDump] Diagnostics written to ${g}`),await k(h),f(`[HeapDump] Heap dump written to ${h}`),m(`tengu_heap_dump`,{triggerManual:e===`manual`,triggerAuto15GB:e===`auto-1.5GB`,dumpNumber:n,success:!0}),{success:!0,heapPath:h,diagPath:g}}catch(t){let r=o(t);return g(r),m(`tengu_heap_dump`,{triggerManual:e===`manual`,triggerAuto15GB:e===`auto-1.5GB`,dumpNumber:n,success:!1}),{success:!1,error:r.message}}}async function k(e){if(typeof Bun<`u`){y(e,Bun.generateHeapSnapshot(`v8`,`arraybuffer`),{mode:384}),Bun.gc(!0);return}let t=v(e,{mode:384});await C(w(),t)}var A=e((()=>{n(),p(),d(),c(),r(),l(),h(),a()}));async function j(){let e=await O();return e.success?{type:`text`,value:`${e.heapPath}\n${e.diagPath}`}:{type:`text`,value:`Failed to create heap dump: ${e.error}`}}e((()=>{A()}))();export{j as call};