diff --git a/README.md b/README.md index 2a55f46..89549f1 100644 --- a/README.md +++ b/README.md @@ -16,10 +16,13 @@ compares](#how-it-compares). ## What it does -- **Walk** a repo deterministically: ignore lists, binary/lockfile skips, a size - cap, symlink-cycle guard. No file-count cap unless you ask for one - (`--max-files`), and asking sets the `capped` flag — never a silent - truncation. +- **Walk** a repo deterministically: ignore lists, `.gitignore` and + `.git/info/exclude`, binary/lockfile skips, a size cap, symlink-cycle guard. + Nested repositories (a subdirectory with its own `.git` — linked worktrees, + vendored clones, submodules) are skipped like git does, and `.git` itself is + never walked even when `--ignore-dir` replaces the default ignore list. No + file-count cap unless you ask for one (`--max-files`), and asking sets the + `capped` flag — never a silent truncation. - **Scan** every file into a `FileRecord`: classification, language, symbols, imports, headings, hashes — with an incremental cache fastpath. Extraction runs across worker threads by default (`--workers`, `CODEINDEX_WORKERS`); diff --git a/scripts/engine.browser.d.mts b/scripts/engine.browser.d.mts index d90ebef..8abadf3 100644 --- a/scripts/engine.browser.d.mts +++ b/scripts/engine.browser.d.mts @@ -526,6 +526,8 @@ interface ResolveContext { }[]; csharpNamespaces: Map; warnings: string[]; + jsMemo?: Map; + dirFilesMemo?: Map; } declare function buildResolveContext(scan: RepoScan): ResolveContext; declare function resolveDocLink(fromRel: string, spec: string, ctx: ResolveContext): Resolution; diff --git a/scripts/engine.browser.mjs b/scripts/engine.browser.mjs index 3b71166..4c1ebc5 100644 --- a/scripts/engine.browser.mjs +++ b/scripts/engine.browser.mjs @@ -1,73 +1,80 @@ -var qu=Object.defineProperty;var F=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Oi=(e,t)=>{for(var n in t)qu(e,n,{get:t[n],enumerable:!0})};function tl(e){let t="";for(let r=0;r{"use strict";Gu=new TextDecoder("utf-8"),Vu=new TextDecoder("utf-16le"),Qa=new TextEncoder,el="0123456789abcdef";T=class e extends Uint8Array{static from(t,n){if(typeof t=="string"){if(n==="hex"){let l=new e(t.length>>1);for(let c=0;ca+l.byteLength,0),s=new e(r),o=0;for(let a of t){if(o+a.byteLength>r){s.set(a.subarray(0,r-o),o);break}s.set(a,o),o+=a.byteLength}return s}subarray(t,n){return super.subarray(t,n)}toString(t,n,r){let s=n!==void 0||r!==void 0?this.subarray(n??0,r??this.length):this;switch((t??"utf8").toLowerCase()){case"utf8":case"utf-8":return Gu.decode(s);case"utf16le":case"utf-16le":case"ucs2":case"ucs-2":return Vu.decode(s);case"latin1":case"binary":case"ascii":return tl(s);case"hex":{let o="";for(let a of s)o+=el[a>>4]+el[a&15];return o}case"base64":return btoa(tl(s));default:throw new TypeError(`Unknown encoding: ${t}`)}}swap16(){if(this.length%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t"/",exit:e=>{throw new Error(`process.exit(${e??0}) is not available in the browser build`)},hrtime:Object.assign(e=>{let t=performance.now(),n=Math.floor(t/1e3),r=Math.floor(t%1e3*1e6);return e?[n-e[0],r-e[1]]:[n,r]},{bigint:()=>BigInt(Math.floor(performance.now()*1e6))}),memoryUsage:()=>({rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}),stdout:{write:e=>(console.log(e.replace(/\n$/,"")),!0),isTTY:!1},stderr:{write:e=>(console.warn(e.replace(/\n$/,"")),!0),isTTY:!1},on:()=>R,emitWarning:e=>console.warn(e)}});var fe,He,mn,Xe=F(()=>{"use strict";k();fe="2.28.1",He=5,mn=14});function nl(e,t){let n="",r=0,s=-1,o=0,a=0;for(let l=0;l<=e.length;++l){if(l2){let c=n.lastIndexOf("/");c===-1?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),s=l,o=0;continue}else if(n.length!==0){n="",r=0,s=l,o=0;continue}}t&&(n+=n.length>0?"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,l):n=e.slice(s+1,l),r=l-s-1;s=l,o=0}else a===46&&o!==-1?++o:o=-1}return n}function Yr(e){if(e.length===0)return".";let t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47,r=nl(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&n&&(r+="/"),t?"/"+r:r}function Qr(e){return e.length>0&&e.charCodeAt(0)===47}function I(...e){if(e.length===0)return".";let t;for(let n of e)n.length>0&&(t=t===void 0?n:t+"/"+n);return t===void 0?".":Yr(t)}function Ne(...e){let t="",n=!1;for(let s=e.length-1;s>=0&&!n;s--){let o=e[s];o===void 0||o.length===0||(t=t.length===0?o:o+"/"+t,n=o.charCodeAt(0)===47)}n||(t=t.length===0?"/":"/"+t);let r=nl(t,!1);return r.length>0?"/"+r:"/"}function Ju(e,t){if(e===t)return"";let n=Ne(e),r=Ne(t);if(n===r)return"";let s=n.slice(1).split("/").filter(Boolean),o=r.slice(1).split("/").filter(Boolean),a=0;for(;a=1;--s)if(e.charCodeAt(s)===47){if(!r){n=s;break}}else r=!1;return n===-1?t?"/":".":t&&n===1?"//":e.slice(0,n)}function ke(e,t){let n=0,r=-1,s=!0;for(let a=e.length-1;a>=0;--a)if(e.charCodeAt(a)===47){if(!s){n=a+1;break}}else r===-1&&(s=!1,r=a+1);if(r===-1)return"";let o=e.slice(n,r);return t!==void 0&&t!==o&&o.endsWith(t)?o.slice(0,o.length-t.length):o}function es(e){let t=-1,n=0,r=-1,s=!0,o=0;for(let a=e.length-1;a>=0;--a){let l=e.charCodeAt(a);if(l===47){if(!s){n=a+1;break}continue}r===-1&&(s=!1,r=a+1),l===46?t===-1?t=a:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||r===-1||o===0||o===1&&t===r-1&&t===n+1?"":e.slice(t,r)}function Ku(e){let t=Qr(e)?"/":"",n=ke(e),r=es(e),s=_e(e);return{root:t,dir:s==="."&&t===""?"":s,base:n,ext:r,name:n.slice(0,n.length-r.length)}}function Xu(e){let t=e.dir||e.root||"",n=e.base||(e.name??"")+(e.ext??"");return t?t===e.root?t+n:t+"/"+n:n}function Zu(e){return e}var $,qy,oe=F(()=>{"use strict";k();$={sep:"/",delimiter:":",normalize:Yr,isAbsolute:Qr,join:I,resolve:Ne,relative:Ju,dirname:_e,basename:ke,extname:es,parse:Ku,format:Xu,toNamespacedPath:Zu},qy={...$,posix:$,win32:$}});function sl(){return++rl}function Ue(e){let t=e.startsWith("/")?e:"/"+e,n=Yr(t);return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function Ct(e,t){let n=new Error(`ENOENT: no such file or directory, ${t} '${e}'`);return n.code="ENOENT",n.errno=-2,n.path=e,n.syscall=t,n}function il(e,t){let n=new Error(`ENOTDIR: not a directory, ${t} '${e}'`);return n.code="ENOTDIR",n.errno=-20,n.path=e,n.syscall=t,n}function pn(e){let t=Ue(e),n=me.get(t);if(n){if(n.kind!=="dir")throw il(e,"mkdir");return n}let r={kind:"dir",mtimeMs:0,mode:511,children:new Set};return me.set(t,r),t!==Ht&&pn(_e(t)).children.add(ke(t)),r}function Yu(){me.clear(),rl=0,ll=0,me.set(Ht,{kind:"dir",mtimeMs:0,mode:511,children:new Set})}function ol(e){for(let t of e){let n=Ue(t.path);pn(_e(n)).children.add(ke(n)),me.set(n,{kind:"file",size:t.size,mtimeMs:sl(),mode:438,bytes:t.bytes})}}function ts(e,t){let n=Ue(e),r=me.get(n);if(r&&r.kind==="file"){r.bytes=t,r.size=t.byteLength,r.mtimeMs=sl();return}ol([{path:n,size:t.byteLength,bytes:t}])}function Qu(e){let t=me.get(Ue(e));return!!t&&t.kind==="file"&&t.bytes!==void 0}function ef(){let e=0;for(let[t,n]of[...me]){if(n.kind!=="file"||n.bytes!==void 0)continue;me.delete(t);let r=me.get(_e(t));r&&r.kind==="dir"&&r.children.delete(ke(t)),e++}return e}function tf(){let e=0;for(let t of me.values())t.kind==="file"&&t.bytes&&(e+=t.bytes.byteLength);return e}function nf(e,t,n){return{name:e,parentPath:t,path:t,isFile:()=>n==="file",isDirectory:()=>n==="dir",isSymbolicLink:ot,isBlockDevice:ot,isCharacterDevice:ot,isFIFO:ot,isSocket:ot}}function rf(e){return{size:e.kind==="file"?e.size:0,mode:e.mode,mtimeMs:e.mtimeMs,mtime:new Date(e.mtimeMs),isFile:()=>e.kind==="file",isDirectory:()=>e.kind==="dir",isSymbolicLink:ot,isBlockDevice:ot,isCharacterDevice:ot,isFIFO:ot,isSocket:ot}}function H(e){return me.has(Ue(e))}function Ee(e){let t=me.get(Ue(e));if(!t)throw Ct(e,"stat");return rf(t)}function gn(e){let t=Ue(e);if(!me.has(t))throw Ct(e,"realpath");return t}function _n(e,t){let n=Ue(e),r=me.get(n);if(!r)throw Ct(e,"scandir");if(r.kind!=="dir")throw il(e,"scandir");let s=[...r.children];return t?.withFileTypes?s.map(o=>{let a=me.get(n===Ht?`/${o}`:`${n}/${o}`);return nf(o,n,a?.kind==="dir"?"dir":"file")}):s}function te(e,t){let n=me.get(Ue(e));if(!n)throw Ct(e,"open");if(n.kind!=="file"){let s=new Error("EISDIR: illegal operation on a directory, read");throw s.code="EISDIR",s}if(!n.bytes)throw Ct(e,"open");let r=T.from(n.bytes);return t?r.toString(typeof t=="string"?t:t.encoding):r}function Re(e,t){let n=typeof t=="string"?new TextEncoder().encode(t):t;ts(e,n)}function ns(e,t){let n=me.get(Ue(e));if(!n)throw Ct(e,"chmod");n.mode=t}function gt(e,t){pn(e)}function Ln(e){let t=`${e}${ll++}`;return pn(t),t}function qe(e,t){let n=Ue(e),r=me.get(n);if(!r){if(t?.force)return;throw Ct(e,"unlink")}if(r.kind==="dir")for(let o of[...r.children])qe(n===Ht?`/${o}`:`${n}/${o}`,t);me.delete(n);let s=me.get(_e(n));s&&s.kind==="dir"&&s.children.delete(ke(n))}function Dn(e,t){let n=Ue(e),r=me.get(n);if(!r)throw Ct(e,"rename");let s=Ue(t);if(r.kind==="dir"){pn(s);for(let o of[...r.children])Dn(n===Ht?`/${o}`:`${n}/${o}`,s===Ht?`/${o}`:`${s}/${o}`)}else pn(_e(s)).children.add(ke(s)),me.set(s,r);qe(n,{force:!0})}function cl(){throw new Error("recursive filesystem watching is unavailable in the browser VFS")}var Ht,me,rl,ot,al,ll,xe=F(()=>{"use strict";k();oe();Ht="/",me=new Map([[Ht,{kind:"dir",mtimeMs:0,mode:511,children:new Set}]]),rl=0;ot=()=>!1;al=Ee;ll=0});function dl(e,t,n){let r=new Error(`spawnSync ${e} ENOENT`);return r.code="ENOENT",r.errno=-2,r.syscall=`spawnSync ${e}`,r.path=e,{pid:0,output:[],stdout:"",stderr:"",status:null,signal:null,error:r}}function ul(e,t,n){let r=new Map,s={pid:void 0,stdin:null,stdout:null,stderr:null,on(a,l){let c=r.get(a)??[];return c.push(l),r.set(a,c),s},kill:()=>!1},o=new Error(`spawn ${e} ENOENT`);return o.code="ENOENT",o.syscall=`spawn ${e}`,o.path=e,Promise.resolve().then(()=>{for(let a of r.get("error")??[])a(o);for(let a of r.get("close")??[])a(null)}),s}var Fi=F(()=>{k()});function pe(e,t,n={}){let r=dl(e,t,{cwd:n.cwd,input:n.input,encoding:"utf8",timeout:n.timeoutMs??12e4,maxBuffer:67108864,env:n.env??R.env}),s=!!r.error&&r.error.code==="ENOENT";return{ok:!r.error&&r.status===0,status:r.status,stdout:r.stdout??"",stderr:r.stderr??(r.error?String(r.error.message):""),missing:s}}function at(e){let t=fl.get(e);if(t!==void 0)return t;let n=pe(R.platform==="win32"?"where":"which",[e]),r=n.ok&&n.stdout.trim().length>0;return fl.set(e,r),r}function Pi(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/\.git$/,"").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,120)}function sf(e,t){return e.length<=t?e:e.slice(0,t)+` -\u2026 [truncated ${e.length-t} chars]`}function of(e,t){let n=e.replace(/\s+/g," ").trim();if(n.length<=t)return n;let r=n.slice(0,t).replace(/\s+\S*$/,"");return r||(r=n.slice(0,t)),(r.match(/`/g)?.length??0)%2===1&&(r=r.replace(/`[^`]*$/,"")),r.lastIndexOf("[")>r.lastIndexOf("]")&&(r=r.slice(0,r.lastIndexOf("["))),r.replace(/\s+$/,"")+"\u2026"}function Ge(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _t(e){return e.normalize("NFKD").replace(/[̀-ͯ]/g,"")}function rs(e){let t=new Set,n=[];for(let r of _t(e).split(/[^A-Za-z0-9_]+/)){if(!r)continue;let s=r.toLowerCase();r.length<2||ml.has(s)||t.has(s)||(t.add(s),n.push(r))}return n}function ss(e){let t=[];for(let n of _t(e).split(/[^A-Za-z0-9_]+/))n&&(n.length<2||ml.has(n.toLowerCase()))&&t.push(n);return t}function af(e){let t=rs(e),n=r=>{let s=0;return/\d/.test(r)&&(s+=3),/[A-Z]/.test(r)&&!/^[A-Z0-9]+$/.test(r)&&(s+=2),/_/.test(r)&&(s+=2),r.length>=8?s+=1.5:r.length>=5&&(s+=.5),s};return t.map((r,s)=>({k:r,s:n(r),i:s})).sort((r,s)=>s.s-r.s||r.i-s.i).map(r=>r.k)}function $i(e,t,n=60){let r=new Map;for(let s of e)s.forEach((o,a)=>{let l=t(o);r.set(l,(r.get(l)??0)+1/(n+a+1))});return r}function ht(e){let t=_t(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2"),n=[],r=new Set,s=o=>{o.length<2||r.has(o)||(r.add(o),n.push(o))};/\s/.test(e.trim())||s(_t(e).toLowerCase().replace(/[^a-z0-9_]+/g,""));for(let o of t.split(/[^A-Za-z0-9]+/))s(o.toLowerCase());return n}function Li(e){if(e.length<4)return e;let t=e;return t.endsWith("ies")&&t.length>4?t=t.slice(0,-3)+"y":t.endsWith("sses")?t=t.slice(0,-2):(t.endsWith("ses")&&t.length>4||t.endsWith("s")&&!t.endsWith("ss")&&!t.endsWith("us")&&!t.endsWith("is"))&&(t=t.slice(0,-1)),t.endsWith("ying")&&t.length>5?t=t.slice(0,-4)+"y":t.endsWith("ing")&&t.length>5?t=t.slice(0,-3):t.endsWith("ed")&&t.length>4&&(t=t.slice(0,-2)),t.endsWith("e")&&t.length>3&&(t=t.slice(0,-1)),t}var fl,ml,Ce=F(()=>{"use strict";k();Fi();fl=new Map;ml=new Set(["the","a","an","is","are","was","were","be","been","being","do","does","did","how","what","why","when","where","which","who","whom","this","that","these","those","of","in","on","to","for","with","and","or","but","if","then","else","than","as","at","by","from","into","about","it","its","i","you","we","they","he","she","there","here","can","could","should","would","will","shall","may","might","must","have","has","had","not","no","yes","so","such","only","any","some","all","get","set","use","used","using","work","works","working","handle","handled","happen","happens","default","value","values","please","explain","tell","me","my","our"])});function lf(e){let t="";for(let n=0;n{"use strict";k();Ce()});function pl(e,t){return t.has(e)||e.startsWith(".codeindex-edit-")}function Fe(e,t={}){let n=t.maxFileBytes??1048576,r=t.maxFiles??1/0,s=t.gitignore!==!1,o=t.ignoreDirs?new Set(t.ignoreDirs):qt,a=[],l=!1,c=0,d;try{d=gn(e)}catch{return{files:a,capped:l,excluded:c}}let f=p=>p===d||p.startsWith(d+"/"),u=[{dir:e,rel:"",rules:[]}],m=new Set;e:for(;u.length;){let p=u.pop(),g;try{g=gn(p.dir)}catch{continue}if(m.has(g)||(m.add(g),!f(g)))continue;let y;try{y=_n(p.dir,{withFileTypes:!0}).sort((S,_)=>S.name<_.name?-1:S.name>_.name?1:0)}catch{continue}let h=p.rules;if(s&&y.some(S=>S.name===".gitignore")){let S=Di(G(I(p.dir,".gitignore")),p.rel);S.length&&(h=[...h,...S])}for(let S of y){let _=S.name,E=I(p.dir,_),b=p.rel?`${p.rel}/${_}`:_,x=S.isSymbolicLink();if(S.isDirectory()&&pl(_,o))continue;let v;try{v=x?Ee(E):al(E)}catch{continue}if(v.isDirectory()){if(pl(_,o)||x||s&&h.length&&is(h,b,!0))continue;u.push({dir:E,rel:b,rules:h});continue}if(!v.isFile())continue;if(v.size>n){c++;continue}if(Wi.has(_.toLowerCase())){c++;continue}let A=es(_).toLowerCase();if(Ui.has(A)){c++;continue}if(_.endsWith(".min.js")||_.endsWith(".min.css")){c++;continue}if(s&&h.length&&is(h,b,!1)){c++;continue}if(x)try{if(!f(gn(E)))continue}catch{continue}if(a.length>=r){l=!0;break e}a.push({rel:b.split("/").join("/"),abs:E,size:v.size,ext:A,mtimeMs:v.mtimeMs})}}return{files:a,capped:l,excluded:c}}function G(e){try{let t=te(e);if(t.length>=2&&t[0]===255&&t[1]===254)return t.subarray(2,2+(t.length-2&-2)).toString("utf16le");if(t.length>=2&&t[0]===254&&t[1]===255){let r=T.from(t.subarray(2,2+(t.length-2&-2)));return r.swap16(),r.toString("utf16le")}if(t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191)return t.subarray(3).toString("utf8");if(t.includes(0))return"";let n=t.toString("utf8");return n.includes("\uFFFD")?t.toString("latin1"):n}catch{return""}}var qt,Wi,Ui,cf,Ae=F(()=>{"use strict";k();xe();oe();ji();qt=new Set([".git","node_modules",".pnpm","bower_components","vendor","dist","build","out","target",".next",".nuxt",".svelte-kit",".turbo","coverage","__pycache__",".venv","venv",".tox",".mypy_cache",".pytest_cache",".gradle",".idea",".vscode",".cache","tmp",".ultraindex",".codeindex","Pods","DerivedData",".terraform","elm-stuff",".dart_tool"]);Wi=new Set(["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lockb","composer.lock","cargo.lock","poetry.lock","pipfile.lock","gemfile.lock","go.sum","flake.lock","packages.lock.json","podfile.lock","mix.lock"]),Ui=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".icns",".svg",".pdf",".zip",".gz",".tar",".tgz",".bz2",".xz",".7z",".rar",".jar",".war",".class",".so",".dylib",".dll",".exe",".bin",".o",".a",".wasm",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".wav",".flac",".ogg",".lock",".min.js",".map"]),cf=2e4});function as(e){let t=pe("git",["-C",e,"rev-parse","--short","HEAD"]);return t.ok?t.stdout.trim():void 0}function zi(e){return pe("git",["-C",e,"rev-parse","--is-inside-work-tree"]).ok}function Hi(e,t){let n=l=>pe("git",[...lt(e),"rev-parse","--verify","--quiet",`${l}^{commit}`]).ok,r=l=>{let c=pe("git",[...lt(e),"merge-base",l,"HEAD"]);return c.ok?c.stdout.trim():void 0};if(t){if(!n(t))return{error:`base ref "${t}" not found (tried git rev-parse --verify)`};let l=r(t);return l?{ref:t,mergeBase:l}:{error:`no merge-base between "${t}" and HEAD`}}let s=pe("git",[...lt(e),"symbolic-ref","--quiet","refs/remotes/origin/HEAD"]),o=[...s.ok?[s.stdout.trim().replace("refs/remotes/","")]:[],"origin/main","origin/master","main","master"];for(let l of o){if(!n(l))continue;let c=r(l);if(c)return{ref:l,mergeBase:c}}let a=pe("git",[...lt(e),"rev-parse","HEAD"]);return a.ok?{ref:"HEAD",mergeBase:a.stdout.trim(),note:"base: HEAD (no default branch found \u2014 reviewing uncommitted work)"}:{error:"cannot resolve HEAD \u2014 empty repository?"}}function qi(e,t){let n=[],r=pe("git",[...lt(e),"diff","-z","-M","--name-status",...Bi(t)]);if(r.ok){let a=r.stdout.split("\0"),l=0;for(;l[a.path,a])),o=pe("git",[...lt(e),"diff","-z","-M","--numstat",...Bi(t)]);if(o.ok){let a=o.stdout.split("\0"),l=0;for(;ln.length>0):[]}function Ze(e,t={}){let n=new Map,r=t.since?[`${t.since}..HEAD`]:[],s=pe("git",[...lt(e),"log",...r,"--pretty=format:","--name-only","-z"]);if(!s.ok)return{churn:n,ok:!1};for(let o of s.stdout.split("\0")){let a=o.replace(/^\n+/,"").trim();a&&n.set(a,(n.get(a)??0)+1)}return{churn:n,ok:!0}}function df(e,t){let n=new Set,r=pe("git",[...lt(e),"diff","-z","--name-only",t,"--"]);if(r.ok)for(let s of r.stdout.split("\0"))s&&n.add(s);for(let s of ls(e))n.add(s);return n}var lt,Bi,Gt=F(()=>{"use strict";k();Ce();lt=e=>["-C",e,"-c","core.quotePath=false"],Bi=e=>e.staged?["--cached"]:[e.mergeBase]});function uf(e){return typeof e=="string"?new TextEncoder().encode(e):e}function ff(e,t){if(e.length===1)return e[0];let n=new Uint8Array(t),r=0;for(let s of e)n.set(s,r),r+=s.byteLength;return n}function _l(e){let t=Math.floor(e.byteLength/536870912|0),n=e.byteLength<<3>>>0,r=Math.ceil((e.byteLength+9)/64),s=new Uint8Array(r*64);s.set(e),s[e.byteLength]=128;let o=new DataView(s.buffer);return o.setUint32(s.byteLength-8,t,!1),o.setUint32(s.byteLength-4,n,!1),o}function Vi(e,t){return(e<>>32-t)>>>0}function ct(e,t){return(e>>>t|e<<32-t)>>>0}function mf(e){let t=_l(e),n=1732584193,r=4023233417,s=2562383102,o=271733878,a=3285377520,l=new Uint32Array(80);for(let f=0;f>>0;y=g,g=p,p=Vi(m,30),m=u,u=E}n=n+u>>>0,r=r+m>>>0,s=s+p>>>0,o=o+g>>>0,a=a+y>>>0}let c=new Uint8Array(20),d=new DataView(c.buffer);return[n,r,s,o,a].forEach((f,u)=>d.setUint32(u*4,f,!1)),c}function gf(e){let t=_l(e),n=1779033703,r=3144134277,s=1013904242,o=2773480762,a=1359893119,l=2600822924,c=528734635,d=1541459225,f=new Uint32Array(64);for(let p=0;p>>3,U=ct(O,17)^ct(O,19)^O>>>10;f[v]=f[v-16]+N+f[v-7]+U>>>0}let g=n,y=r,h=s,S=o,_=a,E=l,b=c,x=d;for(let v=0;v<64;v++){let A=ct(_,6)^ct(_,11)^ct(_,25),O=_&E^~_&b,N=x+A+O+pf[v]+f[v]>>>0,U=ct(g,2)^ct(g,13)^ct(g,22),le=g&y^g&h^y&h,V=U+le>>>0;x=b,b=E,E=_,_=S+N>>>0,S=h,h=y,y=g,g=N+V>>>0}n=n+g>>>0,r=r+y>>>0,s=s+h>>>0,o=o+S>>>0,a=a+_>>>0,l=l+E>>>0,c=c+b>>>0,d=d+x>>>0}let u=new Uint8Array(32),m=new DataView(u.buffer);return[n,r,s,o,a,l,c,d].forEach((p,g)=>m.setUint32(g*4,p,!1)),u}function _f(e){let t="";for(let n of e)t+=gl[n>>4]+gl[n&15];return t}function hf(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function hn(e){let t=e.toLowerCase().replace("-","");if(t!=="sha1"&&t!=="sha256")throw new Error(`createHash: unsupported algorithm "${e}" in the browser build (sha1, sha256)`);let n=[],r=0,s={update(o){let a=uf(o);return n.push(a),r+=a.byteLength,s},digest(o){let a=r===0?new Uint8Array(0):ff(n,r),l=t==="sha1"?mf(a):gf(a);return o==="hex"?_f(l):o==="base64"?hf(l):l}};return s}var pf,gl,cs=F(()=>{k();pf=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);gl="0123456789abcdef"});function Me(e){return hn("sha1").update(e).digest("hex")}function yf(e,t=8){return Me(e).slice(0,t)}var At=F(()=>{"use strict";k();cs()});function ne(e,t,n,r){let s=[],o=t.split(/\r?\n/);for(let a=0;at.slice(0,m).split(/\r?\n/).length,l=new Map;for(let m of n)l.has(m.name)||l.set(m.name,m);let c=xf(t),d=/export\s*\{([\s\S]*?)\}\s*(?:from\s*['"]([^'"]+)['"])?\s*;?/g,f;for(;(f=d.exec(c))&&s.length{"use strict";k();bf={".ts":"typescript",".tsx":"typescript",".mts":"typescript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".go":"go",".rb":"ruby",".rake":"ruby",".java":"java",".rs":"rust",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".clj":"clojure",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".dart":"dart",".lua":"lua",".sh":"shell",".bash":"shell",".zsh":"shell",".ksh":"shell",".fish":"shell",".hh":"cpp",".m":"objective-c",".mm":"objective-c",".sql":"sql",".graphql":"graphql",".gql":"graphql",".proto":"protobuf",".md":"markdown",".mdx":"markdown",".rst":"restructuredtext",".txt":"text",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".html":"html",".css":"css",".scss":"scss",".vue":"vue",".svelte":"svelte",".astro":"astro",".zig":"zig",".hcl":"hcl",".tf":"terraform",".tfvars":"terraform",".sol":"solidity"};wf=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);ds=400});function vf(e){return(e.split("/").pop()??"").replace(/\.[^.]+$/,"")}function Rf(e,t){let n=o=>{if(!(!o||o==="default"))for(let a of t)a.name===o&&(a.exported=!0)},r=(o,a)=>{for(let l of o.split(",")){let c=l.trim().replace(/^type\s+/,"");if(!c)continue;let d=/^([\w$]+)\s+as\s+([\w$]+)$/.exec(c);if(d){d[2]!=="default"&&n(d[1]);continue}if(a){let f=/^([\w$]+)\s*:\s*([\w$]+)$/.exec(c);if(f){n(f[1]),n(f[2]);continue}}n(/^([\w$]+)/.exec(c)?.[1])}},s;for(hl.lastIndex=0;s=hl.exec(e);)s[2]||r(s[1]??"",!1);for(yl.lastIndex=0;s=yl.exec(e);)r(s[1]??"",!0);for(bl.lastIndex=0;s=bl.exec(e);)n(s[2])}var Sf,kf,Ef,hl,yl,bl,wl,xl=F(()=>{"use strict";k();ve();Sf=[{re:/^\s*export\s+(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!0},{re:/^\s*export\s+default\s+(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!0},{re:/^\s*export\s+default\s+(?:abstract\s+)?class\s+(?!extends\b)(?[\w$]+)/,kind:"class",exported:!0},{re:/^\s*(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!1},{re:/^\s*export\s+(?:abstract\s+)?class\s+(?[\w$]+)/,kind:"class",exported:!0},{re:/^\s*(?:abstract\s+)?class\s+(?[\w$]+)/,kind:"class",exported:!1},{re:/^\s*export\s+interface\s+(?[\w$]+)/,kind:"interface",exported:!0},{re:/^\s*interface\s+(?[\w$]+)/,kind:"interface",exported:!1},{re:/^\s*export\s+type\s+(?[\w$]+)/,kind:"type",exported:!0},{re:/^\s*type\s+(?[\w$]+)\s*[=<]/,kind:"type",exported:!1},{re:/^\s*export\s+enum\s+(?[\w$]+)/,kind:"enum",exported:!0},{re:/^\s*export\s+const\s+enum\s+(?[\w$]+)/,kind:"enum",exported:!0},{re:/^\s*export\s+(?:const|let|var)\s+(?[\w$]+)\s*[:=]/,kind:"const",exported:!0},{re:/^\s*exports\.(?[\w$]+)\s*=/,kind:"const",exported:!0},{re:/^\s*module\.exports\.(?[\w$]+)\s*=/,kind:"const",exported:!0},{re:/^\s*(?:const|let)\s+(?[\w$]+)\s*=\s*(?:async\s*)?\([^)]*\)\s*(?::[^=]+)?=>/,kind:"const",exported:!1},{re:/^(?:const|let|var)\s+(?[\w$]+)\s*[:=]/,kind:"const",exported:!1},{re:/^\s*export\s+default\s+(?[A-Za-z_$][\w$]*)\s*;?\s*$/,kind:"default",exported:!0}],kf=/^\s*export\s+default\s+(?:async\s+)?(?:function|class)?\s*(?:\(|\{|extends\b)/,Ef=/^\s*export\s+default\s+(?:async\s+)?(?:function|class)\s+(?!extends\b)[\w$]+/;hl=/export\s*\{([^}]*)\}\s*(from\b)?/g,yl=/module\.exports\s*=\s*\{([^}]*)\}/g,bl=/(^|\n)\s*export\s+default\s+([A-Za-z_$][\w$]*)\s*;?\s*(?=\n|$)/g;wl={lang:"javascript/typescript",exts:[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],extract(e,t){let n=e.match(/\.(ts|tsx|mts|cts)$/)?"typescript":"javascript",r=ne(e,t,n,Sf),s=t.split(/\r?\n/);for(let o=0;o{"use strict";k();ve();ms=e=>!e.startsWith("_")||e.startsWith("__"),Mf=[{re:/^(?:async\s+)?def\s+(?[\w]+)\s*\(/,kind:"function",exported:e=>ms(e.groups.name)},{re:/^\s+(?:async\s+)?def\s+(?[\w]+)\s*\(/,kind:"method",exported:e=>ms(e.groups.name)},{re:/^class\s+(?[\w]+)/,kind:"class",exported:e=>ms(e.groups.name)},{re:/^\s+class\s+(?[\w]+)/,kind:"class",exported:e=>ms(e.groups.name)}],Sl={lang:"python",exts:[".py",".pyi"],extract(e,t){return ne(e,t,"python",Mf)}}});var jn,Cf,El,vl=F(()=>{"use strict";k();ve();jn=e=>/^[A-Z]/.test(e),Cf=[{re:/^func\s+\([^)]*\)\s+(?[\w]+)\s*\(/,kind:"method",exported:e=>jn(e.groups.name)},{re:/^func\s+(?[\w]+)\s*\(/,kind:"function",exported:e=>jn(e.groups.name)},{re:/^type\s+(?[\w]+)\s+struct\b/,kind:"struct",exported:e=>jn(e.groups.name)},{re:/^type\s+(?[\w]+)\s+interface\b/,kind:"interface",exported:e=>jn(e.groups.name)},{re:/^type\s+(?[\w]+)\s+/,kind:"type",exported:e=>jn(e.groups.name)}],El={lang:"go",exts:[".go"],extract(e,t){return ne(e,t,"go",Cf)}}});var Af,Rl,Ml=F(()=>{"use strict";k();ve();Af=[{re:/^\s*def\s+(?:self\.)?(?[\w?!=]+)/,kind:"method",exported:!0},{re:/^\s*class\s+(?[\w:]+)/,kind:"class",exported:!0},{re:/^\s*module\s+(?[\w:]+)/,kind:"module",exported:!0}],Rl={lang:"ruby",exts:[".rb",".rake"],extract(e,t){return ne(e,t,"ruby",Af)}}});var Tf,Cl,Al=F(()=>{"use strict";k();ve();Tf=[{re:/^\s*(?:public|protected|private)?\s*(?:abstract\s+|final\s+)?class\s+(?[\w]+)/,kind:"class",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)?\s*interface\s+(?[\w]+)/,kind:"interface",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)?\s*enum\s+(?[\w]+)/,kind:"enum",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)\s+(?:static\s+|final\s+|abstract\s+|synchronized\s+)*[\w<>\[\],.?\s]+\s+(?[\w]+)\s*\(/,kind:"method",exported:(e,t)=>/\bpublic\b/.test(t)}],Cl={lang:"java",exts:[".java"],extract(e,t){return ne(e,t,"java",Tf)}}});var Wn,If,Tl,Il=F(()=>{"use strict";k();ve();Wn=(e,t)=>/^\s*pub\b/.test(t),If=[{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(?[\w]+)/,kind:"function",exported:Wn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+(?[\w]+)/,kind:"struct",exported:Wn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?enum\s+(?[\w]+)/,kind:"enum",exported:Wn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?trait\s+(?[\w]+)/,kind:"trait",exported:Wn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?type\s+(?[\w]+)/,kind:"type",exported:Wn}],Tl={lang:"rust",exts:[".rs"],extract(e,t){return ne(e,t,"rust",If)}}});var Un,Nf,Nl,Ol=F(()=>{"use strict";k();ve();Un=(e,t)=>/\b(public|internal)\b/.test(t),Nf=[{re:/^\s*(?:public|internal|protected|private)?\s*(?:static\s+|sealed\s+|abstract\s+|partial\s+)*(?:class|record)\s+(?\w+)/,kind:"class",exported:Un},{re:/^\s*(?:public|internal|protected|private)?\s*(?:partial\s+)?interface\s+(?\w+)/,kind:"interface",exported:Un},{re:/^\s*(?:public|internal|protected|private)?\s*(?:readonly\s+)?(?:ref\s+)?struct\s+(?\w+)/,kind:"struct",exported:Un},{re:/^\s*(?:public|internal|protected|private)?\s*enum\s+(?\w+)/,kind:"enum",exported:Un},{re:/^\s*(?:public|internal|protected|private)\s+(?:static\s+|virtual\s+|override\s+|async\s+|sealed\s+|abstract\s+|new\s+)*[\w<>\[\],.?]+\s+(?\w+)\s*(?:<[^>]*>)?\s*\(/,kind:"method",exported:Un}],Nl={lang:"csharp",exts:[".cs"],extract(e,t){return ne(e,t,"csharp",Nf)}}});var Of,Fl,Pl=F(()=>{"use strict";k();ve();Of=[{re:/^\s*(?:abstract\s+|final\s+)*class\s+(?\w+)/,kind:"class",exported:!0},{re:/^\s*interface\s+(?\w+)/,kind:"interface",exported:!0},{re:/^\s*trait\s+(?\w+)/,kind:"trait",exported:!0},{re:/^\s*enum\s+(?\w+)/,kind:"enum",exported:!0},{re:/^\s*(?:public\s+|protected\s+|private\s+|static\s+|abstract\s+|final\s+)*function\s+(?\w+)\s*\(/,kind:"function",exported:(e,t)=>!/\b(private|protected)\b/.test(t)}],Fl={lang:"php",exts:[".php"],extract(e,t){return ne(e,t,"php",Of)}}});var Bn,ps,Ff,$l,Ll=F(()=>{"use strict";k();ve();Bn=(e,t)=>!/\b(private|fileprivate)\b/.test(t),ps="(?:public\\s+|open\\s+|internal\\s+|private\\s+|fileprivate\\s+)?(?:final\\s+)?",Ff=[{re:new RegExp(`^\\s*${ps}class\\s+(?\\w+)`),kind:"class",exported:Bn},{re:new RegExp(`^\\s*${ps}struct\\s+(?\\w+)`),kind:"struct",exported:Bn},{re:new RegExp(`^\\s*${ps}enum\\s+(?\\w+)`),kind:"enum",exported:Bn},{re:new RegExp(`^\\s*${ps}protocol\\s+(?\\w+)`),kind:"protocol",exported:Bn},{re:/^\s*(?:public\s+|open\s+|internal\s+|private\s+|fileprivate\s+)?(?:static\s+|class\s+|final\s+|override\s+|mutating\s+|@\w+\s+)*func\s+(?\w+)/,kind:"function",exported:Bn}],$l={lang:"swift",exts:[".swift"],extract(e,t){return ne(e,t,"swift",Ff)}}});var gs,Pf,Dl,jl=F(()=>{"use strict";k();ve();gs=(e,t)=>!/\b(private|internal)\b/.test(t),Pf=[{re:/^\s*(?:public\s+|internal\s+|private\s+|abstract\s+|sealed\s+|open\s+|final\s+|data\s+)*class\s+(?\w+)/,kind:"class",exported:gs},{re:/^\s*(?:public\s+|internal\s+|private\s+|fun\s+)?interface\s+(?\w+)/,kind:"interface",exported:gs},{re:/^\s*(?:public\s+|internal\s+|private\s+|companion\s+)?object\s+(?\w+)/,kind:"object",exported:gs},{re:/^\s*(?:public\s+|internal\s+|private\s+|protected\s+|override\s+|open\s+|abstract\s+|suspend\s+|inline\s+|operator\s+)*fun\s+(?:<[^>]*>\s+)?(?\w+)\s*\(/,kind:"function",exported:gs}],Dl={lang:"kotlin",exts:[".kt",".kts"],extract(e,t){return ne(e,t,"kotlin",Pf)}}});var $f,Lf,Wl,Ul=F(()=>{"use strict";k();ve();$f="(?!\\s*(?:if|for|while|switch|return|else|do|sizeof|typedef)\\b)",Lf=[{re:/^\s*(?:class|struct)\s+(?[A-Za-z_]\w+)\s*(?:[:{]|$)/,kind:"class",exported:!0},{re:/^\s*namespace\s+(?[A-Za-z_]\w+)/,kind:"namespace",exported:!0},{re:/^\s*(?:typedef\s+)?(?:struct|enum|union)\s+(?[A-Za-z_]\w+)\s*\{/,kind:"struct",exported:!0},{re:new RegExp(`^${$f}[A-Za-z_][\\w\\s\\*&<>:,]*?\\b(?[A-Za-z_]\\w+)\\s*\\([^;{]*\\)\\s*(?:const)?\\s*\\{?\\s*$`),kind:"function",exported:!0}],Wl={lang:"c/cpp",exts:[".c",".h",".cc",".cpp",".cxx",".hpp",".hh"],extract(e,t){return ne(e,t,e.match(/\.(c|h)$/)?"c":"cpp",Lf)}}});var Df,Bl,zl=F(()=>{"use strict";k();ve();Df=[{re:/^\s*local\s+function\s+(?[\w.:]+)\s*\(/,kind:"function",exported:!1},{re:/^\s*function\s+(?[\w.:]+)\s*\(/,kind:"function",exported:!0},{re:/^\s*(?:local\s+)?(?[\w.]+)\s*=\s*function\s*\(/,kind:"function",exported:!0}],Bl={lang:"lua",exts:[".lua"],extract(e,t){return ne(e,t,"lua",Df)}}});var jf,Hl,ql=F(()=>{"use strict";k();ve();jf=[{re:/^\s*function\s+(?[\w:-]+)\s*(?:\(\))?\s*\{?/,kind:"function",exported:!0},{re:/^\s*(?[A-Za-z_][\w:-]*)\s*\(\)\s*\{?/,kind:"function",exported:!0}],Hl={lang:"shell",exts:[".sh",".bash",".zsh",".ksh"],extract(e,t){return ne(e,t,"shell",jf)}}});var Wf,Gl,Vl=F(()=>{"use strict";k();ve();Wf=[{re:/^\s*defmodule\s+(?[\w.]+)/,kind:"module",exported:!0},{re:/^\s*defp\s+(?[\w?!]+)/,kind:"function",exported:!1},{re:/^\s*def\s+(?[\w?!]+)/,kind:"function",exported:!0},{re:/^\s*defmacrop?\s+(?[\w?!]+)/,kind:"macro",exported:!0}],Gl={lang:"elixir",exts:[".ex",".exs"],extract(e,t){return ne(e,t,"elixir",Wf)}}});var Uf,Jl,Kl=F(()=>{"use strict";k();ve();Uf=[{re:/^\s*(?:final\s+|sealed\s+|abstract\s+|implicit\s+)*(?:case\s+)?class\s+(?\w+)/,kind:"class",exported:!0},{re:/^\s*(?:sealed\s+)?trait\s+(?\w+)/,kind:"trait",exported:!0},{re:/^\s*(?:case\s+)?object\s+(?\w+)/,kind:"object",exported:!0},{re:/^\s*(?:override\s+|final\s+|private\s+|protected\s+|implicit\s+)*def\s+(?\w+)/,kind:"def",exported:(e,t)=>!/\b(private|protected)\b/.test(t)}],Jl={lang:"scala",exts:[".scala",".sc"],extract(e,t){return ne(e,t,"scala",Uf)}}});var Tt,Bf,Xl,Zl=F(()=>{"use strict";k();ve();Tt=e=>!(e.groups?.name??"").startsWith("_"),Bf=[{re:/^\s*(?:abstract\s+|base\s+|final\s+|sealed\s+|interface\s+)*class\s+(?\w+)/,kind:"class",exported:Tt},{re:/^\s*mixin\s+(?\w+)/,kind:"mixin",exported:Tt},{re:/^\s*extension\s+(?\w+)/,kind:"extension",exported:Tt},{re:/^\s*enum\s+(?\w+)/,kind:"enum",exported:Tt},{re:/^\s*typedef\s+(?\w+)/,kind:"type",exported:Tt},{re:/^\s*(?:@\w+\s+)*(?:static\s+|final\s+|const\s+|external\s+|abstract\s+)*(?:[\w<>,?\[\]. ]+\s+)?(?\w+)\s*\([^)]*\)\s*(?:async\s*\*?\s*)?(?:=>|\{|;)/,kind:"function",exported:Tt},{re:/^\s*(?:static\s+)?[\w<>,?\[\]. ]+\s+get\s+(?\w+)/,kind:"getter",exported:Tt},{re:/^\s*(?:static\s+)?set\s+(?\w+)\s*\(/,kind:"setter",exported:Tt}],Xl={lang:"dart",exts:[".dart"],extract(e,t){return ne(e,t,"dart",Bf)}}});function Ki(e,t,n){let r=Ji.get(t),s;if(!r)s=[];else try{s=r.extract(e,n)}catch{s=[]}let o=new Set(s.map(l=>l.name)),a=us(e,n,s).filter(l=>!o.has(l.name));return a.length?[...s,...a]:s}function Xi(e){return Ji.get(e)?.lang??Vt(e)}var zf,Ji,yn=F(()=>{"use strict";k();ve();xl();kl();vl();Ml();Al();Il();Ol();Pl();Ll();jl();Ul();zl();ql();Vl();Kl();Zl();zf=[wl,Sl,El,Rl,Cl,Tl,Nl,Fl,$l,Dl,Wl,Bl,Hl,Gl,Jl,Xl],Ji=new Map;for(let e of zf)for(let t of e.exts)Ji.set(t,e)});function Yl(e,t){let n=e.split("/").pop().toLowerCase();return qf.has(t)||Hf.test(n)||Gf.test(e)}function Kf(e,t){let n=e.split("/").pop().toLowerCase();return Vf.has(n)||Jf.has(t)}function Ql(e){return!Xf.has(Xi(e))}function zn(e,t){return Ql(t)?"code":Yl(e,t)?"doc":Kf(e,t)?"config":"other"}var Hf,qf,Gf,Vf,Jf,Zi,Xf,_s=F(()=>{"use strict";k();yn();Hf=/^(readme|changelog|contributing|history|news|authors|notice|security|code_of_conduct|faq|getting[-_]?started|usage|guide|tutorial)\b/i,qf=new Set([".md",".mdx",".rst",".adoc",".txt"]),Gf=/^(docs?|documentation|wiki|guides?|website|site|book)\//i,Vf=new Set(["package.json","pnpm-workspace.yaml","tsconfig.json","jsconfig.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","pipfile","go.mod","cargo.toml","gemfile","pom.xml","build.gradle","build.gradle.kts","composer.json","mix.exs","pubspec.yaml","build.sbt","dockerfile","docker-compose.yml","docker-compose.yaml","makefile",".env.example","manifest.json"]),Jf=new Set([".json",".yaml",".yml",".toml",".ini",".cfg"]),Zi=new Set([".md",".mdx"]);Xf=new Set(["markdown","restructuredtext","text","json","yaml","toml","ini","other","html","css","scss"])});function Zf(e){let t="";for(let n=0;nt.some(r=>r.test(n))}function ec(e){if(!e||e.length===0)return null;let t=yt(e.filter(r=>!r.startsWith("!"))),n=yt(e.filter(r=>r.startsWith("!")).map(r=>r.slice(1)));return r=>(!t||t(r))&&!n?.(r)}var Hn=F(()=>{"use strict";k();Ce()});function M(e,t){return et?1:0}function Yi(e){return(t,n)=>M(e(t),e(n))}var Y=F(()=>{"use strict";k()});function Yf(e){let t=e.split(/\r?\n/),n=[],r=null;for(let s of t){let o=/^\s*(```+|~~~+)/.exec(s);if(r){o&&s.trim().startsWith(r[0][0].repeat(3).slice(0,3))&&(r=null),n.push("");continue}if(o){r=o[1],n.push("");continue}n.push(s)}return n.join(` -`)}function Qf(e){return!e||e.startsWith("#")||e.startsWith("//")?!0:/^[a-z][a-z0-9+.-]*:/i.test(e)}function tc(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,"").replace(/`([^`]*)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[#>*_~-]+/g," ").replace(/\s+/g," ").trim()}function em(e){return/[A-Za-zÀ-ɏ]{3,}/.test(e)}function tm(e){return/^(all notable changes to this project|in the interest of fostering|this project adheres to|we as members and leaders|table of contents)\b/i.test(e)}function Qi(e){let t=e,n,r=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(t);if(r){let h=/(^|\n)title:\s*["']?(.+?)["']?\s*(\n|$)/i.exec(r[1]);h&&(n=h[2].trim()),t=t.slice(r[0].length)}let s=Yf(t),o=s.split(/\r?\n/),a=[],l=n,c,d=!1;for(let h of o){let S=/^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(h);if(S){let _=tc(S[2]);a.push(_),!l&&S[1].length===1&&(l=_),!c&&S[1].length>=2&&(d=!0);continue}if(!c&&!d){let _=h.trim();if(_&&!/^([-*+]|\d+\.)\s/.test(_)&&!_.startsWith("|")&&!_.startsWith("<")){let E=tc(_);E.length>=8&&em(E)&&!E.endsWith(":")&&!tm(E)&&(c=E.slice(0,200))}}}let f=[],u=new Set,m=h=>{let S=h.trim();S=S.replace(/\s+["'(].*$/,"").trim(),S=S.replace(/^<|>$/g,""),!Qf(S)&&(u.has(S)||(u.add(S),f.push({kind:"doc-link",spec:S})))},p=/!?\[[^\]]*\]\(([^)]+)\)/g,g;for(;g=p.exec(s);)m(g[1]);let y=/^\s*\[[^\]]+\]:\s+(\S+)/gm;for(;g=y.exec(s);)m(g[1]);return{title:l,summary:c,headings:a,refs:f}}var eo=F(()=>{"use strict";k()});function om(e){return e.lengthnc?!1:im.test(e)}function am(e){let t=e.trim();return!t||t.length>nc||sm.has(t)?!1:Number.isFinite(Number(t))}function lm(e){let t=e,n=/^(?:[rRbBuUfF]{1,2}|@|\$)?(?:#*)?(['"`])/.exec(t);if(n){let r=n[1],s=t.indexOf(r),o=t.lastIndexOf(r);o>s&&(t=t.slice(s+1,o))}return t}var nc,nm,rm,sm,im,It,hs=F(()=>{"use strict";k();Y();nc=80,nm=2,rm=256,sm=new Set(["0","1","-1","2","-2"]),im=/[\p{L}\p{N}]/u;It=class{seen=new Set;out=[];get full(){return this.out.length>=rm}add(t,n,r){if(this.full||t==="string"&&!om(n)||t==="number"&&!am(n)||t==="regex"&&!n)return;let s=`${t}\0${n}\0${r}`;this.seen.has(s)||(this.seen.add(s),this.out.push({value:n,line:r,kind:t}))}addString(t,n){this.add("string",lm(t),n)}result(){if(this.out.length)return this.out.sort((t,n)=>M(t.value,n.value)||t.line-n.line||M(t.kind,n.kind))}}});function rc(){return"/home"}function ys(){return typeof navigator<"u"&&navigator?.hardwareConcurrency?navigator.hardwareConcurrency:1}function sc(){return Array.from({length:ys()},()=>({model:"browser",speed:0,times:{user:0,nice:0,sys:0,idle:0,irq:0}}))}var to=F(()=>{k()});function bs(e){let t=typeof e=="string"?e:e.href;try{return decodeURIComponent(new URL(t).pathname)}catch{return t}}function qn(e){return new URL(`file://${e.startsWith("/")?"":"/"}${e}`)}var ws=F(()=>{k()});var no={};Oi(no,{createRequire:()=>dm,default:()=>um});var dm,um,ro=F(()=>{k();dm=()=>{throw new Error("node-only API in the browser build")},um={}});function bn(e){if(e!==Nt)throw new Error("Illegal constructor")}function Vn(e){return!!e&&typeof e.row=="number"&&typeof e.column=="number"}function ac(e){w=e}function co(e,t,n,r){let s=n-t,o=e.textCallback(t,r);if(o){for(t+=o.length;t0)t+=a.length,o+=a;else break}t>n&&(o=o.slice(0,s))}return o??""}function lo(e,t,n,r,s){for(let o=0,a=s.length;o>>0,column:w.getValue(e+W,"i32")>>>0}}function cc(e,t){Ve(e,t.startPosition),e+=dt,Ve(e,t.endPosition),e+=dt,w.setValue(e,t.startIndex,"i32"),e+=W,w.setValue(e,t.endIndex,"i32"),e+=W}function xs(e){let t={};return t.startPosition=Jt(e),e+=dt,t.endPosition=Jt(e),e+=dt,t.startIndex=w.getValue(e,"i32")>>>0,e+=W,t.endIndex=w.getValue(e,"i32")>>>0,t}function dc(e,t=D){Ve(t,e.startPosition),t+=dt,Ve(t,e.oldEndPosition),t+=dt,Ve(t,e.newEndPosition),t+=dt,w.setValue(t,e.startIndex,"i32"),t+=W,w.setValue(t,e.oldEndIndex,"i32"),t+=W,w.setValue(t,e.newEndIndex,"i32"),t+=W}function uc(e){let t=w.getValue(e,"i32"),n=w.getValue(e+=W,"i32"),r=w.getValue(e+=W,"i32");return{major_version:t,minor_version:n,patch_version:r}}async function mc(moduleArg={}){var moduleRtn,Module=moduleArg,ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope<"u",ENVIRONMENT_IS_NODE=typeof R=="object"&&R.versions?.node&&R.type!="renderer";if(ENVIRONMENT_IS_NODE){let{createRequire:e}=await Promise.resolve().then(()=>(ro(),no));var require=e(import.meta.url)}Module.currentQueryProgressCallback=null,Module.currentProgressCallback=null,Module.currentLogCallback=null,Module.currentParseCallback=null;var arguments_=[],thisProgram="./this.program",quit_=C((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}C(locateFile,"locateFile");var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");_scriptName.startsWith("file:")&&(scriptDirectory=require("path").dirname(require("url").fileURLToPath(_scriptName))+"/"),readBinary=C(e=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=C(async(e,t=!0)=>{e=isFileURI(e)?new URL(e):e;var n=fs.readFileSync(e,t?void 0:"utf8");return n},"readAsync"),R.argv.length>1&&(thisProgram=R.argv[1].replace(/\\/g,"/")),arguments_=R.argv.slice(2),quit_=C((e,t)=>{throw R.exitCode=e,t},"quit_")}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}ENVIRONMENT_IS_WORKER&&(readBinary=C(e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary")),readAsync=C(async e=>{if(isFileURI(e))return new Promise((n,r)=>{var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=()=>{if(s.status==200||s.status==0&&s.response){n(s.response);return}r(s.status)},s.onerror=r,s.send(null)});var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)},"readAsync")}var out=console.log.bind(console),err=console.error.bind(console),dynamicLibraries=[],wasmBinary,ABORT=!1,EXITSTATUS,isFileURI=C(e=>e.startsWith("file://"),"isFileURI"),readyPromiseResolve,readyPromiseReject,wasmMemory,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64,HEAPU64,HEAP_DATA_VIEW,runtimeInitialized=!1;function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e),Module.HEAP64=HEAP64=new BigInt64Array(e),Module.HEAPU64=HEAPU64=new BigUint64Array(e),Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(e),LE_HEAP_UPDATE()}C(updateMemoryViews,"updateMemoryViews");function initMemory(){if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var e=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:e/65536,maximum:32768})}updateMemoryViews()}C(initMemory,"initMemory");var __RELOC_FUNCS__=[];function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(onPreRuns)}C(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}C(initRuntime,"initRuntime");function preMain(){}C(preMain,"preMain");function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(onPostRuns)}C(postRun,"postRun");function abort(e){Module.onAbort?.(e),e="Aborted("+e+")",err(e),ABORT=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw readyPromiseReject?.(t),t}C(abort,"abort");var wasmBinaryFile;function findWasmBinary(){return Module.locateFile?locateFile("web-tree-sitter.wasm"):new URL("web-tree-sitter.wasm",import.meta.url).href}C(findWasmBinary,"findWasmBinary");function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}C(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}C(getWasmBinary,"getWasmBinary");async function instantiateArrayBuffer(e,t){try{var n=await getWasmBinary(e),r=await WebAssembly.instantiate(n,t);return r}catch(s){err(`failed to asynchronously prepare wasm: ${s}`),abort(s)}}C(instantiateArrayBuffer,"instantiateArrayBuffer");async function instantiateAsync(e,t,n){if(!e&&!isFileURI(t)&&!ENVIRONMENT_IS_NODE)try{var r=fetch(t,{credentials:"same-origin"}),s=await WebAssembly.instantiateStreaming(r,n);return s}catch(o){err(`wasm streaming compile failed: ${o}`),err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(t,n)}C(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}C(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var l=getDylinkMetadata(a);return l.neededDynlibs&&(dynamicLibraries=l.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}C(e,"receiveInstance");function t(o){return e(o.instance,o.module)}C(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(l,c)=>{o(e(l,c))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}C(createWasm,"createWasm");class ExitStatus{static{C(this,"ExitStatus")}name="ExitStatus";constructor(t){this.message=`Program terminated with exit(${t})`,this.status=t}}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(e,t){var n=GOT[t];return n||(n=GOT[t]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(t)||(n.required=!0),n}},LE_ATOMICS_NATIVE_BYTE_ORDER=[],LE_HEAP_LOAD_F32=C(e=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=C(e=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=C(e=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=C(e=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=C(e=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=C(e=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=C((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=C((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=C((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=C((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=C((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=C((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=C(e=>{for(;e.length>0;)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=C(e=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=C(e=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=C((e,t,n,r)=>{var s=t+n;if(r)return s;for(;e[t]&&!(t>=s);)++t;return t},"findStringEnd"),UTF8ArrayToString=C((e,t=0,n,r)=>{var s=findStringEnd(e,t,n,r);if(s-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,s));for(var o="";t>10,56320|d&1023)}}return o},"UTF8ArrayToString"),getDylinkMetadata=C(e=>{var t=0,n=0;function r(){return e[t++]}C(r,"getU8");function s(){for(var V=0,z=1;;){var P=e[t++];if(V+=(P&127)*z,z*=128,!(P&128))break}return V}C(s,"getLEB");function o(){var V=s();return t+=V,UTF8ArrayToString(e,t-V,V)}C(o,"getString");function a(){for(var V=s(),z=[];V--;)z.push(o());return z}C(a,"getStringList");function l(V,z){if(V)throw new Error(z)}if(C(l,"failIf"),e instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(e,"dylink.0");l(c.length===0,"need dylink section"),e=new Uint8Array(c[0]),n=e.length}else{var d=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),f=d[0]==1836278016||d[0]==6386541;l(!f,"need to see wasm magic number"),l(e[8]!==0,"need the dylink section to be first"),t=9;var u=s();n=t+u;var m=o();l(m!=="dylink.0")}for(var p={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},g=1,y=2,h=3,S=4,_=5,E=256,b=3,x=1;t>1)*2);case"i32":return LE_HEAP_LOAD_I32((e>>2)*4);case"i64":return LE_HEAP_LOAD_I64((e>>3)*8);case"float":return LE_HEAP_LOAD_F32((e>>2)*4);case"double":return LE_HEAP_LOAD_F64((e>>3)*8);case"*":return LE_HEAP_LOAD_U32((e>>2)*4);default:abort(`invalid type for getValue: ${t}`)}}C(getValue,"getValue");var newDSO=C((e,t,n)=>{var r={refcount:1/0,name:e,exports:n,global:!0};return LDSO.loadedLibsByName[e]=r,t!=null&&(LDSO.loadedLibsByHandle[t]=r),r},"newDSO"),LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78240,alignMemory=C((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=C(e=>{if(runtimeInitialized)return _calloc(e,1);var t=___heap_base,n=t+alignMemory(e,16);return ___heap_base=n,GOT.__heap_base.value=n,t},"getMemory"),isInternalSym=C(e=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(e)||e.startsWith("__em_js__"),"isInternalSym"),uleb128EncodeWithLen=C(e=>{let t=e.length;return[t%128|128,t>>7,...e]},"uleb128EncodeWithLen"),wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111},generateTypePack=C(e=>uleb128EncodeWithLen(Array.from(e,t=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=C((e,t)=>{var n=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(t.slice(1)),...generateTypePack(t[0]==="v"?"":t[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),r=new WebAssembly.Module(n),s=new WebAssembly.Instance(r,{e:{f:e}}),o=s.exports.f;return o},"convertJsFunctionToWasm"),wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:31,element:"anyfunc"}),getWasmTableEntry=C(e=>{var t=wasmTableMirror[e];return t||(wasmTableMirror[e]=t=wasmTable.get(e)),t},"getWasmTableEntry"),updateTableMap=C((e,t)=>{if(functionsInTableMap)for(var n=e;n(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=C(()=>freeTableIndexes.length?freeTableIndexes.pop():wasmTable.grow(1),"getEmptyTableSlot"),setWasmTableEntry=C((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=C((e,t)=>{var n=getFunctionAddress(e);if(n)return n;var r=getEmptyTableSlot();try{setWasmTableEntry(r,e)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(e,t);setWasmTableEntry(r,s)}return functionsInTableMap.set(e,r),r},"addFunction"),updateGOT=C((e,t)=>{for(var n in e)if(!isInternalSym(n)){var r=e[n];GOT[n]||=new WebAssembly.Global({value:"i32",mutable:!0}),(t||GOT[n].value==0)&&(typeof r=="function"?GOT[n].value=addFunction(r):typeof r=="number"?GOT[n].value=r:err(`unhandled export type for '${n}': ${typeof r}`))}},"updateGOT"),relocateExports=C((e,t,n)=>{var r={};for(var s in e){var o=e[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=t),r[s]=o}return updateGOT(r,n),r},"relocateExports"),isSymbolDefined=C(e=>{var t=wasmImports[e];return!(!t||t.stub)},"isSymbolDefined"),dynCall=C((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(l){return l}return C(a,"convert"),o},"dynCall"),stackSave=C(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=C(e=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=C(e=>(t,...n)=>{var r=stackSave();try{return dynCall(e,t,n)}catch(s){if(stackRestore(r),s!==s+0)throw s;if(_setThrew(1,0),e[0]=="j")return 0n}},"createInvokeFunction"),resolveGlobalSymbol=C((e,t=!1)=>{var n;return isSymbolDefined(e)?n=wasmImports[e]:e.startsWith("invoke_")&&(n=wasmImports[e]=createInvokeFunction(e.split("_")[1])),{sym:n,name:e}},"resolveGlobalSymbol"),onPostCtors=[],addOnPostCtor=C(e=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=C((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=C((binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);function loadModule(){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize)),metadata.tableSize&&wasmTable.grow(metadata.tableSize);var moduleExports;function resolveSymbol(e){var t=resolveGlobalSymbol(e).sym;return!t&&localScope&&(t=localScope[e]),t||(t=moduleExports[e]),t}C(resolveSymbol,"resolveSymbol");var proxyHandler={get(e,t){switch(t){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(t in wasmImports&&!wasmImports[t].stub){var n=wasmImports[t];return n}if(!(t in e)){var r;e[t]=(...s)=>(r||=resolveSymbol(t),r(...s))}return e[t]}},proxy=new Proxy({},proxyHandler);currentModuleWeakSymbols=metadata.weakImports;var info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if(C(addEmAsm,"addEmAsm"),"__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start ${body};`;moduleExports[name]=eval(func)}C(addEmJs,"addEmJs");for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():addOnPostCtor(init)),moduleExports}if(C(postInstantiation,"postInstantiation"),flags.loadAsync)return(async()=>{var e;return binary instanceof WebAssembly.Module?e=new WebAssembly.Instance(binary,info):{module:binary,instance:e}=await WebAssembly.instantiate(binary,info),postInstantiation(binary,e)})();var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return C(loadModule,"loadModule"),flags={...flags,rpath:{parentLibPath:libName,paths:metadata.runtimePaths}},flags.loadAsync?metadata.neededDynlibs.reduce((e,t)=>e.then(()=>loadDynamicLibrary(t,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(e=>loadDynamicLibrary(e,flags,localScope)),loadModule())},"loadWebAssemblyModule"),mergeLibSymbols=C((e,t)=>{for(var[n,r]of Object.entries(e)){let s=C(a=>{isSymbolDefined(a)||(wasmImports[a]=r)},"setImport");s(n);let o="__main_argc_argv";n=="main"&&s(o),n==o&&s("main")}},"mergeLibSymbols"),asyncLoad=C(async e=>{var t=await readAsync(e);return new Uint8Array(t)},"asyncLoad");function loadDynamicLibrary(e,t={global:!0,nodelete:!0},n,r){var s=LDSO.loadedLibsByName[e];if(s)return t.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,e)):n&&Object.assign(n,s.exports),t.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,r&&(LDSO.loadedLibsByHandle[r]=s),t.loadAsync?Promise.resolve(!0):!0;s=newDSO(e,r,"loading"),s.refcount=t.nodelete?1/0:1,s.global=t.global;function o(){if(r){var c=LE_HEAP_LOAD_U32((r+28>>2)*4),d=LE_HEAP_LOAD_U32((r+32>>2)*4);if(c&&d){var f=HEAP8.slice(c,c+d);return t.loadAsync?Promise.resolve(f):f}}var u=locateFile(e);if(t.loadAsync)return asyncLoad(u);if(!readBinary)throw new Error(`${u}: file not found, and synchronous loading of external files is not available`);return readBinary(u)}C(o,"loadLibData");function a(){return t.loadAsync?o().then(c=>loadWebAssemblyModule(c,t,e,n,r)):loadWebAssemblyModule(o(),t,e,n,r)}C(a,"getExports");function l(c){s.global?mergeLibSymbols(c,e):n&&Object.assign(n,c),s.exports=c}return C(l,"moduleLoaded"),t.loadAsync?a().then(c=>(l(c),!0)):(l(a()),!0)}C(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=C(()=>{for(var[e,t]of Object.entries(GOT))if(t.value==0){var n=resolveGlobalSymbol(e,!0).sym;if(!n&&!t.required)continue;if(typeof n=="function")t.value=addFunction(n,n.sig);else if(typeof n=="number")t.value=n;else throw new Error(`bad export type for '${e}': ${typeof n}`)}},"reportUndefinedSymbols"),runDependencies=0,dependenciesFulfilled=null,removeRunDependency=C(e=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}},"removeRunDependency"),addRunDependency=C(e=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=C(async()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs");for(var e of dynamicLibraries)await loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0});reportUndefinedSymbols(),removeRunDependency("loadDylibs")},"loadDylibs"),noExitRuntime=!0;function setValue(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":HEAP8[e]=t;break;case"i8":HEAP8[e]=t;break;case"i16":LE_HEAP_STORE_I16((e>>1)*2,t);break;case"i32":LE_HEAP_STORE_I32((e>>2)*4,t);break;case"i64":LE_HEAP_STORE_I64((e>>3)*8,BigInt(t));break;case"float":LE_HEAP_STORE_F32((e>>2)*4,t);break;case"double":LE_HEAP_STORE_F64((e>>3)*8,t);break;case"*":LE_HEAP_STORE_U32((e>>2)*4,t);break;default:abort(`invalid type for setValue: ${n}`)}}C(setValue,"setValue");var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_high=78240,___stack_low=12704,___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},78240),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=C(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=C(()=>2147483648,"getHeapMax"),growMemory=C(e=>{var t=wasmMemory.buffer.byteLength,n=(e-t+65535)/65536|0;try{return wasmMemory.grow(n),updateMemoryViews(),1}catch{}},"growMemory"),_emscripten_resize_heap=C(e=>{var t=HEAPU8.length;e>>>=0;var n=getHeapMax();if(e>n)return!1;for(var r=1;r<=4;r*=2){var s=t*(1+.2/r);s=Math.min(s,e+100663296);var o=Math.min(n,alignMemory(Math.max(e,s),65536)),a=growMemory(o);if(a)return!0}return!1},"_emscripten_resize_heap");_emscripten_resize_heap.sig="ip";var _fd_close=C(e=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=C(e=>eINT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}C(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=C((e,t)=>{var n=printCharBuffers[e];t===0||t===10?((e===1?out:err)(UTF8ArrayToString(n)),n.length=0):n.push(t)},"printChar"),_fd_write=C((e,t,n,r)=>{for(var s=0,o=0;o>2)*4),l=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var c=0;c>2)*4,s),0},"_fd_write");_fd_write.sig="iippp";function _tree_sitter_log_callback(e,t){if(Module.currentLogCallback){let n=UTF8ToString(t);Module.currentLogCallback(n,e!==0)}}C(_tree_sitter_log_callback,"_tree_sitter_log_callback");function _tree_sitter_parse_callback(e,t,n,r,s){let a=Module.currentParseCallback(t,{row:n,column:r});typeof a=="string"?(setValue(s,a.length,"i32"),stringToUTF16(a,e,10240)):setValue(s,0,"i32")}C(_tree_sitter_parse_callback,"_tree_sitter_parse_callback");function _tree_sitter_progress_callback(e,t){return Module.currentProgressCallback?Module.currentProgressCallback({currentOffset:e,hasError:t}):!1}C(_tree_sitter_progress_callback,"_tree_sitter_progress_callback");function _tree_sitter_query_progress_callback(e){return Module.currentQueryProgressCallback?Module.currentQueryProgressCallback({currentOffset:e}):!1}C(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=C(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=C(e=>{EXITSTATUS=e,keepRuntimeAlive()||(Module.onExit?.(e),ABORT=!0),quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=C((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=C(e=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=C(e=>{for(var t=0,n=0;n=55296&&r<=57343?(t+=4,++n):t+=3}return t},"lengthBytesUTF8"),stringToUTF8Array=C((e,t,n,r)=>{if(!(r>0))return 0;for(var s=n,o=n+r-1,a=0;a=o)break;t[n++]=l}else if(l<=2047){if(n+1>=o)break;t[n++]=192|l>>6,t[n++]=128|l&63}else if(l<=65535){if(n+2>=o)break;t[n++]=224|l>>12,t[n++]=128|l>>6&63,t[n++]=128|l&63}else{if(n+3>=o)break;t[n++]=240|l>>18,t[n++]=128|l>>12&63,t[n++]=128|l>>6&63,t[n++]=128|l&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=C((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=C(e=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=C(e=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=C(e=>{for(var t="";;){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=C((e,t,n)=>{if(n??=2147483647,n<2)return 0;n-=2;for(var r=t,s=n>1)*2,a),t+=2}return LE_HEAP_STORE_I16((t>>1)*2,0),t-r},"stringToUTF16");LE_ATOMICS_NATIVE_BYTE_ORDER=new Int8Array(new Int16Array([1]).buffer)[0]===1?[(e=>e),(e=>e),void 0,(e=>e)]:[(e=>e),(e=>((e&65280)<<8|(e&255)<<24)>>16),void 0,(e=>e>>24&255|e>>8&65280|(e&65280)<<8|(e&255)<<24)];function LE_HEAP_UPDATE(){HEAPU16.unsigned=(e=>e&65535),HEAPU32.unsigned=(e=>e>>>0)}if(C(LE_HEAP_UPDATE,"LE_HEAP_UPDATE"),initMemory(),Module.noExitRuntime&&(noExitRuntime=Module.noExitRuntime),Module.print&&(out=Module.print),Module.printErr&&(err=Module.printErr),Module.dynamicLibraries&&(dynamicLibraries=Module.dynamicLibraries),Module.wasmBinary&&(wasmBinary=Module.wasmBinary),Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.shift()();Module.setValue=setValue,Module.getValue=getValue,Module.UTF8ToString=UTF8ToString,Module.stringToUTF8=stringToUTF8,Module.lengthBytesUTF8=lengthBytesUTF8,Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16,Module.loadWebAssemblyModule=loadWebAssemblyModule,Module.LE_HEAP_STORE_I64=LE_HEAP_STORE_I64;var ASM_CONSTS={},_malloc,_calloc,_realloc,_free,_ts_range_edit,_memcmp,_ts_language_symbol_count,_ts_language_state_count,_ts_language_abi_version,_ts_language_name,_ts_language_field_count,_ts_language_next_state,_ts_language_symbol_name,_ts_language_symbol_for_name,_strncmp,_ts_language_symbol_type,_ts_language_field_name_for_id,_ts_lookahead_iterator_new,_ts_lookahead_iterator_delete,_ts_lookahead_iterator_reset_state,_ts_lookahead_iterator_reset,_ts_lookahead_iterator_next,_ts_lookahead_iterator_current_symbol,_ts_point_edit,_ts_parser_delete,_ts_parser_reset,_ts_parser_set_language,_ts_parser_set_included_ranges,_ts_query_new,_ts_query_delete,_iswspace,_iswalnum,_ts_query_pattern_count,_ts_query_capture_count,_ts_query_string_count,_ts_query_capture_name_for_id,_ts_query_capture_quantifier_for_id,_ts_query_string_value_for_id,_ts_query_predicates_for_pattern,_ts_query_start_byte_for_pattern,_ts_query_end_byte_for_pattern,_ts_query_is_pattern_rooted,_ts_query_is_pattern_non_local,_ts_query_is_pattern_guaranteed_at_step,_ts_query_disable_capture,_ts_query_disable_pattern,_ts_tree_copy,_ts_tree_delete,_ts_init,_ts_parser_new_wasm,_ts_parser_enable_logger_wasm,_ts_parser_parse_wasm,_ts_parser_included_ranges_wasm,_ts_language_type_is_named_wasm,_ts_language_type_is_visible_wasm,_ts_language_metadata_wasm,_ts_language_supertypes_wasm,_ts_language_subtypes_wasm,_ts_tree_root_node_wasm,_ts_tree_root_node_with_offset_wasm,_ts_tree_edit_wasm,_ts_tree_included_ranges_wasm,_ts_tree_get_changed_ranges_wasm,_ts_tree_cursor_new_wasm,_ts_tree_cursor_copy_wasm,_ts_tree_cursor_delete_wasm,_ts_tree_cursor_reset_wasm,_ts_tree_cursor_reset_to_wasm,_ts_tree_cursor_goto_first_child_wasm,_ts_tree_cursor_goto_last_child_wasm,_ts_tree_cursor_goto_first_child_for_index_wasm,_ts_tree_cursor_goto_first_child_for_position_wasm,_ts_tree_cursor_goto_next_sibling_wasm,_ts_tree_cursor_goto_previous_sibling_wasm,_ts_tree_cursor_goto_descendant_wasm,_ts_tree_cursor_goto_parent_wasm,_ts_tree_cursor_current_node_type_id_wasm,_ts_tree_cursor_current_node_state_id_wasm,_ts_tree_cursor_current_node_is_named_wasm,_ts_tree_cursor_current_node_is_missing_wasm,_ts_tree_cursor_current_node_id_wasm,_ts_tree_cursor_start_position_wasm,_ts_tree_cursor_end_position_wasm,_ts_tree_cursor_start_index_wasm,_ts_tree_cursor_end_index_wasm,_ts_tree_cursor_current_field_id_wasm,_ts_tree_cursor_current_depth_wasm,_ts_tree_cursor_current_descendant_index_wasm,_ts_tree_cursor_current_node_wasm,_ts_node_symbol_wasm,_ts_node_field_name_for_child_wasm,_ts_node_field_name_for_named_child_wasm,_ts_node_children_by_field_id_wasm,_ts_node_first_child_for_byte_wasm,_ts_node_first_named_child_for_byte_wasm,_ts_node_grammar_symbol_wasm,_ts_node_child_count_wasm,_ts_node_named_child_count_wasm,_ts_node_child_wasm,_ts_node_named_child_wasm,_ts_node_child_by_field_id_wasm,_ts_node_next_sibling_wasm,_ts_node_prev_sibling_wasm,_ts_node_next_named_sibling_wasm,_ts_node_prev_named_sibling_wasm,_ts_node_descendant_count_wasm,_ts_node_parent_wasm,_ts_node_child_with_descendant_wasm,_ts_node_descendant_for_index_wasm,_ts_node_named_descendant_for_index_wasm,_ts_node_descendant_for_position_wasm,_ts_node_named_descendant_for_position_wasm,_ts_node_start_point_wasm,_ts_node_end_point_wasm,_ts_node_start_index_wasm,_ts_node_end_index_wasm,_ts_node_to_string_wasm,_ts_node_children_wasm,_ts_node_named_children_wasm,_ts_node_descendants_of_type_wasm,_ts_node_is_named_wasm,_ts_node_has_changes_wasm,_ts_node_has_error_wasm,_ts_node_is_error_wasm,_ts_node_is_missing_wasm,_ts_node_is_extra_wasm,_ts_node_parse_state_wasm,_ts_node_next_parse_state_wasm,_ts_query_matches_wasm,_ts_query_captures_wasm,_memset,_memcpy,_memmove,_iswalpha,_iswblank,_iswdigit,_iswlower,_iswupper,_iswxdigit,_memchr,_strlen,_strcmp,_strncat,_strncpy,_towlower,_towupper,_setThrew,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___wasm_apply_data_relocs;function assignWasmExports(e){Module._malloc=_malloc=e.malloc,Module._calloc=_calloc=e.calloc,Module._realloc=_realloc=e.realloc,Module._free=_free=e.free,Module._ts_range_edit=_ts_range_edit=e.ts_range_edit,Module._memcmp=_memcmp=e.memcmp,Module._ts_language_symbol_count=_ts_language_symbol_count=e.ts_language_symbol_count,Module._ts_language_state_count=_ts_language_state_count=e.ts_language_state_count,Module._ts_language_abi_version=_ts_language_abi_version=e.ts_language_abi_version,Module._ts_language_name=_ts_language_name=e.ts_language_name,Module._ts_language_field_count=_ts_language_field_count=e.ts_language_field_count,Module._ts_language_next_state=_ts_language_next_state=e.ts_language_next_state,Module._ts_language_symbol_name=_ts_language_symbol_name=e.ts_language_symbol_name,Module._ts_language_symbol_for_name=_ts_language_symbol_for_name=e.ts_language_symbol_for_name,Module._strncmp=_strncmp=e.strncmp,Module._ts_language_symbol_type=_ts_language_symbol_type=e.ts_language_symbol_type,Module._ts_language_field_name_for_id=_ts_language_field_name_for_id=e.ts_language_field_name_for_id,Module._ts_lookahead_iterator_new=_ts_lookahead_iterator_new=e.ts_lookahead_iterator_new,Module._ts_lookahead_iterator_delete=_ts_lookahead_iterator_delete=e.ts_lookahead_iterator_delete,Module._ts_lookahead_iterator_reset_state=_ts_lookahead_iterator_reset_state=e.ts_lookahead_iterator_reset_state,Module._ts_lookahead_iterator_reset=_ts_lookahead_iterator_reset=e.ts_lookahead_iterator_reset,Module._ts_lookahead_iterator_next=_ts_lookahead_iterator_next=e.ts_lookahead_iterator_next,Module._ts_lookahead_iterator_current_symbol=_ts_lookahead_iterator_current_symbol=e.ts_lookahead_iterator_current_symbol,Module._ts_point_edit=_ts_point_edit=e.ts_point_edit,Module._ts_parser_delete=_ts_parser_delete=e.ts_parser_delete,Module._ts_parser_reset=_ts_parser_reset=e.ts_parser_reset,Module._ts_parser_set_language=_ts_parser_set_language=e.ts_parser_set_language,Module._ts_parser_set_included_ranges=_ts_parser_set_included_ranges=e.ts_parser_set_included_ranges,Module._ts_query_new=_ts_query_new=e.ts_query_new,Module._ts_query_delete=_ts_query_delete=e.ts_query_delete,Module._iswspace=_iswspace=e.iswspace,Module._iswalnum=_iswalnum=e.iswalnum,Module._ts_query_pattern_count=_ts_query_pattern_count=e.ts_query_pattern_count,Module._ts_query_capture_count=_ts_query_capture_count=e.ts_query_capture_count,Module._ts_query_string_count=_ts_query_string_count=e.ts_query_string_count,Module._ts_query_capture_name_for_id=_ts_query_capture_name_for_id=e.ts_query_capture_name_for_id,Module._ts_query_capture_quantifier_for_id=_ts_query_capture_quantifier_for_id=e.ts_query_capture_quantifier_for_id,Module._ts_query_string_value_for_id=_ts_query_string_value_for_id=e.ts_query_string_value_for_id,Module._ts_query_predicates_for_pattern=_ts_query_predicates_for_pattern=e.ts_query_predicates_for_pattern,Module._ts_query_start_byte_for_pattern=_ts_query_start_byte_for_pattern=e.ts_query_start_byte_for_pattern,Module._ts_query_end_byte_for_pattern=_ts_query_end_byte_for_pattern=e.ts_query_end_byte_for_pattern,Module._ts_query_is_pattern_rooted=_ts_query_is_pattern_rooted=e.ts_query_is_pattern_rooted,Module._ts_query_is_pattern_non_local=_ts_query_is_pattern_non_local=e.ts_query_is_pattern_non_local,Module._ts_query_is_pattern_guaranteed_at_step=_ts_query_is_pattern_guaranteed_at_step=e.ts_query_is_pattern_guaranteed_at_step,Module._ts_query_disable_capture=_ts_query_disable_capture=e.ts_query_disable_capture,Module._ts_query_disable_pattern=_ts_query_disable_pattern=e.ts_query_disable_pattern,Module._ts_tree_copy=_ts_tree_copy=e.ts_tree_copy,Module._ts_tree_delete=_ts_tree_delete=e.ts_tree_delete,Module._ts_init=_ts_init=e.ts_init,Module._ts_parser_new_wasm=_ts_parser_new_wasm=e.ts_parser_new_wasm,Module._ts_parser_enable_logger_wasm=_ts_parser_enable_logger_wasm=e.ts_parser_enable_logger_wasm,Module._ts_parser_parse_wasm=_ts_parser_parse_wasm=e.ts_parser_parse_wasm,Module._ts_parser_included_ranges_wasm=_ts_parser_included_ranges_wasm=e.ts_parser_included_ranges_wasm,Module._ts_language_type_is_named_wasm=_ts_language_type_is_named_wasm=e.ts_language_type_is_named_wasm,Module._ts_language_type_is_visible_wasm=_ts_language_type_is_visible_wasm=e.ts_language_type_is_visible_wasm,Module._ts_language_metadata_wasm=_ts_language_metadata_wasm=e.ts_language_metadata_wasm,Module._ts_language_supertypes_wasm=_ts_language_supertypes_wasm=e.ts_language_supertypes_wasm,Module._ts_language_subtypes_wasm=_ts_language_subtypes_wasm=e.ts_language_subtypes_wasm,Module._ts_tree_root_node_wasm=_ts_tree_root_node_wasm=e.ts_tree_root_node_wasm,Module._ts_tree_root_node_with_offset_wasm=_ts_tree_root_node_with_offset_wasm=e.ts_tree_root_node_with_offset_wasm,Module._ts_tree_edit_wasm=_ts_tree_edit_wasm=e.ts_tree_edit_wasm,Module._ts_tree_included_ranges_wasm=_ts_tree_included_ranges_wasm=e.ts_tree_included_ranges_wasm,Module._ts_tree_get_changed_ranges_wasm=_ts_tree_get_changed_ranges_wasm=e.ts_tree_get_changed_ranges_wasm,Module._ts_tree_cursor_new_wasm=_ts_tree_cursor_new_wasm=e.ts_tree_cursor_new_wasm,Module._ts_tree_cursor_copy_wasm=_ts_tree_cursor_copy_wasm=e.ts_tree_cursor_copy_wasm,Module._ts_tree_cursor_delete_wasm=_ts_tree_cursor_delete_wasm=e.ts_tree_cursor_delete_wasm,Module._ts_tree_cursor_reset_wasm=_ts_tree_cursor_reset_wasm=e.ts_tree_cursor_reset_wasm,Module._ts_tree_cursor_reset_to_wasm=_ts_tree_cursor_reset_to_wasm=e.ts_tree_cursor_reset_to_wasm,Module._ts_tree_cursor_goto_first_child_wasm=_ts_tree_cursor_goto_first_child_wasm=e.ts_tree_cursor_goto_first_child_wasm,Module._ts_tree_cursor_goto_last_child_wasm=_ts_tree_cursor_goto_last_child_wasm=e.ts_tree_cursor_goto_last_child_wasm,Module._ts_tree_cursor_goto_first_child_for_index_wasm=_ts_tree_cursor_goto_first_child_for_index_wasm=e.ts_tree_cursor_goto_first_child_for_index_wasm,Module._ts_tree_cursor_goto_first_child_for_position_wasm=_ts_tree_cursor_goto_first_child_for_position_wasm=e.ts_tree_cursor_goto_first_child_for_position_wasm,Module._ts_tree_cursor_goto_next_sibling_wasm=_ts_tree_cursor_goto_next_sibling_wasm=e.ts_tree_cursor_goto_next_sibling_wasm,Module._ts_tree_cursor_goto_previous_sibling_wasm=_ts_tree_cursor_goto_previous_sibling_wasm=e.ts_tree_cursor_goto_previous_sibling_wasm,Module._ts_tree_cursor_goto_descendant_wasm=_ts_tree_cursor_goto_descendant_wasm=e.ts_tree_cursor_goto_descendant_wasm,Module._ts_tree_cursor_goto_parent_wasm=_ts_tree_cursor_goto_parent_wasm=e.ts_tree_cursor_goto_parent_wasm,Module._ts_tree_cursor_current_node_type_id_wasm=_ts_tree_cursor_current_node_type_id_wasm=e.ts_tree_cursor_current_node_type_id_wasm,Module._ts_tree_cursor_current_node_state_id_wasm=_ts_tree_cursor_current_node_state_id_wasm=e.ts_tree_cursor_current_node_state_id_wasm,Module._ts_tree_cursor_current_node_is_named_wasm=_ts_tree_cursor_current_node_is_named_wasm=e.ts_tree_cursor_current_node_is_named_wasm,Module._ts_tree_cursor_current_node_is_missing_wasm=_ts_tree_cursor_current_node_is_missing_wasm=e.ts_tree_cursor_current_node_is_missing_wasm,Module._ts_tree_cursor_current_node_id_wasm=_ts_tree_cursor_current_node_id_wasm=e.ts_tree_cursor_current_node_id_wasm,Module._ts_tree_cursor_start_position_wasm=_ts_tree_cursor_start_position_wasm=e.ts_tree_cursor_start_position_wasm,Module._ts_tree_cursor_end_position_wasm=_ts_tree_cursor_end_position_wasm=e.ts_tree_cursor_end_position_wasm,Module._ts_tree_cursor_start_index_wasm=_ts_tree_cursor_start_index_wasm=e.ts_tree_cursor_start_index_wasm,Module._ts_tree_cursor_end_index_wasm=_ts_tree_cursor_end_index_wasm=e.ts_tree_cursor_end_index_wasm,Module._ts_tree_cursor_current_field_id_wasm=_ts_tree_cursor_current_field_id_wasm=e.ts_tree_cursor_current_field_id_wasm,Module._ts_tree_cursor_current_depth_wasm=_ts_tree_cursor_current_depth_wasm=e.ts_tree_cursor_current_depth_wasm,Module._ts_tree_cursor_current_descendant_index_wasm=_ts_tree_cursor_current_descendant_index_wasm=e.ts_tree_cursor_current_descendant_index_wasm,Module._ts_tree_cursor_current_node_wasm=_ts_tree_cursor_current_node_wasm=e.ts_tree_cursor_current_node_wasm,Module._ts_node_symbol_wasm=_ts_node_symbol_wasm=e.ts_node_symbol_wasm,Module._ts_node_field_name_for_child_wasm=_ts_node_field_name_for_child_wasm=e.ts_node_field_name_for_child_wasm,Module._ts_node_field_name_for_named_child_wasm=_ts_node_field_name_for_named_child_wasm=e.ts_node_field_name_for_named_child_wasm,Module._ts_node_children_by_field_id_wasm=_ts_node_children_by_field_id_wasm=e.ts_node_children_by_field_id_wasm,Module._ts_node_first_child_for_byte_wasm=_ts_node_first_child_for_byte_wasm=e.ts_node_first_child_for_byte_wasm,Module._ts_node_first_named_child_for_byte_wasm=_ts_node_first_named_child_for_byte_wasm=e.ts_node_first_named_child_for_byte_wasm,Module._ts_node_grammar_symbol_wasm=_ts_node_grammar_symbol_wasm=e.ts_node_grammar_symbol_wasm,Module._ts_node_child_count_wasm=_ts_node_child_count_wasm=e.ts_node_child_count_wasm,Module._ts_node_named_child_count_wasm=_ts_node_named_child_count_wasm=e.ts_node_named_child_count_wasm,Module._ts_node_child_wasm=_ts_node_child_wasm=e.ts_node_child_wasm,Module._ts_node_named_child_wasm=_ts_node_named_child_wasm=e.ts_node_named_child_wasm,Module._ts_node_child_by_field_id_wasm=_ts_node_child_by_field_id_wasm=e.ts_node_child_by_field_id_wasm,Module._ts_node_next_sibling_wasm=_ts_node_next_sibling_wasm=e.ts_node_next_sibling_wasm,Module._ts_node_prev_sibling_wasm=_ts_node_prev_sibling_wasm=e.ts_node_prev_sibling_wasm,Module._ts_node_next_named_sibling_wasm=_ts_node_next_named_sibling_wasm=e.ts_node_next_named_sibling_wasm,Module._ts_node_prev_named_sibling_wasm=_ts_node_prev_named_sibling_wasm=e.ts_node_prev_named_sibling_wasm,Module._ts_node_descendant_count_wasm=_ts_node_descendant_count_wasm=e.ts_node_descendant_count_wasm,Module._ts_node_parent_wasm=_ts_node_parent_wasm=e.ts_node_parent_wasm,Module._ts_node_child_with_descendant_wasm=_ts_node_child_with_descendant_wasm=e.ts_node_child_with_descendant_wasm,Module._ts_node_descendant_for_index_wasm=_ts_node_descendant_for_index_wasm=e.ts_node_descendant_for_index_wasm,Module._ts_node_named_descendant_for_index_wasm=_ts_node_named_descendant_for_index_wasm=e.ts_node_named_descendant_for_index_wasm,Module._ts_node_descendant_for_position_wasm=_ts_node_descendant_for_position_wasm=e.ts_node_descendant_for_position_wasm,Module._ts_node_named_descendant_for_position_wasm=_ts_node_named_descendant_for_position_wasm=e.ts_node_named_descendant_for_position_wasm,Module._ts_node_start_point_wasm=_ts_node_start_point_wasm=e.ts_node_start_point_wasm,Module._ts_node_end_point_wasm=_ts_node_end_point_wasm=e.ts_node_end_point_wasm,Module._ts_node_start_index_wasm=_ts_node_start_index_wasm=e.ts_node_start_index_wasm,Module._ts_node_end_index_wasm=_ts_node_end_index_wasm=e.ts_node_end_index_wasm,Module._ts_node_to_string_wasm=_ts_node_to_string_wasm=e.ts_node_to_string_wasm,Module._ts_node_children_wasm=_ts_node_children_wasm=e.ts_node_children_wasm,Module._ts_node_named_children_wasm=_ts_node_named_children_wasm=e.ts_node_named_children_wasm,Module._ts_node_descendants_of_type_wasm=_ts_node_descendants_of_type_wasm=e.ts_node_descendants_of_type_wasm,Module._ts_node_is_named_wasm=_ts_node_is_named_wasm=e.ts_node_is_named_wasm,Module._ts_node_has_changes_wasm=_ts_node_has_changes_wasm=e.ts_node_has_changes_wasm,Module._ts_node_has_error_wasm=_ts_node_has_error_wasm=e.ts_node_has_error_wasm,Module._ts_node_is_error_wasm=_ts_node_is_error_wasm=e.ts_node_is_error_wasm,Module._ts_node_is_missing_wasm=_ts_node_is_missing_wasm=e.ts_node_is_missing_wasm,Module._ts_node_is_extra_wasm=_ts_node_is_extra_wasm=e.ts_node_is_extra_wasm,Module._ts_node_parse_state_wasm=_ts_node_parse_state_wasm=e.ts_node_parse_state_wasm,Module._ts_node_next_parse_state_wasm=_ts_node_next_parse_state_wasm=e.ts_node_next_parse_state_wasm,Module._ts_query_matches_wasm=_ts_query_matches_wasm=e.ts_query_matches_wasm,Module._ts_query_captures_wasm=_ts_query_captures_wasm=e.ts_query_captures_wasm,Module._memset=_memset=e.memset,Module._memcpy=_memcpy=e.memcpy,Module._memmove=_memmove=e.memmove,Module._iswalpha=_iswalpha=e.iswalpha,Module._iswblank=_iswblank=e.iswblank,Module._iswdigit=_iswdigit=e.iswdigit,Module._iswlower=_iswlower=e.iswlower,Module._iswupper=_iswupper=e.iswupper,Module._iswxdigit=_iswxdigit=e.iswxdigit,Module._memchr=_memchr=e.memchr,Module._strlen=_strlen=e.strlen,Module._strcmp=_strcmp=e.strcmp,Module._strncat=_strncat=e.strncat,Module._strncpy=_strncpy=e.strncpy,Module._towlower=_towlower=e.towlower,Module._towupper=_towupper=e.towupper,_setThrew=e.setThrew,__emscripten_stack_restore=e._emscripten_stack_restore,__emscripten_stack_alloc=e._emscripten_stack_alloc,_emscripten_stack_get_current=e.emscripten_stack_get_current,___wasm_apply_data_relocs=e.__wasm_apply_data_relocs}C(assignWasmExports,"assignWasmExports");var wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_high:___stack_high,__stack_low:___stack_low,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback,tree_sitter_progress_callback:_tree_sitter_progress_callback,tree_sitter_query_progress_callback:_tree_sitter_query_progress_callback};function callMain(e=[]){var t=resolveGlobalSymbol("main").sym;if(t){e.unshift(thisProgram);var n=e.length,r=stackAlloc((n+1)*4),s=r;e.forEach(a=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=t(n,r);return exitJS(o,!0),o}catch(a){return handleException(a)}}}C(callMain,"callMain");function run(e=arguments_){if(runDependencies>0){dependenciesFulfilled=run;return}if(preRun(),runDependencies>0){dependenciesFulfilled=run;return}function t(){if(Module.calledRun=!0,!ABORT){initRuntime(),readyPromiseResolve?.(Module),Module.onRuntimeInitialized?.();var n=Module.noInitialRun||!1;n||callMain(e),postRun()}}C(t,"doRun"),Module.setStatus?(Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1)):t()}C(run,"run");var wasmExports;return wasmExports=await createWasm(),run(),runtimeInitialized?moduleRtn=Module:moduleRtn=new Promise((e,t)=>{readyPromiseResolve=e,readyPromiseReject=t}),moduleRtn}async function gc(e){return pc??=await ym(e)}function _c(){return!!pc}function yc(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!oc(e[1]))throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}"`);let s=n==="eq?"||n==="any-eq?",o=!n.startsWith("any-");if(oc(e[2])){let a=e[1].name,l=e[2].name;r[t].push(c=>{let d=[],f=[];for(let m of c)m.name===a&&d.push(m.node),m.name===l&&f.push(m.node);let u=C((m,p,g)=>g?m.text===p.text:m.text!==p.text,"compare");return o?d.every(m=>f.some(p=>u(m,p,s))):d.some(m=>f.some(p=>u(m,p,s)))})}else{let a=e[1].name,l=e[2].value,c=C(f=>f.text===l,"matches"),d=C(f=>f.text!==l,"doesNotMatch");r[t].push(f=>{let u=[];for(let p of f)p.name===a&&u.push(p.node);let m=s?c:d;return o?u.every(m):u.some(m)})}}function bc(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);if(e[2].type!=="string")throw new Error(`Second argument of \`#${n}\` predicate must be a string. Got @${e[2].name}.`);let s=n==="match?"||n==="any-match?",o=!n.startsWith("any-"),a=e[1].name,l=new RegExp(e[2].value);r[t].push(c=>{let d=[];for(let u of c)u.name===a&&d.push(u.node.text);let f=C((u,m)=>m?l.test(u):!l.test(u),"test");return d.length===0?!s:o?d.every(u=>f(u,s)):d.some(u=>f(u,s))})}function wc(e,t,n,r){if(e.length<2)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected at least 1. Got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);let s=n==="any-of?",o=e[1].name,a=e.slice(2);if(!a.every(mo))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let l=a.map(c=>c.value);r[t].push(c=>{let d=[];for(let f of c)f.name===o&&d.push(f.node.text);return d.length===0?!s:d.every(f=>l.includes(f))===s})}function xc(e,t,n,r,s){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(mo))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let o=n==="is?"?r:s;o[t]||(o[t]={}),o[t][e[1].value]=e[2]?.value??null}function Sc(e,t,n){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(mo))throw new Error('Arguments to `#set!` predicate must be strings.".');n[t]||(n[t]={}),n[t][e[1].value]=e[2]?.value??null}function kc(e,t,n,r,s,o,a,l,c,d,f){if(t===bm){let u=r[n];o.push({type:"capture",name:u})}else if(t===wm)o.push({type:"string",value:s[n]});else if(o.length>0){if(o[0].type!=="string")throw new Error("Predicates must begin with a literal value");let u=o[0].value;switch(u){case"any-not-eq?":case"not-eq?":case"any-eq?":case"eq?":yc(o,e,u,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":bc(o,e,u,a);break;case"not-any-of?":case"any-of?":wc(o,e,u,a);break;case"is?":case"is-not?":xc(o,e,u,d,f);break;case"set!":Sc(o,e,c);break;default:l[e].push({operator:u,operands:o.slice(1)})}o.length=0}}var fm,C,Zw,ic,W,so,Le,dt,Jn,$e,Nt,w,mm,pm,gm,_m,hm,uo,ym,pc,D,io,oo,fo,bm,wm,xm,Yw,oc,mo,Ye,Gn,Ec,po=F(()=>{k();fm=Object.defineProperty,C=(e,t)=>fm(e,"name",{value:t,configurable:!0}),Zw=class{static{C(this,"Edit")}startPosition;oldEndPosition;newEndPosition;startIndex;oldEndIndex;newEndIndex;constructor({startIndex:e,oldEndIndex:t,newEndIndex:n,startPosition:r,oldEndPosition:s,newEndPosition:o}){this.startIndex=e>>>0,this.oldEndIndex=t>>>0,this.newEndIndex=n>>>0,this.startPosition=r,this.oldEndPosition=s,this.newEndPosition=o}editPoint(e,t){let n=t,r={...e};if(t>=this.oldEndIndex){n=this.newEndIndex+(t-this.oldEndIndex);let s=e.row;r.row=this.newEndPosition.row+(e.row-this.oldEndPosition.row),r.column=s===this.oldEndPosition.row?this.newEndPosition.column+(e.column-this.oldEndPosition.column):e.column}else t>this.startIndex&&(n=this.newEndIndex,r.row=this.newEndPosition.row,r.column=this.newEndPosition.column);return{point:r,index:n}}editRange(e){let t={startIndex:e.startIndex,startPosition:{...e.startPosition},endIndex:e.endIndex,endPosition:{...e.endPosition}};return e.endIndex>=this.oldEndIndex?e.endIndex!==Number.MAX_SAFE_INTEGER&&(t.endIndex=this.newEndIndex+(e.endIndex-this.oldEndIndex),t.endPosition={row:this.newEndPosition.row+(e.endPosition.row-this.oldEndPosition.row),column:e.endPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.endPosition.column-this.oldEndPosition.column):e.endPosition.column},t.endIndexthis.startIndex&&(t.endIndex=this.startIndex,t.endPosition={...this.startPosition}),e.startIndex>=this.oldEndIndex?(t.startIndex=this.newEndIndex+(e.startIndex-this.oldEndIndex),t.startPosition={row:this.newEndPosition.row+(e.startPosition.row-this.oldEndPosition.row),column:e.startPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.startPosition.column-this.oldEndPosition.column):e.startPosition.column},t.startIndexthis.startIndex&&(t.startIndex=this.startIndex,t.startPosition={...this.startPosition}),t}},ic=2,W=4,so=4*W,Le=5*W,dt=2*W,Jn=2*W+2*dt,$e={row:0,column:0},Nt=Symbol("INTERNAL");C(bn,"assertInternal");C(Vn,"isPoint");C(ac,"setModule");mm=class{static{C(this,"LookaheadIterator")}0=0;language;constructor(e,t,n){bn(e),this[0]=t,this.language=n}get currentTypeId(){return w._ts_lookahead_iterator_current_symbol(this[0])}get currentType(){return this.language.types[this.currentTypeId]||"ERROR"}delete(){w._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(e,t){return w._ts_lookahead_iterator_reset(this[0],e[0],t)?(this.language=e,!0):!1}resetState(e){return!!w._ts_lookahead_iterator_reset_state(this[0],e)}[Symbol.iterator](){return{next:C(()=>w._ts_lookahead_iterator_next(this[0])?{done:!1,value:this.currentType}:{done:!0,value:""},"next")}}};C(co,"getText");pm=class ao{static{C(this,"Tree")}0=0;textCallback;language;constructor(t,n,r,s){bn(t),this[0]=n,this.language=r,this.textCallback=s}copy(){let t=w._ts_tree_copy(this[0]);return new ao(Nt,t,this.language,this.textCallback)}delete(){w._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return w._ts_tree_root_node_wasm(this[0]),ue(this)}rootNodeWithOffset(t,n){let r=D+Le;return w.setValue(r,t,"i32"),Ve(r+W,n),w._ts_tree_root_node_with_offset_wasm(this[0]),ue(this)}edit(t){dc(t),w._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(t){if(!(t instanceof ao))throw new TypeError("Argument must be a Tree");w._ts_tree_get_changed_ranges_wasm(this[0],t[0]);let n=w.getValue(D,"i32"),r=w.getValue(D+W,"i32"),s=new Array(n);if(n>0){let o=r;for(let a=0;a0){let s=n;for(let o=0;o0){let s=n;for(let o=0;o0){let n=t;for(let r=0;r0){let n=t;for(let r=0;r0){let d=l;for(let f=0;f=e.oldEndIndex){this.startIndex=e.newEndIndex+(this.startIndex-e.oldEndIndex);let t,n;this.startPosition.row>e.oldEndPosition.row?(t=this.startPosition.row-e.oldEndPosition.row,n=this.startPosition.column):(t=0,n=this.startPosition.column,this.startPosition.column>=e.oldEndPosition.column&&(n=this.startPosition.column-e.oldEndPosition.column)),t>0?(this.startPosition.row+=t,this.startPosition.column=n):this.startPosition.column+=n}else this.startIndex>e.startIndex&&(this.startIndex=e.newEndIndex,this.startPosition.row=e.newEndPosition.row,this.startPosition.column=e.newEndPosition.column)}toString(){q(this);let e=w._ts_node_to_string_wasm(this.tree[0]),t=w.AsciiToString(e);return w._free(e),t}};C(lo,"unmarshalCaptures");C(q,"marshalNode");C(ue,"unmarshalNode");C(ae,"marshalTreeCursor");C(Be,"unmarshalTreeCursor");C(Ve,"marshalPoint");C(Jt,"unmarshalPoint");C(cc,"marshalRange");C(xs,"unmarshalRange");C(dc,"marshalEdit");C(uc,"unmarshalLanguageMetadata");hm=/^tree_sitter_\w+$/,uo=class fc{static{C(this,"Language")}0=0;types;fields;constructor(t,n){bn(t),this[0]=n,this.types=new Array(w._ts_language_symbol_count(this[0]));for(let r=0,s=this.types.length;r0){let s=n;for(let o=0;o0){let o=r;for(let a=0;a(ro(),no))).readFile(t);else{let l=await fetch(t);if(!l.ok){let d=await l.text();throw new Error(`Language.load failed with status ${l.status}. +var of=Object.defineProperty;var O=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var $i=(e,t)=>{for(var n in t)of(e,n,{get:t[n],enumerable:!0})};function il(e){let t="";for(let r=0;r{"use strict";af=new TextDecoder("utf-8"),lf=new TextDecoder("utf-16le"),rl=new TextEncoder,sl="0123456789abcdef";N=class e extends Uint8Array{static from(t,n){if(typeof t=="string"){if(n==="hex"){let l=new e(t.length>>1);for(let c=0;ca+l.byteLength,0),s=new e(r),o=0;for(let a of t){if(o+a.byteLength>r){s.set(a.subarray(0,r-o),o);break}s.set(a,o),o+=a.byteLength}return s}subarray(t,n){return super.subarray(t,n)}toString(t,n,r){let s=n!==void 0||r!==void 0?this.subarray(n??0,r??this.length):this;switch((t??"utf8").toLowerCase()){case"utf8":case"utf-8":return af.decode(s);case"utf16le":case"utf-16le":case"ucs2":case"ucs-2":return lf.decode(s);case"latin1":case"binary":case"ascii":return il(s);case"hex":{let o="";for(let a of s)o+=sl[a>>4]+sl[a&15];return o}case"base64":return btoa(il(s));default:throw new TypeError(`Unknown encoding: ${t}`)}}swap16(){if(this.length%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t"/",exit:e=>{throw new Error(`process.exit(${e??0}) is not available in the browser build`)},hrtime:Object.assign(e=>{let t=performance.now(),n=Math.floor(t/1e3),r=Math.floor(t%1e3*1e6);return e?[n-e[0],r-e[1]]:[n,r]},{bigint:()=>BigInt(Math.floor(performance.now()*1e6))}),memoryUsage:()=>({rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}),stdout:{write:e=>(console.log(e.replace(/\n$/,"")),!0),isTTY:!1},stderr:{write:e=>(console.warn(e.replace(/\n$/,"")),!0),isTTY:!1},on:()=>R,emitWarning:e=>console.warn(e)}});var fe,He,pn,Xe=O(()=>{"use strict";E();fe="2.28.1",He=5,pn=14});function ol(e,t){let n="",r=0,s=-1,o=0,a=0;for(let l=0;l<=e.length;++l){if(l2){let c=n.lastIndexOf("/");c===-1?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),s=l,o=0;continue}else if(n.length!==0){n="",r=0,s=l,o=0;continue}}t&&(n+=n.length>0?"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,l):n=e.slice(s+1,l),r=l-s-1;s=l,o=0}else a===46&&o!==-1?++o:o=-1}return n}function es(e){if(e.length===0)return".";let t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47,r=ol(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&n&&(r+="/"),t?"/"+r:r}function ts(e){return e.length>0&&e.charCodeAt(0)===47}function I(...e){if(e.length===0)return".";let t;for(let n of e)n.length>0&&(t=t===void 0?n:t+"/"+n);return t===void 0?".":es(t)}function ke(...e){let t="",n=!1;for(let s=e.length-1;s>=0&&!n;s--){let o=e[s];o===void 0||o.length===0||(t=t.length===0?o:o+"/"+t,n=o.charCodeAt(0)===47)}n||(t=t.length===0?"/":"/"+t);let r=ol(t,!1);return r.length>0?"/"+r:"/"}function cf(e,t){if(e===t)return"";let n=ke(e),r=ke(t);if(n===r)return"";let s=n.slice(1).split("/").filter(Boolean),o=r.slice(1).split("/").filter(Boolean),a=0;for(;a=1;--s)if(e.charCodeAt(s)===47){if(!r){n=s;break}}else r=!1;return n===-1?t?"/":".":t&&n===1?"//":e.slice(0,n)}function Ee(e,t){let n=0,r=-1,s=!0;for(let a=e.length-1;a>=0;--a)if(e.charCodeAt(a)===47){if(!s){n=a+1;break}}else r===-1&&(s=!1,r=a+1);if(r===-1)return"";let o=e.slice(n,r);return t!==void 0&&t!==o&&o.endsWith(t)?o.slice(0,o.length-t.length):o}function ns(e){let t=-1,n=0,r=-1,s=!0,o=0;for(let a=e.length-1;a>=0;--a){let l=e.charCodeAt(a);if(l===47){if(!s){n=a+1;break}continue}r===-1&&(s=!1,r=a+1),l===46?t===-1?t=a:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||r===-1||o===0||o===1&&t===r-1&&t===n+1?"":e.slice(t,r)}function df(e){let t=ts(e)?"/":"",n=Ee(e),r=ns(e),s=_e(e);return{root:t,dir:s==="."&&t===""?"":s,base:n,ext:r,name:n.slice(0,n.length-r.length)}}function uf(e){let t=e.dir||e.root||"",n=e.base||(e.name??"")+(e.ext??"");return t?t===e.root?t+n:t+"/"+n:n}function ff(e){return e}var $,hb,ae=O(()=>{"use strict";E();$={sep:"/",delimiter:":",normalize:es,isAbsolute:ts,join:I,resolve:ke,relative:cf,dirname:_e,basename:Ee,extname:ns,parse:df,format:uf,toNamespacedPath:ff},hb={...$,posix:$,win32:$}});function ll(){return++al}function Ue(e){let t=e.startsWith("/")?e:"/"+e,n=es(t);return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function At(e,t){let n=new Error(`ENOENT: no such file or directory, ${t} '${e}'`);return n.code="ENOENT",n.errno=-2,n.path=e,n.syscall=t,n}function cl(e,t){let n=new Error(`ENOTDIR: not a directory, ${t} '${e}'`);return n.code="ENOTDIR",n.errno=-20,n.path=e,n.syscall=t,n}function gn(e){let t=Ue(e),n=me.get(t);if(n){if(n.kind!=="dir")throw cl(e,"mkdir");return n}let r={kind:"dir",mtimeMs:0,mode:511,children:new Set};return me.set(t,r),t!==Ht&&gn(_e(t)).children.add(Ee(t)),r}function mf(){me.clear(),al=0,fl=0,me.set(Ht,{kind:"dir",mtimeMs:0,mode:511,children:new Set})}function dl(e){for(let t of e){let n=Ue(t.path);gn(_e(n)).children.add(Ee(n)),me.set(n,{kind:"file",size:t.size,mtimeMs:ll(),mode:438,bytes:t.bytes})}}function rs(e,t){let n=Ue(e),r=me.get(n);if(r&&r.kind==="file"){r.bytes=t,r.size=t.byteLength,r.mtimeMs=ll();return}dl([{path:n,size:t.byteLength,bytes:t}])}function pf(e){let t=me.get(Ue(e));return!!t&&t.kind==="file"&&t.bytes!==void 0}function gf(){let e=0;for(let[t,n]of[...me]){if(n.kind!=="file"||n.bytes!==void 0)continue;me.delete(t);let r=me.get(_e(t));r&&r.kind==="dir"&&r.children.delete(Ee(t)),e++}return e}function _f(){let e=0;for(let t of me.values())t.kind==="file"&&t.bytes&&(e+=t.bytes.byteLength);return e}function hf(e,t,n){return{name:e,parentPath:t,path:t,isFile:()=>n==="file",isDirectory:()=>n==="dir",isSymbolicLink:ot,isBlockDevice:ot,isCharacterDevice:ot,isFIFO:ot,isSocket:ot}}function yf(e){return{size:e.kind==="file"?e.size:0,mode:e.mode,mtimeMs:e.mtimeMs,mtime:new Date(e.mtimeMs),isFile:()=>e.kind==="file",isDirectory:()=>e.kind==="dir",isSymbolicLink:ot,isBlockDevice:ot,isCharacterDevice:ot,isFIFO:ot,isSocket:ot}}function H(e){return me.has(Ue(e))}function ve(e){let t=me.get(Ue(e));if(!t)throw At(e,"stat");return yf(t)}function _n(e){let t=Ue(e);if(!me.has(t))throw At(e,"realpath");return t}function hn(e,t){let n=Ue(e),r=me.get(n);if(!r)throw At(e,"scandir");if(r.kind!=="dir")throw cl(e,"scandir");let s=[...r.children];return t?.withFileTypes?s.map(o=>{let a=me.get(n===Ht?`/${o}`:`${n}/${o}`);return hf(o,n,a?.kind==="dir"?"dir":"file")}):s}function Q(e,t){let n=me.get(Ue(e));if(!n)throw At(e,"open");if(n.kind!=="file"){let s=new Error("EISDIR: illegal operation on a directory, read");throw s.code="EISDIR",s}if(!n.bytes)throw At(e,"open");let r=N.from(n.bytes);return t?r.toString(typeof t=="string"?t:t.encoding):r}function Me(e,t){let n=typeof t=="string"?new TextEncoder().encode(t):t;rs(e,n)}function ss(e,t){let n=me.get(Ue(e));if(!n)throw At(e,"chmod");n.mode=t}function _t(e,t){gn(e)}function Dn(e){let t=`${e}${fl++}`;return gn(t),t}function Ge(e,t){let n=Ue(e),r=me.get(n);if(!r){if(t?.force)return;throw At(e,"unlink")}if(r.kind==="dir")for(let o of[...r.children])Ge(n===Ht?`/${o}`:`${n}/${o}`,t);me.delete(n);let s=me.get(_e(n));s&&s.kind==="dir"&&s.children.delete(Ee(n))}function Ln(e,t){let n=Ue(e),r=me.get(n);if(!r)throw At(e,"rename");let s=Ue(t);if(r.kind==="dir"){gn(s);for(let o of[...r.children])Ln(n===Ht?`/${o}`:`${n}/${o}`,s===Ht?`/${o}`:`${s}/${o}`)}else gn(_e(s)).children.add(Ee(s)),me.set(s,r);Ge(n,{force:!0})}function ml(){throw new Error("recursive filesystem watching is unavailable in the browser VFS")}var Ht,me,al,ot,ul,fl,xe=O(()=>{"use strict";E();ae();Ht="/",me=new Map([[Ht,{kind:"dir",mtimeMs:0,mode:511,children:new Set}]]),al=0;ot=()=>!1;ul=ve;fl=0});function pl(e,t,n){let r=new Error(`spawnSync ${e} ENOENT`);return r.code="ENOENT",r.errno=-2,r.syscall=`spawnSync ${e}`,r.path=e,{pid:0,output:[],stdout:"",stderr:"",status:null,signal:null,error:r}}function gl(e,t,n){let r=new Map,s={pid:void 0,stdin:null,stdout:null,stderr:null,on(a,l){let c=r.get(a)??[];return c.push(l),r.set(a,c),s},kill:()=>!1},o=new Error(`spawn ${e} ENOENT`);return o.code="ENOENT",o.syscall=`spawn ${e}`,o.path=e,Promise.resolve().then(()=>{for(let a of r.get("error")??[])a(o);for(let a of r.get("close")??[])a(null)}),s}var Di=O(()=>{E()});function pe(e,t,n={}){let r=pl(e,t,{cwd:n.cwd,input:n.input,encoding:"utf8",timeout:n.timeoutMs??12e4,maxBuffer:67108864,env:n.env??R.env}),s=!!r.error&&r.error.code==="ENOENT";return{ok:!r.error&&r.status===0,status:r.status,stdout:r.stdout??"",stderr:r.stderr??(r.error?String(r.error.message):""),missing:s}}function at(e){let t=_l.get(e);if(t!==void 0)return t;let n=pe(R.platform==="win32"?"where":"which",[e]),r=n.ok&&n.stdout.trim().length>0;return _l.set(e,r),r}function Li(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/\.git$/,"").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,120)}function bf(e,t){return e.length<=t?e:e.slice(0,t)+` +\u2026 [truncated ${e.length-t} chars]`}function wf(e,t){let n=e.replace(/\s+/g," ").trim();if(n.length<=t)return n;let r=n.slice(0,t).replace(/\s+\S*$/,"");return r||(r=n.slice(0,t)),(r.match(/`/g)?.length??0)%2===1&&(r=r.replace(/`[^`]*$/,"")),r.lastIndexOf("[")>r.lastIndexOf("]")&&(r=r.slice(0,r.lastIndexOf("["))),r.replace(/\s+$/,"")+"\u2026"}function qe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ht(e){return e.normalize("NFKD").replace(/[̀-ͯ]/g,"")}function is(e){let t=new Set,n=[];for(let r of ht(e).split(/[^A-Za-z0-9_]+/)){if(!r)continue;let s=r.toLowerCase();r.length<2||hl.has(s)||t.has(s)||(t.add(s),n.push(r))}return n}function os(e){let t=[];for(let n of ht(e).split(/[^A-Za-z0-9_]+/))n&&(n.length<2||hl.has(n.toLowerCase()))&&t.push(n);return t}function xf(e){let t=is(e),n=r=>{let s=0;return/\d/.test(r)&&(s+=3),/[A-Z]/.test(r)&&!/^[A-Z0-9]+$/.test(r)&&(s+=2),/_/.test(r)&&(s+=2),r.length>=8?s+=1.5:r.length>=5&&(s+=.5),s};return t.map((r,s)=>({k:r,s:n(r),i:s})).sort((r,s)=>s.s-r.s||r.i-s.i).map(r=>r.k)}function ji(e,t,n=60){let r=new Map;for(let s of e)s.forEach((o,a)=>{let l=t(o);r.set(l,(r.get(l)??0)+1/(n+a+1))});return r}function yt(e){let t=ht(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2"),n=[],r=new Set,s=o=>{o.length<2||r.has(o)||(r.add(o),n.push(o))};/\s/.test(e.trim())||s(ht(e).toLowerCase().replace(/[^a-z0-9_]+/g,""));for(let o of t.split(/[^A-Za-z0-9]+/))s(o.toLowerCase());return n}function Wi(e){if(e.length<4)return e;let t=e;return t.endsWith("ies")&&t.length>4?t=t.slice(0,-3)+"y":t.endsWith("sses")?t=t.slice(0,-2):(t.endsWith("ses")&&t.length>4||t.endsWith("s")&&!t.endsWith("ss")&&!t.endsWith("us")&&!t.endsWith("is"))&&(t=t.slice(0,-1)),t.endsWith("ying")&&t.length>5?t=t.slice(0,-4)+"y":t.endsWith("ing")&&t.length>5?t=t.slice(0,-3):t.endsWith("ed")&&t.length>4&&(t=t.slice(0,-2)),t.endsWith("e")&&t.length>3&&(t=t.slice(0,-1)),t}var _l,hl,Ae=O(()=>{"use strict";E();Di();_l=new Map;hl=new Set(["the","a","an","is","are","was","were","be","been","being","do","does","did","how","what","why","when","where","which","who","whom","this","that","these","those","of","in","on","to","for","with","and","or","but","if","then","else","than","as","at","by","from","into","about","it","its","i","you","we","they","he","she","there","here","can","could","should","would","will","shall","may","might","must","have","has","had","not","no","yes","so","such","only","any","some","all","get","set","use","used","using","work","works","working","handle","handled","happen","happens","default","value","values","please","explain","tell","me","my","our"])});function Sf(e){let t="";for(let n=0;n{"use strict";E();Ae()});function yl(e,t){return e===jn||t.has(e)||e.startsWith(".codeindex-edit-")}function kf(e,t){let n=t.find(s=>s.name===jn);if(!n)return"";let r=I(e,jn);try{if(!n.isDirectory()){let o=/^gitdir:[ \t]*(.+?)[ \t]*$/m.exec(Q(r,"utf8"));if(!o)return"";r=ke(e,o[1]);let a=I(r,"commondir");H(a)&&(r=ke(r,Q(a,"utf8").trim()))}let s=I(r,"info","exclude");return H(s)?q(s):""}catch{return""}}function Pe(e,t={}){let n=t.maxFileBytes??1048576,r=t.maxFiles??1/0,s=t.gitignore!==!1,o=t.ignoreDirs?new Set(t.ignoreDirs):Gt,a=[],l=!1,c=0,d;try{d=_n(e)}catch{return{files:a,capped:l,excluded:c}}let f=p=>p===d||p.startsWith(d+"/"),u=[{dir:e,rel:"",rules:[]}],m=new Set;e:for(;u.length;){let p=u.pop(),g;try{g=_n(p.dir)}catch{continue}if(m.has(g)||(m.add(g),!f(g)))continue;let y;try{y=hn(p.dir,{withFileTypes:!0}).sort((S,_)=>S.name<_.name?-1:S.name>_.name?1:0)}catch{continue}if(p.rel&&y.some(S=>S.name===jn)){c++;continue}let h=p.rules;if(s&&!p.rel){let S=as(kf(p.dir,y),"");S.length&&(h=[...h,...S])}if(s&&y.some(S=>S.name===".gitignore")){let S=as(q(I(p.dir,".gitignore")),p.rel);S.length&&(h=[...h,...S])}for(let S of y){let _=S.name,k=I(p.dir,_),b=p.rel?`${p.rel}/${_}`:_,w=S.isSymbolicLink();if(_===jn||S.isDirectory()&&yl(_,o))continue;let v;try{v=w?ve(k):ul(k)}catch{continue}if(v.isDirectory()){if(yl(_,o)||w||s&&h.length&&ls(h,b,!0))continue;u.push({dir:k,rel:b,rules:h});continue}if(!v.isFile())continue;if(v.size>n){c++;continue}if(Bi.has(_.toLowerCase())){c++;continue}let A=ns(_).toLowerCase();if(zi.has(A)){c++;continue}if(_.endsWith(".min.js")||_.endsWith(".min.css")){c++;continue}if(s&&h.length&&ls(h,b,!1)){c++;continue}if(w)try{if(!f(_n(k)))continue}catch{continue}if(a.length>=r){l=!0;break e}a.push({rel:b.split("/").join("/"),abs:k,size:v.size,ext:A,mtimeMs:v.mtimeMs})}}return{files:a,capped:l,excluded:c}}function q(e){try{let t=Q(e);if(t.length>=2&&t[0]===255&&t[1]===254)return t.subarray(2,2+(t.length-2&-2)).toString("utf16le");if(t.length>=2&&t[0]===254&&t[1]===255){let r=N.from(t.subarray(2,2+(t.length-2&-2)));return r.swap16(),r.toString("utf16le")}if(t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191)return t.subarray(3).toString("utf8");if(t.includes(0))return"";let n=t.toString("utf8");return n.includes("\uFFFD")?t.toString("latin1"):n}catch{return""}}var Gt,jn,Bi,zi,Ef,Ne=O(()=>{"use strict";E();xe();ae();Ui();Gt=new Set([".git","node_modules",".pnpm","bower_components","vendor","dist","build","out","target",".next",".nuxt",".svelte-kit",".turbo","coverage","__pycache__",".venv","venv",".tox",".mypy_cache",".pytest_cache",".gradle",".idea",".vscode",".cache","tmp",".ultraindex",".codeindex","Pods","DerivedData",".terraform","elm-stuff",".dart_tool"]),jn=".git";Bi=new Set(["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lockb","composer.lock","cargo.lock","poetry.lock","pipfile.lock","gemfile.lock","go.sum","flake.lock","packages.lock.json","podfile.lock","mix.lock"]),zi=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".icns",".svg",".pdf",".zip",".gz",".tar",".tgz",".bz2",".xz",".7z",".rar",".jar",".war",".class",".so",".dylib",".dll",".exe",".bin",".o",".a",".wasm",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".wav",".flac",".ogg",".lock",".min.js",".map"]),Ef=2e4});function ds(e){let t=pe("git",["-C",e,"rev-parse","--short","HEAD"]);return t.ok?t.stdout.trim():void 0}function Gi(e){return pe("git",["-C",e,"rev-parse","--is-inside-work-tree"]).ok}function qi(e,t){let n=l=>pe("git",[...lt(e),"rev-parse","--verify","--quiet",`${l}^{commit}`]).ok,r=l=>{let c=pe("git",[...lt(e),"merge-base",l,"HEAD"]);return c.ok?c.stdout.trim():void 0};if(t){if(!n(t))return{error:`base ref "${t}" not found (tried git rev-parse --verify)`};let l=r(t);return l?{ref:t,mergeBase:l}:{error:`no merge-base between "${t}" and HEAD`}}let s=pe("git",[...lt(e),"symbolic-ref","--quiet","refs/remotes/origin/HEAD"]),o=[...s.ok?[s.stdout.trim().replace("refs/remotes/","")]:[],"origin/main","origin/master","main","master"];for(let l of o){if(!n(l))continue;let c=r(l);if(c)return{ref:l,mergeBase:c}}let a=pe("git",[...lt(e),"rev-parse","HEAD"]);return a.ok?{ref:"HEAD",mergeBase:a.stdout.trim(),note:"base: HEAD (no default branch found \u2014 reviewing uncommitted work)"}:{error:"cannot resolve HEAD \u2014 empty repository?"}}function Vi(e,t){let n=[],r=pe("git",[...lt(e),"diff","-z","-M","--name-status",...Hi(t)]);if(r.ok){let a=r.stdout.split("\0"),l=0;for(;l[a.path,a])),o=pe("git",[...lt(e),"diff","-z","-M","--numstat",...Hi(t)]);if(o.ok){let a=o.stdout.split("\0"),l=0;for(;ln.length>0):[]}function Ze(e,t={}){let n=new Map,r=t.since?[`${t.since}..HEAD`]:[],s=pe("git",[...lt(e),"log",...r,"--pretty=format:","--name-only","-z"]);if(!s.ok)return{churn:n,ok:!1};for(let o of s.stdout.split("\0")){let a=o.replace(/^\n+/,"").trim();a&&n.set(a,(n.get(a)??0)+1)}return{churn:n,ok:!0}}function vf(e,t){let n=new Set,r=pe("git",[...lt(e),"diff","-z","--name-only",t,"--"]);if(r.ok)for(let s of r.stdout.split("\0"))s&&n.add(s);for(let s of us(e))n.add(s);return n}var lt,Hi,qt=O(()=>{"use strict";E();Ae();lt=e=>["-C",e,"-c","core.quotePath=false"],Hi=e=>e.staged?["--cached"]:[e.mergeBase]});function Rf(e){return typeof e=="string"?new TextEncoder().encode(e):e}function Mf(e,t){if(e.length===1)return e[0];let n=new Uint8Array(t),r=0;for(let s of e)n.set(s,r),r+=s.byteLength;return n}function wl(e){let t=Math.floor(e.byteLength/536870912|0),n=e.byteLength<<3>>>0,r=Math.ceil((e.byteLength+9)/64),s=new Uint8Array(r*64);s.set(e),s[e.byteLength]=128;let o=new DataView(s.buffer);return o.setUint32(s.byteLength-8,t,!1),o.setUint32(s.byteLength-4,n,!1),o}function Ki(e,t){return(e<>>32-t)>>>0}function ct(e,t){return(e>>>t|e<<32-t)>>>0}function Cf(e){let t=wl(e),n=1732584193,r=4023233417,s=2562383102,o=271733878,a=3285377520,l=new Uint32Array(80);for(let f=0;f>>0;y=g,g=p,p=Ki(m,30),m=u,u=k}n=n+u>>>0,r=r+m>>>0,s=s+p>>>0,o=o+g>>>0,a=a+y>>>0}let c=new Uint8Array(20),d=new DataView(c.buffer);return[n,r,s,o,a].forEach((f,u)=>d.setUint32(u*4,f,!1)),c}function Tf(e){let t=wl(e),n=1779033703,r=3144134277,s=1013904242,o=2773480762,a=1359893119,l=2600822924,c=528734635,d=1541459225,f=new Uint32Array(64);for(let p=0;p>>3,U=ct(F,17)^ct(F,19)^F>>>10;f[v]=f[v-16]+T+f[v-7]+U>>>0}let g=n,y=r,h=s,S=o,_=a,k=l,b=c,w=d;for(let v=0;v<64;v++){let A=ct(_,6)^ct(_,11)^ct(_,25),F=_&k^~_&b,T=w+A+F+Af[v]+f[v]>>>0,U=ct(g,2)^ct(g,13)^ct(g,22),te=g&y^g&h^y&h,V=U+te>>>0;w=b,b=k,k=_,_=S+T>>>0,S=h,h=y,y=g,g=T+V>>>0}n=n+g>>>0,r=r+y>>>0,s=s+h>>>0,o=o+S>>>0,a=a+_>>>0,l=l+k>>>0,c=c+b>>>0,d=d+w>>>0}let u=new Uint8Array(32),m=new DataView(u.buffer);return[n,r,s,o,a,l,c,d].forEach((p,g)=>m.setUint32(g*4,p,!1)),u}function If(e){let t="";for(let n of e)t+=bl[n>>4]+bl[n&15];return t}function Nf(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function yn(e){let t=e.toLowerCase().replace("-","");if(t!=="sha1"&&t!=="sha256")throw new Error(`createHash: unsupported algorithm "${e}" in the browser build (sha1, sha256)`);let n=[],r=0,s={update(o){let a=Rf(o);return n.push(a),r+=a.byteLength,s},digest(o){let a=r===0?new Uint8Array(0):Mf(n,r),l=t==="sha1"?Cf(a):Tf(a);return o==="hex"?If(l):o==="base64"?Nf(l):l}};return s}var Af,bl,ms=O(()=>{E();Af=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);bl="0123456789abcdef"});function Ce(e){return yn("sha1").update(e).digest("hex")}function Ff(e,t=8){return Ce(e).slice(0,t)}var Tt=O(()=>{"use strict";E();ms()});function re(e,t,n,r){let s=[],o=t.split(/\r?\n/);for(let a=0;a{if(!a){a=[0];for(let h=0;h>>1;a[h]<=p?g=h+1:y=h}return g},c=new Map;for(let p of n)c.has(p.name)||c.set(p.name,p);let d=$f(t),f=/export\s*\{([\s\S]*?)\}\s*(?:from\s*['"]([^'"]+)['"])?\s*;?/g,u;for(;(u=f.exec(d))&&s.length{"use strict";E();Of={".ts":"typescript",".tsx":"typescript",".mts":"typescript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".go":"go",".rb":"ruby",".rake":"ruby",".java":"java",".rs":"rust",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".clj":"clojure",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".dart":"dart",".lua":"lua",".sh":"shell",".bash":"shell",".zsh":"shell",".ksh":"shell",".fish":"shell",".hh":"cpp",".m":"objective-c",".mm":"objective-c",".sql":"sql",".graphql":"graphql",".gql":"graphql",".proto":"protobuf",".md":"markdown",".mdx":"markdown",".rst":"restructuredtext",".txt":"text",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".html":"html",".css":"css",".scss":"scss",".vue":"vue",".svelte":"svelte",".astro":"astro",".zig":"zig",".hcl":"hcl",".tf":"terraform",".tfvars":"terraform",".sol":"solidity"};Pf=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);Xi=47,xl=42,Sl=10,Df=34,Lf=39,jf=96,Wf=92,ps=400});function Hf(e){return(e.split("/").pop()??"").replace(/\.[^.]+$/,"")}function Gf(e,t){let n=o=>{if(!(!o||o==="default"))for(let a of t)a.name===o&&(a.exported=!0)},r=(o,a)=>{for(let l of o.split(",")){let c=l.trim().replace(/^type\s+/,"");if(!c)continue;let d=/^([\w$]+)\s+as\s+([\w$]+)$/.exec(c);if(d){d[2]!=="default"&&n(d[1]);continue}if(a){let f=/^([\w$]+)\s*:\s*([\w$]+)$/.exec(c);if(f){n(f[1]),n(f[2]);continue}}n(/^([\w$]+)/.exec(c)?.[1])}},s;for(kl.lastIndex=0;s=kl.exec(e);)s[2]||r(s[1]??"",!1);for(El.lastIndex=0;s=El.exec(e);)r(s[1]??"",!0);for(vl.lastIndex=0;s=vl.exec(e);)n(s[2])}var Uf,Bf,zf,kl,El,vl,Rl,Ml=O(()=>{"use strict";E();Re();Uf=[{re:/^\s*export\s+(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!0},{re:/^\s*export\s+default\s+(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!0},{re:/^\s*export\s+default\s+(?:abstract\s+)?class\s+(?!extends\b)(?[\w$]+)/,kind:"class",exported:!0},{re:/^\s*(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!1},{re:/^\s*export\s+(?:abstract\s+)?class\s+(?[\w$]+)/,kind:"class",exported:!0},{re:/^\s*(?:abstract\s+)?class\s+(?[\w$]+)/,kind:"class",exported:!1},{re:/^\s*export\s+interface\s+(?[\w$]+)/,kind:"interface",exported:!0},{re:/^\s*interface\s+(?[\w$]+)/,kind:"interface",exported:!1},{re:/^\s*export\s+type\s+(?[\w$]+)/,kind:"type",exported:!0},{re:/^\s*type\s+(?[\w$]+)\s*[=<]/,kind:"type",exported:!1},{re:/^\s*export\s+enum\s+(?[\w$]+)/,kind:"enum",exported:!0},{re:/^\s*export\s+const\s+enum\s+(?[\w$]+)/,kind:"enum",exported:!0},{re:/^\s*export\s+(?:const|let|var)\s+(?[\w$]+)\s*[:=]/,kind:"const",exported:!0},{re:/^\s*exports\.(?[\w$]+)\s*=/,kind:"const",exported:!0},{re:/^\s*module\.exports\.(?[\w$]+)\s*=/,kind:"const",exported:!0},{re:/^\s*(?:const|let)\s+(?[\w$]+)\s*=\s*(?:async\s*)?\([^)]*\)\s*(?::[^=]+)?=>/,kind:"const",exported:!1},{re:/^(?:const|let|var)\s+(?[\w$]+)\s*[:=]/,kind:"const",exported:!1},{re:/^\s*export\s+default\s+(?[A-Za-z_$][\w$]*)\s*;?\s*$/,kind:"default",exported:!0}],Bf=/^\s*export\s+default\s+(?:async\s+)?(?:function|class)?\s*(?:\(|\{|extends\b)/,zf=/^\s*export\s+default\s+(?:async\s+)?(?:function|class)\s+(?!extends\b)[\w$]+/;kl=/export\s*\{([^}]*)\}\s*(from\b)?/g,El=/module\.exports\s*=\s*\{([^}]*)\}/g,vl=/(^|\n)\s*export\s+default\s+([A-Za-z_$][\w$]*)\s*;?\s*(?=\n|$)/g;Rl={lang:"javascript/typescript",exts:[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],extract(e,t){let n=e.match(/\.(ts|tsx|mts|cts)$/)?"typescript":"javascript",r=re(e,t,n,Uf),s=t.split(/\r?\n/);for(let o=0;o{"use strict";E();Re();_s=e=>!e.startsWith("_")||e.startsWith("__"),qf=[{re:/^(?:async\s+)?def\s+(?[\w]+)\s*\(/,kind:"function",exported:e=>_s(e.groups.name)},{re:/^\s+(?:async\s+)?def\s+(?[\w]+)\s*\(/,kind:"method",exported:e=>_s(e.groups.name)},{re:/^class\s+(?[\w]+)/,kind:"class",exported:e=>_s(e.groups.name)},{re:/^\s+class\s+(?[\w]+)/,kind:"class",exported:e=>_s(e.groups.name)}],Cl={lang:"python",exts:[".py",".pyi"],extract(e,t){return re(e,t,"python",qf)}}});var Wn,Vf,Tl,Il=O(()=>{"use strict";E();Re();Wn=e=>/^[A-Z]/.test(e),Vf=[{re:/^func\s+\([^)]*\)\s+(?[\w]+)\s*\(/,kind:"method",exported:e=>Wn(e.groups.name)},{re:/^func\s+(?[\w]+)\s*\(/,kind:"function",exported:e=>Wn(e.groups.name)},{re:/^type\s+(?[\w]+)\s+struct\b/,kind:"struct",exported:e=>Wn(e.groups.name)},{re:/^type\s+(?[\w]+)\s+interface\b/,kind:"interface",exported:e=>Wn(e.groups.name)},{re:/^type\s+(?[\w]+)\s+/,kind:"type",exported:e=>Wn(e.groups.name)}],Tl={lang:"go",exts:[".go"],extract(e,t){return re(e,t,"go",Vf)}}});var Jf,Nl,Fl=O(()=>{"use strict";E();Re();Jf=[{re:/^\s*def\s+(?:self\.)?(?[\w?!=]+)/,kind:"method",exported:!0},{re:/^\s*class\s+(?[\w:]+)/,kind:"class",exported:!0},{re:/^\s*module\s+(?[\w:]+)/,kind:"module",exported:!0}],Nl={lang:"ruby",exts:[".rb",".rake"],extract(e,t){return re(e,t,"ruby",Jf)}}});var Kf,Ol,Pl=O(()=>{"use strict";E();Re();Kf=[{re:/^\s*(?:public|protected|private)?\s*(?:abstract\s+|final\s+)?class\s+(?[\w]+)/,kind:"class",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)?\s*interface\s+(?[\w]+)/,kind:"interface",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)?\s*enum\s+(?[\w]+)/,kind:"enum",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)\s+(?:static\s+|final\s+|abstract\s+|synchronized\s+)*[\w<>\[\],.?\s]+\s+(?[\w]+)\s*\(/,kind:"method",exported:(e,t)=>/\bpublic\b/.test(t)}],Ol={lang:"java",exts:[".java"],extract(e,t){return re(e,t,"java",Kf)}}});var Un,Xf,$l,Dl=O(()=>{"use strict";E();Re();Un=(e,t)=>/^\s*pub\b/.test(t),Xf=[{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(?[\w]+)/,kind:"function",exported:Un},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+(?[\w]+)/,kind:"struct",exported:Un},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?enum\s+(?[\w]+)/,kind:"enum",exported:Un},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?trait\s+(?[\w]+)/,kind:"trait",exported:Un},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?type\s+(?[\w]+)/,kind:"type",exported:Un}],$l={lang:"rust",exts:[".rs"],extract(e,t){return re(e,t,"rust",Xf)}}});var Bn,Zf,Ll,jl=O(()=>{"use strict";E();Re();Bn=(e,t)=>/\b(public|internal)\b/.test(t),Zf=[{re:/^\s*(?:public|internal|protected|private)?\s*(?:static\s+|sealed\s+|abstract\s+|partial\s+)*(?:class|record)\s+(?\w+)/,kind:"class",exported:Bn},{re:/^\s*(?:public|internal|protected|private)?\s*(?:partial\s+)?interface\s+(?\w+)/,kind:"interface",exported:Bn},{re:/^\s*(?:public|internal|protected|private)?\s*(?:readonly\s+)?(?:ref\s+)?struct\s+(?\w+)/,kind:"struct",exported:Bn},{re:/^\s*(?:public|internal|protected|private)?\s*enum\s+(?\w+)/,kind:"enum",exported:Bn},{re:/^\s*(?:public|internal|protected|private)\s+(?:static\s+|virtual\s+|override\s+|async\s+|sealed\s+|abstract\s+|new\s+)*[\w<>\[\],.?]+\s+(?\w+)\s*(?:<[^>]*>)?\s*\(/,kind:"method",exported:Bn}],Ll={lang:"csharp",exts:[".cs"],extract(e,t){return re(e,t,"csharp",Zf)}}});var Yf,Wl,Ul=O(()=>{"use strict";E();Re();Yf=[{re:/^\s*(?:abstract\s+|final\s+)*class\s+(?\w+)/,kind:"class",exported:!0},{re:/^\s*interface\s+(?\w+)/,kind:"interface",exported:!0},{re:/^\s*trait\s+(?\w+)/,kind:"trait",exported:!0},{re:/^\s*enum\s+(?\w+)/,kind:"enum",exported:!0},{re:/^\s*(?:public\s+|protected\s+|private\s+|static\s+|abstract\s+|final\s+)*function\s+(?\w+)\s*\(/,kind:"function",exported:(e,t)=>!/\b(private|protected)\b/.test(t)}],Wl={lang:"php",exts:[".php"],extract(e,t){return re(e,t,"php",Yf)}}});var zn,hs,Qf,Bl,zl=O(()=>{"use strict";E();Re();zn=(e,t)=>!/\b(private|fileprivate)\b/.test(t),hs="(?:public\\s+|open\\s+|internal\\s+|private\\s+|fileprivate\\s+)?(?:final\\s+)?",Qf=[{re:new RegExp(`^\\s*${hs}class\\s+(?\\w+)`),kind:"class",exported:zn},{re:new RegExp(`^\\s*${hs}struct\\s+(?\\w+)`),kind:"struct",exported:zn},{re:new RegExp(`^\\s*${hs}enum\\s+(?\\w+)`),kind:"enum",exported:zn},{re:new RegExp(`^\\s*${hs}protocol\\s+(?\\w+)`),kind:"protocol",exported:zn},{re:/^\s*(?:public\s+|open\s+|internal\s+|private\s+|fileprivate\s+)?(?:static\s+|class\s+|final\s+|override\s+|mutating\s+|@\w+\s+)*func\s+(?\w+)/,kind:"function",exported:zn}],Bl={lang:"swift",exts:[".swift"],extract(e,t){return re(e,t,"swift",Qf)}}});var ys,em,Hl,Gl=O(()=>{"use strict";E();Re();ys=(e,t)=>!/\b(private|internal)\b/.test(t),em=[{re:/^\s*(?:public\s+|internal\s+|private\s+|abstract\s+|sealed\s+|open\s+|final\s+|data\s+)*class\s+(?\w+)/,kind:"class",exported:ys},{re:/^\s*(?:public\s+|internal\s+|private\s+|fun\s+)?interface\s+(?\w+)/,kind:"interface",exported:ys},{re:/^\s*(?:public\s+|internal\s+|private\s+|companion\s+)?object\s+(?\w+)/,kind:"object",exported:ys},{re:/^\s*(?:public\s+|internal\s+|private\s+|protected\s+|override\s+|open\s+|abstract\s+|suspend\s+|inline\s+|operator\s+)*fun\s+(?:<[^>]*>\s+)?(?\w+)\s*\(/,kind:"function",exported:ys}],Hl={lang:"kotlin",exts:[".kt",".kts"],extract(e,t){return re(e,t,"kotlin",em)}}});var tm,nm,ql,Vl=O(()=>{"use strict";E();Re();tm="(?!\\s*(?:if|for|while|switch|return|else|do|sizeof|typedef)\\b)",nm=[{re:/^\s*(?:class|struct)\s+(?[A-Za-z_]\w+)\s*(?:[:{]|$)/,kind:"class",exported:!0},{re:/^\s*namespace\s+(?[A-Za-z_]\w+)/,kind:"namespace",exported:!0},{re:/^\s*(?:typedef\s+)?(?:struct|enum|union)\s+(?[A-Za-z_]\w+)\s*\{/,kind:"struct",exported:!0},{re:new RegExp(`^${tm}[A-Za-z_][\\w\\s\\*&<>:,]*?\\b(?[A-Za-z_]\\w+)\\s*\\([^;{]*\\)\\s*(?:const)?\\s*\\{?\\s*$`),kind:"function",exported:!0}],ql={lang:"c/cpp",exts:[".c",".h",".cc",".cpp",".cxx",".hpp",".hh"],extract(e,t){return re(e,t,e.match(/\.(c|h)$/)?"c":"cpp",nm)}}});var rm,Jl,Kl=O(()=>{"use strict";E();Re();rm=[{re:/^\s*local\s+function\s+(?[\w.:]+)\s*\(/,kind:"function",exported:!1},{re:/^\s*function\s+(?[\w.:]+)\s*\(/,kind:"function",exported:!0},{re:/^\s*(?:local\s+)?(?[\w.]+)\s*=\s*function\s*\(/,kind:"function",exported:!0}],Jl={lang:"lua",exts:[".lua"],extract(e,t){return re(e,t,"lua",rm)}}});var sm,Xl,Zl=O(()=>{"use strict";E();Re();sm=[{re:/^\s*function\s+(?[\w:-]+)\s*(?:\(\))?\s*\{?/,kind:"function",exported:!0},{re:/^\s*(?[A-Za-z_][\w:-]*)\s*\(\)\s*\{?/,kind:"function",exported:!0}],Xl={lang:"shell",exts:[".sh",".bash",".zsh",".ksh"],extract(e,t){return re(e,t,"shell",sm)}}});var im,Yl,Ql=O(()=>{"use strict";E();Re();im=[{re:/^\s*defmodule\s+(?[\w.]+)/,kind:"module",exported:!0},{re:/^\s*defp\s+(?[\w?!]+)/,kind:"function",exported:!1},{re:/^\s*def\s+(?[\w?!]+)/,kind:"function",exported:!0},{re:/^\s*defmacrop?\s+(?[\w?!]+)/,kind:"macro",exported:!0}],Yl={lang:"elixir",exts:[".ex",".exs"],extract(e,t){return re(e,t,"elixir",im)}}});var om,ec,tc=O(()=>{"use strict";E();Re();om=[{re:/^\s*(?:final\s+|sealed\s+|abstract\s+|implicit\s+)*(?:case\s+)?class\s+(?\w+)/,kind:"class",exported:!0},{re:/^\s*(?:sealed\s+)?trait\s+(?\w+)/,kind:"trait",exported:!0},{re:/^\s*(?:case\s+)?object\s+(?\w+)/,kind:"object",exported:!0},{re:/^\s*(?:override\s+|final\s+|private\s+|protected\s+|implicit\s+)*def\s+(?\w+)/,kind:"def",exported:(e,t)=>!/\b(private|protected)\b/.test(t)}],ec={lang:"scala",exts:[".scala",".sc"],extract(e,t){return re(e,t,"scala",om)}}});var It,am,nc,rc=O(()=>{"use strict";E();Re();It=e=>!(e.groups?.name??"").startsWith("_"),am=[{re:/^\s*(?:abstract\s+|base\s+|final\s+|sealed\s+|interface\s+)*class\s+(?\w+)/,kind:"class",exported:It},{re:/^\s*mixin\s+(?\w+)/,kind:"mixin",exported:It},{re:/^\s*extension\s+(?\w+)/,kind:"extension",exported:It},{re:/^\s*enum\s+(?\w+)/,kind:"enum",exported:It},{re:/^\s*typedef\s+(?\w+)/,kind:"type",exported:It},{re:/^\s*(?:@\w+\s+)*(?:static\s+|final\s+|const\s+|external\s+|abstract\s+)*(?:[\w<>,?\[\]. ]+\s+)?(?\w+)\s*\([^)]*\)\s*(?:async\s*\*?\s*)?(?:=>|\{|;)/,kind:"function",exported:It},{re:/^\s*(?:static\s+)?[\w<>,?\[\]. ]+\s+get\s+(?\w+)/,kind:"getter",exported:It},{re:/^\s*(?:static\s+)?set\s+(?\w+)\s*\(/,kind:"setter",exported:It}],nc={lang:"dart",exts:[".dart"],extract(e,t){return re(e,t,"dart",am)}}});function Yi(e,t,n){let r=Zi.get(t),s;if(!r)s=[];else try{s=r.extract(e,n)}catch{s=[]}let o=new Set(s.map(l=>l.name)),a=gs(e,n,s).filter(l=>!o.has(l.name));return a.length?[...s,...a]:s}function Qi(e){return Zi.get(e)?.lang??Vt(e)}var lm,Zi,bn=O(()=>{"use strict";E();Re();Ml();Al();Il();Fl();Pl();Dl();jl();Ul();zl();Gl();Vl();Kl();Zl();Ql();tc();rc();lm=[Rl,Cl,Tl,Nl,Ol,$l,Ll,Wl,Bl,Hl,ql,Jl,Xl,Yl,ec,nc],Zi=new Map;for(let e of lm)for(let t of e.exts)Zi.set(t,e)});function sc(e,t){let n=e.split("/").pop().toLowerCase();return dm.has(t)||cm.test(n)||um.test(e)}function pm(e,t){let n=e.split("/").pop().toLowerCase();return fm.has(n)||mm.has(t)}function ic(e){return!gm.has(Qi(e))}function Hn(e,t){return ic(t)?"code":sc(e,t)?"doc":pm(e,t)?"config":"other"}var cm,dm,um,fm,mm,eo,gm,bs=O(()=>{"use strict";E();bn();cm=/^(readme|changelog|contributing|history|news|authors|notice|security|code_of_conduct|faq|getting[-_]?started|usage|guide|tutorial)\b/i,dm=new Set([".md",".mdx",".rst",".adoc",".txt"]),um=/^(docs?|documentation|wiki|guides?|website|site|book)\//i,fm=new Set(["package.json","pnpm-workspace.yaml","tsconfig.json","jsconfig.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","pipfile","go.mod","cargo.toml","gemfile","pom.xml","build.gradle","build.gradle.kts","composer.json","mix.exs","pubspec.yaml","build.sbt","dockerfile","docker-compose.yml","docker-compose.yaml","makefile",".env.example","manifest.json"]),mm=new Set([".json",".yaml",".yml",".toml",".ini",".cfg"]),eo=new Set([".md",".mdx"]);gm=new Set(["markdown","restructuredtext","text","json","yaml","toml","ini","other","html","css","scss"])});function _m(e){let t="";for(let n=0;nt.some(r=>r.test(n))}function oc(e){if(!e||e.length===0)return null;let t=bt(e.filter(r=>!r.startsWith("!"))),n=bt(e.filter(r=>r.startsWith("!")).map(r=>r.slice(1)));return r=>(!t||t(r))&&!n?.(r)}var Gn=O(()=>{"use strict";E();Ae()});function M(e,t){return et?1:0}function to(e){return(t,n)=>M(e(t),e(n))}var Y=O(()=>{"use strict";E()});function hm(e){let t=e.split(/\r?\n/),n=[],r=null;for(let s of t){let o=/^\s*(```+|~~~+)/.exec(s);if(r){o&&s.trim().startsWith(r[0][0].repeat(3).slice(0,3))&&(r=null),n.push("");continue}if(o){r=o[1],n.push("");continue}n.push(s)}return n.join(` +`)}function ym(e){return!e||e.startsWith("#")||e.startsWith("//")?!0:/^[a-z][a-z0-9+.-]*:/i.test(e)}function ac(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,"").replace(/`([^`]*)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[#>*_~-]+/g," ").replace(/\s+/g," ").trim()}function bm(e){return/[A-Za-zÀ-ɏ]{3,}/.test(e)}function wm(e){return/^(all notable changes to this project|in the interest of fostering|this project adheres to|we as members and leaders|table of contents)\b/i.test(e)}function no(e){let t=e,n,r=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(t);if(r){let h=/(^|\n)title:\s*["']?(.+?)["']?\s*(\n|$)/i.exec(r[1]);h&&(n=h[2].trim()),t=t.slice(r[0].length)}let s=hm(t),o=s.split(/\r?\n/),a=[],l=n,c,d=!1;for(let h of o){let S=/^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(h);if(S){let _=ac(S[2]);a.push(_),!l&&S[1].length===1&&(l=_),!c&&S[1].length>=2&&(d=!0);continue}if(!c&&!d){let _=h.trim();if(_&&!/^([-*+]|\d+\.)\s/.test(_)&&!_.startsWith("|")&&!_.startsWith("<")){let k=ac(_);k.length>=8&&bm(k)&&!k.endsWith(":")&&!wm(k)&&(c=k.slice(0,200))}}}let f=[],u=new Set,m=h=>{let S=h.trim();S=S.replace(/\s+["'(].*$/,"").trim(),S=S.replace(/^<|>$/g,""),!ym(S)&&(u.has(S)||(u.add(S),f.push({kind:"doc-link",spec:S})))},p=/!?\[[^\]]*\]\(([^)]+)\)/g,g;for(;g=p.exec(s);)m(g[1]);let y=/^\s*\[[^\]]+\]:\s+(\S+)/gm;for(;g=y.exec(s);)m(g[1]);return{title:l,summary:c,headings:a,refs:f}}var ro=O(()=>{"use strict";E()});function vm(e){return e.lengthlc?!1:Em.test(e)}function Rm(e){let t=e.trim();return!t||t.length>lc||km.has(t)?!1:Number.isFinite(Number(t))}function Mm(e){let t=e,n=/^(?:[rRbBuUfF]{1,2}|@|\$)?(?:#*)?(['"`])/.exec(t);if(n){let r=n[1],s=t.indexOf(r),o=t.lastIndexOf(r);o>s&&(t=t.slice(s+1,o))}return t}var lc,xm,Sm,km,Em,Nt,ws=O(()=>{"use strict";E();Y();lc=80,xm=2,Sm=256,km=new Set(["0","1","-1","2","-2"]),Em=/[\p{L}\p{N}]/u;Nt=class{seen=new Set;out=[];get full(){return this.out.length>=Sm}add(t,n,r){if(this.full||t==="string"&&!vm(n)||t==="number"&&!Rm(n)||t==="regex"&&!n)return;let s=`${t}\0${n}\0${r}`;this.seen.has(s)||(this.seen.add(s),this.out.push({value:n,line:r,kind:t}))}addString(t,n){this.add("string",Mm(t),n)}result(){if(this.out.length)return this.out.sort((t,n)=>M(t.value,n.value)||t.line-n.line||M(t.kind,n.kind))}}});function cc(){return"/home"}function xs(){return typeof navigator<"u"&&navigator?.hardwareConcurrency?navigator.hardwareConcurrency:1}function dc(){return Array.from({length:xs()},()=>({model:"browser",speed:0,times:{user:0,nice:0,sys:0,idle:0,irq:0}}))}var so=O(()=>{E()});function Ss(e){let t=typeof e=="string"?e:e.href;try{return decodeURIComponent(new URL(t).pathname)}catch{return t}}function qn(e){return new URL(`file://${e.startsWith("/")?"":"/"}${e}`)}var ks=O(()=>{E()});var io={};$i(io,{createRequire:()=>Am,default:()=>Tm});var Am,Tm,oo=O(()=>{E();Am=()=>{throw new Error("node-only API in the browser build")},Tm={}});function wn(e){if(e!==Ft)throw new Error("Illegal constructor")}function Jn(e){return!!e&&typeof e.row=="number"&&typeof e.column=="number"}function mc(e){x=e}function mo(e,t,n,r){let s=n-t,o=e.textCallback(t,r);if(o){for(t+=o.length;t0)t+=a.length,o+=a;else break}t>n&&(o=o.slice(0,s))}return o??""}function fo(e,t,n,r,s){for(let o=0,a=s.length;o>>0,column:x.getValue(e+W,"i32")>>>0}}function gc(e,t){Ve(e,t.startPosition),e+=dt,Ve(e,t.endPosition),e+=dt,x.setValue(e,t.startIndex,"i32"),e+=W,x.setValue(e,t.endIndex,"i32"),e+=W}function Es(e){let t={};return t.startPosition=Jt(e),e+=dt,t.endPosition=Jt(e),e+=dt,t.startIndex=x.getValue(e,"i32")>>>0,e+=W,t.endIndex=x.getValue(e,"i32")>>>0,t}function _c(e,t=L){Ve(t,e.startPosition),t+=dt,Ve(t,e.oldEndPosition),t+=dt,Ve(t,e.newEndPosition),t+=dt,x.setValue(t,e.startIndex,"i32"),t+=W,x.setValue(t,e.oldEndIndex,"i32"),t+=W,x.setValue(t,e.newEndIndex,"i32"),t+=W}function hc(e){let t=x.getValue(e,"i32"),n=x.getValue(e+=W,"i32"),r=x.getValue(e+=W,"i32");return{major_version:t,minor_version:n,patch_version:r}}async function bc(moduleArg={}){var moduleRtn,Module=moduleArg,ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope<"u",ENVIRONMENT_IS_NODE=typeof R=="object"&&R.versions?.node&&R.type!="renderer";if(ENVIRONMENT_IS_NODE){let{createRequire:e}=await Promise.resolve().then(()=>(oo(),io));var require=e(import.meta.url)}Module.currentQueryProgressCallback=null,Module.currentProgressCallback=null,Module.currentLogCallback=null,Module.currentParseCallback=null;var arguments_=[],thisProgram="./this.program",quit_=C((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}C(locateFile,"locateFile");var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");_scriptName.startsWith("file:")&&(scriptDirectory=require("path").dirname(require("url").fileURLToPath(_scriptName))+"/"),readBinary=C(e=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=C(async(e,t=!0)=>{e=isFileURI(e)?new URL(e):e;var n=fs.readFileSync(e,t?void 0:"utf8");return n},"readAsync"),R.argv.length>1&&(thisProgram=R.argv[1].replace(/\\/g,"/")),arguments_=R.argv.slice(2),quit_=C((e,t)=>{throw R.exitCode=e,t},"quit_")}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}ENVIRONMENT_IS_WORKER&&(readBinary=C(e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary")),readAsync=C(async e=>{if(isFileURI(e))return new Promise((n,r)=>{var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=()=>{if(s.status==200||s.status==0&&s.response){n(s.response);return}r(s.status)},s.onerror=r,s.send(null)});var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)},"readAsync")}var out=console.log.bind(console),err=console.error.bind(console),dynamicLibraries=[],wasmBinary,ABORT=!1,EXITSTATUS,isFileURI=C(e=>e.startsWith("file://"),"isFileURI"),readyPromiseResolve,readyPromiseReject,wasmMemory,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64,HEAPU64,HEAP_DATA_VIEW,runtimeInitialized=!1;function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e),Module.HEAP64=HEAP64=new BigInt64Array(e),Module.HEAPU64=HEAPU64=new BigUint64Array(e),Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(e),LE_HEAP_UPDATE()}C(updateMemoryViews,"updateMemoryViews");function initMemory(){if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var e=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:e/65536,maximum:32768})}updateMemoryViews()}C(initMemory,"initMemory");var __RELOC_FUNCS__=[];function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(onPreRuns)}C(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}C(initRuntime,"initRuntime");function preMain(){}C(preMain,"preMain");function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(onPostRuns)}C(postRun,"postRun");function abort(e){Module.onAbort?.(e),e="Aborted("+e+")",err(e),ABORT=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw readyPromiseReject?.(t),t}C(abort,"abort");var wasmBinaryFile;function findWasmBinary(){return Module.locateFile?locateFile("web-tree-sitter.wasm"):new URL("web-tree-sitter.wasm",import.meta.url).href}C(findWasmBinary,"findWasmBinary");function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}C(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}C(getWasmBinary,"getWasmBinary");async function instantiateArrayBuffer(e,t){try{var n=await getWasmBinary(e),r=await WebAssembly.instantiate(n,t);return r}catch(s){err(`failed to asynchronously prepare wasm: ${s}`),abort(s)}}C(instantiateArrayBuffer,"instantiateArrayBuffer");async function instantiateAsync(e,t,n){if(!e&&!isFileURI(t)&&!ENVIRONMENT_IS_NODE)try{var r=fetch(t,{credentials:"same-origin"}),s=await WebAssembly.instantiateStreaming(r,n);return s}catch(o){err(`wasm streaming compile failed: ${o}`),err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(t,n)}C(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}C(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var l=getDylinkMetadata(a);return l.neededDynlibs&&(dynamicLibraries=l.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}C(e,"receiveInstance");function t(o){return e(o.instance,o.module)}C(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(l,c)=>{o(e(l,c))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}C(createWasm,"createWasm");class ExitStatus{static{C(this,"ExitStatus")}name="ExitStatus";constructor(t){this.message=`Program terminated with exit(${t})`,this.status=t}}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(e,t){var n=GOT[t];return n||(n=GOT[t]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(t)||(n.required=!0),n}},LE_ATOMICS_NATIVE_BYTE_ORDER=[],LE_HEAP_LOAD_F32=C(e=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=C(e=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=C(e=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=C(e=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=C(e=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=C(e=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=C((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=C((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=C((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=C((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=C((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=C((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=C(e=>{for(;e.length>0;)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=C(e=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=C(e=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=C((e,t,n,r)=>{var s=t+n;if(r)return s;for(;e[t]&&!(t>=s);)++t;return t},"findStringEnd"),UTF8ArrayToString=C((e,t=0,n,r)=>{var s=findStringEnd(e,t,n,r);if(s-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,s));for(var o="";t>10,56320|d&1023)}}return o},"UTF8ArrayToString"),getDylinkMetadata=C(e=>{var t=0,n=0;function r(){return e[t++]}C(r,"getU8");function s(){for(var V=0,z=1;;){var P=e[t++];if(V+=(P&127)*z,z*=128,!(P&128))break}return V}C(s,"getLEB");function o(){var V=s();return t+=V,UTF8ArrayToString(e,t-V,V)}C(o,"getString");function a(){for(var V=s(),z=[];V--;)z.push(o());return z}C(a,"getStringList");function l(V,z){if(V)throw new Error(z)}if(C(l,"failIf"),e instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(e,"dylink.0");l(c.length===0,"need dylink section"),e=new Uint8Array(c[0]),n=e.length}else{var d=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),f=d[0]==1836278016||d[0]==6386541;l(!f,"need to see wasm magic number"),l(e[8]!==0,"need the dylink section to be first"),t=9;var u=s();n=t+u;var m=o();l(m!=="dylink.0")}for(var p={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},g=1,y=2,h=3,S=4,_=5,k=256,b=3,w=1;t>1)*2);case"i32":return LE_HEAP_LOAD_I32((e>>2)*4);case"i64":return LE_HEAP_LOAD_I64((e>>3)*8);case"float":return LE_HEAP_LOAD_F32((e>>2)*4);case"double":return LE_HEAP_LOAD_F64((e>>3)*8);case"*":return LE_HEAP_LOAD_U32((e>>2)*4);default:abort(`invalid type for getValue: ${t}`)}}C(getValue,"getValue");var newDSO=C((e,t,n)=>{var r={refcount:1/0,name:e,exports:n,global:!0};return LDSO.loadedLibsByName[e]=r,t!=null&&(LDSO.loadedLibsByHandle[t]=r),r},"newDSO"),LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78240,alignMemory=C((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=C(e=>{if(runtimeInitialized)return _calloc(e,1);var t=___heap_base,n=t+alignMemory(e,16);return ___heap_base=n,GOT.__heap_base.value=n,t},"getMemory"),isInternalSym=C(e=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(e)||e.startsWith("__em_js__"),"isInternalSym"),uleb128EncodeWithLen=C(e=>{let t=e.length;return[t%128|128,t>>7,...e]},"uleb128EncodeWithLen"),wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111},generateTypePack=C(e=>uleb128EncodeWithLen(Array.from(e,t=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=C((e,t)=>{var n=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(t.slice(1)),...generateTypePack(t[0]==="v"?"":t[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),r=new WebAssembly.Module(n),s=new WebAssembly.Instance(r,{e:{f:e}}),o=s.exports.f;return o},"convertJsFunctionToWasm"),wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:31,element:"anyfunc"}),getWasmTableEntry=C(e=>{var t=wasmTableMirror[e];return t||(wasmTableMirror[e]=t=wasmTable.get(e)),t},"getWasmTableEntry"),updateTableMap=C((e,t)=>{if(functionsInTableMap)for(var n=e;n(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=C(()=>freeTableIndexes.length?freeTableIndexes.pop():wasmTable.grow(1),"getEmptyTableSlot"),setWasmTableEntry=C((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=C((e,t)=>{var n=getFunctionAddress(e);if(n)return n;var r=getEmptyTableSlot();try{setWasmTableEntry(r,e)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(e,t);setWasmTableEntry(r,s)}return functionsInTableMap.set(e,r),r},"addFunction"),updateGOT=C((e,t)=>{for(var n in e)if(!isInternalSym(n)){var r=e[n];GOT[n]||=new WebAssembly.Global({value:"i32",mutable:!0}),(t||GOT[n].value==0)&&(typeof r=="function"?GOT[n].value=addFunction(r):typeof r=="number"?GOT[n].value=r:err(`unhandled export type for '${n}': ${typeof r}`))}},"updateGOT"),relocateExports=C((e,t,n)=>{var r={};for(var s in e){var o=e[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=t),r[s]=o}return updateGOT(r,n),r},"relocateExports"),isSymbolDefined=C(e=>{var t=wasmImports[e];return!(!t||t.stub)},"isSymbolDefined"),dynCall=C((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(l){return l}return C(a,"convert"),o},"dynCall"),stackSave=C(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=C(e=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=C(e=>(t,...n)=>{var r=stackSave();try{return dynCall(e,t,n)}catch(s){if(stackRestore(r),s!==s+0)throw s;if(_setThrew(1,0),e[0]=="j")return 0n}},"createInvokeFunction"),resolveGlobalSymbol=C((e,t=!1)=>{var n;return isSymbolDefined(e)?n=wasmImports[e]:e.startsWith("invoke_")&&(n=wasmImports[e]=createInvokeFunction(e.split("_")[1])),{sym:n,name:e}},"resolveGlobalSymbol"),onPostCtors=[],addOnPostCtor=C(e=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=C((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=C((binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);function loadModule(){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize)),metadata.tableSize&&wasmTable.grow(metadata.tableSize);var moduleExports;function resolveSymbol(e){var t=resolveGlobalSymbol(e).sym;return!t&&localScope&&(t=localScope[e]),t||(t=moduleExports[e]),t}C(resolveSymbol,"resolveSymbol");var proxyHandler={get(e,t){switch(t){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(t in wasmImports&&!wasmImports[t].stub){var n=wasmImports[t];return n}if(!(t in e)){var r;e[t]=(...s)=>(r||=resolveSymbol(t),r(...s))}return e[t]}},proxy=new Proxy({},proxyHandler);currentModuleWeakSymbols=metadata.weakImports;var info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if(C(addEmAsm,"addEmAsm"),"__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start ${body};`;moduleExports[name]=eval(func)}C(addEmJs,"addEmJs");for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():addOnPostCtor(init)),moduleExports}if(C(postInstantiation,"postInstantiation"),flags.loadAsync)return(async()=>{var e;return binary instanceof WebAssembly.Module?e=new WebAssembly.Instance(binary,info):{module:binary,instance:e}=await WebAssembly.instantiate(binary,info),postInstantiation(binary,e)})();var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return C(loadModule,"loadModule"),flags={...flags,rpath:{parentLibPath:libName,paths:metadata.runtimePaths}},flags.loadAsync?metadata.neededDynlibs.reduce((e,t)=>e.then(()=>loadDynamicLibrary(t,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(e=>loadDynamicLibrary(e,flags,localScope)),loadModule())},"loadWebAssemblyModule"),mergeLibSymbols=C((e,t)=>{for(var[n,r]of Object.entries(e)){let s=C(a=>{isSymbolDefined(a)||(wasmImports[a]=r)},"setImport");s(n);let o="__main_argc_argv";n=="main"&&s(o),n==o&&s("main")}},"mergeLibSymbols"),asyncLoad=C(async e=>{var t=await readAsync(e);return new Uint8Array(t)},"asyncLoad");function loadDynamicLibrary(e,t={global:!0,nodelete:!0},n,r){var s=LDSO.loadedLibsByName[e];if(s)return t.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,e)):n&&Object.assign(n,s.exports),t.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,r&&(LDSO.loadedLibsByHandle[r]=s),t.loadAsync?Promise.resolve(!0):!0;s=newDSO(e,r,"loading"),s.refcount=t.nodelete?1/0:1,s.global=t.global;function o(){if(r){var c=LE_HEAP_LOAD_U32((r+28>>2)*4),d=LE_HEAP_LOAD_U32((r+32>>2)*4);if(c&&d){var f=HEAP8.slice(c,c+d);return t.loadAsync?Promise.resolve(f):f}}var u=locateFile(e);if(t.loadAsync)return asyncLoad(u);if(!readBinary)throw new Error(`${u}: file not found, and synchronous loading of external files is not available`);return readBinary(u)}C(o,"loadLibData");function a(){return t.loadAsync?o().then(c=>loadWebAssemblyModule(c,t,e,n,r)):loadWebAssemblyModule(o(),t,e,n,r)}C(a,"getExports");function l(c){s.global?mergeLibSymbols(c,e):n&&Object.assign(n,c),s.exports=c}return C(l,"moduleLoaded"),t.loadAsync?a().then(c=>(l(c),!0)):(l(a()),!0)}C(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=C(()=>{for(var[e,t]of Object.entries(GOT))if(t.value==0){var n=resolveGlobalSymbol(e,!0).sym;if(!n&&!t.required)continue;if(typeof n=="function")t.value=addFunction(n,n.sig);else if(typeof n=="number")t.value=n;else throw new Error(`bad export type for '${e}': ${typeof n}`)}},"reportUndefinedSymbols"),runDependencies=0,dependenciesFulfilled=null,removeRunDependency=C(e=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}},"removeRunDependency"),addRunDependency=C(e=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=C(async()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs");for(var e of dynamicLibraries)await loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0});reportUndefinedSymbols(),removeRunDependency("loadDylibs")},"loadDylibs"),noExitRuntime=!0;function setValue(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":HEAP8[e]=t;break;case"i8":HEAP8[e]=t;break;case"i16":LE_HEAP_STORE_I16((e>>1)*2,t);break;case"i32":LE_HEAP_STORE_I32((e>>2)*4,t);break;case"i64":LE_HEAP_STORE_I64((e>>3)*8,BigInt(t));break;case"float":LE_HEAP_STORE_F32((e>>2)*4,t);break;case"double":LE_HEAP_STORE_F64((e>>3)*8,t);break;case"*":LE_HEAP_STORE_U32((e>>2)*4,t);break;default:abort(`invalid type for setValue: ${n}`)}}C(setValue,"setValue");var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_high=78240,___stack_low=12704,___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},78240),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=C(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=C(()=>2147483648,"getHeapMax"),growMemory=C(e=>{var t=wasmMemory.buffer.byteLength,n=(e-t+65535)/65536|0;try{return wasmMemory.grow(n),updateMemoryViews(),1}catch{}},"growMemory"),_emscripten_resize_heap=C(e=>{var t=HEAPU8.length;e>>>=0;var n=getHeapMax();if(e>n)return!1;for(var r=1;r<=4;r*=2){var s=t*(1+.2/r);s=Math.min(s,e+100663296);var o=Math.min(n,alignMemory(Math.max(e,s),65536)),a=growMemory(o);if(a)return!0}return!1},"_emscripten_resize_heap");_emscripten_resize_heap.sig="ip";var _fd_close=C(e=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=C(e=>eINT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}C(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=C((e,t)=>{var n=printCharBuffers[e];t===0||t===10?((e===1?out:err)(UTF8ArrayToString(n)),n.length=0):n.push(t)},"printChar"),_fd_write=C((e,t,n,r)=>{for(var s=0,o=0;o>2)*4),l=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var c=0;c>2)*4,s),0},"_fd_write");_fd_write.sig="iippp";function _tree_sitter_log_callback(e,t){if(Module.currentLogCallback){let n=UTF8ToString(t);Module.currentLogCallback(n,e!==0)}}C(_tree_sitter_log_callback,"_tree_sitter_log_callback");function _tree_sitter_parse_callback(e,t,n,r,s){let a=Module.currentParseCallback(t,{row:n,column:r});typeof a=="string"?(setValue(s,a.length,"i32"),stringToUTF16(a,e,10240)):setValue(s,0,"i32")}C(_tree_sitter_parse_callback,"_tree_sitter_parse_callback");function _tree_sitter_progress_callback(e,t){return Module.currentProgressCallback?Module.currentProgressCallback({currentOffset:e,hasError:t}):!1}C(_tree_sitter_progress_callback,"_tree_sitter_progress_callback");function _tree_sitter_query_progress_callback(e){return Module.currentQueryProgressCallback?Module.currentQueryProgressCallback({currentOffset:e}):!1}C(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=C(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=C(e=>{EXITSTATUS=e,keepRuntimeAlive()||(Module.onExit?.(e),ABORT=!0),quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=C((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=C(e=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=C(e=>{for(var t=0,n=0;n=55296&&r<=57343?(t+=4,++n):t+=3}return t},"lengthBytesUTF8"),stringToUTF8Array=C((e,t,n,r)=>{if(!(r>0))return 0;for(var s=n,o=n+r-1,a=0;a=o)break;t[n++]=l}else if(l<=2047){if(n+1>=o)break;t[n++]=192|l>>6,t[n++]=128|l&63}else if(l<=65535){if(n+2>=o)break;t[n++]=224|l>>12,t[n++]=128|l>>6&63,t[n++]=128|l&63}else{if(n+3>=o)break;t[n++]=240|l>>18,t[n++]=128|l>>12&63,t[n++]=128|l>>6&63,t[n++]=128|l&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=C((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=C(e=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=C(e=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=C(e=>{for(var t="";;){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=C((e,t,n)=>{if(n??=2147483647,n<2)return 0;n-=2;for(var r=t,s=n>1)*2,a),t+=2}return LE_HEAP_STORE_I16((t>>1)*2,0),t-r},"stringToUTF16");LE_ATOMICS_NATIVE_BYTE_ORDER=new Int8Array(new Int16Array([1]).buffer)[0]===1?[(e=>e),(e=>e),void 0,(e=>e)]:[(e=>e),(e=>((e&65280)<<8|(e&255)<<24)>>16),void 0,(e=>e>>24&255|e>>8&65280|(e&65280)<<8|(e&255)<<24)];function LE_HEAP_UPDATE(){HEAPU16.unsigned=(e=>e&65535),HEAPU32.unsigned=(e=>e>>>0)}if(C(LE_HEAP_UPDATE,"LE_HEAP_UPDATE"),initMemory(),Module.noExitRuntime&&(noExitRuntime=Module.noExitRuntime),Module.print&&(out=Module.print),Module.printErr&&(err=Module.printErr),Module.dynamicLibraries&&(dynamicLibraries=Module.dynamicLibraries),Module.wasmBinary&&(wasmBinary=Module.wasmBinary),Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.shift()();Module.setValue=setValue,Module.getValue=getValue,Module.UTF8ToString=UTF8ToString,Module.stringToUTF8=stringToUTF8,Module.lengthBytesUTF8=lengthBytesUTF8,Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16,Module.loadWebAssemblyModule=loadWebAssemblyModule,Module.LE_HEAP_STORE_I64=LE_HEAP_STORE_I64;var ASM_CONSTS={},_malloc,_calloc,_realloc,_free,_ts_range_edit,_memcmp,_ts_language_symbol_count,_ts_language_state_count,_ts_language_abi_version,_ts_language_name,_ts_language_field_count,_ts_language_next_state,_ts_language_symbol_name,_ts_language_symbol_for_name,_strncmp,_ts_language_symbol_type,_ts_language_field_name_for_id,_ts_lookahead_iterator_new,_ts_lookahead_iterator_delete,_ts_lookahead_iterator_reset_state,_ts_lookahead_iterator_reset,_ts_lookahead_iterator_next,_ts_lookahead_iterator_current_symbol,_ts_point_edit,_ts_parser_delete,_ts_parser_reset,_ts_parser_set_language,_ts_parser_set_included_ranges,_ts_query_new,_ts_query_delete,_iswspace,_iswalnum,_ts_query_pattern_count,_ts_query_capture_count,_ts_query_string_count,_ts_query_capture_name_for_id,_ts_query_capture_quantifier_for_id,_ts_query_string_value_for_id,_ts_query_predicates_for_pattern,_ts_query_start_byte_for_pattern,_ts_query_end_byte_for_pattern,_ts_query_is_pattern_rooted,_ts_query_is_pattern_non_local,_ts_query_is_pattern_guaranteed_at_step,_ts_query_disable_capture,_ts_query_disable_pattern,_ts_tree_copy,_ts_tree_delete,_ts_init,_ts_parser_new_wasm,_ts_parser_enable_logger_wasm,_ts_parser_parse_wasm,_ts_parser_included_ranges_wasm,_ts_language_type_is_named_wasm,_ts_language_type_is_visible_wasm,_ts_language_metadata_wasm,_ts_language_supertypes_wasm,_ts_language_subtypes_wasm,_ts_tree_root_node_wasm,_ts_tree_root_node_with_offset_wasm,_ts_tree_edit_wasm,_ts_tree_included_ranges_wasm,_ts_tree_get_changed_ranges_wasm,_ts_tree_cursor_new_wasm,_ts_tree_cursor_copy_wasm,_ts_tree_cursor_delete_wasm,_ts_tree_cursor_reset_wasm,_ts_tree_cursor_reset_to_wasm,_ts_tree_cursor_goto_first_child_wasm,_ts_tree_cursor_goto_last_child_wasm,_ts_tree_cursor_goto_first_child_for_index_wasm,_ts_tree_cursor_goto_first_child_for_position_wasm,_ts_tree_cursor_goto_next_sibling_wasm,_ts_tree_cursor_goto_previous_sibling_wasm,_ts_tree_cursor_goto_descendant_wasm,_ts_tree_cursor_goto_parent_wasm,_ts_tree_cursor_current_node_type_id_wasm,_ts_tree_cursor_current_node_state_id_wasm,_ts_tree_cursor_current_node_is_named_wasm,_ts_tree_cursor_current_node_is_missing_wasm,_ts_tree_cursor_current_node_id_wasm,_ts_tree_cursor_start_position_wasm,_ts_tree_cursor_end_position_wasm,_ts_tree_cursor_start_index_wasm,_ts_tree_cursor_end_index_wasm,_ts_tree_cursor_current_field_id_wasm,_ts_tree_cursor_current_depth_wasm,_ts_tree_cursor_current_descendant_index_wasm,_ts_tree_cursor_current_node_wasm,_ts_node_symbol_wasm,_ts_node_field_name_for_child_wasm,_ts_node_field_name_for_named_child_wasm,_ts_node_children_by_field_id_wasm,_ts_node_first_child_for_byte_wasm,_ts_node_first_named_child_for_byte_wasm,_ts_node_grammar_symbol_wasm,_ts_node_child_count_wasm,_ts_node_named_child_count_wasm,_ts_node_child_wasm,_ts_node_named_child_wasm,_ts_node_child_by_field_id_wasm,_ts_node_next_sibling_wasm,_ts_node_prev_sibling_wasm,_ts_node_next_named_sibling_wasm,_ts_node_prev_named_sibling_wasm,_ts_node_descendant_count_wasm,_ts_node_parent_wasm,_ts_node_child_with_descendant_wasm,_ts_node_descendant_for_index_wasm,_ts_node_named_descendant_for_index_wasm,_ts_node_descendant_for_position_wasm,_ts_node_named_descendant_for_position_wasm,_ts_node_start_point_wasm,_ts_node_end_point_wasm,_ts_node_start_index_wasm,_ts_node_end_index_wasm,_ts_node_to_string_wasm,_ts_node_children_wasm,_ts_node_named_children_wasm,_ts_node_descendants_of_type_wasm,_ts_node_is_named_wasm,_ts_node_has_changes_wasm,_ts_node_has_error_wasm,_ts_node_is_error_wasm,_ts_node_is_missing_wasm,_ts_node_is_extra_wasm,_ts_node_parse_state_wasm,_ts_node_next_parse_state_wasm,_ts_query_matches_wasm,_ts_query_captures_wasm,_memset,_memcpy,_memmove,_iswalpha,_iswblank,_iswdigit,_iswlower,_iswupper,_iswxdigit,_memchr,_strlen,_strcmp,_strncat,_strncpy,_towlower,_towupper,_setThrew,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___wasm_apply_data_relocs;function assignWasmExports(e){Module._malloc=_malloc=e.malloc,Module._calloc=_calloc=e.calloc,Module._realloc=_realloc=e.realloc,Module._free=_free=e.free,Module._ts_range_edit=_ts_range_edit=e.ts_range_edit,Module._memcmp=_memcmp=e.memcmp,Module._ts_language_symbol_count=_ts_language_symbol_count=e.ts_language_symbol_count,Module._ts_language_state_count=_ts_language_state_count=e.ts_language_state_count,Module._ts_language_abi_version=_ts_language_abi_version=e.ts_language_abi_version,Module._ts_language_name=_ts_language_name=e.ts_language_name,Module._ts_language_field_count=_ts_language_field_count=e.ts_language_field_count,Module._ts_language_next_state=_ts_language_next_state=e.ts_language_next_state,Module._ts_language_symbol_name=_ts_language_symbol_name=e.ts_language_symbol_name,Module._ts_language_symbol_for_name=_ts_language_symbol_for_name=e.ts_language_symbol_for_name,Module._strncmp=_strncmp=e.strncmp,Module._ts_language_symbol_type=_ts_language_symbol_type=e.ts_language_symbol_type,Module._ts_language_field_name_for_id=_ts_language_field_name_for_id=e.ts_language_field_name_for_id,Module._ts_lookahead_iterator_new=_ts_lookahead_iterator_new=e.ts_lookahead_iterator_new,Module._ts_lookahead_iterator_delete=_ts_lookahead_iterator_delete=e.ts_lookahead_iterator_delete,Module._ts_lookahead_iterator_reset_state=_ts_lookahead_iterator_reset_state=e.ts_lookahead_iterator_reset_state,Module._ts_lookahead_iterator_reset=_ts_lookahead_iterator_reset=e.ts_lookahead_iterator_reset,Module._ts_lookahead_iterator_next=_ts_lookahead_iterator_next=e.ts_lookahead_iterator_next,Module._ts_lookahead_iterator_current_symbol=_ts_lookahead_iterator_current_symbol=e.ts_lookahead_iterator_current_symbol,Module._ts_point_edit=_ts_point_edit=e.ts_point_edit,Module._ts_parser_delete=_ts_parser_delete=e.ts_parser_delete,Module._ts_parser_reset=_ts_parser_reset=e.ts_parser_reset,Module._ts_parser_set_language=_ts_parser_set_language=e.ts_parser_set_language,Module._ts_parser_set_included_ranges=_ts_parser_set_included_ranges=e.ts_parser_set_included_ranges,Module._ts_query_new=_ts_query_new=e.ts_query_new,Module._ts_query_delete=_ts_query_delete=e.ts_query_delete,Module._iswspace=_iswspace=e.iswspace,Module._iswalnum=_iswalnum=e.iswalnum,Module._ts_query_pattern_count=_ts_query_pattern_count=e.ts_query_pattern_count,Module._ts_query_capture_count=_ts_query_capture_count=e.ts_query_capture_count,Module._ts_query_string_count=_ts_query_string_count=e.ts_query_string_count,Module._ts_query_capture_name_for_id=_ts_query_capture_name_for_id=e.ts_query_capture_name_for_id,Module._ts_query_capture_quantifier_for_id=_ts_query_capture_quantifier_for_id=e.ts_query_capture_quantifier_for_id,Module._ts_query_string_value_for_id=_ts_query_string_value_for_id=e.ts_query_string_value_for_id,Module._ts_query_predicates_for_pattern=_ts_query_predicates_for_pattern=e.ts_query_predicates_for_pattern,Module._ts_query_start_byte_for_pattern=_ts_query_start_byte_for_pattern=e.ts_query_start_byte_for_pattern,Module._ts_query_end_byte_for_pattern=_ts_query_end_byte_for_pattern=e.ts_query_end_byte_for_pattern,Module._ts_query_is_pattern_rooted=_ts_query_is_pattern_rooted=e.ts_query_is_pattern_rooted,Module._ts_query_is_pattern_non_local=_ts_query_is_pattern_non_local=e.ts_query_is_pattern_non_local,Module._ts_query_is_pattern_guaranteed_at_step=_ts_query_is_pattern_guaranteed_at_step=e.ts_query_is_pattern_guaranteed_at_step,Module._ts_query_disable_capture=_ts_query_disable_capture=e.ts_query_disable_capture,Module._ts_query_disable_pattern=_ts_query_disable_pattern=e.ts_query_disable_pattern,Module._ts_tree_copy=_ts_tree_copy=e.ts_tree_copy,Module._ts_tree_delete=_ts_tree_delete=e.ts_tree_delete,Module._ts_init=_ts_init=e.ts_init,Module._ts_parser_new_wasm=_ts_parser_new_wasm=e.ts_parser_new_wasm,Module._ts_parser_enable_logger_wasm=_ts_parser_enable_logger_wasm=e.ts_parser_enable_logger_wasm,Module._ts_parser_parse_wasm=_ts_parser_parse_wasm=e.ts_parser_parse_wasm,Module._ts_parser_included_ranges_wasm=_ts_parser_included_ranges_wasm=e.ts_parser_included_ranges_wasm,Module._ts_language_type_is_named_wasm=_ts_language_type_is_named_wasm=e.ts_language_type_is_named_wasm,Module._ts_language_type_is_visible_wasm=_ts_language_type_is_visible_wasm=e.ts_language_type_is_visible_wasm,Module._ts_language_metadata_wasm=_ts_language_metadata_wasm=e.ts_language_metadata_wasm,Module._ts_language_supertypes_wasm=_ts_language_supertypes_wasm=e.ts_language_supertypes_wasm,Module._ts_language_subtypes_wasm=_ts_language_subtypes_wasm=e.ts_language_subtypes_wasm,Module._ts_tree_root_node_wasm=_ts_tree_root_node_wasm=e.ts_tree_root_node_wasm,Module._ts_tree_root_node_with_offset_wasm=_ts_tree_root_node_with_offset_wasm=e.ts_tree_root_node_with_offset_wasm,Module._ts_tree_edit_wasm=_ts_tree_edit_wasm=e.ts_tree_edit_wasm,Module._ts_tree_included_ranges_wasm=_ts_tree_included_ranges_wasm=e.ts_tree_included_ranges_wasm,Module._ts_tree_get_changed_ranges_wasm=_ts_tree_get_changed_ranges_wasm=e.ts_tree_get_changed_ranges_wasm,Module._ts_tree_cursor_new_wasm=_ts_tree_cursor_new_wasm=e.ts_tree_cursor_new_wasm,Module._ts_tree_cursor_copy_wasm=_ts_tree_cursor_copy_wasm=e.ts_tree_cursor_copy_wasm,Module._ts_tree_cursor_delete_wasm=_ts_tree_cursor_delete_wasm=e.ts_tree_cursor_delete_wasm,Module._ts_tree_cursor_reset_wasm=_ts_tree_cursor_reset_wasm=e.ts_tree_cursor_reset_wasm,Module._ts_tree_cursor_reset_to_wasm=_ts_tree_cursor_reset_to_wasm=e.ts_tree_cursor_reset_to_wasm,Module._ts_tree_cursor_goto_first_child_wasm=_ts_tree_cursor_goto_first_child_wasm=e.ts_tree_cursor_goto_first_child_wasm,Module._ts_tree_cursor_goto_last_child_wasm=_ts_tree_cursor_goto_last_child_wasm=e.ts_tree_cursor_goto_last_child_wasm,Module._ts_tree_cursor_goto_first_child_for_index_wasm=_ts_tree_cursor_goto_first_child_for_index_wasm=e.ts_tree_cursor_goto_first_child_for_index_wasm,Module._ts_tree_cursor_goto_first_child_for_position_wasm=_ts_tree_cursor_goto_first_child_for_position_wasm=e.ts_tree_cursor_goto_first_child_for_position_wasm,Module._ts_tree_cursor_goto_next_sibling_wasm=_ts_tree_cursor_goto_next_sibling_wasm=e.ts_tree_cursor_goto_next_sibling_wasm,Module._ts_tree_cursor_goto_previous_sibling_wasm=_ts_tree_cursor_goto_previous_sibling_wasm=e.ts_tree_cursor_goto_previous_sibling_wasm,Module._ts_tree_cursor_goto_descendant_wasm=_ts_tree_cursor_goto_descendant_wasm=e.ts_tree_cursor_goto_descendant_wasm,Module._ts_tree_cursor_goto_parent_wasm=_ts_tree_cursor_goto_parent_wasm=e.ts_tree_cursor_goto_parent_wasm,Module._ts_tree_cursor_current_node_type_id_wasm=_ts_tree_cursor_current_node_type_id_wasm=e.ts_tree_cursor_current_node_type_id_wasm,Module._ts_tree_cursor_current_node_state_id_wasm=_ts_tree_cursor_current_node_state_id_wasm=e.ts_tree_cursor_current_node_state_id_wasm,Module._ts_tree_cursor_current_node_is_named_wasm=_ts_tree_cursor_current_node_is_named_wasm=e.ts_tree_cursor_current_node_is_named_wasm,Module._ts_tree_cursor_current_node_is_missing_wasm=_ts_tree_cursor_current_node_is_missing_wasm=e.ts_tree_cursor_current_node_is_missing_wasm,Module._ts_tree_cursor_current_node_id_wasm=_ts_tree_cursor_current_node_id_wasm=e.ts_tree_cursor_current_node_id_wasm,Module._ts_tree_cursor_start_position_wasm=_ts_tree_cursor_start_position_wasm=e.ts_tree_cursor_start_position_wasm,Module._ts_tree_cursor_end_position_wasm=_ts_tree_cursor_end_position_wasm=e.ts_tree_cursor_end_position_wasm,Module._ts_tree_cursor_start_index_wasm=_ts_tree_cursor_start_index_wasm=e.ts_tree_cursor_start_index_wasm,Module._ts_tree_cursor_end_index_wasm=_ts_tree_cursor_end_index_wasm=e.ts_tree_cursor_end_index_wasm,Module._ts_tree_cursor_current_field_id_wasm=_ts_tree_cursor_current_field_id_wasm=e.ts_tree_cursor_current_field_id_wasm,Module._ts_tree_cursor_current_depth_wasm=_ts_tree_cursor_current_depth_wasm=e.ts_tree_cursor_current_depth_wasm,Module._ts_tree_cursor_current_descendant_index_wasm=_ts_tree_cursor_current_descendant_index_wasm=e.ts_tree_cursor_current_descendant_index_wasm,Module._ts_tree_cursor_current_node_wasm=_ts_tree_cursor_current_node_wasm=e.ts_tree_cursor_current_node_wasm,Module._ts_node_symbol_wasm=_ts_node_symbol_wasm=e.ts_node_symbol_wasm,Module._ts_node_field_name_for_child_wasm=_ts_node_field_name_for_child_wasm=e.ts_node_field_name_for_child_wasm,Module._ts_node_field_name_for_named_child_wasm=_ts_node_field_name_for_named_child_wasm=e.ts_node_field_name_for_named_child_wasm,Module._ts_node_children_by_field_id_wasm=_ts_node_children_by_field_id_wasm=e.ts_node_children_by_field_id_wasm,Module._ts_node_first_child_for_byte_wasm=_ts_node_first_child_for_byte_wasm=e.ts_node_first_child_for_byte_wasm,Module._ts_node_first_named_child_for_byte_wasm=_ts_node_first_named_child_for_byte_wasm=e.ts_node_first_named_child_for_byte_wasm,Module._ts_node_grammar_symbol_wasm=_ts_node_grammar_symbol_wasm=e.ts_node_grammar_symbol_wasm,Module._ts_node_child_count_wasm=_ts_node_child_count_wasm=e.ts_node_child_count_wasm,Module._ts_node_named_child_count_wasm=_ts_node_named_child_count_wasm=e.ts_node_named_child_count_wasm,Module._ts_node_child_wasm=_ts_node_child_wasm=e.ts_node_child_wasm,Module._ts_node_named_child_wasm=_ts_node_named_child_wasm=e.ts_node_named_child_wasm,Module._ts_node_child_by_field_id_wasm=_ts_node_child_by_field_id_wasm=e.ts_node_child_by_field_id_wasm,Module._ts_node_next_sibling_wasm=_ts_node_next_sibling_wasm=e.ts_node_next_sibling_wasm,Module._ts_node_prev_sibling_wasm=_ts_node_prev_sibling_wasm=e.ts_node_prev_sibling_wasm,Module._ts_node_next_named_sibling_wasm=_ts_node_next_named_sibling_wasm=e.ts_node_next_named_sibling_wasm,Module._ts_node_prev_named_sibling_wasm=_ts_node_prev_named_sibling_wasm=e.ts_node_prev_named_sibling_wasm,Module._ts_node_descendant_count_wasm=_ts_node_descendant_count_wasm=e.ts_node_descendant_count_wasm,Module._ts_node_parent_wasm=_ts_node_parent_wasm=e.ts_node_parent_wasm,Module._ts_node_child_with_descendant_wasm=_ts_node_child_with_descendant_wasm=e.ts_node_child_with_descendant_wasm,Module._ts_node_descendant_for_index_wasm=_ts_node_descendant_for_index_wasm=e.ts_node_descendant_for_index_wasm,Module._ts_node_named_descendant_for_index_wasm=_ts_node_named_descendant_for_index_wasm=e.ts_node_named_descendant_for_index_wasm,Module._ts_node_descendant_for_position_wasm=_ts_node_descendant_for_position_wasm=e.ts_node_descendant_for_position_wasm,Module._ts_node_named_descendant_for_position_wasm=_ts_node_named_descendant_for_position_wasm=e.ts_node_named_descendant_for_position_wasm,Module._ts_node_start_point_wasm=_ts_node_start_point_wasm=e.ts_node_start_point_wasm,Module._ts_node_end_point_wasm=_ts_node_end_point_wasm=e.ts_node_end_point_wasm,Module._ts_node_start_index_wasm=_ts_node_start_index_wasm=e.ts_node_start_index_wasm,Module._ts_node_end_index_wasm=_ts_node_end_index_wasm=e.ts_node_end_index_wasm,Module._ts_node_to_string_wasm=_ts_node_to_string_wasm=e.ts_node_to_string_wasm,Module._ts_node_children_wasm=_ts_node_children_wasm=e.ts_node_children_wasm,Module._ts_node_named_children_wasm=_ts_node_named_children_wasm=e.ts_node_named_children_wasm,Module._ts_node_descendants_of_type_wasm=_ts_node_descendants_of_type_wasm=e.ts_node_descendants_of_type_wasm,Module._ts_node_is_named_wasm=_ts_node_is_named_wasm=e.ts_node_is_named_wasm,Module._ts_node_has_changes_wasm=_ts_node_has_changes_wasm=e.ts_node_has_changes_wasm,Module._ts_node_has_error_wasm=_ts_node_has_error_wasm=e.ts_node_has_error_wasm,Module._ts_node_is_error_wasm=_ts_node_is_error_wasm=e.ts_node_is_error_wasm,Module._ts_node_is_missing_wasm=_ts_node_is_missing_wasm=e.ts_node_is_missing_wasm,Module._ts_node_is_extra_wasm=_ts_node_is_extra_wasm=e.ts_node_is_extra_wasm,Module._ts_node_parse_state_wasm=_ts_node_parse_state_wasm=e.ts_node_parse_state_wasm,Module._ts_node_next_parse_state_wasm=_ts_node_next_parse_state_wasm=e.ts_node_next_parse_state_wasm,Module._ts_query_matches_wasm=_ts_query_matches_wasm=e.ts_query_matches_wasm,Module._ts_query_captures_wasm=_ts_query_captures_wasm=e.ts_query_captures_wasm,Module._memset=_memset=e.memset,Module._memcpy=_memcpy=e.memcpy,Module._memmove=_memmove=e.memmove,Module._iswalpha=_iswalpha=e.iswalpha,Module._iswblank=_iswblank=e.iswblank,Module._iswdigit=_iswdigit=e.iswdigit,Module._iswlower=_iswlower=e.iswlower,Module._iswupper=_iswupper=e.iswupper,Module._iswxdigit=_iswxdigit=e.iswxdigit,Module._memchr=_memchr=e.memchr,Module._strlen=_strlen=e.strlen,Module._strcmp=_strcmp=e.strcmp,Module._strncat=_strncat=e.strncat,Module._strncpy=_strncpy=e.strncpy,Module._towlower=_towlower=e.towlower,Module._towupper=_towupper=e.towupper,_setThrew=e.setThrew,__emscripten_stack_restore=e._emscripten_stack_restore,__emscripten_stack_alloc=e._emscripten_stack_alloc,_emscripten_stack_get_current=e.emscripten_stack_get_current,___wasm_apply_data_relocs=e.__wasm_apply_data_relocs}C(assignWasmExports,"assignWasmExports");var wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_high:___stack_high,__stack_low:___stack_low,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback,tree_sitter_progress_callback:_tree_sitter_progress_callback,tree_sitter_query_progress_callback:_tree_sitter_query_progress_callback};function callMain(e=[]){var t=resolveGlobalSymbol("main").sym;if(t){e.unshift(thisProgram);var n=e.length,r=stackAlloc((n+1)*4),s=r;e.forEach(a=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=t(n,r);return exitJS(o,!0),o}catch(a){return handleException(a)}}}C(callMain,"callMain");function run(e=arguments_){if(runDependencies>0){dependenciesFulfilled=run;return}if(preRun(),runDependencies>0){dependenciesFulfilled=run;return}function t(){if(Module.calledRun=!0,!ABORT){initRuntime(),readyPromiseResolve?.(Module),Module.onRuntimeInitialized?.();var n=Module.noInitialRun||!1;n||callMain(e),postRun()}}C(t,"doRun"),Module.setStatus?(Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1)):t()}C(run,"run");var wasmExports;return wasmExports=await createWasm(),run(),runtimeInitialized?moduleRtn=Module:moduleRtn=new Promise((e,t)=>{readyPromiseResolve=e,readyPromiseReject=t}),moduleRtn}async function xc(e){return wc??=await Dm(e)}function Sc(){return!!wc}function Ec(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!fc(e[1]))throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}"`);let s=n==="eq?"||n==="any-eq?",o=!n.startsWith("any-");if(fc(e[2])){let a=e[1].name,l=e[2].name;r[t].push(c=>{let d=[],f=[];for(let m of c)m.name===a&&d.push(m.node),m.name===l&&f.push(m.node);let u=C((m,p,g)=>g?m.text===p.text:m.text!==p.text,"compare");return o?d.every(m=>f.some(p=>u(m,p,s))):d.some(m=>f.some(p=>u(m,p,s)))})}else{let a=e[1].name,l=e[2].value,c=C(f=>f.text===l,"matches"),d=C(f=>f.text!==l,"doesNotMatch");r[t].push(f=>{let u=[];for(let p of f)p.name===a&&u.push(p.node);let m=s?c:d;return o?u.every(m):u.some(m)})}}function vc(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);if(e[2].type!=="string")throw new Error(`Second argument of \`#${n}\` predicate must be a string. Got @${e[2].name}.`);let s=n==="match?"||n==="any-match?",o=!n.startsWith("any-"),a=e[1].name,l=new RegExp(e[2].value);r[t].push(c=>{let d=[];for(let u of c)u.name===a&&d.push(u.node.text);let f=C((u,m)=>m?l.test(u):!l.test(u),"test");return d.length===0?!s:o?d.every(u=>f(u,s)):d.some(u=>f(u,s))})}function Rc(e,t,n,r){if(e.length<2)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected at least 1. Got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);let s=n==="any-of?",o=e[1].name,a=e.slice(2);if(!a.every(_o))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let l=a.map(c=>c.value);r[t].push(c=>{let d=[];for(let f of c)f.name===o&&d.push(f.node.text);return d.length===0?!s:d.every(f=>l.includes(f))===s})}function Mc(e,t,n,r,s){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(_o))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let o=n==="is?"?r:s;o[t]||(o[t]={}),o[t][e[1].value]=e[2]?.value??null}function Cc(e,t,n){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(_o))throw new Error('Arguments to `#set!` predicate must be strings.".');n[t]||(n[t]={}),n[t][e[1].value]=e[2]?.value??null}function Ac(e,t,n,r,s,o,a,l,c,d,f){if(t===Lm){let u=r[n];o.push({type:"capture",name:u})}else if(t===jm)o.push({type:"string",value:s[n]});else if(o.length>0){if(o[0].type!=="string")throw new Error("Predicates must begin with a literal value");let u=o[0].value;switch(u){case"any-not-eq?":case"not-eq?":case"any-eq?":case"eq?":Ec(o,e,u,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":vc(o,e,u,a);break;case"not-any-of?":case"any-of?":Rc(o,e,u,a);break;case"is?":case"is-not?":Mc(o,e,u,d,f);break;case"set!":Cc(o,e,c);break;default:l[e].push({operator:u,operands:o.slice(1)})}o.length=0}}var Im,C,Sx,uc,W,ao,De,dt,Kn,$e,Ft,x,Nm,Fm,Om,Pm,$m,po,Dm,wc,L,lo,co,go,Lm,jm,Wm,kx,fc,_o,Ye,Vn,Tc,ho=O(()=>{E();Im=Object.defineProperty,C=(e,t)=>Im(e,"name",{value:t,configurable:!0}),Sx=class{static{C(this,"Edit")}startPosition;oldEndPosition;newEndPosition;startIndex;oldEndIndex;newEndIndex;constructor({startIndex:e,oldEndIndex:t,newEndIndex:n,startPosition:r,oldEndPosition:s,newEndPosition:o}){this.startIndex=e>>>0,this.oldEndIndex=t>>>0,this.newEndIndex=n>>>0,this.startPosition=r,this.oldEndPosition=s,this.newEndPosition=o}editPoint(e,t){let n=t,r={...e};if(t>=this.oldEndIndex){n=this.newEndIndex+(t-this.oldEndIndex);let s=e.row;r.row=this.newEndPosition.row+(e.row-this.oldEndPosition.row),r.column=s===this.oldEndPosition.row?this.newEndPosition.column+(e.column-this.oldEndPosition.column):e.column}else t>this.startIndex&&(n=this.newEndIndex,r.row=this.newEndPosition.row,r.column=this.newEndPosition.column);return{point:r,index:n}}editRange(e){let t={startIndex:e.startIndex,startPosition:{...e.startPosition},endIndex:e.endIndex,endPosition:{...e.endPosition}};return e.endIndex>=this.oldEndIndex?e.endIndex!==Number.MAX_SAFE_INTEGER&&(t.endIndex=this.newEndIndex+(e.endIndex-this.oldEndIndex),t.endPosition={row:this.newEndPosition.row+(e.endPosition.row-this.oldEndPosition.row),column:e.endPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.endPosition.column-this.oldEndPosition.column):e.endPosition.column},t.endIndexthis.startIndex&&(t.endIndex=this.startIndex,t.endPosition={...this.startPosition}),e.startIndex>=this.oldEndIndex?(t.startIndex=this.newEndIndex+(e.startIndex-this.oldEndIndex),t.startPosition={row:this.newEndPosition.row+(e.startPosition.row-this.oldEndPosition.row),column:e.startPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.startPosition.column-this.oldEndPosition.column):e.startPosition.column},t.startIndexthis.startIndex&&(t.startIndex=this.startIndex,t.startPosition={...this.startPosition}),t}},uc=2,W=4,ao=4*W,De=5*W,dt=2*W,Kn=2*W+2*dt,$e={row:0,column:0},Ft=Symbol("INTERNAL");C(wn,"assertInternal");C(Jn,"isPoint");C(mc,"setModule");Nm=class{static{C(this,"LookaheadIterator")}0=0;language;constructor(e,t,n){wn(e),this[0]=t,this.language=n}get currentTypeId(){return x._ts_lookahead_iterator_current_symbol(this[0])}get currentType(){return this.language.types[this.currentTypeId]||"ERROR"}delete(){x._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(e,t){return x._ts_lookahead_iterator_reset(this[0],e[0],t)?(this.language=e,!0):!1}resetState(e){return!!x._ts_lookahead_iterator_reset_state(this[0],e)}[Symbol.iterator](){return{next:C(()=>x._ts_lookahead_iterator_next(this[0])?{done:!1,value:this.currentType}:{done:!0,value:""},"next")}}};C(mo,"getText");Fm=class uo{static{C(this,"Tree")}0=0;textCallback;language;constructor(t,n,r,s){wn(t),this[0]=n,this.language=r,this.textCallback=s}copy(){let t=x._ts_tree_copy(this[0]);return new uo(Ft,t,this.language,this.textCallback)}delete(){x._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return x._ts_tree_root_node_wasm(this[0]),ue(this)}rootNodeWithOffset(t,n){let r=L+De;return x.setValue(r,t,"i32"),Ve(r+W,n),x._ts_tree_root_node_with_offset_wasm(this[0]),ue(this)}edit(t){_c(t),x._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(t){if(!(t instanceof uo))throw new TypeError("Argument must be a Tree");x._ts_tree_get_changed_ranges_wasm(this[0],t[0]);let n=x.getValue(L,"i32"),r=x.getValue(L+W,"i32"),s=new Array(n);if(n>0){let o=r;for(let a=0;a0){let s=n;for(let o=0;o0){let s=n;for(let o=0;o0){let n=t;for(let r=0;r0){let n=t;for(let r=0;r0){let d=l;for(let f=0;f=e.oldEndIndex){this.startIndex=e.newEndIndex+(this.startIndex-e.oldEndIndex);let t,n;this.startPosition.row>e.oldEndPosition.row?(t=this.startPosition.row-e.oldEndPosition.row,n=this.startPosition.column):(t=0,n=this.startPosition.column,this.startPosition.column>=e.oldEndPosition.column&&(n=this.startPosition.column-e.oldEndPosition.column)),t>0?(this.startPosition.row+=t,this.startPosition.column=n):this.startPosition.column+=n}else this.startIndex>e.startIndex&&(this.startIndex=e.newEndIndex,this.startPosition.row=e.newEndPosition.row,this.startPosition.column=e.newEndPosition.column)}toString(){G(this);let e=x._ts_node_to_string_wasm(this.tree[0]),t=x.AsciiToString(e);return x._free(e),t}};C(fo,"unmarshalCaptures");C(G,"marshalNode");C(ue,"unmarshalNode");C(le,"marshalTreeCursor");C(Be,"unmarshalTreeCursor");C(Ve,"marshalPoint");C(Jt,"unmarshalPoint");C(gc,"marshalRange");C(Es,"unmarshalRange");C(_c,"marshalEdit");C(hc,"unmarshalLanguageMetadata");$m=/^tree_sitter_\w+$/,po=class yc{static{C(this,"Language")}0=0;types;fields;constructor(t,n){wn(t),this[0]=n,this.types=new Array(x._ts_language_symbol_count(this[0]));for(let r=0,s=this.types.length;r0){let s=n;for(let o=0;o0){let o=r;for(let a=0;a(oo(),io))).readFile(t);else{let l=await fetch(t);if(!l.ok){let d=await l.text();throw new Error(`Language.load failed with status ${l.status}. -${d}`)}let c=l.clone();try{n=await WebAssembly.compileStreaming(l)}catch(d){console.error("wasm streaming compile failed:",d),console.error("falling back to ArrayBuffer instantiation"),n=new Uint8Array(await c.arrayBuffer())}}let r=await w.loadWebAssemblyModule(n,{loadAsync:!0}),s=Object.keys(r),o=s.find(l=>hm.test(l)&&!l.includes("external_scanner_"));if(!o)throw console.log(`Couldn't find language function in Wasm file. Symbols: -${JSON.stringify(s,null,2)}`),new Error("Language.load failed: no language function found in Wasm file");let a=r[o]();return new fc(Nt,a)}};C(mc,"Module");ym=mc,pc=null;C(gc,"initializeBinding");C(_c,"checkModule");fo=class{static{C(this,"Parser")}0=0;1=0;logCallback=null;language=null;static async init(e){ac(await gc(e)),D=w._ts_init(),io=w.getValue(D,"i32"),oo=w.getValue(D+W,"i32")}constructor(){this.initialize()}initialize(){if(!_c())throw new Error("cannot construct a Parser before calling `init()`");w._ts_parser_new_wasm(),this[0]=w.getValue(D,"i32"),this[1]=w.getValue(D+W,"i32")}delete(){w._ts_parser_delete(this[0]),w._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,this.language=null;else if(e.constructor===uo){t=e[0];let n=w._ts_language_abi_version(t);if(ne.slice(l);else if(typeof e=="function")w.currentParseCallback=e;else throw new Error("Argument must be a string or a function");n?.progressCallback?w.currentProgressCallback=n.progressCallback:w.currentProgressCallback=null,this.logCallback?(w.currentLogCallback=this.logCallback,w._ts_parser_enable_logger_wasm(this[0],1)):(w.currentLogCallback=null,w._ts_parser_enable_logger_wasm(this[0],0));let r=0,s=0;if(n?.includedRanges){r=n.includedRanges.length,s=w._calloc(r,Jn);let l=s;for(let c=0;c0){let r=t;for(let s=0;se.type==="capture","isCaptureStep"),mo=C(e=>e.type==="string","isStringStep"),Ye={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},Gn=class hc extends Error{constructor(t,n,r,s){super(hc.formatMessage(t,n)),this.kind=t,this.info=n,this.index=r,this.length=s,this.name="QueryError"}static{C(this,"QueryError")}static formatMessage(t,n){switch(t){case Ye.NodeName:return`Bad node name '${n.word}'`;case Ye.FieldName:return`Bad field name '${n.word}'`;case Ye.CaptureName:return`Bad capture name @${n.word}`;case Ye.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case Ye.Syntax:return`Bad syntax at offset ${n.suffix}`}}};C(yc,"parseAnyPredicate");C(bc,"parseMatchPredicate");C(wc,"parseAnyOfPredicate");C(xc,"parseIsPredicate");C(Sc,"parseSetDirective");C(kc,"parsePattern");Ec=class{static{C(this,"Query")}0=0;exceededMatchLimit;textPredicates;captureNames;captureQuantifiers;predicates;setProperties;assertedProperties;refutedProperties;matchLimit;constructor(e,t){let n=w.lengthBytesUTF8(t),r=w._malloc(n+1);w.stringToUTF8(t,r,n+1);let s=w._ts_query_new(e[0],r,n,D,D+W);if(!s){let h=w.getValue(D+W,"i32"),S=w.getValue(D,"i32"),_=w.UTF8ToString(r,S).length,E=t.slice(_,_+100).split(` -`)[0],b=E.match(xm)?.[0]??"";switch(w._free(r),h){case Ye.Syntax:throw new Gn(Ye.Syntax,{suffix:`${_}: '${E}'...`},_,0);case Ye.NodeName:throw new Gn(h,{word:b},_,b.length);case Ye.FieldName:throw new Gn(h,{word:b},_,b.length);case Ye.CaptureName:throw new Gn(h,{word:b},_,b.length);case Ye.PatternStructure:throw new Gn(h,{suffix:`${_}: '${E}'...`},_,0)}}let o=w._ts_query_string_count(s),a=w._ts_query_capture_count(s),l=w._ts_query_pattern_count(s),c=new Array(a),d=new Array(l),f=new Array(o);for(let h=0;ho)throw new Error("`startIndex` cannot be greater than `endIndex`");if(r!==$e&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw new Error("`startPosition` cannot be greater than `endPosition`");if(d!==0&&c>d)throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==$e&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");m&&(w.currentQueryProgressCallback=m),q(e),w._ts_query_matches_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,d,f,u);let p=w.getValue(D,"i32"),g=w.getValue(D+W,"i32"),y=w.getValue(D+2*W,"i32"),h=new Array(p);this.exceededMatchLimit=!!y;let S=0,_=g;for(let E=0;EA(v))){h[S]={patternIndex:b,captures:v};let A=this.setProperties[b];h[S].setProperties=A;let O=this.assertedProperties[b];h[S].assertedProperties=O;let N=this.refutedProperties[b];h[S].refutedProperties=N,S++}}return h.length=S,w._free(g),w.currentQueryProgressCallback=null,h}captures(e,t={}){let n=t.startPosition??$e,r=t.endPosition??$e,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??$e,l=t.endContainingPosition??$e,c=t.startContainingIndex??0,d=t.endContainingIndex??0,f=t.matchLimit??4294967295,u=t.maxStartDepth??4294967295,m=t.progressCallback;if(typeof f!="number")throw new Error("Arguments must be numbers");if(this.matchLimit=f,o!==0&&s>o)throw new Error("`startIndex` cannot be greater than `endIndex`");if(r!==$e&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw new Error("`startPosition` cannot be greater than `endPosition`");if(d!==0&&c>d)throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==$e&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");m&&(w.currentQueryProgressCallback=m),q(e),w._ts_query_captures_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,d,f,u);let p=w.getValue(D,"i32"),g=w.getValue(D+W,"i32"),y=w.getValue(D+2*W,"i32"),h=new Array;this.exceededMatchLimit=!!y;let S=new Array,_=g;for(let E=0;EA(S))){let A=S[v],O=this.setProperties[b];A.setProperties=O;let N=this.assertedProperties[b];A.assertedProperties=N;let U=this.refutedProperties[b];A.refutedProperties=U,h.push(A)}}return w._free(g),w.currentQueryProgressCallback=null,h}predicatesForPattern(e){return this.predicates[e]}disableCapture(e){let t=w.lengthBytesUTF8(e),n=w._malloc(t+1);w.stringToUTF8(e,n,t+1),w._ts_query_disable_capture(this[0],n,t),w._free(n)}disablePattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);w._ts_query_disable_pattern(this[0],e)}didExceedMatchLimit(){return this.exceededMatchLimit}startIndexForPattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return w._ts_query_start_byte_for_pattern(this[0],e)}endIndexForPattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return w._ts_query_end_byte_for_pattern(this[0],e)}patternCount(){return w._ts_query_pattern_count(this[0])}captureIndexForName(e){return this.captureNames.indexOf(e)}isPatternRooted(e){return w._ts_query_is_pattern_rooted(this[0],e)===1}isPatternNonLocal(e){return w._ts_query_is_pattern_non_local(this[0],e)===1}isPatternGuaranteedAtStep(e){return w._ts_query_is_pattern_guaranteed_at_step(this[0],e)===1}}});function Yn(e){return Es[e]}function wn(){let e=R.env.XDG_CACHE_HOME,t=e&&e.trim()?e.trim():I(rc(),".cache");return I(t,"codeindex","grammars",fe)}function Qe(e={}){let t=wn(),n=(l,c)=>({tier:l,dir:c,cacheDir:t,dirs:[c,...H(I(c,"..",vc))?[I(c,"..",vc)]:[]]}),r=R.env.CODEINDEX_GRAMMAR_DIR??R.env.ULTRAINDEX_GRAMMAR_DIR;if(r&&r.trim()&&H(r))return n("env",r);let s=e.moduleDir??_e(bs(import.meta.url)),o=[I(s,"grammars"),I(s,"..","..","scripts","grammars"),I(s,"..","scripts","grammars")];for(let l of o)if(H(l))return n("adjacent",l);let a=R.env.CODEINDEX_GRAMMARS_DIR;return a&&a.trim()&&H(a)?n("env",a):H(t)?n("cache",t):{tier:"none",cacheDir:t,dirs:[]}}function Sm(e){return Qe(e).dir}async function et(e){let{dirs:t}=Qe();if(!t.length)return;let n=r=>{for(let s of t){let o=I(s,r);if(H(o))return o}};if(!Rc){let r=n("web-tree-sitter.wasm");if(!r)return;await fo.init({wasmBinary:te(r)}),Rc=!0,ks=new fo}for(let r of new Set(e)){if(Kn.has(r))continue;let s=n(`${r}.wasm`),o=s?(()=>{try{let a=Ee(s);return`${s}:${a.size}:${a.mtimeMs}`}catch{return`${s}:unreadable`}})():`missing:${t.join("|")}`;if(Ss.get(r)!==o){if(!s){Ss.set(r,o);continue}try{Kn.set(r,await uo.load(new Uint8Array(te(s)))),Ss.delete(r)}catch{Ss.set(r,o)}}}}function go(){return[...new Set(Object.values(Es))]}function bt(e){let t=new Set;for(let n of e){let r=Es[n];r!==void 0&&t.add(r)}return[...t].sort()}function tt(e){return Kn.has(e)}function _o(e){return Kn.get(e)}function vs(e){let t=Kn.get(e);return!ks||!t?null:(ks.setLanguage(t),ks)}var Xn,Zn,Es,vc,Rc,ks,Kn,Ss,nt=F(()=>{"use strict";k();xe();to();oe();ws();po();Xe();Xn=new Set(["typescript","tsx","javascript","python","go","rust","java","ruby","c","cpp","c_sharp","php","scala","bash","lua"]),Zn=new Set(["kotlin","elixir","zig","hcl","terraform","solidity"]),Es={".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".go":"go",".rs":"rust",".java":"java",".rb":"ruby",".rake":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"c_sharp",".php":"php",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".lua":"lua",".kt":"kotlin",".kts":"kotlin",".ex":"elixir",".exs":"elixir",".zig":"zig",".hcl":"hcl",".tf":"terraform",".tfvars":"terraform",".sol":"solidity"};vc="grammars-extended";Rc=!1,ks=null,Kn=new Map,Ss=new Map});function Te(e,t){for(let n of e.namedChildren){if(t(n))return n;let r=Te(n,t);if(r)return r}}function Qn(e){let t=e.childForFieldName("name");if(t?.text)return t.text;let n=e.childForFieldName("declarator");for(;n;){let o=n.childForFieldName("name");if(o?.text)return o.text;if(n.namedChildren.length===0&&/(^|_)identifier$/.test(n.type))return n.text;let a=n.childForFieldName("declarator");if(!a||a===n)break;n=a}let s=Te(e,o=>o.type==="variable_declarator")?.childForFieldName("name");if(s?.text)return s.text;for(let o of e.namedChildren)if(/(^|_)(identifier|name|constant)$/.test(o.type))return o.text}function Kt(e){if(!e)return;let t=e.namedChildren;if(t.length===0)return Rs.test(e.type)?e.text:void 0;let n=e.childForFieldName("name")??e.childForFieldName("property")??e.childForFieldName("attribute")??e.childForFieldName("field")??e.childForFieldName("function");if(n)return Kt(n);let r=t[t.length-1];return r&&r!==e?Kt(r):void 0}function er(e){if(!e||e.namedChildren.length===0)return;let t=e.childForFieldName("object")??e.childForFieldName("operand")??e.childForFieldName("value")??e.childForFieldName("path")??e.childForFieldName("expression")??e.childForFieldName("argument")??e.childForFieldName("receiver")??e.childForFieldName("table"),n=t?Kt(t):void 0;return n&&/^[A-Za-z_]\w*$/.test(n)?n:void 0}function ze(e){if(!e)return;let t=e.childForFieldName("type")??e.childForFieldName("name");if(t&&/generic|qualified|scoped|nested/.test(e.type))return ze(t);if(e.namedChildren.length===0)return Mc.test(e.type)?e.text:void 0;let n,r=s=>{if(s.namedChildren.length===0){Mc.test(s.type)&&(n=s.text);return}if(!/arguments|parameters/.test(s.type))for(let o of s.namedChildren)r(o)};return r(e),n}var Rs,Mc,ho=F(()=>{"use strict";k();Rs=/(^|_)(identifier|name|constant|word)$/;Mc=/identifier|constant|(^|_)name$/});function Oe(e){if(!e)return[];let t=[];for(let n of e.namedChildren){if(/arguments|parameters/.test(n.type))continue;let r=ze(n);r&&t.push(r)}return t}function Cc(e,t){if(!t.self)return[];let n=he(e,"class_heritage");if(!n)return[];let r=[];for(let s of Oe(he(n,"extends_clause")))r.push(ge("extends",t.self,s,e));for(let s of Oe(he(n,"implements_clause")))r.push(ge("implements",t.self,s,e));return r}function tr(e,t,n){return Oe(e).map((s,o)=>ge(o===0?"extends":"implements",t,s,n))}var he,ge,Fc,wo,Cs,Ac,yo,km,Tc,Ic,Em,nr,vm,Ms,Nc,Rm,Oc,bo,Pc,$c=F(()=>{"use strict";k();ho();he=(e,t)=>e.namedChildren.find(n=>n.type===t),ge=(e,t,n,r)=>({kind:e,from:t,to:n,line:r.startPosition.row+1});Fc=new Set(["interface","trait","enum","protocol","annotation"]),wo=new Set(["function","method","def","constructor","operator"]),Cs=new Set(["function","function_expression","arrow_function","generator_function","class","function_definition","lambda"]),Ac=e=>/\b(public|internal)\b/.test(e),yo=e=>!/\b(private|protected)\b/.test(e),km=e=>!/^local\b/.test(e),Tc=e=>/\bpub\b/.test(e),Ic=(e,t)=>/^[A-Z]/.test(t),Em=(e,t)=>!t.startsWith("_")||/^__\w+__$/.test(t),nr=()=>!0,vm=()=>!1,Ms=e=>Te(e,t=>t.type==="function_declarator")!==void 0,Nc={defmodule:"module",defprotocol:"protocol",defimpl:"impl",defstruct:"struct",defexception:"exception",def:"function",defp:"function",defmacro:"macro",defmacrop:"macro",defguard:"guard",defguardp:"guard",defdelegate:"function"},Rm=new Set(["resource","data","variable","output","module","provider","locals","terraform"]),Oc={lang:"terraform",defs:{block:"block"},containers:new Set(["config_file","body"]),exported:nr,kindFrom:{block:e=>{let t=e.namedChildren.find(n=>n.type==="identifier")?.text;return t&&Rm.has(t)?t:void 0}},nameFrom:{block:e=>{let t=e.namedChildren.filter(n=>n.type==="string_lit").map(n=>n.text.replace(/^"|"$/g,""));return t.length?t.join("."):e.namedChildren.find(n=>n.type==="identifier")?.text}}},bo={lang:"typescript",defs:{function_declaration:"function",generator_function_declaration:"function",function_signature:"function",class_declaration:"class",abstract_class_declaration:"class",interface_declaration:"interface",type_alias_declaration:"type",enum_declaration:"enum",enum_assignment:"enum-member",method_definition:"method",method_signature:"method",abstract_method_signature:"method",property_signature:"property",public_field_definition:"property",call_signature:"call-signature",construct_signature:"construct-signature",index_signature:"index-signature",internal_module:"namespace",module:"namespace",variable_declarator:"const"},containers:new Set(["class_body","export_statement","ambient_declaration","program","lexical_declaration","variable_declaration","interface_body","object_type","enum_body","statement_block","try_statement","catch_clause","finally_clause","if_statement","else_clause","for_statement","for_in_statement","while_statement","do_statement","switch_statement","switch_body","switch_case","switch_default","labeled_statement","return_statement","expression_statement","call_expression","arguments","arrow_function","function_expression","function","parenthesized_expression"]),exported:vm,exportMarkers:new Set(["export_statement","ambient_declaration"]),bareMembers:{enum_body:"enum-member"},nameFrom:{call_signature:()=>"(call)",construct_signature:()=>"(construct)",index_signature:e=>`[${e.namedChildren.find(t=>t.type==="identifier")?.text??"key"}]`},privateMember:e=>{for(let t of e.namedChildren)if(t.type==="accessibility_modifier"&&/^(private|protected)/.test(t.text)||t.type==="private_property_identifier")return!0;return!1},imports:{import_statement:"string"},calls:{call_expression:"function",new_expression:"constructor"},assignments:!0,relationsFrom:{class_declaration:Cc,abstract_class_declaration:Cc,interface_declaration:(e,t)=>t.self?Oe(he(e,"extends_type_clause")).map(n=>ge("extends",t.self,n,e)):[]}},Pc={typescript:bo,tsx:{...bo,lang:"typescript"},javascript:{...bo,lang:"javascript",defs:{function_declaration:"function",generator_function_declaration:"function",class_declaration:"class",method_definition:"method",field_definition:"property",variable_declarator:"const"}},python:{lang:"python",defs:{function_definition:"function",class_definition:"class"},containers:new Set(["block","decorated_definition","module"]),exported:Em,imports:{import_statement:"path",import_from_statement:"path"},calls:{call:"function"},docstring:!0,relationsFrom:{class_definition:(e,t)=>t.self?Oe(e.childForFieldName("superclasses")).map(n=>ge("extends",t.self,n,e)):[]},extraMembers:(e,t)=>{if(t.inFunctionBody)return[];if(e.type==="import_from_statement"){let s=[];for(let o of e.namedChildren){if(o.type!=="aliased_import")continue;let a=o.namedChildren[0]?.text,l=o.childForFieldName("alias")?.text;a&&l&&a===l&&s.push({name:l,kind:"reexport"})}return s}if(e.type!=="expression_statement")return[];let n=e.namedChildren[0];if(!n||n.type!=="assignment")return[];let r=n.childForFieldName("left");return!r||r.type!=="identifier"?[]:[{name:r.text,kind:t.ownerKind==="class"?"field":"const"}]}},go:{lang:"go",defs:{function_declaration:"function",method_declaration:"method",type_spec:"type",const_spec:"const",var_spec:"var",field_declaration:"field",method_spec:"method",method_elem:"method",package_clause:"package"},containers:new Set(["type_declaration","const_declaration","var_declaration","var_spec_list","source_file","struct_type","interface_type","field_declaration_list"]),exported:Ic,imports:{import_declaration:"string"},calls:{call_expression:"function"},parentFrom:{method_declaration:e=>ze(e.childForFieldName("receiver"))},nameFrom:{field_declaration:e=>e.childForFieldName("name")?.text},relationsFrom:{field_declaration:(e,t)=>{if(!t.self||e.childForFieldName("name"))return[];let n=ze(e.childForFieldName("type"));return n?[ge("extends",t.self,n,e)]:[]}}},ruby:{lang:"ruby",defs:{method:"def",singleton_method:"def",class:"class",module:"module"},containers:new Set(["class","module","body_statement","program"]),exported:nr,calls:{call:"function"},sectionVisibility:e=>(e.type==="identifier"||e.type==="call")&&/^(private|protected)$/.test(e.text)?!1:e.type==="identifier"&&e.text==="public"?!0:void 0,relationsFrom:{class:(e,t)=>{if(!t.self)return[];let n=ze(e.childForFieldName("superclass"));return n?[ge("extends",t.self,n,e)]:[]},call:(e,t)=>{let n=e.childForFieldName("method");if(!t.self||!n||!/^(include|prepend|extend)$/.test(n.text))return[];let r=[];for(let s of e.childForFieldName("arguments")?.namedChildren??[]){let o=ze(s);o&&r.push(ge("implements",t.self,o,e))}return r}},extraMembers:(e,t)=>{if(t.inFunctionBody)return[];if(e.type==="assignment"){let n=e.childForFieldName("left");return n?.type==="constant"?[{name:n.text,kind:"const"}]:[]}if(e.type==="call"){let n=e.childForFieldName("method");if(!n||!/^attr_(reader|writer|accessor)$/.test(n.text))return[];let r=e.childForFieldName("arguments"),s=[];for(let o of r?.namedChildren??[])o.type==="simple_symbol"&&s.push({name:o.text.replace(/^:/,""),kind:"attr"});return s}return[]}},java:{lang:"java",defs:{class_declaration:"class",interface_declaration:"interface",annotation_type_declaration:"annotation",enum_declaration:"enum",enum_constant:"enum-member",record_declaration:"record",method_declaration:"method",constructor_declaration:"constructor",compact_constructor_declaration:"constructor",field_declaration:"field",constant_declaration:"field",annotation_type_element_declaration:"method"},containers:new Set(["class_body","interface_body","enum_body","enum_body_declarations","annotation_type_body","program","formal_parameters"]),exported:Ac,imports:{import_declaration:"path"},calls:{method_invocation:"function",object_creation_expression:"constructor"},kindFrom:{formal_parameter:e=>e.parent?.parent?.type==="record_declaration"?"field":void 0},publicMember:e=>e.parent?.parent?.type==="record_declaration",nameFrom:{field_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,constant_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let s of Oe(e.childForFieldName("superclass")))n.push(ge("extends",t.self,s,e));let r=e.childForFieldName("interfaces");for(let s of Oe(he(r??e,"type_list")??r))n.push(ge("implements",t.self,s,e));return n},interface_declaration:(e,t)=>{let n=e.childForFieldName("interfaces")??he(e,"extends_interfaces");return t.self?Oe(he(n??e,"type_list")??n).map(r=>ge("extends",t.self,r,e)):[]},record_declaration:(e,t)=>{let n=e.childForFieldName("interfaces");return t.self?Oe(he(n??e,"type_list")??n).map(r=>ge("implements",t.self,r,e)):[]}}},rust:{lang:"rust",defs:{function_item:"function",function_signature_item:"function",struct_item:"struct",enum_item:"enum",enum_variant:"enum-member",field_declaration:"field",trait_item:"trait",type_item:"type",associated_type:"type",mod_item:"mod",const_item:"const",static_item:"static",union_item:"union",macro_definition:"macro"},containers:new Set(["impl_item","declaration_list","source_file","field_declaration_list","enum_variant_list","foreign_mod_item","block"]),exported:Tc,calls:{call_expression:"function"},parentFrom:{impl_item:e=>ze(e.childForFieldName("type"))},nestedDefs:new Set(["const_item","static_item"]),publicMembersIn:{impl_item:e=>e.childForFieldName("trait")!==null},relationsFrom:{impl_item:(e,t)=>{let n=ze(e.childForFieldName("trait"));return t.self&&n?[ge("implements",t.self,n,e)]:[]}}},c_sharp:{lang:"csharp",defs:{class_declaration:"class",interface_declaration:"interface",struct_declaration:"struct",enum_declaration:"enum",enum_member_declaration:"enum-member",record_declaration:"record",delegate_declaration:"delegate",method_declaration:"method",constructor_declaration:"constructor",property_declaration:"property",indexer_declaration:"indexer",operator_declaration:"operator",field_declaration:"field",event_declaration:"event",event_field_declaration:"event",conversion_operator_declaration:"operator",destructor_declaration:"destructor"},containers:new Set(["namespace_declaration","declaration_list","compilation_unit","file_scoped_namespace_declaration","enum_member_declaration_list","parameter_list"]),exported:Ac,calls:{invocation_expression:"function",object_creation_expression:"constructor"},kindFrom:{parameter:e=>e.parent?.parent?.type==="record_declaration"?"field":void 0},publicMember:e=>e.parent?.parent?.type==="record_declaration",nameFrom:{field_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,event_field_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,conversion_operator_declaration:e=>e.childForFieldName("type")?.text},relationsFrom:{class_declaration:(e,t)=>t.self?tr(he(e,"base_list"),t.self,e):[],struct_declaration:(e,t)=>t.self?tr(he(e,"base_list"),t.self,e):[],record_declaration:(e,t)=>t.self?tr(he(e,"base_list"),t.self,e):[],interface_declaration:(e,t)=>t.self?Oe(he(e,"base_list")).map(n=>ge("extends",t.self,n,e)):[]}},php:{lang:"php",defs:{function_definition:"function",class_declaration:"class",interface_declaration:"interface",trait_declaration:"trait",enum_declaration:"enum",enum_case:"enum-member",method_declaration:"method",property_declaration:"property",const_declaration:"const",namespace_definition:"namespace"},containers:new Set(["declaration_list","enum_declaration_list","program"]),exported:yo,calls:{function_call_expression:"function",member_call_expression:"member",object_creation_expression:"constructor"},nameFrom:{property_declaration:e=>Te(e,t=>t.type==="variable_name")?.text.replace(/^\$/,""),const_declaration:e=>Te(e,t=>t.type==="const_element")?.namedChildren[0]?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let r of Oe(he(e,"base_clause")))n.push(ge("extends",t.self,r,e));for(let r of Oe(he(e,"class_interface_clause")))n.push(ge("implements",t.self,r,e));return n},interface_declaration:(e,t)=>t.self?Oe(he(e,"base_clause")).map(n=>ge("extends",t.self,n,e)):[]}},c:{lang:"c",defs:{function_definition:"function",struct_specifier:"struct",enum_specifier:"enum",enumerator:"enum-member",union_specifier:"union",type_definition:"type",field_declaration:"field",declaration:"const"},containers:new Set(["translation_unit","declaration_list","field_declaration_list","enumerator_list","linkage_specification","preproc_ifdef","preproc_if"]),exported:nr,calls:{call_expression:"function"},kindFrom:{field_declaration:e=>Ms(e)?"method":"field",declaration:e=>Ms(e)?"function":"const"}},cpp:{lang:"cpp",defs:{function_definition:"function",class_specifier:"class",struct_specifier:"struct",enum_specifier:"enum",enumerator:"enum-member",union_specifier:"union",type_definition:"type",alias_declaration:"type",concept_definition:"concept",namespace_definition:"namespace",namespace_alias_definition:"namespace",field_declaration:"field",declaration:"const",using_declaration:"using",friend_declaration:"friend"},containers:new Set(["translation_unit","declaration_list","field_declaration_list","enumerator_list","template_declaration","linkage_specification","preproc_ifdef","preproc_if"]),exported:nr,calls:{call_expression:"function",new_expression:"constructor"},kindFrom:{field_declaration:e=>Ms(e)?"method":"field",declaration:e=>Ms(e)?"function":"const"},sectionVisibility:e=>e.type==="access_specifier"?!/^(private|protected)/.test(e.text):void 0,nameFrom:{friend_declaration:e=>Qn(e)??(e.namedChildren[0]?Qn(e.namedChildren[0]):void 0)},relationsFrom:{class_specifier:(e,t)=>t.self?Oe(he(e,"base_class_clause")).map(n=>ge("extends",t.self,n,e)):[],struct_specifier:(e,t)=>t.self?Oe(he(e,"base_class_clause")).map(n=>ge("extends",t.self,n,e)):[]}},scala:{lang:"scala",defs:{class_definition:"class",object_definition:"object",trait_definition:"trait",enum_definition:"enum",function_definition:"def",function_declaration:"def",val_definition:"val",val_declaration:"val",var_definition:"var",type_definition:"type",given_definition:"given",package_clause:"package"},containers:new Set(["compilation_unit","package_clause","template_body","class_parameters","parameters","extension_definition"]),parentFrom:{extension_definition:e=>ze(he(e,"parameters")?.namedChildren[0]?.childForFieldName("type")??null)},exported:yo,kindFrom:{class_parameter:e=>/^\s*(?:val|var)\b/.test(e.text)?/^\s*var\b/.test(e.text)?"var":"val":e.parent?.parent?.type==="class_definition"&&/\bcase\s+class\b/.test(e.parent.parent.text.slice(0,80))?"val":void 0},calls:{call_expression:"function",instance_expression:"constructor"},relationsFrom:{class_definition:(e,t)=>t.self?tr(he(e,"extends_clause"),t.self,e):[],object_definition:(e,t)=>t.self?tr(he(e,"extends_clause"),t.self,e):[],trait_definition:(e,t)=>t.self?Oe(he(e,"extends_clause")).map(n=>ge("extends",t.self,n,e)):[]}},bash:{lang:"shell",defs:{function_definition:"function",declaration_command:"const"},containers:new Set(["program","if_statement","compound_statement"]),exported:nr,calls:{command:"function"},nameFrom:{declaration_command:e=>/^\s*local\b/.test(e.text)?void 0:Te(e,t=>t.type==="variable_name")?.text}},kotlin:{lang:"kotlin",defs:{class_declaration:"class",object_declaration:"object",function_declaration:"function",property_declaration:"property",enum_entry:"enum-member",type_alias:"type",class_parameter:"property"},containers:new Set(["source_file","class_body","enum_class_body","companion_object","object_declaration","primary_constructor","class_parameters"]),exported:yo,calls:{call_expression:"function"},kindFrom:{class_parameter:e=>/^\s*(?:val|var)\b/.test(e.text)||/\bdata\s+class\b/.test(e.parent?.parent?.parent?.text.slice(0,80)??"")?"property":void 0,class_declaration:e=>{let t=e.text.slice(0,80);return/\binterface\b/.test(t)?"interface":/\benum\s+class\b/.test(t)?"enum":/\bannotation\s+class\b/.test(t)?"annotation":"class"}},nameFrom:{property_declaration:e=>Te(e,t=>t.type==="variable_declaration")?.namedChildren[0]?.text??e.namedChildren.find(t=>t.type==="identifier")?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let r of he(e,"delegation_specifiers")?.namedChildren??[]){let s=ze(r);s&&n.push(ge(Te(r,o=>o.type==="constructor_invocation")?"extends":"implements",t.self,s,e))}return n}}},elixir:{lang:"elixir",defs:{},containers:new Set(["source","do_block","call","stab_clause"]),exported:e=>!/^\s*defp?macrop\b|^\s*defp\b/.test(e),calls:{call:"function"},kindFrom:{call:e=>Nc[e.childForFieldName("target")?.text??e.namedChildren[0]?.text??""]},skipCall:e=>{if(e.parent?.type==="unary_operator")return!0;if(e.parent?.type!=="arguments")return!1;let t=e.parent.parent,n=t?.childForFieldName("target")??t?.namedChildren[0];return n!==void 0&&Nc[n.text]!==void 0},docFrom:e=>{let t=e.previousNamedSibling;for(;t&&t.type==="unary_operator";){let n=t.namedChildren[0],r=n?.childForFieldName("target")??n?.namedChildren[0];if(r&&/^(doc|moduledoc)$/.test(r.text)){let s=Te(t,o=>o.type==="string");if(s)return s.text.replace(/^"""|"""$/g,"").replace(/^"|"$/g,"").trim()||void 0}t=t.previousNamedSibling}},nameFrom:{call:e=>{let n=(e.childForFieldName("arguments")??e.namedChildren.find(s=>s.type==="arguments"))?.namedChildren[0];if(!n)return;if(n.type==="alias"||n.type==="identifier")return n.text;let r=n.childForFieldName("target")??n.namedChildren[0];return r&&/identifier|alias/.test(r.type)?r.text:void 0}}},zig:{lang:"zig",defs:{function_declaration:"function",variable_declaration:"const",container_field:"field",test_declaration:"test"},containers:new Set(["source_file","variable_declaration","struct_declaration","enum_declaration","union_declaration","error_set_declaration","opaque_declaration","block"]),exported:Tc,calls:{call_expression:"function"},kindFrom:{variable_declaration:e=>{let t=e.namedChildren.find(n=>n.type==="builtin_function");if(!(t&&/^@(import|cImport)\b/.test(t.text))){for(let n of e.namedChildren){if(n.type==="struct_declaration")return"struct";if(n.type==="enum_declaration")return"enum";if(n.type==="union_declaration")return"union";if(n.type==="error_set_declaration")return"error";if(n.type==="opaque_declaration")return"opaque"}return/^\s*(?:pub\s+)?var\b/.test(e.text.slice(0,24))?"var":"const"}},container_field:e=>e.parent?.type==="enum_declaration"?"enum-member":"field"}},solidity:{lang:"solidity",defs:{contract_declaration:"contract",interface_declaration:"interface",library_declaration:"library",function_definition:"function",constructor_definition:"constructor",modifier_definition:"modifier",event_definition:"event",error_declaration:"error",struct_declaration:"struct",struct_member:"field",enum_declaration:"enum",enum_value:"enum-member",state_variable_declaration:"field",constant_variable_declaration:"const",user_defined_type_definition:"type",fallback_receive_definition:"function"},containers:new Set(["source_file","contract_body","struct_declaration","enum_declaration","enum_body"]),exported:(e,t)=>/\b(public|external)\b/.test(e)?!0:/\b(internal|private)\b/.test(e)?!1:Ic(e,t)||!0,calls:{call_expression:"function"},nameFrom:{state_variable_declaration:e=>e.namedChildren.find(t=>t.type==="identifier")?.text,fallback_receive_definition:e=>/^\s*receive\b/.test(e.text)?"receive":"fallback",enum_value:e=>e.text},relationsFrom:{contract_declaration:(e,t)=>t.self?e.namedChildren.filter(n=>n.type==="inheritance_specifier").map(n=>ze(n)).filter(n=>n!==void 0).map(n=>ge("extends",t.self,n,e)):[],interface_declaration:(e,t)=>t.self?e.namedChildren.filter(n=>n.type==="inheritance_specifier").map(n=>ze(n)).filter(n=>n!==void 0).map(n=>ge("extends",t.self,n,e)):[]}},terraform:Oc,hcl:{...Oc,lang:"hcl"},lua:{lang:"lua",defs:{function_declaration:"function"},containers:new Set(["chunk","variable_declaration"]),exported:km,calls:{function_call:"function"},assignments:!0}}});function Am(e){let t=e.childForFieldName("body"),n=t&&t.startIndex>e.startIndex?t.startIndex:void 0,r=s=>{Mm.has(s.type)&&s.startIndex>e.startIndex&&(n===void 0||s.startIndex|=)$/,"").trim().slice(0,Cm)}var Mm,Cm,Lc=F(()=>{"use strict";k();Mm=new Set(["block","statement_block","class_body","declaration_list","field_declaration_list","template_body","compound_statement","body_statement","enum_body","enum_body_declarations","enum_variant_list","enum_member_declaration_list","enumerator_list","interface_body","object_type","do_block","struct_declaration","enum_declaration","union_declaration","error_set_declaration","opaque_declaration","contract_body","enum_class_body"]),Cm=400});function xo(e){return Tm.test(e.trim())}function So(e){return Im.test(e.trim())}function wt(e){return e.replace(/\*+\/\s*$/,"").replace(/^\s*\/\*+!?/,"").replace(/^\s*\/\/[/!]?/,"").replace(/^\s*--+/,"").replace(/^\s*#+/,"").replace(/^\s*\*+/,"").replace(/^\s*(?:"""|''')/,"").replace(/(?:"""|''')\s*$/,"").replace(/[-=~_]{3,}/g," ").trim()}function Nm(e){return e.replace(/<\/?[A-Za-z][^>]*>/g," ").replace(/\s+/g," ").trim()}function ko(e,t=Om){let n=[];for(let o of e){let a=o.trim();if(!(!a||xo(a)||So(a))){if(/^@[a-z]/i.test(a))break;n.push(a)}}let r=Nm(n.join(" "));if(r.length<3)return;let s=/^(.*?[.!?])(\s|$)/.exec(r);return(s?s[1]:r).slice(0,t)}var Tm,Im,Om,As=F(()=>{"use strict";k();Tm=/^(eslint\b|eslint-|prettier\b|prettier-|tslint\b|jshint\b|jslint\b|globals?\b|istanbul\b|c8\s|v8\s|@ts-|ts-|@flow\b|@jsx\b|@jsxRuntime\b|@jest-environment\b|@vitest-environment\b|@license\b|@preserve\b|@copyright\b|copyright\b|spdx-|1);)t.push(n),r=n.startPosition.row,n=n.previousNamedSibling;if(!t.length)return[];t.reverse();let s=[];for(let o of t)for(let a of o.text.split(/\r?\n/))s.push(wt(a));return s}function xn(e){let t=e;for(;t;){let n=$m(t);if(n.length){let o=ko(n);if(o)return o}let r=t.parent;if(!r||!Pm.has(r.type))return;let s=t.previousNamedSibling;if(s&&!Lm.test(s.type))return;t=r}}function Dc(e){let n=e.childForFieldName("body")?.namedChildren[0];if(!n)return;let r=n.type==="string"?n:n.type==="expression_statement"?n.namedChildren[0]:void 0;if(!(!r||r.type!=="string"))return ko(r.text.split(/\r?\n/).map(wt))}var Fm,Pm,Lm,jc=F(()=>{"use strict";k();As();Fm=/(^|_)comment$/,Pm=new Set(["export_statement","ambient_declaration","decorated_definition","template_declaration","labeled_statement","lexical_declaration","variable_declaration","type_declaration","const_declaration","var_declaration","body_statement","body"]);Lm=/decorator|annotation|modifiers/});function ep(e){return e.namedChildren.every(t=>Qm.test(t.type))}function tp(e,t,n,r,s){let o=new Set,a=t.calls!==void 0,l=[],c=new Set,d=(b,x,v)=>{if(!b||b.length<2||!/^[A-Za-z_]\w*$/.test(b))return;let A=x.startPosition.row+1,O=`${b} ${A}`;c.has(O)||(c.add(O),l.push(v?{name:b,line:A,receiver:v}:{name:b,line:A}))},f=new Set,u=b=>{if(!(f.size>=Wc))for(let x of ht(b)){if(f.size>=Wc)return;f.add(x)}},m=new It,p=t.imports?.import_statement!==void 0,g=new Set,y=s&&t.imports!==void 0,h=[],S=new Set,_=b=>{let x=b.trim();x&&!S.has(x)&&(S.add(x),h.push({kind:"import",spec:x}))},E=b=>{let x=b.type,v=b.namedChildren;if(v.length===0&&Jm.test(x)){let A=b.text;Km.test(A)&&!n.has(A)&&o.add(A)}if(Xm.test(x))for(let A of b.text.split(/\r?\n/))u(wt(A));else v.length===0&&Uc.test(x)&&b.endIndex-b.startIndex<=zm&&u(b.text.replace(/^['"`]+|['"`]+$/g,""));if(!m.full){let A=b.startPosition.row+1;Uc.test(x)&&ep(b)?m.addString(b.text,A):v.length===0&&Zm.test(x)?m.add("number",b.text.trim(),A):Ym.test(x)&&m.add("regex",b.text,A)}if(a&&!(t.kindFrom?.[x]&&t.kindFrom[x](b))&&!t.skipCall?.(b)){let A=t.calls[x];if(A==="function"){let O=b.childForFieldName("function")??b.childForFieldName("callee")??b.childForFieldName("method")??b.childForFieldName("name")??b.childForFieldName("target")??v[0]??null;d(Kt(O),b,er(O)??er(b))}else if(A==="member")d(Kt(b.childForFieldName("name")),b,er(b));else if(A==="constructor"){let O=b.childForFieldName("constructor")??b.childForFieldName("type")??b.childForFieldName("name");for(let N=0;!O&&N/string/.test(N.type));O&&_(O.text.replace(/^['"]|['"]$/g,""))}else if(A==="path"){let O=b.childForFieldName("name")??b.childForFieldName("module_name");_((O??b).text.replace(/^(import|from)\s+/,"").split(/\s+/)[0])}}for(let A of v)E(A)};return E(e),l.sort((b,x)=>M(b.name,x.name)||b.line-x.line),{refs:h,idents:[...o].sort().slice(0,Dm),calls:l.slice(0,r),importedNames:[...g].sort(M).slice(0,Wm),terms:[...f].sort(M),literals:m.result()??[]}}function np(e){let t=[],n=r=>{if(/^(shorthand_property_identifier_pattern|identifier)$/.test(r.type)){t.includes(r.text)||t.push(r.text);return}if(r.type==="pair_pattern"){let s=r.childForFieldName("value");s&&n(s);return}for(let s of r.namedChildren)n(s)};for(let r of e.namedChildren)n(r);return t}function Eo(e,t,n,r={}){let s=Yn(t);if(!s||!tt(s))return;let o=Pc[s];if(!o)return;let a=vs(s);if(!a)return;let l=null;try{if(l=a.parse(n),!l)return;let c=r.maxSymbols??Um,d=[],f=l.rootNode,u=(e.split("/").pop()??"").replace(/\.[^.]+$/,""),m=new Set,p=P=>{d.length{let B=o.relationsFrom?.[P.type];if(B)for(let re of B(P,{self:j})){if(re.from===re.to)continue;let J=`${re.kind} ${re.from} ${re.to}`;y.has(J)||g.length>=Bm||(y.add(J),g.push(re))}},S=(P,j,B,re)=>re.inFunctionBody||o.privateMember?.(P)===!0?!1:o.publicMember?.(P)===!0?!0:re.sectionPublic?re.forcePublic?!0:re.exported||o.exported(j,B):!1,_=P=>o.docFrom?.(P)??(o.docstring?Dc(P):void 0)??xn(P),E=(P,j)=>{let B=j.sectionPublic,re=o.bareMembers?.[P.type];for(let J of P.namedChildren){if(o.sectionVisibility){let be=o.sectionVisibility(J);if(be!==void 0){B=be;continue}}let ee=B===j.sectionPublic?j:{...j,sectionPublic:B};if(re&&J.namedChildren.length===0&&Rs.test(J.type)){p({name:J.text,kind:re,file:e,line:J.startPosition.row+1,endLine:J.endPosition.row+1,...ee.parent?{parent:ee.parent}:{},exported:ee.forcePublic||ee.exported,lang:o.lang});continue}for(let be of o.extraMembers?.(J,{ownerKind:ee.ownerKind,inFunctionBody:ee.inFunctionBody})??[]){let Ie=Ot(J,n),X=xn(J);p({name:be.name,kind:be.kind,file:e,line:J.startPosition.row+1,endLine:J.endPosition.row+1,...ee.parent?{parent:ee.parent}:{},...ee.parentPath&&ee.parentPath!==ee.parent?{parentPath:ee.parentPath}:{},signature:Ie,...X?{doc:X}:{},exported:S(J,Ie,be.name,ee),lang:o.lang})}x(J,ee)}},b=(P,j)=>{let B=!1;for(let re of P.namedChildren)o.containers.has(re.type)&&(B=!0,E(re,j));!B&&o.containers.has(P.type)&&E(P,j)},x=(P,j)=>{if(j.funcDepth>Hm)return;let B=P.type,re=o.exportMarkers?.has(B)===!0,J=j.exported||re;if(B==="export_statement"){for(let X of P.namedChildren)if(X.type==="identifier")m.add(X.text);else if(X.type==="export_clause")for(let Z of X.namedChildren){let L=Z.childForFieldName("name")??Z.namedChildren[0];L?.text&&m.add(L.text)}if(u&&P.children.some(X=>X.type==="default"))for(let X of P.namedChildren){let Z=Gm.has(X.type),L=Vm.has(X.type);if((Z||L)&&!X.childForFieldName("name")){let de=xn(P);p({name:u,kind:L?"class":"function",file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,signature:Ot(P,n),...de?{doc:de}:{},exported:!0,lang:o.lang});break}}}if(o.assignments&&B==="expression_statement"){let X=P.namedChildren[0];if(X?.type==="assignment_expression"){let Z=X.childForFieldName("left"),L=X.childForFieldName("right");if(Z?.type==="member_expression"&&Z.text==="module.exports"&&L){if(L.type==="object"){for(let K of L.namedChildren)if(K.type==="shorthand_property_identifier")m.add(K.text);else if(K.type==="pair"){let ce=K.childForFieldName("key"),we=K.childForFieldName("value");ce?.type==="property_identifier"&&m.add(ce.text),we?.type==="identifier"&&m.add(we.text)}return}if(L.type==="identifier"){m.add(L.text);return}}let de=L&&Cs.has(L.type);if(Z&&L&&de){let K,ce=!1;if(Z.type==="member_expression"){let we=Z.childForFieldName("property");if(we?.type==="property_identifier"){K=we.text;let pt=Z.text.slice(0,Z.text.length-we.text.length-1);ce=pt==="exports"||pt==="module.exports"}}else Z.type==="identifier"&&(K=Z.text);if(K){let we=xn(P);p({name:K,kind:L.type==="class"?"class":"function",file:e,line:X.startPosition.row+1,endLine:X.endPosition.row+1,...j.parent?{parent:j.parent}:{},signature:Ot(X,n),...we?{doc:we}:{},exported:!j.inFunctionBody&&(J||ce),lang:o.lang});return}}else if(Z?.type==="member_expression"&&L){let K=Z.childForFieldName("property");if(K?.type==="property_identifier"){let ce=Z.text.slice(0,Z.text.length-K.text.length-1);if(ce==="exports"||ce==="module.exports"){L.type==="identifier"&&m.add(L.text),(L.type!=="identifier"||L.text!==K.text)&&p({name:K.text,kind:"const",file:e,line:X.startPosition.row+1,endLine:X.endPosition.row+1,...j.parent?{parent:j.parent}:{},signature:Ot(X,n),exported:!0,lang:o.lang});return}}}}}if(o.assignments&&B==="assignment_statement"){let X=P.children.find(ce=>ce.type==="variable_list"),Z=P.children.find(ce=>ce.type==="expression_list"),L=X?.namedChildren??[],de=Z?.namedChildren??[],K=Math.min(L.length,de.length);for(let ce=0;ceK.type==="object_pattern"||K.type==="array_pattern");if(L&&!j.inFunctionBody){let K=Ot(P,n),ce=_(P);for(let we of np(L))p({name:we,kind:Ie,file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,...j.parent?{parent:j.parent}:{},signature:K,...ce?{doc:ce}:{},exported:S(P,K,we,{...j,exported:J}),lang:o.lang});return}let de=wo.has(Ie)||qm.has(Ie)||o.nestedDefs?.has(B)===!0||Cs.has(P.childForFieldName("value")?.type??"");if(Z&&(!j.inFunctionBody||de)){let K=Ot(P,n),ce=_(P),we=ee??j.parent,pt=ee??j.parentPath;p({name:Z,kind:Ie,file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,...we?{parent:we}:{},...pt&&pt!==we?{parentPath:pt}:{},signature:K,...ce?{doc:ce}:{},exported:S(P,K,Z,{...j,exported:J}),lang:o.lang}),h(P,Z);let $n=wo.has(Ie);b(P,{parent:Z,parentPath:pt?`${pt}/${Z}`:Z,ownerKind:Ie,exported:J,forcePublic:Fc.has(Ie),inFunctionBody:j.inFunctionBody||$n,funcDepth:j.funcDepth+($n?1:0),sectionPublic:!0});return}}if(h(P,ee??j.parent),o.containers.has(B)){let X=j.forcePublic||o.publicMembersIn?.[B]?.(P)===!0,Z=Cs.has(B);E(P,{...j,exported:J,forcePublic:X,inFunctionBody:j.inFunctionBody||Z,funcDepth:j.funcDepth+(Z?1:0),...ee?{parent:ee,parentPath:ee,ownerKind:"type"}:{}})}};if(E(f,{exported:!1,forcePublic:!1,inFunctionBody:!1,funcDepth:0,sectionPublic:!0}),m.size)for(let P of d)!P.exported&&m.has(P.name)&&(P.exported=!0);let v=r.imports!==!1,{refs:A,idents:O,calls:N,importedNames:U,terms:le,literals:V}=tp(f,o,new Set(d.map(P=>P.name)),r.maxCalls??jm,v),z;if(v&&o.lang==="java"){let P=Te(f,j=>j.type==="package_declaration");P&&(z=P.text.replace(/^package\s+/,"").replace(/;.*$/,"").trim())}return g.sort((P,j)=>M(P.from,j.from)||M(P.kind,j.kind)||M(P.to,j.to)),{symbols:d,refs:A,pkg:z,idents:O,calls:N,importedNames:U,relations:g,terms:le,literals:V,...d.length>=c?{truncated:!0}:{}}}catch{return}finally{l?.delete()}}var Dm,jm,Wm,Um,Bm,Wc,zm,Hm,qm,Gm,Vm,Jm,Km,Xm,Uc,Zm,Ym,Qm,vo=F(()=>{"use strict";k();hs();Y();nt();ho();$c();Lc();jc();As();Ce();Dm=512,jm=512,Wm=256,Um=2e3,Bm=256,Wc=512,zm=80,Hm=2,qm=new Set(["class","struct","enum","interface","trait","type","record","union"]),Gm=new Set(["function","function_expression","function_declaration","generator_function","generator_function_declaration","arrow_function"]),Vm=new Set(["class","class_declaration","abstract_class_declaration"]),Jm=/identifier|constant|(^|_)name$/,Km=/^[A-Za-z_]\w{4,}$/,Xm=/(^|_)comment$/,Uc=/(^|_)string(_literal)?$/,Zm=/(^|_)(integer|float|number|decimal|numeric)(_literal)?$/,Ym=/(^|_)(regex|regular_expression)(_pattern|_literal)?$/,Qm=/(^|_)(fragment|content|escape_sequence|character)$/});function ap(e){let t=e.split(/\r?\n/),n=[],r=null;for(let a=0;aa&&!xo(a)&&!So(a)).join(" ").replace(/\s+/g," ").trim();if(s.length<8)return;let o=/^(.*?[.!?])(\s|$)/.exec(s);return(o?o[1]:s).slice(0,200)}function Mo(e,t=[]){if(t.length>=lp)return t;let n=e.indexOf("{");if(n===-1){let c=e.replace(/\s+as\s+\w+\s*$/,"").replace(/::\s*\*\s*$/,"").replace(/^::/,"").trim();return c&&t.push(c),t}let r=e.slice(0,n),s=0,o=-1;for(let c=n;c({kind:"import",spec:s}))}function up(e,t=[],n=512){let r=new Map,s=new Set(t.map(l=>`${l.name} ${l.line}`)),o=e.split(` -`),a=/(?:\bnew\s+)?(?:([A-Za-z_$][\w$]*)\s*\.\s*)?([A-Za-z_$][\w$]*)\s*\(/g;for(let l=0;ll.namec.name?1:l.line-c.line)}function mp(e){let t=new Set,n=s=>{if(!(t.size>=Ro))for(let o of ht(s)){if(t.size>=Ro)return;t.add(o)}},r=!1;for(let s of e.split(` -`)){if(t.size>=Ro)break;let o=s;if(r){let c=o.indexOf("*/");if(n(wt(c===-1?o:o.slice(0,c))),c===-1)continue;r=!1,o=o.slice(c+2)}let a=o.indexOf("/*");if(a!==-1){let c=o.indexOf("*/",a+2);n(wt(o.slice(a,c===-1?void 0:c))),c===-1?(r=!0,o=o.slice(0,a)):o=o.slice(0,a)+o.slice(c+2)}let l=/(^|\s)(\/\/|#|--)(.*)$/.exec(o);l&&(n(wt(l[2]+l[3])),o=o.slice(0,l.index));for(let c of o.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)){let d=c[2];d.length&&d.length<=fp&&n(d)}}return[...t].sort()}function pp(e){let t=new It,n=!1,r=0;for(let s of e.split(` -`)){if(r++,t.full)break;let o=s;if(n){let c=o.indexOf("*/");if(c===-1)continue;n=!1,o=o.slice(c+2)}let a=o.indexOf("/*");if(a!==-1){let c=o.indexOf("*/",a+2);c===-1?(n=!0,o=o.slice(0,a)):o=o.slice(0,a)+o.slice(c+2)}let l=/(^|\s)(\/\/|#|--)(.*)$/.exec(o);l&&(o=o.slice(0,l.index));for(let c of o.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g))t.add("string",c[2],r);for(let c of o.replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ").matchAll(/(?m.name)),c=us(e,n,a).filter(m=>!l.has(m.name)),d=cp(t,n),f=new Set(d.map(m=>m.spec)),u=(s?s.literals.length?s.literals:void 0:pp(n))?.filter(m=>!(m.kind==="string"&&f.has(m.value)));return{symbols:[...a,...c],...s?.truncated||o.length>a.length||c.length>=ds?{truncated:!0}:{},summary:ap(n),refs:d,pkg:t===".java"?/^\s*package\s+([\w.]+)\s*;/m.exec(n)?.[1]:t===".cs"?/^\s*(?:file-scoped\s+)?namespace\s+([\w.]+)/m.exec(n)?.[1]:void 0,idents:s?.idents,calls:s?s.calls:up(n,a,r.maxCallsPerFile),importedNames:s?.importedNames,relations:s?.relations?.length?s.relations:void 0,terms:s?s.terms:mp(n),literals:u?.length?u:void 0}}var rp,sp,ip,op,lp,dp,Bc,Ro,fp,Ao=F(()=>{"use strict";k();hs();yn();vo();ve();As();Ce();rp=2e3,sp=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),ip=new Set([".py",".pyi"]),op=new Set([".c",".h",".cc",".cpp",".cxx",".hpp",".hh"]);lp=16;dp=new Set(["if","else","elif","for","while","do","switch","case","match","when","unless","until","catch","except","return","throw","raise","yield","await","typeof","instanceof","sizeof","delete","void","in","of","not","and","or","assert","defer","select","with","loop"]),Bc=/(?:\bfunction|\bdef|\bfunc|\bfun|\bfn|\bclass|\bsub|\bmacro|\bproc)\s*[*]?\s*$/;Ro=512,fp=80});function Hc(e){let t=new It,n=0;for(let r of e.split(` -`)){if(n++,t.full)break;let s=yp(r);for(let a of s.matchAll(zc))t.add("string",a[2],n);let o=hp.exec(s);if(o){let a=o[1].trim();a&&!/^[[{|>&*-]/.test(a)&&!gp.test(a)&&t.add("string",a,n)}for(let a of s.replace(zc," ").matchAll(_p))t.add("number",a[0].replace(/_/g,""),n)}return t.result()}function yp(e){let t;for(let n=0;n{"use strict";k();hs();zc=/(['"])((?:\\.|(?!\1)[^\\])*)\1/g,gp=/(['"])((?:\\.|(?!\1)[^\\])*)\1/,_p=/(?u.rel)),a!==void 0&&n.length!==a.size&&(l=!1,c=!0),{root:e,commit:as(e),files:n,languages:r,docText:s,mtimes:o,capped:f.value.capped,excluded:f.value.excluded,contentUnchanged:l,cacheDirty:c}}var Ft=F(()=>{"use strict";k();oe();Ae();Gt();At();_s();yn();Hn();Y();eo();Ao();qc()});function De(e){let t=new Map;for(let n of e.files)t.set(n.rel,{hash:n.hash,record:n,size:n.size,mtimeMs:e.mtimes.get(n.rel)});return t}function No(e,t,n=!1){let r=e.files.filter(s=>zn(s.rel,s.ext)==="code");return n&&r.length>0||r.some(s=>{let o=t.get(s.rel);return!o||o.size!==s.size||o.mtimeMs!==s.mtimeMs})}function Oo(e,t=ut){let n;try{n=JSON.parse(te(I(e,t,"cache.json"),"utf8"))}catch{return}if(!(!n||n.schemaVersion!==5||n.extractorVersion!==14||!n.files))return{cacheMap:new Map(Object.entries(n.files)),meta:{engineVersion:n.engineVersion,commit:n.commit,graphSha1:n.graphSha1,symbolsSha1:n.symbolsSha1}}}function Fo(e,t,n,r=ut){if(!t.contentUnchanged||n.engineVersion!==fe||n.commit!==t.commit||n.graphSha1===void 0||n.symbolsSha1===void 0)return;let s=I(e,r),o,a;try{o=te(I(s,"graph.json")),a=te(I(s,"symbols.json"))}catch{return}if(!(Me(o)!==n.graphSha1||Me(a)!==n.symbolsSha1))try{let l=JSON.parse(o.toString("utf8")),c=JSON.parse(a.toString("utf8"));return l.schemaVersion!==5||c.schemaVersion!==5?void 0:{scan:t,graph:l,symbols:c}}catch{return}}function Po(e,t,n=ut){let r=Oo(e,n);if(!r)return;let s=Pe(e,{...t,cache:r.cacheMap});return{scan:s,cacheMap:De(s),arts:Fo(e,s,r.meta,n)}}async function Is(e,t,n,r=ut){let s=Oo(e,r);if(!s)return;let o=t.precomputedWalk??Fe(e,{maxFileBytes:t.maxBytes,maxFiles:t.maxFiles,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs});No(o,s.cacheMap,t.fullHash)&&await n();let l=Pe(e,{...t,cache:s.cacheMap,precomputedWalk:o}),c=!1,d;return{scan:l,cacheMap:De(l),loadArtifacts:()=>(c||(c=!0,d=Fo(e,l,s.meta,r)),d)}}var ut,sr=F(()=>{"use strict";k();xe();oe();Xe();Ft();At();Ae();_s();ut=".codeindex"});var Ns,Vc=F(()=>{k();Ns=class{constructor(){throw new Error("worker_threads is not available in the browser build (the engine runs single-threaded here)")}}});function bp(){try{let e=bs(import.meta.url);if(e.endsWith("engine.mjs"))return qn(e).href;let t=I(_e(e),"engine.mjs");return H(t)?qn(t).href:void 0}catch{return}}function Jc(e){let t=R.env.CODEINDEX_WORKERS,n=e??(t!==void 0&&t!==""?Number(t):void 0);if(n!==void 0)return Number.isFinite(n)&&n>0?Math.floor(n):0;let r=1;try{r=typeof ys=="function"?ys():sc().length}catch{r=1}return Math.max(0,Math.min(r-1,8))}async function Sp(e,t){await et(e.grammarKeys);let n=e.grammarKeys.filter(s=>tt(s)),r=[];for(let s of e.jobs){let o,a;try{let d=Ee(s.abs);o=d.size,a=d.mtimeMs}catch{continue}let l=G(s.abs),c=Ts(s.rel,s.ext,o,l,Me(l),Vt(s.ext),{maxCallsPerFile:e.maxCallsPerFile});r.push({rel:s.rel,size:o,mtimeMs:a,record:c})}t({ready:n,records:r})}async function Kc(e,t,n,r={}){if(n<2||e.length===0)return;let s=bp();if(!s)return;let o=t.filter(c=>tt(c)).sort(),a=Array.from({length:Math.min(n,e.length)},()=>[]);e.forEach((c,d)=>a[d%a.length].push(c));let l=`import { runExtractWorker } from ${JSON.stringify(s)}; +${d}`)}let c=l.clone();try{n=await WebAssembly.compileStreaming(l)}catch(d){console.error("wasm streaming compile failed:",d),console.error("falling back to ArrayBuffer instantiation"),n=new Uint8Array(await c.arrayBuffer())}}let r=await x.loadWebAssemblyModule(n,{loadAsync:!0}),s=Object.keys(r),o=s.find(l=>$m.test(l)&&!l.includes("external_scanner_"));if(!o)throw console.log(`Couldn't find language function in Wasm file. Symbols: +${JSON.stringify(s,null,2)}`),new Error("Language.load failed: no language function found in Wasm file");let a=r[o]();return new yc(Ft,a)}};C(bc,"Module");Dm=bc,wc=null;C(xc,"initializeBinding");C(Sc,"checkModule");go=class{static{C(this,"Parser")}0=0;1=0;logCallback=null;language=null;static async init(e){mc(await xc(e)),L=x._ts_init(),lo=x.getValue(L,"i32"),co=x.getValue(L+W,"i32")}constructor(){this.initialize()}initialize(){if(!Sc())throw new Error("cannot construct a Parser before calling `init()`");x._ts_parser_new_wasm(),this[0]=x.getValue(L,"i32"),this[1]=x.getValue(L+W,"i32")}delete(){x._ts_parser_delete(this[0]),x._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,this.language=null;else if(e.constructor===po){t=e[0];let n=x._ts_language_abi_version(t);if(ne.slice(l);else if(typeof e=="function")x.currentParseCallback=e;else throw new Error("Argument must be a string or a function");n?.progressCallback?x.currentProgressCallback=n.progressCallback:x.currentProgressCallback=null,this.logCallback?(x.currentLogCallback=this.logCallback,x._ts_parser_enable_logger_wasm(this[0],1)):(x.currentLogCallback=null,x._ts_parser_enable_logger_wasm(this[0],0));let r=0,s=0;if(n?.includedRanges){r=n.includedRanges.length,s=x._calloc(r,Kn);let l=s;for(let c=0;c0){let r=t;for(let s=0;se.type==="capture","isCaptureStep"),_o=C(e=>e.type==="string","isStringStep"),Ye={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},Vn=class kc extends Error{constructor(t,n,r,s){super(kc.formatMessage(t,n)),this.kind=t,this.info=n,this.index=r,this.length=s,this.name="QueryError"}static{C(this,"QueryError")}static formatMessage(t,n){switch(t){case Ye.NodeName:return`Bad node name '${n.word}'`;case Ye.FieldName:return`Bad field name '${n.word}'`;case Ye.CaptureName:return`Bad capture name @${n.word}`;case Ye.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case Ye.Syntax:return`Bad syntax at offset ${n.suffix}`}}};C(Ec,"parseAnyPredicate");C(vc,"parseMatchPredicate");C(Rc,"parseAnyOfPredicate");C(Mc,"parseIsPredicate");C(Cc,"parseSetDirective");C(Ac,"parsePattern");Tc=class{static{C(this,"Query")}0=0;exceededMatchLimit;textPredicates;captureNames;captureQuantifiers;predicates;setProperties;assertedProperties;refutedProperties;matchLimit;constructor(e,t){let n=x.lengthBytesUTF8(t),r=x._malloc(n+1);x.stringToUTF8(t,r,n+1);let s=x._ts_query_new(e[0],r,n,L,L+W);if(!s){let h=x.getValue(L+W,"i32"),S=x.getValue(L,"i32"),_=x.UTF8ToString(r,S).length,k=t.slice(_,_+100).split(` +`)[0],b=k.match(Wm)?.[0]??"";switch(x._free(r),h){case Ye.Syntax:throw new Vn(Ye.Syntax,{suffix:`${_}: '${k}'...`},_,0);case Ye.NodeName:throw new Vn(h,{word:b},_,b.length);case Ye.FieldName:throw new Vn(h,{word:b},_,b.length);case Ye.CaptureName:throw new Vn(h,{word:b},_,b.length);case Ye.PatternStructure:throw new Vn(h,{suffix:`${_}: '${k}'...`},_,0)}}let o=x._ts_query_string_count(s),a=x._ts_query_capture_count(s),l=x._ts_query_pattern_count(s),c=new Array(a),d=new Array(l),f=new Array(o);for(let h=0;ho)throw new Error("`startIndex` cannot be greater than `endIndex`");if(r!==$e&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw new Error("`startPosition` cannot be greater than `endPosition`");if(d!==0&&c>d)throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==$e&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");m&&(x.currentQueryProgressCallback=m),G(e),x._ts_query_matches_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,d,f,u);let p=x.getValue(L,"i32"),g=x.getValue(L+W,"i32"),y=x.getValue(L+2*W,"i32"),h=new Array(p);this.exceededMatchLimit=!!y;let S=0,_=g;for(let k=0;kA(v))){h[S]={patternIndex:b,captures:v};let A=this.setProperties[b];h[S].setProperties=A;let F=this.assertedProperties[b];h[S].assertedProperties=F;let T=this.refutedProperties[b];h[S].refutedProperties=T,S++}}return h.length=S,x._free(g),x.currentQueryProgressCallback=null,h}captures(e,t={}){let n=t.startPosition??$e,r=t.endPosition??$e,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??$e,l=t.endContainingPosition??$e,c=t.startContainingIndex??0,d=t.endContainingIndex??0,f=t.matchLimit??4294967295,u=t.maxStartDepth??4294967295,m=t.progressCallback;if(typeof f!="number")throw new Error("Arguments must be numbers");if(this.matchLimit=f,o!==0&&s>o)throw new Error("`startIndex` cannot be greater than `endIndex`");if(r!==$e&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw new Error("`startPosition` cannot be greater than `endPosition`");if(d!==0&&c>d)throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==$e&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");m&&(x.currentQueryProgressCallback=m),G(e),x._ts_query_captures_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,d,f,u);let p=x.getValue(L,"i32"),g=x.getValue(L+W,"i32"),y=x.getValue(L+2*W,"i32"),h=new Array;this.exceededMatchLimit=!!y;let S=new Array,_=g;for(let k=0;kA(S))){let A=S[v],F=this.setProperties[b];A.setProperties=F;let T=this.assertedProperties[b];A.assertedProperties=T;let U=this.refutedProperties[b];A.refutedProperties=U,h.push(A)}}return x._free(g),x.currentQueryProgressCallback=null,h}predicatesForPattern(e){return this.predicates[e]}disableCapture(e){let t=x.lengthBytesUTF8(e),n=x._malloc(t+1);x.stringToUTF8(e,n,t+1),x._ts_query_disable_capture(this[0],n,t),x._free(n)}disablePattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);x._ts_query_disable_pattern(this[0],e)}didExceedMatchLimit(){return this.exceededMatchLimit}startIndexForPattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return x._ts_query_start_byte_for_pattern(this[0],e)}endIndexForPattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return x._ts_query_end_byte_for_pattern(this[0],e)}patternCount(){return x._ts_query_pattern_count(this[0])}captureIndexForName(e){return this.captureNames.indexOf(e)}isPatternRooted(e){return x._ts_query_is_pattern_rooted(this[0],e)===1}isPatternNonLocal(e){return x._ts_query_is_pattern_non_local(this[0],e)===1}isPatternGuaranteedAtStep(e){return x._ts_query_is_pattern_guaranteed_at_step(this[0],e)===1}}});function Qn(e){return Ms[e]}function xn(){let e=R.env.XDG_CACHE_HOME,t=e&&e.trim()?e.trim():I(cc(),".cache");return I(t,"codeindex","grammars",fe)}function Qe(e={}){let t=xn(),n=(l,c)=>({tier:l,dir:c,cacheDir:t,dirs:[c,...H(I(c,"..",Ic))?[I(c,"..",Ic)]:[]]}),r=R.env.CODEINDEX_GRAMMAR_DIR??R.env.ULTRAINDEX_GRAMMAR_DIR;if(r&&r.trim()&&H(r))return n("env",r);let s=e.moduleDir??_e(Ss(import.meta.url)),o=[I(s,"grammars"),I(s,"..","..","scripts","grammars"),I(s,"..","scripts","grammars")];for(let l of o)if(H(l))return n("adjacent",l);let a=R.env.CODEINDEX_GRAMMARS_DIR;return a&&a.trim()&&H(a)?n("env",a):H(t)?n("cache",t):{tier:"none",cacheDir:t,dirs:[]}}function Um(e){return Qe(e).dir}async function et(e){let{dirs:t}=Qe();if(!t.length)return;let n=r=>{for(let s of t){let o=I(s,r);if(H(o))return o}};if(!Nc){let r=n("web-tree-sitter.wasm");if(!r)return;await go.init({wasmBinary:Q(r)}),Nc=!0,Rs=new go}for(let r of new Set(e)){if(Xn.has(r))continue;let s=n(`${r}.wasm`),o=s?(()=>{try{let a=ve(s);return`${s}:${a.size}:${a.mtimeMs}`}catch{return`${s}:unreadable`}})():`missing:${t.join("|")}`;if(vs.get(r)!==o){if(!s){vs.set(r,o);continue}try{Xn.set(r,await po.load(new Uint8Array(Q(s)))),vs.delete(r)}catch{vs.set(r,o)}}}}function yo(){return[...new Set(Object.values(Ms))]}function wt(e){let t=new Set;for(let n of e){let r=Ms[n];r!==void 0&&t.add(r)}return[...t].sort()}function tt(e){return Xn.has(e)}function bo(e){return Xn.get(e)}function Cs(e){let t=Xn.get(e);return!Rs||!t?null:(Rs.setLanguage(t),Rs)}var Zn,Yn,Ms,Ic,Nc,Rs,Xn,vs,nt=O(()=>{"use strict";E();xe();so();ae();ks();ho();Xe();Zn=new Set(["typescript","tsx","javascript","python","go","rust","java","ruby","c","cpp","c_sharp","php","scala","bash","lua"]),Yn=new Set(["kotlin","elixir","zig","hcl","terraform","solidity"]),Ms={".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".go":"go",".rs":"rust",".java":"java",".rb":"ruby",".rake":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"c_sharp",".php":"php",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".lua":"lua",".kt":"kotlin",".kts":"kotlin",".ex":"elixir",".exs":"elixir",".zig":"zig",".hcl":"hcl",".tf":"terraform",".tfvars":"terraform",".sol":"solidity"};Ic="grammars-extended";Nc=!1,Rs=null,Xn=new Map,vs=new Map});function Te(e,t){for(let n of e.namedChildren){if(t(n))return n;let r=Te(n,t);if(r)return r}}function er(e){let t=e.childForFieldName("name");if(t?.text)return t.text;let n=e.childForFieldName("declarator");for(;n;){let o=n.childForFieldName("name");if(o?.text)return o.text;if(n.namedChildren.length===0&&/(^|_)identifier$/.test(n.type))return n.text;let a=n.childForFieldName("declarator");if(!a||a===n)break;n=a}let s=Te(e,o=>o.type==="variable_declarator")?.childForFieldName("name");if(s?.text)return s.text;for(let o of e.namedChildren)if(/(^|_)(identifier|name|constant)$/.test(o.type))return o.text}function Kt(e){if(!e)return;let t=e.namedChildren;if(t.length===0)return As.test(e.type)?e.text:void 0;let n=e.childForFieldName("name")??e.childForFieldName("property")??e.childForFieldName("attribute")??e.childForFieldName("field")??e.childForFieldName("function");if(n)return Kt(n);let r=t[t.length-1];return r&&r!==e?Kt(r):void 0}function tr(e){if(!e||e.namedChildren.length===0)return;let t=e.childForFieldName("object")??e.childForFieldName("operand")??e.childForFieldName("value")??e.childForFieldName("path")??e.childForFieldName("expression")??e.childForFieldName("argument")??e.childForFieldName("receiver")??e.childForFieldName("table"),n=t?Kt(t):void 0;return n&&/^[A-Za-z_]\w*$/.test(n)?n:void 0}function ze(e){if(!e)return;let t=e.childForFieldName("type")??e.childForFieldName("name");if(t&&/generic|qualified|scoped|nested/.test(e.type))return ze(t);if(e.namedChildren.length===0)return Fc.test(e.type)?e.text:void 0;let n,r=s=>{if(s.namedChildren.length===0){Fc.test(s.type)&&(n=s.text);return}if(!/arguments|parameters/.test(s.type))for(let o of s.namedChildren)r(o)};return r(e),n}var As,Fc,wo=O(()=>{"use strict";E();As=/(^|_)(identifier|name|constant|word)$/;Fc=/identifier|constant|(^|_)name$/});function Fe(e){if(!e)return[];let t=[];for(let n of e.namedChildren){if(/arguments|parameters/.test(n.type))continue;let r=ze(n);r&&t.push(r)}return t}function Oc(e,t){if(!t.self)return[];let n=he(e,"class_heritage");if(!n)return[];let r=[];for(let s of Fe(he(n,"extends_clause")))r.push(ge("extends",t.self,s,e));for(let s of Fe(he(n,"implements_clause")))r.push(ge("implements",t.self,s,e));return r}function nr(e,t,n){return Fe(e).map((s,o)=>ge(o===0?"extends":"implements",t,s,n))}var he,ge,Wc,ko,Is,Pc,xo,Bm,$c,Dc,zm,rr,Hm,Ts,Lc,Gm,jc,So,Uc,Bc=O(()=>{"use strict";E();wo();he=(e,t)=>e.namedChildren.find(n=>n.type===t),ge=(e,t,n,r)=>({kind:e,from:t,to:n,line:r.startPosition.row+1});Wc=new Set(["interface","trait","enum","protocol","annotation"]),ko=new Set(["function","method","def","constructor","operator"]),Is=new Set(["function","function_expression","arrow_function","generator_function","class","function_definition","lambda"]),Pc=e=>/\b(public|internal)\b/.test(e),xo=e=>!/\b(private|protected)\b/.test(e),Bm=e=>!/^local\b/.test(e),$c=e=>/\bpub\b/.test(e),Dc=(e,t)=>/^[A-Z]/.test(t),zm=(e,t)=>!t.startsWith("_")||/^__\w+__$/.test(t),rr=()=>!0,Hm=()=>!1,Ts=e=>Te(e,t=>t.type==="function_declarator")!==void 0,Lc={defmodule:"module",defprotocol:"protocol",defimpl:"impl",defstruct:"struct",defexception:"exception",def:"function",defp:"function",defmacro:"macro",defmacrop:"macro",defguard:"guard",defguardp:"guard",defdelegate:"function"},Gm=new Set(["resource","data","variable","output","module","provider","locals","terraform"]),jc={lang:"terraform",defs:{block:"block"},containers:new Set(["config_file","body"]),exported:rr,kindFrom:{block:e=>{let t=e.namedChildren.find(n=>n.type==="identifier")?.text;return t&&Gm.has(t)?t:void 0}},nameFrom:{block:e=>{let t=e.namedChildren.filter(n=>n.type==="string_lit").map(n=>n.text.replace(/^"|"$/g,""));return t.length?t.join("."):e.namedChildren.find(n=>n.type==="identifier")?.text}}},So={lang:"typescript",defs:{function_declaration:"function",generator_function_declaration:"function",function_signature:"function",class_declaration:"class",abstract_class_declaration:"class",interface_declaration:"interface",type_alias_declaration:"type",enum_declaration:"enum",enum_assignment:"enum-member",method_definition:"method",method_signature:"method",abstract_method_signature:"method",property_signature:"property",public_field_definition:"property",call_signature:"call-signature",construct_signature:"construct-signature",index_signature:"index-signature",internal_module:"namespace",module:"namespace",variable_declarator:"const"},containers:new Set(["class_body","export_statement","ambient_declaration","program","lexical_declaration","variable_declaration","interface_body","object_type","enum_body","statement_block","try_statement","catch_clause","finally_clause","if_statement","else_clause","for_statement","for_in_statement","while_statement","do_statement","switch_statement","switch_body","switch_case","switch_default","labeled_statement","return_statement","expression_statement","call_expression","arguments","arrow_function","function_expression","function","parenthesized_expression"]),exported:Hm,exportMarkers:new Set(["export_statement","ambient_declaration"]),bareMembers:{enum_body:"enum-member"},nameFrom:{call_signature:()=>"(call)",construct_signature:()=>"(construct)",index_signature:e=>`[${e.namedChildren.find(t=>t.type==="identifier")?.text??"key"}]`},privateMember:e=>{for(let t of e.namedChildren)if(t.type==="accessibility_modifier"&&/^(private|protected)/.test(t.text)||t.type==="private_property_identifier")return!0;return!1},imports:{import_statement:"string"},calls:{call_expression:"function",new_expression:"constructor"},assignments:!0,relationsFrom:{class_declaration:Oc,abstract_class_declaration:Oc,interface_declaration:(e,t)=>t.self?Fe(he(e,"extends_type_clause")).map(n=>ge("extends",t.self,n,e)):[]}},Uc={typescript:So,tsx:{...So,lang:"typescript"},javascript:{...So,lang:"javascript",defs:{function_declaration:"function",generator_function_declaration:"function",class_declaration:"class",method_definition:"method",field_definition:"property",variable_declarator:"const"}},python:{lang:"python",defs:{function_definition:"function",class_definition:"class"},containers:new Set(["block","decorated_definition","module"]),exported:zm,imports:{import_statement:"path",import_from_statement:"path"},calls:{call:"function"},docstring:!0,relationsFrom:{class_definition:(e,t)=>t.self?Fe(e.childForFieldName("superclasses")).map(n=>ge("extends",t.self,n,e)):[]},extraMembers:(e,t)=>{if(t.inFunctionBody)return[];if(e.type==="import_from_statement"){let s=[];for(let o of e.namedChildren){if(o.type!=="aliased_import")continue;let a=o.namedChildren[0]?.text,l=o.childForFieldName("alias")?.text;a&&l&&a===l&&s.push({name:l,kind:"reexport"})}return s}if(e.type!=="expression_statement")return[];let n=e.namedChildren[0];if(!n||n.type!=="assignment")return[];let r=n.childForFieldName("left");return!r||r.type!=="identifier"?[]:[{name:r.text,kind:t.ownerKind==="class"?"field":"const"}]}},go:{lang:"go",defs:{function_declaration:"function",method_declaration:"method",type_spec:"type",const_spec:"const",var_spec:"var",field_declaration:"field",method_spec:"method",method_elem:"method",package_clause:"package"},containers:new Set(["type_declaration","const_declaration","var_declaration","var_spec_list","source_file","struct_type","interface_type","field_declaration_list"]),exported:Dc,imports:{import_declaration:"string"},calls:{call_expression:"function"},parentFrom:{method_declaration:e=>ze(e.childForFieldName("receiver"))},nameFrom:{field_declaration:e=>e.childForFieldName("name")?.text},relationsFrom:{field_declaration:(e,t)=>{if(!t.self||e.childForFieldName("name"))return[];let n=ze(e.childForFieldName("type"));return n?[ge("extends",t.self,n,e)]:[]}}},ruby:{lang:"ruby",defs:{method:"def",singleton_method:"def",class:"class",module:"module"},containers:new Set(["class","module","body_statement","program"]),exported:rr,calls:{call:"function"},sectionVisibility:e=>(e.type==="identifier"||e.type==="call")&&/^(private|protected)$/.test(e.text)?!1:e.type==="identifier"&&e.text==="public"?!0:void 0,relationsFrom:{class:(e,t)=>{if(!t.self)return[];let n=ze(e.childForFieldName("superclass"));return n?[ge("extends",t.self,n,e)]:[]},call:(e,t)=>{let n=e.childForFieldName("method");if(!t.self||!n||!/^(include|prepend|extend)$/.test(n.text))return[];let r=[];for(let s of e.childForFieldName("arguments")?.namedChildren??[]){let o=ze(s);o&&r.push(ge("implements",t.self,o,e))}return r}},extraMembers:(e,t)=>{if(t.inFunctionBody)return[];if(e.type==="assignment"){let n=e.childForFieldName("left");return n?.type==="constant"?[{name:n.text,kind:"const"}]:[]}if(e.type==="call"){let n=e.childForFieldName("method");if(!n||!/^attr_(reader|writer|accessor)$/.test(n.text))return[];let r=e.childForFieldName("arguments"),s=[];for(let o of r?.namedChildren??[])o.type==="simple_symbol"&&s.push({name:o.text.replace(/^:/,""),kind:"attr"});return s}return[]}},java:{lang:"java",defs:{class_declaration:"class",interface_declaration:"interface",annotation_type_declaration:"annotation",enum_declaration:"enum",enum_constant:"enum-member",record_declaration:"record",method_declaration:"method",constructor_declaration:"constructor",compact_constructor_declaration:"constructor",field_declaration:"field",constant_declaration:"field",annotation_type_element_declaration:"method"},containers:new Set(["class_body","interface_body","enum_body","enum_body_declarations","annotation_type_body","program","formal_parameters"]),exported:Pc,imports:{import_declaration:"path"},calls:{method_invocation:"function",object_creation_expression:"constructor"},kindFrom:{formal_parameter:e=>e.parent?.parent?.type==="record_declaration"?"field":void 0},publicMember:e=>e.parent?.parent?.type==="record_declaration",nameFrom:{field_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,constant_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let s of Fe(e.childForFieldName("superclass")))n.push(ge("extends",t.self,s,e));let r=e.childForFieldName("interfaces");for(let s of Fe(he(r??e,"type_list")??r))n.push(ge("implements",t.self,s,e));return n},interface_declaration:(e,t)=>{let n=e.childForFieldName("interfaces")??he(e,"extends_interfaces");return t.self?Fe(he(n??e,"type_list")??n).map(r=>ge("extends",t.self,r,e)):[]},record_declaration:(e,t)=>{let n=e.childForFieldName("interfaces");return t.self?Fe(he(n??e,"type_list")??n).map(r=>ge("implements",t.self,r,e)):[]}}},rust:{lang:"rust",defs:{function_item:"function",function_signature_item:"function",struct_item:"struct",enum_item:"enum",enum_variant:"enum-member",field_declaration:"field",trait_item:"trait",type_item:"type",associated_type:"type",mod_item:"mod",const_item:"const",static_item:"static",union_item:"union",macro_definition:"macro"},containers:new Set(["impl_item","declaration_list","source_file","field_declaration_list","enum_variant_list","foreign_mod_item","block"]),exported:$c,calls:{call_expression:"function"},parentFrom:{impl_item:e=>ze(e.childForFieldName("type"))},nestedDefs:new Set(["const_item","static_item"]),publicMembersIn:{impl_item:e=>e.childForFieldName("trait")!==null},relationsFrom:{impl_item:(e,t)=>{let n=ze(e.childForFieldName("trait"));return t.self&&n?[ge("implements",t.self,n,e)]:[]}}},c_sharp:{lang:"csharp",defs:{class_declaration:"class",interface_declaration:"interface",struct_declaration:"struct",enum_declaration:"enum",enum_member_declaration:"enum-member",record_declaration:"record",delegate_declaration:"delegate",method_declaration:"method",constructor_declaration:"constructor",property_declaration:"property",indexer_declaration:"indexer",operator_declaration:"operator",field_declaration:"field",event_declaration:"event",event_field_declaration:"event",conversion_operator_declaration:"operator",destructor_declaration:"destructor"},containers:new Set(["namespace_declaration","declaration_list","compilation_unit","file_scoped_namespace_declaration","enum_member_declaration_list","parameter_list"]),exported:Pc,calls:{invocation_expression:"function",object_creation_expression:"constructor"},kindFrom:{parameter:e=>e.parent?.parent?.type==="record_declaration"?"field":void 0},publicMember:e=>e.parent?.parent?.type==="record_declaration",nameFrom:{field_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,event_field_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,conversion_operator_declaration:e=>e.childForFieldName("type")?.text},relationsFrom:{class_declaration:(e,t)=>t.self?nr(he(e,"base_list"),t.self,e):[],struct_declaration:(e,t)=>t.self?nr(he(e,"base_list"),t.self,e):[],record_declaration:(e,t)=>t.self?nr(he(e,"base_list"),t.self,e):[],interface_declaration:(e,t)=>t.self?Fe(he(e,"base_list")).map(n=>ge("extends",t.self,n,e)):[]}},php:{lang:"php",defs:{function_definition:"function",class_declaration:"class",interface_declaration:"interface",trait_declaration:"trait",enum_declaration:"enum",enum_case:"enum-member",method_declaration:"method",property_declaration:"property",const_declaration:"const",namespace_definition:"namespace"},containers:new Set(["declaration_list","enum_declaration_list","program"]),exported:xo,calls:{function_call_expression:"function",member_call_expression:"member",object_creation_expression:"constructor"},nameFrom:{property_declaration:e=>Te(e,t=>t.type==="variable_name")?.text.replace(/^\$/,""),const_declaration:e=>Te(e,t=>t.type==="const_element")?.namedChildren[0]?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let r of Fe(he(e,"base_clause")))n.push(ge("extends",t.self,r,e));for(let r of Fe(he(e,"class_interface_clause")))n.push(ge("implements",t.self,r,e));return n},interface_declaration:(e,t)=>t.self?Fe(he(e,"base_clause")).map(n=>ge("extends",t.self,n,e)):[]}},c:{lang:"c",defs:{function_definition:"function",struct_specifier:"struct",enum_specifier:"enum",enumerator:"enum-member",union_specifier:"union",type_definition:"type",field_declaration:"field",declaration:"const"},containers:new Set(["translation_unit","declaration_list","field_declaration_list","enumerator_list","linkage_specification","preproc_ifdef","preproc_if"]),exported:rr,calls:{call_expression:"function"},kindFrom:{field_declaration:e=>Ts(e)?"method":"field",declaration:e=>Ts(e)?"function":"const"}},cpp:{lang:"cpp",defs:{function_definition:"function",class_specifier:"class",struct_specifier:"struct",enum_specifier:"enum",enumerator:"enum-member",union_specifier:"union",type_definition:"type",alias_declaration:"type",concept_definition:"concept",namespace_definition:"namespace",namespace_alias_definition:"namespace",field_declaration:"field",declaration:"const",using_declaration:"using",friend_declaration:"friend"},containers:new Set(["translation_unit","declaration_list","field_declaration_list","enumerator_list","template_declaration","linkage_specification","preproc_ifdef","preproc_if"]),exported:rr,calls:{call_expression:"function",new_expression:"constructor"},kindFrom:{field_declaration:e=>Ts(e)?"method":"field",declaration:e=>Ts(e)?"function":"const"},sectionVisibility:e=>e.type==="access_specifier"?!/^(private|protected)/.test(e.text):void 0,nameFrom:{friend_declaration:e=>er(e)??(e.namedChildren[0]?er(e.namedChildren[0]):void 0)},relationsFrom:{class_specifier:(e,t)=>t.self?Fe(he(e,"base_class_clause")).map(n=>ge("extends",t.self,n,e)):[],struct_specifier:(e,t)=>t.self?Fe(he(e,"base_class_clause")).map(n=>ge("extends",t.self,n,e)):[]}},scala:{lang:"scala",defs:{class_definition:"class",object_definition:"object",trait_definition:"trait",enum_definition:"enum",function_definition:"def",function_declaration:"def",val_definition:"val",val_declaration:"val",var_definition:"var",type_definition:"type",given_definition:"given",package_clause:"package"},containers:new Set(["compilation_unit","package_clause","template_body","class_parameters","parameters","extension_definition"]),parentFrom:{extension_definition:e=>ze(he(e,"parameters")?.namedChildren[0]?.childForFieldName("type")??null)},exported:xo,kindFrom:{class_parameter:e=>/^\s*(?:val|var)\b/.test(e.text)?/^\s*var\b/.test(e.text)?"var":"val":e.parent?.parent?.type==="class_definition"&&/\bcase\s+class\b/.test(e.parent.parent.text.slice(0,80))?"val":void 0},calls:{call_expression:"function",instance_expression:"constructor"},relationsFrom:{class_definition:(e,t)=>t.self?nr(he(e,"extends_clause"),t.self,e):[],object_definition:(e,t)=>t.self?nr(he(e,"extends_clause"),t.self,e):[],trait_definition:(e,t)=>t.self?Fe(he(e,"extends_clause")).map(n=>ge("extends",t.self,n,e)):[]}},bash:{lang:"shell",defs:{function_definition:"function",declaration_command:"const"},containers:new Set(["program","if_statement","compound_statement"]),exported:rr,calls:{command:"function"},nameFrom:{declaration_command:e=>/^\s*local\b/.test(e.text)?void 0:Te(e,t=>t.type==="variable_name")?.text}},kotlin:{lang:"kotlin",defs:{class_declaration:"class",object_declaration:"object",function_declaration:"function",property_declaration:"property",enum_entry:"enum-member",type_alias:"type",class_parameter:"property"},containers:new Set(["source_file","class_body","enum_class_body","companion_object","object_declaration","primary_constructor","class_parameters"]),exported:xo,calls:{call_expression:"function"},kindFrom:{class_parameter:e=>/^\s*(?:val|var)\b/.test(e.text)||/\bdata\s+class\b/.test(e.parent?.parent?.parent?.text.slice(0,80)??"")?"property":void 0,class_declaration:e=>{let t=e.text.slice(0,80);return/\binterface\b/.test(t)?"interface":/\benum\s+class\b/.test(t)?"enum":/\bannotation\s+class\b/.test(t)?"annotation":"class"}},nameFrom:{property_declaration:e=>Te(e,t=>t.type==="variable_declaration")?.namedChildren[0]?.text??e.namedChildren.find(t=>t.type==="identifier")?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let r of he(e,"delegation_specifiers")?.namedChildren??[]){let s=ze(r);s&&n.push(ge(Te(r,o=>o.type==="constructor_invocation")?"extends":"implements",t.self,s,e))}return n}}},elixir:{lang:"elixir",defs:{},containers:new Set(["source","do_block","call","stab_clause"]),exported:e=>!/^\s*defp?macrop\b|^\s*defp\b/.test(e),calls:{call:"function"},kindFrom:{call:e=>Lc[e.childForFieldName("target")?.text??e.namedChildren[0]?.text??""]},skipCall:e=>{if(e.parent?.type==="unary_operator")return!0;if(e.parent?.type!=="arguments")return!1;let t=e.parent.parent,n=t?.childForFieldName("target")??t?.namedChildren[0];return n!==void 0&&Lc[n.text]!==void 0},docFrom:e=>{let t=e.previousNamedSibling;for(;t&&t.type==="unary_operator";){let n=t.namedChildren[0],r=n?.childForFieldName("target")??n?.namedChildren[0];if(r&&/^(doc|moduledoc)$/.test(r.text)){let s=Te(t,o=>o.type==="string");if(s)return s.text.replace(/^"""|"""$/g,"").replace(/^"|"$/g,"").trim()||void 0}t=t.previousNamedSibling}},nameFrom:{call:e=>{let n=(e.childForFieldName("arguments")??e.namedChildren.find(s=>s.type==="arguments"))?.namedChildren[0];if(!n)return;if(n.type==="alias"||n.type==="identifier")return n.text;let r=n.childForFieldName("target")??n.namedChildren[0];return r&&/identifier|alias/.test(r.type)?r.text:void 0}}},zig:{lang:"zig",defs:{function_declaration:"function",variable_declaration:"const",container_field:"field",test_declaration:"test"},containers:new Set(["source_file","variable_declaration","struct_declaration","enum_declaration","union_declaration","error_set_declaration","opaque_declaration","block"]),exported:$c,calls:{call_expression:"function"},kindFrom:{variable_declaration:e=>{let t=e.namedChildren.find(n=>n.type==="builtin_function");if(!(t&&/^@(import|cImport)\b/.test(t.text))){for(let n of e.namedChildren){if(n.type==="struct_declaration")return"struct";if(n.type==="enum_declaration")return"enum";if(n.type==="union_declaration")return"union";if(n.type==="error_set_declaration")return"error";if(n.type==="opaque_declaration")return"opaque"}return/^\s*(?:pub\s+)?var\b/.test(e.text.slice(0,24))?"var":"const"}},container_field:e=>e.parent?.type==="enum_declaration"?"enum-member":"field"}},solidity:{lang:"solidity",defs:{contract_declaration:"contract",interface_declaration:"interface",library_declaration:"library",function_definition:"function",constructor_definition:"constructor",modifier_definition:"modifier",event_definition:"event",error_declaration:"error",struct_declaration:"struct",struct_member:"field",enum_declaration:"enum",enum_value:"enum-member",state_variable_declaration:"field",constant_variable_declaration:"const",user_defined_type_definition:"type",fallback_receive_definition:"function"},containers:new Set(["source_file","contract_body","struct_declaration","enum_declaration","enum_body"]),exported:(e,t)=>/\b(public|external)\b/.test(e)?!0:/\b(internal|private)\b/.test(e)?!1:Dc(e,t)||!0,calls:{call_expression:"function"},nameFrom:{state_variable_declaration:e=>e.namedChildren.find(t=>t.type==="identifier")?.text,fallback_receive_definition:e=>/^\s*receive\b/.test(e.text)?"receive":"fallback",enum_value:e=>e.text},relationsFrom:{contract_declaration:(e,t)=>t.self?e.namedChildren.filter(n=>n.type==="inheritance_specifier").map(n=>ze(n)).filter(n=>n!==void 0).map(n=>ge("extends",t.self,n,e)):[],interface_declaration:(e,t)=>t.self?e.namedChildren.filter(n=>n.type==="inheritance_specifier").map(n=>ze(n)).filter(n=>n!==void 0).map(n=>ge("extends",t.self,n,e)):[]}},terraform:jc,hcl:{...jc,lang:"hcl"},lua:{lang:"lua",defs:{function_declaration:"function"},containers:new Set(["chunk","variable_declaration"]),exported:Bm,calls:{function_call:"function"},assignments:!0}}});function Jm(e){let t=e.childForFieldName("body"),n=t&&t.startIndex>e.startIndex?t.startIndex:void 0,r=s=>{qm.has(s.type)&&s.startIndex>e.startIndex&&(n===void 0||s.startIndex|=)$/,"").trim().slice(0,Vm)}var qm,Vm,zc=O(()=>{"use strict";E();qm=new Set(["block","statement_block","class_body","declaration_list","field_declaration_list","template_body","compound_statement","body_statement","enum_body","enum_body_declarations","enum_variant_list","enum_member_declaration_list","enumerator_list","interface_body","object_type","do_block","struct_declaration","enum_declaration","union_declaration","error_set_declaration","opaque_declaration","contract_body","enum_class_body"]),Vm=400});function Eo(e){return Km.test(e.trim())}function vo(e){return Xm.test(e.trim())}function xt(e){return e.replace(/\*+\/\s*$/,"").replace(/^\s*\/\*+!?/,"").replace(/^\s*\/\/[/!]?/,"").replace(/^\s*--+/,"").replace(/^\s*#+/,"").replace(/^\s*\*+/,"").replace(/^\s*(?:"""|''')/,"").replace(/(?:"""|''')\s*$/,"").replace(/[-=~_]{3,}/g," ").trim()}function Zm(e){return e.replace(/<\/?[A-Za-z][^>]*>/g," ").replace(/\s+/g," ").trim()}function Ro(e,t=Ym){let n=[];for(let o of e){let a=o.trim();if(!(!a||Eo(a)||vo(a))){if(/^@[a-z]/i.test(a))break;n.push(a)}}let r=Zm(n.join(" "));if(r.length<3)return;let s=/^(.*?[.!?])(\s|$)/.exec(r);return(s?s[1]:r).slice(0,t)}var Km,Xm,Ym,Ns=O(()=>{"use strict";E();Km=/^(eslint\b|eslint-|prettier\b|prettier-|tslint\b|jshint\b|jslint\b|globals?\b|istanbul\b|c8\s|v8\s|@ts-|ts-|@flow\b|@jsx\b|@jsxRuntime\b|@jest-environment\b|@vitest-environment\b|@license\b|@preserve\b|@copyright\b|copyright\b|spdx-|1);)t.push(n),r=n.startPosition.row,n=n.previousNamedSibling;if(!t.length)return[];t.reverse();let s=[];for(let o of t)for(let a of o.text.split(/\r?\n/))s.push(xt(a));return s}function Sn(e){let t=e;for(;t;){let n=tp(t);if(n.length){let o=Ro(n);if(o)return o}let r=t.parent;if(!r||!ep.has(r.type))return;let s=t.previousNamedSibling;if(s&&!np.test(s.type))return;t=r}}function Hc(e){let n=e.childForFieldName("body")?.namedChildren[0];if(!n)return;let r=n.type==="string"?n:n.type==="expression_statement"?n.namedChildren[0]:void 0;if(!(!r||r.type!=="string"))return Ro(r.text.split(/\r?\n/).map(xt))}var Qm,ep,np,Gc=O(()=>{"use strict";E();Ns();Qm=/(^|_)comment$/,ep=new Set(["export_statement","ambient_declaration","decorated_definition","template_declaration","labeled_statement","lexical_declaration","variable_declaration","type_declaration","const_declaration","var_declaration","body_statement","body"]);np=/decorator|annotation|modifiers/});function wp(e){let t=Vc.get(e);return t===void 0&&(t=(mp.test(e)?Jc:0)|(gp.test(e)?Kc:0)|(_p.test(e)?Mo:0)|(hp.test(e)?Xc:0)|(yp.test(e)?Zc:0),Vc.set(e,t)),t}function xp(e){return e.namedChildren.every(t=>bp.test(t.type))}function Sp(e,t,n,r,s){let o=new Set,a=t.calls!==void 0,l=[],c=new Set,d=(b,w,v)=>{if(!b||b.length<2||!/^[A-Za-z_]\w*$/.test(b))return;let A=w.startPosition.row+1,F=`${b} ${A}`;c.has(F)||(c.add(F),l.push(v?{name:b,line:A,receiver:v}:{name:b,line:A}))},f=new Set,u=b=>{if(!(f.size>=qc))for(let w of yt(b)){if(f.size>=qc)return;f.add(w)}},m=new Nt,p=t.imports?.import_statement!==void 0,g=new Set,y=s&&t.imports!==void 0,h=[],S=new Set,_=b=>{let w=b.trim();w&&!S.has(w)&&(S.add(w),h.push({kind:"import",spec:w}))},k=b=>{let w=b.type,v=b.namedChildren,A=wp(w);if(v.length===0&&A&Jc){let F=b.text;pp.test(F)&&!n.has(F)&&o.add(F)}if(A&Kc)for(let F of b.text.split(/\r?\n/))u(xt(F));else v.length===0&&A&Mo&&b.endIndex-b.startIndex<=lp&&u(b.text.replace(/^['"`]+|['"`]+$/g,""));if(m.full||(A&Mo?xp(b)&&m.addString(b.text,b.startPosition.row+1):v.length===0&&A&Xc?m.add("number",b.text.trim(),b.startPosition.row+1):A&Zc&&m.add("regex",b.text,b.startPosition.row+1)),a&&!(t.kindFrom?.[w]&&t.kindFrom[w](b))&&!t.skipCall?.(b)){let F=t.calls[w];if(F==="function"){let T=b.childForFieldName("function")??b.childForFieldName("callee")??b.childForFieldName("method")??b.childForFieldName("name")??b.childForFieldName("target")??v[0]??null;d(Kt(T),b,tr(T)??tr(b))}else if(F==="member")d(Kt(b.childForFieldName("name")),b,tr(b));else if(F==="constructor"){let T=b.childForFieldName("constructor")??b.childForFieldName("type")??b.childForFieldName("name");for(let U=0;!T&&U/string/.test(U.type));T&&_(T.text.replace(/^['"]|['"]$/g,""))}else if(F==="path"){let T=b.childForFieldName("name")??b.childForFieldName("module_name");_((T??b).text.replace(/^(import|from)\s+/,"").split(/\s+/)[0])}}for(let F of v)k(F)};return k(e),l.sort((b,w)=>M(b.name,w.name)||b.line-w.line),{refs:h,idents:[...o].sort().slice(0,rp),calls:l.slice(0,r),importedNames:[...g].sort(M).slice(0,ip),terms:[...f].sort(M),literals:m.result()??[]}}function kp(e){let t=[],n=r=>{if(/^(shorthand_property_identifier_pattern|identifier)$/.test(r.type)){t.includes(r.text)||t.push(r.text);return}if(r.type==="pair_pattern"){let s=r.childForFieldName("value");s&&n(s);return}for(let s of r.namedChildren)n(s)};for(let r of e.namedChildren)n(r);return t}function Co(e,t,n,r={}){let s=Qn(t);if(!s||!tt(s))return;let o=Uc[s];if(!o)return;let a=Cs(s);if(!a)return;let l=null;try{if(l=a.parse(n),!l)return;let c=r.maxSymbols??op,d=[],f=l.rootNode,u=(e.split("/").pop()??"").replace(/\.[^.]+$/,""),m=new Set,p=P=>{d.length{let B=o.relationsFrom?.[P.type];if(B)for(let se of B(P,{self:j})){if(se.from===se.to)continue;let J=`${se.kind} ${se.from} ${se.to}`;y.has(J)||g.length>=ap||(y.add(J),g.push(se))}},S=(P,j,B,se)=>se.inFunctionBody||o.privateMember?.(P)===!0?!1:o.publicMember?.(P)===!0?!0:se.sectionPublic?se.forcePublic?!0:se.exported||o.exported(j,B):!1,_=P=>o.docFrom?.(P)??(o.docstring?Hc(P):void 0)??Sn(P),k=(P,j)=>{let B=j.sectionPublic,se=o.bareMembers?.[P.type];for(let J of P.namedChildren){if(o.sectionVisibility){let be=o.sectionVisibility(J);if(be!==void 0){B=be;continue}}let ne=B===j.sectionPublic?j:{...j,sectionPublic:B};if(se&&J.namedChildren.length===0&&As.test(J.type)){p({name:J.text,kind:se,file:e,line:J.startPosition.row+1,endLine:J.endPosition.row+1,...ne.parent?{parent:ne.parent}:{},exported:ne.forcePublic||ne.exported,lang:o.lang});continue}for(let be of o.extraMembers?.(J,{ownerKind:ne.ownerKind,inFunctionBody:ne.inFunctionBody})??[]){let Ie=Ot(J,n),X=Sn(J);p({name:be.name,kind:be.kind,file:e,line:J.startPosition.row+1,endLine:J.endPosition.row+1,...ne.parent?{parent:ne.parent}:{},...ne.parentPath&&ne.parentPath!==ne.parent?{parentPath:ne.parentPath}:{},signature:Ie,...X?{doc:X}:{},exported:S(J,Ie,be.name,ne),lang:o.lang})}w(J,ne)}},b=(P,j)=>{let B=!1;for(let se of P.namedChildren)o.containers.has(se.type)&&(B=!0,k(se,j));!B&&o.containers.has(P.type)&&k(P,j)},w=(P,j)=>{if(j.funcDepth>cp)return;let B=P.type,se=o.exportMarkers?.has(B)===!0,J=j.exported||se;if(B==="export_statement"){for(let X of P.namedChildren)if(X.type==="identifier")m.add(X.text);else if(X.type==="export_clause")for(let Z of X.namedChildren){let D=Z.childForFieldName("name")??Z.namedChildren[0];D?.text&&m.add(D.text)}if(u&&P.children.some(X=>X.type==="default"))for(let X of P.namedChildren){let Z=up.has(X.type),D=fp.has(X.type);if((Z||D)&&!X.childForFieldName("name")){let de=Sn(P);p({name:u,kind:D?"class":"function",file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,signature:Ot(P,n),...de?{doc:de}:{},exported:!0,lang:o.lang});break}}}if(o.assignments&&B==="expression_statement"){let X=P.namedChildren[0];if(X?.type==="assignment_expression"){let Z=X.childForFieldName("left"),D=X.childForFieldName("right");if(Z?.type==="member_expression"&&Z.text==="module.exports"&&D){if(D.type==="object"){for(let K of D.namedChildren)if(K.type==="shorthand_property_identifier")m.add(K.text);else if(K.type==="pair"){let ce=K.childForFieldName("key"),we=K.childForFieldName("value");ce?.type==="property_identifier"&&m.add(ce.text),we?.type==="identifier"&&m.add(we.text)}return}if(D.type==="identifier"){m.add(D.text);return}}let de=D&&Is.has(D.type);if(Z&&D&&de){let K,ce=!1;if(Z.type==="member_expression"){let we=Z.childForFieldName("property");if(we?.type==="property_identifier"){K=we.text;let gt=Z.text.slice(0,Z.text.length-we.text.length-1);ce=gt==="exports"||gt==="module.exports"}}else Z.type==="identifier"&&(K=Z.text);if(K){let we=Sn(P);p({name:K,kind:D.type==="class"?"class":"function",file:e,line:X.startPosition.row+1,endLine:X.endPosition.row+1,...j.parent?{parent:j.parent}:{},signature:Ot(X,n),...we?{doc:we}:{},exported:!j.inFunctionBody&&(J||ce),lang:o.lang});return}}else if(Z?.type==="member_expression"&&D){let K=Z.childForFieldName("property");if(K?.type==="property_identifier"){let ce=Z.text.slice(0,Z.text.length-K.text.length-1);if(ce==="exports"||ce==="module.exports"){D.type==="identifier"&&m.add(D.text),(D.type!=="identifier"||D.text!==K.text)&&p({name:K.text,kind:"const",file:e,line:X.startPosition.row+1,endLine:X.endPosition.row+1,...j.parent?{parent:j.parent}:{},signature:Ot(X,n),exported:!0,lang:o.lang});return}}}}}if(o.assignments&&B==="assignment_statement"){let X=P.children.find(ce=>ce.type==="variable_list"),Z=P.children.find(ce=>ce.type==="expression_list"),D=X?.namedChildren??[],de=Z?.namedChildren??[],K=Math.min(D.length,de.length);for(let ce=0;ceK.type==="object_pattern"||K.type==="array_pattern");if(D&&!j.inFunctionBody){let K=Ot(P,n),ce=_(P);for(let we of kp(D))p({name:we,kind:Ie,file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,...j.parent?{parent:j.parent}:{},signature:K,...ce?{doc:ce}:{},exported:S(P,K,we,{...j,exported:J}),lang:o.lang});return}let de=ko.has(Ie)||dp.has(Ie)||o.nestedDefs?.has(B)===!0||Is.has(P.childForFieldName("value")?.type??"");if(Z&&(!j.inFunctionBody||de)){let K=Ot(P,n),ce=_(P),we=ne??j.parent,gt=ne??j.parentPath;p({name:Z,kind:Ie,file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,...we?{parent:we}:{},...gt&>!==we?{parentPath:gt}:{},signature:K,...ce?{doc:ce}:{},exported:S(P,K,Z,{...j,exported:J}),lang:o.lang}),h(P,Z);let $n=ko.has(Ie);b(P,{parent:Z,parentPath:gt?`${gt}/${Z}`:Z,ownerKind:Ie,exported:J,forcePublic:Wc.has(Ie),inFunctionBody:j.inFunctionBody||$n,funcDepth:j.funcDepth+($n?1:0),sectionPublic:!0});return}}if(h(P,ne??j.parent),o.containers.has(B)){let X=j.forcePublic||o.publicMembersIn?.[B]?.(P)===!0,Z=Is.has(B);k(P,{...j,exported:J,forcePublic:X,inFunctionBody:j.inFunctionBody||Z,funcDepth:j.funcDepth+(Z?1:0),...ne?{parent:ne,parentPath:ne,ownerKind:"type"}:{}})}};if(k(f,{exported:!1,forcePublic:!1,inFunctionBody:!1,funcDepth:0,sectionPublic:!0}),m.size)for(let P of d)!P.exported&&m.has(P.name)&&(P.exported=!0);let v=r.imports!==!1,{refs:A,idents:F,calls:T,importedNames:U,terms:te,literals:V}=Sp(f,o,new Set(d.map(P=>P.name)),r.maxCalls??sp,v),z;if(v&&o.lang==="java"){let P=Te(f,j=>j.type==="package_declaration");P&&(z=P.text.replace(/^package\s+/,"").replace(/;.*$/,"").trim())}return g.sort((P,j)=>M(P.from,j.from)||M(P.kind,j.kind)||M(P.to,j.to)),{symbols:d,refs:A,pkg:z,idents:F,calls:T,importedNames:U,relations:g,terms:te,literals:V,...d.length>=c?{truncated:!0}:{}}}catch{return}finally{l?.delete()}}var rp,sp,ip,op,ap,qc,lp,cp,dp,up,fp,mp,pp,gp,_p,hp,yp,bp,Jc,Kc,Mo,Xc,Zc,Vc,Ao=O(()=>{"use strict";E();ws();Y();nt();wo();Bc();zc();Gc();Ns();Ae();rp=512,sp=512,ip=256,op=2e3,ap=256,qc=512,lp=80,cp=2,dp=new Set(["class","struct","enum","interface","trait","type","record","union"]),up=new Set(["function","function_expression","function_declaration","generator_function","generator_function_declaration","arrow_function"]),fp=new Set(["class","class_declaration","abstract_class_declaration"]),mp=/identifier|constant|(^|_)name$/,pp=/^[A-Za-z_]\w{4,}$/,gp=/(^|_)comment$/,_p=/(^|_)string(_literal)?$/,hp=/(^|_)(integer|float|number|decimal|numeric)(_literal)?$/,yp=/(^|_)(regex|regular_expression)(_pattern|_literal)?$/,bp=/(^|_)(fragment|content|escape_sequence|character)$/,Jc=1,Kc=2,Mo=4,Xc=8,Zc=16,Vc=new Map});function Cp(e){let t=e.split(/\r?\n/),n=[],r=null;for(let a=0;aa&&!Eo(a)&&!vo(a)).join(" ").replace(/\s+/g," ").trim();if(s.length<8)return;let o=/^(.*?[.!?])(\s|$)/.exec(s);return(o?o[1]:s).slice(0,200)}function Io(e,t=[]){if(t.length>=Ap)return t;let n=e.indexOf("{");if(n===-1){let c=e.replace(/\s+as\s+\w+\s*$/,"").replace(/::\s*\*\s*$/,"").replace(/^::/,"").trim();return c&&t.push(c),t}let r=e.slice(0,n),s=0,o=-1;for(let c=n;c({kind:"import",spec:s}))}function Np(e,t=[],n=512){let r=new Map,s=new Set(t.map(l=>`${l.name} ${l.line}`)),o=e.split(` +`),a=/(?:\bnew\s+)?(?:([A-Za-z_$][\w$]*)\s*\.\s*)?([A-Za-z_$][\w$]*)\s*\(/g;for(let l=0;ll.namec.name?1:l.line-c.line)}function Op(e){let t=new Set,n=s=>{if(!(t.size>=To))for(let o of yt(s)){if(t.size>=To)return;t.add(o)}},r=!1;for(let s of e.split(` +`)){if(t.size>=To)break;let o=s;if(r){let c=o.indexOf("*/");if(n(xt(c===-1?o:o.slice(0,c))),c===-1)continue;r=!1,o=o.slice(c+2)}let a=o.indexOf("/*");if(a!==-1){let c=o.indexOf("*/",a+2);n(xt(o.slice(a,c===-1?void 0:c))),c===-1?(r=!0,o=o.slice(0,a)):o=o.slice(0,a)+o.slice(c+2)}let l=/(^|\s)(\/\/|#|--)(.*)$/.exec(o);l&&(n(xt(l[2]+l[3])),o=o.slice(0,l.index));for(let c of o.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)){let d=c[2];d.length&&d.length<=Fp&&n(d)}}return[...t].sort()}function Pp(e){let t=new Nt,n=!1,r=0;for(let s of e.split(` +`)){if(r++,t.full)break;let o=s;if(n){let c=o.indexOf("*/");if(c===-1)continue;n=!1,o=o.slice(c+2)}let a=o.indexOf("/*");if(a!==-1){let c=o.indexOf("*/",a+2);c===-1?(n=!0,o=o.slice(0,a)):o=o.slice(0,a)+o.slice(c+2)}let l=/(^|\s)(\/\/|#|--)(.*)$/.exec(o);l&&(o=o.slice(0,l.index));for(let c of o.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g))t.add("string",c[2],r);for(let c of o.replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ").matchAll(/(?m.name)),c=gs(e,n,a).filter(m=>!l.has(m.name)),d=Tp(t,n),f=new Set(d.map(m=>m.spec)),u=(s?s.literals.length?s.literals:void 0:Pp(n))?.filter(m=>!(m.kind==="string"&&f.has(m.value)));return{symbols:[...a,...c],...s?.truncated||o.length>a.length||c.length>=ps?{truncated:!0}:{},summary:Cp(n),refs:d,pkg:t===".java"?/^\s*package\s+([\w.]+)\s*;/m.exec(n)?.[1]:t===".cs"?/^\s*(?:file-scoped\s+)?namespace\s+([\w.]+)/m.exec(n)?.[1]:void 0,idents:s?.idents,calls:s?s.calls:Np(n,a,r.maxCallsPerFile),importedNames:s?.importedNames,relations:s?.relations?.length?s.relations:void 0,terms:s?s.terms:Op(n),literals:u?.length?u:void 0}}var Ep,vp,Rp,Mp,Ap,Ip,Yc,To,Fp,Fo=O(()=>{"use strict";E();ws();bn();Ao();Re();Ns();Ae();Ep=2e3,vp=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),Rp=new Set([".py",".pyi"]),Mp=new Set([".c",".h",".cc",".cpp",".cxx",".hpp",".hh"]);Ap=16;Ip=new Set(["if","else","elif","for","while","do","switch","case","match","when","unless","until","catch","except","return","throw","raise","yield","await","typeof","instanceof","sizeof","delete","void","in","of","not","and","or","assert","defer","select","with","loop"]),Yc=/(?:\bfunction|\bdef|\bfunc|\bfun|\bfn|\bclass|\bsub|\bmacro|\bproc)\s*[*]?\s*$/;To=512,Fp=80});function ed(e){let t=new Nt,n=0;for(let r of e.split(` +`)){if(n++,t.full)break;let s=jp(r);for(let a of s.matchAll(Qc))t.add("string",a[2],n);let o=Lp.exec(s);if(o){let a=o[1].trim();a&&!/^[[{|>&*-]/.test(a)&&!$p.test(a)&&t.add("string",a,n)}for(let a of s.replace(Qc," ").matchAll(Dp))t.add("number",a[0].replace(/_/g,""),n)}return t.result()}function jp(e){let t;for(let n=0;n{"use strict";E();ws();Qc=/(['"])((?:\\.|(?!\1)[^\\])*)\1/g,$p=/(['"])((?:\\.|(?!\1)[^\\])*)\1/,Dp=/(?u.rel)),a!==void 0&&n.length!==a.size&&(l=!1,c=!0),{root:e,commit:ds(e),files:n,languages:r,docText:s,mtimes:o,capped:f.value.capped,excluded:f.value.excluded,contentUnchanged:l,cacheDirty:c}}var Pt=O(()=>{"use strict";E();ae();Ne();qt();Tt();bs();bn();Gn();Y();ro();Fo();td()});var Os,rd=O(()=>{E();Os=class{constructor(){throw new Error("worker_threads is not available in the browser build (the engine runs single-threaded here)")}}});function Wp(){try{let e=Ss(import.meta.url);if(e.endsWith("engine.mjs"))return qn(e).href;let t=I(_e(e),"engine.mjs");return H(t)?qn(t).href:void 0}catch{return}}function sd(e){let t=R.env.CODEINDEX_WORKERS,n=e??(t!==void 0&&t!==""?Number(t):void 0);if(n!==void 0)return Number.isFinite(n)&&n>0?Math.floor(n):0;let r=1;try{r=typeof xs=="function"?xs():dc().length}catch{r=1}return Math.max(0,Math.min(r-1,8))}async function zp(e,t){await et(e.grammarKeys);let n=e.grammarKeys.filter(s=>tt(s)),r=[];for(let s of e.jobs){let o,a;try{let d=ve(s.abs);o=d.size,a=d.mtimeMs}catch{continue}let l=q(s.abs),c=Fs(s.rel,s.ext,o,l,Ce(l),Vt(s.ext),{maxCallsPerFile:e.maxCallsPerFile});r.push({rel:s.rel,size:o,mtimeMs:a,record:c})}t({ready:n,records:r})}async function id(e,t,n,r={}){if(n<2||e.length===0)return;let s=Wp();if(!s)return;let o=t.filter(m=>tt(m)).sort(),a=Math.min(n,e.length),l=`import { runExtractWorker } from ${JSON.stringify(s)}; import { parentPort, workerData } from "node:worker_threads"; -runExtractWorker(workerData.input, (o) => parentPort.postMessage(o)).catch((e) => parentPort.postMessage({ error: String(e) })); -`;try{let c=await Promise.all(a.map(f=>new Promise((u,m)=>{let p=new Ns(l,{eval:!0,workerData:{input:{jobs:f,grammarKeys:o,maxCallsPerFile:r.maxCallsPerFile}}}),g=setTimeout(()=>{m(new Error("extraction worker timed out")),p.terminate()},wp),y=h=>{clearTimeout(g),h()};p.once("message",h=>{y(()=>u(h)),p.terminate()}),p.once("error",h=>y(()=>m(h))),p.once("exit",h=>{h!==0&&y(()=>m(new Error(`extraction worker exited with ${h}`)))})}))),d=new Map;for(let f of c){if("error"in f||f.ready.slice().sort().join(",")!==o.join(","))return;for(let u of f.records)d.set(u.rel,{size:u.size,mtimeMs:u.mtimeMs,record:u.record})}return d}catch{return}}async function Pt(e,t={}){let n=Jc(t.workers);if(n<2)return Pe(e,t);let r=t.precomputedWalk??Fe(e,{maxFileBytes:t.maxBytes,maxFiles:t.maxFiles,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs}),s={...t,precomputedWalk:r},o=[];for(let{f:d}of Io(e,s)){let f=t.cache?.get(d.rel);!t.fullHash&&f&&f.size!==void 0&&f.mtimeMs!==void 0&&f.size===d.size&&f.mtimeMs===d.mtimeMs||o.push({abs:d.abs,rel:d.rel,ext:d.ext})}if(o.length===0)return Pe(e,s);if(!(t.workers!==void 0||(R.env.CODEINDEX_WORKERS??"")!=="")&&o.lengthd.ext)),c=await Kc(o,l,n,{maxCallsPerFile:t.maxCallsPerFile});return Pe(e,c?{...s,extracted:c}:s)}var wp,xp,Os=F(()=>{"use strict";k();xe();to();oe();ws();Vc();At();Ae();yn();nt();Ft();wp=600*1e3,xp=200});function Jp(e){let t=Se(e).split("/").filter(s=>s!=="."),n=[],r=0;for(;rt?1:0)}function Wo(e){let t="",n=!1;for(let s=0;s parentPort.postMessage(o); +const fail = (e) => post({ error: String(e) }); +runExtractWorker({ ...base, jobs: [] }, post).then(() => { + parentPort.on("message", (m) => { + if (m.done) { parentPort.close(); return; } + runExtractWorker({ ...base, jobs: m.jobs }, post).catch(fail); + }); +}).catch(fail); +`,c=new Map,d=0,f=()=>{let m=e.length-d;if(m<=0)return[];let p=Math.max(Gp,Math.ceil(m/(a*Hp))),g=e.slice(d,d+p);return d+=g.length,g},u=[];try{return await Promise.all(Array.from({length:a},()=>new Promise((m,p)=>{let g=new Os(l,{eval:!0,workerData:{input:{jobs:[],grammarKeys:o,maxCallsPerFile:r.maxCallsPerFile}}});u.push(g);let y=!1,h,S=()=>{h&&clearTimeout(h),h=setTimeout(()=>{_(()=>p(new Error("extraction worker timed out"))),g.terminate()},Up)},_=w=>{h&&clearTimeout(h),y=!0,w()};S();let k=0,b=()=>{let w=f();return w.length===0?!1:(k++,g.postMessage({jobs:w}),!0)};g.on("message",w=>{if(!y){if("error"in w){_(()=>p(new Error(w.error))),g.terminate();return}if(w.ready.slice().sort().join(",")!==o.join(",")){_(()=>p(new Error("extraction worker grammar tier mismatch"))),g.terminate();return}for(let v of w.records)c.set(v.rel,{size:v.size,mtimeMs:v.mtimeMs,record:v.record});if(k===0?b():k--,b(),k===0){_(()=>m()),g.postMessage({done:!0}),g.terminate();return}S()}}),g.once("error",w=>_(()=>p(w))),g.once("exit",w=>{!y&&w!==0&&_(()=>p(new Error(`extraction worker exited with ${w}`)))})}))),c}catch{for(let m of u)m.terminate();return}}async function ut(e,t={}){let n=sd(t.workers);if(n<2)return Le(e,t);let r=t.precomputedWalk??Pe(e,{maxFileBytes:t.maxBytes,maxFiles:t.maxFiles,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs}),s={...t,precomputedWalk:r},o=[];for(let{f:d}of Po(e,s)){let f=t.cache?.get(d.rel);!t.fullHash&&f&&f.size!==void 0&&f.mtimeMs!==void 0&&f.size===d.size&&f.mtimeMs===d.mtimeMs||o.push({abs:d.abs,rel:d.rel,ext:d.ext})}if(o.length===0)return Le(e,s);if(!(t.workers!==void 0||(R.env.CODEINDEX_WORKERS??"")!=="")&&o.lengthd.ext)),c=await id(o,l,n,{maxCallsPerFile:t.maxCallsPerFile});return Le(e,c?{...s,extracted:c}:s)}var Up,Bp,Hp,Gp,ir=O(()=>{"use strict";E();xe();so();ae();ks();rd();Tt();Ne();bn();nt();Pt();Up=600*1e3,Bp=200;Hp=4,Gp=4});function je(e){let t=new Map;for(let n of e.files)t.set(n.rel,{hash:n.hash,record:n,size:n.size,mtimeMs:e.mtimes.get(n.rel)});return t}function $o(e,t,n=!1){let r=e.files.filter(s=>Hn(s.rel,s.ext)==="code");return n&&r.length>0||r.some(s=>{let o=t.get(s.rel);return!o||o.size!==s.size||o.mtimeMs!==s.mtimeMs})}function Do(e,t=ft){let n;try{n=JSON.parse(Q(I(e,t,"cache.json"),"utf8"))}catch{return}if(!(!n||n.schemaVersion!==5||n.extractorVersion!==14||!n.files))return{cacheMap:new Map(Object.entries(n.files)),meta:{engineVersion:n.engineVersion,commit:n.commit,graphSha1:n.graphSha1,symbolsSha1:n.symbolsSha1}}}function Lo(e,t,n,r=ft){if(!t.contentUnchanged||n.engineVersion!==fe||n.commit!==t.commit||n.graphSha1===void 0||n.symbolsSha1===void 0)return;let s=I(e,r),o,a;try{o=Q(I(s,"graph.json")),a=Q(I(s,"symbols.json"))}catch{return}if(!(Ce(o)!==n.graphSha1||Ce(a)!==n.symbolsSha1))try{let l=JSON.parse(o.toString("utf8")),c=JSON.parse(a.toString("utf8"));return l.schemaVersion!==5||c.schemaVersion!==5?void 0:{scan:t,graph:l,symbols:c}}catch{return}}function jo(e,t,n=ft){let r=Do(e,n);if(!r)return;let s=Le(e,{...t,cache:r.cacheMap});return{scan:s,cacheMap:je(s),arts:Lo(e,s,r.meta,n)}}async function Ps(e,t,n,r=ft){let s=Do(e,r);if(!s)return;let o=t.precomputedWalk??Pe(e,{maxFileBytes:t.maxBytes,maxFiles:t.maxFiles,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs});$o(o,s.cacheMap,t.fullHash)&&await n();let l=await ut(e,{...t,cache:s.cacheMap,precomputedWalk:o}),c=!1,d;return{scan:l,cacheMap:je(l),loadArtifacts:()=>(c||(c=!0,d=Lo(e,l,s.meta,r)),d)}}var ft,or=O(()=>{"use strict";E();xe();ae();Xe();Pt();ir();Tt();Ne();bs();ft=".codeindex"});function gd(e,t,n){let r=e.dirFilesMemo??=new Map,s=n+"\0"+t,o=r.get(s);return o||r.set(s,o=(e.filesByDir.get(t)??[]).filter(a=>a.endsWith(n)).sort()),o}function hg(e){let t=Se(e).split("/").filter(s=>s!=="."),n=[],r=0;for(;rt?1:0)}function Ho(e){let t="",n=!1;for(let s=0;s=Zp)){if(typeof e=="string")t.includes(e)||t.push(e);else if(Array.isArray(e))for(let n of e)Uo(n,t);else if(e!==null&&typeof e=="object"){let n=Object.keys(e).sort((r,s)=>sd(r)-sd(s)||(rs?1:0));for(let r of n)Uo(e[r],t)}}}function Yp(e){if(e==null)return[];let t=[],n=(r,s)=>{let o=[];Uo(s,o),o.length&&t.push({key:r,star:r.includes("*"),targets:o})};if(typeof e=="string"||Array.isArray(e))n(".",e);else if(typeof e=="object"){let r=Object.keys(e);if(r.every(s=>s==="."||s.startsWith("./")))for(let s of r)n(s,e[s]);else n(".",e)}return t.sort((r,s)=>Number(r.star)-Number(s.star)||s.key.length-r.key.length||(r.key{let o=/^\s*([^\s=]+)(?:\s+v\S+)?\s*=>\s*(\S+)(?:\s+v\S+)?\s*$/.exec(s);if(!o)return;let a=o[2];if(!/^\.\.?\//.test(a))return;let l=Se($.join(t,a));l.startsWith("..")||n.push({from:o[1],toDir:l})};for(let s of e.matchAll(/^[ \t]*replace[ \t]+([^(\r\n][^\r\n]*)$/gm))r(s[1]);for(let s of e.matchAll(/^[ \t]*replace[ \t]*\(([\s\S]*?)\)/gm))for(let o of s[1].split(/\r?\n/))r(o);return n}function Bo(e){let t=new Set(e.files.map(y=>y.rel)),n=new Map,r=new Set;for(let y of e.files){let h=y.rel.includes("/")?$.dirname(y.rel):"",S=n.get(h);S||n.set(h,S=[]),S.push(y.rel);let _=h;for(;_&&!r.has(_);)r.add(_),_=_.includes("/")?$.dirname(_):""}let s=[],o=[];for(let y of t){let h=y.slice(y.lastIndexOf("/")+1);if(h!=="tsconfig.json"&&h!=="jsconfig.json"&&!(y==="tsconfig.base.json"))continue;let _=y.includes("/")?$.dirname(y):"",E=id(e.root,t,y,s,new Set);if(!E?.paths)continue;let b=[];for(let[v,A]of Object.entries(E.paths)){if(!Array.isArray(A))continue;let O=v.endsWith("*");b.push({prefix:O?v.slice(0,-1):v,star:O,targets:A})}if(!b.length)continue;let x=E.baseUrl!==void 0?Se($.join(E.baseUrlDir,E.baseUrl)).replace(/^\.$/,""):E.pathsDir;o.push({dir:_,baseUrl:x,paths:b})}o.sort((y,h)=>h.dir.length-y.dir.length);let a=[];for(let y of t){if(y!=="go.mod"&&!y.endsWith("/go.mod"))continue;let h=G(I(e.root,y)),S=/^\s*module\s+(\S+)/m.exec(h);if(!S)continue;let _=y.includes("/")?$.dirname(y):"";a.push({module:S[1],dir:_,replaces:Qp(h,_)})}a.sort((y,h)=>h.dir.length-y.dir.length||(y.dirh.dir.length-y.dir.length||(y.dirtypeof _=="string");f.push({name:h.name,dir:y.includes("/")?$.dirname(y):"",exportEntries:Yp(h.exports),mainCandidates:S})}f.sort((y,h)=>h.name.length-y.name.length);let u=new Set([""]);for(let y of r){let h=y.slice(y.lastIndexOf("/")+1);(h==="include"||h==="inc"||h==="src")&&u.add(y)}let m=new Set([""]);for(let y of r)y.slice(y.lastIndexOf("/")+1)==="lib"&&m.add(y);let p=[];for(let y of t){if(y!=="composer.json"&&!y.endsWith("/composer.json"))continue;let h=Wo(G(I(e.root,y)));if(!h){s.push(`unparseable ${y} \u2014 skipped for PHP PSR-4 resolution`);continue}let S=y.includes("/")?$.dirname(y):"";for(let _ of[h.autoload?.["psr-4"],h["autoload-dev"]?.["psr-4"]])if(_)for(let[E,b]of Object.entries(_))for(let x of Array.isArray(b)?b:[b])typeof x=="string"&&p.push({prefix:E.replace(/\\+$/,""),dir:Se($.join(S,x)).replace(/^\.$/,"")})}p.sort((y,h)=>h.prefix.length-y.prefix.length);let g=new Map;for(let y of e.files){if(y.ext!==".cs"||!y.pkg)continue;let h=g.get(y.pkg);h||g.set(y.pkg,h=[]),h.push(y.rel)}for(let y of g.values())y.sort(M);return{fileSet:t,dirSet:r,filesByDir:n,tsConfigs:o,goModules:a,rustCrates:l,javaRoots:[...c].sort(Do),pyRoots:[...d],workspacePackages:f,cIncludeRoots:[...u].sort(Do),rubyLibRoots:[...m].sort(Do),phpPsr4:p,csharpNamespaces:g,warnings:s}}function ft(e,t){for(let n of t){let r=Se(n);if(r&&!r.startsWith("..")&&e.fileSet.has(r))return r}}function zo(e,t,n){let r=t.split("#")[0].split("?")[0];if(!r)return{kind:"external"};if(r.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(r))return{kind:"external"};let s=e.includes("/")?$.dirname(e):"",o=Se($.join(s,r));if(o.startsWith(".."))return{kind:"dangling",reason:"escapes-repo-root"};let a=ft(n,[o,o+".md",o+".mdx",$.join(o,"README.md"),$.join(o,"readme.md"),$.join(o,"index.md"),$.join(o,"index.mdx")]);return a?{kind:"resolved",target:a}:n.dirSet.has(o)?{kind:"external"}:{kind:"dangling",reason:"missing-target"}}function eg(e,t,n){let r=a=>ft(n,[...Up.map(l=>a+l),...Bp.map(l=>$.join(a,l))]),s=a=>{let l=r(a);if(l)return l;let c=a.replace(/\.(js|jsx|mjs|cjs)$/,"");return c!==a?r(c):void 0};if(t.startsWith(".")){let a=e.includes("/")?$.dirname(e):"",l=Se($.join(a,t));if(l.startsWith(".."))return{kind:"dangling",reason:"escapes-repo-root"};let c=s(l);return c?{kind:"resolved",target:c}:{kind:"dangling",reason:"missing-module"}}let o;for(let a of n.tsConfigs){if(a.dir&&e!==a.dir&&!e.startsWith(a.dir+"/"))continue;let l=!1;for(let c of a.paths){if(!(c.star?t.startsWith(c.prefix):t===c.prefix))continue;l=!0;let d=c.star?t.slice(c.prefix.length):"",f=!1;for(let u of c.targets){let m=c.star?u.replace(/\*/,d):u,p=Se($.join(a.baseUrl,m)),g=s(p);if(g)return{kind:"resolved",target:g};let y=p.includes("/")?$.dirname(p):"";(n.dirSet.has(y)||n.fileSet.has(p))&&(f=!0)}o=f?{kind:"dangling",reason:"alias-unresolved"}:{kind:"external"};break}if(l)break}for(let a of n.workspacePackages){if(t!==a.name&&!t.startsWith(a.name+"/"))continue;let l=t.slice(a.name.length).replace(/^\//,""),c=u=>{for(let m of[u,...Jp(u)]){let p=s(Se($.join(a.dir,m)));if(p)return p}},d=l?"./"+l:".";for(let u of a.exportEntries){let m;if(u.star){let p=u.key.indexOf("*"),g=u.key.slice(0,p),y=u.key.slice(p+1);if(!d.startsWith(g)||!d.endsWith(y)||d.length{let a=o?o.replace(/\./g,"/"):"",l=Se($.join(s,a));return ft(n,[l+".py",l+".pyi",$.join(l,"__init__.py")])};if(t.startsWith(".")){let s=/^\.+/.exec(t)[0].length,o=t.slice(s),l=e.includes("/")?$.dirname(e):"";for(let d=1;d{let l=Se(a).replace(/^\.$/,""),c=(n.filesByDir.get(l)??[]).filter(d=>d.endsWith(".go")).sort();return c.length?{kind:"resolved",target:c[0]}:{kind:"dangling",reason:"missing-package"}},s=n.goModules.find(a=>!a.dir||e===a.dir||e.startsWith(a.dir+"/"));if(s)for(let a of s.replaces){if(t!==a.from&&!t.startsWith(a.from+"/"))continue;let l=t.slice(a.from.length).replace(/^\//,"");return r($.join(a.toDir,l))}let o=s?[s,...n.goModules.filter(a=>a!==s)]:n.goModules;for(let a of o){if(t!==a.module&&!t.startsWith(a.module+"/"))continue;let l=t.slice(a.module.length).replace(/^\//,"");return r($.join(a.dir,l))}return{kind:"external"}}function rg(e,t,n){if(!n.rustCrates.length)return{kind:"external"};let r=(_,E)=>ft(n,[$.join(_,E+".rs"),$.join(_,E,"mod.rs")]),s=(_,E)=>{for(let b=E.length;b>=1;b--){let x=Se($.join(_,...E.slice(0,b-1))),v=r(x,E[b-1]);if(v)return v}},o=e.includes("/")?$.dirname(e):"",a=e.slice(e.lastIndexOf("/")+1).replace(/\.rs$/,""),l=a==="mod"||a==="lib"||a==="main",c=l?o:$.join(o,a);if(t.startsWith("mod ")){let _=t.slice(4),E=r(c,_)??(l?void 0:r(o,_));return E?{kind:"resolved",target:E}:{kind:"dangling",reason:"missing-module"}}let d=t.split("::").map(_=>_.trim()).filter(Boolean);if(!d.length)return{kind:"external"};let f=d[0],u=n.rustCrates.find(_=>!_.dir||e===_.dir||e.startsWith(_.dir+"/")),m,p=[];if(f==="crate"&&u)m=u.srcDir,p=d.slice(1);else if(f==="self")m=c,p=d.slice(1);else if(f==="super"){let _=l?o.includes("/")?$.dirname(o):"":o,E=1;for(;EE.name===f);if(_){let E=s(_.srcDir,d.slice(1));if(E)return{kind:"resolved",target:E};if(_.rootFile)return{kind:"resolved",target:_.rootFile}}return{kind:"external"}}if(!p.length)return{kind:"external"};let g=s(m,p);if(g)return{kind:"resolved",target:g};if(u&&m===u.srcDir&&u.rootFile)return{kind:"resolved",target:u.rootFile};let y=m.includes("/")?$.dirname(m):"",h=m.slice(m.lastIndexOf("/")+1),S=h?r(y,h):void 0;return S&&S!==e?{kind:"resolved",target:S}:{kind:"external"}}function sg(e,t){if(!t.javaRoots.length)return{kind:"external"};let n=o=>{for(let a of t.javaRoots){let l=Se($.join(a,o));if(l.endsWith("/*")||l==="*"){let c=l==="*"?"":l.slice(0,-2),d=(t.filesByDir.get(c)??[]).filter(f=>f.endsWith(".java")).sort();if(d.length)return d[0];continue}if(t.fileSet.has(l+".java"))return l+".java"}},r=e.replace(/\./g,"/"),s=n(r);if(!s&&!e.endsWith(".*")){let o=r.split("/");for(let a=o.length-1;a>=2&&!s;a--)s=n(o.slice(0,a).join("/"))}return s?{kind:"resolved",target:s}:{kind:"external"}}function ig(e,t,n){let r=e.includes("/")?$.dirname(e):"",s=ft(n,[$.join(r,t),...n.cIncludeRoots.map(o=>$.join(o,t))]);return s?{kind:"resolved",target:s}:{kind:"dangling",reason:"missing-include"}}function og(e,t,n){if(t.startsWith(".")){let r=e.includes("/")?$.dirname(e):"",s=Se($.join(r,t)),o=ft(n,[s+".rb",$.join(s,"index.rb")]);return o?{kind:"resolved",target:o}:{kind:"dangling",reason:"missing-module"}}for(let r of n.rubyLibRoots){let s=ft(n,[$.join(r,t+".rb")]);if(s)return{kind:"resolved",target:s}}return{kind:"external"}}function ag(e,t,n){if(t.startsWith(".")){let s=e.includes("/")?$.dirname(e):"",o=Se($.join(s,t)),a=ft(n,[o,o+".php"]);return a?{kind:"resolved",target:a}:{kind:"dangling",reason:"missing-module"}}let r=t.replace(/^\\+/,"");for(let{prefix:s,dir:o}of n.phpPsr4){if(s&&r!==s&&!r.startsWith(s+"\\"))continue;let a=s?r.slice(s.length).replace(/^\\+/,""):r,l=ft(n,[$.join(o,a.replace(/\\/g,"/"))+".php"]);if(l)return{kind:"resolved",target:l}}return{kind:"external"}}function lg(e,t){let n=t.csharpNamespaces.get(e);if(n?.length)return{kind:"resolved",target:n[0]};let r;for(let[s,o]of t.csharpNamespaces)if(s===e||s.startsWith(e+".")){let a=o[0];(r===void 0||M(a,r)<0)&&(r=a)}return r?{kind:"resolved",target:r}:{kind:"external"}}function or(e,t,n,r){let s=n.lastIndexOf(".");return s!==-1&&Wp.has(n.slice(s).toLowerCase().replace(/[?#].*$/,""))?{kind:"external"}:zp.has(t)||Hp.has(t)?eg(e,n,r):qp.has(t)?tg(e,n,r):t===".go"?ng(e,n,r):t===".rs"?rg(e,n,r):t===".java"?sg(n,r):Gp.has(t)?ig(e,n,r):t===".rb"||t===".rake"?og(e,n,r):t===".php"?ag(e,n,r):t===".cs"?lg(n,r):{kind:"external"}}var Wp,Up,Bp,zp,Hp,qp,Gp,Vp,jo,Zp,Ps=F(()=>{"use strict";k();oe();oe();Ae();Y();Wp=new Set([".svg",".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".icns",".pdf",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".wav",".flac",".ogg",".map"]),Up=["",".ts",".tsx",".d.ts",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".svelte",".astro",".html",".htm"],Bp=["index.ts","index.tsx","index.js","index.jsx","index.mjs","index.cjs"],zp=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),Hp=new Set([".vue",".svelte",".astro",".html",".htm"]),qp=new Set([".py",".pyi"]),Gp=new Set([".c",".h",".cc",".cpp",".cxx",".hpp",".hh"]),Vp=new Set(["dist","build","lib","out","output","esm","cjs","umd"]);jo=["source","ts","import","module","require","node","default"],Zp=8});function Ls(e){return fg.test(e.split("/").pop())}function mg(e){return e.includes("/")?$.dirname(e):$s}function od(e){return e===$s?0:dg.test(e)||ug.test(e)?2:cg.test(e)?0:null}function pg(e,t){let n=od(e);return n!==null?n:t.every(r=>r.kind==="doc"||r.kind==="config"||Ls(r.rel))?2:1}function gg(e,t){let n=t.find(a=>/^(readme|index)\.(md|mdx)$/i.test(a.rel.split("/").pop()));if(n?.summary)return n.summary;if(n?.title)return n.title;let r=t.filter(a=>a.summary).sort((a,l)=>(l.summary?.length??0)-(a.summary?.length??0));if(r[0]?.summary)return r[0].summary;let s=[...new Set(t.map(a=>a.lang))].filter(a=>a!=="other"),o=e===$s?"the repository root":`\`${e}/\``;return`${t.length} file(s) in ${o}${s.length?` (${s.slice(0,3).join(", ")})`:""}.`}function Ho(e){let t=new Map;for(let c of e.files){let d=mg(c.rel),f=t.get(d);f||t.set(d,f=[]),f.push(c)}let n=[...t.keys()].sort(M),r=new Map,s=new Map;for(let c of n){let d=c===$s?"root":Pi(c);r.set(c,d),s.set(d,(s.get(d)??0)+1)}let o=c=>{let d=r.get(c);return d&&s.get(d)===1?d:`${d||"module"}-${Me(c).slice(0,8)}`},a=[],l=new Map;for(let c of n){let d=t.get(c).slice().sort((m,p)=>M(m.rel,p.rel)),f=o(c),u={slug:f,path:c,title:c,tier:pg(c,d),members:d.map(m=>m.rel),summary:gg(c,d)};a.push(u);for(let m of d)l.set(m.rel,f)}return a.sort((c,d)=>M(c.slug,d.slug)),{modules:a,moduleOf:l}}var $s,cg,dg,ug,fg,Ds=F(()=>{"use strict";k();oe();Ce();At();Y();$s="(root)",cg=/(^|\/)(types?|util|utils|lib|libs|common|core|config|configs|constants|shared|helpers|internal)$/i,dg=/(^|\/)(tests?|__tests?__|__mocks?__|__snapshots?__|spec|specs|e2e|examples?|example|benchmark|benchmarks|fixtures?|docs?|documentation|\.github)(\/|$)/i,ug=/(^|\/)(scripts?|bin|\.storybook)$/i,fg=/\.(test|spec|e2e|stories|story)\.[cm]?[jt]sx?$/i});function st(e){return e==="typescript"||e==="javascript"?"js":e==="c"||e==="cpp"?"c":e}function hg(e,t){let n=e.split("/"),r=t.split("/"),s=0;for(;sr?(r=a,n=o,s=!1):a===r&&(s=!0)}return s?void 0:n}function qo(e,t){let n=new Map,r=new Set;for(let o of e.files)for(let a of o.symbols){if(!a.exported||_g.has(a.kind))continue;let l=`${a.name} ${a.file}`;if(r.has(l))continue;r.add(l);let c=n.get(a.name);c||n.set(a.name,c=[]),c.push({file:a.file,lang:a.lang})}let s=new Map;for(let o of e.files){if(!o.calls?.length)continue;let a=st(o.lang),l=new Set(o.symbols.map(d=>d.name)),c=new Map;for(let d of o.calls)c.set(d.name,(c.get(d.name)??0)+1);for(let[d,f]of c){if(l.has(d))continue;let u=(n.get(d)??[]).filter(S=>st(S.lang)===a&&S.file!==o.rel);if(!u.length)continue;let m=u.filter(S=>t.has(`${o.rel}|${S.file}`)),p,g;if(a==="js"){if(!m.length)continue;p=rt(o.rel,m),g="extracted"}else m.length?(p=rt(o.rel,m),g="extracted"):(p=rt(o.rel,u),g="inferred");if(!p)continue;let y=`${o.rel}|${p.file}`,h=s.get(y);h?(h.weight+=f,g==="extracted"&&(h.confidence="extracted")):s.set(y,{from:o.rel,to:p.file,weight:f,confidence:g})}}return[...s.values()].map(o=>({from:o.from,to:o.to,kind:"call",weight:Math.min(o.weight,5),confidence:o.confidence})).sort((o,a)=>M(o.from,a.from)||M(o.to,a.to))}var _g,Sn=F(()=>{"use strict";k();Y();_g=new Set(["reexport","reexport-all","default"])});function ad(e){let t=new Map,n=new Set;for(let r of e.files)for(let s of r.symbols){if(!bg.has(s.kind))continue;let o=`${s.name} ${s.file}`;if(n.has(o))continue;n.add(o);let a=t.get(s.name);a||t.set(s.name,a=[]),a.push({name:s.name,file:s.file,kind:s.kind,lang:s.lang,line:s.line})}return t}function ar(e,t){let n=ad(e),r=[];for(let s of e.files){if(!s.relations?.length)continue;let o=st(s.lang);for(let a of s.relations){let l=(n.get(a.to)??[]).filter(m=>st(m.lang)===o);if(!l.length)continue;let c=l.filter(m=>t.has(`${s.rel}|${m.file}`)||m.file===s.rel),d=c.length?c:l,f=rt(s.rel,d.map(m=>({file:m.file,lang:m.lang})));if(!f)continue;let u=d.find(m=>m.file===f.file);r.push({kind:yg.has(u.kind)?"implements":a.kind,from:a.from,fromFile:s.rel,fromLine:a.line,to:u.name,toFile:u.file,toKind:u.kind})}}return r.sort((s,o)=>M(s.fromFile,o.fromFile)||M(s.from,o.from)||M(s.kind,o.kind)||M(s.to,o.to))}function Go(e,t){let n=new Map;for(let r of ar(e,t)){if(r.toFile===r.fromFile)continue;let s=`${r.fromFile}${je}${r.toFile}${je}${r.kind}`,o=n.get(s);o?o.weight=Math.min(o.weight+1,5):n.set(s,{from:r.fromFile,to:r.toFile,kind:r.kind,weight:1})}return[...n.values()].sort((r,s)=>M(r.from,s.from)||M(r.to,s.to)||M(r.kind,s.kind))}function kn(e,t){let n=ad(e),r=ar(e,t),s=new Map,o=(u,m)=>`${u}${je}${m}`;for(let u of n.values())for(let m of u)s.set(o(m.name,m.file),{name:m.name,file:m.file,line:m.line,kind:m.kind,extends:[],implements:[],extendedBy:[],implementedBy:[],unresolved:[]});let a=u=>({name:u.name,file:u.file,line:u.line,kind:u.kind});for(let u of r){let m=s.get(o(u.from,u.fromFile)),p=s.get(o(u.to,u.toFile));p&&(m?((u.kind==="extends"?m.extends:m.implements).push(a(p)),(u.kind==="extends"?p.extendedBy:p.implementedBy).push(a(m))):(u.kind==="extends"?p.extendedBy:p.implementedBy).push({name:u.from,file:u.fromFile,line:u.fromLine,kind:"unknown"}))}let l=new Set(r.map(u=>`${u.fromFile}${je}${u.from}${je}${u.kind}${je}${u.to}`));for(let u of e.files)for(let m of u.relations??[]){if(l.has(`${u.rel}${je}${m.from}${je}${m.kind}${je}${m.to}`))continue;let p=m.kind==="extends"?"implements":"extends";l.has(`${u.rel}${je}${m.from}${je}${p}${je}${m.to}`)||s.get(o(m.from,u.rel))?.unresolved.push({kind:m.kind,to:m.to})}let c=(u,m)=>M(u.name,m.name)||M(u.file,m.file),d=new Map,f=[...s.keys()].sort(M);for(let u of f){let m=s.get(u);m.extends.sort(c),m.implements.sort(c),m.extendedBy.sort(c),m.implementedBy.sort(c),m.unresolved.sort((p,g)=>M(p.kind,g.kind)||M(p.to,g.to)),d.has(m.name)?d.set(`${m.name}@${m.file}`,m):d.set(m.name,m)}return d}function lr(e,t){let n=e.get(t);if(!n)return[];let r=new Set([`${n.name}${je}${n.file}`]),s=[],o=[n];for(;o.length;){let a=[];for(let l of o)for(let c of[...l.implementedBy,...l.extendedBy]){let d=`${c.name}${je}${c.file}`;if(r.has(d))continue;r.add(d),s.push(c);let f=e.get(c.name)??e.get(`${c.name}@${c.file}`);f&&f.file===c.file&&a.push(f)}o=a}return s.sort((a,l)=>M(a.name,l.name)||M(a.file,l.file))}function wg(e,t){return e.get(t)}var je,yg,bg,Xt=F(()=>{"use strict";k();Sn();Y();je="\0",yg=new Set(["interface","trait","protocol"]),bg=new Set(["class","interface","trait","struct","type","enum","record","object","protocol","module","mod","union","annotation"])});function Vo(e){let t=En(e),n=new Map;if(!t.size)return n;let r=(s,o)=>{let a=n.get(s);a||n.set(s,a=new Set),a.add(o)};for(let s of e.files)if(s.kind==="code"&&s.idents)for(let o of s.idents){let a=t.get(o);a&&a!==s.rel&&r(o,s.rel)}else if(s.kind==="doc"){let o=e.docText.get(s.rel);if(!o)continue;for(let a of o.split(/[^A-Za-z0-9_]+/)){let l=t.get(a);l&&l!==s.rel&&r(a,s.rel)}}return n}function Jo(e,t=new Map,n=5){let r=new Map;for(let a of e.files)for(let l of a.symbols){let c=r.get(l.name);c||r.set(l.name,c=[]),c.push({file:l.file,line:l.line,...l.endLine!==void 0?{endLine:l.endLine}:{},kind:l.kind,exported:l.exported,lang:l.lang,...l.parent?{parent:l.parent}:{}})}let s={};for(let a of[...r.keys()].sort(M))s[a]=r.get(a).slice().sort((l,c)=>M(l.file,c.file)||l.line-c.line||M(l.kind,c.kind));let o={};for(let a of[...t.keys()].sort(M)){let l=[...t.get(a)].sort(M);l.length&&(o[a]=l)}return{schemaVersion:n,defs:s,refs:o}}function js(e){return JSON.stringify(e,null,2)+` -`}var cr=F(()=>{"use strict";k();Xe();Y();mt()});function dr(e){return new Set(Qt(e))}function Zt(e,t,n={}){let r=t??Qt(e),s=n.recall===!0,o=new Map;for(let m of e.files){let p=new Set;for(let g of m.symbols){if(!g.exported||Ws.has(g.kind)||p.has(g.name))continue;p.add(g.name);let y=o.get(g.name);y||o.set(g.name,y=[]),y.push(g)}}let a=new Map;for(let[m,p]of o){let g=new Map;for(let y of p){let h=st(y.lang),S=g.get(h);S||g.set(h,S=[]),S.push(y)}a.set(m,g)}let l=new Map;for(let m of e.files){let p=new Map;for(let g of m.symbols)!Ws.has(g.kind)&&!p.has(g.name)&&p.set(g.name,g);l.set(m.rel,p)}let c=new Map,d=(m,p)=>{let g=c.get(m.name+"\0"+m.file);g||c.set(m.name+"\0"+m.file,g={def:m,callers:[]}),g.callers.push(p)};for(let m of e.files){if(!m.calls?.length)continue;let p=st(m.lang),g=l.get(m.rel);for(let y of m.calls){let h=g.get(y.name);if(h){h.line!==y.line&&d(h,s?{file:m.rel,line:y.line,confidence:"corroborated"}:{file:m.rel,line:y.line});continue}let S=(a.get(y.name)?.get(p)??[]).filter(x=>x.file!==m.rel);if(!S.length)continue;let _=S.filter(x=>r.has(`${m.rel}|${x.file}`)),E=p==="js"?_.length?rt(m.rel,_):s&&S.length===1?S[0]:void 0:_.length?rt(m.rel,_):rt(m.rel,S);if(!E)continue;d(E,s?{file:m.rel,line:y.line,confidence:_.length?"corroborated":"unique-name"}:{file:m.rel,line:y.line})}}let f=new Map,u=[...c.keys()].sort(M);for(let m of u){let{def:p,callers:g}=c.get(m);g.sort((y,h)=>M(y.file,h.file)||y.line-h.line),f.has(p.name)?f.set(`${p.name}@${p.file}`,{def:p,callers:g}):f.set(p.name,{def:p,callers:g})}return f}function xg(e,t,n){let r=e.files.find(s=>s.rel===t);if(r?.symbols.length)return Us(r.symbols,n)}function Us(e,t){let n;for(let r of e)Ws.has(r.kind)||r.line>t||r.endLine!==void 0&&t>r.endLine||(!n||r.line>n.line||r.line===n.line&&(r.endLine??1/0)<=(n.endLine??1/0))&&(n=r);return n}function Sg(e){let t=new Map;for(let r of e.files){if(!r.calls?.length)continue;let s=r.symbols.filter(o=>!Ws.has(o.kind));for(let o of r.calls){let a={file:r.rel,line:o.line};o.receiver!==void 0&&(a.receiver=o.receiver);let l=Us(s,o.line);l&&(a.enclosingSymbol=l);let c=t.get(o.name);c||t.set(o.name,c=[]),c.push(a)}}let n=new Map;for(let r of[...t.keys()].sort(M)){let s=t.get(r);s.sort((o,a)=>M(o.file,a.file)||o.line-a.line),n.set(r,s)}return n}var Ws,Yt=F(()=>{"use strict";k();Sn();mt();Y();Ws=new Set(["reexport","reexport-all","default"])});function en(e){return e.parent?`${e.file}#${e.parent}/${e.name}`:`${e.file}#${e.name}`}function Eg(e){return{id:en(e),name:e.name,kind:e.kind,file:e.file,line:e.line,...e.endLine!==void 0?{endLine:e.endLine}:{},exported:e.exported,...e.doc?{doc:e.doc}:{},...e.signature?{signature:e.signature}:{}}}function ur(e,t){let n=new Map,r=new Map,s=new Map,o=new Set;for(let p of e.files){let g=[];for(let y of p.symbols){if(kg.has(y.kind)||(g.push(y),n.set(en(y),Eg(y)),!y.exported))continue;let h=`${y.name} ${y.file}`;if(o.has(h))continue;o.add(h);let S=s.get(y.name);S||s.set(y.name,S=[]),S.push(y)}r.set(p.rel,g)}let a=new Map,l=(p,g,y)=>{if(p===g)return;let h=`${p}${Bs}${g}${Bs}${y}`,S=a.get(h);S?S.weight+=1:a.set(h,{from:p,to:g,kind:y,weight:1})};for(let p of e.files){if(!p.calls?.length)continue;let g=st(p.lang),y=r.get(p.rel)??[],h=new Map;for(let S of y)h.has(S.name)||h.set(S.name,S);for(let S of p.calls){let _=Us(y,S.line);if(!_)continue;let E=h.get(S.name);if(E){E.line!==S.line&&l(en(_),en(E),"calls");continue}let b=(s.get(S.name)??[]).filter(N=>st(N.lang)===g&&N.file!==p.rel);if(!b.length)continue;let x=b.filter(N=>t.has(`${p.rel}|${N.file}`)),v=x.length?x:g==="js"?[]:b;if(!v.length)continue;let A=rt(p.rel,v.map(N=>({file:N.file,lang:N.lang})));if(!A)continue;let O=v.find(N=>N.file===A.file);l(en(_),en(O),"calls")}}let c=new Map;for(let p of n.values())c.set(`${p.name} ${p.file}`,p.id);for(let p of ar(e,t)){let g=c.get(`${p.from} ${p.fromFile}`),y=c.get(`${p.to} ${p.toFile}`);g&&y&&l(g,y,p.kind)}let d=[...a.values()].sort((p,g)=>M(p.from,g.from)||M(p.kind,g.kind)||M(p.to,g.to)),f=new Map,u=new Map;for(let p of d)(f.get(p.from)??f.set(p.from,[]).get(p.from)).push(p),(u.get(p.to)??u.set(p.to,[]).get(p.to)).push(p);let m=new Map;for(let p of[...n.keys()].sort(M)){let g=n.get(p);(m.get(g.name)??m.set(g.name,[]).get(g.name)).push(p)}return{nodes:n,edges:d,out:f,in:u,byName:m}}function fr(e,t,n={}){let r=Math.max(1,Math.min(n.depth??2,vg)),s=n.direction??"both",o=e.nodes.has(t)?[t]:e.byName.get(t)??[...e.nodes.keys()].filter(p=>p.endsWith(`#${t}`)),a=o.map(p=>e.nodes.get(p)).filter(Boolean);if(!a.length)return{root:[],nodes:[],edges:[]};let l=new Map;for(let p of o)l.set(p,0);let c=new Map,d=[...o],f=!1;for(let p=1;p<=r&&d.length;p++){let g=[];for(let y of d){let h=(S,_)=>{for(let E of S??[]){c.set(`${E.from}${Bs}${E.to}${Bs}${E.kind}`,E);let b=_(E);if(!l.has(b)){if(l.size>=Rg){f=!0;continue}l.set(b,p),g.push(b)}}};s!=="in"&&h(e.out.get(y),S=>S.to),s!=="out"&&h(e.in.get(y),S=>S.from)}d=g}let u=[...l.entries()].map(([p,g])=>({...e.nodes.get(p),depth:g})).sort((p,g)=>p.depth-g.depth||M(p.file,g.file)||M(p.name,g.name)),m=[...c.values()].filter(p=>l.has(p.from)&&l.has(p.to)).sort((p,g)=>M(p.from,g.from)||M(p.kind,g.kind)||M(p.to,g.to));return{root:a,nodes:u,edges:m,...f?{truncated:!0}:{}}}var Bs,kg,vg,Rg,mr=F(()=>{"use strict";k();Sn();Yt();Xt();Y();Bs="\0",kg=new Set(["reexport","reexport-all","default"]);vg=5,Rg=400});function $t(e){if(Cg.test(e)||Ls(e))return!0;let t=e.split("/").pop();return Mg.some(n=>n.test(t))}function pr(e){let t=new Set,n=new Map;for(let a of e.files)n.set(a.rel,a.module),a.fileKind==="code"&&$t(a.rel)&&t.add(a.rel);let r=new Map,s=new Map;for(let a of e.fileEdges){if(a.dangling||a.kind!=="import"&&a.kind!=="use"&&a.kind!=="call"||!t.has(a.from)||t.has(a.to))continue;let l=r.get(a.to);l||r.set(a.to,l=new Set),l.add(a.from);let c=n.get(a.to);if(c!==void 0){let d=s.get(c);d||s.set(c,d=new Set),d.add(a.from)}}let o=a=>{let l=new Map;for(let c of[...a.keys()].sort(M))l.set(c,[...a.get(c)].sort(M));return l};return{testFiles:t,testedByFile:o(r),testedByModule:o(s)}}function Ag(e,t){let n=e.modules.find(r=>r.slug===t);return n?.testedBy?n.testedBy:pr(e).testedByModule.get(t)??[]}function Tg(e){let t=pr(e),n=new Map;for(let r of e.files)r.fileKind!=="code"||t.testFiles.has(r.rel)||n.set(r.module,(n.get(r.module)??0)+1);return e.modules.filter(r=>r.tier<=1&&r.symbols>0&&(n.get(r.slug)??0)>0&&!t.testedByModule.has(r.slug))}var Mg,Cg,vn=F(()=>{"use strict";k();Ds();Y();Mg=[/^test_.*\.py$/i,/_test\.py$/i,/_test\.go$/,/(Test|Tests|IT)\.java$/,/(Test|Tests)\.kt$/,/_spec\.rb$/,/_test\.rb$/,/Test\.php$/,/(Test|Tests)\.cs$/,/_test\.exs$/],Cg=/(^|\/)(tests?|__tests?__|spec|specs|e2e)(\/|$)/i});function Rn(e,t,n){let r=e.fields[t];for(let s of ht(n))r.tf.set(s,(r.tf.get(s)??0)+1),r.len++,e.all.add(s)}function jg(){let e={};for(let t of zs)e[t]={tf:new Map,len:0};return e}function Hs(e){let t=[];for(let n of e.files){let r={file:n.rel,fields:jg(),all:new Set,symbols:[],decls:[],exactNames:new Set,isTest:$t(n.rel)},s=new Set;for(let o of n.symbols)Rn(r,"name",o.name),o.doc&&Rn(r,"doc",o.doc),r.exactNames.add(_t(o.name).toLowerCase()),s.has(o.name)||(s.add(o.name),r.symbols.push(o.name),r.decls.push({name:o.name,kind:o.kind,line:o.line}));for(let o of n.rel.split("/"))Rn(r,"path",o);for(let o of n.headings)Rn(r,"heading",o);n.summary&&Rn(r,"summary",n.summary);for(let o of n.terms??[])Rn(r,"body",o);t.push(r)}return t}function fd(e){let t=`^^${e}$$`,n=new Set;for(let r=0;r+3<=t.length;r++)n.add(t.slice(r,r+3));return n}function Wg(e,t){if(!e.size||!t.size)return 0;let n=0;for(let r of e)t.has(r)&&n++;return 2*n/(e.size+t.size)}function md(e){let t=new Set,n=new Map;for(let r of e)for(let s of r.all){if(t.has(s))continue;t.add(s);let o=Li(s);if(o===s)continue;let a=n.get(o);a||n.set(o,a=[]),a.push(s)}for(let r of n.values())r.sort(M);return n}function pd(e){let t=new Map;for(let n of e)for(let r of n.all)t.has(r)||t.set(r,fd(r));return t}function Lt(e,t,n={}){return gd(e,t,n).results}function tn(e,t,n={}){return gd(e,t,n)}function dd(e,t,n){return{results:[],explain:{query:e,terms:[],droppedStopwords:ss(e),unresolvedTerms:[],verdict:t,note:n,bridgedOnlyResults:0,resultCount:0}}}function gd(e,t,n={}){let r=[],s=new Set;for(let _ of rs(t))for(let E of ht(_))s.has(E)||(s.add(E),r.push(E));if(!r.length){let _=ss(t);return dd(t,"none",_.length?`Nothing was searched for: every token in this query (${_.join(", ")}) is a stopword or too short to index. Search with the identifiers or domain words you are actually looking for.`:"Nothing was searched for: the query carried no indexable token.")}let o=r.some(_=>Dg.test(_)),a=_d(e),l=a.length;if(!l)return dd(t,"none","This index contains no files.");let c={};for(let _ of zs){let E=0;for(let b of a)E+=b.fields[_].len;c[_]=E/l||1}let d=new Map;for(let _ of r){let E=0;for(let b of a)b.all.has(_)&&E++;d.set(_,E)}let f=n.fuzzy??!0,u=new Map;if(f){let _=r.filter(E=>d.get(E)===0);if(_.length){let E=bd(e),b=[];for(let x of _){let v=(E.get(Li(x))??[]).filter(A=>A!==x);v.length?u.set(x,v.slice(0,cd).map(A=>({term:A,dice:ud}))):b.push(x)}if(b.length){let x=hd(e);for(let v of b){let A=fd(v),O=[];for(let[N,U]of x){let le=Wg(A,U);le>=Og&&O.push({term:N,dice:le})}O.sort((N,U)=>U.dice-N.dice||M(N.term,U.term)),u.set(v,O.slice(0,cd))}}}}let m=new Map,p=_=>{let E=d.get(_)??m.get(_);if(E!==void 0)return E;let b=0;for(let x of a)x.all.has(_)&&b++;return m.set(_,b),b},g=_=>Math.log(1+(l-_+.5)/(_+.5)),y=n.rank==="graph"?yd(e):void 0,h=[];for(let _ of a){let E=0,b=[],x=new Set,v=new Set,A=new Set,O=!1,N=z=>{let P=0;for(let j of zs){let B=_.fields[j],re=B.tf.get(z);if(!re)continue;x.add(j);let J=Pg[j];P+=Fg[j]*re/(1-J+J*B.len/c[j])}return P};for(let z of r){let P=N(z);if(P>0){b.push(z),v.add(z),_.exactNames.has(z)&&(O=!0),E+=g(d.get(z))*(P/(ld+P));continue}for(let j of u.get(z)??[]){let B=N(j.term);B&&(E+=g(p(j.term))*(B/(ld+B))*j.dice,v.add(j.term),A.add(z))}}if(!b.length&&!A.size)continue;O&&(E*=$g),_.isTest&&!o&&(E*=Lg),y&&(E*=1+.35*Math.log1p(y.get(_.file)??0));let le=_.decls.map(z=>{let P=new Set(ht(z.name)),j=0;for(let B of v)P.has(B)&&j++;return{decl:z,hits:j}}).filter(z=>z.hits>0).sort((z,P)=>P.hits-z.hits||M(z.decl.name,P.decl.name)).slice(0,Ng).map(z=>z.decl),V={file:_.file,score:Number(E.toFixed(4)),matchedTerms:b.sort(M),topSymbols:le.map(z=>z.name)};x.size&&(V.matchedFields=zs.filter(z=>x.has(z))),le.length&&(V.symbolHits=le,V.line=Math.min(...le.map(z=>z.line))),A.size&&(V.fuzzyTerms=[...A].sort(M)),b.length||(V.bridgedOnly=!0),h.push(V)}h.sort((_,E)=>E.score-_.score||M(_.file,E.file));let S=(n.exact?h.filter(_=>!_.bridgedOnly):h).slice(0,n.limit??Ig);return{results:S,explain:Ug(t,r,d,u,S)}}function Ug(e,t,n,r,s){let o=t.map(g=>{let y=n.get(g)??0,h=y===0?r.get(g)??[]:[];if(!h.length)return{term:g,df:y};let S=h[0].dice===ud?"stem":"trigram";return{term:g,df:y,bridge:{via:S,to:h.map(_=>_.term),dice:h[0].dice}}}),a=o.filter(g=>g.df===0&&!g.bridge).map(g=>g.term).sort(M),l=!/\s/.test(e.trim())&&t.length?{term:t[0],df:n.get(t[0])??0}:void 0,c=s.filter(g=>g.bridgedOnly).length,d=s.length>0&&c===s.length,f=l?.df===0,u=s.length?f||d?"weak":"match":"none",m={query:e,terms:o,droppedStopwords:ss(e),unresolvedTerms:a,...l?{wholeIdentifier:l}:{},verdict:u,bridgedOnlyResults:c,resultCount:s.length},p=Bg(m,f,d);return p&&(m.note=p),m}function Bg(e,t,n){let{verdict:r,wholeIdentifier:s,resultCount:o,terms:a}=e;if(r!=="match"){if(!o)return e.unresolvedTerms.length?`No file matches. ${e.unresolvedTerms.length===1?"The term":"The terms"} ${e.unresolvedTerms.join(", ")} appear nowhere in this index.`:"No file matches this query.";if(t&&s){let l=a.filter(u=>u.term!==s.term&&u.df>0).map(u=>u.term).join(", "),c=a.find(u=>u.term===s.term)?.bridge?.to??[],d=l?` The ${o} result${o===1?"":"s"} below match only its parts (${l}).`:"",f=c.length?` Closest indexed name${c.length===1?"":"s"}: ${c.join(", ")}.`:"";return`No file in this index defines or mentions "${s.term}".${d}${f} If you expected it here, check you are indexing the right branch or commit.`}if(n)return`Nothing matched verbatim. Every result below came from a near match: ${a.filter(d=>d.bridge).map(d=>`"${d.term}" \u2192 ${d.bridge.to.join(", ")}`).join("; ")}. Re-run with --exact to see only literal matches.`}}var ld,Ig,Ng,Og,cd,ud,zs,Fg,Pg,$g,Lg,Dg,Mn=F(()=>{"use strict";k();mt();Ce();vn();Y();ld=1.2,Ig=20,Ng=5,Og=.6,cd=3,ud=.9,zs=["name","path","heading","summary","doc","body"],Fg={name:3,path:2,heading:1.5,summary:1.5,doc:1.6,body:.7},Pg={name:.75,path:.75,heading:.75,summary:.75,doc:.75,body:.4},$g=1.35,Lg=.65,Dg=/^(test|tests|spec|specs|fixture|fixtures|mock|mocks|stub|stubs)$/});function gr(e,t,n=.85){let r=new Map,s=e.length;if(s===0)return r;let o=new Map(e.map((d,f)=>[d,f])),a=Array.from({length:s},()=>[]),l=new Array(s).fill(0);for(let d of t){if(d.dangling)continue;let f=o.get(d.from),u=o.get(d.to);f===void 0||u===void 0||f===u||(a[f].push([u,d.weight]),l[f]+=d.weight)}let c=new Array(s).fill(1/s);for(let d=0;d<100;d++){let f=0;for(let g=0;gr.set(d,c[f])),r}function wd(e,t){let n=new Map;for(let d of e)n.set(d,0);let r=e.length;if(r<3)return n;let s=new Map(e.map((d,f)=>[d,f])),o=Array.from({length:r},()=>new Set);for(let d of t){if(d.dangling)continue;let f=s.get(d.from),u=s.get(d.to);f===void 0||u===void 0||f===u||(o[f].add(u),o[u].add(f))}let a=o.map(d=>[...d].sort((f,u)=>f-u)),l=new Array(r).fill(0);for(let d=0;d[]),m=new Array(r).fill(0),p=new Array(r).fill(-1);m[d]=1,p[d]=0;let g=[d];for(let h=0;h=0;h--){let S=f[h];for(let _ of u[S])y[_]+=m[_]/m[S]*(1+y[S]);S!==d&&(l[S]+=y[S])}}let c=(r-1)*(r-2)/2;return e.forEach((d,f)=>n.set(d,l[f]/2/c)),n}function Ko(e){let t=[],n=e.modules.length;if(n>0){let s=e.modules.map(a=>a.id),o=gr(s,e.moduleEdges);for(let a of e.modules)a.pagerank=Number(((o.get(a.id)??0)*n).toFixed(4));if(n>3e3)t.push(`betweenness skipped (${n} modules > 3000)`);else{let a=wd(s,e.moduleEdges);for(let l of e.modules)l.betweenness=Number((a.get(l.id)??0).toFixed(6))}}let r=e.files.length;if(r>0){let s=e.files.map(a=>a.id),o=gr(s,e.fileEdges);for(let a of e.files)a.pagerank=Number(((o.get(a.id)??0)*r).toFixed(4))}return t}var qs=F(()=>{"use strict";k()});function Gs(e){return 1+(e.match(zg)??[]).length}function _r(e,t,n=50){let r=[];for(let s of e.files){if(s.kind!=="code"||t&&s.rel!==t||!s.symbols.length)continue;let o=G(I(e.root,s.rel)).split(` +`||t[a]==="\r");)a++;if(t[a]==="}"||t[a]==="]")continue}r+=o}try{return JSON.parse(r)}catch{return}}function bg(e,t,n){let r=Se($.join(t,n)),s=n.endsWith(".json")?[r]:[r+".json",$.join(r,"tsconfig.json")];for(let o of s)if(e.has(o))return o}function _d(e,t,n,r,s){if(s.has(n))return;s.add(n);let o=Ho(q(I(e,n)));if(o===void 0){r.push(`unparseable ${n} \u2014 its path aliases were ignored`);return}let a=n.includes("/")?$.dirname(n):"",l={baseUrlDir:"",pathsDir:""},c=o.extends===void 0?[]:Array.isArray(o.extends)?o.extends:[o.extends];for(let f of c){if(typeof f!="string")continue;let u=bg(t,a,f);if(!u){/^\.\.?\//.test(f)&&r.push(`${n} extends "${f}" which is missing \u2014 its path aliases were ignored`);continue}let m=_d(e,t,u,r,s);m?.baseUrl!==void 0&&(l.baseUrl=m.baseUrl,l.baseUrlDir=m.baseUrlDir),m?.paths&&(l.paths=m.paths,l.pathsDir=m.pathsDir)}let d=o.compilerOptions;return d?.baseUrl!==void 0&&(l.baseUrl=d.baseUrl,l.baseUrlDir=a),d?.paths&&(l.paths=d.paths,l.pathsDir=a),l}function pd(e){let t=zo.indexOf(e);return t!==-1?t:e==="types"?zo.length+1:zo.length}function Go(e,t){if(!(t.length>=wg)){if(typeof e=="string")t.includes(e)||t.push(e);else if(Array.isArray(e))for(let n of e)Go(n,t);else if(e!==null&&typeof e=="object"){let n=Object.keys(e).sort((r,s)=>pd(r)-pd(s)||(rs?1:0));for(let r of n)Go(e[r],t)}}}function xg(e){if(e==null)return[];let t=[],n=(r,s)=>{let o=[];Go(s,o),o.length&&t.push({key:r,star:r.includes("*"),targets:o})};if(typeof e=="string"||Array.isArray(e))n(".",e);else if(typeof e=="object"){let r=Object.keys(e);if(r.every(s=>s==="."||s.startsWith("./")))for(let s of r)n(s,e[s]);else n(".",e)}return t.sort((r,s)=>Number(r.star)-Number(s.star)||s.key.length-r.key.length||(r.key{let o=/^\s*([^\s=]+)(?:\s+v\S+)?\s*=>\s*(\S+)(?:\s+v\S+)?\s*$/.exec(s);if(!o)return;let a=o[2];if(!/^\.\.?\//.test(a))return;let l=Se($.join(t,a));l.startsWith("..")||n.push({from:o[1],toDir:l})};for(let s of e.matchAll(/^[ \t]*replace[ \t]+([^(\r\n][^\r\n]*)$/gm))r(s[1]);for(let s of e.matchAll(/^[ \t]*replace[ \t]*\(([\s\S]*?)\)/gm))for(let o of s[1].split(/\r?\n/))r(o);return n}function qo(e){let t=new Set(e.files.map(y=>y.rel)),n=new Map,r=new Set;for(let y of e.files){let h=y.rel.includes("/")?$.dirname(y.rel):"",S=n.get(h);S||n.set(h,S=[]),S.push(y.rel);let _=h;for(;_&&!r.has(_);)r.add(_),_=_.includes("/")?$.dirname(_):""}let s=[],o=[];for(let y of t){let h=y.slice(y.lastIndexOf("/")+1);if(h!=="tsconfig.json"&&h!=="jsconfig.json"&&!(y==="tsconfig.base.json"))continue;let _=y.includes("/")?$.dirname(y):"",k=_d(e.root,t,y,s,new Set);if(!k?.paths)continue;let b=[];for(let[v,A]of Object.entries(k.paths)){if(!Array.isArray(A))continue;let F=v.endsWith("*");b.push({prefix:F?v.slice(0,-1):v,star:F,targets:A})}if(!b.length)continue;let w=k.baseUrl!==void 0?Se($.join(k.baseUrlDir,k.baseUrl)).replace(/^\.$/,""):k.pathsDir;o.push({dir:_,baseUrl:w,paths:b})}o.sort((y,h)=>h.dir.length-y.dir.length);let a=[];for(let y of t){if(y!=="go.mod"&&!y.endsWith("/go.mod"))continue;let h=q(I(e.root,y)),S=/^\s*module\s+(\S+)/m.exec(h);if(!S)continue;let _=y.includes("/")?$.dirname(y):"";a.push({module:S[1],dir:_,replaces:Sg(h,_)})}a.sort((y,h)=>h.dir.length-y.dir.length||(y.dirh.dir.length-y.dir.length||(y.dirtypeof _=="string");f.push({name:h.name,dir:y.includes("/")?$.dirname(y):"",exportEntries:xg(h.exports),mainCandidates:S})}f.sort((y,h)=>h.name.length-y.name.length);let u=new Set([""]);for(let y of r){let h=y.slice(y.lastIndexOf("/")+1);(h==="include"||h==="inc"||h==="src")&&u.add(y)}let m=new Set([""]);for(let y of r)y.slice(y.lastIndexOf("/")+1)==="lib"&&m.add(y);let p=[];for(let y of t){if(y!=="composer.json"&&!y.endsWith("/composer.json"))continue;let h=Ho(q(I(e.root,y)));if(!h){s.push(`unparseable ${y} \u2014 skipped for PHP PSR-4 resolution`);continue}let S=y.includes("/")?$.dirname(y):"";for(let _ of[h.autoload?.["psr-4"],h["autoload-dev"]?.["psr-4"]])if(_)for(let[k,b]of Object.entries(_))for(let w of Array.isArray(b)?b:[b])typeof w=="string"&&p.push({prefix:k.replace(/\\+$/,""),dir:Se($.join(S,w)).replace(/^\.$/,"")})}p.sort((y,h)=>h.prefix.length-y.prefix.length);let g=new Map;for(let y of e.files){if(y.ext!==".cs"||!y.pkg)continue;let h=g.get(y.pkg);h||g.set(y.pkg,h=[]),h.push(y.rel)}for(let y of g.values())y.sort(M);return{fileSet:t,dirSet:r,filesByDir:n,tsConfigs:o,goModules:a,rustCrates:l,javaRoots:[...c].sort(Bo),pyRoots:[...d],workspacePackages:f,cIncludeRoots:[...u].sort(Bo),rubyLibRoots:[...m].sort(Bo),phpPsr4:p,csharpNamespaces:g,warnings:s}}function mt(e,t){for(let n of t){let r=Se(n);if(r&&!r.startsWith("..")&&e.fileSet.has(r))return r}}function Vo(e,t,n){let r=t.split("#")[0].split("?")[0];if(!r)return{kind:"external"};if(r.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(r))return{kind:"external"};let s=e.includes("/")?$.dirname(e):"",o=Se($.join(s,r));if(o.startsWith(".."))return{kind:"dangling",reason:"escapes-repo-root"};let a=mt(n,[o,o+".md",o+".mdx",$.join(o,"README.md"),$.join(o,"readme.md"),$.join(o,"index.md"),$.join(o,"index.mdx")]);return a?{kind:"resolved",target:a}:n.dirSet.has(o)?{kind:"external"}:{kind:"dangling",reason:"missing-target"}}function kg(e,t,n){let r=a=>mt(n,[...dg.map(l=>a+l),...ug.map(l=>$.join(a,l))]),s=a=>{let l=r(a);if(l)return l;let c=a.replace(/\.(js|jsx|mjs|cjs)$/,"");return c!==a?r(c):void 0};if(t.startsWith(".")){let a=e.includes("/")?$.dirname(e):"",l=Se($.join(a,t));if(l.startsWith(".."))return{kind:"dangling",reason:"escapes-repo-root"};let c=s(l);return c?{kind:"resolved",target:c}:{kind:"dangling",reason:"missing-module"}}let o;for(let a of n.tsConfigs){if(a.dir&&e!==a.dir&&!e.startsWith(a.dir+"/"))continue;let l=!1;for(let c of a.paths){if(!(c.star?t.startsWith(c.prefix):t===c.prefix))continue;l=!0;let d=c.star?t.slice(c.prefix.length):"",f=!1;for(let u of c.targets){let m=c.star?u.replace(/\*/,d):u,p=Se($.join(a.baseUrl,m)),g=s(p);if(g)return{kind:"resolved",target:g};let y=p.includes("/")?$.dirname(p):"";(n.dirSet.has(y)||n.fileSet.has(p))&&(f=!0)}o=f?{kind:"dangling",reason:"alias-unresolved"}:{kind:"external"};break}if(l)break}for(let a of n.workspacePackages){if(t!==a.name&&!t.startsWith(a.name+"/"))continue;let l=t.slice(a.name.length).replace(/^\//,""),c=u=>{for(let m of[u,...hg(u)]){let p=s(Se($.join(a.dir,m)));if(p)return p}},d=l?"./"+l:".";for(let u of a.exportEntries){let m;if(u.star){let p=u.key.indexOf("*"),g=u.key.slice(0,p),y=u.key.slice(p+1);if(!d.startsWith(g)||!d.endsWith(y)||d.length{let a=o?o.replace(/\./g,"/"):"",l=Se($.join(s,a));return mt(n,[l+".py",l+".pyi",$.join(l,"__init__.py")])};if(t.startsWith(".")){let s=/^\.+/.exec(t)[0].length,o=t.slice(s),l=e.includes("/")?$.dirname(e):"";for(let d=1;d{let l=Se(a).replace(/^\.$/,""),c=gd(n,l,".go");return c.length?{kind:"resolved",target:c[0]}:{kind:"dangling",reason:"missing-package"}},s=n.goModules.find(a=>!a.dir||e===a.dir||e.startsWith(a.dir+"/"));if(s)for(let a of s.replaces){if(t!==a.from&&!t.startsWith(a.from+"/"))continue;let l=t.slice(a.from.length).replace(/^\//,"");return r($.join(a.toDir,l))}let o=s?[s,...n.goModules.filter(a=>a!==s)]:n.goModules;for(let a of o){if(t!==a.module&&!t.startsWith(a.module+"/"))continue;let l=t.slice(a.module.length).replace(/^\//,"");return r($.join(a.dir,l))}return{kind:"external"}}function Rg(e,t,n){if(!n.rustCrates.length)return{kind:"external"};let r=(_,k)=>mt(n,[$.join(_,k+".rs"),$.join(_,k,"mod.rs")]),s=(_,k)=>{for(let b=k.length;b>=1;b--){let w=Se($.join(_,...k.slice(0,b-1))),v=r(w,k[b-1]);if(v)return v}},o=e.includes("/")?$.dirname(e):"",a=e.slice(e.lastIndexOf("/")+1).replace(/\.rs$/,""),l=a==="mod"||a==="lib"||a==="main",c=l?o:$.join(o,a);if(t.startsWith("mod ")){let _=t.slice(4),k=r(c,_)??(l?void 0:r(o,_));return k?{kind:"resolved",target:k}:{kind:"dangling",reason:"missing-module"}}let d=t.split("::").map(_=>_.trim()).filter(Boolean);if(!d.length)return{kind:"external"};let f=d[0],u=n.rustCrates.find(_=>!_.dir||e===_.dir||e.startsWith(_.dir+"/")),m,p=[];if(f==="crate"&&u)m=u.srcDir,p=d.slice(1);else if(f==="self")m=c,p=d.slice(1);else if(f==="super"){let _=l?o.includes("/")?$.dirname(o):"":o,k=1;for(;kk.name===f);if(_){let k=s(_.srcDir,d.slice(1));if(k)return{kind:"resolved",target:k};if(_.rootFile)return{kind:"resolved",target:_.rootFile}}return{kind:"external"}}if(!p.length)return{kind:"external"};let g=s(m,p);if(g)return{kind:"resolved",target:g};if(u&&m===u.srcDir&&u.rootFile)return{kind:"resolved",target:u.rootFile};let y=m.includes("/")?$.dirname(m):"",h=m.slice(m.lastIndexOf("/")+1),S=h?r(y,h):void 0;return S&&S!==e?{kind:"resolved",target:S}:{kind:"external"}}function Mg(e,t){if(!t.javaRoots.length)return{kind:"external"};let n=o=>{for(let a of t.javaRoots){let l=Se($.join(a,o));if(l.endsWith("/*")||l==="*"){let c=l==="*"?"":l.slice(0,-2),d=gd(t,c,".java");if(d.length)return d[0];continue}if(t.fileSet.has(l+".java"))return l+".java"}},r=e.replace(/\./g,"/"),s=n(r);if(!s&&!e.endsWith(".*")){let o=r.split("/");for(let a=o.length-1;a>=2&&!s;a--)s=n(o.slice(0,a).join("/"))}return s?{kind:"resolved",target:s}:{kind:"external"}}function Cg(e,t,n){let r=e.includes("/")?$.dirname(e):"",s=mt(n,[$.join(r,t),...n.cIncludeRoots.map(o=>$.join(o,t))]);return s?{kind:"resolved",target:s}:{kind:"dangling",reason:"missing-include"}}function Ag(e,t,n){if(t.startsWith(".")){let r=e.includes("/")?$.dirname(e):"",s=Se($.join(r,t)),o=mt(n,[s+".rb",$.join(s,"index.rb")]);return o?{kind:"resolved",target:o}:{kind:"dangling",reason:"missing-module"}}for(let r of n.rubyLibRoots){let s=mt(n,[$.join(r,t+".rb")]);if(s)return{kind:"resolved",target:s}}return{kind:"external"}}function Tg(e,t,n){if(t.startsWith(".")){let s=e.includes("/")?$.dirname(e):"",o=Se($.join(s,t)),a=mt(n,[o,o+".php"]);return a?{kind:"resolved",target:a}:{kind:"dangling",reason:"missing-module"}}let r=t.replace(/^\\+/,"");for(let{prefix:s,dir:o}of n.phpPsr4){if(s&&r!==s&&!r.startsWith(s+"\\"))continue;let a=s?r.slice(s.length).replace(/^\\+/,""):r,l=mt(n,[$.join(o,a.replace(/\\/g,"/"))+".php"]);if(l)return{kind:"resolved",target:l}}return{kind:"external"}}function Ig(e,t){let n=t.csharpNamespaces.get(e);if(n?.length)return{kind:"resolved",target:n[0]};let r;for(let[s,o]of t.csharpNamespaces)if(s===e||s.startsWith(e+".")){let a=o[0];(r===void 0||M(a,r)<0)&&(r=a)}return r?{kind:"resolved",target:r}:{kind:"external"}}function lr(e,t,n,r){let s=n.lastIndexOf(".");if(s!==-1&&cg.has(n.slice(s).toLowerCase().replace(/[?#].*$/,"")))return{kind:"external"};if(fg.has(t)||mg.has(t)){let a=(e.includes("/")?$.dirname(e):"")+"\0"+n,l=r.jsMemo??=new Map,c=l.get(a);return c||l.set(a,c=kg(e,n,r)),{...c}}return pg.has(t)?Eg(e,n,r):t===".go"?vg(e,n,r):t===".rs"?Rg(e,n,r):t===".java"?Mg(n,r):gg.has(t)?Cg(e,n,r):t===".rb"||t===".rake"?Ag(e,n,r):t===".php"?Tg(e,n,r):t===".cs"?Ig(n,r):{kind:"external"}}var cg,dg,ug,fg,mg,pg,gg,_g,zo,wg,Ds=O(()=>{"use strict";E();ae();ae();Ne();Y();cg=new Set([".svg",".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".icns",".pdf",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".wav",".flac",".ogg",".map"]),dg=["",".ts",".tsx",".d.ts",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".svelte",".astro",".html",".htm"],ug=["index.ts","index.tsx","index.js","index.jsx","index.mjs","index.cjs"],fg=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),mg=new Set([".vue",".svelte",".astro",".html",".htm"]),pg=new Set([".py",".pyi"]),gg=new Set([".c",".h",".cc",".cpp",".cxx",".hpp",".hh"]),_g=new Set(["dist","build","lib","out","output","esm","cjs","umd"]);zo=["source","ts","import","module","require","node","default"],wg=8});function js(e){return Pg.test(e.split("/").pop())}function $g(e){return e.includes("/")?$.dirname(e):Ls}function hd(e){return e===Ls?0:Fg.test(e)||Og.test(e)?2:Ng.test(e)?0:null}function Dg(e,t){let n=hd(e);return n!==null?n:t.every(r=>r.kind==="doc"||r.kind==="config"||js(r.rel))?2:1}function Lg(e,t){let n=t.find(a=>/^(readme|index)\.(md|mdx)$/i.test(a.rel.split("/").pop()));if(n?.summary)return n.summary;if(n?.title)return n.title;let r=t.filter(a=>a.summary).sort((a,l)=>(l.summary?.length??0)-(a.summary?.length??0));if(r[0]?.summary)return r[0].summary;let s=[...new Set(t.map(a=>a.lang))].filter(a=>a!=="other"),o=e===Ls?"the repository root":`\`${e}/\``;return`${t.length} file(s) in ${o}${s.length?` (${s.slice(0,3).join(", ")})`:""}.`}function Jo(e){let t=new Map;for(let c of e.files){let d=$g(c.rel),f=t.get(d);f||t.set(d,f=[]),f.push(c)}let n=[...t.keys()].sort(M),r=new Map,s=new Map;for(let c of n){let d=c===Ls?"root":Li(c);r.set(c,d),s.set(d,(s.get(d)??0)+1)}let o=c=>{let d=r.get(c);return d&&s.get(d)===1?d:`${d||"module"}-${Ce(c).slice(0,8)}`},a=[],l=new Map;for(let c of n){let d=t.get(c).slice().sort((m,p)=>M(m.rel,p.rel)),f=o(c),u={slug:f,path:c,title:c,tier:Dg(c,d),members:d.map(m=>m.rel),summary:Lg(c,d)};a.push(u);for(let m of d)l.set(m.rel,f)}return a.sort((c,d)=>M(c.slug,d.slug)),{modules:a,moduleOf:l}}var Ls,Ng,Fg,Og,Pg,Ws=O(()=>{"use strict";E();ae();Ae();Tt();Y();Ls="(root)",Ng=/(^|\/)(types?|util|utils|lib|libs|common|core|config|configs|constants|shared|helpers|internal)$/i,Fg=/(^|\/)(tests?|__tests?__|__mocks?__|__snapshots?__|spec|specs|e2e|examples?|example|benchmark|benchmarks|fixtures?|docs?|documentation|\.github)(\/|$)/i,Og=/(^|\/)(scripts?|bin|\.storybook)$/i,Pg=/\.(test|spec|e2e|stories|story)\.[cm]?[jt]sx?$/i});function st(e){return e==="typescript"||e==="javascript"?"js":e==="c"||e==="cpp"?"c":e}function Wg(e,t){let n=e.split("/"),r=t.split("/"),s=0;for(;sr?(r=a,n=o,s=!1):a===r&&(s=!0)}return s?void 0:n}function Ko(e,t){let n=new Map,r=new Set;for(let o of e.files)for(let a of o.symbols){if(!a.exported||jg.has(a.kind))continue;let l=`${a.name} ${a.file}`;if(r.has(l))continue;r.add(l);let c=n.get(a.name);c||n.set(a.name,c=[]),c.push({file:a.file,lang:a.lang})}let s=new Map;for(let o of e.files){if(!o.calls?.length)continue;let a=st(o.lang),l=new Set(o.symbols.map(d=>d.name)),c=new Map;for(let d of o.calls)c.set(d.name,(c.get(d.name)??0)+1);for(let[d,f]of c){if(l.has(d))continue;let u=(n.get(d)??[]).filter(S=>st(S.lang)===a&&S.file!==o.rel);if(!u.length)continue;let m=u.filter(S=>t.has(`${o.rel}|${S.file}`)),p,g;if(a==="js"){if(!m.length)continue;p=rt(o.rel,m),g="extracted"}else m.length?(p=rt(o.rel,m),g="extracted"):(p=rt(o.rel,u),g="inferred");if(!p)continue;let y=`${o.rel}|${p.file}`,h=s.get(y);h?(h.weight+=f,g==="extracted"&&(h.confidence="extracted")):s.set(y,{from:o.rel,to:p.file,weight:f,confidence:g})}}return[...s.values()].map(o=>({from:o.from,to:o.to,kind:"call",weight:Math.min(o.weight,5),confidence:o.confidence})).sort((o,a)=>M(o.from,a.from)||M(o.to,a.to))}var jg,kn=O(()=>{"use strict";E();Y();jg=new Set(["reexport","reexport-all","default"])});function yd(e){let t=new Map,n=new Set;for(let r of e.files)for(let s of r.symbols){if(!Bg.has(s.kind))continue;let o=`${s.name} ${s.file}`;if(n.has(o))continue;n.add(o);let a=t.get(s.name);a||t.set(s.name,a=[]),a.push({name:s.name,file:s.file,kind:s.kind,lang:s.lang,line:s.line})}return t}function cr(e,t){let n=yd(e),r=[];for(let s of e.files){if(!s.relations?.length)continue;let o=st(s.lang);for(let a of s.relations){let l=(n.get(a.to)??[]).filter(m=>st(m.lang)===o);if(!l.length)continue;let c=l.filter(m=>t.has(`${s.rel}|${m.file}`)||m.file===s.rel),d=c.length?c:l,f=rt(s.rel,d.map(m=>({file:m.file,lang:m.lang})));if(!f)continue;let u=d.find(m=>m.file===f.file);r.push({kind:Ug.has(u.kind)?"implements":a.kind,from:a.from,fromFile:s.rel,fromLine:a.line,to:u.name,toFile:u.file,toKind:u.kind})}}return r.sort((s,o)=>M(s.fromFile,o.fromFile)||M(s.from,o.from)||M(s.kind,o.kind)||M(s.to,o.to))}function Xo(e,t){let n=new Map;for(let r of cr(e,t)){if(r.toFile===r.fromFile)continue;let s=`${r.fromFile}${We}${r.toFile}${We}${r.kind}`,o=n.get(s);o?o.weight=Math.min(o.weight+1,5):n.set(s,{from:r.fromFile,to:r.toFile,kind:r.kind,weight:1})}return[...n.values()].sort((r,s)=>M(r.from,s.from)||M(r.to,s.to)||M(r.kind,s.kind))}function En(e,t){let n=yd(e),r=cr(e,t),s=new Map,o=(u,m)=>`${u}${We}${m}`;for(let u of n.values())for(let m of u)s.set(o(m.name,m.file),{name:m.name,file:m.file,line:m.line,kind:m.kind,extends:[],implements:[],extendedBy:[],implementedBy:[],unresolved:[]});let a=u=>({name:u.name,file:u.file,line:u.line,kind:u.kind});for(let u of r){let m=s.get(o(u.from,u.fromFile)),p=s.get(o(u.to,u.toFile));p&&(m?((u.kind==="extends"?m.extends:m.implements).push(a(p)),(u.kind==="extends"?p.extendedBy:p.implementedBy).push(a(m))):(u.kind==="extends"?p.extendedBy:p.implementedBy).push({name:u.from,file:u.fromFile,line:u.fromLine,kind:"unknown"}))}let l=new Set(r.map(u=>`${u.fromFile}${We}${u.from}${We}${u.kind}${We}${u.to}`));for(let u of e.files)for(let m of u.relations??[]){if(l.has(`${u.rel}${We}${m.from}${We}${m.kind}${We}${m.to}`))continue;let p=m.kind==="extends"?"implements":"extends";l.has(`${u.rel}${We}${m.from}${We}${p}${We}${m.to}`)||s.get(o(m.from,u.rel))?.unresolved.push({kind:m.kind,to:m.to})}let c=(u,m)=>M(u.name,m.name)||M(u.file,m.file),d=new Map,f=[...s.keys()].sort(M);for(let u of f){let m=s.get(u);m.extends.sort(c),m.implements.sort(c),m.extendedBy.sort(c),m.implementedBy.sort(c),m.unresolved.sort((p,g)=>M(p.kind,g.kind)||M(p.to,g.to)),d.has(m.name)?d.set(`${m.name}@${m.file}`,m):d.set(m.name,m)}return d}function dr(e,t){let n=e.get(t);if(!n)return[];let r=new Set([`${n.name}${We}${n.file}`]),s=[],o=[n];for(;o.length;){let a=[];for(let l of o)for(let c of[...l.implementedBy,...l.extendedBy]){let d=`${c.name}${We}${c.file}`;if(r.has(d))continue;r.add(d),s.push(c);let f=e.get(c.name)??e.get(`${c.name}@${c.file}`);f&&f.file===c.file&&a.push(f)}o=a}return s.sort((a,l)=>M(a.name,l.name)||M(a.file,l.file))}function zg(e,t){return e.get(t)}var We,Ug,Bg,Xt=O(()=>{"use strict";E();kn();Y();We="\0",Ug=new Set(["interface","trait","protocol"]),Bg=new Set(["class","interface","trait","struct","type","enum","record","object","protocol","module","mod","union","annotation"])});function Zo(e){let t=Zt(e),n=new Map;if(!t.size)return n;let r=(o,a)=>{let l=n.get(o);l||n.set(o,l=new Set),l.add(a)},s=Bs(e);for(let o of e.files)if(o.kind==="code"&&o.idents)for(let a of o.idents){let l=t.get(a);l&&l!==o.rel&&r(a,o.rel)}else if(o.kind==="doc"){let a=s.get(o.rel);if(!a||!a.retained)continue;for(let l of a.counts.keys()){let c=t.get(l);c&&c!==o.rel&&r(l,o.rel)}}return n}function Yo(e,t=new Map,n=5){let r=new Map;for(let a of e.files)for(let l of a.symbols){let c=r.get(l.name);c||r.set(l.name,c=[]),c.push({file:l.file,line:l.line,...l.endLine!==void 0?{endLine:l.endLine}:{},kind:l.kind,exported:l.exported,lang:l.lang,...l.parent?{parent:l.parent}:{}})}let s={};for(let a of[...r.keys()].sort(M))s[a]=r.get(a).slice().sort((l,c)=>M(l.file,c.file)||l.line-c.line||M(l.kind,c.kind));let o={};for(let a of[...t.keys()].sort(M)){let l=[...t.get(a)].sort(M);l.length&&(o[a]=l)}return{schemaVersion:n,defs:s,refs:o}}function Us(e){return JSON.stringify(e,null,2)+` +`}var ur=O(()=>{"use strict";E();Xe();Y();pt()});function fr(e){return new Set(en(e))}function Yt(e,t,n={}){let r=t??en(e),s=n.recall===!0,o=new Map;for(let m of e.files){let p=new Set;for(let g of m.symbols){if(!g.exported||zs.has(g.kind)||p.has(g.name))continue;p.add(g.name);let y=o.get(g.name);y||o.set(g.name,y=[]),y.push(g)}}let a=new Map;for(let[m,p]of o){let g=new Map;for(let y of p){let h=st(y.lang),S=g.get(h);S||g.set(h,S=[]),S.push(y)}a.set(m,g)}let l=new Map;for(let m of e.files){let p=new Map;for(let g of m.symbols)!zs.has(g.kind)&&!p.has(g.name)&&p.set(g.name,g);l.set(m.rel,p)}let c=new Map,d=(m,p)=>{let g=c.get(m.name+"\0"+m.file);g||c.set(m.name+"\0"+m.file,g={def:m,callers:[]}),g.callers.push(p)};for(let m of e.files){if(!m.calls?.length)continue;let p=st(m.lang),g=l.get(m.rel);for(let y of m.calls){let h=g.get(y.name);if(h){h.line!==y.line&&d(h,s?{file:m.rel,line:y.line,confidence:"corroborated"}:{file:m.rel,line:y.line});continue}let S=(a.get(y.name)?.get(p)??[]).filter(w=>w.file!==m.rel);if(!S.length)continue;let _=S.filter(w=>r.has(`${m.rel}|${w.file}`)),k=p==="js"?_.length?rt(m.rel,_):s&&S.length===1?S[0]:void 0:_.length?rt(m.rel,_):rt(m.rel,S);if(!k)continue;d(k,s?{file:m.rel,line:y.line,confidence:_.length?"corroborated":"unique-name"}:{file:m.rel,line:y.line})}}let f=new Map,u=[...c.keys()].sort(M);for(let m of u){let{def:p,callers:g}=c.get(m);g.sort((y,h)=>M(y.file,h.file)||y.line-h.line),f.has(p.name)?f.set(`${p.name}@${p.file}`,{def:p,callers:g}):f.set(p.name,{def:p,callers:g})}return f}function Hg(e,t,n){let r=e.files.find(s=>s.rel===t);if(r?.symbols.length)return Hs(r.symbols,n)}function Hs(e,t){let n;for(let r of e)zs.has(r.kind)||r.line>t||r.endLine!==void 0&&t>r.endLine||(!n||r.line>n.line||r.line===n.line&&(r.endLine??1/0)<=(n.endLine??1/0))&&(n=r);return n}function Gg(e){let t=new Map;for(let r of e.files){if(!r.calls?.length)continue;let s=r.symbols.filter(o=>!zs.has(o.kind));for(let o of r.calls){let a={file:r.rel,line:o.line};o.receiver!==void 0&&(a.receiver=o.receiver);let l=Hs(s,o.line);l&&(a.enclosingSymbol=l);let c=t.get(o.name);c||t.set(o.name,c=[]),c.push(a)}}let n=new Map;for(let r of[...t.keys()].sort(M)){let s=t.get(r);s.sort((o,a)=>M(o.file,a.file)||o.line-a.line),n.set(r,s)}return n}var zs,Qt=O(()=>{"use strict";E();kn();pt();Y();zs=new Set(["reexport","reexport-all","default"])});function tn(e){return e.parent?`${e.file}#${e.parent}/${e.name}`:`${e.file}#${e.name}`}function Vg(e){return{id:tn(e),name:e.name,kind:e.kind,file:e.file,line:e.line,...e.endLine!==void 0?{endLine:e.endLine}:{},exported:e.exported,...e.doc?{doc:e.doc}:{},...e.signature?{signature:e.signature}:{}}}function mr(e,t){let n=new Map,r=new Map,s=new Map,o=new Set;for(let p of e.files){let g=[];for(let y of p.symbols){if(qg.has(y.kind)||(g.push(y),n.set(tn(y),Vg(y)),!y.exported))continue;let h=`${y.name} ${y.file}`;if(o.has(h))continue;o.add(h);let S=s.get(y.name);S||s.set(y.name,S=[]),S.push(y)}r.set(p.rel,g)}let a=new Map,l=(p,g,y)=>{if(p===g)return;let h=`${p}${Gs}${g}${Gs}${y}`,S=a.get(h);S?S.weight+=1:a.set(h,{from:p,to:g,kind:y,weight:1})};for(let p of e.files){if(!p.calls?.length)continue;let g=st(p.lang),y=r.get(p.rel)??[],h=new Map;for(let S of y)h.has(S.name)||h.set(S.name,S);for(let S of p.calls){let _=Hs(y,S.line);if(!_)continue;let k=h.get(S.name);if(k){k.line!==S.line&&l(tn(_),tn(k),"calls");continue}let b=(s.get(S.name)??[]).filter(T=>st(T.lang)===g&&T.file!==p.rel);if(!b.length)continue;let w=b.filter(T=>t.has(`${p.rel}|${T.file}`)),v=w.length?w:g==="js"?[]:b;if(!v.length)continue;let A=rt(p.rel,v.map(T=>({file:T.file,lang:T.lang})));if(!A)continue;let F=v.find(T=>T.file===A.file);l(tn(_),tn(F),"calls")}}let c=new Map;for(let p of n.values())c.set(`${p.name} ${p.file}`,p.id);for(let p of cr(e,t)){let g=c.get(`${p.from} ${p.fromFile}`),y=c.get(`${p.to} ${p.toFile}`);g&&y&&l(g,y,p.kind)}let d=[...a.values()].sort((p,g)=>M(p.from,g.from)||M(p.kind,g.kind)||M(p.to,g.to)),f=new Map,u=new Map;for(let p of d)(f.get(p.from)??f.set(p.from,[]).get(p.from)).push(p),(u.get(p.to)??u.set(p.to,[]).get(p.to)).push(p);let m=new Map;for(let p of[...n.keys()].sort(M)){let g=n.get(p);(m.get(g.name)??m.set(g.name,[]).get(g.name)).push(p)}return{nodes:n,edges:d,out:f,in:u,byName:m}}function pr(e,t,n={}){let r=Math.max(1,Math.min(n.depth??2,Jg)),s=n.direction??"both",o=e.nodes.has(t)?[t]:e.byName.get(t)??[...e.nodes.keys()].filter(p=>p.endsWith(`#${t}`)),a=o.map(p=>e.nodes.get(p)).filter(Boolean);if(!a.length)return{root:[],nodes:[],edges:[]};let l=new Map;for(let p of o)l.set(p,0);let c=new Map,d=[...o],f=!1;for(let p=1;p<=r&&d.length;p++){let g=[];for(let y of d){let h=(S,_)=>{for(let k of S??[]){c.set(`${k.from}${Gs}${k.to}${Gs}${k.kind}`,k);let b=_(k);if(!l.has(b)){if(l.size>=Kg){f=!0;continue}l.set(b,p),g.push(b)}}};s!=="in"&&h(e.out.get(y),S=>S.to),s!=="out"&&h(e.in.get(y),S=>S.from)}d=g}let u=[...l.entries()].map(([p,g])=>({...e.nodes.get(p),depth:g})).sort((p,g)=>p.depth-g.depth||M(p.file,g.file)||M(p.name,g.name)),m=[...c.values()].filter(p=>l.has(p.from)&&l.has(p.to)).sort((p,g)=>M(p.from,g.from)||M(p.kind,g.kind)||M(p.to,g.to));return{root:a,nodes:u,edges:m,...f?{truncated:!0}:{}}}var Gs,qg,Jg,Kg,gr=O(()=>{"use strict";E();kn();Qt();Xt();Y();Gs="\0",qg=new Set(["reexport","reexport-all","default"]);Jg=5,Kg=400});function $t(e){if(Zg.test(e)||js(e))return!0;let t=e.split("/").pop();return Xg.some(n=>n.test(t))}function _r(e){let t=new Set,n=new Map;for(let a of e.files)n.set(a.rel,a.module),a.fileKind==="code"&&$t(a.rel)&&t.add(a.rel);let r=new Map,s=new Map;for(let a of e.fileEdges){if(a.dangling||a.kind!=="import"&&a.kind!=="use"&&a.kind!=="call"||!t.has(a.from)||t.has(a.to))continue;let l=r.get(a.to);l||r.set(a.to,l=new Set),l.add(a.from);let c=n.get(a.to);if(c!==void 0){let d=s.get(c);d||s.set(c,d=new Set),d.add(a.from)}}let o=a=>{let l=new Map;for(let c of[...a.keys()].sort(M))l.set(c,[...a.get(c)].sort(M));return l};return{testFiles:t,testedByFile:o(r),testedByModule:o(s)}}function Yg(e,t){let n=e.modules.find(r=>r.slug===t);return n?.testedBy?n.testedBy:_r(e).testedByModule.get(t)??[]}function Qg(e){let t=_r(e),n=new Map;for(let r of e.files)r.fileKind!=="code"||t.testFiles.has(r.rel)||n.set(r.module,(n.get(r.module)??0)+1);return e.modules.filter(r=>r.tier<=1&&r.symbols>0&&(n.get(r.slug)??0)>0&&!t.testedByModule.has(r.slug))}var Xg,Zg,vn=O(()=>{"use strict";E();Ws();Y();Xg=[/^test_.*\.py$/i,/_test\.py$/i,/_test\.go$/,/(Test|Tests|IT)\.java$/,/(Test|Tests)\.kt$/,/_spec\.rb$/,/_test\.rb$/,/Test\.php$/,/(Test|Tests)\.cs$/,/_test\.exs$/],Zg=/(^|\/)(tests?|__tests?__|spec|specs|e2e)(\/|$)/i});function Rn(e,t,n){let r=e.fields[t];for(let s of yt(n))r.tf.set(s,(r.tf.get(s)??0)+1),r.len++,e.all.add(s)}function l_(){let e={};for(let t of qs)e[t]={tf:new Map,len:0};return e}function Vs(e){let t=[];for(let n of e.files){let r={file:n.rel,fields:l_(),all:new Set,symbols:[],decls:[],exactNames:new Set,isTest:$t(n.rel)},s=new Set;for(let o of n.symbols)Rn(r,"name",o.name),o.doc&&Rn(r,"doc",o.doc),r.exactNames.add(ht(o.name).toLowerCase()),s.has(o.name)||(s.add(o.name),r.symbols.push(o.name),r.decls.push({name:o.name,kind:o.kind,line:o.line}));for(let o of n.rel.split("/"))Rn(r,"path",o);for(let o of n.headings)Rn(r,"heading",o);n.summary&&Rn(r,"summary",n.summary);for(let o of n.terms??[])Rn(r,"body",o);t.push(r)}return t}function kd(e){let t=`^^${e}$$`,n=new Set;for(let r=0;r+3<=t.length;r++)n.add(t.slice(r,r+3));return n}function c_(e,t){if(!e.size||!t.size)return 0;let n=0;for(let r of e)t.has(r)&&n++;return 2*n/(e.size+t.size)}function Ed(e){let t=new Set,n=new Map;for(let r of e)for(let s of r.all){if(t.has(s))continue;t.add(s);let o=Wi(s);if(o===s)continue;let a=n.get(o);a||n.set(o,a=[]),a.push(s)}for(let r of n.values())r.sort(M);return n}function vd(e){let t=new Map;for(let n of e)for(let r of n.all)t.has(r)||t.set(r,kd(r));return t}function Dt(e,t,n={}){return Rd(e,t,n).results}function nn(e,t,n={}){return Rd(e,t,n)}function xd(e,t,n){return{results:[],explain:{query:e,terms:[],droppedStopwords:os(e),unresolvedTerms:[],verdict:t,note:n,bridgedOnlyResults:0,resultCount:0}}}function Rd(e,t,n={}){let r=[],s=new Set;for(let _ of is(t))for(let k of yt(_))s.has(k)||(s.add(k),r.push(k));if(!r.length){let _=os(t);return xd(t,"none",_.length?`Nothing was searched for: every token in this query (${_.join(", ")}) is a stopword or too short to index. Search with the identifiers or domain words you are actually looking for.`:"Nothing was searched for: the query carried no indexable token.")}let o=r.some(_=>a_.test(_)),a=Md(e),l=a.length;if(!l)return xd(t,"none","This index contains no files.");let c={};for(let _ of qs){let k=0;for(let b of a)k+=b.fields[_].len;c[_]=k/l||1}let d=new Map;for(let _ of r){let k=0;for(let b of a)b.all.has(_)&&k++;d.set(_,k)}let f=n.fuzzy??!0,u=new Map;if(f){let _=r.filter(k=>d.get(k)===0);if(_.length){let k=Td(e),b=[];for(let w of _){let v=(k.get(Wi(w))??[]).filter(A=>A!==w);v.length?u.set(w,v.slice(0,wd).map(A=>({term:A,dice:Sd}))):b.push(w)}if(b.length){let w=Cd(e);for(let v of b){let A=kd(v),F=[];for(let[T,U]of w){let te=c_(A,U);te>=n_&&F.push({term:T,dice:te})}F.sort((T,U)=>U.dice-T.dice||M(T.term,U.term)),u.set(v,F.slice(0,wd))}}}}let m=new Map,p=_=>{let k=d.get(_)??m.get(_);if(k!==void 0)return k;let b=0;for(let w of a)w.all.has(_)&&b++;return m.set(_,b),b},g=_=>Math.log(1+(l-_+.5)/(_+.5)),y=n.rank==="graph"?Ad(e):void 0,h=[];for(let _ of a){let k=0,b=[],w=new Set,v=new Set,A=new Set,F=!1,T=z=>{let P=0;for(let j of qs){let B=_.fields[j],se=B.tf.get(z);if(!se)continue;w.add(j);let J=s_[j];P+=r_[j]*se/(1-J+J*B.len/c[j])}return P};for(let z of r){let P=T(z);if(P>0){b.push(z),v.add(z),_.exactNames.has(z)&&(F=!0),k+=g(d.get(z))*(P/(bd+P));continue}for(let j of u.get(z)??[]){let B=T(j.term);B&&(k+=g(p(j.term))*(B/(bd+B))*j.dice,v.add(j.term),A.add(z))}}if(!b.length&&!A.size)continue;F&&(k*=i_),_.isTest&&!o&&(k*=o_),y&&(k*=1+.35*Math.log1p(y.get(_.file)??0));let te=_.decls.map(z=>{let P=new Set(yt(z.name)),j=0;for(let B of v)P.has(B)&&j++;return{decl:z,hits:j}}).filter(z=>z.hits>0).sort((z,P)=>P.hits-z.hits||M(z.decl.name,P.decl.name)).slice(0,t_).map(z=>z.decl),V={file:_.file,score:Number(k.toFixed(4)),matchedTerms:b.sort(M),topSymbols:te.map(z=>z.name)};w.size&&(V.matchedFields=qs.filter(z=>w.has(z))),te.length&&(V.symbolHits=te,V.line=Math.min(...te.map(z=>z.line))),A.size&&(V.fuzzyTerms=[...A].sort(M)),b.length||(V.bridgedOnly=!0),h.push(V)}h.sort((_,k)=>k.score-_.score||M(_.file,k.file));let S=(n.exact?h.filter(_=>!_.bridgedOnly):h).slice(0,n.limit??e_);return{results:S,explain:d_(t,r,d,u,S)}}function d_(e,t,n,r,s){let o=t.map(g=>{let y=n.get(g)??0,h=y===0?r.get(g)??[]:[];if(!h.length)return{term:g,df:y};let S=h[0].dice===Sd?"stem":"trigram";return{term:g,df:y,bridge:{via:S,to:h.map(_=>_.term),dice:h[0].dice}}}),a=o.filter(g=>g.df===0&&!g.bridge).map(g=>g.term).sort(M),l=!/\s/.test(e.trim())&&t.length?{term:t[0],df:n.get(t[0])??0}:void 0,c=s.filter(g=>g.bridgedOnly).length,d=s.length>0&&c===s.length,f=l?.df===0,u=s.length?f||d?"weak":"match":"none",m={query:e,terms:o,droppedStopwords:os(e),unresolvedTerms:a,...l?{wholeIdentifier:l}:{},verdict:u,bridgedOnlyResults:c,resultCount:s.length},p=u_(m,f,d);return p&&(m.note=p),m}function u_(e,t,n){let{verdict:r,wholeIdentifier:s,resultCount:o,terms:a}=e;if(r!=="match"){if(!o)return e.unresolvedTerms.length?`No file matches. ${e.unresolvedTerms.length===1?"The term":"The terms"} ${e.unresolvedTerms.join(", ")} appear nowhere in this index.`:"No file matches this query.";if(t&&s){let l=a.filter(u=>u.term!==s.term&&u.df>0).map(u=>u.term).join(", "),c=a.find(u=>u.term===s.term)?.bridge?.to??[],d=l?` The ${o} result${o===1?"":"s"} below match only its parts (${l}).`:"",f=c.length?` Closest indexed name${c.length===1?"":"s"}: ${c.join(", ")}.`:"";return`No file in this index defines or mentions "${s.term}".${d}${f} If you expected it here, check you are indexing the right branch or commit.`}if(n)return`Nothing matched verbatim. Every result below came from a near match: ${a.filter(d=>d.bridge).map(d=>`"${d.term}" \u2192 ${d.bridge.to.join(", ")}`).join("; ")}. Re-run with --exact to see only literal matches.`}}var bd,e_,t_,n_,wd,Sd,qs,r_,s_,i_,o_,a_,Mn=O(()=>{"use strict";E();pt();Ae();vn();Y();bd=1.2,e_=20,t_=5,n_=.6,wd=3,Sd=.9,qs=["name","path","heading","summary","doc","body"],r_={name:3,path:2,heading:1.5,summary:1.5,doc:1.6,body:.7},s_={name:.75,path:.75,heading:.75,summary:.75,doc:.75,body:.4},i_=1.35,o_=.65,a_=/^(test|tests|spec|specs|fixture|fixtures|mock|mocks|stub|stubs)$/});function hr(e,t,n=.85){let r=new Map,s=e.length;if(s===0)return r;let o=new Map(e.map((d,f)=>[d,f])),a=Array.from({length:s},()=>[]),l=new Array(s).fill(0);for(let d of t){if(d.dangling)continue;let f=o.get(d.from),u=o.get(d.to);f===void 0||u===void 0||f===u||(a[f].push([u,d.weight]),l[f]+=d.weight)}let c=new Array(s).fill(1/s);for(let d=0;d<100;d++){let f=0;for(let g=0;gr.set(d,c[f])),r}function Id(e,t){let n=new Map;for(let y of e)n.set(y,0);let r=e.length;if(r<3)return n;let s=new Map(e.map((y,h)=>[y,h])),o=Array.from({length:r},()=>new Set);for(let y of t){if(y.dangling)continue;let h=s.get(y.from),S=s.get(y.to);h===void 0||S===void 0||h===S||(o[h].add(S),o[S].add(h))}let a=o.map(y=>[...y].sort((h,S)=>h-S)),l=new Float64Array(r),c=[],d=[],f=Array.from({length:r},()=>[]),u=new Float64Array(r),m=new Int32Array(r).fill(-1),p=new Float64Array(r);for(let y=0;y=0;h--){let S=c[h];for(let _ of f[S])p[_]+=u[_]/u[S]*(1+p[S]);S!==y&&(l[S]+=p[S])}}let g=(r-1)*(r-2)/2;return e.forEach((y,h)=>n.set(y,l[h]/2/g)),n}function Qo(e){let t=[],n=e.modules.length;if(n>0){let s=e.modules.map(a=>a.id),o=hr(s,e.moduleEdges);for(let a of e.modules)a.pagerank=Number(((o.get(a.id)??0)*n).toFixed(4));if(n>3e3)t.push(`betweenness skipped (${n} modules > 3000)`);else{let a=Id(s,e.moduleEdges);for(let l of e.modules)l.betweenness=Number((a.get(l.id)??0).toFixed(6))}}let r=e.files.length;if(r>0){let s=e.files.map(a=>a.id),o=hr(s,e.fileEdges);for(let a of e.files)a.pagerank=Number(((o.get(a.id)??0)*r).toFixed(4))}return t}var Js=O(()=>{"use strict";E()});function Ks(e){return 1+(e.match(f_)??[]).length}function yr(e,t,n=50){let r=[];for(let s of e.files){if(s.kind!=="code"||t&&s.rel!==t||!s.symbols.length)continue;let o=q(I(e.root,s.rel)).split(` `);for(let a of s.symbols){if(a.kind==="reexport"||a.kind==="reexport-all")continue;let l=a.endLine??a.line,c=o.slice(a.line-1,l).join(` -`),d={file:s.rel,name:a.name,line:a.line,complexity:Gs(c)};a.endLine!==void 0&&(d.endLine=a.endLine),r.push(d)}}return r.sort((s,o)=>o.complexity-s.complexity||M(s.file,o.file)||s.line-o.line),r.slice(0,n)}function hr(e,t,n=20){let r=xd(e),s=e.files.filter(o=>o.kind==="code").map(o=>{let a=r.get(o.rel),l=t.get(o.rel)??0;return{file:o.rel,complexity:a,commits:l,score:(l+1)*a}});return s.sort((o,a)=>a.score-o.score||M(o.file,a.file)),s.slice(0,n)}var zg,yr=F(()=>{"use strict";k();oe();mt();Ae();Y();zg=/\b(if|elif|elsif|else\s+if|for|foreach|while|until|unless|case|when|match|catch|rescue|except)\b|&&|\|\||(?[n.rel,n]))}function kd(e){let t=We(e);if(!t.symbolsByName){let n=new Map;for(let r of e.files)for(let s of r.symbols){let o=n.get(s.name);o?o.push(s):n.set(s.name,[s])}t.symbolsByName=n}return t.symbolsByName}function Zo(e){let t=We(e);return t.resolveCtx??=Bo(e)}function Qt(e){let t=We(e);if(!t.importPairs){let n=Zo(e),r=new Set;for(let s of e.files)for(let o of s.refs){if(o.kind!=="import")continue;let a=or(s.rel,s.ext,o.spec,n);a.kind==="resolved"&&a.target!==s.rel&&r.add(`${s.rel}|${a.target}`)}t.importPairs=r}return t.importPairs}function Ed(e,t,n){let r=Xo.get(e);!r||r.resolveCtx!==t||r.importPairs||(r.importPairs=n)}function En(e){let t=We(e);return t.uniqueDefs??=Qo(e)}function Vs(e){let t=We(e);return t.symbolRefs??=Vo(e)}function Cn(e){let t=We(e);return t.callerIndex??=Zt(e,Qt(e))}function Yo(e){let t=We(e);return t.hierarchy??=kn(e,Qt(e))}function vd(e){let t=We(e);return t.symbolGraph??=ur(e,Qt(e))}function _d(e){let t=We(e);return(t.bm25??={docs:Hs(e)}).docs}function hd(e){let t=We(e),n=t.bm25??={docs:Hs(e)};return n.trigrams??=pd(n.docs)}function yd(e){let t=We(e);if(!t.importPagerank){let n=e.files.map(s=>s.rel),r=[];for(let s of Qt(e)){let o=s.indexOf("|");r.push({from:s.slice(0,o),to:s.slice(o+1),kind:"import",weight:1})}t.importPagerank=gr(n,r)}return t.importPagerank}function bd(e){let t=We(e),n=t.bm25??={docs:Hs(e)};return n.stems??=md(n.docs)}function xd(e){let t=We(e);if(!t.fileComplexity){let n=new Map;for(let r of e.files)r.kind==="code"&&n.set(r.rel,Gs(G(I(e.root,r.rel))));t.fileComplexity=n}return t.fileComplexity}var Xo,mt=F(()=>{"use strict";k();oe();Ps();Js();cr();Yt();Xt();mr();Mn();qs();yr();Ae();Xo=new WeakMap});function Hg(e){return e.length<5?!1:/[a-z][A-Z]/.test(e)||/[A-Z]{2}/.test(e)||e.includes("_")||/\d/.test(e)}function Qo(e){let t=new Map;for(let r of e.files)for(let s of r.symbols){if(!s.exported||qg.has(s.kind)||!Hg(s.name))continue;let o=t.get(s.name);o||t.set(s.name,o=new Set),o.add(r.rel)}let n=new Map;for(let[r,s]of t)s.size===1&&n.set(r,[...s][0]);return n}function Dt(e,t){let n=Gg(t.from,t.to,t.kind),r=e.get(n);if(r){r.weight+=t.weight;return}e.set(n,{...t})}function ta(e,t,n,r,s){let o=new Map,a=new Set;for(let x of e.files)for(let v of x.refs)if(v.kind==="doc-link"){let A=zo(x.rel,v.spec,t);if(A.kind==="external")continue;A.kind==="dangling"?Dt(o,{from:x.rel,to:v.spec,kind:"doc-link",weight:1,dangling:!0,reason:A.reason}):A.target!==x.rel&&Dt(o,{from:x.rel,to:A.target,kind:"doc-link",weight:1})}else{let A=or(x.rel,x.ext,v.spec,t);if(A.kind==="external")continue;A.kind==="dangling"?Dt(o,{from:x.rel,to:v.spec,kind:"import",weight:1,dangling:!0,reason:A.reason}):A.target!==x.rel&&(Dt(o,{from:x.rel,to:A.target,kind:"import",weight:1}),a.add(`${x.rel}|${A.target}`))}let l=new Set;for(let x of qo(e,a))Dt(o,x),l.add(`${x.from}|${x.to}`);for(let x of Go(e,a))Dt(o,x),l.add(`${x.from}|${x.to}`);Ed(e,t,a);let c=En(e);if(c.size)for(let x of e.files){if(x.kind!=="code"||!x.idents?.length)continue;let v=new Map;for(let A of x.idents){let O=c.get(A);!O||O===x.rel||v.set(O,(v.get(O)??0)+1)}for(let[A,O]of v){let N=`${x.rel}|${A}`;a.has(N)||l.has(N)||Dt(o,{from:x.rel,to:A,kind:"use",weight:Math.min(O,5)})}}if(c.size)for(let x of e.files){if(x.kind!=="doc")continue;let v=e.docText.get(x.rel)??G(I(e.root,x.rel));if(!v)continue;let A=new Map;for(let O of v.split(/[^A-Za-z0-9_]+/))c.has(O)&&A.set(O,(A.get(O)??0)+1);for(let[O,N]of A){let U=c.get(O);U!==x.rel&&Dt(o,{from:x.rel,to:U,kind:"mention",weight:Math.min(N,5)})}}let d=[...o.values()].sort((x,v)=>M(x.from,v.from)||M(x.to,v.to)||M(x.kind,v.kind)),f=new Map,u=new Map,m=new Set(e.files.map(x=>x.rel));for(let x of d)x.dangling||!m.has(x.to)||(u.set(x.from,(u.get(x.from)??0)+1),f.set(x.to,(f.get(x.to)??0)+1));let p={import:7,extends:6,implements:5,call:4,use:3,"doc-link":2,mention:1,contains:0},g=new Map;for(let x of d){if(x.dangling||!m.has(x.to))continue;let v=r.get(x.from),A=r.get(x.to);if(!v||!A||v===A)continue;let O=`${v}${ea}${A}`,N=g.get(O);N?(N.weight+=x.weight,(p[x.kind]??0)>(p[N.kind]??0)&&(N.kind=x.kind)):g.set(O,{from:v,to:A,kind:x.kind,weight:x.weight})}let y=[...g.values()].sort((x,v)=>M(x.from,v.from)||M(x.to,v.to)),h=new Map,S=new Map;for(let x of y)S.set(x.from,(S.get(x.from)??0)+1),h.set(x.to,(h.get(x.to)??0)+1);let _=e.files.map(x=>({id:x.rel,kind:"file",rel:x.rel,fileKind:x.kind,lang:x.lang,module:r.get(x.rel)??"root",title:x.title,summary:x.summary,symbols:x.symbols.length,lines:x.lines,degIn:f.get(x.rel)??0,degOut:u.get(x.rel)??0})).sort((x,v)=>M(x.rel,v.rel)),E=new Map;for(let x of e.files){let v=r.get(x.rel)??"root";E.set(v,(E.get(v)??0)+x.symbols.length)}let b=n.map(x=>({id:x.slug,kind:"module",slug:x.slug,path:x.path,title:x.title,summary:x.summary,tier:x.tier,members:x.members,symbols:E.get(x.slug)??0,degIn:h.get(x.slug)??0,degOut:S.get(x.slug)??0})).sort((x,v)=>M(x.slug,v.slug));return{schemaVersion:s?.schemaVersion??5,version:s?.version??fe,commit:e.commit,fileCount:e.files.length,languages:e.languages,files:_,modules:b,fileEdges:d,moduleEdges:y}}var qg,ea,Gg,Js=F(()=>{"use strict";k();oe();Xe();Ps();Sn();Xt();mt();Ae();Y();qg=new Set(["reexport","reexport-all","default"]);ea="\0",Gg=(e,t,n)=>`${e}${ea}${t}${ea}${n}`});function*Vg(e){for(let t of e.files)yield*t.symbols}function ra(e,t){let n=Sd(e).get(t);return n?[...n.symbols].filter(r=>!na.has(r.kind)).sort((r,s)=>r.line-s.line||M(r.name,s.name)):[]}function An(e,t,n={}){let r=t.split("/").filter(Boolean);if(!r.length)return[];let s=r[r.length-1],o=r.slice(0,-1),a=(f,u)=>n.substring?f.toLowerCase().includes(u.toLowerCase()):f===u,l=[],c=n.substring?Vg(e):kd(e).get(s)??[];for(let f of c)if(!na.has(f.kind)&&a(f.name,s)){if(o.length){let u=o[o.length-1];if(!f.parent||f.parent!==u)continue}l.push({...f})}l.sort((f,u)=>+(u.name===s)-+(f.name===s)||M(f.file,u.file)||f.line-u.line);let d=l.slice(0,n.maxResults??50);if(n.includeBody){let f=new Map,u=new Set;for(let m of d){let p=m.endLine??m.line;if(u.has(m.file))continue;let g=f.get(m.file);if(!g){let y=G(I(e.root,m.file));if(!y){u.add(m.file);continue}g=y.split(` +`),d={file:s.rel,name:a.name,line:a.line,complexity:Ks(c)};a.endLine!==void 0&&(d.endLine=a.endLine),r.push(d)}}return r.sort((s,o)=>o.complexity-s.complexity||M(s.file,o.file)||s.line-o.line),r.slice(0,n)}function br(e,t,n=20){let r=Nd(e),s=e.files.filter(o=>o.kind==="code").map(o=>{let a=r.get(o.rel),l=t.get(o.rel)??0;return{file:o.rel,complexity:a,commits:l,score:(l+1)*a}});return s.sort((o,a)=>a.score-o.score||M(o.file,a.file)),s.slice(0,n)}var f_,wr=O(()=>{"use strict";E();ae();pt();Ne();Y();f_=/\b(if|elif|elsif|else\s+if|for|foreach|while|until|unless|case|when|match|catch|rescue|except)\b|&&|\|\||(?[n.rel,n]))}function Od(e){let t=Oe(e);if(!t.symbolsByName){let n=new Map;for(let r of e.files)for(let s of r.symbols){let o=n.get(s.name);o?o.push(s):n.set(s.name,[s])}t.symbolsByName=n}return t.symbolsByName}function ta(e){let t=Oe(e);return t.resolveCtx??=qo(e)}function en(e){let t=Oe(e);if(!t.importPairs){let n=ta(e),r=new Set;for(let s of e.files)for(let o of s.refs){if(o.kind!=="import")continue;let a=lr(s.rel,s.ext,o.spec,n);a.kind==="resolved"&&a.target!==s.rel&&r.add(`${s.rel}|${a.target}`)}t.importPairs=r}return t.importPairs}function Pd(e,t,n){let r=ea.get(e);!r||r.resolveCtx!==t||r.importPairs||(r.importPairs=n)}function Zt(e){let t=Oe(e);return t.uniqueDefs??=ra(e)}function Xs(e){let t=Oe(e);return t.symbolRefs??=Zo(e)}function Bs(e){let t=Oe(e);if(t.docMentions)return t.docMentions;let n=Zt(e),r=new Map;if(n.size)for(let s of e.files){if(s.kind!=="doc")continue;let o=e.docText.get(s.rel),a=o??q(I(e.root,s.rel));if(!a)continue;let l=new Map;for(let c of a.split(/[^A-Za-z0-9_]+/))n.has(c)&&l.set(c,(l.get(c)??0)+1);r.set(s.rel,{counts:l,retained:o!==void 0})}return t.docMentions=r}function $d(e){let t=Oe(e);if(t.identSets)return t.identSets;let n=new Map;for(let r of e.files)r.kind==="code"&&r.idents?.length&&n.set(r.rel,new Set(r.idents));return t.identSets=n}function Cn(e){let t=Oe(e);return t.callerIndex??=Yt(e,en(e))}function na(e){let t=Oe(e);return t.hierarchy??=En(e,en(e))}function Dd(e){let t=Oe(e);return t.symbolGraph??=mr(e,en(e))}function Md(e){let t=Oe(e);return(t.bm25??={docs:Vs(e)}).docs}function Cd(e){let t=Oe(e),n=t.bm25??={docs:Vs(e)};return n.trigrams??=vd(n.docs)}function Ad(e){let t=Oe(e);if(!t.importPagerank){let n=e.files.map(s=>s.rel),r=[];for(let s of en(e)){let o=s.indexOf("|");r.push({from:s.slice(0,o),to:s.slice(o+1),kind:"import",weight:1})}t.importPagerank=hr(n,r)}return t.importPagerank}function Td(e){let t=Oe(e),n=t.bm25??={docs:Vs(e)};return n.stems??=Ed(n.docs)}function Nd(e){let t=Oe(e);if(!t.fileComplexity){let n=new Map;for(let r of e.files)r.kind==="code"&&n.set(r.rel,Ks(q(I(e.root,r.rel))));t.fileComplexity=n}return t.fileComplexity}var ea,pt=O(()=>{"use strict";E();ae();Ds();Zs();ur();Qt();Xt();gr();Mn();Js();wr();Ne();ea=new WeakMap});function m_(e){return e.length<5?!1:/[a-z][A-Z]/.test(e)||/[A-Z]{2}/.test(e)||e.includes("_")||/\d/.test(e)}function ra(e){let t=new Map;for(let r of e.files)for(let s of r.symbols){if(!s.exported||p_.has(s.kind)||!m_(s.name))continue;let o=t.get(s.name);o||t.set(s.name,o=new Set),o.add(r.rel)}let n=new Map;for(let[r,s]of t)s.size===1&&n.set(r,[...s][0]);return n}function Lt(e,t){let n=g_(t.from,t.to,t.kind),r=e.get(n);if(r){r.weight+=t.weight;return}e.set(n,{...t})}function ia(e,t,n,r,s){let o=new Map,a=new Set;for(let w of e.files)for(let v of w.refs)if(v.kind==="doc-link"){let A=Vo(w.rel,v.spec,t);if(A.kind==="external")continue;A.kind==="dangling"?Lt(o,{from:w.rel,to:v.spec,kind:"doc-link",weight:1,dangling:!0,reason:A.reason}):A.target!==w.rel&&Lt(o,{from:w.rel,to:A.target,kind:"doc-link",weight:1})}else{let A=lr(w.rel,w.ext,v.spec,t);if(A.kind==="external")continue;A.kind==="dangling"?Lt(o,{from:w.rel,to:v.spec,kind:"import",weight:1,dangling:!0,reason:A.reason}):A.target!==w.rel&&(Lt(o,{from:w.rel,to:A.target,kind:"import",weight:1}),a.add(`${w.rel}|${A.target}`))}let l=new Set;for(let w of Ko(e,a))Lt(o,w),l.add(`${w.from}|${w.to}`);for(let w of Xo(e,a))Lt(o,w),l.add(`${w.from}|${w.to}`);Pd(e,t,a);let c=Zt(e);if(c.size)for(let w of e.files){if(w.kind!=="code"||!w.idents?.length)continue;let v=new Map;for(let A of w.idents){let F=c.get(A);!F||F===w.rel||v.set(F,(v.get(F)??0)+1)}for(let[A,F]of v){let T=`${w.rel}|${A}`;a.has(T)||l.has(T)||Lt(o,{from:w.rel,to:A,kind:"use",weight:Math.min(F,5)})}}if(c.size)for(let[w,{counts:v}]of Bs(e))for(let[A,F]of v){let T=c.get(A);T!==w&&Lt(o,{from:w,to:T,kind:"mention",weight:Math.min(F,5)})}let d=[...o.values()].sort((w,v)=>M(w.from,v.from)||M(w.to,v.to)||M(w.kind,v.kind)),f=new Map,u=new Map,m=new Set(e.files.map(w=>w.rel));for(let w of d)w.dangling||!m.has(w.to)||(u.set(w.from,(u.get(w.from)??0)+1),f.set(w.to,(f.get(w.to)??0)+1));let p={import:7,extends:6,implements:5,call:4,use:3,"doc-link":2,mention:1,contains:0},g=new Map;for(let w of d){if(w.dangling||!m.has(w.to))continue;let v=r.get(w.from),A=r.get(w.to);if(!v||!A||v===A)continue;let F=`${v}${sa}${A}`,T=g.get(F);T?(T.weight+=w.weight,(p[w.kind]??0)>(p[T.kind]??0)&&(T.kind=w.kind)):g.set(F,{from:v,to:A,kind:w.kind,weight:w.weight})}let y=[...g.values()].sort((w,v)=>M(w.from,v.from)||M(w.to,v.to)),h=new Map,S=new Map;for(let w of y)S.set(w.from,(S.get(w.from)??0)+1),h.set(w.to,(h.get(w.to)??0)+1);let _=e.files.map(w=>({id:w.rel,kind:"file",rel:w.rel,fileKind:w.kind,lang:w.lang,module:r.get(w.rel)??"root",title:w.title,summary:w.summary,symbols:w.symbols.length,lines:w.lines,degIn:f.get(w.rel)??0,degOut:u.get(w.rel)??0})).sort((w,v)=>M(w.rel,v.rel)),k=new Map;for(let w of e.files){let v=r.get(w.rel)??"root";k.set(v,(k.get(v)??0)+w.symbols.length)}let b=n.map(w=>({id:w.slug,kind:"module",slug:w.slug,path:w.path,title:w.title,summary:w.summary,tier:w.tier,members:w.members,symbols:k.get(w.slug)??0,degIn:h.get(w.slug)??0,degOut:S.get(w.slug)??0})).sort((w,v)=>M(w.slug,v.slug));return{schemaVersion:s?.schemaVersion??5,version:s?.version??fe,commit:e.commit,fileCount:e.files.length,languages:e.languages,files:_,modules:b,fileEdges:d,moduleEdges:y}}var p_,sa,g_,Zs=O(()=>{"use strict";E();Xe();Ds();kn();Xt();pt();Y();p_=new Set(["reexport","reexport-all","default"]);sa="\0",g_=(e,t,n)=>`${e}${sa}${t}${sa}${n}`});function*__(e){for(let t of e.files)yield*t.symbols}function aa(e,t){let n=Fd(e).get(t);return n?[...n.symbols].filter(r=>!oa.has(r.kind)).sort((r,s)=>r.line-s.line||M(r.name,s.name)):[]}function An(e,t,n={}){let r=t.split("/").filter(Boolean);if(!r.length)return[];let s=r[r.length-1],o=r.slice(0,-1),a=(f,u)=>n.substring?f.toLowerCase().includes(u.toLowerCase()):f===u,l=[],c=n.substring?__(e):Od(e).get(s)??[];for(let f of c)if(!oa.has(f.kind)&&a(f.name,s)){if(o.length){let u=o[o.length-1];if(!f.parent||f.parent!==u)continue}l.push({...f})}l.sort((f,u)=>+(u.name===s)-+(f.name===s)||M(f.file,u.file)||f.line-u.line);let d=l.slice(0,n.maxResults??50);if(n.includeBody){let f=new Map,u=new Set;for(let m of d){let p=m.endLine??m.line;if(u.has(m.file))continue;let g=f.get(m.file);if(!g){let y=q(I(e.root,m.file));if(!y){u.add(m.file);continue}g=y.split(` `),f.set(m.file,g)}m.body=g.slice(m.line-1,p).join(` -`)}}return n.concise?d.map(f=>({name:f.name,kind:f.kind,file:f.file,line:f.line,...f.body!==void 0?{body:f.body}:{}})):d}function sa(e,t){let n=[];for(let d of e.files)for(let f of d.symbols)f.name===t&&!na.has(f.kind)&&n.push(f);n.sort((d,f)=>M(d.file,f.file)||d.line-f.line);let s=Cn(e).get(t),o=s?[...s.callers]:[],a=new Set,c=En(e).get(t);for(let d of e.files)if(d.rel!==c){if(d.kind==="code"&&d.idents?.includes(t))a.add(d.rel);else if(d.kind==="doc"){let f=e.docText.get(d.rel);f&&new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(f)&&a.add(d.rel)}}for(let d of o)a.add(d.file);return{defs:n,callSites:o,referencingFiles:[...a].sort(M)}}var na,Ks=F(()=>{"use strict";k();oe();Ae();mt();Y();na=new Set(["reexport","reexport-all","default"])});function Xs(e,t,n){let r=An(e,t);if(n&&(r=r.filter(o=>o.file===n)),r.length===1)return r[0];if(r.length===0){let o=An(e,t,{substring:!0,maxResults:5}).map(a=>`${a.file}:${a.line} ${a.parent?a.parent+"/":""}${a.name}`).join(", ");throw new Error(`no symbol matches "${t}"${n?` in ${n}`:""}${o?` \u2014 near matches: ${o}`:""}`)}let s=r.map(o=>`${o.file}:${o.line}`).join(", ");throw new Error(`"${t}" is ambiguous (${r.length} matches: ${s}) \u2014 qualify with \`file\` or a Parent/name path`)}function Rd(e){return te(e,"utf8").split(` -`)}function Md(e,t,n=qe){let r=gn(e),s=Ee(r).mode,o;try{o=Ln(I(_e(r),".codeindex-edit-"))}catch{Re(r,t),ns(r,s);return}let a=I(o,ke(r));try{Re(a,t),ns(a,s);try{Dn(a,r)}catch{Re(r,t),ns(r,s)}}finally{try{n(o,{recursive:!0,force:!0})}catch{}}}function ia(e,t,n,r){let s=Xs(e,t,r),o=s.endLine??s.line,a=I(e.root,s.file),l=Rd(a),c=n.replace(/^\n+|\n+$/g,"").split(` -`);return l.splice(s.line-1,o-s.line+1,...c),Md(a,l.join(` -`)),{file:s.file,startLine:s.line,endLine:s.line+c.length-1,lines:c.length}}function Cd(e,t,n,r,s,o){let a=I(e.root,t.file),l=Rd(a),c=Jg.has(t.kind)?1:0,d=n.replace(/^\n+|\n+$/g,"").split(` -`),f=[];return s&&c&&l[r-1]?.trim()!==""&&f.push(""),f.push(...d),o&&c&&l[r]?.trim()!==""&&f.push(""),l.splice(r,0,...f),Md(a,l.join(` -`)),{file:t.file,startLine:r+1,endLine:r+f.length,lines:f.length}}function oa(e,t,n,r){let s=Xs(e,t,r),o=s.endLine??s.line;return Cd(e,s,n,o,!0,!0)}function aa(e,t,n,r){let s=Xs(e,t,r);return Cd(e,s,n,s.line-1,!0,!0)}var Jg,la=F(()=>{"use strict";k();xe();oe();Ks();Jg=new Set(["function","method","class","interface","struct","trait","enum","def"])});function Td(e){let t=e.replace(/^mem:/,"").replace(/\.md$/,"");if(!t)throw new Error("memory name is empty");let n=t.split("/");for(let r of n){if(!r||r==="."||r===".."||r.includes("\\"))throw new Error(`invalid memory name: "${e}"`);if(!/^[\w][\w.-]*$/.test(r))throw new Error(`invalid memory name segment: "${r}"`)}return t}function ca(e,t){return I(e,...Ad,`${Td(t)}.md`)}function br(e,t,n){let r=ca(e,t);return gt(_e(r),{recursive:!0}),Re(r,n.endsWith(` +`)}}return n.concise?d.map(f=>({name:f.name,kind:f.kind,file:f.file,line:f.line,...f.body!==void 0?{body:f.body}:{}})):d}function la(e,t){let n=[];for(let u of e.files)for(let m of u.symbols)m.name===t&&!oa.has(m.kind)&&n.push(m);n.sort((u,m)=>M(u.file,m.file)||u.line-m.line);let s=Cn(e).get(t),o=s?[...s.callers]:[],a=new Set,c=Zt(e).get(t),d=$d(e),f=new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`);for(let u of e.files)if(u.rel!==c){if(u.kind==="code"&&d.get(u.rel)?.has(t))a.add(u.rel);else if(u.kind==="doc"){let m=e.docText.get(u.rel);m&&f.test(m)&&a.add(u.rel)}}for(let u of o)a.add(u.file);return{defs:n,callSites:o,referencingFiles:[...a].sort(M)}}var oa,Ys=O(()=>{"use strict";E();ae();Ne();pt();Y();oa=new Set(["reexport","reexport-all","default"])});function Qs(e,t,n){let r=An(e,t);if(n&&(r=r.filter(o=>o.file===n)),r.length===1)return r[0];if(r.length===0){let o=An(e,t,{substring:!0,maxResults:5}).map(a=>`${a.file}:${a.line} ${a.parent?a.parent+"/":""}${a.name}`).join(", ");throw new Error(`no symbol matches "${t}"${n?` in ${n}`:""}${o?` \u2014 near matches: ${o}`:""}`)}let s=r.map(o=>`${o.file}:${o.line}`).join(", ");throw new Error(`"${t}" is ambiguous (${r.length} matches: ${s}) \u2014 qualify with \`file\` or a Parent/name path`)}function Ld(e){return Q(e,"utf8").split(` +`)}function jd(e,t,n=Ge){let r=_n(e),s=ve(r).mode,o;try{o=Dn(I(_e(r),".codeindex-edit-"))}catch{Me(r,t),ss(r,s);return}let a=I(o,Ee(r));try{Me(a,t),ss(a,s);try{Ln(a,r)}catch{Me(r,t),ss(r,s)}}finally{try{n(o,{recursive:!0,force:!0})}catch{}}}function ca(e,t,n,r){let s=Qs(e,t,r),o=s.endLine??s.line,a=I(e.root,s.file),l=Ld(a),c=n.replace(/^\n+|\n+$/g,"").split(` +`);return l.splice(s.line-1,o-s.line+1,...c),jd(a,l.join(` +`)),{file:s.file,startLine:s.line,endLine:s.line+c.length-1,lines:c.length}}function Wd(e,t,n,r,s,o){let a=I(e.root,t.file),l=Ld(a),c=h_.has(t.kind)?1:0,d=n.replace(/^\n+|\n+$/g,"").split(` +`),f=[];return s&&c&&l[r-1]?.trim()!==""&&f.push(""),f.push(...d),o&&c&&l[r]?.trim()!==""&&f.push(""),l.splice(r,0,...f),jd(a,l.join(` +`)),{file:t.file,startLine:r+1,endLine:r+f.length,lines:f.length}}function da(e,t,n,r){let s=Qs(e,t,r),o=s.endLine??s.line;return Wd(e,s,n,o,!0,!0)}function ua(e,t,n,r){let s=Qs(e,t,r);return Wd(e,s,n,s.line-1,!0,!0)}var h_,fa=O(()=>{"use strict";E();xe();ae();Ys();h_=new Set(["function","method","class","interface","struct","trait","enum","def"])});function Bd(e){let t=e.replace(/^mem:/,"").replace(/\.md$/,"");if(!t)throw new Error("memory name is empty");let n=t.split("/");for(let r of n){if(!r||r==="."||r===".."||r.includes("\\"))throw new Error(`invalid memory name: "${e}"`);if(!/^[\w][\w.-]*$/.test(r))throw new Error(`invalid memory name segment: "${r}"`)}return t}function ma(e,t){return I(e,...Ud,`${Bd(t)}.md`)}function xr(e,t,n){let r=ma(e,t);return _t(_e(r),{recursive:!0}),Me(r,n.endsWith(` `)?n:n+` -`),Td(t)}function da(e,t){try{return te(ca(e,t),"utf8")}catch{return}}function ua(e,t){let n=ca(e,t);try{Ee(n)}catch{return!1}return qe(n),!0}function fa(e){let t=I(e,...Ad),n=[],r=(s,o)=>{let a;try{a=_n(s,{withFileTypes:!0})}catch{return}for(let l of a)l.isDirectory()?r(I(s,l.name),o?`${o}/${l.name}`:l.name):l.name.endsWith(".md")&&n.push(o?`${o}/${l.name.slice(0,-3)}`:l.name.slice(0,-3))};return r(t,""),n.sort()}var Ad,Zs=F(()=>{"use strict";k();xe();oe();Ad=[".codeindex","memories"]});function xt(e,t,n){let r=G(e);if(r)try{let s=JSON.parse(r);if(s&&typeof s=="object")return s;t&&n&&n.push(`malformed ${t}: not a JSON object`);return}catch(s){if(t&&n){let o=String(s instanceof Error?s.message:s).split(` -`)[0];n.push(`malformed ${t}: ${o}`)}return}}function jt(e,t){let n=new RegExp(`^\\[${Ge(t)}\\]\\s*$([\\s\\S]*?)(?=^\\[|$(?![\\s\\S]))`,"m"),r=e.match(n);return r?r[1]:null}function wr(e,t){let n=e.match(new RegExp(`${Ge(t)}\\s*=\\s*\\[([^\\]]*)\\]`));return n?n[1].split(/\r?\n/).map(r=>r.replace(/#.*$/,"")).join(` -`).split(",").map(r=>r.trim().replace(/^["']|["']$/g,"")).filter(Boolean):[]}function Tn(e,t){return e?.match(new RegExp(`^\\s*${Ge(t)}\\s*=\\s*["']([^"']+)["']`,"m"))?.[1]}function ma(e){let t="";for(let n=0;nZg(e,t,n,r),o=()=>Yg(e,t),a=()=>Qg(e,t),l=()=>e_(e,t),c=()=>t_(e,t),d=()=>n_(e,t,r),f=()=>r_(e,t,r),m=n==="go"?[a,s,o,l,c,d,f]:n==="uv"?[c,s,o,a,l,d,f]:n==="composer"?[d,s,c,o,a,l,f]:n==="gradle"?[s,l,o,a,c,d,f,()=>s_(e,t)]:[s,o,a,l,c,d,f];for(let p of m){let g=p();if(g)return g}}function o_(e){return e.replace(/[\s\S]*?<\/parent>/g,"").replace(/[\s\S]*?<\/dependencies>/g,"").match(/\s*([^<]+?)\s*<\/artifactId>/)?.[1]}function xr(e,t,n,r,s){let o=t.replace(/^\.\//,"").replace(/\/+$/,"");if(!o||o==="."||n.has(o)||o.split("/").includes(".."))return;let a=i_(e,o,r,s);a&&n.set(o,a)}function a_(e,t){try{return Ee(I(e,t)).isDirectory()}catch{return!1}}function Id(e,t){let n;try{n=_n(t?I(e,t):e,{withFileTypes:!0})}catch{return[]}return n.filter(r=>r.isDirectory()&&!r.name.startsWith(".")&&!Kg.has(r.name)).map(r=>t?`${t}/${r.name}`:r.name).sort(M)}function Nd(e,t,n,r){if(!(n>Xg))for(let s of Id(e,t))r.push(s),Nd(e,s,n+1,r)}function l_(e,t){let n=t.split("/").filter(s=>s&&s!==".");if(n.includes(".."))return[];let r=[""];for(let s of n){let o=new Set;if(s==="**")for(let a of r){a&&o.add(a);let l=[];Nd(e,a,0,l);for(let c of l)o.add(c)}else if(s.includes("*")){let a=new RegExp(`^${s.split("*").map(Ge).join("[^/]*")}$`);for(let l of r)for(let c of Id(e,l))a.test(c.split("/").pop())&&o.add(c)}else for(let a of r){let l=a?`${a}/${s}`:s;a_(e,l)&&o.add(l)}if(r=[...o],!r.length)return[]}return r.filter(Boolean)}function Ys(e,t,n,r,s){let o=t.replace(/^\.\//,"").replace(/\/+$/,"");if(o){if(!o.includes("*")){xr(e,o,n,r,s);return}for(let a of l_(e,o))xr(e,a,n,r,s)}}function c_(e,t){let n=[],r=[],s=(d,f)=>{let u=d.trim();u&&(u.startsWith("!")?r.push(u.slice(1)):n.push({pattern:u,kind:f}))},a=xt(I(e,"package.json"),"package.json",t)?.workspaces;if(Array.isArray(a))for(let d of a)typeof d=="string"&&s(d,"npm");else if(a&&typeof a=="object"&&Array.isArray(a.packages))for(let d of a.packages)typeof d=="string"&&s(d,"npm");let l=G(I(e,"pnpm-workspace.yaml")),c=!1;for(let d of l.split(/\r?\n/)){if(/^\S/.test(d)){c=/^packages\s*:/.test(d);continue}if(!c)continue;let f=d.match(/^\s*-\s*['"]?([^'"#]+?)['"]?\s*(?:#.*)?$/);f&&s(f[1].trim(),"pnpm")}return{positives:n,negations:r}}function d_(e,t){let n=xt(I(e,"lerna.json"),"lerna.json",t);if(n&&Array.isArray(n.packages))return n.packages.filter(s=>typeof s=="string").map(s=>({pattern:s,kind:"lerna"}));let r=xt(I(e,"nx.json"),"nx.json",t);if(r){let s=r.workspaceLayout??{},o=typeof s.appsDir=="string"?s.appsDir:"apps",a=typeof s.libsDir=="string"?s.libsDir:"libs";return[...new Set([o,a])].map(l=>({pattern:`${l}/*`,kind:"nx"}))}return[]}function u_(e,t,n){let r=G(I(e,"Cargo.toml"));if(!r)return;let s=jt(r,"workspace");if(!s)return;let o=wr(s,"members");if(!o.length)return;let a=wr(s,"exclude").map(ma),l=new Map;for(let c of o)Ys(e,c,l,"cargo",n);for(let[c,d]of l)a.some(f=>f.test(c))||t.has(c)||t.set(c,d)}function f_(e,t,n){let r=G(I(e,"go.work"));if(!r)return;let s=[];for(let o of r.matchAll(/^use\s*\(([\s\S]*?)\)/gm))for(let a of o[1].split(/\r?\n/)){let l=a.replace(/\/\/.*$/,"").trim();l&&s.push(l)}for(let o of r.matchAll(/^use\s+([^\s(]+)/gm))s.push(o[1]);for(let o of s)o==="."||o==="./"||xr(e,o,t,"go",n)}function m_(e,t,n){let r=G(I(e,"pom.xml"));if(!r)return;let s=r.match(/([\s\S]*?)<\/modules>/)?.[1];if(s)for(let o of s.matchAll(/\s*([^<]+?)\s*<\/module>/g))xr(e,o[1],t,"maven",n)}function p_(e,t,n){let r=G(I(e,"pyproject.toml"));if(!r)return;let s=jt(r,"tool.uv.workspace");if(!s)return;let o=wr(s,"members");if(!o.length)return;let a=wr(s,"exclude").map(ma),l=new Map;for(let c of o)Ys(e,c,l,"uv",n);for(let[c,d]of l)a.some(f=>f.test(c))||t.has(c)||t.set(c,d)}function g_(e,t,n){let s=xt(I(e,"composer.json"),"composer.json",n)?.repositories;if(Array.isArray(s))for(let o of s){if(!o||typeof o!="object")continue;let{type:a,url:l}=o;a==="path"&&typeof l=="string"&&l&&Ys(e,l,t,"composer",n)}}function __(e,t,n){for(let r of["settings.gradle","settings.gradle.kts"]){let s=G(I(e,r));if(s){for(let o of s.split(/\r?\n/))if(/^\s*include[\s(]/.test(o))for(let a of o.matchAll(/["']([^"']+)["']/g)){let l=a[1].replace(/^:/,"").replace(/:/g,"/");l&&xr(e,l,t,"gradle",n)}}}}function h_(e,t,n,r){let s=xt(I(e,t.dir,"package.json"),`${t.dir}/package.json`,r);if(!s)return[];let o=new Set;for(let a of["dependencies","devDependencies","peerDependencies"]){let l=s[a];if(!(!l||typeof l!="object"))for(let c of Object.keys(l))c!==t.name&&n.has(c)&&o.add(c)}return[...o]}function Od(e,t){let n=`${e}/${t}`.split("/"),r=[];for(let s of n)!s||s==="."||(s===".."?r.pop():r.push(s));return r.join("/")}function y_(e,t,n,r){let s=G(I(e,t.dir,"Cargo.toml"));if(!s)return[];let o=new Set;for(let a of["dependencies","dev-dependencies","build-dependencies"]){let l=jt(s,a);if(l)for(let c of l.split(/\r?\n/)){let d=c.match(/^\s*([A-Za-z0-9_-]+)\s*=\s*(.+)$/);if(!d)continue;let f=d[1];if(f!==t.name&&n.has(f)){o.add(f);continue}let u=d[2].match(/path\s*=\s*["']([^"']+)["']/);if(u){let m=r.get(Od(t.dir,u[1]));m&&m!==t.name&&o.add(m)}}}return[...o]}function b_(e,t,n,r){let s=G(I(e,t.dir,"go.mod"));if(!s)return[];let o=new Set;for(let a of s.matchAll(/^\s*(?:require\s+)?([^\s/(][^\s]*)\s+v[^\s]+/gm)){let l=a[1];l!==t.name&&n.has(l)&&o.add(l)}for(let a of s.matchAll(/^\s*(?:replace\s+)?(\S+)(?:\s+\S+)?\s*=>\s*(\.\.?\/\S+)/gm)){let l=r.get(Od(t.dir,a[2]));l&&l!==t.name&&o.add(l)}return[...o]}function w_(e,t,n){let r=G(I(e,t.dir,"pom.xml"));if(!r)return[];let s=new Set;for(let o of r.replace(/[\s\S]*?<\/parent>/g,"").matchAll(/([\s\S]*?)<\/dependency>/g)){let a=o[1].match(/\s*([^<]+?)\s*<\/artifactId>/)?.[1];a&&a!==t.name&&n.has(a)&&s.add(a)}return[...s]}function x_(e,t,n){let r=G(I(e,t.dir,"pyproject.toml"));if(!r)return[];let s=new Set,o=jt(r,"project");if(o)for(let l of wr(o,"dependencies")){let c=l.match(/^[A-Za-z0-9_.-]+/)?.[0];c&&c!==t.name&&n.has(c)&&s.add(c)}let a=jt(r,"tool.uv.sources");if(a)for(let l of a.split(/\r?\n/)){let c=l.match(/^\s*([A-Za-z0-9_.-]+)\s*=\s*\{[^}]*workspace\s*=\s*true/);c&&c[1]!==t.name&&n.has(c[1])&&s.add(c[1])}return[...s]}function S_(e,t,n,r){let s=xt(I(e,t.dir,"composer.json"),`${t.dir}/composer.json`,r);if(!s)return[];let o=new Set;for(let a of["require","require-dev"]){let l=s[a];if(!(!l||typeof l!="object"))for(let c of Object.keys(l))c!==t.name&&n.has(c)&&o.add(c)}return[...o]}function k_(e,t,n,r){for(let s of["build.gradle","build.gradle.kts"]){let o=G(I(e,t.dir,s));if(!o)continue;let a=new Set;for(let l of o.matchAll(/project\s*\(\s*["']:?([^"']+)["']\s*\)/g)){let c=l[1].replace(/:/g,"/"),d=r.get(c)??(n.has(c)?c:void 0);d&&d!==t.name&&a.add(d)}return[...a]}return[]}function E_(e,t,n,r,s){switch(t.kind){case"cargo":return y_(e,t,n,r);case"go":return b_(e,t,n,r);case"maven":return w_(e,t,n);case"uv":return x_(e,t,n);case"composer":return S_(e,t,n,s);case"gradle":return k_(e,t,n,r);default:return h_(e,t,n,s)}}function v_(e){let t=new Map(e.map(o=>[o.name,[...o.dependsOn??[]].sort(M)])),n=new Map,r=[],s=o=>{n.set(o,"visiting"),r.push(o);for(let a of t.get(o)??[])if(t.has(a)){if(n.get(a)==="visiting")return[...r.slice(r.indexOf(a)),a];if(!n.has(a)){let l=s(a);if(l)return l}}return r.pop(),n.set(o,"done"),null};for(let o of[...t.keys()].sort(M))if(!n.has(o)){let a=s(o);if(a)return a}}function R_(e){let t=new Map(e.map(r=>[r.name,new Set(r.dependsOn??[])])),n=[];for(;t.size>0;){let r=[...t.entries()].filter(([,s])=>[...s].every(o=>!t.has(o))).map(([s])=>s).sort(M);if(!r.length){n.push(...[...t.keys()].sort(M));break}for(let s of r)n.push(s),t.delete(s)}return n}function nn(e){let t=[],n=new Map,{positives:r,negations:s}=c_(e,t),o=r.length?r:d_(e,t);if(o.length){let f=new Map;for(let{pattern:m,kind:p}of o)Ys(e,m,f,p,t);let u=s.map(ma);for(let[m,p]of f)u.some(g=>g.test(m))||n.set(m,p)}u_(e,n,t),f_(e,n,t),m_(e,n,t),p_(e,n,t),g_(e,n,t),__(e,n,t);let a=[...n.values()].sort((f,u)=>M(f.dir,u.dir)),l=new Set(a.map(f=>f.name)),c=new Map(a.map(f=>[f.dir,f.name]));for(let f of a){let u=E_(e,f,l,c,t);u.length&&(f.dependsOn=u.sort(M))}let d=[...a].sort((f,u)=>u.dir.length-f.dir.length);return{packages:a,cycle:v_(a),topoOrder:R_(a),warnings:[...new Set(t)].sort(M),packageOf:f=>d.find(u=>f===u.dir||f.startsWith(u.dir+"/"))}}var Kg,Xg,Sr=F(()=>{"use strict";k();xe();oe();Ae();Y();Ce();Kg=new Set(["node_modules",".git","dist","build","target","coverage"]),Xg=4});function M_(e,t){return e.modules.find(n=>n.slug===t)?.community}function O_(e,t){let n=e.length,r=new Map(e.map((l,c)=>[l,c])),s=Array.from({length:n},()=>new Map);for(let l of t){if(l.dangling)continue;let c=r.get(l.from),d=r.get(l.to);c===void 0||d===void 0||c===d||(s[c].set(d,(s[c].get(d)??0)+l.weight),s[d].set(c,(s[d].get(c)??0)+l.weight))}let o=s.map(l=>{let c=0;for(let d of l.values())c+=d;return c}),a=o.reduce((l,c)=>l+c,0);return{n,adj:s,k:o,twoM:a}}function pa(e){let t=new Map,n=new Array(e.length);for(let r=0;rf);if(s===0)return pa(o);let a=r.slice(),l=!0,c=0;for(;l&&cy-h)){if(g===f)continue;let y=u.get(g)-Fd*r[d]*a[g]/s;y>p+T_&&(p=y,m=g)}a[m]+=r[d],m!==f&&(o[d]=m,l=!0)}}return pa(o)}function P_(e,t,n){let r=Array.from({length:n},()=>new Map);for(let a=0;a{let l=0;for(let c of a.values())l+=c;return l}),o=s.reduce((a,l)=>a+l,0);return{n,adj:r,k:s,twoM:o}}function Pd(e){if(e.n===0)return[];let t=e,n=Array.from({length:e.n},(r,s)=>s);for(let r=0;rn&&n.length>0)}function $_(e,t){let n=t.length,r=new Map;t.forEach((c,d)=>r.set(c,d));let s=Array.from({length:n},()=>new Map);for(let c=0;c{let d=0;for(let f of c.values())d+=f;return d}),a=o.reduce((c,d)=>c+d,0),l=Pd({n,adj:s,k:o,twoM:a});return $d(l).map(c=>c.map(d=>t[d]))}function L_(e,t,n){let r=[];for(let s of e){if(s.length>I_*n&&s.length>=N_){let o=$_(t,s);if(o.length>1){r.push(...o);continue}}r.push(s)}return r}function D_(e,t){if(e.length!==t.length)return t.length-e.length;for(let n=0;n({id:Number(u),set:new Set(m)})),o=[];e.forEach((u,m)=>{for(let p of s){let g=0;for(let y of u)p.set.has(y)&&g++;g>0&&o.push({ni:m,prevId:p.id,inter:g})}}),o.sort((u,m)=>m.inter-u.inter||u.ni-m.ni||u.prevId-m.prevId);let a=new Map,l=new Set;for(let u of o)a.has(u.ni)||l.has(u.prevId)||(a.set(u.ni,u.prevId),l.add(u.prevId));let c=new Set;for(let u=0;u=0&&mf.slug).sort(M),o=O_(s,t),a=Pd(o),c=L_($d(a),o,s.length).map(f=>f.map(u=>s[u]).sort(M));c.sort(D_);let d=j_(c,n);return c.forEach((f,u)=>{for(let m of f)r.set(m,d[u])}),r}var Fd,C_,A_,T_,I_,N_,_a=F(()=>{"use strict";k();Y();Fd=1,C_=20,A_=10,T_=1e-12,I_=.25,N_=10});function Qs(e){let t=new Map,n=new Map;for(let a of e.modules)a.community!==void 0&&t.set(a.slug,a.community),n.set(a.slug,a.tier);let r=new Map,s=(a,l)=>ar.get(s(a.comms[0],a.comms[1]))<=U_).map(a=>({from:a.edge.from,to:a.edge.to,kind:a.edge.kind,weight:a.edge.weight,communities:a.comms,pairEdges:r.get(s(a.comms[0],a.comms[1]))})).sort((a,l)=>a.pairEdges-l.pairEdges||M(a.from,l.from)||M(a.to,l.to)).slice(0,W_)}function z_(e,t,n){return(e.surprises??Qs(e)).some(s=>s.from===t&&s.to===n)}var W_,U_,B_,ha=F(()=>{"use strict";k();Y();W_=24,U_=2,B_=new Set(["import","call","use"])});function H_(e){let t={};for(let n of Object.keys(e).sort(M))t[n]=e[n];return t}function In(e){let t={...e,languages:H_(e.languages)};return JSON.stringify(t,null,2)+` -`}var ei=F(()=>{"use strict";k();Y()});function Ah(e,t){return t!=="string"?!0:e.length>=Mh||Ch.test(e)}function Fh(e){if(!e)return!1;for(let t=0;t")&&!"=!<>+-*/%&|^".includes(e[t-1]??""))return Oh.test(e.slice(t+1));return!1}function Ph(e,t){let n;for(let r of e){if(!vh.has(r.kind)||Fh(r.signature))continue;let s=r.endLine??r.line;s-r.line>Rh||ts||(!n||r.line>n.line)&&(n=r)}return n}function rn(e,t={}){let n=t.minFiles??qd.minFiles,r=t.minCount??qd.minCount,s=new Map;for(let a of e.files)if(a.literals?.length&&!(!t.includeTests&&$t(a.rel)))for(let l of a.literals){if(t.kinds&&!t.kinds.has(l.kind)||!Ah(l.value,l.kind))continue;let c=`${l.kind}\0${l.value}`,d=s.get(c);d||s.set(c,d={value:l.value,kind:l.kind,sites:[]});let f=Ph(a.symbols,l.line);d.sites.push(f?{file:a.rel,line:l.line,holder:f.name,holderExported:f.exported}:{file:a.rel,line:l.line})}let o=[];for(let a of s.values()){let l=new Set(a.sites.map(p=>p.file));if(l.sizep.holder),d=a.sites.filter(p=>!p.holder),f=new Set(c.map(p=>p.holder)),m=new Set(c.map(p=>`${p.file}\0${p.holder}`)).size>=2?"competing":c.length>0?"bypassed":"uncentralized";if(a.kind==="number"){if(f.size!==1||d.length===0)continue;m="bypassed"}m==="bypassed"&&d.length===0||o.push({value:a.value,kind:a.kind,tier:m,holders:c.sort(Gd),literals:d.sort(Gd),files:l.size,count:a.sites.length})}return o.sort((a,l)=>Vd(a.tier)-Vd(l.tier)||l.files-a.files||l.count-a.count||M(a.value,l.value)),{duplications:o,families:$h(o)}}function Gd(e,t){return M(e.file,t.file)||e.line-t.line}function Vd(e){return e==="competing"?0:e==="bypassed"?1:2}function $h(e){let t=new Map;for(let r of e){if(r.kind!=="string"||!Th.test(r.value))continue;let s=Lh(r.value);if(!s)continue;let o=t.get(s);o?o.push(r):t.set(s,[r])}let n=[];for(let[r,s]of t){if(s.lengths.files-r.files||s.count-r.count||M(r.prefix,s.prefix)),n}function Lh(e){let t=e.startsWith("/")?e.slice(1):e,n=t.search(/[/:]/);if(n<=0)return;let r=(e.startsWith("/")?"/":"")+t.slice(0,n);return r.length>=Nh?r:void 0}var Jd,qd,vh,Rh,Mh,Ch,Th,Ih,Nh,Oh,kr=F(()=>{"use strict";k();vn();Y();Jd=24,qd={minFiles:2,minCount:3},vh=new Set(["const","constant","variable","enum","enumerator","property","field","static"]),Rh=12,Mh=6,Ch=/[/:._-]/;Th=/^[/@a-z0-9][\w./:@-]*$/i,Ih=2,Nh=4,Oh=/^\s*(?:async\b|function\b|\(|[A-Za-z_$][\w$]*\s*=>)/});function Dh(e,t={}){return Et(Pe(e,t),t)}function Et(e,t={}){let n=Zo(e),{modules:r,moduleOf:s}=Ho(e),o=ta(e,n,r,s,t.meta),a=ga(o.modules,o.moduleEdges,t.previousCommunities);for(let u of o.modules){let m=a.get(u.slug);m!==void 0&&(u.community=m)}Ko(o);let l=pr(o);for(let u of o.files)l.testFiles.has(u.rel)&&(u.testFile=!0);for(let u of o.modules){let m=l.testedByModule.get(u.slug);m?.length&&(u.testedBy=m)}let c=Qs(o);c.length&&(o.surprises=c);let{duplications:d}=rn(e);d.length&&(o.literalDuplications=d.slice(0,Jd));let f=Jo(e,Vs(e),t.meta?.schemaVersion);return{scan:e,graph:o,symbols:f}}var ri=F(()=>{"use strict";k();Ft();mt();Ds();Js();_a();qs();vn();ha();kr();cr()});function Wh(e){return e.sort((t,n)=>M(t.file,n.file)||t.line-n.line)}function Uh(e,t,n){let r=["--no-heading","--line-number","--null","--color=never","--no-messages","--hidden","--no-require-git","--no-ignore-global","--no-ignore-exclude","--no-ignore-parent","--no-ignore-dot","--max-filesize","1M"];for(let c of qt)r.push("--glob",`!**/${c}/**`);for(let c of Wi)r.push("--iglob",`!**/${c}`);for(let c of Ui)r.push("--iglob",`!**/*${c}`);r.push("--glob","!*.min.js","--glob","!*.min.css"),n.ignoreCase&&r.push("--ignore-case");let s=n.globs??[],o=c=>c.startsWith("/")?c:`/${c}`;for(let c of s.filter(d=>!d.startsWith("!")))r.push("--glob",o(c));for(let c of s.filter(d=>d.startsWith("!")))r.push("--glob",`!${o(c.slice(1))}`);r.push("--regexp",t,"./");let a=pe("rg",r,{cwd:e});if(a.missing||!a.ok&&a.status!==1)return;let l=[];for(let c of a.stdout.split(` -`)){if(!c)continue;let d=c.indexOf("\0");if(d===-1)continue;let f=c.slice(0,d).replace(/^\.\//,""),u=c.slice(d+1),m=u.indexOf(":");m!==-1&&l.push({file:f,line:Number(u.slice(0,m)),text:u.slice(m+1)})}return l}function Bh(e,t,n){let r=ec(n.globs?.map(o=>o.replace(/^(!?)\//,"$1"))),s=[];for(let o of Fe(e).files){if(r&&!r(o.rel))continue;let a=G(o.abs);if(!a)continue;let l=a.split(` -`);for(let c=0;c{"use strict";k();Ae();Hn();Ce();Y();jh=200});function vt(e){let t=R.env.CODEINDEX_EMBED_DIR,n=[];t&&n.push(t),e&&n.push(I(e,".codeindex",Kd)),n.push(I(R.cwd(),".codeindex",Kd));for(let r of n)if(H(I(r,"model.json")))return r}function qh(e){return vt(e)!==void 0}function ba(e,t){let{modelId:n,dim:r,vocab:s,weights:o,unk:a}=e??{};if(typeof n!="string"||!n)throw new Error(`embed model: missing modelId in ${t}`);if(!Number.isInteger(r)||r<=0)throw new Error(`embed model: bad dim ${r} in ${t}`);if(!Array.isArray(s)||!Array.isArray(o)||s.length!==o.length)throw new Error(`embed model: vocab/weights length mismatch in ${t}`);let l=s.length,c=new Float64Array(l*r),d=new Map;for(let m=0;m{"use strict";k();cs();xe();oe();it=1,Kd="models",zh="https://github.com/maxgfr/codeindex/releases/download/embed-model-v1/model.json",Hh="163ad053eab4e9a80d421ed4164f32292c83290f02fbbe6fe4b9b1cd6ea18d34"});function Zd(e){let t=_t(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2"),n=[];for(let r of t.toLowerCase().split(/[^a-z0-9]+/))r&&n.push(r);return n}function Yd(e,t){if(!e)return[];let n=[],r=0,s=e.length;for(;rr;){let l=r===0?e.slice(r,o):"##"+e.slice(r,o),c=t.vocab.get(l);if(c!==void 0){a=c;break}o--}if(a===-1)return t.unkId>=0?[t.unkId]:[];n.push(a),r=o}return n}function Qd(e,t){let n=[];for(let r of Zd(e))for(let s of Yd(r,t))n.push(s);return n}function eu(e){let t=Math.floor(e),n=e-t;return n<.5?t:n>.5?t+1:t%2===0?t:t+1}function Rr(e){let t=e.length,n=new Int8Array(t),r=0;for(let o=0;ovr?a=vr:a<-vr&&(a=-vr),n[o]=a}return n}function Mr(e,t){let{dim:n,weights:r}=e,s=Qd(t,e);if(s.length===0)return new Int8Array(n);let o=new Float64Array(n);for(let l of s){let c=l*n;for(let d=0;d{"use strict";k();Ce();vr=127});function Gh(e,t,n,r){return[t,n??"",r??"",e.replace(/\//g," ")].join(` -`)}function Vh(e,t,n,r){return[t??"",n??"",...r,e.replace(/\//g," ")].join(` -`)}function ii(e){let t=[];for(let n of e.files){let r=new Set,s=!1;for(let o of n.symbols)r.has(o.name)||(r.add(o.name),s=!0,t.push({file:n.rel,symbol:o.name,line:o.line,text:Gh(n.rel,o.name,o.signature,n.summary)}));if(!s){let o=Vh(n.rel,n.title,n.summary,n.headings);o.replace(/\s+/g,"")&&t.push({file:n.rel,text:o})}}return t}function on(e,t){let n=ii(e).map(r=>{let s={file:r.file,vec:Mr(t,r.text)};return r.symbol!==void 0&&(s.symbol=r.symbol),r.line!==void 0&&(s.line=r.line),s});return{embedVersion:it,modelId:t.modelId,dim:t.dim,records:n}}function oi(e){let t=JSON.stringify({embedVersion:e.embedVersion,modelId:e.modelId,dim:e.dim,count:e.records.length,records:e.records.map(a=>({file:a.file,symbol:a.symbol??"",line:a.line??0}))}),n=new TextEncoder().encode(t),r=e.records.length*e.dim,s=new Uint8Array(8+n.length+r);s.set([67,73,69,49],0),new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(4,n.length,!0),s.set(n,8);let o=8+n.length;for(let a of e.records)for(let l=0;le.byteLength)throw new Error("embeddings.bin: truncated header");let r=JSON.parse(new TextDecoder().decode(e.subarray(8,8+n))),s=8+n,{dim:o}=r;if(s+r.records.length*o>e.byteLength)throw new Error("embeddings.bin: truncated body");let a=r.records.map((l,c)=>{let d=new Int8Array(e.buffer.slice(e.byteOffset+s+c*o,e.byteOffset+s+(c+1)*o)),f={file:l.file,vec:d};return l.symbol&&(f.symbol=l.symbol),l.line&&(f.line=l.line),f});return{embedVersion:r.embedVersion,modelId:r.modelId,dim:o,records:a}}var Jh,On=F(()=>{"use strict";k();Cr();sn();Jh="CIE1"});function an(e,t,n,r={}){let s=r.limit??Xh,o=Lt(e,t,{limit:Math.max(s,50),fuzzy:r.fuzzy}),a=r.queryVec??(r.model?Mr(r.model,t):void 0);if(!a||!n||n.records.length===0)return o.slice(0,s);let l=new Map;for(let p of n.records){let g=xa(a,p.vec),y=l.get(p.file);(!y||g>y.score)&&l.set(p.file,{score:g,symbol:p.symbol})}let c=[...l.entries()].filter(([,p])=>p.score>0).sort((p,g)=>g[1].score-p[1].score||M(p[0],g[0])).map(([p])=>p),d=o.map(p=>p.file),f=$i([d,c],p=>p,r.rrfK??Zh),u=new Map(o.map(p=>[p.file,p]));return[...f.entries()].sort((p,g)=>g[1]-p[1]||M(p[0],g[0])).map(([p,g])=>{let y=u.get(p),h={file:p,score:Number(g.toFixed(4)),matchedTerms:y?.matchedTerms??[],topSymbols:y?.topSymbols??[]},S=l.get(p);return S?.symbol&&(h.semanticSymbol=S.symbol),y?.fuzzyTerms&&(h.fuzzyTerms=y.fuzzyTerms),h}).slice(0,s)}var Xh,Zh,ai=F(()=>{"use strict";k();Ce();Y();Mn();Cr();Xh=20,Zh=60});function Ut(e={}){let t=e.url??R.env.CODEINDEX_EMBED_ENDPOINT;return t&&t.trim()?t.trim():void 0}function tu(e){return e.replace(/\/+$/,"")}function nu(e){let t=tu(e);return t.endsWith("/embed")?t:t+"/embed"}function ru(e){return tu(e).replace(/\/embed$/,"")+"/healthz"}function su(e){if(typeof e.timeoutMs=="number")return e.timeoutMs;let t=Number(R.env.CODEINDEX_EMBED_TIMEOUT_MS);return Number.isFinite(t)&&t>0?t:3e4}async function Sa(e,t={}){let n=Ut(t);if(!n)throw new Error("no embedding endpoint configured (set CODEINDEX_EMBED_ENDPOINT or pass opts.url)");let r=nu(n),s=new AbortController,o=setTimeout(()=>s.abort(),su(t));try{let a=await fetch(r,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify({texts:e}),signal:s.signal});if(!a.ok)throw new Error(`embedding endpoint ${r} returned HTTP ${a.status}`);let c=(await a.json()).vectors;if(!Array.isArray(c)||!c.every(d=>Array.isArray(d)&&d.every(f=>typeof f=="number")))throw new Error(`embedding endpoint ${r} returned a malformed { vectors } payload`);return c}finally{clearTimeout(o)}}async function Ar(e,t={}){let n=new AbortController,r=setTimeout(()=>n.abort(),su(t));try{return(await fetch(ru(e),{signal:n.signal,headers:t.headers})).ok}catch{return!1}finally{clearTimeout(r)}}async function Tr(e,t={}){let[n]=await Sa([e],t);if(!n)throw new Error("embedding endpoint returned no vector for the query");return Rr(n)}async function Ir(e,t={}){let n=ii(e),r=t.batchSize&&t.batchSize>0?t.batchSize:64,s=[],o=0;for(let a=0;ad.text),t);if(c.length!==l.length)throw new Error(`embedding endpoint returned ${c.length} vectors for ${l.length} texts`);for(let d=0;do&&(o=u.length);let m={file:f.file,vec:u};f.symbol!==void 0&&(m.symbol=f.symbol),f.line!==void 0&&(m.line=f.line),s.push(m)}}return{embedVersion:it,modelId:"endpoint",dim:o,records:s}}var li=F(()=>{"use strict";k();Cr();sn();On()});function ln(e,t,n={}){let r=(n.budgetTokens??1024)*iu,s=n.maxSymbolsPerFile??8,o=[...t.files].filter(f=>f.fileKind==="code").sort((f,u)=>(u.pagerank??0)-(f.pagerank??0)||u.symbols-f.symbols||M(f.rel,u.rel)),a=new Map(e.files.map(f=>[f.rel,f])),c=`# repo map \u2014 ${t.fileCount} files +`),Bd(t)}function pa(e,t){try{return Q(ma(e,t),"utf8")}catch{return}}function ga(e,t){let n=ma(e,t);try{ve(n)}catch{return!1}return Ge(n),!0}function _a(e){let t=I(e,...Ud),n=[],r=(s,o)=>{let a;try{a=hn(s,{withFileTypes:!0})}catch{return}for(let l of a)l.isDirectory()?r(I(s,l.name),o?`${o}/${l.name}`:l.name):l.name.endsWith(".md")&&n.push(o?`${o}/${l.name.slice(0,-3)}`:l.name.slice(0,-3))};return r(t,""),n.sort()}var Ud,ei=O(()=>{"use strict";E();xe();ae();Ud=[".codeindex","memories"]});function St(e,t,n){let r=q(e);if(r)try{let s=JSON.parse(r);if(s&&typeof s=="object")return s;t&&n&&n.push(`malformed ${t}: not a JSON object`);return}catch(s){if(t&&n){let o=String(s instanceof Error?s.message:s).split(` +`)[0];n.push(`malformed ${t}: ${o}`)}return}}function jt(e,t){let n=new RegExp(`^\\[${qe(t)}\\]\\s*$([\\s\\S]*?)(?=^\\[|$(?![\\s\\S]))`,"m"),r=e.match(n);return r?r[1]:null}function Sr(e,t){let n=e.match(new RegExp(`${qe(t)}\\s*=\\s*\\[([^\\]]*)\\]`));return n?n[1].split(/\r?\n/).map(r=>r.replace(/#.*$/,"")).join(` +`).split(",").map(r=>r.trim().replace(/^["']|["']$/g,"")).filter(Boolean):[]}function Tn(e,t){return e?.match(new RegExp(`^\\s*${qe(t)}\\s*=\\s*["']([^"']+)["']`,"m"))?.[1]}function ha(e){let t="";for(let n=0;nw_(e,t,n,r),o=()=>x_(e,t),a=()=>S_(e,t),l=()=>k_(e,t),c=()=>E_(e,t),d=()=>v_(e,t,r),f=()=>R_(e,t,r),m=n==="go"?[a,s,o,l,c,d,f]:n==="uv"?[c,s,o,a,l,d,f]:n==="composer"?[d,s,c,o,a,l,f]:n==="gradle"?[s,l,o,a,c,d,f,()=>M_(e,t)]:[s,o,a,l,c,d,f];for(let p of m){let g=p();if(g)return g}}function A_(e){return e.replace(/[\s\S]*?<\/parent>/g,"").replace(/[\s\S]*?<\/dependencies>/g,"").match(/\s*([^<]+?)\s*<\/artifactId>/)?.[1]}function kr(e,t,n,r,s){let o=t.replace(/^\.\//,"").replace(/\/+$/,"");if(!o||o==="."||n.has(o)||o.split("/").includes(".."))return;let a=C_(e,o,r,s);a&&n.set(o,a)}function T_(e,t){try{return ve(I(e,t)).isDirectory()}catch{return!1}}function zd(e,t){let n;try{n=hn(t?I(e,t):e,{withFileTypes:!0})}catch{return[]}return n.filter(r=>r.isDirectory()&&!r.name.startsWith(".")&&!y_.has(r.name)).map(r=>t?`${t}/${r.name}`:r.name).sort(M)}function Hd(e,t,n,r){if(!(n>b_))for(let s of zd(e,t))r.push(s),Hd(e,s,n+1,r)}function I_(e,t){let n=t.split("/").filter(s=>s&&s!==".");if(n.includes(".."))return[];let r=[""];for(let s of n){let o=new Set;if(s==="**")for(let a of r){a&&o.add(a);let l=[];Hd(e,a,0,l);for(let c of l)o.add(c)}else if(s.includes("*")){let a=new RegExp(`^${s.split("*").map(qe).join("[^/]*")}$`);for(let l of r)for(let c of zd(e,l))a.test(c.split("/").pop())&&o.add(c)}else for(let a of r){let l=a?`${a}/${s}`:s;T_(e,l)&&o.add(l)}if(r=[...o],!r.length)return[]}return r.filter(Boolean)}function ti(e,t,n,r,s){let o=t.replace(/^\.\//,"").replace(/\/+$/,"");if(o){if(!o.includes("*")){kr(e,o,n,r,s);return}for(let a of I_(e,o))kr(e,a,n,r,s)}}function N_(e,t){let n=[],r=[],s=(d,f)=>{let u=d.trim();u&&(u.startsWith("!")?r.push(u.slice(1)):n.push({pattern:u,kind:f}))},a=St(I(e,"package.json"),"package.json",t)?.workspaces;if(Array.isArray(a))for(let d of a)typeof d=="string"&&s(d,"npm");else if(a&&typeof a=="object"&&Array.isArray(a.packages))for(let d of a.packages)typeof d=="string"&&s(d,"npm");let l=q(I(e,"pnpm-workspace.yaml")),c=!1;for(let d of l.split(/\r?\n/)){if(/^\S/.test(d)){c=/^packages\s*:/.test(d);continue}if(!c)continue;let f=d.match(/^\s*-\s*['"]?([^'"#]+?)['"]?\s*(?:#.*)?$/);f&&s(f[1].trim(),"pnpm")}return{positives:n,negations:r}}function F_(e,t){let n=St(I(e,"lerna.json"),"lerna.json",t);if(n&&Array.isArray(n.packages))return n.packages.filter(s=>typeof s=="string").map(s=>({pattern:s,kind:"lerna"}));let r=St(I(e,"nx.json"),"nx.json",t);if(r){let s=r.workspaceLayout??{},o=typeof s.appsDir=="string"?s.appsDir:"apps",a=typeof s.libsDir=="string"?s.libsDir:"libs";return[...new Set([o,a])].map(l=>({pattern:`${l}/*`,kind:"nx"}))}return[]}function O_(e,t,n){let r=q(I(e,"Cargo.toml"));if(!r)return;let s=jt(r,"workspace");if(!s)return;let o=Sr(s,"members");if(!o.length)return;let a=Sr(s,"exclude").map(ha),l=new Map;for(let c of o)ti(e,c,l,"cargo",n);for(let[c,d]of l)a.some(f=>f.test(c))||t.has(c)||t.set(c,d)}function P_(e,t,n){let r=q(I(e,"go.work"));if(!r)return;let s=[];for(let o of r.matchAll(/^use\s*\(([\s\S]*?)\)/gm))for(let a of o[1].split(/\r?\n/)){let l=a.replace(/\/\/.*$/,"").trim();l&&s.push(l)}for(let o of r.matchAll(/^use\s+([^\s(]+)/gm))s.push(o[1]);for(let o of s)o==="."||o==="./"||kr(e,o,t,"go",n)}function $_(e,t,n){let r=q(I(e,"pom.xml"));if(!r)return;let s=r.match(/([\s\S]*?)<\/modules>/)?.[1];if(s)for(let o of s.matchAll(/\s*([^<]+?)\s*<\/module>/g))kr(e,o[1],t,"maven",n)}function D_(e,t,n){let r=q(I(e,"pyproject.toml"));if(!r)return;let s=jt(r,"tool.uv.workspace");if(!s)return;let o=Sr(s,"members");if(!o.length)return;let a=Sr(s,"exclude").map(ha),l=new Map;for(let c of o)ti(e,c,l,"uv",n);for(let[c,d]of l)a.some(f=>f.test(c))||t.has(c)||t.set(c,d)}function L_(e,t,n){let s=St(I(e,"composer.json"),"composer.json",n)?.repositories;if(Array.isArray(s))for(let o of s){if(!o||typeof o!="object")continue;let{type:a,url:l}=o;a==="path"&&typeof l=="string"&&l&&ti(e,l,t,"composer",n)}}function j_(e,t,n){for(let r of["settings.gradle","settings.gradle.kts"]){let s=q(I(e,r));if(s){for(let o of s.split(/\r?\n/))if(/^\s*include[\s(]/.test(o))for(let a of o.matchAll(/["']([^"']+)["']/g)){let l=a[1].replace(/^:/,"").replace(/:/g,"/");l&&kr(e,l,t,"gradle",n)}}}}function W_(e,t,n,r){let s=St(I(e,t.dir,"package.json"),`${t.dir}/package.json`,r);if(!s)return[];let o=new Set;for(let a of["dependencies","devDependencies","peerDependencies"]){let l=s[a];if(!(!l||typeof l!="object"))for(let c of Object.keys(l))c!==t.name&&n.has(c)&&o.add(c)}return[...o]}function Gd(e,t){let n=`${e}/${t}`.split("/"),r=[];for(let s of n)!s||s==="."||(s===".."?r.pop():r.push(s));return r.join("/")}function U_(e,t,n,r){let s=q(I(e,t.dir,"Cargo.toml"));if(!s)return[];let o=new Set;for(let a of["dependencies","dev-dependencies","build-dependencies"]){let l=jt(s,a);if(l)for(let c of l.split(/\r?\n/)){let d=c.match(/^\s*([A-Za-z0-9_-]+)\s*=\s*(.+)$/);if(!d)continue;let f=d[1];if(f!==t.name&&n.has(f)){o.add(f);continue}let u=d[2].match(/path\s*=\s*["']([^"']+)["']/);if(u){let m=r.get(Gd(t.dir,u[1]));m&&m!==t.name&&o.add(m)}}}return[...o]}function B_(e,t,n,r){let s=q(I(e,t.dir,"go.mod"));if(!s)return[];let o=new Set;for(let a of s.matchAll(/^\s*(?:require\s+)?([^\s/(][^\s]*)\s+v[^\s]+/gm)){let l=a[1];l!==t.name&&n.has(l)&&o.add(l)}for(let a of s.matchAll(/^\s*(?:replace\s+)?(\S+)(?:\s+\S+)?\s*=>\s*(\.\.?\/\S+)/gm)){let l=r.get(Gd(t.dir,a[2]));l&&l!==t.name&&o.add(l)}return[...o]}function z_(e,t,n){let r=q(I(e,t.dir,"pom.xml"));if(!r)return[];let s=new Set;for(let o of r.replace(/[\s\S]*?<\/parent>/g,"").matchAll(/([\s\S]*?)<\/dependency>/g)){let a=o[1].match(/\s*([^<]+?)\s*<\/artifactId>/)?.[1];a&&a!==t.name&&n.has(a)&&s.add(a)}return[...s]}function H_(e,t,n){let r=q(I(e,t.dir,"pyproject.toml"));if(!r)return[];let s=new Set,o=jt(r,"project");if(o)for(let l of Sr(o,"dependencies")){let c=l.match(/^[A-Za-z0-9_.-]+/)?.[0];c&&c!==t.name&&n.has(c)&&s.add(c)}let a=jt(r,"tool.uv.sources");if(a)for(let l of a.split(/\r?\n/)){let c=l.match(/^\s*([A-Za-z0-9_.-]+)\s*=\s*\{[^}]*workspace\s*=\s*true/);c&&c[1]!==t.name&&n.has(c[1])&&s.add(c[1])}return[...s]}function G_(e,t,n,r){let s=St(I(e,t.dir,"composer.json"),`${t.dir}/composer.json`,r);if(!s)return[];let o=new Set;for(let a of["require","require-dev"]){let l=s[a];if(!(!l||typeof l!="object"))for(let c of Object.keys(l))c!==t.name&&n.has(c)&&o.add(c)}return[...o]}function q_(e,t,n,r){for(let s of["build.gradle","build.gradle.kts"]){let o=q(I(e,t.dir,s));if(!o)continue;let a=new Set;for(let l of o.matchAll(/project\s*\(\s*["']:?([^"']+)["']\s*\)/g)){let c=l[1].replace(/:/g,"/"),d=r.get(c)??(n.has(c)?c:void 0);d&&d!==t.name&&a.add(d)}return[...a]}return[]}function V_(e,t,n,r,s){switch(t.kind){case"cargo":return U_(e,t,n,r);case"go":return B_(e,t,n,r);case"maven":return z_(e,t,n);case"uv":return H_(e,t,n);case"composer":return G_(e,t,n,s);case"gradle":return q_(e,t,n,r);default:return W_(e,t,n,s)}}function J_(e){let t=new Map(e.map(o=>[o.name,[...o.dependsOn??[]].sort(M)])),n=new Map,r=[],s=o=>{n.set(o,"visiting"),r.push(o);for(let a of t.get(o)??[])if(t.has(a)){if(n.get(a)==="visiting")return[...r.slice(r.indexOf(a)),a];if(!n.has(a)){let l=s(a);if(l)return l}}return r.pop(),n.set(o,"done"),null};for(let o of[...t.keys()].sort(M))if(!n.has(o)){let a=s(o);if(a)return a}}function K_(e){let t=new Map(e.map(r=>[r.name,new Set(r.dependsOn??[])])),n=[];for(;t.size>0;){let r=[...t.entries()].filter(([,s])=>[...s].every(o=>!t.has(o))).map(([s])=>s).sort(M);if(!r.length){n.push(...[...t.keys()].sort(M));break}for(let s of r)n.push(s),t.delete(s)}return n}function rn(e){let t=[],n=new Map,{positives:r,negations:s}=N_(e,t),o=r.length?r:F_(e,t);if(o.length){let f=new Map;for(let{pattern:m,kind:p}of o)ti(e,m,f,p,t);let u=s.map(ha);for(let[m,p]of f)u.some(g=>g.test(m))||n.set(m,p)}O_(e,n,t),P_(e,n,t),$_(e,n,t),D_(e,n,t),L_(e,n,t),j_(e,n,t);let a=[...n.values()].sort((f,u)=>M(f.dir,u.dir)),l=new Set(a.map(f=>f.name)),c=new Map(a.map(f=>[f.dir,f.name]));for(let f of a){let u=V_(e,f,l,c,t);u.length&&(f.dependsOn=u.sort(M))}let d=[...a].sort((f,u)=>u.dir.length-f.dir.length);return{packages:a,cycle:J_(a),topoOrder:K_(a),warnings:[...new Set(t)].sort(M),packageOf:f=>d.find(u=>f===u.dir||f.startsWith(u.dir+"/"))}}var y_,b_,Er=O(()=>{"use strict";E();xe();ae();Ne();Y();Ae();y_=new Set(["node_modules",".git","dist","build","target","coverage"]),b_=4});function X_(e,t){return e.modules.find(n=>n.slug===t)?.community}function nh(e,t){let n=e.length,r=new Map(e.map((l,c)=>[l,c])),s=Array.from({length:n},()=>new Map);for(let l of t){if(l.dangling)continue;let c=r.get(l.from),d=r.get(l.to);c===void 0||d===void 0||c===d||(s[c].set(d,(s[c].get(d)??0)+l.weight),s[d].set(c,(s[d].get(c)??0)+l.weight))}let o=s.map(l=>{let c=0;for(let d of l.values())c+=d;return c}),a=o.reduce((l,c)=>l+c,0);return{n,adj:s,k:o,twoM:a}}function ya(e){let t=new Map,n=new Array(e.length);for(let r=0;rf);if(s===0)return ya(o);let a=r.slice(),l=!0,c=0;for(;l&&cy-h)){if(g===f)continue;let y=u.get(g)-qd*r[d]*a[g]/s;y>p+Q_&&(p=y,m=g)}a[m]+=r[d],m!==f&&(o[d]=m,l=!0)}}return ya(o)}function sh(e,t,n){let r=Array.from({length:n},()=>new Map);for(let a=0;a{let l=0;for(let c of a.values())l+=c;return l}),o=s.reduce((a,l)=>a+l,0);return{n,adj:r,k:s,twoM:o}}function Vd(e){if(e.n===0)return[];let t=e,n=Array.from({length:e.n},(r,s)=>s);for(let r=0;rn&&n.length>0)}function ih(e,t){let n=t.length,r=new Map;t.forEach((c,d)=>r.set(c,d));let s=Array.from({length:n},()=>new Map);for(let c=0;c{let d=0;for(let f of c.values())d+=f;return d}),a=o.reduce((c,d)=>c+d,0),l=Vd({n,adj:s,k:o,twoM:a});return Jd(l).map(c=>c.map(d=>t[d]))}function oh(e,t,n){let r=[];for(let s of e){if(s.length>eh*n&&s.length>=th){let o=ih(t,s);if(o.length>1){r.push(...o);continue}}r.push(s)}return r}function ah(e,t){if(e.length!==t.length)return t.length-e.length;for(let n=0;n({id:Number(u),set:new Set(m)})),o=[];e.forEach((u,m)=>{for(let p of s){let g=0;for(let y of u)p.set.has(y)&&g++;g>0&&o.push({ni:m,prevId:p.id,inter:g})}}),o.sort((u,m)=>m.inter-u.inter||u.ni-m.ni||u.prevId-m.prevId);let a=new Map,l=new Set;for(let u of o)a.has(u.ni)||l.has(u.prevId)||(a.set(u.ni,u.prevId),l.add(u.prevId));let c=new Set;for(let u=0;u=0&&mf.slug).sort(M),o=nh(s,t),a=Vd(o),c=oh(Jd(a),o,s.length).map(f=>f.map(u=>s[u]).sort(M));c.sort(ah);let d=lh(c,n);return c.forEach((f,u)=>{for(let m of f)r.set(m,d[u])}),r}var qd,Z_,Y_,Q_,eh,th,wa=O(()=>{"use strict";E();Y();qd=1,Z_=20,Y_=10,Q_=1e-12,eh=.25,th=10});function ni(e){let t=new Map,n=new Map;for(let a of e.modules)a.community!==void 0&&t.set(a.slug,a.community),n.set(a.slug,a.tier);let r=new Map,s=(a,l)=>ar.get(s(a.comms[0],a.comms[1]))<=dh).map(a=>({from:a.edge.from,to:a.edge.to,kind:a.edge.kind,weight:a.edge.weight,communities:a.comms,pairEdges:r.get(s(a.comms[0],a.comms[1]))})).sort((a,l)=>a.pairEdges-l.pairEdges||M(a.from,l.from)||M(a.to,l.to)).slice(0,ch)}function fh(e,t,n){return(e.surprises??ni(e)).some(s=>s.from===t&&s.to===n)}var ch,dh,uh,xa=O(()=>{"use strict";E();Y();ch=24,dh=2,uh=new Set(["import","call","use"])});function mh(e){let t={};for(let n of Object.keys(e).sort(M))t[n]=e[n];return t}function In(e){let t={...e,languages:mh(e.languages)};return JSON.stringify(t,null,2)+` +`}var ri=O(()=>{"use strict";E();Y()});function Yh(e,t){return t!=="string"?!0:e.length>=Xh||Zh.test(e)}function ry(e){if(!e)return!1;for(let t=0;t")&&!"=!<>+-*/%&|^".includes(e[t-1]??""))return ny.test(e.slice(t+1));return!1}function sy(e){let t=[];for(let n of e)Jh.has(n.kind)&&(ry(n.signature)||(n.endLine??n.line)-n.line>Kh||t.push(n));return t}function iy(e,t){let n;for(let r of e){let s=r.endLine??r.line;ts||(!n||r.line>n.line)&&(n=r)}return n}function sn(e,t={}){let n=t.minFiles??ru.minFiles,r=t.minCount??ru.minCount,s=new Map;for(let a of e.files){if(!a.literals?.length||!t.includeTests&&$t(a.rel))continue;let l;for(let c of a.literals){if(t.kinds&&!t.kinds.has(c.kind)||!Yh(c.value,c.kind))continue;let d=`${c.kind}\0${c.value}`,f=s.get(d);f||s.set(d,f={value:c.value,kind:c.kind,sites:[]});let u=iy(l??=sy(a.symbols),c.line);f.sites.push(u?{file:a.rel,line:c.line,holder:u.name,holderExported:u.exported}:{file:a.rel,line:c.line})}}let o=[];for(let a of s.values()){let l=new Set(a.sites.map(p=>p.file));if(l.sizep.holder),d=a.sites.filter(p=>!p.holder),f=new Set(c.map(p=>p.holder)),m=new Set(c.map(p=>`${p.file}\0${p.holder}`)).size>=2?"competing":c.length>0?"bypassed":"uncentralized";if(a.kind==="number"){if(f.size!==1||d.length===0)continue;m="bypassed"}m==="bypassed"&&d.length===0||o.push({value:a.value,kind:a.kind,tier:m,holders:c.sort(su),literals:d.sort(su),files:l.size,count:a.sites.length})}return o.sort((a,l)=>iu(a.tier)-iu(l.tier)||l.files-a.files||l.count-a.count||M(a.value,l.value)),{duplications:o,families:oy(o)}}function su(e,t){return M(e.file,t.file)||e.line-t.line}function iu(e){return e==="competing"?0:e==="bypassed"?1:2}function oy(e){let t=new Map;for(let r of e){if(r.kind!=="string"||!Qh.test(r.value))continue;let s=ay(r.value);if(!s)continue;let o=t.get(s);o?o.push(r):t.set(s,[r])}let n=[];for(let[r,s]of t){if(s.lengths.files-r.files||s.count-r.count||M(r.prefix,s.prefix)),n}function ay(e){let t=e.startsWith("/")?e.slice(1):e,n=t.search(/[/:]/);if(n<=0)return;let r=(e.startsWith("/")?"/":"")+t.slice(0,n);return r.length>=ty?r:void 0}var ou,ru,Jh,Kh,Xh,Zh,Qh,ey,ty,ny,vr=O(()=>{"use strict";E();vn();Y();ou=24,ru={minFiles:2,minCount:3},Jh=new Set(["const","constant","variable","enum","enumerator","property","field","static"]),Kh=12,Xh=6,Zh=/[/:._-]/;Qh=/^[/@a-z0-9][\w./:@-]*$/i,ey=2,ty=4,ny=/^\s*(?:async\b|function\b|\(|[A-Za-z_$][\w$]*\s*=>)/});function ly(e,t={}){return vt(Le(e,t),t)}function vt(e,t={}){let n=ta(e),{modules:r,moduleOf:s}=Jo(e),o=ia(e,n,r,s,t.meta),a=ba(o.modules,o.moduleEdges,t.previousCommunities);for(let u of o.modules){let m=a.get(u.slug);m!==void 0&&(u.community=m)}Qo(o);let l=_r(o);for(let u of o.files)l.testFiles.has(u.rel)&&(u.testFile=!0);for(let u of o.modules){let m=l.testedByModule.get(u.slug);m?.length&&(u.testedBy=m)}let c=ni(o);c.length&&(o.surprises=c);let{duplications:d}=sn(e);d.length&&(o.literalDuplications=d.slice(0,ou));let f=Yo(e,Xs(e),t.meta?.schemaVersion);return{scan:e,graph:o,symbols:f}}var oi=O(()=>{"use strict";E();Pt();pt();Ws();Zs();wa();Js();vn();xa();vr();ur()});function dy(e){return e.sort((t,n)=>M(t.file,n.file)||t.line-n.line)}function uy(e,t,n){let r=["--no-heading","--line-number","--null","--color=never","--no-messages","--hidden","--no-require-git","--no-ignore-global","--no-ignore-exclude","--no-ignore-parent","--no-ignore-dot","--max-filesize","1M"];for(let c of Gt)r.push("--glob",`!**/${c}/**`);for(let c of Bi)r.push("--iglob",`!**/${c}`);for(let c of zi)r.push("--iglob",`!**/*${c}`);r.push("--glob","!*.min.js","--glob","!*.min.css"),n.ignoreCase&&r.push("--ignore-case");let s=n.globs??[],o=c=>c.startsWith("/")?c:`/${c}`;for(let c of s.filter(d=>!d.startsWith("!")))r.push("--glob",o(c));for(let c of s.filter(d=>d.startsWith("!")))r.push("--glob",`!${o(c.slice(1))}`);r.push("--regexp",t,"./");let a=pe("rg",r,{cwd:e});if(a.missing||!a.ok&&a.status!==1)return;let l=[];for(let c of a.stdout.split(` +`)){if(!c)continue;let d=c.indexOf("\0");if(d===-1)continue;let f=c.slice(0,d).replace(/^\.\//,""),u=c.slice(d+1),m=u.indexOf(":");m!==-1&&l.push({file:f,line:Number(u.slice(0,m)),text:u.slice(m+1)})}return l}function fy(e,t,n){let r=oc(n.globs?.map(o=>o.replace(/^(!?)\//,"$1"))),s=[];for(let o of Pe(e).files){if(r&&!r(o.rel))continue;let a=q(o.abs);if(!a)continue;let l=a.split(` +`);for(let c=0;c{"use strict";E();Ne();Gn();Ae();Y();cy=200});function Rt(e){let t=R.env.CODEINDEX_EMBED_DIR,n=[];t&&n.push(t),e&&n.push(I(e,".codeindex",au)),n.push(I(R.cwd(),".codeindex",au));for(let r of n)if(H(I(r,"model.json")))return r}function gy(e){return Rt(e)!==void 0}function ka(e,t){let{modelId:n,dim:r,vocab:s,weights:o,unk:a}=e??{};if(typeof n!="string"||!n)throw new Error(`embed model: missing modelId in ${t}`);if(!Number.isInteger(r)||r<=0)throw new Error(`embed model: bad dim ${r} in ${t}`);if(!Array.isArray(s)||!Array.isArray(o)||s.length!==o.length)throw new Error(`embed model: vocab/weights length mismatch in ${t}`);let l=s.length,c=new Float64Array(l*r),d=new Map;for(let m=0;m{"use strict";E();ms();xe();ae();it=1,au="models",my="https://github.com/maxgfr/codeindex/releases/download/embed-model-v1/model.json",py="163ad053eab4e9a80d421ed4164f32292c83290f02fbbe6fe4b9b1cd6ea18d34"});function cu(e){let t=ht(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2"),n=[];for(let r of t.toLowerCase().split(/[^a-z0-9]+/))r&&n.push(r);return n}function du(e,t){if(!e)return[];let n=[],r=0,s=e.length;for(;rr;){let l=r===0?e.slice(r,o):"##"+e.slice(r,o),c=t.vocab.get(l);if(c!==void 0){a=c;break}o--}if(a===-1)return t.unkId>=0?[t.unkId]:[];n.push(a),r=o}return n}function uu(e,t){let n=[];for(let r of cu(e))for(let s of du(r,t))n.push(s);return n}function fu(e){let t=Math.floor(e),n=e-t;return n<.5?t:n>.5?t+1:t%2===0?t:t+1}function Cr(e){let t=e.length,n=new Int8Array(t),r=0;for(let o=0;oMr?a=Mr:a<-Mr&&(a=-Mr),n[o]=a}return n}function Ar(e,t){let{dim:n,weights:r}=e,s=uu(t,e);if(s.length===0)return new Int8Array(n);let o=new Float64Array(n);for(let l of s){let c=l*n;for(let d=0;d{"use strict";E();Ae();Mr=127});function _y(e,t,n,r){return[t,n??"",r??"",e.replace(/\//g," ")].join(` +`)}function hy(e,t,n,r){return[t??"",n??"",...r,e.replace(/\//g," ")].join(` +`)}function li(e){let t=[];for(let n of e.files){let r=new Set,s=!1;for(let o of n.symbols)r.has(o.name)||(r.add(o.name),s=!0,t.push({file:n.rel,symbol:o.name,line:o.line,text:_y(n.rel,o.name,o.signature,n.summary)}));if(!s){let o=hy(n.rel,n.title,n.summary,n.headings);o.replace(/\s+/g,"")&&t.push({file:n.rel,text:o})}}return t}function an(e,t){let n=li(e).map(r=>{let s={file:r.file,vec:Ar(t,r.text)};return r.symbol!==void 0&&(s.symbol=r.symbol),r.line!==void 0&&(s.line=r.line),s});return{embedVersion:it,modelId:t.modelId,dim:t.dim,records:n}}function ci(e){let t=JSON.stringify({embedVersion:e.embedVersion,modelId:e.modelId,dim:e.dim,count:e.records.length,records:e.records.map(a=>({file:a.file,symbol:a.symbol??"",line:a.line??0}))}),n=new TextEncoder().encode(t),r=e.records.length*e.dim,s=new Uint8Array(8+n.length+r);s.set([67,73,69,49],0),new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(4,n.length,!0),s.set(n,8);let o=8+n.length;for(let a of e.records)for(let l=0;le.byteLength)throw new Error("embeddings.bin: truncated header");let r=JSON.parse(new TextDecoder().decode(e.subarray(8,8+n))),s=8+n,{dim:o}=r;if(s+r.records.length*o>e.byteLength)throw new Error("embeddings.bin: truncated body");let a=r.records.map((l,c)=>{let d=new Int8Array(e.buffer.slice(e.byteOffset+s+c*o,e.byteOffset+s+(c+1)*o)),f={file:l.file,vec:d};return l.symbol&&(f.symbol=l.symbol),l.line&&(f.line=l.line),f});return{embedVersion:r.embedVersion,modelId:r.modelId,dim:o,records:a}}var yy,Fn=O(()=>{"use strict";E();Tr();on();yy="CIE1"});function ln(e,t,n,r={}){let s=r.limit??wy,o=Dt(e,t,{limit:Math.max(s,50),fuzzy:r.fuzzy}),a=r.queryVec??(r.model?Ar(r.model,t):void 0);if(!a||!n||n.records.length===0)return o.slice(0,s);let l=new Map;for(let p of n.records){let g=va(a,p.vec),y=l.get(p.file);(!y||g>y.score)&&l.set(p.file,{score:g,symbol:p.symbol})}let c=[...l.entries()].filter(([,p])=>p.score>0).sort((p,g)=>g[1].score-p[1].score||M(p[0],g[0])).map(([p])=>p),d=o.map(p=>p.file),f=ji([d,c],p=>p,r.rrfK??xy),u=new Map(o.map(p=>[p.file,p]));return[...f.entries()].sort((p,g)=>g[1]-p[1]||M(p[0],g[0])).map(([p,g])=>{let y=u.get(p),h={file:p,score:Number(g.toFixed(4)),matchedTerms:y?.matchedTerms??[],topSymbols:y?.topSymbols??[]},S=l.get(p);return S?.symbol&&(h.semanticSymbol=S.symbol),y?.fuzzyTerms&&(h.fuzzyTerms=y.fuzzyTerms),h}).slice(0,s)}var wy,xy,di=O(()=>{"use strict";E();Ae();Y();Mn();Tr();wy=20,xy=60});function Ut(e={}){let t=e.url??R.env.CODEINDEX_EMBED_ENDPOINT;return t&&t.trim()?t.trim():void 0}function mu(e){return e.replace(/\/+$/,"")}function pu(e){let t=mu(e);return t.endsWith("/embed")?t:t+"/embed"}function gu(e){return mu(e).replace(/\/embed$/,"")+"/healthz"}function _u(e){if(typeof e.timeoutMs=="number")return e.timeoutMs;let t=Number(R.env.CODEINDEX_EMBED_TIMEOUT_MS);return Number.isFinite(t)&&t>0?t:3e4}async function Ra(e,t={}){let n=Ut(t);if(!n)throw new Error("no embedding endpoint configured (set CODEINDEX_EMBED_ENDPOINT or pass opts.url)");let r=pu(n),s=new AbortController,o=setTimeout(()=>s.abort(),_u(t));try{let a=await fetch(r,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify({texts:e}),signal:s.signal});if(!a.ok)throw new Error(`embedding endpoint ${r} returned HTTP ${a.status}`);let c=(await a.json()).vectors;if(!Array.isArray(c)||!c.every(d=>Array.isArray(d)&&d.every(f=>typeof f=="number")))throw new Error(`embedding endpoint ${r} returned a malformed { vectors } payload`);return c}finally{clearTimeout(o)}}async function Ir(e,t={}){let n=new AbortController,r=setTimeout(()=>n.abort(),_u(t));try{return(await fetch(gu(e),{signal:n.signal,headers:t.headers})).ok}catch{return!1}finally{clearTimeout(r)}}async function Nr(e,t={}){let[n]=await Ra([e],t);if(!n)throw new Error("embedding endpoint returned no vector for the query");return Cr(n)}async function Fr(e,t={}){let n=li(e),r=t.batchSize&&t.batchSize>0?t.batchSize:64,s=[],o=0;for(let a=0;ad.text),t);if(c.length!==l.length)throw new Error(`embedding endpoint returned ${c.length} vectors for ${l.length} texts`);for(let d=0;do&&(o=u.length);let m={file:f.file,vec:u};f.symbol!==void 0&&(m.symbol=f.symbol),f.line!==void 0&&(m.line=f.line),s.push(m)}}return{embedVersion:it,modelId:"endpoint",dim:o,records:s}}var ui=O(()=>{"use strict";E();Tr();on();Fn()});function cn(e,t,n={}){let r=(n.budgetTokens??1024)*hu,s=n.maxSymbolsPerFile??8,o=[...t.files].filter(f=>f.fileKind==="code").sort((f,u)=>(u.pagerank??0)-(f.pagerank??0)||u.symbols-f.symbols||M(f.rel,u.rel)),a=new Map(e.files.map(f=>[f.rel,f])),c=`# repo map \u2014 ${t.fileCount} files `,d=0;for(let f of o){let u=a.get(f.rel);if(!u)continue;let m=[...u.symbols].filter(g=>g.kind!=="reexport"&&g.kind!=="reexport-all").sort((g,y)=>Number(y.exported)-Number(g.exported)||g.line-y.line).slice(0,s),p=` ${f.rel}: `;for(let g of m){let y=(g.signature??`${g.kind} ${g.name}`).replace(/\s+/g," ").trim().slice(0,120);p+=` ${g.line}: ${y} `}if(c.length+p.length>r)break;c+=p,d++}return`${c} -(${d} of ${o.length} code files shown, ~${Math.ceil(c.length/iu)} tokens) -`}var iu,Nr=F(()=>{"use strict";k();Y();iu=4});function Or(e,t={}){let n=t.maxCommitFiles??30,r=t.minTogether??3,s=t.maxPairs??100,o=t.since?[`${t.since}..HEAD`]:[],a=pe("git",["-C",e,"-c","core.quotePath=false","log",...o,"--pretty=format:%x1e","--name-only"]);if(!a.ok)return{ok:!1,couplings:[]};let l=new Map,c=new Map;for(let f of a.stdout.split("")){let u=f.split(` -`).map(p=>p.trim()).filter(Boolean);if(!u.length||u.length>n)continue;let m=[...new Set(u)].sort(M);for(let p of m)l.set(p,(l.get(p)??0)+1);for(let p=0;pu.strength-f.strength||u.together-f.together||M(f.a,u.a)||M(f.b,u.b)),{ok:!0,couplings:d.slice(0,s)}}function cn(e,t,n=20){let r=e.files.filter(s=>s.kind==="code").map(s=>{let o=t.get(s.rel)??0;return{rel:s.rel,lines:s.lines,commits:o,score:Number((o*Math.log2(s.lines+1)).toFixed(2))}});return r.sort((s,o)=>o.score-s.score||o.lines-s.lines||M(s.rel,o.rel)),r.slice(0,n)}var ou,Fr=F(()=>{"use strict";k();Ce();Y();ou="\0"});function Qh(e){for(let t of Yh){let n=I(e,t);if(!H(n))continue;let r;try{r=te(n,"utf8")}catch{continue}for(let s of r.split(/\n\s*\n/)){let o=s.trim();if(!o||o.startsWith("#")||o.startsWith("<")||/^(\[!\[|!\[|\[)/.test(o)&&!/[.:]\s/.test(o))continue;let a=o.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[*_`]/g,"").replace(/\s+/g," ").trim();if(a.length>20)return a.slice(0,400)}break}}function ka(e,t,n={}){let r=[],s=Ne(e.root).replace(/\/+$/,"").split("/").pop()||"repository";r.push(`# ${s}`,"");let o=Qh(e.root);o&&r.push(o,"");let a=Object.entries(t.languages).sort((m,p)=>p[1]-m[1]||M(m[0],p[0])).slice(0,6).map(([m,p])=>`${m} ${p}`).join(", ");r.push(`**${t.fileCount} indexed files** \xB7 ${a}`,"");let l=nn(e.root);if(l.packages.length>1){r.push(`## Layout \u2014 monorepo, ${l.packages.length} packages`,"");for(let m of l.packages.slice(0,20))r.push(`- \`${m.dir}\` \u2014 ${m.name}`);l.packages.length>20&&r.push(`- \u2026and ${l.packages.length-20} more`),l.cycle?.length&&r.push("",`\u26A0 dependency cycle: ${l.cycle.join(" \u2192 ")}`),r.push("")}r.push("## Key files","",ln(e,t,{budgetTokens:n.budgetTokens??900}).trim(),"");let{churn:c,ok:d}=Ze(e.root);if(d&&c.size){let m=cn(e,c,8);if(m.length){r.push("## Where work concentrates","","Files ranked by commits \xD7 size \u2014 where changes and defects cluster.","");for(let p of m)r.push(`- \`${p.rel}\` \u2014 ${p.commits} commits, ${p.lines} lines`);r.push("")}}r.push("## Next","","- `search ` \u2014 BM25 over names, paths, doc comments and prose; `explain_search` says whether it really matched","- `find_symbol ` / `symbols_overview ` \u2014 read structure without reading files","- `find_references ` \u2014 three labelled tiers; add `lsp: true` when a language server is configured","");let f=r.join(` -`);if(n.remember===!1)return{brief:f};let u=n.memoryName??"onboarding";return br(e.root,u,f),{brief:f,memory:u}}var Yh,Ea=F(()=>{"use strict";k();xe();oe();Nr();Sr();Fr();Gt();Zs();Y();Yh=["README.md","README.markdown","README.rst","README.txt","README"]});function ci(e){let t=JSON.stringify(e);return`Content-Length: ${ty(t)}${ey}${t}`}function ty(e){return new TextEncoder().encode(e).byteLength}function va(){let e=new TextEncoder,t=new TextDecoder,n=new Uint8Array(0),r=o=>{let a=new Uint8Array(n.length+o.length);a.set(n),a.set(o,n.length),n=a},s=()=>{for(let o=0;o+3au){n=n.subarray(l+4);continue}let u=l+4;if(n.lengthc===0||c===1&&/^[A-Za-z]:$/.test(l)?l:encodeURIComponent(l)).join("/")}function lu(e,t){if(!t.startsWith("file://"))return;let n;try{let l=t.slice(7);n=decodeURIComponent(l.startsWith("/")?l:`//${l}`).replace(/\\/g,"/")}catch{return}/^\/[A-Za-z]:/.test(n)&&(n=n.slice(1));let r=e.replace(/\\/g,"/").replace(/\/+$/,""),s=/^[A-Za-z]:/.test(r)||r.startsWith("//"),o=s?n.toLowerCase():n,a=s?r.toLowerCase():r;if(o===a)return"";if(o.startsWith(`${a}/`))return n.slice(r.length+1)}function di(e,t){let n=Array.isArray(t)?t:t&&typeof t=="object"?[t]:[],r=new Set,s=[];for(let o of n){if(!o||typeof o!="object")continue;let a=o.uri??o.targetUri;if(!a)continue;let l=lu(e,a);if(l===void 0||l==="")continue;let c=(o.range??o.targetSelectionRange??o.targetRange)?.start,d=typeof c?.line=="number"?c.line+1:1,f=typeof c?.character=="number"?c.character:void 0,u=`${l}:${d}:${f??""}`;r.has(u)||(r.add(u),s.push(f===void 0?{file:l,line:d}:{file:l,line:d,character:f}))}return s.sort((o,a)=>M(o.file,a.file)||o.line-a.line||(o.character??0)-(a.character??0))}var au,ey,Ra=F(()=>{"use strict";k();Y();au=32*1024*1024,ey=`\r +(${d} of ${o.length} code files shown, ~${Math.ceil(c.length/hu)} tokens) +`}var hu,Or=O(()=>{"use strict";E();Y();hu=4});function Pr(e,t={}){let n=t.maxCommitFiles??30,r=t.minTogether??3,s=t.maxPairs??100,o=t.since?[`${t.since}..HEAD`]:[],a=pe("git",["-C",e,"-c","core.quotePath=false","log",...o,"--pretty=format:%x1e","--name-only"]);if(!a.ok)return{ok:!1,couplings:[]};let l=new Map,c=new Map;for(let f of a.stdout.split("")){let u=f.split(` +`).map(p=>p.trim()).filter(Boolean);if(!u.length||u.length>n)continue;let m=[...new Set(u)].sort(M);for(let p of m)l.set(p,(l.get(p)??0)+1);for(let p=0;pu.strength-f.strength||u.together-f.together||M(f.a,u.a)||M(f.b,u.b)),{ok:!0,couplings:d.slice(0,s)}}function dn(e,t,n=20){let r=e.files.filter(s=>s.kind==="code").map(s=>{let o=t.get(s.rel)??0;return{rel:s.rel,lines:s.lines,commits:o,score:Number((o*Math.log2(s.lines+1)).toFixed(2))}});return r.sort((s,o)=>o.score-s.score||o.lines-s.lines||M(s.rel,o.rel)),r.slice(0,n)}var yu,$r=O(()=>{"use strict";E();Ae();Y();yu="\0"});function ky(e){for(let t of Sy){let n=I(e,t);if(!H(n))continue;let r;try{r=Q(n,"utf8")}catch{continue}for(let s of r.split(/\n\s*\n/)){let o=s.trim();if(!o||o.startsWith("#")||o.startsWith("<")||/^(\[!\[|!\[|\[)/.test(o)&&!/[.:]\s/.test(o))continue;let a=o.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[*_`]/g,"").replace(/\s+/g," ").trim();if(a.length>20)return a.slice(0,400)}break}}function Ma(e,t,n={}){let r=[],s=ke(e.root).replace(/\/+$/,"").split("/").pop()||"repository";r.push(`# ${s}`,"");let o=ky(e.root);o&&r.push(o,"");let a=Object.entries(t.languages).sort((m,p)=>p[1]-m[1]||M(m[0],p[0])).slice(0,6).map(([m,p])=>`${m} ${p}`).join(", ");r.push(`**${t.fileCount} indexed files** \xB7 ${a}`,"");let l=rn(e.root);if(l.packages.length>1){r.push(`## Layout \u2014 monorepo, ${l.packages.length} packages`,"");for(let m of l.packages.slice(0,20))r.push(`- \`${m.dir}\` \u2014 ${m.name}`);l.packages.length>20&&r.push(`- \u2026and ${l.packages.length-20} more`),l.cycle?.length&&r.push("",`\u26A0 dependency cycle: ${l.cycle.join(" \u2192 ")}`),r.push("")}r.push("## Key files","",cn(e,t,{budgetTokens:n.budgetTokens??900}).trim(),"");let{churn:c,ok:d}=Ze(e.root);if(d&&c.size){let m=dn(e,c,8);if(m.length){r.push("## Where work concentrates","","Files ranked by commits \xD7 size \u2014 where changes and defects cluster.","");for(let p of m)r.push(`- \`${p.rel}\` \u2014 ${p.commits} commits, ${p.lines} lines`);r.push("")}}r.push("## Next","","- `search ` \u2014 BM25 over names, paths, doc comments and prose; `explain_search` says whether it really matched","- `find_symbol ` / `symbols_overview ` \u2014 read structure without reading files","- `find_references ` \u2014 three labelled tiers; add `lsp: true` when a language server is configured","");let f=r.join(` +`);if(n.remember===!1)return{brief:f};let u=n.memoryName??"onboarding";return xr(e.root,u,f),{brief:f,memory:u}}var Sy,Ca=O(()=>{"use strict";E();xe();ae();Or();Er();$r();qt();ei();Y();Sy=["README.md","README.markdown","README.rst","README.txt","README"]});function fi(e){let t=JSON.stringify(e);return`Content-Length: ${vy(t)}${Ey}${t}`}function vy(e){return new TextEncoder().encode(e).byteLength}function Aa(){let e=new TextEncoder,t=new TextDecoder,n=new Uint8Array(0),r=o=>{let a=new Uint8Array(n.length+o.length);a.set(n),a.set(o,n.length),n=a},s=()=>{for(let o=0;o+3bu){n=n.subarray(l+4);continue}let u=l+4;if(n.lengthc===0||c===1&&/^[A-Za-z]:$/.test(l)?l:encodeURIComponent(l)).join("/")}function wu(e,t){if(!t.startsWith("file://"))return;let n;try{let l=t.slice(7);n=decodeURIComponent(l.startsWith("/")?l:`//${l}`).replace(/\\/g,"/")}catch{return}/^\/[A-Za-z]:/.test(n)&&(n=n.slice(1));let r=e.replace(/\\/g,"/").replace(/\/+$/,""),s=/^[A-Za-z]:/.test(r)||r.startsWith("//"),o=s?n.toLowerCase():n,a=s?r.toLowerCase():r;if(o===a)return"";if(o.startsWith(`${a}/`))return n.slice(r.length+1)}function mi(e,t){let n=Array.isArray(t)?t:t&&typeof t=="object"?[t]:[],r=new Set,s=[];for(let o of n){if(!o||typeof o!="object")continue;let a=o.uri??o.targetUri;if(!a)continue;let l=wu(e,a);if(l===void 0||l==="")continue;let c=(o.range??o.targetSelectionRange??o.targetRange)?.start,d=typeof c?.line=="number"?c.line+1:1,f=typeof c?.character=="number"?c.character:void 0,u=`${l}:${d}:${f??""}`;r.has(u)||(r.add(u),s.push(f===void 0?{file:l,line:d}:{file:l,line:d,character:f}))}return s.sort((o,a)=>M(o.file,a.file)||o.line-a.line||(o.character??0)-(a.character??0))}var bu,Ey,Ta=O(()=>{"use strict";E();Y();bu=32*1024*1024,Ey=`\r \r -`});async function Ma(e,t){let n=t.timeoutMs??ny,r=t.startupTimeoutMs??ry,s=va(),o=new Map,a=new Set,l=1,c,d=h=>{c=h;for(let[,S]of o)clearTimeout(S.timer),S.reject(h);o.clear()};e.onData(h=>{for(let S of s.push(h)){if(typeof S.id!="number")continue;let _=o.get(S.id);_&&(o.delete(S.id),clearTimeout(_.timer),S.error?_.reject(new Error(`${S.error.message} (code ${S.error.code})`)):_.resolve(S.result))}}),e.onExit(h=>d(new Error(`language server exited (code ${h??"unknown"})`)));let f=(h,S)=>{c||e.write(ci({jsonrpc:"2.0",method:h,params:S}))},u=(h,S,_=n)=>{if(c)return Promise.reject(c);let E=l++;return new Promise((b,x)=>{let v=setTimeout(()=>{o.delete(E),x(new ui(h,_))},_);v.unref?.(),o.set(E,{resolve:b,reject:x,timer:v}),e.write(ci({jsonrpc:"2.0",id:E,method:h,params:S}))})},m=await u("initialize",{processId:null,rootUri:dn(t.root,""),workspaceFolders:[{uri:dn(t.root,""),name:"repo"}],capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1,linkSupport:!0},implementation:{dynamicRegistration:!1,linkSupport:!0}}},...t.initializationOptions!==void 0?{initializationOptions:t.initializationOptions}:{}},r);f("initialized",{});let p=h=>{let S=m?.capabilities?.[h];return S===!0||typeof S=="object"&&S!==null},g={references:p("referencesProvider"),definition:p("definitionProvider"),implementation:p("implementationProvider"),typeHierarchy:p("typeHierarchyProvider")},y=(h,S,_)=>({textDocument:{uri:dn(t.root,h)},position:{line:Math.max(0,S-1),character:_}});return{capabilities:g,didOpen(h,S,_){a.has(h)||(a.add(h),f("textDocument/didOpen",{textDocument:{uri:dn(t.root,h),languageId:_,version:1,text:S}}))},async references(h,S,_){if(!g.references)return[];let E=await u("textDocument/references",{...y(h,S,_),context:{includeDeclaration:!0}});return di(t.root,E)},async definition(h,S,_){return g.definition?di(t.root,await u("textDocument/definition",y(h,S,_))):[]},async shutdown(){try{for(let h of a)f("textDocument/didClose",{textDocument:{uri:dn(t.root,h)}});a.clear(),await u("shutdown",null,Math.min(n,2e3)),f("exit",void 0)}catch{}finally{d(new Error("session closed")),e.close()}}}}var ui,ny,ry,Ca=F(()=>{"use strict";k();Ra();ui=class extends Error{constructor(t,n){super(`${t} exceeded ${n}ms`),this.name="LspTimeout"}},ny=5e3,ry=15e3});function fi(e){let t=R.env.CODEINDEX_LSP_CONFIG;if(t!==void 0){let s=t.trim();return!s||s==="0"||s.toLowerCase()==="off"?{path:void 0,source:"none"}:{path:Ne(s),source:"env"}}let n=I(e,du,cu);if(H(n))return{path:n,source:"repo"};let r=I(R.cwd(),du,cu);return r!==n&&H(r)?{path:r,source:"cwd"}:{path:void 0,source:"none"}}function uu(e){if(!e||typeof e!="object")throw new Error("lsp.json must be a JSON object");let t=e;if(t.version!==1)throw new Error(`lsp.json: unsupported version ${JSON.stringify(t.version)} (expected 1)`);if(!Array.isArray(t.servers))throw new Error("lsp.json: `servers` must be an array");let n=new Set;return{version:1,servers:t.servers.map((s,o)=>{if(!s||typeof s!="object")throw new Error(`lsp.json: servers[${o}] must be an object`);let a=s,l=typeof a.id=="string"&&a.id.trim()?a.id.trim():void 0;if(!l)throw new Error(`lsp.json: servers[${o}].id must be a non-empty string`);if(n.has(l))throw new Error(`lsp.json: duplicate server id ${JSON.stringify(l)}`);if(n.add(l),typeof a.command!="string"||!a.command.trim())throw new Error(`lsp.json: servers[${o}].command must be a non-empty string`);if(!Array.isArray(a.languages)||!a.languages.length||a.languages.some(c=>typeof c!="string"))throw new Error(`lsp.json: servers[${o}].languages must be a non-empty array of strings`);if(a.args!==void 0&&(!Array.isArray(a.args)||a.args.some(c=>typeof c!="string")))throw new Error(`lsp.json: servers[${o}].args must be an array of strings`);return{id:l,languages:a.languages,...typeof a.languageId=="string"?{languageId:a.languageId}:{},command:a.command,...Array.isArray(a.args)?{args:a.args}:{},...a.env&&typeof a.env=="object"?{env:a.env}:{},...a.initializationOptions!==void 0?{initializationOptions:a.initializationOptions}:{},...typeof a.timeoutMs=="number"?{timeoutMs:a.timeoutMs}:{},...typeof a.startupTimeoutMs=="number"?{startupTimeoutMs:a.startupTimeoutMs}:{}}})}}function mi(e){let{path:t}=fi(e);if(!t||!H(t))return;let n;try{n=JSON.parse(te(t,"utf8"))}catch(r){throw new Error(`${t}: ${r instanceof Error?r.message:String(r)}`)}return uu(n)}function Aa(e,t){return e.servers.find(n=>n.languages.includes(t))}function fu(e){return pu("CODEINDEX_LSP_TIMEOUT_MS")??e.timeoutMs??sy}function mu(e){return pu("CODEINDEX_LSP_STARTUP_TIMEOUT_MS")??e.startupTimeoutMs??iy}function pu(e){let t=R.env[e];if(t===void 0)return;let n=Number(t);return Number.isFinite(n)&&n>0?n:void 0}var cu,du,sy,iy,Ta=F(()=>{"use strict";k();xe();oe();cu="lsp.json",du=".codeindex";sy=5e3,iy=15e3});function Bt(e,t){return{server:e,ok:!1,reason:t,refs:[],agreement:{both:[],lspOnly:[],staticOnly:[]}}}function _u(e,t,n,r){try{let o=te(I(e,t),"utf8").split(/\r?\n/)[n-1]?.indexOf(r)??-1;return o<0?0:o}catch{return 0}}function Ia(e,t){let n=new Set(e.map(l=>l.file)),r=new Set([...t.callSites.map(l=>l.file),...t.referencingFiles,...t.defs.map(l=>l.file)]),s=[],o=[],a=[];for(let l of n)(r.has(l)?s:o).push(l);for(let l of r)n.has(l)||a.push(l);return{both:s.sort(M),lspOnly:o.sort(M),staticOnly:a.sort(M)}}async function hu(e,t,n,r,s,o){if(!r.capabilities.references)return{...n,lsp:Bt(s,"server does not provide textDocument/references")};if(!n.defs.length)return{...n,lsp:Bt(s,`no declaration of ${t} to anchor a request on`)};let a=new Set,l=[];try{for(let c of n.defs){let d=oy(e.root,c.file);if(!d)continue;r.didOpen(c.file,d,o);let f=_u(e.root,c.file,c.line,t);for(let u of await r.references(c.file,c.line,f)){let m=`${u.file}:${u.line}:${u.character??""}`;a.has(m)||(a.add(m),l.push(u))}}}catch(c){return{...n,lsp:{server:s,ok:!1,reason:c instanceof Error?c.message:String(c),refs:l.sort(gu),agreement:Ia(l,n)}}}return l.sort(gu),{...n,lsp:{server:s,ok:!0,refs:l,agreement:Ia(l,n)}}}function gu(e,t){return M(e.file,t.file)||e.line-t.line||(e.character??0)-(t.character??0)}function oy(e,t){try{return te(I(e,t),"utf8")}catch{return""}}var Na=F(()=>{"use strict";k();xe();oe();Y()});function Oa(e,t){let n;try{n=ul(e.command,e.args??[],{cwd:t,stdio:["pipe","pipe","pipe"],...e.env?{env:{...R.env,...e.env}}:{}})}catch{return}let r=!1,s=[],o=[],a=l=>{if(!r){r=!0;for(let c of o)c(l)}};return n.on("error",()=>a(null)),n.on("close",l=>a(l)),n.stdout?.on("data",l=>{for(let c of s)c(l)}),n.stderr?.on("data",()=>{}),{write(l){if(!r)try{n.stdin?.write(l)}catch{a(null)}},onData(l){s.push(l)},onExit(l){r?l(null):o.push(l)},close(){try{n.stdin?.end()}catch{}let l=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},2e3);l.unref?.(),n.on("close",()=>clearTimeout(l))}}}var Fa=F(()=>{"use strict";k();Fi()});async function Pr(e,t,n=!1){let{path:r,source:s}=fi(t),o=mi(t);if(!o)return{lspVersion:1,mode:"none",configPath:r??null,source:s,servers:[],unmappedLanguages:[]};let a=new Map;for(let f of e.files)a.set(f.lang,(a.get(f.lang)??0)+1);let l=[];for(let f of o.servers){let u={id:f.id,languages:f.languages,command:f.command,onPath:at(f.command),filesInRepo:f.languages.reduce((m,p)=>m+(a.get(p)??0),0)};if(n){let m=await yu(f,e.root);m.ok?(u.reachable=!0,u.capabilities=m.session.capabilities,await m.session.shutdown()):(u.reachable=!1,u.error=m.reason)}l.push(u)}let c=new Set(o.servers.flatMap(f=>f.languages)),d=[...a.keys()].filter(f=>!c.has(f)&&f!=="other").sort();return{lspVersion:1,mode:"configured",configPath:r??null,source:s,servers:l,unmappedLanguages:d}}async function yu(e,t){if(!at(e.command))return{ok:!1,reason:`${e.command} is not on PATH`};let n=Oa(e,t);if(!n)return{ok:!1,reason:`could not start ${e.command}`};try{return{ok:!0,session:await Ma(n,{root:t,timeoutMs:fu(e),startupTimeoutMs:mu(e),...e.initializationOptions!==void 0?{initializationOptions:e.initializationOptions}:{}})}}catch(r){return n.close(),{ok:!1,reason:r instanceof Error?r.message:String(r)}}}async function Pa(e,t,n,r){let s;try{s=mi(t)}catch(c){return{...r,lsp:Bt("(config)",c instanceof Error?c.message:String(c))}}if(!s)return r;let o=r.defs[0]?.lang;if(!o)return{...r,lsp:Bt("(none)",`no declaration of ${n} to anchor a request on`)};let a=Aa(s,o);if(!a)return{...r,lsp:Bt("(none)",`no server configured for ${o}`)};let l=await yu(a,e.root);if(!l.ok)return{...r,lsp:Bt(a.id,l.reason)};try{return await hu(e,n,r,l.session,a.id,a.languageId??a.languages[0])}finally{await l.session.shutdown()}}var pi=F(()=>{"use strict";k();Ce();Ca();Ta();Na();Fa()});function uy(e){let n=e.split("/").pop().split(".")[0].toLowerCase();return dy.has(n)}function wu(e){return Array.isArray(e)?e:[e]}function $r(e){let t=Array.isArray(e)?e:e?.rules;if(!Array.isArray(t))throw new Error("rules config must be an array (or an object with a `rules` array)");return t.map((n,r)=>{let s=`rules[${r}]`;if(typeof n!="object"||n===null)throw new Error(`${s}: must be an object`);let o=n;if(typeof o.name!="string"||!o.name)throw new Error(`${s}: \`name\` (non-empty string) is required`);if(o.severity!==void 0&&!ay.has(o.severity))throw new Error(`${s} (${o.name}): \`severity\` must be "error" or "warn"`);if(o.comment!==void 0&&typeof o.comment!="string")throw new Error(`${s} (${o.name}): \`comment\` must be a string`);if(o.builtin!==void 0){if(!ly.has(o.builtin))throw new Error(`${s} (${o.name}): \`builtin\` must be "cycles", "orphans" or "literals"`);return{name:o.name,builtin:o.builtin,severity:o.severity,comment:o.comment,...o.tiers!==void 0?{tiers:o.tiers}:{}}}let a=d=>{let f=o[d];if(!(typeof f=="string"?f.length>0:Array.isArray(f)&&f.length>0&&f.every(m=>typeof m=="string"&&m)))throw new Error(`${s} (${o.name}): \`${d}\` must be a glob or a non-empty array of globs`);return f},l=a("from"),c=a("to");if(o.kind!==void 0&&!(Array.isArray(o.kind)&&o.kind.every(f=>bu.has(f))))throw new Error(`${s} (${o.name}): \`kind\` must be an array of edge kinds (${[...bu].join(", ")})`);return{name:o.name,from:l,to:c,kind:o.kind,severity:o.severity,comment:o.comment}})}function fy(e){let t=new Map;for(let f of e.moduleEdges){if(f.kind!=="import")continue;let u=t.get(f.from);u||t.set(f.from,u=[]),u.push(f.to)}for(let f of t.values())f.sort(M);let n=[...t.keys()].sort(M),r=new Map,s=new Map,o=new Set,a=[],l=[],c=0;for(let f of n){if(r.has(f))continue;let u=[{node:f,next:0}];for(;u.length;){let m=u[u.length-1],p=m.node;m.next===0&&(r.set(p,c),s.set(p,c),c++,a.push(p),o.add(p));let g=t.get(p)??[];if(m.next1&&l.push(h)}u.pop();let y=u[u.length-1];y&&s.set(y.node,Math.min(s.get(y.node),s.get(p)))}}}let d=[];for(let f of l){let u=new Set(f),m=[...f].sort(M)[0],p=new Map([[m,null]]),g=[m];for(let S=0;S(t.get(S)??[]).includes(m)&&S!==m)??m,h=[];for(let S=y;S!==null;S=p.get(S)??null)h.unshift(S);h.push(m),d.push({start:m,path:h})}return d}function Lr(e,t){let n=[],r=(o,a)=>{n.push({rule:o.name,...a,severity:o.severity??"error",...o.comment!==void 0?{comment:o.comment}:{}})},s=new Set(e.files.map(o=>o.rel));for(let o of t){if("builtin"in o){if(o.builtin==="cycles")for(let d of fy(e))r(o,{from:d.start,to:d.path.join(" -> "),kind:"cycle"});else if(o.builtin==="literals"){let d=new Set(o.tiers?.length?o.tiers:cy);for(let f of e.literalDuplications??[]){if(!d.has(f.tier))continue;let u=f.holders[0]??f.literals[0];r(o,{from:`${u.file}:${u.line}`,to:`${f.tier} ${JSON.stringify(f.value)} (${f.count} sites, ${f.files} files)`,kind:"literal"})}}else for(let d of e.files)d.fileKind!=="code"||d.degIn!==0||d.degOut!==0||uy(d.rel)||r(o,{from:d.rel,to:d.rel,kind:"orphan"});continue}let a=yt(wu(o.from)),l=yt(wu(o.to));if(!a||!l)continue;let c=o.kind?.length?new Set(o.kind):null;for(let d of e.fileEdges)d.dangling||!s.has(d.to)||c&&!c.has(d.kind)||!a(d.from)||!l(d.to)||r(o,{from:d.from,to:d.to,kind:d.kind})}return n.sort((o,a)=>M(o.rule,a.rule)||M(o.from,a.from)||M(o.to,a.to)||M(o.kind,a.kind)),n}var bu,ay,ly,cy,dy,gi=F(()=>{"use strict";k();Hn();Y();bu=new Set(["contains","doc-link","import","call","use","mention"]),ay=new Set(["error","warn"]),ly=new Set(["cycles","orphans","literals"]),cy=["competing","bypassed"],dy=new Set(["index","main","app","application","cli","server","entry","entrypoint","setup","conftest","__init__","__main__","mod","lib"])});function Dr(e){let t=Cn(e),n=Vs(e),r=[],s=o=>o.exported&&!my.has(o.kind)&&!$t(o.file)&&!py.test(o.file);for(let o of e.files)for(let a of o.symbols){if(!s(a))continue;let l=t.get(a.name)??t.get(`${a.name}@${a.file}`);if(!!l&&l.def.file===a.file&&l.callers.length>0)continue;let d=(n.get(a.name)?.size??0)>0;r.push({name:a.name,file:a.file,line:a.line,kind:a.kind,tier:d?"uncalled":"unreferenced"})}return r.sort((o,a)=>M(o.tier,a.tier)||M(o.file,a.file)||o.line-a.line)}var my,py,_i=F(()=>{"use strict";k();mt();vn();Y();my=new Set(["reexport","reexport-all","default"]),py=/(^|\/)(index|main|cli|app|server|engine)\.[a-z]+$/});function jr(e,t={}){let n=t.maxEdges??80,r=[...e.moduleEdges].filter(l=>!l.dangling);t.module&&(r=r.filter(l=>l.from===t.module||l.to===t.module)),r.sort((l,c)=>c.weight-l.weight||M(l.from,c.from)||M(l.to,c.to));let s=Math.max(0,r.length-n);r=r.slice(0,n);let o=new Set;for(let l of r)o.add(l.from),o.add(l.to);t.module&&o.add(t.module);let a=["graph LR"];for(let l of[...e.modules].sort((c,d)=>M(c.slug,d.slug)))o.has(l.slug)&&a.push(` ${$a(l.slug)}["${l.slug}${l.tier===0?" (core)":""}"]`);for(let l of r){let c=l.kind==="import"?"":`|${l.kind}|`;a.push(` ${$a(l.from)} -->${c} ${$a(l.to)}`)}return s&&a.push(` %% ${s} lighter edges omitted (maxEdges=${n})`),a.join(` +`});async function Ia(e,t){let n=t.timeoutMs??Ry,r=t.startupTimeoutMs??My,s=Aa(),o=new Map,a=new Set,l=1,c,d=h=>{c=h;for(let[,S]of o)clearTimeout(S.timer),S.reject(h);o.clear()};e.onData(h=>{for(let S of s.push(h)){if(typeof S.id!="number")continue;let _=o.get(S.id);_&&(o.delete(S.id),clearTimeout(_.timer),S.error?_.reject(new Error(`${S.error.message} (code ${S.error.code})`)):_.resolve(S.result))}}),e.onExit(h=>d(new Error(`language server exited (code ${h??"unknown"})`)));let f=(h,S)=>{c||e.write(fi({jsonrpc:"2.0",method:h,params:S}))},u=(h,S,_=n)=>{if(c)return Promise.reject(c);let k=l++;return new Promise((b,w)=>{let v=setTimeout(()=>{o.delete(k),w(new pi(h,_))},_);v.unref?.(),o.set(k,{resolve:b,reject:w,timer:v}),e.write(fi({jsonrpc:"2.0",id:k,method:h,params:S}))})},m=await u("initialize",{processId:null,rootUri:un(t.root,""),workspaceFolders:[{uri:un(t.root,""),name:"repo"}],capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1,linkSupport:!0},implementation:{dynamicRegistration:!1,linkSupport:!0}}},...t.initializationOptions!==void 0?{initializationOptions:t.initializationOptions}:{}},r);f("initialized",{});let p=h=>{let S=m?.capabilities?.[h];return S===!0||typeof S=="object"&&S!==null},g={references:p("referencesProvider"),definition:p("definitionProvider"),implementation:p("implementationProvider"),typeHierarchy:p("typeHierarchyProvider")},y=(h,S,_)=>({textDocument:{uri:un(t.root,h)},position:{line:Math.max(0,S-1),character:_}});return{capabilities:g,didOpen(h,S,_){a.has(h)||(a.add(h),f("textDocument/didOpen",{textDocument:{uri:un(t.root,h),languageId:_,version:1,text:S}}))},async references(h,S,_){if(!g.references)return[];let k=await u("textDocument/references",{...y(h,S,_),context:{includeDeclaration:!0}});return mi(t.root,k)},async definition(h,S,_){return g.definition?mi(t.root,await u("textDocument/definition",y(h,S,_))):[]},async shutdown(){try{for(let h of a)f("textDocument/didClose",{textDocument:{uri:un(t.root,h)}});a.clear(),await u("shutdown",null,Math.min(n,2e3)),f("exit",void 0)}catch{}finally{d(new Error("session closed")),e.close()}}}}var pi,Ry,My,Na=O(()=>{"use strict";E();Ta();pi=class extends Error{constructor(t,n){super(`${t} exceeded ${n}ms`),this.name="LspTimeout"}},Ry=5e3,My=15e3});function gi(e){let t=R.env.CODEINDEX_LSP_CONFIG;if(t!==void 0){let s=t.trim();return!s||s==="0"||s.toLowerCase()==="off"?{path:void 0,source:"none"}:{path:ke(s),source:"env"}}let n=I(e,Su,xu);if(H(n))return{path:n,source:"repo"};let r=I(R.cwd(),Su,xu);return r!==n&&H(r)?{path:r,source:"cwd"}:{path:void 0,source:"none"}}function ku(e){if(!e||typeof e!="object")throw new Error("lsp.json must be a JSON object");let t=e;if(t.version!==1)throw new Error(`lsp.json: unsupported version ${JSON.stringify(t.version)} (expected 1)`);if(!Array.isArray(t.servers))throw new Error("lsp.json: `servers` must be an array");let n=new Set;return{version:1,servers:t.servers.map((s,o)=>{if(!s||typeof s!="object")throw new Error(`lsp.json: servers[${o}] must be an object`);let a=s,l=typeof a.id=="string"&&a.id.trim()?a.id.trim():void 0;if(!l)throw new Error(`lsp.json: servers[${o}].id must be a non-empty string`);if(n.has(l))throw new Error(`lsp.json: duplicate server id ${JSON.stringify(l)}`);if(n.add(l),typeof a.command!="string"||!a.command.trim())throw new Error(`lsp.json: servers[${o}].command must be a non-empty string`);if(!Array.isArray(a.languages)||!a.languages.length||a.languages.some(c=>typeof c!="string"))throw new Error(`lsp.json: servers[${o}].languages must be a non-empty array of strings`);if(a.args!==void 0&&(!Array.isArray(a.args)||a.args.some(c=>typeof c!="string")))throw new Error(`lsp.json: servers[${o}].args must be an array of strings`);return{id:l,languages:a.languages,...typeof a.languageId=="string"?{languageId:a.languageId}:{},command:a.command,...Array.isArray(a.args)?{args:a.args}:{},...a.env&&typeof a.env=="object"?{env:a.env}:{},...a.initializationOptions!==void 0?{initializationOptions:a.initializationOptions}:{},...typeof a.timeoutMs=="number"?{timeoutMs:a.timeoutMs}:{},...typeof a.startupTimeoutMs=="number"?{startupTimeoutMs:a.startupTimeoutMs}:{}}})}}function _i(e){let{path:t}=gi(e);if(!t||!H(t))return;let n;try{n=JSON.parse(Q(t,"utf8"))}catch(r){throw new Error(`${t}: ${r instanceof Error?r.message:String(r)}`)}return ku(n)}function Fa(e,t){return e.servers.find(n=>n.languages.includes(t))}function Eu(e){return Ru("CODEINDEX_LSP_TIMEOUT_MS")??e.timeoutMs??Cy}function vu(e){return Ru("CODEINDEX_LSP_STARTUP_TIMEOUT_MS")??e.startupTimeoutMs??Ay}function Ru(e){let t=R.env[e];if(t===void 0)return;let n=Number(t);return Number.isFinite(n)&&n>0?n:void 0}var xu,Su,Cy,Ay,Oa=O(()=>{"use strict";E();xe();ae();xu="lsp.json",Su=".codeindex";Cy=5e3,Ay=15e3});function Bt(e,t){return{server:e,ok:!1,reason:t,refs:[],agreement:{both:[],lspOnly:[],staticOnly:[]}}}function Cu(e,t,n,r){try{let o=Q(I(e,t),"utf8").split(/\r?\n/)[n-1]?.indexOf(r)??-1;return o<0?0:o}catch{return 0}}function Pa(e,t){let n=new Set(e.map(l=>l.file)),r=new Set([...t.callSites.map(l=>l.file),...t.referencingFiles,...t.defs.map(l=>l.file)]),s=[],o=[],a=[];for(let l of n)(r.has(l)?s:o).push(l);for(let l of r)n.has(l)||a.push(l);return{both:s.sort(M),lspOnly:o.sort(M),staticOnly:a.sort(M)}}async function Au(e,t,n,r,s,o){if(!r.capabilities.references)return{...n,lsp:Bt(s,"server does not provide textDocument/references")};if(!n.defs.length)return{...n,lsp:Bt(s,`no declaration of ${t} to anchor a request on`)};let a=new Set,l=[];try{for(let c of n.defs){let d=Ty(e.root,c.file);if(!d)continue;r.didOpen(c.file,d,o);let f=Cu(e.root,c.file,c.line,t);for(let u of await r.references(c.file,c.line,f)){let m=`${u.file}:${u.line}:${u.character??""}`;a.has(m)||(a.add(m),l.push(u))}}}catch(c){return{...n,lsp:{server:s,ok:!1,reason:c instanceof Error?c.message:String(c),refs:l.sort(Mu),agreement:Pa(l,n)}}}return l.sort(Mu),{...n,lsp:{server:s,ok:!0,refs:l,agreement:Pa(l,n)}}}function Mu(e,t){return M(e.file,t.file)||e.line-t.line||(e.character??0)-(t.character??0)}function Ty(e,t){try{return Q(I(e,t),"utf8")}catch{return""}}var $a=O(()=>{"use strict";E();xe();ae();Y()});function Da(e,t){let n;try{n=gl(e.command,e.args??[],{cwd:t,stdio:["pipe","pipe","pipe"],...e.env?{env:{...R.env,...e.env}}:{}})}catch{return}let r=!1,s=[],o=[],a=l=>{if(!r){r=!0;for(let c of o)c(l)}};return n.on("error",()=>a(null)),n.on("close",l=>a(l)),n.stdout?.on("data",l=>{for(let c of s)c(l)}),n.stderr?.on("data",()=>{}),{write(l){if(!r)try{n.stdin?.write(l)}catch{a(null)}},onData(l){s.push(l)},onExit(l){r?l(null):o.push(l)},close(){try{n.stdin?.end()}catch{}let l=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},2e3);l.unref?.(),n.on("close",()=>clearTimeout(l))}}}var La=O(()=>{"use strict";E();Di()});async function Dr(e,t,n=!1){let{path:r,source:s}=gi(t),o=_i(t);if(!o)return{lspVersion:1,mode:"none",configPath:r??null,source:s,servers:[],unmappedLanguages:[]};let a=new Map;for(let f of e.files)a.set(f.lang,(a.get(f.lang)??0)+1);let l=[];for(let f of o.servers){let u={id:f.id,languages:f.languages,command:f.command,onPath:at(f.command),filesInRepo:f.languages.reduce((m,p)=>m+(a.get(p)??0),0)};if(n){let m=await Tu(f,e.root);m.ok?(u.reachable=!0,u.capabilities=m.session.capabilities,await m.session.shutdown()):(u.reachable=!1,u.error=m.reason)}l.push(u)}let c=new Set(o.servers.flatMap(f=>f.languages)),d=[...a.keys()].filter(f=>!c.has(f)&&f!=="other").sort();return{lspVersion:1,mode:"configured",configPath:r??null,source:s,servers:l,unmappedLanguages:d}}async function Tu(e,t){if(!at(e.command))return{ok:!1,reason:`${e.command} is not on PATH`};let n=Da(e,t);if(!n)return{ok:!1,reason:`could not start ${e.command}`};try{return{ok:!0,session:await Ia(n,{root:t,timeoutMs:Eu(e),startupTimeoutMs:vu(e),...e.initializationOptions!==void 0?{initializationOptions:e.initializationOptions}:{}})}}catch(r){return n.close(),{ok:!1,reason:r instanceof Error?r.message:String(r)}}}async function ja(e,t,n,r){let s;try{s=_i(t)}catch(c){return{...r,lsp:Bt("(config)",c instanceof Error?c.message:String(c))}}if(!s)return r;let o=r.defs[0]?.lang;if(!o)return{...r,lsp:Bt("(none)",`no declaration of ${n} to anchor a request on`)};let a=Fa(s,o);if(!a)return{...r,lsp:Bt("(none)",`no server configured for ${o}`)};let l=await Tu(a,e.root);if(!l.ok)return{...r,lsp:Bt(a.id,l.reason)};try{return await Au(e,n,r,l.session,a.id,a.languageId??a.languages[0])}finally{await l.session.shutdown()}}var hi=O(()=>{"use strict";E();Ae();Na();Oa();$a();La()});function Py(e){let n=e.split("/").pop().split(".")[0].toLowerCase();return Oy.has(n)}function Nu(e){return Array.isArray(e)?e:[e]}function Lr(e){let t=Array.isArray(e)?e:e?.rules;if(!Array.isArray(t))throw new Error("rules config must be an array (or an object with a `rules` array)");return t.map((n,r)=>{let s=`rules[${r}]`;if(typeof n!="object"||n===null)throw new Error(`${s}: must be an object`);let o=n;if(typeof o.name!="string"||!o.name)throw new Error(`${s}: \`name\` (non-empty string) is required`);if(o.severity!==void 0&&!Iy.has(o.severity))throw new Error(`${s} (${o.name}): \`severity\` must be "error" or "warn"`);if(o.comment!==void 0&&typeof o.comment!="string")throw new Error(`${s} (${o.name}): \`comment\` must be a string`);if(o.builtin!==void 0){if(!Ny.has(o.builtin))throw new Error(`${s} (${o.name}): \`builtin\` must be "cycles", "orphans" or "literals"`);return{name:o.name,builtin:o.builtin,severity:o.severity,comment:o.comment,...o.tiers!==void 0?{tiers:o.tiers}:{}}}let a=d=>{let f=o[d];if(!(typeof f=="string"?f.length>0:Array.isArray(f)&&f.length>0&&f.every(m=>typeof m=="string"&&m)))throw new Error(`${s} (${o.name}): \`${d}\` must be a glob or a non-empty array of globs`);return f},l=a("from"),c=a("to");if(o.kind!==void 0&&!(Array.isArray(o.kind)&&o.kind.every(f=>Iu.has(f))))throw new Error(`${s} (${o.name}): \`kind\` must be an array of edge kinds (${[...Iu].join(", ")})`);return{name:o.name,from:l,to:c,kind:o.kind,severity:o.severity,comment:o.comment}})}function $y(e){let t=new Map;for(let f of e.moduleEdges){if(f.kind!=="import")continue;let u=t.get(f.from);u||t.set(f.from,u=[]),u.push(f.to)}for(let f of t.values())f.sort(M);let n=[...t.keys()].sort(M),r=new Map,s=new Map,o=new Set,a=[],l=[],c=0;for(let f of n){if(r.has(f))continue;let u=[{node:f,next:0}];for(;u.length;){let m=u[u.length-1],p=m.node;m.next===0&&(r.set(p,c),s.set(p,c),c++,a.push(p),o.add(p));let g=t.get(p)??[];if(m.next1&&l.push(h)}u.pop();let y=u[u.length-1];y&&s.set(y.node,Math.min(s.get(y.node),s.get(p)))}}}let d=[];for(let f of l){let u=new Set(f),m=[...f].sort(M)[0],p=new Map([[m,null]]),g=[m];for(let S=0;S(t.get(S)??[]).includes(m)&&S!==m)??m,h=[];for(let S=y;S!==null;S=p.get(S)??null)h.unshift(S);h.push(m),d.push({start:m,path:h})}return d}function jr(e,t){let n=[],r=(o,a)=>{n.push({rule:o.name,...a,severity:o.severity??"error",...o.comment!==void 0?{comment:o.comment}:{}})},s=new Set(e.files.map(o=>o.rel));for(let o of t){if("builtin"in o){if(o.builtin==="cycles")for(let d of $y(e))r(o,{from:d.start,to:d.path.join(" -> "),kind:"cycle"});else if(o.builtin==="literals"){let d=new Set(o.tiers?.length?o.tiers:Fy);for(let f of e.literalDuplications??[]){if(!d.has(f.tier))continue;let u=f.holders[0]??f.literals[0];r(o,{from:`${u.file}:${u.line}`,to:`${f.tier} ${JSON.stringify(f.value)} (${f.count} sites, ${f.files} files)`,kind:"literal"})}}else for(let d of e.files)d.fileKind!=="code"||d.degIn!==0||d.degOut!==0||Py(d.rel)||r(o,{from:d.rel,to:d.rel,kind:"orphan"});continue}let a=bt(Nu(o.from)),l=bt(Nu(o.to));if(!a||!l)continue;let c=o.kind?.length?new Set(o.kind):null;for(let d of e.fileEdges)d.dangling||!s.has(d.to)||c&&!c.has(d.kind)||!a(d.from)||!l(d.to)||r(o,{from:d.from,to:d.to,kind:d.kind})}return n.sort((o,a)=>M(o.rule,a.rule)||M(o.from,a.from)||M(o.to,a.to)||M(o.kind,a.kind)),n}var Iu,Iy,Ny,Fy,Oy,yi=O(()=>{"use strict";E();Gn();Y();Iu=new Set(["contains","doc-link","import","call","use","mention"]),Iy=new Set(["error","warn"]),Ny=new Set(["cycles","orphans","literals"]),Fy=["competing","bypassed"],Oy=new Set(["index","main","app","application","cli","server","entry","entrypoint","setup","conftest","__init__","__main__","mod","lib"])});function Wr(e){let t=Cn(e),n=Xs(e),r=[],s=o=>o.exported&&!Dy.has(o.kind)&&!$t(o.file)&&!Ly.test(o.file);for(let o of e.files)for(let a of o.symbols){if(!s(a))continue;let l=t.get(`${a.name}@${a.file}`)??t.get(a.name);if(!!l&&l.def.file===a.file&&l.callers.length>0)continue;let d=(n.get(a.name)?.size??0)>0;r.push({name:a.name,file:a.file,line:a.line,kind:a.kind,tier:d?"uncalled":"unreferenced"})}return r.sort((o,a)=>M(o.tier,a.tier)||M(o.file,a.file)||o.line-a.line)}var Dy,Ly,bi=O(()=>{"use strict";E();pt();vn();Y();Dy=new Set(["reexport","reexport-all","default"]),Ly=/(^|\/)(index|main|cli|app|server|engine)\.[a-z]+$/});function Ur(e,t={}){let n=t.maxEdges??80,r=[...e.moduleEdges].filter(l=>!l.dangling);t.module&&(r=r.filter(l=>l.from===t.module||l.to===t.module)),r.sort((l,c)=>c.weight-l.weight||M(l.from,c.from)||M(l.to,c.to));let s=Math.max(0,r.length-n);r=r.slice(0,n);let o=new Set;for(let l of r)o.add(l.from),o.add(l.to);t.module&&o.add(t.module);let a=["graph LR"];for(let l of[...e.modules].sort((c,d)=>M(c.slug,d.slug)))o.has(l.slug)&&a.push(` ${Wa(l.slug)}["${l.slug}${l.tier===0?" (core)":""}"]`);for(let l of r){let c=l.kind==="import"?"":`|${l.kind}|`;a.push(` ${Wa(l.from)} -->${c} ${Wa(l.to)}`)}return s&&a.push(` %% ${s} lighter edges omitted (maxEdges=${n})`),a.join(` `)+` -`}function La(e){return"m_"+e.replace(/[^A-Za-z0-9_]/g,"_")}function yy(e,t={}){let n=t.maxModules??_y,r=t.maxEdges??hy,o=e.modules.slice().sort((d,f)=>xu(f)-xu(d)||M(d.slug,f.slug)).slice(0,n),a=new Set(o.map(d=>d.slug)),l=e.moduleEdges.filter(d=>a.has(d.from)&&a.has(d.to)).sort((d,f)=>f.weight-d.weight||M(d.from,f.from)||M(d.to,f.to)).slice(0,r),c=[];c.push(`%% ${t.title??"module graph"} \u2014 ${o.length} of ${e.modules.length} modules, ${l.length} of ${e.moduleEdges.length} edges`),(o.lengthu.tier===d);if(f.length){c.push(` subgraph ${gy[d]}`);for(let u of f)c.push(` ${La(u.slug)}["${u.path.replace(/"/g,"'")}"]`);c.push(" end")}}for(let d of l){let f=d.weight>1?`|${d.weight}| `:"";c.push(` ${La(d.from)} -->${f?" "+f:" "}${La(d.to)}`)}return{content:"```mermaid\n"+c.join(` -`)+"\n```\n",shownModules:o.length,totalModules:e.modules.length,shownEdges:l.length,totalEdges:e.moduleEdges.length}}var $a,gy,_y,hy,xu,hi=F(()=>{"use strict";k();Y();$a=e=>e.replace(/[^\w]/g,"_");gy={0:"Foundations",1:"Features",2:"Tail"},_y=40,hy=80,xu=e=>e.degIn+e.degOut});function Mu(){throw new Error("readline is not available in the browser build (the MCP stdio transport is Node-only)")}var Cu=F(()=>{k()});function yi(e,t){let n=e.properties??{};for(let[r,s]of Object.entries(t)){if(s==null)continue;let o=n[r];if(!o?.type)continue;let a=Array.isArray(s)?"array":typeof s;if(o.type==="number"){let l=a==="number"?s:a==="string"&&s.trim()!==""?Number(s):NaN;if(!Number.isFinite(l))return`\`${r}\` must be a number, got ${a==="string"?JSON.stringify(s):a}`;if(o.minimum!==void 0&&lo.maximum)return`\`${r}\` must be at most ${o.maximum}`;continue}if(o.type==="array"){if(a!=="array")return`\`${r}\` must be an array of strings, got ${a}`;if(o.items?.type==="string"&&!s.every(l=>typeof l=="string"))return`\`${r}\` must be an array of strings`;continue}if(a!==o.type)return`\`${r}\` must be a ${o.type}, got ${a}`}}function bi(e,t,n){if(t||!n)return;let r;try{r=JSON.parse(e)}catch{return}if(!(r===null||typeof r!="object"||Array.isArray(r)))return r}function wi(e){return typeof e=="string"&&Mt.includes(e)?e:Ey}function Si(e,t,n,r){let s=T.byteLength(e,"utf8");if(s<=r)return e;let o=Ba[t]?I(n,ut,Ba[t]):void 0;return JSON.stringify({truncated:!0,tool:t,bytes:s,maxBytes:r,reason:"This response exceeds the configured limit and was withheld rather than sent as an unusable partial payload.",narrower:vy[t]??"narrow the request with `scope`, `include`/`exclude`, or a `limit`",...o&&H(o)?{artifact:o,artifactNote:"The full result is already on disk here \u2014 read it directly if you need all of it."}:o?{artifactNote:`Run \`codeindex index --repo ${n} --out ${I(n,ut)}\` to get this as a file.`}:{}},null,2)+` -`}function ki(e,t){let n=Ba[t];if(!n)return;let r;try{r=JSON.parse(e)}catch{return}if(!(r.truncated!==!0||typeof r.artifact!="string"))return{type:"resource_link",uri:qn(r.artifact).href,name:n,description:`The full ${t} result this call was too large to inline.`,mimeType:"application/json"}}var Mt,Ey,Au,Ur,xi,vy,Ba,Ei=F(()=>{"use strict";k();xe();oe();ws();sr();Mt=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],Ey=Mt[Mt.length-1],Au="2025-03-26",Ur="2025-06-18";xi=1e6,vy={graph:"pass `scope` to a subdirectory, or use repo_map / mermaid for an overview",symbols:"pass `name` to look up one symbol, or use find_symbol / symbols_overview",callers:"pass `name` to look up one symbol's call sites",dead_code:"pass `scope` to a subdirectory",find_references:"the symbol is referenced very widely \u2014 narrow with `scope` on a graph query",check_rules:"narrow the rule set, or pass `scope` to a subdirectory"},Ba={graph:"graph.json",symbols:"symbols.json"}});function za(e){let t=zr[e];if(t)return{readOnlyHint:!t.write,...t.write?{destructiveHint:t.destructive===!0,idempotentHint:t.idempotent===!0}:{},openWorldHint:t.openWorld===!0}}function Hr(){return["all",...Object.keys(vi).sort()]}function qr(e){let t=e.split(",").map(r=>r.trim()).filter(Boolean),n=new Set;for(let r of t){if(r==="all")return new Set(Br.map(o=>o.name));let s=vi[r];if(!s)throw new Error(`unknown tool profile "${r}" \u2014 one of: ${Hr().join(", ")}`);for(let o of s)n.add(o)}return n}function Gr(e,t=Mt[0],n){let r=t>=Au,s=t>=Ur,o=n?qr(n):void 0,a=o?Br.filter(l=>o.has(l.name)):Br;return!e&&!r&&!s?a:a.map(l=>({...l,...s&&zr[l.name]?{title:zr[l.name].title}:{},...s&&fn[l.name]?{outputSchema:fn[l.name]}:{},...r?{annotations:za(l.name)}:{},inputSchema:e?{...l.inputSchema,properties:{...l.inputSchema.properties,repo:{type:"string",description:`Absolute path to the repository root (optional \u2014 defaults to ${e})`}},required:l.inputSchema.required.filter(c=>c!=="repo")}:l.inputSchema}))}var Q,un,Br,Fn,ye,fn,zr,vi,Ri=F(()=>{"use strict";k();Ei();Q={repo:{type:"string",description:"Absolute path to the repository root"}},un={scope:{type:"string",description:"Restrict to one directory (repo-relative)"},include:{type:"array",items:{type:"string"},description:"Include globs"},exclude:{type:"array",items:{type:"string"},description:"Exclude globs"}},Br=[{name:"scan_summary",description:"Deterministically scan a repository: file count, per-language file histogram, HEAD commit, and whether the walk was capped. Fast first look at any codebase.",inputSchema:{type:"object",properties:{...Q,...un},required:["repo"]}},{name:"graph",description:"Build the full typed cross-file link-graph (import/call/use/doc-link/mention edges, module grouping, PageRank centrality, Louvain communities, tests-map). Returns graph.json. Large on big repos \u2014 prefer scan_summary/symbols/callers for targeted questions.",inputSchema:{type:"object",properties:{...Q,...un},required:["repo"]}},{name:"symbols",description:"Where is a symbol defined and which files reference it? Returns the definition sites (file, line, kind, exported) and referencing files. Omit `name` for the full symbol index.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Symbol name to look up"}},required:["repo"]}},{name:"callers",description:"Who calls a function? Per-symbol caller index: each defined symbol with the exact (file, line) call sites that bind to it. Omit `name` for the full index.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Symbol name to look up"},recall:{type:"boolean",description:"Recall-oriented binding: relax the JS/TS import gate to unique repo-wide names, labelling each site corroborated|unique-name (default false = precision)"}},required:["repo"]}},{name:"workspaces",description:"Detect monorepo packages (npm/pnpm/yarn/lerna/nx/cargo/go.work/maven) with the workspace dependency graph, one cycle if present, and a topological build order.",inputSchema:{type:"object",properties:{...Q},required:["repo"]}},{name:"churn",description:"Per-file git commit counts (whole history, or since a ref) \u2014 the churn half of hotspot analysis.",inputSchema:{type:"object",properties:{...Q,since:{type:"string",description:"Only count commits after this ref"}},required:["repo"]}},{name:"symbols_overview",description:"All symbols declared in ONE file (name, kind, line span, exported, parent), in declaration order \u2014 the fastest way to understand a file without reading it.",inputSchema:{type:"object",properties:{...Q,file:{type:"string",description:"Repo-relative file path"}},required:["repo","file"]}},{name:"find_symbol",description:`Find symbol declarations by name or name path ('Class/method' matches a method inside Class). Each match carries its COMPLETE SIGNATURE (parameters and return type) by default, because "what shape is it" is the question that follows "where is it" almost every time and one round trip beats two. Options: substring matching, includeBody for the declaration's source, concise to drop everything but name/kind/file/line when you genuinely only want a location. Exact-name matches rank first.`,inputSchema:{type:"object",properties:{...Q,namePath:{type:"string",description:"Symbol name or Parent/child path"},substring:{type:"boolean"},includeBody:{type:"boolean"},concise:{type:"boolean",description:"Return only name/kind/file/line \u2014 drop the signature, line span, visibility and language. Roughly 2.5x smaller; use it when you are resolving a path and nothing more (default false)."},maxResults:{type:"number",minimum:1,description:"Cap matches (default 50)"}},required:["repo","namePath"]}},{name:"find_references",description:"Who references a symbol? Three labeled tiers: defs (declarations), callSites (line-precise, import-corroborated call bindings), referencingFiles (file-level identifier/doc mentions \u2014 may include homonyms). Confidence decreases across tiers; the labels let you decide what to trust.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Symbol name"},lsp:{type:"boolean",description:"Also ask a configured language server (see lsp_status) and append an `lsp` block: its references plus an `agreement` matrix (both / lspOnly / staticOnly). The three static tiers are unchanged either way. `staticOnly` is where the homonyms are. No config, no binary, a crash or a timeout all degrade to the static answer with a stated reason (default false)."}},required:["repo","name"]}},{name:"lsp_status",description:"Is the optional LSP tier configured, and would it answer? Reports the config path and its source, each server with whether its command is on PATH and how many files in this repo it claims, and the languages no server covers. Opt-in by asset: the tier is active only when /.codeindex/lsp.json exists (or CODEINDEX_LSP_CONFIG points at one). `probe: true` additionally starts each server to read the capabilities it really advertises. The tier never touches graph.json/symbols.json \u2014 it annotates query answers only.",inputSchema:{type:"object",properties:{...Q,probe:{type:"boolean",description:"Start each server and read its real capabilities (default false: no spawn)"}},required:["repo"]}},{name:"onboard",description:"One call that says what this repository IS: its own tagline, size and language mix, monorepo layout when there is one, a token-budgeted map of the highest-PageRank files with their key signatures, and where git says work concentrates. Composes scan_summary + workspaces + repo_map + hotspots so the first four round trips of a session become one, and persists the result as the `onboarding` memory (read_memory) so the next session does not repeat them. Set remember:false to skip the write.",inputSchema:{type:"object",properties:{...Q,budgetTokens:{type:"number",minimum:1,description:"Token budget for the key-files section (default 900)"},remember:{type:"boolean",description:"Persist the brief as the `onboarding` memory (default true)"}},required:["repo"]}},{name:"repo_map",description:"Token-budgeted map of the repository: the highest-PageRank files with their key exported signatures, deterministically rendered to fit `budgetTokens` (default 1024). The densest single read to understand an unfamiliar codebase.",inputSchema:{type:"object",properties:{...Q,budgetTokens:{type:"number",minimum:1,description:"Approximate token budget (default 1024)"}},required:["repo"]}},{name:"hotspots",description:"Where does work concentrate? Files ranked by git churn \xD7 size (commits \xD7 log2 lines). High-scoring files are where changes and defects cluster.",inputSchema:{type:"object",properties:{...Q,since:{type:"string",description:"Only count commits after this ref"}},required:["repo"]}},{name:"coupling",description:"Change coupling: pairs of files that repeatedly change in the same commits \u2014 hidden dependencies no import shows. strength 1.0 = every change to one touched the other.",inputSchema:{type:"object",properties:{...Q,since:{type:"string",description:"Only mine commits after this ref"}},required:["repo"]}},{name:"replace_symbol_body",description:"WRITE: replace a symbol's whole declaration with `body` (verbatim, supply full indentation). The symbol is resolved by name path ('Class/method'); ambiguity errors list the candidates \u2014 qualify with `file`. Line spans come from the AST index.",inputSchema:{type:"object",properties:{...Q,namePath:{type:"string"},body:{type:"string"},file:{type:"string",description:"Disambiguate: repo-relative file containing the symbol"}},required:["repo","namePath","body"]}},{name:"insert_after_symbol",description:"WRITE: insert `body` after a symbol's declaration (blank-line separation preserved for definition-like kinds). Resolved like replace_symbol_body.",inputSchema:{type:"object",properties:{...Q,namePath:{type:"string"},body:{type:"string"},file:{type:"string"}},required:["repo","namePath","body"]}},{name:"insert_before_symbol",description:"WRITE: insert `body` before a symbol's declaration (blank-line separation preserved). Resolved like replace_symbol_body.",inputSchema:{type:"object",properties:{...Q,namePath:{type:"string"},body:{type:"string"},file:{type:"string"}},required:["repo","namePath","body"]}},{name:"write_memory",description:"Persist a named markdown note under /.codeindex/memories/ (names may use topic/name form). Write small, focused notes: project map, build commands, conventions.",inputSchema:{type:"object",properties:{...Q,name:{type:"string"},content:{type:"string"}},required:["repo","name","content"]}},{name:"read_memory",description:"Read one persisted memory by name.",inputSchema:{type:"object",properties:{...Q,name:{type:"string"}},required:["repo","name"]}},{name:"list_memories",description:"List persisted memory names \u2014 load this first, then read individual memories on relevance.",inputSchema:{type:"object",properties:{...Q},required:["repo"]}},{name:"delete_memory",description:"Delete one persisted memory by name.",inputSchema:{type:"object",properties:{...Q,name:{type:"string"}},required:["repo","name"]}},{name:"dead_code",description:"Dead-code candidates in two labeled tiers: 'unreferenced' (no call site binds AND nothing references the name) and 'uncalled' (referenced somewhere \u2014 re-export, type position \u2014 but never called). Exported symbols only; test files and entrypoint-looking files excluded as roots. On a large repo this list runs to thousands of entries \u2014 pass `limit`, or `scope` to one subdirectory.",inputSchema:{type:"object",properties:{...Q,...un,limit:{type:"number",minimum:0,description:"Cap entries (default: all)"}},required:["repo"]}},{name:"duplicated_literals",description:"Values with no single source of truth: one literal written out across many files. Three labeled tiers \u2014 'competing' (two or more exported constants hold the same value), 'bypassed' (a constant holds it and other files rewrite it anyway), 'uncentralized' (nothing holds it). Path-like values are also grouped into namespace families, so a whole route space reports once instead of once per route. Covers config files (JSON/YAML/TOML) as well as code, which is where the dangerous cases live: a threshold declared in TypeScript and again in a rules JSON is checked by no compiler. Use it to answer 'what breaks if this value changes' and 'is there already a helper for this'.",inputSchema:{type:"object",properties:{...Q,...un,minFiles:{type:"number",minimum:1,description:"Distinct files a value must span (default 2)"},minCount:{type:"number",minimum:1,description:"Total occurrences required (default 3)"},includeTests:{type:"boolean",description:"Count test files too (default false)"},limit:{type:"number",minimum:0,description:"Cap duplications (default: all)"}},required:["repo"]}},{name:"complexity",description:"Cyclomatic-complexity estimates (branch-token counting over AST line spans), most-complex first. Pass `file` for one file's symbols, omit for the repo-wide top. Combine with hotspots: the `risk` field of this tool's sibling ranks complexity \xD7 churn.",inputSchema:{type:"object",properties:{...Q,file:{type:"string"},risk:{type:"boolean",description:"Return complexity \xD7 git-churn risk ranking instead"},since:{type:"string",description:"Only count risk churn after this ref"},top:{type:"number",minimum:1,description:"Cap ranked symbols"}},required:["repo"]}},{name:"mermaid",description:"Mermaid diagram of the module graph (renders inline in Claude/GitHub \u2014 no graph database). Optionally scoped to one module's neighborhood.",inputSchema:{type:"object",properties:{...Q,module:{type:"string",description:"Module slug to focus on"},maxEdges:{type:"number",minimum:1,description:"Cap rendered edges"}},required:["repo"]}},{name:"grep",description:"Search file contents (ripgrep when available, deterministic JS fallback otherwise). Returns sorted (file, line, text) hits.",inputSchema:{type:"object",properties:{...Q,pattern:{type:"string",description:"Regular expression to search for"},scope:{type:"string",description:"Restrict to one directory (repo-relative)"},globs:{type:"array",items:{type:"string"},description:"Restrict to matching paths"},ignoreCase:{type:"boolean"},maxHits:{type:"number",minimum:1}},required:["repo","pattern"]}},{name:"search",description:'Natural-language-ish lexical search: BM25F ranking over SIX weighted fields \u2014 symbol names (camelCase/snake_case subtokens), path segments, markdown headings, the file summary, per-symbol DOC COMMENTS, and the prose body (comment + short-literal words). The last two are why "where is rate limiting handled" works: the phrase lives in a comment, not in a name. Results carry `matchedFields`, a `line` anchor and `symbolHits` (name/kind/line). NOT embeddings by default \u2014 deterministic, diacritic-folded, zero API keys. Answers "where is auth handled?"-style queries with ranked files, matched terms and top symbols. Query terms with zero document frequency get a deterministic trigram-fuzzy fallback (typo-tolerant) unless `fuzzy: false`. Set `semantic: true` to RRF-fuse an embedding tier (HTTP endpoint, else a local static model) with lexical \u2014 the response then wraps the ranked list as `{ results, tier, degradedReason? }`, `tier` being "endpoint"/"static" when fusion happened or "lexical" (with `degradedReason`) when it did not (see embed_status). Without `semantic`, the response is the bare ranked array, unchanged.',inputSchema:{type:"object",properties:{...Q,...un,query:{type:"string",description:"Natural-language or identifier query"},limit:{type:"number",minimum:0,description:"Max results (default 20)"},fuzzy:{type:"boolean",description:'Fallback for query terms with zero document frequency: a morphological stem match first ("caching" finds "cache"), then trigram similarity for typos (default true)'},rank:{type:"string",description:`Structural prior: "graph" multiplies the lexical score by the file's PageRank over the resolved import graph; "lexical" (default) scores on text alone. Unproven on the judged corpus \u2014 see SearchOptions.rank.`},exact:{type:"boolean",description:"Drop results that carry no verbatim query-term match \u2014 the ones the stem/trigram bridge produced (default false)."},explain:{type:"boolean",description:"Wrap the response as `{ results, explain }` with the query verdict (default false = bare array). See explain_search."},semantic:{type:"boolean",description:'RRF-fuse an embedding tier with lexical (default false). Precedence: the HTTP endpoint (CODEINDEX_EMBED_ENDPOINT) if set, else a local static model. The response reports the effective tier as a top-level `tier` field ("endpoint"/"static" on success, "lexical" plus `degradedReason` when neither is available/reachable) instead of degrading silently \u2014 see embed_status.'}},required:["repo","query"]}},{name:"explain_search",description:'Search, and say whether the query actually found anything. Returns `{ results, explain }` where explain.verdict is "match" (a verbatim term matched), "weak" (results exist but rest on a near match, or the identifier you asked for has document frequency 0) or "none". Use this instead of `search` whenever an empty-feeling or surprising result matters: a query for an identifier that is NOT in the indexed tree still returns confident-looking rows built from its subtokens \u2014 searching "nullGipStep7" in a repo that only has "nullGipStep2" ranks files matching "null" and "gip" \u2014 and only the verdict distinguishes that from a real hit. Also names the terms dropped as stopwords, the terms that exist nowhere, and what each near match bridged to.',inputSchema:{type:"object",properties:{...Q,...un,query:{type:"string",description:"Natural-language or identifier query"},limit:{type:"number",minimum:0,description:"Max results (default 20)"},fuzzy:{type:"boolean",description:"Stem/trigram fallback for zero-document-frequency terms (default true)"},exact:{type:"boolean",description:"Drop results carrying no verbatim term match (default false)"}},required:["repo","query"]}},{name:"embed_status",description:"Report the embedding tier: the effective mode (none/static/endpoint; endpoint > static model), the resolved model (opt-in, never shipped in the package) with its modelId/dim, EMBED_VERSION, and the configured HTTP endpoint with its reachability. Use to check whether `search` with semantic:true will fuse embeddings or degrade to lexical.",inputSchema:{type:"object",properties:{...Q},required:["repo"]}},{name:"type_hierarchy",description:"How do types relate? For one type: the base classes it extends, the interfaces/traits it implements, and \u2014 the reverse direction, which no other tool answers \u2014 what extends or implements IT, plus any declared supertype with no definition in this repo. Omit `name` for the whole hierarchy.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Type name to look up"}},required:["repo"]}},{name:"implementations",description:"Who implements this interface (or extends this class)? Walks the hierarchy TRANSITIVELY, so a class implementing a sub-interface of the one asked about is included. The tool to reach for before changing an interface.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Interface/trait/class name"}},required:["repo","name"]}},{name:"call_graph",description:"What does this symbol reach, and what reaches it? A bounded symbol-to-symbol neighborhood around `symbol` \u2014 `depth` hops (default 2) following `calls`/`extends`/`implements` edges, `direction` out (callees) | in (callers) | both. Answers impact questions the one-hop `callers` tool cannot.",inputSchema:{type:"object",properties:{...Q,symbol:{type:"string",description:"Symbol name to centre on"},depth:{type:"number",minimum:1,maximum:5,description:"Hops to follow (default 2, max 5)"},direction:{type:"string",description:"out | in | both (default both)"}},required:["repo","symbol"]}},{name:"check_rules",description:'Validate dependency-cruiser-style architecture rules against the link-graph. Rules (inline JSON array): forbidden edges {name, from, to, kind?, severity?, comment?} with glob paths, plus builtins {name, builtin: "cycles"|"orphans"} (module-level import cycles; edge-less code files). Returns deterministic violations with severity error|warn \u2014 a CI gate.',inputSchema:{type:"object",properties:{...Q,...un,rules:{type:"array",description:"Rules array (inline JSON \u2014 see description)"},configPath:{type:"string",description:"Read the rules from this JSON file instead (repo-relative or absolute) \u2014 the CLI's --config. Ignored when `rules` is given."}},required:["repo"]}}],Fn={type:"array",items:{type:"string"}},ye={type:"object"},fn={call_graph:{type:"object",properties:{root:{type:"array",items:ye},nodes:{type:"array",items:ye},edges:{type:"array",items:ye},truncated:{type:"boolean"}},required:["root","nodes","edges"]},scan_summary:{type:"object",properties:{engineVersion:{type:"string"},commit:{type:"string"},fileCount:{type:"integer"},languages:{type:"object",additionalProperties:{type:"integer"}},capped:{type:"boolean"}},required:["engineVersion","fileCount","languages","capped"]},graph:{type:"object",properties:{schemaVersion:{type:"integer"},version:{type:"string"},commit:{type:"string"},fileCount:{type:"integer"},languages:{type:"object",additionalProperties:{type:"integer"}},files:{type:"array",items:ye},modules:{type:"array",items:ye},fileEdges:{type:"array",items:ye},moduleEdges:{type:"array",items:ye}},required:["schemaVersion","files","fileEdges","modules","moduleEdges"]},symbols:{oneOf:[{type:"object",properties:{schemaVersion:{type:"integer"},defs:ye,refs:ye},required:["schemaVersion","defs"]},{type:"object",properties:{name:{type:"string"},defs:{type:"array",items:ye},refs:Fn},required:["name","defs","refs"]}]},callers:{oneOf:[{type:"object",additionalProperties:ye},{type:"object",properties:{error:{type:"string"}},required:["error"]}]},workspaces:{type:"object",properties:{packages:{type:"array",items:ye},cycle:{type:["array","null"],items:{type:"string"}},topoOrder:Fn},required:["packages","topoOrder"]},churn:{type:"object",properties:{ok:{type:"boolean"},churn:{type:"object",additionalProperties:{type:"integer"}}},required:["ok","churn"]},find_references:{type:"object",properties:{defs:{type:"array",items:ye},callSites:{type:"array",items:ye},referencingFiles:Fn},required:["defs","callSites","referencingFiles"]},lsp_status:{type:"object",properties:{lspVersion:{type:"number"},mode:{type:"string",enum:["none","configured"]},configPath:{type:["string","null"]},source:{type:"string",enum:["env","repo","cwd","none"]},servers:{type:"array",items:ye},unmappedLanguages:Fn},required:["lspVersion","mode","source","servers","unmappedLanguages"]},onboard:{type:"object",properties:{brief:{type:"string"},memory:{type:"string"}},required:["brief"]},explain_search:{type:"object",properties:{results:{type:"array",items:ye},explain:{type:"object",properties:{query:{type:"string"},terms:{type:"array",items:ye},droppedStopwords:Fn,unresolvedTerms:Fn,wholeIdentifier:ye,verdict:{type:"string",enum:["match","weak","none"]},note:{type:"string"},bridgedOnlyResults:{type:"number"},resultCount:{type:"number"}},required:["query","terms","droppedStopwords","unresolvedTerms","verdict","bridgedOnlyResults","resultCount"]}},required:["results","explain"]},hotspots:{type:"object",properties:{churnOk:{type:"boolean"},hotspots:{type:"array",items:ye}},required:["churnOk","hotspots"]},coupling:{type:"object",properties:{ok:{type:"boolean"},couplings:{type:"array",items:ye}},required:["ok","couplings"]},duplicated_literals:{type:"object",properties:{duplications:{type:"array",items:ye},families:{type:"array",items:ye}},required:["duplications","families"]},embed_status:{type:"object",properties:{embedVersion:{type:"integer"},mode:{type:"string",enum:["none","static","endpoint"]},model:{},endpoint:{},endpointReachable:{type:"boolean"}},required:["embedVersion","mode"]},write_memory:{type:"object",properties:{written:{type:"string"}},required:["written"]},delete_memory:{type:"object",properties:{deleted:{type:"boolean"}},required:["deleted"]}};for(let e of["replace_symbol_body","insert_after_symbol","insert_before_symbol"])fn[e]={type:"object",properties:{file:{type:"string"},symbol:{type:"string"},startLine:{type:"integer"},endLine:{type:"integer"}},required:["file"]};zr={scan_summary:{title:"Scan summary"},graph:{title:"Link graph"},symbols:{title:"Symbol index"},callers:{title:"Caller index"},workspaces:{title:"Monorepo workspaces"},churn:{title:"Git churn"},symbols_overview:{title:"File symbol overview"},find_symbol:{title:"Find symbol"},find_references:{title:"Find references"},repo_map:{title:"Repository map"},onboard:{title:"Project brief",write:!0,destructive:!1,idempotent:!0},hotspots:{title:"Hotspots"},coupling:{title:"Change coupling"},replace_symbol_body:{title:"Replace symbol body",write:!0,destructive:!0,idempotent:!0},insert_after_symbol:{title:"Insert after symbol",write:!0,destructive:!1,idempotent:!1},insert_before_symbol:{title:"Insert before symbol",write:!0,destructive:!1,idempotent:!1},write_memory:{title:"Write memory",write:!0,destructive:!1,idempotent:!0},read_memory:{title:"Read memory"},list_memories:{title:"List memories"},delete_memory:{title:"Delete memory",write:!0,destructive:!0,idempotent:!0},dead_code:{title:"Dead-code candidates"},duplicated_literals:{title:"Values with no single source of truth"},complexity:{title:"Complexity"},mermaid:{title:"Mermaid module diagram"},grep:{title:"Grep file contents"},search:{title:"Lexical search",openWorld:!0},explain_search:{title:"Search with a verdict",openWorld:!0},lsp_status:{title:"LSP tier status",openWorld:!0},embed_status:{title:"Embedding tier status",openWorld:!0},type_hierarchy:{title:"Type hierarchy"},implementations:{title:"Implementations"},call_graph:{title:"Call graph neighborhood"},check_rules:{title:"Check architecture rules"}};vi={orient:["scan_summary","repo_map","onboard","workspaces","mermaid","read_memory","list_memories"],find:["search","explain_search","grep","find_symbol","symbols","symbols_overview"],impact:["find_references","callers","call_graph","dead_code","type_hierarchy","implementations","lsp_status"],edit:["find_symbol","symbols_overview","replace_symbol_body","insert_after_symbol","insert_before_symbol"],risk:["hotspots","churn","coupling","complexity","check_rules","duplicated_literals","dead_code"]}});function Ha(e){return Me(e.files.map(t=>`${t.rel}:${t.hash}`).join(` -`))}async function Vr(e,t){let n=`${e.mode}:${e.identity}:${Ha(e.scan)}`;if(Mi&&Mi.key===n)return Mi.index;let r=await t();return Mi={key:n,index:r},r}function Jr(e){let t;try{t=Ee(I(e,"model.json"))}catch{return}let n=`${e}:${t.mtimeMs}:${t.size}`;if(Ci&&Ci.key===n)return Ci.model;let r=Wt(e);return r&&(Ci={key:n,model:r}),r}function Tu(e){let t=Je.findIndex(r=>r.key===e);if(t<0)return;let[n]=Je.splice(t,1);return Je.unshift(n),n}function zt(e){let t=Je.findIndex(n=>n.key===e.key);return t>=0&&Je.splice(t,1),Je.unshift(e),Je.length=Math.min(Je.length,Ry),e}function Iu(){Je.length=0}function qa(e,t){let n=e+"\0";for(let r of Je)r.key.startsWith(n)&&(t?r.cacheMap.delete(t):r.cacheMap.clear())}function Nu(e,t){return e+"\0"+JSON.stringify({scope:t.scope,include:t.include,exclude:t.exclude,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs,maxBytes:t.maxBytes,maxFiles:t.maxFiles,maxCallsPerFile:t.maxCallsPerFile,out:t.out,fullHash:t.fullHash})}function Kr(e,t={},n){let r=Nu(e,t),s=Tu(r);if(s){let l=Pe(e,{...t,cache:s.cacheMap,precomputedWalk:n});return l.contentUnchanged?(l.cacheDirty&&(s.cacheMap=De(l)),s.scan.commit!==l.commit&&(s.scan.commit=l.commit,s.arts=void 0,s.loadArtifacts=void 0),s.scan):(zt({key:r,scan:l,cacheMap:De(l)}),l)}let o=Po(e,{...t,precomputedWalk:n});if(o)return zt({key:r,scan:o.scan,cacheMap:o.cacheMap,arts:o.arts}),o.scan;let a=Pe(e,{...t,precomputedWalk:n});return zt({key:r,scan:a,cacheMap:De(a)}),a}async function Ai(e,t={},n,r=async()=>{}){let s=Nu(e,t),o=Je.find(c=>c.key===s);if(o){let c=o.cacheMap,d=m=>(m.cacheDirty&&(o.cacheMap=De(m)),o.scan.commit!==m.commit&&(o.scan.commit=m.commit,o.arts=void 0,o.loadArtifacts=void 0),Tu(s),o.scan);if(n&&No(n,c,t.fullHash)){await r();let m=await Pt(e,{...t,cache:c,precomputedWalk:n});return m.contentUnchanged?d(m):(zt({key:s,scan:m,cacheMap:De(m)}),m)}let f=Pe(e,{...t,cache:c,precomputedWalk:n});if(f.contentUnchanged)return d(f);if(n)return zt({key:s,scan:f,cacheMap:De(f)}),f;await r();let u=await Pt(e,{...t,cache:c,precomputedWalk:n});return zt({key:s,scan:u,cacheMap:De(u)}),u}let a=await Is(e,{...t,precomputedWalk:n},r);if(a)return zt({key:s,scan:a.scan,cacheMap:a.cacheMap,arts:a.arts,loadArtifacts:a.loadArtifacts}),a.scan;await r();let l=await Pt(e,{...t,precomputedWalk:n});return zt({key:s,scan:l,cacheMap:De(l)}),l}function Ti(e,t={},n){return rr(e,{...t,precomputedWalk:n})}function Ii(e,t={},n,r){let s=r??Kr(e,t,n),o=Je.find(a=>a.scan===s);return o?o.arts??=o.loadArtifacts?.()??Et(s,t):Et(s,t)}async function Ou(e){await Xr(Fe(e,{}))}async function Xr(e){await et(bt(e.files.map(t=>t.ext)))}var Mi,Ci,Ry,Je,Ga=F(()=>{"use strict";k();xe();oe();ri();Ft();Os();sr();Ae();nt();sn();On();At();Ry=4,Je=[]});var $u={};Oi($u,{DEFAULT_MAX_RESPONSE_BYTES:()=>xi,OUTPUT_SCHEMAS:()=>fn,PROTOCOL_VERSIONS:()=>Mt,TOOLS:()=>Br,TOOL_META:()=>zr,TOOL_PROFILES:()=>vi,annotationsFor:()=>za,capResponse:()=>Si,getArtifacts:()=>Ii,getScan:()=>Kr,getScanParallel:()=>Ai,getScanSummary:()=>Ti,memoizedEmbedModel:()=>Jr,memoizedEmbeddingIndex:()=>Vr,negotiateProtocol:()=>wi,profileNames:()=>Hr,resourceLinkFor:()=>ki,runMcpServer:()=>Pu,scanFingerprint:()=>Ha,structuredContentFor:()=>bi,toCacheMap:()=>De,toolsFor:()=>Gr,toolsInProfiles:()=>qr,validateArgs:()=>yi,warmGrammarsForRepo:()=>Ou,warmGrammarsForWalk:()=>Xr});function My(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.jsonrpc!=="2.0"||typeof t.method!="string"?!1:t.id===void 0||t.id===null||typeof t.id=="number"||typeof t.id=="string"}function Cy(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method!="string"&&("result"in t||"error"in t)}function se(e){return typeof e=="string"&&e?e:void 0}function Va(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")&&e.length?e:void 0}function Zr(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return Number.isFinite(t)&&t>=0?t:void 0}function Ke(e){let t=Zr(e);return t!==void 0&&t>0?t:void 0}function Fu(e){return e instanceof Error?e.message:String(e)}async function Ty(e,t,n){let r=se(t.repo)??n;if(!r)throw new Error("`repo` is required (absolute path to the repository root)");try{if(!Ee(r).isDirectory())throw new Error("not a directory")}catch{throw new Error(`repository root is not a readable directory: ${r}`)}let s={scope:se(t.scope),include:Va(t.include),exclude:Va(t.exclude)},o=se(t.rank),a=o==="graph"||o==="lexical"?{rank:o}:{},l,c;Ay.has(e)||(l=Fe(r,{}),c=await Ai(r,s,l,()=>l?Xr(l):Promise.resolve()));let d=()=>c??Kr(r,s,l),f=()=>Ii(r,s,l,c);if(e==="scan_summary"){let u=Ti(r,s,l);return JSON.stringify({engineVersion:fe,commit:u.commit,fileCount:u.fileCount,languages:u.languages,capped:u.capped},null,2)}if(e==="graph")return In(f().graph);if(e==="symbols"){let{symbols:u}=f(),m=se(t.name);return JSON.stringify(m?{name:m,defs:u.defs[m]??[],refs:u.refs[m]??[]}:u,null,2)}if(e==="callers"){let u=d(),m=t.recall===!0?Zt(u,void 0,{recall:!0}):Cn(u),p=se(t.name);if(p){let y=m.get(p);return JSON.stringify(y??{error:`no tracked callers for "${p}"`},null,2)}let g={};for(let[y,h]of m)g[y]=h;return JSON.stringify(g,null,2)}if(e==="workspaces"){let u=nn(r);return JSON.stringify({packages:u.packages,cycle:u.cycle??null,topoOrder:u.topoOrder},null,2)}if(e==="churn"){let{churn:u,ok:m}=Ze(r,{since:se(t.since)}),p={};for(let g of[...u.keys()].sort())p[g]=u.get(g);return JSON.stringify({ok:m,churn:p},null,2)}if(e==="symbols_overview"){let u=se(t.file);if(!u)throw new Error("`file` is required");return JSON.stringify(ra(d(),u),null,2)}if(e==="find_symbol"){let u=se(t.namePath);if(!u)throw new Error("`namePath` is required");let m=An(d(),u,{substring:t.substring===!0,includeBody:t.includeBody===!0,concise:t.concise===!0,maxResults:Ke(t.maxResults)});return JSON.stringify(m,null,2)}if(e==="find_references"){let u=se(t.name);if(!u)throw new Error("`name` is required");let m=d(),p=sa(m,u);return t.lsp===!0?JSON.stringify(await Pa(m,r,u,p),null,2):JSON.stringify(p,null,2)}if(e==="lsp_status")return JSON.stringify(await Pr(d(),r,t.probe===!0),null,2);if(e==="replace_symbol_body"||e==="insert_after_symbol"||e==="insert_before_symbol"){let u=se(t.namePath),m=typeof t.body=="string"?t.body:void 0;if(!u||m===void 0)throw new Error("`namePath` and `body` are required");let p=d(),y=(e==="replace_symbol_body"?ia:e==="insert_after_symbol"?oa:aa)(p,u,m,se(t.file));return Iu(),JSON.stringify(y,null,2)}if(e==="write_memory"){let u=se(t.name),m=typeof t.content=="string"?t.content:void 0;if(!u||m===void 0)throw new Error("`name` and `content` are required");return JSON.stringify({written:br(r,u,m)},null,2)}if(e==="read_memory"){let u=se(t.name);if(!u)throw new Error("`name` is required");let m=da(r,u);if(m===void 0)throw new Error(`no memory named "${u}" \u2014 see list_memories`);return m}if(e==="list_memories")return JSON.stringify(fa(r),null,2);if(e==="delete_memory"){let u=se(t.name);if(!u)throw new Error("`name` is required");return JSON.stringify({deleted:ua(r,u)},null,2)}if(e==="dead_code"){let u=Dr(d()),m=Zr(t.limit);return m===void 0||u.length<=m?JSON.stringify(u,null,2):JSON.stringify({total:u.length,shown:m,truncated:!0,candidates:u.slice(0,m)},null,2)}if(e==="duplicated_literals"){let u=rn(d(),{minFiles:Ke(t.minFiles),minCount:Ke(t.minCount),includeTests:t.includeTests===!0}),m=Zr(t.limit);return m===void 0||u.duplications.length<=m?JSON.stringify(u,null,2):JSON.stringify({total:u.duplications.length,shown:m,truncated:!0,duplications:u.duplications.slice(0,m),families:u.families},null,2)}if(e==="complexity"){let u=d();if(t.risk===!0){let{churn:m,ok:p}=Ze(r,{since:se(t.since)});return JSON.stringify({churnOk:p,risks:hr(u,m,Ke(t.top))},null,2)}return JSON.stringify(_r(u,se(t.file),Ke(t.top)),null,2)}if(e==="mermaid"){let{graph:u}=f();return jr(u,{module:se(t.module),maxEdges:Ke(t.maxEdges)})}if(e==="onboard"){let u=d(),{graph:m}=f();return JSON.stringify(ka(u,m,{...Ke(t.budgetTokens)!==void 0?{budgetTokens:Ke(t.budgetTokens)}:{},...t.remember===!1?{remember:!1}:{}}),null,2)}if(e==="repo_map"){let{scan:u,graph:m}=f();return ln(u,m,{budgetTokens:Ke(t.budgetTokens)})}if(e==="hotspots"){let u=d(),{churn:m,ok:p}=Ze(r,{since:se(t.since)});return JSON.stringify({churnOk:p,hotspots:cn(u,m)},null,2)}if(e==="coupling"){let{ok:u,couplings:m}=Or(r,{since:se(t.since)});return JSON.stringify({ok:u,couplings:m},null,2)}if(e==="grep"){let u=se(t.pattern);if(!u)throw new Error("`pattern` is required");let m=se(t.scope),p=Va(t.globs),g=Er(r,u,{globs:m?[...p??[],`${m.replace(/\/+$/,"")}/**`]:p,ignoreCase:t.ignoreCase===!0,maxHits:Ke(t.maxHits)});return JSON.stringify(g,null,2)}if(e==="search"){let u=se(t.query);if(!u)throw new Error("`query` is required");let m=d(),p=Zr(t.limit),g=typeof t.fuzzy=="boolean"?t.fuzzy:void 0,y=t.exact===!0?{exact:!0}:{};if(t.semantic===!0){let _=Ut();if(_)try{let v=await Vr({mode:"endpoint",identity:_,scan:m},()=>Ir(m)),A=await Tr(u),O=an(m,u,v,{queryVec:A,limit:p,fuzzy:g});return JSON.stringify({results:O,tier:"endpoint"},null,2)}catch(v){let A=Lt(m,u,{limit:p,fuzzy:g,...a});return JSON.stringify({results:A,tier:"lexical",degradedReason:`embedding endpoint failed: ${Fu(v)}`},null,2)}let E=vt(r),b=E?Jr(E):void 0;if(b){let v=await Vr({mode:"static",identity:`${E}#${b.modelId}`,scan:m},()=>on(m,b)),A=an(m,u,v,{model:b,limit:p,fuzzy:g});return JSON.stringify({results:A,tier:"static"},null,2)}let x=Lt(m,u,{limit:p,fuzzy:g,...a});return JSON.stringify({results:x,tier:"lexical",degradedReason:"no embedding endpoint or static model configured \u2014 see embed_status"},null,2)}let{results:h,explain:S}=tn(m,u,{limit:p,fuzzy:g,...y,...a});return JSON.stringify(t.explain===!0?{results:h,explain:S}:h,null,2)}if(e==="explain_search"){let u=se(t.query);if(!u)throw new Error("`query` is required");let m=d(),p=Zr(t.limit),g=typeof t.fuzzy=="boolean"?t.fuzzy:void 0,{results:y,explain:h}=tn(m,u,{limit:p,fuzzy:g,...t.exact===!0?{exact:!0}:{},...a});return JSON.stringify({results:y,explain:h},null,2)}if(e==="embed_status"){let u=vt(r),m=u?Jr(u):void 0,p=Ut(),y={embedVersion:it,mode:p?"endpoint":m?"static":"none",model:m?{present:!0,dir:u,modelId:m.modelId,dim:m.dim,vocabSize:m.vocabSize}:{present:!1},endpoint:p??null};return p&&(y.endpointReachable=await Ar(p)),JSON.stringify(y,null,2)}if(e==="type_hierarchy"){let u=Yo(d()),m=se(t.name);if(!m){let g={};for(let[y,h]of u)g[y]=h;return JSON.stringify(g,null,2)}let p=u.get(m);return JSON.stringify(p||{error:`no type named ${m}`},null,2)}if(e==="implementations"){let u=se(t.name);if(!u)throw new Error("`name` is required");let m=Yo(d());return m.has(u)?JSON.stringify({name:u,implementations:lr(m,u)},null,2):JSON.stringify({error:`no type named ${u}`},null,2)}if(e==="call_graph"){let u=se(t.symbol);if(!u)throw new Error("`symbol` is required");let m=se(t.direction),p=m==="out"||m==="in"?m:"both",g=fr(vd(d()),u,{...Ke(t.depth)!==void 0?{depth:Ke(t.depth)}:{},direction:p});return g.root.length?JSON.stringify(g,null,2):JSON.stringify({error:`no symbol named ${u}`},null,2)}if(e==="check_rules"){let u=se(t.configPath),m=t.rules;if(m===void 0&&u){let y=Qr(u)?u:I(r,u);try{m=JSON.parse(te(y,"utf8"))}catch(h){throw new Error(`cannot read rules from ${y}: ${Fu(h)}`)}}if(m===void 0)throw new Error("`rules` (or `configPath`) is required");let p=$r(m),{graph:g}=f();return JSON.stringify(Lr(g,p),null,2)}throw new Error(`unknown tool: ${e}`)}async function Pu(e={}){let t={name:e.serverInfo?.name??"codeindex",version:e.serverInfo?.version??fe},n=Mt[0],r=Gr(e.defaultRepo,n,e.profile),s;if(e.watch&&e.defaultRepo)try{s=cl(e.defaultRepo,{recursive:!0},(c,d)=>{let f=d?.toString().replaceAll("\\","/")??"";f.split("/").some(m=>qt.has(m)||m.startsWith(".codeindex-edit-"))||qa(e.defaultRepo,f||void 0)}),s.on("error",c=>{R.stderr.write(`codeindex: MCP watcher disabled (${c.message}); using freshness scans -`),s?.close(),s=void 0,qa(e.defaultRepo)})}catch(c){R.stderr.write(`codeindex: MCP watcher unavailable (${c instanceof Error?c.message:String(c)}); using freshness scans +`}function Ua(e){return"m_"+e.replace(/[^A-Za-z0-9_]/g,"_")}function By(e,t={}){let n=t.maxModules??Wy,r=t.maxEdges??Uy,o=e.modules.slice().sort((d,f)=>Fu(f)-Fu(d)||M(d.slug,f.slug)).slice(0,n),a=new Set(o.map(d=>d.slug)),l=e.moduleEdges.filter(d=>a.has(d.from)&&a.has(d.to)).sort((d,f)=>f.weight-d.weight||M(d.from,f.from)||M(d.to,f.to)).slice(0,r),c=[];c.push(`%% ${t.title??"module graph"} \u2014 ${o.length} of ${e.modules.length} modules, ${l.length} of ${e.moduleEdges.length} edges`),(o.lengthu.tier===d);if(f.length){c.push(` subgraph ${jy[d]}`);for(let u of f)c.push(` ${Ua(u.slug)}["${u.path.replace(/"/g,"'")}"]`);c.push(" end")}}for(let d of l){let f=d.weight>1?`|${d.weight}| `:"";c.push(` ${Ua(d.from)} -->${f?" "+f:" "}${Ua(d.to)}`)}return{content:"```mermaid\n"+c.join(` +`)+"\n```\n",shownModules:o.length,totalModules:e.modules.length,shownEdges:l.length,totalEdges:e.moduleEdges.length}}var Wa,jy,Wy,Uy,Fu,wi=O(()=>{"use strict";E();Y();Wa=e=>e.replace(/[^\w]/g,"_");jy={0:"Foundations",1:"Features",2:"Tail"},Wy=40,Uy=80,Fu=e=>e.degIn+e.degOut});function Uu(){throw new Error("readline is not available in the browser build (the MCP stdio transport is Node-only)")}var Bu=O(()=>{E()});function xi(e,t){let n=e.properties??{};for(let[r,s]of Object.entries(t)){if(s==null)continue;let o=n[r];if(!o?.type)continue;let a=Array.isArray(s)?"array":typeof s;if(o.type==="number"){let l=a==="number"?s:a==="string"&&s.trim()!==""?Number(s):NaN;if(!Number.isFinite(l))return`\`${r}\` must be a number, got ${a==="string"?JSON.stringify(s):a}`;if(o.minimum!==void 0&&lo.maximum)return`\`${r}\` must be at most ${o.maximum}`;continue}if(o.type==="array"){if(a!=="array")return`\`${r}\` must be an array of strings, got ${a}`;if(o.items?.type==="string"&&!s.every(l=>typeof l=="string"))return`\`${r}\` must be an array of strings`;continue}if(a!==o.type)return`\`${r}\` must be a ${o.type}, got ${a}`}}function Si(e,t,n){if(t||!n)return;let r;try{r=JSON.parse(e)}catch{return}if(!(r===null||typeof r!="object"||Array.isArray(r)))return r}function ki(e){return typeof e=="string"&&Ct.includes(e)?e:Xy}function vi(e,t,n,r){let s=N.byteLength(e,"utf8");if(s<=r)return e;let o=qa[t]?I(n,ft,qa[t]):void 0;return JSON.stringify({truncated:!0,tool:t,bytes:s,maxBytes:r,reason:"This response exceeds the configured limit and was withheld rather than sent as an unusable partial payload.",narrower:Zy[t]??"narrow the request with `scope`, `include`/`exclude`, or a `limit`",...o&&H(o)?{artifact:o,artifactNote:"The full result is already on disk here \u2014 read it directly if you need all of it."}:o?{artifactNote:`Run \`codeindex index --repo ${n} --out ${I(n,ft)}\` to get this as a file.`}:{}},null,2)+` +`}function Ri(e,t){let n=qa[t];if(!n)return;let r;try{r=JSON.parse(e)}catch{return}if(!(r.truncated!==!0||typeof r.artifact!="string"))return{type:"resource_link",uri:qn(r.artifact).href,name:n,description:`The full ${t} result this call was too large to inline.`,mimeType:"application/json"}}var Ct,Xy,zu,zr,Ei,Zy,qa,Mi=O(()=>{"use strict";E();xe();ae();ks();or();Ct=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],Xy=Ct[Ct.length-1],zu="2025-03-26",zr="2025-06-18";Ei=1e6,Zy={graph:"pass `scope` to a subdirectory, or use repo_map / mermaid for an overview",symbols:"pass `name` to look up one symbol, or use find_symbol / symbols_overview",callers:"pass `name` to look up one symbol's call sites",dead_code:"pass `scope` to a subdirectory",find_references:"the symbol is referenced very widely \u2014 narrow with `scope` on a graph query",check_rules:"narrow the rule set, or pass `scope` to a subdirectory"},qa={graph:"graph.json",symbols:"symbols.json"}});function Va(e){let t=Gr[e];if(t)return{readOnlyHint:!t.write,...t.write?{destructiveHint:t.destructive===!0,idempotentHint:t.idempotent===!0}:{},openWorldHint:t.openWorld===!0}}function qr(){return["all",...Object.keys(Ci).sort()]}function Vr(e){let t=e.split(",").map(r=>r.trim()).filter(Boolean),n=new Set;for(let r of t){if(r==="all")return new Set(Hr.map(o=>o.name));let s=Ci[r];if(!s)throw new Error(`unknown tool profile "${r}" \u2014 one of: ${qr().join(", ")}`);for(let o of s)n.add(o)}return n}function Jr(e,t=Ct[0],n){let r=t>=zu,s=t>=zr,o=n?Vr(n):void 0,a=o?Hr.filter(l=>o.has(l.name)):Hr;return!e&&!r&&!s?a:a.map(l=>({...l,...s&&Gr[l.name]?{title:Gr[l.name].title}:{},...s&&mn[l.name]?{outputSchema:mn[l.name]}:{},...r?{annotations:Va(l.name)}:{},inputSchema:e?{...l.inputSchema,properties:{...l.inputSchema.properties,repo:{type:"string",description:`Absolute path to the repository root (optional \u2014 defaults to ${e})`}},required:l.inputSchema.required.filter(c=>c!=="repo")}:l.inputSchema}))}var ee,fn,Hr,On,ye,mn,Gr,Ci,Ai=O(()=>{"use strict";E();Mi();ee={repo:{type:"string",description:"Absolute path to the repository root"}},fn={scope:{type:"string",description:"Restrict to one directory (repo-relative)"},include:{type:"array",items:{type:"string"},description:"Include globs"},exclude:{type:"array",items:{type:"string"},description:"Exclude globs"}},Hr=[{name:"scan_summary",description:"Deterministically scan a repository: file count, per-language file histogram, HEAD commit, and whether the walk was capped. Fast first look at any codebase.",inputSchema:{type:"object",properties:{...ee,...fn},required:["repo"]}},{name:"graph",description:"Build the full typed cross-file link-graph (import/call/use/doc-link/mention edges, module grouping, PageRank centrality, Louvain communities, tests-map). Returns graph.json. Large on big repos \u2014 prefer scan_summary/symbols/callers for targeted questions.",inputSchema:{type:"object",properties:{...ee,...fn},required:["repo"]}},{name:"symbols",description:"Where is a symbol defined and which files reference it? Returns the definition sites (file, line, kind, exported) and referencing files. Omit `name` for the full symbol index.",inputSchema:{type:"object",properties:{...ee,name:{type:"string",description:"Symbol name to look up"}},required:["repo"]}},{name:"callers",description:"Who calls a function? Per-symbol caller index: each defined symbol with the exact (file, line) call sites that bind to it. Omit `name` for the full index.",inputSchema:{type:"object",properties:{...ee,name:{type:"string",description:"Symbol name to look up"},recall:{type:"boolean",description:"Recall-oriented binding: relax the JS/TS import gate to unique repo-wide names, labelling each site corroborated|unique-name (default false = precision)"}},required:["repo"]}},{name:"workspaces",description:"Detect monorepo packages (npm/pnpm/yarn/lerna/nx/cargo/go.work/maven) with the workspace dependency graph, one cycle if present, and a topological build order.",inputSchema:{type:"object",properties:{...ee},required:["repo"]}},{name:"churn",description:"Per-file git commit counts (whole history, or since a ref) \u2014 the churn half of hotspot analysis.",inputSchema:{type:"object",properties:{...ee,since:{type:"string",description:"Only count commits after this ref"}},required:["repo"]}},{name:"symbols_overview",description:"All symbols declared in ONE file (name, kind, line span, exported, parent), in declaration order \u2014 the fastest way to understand a file without reading it.",inputSchema:{type:"object",properties:{...ee,file:{type:"string",description:"Repo-relative file path"}},required:["repo","file"]}},{name:"find_symbol",description:`Find symbol declarations by name or name path ('Class/method' matches a method inside Class). Each match carries its COMPLETE SIGNATURE (parameters and return type) by default, because "what shape is it" is the question that follows "where is it" almost every time and one round trip beats two. Options: substring matching, includeBody for the declaration's source, concise to drop everything but name/kind/file/line when you genuinely only want a location. Exact-name matches rank first.`,inputSchema:{type:"object",properties:{...ee,namePath:{type:"string",description:"Symbol name or Parent/child path"},substring:{type:"boolean"},includeBody:{type:"boolean"},concise:{type:"boolean",description:"Return only name/kind/file/line \u2014 drop the signature, line span, visibility and language. Roughly 2.5x smaller; use it when you are resolving a path and nothing more (default false)."},maxResults:{type:"number",minimum:1,description:"Cap matches (default 50)"}},required:["repo","namePath"]}},{name:"find_references",description:"Who references a symbol? Three labeled tiers: defs (declarations), callSites (line-precise, import-corroborated call bindings), referencingFiles (file-level identifier/doc mentions \u2014 may include homonyms). Confidence decreases across tiers; the labels let you decide what to trust.",inputSchema:{type:"object",properties:{...ee,name:{type:"string",description:"Symbol name"},lsp:{type:"boolean",description:"Also ask a configured language server (see lsp_status) and append an `lsp` block: its references plus an `agreement` matrix (both / lspOnly / staticOnly). The three static tiers are unchanged either way. `staticOnly` is where the homonyms are. No config, no binary, a crash or a timeout all degrade to the static answer with a stated reason (default false)."}},required:["repo","name"]}},{name:"lsp_status",description:"Is the optional LSP tier configured, and would it answer? Reports the config path and its source, each server with whether its command is on PATH and how many files in this repo it claims, and the languages no server covers. Opt-in by asset: the tier is active only when /.codeindex/lsp.json exists (or CODEINDEX_LSP_CONFIG points at one). `probe: true` additionally starts each server to read the capabilities it really advertises. The tier never touches graph.json/symbols.json \u2014 it annotates query answers only.",inputSchema:{type:"object",properties:{...ee,probe:{type:"boolean",description:"Start each server and read its real capabilities (default false: no spawn)"}},required:["repo"]}},{name:"onboard",description:"One call that says what this repository IS: its own tagline, size and language mix, monorepo layout when there is one, a token-budgeted map of the highest-PageRank files with their key signatures, and where git says work concentrates. Composes scan_summary + workspaces + repo_map + hotspots so the first four round trips of a session become one, and persists the result as the `onboarding` memory (read_memory) so the next session does not repeat them. Set remember:false to skip the write.",inputSchema:{type:"object",properties:{...ee,budgetTokens:{type:"number",minimum:1,description:"Token budget for the key-files section (default 900)"},remember:{type:"boolean",description:"Persist the brief as the `onboarding` memory (default true)"}},required:["repo"]}},{name:"repo_map",description:"Token-budgeted map of the repository: the highest-PageRank files with their key exported signatures, deterministically rendered to fit `budgetTokens` (default 1024). The densest single read to understand an unfamiliar codebase.",inputSchema:{type:"object",properties:{...ee,budgetTokens:{type:"number",minimum:1,description:"Approximate token budget (default 1024)"}},required:["repo"]}},{name:"hotspots",description:"Where does work concentrate? Files ranked by git churn \xD7 size (commits \xD7 log2 lines). High-scoring files are where changes and defects cluster.",inputSchema:{type:"object",properties:{...ee,since:{type:"string",description:"Only count commits after this ref"}},required:["repo"]}},{name:"coupling",description:"Change coupling: pairs of files that repeatedly change in the same commits \u2014 hidden dependencies no import shows. strength 1.0 = every change to one touched the other.",inputSchema:{type:"object",properties:{...ee,since:{type:"string",description:"Only mine commits after this ref"}},required:["repo"]}},{name:"replace_symbol_body",description:"WRITE: replace a symbol's whole declaration with `body` (verbatim, supply full indentation). The symbol is resolved by name path ('Class/method'); ambiguity errors list the candidates \u2014 qualify with `file`. Line spans come from the AST index.",inputSchema:{type:"object",properties:{...ee,namePath:{type:"string"},body:{type:"string"},file:{type:"string",description:"Disambiguate: repo-relative file containing the symbol"}},required:["repo","namePath","body"]}},{name:"insert_after_symbol",description:"WRITE: insert `body` after a symbol's declaration (blank-line separation preserved for definition-like kinds). Resolved like replace_symbol_body.",inputSchema:{type:"object",properties:{...ee,namePath:{type:"string"},body:{type:"string"},file:{type:"string"}},required:["repo","namePath","body"]}},{name:"insert_before_symbol",description:"WRITE: insert `body` before a symbol's declaration (blank-line separation preserved). Resolved like replace_symbol_body.",inputSchema:{type:"object",properties:{...ee,namePath:{type:"string"},body:{type:"string"},file:{type:"string"}},required:["repo","namePath","body"]}},{name:"write_memory",description:"Persist a named markdown note under /.codeindex/memories/ (names may use topic/name form). Write small, focused notes: project map, build commands, conventions.",inputSchema:{type:"object",properties:{...ee,name:{type:"string"},content:{type:"string"}},required:["repo","name","content"]}},{name:"read_memory",description:"Read one persisted memory by name.",inputSchema:{type:"object",properties:{...ee,name:{type:"string"}},required:["repo","name"]}},{name:"list_memories",description:"List persisted memory names \u2014 load this first, then read individual memories on relevance.",inputSchema:{type:"object",properties:{...ee},required:["repo"]}},{name:"delete_memory",description:"Delete one persisted memory by name.",inputSchema:{type:"object",properties:{...ee,name:{type:"string"}},required:["repo","name"]}},{name:"dead_code",description:"Dead-code candidates in two labeled tiers: 'unreferenced' (no call site binds AND nothing references the name) and 'uncalled' (referenced somewhere \u2014 re-export, type position \u2014 but never called). Exported symbols only; test files and entrypoint-looking files excluded as roots. On a large repo this list runs to thousands of entries \u2014 pass `limit`, or `scope` to one subdirectory.",inputSchema:{type:"object",properties:{...ee,...fn,limit:{type:"number",minimum:0,description:"Cap entries (default: all)"}},required:["repo"]}},{name:"duplicated_literals",description:"Values with no single source of truth: one literal written out across many files. Three labeled tiers \u2014 'competing' (two or more exported constants hold the same value), 'bypassed' (a constant holds it and other files rewrite it anyway), 'uncentralized' (nothing holds it). Path-like values are also grouped into namespace families, so a whole route space reports once instead of once per route. Covers config files (JSON/YAML/TOML) as well as code, which is where the dangerous cases live: a threshold declared in TypeScript and again in a rules JSON is checked by no compiler. Use it to answer 'what breaks if this value changes' and 'is there already a helper for this'.",inputSchema:{type:"object",properties:{...ee,...fn,minFiles:{type:"number",minimum:1,description:"Distinct files a value must span (default 2)"},minCount:{type:"number",minimum:1,description:"Total occurrences required (default 3)"},includeTests:{type:"boolean",description:"Count test files too (default false)"},limit:{type:"number",minimum:0,description:"Cap duplications (default: all)"}},required:["repo"]}},{name:"complexity",description:"Cyclomatic-complexity estimates (branch-token counting over AST line spans), most-complex first. Pass `file` for one file's symbols, omit for the repo-wide top. Combine with hotspots: the `risk` field of this tool's sibling ranks complexity \xD7 churn.",inputSchema:{type:"object",properties:{...ee,file:{type:"string"},risk:{type:"boolean",description:"Return complexity \xD7 git-churn risk ranking instead"},since:{type:"string",description:"Only count risk churn after this ref"},top:{type:"number",minimum:1,description:"Cap ranked symbols"}},required:["repo"]}},{name:"mermaid",description:"Mermaid diagram of the module graph (renders inline in Claude/GitHub \u2014 no graph database). Optionally scoped to one module's neighborhood.",inputSchema:{type:"object",properties:{...ee,module:{type:"string",description:"Module slug to focus on"},maxEdges:{type:"number",minimum:1,description:"Cap rendered edges"}},required:["repo"]}},{name:"grep",description:"Search file contents (ripgrep when available, deterministic JS fallback otherwise). Returns sorted (file, line, text) hits.",inputSchema:{type:"object",properties:{...ee,pattern:{type:"string",description:"Regular expression to search for"},scope:{type:"string",description:"Restrict to one directory (repo-relative)"},globs:{type:"array",items:{type:"string"},description:"Restrict to matching paths"},ignoreCase:{type:"boolean"},maxHits:{type:"number",minimum:1}},required:["repo","pattern"]}},{name:"search",description:'Natural-language-ish lexical search: BM25F ranking over SIX weighted fields \u2014 symbol names (camelCase/snake_case subtokens), path segments, markdown headings, the file summary, per-symbol DOC COMMENTS, and the prose body (comment + short-literal words). The last two are why "where is rate limiting handled" works: the phrase lives in a comment, not in a name. Results carry `matchedFields`, a `line` anchor and `symbolHits` (name/kind/line). NOT embeddings by default \u2014 deterministic, diacritic-folded, zero API keys. Answers "where is auth handled?"-style queries with ranked files, matched terms and top symbols. Query terms with zero document frequency get a deterministic trigram-fuzzy fallback (typo-tolerant) unless `fuzzy: false`. Set `semantic: true` to RRF-fuse an embedding tier (HTTP endpoint, else a local static model) with lexical \u2014 the response then wraps the ranked list as `{ results, tier, degradedReason? }`, `tier` being "endpoint"/"static" when fusion happened or "lexical" (with `degradedReason`) when it did not (see embed_status). Without `semantic`, the response is the bare ranked array, unchanged.',inputSchema:{type:"object",properties:{...ee,...fn,query:{type:"string",description:"Natural-language or identifier query"},limit:{type:"number",minimum:0,description:"Max results (default 20)"},fuzzy:{type:"boolean",description:'Fallback for query terms with zero document frequency: a morphological stem match first ("caching" finds "cache"), then trigram similarity for typos (default true)'},rank:{type:"string",description:`Structural prior: "graph" multiplies the lexical score by the file's PageRank over the resolved import graph; "lexical" (default) scores on text alone. Unproven on the judged corpus \u2014 see SearchOptions.rank.`},exact:{type:"boolean",description:"Drop results that carry no verbatim query-term match \u2014 the ones the stem/trigram bridge produced (default false)."},explain:{type:"boolean",description:"Wrap the response as `{ results, explain }` with the query verdict (default false = bare array). See explain_search."},semantic:{type:"boolean",description:'RRF-fuse an embedding tier with lexical (default false). Precedence: the HTTP endpoint (CODEINDEX_EMBED_ENDPOINT) if set, else a local static model. The response reports the effective tier as a top-level `tier` field ("endpoint"/"static" on success, "lexical" plus `degradedReason` when neither is available/reachable) instead of degrading silently \u2014 see embed_status.'}},required:["repo","query"]}},{name:"explain_search",description:'Search, and say whether the query actually found anything. Returns `{ results, explain }` where explain.verdict is "match" (a verbatim term matched), "weak" (results exist but rest on a near match, or the identifier you asked for has document frequency 0) or "none". Use this instead of `search` whenever an empty-feeling or surprising result matters: a query for an identifier that is NOT in the indexed tree still returns confident-looking rows built from its subtokens \u2014 searching "nullGipStep7" in a repo that only has "nullGipStep2" ranks files matching "null" and "gip" \u2014 and only the verdict distinguishes that from a real hit. Also names the terms dropped as stopwords, the terms that exist nowhere, and what each near match bridged to.',inputSchema:{type:"object",properties:{...ee,...fn,query:{type:"string",description:"Natural-language or identifier query"},limit:{type:"number",minimum:0,description:"Max results (default 20)"},fuzzy:{type:"boolean",description:"Stem/trigram fallback for zero-document-frequency terms (default true)"},exact:{type:"boolean",description:"Drop results carrying no verbatim term match (default false)"}},required:["repo","query"]}},{name:"embed_status",description:"Report the embedding tier: the effective mode (none/static/endpoint; endpoint > static model), the resolved model (opt-in, never shipped in the package) with its modelId/dim, EMBED_VERSION, and the configured HTTP endpoint with its reachability. Use to check whether `search` with semantic:true will fuse embeddings or degrade to lexical.",inputSchema:{type:"object",properties:{...ee},required:["repo"]}},{name:"type_hierarchy",description:"How do types relate? For one type: the base classes it extends, the interfaces/traits it implements, and \u2014 the reverse direction, which no other tool answers \u2014 what extends or implements IT, plus any declared supertype with no definition in this repo. Omit `name` for the whole hierarchy.",inputSchema:{type:"object",properties:{...ee,name:{type:"string",description:"Type name to look up"}},required:["repo"]}},{name:"implementations",description:"Who implements this interface (or extends this class)? Walks the hierarchy TRANSITIVELY, so a class implementing a sub-interface of the one asked about is included. The tool to reach for before changing an interface.",inputSchema:{type:"object",properties:{...ee,name:{type:"string",description:"Interface/trait/class name"}},required:["repo","name"]}},{name:"call_graph",description:"What does this symbol reach, and what reaches it? A bounded symbol-to-symbol neighborhood around `symbol` \u2014 `depth` hops (default 2) following `calls`/`extends`/`implements` edges, `direction` out (callees) | in (callers) | both. Answers impact questions the one-hop `callers` tool cannot.",inputSchema:{type:"object",properties:{...ee,symbol:{type:"string",description:"Symbol name to centre on"},depth:{type:"number",minimum:1,maximum:5,description:"Hops to follow (default 2, max 5)"},direction:{type:"string",description:"out | in | both (default both)"}},required:["repo","symbol"]}},{name:"check_rules",description:'Validate dependency-cruiser-style architecture rules against the link-graph. Rules (inline JSON array): forbidden edges {name, from, to, kind?, severity?, comment?} with glob paths, plus builtins {name, builtin: "cycles"|"orphans"} (module-level import cycles; edge-less code files). Returns deterministic violations with severity error|warn \u2014 a CI gate.',inputSchema:{type:"object",properties:{...ee,...fn,rules:{type:"array",description:"Rules array (inline JSON \u2014 see description)"},configPath:{type:"string",description:"Read the rules from this JSON file instead (repo-relative or absolute) \u2014 the CLI's --config. Ignored when `rules` is given."}},required:["repo"]}}],On={type:"array",items:{type:"string"}},ye={type:"object"},mn={call_graph:{type:"object",properties:{root:{type:"array",items:ye},nodes:{type:"array",items:ye},edges:{type:"array",items:ye},truncated:{type:"boolean"}},required:["root","nodes","edges"]},scan_summary:{type:"object",properties:{engineVersion:{type:"string"},commit:{type:"string"},fileCount:{type:"integer"},languages:{type:"object",additionalProperties:{type:"integer"}},capped:{type:"boolean"}},required:["engineVersion","fileCount","languages","capped"]},graph:{type:"object",properties:{schemaVersion:{type:"integer"},version:{type:"string"},commit:{type:"string"},fileCount:{type:"integer"},languages:{type:"object",additionalProperties:{type:"integer"}},files:{type:"array",items:ye},modules:{type:"array",items:ye},fileEdges:{type:"array",items:ye},moduleEdges:{type:"array",items:ye}},required:["schemaVersion","files","fileEdges","modules","moduleEdges"]},symbols:{oneOf:[{type:"object",properties:{schemaVersion:{type:"integer"},defs:ye,refs:ye},required:["schemaVersion","defs"]},{type:"object",properties:{name:{type:"string"},defs:{type:"array",items:ye},refs:On},required:["name","defs","refs"]}]},callers:{oneOf:[{type:"object",additionalProperties:ye},{type:"object",properties:{error:{type:"string"}},required:["error"]}]},workspaces:{type:"object",properties:{packages:{type:"array",items:ye},cycle:{type:["array","null"],items:{type:"string"}},topoOrder:On},required:["packages","topoOrder"]},churn:{type:"object",properties:{ok:{type:"boolean"},churn:{type:"object",additionalProperties:{type:"integer"}}},required:["ok","churn"]},find_references:{type:"object",properties:{defs:{type:"array",items:ye},callSites:{type:"array",items:ye},referencingFiles:On},required:["defs","callSites","referencingFiles"]},lsp_status:{type:"object",properties:{lspVersion:{type:"number"},mode:{type:"string",enum:["none","configured"]},configPath:{type:["string","null"]},source:{type:"string",enum:["env","repo","cwd","none"]},servers:{type:"array",items:ye},unmappedLanguages:On},required:["lspVersion","mode","source","servers","unmappedLanguages"]},onboard:{type:"object",properties:{brief:{type:"string"},memory:{type:"string"}},required:["brief"]},explain_search:{type:"object",properties:{results:{type:"array",items:ye},explain:{type:"object",properties:{query:{type:"string"},terms:{type:"array",items:ye},droppedStopwords:On,unresolvedTerms:On,wholeIdentifier:ye,verdict:{type:"string",enum:["match","weak","none"]},note:{type:"string"},bridgedOnlyResults:{type:"number"},resultCount:{type:"number"}},required:["query","terms","droppedStopwords","unresolvedTerms","verdict","bridgedOnlyResults","resultCount"]}},required:["results","explain"]},hotspots:{type:"object",properties:{churnOk:{type:"boolean"},hotspots:{type:"array",items:ye}},required:["churnOk","hotspots"]},coupling:{type:"object",properties:{ok:{type:"boolean"},couplings:{type:"array",items:ye}},required:["ok","couplings"]},duplicated_literals:{type:"object",properties:{duplications:{type:"array",items:ye},families:{type:"array",items:ye}},required:["duplications","families"]},embed_status:{type:"object",properties:{embedVersion:{type:"integer"},mode:{type:"string",enum:["none","static","endpoint"]},model:{},endpoint:{},endpointReachable:{type:"boolean"}},required:["embedVersion","mode"]},write_memory:{type:"object",properties:{written:{type:"string"}},required:["written"]},delete_memory:{type:"object",properties:{deleted:{type:"boolean"}},required:["deleted"]}};for(let e of["replace_symbol_body","insert_after_symbol","insert_before_symbol"])mn[e]={type:"object",properties:{file:{type:"string"},symbol:{type:"string"},startLine:{type:"integer"},endLine:{type:"integer"}},required:["file"]};Gr={scan_summary:{title:"Scan summary"},graph:{title:"Link graph"},symbols:{title:"Symbol index"},callers:{title:"Caller index"},workspaces:{title:"Monorepo workspaces"},churn:{title:"Git churn"},symbols_overview:{title:"File symbol overview"},find_symbol:{title:"Find symbol"},find_references:{title:"Find references"},repo_map:{title:"Repository map"},onboard:{title:"Project brief",write:!0,destructive:!1,idempotent:!0},hotspots:{title:"Hotspots"},coupling:{title:"Change coupling"},replace_symbol_body:{title:"Replace symbol body",write:!0,destructive:!0,idempotent:!0},insert_after_symbol:{title:"Insert after symbol",write:!0,destructive:!1,idempotent:!1},insert_before_symbol:{title:"Insert before symbol",write:!0,destructive:!1,idempotent:!1},write_memory:{title:"Write memory",write:!0,destructive:!1,idempotent:!0},read_memory:{title:"Read memory"},list_memories:{title:"List memories"},delete_memory:{title:"Delete memory",write:!0,destructive:!0,idempotent:!0},dead_code:{title:"Dead-code candidates"},duplicated_literals:{title:"Values with no single source of truth"},complexity:{title:"Complexity"},mermaid:{title:"Mermaid module diagram"},grep:{title:"Grep file contents"},search:{title:"Lexical search",openWorld:!0},explain_search:{title:"Search with a verdict",openWorld:!0},lsp_status:{title:"LSP tier status",openWorld:!0},embed_status:{title:"Embedding tier status",openWorld:!0},type_hierarchy:{title:"Type hierarchy"},implementations:{title:"Implementations"},call_graph:{title:"Call graph neighborhood"},check_rules:{title:"Check architecture rules"}};Ci={orient:["scan_summary","repo_map","onboard","workspaces","mermaid","read_memory","list_memories"],find:["search","explain_search","grep","find_symbol","symbols","symbols_overview"],impact:["find_references","callers","call_graph","dead_code","type_hierarchy","implementations","lsp_status"],edit:["find_symbol","symbols_overview","replace_symbol_body","insert_after_symbol","insert_before_symbol"],risk:["hotspots","churn","coupling","complexity","check_rules","duplicated_literals","dead_code"]}});function Ja(e){return Ce(e.files.map(t=>`${t.rel}:${t.hash}`).join(` +`))}async function Kr(e,t){let n=`${e.mode}:${e.identity}:${Ja(e.scan)}`;if(Ti&&Ti.key===n)return Ti.index;let r=await t();return Ti={key:n,index:r},r}function Xr(e){let t;try{t=ve(I(e,"model.json"))}catch{return}let n=`${e}:${t.mtimeMs}:${t.size}`;if(Ii&&Ii.key===n)return Ii.model;let r=Wt(e);return r&&(Ii={key:n,model:r}),r}function Hu(e){let t=Je.findIndex(r=>r.key===e);if(t<0)return;let[n]=Je.splice(t,1);return Je.unshift(n),n}function zt(e){let t=Je.findIndex(n=>n.key===e.key);return t>=0&&Je.splice(t,1),Je.unshift(e),Je.length=Math.min(Je.length,Yy),e}function Gu(){Je.length=0}function Ka(e,t){let n=e+"\0";for(let r of Je)r.key.startsWith(n)&&(t?r.cacheMap.delete(t):r.cacheMap.clear())}function qu(e,t){return e+"\0"+JSON.stringify({scope:t.scope,include:t.include,exclude:t.exclude,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs,maxBytes:t.maxBytes,maxFiles:t.maxFiles,maxCallsPerFile:t.maxCallsPerFile,out:t.out,fullHash:t.fullHash})}function Zr(e,t={},n){let r=qu(e,t),s=Hu(r);if(s){let l=Le(e,{...t,cache:s.cacheMap,precomputedWalk:n});return l.contentUnchanged?(l.cacheDirty&&(s.cacheMap=je(l)),s.scan.commit!==l.commit&&(s.scan.commit=l.commit,s.arts=void 0,s.loadArtifacts=void 0),s.scan):(zt({key:r,scan:l,cacheMap:je(l)}),l)}let o=jo(e,{...t,precomputedWalk:n});if(o)return zt({key:r,scan:o.scan,cacheMap:o.cacheMap,arts:o.arts}),o.scan;let a=Le(e,{...t,precomputedWalk:n});return zt({key:r,scan:a,cacheMap:je(a)}),a}async function Ni(e,t={},n,r=async()=>{}){let s=qu(e,t),o=Je.find(c=>c.key===s);if(o){let c=o.cacheMap,d=m=>(m.cacheDirty&&(o.cacheMap=je(m)),o.scan.commit!==m.commit&&(o.scan.commit=m.commit,o.arts=void 0,o.loadArtifacts=void 0),Hu(s),o.scan);if(n&&$o(n,c,t.fullHash)){await r();let m=await ut(e,{...t,cache:c,precomputedWalk:n});return m.contentUnchanged?d(m):(zt({key:s,scan:m,cacheMap:je(m)}),m)}let f=Le(e,{...t,cache:c,precomputedWalk:n});if(f.contentUnchanged)return d(f);if(n)return zt({key:s,scan:f,cacheMap:je(f)}),f;await r();let u=await ut(e,{...t,cache:c,precomputedWalk:n});return zt({key:s,scan:u,cacheMap:je(u)}),u}let a=await Ps(e,{...t,precomputedWalk:n},r);if(a)return zt({key:s,scan:a.scan,cacheMap:a.cacheMap,arts:a.arts,loadArtifacts:a.loadArtifacts}),a.scan;await r();let l=await ut(e,{...t,precomputedWalk:n});return zt({key:s,scan:l,cacheMap:je(l)}),l}function Fi(e,t={},n){return sr(e,{...t,precomputedWalk:n})}function Oi(e,t={},n,r){let s=r??Zr(e,t,n),o=Je.find(a=>a.scan===s);return o?o.arts??=o.loadArtifacts?.()??vt(s,t):vt(s,t)}async function Vu(e){await Yr(Pe(e,{}))}async function Yr(e){await et(wt(e.files.map(t=>t.ext)))}var Ti,Ii,Yy,Je,Xa=O(()=>{"use strict";E();xe();ae();oi();Pt();ir();or();Ne();nt();on();Fn();Tt();Yy=4,Je=[]});var Xu={};$i(Xu,{DEFAULT_MAX_RESPONSE_BYTES:()=>Ei,OUTPUT_SCHEMAS:()=>mn,PROTOCOL_VERSIONS:()=>Ct,TOOLS:()=>Hr,TOOL_META:()=>Gr,TOOL_PROFILES:()=>Ci,annotationsFor:()=>Va,capResponse:()=>vi,getArtifacts:()=>Oi,getScan:()=>Zr,getScanParallel:()=>Ni,getScanSummary:()=>Fi,memoizedEmbedModel:()=>Xr,memoizedEmbeddingIndex:()=>Kr,negotiateProtocol:()=>ki,profileNames:()=>qr,resourceLinkFor:()=>Ri,runMcpServer:()=>Ku,scanFingerprint:()=>Ja,structuredContentFor:()=>Si,toCacheMap:()=>je,toolsFor:()=>Jr,toolsInProfiles:()=>Vr,validateArgs:()=>xi,warmGrammarsForRepo:()=>Vu,warmGrammarsForWalk:()=>Yr});function Qy(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.jsonrpc!=="2.0"||typeof t.method!="string"?!1:t.id===void 0||t.id===null||typeof t.id=="number"||typeof t.id=="string"}function eb(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method!="string"&&("result"in t||"error"in t)}function ie(e){return typeof e=="string"&&e?e:void 0}function Za(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")&&e.length?e:void 0}function Qr(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return Number.isFinite(t)&&t>=0?t:void 0}function Ke(e){let t=Qr(e);return t!==void 0&&t>0?t:void 0}function Ju(e){return e instanceof Error?e.message:String(e)}async function nb(e,t,n){let r=ie(t.repo)??n;if(!r)throw new Error("`repo` is required (absolute path to the repository root)");try{if(!ve(r).isDirectory())throw new Error("not a directory")}catch{throw new Error(`repository root is not a readable directory: ${r}`)}let s={scope:ie(t.scope),include:Za(t.include),exclude:Za(t.exclude)},o=ie(t.rank),a=o==="graph"||o==="lexical"?{rank:o}:{},l,c;tb.has(e)||(l=Pe(r,{}),c=await Ni(r,s,l,()=>l?Yr(l):Promise.resolve()));let d=()=>c??Zr(r,s,l),f=()=>Oi(r,s,l,c);if(e==="scan_summary"){let u=Fi(r,s,l);return JSON.stringify({engineVersion:fe,commit:u.commit,fileCount:u.fileCount,languages:u.languages,capped:u.capped},null,2)}if(e==="graph")return In(f().graph);if(e==="symbols"){let{symbols:u}=f(),m=ie(t.name);return JSON.stringify(m?{name:m,defs:u.defs[m]??[],refs:u.refs[m]??[]}:u,null,2)}if(e==="callers"){let u=d(),m=t.recall===!0?Yt(u,void 0,{recall:!0}):Cn(u),p=ie(t.name);if(p){let y=m.get(p);return JSON.stringify(y??{error:`no tracked callers for "${p}"`},null,2)}let g={};for(let[y,h]of m)g[y]=h;return JSON.stringify(g,null,2)}if(e==="workspaces"){let u=rn(r);return JSON.stringify({packages:u.packages,cycle:u.cycle??null,topoOrder:u.topoOrder},null,2)}if(e==="churn"){let{churn:u,ok:m}=Ze(r,{since:ie(t.since)}),p={};for(let g of[...u.keys()].sort())p[g]=u.get(g);return JSON.stringify({ok:m,churn:p},null,2)}if(e==="symbols_overview"){let u=ie(t.file);if(!u)throw new Error("`file` is required");return JSON.stringify(aa(d(),u),null,2)}if(e==="find_symbol"){let u=ie(t.namePath);if(!u)throw new Error("`namePath` is required");let m=An(d(),u,{substring:t.substring===!0,includeBody:t.includeBody===!0,concise:t.concise===!0,maxResults:Ke(t.maxResults)});return JSON.stringify(m,null,2)}if(e==="find_references"){let u=ie(t.name);if(!u)throw new Error("`name` is required");let m=d(),p=la(m,u);return t.lsp===!0?JSON.stringify(await ja(m,r,u,p),null,2):JSON.stringify(p,null,2)}if(e==="lsp_status")return JSON.stringify(await Dr(d(),r,t.probe===!0),null,2);if(e==="replace_symbol_body"||e==="insert_after_symbol"||e==="insert_before_symbol"){let u=ie(t.namePath),m=typeof t.body=="string"?t.body:void 0;if(!u||m===void 0)throw new Error("`namePath` and `body` are required");let p=d(),y=(e==="replace_symbol_body"?ca:e==="insert_after_symbol"?da:ua)(p,u,m,ie(t.file));return Gu(),JSON.stringify(y,null,2)}if(e==="write_memory"){let u=ie(t.name),m=typeof t.content=="string"?t.content:void 0;if(!u||m===void 0)throw new Error("`name` and `content` are required");return JSON.stringify({written:xr(r,u,m)},null,2)}if(e==="read_memory"){let u=ie(t.name);if(!u)throw new Error("`name` is required");let m=pa(r,u);if(m===void 0)throw new Error(`no memory named "${u}" \u2014 see list_memories`);return m}if(e==="list_memories")return JSON.stringify(_a(r),null,2);if(e==="delete_memory"){let u=ie(t.name);if(!u)throw new Error("`name` is required");return JSON.stringify({deleted:ga(r,u)},null,2)}if(e==="dead_code"){let u=Wr(d()),m=Qr(t.limit);return m===void 0||u.length<=m?JSON.stringify(u,null,2):JSON.stringify({total:u.length,shown:m,truncated:!0,candidates:u.slice(0,m)},null,2)}if(e==="duplicated_literals"){let u=sn(d(),{minFiles:Ke(t.minFiles),minCount:Ke(t.minCount),includeTests:t.includeTests===!0}),m=Qr(t.limit);return m===void 0||u.duplications.length<=m?JSON.stringify(u,null,2):JSON.stringify({total:u.duplications.length,shown:m,truncated:!0,duplications:u.duplications.slice(0,m),families:u.families},null,2)}if(e==="complexity"){let u=d();if(t.risk===!0){let{churn:m,ok:p}=Ze(r,{since:ie(t.since)});return JSON.stringify({churnOk:p,risks:br(u,m,Ke(t.top))},null,2)}return JSON.stringify(yr(u,ie(t.file),Ke(t.top)),null,2)}if(e==="mermaid"){let{graph:u}=f();return Ur(u,{module:ie(t.module),maxEdges:Ke(t.maxEdges)})}if(e==="onboard"){let u=d(),{graph:m}=f();return JSON.stringify(Ma(u,m,{...Ke(t.budgetTokens)!==void 0?{budgetTokens:Ke(t.budgetTokens)}:{},...t.remember===!1?{remember:!1}:{}}),null,2)}if(e==="repo_map"){let{scan:u,graph:m}=f();return cn(u,m,{budgetTokens:Ke(t.budgetTokens)})}if(e==="hotspots"){let u=d(),{churn:m,ok:p}=Ze(r,{since:ie(t.since)});return JSON.stringify({churnOk:p,hotspots:dn(u,m)},null,2)}if(e==="coupling"){let{ok:u,couplings:m}=Pr(r,{since:ie(t.since)});return JSON.stringify({ok:u,couplings:m},null,2)}if(e==="grep"){let u=ie(t.pattern);if(!u)throw new Error("`pattern` is required");let m=ie(t.scope),p=Za(t.globs),g=Rr(r,u,{globs:m?[...p??[],`${m.replace(/\/+$/,"")}/**`]:p,ignoreCase:t.ignoreCase===!0,maxHits:Ke(t.maxHits)});return JSON.stringify(g,null,2)}if(e==="search"){let u=ie(t.query);if(!u)throw new Error("`query` is required");let m=d(),p=Qr(t.limit),g=typeof t.fuzzy=="boolean"?t.fuzzy:void 0,y=t.exact===!0?{exact:!0}:{};if(t.semantic===!0){let _=Ut();if(_)try{let v=await Kr({mode:"endpoint",identity:_,scan:m},()=>Fr(m)),A=await Nr(u),F=ln(m,u,v,{queryVec:A,limit:p,fuzzy:g});return JSON.stringify({results:F,tier:"endpoint"},null,2)}catch(v){let A=Dt(m,u,{limit:p,fuzzy:g,...a});return JSON.stringify({results:A,tier:"lexical",degradedReason:`embedding endpoint failed: ${Ju(v)}`},null,2)}let k=Rt(r),b=k?Xr(k):void 0;if(b){let v=await Kr({mode:"static",identity:`${k}#${b.modelId}`,scan:m},()=>an(m,b)),A=ln(m,u,v,{model:b,limit:p,fuzzy:g});return JSON.stringify({results:A,tier:"static"},null,2)}let w=Dt(m,u,{limit:p,fuzzy:g,...a});return JSON.stringify({results:w,tier:"lexical",degradedReason:"no embedding endpoint or static model configured \u2014 see embed_status"},null,2)}let{results:h,explain:S}=nn(m,u,{limit:p,fuzzy:g,...y,...a});return JSON.stringify(t.explain===!0?{results:h,explain:S}:h,null,2)}if(e==="explain_search"){let u=ie(t.query);if(!u)throw new Error("`query` is required");let m=d(),p=Qr(t.limit),g=typeof t.fuzzy=="boolean"?t.fuzzy:void 0,{results:y,explain:h}=nn(m,u,{limit:p,fuzzy:g,...t.exact===!0?{exact:!0}:{},...a});return JSON.stringify({results:y,explain:h},null,2)}if(e==="embed_status"){let u=Rt(r),m=u?Xr(u):void 0,p=Ut(),y={embedVersion:it,mode:p?"endpoint":m?"static":"none",model:m?{present:!0,dir:u,modelId:m.modelId,dim:m.dim,vocabSize:m.vocabSize}:{present:!1},endpoint:p??null};return p&&(y.endpointReachable=await Ir(p)),JSON.stringify(y,null,2)}if(e==="type_hierarchy"){let u=na(d()),m=ie(t.name);if(!m){let g={};for(let[y,h]of u)g[y]=h;return JSON.stringify(g,null,2)}let p=u.get(m);return JSON.stringify(p||{error:`no type named ${m}`},null,2)}if(e==="implementations"){let u=ie(t.name);if(!u)throw new Error("`name` is required");let m=na(d());return m.has(u)?JSON.stringify({name:u,implementations:dr(m,u)},null,2):JSON.stringify({error:`no type named ${u}`},null,2)}if(e==="call_graph"){let u=ie(t.symbol);if(!u)throw new Error("`symbol` is required");let m=ie(t.direction),p=m==="out"||m==="in"?m:"both",g=pr(Dd(d()),u,{...Ke(t.depth)!==void 0?{depth:Ke(t.depth)}:{},direction:p});return g.root.length?JSON.stringify(g,null,2):JSON.stringify({error:`no symbol named ${u}`},null,2)}if(e==="check_rules"){let u=ie(t.configPath),m=t.rules;if(m===void 0&&u){let y=ts(u)?u:I(r,u);try{m=JSON.parse(Q(y,"utf8"))}catch(h){throw new Error(`cannot read rules from ${y}: ${Ju(h)}`)}}if(m===void 0)throw new Error("`rules` (or `configPath`) is required");let p=Lr(m),{graph:g}=f();return JSON.stringify(jr(g,p),null,2)}throw new Error(`unknown tool: ${e}`)}async function Ku(e={}){let t={name:e.serverInfo?.name??"codeindex",version:e.serverInfo?.version??fe},n=Ct[0],r=Jr(e.defaultRepo,n,e.profile),s;if(e.watch&&e.defaultRepo)try{s=ml(e.defaultRepo,{recursive:!0},(c,d)=>{let f=d?.toString().replaceAll("\\","/")??"";f.split("/").some(m=>Gt.has(m)||m.startsWith(".codeindex-edit-"))||Ka(e.defaultRepo,f||void 0)}),s.on("error",c=>{R.stderr.write(`codeindex: MCP watcher disabled (${c.message}); using freshness scans +`),s?.close(),s=void 0,Ka(e.defaultRepo)})}catch(c){R.stderr.write(`codeindex: MCP watcher unavailable (${c instanceof Error?c.message:String(c)}); using freshness scans `)}let o=c=>{let d=Array.isArray(c)?c.map(f=>({jsonrpc:"2.0",...f})):{jsonrpc:"2.0",...c};R.stdout.write(JSON.stringify(d)+` -`)},a=Mu({input:R.stdin,terminal:!1});try{for await(let c of a){let d=c.trim();if(!d)continue;let f;try{f=JSON.parse(d)}catch{o({id:null,error:{code:-32700,message:"parse error"}});continue}if(Array.isArray(f)&&f.length===0){o({id:null,error:{code:-32600,message:"invalid request"}});continue}let u=async m=>{if(!Cy(m))return My(m)?l(m):{id:null,error:{code:-32600,message:"invalid request"}}};if(Array.isArray(f)){let m=[];for(let p of f){let g=await u(p);g&&m.push(g)}m.length>0&&o(m)}else{let m=await u(f);m&&o(m)}}}finally{s?.close()}async function l(c){let d=!("id"in c),f=u=>d?void 0:{id:c.id??null,...u};try{if(c.method==="initialize")return n=wi(c.params?.protocolVersion),r=Gr(e.defaultRepo,n,e.profile),f({result:{protocolVersion:n,capabilities:{tools:{}},serverInfo:t}});if(c.method==="ping")return f({result:{}});if(c.method==="tools/list")return f({result:{tools:r}});if(c.method==="tools/call"){let u=c.params??{},m=se(u.name)??"",p=u.arguments??{};try{let g=r.find(v=>v.name===m),y=g?yi(g.inputSchema,p):void 0;if(y)throw new Error(y);let h=await Ty(m,p,e.defaultRepo),S=se(p.repo)??e.defaultRepo??"",_=Si(h,m,S,e.maxResponseBytes??xi),E=_!==h,b=E&&n>=Ur?ki(_,m):void 0,x=n>=Ur?bi(_,E,fn[m]!==void 0):void 0;return f({result:{content:b?[{type:"text",text:_},b]:[{type:"text",text:_}],...x?{structuredContent:x}:{}}})}catch(g){return f({result:{content:[{type:"text",text:g instanceof Error?g.message:String(g)}],isError:!0}})}}else return f({error:{code:-32601,message:`method not found: ${c.method}`}})}catch(u){return f({error:{code:-32603,message:u instanceof Error?u.message:String(u)}})}}}var Ay,Ja=F(()=>{"use strict";k();xe();oe();Cu();Xe();ei();Yt();mt();Xt();mr();Sr();Gt();si();Fr();Nr();_i();kr();yr();hi();Ks();pi();Ea();la();Zs();Mn();gi();sn();On();ai();li();Ae();Ri();Ei();Ga();Ri();Ei();Ga();Ay=new Set(["workspaces","churn","coupling","grep","write_memory","read_memory","list_memories","delete_memory","embed_status","scan_summary"])});var ju={};Oi(ju,{rewriteCommand:()=>Du,shellQuote:()=>Ni,tokenize:()=>Lu});function Lu(e){let t=[],n="",r,s=!1;for(let o=0;o2&&/^-[a-zA-Z]+$/.test(o)){let a=o.slice(1).split("").map(l=>`-${l}`);t.splice(s,1,...a),s--}else return}}if(n.pattern===void 0){let s=r.shift();if(s===void 0||s==="")return;n.pattern=s}if(!(r.length>1))return n.path=r[0],n}function Du(e,t="codeindex"){let n=e.trim();if(!n||Iy.test(n))return;let r=Lu(n);if(!r||r.length<2)return;let[s,...o]=r;if(s===void 0||!Ny.has(s))return;let a=Oy(s,o);if(!a||a.pattern===void 0)return;let l=a.pattern;if(!a.recursive)return;let c=a.path,d=[t,"grep",Ni(l)];c&&c!=="."&&c!=="./"&&d.push("--scope",Ni(c.replace(/\/+$/,""))),a.ignoreCase&&d.push("--ignore-case");for(let f of a.includes)d.push("--include",Ni(f));return d.join(" ")}var Iy,Ny,Ka=F(()=>{"use strict";k();Iy=/[|&;<>`\n\r$(){}]/,Ny=new Set(["grep","egrep","rg","ripgrep"])});k();k();Xe();Ae();Ft();Ft();sr();Os();Hn();ji();_s();k();oe();var kp=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".svelte",".astro",".py",".rb",".go",".rs",".java",".kt",".kts",".php",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".scala",".clj",".ex",".exs",".dart",".lua",".sh",".bash",".zig",".elm",".hcl",".tf",".tfvars",".sol",".hh",".sc",".pyi",".rake",".cxx"]),Ep=new Set([".css",".scss",".sass",".less",".styl",".pcss"]),vp=new Set([".md",".mdx",".rst",".adoc",".txt"]),Rp=new Set([".json",".yaml",".yml",".toml",".csv",".xml",".env"]),Mp=new Set([".png",".jpg",".jpeg",".gif",".webp",".avif",".ico",".bmp",".tiff",".svg",".pdf",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".zip",".gz",".tar",".rar",".7z",".wasm",".so",".dylib",".dll",".exe",".bin",".class",".jar",".pyc",".node"]),Cp=["locales","locale","i18n","lang","langs","translations","messages"],Ap=new Set([".json",".yaml",".yml",".po",".properties"]),Tp=["__tests__","test","tests","spec","e2e","__mocks__"],Ip=["migrations","entities","models"],Np=new Set(["package.json","tsconfig.json","dockerfile","makefile","pyproject.toml","cargo.toml","go.mod","requirements.txt","gemfile","composer.json","pubspec.yaml"]);function Op(e,t){let n=e.toLowerCase(),r=ke(n),s=n.split("/"),o=a=>a.some(l=>s.includes(l));return o(Cp)&&Ap.has(t)?"i18n":t===".prisma"||t===".sql"||t===".graphql"||t===".gql"||r.startsWith("schema.")||r==="models.py"||o(Ip)?"schema":n.includes(".test.")||n.includes(".spec.")||o(Tp)?"test":Np.has(r)||r.endsWith(".config.js")||r.endsWith(".config.ts")||r.endsWith(".config.mjs")||r.startsWith(".eslintrc")||r.startsWith(".prettierrc")||r.startsWith(".env")||r.startsWith("docker-compose")?"config":vp.has(t)?"doc":Ep.has(t)?"style":kp.has(t)?"code":Mp.has(t)?"asset":Rp.has(t)?"data":"other"}yn();Ao();eo();nt();vo();k();xe();oe();po();nt();Y();var Xc=new Map;function Zc(e,t){let n=Xc.get(e);if(n!==void 0)return n;let r=null;for(let s of Qe().dirs){let o=I(s,`${e}.tags.scm`);if(H(o)){try{r=new Ec(t,te(o,"utf8"))}catch{r=null}break}}return Xc.set(e,r),r}function Fp(e){if(!Qe().dirs.some(r=>H(I(r,`${e}.tags.scm`))))return{present:!1,compiled:!1};let n=_o(e);return n?{present:!0,compiled:Zc(e,n)!==null}:{present:!0,compiled:!1}}function Pp(e,t){let n=Yn(e);if(!n)return[];let r=_o(n),s=vs(n);if(!r||!s)return[];let o=Zc(n,r);if(!o)return[];let a=null;try{if(a=s.parse(t),!a)return[];let l=[],c=new Set;for(let d of o.matches(a.rootNode)){let f,u,m=0;for(let g of d.captures)g.name==="name"?(f=g.node.text,m=g.node.startPosition.row+1):g.name.startsWith("definition.")&&(u=g.name.slice(11));if(!f||!u)continue;let p=`${u} ${f} ${m}`;c.has(p)||(c.add(p),l.push({kind:u,name:f,line:m}))}return l.sort((d,f)=>d.line-f.line||M(d.name,f.name)||M(d.kind,f.kind))}catch{return[]}finally{a?.delete()}}nt();nt();k();cs();xe();oe();k();function Yc(){throw new Error("zlib.gunzipSync is not available in the browser build (use DecompressionStream at an async boundary)")}Xe();var Lo=`https://github.com/maxgfr/codeindex/releases/download/v${fe}/grammars-${fe}.tar.gz`;function Fs(){let e=R.env.CODEINDEX_GRAMMARS_URL;return e&&e.trim()?{url:e.trim()}:{url:Lo,sha256Url:`${Lo}.sha256`}}async function Qc(e,t){let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status} from ${e}`);let r=T.from(await n.arrayBuffer());if(t){let s=hn("sha256").update(r).digest("hex");if(s!==t)throw new Error(`sha256 mismatch: expected ${t}, got ${s}`)}return r}function ed(e){return T.isBuffer(e)?e:T.from(e.buffer,e.byteOffset,e.byteLength)}async function td(e){let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status} from ${e}`);let r=((await t.text()).trim().split(/\s+/)[0]??"").toLowerCase();if(!/^[0-9a-f]{64}$/.test(r))throw new Error(`invalid sha256 sidecar at ${e}`);return r}function $o(e,t,n){let r=e.subarray(t,t+n),s=r.indexOf(0);return r.toString("utf8",0,s===-1?r.length:s)}function*$p(e){let t=0;for(;t+512<=e.length;){let n=e.subarray(t,t+512),r=!0;for(let f=0;f<512;f++)if(n[f]!==0){r=!1;break}if(r)break;let s=$o(n,0,100),o=$o(n,345,155),a=$o(n,124,12).trim(),l=a?parseInt(a,8):0,c=String.fromCharCode(n[156]??0);t+=512;let d=e.subarray(t,t+l);t+=Math.ceil(l/512)*512,yield{name:o?`${o}/${s}`:s,type:c,data:d}}}function Lp(e){if(!e||e.includes("\0")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:/.test(e))return null;let t=[];for(let n of e.split(/[/\\]/))if(!(n===""||n===".")){if(n==="..")return null;t.push(n)}return t.length?t.join("/"):null}function nd(e,t){let n=Ne(t),r=[];for(let s of $p(ed(e))){if(s.type!=="0"&&s.type!=="\0")continue;let o=Lp(s.name);if(o===null)throw new Error(`refusing unsafe tar entry: ${s.name}`);let a=Ne(t,o);if(a!==n&&!a.startsWith(n+"/"))throw new Error(`tar entry escapes destination: ${s.name}`);gt(_e(a),{recursive:!0}),Re(a,s.data),r.push(o)}return r}function rd(e,t){let n=ed(e),r=n.length>=2&&n[0]===31&&n[1]===139?Yc(n):n;return nd(r,t)}function Dp(e,t,n,r,s=Dn,o=qe){let a=_e(t),l=Ln(I(a,".grammars-swap-")),c=I(l,"previous-cache"),d=I(l,"previous-marker"),f=I(l,"next-marker"),u=!1,m=!1,p=!1,g=!1;try{r&&Re(f,r+` -`),H(t)&&(s(t,c),u=!0),H(n)&&(s(n,d),m=!0),s(e,t),p=!0,r&&(s(f,n),g=!0)}catch(y){let h=[],S=_=>{try{_()}catch(E){h.push(E)}};if(g&&H(n)&&S(()=>qe(n,{force:!0})),p&&H(t)&&S(()=>qe(t,{recursive:!0,force:!0})),m&&H(d)&&S(()=>s(d,n)),u&&H(c)&&S(()=>s(c,t)),h.length===0)try{qe(l,{recursive:!0,force:!0})}catch{}if(h.length>0){let _=h[0];throw new Error(`${y instanceof Error?y.message:String(y)}; rollback failed: ${_ instanceof Error?_.message:String(_)} (backup preserved at ${l})`)}throw y}try{o(l,{recursive:!0,force:!0})}catch{}}async function ir(e,t={}){let n=t.onNote??(()=>{}),r=Fs(),s;if(r.sha256Url)try{s=await td(r.sha256Url)}catch(d){n(`codeindex: could not fetch checksum (${d instanceof Error?d.message:String(d)}) \u2014 proceeding unverified -`)}let o=I(e,"web-tree-sitter.wasm"),a=I(_e(e),`${fe}.sha256`);if(H(o)&&s&&H(a)){let d="";try{d=te(a,"utf8").trim()}catch{}if(d===s)return{ok:!0,status:"up-to-date",cacheDir:e,message:`codeindex: grammars already present at ${e} (up to date) +`)},a=Uu({input:R.stdin,terminal:!1});try{for await(let c of a){let d=c.trim();if(!d)continue;let f;try{f=JSON.parse(d)}catch{o({id:null,error:{code:-32700,message:"parse error"}});continue}if(Array.isArray(f)&&f.length===0){o({id:null,error:{code:-32600,message:"invalid request"}});continue}let u=async m=>{if(!eb(m))return Qy(m)?l(m):{id:null,error:{code:-32600,message:"invalid request"}}};if(Array.isArray(f)){let m=[];for(let p of f){let g=await u(p);g&&m.push(g)}m.length>0&&o(m)}else{let m=await u(f);m&&o(m)}}}finally{s?.close()}async function l(c){let d=!("id"in c),f=u=>d?void 0:{id:c.id??null,...u};try{if(c.method==="initialize")return n=ki(c.params?.protocolVersion),r=Jr(e.defaultRepo,n,e.profile),f({result:{protocolVersion:n,capabilities:{tools:{}},serverInfo:t}});if(c.method==="ping")return f({result:{}});if(c.method==="tools/list")return f({result:{tools:r}});if(c.method==="tools/call"){let u=c.params??{},m=ie(u.name)??"",p=u.arguments??{};try{let g=r.find(v=>v.name===m),y=g?xi(g.inputSchema,p):void 0;if(y)throw new Error(y);let h=await nb(m,p,e.defaultRepo),S=ie(p.repo)??e.defaultRepo??"",_=vi(h,m,S,e.maxResponseBytes??Ei),k=_!==h,b=k&&n>=zr?Ri(_,m):void 0,w=n>=zr?Si(_,k,mn[m]!==void 0):void 0;return f({result:{content:b?[{type:"text",text:_},b]:[{type:"text",text:_}],...w?{structuredContent:w}:{}}})}catch(g){return f({result:{content:[{type:"text",text:g instanceof Error?g.message:String(g)}],isError:!0}})}}else return f({error:{code:-32601,message:`method not found: ${c.method}`}})}catch(u){return f({error:{code:-32603,message:u instanceof Error?u.message:String(u)}})}}}var tb,Ya=O(()=>{"use strict";E();xe();ae();Bu();Xe();ri();Qt();pt();Xt();gr();Er();qt();ai();$r();Or();bi();vr();wr();wi();Ys();hi();Ca();fa();ei();Mn();yi();on();Fn();di();ui();Ne();Ai();Mi();Xa();Ai();Mi();Xa();tb=new Set(["workspaces","churn","coupling","grep","write_memory","read_memory","list_memories","delete_memory","embed_status","scan_summary"])});var Qu={};$i(Qu,{rewriteCommand:()=>Yu,shellQuote:()=>Pi,tokenize:()=>Zu});function Zu(e){let t=[],n="",r,s=!1;for(let o=0;o2&&/^-[a-zA-Z]+$/.test(o)){let a=o.slice(1).split("").map(l=>`-${l}`);t.splice(s,1,...a),s--}else return}}if(n.pattern===void 0){let s=r.shift();if(s===void 0||s==="")return;n.pattern=s}if(!(r.length>1))return n.path=r[0],n}function Yu(e,t="codeindex"){let n=e.trim();if(!n||rb.test(n))return;let r=Zu(n);if(!r||r.length<2)return;let[s,...o]=r;if(s===void 0||!sb.has(s))return;let a=ib(s,o);if(!a||a.pattern===void 0)return;let l=a.pattern;if(!a.recursive)return;let c=a.path,d=[t,"grep",Pi(l)];c&&c!=="."&&c!=="./"&&d.push("--scope",Pi(c.replace(/\/+$/,""))),a.ignoreCase&&d.push("--ignore-case");for(let f of a.includes)d.push("--include",Pi(f));return d.join(" ")}var rb,sb,Qa=O(()=>{"use strict";E();rb=/[|&;<>`\n\r$(){}]/,sb=new Set(["grep","egrep","rg","ripgrep"])});E();E();Xe();Ne();Pt();Pt();or();ir();Gn();Ui();bs();E();ae();var qp=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".svelte",".astro",".py",".rb",".go",".rs",".java",".kt",".kts",".php",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".scala",".clj",".ex",".exs",".dart",".lua",".sh",".bash",".zig",".elm",".hcl",".tf",".tfvars",".sol",".hh",".sc",".pyi",".rake",".cxx"]),Vp=new Set([".css",".scss",".sass",".less",".styl",".pcss"]),Jp=new Set([".md",".mdx",".rst",".adoc",".txt"]),Kp=new Set([".json",".yaml",".yml",".toml",".csv",".xml",".env"]),Xp=new Set([".png",".jpg",".jpeg",".gif",".webp",".avif",".ico",".bmp",".tiff",".svg",".pdf",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".zip",".gz",".tar",".rar",".7z",".wasm",".so",".dylib",".dll",".exe",".bin",".class",".jar",".pyc",".node"]),Zp=["locales","locale","i18n","lang","langs","translations","messages"],Yp=new Set([".json",".yaml",".yml",".po",".properties"]),Qp=["__tests__","test","tests","spec","e2e","__mocks__"],eg=["migrations","entities","models"],tg=new Set(["package.json","tsconfig.json","dockerfile","makefile","pyproject.toml","cargo.toml","go.mod","requirements.txt","gemfile","composer.json","pubspec.yaml"]);function ng(e,t){let n=e.toLowerCase(),r=Ee(n),s=n.split("/"),o=a=>a.some(l=>s.includes(l));return o(Zp)&&Yp.has(t)?"i18n":t===".prisma"||t===".sql"||t===".graphql"||t===".gql"||r.startsWith("schema.")||r==="models.py"||o(eg)?"schema":n.includes(".test.")||n.includes(".spec.")||o(Qp)?"test":tg.has(r)||r.endsWith(".config.js")||r.endsWith(".config.ts")||r.endsWith(".config.mjs")||r.startsWith(".eslintrc")||r.startsWith(".prettierrc")||r.startsWith(".env")||r.startsWith("docker-compose")?"config":Jp.has(t)?"doc":Vp.has(t)?"style":qp.has(t)?"code":Xp.has(t)?"asset":Kp.has(t)?"data":"other"}bn();Fo();ro();nt();Ao();E();xe();ae();ho();nt();Y();var od=new Map;function ad(e,t){let n=od.get(e);if(n!==void 0)return n;let r=null;for(let s of Qe().dirs){let o=I(s,`${e}.tags.scm`);if(H(o)){try{r=new Tc(t,Q(o,"utf8"))}catch{r=null}break}}return od.set(e,r),r}function rg(e){if(!Qe().dirs.some(r=>H(I(r,`${e}.tags.scm`))))return{present:!1,compiled:!1};let n=bo(e);return n?{present:!0,compiled:ad(e,n)!==null}:{present:!0,compiled:!1}}function sg(e,t){let n=Qn(e);if(!n)return[];let r=bo(n),s=Cs(n);if(!r||!s)return[];let o=ad(n,r);if(!o)return[];let a=null;try{if(a=s.parse(t),!a)return[];let l=[],c=new Set;for(let d of o.matches(a.rootNode)){let f,u,m=0;for(let g of d.captures)g.name==="name"?(f=g.node.text,m=g.node.startPosition.row+1):g.name.startsWith("definition.")&&(u=g.name.slice(11));if(!f||!u)continue;let p=`${u} ${f} ${m}`;c.has(p)||(c.add(p),l.push({kind:u,name:f,line:m}))}return l.sort((d,f)=>d.line-f.line||M(d.name,f.name)||M(d.kind,f.kind))}catch{return[]}finally{a?.delete()}}nt();nt();E();ms();xe();ae();E();function ld(){throw new Error("zlib.gunzipSync is not available in the browser build (use DecompressionStream at an async boundary)")}Xe();var Uo=`https://github.com/maxgfr/codeindex/releases/download/v${fe}/grammars-${fe}.tar.gz`;function $s(){let e=R.env.CODEINDEX_GRAMMARS_URL;return e&&e.trim()?{url:e.trim()}:{url:Uo,sha256Url:`${Uo}.sha256`}}async function cd(e,t){let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status} from ${e}`);let r=N.from(await n.arrayBuffer());if(t){let s=yn("sha256").update(r).digest("hex");if(s!==t)throw new Error(`sha256 mismatch: expected ${t}, got ${s}`)}return r}function dd(e){return N.isBuffer(e)?e:N.from(e.buffer,e.byteOffset,e.byteLength)}async function ud(e){let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status} from ${e}`);let r=((await t.text()).trim().split(/\s+/)[0]??"").toLowerCase();if(!/^[0-9a-f]{64}$/.test(r))throw new Error(`invalid sha256 sidecar at ${e}`);return r}function Wo(e,t,n){let r=e.subarray(t,t+n),s=r.indexOf(0);return r.toString("utf8",0,s===-1?r.length:s)}function*ig(e){let t=0;for(;t+512<=e.length;){let n=e.subarray(t,t+512),r=!0;for(let f=0;f<512;f++)if(n[f]!==0){r=!1;break}if(r)break;let s=Wo(n,0,100),o=Wo(n,345,155),a=Wo(n,124,12).trim(),l=a?parseInt(a,8):0,c=String.fromCharCode(n[156]??0);t+=512;let d=e.subarray(t,t+l);t+=Math.ceil(l/512)*512,yield{name:o?`${o}/${s}`:s,type:c,data:d}}}function og(e){if(!e||e.includes("\0")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:/.test(e))return null;let t=[];for(let n of e.split(/[/\\]/))if(!(n===""||n===".")){if(n==="..")return null;t.push(n)}return t.length?t.join("/"):null}function fd(e,t){let n=ke(t),r=[];for(let s of ig(dd(e))){if(s.type!=="0"&&s.type!=="\0")continue;let o=og(s.name);if(o===null)throw new Error(`refusing unsafe tar entry: ${s.name}`);let a=ke(t,o);if(a!==n&&!a.startsWith(n+"/"))throw new Error(`tar entry escapes destination: ${s.name}`);_t(_e(a),{recursive:!0}),Me(a,s.data),r.push(o)}return r}function md(e,t){let n=dd(e),r=n.length>=2&&n[0]===31&&n[1]===139?ld(n):n;return fd(r,t)}function ag(e,t,n,r,s=Ln,o=Ge){let a=_e(t),l=Dn(I(a,".grammars-swap-")),c=I(l,"previous-cache"),d=I(l,"previous-marker"),f=I(l,"next-marker"),u=!1,m=!1,p=!1,g=!1;try{r&&Me(f,r+` +`),H(t)&&(s(t,c),u=!0),H(n)&&(s(n,d),m=!0),s(e,t),p=!0,r&&(s(f,n),g=!0)}catch(y){let h=[],S=_=>{try{_()}catch(k){h.push(k)}};if(g&&H(n)&&S(()=>Ge(n,{force:!0})),p&&H(t)&&S(()=>Ge(t,{recursive:!0,force:!0})),m&&H(d)&&S(()=>s(d,n)),u&&H(c)&&S(()=>s(c,t)),h.length===0)try{Ge(l,{recursive:!0,force:!0})}catch{}if(h.length>0){let _=h[0];throw new Error(`${y instanceof Error?y.message:String(y)}; rollback failed: ${_ instanceof Error?_.message:String(_)} (backup preserved at ${l})`)}throw y}try{o(l,{recursive:!0,force:!0})}catch{}}async function ar(e,t={}){let n=t.onNote??(()=>{}),r=$s(),s;if(r.sha256Url)try{s=await ud(r.sha256Url)}catch(d){n(`codeindex: could not fetch checksum (${d instanceof Error?d.message:String(d)}) \u2014 proceeding unverified +`)}let o=I(e,"web-tree-sitter.wasm"),a=I(_e(e),`${fe}.sha256`);if(H(o)&&s&&H(a)){let d="";try{d=Q(a,"utf8").trim()}catch{}if(d===s)return{ok:!0,status:"up-to-date",cacheDir:e,message:`codeindex: grammars already present at ${e} (up to date) `}}n(`codeindex: fetching grammars from ${r.url} \u2192 ${e} -`);let l;try{l=await Qc(r.url,s)}catch(d){return{ok:!1,status:"failed",cacheDir:e,message:`codeindex: pull failed \u2014 ${d instanceof Error?d.message:String(d)} (nothing written) -`}}let c;try{if(gt(_e(e),{recursive:!0}),c=Ln(I(_e(e),".grammars-tmp-")),rd(l,c),!H(I(c,"web-tree-sitter.wasm")))throw new Error("archive is missing web-tree-sitter.wasm");Dp(c,e,a,s),c=void 0}catch(d){if(c)try{qe(c,{recursive:!0,force:!0})}catch{}return{ok:!1,status:"failed",cacheDir:e,message:`codeindex: pull failed \u2014 ${d instanceof Error?d.message:String(d)} (nothing written) +`);let l;try{l=await cd(r.url,s)}catch(d){return{ok:!1,status:"failed",cacheDir:e,message:`codeindex: pull failed \u2014 ${d instanceof Error?d.message:String(d)} (nothing written) +`}}let c;try{if(_t(_e(e),{recursive:!0}),c=Dn(I(_e(e),".grammars-tmp-")),md(l,c),!H(I(c,"web-tree-sitter.wasm")))throw new Error("archive is missing web-tree-sitter.wasm");ag(c,e,a,s),c=void 0}catch(d){if(c)try{Ge(c,{recursive:!0,force:!0})}catch{}return{ok:!1,status:"failed",cacheDir:e,message:`codeindex: pull failed \u2014 ${d instanceof Error?d.message:String(d)} (nothing written) `}}return{ok:!0,status:"pulled",cacheDir:e,message:`codeindex: grammars extracted \u2192 ${e} -`}}k();nt();async function jp(e={}){let t=e.label??"codeindex",n=[],r=f=>{n.push(f),e.onNote?e.onNote(f):R.stderr.write(f)},s=R.env.CODEINDEX_NO_GRAMMARS_PULL,o=(e.pull??!0)&&!(s&&s.trim()&&s!=="0"),a=[...e.keys??go()],l=!1;if(Qe().tier==="none"&&o){r(`${t}: tree-sitter grammars not found locally \u2014 pulling them into the shared cache (once per machine)\u2026 -`);let f=await ir(wn(),{onNote:r});r(f.message),l=f.ok&&f.status==="pulled"}await et(a);let c=Qe().tier,d=a.some(f=>tt(f));return d||r(`${t}: no tree-sitter grammars available (offline?) \u2014 extracting with the regex tier, so symbols and call sites are less precise. Run \`codeindex grammars pull\` once online to enable AST precision. -`),{tier:c,ready:d,pulled:l,notes:n}}Ps();Ds();Js();Sn();Xt();mr();Yt();Ks();la();Zs();Sr();qs();_a();vn();ha();cr();ei();k();oe();Xe();Ae();Y();var kt=class{buf;len=0;constructor(t=64){this.buf=new Uint8Array(t)}get length(){return this.len}grow(t){if(this.len+t<=this.buf.length)return;let n=this.buf.length*2||64;for(;n127;)e.push(t&127|128),t=Math.floor(t/128);e.push(t&127)}function jd(e,t,n){ni(e,t*8+n)}function ti(e,t,n){jd(e,t,0),ni(e,n)}function Wd(e,t,n){jd(e,t,2),ni(e,n.length),e.pushAll(n)}function Nn(e,t,n){Wd(e,t,n.view())}function St(e,t,n){Wd(e,t,q_.encode(n))}function G_(e,t,n){let r=new kt(n.length*2);for(let s of n)ni(r,s);Nn(e,t,r)}var V_=1,J_=2,K_=2,X_=3,Z_=4,Y_=1,Q_=2,eh=1,th=2,nh=3,rh=4,sh=6,ih=1,oh=2,ah=3,lh=1,ch=5,dh=6,uh=8,fh=1,mh=1,ph=2,gh={function:17,method:26,class:7,interface:21,enum:11,struct:49,trait:53,type:54,const:8,var:61},Ud="codeindex . . . ",_h=/^[A-Za-z0-9_+\-$]+$/;function Bd(e){return _h.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function zd(e){return"`"+e.replace(/`/g,"``")+"`/"}function Hd(e){return Bd(e)+"#"}var hh=new Set(["class","interface","enum","struct","trait","type"]),yh=new Set(["function","method","def"]);function bh(e){return hh.has(e)?"#":yh.has(e)?"().":"."}function wh(e,t){let n=Ud+zd(e);return t.parent&&(n+=Hd(t.parent)),n+Bd(t.name)+bh(t.kind)}function xh(e,t){return Ud+zd(e)+Hd(t)}function Sh(e,t,n){if(!n.has(e))return n.add(e),e;for(let r=0;;r++){let s=r===0?String(t):`${t}_${r}`,o=`${e}(${s})`;if(!n.has(o))return n.add(o),o}}function Ld(e){return e==="typescript"||e==="javascript"?"js":e==="c"||e==="cpp"?"c":e}var kh=new Set(["reexport","reexport-all","default"]);function Dd(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function Eh(e,t){if(!t)return null;let n=/^[A-Za-z_$][\w$]*$/.test(t),r=0;for(;;){let s=e.indexOf(t,r);if(s<0)return null;if(!n)return[s,s+t.length];let o=s>0?e.charCodeAt(s-1):-1,a=s+t.length,l=ap.kind==="code"&&p.symbols.length>0),o=new Map,a=new Map;for(let p of s){let g=new Set,y=[];for(let h of p.symbols){let S=Sh(wh(p.rel,h),h.line,g);if(y.push({sym:h,symbolString:S}),h.exported&&!kh.has(h.kind)){let _=a.get(h.name);_||a.set(h.name,_=[]),_.push({symbolString:S,family:Ld(h.lang)})}}o.set(p.rel,y)}let l=(p,g)=>{let y=a.get(p);if(!y||y.length!==1)return;let h=y[0];return h.family===g?h.symbolString:void 0},c=[];for(let p of s){let y=G(I(e.root,p.rel)).split(` -`).map(N=>N.endsWith("\r")?N.slice(0,-1):N),h=(N,U)=>{let le=y[N-1];if(le===void 0)return[N-1,0,0];let V=Eh(le,U);return V?[N-1,V[0],V[1]]:[N-1,0,le.length]},S=o.get(p.rel),_=[];for(let{sym:N,symbolString:U}of S)_.push({range:h(N.line,N.name),symbol:U,roles:mh});let E=Ld(p.lang);for(let N of p.calls??[]){let U=l(N.name,E);U&&_.push({range:h(N.line,N.name),symbol:U,roles:0})}_.sort((N,U)=>N.range[0]-U.range[0]||N.range[1]-U.range[1]||N.range[2]-U.range[2]||N.roles-U.roles||M(N.symbol,U.symbol));let b=new Set,x=S.map(({sym:N,symbolString:U})=>({symbol:U,displayName:N.name,kind:gh[N.kind],enclosing:N.parent?xh(p.rel,N.parent):void 0})).sort((N,U)=>M(N.symbol,U.symbol)),v=new kt(1024);St(v,eh,p.rel);let A=new kt(64);for(let N of _){let U=`${N.range.join(",")} ${N.roles} ${N.symbol}`;b.has(U)||(b.add(U),A.reset(),G_(A,ih,N.range),St(A,oh,N.symbol),N.roles!==0&&ti(A,ah,N.roles),Nn(v,th,A))}let O=new kt(64);for(let N of x)O.reset(),St(O,lh,N.symbol),N.kind!==void 0&&ti(O,ch,N.kind),St(O,dh,N.displayName),N.enclosing&&St(O,uh,N.enclosing),Nn(v,nh,O);St(v,rh,p.lang),ti(v,sh,ph),c.push(v)}let d=new kt;St(d,Y_,"codeindex"),St(d,Q_,r);let f=new kt;Nn(f,K_,d),St(f,X_,n),ti(f,Z_,fh);let u=0;for(let p of c)u+=p.length;let m=new kt(u+f.length+16);Nn(m,V_,f);for(let p of c)Nn(m,J_,p);return m.toUint8Array()}ri();Gt();si();Mn();sn();Cr();On();ai();li();Ea();pi();Ta();Ca();Fa();Ra();Na();gi();Fr();Nr();_i();kr();yr();hi();k();Y();var by=new Set(["import","use","call"]);function ku(e){let t=e.slice().sort((s,o)=>s-o),n=t.length,r=n===0?0:t[Math.min(n-1,Math.floor(.99*n))];return Math.max(50,r)}function Eu(e,t,n=1/0){let r=new Map;for(let l of e){if(l.dangling||!by.has(l.kind))continue;let c=r.get(l.to);c||r.set(l.to,c=[]),c.push(l)}let s=new Map,o=new Set(t),a=[...t];for(let l=1;l<=n&&a.length;l++){let c=[];for(let d of a)for(let f of(r.get(d)??[]).slice().sort((u,m)=>M(u.from,m.from)))o.has(f.from)||(o.add(f.from),s.set(f.from,l),c.push(f.from));a=c}return s}function Wr(e,t,n=1/0){let r=new Map(e.files.map(f=>[f.rel,f.module])),s=e.modules.find(f=>f.slug===t),o=s?void 0:e.files.find(f=>f.rel===t);if(!s&&!o)return;let a=s?s.members:[o.rel],c=[...Eu(e.fileEdges,a,n).entries()].map(([f,u])=>({rel:f,module:r.get(f)??"root",depth:u})).sort((f,u)=>f.depth-u.depth||M(f.rel,u.rel)),d=[...new Set(c.map(f=>f.module).filter(f=>f!==t))].sort(M);return{target:t,scope:s?"module":"file",seeds:a,files:c,modules:d}}function Su(e,t,n,r){let s=new Map,o=new Map,a=new Map;for(let u of e)u.dangling||r&&!r.has(u.kind)||((s.get(u.from)??s.set(u.from,[]).get(u.from)).push(u),(o.get(u.to)??o.set(u.to,[]).get(u.to)).push(u),a.set(u.from,(a.get(u.from)??0)+1),a.set(u.to,(a.get(u.to)??0)+1));let l=ku([...a.values()]),c=new Set([t]),d=[],f=[t];for(let u=1;u<=n;u++){let m=[];for(let p of f)if(!(p!==t&&(a.get(p)??0)>=l)){for(let g of(s.get(p)??[]).slice().sort((y,h)=>M(y.to,h.to)))c.has(g.to)||(d.push({node:g.to,direction:"out",kind:g.kind,weight:g.weight,depth:u,confidence:g.confidence}),c.add(g.to),m.push(g.to));for(let g of(o.get(p)??[]).slice().sort((y,h)=>M(y.from,h.from)))c.has(g.from)||(d.push({node:g.from,direction:"in",kind:g.kind,weight:g.weight,depth:u,confidence:g.confidence}),c.add(g.from),m.push(g.from))}f=m}return d}function Da(e,t,n=1,r){let s=e.modules.find(a=>a.slug===t);if(s)return{target:t,scope:"module",links:Su(e.moduleEdges,t,n,r),members:s.members};if(e.files.find(a=>a.rel===t))return{target:t,scope:"file",links:Su(e.fileEdges,t,n,r)}}k();Gt();Y();Ae();Ce();var Rt={exportedChange:25,hubHigh:20,hubMed:10,blastHigh:20,blastMed:10,testGap:20,surprise:10,dangling:15},wy=60,xy=30,Sy=3,ja=2;function vu(e,t){let n=[],r=new Set,s=(a,l)=>{let c=`${a.name}:${a.line}`;r.has(c)||(r.add(c),n.push({name:a.name,kind:a.kind,exported:a.exported,line:a.line,...a.endLine!==void 0?{endLine:a.endLine}:{},...a.parent!==void 0?{parent:a.parent}:{},...l?{approx:!0}:{}}))},o=a=>(a.endLine??a.line)-a.line;for(let a of t){let l=e.filter(c=>c.line<=a.end&&(c.endLine??c.line)>=a.start);if(l.length){l.sort((c,d)=>o(c)-o(d)||d.line-c.line||M(c.name,d.name));for(let c of l)s(c,!1)}else{let c=e.filter(f=>f.line<=a.start&&f.endLine===void 0),d=c[c.length-1];d&&s(d,!0)}}return n}function ky(e,t){if(e.length<=1)return 0;let n=0;for(let r of e)r[b.rel,b])),a=new Map;if(t){for(let[b,x]of Object.entries(t.defs))for(let v of x){let A=a.get(v.file);A||a.set(v.file,A=[]),A.push({name:b,...v})}for(let b of a.values())b.sort((x,v)=>x.line-v.line||M(x.name,v.name))}let l=[],c=[],d=[];for(let b of[...n.files].sort((x,v)=>M(x.path,v.path))){let x={...b.oldPath!==void 0?{oldPath:b.oldPath}:{},...b.binary?{binary:!0}:{},...b.linesAdded!==void 0?{linesAdded:b.linesAdded}:{},...b.linesDeleted!==void 0?{linesDeleted:b.linesDeleted}:{}};if(b.status==="deleted"){l.push(b.path),d.push({path:b.path,status:b.status,...x,hunks:[],symbols:[]});continue}let v=o.get(b.path);if(!v){c.push(b.path);continue}let A=n.hunks.get(b.path)??[];!A.length&&b.status==="added"&&!b.binary&&(A=[{start:1,end:Math.max(v.lines,1)}]);let O=b.binary?[]:vu(a.get(b.path)??[],A);d.push({path:b.path,status:b.status,...x,module:v.module,hunks:A.map(N=>({start:N.start,end:N.end})),symbols:O})}let f=new Set(d.filter(b=>b.status!=="deleted").map(b=>b.path)),u=e.fileEdges.filter(b=>b.dangling&&(b.kind==="import"||b.kind==="doc-link")&&f.has(b.from)).map(b=>({from:b.from,spec:b.to,reason:b.reason??"unknown"})).sort((b,x)=>M(b.from,x.from)||M(b.spec,x.spec)),m=(b,x)=>{if(!x.startsWith("."))return!1;let v=b.split("/").slice(0,-1);for(let A of x.split("/"))A==="."||A===""||(A===".."?v.pop():v.push(A));return v.some(A=>qt.has(A))},p=new Map;for(let b of d){if(b.status==="deleted"||!b.module)continue;let x=p.get(b.module);x||p.set(b.module,x=[]),x.push(b)}let g=new Set;for(let b of e.files)b.fileKind==="code"&&!b.testFile&&g.add(b.module);let y=e.modules.some(b=>b.pagerank!==void 0),h=b=>y?b.pagerank??0:b.degIn+b.degOut,S=e.modules.map(h),_=y?"pagerank":"degree",E=[];for(let b of[...p.keys()].sort(M)){let x=e.modules.find(L=>L.slug===b);if(!x)continue;let v=p.get(b),A=[],O=0,N=[...new Set(v.flatMap(L=>L.symbols.filter(de=>de.exported).map(de=>de.name)))].sort(M);if(N.length){O+=Rt.exportedChange;let L=N.slice(0,3).join(", ")+(N.length>3?", \u2026":"");A.push(N.length===1?`exported symbol ${L} changed`:`exported symbols ${L} changed`)}let U=ky(S,h(x));U>=.9?(O+=Rt.hubHigh,A.push(`${_} p${Math.round(U*100)} hub`)):U>=.75&&(O+=Rt.hubMed,A.push(`${_} p${Math.round(U*100)} hub`));let le=new Map,V=new Set;for(let L of v){let de=Wr(e,L.path,r);if(de){for(let K of de.files){let ce=le.get(K.rel);(ce===void 0||K.depthL===1).length,transitiveFiles:z,modules:[...V].sort(M)};z>=20||j.modules.length>=5?(O+=Rt.blastHigh,A.push(`${z} dependent files across ${j.modules.length} modules (depth ${r})`)):z>=5&&(O+=Rt.blastMed,A.push(`${z} dependent files across ${j.modules.length} modules (depth ${r})`));let B=x.tier<=1&&x.symbols>0&&g.has(b),re=x.testedBy??[],J=B?re.length?{status:"covered",files:re}:{status:"gap",files:[]}:{status:"n/a",files:[]};J.status==="gap"&&(O+=Rt.testGap,A.push("no test covers this module"));let ee=(e.surprises??[]).find(L=>L.from===b||L.to===b);ee&&(O+=Rt.surprise,A.push(`cross-community edge to ${ee.from===b?ee.to:ee.from} (surprising)`));let be=u.filter(L=>v.some(de=>de.path===L.from)&&!m(L.from,L.spec));if(be.length){O+=Rt.dangling;let L=be[0],de=be.length>1?` (+${be.length-1} more)`:"";A.push(`dangling import "${L.spec}" in ${L.from}${de}`)}O=Math.min(100,O);let Ie=v.map(L=>L.path).sort(M),X=v.flatMap(L=>L.symbols),Z=v.slice().sort((L,de)=>de.symbols.filter(K=>K.exported).length-L.symbols.filter(K=>K.exported).length||de.symbols.length-L.symbols.length||M(L.path,de.path)).slice(0,Sy).map(L=>L.path);E.push({slug:b,path:x.path,score:O,bucket:O>=wy?"HIGH":O>=xy?"MEDIUM":"LOW",reasons:A,changedFiles:Ie,changedSymbols:{total:new Set(X.map(L=>`${L.name}:${L.line}`)).size,exported:new Set(X.filter(L=>L.exported).map(L=>`${L.name}:${L.line}`)).size},impact:j,tests:J,open:Z})}return E.sort((b,x)=>x.score-b.score||M(b.slug,x.slug)),{base:n.base,...e.commit!==void 0?{indexCommit:e.commit}:{},depth:r,changes:d,modules:E,dangling:u,deleted:l.sort(M),unindexed:c.sort(M),notes:s}}function Wa(e,t,n,r={}){if(!at("git"))return{error:"git is required for delta and was not found on PATH"};if(!zi(e))return{error:`delta needs a git worktree \u2014 ${e} is not inside one`};let s=[],o;if(r.staged){let c=pe("git",["-C",e,"rev-parse","HEAD"]);if(!c.ok)return{error:"cannot resolve HEAD \u2014 empty repository?"};o={ref:"HEAD",mergeBase:c.stdout.trim(),staged:!0}}else{let c=Hi(e,r.base);if("error"in c)return{error:c.error};c.note&&s.push(c.note),o={ref:c.ref,mergeBase:c.mergeBase,staged:!1}}let a=r.staged?{staged:!0}:{mergeBase:o.mergeBase},l=qi(e,a);if(!r.staged){let c=new Set(l.map(d=>d.path));for(let d of ls(e))c.has(d)||l.push({path:d,status:"added"})}return Ru(t,n,{files:l,hunks:Gi(e,a),base:o,notes:s},r.depth??ja)}function Ua(e){let t=e.base.mergeBase.slice(0,7),n=`${e.base.staged?"staged vs ":""}${e.base.ref}`;if(!e.changes.length&&!e.unindexed.length)return`codeindex: no changes vs ${n} (merge-base ${t}) +`}}E();nt();async function lg(e={}){let t=e.label??"codeindex",n=[],r=f=>{n.push(f),e.onNote?e.onNote(f):R.stderr.write(f)},s=R.env.CODEINDEX_NO_GRAMMARS_PULL,o=(e.pull??!0)&&!(s&&s.trim()&&s!=="0"),a=[...e.keys??yo()],l=!1;if(Qe().tier==="none"&&o){r(`${t}: tree-sitter grammars not found locally \u2014 pulling them into the shared cache (once per machine)\u2026 +`);let f=await ar(xn(),{onNote:r});r(f.message),l=f.ok&&f.status==="pulled"}await et(a);let c=Qe().tier,d=a.some(f=>tt(f));return d||r(`${t}: no tree-sitter grammars available (offline?) \u2014 extracting with the regex tier, so symbols and call sites are less precise. Run \`codeindex grammars pull\` once online to enable AST precision. +`),{tier:c,ready:d,pulled:l,notes:n}}Ds();Ws();Zs();kn();Xt();gr();Qt();Ys();fa();ei();Er();Js();wa();vn();xa();ur();ri();E();ae();Xe();Ne();Y();var Et=class{buf;len=0;constructor(t=64){this.buf=new Uint8Array(t)}get length(){return this.len}grow(t){if(this.len+t<=this.buf.length)return;let n=this.buf.length*2||64;for(;n127;)e.push(t&127|128),t=Math.floor(t/128);e.push(t&127)}function Zd(e,t,n){ii(e,t*8+n)}function si(e,t,n){Zd(e,t,0),ii(e,n)}function Yd(e,t,n){Zd(e,t,2),ii(e,n.length),e.pushAll(n)}function Nn(e,t,n){Yd(e,t,n.view())}function kt(e,t,n){Yd(e,t,ph.encode(n))}function gh(e,t,n){let r=new Et(n.length*2);for(let s of n)ii(r,s);Nn(e,t,r)}var _h=1,hh=2,yh=2,bh=3,wh=4,xh=1,Sh=2,kh=1,Eh=2,vh=3,Rh=4,Mh=6,Ch=1,Ah=2,Th=3,Ih=1,Nh=5,Fh=6,Oh=8,Ph=1,$h=1,Dh=2,Lh={function:17,method:26,class:7,interface:21,enum:11,struct:49,trait:53,type:54,const:8,var:61},Qd="codeindex . . . ",jh=/^[A-Za-z0-9_+\-$]+$/;function eu(e){return jh.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function tu(e){return"`"+e.replace(/`/g,"``")+"`/"}function nu(e){return eu(e)+"#"}var Wh=new Set(["class","interface","enum","struct","trait","type"]),Uh=new Set(["function","method","def"]);function Bh(e){return Wh.has(e)?"#":Uh.has(e)?"().":"."}function zh(e,t){let n=Qd+tu(e);return t.parent&&(n+=nu(t.parent)),n+eu(t.name)+Bh(t.kind)}function Hh(e,t){return Qd+tu(e)+nu(t)}function Gh(e,t,n){if(!n.has(e))return n.add(e),e;for(let r=0;;r++){let s=r===0?String(t):`${t}_${r}`,o=`${e}(${s})`;if(!n.has(o))return n.add(o),o}}function Kd(e){return e==="typescript"||e==="javascript"?"js":e==="c"||e==="cpp"?"c":e}var qh=new Set(["reexport","reexport-all","default"]);function Xd(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function Vh(e,t){if(!t)return null;let n=/^[A-Za-z_$][\w$]*$/.test(t),r=0;for(;;){let s=e.indexOf(t,r);if(s<0)return null;if(!n)return[s,s+t.length];let o=s>0?e.charCodeAt(s-1):-1,a=s+t.length,l=ap.kind==="code"&&p.symbols.length>0),o=new Map,a=new Map;for(let p of s){let g=new Set,y=[];for(let h of p.symbols){let S=Gh(zh(p.rel,h),h.line,g);if(y.push({sym:h,symbolString:S}),h.exported&&!qh.has(h.kind)){let _=a.get(h.name);_||a.set(h.name,_=[]),_.push({symbolString:S,family:Kd(h.lang)})}}o.set(p.rel,y)}let l=(p,g)=>{let y=a.get(p);if(!y||y.length!==1)return;let h=y[0];return h.family===g?h.symbolString:void 0},c=[];for(let p of s){let y=q(I(e.root,p.rel)).split(` +`).map(T=>T.endsWith("\r")?T.slice(0,-1):T),h=(T,U)=>{let te=y[T-1];if(te===void 0)return[T-1,0,0];let V=Vh(te,U);return V?[T-1,V[0],V[1]]:[T-1,0,te.length]},S=o.get(p.rel),_=[];for(let{sym:T,symbolString:U}of S)_.push({range:h(T.line,T.name),symbol:U,roles:$h});let k=Kd(p.lang);for(let T of p.calls??[]){let U=l(T.name,k);U&&_.push({range:h(T.line,T.name),symbol:U,roles:0})}_.sort((T,U)=>T.range[0]-U.range[0]||T.range[1]-U.range[1]||T.range[2]-U.range[2]||T.roles-U.roles||M(T.symbol,U.symbol));let b=new Set,w=S.map(({sym:T,symbolString:U})=>({symbol:U,displayName:T.name,kind:Lh[T.kind],enclosing:T.parent?Hh(p.rel,T.parent):void 0})).sort((T,U)=>M(T.symbol,U.symbol)),v=new Et(1024);kt(v,kh,p.rel);let A=new Et(64);for(let T of _){let U=`${T.range.join(",")} ${T.roles} ${T.symbol}`;b.has(U)||(b.add(U),A.reset(),gh(A,Ch,T.range),kt(A,Ah,T.symbol),T.roles!==0&&si(A,Th,T.roles),Nn(v,Eh,A))}let F=new Et(64);for(let T of w)F.reset(),kt(F,Ih,T.symbol),T.kind!==void 0&&si(F,Nh,T.kind),kt(F,Fh,T.displayName),T.enclosing&&kt(F,Oh,T.enclosing),Nn(v,vh,F);kt(v,Rh,p.lang),si(v,Mh,Dh),c.push(v)}let d=new Et;kt(d,xh,"codeindex"),kt(d,Sh,r);let f=new Et;Nn(f,yh,d),kt(f,bh,n),si(f,wh,Ph);let u=0;for(let p of c)u+=p.length;let m=new Et(u+f.length+16);Nn(m,_h,f);for(let p of c)Nn(m,hh,p);return m.toUint8Array()}oi();qt();ai();Mn();on();Tr();Fn();di();ui();Ca();hi();Oa();Na();La();Ta();$a();yi();$r();Or();bi();vr();wr();wi();E();Y();var zy=new Set(["import","use","call"]),Ou=new WeakMap;function Hy(e){let t=Ou.get(e);if(t&&t.length===e.length)return t.map;let n=new Map;for(let r of e){if(r.dangling||!zy.has(r.kind))continue;let s=n.get(r.to);s||n.set(r.to,s=[]),s.push(r)}for(let r of n.values())r.sort((s,o)=>M(s.from,o.from));return Ou.set(e,{length:e.length,map:n}),n}var Pu=new WeakMap;function Gy(e,t){let n=t?[...t].sort(M).join(","):"*",r=Pu.get(e);(!r||r.length!==e.length)&&Pu.set(e,r={length:e.length,views:new Map});let s=r.views.get(n);if(s)return s;let o=new Map,a=new Map,l=new Map;for(let d of e)d.dangling||t&&!t.has(d.kind)||((o.get(d.from)??o.set(d.from,[]).get(d.from)).push(d),(a.get(d.to)??a.set(d.to,[]).get(d.to)).push(d),l.set(d.from,(l.get(d.from)??0)+1),l.set(d.to,(l.get(d.to)??0)+1));for(let d of o.values())d.sort((f,u)=>M(f.to,u.to));for(let d of a.values())d.sort((f,u)=>M(f.from,u.from));let c={out:o,inn:a,degree:l,threshold:Du([...l.values()])};return r.views.set(n,c),c}function Du(e){let t=e.slice().sort((s,o)=>s-o),n=t.length,r=n===0?0:t[Math.min(n-1,Math.floor(.99*n))];return Math.max(50,r)}function Lu(e,t,n=1/0){let r=Hy(e),s=new Map,o=new Set(t),a=[...t];for(let l=1;l<=n&&a.length;l++){let c=[];for(let d of a)for(let f of r.get(d)??[])o.has(f.from)||(o.add(f.from),s.set(f.from,l),c.push(f.from));a=c}return s}function Br(e,t,n=1/0){let r=new Map(e.files.map(f=>[f.rel,f.module])),s=e.modules.find(f=>f.slug===t),o=s?void 0:e.files.find(f=>f.rel===t);if(!s&&!o)return;let a=s?s.members:[o.rel],c=[...Lu(e.fileEdges,a,n).entries()].map(([f,u])=>({rel:f,module:r.get(f)??"root",depth:u})).sort((f,u)=>f.depth-u.depth||M(f.rel,u.rel)),d=[...new Set(c.map(f=>f.module).filter(f=>f!==t))].sort(M);return{target:t,scope:s?"module":"file",seeds:a,files:c,modules:d}}function $u(e,t,n,r){let{out:s,inn:o,degree:a,threshold:l}=Gy(e,r),c=new Set([t]),d=[],f=[t];for(let u=1;u<=n;u++){let m=[];for(let p of f)if(!(p!==t&&(a.get(p)??0)>=l)){for(let g of s.get(p)??[])c.has(g.to)||(d.push({node:g.to,direction:"out",kind:g.kind,weight:g.weight,depth:u,confidence:g.confidence}),c.add(g.to),m.push(g.to));for(let g of o.get(p)??[])c.has(g.from)||(d.push({node:g.from,direction:"in",kind:g.kind,weight:g.weight,depth:u,confidence:g.confidence}),c.add(g.from),m.push(g.from))}f=m}return d}function Ba(e,t,n=1,r){let s=e.modules.find(a=>a.slug===t);if(s)return{target:t,scope:"module",links:$u(e.moduleEdges,t,n,r),members:s.members};if(e.files.find(a=>a.rel===t))return{target:t,scope:"file",links:$u(e.fileEdges,t,n,r)}}E();qt();Y();Ne();Ae();var Mt={exportedChange:25,hubHigh:20,hubMed:10,blastHigh:20,blastMed:10,testGap:20,surprise:10,dangling:15},qy=60,Vy=30,Jy=3,za=2;function ju(e,t){let n=[],r=new Set,s=(a,l)=>{let c=`${a.name}:${a.line}`;r.has(c)||(r.add(c),n.push({name:a.name,kind:a.kind,exported:a.exported,line:a.line,...a.endLine!==void 0?{endLine:a.endLine}:{},...a.parent!==void 0?{parent:a.parent}:{},...l?{approx:!0}:{}}))},o=a=>(a.endLine??a.line)-a.line;for(let a of t){let l=e.filter(c=>c.line<=a.end&&(c.endLine??c.line)>=a.start);if(l.length){l.sort((c,d)=>o(c)-o(d)||d.line-c.line||M(c.name,d.name));for(let c of l)s(c,!1)}else{let c=e.filter(f=>f.line<=a.start&&f.endLine===void 0),d=c[c.length-1];d&&s(d,!0)}}return n}function Ky(e,t){if(e.length<=1)return 0;let n=0;for(let r of e)r[b.rel,b])),a=new Map;if(t){for(let[b,w]of Object.entries(t.defs))for(let v of w){let A=a.get(v.file);A||a.set(v.file,A=[]),A.push({name:b,...v})}for(let b of a.values())b.sort((w,v)=>w.line-v.line||M(w.name,v.name))}let l=[],c=[],d=[];for(let b of[...n.files].sort((w,v)=>M(w.path,v.path))){let w={...b.oldPath!==void 0?{oldPath:b.oldPath}:{},...b.binary?{binary:!0}:{},...b.linesAdded!==void 0?{linesAdded:b.linesAdded}:{},...b.linesDeleted!==void 0?{linesDeleted:b.linesDeleted}:{}};if(b.status==="deleted"){l.push(b.path),d.push({path:b.path,status:b.status,...w,hunks:[],symbols:[]});continue}let v=o.get(b.path);if(!v){c.push(b.path);continue}let A=n.hunks.get(b.path)??[];!A.length&&b.status==="added"&&!b.binary&&(A=[{start:1,end:Math.max(v.lines,1)}]);let F=b.binary?[]:ju(a.get(b.path)??[],A);d.push({path:b.path,status:b.status,...w,module:v.module,hunks:A.map(T=>({start:T.start,end:T.end})),symbols:F})}let f=new Set(d.filter(b=>b.status!=="deleted").map(b=>b.path)),u=e.fileEdges.filter(b=>b.dangling&&(b.kind==="import"||b.kind==="doc-link")&&f.has(b.from)).map(b=>({from:b.from,spec:b.to,reason:b.reason??"unknown"})).sort((b,w)=>M(b.from,w.from)||M(b.spec,w.spec)),m=(b,w)=>{if(!w.startsWith("."))return!1;let v=b.split("/").slice(0,-1);for(let A of w.split("/"))A==="."||A===""||(A===".."?v.pop():v.push(A));return v.some(A=>Gt.has(A))},p=new Map;for(let b of d){if(b.status==="deleted"||!b.module)continue;let w=p.get(b.module);w||p.set(b.module,w=[]),w.push(b)}let g=new Set;for(let b of e.files)b.fileKind==="code"&&!b.testFile&&g.add(b.module);let y=e.modules.some(b=>b.pagerank!==void 0),h=b=>y?b.pagerank??0:b.degIn+b.degOut,S=e.modules.map(h),_=y?"pagerank":"degree",k=[];for(let b of[...p.keys()].sort(M)){let w=e.modules.find(D=>D.slug===b);if(!w)continue;let v=p.get(b),A=[],F=0,T=[...new Set(v.flatMap(D=>D.symbols.filter(de=>de.exported).map(de=>de.name)))].sort(M);if(T.length){F+=Mt.exportedChange;let D=T.slice(0,3).join(", ")+(T.length>3?", \u2026":"");A.push(T.length===1?`exported symbol ${D} changed`:`exported symbols ${D} changed`)}let U=Ky(S,h(w));U>=.9?(F+=Mt.hubHigh,A.push(`${_} p${Math.round(U*100)} hub`)):U>=.75&&(F+=Mt.hubMed,A.push(`${_} p${Math.round(U*100)} hub`));let te=new Map,V=new Set;for(let D of v){let de=Br(e,D.path,r);if(de){for(let K of de.files){let ce=te.get(K.rel);(ce===void 0||K.depthD===1).length,transitiveFiles:z,modules:[...V].sort(M)};z>=20||j.modules.length>=5?(F+=Mt.blastHigh,A.push(`${z} dependent files across ${j.modules.length} modules (depth ${r})`)):z>=5&&(F+=Mt.blastMed,A.push(`${z} dependent files across ${j.modules.length} modules (depth ${r})`));let B=w.tier<=1&&w.symbols>0&&g.has(b),se=w.testedBy??[],J=B?se.length?{status:"covered",files:se}:{status:"gap",files:[]}:{status:"n/a",files:[]};J.status==="gap"&&(F+=Mt.testGap,A.push("no test covers this module"));let ne=(e.surprises??[]).find(D=>D.from===b||D.to===b);ne&&(F+=Mt.surprise,A.push(`cross-community edge to ${ne.from===b?ne.to:ne.from} (surprising)`));let be=u.filter(D=>v.some(de=>de.path===D.from)&&!m(D.from,D.spec));if(be.length){F+=Mt.dangling;let D=be[0],de=be.length>1?` (+${be.length-1} more)`:"";A.push(`dangling import "${D.spec}" in ${D.from}${de}`)}F=Math.min(100,F);let Ie=v.map(D=>D.path).sort(M),X=v.flatMap(D=>D.symbols),Z=v.slice().sort((D,de)=>de.symbols.filter(K=>K.exported).length-D.symbols.filter(K=>K.exported).length||de.symbols.length-D.symbols.length||M(D.path,de.path)).slice(0,Jy).map(D=>D.path);k.push({slug:b,path:w.path,score:F,bucket:F>=qy?"HIGH":F>=Vy?"MEDIUM":"LOW",reasons:A,changedFiles:Ie,changedSymbols:{total:new Set(X.map(D=>`${D.name}:${D.line}`)).size,exported:new Set(X.filter(D=>D.exported).map(D=>`${D.name}:${D.line}`)).size},impact:j,tests:J,open:Z})}return k.sort((b,w)=>w.score-b.score||M(b.slug,w.slug)),{base:n.base,...e.commit!==void 0?{indexCommit:e.commit}:{},depth:r,changes:d,modules:k,dangling:u,deleted:l.sort(M),unindexed:c.sort(M),notes:s}}function Ha(e,t,n,r={}){if(!at("git"))return{error:"git is required for delta and was not found on PATH"};if(!Gi(e))return{error:`delta needs a git worktree \u2014 ${e} is not inside one`};let s=[],o;if(r.staged){let c=pe("git",["-C",e,"rev-parse","HEAD"]);if(!c.ok)return{error:"cannot resolve HEAD \u2014 empty repository?"};o={ref:"HEAD",mergeBase:c.stdout.trim(),staged:!0}}else{let c=qi(e,r.base);if("error"in c)return{error:c.error};c.note&&s.push(c.note),o={ref:c.ref,mergeBase:c.mergeBase,staged:!1}}let a=r.staged?{staged:!0}:{mergeBase:o.mergeBase},l=Vi(e,a);if(!r.staged){let c=new Set(l.map(d=>d.path));for(let d of us(e))c.has(d)||l.push({path:d,status:"added"})}return Wu(t,n,{files:l,hunks:Ji(e,a),base:o,notes:s},r.depth??za)}function Ga(e){let t=e.base.mergeBase.slice(0,7),n=`${e.base.staged?"staged vs ":""}${e.base.ref}`;if(!e.changes.length&&!e.unindexed.length)return`codeindex: no changes vs ${n} (merge-base ${t}) `;let r=e.changes.length+e.unindexed.length,s=[`codeindex: delta vs ${n} (merge-base ${t}) \u2014 ${r} changed file(s), ${e.modules.length} module(s)${e.indexCommit?`, index @ ${e.indexCommit}`:""}`];for(let o of e.notes)s.push(` note: ${o}`);for(let o of e.modules){s.push(` ${o.bucket.padEnd(6)} ${o.slug} score ${o.score}${o.reasons.length?` \u2014 ${o.reasons.join("; ")}`:""}`);let a=o.tests.status==="gap"?"GAP":o.tests.status==="covered"?`covered (${o.tests.files.length})`:"n/a";s.push(` open: ${o.open.join(", ")||"\u2014"} \xB7 tests: ${a}`)}return e.dangling.length&&s.push(` dangling: ${e.dangling.map(o=>`${o.spec} (from ${o.from})`).join(" \xB7 ")}`),e.deleted.length&&s.push(` deleted: ${e.deleted.join(", ")}`),e.unindexed.length&&s.push(` unindexed: ${e.unindexed.join(", ")}`),s.join(` `)+` -`}Ja();Ka();At();Y();Ce();k();xe();oe();Xe();Xe();nt();ri();At();ei();cr();Ft();Os();sr();Ae();Xt();Yt();mr();Yt();Sr();Gt();si();Fr();Nr();_i();kr();yr();hi();Mn();gi();sn();On();ai();li();Ce();pi();Ri();var Wu=`codeindex engine v${fe} \u2014 deterministic repo indexing +`}Ya();Qa();Tt();Y();Ae();E();xe();ae();Xe();Xe();nt();oi();Tt();ri();ur();Pt();ir();or();Ne();Xt();Qt();gr();Qt();Er();qt();ai();$r();Or();bi();vr();wr();wi();Mn();yi();on();Fn();di();ui();Ae();hi();Ai();var ef=`codeindex engine v${fe} \u2014 deterministic repo indexing Usage: engine.mjs [flags] @@ -186,6 +193,7 @@ Flags (accepted before OR after the subcommand: '--repo X scan' and --no-gitignore Do not honor .gitignore files (default: honored) --ignore-dir Directory names to skip (repeatable) \u2014 REPLACES the default ignored-directory set, never merges with it + (\`.git\` stays skipped regardless) --max-files Cap walked files (default: none \u2014 the whole tree is indexed; a cap sets the \`capped\` flag) --max-bytes Skip files above this size (default 1 MiB) @@ -224,54 +232,54 @@ Flags (accepted before OR after the subcommand: '--repo X scan' and --min-count \`literals\`: total occurrences required (default 3) --include-tests \`literals\`: count test files too. Off by default \u2014 a test restating a value is usually asserting it deliberately -`;function Fy(e){let t={repo:R.cwd(),include:[],exclude:[],gitignore:!0,ignoreDirs:[],noAst:!1,fuzzy:!0,semantic:!1};for(let n=0;n{let a=e[++n];if(a===void 0)throw new Error(`missing value for ${r}`);return a},o=()=>{let a=s(),l=Number(a);if(!Number.isFinite(l)||l<=0)throw new Error(`${r} expects a positive number, got "${a}"`);return l};if(r==="--repo")t.repo=Ne(s());else if(r==="--out"){let a=s();t.out=a==="-"?"-":Ne(a)}else if(r==="--project-root")t.projectRoot=s();else if(r==="--include")t.include.push(s());else if(r==="--exclude")t.exclude.push(s());else if(r==="--scope")t.scope=s();else if(r==="--no-gitignore")t.gitignore=!1;else if(r==="--ignore-dir")t.ignoreDirs.push(s());else if(r==="--max-files")t.maxFiles=o();else if(r==="--max-bytes")t.maxBytes=o();else if(r==="--max-calls")t.maxCalls=o();else if(r==="--ignore-case")t.ignoreCase=!0;else if(r==="--max-hits")t.maxHits=o();else if(r==="--budget-tokens")t.budgetTokens=o();else if(r==="--min-files")t.minFiles=o();else if(r==="--min-count")t.minCount=o();else if(r==="--include-tests")t.includeTests=!0;else if(r==="--no-ast")t.noAst=!0;else if(r==="--index")t.indexDir=s();else if(r==="--no-index-cache")t.noIndexCache=!0;else if(r==="--workers"){let a=s(),l=Number(a);if(!Number.isInteger(l)||l<0)throw new Error(`--workers expects a non-negative integer, got "${a}"`);t.workers=l}else if(r==="--since")t.since=s();else if(r==="--config")t.config=Ne(s());else if(r==="--limit")t.limit=o();else if(r==="--no-fuzzy")t.fuzzy=!1;else if(r==="--exact")t.exact=!0;else if(r==="--explain")t.explain=!0;else if(r==="--semantic")t.semantic=!0;else if(r==="--recall")t.recall=!0;else if(r==="--run")t.run=!0;else if(r==="--probe")t.probe=!0;else if(r==="--base")t.base=s();else if(r==="--staged")t.staged=!0;else if(r==="--depth")t.depth=o();else if(r==="--kind")t.kind=s();else if(r==="--rank"){let a=s();if(a!=="graph"&&a!=="lexical")throw new Error(`--rank expects graph|lexical, got "${a}"`);t.rank=a}else if(r==="--direction"){let a=s();if(a!=="out"&&a!=="in"&&a!=="both")throw new Error(`--direction expects out|in|both, got "${a}"`);t.direction=a}else if(r==="--json")t.json=!0;else if(!r.startsWith("--")&&t.positional===void 0)t.positional=r;else throw new Error(`unknown flag: ${r}`)}return t}function ie(e,t){t?Re(t,e):R.stdout.write(e)}function Pn(e,t){return{include:e.include.length?e.include:void 0,exclude:e.exclude.length?e.exclude:void 0,scope:e.scope,gitignore:e.gitignore,ignoreDirs:e.ignoreDirs.length?e.ignoreDirs:void 0,maxFiles:e.maxFiles,maxBytes:e.maxBytes,maxCallsPerFile:e.maxCalls,precomputedWalk:t}}var Py=new Set(["grep","churn","coupling","workspaces","grammars"]);function $y(e){let t,n,r,s,o=!1;for(let a=0;a");return{defaultRepo:t,serverInfo:n?{name:n}:void 0,maxResponseBytes:r,profile:s,watch:o}}var Ly=new Set(["--repo","--out","--project-root","--include","--exclude","--scope","--ignore-dir","--max-files","--max-bytes","--max-calls","--max-hits","--budget-tokens","--min-files","--min-count","--since","--config","--limit","--server-name","--tools","--workers","--index","--max-response-bytes","--base","--depth","--kind","--rank","--direction"]);function Dy(e){let t=[],n=0;for(;n=e.length?e:[e[n],...t,...e.slice(n+1)]}async function jy(e){let t=Dy(e),[n,...r]=t;if(!n||n==="help"||n==="--help"||n==="-h"){R.stdout.write(Wu);return}if(n==="version"||n==="--version"){R.stdout.write(fe+` -`);return}if(n==="rewrite"){let{rewriteCommand:_}=await Promise.resolve().then(()=>(Ka(),ju)),E=_(r.join(" "));if(!E){R.exitCode=1;return}R.stdout.write(E+` -`);return}if(n==="mcp"){let{runMcpServer:_}=await Promise.resolve().then(()=>(Ja(),$u));await _($y(r));return}let s=Fy(r);if(!H(s.repo))throw new Error(`--repo path does not exist: ${s.repo}`);if(!Ee(s.repo).isDirectory())throw new Error(`--repo path is not a directory: ${s.repo}`);let o=!Py.has(n)&&!(n==="embed"&&s.positional!=="build"),a;o&&!s.noAst&&(a=Fe(s.repo,{maxFileBytes:s.maxBytes,maxFiles:s.maxFiles,gitignore:s.gitignore,ignoreDirs:s.ignoreDirs.length?s.ignoreDirs:void 0}));let l=!1,c=async()=>{l||s.noAst||!a||(await et(bt(a.files.map(_=>_.ext))),l=!0)},d=s.indexDir??ut,f=!1,u,m,p=async()=>{if(u)return u;if(f)return m;if(f=!0,!s.noIndexCache)return u=Is(s.repo,Pn(s,a),c,d).then(_=>(_&&(m={scan:_.scan,arts:_.arts,loadArtifacts:_.loadArtifacts}),m)),u},g,y=async()=>{let _=(await p())?.scan;return _||(g??=c().then(()=>Pt(s.repo,{...Pn(s,a),workers:s.workers})))},h,S=async()=>{let _=await p();return _?.arts?_.arts:_?_.arts??=_.loadArtifacts?.()??Et(_.scan,Pn(s,a)):h??=y().then(E=>Et(E,Pn(s,a)))};if(n==="index"){if(!s.out)throw new Error("index needs --out ");let _=s.out;gt(_,{recursive:!0});let E=I(_,"cache.json"),b,x={};try{let B=JSON.parse(te(E,"utf8"));B.schemaVersion===5&&B.extractorVersion===14&&(b=new Map(Object.entries(B.files)),x={engineVersion:B.engineVersion,commit:B.commit,graphSha1:B.graphSha1,symbolsSha1:B.symbolsSha1,embed:B.embed})}catch{}await c();let v=await Pt(s.repo,{...Pn(s,a),cache:b,out:_,workers:s.workers}),A=vt(s.repo),O=A?Wt(A):void 0,N=I(_,"graph.json"),U=I(_,"symbols.json"),le=I(_,"embeddings.bin"),V=B=>{try{return Me(te(B))}catch{return}},z=B=>{let re={};for(let J of v.files){let ee={hash:J.hash,record:J,size:J.size},be=v.mtimes.get(J.rel);be!==void 0&&(ee.mtimeMs=be),re[J.rel]=ee}Re(E,JSON.stringify({schemaVersion:5,extractorVersion:14,engineVersion:fe,commit:v.commit,graphSha1:B.graphSha1,symbolsSha1:B.symbolsSha1,embed:B.embed,files:re})+` -`)},P=!O||x.embed!==void 0&&x.embed.embedVersion===it&&x.embed.modelId===O.modelId&&x.embed.sha1!==void 0&&V(le)===x.embed.sha1;if(v.contentUnchanged&&x.engineVersion===fe&&x.commit===v.commit&&x.graphSha1!==void 0&&V(N)===x.graphSha1&&x.symbolsSha1!==void 0&&V(U)===x.symbolsSha1&&P)v.cacheDirty&&z(x),R.stderr.write(`codeindex: ${v.files.length} files \u2192 ${_}/graph.json + symbols.json${v.capped?" (capped)":""} (unchanged \u2014 artifacts reused) -`);else{let{graph:B,symbols:re}=Et(v),J=In(B),ee=js(re);Re(N,J),Re(U,ee);let be="",Ie;if(O){let X=on(v,O),Z=oi(X);Re(le,Z),Ie={embedVersion:it,modelId:O.modelId,sha1:Me(Z)},be=` + embeddings.bin (${X.records.length} records, model ${O.modelId})`}z({graphSha1:Me(J),symbolsSha1:Me(ee),embed:Ie}),R.stderr.write(`codeindex: ${v.files.length} files \u2192 ${_}/graph.json + symbols.json${be}${v.capped?" (capped)":""} -`)}}else if(n==="scan"){let _=rr(s.repo,Pn(s,a)),E={engineVersion:fe,commit:_.commit,fileCount:_.fileCount,languages:_.languages,capped:_.capped};ie(JSON.stringify(E,null,2)+` -`,s.out)}else if(n==="graph"){let{graph:_}=await S();ie(In(_),s.out)}else if(n==="symbols"){let{symbols:_}=await S();ie(js(_),s.out)}else if(n==="scip"){let _=await y(),E=ya(_,{projectRoot:s.projectRoot}),b=s.out??Ne("index.scip");b==="-"?R.stdout.write(T.from(E)):(Re(b,E),R.stderr.write(`codeindex: SCIP index \u2192 ${b} (${E.length} bytes) -`))}else if(n==="callers"){let _=await y(),E=Zt(_,void 0,{recall:s.recall}),b={};for(let[x,v]of E)b[x]=v;ie(JSON.stringify(b,null,2)+` -`,s.out)}else if(n==="hierarchy"){let _=await y(),E=kn(_,dr(_));if(s.positional){let b=E.get(s.positional);if(!b)throw new Error(`no type named ${s.positional}`);ie(JSON.stringify(b,null,2)+` -`,s.out)}else{let b={};for(let[x,v]of E)b[x]=v;ie(JSON.stringify(b,null,2)+` -`,s.out)}}else if(n==="implementations"){if(!s.positional)throw new Error("implementations needs a type name: cli.mjs implementations --repo ");let _=await y(),E=kn(_,dr(_));if(!E.has(s.positional))throw new Error(`no type named ${s.positional}`);ie(JSON.stringify({name:s.positional,implementations:lr(E,s.positional)},null,2)+` -`,s.out)}else if(n==="callgraph"){if(!s.positional)throw new Error("callgraph needs a symbol: cli.mjs callgraph --repo ");let _=await y(),E=ur(_,dr(_)),b=fr(E,s.positional,{...s.depth!==void 0?{depth:s.depth}:{},...s.direction?{direction:s.direction}:{}});if(!b.root.length)throw new Error(`no symbol named ${s.positional}`);ie(JSON.stringify(b,null,2)+` -`,s.out)}else if(n==="search"){if(!s.positional)throw new Error('search needs a query: cli.mjs search "" --repo ');let _=await y(),E={limit:s.limit,fuzzy:s.fuzzy,...s.exact?{exact:!0}:{},...s.rank?{rank:s.rank}:{}},b=()=>{let{explain:x}=tn(_,s.positional,E);x.note&&R.stderr.write(`codeindex: ${x.note} -`)};if(s.semantic){let x=Ut(),v=()=>{let A=Lt(_,s.positional,E);ie(JSON.stringify(A,null,2)+` -`,s.out)};if(x)try{let A=await Ir(_),O=await Tr(s.positional),N=an(_,s.positional,A,{queryVec:O,limit:s.limit,fuzzy:s.fuzzy});ie(JSON.stringify(N,null,2)+` -`,s.out)}catch(A){R.stderr.write(`codeindex: embedding endpoint ${x} unavailable (${A instanceof Error?A.message:A}) \u2014 returning lexical results -`),v()}else{let A=vt(s.repo),O=A?Wt(A):void 0;if(!O)R.stderr.write("codeindex: semantic search unavailable (no embedding model or endpoint) \u2014 returning lexical results; run `codeindex embed pull` or set CODEINDEX_EMBED_ENDPOINT to enable it\n"),v();else{let N=on(_,O),U=an(_,s.positional,N,{model:O,limit:s.limit,fuzzy:s.fuzzy});ie(JSON.stringify(U,null,2)+` -`,s.out)}}b()}else{let{results:x,explain:v}=tn(_,s.positional,E);ie(JSON.stringify(s.explain?{results:x,explain:v}:x,null,2)+` +`;function ob(e){let t={repo:R.cwd(),include:[],exclude:[],gitignore:!0,ignoreDirs:[],noAst:!1,fuzzy:!0,semantic:!1};for(let n=0;n{let a=e[++n];if(a===void 0)throw new Error(`missing value for ${r}`);return a},o=()=>{let a=s(),l=Number(a);if(!Number.isFinite(l)||l<=0)throw new Error(`${r} expects a positive number, got "${a}"`);return l};if(r==="--repo")t.repo=ke(s());else if(r==="--out"){let a=s();t.out=a==="-"?"-":ke(a)}else if(r==="--project-root")t.projectRoot=s();else if(r==="--include")t.include.push(s());else if(r==="--exclude")t.exclude.push(s());else if(r==="--scope")t.scope=s();else if(r==="--no-gitignore")t.gitignore=!1;else if(r==="--ignore-dir")t.ignoreDirs.push(s());else if(r==="--max-files")t.maxFiles=o();else if(r==="--max-bytes")t.maxBytes=o();else if(r==="--max-calls")t.maxCalls=o();else if(r==="--ignore-case")t.ignoreCase=!0;else if(r==="--max-hits")t.maxHits=o();else if(r==="--budget-tokens")t.budgetTokens=o();else if(r==="--min-files")t.minFiles=o();else if(r==="--min-count")t.minCount=o();else if(r==="--include-tests")t.includeTests=!0;else if(r==="--no-ast")t.noAst=!0;else if(r==="--index")t.indexDir=s();else if(r==="--no-index-cache")t.noIndexCache=!0;else if(r==="--workers"){let a=s(),l=Number(a);if(!Number.isInteger(l)||l<0)throw new Error(`--workers expects a non-negative integer, got "${a}"`);t.workers=l}else if(r==="--since")t.since=s();else if(r==="--config")t.config=ke(s());else if(r==="--limit")t.limit=o();else if(r==="--no-fuzzy")t.fuzzy=!1;else if(r==="--exact")t.exact=!0;else if(r==="--explain")t.explain=!0;else if(r==="--semantic")t.semantic=!0;else if(r==="--recall")t.recall=!0;else if(r==="--run")t.run=!0;else if(r==="--probe")t.probe=!0;else if(r==="--base")t.base=s();else if(r==="--staged")t.staged=!0;else if(r==="--depth")t.depth=o();else if(r==="--kind")t.kind=s();else if(r==="--rank"){let a=s();if(a!=="graph"&&a!=="lexical")throw new Error(`--rank expects graph|lexical, got "${a}"`);t.rank=a}else if(r==="--direction"){let a=s();if(a!=="out"&&a!=="in"&&a!=="both")throw new Error(`--direction expects out|in|both, got "${a}"`);t.direction=a}else if(r==="--json")t.json=!0;else if(!r.startsWith("--")&&t.positional===void 0)t.positional=r;else throw new Error(`unknown flag: ${r}`)}return t}function oe(e,t){t?Me(t,e):R.stdout.write(e)}function Pn(e,t){return{include:e.include.length?e.include:void 0,exclude:e.exclude.length?e.exclude:void 0,scope:e.scope,gitignore:e.gitignore,ignoreDirs:e.ignoreDirs.length?e.ignoreDirs:void 0,maxFiles:e.maxFiles,maxBytes:e.maxBytes,maxCallsPerFile:e.maxCalls,precomputedWalk:t}}var ab=new Set(["grep","churn","coupling","workspaces","grammars"]);function lb(e){let t,n,r,s,o=!1;for(let a=0;a");return{defaultRepo:t,serverInfo:n?{name:n}:void 0,maxResponseBytes:r,profile:s,watch:o}}var cb=new Set(["--repo","--out","--project-root","--include","--exclude","--scope","--ignore-dir","--max-files","--max-bytes","--max-calls","--max-hits","--budget-tokens","--min-files","--min-count","--since","--config","--limit","--server-name","--tools","--workers","--index","--max-response-bytes","--base","--depth","--kind","--rank","--direction"]);function db(e){let t=[],n=0;for(;n=e.length?e:[e[n],...t,...e.slice(n+1)]}async function ub(e){let t=db(e),[n,...r]=t;if(!n||n==="help"||n==="--help"||n==="-h"){R.stdout.write(ef);return}if(n==="version"||n==="--version"){R.stdout.write(fe+` +`);return}if(n==="rewrite"){let{rewriteCommand:_}=await Promise.resolve().then(()=>(Qa(),Qu)),k=_(r.join(" "));if(!k){R.exitCode=1;return}R.stdout.write(k+` +`);return}if(n==="mcp"){let{runMcpServer:_}=await Promise.resolve().then(()=>(Ya(),Xu));await _(lb(r));return}let s=ob(r);if(!H(s.repo))throw new Error(`--repo path does not exist: ${s.repo}`);if(!ve(s.repo).isDirectory())throw new Error(`--repo path is not a directory: ${s.repo}`);let o=!ab.has(n)&&!(n==="embed"&&s.positional!=="build"),a;o&&!s.noAst&&(a=Pe(s.repo,{maxFileBytes:s.maxBytes,maxFiles:s.maxFiles,gitignore:s.gitignore,ignoreDirs:s.ignoreDirs.length?s.ignoreDirs:void 0}));let l=!1,c=async()=>{l||s.noAst||!a||(await et(wt(a.files.map(_=>_.ext))),l=!0)},d=s.indexDir??ft,f=!1,u,m,p=async()=>{if(u)return u;if(f)return m;if(f=!0,!s.noIndexCache)return u=Ps(s.repo,{...Pn(s,a),workers:s.workers},c,d).then(_=>(_&&(m={scan:_.scan,arts:_.arts,loadArtifacts:_.loadArtifacts}),m)),u},g,y=async()=>{let _=(await p())?.scan;return _||(g??=c().then(()=>ut(s.repo,{...Pn(s,a),workers:s.workers})))},h,S=async()=>{let _=await p();return _?.arts?_.arts:_?_.arts??=_.loadArtifacts?.()??vt(_.scan,Pn(s,a)):h??=y().then(k=>vt(k,Pn(s,a)))};if(n==="index"){if(!s.out)throw new Error("index needs --out ");let _=s.out;_t(_,{recursive:!0});let k=I(_,"cache.json"),b,w={};try{let B=JSON.parse(Q(k,"utf8"));B.schemaVersion===5&&B.extractorVersion===14&&(b=new Map(Object.entries(B.files)),w={engineVersion:B.engineVersion,commit:B.commit,graphSha1:B.graphSha1,symbolsSha1:B.symbolsSha1,embed:B.embed})}catch{}await c();let v=await ut(s.repo,{...Pn(s,a),cache:b,out:_,workers:s.workers}),A=Rt(s.repo),F=A?Wt(A):void 0,T=I(_,"graph.json"),U=I(_,"symbols.json"),te=I(_,"embeddings.bin"),V=B=>{try{return Ce(Q(B))}catch{return}},z=B=>{let se={};for(let J of v.files){let ne={hash:J.hash,record:J,size:J.size},be=v.mtimes.get(J.rel);be!==void 0&&(ne.mtimeMs=be),se[J.rel]=ne}Me(k,JSON.stringify({schemaVersion:5,extractorVersion:14,engineVersion:fe,commit:v.commit,graphSha1:B.graphSha1,symbolsSha1:B.symbolsSha1,embed:B.embed,files:se})+` +`)},P=!F||w.embed!==void 0&&w.embed.embedVersion===it&&w.embed.modelId===F.modelId&&w.embed.sha1!==void 0&&V(te)===w.embed.sha1;if(v.contentUnchanged&&w.engineVersion===fe&&w.commit===v.commit&&w.graphSha1!==void 0&&V(T)===w.graphSha1&&w.symbolsSha1!==void 0&&V(U)===w.symbolsSha1&&P)v.cacheDirty&&z(w),R.stderr.write(`codeindex: ${v.files.length} files \u2192 ${_}/graph.json + symbols.json${v.capped?" (capped)":""} (unchanged \u2014 artifacts reused) +`);else{let{graph:B,symbols:se}=vt(v),J=In(B),ne=Us(se);Me(T,J),Me(U,ne);let be="",Ie;if(F){let X=an(v,F),Z=ci(X);Me(te,Z),Ie={embedVersion:it,modelId:F.modelId,sha1:Ce(Z)},be=` + embeddings.bin (${X.records.length} records, model ${F.modelId})`}z({graphSha1:Ce(J),symbolsSha1:Ce(ne),embed:Ie}),R.stderr.write(`codeindex: ${v.files.length} files \u2192 ${_}/graph.json + symbols.json${be}${v.capped?" (capped)":""} +`)}}else if(n==="scan"){let _=sr(s.repo,Pn(s,a)),k={engineVersion:fe,commit:_.commit,fileCount:_.fileCount,languages:_.languages,capped:_.capped};oe(JSON.stringify(k,null,2)+` +`,s.out)}else if(n==="graph"){let{graph:_}=await S();oe(In(_),s.out)}else if(n==="symbols"){let{symbols:_}=await S();oe(Us(_),s.out)}else if(n==="scip"){let _=await y(),k=Sa(_,{projectRoot:s.projectRoot}),b=s.out??ke("index.scip");b==="-"?R.stdout.write(N.from(k)):(Me(b,k),R.stderr.write(`codeindex: SCIP index \u2192 ${b} (${k.length} bytes) +`))}else if(n==="callers"){let _=await y(),k=Yt(_,void 0,{recall:s.recall}),b={};for(let[w,v]of k)b[w]=v;oe(JSON.stringify(b,null,2)+` +`,s.out)}else if(n==="hierarchy"){let _=await y(),k=En(_,fr(_));if(s.positional){let b=k.get(s.positional);if(!b)throw new Error(`no type named ${s.positional}`);oe(JSON.stringify(b,null,2)+` +`,s.out)}else{let b={};for(let[w,v]of k)b[w]=v;oe(JSON.stringify(b,null,2)+` +`,s.out)}}else if(n==="implementations"){if(!s.positional)throw new Error("implementations needs a type name: cli.mjs implementations --repo ");let _=await y(),k=En(_,fr(_));if(!k.has(s.positional))throw new Error(`no type named ${s.positional}`);oe(JSON.stringify({name:s.positional,implementations:dr(k,s.positional)},null,2)+` +`,s.out)}else if(n==="callgraph"){if(!s.positional)throw new Error("callgraph needs a symbol: cli.mjs callgraph --repo ");let _=await y(),k=mr(_,fr(_)),b=pr(k,s.positional,{...s.depth!==void 0?{depth:s.depth}:{},...s.direction?{direction:s.direction}:{}});if(!b.root.length)throw new Error(`no symbol named ${s.positional}`);oe(JSON.stringify(b,null,2)+` +`,s.out)}else if(n==="search"){if(!s.positional)throw new Error('search needs a query: cli.mjs search "" --repo ');let _=await y(),k={limit:s.limit,fuzzy:s.fuzzy,...s.exact?{exact:!0}:{},...s.rank?{rank:s.rank}:{}},b=()=>{let{explain:w}=nn(_,s.positional,k);w.note&&R.stderr.write(`codeindex: ${w.note} +`)};if(s.semantic){let w=Ut(),v=()=>{let A=Dt(_,s.positional,k);oe(JSON.stringify(A,null,2)+` +`,s.out)};if(w)try{let A=await Fr(_),F=await Nr(s.positional),T=ln(_,s.positional,A,{queryVec:F,limit:s.limit,fuzzy:s.fuzzy});oe(JSON.stringify(T,null,2)+` +`,s.out)}catch(A){R.stderr.write(`codeindex: embedding endpoint ${w} unavailable (${A instanceof Error?A.message:A}) \u2014 returning lexical results +`),v()}else{let A=Rt(s.repo),F=A?Wt(A):void 0;if(!F)R.stderr.write("codeindex: semantic search unavailable (no embedding model or endpoint) \u2014 returning lexical results; run `codeindex embed pull` or set CODEINDEX_EMBED_ENDPOINT to enable it\n"),v();else{let T=an(_,F),U=ln(_,s.positional,T,{model:F,limit:s.limit,fuzzy:s.fuzzy});oe(JSON.stringify(U,null,2)+` +`,s.out)}}b()}else{let{results:w,explain:v}=nn(_,s.positional,k);oe(JSON.stringify(s.explain?{results:w,explain:v}:w,null,2)+` `,s.out),v.note&&R.stderr.write(`codeindex: ${v.note} -`)}}else if(n==="embed"){let _=s.positional,E=vt(s.repo);if(_==="status"){let b=E?Wt(E):void 0,x=Ut(),A={embedVersion:it,mode:x?"endpoint":b?"static":"none",model:b?{present:!0,dir:E,modelId:b.modelId,dim:b.dim,vocabSize:b.vocabSize}:{present:!1},endpoint:x??null};x&&(A.endpointReachable=await Ar(x)),ie(JSON.stringify(A,null,2)+` -`,s.out)}else if(_==="serve"){let b=["run","-d","-p","8756:8756","ghcr.io/maxgfr/codeindex-embed:latest"],x=`docker ${b.join(" ")}`;if(!at("docker")){R.stderr.write(`codeindex: docker not found on PATH. Install Docker, then run: - `+x+` -`),R.exitCode=1;return}if(s.run){R.stderr.write(`codeindex: starting embedding server \u2192 ${x} +`)}}else if(n==="embed"){let _=s.positional,k=Rt(s.repo);if(_==="status"){let b=k?Wt(k):void 0,w=Ut(),A={embedVersion:it,mode:w?"endpoint":b?"static":"none",model:b?{present:!0,dir:k,modelId:b.modelId,dim:b.dim,vocabSize:b.vocabSize}:{present:!1},endpoint:w??null};w&&(A.endpointReachable=await Ir(w)),oe(JSON.stringify(A,null,2)+` +`,s.out)}else if(_==="serve"){let b=["run","-d","-p","8756:8756","ghcr.io/maxgfr/codeindex-embed:latest"],w=`docker ${b.join(" ")}`;if(!at("docker")){R.stderr.write(`codeindex: docker not found on PATH. Install Docker, then run: + `+w+` +`),R.exitCode=1;return}if(s.run){R.stderr.write(`codeindex: starting embedding server \u2192 ${w} `);let v=pe("docker",b);if(v.stdout.trim()&&R.stdout.write(v.stdout.trim()+` `),!v.ok){R.stderr.write(v.stderr||`codeindex: docker run failed `),R.exitCode=1;return}R.stderr.write(`codeindex: server starting on http://localhost:8756 \u2014 then: CODEINDEX_EMBED_ENDPOINT=http://localhost:8756 codeindex search "" --repo . --semantic -`)}else R.stdout.write(x+` -`),R.stderr.write('codeindex: run the line above to start the embedding server (or `embed serve --run`), then:\n CODEINDEX_EMBED_ENDPOINT=http://localhost:8756 codeindex search "" --repo . --semantic\n')}else if(_==="build"){if(!s.out)throw new Error("embed build needs --out ");if(!E){R.stderr.write("codeindex: no embedding model present \u2014 run `codeindex embed pull` first (nothing written)\n"),R.exitCode=1;return}let b=Wt(E);gt(s.out,{recursive:!0});let x=await y(),v=on(x,b);Re(I(s.out,"embeddings.bin"),oi(v)),R.stderr.write(`codeindex: ${v.records.length} embedding records \u2192 ${s.out}/embeddings.bin (model ${b.modelId}) -`)}else if(_==="pull"){let{url:b,sha256:x}=wa(),v=R.env.CODEINDEX_EMBED_DIR??I(s.repo,".codeindex","models");gt(v,{recursive:!0}),R.stderr.write(`codeindex: fetching model from ${b} \u2192 ${I(v,"model.json")} -`);let A;try{A=await Xd(b,x)}catch(O){R.stderr.write(`codeindex: pull failed \u2014 ${O instanceof Error?O.message:String(O)} (nothing written) -`),R.exitCode=1;return}try{ba(JSON.parse(A),b)}catch(O){R.stderr.write(`codeindex: pull failed \u2014 response is not a valid model.json (${O instanceof Error?O.message:String(O)}) (nothing written) -`),R.exitCode=1;return}Re(I(v,"model.json"),A),R.stderr.write(`codeindex: model written to ${I(v,"model.json")} -`)}else throw new Error("embed needs a subcommand: status | build | pull | serve")}else if(n==="lsp"){if(s.positional!=="status")throw new Error("lsp needs a subcommand: status");ie(JSON.stringify(await Pr(await y(),s.repo,s.probe===!0),null,2)+` -`,s.out)}else if(n==="grammars"){let _=s.positional,E=wn();if(_==="status"){let b=Qe(),x=V=>b.dirs.some(z=>H(I(z,V))),v=x("web-tree-sitter.wasm"),A=Fs(),O=V=>[...V].filter(z=>x(`${z}.wasm`)).sort(),N=O(Xn),U=O(Zn),le={engineVersion:fe,tier:b.tier,dir:b.dir??null,dirs:b.dirs,cacheDir:E,runtimePresent:v,pullNeeded:!v,core:{resolved:N.length,of:Xn.size,missing:[...Xn].filter(V=>!N.includes(V)).sort()},extended:{resolved:U.length,of:Zn.size,missing:[...Zn].filter(V=>!U.includes(V)).sort()},url:A.url};ie(JSON.stringify(le,null,2)+` -`,s.out)}else if(_==="pull"){let b=await ir(E,{onNote:x=>R.stderr.write(x)});R.stderr.write(b.message),b.ok||(R.exitCode=1)}else throw new Error("grammars needs a subcommand: status | pull")}else if(n==="rules"){if(!s.config)throw new Error("rules needs --config ");let _=$r(JSON.parse(te(s.config,"utf8"))),{graph:E}=await S(),b=Lr(E,_),x=b.filter(v=>v.severity==="error").length;ie(JSON.stringify({errors:x,warnings:b.length-x,violations:b},null,2)+` -`,s.out),x>0&&(R.exitCode=1)}else if(n==="workspaces"){let _=nn(s.repo);ie(JSON.stringify({packages:_.packages,cycle:_.cycle??null,topoOrder:_.topoOrder},null,2)+` -`,s.out)}else if(n==="churn"){let{churn:_,ok:E}=Ze(s.repo,{since:s.since}),b={};for(let x of[..._.keys()].sort())b[x]=_.get(x);ie(JSON.stringify({ok:E,churn:b},null,2)+` -`,s.out)}else if(n==="repomap"){let{scan:_,graph:E}=await S();ie(ln(_,E,{budgetTokens:s.budgetTokens}),s.out)}else if(n==="hotspots"){let _=await y(),{churn:E,ok:b}=Ze(s.repo,{since:s.since});ie(JSON.stringify({churnOk:b,hotspots:cn(_,E)},null,2)+` -`,s.out)}else if(n==="coupling"){let{ok:_,couplings:E}=Or(s.repo,{since:s.since});ie(JSON.stringify({ok:_,couplings:E},null,2)+` -`,s.out)}else if(n==="deadcode")ie(JSON.stringify(Dr(await y()),null,2)+` -`,s.out);else if(n==="literals"){let _=rn(await y(),{minFiles:s.minFiles,minCount:s.minCount,includeTests:s.includeTests});ie(JSON.stringify(_,null,2)+` -`,s.out)}else if(n==="complexity"){let _=await y();ie(JSON.stringify(_r(_,s.positional),null,2)+` -`,s.out)}else if(n==="risk"){let _=await y(),{churn:E,ok:b}=Ze(s.repo,{since:s.since});ie(JSON.stringify({churnOk:b,risks:hr(_,E)},null,2)+` -`,s.out)}else if(n==="delta"){let{graph:_,symbols:E}=await S(),b=Wa(s.repo,_,E,{base:s.base,staged:s.staged,depth:s.depth});if("error"in b)throw new Error(b.error);ie(s.json?JSON.stringify(b,null,2)+` -`:Ua(b),s.out)}else if(n==="impact"){if(!s.positional)throw new Error("impact needs a target: cli.mjs impact --repo ");let{graph:_}=await S(),E=Wr(_,s.positional,s.depth??1/0);if(!E)throw new Error(`no such file or module in the index: ${s.positional}`);ie(JSON.stringify(E,null,2)+` -`,s.out)}else if(n==="neighbors"){if(!s.positional)throw new Error("neighbors needs a target: cli.mjs neighbors --repo ");let{graph:_}=await S(),E=s.kind?new Set(s.kind.split(",").map(x=>x.trim()).filter(Boolean)):void 0,b=Da(_,s.positional,s.depth??1,E);if(!b)throw new Error(`no such file or module in the index: ${s.positional}`);ie(JSON.stringify(b,null,2)+` -`,s.out)}else if(n==="mermaid"){let{graph:_}=await S();ie(jr(_,{module:s.positional}),s.out)}else if(n==="grep"){if(!s.positional)throw new Error("grep needs a pattern: cli.mjs grep --repo ");let E=[...s.scope?[`${s.scope.replace(/\/+$/,"")}/**`]:[],...s.include,...s.exclude.map(x=>`!${x}`)],b=Er(s.repo,s.positional,{globs:E.length?E:void 0,ignoreCase:s.ignoreCase,maxHits:s.maxHits});ie(JSON.stringify(b,null,2)+` +`)}else R.stdout.write(w+` +`),R.stderr.write('codeindex: run the line above to start the embedding server (or `embed serve --run`), then:\n CODEINDEX_EMBED_ENDPOINT=http://localhost:8756 codeindex search "" --repo . --semantic\n')}else if(_==="build"){if(!s.out)throw new Error("embed build needs --out ");if(!k){R.stderr.write("codeindex: no embedding model present \u2014 run `codeindex embed pull` first (nothing written)\n"),R.exitCode=1;return}let b=Wt(k);_t(s.out,{recursive:!0});let w=await y(),v=an(w,b);Me(I(s.out,"embeddings.bin"),ci(v)),R.stderr.write(`codeindex: ${v.records.length} embedding records \u2192 ${s.out}/embeddings.bin (model ${b.modelId}) +`)}else if(_==="pull"){let{url:b,sha256:w}=Ea(),v=R.env.CODEINDEX_EMBED_DIR??I(s.repo,".codeindex","models");_t(v,{recursive:!0}),R.stderr.write(`codeindex: fetching model from ${b} \u2192 ${I(v,"model.json")} +`);let A;try{A=await lu(b,w)}catch(F){R.stderr.write(`codeindex: pull failed \u2014 ${F instanceof Error?F.message:String(F)} (nothing written) +`),R.exitCode=1;return}try{ka(JSON.parse(A),b)}catch(F){R.stderr.write(`codeindex: pull failed \u2014 response is not a valid model.json (${F instanceof Error?F.message:String(F)}) (nothing written) +`),R.exitCode=1;return}Me(I(v,"model.json"),A),R.stderr.write(`codeindex: model written to ${I(v,"model.json")} +`)}else throw new Error("embed needs a subcommand: status | build | pull | serve")}else if(n==="lsp"){if(s.positional!=="status")throw new Error("lsp needs a subcommand: status");oe(JSON.stringify(await Dr(await y(),s.repo,s.probe===!0),null,2)+` +`,s.out)}else if(n==="grammars"){let _=s.positional,k=xn();if(_==="status"){let b=Qe(),w=V=>b.dirs.some(z=>H(I(z,V))),v=w("web-tree-sitter.wasm"),A=$s(),F=V=>[...V].filter(z=>w(`${z}.wasm`)).sort(),T=F(Zn),U=F(Yn),te={engineVersion:fe,tier:b.tier,dir:b.dir??null,dirs:b.dirs,cacheDir:k,runtimePresent:v,pullNeeded:!v,core:{resolved:T.length,of:Zn.size,missing:[...Zn].filter(V=>!T.includes(V)).sort()},extended:{resolved:U.length,of:Yn.size,missing:[...Yn].filter(V=>!U.includes(V)).sort()},url:A.url};oe(JSON.stringify(te,null,2)+` +`,s.out)}else if(_==="pull"){let b=await ar(k,{onNote:w=>R.stderr.write(w)});R.stderr.write(b.message),b.ok||(R.exitCode=1)}else throw new Error("grammars needs a subcommand: status | pull")}else if(n==="rules"){if(!s.config)throw new Error("rules needs --config ");let _=Lr(JSON.parse(Q(s.config,"utf8"))),{graph:k}=await S(),b=jr(k,_),w=b.filter(v=>v.severity==="error").length;oe(JSON.stringify({errors:w,warnings:b.length-w,violations:b},null,2)+` +`,s.out),w>0&&(R.exitCode=1)}else if(n==="workspaces"){let _=rn(s.repo);oe(JSON.stringify({packages:_.packages,cycle:_.cycle??null,topoOrder:_.topoOrder},null,2)+` +`,s.out)}else if(n==="churn"){let{churn:_,ok:k}=Ze(s.repo,{since:s.since}),b={};for(let w of[..._.keys()].sort())b[w]=_.get(w);oe(JSON.stringify({ok:k,churn:b},null,2)+` +`,s.out)}else if(n==="repomap"){let{scan:_,graph:k}=await S();oe(cn(_,k,{budgetTokens:s.budgetTokens}),s.out)}else if(n==="hotspots"){let _=await y(),{churn:k,ok:b}=Ze(s.repo,{since:s.since});oe(JSON.stringify({churnOk:b,hotspots:dn(_,k)},null,2)+` +`,s.out)}else if(n==="coupling"){let{ok:_,couplings:k}=Pr(s.repo,{since:s.since});oe(JSON.stringify({ok:_,couplings:k},null,2)+` +`,s.out)}else if(n==="deadcode")oe(JSON.stringify(Wr(await y()),null,2)+` +`,s.out);else if(n==="literals"){let _=sn(await y(),{minFiles:s.minFiles,minCount:s.minCount,includeTests:s.includeTests});oe(JSON.stringify(_,null,2)+` +`,s.out)}else if(n==="complexity"){let _=await y();oe(JSON.stringify(yr(_,s.positional),null,2)+` +`,s.out)}else if(n==="risk"){let _=await y(),{churn:k,ok:b}=Ze(s.repo,{since:s.since});oe(JSON.stringify({churnOk:b,risks:br(_,k)},null,2)+` +`,s.out)}else if(n==="delta"){let{graph:_,symbols:k}=await S(),b=Ha(s.repo,_,k,{base:s.base,staged:s.staged,depth:s.depth});if("error"in b)throw new Error(b.error);oe(s.json?JSON.stringify(b,null,2)+` +`:Ga(b),s.out)}else if(n==="impact"){if(!s.positional)throw new Error("impact needs a target: cli.mjs impact --repo ");let{graph:_}=await S(),k=Br(_,s.positional,s.depth??1/0);if(!k)throw new Error(`no such file or module in the index: ${s.positional}`);oe(JSON.stringify(k,null,2)+` +`,s.out)}else if(n==="neighbors"){if(!s.positional)throw new Error("neighbors needs a target: cli.mjs neighbors --repo ");let{graph:_}=await S(),k=s.kind?new Set(s.kind.split(",").map(w=>w.trim()).filter(Boolean)):void 0,b=Ba(_,s.positional,s.depth??1,k);if(!b)throw new Error(`no such file or module in the index: ${s.positional}`);oe(JSON.stringify(b,null,2)+` +`,s.out)}else if(n==="mermaid"){let{graph:_}=await S();oe(Ur(_,{module:s.positional}),s.out)}else if(n==="grep"){if(!s.positional)throw new Error("grep needs a pattern: cli.mjs grep --repo ");let k=[...s.scope?[`${s.scope.replace(/\/+$/,"")}/**`]:[],...s.include,...s.exclude.map(w=>`!${w}`)],b=Rr(s.repo,s.positional,{globs:k.length?k:void 0,ignoreCase:s.ignoreCase,maxHits:s.maxHits});oe(JSON.stringify(b,null,2)+` `,s.out)}else R.stderr.write(`unknown command: ${n} -${Wu}`),R.exitCode=2}xe();k();xe();nt();var Xa="/grammars",Za="web-tree-sitter.wasm";function Uu(e){zu(Za,e)}function Bu(e,t){zu(`${e}.wasm`,t)}function zu(e,t){ts(`${Xa}/${e}`,t),R.env.CODEINDEX_GRAMMAR_DIR=Xa}function Hu(e){return`${e}.wasm`}async function Wy(e,t){let n=bt(e);if(!n.length)return{tier:"regex",loaded:[],failed:[],note:"no language here ships a tree-sitter grammar"};try{Uu(await t(Za))}catch(o){return{tier:"regex",loaded:[],failed:[...n],note:`tree-sitter runtime unavailable (${o.message})`}}await Promise.all(n.map(async o=>{try{Bu(o,await t(Hu(o)))}catch{}})),await et(n);let r=n.filter(o=>tt(o)).sort(),s=n.filter(o=>!tt(o)).sort();return{tier:r.length?"ast":"regex",loaded:r,failed:s,note:s.length?`${s.join(", ")} could not load; those languages use the regex tier`:""}}export{Xn as CORE_GRAMMARS,ja as DEFAULT_DELTA_DEPTH,Lo as DEFAULT_GRAMMARS_URL,cf as DEFAULT_MAX_FILES,it as EMBED_VERSION,fe as ENGINE_VERSION,Zn as EXTENDED_GRAMMARS,mn as EXTRACTOR_VERSION,Es as EXT_GRAMMAR,Xa as GRAMMARS_DIR,ut as INDEX_DIR,ui as LspTimeout,Zi as MARKDOWN_EXT,au as MAX_FRAME_BYTES,Rt as RISK_WEIGHTS,Za as RUNTIME_WASM,He as SCHEMA_VERSION,Ia as agreementOf,go as allGrammarKeys,Ko as applyCentrality,Zd as basicTokenize,wd as betweennessOf,Et as buildArtifactsFromScan,Zt as buildCallerIndex,Ts as buildCodeRecord,on as buildEmbeddingIndex,Ir as buildEndpointIndex,ta as buildGraph,Dh as buildIndexArtifacts,Ho as buildModules,Sg as buildRawCallerIndex,Bo as buildResolveContext,ur as buildSymbolGraph,Jo as buildSymbolIndex,kn as buildTypeHierarchy,Yi as byKey,M as byStr,Op as categorize,Or as changeCoupling,df as changedSince,Lr as checkRules,zn as classify,sf as clip,of as clipInline,_u as columnOfSymbol,M_ as communityOf,yt as compileGlobs,Gs as complexityOfSource,Ru as computeDelta,dr as computeImportPairs,Qs as computeSurprises,Vo as computeSymbolRefs,pr as computeTestMap,va as createFramer,ua as deleteMemory,Wa as deltaFor,Kh as deserializeEmbeddings,ga as detectCommunities,nn as detectWorkspaces,qi as diffFiles,Gi as diffHunks,nu as embedEndpointUrl,Sa as embedViaEndpoint,ii as embeddingUnits,xg as enclosingSymbol,Mr as encode,ci as encodeMessage,Tr as encodeQueryViaEndpoint,et as ensureGrammars,Ge as escapeRegExp,tn as explainQuery,Vt as extToLang,Eo as extractAst,Co as extractCode,rd as extractGrammarsTarball,Kc as extractInParallel,Qi as extractMarkdown,Ki as extractSymbols,Pp as extractTags,nd as extractTarInto,td as fetchExpectedSha256,Qc as fetchGrammarsTarball,dn as fileUri,Dr as findDeadCode,rn as findLiteralDuplications,sa as findReferences,An as findSymbol,_t as foldText,Ua as formatDeltaPanel,Ze as gitChurn,Yn as grammarKeyForExt,bt as grammarKeysForExts,tt as grammarReady,Hu as grammarWasmName,Er as grepRepo,qh as hasEmbedModel,Qu as hasFileBytes,at as have,as as headCommit,ru as healthzUrl,ku as hubThreshold,Wr as impactOf,lr as implementationsOf,oa as insertAfterSymbol,aa as insertBeforeSymbol,xa as intDot,Ql as isCode,Yl as isDoc,zi as isGitWorktree,is as isIgnored,z_ as isSurprising,Ls as isTestFile,$t as isTestPath,Io as keptCodeFiles,rs as keywords,Xi as languageOf,fa as listMemories,Wt as loadEmbedModel,Wy as loadGrammars,mi as loadLspConfig,di as locationsToRefs,Pr as lspStatus,Bt as lspUnavailable,ol as mountFiles,Bu as mountGrammar,Uu as mountRuntime,fr as neighborhood,Da as neighborsOf,ka as onboardBrief,Ma as openLspSession,gr as pagerankOf,Di as parseGitignore,uu as parseLspConfig,$r as parseRules,Fo as preloadArtifacts,Po as preloadSession,Ar as probeEndpoint,ef as pruneUnfetched,ir as pullGrammars,Rr as quantize,cn as rankHotspots,af as rankedKeywords,da as readMemory,Oo as readPersistedIndex,G as readText,Pa as referencesWithLsp,lu as relFromUri,In as renderGraphJson,jr as renderMermaid,yy as renderMermaidClustered,ln as renderRepoMap,ya as renderScip,js as renderSymbolsJson,ia as replaceSymbolBody,Yu as resetVfs,tf as residentBytes,Hi as resolveBaseRef,qo as resolveCallEdges,zo as resolveDocLink,Ut as resolveEmbedEndpoint,vt as resolveEmbedModelDir,wa as resolveEmbedPullUrl,Sm as resolveGrammarsDir,Fs as resolveGrammarsPullTarget,Qe as resolveGrammarsTier,or as resolveImport,fi as resolveLspConfigPath,Go as resolveRelationEdges,ar as resolveRelations,Xs as resolveUniqueSymbol,Eu as reverseClosure,Du as rewriteCommand,hr as riskHotspots,eu as roundHalfToEven,$i as rrf,jy as runCli,Sp as runExtractWorker,Pu as runMcpServer,Pe as scanRepo,Pt as scanRepoParallel,rr as scanSummary,Lt as searchIndex,an as searchSemantic,oi as serializeEmbeddings,Aa as serverForLang,ts as setFileBytes,pe as sh,Me as sha1,wn as sharedGrammarsCacheDir,yf as shortHash,Pi as slugify,Oa as spawnLspTransport,ht as subtokens,_r as symbolComplexity,en as symbolId,vu as symbolsInHunks,ra as symbolsOverview,Fp as tagsQueryStatus,Ag as testsForModule,od as tierForPath,De as toCacheMap,Qd as tokenize,wg as typeEntry,Qo as uniqueSymbolDefs,Tg as untestedModules,ls as untrackedFiles,Fe as walk,jp as warmGrammars,Yd as wordpiece,Jc as workerCount,br as writeMemory}; +${ef}`),R.exitCode=2}xe();E();xe();nt();var el="/grammars",tl="web-tree-sitter.wasm";function tf(e){rf(tl,e)}function nf(e,t){rf(`${e}.wasm`,t)}function rf(e,t){rs(`${el}/${e}`,t),R.env.CODEINDEX_GRAMMAR_DIR=el}function sf(e){return`${e}.wasm`}async function fb(e,t){let n=wt(e);if(!n.length)return{tier:"regex",loaded:[],failed:[],note:"no language here ships a tree-sitter grammar"};try{tf(await t(tl))}catch(o){return{tier:"regex",loaded:[],failed:[...n],note:`tree-sitter runtime unavailable (${o.message})`}}await Promise.all(n.map(async o=>{try{nf(o,await t(sf(o)))}catch{}})),await et(n);let r=n.filter(o=>tt(o)).sort(),s=n.filter(o=>!tt(o)).sort();return{tier:r.length?"ast":"regex",loaded:r,failed:s,note:s.length?`${s.join(", ")} could not load; those languages use the regex tier`:""}}export{Zn as CORE_GRAMMARS,za as DEFAULT_DELTA_DEPTH,Uo as DEFAULT_GRAMMARS_URL,Ef as DEFAULT_MAX_FILES,it as EMBED_VERSION,fe as ENGINE_VERSION,Yn as EXTENDED_GRAMMARS,pn as EXTRACTOR_VERSION,Ms as EXT_GRAMMAR,el as GRAMMARS_DIR,ft as INDEX_DIR,pi as LspTimeout,eo as MARKDOWN_EXT,bu as MAX_FRAME_BYTES,Mt as RISK_WEIGHTS,tl as RUNTIME_WASM,He as SCHEMA_VERSION,Pa as agreementOf,yo as allGrammarKeys,Qo as applyCentrality,cu as basicTokenize,Id as betweennessOf,vt as buildArtifactsFromScan,Yt as buildCallerIndex,Fs as buildCodeRecord,an as buildEmbeddingIndex,Fr as buildEndpointIndex,ia as buildGraph,ly as buildIndexArtifacts,Jo as buildModules,Gg as buildRawCallerIndex,qo as buildResolveContext,mr as buildSymbolGraph,Yo as buildSymbolIndex,En as buildTypeHierarchy,to as byKey,M as byStr,ng as categorize,Pr as changeCoupling,vf as changedSince,jr as checkRules,Hn as classify,bf as clip,wf as clipInline,Cu as columnOfSymbol,X_ as communityOf,bt as compileGlobs,Ks as complexityOfSource,Wu as computeDelta,fr as computeImportPairs,ni as computeSurprises,Zo as computeSymbolRefs,_r as computeTestMap,Aa as createFramer,ga as deleteMemory,Ha as deltaFor,by as deserializeEmbeddings,ba as detectCommunities,rn as detectWorkspaces,Vi as diffFiles,Ji as diffHunks,pu as embedEndpointUrl,Ra as embedViaEndpoint,li as embeddingUnits,Hg as enclosingSymbol,Ar as encode,fi as encodeMessage,Nr as encodeQueryViaEndpoint,et as ensureGrammars,qe as escapeRegExp,nn as explainQuery,Vt as extToLang,Co as extractAst,No as extractCode,md as extractGrammarsTarball,id as extractInParallel,no as extractMarkdown,Yi as extractSymbols,sg as extractTags,fd as extractTarInto,ud as fetchExpectedSha256,cd as fetchGrammarsTarball,un as fileUri,Wr as findDeadCode,sn as findLiteralDuplications,la as findReferences,An as findSymbol,ht as foldText,Ga as formatDeltaPanel,Ze as gitChurn,Qn as grammarKeyForExt,wt as grammarKeysForExts,tt as grammarReady,sf as grammarWasmName,Rr as grepRepo,gy as hasEmbedModel,pf as hasFileBytes,at as have,ds as headCommit,gu as healthzUrl,Du as hubThreshold,Br as impactOf,dr as implementationsOf,da as insertAfterSymbol,ua as insertBeforeSymbol,va as intDot,ic as isCode,sc as isDoc,Gi as isGitWorktree,ls as isIgnored,fh as isSurprising,js as isTestFile,$t as isTestPath,Po as keptCodeFiles,is as keywords,Qi as languageOf,_a as listMemories,Wt as loadEmbedModel,fb as loadGrammars,_i as loadLspConfig,mi as locationsToRefs,Dr as lspStatus,Bt as lspUnavailable,dl as mountFiles,nf as mountGrammar,tf as mountRuntime,pr as neighborhood,Ba as neighborsOf,Ma as onboardBrief,Ia as openLspSession,hr as pagerankOf,as as parseGitignore,ku as parseLspConfig,Lr as parseRules,Lo as preloadArtifacts,jo as preloadSession,Ir as probeEndpoint,gf as pruneUnfetched,ar as pullGrammars,Cr as quantize,dn as rankHotspots,xf as rankedKeywords,pa as readMemory,Do as readPersistedIndex,q as readText,ja as referencesWithLsp,wu as relFromUri,In as renderGraphJson,Ur as renderMermaid,By as renderMermaidClustered,cn as renderRepoMap,Sa as renderScip,Us as renderSymbolsJson,ca as replaceSymbolBody,mf as resetVfs,_f as residentBytes,qi as resolveBaseRef,Ko as resolveCallEdges,Vo as resolveDocLink,Ut as resolveEmbedEndpoint,Rt as resolveEmbedModelDir,Ea as resolveEmbedPullUrl,Um as resolveGrammarsDir,$s as resolveGrammarsPullTarget,Qe as resolveGrammarsTier,lr as resolveImport,gi as resolveLspConfigPath,Xo as resolveRelationEdges,cr as resolveRelations,Qs as resolveUniqueSymbol,Lu as reverseClosure,Yu as rewriteCommand,br as riskHotspots,fu as roundHalfToEven,ji as rrf,ub as runCli,zp as runExtractWorker,Ku as runMcpServer,Le as scanRepo,ut as scanRepoParallel,sr as scanSummary,Dt as searchIndex,ln as searchSemantic,ci as serializeEmbeddings,Fa as serverForLang,rs as setFileBytes,pe as sh,Ce as sha1,xn as sharedGrammarsCacheDir,Ff as shortHash,Li as slugify,Da as spawnLspTransport,yt as subtokens,yr as symbolComplexity,tn as symbolId,ju as symbolsInHunks,aa as symbolsOverview,rg as tagsQueryStatus,Yg as testsForModule,hd as tierForPath,je as toCacheMap,uu as tokenize,zg as typeEntry,ra as uniqueSymbolDefs,Qg as untestedModules,us as untrackedFiles,Pe as walk,lg as warmGrammars,du as wordpiece,sd as workerCount,xr as writeMemory}; diff --git a/scripts/engine.d.mts b/scripts/engine.d.mts index c6d57f6..52c5b68 100644 --- a/scripts/engine.d.mts +++ b/scripts/engine.d.mts @@ -526,6 +526,8 @@ interface ResolveContext { }[]; csharpNamespaces: Map; warnings: string[]; + jsMemo?: Map; + dirFilesMemo?: Map; } declare function buildResolveContext(scan: RepoScan): ResolveContext; declare function resolveDocLink(fromRel: string, spec: string, ctx: ResolveContext): Resolution; diff --git a/scripts/engine.mjs b/scripts/engine.mjs index ddf0a35..b07ff94 100755 --- a/scripts/engine.mjs +++ b/scripts/engine.mjs @@ -353,10 +353,28 @@ var init_ignore = __esm({ }); // src/walk.ts -import { readdirSync, statSync, lstatSync, readFileSync, realpathSync } from "fs"; -import { join, sep, extname } from "path"; +import { readdirSync, statSync, lstatSync, readFileSync, realpathSync, existsSync } from "fs"; +import { join, resolve, sep, extname } from "path"; function isIgnoredDirectory(name2, ignoreDirs) { - return ignoreDirs.has(name2) || name2.startsWith(".codeindex-edit-"); + return name2 === GIT_ENTRY || ignoreDirs.has(name2) || name2.startsWith(".codeindex-edit-"); +} +function readInfoExclude(root, entries) { + const marker = entries.find((e) => e.name === GIT_ENTRY); + if (!marker) return ""; + let gitDir = join(root, GIT_ENTRY); + try { + if (!marker.isDirectory()) { + const m = /^gitdir:[ \t]*(.+?)[ \t]*$/m.exec(readFileSync(gitDir, "utf8")); + if (!m) return ""; + gitDir = resolve(root, m[1]); + const common = join(gitDir, "commondir"); + if (existsSync(common)) gitDir = resolve(gitDir, readFileSync(common, "utf8").trim()); + } + const exclude = join(gitDir, "info", "exclude"); + return existsSync(exclude) ? readText(exclude) : ""; + } catch { + return ""; + } } function walk(root, opts = {}) { const maxFileBytes = opts.maxFileBytes ?? 1024 * 1024; @@ -396,7 +414,15 @@ function walk(root, opts = {}) { } catch { continue; } + if (frame.rel && entries.some((e) => e.name === GIT_ENTRY)) { + excluded++; + continue; + } let rules = frame.rules; + if (useGitignore && !frame.rel) { + const parsed = parseGitignore(readInfoExclude(frame.dir, entries), ""); + if (parsed.length) rules = [...rules, ...parsed]; + } if (useGitignore && entries.some((e) => e.name === ".gitignore")) { const parsed = parseGitignore(readText(join(frame.dir, ".gitignore")), frame.rel); if (parsed.length) rules = [...rules, ...parsed]; @@ -406,6 +432,7 @@ function walk(root, opts = {}) { const abs = join(frame.dir, name2); const rel2 = frame.rel ? `${frame.rel}/${name2}` : name2; const isLink = entry.isSymbolicLink(); + if (name2 === GIT_ENTRY) continue; if (entry.isDirectory() && isIgnoredDirectory(name2, ignoreDirs)) continue; let st; try { @@ -477,7 +504,7 @@ function readText(abs) { return ""; } } -var IGNORE_DIRS, LOCKFILES, BINARY_EXT, DEFAULT_MAX_FILES; +var IGNORE_DIRS, GIT_ENTRY, LOCKFILES, BINARY_EXT, DEFAULT_MAX_FILES; var init_walk = __esm({ "src/walk.ts"() { "use strict"; @@ -516,6 +543,7 @@ var init_walk = __esm({ "elm-stuff", ".dart_tool" ]); + GIT_ENTRY = ".git"; LOCKFILES = /* @__PURE__ */ new Set([ "package-lock.json", "npm-shrinkwrap.json", @@ -779,34 +807,46 @@ function extToLang(ext) { return EXT_LANG[ext] ?? "other"; } function blankComments(src) { - const out2 = src.split(""); - let i2 = 0; const n = src.length; + let out2 = ""; + let kept = 0; + let i2 = 0; while (i2 < n) { - const c2 = src[i2]; - const next = src[i2 + 1]; - if (c2 === "/" && next === "/") { - while (i2 < n && src[i2] !== "\n") { - out2[i2] = " "; - i2++; + const c2 = src.charCodeAt(i2); + if (c2 === SLASH) { + const next = src.charCodeAt(i2 + 1); + if (next === SLASH) { + out2 += src.slice(kept, i2); + const start2 = i2; + while (i2 < n && src.charCodeAt(i2) !== NEWLINE) i2++; + out2 += " ".repeat(i2 - start2); + kept = i2; + continue; } - continue; - } - if (c2 === "/" && next === "*") { - while (i2 < n && !(src[i2] === "*" && src[i2 + 1] === "/")) { - if (src[i2] !== "\n") out2[i2] = " "; - i2++; + if (next === STAR) { + out2 += src.slice(kept, i2); + let run2 = 0; + while (i2 < n && !(src.charCodeAt(i2) === STAR && src.charCodeAt(i2 + 1) === SLASH)) { + if (src.charCodeAt(i2) === NEWLINE) { + out2 += " ".repeat(run2) + "\n"; + run2 = 0; + } else run2++; + i2++; + } + if (i2 < n) run2++; + if (i2 + 1 < n) run2++; + out2 += " ".repeat(run2); + i2 += 2; + kept = Math.min(i2, n); + continue; } - if (i2 < n) out2[i2] = " "; - if (i2 + 1 < n) out2[i2 + 1] = " "; - i2 += 2; + i2++; continue; } - if (c2 === '"' || c2 === "'" || c2 === "`") { - const quote = c2; + if (c2 === DQUOTE || c2 === SQUOTE || c2 === BACKTICK) { i2++; - while (i2 < n && src[i2] !== quote) { - if (src[i2] === "\\") i2++; + while (i2 < n && src.charCodeAt(i2) !== c2) { + if (src.charCodeAt(i2) === BACKSLASH) i2++; i2++; } i2++; @@ -814,14 +854,28 @@ function blankComments(src) { } i2++; } - return out2.join(""); + return kept === 0 ? src : out2 + src.slice(kept); } function extractReexports(rel2, content, localSymbols) { if (!REEXPORT_EXTS.has(rel2.slice(rel2.lastIndexOf(".")))) return []; const lang = /\.(ts|tsx|mts|cts)$/.test(rel2) ? "typescript" : "javascript"; const out2 = []; const seen = /* @__PURE__ */ new Set(); - const lineAt = (idx) => content.slice(0, idx).split(/\r?\n/).length; + let lineStarts; + const lineAt = (idx) => { + if (!lineStarts) { + lineStarts = [0]; + for (let i2 = 0; i2 < content.length; i2++) if (content.charCodeAt(i2) === 10) lineStarts.push(i2 + 1); + } + let lo = 0; + let hi = lineStarts.length; + while (lo < hi) { + const mid = lo + hi >>> 1; + if (lineStarts[mid] <= idx) lo = mid + 1; + else hi = mid; + } + return lo; + }; const localDeclOf = /* @__PURE__ */ new Map(); for (const s of localSymbols) if (!localDeclOf.has(s.name)) localDeclOf.set(s.name, s); const scanned = blankComments(content); @@ -872,7 +926,7 @@ function extractReexports(rel2, content, localSymbols) { } return out2; } -var EXT_LANG, REEXPORT_EXTS, MAX_REEXPORTS; +var EXT_LANG, REEXPORT_EXTS, SLASH, STAR, NEWLINE, DQUOTE, SQUOTE, BACKTICK, BACKSLASH, MAX_REEXPORTS; var init_common = __esm({ "src/lang/common.ts"() { "use strict"; @@ -952,6 +1006,13 @@ var init_common = __esm({ ".sol": "solidity" }; REEXPORT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]); + SLASH = 47; + STAR = 42; + NEWLINE = 10; + DQUOTE = 34; + SQUOTE = 39; + BACKTICK = 96; + BACKSLASH = 92; MAX_REEXPORTS = 400; } }); @@ -1983,13 +2044,13 @@ async function Module2(moduleArg = {}) { } readAsync = /* @__PURE__ */ __name(async (url) => { if (isFileURI(url)) { - return new Promise((resolve5, reject) => { + return new Promise((resolve6, reject) => { var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = "arraybuffer"; xhr.onload = () => { if (xhr.status == 200 || xhr.status == 0 && xhr.response) { - resolve5(xhr.response); + resolve6(xhr.response); return; } reject(xhr.status); @@ -2185,9 +2246,9 @@ async function Module2(moduleArg = {}) { __name(receiveInstantiationResult, "receiveInstantiationResult"); var info2 = getWasmImports(); if (Module["instantiateWasm"]) { - return new Promise((resolve5, reject) => { + return new Promise((resolve6, reject) => { Module["instantiateWasm"](info2, (mod, inst) => { - resolve5(receiveInstance(mod, inst)); + resolve6(receiveInstance(mod, inst)); }); }); } @@ -3518,8 +3579,8 @@ async function Module2(moduleArg = {}) { if (runtimeInitialized) { moduleRtn = Module; } else { - moduleRtn = new Promise((resolve5, reject) => { - readyPromiseResolve = resolve5; + moduleRtn = new Promise((resolve6, reject) => { + readyPromiseResolve = resolve6; readyPromiseReject = reject; }); } @@ -5749,7 +5810,7 @@ ${JSON.stringify(symbolNames, null, 2)}`); }); // src/ast/loader.ts -import { readFileSync as readFileSync2, existsSync, statSync as statSync2 } from "fs"; +import { readFileSync as readFileSync2, existsSync as existsSync2, statSync as statSync2 } from "fs"; import { homedir } from "os"; import { dirname, join as join2 } from "path"; import { fileURLToPath } from "url"; @@ -5767,10 +5828,10 @@ function resolveGrammarsTier(opts = {}) { tier, dir, cacheDir, - dirs: [dir, ...existsSync(join2(dir, "..", EXTENDED_DIR)) ? [join2(dir, "..", EXTENDED_DIR)] : []] + dirs: [dir, ...existsSync2(join2(dir, "..", EXTENDED_DIR)) ? [join2(dir, "..", EXTENDED_DIR)] : []] }); const legacy = process.env.CODEINDEX_GRAMMAR_DIR ?? process.env.ULTRAINDEX_GRAMMAR_DIR; - if (legacy && legacy.trim() && existsSync(legacy)) return withDirs("env", legacy); + if (legacy && legacy.trim() && existsSync2(legacy)) return withDirs("env", legacy); const here = opts.moduleDir ?? dirname(fileURLToPath(import.meta.url)); const adjacent = [ join2(here, "grammars"), @@ -5779,10 +5840,10 @@ function resolveGrammarsTier(opts = {}) { // dev: src/ast → /scripts/grammars join2(here, "..", "scripts", "grammars") ]; - for (const c2 of adjacent) if (existsSync(c2)) return withDirs("adjacent", c2); + for (const c2 of adjacent) if (existsSync2(c2)) return withDirs("adjacent", c2); const env = process.env.CODEINDEX_GRAMMARS_DIR; - if (env && env.trim() && existsSync(env)) return withDirs("env", env); - if (existsSync(cacheDir)) return withDirs("cache", cacheDir); + if (env && env.trim() && existsSync2(env)) return withDirs("env", env); + if (existsSync2(cacheDir)) return withDirs("cache", cacheDir); return { tier: "none", cacheDir, dirs: [] }; } function resolveGrammarsDir(opts) { @@ -5794,7 +5855,7 @@ async function ensureGrammars(keys) { const firstIn = (name2) => { for (const d of dirs) { const p = join2(d, name2); - if (existsSync(p)) return p; + if (existsSync2(p)) return p; } return void 0; }; @@ -7155,6 +7216,14 @@ var init_doc = __esm({ }); // src/ast/extract.ts +function typeFlagsOf(type) { + let flags2 = typeFlags.get(type); + if (flags2 === void 0) { + flags2 = (REF_IDENT_TYPE.test(type) ? T_REF_IDENT : 0) | (COMMENT_NODE.test(type) ? T_COMMENT : 0) | (STRING_NODE.test(type) ? T_STRING : 0) | (NUMBER_NODE.test(type) ? T_NUMBER : 0) | (REGEX_NODE.test(type) ? T_REGEX : 0); + typeFlags.set(type, flags2); + } + return flags2; +} function isPlainString(node) { return node.namedChildren.every((c2) => STRING_PART.test(c2.type)); } @@ -7195,20 +7264,21 @@ function collectAll(root, spec, defNames, maxCalls, wantImports) { const visit = (node) => { const type = node.type; const kids = node.namedChildren; - if (kids.length === 0 && REF_IDENT_TYPE.test(type)) { + const flags2 = typeFlagsOf(type); + if (kids.length === 0 && flags2 & T_REF_IDENT) { const text = node.text; if (REF_IDENT_TEXT.test(text) && !defNames.has(text)) identsFound.add(text); } - if (COMMENT_NODE.test(type)) { + if (flags2 & T_COMMENT) { for (const line of node.text.split(/\r?\n/)) addTerms2(stripCommentMarkers(line)); - } else if (kids.length === 0 && STRING_NODE.test(type) && node.endIndex - node.startIndex <= MAX_LITERAL_LEN2) { + } else if (kids.length === 0 && flags2 & T_STRING && node.endIndex - node.startIndex <= MAX_LITERAL_LEN2) { addTerms2(node.text.replace(/^['"`]+|['"`]+$/g, "")); } if (!literals.full) { - const line = node.startPosition.row + 1; - if (STRING_NODE.test(type) && isPlainString(node)) literals.addString(node.text, line); - else if (kids.length === 0 && NUMBER_NODE.test(type)) literals.add("number", node.text.trim(), line); - else if (REGEX_NODE.test(type)) literals.add("regex", node.text, line); + if (flags2 & T_STRING) { + if (isPlainString(node)) literals.addString(node.text, node.startPosition.row + 1); + } else if (kids.length === 0 && flags2 & T_NUMBER) literals.add("number", node.text.trim(), node.startPosition.row + 1); + else if (flags2 & T_REGEX) literals.add("regex", node.text, node.startPosition.row + 1); } if (wantCalls && !(spec.kindFrom?.[type] && spec.kindFrom[type](node)) && !spec.skipCall?.(node)) { const how = spec.calls[type]; @@ -7632,7 +7702,7 @@ function extractAst(rel2, ext, content, opts = {}) { tree?.delete(); } } -var MAX_REF_IDENTS, MAX_CALLS, MAX_IMPORTED_NAMES, MAX_SYMBOLS, MAX_RELATIONS, MAX_TERMS, MAX_LITERAL_LEN2, MAX_FUNC_DEPTH, NESTED_TYPE_KINDS, ANON_DEFAULT_FN, ANON_DEFAULT_CLASS, REF_IDENT_TYPE, REF_IDENT_TEXT, COMMENT_NODE, STRING_NODE, NUMBER_NODE, REGEX_NODE, STRING_PART; +var MAX_REF_IDENTS, MAX_CALLS, MAX_IMPORTED_NAMES, MAX_SYMBOLS, MAX_RELATIONS, MAX_TERMS, MAX_LITERAL_LEN2, MAX_FUNC_DEPTH, NESTED_TYPE_KINDS, ANON_DEFAULT_FN, ANON_DEFAULT_CLASS, REF_IDENT_TYPE, REF_IDENT_TEXT, COMMENT_NODE, STRING_NODE, NUMBER_NODE, REGEX_NODE, STRING_PART, T_REF_IDENT, T_COMMENT, T_STRING, T_NUMBER, T_REGEX, typeFlags; var init_extract = __esm({ "src/ast/extract.ts"() { "use strict"; @@ -7670,6 +7740,12 @@ var init_extract = __esm({ NUMBER_NODE = /(^|_)(integer|float|number|decimal|numeric)(_literal)?$/; REGEX_NODE = /(^|_)(regex|regular_expression)(_pattern|_literal)?$/; STRING_PART = /(^|_)(fragment|content|escape_sequence|character)$/; + T_REF_IDENT = 1; + T_COMMENT = 2; + T_STRING = 4; + T_NUMBER = 8; + T_REGEX = 16; + typeFlags = /* @__PURE__ */ new Map(); } }); @@ -8273,125 +8349,18 @@ var init_scan = __esm({ } }); -// src/preload.ts -import { readFileSync as readFileSync3 } from "fs"; -import { join as join3 } from "path"; -function toCacheMap(scan2) { - const m = /* @__PURE__ */ new Map(); - for (const f of scan2.files) m.set(f.rel, { hash: f.hash, record: f, size: f.size, mtimeMs: scan2.mtimes.get(f.rel) }); - return m; -} -function needsGrammarWarm(walked, cache, fullHash = false) { - const codeFiles = walked.files.filter((file) => classify(file.rel, file.ext) === "code"); - return fullHash && codeFiles.length > 0 || codeFiles.some((file) => { - const cached = cache.get(file.rel); - return !cached || cached.size !== file.size || cached.mtimeMs !== file.mtimeMs; - }); -} -function readPersistedIndex(repo, indexDir = INDEX_DIR) { - let parsed; - try { - parsed = JSON.parse(readFileSync3(join3(repo, indexDir, "cache.json"), "utf8")); - } catch { - return void 0; - } - if (!parsed || parsed.schemaVersion !== SCHEMA_VERSION || parsed.extractorVersion !== EXTRACTOR_VERSION || !parsed.files) { - return void 0; - } - return { - cacheMap: new Map(Object.entries(parsed.files)), - meta: { - engineVersion: parsed.engineVersion, - commit: parsed.commit, - graphSha1: parsed.graphSha1, - symbolsSha1: parsed.symbolsSha1 - } - }; -} -function preloadArtifacts(repo, scan2, meta, indexDir = INDEX_DIR) { - if (!scan2.contentUnchanged || meta.engineVersion !== ENGINE_VERSION || meta.commit !== scan2.commit || meta.graphSha1 === void 0 || meta.symbolsSha1 === void 0) { - return void 0; - } - const dir = join3(repo, indexDir); - let graphBytes; - let symbolsBytes; - try { - graphBytes = readFileSync3(join3(dir, "graph.json")); - symbolsBytes = readFileSync3(join3(dir, "symbols.json")); - } catch { - return void 0; - } - if (sha1(graphBytes) !== meta.graphSha1 || sha1(symbolsBytes) !== meta.symbolsSha1) { - return void 0; - } - try { - const graph = JSON.parse(graphBytes.toString("utf8")); - const symbols = JSON.parse(symbolsBytes.toString("utf8")); - if (graph.schemaVersion !== SCHEMA_VERSION || symbols.schemaVersion !== SCHEMA_VERSION) return void 0; - return { scan: scan2, graph, symbols }; - } catch { - return void 0; - } -} -function preloadSession(repo, opts, indexDir = INDEX_DIR) { - const persisted = readPersistedIndex(repo, indexDir); - if (!persisted) return void 0; - const scan2 = scanRepo(repo, { ...opts, cache: persisted.cacheMap }); - return { scan: scan2, cacheMap: toCacheMap(scan2), arts: preloadArtifacts(repo, scan2, persisted.meta, indexDir) }; -} -async function preloadSessionLazy(repo, opts, warm, indexDir = INDEX_DIR) { - const persisted = readPersistedIndex(repo, indexDir); - if (!persisted) return void 0; - const walked = opts.precomputedWalk ?? walk(repo, { - maxFileBytes: opts.maxBytes, - maxFiles: opts.maxFiles, - gitignore: opts.gitignore, - ignoreDirs: opts.ignoreDirs - }); - const needsWarm = needsGrammarWarm(walked, persisted.cacheMap, opts.fullHash); - if (needsWarm) { - await warm(); - } - const scan2 = scanRepo(repo, { ...opts, cache: persisted.cacheMap, precomputedWalk: walked }); - let artifactsTried = false; - let artifacts; - return { - scan: scan2, - cacheMap: toCacheMap(scan2), - loadArtifacts: () => { - if (!artifactsTried) { - artifactsTried = true; - artifacts = preloadArtifacts(repo, scan2, persisted.meta, indexDir); - } - return artifacts; - } - }; -} -var INDEX_DIR; -var init_preload = __esm({ - "src/preload.ts"() { - "use strict"; - init_types(); - init_scan(); - init_hash(); - init_walk(); - init_classify(); - INDEX_DIR = ".codeindex"; - } -}); - // src/pool.ts -import { existsSync as existsSync2, statSync as statSync3 } from "fs"; +import { existsSync as existsSync3, statSync as statSync3 } from "fs"; import * as os from "os"; -import { dirname as dirname2, join as join4 } from "path"; +import { dirname as dirname2, join as join3 } from "path"; import { fileURLToPath as fileURLToPath2, pathToFileURL } from "url"; import { Worker } from "worker_threads"; function resolveEngineUrl() { try { const here = fileURLToPath2(import.meta.url); if (here.endsWith("engine.mjs")) return pathToFileURL(here).href; - const adjacent = join4(dirname2(here), "engine.mjs"); - if (existsSync2(adjacent)) return pathToFileURL(adjacent).href; + const adjacent = join3(dirname2(here), "engine.mjs"); + if (existsSync3(adjacent)) return pathToFileURL(adjacent).href; return void 0; } catch { return void 0; @@ -8436,47 +8405,97 @@ async function extractInParallel(jobs, grammarKeys, count, opts = {}) { const engineUrl = resolveEngineUrl(); if (!engineUrl) return void 0; const wanted = grammarKeys.filter((k) => grammarReady(k)).sort(); - const shards = Array.from({ length: Math.min(count, jobs.length) }, () => []); - jobs.forEach((j, i2) => shards[i2 % shards.length].push(j)); + const workers = Math.min(count, jobs.length); const bootstrap = `import { runExtractWorker } from ${JSON.stringify(engineUrl)}; import { parentPort, workerData } from "node:worker_threads"; -runExtractWorker(workerData.input, (o) => parentPort.postMessage(o)).catch((e) => parentPort.postMessage({ error: String(e) })); +const base = workerData.input; +const post = (o) => parentPort.postMessage(o); +const fail = (e) => post({ error: String(e) }); +runExtractWorker({ ...base, jobs: [] }, post).then(() => { + parentPort.on("message", (m) => { + if (m.done) { parentPort.close(); return; } + runExtractWorker({ ...base, jobs: m.jobs }, post).catch(fail); + }); +}).catch(fail); `; + const out2 = /* @__PURE__ */ new Map(); + let next = 0; + const takeBatch = () => { + const remaining = jobs.length - next; + if (remaining <= 0) return []; + const size = Math.max(MIN_BATCH_JOBS, Math.ceil(remaining / (workers * BATCHES_PER_WORKER))); + const batch = jobs.slice(next, next + size); + next += batch.length; + return batch; + }; + const spawned = []; try { - const outputs = await Promise.all( - shards.map( - (jobsForShard) => new Promise((resolve5, reject) => { + await Promise.all( + Array.from( + { length: workers }, + () => new Promise((resolve6, reject) => { const w = new Worker(bootstrap, { eval: true, - workerData: { input: { jobs: jobsForShard, grammarKeys: wanted, maxCallsPerFile: opts.maxCallsPerFile } } + workerData: { input: { jobs: [], grammarKeys: wanted, maxCallsPerFile: opts.maxCallsPerFile } } }); - const timer = setTimeout(() => { - reject(new Error("extraction worker timed out")); - void w.terminate(); - }, WORKER_TIMEOUT_MS); + spawned.push(w); + let finished = false; + let timer; + const arm = () => { + if (timer) clearTimeout(timer); + timer = setTimeout(() => { + settle(() => reject(new Error("extraction worker timed out"))); + void w.terminate(); + }, WORKER_TIMEOUT_MS); + }; const settle = (fn) => { - clearTimeout(timer); + if (timer) clearTimeout(timer); + finished = true; fn(); }; - w.once("message", (m) => { - settle(() => resolve5(m)); - void w.terminate(); + arm(); + let inflight = 0; + const dispatch = () => { + const batch = takeBatch(); + if (batch.length === 0) return false; + inflight++; + w.postMessage({ jobs: batch }); + return true; + }; + w.on("message", (m) => { + if (finished) return; + if ("error" in m) { + settle(() => reject(new Error(m.error))); + void w.terminate(); + return; + } + if (m.ready.slice().sort().join(",") !== wanted.join(",")) { + settle(() => reject(new Error("extraction worker grammar tier mismatch"))); + void w.terminate(); + return; + } + for (const r of m.records) out2.set(r.rel, { size: r.size, mtimeMs: r.mtimeMs, record: r.record }); + if (inflight === 0) dispatch(); + else inflight--; + dispatch(); + if (inflight === 0) { + settle(() => resolve6()); + w.postMessage({ done: true }); + void w.terminate(); + return; + } + arm(); }); w.once("error", (e) => settle(() => reject(e))); w.once("exit", (code) => { - if (code !== 0) settle(() => reject(new Error(`extraction worker exited with ${code}`))); + if (!finished && code !== 0) settle(() => reject(new Error(`extraction worker exited with ${code}`))); }); }) ) ); - const out2 = /* @__PURE__ */ new Map(); - for (const o of outputs) { - if ("error" in o) return void 0; - if (o.ready.slice().sort().join(",") !== wanted.join(",")) return void 0; - for (const r of o.records) out2.set(r.rel, { size: r.size, mtimeMs: r.mtimeMs, record: r.record }); - } return out2; } catch { + for (const w of spawned) void w.terminate(); return void 0; } } @@ -8505,7 +8524,7 @@ async function scanRepoParallel(root, opts = {}) { const extracted = await extractInParallel(jobs, grammarKeys, count, { maxCallsPerFile: opts.maxCallsPerFile }); return scanRepo(root, extracted ? { ...scanOpts, extracted } : scanOpts); } -var WORKER_TIMEOUT_MS, DEFAULT_MIN_PARALLEL_JOBS; +var WORKER_TIMEOUT_MS, DEFAULT_MIN_PARALLEL_JOBS, BATCHES_PER_WORKER, MIN_BATCH_JOBS; var init_pool = __esm({ "src/pool.ts"() { "use strict"; @@ -8516,12 +8535,129 @@ var init_pool = __esm({ init_scan(); WORKER_TIMEOUT_MS = 10 * 60 * 1e3; DEFAULT_MIN_PARALLEL_JOBS = 200; + BATCHES_PER_WORKER = 4; + MIN_BATCH_JOBS = 4; + } +}); + +// src/preload.ts +import { readFileSync as readFileSync3 } from "fs"; +import { join as join4 } from "path"; +function toCacheMap(scan2) { + const m = /* @__PURE__ */ new Map(); + for (const f of scan2.files) m.set(f.rel, { hash: f.hash, record: f, size: f.size, mtimeMs: scan2.mtimes.get(f.rel) }); + return m; +} +function needsGrammarWarm(walked, cache, fullHash = false) { + const codeFiles = walked.files.filter((file) => classify(file.rel, file.ext) === "code"); + return fullHash && codeFiles.length > 0 || codeFiles.some((file) => { + const cached = cache.get(file.rel); + return !cached || cached.size !== file.size || cached.mtimeMs !== file.mtimeMs; + }); +} +function readPersistedIndex(repo, indexDir = INDEX_DIR) { + let parsed; + try { + parsed = JSON.parse(readFileSync3(join4(repo, indexDir, "cache.json"), "utf8")); + } catch { + return void 0; + } + if (!parsed || parsed.schemaVersion !== SCHEMA_VERSION || parsed.extractorVersion !== EXTRACTOR_VERSION || !parsed.files) { + return void 0; + } + return { + cacheMap: new Map(Object.entries(parsed.files)), + meta: { + engineVersion: parsed.engineVersion, + commit: parsed.commit, + graphSha1: parsed.graphSha1, + symbolsSha1: parsed.symbolsSha1 + } + }; +} +function preloadArtifacts(repo, scan2, meta, indexDir = INDEX_DIR) { + if (!scan2.contentUnchanged || meta.engineVersion !== ENGINE_VERSION || meta.commit !== scan2.commit || meta.graphSha1 === void 0 || meta.symbolsSha1 === void 0) { + return void 0; + } + const dir = join4(repo, indexDir); + let graphBytes; + let symbolsBytes; + try { + graphBytes = readFileSync3(join4(dir, "graph.json")); + symbolsBytes = readFileSync3(join4(dir, "symbols.json")); + } catch { + return void 0; + } + if (sha1(graphBytes) !== meta.graphSha1 || sha1(symbolsBytes) !== meta.symbolsSha1) { + return void 0; + } + try { + const graph = JSON.parse(graphBytes.toString("utf8")); + const symbols = JSON.parse(symbolsBytes.toString("utf8")); + if (graph.schemaVersion !== SCHEMA_VERSION || symbols.schemaVersion !== SCHEMA_VERSION) return void 0; + return { scan: scan2, graph, symbols }; + } catch { + return void 0; + } +} +function preloadSession(repo, opts, indexDir = INDEX_DIR) { + const persisted = readPersistedIndex(repo, indexDir); + if (!persisted) return void 0; + const scan2 = scanRepo(repo, { ...opts, cache: persisted.cacheMap }); + return { scan: scan2, cacheMap: toCacheMap(scan2), arts: preloadArtifacts(repo, scan2, persisted.meta, indexDir) }; +} +async function preloadSessionLazy(repo, opts, warm, indexDir = INDEX_DIR) { + const persisted = readPersistedIndex(repo, indexDir); + if (!persisted) return void 0; + const walked = opts.precomputedWalk ?? walk(repo, { + maxFileBytes: opts.maxBytes, + maxFiles: opts.maxFiles, + gitignore: opts.gitignore, + ignoreDirs: opts.ignoreDirs + }); + const needsWarm = needsGrammarWarm(walked, persisted.cacheMap, opts.fullHash); + if (needsWarm) { + await warm(); + } + const scan2 = await scanRepoParallel(repo, { ...opts, cache: persisted.cacheMap, precomputedWalk: walked }); + let artifactsTried = false; + let artifacts; + return { + scan: scan2, + cacheMap: toCacheMap(scan2), + loadArtifacts: () => { + if (!artifactsTried) { + artifactsTried = true; + artifacts = preloadArtifacts(repo, scan2, persisted.meta, indexDir); + } + return artifacts; + } + }; +} +var INDEX_DIR; +var init_preload = __esm({ + "src/preload.ts"() { + "use strict"; + init_types(); + init_scan(); + init_pool(); + init_hash(); + init_walk(); + init_classify(); + INDEX_DIR = ".codeindex"; } }); // src/resolve.ts import { posix } from "path"; import { join as join7 } from "path"; +function filesInDir(ctx, dir, ext) { + const memo = ctx.dirFilesMemo ??= /* @__PURE__ */ new Map(); + const key = ext + "\0" + dir; + let list = memo.get(key); + if (!list) memo.set(key, list = (ctx.filesByDir.get(dir) ?? []).filter((f) => f.endsWith(ext)).sort()); + return list; +} function distToSrcCandidates(target) { const segs = norm(target).split("/").filter((s) => s !== "."); const out2 = []; @@ -8973,7 +9109,7 @@ function resolveGo(fromRel, spec, ctx) { if (!ctx.goModules.length) return { kind: "external" }; const probePkg = (dir) => { const d = norm(dir).replace(/^\.$/, ""); - const inDir = (ctx.filesByDir.get(d) ?? []).filter((f) => f.endsWith(".go")).sort(); + const inDir = filesInDir(ctx, d, ".go"); return inDir.length ? { kind: "resolved", target: inDir[0] } : { kind: "dangling", reason: "missing-package" }; }; const home = ctx.goModules.find((g) => !g.dir || fromRel === g.dir || fromRel.startsWith(g.dir + "/")); @@ -9059,7 +9195,7 @@ function resolveJava(spec, ctx) { const p = norm(posix.join(root, pkgPath)); if (p.endsWith("/*") || p === "*") { const dir = p === "*" ? "" : p.slice(0, -2); - const inDir = (ctx.filesByDir.get(dir) ?? []).filter((f) => f.endsWith(".java")).sort(); + const inDir = filesInDir(ctx, dir, ".java"); if (inDir.length) return inDir[0]; continue; } @@ -9128,7 +9264,14 @@ function resolveImport(fromRel, ext, spec, ctx) { if (dot !== -1 && ASSET_EXT.has(spec.slice(dot).toLowerCase().replace(/[?#].*$/, ""))) { return { kind: "external" }; } - if (JS_TS2.has(ext) || SFC_HTML.has(ext)) return resolveJs(fromRel, spec, ctx); + if (JS_TS2.has(ext) || SFC_HTML.has(ext)) { + const dir = fromRel.includes("/") ? posix.dirname(fromRel) : ""; + const key = dir + "\0" + spec; + const memo = ctx.jsMemo ??= /* @__PURE__ */ new Map(); + let r = memo.get(key); + if (!r) memo.set(key, r = resolveJs(fromRel, spec, ctx)); + return { ...r }; + } if (PY2.has(ext)) return resolvePython(fromRel, spec, ctx); if (ext === ".go") return resolveGo(fromRel, spec, ctx); if (ext === ".rs") return resolveRust(fromRel, spec, ctx); @@ -9554,6 +9697,7 @@ function computeSymbolRefs(scan2) { if (!set) refs.set(name2, set = /* @__PURE__ */ new Set()); set.add(file); }; + const mentions = docMentionsFor(scan2); for (const f of scan2.files) { if (f.kind === "code" && f.idents) { for (const id of f.idents) { @@ -9561,9 +9705,9 @@ function computeSymbolRefs(scan2) { if (target && target !== f.rel) add(id, f.rel); } } else if (f.kind === "doc") { - const content = scan2.docText.get(f.rel); - if (!content) continue; - for (const tok of content.split(/[^A-Za-z0-9_]+/)) { + const m = mentions.get(f.rel); + if (!m || !m.retained) continue; + for (const tok of m.counts.keys()) { const target = unique.get(tok); if (target && target !== f.rel) add(tok, f.rel); } @@ -10334,15 +10478,25 @@ function betweennessOf(ids, edges) { nbSets[b].add(a); } const adj = nbSets.map((s) => [...s].sort((x, y) => x - y)); - const cb = new Array(n).fill(0); + const cb = new Float64Array(n); + const stack = []; + const queue = []; + const pred = Array.from({ length: n }, () => []); + const sigma = new Float64Array(n); + const dist = new Int32Array(n).fill(-1); + const delta = new Float64Array(n); for (let s = 0; s < n; s++) { - const stack = []; - const pred = Array.from({ length: n }, () => []); - const sigma = new Array(n).fill(0); - const dist = new Array(n).fill(-1); + for (const v of stack) { + sigma[v] = 0; + dist[v] = -1; + delta[v] = 0; + pred[v].length = 0; + } + stack.length = 0; + queue.length = 0; sigma[s] = 1; dist[s] = 0; - const queue = [s]; + queue.push(s); for (let qi = 0; qi < queue.length; qi++) { const v = queue[qi]; stack.push(v); @@ -10357,7 +10511,6 @@ function betweennessOf(ids, edges) { } } } - const delta = new Array(n).fill(0); for (let si = stack.length - 1; si >= 0; si--) { const w = stack[si]; for (const v of pred[w]) delta[v] += sigma[v] / sigma[w] * (1 + delta[w]); @@ -10505,6 +10658,33 @@ function symbolRefsFor(scan2) { const c2 = cacheFor(scan2); return c2.symbolRefs ??= computeSymbolRefs(scan2); } +function docMentionsFor(scan2) { + const c2 = cacheFor(scan2); + if (c2.docMentions) return c2.docMentions; + const unique = uniqueDefsFor(scan2); + const out2 = /* @__PURE__ */ new Map(); + if (unique.size) { + for (const f of scan2.files) { + if (f.kind !== "doc") continue; + const retained = scan2.docText.get(f.rel); + const content = retained ?? readText(join9(scan2.root, f.rel)); + if (!content) continue; + const counts = /* @__PURE__ */ new Map(); + for (const tok of content.split(/[^A-Za-z0-9_]+/)) { + if (unique.has(tok)) counts.set(tok, (counts.get(tok) ?? 0) + 1); + } + out2.set(f.rel, { counts, retained: retained !== void 0 }); + } + } + return c2.docMentions = out2; +} +function identSetsFor(scan2) { + const c2 = cacheFor(scan2); + if (c2.identSets) return c2.identSets; + const out2 = /* @__PURE__ */ new Map(); + for (const f of scan2.files) if (f.kind === "code" && f.idents?.length) out2.set(f.rel, new Set(f.idents)); + return c2.identSets = out2; +} function callerIndexFor(scan2) { const c2 = cacheFor(scan2); return c2.callerIndex ??= buildCallerIndex(scan2, importPairsFor(scan2)); @@ -10575,7 +10755,6 @@ var init_derived = __esm({ }); // src/graph.ts -import { join as join10 } from "path"; function isDistinctive(name2) { if (name2.length < 5) return false; const internalUpper = /[a-z][A-Z]/.test(name2) || /[A-Z]{2}/.test(name2); @@ -10657,18 +10836,11 @@ function buildGraph(scan2, ctx, modules, moduleOf, meta) { } } if (unique.size) { - for (const f of scan2.files) { - if (f.kind !== "doc") continue; - const content = scan2.docText.get(f.rel) ?? readText(join10(scan2.root, f.rel)); - if (!content) continue; - const tokens = /* @__PURE__ */ new Map(); - for (const tok of content.split(/[^A-Za-z0-9_]+/)) { - if (unique.has(tok)) tokens.set(tok, (tokens.get(tok) ?? 0) + 1); - } - for (const [name2, count] of tokens) { + for (const [rel2, { counts }] of docMentionsFor(scan2)) { + for (const [name2, count] of counts) { const target = unique.get(name2); - if (target === f.rel) continue; - collect(fileEdgeMap, { from: f.rel, to: target, kind: "mention", weight: Math.min(count, 5) }); + if (target === rel2) continue; + collect(fileEdgeMap, { from: rel2, to: target, kind: "mention", weight: Math.min(count, 5) }); } } } @@ -10768,7 +10940,6 @@ var init_graph = __esm({ init_calls(); init_relations(); init_derived(); - init_walk(); init_sort(); REFERENCE_KINDS4 = /* @__PURE__ */ new Set(["reexport", "reexport-all", "default"]); SEP3 = "\0"; @@ -10777,7 +10948,7 @@ var init_graph = __esm({ }); // src/query.ts -import { join as join11 } from "path"; +import { join as join10 } from "path"; function* allSymbols(scan2) { for (const file of scan2.files) yield* file.symbols; } @@ -10815,7 +10986,7 @@ function findSymbol(scan2, namePath, opts = {}) { if (unreadableFiles.has(m.file)) continue; let lines = linesByFile.get(m.file); if (!lines) { - const content = readText(join11(scan2.root, m.file)); + const content = readText(join10(scan2.root, m.file)); if (!content) { unreadableFiles.add(m.file); continue; @@ -10851,14 +11022,14 @@ function findReferences(scan2, name2) { const referencingFiles = /* @__PURE__ */ new Set(); const unique = uniqueDefsFor(scan2); const defFile = unique.get(name2); + const idents = identSetsFor(scan2); + const mention = new RegExp(`\\b${name2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`); for (const f of scan2.files) { if (f.rel === defFile) continue; - if (f.kind === "code" && f.idents?.includes(name2)) referencingFiles.add(f.rel); + if (f.kind === "code" && idents.get(f.rel)?.has(name2)) referencingFiles.add(f.rel); else if (f.kind === "doc") { const content = scan2.docText.get(f.rel); - if (content && new RegExp(`\\b${name2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(content)) { - referencingFiles.add(f.rel); - } + if (content && mention.test(content)) referencingFiles.add(f.rel); } } for (const site of callSites) referencingFiles.add(site.file); @@ -10877,7 +11048,7 @@ var init_query = __esm({ // src/edit.ts import { chmodSync, mkdtempSync as mkdtempSync2, readFileSync as readFileSync6, realpathSync as realpathSync2, renameSync as renameSync2, rmSync as rmSync2, statSync as statSync4, writeFileSync as writeFileSync2 } from "fs"; -import { basename as basename3, dirname as dirname4, join as join12 } from "path"; +import { basename as basename3, dirname as dirname4, join as join11 } from "path"; function resolveUniqueSymbol(scan2, namePath, file) { let matches = findSymbol(scan2, namePath); if (file) matches = matches.filter((m) => m.file === file); @@ -10897,13 +11068,13 @@ function atomicWriteText(abs, content, cleanup = rmSync2) { const mode = statSync4(target).mode; let tempDir; try { - tempDir = mkdtempSync2(join12(dirname4(target), ".codeindex-edit-")); + tempDir = mkdtempSync2(join11(dirname4(target), ".codeindex-edit-")); } catch { writeFileSync2(target, content); chmodSync(target, mode); return; } - const tempFile = join12(tempDir, basename3(target)); + const tempFile = join11(tempDir, basename3(target)); try { writeFileSync2(tempFile, content); chmodSync(tempFile, mode); @@ -10923,7 +11094,7 @@ function atomicWriteText(abs, content, cleanup = rmSync2) { function replaceSymbolBody(scan2, namePath, body2, file) { const sym = resolveUniqueSymbol(scan2, namePath, file); const end = sym.endLine ?? sym.line; - const abs = join12(scan2.root, sym.file); + const abs = join11(scan2.root, sym.file); const lines = readLines(abs); const newLines = body2.replace(/^\n+|\n+$/g, "").split("\n"); lines.splice(sym.line - 1, end - sym.line + 1, ...newLines); @@ -10931,7 +11102,7 @@ function replaceSymbolBody(scan2, namePath, body2, file) { return { file: sym.file, startLine: sym.line, endLine: sym.line + newLines.length - 1, lines: newLines.length }; } function insertAt(scan2, sym, body2, index, blankBefore, blankAfter) { - const abs = join12(scan2.root, sym.file); + const abs = join11(scan2.root, sym.file); const lines = readLines(abs); const minGap = SEPARATED_KINDS.has(sym.kind) ? 1 : 0; const newLines = body2.replace(/^\n+|\n+$/g, "").split("\n"); @@ -10963,7 +11134,7 @@ var init_edit = __esm({ // src/memory.ts import { mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync7, rmSync as rmSync3, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs"; -import { dirname as dirname5, join as join13 } from "path"; +import { dirname as dirname5, join as join12 } from "path"; function sanitize(name2) { const clean = name2.replace(/^mem:/, "").replace(/\.md$/, ""); if (!clean) throw new Error("memory name is empty"); @@ -10977,7 +11148,7 @@ function sanitize(name2) { return clean; } function memoryPath(repo, name2) { - return join13(repo, ...MEMORY_DIR, `${sanitize(name2)}.md`); + return join12(repo, ...MEMORY_DIR, `${sanitize(name2)}.md`); } function writeMemory(repo, name2, content) { const path = memoryPath(repo, name2); @@ -11003,7 +11174,7 @@ function deleteMemory(repo, name2) { return true; } function listMemories(repo) { - const root = join13(repo, ...MEMORY_DIR); + const root = join12(repo, ...MEMORY_DIR); const out2 = []; const walk2 = (dir, prefix) => { let entries; @@ -11013,7 +11184,7 @@ function listMemories(repo) { return; } for (const e of entries) { - if (e.isDirectory()) walk2(join13(dir, e.name), prefix ? `${prefix}/${e.name}` : e.name); + if (e.isDirectory()) walk2(join12(dir, e.name), prefix ? `${prefix}/${e.name}` : e.name); else if (e.name.endsWith(".md")) out2.push(prefix ? `${prefix}/${e.name.slice(0, -3)}` : e.name.slice(0, -3)); } }; @@ -11029,8 +11200,8 @@ var init_memory = __esm({ }); // src/workspaces.ts -import { existsSync as existsSync5, readdirSync as readdirSync3, statSync as statSync6 } from "fs"; -import { join as join14 } from "path"; +import { existsSync as existsSync6, readdirSync as readdirSync3, statSync as statSync6 } from "fs"; +import { join as join13 } from "path"; function readJson(path, label, warnings) { const raw = readText(path); if (!raw) return void 0; @@ -11081,8 +11252,8 @@ function wsGlobToRegExp(pat) { return new RegExp(`^${re}($|/)`); } function probeNodePkg(root, dir, kind, warnings) { - const path = join14(root, dir, "package.json"); - if (!existsSync5(path)) return void 0; + const path = join13(root, dir, "package.json"); + if (!existsSync6(path)) return void 0; const manifest = `${dir}/package.json`; const pkg = readJson(path, manifest, warnings); const out2 = { @@ -11095,8 +11266,8 @@ function probeNodePkg(root, dir, kind, warnings) { return out2; } function probeCargo(root, dir) { - const path = join14(root, dir, "Cargo.toml"); - if (!existsSync5(path)) return void 0; + const path = join13(root, dir, "Cargo.toml"); + if (!existsSync6(path)) return void 0; const body2 = tomlSectionBody(readText(path), "package"); const out2 = { name: tomlString(body2, "name") ?? dir, @@ -11109,19 +11280,19 @@ function probeCargo(root, dir) { return out2; } function probeGoMod(root, dir) { - const path = join14(root, dir, "go.mod"); - if (!existsSync5(path)) return void 0; + const path = join13(root, dir, "go.mod"); + if (!existsSync6(path)) return void 0; const name2 = readText(path).match(/^module\s+(\S+)/m)?.[1] ?? dir; return { name: name2, dir, kind: "go", manifest: `${dir}/go.mod` }; } function probeMaven(root, dir) { - const path = join14(root, dir, "pom.xml"); - if (!existsSync5(path)) return void 0; + const path = join13(root, dir, "pom.xml"); + if (!existsSync6(path)) return void 0; return { name: ownArtifactId(readText(path)) ?? dir, dir, kind: "maven", manifest: `${dir}/pom.xml` }; } function probePyproject(root, dir) { - const path = join14(root, dir, "pyproject.toml"); - if (!existsSync5(path)) return void 0; + const path = join13(root, dir, "pyproject.toml"); + if (!existsSync6(path)) return void 0; const toml = readText(path); const project = tomlSectionBody(toml, "project"); const poetry = tomlSectionBody(toml, "tool.poetry"); @@ -11136,8 +11307,8 @@ function probePyproject(root, dir) { return out2; } function probeComposer(root, dir, warnings) { - const path = join14(root, dir, "composer.json"); - if (!existsSync5(path)) return void 0; + const path = join13(root, dir, "composer.json"); + if (!existsSync6(path)) return void 0; const manifest = `${dir}/composer.json`; const pkg = readJson(path, manifest, warnings); const out2 = { @@ -11150,8 +11321,8 @@ function probeComposer(root, dir, warnings) { return out2; } function probeNxProject(root, dir, warnings) { - const path = join14(root, dir, "project.json"); - if (!existsSync5(path)) return void 0; + const path = join13(root, dir, "project.json"); + if (!existsSync6(path)) return void 0; const manifest = `${dir}/project.json`; const proj = readJson(path, manifest, warnings); return { @@ -11163,7 +11334,7 @@ function probeNxProject(root, dir, warnings) { } function probeGradle(root, dir) { for (const f of ["build.gradle", "build.gradle.kts"]) { - if (existsSync5(join14(root, dir, f))) { + if (existsSync6(join13(root, dir, f))) { return { name: dir, dir, kind: "gradle", manifest: `${dir}/${f}` }; } } @@ -11198,7 +11369,7 @@ function addPackage(root, dir, found, kind, warnings) { } function isDirAt(root, rel2) { try { - return statSync6(join14(root, rel2)).isDirectory(); + return statSync6(join13(root, rel2)).isDirectory(); } catch { return false; } @@ -11206,7 +11377,7 @@ function isDirAt(root, rel2) { function subdirsOf(root, base) { let entries; try { - entries = readdirSync3(base ? join14(root, base) : root, { withFileTypes: true }); + entries = readdirSync3(base ? join13(root, base) : root, { withFileTypes: true }); } catch { return []; } @@ -11268,14 +11439,14 @@ function npmFamilyPatterns(root, warnings) { if (t.startsWith("!")) negations.push(t.slice(1)); else positives.push({ pattern: t, kind }); }; - const pkg = readJson(join14(root, "package.json"), "package.json", warnings); + const pkg = readJson(join13(root, "package.json"), "package.json", warnings); const ws = pkg?.workspaces; if (Array.isArray(ws)) { for (const x of ws) if (typeof x === "string") push(x, "npm"); } else if (ws && typeof ws === "object" && Array.isArray(ws.packages)) { for (const x of ws.packages) if (typeof x === "string") push(x, "npm"); } - const pnpm = readText(join14(root, "pnpm-workspace.yaml")); + const pnpm = readText(join13(root, "pnpm-workspace.yaml")); let inPackages = false; for (const line of pnpm.split(/\r?\n/)) { if (/^\S/.test(line)) { @@ -11289,11 +11460,11 @@ function npmFamilyPatterns(root, warnings) { return { positives, negations }; } function fallbackNpmPatterns(root, warnings) { - const lerna = readJson(join14(root, "lerna.json"), "lerna.json", warnings); + const lerna = readJson(join13(root, "lerna.json"), "lerna.json", warnings); if (lerna && Array.isArray(lerna.packages)) { return lerna.packages.filter((x) => typeof x === "string").map((pattern) => ({ pattern, kind: "lerna" })); } - const nx = readJson(join14(root, "nx.json"), "nx.json", warnings); + const nx = readJson(join13(root, "nx.json"), "nx.json", warnings); if (nx) { const layout = nx.workspaceLayout ?? {}; const appsDir = typeof layout.appsDir === "string" ? layout.appsDir : "apps"; @@ -11303,7 +11474,7 @@ function fallbackNpmPatterns(root, warnings) { return []; } function detectCargoMembers(root, found, warnings) { - const toml = readText(join14(root, "Cargo.toml")); + const toml = readText(join13(root, "Cargo.toml")); if (!toml) return; const body2 = tomlSectionBody(toml, "workspace"); if (!body2) return; @@ -11318,7 +11489,7 @@ function detectCargoMembers(root, found, warnings) { } } function detectGoWork(root, found, warnings) { - const gowork = readText(join14(root, "go.work")); + const gowork = readText(join13(root, "go.work")); if (!gowork) return; const dirs = []; for (const block of gowork.matchAll(/^use\s*\(([\s\S]*?)\)/gm)) { @@ -11334,7 +11505,7 @@ function detectGoWork(root, found, warnings) { } } function detectMavenModules(root, found, warnings) { - const pom = readText(join14(root, "pom.xml")); + const pom = readText(join13(root, "pom.xml")); if (!pom) return; const modules = pom.match(/([\s\S]*?)<\/modules>/)?.[1]; if (!modules) return; @@ -11343,7 +11514,7 @@ function detectMavenModules(root, found, warnings) { } } function detectUvMembers(root, found, warnings) { - const toml = readText(join14(root, "pyproject.toml")); + const toml = readText(join13(root, "pyproject.toml")); if (!toml) return; const body2 = tomlSectionBody(toml, "tool.uv.workspace"); if (!body2) return; @@ -11358,7 +11529,7 @@ function detectUvMembers(root, found, warnings) { } } function detectComposerPathRepos(root, found, warnings) { - const composer = readJson(join14(root, "composer.json"), "composer.json", warnings); + const composer = readJson(join13(root, "composer.json"), "composer.json", warnings); const repos = composer?.repositories; if (!Array.isArray(repos)) return; for (const r of repos) { @@ -11369,7 +11540,7 @@ function detectComposerPathRepos(root, found, warnings) { } function detectGradleIncludes(root, found, warnings) { for (const f of ["settings.gradle", "settings.gradle.kts"]) { - const text = readText(join14(root, f)); + const text = readText(join13(root, f)); if (!text) continue; for (const line of text.split(/\r?\n/)) { if (!/^\s*include[\s(]/.test(line)) continue; @@ -11381,7 +11552,7 @@ function detectGradleIncludes(root, found, warnings) { } } function npmEdges(root, pkg, byName, warnings) { - const manifest = readJson(join14(root, pkg.dir, "package.json"), `${pkg.dir}/package.json`, warnings); + const manifest = readJson(join13(root, pkg.dir, "package.json"), `${pkg.dir}/package.json`, warnings); if (!manifest) return []; const edges = /* @__PURE__ */ new Set(); for (const field of ["dependencies", "devDependencies", "peerDependencies"]) { @@ -11404,7 +11575,7 @@ function normalizeDepPath(fromDir, rel2) { return out2.join("/"); } function cargoEdges(root, pkg, byName, byDir) { - const toml = readText(join14(root, pkg.dir, "Cargo.toml")); + const toml = readText(join13(root, pkg.dir, "Cargo.toml")); if (!toml) return []; const edges = /* @__PURE__ */ new Set(); for (const section of ["dependencies", "dev-dependencies", "build-dependencies"]) { @@ -11428,7 +11599,7 @@ function cargoEdges(root, pkg, byName, byDir) { return [...edges]; } function goPkgEdges(root, pkg, byName, byDir) { - const gomod = readText(join14(root, pkg.dir, "go.mod")); + const gomod = readText(join13(root, pkg.dir, "go.mod")); if (!gomod) return []; const edges = /* @__PURE__ */ new Set(); for (const m of gomod.matchAll(/^\s*(?:require\s+)?([^\s/(][^\s]*)\s+v[^\s]+/gm)) { @@ -11442,7 +11613,7 @@ function goPkgEdges(root, pkg, byName, byDir) { return [...edges]; } function mavenEdges(root, pkg, byName) { - const pom = readText(join14(root, pkg.dir, "pom.xml")); + const pom = readText(join13(root, pkg.dir, "pom.xml")); if (!pom) return []; const edges = /* @__PURE__ */ new Set(); for (const m of pom.replace(/[\s\S]*?<\/parent>/g, "").matchAll(/([\s\S]*?)<\/dependency>/g)) { @@ -11452,7 +11623,7 @@ function mavenEdges(root, pkg, byName) { return [...edges]; } function uvEdges(root, pkg, byName) { - const toml = readText(join14(root, pkg.dir, "pyproject.toml")); + const toml = readText(join13(root, pkg.dir, "pyproject.toml")); if (!toml) return []; const edges = /* @__PURE__ */ new Set(); const project = tomlSectionBody(toml, "project"); @@ -11472,7 +11643,7 @@ function uvEdges(root, pkg, byName) { return [...edges]; } function composerEdges(root, pkg, byName, warnings) { - const manifest = readJson(join14(root, pkg.dir, "composer.json"), `${pkg.dir}/composer.json`, warnings); + const manifest = readJson(join13(root, pkg.dir, "composer.json"), `${pkg.dir}/composer.json`, warnings); if (!manifest) return []; const edges = /* @__PURE__ */ new Set(); for (const field of ["require", "require-dev"]) { @@ -11486,7 +11657,7 @@ function composerEdges(root, pkg, byName, warnings) { } function gradleEdges(root, pkg, byName, byDir) { for (const f of ["build.gradle", "build.gradle.kts"]) { - const text = readText(join14(root, pkg.dir, f)); + const text = readText(join13(root, pkg.dir, f)); if (!text) continue; const edges = /* @__PURE__ */ new Set(); for (const m of text.matchAll(/project\s*\(\s*["']:?([^"']+)["']\s*\)/g)) { @@ -11908,13 +12079,20 @@ function isFunctionValued(signature) { } return false; } -function holderFor(symbols, line) { - let best; +function holderCandidates(symbols) { + const out2 = []; for (const s of symbols) { if (!HOLDER_KINDS.has(s.kind)) continue; if (isFunctionValued(s.signature)) continue; + if ((s.endLine ?? s.line) - s.line > MAX_HOLDER_SPAN) continue; + out2.push(s); + } + return out2; +} +function holderFor(candidates, line) { + let best; + for (const s of candidates) { const end = s.endLine ?? s.line; - if (end - s.line > MAX_HOLDER_SPAN) continue; if (line < s.line || line > end) continue; if (!best || s.line > best.line) best = s; } @@ -11927,13 +12105,14 @@ function findLiteralDuplications(scan2, opts = {}) { for (const f of scan2.files) { if (!f.literals?.length) continue; if (!opts.includeTests && isTestPath(f.rel)) continue; + let holders; for (const lit of f.literals) { if (opts.kinds && !opts.kinds.has(lit.kind)) continue; if (!isDistinctive2(lit.value, lit.kind)) continue; const key = `${lit.kind}\0${lit.value}`; let g = groups.get(key); if (!g) groups.set(key, g = { value: lit.value, kind: lit.kind, sites: [] }); - const holder = holderFor(f.symbols, lit.line); + const holder = holderFor(holders ??= holderCandidates(f.symbols), lit.line); g.sites.push( holder ? { file: f.rel, line: lit.line, holder: holder.name, holderExported: holder.exported } : { file: f.rel, line: lit.line } ); @@ -12151,16 +12330,16 @@ var init_grep = __esm({ // src/embed/model.ts import { createHash as createHash3 } from "crypto"; -import { existsSync as existsSync6, readFileSync as readFileSync8 } from "fs"; -import { join as join16 } from "path"; +import { existsSync as existsSync7, readFileSync as readFileSync8 } from "fs"; +import { join as join15 } from "path"; function resolveEmbedModelDir(repo) { const env = process.env.CODEINDEX_EMBED_DIR; const candidates = []; if (env) candidates.push(env); - if (repo) candidates.push(join16(repo, ".codeindex", DEFAULT_EMBED_DIRNAME)); - candidates.push(join16(process.cwd(), ".codeindex", DEFAULT_EMBED_DIRNAME)); + if (repo) candidates.push(join15(repo, ".codeindex", DEFAULT_EMBED_DIRNAME)); + candidates.push(join15(process.cwd(), ".codeindex", DEFAULT_EMBED_DIRNAME)); for (const c2 of candidates) { - if (existsSync6(join16(c2, "model.json"))) return c2; + if (existsSync7(join15(c2, "model.json"))) return c2; } return void 0; } @@ -12193,8 +12372,8 @@ function parseEmbedModel(raw, source) { } function loadEmbedModel(dir) { if (!dir) return void 0; - const path = join16(dir, "model.json"); - if (!existsSync6(path)) return void 0; + const path = join15(dir, "model.json"); + if (!existsSync7(path)) return void 0; const raw = JSON.parse(readFileSync8(path, "utf8")); return parseEmbedModel(raw, path); } @@ -12629,12 +12808,12 @@ var init_coupling = __esm({ }); // src/onboard.ts -import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs"; -import { join as join17, resolve as resolve2 } from "path"; +import { existsSync as existsSync8, readFileSync as readFileSync9 } from "fs"; +import { join as join16, resolve as resolve3 } from "path"; function tagline(root) { for (const name2 of README_NAMES) { - const path = join17(root, name2); - if (!existsSync7(path)) continue; + const path = join16(root, name2); + if (!existsSync8(path)) continue; let text; try { text = readFileSync9(path, "utf8"); @@ -12654,7 +12833,7 @@ function tagline(root) { } function onboardBrief(scan2, graph, opts = {}) { const lines = []; - const name2 = resolve2(scan2.root).replace(/\/+$/, "").split("/").pop() || "repository"; + const name2 = resolve3(scan2.root).replace(/\/+$/, "").split("/").pop() || "repository"; lines.push(`# ${name2}`, ""); const summary = tagline(scan2.root); if (summary) lines.push(summary, ""); @@ -12856,13 +13035,13 @@ async function openLspSession(transport, options) { const request = (method, params, budget = timeoutMs) => { if (dead) return Promise.reject(dead); const id = nextId++; - return new Promise((resolve5, reject) => { + return new Promise((resolve6, reject) => { const timer = setTimeout(() => { pending.delete(id); reject(new LspTimeout(method, budget)); }, budget); timer.unref?.(); - pending.set(id, { resolve: resolve5, reject, timer }); + pending.set(id, { resolve: resolve6, reject, timer }); transport.write(encodeMessage({ jsonrpc: "2.0", id, method, params })); }); }; @@ -12951,19 +13130,19 @@ var init_client = __esm({ }); // src/lsp/config.ts -import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs"; -import { join as join18, resolve as resolve3 } from "path"; +import { existsSync as existsSync9, readFileSync as readFileSync10 } from "fs"; +import { join as join17, resolve as resolve4 } from "path"; function resolveLspConfigPath(repo) { const env = process.env.CODEINDEX_LSP_CONFIG; if (env !== void 0) { const trimmed = env.trim(); if (!trimmed || trimmed === "0" || trimmed.toLowerCase() === "off") return { path: void 0, source: "none" }; - return { path: resolve3(trimmed), source: "env" }; + return { path: resolve4(trimmed), source: "env" }; } - const inRepo = join18(repo, LSP_CONFIG_DIR, LSP_CONFIG_NAME); - if (existsSync8(inRepo)) return { path: inRepo, source: "repo" }; - const inCwd = join18(process.cwd(), LSP_CONFIG_DIR, LSP_CONFIG_NAME); - if (inCwd !== inRepo && existsSync8(inCwd)) return { path: inCwd, source: "cwd" }; + const inRepo = join17(repo, LSP_CONFIG_DIR, LSP_CONFIG_NAME); + if (existsSync9(inRepo)) return { path: inRepo, source: "repo" }; + const inCwd = join17(process.cwd(), LSP_CONFIG_DIR, LSP_CONFIG_NAME); + if (inCwd !== inRepo && existsSync9(inCwd)) return { path: inCwd, source: "cwd" }; return { path: void 0, source: "none" }; } function parseLspConfig(payload) { @@ -13002,7 +13181,7 @@ function parseLspConfig(payload) { } function loadLspConfig(repo) { const { path } = resolveLspConfigPath(repo); - if (!path || !existsSync8(path)) return void 0; + if (!path || !existsSync9(path)) return void 0; let payload; try { payload = JSON.parse(readFileSync10(path, "utf8")); @@ -13039,13 +13218,13 @@ var init_config2 = __esm({ // src/lsp/refs.ts import { readFileSync as readFileSync11 } from "fs"; -import { join as join19 } from "path"; +import { join as join18 } from "path"; function lspUnavailable(server, reason) { return { server, ok: false, reason, refs: [], agreement: { both: [], lspOnly: [], staticOnly: [] } }; } function columnOfSymbol(root, rel2, line, name2) { try { - const lines = readFileSync11(join19(root, rel2), "utf8").split(/\r?\n/); + const lines = readFileSync11(join18(root, rel2), "utf8").split(/\r?\n/); const index = lines[line - 1]?.indexOf(name2) ?? -1; return index < 0 ? 0 : index; } catch { @@ -13110,7 +13289,7 @@ function refOrder(a, b) { } function readTextOrEmpty(root, rel2) { try { - return readFileSync11(join19(root, rel2), "utf8"); + return readFileSync11(join18(root, rel2), "utf8"); } catch { return ""; } @@ -13480,7 +13659,7 @@ function findDeadCode(scan2) { for (const f of scan2.files) { for (const s of f.symbols) { if (!consider(s)) continue; - const entry = callers.get(s.name) ?? callers.get(`${s.name}@${s.file}`); + const entry = callers.get(`${s.name}@${s.file}`) ?? callers.get(s.name); const hasCallers = !!entry && entry.def.file === s.file && entry.callers.length > 0; if (hasCallers) continue; const referenced = (refs.get(s.name)?.size ?? 0) > 0; @@ -13580,8 +13759,8 @@ var init_viz = __esm({ }); // src/mcp/protocol.ts -import { existsSync as existsSync9 } from "fs"; -import { join as join20 } from "path"; +import { existsSync as existsSync10 } from "fs"; +import { join as join19 } from "path"; import { pathToFileURL as pathToFileURL2 } from "url"; function validateArgs(schema, args2) { const props = schema.properties ?? {}; @@ -13627,7 +13806,7 @@ function negotiateProtocol(requested) { function capResponse(text, tool, repo, maxBytes) { const bytes = Buffer.byteLength(text, "utf8"); if (bytes <= maxBytes) return text; - const artifact = ARTIFACT_FOR[tool] ? join20(repo, INDEX_DIR, ARTIFACT_FOR[tool]) : void 0; + const artifact = ARTIFACT_FOR[tool] ? join19(repo, INDEX_DIR, ARTIFACT_FOR[tool]) : void 0; return JSON.stringify( { truncated: true, @@ -13636,7 +13815,7 @@ function capResponse(text, tool, repo, maxBytes) { maxBytes, reason: "This response exceeds the configured limit and was withheld rather than sent as an unusable partial payload.", narrower: NARROWER[tool] ?? "narrow the request with `scope`, `include`/`exclude`, or a `limit`", - ...artifact && existsSync9(artifact) ? { artifact, artifactNote: "The full result is already on disk here \u2014 read it directly if you need all of it." } : artifact ? { artifactNote: `Run \`codeindex index --repo ${repo} --out ${join20(repo, INDEX_DIR)}\` to get this as a file.` } : {} + ...artifact && existsSync10(artifact) ? { artifact, artifactNote: "The full result is already on disk here \u2014 read it directly if you need all of it." } : artifact ? { artifactNote: `Run \`codeindex index --repo ${repo} --out ${join19(repo, INDEX_DIR)}\` to get this as a file.` } : {} }, null, 2 @@ -14359,7 +14538,7 @@ var init_tools = __esm({ // src/mcp/session.ts import { statSync as statSync7 } from "fs"; -import { join as join21 } from "path"; +import { join as join20 } from "path"; function scanFingerprint(scan2) { return sha1(scan2.files.map((f) => `${f.rel}:${f.hash}`).join("\n")); } @@ -14373,7 +14552,7 @@ async function memoizedEmbeddingIndex(key, build) { function memoizedEmbedModel(modelDir) { let stat; try { - stat = statSync7(join21(modelDir, "model.json")); + stat = statSync7(join20(modelDir, "model.json")); } catch { return void 0; } @@ -14569,7 +14748,7 @@ __export(mcp_exports, { warmGrammarsForWalk: () => warmGrammarsForWalk }); import { readFileSync as readFileSync12, statSync as statSync8, watch as watchFs } from "fs"; -import { isAbsolute, join as join22 } from "path"; +import { isAbsolute, join as join21 } from "path"; import { createInterface } from "readline"; function isRpcRequest(value) { if (!value || typeof value !== "object" || Array.isArray(value)) return false; @@ -14904,7 +15083,7 @@ async function callTool(name2, args2, defaultRepo) { const configPath = str(args2.configPath); let payload = args2.rules; if (payload === void 0 && configPath) { - const abs = isAbsolute(configPath) ? configPath : join22(repo, configPath); + const abs = isAbsolute(configPath) ? configPath : join21(repo, configPath); try { payload = JSON.parse(readFileSync12(abs, "utf8")); } catch (e) { @@ -15367,7 +15546,7 @@ init_extract(); init_web_tree_sitter(); init_loader(); init_sort(); -import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs"; +import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs"; import { join as join5 } from "path"; var queries = /* @__PURE__ */ new Map(); function queryFor(key, language) { @@ -15376,7 +15555,7 @@ function queryFor(key, language) { let compiled = null; for (const dir of resolveGrammarsTier().dirs) { const path = join5(dir, `${key}.tags.scm`); - if (!existsSync3(path)) continue; + if (!existsSync4(path)) continue; try { compiled = new Query(language, readFileSync4(path, "utf8")); } catch { @@ -15388,7 +15567,7 @@ function queryFor(key, language) { return compiled; } function tagsQueryStatus(key) { - const present = resolveGrammarsTier().dirs.some((d) => existsSync3(join5(d, `${key}.tags.scm`))); + const present = resolveGrammarsTier().dirs.some((d) => existsSync4(join5(d, `${key}.tags.scm`))); if (!present) return { present: false, compiled: false }; const language = languageFor(key); if (!language) return { present: true, compiled: false }; @@ -15441,8 +15620,8 @@ init_loader(); // src/ast/grammars-pull.ts init_types(); import { createHash as createHash2 } from "crypto"; -import { existsSync as existsSync4, mkdirSync, mkdtempSync, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync } from "fs"; -import { dirname as dirname3, join as join6, resolve, sep as sep2 } from "path"; +import { existsSync as existsSync5, mkdirSync, mkdtempSync, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync } from "fs"; +import { dirname as dirname3, join as join6, resolve as resolve2, sep as sep2 } from "path"; import { gunzipSync } from "zlib"; var DEFAULT_GRAMMARS_URL = `https://github.com/maxgfr/codeindex/releases/download/v${ENGINE_VERSION}/grammars-${ENGINE_VERSION}.tar.gz`; function resolveGrammarsPullTarget() { @@ -15513,13 +15692,13 @@ function safeRelPath(name2) { return out2.length ? out2.join("/") : null; } function extractTarInto(rawTar, destDir) { - const root = resolve(destDir); + const root = resolve2(destDir); const written = []; for (const entry of readTar(asBuffer(rawTar))) { if (entry.type !== "0" && entry.type !== "\0") continue; const rel2 = safeRelPath(entry.name); if (rel2 === null) throw new Error(`refusing unsafe tar entry: ${entry.name}`); - const dest = resolve(destDir, rel2); + const dest = resolve2(destDir, rel2); if (dest !== root && !dest.startsWith(root + sep2)) { throw new Error(`tar entry escapes destination: ${entry.name}`); } @@ -15546,11 +15725,11 @@ function installGrammarCacheAtomically(tempDir, cacheDir, markerPath, expectedSh let markerInstalled = false; try { if (expectedSha256) writeFileSync(nextMarker, expectedSha256 + "\n"); - if (existsSync4(cacheDir)) { + if (existsSync5(cacheDir)) { rename(cacheDir, previousCache); cacheBackedUp = true; } - if (existsSync4(markerPath)) { + if (existsSync5(markerPath)) { rename(markerPath, previousMarker); markerBackedUp = true; } @@ -15569,10 +15748,10 @@ function installGrammarCacheAtomically(tempDir, cacheDir, markerPath, expectedSh rollbackErrors.push(rollback); } }; - if (markerInstalled && existsSync4(markerPath)) attempt(() => rmSync(markerPath, { force: true })); - if (cacheInstalled && existsSync4(cacheDir)) attempt(() => rmSync(cacheDir, { recursive: true, force: true })); - if (markerBackedUp && existsSync4(previousMarker)) attempt(() => rename(previousMarker, markerPath)); - if (cacheBackedUp && existsSync4(previousCache)) attempt(() => rename(previousCache, cacheDir)); + if (markerInstalled && existsSync5(markerPath)) attempt(() => rmSync(markerPath, { force: true })); + if (cacheInstalled && existsSync5(cacheDir)) attempt(() => rmSync(cacheDir, { recursive: true, force: true })); + if (markerBackedUp && existsSync5(previousMarker)) attempt(() => rename(previousMarker, markerPath)); + if (cacheBackedUp && existsSync5(previousCache)) attempt(() => rename(previousCache, cacheDir)); if (rollbackErrors.length === 0) { try { rmSync(swapDir, { recursive: true, force: true }); @@ -15607,7 +15786,7 @@ async function pullGrammars(cacheDir, opts = {}) { } const runtime = join6(cacheDir, "web-tree-sitter.wasm"); const markerPath = join6(dirname3(cacheDir), `${ENGINE_VERSION}.sha256`); - if (existsSync4(runtime) && expected && existsSync4(markerPath)) { + if (existsSync5(runtime) && expected && existsSync5(markerPath)) { let marker = ""; try { marker = readFileSync5(markerPath, "utf8").trim(); @@ -15637,7 +15816,7 @@ async function pullGrammars(cacheDir, opts = {}) { mkdirSync(dirname3(cacheDir), { recursive: true }); tmp = mkdtempSync(join6(dirname3(cacheDir), ".grammars-tmp-")); extractGrammarsTarball(bytes, tmp); - if (!existsSync4(join6(tmp, "web-tree-sitter.wasm"))) { + if (!existsSync5(join6(tmp, "web-tree-sitter.wasm"))) { throw new Error("archive is missing web-tree-sitter.wasm"); } installGrammarCacheAtomically(tmp, cacheDir, markerPath, expected); @@ -15717,7 +15896,7 @@ init_graph_json(); init_types(); init_walk(); init_sort(); -import { join as join15 } from "path"; +import { join as join14 } from "path"; var Bytes = class { buf; len = 0; @@ -15931,7 +16110,7 @@ function renderScip(scan2, opts = {}) { }; const documents = []; for (const f of docs) { - const text = readText(join15(scan2.root, f.rel)); + const text = readText(join14(scan2.root, f.rel)); const lines = text.split("\n").map((l) => l.endsWith("\r") ? l.slice(0, -1) : l); const locate = (lineNo, name2) => { const line = lines[lineNo - 1]; @@ -16029,6 +16208,45 @@ init_viz(); // src/traverse.ts init_sort(); var DEPENDS_KINDS = /* @__PURE__ */ new Set(["import", "use", "call"]); +var dependentsMemo = /* @__PURE__ */ new WeakMap(); +function dependentsOf(edges) { + const hit = dependentsMemo.get(edges); + if (hit && hit.length === edges.length) return hit.map; + const map = /* @__PURE__ */ new Map(); + for (const e of edges) { + if (e.dangling || !DEPENDS_KINDS.has(e.kind)) continue; + let arr = map.get(e.to); + if (!arr) map.set(e.to, arr = []); + arr.push(e); + } + for (const arr of map.values()) arr.sort((a, b) => byStr(a.from, b.from)); + dependentsMemo.set(edges, { length: edges.length, map }); + return map; +} +var adjacencyMemo = /* @__PURE__ */ new WeakMap(); +function adjacencyOf(edges, kinds) { + const viewKey = kinds ? [...kinds].sort(byStr).join(",") : "*"; + let entry = adjacencyMemo.get(edges); + if (!entry || entry.length !== edges.length) adjacencyMemo.set(edges, entry = { length: edges.length, views: /* @__PURE__ */ new Map() }); + const cached = entry.views.get(viewKey); + if (cached) return cached; + const out2 = /* @__PURE__ */ new Map(); + const inn = /* @__PURE__ */ new Map(); + const degree = /* @__PURE__ */ new Map(); + for (const e of edges) { + if (e.dangling) continue; + if (kinds && !kinds.has(e.kind)) continue; + (out2.get(e.from) ?? out2.set(e.from, []).get(e.from)).push(e); + (inn.get(e.to) ?? inn.set(e.to, []).get(e.to)).push(e); + degree.set(e.from, (degree.get(e.from) ?? 0) + 1); + degree.set(e.to, (degree.get(e.to) ?? 0) + 1); + } + for (const arr of out2.values()) arr.sort((a, b) => byStr(a.to, b.to)); + for (const arr of inn.values()) arr.sort((a, b) => byStr(a.from, b.from)); + const adj = { out: out2, inn, degree, threshold: hubThreshold([...degree.values()]) }; + entry.views.set(viewKey, adj); + return adj; +} function hubThreshold(degrees) { const sorted = degrees.slice().sort((a, b) => a - b); const n = sorted.length; @@ -16036,20 +16254,14 @@ function hubThreshold(degrees) { return Math.max(50, p99); } function reverseClosure(edges, seeds, depth = Infinity) { - const dependents = /* @__PURE__ */ new Map(); - for (const e of edges) { - if (e.dangling || !DEPENDS_KINDS.has(e.kind)) continue; - let arr = dependents.get(e.to); - if (!arr) dependents.set(e.to, arr = []); - arr.push(e); - } + const dependents = dependentsOf(edges); const depthOf = /* @__PURE__ */ new Map(); const seen = new Set(seeds); let frontier = [...seeds]; for (let d = 1; d <= depth && frontier.length; d++) { const next = []; for (const node of frontier) { - for (const e of (dependents.get(node) ?? []).slice().sort((a, b) => byStr(a.from, b.from))) { + for (const e of dependents.get(node) ?? []) { if (seen.has(e.from)) continue; seen.add(e.from); depthOf.set(e.from, d); @@ -16072,18 +16284,7 @@ function impactOf(graph, target, depth = Infinity) { return { target, scope: mod ? "module" : "file", seeds, files, modules }; } function bfs(edges, start2, depth, kinds) { - const out2 = /* @__PURE__ */ new Map(); - const inn = /* @__PURE__ */ new Map(); - const degree = /* @__PURE__ */ new Map(); - for (const e of edges) { - if (e.dangling) continue; - if (kinds && !kinds.has(e.kind)) continue; - (out2.get(e.from) ?? out2.set(e.from, []).get(e.from)).push(e); - (inn.get(e.to) ?? inn.set(e.to, []).get(e.to)).push(e); - degree.set(e.from, (degree.get(e.from) ?? 0) + 1); - degree.set(e.to, (degree.get(e.to) ?? 0) + 1); - } - const threshold = hubThreshold([...degree.values()]); + const { out: out2, inn, degree, threshold } = adjacencyOf(edges, kinds); const seen = /* @__PURE__ */ new Set([start2]); const links = []; let frontier = [start2]; @@ -16091,13 +16292,13 @@ function bfs(edges, start2, depth, kinds) { const next = []; for (const node of frontier) { if (node !== start2 && (degree.get(node) ?? 0) >= threshold) continue; - for (const e of (out2.get(node) ?? []).slice().sort((a, b) => byStr(a.to, b.to))) { + for (const e of out2.get(node) ?? []) { if (seen.has(e.to)) continue; links.push({ node: e.to, direction: "out", kind: e.kind, weight: e.weight, depth: d, confidence: e.confidence }); seen.add(e.to); next.push(e.to); } - for (const e of (inn.get(node) ?? []).slice().sort((a, b) => byStr(a.from, b.from))) { + for (const e of inn.get(node) ?? []) { if (seen.has(e.from)) continue; links.push({ node: e.from, direction: "in", kind: e.kind, weight: e.weight, depth: d, confidence: e.confidence }); seen.add(e.from); @@ -16417,8 +16618,8 @@ init_util(); init_types(); init_types(); init_loader(); -import { existsSync as existsSync10, mkdirSync as mkdirSync3, readFileSync as readFileSync13, statSync as statSync9, writeFileSync as writeFileSync4 } from "fs"; -import { join as join23, resolve as resolve4 } from "path"; +import { existsSync as existsSync11, mkdirSync as mkdirSync3, readFileSync as readFileSync13, statSync as statSync9, writeFileSync as writeFileSync4 } from "fs"; +import { join as join22, resolve as resolve5 } from "path"; init_pipeline(); init_hash(); init_graph_json(); @@ -16568,6 +16769,7 @@ Flags (accepted before OR after the subcommand: '--repo X scan' and --no-gitignore Do not honor .gitignore files (default: honored) --ignore-dir Directory names to skip (repeatable) \u2014 REPLACES the default ignored-directory set, never merges with it + (\`.git\` stays skipped regardless) --max-files Cap walked files (default: none \u2014 the whole tree is indexed; a cap sets the \`capped\` flag) --max-bytes Skip files above this size (default 1 MiB) @@ -16622,10 +16824,10 @@ function parseFlags(args2) { if (!Number.isFinite(n) || n <= 0) throw new Error(`${a} expects a positive number, got "${raw}"`); return n; }; - if (a === "--repo") flags2.repo = resolve4(next()); + if (a === "--repo") flags2.repo = resolve5(next()); else if (a === "--out") { const v = next(); - flags2.out = v === "-" ? "-" : resolve4(v); + flags2.out = v === "-" ? "-" : resolve5(v); } else if (a === "--project-root") flags2.projectRoot = next(); else if (a === "--include") flags2.include.push(next()); else if (a === "--exclude") flags2.exclude.push(next()); @@ -16650,7 +16852,7 @@ function parseFlags(args2) { if (!Number.isInteger(n) || n < 0) throw new Error(`--workers expects a non-negative integer, got "${raw}"`); flags2.workers = n; } else if (a === "--since") flags2.since = next(); - else if (a === "--config") flags2.config = resolve4(next()); + else if (a === "--config") flags2.config = resolve5(next()); else if (a === "--limit") flags2.limit = num2(); else if (a === "--no-fuzzy") flags2.fuzzy = false; else if (a === "--exact") flags2.exact = true; @@ -16709,7 +16911,7 @@ function parseMcpFlags(argv) { if (a === "--repo") { const v = argv[++i2]; if (!v) throw new Error("--repo requires a directory"); - defaultRepo = resolve4(v); + defaultRepo = resolve5(v); } else if (a === "--server-name") { const v = argv[++i2]; if (!v) throw new Error("--server-name requires a value"); @@ -16730,7 +16932,7 @@ function parseMcpFlags(argv) { throw new Error(`unknown flag for \`mcp\`: ${a}`); } } - if (defaultRepo && !existsSync10(defaultRepo)) throw new Error(`--repo path does not exist: ${defaultRepo}`); + if (defaultRepo && !existsSync11(defaultRepo)) throw new Error(`--repo path does not exist: ${defaultRepo}`); if (watch && !defaultRepo) throw new Error("--watch requires --repo "); return { defaultRepo, serverInfo: name2 ? { name: name2 } : void 0, maxResponseBytes, profile, watch }; } @@ -16806,7 +17008,7 @@ async function runCli(rawArgv) { return; } const flags2 = parseFlags(rest); - if (!existsSync10(flags2.repo)) throw new Error(`--repo path does not exist: ${flags2.repo}`); + if (!existsSync11(flags2.repo)) throw new Error(`--repo path does not exist: ${flags2.repo}`); if (!statSync9(flags2.repo).isDirectory()) throw new Error(`--repo path is not a directory: ${flags2.repo}`); const scans = !SCANLESS_COMMANDS.has(cmd) && !(cmd === "embed" && flags2.positional !== "build"); let precomputedWalk; @@ -16833,7 +17035,12 @@ async function runCli(rawArgv) { if (preloadTried) return preloaded; preloadTried = true; if (flags2.noIndexCache) return void 0; - preloadPromise = preloadSessionLazy(flags2.repo, scanOptions(flags2, precomputedWalk), warmPresentGrammars, indexDir).then((p) => { + preloadPromise = preloadSessionLazy( + flags2.repo, + { ...scanOptions(flags2, precomputedWalk), workers: flags2.workers }, + warmPresentGrammars, + indexDir + ).then((p) => { if (p) preloaded = { scan: p.scan, arts: p.arts, loadArtifacts: p.loadArtifacts }; return preloaded; }); @@ -16861,7 +17068,7 @@ async function runCli(rawArgv) { if (!flags2.out) throw new Error("index needs --out "); const outDir = flags2.out; mkdirSync3(outDir, { recursive: true }); - const cachePath = join23(outDir, "cache.json"); + const cachePath = join22(outDir, "cache.json"); let cache; let meta = {}; try { @@ -16887,9 +17094,9 @@ async function runCli(rawArgv) { }); const modelDir = resolveEmbedModelDir(flags2.repo); const model = modelDir ? loadEmbedModel(modelDir) : void 0; - const graphPath = join23(outDir, "graph.json"); - const symbolsPath = join23(outDir, "symbols.json"); - const embedPath = join23(outDir, "embeddings.bin"); + const graphPath = join22(outDir, "graph.json"); + const symbolsPath = join22(outDir, "symbols.json"); + const embedPath = join22(outDir, "embeddings.bin"); const artifactSha = (path) => { try { return sha1(readFileSync13(path)); @@ -16965,7 +17172,7 @@ async function runCli(rawArgv) { } else if (cmd === "scip") { const scan2 = await readScan(); const bytes = renderScip(scan2, { projectRoot: flags2.projectRoot }); - const out2 = flags2.out ?? resolve4("index.scip"); + const out2 = flags2.out ?? resolve5("index.scip"); if (out2 === "-") process.stdout.write(Buffer.from(bytes)); else { writeFileSync4(out2, bytes); @@ -17118,14 +17325,14 @@ async function runCli(rawArgv) { mkdirSync3(flags2.out, { recursive: true }); const scan2 = await readScan(); const index = buildEmbeddingIndex(scan2, model); - writeFileSync4(join23(flags2.out, "embeddings.bin"), serializeEmbeddings(index)); + writeFileSync4(join22(flags2.out, "embeddings.bin"), serializeEmbeddings(index)); process.stderr.write(`codeindex: ${index.records.length} embedding records \u2192 ${flags2.out}/embeddings.bin (model ${model.modelId}) `); } else if (sub === "pull") { const { url, sha256 } = resolveEmbedPullUrl(); - const destDir = process.env.CODEINDEX_EMBED_DIR ?? join23(flags2.repo, ".codeindex", "models"); + const destDir = process.env.CODEINDEX_EMBED_DIR ?? join22(flags2.repo, ".codeindex", "models"); mkdirSync3(destDir, { recursive: true }); - process.stderr.write(`codeindex: fetching model from ${url} \u2192 ${join23(destDir, "model.json")} + process.stderr.write(`codeindex: fetching model from ${url} \u2192 ${join22(destDir, "model.json")} `); let body2; try { @@ -17146,8 +17353,8 @@ async function runCli(rawArgv) { process.exitCode = 1; return; } - writeFileSync4(join23(destDir, "model.json"), body2); - process.stderr.write(`codeindex: model written to ${join23(destDir, "model.json")} + writeFileSync4(join22(destDir, "model.json"), body2); + process.stderr.write(`codeindex: model written to ${join22(destDir, "model.json")} `); } else { throw new Error("embed needs a subcommand: status | build | pull | serve"); @@ -17161,7 +17368,7 @@ async function runCli(rawArgv) { const cacheDir = sharedGrammarsCacheDir(); if (sub === "status") { const info2 = resolveGrammarsTier(); - const present = (name2) => info2.dirs.some((d) => existsSync10(join23(d, name2))); + const present = (name2) => info2.dirs.some((d) => existsSync11(join22(d, name2))); const runtimePresent = present("web-tree-sitter.wasm"); const target = resolveGrammarsPullTarget(); const resolvedIn = (keys) => [...keys].filter((k) => present(`${k}.wasm`)).sort(); diff --git a/src/ast/extract.ts b/src/ast/extract.ts index f7f19e6..4b35481 100644 --- a/src/ast/extract.ts +++ b/src/ast/extract.ts @@ -108,6 +108,28 @@ const REGEX_NODE = /(^|_)(regex|regular_expression)(_pattern|_literal)?$/; // concatenated source is not a value anything else can equal — storing it // would invent duplications that do not exist. const STRING_PART = /(^|_)(fragment|content|escape_sequence|character)$/; + +// Type-class bits for collectAll's visitor, memoized per node type (see +// typeFlagsOf). The regexes above stay the single source of truth. +const T_REF_IDENT = 1; +const T_COMMENT = 2; +const T_STRING = 4; +const T_NUMBER = 8; +const T_REGEX = 16; +const typeFlags = new Map(); +function typeFlagsOf(type: string): number { + let flags = typeFlags.get(type); + if (flags === undefined) { + flags = + (REF_IDENT_TYPE.test(type) ? T_REF_IDENT : 0) | + (COMMENT_NODE.test(type) ? T_COMMENT : 0) | + (STRING_NODE.test(type) ? T_STRING : 0) | + (NUMBER_NODE.test(type) ? T_NUMBER : 0) | + (REGEX_NODE.test(type) ? T_REGEX : 0); + typeFlags.set(type, flags); + } + return flags; +} function isPlainString(node: TSNode): boolean { return node.namedChildren.every((c) => STRING_PART.test(c.type)); } @@ -164,17 +186,21 @@ function collectAll( const visit = (node: TSNode): void => { const type = node.type; const kids = node.namedChildren; + // The five type-class tests below are pure functions of the node type, and + // a grammar has a few hundred types at most — memoized once per type + // instead of five regex runs on every node of every file. + const flags = typeFlagsOf(type); // --- distinctive referenced identifiers (leaves only) --- - if (kids.length === 0 && REF_IDENT_TYPE.test(type)) { + if (kids.length === 0 && flags & T_REF_IDENT) { const text = node.text; if (REF_IDENT_TEXT.test(text) && !defNames.has(text)) identsFound.add(text); } // --- prose: comments and short string literals --- - if (COMMENT_NODE.test(type)) { + if (flags & T_COMMENT) { for (const line of node.text.split(/\r?\n/)) addTerms(stripCommentMarkers(line)); - } else if (kids.length === 0 && STRING_NODE.test(type) && node.endIndex - node.startIndex <= MAX_LITERAL_LEN) { + } else if (kids.length === 0 && flags & T_STRING && node.endIndex - node.startIndex <= MAX_LITERAL_LEN) { addTerms(node.text.replace(/^['"`]+|['"`]+$/g, "")); } @@ -184,10 +210,10 @@ function collectAll( // lives in a `string_fragment` child, so a leaf-only guard sees no strings // at all in the very languages this analysis is most needed for. if (!literals.full) { - const line = node.startPosition.row + 1; - if (STRING_NODE.test(type) && isPlainString(node)) literals.addString(node.text, line); - else if (kids.length === 0 && NUMBER_NODE.test(type)) literals.add("number", node.text.trim(), line); - else if (REGEX_NODE.test(type)) literals.add("regex", node.text, line); + if (flags & T_STRING) { + if (isPlainString(node)) literals.addString(node.text, node.startPosition.row + 1); + } else if (kids.length === 0 && flags & T_NUMBER) literals.add("number", node.text.trim(), node.startPosition.row + 1); + else if (flags & T_REGEX) literals.add("regex", node.text, node.startPosition.row + 1); } // --- call sites --- diff --git a/src/centrality.ts b/src/centrality.ts index d0ddc2c..feb7ef5 100644 --- a/src/centrality.ts +++ b/src/centrality.ts @@ -83,15 +83,33 @@ export function betweennessOf(ids: string[], edges: Edge[]): Map } const adj = nbSets.map((s) => [...s].sort((x, y) => x - y)); - const cb = new Array(n).fill(0); + const cb = new Float64Array(n); + // Per-source scratch, allocated ONCE. The previous per-source `new Array(n)` + // ×3 plus n fresh predecessor arrays made Brandes O(n²) in allocations AND + // in initialisation, whatever the graph looks like — and an import graph is + // mostly small components, so a source's BFS touches a few dozen nodes + // while its setup touched all 3 000. Only the nodes a BFS visited (`stack`) + // are reset for the next source, so each source costs its component, not + // the graph. Float64Array holds exactly the doubles the plain arrays held, + // and every accumulation runs in the same order, so scores are bit-identical. + const stack: number[] = []; + const queue: number[] = []; + const pred: number[][] = Array.from({ length: n }, () => []); + const sigma = new Float64Array(n); + const dist = new Int32Array(n).fill(-1); + const delta = new Float64Array(n); for (let s = 0; s < n; s++) { - const stack: number[] = []; - const pred: number[][] = Array.from({ length: n }, () => []); - const sigma = new Array(n).fill(0); - const dist = new Array(n).fill(-1); + for (const v of stack) { + sigma[v] = 0; + dist[v] = -1; + delta[v] = 0; + pred[v]!.length = 0; + } + stack.length = 0; + queue.length = 0; sigma[s] = 1; dist[s] = 0; - const queue: number[] = [s]; + queue.push(s); for (let qi = 0; qi < queue.length; qi++) { const v = queue[qi]!; stack.push(v); @@ -106,7 +124,6 @@ export function betweennessOf(ids: string[], edges: Edge[]): Map } } } - const delta = new Array(n).fill(0); for (let si = stack.length - 1; si >= 0; si--) { const w = stack[si]!; for (const v of pred[w]!) delta[v]! += (sigma[v]! / sigma[w]!) * (1 + delta[w]!); diff --git a/src/deadcode.ts b/src/deadcode.ts index 4d74dd8..87f4dea 100644 --- a/src/deadcode.ts +++ b/src/deadcode.ts @@ -36,7 +36,12 @@ export function findDeadCode(scan: RepoScan): DeadSymbol[] { for (const f of scan.files) { for (const s of f.symbols) { if (!consider(s)) continue; - const entry = callers.get(s.name) ?? callers.get(`${s.name}@${s.file}`); + // The qualified key FIRST: when several files export the same name, the + // bare key holds the first-sorted def's entry, and the others live under + // "name@file" only. Looking the bare key up first would answer with a + // homonym from another file, fail the file check below, and flag a + // symbol that IS called as dead. + const entry = callers.get(`${s.name}@${s.file}`) ?? callers.get(s.name); const hasCallers = !!entry && entry.def.file === s.file && entry.callers.length > 0; if (hasCallers) continue; const referenced = (refs.get(s.name)?.size ?? 0) > 0; diff --git a/src/derived.ts b/src/derived.ts index 0e5a05d..9818e8c 100644 --- a/src/derived.ts +++ b/src/derived.ts @@ -54,6 +54,19 @@ interface DerivedCache { symbolGraph?: SymbolGraph; fileComplexity?: Map; // rel → whole-file branch count + 1 (code files) importPagerank?: Map; // rel → PageRank over the resolved import graph + docMentions?: Map; // doc rel → unique symbol names it mentions, with counts + identSets?: Map>; // code rel → its distinctive identifiers, as a Set +} + +export interface DocMentions { + // name → occurrences, in first-occurrence order (the order both consumers + // iterated the raw token stream in). + counts: Map; + // True when the text came from the scan's retained docText; false when it + // had to be re-read from disk. The graph's mention pass accepts both, the + // symbol-refs pass only retained text — the split each consumer applied + // when it tokenized on its own. + retained: boolean; } const caches = new WeakMap(); @@ -137,6 +150,44 @@ export function symbolRefsFor(scan: RepoScan): Map> { return (c.symbolRefs ??= computeSymbolRefs(scan)); } +// Which unique symbol names each doc file mentions, tokenized ONCE per scan. +// buildGraph (mention edges) and computeSymbolRefs (symbols.json refs) both +// split every doc on the same non-identifier regex and looked each token up +// in the same unique-defs map; this shares that pass. Only names present in +// uniqueDefsFor(scan) are kept — the only tokens either consumer ever used. +export function docMentionsFor(scan: RepoScan): Map { + const c = cacheFor(scan); + if (c.docMentions) return c.docMentions; + const unique = uniqueDefsFor(scan); + const out = new Map(); + if (unique.size) { + for (const f of scan.files) { + if (f.kind !== "doc") continue; + const retained = scan.docText.get(f.rel); + // Fall back to disk only when a doc somehow was not retained — the + // graph's mention pass always did; the refs pass records the miss. + const content = retained ?? readText(join(scan.root, f.rel)); + if (!content) continue; + const counts = new Map(); + for (const tok of content.split(/[^A-Za-z0-9_]+/)) { + if (unique.has(tok)) counts.set(tok, (counts.get(tok) ?? 0) + 1); + } + out.set(f.rel, { counts, retained: retained !== undefined }); + } + } + return (c.docMentions = out); +} + +// Each code file's distinctive identifiers as a Set — findReferences tested +// membership with Array.includes on every file for every query. +export function identSetsFor(scan: RepoScan): Map> { + const c = cacheFor(scan); + if (c.identSets) return c.identSets; + const out = new Map>(); + for (const f of scan.files) if (f.kind === "code" && f.idents?.length) out.set(f.rel, new Set(f.idents)); + return (c.identSets = out); +} + // Default (precision) caller index only. Recall-mode indexes are option- // dependent and stay unmemoized on buildCallerIndex's public path. export function callerIndexFor(scan: RepoScan): CallerIndex { diff --git a/src/engine-cli.ts b/src/engine-cli.ts index a7ffc63..0bc6c35 100644 --- a/src/engine-cli.ts +++ b/src/engine-cli.ts @@ -169,6 +169,7 @@ Flags (accepted before OR after the subcommand: '--repo X scan' and --no-gitignore Do not honor .gitignore files (default: honored) --ignore-dir Directory names to skip (repeatable) — REPLACES the default ignored-directory set, never merges with it + (\`.git\` stays skipped regardless) --max-files Cap walked files (default: none — the whole tree is indexed; a cap sets the \`capped\` flag) --max-bytes Skip files above this size (default 1 MiB) @@ -559,7 +560,12 @@ export async function runCli(rawArgv: string[]): Promise { if (preloadTried) return preloaded; preloadTried = true; if (flags.noIndexCache) return undefined; - preloadPromise = preloadSessionLazy(flags.repo, scanOptions(flags, precomputedWalk), warmPresentGrammars, indexDir).then((p) => { + preloadPromise = preloadSessionLazy( + flags.repo, + { ...scanOptions(flags, precomputedWalk), workers: flags.workers }, + warmPresentGrammars, + indexDir, + ).then((p) => { if (p) preloaded = { scan: p.scan, arts: p.arts, loadArtifacts: p.loadArtifacts }; return preloaded; }); diff --git a/src/graph.ts b/src/graph.ts index 14ed6ff..5390a00 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -1,4 +1,3 @@ -import { join } from "node:path"; import { ENGINE_VERSION, SCHEMA_VERSION } from "./types.js"; import type { Edge, FileNode, Graph, ModuleNode } from "./types.js"; import type { RepoScan } from "./scan.js"; @@ -6,8 +5,7 @@ import type { ModuleInfo } from "./modules.js"; import { resolveDocLink, resolveImport, type ResolveContext } from "./resolve.js"; import { resolveCallEdges } from "./calls.js"; import { resolveRelationEdges } from "./relations.js"; -import { publishImportPairs, uniqueDefsFor } from "./derived.js"; -import { readText } from "./walk.js"; +import { docMentionsFor, publishImportPairs, uniqueDefsFor } from "./derived.js"; import { byStr } from "./sort.js"; // A symbol name distinctive enough to anchor a doc→code "mention" edge without @@ -157,20 +155,13 @@ export function buildGraph( } } if (unique.size) { - for (const f of scan.files) { - if (f.kind !== "doc") continue; - // Reuse the content the scan already read (falling back to disk only if a - // doc somehow was not retained) — no second read of every doc file. - const content = scan.docText.get(f.rel) ?? readText(join(scan.root, f.rel)); - if (!content) continue; - const tokens = new Map(); - for (const tok of content.split(/[^A-Za-z0-9_]+/)) { - if (unique.has(tok)) tokens.set(tok, (tokens.get(tok) ?? 0) + 1); - } - for (const [name, count] of tokens) { + // Doc tokens come from the per-scan memo (src/derived.ts): the retained + // docText, tokenized once and shared with the symbols.json refs pass. + for (const [rel, { counts }] of docMentionsFor(scan)) { + for (const [name, count] of counts) { const target = unique.get(name)!; - if (target === f.rel) continue; - collect(fileEdgeMap, { from: f.rel, to: target, kind: "mention", weight: Math.min(count, 5) }); + if (target === rel) continue; + collect(fileEdgeMap, { from: rel, to: target, kind: "mention", weight: Math.min(count, 5) }); } } } diff --git a/src/lang/common.ts b/src/lang/common.ts index 89237b7..3f291f8 100644 --- a/src/lang/common.ts +++ b/src/lang/common.ts @@ -89,35 +89,52 @@ const REEXPORT_EXTS = new Set([".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".m // Template literals are treated as plain strings: an `${…}` expression cannot // legally contain an unterminated comment, so nesting adds nothing here. export function blankComments(src: string): string { - const out = src.split(""); - let i = 0; + // One pass over char codes, copying the kept stretches as slices and the + // comments as runs of spaces (newlines inside a block comment are kept so + // offsets AND line numbers survive). The previous per-character + // `split("")`/`join("")` allocated one string per byte of every file — the + // single largest non-parser cost of extraction. const n = src.length; + let out = ""; + let kept = 0; // start of the stretch not yet copied into `out` + let i = 0; while (i < n) { - const c = src[i]!; - const next = src[i + 1]; - if (c === "/" && next === "/") { - while (i < n && src[i] !== "\n") { - out[i] = " "; - i++; + const c = src.charCodeAt(i); + if (c === SLASH) { + const next = src.charCodeAt(i + 1); + if (next === SLASH) { + out += src.slice(kept, i); + const start = i; + while (i < n && src.charCodeAt(i) !== NEWLINE) i++; + out += " ".repeat(i - start); + kept = i; + continue; } - continue; - } - if (c === "/" && next === "*") { - while (i < n && !(src[i] === "*" && src[i + 1] === "/")) { - if (src[i] !== "\n") out[i] = " "; - i++; + if (next === STAR) { + out += src.slice(kept, i); + let run = 0; + while (i < n && !(src.charCodeAt(i) === STAR && src.charCodeAt(i + 1) === SLASH)) { + if (src.charCodeAt(i) === NEWLINE) { + out += " ".repeat(run) + "\n"; + run = 0; + } else run++; + i++; + } + // Blank the closing delimiter too, or `*/` would read as code. + if (i < n) run++; + if (i + 1 < n) run++; + out += " ".repeat(run); + i += 2; + kept = Math.min(i, n); + continue; } - // Blank the closing delimiter too, or `*/` would read as code. - if (i < n) out[i] = " "; - if (i + 1 < n) out[i + 1] = " "; - i += 2; + i++; continue; } - if (c === '"' || c === "'" || c === "`") { - const quote = c; + if (c === DQUOTE || c === SQUOTE || c === BACKTICK) { i++; - while (i < n && src[i] !== quote) { - if (src[i] === "\\") i++; // skip the escaped char + while (i < n && src.charCodeAt(i) !== c) { + if (src.charCodeAt(i) === BACKSLASH) i++; // skip the escaped char i++; } i++; @@ -125,9 +142,17 @@ export function blankComments(src: string): string { } i++; } - return out.join(""); + return kept === 0 ? src : out + src.slice(kept); } +const SLASH = 47; // "/" +const STAR = 42; // "*" +const NEWLINE = 10; // "\n" +const DQUOTE = 34; // '"' +const SQUOTE = 39; // "'" +const BACKTICK = 96; // "`" +const BACKSLASH = 92; // "\\" + // Per-file re-export ceiling. Raised from 60: this engine's own public barrel // (src/engine.ts) declares ~200 names, so 60 hid two thirds of its API — and it // hid them SILENTLY, which is the one thing the walk's `capped` doctrine forbids. @@ -160,7 +185,25 @@ export function extractReexports(rel: string, content: string, localSymbols: Cod const lang = /\.(ts|tsx|mts|cts)$/.test(rel) ? "typescript" : "javascript"; const out: CodeSymbol[] = []; const seen = new Set(); - const lineAt = (idx: number): number => content.slice(0, idx).split(/\r?\n/).length; + // 1-based line of a character offset. Line starts are computed lazily, once + // per file — the previous `slice(0, idx).split(...)` re-scanned the whole + // prefix for every re-exported name, quadratic on a 200-name barrel. + let lineStarts: number[] | undefined; + const lineAt = (idx: number): number => { + if (!lineStarts) { + lineStarts = [0]; + for (let i = 0; i < content.length; i++) if (content.charCodeAt(i) === 10) lineStarts.push(i + 1); + } + // Binary search: number of line starts ≤ idx. + let lo = 0; + let hi = lineStarts.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (lineStarts[mid]! <= idx) lo = mid + 1; + else hi = mid; + } + return lo; + }; // Keyed on the whole CodeSymbol (not just kind) so the alias branch below // can also cite the resolved declaration's own line/endLine, not just mirror // its kind. diff --git a/src/literals.ts b/src/literals.ts index 5927ff6..b74df73 100644 --- a/src/literals.ts +++ b/src/literals.ts @@ -115,7 +115,23 @@ function isFunctionValued(signature: string | undefined): boolean { return false; } -function holderFor(symbols: CodeSymbol[], line: number): CodeSymbol | undefined { +// A file's symbols that can hold a literal at all — the kind, function-valued +// and span filters are properties of the SYMBOL, so they are applied once per +// file here rather than once per (literal × symbol) inside holderFor, which +// ran the signature regex L×S times on a file with L literals and S symbols. +// Order is preserved, so holderFor's innermost-wins tie-break is unchanged. +function holderCandidates(symbols: CodeSymbol[]): CodeSymbol[] { + const out: CodeSymbol[] = []; + for (const s of symbols) { + if (!HOLDER_KINDS.has(s.kind)) continue; + if (isFunctionValued(s.signature)) continue; + if ((s.endLine ?? s.line) - s.line > MAX_HOLDER_SPAN) continue; + out.push(s); + } + return out; +} + +function holderFor(candidates: CodeSymbol[], line: number): CodeSymbol | undefined { // A literal sitting inside a constant's declaration span IS that constant's // value. This span join needs no new extraction: both tiers already report a // symbol's line, and the AST tier reports endLine. It is also why the feature @@ -130,11 +146,8 @@ function holderFor(symbols: CodeSymbol[], line: number): CodeSymbol | undefined // fact that a helper already exists. `holderExported` keeps the distinction // visible instead of encoding it as absence. let best: CodeSymbol | undefined; - for (const s of symbols) { - if (!HOLDER_KINDS.has(s.kind)) continue; - if (isFunctionValued(s.signature)) continue; + for (const s of candidates) { const end = s.endLine ?? s.line; - if (end - s.line > MAX_HOLDER_SPAN) continue; if (line < s.line || line > end) continue; // Innermost wins: a const nested in an exported object literal is the // tighter holder. @@ -154,13 +167,14 @@ export function findLiteralDuplications(scan: RepoScan, opts: LiteralsOptions = for (const f of scan.files) { if (!f.literals?.length) continue; if (!opts.includeTests && isTestPath(f.rel)) continue; + let holders: CodeSymbol[] | undefined; // this file's holder candidates, built on first use for (const lit of f.literals) { if (opts.kinds && !opts.kinds.has(lit.kind)) continue; if (!isDistinctive(lit.value, lit.kind)) continue; const key = `${lit.kind}\u0000${lit.value}`; let g = groups.get(key); if (!g) groups.set(key, (g = { value: lit.value, kind: lit.kind, sites: [] })); - const holder = holderFor(f.symbols, lit.line); + const holder = holderFor((holders ??= holderCandidates(f.symbols)), lit.line); g.sites.push( holder ? { file: f.rel, line: lit.line, holder: holder.name, holderExported: holder.exported } diff --git a/src/pool.ts b/src/pool.ts index 81d26f5..6dab40d 100644 --- a/src/pool.ts +++ b/src/pool.ts @@ -153,67 +153,145 @@ export async function extractInParallel( // whole run back to sequential — losing parallelism on exactly the tier where // it is cheapest. const wanted = grammarKeys.filter((k) => grammarReady(k)).sort(); + const workers = Math.min(count, jobs.length); - // Round-robin over the path-sorted job list, so every shard sees the same - // language mix and no shard loads a grammar the others don't. - const shards: Job[][] = Array.from({ length: Math.min(count, jobs.length) }, () => []); - jobs.forEach((j, i) => shards[i % shards.length]!.push(j)); - + // Jobs are handed out in BATCHES, on demand, from the path-sorted queue — + // not pre-split into one static shard per worker. Static shards assume equal + // workers; on a heterogeneous CPU (Apple's 4 performance + 6 efficiency + // cores, most laptops today) the shards that land on slow cores finish + // last and the whole index waits for them: measured on a 2 358-file repo, + // eight equal shards ran at 1 ms/file each where one worker alone managed + // 0.45 ms/file, and eight workers barely beat four. A worker that finishes + // its batch simply asks for the next, so fast cores take more of the queue. + // Batches shrink as the queue drains (guided scheduling) so the tail is at + // most one small batch on the slowest core. Records are keyed by path and + // scanRepo orders them, so WHICH worker built a record never shows. + // + // The bootstrap warms the grammars once (an empty batch), announces the set + // it got ready, then extracts each batch it is sent through the SAME + // runExtractWorker a one-shot worker used — the per-record contract has not + // moved. const bootstrap = `import { runExtractWorker } from ${JSON.stringify(engineUrl)};\n` + `import { parentPort, workerData } from "node:worker_threads";\n` + - `runExtractWorker(workerData.input, (o) => parentPort.postMessage(o))` + - `.catch((e) => parentPort.postMessage({ error: String(e) }));\n`; + `const base = workerData.input;\n` + + `const post = (o) => parentPort.postMessage(o);\n` + + `const fail = (e) => post({ error: String(e) });\n` + + `runExtractWorker({ ...base, jobs: [] }, post).then(() => {\n` + + ` parentPort.on("message", (m) => {\n` + + ` if (m.done) { parentPort.close(); return; }\n` + + ` runExtractWorker({ ...base, jobs: m.jobs }, post).catch(fail);\n` + + ` });\n` + + `}).catch(fail);\n`; + const out = new Map(); + let next = 0; // index of the first job not yet dispatched + const takeBatch = (): Job[] => { + const remaining = jobs.length - next; + if (remaining <= 0) return []; + const size = Math.max(MIN_BATCH_JOBS, Math.ceil(remaining / (workers * BATCHES_PER_WORKER))); + const batch = jobs.slice(next, next + size); + next += batch.length; + return batch; + }; + + const spawned: Worker[] = []; try { - const outputs = await Promise.all( - shards.map( - (jobsForShard) => - new Promise((resolve, reject) => { + await Promise.all( + Array.from( + { length: workers }, + () => + new Promise((resolve, reject) => { const w = new Worker(bootstrap, { eval: true, - workerData: { input: { jobs: jobsForShard, grammarKeys: wanted, maxCallsPerFile: opts.maxCallsPerFile } }, + workerData: { input: { jobs: [], grammarKeys: wanted, maxCallsPerFile: opts.maxCallsPerFile } }, }); + spawned.push(w); + let finished = false; // A worker that neither answers nor errors would hang the whole // index, since Promise.all waits forever. The bound is a deadlock // guard, not a performance knob — tripping it costs a fallback to - // the sequential scan, which is always correct. - const timer = setTimeout(() => { - reject(new Error("extraction worker timed out")); - void w.terminate(); - }, WORKER_TIMEOUT_MS); + // the sequential scan, which is always correct. Re-armed on every + // message, so it bounds one batch, not the whole run. + let timer: ReturnType | undefined; + const arm = (): void => { + if (timer) clearTimeout(timer); + timer = setTimeout(() => { + settle(() => reject(new Error("extraction worker timed out"))); + void w.terminate(); + }, WORKER_TIMEOUT_MS); + }; const settle = (fn: () => void): void => { - clearTimeout(timer); + if (timer) clearTimeout(timer); + finished = true; fn(); }; - w.once("message", (m: WorkerOutput | { error: string }) => { - settle(() => resolve(m)); - void w.terminate(); + arm(); + // Two batches in flight per worker: the next one is already queued + // in the worker's mailbox when it posts a result, so it never idles + // on the main thread's turn to deserialize records and answer. + let inflight = 0; + const dispatch = (): boolean => { + const batch = takeBatch(); + if (batch.length === 0) return false; + inflight++; + w.postMessage({ jobs: batch }); + return true; + }; + w.on("message", (m: WorkerOutput | { error: string }) => { + if (finished) return; + if ("error" in m) { + settle(() => reject(new Error(m.error))); + void w.terminate(); + return; + } + // A worker that readied a different grammar set would produce + // regex-tier records for some language — discard the whole run + // rather than emit a mix of tiers. + if (m.ready.slice().sort().join(",") !== wanted.join(",")) { + settle(() => reject(new Error("extraction worker grammar tier mismatch"))); + void w.terminate(); + return; + } + for (const r of m.records) out.set(r.rel, { size: r.size, mtimeMs: r.mtimeMs, record: r.record }); + if (inflight === 0) dispatch(); // the readiness message: prime a second batch + else inflight--; + dispatch(); + if (inflight === 0) { + settle(() => resolve()); + w.postMessage({ done: true }); + void w.terminate(); + return; + } + arm(); }); w.once("error", (e) => settle(() => reject(e))); w.once("exit", (code) => { // Already-settled rejects are no-ops; terminate() itself exits non-zero. - if (code !== 0) settle(() => reject(new Error(`extraction worker exited with ${code}`))); + if (!finished && code !== 0) settle(() => reject(new Error(`extraction worker exited with ${code}`))); }); }), ), ); - - const out = new Map(); - for (const o of outputs) { - if ("error" in o) return undefined; - // A worker that readied a different grammar set would have produced - // regex-tier records for some language — discard the whole run rather - // than emit a mix of tiers. - if (o.ready.slice().sort().join(",") !== wanted.join(",")) return undefined; - for (const r of o.records) out.set(r.rel, { size: r.size, mtimeMs: r.mtimeMs, record: r.record }); - } + // Every job was dispatched and every dispatched batch came back (a worker + // only resolves once the queue is empty, and only after its own batch + // returned) — but a vanished file is dropped by the worker and re-read on + // the main thread, so the map may legitimately be smaller than `jobs`. return out; } catch { + // One failure discards the whole run: stop the others now rather than let + // them drain a queue nobody will read. + for (const w of spawned) void w.terminate(); return undefined; } } +// Guided-scheduling knobs: a batch is `remaining / (workers × BATCHES_PER_WORKER)` +// jobs, never fewer than MIN_BATCH_JOBS. The first batches are large (little +// message traffic), the last ones small (little tail). +const BATCHES_PER_WORKER = 4; +const MIN_BATCH_JOBS = 4; + // scanRepo, with the code files extracted across workers. // // The parallel part is strictly a pre-pass: it produces the SAME records diff --git a/src/preload.ts b/src/preload.ts index d42b3cf..850cb65 100644 --- a/src/preload.ts +++ b/src/preload.ts @@ -24,6 +24,7 @@ import { join } from "node:path"; import { ENGINE_VERSION, EXTRACTOR_VERSION, SCHEMA_VERSION } from "./types.js"; import type { FileRecord, Graph, SymbolIndex } from "./types.js"; import { scanRepo, type RepoScan, type ScanOptions } from "./scan.js"; +import { scanRepoParallel } from "./pool.js"; import type { IndexArtifacts } from "./pipeline.js"; import { sha1 } from "./hash.js"; import { walk, type WalkResult } from "./walk.js"; @@ -189,9 +190,18 @@ export function preloadSession( // case loads no tree-sitter wasm; a new/stat-changed path warms BEFORE the one // extraction pass, so changed files land at the AST tier without a provisional // regex extraction followed by a second scan. +// +// The one extraction pass runs through scanRepoParallel: a persisted index +// whose code files drifted (a branch switch, a pull) used to re-extract every +// changed file on the main thread, so `--workers` / CODEINDEX_WORKERS silently +// meant nothing to a read command as soon as a `.codeindex/` existed. With a +// cache, the pool only ships the files the stat fastpath cannot serve, and +// scanRepo consumes the records exactly as the sequential loop would have +// built them (pool.ts) — an unchanged index still loads no wasm and spawns +// nothing. export async function preloadSessionLazy( repo: string, - opts: Omit, + opts: Omit & { workers?: number }, warm: () => Promise, indexDir: string = INDEX_DIR, ): Promise { @@ -213,7 +223,7 @@ export async function preloadSessionLazy( if (needsWarm) { await warm(); } - const scan = scanRepo(repo, { ...opts, cache: persisted.cacheMap, precomputedWalk: walked }); + const scan = await scanRepoParallel(repo, { ...opts, cache: persisted.cacheMap, precomputedWalk: walked }); let artifactsTried = false; let artifacts: IndexArtifacts | undefined; return { diff --git a/src/query.ts b/src/query.ts index 1dadae3..acc83ac 100644 --- a/src/query.ts +++ b/src/query.ts @@ -9,7 +9,7 @@ import type { CodeSymbol } from "./types.js"; import type { RepoScan } from "./scan.js"; import { readText } from "./walk.js"; import type { CallerSite } from "./callers.js"; -import { callerIndexFor, fileByRelFor, symbolsByNameFor, uniqueDefsFor } from "./derived.js"; +import { callerIndexFor, fileByRelFor, identSetsFor, symbolsByNameFor, uniqueDefsFor } from "./derived.js"; import { byStr } from "./sort.js"; const REFERENCE_KINDS = new Set(["reexport", "reexport-all", "default"]); @@ -151,14 +151,17 @@ export function findReferences(scan: RepoScan, name: string): SymbolReferences { const referencingFiles = new Set(); const unique = uniqueDefsFor(scan); const defFile = unique.get(name); + // Per-file identifier Sets are memoized per scan (src/derived.ts) and the + // doc pattern is compiled once — the loop used to run Array.includes over + // every code file's identifiers and build a RegExp per doc, per query. + const idents = identSetsFor(scan); + const mention = new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`); for (const f of scan.files) { if (f.rel === defFile) continue; - if (f.kind === "code" && f.idents?.includes(name)) referencingFiles.add(f.rel); + if (f.kind === "code" && idents.get(f.rel)?.has(name)) referencingFiles.add(f.rel); else if (f.kind === "doc") { const content = scan.docText.get(f.rel); - if (content && new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(content)) { - referencingFiles.add(f.rel); - } + if (content && mention.test(content)) referencingFiles.add(f.rel); } } for (const site of callSites) referencingFiles.add(site.file); diff --git a/src/render/symbols-json.ts b/src/render/symbols-json.ts index c12e63e..763e60b 100644 --- a/src/render/symbols-json.ts +++ b/src/render/symbols-json.ts @@ -2,7 +2,7 @@ import { SCHEMA_VERSION } from "../types.js"; import type { SymbolIndex } from "../types.js"; import type { RepoScan } from "../scan.js"; import { byStr } from "../sort.js"; -import { uniqueDefsFor } from "../derived.js"; +import { docMentionsFor, uniqueDefsFor } from "../derived.js"; // Files that REFERENCE each unique exported symbol — code files via their AST // identifiers, doc files via naming the symbol. Feeds symbols.json `refs` so @@ -18,6 +18,10 @@ export function computeSymbolRefs(scan: RepoScan): Map> { if (!set) refs.set(name, (set = new Set())); set.add(file); }; + // Doc tokens come from the per-scan memo shared with buildGraph's mention + // pass (src/derived.ts). Only RETAINED docText counts here, as before — a + // doc the memo had to re-read from disk is skipped. + const mentions = docMentionsFor(scan); for (const f of scan.files) { if (f.kind === "code" && f.idents) { for (const id of f.idents) { @@ -25,9 +29,9 @@ export function computeSymbolRefs(scan: RepoScan): Map> { if (target && target !== f.rel) add(id, f.rel); } } else if (f.kind === "doc") { - const content = scan.docText.get(f.rel); - if (!content) continue; - for (const tok of content.split(/[^A-Za-z0-9_]+/)) { + const m = mentions.get(f.rel); + if (!m || !m.retained) continue; + for (const tok of m.counts.keys()) { const target = unique.get(tok); if (target && target !== f.rel) add(tok, f.rel); } diff --git a/src/resolve.ts b/src/resolve.ts index 2cbdc5f..49023eb 100644 --- a/src/resolve.ts +++ b/src/resolve.ts @@ -70,6 +70,24 @@ export interface ResolveContext { phpPsr4: { prefix: string; dir: string }[]; // composer PSR-4 namespace prefix -> dir, longest first csharpNamespaces: Map; // C# namespace -> files declaring it (sorted) warnings: string[]; // build-time config issues (e.g. an unparseable tsconfig) + // Memo of JS/TS resolutions keyed by "\0" — resolveJs is + // a pure function of those two (its tsconfig scope, workspace and probe + // logic only ever look at the importer's DIRECTORY), and a package's files + // import the same handful of specifiers over and over. Each hit skips ~20 + // normalize+probe rounds. Optional so a hand-built context still works. + jsMemo?: Map; + // Per-directory sorted file lists by extension ("\0"), for the + // Go-package / Java-wildcard "first file in the directory" rule. + dirFilesMemo?: Map; +} + +// Files of `dir` ending in `ext`, sorted — computed once per (ext, dir). +function filesInDir(ctx: ResolveContext, dir: string, ext: string): string[] { + const memo = (ctx.dirFilesMemo ??= new Map()); + const key = ext + "\0" + dir; + let list = memo.get(key); + if (!list) memo.set(key, (list = (ctx.filesByDir.get(dir) ?? []).filter((f) => f.endsWith(ext)).sort())); + return list; } // Extensions walk() skips (images, fonts, media, maps). An import of one of these @@ -724,7 +742,7 @@ function resolveGo(fromRel: string, spec: string, ctx: ResolveContext): Resoluti // .go file in that dir as the representative node. const probePkg = (dir: string): Resolution => { const d = norm(dir).replace(/^\.$/, ""); - const inDir = (ctx.filesByDir.get(d) ?? []).filter((f) => f.endsWith(".go")).sort(); + const inDir = filesInDir(ctx, d, ".go"); return inDir.length ? { kind: "resolved", target: inDir[0]! } : { kind: "dangling", reason: "missing-package" }; @@ -843,7 +861,7 @@ function resolveJava(spec: string, ctx: ResolveContext): Resolution { // lexicographically-first .java file (the Go-package pattern). if (p.endsWith("/*") || p === "*") { const dir = p === "*" ? "" : p.slice(0, -2); - const inDir = (ctx.filesByDir.get(dir) ?? []).filter((f) => f.endsWith(".java")).sort(); + const inDir = filesInDir(ctx, dir, ".java"); if (inDir.length) return inDir[0]; continue; } @@ -937,7 +955,16 @@ export function resolveImport( if (dot !== -1 && ASSET_EXT.has(spec.slice(dot).toLowerCase().replace(/[?#].*$/, ""))) { return { kind: "external" }; } - if (JS_TS.has(ext) || SFC_HTML.has(ext)) return resolveJs(fromRel, spec, ctx); + if (JS_TS.has(ext) || SFC_HTML.has(ext)) { + const dir = fromRel.includes("/") ? posix.dirname(fromRel) : ""; + const key = dir + "\0" + spec; + const memo = (ctx.jsMemo ??= new Map()); + let r = memo.get(key); + if (!r) memo.set(key, (r = resolveJs(fromRel, spec, ctx))); + // A copy per caller: Resolution is a flat record, and a shared object would + // let one consumer's edit reach every later import of the same spec. + return { ...r }; + } if (PY.has(ext)) return resolvePython(fromRel, spec, ctx); if (ext === ".go") return resolveGo(fromRel, spec, ctx); if (ext === ".rs") return resolveRust(fromRel, spec, ctx); diff --git a/src/scan.ts b/src/scan.ts index 5ece681..a5e0dea 100644 --- a/src/scan.ts +++ b/src/scan.ts @@ -51,8 +51,9 @@ export interface ScanOptions { scope?: string; // Honor .gitignore files (default true — see WalkOptions.gitignore). gitignore?: boolean; - // Directory names to skip — REPLACES the default set (see - // WalkOptions.ignoreDirs; compose with the IGNORE_DIRS export to extend it). + // Directory names to skip — REPLACES the default set, except `.git` which is + // always skipped (see WalkOptions.ignoreDirs; compose with the IGNORE_DIRS + // export to extend it). ignoreDirs?: string[]; maxBytes?: number; maxFiles?: number; diff --git a/src/traverse.ts b/src/traverse.ts index 02dbfe3..e1c544e 100644 --- a/src/traverse.ts +++ b/src/traverse.ts @@ -13,6 +13,61 @@ import { byStr } from "./sort.js"; // mention says something references the name, not that it would break. const DEPENDS_KINDS = new Set(["import", "use", "call"]); +// Adjacency, built ONCE per edge list and kept as long as the list itself. +// Both traversals rebuilt their maps — and re-sorted every neighbour list — +// on every call, while a consumer such as the change-risk scorer (delta.ts) +// asks impactOf() once per changed file of every module. Keyed on the edge +// ARRAY's identity (a Graph's `edges` is never rebuilt in place); the length +// check guards the one cheap-to-detect mutation. Lists are pre-sorted with the +// comparator the per-call sort used, on the same insertion order, so the +// traversal visits exactly the same sequence. +const dependentsMemo = new WeakMap }>(); +function dependentsOf(edges: Edge[]): Map { + const hit = dependentsMemo.get(edges); + if (hit && hit.length === edges.length) return hit.map; + const map = new Map(); // target file → incoming depends-on edges + for (const e of edges) { + if (e.dangling || !DEPENDS_KINDS.has(e.kind)) continue; + let arr = map.get(e.to); + if (!arr) map.set(e.to, (arr = [])); + arr.push(e); + } + for (const arr of map.values()) arr.sort((a, b) => byStr(a.from, b.from)); + dependentsMemo.set(edges, { length: edges.length, map }); + return map; +} + +interface Adjacency { + out: Map; // from → edges, sorted by `to` + inn: Map; // to → edges, sorted by `from` + degree: Map; + threshold: number; // hubThreshold over this view's degree distribution +} +const adjacencyMemo = new WeakMap }>(); +function adjacencyOf(edges: Edge[], kinds?: Set): Adjacency { + const viewKey = kinds ? [...kinds].sort(byStr).join(",") : "*"; + let entry = adjacencyMemo.get(edges); + if (!entry || entry.length !== edges.length) adjacencyMemo.set(edges, (entry = { length: edges.length, views: new Map() })); + const cached = entry.views.get(viewKey); + if (cached) return cached; + const out = new Map(); + const inn = new Map(); + const degree = new Map(); + for (const e of edges) { + if (e.dangling) continue; + if (kinds && !kinds.has(e.kind)) continue; + (out.get(e.from) ?? out.set(e.from, []).get(e.from)!).push(e); + (inn.get(e.to) ?? inn.set(e.to, []).get(e.to)!).push(e); + degree.set(e.from, (degree.get(e.from) ?? 0) + 1); + degree.set(e.to, (degree.get(e.to) ?? 0) + 1); + } + for (const arr of out.values()) arr.sort((a, b) => byStr(a.to, b.to)); + for (const arr of inn.values()) arr.sort((a, b) => byStr(a.from, b.from)); + const adj = { out, inn, degree, threshold: hubThreshold([...degree.values()]) }; + entry.views.set(viewKey, adj); + return adj; +} + // The hub-gating threshold over a degree distribution: max(50, p99). p99 = the // degree at index min(n-1, floor(0.99n)) of the ASCENDING degree array (numeric // sort — deterministic without byStr). @@ -47,20 +102,14 @@ export interface ImpactResult { // Reverse dependency closure: every file that transitively IMPORTS, USES, or // CALLS one of `seeds`, out to `depth` hops (default: the full closure). export function reverseClosure(edges: Edge[], seeds: string[], depth = Infinity): Map { - const dependents = new Map(); // target file → incoming depends-on edges - for (const e of edges) { - if (e.dangling || !DEPENDS_KINDS.has(e.kind)) continue; - let arr = dependents.get(e.to); - if (!arr) dependents.set(e.to, (arr = [])); - arr.push(e); - } + const dependents = dependentsOf(edges); const depthOf = new Map(); const seen = new Set(seeds); let frontier = [...seeds]; for (let d = 1; d <= depth && frontier.length; d++) { const next: string[] = []; for (const node of frontier) { - for (const e of (dependents.get(node) ?? []).slice().sort((a, b) => byStr(a.from, b.from))) { + for (const e of dependents.get(node) ?? []) { if (seen.has(e.from)) continue; seen.add(e.from); depthOf.set(e.from, d); @@ -110,21 +159,10 @@ export interface NeighborResult { // distribution feeding the hub gate is measured over that same filtered // subgraph, so the gate reflects the view the caller asked for. function bfs(edges: Edge[], start: string, depth: number, kinds?: Set): NeighborLink[] { - const out = new Map(); - const inn = new Map(); - const degree = new Map(); - for (const e of edges) { - if (e.dangling) continue; - if (kinds && !kinds.has(e.kind)) continue; - (out.get(e.from) ?? out.set(e.from, []).get(e.from)!).push(e); - (inn.get(e.to) ?? inn.set(e.to, []).get(e.to)!).push(e); - degree.set(e.from, (degree.get(e.from) ?? 0) + 1); - degree.set(e.to, (degree.get(e.to) ?? 0) + 1); - } // A non-start node at or above the threshold is EMITTED as a link but never // expanded THROUGH. Only bites at depth ≥ 2 — depth-1 links all come from // `start`, which always expands. - const threshold = hubThreshold([...degree.values()]); + const { out, inn, degree, threshold } = adjacencyOf(edges, kinds); const seen = new Set([start]); const links: NeighborLink[] = []; let frontier = [start]; @@ -132,13 +170,13 @@ function bfs(edges: Edge[], start: string, depth: number, kinds?: Set): const next: string[] = []; for (const node of frontier) { if (node !== start && (degree.get(node) ?? 0) >= threshold) continue; - for (const e of (out.get(node) ?? []).slice().sort((a, b) => byStr(a.to, b.to))) { + for (const e of out.get(node) ?? []) { if (seen.has(e.to)) continue; links.push({ node: e.to, direction: "out", kind: e.kind, weight: e.weight, depth: d, confidence: e.confidence }); seen.add(e.to); next.push(e.to); } - for (const e of (inn.get(node) ?? []).slice().sort((a, b) => byStr(a.from, b.from))) { + for (const e of inn.get(node) ?? []) { if (seen.has(e.from)) continue; links.push({ node: e.from, direction: "in", kind: e.kind, weight: e.weight, depth: d, confidence: e.confidence }); seen.add(e.from); diff --git a/src/walk.ts b/src/walk.ts index 02156ec..6f69aa7 100644 --- a/src/walk.ts +++ b/src/walk.ts @@ -1,5 +1,5 @@ -import { readdirSync, statSync, lstatSync, readFileSync, realpathSync, type Dirent } from "node:fs"; -import { join, relative, sep, extname } from "node:path"; +import { readdirSync, statSync, lstatSync, readFileSync, realpathSync, existsSync, type Dirent } from "node:fs"; +import { join, resolve, sep, extname } from "node:path"; import { parseGitignore, isIgnored, type IgnoreRule } from "./ignore.js"; // Directories that never carry signal for a documentation/code question and @@ -15,12 +15,45 @@ export const IGNORE_DIRS = new Set([ "tmp", ".ultraindex", ".codeindex", "Pods", "DerivedData", ".terraform", "elm-stuff", ".dart_tool", ]); +// The VCS entry that marks a repository root: a directory for a normal clone, +// a "gitdir: " FILE for a linked worktree or a submodule. +const GIT_ENTRY = ".git"; + function isIgnoredDirectory(name: string, ignoreDirs: Set): boolean { - // A process killed during an atomic symbolic edit can leave this directory - // beside the source. It contains a copy of that source and must never become - // a duplicate phantom file in the next index, even when the consumer repo - // has no matching .gitignore rule. - return ignoreDirs.has(name) || name.startsWith(".codeindex-edit-"); + // `.git` is structural, not a preference: VCS internals (objects, packs, + // hooks) never carry signal, so it stays ignored even when a caller-supplied + // `ignoreDirs` replaces the default set without listing it — `--ignore-dir + // foo` used to pull thousands of loose objects into the index. + // A process killed during an atomic symbolic edit can leave the + // `.codeindex-edit-*` directory beside the source. It contains a copy of that + // source and must never become a duplicate phantom file in the next index, + // even when the consumer repo has no matching .gitignore rule. + return name === GIT_ENTRY || ignoreDirs.has(name) || name.startsWith(".codeindex-edit-"); +} + +// Locate this checkout's `info/exclude` — git's per-clone, never-committed +// ignore file (the walker honored only .gitignore, so local junk a developer +// excluded there was still indexed). A directory `.git` holds it directly; a +// gitfile points at the real git dir, and a linked worktree's git dir further +// points at the shared common dir (`commondir` file), which is where git keeps +// `info/` for every worktree. Returns "" when absent or unreadable. +function readInfoExclude(root: string, entries: readonly Dirent[]): string { + const marker = entries.find((e) => e.name === GIT_ENTRY); + if (!marker) return ""; + let gitDir = join(root, GIT_ENTRY); + try { + if (!marker.isDirectory()) { + const m = /^gitdir:[ \t]*(.+?)[ \t]*$/m.exec(readFileSync(gitDir, "utf8")); + if (!m) return ""; + gitDir = resolve(root, m[1]!); + const common = join(gitDir, "commondir"); + if (existsSync(common)) gitDir = resolve(gitDir, readFileSync(common, "utf8").trim()); + } + const exclude = join(gitDir, "info", "exclude"); + return existsSync(exclude) ? readText(exclude) : ""; + } catch { + return ""; + } } // Lockfiles: huge, machine-generated, and pure noise for a code/docs question — @@ -48,7 +81,8 @@ export interface WalkOptions { // every consumer; pass false to index generated/ignored trees deliberately. gitignore?: boolean; // Directory names to skip, REPLACING the default set entirely (not merging - // with it). IGNORE_DIRS is a public export, so consumers compose + // with it) — except `.git`, which is skipped whatever the list says. + // IGNORE_DIRS is a public export, so consumers compose // `[...IGNORE_DIRS, "extra"]` — or filter it — themselves; replace is the // simplest contract. Deliberate scope boundary: grep.ts (the ripgrep // universe) and the MCP server keep the DEFAULT set — recall consumers @@ -68,8 +102,10 @@ export interface WalkResult { files: WalkedFile[]; capped: boolean; // true when the maxFiles cap was hit and the walk stopped early // Files that were SEEN and rejected by the size/lockfile/binary/minified/ - // gitignore rules. Ignored DIRECTORIES (node_modules, gitignored trees…) - // are not counted — their contents were never even listed. + // gitignore rules, plus one per nested-repository boundary the walk stopped + // at (a subdirectory carrying its own `.git`). Ignored DIRECTORIES + // (node_modules, gitignored trees…) are not counted — their contents were + // never even listed. excluded: number; } @@ -140,7 +176,24 @@ export function walk(root: string, opts: WalkOptions = {}): WalkResult { } catch { continue; } + // Nested-repository boundary: a subdirectory with its own `.git` (directory + // or gitfile) is another repo — a linked worktree under .claude/worktrees/, + // a vendored clone, a submodule. Its files belong to THAT repo's index, and + // walking them here produced thousands of phantom duplicates of the same + // sources (a repo with four worktrees indexed five copies of itself); git + // itself never lists them. Decided on the dirents already listed — zero + // extra syscalls — and structural: independent of the gitignore layer. + if (frame.rel && entries.some((e) => e.name === GIT_ENTRY)) { + excluded++; + continue; + } let rules = frame.rules; + if (useGitignore && !frame.rel) { + // `.git/info/exclude` sits BEFORE every .gitignore in git's own + // precedence (a .gitignore rule can still negate it — later rules win). + const parsed = parseGitignore(readInfoExclude(frame.dir, entries), ""); + if (parsed.length) rules = [...rules, ...parsed]; + } if (useGitignore && entries.some((e) => e.name === ".gitignore")) { const parsed = parseGitignore(readText(join(frame.dir, ".gitignore")), frame.rel); if (parsed.length) rules = [...rules, ...parsed]; @@ -152,6 +205,10 @@ export function walk(root: string, opts: WalkOptions = {}): WalkResult { // The dirent type IS the lstat type (Node lstats internally when the // filesystem can't supply it), so no lstat is needed to detect links. const isLink = entry.isSymbolicLink(); + // The root's own `.git` entry, whatever its type: the directory is VCS + // internals, the gitfile of a linked worktree or submodule is a one-line + // pointer — neither is source, and git lists neither. + if (name === GIT_ENTRY) continue; // Ignored-directory boundary (node_modules, .git…): skip on the dirent // type alone — ZERO stat syscalls. A symlink reports isDirectory() // false on its dirent and falls through to the stat-based diff --git a/tests/phase2.test.ts b/tests/phase2.test.ts index e9d4c4e..7a9507e 100644 --- a/tests/phase2.test.ts +++ b/tests/phase2.test.ts @@ -498,6 +498,22 @@ describe("dead code, complexity, mermaid", () => { expect(dead.find((d) => d.name === "neverCalled")!.tier).toBe("unreferenced"); }); + it("findDeadCode spares a called export whose name is also exported by another file", () => { + // Two files export `helper`; each has its own caller. The caller index + // keeps the first-sorted def under the bare name and the second under + // "helper@b/helper.ts" — the second used to be reported dead because the + // bare key was consulted first and pointed at the other file's def. + const root = mkdtempSync(join(tmpdir(), "ci-dead-homonym-")); + mkdirSync(join(root, "a")); + mkdirSync(join(root, "b")); + writeFileSync(join(root, "a", "helper.ts"), "export function helper(): number {\n return 1;\n}\n"); + writeFileSync(join(root, "b", "helper.ts"), "export function helper(): number {\n return 2;\n}\n"); + writeFileSync(join(root, "a", "use.ts"), 'import { helper } from "./helper";\nexport const x = helper();\n'); + writeFileSync(join(root, "b", "use.ts"), 'import { helper } from "./helper";\nexport const y = helper();\n'); + const dead = findDeadCode(scanRepo(root)); + expect(dead.filter((d) => d.name === "helper")).toEqual([]); + }); + it("symbolComplexity counts branches; riskHotspots multiplies by churn", () => { const root = makeRepo(); const scan = scanRepo(root); diff --git a/tests/walk-nested.test.ts b/tests/walk-nested.test.ts new file mode 100644 index 0000000..26c713c --- /dev/null +++ b/tests/walk-nested.test.ts @@ -0,0 +1,119 @@ +// Repository boundaries in the walker: `.git` is never walked, nested repos +// (linked worktrees, vendored clones, submodules) are skipped like git does, +// and `.git/info/exclude` is honored. Fixtures are built in a temp dir because +// git refuses to track a path named `.git`. +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { walk } from "../src/walk.js"; + +const GIT = ".git"; +const body = "export const a = 1;\n"; + +function mkfile(root: string, rel: string, content = body): void { + const abs = join(root, ...rel.split("/")); + mkdirSync(join(abs, ".."), { recursive: true }); + writeFileSync(abs, content); +} + +// A plain clone: `.git` is a directory holding info/exclude. +function cloneFixture(): string { + const root = mkdtempSync(join(tmpdir(), "ci-nested-")); + mkfile(root, "src/main.ts"); + mkfile(root, "src/local-notes.ts"); + mkfile(root, "scratch/keep.ts"); + mkfile(root, "scratch/drop.ts"); + mkfile(root, `${GIT}/HEAD`, "ref: refs/heads/main\n"); + mkfile(root, `${GIT}/objects/ab/cdef`, "loose object\n"); + // `scratch/*` (not `scratch/`): an ignored DIRECTORY is never descended, so + // only a file-level rule can be negated back — same as git. + mkfile(root, `${GIT}/info/exclude`, "# local junk\nsrc/local-notes.ts\nscratch/*\n!scratch/keep.ts\n"); + return root; +} + +const rels = (root: string, opts?: Parameters[1]) => walk(root, opts).files.map((f) => f.rel).sort(); + +describe("walk stops at nested repository boundaries", () => { + it("skips a subdirectory carrying a gitfile (linked worktree / submodule)", () => { + const root = cloneFixture(); + mkfile(root, ".claude/worktrees/feature/src/main.ts"); + mkfile(root, `.claude/worktrees/feature/${GIT}`, `gitdir: ${join(root, GIT, "worktrees", "feature")}\n`); + mkfile(root, ".claude/skills/note.md", "# note\n"); + const walked = walk(root); + const files = walked.files.map((f) => f.rel).sort(); + expect(files).toEqual([".claude/skills/note.md", "scratch/keep.ts", "src/main.ts"]); + expect(files.some((r) => r.startsWith(".claude/worktrees/"))).toBe(false); + // The boundary is counted as one exclusion so consumers can report it — + // on top of the two files info/exclude dropped. + expect(walked.excluded).toBe(3); + }); + + it("skips a subdirectory carrying its own .git DIRECTORY (vendored clone)", () => { + const root = cloneFixture(); + mkfile(root, "third_party/lib/index.ts"); + mkfile(root, `third_party/lib/${GIT}/HEAD`, "ref: refs/heads/main\n"); + mkfile(root, "third_party/own.ts"); + expect(rels(root)).toEqual(["scratch/keep.ts", "src/main.ts", "third_party/own.ts"]); + }); + + it("the boundary is structural: gitignore:false still stops at it", () => { + const root = cloneFixture(); + mkfile(root, "vendored/app/x.ts"); + mkfile(root, `vendored/app/${GIT}`, "gitdir: /nowhere\n"); + const files = rels(root, { gitignore: false }); + expect(files).not.toContain("vendored/app/x.ts"); + // …while info/exclude, part of the gitignore layer, is disabled. + expect(files).toContain("src/local-notes.ts"); + expect(files).toContain("scratch/drop.ts"); + }); +}); + +describe("walk honors .git/info/exclude", () => { + it("applies its rules, including negation, before the .gitignore chain", () => { + const root = cloneFixture(); + expect(rels(root)).toEqual(["scratch/keep.ts", "src/main.ts"]); + }); + + it("a later .gitignore rule can re-include what info/exclude dropped", () => { + const root = cloneFixture(); + mkfile(root, ".gitignore", "!src/local-notes.ts\n"); + expect(rels(root)).toEqual([".gitignore", "scratch/keep.ts", "src/local-notes.ts", "src/main.ts"]); + }); + + it("follows a gitfile to the linked worktree's common dir", () => { + // Layout of `git worktree add`: /.git → "gitdir:
/.git/worktrees/", + // whose `commondir` file points back at
/.git where info/ lives. + const main = mkdtempSync(join(tmpdir(), "ci-wt-main-")); + mkfile(main, `${GIT}/info/exclude`, "*.local.ts\n"); + mkfile(main, `${GIT}/worktrees/feat/commondir`, "../..\n"); + const wt = mkdtempSync(join(tmpdir(), "ci-wt-")); + mkfile(wt, "a.ts"); + mkfile(wt, "a.local.ts"); + writeFileSync(join(wt, GIT), `gitdir: ${join(main, GIT, "worktrees", "feat")}\n`); + expect(rels(wt)).toEqual(["a.ts"]); + }); + + it("a gitfile at the root is not indexed as a source file", () => { + const wt = mkdtempSync(join(tmpdir(), "ci-gitfile-")); + mkfile(wt, "a.ts"); + writeFileSync(join(wt, GIT), "gitdir: /nowhere\n"); + expect(rels(wt)).toEqual(["a.ts"]); + expect(rels(wt, { gitignore: false })).toEqual(["a.ts"]); + }); +}); + +describe(".git is skipped whatever ignoreDirs says", () => { + it("--ignore-dir replacing the default list does not pull .git/objects in", () => { + const root = cloneFixture(); + mkfile(root, "generated/x.ts"); + const files = rels(root, { ignoreDirs: ["generated"] }); + expect(files).toEqual(["scratch/keep.ts", "src/main.ts"]); + expect(files.some((r) => r.startsWith(`${GIT}/`))).toBe(false); + }); + + it("an empty replacement list still skips .git", () => { + const root = cloneFixture(); + expect(rels(root, { ignoreDirs: [], gitignore: false }).some((r) => r.startsWith(`${GIT}/`))).toBe(false); + }); +});