@omfalos/mokosh 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.mjs CHANGED
@@ -1,30 +1,31 @@
1
1
  #!/usr/bin/env node
2
- var Be=(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 sn from"path";import{fileURLToPath as nn}from"url";var on=()=>nn(import.meta.url),an=()=>sn.dirname(on()),u=an();import{StdioServerTransport as Va}from"@modelcontextprotocol/sdk/server/stdio.js";import{Server as Ja}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Ha,ListToolsRequestSchema as Qa}from"@modelcontextprotocol/sdk/types.js";import Ba from"fs";import He from"fs";import Qt from"path";var pn=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],Bt=[];function ye(t){Bt.push(t)}function Ut(t){return[...pn,...Bt].some(e=>typeof e=="string"?t.includes(e):e instanceof RegExp?e.test(t):e(t))}var cn=[".test.",".spec.","-test.","-spec."],Kt=[];function xe(t){Kt.push(t)}function q(){return[...cn,...Kt]}var ln=["jest","vitest","playwright","cypress","@testing-library/"],Jt=[];function Se(t){Jt.push(t)}function Ue(){return[...ln,...Jt]}var Ht=.8;function Ke(t){Ht=t}function Je(){return Ht}var un=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function X(t,{allowJs:e=!0,isExplicitPath:r=!1}={}){if(r){let s=Qt.resolve(t);return He.existsSync(s)?s.endsWith(".json")?Vt(s):e?qt(s):{}:{}}for(let s of un){let n=Qt.resolve(t,s);if(He.existsSync(n)){if(s.endsWith(".json"))return Vt(n);if(e)return qt(n)}}return{}}function Vt(t){return JSON.parse(He.readFileSync(t,"utf-8"))}function qt(t){let e=Be(t);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function Qe(t){for(let e of t.configMatchers??[])ye(e);for(let e of t.testPatterns??[])xe(e);for(let e of t.testLibraries??[])Se(e);t.barrelThreshold!==void 0&&Ke(t.barrelThreshold)}function O(t){return{gitStats:t?.gitStats??!1,parallelParsing:t?.parallelParsing,pathAliases:t?.pathAliases}}var Ve=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"],qe=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".feature",".md",".mdx"];import fn from"fs";import Xt from"path";function Xe(t,e){let r=Xt.resolve(t,e);try{let s=fn.readFileSync(r,"utf-8"),n=JSON.parse(s),o=new Map;for(let[i,a]of Object.entries(n)){if(i==="total")continue;let p=a?.lines?.pct;if(typeof p!="number")continue;let c=Xt.relative(t,i);o.set(c,p)}return o}catch{return new Map}}var be={serialize(t){let e=["graph TD"],r=new Set;for(let s of t.nodes.values()){let n=`"${s.path}"`;for(let o of s.imports){if(!o.toPath)continue;let i=`"${o.toPath}"`,a=`${s.path} -> ${o.toPath}`;if(!r.has(a)){let p=o.isStyle?"-- styles -->":"-->";e.push(` ${n} ${p} ${i}`),r.add(a)}}}return e.join(`
3
- `)}};import Yt from"fs";import gn from"path";function Ye(t,e){let r=t.replace(/^\.\//,"");if(e.nodes.has(r))return r;let s=r.replace(/^dist\//,"src/").replace(/\.(js|mjs|cjs)$/,".ts");return e.nodes.has(s)?s:null}function Zt(t,e){if(typeof t=="string")return Ye(t,e);if(t&&typeof t=="object"){let r=t;for(let s of["import","require","default"]){let n=Zt(r[s],e);if(n)return n}}return null}function dn(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 hn(t,e){let r=new Set,s=new Set,n=[...e];for(;n.length;){let o=n.shift();if(s.has(o))continue;s.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 c=t.nodes.get(a.toPath);if(c)for(let m of c.exports)r.add(m.name);n.push(a.toPath)}else for(let c of a.symbols)r.add(c)}}}return r}function Ze(t,e){let r=[],s=gn.join(e,"package.json");if(Yt.existsSync(s))try{let n=JSON.parse(Yt.readFileSync(s,"utf8"));if(n.exports&&typeof n.exports=="object"&&!Array.isArray(n.exports))for(let o of Object.values(n.exports)){let i=Zt(o,t);i&&!r.includes(i)&&r.push(i)}else if(typeof n.exports=="string"){let o=Ye(n.exports,t);o&&r.push(o)}if(r.length===0)for(let o of[n.main,n.module].filter(Boolean)){let i=Ye(o,t);i&&!r.includes(i)&&r.push(i)}}catch{}if(r.length===0){for(let n of["src/index.ts","src/index.js","index.ts","index.js"])if(t.nodes.has(n)){r.push(n);break}}return r}function yn(t,e){let r=new Set(e);for(let s of e)t.traverse(s,n=>(r.add(n.path),!0),{direction:"outgoing"});return r}function xn(t,e,r){let s=new Map;for(let n of e){if(r.includes(n))continue;let o=t.nodes.get(n);if(!o)continue;let i=o.category==="barrel";for(let a of o.exports){let p=s.get(a.name),c=!!(a.signature||a.doc);(!p||c&&!i)&&s.set(a.name,{file:n,symbol:a})}}return s}function Sn(t,e,r,s){let n=[];for(let o of t){let i=e.get(o),a=s.flatMap(g=>r.nodes.get(g)?.exports??[]).find(g=>g.name===o),p=i?.symbol??a,c=i?.file??s.find(g=>r.nodes.get(g)?.exports.some(d=>d.name===o))??s[0],m={name:o,definedIn:c,kind:dn(p?.signature)};p?.doc&&(m.doc=p.doc),p?.signature&&(m.signature=p.signature),n.push(m)}return n.sort((o,i)=>o.name.localeCompare(i.name)),n}function bn(t,e,r){let s=p=>t.nodes.get(p)?.category==="test",n=[...e].filter(p=>!r.includes(p)&&!s(p)),o=[...t.nodes.keys()].filter(p=>!e.has(p)),i=o.filter(p=>!s(p)),a=o.filter(p=>s(p));return{internalFiles:n,unreachableFromEntry:i,testFiles:a}}function et(t,e){if(e.length===0)throw new Error("buildApiSurface requires at least one entry point");for(let c of e)if(!t.nodes.has(c))throw new Error(`Entry point not found in graph: ${c}`);let r=yn(t,e),s=xn(t,r,e),n=hn(t,e),o=Sn(n,s,t,e),{internalFiles:i,unreachableFromEntry:a,testFiles:p}=bn(t,r,e);return{entryPoints:e,publicExports:o,internalFiles:i,unreachableFromEntry:a,testFiles:p}}function tt(t,e){let r=null,s=[];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&&s.push({file:o.path,callerFunction:i.from})}let n=[];if(r){let o=t.nodes.get(r);for(let i of o?.callEdges??[])i.from===e&&n.push({file:i.toFile,calleeFunction:i.to})}return{functionName:e,definedIn:r,callers:s,callees:n}}import Tp from"fs";import Ap from"path";function er(t){let e=[...t.nodes.entries()].sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>`${s}:${n.mtime}:${n.size}`).join("|"),r=2166136261;for(let s=0;s<e.length;s++)r^=e.charCodeAt(s),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}function rt(t){let e=new Map;for(let r of t.nodes.keys()){let s=[];t.traverse(r,n=>(n.path!==r&&s.push(n.path),!0),{direction:"incoming"}),e.set(r,s)}return{impact:e,graphHash:er(t)}}function st(t,e){return t.impact.get(e)??[]}import ve from"path";function vn(t){let e=new Map;for(let[r,s]of t){let n=s.imports.filter(o=>o.toPath&&!o.isExternal).length;n>0&&e.set(r,n)}return e}function kn(t,e,r){let s=new Map;for(let[n,o]of e){if(o<r)continue;let i=t.get(n);if(!i||i.category==="test"||i.category==="barrel")continue;let a=ve.extname(n),p=ve.basename(n,a),c=p==="index"?ve.basename(ve.dirname(n)):p;s.set(n,{path:n,outDegree:o,tag:`feature:${c}`})}return s}function G(t,e){let r=e?.minOutDegree??5;return kn(t,vn(t),r)}var Cn=(t,e)=>t.outDegree-e.outDegree;function wn(t,e){let r=new Map;for(let s of e.values()){let n=new Set;t.traverse(s.path,o=>(o.path!==s.path&&n.add(o.path),!0),{direction:"outgoing"}),r.set(s.path,n)}return r}function En(t,e,r,s){let n=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||s(a,i)<0)&&(i=a);i&&n.set(o,i.path)}return n}function Fn(t,e){let r=new Map;for(let s of t.values()){let n=s.tag.replace("feature:",""),o=[];for(let[i,a]of e)a===s.path&&o.push(i);r.set(n,{hub:s.path,outDegree:s.outDegree,files:o})}return r}function Tn(t,e,r){let s=[];for(let n of t.keys())!e.has(n)&&!r.has(n)&&s.push(n);return s}function Y(t,e){let r=e?.detectFn??G,s=e?.hubComparator??Cn,n=r(t.nodes,e),o=wn(t,n),i=En(t.nodes,n,o,s);return{features:Fn(n,i),unassigned:Tn(t.nodes,n,i)}}var tr=new Set(["typescript","javascript","python","go","scss","less","lua","coffeescript"]),ke=new Set(["typescript","javascript","python"]),Ce=new Set(["typescript","javascript"]);function nt(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,s])=>({type:r,fileCount:s,exportsTracked:tr.has(r),importSymbolsTracked:ke.has(r),callEdgesTracked:Ce.has(r)})).sort((r,s)=>s.fileCount-r.fileCount)}var Z=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let r=new Set(this.nodes.keys());return e.filter(s=>!r.has(s))}findHighExportUsage(e){let r=[];for(let s of this.nodes.values()){if(s.maxExportUsage===void 0||s.maxExportUsage<e)continue;let n=s.imports.reduce((o,i)=>(i.exportUsageRatio??0)>(o?.exportUsageRatio??0)?i:o,null);r.push({path:s.path,maxExportUsage:s.maxExportUsage,tightestDep:n?.toPath??""})}return r.sort((s,n)=>n.maxExportUsage-s.maxExportUsage)}findCycles(){let e=[],r=new Set,s=new Set,n=[],o=i=>{r.add(i),s.add(i),n.push(i);let a=this.nodes.get(i);if(a){for(let p of a.imports)if(!(!p.toPath||p.isExternal))if(s.has(p.toPath)){let c=n.indexOf(p.toPath);e.push([...n.slice(c),p.toPath])}else r.has(p.toPath)||o(p.toPath)}s.delete(i),n.pop()};for(let i of this.nodes.keys())r.has(i)||o(i);return e}};var P=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 s of e.nodes)r.set(s.path,s);return new t(r)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let r of this.nodes.values())for(let s of r.imports)if(s.toPath){let n=e.get(s.toPath)||[];n.push(r.path),e.set(s.toPath,n)}return this._incomingEdgesCache=e,e}dfs(e,r,s,n){let o=new Set,i=s.maxDepth??1/0,a=(p,c,m)=>{if(c>i||o.has(p))return;let g=this.nodes.get(p);if(g&&(o.add(p),r(g,c,m)!==!1))for(let d of n(p))a(d,c+1,p)};a(e,0,null)}traverse(e,r,s={}){let n=s.direction??"outgoing",o=n==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,r,s,i=>n==="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 s of r.callEdges??[]){let n=e.get(s.toFile)??[];n.push(r.path),e.set(s.toFile,n)}return this._callIncomingCache=e,e}traverseCalls(e,r,s={}){let n=s.direction??"outgoing",o=n==="incoming"?this.getCallIncomingCache():null;this.dfs(e,r,s,i=>n==="outgoing"?this.nodes.get(i)?.callEdges?.map(a=>a.toFile)??[]:o?.get(i)??[])}getCallers(e){let r=[];return this.traverseCalls(e,s=>(s.path!==e&&r.push(s.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(s=>this.nodes.get(s.toPath)).filter(s=>s!==void 0):[]}findUnusedFiles(e){return new Z(this.nodes).findUnusedFiles(e)}findCycles(){return new Z(this.nodes).findCycles()}};var D=class{affectedSymbols=new Map;constructor(e,r){this.affectedSymbols.set(e,new Set(["default",...r]))}updateAffectedSymbols(e,r){let s=this.affectedSymbols.get(r)||new Set,n=e.imports.find(p=>p.toPath===r);if(!n)return!1;let o=n.symbols||["*"],i=new Set;for(let p of o)(p==="*"||s.has("*")||s.has(p))&&i.add("*");if(i.size===0)return!1;let a=this.affectedSymbols.get(e.path)||new Set;for(let p of i)a.add(p);return this.affectedSymbols.set(e.path,a),!0}};function ee(t,e){let r=t.nodes.get(e);if(r)return{category:r.category,exports:r.exports.map(s=>s.name)}}function ot(t,e,r=1){let s=[];return t.traverse(e,(n,o,i)=>{if(n.path===e)return!0;let a=i?t.nodes.get(i)?.imports.find(p=>p.toPath===n.path):void 0;return s.push({path:n.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"outgoing",maxDepth:r}),s}function te(t,e){let r=[];return t.traverse(e,s=>{if(s.path===e)return!0;let n=s.imports.find(o=>o.toPath===e);return r.push({path:s.path,...n?.symbols?{symbols:n.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),r}function it(t,e,r={}){let{testsOnly:s=!1,changedSymbols:n}=r,o=n?new D(e,n):null,i=[];return t.traverse(e,(a,p,c)=>{if(a.path===e)return!0;if(o&&c&&!o.updateAffectedSymbols(a,c))return!1;let m=a.category==="test"||a.tags.some(g=>g.name==="test");return(!s||m)&&i.push(a.path),!0},{direction:"incoming"}),i}function at(t,e,r={}){let{depth:s=1,withEdgeDetail:n=!1}=r,o=[];return t.traverseCalls(e,i=>{if(i.path===e)return!0;let a={file:i.path};return n&&(a.edges=(i.callEdges??[]).filter(p=>p.toFile===e).map(p=>({from:p.from,to:p.to}))),o.push(a),!0},{direction:"incoming",maxDepth:s}),o}function pt(t,e={}){let{metric:r="cognitiveComplexity",threshold:s=10,limit:n=20}=e;return[...t.nodes.values()].flatMap(o=>(o.functions??[]).filter(i=>i[r]>=s).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,n)}function ct(t){return{nodes:t.nodes.map(r=>({path:r.path,type:r.type,category:r.category,exports:r.exports.map(s=>s.name),tags:r.tags.filter(s=>s.kind==="comment-marker"||s.kind==="import").map(s=>s.name),importsFiles:r.imports.filter(s=>!s.isExternal&&s.toPath).map(s=>s.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 lt(t){let e=t.getPackageDependencies(),r=Array.from(t.packages.values()).map(({graph:s,pkg:n})=>({name:n.name,relativeRoot:n.relativeRoot,nodeCount:s.nodes.size,dependsOn:e.get(n.name)??[]}));return{monorepoType:t.type,packageCount:r.length,packages:r}}function ut(t){return[...t.nodes.values()].some(e=>e.coveragePct!==void 0)}function rr(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 x(e,"component")||x(e,"components")?"component":x(e,"controller")||x(e,"controllers")?"controller":x(e,"middleware")?"middleware":x(e,"router")||x(e,"routes")||x(e,"route")?"router":x(e,"store")||x(e,"stores")?"store":x(e,"service")||x(e,"services")?"service":x(e,"handler")||x(e,"handlers")?"handler":x(e,"adapter")||x(e,"adapters")?"adapter":x(e,"plugin")||x(e,"plugins")?"plugin":x(e,"api")?"api":x(e,"cli")||x(e,"commands")||re(e)==="cli"?"cli":x(e,"util")||x(e,"utils")||x(e,"helper")||x(e,"helpers")?"util":x(e,"model")||x(e,"models")||re(e)==="model"?"model":x(e,"parser")||x(e,"parsers")||re(e)==="parser"?"parser":re(e)==="builder"?"builder":re(e)==="resolver"?"resolver":"other"}function x(t,e){return t.includes(`/${e}/`)||t.includes(`/${e}.`)}function re(t){let e=t.slice(t.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function ft(t,e){let r=Y(t,e),s=new Map;for(let[o,i]of r.features){for(let a of i.files)s.set(a,o);s.set(i.hub,o)}let n=new Map;for(let o of t.nodes.values()){let i=s.get(o.path);n.set(o.path,{path:o.path,role:rr(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return n}function mt(t,e){let r=[];for(let s of t.nodes.values())if(s.exports.some(n=>n.name===e))if(Ce.has(s.type)){let n=[];for(let o of t.nodes.values())for(let i of o.callEdges??[])i.to===e&&n.push({file:o.path,callerFunction:i.from});r.push({path:s.path,category:s.category,precision:"call",callers:n})}else if(ke.has(s.type)){let n=[];for(let o of t.nodes.values())for(let i of o.imports)i.toPath===s.path&&i.symbols?.includes(e)&&n.push({file:o.path,symbols:i.symbols});r.push({path:s.path,category:s.category,precision:"import-symbol",importers:n})}else{let n=te(t,s.path).map(o=>({file:o.path,...o.symbols?{symbols:o.symbols}:{}}));r.push({path:s.path,category:s.category,precision:"file-level",importers:n})}return r}function Pn(t){return t?t.startsWith("interface ")?"interface":t.startsWith("class ")?"class":t.startsWith("enum ")?"enum":"type":"type"}function An(t,e){if(e==="type-only")return!0;let r=t.signature??"";return r.startsWith("interface ")||r.startsWith("class ")||r.startsWith("enum ")}function gt(t){let e=new Map;for(let s of t.nodes.values())if(!(s.type!=="typescript"&&s.type!=="javascript"))for(let n of s.exports){if(!An(n,s.category))continue;let o=`${s.path}::${n.name}`;e.set(o,{name:n.name,file:s.path,kind:Pn(n.signature),...n.doc?{doc:n.doc}:{}})}let r=[];for(let s of t.nodes.values())if(!(s.type!=="typescript"&&s.type!=="javascript")){for(let n of s.imports)if(!(!n.toPath||n.isExternal||!n.symbols?.length))for(let o of n.symbols)e.has(`${n.toPath}::${o}`)&&r.push({fromFile:s.path,toType:o,toFile:n.toPath})}return{types:e,edges:r}}function dt(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 s=new Set,n=new Map;for(let o of t.edges)if(o.toType===e&&o.toFile===r.file&&s.add(o.fromFile),o.fromFile===r.file){let i=t.types.get(`${o.toFile}::${o.toType}`);i&&n.set(`${i.file}::${i.name}`,i)}return{type:r,usedByFiles:Array.from(s),uses:Array.from(n.values())}}import zn from"path";import yt from"fs";import ir from"path";import se from"fs";import w from"path";import sr from"fs";import lc from"path";function nr(t){try{return sr.statSync(t,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function we(t){try{return sr.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}function ht(t,e){let r=w.join(e,"package.json");if(!se.existsSync(r))return null;let s={};try{s=JSON.parse(se.readFileSync(r,"utf-8"))}catch{return null}let n=s.name;return n?{name:n,root:e,relativeRoot:w.relative(t,e),entryPoints:Mn(e,s)}:null}function Mn(t,e){let r=[];if(e.exports){let n=e.exports;if(typeof n=="string")r.push(w.join(t,n));else if(typeof n=="object"&&n!==null){let o=n["."];if(typeof o=="string")r.push(w.join(t,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&r.push(w.join(t,i))}}}e.main&&r.push(w.join(t,e.main));for(let n of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])r.push(w.join(t,n));let s=r.filter(we);return s.length>0?s.slice(0,1):r.slice(0,1)}function j(t,e){let r=[],s=new Set;for(let n of e){let o=n.replace(/\/$/,"").replace(/^\.\//,"");In(t,o,s,r)}return r}function In(t,e,r,s){if(!e.includes("*")){Nn(t,e,r,s);return}let n=e.split("/");n.includes("**")?Rn(t,n,r,s):Gn(t,n,r,s)}function Nn(t,e,r,s){let n=w.join(t,e);if(r.has(n)||!nr(n))return;r.add(n);let o=ht(t,n);o&&s.push(o)}function Rn(t,e,r,s){let n=w.join(t,e[0]==="**"?"":e[0]??"");or(t,n,r,s)}function Gn(t,e,r,s){let n=e.findIndex(a=>a.includes("*")),o=w.join(t,...e.slice(0,n)),i;try{i=se.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let p=w.join(o,a.name);if(r.has(p))continue;r.add(p);let c=ht(t,p);c&&s.push(c)}}function or(t,e,r,s){let n;try{n=se.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of n){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=w.join(e,o.name);if(se.existsSync(w.join(i,"package.json"))&&!r.has(i)){r.add(i);let a=ht(t,i);a&&s.push(a)}else or(t,i,r,s)}}var ar={type:"npm",detect(t){let e=ir.join(t,"package.json");if(!yt.existsSync(e))return null;let r;try{r=JSON.parse(yt.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r||yt.existsSync(ir.join(t,"yarn.lock")))return null;let s=Array.isArray(r)?r:r.packages??[];return s.length===0?null:j(t,s)}};import W from"fs";import v from"path";var pr={type:"nx",detect(t){return W.existsSync(v.join(t,"nx.json"))?cr(t,t,new Set,0).map(r=>Dn(t,r,v.join(r,"project.json"))).filter(r=>r!==null):null}};function cr(t,e,r,s){if(s>4)return[];let n;try{n=W.readdirSync(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let i of n){if(!i.isDirectory())continue;let a=i.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let p=v.join(e,a);W.existsSync(v.join(p,"project.json"))&&!r.has(p)?(r.add(p),o.push(p)):o.push(...cr(t,p,r,s+1))}return o}function Dn(t,e,r){let s={};try{s=JSON.parse(W.readFileSync(r,"utf-8"))}catch{return null}let n=s.name,o,i,a=v.join(e,"package.json");if(W.existsSync(a))try{let p=JSON.parse(W.readFileSync(a,"utf-8"));n=p.name??n,o=p.main,i=p.exports}catch{}return n?{name:n,root:e,relativeRoot:v.relative(t,e),entryPoints:_n(e,s,o,i)}:null}function _n(t,e,r,s){let n=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=v.resolve(t,"../..");n.push(v.resolve(a,o)),n.push(v.resolve(t,o))}if(s){let a=s;if(typeof a=="string")n.push(v.join(t,a));else if(typeof a=="object"&&a!==null){let p=a["."];typeof p=="string"&&n.push(v.join(t,p))}}if(r&&n.push(v.join(t,r)),e.sourceRoot){let a=v.resolve(t,"../.."),p=v.resolve(a,e.sourceRoot);n.push(v.join(p,"index.ts"),v.join(p,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])n.push(v.join(t,a));let i=n.filter(we);return i.length>0?i.slice(0,1):n.slice(0,1)}import lr from"fs";import Ln from"path";import{load as On}from"js-yaml";var ur={type:"pnpm",detect(t){let e=Ln.join(t,"pnpm-workspace.yaml");if(!lr.existsSync(e))return null;let r=[];try{r=On(lr.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return j(t,r)}};import jn from"fs";import Wn from"path";var fr={type:"turborepo",detect(t){return jn.existsSync(Wn.join(t,"turbo.json"))?[]:null}};import xt from"fs";import mr from"path";var gr={type:"yarn",detect(t){if(!xt.existsSync(mr.join(t,"yarn.lock")))return null;let e=mr.join(t,"package.json");if(!xt.existsSync(e))return null;let r;try{r=JSON.parse(xt.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r)return null;let s=Array.isArray(r)?r:r.packages??[];return s.length===0?null:j(t,s)}};var dr=[];function A(t){dr.push(t)}function hr(){return dr}A(fr);A(pr);A(ur);A(gr);A(ar);function ne(t,e=hr()){let r=zn.resolve(t),s=new Map,n=[];for(let i of e){let a=i.detect(r);if(a!==null){n.push(i.type);for(let p of a)s.has(p.name)||s.set(p.name,p)}}if(n.length===0)return{root:r,type:"none",types:[],packages:[],packageMap:new Map};let o=Array.from(s.values());return{root:r,type:n[0],types:n,packages:o,packageMap:new Map(o.map(i=>[i.name,i]))}}var oe=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:s}of this.packages.values()){let n=new Set;for(let o of r.nodes.values())for(let i of o.imports)i.isWorkspace&&i.workspacePackage&&n.add(i.workspacePackage);e.set(s.name,[...n])}return e}getAffectedAcrossPackages(e){let r=this.getPackageForFile(e);if(!r)return[];let s=this.packages.get(r.name);if(!s)return[];let n=[];s.graph.traverse(e,o=>(o.path!==e&&n.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(c=>c.isWorkspace&&c.workspacePackage===r.name)&&n.push({file:a.path,package:i.name});return n}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:s,nodes:n}of e.packages){let o=new Map(n.map(a=>[a.path,a])),i=new P(o);r.packages.set(s.name,{graph:i,pkg:{...s,root:""}})}return r}};var yr=new Map;function z(t,e){yr.set(t,e)}function xr(t){return yr.get(t)}function Sr(t,e){return e.startsWith("!")?t!==e.slice(1):t===e}function $n(t,e){return e.startsWith("!")?!t.includes(e.slice(1)):t.includes(e)}var Bn=(t,e)=>!e.category||Sr(t.category,e.category),Un=(t,e)=>!e.type||Sr(t.type,e.type),Kn=(t,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?t.lastAuthor!==e.lastAuthor.slice(1):t.lastAuthor!==void 0&&t.lastAuthor===e.lastAuthor:!0,Jn=(t,e)=>!e.path||$n(t.path,e.path),Hn=(t,e)=>e.isExternal===void 0?!0:t.imports.some(s=>s.isExternal)===e.isExternal,Qn=(t,e)=>{if(!e.tags||e.tags.length===0)return!0;let r=e.tags.filter(n=>!n.startsWith("!")),s=e.tags.filter(n=>n.startsWith("!")).map(n=>n.slice(1));return!(r.length>0&&!r.some(n=>t.tags.some(o=>o.name===n))||s.some(n=>t.tags.some(o=>o.name===n)))},Vn=(t,e)=>!e.allTags?.length||e.allTags.every(r=>t.tags.some(s=>s.name===r)),qn=(t,e)=>!e.importsFile||t.imports.some(r=>r.toPath?.includes(e.importsFile)),Xn=(t,e,r)=>e.importedBy===void 0?!0:(r?.get(t.path)??[]).some(n=>n.includes(e.importedBy)),Yn=(t,e)=>e.minImports===void 0||t.imports.length>=e.minImports,Zn=(t,e)=>e.maxImports===void 0||t.imports.length<=e.maxImports,eo=(t,e)=>e.minSize===void 0||t.size>=e.minSize,to=(t,e)=>e.maxSize===void 0||t.size<=e.maxSize,ro=(t,e)=>e.hasDocstring===void 0||!!t.description===e.hasDocstring,so=(t,e)=>e.isDocumented===void 0||!!t.documentedBy?.length===e.isDocumented,no=(t,e)=>e.isStale===void 0||!!t.staleFor?.length===e.isStale,oo=(t,e)=>e.minCoverage===void 0||(t.coveragePct??101)>=e.minCoverage,io=(t,e)=>e.maxCoverage===void 0||(t.coveragePct??0)<=e.maxCoverage,ao=(t,e)=>e.minExportUsage===void 0||(t.avgExportUsage??-1)>=e.minExportUsage,po=(t,e)=>e.maxExportUsage===void 0||(t.avgExportUsage??0)<=e.maxExportUsage,co=(t,e)=>e.minComplexity===void 0||(t.complexity??-1/0)>=e.minComplexity,lo=(t,e)=>e.maxComplexity===void 0||(t.complexity??0)<=e.maxComplexity,uo=(t,e)=>e.minCognitiveComplexity===void 0||(t.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,fo=(t,e)=>e.maxCognitiveComplexity===void 0||(t.cognitiveComplexity??0)<=e.maxCognitiveComplexity,mo=(t,e)=>e.minCommits===void 0||(t.commitCount90d??-1/0)>=e.minCommits,go=(t,e)=>e.maxCommits===void 0||(t.commitCount90d??0)<=e.maxCommits,ho=(t,e,r)=>!e.any?.length||e.any.some(s=>ie(t,s,r)),yo=[Bn,Un,Kn,Jn,Hn,Qn,Vn,qn,Xn,Yn,Zn,eo,to,ro,so,no,oo,io,ao,po,co,lo,uo,fo,mo,go,ho];function ie(t,e,r){return yo.every(s=>s(t,e,r))}function Ee(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 p=r.get(a.toPath)??[];p.push(i.path),r.set(a.toPath,p)}}let s=t.nodes.filter(i=>ie(i,e,r)),n=new Set(s.map(i=>i.path)),o=s.map(i=>({...i,imports:i.imports.filter(a=>!a.toPath||n.has(a.toPath))}));if(e.sort){let i=e.sortDir==="asc"?-1:1;o.sort((a,p)=>{let c=0;return e.sort==="size"?c=p.size-a.size:e.sort==="imports"?c=p.imports.length-a.imports.length:e.sort==="commitCount90d"?c=(p.commitCount90d??0)-(a.commitCount90d??0):e.sort==="exportUsage"?c=(p.avgExportUsage??0)-(a.avgExportUsage??0):e.sort==="complexity"?c=(p.complexity??0)-(a.complexity??0):e.sort==="cognitiveComplexity"&&(c=(p.cognitiveComplexity??0)-(a.cognitiveComplexity??0)),c*i})}return e.limit!==void 0&&o.splice(e.limit),{nodes:o,cycles:t.cycles?.filter(i=>i.every(a=>n.has(a)))??void 0}}function br(t,e){let r=e.indexOf(":");if(r===-1)return;let s=e.slice(0,r).trim().toLowerCase(),n=e.slice(r+1).trim();if(!(!s||!n))switch(s){case"category":t.category=n;break;case"type":t.type=n;break;case"tag":case"tags":n.includes("+")?t.allTags=[...t.allTags??[],...n.split("+")]:t.tags=[...t.tags??[],n];break;case"path":t.path=n;break;case"external":t.isExternal=n.toLowerCase()==="true";break;case"importsfile":t.importsFile=n;break;case"importedby":t.importedBy=n;break;case"minimports":t.minImports=parseInt(n,10);break;case"maximports":t.maxImports=parseInt(n,10);break;case"minsize":t.minSize=parseInt(n,10);break;case"maxsize":t.maxSize=parseInt(n,10);break;case"sort":t.sort=n;break;case"sortdir":t.sortDir=n.toLowerCase()==="asc"?"asc":"desc";break;case"limit":t.limit=parseInt(n,10);break;case"hasdocstring":t.hasDocstring=n.toLowerCase()!=="false";break;case"mincoverage":t.minCoverage=parseInt(n,10);break;case"maxcoverage":t.maxCoverage=parseInt(n,10);break;case"minexportusage":t.minExportUsage=parseFloat(n);break;case"maxexportusage":t.maxExportUsage=parseFloat(n);break;case"mincomplexity":t.minComplexity=parseInt(n,10);break;case"maxcomplexity":t.maxComplexity=parseInt(n,10);break;case"mincognitivecomplexity":t.minCognitiveComplexity=parseInt(n,10);break;case"maxcognitivecomplexity":t.maxCognitiveComplexity=parseInt(n,10);break;case"mincommits":t.minCommits=parseInt(n,10);break;case"maxcommits":t.maxCommits=parseInt(n,10);break;case"isdocumented":t.isDocumented=n.toLowerCase()!=="false";break;case"isstale":t.isStale=n.toLowerCase()!=="false";break;case"lastauthor":t.lastAuthor=n;break}}function xo(t){let e=[];for(let r of t.split("|")){let s=r.trim();if(!s)continue;let n={};br(n,s),Object.keys(n).length>0&&e.push(n)}return e}function Fe(t){let e={},r=t.split(",");for(let s of r){let n=s.trim();if(n.toLowerCase().startsWith("any(")&&n.endsWith(")")){let o=n.slice(4,-1),i=xo(o);i.length>0&&(e.any=[...e.any??[],...i]);continue}br(e,s)}return e}import Nr from"fs/promises";import $o from"path";import wt from"path";import Ge from"typescript";import kr from"path";import Cr from"typescript";import k from"typescript";var vr=new Set(["describe","test","it"]);function $(t){let e=[];for(let r of t.statements){if(!k.isExpressionStatement(r))continue;let s=r.expression;if(!k.isCallExpression(s))continue;let n=s.expression;k.isIdentifier(n)&&vr.has(n.text)&&e.push(s),k.isPropertyAccessExpression(n)&&k.isIdentifier(n.expression)&&vr.has(n.expression.text)&&e.push(s)}return e}function B(t,e,r){for(let s of t.arguments){if(!k.isObjectLiteralExpression(s))continue;let n=s.properties.find(o=>k.isPropertyAssignment(o)&&k.isIdentifier(o.name)&&o.name.text===e);if(!(!n||!k.isArrayLiteralExpression(n.initializer)))return n.initializer.elements.filter(k.isStringLiteral).map(o=>o.text)}return null}function U(t,e,r,s){if(t.arguments.length===0)return null;for(let o=1;o<t.arguments.length;o++){let i=t.arguments[o];if(!k.isObjectLiteralExpression(i))continue;let a=i.properties.find(c=>k.isPropertyAssignment(c)&&k.isIdentifier(c.name)&&c.name.text===e);if(a)return{start:a.initializer.getStart(s),end:a.initializer.getEnd(),text:r};let p=i.getEnd()-1;return{start:p,end:p,text:`${i.properties.length>0?", ":""}${e}: ${r}`}}let n=t.arguments[t.arguments.length-1];return{start:n.getStart(s),end:n.getStart(s),text:`{ ${e}: ${r} }, `}}function K(t,e,r){let s=t.arguments;for(let n=1;n<s.length;n++){let o=s[n];if(!k.isObjectLiteralExpression(o))continue;let i=o.properties.findIndex(p=>k.isPropertyAssignment(p)&&k.isIdentifier(p.name)&&p.name.text===e);if(i<0)continue;if(o.properties.length===1)return{start:s[n-1].getEnd(),end:o.getEnd(),text:""};let a=o.properties[i];return i===o.properties.length-1?{start:o.properties[i-1].getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(r),end:o.properties[i+1].getStart(r),text:""}}return null}function J(t,e){let r=[...e].sort((n,o)=>o.start-n.start),s=t;for(let n of r)s=s.slice(0,n.start)+n.text+s.slice(n.end);return s}function H(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}var T=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function So(t){return H(t.map(e=>`@${e}`))}function bo(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}var Te=class{name="cypress";canHandle(e){return T.has(kr.extname(e).toLowerCase())}apply(e,r,s){let n=Cr.createSourceFile(kr.basename(e),r,Cr.ScriptTarget.Latest,!0),o=$(n);if(o.length===0)return r;let i=B(o[0],"tags",n),a=[...s].sort();if(i!==null&&JSON.stringify(bo(i).sort())===JSON.stringify(a))return r;let p=o.flatMap(c=>{let m=s.length===0?K(c,"tags",n):U(c,"tags",So(a),n);return m?[m]:[]});return p.length>0?J(r,p):r}};import vo from"path";var St=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,bt=/^@([a-zA-Z0-9_-]+)/gm;function ko(t){return["# <mokosh-tags>",...t.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
2
+ var qe=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});import dn from"path";import{fileURLToPath as hn}from"url";var yn=()=>hn(import.meta.url),xn=()=>dn.dirname(yn()),f=xn();import{StdioServerTransport as dc}from"@modelcontextprotocol/sdk/server/stdio.js";import{Server as uc}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as mc,ListToolsRequestSchema as gc}from"@modelcontextprotocol/sdk/types.js";import pc from"fs";import et from"fs";import rr from"path";var Sn=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],Xt=[];function Ee(r){Xt.push(r)}function Yt(r){return[...Sn,...Xt].some(e=>typeof e=="string"?r.includes(e):e instanceof RegExp?e.test(r):e(r))}var bn=[".test.",".spec.","-test.","-spec."],Zt=[];function Fe(r){Zt.push(r)}function re(){return[...bn,...Zt]}var vn=["jest","vitest","playwright","cypress","@testing-library/"],er=[];function Te(r){er.push(r)}function Xe(){return[...vn,...er]}var tr=.8;function Ye(r){tr=r}function Ze(){return tr}var Cn=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function se(r,{allowJs:e=!0,isExplicitPath:t=!1}={}){if(t){let s=rr.resolve(r);return et.existsSync(s)?s.endsWith(".json")?sr(s):e?nr(s):{}:{}}for(let s of Cn){let n=rr.resolve(r,s);if(et.existsSync(n)){if(s.endsWith(".json"))return sr(n);if(e)return nr(n)}}return{}}function sr(r){return JSON.parse(et.readFileSync(r,"utf-8"))}function nr(r){let e=qe(r);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function tt(r){for(let e of r.configMatchers??[])Ee(e);for(let e of r.testPatterns??[])Fe(e);for(let e of r.testLibraries??[])Te(e);r.barrelThreshold!==void 0&&Ye(r.barrelThreshold)}function U(r){return{gitStats:r?.gitStats??!1,parallelParsing:r?.parallelParsing,pathAliases:r?.pathAliases}}var rt=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"],st=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".feature",".md",".mdx"];import kn from"fs";import or from"path";function nt(r,e){let t=or.resolve(r,e);try{let s=kn.readFileSync(t,"utf-8"),n=JSON.parse(s),o=new Map;for(let[i,a]of Object.entries(n)){if(i==="total")continue;let c=a?.lines?.pct;if(typeof c!="number")continue;let p=or.relative(r,i);o.set(p,c)}return o}catch{return new Map}}var Pe={serialize(r){let e=["graph TD"],t=new Set;for(let s of r.nodes.values()){let n=`"${s.path}"`;for(let o of s.imports){if(!o.toPath)continue;let i=`"${o.toPath}"`,a=`${s.path} -> ${o.toPath}`;if(!t.has(a)){let c=o.isStyle?"-- styles -->":"-->";e.push(` ${n} ${c} ${i}`),t.add(a)}}}return e.join(`
3
+ `)}};import ir from"fs";import En from"path";function ot(r,e){let t=r.replace(/^\.\//,"");if(e.nodes.has(t))return t;let s=t.replace(/^dist\//,"src/").replace(/\.(js|mjs|cjs)$/,".ts");return e.nodes.has(s)?s:null}function ar(r,e){if(typeof r=="string")return ot(r,e);if(r&&typeof r=="object"){let t=r;for(let s of["import","require","default"]){let n=ar(t[s],e);if(n)return n}}return null}function Fn(r){if(!r)return"unknown";let e=r.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 Tn(r,e){let t=new Set,s=new Set,n=[...e];for(;n.length;){let o=n.shift();if(s.has(o))continue;s.add(o);let i=r.nodes.get(o);if(i){for(let a of i.exports)t.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 p=r.nodes.get(a.toPath);if(p)for(let l of p.exports)t.add(l.name);n.push(a.toPath)}else for(let p of a.symbols)t.add(p)}}}return t}function it(r,e){let t=[],s=En.join(e,"package.json");if(ir.existsSync(s))try{let n=JSON.parse(ir.readFileSync(s,"utf8"));if(n.exports&&typeof n.exports=="object"&&!Array.isArray(n.exports))for(let o of Object.values(n.exports)){let i=ar(o,r);i&&!t.includes(i)&&t.push(i)}else if(typeof n.exports=="string"){let o=ot(n.exports,r);o&&t.push(o)}if(t.length===0)for(let o of[n.main,n.module].filter(Boolean)){let i=ot(o,r);i&&!t.includes(i)&&t.push(i)}}catch{}if(t.length===0){for(let n of["src/index.ts","src/index.js","index.ts","index.js"])if(r.nodes.has(n)){t.push(n);break}}return t}function Pn(r,e){let t=new Set(e);for(let s of e)r.traverse(s,n=>(t.add(n.path),!0),{direction:"outgoing"});return t}function An(r,e,t){let s=new Map;for(let n of e){if(t.includes(n))continue;let o=r.nodes.get(n);if(!o)continue;let i=o.category==="barrel";for(let a of o.exports){let c=s.get(a.name),p=!!(a.signature||a.doc);(!c||p&&!i)&&s.set(a.name,{file:n,symbol:a})}}return s}function Nn(r,e,t,s){let n=[];for(let o of r){let i=e.get(o),a=s.flatMap(g=>t.nodes.get(g)?.exports??[]).find(g=>g.name===o),c=i?.symbol??a,p=i?.file??s.find(g=>t.nodes.get(g)?.exports.some(d=>d.name===o))??s[0],l={name:o,definedIn:p,kind:Fn(c?.signature)};c?.doc&&(l.doc=c.doc),c?.signature&&(l.signature=c.signature),n.push(l)}return n.sort((o,i)=>o.name.localeCompare(i.name)),n}function Mn(r,e,t){let s=c=>r.nodes.get(c)?.category==="test",n=[...e].filter(c=>!t.includes(c)&&!s(c)),o=[...r.nodes.keys()].filter(c=>!e.has(c)),i=o.filter(c=>!s(c)),a=o.filter(c=>s(c));return{internalFiles:n,unreachableFromEntry:i,testFiles:a}}function at(r,e){if(e.length===0)throw new Error("buildApiSurface requires at least one entry point");for(let p of e)if(!r.nodes.has(p))throw new Error(`Entry point not found in graph: ${p}`);let t=Pn(r,e),s=An(r,t,e),n=Tn(r,e),o=Nn(n,s,r,e),{internalFiles:i,unreachableFromEntry:a,testFiles:c}=Mn(r,t,e);return{entryPoints:e,publicExports:o,internalFiles:i,unreachableFromEntry:a,testFiles:c}}function ct(r,e){let t=null,s=[];for(let o of r.nodes.values()){o.exports.some(i=>i.name===e)&&(t=o.path);for(let i of o.callEdges??[])i.to===e&&s.push({file:o.path,callerFunction:i.from})}let n=[];if(t){let o=r.nodes.get(t);for(let i of o?.callEdges??[])i.from===e&&n.push({file:i.toFile,calleeFunction:i.to})}return{functionName:e,definedIn:t,callers:s,callees:n}}import Vc from"fs";import Qc from"path";function cr(r){let e=[...r.nodes.entries()].sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>`${s}:${n.mtime}:${n.size}`).join("|"),t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function pt(r){let e=new Map;for(let t of r.nodes.keys()){let s=[];r.traverse(t,n=>(n.path!==t&&s.push(n.path),!0),{direction:"incoming"}),e.set(t,s)}return{impact:e,graphHash:cr(r)}}function lt(r,e){return r.impact.get(e)??[]}import Ae from"path";function In(r){let e=new Map;for(let[t,s]of r){let n=s.imports.filter(o=>o.toPath&&!o.isExternal).length;n>0&&e.set(t,n)}return e}function Rn(r,e,t){let s=new Map;for(let[n,o]of e){if(o<t)continue;let i=r.get(n);if(!i||i.category==="test"||i.category==="barrel")continue;let a=Ae.extname(n),c=Ae.basename(n,a),p=c==="index"?Ae.basename(Ae.dirname(n)):c;s.set(n,{path:n,outDegree:o,tag:`feature:${p}`})}return s}function L(r,e){let t=e?.minOutDegree??5;return Rn(r,In(r),t)}var Dn=(r,e)=>r.outDegree-e.outDegree;function Gn(r,e){let t=new Map;for(let s of e.values()){let n=new Set;r.traverse(s.path,o=>(o.path!==s.path&&n.add(o.path),!0),{direction:"outgoing"}),t.set(s.path,n)}return t}function Ln(r,e,t,s){let n=new Map;for(let[o]of r){if(e.has(o))continue;let i=null;for(let a of e.values())t.get(a.path)?.has(o)&&(!i||s(a,i)<0)&&(i=a);i&&n.set(o,i.path)}return n}function _n(r,e){let t=new Map;for(let s of r.values()){let n=s.tag.replace("feature:",""),o=[];for(let[i,a]of e)a===s.path&&o.push(i);t.set(n,{hub:s.path,outDegree:s.outDegree,files:o})}return t}function On(r,e,t){let s=[];for(let n of r.keys())!e.has(n)&&!t.has(n)&&s.push(n);return s}function ne(r,e){let t=e?.detectFn??L,s=e?.hubComparator??Dn,n=t(r.nodes,e),o=Gn(r,n),i=Ln(r.nodes,n,o,s);return{features:_n(n,i),unassigned:On(r.nodes,n,i)}}var pr=new Set(["typescript","javascript","python","go","scss","less","lua","coffeescript"]),lr=new Set(["typescript","javascript","python"]),Ne=new Set(["typescript","javascript","go","python"]);function ft(r){let e=new Map;for(let t of r.nodes.values())e.set(t.type,(e.get(t.type)??0)+1);return[...e.entries()].map(([t,s])=>({type:t,fileCount:s,exportsTracked:pr.has(t),importSymbolsTracked:lr.has(t),callEdgesTracked:Ne.has(t)})).sort((t,s)=>s.fileCount-t.fileCount)}var oe=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let t=new Set(this.nodes.keys());return e.filter(s=>!t.has(s))}findHighExportUsage(e){let t=[];for(let s of this.nodes.values()){if(s.maxExportUsage===void 0||s.maxExportUsage<e)continue;let n=s.imports.reduce((o,i)=>(i.exportUsageRatio??0)>(o?.exportUsageRatio??0)?i:o,null);t.push({path:s.path,maxExportUsage:s.maxExportUsage,tightestDep:n?.toPath??""})}return t.sort((s,n)=>n.maxExportUsage-s.maxExportUsage)}findCycles(){let e=[],t=new Set,s=new Set,n=[],o=i=>{t.add(i),s.add(i),n.push(i);let a=this.nodes.get(i);if(a){for(let c of a.imports)if(!(!c.toPath||c.isExternal))if(s.has(c.toPath)){let p=n.indexOf(c.toPath);e.push([...n.slice(p),c.toPath])}else t.has(c.toPath)||o(c.toPath)}s.delete(i),n.pop()};for(let i of this.nodes.keys())t.has(i)||o(i);return e}};var M=class r{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let t=new Map;for(let s of e.nodes)t.set(s.path,s);return new r(t)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let t of this.nodes.values())for(let s of t.imports)if(s.toPath){let n=e.get(s.toPath)||[];n.push(t.path),e.set(s.toPath,n)}return this._incomingEdgesCache=e,e}dfs(e,t,s,n){let o=new Set,i=s.maxDepth??1/0,a=(c,p,l)=>{if(p>i||o.has(c))return;let g=this.nodes.get(c);if(g&&(o.add(c),t(g,p,l)!==!1))for(let d of n(c))a(d,p+1,c)};a(e,0,null)}traverse(e,t,s={}){let n=s.direction??"outgoing",o=n==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,t,s,i=>n==="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 t of this.nodes.values())for(let s of t.callEdges??[]){let n=e.get(s.toFile)??[];n.push(t.path),e.set(s.toFile,n)}return this._callIncomingCache=e,e}traverseCalls(e,t,s={}){let n=s.direction??"outgoing",o=n==="incoming"?this.getCallIncomingCache():null;this.dfs(e,t,s,i=>n==="outgoing"?this.nodes.get(i)?.callEdges?.map(a=>a.toFile)??[]:o?.get(i)??[])}getCallers(e){let t=[];return this.traverseCalls(e,s=>(s.path!==e&&t.push(s.path),!0),{direction:"incoming",maxDepth:1}),t}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let t=this.nodes.get(e);return t?t.imports.map(s=>this.nodes.get(s.toPath)).filter(s=>s!==void 0):[]}findUnusedFiles(e){return new oe(this.nodes).findUnusedFiles(e)}findCycles(){return new oe(this.nodes).findCycles()}};var _=class{affectedSymbols=new Map;constructor(e,t){this.affectedSymbols.set(e,new Set(["default",...t]))}updateAffectedSymbols(e,t){let s=this.affectedSymbols.get(t)||new Set,n=e.imports.find(c=>c.toPath===t);if(!n)return!1;let o=n.symbols||["*"],i=new Set;for(let c of o)(c==="*"||s.has("*")||s.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 ie(r,e){let t=r.nodes.get(e);if(t)return{category:t.category,exports:t.exports.map(s=>s.name)}}function ut(r,e,t=1){let s=[];return r.traverse(e,(n,o,i)=>{if(n.path===e)return!0;let a=i?r.nodes.get(i)?.imports.find(c=>c.toPath===n.path):void 0;return s.push({path:n.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"outgoing",maxDepth:t}),s}function ae(r,e){let t=[];return r.traverse(e,s=>{if(s.path===e)return!0;let n=s.imports.find(o=>o.toPath===e);return t.push({path:s.path,...n?.symbols?{symbols:n.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),t}function mt(r,e,t={}){let{testsOnly:s=!1,changedSymbols:n}=t,o=n?new _(e,n):null,i=[];return r.traverse(e,(a,c,p)=>{if(a.path===e)return!0;if(o&&p&&!o.updateAffectedSymbols(a,p))return!1;let l=a.category==="test"||a.tags.some(g=>g.name==="test");return(!s||l)&&i.push(a.path),!0},{direction:"incoming"}),i}function gt(r,e,t={}){let{depth:s=1,withEdgeDetail:n=!1}=t,o=[];return r.traverseCalls(e,i=>{if(i.path===e)return!0;let a={file:i.path};return n&&(a.edges=(i.callEdges??[]).filter(c=>c.toFile===e).map(c=>({from:c.from,to:c.to}))),o.push(a),!0},{direction:"incoming",maxDepth:s}),o}function dt(r,e={}){let{metric:t="cognitiveComplexity",threshold:s=10,limit:n=20}=e;return[...r.nodes.values()].flatMap(o=>(o.functions??[]).filter(i=>i[t]>=s).map(i=>({file:o.path,name:i.name,line:i.line,complexity:i.complexity,cognitiveComplexity:i.cognitiveComplexity}))).sort((o,i)=>i[t]-o[t]).slice(0,n)}function ht(r){return{nodes:r.nodes.map(t=>({path:t.path,type:t.type,category:t.category,exports:t.exports.map(s=>s.name),tags:t.tags.filter(s=>s.kind==="comment-marker"||s.kind==="import").map(s=>s.name),importsFiles:t.imports.filter(s=>!s.isExternal&&s.toPath).map(s=>s.toPath),...t.description!==void 0&&{description:t.description},...t.testedBy!==void 0&&{testedBy:t.testedBy},...t.coveragePct!==void 0&&{coveragePct:t.coveragePct},...t.avgExportUsage!==void 0&&{avgExportUsage:t.avgExportUsage},...t.maxExportUsage!==void 0&&{maxExportUsage:t.maxExportUsage}})),cycles:r.cycles}}function yt(r){let e=r.getPackageDependencies(),t=Array.from(r.packages.values()).map(({graph:s,pkg:n})=>({name:n.name,relativeRoot:n.relativeRoot,nodeCount:s.nodes.size,dependsOn:e.get(n.name)??[]}));return{monorepoType:r.type,packageCount:t.length,packages:t}}function xt(r){return[...r.nodes.values()].some(e=>e.coveragePct!==void 0)}function fr(r){if(r.category==="test")return"test";if(r.category==="config")return"config";if(r.category==="type-only")return"types";let e=r.path;return b(e,"component")||b(e,"components")?"component":b(e,"controller")||b(e,"controllers")?"controller":b(e,"middleware")?"middleware":b(e,"router")||b(e,"routes")||b(e,"route")?"router":b(e,"store")||b(e,"stores")?"store":b(e,"service")||b(e,"services")?"service":b(e,"handler")||b(e,"handlers")?"handler":b(e,"adapter")||b(e,"adapters")?"adapter":b(e,"plugin")||b(e,"plugins")?"plugin":b(e,"api")?"api":b(e,"cli")||b(e,"commands")||ce(e)==="cli"?"cli":b(e,"util")||b(e,"utils")||b(e,"helper")||b(e,"helpers")?"util":b(e,"model")||b(e,"models")||ce(e)==="model"?"model":b(e,"parser")||b(e,"parsers")||ce(e)==="parser"?"parser":ce(e)==="builder"?"builder":ce(e)==="resolver"?"resolver":"other"}function b(r,e){return r.includes(`/${e}/`)||r.includes(`/${e}.`)}function ce(r){let e=r.slice(r.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function St(r,e){let t=ne(r,e),s=new Map;for(let[o,i]of t.features){for(let a of i.files)s.set(a,o);s.set(i.hub,o)}let n=new Map;for(let o of r.nodes.values()){let i=s.get(o.path);n.set(o.path,{path:o.path,role:fr(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return n}function bt(r,e){let t=[];for(let s of r.nodes.values())if(s.exports.some(n=>n.name===e))if(Ne.has(s.type)){let n=[];for(let o of r.nodes.values())for(let i of o.callEdges??[])i.to===e&&n.push({file:o.path,callerFunction:i.from});t.push({path:s.path,category:s.category,precision:"call",callers:n})}else{let n=ae(r,s.path).map(o=>({file:o.path,...o.symbols?{symbols:o.symbols}:{}}));t.push({path:s.path,category:s.category,precision:"file-level",importers:n})}return t}function jn(r){return r?r.startsWith("interface ")?"interface":r.startsWith("class ")?"class":r.startsWith("enum ")?"enum":"type":"type"}function Wn(r,e){if(e==="type-only")return!0;let t=r.signature??"";return t.startsWith("interface ")||t.startsWith("class ")||t.startsWith("enum ")}function vt(r){let e=new Map;for(let s of r.nodes.values())if(!(s.type!=="typescript"&&s.type!=="javascript"))for(let n of s.exports){if(!Wn(n,s.category))continue;let o=`${s.path}::${n.name}`;e.set(o,{name:n.name,file:s.path,kind:jn(n.signature),...n.doc?{doc:n.doc}:{}})}let t=[];for(let s of r.nodes.values())if(!(s.type!=="typescript"&&s.type!=="javascript")){for(let n of s.imports)if(!(!n.toPath||n.isExternal||!n.symbols?.length))for(let o of n.symbols)e.has(`${n.toPath}::${o}`)&&t.push({fromFile:s.path,toType:o,toFile:n.toPath})}return{types:e,edges:t}}function Ct(r,e){let t=null;for(let o of r.types.values())if(o.name===e){t=o;break}if(!t)return{type:null,usedByFiles:[],uses:[]};let s=new Set,n=new Map;for(let o of r.edges)if(o.toType===e&&o.toFile===t.file&&s.add(o.fromFile),o.fromFile===t.file){let i=r.types.get(`${o.toFile}::${o.toType}`);i&&n.set(`${i.file}::${i.name}`,i)}return{type:t,usedByFiles:Array.from(s),uses:Array.from(n.values())}}import Yn from"path";import wt from"fs";import dr from"path";import pe from"fs";import T from"path";import ur from"fs";import Np from"path";function mr(r){try{return ur.statSync(r,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function Me(r){try{return ur.statSync(r,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}function kt(r,e){let t=T.join(e,"package.json");if(!pe.existsSync(t))return null;let s={};try{s=JSON.parse(pe.readFileSync(t,"utf-8"))}catch{return null}let n=s.name;return n?{name:n,root:e,relativeRoot:T.relative(r,e),entryPoints:zn(e,s)}:null}function zn(r,e){let t=[];if(e.exports){let n=e.exports;if(typeof n=="string")t.push(T.join(r,n));else if(typeof n=="object"&&n!==null){let o=n["."];if(typeof o=="string")t.push(T.join(r,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&t.push(T.join(r,i))}}}e.main&&t.push(T.join(r,e.main));for(let n of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])t.push(T.join(r,n));let s=t.filter(Me);return s.length>0?s.slice(0,1):t.slice(0,1)}function K(r,e){let t=[],s=new Set;for(let n of e){let o=n.replace(/\/$/,"").replace(/^\.\//,"");$n(r,o,s,t)}return t}function $n(r,e,t,s){if(!e.includes("*")){Bn(r,e,t,s);return}let n=e.split("/");n.includes("**")?Un(r,n,t,s):Kn(r,n,t,s)}function Bn(r,e,t,s){let n=T.join(r,e);if(t.has(n)||!mr(n))return;t.add(n);let o=kt(r,n);o&&s.push(o)}function Un(r,e,t,s){let n=T.join(r,e[0]==="**"?"":e[0]??"");gr(r,n,t,s)}function Kn(r,e,t,s){let n=e.findIndex(a=>a.includes("*")),o=T.join(r,...e.slice(0,n)),i;try{i=pe.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let c=T.join(o,a.name);if(t.has(c))continue;t.add(c);let p=kt(r,c);p&&s.push(p)}}function gr(r,e,t,s){let n;try{n=pe.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of n){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=T.join(e,o.name);if(pe.existsSync(T.join(i,"package.json"))&&!t.has(i)){t.add(i);let a=kt(r,i);a&&s.push(a)}else gr(r,i,t,s)}}var hr={type:"npm",detect(r){let e=dr.join(r,"package.json");if(!wt.existsSync(e))return null;let t;try{t=JSON.parse(wt.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!t||wt.existsSync(dr.join(r,"yarn.lock")))return null;let s=Array.isArray(t)?t:t.packages??[];return s.length===0?null:K(r,s)}};import J from"fs";import w from"path";var yr={type:"nx",detect(r){return J.existsSync(w.join(r,"nx.json"))?xr(r,r,new Set,0).map(t=>Jn(r,t,w.join(t,"project.json"))).filter(t=>t!==null):null}};function xr(r,e,t,s){if(s>4)return[];let n;try{n=J.readdirSync(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let i of n){if(!i.isDirectory())continue;let a=i.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let c=w.join(e,a);J.existsSync(w.join(c,"project.json"))&&!t.has(c)?(t.add(c),o.push(c)):o.push(...xr(r,c,t,s+1))}return o}function Jn(r,e,t){let s={};try{s=JSON.parse(J.readFileSync(t,"utf-8"))}catch{return null}let n=s.name,o,i,a=w.join(e,"package.json");if(J.existsSync(a))try{let c=JSON.parse(J.readFileSync(a,"utf-8"));n=c.name??n,o=c.main,i=c.exports}catch{}return n?{name:n,root:e,relativeRoot:w.relative(r,e),entryPoints:Vn(e,s,o,i)}:null}function Vn(r,e,t,s){let n=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=w.resolve(r,"../..");n.push(w.resolve(a,o)),n.push(w.resolve(r,o))}if(s){let a=s;if(typeof a=="string")n.push(w.join(r,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&n.push(w.join(r,c))}}if(t&&n.push(w.join(r,t)),e.sourceRoot){let a=w.resolve(r,"../.."),c=w.resolve(a,e.sourceRoot);n.push(w.join(c,"index.ts"),w.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])n.push(w.join(r,a));let i=n.filter(Me);return i.length>0?i.slice(0,1):n.slice(0,1)}import Sr from"fs";import Hn from"path";import{load as Qn}from"js-yaml";var br={type:"pnpm",detect(r){let e=Hn.join(r,"pnpm-workspace.yaml");if(!Sr.existsSync(e))return null;let t=[];try{t=Qn(Sr.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return K(r,t)}};import qn from"fs";import Xn from"path";var vr={type:"turborepo",detect(r){return qn.existsSync(Xn.join(r,"turbo.json"))?[]:null}};import Et from"fs";import Cr from"path";var kr={type:"yarn",detect(r){if(!Et.existsSync(Cr.join(r,"yarn.lock")))return null;let e=Cr.join(r,"package.json");if(!Et.existsSync(e))return null;let t;try{t=JSON.parse(Et.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!t)return null;let s=Array.isArray(t)?t:t.packages??[];return s.length===0?null:K(r,s)}};var wr=[];function I(r){wr.push(r)}function Er(){return wr}I(vr);I(yr);I(br);I(kr);I(hr);function le(r,e=Er()){let t=Yn.resolve(r),s=new Map,n=[];for(let i of e){let a=i.detect(t);if(a!==null){n.push(i.type);for(let c of a)s.has(c.name)||s.set(c.name,c)}}if(n.length===0)return{root:t,type:"none",types:[],packages:[],packageMap:new Map};let o=Array.from(s.values());return{root:t,type:n[0],types:n,packages:o,packageMap:new Map(o.map(i=>[i.name,i]))}}var fe=class r{constructor(e,t){this.monorepoRoot=e;this.type=t}monorepoRoot;type;packages=new Map;addPackage(e,t){this.packages.set(e.name,{graph:t,pkg:e})}getPackageForFile(e){for(let{pkg:t}of this.packages.values())if(e===t.relativeRoot||e.startsWith(`${t.relativeRoot}/`))return t}getPackageDependencies(){let e=new Map;for(let{graph:t,pkg:s}of this.packages.values()){let n=new Set;for(let o of t.nodes.values())for(let i of o.imports)i.isWorkspace&&i.workspacePackage&&n.add(i.workspacePackage);e.set(s.name,[...n])}return e}getAffectedAcrossPackages(e){let t=this.getPackageForFile(e);if(!t)return[];let s=this.packages.get(t.name);if(!s)return[];let n=[];s.graph.traverse(e,o=>(o.path!==e&&n.push({file:o.path,package:t.name}),!0),{direction:"incoming"});for(let{graph:o,pkg:i}of this.packages.values())if(i.name!==t.name)for(let a of o.nodes.values())a.imports.some(p=>p.isWorkspace&&p.workspacePackage===t.name)&&n.push({file:a.path,package:i.name});return n}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:t})=>({pkg:{name:t.name,relativeRoot:t.relativeRoot,entryPoints:t.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let t=new r(e.monorepoRoot,e.type);for(let{pkg:s,nodes:n}of e.packages){let o=new Map(n.map(a=>[a.path,a])),i=new M(o);t.packages.set(s.name,{graph:i,pkg:{...s,root:""}})}return t}};var Fr=new Map;function V(r,e){Fr.set(r,e)}function Tr(r){return Fr.get(r)}function Pr(r,e){return e.startsWith("!")?r!==e.slice(1):r===e}function Zn(r,e){return e.startsWith("!")?!r.includes(e.slice(1)):r.includes(e)}var eo=(r,e)=>!e.category||Pr(r.category,e.category),to=(r,e)=>!e.type||Pr(r.type,e.type),ro=(r,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?r.lastAuthor!==e.lastAuthor.slice(1):r.lastAuthor!==void 0&&r.lastAuthor===e.lastAuthor:!0,so=(r,e)=>!e.path||Zn(r.path,e.path),no=(r,e)=>e.isExternal===void 0?!0:r.imports.some(s=>s.isExternal)===e.isExternal,oo=(r,e)=>{if(!e.tags||e.tags.length===0)return!0;let t=e.tags.filter(n=>!n.startsWith("!")),s=e.tags.filter(n=>n.startsWith("!")).map(n=>n.slice(1));return!(t.length>0&&!t.some(n=>r.tags.some(o=>o.name===n))||s.some(n=>r.tags.some(o=>o.name===n)))},io=(r,e)=>!e.allTags?.length||e.allTags.every(t=>r.tags.some(s=>s.name===t)),ao=(r,e)=>!e.importsFile||r.imports.some(t=>t.toPath?.includes(e.importsFile)),co=(r,e,t)=>e.importedBy===void 0?!0:(t?.get(r.path)??[]).some(n=>n.includes(e.importedBy)),po=(r,e)=>e.minImports===void 0||r.imports.length>=e.minImports,lo=(r,e)=>e.maxImports===void 0||r.imports.length<=e.maxImports,fo=(r,e)=>e.minSize===void 0||r.size>=e.minSize,uo=(r,e)=>e.maxSize===void 0||r.size<=e.maxSize,mo=(r,e)=>e.hasDocstring===void 0||!!r.description===e.hasDocstring,go=(r,e)=>e.isDocumented===void 0||!!r.documentedBy?.length===e.isDocumented,ho=(r,e)=>e.isStale===void 0||!!r.staleFor?.length===e.isStale,yo=(r,e)=>e.minCoverage===void 0||(r.coveragePct??101)>=e.minCoverage,xo=(r,e)=>e.maxCoverage===void 0||(r.coveragePct??0)<=e.maxCoverage,So=(r,e)=>e.minExportUsage===void 0||(r.avgExportUsage??-1)>=e.minExportUsage,bo=(r,e)=>e.maxExportUsage===void 0||(r.avgExportUsage??0)<=e.maxExportUsage,vo=(r,e)=>e.minComplexity===void 0||(r.complexity??-1/0)>=e.minComplexity,Co=(r,e)=>e.maxComplexity===void 0||(r.complexity??0)<=e.maxComplexity,ko=(r,e)=>e.minCognitiveComplexity===void 0||(r.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,wo=(r,e)=>e.maxCognitiveComplexity===void 0||(r.cognitiveComplexity??0)<=e.maxCognitiveComplexity,Eo=(r,e)=>e.minCommits===void 0||(r.commitCount90d??-1/0)>=e.minCommits,Fo=(r,e)=>e.maxCommits===void 0||(r.commitCount90d??0)<=e.maxCommits,To=(r,e,t)=>!e.any?.length||e.any.some(s=>ue(r,s,t)),Po=[eo,to,ro,so,no,oo,io,ao,co,po,lo,fo,uo,mo,go,ho,yo,xo,So,bo,vo,Co,ko,wo,Eo,Fo,To];function ue(r,e,t){return Po.every(s=>s(r,e,t))}function Ie(r,e){let t=new Map;if(e.importedBy!==void 0){for(let i of r.nodes)for(let a of i.imports)if(a.toPath){let c=t.get(a.toPath)??[];c.push(i.path),t.set(a.toPath,c)}}let s=r.nodes.filter(i=>ue(i,e,t)),n=new Set(s.map(i=>i.path)),o=s.map(i=>({...i,imports:i.imports.filter(a=>!a.toPath||n.has(a.toPath))}));if(e.sort){let i=e.sortDir==="asc"?-1:1;o.sort((a,c)=>{let p=0;return e.sort==="size"?p=c.size-a.size:e.sort==="imports"?p=c.imports.length-a.imports.length:e.sort==="commitCount90d"?p=(c.commitCount90d??0)-(a.commitCount90d??0):e.sort==="exportUsage"?p=(c.avgExportUsage??0)-(a.avgExportUsage??0):e.sort==="complexity"?p=(c.complexity??0)-(a.complexity??0):e.sort==="cognitiveComplexity"&&(p=(c.cognitiveComplexity??0)-(a.cognitiveComplexity??0)),p*i})}return e.limit!==void 0&&o.splice(e.limit),{nodes:o,cycles:r.cycles?.filter(i=>i.every(a=>n.has(a)))??void 0}}function Ar(r,e){let t=e.indexOf(":");if(t===-1)return;let s=e.slice(0,t).trim().toLowerCase(),n=e.slice(t+1).trim();if(!(!s||!n))switch(s){case"category":r.category=n;break;case"type":r.type=n;break;case"tag":case"tags":n.includes("+")?r.allTags=[...r.allTags??[],...n.split("+")]:r.tags=[...r.tags??[],n];break;case"path":r.path=n;break;case"external":r.isExternal=n.toLowerCase()==="true";break;case"importsfile":r.importsFile=n;break;case"importedby":r.importedBy=n;break;case"minimports":r.minImports=parseInt(n,10);break;case"maximports":r.maxImports=parseInt(n,10);break;case"minsize":r.minSize=parseInt(n,10);break;case"maxsize":r.maxSize=parseInt(n,10);break;case"sort":r.sort=n;break;case"sortdir":r.sortDir=n.toLowerCase()==="asc"?"asc":"desc";break;case"limit":r.limit=parseInt(n,10);break;case"hasdocstring":r.hasDocstring=n.toLowerCase()!=="false";break;case"mincoverage":r.minCoverage=parseInt(n,10);break;case"maxcoverage":r.maxCoverage=parseInt(n,10);break;case"minexportusage":r.minExportUsage=parseFloat(n);break;case"maxexportusage":r.maxExportUsage=parseFloat(n);break;case"mincomplexity":r.minComplexity=parseInt(n,10);break;case"maxcomplexity":r.maxComplexity=parseInt(n,10);break;case"mincognitivecomplexity":r.minCognitiveComplexity=parseInt(n,10);break;case"maxcognitivecomplexity":r.maxCognitiveComplexity=parseInt(n,10);break;case"mincommits":r.minCommits=parseInt(n,10);break;case"maxcommits":r.maxCommits=parseInt(n,10);break;case"isdocumented":r.isDocumented=n.toLowerCase()!=="false";break;case"isstale":r.isStale=n.toLowerCase()!=="false";break;case"lastauthor":r.lastAuthor=n;break}}function Ao(r){let e=[];for(let t of r.split("|")){let s=t.trim();if(!s)continue;let n={};Ar(n,s),Object.keys(n).length>0&&e.push(n)}return e}function Re(r){let e={},t=r.split(",");for(let s of t){let n=s.trim();if(n.toLowerCase().startsWith("any(")&&n.endsWith(")")){let o=n.slice(4,-1),i=Ao(o);i.length>0&&(e.any=[...e.any??[],...i]);continue}Ar(e,s)}return e}import zr from"fs/promises";import Zo from"path";import Mt from"path";import ze from"typescript";import Mr from"path";import Ir from"typescript";import E from"typescript";var Nr=new Set(["describe","test","it"]);function H(r){let e=[];for(let t of r.statements){if(!E.isExpressionStatement(t))continue;let s=t.expression;if(!E.isCallExpression(s))continue;let n=s.expression;E.isIdentifier(n)&&Nr.has(n.text)&&e.push(s),E.isPropertyAccessExpression(n)&&E.isIdentifier(n.expression)&&Nr.has(n.expression.text)&&e.push(s)}return e}function Q(r,e,t){for(let s of r.arguments){if(!E.isObjectLiteralExpression(s))continue;let n=s.properties.find(o=>E.isPropertyAssignment(o)&&E.isIdentifier(o.name)&&o.name.text===e);if(!(!n||!E.isArrayLiteralExpression(n.initializer)))return n.initializer.elements.filter(E.isStringLiteral).map(o=>o.text)}return null}function q(r,e,t,s){if(r.arguments.length===0)return null;for(let o=1;o<r.arguments.length;o++){let i=r.arguments[o];if(!E.isObjectLiteralExpression(i))continue;let a=i.properties.find(p=>E.isPropertyAssignment(p)&&E.isIdentifier(p.name)&&p.name.text===e);if(a)return{start:a.initializer.getStart(s),end:a.initializer.getEnd(),text:t};let c=i.getEnd()-1;return{start:c,end:c,text:`${i.properties.length>0?", ":""}${e}: ${t}`}}let n=r.arguments[r.arguments.length-1];return{start:n.getStart(s),end:n.getStart(s),text:`{ ${e}: ${t} }, `}}function X(r,e,t){let s=r.arguments;for(let n=1;n<s.length;n++){let o=s[n];if(!E.isObjectLiteralExpression(o))continue;let i=o.properties.findIndex(c=>E.isPropertyAssignment(c)&&E.isIdentifier(c.name)&&c.name.text===e);if(i<0)continue;if(o.properties.length===1)return{start:s[n-1].getEnd(),end:o.getEnd(),text:""};let a=o.properties[i];return i===o.properties.length-1?{start:o.properties[i-1].getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(t),end:o.properties[i+1].getStart(t),text:""}}return null}function Y(r,e){let t=[...e].sort((n,o)=>o.start-n.start),s=r;for(let n of t)s=s.slice(0,n.start)+n.text+s.slice(n.end);return s}function Z(r){return`[${r.map(e=>JSON.stringify(e)).join(", ")}]`}var N=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function No(r){return Z(r.map(e=>`@${e}`))}function Mo(r){return r.map(e=>e.startsWith("@")?e.slice(1):e)}var De=class{name="cypress";canHandle(e){return N.has(Mr.extname(e).toLowerCase())}apply(e,t,s){let n=Ir.createSourceFile(Mr.basename(e),t,Ir.ScriptTarget.Latest,!0),o=H(n);if(o.length===0)return t;let i=Q(o[0],"tags",n),a=[...s].sort();if(i!==null&&JSON.stringify(Mo(i).sort())===JSON.stringify(a))return t;let c=o.flatMap(p=>{let l=s.length===0?X(p,"tags",n):q(p,"tags",No(a),n);return l?[l]:[]});return c.length>0?Y(t,c):t}};import Io from"path";var Ft=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,Tt=/^@([a-zA-Z0-9_-]+)/gm;function Ro(r){return["# <mokosh-tags>",...r.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
4
4
  `)+`
5
5
 
6
- `}function Co(t){let e=new Set;bt.lastIndex=0;let r=bt.exec(t);for(;r!==null;)r[1]&&e.add(r[1]),r=bt.exec(t);return e}var Pe=class{name="gherkin";canHandle(e){return vo.extname(e).toLowerCase()===".feature"}apply(e,r,s){let n=r.replace(St,""),o=Co(n),i=s.filter(p=>!o.has(p)),a=i.length>0?ko(i):"";return St.test(r)?r.replace(St,a):a?r.replace(/^(Feature:)/m,`${a}$1`):r}};function wr(t,e){let r=t.replace(/\\/g,"/"),s=e.replace(/\\/g,"/"),n="";for(let o=0;o<r.length;o++){let i=r[o];i==="*"?r[o+1]==="*"?(n+=".*",o++):n+="[^/]*":i==="?"?n+="[^/]":i!==void 0&&(n+=i.replace(/[.+^${}()|[\]\\]/g,"\\$&"))}return new RegExp(`^${n}$`).test(s)}import wo from"path";var vt=/^\/\/go:build mokosh_[^\n]+\n/m,Eo=/^package\s+\S+/m;function Fo(t){return`//go:build ${t.map(r=>`mokosh_${r}`).join(" || ")}
7
- `}function To(t){let e=vt.exec(t);if(!e)return null;let r=e[0],s=/mokosh_([a-zA-Z0-9_-]+)/g,n=[],o=s.exec(r);for(;o!==null;)o[1]&&n.push(o[1]),o=s.exec(r);return n}var Ae=class{name="go";canHandle(e){return wo.basename(e).endsWith("_test.go")}apply(e,r,s){let n=To(r),o=[...s].sort();if(n!==null&&JSON.stringify([...n].sort())===JSON.stringify(o))return r;if(s.length===0)return r.replace(vt,"");let i=Fo(o);if(n!==null)return r.replace(vt,i);let a=Eo.exec(r);if(!a)return r;let p=a.index;return r.slice(0,p)+i+`
8
- `+r.slice(p)}};import Po from"path";var Ao=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,kt=/^ \* @group (.+)$/gm;function Mo(t){return["/**",...t.map(e=>` * @group ${e}`)," */"].join(`
6
+ `}function Do(r){let e=new Set;Tt.lastIndex=0;let t=Tt.exec(r);for(;t!==null;)t[1]&&e.add(t[1]),t=Tt.exec(r);return e}var Ge=class{name="gherkin";canHandle(e){return Io.extname(e).toLowerCase()===".feature"}apply(e,t,s){let n=t.replace(Ft,""),o=Do(n),i=s.filter(c=>!o.has(c)),a=i.length>0?Ro(i):"";return Ft.test(t)?t.replace(Ft,a):a?t.replace(/^(Feature:)/m,`${a}$1`):t}};function Rr(r,e){let t=r.replace(/\\/g,"/"),s=e.replace(/\\/g,"/"),n="";for(let o=0;o<t.length;o++){let i=t[o];i==="*"?t[o+1]==="*"?(n+=".*",o++):n+="[^/]*":i==="?"?n+="[^/]":i!==void 0&&(n+=i.replace(/[.+^${}()|[\]\\]/g,"\\$&"))}return new RegExp(`^${n}$`).test(s)}import Go from"path";var Pt=/^\/\/go:build mokosh_[^\n]+\n/m,Lo=/^package\s+\S+/m;function _o(r){return`//go:build ${r.map(t=>`mokosh_${t}`).join(" || ")}
7
+ `}function Oo(r){let e=Pt.exec(r);if(!e)return null;let t=e[0],s=/mokosh_([a-zA-Z0-9_-]+)/g,n=[],o=s.exec(t);for(;o!==null;)o[1]&&n.push(o[1]),o=s.exec(t);return n}var Le=class{name="go";canHandle(e){return Go.basename(e).endsWith("_test.go")}apply(e,t,s){let n=Oo(t),o=[...s].sort();if(n!==null&&JSON.stringify([...n].sort())===JSON.stringify(o))return t;if(s.length===0)return t.replace(Pt,"");let i=_o(o);if(n!==null)return t.replace(Pt,i);let a=Lo.exec(t);if(!a)return t;let c=a.index;return t.slice(0,c)+i+`
8
+ `+t.slice(c)}};import jo from"path";var Wo=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,At=/^ \* @group (.+)$/gm;function zo(r){return["/**",...r.map(e=>` * @group ${e}`)," */"].join(`
9
9
  `)+`
10
10
 
11
- `}function Io(t){let e=[];kt.lastIndex=0;let r=kt.exec(t);for(;r!==null;)r[1]&&e.push(r[1]),r=kt.exec(t);return e}var Me=class{name="jest";canHandle(e){return T.has(Po.extname(e).toLowerCase())}apply(e,r,s){let n=Ao.exec(r),o=n?Io(n[0]):null,i=[...s].sort();if(o!==null&&JSON.stringify([...o].sort())===JSON.stringify(i))return r;let a=n?r.slice(n[0].length):r;return s.length===0?a:Mo(i)+a}};import Er from"path";import Fr from"typescript";function No(t){return H(t.map(e=>`@${e}`))}function Ro(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}var Ie=class{name="playwright";canHandle(e){return T.has(Er.extname(e).toLowerCase())}apply(e,r,s){let n=Fr.createSourceFile(Er.basename(e),r,Fr.ScriptTarget.Latest,!0),o=$(n);if(o.length===0)return r;let i=B(o[0],"tag",n),a=[...s].sort();if(i!==null&&JSON.stringify(Ro(i).sort())===JSON.stringify(a))return r;let p=o.flatMap(c=>{let m=s.length===0?K(c,"tag",n):U(c,"tag",No(a),n);return m?[m]:[]});return p.length>0?J(r,p):r}};import Go from"path";var Ct=/^pytestmark\s*=\s*.+$/m,Do=/^import pytest\s*$/m;function _o(t){let e=t.map(r=>`pytest.mark.${r}`).join(", ");return t.length===1?`pytestmark = pytest.mark.${t[0]}`:`pytestmark = [${e}]`}function Lo(t){let e=Ct.exec(t);if(!e)return null;let r=e[0],s=[],n=/pytest\.mark\.([a-zA-Z0-9_-]+)/g,o=n.exec(r);for(;o!==null;)o[1]&&s.push(o[1]),o=n.exec(r);return s}var Ne=class{name="pytest";canHandle(e){return Go.extname(e).toLowerCase()===".py"}apply(e,r,s){let n=Lo(r),o=[...s].sort();if(n!==null&&JSON.stringify([...n].sort())===JSON.stringify(o))return r;if(s.length===0)return r.replace(Ct,"").replace(/\n{3,}/g,`
11
+ `}function $o(r){let e=[];At.lastIndex=0;let t=At.exec(r);for(;t!==null;)t[1]&&e.push(t[1]),t=At.exec(r);return e}var _e=class{name="jest";canHandle(e){return N.has(jo.extname(e).toLowerCase())}apply(e,t,s){let n=Wo.exec(t),o=n?$o(n[0]):null,i=[...s].sort();if(o!==null&&JSON.stringify([...o].sort())===JSON.stringify(i))return t;let a=n?t.slice(n[0].length):t;return s.length===0?a:zo(i)+a}};import Dr from"path";import Gr from"typescript";function Bo(r){return Z(r.map(e=>`@${e}`))}function Uo(r){return r.map(e=>e.startsWith("@")?e.slice(1):e)}var Oe=class{name="playwright";canHandle(e){return N.has(Dr.extname(e).toLowerCase())}apply(e,t,s){let n=Gr.createSourceFile(Dr.basename(e),t,Gr.ScriptTarget.Latest,!0),o=H(n);if(o.length===0)return t;let i=Q(o[0],"tag",n),a=[...s].sort();if(i!==null&&JSON.stringify(Uo(i).sort())===JSON.stringify(a))return t;let c=o.flatMap(p=>{let l=s.length===0?X(p,"tag",n):q(p,"tag",Bo(a),n);return l?[l]:[]});return c.length>0?Y(t,c):t}};import Ko from"path";var Nt=/^pytestmark\s*=\s*.+$/m,Jo=/^import pytest\s*$/m;function Vo(r){let e=r.map(t=>`pytest.mark.${t}`).join(", ");return r.length===1?`pytestmark = pytest.mark.${r[0]}`:`pytestmark = [${e}]`}function Ho(r){let e=Nt.exec(r);if(!e)return null;let t=e[0],s=[],n=/pytest\.mark\.([a-zA-Z0-9_-]+)/g,o=n.exec(t);for(;o!==null;)o[1]&&s.push(o[1]),o=n.exec(t);return s}var je=class{name="pytest";canHandle(e){return Ko.extname(e).toLowerCase()===".py"}apply(e,t,s){let n=Ho(t),o=[...s].sort();if(n!==null&&JSON.stringify([...n].sort())===JSON.stringify(o))return t;if(s.length===0)return t.replace(Nt,"").replace(/\n{3,}/g,`
12
12
 
13
- `);let i=_o(o);if(n!==null)return r.replace(Ct,i);let a=Do.test(r),p=Oo(r),c=r.slice(0,p),m=r.slice(p),g=a?"":`import pytest
14
- `,d=c.endsWith(`
13
+ `);let i=Vo(o);if(n!==null)return t.replace(Nt,i);let a=Jo.test(t),c=Qo(t),p=t.slice(0,c),l=t.slice(c),g=a?"":`import pytest
14
+ `,d=p.endsWith(`
15
15
 
16
16
  `)?"":`
17
- `;return c+d+g+i+`
18
- `+m}};function Oo(t){let e=t.split(`
19
- `),r=-1;for(let n=0;n<e.length;n++){let o=e[n].trimStart();(o.startsWith("import ")||o.startsWith("from "))&&(r=n)}if(r<0)return 0;let s=0;for(let n=0;n<=r;n++)s+=e[n].length+1;return s}import Tr from"path";import Pr from"typescript";var jo=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,Re=class{name="vitest";canHandle(e){return T.has(Tr.extname(e).toLowerCase())}apply(e,r,s){let n=r.replace(jo,""),o=Pr.createSourceFile(Tr.basename(e),n,Pr.ScriptTarget.Latest,!0),i=$(o);if(i.length===0)return n;let a=B(i[0],"tags",o),p=[...s].sort();if(a!==null&&JSON.stringify([...a].sort())===JSON.stringify(p))return n;let c=i.flatMap(m=>{let g=s.length===0?K(m,"tags",o):U(m,"tags",H(p),o);return g?[g]:[]});return c.length>0?J(n,c):n}};var Ar={vitest:()=>new Re,playwright:()=>new Ie,cypress:()=>new Te,jest:()=>new Me},Wo={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function zo(t){let e=Ge.createSourceFile("detect.ts",t,Ge.ScriptTarget.Latest,!0);for(let r of e.statements){if(!Ge.isImportDeclaration(r)||!Ge.isStringLiteral(r.moduleSpecifier))continue;let s=Wo[r.moduleSpecifier.text];if(s)return s}return null}var Et=class{constructor(e,r,s){this.rootDir=e;this.defaultFramework=r;this.frameworkOverrides=s}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return T.has(wt.extname(e).toLowerCase())}apply(e,r,s){let n=zo(r)??this.matchOverride(e)??this.defaultFramework;return(Ar[n]??Ar.vitest)().apply(e,r,s)}matchOverride(e){let r=wt.relative(this.rootDir,e).split(wt.sep).join("/");for(let[s,n]of this.frameworkOverrides)if(wr(s,r))return n;return null}};function Mr(t="vitest",e={},r=process.cwd()){return[new Pe,new Ne,new Ae,new Et(r,t,Object.entries(e))]}function Ir(t,e){return e.find(r=>r.canHandle(t))??null}var Bo=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,Uo=new Set(["import"]),Ko=new Set(["common","fixture","fixtures","helper","helpers","index","main","mock","mocks","setup","shared","spec","test","tests","types","util","utils"]);async function Jo(t,e,r,s){let n;try{n=await Nr.readFile(t,"utf8")}catch(a){return{path:t,status:"error",error:String(a)}}let o=Ir(t,s);if(!o)return{path:t,status:"unchanged"};let i=o.apply(t,n,e);return i===n?{path:t,status:"unchanged"}:(r||await Nr.writeFile(t,i,"utf8"),{path:t,status:"updated"})}async function Ft(t,e,r){let s=X(e),n=s.tagApplier?.framework??"vitest",o=s.tagApplier?.frameworkOverrides??{},i=Mr(n,o,e),a={updated:0,unchanged:0,errors:0,files:[]};for(let p of t.nodes.values()){if(p.category!=="test")continue;let c=new Set,m=[];for(let S of p.tags)Uo.has(S.kind)&&Bo.test(S.name)&&(Ko.has(S.name.toLowerCase())||c.has(S.name)||(c.add(S.name),m.push(S.name)));m.sort();let g=$o.resolve(e,p.path),d=await Jo(g,m,r.dryRun,i);d.path=p.path,a.files.push(d),d.status==="updated"?a.updated++:d.status==="unchanged"?a.unchanged++:a.errors++}return a}var De=class{isTestNode(e){return e.category==="test"||e.tags.some(r=>r.name==="test")}};import ge from"fs";import C from"path";import Oa from"piscina";import{execFileSync as Tt}from"child_process";var _e=class{getChangedFiles(){try{let r=[["diff","--name-only"],["diff","--cached","--name-only"],["ls-files","--others","--exclude-standard"]].flatMap(s=>{try{return Tt("git",s,{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
20
- `).map(o=>o.trim()).filter(o=>o!=="")}catch{return[]}});return Array.from(new Set(r))}catch(e){return console.error("Error getting git diff:",e),[]}}},Rr="%x00%H%x09%ae%x09%at",Gr=256*1024*1024;function Dr(t,e){let r="",s=0;for(let n of t.split(`
21
- `)){if(n.startsWith("\0")){let[,p,c]=n.slice(1).split(" ");r=p??"",s=c?Number(c)*1e3:0;continue}if(n==="")continue;let o=n.split(" "),i=o[0];if(!i)continue;let a=i.startsWith("R")||i.startsWith("C")?o[2]:o[1];a&&e(a,r,s)}}function _r(t){let e=new Map;try{let r=Tt("git",["-C",t,"log","--since=90 days ago","--name-status","-M",`--format=${Rr}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:Gr});Dr(r,(s,n,o)=>{let i=e.get(s);if(i){i.commitCount90d+=1;return}e.set(s,{commitCount90d:1,lastAuthor:n||void 0,lastCommitAt:o||void 0})})}catch{return e}try{let r=Tt("git",["-C",t,"log","--name-status","-M",`--format=${Rr}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:Gr});Dr(r,(s,n,o)=>{e.has(s)||e.set(s,{commitCount90d:0,lastAuthor:void 0,lastCommitAt:o||void 0})})}catch{}return e}import Le from"fs";import Ho from"path";import{load as Lr}from"js-yaml";function Or(t){let e=t.lastIndexOf("@");return e>0?t.substring(0,e):t}function Qo(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)),Or(r)}).filter(Boolean)}function Vo(t,e){let r=t.startsWith("/")?t.slice(1):t,s=r.lastIndexOf("@");return s>0?{name:r.substring(0,s),version:e||r.substring(s+1)}:{name:r,version:e}}function qo(t){try{let e=Lr(t),r={dependencies:{}};for(let[s,n]of Object.entries(e))if(!(s==="__metadata"||!n?.version))for(let o of s.split(", ")){let i=Or(o);i&&(r.dependencies[i]={version:n.version,...n.dependencies!==void 0&&{dependencies:n.dependencies}})}return r}catch{return null}}function Xo(t){let e={dependencies:{}};for(let r of t.split(/\n\n+/)){let s=r.split(`
22
- `).filter(p=>p.trim().length>0&&!p.trim().startsWith("#"));if(s.length<2)continue;let n=s[0];if(!n||n.startsWith(" "))continue;let o=Qo(n);if(o.length===0)continue;let a=s.find(p=>p.trim().startsWith('version "'))?.match(/version "(.*?)"/)?.[1]??"";for(let p of o)e.dependencies[p]={version:a}}return e}function Yo(t){let e=Le.readFileSync(t,"utf-8"),r=JSON.parse(e),s={dependencies:{}};if(r.packages)for(let[n,o]of Object.entries(r.packages)){if(!n.startsWith("node_modules/"))continue;let i=n.replace("node_modules/","");i.includes("node_modules/")||(s.dependencies[i]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}else if(r.dependencies)for(let[n,o]of Object.entries(r.dependencies))s.dependencies[n]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}};return s}function Zo(t){let e=Le.readFileSync(t,"utf-8");if(e.includes("__metadata:")){let r=qo(e);if(r!==null)return r}return Xo(e)}function ei(t){let e=Le.readFileSync(t,"utf-8"),r={dependencies:{}};try{let s=Lr(e);if(s.packages)for(let[n,o]of Object.entries(s.packages)){let{name:i,version:a}=Vo(n,o.version);i&&(r.dependencies[i]={version:a,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}if(s.dependencies)for(let[n,o]of Object.entries(s.dependencies)){if(r.dependencies[n])continue;let i=typeof o=="string"?o:o.version;r.dependencies[n]={version:i||""}}}catch{}return r}function jr(t){let e=[["package-lock.json",Yo],["yarn.lock",Zo],["pnpm-lock.yaml",ei]];for(let[r,s]of e){let n=Ho.join(t,r);if(Le.existsSync(n))return s(n)}return null}import Wr from"path";function M(t){switch(Wr.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":case".cpp":case".cc":case".cxx":case".c":return"unknown";case".feature":return"gherkin";case".md":case".mdx":return"markdown";default:return"unknown"}}function E(t){let e=Wr.extname(t).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}import ti from"coffeescript";function I(t){return t.startsWith("'")||t.startsWith('"')?t.slice(1,-1):t}function $r(t){if(t){if(typeof t.originalValue=="string")return t.originalValue;if(typeof t.value=="string")return I(t.value)}}function _(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function ri(t){let e=new Set,r=/@tag\s+([a-zA-Z0-9_-]+)/g,s=r.exec(t);for(;s!==null;)s[1]&&e.add(s[1]),s=r.exec(t);return e}function si(t,e){let r=t.toLowerCase();return r.includes(".test.")||r.includes(".spec.")||e.has("test")?"test":"logic"}function ni(t,e){let r=$r(e.source);return r?{fromPath:t,toPath:"",rawSpecifier:r,isStyle:E(r),type:"static"}:null}function oi(t,e){let r=e.variable?.base?.value==="require",s=$r(e.args?.[0]?.base);return!r||!s?null:{fromPath:t,toPath:"",rawSpecifier:s,isStyle:E(s),type:"require"}}function zr(t,e){if(e)return[{name:e}];let r=t.value;if(r?.constructor?.name==="Class"){let n=_(r.variable);return n?[{name:n}]:[]}if(r?.base?.constructor?.name==="Obj"&&Array.isArray(r.base.properties))return r.base.properties.map(n=>_(n.variable)??_(n)).filter(n=>!!n).map(n=>({name:n}));let s=_(r);return s?[{name:s}]:[]}function ii(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=_(t.variable)??_(t.variable?.base);return e?[{name:e}]:[]}function ai(t,e,r,s){let n=e.constructor?.name;if(n==="ImportDeclaration"){let o=ni(t,e);o&&r.push(o)}else if(n==="Call"){let o=oi(t,e);o&&r.push(o)}else if(n==="Assign"){let o=_(e.variable?.base),i=e.variable?.properties?.[0]?.name?.value;o==="module"&&i==="exports"?s.push(...zr(e,void 0)):o==="exports"&&typeof i=="string"&&s.push(...zr(e,i))}else n==="ExportNamedDeclaration"&&e.clause?s.push(...ii(e.clause)):n==="ExportDefaultDeclaration"&&s.push({name:"default"})}function Pt(t,e,r,s){if(!(!e||typeof e!="object")){ai(t,e,r,s);for(let n in e){if(n==="locationData")continue;let o=e[n];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let i of o)Pt(t,i,r,s);else Pt(t,o,r,s)}}}function Br(t,e){let r=ri(e),s=si(t,r),n=[],o=[];try{Pt(t,ti.nodes(e),n,o)}catch{}let i=new Set,a=o.filter(p=>i.has(p.name)?!1:(i.add(p.name),!0));return{imports:n,exports:a,tags:Array.from(r).map(p=>({name:p,kind:"comment-marker"})),category:s}}import{AstBuilder as pi,GherkinClassicTokenMatcher as ci,Parser as li}from"@cucumber/gherkin";import{IdGenerator as ui}from"@cucumber/messages";var fi=ui.uuid();function At(t,e){let r=new Set;try{let s=new pi(fi),n=new ci,i=new li(s,n).parse(e);i.feature&&(i.feature.tags.forEach(a=>{r.add(a.name.startsWith("@")?a.name.slice(1):a.name)}),i.feature.children.forEach(a=>{a.scenario&&(a.scenario.tags.forEach(p=>{r.add(p.name.startsWith("@")?p.name.slice(1):p.name)}),a.scenario.examples.forEach(p=>{p.tags.forEach(c=>{r.add(c.name.startsWith("@")?c.name.slice(1):c.name)})})),a.rule&&a.rule.children.forEach(p=>{p.scenario&&p.scenario.tags.forEach(c=>{r.add(c.name.startsWith("@")?c.name.slice(1):c.name)})})}))}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"}}z("gherkin",At);import mi from"path";import{parser as gi}from"@lezer/go";var di=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,hi=/^\/\/go:build\s+(.+)$/,yi=/^\/\/\s*\+build\s+(.+)$/;function Kr(t,e){let r=[],s=new Map,n=new Set,o=new Set,a=gi.parse(e).cursor();do switch(a.name){case"LineComment":{let g=e.slice(a.from,a.to),d=g.match(di);d?.[1]&&n.add(d[1]);let S=g.match(hi);S&&Ur(S[1],o);let F=g.match(yi);F&&Ur(F[1],o);break}case"ImportSpec":{let g=a.node.getChild("String");if(g){let S=e.slice(g.from,g.to).slice(1,-1);r.push({fromPath:t,toPath:"",rawSpecifier:S,isExternal:!0,isStyle:!1,type:"static"})}break}case"FunctionDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let g=a.node.getChild("DefName")??a.node.getChild("TypeSpec")?.getChild("DefName")??a.node.getChild("VarSpec")?.getChild("DefName")??a.node.getChild("ConstSpec")?.getChild("DefName");if(g){let d=e.slice(g.from,g.to);d!=="_"&&/^[A-Z]/.test(d)&&!s.has(d)&&s.set(d,{name:d})}break}}while(a.next());let p=r.some(g=>g.rawSpecifier==="testing"),c=mi.basename(t).endsWith("_test.go")||n.has("test")||p?"test":"logic",m=new Set([...n,...o]);return{imports:r,exports:Array.from(s.values()),tags:Array.from(m).map(g=>({name:g,kind:"comment-marker"})),category:c}}function Ur(t,e){for(let r of t.split(/[\s,&|!()]+/)){let s=r.trim();s&&s!=="ignore"&&e.add(s)}}import xi from"livescript";function Si(t){let e=new Set,r=/@tag\s+([a-zA-Z0-9_-]+)/g,s=r.exec(t);for(;s!==null;)s[1]&&e.add(s[1]),s=r.exec(t);return e}function bi(t,e){let r=t.toLowerCase();return r.includes(".test.")||r.includes(".spec.")||e.has("test")?"test":"logic"}var vi=new Set(["first_line","first_column","last_line","last_column","line","column"]);function ki(t,e){let r=t.constructor?.name||t.type;if(r==="Import"){let s=t.right?.value;if(typeof s=="string"){let n=I(s);return{fromPath:e,toPath:"",rawSpecifier:n,isStyle:E(n),type:"static"}}}if(r==="Chain"&&t.head?.value==="require"){let s=t.tails?.[0];if(s?.constructor?.name==="Call"||s?.type==="Call"){let n=s.args?.[0]?.value;if(typeof n=="string"){let o=I(n);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:E(o),type:"require"}}}}return null}function Mt(t,e){if(!t||typeof t!="object")return[];let r=[],s=ki(t,e);s&&r.push(s);for(let n in t){if(vi.has(n))continue;let o=t[n];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let i of o)r.push(...Mt(i,e));else r.push(...Mt(o,e))}return r}function Jr(t,e){let r=Si(e),s=bi(t,r),n=[];try{n=Mt(xi.ast(e),t)}catch{}return{imports:n,exports:[],tags:Array.from(r).map(o=>({name:o,kind:"comment-marker"})),category:s}}import Ci from"luaparse";function wi(t){let e=new Set,r=/@tag\s+([a-zA-Z0-9_-]+)/g,s=r.exec(t);for(;s!==null;)s[1]&&e.add(s[1]),s=r.exec(t);return e}function Ei(t,e){let r=t.toLowerCase();return r.includes(".test.")||r.includes(".spec.")||e.has("test")?"test":"logic"}function Fi(t,e){let r=[];function s(n){if(!(!n||typeof n!="object")){if((n.type==="CallExpression"||n.type==="StringCallExpression")&&n.base?.type==="Identifier"&&n.base?.name==="require"){let o;if(n.type==="CallExpression"){let i=n.arguments?.[0];i?.type==="StringLiteral"&&(o=I(i.raw))}else if(n.type==="StringCallExpression"){let i=n.argument;i?.type==="StringLiteral"&&(o=I(i.raw))}o&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:E(o),type:"require"})}for(let o in n){if(o==="loc")continue;let i=n[o];if(i&&typeof i=="object")if(Array.isArray(i))for(let a of i)s(a);else s(i)}}}return s(t),r}function Ti(t){let e=new Set;for(let r of t)r.type==="LocalStatement"&&r.variables.forEach((s,n)=>{r.init[n]?.type==="TableConstructorExpression"&&e.add(s.name)});return e}function Pi(t){let e=t[t.length-1];if(e?.type!=="ReturnStatement")return[];let r=e.arguments[0];if(r?.type!=="TableConstructorExpression")return[];let s=[];for(let n of r.fields)n.type==="TableKeyString"&&s.push({name:n.key.name});return s}function Ai(t){let e=t.body,r=Ti(e),s=Pi(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)&&s.push({name:o.identifier.identifier.name}):o.identifier?.type==="Identifier"&&!o.isLocal&&s.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)&&s.push({name:i.identifier.name});let n=new Set;return s.filter(o=>n.has(o.name)?!1:(n.add(o.name),!0))}function Hr(t,e){let r=wi(e),s=Ei(t,r),n=[],o=[];try{let i=Ci.parse(e);n=Fi(i,t),o=Ai(i)}catch{}return{imports:n,exports:o,tags:Array.from(r).map(i=>({name:i,kind:"comment-marker"})),category:s}}var Mi=["http://","https://","mailto:","//"],Ii="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",Ni=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${Ii})\\b`,"g"),Qr;async function Ri(){return Qr??=(async()=>{let{unified:t}=await import("unified"),e=(await import("remark-parse")).default;return t().use(e)})(),Qr}function Gi(t){let e=t.trim();return e.length===0||e.startsWith("#")||Mi.some(r=>e.startsWith(r))}function Di(t,e){let r=t.match(Ni);return r?r.map(s=>({fromPath:e,toPath:"",rawSpecifier:s,isStyle:!1,type:"static"})):[]}function Vr(t,e,r){if(t.type==="link"&&typeof t.url=="string"&&!Gi(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(...Di(t.value,e)),Array.isArray(t.children))for(let s of t.children)Vr(s,e,r)}async function qr(t,e){let s=(await Ri()).parse(e),n=[];Vr(s,t,n);let o=new Set;return{imports:n.filter(a=>o.has(a.rawSpecifier)?!1:(o.add(a.rawSpecifier),!0)),exports:[],tags:[],category:"other"}}import _i from"path";import{parser as Li}from"@lezer/python";var Oi=new Set(["pytest","unittest","nose","hypothesis"]);function Xr(t,e){let r=[],s=[],n=new Set,o=_i.basename(t).toLowerCase(),a=Li.parse(e).cursor();do switch(a.name){case"Comment":{let c=e.slice(a.from,a.to).match(/#\s*@tag\s+([a-zA-Z0-9_-]+)/);c?.[1]&&n.add(c[1]);break}case"ImportStatement":{for(let c of ji(a.node,e,t))r.push(c);break}case"FunctionDefinition":case"ClassDefinition":{let c=a.node.parent;if(c?.name==="Script"||c?.name==="DecoratedStatement"&&c.parent?.name==="Script"){let g=a.node.getChild("VariableName");g&&s.push({name:e.slice(g.from,g.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let c=a.node.firstChild;c?.name==="VariableName"&&s.push({name:e.slice(c.from,c.to)})}break}}while(a.next());let p=Bi(o,r,n);return p==="test"&&n.add("test"),{imports:r,exports:s,tags:Array.from(n).map(c=>({name:c,kind:"comment-marker"})),category:p}}function ji(t,e,r){let s=t.firstChild;return s?s.name==="from"?Wi(t,e,r):zi(t,e,r):[]}function Wi(t,e,r){let s=t.firstChild;if(!s)return[];let n=s.nextSibling;for(;n&&n.name!=="import";)n=n.nextSibling;if(!n)return[];let o=e.slice(s.to,n.from).trim(),i=$i(n.nextSibling,e);if(!i.length)return[];let a=0;for(;a<o.length&&o[a]===".";)a++;let p=o.slice(a);if(a===0)return[ae(r,o,i,!0)];let c=a===1?"./":"../".repeat(a-1);return p?[ae(r,c+p.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[ae(r,c.slice(0,-1),["*"],!1)]:i.map(m=>ae(r,c+m,[m],!1))}function zi(t,e,r){let s=[],n=t.firstChild?.nextSibling??null;for(;n;){if(n.name==="VariableName"){let o=e.slice(n.from,n.to);for(;n.nextSibling?.name==="."&&n.nextSibling.nextSibling?.name==="VariableName";)n=n.nextSibling.nextSibling,o+=`.${e.slice(n.from,n.to)}`;n.nextSibling?.name==="as"&&(n=n.nextSibling.nextSibling??n.nextSibling),s.push(ae(r,o,["*"],!0))}n=n.nextSibling}return s}function $i(t,e){let r=[],s=t;for(;s;)s.name==="*"?r.push("*"):s.name==="VariableName"&&(r.push(e.slice(s.from,s.to)),s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling)),s=s.nextSibling;return r}function ae(t,e,r,s){return{fromPath:t,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:s,type:"static",symbols:r.length>0?r:void 0}}function Bi(t,e,r){return t.startsWith("test_")||t.endsWith("_test.py")?"test":t==="conftest.py"||t==="setup.py"?"config":r.has("test")||e.some(s=>Oi.has(s.rawSpecifier))?"test":"logic"}import Zr from"path";import l from"typescript";import h from"typescript";function Ui(t){let e=1;function r(s){switch(s.kind){case h.SyntaxKind.IfStatement:case h.SyntaxKind.ConditionalExpression:case h.SyntaxKind.ForStatement:case h.SyntaxKind.ForInStatement:case h.SyntaxKind.ForOfStatement:case h.SyntaxKind.WhileStatement:case h.SyntaxKind.DoStatement:case h.SyntaxKind.CatchClause:case h.SyntaxKind.CaseClause:e++;break;case h.SyntaxKind.BinaryExpression:{let n=s.operatorToken.kind;(n===h.SyntaxKind.AmpersandAmpersandToken||n===h.SyntaxKind.BarBarToken||n===h.SyntaxKind.QuestionQuestionToken)&&e++;break}}h.forEachChild(s,r)}return r(t),e}function Ki(t){let e=0;function r(s,n,o){if(h.isIfStatement(s)){e+=o?1:1+n;let a=o?n:n+1;r(s.expression,a,!1),r(s.thenStatement,a,!1),s.elseStatement&&(h.isIfStatement(s.elseStatement)?r(s.elseStatement,n,!0):(e+=1,r(s.elseStatement,n+1,!1)));return}if(h.isForStatement(s)||h.isForInStatement(s)||h.isForOfStatement(s)||h.isWhileStatement(s)||h.isDoStatement(s)||h.isSwitchStatement(s)){e+=1+n,h.forEachChild(s,a=>r(a,n+1,!1));return}if(h.isCatchClause(s)){e+=1+n,h.forEachChild(s,a=>r(a,n,!1));return}if(h.isConditionalExpression(s)&&(e+=1),h.isBinaryExpression(s)){let a=s.operatorToken.kind;(a===h.SyntaxKind.AmpersandAmpersandToken||a===h.SyntaxKind.BarBarToken||a===h.SyntaxKind.QuestionQuestionToken)&&(e+=1)}if(n>0&&(h.isFunctionDeclaration(s)||h.isFunctionExpression(s)||h.isArrowFunction(s))){e+=1+n,h.forEachChild(s,a=>r(a,n+1,!1));return}h.forEachChild(s,a=>r(a,n,!1))}return r(t,0,!1),e}function It(t){return{complexity:Ui(t),cognitiveComplexity:Ki(t)}}import b from"typescript";var Nt=new Set(["test","describe","it"]);function Yr(t,e){Ji(t,e),Qi(t,e),Vi(t,e),qi(t,e)}function Ji(t,e){if((b.isFunctionDeclaration(t)||b.isVariableDeclaration(t))&&t.name&&b.isIdentifier(t.name)&&Hi(t)){let r;if(b.isFunctionDeclaration(t))r="function";else{let s=t.initializer;r=s&&(b.isArrowFunction(s)||b.isFunctionExpression(s))?"function":"variable"}e.tags.add({name:t.name.text,kind:r})}}function Hi(t){if(b.isFunctionDeclaration(t))return b.isSourceFile(t.parent);let e=t.parent?.parent;return!!e&&b.isSourceFile(e.parent)}function Qi(t,e){if(!b.isStringLiteral(t))return;let r=t.text.match(/@[\w-]+/g);if(r)for(let s of r)e.tags.add({name:s.substring(1),kind:"comment-marker"})}function Vi(t,e){if(!b.isSourceFile(t))return;let r=/@tag\s+([a-zA-Z0-9_-]+)/g,s=t.getFullText(),n=r.exec(s);for(;n!==null;)n[1]&&e.tags.add({name:n[1],kind:"comment-marker"}),n=r.exec(s)}function qi(t,e){if(b.isCallExpression(t)&&Xi(t.expression))for(let r of t.arguments)b.isObjectLiteralExpression(r)&&Yi(r,e)}function Xi(t){return b.isIdentifier(t)?Nt.has(t.text):!!(b.isPropertyAccessExpression(t)&&(Nt.has(t.name.text)||b.isIdentifier(t.expression)&&Nt.has(t.expression.text)))}function Yi(t,e){for(let r of t.properties){if(!b.isPropertyAssignment(r)||!b.isIdentifier(r.name)||r.name.text!=="tags"&&r.name.text!=="tag")continue;let{initializer:s}=r,n=b.isArrayLiteralExpression(s)?s.elements.filter(b.isStringLiteral):r.name.text==="tag"&&b.isStringLiteral(s)?[s]:[];for(let o of n)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function Rt(t,e,r){let s=[],n=new Map,o=new Set,i=l.createSourceFile(t,e,l.ScriptTarget.Latest,!0,r==="typescript"?l.ScriptKind.TSX:l.ScriptKind.JSX),a={filePath:t,imports:s,exports:n,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},p=R=>{ra(R,a),l.forEachChild(R,p)};p(i);let c=ma(t,a);(c==="test"||c==="barrel")&&o.add({name:c,kind:"comment-marker"}),c!=="test"&&ga(a,i);let m=i.statements[0],g=m?ts(m):void 0,{complexity:d,cognitiveComplexity:S}=It(i),F=Zi(i);return{imports:s,exports:Array.from(n.values()),tags:Array.from(o),category:c,rawCallEdges:a.rawCallEdges??[],complexity:d,cognitiveComplexity:S,...F.length>0?{functions:F}:{},...g!==void 0?{description:g}:{}}}function Zi(t){let e=[],r=(n,o)=>{let{complexity:i,cognitiveComplexity:a}=It(o),p=t.getLineAndCharacterOfPosition(o.getStart(t)).line+1;e.push({name:n,line:p,complexity:i,cognitiveComplexity:a})},s=(n,o)=>{if(l.isFunctionDeclaration(n)&&n.name&&n.body?r(n.name.text,n):l.isVariableDeclaration(n)&&l.isIdentifier(n.name)&&n.initializer&&(l.isArrowFunction(n.initializer)||l.isFunctionExpression(n.initializer))?r(n.name.text,n.initializer):o&&l.isMethodDeclaration(n)&&l.isIdentifier(n.name)&&n.body?r(`${o}.${n.name.text}`,n):o&&l.isConstructorDeclaration(n)&&n.body?r(`${o}.constructor`,n):o&&l.isGetAccessorDeclaration(n)&&l.isIdentifier(n.name)&&n.body?r(`${o}.get ${n.name.text}`,n):o&&l.isSetAccessorDeclaration(n)&&l.isIdentifier(n.name)&&n.body&&r(`${o}.set ${n.name.text}`,n),l.isClassDeclaration(n)&&n.name){let i=n.name.text;l.forEachChild(n,a=>s(a,i));return}l.forEachChild(n,i=>s(i,o))};return s(t,void 0),e}function es(t,e,r,s){let n={name:t},o=ts(r);o!==void 0&&(n.doc=o);let i=ea(e);i!==void 0&&(n.flags=i);let a=ta(e,s);return a!==void 0&&(n.signature=a),n}function ts(t){let e=l.getJSDocCommentsAndTags(t);for(let r of e)if(l.isJSDoc(r)&&r.comment)return l.getTextOfJSDocComment(r.comment)||void 0}function ea(t){let e=new Set(["deprecated","internal","public","alpha","beta"]),r=l.getJSDocTags(t).map(s=>s.tagName.text).filter(s=>e.has(s));return r.length>0?r:void 0}function ta(t,e){let r=l.createPrinter({removeComments:!0}),s=n=>r.printNode(l.EmitHint.Unspecified,n,e);if(l.isFunctionDeclaration(t)||l.isMethodDeclaration(t)){let n=t.parameters.map(s).join(", "),o=t.type?s(t.type):"void";return`${t.typeParameters?`<${t.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${n}) => ${o}`}if(l.isVariableDeclaration(t)){if(t.type)return s(t.type);if(t.initializer&&(l.isArrowFunction(t.initializer)||l.isFunctionExpression(t.initializer))){let n=t.initializer,o=n.parameters.map(s).join(", "),i=n.type?s(n.type):"unknown";return`(${o}) => ${i}`}return}if(l.isClassDeclaration(t)&&t.name)return`class ${t.name.text}`;if(l.isInterfaceDeclaration(t))return`interface ${t.name.text}`;if(l.isTypeAliasDeclaration(t))return s(t.type);if(l.isEnumDeclaration(t))return`enum ${t.name.text}`}function ra(t,e){sa(t,e),na(t,e),ia(t,e),aa(t,e),fa(t,e),Yr(t,e)}function sa(t,e){if(!l.isSourceFile(t))return;let r=t.statements.filter(s=>!l.isEmptyStatement(s));e.totalStatements=r.length,e.exportStatements=r.filter(s=>l.isExportDeclaration(s)||l.isExportAssignment(s)||Gt(s)).length}function na(t,e){if(l.isJsxElement(t)||l.isJsxSelfClosingElement(t)||l.isJsxFragment(t)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(l.isFunctionDeclaration(t)||l.isMethodDeclaration(t)||l.isArrowFunction(t)||l.isClassDeclaration(t)||l.isVariableStatement(t)||l.isEnumDeclaration(t)){e.hasTypesOnly=!1;return}l.isExportDeclaration(t)&&!oa(t)&&(e.hasTypesOnly=!1)}function oa(t){return t.isTypeOnly?!0:!t.exportClause||!l.isNamedExports(t.exportClause)?!1:t.exportClause.elements.every(e=>e.isTypeOnly)}function ia(t,e){if(!l.isImportDeclaration(t)||!t.moduleSpecifier||!l.isStringLiteral(t.moduleSpecifier))return;let r=[];if(t.importClause&&(t.importClause.name&&r.push("default"),t.importClause.namedBindings))if(l.isNamedImports(t.importClause.namedBindings))for(let n of t.importClause.namedBindings.elements)r.push(n.name.text);else l.isNamespaceImport(t.importClause.namedBindings)&&r.push("*");let s=r.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.moduleSpecifier.text,isStyle:E(t.moduleSpecifier.text),type:s,symbols:r.length>0?r:void 0})}function aa(t,e){l.isExportDeclaration(t)?pa(t,e):l.isExportAssignment(t)?e.exports.set("default",{name:"default"}):Gt(t)&&ua(t,e)}function pa(t,e){if(t.moduleSpecifier&&l.isStringLiteral(t.moduleSpecifier))ca(t,t.moduleSpecifier.text,e);else if(t.exportClause&&l.isNamedExports(t.exportClause))for(let r of t.exportClause.elements){let s=r.name.text;e.exports.set(s,{name:s})}}function ca(t,e,r){let s=la(t),n={fromPath:r.filePath,toPath:"",rawSpecifier:e,isStyle:E(e),type:"re-export"};s.length>0&&(n.symbols=s),r.imports.push(n)}function la(t){return t.exportClause?l.isNamedExports(t.exportClause)?t.exportClause.elements.map(e=>e.name.text):[]:["*"]}function ua(t,e){if((l.isFunctionDeclaration(t)||l.isClassDeclaration(t)||l.isInterfaceDeclaration(t)||l.isTypeAliasDeclaration(t)||l.isEnumDeclaration(t))&&t.name){let s=t.name.text;e.exports.set(s,es(s,t,t,e.sourceFile));return}if(l.isVariableStatement(t)){for(let s of t.declarationList.declarations)if(l.isIdentifier(s.name)){let n=s.name.text;e.exports.set(n,es(n,s,t,e.sourceFile))}}}function fa(t,e){if(!l.isCallExpression(t))return;let r=t.arguments[0];!r||!l.isStringLiteral(r)||(t.expression.kind===l.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:E(r.text),type:"dynamic"}):l.isIdentifier(t.expression)&&t.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:E(r.text),type:"require"}))}function ma(t,e){let r=Zr.basename(t).toLowerCase(),s=Zr.extname(t).toLowerCase();return q().some(o=>r.includes(o))?"test":Ut(r)?"config":e.imports.some(o=>Ue().some(i=>o.rawSpecifier.includes(i)))?"test":s===".tsx"||s===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>Je()?"barrel":"logic"}function Gt(t){return l.canHaveModifiers(t)&&l.getModifiers(t)?.some(e=>e.kind===l.SyntaxKind.ExportKeyword)===!0}function ga(t,e){let r=t.rawCallEdges??[];t.rawCallEdges=r;let s=new Map;for(let n of e.statements){if(!l.isImportDeclaration(n)||!l.isStringLiteral(n.moduleSpecifier))continue;let o=n.moduleSpecifier.text,i=n.importClause;if(i&&(i.name&&s.set(i.name.text,o),i.namedBindings&&l.isNamedImports(i.namedBindings)))for(let a of i.namedBindings.elements)s.set(a.name.text,o)}if(s.size!==0)for(let n of e.statements){let o=ha(n);if(o){let i=ya(n);i&&Oe(i,o,s,r);continue}l.isClassDeclaration(n)&&n.name&&da(n,s,r)}}function da(t,e,r){let s=t.name.text;for(let n of t.members)l.isMethodDeclaration(n)&&n.body&&l.isIdentifier(n.name)?Oe(n.body,`${s}.${n.name.text}`,e,r):l.isConstructorDeclaration(n)&&n.body&&Oe(n.body,`${s}.constructor`,e,r)}function ha(t){if(Gt(t)){if(l.isFunctionDeclaration(t)&&t.name)return t.name.text;if(l.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(l.isIdentifier(e.name)&&e.initializer&&(l.isArrowFunction(e.initializer)||l.isFunctionExpression(e.initializer)))return e.name.text}}}function ya(t){if(l.isFunctionDeclaration(t))return t.body;if(l.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(e.initializer&&(l.isArrowFunction(e.initializer)||l.isFunctionExpression(e.initializer)))return e.initializer}}function Oe(t,e,r,s){if(l.isCallExpression(t)&&l.isIdentifier(t.expression)){let n=t.expression.text,o=r.get(n);o&&!s.some(i=>i.from===e&&i.to===n&&i.toSpecifier===o)&&s.push({from:e,to:n,toSpecifier:o})}l.forEachChild(t,n=>Oe(n,e,r,s))}function je(t,e){if(e.length===0)return"ui";let r=!1;return t.walk(s=>{if(s.type==="rule")return r=!0,!1}),r?"ui":"barrel"}import ss from"postcss";import*as xa from"postcss-less";var Sa=xa,ns=new Set(["reference","inline"]);function rs(t){return t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("data:")}function ba(t){let e=t.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function va(t,e){let r=t.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(r){let o=r[1]?.trim()??"",i=r[2]??"";if(!i)return null;let a=ns.has(o)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a,...rs(i)?{isExternal:!0}:{}}}let s=t.match(/^url\(['"]?([^'")]+)['"]?\)/),n=s?s[1]?.trim()??"":t.match(/^['"]([^'"]+)['"]/)?.[1]??"";return n?{fromPath:e,toPath:"",rawSpecifier:n,isStyle:!0,type:"static",...rs(n)?{isExternal:!0}:{}}:null}function ka(t,e){let r=[],s=/url\(['"]?([^'")]+)['"]?\)/g,n=s.exec(t);for(;n!==null;){let o=n[1]?.trim()??"";ba(o)&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),n=s.exec(t)}return r}function os(t,e){let r=[];return t.walk(s=>{if(s.type==="atrule"&&s.name==="import"){let n=va(s.params,e);n&&r.push(n)}s.type==="decl"&&r.push(...ka(s.value,e))}),r}function Ca(t){return t.replace(/(?<!:)\/\/.*/g,"")}function wa(t,e){let r=[],s=/@import\s+(?:\(([^)]+)\)\s+)?['"]([^'"]+)['"]/g,n=s.exec(t);for(;n!==null;){let o=n[1]?.trim()??"",i=n[2]??"";if(i){let a=ns.has(o)?"side-effect":"static";r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a})}n=s.exec(t)}return r}function is(t,e){let r=ss.parse(Ca(t));return{imports:os(r,e),root:r}}function Ea(t){let e=[],r=[];for(let s of t.nodes??[]){if(s.type!=="atrule")continue;let{value:n}=s;if(n===void 0)continue;let o=s.name;o&&(e.push({name:o}),r.push({name:o,kind:"variable"}))}return{exports:e,tags:r}}function as(t,e){try{let r=Sa.parse(t),{exports:s,tags:n}=Ea(r);return{imports:os(r,e),root:r,exports:s,tags:n}}catch{return{imports:wa(t,e),root:ss.parse(""),exports:[],tags:[]}}}import{parse as Fa}from"postcss-scss";function ps(t){return t.startsWith("_")||t.startsWith("-")}function Ta(t){return!!(t.startsWith("sass:")||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("_"))}function Pa(t){let e=t.match(/^['"]([^'"]+)['"]/);if(!e?.[1])return{specifier:""};let r=e[1],n=t.match(/\bas\s+(\S+)/)?.[1];return n!==void 0?{specifier:r,alias:n}:{specifier:r}}function Aa(t){let e=[],r=[];for(let s of t.nodes??[]){if(s.type==="decl"&&s.prop.startsWith("$")){let n=s.prop.slice(1);if(!n||ps(n))continue;e.push({name:n}),r.push({name:n,kind:"variable"});continue}if(s.type==="atrule"&&(s.name==="mixin"||s.name==="function")){let o=s.params.match(/^([\w-]+)/)?.[1];if(!o||ps(o))continue;let i=s.params.trim();e.push(i.includes("(")?{name:o,signature:i}:{name:o}),r.push({name:o,kind:"function"})}}return{exports:e,tags:r}}function cs(t,e){let r=Fa(t),s=[];r.walk(i=>{if(i.type!=="atrule")return;let{name:a,params:p}=i;if(a!=="import"&&a!=="use"&&a!=="forward")return;let{specifier:c,alias:m}=Pa(p);if(!c)return;let g={fromPath:e,toPath:"",rawSpecifier:c,isStyle:!0,type:a==="forward"?"re-export":"static",...Ta(c)?{isExternal:!0}:{}};m&&(g.symbols=[m]),s.push(g)});let{exports:n,tags:o}=Aa(r);return{imports:s,root:r,exports:n,tags:o}}function ls(t,e){let r=[],s=/@require\s+['"]([^'"]+)['"]/g,n=s.exec(t);for(;n!==null;){let i=n[1];i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"require"}),n=s.exec(t)}let o=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(n=o.exec(t);n!==null;){let i=n[1];i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),n=o.exec(t)}return r}function us(t,e){if(e.length===0)return"ui";try{let r=Be("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 pe(t,e){let r=M(t);if(r==="stylus"){let o=ls(e,t);return{imports:o,exports:[],tags:[],category:us(e,o)}}if(r==="scss"){let{imports:o,root:i,exports:a,tags:p}=cs(e,t);return{imports:o,exports:a,tags:p,category:je(i,o)}}if(r==="less"){let{imports:o,root:i,exports:a,tags:p}=as(e,t);return{imports:o,exports:a,tags:p,category:je(i,o)}}let{imports:s,root:n}=is(e,t);return{imports:s,exports:[],tags:[],category:je(n,s)}}for(let[t,e]of[["javascript",(r,s)=>Rt(r,s,"javascript")],["typescript",(r,s)=>Rt(r,s,"typescript")],["css",pe],["scss",pe],["less",pe],["stylus",pe],["coffeescript",Br],["livescript",Jr],["lua",Hr],["python",Xr],["go",Kr],["gherkin",At],["markdown",qr]])z(t,e);async function fs(t,e){let r=M(t),s=xr(r);return s?s(t,e):{imports:[],exports:[],tags:[],category:"other"}}import ms from"path";function ds(t,e){for(let r of t.values()){let s=e.get(r.path);s!==void 0&&(r.coveragePct=s)}}function hs(t,e){for(let r of t)if(r.isExternal){let s=r.rawSpecifier.startsWith("@")?r.rawSpecifier.split("/").slice(0,2).join("/"):r.rawSpecifier.split("/")[0];s&&!e.some(n=>n.name===s)&&e.push({name:s,kind:"library"})}}function ys(t){for(let e of t.values())if(e.category==="test")for(let r of e.imports){if(r.isExternal||!r.toPath)continue;let s=t.get(r.toPath);s&&(s.category!=="logic"&&s.category!=="barrel"||(s.testedBy??=[],s.testedBy.includes(e.path)||s.testedBy.push(e.path)))}}function xs(t){for(let e of t.values())if(e.type==="markdown")for(let r of e.imports){if(r.isExternal||!r.toPath)continue;let s=t.get(r.toPath);!s||s===e||(s.documentedBy??=[],s.documentedBy.includes(e.path)||s.documentedBy.push(e.path),s.category==="logic"&&(s.lastCommitAt??0)>(e.lastCommitAt??0)&&(e.staleFor??=[],e.staleFor.includes(s.path)||e.staleFor.push(s.path)))}}function gs(t){return Math.round(t*1e4)/1e4}function Ss(t){for(let e of t.values()){let r=[];for(let s of e.imports){if(s.isExternal||!s.toPath)continue;let n=t.get(s.toPath);if(!n||n.exports.length===0)continue;let o;if(s.symbols===void 0){if(s.type==="side-effect")continue;o=1}else s.symbols.includes("*")?o=1:o=s.symbols.length/n.exports.length;s.exportUsageRatio=gs(Math.min(1,o)),r.push(s.exportUsageRatio)}r.length>0&&(e.avgExportUsage=gs(r.reduce((s,n)=>s+n,0)/r.length),e.maxExportUsage=Math.max(...r))}}function Dt(t,e,r){e&&(t.some(s=>s.name===e&&s.kind===r)||t.push({name:e,kind:r}))}function Ma(t,e){let r=e.toPath,s=ms.basename(r,ms.extname(r)).replace(/\.(test|spec)$/,"");Dt(t.tags,s,"import")}function Ia(t,e){if(!(!e.symbols||e.symbols.includes("*")))for(let r of e.symbols)Dt(t.tags,r,"import")}function Na(t,e,r){let s=r.get(e.toPath);if(!(!s||s.category==="test"))for(let n of s.tags)n.kind==="comment-marker"&&Dt(t.tags,n.name,"comment-marker")}function bs(t){for(let e of t.values())if(e.category==="test")for(let r of e.imports)!r.toPath||r.isExternal||(Ma(e,r),Ia(e,r),Na(e,r,t))}import We from"fs";import N from"path";import Cs from"fs";import Q from"path";var ce=class{extensions=[".go"];goModCache=new Map;resolve(e,r,s,n){let{mod:o,replaces:i}=this.readGoMod(s);if(!o)return null;let a=this.applyReplace(r,i,s);if(a!==void 0)return ks(a);if(r!==o&&!r.startsWith(`${o}/`))return null;let p=r.slice(o.length).replace(/^\//,"");return p?ks(Q.join(s,p)):null}readGoMod(e){let r=this.goModCache.get(e);if(r!==void 0)return r;let s={mod:null,replaces:new Map};try{let n=Cs.readFileSync(Q.join(e,"go.mod"),"utf-8"),o=Ra(n,e);return this.goModCache.set(e,o),o}catch{return this.goModCache.set(e,s),s}}applyReplace(e,r,s){for(let[n,o]of r){if(e===n)return o;if(e.startsWith(`${n}/`)){let i=e.slice(n.length+1);return Q.join(o,i)}}}};function Ra(t,e){let r=t.split(`
23
- `),s=null,n=new Map,o=!1;for(let i of r){let a=i.trim();if(a.startsWith("module ")){s=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){o=!0;continue}if(o&&a===")"){o=!1;continue}if(o&&a.includes("=>")){vs(a,e,n);continue}!o&&/^replace\s+/.test(a)&&a.includes("=>")&&vs(a.replace(/^replace\s+/,""),e,n)}return{mod:s,replaces:n}}function vs(t,e,r){let[s,n]=t.split("=>").map(a=>a.trim());if(!s||!n)return;let o=s.split(/\s+/)[0];if(!n.startsWith(".")&&!n.startsWith("/"))return;let i=Q.isAbsolute(n)?n:Q.resolve(e,n);r.set(o,i)}function ks(t){let e;try{e=Cs.readdirSync(t,{withFileTypes:!0})}catch{return null}let r=e.filter(s=>s.isFile()&&s.name.endsWith(".go")&&!s.name.endsWith("_test.go")).map(s=>({path:Q.join(t,s.name),isExternal:!1})).sort((s,n)=>s.path.localeCompare(n.path));return r.length>0?r:null}import Ga from"fs";import _t from"path";var le=class{extensions=[".lua"];resolve(e,r,s,n){let o=r.replace(/\./g,_t.sep),i=[s,_t.join(s,"lib")];for(let a of i){if(!Ga.existsSync(a))continue;let p=n(_t.join(a,"_dummy.lua"),o);if(p)return[p]}return null}};import Da from"path";var ue=class{extensions=[".md",".mdx"];resolve(e,r,s,n){let o=n(Da.join(s,"_dummy"),`./${r}`);return o?[o]:null}};import _a from"fs";import Lt from"path";var fe=class{extensions=[".py"];resolve(e,r,s,n){let o=r.replace(/\./g,Lt.sep),i=Lt.join(s,`${o}.py`);if(ws(i))return[{path:i,isExternal:!1}];let a=Lt.join(s,o,"__init__.py");return ws(a)?[{path:a,isExternal:!1}]:null}};function ws(t){try{return _a.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}import Es from"path";var La=["~","http://","https://","//","data:","sass:"],me=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,r,s,n){if(La.some(m=>r.startsWith(m)))return null;let o=n(e,r);if(o)return[o];let i=Es.dirname(r),a=Es.basename(r),p=i==="."?`_${a}`:`${i}/_${a}`,c=n(e,p);return c?[c]:null}};var L=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 fe,new le,new ce,new me,new ue]}rootDir;workspaceMap;tsconfigSearchPaths;pathAliases;langResolvers;resolveAll(e,r){let s=this.resolvePathAlias(r);if(s)return[s];if(r.startsWith(".")||r.startsWith("/")){let i=this.resolveLocalPath(e,r);return i?[i]:[]}let n=(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,n);if(a)return a}let o=this.resolveWorkspaceImport(r);return o?[o]:[{path:r,isExternal:!0}]}resolve(e,r){let s=this.resolvePathAlias(r);if(s)return s;if(r.startsWith(".")||r.startsWith("/"))return this.resolveLocalPath(e,r);let n=(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,n);if(a)return a[0]??null}let o=this.resolveWorkspaceImport(r);return o||{path:r,isExternal:!0}}resolveLocalPath(e,r){let s=N.dirname(e),n=r.startsWith("/")?r:N.resolve(s,r),o=!n.startsWith(this.rootDir),i=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature",".md",".mdx"],a=n.match(/\.(js|mjs|cjs)$/);if(a){let p=n.slice(0,-a[0].length);for(let c of[".ts",".tsx"]){let m=this.tryExtensions(p,c,o);if(m)return m}}for(let p of i){let c=this.tryExtensions(n,p,o);if(c)return c}return o?{path:n,isExternal:!0}:null}tryExtensions(e,r,s){let n=e+r;if(this.isFile(n))return{path:n,isExternal:s};let o=N.join(e,`index${r}`);if(this.isFile(o))return{path:o,isExternal:s};if(r===".py"){let i=N.join(e,"__init__.py");if(this.isFile(i))return{path:i,isExternal:s}}return null}isFile(e){try{return We.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){if(this.pathAliases)for(let r in this.pathAliases){let s=this.matchAliasPattern(r,e),n=this.pathAliases[r];if(s&&n){let o=this.tryAliasSubstitutions(n,s[1]||"");if(o)return o}}for(let r of this.tsconfigSearchPaths){let s=N.join(r,"tsconfig.json");if(We.existsSync(s))try{let o=JSON.parse(We.readFileSync(s,"utf-8")).compilerOptions?.paths;if(!o)continue;for(let i in o){let a=this.matchAliasPattern(i,e);if(a){let p=this.tryAliasSubstitutions(o[i],a[1]||"",r);if(p)return p}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,r){let s=this.aliasRegexCache.get(e);if(!s){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");s=new RegExp(`^${n}$`),this.aliasRegexCache.set(e,s)}return r.match(s)}tryAliasSubstitutions(e,r,s=this.rootDir){let n=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let o of e){let i=o.replace("*",r),a=N.resolve(s,i);for(let p of n){let c=this.tryExtensions(a,p,!1);if(c)return c}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[r,s]of this.workspaceMap){if(e!==r&&!e.startsWith(`${r}/`))continue;let n=e.slice(r.length),o={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:r};if(!n){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let p=N.join(s,a);try{if(We.statSync(p,{throwIfNoEntry:!1})?.isFile())return{...o,path:p}}catch{}}return{...o,path:s}}let i=this.resolveLocalPath(N.join(s,"_dummy"),n.slice(1));return i?{...o,path:i.path}:null}return null}};var ja=["tests","test","__tests__","specs","spec"],Fs=new Set(["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"]),Wa=20;function za(t,e){if(t.length===0)return e;let r=t.map(i=>C.dirname(i).split(C.sep)),s=r[0];for(let i of r.slice(1)){let a=0;for(;a<s.length&&a<i.length&&s[a]===i[a];)a++;s=s.slice(0,a)}let n=s.join(C.sep)||C.sep,o=C.relative(e,n);return o.startsWith("..")||C.isAbsolute(o)?e:n}var de=class{constructor(e,r=null,s,n,o=!1,i=new Map,a=!0){this.rootDir=e;this.enableGitStats=o;this.coverageMap=i;this.parallelParsing=a;this.previousGraph=r,this.resolver=s||new L(e),this.lockFile=jr(e),n&&(this.progressCallback=n)}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(s=>C.isAbsolute(s)?s:C.resolve(this.rootDir,s));await this.initPool(),this.enableGitStats&&(this.gitStatsMap=_r(this.rootDir));try{for(let s of r)this.enqueue(s);return await this.drain(),await this.processTestFiles(za(r,this.rootDir)),await this.processDocFiles(),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
17
+ `;return p+d+g+i+`
18
+ `+l}};function Qo(r){let e=r.split(`
19
+ `),t=-1;for(let n=0;n<e.length;n++){let o=e[n].trimStart();(o.startsWith("import ")||o.startsWith("from "))&&(t=n)}if(t<0)return 0;let s=0;for(let n=0;n<=t;n++)s+=e[n].length+1;return s}import Lr from"path";import _r from"typescript";var qo=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,We=class{name="vitest";canHandle(e){return N.has(Lr.extname(e).toLowerCase())}apply(e,t,s){let n=t.replace(qo,""),o=_r.createSourceFile(Lr.basename(e),n,_r.ScriptTarget.Latest,!0),i=H(o);if(i.length===0)return n;let a=Q(i[0],"tags",o),c=[...s].sort();if(a!==null&&JSON.stringify([...a].sort())===JSON.stringify(c))return n;let p=i.flatMap(l=>{let g=s.length===0?X(l,"tags",o):q(l,"tags",Z(c),o);return g?[g]:[]});return p.length>0?Y(n,p):n}};var Or={vitest:()=>new We,playwright:()=>new Oe,cypress:()=>new De,jest:()=>new _e},Xo={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function Yo(r){let e=ze.createSourceFile("detect.ts",r,ze.ScriptTarget.Latest,!0);for(let t of e.statements){if(!ze.isImportDeclaration(t)||!ze.isStringLiteral(t.moduleSpecifier))continue;let s=Xo[t.moduleSpecifier.text];if(s)return s}return null}var It=class{constructor(e,t,s){this.rootDir=e;this.defaultFramework=t;this.frameworkOverrides=s}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return N.has(Mt.extname(e).toLowerCase())}apply(e,t,s){let n=Yo(t)??this.matchOverride(e)??this.defaultFramework;return(Or[n]??Or.vitest)().apply(e,t,s)}matchOverride(e){let t=Mt.relative(this.rootDir,e).split(Mt.sep).join("/");for(let[s,n]of this.frameworkOverrides)if(Rr(s,t))return n;return null}};function jr(r="vitest",e={},t=process.cwd()){return[new Ge,new je,new Le,new It(t,r,Object.entries(e))]}function Wr(r,e){return e.find(t=>t.canHandle(r))??null}var ei=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,ti=new Set(["import"]),ri=new Set(["common","fixture","fixtures","helper","helpers","index","main","mock","mocks","setup","shared","spec","test","tests","types","util","utils"]);async function si(r,e,t,s){let n;try{n=await zr.readFile(r,"utf8")}catch(a){return{path:r,status:"error",error:String(a)}}let o=Wr(r,s);if(!o)return{path:r,status:"unchanged"};let i=o.apply(r,n,e);return i===n?{path:r,status:"unchanged"}:(t||await zr.writeFile(r,i,"utf8"),{path:r,status:"updated"})}async function Rt(r,e,t){let s=se(e),n=s.tagApplier?.framework??"vitest",o=s.tagApplier?.frameworkOverrides??{},i=jr(n,o,e),a={updated:0,unchanged:0,errors:0,files:[]};for(let c of r.nodes.values()){if(c.category!=="test")continue;let p=new Set,l=[];for(let h of c.tags)ti.has(h.kind)&&ei.test(h.name)&&(ri.has(h.name.toLowerCase())||p.has(h.name)||(p.add(h.name),l.push(h.name)));l.sort();let g=Zo.resolve(e,c.path),d=await si(g,l,t.dryRun,i);d.path=c.path,a.files.push(d),d.status==="updated"?a.updated++:d.status==="unchanged"?a.unchanged++:a.errors++}return a}var $e=class{isTestNode(e){return e.category==="test"||e.tags.some(t=>t.name==="test")}};import ve from"fs";import F from"path";import nc from"piscina";import{execFileSync as Dt}from"child_process";var Be=class{getChangedFiles(){try{let t=[["diff","--name-only"],["diff","--cached","--name-only"],["ls-files","--others","--exclude-standard"]].flatMap(s=>{try{return Dt("git",s,{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
20
+ `).map(o=>o.trim()).filter(o=>o!=="")}catch{return[]}});return Array.from(new Set(t))}catch(e){return console.error("Error getting git diff:",e),[]}}},$r="%x00%H%x09%ae%x09%at",Br=256*1024*1024;function Ur(r,e){let t="",s=0;for(let n of r.split(`
21
+ `)){if(n.startsWith("\0")){let[,c,p]=n.slice(1).split(" ");t=c??"",s=p?Number(p)*1e3:0;continue}if(n==="")continue;let o=n.split(" "),i=o[0];if(!i)continue;let a=i.startsWith("R")||i.startsWith("C")?o[2]:o[1];a&&e(a,t,s)}}function Kr(r){let e=new Map;try{let t=Dt("git",["-C",r,"log","--since=90 days ago","--name-status","-M",`--format=${$r}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:Br});Ur(t,(s,n,o)=>{let i=e.get(s);if(i){i.commitCount90d+=1;return}e.set(s,{commitCount90d:1,lastAuthor:n||void 0,lastCommitAt:o||void 0})})}catch{return e}try{let t=Dt("git",["-C",r,"log","--name-status","-M",`--format=${$r}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:Br});Ur(t,(s,n,o)=>{e.has(s)||e.set(s,{commitCount90d:0,lastAuthor:void 0,lastCommitAt:o||void 0})})}catch{}return e}import Ue from"fs";import ni from"path";import{load as Jr}from"js-yaml";function Vr(r){let e=r.lastIndexOf("@");return e>0?r.substring(0,e):r}function oi(r){return r.replace(/:$/,"").split(",").map(e=>{let t=e.trim();return t.startsWith('"')&&(t=t.slice(1)),t.endsWith('"')&&(t=t.slice(0,-1)),Vr(t)}).filter(Boolean)}function ii(r,e){let t=r.startsWith("/")?r.slice(1):r,s=t.lastIndexOf("@");return s>0?{name:t.substring(0,s),version:e||t.substring(s+1)}:{name:t,version:e}}function ai(r){try{let e=Jr(r),t={dependencies:{}};for(let[s,n]of Object.entries(e))if(!(s==="__metadata"||!n?.version))for(let o of s.split(", ")){let i=Vr(o);i&&(t.dependencies[i]={version:n.version,...n.dependencies!==void 0&&{dependencies:n.dependencies}})}return t}catch{return null}}function ci(r){let e={dependencies:{}};for(let t of r.split(/\n\n+/)){let s=t.split(`
22
+ `).filter(c=>c.trim().length>0&&!c.trim().startsWith("#"));if(s.length<2)continue;let n=s[0];if(!n||n.startsWith(" "))continue;let o=oi(n);if(o.length===0)continue;let a=s.find(c=>c.trim().startsWith('version "'))?.match(/version "(.*?)"/)?.[1]??"";for(let c of o)e.dependencies[c]={version:a}}return e}function pi(r){let e=Ue.readFileSync(r,"utf-8"),t=JSON.parse(e),s={dependencies:{}};if(t.packages)for(let[n,o]of Object.entries(t.packages)){if(!n.startsWith("node_modules/"))continue;let i=n.replace("node_modules/","");i.includes("node_modules/")||(s.dependencies[i]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}else if(t.dependencies)for(let[n,o]of Object.entries(t.dependencies))s.dependencies[n]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}};return s}function li(r){let e=Ue.readFileSync(r,"utf-8");if(e.includes("__metadata:")){let t=ai(e);if(t!==null)return t}return ci(e)}function fi(r){let e=Ue.readFileSync(r,"utf-8"),t={dependencies:{}};try{let s=Jr(e);if(s.packages)for(let[n,o]of Object.entries(s.packages)){let{name:i,version:a}=ii(n,o.version);i&&(t.dependencies[i]={version:a,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}if(s.dependencies)for(let[n,o]of Object.entries(s.dependencies)){if(t.dependencies[n])continue;let i=typeof o=="string"?o:o.version;t.dependencies[n]={version:i||""}}}catch{}return t}function Hr(r){let e=[["package-lock.json",pi],["yarn.lock",li],["pnpm-lock.yaml",fi]];for(let[t,s]of e){let n=ni.join(r,t);if(Ue.existsSync(n))return s(n)}return null}import Qr from"path";function R(r){switch(Qr.extname(r).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":case".cpp":case".cc":case".cxx":case".c":return"unknown";case".feature":return"gherkin";case".md":case".mdx":return"markdown";default:return"unknown"}}function P(r){let e=Qr.extname(r).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}import ui from"coffeescript";function D(r){return r.startsWith("'")||r.startsWith('"')?r.slice(1,-1):r}function Xr(r){if(r){if(typeof r.originalValue=="string")return r.originalValue;if(typeof r.value=="string")return D(r.value)}}function O(r){if(r){if(typeof r.value=="string")return r.value;if(typeof r.base?.value=="string")return r.base.value}}function mi(r){let e=new Set,t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=t.exec(r);for(;s!==null;)s[1]&&e.add(s[1]),s=t.exec(r);return e}function gi(r,e){let t=r.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||e.has("test")?"test":"logic"}function di(r,e){let t=Xr(e.source);return t?{fromPath:r,toPath:"",rawSpecifier:t,isStyle:P(t),type:"static"}:null}function hi(r,e){let t=e.variable?.base?.value==="require",s=Xr(e.args?.[0]?.base);return!t||!s?null:{fromPath:r,toPath:"",rawSpecifier:s,isStyle:P(s),type:"require"}}function qr(r,e){if(e)return[{name:e}];let t=r.value;if(t?.constructor?.name==="Class"){let n=O(t.variable);return n?[{name:n}]:[]}if(t?.base?.constructor?.name==="Obj"&&Array.isArray(t.base.properties))return t.base.properties.map(n=>O(n.variable)??O(n)).filter(n=>!!n).map(n=>({name:n}));let s=O(t);return s?[{name:s}]:[]}function yi(r){if(Array.isArray(r.specifiers))return r.specifiers.map(t=>t.identifier??t.original?.value).filter(t=>!!t).map(t=>({name:t}));let e=O(r.variable)??O(r.variable?.base);return e?[{name:e}]:[]}function xi(r,e,t,s){let n=e.constructor?.name;if(n==="ImportDeclaration"){let o=di(r,e);o&&t.push(o)}else if(n==="Call"){let o=hi(r,e);o&&t.push(o)}else if(n==="Assign"){let o=O(e.variable?.base),i=e.variable?.properties?.[0]?.name?.value;o==="module"&&i==="exports"?s.push(...qr(e,void 0)):o==="exports"&&typeof i=="string"&&s.push(...qr(e,i))}else n==="ExportNamedDeclaration"&&e.clause?s.push(...yi(e.clause)):n==="ExportDefaultDeclaration"&&s.push({name:"default"})}function Gt(r,e,t,s){if(!(!e||typeof e!="object")){xi(r,e,t,s);for(let n in e){if(n==="locationData")continue;let o=e[n];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let i of o)Gt(r,i,t,s);else Gt(r,o,t,s)}}}function Yr(r,e){let t=mi(e),s=gi(r,t),n=[],o=[];try{Gt(r,ui.nodes(e),n,o)}catch{}let i=new Set,a=o.filter(c=>i.has(c.name)?!1:(i.add(c.name),!0));return{imports:n,exports:a,tags:Array.from(t).map(c=>({name:c,kind:"comment-marker"})),category:s}}import{AstBuilder as Si,GherkinClassicTokenMatcher as bi,Parser as vi}from"@cucumber/gherkin";import{IdGenerator as Ci}from"@cucumber/messages";var ki=Ci.uuid();function Lt(r,e){let t=new Set;try{let s=new Si(ki),n=new bi,i=new vi(s,n).parse(e);i.feature&&(i.feature.tags.forEach(a=>{t.add(a.name.startsWith("@")?a.name.slice(1):a.name)}),i.feature.children.forEach(a=>{a.scenario&&(a.scenario.tags.forEach(c=>{t.add(c.name.startsWith("@")?c.name.slice(1):c.name)}),a.scenario.examples.forEach(c=>{c.tags.forEach(p=>{t.add(p.name.startsWith("@")?p.name.slice(1):p.name)})})),a.rule&&a.rule.children.forEach(c=>{c.scenario&&c.scenario.tags.forEach(p=>{t.add(p.name.startsWith("@")?p.name.slice(1):p.name)})})}))}catch(s){console.warn(`[GherkinParser] Failed to parse ${r}:`,s)}return{imports:[],exports:[],tags:Array.from(t).map(s=>({name:s,kind:"comment-marker"})),category:"test"}}V("gherkin",Lt);import Fi from"path";import{parser as Ti}from"@lezer/go";function j(r){let e=[],t=r.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}function me(r,e){let t=1;for(let s=0;s<e&&s<r.length;s++)r[s]===`
23
+ `&&t++;return t}function wi(r,e){let t=1;function s(n){switch(n.type.name){case"IfStatement":case"ForStatement":t++;break;case"Case":{n.firstChild?.type.name==="case"&&t++;break}case"LogicOp":{let i=e.slice(n.from,n.to);(i==="&&"||i==="||")&&t++;break}}let o=n.firstChild;for(;o;)s(o),o=o.nextSibling}return s(r),t}function Ei(r,e){let t=0;function s(n,o,i){let a=n.type.name;if(a==="IfStatement"){t+=i?1:1+o;let l=j(n),g=i?o:o+1,d=l[1];d&&d.type.name!=="Block"&&s(d,g,!1);let h=l.find(S=>S.type.name==="Block");h&&s(h,g,!1);let v=l.findIndex(S=>S.type.name==="else");if(v>=0){let S=l[v+1];S?.type.name==="IfStatement"?s(S,o,!0):S&&(t+=1,s(S,o+1,!1))}return}if(a==="ForStatement"||a==="SwitchStatement"||a==="SelectStatement"){t+=1+o;let l=n.firstChild;for(;l;)s(l,o+1,!1),l=l.nextSibling;return}if(a==="LogicOp"){let l=e.slice(n.from,n.to);(l==="&&"||l==="||")&&(t+=1)}if(o>0&&a==="FunctionLiteral"){t+=1+o;let l=n.firstChild;for(;l;)s(l,o+1,!1),l=l.nextSibling;return}let p=n.firstChild;for(;p;)s(p,o,!1),p=p.nextSibling}return s(r,0,!1),t}function Ke(r,e){return{complexity:wi(r,e),cognitiveComplexity:Ei(r,e)}}function _t(r,e){let s=r.getChild("Parameters")?.getChild("Parameter"),n=s?.getChild("TypeName")??s?.getChild("PointerType")?.getChild("TypeName");return n?e.slice(n.from,n.to):void 0}function Zr(r,e){let t=[],s=r.cursor();do if(s.name==="FunctionDecl"){let n=s.node.getChild("DefName");if(n){let o=e.slice(n.from,n.to),{complexity:i,cognitiveComplexity:a}=Ke(s.node,e);t.push({name:o,line:me(e,s.from),complexity:i,cognitiveComplexity:a})}}else if(s.name==="MethodDecl"){let n=s.node.getChild("FieldName");if(n){let o=e.slice(n.from,n.to),i=_t(s.node,e),a=i?`${i}.${o}`:o,{complexity:c,cognitiveComplexity:p}=Ke(s.node,e);t.push({name:a,line:me(e,s.from),complexity:c,cognitiveComplexity:p})}}while(s.next());return t}var Pi=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,Ai=/^\/\/go:build\s+(.+)$/,Ni=/^\/\/\s*\+build\s+(.+)$/;function ts(r,e){let t=[],s=new Map,n=new Set,o=new Set,i=new Map,a=Ti.parse(e),c=a.cursor();do switch(c.name){case"LineComment":{let k=e.slice(c.from,c.to),A=k.match(Pi);A?.[1]&&n.add(A[1]);let $=k.match(Ai);$&&es($[1],o);let B=k.match(Ni);B&&es(B[1],o);break}case"ImportSpec":{let k=c.node.getChild("String");if(k){let $=e.slice(k.from,k.to).slice(1,-1);t.push({fromPath:r,toPath:"",rawSpecifier:$,isExternal:!0,isStyle:!1,type:"static"});let B=c.node.getChild("DefName"),we=B?e.slice(B.from,B.to):$.split("/").pop();we&&we!=="_"&&we!=="."&&i.set(we,$)}break}case"FunctionDecl":case"MethodDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let k=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(k){let A=e.slice(k.from,k.to);A!=="_"&&/^[A-Z]/.test(A)&&!s.has(A)&&s.set(A,{name:A})}break}}while(c.next());let p=t.some(k=>k.rawSpecifier==="testing"),l=Fi.basename(r).endsWith("_test.go")||n.has("test")||p?"test":"logic",g=new Set([...n,...o]),{complexity:d,cognitiveComplexity:h}=Ke(a.topNode,e),v=Zr(a,e),S=l==="test"?[]:Mi(a,e,i);return{imports:t,exports:Array.from(s.values()),tags:Array.from(g).map(k=>({name:k,kind:"comment-marker"})),category:l,rawCallEdges:S,complexity:d,cognitiveComplexity:h,...v.length>0?{functions:v}:{}}}function Mi(r,e,t){let s=[];function n(i,a){if(i.type.name==="CallExpr"){let p=i.firstChild;if(p?.type.name==="SelectorExpr"){let l=p.firstChild,g=p.getChild("FieldName");if(l?.type.name==="VariableName"&&g){let d=e.slice(l.from,l.to),h=t.get(d);if(h){let v=e.slice(g.from,g.to);s.push({from:a,to:v,toSpecifier:h})}}}}let c=i.firstChild;for(;c;)n(c,a),c=c.nextSibling}let o=r.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)&&n(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),p=_t(o.node,e);n(a,p?`${p}.${c}`:c)}}while(o.next());return s}function es(r,e){for(let t of r.split(/[\s,&|!()]+/)){let s=t.trim();s&&s!=="ignore"&&e.add(s)}}import Ii from"livescript";function Ri(r){let e=new Set,t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=t.exec(r);for(;s!==null;)s[1]&&e.add(s[1]),s=t.exec(r);return e}function Di(r,e){let t=r.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||e.has("test")?"test":"logic"}function W(r){if(r){if(typeof r.value=="string")return r.value;if(typeof r.base?.value=="string")return r.base.value}}function Gi(r){if(!r)return[];if(r.constructor?.name==="Class"){let t=W(r.title);return t?[{name:t}]:[]}if(r.constructor?.name==="Obj"&&Array.isArray(r.items))return r.items.map(t=>W(t.key)??W(t.val)).filter(t=>!!t).map(t=>({name:t}));let e=W(r);return e?[{name:e}]:[]}function Li(r){let e=r.constructor?.name||r.type;if(e==="Assign"&&r.left?.constructor?.name==="Chain"){let t=r.left,s=W(t.head),o=t.tails?.[0]?.key?.name;if(s==="module"&&o==="exports")return Gi(r.right);if(s==="exports"&&typeof o=="string")return[{name:o}];if(t.head?.verb==="out"&&typeof o=="string")return[{name:o}]}if(e==="Import"&&r.left?.verb==="out"){let t=r.right;if(t?.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(s=>W(s.val)??W(s.key)).filter(s=>!!s).map(s=>({name:s}))}return[]}var _i=new Set(["first_line","first_column","last_line","last_column","line","column"]);function Oi(r,e){let t=r.constructor?.name||r.type;if(t==="Import"){let s=r.right?.value;if(typeof s=="string"){let n=D(s);return{fromPath:e,toPath:"",rawSpecifier:n,isStyle:P(n),type:"static"}}}if(t==="Chain"&&r.head?.value==="require"){let s=r.tails?.[0];if(s?.constructor?.name==="Call"||s?.type==="Call"){let n=s.args?.[0]?.value;if(typeof n=="string"){let o=D(n);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:P(o),type:"require"}}}}return null}function Ot(r,e,t){if(!r||typeof r!="object")return[];let s=[],n=Oi(r,e);n&&s.push(n),t.push(...Li(r));for(let o in r){if(_i.has(o))continue;let i=r[o];if(!(!i||typeof i!="object"))if(Array.isArray(i))for(let a of i)s.push(...Ot(a,e,t));else s.push(...Ot(i,e,t))}return s}function rs(r,e){let t=Ri(e),s=Di(r,t),n=[],o=[];try{n=Ot(Ii.ast(e),r,o)}catch{}let i=new Set,a=o.filter(c=>i.has(c.name)?!1:(i.add(c.name),!0));return{imports:n,exports:a,tags:Array.from(t).map(c=>({name:c,kind:"comment-marker"})),category:s}}import ji from"luaparse";function Wi(r){let e=new Set,t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=t.exec(r);for(;s!==null;)s[1]&&e.add(s[1]),s=t.exec(r);return e}function zi(r,e){let t=r.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||e.has("test")?"test":"logic"}function $i(r,e){let t=[];function s(n){if(!(!n||typeof n!="object")){if((n.type==="CallExpression"||n.type==="StringCallExpression")&&n.base?.type==="Identifier"&&n.base?.name==="require"){let o;if(n.type==="CallExpression"){let i=n.arguments?.[0];i?.type==="StringLiteral"&&(o=D(i.raw))}else if(n.type==="StringCallExpression"){let i=n.argument;i?.type==="StringLiteral"&&(o=D(i.raw))}o&&t.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:P(o),type:"require"})}for(let o in n){if(o==="loc")continue;let i=n[o];if(i&&typeof i=="object")if(Array.isArray(i))for(let a of i)s(a);else s(i)}}}return s(r),t}function Bi(r){let e=new Set;for(let t of r)t.type==="LocalStatement"&&t.variables.forEach((s,n)=>{t.init[n]?.type==="TableConstructorExpression"&&e.add(s.name)});return e}function Ui(r){let e=r[r.length-1];if(e?.type!=="ReturnStatement")return[];let t=e.arguments[0];if(t?.type!=="TableConstructorExpression")return[];let s=[];for(let n of t.fields)n.type==="TableKeyString"&&s.push({name:n.key.name});return s}function Ki(r){let e=r.body,t=Bi(e),s=Ui(e);for(let o of e)if(o.type==="FunctionDeclaration")o.identifier?.type==="MemberExpression"?o.identifier.base.type==="Identifier"&&t.has(o.identifier.base.name)&&s.push({name:o.identifier.identifier.name}):o.identifier?.type==="Identifier"&&!o.isLocal&&s.push({name:o.identifier.name});else if(o.type==="AssignmentStatement")for(let i of o.variables)i.type==="MemberExpression"&&i.base.type==="Identifier"&&t.has(i.base.name)&&s.push({name:i.identifier.name});let n=new Set;return s.filter(o=>n.has(o.name)?!1:(n.add(o.name),!0))}function ss(r,e){let t=Wi(e),s=zi(r,t),n=[],o=[];try{let i=ji.parse(e);n=$i(i,r),o=Ki(i)}catch{}return{imports:n,exports:o,tags:Array.from(t).map(i=>({name:i,kind:"comment-marker"})),category:s}}var Ji=["http://","https://","mailto:","//"],Vi="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",Hi=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${Vi})\\b`,"g"),ns;async function Qi(){return ns??=(async()=>{let{unified:r}=await import("unified"),e=(await import("remark-parse")).default;return r().use(e)})(),ns}function qi(r){let e=r.trim();return e.length===0||e.startsWith("#")||Ji.some(t=>e.startsWith(t))}function Xi(r,e){let t=r.match(Hi);return t?t.map(s=>({fromPath:e,toPath:"",rawSpecifier:s,isStyle:!1,type:"static"})):[]}function os(r,e,t){if(r.type==="link"&&typeof r.url=="string"&&!qi(r.url)&&t.push({fromPath:e,toPath:"",rawSpecifier:r.url,isStyle:!1,type:"static"}),(r.type==="code"||r.type==="inlineCode")&&typeof r.value=="string"&&t.push(...Xi(r.value,e)),Array.isArray(r.children))for(let s of r.children)os(s,e,t)}async function is(r,e){let s=(await Qi()).parse(e),n=[];os(s,r,n);let o=new Set;return{imports:n.filter(a=>o.has(a.rawSpecifier)?!1:(o.add(a.rawSpecifier),!0)),exports:[],tags:[],category:"other"}}import ea from"path";import{parser as ta}from"@lezer/python";function Yi(r){let e=1;function t(s){switch(s.type.name){case"IfStatement":{e+=j(s).filter(o=>o.type.name==="if"||o.type.name==="elif").length;break}case"TryStatement":{e+=j(s).filter(o=>o.type.name==="except").length;break}case"ForStatement":case"WhileStatement":case"ConditionalExpression":e++;break;case"and":case"or":e++;break}let n=s.firstChild;for(;n;)t(n),n=n.nextSibling}return t(r),e}function Zi(r){let e=0;function t(s,n){let o=s.type.name;if(o==="IfStatement"){let c=j(s),p=0,l=0;for(;l<c.length;){let g=c[l];if(g?.type.name==="if"||g?.type.name==="elif"){let d=p>0;e+=d?1:1+n;let h=d?n:n+1,v=c[l+1],S=c[l+2];v&&t(v,h),S&&t(S,h),p++,l+=3}else if(g?.type.name==="else"){e+=1;let d=c[l+1];d&&t(d,n+1),l+=2}else l++}return}if(o==="TryStatement"){let c=j(s),p=0;for(;p<c.length;){let l=c[p];if(l?.type.name==="except"){for(e+=1+n,p++;p<c.length&&c[p]?.type.name!=="Body";)t(c[p],n),p++;p<c.length&&(t(c[p],n),p++)}else l?.type.name==="Body"&&t(l,n),p++}return}if(o==="ForStatement"||o==="WhileStatement"){e+=1+n;let c=s.firstChild;for(;c;)t(c,n+1),c=c.nextSibling;return}if((o==="ConditionalExpression"||o==="and"||o==="or")&&(e+=1),n>0&&(o==="FunctionDefinition"||o==="LambdaExpression")){e+=1+n;let c=s.firstChild;for(;c;)t(c,n+1),c=c.nextSibling;return}let a=s.firstChild;for(;a;)t(a,n),a=a.nextSibling}return t(r,0),e}function jt(r){return{complexity:Yi(r),cognitiveComplexity:Zi(r)}}function as(r,e){let t=[];function s(i,a){let{complexity:c,cognitiveComplexity:p}=jt(i);t.push({name:a,line:me(e,i.from),complexity:c,cognitiveComplexity:p})}function n(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,p=i.getChild("Body");if(p){let l=p.firstChild;for(;l;){if(l.type.name==="FunctionDefinition"){let g=l.getChild("VariableName"),d=g?e.slice(g.from,g.to):void 0;d&&s(l,c?`${c}.${d}`:d),n(l)}else o(l);l=l.nextSibling}}return}if(i.type.name==="FunctionDefinition"){let a=i.getChild("VariableName");a&&s(i,e.slice(a.from,a.to)),n(i);return}n(i)}return o(r.topNode),t}var ra=new Set(["pytest","unittest","nose","hypothesis"]);function cs(r,e){let t=[],s=[],n=new Set,o=ea.basename(r).toLowerCase(),i=ta.parse(e),a=i.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]&&n.add(h[1]);break}case"ImportStatement":{for(let h of sa(a.node,e,r))t.push(h);break}case"FunctionDefinition":case"ClassDefinition":{let h=a.node.parent;if(h?.name==="Script"||h?.name==="DecoratedStatement"&&h.parent?.name==="Script"){let S=a.node.getChild("VariableName");S&&s.push({name:e.slice(S.from,S.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let h=a.node.firstChild;h?.name==="VariableName"&&s.push({name:e.slice(h.from,h.to)})}break}}while(a.next());let c=pa(o,t,n);c==="test"&&n.add("test");let{complexity:p,cognitiveComplexity:l}=jt(i.topNode),g=as(i,e),d=c==="test"?[]:ca(i,e);return{imports:t,exports:s,tags:Array.from(n).map(h=>({name:h,kind:"comment-marker"})),category:c,rawCallEdges:d,complexity:p,cognitiveComplexity:l,...g.length>0?{functions:g}:{}}}function sa(r,e,t){let s=r.firstChild;return s?s.name==="from"?na(r,e,t):oa(r,e,t):[]}function na(r,e,t){let s=r.firstChild;if(!s)return[];let n=s.nextSibling;for(;n&&n.name!=="import";)n=n.nextSibling;if(!n)return[];let o=e.slice(s.to,n.from).trim(),i=ia(n.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[ge(t,o,i,!0)];let p=a===1?"./":"../".repeat(a-1);return c?[ge(t,p+c.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[ge(t,p.slice(0,-1),["*"],!1)]:i.map(l=>ge(t,p+l,[l],!1))}function oa(r,e,t){let s=[],n=r.firstChild?.nextSibling??null;for(;n;){if(n.name==="VariableName"){let o=e.slice(n.from,n.to);for(;n.nextSibling?.name==="."&&n.nextSibling.nextSibling?.name==="VariableName";)n=n.nextSibling.nextSibling,o+=`.${e.slice(n.from,n.to)}`;n.nextSibling?.name==="as"&&(n=n.nextSibling.nextSibling??n.nextSibling),s.push(ge(t,o,["*"],!0))}n=n.nextSibling}return s}function ia(r,e){let t=[],s=r;for(;s;)s.name==="*"?t.push("*"):s.name==="VariableName"&&(t.push(e.slice(s.from,s.to)),s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling)),s=s.nextSibling;return t}function aa(r,e){let t=new Map,s=r.cursor();do{if(s.name!=="ImportStatement")continue;let o=s.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 p=a.slice(c),l=c<=1?"./":"../".repeat(c-1),g=i.nextSibling;for(;g;){if(g.type.name==="VariableName"){let d=e.slice(g.from,g.to),h=d;if(g.nextSibling?.type.name==="as"){let S=g.nextSibling.nextSibling;S?.type.name==="VariableName"&&(h=e.slice(S.from,S.to),g=S)}let v=c===0?a:p?l+p.replace(/\./g,"/"):l+d;t.set(h,v)}g=g.nextSibling}}while(s.next());return t}function ca(r,e){let t=aa(r,e),s=[];function n(a,c){if(a.type.name==="CallExpression"&&a.firstChild?.type.name==="VariableName"){let l=a.firstChild,g=e.slice(l.from,l.to),d=t.get(g);d&&s.push({from:c,to:g,toSpecifier:d})}let p=a.firstChild;for(;p;)n(p,c),p=p.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"),p=c?e.slice(c.from,c.to):void 0,l=a.getChild("Body");if(l){let g=l.firstChild;for(;g;){if(g.type.name==="FunctionDefinition"){let d=g.getChild("VariableName"),h=d?e.slice(d.from,d.to):void 0;h&&n(g,p?`${p}.${h}`:h)}else i(g);g=g.nextSibling}}return}if(a.type.name==="FunctionDefinition"){let c=a.getChild("VariableName");c&&n(a,e.slice(c.from,c.to));return}o(a)}return i(r.topNode),s}function ge(r,e,t,s){return{fromPath:r,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:s,type:"static",symbols:t.length>0?t:void 0}}function pa(r,e,t){return r.startsWith("test_")||r.endsWith("_test.py")?"test":r==="conftest.py"||r==="setup.py"?"config":t.has("test")||e.some(s=>ra.has(s.rawSpecifier))?"test":"logic"}import ls from"path";import u from"typescript";import y from"typescript";function la(r){let e=1;function t(s){switch(s.kind){case y.SyntaxKind.IfStatement:case y.SyntaxKind.ConditionalExpression:case y.SyntaxKind.ForStatement:case y.SyntaxKind.ForInStatement:case y.SyntaxKind.ForOfStatement:case y.SyntaxKind.WhileStatement:case y.SyntaxKind.DoStatement:case y.SyntaxKind.CatchClause:case y.SyntaxKind.CaseClause:e++;break;case y.SyntaxKind.BinaryExpression:{let n=s.operatorToken.kind;(n===y.SyntaxKind.AmpersandAmpersandToken||n===y.SyntaxKind.BarBarToken||n===y.SyntaxKind.QuestionQuestionToken)&&e++;break}}y.forEachChild(s,t)}return t(r),e}function fa(r){let e=0;function t(s,n,o){if(y.isIfStatement(s)){e+=o?1:1+n;let a=o?n:n+1;t(s.expression,a,!1),t(s.thenStatement,a,!1),s.elseStatement&&(y.isIfStatement(s.elseStatement)?t(s.elseStatement,n,!0):(e+=1,t(s.elseStatement,n+1,!1)));return}if(y.isForStatement(s)||y.isForInStatement(s)||y.isForOfStatement(s)||y.isWhileStatement(s)||y.isDoStatement(s)||y.isSwitchStatement(s)){e+=1+n,y.forEachChild(s,a=>t(a,n+1,!1));return}if(y.isCatchClause(s)){e+=1+n,y.forEachChild(s,a=>t(a,n,!1));return}if(y.isConditionalExpression(s)&&(e+=1),y.isBinaryExpression(s)){let a=s.operatorToken.kind;(a===y.SyntaxKind.AmpersandAmpersandToken||a===y.SyntaxKind.BarBarToken||a===y.SyntaxKind.QuestionQuestionToken)&&(e+=1)}if(n>0&&(y.isFunctionDeclaration(s)||y.isFunctionExpression(s)||y.isArrowFunction(s))){e+=1+n,y.forEachChild(s,a=>t(a,n+1,!1));return}y.forEachChild(s,a=>t(a,n,!1))}return t(r,0,!1),e}function Wt(r){return{complexity:la(r),cognitiveComplexity:fa(r)}}import C from"typescript";var zt=new Set(["test","describe","it"]);function ps(r,e){ua(r,e),ga(r,e),da(r,e),ha(r,e)}function ua(r,e){if((C.isFunctionDeclaration(r)||C.isVariableDeclaration(r))&&r.name&&C.isIdentifier(r.name)&&ma(r)){let t;if(C.isFunctionDeclaration(r))t="function";else{let s=r.initializer;t=s&&(C.isArrowFunction(s)||C.isFunctionExpression(s))?"function":"variable"}e.tags.add({name:r.name.text,kind:t})}}function ma(r){if(C.isFunctionDeclaration(r))return C.isSourceFile(r.parent);let e=r.parent?.parent;return!!e&&C.isSourceFile(e.parent)}function ga(r,e){if(!C.isStringLiteral(r))return;let t=r.text.match(/@[\w-]+/g);if(t)for(let s of t)e.tags.add({name:s.substring(1),kind:"comment-marker"})}function da(r,e){if(!C.isSourceFile(r))return;let t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=r.getFullText(),n=t.exec(s);for(;n!==null;)n[1]&&e.tags.add({name:n[1],kind:"comment-marker"}),n=t.exec(s)}function ha(r,e){if(C.isCallExpression(r)&&ya(r.expression))for(let t of r.arguments)C.isObjectLiteralExpression(t)&&xa(t,e)}function ya(r){return C.isIdentifier(r)?zt.has(r.text):!!(C.isPropertyAccessExpression(r)&&(zt.has(r.name.text)||C.isIdentifier(r.expression)&&zt.has(r.expression.text)))}function xa(r,e){for(let t of r.properties){if(!C.isPropertyAssignment(t)||!C.isIdentifier(t.name)||t.name.text!=="tags"&&t.name.text!=="tag")continue;let{initializer:s}=t,n=C.isArrayLiteralExpression(s)?s.elements.filter(C.isStringLiteral):t.name.text==="tag"&&C.isStringLiteral(s)?[s]:[];for(let o of n)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function $t(r,e,t){let s=[],n=new Map,o=new Set,i=u.createSourceFile(r,e,u.ScriptTarget.Latest,!0,t==="typescript"?u.ScriptKind.TSX:u.ScriptKind.JSX),a={filePath:r,imports:s,exports:n,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=S=>{Ca(S,a),u.forEachChild(S,c)};c(i);let p=Ra(r,a);(p==="test"||p==="barrel")&&o.add({name:p,kind:"comment-marker"}),p!=="test"&&Da(a,i);let l=i.statements[0],g=l?us(l):void 0,{complexity:d,cognitiveComplexity:h}=Wt(i),v=Sa(i);return{imports:s,exports:Array.from(n.values()),tags:Array.from(o),category:p,rawCallEdges:a.rawCallEdges??[],complexity:d,cognitiveComplexity:h,...v.length>0?{functions:v}:{},...g!==void 0?{description:g}:{}}}function Sa(r){let e=[],t=(n,o)=>{let{complexity:i,cognitiveComplexity:a}=Wt(o),c=r.getLineAndCharacterOfPosition(o.getStart(r)).line+1;e.push({name:n,line:c,complexity:i,cognitiveComplexity:a})},s=(n,o)=>{if(u.isFunctionDeclaration(n)&&n.name&&n.body?t(n.name.text,n):u.isVariableDeclaration(n)&&u.isIdentifier(n.name)&&n.initializer&&(u.isArrowFunction(n.initializer)||u.isFunctionExpression(n.initializer))?t(n.name.text,n.initializer):o&&u.isMethodDeclaration(n)&&u.isIdentifier(n.name)&&n.body?t(`${o}.${n.name.text}`,n):o&&u.isConstructorDeclaration(n)&&n.body?t(`${o}.constructor`,n):o&&u.isGetAccessorDeclaration(n)&&u.isIdentifier(n.name)&&n.body?t(`${o}.get ${n.name.text}`,n):o&&u.isSetAccessorDeclaration(n)&&u.isIdentifier(n.name)&&n.body&&t(`${o}.set ${n.name.text}`,n),u.isClassDeclaration(n)&&n.name){let i=n.name.text;u.forEachChild(n,a=>s(a,i));return}u.forEachChild(n,i=>s(i,o))};return s(r,void 0),e}function fs(r,e,t,s){let n={name:r},o=us(t);o!==void 0&&(n.doc=o);let i=ba(e);i!==void 0&&(n.flags=i);let a=va(e,s);return a!==void 0&&(n.signature=a),n}function us(r){let e=u.getJSDocCommentsAndTags(r);for(let t of e)if(u.isJSDoc(t)&&t.comment)return u.getTextOfJSDocComment(t.comment)||void 0}function ba(r){let e=new Set(["deprecated","internal","public","alpha","beta"]),t=u.getJSDocTags(r).map(s=>s.tagName.text).filter(s=>e.has(s));return t.length>0?t:void 0}function va(r,e){let t=u.createPrinter({removeComments:!0}),s=n=>t.printNode(u.EmitHint.Unspecified,n,e);if(u.isFunctionDeclaration(r)||u.isMethodDeclaration(r)){let n=r.parameters.map(s).join(", "),o=r.type?s(r.type):"void";return`${r.typeParameters?`<${r.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${n}) => ${o}`}if(u.isVariableDeclaration(r)){if(r.type)return s(r.type);if(r.initializer&&(u.isArrowFunction(r.initializer)||u.isFunctionExpression(r.initializer))){let n=r.initializer,o=n.parameters.map(s).join(", "),i=n.type?s(n.type):"unknown";return`(${o}) => ${i}`}return}if(u.isClassDeclaration(r)&&r.name)return`class ${r.name.text}`;if(u.isInterfaceDeclaration(r))return`interface ${r.name.text}`;if(u.isTypeAliasDeclaration(r))return s(r.type);if(u.isEnumDeclaration(r))return`enum ${r.name.text}`}function Ca(r,e){ka(r,e),wa(r,e),Fa(r,e),Ta(r,e),Ia(r,e),ps(r,e)}function ka(r,e){if(!u.isSourceFile(r))return;let t=r.statements.filter(s=>!u.isEmptyStatement(s));e.totalStatements=t.length,e.exportStatements=t.filter(s=>u.isExportDeclaration(s)||u.isExportAssignment(s)||Bt(s)).length}function wa(r,e){if(u.isJsxElement(r)||u.isJsxSelfClosingElement(r)||u.isJsxFragment(r)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(u.isFunctionDeclaration(r)||u.isMethodDeclaration(r)||u.isArrowFunction(r)||u.isClassDeclaration(r)||u.isVariableStatement(r)||u.isEnumDeclaration(r)){e.hasTypesOnly=!1;return}u.isExportDeclaration(r)&&!Ea(r)&&(e.hasTypesOnly=!1)}function Ea(r){return r.isTypeOnly?!0:!r.exportClause||!u.isNamedExports(r.exportClause)?!1:r.exportClause.elements.every(e=>e.isTypeOnly)}function Fa(r,e){if(!u.isImportDeclaration(r)||!r.moduleSpecifier||!u.isStringLiteral(r.moduleSpecifier))return;let t=[];if(r.importClause&&(r.importClause.name&&t.push("default"),r.importClause.namedBindings))if(u.isNamedImports(r.importClause.namedBindings))for(let n of r.importClause.namedBindings.elements)t.push(n.name.text);else u.isNamespaceImport(r.importClause.namedBindings)&&t.push("*");let s=t.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.moduleSpecifier.text,isStyle:P(r.moduleSpecifier.text),type:s,symbols:t.length>0?t:void 0})}function Ta(r,e){u.isExportDeclaration(r)?Pa(r,e):u.isExportAssignment(r)?e.exports.set("default",{name:"default"}):Bt(r)&&Ma(r,e)}function Pa(r,e){if(r.moduleSpecifier&&u.isStringLiteral(r.moduleSpecifier))Aa(r,r.moduleSpecifier.text,e);else if(r.exportClause&&u.isNamedExports(r.exportClause))for(let t of r.exportClause.elements){let s=t.name.text;e.exports.set(s,{name:s})}}function Aa(r,e,t){let s=Na(r),n={fromPath:t.filePath,toPath:"",rawSpecifier:e,isStyle:P(e),type:"re-export"};s.length>0&&(n.symbols=s),t.imports.push(n)}function Na(r){return r.exportClause?u.isNamedExports(r.exportClause)?r.exportClause.elements.map(e=>e.name.text):[]:["*"]}function Ma(r,e){if((u.isFunctionDeclaration(r)||u.isClassDeclaration(r)||u.isInterfaceDeclaration(r)||u.isTypeAliasDeclaration(r)||u.isEnumDeclaration(r))&&r.name){let s=r.name.text;e.exports.set(s,fs(s,r,r,e.sourceFile));return}if(u.isVariableStatement(r)){for(let s of r.declarationList.declarations)if(u.isIdentifier(s.name)){let n=s.name.text;e.exports.set(n,fs(n,s,r,e.sourceFile))}}}function Ia(r,e){if(!u.isCallExpression(r))return;let t=r.arguments[0];!t||!u.isStringLiteral(t)||(r.expression.kind===u.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.text,isStyle:P(t.text),type:"dynamic"}):u.isIdentifier(r.expression)&&r.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.text,isStyle:P(t.text),type:"require"}))}function Ra(r,e){let t=ls.basename(r).toLowerCase(),s=ls.extname(r).toLowerCase();return re().some(o=>t.includes(o))?"test":Yt(t)?"config":e.imports.some(o=>Xe().some(i=>o.rawSpecifier.includes(i)))?"test":s===".tsx"||s===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>Ze()?"barrel":"logic"}function Bt(r){return u.canHaveModifiers(r)&&u.getModifiers(r)?.some(e=>e.kind===u.SyntaxKind.ExportKeyword)===!0}function Da(r,e){let t=r.rawCallEdges??[];r.rawCallEdges=t;let s=new Map;for(let n of e.statements){if(!u.isImportDeclaration(n)||!u.isStringLiteral(n.moduleSpecifier))continue;let o=n.moduleSpecifier.text,i=n.importClause;if(i&&(i.name&&s.set(i.name.text,o),i.namedBindings&&u.isNamedImports(i.namedBindings)))for(let a of i.namedBindings.elements)s.set(a.name.text,o)}if(s.size!==0)for(let n of e.statements){let o=La(n);if(o){let i=_a(n);i&&Je(i,o,s,t);continue}u.isClassDeclaration(n)&&n.name&&Ga(n,s,t)}}function Ga(r,e,t){let s=r.name.text;for(let n of r.members)u.isMethodDeclaration(n)&&n.body&&u.isIdentifier(n.name)?Je(n.body,`${s}.${n.name.text}`,e,t):u.isConstructorDeclaration(n)&&n.body&&Je(n.body,`${s}.constructor`,e,t)}function La(r){if(Bt(r)){if(u.isFunctionDeclaration(r)&&r.name)return r.name.text;if(u.isVariableStatement(r)){for(let e of r.declarationList.declarations)if(u.isIdentifier(e.name)&&e.initializer&&(u.isArrowFunction(e.initializer)||u.isFunctionExpression(e.initializer)))return e.name.text}}}function _a(r){if(u.isFunctionDeclaration(r))return r.body;if(u.isVariableStatement(r)){for(let e of r.declarationList.declarations)if(e.initializer&&(u.isArrowFunction(e.initializer)||u.isFunctionExpression(e.initializer)))return e.initializer}}function Je(r,e,t,s){if(u.isCallExpression(r)&&u.isIdentifier(r.expression)){let n=r.expression.text,o=t.get(n);o&&!s.some(i=>i.from===e&&i.to===n&&i.toSpecifier===o)&&s.push({from:e,to:n,toSpecifier:o})}u.forEachChild(r,n=>Je(n,e,t,s))}function Ve(r,e){if(e.length===0)return"ui";let t=!1;return r.walk(s=>{if(s.type==="rule")return t=!0,!1}),t?"ui":"barrel"}import gs from"postcss";import*as Oa from"postcss-less";var ja=Oa,ds=new Set(["reference","inline"]);function ms(r){return r.startsWith("~")||r.startsWith("http://")||r.startsWith("https://")||r.startsWith("//")||r.startsWith("data:")}function Wa(r){let e=r.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function za(r,e){let t=r.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(t){let o=t[1]?.trim()??"",i=t[2]??"";if(!i)return null;let a=ds.has(o)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a,...ms(i)?{isExternal:!0}:{}}}let s=r.match(/^url\(['"]?([^'")]+)['"]?\)/),n=s?s[1]?.trim()??"":r.match(/^['"]([^'"]+)['"]/)?.[1]??"";return n?{fromPath:e,toPath:"",rawSpecifier:n,isStyle:!0,type:"static",...ms(n)?{isExternal:!0}:{}}:null}function $a(r,e){let t=[],s=/url\(['"]?([^'")]+)['"]?\)/g,n=s.exec(r);for(;n!==null;){let o=n[1]?.trim()??"";Wa(o)&&t.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),n=s.exec(r)}return t}function hs(r,e){let t=[];return r.walk(s=>{if(s.type==="atrule"&&s.name==="import"){let n=za(s.params,e);n&&t.push(n)}s.type==="decl"&&t.push(...$a(s.value,e))}),t}function Ba(r){return r.replace(/(?<!:)\/\/.*/g,"")}function Ua(r,e){let t=[],s=/@import\s+(?:\(([^)]+)\)\s+)?['"]([^'"]+)['"]/g,n=s.exec(r);for(;n!==null;){let o=n[1]?.trim()??"",i=n[2]??"";if(i){let a=ds.has(o)?"side-effect":"static";t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a})}n=s.exec(r)}return t}function ys(r,e){let t=gs.parse(Ba(r));return{imports:hs(t,e),root:t}}function Ka(r){let e=[],t=[];for(let s of r.nodes??[]){if(s.type!=="atrule")continue;let{value:n}=s;if(n===void 0)continue;let o=s.name;o&&(e.push({name:o}),t.push({name:o,kind:"variable"}))}return{exports:e,tags:t}}function xs(r,e){try{let t=ja.parse(r),{exports:s,tags:n}=Ka(t);return{imports:hs(t,e),root:t,exports:s,tags:n}}catch{return{imports:Ua(r,e),root:gs.parse(""),exports:[],tags:[]}}}import{parse as Ja}from"postcss-scss";function Ss(r){return r.startsWith("_")||r.startsWith("-")}function Va(r){return!!(r.startsWith("sass:")||r.startsWith("~")||r.startsWith("http://")||r.startsWith("https://")||r.startsWith("//")||!r.startsWith(".")&&!r.startsWith("/")&&!r.startsWith("_"))}function Ha(r){let e=r.match(/^['"]([^'"]+)['"]/);if(!e?.[1])return{specifier:""};let t=e[1],n=r.match(/\bas\s+(\S+)/)?.[1];return n!==void 0?{specifier:t,alias:n}:{specifier:t}}function Qa(r){let e=[],t=[];for(let s of r.nodes??[]){if(s.type==="decl"&&s.prop.startsWith("$")){let n=s.prop.slice(1);if(!n||Ss(n))continue;e.push({name:n}),t.push({name:n,kind:"variable"});continue}if(s.type==="atrule"&&(s.name==="mixin"||s.name==="function")){let o=s.params.match(/^([\w-]+)/)?.[1];if(!o||Ss(o))continue;let i=s.params.trim();e.push(i.includes("(")?{name:o,signature:i}:{name:o}),t.push({name:o,kind:"function"})}}return{exports:e,tags:t}}function bs(r,e){let t=Ja(r),s=[];t.walk(i=>{if(i.type!=="atrule")return;let{name:a,params:c}=i;if(a!=="import"&&a!=="use"&&a!=="forward")return;let{specifier:p,alias:l}=Ha(c);if(!p)return;let g={fromPath:e,toPath:"",rawSpecifier:p,isStyle:!0,type:a==="forward"?"re-export":"static",...Va(p)?{isExternal:!0}:{}};l&&(g.symbols=[l]),s.push(g)});let{exports:n,tags:o}=Qa(t);return{imports:s,root:t,exports:n,tags:o}}function vs(r,e){let t=[],s=/@require\s+['"]([^'"]+)['"]/g,n=s.exec(r);for(;n!==null;){let i=n[1];i&&t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"require"}),n=s.exec(r)}let o=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(n=o.exec(r);n!==null;){let i=n[1];i&&t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),n=o.exec(r)}return t}function Cs(r,e){if(e.length===0)return"ui";try{let t=qe("stylus");return new t.Parser(r).parse().nodes.some(o=>o.constructor.name!=="Import")?"ui":"barrel"}catch{return r.replace(/^\s*@?(?:require|import)\b.*/gm,"").trim().length>0?"ui":"barrel"}}function de(r,e){let t=R(r);if(t==="stylus"){let o=vs(e,r);return{imports:o,exports:[],tags:[],category:Cs(e,o)}}if(t==="scss"){let{imports:o,root:i,exports:a,tags:c}=bs(e,r);return{imports:o,exports:a,tags:c,category:Ve(i,o)}}if(t==="less"){let{imports:o,root:i,exports:a,tags:c}=xs(e,r);return{imports:o,exports:a,tags:c,category:Ve(i,o)}}let{imports:s,root:n}=ys(e,r);return{imports:s,exports:[],tags:[],category:Ve(n,s)}}for(let[r,e]of[["javascript",(t,s)=>$t(t,s,"javascript")],["typescript",(t,s)=>$t(t,s,"typescript")],["css",de],["scss",de],["less",de],["stylus",de],["coffeescript",Yr],["livescript",rs],["lua",ss],["python",cs],["go",ts],["gherkin",Lt],["markdown",is]])V(r,e);async function ks(r,e){let t=R(r),s=Tr(t);return s?s(r,e):{imports:[],exports:[],tags:[],category:"other"}}import ws from"path";function Fs(r,e){for(let t of r.values()){let s=e.get(t.path);s!==void 0&&(t.coveragePct=s)}}function Ts(r,e){for(let t of r)if(t.isExternal){let s=t.rawSpecifier.startsWith("@")?t.rawSpecifier.split("/").slice(0,2).join("/"):t.rawSpecifier.split("/")[0];s&&!e.some(n=>n.name===s)&&e.push({name:s,kind:"library"})}}function Ps(r){for(let e of r.values())if(e.category==="test")for(let t of e.imports){if(t.isExternal||!t.toPath)continue;let s=r.get(t.toPath);s&&(s.category!=="logic"&&s.category!=="barrel"||(s.testedBy??=[],s.testedBy.includes(e.path)||s.testedBy.push(e.path)))}}function As(r){for(let e of r.values())if(e.type==="markdown")for(let t of e.imports){if(t.isExternal||!t.toPath)continue;let s=r.get(t.toPath);!s||s===e||(s.documentedBy??=[],s.documentedBy.includes(e.path)||s.documentedBy.push(e.path),s.category==="logic"&&(s.lastCommitAt??0)>(e.lastCommitAt??0)&&(e.staleFor??=[],e.staleFor.includes(s.path)||e.staleFor.push(s.path)))}}function Es(r){return Math.round(r*1e4)/1e4}function Ns(r){for(let e of r.values()){let t=[];for(let s of e.imports){if(s.isExternal||!s.toPath)continue;let n=r.get(s.toPath);if(!n||n.exports.length===0)continue;let o;if(s.symbols===void 0){if(s.type==="side-effect")continue;o=1}else s.symbols.includes("*")?o=1:o=s.symbols.length/n.exports.length;s.exportUsageRatio=Es(Math.min(1,o)),t.push(s.exportUsageRatio)}t.length>0&&(e.avgExportUsage=Es(t.reduce((s,n)=>s+n,0)/t.length),e.maxExportUsage=Math.max(...t))}}function Ut(r,e,t){e&&(r.some(s=>s.name===e&&s.kind===t)||r.push({name:e,kind:t}))}function qa(r,e){let t=e.toPath,s=ws.basename(t,ws.extname(t)).replace(/\.(test|spec)$/,"");Ut(r.tags,s,"import")}function Xa(r,e){if(!(!e.symbols||e.symbols.includes("*")))for(let t of e.symbols)Ut(r.tags,t,"import")}function Ya(r,e,t){let s=t.get(e.toPath);if(!(!s||s.category==="test"))for(let n of s.tags)n.kind==="comment-marker"&&Ut(r.tags,n.name,"comment-marker")}function Ms(r){for(let e of r.values())if(e.category==="test")for(let t of e.imports)!t.toPath||t.isExternal||(qa(e,t),Xa(e,t),Ya(e,t,r))}import He from"fs";import G from"path";import Ds from"fs";import ee from"path";var he=class{extensions=[".go"];goModCache=new Map;resolve(e,t,s,n){let{mod:o,replaces:i}=this.readGoMod(s);if(!o)return null;let a=this.applyReplace(t,i,s);if(a!==void 0)return Rs(a);if(t!==o&&!t.startsWith(`${o}/`))return null;let c=t.slice(o.length).replace(/^\//,"");return c?Rs(ee.join(s,c)):null}readGoMod(e){let t=this.goModCache.get(e);if(t!==void 0)return t;let s={mod:null,replaces:new Map};try{let n=Ds.readFileSync(ee.join(e,"go.mod"),"utf-8"),o=Za(n,e);return this.goModCache.set(e,o),o}catch{return this.goModCache.set(e,s),s}}applyReplace(e,t,s){for(let[n,o]of t){if(e===n)return o;if(e.startsWith(`${n}/`)){let i=e.slice(n.length+1);return ee.join(o,i)}}}};function Za(r,e){let t=r.split(`
24
+ `),s=null,n=new Map,o=!1;for(let i of t){let a=i.trim();if(a.startsWith("module ")){s=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){o=!0;continue}if(o&&a===")"){o=!1;continue}if(o&&a.includes("=>")){Is(a,e,n);continue}!o&&/^replace\s+/.test(a)&&a.includes("=>")&&Is(a.replace(/^replace\s+/,""),e,n)}return{mod:s,replaces:n}}function Is(r,e,t){let[s,n]=r.split("=>").map(a=>a.trim());if(!s||!n)return;let o=s.split(/\s+/)[0];if(!n.startsWith(".")&&!n.startsWith("/"))return;let i=ee.isAbsolute(n)?n:ee.resolve(e,n);t.set(o,i)}function Rs(r){let e;try{e=Ds.readdirSync(r,{withFileTypes:!0})}catch{return null}let t=e.filter(s=>s.isFile()&&s.name.endsWith(".go")&&!s.name.endsWith("_test.go")).map(s=>({path:ee.join(r,s.name),isExternal:!1})).sort((s,n)=>s.path.localeCompare(n.path));return t.length>0?t:null}import ec from"fs";import Kt from"path";var ye=class{extensions=[".lua"];resolve(e,t,s,n){let o=t.replace(/\./g,Kt.sep),i=[s,Kt.join(s,"lib")];for(let a of i){if(!ec.existsSync(a))continue;let c=n(Kt.join(a,"_dummy.lua"),o);if(c)return[c]}return null}};import tc from"path";var xe=class{extensions=[".md",".mdx"];resolve(e,t,s,n){let o=n(tc.join(s,"_dummy"),`./${t}`);return o?[o]:null}};import rc from"fs";import Jt from"path";var Se=class{extensions=[".py"];resolve(e,t,s,n){let o=t.replace(/\./g,Jt.sep),i=Jt.join(s,`${o}.py`);if(Gs(i))return[{path:i,isExternal:!1}];let a=Jt.join(s,o,"__init__.py");return Gs(a)?[{path:a,isExternal:!1}]:null}};function Gs(r){try{return rc.statSync(r,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}import Ls from"path";var sc=["~","http://","https://","//","data:","sass:"],be=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,t,s,n){if(sc.some(l=>t.startsWith(l)))return null;let o=n(e,t);if(o)return[o];let i=Ls.dirname(t),a=Ls.basename(t),c=i==="."?`_${a}`:`${i}/_${a}`,p=n(e,c);return p?[p]:null}};var z=class{constructor(e,t={}){this.rootDir=e;this.workspaceMap=t.workspaceMap??new Map,this.tsconfigSearchPaths=t.tsconfigSearchPaths??[e],this.pathAliases=t.pathAliases,this.langResolvers=t.langResolvers??[new Se,new ye,new he,new be,new xe]}rootDir;workspaceMap;tsconfigSearchPaths;pathAliases;langResolvers;resolveAll(e,t){let s=this.resolvePathAlias(t);if(s)return[s];if(t.startsWith(".")||t.startsWith("/")){let i=this.resolveLocalPath(e,t);return i?[i]:[]}let n=(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,t,this.rootDir,n);if(a)return a}let o=this.resolveWorkspaceImport(t);return o?[o]:[{path:t,isExternal:!0}]}resolve(e,t){let s=this.resolvePathAlias(t);if(s)return s;if(t.startsWith(".")||t.startsWith("/"))return this.resolveLocalPath(e,t);let n=(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,t,this.rootDir,n);if(a)return a[0]??null}let o=this.resolveWorkspaceImport(t);return o||{path:t,isExternal:!0}}resolveLocalPath(e,t){let s=G.dirname(e),n=t.startsWith("/")?t:G.resolve(s,t),o=!n.startsWith(this.rootDir),i=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature",".md",".mdx"],a=n.match(/\.(js|mjs|cjs)$/);if(a){let c=n.slice(0,-a[0].length);for(let p of[".ts",".tsx"]){let l=this.tryExtensions(c,p,o);if(l)return l}}for(let c of i){let p=this.tryExtensions(n,c,o);if(p)return p}return o?{path:n,isExternal:!0}:null}tryExtensions(e,t,s){let n=e+t;if(this.isFile(n))return{path:n,isExternal:s};let o=G.join(e,`index${t}`);if(this.isFile(o))return{path:o,isExternal:s};if(t===".py"){let i=G.join(e,"__init__.py");if(this.isFile(i))return{path:i,isExternal:s}}return null}isFile(e){try{return He.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){if(this.pathAliases)for(let t in this.pathAliases){let s=this.matchAliasPattern(t,e),n=this.pathAliases[t];if(s&&n){let o=this.tryAliasSubstitutions(n,s[1]||"");if(o)return o}}for(let t of this.tsconfigSearchPaths){let s=G.join(t,"tsconfig.json");if(He.existsSync(s))try{let o=JSON.parse(He.readFileSync(s,"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]||"",t);if(c)return c}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,t){let s=this.aliasRegexCache.get(e);if(!s){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");s=new RegExp(`^${n}$`),this.aliasRegexCache.set(e,s)}return t.match(s)}tryAliasSubstitutions(e,t,s=this.rootDir){let n=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let o of e){let i=o.replace("*",t),a=G.resolve(s,i);for(let c of n){let p=this.tryExtensions(a,c,!1);if(p)return p}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[t,s]of this.workspaceMap){if(e!==t&&!e.startsWith(`${t}/`))continue;let n=e.slice(t.length),o={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:t};if(!n){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let c=G.join(s,a);try{if(He.statSync(c,{throwIfNoEntry:!1})?.isFile())return{...o,path:c}}catch{}}return{...o,path:s}}let i=this.resolveLocalPath(G.join(s,"_dummy"),n.slice(1));return i?{...o,path:i.path}:null}return null}};var oc=["tests","test","__tests__","specs","spec"],_s=new Set(["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"]),ic=20;function ac(r,e){if(r.length===0)return e;let t=r.map(i=>F.dirname(i).split(F.sep)),s=t[0];for(let i of t.slice(1)){let a=0;for(;a<s.length&&a<i.length&&s[a]===i[a];)a++;s=s.slice(0,a)}let n=s.join(F.sep)||F.sep,o=F.relative(e,n);return o.startsWith("..")||F.isAbsolute(o)?e:n}var Ce=class{constructor(e,t=null,s,n,o=!1,i=new Map,a=!0){this.rootDir=e;this.enableGitStats=o;this.coverageMap=i;this.parallelParsing=a;this.previousGraph=t,this.resolver=s||new z(e),this.lockFile=Hr(e),n&&(this.progressCallback=n)}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 t=e.map(s=>F.isAbsolute(s)?s:F.resolve(this.rootDir,s));await this.initPool(),this.enableGitStats&&(this.gitStatsMap=Kr(this.rootDir));try{for(let s of t)this.enqueue(s);return await this.drain(),await this.processTestFiles(ac(t,this.rootDir)),await this.processDocFiles(),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
24
25
  Done. Total processed: ${this.visited.size} nodes.
25
- `),bs(this.graph.nodes),ys(this.graph.nodes),Ss(this.graph.nodes),xs(this.graph.nodes),this.coverageMap.size>0&&ds(this.graph.nodes,this.coverageMap),new P(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??Wa;if(!(r>0&&!this.hasAtLeastFiles(this.rootDir,r)))try{let s=C.join(u,"parse-worker.js");this.pool=new Oa({filename:s,...e.maxThreads!==void 0?{maxThreads:e.maxThreads}:{}})}catch(s){process.stderr.write(`
26
+ `),Ms(this.graph.nodes),Ps(this.graph.nodes),Ns(this.graph.nodes),As(this.graph.nodes),this.coverageMap.size>0&&Fs(this.graph.nodes,this.coverageMap),new M(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:{},t=e.minFiles??ic;if(!(t>0&&!this.hasAtLeastFiles(this.rootDir,t)))try{let s=F.join(f,"parse-worker.js");this.pool=new nc({filename:s,...e.maxThreads!==void 0?{maxThreads:e.maxThreads}:{}})}catch(s){process.stderr.write(`
26
27
  Warning: failed to start parse worker pool, falling back to synchronous parsing: ${s}
27
- `),this.pool=null}}hasAtLeastFiles(e,r){let s=0,n=[e];for(;n.length>0;){let o=n.pop(),i;try{i=ge.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let a of i)if(a.isDirectory())Fs.has(a.name)||n.push(C.join(o,a.name));else if(a.isFile()&&(s++,s>=r))return!0}return s>=r}async processTestFiles(e){let r=q(),s=o=>r.some(i=>o.name.includes(i));this.walkProject(e,s);let n=e;for(;n!==this.rootDir;){let o=C.dirname(n);if(o===n)break;for(let i of ja){let a=C.join(o,i);try{ge.statSync(a).isDirectory()&&this.walkProject(a,s)}catch{}}n=o}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 s;try{s=ge.readdirSync(e,{withFileTypes:!0})}catch{return}for(let n of s){let o=C.join(e,n.name);n.isDirectory()?Fs.has(n.name)||this.walkProject(o,r):n.isFile()&&r(n)&&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=ge.statSync(e,{throwIfNoEntry:!1});if(!r?.isFile())return;let s=C.relative(this.rootDir,e),n=await this.getNode(e,s,r);n.imports=await this.resolveImports(e,n.imports),hs(n.imports,n.tags),this.graph.nodes.set(n.path,n)}async getNode(e,r,s){let n=this.previousGraph?.nodes.get(r);if(n&&n.mtime===s.mtimeMs&&n.size===s.size)return{...n};let o=await this.tryParse(e,r);if(!o)return this.makeStubNode(e,r,s);let i=this.resolveCallEdges(e,o.rawCallEdges),a=this.buildNode(e,r,s,o,i);return this.attachGitStats(a,r),a}async tryParse(e,r){let s=ge.readFileSync(e,"utf-8");try{return await this.parseContent(e,s)}catch(n){return process.stderr.write(`
28
- Warning: failed to parse ${r}: ${n}
29
- `),null}}parseContent(e,r){return this.pool?this.pool.run({filePath:e,content:r}):fs(e,r)}makeStubNode(e,r,s){return{path:r,type:M(e),category:"other",imports:[],exports:[],tags:[],mtime:s.mtimeMs,size:s.size}}resolveCallEdges(e,r){let s=[];for(let n of r??[])try{let o=this.resolver.resolve(e,n.toSpecifier);o&&!o.isExternal&&s.push({from:n.from,to:n.to,toFile:C.relative(this.rootDir,o.path)})}catch{}return s}buildNode(e,r,s,n,o){let{imports:i,exports:a,tags:p,category:c,description:m,complexity:g,cognitiveComplexity:d,functions:S}=n;return{path:r,type:M(e),category:c,imports:i,exports:a,tags:p,mtime:s.mtimeMs,size:s.size,...m!==void 0?{description:m}:{},...o.length>0?{callEdges:o}:{},...g!==void 0?{complexity:g}:{},...d!==void 0?{cognitiveComplexity:d}:{},...S!==void 0?{functions:S}:{}}}attachGitStats(e,r){let s=this.gitStatsMap?.get(r);s&&(e.commitCount90d=s.commitCount90d,s.lastAuthor!==void 0&&(e.lastAuthor=s.lastAuthor),s.lastCommitAt!==void 0&&(e.lastCommitAt=s.lastCommitAt))}async resolveImports(e,r){let s=[];for(let n of r){let o=this.resolver.resolveAll(e,n.rawSpecifier);if(o.length!==0)for(let i of o){let a={...n,toPath:i.isExternal?i.path:C.relative(this.rootDir,i.path),isExternal:i.isExternal};i.isWorkspace&&(a.isWorkspace=!0,a.workspacePackage=i.workspacePackage),i.isExternal?this.attachLockfileVersion(a):this.enqueue(i.path),s.push(a)}}return s}attachLockfileVersion(e){if(!this.lockFile)return;let r=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],s=r?this.lockFile.dependencies[r]:void 0;s&&(e.version=s.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};function Ts(t,e){return{identifier:e?.identifier??new De,featureMap:e?.featureDetection===!1?new Map:G(t.nodes,e?.featureDetection??void 0)}}function Ps(t,e,r,s,n){for(let o of e){let i=t.nodes.get(o);if(!i)continue;let a=new D(o,["*",...i.exports.map(p=>p.name)]);t.traverse(o,(p,c,m)=>{if(!m)return!0;if(!a.updateAffectedSymbols(p,m))return!1;if(c>0){let g=r.get(p.path);if(g)return s(g),!1}return n(p),!0},{direction:"incoming"})}}function Ot(t,e,r){let{identifier:s,featureMap:n}=Ts(t,r),o=new Set;for(let i of e){let a=n.get(i);a&&o.add(a.tag)}return Ps(t,e,n,i=>o.add(i.tag),i=>{if(s.isTestNode(i))for(let a of i.tags)o.add(a.name)}),Array.from(o)}function jt(t,e,r){let{identifier:s,featureMap:n}=Ts(t,r),o=new Set;return Ps(t,e,n,()=>{},i=>{s.isTestNode(i)&&o.add(i.path)}),Array.from(o)}import $a from"fs";import he from"path";async function As(t,e,r=null,s={}){let n=s.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},o=he.resolve(t);return await new de(o,r,s.pathAliases?new L(o,{pathAliases:s.pathAliases}):void 0,n,s.gitStats??!1,s.coverageMap??new Map,s.parallelParsing??!0).build(e)}async function Ms(t,e={}){let r=he.resolve(t),s=ne(r),n=e.packages?s.packages.filter(a=>e.packages?.includes(a.name)||e.packages?.includes(a.relativeRoot)):s.packages,o=new Map(s.packages.map(a=>[a.name,a.root])),i=new oe(r,s.type);for(let a of n){let p=e.silent?void 0:g=>{process.stderr.write(`[${a.name}] Processed ${g} files...\r`)},m=await new de(r,null,new L(r,{workspaceMap:o,tsconfigSearchPaths:[a.root,r],pathAliases:e.pathAliases}),p,e.gitStats??!1,new Map,e.parallelParsing??!0).build(a.entryPoints);i.addPackage(a,m)}return i}function Is(t,e={}){let r=[],s=new Set([...e.ignoreDirs??Ve,...e.additionalIgnoreDirs??[]]),n=new Set([...e.extensions??qe,...e.additionalExtensions??[]]);function o(i){try{let a=$a.readdirSync(i,{withFileTypes:!0});for(let p of a){let c=he.join(i,p.name);p.isDirectory()?s.has(p.name)||o(c):p.isFile()&&n.has(he.extname(p.name).toLowerCase())&&r.push(he.relative(t,c))}}catch{}}return o(t),r}var Ns=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;var ze=class{graphs=new Map;configs=new Map;workspaceGraphs=new Map;changeImpactCaches=new Map;dirtyRoots=new Set;watchers=new Map;lastAnalyze=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,s=new Map){let n=this.configs.get(e),o=await As(e,r,this.graphs.get(e)??null,{...O(n),coverageMap:s});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 s=this.workspaceGraphs.get(e);if(s)return s;let n=await Ms(e,r);return this.workspaceGraphs.set(e,n),n}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 s=this.require(e),n=rt(s);return this.changeImpactCaches.set(e,n),n}storeLastAnalyze(e,r){this.lastAnalyze.set(e,r)}startWatching(e){if(!this.watchers.has(e))try{let r=Ba.watch(e,{recursive:!0},(s,n)=>{!n||Ns.test(n)||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,O(r))}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),r}};import V from"path";import Ua from"fs";import Ka from"os";import Wt from"path";function y(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Rs(t){if(!Wt.isAbsolute(t))throw new Error("root must be an absolute path");let e=Wt.resolve(t),r=Ka.homedir();if(e!==r&&!e.startsWith(r+Wt.sep))throw new Error("root must be within the user home directory");let s;try{s=Ua.statSync(e)}catch{throw new Error("root does not exist")}if(!s.isDirectory())throw new Error("root is not a directory")}async function Gs(t,e){let{root:r,entryPoints:s}=e;if(!t.isConfigured(r)){let d=X(r,{allowJs:!1});Qe(d),t.storeConfig(r,d)}if(s.length===0){let d=ne(r);if(d.type!=="none"){let S=t.getConfig(r),F=await t.getOrBuildWorkspace(r,O(S));t.storeLastAnalyze(r,{kind:"workspace"}),t.startWatching(r);let R=Array.from(F.packages.values()).map(({graph:$e,pkg:$t})=>({package:$t.name,relativeRoot:$t.relativeRoot,nodeCount:$e.nodes.size}));return y({monorepoType:d.type,packageCount:F.packages.size,packages:R})}}let n=s.map(d=>V.resolve(r,d)),o=t.getConfig(r),i=o?.coverageReportPath?Xe(r,o.coverageReportPath):new Map,a=await t.getOrBuild(r,n,i);t.storeLastAnalyze(r,{kind:"single",entryPoints:n,coverageMap:i}),t.startWatching(r);let p=a.serialize(),c=p.nodes.reduce((d,S)=>(d[S.category]=(d[S.category]??0)+1,d),{}),m=a.findCycles(),g=nt(a);return y({nodeCount:p.nodes.length,categories:c,cycles:m,languageCoverage:g})}async function Ds(t,e){let{root:r,file:s,depth:n=1,withMeta:o=!1}=e,i=await t.ensureFresh(r),a=ot(i,s,n),p=o?a.map(c=>({...c,...ee(i,c.path)})):a;return y({file:s,dependencies:p})}async function _s(t,e){let{root:r,file:s,withMeta:n=!1}=e,o=await t.ensureFresh(r),i=te(o,s),a=n?i.map(p=>({...p,...ee(o,p.path)})):i;return y({file:s,dependents:a})}async function Ls(t,e){let{root:r,file:s,testsOnly:n=!1,cached:o=!1,changedSymbols:i,withMeta:a=!1}=e,p=await t.ensureFresh(r),c=d=>a?d.map(S=>({path:S,...ee(p,S)})):d;if(o){let d=t.getOrBuildChangeImpact(r),S=st(d,s),F=n?S.filter($e=>p.nodes.get($e)?.category==="test"):S,R=c(F);return y({file:s,affected:R,count:R.length})}let m=it(p,s,{testsOnly:n,changedSymbols:i}),g=c(m);return y({file:s,affected:g,count:g.length})}async function Os(t,e){let{root:r,file:s,depth:n=1,withEdgeDetail:o=!1}=e,i=await t.ensureFresh(r),a=at(i,s,{depth:n,withEdgeDetail:o});return y({file:s,callers:a,count:a.length})}async function js(t,e){let{root:r,entryPoints:s}=e,n=s.map(p=>V.resolve(r,p)),o=await t.getOrBuild(r,n),i=Is(r),a=o.findUnusedFiles(i);return y({unusedFiles:a,count:a.length})}async function Ws(t,e){let{root:r,coverageThreshold:s}=e,n=await t.ensureFresh(r),o=t.getConfig(r),i=s??o?.coverageThreshold??80;if(!ut(n))return y({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let a=[...n.nodes.values()].filter(p=>p.category!=="test"&&p.category!=="config").filter(p=>p.coveragePct!==void 0&&p.coveragePct<i).map(p=>({file:p.path,coveragePct:p.coveragePct}));return y({threshold:i,uncovered:a,count:a.length})}async function zs(t,e){let{root:r}=e,n=[...(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 y({staleDocs:n,count:n.length})}async function $s(t,e){let{root:r,metric:s="cognitiveComplexity",threshold:n=10,limit:o=20}=e,i=await t.ensureFresh(r),a=pt(i,{metric:s,threshold:n,limit:o});return y({metric:s,threshold:n,functions:a,count:a.length})}async function Bs(t,e){let{root:r,changedFiles:s,featureThreshold:n,format:o="tags"}=e,i=await t.ensureFresh(r),a=s??new _e().getChangedFiles().map(m=>V.relative(r,V.resolve(r,m))),p=n!==void 0?{featureDetection:{minOutDegree:n}}:void 0;if(o==="paths"){let m=jt(i,a,p);return y({changedFiles:a,affectedTests:m,count:m.length})}let c=Ot(i,a,p);return y({changedFiles:a,proposedTags:c})}async function Us(t,e){let{root:r,entryPoints:s,featureThreshold:n}=e,o=s?await t.getOrBuild(r,s.map(p=>V.resolve(r,p))):await t.ensureFresh(r),i=G(o.nodes,n!==void 0?{minOutDegree:n}:void 0),a=Array.from(i.values()).sort((p,c)=>c.outDegree-p.outDegree);return y({features:a,count:a.length})}async function Ks(t,e){let{root:r,entryPoints:s,filter:n,mermaid:o=!1,slim:i=!0}=e,a=s?await t.getOrBuild(r,s.map(c=>V.resolve(r,c))):await t.ensureFresh(r),p=Ee(a.serialize(),Fe(n));return o?y(be.serialize(P.deserialize(p))):i?y(ct(p)):y(p)}async function Js(t,e){let{root:r}=e,s=await t.ensureFreshWorkspace(r);return y(lt(s))}async function Hs(t,e){let{root:r,file:s}=e,o=(await t.ensureFreshWorkspace(r)).getAffectedAcrossPackages(s);return y({file:s,affected:o,count:o.length})}function Qs(t,e){let{root:r}=e,s=t.invalidate(r);return y({root:r,cleared:s,message:s?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function Vs(t,e){let{root:r,type:s}=e,n=await t.ensureFresh(r),o=gt(n);if(s)return y(dt(o,s));let i=Array.from(o.types.values());return y({count:i.length,types:i})}async function qs(t,e){let{root:r,paths:s,minOutDegree:n}=e,o=await t.ensureFresh(r),i=ft(o,n!==void 0?{minOutDegree:n}:void 0);if(s?.length){let p=s.map(c=>i.get(c)).filter(Boolean);return y({count:p.length,modules:p})}let a=Array.from(i.values());return y({count:a.length,modules:a})}async function Xs(t,e){let{root:r,minOutDegree:s}=e,n=await t.ensureFresh(r),o=Y(n,s!==void 0?{minOutDegree:s}:void 0),i=Object.fromEntries(o.features);return y({features:i,unassigned:o.unassigned})}async function Ys(t,e){let{root:r,function:s}=e,n=await t.ensureFresh(r);return y(tt(n,s))}async function Zs(t,e){let{root:r,name:s}=e,n=await t.ensureFresh(r),o=mt(n,s);return y({name:s,matches:o,count:o.length})}async function en(t,e){let{root:r,entryPoints:s}=e,n=await t.ensureFresh(r),o=s?.length?s:Ze(n,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 y(et(n,o))}async function tn(t,e){let r=await t.ensureFresh(e.root),s=await Ft(r,e.root,{dryRun:e.dryRun??!1});return y(s)}var rn=[{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. Set testsOnly=true to get only test files. Set cached=true to use a pre-computed O(1) lookup cache instead of graph traversal \u2014 faster on repeated calls for the same root. Pass changedSymbols to restrict blast-radius to files that actually import those symbols \u2014 omit to treat the whole file as changed. Set withMeta=true to get { path, category, exports } objects instead of bare path strings.",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.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"}}},required:["root","entryPoints"]}},{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. TypeScript/JavaScript only.",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:"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."},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, or path. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used.",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. Pass false only when full edge metadata is needed."}},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 typically 85\u201395% fewer tokens than a full graph query.",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: TypeScript/JavaScript gets function-level callers (via call edges); Python gets named-import tracking (which files import this exact symbol); everything else (Go, CoffeeScript, LiveScript, Lua, Gherkin, Markdown, CSS/SCSS/Stylus) falls back to whole-file dependents, which is import-level only \u2014 a listed importer might not even use this specific export. Files whose parser never records exports (CoffeeScript, LiveScript, Lua, Gherkin, Markdown, CSS/SCSS/Stylus) never appear as matches, so a name that only exists in one of those returns an empty result, same as a typo. Each match's `precision` field is 'call' | 'import-symbol' | 'file-level' \u2014 check it before trusting caller/importer results as symbol-exact.",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. Expands export* chains so every symbol accessible to consumers is listed (not just those directly declared in the entry file). Each export is resolved to its defining file and tagged with a kind (function/class/interface/type/enum/const). The graph is partitioned into: internalFiles (implementation reachable from entry points), unreachableFromEntry (non-test files not reachable from any entry point \u2014 may be separate consumers like CLI/MCP, config, or dead code), and testFiles (test suite). Supports multiple public entry points for libraries with sub-path exports. Requires a prior analyze() call. When entryPoints is omitted, auto-detects all entry points from package.json exports/main/module.",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 for a project root, forcing the next analyze() call to rebuild from disk. Call this after editing source files mid-session \u2014 otherwise get_affected, get_dependencies, and other query tools will reason from stale data.",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. Tags of kind 'import' (filename-derived) and 'comment-marker' (domain semantic, propagated from source files) are written as an idempotent block. Re-running is safe: the existing block is replaced in place. Tags already present in the file are excluded from the block to avoid duplication. Supports TypeScript/JavaScript (// <mokosh-tags> block with // @tag lines) and Gherkin .feature files (# <mokosh-tags> block with @tagname lines). Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call.",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 zt(){let t=new ze,e=new Ja({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(Qa,async()=>({tools:rn})),e.setRequestHandler(Ha,async r=>{let{name:s,arguments:n}=r.params,o=n,a={analyze:p=>Gs(t,p),get_dependencies:p=>Ds(t,p),get_dependents:p=>_s(t,p),get_affected:p=>Ls(t,p),get_callers:p=>Os(t,p),find_symbol:p=>Zs(t,p),find_unused:p=>js(t,p),find_uncovered:p=>Ws(t,p),check_doc_drift:p=>zs(t,p),find_complex_functions:p=>$s(t,p),propose_tags:p=>Bs(t,p),detect_features:p=>Us(t,p),get_type_graph:p=>Vs(t,p),get_module_responsibility:p=>qs(t,p),get_feature_graph:p=>Xs(t,p),get_call_graph:p=>Ys(t,p),get_api_surface:p=>en(t,p),query:p=>Ks(t,p),get_workspace_packages:p=>Js(t,p),get_workspace_affected:p=>Hs(t,p),clear_cache:p=>Qs(t,p),apply_tags:p=>tn(t,p)}[s];if(!a)throw new Error(`Unknown tool: ${s}`);try{return Rs(o.root),await a(o)}catch(p){return{content:[{type:"text",text:`Error: ${p instanceof Error?p.message:String(p)}`}],isError:!0}}}),e}async function qa(){let t=zt(),e=new Va;await t.connect(e)}qa().catch(console.error);export{zt as createMcpServer};
28
+ `),this.pool=null}}hasAtLeastFiles(e,t){let s=0,n=[e];for(;n.length>0;){let o=n.pop(),i;try{i=ve.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let a of i)if(a.isDirectory())_s.has(a.name)||n.push(F.join(o,a.name));else if(a.isFile()&&(s++,s>=t))return!0}return s>=t}async processTestFiles(e){let t=re(),s=o=>t.some(i=>o.name.includes(i));this.walkProject(e,s);let n=e;for(;n!==this.rootDir;){let o=F.dirname(n);if(o===n)break;for(let i of oc){let a=F.join(o,i);try{ve.statSync(a).isDirectory()&&this.walkProject(a,s)}catch{}}n=o}await this.drain()}async processDocFiles(){this.walkProject(this.rootDir,e=>e.name.endsWith(".md")||e.name.endsWith(".mdx")),await this.drain()}walkProject(e,t){let s;try{s=ve.readdirSync(e,{withFileTypes:!0})}catch{return}for(let n of s){let o=F.join(e,n.name);n.isDirectory()?_s.has(n.name)||this.walkProject(o,t):n.isFile()&&t(n)&&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(t=>this.finishFile(t)))}}async finishFile(e){let t=ve.statSync(e,{throwIfNoEntry:!1});if(!t?.isFile())return;let s=F.relative(this.rootDir,e),n=await this.getNode(e,s,t);n.imports=await this.resolveImports(e,n.imports),Ts(n.imports,n.tags),this.graph.nodes.set(n.path,n)}async getNode(e,t,s){let n=this.previousGraph?.nodes.get(t);if(n&&n.mtime===s.mtimeMs&&n.size===s.size)return{...n};let o=await this.tryParse(e,t);if(!o)return this.makeStubNode(e,t,s);let i=this.resolveCallEdges(e,o.rawCallEdges),a=this.buildNode(e,t,s,o,i);return this.attachGitStats(a,t),a}async tryParse(e,t){let s=ve.readFileSync(e,"utf-8");try{return await this.parseContent(e,s)}catch(n){return process.stderr.write(`
29
+ Warning: failed to parse ${t}: ${n}
30
+ `),null}}parseContent(e,t){return this.pool?this.pool.run({filePath:e,content:t}):ks(e,t)}makeStubNode(e,t,s){return{path:t,type:R(e),category:"other",imports:[],exports:[],tags:[],mtime:s.mtimeMs,size:s.size}}resolveCallEdges(e,t){let s=[];for(let n of t??[])try{let o=this.resolver.resolve(e,n.toSpecifier);o&&!o.isExternal&&s.push({from:n.from,to:n.to,toFile:F.relative(this.rootDir,o.path)})}catch{}return s}buildNode(e,t,s,n,o){let{imports:i,exports:a,tags:c,category:p,description:l,complexity:g,cognitiveComplexity:d,functions:h}=n;return{path:t,type:R(e),category:p,imports:i,exports:a,tags:c,mtime:s.mtimeMs,size:s.size,...l!==void 0?{description:l}:{},...o.length>0?{callEdges:o}:{},...g!==void 0?{complexity:g}:{},...d!==void 0?{cognitiveComplexity:d}:{},...h!==void 0?{functions:h}:{}}}attachGitStats(e,t){let s=this.gitStatsMap?.get(t);s&&(e.commitCount90d=s.commitCount90d,s.lastAuthor!==void 0&&(e.lastAuthor=s.lastAuthor),s.lastCommitAt!==void 0&&(e.lastCommitAt=s.lastCommitAt))}async resolveImports(e,t){let s=[];for(let n of t){let o=this.resolver.resolveAll(e,n.rawSpecifier);if(o.length!==0)for(let i of o){let a={...n,toPath:i.isExternal?i.path:F.relative(this.rootDir,i.path),isExternal:i.isExternal};i.isWorkspace&&(a.isWorkspace=!0,a.workspacePackage=i.workspacePackage),i.isExternal?this.attachLockfileVersion(a):this.enqueue(i.path),s.push(a)}}return s}attachLockfileVersion(e){if(!this.lockFile)return;let t=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],s=t?this.lockFile.dependencies[t]:void 0;s&&(e.version=s.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};function Os(r,e){return{identifier:e?.identifier??new $e,featureMap:e?.featureDetection===!1?new Map:L(r.nodes,e?.featureDetection??void 0)}}function js(r,e,t,s,n){for(let o of e){let i=r.nodes.get(o);if(!i)continue;let a=new _(o,["*",...i.exports.map(c=>c.name)]);r.traverse(o,(c,p,l)=>{if(!l)return!0;if(!a.updateAffectedSymbols(c,l))return!1;if(p>0){let g=t.get(c.path);if(g)return s(g),!1}return n(c),!0},{direction:"incoming"})}}function Vt(r,e,t){let{identifier:s,featureMap:n}=Os(r,t),o=new Set;for(let i of e){let a=n.get(i);a&&o.add(a.tag)}return js(r,e,n,i=>o.add(i.tag),i=>{if(s.isTestNode(i))for(let a of i.tags)o.add(a.name)}),Array.from(o)}function Ht(r,e,t){let{identifier:s,featureMap:n}=Os(r,t),o=new Set;return js(r,e,n,()=>{},i=>{s.isTestNode(i)&&o.add(i.path)}),Array.from(o)}import cc from"fs";import ke from"path";async function Ws(r,e,t=null,s={}){let n=s.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},o=ke.resolve(r);return await new Ce(o,t,s.pathAliases?new z(o,{pathAliases:s.pathAliases}):void 0,n,s.gitStats??!1,s.coverageMap??new Map,s.parallelParsing??!0).build(e)}async function zs(r,e={}){let t=ke.resolve(r),s=le(t),n=e.packages?s.packages.filter(a=>e.packages?.includes(a.name)||e.packages?.includes(a.relativeRoot)):s.packages,o=new Map(s.packages.map(a=>[a.name,a.root])),i=new fe(t,s.type);for(let a of n){let c=e.silent?void 0:g=>{process.stderr.write(`[${a.name}] Processed ${g} files...\r`)},l=await new Ce(t,null,new z(t,{workspaceMap:o,tsconfigSearchPaths:[a.root,t],pathAliases:e.pathAliases}),c,e.gitStats??!1,new Map,e.parallelParsing??!0).build(a.entryPoints);i.addPackage(a,l)}return i}function $s(r,e={}){let t=[],s=new Set([...e.ignoreDirs??rt,...e.additionalIgnoreDirs??[]]),n=new Set([...e.extensions??st,...e.additionalExtensions??[]]);function o(i){try{let a=cc.readdirSync(i,{withFileTypes:!0});for(let c of a){let p=ke.join(i,c.name);c.isDirectory()?s.has(c.name)||o(p):c.isFile()&&n.has(ke.extname(c.name).toLowerCase())&&t.push(ke.relative(r,p))}}catch{}}return o(r),t}var Bs=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;var Qe=class{graphs=new Map;configs=new Map;workspaceGraphs=new Map;changeImpactCaches=new Map;dirtyRoots=new Set;watchers=new Map;lastAnalyze=new Map;isConfigured(e){return this.configs.has(e)}storeConfig(e,t){this.configs.set(e,t)}getConfig(e){return this.configs.get(e)}async getOrBuild(e,t,s=new Map){let n=this.configs.get(e),o=await Ws(e,t,this.graphs.get(e)??null,{...U(n),coverageMap:s});return this.graphs.set(e,o),o}require(e){let t=this.graphs.get(e);if(!t)throw new Error('No graph cached for this root. Call "analyze" first.');return t}async getOrBuildWorkspace(e,t={}){let s=this.workspaceGraphs.get(e);if(s)return s;let n=await zs(e,t);return this.workspaceGraphs.set(e,n),n}requireWorkspace(e){let t=this.workspaceGraphs.get(e);if(!t)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return t}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){let t=this.changeImpactCaches.get(e);if(t)return t;let s=this.require(e),n=pt(s);return this.changeImpactCaches.set(e,n),n}storeLastAnalyze(e,t){this.lastAnalyze.set(e,t)}startWatching(e){if(!this.watchers.has(e))try{let t=pc.watch(e,{recursive:!0},(s,n)=>{!n||Bs.test(n)||this.dirtyRoots.add(e)});t.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,t)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e);let t=this.lastAnalyze.get(e);return t?.kind==="single"?this.getOrBuild(e,t.entryPoints,t.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 t=this.configs.get(e);return this.getOrBuildWorkspace(e,U(t))}invalidate(e){let t=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),t}};import te from"path";import lc from"fs";import fc from"os";import Qt from"path";function x(r){return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}function Us(r){if(!Qt.isAbsolute(r))throw new Error("root must be an absolute path");let e=Qt.resolve(r),t=fc.homedir();if(e!==t&&!e.startsWith(t+Qt.sep))throw new Error("root must be within the user home directory");let s;try{s=lc.statSync(e)}catch{throw new Error("root does not exist")}if(!s.isDirectory())throw new Error("root is not a directory")}async function Ks(r,e){let{root:t,entryPoints:s}=e;if(!r.isConfigured(t)){let d=se(t,{allowJs:!1});tt(d),r.storeConfig(t,d)}if(s.length===0){let d=le(t);if(d.type!=="none"){let h=r.getConfig(t),v=await r.getOrBuildWorkspace(t,U(h));r.storeLastAnalyze(t,{kind:"workspace"}),r.startWatching(t);let S=Array.from(v.packages.values()).map(({graph:k,pkg:A})=>({package:A.name,relativeRoot:A.relativeRoot,nodeCount:k.nodes.size}));return x({monorepoType:d.type,packageCount:v.packages.size,packages:S})}}let n=s.map(d=>te.resolve(t,d)),o=r.getConfig(t),i=o?.coverageReportPath?nt(t,o.coverageReportPath):new Map,a=await r.getOrBuild(t,n,i);r.storeLastAnalyze(t,{kind:"single",entryPoints:n,coverageMap:i}),r.startWatching(t);let c=a.serialize(),p=c.nodes.reduce((d,h)=>(d[h.category]=(d[h.category]??0)+1,d),{}),l=a.findCycles(),g=ft(a);return x({nodeCount:c.nodes.length,categories:p,cycles:l,languageCoverage:g})}async function Js(r,e){let{root:t,file:s,depth:n=1,withMeta:o=!1}=e,i=await r.ensureFresh(t),a=ut(i,s,n),c=o?a.map(p=>({...p,...ie(i,p.path)})):a;return x({file:s,dependencies:c})}async function Vs(r,e){let{root:t,file:s,withMeta:n=!1}=e,o=await r.ensureFresh(t),i=ae(o,s),a=n?i.map(c=>({...c,...ie(o,c.path)})):i;return x({file:s,dependents:a})}async function Hs(r,e){let{root:t,file:s,testsOnly:n=!1,cached:o=!1,changedSymbols:i,withMeta:a=!1}=e,c=await r.ensureFresh(t),p=d=>a?d.map(h=>({path:h,...ie(c,h)})):d;if(o){let d=r.getOrBuildChangeImpact(t),h=lt(d,s),v=n?h.filter(k=>c.nodes.get(k)?.category==="test"):h,S=p(v);return x({file:s,affected:S,count:S.length})}let l=mt(c,s,{testsOnly:n,changedSymbols:i}),g=p(l);return x({file:s,affected:g,count:g.length})}async function Qs(r,e){let{root:t,file:s,depth:n=1,withEdgeDetail:o=!1}=e,i=await r.ensureFresh(t),a=gt(i,s,{depth:n,withEdgeDetail:o});return x({file:s,callers:a,count:a.length})}async function qs(r,e){let{root:t,entryPoints:s}=e,n=s.map(c=>te.resolve(t,c)),o=await r.getOrBuild(t,n),i=$s(t),a=o.findUnusedFiles(i);return x({unusedFiles:a,count:a.length})}async function Xs(r,e){let{root:t,coverageThreshold:s}=e,n=await r.ensureFresh(t),o=r.getConfig(t),i=s??o?.coverageThreshold??80;if(!xt(n))return x({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let a=[...n.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 x({threshold:i,uncovered:a,count:a.length})}async function Ys(r,e){let{root:t}=e,n=[...(await r.ensureFresh(t)).nodes.values()].filter(o=>o.type==="markdown"&&o.staleFor&&o.staleFor.length>0).map(o=>({doc:o.path,staleFor:o.staleFor}));return x({staleDocs:n,count:n.length})}async function Zs(r,e){let{root:t,metric:s="cognitiveComplexity",threshold:n=10,limit:o=20}=e,i=await r.ensureFresh(t),a=dt(i,{metric:s,threshold:n,limit:o});return x({metric:s,threshold:n,functions:a,count:a.length})}async function en(r,e){let{root:t,changedFiles:s,featureThreshold:n,format:o="tags"}=e,i=await r.ensureFresh(t),a=s??new Be().getChangedFiles().map(l=>te.relative(t,te.resolve(t,l))),c=n!==void 0?{featureDetection:{minOutDegree:n}}:void 0;if(o==="paths"){let l=Ht(i,a,c);return x({changedFiles:a,affectedTests:l,count:l.length})}let p=Vt(i,a,c);return x({changedFiles:a,proposedTags:p})}async function tn(r,e){let{root:t,entryPoints:s,featureThreshold:n}=e,o=s?await r.getOrBuild(t,s.map(c=>te.resolve(t,c))):await r.ensureFresh(t),i=L(o.nodes,n!==void 0?{minOutDegree:n}:void 0),a=Array.from(i.values()).sort((c,p)=>p.outDegree-c.outDegree);return x({features:a,count:a.length})}async function rn(r,e){let{root:t,entryPoints:s,filter:n,mermaid:o=!1,slim:i=!0}=e,a=s?await r.getOrBuild(t,s.map(p=>te.resolve(t,p))):await r.ensureFresh(t),c=Ie(a.serialize(),Re(n));return o?x(Pe.serialize(M.deserialize(c))):i?x(ht(c)):x(c)}async function sn(r,e){let{root:t}=e,s=await r.ensureFreshWorkspace(t);return x(yt(s))}async function nn(r,e){let{root:t,file:s}=e,o=(await r.ensureFreshWorkspace(t)).getAffectedAcrossPackages(s);return x({file:s,affected:o,count:o.length})}function on(r,e){let{root:t}=e,s=r.invalidate(t);return x({root:t,cleared:s,message:s?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function an(r,e){let{root:t,type:s}=e,n=await r.ensureFresh(t),o=vt(n);if(s)return x(Ct(o,s));let i=Array.from(o.types.values());return x({count:i.length,types:i})}async function cn(r,e){let{root:t,paths:s,minOutDegree:n}=e,o=await r.ensureFresh(t),i=St(o,n!==void 0?{minOutDegree:n}:void 0);if(s?.length){let c=s.map(p=>i.get(p)).filter(Boolean);return x({count:c.length,modules:c})}let a=Array.from(i.values());return x({count:a.length,modules:a})}async function pn(r,e){let{root:t,minOutDegree:s}=e,n=await r.ensureFresh(t),o=ne(n,s!==void 0?{minOutDegree:s}:void 0),i=Object.fromEntries(o.features);return x({features:i,unassigned:o.unassigned})}async function ln(r,e){let{root:t,function:s}=e,n=await r.ensureFresh(t);return x(ct(n,s))}async function fn(r,e){let{root:t,name:s}=e,n=await r.ensureFresh(t),o=bt(n,s);return x({name:s,matches:o,count:o.length})}async function un(r,e){let{root:t,entryPoints:s}=e,n=await r.ensureFresh(t),o=s?.length?s:it(n,t);if(o.length===0)throw new Error("No entry points found. Pass entryPoints explicitly or ensure package.json has a main/exports field.");return x(at(n,o))}async function mn(r,e){let t=await r.ensureFresh(e.root),s=await Rt(t,e.root,{dryRun:e.dryRun??!1});return x(s)}var gn=[{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. Set testsOnly=true to get only test files. Set cached=true to use a pre-computed O(1) lookup cache instead of graph traversal \u2014 faster on repeated calls for the same root. Pass changedSymbols to restrict blast-radius to files that actually import those symbols \u2014 omit to treat the whole file as changed. Set withMeta=true to get { path, category, exports } objects instead of bare path strings.",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.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"}}},required:["root","entryPoints"]}},{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:"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."},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, or path. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used.",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. Pass false only when full edge metadata is needed."}},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 typically 85\u201395% fewer tokens than a full graph query.",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: TypeScript/JavaScript, Go, and Python get function-level callers (via call edges) \u2014 though coverage differs per language (Go only tracks package-qualified calls, Python only tracks bare calls to `from module import name` symbols); everything else (CoffeeScript, LiveScript, Lua, Gherkin, Markdown, CSS/SCSS/Stylus) falls back to whole-file dependents, which is import-level only \u2014 a listed importer might not even use this specific export. Files whose parser never records exports (CoffeeScript, LiveScript, Lua, Gherkin, Markdown, CSS/SCSS/Stylus) never appear as matches, so a name that only exists in one of those returns an empty result, same as a typo. Each match's `precision` field is 'call' | 'file-level' \u2014 check it before trusting caller/importer results as symbol-exact.",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. Expands export* chains so every symbol accessible to consumers is listed (not just those directly declared in the entry file). Each export is resolved to its defining file and tagged with a kind (function/class/interface/type/enum/const). The graph is partitioned into: internalFiles (implementation reachable from entry points), unreachableFromEntry (non-test files not reachable from any entry point \u2014 may be separate consumers like CLI/MCP, config, or dead code), and testFiles (test suite). Supports multiple public entry points for libraries with sub-path exports. Requires a prior analyze() call. When entryPoints is omitted, auto-detects all entry points from package.json exports/main/module.",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 for a project root, forcing the next analyze() call to rebuild from disk. Call this after editing source files mid-session \u2014 otherwise get_affected, get_dependencies, and other query tools will reason from stale data.",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. Tags of kind 'import' (filename-derived) and 'comment-marker' (domain semantic, propagated from source files) are written as an idempotent block. Re-running is safe: the existing block is replaced in place. Tags already present in the file are excluded from the block to avoid duplication. Supports TypeScript/JavaScript (// <mokosh-tags> block with // @tag lines) and Gherkin .feature files (# <mokosh-tags> block with @tagname lines). Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call.",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 qt(){let r=new Qe,e=new uc({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(gc,async()=>({tools:gn})),e.setRequestHandler(mc,async t=>{let{name:s,arguments:n}=t.params,o=n,a={analyze:c=>Ks(r,c),get_dependencies:c=>Js(r,c),get_dependents:c=>Vs(r,c),get_affected:c=>Hs(r,c),get_callers:c=>Qs(r,c),find_symbol:c=>fn(r,c),find_unused:c=>qs(r,c),find_uncovered:c=>Xs(r,c),check_doc_drift:c=>Ys(r,c),find_complex_functions:c=>Zs(r,c),propose_tags:c=>en(r,c),detect_features:c=>tn(r,c),get_type_graph:c=>an(r,c),get_module_responsibility:c=>cn(r,c),get_feature_graph:c=>pn(r,c),get_call_graph:c=>ln(r,c),get_api_surface:c=>un(r,c),query:c=>rn(r,c),get_workspace_packages:c=>sn(r,c),get_workspace_affected:c=>nn(r,c),clear_cache:c=>on(r,c),apply_tags:c=>mn(r,c)}[s];if(!a)throw new Error(`Unknown tool: ${s}`);try{return Us(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 hc(){let r=qt(),e=new dc;await r.connect(e)}hc().catch(console.error);export{qt as createMcpServer};
30
31
  //# sourceMappingURL=mcp.mjs.map