@omfalos/mokosh 0.4.4 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/cli.js +68 -44
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +68 -44
- package/dist/cli.mjs.map +1 -1
- package/dist/duplication-worker.d.mts +2 -2
- package/dist/duplication-worker.d.ts +2 -2
- package/dist/duplication-worker.js +6 -4
- package/dist/duplication-worker.js.map +1 -1
- package/dist/duplication-worker.mjs +6 -4
- package/dist/duplication-worker.mjs.map +1 -1
- package/dist/index.d.mts +417 -58
- package/dist/index.d.ts +417 -58
- package/dist/index.js +43 -28
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +43 -28
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.js +46 -30
- package/dist/mcp.js.map +1 -1
- package/dist/mcp.mjs +46 -30
- package/dist/mcp.mjs.map +1 -1
- package/dist/parse-worker.d.mts +2 -2
- package/dist/parse-worker.d.ts +2 -2
- package/dist/parse-worker.js +6 -2
- package/dist/parse-worker.js.map +1 -1
- package/dist/parse-worker.mjs +6 -2
- package/dist/parse-worker.mjs.map +1 -1
- package/dist/{parse-CAKctgb6.d.mts → parse-yamNoaoL.d.mts} +1 -1
- package/dist/{parse-CAKctgb6.d.ts → parse-yamNoaoL.d.ts} +1 -1
- package/dist/{tokenizer-BaF1eUBQ.d.mts → tokenizer-D9P-y7lH.d.mts} +3 -3
- package/dist/{tokenizer-BaF1eUBQ.d.ts → tokenizer-D9P-y7lH.d.ts} +3 -3
- package/dist/{types-BtSqoqbZ.d.mts → types-Ba-BjVQG.d.mts} +5 -1
- package/dist/{types-BlN-U5AM.d.ts → types-DWARi8gF.d.ts} +5 -1
- package/package.json +3 -2
package/dist/mcp.mjs
CHANGED
|
@@ -1,41 +1,57 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}};import
|
|
4
|
-
`).
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
`&&
|
|
2
|
+
var Jt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});import Oi from"path";import{fileURLToPath as ji}from"url";var Wi=()=>ji(import.meta.url),zi=()=>Oi.dirname(Wi()),f=zi();import{StdioServerTransport as nf}from"@modelcontextprotocol/sdk/server/stdio.js";import{Server as ef}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as tf,ListToolsRequestSchema as rf}from"@modelcontextprotocol/sdk/types.js";import pe from"fs";import V from"path";import tr from"fs";import Dn from"path";var $i=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],qt=[];function rt(t){qt.push(t)}function Nn(t){return[...$i,...qt].some(e=>typeof e=="string"?t.includes(e):e instanceof RegExp?e.test(t):e(t))}var Bi=[".test.",".spec.","-test.","-spec."],Vt=[];function nt(t){Vt.push(t)}function Ne(){return[...Bi,...Vt]}var Hi=["jest","vitest","playwright","cypress","@testing-library/"],Qt=[];function st(t){Qt.push(t)}function Yt(){return[...Hi,...Qt]}var Rn=.8,Xt=Rn;function Zt(t){Xt=t}function er(){return Xt}function ot(){qt.length=0,Vt.length=0,Qt.length=0,Xt=Rn}var Ui=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function Re(t,{allowJs:e=!0,isExplicitPath:r=!1}={}){if(r){let n=Dn.resolve(t);return tr.existsSync(n)?n.endsWith(".json")?In(n):e?Mn(n):{}:{}}for(let n of Ui){let s=Dn.resolve(t,n);if(tr.existsSync(s)){if(n.endsWith(".json"))return In(s);if(e)return Mn(s)}}return{}}function In(t){return JSON.parse(tr.readFileSync(t,"utf-8"))}function Mn(t){let e=Jt(t);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function rr(t){ot();for(let e of t.configMatchers??[])rt(e);for(let e of t.testPatterns??[])nt(e);for(let e of t.testLibraries??[])st(e);t.barrelThreshold!==void 0&&Zt(t.barrelThreshold)}function H(t){return{gitStats:t?.gitStats??!1,parallelParsing:t?.parallelParsing,pathAliases:t?.pathAliases,additionalIgnoreDirs:t?.ignoreDirs}}var Q="mokosh-cache",De="duplication-tokens.json",nr="graph.json",sr="workspace-graph.json",or="branch-graphs",N=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage",".pytest_cache","__pycache__",".gradle","target"],ir=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".java",".kt",".kts",".scala",".sc",".groovy",".gradle",".feature",".md",".mdx"];import Ki from"fs";import _n from"path";function ar(t,e){let r=_n.resolve(t,e);try{let n=Ki.readFileSync(r,"utf-8"),s=JSON.parse(n),o=new Map;if(typeof s!="object"||s===null)return o;for(let[i,a]of Object.entries(s)){if(i==="total")continue;let c=a?.lines?.pct;if(typeof c!="number")continue;let l=_n.relative(t,i);o.set(l,c)}return o}catch{return new Map}}var it={serialize(t){let e=["graph TD"],r=new Set;for(let n of t.nodes.values()){let s=`"${n.path}"`;for(let o of n.imports){if(!o.toPath)continue;let i=`"${o.toPath}"`,a=`${n.path} -> ${o.toPath}`;if(!r.has(a)){let c=o.isStyle?"-- styles -->":"-->";e.push(` ${s} ${c} ${i}`),r.add(a)}}}return e.join(`
|
|
3
|
+
`)}};var fe=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let r=new Set(this.nodes.keys());return e.filter(n=>!r.has(n))}findHighExportUsage(e){let r=[];for(let n of this.nodes.values()){if(n.maxExportUsage===void 0||n.maxExportUsage<e)continue;let s=n.imports.reduce((o,i)=>(i.exportUsageRatio??0)>(o?.exportUsageRatio??0)?i:o,null);r.push({path:n.path,maxExportUsage:n.maxExportUsage,tightestDep:s?.toPath??""})}return r.sort((n,s)=>s.maxExportUsage-n.maxExportUsage)}findCycles(e={}){let r=new Set(e.includeKinds??[]),n=[],s=new Set,o=new Set,i=[],a=c=>{s.add(c),o.add(c),i.push(c);let l=this.nodes.get(c);if(l){for(let p of l.imports)if(!(!p.toPath||p.isExternal)&&!(p.isSamePackage&&!r.has("samePackage"))&&!(p.isDocReference&&!r.has("docReference")))if(o.has(p.toPath)){let u=i.indexOf(p.toPath);n.push([...i.slice(u),p.toPath])}else s.has(p.toPath)||a(p.toPath)}o.delete(c),i.pop()};for(let c of this.nodes.keys())s.has(c)||a(c);return n}};import Ln from"fs";import qi from"path";function cr(t,e){let r=t.replace(/^\.\//,"");if(e.nodes.has(r))return r;let n=r.replace(/^dist\//,"src/").replace(/\.(js|mjs|cjs)$/,".ts");return e.nodes.has(n)?n:null}function Gn(t,e){if(typeof t=="string")return cr(t,e);if(t&&typeof t=="object"){let r=t;for(let n of["import","require","default"]){let s=Gn(r[n],e);if(s)return s}}return null}function Vi(t){if(!t)return"unknown";let e=t.trimStart();return e.startsWith("interface ")?"interface":e.startsWith("class ")?"class":e.startsWith("enum ")?"enum":e.startsWith("type ")?"type":e.startsWith("namespace ")?"namespace":e.startsWith("const ")||e.startsWith("let ")||e.startsWith("var ")||e.startsWith("readonly ")?"const":e.startsWith("(")||e.startsWith("async ")||e.startsWith("function ")||e.includes("=>")?"function":"unknown"}function Qi(t,e){let r=new Set,n=new Set,s=[...e];for(;s.length;){let o=s.shift();if(n.has(o))continue;n.add(o);let i=t.nodes.get(o);if(i){for(let a of i.exports)r.add(a.name);for(let a of i.imports){if(a.type!=="re-export"||a.isExternal||!a.toPath)continue;if(!a.symbols?.length||a.symbols.includes("*")){let l=t.nodes.get(a.toPath);if(l)for(let p of l.exports)r.add(p.name);s.push(a.toPath)}else for(let l of a.symbols)r.add(l)}}}return r}function lr(t,e){let r=[],n=qi.join(e,"package.json");if(Ln.existsSync(n))try{let s=JSON.parse(Ln.readFileSync(n,"utf8"));if(s.exports&&typeof s.exports=="object"&&!Array.isArray(s.exports))for(let o of Object.values(s.exports)){let i=Gn(o,t);i&&!r.includes(i)&&r.push(i)}else if(typeof s.exports=="string"){let o=cr(s.exports,t);o&&r.push(o)}if(r.length===0)for(let o of[s.main,s.module].filter(Boolean)){let i=cr(o,t);i&&!r.includes(i)&&r.push(i)}}catch{}if(r.length===0){for(let s of["src/index.ts","src/index.js","index.ts","index.js"])if(t.nodes.has(s)){r.push(s);break}}return r}function Yi(t,e){let r=new Set(e);for(let n of e)t.traverse(n,s=>(r.add(s.path),!0),{direction:"outgoing"});return r}function Xi(t,e,r){let n=new Map;for(let s of e){if(r.includes(s))continue;let o=t.nodes.get(s);if(!o)continue;let i=o.category==="barrel";for(let a of o.exports){let c=n.get(a.name),l=!!(a.signature||a.doc);(!c||l&&!i)&&n.set(a.name,{file:s,symbol:a})}}return n}function Zi(t,e,r,n){let s=[];for(let o of t){let i=e.get(o),a=n.flatMap(u=>r.nodes.get(u)?.exports??[]).find(u=>u.name===o),c=i?.symbol??a,l=i?.file??n.find(u=>r.nodes.get(u)?.exports.some(m=>m.name===o))??n[0],p={name:o,definedIn:l,kind:Vi(c?.signature)};c?.doc&&(p.doc=c.doc),c?.signature&&(p.signature=c.signature),s.push(p)}return s.sort((o,i)=>o.name.localeCompare(i.name)),s}function ea(t,e,r){let n=c=>t.nodes.get(c)?.category==="test",s=[...e].filter(c=>!r.includes(c)&&!n(c)),o=[...t.nodes.keys()].filter(c=>!e.has(c)),i=o.filter(c=>!n(c)),a=o.filter(c=>n(c));return{internalFiles:s,unreachableFromEntry:i,testFiles:a}}function pr(t,e){if(e.length===0)throw new Error("buildApiSurface requires at least one entry point");for(let l of e)if(!t.nodes.has(l))throw new Error(`Entry point not found in graph: ${l}`);let r=Yi(t,e),n=Xi(t,r,e),s=Qi(t,e),o=Zi(s,n,t,e),{internalFiles:i,unreachableFromEntry:a,testFiles:c}=ea(t,r,e);return{entryPoints:e,publicExports:o,internalFiles:i,unreachableFromEntry:a,testFiles:c}}function ur(t,e){let r=null,n=[];for(let o of t.nodes.values()){o.exports.some(i=>i.name===e)&&(r=o.path);for(let i of o.callEdges??[])i.to===e&&n.push({file:o.path,callerFunction:i.from})}let s=[];if(r){let o=t.nodes.get(r);for(let i of o?.callEdges??[])i.from===e&&s.push({file:i.toFile,calleeFunction:i.to})}return{functionName:e,definedIn:r,callers:n,callees:s}}import Of from"fs";import Wf from"path";function On(t){let e=[...t.nodes.entries()].sort(([n],[s])=>n.localeCompare(s)).map(([n,s])=>`${n}:${s.mtime}:${s.size}`).join("|"),r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}function mr(t){let e=new Map;for(let r of t.nodes.keys()){let n=[];t.traverse(r,s=>(s.path!==r&&n.push(s.path),!0),{direction:"incoming"}),e.set(r,n)}return{impact:e,graphHash:On(t)}}function fr(t,e){return t.impact.get(e)??[]}import Ap from"path";import Ie from"fs";import jn from"path";var R=class t{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let r=new Map;for(let n of e.nodes)r.set(n.path,n);return new t(r)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let r of this.nodes.values())for(let n of r.imports)if(n.toPath){let s=e.get(n.toPath)||[];s.push(r.path),e.set(n.toPath,s)}return this._incomingEdgesCache=e,e}dfs(e,r,n,s){let o=new Set,i=n.maxDepth??1/0,a=(c,l,p)=>{if(l>i||o.has(c))return;let u=this.nodes.get(c);if(u&&(o.add(c),r(u,l,p)!==!1))for(let m of s(c))a(m,l+1,c)};a(e,0,null)}traverse(e,r,n={}){let s=n.direction??"outgoing",o=s==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,r,n,i=>s==="outgoing"?this.nodes.get(i)?.imports.map(a=>a.toPath).filter(Boolean)??[]:o?.get(i)??[])}getCallIncomingCache(){if(this._callIncomingCache)return this._callIncomingCache;let e=new Map;for(let r of this.nodes.values())for(let n of r.callEdges??[]){let s=e.get(n.toFile)??[];s.push(r.path),e.set(n.toFile,s)}return this._callIncomingCache=e,e}traverseCalls(e,r,n={}){let s=n.direction??"outgoing",o=s==="incoming"?this.getCallIncomingCache():null;this.dfs(e,r,n,i=>s==="outgoing"?this.nodes.get(i)?.callEdges?.map(a=>a.toFile)??[]:o?.get(i)??[])}getCallers(e){let r=[];return this.traverseCalls(e,n=>(n.path!==e&&r.push(n.path),!0),{direction:"incoming",maxDepth:1}),r}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let r=this.nodes.get(e);return r?r.imports.map(n=>this.nodes.get(n.toPath)).filter(n=>n!==void 0):[]}findUnusedFiles(e){return new fe(this.nodes).findUnusedFiles(e)}findCycles(e){return new fe(this.nodes).findCycles(e)}};function at(t){return jn.join(t,Q,or)}function Wn(t,e){return jn.join(at(t),`${e}.json`)}function zn(t,e){let r=Wn(t,e);if(!Ie.existsSync(r))return null;try{let n=Ie.readFileSync(r,"utf-8");return R.deserialize(JSON.parse(n))}catch{return null}}function $n(t,e,r){let n=at(t);Ie.existsSync(n)||Ie.mkdirSync(n,{recursive:!0}),Ie.writeFileSync(Wn(t,e),JSON.stringify(r.serialize()))}import Be from"fs";import P from"path";import Kl from"piscina";import{execFileSync as gr}from"child_process";var ct=class{getChangedFiles(e,r){try{let s=[["diff","--name-only"],["diff","--cached","--name-only"],["ls-files","--others","--exclude-standard"],...r?[["diff","--name-only","--end-of-options",`${r}...HEAD`]]:[]].flatMap(o=>{try{return gr("git",o,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
4
|
+
`).map(a=>a.trim()).filter(a=>a!=="")}catch{return[]}});return Array.from(new Set(s))}catch(n){return console.error("Error getting git diff:",n),[]}}},Bn="%x00%H%x09%ae%x09%at",Hn=256*1024*1024;function Un(t,e){let r="",n=0;for(let s of t.split(`
|
|
5
|
+
`)){if(s.startsWith("\0")){let[,c,l]=s.slice(1).split(" ");r=c??"",n=l?Number(l)*1e3:0;continue}if(s==="")continue;let o=s.split(" "),i=o[0];if(!i)continue;let a=i.startsWith("R")||i.startsWith("C")?o[2]:o[1];a&&e(a,r,n)}}function Kn(t){let e=new Map;try{let r=gr("git",["-C",t,"log","--since=90 days ago","--name-status","-M",`--format=${Bn}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:Hn});Un(r,(n,s,o)=>{let i=e.get(n);if(i){i.commitCount90d+=1;return}e.set(n,{commitCount90d:1,lastAuthor:s||void 0,lastCommitAt:o||void 0})})}catch{return e}try{let r=gr("git",["-C",t,"log","--name-status","-M",`--format=${Bn}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:Hn});Un(r,(n,s,o)=>{e.has(n)||e.set(n,{commitCount90d:0,lastAuthor:void 0,lastCommitAt:o||void 0})})}catch{}return e}import lt from"fs";import ta from"path";import{load as Jn}from"js-yaml";var Me=["package-lock.json","yarn.lock","pnpm-lock.yaml"];function qn(t){let e=t.lastIndexOf("@");return e>0?t.substring(0,e):t}function ra(t){return t.replace(/:$/,"").split(",").map(e=>{let r=e.trim();return r.startsWith('"')&&(r=r.slice(1)),r.endsWith('"')&&(r=r.slice(0,-1)),qn(r)}).filter(Boolean)}function na(t,e){let r=t.startsWith("/")?t.slice(1):t,n=r.lastIndexOf("@");return n>0?{name:r.substring(0,n),version:e||r.substring(n+1)}:{name:r,version:e}}function sa(t){try{let e=Jn(t),r={dependencies:{}};for(let[n,s]of Object.entries(e))if(!(n==="__metadata"||!s?.version))for(let o of n.split(", ")){let i=qn(o);i&&(r.dependencies[i]={version:s.version,...s.dependencies!==void 0&&{dependencies:s.dependencies}})}return r}catch{return null}}function oa(t){let e={dependencies:{}};for(let r of t.split(/\n\n+/)){let n=r.split(`
|
|
6
|
+
`).filter(c=>c.trim().length>0&&!c.trim().startsWith("#"));if(n.length<2)continue;let s=n[0];if(!s||s.startsWith(" "))continue;let o=ra(s);if(o.length===0)continue;let a=n.find(c=>c.trim().startsWith('version "'))?.match(/version "(.*?)"/)?.[1]??"";for(let c of o)e.dependencies[c]={version:a}}return e}function Vn(t){let e=lt.readFileSync(t,"utf-8"),r=JSON.parse(e),n={dependencies:{}};if(r.packages)for(let[s,o]of Object.entries(r.packages)){if(!s.startsWith("node_modules/"))continue;let i=s.replace("node_modules/","");i.includes("node_modules/")||(n.dependencies[i]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}else if(r.dependencies)for(let[s,o]of Object.entries(r.dependencies))n.dependencies[s]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}};return n}function Qn(t){let e=lt.readFileSync(t,"utf-8");if(e.includes("__metadata:")){let r=sa(e);if(r!==null)return r}return oa(e)}function Yn(t){let e=lt.readFileSync(t,"utf-8"),r={dependencies:{}};try{let n=Jn(e);if(n.packages)for(let[s,o]of Object.entries(n.packages)){let{name:i,version:a}=na(s,o.version);i&&(r.dependencies[i]={version:a,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}if(n.dependencies)for(let[s,o]of Object.entries(n.dependencies)){if(r.dependencies[s])continue;let i=typeof o=="string"?o:o.version;r.dependencies[s]={version:i||""}}}catch{}return r}var ia={"package-lock.json":Vn,"yarn.lock":Qn,"pnpm-lock.yaml":Yn};function dr(t){for(let e of Me){let r=ta.join(t,e);if(lt.existsSync(r))return ia[e](r)}return null}import mt from"fs";import ut from"path";function Xn(t){let e=t.trim();return e.length>=2&&(e[0]==='"'||e[0]==="'")&&e[e.length-1]===e[0]?e.slice(1,-1):e}function aa(t){let e=t.trim();if(e.startsWith('"')||e.startsWith("'")){let a=Xn(e).split(":");return a.length>=3&&a[0]&&a[2]?{group:a[0],version:a[2]}:null}if(!e.startsWith("{"))return null;let r=e.match(/module\s*=\s*["']([^"']+)["']/),n=e.match(/group\s*=\s*["']([^"']+)["']/),s=r?r[1].split(":")[0]:n?.[1];if(!s)return null;let o=e.match(/version\.ref\s*=\s*["']([^"']+)["']/)??e.match(/version\s*=\s*\{\s*ref\s*=\s*["']([^"']+)["']/),i=e.match(/version\s*=\s*["']([^"']+)["']/);return{group:s,...i?.[1]!==void 0&&{version:i[1]},...o?.[1]!==void 0&&{versionRef:o[1]}}}function hr(t){let e=t.split(/\r?\n/).map(o=>o.replace(/#.*$/,"").trim()),r={},n="";for(let o of e){let i=o.match(/^\[([\w.-]+)\]$/);if(i){n=i[1];continue}if(n!=="versions"||!o)continue;let a=o.indexOf("=");if(a===-1)continue;let c=o.slice(0,a).trim(),l=Xn(o.slice(a+1));c&&l&&(r[c]=l)}let s={};n="";for(let o of e){let i=o.match(/^\[([\w.-]+)\]$/);if(i){n=i[1];continue}if(n!=="libraries"||!o)continue;let a=o.indexOf("=");if(a===-1)continue;let c=aa(o.slice(a+1));if(!c)continue;let l=c.versionRef?r[c.versionRef]:c.version;l&&(s[c.group]=l)}return s}function yr(t){let e={};for(let r of t.split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#")||n.startsWith("empty="))continue;let o=n.split("=")[0].split(":");o.length>=3&&o[0]&&o[2]&&(e[o[0]]=o[2])}return e}function xr(t){let e={},r=/["']([\w.-]+):([\w.-]+):([\w.\-+]+)["']/g;for(let s=r.exec(t);s;s=r.exec(t)){let[,o,,i]=s;o&&i&&/\d/.test(i)&&(e[o]=i)}let n=/group:\s*["']([\w.-]+)["'][^\n)]*?version:\s*["']([\w.\-+]+)["']/g;for(let s=n.exec(t);s;s=n.exec(t))s[1]&&s[2]&&/\d/.test(s[2])&&(e[s[1]]=s[2]);return e}function pt(t){let e={},r=/["']([\w.-]+)["']\s*%%?\s*["']([\w.-]+)["']\s*%\s*["']([\w.\-+]+)["']/g;for(let n=r.exec(t);n;n=r.exec(t)){let[,s,,o]=n;s&&o&&(e[s]=o)}return e}var ca=new Set(["node_modules","build",".gradle","target",".git","dist"]),la=2;function _e(t){try{return mt.existsSync(t)?mt.readFileSync(t,"utf-8"):null}catch{return null}}function br(t){let e={},r=p=>{for(let[u,m]of Object.entries(p))!e[u]&&m&&(e[u]=m)},n=_e(ut.join(t,"gradle","libs.versions.toml"));n&&r(hr(n));let s=[],o=[],i=[],a=(p,u)=>{let m;try{m=mt.readdirSync(p,{withFileTypes:!0})}catch{return}for(let d of m){let y=ut.join(p,d.name);if(d.isDirectory()){u<la&&!d.name.startsWith(".")&&!ca.has(d.name)&&a(y,u+1);continue}d.isFile()&&(d.name==="gradle.lockfile"?s.push(y):d.name==="build.gradle"||d.name==="build.gradle.kts"?o.push(y):d.name==="build.sbt"&&i.push(y))}};a(t,0);for(let p of s){let u=_e(p);u&&r(yr(u))}for(let p of o){let u=_e(p);u&&r(xr(u))}for(let p of i){let u=_e(p);u&&r(pt(u))}try{let p=ut.join(t,"project");for(let u of mt.readdirSync(p,{withFileTypes:!0}))if(u.isFile()&&u.name.endsWith(".scala")){let m=_e(ut.join(p,u.name));m&&r(pt(m))}}catch{}let c=Object.keys(e);if(c.length===0)return null;let l={};for(let p of c)l[p]={version:e[p]};return l}function Zn(t){let e=dr(t),r=br(t);return r?{...e??{dependencies:{}},jvmDependencies:r}:e}import es from"path";function G(t){switch(es.extname(t).toLowerCase()){case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".ts":case".tsx":return"typescript";case".css":return"css";case".scss":case".sass":return"scss";case".less":return"less";case".styl":return"stylus";case".coffee":return"coffeescript";case".ls":return"livescript";case".lua":return"lua";case".py":return"python";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":case".sc":return"scala";case".groovy":case".gradle":return"groovy";case".cpp":case".cc":case".cxx":case".c":return"unknown";case".feature":return"gherkin";case".md":case".mdx":return"markdown";default:return"unknown"}}function D(t){let e=es.extname(t).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}import pa from"coffeescript";function U(t){return t.startsWith("'")||t.startsWith('"')?t.slice(1,-1):t}function ge(t){let e=new Set,r=/@tag\s+([a-zA-Z0-9_-]+)/g,n=r.exec(t);for(;n!==null;)n[1]&&e.add(n[1]),n=r.exec(t);return e}function de(t,e){let r=t.toLowerCase();return r.includes(".test.")||r.includes(".spec.")||e.has("test")?"test":"logic"}function rs(t){if(t){if(typeof t.originalValue=="string")return t.originalValue;if(typeof t.value=="string")return U(t.value)}}function Y(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function ua(t,e){let r=rs(e.source);return r?{fromPath:t,toPath:"",rawSpecifier:r,isStyle:D(r),type:"static"}:null}function ma(t,e){let r=e.variable?.base?.value==="require",n=rs(e.args?.[0]?.base);return!r||!n?null:{fromPath:t,toPath:"",rawSpecifier:n,isStyle:D(n),type:"require"}}function ts(t,e){if(e)return[{name:e}];let r=t.value;if(r?.constructor?.name==="Class"){let s=Y(r.variable);return s?[{name:s}]:[]}if(r?.base?.constructor?.name==="Obj"&&Array.isArray(r.base.properties))return r.base.properties.map(s=>Y(s.variable)??Y(s)).filter(s=>!!s).map(s=>({name:s}));let n=Y(r);return n?[{name:n}]:[]}function fa(t){if(Array.isArray(t.specifiers))return t.specifiers.map(r=>r.identifier??r.original?.value).filter(r=>!!r).map(r=>({name:r}));let e=Y(t.variable)??Y(t.variable?.base);return e?[{name:e}]:[]}function ga(t,e,r,n){let s=e.constructor?.name;if(s==="ImportDeclaration"){let o=ua(t,e);o&&r.push(o)}else if(s==="Call"){let o=ma(t,e);o&&r.push(o)}else if(s==="Assign"){let o=Y(e.variable?.base),i=e.variable?.properties?.[0]?.name?.value;o==="module"&&i==="exports"?n.push(...ts(e,void 0)):o==="exports"&&typeof i=="string"&&n.push(...ts(e,i))}else s==="ExportNamedDeclaration"&&e.clause?n.push(...fa(e.clause)):s==="ExportDefaultDeclaration"&&n.push({name:"default"})}function Sr(t,e,r,n){if(!(!e||typeof e!="object")){ga(t,e,r,n);for(let s in e){if(s==="locationData")continue;let o=e[s];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let i of o)Sr(t,i,r,n);else Sr(t,o,r,n)}}}function ns(t,e){let r=ge(e),n=de(t,r),s=[],o=[];try{Sr(t,pa.nodes(e),s,o)}catch{}let i=new Set,a=o.filter(c=>i.has(c.name)?!1:(i.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(r).map(c=>({name:c,kind:"comment-marker"})),category:n}}import{AstBuilder as da,GherkinClassicTokenMatcher as ha,Parser as ya}from"@cucumber/gherkin";import{IdGenerator as xa}from"@cucumber/messages";var ss=new Map;function he(t,e){ss.set(t,e)}function os(t){return ss.get(t)}var ba=xa.uuid();function kr(t,e){let r=new Set,n=s=>{for(let o of s)r.add(o.name.startsWith("@")?o.name.slice(1):o.name)};try{let s=new da(ba),o=new ha,a=new ya(s,o).parse(e);if(a.feature){n(a.feature.tags);for(let c of a.feature.children){if(c.scenario){n(c.scenario.tags);for(let l of c.scenario.examples)n(l.tags)}if(c.rule)for(let l of c.rule.children)l.scenario&&n(l.scenario.tags)}}}catch(s){console.warn(`[GherkinParser] Failed to parse ${t}:`,s)}return{imports:[],exports:[],tags:Array.from(r).map(s=>({name:s,kind:"comment-marker"})),category:"test"}}he("gherkin",kr);import wa from"path";import{parser as Ea}from"@lezer/go";function X(t){let e=[],r=t.firstChild;for(;r;)e.push(r),r=r.nextSibling;return e}function Z(t,e){let r=1;for(let n=0;n<e&&n<t.length;n++)t[n]===`
|
|
7
|
+
`&&r++;return r}function Sa(t,e){let r=1;function n(s){switch(s.type.name){case"IfStatement":case"ForStatement":r++;break;case"Case":{s.firstChild?.type.name==="case"&&r++;break}case"LogicOp":{let i=e.slice(s.from,s.to);(i==="&&"||i==="||")&&r++;break}}let o=s.firstChild;for(;o;)n(o),o=o.nextSibling}return n(t),r}function as(t,e,r,n){let s=r?1:1+e,o=X(t),i=r?e:e+1,a=o[1];a&&a.type.name!=="Block"&&(s+=ye(a,i,!1,n));let c=o.find(p=>p.type.name==="Block");c&&(s+=ye(c,i,!1,n));let l=o.findIndex(p=>p.type.name==="else");if(l>=0){let p=o[l+1];p?.type.name==="IfStatement"?s+=as(p,e,!0,n):p&&(s+=1+ye(p,e+1,!1,n))}return s}function is(t,e,r){let n=1+e,s=t.firstChild;for(;s;)n+=ye(s,e+1,!1,r),s=s.nextSibling;return n}function ka(t,e,r){let n=0,s=t.firstChild;for(;s;)n+=ye(s,e,!1,r),s=s.nextSibling;return n}function va(t,e){let r=e.slice(t.from,t.to);return r==="&&"||r==="||"}function ye(t,e,r,n){let s=t.type.name;if(s==="IfStatement")return as(t,e,r,n);if(s==="ForStatement"||s==="SwitchStatement"||s==="SelectStatement")return is(t,e,n);let o=s==="LogicOp"&&va(t,n)?1:0;return e>0&&s==="FunctionLiteral"?o+is(t,e,n):o+ka(t,e,n)}function Ca(t,e){return ye(t,0,!1,e)}function ft(t,e){return{complexity:Sa(t,e),cognitiveComplexity:Ca(t,e)}}function vr(t,e){let n=t.getChild("Parameters")?.getChild("Parameter"),s=n?.getChild("TypeName")??n?.getChild("PointerType")?.getChild("TypeName");return s?e.slice(s.from,s.to):void 0}function cs(t,e){let r=[],n=t.cursor();do if(n.name==="FunctionDecl"){let s=n.node.getChild("DefName");if(s){let o=e.slice(s.from,s.to),{complexity:i,cognitiveComplexity:a}=ft(n.node,e);r.push({name:o,line:Z(e,n.from),complexity:i,cognitiveComplexity:a})}}else if(n.name==="MethodDecl"){let s=n.node.getChild("FieldName");if(s){let o=e.slice(s.from,s.to),i=vr(n.node,e),a=i?`${i}.${o}`:o,{complexity:c,cognitiveComplexity:l}=ft(n.node,e);r.push({name:a,line:Z(e,n.from),complexity:c,cognitiveComplexity:l})}}while(n.next());return r}var Ta=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,Fa=/^\/\/go:build\s+(.+)$/,Pa=/^\/\/\s*\+build\s+(.+)$/;function ps(t,e){let r=[],n=new Map,s=new Set,o=new Set,i=new Map,a=Ea.parse(e),c=a.cursor();do switch(c.name){case"LineComment":{let x=e.slice(c.from,c.to),C=x.match(Ta);C?.[1]&&s.add(C[1]);let A=x.match(Fa);A&&ls(A[1],o);let S=x.match(Pa);S&&ls(S[1],o);break}case"ImportSpec":{let x=c.node.getChild("String");if(x){let A=e.slice(x.from,x.to).slice(1,-1);r.push({fromPath:t,toPath:"",rawSpecifier:A,isExternal:!0,isStyle:!1,type:"static"});let S=c.node.getChild("DefName"),E=S?e.slice(S.from,S.to):A.split("/").pop();E&&E!=="_"&&E!=="."&&i.set(E,A)}break}case"FunctionDecl":case"MethodDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let x=c.node.getChild("DefName")??c.node.getChild("FieldName")??c.node.getChild("TypeSpec")?.getChild("DefName")??c.node.getChild("VarSpec")?.getChild("DefName")??c.node.getChild("ConstSpec")?.getChild("DefName");if(x){let C=e.slice(x.from,x.to);C!=="_"&&/^[A-Z]/.test(C)&&!n.has(C)&&n.set(C,{name:C})}break}}while(c.next());let l=r.some(x=>x.rawSpecifier==="testing"),p=wa.basename(t).endsWith("_test.go")||s.has("test")||l?"test":"logic",u=new Set([...s,...o]),{complexity:m,cognitiveComplexity:d}=ft(a.topNode,e),y=cs(a,e),v=p==="test"?[]:Aa(a,e,i);return{imports:r,exports:Array.from(n.values()),tags:Array.from(u).map(x=>({name:x,kind:"comment-marker"})),category:p,rawCallEdges:v,complexity:m,cognitiveComplexity:d,...y.length>0?{functions:y}:{}}}function Aa(t,e,r){let n=[];function s(i,a){if(i.type.name==="CallExpr"){let l=i.firstChild;if(l?.type.name==="SelectorExpr"){let p=l.firstChild,u=l.getChild("FieldName");if(p?.type.name==="VariableName"&&u){let m=e.slice(p.from,p.to),d=r.get(m);if(d){let y=e.slice(u.from,u.to);n.push({from:a,to:y,toSpecifier:d})}}}}let c=i.firstChild;for(;c;)s(c,a),c=c.nextSibling}let o=t.cursor();do if(o.name==="FunctionDecl"){let i=o.node.getChild("DefName"),a=o.node.getChild("Block");if(i&&a){let c=e.slice(i.from,i.to);/^[A-Z]/.test(c)&&s(a,c)}}else if(o.name==="MethodDecl"){let i=o.node.getChild("FieldName"),a=o.node.getChild("Block");if(i&&a){let c=e.slice(i.from,i.to),l=vr(o.node,e);s(a,l?`${l}.${c}`:c)}}while(o.next());return n}function ls(t,e){for(let r of t.split(/[\s,&|!()]+/)){let n=r.trim();n&&n!=="ignore"&&e.add(n)}}var Na=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/g,Ra=["org.junit","androidx.test","org.robolectric","org.mockito","org.scalatest","munit","spock.lang","io.kotest","org.spekframework","org.testng","org.assertj","com.google.truth","org.hamcrest","io.mockk","com.nhaarman.mockitokotlin2"],Cr=["test","androidTest","integrationTest","it"],Da=new RegExp(`/src/(${Cr.join("|")})/`),Ia=/(?:Test|Tests|Spec|IT|ITCase)$/;function wr(t){let e=t.replace(/\.\w+$/,"");return Ia.test(e)}function xe(t){let e=new Set;for(let r of t.matchAll(Na))r[1]&&e.add(r[1]);return e}function K(t){let e=t.replace(/\/\*[\s\S]*?\*\//g,r=>r.replace(/[^\n]/g," "));return e=e.replace(/\/\/[^\n]*/g,r=>" ".repeat(r.length)),e}function be(t){let e=K(t),r=new Set;for(let s of e.matchAll(/@([A-Z]\w*)/g))s[1]&&r.add(s[1]);let n=new Set;for(let s of e.matchAll(/\b(?:class|object|interface|trait|enum)\s+([A-Za-z_]\w*)/g))s[1]&&n.add(s[1]);return{annotations:[...r],typeNames:[...n]}}function Se(t,e){return{fromPath:t,toPath:"",rawSpecifier:e,isExternal:!0,isStyle:!1,type:"static"}}function J(t,e){return{fromPath:t,toPath:"",rawSpecifier:`${e}.*`,isExternal:!0,isStyle:!1,type:"side-effect",isSamePackage:!0}}function M(t,e){let r=[];for(let n of K(t).split(`
|
|
8
|
+
`)){let s=n.trim();if(!s||s.startsWith("@")||s.startsWith("*"))continue;let o=s.match(/^package\s+(?:object\s+)?([\w.]+)/);if(o?.[1]){if(r.push(o[1]),!e)break;continue}if(!(e&&/^import\s/.test(s)))break}return r.length>0?r.join("."):null}var Ma=new Set(["Configuration","SpringBootApplication","EnableAutoConfiguration"]),_a=new Set(["Composable","Preview"]),La=new Set(["RestController","Controller","Service","Repository","Component","Entity","MappedSuperclass","Embeddable"]),Ga=["Activity","Fragment","ViewModel","Screen","Composable"];function O(t,e,r={}){let n=t.replace(/\\/g,"/"),s=n.split("/").pop()??"";if(s.endsWith(".gradle")||s==="build.gradle.kts"||s==="settings.gradle.kts")return"config";if(Da.test(n)||e.some(i=>Ra.some(a=>i===a||i.startsWith(`${a}.`))))return"test";let o=r.annotations??[];return o.some(i=>Ma.has(i))?"config":o.some(i=>_a.has(i))||(r.typeNames??[]).some(i=>Ga.some(a=>i.endsWith(a)))?"ui":o.some(i=>La.has(i))?"logic":wr(s)?"test":"logic"}var Oa=/^\s*import\s+(static\s+)?([\w.]+(?:\.\*)?)(?:\s+as\s+\w+)?\s*$/,ja=/^(?:@\w+\s+)*(?:public\s+|private\s+|protected\s+|final\s+|abstract\s+|static\s+)*(class|interface|trait|enum|def)\s+([A-Za-z_][A-Za-z0-9_]*)/;function Wa(t,e){return t?e.endsWith(".*")?e.slice(0,-2)||null:e.split(".").slice(0,-1).join(".")||null:e||null}function us(t,e){let r=xe(e),s=K(e).split(`
|
|
9
|
+
`),o=[],i=new Set;for(let l of s){let p=l.match(Oa);if(p?.[2]){let m=Wa(!!p[1],p[2]);m&&o.push(Se(t,m));continue}let u=l.match(ja);u?.[2]&&i.add(u[2])}let a=M(e,!1);a&&o.push(J(t,a));let c=Array.from(i,l=>({name:l}));return{imports:o,exports:c,tags:Array.from(r).map(l=>({name:l,kind:"comment-marker"})),category:O(t,o.map(l=>l.rawSpecifier),{typeNames:[...i],annotations:be(e).annotations})}}import{parser as Ka}from"@lezer/java";var ms=new Set(["ForStatement","EnhancedForStatement","WhileStatement","DoStatement"]),za=new Set(["ClassDeclaration","InterfaceDeclaration","EnumDeclaration","RecordDeclaration","AnnotationTypeDeclaration"]);function $a(t,e){let r=1;function n(s){let o=s.type.name;if(o==="IfStatement"||o==="CatchClause"||o==="TernaryExpression")r++;else if(ms.has(o))r++;else if(o==="SwitchLabel")s.firstChild?.type.name==="case"&&r++;else if(o==="LogicOp"){let a=e.slice(s.from,s.to);(a==="&&"||a==="||")&&r++}let i=s.firstChild;for(;i;)n(i),i=i.nextSibling}return n(t),r}function fs(t,e,r,n){let s=r?1:1+e,o=[];for(let p=t.firstChild;p;p=p.nextSibling)o.push(p);let i=r?e:e+1,a=o[1];a&&a.type.name!=="Block"&&(s+=ke(a,i,!1,n));let c=o.find(p=>p.type.name==="Block");c&&(s+=ke(c,i,!1,n));let l=o.findIndex(p=>p.type.name==="else");if(l>=0){let p=o[l+1];p?.type.name==="IfStatement"?s+=fs(p,e,!0,n):p&&(s+=1+ke(p,e+1,!1,n))}return s}function Er(t,e,r){let n=1+e,s=t.firstChild;for(;s;)n+=ke(s,e+1,!1,r),s=s.nextSibling;return n}function Ba(t,e,r){let n=0,s=t.firstChild;for(;s;)n+=ke(s,e,!1,r),s=s.nextSibling;return n}function Ha(t,e){let r=e.slice(t.from,t.to);return r==="&&"||r==="||"}function ke(t,e,r,n){let s=t.type.name;if(s==="IfStatement")return fs(t,e,r,n);if(ms.has(s)||s==="SwitchStatement"||s==="CatchClause"||s==="TernaryExpression")return Er(t,e,n);let o=s==="LogicOp"&&Ha(t,n)?1:0;return e>0&&s==="LambdaExpression"?o+Er(t,e,n):o+Ba(t,e,n)}function Ua(t,e){return ke(t,0,!1,e)}function Tr(t,e){return{complexity:$a(t,e),cognitiveComplexity:Ua(t,e)}}function Fr(t,e){for(let r=t.parent;r;r=r.parent)if(za.has(r.type.name)){let n=r.getChild("Definition");if(n)return e.slice(n.from,n.to)}}function gs(t,e){let r=[],n=t.cursor();do if(n.name==="MethodDeclaration"||n.name==="ConstructorDeclaration"){let s=n.node.getChild("Definition");if(s){let o=e.slice(s.from,s.to),i=Fr(n.node,e),a=i&&n.name==="MethodDeclaration"?`${i}.${o}`:o,{complexity:c,cognitiveComplexity:l}=Tr(n.node,e);r.push({name:a,line:Z(e,n.from),complexity:c,cognitiveComplexity:l})}}while(n.next());return r}var Ja=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/;function qa(t,e){let r=t.getChild("ScopedIdentifier");if(!r)return null;let n=t.getChild("static")!=null,s=t.getChild("Asterisk")!=null,o=e.slice(r.from,r.to);return n?(s||(o=o.split(".").slice(0,-1).join(".")),o?{specifier:o,wildcard:!1}:null):s?{specifier:`${o}.*`,wildcard:!0}:{specifier:o,wildcard:!1}}function Va(t){let e=new Map;for(let r of t){if(r.type==="side-effect")continue;let n=r.rawSpecifier;if(n.endsWith(".*"))continue;let s=n.split(".").pop();s&&e.set(s,n)}return e}function Qa(t,e){let r=t;if(r.name==="GenericType"&&(r=r.firstChild),!r)return null;if(r.name==="TypeName")return e.slice(r.from,r.to);if(r.name==="ScopedTypeName"){let n=null;for(let s=r.firstChild;s;s=s.nextSibling)s.name==="TypeName"&&(n=s);return n?e.slice(n.from,n.to):null}return null}function Ya(t,e,r){let n=[];function s(i,a){let c=i.type.name;if(c==="MethodInvocation"){let p=i.firstChild;if(p?.type.name==="Identifier"){let u=r.get(e.slice(p.from,p.to)),m=i.getChild("MethodName");u&&m&&n.push({from:a,to:e.slice(m.from,m.to),toSpecifier:u})}}else if(c==="ObjectCreationExpression"){let p=i.getChild("TypeName")??i.getChild("GenericType")??i.getChild("ScopedTypeName"),u=p&&Qa(p,e);if(u){let m=r.get(u);m&&n.push({from:a,to:"new",toSpecifier:m})}}let l=i.firstChild;for(;l;)s(l,a),l=l.nextSibling}let o=t.cursor();do if(o.name==="MethodDeclaration"||o.name==="ConstructorDeclaration"){let i=o.node.getChild("Definition"),a=o.node.getChild("Block")??o.node.getChild("ConstructorBody");if(i&&a){let c=e.slice(i.from,i.to),l=Fr(o.node,e),p=l&&o.name==="MethodDeclaration"?`${l}.${c}`:c;s(a,p)}}while(o.next());return n}function ds(t,e){let r=[],n=new Map,s=new Set,o=new Set,i;try{i=Ka.parse(e)}catch{return{imports:[],exports:[],tags:[],category:O(t,[])}}let a=i.cursor();do switch(a.name){case"LineComment":{let y=e.slice(a.from,a.to).match(Ja);y?.[1]&&s.add(y[1]);break}case"MarkerAnnotation":case"Annotation":{let y=a.node.getChild("Identifier");y&&o.add(e.slice(y.from,y.to));break}case"ImportDeclaration":{let y=qa(a.node,e);y&&r.push({fromPath:t,toPath:"",rawSpecifier:y.specifier,isExternal:!0,isStyle:!1,type:"static"});break}case"ClassDeclaration":case"InterfaceDeclaration":case"EnumDeclaration":case"AnnotationTypeDeclaration":{if(a.node.parent?.name==="Program"){let y=a.node.getChild("Definition");if(y){let v=e.slice(y.from,y.to);n.has(v)||n.set(v,{name:v})}}break}}while(a.next());let c=M(e,!1);c&&r.push(J(t,c));let l=O(t,r.map(y=>y.rawSpecifier),{typeNames:[...n.keys()],annotations:[...o]}),{complexity:p,cognitiveComplexity:u}=Tr(i.topNode,e),m=gs(i,e),d=l==="test"?[]:Ya(i,e,Va(r));return{imports:r,exports:Array.from(n.values()),tags:Array.from(s).map(y=>({name:y,kind:"comment-marker"})),category:l,rawCallEdges:d,complexity:p,cognitiveComplexity:u,...m.length>0?{functions:m}:{}}}var Xa=/^\s*import\s+([\w.]+(?:\.\*)?)(?:\s+as\s+\w+)?\s*$/,Pr="(?:public\\s+|internal\\s+|private\\s+|protected\\s+|open\\s+|abstract\\s+|final\\s+|sealed\\s+|data\\s+|value\\s+|inline\\s+|noinline\\s+|crossinline\\s+|external\\s+|expect\\s+|actual\\s+|suspend\\s+|operator\\s+|infix\\s+|tailrec\\s+|const\\s+|lateinit\\s+)*",Za=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${Pr}(?:(?:enum|annotation)\\s+)?(class|interface|object|typealias)\\s+([A-Za-z_][A-Za-z0-9_]*)`),ec=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${Pr}fun\\s+(?:<[^>]*>\\s*)?(?:[A-Za-z_][\\w.]*(?:<[^>]*>)?\\.)?([A-Za-z_][A-Za-z0-9_]*)\\s*[(<]`),tc=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${Pr}(?:val|var)\\s+(?:<[^>]*>\\s*)?([A-Za-z_][A-Za-z0-9_]*)`);function hs(t,e){let r=xe(e),s=K(e).split(`
|
|
10
|
+
`),o=[],i=new Set;for(let l of s){let p=l.match(Xa);if(p?.[1]){o.push(Se(t,p[1]));continue}let u=l.match(Za);if(u?.[2]){i.add(u[2]);continue}let m=l.match(ec);if(m?.[1]){i.add(m[1]);continue}let d=l.match(tc);d?.[1]&&i.add(d[1])}let a=M(e,!1);a&&o.push(J(t,a));let c=Array.from(i,l=>({name:l}));return{imports:o,exports:c,tags:Array.from(r).map(l=>({name:l,kind:"comment-marker"})),category:O(t,o.map(l=>l.rawSpecifier),{typeNames:[...i],annotations:be(e).annotations})}}import rc from"livescript";function ee(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function nc(t){if(!t)return[];if(t.constructor?.name==="Class"){let r=ee(t.title);return r?[{name:r}]:[]}if(t.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(r=>ee(r.key)??ee(r.val)).filter(r=>!!r).map(r=>({name:r}));let e=ee(t);return e?[{name:e}]:[]}function sc(t){let e=t.constructor?.name||t.type;if(e==="Assign"&&t.left?.constructor?.name==="Chain"){let r=t.left,n=ee(r.head),o=r.tails?.[0]?.key?.name;if(n==="module"&&o==="exports")return nc(t.right);if(n==="exports"&&typeof o=="string")return[{name:o}];if(r.head?.verb==="out"&&typeof o=="string")return[{name:o}]}if(e==="Import"&&t.left?.verb==="out"){let r=t.right;if(r?.constructor?.name==="Obj"&&Array.isArray(r.items))return r.items.map(n=>ee(n.val)??ee(n.key)).filter(n=>!!n).map(n=>({name:n}))}return[]}var oc=new Set(["first_line","first_column","last_line","last_column","line","column"]);function ic(t,e){let r=t.constructor?.name||t.type;if(r==="Import"){let n=t.right?.value;if(typeof n=="string"){let s=U(n);return{fromPath:e,toPath:"",rawSpecifier:s,isStyle:D(s),type:"static"}}}if(r==="Chain"&&t.head?.value==="require"){let n=t.tails?.[0];if(n?.constructor?.name==="Call"||n?.type==="Call"){let s=n.args?.[0]?.value;if(typeof s=="string"){let o=U(s);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:D(o),type:"require"}}}}return null}function Ar(t,e,r){if(!t||typeof t!="object")return[];let n=[],s=ic(t,e);s&&n.push(s),r.push(...sc(t));for(let o in t){if(oc.has(o))continue;let i=t[o];if(!(!i||typeof i!="object"))if(Array.isArray(i))for(let a of i)n.push(...Ar(a,e,r));else n.push(...Ar(i,e,r))}return n}function ys(t,e){let r=ge(e),n=de(t,r),s=[],o=[];try{s=Ar(rc.ast(e),t,o)}catch{}let i=new Set,a=o.filter(c=>i.has(c.name)?!1:(i.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(r).map(c=>({name:c,kind:"comment-marker"})),category:n}}import ac from"luaparse";function cc(t,e){let r=[];function n(s){if(!(!s||typeof s!="object")){if((s.type==="CallExpression"||s.type==="StringCallExpression")&&s.base?.type==="Identifier"&&s.base?.name==="require"){let o;if(s.type==="CallExpression"){let i=s.arguments?.[0];i?.type==="StringLiteral"&&(o=U(i.raw))}else if(s.type==="StringCallExpression"){let i=s.argument;i?.type==="StringLiteral"&&(o=U(i.raw))}o&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:D(o),type:"require"})}for(let o in s){if(o==="loc")continue;let i=s[o];if(i&&typeof i=="object")if(Array.isArray(i))for(let a of i)n(a);else n(i)}}}return n(t),r}function lc(t){let e=new Set;for(let r of t)r.type==="LocalStatement"&&r.variables.forEach((n,s)=>{r.init[s]?.type==="TableConstructorExpression"&&e.add(n.name)});return e}function pc(t){let e=t[t.length-1];if(e?.type!=="ReturnStatement")return[];let r=e.arguments[0];if(r?.type!=="TableConstructorExpression")return[];let n=[];for(let s of r.fields)s.type==="TableKeyString"&&n.push({name:s.key.name});return n}function uc(t){let e=t.body,r=lc(e),n=pc(e);for(let o of e)if(o.type==="FunctionDeclaration")o.identifier?.type==="MemberExpression"?o.identifier.base.type==="Identifier"&&r.has(o.identifier.base.name)&&n.push({name:o.identifier.identifier.name}):o.identifier?.type==="Identifier"&&!o.isLocal&&n.push({name:o.identifier.name});else if(o.type==="AssignmentStatement")for(let i of o.variables)i.type==="MemberExpression"&&i.base.type==="Identifier"&&r.has(i.base.name)&&n.push({name:i.identifier.name});let s=new Set;return n.filter(o=>s.has(o.name)?!1:(s.add(o.name),!0))}function xs(t,e){let r=ge(e),n=de(t,r),s=[],o=[];try{let i=ac.parse(e);s=cc(i,t),o=uc(i)}catch{}return{imports:s,exports:o,tags:Array.from(r).map(i=>({name:i,kind:"comment-marker"})),category:n}}var mc=["http://","https://","mailto:","//"],fc="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",gc=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${fc})\\b`,"g"),bs;async function dc(){return bs??=(async()=>{let{unified:t}=await import("unified"),e=(await import("remark-parse")).default;return t().use(e)})(),bs}function hc(t){let e=t.trim();return e.length===0||e.startsWith("#")||mc.some(r=>e.startsWith(r))}function yc(t,e){let r=t.match(gc);return r?r.map(n=>({fromPath:e,toPath:"",rawSpecifier:n,isStyle:!1,type:"static",isDocReference:!0})):[]}function Ss(t,e,r){if(t.type==="link"&&typeof t.url=="string"&&!hc(t.url)&&r.push({fromPath:e,toPath:"",rawSpecifier:t.url,isStyle:!1,type:"static",isDocReference:!0}),(t.type==="code"||t.type==="inlineCode")&&typeof t.value=="string"&&r.push(...yc(t.value,e)),Array.isArray(t.children))for(let n of t.children)Ss(n,e,r)}async function ks(t,e){let n=(await dc()).parse(e),s=[];Ss(n,t,s);let o=new Set;return{imports:s.filter(a=>o.has(a.rawSpecifier)?!1:(o.add(a.rawSpecifier),!0)),exports:[],tags:[],category:"other"}}import Cc from"path";import{parser as wc}from"@lezer/python";function xc(t){let e=1;function r(n){switch(n.type.name){case"IfStatement":{e+=X(n).filter(o=>o.type.name==="if"||o.type.name==="elif").length;break}case"TryStatement":{e+=X(n).filter(o=>o.type.name==="except").length;break}case"ForStatement":case"WhileStatement":case"ConditionalExpression":e++;break;case"and":case"or":e++;break}let s=n.firstChild;for(;s;)r(s),s=s.nextSibling}return r(t),e}function bc(t,e){let r=0,n=X(t),s=0,o=0;for(;o<n.length;){let i=n[o];if(i?.type.name==="if"||i?.type.name==="elif"){let a=s>0;r+=a?1:1+e;let c=a?e:e+1,l=n[o+1],p=n[o+2];l&&(r+=j(l,c)),p&&(r+=j(p,c)),s++,o+=3}else if(i?.type.name==="else"){r+=1;let a=n[o+1];a&&(r+=j(a,e+1)),o+=2}else o++}return r}function Sc(t,e){let r=0,n=X(t),s=0;for(;s<n.length;){let o=n[s];if(o?.type.name==="except"){for(r+=1+e,s++;s<n.length&&n[s]?.type.name!=="Body";)r+=j(n[s],e),s++;s<n.length&&(r+=j(n[s],e),s++)}else o?.type.name==="Body"&&(r+=j(o,e)),s++}return r}function vs(t,e){let r=1+e,n=t.firstChild;for(;n;)r+=j(n,e+1),n=n.nextSibling;return r}function kc(t,e){let r=0,n=t.firstChild;for(;n;)r+=j(n,e),n=n.nextSibling;return r}function j(t,e){let r=t.type.name;switch(r){case"IfStatement":return bc(t,e);case"TryStatement":return Sc(t,e);case"ForStatement":case"WhileStatement":return vs(t,e);default:{let n=r==="ConditionalExpression"||r==="and"||r==="or"?1:0;return e>0&&(r==="FunctionDefinition"||r==="LambdaExpression")?n+vs(t,e):n+kc(t,e)}}}function vc(t){return j(t,0)}function Nr(t){return{complexity:xc(t),cognitiveComplexity:vc(t)}}function Cs(t,e){let r=[];function n(i,a){let{complexity:c,cognitiveComplexity:l}=Nr(i);r.push({name:a,line:Z(e,i.from),complexity:c,cognitiveComplexity:l})}function s(i){let a=i.firstChild;for(;a;)o(a),a=a.nextSibling}function o(i){if(i.type.name==="ClassDefinition"){let a=i.getChild("VariableName"),c=a?e.slice(a.from,a.to):void 0,l=i.getChild("Body");if(l){let p=l.firstChild;for(;p;){if(p.type.name==="FunctionDefinition"){let u=p.getChild("VariableName"),m=u?e.slice(u.from,u.to):void 0;m&&n(p,c?`${c}.${m}`:m),s(p)}else o(p);p=p.nextSibling}}return}if(i.type.name==="FunctionDefinition"){let a=i.getChild("VariableName");a&&n(i,e.slice(a.from,a.to)),s(i);return}s(i)}return o(t.topNode),r}var Ec=new Set(["pytest","unittest","nose","hypothesis"]);function ws(t,e){let r=[],n=[],s=new Set,o=Cc.basename(t).toLowerCase(),i=wc.parse(e),a=i.cursor();do switch(a.name){case"Comment":{let d=e.slice(a.from,a.to).match(/#\s*@tag\s+([a-zA-Z0-9_-]+)/);d?.[1]&&s.add(d[1]);break}case"ImportStatement":{for(let d of Tc(a.node,e,t))r.push(d);break}case"FunctionDefinition":case"ClassDefinition":{let d=a.node.parent;if(d?.name==="Script"||d?.name==="DecoratedStatement"&&d.parent?.name==="Script"){let v=a.node.getChild("VariableName");v&&n.push({name:e.slice(v.from,v.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let d=a.node.firstChild;d?.name==="VariableName"&&n.push({name:e.slice(d.from,d.to)})}break}}while(a.next());let c=Dc(o,r,s);c==="test"&&s.add("test");let{complexity:l,cognitiveComplexity:p}=Nr(i.topNode),u=Cs(i,e),m=c==="test"?[]:Rc(i,e);return{imports:r,exports:n,tags:Array.from(s).map(d=>({name:d,kind:"comment-marker"})),category:c,rawCallEdges:m,complexity:l,cognitiveComplexity:p,...u.length>0?{functions:u}:{}}}function Tc(t,e,r){let n=t.firstChild;return n?n.name==="from"?Fc(t,e,r):Pc(t,e,r):[]}function Fc(t,e,r){let n=t.firstChild;if(!n)return[];let s=n.nextSibling;for(;s&&s.name!=="import";)s=s.nextSibling;if(!s)return[];let o=e.slice(n.to,s.from).trim(),i=Ac(s.nextSibling,e);if(!i.length)return[];let a=0;for(;a<o.length&&o[a]===".";)a++;let c=o.slice(a);if(a===0)return[Le(r,o,i,!0)];let l=a===1?"./":"../".repeat(a-1);return c?[Le(r,l+c.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[Le(r,l.slice(0,-1),["*"],!1)]:i.map(p=>Le(r,l+p,[p],!1))}function Pc(t,e,r){let n=[],s=t.firstChild?.nextSibling??null;for(;s;){if(s.name==="VariableName"){let o=e.slice(s.from,s.to);for(;s.nextSibling?.name==="."&&s.nextSibling.nextSibling?.name==="VariableName";)s=s.nextSibling.nextSibling,o+=`.${e.slice(s.from,s.to)}`;s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling),n.push(Le(r,o,["*"],!0))}s=s.nextSibling}return n}function Ac(t,e){let r=[],n=t;for(;n;)n.name==="*"?r.push("*"):n.name==="VariableName"&&(r.push(e.slice(n.from,n.to)),n.nextSibling?.name==="as"&&(n=n.nextSibling.nextSibling??n.nextSibling)),n=n.nextSibling;return r}function Nc(t,e){let r=new Map,n=t.cursor();do{if(n.name!=="ImportStatement")continue;let o=n.node.firstChild;if(o?.type.name!=="from")continue;let i=o.nextSibling;for(;i&&i.type.name!=="import";)i=i.nextSibling;if(!i)continue;let a=e.slice(o.to,i.from).trim(),c=0;for(;c<a.length&&a[c]===".";)c++;let l=a.slice(c),p=c<=1?"./":"../".repeat(c-1),u=i.nextSibling;for(;u;){if(u.type.name==="VariableName"){let m=e.slice(u.from,u.to),d=m;if(u.nextSibling?.type.name==="as"){let v=u.nextSibling.nextSibling;v?.type.name==="VariableName"&&(d=e.slice(v.from,v.to),u=v)}let y=c===0?a:l?p+l.replace(/\./g,"/"):p+m;r.set(d,y)}u=u.nextSibling}}while(n.next());return r}function Rc(t,e){let r=Nc(t,e),n=[];function s(a,c){if(a.type.name==="CallExpression"&&a.firstChild?.type.name==="VariableName"){let p=a.firstChild,u=e.slice(p.from,p.to),m=r.get(u);m&&n.push({from:c,to:u,toSpecifier:m})}let l=a.firstChild;for(;l;)s(l,c),l=l.nextSibling}function o(a){let c=a.firstChild;for(;c;)i(c),c=c.nextSibling}function i(a){if(a.type.name==="ClassDefinition"){let c=a.getChild("VariableName"),l=c?e.slice(c.from,c.to):void 0,p=a.getChild("Body");if(p){let u=p.firstChild;for(;u;){if(u.type.name==="FunctionDefinition"){let m=u.getChild("VariableName"),d=m?e.slice(m.from,m.to):void 0;d&&s(u,l?`${l}.${d}`:d)}else i(u);u=u.nextSibling}}return}if(a.type.name==="FunctionDefinition"){let c=a.getChild("VariableName");c&&s(a,e.slice(c.from,c.to));return}o(a)}return i(t.topNode),n}function Le(t,e,r,n){return{fromPath:t,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:n,type:"static",symbols:r.length>0?r:void 0}}function Dc(t,e,r){return t.startsWith("test_")||t.endsWith("_test.py")?"test":t==="conftest.py"||t==="setup.py"?"config":r.has("test")||e.some(n=>Ec.has(n.rawSpecifier))?"test":"logic"}var Ic=/^\s*import\s+(.+?)\s*$/,Mc=/^(?:@\w+\s+)*(?:private\s+|protected\s+|final\s+|sealed\s+|abstract\s+|implicit\s+|case\s+)*(class|trait|object|type|enum)\s+([A-Za-z_$][A-Za-z0-9_$]*)/;function _c(t,e){let r=e.split("=>")[0]?.trim();return r?r==="_"||r==="*"||r==="given"?`${t}.*`:`${t}.${r}`:null}function Lc(t){let e=t.indexOf("{");if(e!==-1){let n=t.indexOf("}",e),s=t.slice(0,e).trim().replace(/\.$/,""),o=t.slice(e+1,n===-1?void 0:n);return s?o.split(",").map(i=>_c(s,i.trim())).filter(i=>i!=null):[]}let r=[];for(let n of t.split(",")){let s=n.trim().replace(/\s+as\s+\w+$/,"");if(s)if(s.endsWith("._")||s.endsWith(".*")||s.endsWith(".given")){let o=s.replace(/\.(_|\*|given)$/,"");o&&r.push(`${o}.*`)}else r.push(s)}return r}function Es(t,e){let r=xe(e),s=K(e).split(`
|
|
11
|
+
`),o=[],i=new Set;for(let l of s){let p=l.match(Ic);if(p?.[1]){for(let m of Lc(p[1]))o.push(Se(t,m));continue}let u=l.match(Mc);u?.[2]&&i.add(u[2])}let a=M(e,!0);a&&o.push(J(t,a));let c=Array.from(i,l=>({name:l}));return{imports:o,exports:c,tags:Array.from(r).map(l=>({name:l,kind:"comment-marker"})),category:O(t,o.map(l=>l.rawSpecifier),{typeNames:[...i],annotations:be(e).annotations})}}import As from"path";import h from"typescript";import k from"typescript";function Gc(t){let e=1;function r(n){switch(n.kind){case k.SyntaxKind.IfStatement:case k.SyntaxKind.ConditionalExpression:case k.SyntaxKind.ForStatement:case k.SyntaxKind.ForInStatement:case k.SyntaxKind.ForOfStatement:case k.SyntaxKind.WhileStatement:case k.SyntaxKind.DoStatement:case k.SyntaxKind.CatchClause:case k.SyntaxKind.CaseClause:e++;break;case k.SyntaxKind.BinaryExpression:{let s=n.operatorToken.kind;(s===k.SyntaxKind.AmpersandAmpersandToken||s===k.SyntaxKind.BarBarToken||s===k.SyntaxKind.QuestionQuestionToken)&&e++;break}}k.forEachChild(n,r)}return r(t),e}function Fs(t,e,r){let n=r?1:1+e,s=r?e:e+1;return n+=te(t.expression,s,!1),n+=te(t.thenStatement,s,!1),t.elseStatement&&(k.isIfStatement(t.elseStatement)?n+=Fs(t.elseStatement,e,!0):n+=1+te(t.elseStatement,e+1,!1)),n}function Ts(t,e){let r=1+e;return k.forEachChild(t,n=>{r+=te(n,e+1,!1)}),r}function Oc(t,e){let r=1+e;return k.forEachChild(t,n=>{r+=te(n,e,!1)}),r}function jc(t,e){let r=0;return k.forEachChild(t,n=>{r+=te(n,e,!1)}),r}function Wc(t){let e=t.operatorToken.kind;return e===k.SyntaxKind.AmpersandAmpersandToken||e===k.SyntaxKind.BarBarToken||e===k.SyntaxKind.QuestionQuestionToken}function te(t,e,r){if(k.isIfStatement(t))return Fs(t,e,r);if(k.isForStatement(t)||k.isForInStatement(t)||k.isForOfStatement(t)||k.isWhileStatement(t)||k.isDoStatement(t)||k.isSwitchStatement(t))return Ts(t,e);if(k.isCatchClause(t))return Oc(t,e);let n=0;return k.isConditionalExpression(t)&&(n+=1),k.isBinaryExpression(t)&&Wc(t)&&(n+=1),e>0&&(k.isFunctionDeclaration(t)||k.isFunctionExpression(t)||k.isArrowFunction(t))?n+Ts(t,e):n+jc(t,e)}function zc(t){return te(t,0,!1)}function Rr(t){return{complexity:Gc(t),cognitiveComplexity:zc(t)}}import w from"typescript";var Dr=new Set(["test","describe","it"]);function Ps(t,e){$c(t,e),Hc(t,e),Uc(t,e),Kc(t,e)}function $c(t,e){if((w.isFunctionDeclaration(t)||w.isVariableDeclaration(t))&&t.name&&w.isIdentifier(t.name)&&Bc(t)){let r;if(w.isFunctionDeclaration(t))r="function";else{let n=t.initializer;r=n&&(w.isArrowFunction(n)||w.isFunctionExpression(n))?"function":"variable"}e.tags.add({name:t.name.text,kind:r})}}function Bc(t){if(w.isFunctionDeclaration(t))return w.isSourceFile(t.parent);let e=t.parent?.parent;return!!e&&w.isSourceFile(e.parent)}function Hc(t,e){if(!w.isStringLiteral(t))return;let r=t.text.match(/@[\w-]+/g);if(r)for(let n of r)e.tags.add({name:n.substring(1),kind:"comment-marker"})}function Uc(t,e){if(!w.isSourceFile(t))return;let r=/@tag\s+([a-zA-Z0-9_-]+)/g,n=t.getFullText(),s=r.exec(n);for(;s!==null;)s[1]&&e.tags.add({name:s[1],kind:"comment-marker"}),s=r.exec(n)}function Kc(t,e){if(w.isCallExpression(t)&&Jc(t.expression))for(let r of t.arguments)w.isObjectLiteralExpression(r)&&qc(r,e)}function Jc(t){return w.isIdentifier(t)?Dr.has(t.text):!!(w.isPropertyAccessExpression(t)&&(Dr.has(t.name.text)||w.isIdentifier(t.expression)&&Dr.has(t.expression.text)))}function qc(t,e){for(let r of t.properties){if(!w.isPropertyAssignment(r)||!w.isIdentifier(r.name)||r.name.text!=="tags"&&r.name.text!=="tag")continue;let{initializer:n}=r,s=w.isArrayLiteralExpression(n)?n.elements.filter(w.isStringLiteral):r.name.text==="tag"&&w.isStringLiteral(n)?[n]:[];for(let o of s)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function Ir(t,e,r){let n=[],s=new Map,o=new Set,i=h.createSourceFile(t,e,h.ScriptTarget.Latest,!0,r==="typescript"?h.ScriptKind.TSX:h.ScriptKind.JSX),a={filePath:t,imports:n,exports:s,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=v=>{Xc(v,a),h.forEachChild(v,c)};c(i);let l=ll(t,a);(l==="test"||l==="barrel")&&o.add({name:l,kind:"comment-marker"}),l!=="test"&&pl(a,i);let p=i.statements[0],u=p?Rs(p):void 0,{complexity:m,cognitiveComplexity:d}=Rr(i),y=Vc(i);return{imports:n,exports:Array.from(s.values()),tags:Array.from(o),category:l,rawCallEdges:a.rawCallEdges??[],complexity:m,cognitiveComplexity:d,...y.length>0?{functions:y}:{},...u!==void 0?{description:u}:{}}}function Vc(t){let e=[],r=(s,o)=>{let{complexity:i,cognitiveComplexity:a}=Rr(o),c=t.getLineAndCharacterOfPosition(o.getStart(t)).line+1;e.push({name:s,line:c,complexity:i,cognitiveComplexity:a})},n=(s,o)=>{if(h.isFunctionDeclaration(s)&&s.name&&s.body?r(s.name.text,s):h.isVariableDeclaration(s)&&h.isIdentifier(s.name)&&s.initializer&&(h.isArrowFunction(s.initializer)||h.isFunctionExpression(s.initializer))?r(s.name.text,s.initializer):o&&h.isMethodDeclaration(s)&&h.isIdentifier(s.name)&&s.body?r(`${o}.${s.name.text}`,s):o&&h.isConstructorDeclaration(s)&&s.body?r(`${o}.constructor`,s):o&&h.isGetAccessorDeclaration(s)&&h.isIdentifier(s.name)&&s.body?r(`${o}.get ${s.name.text}`,s):o&&h.isSetAccessorDeclaration(s)&&h.isIdentifier(s.name)&&s.body&&r(`${o}.set ${s.name.text}`,s),h.isClassDeclaration(s)&&s.name){let i=s.name.text;h.forEachChild(s,a=>n(a,i));return}h.forEachChild(s,i=>n(i,o))};return n(t,void 0),e}function Ns(t,e,r,n){let s={name:t},o=Rs(r);o!==void 0&&(s.doc=o);let i=Qc(e);i!==void 0&&(s.flags=i);let a=Yc(e,n);return a!==void 0&&(s.signature=a),s}function Rs(t){let e=h.getJSDocCommentsAndTags(t);for(let r of e)if(h.isJSDoc(r)&&r.comment)return h.getTextOfJSDocComment(r.comment)||void 0}function Qc(t){let e=new Set(["deprecated","internal","public","alpha","beta"]),r=h.getJSDocTags(t).map(n=>n.tagName.text).filter(n=>e.has(n));return r.length>0?r:void 0}function Yc(t,e){let r=h.createPrinter({removeComments:!0}),n=s=>r.printNode(h.EmitHint.Unspecified,s,e);if(h.isFunctionDeclaration(t)||h.isMethodDeclaration(t)){let s=t.parameters.map(n).join(", "),o=t.type?n(t.type):"void";return`${t.typeParameters?`<${t.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${s}) => ${o}`}if(h.isVariableDeclaration(t)){if(t.type)return n(t.type);if(t.initializer&&(h.isArrowFunction(t.initializer)||h.isFunctionExpression(t.initializer))){let s=t.initializer,o=s.parameters.map(n).join(", "),i=s.type?n(s.type):"unknown";return`(${o}) => ${i}`}return}if(h.isClassDeclaration(t)&&t.name)return`class ${t.name.text}`;if(h.isInterfaceDeclaration(t))return`interface ${t.name.text}`;if(h.isTypeAliasDeclaration(t))return n(t.type);if(h.isEnumDeclaration(t))return`enum ${t.name.text}`}function Xc(t,e){Zc(t,e),el(t,e),rl(t,e),nl(t,e),cl(t,e),Ps(t,e)}function Zc(t,e){if(!h.isSourceFile(t))return;let r=t.statements.filter(n=>!h.isEmptyStatement(n));e.totalStatements=r.length,e.exportStatements=r.filter(n=>h.isExportDeclaration(n)||h.isExportAssignment(n)||Mr(n)).length}function el(t,e){if(h.isJsxElement(t)||h.isJsxSelfClosingElement(t)||h.isJsxFragment(t)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(h.isFunctionDeclaration(t)||h.isMethodDeclaration(t)||h.isArrowFunction(t)||h.isClassDeclaration(t)||h.isVariableStatement(t)||h.isEnumDeclaration(t)){e.hasTypesOnly=!1;return}h.isExportDeclaration(t)&&!tl(t)&&(e.hasTypesOnly=!1)}function tl(t){return t.isTypeOnly?!0:!t.exportClause||!h.isNamedExports(t.exportClause)?!1:t.exportClause.elements.every(e=>e.isTypeOnly)}function rl(t,e){if(!h.isImportDeclaration(t)||!t.moduleSpecifier||!h.isStringLiteral(t.moduleSpecifier))return;let r=[];if(t.importClause&&(t.importClause.name&&r.push("default"),t.importClause.namedBindings))if(h.isNamedImports(t.importClause.namedBindings))for(let s of t.importClause.namedBindings.elements)r.push(s.name.text);else h.isNamespaceImport(t.importClause.namedBindings)&&r.push("*");let n=r.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.moduleSpecifier.text,isStyle:D(t.moduleSpecifier.text),type:n,symbols:r.length>0?r:void 0})}function nl(t,e){h.isExportDeclaration(t)?sl(t,e):h.isExportAssignment(t)?e.exports.set("default",{name:"default"}):Mr(t)&&al(t,e)}function sl(t,e){if(t.moduleSpecifier&&h.isStringLiteral(t.moduleSpecifier))ol(t,t.moduleSpecifier.text,e);else if(t.exportClause&&h.isNamedExports(t.exportClause))for(let r of t.exportClause.elements){let n=r.name.text;e.exports.set(n,{name:n})}}function ol(t,e,r){let n=il(t),s={fromPath:r.filePath,toPath:"",rawSpecifier:e,isStyle:D(e),type:"re-export"};n.length>0&&(s.symbols=n),r.imports.push(s)}function il(t){return t.exportClause?h.isNamedExports(t.exportClause)?t.exportClause.elements.map(e=>e.name.text):[]:["*"]}function al(t,e){if((h.isFunctionDeclaration(t)||h.isClassDeclaration(t)||h.isInterfaceDeclaration(t)||h.isTypeAliasDeclaration(t)||h.isEnumDeclaration(t))&&t.name){let n=t.name.text;e.exports.set(n,Ns(n,t,t,e.sourceFile));return}if(h.isVariableStatement(t)){for(let n of t.declarationList.declarations)if(h.isIdentifier(n.name)){let s=n.name.text;e.exports.set(s,Ns(s,n,t,e.sourceFile))}}}function cl(t,e){if(!h.isCallExpression(t))return;let r=t.arguments[0];!r||!h.isStringLiteral(r)||(t.expression.kind===h.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:D(r.text),type:"dynamic"}):h.isIdentifier(t.expression)&&t.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:D(r.text),type:"require"}))}function ll(t,e){let r=As.basename(t).toLowerCase(),n=As.extname(t).toLowerCase();return Ne().some(o=>r.includes(o))?"test":Nn(r)?"config":e.imports.some(o=>Yt().some(i=>o.rawSpecifier.includes(i)))?"test":n===".tsx"||n===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>er()?"barrel":"logic"}function Mr(t){return h.canHaveModifiers(t)&&h.getModifiers(t)?.some(e=>e.kind===h.SyntaxKind.ExportKeyword)===!0}function pl(t,e){let r=t.rawCallEdges??[];t.rawCallEdges=r;let n=new Map;for(let s of e.statements){if(!h.isImportDeclaration(s)||!h.isStringLiteral(s.moduleSpecifier))continue;let o=s.moduleSpecifier.text,i=s.importClause;if(i&&(i.name&&n.set(i.name.text,o),i.namedBindings&&h.isNamedImports(i.namedBindings)))for(let a of i.namedBindings.elements)n.set(a.name.text,o)}if(n.size!==0)for(let s of e.statements){let o=ml(s);if(o){let i=fl(s);i&>(i,o,n,r);continue}h.isClassDeclaration(s)&&s.name&&ul(s,s.name.text,n,r)}}function ul(t,e,r,n){for(let s of t.members)h.isMethodDeclaration(s)&&s.body&&h.isIdentifier(s.name)?gt(s.body,`${e}.${s.name.text}`,r,n):h.isConstructorDeclaration(s)&&s.body&>(s.body,`${e}.constructor`,r,n)}function ml(t){if(Mr(t)){if(h.isFunctionDeclaration(t)&&t.name)return t.name.text;if(h.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(h.isIdentifier(e.name)&&e.initializer&&(h.isArrowFunction(e.initializer)||h.isFunctionExpression(e.initializer)))return e.name.text}}}function fl(t){if(h.isFunctionDeclaration(t))return t.body;if(h.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(e.initializer&&(h.isArrowFunction(e.initializer)||h.isFunctionExpression(e.initializer)))return e.initializer}}function gt(t,e,r,n){if(h.isCallExpression(t)&&h.isIdentifier(t.expression)){let s=t.expression.text,o=r.get(s);o&&!n.some(i=>i.from===e&&i.to===s&&i.toSpecifier===o)&&n.push({from:e,to:s,toSpecifier:o})}h.forEachChild(t,s=>gt(s,e,r,n))}function dt(t,e){if(e.length===0)return"ui";let r=!1;return t.walk(n=>{if(n.type==="rule")return r=!0,!1}),r?"ui":"barrel"}import Is from"postcss";import*as gl from"postcss-less";var dl=gl,Ms=new Set(["reference","inline"]);function Ds(t){return t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("data:")}function hl(t){let e=t.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function yl(t,e){let r=t.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(r){let o=r[1]?.trim()??"",i=r[2]??"";if(!i)return null;let a=Ms.has(o)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a,...Ds(i)?{isExternal:!0}:{}}}let n=t.match(/^url\(['"]?([^'")]+)['"]?\)/),s=n?n[1]?.trim()??"":t.match(/^['"]([^'"]+)['"]/)?.[1]??"";return s?{fromPath:e,toPath:"",rawSpecifier:s,isStyle:!0,type:"static",...Ds(s)?{isExternal:!0}:{}}:null}function xl(t,e){let r=[],n=/url\(['"]?([^'")]+)['"]?\)/g,s=n.exec(t);for(;s!==null;){let o=s[1]?.trim()??"";hl(o)&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),s=n.exec(t)}return r}function _s(t,e){let r=[];return t.walk(n=>{if(n.type==="atrule"&&n.name==="import"){let s=yl(n.params,e);s&&r.push(s)}n.type==="decl"&&r.push(...xl(n.value,e))}),r}function bl(t){return t.replace(/(?<!:)\/\/.*/g,"")}function Sl(t,e){let r=[],n=/@import\s+(?:\(([^)]+)\)\s+)?['"]([^'"]+)['"]/g,s=n.exec(t);for(;s!==null;){let o=s[1]?.trim()??"",i=s[2]??"";if(i){let a=Ms.has(o)?"side-effect":"static";r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a})}s=n.exec(t)}return r}function ht(t,e){let r=Is.parse(bl(t));return{imports:_s(r,e),root:r}}function kl(t){let e=[],r=[];for(let n of t.nodes??[]){if(n.type!=="atrule")continue;let{value:s}=n;if(s===void 0)continue;let o=n.name;o&&(e.push({name:o}),r.push({name:o,kind:"variable"}))}return{exports:e,tags:r}}function yt(t,e){try{let r=dl.parse(t),{exports:n,tags:s}=kl(r);return{imports:_s(r,e),root:r,exports:n,tags:s}}catch{return{imports:Sl(t,e),root:Is.parse(""),exports:[],tags:[]}}}import{parse as vl}from"postcss-scss";function Ls(t){return t.startsWith("_")||t.startsWith("-")}function Cl(t){return!!(t.startsWith("sass:")||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("_"))}function wl(t){let e=t.match(/^['"]([^'"]+)['"]/);if(!e?.[1])return{specifier:""};let r=e[1],s=t.match(/\bas\s+(\S+)/)?.[1];return s!==void 0?{specifier:r,alias:s}:{specifier:r}}function El(t){let e=[],r=[];for(let n of t.nodes??[]){if(n.type==="decl"&&n.prop.startsWith("$")){let s=n.prop.slice(1);if(!s||Ls(s))continue;e.push({name:s}),r.push({name:s,kind:"variable"});continue}if(n.type==="atrule"&&(n.name==="mixin"||n.name==="function")){let o=n.params.match(/^([\w-]+)/)?.[1];if(!o||Ls(o))continue;let i=n.params.trim();e.push(i.includes("(")?{name:o,signature:i}:{name:o}),r.push({name:o,kind:"function"})}}return{exports:e,tags:r}}function xt(t,e){let r=vl(t),n=[];r.walk(i=>{if(i.type!=="atrule")return;let{name:a,params:c}=i;if(a!=="import"&&a!=="use"&&a!=="forward")return;let{specifier:l,alias:p}=wl(c);if(!l)return;let u={fromPath:e,toPath:"",rawSpecifier:l,isStyle:!0,type:a==="forward"?"re-export":"static",...Cl(l)?{isExternal:!0}:{}};p&&(u.symbols=[p]),n.push(u)});let{exports:s,tags:o}=El(r);return{imports:n,root:r,exports:s,tags:o}}function Gs(t,e){let r=[],n=/@require\s+['"]([^'"]+)['"]/g,s=n.exec(t);for(;s!==null;){let i=s[1];i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"require"}),s=n.exec(t)}let o=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(s=o.exec(t);s!==null;){let i=s[1];i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),s=o.exec(t)}return r}function Os(t,e){if(e.length===0)return"ui";try{let r=Jt("stylus");return new r.Parser(t).parse().nodes.some(o=>o.constructor.name!=="Import")?"ui":"barrel"}catch{return t.replace(/^\s*@?(?:require|import)\b.*/gm,"").trim().length>0?"ui":"barrel"}}function Ge(t,e){let r=G(t);if(r==="stylus"){let o=Gs(e,t);return{imports:o,exports:[],tags:[],category:Os(e,o)}}if(r==="scss"){let{imports:o,root:i,exports:a,tags:c}=xt(e,t);return{imports:o,exports:a,tags:c,category:dt(i,o)}}if(r==="less"){let{imports:o,root:i,exports:a,tags:c}=yt(e,t);return{imports:o,exports:a,tags:c,category:dt(i,o)}}let{imports:n,root:s}=ht(e,t);return{imports:n,exports:[],tags:[],category:dt(s,n)}}for(let[t,e]of[["javascript",(r,n)=>Ir(r,n,"javascript")],["typescript",(r,n)=>Ir(r,n,"typescript")],["css",Ge],["scss",Ge],["less",Ge],["stylus",Ge],["coffeescript",ns],["livescript",ys],["lua",xs],["python",ws],["go",ps],["java",ds],["kotlin",hs],["scala",Es],["groovy",us],["gherkin",kr],["markdown",ks]])he(t,e);async function js(t,e){let r=G(t),n=os(r);return n?n(t,e):{imports:[],exports:[],tags:[],category:"other"}}import Ws from"path";function Tl(t,e){let r=e.get(t.path);r!==void 0&&(t.coveragePct=r)}function $s(t,e){for(let r of t)if(r.isExternal){let n=r.rawSpecifier.startsWith("@")?r.rawSpecifier.split("/").slice(0,2).join("/"):r.rawSpecifier.split("/")[0];n&&!e.some(s=>s.name===n)&&e.push({name:n,kind:"library"})}}function Fl(t,e,r){if(e.isExternal||!e.toPath)return;let n=r.get(e.toPath);n&&(n.category!=="logic"&&n.category!=="barrel"||(n.testedBy??=[],n.testedBy.includes(t.path)||n.testedBy.push(t.path)))}function Pl(t,e){if(t.type==="markdown")for(let r of t.imports){if(r.isExternal||!r.toPath)continue;let n=e.get(r.toPath);!n||n===t||(n.documentedBy??=[],n.documentedBy.includes(t.path)||n.documentedBy.push(t.path),n.category==="logic"&&(n.lastCommitAt??0)>(t.lastCommitAt??0)&&(t.staleFor??=[],t.staleFor.includes(n.path)||t.staleFor.push(n.path)))}}function zs(t){return Math.round(t*1e4)/1e4}function Al(t,e){let r=[];for(let n of t.imports){if(n.isExternal||!n.toPath)continue;let s=e.get(n.toPath);if(!s||s.exports.length===0)continue;let o;if(n.symbols===void 0){if(n.type==="side-effect")continue;o=1}else n.symbols.includes("*")?o=1:o=n.symbols.length/s.exports.length;n.exportUsageRatio=zs(Math.min(1,o)),r.push(n.exportUsageRatio)}r.length>0&&(t.avgExportUsage=zs(r.reduce((n,s)=>n+s,0)/r.length),t.maxExportUsage=Math.max(...r))}function _r(t,e,r){e&&(t.some(n=>n.name===e&&n.kind===r)||t.push({name:e,kind:r}))}function Nl(t,e){let r=e.toPath,n=Ws.basename(r,Ws.extname(r)).replace(/\.(test|spec)$/,"");_r(t.tags,n,"import")}function Rl(t,e){if(!(!e.symbols||e.symbols.includes("*")))for(let r of e.symbols)_r(t.tags,r,"import")}function Dl(t,e,r){let n=r.get(e.toPath);if(!(!n||n.category==="test"))for(let s of n.tags)s.kind==="comment-marker"&&_r(t.tags,s.name,"comment-marker")}function Il(t,e,r){!e.toPath||e.isExternal||(Nl(t,e),Rl(t,e),Dl(t,e,r))}function Bs(t,e){for(let r of t.values())delete r.testedBy,delete r.documentedBy,delete r.staleFor,r.category==="test"&&(r.tags=r.tags.filter(n=>n.kind!=="import"));for(let r of t.values()){if(Al(r,t),e.size>0&&Tl(r,e),r.category==="test")for(let n of r.imports)Fl(r,n,t),Il(r,n,t);Pl(r,t)}}var Hs=new Set(["java","kotlin","scala","groovy"]),Us=new Set(["typescript","javascript","python","go","java","kotlin","scala","groovy","scss","less","lua","coffeescript"]),Ks=new Set(["typescript","javascript","python"]),bt=new Set(["typescript","javascript","go","python","java"]);function Lr(t){let e=new Map;for(let r of t.nodes.values())e.set(r.type,(e.get(r.type)??0)+1);return[...e.entries()].map(([r,n])=>({type:r,fileCount:n,exportsTracked:Us.has(r),importSymbolsTracked:Ks.has(r),callEdgesTracked:bt.has(r)})).sort((r,n)=>n.fileCount-r.fileCount)}import Ct from"fs";import W from"path";import Vs from"fs";import ve from"path";var Oe=class{extensions=[".go"];goModCache=new Map;resolve(e,r,n,s){let{mod:o,replaces:i}=this.readGoMod(n);if(!o)return null;let a=this.applyReplace(r,i,n);if(a!==void 0)return qs(a);if(r!==o&&!r.startsWith(`${o}/`))return null;let c=r.slice(o.length).replace(/^\//,"");return c?qs(ve.join(n,c)):null}readGoMod(e){let r=this.goModCache.get(e);if(r!==void 0)return r;let n={mod:null,replaces:new Map};try{let s=Vs.readFileSync(ve.join(e,"go.mod"),"utf-8"),o=Ml(s,e);return this.goModCache.set(e,o),o}catch{return this.goModCache.set(e,n),n}}applyReplace(e,r,n){for(let[s,o]of r){if(e===s)return o;if(e.startsWith(`${s}/`)){let i=e.slice(s.length+1);return ve.join(o,i)}}}};function Ml(t,e){let r=t.split(`
|
|
12
|
+
`),n=null,s=new Map,o=!1;for(let i of r){let a=i.trim();if(a.startsWith("module ")){n=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){o=!0;continue}if(o&&a===")"){o=!1;continue}if(o&&a.includes("=>")){Js(a,e,s);continue}!o&&/^replace\s+/.test(a)&&a.includes("=>")&&Js(a.replace(/^replace\s+/,""),e,s)}return{mod:n,replaces:s}}function Js(t,e,r){let[n,s]=t.split("=>").map(a=>a.trim());if(!n||!s)return;let o=n.split(/\s+/)[0];if(!s.startsWith(".")&&!s.startsWith("/"))return;let i=ve.isAbsolute(s)?s:ve.resolve(e,s);r.set(o,i)}function qs(t){let e;try{e=Vs.readdirSync(t,{withFileTypes:!0})}catch{return null}let r=e.filter(n=>n.isFile()&&n.name.endsWith(".go")&&!n.name.endsWith("_test.go")).map(n=>({path:ve.join(t,n.name),isExternal:!1})).sort((n,s)=>n.path.localeCompare(s.path));return r.length>0?r:null}import St from"fs";import kt from"path";var _l=new Set([".java",".kt",".kts",".scala",".sc",".groovy"]),Ll=12,Qs=4096,Gl=new Set(Cr);function Xs(t){let e=t.replace(/\\/g,"/"),r=e.match(/^(.*)\/src\/([^/]+)(?:\/|$)/);if(!r?.[1]||!r[2]){let o=e.lastIndexOf("/");return{module:o===-1?e:e.slice(0,o),rootSegment:"",sourceRoot:"unknown"}}let n=r[2],s=n==="main"?"main":Gl.has(n)?n:"unknown";return{module:r[1],rootSegment:n,sourceRoot:s}}var re=class{constructor(e=[]){this.extraIgnoreDirs=e}extraIgnoreDirs;extensions=[".java",".kt",".kts",".scala",".sc",".groovy",".gradle"];indexCache=new Map;resolve(e,r,n,s){let o=this.getIndex(n);if(o.size===0)return null;let i=r.endsWith(".*"),a=(i?r.slice(0,-2):r).split(".").filter(Boolean);if(a.length===0)return null;if(i){let c=o.get(a.join("."));if(!c)return null;let l=Xs(e),p=c.filter(d=>d.module===l.module&&d.rootSegment===l.rootSegment),u=l.sourceRoot!=="main"&&l.sourceRoot!=="unknown",m=p.flatMap(d=>u?d.files:d.files.filter(y=>!wr(Ys(y))));return Gr(m)}for(let c=a.length-1;c>=1;c--){let l=jl(o,a.slice(0,c).join("."));if(!l)continue;let p=a[c],u=l.filter(m=>Ys(m)===p);if(u.length>0)return Gr(u);if(c===a.length-1)return Gr(l)}return null}getIndex(e){let r=this.indexCache.get(e);if(r)return r;let n=Ol(e,this.extraIgnoreDirs);return this.indexCache.set(e,n),n}};function Ol(t,e=[]){let r=new Map,n=(process.env.MOKOSH_IGNORE_DIRS??"").split(",").map(a=>a.trim()).filter(Boolean),s=new Set([...N,...n,...e]),o=(a,c)=>{let{module:l,rootSegment:p,sourceRoot:u}=Xs(c),m=r.get(a);if(!m){r.set(a,[{module:l,rootSegment:p,sourceRoot:u,files:[c]}]);return}let d=m.find(y=>y.module===l&&y.rootSegment===p);d?d.files.push(c):m.push({module:l,rootSegment:p,sourceRoot:u,files:[c]})},i=(a,c)=>{if(c>Ll)return;let l;try{l=St.readdirSync(a,{withFileTypes:!0})}catch{return}for(let p of l){let u=kt.join(a,p.name);if(p.isDirectory()){!p.name.startsWith(".")&&!s.has(p.name)&&i(u,c+1);continue}if(!p.isFile())continue;let m=kt.extname(p.name);if(!_l.has(m))continue;let d=Wl(u,m===".scala"||m===".sc");d&&o(d,u)}};i(t,0);for(let a of r.values())for(let c of a)c.files.sort();return r}function jl(t,e){let r=t.get(e);if(!(!r||r.length===0))return r.length===1?r[0]?.files:r.flatMap(n=>n.files).sort()}function Wl(t,e){let r;try{let n=St.openSync(t,"r");try{let s=Buffer.alloc(Qs),o=St.readSync(n,s,0,Qs,0);r=s.toString("utf8",0,o)}finally{St.closeSync(n)}}catch{return null}return M(r,e)}function Gr(t){return!t||t.length===0?null:t.map(e=>({path:e,isExternal:!1}))}function Ys(t){return kt.basename(t,kt.extname(t))}import zl from"fs";import Or from"path";var je=class{extensions=[".lua"];resolve(e,r,n,s){let o=r.replace(/\./g,Or.sep),i=[n,Or.join(n,"lib")];for(let a of i){if(!zl.existsSync(a))continue;let c=s(Or.join(a,"_dummy.lua"),o);if(c)return[c]}return null}};import $l from"path";var Bl=new Set(N),We=class{extensions=[".md",".mdx"];resolve(e,r,n,s){let o=r.replace(/^\.\//,"").split("/")[0];if(o&&Bl.has(o))return null;let i=s($l.join(n,"_dummy"),`./${r}`);return i?[i]:null}};import Hl from"fs";import jr from"path";var ze=class{extensions=[".py"];resolve(e,r,n,s){let o=r.replace(/\./g,jr.sep),i=jr.join(n,`${o}.py`);if(Zs(i))return[{path:i,isExternal:!1}];let a=jr.join(n,o,"__init__.py");return Zs(a)?[{path:a,isExternal:!1}]:null}};function Zs(t){try{return Hl.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}import eo from"path";var Ul=["~","http://","https://","//","data:","sass:"],$e=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,r,n,s){if(Ul.some(p=>r.startsWith(p)))return null;let o=s(e,r);if(o)return[o];let i=eo.dirname(r),a=eo.basename(r),c=i==="."?`_${a}`:`${i}/_${a}`,l=s(e,c);return l?[l]:null}};function vt(t={}){return[new ze,new je,new Oe,t.jvm??new re,new $e,new We]}var z=class{constructor(e,r={}){this.rootDir=e;this.workspaceMap=r.workspaceMap??new Map,this.tsconfigSearchPaths=r.tsconfigSearchPaths??[e],this.pathAliases=r.pathAliases,this.langResolvers=r.langResolvers??vt()}rootDir;workspaceMap;tsconfigSearchPaths;pathAliases;langResolvers;resolutionCache=new Map;langBucketFor(e){for(let r=0;r<this.langResolvers.length;r++)if(this.langResolvers[r]?.extensions.some(n=>e.endsWith(n)))return String(r);return"none"}cacheKey(e,r){return`${W.dirname(e)}\0${this.langBucketFor(e)}\0${r}`}resolveAll(e,r){let n=this.cacheKey(e,r),s=this.resolutionCache.get(n);if(s!==void 0)return s??[];let o=this.resolveAllUncached(e,r);return this.resolutionCache.set(n,o.length>0?o:null),o}resolveAllUncached(e,r){let n=this.resolvePathAlias(r);if(n)return[n];if(r.startsWith(".")||r.startsWith("/")){let i=this.resolveLocalPath(e,r);return i?[i]:[]}let s=(i,a)=>this.resolveLocalPath(i,a);for(let i of this.langResolvers)if(i.extensions.some(a=>e.endsWith(a))){let a=i.resolve(e,r,this.rootDir,s);if(a)return a}let o=this.resolveWorkspaceImport(r);return o?[o]:[{path:r,isExternal:!0}]}resolve(e,r){return this.resolveAll(e,r)[0]??null}resolveLocalPath(e,r){let n=W.dirname(e),s=r.startsWith("/")?r:W.resolve(n,r),o=!s.startsWith(this.rootDir),i=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature",".md",".mdx"],a=s.match(/\.(js|mjs|cjs)$/);if(a){let c=s.slice(0,-a[0].length);for(let l of[".ts",".tsx"]){let p=this.tryExtensions(c,l,o);if(p)return p}}for(let c of i){let l=this.tryExtensions(s,c,o);if(l)return l}return o?{path:s,isExternal:!0}:null}tryExtensions(e,r,n){let s=e+r;if(this.isFile(s))return{path:s,isExternal:n};let o=W.join(e,`index${r}`);if(this.isFile(o))return{path:o,isExternal:n};if(r===".py"){let i=W.join(e,"__init__.py");if(this.isFile(i))return{path:i,isExternal:n}}return null}isFile(e){try{return Ct.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){if(this.pathAliases)for(let r in this.pathAliases){let n=this.matchAliasPattern(r,e),s=this.pathAliases[r];if(n&&s){let o=this.tryAliasSubstitutions(s,n[1]||"");if(o)return o}}for(let r of this.tsconfigSearchPaths){let n=W.join(r,"tsconfig.json");if(Ct.existsSync(n))try{let o=JSON.parse(Ct.readFileSync(n,"utf-8")).compilerOptions?.paths;if(!o)continue;for(let i in o){let a=this.matchAliasPattern(i,e);if(a){let c=this.tryAliasSubstitutions(o[i],a[1]||"",r);if(c)return c}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,r){let n=this.aliasRegexCache.get(e);if(!n){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");n=new RegExp(`^${s}$`),this.aliasRegexCache.set(e,n)}return r.match(n)}tryAliasSubstitutions(e,r,n=this.rootDir){let s=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let o of e){let i=o.replace("*",r),a=W.resolve(n,i);for(let c of s){let l=this.tryExtensions(a,c,!1);if(l)return l}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[r,n]of this.workspaceMap){if(e!==r&&!e.startsWith(`${r}/`))continue;let s=e.slice(r.length),o={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:r};if(!s){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let c=W.join(n,a);try{if(Ct.statSync(c,{throwIfNoEntry:!1})?.isFile())return{...o,path:c}}catch{}}return{...o,path:n}}let i=this.resolveLocalPath(W.join(n,"_dummy"),s.slice(1));return i?{...o,path:i.path}:null}return null}};var Jl=["tests","test","__tests__","specs","spec"],ql=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage",".pytest_cache","__pycache__"],Vl=600;function Ql(){return(process.env.MOKOSH_IGNORE_DIRS??"").split(",").map(t=>t.trim()).filter(Boolean)}function Yl(t,e){if(t.length===0)return e;let r=t.map(i=>P.dirname(i).split(P.sep)),n=r[0]??[];for(let i of r.slice(1)){let a=0;for(;a<n.length&&a<i.length&&n[a]===i[a];)a++;n=n.slice(0,a)}let s=n.join(P.sep)||P.sep,o=P.relative(e,s);return o.startsWith("..")||P.isAbsolute(o)?e:s}var ne=class{constructor(e,r=null,n,s,o=!1,i=new Map,a=!0,c=[],l=null){this.rootDir=e;this.enableGitStats=o;this.coverageMap=i;this.parallelParsing=a;this.docFiles=l;this.previousGraph=r,this.walkIgnoreDirs=new Set([...ql,...c,...Ql()]),this.resolver=n||new z(e),this.lockFile=Zn(e),s&&(this.progressCallback=s)}rootDir;enableGitStats;coverageMap;parallelParsing;docFiles;graph={nodes:new Map};visited=new Set;queue=[];previousGraph=null;resolver;lockFile=null;progressCallback;pool=null;gitStatsMap=null;walkIgnoreDirs;async build(e){let r=e.map(n=>P.isAbsolute(n)?n:P.resolve(this.rootDir,n));await this.initPool(),this.enableGitStats&&(this.gitStatsMap=Kn(this.rootDir));try{for(let n of r)this.enqueue(n);return await this.drain(),await this.processTestFiles(Yl(r,this.rootDir)),await this.processDocFiles(),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
|
|
13
|
+
Done. Total processed: ${this.visited.size} nodes.
|
|
14
|
+
`),Bs(this.graph.nodes,this.coverageMap),new R(this.graph.nodes)}finally{this.pool&&(await this.pool.destroy(),this.pool=null)}}async initPool(){if(this.parallelParsing===!1)return;let e=typeof this.parallelParsing=="object"?this.parallelParsing:{},r=e.minFiles??Vl;if(!(r>0&&!this.hasAtLeastFiles(this.rootDir,r))){e.maxThreads!==void 0&&e.maxThreads<1&&process.stderr.write(`
|
|
15
|
+
Warning: parallelParsing.maxThreads (${e.maxThreads}) must be at least 1; using 1.
|
|
16
|
+
`);try{let n=P.join(f,"parse-worker.js");this.pool=new Kl({filename:n,...e.maxThreads!==void 0?{maxThreads:Math.max(1,e.maxThreads)}:{}})}catch(n){process.stderr.write(`
|
|
17
|
+
Warning: failed to start parse worker pool, falling back to synchronous parsing: ${n}
|
|
18
|
+
`),this.pool=null}}}hasAtLeastFiles(e,r){let n=0,s=[e];for(;s.length>0;){let o=s.pop();if(o===void 0)continue;let i;try{i=Be.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let a of i)if(a.isDirectory())this.walkIgnoreDirs.has(a.name)||s.push(P.join(o,a.name));else if(a.isFile()&&(n++,n>=r))return!0}return n>=r}async processTestFiles(e){let r=Ne(),n=o=>r.some(i=>o.name.includes(i));this.walkProject(e,n);let s=e;for(;s!==this.rootDir;){let o=P.dirname(s);if(o===s)break;for(let i of Jl){let a=P.join(o,i);try{Be.statSync(a).isDirectory()&&this.walkProject(a,n)}catch{}}s=o}await this.drain()}async processDocFiles(){if(this.docFiles!==null){for(let e of this.docFiles)this.enqueue(e);await this.drain();return}this.walkProject(this.rootDir,e=>e.name.endsWith(".md")||e.name.endsWith(".mdx")),await this.drain()}walkProject(e,r){let n;try{n=Be.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of n){let o=P.join(e,s.name);s.isDirectory()?this.walkIgnoreDirs.has(s.name)||this.walkProject(o,r):s.isFile()&&r(s)&&this.enqueue(o)}}enqueue(e){this.visited.has(e)||(this.visited.add(e),this.showProgress(),this.queue.push(e))}async drain(){for(;this.queue.length>0;){let e=this.queue;this.queue=[],await Promise.all(e.map(r=>this.finishFile(r)))}}async finishFile(e){let r=Be.statSync(e,{throwIfNoEntry:!1});if(!r?.isFile())return;let n=P.relative(this.rootDir,e),s=await this.getNode(e,n,r);s.imports=await this.resolveImports(e,s.imports),$s(s.imports,s.tags),this.graph.nodes.set(s.path,s)}async getNode(e,r,n){let s=this.previousGraph?.nodes.get(r);if(s&&s.mtime===n.mtimeMs&&s.size===n.size)return{...s};let o=await this.tryParse(e,r);if(!o)return this.makeStubNode(e,r,n);let i=this.resolveCallEdges(e,o.rawCallEdges),a=this.buildNode(e,r,n,o,i);return this.attachGitStats(a,r),a}async tryParse(e,r){let n=Be.readFileSync(e,"utf-8");try{return await this.parseContent(e,n)}catch(s){return process.stderr.write(`
|
|
19
|
+
Warning: failed to parse ${r}: ${s}
|
|
20
|
+
`),null}}parseContent(e,r){return this.pool?this.pool.run({filePath:e,content:r}):js(e,r)}makeStubNode(e,r,n){return{path:r,type:G(e),category:"other",imports:[],exports:[],tags:[],mtime:n.mtimeMs,size:n.size}}resolveCallEdges(e,r){let n=[];for(let s of r??[])try{let o=this.resolver.resolve(e,s.toSpecifier);o&&!o.isExternal&&n.push({from:s.from,to:s.to,toFile:P.relative(this.rootDir,o.path)})}catch{}return n}buildNode(e,r,n,s,o){let{imports:i,exports:a,tags:c,category:l,description:p,complexity:u,cognitiveComplexity:m,functions:d}=s;return{path:r,type:G(e),category:l,imports:i,exports:a,tags:c,mtime:n.mtimeMs,size:n.size,...p!==void 0?{description:p}:{},...o.length>0?{callEdges:o}:{},...u!==void 0?{complexity:u}:{},...m!==void 0?{cognitiveComplexity:m}:{},...d!==void 0?{functions:d}:{}}}attachGitStats(e,r){let n=this.gitStatsMap?.get(r);n&&(e.commitCount90d=n.commitCount90d,n.lastAuthor!==void 0&&(e.lastAuthor=n.lastAuthor),n.lastCommitAt!==void 0&&(e.lastCommitAt=n.lastCommitAt))}async resolveImports(e,r){let n=[];for(let s of r){let o=this.resolver.resolveAll(e,s.rawSpecifier);if(!(o.length===0||s.type==="side-effect"&&s.rawSpecifier.endsWith(".*")&&o.every(a=>a.isExternal)))for(let a of o){if(!a.isExternal&&a.path===e)continue;let c={...s,toPath:a.isExternal?a.path:P.relative(this.rootDir,a.path),isExternal:a.isExternal};a.isWorkspace&&(c.isWorkspace=!0,c.workspacePackage=a.workspacePackage),a.isExternal?this.attachLockfileVersion(c):this.enqueue(a.path),n.push(c)}}return n}attachLockfileVersion(e){if(!this.lockFile)return;let r=this.lockFile.jvmDependencies;if(r&&Hs.has(G(e.fromPath))){let o=e.rawSpecifier.replace(/\.\*$/,""),i="";for(let a of Object.keys(r))(o===a||o.startsWith(`${a}.`))&&a.length>i.length&&(i=a);i&&(e.version=r[i]?.version);return}let n=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],s=n?this.lockFile.dependencies[n]:void 0;s&&(e.version=s.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};import{readFile as mo}from"fs/promises";import Ke from"path";import kp from"piscina";var Xl=new Set(["css","scss","less","stylus"]);function to(t){return Xl.has(t)?"style":"code"}import ro from"path";var Zl=new Set(["generated","__generated__","__generated","gen","__snapshots__"]),ep=[".pb.go",".pb.ts",".pb.js","_pb2.py","_pb2.pyi","_pb.dart",".g.dart",".generated.ts",".generated.tsx",".generated.js",".generated.jsx","_generated.go",".gen.go",".gen.ts",".snap"],tp=["@generated","do not edit","code generated by","autogenerated","auto-generated","this file was automatically generated","this is a generated file","jest snapshot v1"],rp=500;function np(t,e){let r=t.split(/[\\/]/),n=/^\*\*\/(.+?)\/\*\*$/.exec(e);return n?r.includes(n[1]):e.startsWith("*.")?ro.basename(t).endsWith(e.slice(1)):r.includes(e)}function wt(t,e=[]){if(t.split(/[\\/]/).some(s=>Zl.has(s)))return!0;let n=ro.basename(t);return ep.some(s=>n.endsWith(s))?!0:e.some(s=>np(t,s))}function He(t){let e=t.slice(0,rp).toLowerCase();return tp.some(r=>e.includes(r))}function sp(t){return t.trim().replace(/\s+/g," ")}function op(t){try{return t.fileType==="scss"?xt(t.source,t.file).root:t.fileType==="less"?yt(t.source,t.file).root:t.fileType==="css"?ht(t.source,t.file).root:void 0}catch{return}}function ip(t){let e=op(t);if(!e)return[];let r=[];return e.walkRules(n=>{let s=n.nodes?.filter(p=>p.type==="decl")??[];if(s.length===0)return;let o=s[0],i=s[s.length-1],a=n.source?.start?.line??o?.source?.start?.line,c=i?.source?.end?.line??i?.source?.start?.line??a;if(a===void 0||c===void 0)return;let l=s.map(p=>`${p.prop.trim().toLowerCase()}:${sp(p.value)}`).join(";");r.push({file:t.file,startLine:a,endLine:c,lines:c-a+1,signature:l,declCount:s.length})}),r}function no(t,e,r=2){let n=new Map;for(let o of t)for(let i of ip(o)){if(i.declCount<r||i.lines<e)continue;let a=n.get(i.signature);a?a.push(i):n.set(i.signature,[i])}let s=[];for(let o of n.values())for(let i=0;i<o.length;i++)for(let a=i+1;a<o.length;a++){let c=o[i],l=o[a];if(c.file===l.file&&c.startLine===l.startLine&&c.endLine===l.endLine)continue;let p={file:c.file,startLine:c.startLine,endLine:c.endLine},u={file:l.file,startLine:l.startLine,endLine:l.endLine};s.push({occurrences:[p,u],lines:Math.min(c.lines,l.lines),tokens:c.declCount,family:"style"})}return s.sort((o,i)=>i.lines-o.lines)}function so(t){let e=t.length,r=[],n=[{lcpLength:0,low:0}];for(let s=1;s<e;s++){let o=s-1;for(;t[s]<n[n.length-1].lcpLength;){let i=n.pop();r.push({lcpLength:i.lcpLength,low:i.low,high:s-1}),o=i.low}t[s]>n[n.length-1].lcpLength&&n.push({lcpLength:t[s],low:o})}for(;n.length>1;){let s=n.pop();r.push({lcpLength:s.lcpLength,low:s.low,high:e-1})}return r}var ap=new Set(["{","}",":",",","[","]"]);function oo(t,e,r){let n=0;for(let s=e;s<e+r;s++)ap.has(t[s].text)&&n++;return n/r}function io(t){let e=t.length;if(e===0)return[];let r=Array.from({length:e},(o,i)=>i),n=new Array(e);{let o=[...new Set(t)].sort(),i=new Map(o.map((a,c)=>[a,c]));for(let a=0;a<e;a++)n[a]=i.get(t[a])}let s=new Array(e).fill(0);for(let o=1;o<e;o*=2){let i=a=>a+o<e?n[a+o]:-1;r.sort((a,c)=>{let l=n[a]-n[c];return l!==0?l:i(a)-i(c)}),s[r[0]]=0;for(let a=1;a<e;a++){let c=r[a-1],l=r[a],p=n[c]===n[l],u=i(c)===i(l);s[l]=s[c]+(p&&u?0:1)}if([n,s]=[s,n],n[r[e-1]]===e-1)break}return r}function ao(t,e){let r=t.length,n=new Array(r).fill(0);if(r===0)return n;let s=new Array(r);for(let i=0;i<r;i++)s[e[i]]=i;let o=0;for(let i=0;i<r;i++){let a=s[i];if(a>0){let c=e[a-1];for(;i+o<r&&c+o<r&&t[i+o]===t[c+o];)o++;n[a]=o,o>0&&o--}else o=0}return n}function co(t,e,r,n=.5){let s=[],o=[],i=new Map;for(let{file:u,tokens:m}of t)if(m.length!==0){i.set(u,m);for(let d=0;d<m.length;d++)s.push(m[d].text),o.push({file:u,localIndex:d});s.push(` ${u}`),o.push({file:u,localIndex:-1})}if(s.length===0)return[];let a=io(s),c=ao(s,a),l=so(c),p=[];for(let u of l){let m=cp(u,a,o,i,e,r,n);m&&p.push(m)}return p.sort((u,m)=>m.lines-u.lines)}function cp(t,e,r,n,s,o,i){if(t.lcpLength<s)return;let a=[];for(let d=t.low;d<=t.high;d++){let y=r[e[d]];y.localIndex!==-1&&a.push(y)}if(a.length<2||!lp(a,n))return;let c=pp(a,t.lcpLength);if(c.length<2)return;let l=c[0],p=n.get(l.file);if(oo(p,l.localIndex,t.lcpLength)>i)return;let u=c.map(({file:d,localIndex:y})=>{let v=n.get(d);return{file:d,startLine:v[y].line,endLine:v[y+t.lcpLength-1].line}}),m=Math.min(...u.map(d=>d.endLine-d.startLine+1));if(!(m<o))return{occurrences:u,lines:m,tokens:t.lcpLength}}function lp(t,e){let r=null;for(let{file:n,localIndex:s}of t){if(s===0)return!0;let i=e.get(n)[s-1].text;if(r===null)r=i;else if(r!==i)return!0}return!1}function pp(t,e){let r=new Map;for(let{file:s,localIndex:o}of t){let i=r.get(s);i?i.push(o):r.set(s,[o])}let n=[];for(let[s,o]of r){o.sort((a,c)=>a-c);let i=Number.NEGATIVE_INFINITY;for(let a of o)a>=i&&(n.push({file:s,localIndex:a}),i=a+e)}return n}var up={typescript:{line:["//"],block:[["/*","*/"]]},javascript:{line:["//"],block:[["/*","*/"]]},go:{line:["//"],block:[["/*","*/"]]},java:{line:["//"],block:[["/*","*/"]]},kotlin:{line:["//"],block:[["/*","*/"]]},scala:{line:["//"],block:[["/*","*/"]]},groovy:{line:["//"],block:[["/*","*/"]]},css:{block:[["/*","*/"]]},scss:{line:["//"],block:[["/*","*/"]]},less:{line:["//"],block:[["/*","*/"]]},stylus:{line:["//"],block:[["/*","*/"]]},python:{line:["#"]},gherkin:{line:["#"]},coffeescript:{line:["#"],block:[["###","###"]]},livescript:{line:["#"],block:[["###","###"]]},lua:{line:["--"],block:[["--[[","]]"]]},markdown:{block:[["<!--","-->"]]}};function lo(t,e,r){let n=t.slice(e,r).replace(/[^\n]/g," ");return t.slice(0,e)+n+t.slice(r)}function mp(t,e){if(!e)return t;let r=t;for(let[n,s]of e.block??[]){let o=0;for(;;){let i=r.indexOf(n,o);if(i===-1)break;let a=r.indexOf(s,i+n.length),c=a===-1?r.length:a+s.length;r=lo(r,i,c),o=c}}for(let n of e.line??[]){let s=0;for(;;){let o=r.indexOf(n,s);if(o===-1)break;let i=r.indexOf(`
|
|
21
|
+
`,o),a=i===-1?r.length:i;r=lo(r,o,a),s=a}}return r}var fp={typescript:[/^\s*import[\s{("*]/,/^\s*export\s.*\sfrom\s/],javascript:[/^\s*import[\s{("*]/,/^\s*export\s.*\sfrom\s/],python:[/^\s*import\s+\S/,/^\s*from\s+\S+\s+import[\s(]/],go:[/^\s*import\s+["(]/],java:[/^\s*import\s+/],kotlin:[/^\s*import\s+/],scala:[/^\s*import\s+/],groovy:[/^\s*import\s+/]};function gp(t,e){let r=fp[e];if(!r)return t;let n=t.split(`
|
|
22
|
+
`),s=e==="go",o=!1,i=!1;for(let a=0;a<n.length;a++){let c=n[a],l=()=>{n[a]=c.replace(/[^\r]/g," ")};if(o){l(),c.includes(")")&&(o=!1);continue}if(i){l(),(/}\s*from\s/.test(c)||c.includes("}"))&&(i=!1);continue}r.some(p=>p.test(c))&&(l(),s&&/^\s*import\s+\(/.test(c)&&!c.includes(")")?o=!0:(e==="typescript"||e==="javascript")&&/^\s*import\b/.test(c)&&c.includes("{")&&!c.includes("}")&&(i=!0))}return n.join(`
|
|
23
|
+
`)}var dp=["===","!==","...","=>","==","!=","<=",">=","&&","||","::","->","..","+=","-=","*=","/="],Wr=new RegExp(`${dp.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")}|[A-Za-z_$][A-Za-z0-9_$]*|\\d+(?:\\.\\d+)?|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|\\S`,"g"),hp=/^[A-Za-z_$][A-Za-z0-9_$]*$/,po=/^\d+(?:\.\d+)?$/,yp=/^(".*"|'.*'|`.*`)$/s,xp=new Set(["if","else","elif","for","while","do","switch","case","default","break","continue","return","function","def","class","struct","interface","const","let","var","local","import","export","from","package","try","catch","except","finally","throw","raise","new","this","self","end","then","yield","async","await","nil","null","None","true","false","True","False","and","or","not","in","of","is"]);function uo(t,e,r=!0){let n=gp(mp(t,up[e]),e),s=[],o=1,i=0;Wr.lastIndex=0;let a=Wr.exec(n);for(;a!==null;){for(let p=i;p<a.index;p++)n[p]===`
|
|
24
|
+
`&&o++;i=a.index;let c=a[0],l=c;hp.test(c)&&!xp.has(c)?l="ID":r&&(po.test(c)||yp.test(c))&&(l=po.test(c)?"NUM":"STR"),s.push({text:l,line:o});for(let p=i;p<a.index+c.length;p++)n[p]===`
|
|
25
|
+
`&&o++;i=a.index+c.length,a=Wr.exec(n)}return s}import Ue from"fs";import bp from"path";function Sp(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.mtime=="number"&&typeof e.size=="number"&&typeof e.ignoreLiterals=="boolean"&&typeof e.generated=="boolean"&&Array.isArray(e.tokens)}function Ce(t){try{if(!Ue.existsSync(t))return new Map;let e=Ue.readFileSync(t,"utf-8"),r=JSON.parse(e);if(!Array.isArray(r))return new Map;let n=r.filter(s=>Array.isArray(s)&&s.length===2&&typeof s[0]=="string"&&Sp(s[1]));return new Map(n)}catch{return new Map}}function we(t,e){let r=bp.dirname(e);Ue.existsSync(r)||Ue.mkdirSync(r,{recursive:!0}),Ue.writeFileSync(e,JSON.stringify([...t.entries()]))}var vp=20,Cp=new Set(["css","scss","less"]);function wp(t){return Me.includes(Ke.basename(t))}function Ep(t,e){if(e.length===0)return!1;let r=new Set(e);return t.split(Ke.sep).some(n=>r.has(n))}function fo(t,e){let r=[];return new Set(t.occurrences.map(n=>n.file)).size===1&&r.push("same-file"),t.occurrences.some(n=>e.has(n.file))&&r.push("generated"),r.length>0?{...t,signals:r}:t}async function Ee(t,e,r={}){let{minLines:n=6,windowSize:s=15,ignoreLiterals:o=!0,maxPunctuationRatio:i=.5,limit:a=50,ignoreDirs:c=N,includeGenerated:l=!1,ignoreGlobs:p=[],parallelTokenizing:u=!0,tokenCache:m}=r,d=[...t.nodes.values()].filter(x=>!wp(x.path)&&!Ep(x.path,c)),y=new Set,v=Tp(u,d.length);try{let x=[],C=new Map;if(await Promise.all(d.map(async S=>{let E=wt(S.path,p);if(E&&!l)return;if(Cp.has(S.type)){let B;try{B=await mo(Ke.join(e,S.path),"utf8")}catch{return}let An=E||He(B);if(An&&!l)return;An&&y.add(S.path),x.push({file:S.path,source:B,fileType:S.type});return}let $=m?.get(S.path),Gi=$&&$.mtime===S.mtime&&$.size===S.size&&$.ignoreLiterals===o,tt,me;if(Gi)tt=$.tokens,me=$.generated;else{let B;try{B=await mo(Ke.join(e,S.path),"utf8")}catch{return}if(me=E||He(B),me&&!l)return;tt=v?await v.run({source:B,fileType:S.type,ignoreLiterals:o}):uo(B,S.type,o),m?.set(S.path,{mtime:S.mtime,size:S.size,ignoreLiterals:o,generated:me,tokens:tt})}if(me&&!l)return;me&&y.add(S.path);let Tn=to(S.type),Fn={file:S.path,tokens:tt},Pn=C.get(Tn);Pn?Pn.push(Fn):C.set(Tn,[Fn])})),m){let S=new Set(d.map(E=>E.path));for(let E of m.keys())S.has(E)||m.delete(E)}let A=no(x,n).map(S=>fo(S,y));for(let[S,E]of C)for(let $ of co(E,s,n,i))A.push(fo({...$,family:S},y));return{groups:A.sort((S,E)=>E.lines-S.lines).slice(0,a)}}finally{v&&await v.destroy()}}function Tp(t,e){if(t===!1)return null;let r=typeof t=="object"?t:{},n=r.minFiles??vp;if(e<n)return null;r.maxThreads!==void 0&&r.maxThreads<1&&process.stderr.write(`
|
|
8
26
|
Warning: parallelTokenizing.maxThreads (${r.maxThreads}) must be at least 1; using 1.
|
|
9
|
-
`);try{return new
|
|
27
|
+
`);try{return new kp({filename:Ke.join(f,"duplication-worker.js"),...r.maxThreads!==void 0?{maxThreads:Math.max(1,r.maxThreads)}:{}})}catch(s){return process.stderr.write(`
|
|
10
28
|
Warning: failed to start duplicate-detection worker pool, falling back to synchronous tokenizing: ${s}
|
|
11
|
-
`),null}}import We from"path";function so(t){let e=new Map;for(let[r,n]of t){let s=n.imports.filter(i=>i.toPath&&!i.isExternal).length;s>0&&e.set(r,s)}return e}function io(t,e,r){let n=new Map;for(let[s,i]of e){if(i<r)continue;let o=t.get(s);if(!o||o.category==="test"||o.category==="barrel")continue;let a=We.extname(s),c=We.basename(s,a),l=c==="index"?We.basename(We.dirname(s)):c;n.set(s,{path:s,outDegree:i,tag:`feature:${l}`})}return n}function W(t,e){let r=e?.minOutDegree??5;return io(t,so(t),r)}var oo=(t,e)=>t.outDegree-e.outDegree;function ao(t,e){let r=new Map;for(let n of e.values()){let s=new Set;t.traverse(n.path,i=>(i.path!==n.path&&s.add(i.path),!0),{direction:"outgoing"}),r.set(n.path,s)}return r}function co(t,e,r,n){let s=new Map;for(let[i]of t){if(e.has(i))continue;let o=null;for(let a of e.values())r.get(a.path)?.has(i)&&(!o||n(a,o)<0)&&(o=a);o&&s.set(i,o.path)}return s}function lo(t,e){let r=new Map;for(let n of t.values()){let s=n.tag.replace("feature:",""),i=[];for(let[o,a]of e)a===n.path&&i.push(o);r.set(s,{hub:n.path,outDegree:n.outDegree,files:i})}return r}function po(t,e,r){let n=[];for(let s of t.keys())!e.has(s)&&!r.has(s)&&n.push(s);return n}function le(t,e){let r=e?.detectFn??W,n=e?.hubComparator??oo,s=r(t.nodes,e),i=ao(t,s),o=co(t.nodes,s,i,n);return{features:lo(s,o),unassigned:po(t.nodes,s,o)}}var rn=new Set(["typescript","javascript","python","go","scss","less","lua","coffeescript"]),nn=new Set(["typescript","javascript","python"]),Be=new Set(["typescript","javascript","go","python"]);function Dt(t){let e=new Map;for(let r of t.nodes.values())e.set(r.type,(e.get(r.type)??0)+1);return[...e.entries()].map(([r,n])=>({type:r,fileCount:n,exportsTracked:rn.has(r),importSymbolsTracked:nn.has(r),callEdgesTracked:Be.has(r)})).sort((r,n)=>n.fileCount-r.fileCount)}var pe=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let r=new Set(this.nodes.keys());return e.filter(n=>!r.has(n))}findHighExportUsage(e){let r=[];for(let n of this.nodes.values()){if(n.maxExportUsage===void 0||n.maxExportUsage<e)continue;let s=n.imports.reduce((i,o)=>(o.exportUsageRatio??0)>(i?.exportUsageRatio??0)?o:i,null);r.push({path:n.path,maxExportUsage:n.maxExportUsage,tightestDep:s?.toPath??""})}return r.sort((n,s)=>s.maxExportUsage-n.maxExportUsage)}findCycles(){let e=[],r=new Set,n=new Set,s=[],i=o=>{r.add(o),n.add(o),s.push(o);let a=this.nodes.get(o);if(a){for(let c of a.imports)if(!(!c.toPath||c.isExternal))if(n.has(c.toPath)){let l=s.indexOf(c.toPath);e.push([...s.slice(l),c.toPath])}else r.has(c.toPath)||i(c.toPath)}n.delete(o),s.pop()};for(let o of this.nodes.keys())r.has(o)||i(o);return e}};var I=class t{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let r=new Map;for(let n of e.nodes)r.set(n.path,n);return new t(r)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let r of this.nodes.values())for(let n of r.imports)if(n.toPath){let s=e.get(n.toPath)||[];s.push(r.path),e.set(n.toPath,s)}return this._incomingEdgesCache=e,e}dfs(e,r,n,s){let i=new Set,o=n.maxDepth??1/0,a=(c,l,p)=>{if(l>o||i.has(c))return;let u=this.nodes.get(c);if(u&&(i.add(c),r(u,l,p)!==!1))for(let d of s(c))a(d,l+1,c)};a(e,0,null)}traverse(e,r,n={}){let s=n.direction??"outgoing",i=s==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,r,n,o=>s==="outgoing"?this.nodes.get(o)?.imports.map(a=>a.toPath).filter(Boolean)??[]:i?.get(o)??[])}getCallIncomingCache(){if(this._callIncomingCache)return this._callIncomingCache;let e=new Map;for(let r of this.nodes.values())for(let n of r.callEdges??[]){let s=e.get(n.toFile)??[];s.push(r.path),e.set(n.toFile,s)}return this._callIncomingCache=e,e}traverseCalls(e,r,n={}){let s=n.direction??"outgoing",i=s==="incoming"?this.getCallIncomingCache():null;this.dfs(e,r,n,o=>s==="outgoing"?this.nodes.get(o)?.callEdges?.map(a=>a.toFile)??[]:i?.get(o)??[])}getCallers(e){let r=[];return this.traverseCalls(e,n=>(n.path!==e&&r.push(n.path),!0),{direction:"incoming",maxDepth:1}),r}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let r=this.nodes.get(e);return r?r.imports.map(n=>this.nodes.get(n.toPath)).filter(n=>n!==void 0):[]}findUnusedFiles(e){return new pe(this.nodes).findUnusedFiles(e)}findCycles(){return new pe(this.nodes).findCycles()}};var B=class{affectedSymbols=new Map;constructor(e,r){this.affectedSymbols.set(e,new Set(["default",...r]))}updateAffectedSymbols(e,r){let n=this.affectedSymbols.get(r)||new Set,s=e.imports.find(c=>c.toPath===r);if(!s)return!1;let i=s.symbols||["*"],o=new Set;for(let c of i)(c==="*"||n.has("*")||n.has(c))&&o.add("*");if(o.size===0)return!1;let a=this.affectedSymbols.get(e.path)||new Set;for(let c of o)a.add(c);return this.affectedSymbols.set(e.path,a),!0}};function ue(t,e){let r=t.nodes.get(e);if(r)return{category:r.category,exports:r.exports.map(n=>n.name)}}function Mt(t,e,r=1){let n=[];return t.traverse(e,(s,i,o)=>{if(s.path===e)return!0;let a=o?t.nodes.get(o)?.imports.find(c=>c.toPath===s.path):void 0;return n.push({path:s.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"outgoing",maxDepth:r}),n}function fe(t,e){let r=[];return t.traverse(e,n=>{if(n.path===e)return!0;let s=n.imports.find(i=>i.toPath===e);return r.push({path:n.path,...s?.symbols?{symbols:s.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),r}function Rt(t,e,r={}){let{testsOnly:n=!1,changedSymbols:s}=r,i=s?new B(e,s):null,o=[];return t.traverse(e,(a,c,l)=>{if(a.path===e)return!0;if(i&&l&&!i.updateAffectedSymbols(a,l))return!1;let p=a.category==="test"||a.tags.some(u=>u.name==="test");return(!n||p)&&o.push(a.path),!0},{direction:"incoming"}),o}function Lt(t,e,r={}){let{depth:n=1,withEdgeDetail:s=!1}=r,i=[];return t.traverseCalls(e,o=>{if(o.path===e)return!0;let a={file:o.path};return s&&(a.edges=(o.callEdges??[]).filter(c=>c.toFile===e).map(c=>({from:c.from,to:c.to}))),i.push(a),!0},{direction:"incoming",maxDepth:n}),i}function Gt(t,e={}){let{metric:r="cognitiveComplexity",threshold:n=10,limit:s=20}=e;return[...t.nodes.values()].flatMap(i=>(i.functions??[]).filter(o=>o[r]>=n).map(o=>({file:i.path,name:o.name,line:o.line,complexity:o.complexity,cognitiveComplexity:o.cognitiveComplexity}))).sort((i,o)=>o[r]-i[r]).slice(0,s)}function _t(t){return{nodes:t.nodes.map(r=>({path:r.path,type:r.type,category:r.category,exports:r.exports.map(n=>n.name),tags:r.tags.filter(n=>n.kind==="comment-marker"||n.kind==="import").map(n=>n.name),importsFiles:r.imports.filter(n=>!n.isExternal&&n.toPath).map(n=>n.toPath),...r.description!==void 0&&{description:r.description},...r.testedBy!==void 0&&{testedBy:r.testedBy},...r.coveragePct!==void 0&&{coveragePct:r.coveragePct},...r.avgExportUsage!==void 0&&{avgExportUsage:r.avgExportUsage},...r.maxExportUsage!==void 0&&{maxExportUsage:r.maxExportUsage}})),cycles:t.cycles}}function Ot(t){let e=t.getPackageDependencies(),r=Array.from(t.packages.values()).map(({graph:n,pkg:s})=>({name:s.name,relativeRoot:s.relativeRoot,nodeCount:n.nodes.size,dependsOn:e.get(s.name)??[]}));return{monorepoType:t.type,packageCount:r.length,packages:r}}function $e(t){return[...t.nodes.values()].some(e=>e.coveragePct!==void 0)}function sn(t){return[...t.nodes.values()].some(e=>e.commitCount90d!==void 0)}function jt(t,e={}){let{metric:r="cognitiveComplexity",minComplexity:n=10,maxCoveragePct:s=50,minChurn:i=0,limit:o=20}=e,a=sn(t),c=[...t.nodes.values()].filter(l=>l.coveragePct!==void 0&&l.coveragePct<=s&&(!a||(l.commitCount90d??0)>=i)).flatMap(l=>(l.functions??[]).filter(p=>p[r]>=n).map(p=>({file:l.path,name:p.name,line:p.line,complexity:p.complexity,cognitiveComplexity:p.cognitiveComplexity,coveragePct:l.coveragePct,...l.commitCount90d!==void 0&&{commitCount90d:l.commitCount90d}}))).sort((l,p)=>p[r]-l[r]).slice(0,o);return{hotspots:c,count:c.length,churnDataAvailable:a}}function on(t){if(t.category==="test")return"test";if(t.category==="config")return"config";if(t.category==="type-only")return"types";let e=t.path;return S(e,"component")||S(e,"components")?"component":S(e,"controller")||S(e,"controllers")?"controller":S(e,"middleware")?"middleware":S(e,"router")||S(e,"routes")||S(e,"route")?"router":S(e,"store")||S(e,"stores")?"store":S(e,"service")||S(e,"services")?"service":S(e,"handler")||S(e,"handlers")?"handler":S(e,"adapter")||S(e,"adapters")?"adapter":S(e,"plugin")||S(e,"plugins")?"plugin":S(e,"api")?"api":S(e,"cli")||S(e,"commands")||me(e)==="cli"?"cli":S(e,"util")||S(e,"utils")||S(e,"helper")||S(e,"helpers")?"util":S(e,"model")||S(e,"models")||me(e)==="model"?"model":S(e,"parser")||S(e,"parsers")||me(e)==="parser"?"parser":me(e)==="builder"?"builder":me(e)==="resolver"?"resolver":"other"}function S(t,e){return t.includes(`/${e}/`)||t.includes(`/${e}.`)}function me(t){let e=t.slice(t.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function zt(t,e){let r=le(t,e),n=new Map;for(let[i,o]of r.features){for(let a of o.files)n.set(a,i);n.set(o.hub,i)}let s=new Map;for(let i of t.nodes.values()){let o=n.get(i.path);s.set(i.path,{path:i.path,role:on(i),...i.description?{description:i.description}:{},exports:i.exports.map(a=>a.name),...o?{featureHub:o}:{}})}return s}function Wt(t,e){let r=[];for(let n of t.nodes.values())if(n.exports.some(s=>s.name===e))if(Be.has(n.type)){let s=[];for(let i of t.nodes.values())for(let o of i.callEdges??[])o.to===e&&s.push({file:i.path,callerFunction:o.from});r.push({path:n.path,category:n.category,precision:"call",callers:s})}else{let s=fe(t,n.path).map(i=>({file:i.path,...i.symbols?{symbols:i.symbols}:{}}));r.push({path:n.path,category:n.category,precision:"file-level",importers:s})}return r}function uo(t){return t?t.startsWith("interface ")?"interface":t.startsWith("class ")?"class":t.startsWith("enum ")?"enum":"type":"type"}function fo(t,e){if(e==="type-only")return!0;let r=t.signature??"";return r.startsWith("interface ")||r.startsWith("class ")||r.startsWith("enum ")}function Bt(t){let e=new Map;for(let n of t.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript"))for(let s of n.exports){if(!fo(s,n.category))continue;let i=`${n.path}::${s.name}`;e.set(i,{name:s.name,file:n.path,kind:uo(s.signature),...s.doc?{doc:s.doc}:{}})}let r=[];for(let n of t.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript")){for(let s of n.imports)if(!(!s.toPath||s.isExternal||!s.symbols?.length))for(let i of s.symbols)e.has(`${s.toPath}::${i}`)&&r.push({fromFile:n.path,toType:i,toFile:s.toPath})}return{types:e,edges:r}}function $t(t,e){let r=null;for(let i of t.types.values())if(i.name===e){r=i;break}if(!r)return{type:null,usedByFiles:[],uses:[]};let n=new Set,s=new Map;for(let i of t.edges)if(i.toType===e&&i.toFile===r.file&&n.add(i.fromFile),i.fromFile===r.file){let o=t.types.get(`${i.toFile}::${i.toType}`);o&&s.set(`${o.file}::${o.name}`,o)}return{type:r,usedByFiles:Array.from(n),uses:Array.from(s.values())}}import Fo from"path";import Ht from"fs";import pn from"path";import ge from"fs";import A from"path";import an from"fs";import Gu from"path";function cn(t){try{return an.statSync(t,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function Ue(t){try{return an.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}function Ut(t,e){let r=A.join(e,"package.json");if(!ge.existsSync(r))return null;let n={};try{n=JSON.parse(ge.readFileSync(r,"utf-8"))}catch{return null}let s=n.name;return s?{name:s,root:e,relativeRoot:A.relative(t,e),entryPoints:mo(e,n)}:null}function mo(t,e){let r=[];if(e.exports){let s=e.exports;if(typeof s=="string")r.push(A.join(t,s));else if(typeof s=="object"&&s!==null){let i=s["."];if(typeof i=="string")r.push(A.join(t,i));else if(typeof i=="object"&&i!==null){let o=i.import??i.require??i.default;typeof o=="string"&&r.push(A.join(t,o))}}}e.main&&r.push(A.join(t,e.main));for(let s of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])r.push(A.join(t,s));let n=r.filter(Ue);return n.length>0?n.slice(0,1):r.slice(0,1)}function Y(t,e){let r=[],n=new Set;for(let s of e){let i=s.replace(/\/$/,"").replace(/^\.\//,"");go(t,i,n,r)}return r}function go(t,e,r,n){if(!e.includes("*")){ho(t,e,r,n);return}let s=e.split("/");s.includes("**")?yo(t,s,r,n):xo(t,s,r,n)}function ho(t,e,r,n){let s=A.join(t,e);if(r.has(s)||!cn(s))return;r.add(s);let i=Ut(t,s);i&&n.push(i)}function yo(t,e,r,n){let s=A.join(t,e[0]==="**"?"":e[0]??"");ln(t,s,r,n)}function xo(t,e,r,n){let s=e.findIndex(a=>a.includes("*")),i=A.join(t,...e.slice(0,s)),o;try{o=ge.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of o){if(!a.isDirectory())continue;let c=A.join(i,a.name);if(r.has(c))continue;r.add(c);let l=Ut(t,c);l&&n.push(l)}}function ln(t,e,r,n){let s;try{s=ge.readdirSync(e,{withFileTypes:!0})}catch{return}for(let i of s){if(!i.isDirectory()||i.name==="node_modules"||i.name.startsWith("."))continue;let o=A.join(e,i.name);if(ge.existsSync(A.join(o,"package.json"))&&!r.has(o)){r.add(o);let a=Ut(t,o);a&&n.push(a)}else ln(t,o,r,n)}}var un={type:"npm",detect(t){let e=pn.join(t,"package.json");if(!Ht.existsSync(e))return null;let r;try{r=JSON.parse(Ht.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r||Ht.existsSync(pn.join(t,"yarn.lock")))return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:Y(t,n)}};import X from"fs";import T from"path";var fn={type:"nx",detect(t){return X.existsSync(T.join(t,"nx.json"))?mn(t,t,new Set,0).map(r=>bo(t,r,T.join(r,"project.json"))).filter(r=>r!==null):null}};function mn(t,e,r,n){if(n>4)return[];let s;try{s=X.readdirSync(e,{withFileTypes:!0})}catch{return[]}let i=[];for(let o of s){if(!o.isDirectory())continue;let a=o.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let c=T.join(e,a);X.existsSync(T.join(c,"project.json"))&&!r.has(c)?(r.add(c),i.push(c)):i.push(...mn(t,c,r,n+1))}return i}function bo(t,e,r){let n={};try{n=JSON.parse(X.readFileSync(r,"utf-8"))}catch{return null}let s=n.name,i,o,a=T.join(e,"package.json");if(X.existsSync(a))try{let c=JSON.parse(X.readFileSync(a,"utf-8"));s=c.name??s,i=c.main,o=c.exports}catch{}return s?{name:s,root:e,relativeRoot:T.relative(t,e),entryPoints:So(e,n,i,o)}:null}function So(t,e,r,n){let s=[],i=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(i){let a=T.resolve(t,"../..");s.push(T.resolve(a,i)),s.push(T.resolve(t,i))}if(n){let a=n;if(typeof a=="string")s.push(T.join(t,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&s.push(T.join(t,c))}}if(r&&s.push(T.join(t,r)),e.sourceRoot){let a=T.resolve(t,"../.."),c=T.resolve(a,e.sourceRoot);s.push(T.join(c,"index.ts"),T.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])s.push(T.join(t,a));let o=s.filter(Ue);return o.length>0?o.slice(0,1):s.slice(0,1)}import gn from"fs";import ko from"path";import{load as Co}from"js-yaml";var dn={type:"pnpm",detect(t){let e=ko.join(t,"pnpm-workspace.yaml");if(!gn.existsSync(e))return null;let r=[];try{r=Co(gn.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return Y(t,r)}};import vo from"fs";import wo from"path";var hn={type:"turborepo",detect(t){return vo.existsSync(wo.join(t,"turbo.json"))?[]:null}};import Kt from"fs";import yn from"path";var xn={type:"yarn",detect(t){if(!Kt.existsSync(yn.join(t,"yarn.lock")))return null;let e=yn.join(t,"package.json");if(!Kt.existsSync(e))return null;let r;try{r=JSON.parse(Kt.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r)return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:Y(t,n)}};var bn=[];function G(t){bn.push(t)}function Sn(){return bn}G(hn);G(fn);G(dn);G(xn);G(un);function de(t,e=Sn()){let r=Fo.resolve(t),n=new Map,s=[];for(let o of e){let a=o.detect(r);if(a!==null){s.push(o.type);for(let c of a)n.has(c.name)||n.set(c.name,c)}}if(s.length===0)return{root:r,type:"none",types:[],packages:[],packageMap:new Map};let i=Array.from(n.values());return{root:r,type:s[0],types:s,packages:i,packageMap:new Map(i.map(o=>[o.name,o]))}}var he=class t{constructor(e,r){this.monorepoRoot=e;this.type=r}monorepoRoot;type;packages=new Map;addPackage(e,r){this.packages.set(e.name,{graph:r,pkg:e})}getPackageForFile(e){for(let{pkg:r}of this.packages.values())if(e===r.relativeRoot||e.startsWith(`${r.relativeRoot}/`))return r}getPackageDependencies(){let e=new Map;for(let{graph:r,pkg:n}of this.packages.values()){let s=new Set;for(let i of r.nodes.values())for(let o of i.imports)o.isWorkspace&&o.workspacePackage&&s.add(o.workspacePackage);e.set(n.name,[...s])}return e}getAffectedAcrossPackages(e){let r=this.getPackageForFile(e);if(!r)return[];let n=this.packages.get(r.name);if(!n)return[];let s=[];n.graph.traverse(e,i=>(i.path!==e&&s.push({file:i.path,package:r.name}),!0),{direction:"incoming"});for(let{graph:i,pkg:o}of this.packages.values())if(o.name!==r.name)for(let a of i.nodes.values())a.imports.some(l=>l.isWorkspace&&l.workspacePackage===r.name)&&s.push({file:a.path,package:o.name});return s}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:r})=>({pkg:{name:r.name,relativeRoot:r.relativeRoot,entryPoints:r.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let r=new t(e.monorepoRoot,e.type);for(let{pkg:n,nodes:s}of e.packages){let i=new Map(s.map(a=>[a.path,a])),o=new I(i);r.packages.set(n.name,{graph:o,pkg:{...n,root:""}})}return r}};var kn=new Map;function Z(t,e){kn.set(t,e)}function Cn(t){return kn.get(t)}function vn(t,e){return e.startsWith("!")?t!==e.slice(1):t===e}function To(t,e){return e.startsWith("!")?!t.includes(e.slice(1)):t.includes(e)}var Eo=(t,e)=>!e.category||vn(t.category,e.category),Ao=(t,e)=>!e.type||vn(t.type,e.type),Po=(t,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?t.lastAuthor!==e.lastAuthor.slice(1):t.lastAuthor!==void 0&&t.lastAuthor===e.lastAuthor:!0,No=(t,e)=>!e.path||To(t.path,e.path),Io=(t,e)=>e.isExternal===void 0?!0:t.imports.some(n=>n.isExternal)===e.isExternal,Do=(t,e)=>{if(!e.tags||e.tags.length===0)return!0;let r=e.tags.filter(s=>!s.startsWith("!")),n=e.tags.filter(s=>s.startsWith("!")).map(s=>s.slice(1));return!(r.length>0&&!r.some(s=>t.tags.some(i=>i.name===s))||n.some(s=>t.tags.some(i=>i.name===s)))},Mo=(t,e)=>!e.allTags?.length||e.allTags.every(r=>t.tags.some(n=>n.name===r)),Ro=(t,e)=>!e.importsFile||t.imports.some(r=>r.toPath?.includes(e.importsFile)),Lo=(t,e,r)=>e.importedBy===void 0?!0:(r?.get(t.path)??[]).some(s=>s.includes(e.importedBy)),Go=(t,e)=>e.minImports===void 0||t.imports.length>=e.minImports,_o=(t,e)=>e.maxImports===void 0||t.imports.length<=e.maxImports,Oo=(t,e)=>e.minSize===void 0||t.size>=e.minSize,jo=(t,e)=>e.maxSize===void 0||t.size<=e.maxSize,zo=(t,e)=>e.hasDocstring===void 0||!!t.description===e.hasDocstring,Wo=(t,e)=>e.isDocumented===void 0||!!t.documentedBy?.length===e.isDocumented,Bo=(t,e)=>e.isStale===void 0||!!t.staleFor?.length===e.isStale,$o=(t,e)=>e.minCoverage===void 0||(t.coveragePct??101)>=e.minCoverage,Uo=(t,e)=>e.maxCoverage===void 0||(t.coveragePct??0)<=e.maxCoverage,Ho=(t,e)=>e.minExportUsage===void 0||(t.avgExportUsage??-1)>=e.minExportUsage,Ko=(t,e)=>e.maxExportUsage===void 0||(t.avgExportUsage??0)<=e.maxExportUsage,Jo=(t,e)=>e.minComplexity===void 0||(t.complexity??-1/0)>=e.minComplexity,Vo=(t,e)=>e.maxComplexity===void 0||(t.complexity??0)<=e.maxComplexity,Qo=(t,e)=>e.minCognitiveComplexity===void 0||(t.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,qo=(t,e)=>e.maxCognitiveComplexity===void 0||(t.cognitiveComplexity??0)<=e.maxCognitiveComplexity,Yo=(t,e)=>e.minCommits===void 0||(t.commitCount90d??-1/0)>=e.minCommits,Xo=(t,e)=>e.maxCommits===void 0||(t.commitCount90d??0)<=e.maxCommits,Zo=(t,e,r)=>!e.any?.length||e.any.some(n=>ye(t,n,r)),ea=[Eo,Ao,Po,No,Io,Do,Mo,Ro,Lo,Go,_o,Oo,jo,zo,Wo,Bo,$o,Uo,Ho,Ko,Jo,Vo,Qo,qo,Yo,Xo,Zo];function ye(t,e,r){return ea.every(n=>n(t,e,r))}function He(t,e){let r=new Map;if(e.importedBy!==void 0){for(let o of t.nodes)for(let a of o.imports)if(a.toPath){let c=r.get(a.toPath)??[];c.push(o.path),r.set(a.toPath,c)}}let n=t.nodes.filter(o=>ye(o,e,r)),s=new Set(n.map(o=>o.path)),i=n.map(o=>({...o,imports:o.imports.filter(a=>!a.toPath||s.has(a.toPath))}));if(e.sort){let o=e.sortDir==="asc"?-1:1;i.sort((a,c)=>{let l=0;return e.sort==="size"?l=c.size-a.size:e.sort==="imports"?l=c.imports.length-a.imports.length:e.sort==="commitCount90d"?l=(c.commitCount90d??0)-(a.commitCount90d??0):e.sort==="exportUsage"?l=(c.avgExportUsage??0)-(a.avgExportUsage??0):e.sort==="complexity"?l=(c.complexity??0)-(a.complexity??0):e.sort==="cognitiveComplexity"&&(l=(c.cognitiveComplexity??0)-(a.cognitiveComplexity??0)),l*o})}return e.limit!==void 0&&i.splice(e.limit),{nodes:i,cycles:t.cycles?.filter(o=>o.every(a=>s.has(a)))??void 0}}function wn(t,e){let r=e.indexOf(":");if(r===-1)return;let n=e.slice(0,r).trim().toLowerCase(),s=e.slice(r+1).trim();if(!(!n||!s))switch(n){case"category":t.category=s;break;case"type":t.type=s;break;case"tag":case"tags":s.includes("+")?t.allTags=[...t.allTags??[],...s.split("+")]:t.tags=[...t.tags??[],s];break;case"path":t.path=s;break;case"external":t.isExternal=s.toLowerCase()==="true";break;case"importsfile":t.importsFile=s;break;case"importedby":t.importedBy=s;break;case"minimports":t.minImports=parseInt(s,10);break;case"maximports":t.maxImports=parseInt(s,10);break;case"minsize":t.minSize=parseInt(s,10);break;case"maxsize":t.maxSize=parseInt(s,10);break;case"sort":t.sort=s;break;case"sortdir":t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";break;case"limit":t.limit=parseInt(s,10);break;case"hasdocstring":t.hasDocstring=s.toLowerCase()!=="false";break;case"mincoverage":t.minCoverage=parseInt(s,10);break;case"maxcoverage":t.maxCoverage=parseInt(s,10);break;case"minexportusage":t.minExportUsage=parseFloat(s);break;case"maxexportusage":t.maxExportUsage=parseFloat(s);break;case"mincomplexity":t.minComplexity=parseInt(s,10);break;case"maxcomplexity":t.maxComplexity=parseInt(s,10);break;case"mincognitivecomplexity":t.minCognitiveComplexity=parseInt(s,10);break;case"maxcognitivecomplexity":t.maxCognitiveComplexity=parseInt(s,10);break;case"mincommits":t.minCommits=parseInt(s,10);break;case"maxcommits":t.maxCommits=parseInt(s,10);break;case"isdocumented":t.isDocumented=s.toLowerCase()!=="false";break;case"isstale":t.isStale=s.toLowerCase()!=="false";break;case"lastauthor":t.lastAuthor=s;break}}function ta(t){let e=[];for(let r of t.split("|")){let n=r.trim();if(!n)continue;let s={};wn(s,n),Object.keys(s).length>0&&e.push(s)}return e}function Ke(t){let e={},r=t.split(",");for(let n of r){let s=n.trim();if(s.toLowerCase().startsWith("any(")&&s.endsWith(")")){let i=s.slice(4,-1),o=ta(i);o.length>0&&(e.any=[...e.any??[],...o]);continue}wn(e,n)}return e}import Dn from"fs/promises";import Fa from"path";import sr from"path";import tt from"typescript";import sa from"path";import ra from"path";import F from"typescript";var Fn=new Set(["describe","test","it"]);function $(t,e){let r=t[e];if(r===void 0)throw new Error(`Index ${e} out of bounds (length ${t.length})`);return r}function Jt(t){let e=[];for(let r of t.statements){if(!F.isExpressionStatement(r))continue;let n=r.expression;if(!F.isCallExpression(n))continue;let s=n.expression;F.isIdentifier(s)&&Fn.has(s.text)&&e.push(n),F.isPropertyAccessExpression(s)&&F.isIdentifier(s.expression)&&Fn.has(s.expression.text)&&e.push(n)}return e}function Vt(t,e,r){for(let n of t.arguments){if(!F.isObjectLiteralExpression(n))continue;let s=n.properties.find(i=>F.isPropertyAssignment(i)&&F.isIdentifier(i.name)&&i.name.text===e);if(!(!s||!F.isArrayLiteralExpression(s.initializer)))return s.initializer.elements.filter(F.isStringLiteral).map(i=>i.text)}return null}function Qt(t,e,r,n){if(t.arguments.length===0)return null;for(let i=1;i<t.arguments.length;i++){let o=$(t.arguments,i);if(!F.isObjectLiteralExpression(o))continue;let a=o.properties.find(l=>F.isPropertyAssignment(l)&&F.isIdentifier(l.name)&&l.name.text===e);if(a)return{start:a.initializer.getStart(n),end:a.initializer.getEnd(),text:r};let c=o.getEnd()-1;return{start:c,end:c,text:`${o.properties.length>0?", ":""}${e}: ${r}`}}let s=$(t.arguments,t.arguments.length-1);return{start:s.getStart(n),end:s.getStart(n),text:`{ ${e}: ${r} }, `}}function qt(t,e,r){let n=t.arguments;for(let s=1;s<n.length;s++){let i=$(n,s);if(!F.isObjectLiteralExpression(i))continue;let o=i.properties.findIndex(c=>F.isPropertyAssignment(c)&&F.isIdentifier(c.name)&&c.name.text===e);if(o<0)continue;if(i.properties.length===1)return{start:$(n,s-1).getEnd(),end:i.getEnd(),text:""};let a=$(i.properties,o);return o===i.properties.length-1?{start:$(i.properties,o-1).getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(r),end:$(i.properties,o+1).getStart(r),text:""}}return null}function Yt(t,e){let r=[...e].sort((s,i)=>i.start-s.start),n=t;for(let s of r)n=n.slice(0,s.start)+s.text+n.slice(s.end);return n}function Xt(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}var M=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function na(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}function Je(t,e,r,n){let s=F.createSourceFile(ra.basename(t),e,F.ScriptTarget.Latest,!0),i=Jt(s),[o]=i;if(!o)return e;let a=Vt(o,n,s),c=[...r].sort();if(a!==null&&JSON.stringify(na(a).sort())===JSON.stringify(c))return e;let l=Xt(c.map(u=>`@${u}`)),p=i.flatMap(u=>{let d=r.length===0?qt(u,n,s):Qt(u,n,l,s);return d?[d]:[]});return p.length>0?Yt(e,p):e}var Ve=class{name="cypress";canHandle(e){return M.has(sa.extname(e).toLowerCase())}apply(e,r,n){return Je(e,r,n,"tags")}};import ia from"path";var Zt=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,er=/^@([a-zA-Z0-9_-]+)/gm;function oa(t){return`${["# <mokosh-tags>",...t.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
|
|
29
|
+
`),null}}var se=class{affectedSymbols=new Map;constructor(e,r){this.affectedSymbols.set(e,new Set(["default",...r]))}updateAffectedSymbols(e,r){let n=this.affectedSymbols.get(r)||new Set,s=e.imports.find(c=>c.toPath===r);if(!s)return!1;let o=s.symbols||["*"],i=new Set;for(let c of o)(c==="*"||n.has("*")||n.has(c))&&i.add("*");if(i.size===0)return!1;let a=this.affectedSymbols.get(e.path)||new Set;for(let c of i)a.add(c);return this.affectedSymbols.set(e.path,a),!0}};function Je(t,e){let r=t.nodes.get(e);if(r)return{category:r.category,exports:r.exports.map(n=>n.name)}}function zr(t,e,r=1){let n=[];return t.traverse(e,(s,o,i)=>{if(s.path===e)return!0;let a=i?t.nodes.get(i)?.imports.find(c=>c.toPath===s.path):void 0;return n.push({path:s.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"outgoing",maxDepth:r}),n}function qe(t,e){let r=[];return t.traverse(e,n=>{if(n.path===e)return!0;let s=n.imports.find(o=>o.toPath===e);return r.push({path:n.path,...s?.symbols?{symbols:s.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),r}function $r(t,e,r={}){let{testsOnly:n=!1,changedSymbols:s}=r,o=s?new se(e,s):null,i=[];return t.traverse(e,(a,c,l)=>{if(a.path===e)return!0;if(o&&l&&!o.updateAffectedSymbols(a,l))return!1;let p=a.category==="test"||a.tags.some(u=>u.name==="test");return(!n||p)&&i.push(a.path),!0},{direction:"incoming"}),i}function Br(t,e,r={}){let{depth:n=1,withEdgeDetail:s=!1}=r,o=[];return t.traverseCalls(e,i=>{if(i.path===e)return!0;let a={file:i.path};return s&&(a.edges=(i.callEdges??[]).filter(c=>c.toFile===e).map(c=>({from:c.from,to:c.to}))),o.push(a),!0},{direction:"incoming",maxDepth:n}),o}function Te(t,e={}){let{metric:r="cognitiveComplexity",threshold:n=10,limit:s=20}=e;return[...t.nodes.values()].flatMap(o=>(o.functions??[]).filter(i=>i[r]>=n).map(i=>({file:o.path,name:i.name,line:i.line,complexity:i.complexity,cognitiveComplexity:i.cognitiveComplexity}))).sort((o,i)=>i[r]-o[r]).slice(0,s)}function Hr(t){return{nodes:t.nodes.map(r=>({path:r.path,type:r.type,category:r.category,exports:r.exports.map(n=>n.name),tags:r.tags.filter(n=>n.kind==="comment-marker"||n.kind==="import").map(n=>n.name),importsFiles:r.imports.filter(n=>!n.isExternal&&n.toPath).map(n=>n.toPath),...r.description!==void 0&&{description:r.description},...r.testedBy!==void 0&&{testedBy:r.testedBy},...r.coveragePct!==void 0&&{coveragePct:r.coveragePct},...r.avgExportUsage!==void 0&&{avgExportUsage:r.avgExportUsage},...r.maxExportUsage!==void 0&&{maxExportUsage:r.maxExportUsage}})),cycles:t.cycles}}function oe(t){return[...t.nodes.values()].some(e=>e.coveragePct!==void 0)}function go(t){return[...t.nodes.values()].some(e=>e.commitCount90d!==void 0)}function Fe(t,e={}){let{metric:r="cognitiveComplexity",minComplexity:n=10,maxCoveragePct:s=50,minChurn:o=0,limit:i=20}=e,a=go(t),c=[...t.nodes.values()].filter(l=>l.coveragePct!==void 0&&l.coveragePct<=s&&(!a||(l.commitCount90d??0)>=o)).flatMap(l=>(l.functions??[]).filter(p=>p[r]>=n).map(p=>({file:l.path,name:p.name,line:p.line,complexity:p.complexity,cognitiveComplexity:p.cognitiveComplexity,coveragePct:l.coveragePct,...l.commitCount90d!==void 0&&{commitCount90d:l.commitCount90d}}))).sort((l,p)=>p[r]-l[r]).slice(0,i);return{hotspots:c,count:c.length,churnDataAvailable:a}}import{execFileSync as Kr}from"child_process";import Ur from"fs";import Fp from"os";import Pp from"path";function Jr(t,e){try{return Kr("git",["rev-parse","--verify",`${e}^{commit}`],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error(`Could not resolve git ref "${e}" in ${t}`)}}async function ho(t,e,r){let n=Ur.mkdtempSync(Pp.join(Fp.tmpdir(),`mokosh-worktree-${e.slice(0,12)}-`));Ur.rmdirSync(n);try{return Kr("git",["worktree","add","--detach",n,e],{cwd:t,stdio:["ignore","pipe","pipe"]}),await r(n)}finally{try{Kr("git",["worktree","remove","--force",n],{cwd:t,stdio:["ignore","pipe","pipe"]})}catch{Ur.rmSync(n,{recursive:!0,force:!0})}}}async function vo(t,e,r,n={}){let s=Jr(t,e),o=zn(t,s);if(o)return{sha:s,graph:o};let i=await ho(t,s,async a=>{let c=n.pathAliases?new z(a,{pathAliases:n.pathAliases}):void 0;return new ne(a,null,c,void 0,n.gitStats??!1,new Map,n.parallelParsing??!0,n.additionalIgnoreDirs??[]).build(r)});return $n(t,s,i),{sha:s,graph:i}}var yo=t=>Math.round(t*100)/100,xo=t=>t.length>8?t.slice(0,8):t;function Np(t,e){return`${t.file}:${t.line} ${t.name} (${t[e]})`}function Rp(t,e){return`${t.file}:${t.line} ${t.name} (${t[e]}, cov ${t.coveragePct}%)`}function Dp(t,e=4){let r=t.occurrences.slice(0,e).map(o=>`${o.file}:${o.startLine}-${o.endLine}`),n=t.occurrences.length-r.length,s=n>0?`, +${n} more`:"";return`${t.lines}L x${t.occurrences.length}: ${r.join(", ")}${s}`}var ie=(t,e)=>`${t} ${e}${t===1?"":"s"}`;function Ip(t,e){let{files:r,staleReferences:n,duplication:s,complexity:o,docDrift:i,coverage:a}=t,c=[],l=[r.added.length&&`${r.added.length} added`,r.changed.length&&`${r.changed.length} changed`,r.removed.length&&`${r.removed.length} removed`].filter(Boolean);c.push(l.length?`Files: ${l.join(", ")}`:"No file changes"),n.length>0&&c.push(`\u26A0 ${ie(n.length,"stale reference")} \u2014 removed export still imported`);let p=o.newHotspots[0];return p?c.push(`+${ie(o.newHotspots.length,"complexity hotspot")} (max ${e} ${p[e]} in ${p.file})`):o.resolvedHotspots.length>0&&c.push(`${ie(o.resolvedHotspots.length,"complexity hotspot")} resolved`),s.newGroups.length>0?c.push(`+${ie(s.newGroups.length,"duplication group")}`):s.resolvedGroups.length>0&&c.push(`${ie(s.resolvedGroups.length,"duplication group")} resolved`),i.newlyStale.length>0&&c.push(`${ie(i.newlyStale.length,"doc")} newly stale`),a&&a.newHotspots.length>0&&c.push(`+${ie(a.newHotspots.length,"risk hotspot")}`),c}function Mp(t){let{staleReferences:e,duplication:r,complexity:n,docDrift:s,coverage:o}=t;return e.length>0||(o?.newHotspots.length??0)>0?"attention":n.newHotspots.length>0||r.newGroups.length>0||s.newlyStale.length>0?"review-worthy":"clean"}function qr(t,e={}){let r=e.metric??"cognitiveComplexity",n=e.maxItems??8,s=e.maxPathList??100,{files:o,staleReferences:i,duplication:a,complexity:c,docDrift:l,coverage:p}=t,u=yo(c.head.avgCognitiveComplexity-c.base.avgCognitiveComplexity),m=o.added.length+o.changed.length+o.removed.length,d={base:`${t.base.ref}@${xo(t.base.sha)}`,head:`${t.head.ref}@${xo(t.head.sha)}`,verdict:Mp(t),headline:Ip(t,r),files:{added:o.added.length,changed:o.changed.length,removed:o.removed.length,...m<=s?{paths:{added:o.added,changed:o.changed,removed:o.removed}}:{}}};return i.length>0&&(d.staleReferences=i),(c.newHotspots.length>0||c.resolvedHotspots.length>0)&&(d.complexity={avgDelta:u,newHotspots:c.newHotspots.slice(0,n).map(y=>Np(y,r)),newHotspotCount:c.newHotspots.length,resolvedCount:c.resolvedHotspots.length}),(a.newGroups.length>0||a.resolvedGroups.length>0)&&(d.duplication={newGroups:a.newGroups.slice(0,n).map(y=>Dp(y)),newGroupCount:a.newGroups.length,resolvedCount:a.resolvedGroups.length,totalGroups:a.head.groups}),(l.newlyStale.length>0||l.resolved.length>0)&&(d.docDrift={newlyStale:l.newlyStale.slice(0,n).map(y=>y.replace("::"," \u2192 ")),newlyStaleCount:l.newlyStale.length,resolvedCount:l.resolved.length}),p&&(p.newHotspots.length>0||p.resolvedHotspots.length>0)&&(d.coverage={avgDelta:yo(p.head.avgCoveragePct-p.base.avgCoveragePct),newHotspots:p.newHotspots.slice(0,n).map(y=>Rp(y,r)),newHotspotCount:p.newHotspots.length,resolvedCount:p.resolvedHotspots.length}),d}function _p(t,e){let r=[],n=[];for(let[o,i]of e.nodes){let a=t.nodes.get(o);if(!a){r.push(o);continue}let c=JSON.stringify({category:a.category,exports:a.exports.map(p=>p.name).sort(),imports:a.imports.map(p=>p.toPath).sort()}),l=JSON.stringify({category:i.category,exports:i.exports.map(p=>p.name).sort(),imports:i.imports.map(p=>p.toPath).sort()});c!==l&&n.push(o)}let s=[...t.nodes.keys()].filter(o=>!e.nodes.has(o));return{added:r,removed:s,changed:n}}function Lp(t,e){let r=[];for(let[n,s]of t.nodes){let o=e.nodes.get(n);if(!o)continue;let i=new Set(o.exports.map(c=>c.name)),a=s.exports.map(c=>c.name).filter(c=>!i.has(c));if(a.length!==0)for(let c of a){let l=[...e.nodes.values()].filter(p=>p.imports.some(u=>u.toPath===n&&u.symbols?.includes(c))).map(p=>p.path);l.length>0&&r.push({file:n,symbol:c,stillReferencedBy:l})}}return r}function Et(t){return t.occurrences.map(e=>`${e.file}:${e.startLine}-${e.endLine}`).sort().join("|")}async function Gp(t,e,r,n,s){let o=Ap.join(at(t),`${n}-${De}`),i=Ce(o),[{groups:a},{groups:c}]=await Promise.all([Ee(e,t,{minLines:s,tokenCache:i}),Ee(r,t,{minLines:s})]);we(i,o);let l=new Set(a.map(Et)),p=new Set(c.map(Et));return{base:{groups:a.length},head:{groups:c.length},newGroups:c.filter(u=>!l.has(Et(u))),resolvedGroups:a.filter(u=>!p.has(Et(u)))}}function bo(t){let e=[...t.nodes.values()].map(r=>r.cognitiveComplexity).filter(r=>r!==void 0);return e.length===0?0:e.reduce((r,n)=>r+n,0)/e.length}function Op(t,e,r,n){let s=Te(t,{metric:r,threshold:n,limit:1/0}),o=Te(e,{metric:r,threshold:n,limit:1/0}),i=l=>`${l.file}:${l.name}`,a=new Set(s.map(i)),c=new Set(o.map(i));return{base:{avgCognitiveComplexity:bo(t)},head:{avgCognitiveComplexity:bo(e)},newHotspots:o.filter(l=>!a.has(i(l))),resolvedHotspots:s.filter(l=>!c.has(i(l)))}}function So(t){let e=new Set;for(let r of t.nodes.values())if(!(r.type!=="markdown"||!r.staleFor))for(let n of r.staleFor)e.add(`${r.path}::${n}`);return e}function jp(t,e){let r=So(t),n=So(e);return{base:{staleCount:r.size},head:{staleCount:n.size},newlyStale:[...n].filter(s=>!r.has(s)),resolved:[...r].filter(s=>!n.has(s))}}function ko(t){let e=[...t.nodes.values()].map(r=>r.coveragePct).filter(r=>r!==void 0);return e.length===0?0:e.reduce((r,n)=>r+n,0)/e.length}function Wp(t,e,r){if(!oe(t)||!oe(e))return null;let n=Fe(t,{maxCoveragePct:r,limit:1/0}).hotspots,s=Fe(e,{maxCoveragePct:r,limit:1/0}).hotspots,o=c=>`${c.file}:${c.name}`,i=new Set(n.map(o)),a=new Set(s.map(o));return{base:{avgCoveragePct:ko(t)},head:{avgCoveragePct:ko(e)},newHotspots:s.filter(c=>!i.has(o(c))),resolvedHotspots:n.filter(c=>!a.has(o(c)))}}async function Vr(t,e,r,n={}){let{sha:s,graph:o}=await vo(t,e,n.entryPoints??[],n),i=Jr(t,n.headRef??"HEAD"),[a,c]=await Promise.all([Gp(t,o,r,s,n.minDuplicateLines),Promise.resolve(Wp(o,r,n.maxCoveragePct))]);return{base:{ref:e,sha:s},head:{ref:n.headRef??"HEAD",sha:i},files:_p(o,r),staleReferences:Lp(o,r),duplication:a,complexity:Op(o,r,n.complexityMetric,n.complexityThreshold),docDrift:jp(o,r),coverage:c}}import Tt from"path";function zp(t){let e=new Map;for(let[r,n]of t){let s=n.imports.filter(o=>o.toPath&&!o.isExternal).length;s>0&&e.set(r,s)}return e}function $p(t,e,r){let n=new Map;for(let[s,o]of e){if(o<r)continue;let i=t.get(s);if(!i||i.category==="test"||i.category==="barrel")continue;let a=Tt.extname(s),c=Tt.basename(s,a),l=c==="index"?Tt.basename(Tt.dirname(s)):c;n.set(s,{path:s,outDegree:o,tag:`feature:${l}`})}return n}function ae(t,e){let r=e?.minOutDegree??5;return $p(t,zp(t),r)}var Bp=(t,e)=>t.outDegree-e.outDegree;function Hp(t,e){let r=new Map;for(let n of e.values()){let s=new Set;t.traverse(n.path,o=>(o.path!==n.path&&s.add(o.path),!0),{direction:"outgoing"}),r.set(n.path,s)}return r}function Up(t,e,r,n){let s=new Map;for(let[o]of t){if(e.has(o))continue;let i=null;for(let a of e.values())r.get(a.path)?.has(o)&&(!i||n(a,i)<0)&&(i=a);i&&s.set(o,i.path)}return s}function Kp(t,e){let r=new Map;for(let n of t.values()){let s=n.tag.replace("feature:",""),o=[];for(let[i,a]of e)a===n.path&&o.push(i);r.set(s,{hub:n.path,outDegree:n.outDegree,files:o})}return r}function Jp(t,e,r){let n=[];for(let s of t.keys())!e.has(s)&&!r.has(s)&&n.push(s);return n}function Ve(t,e){let r=e?.detectFn??ae,n=e?.hubComparator??Bp,s=r(t.nodes,e),o=Hp(t,s),i=Up(t.nodes,s,o,n);return{features:Kp(s,i),unassigned:Jp(t.nodes,s,i)}}var qp=[{role:"component",segments:["component","components"]},{role:"controller",segments:["controller","controllers"]},{role:"middleware",segments:["middleware"]},{role:"router",segments:["router","routes","route"]},{role:"store",segments:["store","stores"]},{role:"service",segments:["service","services"]},{role:"handler",segments:["handler","handlers"]},{role:"adapter",segments:["adapter","adapters"]},{role:"plugin",segments:["plugin","plugins"]},{role:"api",segments:["api"]},{role:"cli",segments:["cli","commands"],basenames:["cli"]},{role:"util",segments:["util","utils","helper","helpers"]},{role:"model",segments:["model","models"],basenames:["model"]},{role:"parser",segments:["parser","parsers"],basenames:["parser"]},{role:"builder",basenames:["builder"]},{role:"resolver",basenames:["resolver"]}];function Co(t){if(t.category==="test")return"test";if(t.category==="config")return"config";if(t.category==="type-only")return"types";let e=t.path,r=Qp(e);for(let n of qp)if(n.segments?.some(s=>Vp(e,s))||n.basenames?.includes(r))return n.role;return"other"}function Vp(t,e){return t.includes(`/${e}/`)||t.includes(`/${e}.`)}function Qp(t){let e=t.slice(t.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function Qr(t,e){let r=Ve(t,e),n=new Map;for(let[o,i]of r.features){for(let a of i.files)n.set(a,o);n.set(i.hub,o)}let s=new Map;for(let o of t.nodes.values()){let i=n.get(o.path);s.set(o.path,{path:o.path,role:Co(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return s}function Yr(t,e){let r=[];for(let n of t.nodes.values())if(n.exports.some(s=>s.name===e))if(bt.has(n.type)){let s=[];for(let o of t.nodes.values())for(let i of o.callEdges??[])i.to===e&&s.push({file:o.path,callerFunction:i.from});r.push({path:n.path,category:n.category,precision:"call",callers:s})}else{let s=qe(t,n.path).map(o=>({file:o.path,...o.symbols?{symbols:o.symbols}:{}}));r.push({path:n.path,category:n.category,precision:"file-level",importers:s})}return r}function Yp(t){return t?t.startsWith("interface ")?"interface":t.startsWith("class ")?"class":t.startsWith("enum ")?"enum":"type":"type"}function Xp(t,e){if(e==="type-only")return!0;let r=t.signature??"";return r.startsWith("interface ")||r.startsWith("class ")||r.startsWith("enum ")}function Xr(t){let e=new Map;for(let n of t.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript"))for(let s of n.exports){if(!Xp(s,n.category))continue;let o=`${n.path}::${s.name}`;e.set(o,{name:s.name,file:n.path,kind:Yp(s.signature),...s.doc?{doc:s.doc}:{}})}let r=[];for(let n of t.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript")){for(let s of n.imports)if(!(!s.toPath||s.isExternal||!s.symbols?.length))for(let o of s.symbols)e.has(`${s.toPath}::${o}`)&&r.push({fromFile:n.path,toType:o,toFile:s.toPath})}return{types:e,edges:r}}function Zr(t,e){let r=null;for(let o of t.types.values())if(o.name===e){r=o;break}if(!r)return{type:null,usedByFiles:[],uses:[]};let n=new Set,s=new Map;for(let o of t.edges)if(o.toType===e&&o.toFile===r.file&&n.add(o.fromFile),o.fromFile===r.file){let i=t.types.get(`${o.toFile}::${o.toType}`);i&&s.set(`${i.file}::${i.name}`,i)}return{type:r,usedByFiles:Array.from(n),uses:Array.from(s.values())}}import ku from"path";import To from"fs";import Fo from"path";import Zp from"fs";import en from"path";import wo from"fs";import xb from"path";function Ft(t){try{return wo.statSync(t,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function Pt(t){try{return wo.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}var eu=new Set([".java",".kt",".kts",".scala",".sc",".groovy",".gradle"]),tu=new Set(N);function Eo(t,e=[]){let r;try{r=Zp.readdirSync(t,{withFileTypes:!0})}catch{return e}for(let n of r){let s=en.join(t,n.name);n.isDirectory()?!tu.has(n.name)&&!n.name.startsWith(".")&&Eo(s,e):n.isFile()&&eu.has(en.extname(n.name).toLowerCase())&&e.push(s)}return e}function At(t,e,r){if(!Ft(e))return null;let n=Eo(e);return n.length===0?null:{name:r,root:e,relativeRoot:en.relative(t,e),entryPoints:n}}function ru(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function nu(t){let e=ru(t),r=new Set;for(let n of e.matchAll(/['"](:[A-Za-z0-9_\-.:]+)['"]/g)){let s=n[1].replace(/^:/,"").replace(/:$/,"");s&&r.add(s)}return[...r]}var Po={type:"gradle",detect(t){let e=["settings.gradle.kts","settings.gradle"].map(o=>Fo.join(t,o)).find(o=>To.existsSync(o));if(!e)return null;let r;try{r=To.readFileSync(e,"utf-8")}catch{return null}let n=nu(r);if(n.length===0)return null;let s=[];for(let o of n){let i=Fo.join(t,...o.split(":")),a=At(t,i,o);a&&s.push(a)}return s.length>0?s:null}};import rn from"fs";import No from"path";import Qe from"fs";import I from"path";function tn(t,e){let r=I.join(e,"package.json");if(!Qe.existsSync(r))return null;let n={};try{n=JSON.parse(Qe.readFileSync(r,"utf-8"))}catch{return null}let s=n.name;return s?{name:s,root:e,relativeRoot:I.relative(t,e),entryPoints:su(e,n)}:null}function su(t,e){let r=[];if(e.exports){let s=e.exports;if(typeof s=="string")r.push(I.join(t,s));else if(typeof s=="object"&&s!==null){let o=s["."];if(typeof o=="string")r.push(I.join(t,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&r.push(I.join(t,i))}}}e.main&&r.push(I.join(t,e.main));for(let s of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])r.push(I.join(t,s));let n=r.filter(Pt);return n.length>0?n.slice(0,1):r.slice(0,1)}function Pe(t,e){let r=[],n=new Set;for(let s of e){let o=s.replace(/\/$/,"").replace(/^\.\//,"");ou(t,o,n,r)}return r}function ou(t,e,r,n){if(!e.includes("*")){iu(t,e,r,n);return}let s=e.split("/");s.includes("**")?au(t,s,r,n):cu(t,s,r,n)}function iu(t,e,r,n){let s=I.join(t,e);if(r.has(s)||!Ft(s))return;r.add(s);let o=tn(t,s);o&&n.push(o)}function au(t,e,r,n){let s=I.join(t,e[0]==="**"?"":e[0]??"");Ao(t,s,r,n)}function cu(t,e,r,n){let s=e.findIndex(a=>a.includes("*")),o=I.join(t,...e.slice(0,s)),i;try{i=Qe.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let c=I.join(o,a.name);if(r.has(c))continue;r.add(c);let l=tn(t,c);l&&n.push(l)}}function Ao(t,e,r,n){let s;try{s=Qe.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of s){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=I.join(e,o.name);if(Qe.existsSync(I.join(i,"package.json"))&&!r.has(i)){r.add(i);let a=tn(t,i);a&&n.push(a)}else Ao(t,i,r,n)}}var Ro={type:"npm",detect(t){let e=No.join(t,"package.json");if(!rn.existsSync(e))return null;let r;try{r=JSON.parse(rn.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r||rn.existsSync(No.join(t,"yarn.lock")))return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:Pe(t,n)}};import Ae from"fs";import F from"path";var Do={type:"nx",detect(t){return Ae.existsSync(F.join(t,"nx.json"))?Io(t,t,new Set,0).map(r=>lu(t,r,F.join(r,"project.json"))).filter(r=>r!==null):null}};function Io(t,e,r,n){if(n>4)return[];let s;try{s=Ae.readdirSync(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let i of s){if(!i.isDirectory())continue;let a=i.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let c=F.join(e,a);Ae.existsSync(F.join(c,"project.json"))&&!r.has(c)?(r.add(c),o.push(c)):o.push(...Io(t,c,r,n+1))}return o}function lu(t,e,r){let n={};try{n=JSON.parse(Ae.readFileSync(r,"utf-8"))}catch{return null}let s=n.name,o,i,a=F.join(e,"package.json");if(Ae.existsSync(a))try{let c=JSON.parse(Ae.readFileSync(a,"utf-8"));s=c.name??s,o=c.main,i=c.exports}catch{}return s?{name:s,root:e,relativeRoot:F.relative(t,e),entryPoints:pu(e,n,o,i)}:null}function pu(t,e,r,n){let s=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=F.resolve(t,"../..");s.push(F.resolve(a,o)),s.push(F.resolve(t,o))}if(n){let a=n;if(typeof a=="string")s.push(F.join(t,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&s.push(F.join(t,c))}}if(r&&s.push(F.join(t,r)),e.sourceRoot){let a=F.resolve(t,"../.."),c=F.resolve(a,e.sourceRoot);s.push(F.join(c,"index.ts"),F.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])s.push(F.join(t,a));let i=s.filter(Pt);return i.length>0?i.slice(0,1):s.slice(0,1)}import Mo from"fs";import uu from"path";import{load as mu}from"js-yaml";var _o={type:"pnpm",detect(t){let e=uu.join(t,"pnpm-workspace.yaml");if(!Mo.existsSync(e))return null;let r=[];try{r=mu(Mo.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return Pe(t,r)}};import Ye from"fs";import Nt from"path";function fu(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function gu(t){let e=fu(t),r=new Map;for(let n of e.matchAll(/(?:lazy\s+)?val\s+([A-Za-z0-9_]+)\s*=\s*\(?\s*project\b([^\n]*)/g)){let s=n[1],i=n[2].match(/\bfile\s*\(\s*["']([^"']+)["']\s*\)/),a=i?i[1]:s;if(a==="."||a==="./")continue;let c=a.replace(/^\.\//,"").replace(/\/$/,"");r.has(c)||r.set(c,{name:s,dir:c})}return[...r.values()]}var Lo={type:"sbt",detect(t){let e=Nt.join(t,"build.sbt"),r=Nt.join(t,"project");if(!Ye.existsSync(e)||!Ye.existsSync(r))return null;let n=[];try{n.push(Ye.readFileSync(e,"utf-8"))}catch{return null}try{for(let a of Ye.readdirSync(r))a.endsWith(".scala")&&n.push(Ye.readFileSync(Nt.join(r,a),"utf-8"))}catch{}let s=new Set,o=[];for(let a of n)for(let c of gu(a))s.has(c.dir)||(s.add(c.dir),o.push(c));if(o.length===0)return null;let i=[];for(let a of o){let c=Nt.join(t,...a.dir.split("/")),l=At(t,c,a.name);l&&i.push(l)}return i.length>0?i:null}};import du from"fs";import hu from"path";var Go={type:"turborepo",detect(t){return du.existsSync(hu.join(t,"turbo.json"))?[]:null}};import nn from"fs";import Oo from"path";var jo={type:"yarn",detect(t){if(!nn.existsSync(Oo.join(t,"yarn.lock")))return null;let e=Oo.join(t,"package.json");if(!nn.existsSync(e))return null;let r;try{r=JSON.parse(nn.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r)return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:Pe(t,n)}};var Wo=[];function _(t){Wo.push(t)}function zo(){return Wo}import yu from"fs";import xu from"path";var bu=["dependencies","devDependencies","peerDependencies","optionalDependencies"];function Su(t){try{let e=yu.readFileSync(xu.join(t,"package.json"),"utf-8"),r=JSON.parse(e),n=new Set;for(let s of bu){let o=r[s];if(o&&typeof o=="object")for(let i of Object.keys(o))n.add(i)}return n}catch{return null}}function Xe(t,e){if(e){let o=e.getPackageDependencies(),i=Array.from(e.packages.values()).map(({graph:a,pkg:c})=>({name:c.name,relativeRoot:c.relativeRoot,dependsOn:o.get(c.name)??[],nodeCount:a.nodes.size}));return{monorepoType:t.type,monorepoTypes:t.types,packageCount:i.length,packages:i,dependsOnResolved:!0,nodeCountsResolved:!0}}let r=new Set(t.packages.map(o=>o.name)),n=!0,s=t.packages.map(o=>{let i=Su(o.root);if(i===null)return n=!1,{name:o.name,relativeRoot:o.relativeRoot,dependsOn:[]};let a=[...i].filter(c=>c!==o.name&&r.has(c)).sort();return{name:o.name,relativeRoot:o.relativeRoot,dependsOn:a}});return{monorepoType:t.type,monorepoTypes:t.types,packageCount:s.length,packages:s,dependsOnResolved:n,nodeCountsResolved:!1,note:"Layout only \u2014 per-package node counts and (for build-system monorepos without package.json) dependency edges require a full graph. Call analyze with empty entryPoints, then get_workspace_packages again."}}_(Go);_(Do);_(_o);_(jo);_(Ro);_(Po);_(Lo);function Ze(t,e=zo()){let r=ku.resolve(t),n=new Map,s=[];for(let i of e){let a=i.detect(r);if(a!==null){s.push(i.type);for(let c of a)n.has(c.name)||n.set(c.name,c)}}if(s.length===0)return{root:r,type:"none",types:[],packages:[],packageMap:new Map};let o=Array.from(n.values());return{root:r,type:s[0],types:s,packages:o,packageMap:new Map(o.map(i=>[i.name,i]))}}var ce=class t{constructor(e,r){this.monorepoRoot=e;this.type=r}monorepoRoot;type;packages=new Map;addPackage(e,r){this.packages.set(e.name,{graph:r,pkg:e})}annotateCrossPackageEdges(){for(let{graph:e}of this.packages.values())for(let r of e.nodes.values()){let n=this.getPackageForFile(r.path);if(n)for(let s of r.imports){if(s.isExternal||s.isWorkspace)continue;let o=this.getPackageForFile(s.toPath);o&&o.name!==n.name&&(s.isWorkspace=!0,s.workspacePackage=o.name)}}}getPackageForFile(e){for(let{pkg:r}of this.packages.values())if(e===r.relativeRoot||e.startsWith(`${r.relativeRoot}/`))return r}getPackageDependencies(){let e=new Map;for(let{graph:r,pkg:n}of this.packages.values()){let s=new Set;for(let o of r.nodes.values())for(let i of o.imports)i.isWorkspace&&i.workspacePackage&&s.add(i.workspacePackage);e.set(n.name,[...s])}return e}getAffectedAcrossPackages(e){let r=this.getPackageForFile(e);if(!r)return[];let n=this.packages.get(r.name);if(!n)return[];let s=[];n.graph.traverse(e,o=>(o.path!==e&&s.push({file:o.path,package:r.name}),!0),{direction:"incoming"});for(let{graph:o,pkg:i}of this.packages.values())if(i.name!==r.name)for(let a of o.nodes.values())a.imports.some(l=>l.isWorkspace&&l.workspacePackage===r.name)&&s.push({file:a.path,package:i.name});return s}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:r})=>({pkg:{name:r.name,relativeRoot:r.relativeRoot,entryPoints:r.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let r=new t(e.monorepoRoot,e.type);for(let{pkg:n,nodes:s}of e.packages){let o=new Map(s.map(a=>[a.path,a])),i=new R(o);r.packages.set(n.name,{graph:i,pkg:{...n,root:""}})}return r}};function $o(t,e){return e.startsWith("!")?t!==e.slice(1):t===e}function vu(t,e){return e.startsWith("!")?!t.includes(e.slice(1)):t.includes(e)}var Cu=(t,e)=>!e.category||$o(t.category,e.category),wu=(t,e)=>!e.type||$o(t.type,e.type),Eu=(t,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?t.lastAuthor!==e.lastAuthor.slice(1):t.lastAuthor!==void 0&&t.lastAuthor===e.lastAuthor:!0,Tu=(t,e)=>!e.path||vu(t.path,e.path),Fu=(t,e)=>e.isExternal===void 0?!0:t.imports.some(n=>n.isExternal)===e.isExternal,Pu=(t,e)=>{if(!e.tags||e.tags.length===0)return!0;let r=e.tags.filter(s=>!s.startsWith("!")),n=e.tags.filter(s=>s.startsWith("!")).map(s=>s.slice(1));return!(r.length>0&&!r.some(s=>t.tags.some(o=>o.name===s))||n.some(s=>t.tags.some(o=>o.name===s)))},Au=(t,e)=>!e.allTags?.length||e.allTags.every(r=>t.tags.some(n=>n.name===r)),Nu=(t,e)=>!e.importsFile||t.imports.some(r=>r.toPath?.includes(e.importsFile)),Ru=(t,e,r)=>e.importedBy===void 0?!0:(r?.get(t.path)??[]).some(s=>s.includes(e.importedBy)),Du=(t,e)=>e.minImports===void 0||t.imports.length>=e.minImports,Iu=(t,e)=>e.maxImports===void 0||t.imports.length<=e.maxImports,Mu=(t,e)=>e.minSize===void 0||t.size>=e.minSize,_u=(t,e)=>e.maxSize===void 0||t.size<=e.maxSize,Lu=(t,e)=>e.hasDocstring===void 0||!!t.description===e.hasDocstring,Gu=(t,e)=>e.isDocumented===void 0||!!t.documentedBy?.length===e.isDocumented,Ou=(t,e)=>e.isStale===void 0||!!t.staleFor?.length===e.isStale,ju=(t,e)=>e.minCoverage===void 0||(t.coveragePct??101)>=e.minCoverage,Wu=(t,e)=>e.maxCoverage===void 0||(t.coveragePct??0)<=e.maxCoverage,zu=(t,e)=>e.minExportUsage===void 0||(t.avgExportUsage??-1)>=e.minExportUsage,$u=(t,e)=>e.maxExportUsage===void 0||(t.avgExportUsage??0)<=e.maxExportUsage,Bu=(t,e)=>e.minComplexity===void 0||(t.complexity??-1/0)>=e.minComplexity,Hu=(t,e)=>e.maxComplexity===void 0||(t.complexity??0)<=e.maxComplexity,Uu=(t,e)=>e.minCognitiveComplexity===void 0||(t.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,Ku=(t,e)=>e.maxCognitiveComplexity===void 0||(t.cognitiveComplexity??0)<=e.maxCognitiveComplexity,Ju=(t,e)=>e.minCommits===void 0||(t.commitCount90d??-1/0)>=e.minCommits,qu=(t,e)=>e.maxCommits===void 0||(t.commitCount90d??0)<=e.maxCommits,Vu=(t,e,r)=>!e.any?.length||e.any.some(n=>et(t,n,r)),Qu=[Cu,wu,Eu,Tu,Fu,Pu,Au,Nu,Ru,Du,Iu,Mu,_u,Lu,Gu,Ou,ju,Wu,zu,$u,Bu,Hu,Uu,Ku,Ju,qu,Vu];function et(t,e,r){return Qu.every(n=>n(t,e,r))}function Rt(t,e){let r=new Map;if(e.importedBy!==void 0){for(let i of t.nodes)for(let a of i.imports)if(a.toPath){let c=r.get(a.toPath)??[];c.push(i.path),r.set(a.toPath,c)}}let n=t.nodes.filter(i=>et(i,e,r)),s=new Set(n.map(i=>i.path)),o=n.map(i=>({...i,imports:i.imports.filter(a=>!a.toPath||s.has(a.toPath))}));if(e.sort){let i=e.sortDir==="asc"?-1:1;o.sort((a,c)=>{let l=0;switch(e.sort){case"size":l=c.size-a.size;break;case"imports":l=c.imports.length-a.imports.length;break;case"commitCount90d":l=(c.commitCount90d??0)-(a.commitCount90d??0);break;case"exportUsage":l=(c.avgExportUsage??0)-(a.avgExportUsage??0);break;case"complexity":l=(c.complexity??0)-(a.complexity??0);break;case"cognitiveComplexity":l=(c.cognitiveComplexity??0)-(a.cognitiveComplexity??0);break}return l*i})}return e.limit!==void 0&&o.splice(e.limit),{nodes:o,cycles:t.cycles?.filter(i=>i.every(a=>s.has(a)))??void 0}}var Yu={category:{field:"category",kind:"string"},type:{field:"type",kind:"string"},path:{field:"path",kind:"string"},importsfile:{field:"importsFile",kind:"string"},importedby:{field:"importedBy",kind:"string"},lastauthor:{field:"lastAuthor",kind:"string"},external:{field:"isExternal",kind:"boolIsTrue"},hasdocstring:{field:"hasDocstring",kind:"boolNotFalse"},isdocumented:{field:"isDocumented",kind:"boolNotFalse"},isstale:{field:"isStale",kind:"boolNotFalse"},minimports:{field:"minImports",kind:"int"},maximports:{field:"maxImports",kind:"int"},minsize:{field:"minSize",kind:"int"},maxsize:{field:"maxSize",kind:"int"},limit:{field:"limit",kind:"int"},mincoverage:{field:"minCoverage",kind:"int"},maxcoverage:{field:"maxCoverage",kind:"int"},minexportusage:{field:"minExportUsage",kind:"float"},maxexportusage:{field:"maxExportUsage",kind:"float"},mincomplexity:{field:"minComplexity",kind:"int"},maxcomplexity:{field:"maxComplexity",kind:"int"},mincognitivecomplexity:{field:"minCognitiveComplexity",kind:"int"},maxcognitivecomplexity:{field:"maxCognitiveComplexity",kind:"int"},mincommits:{field:"minCommits",kind:"int"},maxcommits:{field:"maxCommits",kind:"int"}};function Xu(t,e,r,n){let s=t;switch(r){case"string":s[e]=n;break;case"int":s[e]=parseInt(n,10);break;case"float":s[e]=parseFloat(n);break;case"boolNotFalse":s[e]=n.toLowerCase()!=="false";break;case"boolIsTrue":s[e]=n.toLowerCase()==="true";break}}function Ho(t,e){let r=e.indexOf(":");if(r===-1)return;let n=e.slice(0,r).trim().toLowerCase(),s=e.slice(r+1).trim();if(!n||!s)return;if(n==="tag"||n==="tags"){s.includes("+")?t.allTags=[...t.allTags??[],...s.split("+")]:t.tags=[...t.tags??[],s];return}if(n==="sort"){t.sort=s;return}if(n==="sortdir"){t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";return}let o=Yu[n];o&&Xu(t,o.field,o.kind,s)}function Zu(t){let e=[];for(let r of t.split("|")){let n=r.trim();if(!n)continue;let s={};Ho(s,n),Object.keys(s).length>0&&e.push(s)}return e}var Bo="any(";function Dt(t){let e={},r=t.split(",");for(let n of r){let s=n.trim();if(s.toLowerCase().startsWith(Bo)&&s.endsWith(")")){let o=s.slice(Bo.length,-1),i=Zu(o);i.length>0&&(e.any=[...e.any??[],...i]);continue}Ho(e,n)}return e}import ei from"fs/promises";import Om from"path";import bn from"path";import Bt from"typescript";import rm from"path";import em from"path";import T from"typescript";var Uo=new Set(["describe","test","it"]);function le(t,e){let r=t[e];if(r===void 0)throw new Error(`Index ${e} out of bounds (length ${t.length})`);return r}function sn(t){let e=[];for(let r of t.statements){if(!T.isExpressionStatement(r))continue;let n=r.expression;if(!T.isCallExpression(n))continue;let s=n.expression;T.isIdentifier(s)&&Uo.has(s.text)&&e.push(n),T.isPropertyAccessExpression(s)&&T.isIdentifier(s.expression)&&Uo.has(s.expression.text)&&e.push(n)}return e}function on(t,e,r){for(let n of t.arguments){if(!T.isObjectLiteralExpression(n))continue;let s=n.properties.find(o=>T.isPropertyAssignment(o)&&T.isIdentifier(o.name)&&o.name.text===e);if(!(!s||!T.isArrayLiteralExpression(s.initializer)))return s.initializer.elements.filter(T.isStringLiteral).map(o=>o.text)}return null}function an(t,e,r,n){if(t.arguments.length===0)return null;for(let o=1;o<t.arguments.length;o++){let i=le(t.arguments,o);if(!T.isObjectLiteralExpression(i))continue;let a=i.properties.find(l=>T.isPropertyAssignment(l)&&T.isIdentifier(l.name)&&l.name.text===e);if(a)return{start:a.initializer.getStart(n),end:a.initializer.getEnd(),text:r};let c=i.getEnd()-1;return{start:c,end:c,text:`${i.properties.length>0?", ":""}${e}: ${r}`}}let s=le(t.arguments,t.arguments.length-1);return{start:s.getStart(n),end:s.getStart(n),text:`{ ${e}: ${r} }, `}}function cn(t,e,r){let n=t.arguments;for(let s=1;s<n.length;s++){let o=le(n,s);if(!T.isObjectLiteralExpression(o))continue;let i=o.properties.findIndex(c=>T.isPropertyAssignment(c)&&T.isIdentifier(c.name)&&c.name.text===e);if(i<0)continue;if(o.properties.length===1)return{start:le(n,s-1).getEnd(),end:o.getEnd(),text:""};let a=le(o.properties,i);return i===o.properties.length-1?{start:le(o.properties,i-1).getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(r),end:le(o.properties,i+1).getStart(r),text:""}}return null}function ln(t,e){let r=[...e].sort((s,o)=>o.start-s.start),n=t;for(let s of r)n=n.slice(0,s.start)+s.text+n.slice(s.end);return n}function pn(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}var L=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function tm(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}function It(t,e,r,n){let s=T.createSourceFile(em.basename(t),e,T.ScriptTarget.Latest,!0),o=sn(s),[i]=o;if(!i)return e;let a=on(i,n,s),c=[...r].sort();if(a!==null&&JSON.stringify(tm(a).sort())===JSON.stringify(c))return e;let l=pn(c.map(u=>`@${u}`)),p=o.flatMap(u=>{let m=r.length===0?cn(u,n,s):an(u,n,l,s);return m?[m]:[]});return p.length>0?ln(e,p):e}var Mt=class{name="cypress";canHandle(e){return L.has(rm.extname(e).toLowerCase())}apply(e,r,n){return It(e,r,n,"tags")}};import nm from"path";var un=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,mn=/^@([a-zA-Z0-9_-]+)/gm;function sm(t){return`${["# <mokosh-tags>",...t.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
|
|
12
30
|
`)}
|
|
13
31
|
|
|
14
|
-
`}function
|
|
15
|
-
`}function
|
|
16
|
-
${r.slice(c)}`}};import
|
|
32
|
+
`}function om(t){let e=new Set;mn.lastIndex=0;let r=mn.exec(t);for(;r!==null;)r[1]&&e.add(r[1]),r=mn.exec(t);return e}var _t=class{name="gherkin";canHandle(e){return nm.extname(e).toLowerCase()===".feature"}apply(e,r,n){let s=r.replace(un,""),o=om(s),i=n.filter(c=>!o.has(c)),a=i.length>0?sm(i):"";return un.test(r)?r.replace(un,a):a?r.replace(/^(Feature:)/m,`${a}$1`):r}};function Ko(t,e){let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/"),s="";for(let o=0;o<r.length;o++){let i=r[o];i==="*"?r[o+1]==="*"?(s+=".*",o++):s+="[^/]*":i==="?"?s+="[^/]":i!==void 0&&(s+=i.replace(/[.+^${}()|[\]\\]/g,"\\$&"))}return new RegExp(`^${s}$`).test(n)}import im from"path";var fn=/^\/\/go:build mokosh_[^\n]+\n/m,am=/^package\s+\S+/m;function cm(t){return`//go:build ${t.map(r=>`mokosh_${r}`).join(" || ")}
|
|
33
|
+
`}function lm(t){let e=fn.exec(t);if(!e)return null;let r=e[0]??"",n=/mokosh_([a-zA-Z0-9_-]+)/g,s=[],o=n.exec(r);for(;o!==null;)o[1]&&s.push(o[1]),o=n.exec(r);return s}var Lt=class{name="go";canHandle(e){return im.basename(e).endsWith("_test.go")}apply(e,r,n){let s=lm(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return r.replace(fn,"");let i=cm(o);if(s!==null)return r.replace(fn,i);let a=am.exec(r);if(!a)return r;let c=a.index;return`${r.slice(0,c)+i}
|
|
34
|
+
${r.slice(c)}`}};import pm from"path";var um=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,gn=/^ \* @group (.+)$/gm;function mm(t){return`${["/**",...t.map(e=>` * @group ${e}`)," */"].join(`
|
|
17
35
|
`)}
|
|
18
36
|
|
|
19
|
-
`}function
|
|
37
|
+
`}function fm(t){let e=[];gn.lastIndex=0;let r=gn.exec(t);for(;r!==null;)r[1]&&e.push(r[1]),r=gn.exec(t);return e}var Gt=class{name="jest";canHandle(e){return L.has(pm.extname(e).toLowerCase())}apply(e,r,n){let s=um.exec(r),o=s?fm(s[0]):null,i=[...n].sort();if(o!==null&&JSON.stringify([...o].sort())===JSON.stringify(i))return r;let a=s?r.slice(s[0].length):r;return n.length===0?a:mm(i)+a}};import gm from"path";var dm="// mokosh:tags",hn=/^\/\/ mokosh:tags\n(?:[ \t]*@Tag\("[^"]*"\)\n)*/m,dn="import org.junit.jupiter.api.Tag;",qo=/^import org\.junit\.jupiter\.api\.Tag;\n/m,hm=/^(?:public\s+|final\s+|abstract\s+|sealed\s+|non-sealed\s+|strictfp\s+)*(?:class|interface|enum|record|@interface)\s+\w+/m,ym=/^import\s+[^\n]+;\n(?![\s\S]*^import\s)/m,xm=/^package\s+[^\n]+;\n/m,bm=/\/src\/(test|androidTest|integrationTest|it)\//,Sm=/(Test|Tests|Spec|IT)\.(java|groovy)$/;function km(t){let e=hn.exec(t);if(!e)return null;let r=[],n=/@Tag\("([^"]*)"\)/g,s=n.exec(e[0]);for(;s!==null;)s[1]&&r.push(s[1]),s=n.exec(e[0]);return r}function vm(t){return`${dm}
|
|
38
|
+
${t.map(e=>`@Tag("${e}")`).join(`
|
|
39
|
+
`)}
|
|
40
|
+
`}function Jo(t){if(qo.test(t))return t;let e=ym.exec(t);if(e){let n=e.index+e[0].length;return t.slice(0,n)+dn+`
|
|
41
|
+
`+t.slice(n)}let r=xm.exec(t);if(r){let n=r.index+r[0].length;return t.slice(0,n)+`
|
|
42
|
+
`+dn+`
|
|
43
|
+
`+t.slice(n)}return dn+`
|
|
44
|
+
`+t}function Cm(t){return/@Tag\b/.test(t)?t:t.replace(qo,"")}var Ot=class{name="junit";canHandle(e){let r=e.replace(/\\/g,"/"),n=gm.extname(r).toLowerCase();return n!==".java"&&n!==".groovy"?!1:bm.test(r)||Sm.test(r)}apply(e,r,n){let s=km(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return s===null?r:Cm(r.replace(hn,""));let i=vm(o);if(s!==null)return Jo(r.replace(hn,i));let a=hm.exec(r);if(!a)return r;let c=r.slice(0,a.index)+i+r.slice(a.index);return Jo(c)}};import wm from"path";var jt=class{name="playwright";canHandle(e){return L.has(wm.extname(e).toLowerCase())}apply(e,r,n){return It(e,r,n,"tag")}};import Em from"path";var yn=/^pytestmark\s*=\s*.+$/m,Tm=/^import pytest\s*$/m;function Fm(t){let e=t.map(r=>`pytest.mark.${r}`).join(", ");return t.length===1?`pytestmark = pytest.mark.${t[0]}`:`pytestmark = [${e}]`}function Pm(t){let e=yn.exec(t);if(!e)return null;let r=e[0],n=[],s=/pytest\.mark\.([a-zA-Z0-9_-]+)/g,o=s.exec(r);for(;o!==null;)o[1]&&n.push(o[1]),o=s.exec(r);return n}var Wt=class{name="pytest";canHandle(e){return Em.extname(e).toLowerCase()===".py"}apply(e,r,n){let s=Pm(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return r.replace(yn,"").replace(/\n{3,}/g,`
|
|
20
45
|
|
|
21
|
-
`);let
|
|
22
|
-
`,
|
|
46
|
+
`);let i=Fm(o);if(s!==null)return r.replace(yn,i);let a=Tm.test(r),c=Am(r),l=r.slice(0,c),p=r.slice(c),u=a?"":`import pytest
|
|
47
|
+
`,m=l.endsWith(`
|
|
23
48
|
|
|
24
49
|
`)?"":`
|
|
25
|
-
`;return`${l+
|
|
26
|
-
${p}`}};function
|
|
27
|
-
`),r=-1;return e.forEach((s,
|
|
28
|
-
|
|
29
|
-
`)
|
|
30
|
-
`&&r++;return r}function za(t,e){let r=1;function n(s){switch(s.type.name){case"IfStatement":case"ForStatement":r++;break;case"Case":{s.firstChild?.type.name==="case"&&r++;break}case"LogicOp":{let o=e.slice(s.from,s.to);(o==="&&"||o==="||")&&r++;break}}let i=s.firstChild;for(;i;)n(i),i=i.nextSibling}return n(t),r}function Bn(t,e,r,n){let s=r?1:1+e,i=H(t),o=r?e:e+1,a=i[1];a&&a.type.name!=="Block"&&(s+=re(a,o,!1,n));let c=i.find(p=>p.type.name==="Block");c&&(s+=re(c,o,!1,n));let l=i.findIndex(p=>p.type.name==="else");if(l>=0){let p=i[l+1];p?.type.name==="IfStatement"?s+=Bn(p,e,!0,n):p&&(s+=1+re(p,e+1,!1,n))}return s}function Wn(t,e,r){let n=1+e,s=t.firstChild;for(;s;)n+=re(s,e+1,!1,r),s=s.nextSibling;return n}function Wa(t,e,r){let n=0,s=t.firstChild;for(;s;)n+=re(s,e,!1,r),s=s.nextSibling;return n}function Ba(t,e){let r=e.slice(t.from,t.to);return r==="&&"||r==="||"}function re(t,e,r,n){let s=t.type.name;if(s==="IfStatement")return Bn(t,e,r,n);if(s==="ForStatement"||s==="SwitchStatement"||s==="SelectStatement")return Wn(t,e,n);let i=s==="LogicOp"&&Ba(t,n)?1:0;return e>0&&s==="FunctionLiteral"?i+Wn(t,e,n):i+Wa(t,e,n)}function $a(t,e){return re(t,0,!1,e)}function st(t,e){return{complexity:za(t,e),cognitiveComplexity:$a(t,e)}}function pr(t,e){let n=t.getChild("Parameters")?.getChild("Parameter"),s=n?.getChild("TypeName")??n?.getChild("PointerType")?.getChild("TypeName");return s?e.slice(s.from,s.to):void 0}function $n(t,e){let r=[],n=t.cursor();do if(n.name==="FunctionDecl"){let s=n.node.getChild("DefName");if(s){let i=e.slice(s.from,s.to),{complexity:o,cognitiveComplexity:a}=st(n.node,e);r.push({name:i,line:xe(e,n.from),complexity:o,cognitiveComplexity:a})}}else if(n.name==="MethodDecl"){let s=n.node.getChild("FieldName");if(s){let i=e.slice(s.from,s.to),o=pr(n.node,e),a=o?`${o}.${i}`:i,{complexity:c,cognitiveComplexity:l}=st(n.node,e);r.push({name:a,line:xe(e,n.from),complexity:c,cognitiveComplexity:l})}}while(n.next());return r}var Ka=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,Ja=/^\/\/go:build\s+(.+)$/,Va=/^\/\/\s*\+build\s+(.+)$/;function Hn(t,e){let r=[],n=new Map,s=new Set,i=new Set,o=new Map,a=Ha.parse(e),c=a.cursor();do switch(c.name){case"LineComment":{let y=e.slice(c.from,c.to),k=y.match(Ka);k?.[1]&&s.add(k[1]);let D=y.match(Ja);D&&Un(D[1],i);let N=y.match(Va);N&&Un(N[1],i);break}case"ImportSpec":{let y=c.node.getChild("String");if(y){let D=e.slice(y.from,y.to).slice(1,-1);r.push({fromPath:t,toPath:"",rawSpecifier:D,isExternal:!0,isStyle:!1,type:"static"});let N=c.node.getChild("DefName"),j=N?e.slice(N.from,N.to):D.split("/").pop();j&&j!=="_"&&j!=="."&&o.set(j,D)}break}case"FunctionDecl":case"MethodDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let y=c.node.getChild("DefName")??c.node.getChild("FieldName")??c.node.getChild("TypeSpec")?.getChild("DefName")??c.node.getChild("VarSpec")?.getChild("DefName")??c.node.getChild("ConstSpec")?.getChild("DefName");if(y){let k=e.slice(y.from,y.to);k!=="_"&&/^[A-Z]/.test(k)&&!n.has(k)&&n.set(k,{name:k})}break}}while(c.next());let l=r.some(y=>y.rawSpecifier==="testing"),p=Ua.basename(t).endsWith("_test.go")||s.has("test")||l?"test":"logic",u=new Set([...s,...i]),{complexity:d,cognitiveComplexity:h}=st(a.topNode,e),C=$n(a,e),v=p==="test"?[]:Qa(a,e,o);return{imports:r,exports:Array.from(n.values()),tags:Array.from(u).map(y=>({name:y,kind:"comment-marker"})),category:p,rawCallEdges:v,complexity:d,cognitiveComplexity:h,...C.length>0?{functions:C}:{}}}function Qa(t,e,r){let n=[];function s(o,a){if(o.type.name==="CallExpr"){let l=o.firstChild;if(l?.type.name==="SelectorExpr"){let p=l.firstChild,u=l.getChild("FieldName");if(p?.type.name==="VariableName"&&u){let d=e.slice(p.from,p.to),h=r.get(d);if(h){let C=e.slice(u.from,u.to);n.push({from:a,to:C,toSpecifier:h})}}}}let c=o.firstChild;for(;c;)s(c,a),c=c.nextSibling}let i=t.cursor();do if(i.name==="FunctionDecl"){let o=i.node.getChild("DefName"),a=i.node.getChild("Block");if(o&&a){let c=e.slice(o.from,o.to);/^[A-Z]/.test(c)&&s(a,c)}}else if(i.name==="MethodDecl"){let o=i.node.getChild("FieldName"),a=i.node.getChild("Block");if(o&&a){let c=e.slice(o.from,o.to),l=pr(i.node,e);s(a,l?`${l}.${c}`:c)}}while(i.next());return n}function Un(t,e){for(let r of t.split(/[\s,&|!()]+/)){let n=r.trim();n&&n!=="ignore"&&e.add(n)}}import qa from"livescript";function K(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function Ya(t){if(!t)return[];if(t.constructor?.name==="Class"){let r=K(t.title);return r?[{name:r}]:[]}if(t.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(r=>K(r.key)??K(r.val)).filter(r=>!!r).map(r=>({name:r}));let e=K(t);return e?[{name:e}]:[]}function Xa(t){let e=t.constructor?.name||t.type;if(e==="Assign"&&t.left?.constructor?.name==="Chain"){let r=t.left,n=K(r.head),i=r.tails?.[0]?.key?.name;if(n==="module"&&i==="exports")return Ya(t.right);if(n==="exports"&&typeof i=="string")return[{name:i}];if(r.head?.verb==="out"&&typeof i=="string")return[{name:i}]}if(e==="Import"&&t.left?.verb==="out"){let r=t.right;if(r?.constructor?.name==="Obj"&&Array.isArray(r.items))return r.items.map(n=>K(n.val)??K(n.key)).filter(n=>!!n).map(n=>({name:n}))}return[]}var Za=new Set(["first_line","first_column","last_line","last_column","line","column"]);function ec(t,e){let r=t.constructor?.name||t.type;if(r==="Import"){let n=t.right?.value;if(typeof n=="string"){let s=O(n);return{fromPath:e,toPath:"",rawSpecifier:s,isStyle:P(s),type:"static"}}}if(r==="Chain"&&t.head?.value==="require"){let n=t.tails?.[0];if(n?.constructor?.name==="Call"||n?.type==="Call"){let s=n.args?.[0]?.value;if(typeof s=="string"){let i=O(s);return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:P(i),type:"require"}}}}return null}function ur(t,e,r){if(!t||typeof t!="object")return[];let n=[],s=ec(t,e);s&&n.push(s),r.push(...Xa(t));for(let i in t){if(Za.has(i))continue;let o=t[i];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let a of o)n.push(...ur(a,e,r));else n.push(...ur(o,e,r))}return n}function Kn(t,e){let r=ee(e),n=te(t,r),s=[],i=[];try{s=ur(qa.ast(e),t,i)}catch{}let o=new Set,a=i.filter(c=>o.has(c.name)?!1:(o.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(r).map(c=>({name:c,kind:"comment-marker"})),category:n}}import tc from"luaparse";function rc(t,e){let r=[];function n(s){if(!(!s||typeof s!="object")){if((s.type==="CallExpression"||s.type==="StringCallExpression")&&s.base?.type==="Identifier"&&s.base?.name==="require"){let i;if(s.type==="CallExpression"){let o=s.arguments?.[0];o?.type==="StringLiteral"&&(i=O(o.raw))}else if(s.type==="StringCallExpression"){let o=s.argument;o?.type==="StringLiteral"&&(i=O(o.raw))}i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:P(i),type:"require"})}for(let i in s){if(i==="loc")continue;let o=s[i];if(o&&typeof o=="object")if(Array.isArray(o))for(let a of o)n(a);else n(o)}}}return n(t),r}function nc(t){let e=new Set;for(let r of t)r.type==="LocalStatement"&&r.variables.forEach((n,s)=>{r.init[s]?.type==="TableConstructorExpression"&&e.add(n.name)});return e}function sc(t){let e=t[t.length-1];if(e?.type!=="ReturnStatement")return[];let r=e.arguments[0];if(r?.type!=="TableConstructorExpression")return[];let n=[];for(let s of r.fields)s.type==="TableKeyString"&&n.push({name:s.key.name});return n}function ic(t){let e=t.body,r=nc(e),n=sc(e);for(let i of e)if(i.type==="FunctionDeclaration")i.identifier?.type==="MemberExpression"?i.identifier.base.type==="Identifier"&&r.has(i.identifier.base.name)&&n.push({name:i.identifier.identifier.name}):i.identifier?.type==="Identifier"&&!i.isLocal&&n.push({name:i.identifier.name});else if(i.type==="AssignmentStatement")for(let o of i.variables)o.type==="MemberExpression"&&o.base.type==="Identifier"&&r.has(o.base.name)&&n.push({name:o.identifier.name});let s=new Set;return n.filter(i=>s.has(i.name)?!1:(s.add(i.name),!0))}function Jn(t,e){let r=ee(e),n=te(t,r),s=[],i=[];try{let o=tc.parse(e);s=rc(o,t),i=ic(o)}catch{}return{imports:s,exports:i,tags:Array.from(r).map(o=>({name:o,kind:"comment-marker"})),category:n}}var oc=["http://","https://","mailto:","//"],ac="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",cc=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${ac})\\b`,"g"),Vn;async function lc(){return Vn??=(async()=>{let{unified:t}=await import("unified"),e=(await import("remark-parse")).default;return t().use(e)})(),Vn}function pc(t){let e=t.trim();return e.length===0||e.startsWith("#")||oc.some(r=>e.startsWith(r))}function uc(t,e){let r=t.match(cc);return r?r.map(n=>({fromPath:e,toPath:"",rawSpecifier:n,isStyle:!1,type:"static"})):[]}function Qn(t,e,r){if(t.type==="link"&&typeof t.url=="string"&&!pc(t.url)&&r.push({fromPath:e,toPath:"",rawSpecifier:t.url,isStyle:!1,type:"static"}),(t.type==="code"||t.type==="inlineCode")&&typeof t.value=="string"&&r.push(...uc(t.value,e)),Array.isArray(t.children))for(let n of t.children)Qn(n,e,r)}async function qn(t,e){let n=(await lc()).parse(e),s=[];Qn(n,t,s);let i=new Set;return{imports:s.filter(a=>i.has(a.rawSpecifier)?!1:(i.add(a.rawSpecifier),!0)),exports:[],tags:[],category:"other"}}import yc from"path";import{parser as xc}from"@lezer/python";function fc(t){let e=1;function r(n){switch(n.type.name){case"IfStatement":{e+=H(n).filter(i=>i.type.name==="if"||i.type.name==="elif").length;break}case"TryStatement":{e+=H(n).filter(i=>i.type.name==="except").length;break}case"ForStatement":case"WhileStatement":case"ConditionalExpression":e++;break;case"and":case"or":e++;break}let s=n.firstChild;for(;s;)r(s),s=s.nextSibling}return r(t),e}function mc(t,e){let r=0,n=H(t),s=0,i=0;for(;i<n.length;){let o=n[i];if(o?.type.name==="if"||o?.type.name==="elif"){let a=s>0;r+=a?1:1+e;let c=a?e:e+1,l=n[i+1],p=n[i+2];l&&(r+=R(l,c)),p&&(r+=R(p,c)),s++,i+=3}else if(o?.type.name==="else"){r+=1;let a=n[i+1];a&&(r+=R(a,e+1)),i+=2}else i++}return r}function gc(t,e){let r=0,n=H(t),s=0;for(;s<n.length;){let i=n[s];if(i?.type.name==="except"){for(r+=1+e,s++;s<n.length&&n[s]?.type.name!=="Body";)r+=R(n[s],e),s++;s<n.length&&(r+=R(n[s],e),s++)}else i?.type.name==="Body"&&(r+=R(i,e)),s++}return r}function Yn(t,e){let r=1+e,n=t.firstChild;for(;n;)r+=R(n,e+1),n=n.nextSibling;return r}function dc(t,e){let r=0,n=t.firstChild;for(;n;)r+=R(n,e),n=n.nextSibling;return r}function R(t,e){let r=t.type.name;if(r==="IfStatement")return mc(t,e);if(r==="TryStatement")return gc(t,e);if(r==="ForStatement"||r==="WhileStatement")return Yn(t,e);let n=r==="ConditionalExpression"||r==="and"||r==="or"?1:0;return e>0&&(r==="FunctionDefinition"||r==="LambdaExpression")?n+Yn(t,e):n+dc(t,e)}function hc(t){return R(t,0)}function fr(t){return{complexity:fc(t),cognitiveComplexity:hc(t)}}function Xn(t,e){let r=[];function n(o,a){let{complexity:c,cognitiveComplexity:l}=fr(o);r.push({name:a,line:xe(e,o.from),complexity:c,cognitiveComplexity:l})}function s(o){let a=o.firstChild;for(;a;)i(a),a=a.nextSibling}function i(o){if(o.type.name==="ClassDefinition"){let a=o.getChild("VariableName"),c=a?e.slice(a.from,a.to):void 0,l=o.getChild("Body");if(l){let p=l.firstChild;for(;p;){if(p.type.name==="FunctionDefinition"){let u=p.getChild("VariableName"),d=u?e.slice(u.from,u.to):void 0;d&&n(p,c?`${c}.${d}`:d),s(p)}else i(p);p=p.nextSibling}}return}if(o.type.name==="FunctionDefinition"){let a=o.getChild("VariableName");a&&n(o,e.slice(a.from,a.to)),s(o);return}s(o)}return i(t.topNode),r}var bc=new Set(["pytest","unittest","nose","hypothesis"]);function Zn(t,e){let r=[],n=[],s=new Set,i=yc.basename(t).toLowerCase(),o=xc.parse(e),a=o.cursor();do switch(a.name){case"Comment":{let h=e.slice(a.from,a.to).match(/#\s*@tag\s+([a-zA-Z0-9_-]+)/);h?.[1]&&s.add(h[1]);break}case"ImportStatement":{for(let h of Sc(a.node,e,t))r.push(h);break}case"FunctionDefinition":case"ClassDefinition":{let h=a.node.parent;if(h?.name==="Script"||h?.name==="DecoratedStatement"&&h.parent?.name==="Script"){let v=a.node.getChild("VariableName");v&&n.push({name:e.slice(v.from,v.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let h=a.node.firstChild;h?.name==="VariableName"&&n.push({name:e.slice(h.from,h.to)})}break}}while(a.next());let c=Tc(i,r,s);c==="test"&&s.add("test");let{complexity:l,cognitiveComplexity:p}=fr(o.topNode),u=Xn(o,e),d=c==="test"?[]:Fc(o,e);return{imports:r,exports:n,tags:Array.from(s).map(h=>({name:h,kind:"comment-marker"})),category:c,rawCallEdges:d,complexity:l,cognitiveComplexity:p,...u.length>0?{functions:u}:{}}}function Sc(t,e,r){let n=t.firstChild;return n?n.name==="from"?kc(t,e,r):Cc(t,e,r):[]}function kc(t,e,r){let n=t.firstChild;if(!n)return[];let s=n.nextSibling;for(;s&&s.name!=="import";)s=s.nextSibling;if(!s)return[];let i=e.slice(n.to,s.from).trim(),o=vc(s.nextSibling,e);if(!o.length)return[];let a=0;for(;a<i.length&&i[a]===".";)a++;let c=i.slice(a);if(a===0)return[be(r,i,o,!0)];let l=a===1?"./":"../".repeat(a-1);return c?[be(r,l+c.replace(/\./g,"/"),o,!1)]:o[0]==="*"?[be(r,l.slice(0,-1),["*"],!1)]:o.map(p=>be(r,l+p,[p],!1))}function Cc(t,e,r){let n=[],s=t.firstChild?.nextSibling??null;for(;s;){if(s.name==="VariableName"){let i=e.slice(s.from,s.to);for(;s.nextSibling?.name==="."&&s.nextSibling.nextSibling?.name==="VariableName";)s=s.nextSibling.nextSibling,i+=`.${e.slice(s.from,s.to)}`;s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling),n.push(be(r,i,["*"],!0))}s=s.nextSibling}return n}function vc(t,e){let r=[],n=t;for(;n;)n.name==="*"?r.push("*"):n.name==="VariableName"&&(r.push(e.slice(n.from,n.to)),n.nextSibling?.name==="as"&&(n=n.nextSibling.nextSibling??n.nextSibling)),n=n.nextSibling;return r}function wc(t,e){let r=new Map,n=t.cursor();do{if(n.name!=="ImportStatement")continue;let i=n.node.firstChild;if(i?.type.name!=="from")continue;let o=i.nextSibling;for(;o&&o.type.name!=="import";)o=o.nextSibling;if(!o)continue;let a=e.slice(i.to,o.from).trim(),c=0;for(;c<a.length&&a[c]===".";)c++;let l=a.slice(c),p=c<=1?"./":"../".repeat(c-1),u=o.nextSibling;for(;u;){if(u.type.name==="VariableName"){let d=e.slice(u.from,u.to),h=d;if(u.nextSibling?.type.name==="as"){let v=u.nextSibling.nextSibling;v?.type.name==="VariableName"&&(h=e.slice(v.from,v.to),u=v)}let C=c===0?a:l?p+l.replace(/\./g,"/"):p+d;r.set(h,C)}u=u.nextSibling}}while(n.next());return r}function Fc(t,e){let r=wc(t,e),n=[];function s(a,c){if(a.type.name==="CallExpression"&&a.firstChild?.type.name==="VariableName"){let p=a.firstChild,u=e.slice(p.from,p.to),d=r.get(u);d&&n.push({from:c,to:u,toSpecifier:d})}let l=a.firstChild;for(;l;)s(l,c),l=l.nextSibling}function i(a){let c=a.firstChild;for(;c;)o(c),c=c.nextSibling}function o(a){if(a.type.name==="ClassDefinition"){let c=a.getChild("VariableName"),l=c?e.slice(c.from,c.to):void 0,p=a.getChild("Body");if(p){let u=p.firstChild;for(;u;){if(u.type.name==="FunctionDefinition"){let d=u.getChild("VariableName"),h=d?e.slice(d.from,d.to):void 0;h&&s(u,l?`${l}.${h}`:h)}else o(u);u=u.nextSibling}}return}if(a.type.name==="FunctionDefinition"){let c=a.getChild("VariableName");c&&s(a,e.slice(c.from,c.to));return}i(a)}return o(t.topNode),n}function be(t,e,r,n){return{fromPath:t,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:n,type:"static",symbols:r.length>0?r:void 0}}function Tc(t,e,r){return t.startsWith("test_")||t.endsWith("_test.py")?"test":t==="conftest.py"||t==="setup.py"?"config":r.has("test")||e.some(n=>bc.has(n.rawSpecifier))?"test":"logic"}import ns from"path";import g from"typescript";import b from"typescript";function Ec(t){let e=1;function r(n){switch(n.kind){case b.SyntaxKind.IfStatement:case b.SyntaxKind.ConditionalExpression:case b.SyntaxKind.ForStatement:case b.SyntaxKind.ForInStatement:case b.SyntaxKind.ForOfStatement:case b.SyntaxKind.WhileStatement:case b.SyntaxKind.DoStatement:case b.SyntaxKind.CatchClause:case b.SyntaxKind.CaseClause:e++;break;case b.SyntaxKind.BinaryExpression:{let s=n.operatorToken.kind;(s===b.SyntaxKind.AmpersandAmpersandToken||s===b.SyntaxKind.BarBarToken||s===b.SyntaxKind.QuestionQuestionToken)&&e++;break}}b.forEachChild(n,r)}return r(t),e}function ts(t,e,r){let n=r?1:1+e,s=r?e:e+1;return n+=J(t.expression,s,!1),n+=J(t.thenStatement,s,!1),t.elseStatement&&(b.isIfStatement(t.elseStatement)?n+=ts(t.elseStatement,e,!0):n+=1+J(t.elseStatement,e+1,!1)),n}function es(t,e){let r=1+e;return b.forEachChild(t,n=>{r+=J(n,e+1,!1)}),r}function Ac(t,e){let r=1+e;return b.forEachChild(t,n=>{r+=J(n,e,!1)}),r}function Pc(t,e){let r=0;return b.forEachChild(t,n=>{r+=J(n,e,!1)}),r}function Nc(t){let e=t.operatorToken.kind;return e===b.SyntaxKind.AmpersandAmpersandToken||e===b.SyntaxKind.BarBarToken||e===b.SyntaxKind.QuestionQuestionToken}function J(t,e,r){if(b.isIfStatement(t))return ts(t,e,r);if(b.isForStatement(t)||b.isForInStatement(t)||b.isForOfStatement(t)||b.isWhileStatement(t)||b.isDoStatement(t)||b.isSwitchStatement(t))return es(t,e);if(b.isCatchClause(t))return Ac(t,e);let n=0;return b.isConditionalExpression(t)&&(n+=1),b.isBinaryExpression(t)&&Nc(t)&&(n+=1),e>0&&(b.isFunctionDeclaration(t)||b.isFunctionExpression(t)||b.isArrowFunction(t))?n+es(t,e):n+Pc(t,e)}function Ic(t){return J(t,0,!1)}function mr(t){return{complexity:Ec(t),cognitiveComplexity:Ic(t)}}import w from"typescript";var gr=new Set(["test","describe","it"]);function rs(t,e){Dc(t,e),Rc(t,e),Lc(t,e),Gc(t,e)}function Dc(t,e){if((w.isFunctionDeclaration(t)||w.isVariableDeclaration(t))&&t.name&&w.isIdentifier(t.name)&&Mc(t)){let r;if(w.isFunctionDeclaration(t))r="function";else{let n=t.initializer;r=n&&(w.isArrowFunction(n)||w.isFunctionExpression(n))?"function":"variable"}e.tags.add({name:t.name.text,kind:r})}}function Mc(t){if(w.isFunctionDeclaration(t))return w.isSourceFile(t.parent);let e=t.parent?.parent;return!!e&&w.isSourceFile(e.parent)}function Rc(t,e){if(!w.isStringLiteral(t))return;let r=t.text.match(/@[\w-]+/g);if(r)for(let n of r)e.tags.add({name:n.substring(1),kind:"comment-marker"})}function Lc(t,e){if(!w.isSourceFile(t))return;let r=/@tag\s+([a-zA-Z0-9_-]+)/g,n=t.getFullText(),s=r.exec(n);for(;s!==null;)s[1]&&e.tags.add({name:s[1],kind:"comment-marker"}),s=r.exec(n)}function Gc(t,e){if(w.isCallExpression(t)&&_c(t.expression))for(let r of t.arguments)w.isObjectLiteralExpression(r)&&Oc(r,e)}function _c(t){return w.isIdentifier(t)?gr.has(t.text):!!(w.isPropertyAccessExpression(t)&&(gr.has(t.name.text)||w.isIdentifier(t.expression)&&gr.has(t.expression.text)))}function Oc(t,e){for(let r of t.properties){if(!w.isPropertyAssignment(r)||!w.isIdentifier(r.name)||r.name.text!=="tags"&&r.name.text!=="tag")continue;let{initializer:n}=r,s=w.isArrayLiteralExpression(n)?n.elements.filter(w.isStringLiteral):r.name.text==="tag"&&w.isStringLiteral(n)?[n]:[];for(let i of s)e.tags.add({name:i.text.replace(/^@/,""),kind:"comment-marker"})}}function dr(t,e,r){let n=[],s=new Map,i=new Set,o=g.createSourceFile(t,e,g.ScriptTarget.Latest,!0,r==="typescript"?g.ScriptKind.TSX:g.ScriptKind.JSX),a={filePath:t,imports:n,exports:s,tags:i,rawCallEdges:[],sourceFile:o,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=v=>{Bc(v,a),g.forEachChild(v,c)};c(o);let l=Zc(t,a);(l==="test"||l==="barrel")&&i.add({name:l,kind:"comment-marker"}),l!=="test"&&el(a,o);let p=o.statements[0],u=p?is(p):void 0,{complexity:d,cognitiveComplexity:h}=mr(o),C=jc(o);return{imports:n,exports:Array.from(s.values()),tags:Array.from(i),category:l,rawCallEdges:a.rawCallEdges??[],complexity:d,cognitiveComplexity:h,...C.length>0?{functions:C}:{},...u!==void 0?{description:u}:{}}}function jc(t){let e=[],r=(s,i)=>{let{complexity:o,cognitiveComplexity:a}=mr(i),c=t.getLineAndCharacterOfPosition(i.getStart(t)).line+1;e.push({name:s,line:c,complexity:o,cognitiveComplexity:a})},n=(s,i)=>{if(g.isFunctionDeclaration(s)&&s.name&&s.body?r(s.name.text,s):g.isVariableDeclaration(s)&&g.isIdentifier(s.name)&&s.initializer&&(g.isArrowFunction(s.initializer)||g.isFunctionExpression(s.initializer))?r(s.name.text,s.initializer):i&&g.isMethodDeclaration(s)&&g.isIdentifier(s.name)&&s.body?r(`${i}.${s.name.text}`,s):i&&g.isConstructorDeclaration(s)&&s.body?r(`${i}.constructor`,s):i&&g.isGetAccessorDeclaration(s)&&g.isIdentifier(s.name)&&s.body?r(`${i}.get ${s.name.text}`,s):i&&g.isSetAccessorDeclaration(s)&&g.isIdentifier(s.name)&&s.body&&r(`${i}.set ${s.name.text}`,s),g.isClassDeclaration(s)&&s.name){let o=s.name.text;g.forEachChild(s,a=>n(a,o));return}g.forEachChild(s,o=>n(o,i))};return n(t,void 0),e}function ss(t,e,r,n){let s={name:t},i=is(r);i!==void 0&&(s.doc=i);let o=zc(e);o!==void 0&&(s.flags=o);let a=Wc(e,n);return a!==void 0&&(s.signature=a),s}function is(t){let e=g.getJSDocCommentsAndTags(t);for(let r of e)if(g.isJSDoc(r)&&r.comment)return g.getTextOfJSDocComment(r.comment)||void 0}function zc(t){let e=new Set(["deprecated","internal","public","alpha","beta"]),r=g.getJSDocTags(t).map(n=>n.tagName.text).filter(n=>e.has(n));return r.length>0?r:void 0}function Wc(t,e){let r=g.createPrinter({removeComments:!0}),n=s=>r.printNode(g.EmitHint.Unspecified,s,e);if(g.isFunctionDeclaration(t)||g.isMethodDeclaration(t)){let s=t.parameters.map(n).join(", "),i=t.type?n(t.type):"void";return`${t.typeParameters?`<${t.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${s}) => ${i}`}if(g.isVariableDeclaration(t)){if(t.type)return n(t.type);if(t.initializer&&(g.isArrowFunction(t.initializer)||g.isFunctionExpression(t.initializer))){let s=t.initializer,i=s.parameters.map(n).join(", "),o=s.type?n(s.type):"unknown";return`(${i}) => ${o}`}return}if(g.isClassDeclaration(t)&&t.name)return`class ${t.name.text}`;if(g.isInterfaceDeclaration(t))return`interface ${t.name.text}`;if(g.isTypeAliasDeclaration(t))return n(t.type);if(g.isEnumDeclaration(t))return`enum ${t.name.text}`}function Bc(t,e){$c(t,e),Uc(t,e),Kc(t,e),Jc(t,e),Xc(t,e),rs(t,e)}function $c(t,e){if(!g.isSourceFile(t))return;let r=t.statements.filter(n=>!g.isEmptyStatement(n));e.totalStatements=r.length,e.exportStatements=r.filter(n=>g.isExportDeclaration(n)||g.isExportAssignment(n)||hr(n)).length}function Uc(t,e){if(g.isJsxElement(t)||g.isJsxSelfClosingElement(t)||g.isJsxFragment(t)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(g.isFunctionDeclaration(t)||g.isMethodDeclaration(t)||g.isArrowFunction(t)||g.isClassDeclaration(t)||g.isVariableStatement(t)||g.isEnumDeclaration(t)){e.hasTypesOnly=!1;return}g.isExportDeclaration(t)&&!Hc(t)&&(e.hasTypesOnly=!1)}function Hc(t){return t.isTypeOnly?!0:!t.exportClause||!g.isNamedExports(t.exportClause)?!1:t.exportClause.elements.every(e=>e.isTypeOnly)}function Kc(t,e){if(!g.isImportDeclaration(t)||!t.moduleSpecifier||!g.isStringLiteral(t.moduleSpecifier))return;let r=[];if(t.importClause&&(t.importClause.name&&r.push("default"),t.importClause.namedBindings))if(g.isNamedImports(t.importClause.namedBindings))for(let s of t.importClause.namedBindings.elements)r.push(s.name.text);else g.isNamespaceImport(t.importClause.namedBindings)&&r.push("*");let n=r.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.moduleSpecifier.text,isStyle:P(t.moduleSpecifier.text),type:n,symbols:r.length>0?r:void 0})}function Jc(t,e){g.isExportDeclaration(t)?Vc(t,e):g.isExportAssignment(t)?e.exports.set("default",{name:"default"}):hr(t)&&Yc(t,e)}function Vc(t,e){if(t.moduleSpecifier&&g.isStringLiteral(t.moduleSpecifier))Qc(t,t.moduleSpecifier.text,e);else if(t.exportClause&&g.isNamedExports(t.exportClause))for(let r of t.exportClause.elements){let n=r.name.text;e.exports.set(n,{name:n})}}function Qc(t,e,r){let n=qc(t),s={fromPath:r.filePath,toPath:"",rawSpecifier:e,isStyle:P(e),type:"re-export"};n.length>0&&(s.symbols=n),r.imports.push(s)}function qc(t){return t.exportClause?g.isNamedExports(t.exportClause)?t.exportClause.elements.map(e=>e.name.text):[]:["*"]}function Yc(t,e){if((g.isFunctionDeclaration(t)||g.isClassDeclaration(t)||g.isInterfaceDeclaration(t)||g.isTypeAliasDeclaration(t)||g.isEnumDeclaration(t))&&t.name){let n=t.name.text;e.exports.set(n,ss(n,t,t,e.sourceFile));return}if(g.isVariableStatement(t)){for(let n of t.declarationList.declarations)if(g.isIdentifier(n.name)){let s=n.name.text;e.exports.set(s,ss(s,n,t,e.sourceFile))}}}function Xc(t,e){if(!g.isCallExpression(t))return;let r=t.arguments[0];!r||!g.isStringLiteral(r)||(t.expression.kind===g.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:P(r.text),type:"dynamic"}):g.isIdentifier(t.expression)&&t.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:P(r.text),type:"require"}))}function Zc(t,e){let r=ns.basename(t).toLowerCase(),n=ns.extname(t).toLowerCase();return ie().some(i=>r.includes(i))?"test":Ar(r)?"config":e.imports.some(i=>mt().some(o=>i.rawSpecifier.includes(o)))?"test":n===".tsx"||n===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>ht()?"barrel":"logic"}function hr(t){return g.canHaveModifiers(t)&&g.getModifiers(t)?.some(e=>e.kind===g.SyntaxKind.ExportKeyword)===!0}function el(t,e){let r=t.rawCallEdges??[];t.rawCallEdges=r;let n=new Map;for(let s of e.statements){if(!g.isImportDeclaration(s)||!g.isStringLiteral(s.moduleSpecifier))continue;let i=s.moduleSpecifier.text,o=s.importClause;if(o&&(o.name&&n.set(o.name.text,i),o.namedBindings&&g.isNamedImports(o.namedBindings)))for(let a of o.namedBindings.elements)n.set(a.name.text,i)}if(n.size!==0)for(let s of e.statements){let i=rl(s);if(i){let o=nl(s);o&&it(o,i,n,r);continue}g.isClassDeclaration(s)&&s.name&&tl(s,s.name.text,n,r)}}function tl(t,e,r,n){for(let s of t.members)g.isMethodDeclaration(s)&&s.body&&g.isIdentifier(s.name)?it(s.body,`${e}.${s.name.text}`,r,n):g.isConstructorDeclaration(s)&&s.body&&it(s.body,`${e}.constructor`,r,n)}function rl(t){if(hr(t)){if(g.isFunctionDeclaration(t)&&t.name)return t.name.text;if(g.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(g.isIdentifier(e.name)&&e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer)))return e.name.text}}}function nl(t){if(g.isFunctionDeclaration(t))return t.body;if(g.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer)))return e.initializer}}function it(t,e,r,n){if(g.isCallExpression(t)&&g.isIdentifier(t.expression)){let s=t.expression.text,i=r.get(s);i&&!n.some(o=>o.from===e&&o.to===s&&o.toSpecifier===i)&&n.push({from:e,to:s,toSpecifier:i})}g.forEachChild(t,s=>it(s,e,r,n))}function ot(t,e){if(e.length===0)return"ui";let r=!1;return t.walk(n=>{if(n.type==="rule")return r=!0,!1}),r?"ui":"barrel"}function os(t,e){let r=[],n=/@require\s+['"]([^'"]+)['"]/g,s=n.exec(t);for(;s!==null;){let o=s[1];o&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"require"}),s=n.exec(t)}let i=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(s=i.exec(t);s!==null;){let o=s[1];o&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),s=i.exec(t)}return r}function as(t,e){if(e.length===0)return"ui";try{let r=lt("stylus");return new r.Parser(t).parse().nodes.some(i=>i.constructor.name!=="Import")?"ui":"barrel"}catch{return t.replace(/^\s*@?(?:require|import)\b.*/gm,"").trim().length>0?"ui":"barrel"}}function Se(t,e){let r=_(t);if(r==="stylus"){let i=os(e,t);return{imports:i,exports:[],tags:[],category:as(e,i)}}if(r==="scss"){let{imports:i,root:o,exports:a,tags:c}=Oe(e,t);return{imports:i,exports:a,tags:c,category:ot(o,i)}}if(r==="less"){let{imports:i,root:o,exports:a,tags:c}=_e(e,t);return{imports:i,exports:a,tags:c,category:ot(o,i)}}let{imports:n,root:s}=Ge(e,t);return{imports:n,exports:[],tags:[],category:ot(s,n)}}for(let[t,e]of[["javascript",(r,n)=>dr(r,n,"javascript")],["typescript",(r,n)=>dr(r,n,"typescript")],["css",Se],["scss",Se],["less",Se],["stylus",Se],["coffeescript",zn],["livescript",Kn],["lua",Jn],["python",Zn],["go",Hn],["gherkin",lr],["markdown",qn]])Z(t,e);async function cs(t,e){let r=_(t),n=Cn(r);return n?n(t,e):{imports:[],exports:[],tags:[],category:"other"}}import ls from"path";function sl(t,e){let r=e.get(t.path);r!==void 0&&(t.coveragePct=r)}function us(t,e){for(let r of t)if(r.isExternal){let n=r.rawSpecifier.startsWith("@")?r.rawSpecifier.split("/").slice(0,2).join("/"):r.rawSpecifier.split("/")[0];n&&!e.some(s=>s.name===n)&&e.push({name:n,kind:"library"})}}function il(t,e,r){if(e.isExternal||!e.toPath)return;let n=r.get(e.toPath);n&&(n.category!=="logic"&&n.category!=="barrel"||(n.testedBy??=[],n.testedBy.includes(t.path)||n.testedBy.push(t.path)))}function ol(t,e){if(t.type==="markdown")for(let r of t.imports){if(r.isExternal||!r.toPath)continue;let n=e.get(r.toPath);!n||n===t||(n.documentedBy??=[],n.documentedBy.includes(t.path)||n.documentedBy.push(t.path),n.category==="logic"&&(n.lastCommitAt??0)>(t.lastCommitAt??0)&&(t.staleFor??=[],t.staleFor.includes(n.path)||t.staleFor.push(n.path)))}}function ps(t){return Math.round(t*1e4)/1e4}function al(t,e){let r=[];for(let n of t.imports){if(n.isExternal||!n.toPath)continue;let s=e.get(n.toPath);if(!s||s.exports.length===0)continue;let i;if(n.symbols===void 0){if(n.type==="side-effect")continue;i=1}else n.symbols.includes("*")?i=1:i=n.symbols.length/s.exports.length;n.exportUsageRatio=ps(Math.min(1,i)),r.push(n.exportUsageRatio)}r.length>0&&(t.avgExportUsage=ps(r.reduce((n,s)=>n+s,0)/r.length),t.maxExportUsage=Math.max(...r))}function yr(t,e,r){e&&(t.some(n=>n.name===e&&n.kind===r)||t.push({name:e,kind:r}))}function cl(t,e){let r=e.toPath,n=ls.basename(r,ls.extname(r)).replace(/\.(test|spec)$/,"");yr(t.tags,n,"import")}function ll(t,e){if(!(!e.symbols||e.symbols.includes("*")))for(let r of e.symbols)yr(t.tags,r,"import")}function pl(t,e,r){let n=r.get(e.toPath);if(!(!n||n.category==="test"))for(let s of n.tags)s.kind==="comment-marker"&&yr(t.tags,s.name,"comment-marker")}function ul(t,e,r){!e.toPath||e.isExternal||(cl(t,e),ll(t,e),pl(t,e,r))}function fs(t,e){for(let r of t.values())delete r.testedBy,delete r.documentedBy,delete r.staleFor,r.category==="test"&&(r.tags=r.tags.filter(n=>n.kind!=="import"));for(let r of t.values()){if(al(r,t),e.size>0&&sl(r,e),r.category==="test")for(let n of r.imports)il(r,n,t),ul(r,n,t);ol(r,t)}}import at from"fs";import L from"path";import ds from"fs";import ne from"path";var ke=class{extensions=[".go"];goModCache=new Map;resolve(e,r,n,s){let{mod:i,replaces:o}=this.readGoMod(n);if(!i)return null;let a=this.applyReplace(r,o,n);if(a!==void 0)return gs(a);if(r!==i&&!r.startsWith(`${i}/`))return null;let c=r.slice(i.length).replace(/^\//,"");return c?gs(ne.join(n,c)):null}readGoMod(e){let r=this.goModCache.get(e);if(r!==void 0)return r;let n={mod:null,replaces:new Map};try{let s=ds.readFileSync(ne.join(e,"go.mod"),"utf-8"),i=fl(s,e);return this.goModCache.set(e,i),i}catch{return this.goModCache.set(e,n),n}}applyReplace(e,r,n){for(let[s,i]of r){if(e===s)return i;if(e.startsWith(`${s}/`)){let o=e.slice(s.length+1);return ne.join(i,o)}}}};function fl(t,e){let r=t.split(`
|
|
31
|
-
`),n=null,s=new Map,i=!1;for(let o of r){let a=o.trim();if(a.startsWith("module ")){n=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){i=!0;continue}if(i&&a===")"){i=!1;continue}if(i&&a.includes("=>")){ms(a,e,s);continue}!i&&/^replace\s+/.test(a)&&a.includes("=>")&&ms(a.replace(/^replace\s+/,""),e,s)}return{mod:n,replaces:s}}function ms(t,e,r){let[n,s]=t.split("=>").map(a=>a.trim());if(!n||!s)return;let i=n.split(/\s+/)[0];if(!s.startsWith(".")&&!s.startsWith("/"))return;let o=ne.isAbsolute(s)?s:ne.resolve(e,s);r.set(i,o)}function gs(t){let e;try{e=ds.readdirSync(t,{withFileTypes:!0})}catch{return null}let r=e.filter(n=>n.isFile()&&n.name.endsWith(".go")&&!n.name.endsWith("_test.go")).map(n=>({path:ne.join(t,n.name),isExternal:!1})).sort((n,s)=>n.path.localeCompare(s.path));return r.length>0?r:null}import ml from"fs";import xr from"path";var Ce=class{extensions=[".lua"];resolve(e,r,n,s){let i=r.replace(/\./g,xr.sep),o=[n,xr.join(n,"lib")];for(let a of o){if(!ml.existsSync(a))continue;let c=s(xr.join(a,"_dummy.lua"),i);if(c)return[c]}return null}};import gl from"path";var ve=class{extensions=[".md",".mdx"];resolve(e,r,n,s){let i=s(gl.join(n,"_dummy"),`./${r}`);return i?[i]:null}};import dl from"fs";import br from"path";var we=class{extensions=[".py"];resolve(e,r,n,s){let i=r.replace(/\./g,br.sep),o=br.join(n,`${i}.py`);if(hs(o))return[{path:o,isExternal:!1}];let a=br.join(n,i,"__init__.py");return hs(a)?[{path:a,isExternal:!1}]:null}};function hs(t){try{return dl.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}import ys from"path";var hl=["~","http://","https://","//","data:","sass:"],Fe=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,r,n,s){if(hl.some(p=>r.startsWith(p)))return null;let i=s(e,r);if(i)return[i];let o=ys.dirname(r),a=ys.basename(r),c=o==="."?`_${a}`:`${o}/_${a}`,l=s(e,c);return l?[l]:null}};var V=class{constructor(e,r={}){this.rootDir=e;this.workspaceMap=r.workspaceMap??new Map,this.tsconfigSearchPaths=r.tsconfigSearchPaths??[e],this.pathAliases=r.pathAliases,this.langResolvers=r.langResolvers??[new we,new Ce,new ke,new Fe,new ve]}rootDir;workspaceMap;tsconfigSearchPaths;pathAliases;langResolvers;resolutionCache=new Map;langBucketFor(e){for(let r=0;r<this.langResolvers.length;r++)if(this.langResolvers[r]?.extensions.some(n=>e.endsWith(n)))return String(r);return"none"}cacheKey(e,r){return`${L.dirname(e)}\0${this.langBucketFor(e)}\0${r}`}resolveAll(e,r){let n=this.cacheKey(e,r),s=this.resolutionCache.get(n);if(s!==void 0)return s??[];let i=this.resolveAllUncached(e,r);return this.resolutionCache.set(n,i.length>0?i:null),i}resolveAllUncached(e,r){let n=this.resolvePathAlias(r);if(n)return[n];if(r.startsWith(".")||r.startsWith("/")){let o=this.resolveLocalPath(e,r);return o?[o]:[]}let s=(o,a)=>this.resolveLocalPath(o,a);for(let o of this.langResolvers)if(o.extensions.some(a=>e.endsWith(a))){let a=o.resolve(e,r,this.rootDir,s);if(a)return a}let i=this.resolveWorkspaceImport(r);return i?[i]:[{path:r,isExternal:!0}]}resolve(e,r){return this.resolveAll(e,r)[0]??null}resolveLocalPath(e,r){let n=L.dirname(e),s=r.startsWith("/")?r:L.resolve(n,r),i=!s.startsWith(this.rootDir),o=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature",".md",".mdx"],a=s.match(/\.(js|mjs|cjs)$/);if(a){let c=s.slice(0,-a[0].length);for(let l of[".ts",".tsx"]){let p=this.tryExtensions(c,l,i);if(p)return p}}for(let c of o){let l=this.tryExtensions(s,c,i);if(l)return l}return i?{path:s,isExternal:!0}:null}tryExtensions(e,r,n){let s=e+r;if(this.isFile(s))return{path:s,isExternal:n};let i=L.join(e,`index${r}`);if(this.isFile(i))return{path:i,isExternal:n};if(r===".py"){let o=L.join(e,"__init__.py");if(this.isFile(o))return{path:o,isExternal:n}}return null}isFile(e){try{return at.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){if(this.pathAliases)for(let r in this.pathAliases){let n=this.matchAliasPattern(r,e),s=this.pathAliases[r];if(n&&s){let i=this.tryAliasSubstitutions(s,n[1]||"");if(i)return i}}for(let r of this.tsconfigSearchPaths){let n=L.join(r,"tsconfig.json");if(at.existsSync(n))try{let i=JSON.parse(at.readFileSync(n,"utf-8")).compilerOptions?.paths;if(!i)continue;for(let o in i){let a=this.matchAliasPattern(o,e);if(a){let c=this.tryAliasSubstitutions(i[o],a[1]||"",r);if(c)return c}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,r){let n=this.aliasRegexCache.get(e);if(!n){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");n=new RegExp(`^${s}$`),this.aliasRegexCache.set(e,n)}return r.match(n)}tryAliasSubstitutions(e,r,n=this.rootDir){let s=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let i of e){let o=i.replace("*",r),a=L.resolve(n,o);for(let c of s){let l=this.tryExtensions(a,c,!1);if(l)return l}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[r,n]of this.workspaceMap){if(e!==r&&!e.startsWith(`${r}/`))continue;let s=e.slice(r.length),i={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:r};if(!s){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let c=L.join(n,a);try{if(at.statSync(c,{throwIfNoEntry:!1})?.isFile())return{...i,path:c}}catch{}}return{...i,path:n}}let o=this.resolveLocalPath(L.join(n,"_dummy"),s.slice(1));return o?{...i,path:o.path}:null}return null}};var xl=["tests","test","__tests__","specs","spec"],xs=new Set(["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"]),bl=600;function Sl(t,e){if(t.length===0)return e;let r=t.map(o=>E.dirname(o).split(E.sep)),n=r[0]??[];for(let o of r.slice(1)){let a=0;for(;a<n.length&&a<o.length&&n[a]===o[a];)a++;n=n.slice(0,a)}let s=n.join(E.sep)||E.sep,i=E.relative(e,s);return i.startsWith("..")||E.isAbsolute(i)?e:s}var Ee=class{constructor(e,r=null,n,s,i=!1,o=new Map,a=!0){this.rootDir=e;this.enableGitStats=i;this.coverageMap=o;this.parallelParsing=a;this.previousGraph=r,this.resolver=n||new V(e),this.lockFile=jr(e),s&&(this.progressCallback=s)}rootDir;enableGitStats;coverageMap;parallelParsing;graph={nodes:new Map};visited=new Set;queue=[];previousGraph=null;resolver;lockFile=null;progressCallback;pool=null;gitStatsMap=null;async build(e){let r=e.map(n=>E.isAbsolute(n)?n:E.resolve(this.rootDir,n));await this.initPool(),this.enableGitStats&&(this.gitStatsMap=Gn(this.rootDir));try{for(let n of r)this.enqueue(n);return await this.drain(),await this.processTestFiles(Sl(r,this.rootDir)),await this.processDocFiles(),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
|
|
32
|
-
Done. Total processed: ${this.visited.size} nodes.
|
|
33
|
-
`),fs(this.graph.nodes,this.coverageMap),new I(this.graph.nodes)}finally{this.pool&&(await this.pool.destroy(),this.pool=null)}}async initPool(){if(this.parallelParsing===!1)return;let e=typeof this.parallelParsing=="object"?this.parallelParsing:{},r=e.minFiles??bl;if(!(r>0&&!this.hasAtLeastFiles(this.rootDir,r))){e.maxThreads!==void 0&&e.maxThreads<1&&process.stderr.write(`
|
|
34
|
-
Warning: parallelParsing.maxThreads (${e.maxThreads}) must be at least 1; using 1.
|
|
35
|
-
`);try{let n=E.join(f,"parse-worker.js");this.pool=new yl({filename:n,...e.maxThreads!==void 0?{maxThreads:Math.max(1,e.maxThreads)}:{}})}catch(n){process.stderr.write(`
|
|
36
|
-
Warning: failed to start parse worker pool, falling back to synchronous parsing: ${n}
|
|
37
|
-
`),this.pool=null}}}hasAtLeastFiles(e,r){let n=0,s=[e];for(;s.length>0;){let i=s.pop();if(i===void 0)continue;let o;try{o=Te.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o)if(a.isDirectory())xs.has(a.name)||s.push(E.join(i,a.name));else if(a.isFile()&&(n++,n>=r))return!0}return n>=r}async processTestFiles(e){let r=ie(),n=i=>r.some(o=>i.name.includes(o));this.walkProject(e,n);let s=e;for(;s!==this.rootDir;){let i=E.dirname(s);if(i===s)break;for(let o of xl){let a=E.join(i,o);try{Te.statSync(a).isDirectory()&&this.walkProject(a,n)}catch{}}s=i}await this.drain()}async processDocFiles(){this.walkProject(this.rootDir,e=>e.name.endsWith(".md")||e.name.endsWith(".mdx")),await this.drain()}walkProject(e,r){let n;try{n=Te.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of n){let i=E.join(e,s.name);s.isDirectory()?xs.has(s.name)||this.walkProject(i,r):s.isFile()&&r(s)&&this.enqueue(i)}}enqueue(e){this.visited.has(e)||(this.visited.add(e),this.showProgress(),this.queue.push(e))}async drain(){for(;this.queue.length>0;){let e=this.queue;this.queue=[],await Promise.all(e.map(r=>this.finishFile(r)))}}async finishFile(e){let r=Te.statSync(e,{throwIfNoEntry:!1});if(!r?.isFile())return;let n=E.relative(this.rootDir,e),s=await this.getNode(e,n,r);s.imports=await this.resolveImports(e,s.imports),us(s.imports,s.tags),this.graph.nodes.set(s.path,s)}async getNode(e,r,n){let s=this.previousGraph?.nodes.get(r);if(s&&s.mtime===n.mtimeMs&&s.size===n.size)return{...s};let i=await this.tryParse(e,r);if(!i)return this.makeStubNode(e,r,n);let o=this.resolveCallEdges(e,i.rawCallEdges),a=this.buildNode(e,r,n,i,o);return this.attachGitStats(a,r),a}async tryParse(e,r){let n=Te.readFileSync(e,"utf-8");try{return await this.parseContent(e,n)}catch(s){return process.stderr.write(`
|
|
38
|
-
Warning: failed to parse ${r}: ${s}
|
|
39
|
-
`),null}}parseContent(e,r){return this.pool?this.pool.run({filePath:e,content:r}):cs(e,r)}makeStubNode(e,r,n){return{path:r,type:_(e),category:"other",imports:[],exports:[],tags:[],mtime:n.mtimeMs,size:n.size}}resolveCallEdges(e,r){let n=[];for(let s of r??[])try{let i=this.resolver.resolve(e,s.toSpecifier);i&&!i.isExternal&&n.push({from:s.from,to:s.to,toFile:E.relative(this.rootDir,i.path)})}catch{}return n}buildNode(e,r,n,s,i){let{imports:o,exports:a,tags:c,category:l,description:p,complexity:u,cognitiveComplexity:d,functions:h}=s;return{path:r,type:_(e),category:l,imports:o,exports:a,tags:c,mtime:n.mtimeMs,size:n.size,...p!==void 0?{description:p}:{},...i.length>0?{callEdges:i}:{},...u!==void 0?{complexity:u}:{},...d!==void 0?{cognitiveComplexity:d}:{},...h!==void 0?{functions:h}:{}}}attachGitStats(e,r){let n=this.gitStatsMap?.get(r);n&&(e.commitCount90d=n.commitCount90d,n.lastAuthor!==void 0&&(e.lastAuthor=n.lastAuthor),n.lastCommitAt!==void 0&&(e.lastCommitAt=n.lastCommitAt))}async resolveImports(e,r){let n=[];for(let s of r){let i=this.resolver.resolveAll(e,s.rawSpecifier);if(i.length!==0)for(let o of i){let a={...s,toPath:o.isExternal?o.path:E.relative(this.rootDir,o.path),isExternal:o.isExternal};o.isWorkspace&&(a.isWorkspace=!0,a.workspacePackage=o.workspacePackage),o.isExternal?this.attachLockfileVersion(a):this.enqueue(o.path),n.push(a)}}return n}attachLockfileVersion(e){if(!this.lockFile)return;let r=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],n=r?this.lockFile.dependencies[r]:void 0;n&&(e.version=n.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};function bs(t,e){return{identifier:e?.identifier??new rt,featureMap:e?.featureDetection===!1?new Map:W(t.nodes,e?.featureDetection??void 0)}}function Ss(t,e,r,n,s){for(let i of e){let o=t.nodes.get(i);if(!o)continue;let a=new B(i,["*",...o.exports.map(c=>c.name)]);t.traverse(i,(c,l,p)=>{if(!p)return!0;if(!a.updateAffectedSymbols(c,p))return!1;if(l>0){let u=r.get(c.path);if(u)return n(u),!1}return s(c),!0},{direction:"incoming"})}}function Sr(t,e,r){let{identifier:n,featureMap:s}=bs(t,r),i=new Set;for(let o of e){let a=s.get(o);a&&i.add(a.tag)}return Ss(t,e,s,o=>i.add(o.tag),o=>{if(n.isTestNode(o))for(let a of o.tags)i.add(a.name)}),Array.from(i)}function kr(t,e,r){let{identifier:n,featureMap:s}=bs(t,r),i=new Set;return Ss(t,e,s,()=>{},o=>{n.isTestNode(o)&&i.add(o.path)}),Array.from(i)}import kl from"fs";import Ae from"path";async function ks(t,e,r=null,n={}){let s=n.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},i=Ae.resolve(t);return await new Ee(i,r,n.pathAliases?new V(i,{pathAliases:n.pathAliases}):void 0,s,n.gitStats??!1,n.coverageMap??new Map,n.parallelParsing??!0).build(e)}async function Cs(t,e={}){let r=Ae.resolve(t),n=de(r),s=e.packages?n.packages.filter(a=>e.packages?.includes(a.name)||e.packages?.includes(a.relativeRoot)):n.packages,i=new Map(n.packages.map(a=>[a.name,a.root])),o=new he(r,n.type);for(let a of s){let c=e.silent?void 0:u=>{process.stderr.write(`[${a.name}] Processed ${u} files...\r`)},p=await new Ee(r,null,new V(r,{workspaceMap:i,tsconfigSearchPaths:[a.root,r],pathAliases:e.pathAliases}),c,e.gitStats??!1,new Map,e.parallelParsing??!0).build(a.entryPoints);o.addPackage(a,p)}return o}function vs(t,e={}){let r=[],n=new Set([...e.ignoreDirs??z,...e.additionalIgnoreDirs??[]]),s=new Set([...e.extensions??kt,...e.additionalExtensions??[]]);function i(o){try{let a=kl.readdirSync(o,{withFileTypes:!0});for(let c of a){let l=Ae.join(o,c.name);c.isDirectory()?n.has(c.name)||i(l):c.isFile()&&s.has(Ae.extname(c.name).toLowerCase())&&r.push(Ae.relative(t,l))}}catch{}}return i(t),r}var ws=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;function Fs(t){return vr.join(t,Me,bt)}function Cl(t,e){return e?.cachePath?vr.resolve(t,e.cachePath):vr.join(t,Me,St)}function vl(t){try{if(!Cr.existsSync(t))return null;let e=Cr.readFileSync(t,"utf-8");return I.deserialize(JSON.parse(e))}catch{return null}}var ct=class{graphs=new Map;configs=new Map;workspaceGraphs=new Map;changeImpactCaches=new Map;dirtyRoots=new Set;watchers=new Map;lastAnalyze=new Map;duplicationTokenCaches=new Map;isConfigured(e){return this.configs.has(e)}storeConfig(e,r){this.configs.set(e,r)}getConfig(e){return this.configs.get(e)}async getOrBuild(e,r,n=new Map){let s=this.configs.get(e),i=this.graphs.get(e)??vl(Cl(e,s)),o=await ks(e,r,i,{...q(s),coverageMap:n});return this.graphs.set(e,o),o}require(e){let r=this.graphs.get(e);if(!r)throw new Error('No graph cached for this root. Call "analyze" first.');return r}async getOrBuildWorkspace(e,r={}){let n=this.workspaceGraphs.get(e);if(n)return n;let s=await Cs(e,r);return this.workspaceGraphs.set(e,s),s}requireWorkspace(e){let r=this.workspaceGraphs.get(e);if(!r)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return r}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){let r=this.changeImpactCaches.get(e);if(r)return r;let n=this.require(e),s=Et(n);return this.changeImpactCaches.set(e,s),s}storeLastAnalyze(e,r){this.lastAnalyze.set(e,r)}startWatching(e){if(!this.watchers.has(e))try{let r=Cr.watch(e,{recursive:!0},(n,s)=>{!s||ws.test(s)||this.dirtyRoots.add(e)});r.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,r)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e);let r=this.lastAnalyze.get(e);return r?.kind==="single"?this.getOrBuild(e,r.entryPoints,r.coverageMap):this.require(e)}async ensureFreshWorkspace(e){if(!this.dirtyRoots.has(e))return this.requireWorkspace(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e),this.workspaceGraphs.delete(e);let r=this.configs.get(e);return this.getOrBuildWorkspace(e,q(r))}async getDuplicationTokenCache(e){let r=this.duplicationTokenCaches.get(e);return r||(r=je(Fs(e)),this.duplicationTokenCaches.set(e,r)),r}flushDuplicationTokenCache(e){let r=this.duplicationTokenCaches.get(e);if(r)try{ze(r,Fs(e))}catch(n){process.stderr.write(`Warning: failed to persist duplication token cache: ${n}
|
|
40
|
-
`)}}invalidate(e){let r=this.graphs.has(e)||this.workspaceGraphs.has(e);return this.graphs.delete(e),this.workspaceGraphs.delete(e),this.changeImpactCaches.delete(e),this.dirtyRoots.delete(e),this.duplicationTokenCaches.delete(e),this.configs.delete(e),r}};import se from"path";import wl from"fs";import Fl from"os";import wr from"path";function x(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function Ts(t){if(!wr.isAbsolute(t))throw new Error("root must be an absolute path");let e=wr.resolve(t),r=Fl.homedir();if(e!==r&&!e.startsWith(r+wr.sep))throw new Error("root must be within the user home directory");let n;try{n=wl.statSync(e)}catch{throw new Error("root does not exist")}if(!n.isDirectory())throw new Error("root is not a directory")}async function Es(t,e){let{root:r,entryPoints:n}=e;if(!t.isConfigured(r)){let d=oe(r,{allowJs:!1});xt(d),t.storeConfig(r,d)}if(n.length===0){let d=de(r);if(d.type!=="none"){let h=t.getConfig(r),C=await t.getOrBuildWorkspace(r,q(h));t.storeLastAnalyze(r,{kind:"workspace"}),t.startWatching(r);let v=Array.from(C.packages.values()).map(({graph:y,pkg:k})=>({package:k.name,relativeRoot:k.relativeRoot,nodeCount:y.nodes.size}));return x({monorepoType:d.type,packageCount:C.packages.size,packages:v})}}let s=n.map(d=>se.resolve(r,d)),i=t.getConfig(r),o=i?.coverageReportPath?Ct(r,i.coverageReportPath):new Map,a=await t.getOrBuild(r,s,o);t.storeLastAnalyze(r,{kind:"single",entryPoints:s,coverageMap:o}),t.startWatching(r);let c=a.serialize(),l=c.nodes.reduce((d,h)=>(d[h.category]=(d[h.category]??0)+1,d),{}),p=a.findCycles(),u=Dt(a);return x({nodeCount:c.nodes.length,categories:l,cycles:p,languageCoverage:u})}async function As(t,e){let{root:r,file:n,depth:s=1,withMeta:i=!1}=e,o=await t.ensureFresh(r),a=Mt(o,n,s),c=i?a.map(l=>({...l,...ue(o,l.path)})):a;return x({file:n,dependencies:c})}async function Ps(t,e){let{root:r,file:n,withMeta:s=!1}=e,i=await t.ensureFresh(r),o=fe(i,n),a=s?o.map(c=>({...c,...ue(i,c.path)})):o;return x({file:n,dependents:a})}async function Ns(t,e){let{root:r,file:n,testsOnly:s=!1,cached:i=!1,changedSymbols:o,withMeta:a=!1}=e,c=await t.ensureFresh(r),l=d=>a?d.map(h=>({path:h,...ue(c,h)})):d;if(i){let d=t.getOrBuildChangeImpact(r),h=At(d,n),C=s?h.filter(y=>c.nodes.get(y)?.category==="test"):h,v=l(C);return x({file:n,affected:v,count:v.length})}let p=Rt(c,n,{testsOnly:s,changedSymbols:o}),u=l(p);return x({file:n,affected:u,count:u.length})}async function Is(t,e){let{root:r,file:n,depth:s=1,withEdgeDetail:i=!1}=e,o=await t.ensureFresh(r),a=Lt(o,n,{depth:s,withEdgeDetail:i});return x({file:n,callers:a,count:a.length})}async function Ds(t,e){let{root:r,entryPoints:n}=e,s=n?await t.getOrBuild(r,n.map(c=>se.resolve(r,c))):await t.ensureFresh(r),i=t.getConfig(r),o=vs(r,{additionalIgnoreDirs:i?.ignoreDirs??[],additionalExtensions:i?.extensions??[]}),a=s.findUnusedFiles(o);return x({unusedFiles:a,count:a.length})}async function Ms(t,e){let{root:r}=e,n=await t.ensureFresh(r),s=new Map;for(let o of n.nodes.values())for(let a of o.tags)s.set(a.name,(s.get(a.name)??0)+1);let i=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count);return x({tags:i,count:i.length})}async function Rs(t,e){let{root:r,coverageThreshold:n}=e,s=await t.ensureFresh(r),i=t.getConfig(r),o=n??i?.coverageThreshold??80;if(!$e(s))return x({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let a=[...s.nodes.values()].filter(c=>c.category!=="test"&&c.category!=="config").filter(c=>c.coveragePct!==void 0&&c.coveragePct<o).map(c=>({file:c.path,coveragePct:c.coveragePct}));return x({threshold:o,uncovered:a,count:a.length})}async function Ls(t,e){let{root:r}=e,s=[...(await t.ensureFresh(r)).nodes.values()].filter(i=>i.type==="markdown"&&i.staleFor&&i.staleFor.length>0).map(i=>({doc:i.path,staleFor:i.staleFor}));return x({staleDocs:s,count:s.length})}async function Gs(t,e){let{root:r,metric:n="cognitiveComplexity",threshold:s=10,limit:i=20}=e,o=await t.ensureFresh(r),a=Gt(o,{metric:n,threshold:s,limit:i});return x({metric:n,threshold:s,functions:a,count:a.length})}async function _s(t,e){let{root:r,metric:n="cognitiveComplexity",minComplexity:s=10,maxCoveragePct:i=50,minChurn:o=0,limit:a=20}=e,c=await t.ensureFresh(r);if(!$e(c))return x({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let{hotspots:l,count:p,churnDataAvailable:u}=jt(c,{metric:n,minComplexity:s,maxCoveragePct:i,minChurn:o,limit:a});return x({metric:n,minComplexity:s,maxCoveragePct:i,minChurn:o,churnDataAvailable:u,hotspots:l,count:p})}async function Os(t,e){let{root:r,minLines:n=6,ignoreLiterals:s=!0,maxPunctuationRatio:i=.5,limit:o=50}=e,a=await t.ensureFresh(r),c=e.ignoreDirs??[...z,...t.getConfig(r)?.ignoreDirs??[]],{groups:l}=await It(a,r,{minLines:n,ignoreLiterals:s,maxPunctuationRatio:i,limit:o,ignoreDirs:c,tokenCache:await t.getDuplicationTokenCache(r)});return t.flushDuplicationTokenCache(r),x({minLines:n,groups:l,count:l.length})}async function js(t,e){let{root:r,changedFiles:n,base:s,featureThreshold:i,format:o="tags"}=e,a=await t.ensureFresh(r),c=n??new nt().getChangedFiles(r,s).map(u=>se.relative(r,se.resolve(r,u))),l=i!==void 0?{featureDetection:{minOutDegree:i}}:void 0;if(o==="paths"){let u=kr(a,c,l);return x({changedFiles:c,affectedTests:u,count:u.length})}let p=Sr(a,c,l);return x({changedFiles:c,proposedTags:p})}async function zs(t,e){let{root:r,entryPoints:n,featureThreshold:s}=e,i=n?await t.getOrBuild(r,n.map(c=>se.resolve(r,c))):await t.ensureFresh(r),o=W(i.nodes,s!==void 0?{minOutDegree:s}:void 0),a=Array.from(o.values()).sort((c,l)=>l.outDegree-c.outDegree);return x({features:a,count:a.length})}async function Ws(t,e){let{root:r,entryPoints:n,filter:s,mermaid:i=!1,slim:o=!0}=e,a=n?await t.getOrBuild(r,n.map(l=>se.resolve(r,l))):await t.ensureFresh(r),c=He(a.serialize(),Ke(s));return i?x(Re.serialize(I.deserialize(c))):o?x(_t(c)):x(c)}async function Bs(t,e){let{root:r}=e,n=await t.ensureFreshWorkspace(r);return x(Ot(n))}async function $s(t,e){let{root:r,file:n}=e,i=(await t.ensureFreshWorkspace(r)).getAffectedAcrossPackages(n);return x({file:n,affected:i,count:i.length})}function Us(t,e){let{root:r}=e,n=t.invalidate(r);return x({root:r,cleared:n,message:n?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function Hs(t,e){let{root:r,type:n}=e,s=await t.ensureFresh(r),i=Bt(s);if(n)return x($t(i,n));let o=Array.from(i.types.values());return x({count:o.length,types:o})}async function Ks(t,e){let{root:r,paths:n,minOutDegree:s}=e,i=await t.ensureFresh(r),o=zt(i,s!==void 0?{minOutDegree:s}:void 0);if(n?.length){let c=n.map(l=>o.get(l)).filter(Boolean);return x({count:c.length,modules:c})}let a=Array.from(o.values());return x({count:a.length,modules:a})}async function Js(t,e){let{root:r,minOutDegree:n}=e,s=await t.ensureFresh(r),i=le(s,n!==void 0?{minOutDegree:n}:void 0),o=Object.fromEntries(i.features);return x({features:o,unassigned:i.unassigned})}async function Vs(t,e){let{root:r,function:n}=e,s=await t.ensureFresh(r);return x(Tt(s,n))}async function Qs(t,e){let{root:r,name:n}=e,s=await t.ensureFresh(r),i=Wt(s,n);return x({name:n,matches:i,count:i.length})}async function qs(t,e){let{root:r,entryPoints:n}=e,s=await t.ensureFresh(r),i=n?.length?n:wt(s,r);if(i.length===0)throw new Error("No entry points found. Pass entryPoints explicitly or ensure package.json has a main/exports field.");return x(Ft(s,i))}async function Ys(t,e){let r=await t.ensureFresh(e.root),n=await or(r,e.root,{dryRun:e.dryRun??!1});return x(n)}var Xs=[{name:"analyze",description:"Build the dependency graph for a project from entry points. Returns a summary of node count, categories, and cycles. Must be called before get_dependencies, get_dependents, get_affected, or propose_tags. Pass an empty entryPoints array to auto-detect a monorepo (pnpm/npm/yarn/Nx/Turborepo) and build per-package graphs \u2014 use get_workspace_packages and get_workspace_affected for monorepo queries.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root (or monorepo root)"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root (e.g. ['src/index.ts']). Pass [] to trigger monorepo auto-detection."}},required:["root","entryPoints"]}},{name:"get_dependencies",description:"Get files that a given file imports (outgoing traversal). depth=1 returns immediate imports; omit for the full transitive tree. Each result includes the specific symbols imported from that file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_dependents",description:"Get files that directly import a given file (one-hop incoming edges). Each result includes the specific symbols that dependent file imports from this file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_affected",description:"Get all files transitively affected if a given file changes \u2014 full incoming traversal upward. Use before a refactor to understand blast radius. See docs/mcp.md for details on the testsOnly, cached, changedSymbols, and withMeta options.",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},testsOnly:{type:"boolean",description:"Return only test/spec files (default: false)"},cached:{type:"boolean",description:"Use a pre-computed impact cache for O(1) lookup instead of graph traversal. Cache is built lazily on first use and reused for the session (default: false)."},changedSymbols:{type:"array",items:{type:"string"},description:"Restrict blast-radius to files that import at least one of these symbols. Omit to treat the whole file as changed (conservative, same as before)."},withMeta:{type:"boolean",description:"Return each affected file as { path, category, exports } instead of a bare path string (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_callers",description:"Get files whose exported functions call into a given file (call-graph dependents). More precise than get_affected: only files with actual runtime call edges, not mere imports. Requires prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to project root"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withEdgeDetail:{type:"boolean",description:"Include from/to function names per edge (default: false)"}},required:["root","file"]}},{name:"find_unused",description:"Find files in the project that are not reachable from any entry point. Useful before cleanup passes. Omit entryPoints to reuse the cached graph from a prior analyze() call instead of rebuilding.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to reuse the cached graph from a prior analyze() call."}},required:["root"]}},{name:"list_tags",description:"List every distinct tag name present in the graph, with how many nodes carry each one. Call this before querying with tag:<name> to avoid a speculative filter silently returning zero results. Includes all tag kinds \u2014 a superset of what query's slim mode keeps (slim only retains comment-marker and import tags).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_uncovered",description:"Find non-test files whose line coverage is below the configured threshold. Requires a prior analyze() call and coverageReportPath set in mokosh.config. coverageThreshold overrides the config default (default: 80).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},coverageThreshold:{type:"number",description:"Line-coverage % below which a file is considered uncovered. Overrides config value."}},required:["root"]}},{name:"check_doc_drift",description:"Find markdown docs whose referenced files changed more recently than the doc itself \u2014 a commit-recency heuristic for stale documentation, not a content diff. Requires a prior analyze() call with gitStats: true in mokosh.config (otherwise no file has commit-timestamp data and nothing is flagged). See docs/adr-009-markdown-parsing.md for known limitations.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_complex_functions",description:"Find individual functions/methods above a cognitive (or cyclomatic) complexity threshold, sorted worst-first. Requires a prior analyze() call. Populated for TypeScript/JavaScript, Go, and Python.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which score to threshold/sort on (default: cognitiveComplexity)"},threshold:{type:"number",description:"Minimum score to include (default: 10)"},limit:{type:"number",description:"Max results to return, worst-first (default: 20)"}},required:["root"]}},{name:"find_risk_hotspots",description:"Find functions that are complex, in a poorly-covered file, and \u2014 when gitStats is enabled in mokosh.config \u2014 in a frequently-changed file. Requires a prior analyze() call and coverageReportPath set in mokosh.config; errors if no coverage data was loaded. Churn filtering is skipped (churnDataAvailable: false) when gitStats wasn't enabled, since complexity + low coverage alone is still a meaningful signal.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score to filter/sort on (default: cognitiveComplexity)"},minComplexity:{type:"number",description:"Minimum per-function complexity score to include (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to include (default: 50)"},minChurn:{type:"number",description:"Minimum containing-file 90-day commit count to include (default: 0). Ignored when gitStats wasn't enabled at analyze time."},limit:{type:"number",description:"Max results to return, worst-first by metric (default: 20)"}},required:["root"]}},{name:"find_duplicates",description:"Find duplicated code blocks across the project, largest-first. CSS/SCSS/Less are matched structurally by rule body; every other parsed language is tokenized and matched via suffix array. Lock files and ignored directories are always excluded. Requires a prior analyze() call. See docs/mcp.md for matching-strategy, normalization, and caching details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minLines:{type:"number",description:"Minimum duplicated block size in lines to report (default: 6)"},ignoreLiterals:{type:"boolean",description:"Normalize string/number literals too, not just identifiers, so only structural shape drives a match (default: true). Set false for stricter, exact-text-only matching."},maxPunctuationRatio:{type:"number",description:"Maximum fraction of a token-shingled block's window that may be object/array-literal structural punctuation ({ } : , [ ]) (default: 0.5). Filters out blocks that are mostly schema/object-literal shape instead of substantive shared logic. Does not apply to the CSS/Less/SCSS structural comparator. Set 1 to disable."},ignoreDirs:{type:"array",items:{type:"string"},description:"Directory names to exclude, matched against any path segment (default: DEFAULT_IGNORE_DIRS merged with this root's configured ignoreDirs, if any). Pass [] to disable."},limit:{type:"number",description:"Max duplicate blocks to return, largest-first (default: 50)"}},required:["root"]}},{name:"propose_tags",description:"Propose what to run based on changed files. Pass changedFiles explicitly or omit to use git diff. format='tags' (default) returns test tags for CI tag-filtering; format='paths' returns test file paths ready to pipe directly to a test runner (e.g. vitest). Feature hubs act as traversal boundaries in both modes.",inputSchema:{type:"object",properties:{root:{type:"string"},changedFiles:{type:"array",items:{type:"string"},description:"Changed files relative to root. Omit to read from git diff."},base:{type:"string",description:"Diff against this ref (e.g. 'origin/main') instead of only local working-tree/staged/untracked changes. Ignored when changedFiles is given. Needed in CI, where the checkout is already clean."},featureThreshold:{type:"number",description:"Min importers for a file to be treated as a feature hub (default: 5). A hub short-circuits traversal and emits a feature:<name> tag instead of all downstream tags."},format:{type:"string",enum:["tags","paths"],description:"Output format: 'tags' returns test tag names for CI filtering (default); 'paths' returns test file paths to pipe to a test runner."}},required:["root"]}},{name:"detect_features",description:"Identify feature hub files \u2014 non-test files that import many other internal modules (orchestrators / aggregators like src/parser.ts or src/cli/runner.ts). Returns a list sorted by import count descending.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to use the cached graph."},featureThreshold:{type:"number",description:"Min internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"query",description:"Filter the graph by category, tag, path, or other node metadata. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used. See docs/mcp.md for the full query DSL reference.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the graph. Omit to reuse the cached graph from a prior 'analyze' call."},filter:{type:"string",description:"Query string e.g. 'category:logic' or 'category:logic,tag:auth'. Supports: category, type, tag, path, external, importsFile, importedBy, minImports, maxImports, minSize, maxSize, hasDocstring, minCoverage, maxCoverage, minExportUsage, maxExportUsage, minComplexity, maxComplexity, minCognitiveComplexity, maxCognitiveComplexity, minCommits, maxCommits, isDocumented, isStale, lastAuthor. OR logic: any(key:val|key:val) matches if any single-key clause holds, ANDed with the rest of the query. sort: size|imports|commitCount90d|exportUsage|complexity|cognitiveComplexity, with sortDir: asc|desc (default desc). limit: N."},mermaid:{type:"boolean",description:"Return a Mermaid diagram (default: false)"},slim:{type:"boolean",description:"Compact response mode (default: true). Returns export names, meaningful tags, and a flat importsFiles path list \u2014 no edge objects, no mtime/size. Tags are filtered to kinds comment-marker and import only; function/class/variable/type/library tags are dropped in slim output. Use list_tags to see the full tag inventory, or pass slim: false to get every tag kind on matching nodes."}},required:["root","filter"]}},{name:"get_workspace_packages",description:"List all workspace packages detected in a monorepo, with their node counts and inter-package dependencies. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"}},required:["root"]}},{name:"get_workspace_affected",description:"Cross-package blast-radius analysis. Returns every file that could be affected if a given file changes, annotated with the package it belongs to. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"},file:{type:"string",description:"Monorepo-root-relative path of the changed file (e.g. 'packages/shared/src/utils.ts')"}},required:["root","file"]}},{name:"get_type_graph",description:"Return type-level relationships for the project. Without a type name, returns an inventory of all interfaces, classes, enums, and type aliases with their file and kind. With a type name, returns which files import that type (usedByFiles) and which types the defining file imports (uses). Requires a prior analyze() call. Only covers TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},type:{type:"string",description:"Exact exported name of the type to look up (e.g. 'FileNode'). Omit to get the full type inventory."}},required:["root"]}},{name:"get_module_responsibility",description:"Return what each file is responsible for: its semantic role, JSDoc description (when present), exported symbol names, and which feature hub it belongs to. Pass specific paths to filter, or omit paths to get all files. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},paths:{type:"array",items:{type:"string"},description:"Project-relative file paths to include. Omit to return all files."},minOutDegree:{type:"number",description:"Min imports for a file to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_feature_graph",description:"Group files by domain: returns which files each feature hub (high-import orchestrator) transitively owns. Each file is assigned to the most specific hub that can reach it (lowest out-degree wins). Use this instead of a full query when answering 'what files are in the X feature/module?' \u2014 it returns only paths grouped by hub, so it's substantially smaller than a full graph query for the same question; compare output sizes yourself if you need an exact figure for your repo.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minOutDegree:{type:"number",description:"Minimum internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_call_graph",description:"Look up callers and callees for a named function. Returns the file that defines the function, all files/functions that call it, and all files/functions it calls. Always requires a function name \u2014 never returns the full call graph unfiltered. Call edges are only populated for TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},function:{type:"string",description:"Exact name of the function to look up (e.g. 'parseFile')."}},required:["root","function"]}},{name:"find_symbol",description:"Find every file that exports a symbol by exact name, with the best available usage info per match. Precision varies by the defining file's language \u2014 check each match's `precision` field ('call' | 'file-level') before trusting caller/importer results as symbol-exact. See docs/mcp.md for per-language coverage details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},name:{type:"string",description:"Exact export name to look up (e.g. 'parseFile')."}},required:["root","name"]}},{name:"get_api_surface",description:"Build the API surface report for a project: every exported symbol resolved to its defining file and kind, partitioned into internalFiles, unreachableFromEntry, and testFiles. Requires a prior analyze() call. When entryPoints is omitted, auto-detects from package.json exports/main/module. See docs/mcp.md for the export* expansion and partition semantics.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},entryPoints:{type:"array",items:{type:"string"},description:"Project-relative paths of public entry points (e.g. ['src/index.ts', 'src/utils.ts']). Omit to auto-detect from package.json exports / main / module fields."}},required:["root"]}},{name:"clear_cache",description:"Drop the cached dependency graph and loaded mokosh.config.json for a project root, forcing the next analyze() call to rebuild from disk and re-read config. Call this after editing source files OR mokosh.config.json mid-session \u2014 otherwise get_affected, get_dependencies, and other query tools will reason from stale data (or a stale config).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root to invalidate."}},required:["root"]}},{name:"apply_tags",description:"Write @tag annotations into test file source code based on the dependency graph, as an idempotent block \u2014 re-running is safe, the existing block is replaced in place. Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call. See docs/mcp.md for tag-kind and per-language block syntax details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root."},dryRun:{type:"boolean",description:"When true, computes which files would change but does not write to disk (default: false)."}},required:["root"]}}];function Fr(){let t=new ct,e=new Tl({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(Al,async()=>({tools:Xs})),e.setRequestHandler(El,async r=>{let{name:n,arguments:s}=r.params,i=s,a={analyze:c=>Es(t,c),get_dependencies:c=>As(t,c),get_dependents:c=>Ps(t,c),get_affected:c=>Ns(t,c),get_callers:c=>Is(t,c),find_symbol:c=>Qs(t,c),find_unused:c=>Ds(t,c),find_uncovered:c=>Rs(t,c),list_tags:c=>Ms(t,c),check_doc_drift:c=>Ls(t,c),find_complex_functions:c=>Gs(t,c),find_risk_hotspots:c=>_s(t,c),find_duplicates:c=>Os(t,c),propose_tags:c=>js(t,c),detect_features:c=>zs(t,c),get_type_graph:c=>Hs(t,c),get_module_responsibility:c=>Ks(t,c),get_feature_graph:c=>Js(t,c),get_call_graph:c=>Vs(t,c),get_api_surface:c=>qs(t,c),query:c=>Ws(t,c),get_workspace_packages:c=>Bs(t,c),get_workspace_affected:c=>$s(t,c),clear_cache:c=>Us(t,c),apply_tags:c=>Ys(t,c)}[n];if(!a)throw new Error(`Unknown tool: ${n}`);try{return Ts(i.root),await a(i)}catch(c){return{content:[{type:"text",text:`Error: ${c instanceof Error?c.message:String(c)}`}],isError:!0}}}),e}async function Nl(){let t=Fr(),e=new Pl;await t.connect(e)}Nl().catch(console.error);export{Fr as createMcpServer};
|
|
50
|
+
`;return`${l+m+u+i}
|
|
51
|
+
${p}`}};function Am(t){let e=t.split(`
|
|
52
|
+
`),r=-1;return e.forEach((s,o)=>{(s.trimStart().startsWith("import ")||s.trimStart().startsWith("from "))&&(r=o)}),r<0?0:e.slice(0,r+1).reduce((s,o)=>s+o.length+1,0)}import Nm from"path";var xn=/^\/\/ mokosh:tags .*\n/m,Rm=/^(?:sealed\s+|abstract\s+|final\s+|private\s+|implicit\s+|case\s+)*(?:class|object|trait)\s+\w+/m,Dm=/\/src\/(test|it)\//,Im=/(Spec|Suite|Test|Props)\.scala$/;function Mm(t){let e=xn.exec(t);return e?e[0].replace(/^\/\/ mokosh:tags /,"").trim().split(/\s*,\s*/).filter(Boolean):null}var zt=class{name="scalatest";canHandle(e){let r=e.replace(/\\/g,"/");return Nm.extname(r).toLowerCase()!==".scala"?!1:Dm.test(r)||Im.test(r)}apply(e,r,n){let s=Mm(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return s===null?r:r.replace(xn,"");let i=`// mokosh:tags ${o.join(", ")}
|
|
53
|
+
`;if(s!==null)return r.replace(xn,i);let a=Rm.exec(r);return a?r.slice(0,a.index)+i+r.slice(a.index):r}};import Vo from"path";import Qo from"typescript";var _m=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,$t=class{name="vitest";canHandle(e){return L.has(Vo.extname(e).toLowerCase())}apply(e,r,n){let s=r.replace(_m,""),o=Qo.createSourceFile(Vo.basename(e),s,Qo.ScriptTarget.Latest,!0),i=sn(o),[a]=i;if(!a)return s;let c=on(a,"tags",o),l=[...n].sort();if(c!==null&&JSON.stringify([...c].sort())===JSON.stringify(l))return s;let p=i.flatMap(u=>{let m=n.length===0?cn(u,"tags",o):an(u,"tags",pn(l),o);return m?[m]:[]});return p.length>0?ln(s,p):s}};var Yo={vitest:()=>new $t,playwright:()=>new jt,cypress:()=>new Mt,jest:()=>new Gt},Lm={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function Gm(t){let e=Bt.createSourceFile("detect.ts",t,Bt.ScriptTarget.Latest,!0);for(let r of e.statements){if(!Bt.isImportDeclaration(r)||!Bt.isStringLiteral(r.moduleSpecifier))continue;let n=Lm[r.moduleSpecifier.text];if(n)return n}return null}var Sn=class{constructor(e,r,n){this.rootDir=e;this.defaultFramework=r;this.frameworkOverrides=n}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return L.has(bn.extname(e).toLowerCase())}apply(e,r,n){let s=Gm(r)??this.matchOverride(e)??this.defaultFramework;return(Yo[s]??Yo.vitest)().apply(e,r,n)}matchOverride(e){let r=bn.relative(this.rootDir,e).split(bn.sep).join("/");for(let[n,s]of this.frameworkOverrides)if(Ko(n,r))return s;return null}};function Xo(t="vitest",e={},r=process.cwd()){return[new _t,new Wt,new Lt,new Ot,new zt,new Sn(r,t,Object.entries(e))]}function Zo(t,e){return e.find(r=>r.canHandle(t))??null}var jm=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,Wm=new Set(["import"]),zm=new Set(["common","fixture","fixtures","helper","helpers","index","main","mock","mocks","setup","shared","spec","test","tests","types","util","utils"]);async function $m(t,e,r,n){let s;try{s=await ei.readFile(t,"utf8")}catch(a){return{path:t,status:"error",error:String(a)}}let o=Zo(t,n);if(!o)return{path:t,status:"unchanged"};let i=o.apply(t,s,e);return i===s?{path:t,status:"unchanged"}:(r||await ei.writeFile(t,i,"utf8"),{path:t,status:"updated"})}async function kn(t,e,r){let n=Re(e),s=n.tagApplier?.framework??"vitest",o=n.tagApplier?.frameworkOverrides??{},i=Xo(s,o,e),a={updated:0,unchanged:0,errors:0,files:[]};for(let c of t.nodes.values()){if(c.category!=="test")continue;let l=new Set,p=[];for(let d of c.tags)Wm.has(d.kind)&&jm.test(d.name)&&(zm.has(d.name.toLowerCase())||l.has(d.name)||(l.add(d.name),p.push(d.name)));p.sort();let u=Om.resolve(e,c.path),m=await $m(u,p,r.dryRun,i);m.path=c.path,a.files.push(m),m.status==="updated"?a.updated++:m.status==="unchanged"?a.unchanged++:a.errors++}return a}var Ht=class{isTestNode(e){return e.category==="test"||e.tags.some(r=>r.name==="test")}};function ti(t,e){return{identifier:e?.identifier??new Ht,featureMap:e?.featureDetection===!1?new Map:ae(t.nodes,e?.featureDetection??void 0)}}function ri(t,e,r,n,s){for(let o of e){let i=t.nodes.get(o);if(!i)continue;let a=new se(o,["*",...i.exports.map(c=>c.name)]);t.traverse(o,(c,l,p)=>{if(!p)return!0;if(!a.updateAffectedSymbols(c,p))return!1;if(l>0){let u=r.get(c.path);if(u)return n(u),!1}return s(c),!0},{direction:"incoming"})}}function vn(t,e,r){let{identifier:n,featureMap:s}=ti(t,r),o=new Set;for(let i of e){let a=s.get(i);a&&o.add(a.tag)}return ri(t,e,s,i=>o.add(i.tag),i=>{if(n.isTestNode(i))for(let a of i.tags)o.add(a.name)}),Array.from(o)}function Cn(t,e,r){let{identifier:n,featureMap:s}=ti(t,r),o=new Set;return ri(t,e,s,()=>{},i=>{n.isTestNode(i)&&o.add(i.path)}),Array.from(o)}import Bm from"crypto";import ni from"fs";import Hm from"os";import q from"path";async function si(t,e,r=null,n={}){let s=n.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},o=q.resolve(t);return await new ne(o,r,n.pathAliases?new z(o,{pathAliases:n.pathAliases}):void 0,s,n.gitStats??!1,n.coverageMap??new Map,n.parallelParsing??!0,n.additionalIgnoreDirs??[],n.docFiles??null).build(e)}function Um(t){let e=Number.parseInt(process.env.MOKOSH_WORKSPACE_CONCURRENCY??"",10),r=Number.isFinite(e)&&e>0?e:Hm.cpus().length||1;return Math.max(1,Math.min(r,Math.max(1,t)))}function Km(t,e,r){let n=new Map(e.map(o=>[o.name,[]])),s=[...e].sort((o,i)=>i.root.length-o.root.length);for(let o of r){if(!o.endsWith(".md")&&!o.endsWith(".mdx"))continue;let i=q.join(t,o),a=s.find(c=>i===c.root||i.startsWith(`${c.root}${q.sep}`));a&&n.get(a.name)?.push(i)}return n}function oi(t){let e=Ut(t),r=Bm.createHash("sha256");for(let n of[...e].sort()){let s=`${n}\0?\0?`;try{let o=ni.statSync(q.join(t,n));s=`${n}\0${o.mtimeMs}\0${o.size}`}catch{}r.update(`${s}
|
|
54
|
+
`)}return{digest:r.digest("hex"),files:e}}async function ii(t,e={}){let r=q.resolve(t),n=e.layout??Ze(r),s=e.projectFiles??Ut(r),o=e.additionalIgnoreDirs??[],i=e.packages?n.packages.filter(x=>e.packages?.includes(x.name)||e.packages?.includes(x.relativeRoot)):n.packages,a=new Map(n.packages.map(x=>[x.name,x.root])),c=new ce(r,n.type),l=new re(o),p=Km(r,i,s),u=Um(i.length),m=u>1?!1:e.parallelParsing??!0,d=new Array(i.length),y=0,v=async()=>{for(let x=y++;x<i.length;x=y++){let C=i[x],A=e.silent?void 0:E=>{process.stderr.write(`[${C.name}] Processed ${E} files...\r`)},S=new ne(r,e.previousWorkspace?.packages.get(C.name)?.graph??null,new z(r,{workspaceMap:a,tsconfigSearchPaths:[C.root,r],pathAliases:e.pathAliases,langResolvers:vt({jvm:l})}),A,e.gitStats??!1,new Map,m,o,p.get(C.name)??[]);d[x]=await S.build(C.entryPoints)}};return await Promise.all(Array.from({length:u},v)),i.forEach((x,C)=>{c.addPackage(x,d[C])}),c.annotateCrossPackageEdges(),c}function Ut(t,e={}){let r=[],n=new Set([...e.ignoreDirs??N,...e.additionalIgnoreDirs??[]]),s=new Set([...e.extensions??ir,...e.additionalExtensions??[]]);function o(i){try{let a=ni.readdirSync(i,{withFileTypes:!0});for(let c of a){let l=q.join(i,c.name);c.isDirectory()?n.has(c.name)||o(l):c.isFile()&&s.has(q.extname(c.name).toLowerCase())&&r.push(q.relative(t,l))}}catch{}}return o(t),r}var ai=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;function ci(t){return V.join(t,Q,De)}function Jm(t,e){return e?.cachePath?V.resolve(t,e.cachePath):V.join(t,Q,nr)}function qm(t,e){let r=e?.cachePath?V.dirname(V.resolve(t,e.cachePath)):V.join(t,Q);return V.join(r,sr)}function Vm(t,e){try{if(!pe.existsSync(t))return null;let r=JSON.parse(pe.readFileSync(t,"utf-8"));return!r.graph||r.digest!==e?null:ce.deserialize(r.graph)}catch{return null}}function Qm(t,e,r){try{pe.mkdirSync(V.dirname(t),{recursive:!0}),pe.writeFileSync(t,JSON.stringify({digest:e,graph:r.serialize()}))}catch(n){process.stderr.write(`Warning: failed to persist workspace graph cache: ${n}
|
|
55
|
+
`)}}function Ym(t){try{if(!pe.existsSync(t))return null;let e=pe.readFileSync(t,"utf-8");return R.deserialize(JSON.parse(e))}catch{return null}}var Kt=class{graphs=new Map;configs=new Map;workspaceGraphs=new Map;layouts=new Map;workspaceBuilds=new Map;changeImpactCaches=new Map;dirtyRoots=new Set;watchers=new Map;lastAnalyze=new Map;duplicationTokenCaches=new Map;isConfigured(e){return this.configs.has(e)}storeConfig(e,r){this.configs.set(e,r)}getConfig(e){return this.configs.get(e)}async getOrBuild(e,r,n=new Map){let s=this.configs.get(e),o=this.graphs.get(e)??Ym(Jm(e,s)),i=await si(e,r,o,{...H(s),coverageMap:n});return this.graphs.set(e,i),i}require(e){let r=this.graphs.get(e);if(!r)throw new Error('No graph cached for this root. Call "analyze" first.');return r}getLayout(e){let r=this.layouts.get(e);if(r)return r;let n=Ze(e);return this.layouts.set(e,n),n}async getOrBuildWorkspace(e,r={}){let n=this.workspaceGraphs.get(e);if(n)return n;let s=this.workspaceBuilds.get(e);if(s)return s;let{forceFresh:o,...i}=r,a=qm(e,this.configs.get(e)),{digest:c,files:l}=oi(e),p=o?null:Vm(a,c);if(p)return this.workspaceGraphs.set(e,p),p;let u=ii(e,{...i,layout:this.getLayout(e),projectFiles:l}).then(m=>(this.workspaceGraphs.set(e,m),Qm(a,c,m),m)).finally(()=>{this.workspaceBuilds.delete(e)});return this.workspaceBuilds.set(e,u),u}requireWorkspace(e){let r=this.workspaceGraphs.get(e);if(!r)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return r}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){let r=this.changeImpactCaches.get(e);if(r)return r;let n=this.require(e),s=mr(n);return this.changeImpactCaches.set(e,s),s}storeLastAnalyze(e,r){this.lastAnalyze.set(e,r)}getLastEntryPoints(e){let r=this.lastAnalyze.get(e);return r?.kind==="single"?r.entryPoints:void 0}startWatching(e){if(!this.watchers.has(e))try{let r=pe.watch(e,{recursive:!0},(n,s)=>{!s||ai.test(s)||this.dirtyRoots.add(e)});r.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,r)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e);let r=this.lastAnalyze.get(e);return r?.kind==="single"?this.getOrBuild(e,r.entryPoints,r.coverageMap):this.require(e)}async ensureFreshWorkspace(e){if(!this.dirtyRoots.has(e)){let s=this.workspaceGraphs.get(e);return s||this.getOrBuildWorkspace(e,H(this.configs.get(e)))}this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e);let r=this.workspaceGraphs.get(e);this.workspaceGraphs.delete(e);let n=this.configs.get(e);return this.getOrBuildWorkspace(e,{...H(n),forceFresh:!0,previousWorkspace:r})}async getDuplicationTokenCache(e){let r=this.duplicationTokenCaches.get(e);return r||(r=Ce(ci(e)),this.duplicationTokenCaches.set(e,r)),r}flushDuplicationTokenCache(e){let r=this.duplicationTokenCaches.get(e);if(r)try{we(r,ci(e))}catch(n){process.stderr.write(`Warning: failed to persist duplication token cache: ${n}
|
|
56
|
+
`)}}invalidate(e){let r=this.graphs.has(e)||this.workspaceGraphs.has(e);return this.graphs.delete(e),this.workspaceGraphs.delete(e),this.workspaceBuilds.delete(e),this.layouts.delete(e),this.changeImpactCaches.delete(e),this.dirtyRoots.delete(e),this.duplicationTokenCaches.delete(e),this.configs.delete(e),r}};import ue from"path";import Xm from"fs";import Zm from"os";import wn from"path";function b(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function li(t){if(!wn.isAbsolute(t))throw new Error("root must be an absolute path");let e=wn.resolve(t),r=Zm.homedir();if(e!==r&&!e.startsWith(r+wn.sep))throw new Error("root must be within the user home directory");let n;try{n=Xm.statSync(e)}catch{throw new Error("root does not exist")}if(!n.isDirectory())throw new Error("root is not a directory")}async function pi(t,e){let{root:r,entryPoints:n}=e;if(!t.isConfigured(r)){let m=Re(r,{allowJs:!1});rr(m),t.storeConfig(r,m)}if(n.length===0){let m=t.getLayout(r);if(m.type!=="none"){let d=t.getConfig(r),y={...H(d),packages:e.packages};if(t.storeLastAnalyze(r,{kind:"workspace"}),t.startWatching(r),!e.eager){let C=t.hasWorkspace(r)?t.requireWorkspace(r):void 0;return b(Xe(m,C))}let v=await t.getOrBuildWorkspace(r,y),x=Array.from(v.packages.values()).map(({graph:C,pkg:A})=>({package:A.name,relativeRoot:A.relativeRoot,nodeCount:C.nodes.size}));return b({monorepoType:m.type,packageCount:v.packages.size,packages:x})}}let s=n.map(m=>ue.resolve(r,m)),o=t.getConfig(r),i=o?.coverageReportPath?ar(r,o.coverageReportPath):new Map,a=await t.getOrBuild(r,s,i);t.storeLastAnalyze(r,{kind:"single",entryPoints:s,coverageMap:i}),t.startWatching(r);let c=a.serialize(),l=c.nodes.reduce((m,d)=>(m[d.category]=(m[d.category]??0)+1,m),{}),p=a.findCycles({includeKinds:e.cycleKinds}),u=Lr(a);return b({nodeCount:c.nodes.length,categories:l,cycles:p,languageCoverage:u})}async function ui(t,e){let{root:r,file:n,depth:s=1,withMeta:o=!1}=e,i=await t.ensureFresh(r),a=zr(i,n,s),c=o?a.map(l=>({...l,...Je(i,l.path)})):a;return b({file:n,dependencies:c})}async function mi(t,e){let{root:r,file:n,withMeta:s=!1}=e,o=await t.ensureFresh(r),i=qe(o,n),a=s?i.map(c=>({...c,...Je(o,c.path)})):i;return b({file:n,dependents:a})}async function fi(t,e){let{root:r,file:n,testsOnly:s=!1,cached:o=!1,changedSymbols:i,withMeta:a=!1}=e,c=await t.ensureFresh(r),l=m=>a?m.map(d=>({path:d,...Je(c,d)})):m;if(o){let m=t.getOrBuildChangeImpact(r),d=fr(m,n),y=s?d.filter(x=>c.nodes.get(x)?.category==="test"):d,v=l(y);return b({file:n,affected:v,count:v.length})}let p=$r(c,n,{testsOnly:s,changedSymbols:i}),u=l(p);return b({file:n,affected:u,count:u.length})}async function gi(t,e){let{root:r,baseRef:n,headRef:s,minDuplicateLines:o,complexityMetric:i,complexityThreshold:a}=e,c=await t.ensureFresh(r),l=e.entryPoints??t.getLastEntryPoints(r)?.map(u=>ue.relative(r,u))??[],p=await Vr(r,n,c,{headRef:s,entryPoints:l,minDuplicateLines:o,complexityMetric:i,complexityThreshold:a,maxCoveragePct:e.maxCoveragePct,...H(t.getConfig(r))});return e.detail==="full"?b(p):b(qr(p,{metric:i,maxItems:e.maxItems}))}async function di(t,e){let{root:r,file:n,depth:s=1,withEdgeDetail:o=!1}=e,i=await t.ensureFresh(r),a=Br(i,n,{depth:s,withEdgeDetail:o});return b({file:n,callers:a,count:a.length})}async function hi(t,e){let{root:r,entryPoints:n}=e,s=n?await t.getOrBuild(r,n.map(c=>ue.resolve(r,c))):await t.ensureFresh(r),o=t.getConfig(r),i=Ut(r,{additionalIgnoreDirs:o?.ignoreDirs??[],additionalExtensions:o?.extensions??[]}),a=s.findUnusedFiles(i);return b({unusedFiles:a,count:a.length})}async function yi(t,e){let{root:r}=e,n=await t.ensureFresh(r),s=new Map;for(let i of n.nodes.values())for(let a of i.tags)s.set(a.name,(s.get(a.name)??0)+1);let o=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count);return b({tags:o,count:o.length})}async function xi(t,e){let{root:r,coverageThreshold:n}=e,s=await t.ensureFresh(r),o=t.getConfig(r),i=n??o?.coverageThreshold??80;if(!oe(s))return b({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let a=[...s.nodes.values()].filter(c=>c.category!=="test"&&c.category!=="config").filter(c=>c.coveragePct!==void 0&&c.coveragePct<i).map(c=>({file:c.path,coveragePct:c.coveragePct}));return b({threshold:i,uncovered:a,count:a.length})}async function bi(t,e){let{root:r}=e,s=[...(await t.ensureFresh(r)).nodes.values()].filter(o=>o.type==="markdown"&&o.staleFor&&o.staleFor.length>0).map(o=>({doc:o.path,staleFor:o.staleFor}));return b({staleDocs:s,count:s.length})}async function Si(t,e){let{root:r,metric:n="cognitiveComplexity",threshold:s=10,limit:o=20}=e,i=await t.ensureFresh(r),a=Te(i,{metric:n,threshold:s,limit:o});return b({metric:n,threshold:s,functions:a,count:a.length})}async function ki(t,e){let{root:r,metric:n="cognitiveComplexity",minComplexity:s=10,maxCoveragePct:o=50,minChurn:i=0,limit:a=20}=e,c=await t.ensureFresh(r);if(!oe(c))return b({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let{hotspots:l,count:p,churnDataAvailable:u}=Fe(c,{metric:n,minComplexity:s,maxCoveragePct:o,minChurn:i,limit:a});return b({metric:n,minComplexity:s,maxCoveragePct:o,minChurn:i,churnDataAvailable:u,hotspots:l,count:p})}async function vi(t,e){let{root:r,minLines:n=6,ignoreLiterals:s=!0,maxPunctuationRatio:o=.5,limit:i=50}=e,a=await t.ensureFresh(r),c=t.getConfig(r),l=e.ignoreDirs??[...N,...c?.ignoreDirs??[]],{groups:p}=await Ee(a,r,{minLines:n,ignoreLiterals:s,maxPunctuationRatio:o,limit:i,ignoreDirs:l,includeGenerated:e.includeGenerated??c?.duplication?.includeGenerated??!1,ignoreGlobs:c?.duplication?.ignoreGlobs??[],tokenCache:await t.getDuplicationTokenCache(r)});return t.flushDuplicationTokenCache(r),b({minLines:n,groups:p,count:p.length})}async function Ci(t,e){let{root:r,changedFiles:n,base:s,featureThreshold:o,format:i="tags"}=e,a=await t.ensureFresh(r),c=n??new ct().getChangedFiles(r,s).map(u=>ue.relative(r,ue.resolve(r,u))),l=o!==void 0?{featureDetection:{minOutDegree:o}}:void 0;if(i==="paths"){let u=Cn(a,c,l);return b({changedFiles:c,affectedTests:u,count:u.length})}let p=vn(a,c,l);return b({changedFiles:c,proposedTags:p})}async function wi(t,e){let{root:r,entryPoints:n,featureThreshold:s}=e,o=n?await t.getOrBuild(r,n.map(c=>ue.resolve(r,c))):await t.ensureFresh(r),i=ae(o.nodes,s!==void 0?{minOutDegree:s}:void 0),a=Array.from(i.values()).sort((c,l)=>l.outDegree-c.outDegree);return b({features:a,count:a.length})}async function Ei(t,e){let{root:r,entryPoints:n,filter:s,mermaid:o=!1,slim:i=!0}=e,a=n?await t.getOrBuild(r,n.map(l=>ue.resolve(r,l))):await t.ensureFresh(r),c=Rt(a.serialize(),Dt(s));return o?b(it.serialize(R.deserialize(c))):i?b(Hr(c)):b(c)}async function Ti(t,e){let{root:r}=e,n=t.getLayout(r);if(n.type==="none")throw new Error(`${r} is not a recognized monorepo root (no pnpm/npm/yarn/Nx/Turborepo/Gradle/sbt workspace detected).`);let s=t.hasWorkspace(r)?t.requireWorkspace(r):void 0;return b(Xe(n,s))}async function Fi(t,e){let{root:r,file:n}=e,o=(await t.ensureFreshWorkspace(r)).getAffectedAcrossPackages(n);return b({file:n,affected:o,count:o.length})}function Pi(t,e){let{root:r}=e,n=t.invalidate(r);return b({root:r,cleared:n,message:n?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function Ai(t,e){let{root:r,type:n}=e,s=await t.ensureFresh(r),o=Xr(s);if(n)return b(Zr(o,n));let i=Array.from(o.types.values());return b({count:i.length,types:i})}async function Ni(t,e){let{root:r,paths:n,minOutDegree:s}=e,o=await t.ensureFresh(r),i=Qr(o,s!==void 0?{minOutDegree:s}:void 0);if(n?.length){let c=n.map(l=>i.get(l)).filter(Boolean);return b({count:c.length,modules:c})}let a=Array.from(i.values());return b({count:a.length,modules:a})}async function Ri(t,e){let{root:r,minOutDegree:n}=e,s=await t.ensureFresh(r),o=Ve(s,n!==void 0?{minOutDegree:n}:void 0),i=Object.fromEntries(o.features);return b({features:i,unassigned:o.unassigned})}async function Di(t,e){let{root:r,function:n}=e,s=await t.ensureFresh(r);return b(ur(s,n))}async function Ii(t,e){let{root:r,name:n}=e,s=await t.ensureFresh(r),o=Yr(s,n);return b({name:n,matches:o,count:o.length})}async function Mi(t,e){let{root:r,entryPoints:n}=e,s=await t.ensureFresh(r),o=n?.length?n:lr(s,r);if(o.length===0)throw new Error("No entry points found. Pass entryPoints explicitly or ensure package.json has a main/exports field.");return b(pr(s,o))}async function _i(t,e){let r=await t.ensureFresh(e.root),n=await kn(r,e.root,{dryRun:e.dryRun??!1});return b(n)}var Li=[{name:"analyze",description:"Build the dependency graph for a project from entry points. Returns a summary of node count, categories, and cycles. Must be called before get_dependencies, get_dependents, get_affected, or propose_tags. Pass an empty entryPoints array to auto-detect a monorepo (pnpm/npm/yarn/Nx/Turborepo/Gradle/sbt): this returns the package layout immediately and builds per-package graphs lazily on the first get_workspace_affected call \u2014 pass eager:true to build them all up front. Use get_workspace_packages and get_workspace_affected for monorepo queries.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root (or monorepo root)"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root (e.g. ['src/index.ts']). Pass [] to trigger monorepo auto-detection."},eager:{type:"boolean",description:"Monorepo only: build every package graph before returning (restores the { nodeCount, categories, cycles } payload) instead of the fast layout-only response. Default false."},packages:{type:"array",items:{type:"string"},description:"Monorepo only: restrict the build to these package names or relative roots. The escape hatch for very large monorepos."},cycleKinds:{type:"array",items:{type:"string",enum:["docReference","samePackage"]},description:"Include normally-filtered cycle edge kinds in the `cycles` output: 'docReference' (Markdown doc cross-links, ADR-009), 'samePackage' (JVM same-package siblings). Default: none \u2014 only genuine import cycles are reported."}},required:["root","entryPoints"]}},{name:"get_dependencies",description:"Get files that a given file imports (outgoing traversal). depth=1 returns immediate imports; omit for the full transitive tree. Each result includes the specific symbols imported from that file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_dependents",description:"Get files that directly import a given file (one-hop incoming edges). Each result includes the specific symbols that dependent file imports from this file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_affected",description:"Get all files transitively affected if a given file changes \u2014 full incoming traversal upward. Use before a refactor to understand blast radius. See docs/mcp.md for details on the testsOnly, cached, changedSymbols, and withMeta options.",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},testsOnly:{type:"boolean",description:"Return only test/spec files (default: false)"},cached:{type:"boolean",description:"Use a pre-computed impact cache for O(1) lookup instead of graph traversal. Cache is built lazily on first use and reused for the session (default: false)."},changedSymbols:{type:"array",items:{type:"string"},description:"Restrict blast-radius to files that import at least one of these symbols. Omit to treat the whole file as changed (conservative, same as before)."},withMeta:{type:"boolean",description:"Return each affected file as { path, category, exports } instead of a bare path string (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"compare_branches",description:"Compare the current graph (root) against baseRef, for reviewing a PR/branch: file diff, stale post-rename references, and deltas for duplication, complexity, doc drift, and coverage/risk hotspots. Returns a compact summary by default (verdict + headline + capped delta lists); pass detail:'full' for every entry. See docs/mcp.md for details. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},baseRef:{type:"string",description:"Git ref to compare against, e.g. 'main', 'origin/main', or a commit sha"},headRef:{type:"string",description:"Git ref to label the head side of the comparison (default: 'HEAD'). The graph itself always comes from the already-analyzed root, not a checkout of this ref."},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the base-ref graph from, relative to root. Defaults to the entry points from the last analyze() call for this root."},minDuplicateLines:{type:"number",description:"Minimum duplicated block size, in source lines, for the duplication delta (default: 6)"},complexityMetric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score drives the complexity delta (default: cognitiveComplexity)"},complexityThreshold:{type:"number",description:"Minimum per-function score to count as a complexity hotspot (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to count as a risk hotspot (default: 50)"},detail:{type:"string",enum:["summary","full"],description:"'summary' (default): verdict, headline, and each delta list capped at maxItems with true counts; empty sections omitted. 'full': the complete BranchComparison with every entry."},maxItems:{type:"number",description:"In summary mode, max entries kept per delta list (complexity/duplication/doc-drift/coverage); the true count is always reported alongside (default: 8). Stale references are never truncated."}},required:["root","baseRef"]}},{name:"get_callers",description:"Get files whose exported functions call into a given file (call-graph dependents). More precise than get_affected: only files with actual runtime call edges, not mere imports. Requires prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to project root"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withEdgeDetail:{type:"boolean",description:"Include from/to function names per edge (default: false)"}},required:["root","file"]}},{name:"find_unused",description:"Find files in the project that are not reachable from any entry point. Useful before cleanup passes. Omit entryPoints to reuse the cached graph from a prior analyze() call instead of rebuilding.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to reuse the cached graph from a prior analyze() call."}},required:["root"]}},{name:"list_tags",description:"List every distinct tag name present in the graph, with how many nodes carry each one. Call this before querying with tag:<name> to avoid a speculative filter silently returning zero results. Includes all tag kinds \u2014 a superset of what query's slim mode keeps (slim only retains comment-marker and import tags).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_uncovered",description:"Find non-test files whose line coverage is below the configured threshold. Requires a prior analyze() call and coverageReportPath set in mokosh.config. coverageThreshold overrides the config default (default: 80).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},coverageThreshold:{type:"number",description:"Line-coverage % below which a file is considered uncovered. Overrides config value."}},required:["root"]}},{name:"check_doc_drift",description:"Find markdown docs whose referenced files changed more recently than the doc itself \u2014 a commit-recency heuristic for stale documentation, not a content diff. Requires a prior analyze() call with gitStats: true in mokosh.config (otherwise no file has commit-timestamp data and nothing is flagged). See docs/adr-009-markdown-parsing.md for known limitations.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_complex_functions",description:"Find individual functions/methods above a cognitive (or cyclomatic) complexity threshold, sorted worst-first. Requires a prior analyze() call. Populated for TypeScript/JavaScript, Go, and Python.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which score to threshold/sort on (default: cognitiveComplexity)"},threshold:{type:"number",description:"Minimum score to include (default: 10)"},limit:{type:"number",description:"Max results to return, worst-first (default: 20)"}},required:["root"]}},{name:"find_risk_hotspots",description:"Find functions that are complex, in a poorly-covered file, and \u2014 when gitStats is enabled in mokosh.config \u2014 in a frequently-changed file. Requires a prior analyze() call and coverageReportPath set in mokosh.config; errors if no coverage data was loaded. Churn filtering is skipped (churnDataAvailable: false) when gitStats wasn't enabled, since complexity + low coverage alone is still a meaningful signal.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score to filter/sort on (default: cognitiveComplexity)"},minComplexity:{type:"number",description:"Minimum per-function complexity score to include (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to include (default: 50)"},minChurn:{type:"number",description:"Minimum containing-file 90-day commit count to include (default: 0). Ignored when gitStats wasn't enabled at analyze time."},limit:{type:"number",description:"Max results to return, worst-first by metric (default: 20)"}},required:["root"]}},{name:"find_duplicates",description:"Find duplicated code blocks across the project, largest-first. CSS/SCSS/Less are matched structurally by rule body; every other parsed language is tokenized and matched via suffix array. Lock files and ignored directories are always excluded. Requires a prior analyze() call. See docs/mcp.md for matching-strategy, normalization, and caching details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minLines:{type:"number",description:"Minimum duplicated block size in lines to report (default: 6)"},ignoreLiterals:{type:"boolean",description:"Normalize string/number literals too, not just identifiers, so only structural shape drives a match (default: true). Set false for stricter, exact-text-only matching."},maxPunctuationRatio:{type:"number",description:"Maximum fraction of a token-shingled block's window that may be object/array-literal structural punctuation ({ } : , [ ]) (default: 0.5). Filters out blocks that are mostly schema/object-literal shape instead of substantive shared logic. Does not apply to the CSS/Less/SCSS structural comparator. Set 1 to disable."},ignoreDirs:{type:"array",items:{type:"string"},description:"Directory names to exclude, matched against any path segment (default: DEFAULT_IGNORE_DIRS merged with this root's configured ignoreDirs, if any). Pass [] to disable."},limit:{type:"number",description:"Max duplicate blocks to return, largest-first (default: 50)"},includeGenerated:{type:"boolean",description:"Scan generated / vendored files too (default: false). By default protobuf output, *.generated.* files, files under a generated/ directory, and files with a @generated / DO NOT EDIT / Code generated by marker in their first ~500 bytes are skipped \u2014 their repetition isn't actionable copy-paste. Matches involving a generated file are tagged signals: ['generated']."}},required:["root"]}},{name:"propose_tags",description:"Propose what to run based on changed files. Pass changedFiles explicitly or omit to use git diff. format='tags' (default) returns test tags for CI tag-filtering; format='paths' returns test file paths ready to pipe directly to a test runner (e.g. vitest). Feature hubs act as traversal boundaries in both modes.",inputSchema:{type:"object",properties:{root:{type:"string"},changedFiles:{type:"array",items:{type:"string"},description:"Changed files relative to root. Omit to read from git diff."},base:{type:"string",description:"Diff against this ref (e.g. 'origin/main') instead of only local working-tree/staged/untracked changes. Ignored when changedFiles is given. Needed in CI, where the checkout is already clean."},featureThreshold:{type:"number",description:"Min importers for a file to be treated as a feature hub (default: 5). A hub short-circuits traversal and emits a feature:<name> tag instead of all downstream tags."},format:{type:"string",enum:["tags","paths"],description:"Output format: 'tags' returns test tag names for CI filtering (default); 'paths' returns test file paths to pipe to a test runner."}},required:["root"]}},{name:"detect_features",description:"Identify feature hub files \u2014 non-test files that import many other internal modules (orchestrators / aggregators like src/parser.ts or src/cli/runner.ts). Returns a list sorted by import count descending.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to use the cached graph."},featureThreshold:{type:"number",description:"Min internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"query",description:"Filter the graph by category, tag, path, or other node metadata. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used. See docs/mcp.md for the full query DSL reference.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the graph. Omit to reuse the cached graph from a prior 'analyze' call."},filter:{type:"string",description:"Query string e.g. 'category:logic' or 'category:logic,tag:auth'. Supports: category, type, tag, path, external, importsFile, importedBy, minImports, maxImports, minSize, maxSize, hasDocstring, minCoverage, maxCoverage, minExportUsage, maxExportUsage, minComplexity, maxComplexity, minCognitiveComplexity, maxCognitiveComplexity, minCommits, maxCommits, isDocumented, isStale, lastAuthor. OR logic: any(key:val|key:val) matches if any single-key clause holds, ANDed with the rest of the query. sort: size|imports|commitCount90d|exportUsage|complexity|cognitiveComplexity, with sortDir: asc|desc (default desc). limit: N."},mermaid:{type:"boolean",description:"Return a Mermaid diagram (default: false)"},slim:{type:"boolean",description:"Compact response mode (default: true). Returns export names, meaningful tags, and a flat importsFiles path list \u2014 no edge objects, no mtime/size. Tags are filtered to kinds comment-marker and import only; function/class/variable/type/library tags are dropped in slim output. Use list_tags to see the full tag inventory, or pass slim: false to get every tag kind on matching nodes."}},required:["root","filter"]}},{name:"get_workspace_packages",description:"List all workspace packages detected in a monorepo: name, relativeRoot, and dependsOn. Answers from the repo layout and package.json manifests alone \u2014 no analyze() required and no graph build, so it is fast on large monorepos. Per-package nodeCount (and, for Gradle/sbt monorepos, exact dependsOn edges) are included only when a workspace graph is already built from a prior analyze() call; check the dependsOnResolved / nodeCountsResolved flags in the response.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"}},required:["root"]}},{name:"get_workspace_affected",description:"Cross-package blast-radius analysis. Returns every file that could be affected if a given file changes, annotated with the package it belongs to. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"},file:{type:"string",description:"Monorepo-root-relative path of the changed file (e.g. 'packages/shared/src/utils.ts')"}},required:["root","file"]}},{name:"get_type_graph",description:"Return type-level relationships for the project. Without a type name, returns an inventory of all interfaces, classes, enums, and type aliases with their file and kind. With a type name, returns which files import that type (usedByFiles) and which types the defining file imports (uses). Requires a prior analyze() call. Only covers TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},type:{type:"string",description:"Exact exported name of the type to look up (e.g. 'FileNode'). Omit to get the full type inventory."}},required:["root"]}},{name:"get_module_responsibility",description:"Return what each file is responsible for: its semantic role, JSDoc description (when present), exported symbol names, and which feature hub it belongs to. Pass specific paths to filter, or omit paths to get all files. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},paths:{type:"array",items:{type:"string"},description:"Project-relative file paths to include. Omit to return all files."},minOutDegree:{type:"number",description:"Min imports for a file to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_feature_graph",description:"Group files by domain: returns which files each feature hub (high-import orchestrator) transitively owns. Each file is assigned to the most specific hub that can reach it (lowest out-degree wins). Use this instead of a full query when answering 'what files are in the X feature/module?' \u2014 it returns only paths grouped by hub, so it's substantially smaller than a full graph query for the same question; compare output sizes yourself if you need an exact figure for your repo.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minOutDegree:{type:"number",description:"Minimum internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_call_graph",description:"Look up callers and callees for a named function. Returns the file that defines the function, all files/functions that call it, and all files/functions it calls. Always requires a function name \u2014 never returns the full call graph unfiltered. Call edges are only populated for TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},function:{type:"string",description:"Exact name of the function to look up (e.g. 'parseFile')."}},required:["root","function"]}},{name:"find_symbol",description:"Find every file that exports a symbol by exact name, with the best available usage info per match. Precision varies by the defining file's language \u2014 check each match's `precision` field ('call' | 'file-level') before trusting caller/importer results as symbol-exact. See docs/mcp.md for per-language coverage details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},name:{type:"string",description:"Exact export name to look up (e.g. 'parseFile')."}},required:["root","name"]}},{name:"get_api_surface",description:"Build the API surface report for a project: every exported symbol resolved to its defining file and kind, partitioned into internalFiles, unreachableFromEntry, and testFiles. Requires a prior analyze() call. When entryPoints is omitted, auto-detects from package.json exports/main/module. See docs/mcp.md for the export* expansion and partition semantics.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},entryPoints:{type:"array",items:{type:"string"},description:"Project-relative paths of public entry points (e.g. ['src/index.ts', 'src/utils.ts']). Omit to auto-detect from package.json exports / main / module fields."}},required:["root"]}},{name:"clear_cache",description:"Drop the cached dependency graph and loaded mokosh.config.json for a project root, forcing the next analyze() call to rebuild from disk and re-read config. Call this after editing source files OR mokosh.config.json mid-session \u2014 otherwise get_affected, get_dependencies, and other query tools will reason from stale data (or a stale config).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root to invalidate."}},required:["root"]}},{name:"apply_tags",description:"Write @tag annotations into test file source code based on the dependency graph, as an idempotent block \u2014 re-running is safe, the existing block is replaced in place. Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call. See docs/mcp.md for tag-kind and per-language block syntax details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root."},dryRun:{type:"boolean",description:"When true, computes which files would change but does not write to disk (default: false)."}},required:["root"]}}];function En(){let t=new Kt,e=new ef({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(rf,async()=>({tools:Li})),e.setRequestHandler(tf,async r=>{let{name:n,arguments:s}=r.params,o=s,a={analyze:c=>pi(t,c),get_dependencies:c=>ui(t,c),get_dependents:c=>mi(t,c),get_affected:c=>fi(t,c),compare_branches:c=>gi(t,c),get_callers:c=>di(t,c),find_symbol:c=>Ii(t,c),find_unused:c=>hi(t,c),find_uncovered:c=>xi(t,c),list_tags:c=>yi(t,c),check_doc_drift:c=>bi(t,c),find_complex_functions:c=>Si(t,c),find_risk_hotspots:c=>ki(t,c),find_duplicates:c=>vi(t,c),propose_tags:c=>Ci(t,c),detect_features:c=>wi(t,c),get_type_graph:c=>Ai(t,c),get_module_responsibility:c=>Ni(t,c),get_feature_graph:c=>Ri(t,c),get_call_graph:c=>Di(t,c),get_api_surface:c=>Mi(t,c),query:c=>Ei(t,c),get_workspace_packages:c=>Ti(t,c),get_workspace_affected:c=>Fi(t,c),clear_cache:c=>Pi(t,c),apply_tags:c=>_i(t,c)}[n];if(!a)throw new Error(`Unknown tool: ${n}`);try{return li(o.root),await a(o)}catch(c){return{content:[{type:"text",text:`Error: ${c instanceof Error?c.message:String(c)}`}],isError:!0}}}),e}async function sf(){let t=En(),e=new nf;await t.connect(e)}sf().catch(console.error);export{En as createMcpServer};
|
|
41
57
|
//# sourceMappingURL=mcp.mjs.map
|