@omfalos/mokosh 0.3.2 → 0.3.3

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,34 +1,36 @@
1
1
  #!/usr/bin/env node
2
- var tt=(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 Rs from"path";import{fileURLToPath as Gs}from"url";var Ls=()=>Gs(import.meta.url),_s=()=>Rs.dirname(Ls()),u=_s();import{StdioServerTransport as Hc}from"@modelcontextprotocol/sdk/server/stdio.js";import{Server as Kc}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Jc,ListToolsRequestSchema as Vc}from"@modelcontextprotocol/sdk/types.js";import $c from"fs";import ot from"fs";import xr from"path";var Os=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],mr=[];function we(t){mr.push(t)}function gr(t){return[...Os,...mr].some(e=>typeof e=="string"?t.includes(e):e instanceof RegExp?e.test(t):e(t))}var js=[".test.",".spec.","-test.","-spec."],dr=[];function Ce(t){dr.push(t)}function te(){return[...js,...dr]}var Ws=["jest","vitest","playwright","cypress","@testing-library/"],hr=[];function Fe(t){hr.push(t)}function rt(){return[...Ws,...hr]}var yr=.8;function nt(t){yr=t}function st(){return yr}var zs=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function re(t,{allowJs:e=!0,isExplicitPath:r=!1}={}){if(r){let n=xr.resolve(t);return ot.existsSync(n)?n.endsWith(".json")?Sr(n):e?br(n):{}:{}}for(let n of zs){let s=xr.resolve(t,n);if(ot.existsSync(s)){if(n.endsWith(".json"))return Sr(s);if(e)return br(s)}}return{}}function Sr(t){return JSON.parse(ot.readFileSync(t,"utf-8"))}function br(t){let e=tt(t);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function it(t){for(let e of t.configMatchers??[])we(e);for(let e of t.testPatterns??[])Ce(e);for(let e of t.testLibraries??[])Fe(e);t.barrelThreshold!==void 0&&nt(t.barrelThreshold)}function V(t){return{gitStats:t?.gitStats??!1,parallelParsing:t?.parallelParsing,pathAliases:t?.pathAliases}}var j=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"],at=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".feature",".md",".mdx"];import $s from"fs";import vr from"path";function ct(t,e){let r=vr.resolve(t,e);try{let n=$s.readFileSync(r,"utf-8"),s=JSON.parse(n),o=new Map;for(let[i,a]of Object.entries(s)){if(i==="total")continue;let c=a?.lines?.pct;if(typeof c!="number")continue;let p=vr.relative(t,i);o.set(p,c)}return o}catch{return new Map}}var Ee={serialize(t){let e=["graph TD"],r=new Set;for(let n of t.nodes.values()){let s=`"${n.path}"`;for(let o of n.imports){if(!o.toPath)continue;let i=`"${o.toPath}"`,a=`${n.path} -> ${o.toPath}`;if(!r.has(a)){let c=o.isStyle?"-- styles -->":"-->";e.push(` ${s} ${c} ${i}`),r.add(a)}}}return e.join(`
3
- `)}};import kr from"fs";import Us from"path";function pt(t,e){let r=t.replace(/^\.\//,"");if(e.nodes.has(r))return r;let n=r.replace(/^dist\//,"src/").replace(/\.(js|mjs|cjs)$/,".ts");return e.nodes.has(n)?n:null}function wr(t,e){if(typeof t=="string")return pt(t,e);if(t&&typeof t=="object"){let r=t;for(let n of["import","require","default"]){let s=wr(r[n],e);if(s)return s}}return null}function Ks(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 Js(t,e){let r=new Set,n=new Set,s=[...e];for(;s.length;){let o=s.shift();if(n.has(o))continue;n.add(o);let i=t.nodes.get(o);if(i){for(let a of i.exports)r.add(a.name);for(let a of i.imports){if(a.type!=="re-export"||a.isExternal||!a.toPath)continue;if(!a.symbols?.length||a.symbols.includes("*")){let p=t.nodes.get(a.toPath);if(p)for(let l of p.exports)r.add(l.name);s.push(a.toPath)}else for(let p of a.symbols)r.add(p)}}}return r}function lt(t,e){let r=[],n=Us.join(e,"package.json");if(kr.existsSync(n))try{let s=JSON.parse(kr.readFileSync(n,"utf8"));if(s.exports&&typeof s.exports=="object"&&!Array.isArray(s.exports))for(let o of Object.values(s.exports)){let i=wr(o,t);i&&!r.includes(i)&&r.push(i)}else if(typeof s.exports=="string"){let o=pt(s.exports,t);o&&r.push(o)}if(r.length===0)for(let o of[s.main,s.module].filter(Boolean)){let i=pt(o,t);i&&!r.includes(i)&&r.push(i)}}catch{}if(r.length===0){for(let s of["src/index.ts","src/index.js","index.ts","index.js"])if(t.nodes.has(s)){r.push(s);break}}return r}function Vs(t,e){let r=new Set(e);for(let n of e)t.traverse(n,s=>(r.add(s.path),!0),{direction:"outgoing"});return r}function Hs(t,e,r){let n=new Map;for(let s of e){if(r.includes(s))continue;let o=t.nodes.get(s);if(!o)continue;let i=o.category==="barrel";for(let a of o.exports){let c=n.get(a.name),p=!!(a.signature||a.doc);(!c||p&&!i)&&n.set(a.name,{file:s,symbol:a})}}return n}function Qs(t,e,r,n){let s=[];for(let o of t){let i=e.get(o),a=n.flatMap(d=>r.nodes.get(d)?.exports??[]).find(d=>d.name===o),c=i?.symbol??a,p=i?.file??n.find(d=>r.nodes.get(d)?.exports.some(f=>f.name===o))??n[0],l={name:o,definedIn:p,kind:Ks(c?.signature)};c?.doc&&(l.doc=c.doc),c?.signature&&(l.signature=c.signature),s.push(l)}return s.sort((o,i)=>o.name.localeCompare(i.name)),s}function qs(t,e,r){let n=c=>t.nodes.get(c)?.category==="test",s=[...e].filter(c=>!r.includes(c)&&!n(c)),o=[...t.nodes.keys()].filter(c=>!e.has(c)),i=o.filter(c=>!n(c)),a=o.filter(c=>n(c));return{internalFiles:s,unreachableFromEntry:i,testFiles:a}}function ut(t,e){if(e.length===0)throw new Error("buildApiSurface requires at least one entry point");for(let p of e)if(!t.nodes.has(p))throw new Error(`Entry point not found in graph: ${p}`);let r=Vs(t,e),n=Hs(t,r,e),s=Js(t,e),o=Qs(s,n,t,e),{internalFiles:i,unreachableFromEntry:a,testFiles:c}=qs(t,r,e);return{entryPoints:e,publicExports:o,internalFiles:i,unreachableFromEntry:a,testFiles:c}}function ft(t,e){let r=null,n=[];for(let o of t.nodes.values()){o.exports.some(i=>i.name===e)&&(r=o.path);for(let i of o.callEdges??[])i.to===e&&n.push({file:o.path,callerFunction:i.from})}let s=[];if(r){let o=t.nodes.get(r);for(let i of o?.callEdges??[])i.from===e&&s.push({file:i.toFile,calleeFunction:i.to})}return{functionName:e,definedIn:r,callers:n,callees:s}}import Ep from"fs";import Pp from"path";function Cr(t){let e=[...t.nodes.entries()].sort(([n],[s])=>n.localeCompare(s)).map(([n,s])=>`${n}:${s.mtime}:${s.size}`).join("|"),r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}function mt(t){let e=new Map;for(let r of t.nodes.keys()){let n=[];t.traverse(r,s=>(s.path!==r&&n.push(s.path),!0),{direction:"incoming"}),e.set(r,n)}return{impact:e,graphHash:Cr(t)}}function gt(t,e){return t.impact.get(e)??[]}import{readFile as Ro}from"fs/promises";import xt from"path";import Te from"fs";import Ys from"path";import{load as Fr}from"js-yaml";var dt=["package-lock.json","yarn.lock","pnpm-lock.yaml"];function Er(t){let e=t.lastIndexOf("@");return e>0?t.substring(0,e):t}function Xs(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)),Er(r)}).filter(Boolean)}function Zs(t,e){let r=t.startsWith("/")?t.slice(1):t,n=r.lastIndexOf("@");return n>0?{name:r.substring(0,n),version:e||r.substring(n+1)}:{name:r,version:e}}function eo(t){try{let e=Fr(t),r={dependencies:{}};for(let[n,s]of Object.entries(e))if(!(n==="__metadata"||!s?.version))for(let o of n.split(", ")){let i=Er(o);i&&(r.dependencies[i]={version:s.version,...s.dependencies!==void 0&&{dependencies:s.dependencies}})}return r}catch{return null}}function to(t){let e={dependencies:{}};for(let r of t.split(/\n\n+/)){let n=r.split(`
4
- `).filter(c=>c.trim().length>0&&!c.trim().startsWith("#"));if(n.length<2)continue;let s=n[0];if(!s||s.startsWith(" "))continue;let o=Xs(s);if(o.length===0)continue;let a=n.find(c=>c.trim().startsWith('version "'))?.match(/version "(.*?)"/)?.[1]??"";for(let c of o)e.dependencies[c]={version:a}}return e}function ro(t){let e=Te.readFileSync(t,"utf-8"),r=JSON.parse(e),n={dependencies:{}};if(r.packages)for(let[s,o]of Object.entries(r.packages)){if(!s.startsWith("node_modules/"))continue;let i=s.replace("node_modules/","");i.includes("node_modules/")||(n.dependencies[i]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}else if(r.dependencies)for(let[s,o]of Object.entries(r.dependencies))n.dependencies[s]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}};return n}function no(t){let e=Te.readFileSync(t,"utf-8");if(e.includes("__metadata:")){let r=eo(e);if(r!==null)return r}return to(e)}function so(t){let e=Te.readFileSync(t,"utf-8"),r={dependencies:{}};try{let n=Fr(e);if(n.packages)for(let[s,o]of Object.entries(n.packages)){let{name:i,version:a}=Zs(s,o.version);i&&(r.dependencies[i]={version:a,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}if(n.dependencies)for(let[s,o]of Object.entries(n.dependencies)){if(r.dependencies[s])continue;let i=typeof o=="string"?o:o.version;r.dependencies[s]={version:i||""}}}catch{}return r}function Tr(t){let e={"package-lock.json":ro,"yarn.lock":no,"pnpm-lock.yaml":so},r=dt.map(n=>[n,e[n]]);for(let[n,s]of r){let o=Ys.join(t,n);if(Te.existsSync(o))return s(o)}return null}var oo=new Set(["css","scss","less","stylus"]);function Pr(t){return oo.has(t)?"style":"code"}function io(t){let e=5381;for(let r=0;r<t.length;r++)e=e*33+t.charCodeAt(r)>>>0;return e.toString(36)}function ao(t,e){let r=[];for(let n=0;n<=t.length-e;n++)r.push(io(t.slice(n,n+e).map(s=>s.text).join(" ")));return r}function co(t,e,r){let n=t.get(e.file),s=t.get(r.file);if(!n||!s)return 0;let o=0;for(;e.windowIndex+o+1<n.length&&r.windowIndex+o+1<s.length&&n[e.windowIndex+o+1]===s[r.windowIndex+o+1];)o++;return o}function po(t,e,r){if(e.windowIndex===0||r.windowIndex===0)return!0;let n=t.get(e.file),s=t.get(r.file);return!n||!s?!0:n[e.windowIndex-1]!==s[r.windowIndex-1]}var ht=class{parent=new Map;find(e){this.parent.has(e)||this.parent.set(e,e);let r=e;for(;this.parent.get(r)!==r;)r=this.parent.get(r);let n=e;for(;n!==r;){let s=this.parent.get(n);this.parent.set(n,r),n=s}return r}union(e,r){let n=this.find(e),s=this.find(r);n!==s&&this.parent.set(n,s)}root(e){return this.find(e)}};function Pe(t){return`${t.file}#${t.startLine}#${t.endLine}`}var lo=new Set(["{","}",":",",","[","]"]);function uo(t,e,r){let n=0;for(let s=e;s<e+r;s++)lo.has(t[s].text)&&n++;return n/r}function Ar(t,e,r,n=.5){let s=new Map,o=new Map,i=new Map;for(let{file:f,tokens:h}of t){if(h.length<e)continue;o.set(f,h);let x=ao(h,e);s.set(f,x);for(let y=0;y<x.length;y++){let S={file:f,windowIndex:y},C=i.get(x[y]);C?C.push(S):i.set(x[y],[S])}}let a=[];for(let f of i.values())if(!(f.length<2))for(let h=0;h<f.length;h++)for(let x=h+1;x<f.length;x++){let y=f[h],S=f[x];if(y.file===S.file&&y.windowIndex===S.windowIndex||!po(s,y,S))continue;let C=co(s,y,S),N=e+C,M=o.get(y.file);if(uo(M,y.windowIndex,N)>n)continue;if(y.file===S.file){let[Is,Ds]=y.windowIndex<S.windowIndex?[y,S]:[S,y];if(Is.windowIndex+N>Ds.windowIndex)continue}let O=o.get(S.file),Ze={file:y.file,startLine:M[y.windowIndex].line,endLine:M[y.windowIndex+N-1].line},et={file:S.file,startLine:O[S.windowIndex].line,endLine:O[S.windowIndex+N-1].line},fr=Math.min(Ze.endLine-Ze.startLine+1,et.endLine-et.startLine+1);fr<r||a.push({occA:Ze,occB:et,lines:fr,tokens:N})}let c=new ht,p=new Map;for(let{occA:f,occB:h}of a){let x=Pe(f),y=Pe(h);p.set(x,f),p.set(y,h),c.union(x,y)}let l=new Map;for(let f of p.keys()){let h=c.root(f),x=l.get(h);x?x.add(f):l.set(h,new Set([f]))}let d=[];for(let f of l.values()){if(f.size<2)continue;let h=[...f].map(S=>p.get(S)),x=0,y=e;for(let S of a)!f.has(Pe(S.occA))||!f.has(Pe(S.occB))||S.lines>x&&(x=S.lines,y=S.tokens);d.push({occurrences:h,lines:x,tokens:y})}return d.sort((f,h)=>h.lines-f.lines)}import Mr from"postcss";import*as fo from"postcss-less";var mo=fo,Ir=new Set(["reference","inline"]);function Nr(t){return t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("data:")}function go(t){let e=t.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function ho(t,e){let r=t.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(r){let o=r[1]?.trim()??"",i=r[2]??"";if(!i)return null;let a=Ir.has(o)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a,...Nr(i)?{isExternal:!0}:{}}}let n=t.match(/^url\(['"]?([^'")]+)['"]?\)/),s=n?n[1]?.trim()??"":t.match(/^['"]([^'"]+)['"]/)?.[1]??"";return s?{fromPath:e,toPath:"",rawSpecifier:s,isStyle:!0,type:"static",...Nr(s)?{isExternal:!0}:{}}:null}function yo(t,e){let r=[],n=/url\(['"]?([^'")]+)['"]?\)/g,s=n.exec(t);for(;s!==null;){let o=s[1]?.trim()??"";go(o)&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),s=n.exec(t)}return r}function Dr(t,e){let r=[];return t.walk(n=>{if(n.type==="atrule"&&n.name==="import"){let s=ho(n.params,e);s&&r.push(s)}n.type==="decl"&&r.push(...yo(n.value,e))}),r}function xo(t){return t.replace(/(?<!:)\/\/.*/g,"")}function So(t,e){let r=[],n=/@import\s+(?:\(([^)]+)\)\s+)?['"]([^'"]+)['"]/g,s=n.exec(t);for(;s!==null;){let o=s[1]?.trim()??"",i=s[2]??"";if(i){let a=Ir.has(o)?"side-effect":"static";r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a})}s=n.exec(t)}return r}function Ae(t,e){let r=Mr.parse(xo(t));return{imports:Dr(r,e),root:r}}function bo(t){let e=[],r=[];for(let n of t.nodes??[]){if(n.type!=="atrule")continue;let{value:s}=n;if(s===void 0)continue;let o=n.name;o&&(e.push({name:o}),r.push({name:o,kind:"variable"}))}return{exports:e,tags:r}}function Ne(t,e){try{let r=mo.parse(t),{exports:n,tags:s}=bo(r);return{imports:Dr(r,e),root:r,exports:n,tags:s}}catch{return{imports:So(t,e),root:Mr.parse(""),exports:[],tags:[]}}}import{parse as vo}from"postcss-scss";function Rr(t){return t.startsWith("_")||t.startsWith("-")}function ko(t){return!!(t.startsWith("sass:")||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("_"))}function wo(t){let e=t.match(/^['"]([^'"]+)['"]/);if(!e?.[1])return{specifier:""};let r=e[1],s=t.match(/\bas\s+(\S+)/)?.[1];return s!==void 0?{specifier:r,alias:s}:{specifier:r}}function Co(t){let e=[],r=[];for(let n of t.nodes??[]){if(n.type==="decl"&&n.prop.startsWith("$")){let s=n.prop.slice(1);if(!s||Rr(s))continue;e.push({name:s}),r.push({name:s,kind:"variable"});continue}if(n.type==="atrule"&&(n.name==="mixin"||n.name==="function")){let o=n.params.match(/^([\w-]+)/)?.[1];if(!o||Rr(o))continue;let i=n.params.trim();e.push(i.includes("(")?{name:o,signature:i}:{name:o}),r.push({name:o,kind:"function"})}}return{exports:e,tags:r}}function Me(t,e){let r=vo(t),n=[];r.walk(i=>{if(i.type!=="atrule")return;let{name:a,params:c}=i;if(a!=="import"&&a!=="use"&&a!=="forward")return;let{specifier:p,alias:l}=wo(c);if(!p)return;let d={fromPath:e,toPath:"",rawSpecifier:p,isStyle:!0,type:a==="forward"?"re-export":"static",...ko(p)?{isExternal:!0}:{}};l&&(d.symbols=[l]),n.push(d)});let{exports:s,tags:o}=Co(r);return{imports:n,root:r,exports:s,tags:o}}function Fo(t){return t.trim().replace(/\s+/g," ")}function Eo(t){try{return t.fileType==="scss"?Me(t.source,t.file).root:t.fileType==="less"?Ne(t.source,t.file).root:t.fileType==="css"?Ae(t.source,t.file).root:void 0}catch{return}}function To(t){let e=Eo(t);if(!e)return[];let r=[];return e.walkRules(n=>{let s=n.nodes?.filter(l=>l.type==="decl")??[];if(s.length===0)return;let o=s[0],i=s[s.length-1],a=n.source?.start?.line??o?.source?.start?.line,c=i?.source?.end?.line??i?.source?.start?.line??a;if(a===void 0||c===void 0)return;let p=s.map(l=>`${l.prop.trim().toLowerCase()}:${Fo(l.value)}`).join(";");r.push({file:t.file,startLine:a,endLine:c,lines:c-a+1,signature:p,declCount:s.length})}),r}function Gr(t,e,r=2){let n=new Map;for(let o of t)for(let i of To(o)){if(i.declCount<r||i.lines<e)continue;let a=n.get(i.signature);a?a.push(i):n.set(i.signature,[i])}let s=[];for(let o of n.values())for(let i=0;i<o.length;i++)for(let a=i+1;a<o.length;a++){let c=o[i],p=o[a];if(c.file===p.file&&c.startLine===p.startLine&&c.endLine===p.endLine)continue;let l={file:c.file,startLine:c.startLine,endLine:c.endLine},d={file:p.file,startLine:p.startLine,endLine:p.endLine};s.push({occurrences:[l,d],lines:Math.min(c.lines,p.lines),tokens:c.declCount,family:"style"})}return s.sort((o,i)=>i.lines-o.lines)}var Po={typescript:{line:["//"],block:[["/*","*/"]]},javascript:{line:["//"],block:[["/*","*/"]]},go:{line:["//"],block:[["/*","*/"]]},css:{block:[["/*","*/"]]},scss:{line:["//"],block:[["/*","*/"]]},less:{line:["//"],block:[["/*","*/"]]},stylus:{line:["//"],block:[["/*","*/"]]},python:{line:["#"]},gherkin:{line:["#"]},coffeescript:{line:["#"],block:[["###","###"]]},livescript:{line:["#"],block:[["###","###"]]},lua:{line:["--"],block:[["--[[","]]"]]},markdown:{block:[["<!--","-->"]]}};function Lr(t,e,r){let n=t.slice(e,r).replace(/[^\n]/g," ");return t.slice(0,e)+n+t.slice(r)}function Ao(t,e){if(!e)return t;let r=t;for(let[n,s]of e.block??[]){let o=0;for(;;){let i=r.indexOf(n,o);if(i===-1)break;let a=r.indexOf(s,i+n.length),c=a===-1?r.length:a+s.length;r=Lr(r,i,c),o=c}}for(let n of e.line??[]){let s=0;for(;;){let o=r.indexOf(n,s);if(o===-1)break;let i=r.indexOf(`
5
- `,o),a=i===-1?r.length:i;r=Lr(r,o,a),s=a}}return r}var No=["===","!==","...","=>","==","!=","<=",">=","&&","||","::","->","..","+=","-=","*=","/="],yt=new RegExp(`${No.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")}|[A-Za-z_$][A-Za-z0-9_$]*|\\d+(?:\\.\\d+)?|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|\\S`,"g"),Mo=/^[A-Za-z_$][A-Za-z0-9_$]*$/,_r=/^\d+(?:\.\d+)?$/,Io=/^(".*"|'.*'|`.*`)$/s,Do=new Set(["if","else","elif","for","while","do","switch","case","default","break","continue","return","function","def","class","struct","interface","const","let","var","local","import","export","from","package","try","catch","except","finally","throw","raise","new","this","self","end","then","yield","async","await","nil","null","None","true","false","True","False","and","or","not","in","of","is"]);function Or(t,e,r=!0){let n=Ao(t,Po[e]),s=[],o=1,i=0;yt.lastIndex=0;let a=yt.exec(n);for(;a!==null;){for(let l=i;l<a.index;l++)n[l]===`
6
- `&&o++;i=a.index;let c=a[0],p=c;Mo.test(c)&&!Do.has(c)?p="ID":r&&(_r.test(c)||Io.test(c))&&(p=_r.test(c)?"NUM":"STR"),s.push({text:p,line:o});for(let l=i;l<a.index+c.length;l++)n[l]===`
7
- `&&o++;i=a.index+c.length,a=yt.exec(n)}return s}var Go=new Set(["css","scss","less"]);function Lo(t){return dt.includes(xt.basename(t))}function _o(t,e){if(e.length===0)return!1;let r=new Set(e);return t.split(xt.sep).some(n=>r.has(n))}async function St(t,e,r={}){let{minLines:n=6,windowSize:s=15,ignoreLiterals:o=!0,maxPunctuationRatio:i=.5,limit:a=50,ignoreDirs:c=j}=r,p=[...t.nodes.values()].filter(h=>!Lo(h.path)&&!_o(h.path,c)),l=[],d=new Map;await Promise.all(p.map(async h=>{let x;try{x=await Ro(xt.join(e,h.path),"utf8")}catch{return}if(Go.has(h.type)){l.push({file:h.path,source:x,fileType:h.type});return}let y=Pr(h.type),S={file:h.path,tokens:Or(x,h.type,o)},C=d.get(y);C?C.push(S):d.set(y,[S])}));let f=Gr(l,n);for(let[h,x]of d)for(let y of Ar(x,s,n,i))f.push({...y,family:h});return f.sort((h,x)=>x.lines-h.lines).slice(0,a)}import Ie from"path";function Oo(t){let e=new Map;for(let[r,n]of t){let s=n.imports.filter(o=>o.toPath&&!o.isExternal).length;s>0&&e.set(r,s)}return e}function jo(t,e,r){let n=new Map;for(let[s,o]of e){if(o<r)continue;let i=t.get(s);if(!i||i.category==="test"||i.category==="barrel")continue;let a=Ie.extname(s),c=Ie.basename(s,a),p=c==="index"?Ie.basename(Ie.dirname(s)):c;n.set(s,{path:s,outDegree:o,tag:`feature:${p}`})}return n}function W(t,e){let r=e?.minOutDegree??5;return jo(t,Oo(t),r)}var Wo=(t,e)=>t.outDegree-e.outDegree;function zo(t,e){let r=new Map;for(let n of e.values()){let s=new Set;t.traverse(n.path,o=>(o.path!==n.path&&s.add(o.path),!0),{direction:"outgoing"}),r.set(n.path,s)}return r}function $o(t,e,r,n){let s=new Map;for(let[o]of t){if(e.has(o))continue;let i=null;for(let a of e.values())r.get(a.path)?.has(o)&&(!i||n(a,i)<0)&&(i=a);i&&s.set(o,i.path)}return s}function Bo(t,e){let r=new Map;for(let n of t.values()){let s=n.tag.replace("feature:",""),o=[];for(let[i,a]of e)a===n.path&&o.push(i);r.set(s,{hub:n.path,outDegree:n.outDegree,files:o})}return r}function Uo(t,e,r){let n=[];for(let s of t.keys())!e.has(s)&&!r.has(s)&&n.push(s);return n}function ne(t,e){let r=e?.detectFn??W,n=e?.hubComparator??Wo,s=r(t.nodes,e),o=zo(t,s),i=$o(t.nodes,s,o,n);return{features:Bo(s,i),unassigned:Uo(t.nodes,s,i)}}var jr=new Set(["typescript","javascript","python","go","scss","less","lua","coffeescript"]),Wr=new Set(["typescript","javascript","python"]),De=new Set(["typescript","javascript","go","python"]);function bt(t){let e=new Map;for(let r of t.nodes.values())e.set(r.type,(e.get(r.type)??0)+1);return[...e.entries()].map(([r,n])=>({type:r,fileCount:n,exportsTracked:jr.has(r),importSymbolsTracked:Wr.has(r),callEdgesTracked:De.has(r)})).sort((r,n)=>n.fileCount-r.fileCount)}var se=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let r=new Set(this.nodes.keys());return e.filter(n=>!r.has(n))}findHighExportUsage(e){let r=[];for(let n of this.nodes.values()){if(n.maxExportUsage===void 0||n.maxExportUsage<e)continue;let s=n.imports.reduce((o,i)=>(i.exportUsageRatio??0)>(o?.exportUsageRatio??0)?i:o,null);r.push({path:n.path,maxExportUsage:n.maxExportUsage,tightestDep:s?.toPath??""})}return r.sort((n,s)=>s.maxExportUsage-n.maxExportUsage)}findCycles(){let e=[],r=new Set,n=new Set,s=[],o=i=>{r.add(i),n.add(i),s.push(i);let a=this.nodes.get(i);if(a){for(let c of a.imports)if(!(!c.toPath||c.isExternal))if(n.has(c.toPath)){let p=s.indexOf(c.toPath);e.push([...s.slice(p),c.toPath])}else r.has(c.toPath)||o(c.toPath)}n.delete(i),s.pop()};for(let i of this.nodes.keys())r.has(i)||o(i);return e}};var D=class t{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let r=new Map;for(let n of e.nodes)r.set(n.path,n);return new t(r)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let r of this.nodes.values())for(let n of r.imports)if(n.toPath){let s=e.get(n.toPath)||[];s.push(r.path),e.set(n.toPath,s)}return this._incomingEdgesCache=e,e}dfs(e,r,n,s){let o=new Set,i=n.maxDepth??1/0,a=(c,p,l)=>{if(p>i||o.has(c))return;let d=this.nodes.get(c);if(d&&(o.add(c),r(d,p,l)!==!1))for(let f of s(c))a(f,p+1,c)};a(e,0,null)}traverse(e,r,n={}){let s=n.direction??"outgoing",o=s==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,r,n,i=>s==="outgoing"?this.nodes.get(i)?.imports.map(a=>a.toPath).filter(Boolean)??[]:o?.get(i)??[])}getCallIncomingCache(){if(this._callIncomingCache)return this._callIncomingCache;let e=new Map;for(let r of this.nodes.values())for(let n of r.callEdges??[]){let s=e.get(n.toFile)??[];s.push(r.path),e.set(n.toFile,s)}return this._callIncomingCache=e,e}traverseCalls(e,r,n={}){let s=n.direction??"outgoing",o=s==="incoming"?this.getCallIncomingCache():null;this.dfs(e,r,n,i=>s==="outgoing"?this.nodes.get(i)?.callEdges?.map(a=>a.toFile)??[]:o?.get(i)??[])}getCallers(e){let r=[];return this.traverseCalls(e,n=>(n.path!==e&&r.push(n.path),!0),{direction:"incoming",maxDepth:1}),r}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let r=this.nodes.get(e);return r?r.imports.map(n=>this.nodes.get(n.toPath)).filter(n=>n!==void 0):[]}findUnusedFiles(e){return new se(this.nodes).findUnusedFiles(e)}findCycles(){return new se(this.nodes).findCycles()}};var z=class{affectedSymbols=new Map;constructor(e,r){this.affectedSymbols.set(e,new Set(["default",...r]))}updateAffectedSymbols(e,r){let n=this.affectedSymbols.get(r)||new Set,s=e.imports.find(c=>c.toPath===r);if(!s)return!1;let o=s.symbols||["*"],i=new Set;for(let c of o)(c==="*"||n.has("*")||n.has(c))&&i.add("*");if(i.size===0)return!1;let a=this.affectedSymbols.get(e.path)||new Set;for(let c of i)a.add(c);return this.affectedSymbols.set(e.path,a),!0}};function oe(t,e){let r=t.nodes.get(e);if(r)return{category:r.category,exports:r.exports.map(n=>n.name)}}function vt(t,e,r=1){let n=[];return t.traverse(e,(s,o,i)=>{if(s.path===e)return!0;let a=i?t.nodes.get(i)?.imports.find(c=>c.toPath===s.path):void 0;return n.push({path:s.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"outgoing",maxDepth:r}),n}function ie(t,e){let r=[];return t.traverse(e,n=>{if(n.path===e)return!0;let s=n.imports.find(o=>o.toPath===e);return r.push({path:n.path,...s?.symbols?{symbols:s.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),r}function kt(t,e,r={}){let{testsOnly:n=!1,changedSymbols:s}=r,o=s?new z(e,s):null,i=[];return t.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(d=>d.name==="test");return(!n||l)&&i.push(a.path),!0},{direction:"incoming"}),i}function wt(t,e,r={}){let{depth:n=1,withEdgeDetail:s=!1}=r,o=[];return t.traverseCalls(e,i=>{if(i.path===e)return!0;let a={file:i.path};return s&&(a.edges=(i.callEdges??[]).filter(c=>c.toFile===e).map(c=>({from:c.from,to:c.to}))),o.push(a),!0},{direction:"incoming",maxDepth:n}),o}function Ct(t,e={}){let{metric:r="cognitiveComplexity",threshold:n=10,limit:s=20}=e;return[...t.nodes.values()].flatMap(o=>(o.functions??[]).filter(i=>i[r]>=n).map(i=>({file:o.path,name:i.name,line:i.line,complexity:i.complexity,cognitiveComplexity:i.cognitiveComplexity}))).sort((o,i)=>i[r]-o[r]).slice(0,s)}function Ft(t){return{nodes:t.nodes.map(r=>({path:r.path,type:r.type,category:r.category,exports:r.exports.map(n=>n.name),tags:r.tags.filter(n=>n.kind==="comment-marker"||n.kind==="import").map(n=>n.name),importsFiles:r.imports.filter(n=>!n.isExternal&&n.toPath).map(n=>n.toPath),...r.description!==void 0&&{description:r.description},...r.testedBy!==void 0&&{testedBy:r.testedBy},...r.coveragePct!==void 0&&{coveragePct:r.coveragePct},...r.avgExportUsage!==void 0&&{avgExportUsage:r.avgExportUsage},...r.maxExportUsage!==void 0&&{maxExportUsage:r.maxExportUsage}})),cycles:t.cycles}}function Et(t){let e=t.getPackageDependencies(),r=Array.from(t.packages.values()).map(({graph:n,pkg:s})=>({name:s.name,relativeRoot:s.relativeRoot,nodeCount:n.nodes.size,dependsOn:e.get(s.name)??[]}));return{monorepoType:t.type,packageCount:r.length,packages:r}}function Tt(t){return[...t.nodes.values()].some(e=>e.coveragePct!==void 0)}function zr(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 k(e,"component")||k(e,"components")?"component":k(e,"controller")||k(e,"controllers")?"controller":k(e,"middleware")?"middleware":k(e,"router")||k(e,"routes")||k(e,"route")?"router":k(e,"store")||k(e,"stores")?"store":k(e,"service")||k(e,"services")?"service":k(e,"handler")||k(e,"handlers")?"handler":k(e,"adapter")||k(e,"adapters")?"adapter":k(e,"plugin")||k(e,"plugins")?"plugin":k(e,"api")?"api":k(e,"cli")||k(e,"commands")||ae(e)==="cli"?"cli":k(e,"util")||k(e,"utils")||k(e,"helper")||k(e,"helpers")?"util":k(e,"model")||k(e,"models")||ae(e)==="model"?"model":k(e,"parser")||k(e,"parsers")||ae(e)==="parser"?"parser":ae(e)==="builder"?"builder":ae(e)==="resolver"?"resolver":"other"}function k(t,e){return t.includes(`/${e}/`)||t.includes(`/${e}.`)}function ae(t){let e=t.slice(t.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function Pt(t,e){let r=ne(t,e),n=new Map;for(let[o,i]of r.features){for(let a of i.files)n.set(a,o);n.set(i.hub,o)}let s=new Map;for(let o of t.nodes.values()){let i=n.get(o.path);s.set(o.path,{path:o.path,role:zr(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return s}function At(t,e){let r=[];for(let n of t.nodes.values())if(n.exports.some(s=>s.name===e))if(De.has(n.type)){let s=[];for(let o of t.nodes.values())for(let i of o.callEdges??[])i.to===e&&s.push({file:o.path,callerFunction:i.from});r.push({path:n.path,category:n.category,precision:"call",callers:s})}else{let s=ie(t,n.path).map(o=>({file:o.path,...o.symbols?{symbols:o.symbols}:{}}));r.push({path:n.path,category:n.category,precision:"file-level",importers:s})}return r}function Ko(t){return t?t.startsWith("interface ")?"interface":t.startsWith("class ")?"class":t.startsWith("enum ")?"enum":"type":"type"}function Jo(t,e){if(e==="type-only")return!0;let r=t.signature??"";return r.startsWith("interface ")||r.startsWith("class ")||r.startsWith("enum ")}function Nt(t){let e=new Map;for(let n of t.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript"))for(let s of n.exports){if(!Jo(s,n.category))continue;let o=`${n.path}::${s.name}`;e.set(o,{name:s.name,file:n.path,kind:Ko(s.signature),...s.doc?{doc:s.doc}:{}})}let r=[];for(let n of t.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript")){for(let s of n.imports)if(!(!s.toPath||s.isExternal||!s.symbols?.length))for(let o of s.symbols)e.has(`${s.toPath}::${o}`)&&r.push({fromFile:n.path,toType:o,toFile:s.toPath})}return{types:e,edges:r}}function Mt(t,e){let r=null;for(let o of t.types.values())if(o.name===e){r=o;break}if(!r)return{type:null,usedByFiles:[],uses:[]};let n=new Set,s=new Map;for(let o of t.edges)if(o.toType===e&&o.toFile===r.file&&n.add(o.fromFile),o.fromFile===r.file){let i=t.types.get(`${o.toFile}::${o.toType}`);i&&s.set(`${i.file}::${i.name}`,i)}return{type:r,usedByFiles:Array.from(n),uses:Array.from(s.values())}}import si from"path";import Dt from"fs";import Kr from"path";import ce from"fs";import P from"path";import $r from"fs";import Wl from"path";function Br(t){try{return $r.statSync(t,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function Re(t){try{return $r.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}function It(t,e){let r=P.join(e,"package.json");if(!ce.existsSync(r))return null;let n={};try{n=JSON.parse(ce.readFileSync(r,"utf-8"))}catch{return null}let s=n.name;return s?{name:s,root:e,relativeRoot:P.relative(t,e),entryPoints:Vo(e,n)}:null}function Vo(t,e){let r=[];if(e.exports){let s=e.exports;if(typeof s=="string")r.push(P.join(t,s));else if(typeof s=="object"&&s!==null){let o=s["."];if(typeof o=="string")r.push(P.join(t,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&r.push(P.join(t,i))}}}e.main&&r.push(P.join(t,e.main));for(let s of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])r.push(P.join(t,s));let n=r.filter(Re);return n.length>0?n.slice(0,1):r.slice(0,1)}function H(t,e){let r=[],n=new Set;for(let s of e){let o=s.replace(/\/$/,"").replace(/^\.\//,"");Ho(t,o,n,r)}return r}function Ho(t,e,r,n){if(!e.includes("*")){Qo(t,e,r,n);return}let s=e.split("/");s.includes("**")?qo(t,s,r,n):Yo(t,s,r,n)}function Qo(t,e,r,n){let s=P.join(t,e);if(r.has(s)||!Br(s))return;r.add(s);let o=It(t,s);o&&n.push(o)}function qo(t,e,r,n){let s=P.join(t,e[0]==="**"?"":e[0]??"");Ur(t,s,r,n)}function Yo(t,e,r,n){let s=e.findIndex(a=>a.includes("*")),o=P.join(t,...e.slice(0,s)),i;try{i=ce.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let c=P.join(o,a.name);if(r.has(c))continue;r.add(c);let p=It(t,c);p&&n.push(p)}}function Ur(t,e,r,n){let s;try{s=ce.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of s){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=P.join(e,o.name);if(ce.existsSync(P.join(i,"package.json"))&&!r.has(i)){r.add(i);let a=It(t,i);a&&n.push(a)}else Ur(t,i,r,n)}}var Jr={type:"npm",detect(t){let e=Kr.join(t,"package.json");if(!Dt.existsSync(e))return null;let r;try{r=JSON.parse(Dt.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r||Dt.existsSync(Kr.join(t,"yarn.lock")))return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:H(t,n)}};import Q from"fs";import E from"path";var Vr={type:"nx",detect(t){return Q.existsSync(E.join(t,"nx.json"))?Hr(t,t,new Set,0).map(r=>Xo(t,r,E.join(r,"project.json"))).filter(r=>r!==null):null}};function Hr(t,e,r,n){if(n>4)return[];let s;try{s=Q.readdirSync(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let i of s){if(!i.isDirectory())continue;let a=i.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let c=E.join(e,a);Q.existsSync(E.join(c,"project.json"))&&!r.has(c)?(r.add(c),o.push(c)):o.push(...Hr(t,c,r,n+1))}return o}function Xo(t,e,r){let n={};try{n=JSON.parse(Q.readFileSync(r,"utf-8"))}catch{return null}let s=n.name,o,i,a=E.join(e,"package.json");if(Q.existsSync(a))try{let c=JSON.parse(Q.readFileSync(a,"utf-8"));s=c.name??s,o=c.main,i=c.exports}catch{}return s?{name:s,root:e,relativeRoot:E.relative(t,e),entryPoints:Zo(e,n,o,i)}:null}function Zo(t,e,r,n){let s=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=E.resolve(t,"../..");s.push(E.resolve(a,o)),s.push(E.resolve(t,o))}if(n){let a=n;if(typeof a=="string")s.push(E.join(t,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&s.push(E.join(t,c))}}if(r&&s.push(E.join(t,r)),e.sourceRoot){let a=E.resolve(t,"../.."),c=E.resolve(a,e.sourceRoot);s.push(E.join(c,"index.ts"),E.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])s.push(E.join(t,a));let i=s.filter(Re);return i.length>0?i.slice(0,1):s.slice(0,1)}import Qr from"fs";import ei from"path";import{load as ti}from"js-yaml";var qr={type:"pnpm",detect(t){let e=ei.join(t,"pnpm-workspace.yaml");if(!Qr.existsSync(e))return null;let r=[];try{r=ti(Qr.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return H(t,r)}};import ri from"fs";import ni from"path";var Yr={type:"turborepo",detect(t){return ri.existsSync(ni.join(t,"turbo.json"))?[]:null}};import Rt from"fs";import Xr from"path";var Zr={type:"yarn",detect(t){if(!Rt.existsSync(Xr.join(t,"yarn.lock")))return null;let e=Xr.join(t,"package.json");if(!Rt.existsSync(e))return null;let r;try{r=JSON.parse(Rt.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r)return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:H(t,n)}};var en=[];function R(t){en.push(t)}function tn(){return en}R(Yr);R(Vr);R(qr);R(Zr);R(Jr);function pe(t,e=tn()){let r=si.resolve(t),n=new Map,s=[];for(let i of e){let a=i.detect(r);if(a!==null){s.push(i.type);for(let c of a)n.has(c.name)||n.set(c.name,c)}}if(s.length===0)return{root:r,type:"none",types:[],packages:[],packageMap:new Map};let o=Array.from(n.values());return{root:r,type:s[0],types:s,packages:o,packageMap:new Map(o.map(i=>[i.name,i]))}}var le=class t{constructor(e,r){this.monorepoRoot=e;this.type=r}monorepoRoot;type;packages=new Map;addPackage(e,r){this.packages.set(e.name,{graph:r,pkg:e})}getPackageForFile(e){for(let{pkg:r}of this.packages.values())if(e===r.relativeRoot||e.startsWith(`${r.relativeRoot}/`))return r}getPackageDependencies(){let e=new Map;for(let{graph:r,pkg:n}of this.packages.values()){let s=new Set;for(let o of r.nodes.values())for(let i of o.imports)i.isWorkspace&&i.workspacePackage&&s.add(i.workspacePackage);e.set(n.name,[...s])}return e}getAffectedAcrossPackages(e){let r=this.getPackageForFile(e);if(!r)return[];let n=this.packages.get(r.name);if(!n)return[];let s=[];n.graph.traverse(e,o=>(o.path!==e&&s.push({file:o.path,package:r.name}),!0),{direction:"incoming"});for(let{graph:o,pkg:i}of this.packages.values())if(i.name!==r.name)for(let a of o.nodes.values())a.imports.some(p=>p.isWorkspace&&p.workspacePackage===r.name)&&s.push({file:a.path,package:i.name});return s}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:r})=>({pkg:{name:r.name,relativeRoot:r.relativeRoot,entryPoints:r.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let r=new t(e.monorepoRoot,e.type);for(let{pkg:n,nodes:s}of e.packages){let o=new Map(s.map(a=>[a.path,a])),i=new D(o);r.packages.set(n.name,{graph:i,pkg:{...n,root:""}})}return r}};var rn=new Map;function q(t,e){rn.set(t,e)}function nn(t){return rn.get(t)}function sn(t,e){return e.startsWith("!")?t!==e.slice(1):t===e}function oi(t,e){return e.startsWith("!")?!t.includes(e.slice(1)):t.includes(e)}var ii=(t,e)=>!e.category||sn(t.category,e.category),ai=(t,e)=>!e.type||sn(t.type,e.type),ci=(t,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?t.lastAuthor!==e.lastAuthor.slice(1):t.lastAuthor!==void 0&&t.lastAuthor===e.lastAuthor:!0,pi=(t,e)=>!e.path||oi(t.path,e.path),li=(t,e)=>e.isExternal===void 0?!0:t.imports.some(n=>n.isExternal)===e.isExternal,ui=(t,e)=>{if(!e.tags||e.tags.length===0)return!0;let r=e.tags.filter(s=>!s.startsWith("!")),n=e.tags.filter(s=>s.startsWith("!")).map(s=>s.slice(1));return!(r.length>0&&!r.some(s=>t.tags.some(o=>o.name===s))||n.some(s=>t.tags.some(o=>o.name===s)))},fi=(t,e)=>!e.allTags?.length||e.allTags.every(r=>t.tags.some(n=>n.name===r)),mi=(t,e)=>!e.importsFile||t.imports.some(r=>r.toPath?.includes(e.importsFile)),gi=(t,e,r)=>e.importedBy===void 0?!0:(r?.get(t.path)??[]).some(s=>s.includes(e.importedBy)),di=(t,e)=>e.minImports===void 0||t.imports.length>=e.minImports,hi=(t,e)=>e.maxImports===void 0||t.imports.length<=e.maxImports,yi=(t,e)=>e.minSize===void 0||t.size>=e.minSize,xi=(t,e)=>e.maxSize===void 0||t.size<=e.maxSize,Si=(t,e)=>e.hasDocstring===void 0||!!t.description===e.hasDocstring,bi=(t,e)=>e.isDocumented===void 0||!!t.documentedBy?.length===e.isDocumented,vi=(t,e)=>e.isStale===void 0||!!t.staleFor?.length===e.isStale,ki=(t,e)=>e.minCoverage===void 0||(t.coveragePct??101)>=e.minCoverage,wi=(t,e)=>e.maxCoverage===void 0||(t.coveragePct??0)<=e.maxCoverage,Ci=(t,e)=>e.minExportUsage===void 0||(t.avgExportUsage??-1)>=e.minExportUsage,Fi=(t,e)=>e.maxExportUsage===void 0||(t.avgExportUsage??0)<=e.maxExportUsage,Ei=(t,e)=>e.minComplexity===void 0||(t.complexity??-1/0)>=e.minComplexity,Ti=(t,e)=>e.maxComplexity===void 0||(t.complexity??0)<=e.maxComplexity,Pi=(t,e)=>e.minCognitiveComplexity===void 0||(t.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,Ai=(t,e)=>e.maxCognitiveComplexity===void 0||(t.cognitiveComplexity??0)<=e.maxCognitiveComplexity,Ni=(t,e)=>e.minCommits===void 0||(t.commitCount90d??-1/0)>=e.minCommits,Mi=(t,e)=>e.maxCommits===void 0||(t.commitCount90d??0)<=e.maxCommits,Ii=(t,e,r)=>!e.any?.length||e.any.some(n=>ue(t,n,r)),Di=[ii,ai,ci,pi,li,ui,fi,mi,gi,di,hi,yi,xi,Si,bi,vi,ki,wi,Ci,Fi,Ei,Ti,Pi,Ai,Ni,Mi,Ii];function ue(t,e,r){return Di.every(n=>n(t,e,r))}function Ge(t,e){let r=new Map;if(e.importedBy!==void 0){for(let i of t.nodes)for(let a of i.imports)if(a.toPath){let c=r.get(a.toPath)??[];c.push(i.path),r.set(a.toPath,c)}}let n=t.nodes.filter(i=>ue(i,e,r)),s=new Set(n.map(i=>i.path)),o=n.map(i=>({...i,imports:i.imports.filter(a=>!a.toPath||s.has(a.toPath))}));if(e.sort){let i=e.sortDir==="asc"?-1:1;o.sort((a,c)=>{let 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:t.cycles?.filter(i=>i.every(a=>s.has(a)))??void 0}}function on(t,e){let r=e.indexOf(":");if(r===-1)return;let n=e.slice(0,r).trim().toLowerCase(),s=e.slice(r+1).trim();if(!(!n||!s))switch(n){case"category":t.category=s;break;case"type":t.type=s;break;case"tag":case"tags":s.includes("+")?t.allTags=[...t.allTags??[],...s.split("+")]:t.tags=[...t.tags??[],s];break;case"path":t.path=s;break;case"external":t.isExternal=s.toLowerCase()==="true";break;case"importsfile":t.importsFile=s;break;case"importedby":t.importedBy=s;break;case"minimports":t.minImports=parseInt(s,10);break;case"maximports":t.maxImports=parseInt(s,10);break;case"minsize":t.minSize=parseInt(s,10);break;case"maxsize":t.maxSize=parseInt(s,10);break;case"sort":t.sort=s;break;case"sortdir":t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";break;case"limit":t.limit=parseInt(s,10);break;case"hasdocstring":t.hasDocstring=s.toLowerCase()!=="false";break;case"mincoverage":t.minCoverage=parseInt(s,10);break;case"maxcoverage":t.maxCoverage=parseInt(s,10);break;case"minexportusage":t.minExportUsage=parseFloat(s);break;case"maxexportusage":t.maxExportUsage=parseFloat(s);break;case"mincomplexity":t.minComplexity=parseInt(s,10);break;case"maxcomplexity":t.maxComplexity=parseInt(s,10);break;case"mincognitivecomplexity":t.minCognitiveComplexity=parseInt(s,10);break;case"maxcognitivecomplexity":t.maxCognitiveComplexity=parseInt(s,10);break;case"mincommits":t.minCommits=parseInt(s,10);break;case"maxcommits":t.maxCommits=parseInt(s,10);break;case"isdocumented":t.isDocumented=s.toLowerCase()!=="false";break;case"isstale":t.isStale=s.toLowerCase()!=="false";break;case"lastauthor":t.lastAuthor=s;break}}function Ri(t){let e=[];for(let r of t.split("|")){let n=r.trim();if(!n)continue;let s={};on(s,n),Object.keys(s).length>0&&e.push(s)}return e}function Le(t){let e={},r=t.split(",");for(let n of r){let s=n.trim();if(s.toLowerCase().startsWith("any(")&&s.endsWith(")")){let o=s.slice(4,-1),i=Ri(o);i.length>0&&(e.any=[...e.any??[],...i]);continue}on(e,n)}return e}import gn from"fs/promises";import sa from"path";import Jt from"path";import Ke from"typescript";import _i from"path";import Gi from"path";import F from"typescript";var an=new Set(["describe","test","it"]);function $(t,e){let r=t[e];if(r===void 0)throw new Error(`Index ${e} out of bounds (length ${t.length})`);return r}function Gt(t){let e=[];for(let r of t.statements){if(!F.isExpressionStatement(r))continue;let n=r.expression;if(!F.isCallExpression(n))continue;let s=n.expression;F.isIdentifier(s)&&an.has(s.text)&&e.push(n),F.isPropertyAccessExpression(s)&&F.isIdentifier(s.expression)&&an.has(s.expression.text)&&e.push(n)}return e}function Lt(t,e,r){for(let n of t.arguments){if(!F.isObjectLiteralExpression(n))continue;let s=n.properties.find(o=>F.isPropertyAssignment(o)&&F.isIdentifier(o.name)&&o.name.text===e);if(!(!s||!F.isArrayLiteralExpression(s.initializer)))return s.initializer.elements.filter(F.isStringLiteral).map(o=>o.text)}return null}function _t(t,e,r,n){if(t.arguments.length===0)return null;for(let o=1;o<t.arguments.length;o++){let i=$(t.arguments,o);if(!F.isObjectLiteralExpression(i))continue;let a=i.properties.find(p=>F.isPropertyAssignment(p)&&F.isIdentifier(p.name)&&p.name.text===e);if(a)return{start:a.initializer.getStart(n),end:a.initializer.getEnd(),text:r};let c=i.getEnd()-1;return{start:c,end:c,text:`${i.properties.length>0?", ":""}${e}: ${r}`}}let s=$(t.arguments,t.arguments.length-1);return{start:s.getStart(n),end:s.getStart(n),text:`{ ${e}: ${r} }, `}}function Ot(t,e,r){let n=t.arguments;for(let s=1;s<n.length;s++){let o=$(n,s);if(!F.isObjectLiteralExpression(o))continue;let i=o.properties.findIndex(c=>F.isPropertyAssignment(c)&&F.isIdentifier(c.name)&&c.name.text===e);if(i<0)continue;if(o.properties.length===1)return{start:$(n,s-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 jt(t,e){let r=[...e].sort((s,o)=>o.start-s.start),n=t;for(let s of r)n=n.slice(0,s.start)+s.text+n.slice(s.end);return n}function Wt(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}var I=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function Li(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}function _e(t,e,r,n){let s=F.createSourceFile(Gi.basename(t),e,F.ScriptTarget.Latest,!0),o=Gt(s),[i]=o;if(!i)return e;let a=Lt(i,n,s),c=[...r].sort();if(a!==null&&JSON.stringify(Li(a).sort())===JSON.stringify(c))return e;let p=Wt(c.map(d=>`@${d}`)),l=o.flatMap(d=>{let f=r.length===0?Ot(d,n,s):_t(d,n,p,s);return f?[f]:[]});return l.length>0?jt(e,l):e}var Oe=class{name="cypress";canHandle(e){return I.has(_i.extname(e).toLowerCase())}apply(e,r,n){return _e(e,r,n,"tags")}};import Oi from"path";var zt=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,$t=/^@([a-zA-Z0-9_-]+)/gm;function ji(t){return`${["# <mokosh-tags>",...t.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
2
+ var st=(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 Ls from"path";import{fileURLToPath as _s}from"url";var Os=()=>_s(import.meta.url),js=()=>Ls.dirname(Os()),u=js();import{StdioServerTransport as el}from"@modelcontextprotocol/sdk/server/stdio.js";import{Server as Yc}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Xc,ListToolsRequestSchema as Zc}from"@modelcontextprotocol/sdk/types.js";import Hc from"fs";import ct from"fs";import br from"path";var Ws=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],dr=[];function Fe(t){dr.push(t)}function hr(t){return[...Ws,...dr].some(e=>typeof e=="string"?t.includes(e):e instanceof RegExp?e.test(t):e(t))}var zs=[".test.",".spec.","-test.","-spec."],yr=[];function Ee(t){yr.push(t)}function ne(){return[...zs,...yr]}var Bs=["jest","vitest","playwright","cypress","@testing-library/"],xr=[];function Te(t){xr.push(t)}function ot(){return[...Bs,...xr]}var Sr=.8;function it(t){Sr=t}function at(){return Sr}var $s=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function se(t,{allowJs:e=!0,isExplicitPath:r=!1}={}){if(r){let n=br.resolve(t);return ct.existsSync(n)?n.endsWith(".json")?kr(n):e?vr(n):{}:{}}for(let n of $s){let s=br.resolve(t,n);if(ct.existsSync(s)){if(n.endsWith(".json"))return kr(s);if(e)return vr(s)}}return{}}function kr(t){return JSON.parse(ct.readFileSync(t,"utf-8"))}function vr(t){let e=st(t);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function lt(t){for(let e of t.configMatchers??[])Fe(e);for(let e of t.testPatterns??[])Ee(e);for(let e of t.testLibraries??[])Te(e);t.barrelThreshold!==void 0&&it(t.barrelThreshold)}function H(t){return{gitStats:t?.gitStats??!1,parallelParsing:t?.parallelParsing,pathAliases:t?.pathAliases}}var j=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"],pt=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".feature",".md",".mdx"];import Us from"fs";import wr from"path";function ut(t,e){let r=wr.resolve(t,e);try{let n=Us.readFileSync(r,"utf-8"),s=JSON.parse(n),o=new Map;for(let[i,a]of Object.entries(s)){if(i==="total")continue;let c=a?.lines?.pct;if(typeof c!="number")continue;let l=wr.relative(t,i);o.set(l,c)}return o}catch{return new Map}}var Pe={serialize(t){let e=["graph TD"],r=new Set;for(let n of t.nodes.values()){let s=`"${n.path}"`;for(let o of n.imports){if(!o.toPath)continue;let i=`"${o.toPath}"`,a=`${n.path} -> ${o.toPath}`;if(!r.has(a)){let c=o.isStyle?"-- styles -->":"-->";e.push(` ${s} ${c} ${i}`),r.add(a)}}}return e.join(`
3
+ `)}};import Cr from"fs";import Js from"path";function ft(t,e){let r=t.replace(/^\.\//,"");if(e.nodes.has(r))return r;let n=r.replace(/^dist\//,"src/").replace(/\.(js|mjs|cjs)$/,".ts");return e.nodes.has(n)?n:null}function Fr(t,e){if(typeof t=="string")return ft(t,e);if(t&&typeof t=="object"){let r=t;for(let n of["import","require","default"]){let s=Fr(r[n],e);if(s)return s}}return null}function Vs(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 Hs(t,e){let r=new Set,n=new Set,s=[...e];for(;s.length;){let o=s.shift();if(n.has(o))continue;n.add(o);let i=t.nodes.get(o);if(i){for(let a of i.exports)r.add(a.name);for(let a of i.imports){if(a.type!=="re-export"||a.isExternal||!a.toPath)continue;if(!a.symbols?.length||a.symbols.includes("*")){let l=t.nodes.get(a.toPath);if(l)for(let p of l.exports)r.add(p.name);s.push(a.toPath)}else for(let l of a.symbols)r.add(l)}}}return r}function mt(t,e){let r=[],n=Js.join(e,"package.json");if(Cr.existsSync(n))try{let s=JSON.parse(Cr.readFileSync(n,"utf8"));if(s.exports&&typeof s.exports=="object"&&!Array.isArray(s.exports))for(let o of Object.values(s.exports)){let i=Fr(o,t);i&&!r.includes(i)&&r.push(i)}else if(typeof s.exports=="string"){let o=ft(s.exports,t);o&&r.push(o)}if(r.length===0)for(let o of[s.main,s.module].filter(Boolean)){let i=ft(o,t);i&&!r.includes(i)&&r.push(i)}}catch{}if(r.length===0){for(let s of["src/index.ts","src/index.js","index.ts","index.js"])if(t.nodes.has(s)){r.push(s);break}}return r}function Qs(t,e){let r=new Set(e);for(let n of e)t.traverse(n,s=>(r.add(s.path),!0),{direction:"outgoing"});return r}function qs(t,e,r){let n=new Map;for(let s of e){if(r.includes(s))continue;let o=t.nodes.get(s);if(!o)continue;let i=o.category==="barrel";for(let a of o.exports){let c=n.get(a.name),l=!!(a.signature||a.doc);(!c||l&&!i)&&n.set(a.name,{file:s,symbol:a})}}return n}function Ys(t,e,r,n){let s=[];for(let o of t){let i=e.get(o),a=n.flatMap(m=>r.nodes.get(m)?.exports??[]).find(m=>m.name===o),c=i?.symbol??a,l=i?.file??n.find(m=>r.nodes.get(m)?.exports.some(d=>d.name===o))??n[0],p={name:o,definedIn:l,kind:Vs(c?.signature)};c?.doc&&(p.doc=c.doc),c?.signature&&(p.signature=c.signature),s.push(p)}return s.sort((o,i)=>o.name.localeCompare(i.name)),s}function Xs(t,e,r){let n=c=>t.nodes.get(c)?.category==="test",s=[...e].filter(c=>!r.includes(c)&&!n(c)),o=[...t.nodes.keys()].filter(c=>!e.has(c)),i=o.filter(c=>!n(c)),a=o.filter(c=>n(c));return{internalFiles:s,unreachableFromEntry:i,testFiles:a}}function gt(t,e){if(e.length===0)throw new Error("buildApiSurface requires at least one entry point");for(let l of e)if(!t.nodes.has(l))throw new Error(`Entry point not found in graph: ${l}`);let r=Qs(t,e),n=qs(t,r,e),s=Hs(t,e),o=Ys(s,n,t,e),{internalFiles:i,unreachableFromEntry:a,testFiles:c}=Xs(t,r,e);return{entryPoints:e,publicExports:o,internalFiles:i,unreachableFromEntry:a,testFiles:c}}function dt(t,e){let r=null,n=[];for(let o of t.nodes.values()){o.exports.some(i=>i.name===e)&&(r=o.path);for(let i of o.callEdges??[])i.to===e&&n.push({file:o.path,callerFunction:i.from})}let s=[];if(r){let o=t.nodes.get(r);for(let i of o?.callEdges??[])i.from===e&&s.push({file:i.toFile,calleeFunction:i.to})}return{functionName:e,definedIn:r,callers:n,callees:s}}import Ml from"fs";import Rl from"path";function Er(t){let e=[...t.nodes.entries()].sort(([n],[s])=>n.localeCompare(s)).map(([n,s])=>`${n}:${s.mtime}:${s.size}`).join("|"),r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}function ht(t){let e=new Map;for(let r of t.nodes.keys()){let n=[];t.traverse(r,s=>(s.path!==r&&n.push(s.path),!0),{direction:"incoming"}),e.set(r,n)}return{impact:e,graphHash:Er(t)}}function yt(t,e){return t.impact.get(e)??[]}import{readFile as _o}from"fs/promises";import Re from"path";import Oo from"piscina";import Ae from"fs";import Zs from"path";import{load as Tr}from"js-yaml";var xt=["package-lock.json","yarn.lock","pnpm-lock.yaml"];function Pr(t){let e=t.lastIndexOf("@");return e>0?t.substring(0,e):t}function eo(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)),Pr(r)}).filter(Boolean)}function to(t,e){let r=t.startsWith("/")?t.slice(1):t,n=r.lastIndexOf("@");return n>0?{name:r.substring(0,n),version:e||r.substring(n+1)}:{name:r,version:e}}function ro(t){try{let e=Tr(t),r={dependencies:{}};for(let[n,s]of Object.entries(e))if(!(n==="__metadata"||!s?.version))for(let o of n.split(", ")){let i=Pr(o);i&&(r.dependencies[i]={version:s.version,...s.dependencies!==void 0&&{dependencies:s.dependencies}})}return r}catch{return null}}function no(t){let e={dependencies:{}};for(let r of t.split(/\n\n+/)){let n=r.split(`
4
+ `).filter(c=>c.trim().length>0&&!c.trim().startsWith("#"));if(n.length<2)continue;let s=n[0];if(!s||s.startsWith(" "))continue;let o=eo(s);if(o.length===0)continue;let a=n.find(c=>c.trim().startsWith('version "'))?.match(/version "(.*?)"/)?.[1]??"";for(let c of o)e.dependencies[c]={version:a}}return e}function so(t){let e=Ae.readFileSync(t,"utf-8"),r=JSON.parse(e),n={dependencies:{}};if(r.packages)for(let[s,o]of Object.entries(r.packages)){if(!s.startsWith("node_modules/"))continue;let i=s.replace("node_modules/","");i.includes("node_modules/")||(n.dependencies[i]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}else if(r.dependencies)for(let[s,o]of Object.entries(r.dependencies))n.dependencies[s]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}};return n}function oo(t){let e=Ae.readFileSync(t,"utf-8");if(e.includes("__metadata:")){let r=ro(e);if(r!==null)return r}return no(e)}function io(t){let e=Ae.readFileSync(t,"utf-8"),r={dependencies:{}};try{let n=Tr(e);if(n.packages)for(let[s,o]of Object.entries(n.packages)){let{name:i,version:a}=to(s,o.version);i&&(r.dependencies[i]={version:a,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}if(n.dependencies)for(let[s,o]of Object.entries(n.dependencies)){if(r.dependencies[s])continue;let i=typeof o=="string"?o:o.version;r.dependencies[s]={version:i||""}}}catch{}return r}function Ar(t){let e={"package-lock.json":so,"yarn.lock":oo,"pnpm-lock.yaml":io},r=xt.map(n=>[n,e[n]]);for(let[n,s]of r){let o=Zs.join(t,n);if(Ae.existsSync(o))return s(o)}return null}var ao=new Set(["css","scss","less","stylus"]);function Nr(t){return ao.has(t)?"style":"code"}function co(t){let e=5381;for(let r=0;r<t.length;r++)e=e*33+t.charCodeAt(r)>>>0;return e.toString(36)}function lo(t,e){let r=[];for(let n=0;n<=t.length-e;n++)r.push(co(t.slice(n,n+e).map(s=>s.text).join(" ")));return r}function po(t,e,r){let n=t.get(e.file),s=t.get(r.file);if(!n||!s)return 0;let o=0;for(;e.windowIndex+o+1<n.length&&r.windowIndex+o+1<s.length&&n[e.windowIndex+o+1]===s[r.windowIndex+o+1];)o++;return o}function uo(t,e,r){if(e.windowIndex===0||r.windowIndex===0)return!0;let n=t.get(e.file),s=t.get(r.file);return!n||!s?!0:n[e.windowIndex-1]!==s[r.windowIndex-1]}var St=class{parent=new Map;find(e){this.parent.has(e)||this.parent.set(e,e);let r=e;for(;this.parent.get(r)!==r;)r=this.parent.get(r);let n=e;for(;n!==r;){let s=this.parent.get(n);this.parent.set(n,r),n=s}return r}union(e,r){let n=this.find(e),s=this.find(r);n!==s&&this.parent.set(n,s)}root(e){return this.find(e)}};function Ne(t){return`${t.file}#${t.startLine}#${t.endLine}`}var fo=new Set(["{","}",":",",","[","]"]);function mo(t,e,r){let n=0;for(let s=e;s<e+r;s++)fo.has(t[s].text)&&n++;return n/r}var go=400;function Ir(t,e,r,n=.5,s=go){let o=new Map,i=new Map,a=new Map;for(let{file:S,tokens:y}of t){if(y.length<e)continue;i.set(S,y);let b=lo(y,e);o.set(S,b);for(let x=0;x<b.length;x++){let k={file:S,windowIndex:x},T=a.get(b[x]);T?T.push(k):a.set(b[x],[k])}}let c=[],l=0;for(let S of a.values())if(!(S.length<2)){if(S.length>s){l++;continue}for(let y=0;y<S.length;y++)for(let b=y+1;b<S.length;b++){let x=S[y],k=S[b];if(x.file===k.file&&x.windowIndex===k.windowIndex||!uo(o,x,k))continue;let T=po(o,x,k),N=e+T,V=i.get(x.file);if(mo(V,x.windowIndex,N)>n)continue;if(x.file===k.file){let[Rs,Gs]=x.windowIndex<k.windowIndex?[x,k]:[k,x];if(Rs.windowIndex+N>Gs.windowIndex)continue}let re=i.get(k.file),rt={file:x.file,startLine:V[x.windowIndex].line,endLine:V[x.windowIndex+N-1].line},nt={file:k.file,startLine:re[k.windowIndex].line,endLine:re[k.windowIndex+N-1].line},gr=Math.min(rt.endLine-rt.startLine+1,nt.endLine-nt.startLine+1);gr<r||c.push({occA:rt,occB:nt,lines:gr,tokens:N})}}let p=new St,m=new Map;for(let{occA:S,occB:y}of c){let b=Ne(S),x=Ne(y);m.set(b,S),m.set(x,y),p.union(b,x)}let d=new Map;for(let S of m.keys()){let y=p.root(S),b=d.get(y);b?b.add(S):d.set(y,new Set([S]))}let h=[];for(let S of d.values()){if(S.size<2)continue;let y=[...S].map(k=>m.get(k)),b=0,x=e;for(let k of c)!S.has(Ne(k.occA))||!S.has(Ne(k.occB))||k.lines>b&&(b=k.lines,x=k.tokens);h.push({occurrences:y,lines:b,tokens:x})}return{groups:h.sort((S,y)=>y.lines-S.lines),skippedBuckets:l}}import Dr from"postcss";import*as ho from"postcss-less";var yo=ho,Rr=new Set(["reference","inline"]);function Mr(t){return t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("data:")}function xo(t){let e=t.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function So(t,e){let r=t.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(r){let o=r[1]?.trim()??"",i=r[2]??"";if(!i)return null;let a=Rr.has(o)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a,...Mr(i)?{isExternal:!0}:{}}}let n=t.match(/^url\(['"]?([^'")]+)['"]?\)/),s=n?n[1]?.trim()??"":t.match(/^['"]([^'"]+)['"]/)?.[1]??"";return s?{fromPath:e,toPath:"",rawSpecifier:s,isStyle:!0,type:"static",...Mr(s)?{isExternal:!0}:{}}:null}function bo(t,e){let r=[],n=/url\(['"]?([^'")]+)['"]?\)/g,s=n.exec(t);for(;s!==null;){let o=s[1]?.trim()??"";xo(o)&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),s=n.exec(t)}return r}function Gr(t,e){let r=[];return t.walk(n=>{if(n.type==="atrule"&&n.name==="import"){let s=So(n.params,e);s&&r.push(s)}n.type==="decl"&&r.push(...bo(n.value,e))}),r}function ko(t){return t.replace(/(?<!:)\/\/.*/g,"")}function vo(t,e){let r=[],n=/@import\s+(?:\(([^)]+)\)\s+)?['"]([^'"]+)['"]/g,s=n.exec(t);for(;s!==null;){let o=s[1]?.trim()??"",i=s[2]??"";if(i){let a=Rr.has(o)?"side-effect":"static";r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a})}s=n.exec(t)}return r}function Ie(t,e){let r=Dr.parse(ko(t));return{imports:Gr(r,e),root:r}}function wo(t){let e=[],r=[];for(let n of t.nodes??[]){if(n.type!=="atrule")continue;let{value:s}=n;if(s===void 0)continue;let o=n.name;o&&(e.push({name:o}),r.push({name:o,kind:"variable"}))}return{exports:e,tags:r}}function Me(t,e){try{let r=yo.parse(t),{exports:n,tags:s}=wo(r);return{imports:Gr(r,e),root:r,exports:n,tags:s}}catch{return{imports:vo(t,e),root:Dr.parse(""),exports:[],tags:[]}}}import{parse as Co}from"postcss-scss";function Lr(t){return t.startsWith("_")||t.startsWith("-")}function Fo(t){return!!(t.startsWith("sass:")||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("_"))}function Eo(t){let e=t.match(/^['"]([^'"]+)['"]/);if(!e?.[1])return{specifier:""};let r=e[1],s=t.match(/\bas\s+(\S+)/)?.[1];return s!==void 0?{specifier:r,alias:s}:{specifier:r}}function To(t){let e=[],r=[];for(let n of t.nodes??[]){if(n.type==="decl"&&n.prop.startsWith("$")){let s=n.prop.slice(1);if(!s||Lr(s))continue;e.push({name:s}),r.push({name:s,kind:"variable"});continue}if(n.type==="atrule"&&(n.name==="mixin"||n.name==="function")){let o=n.params.match(/^([\w-]+)/)?.[1];if(!o||Lr(o))continue;let i=n.params.trim();e.push(i.includes("(")?{name:o,signature:i}:{name:o}),r.push({name:o,kind:"function"})}}return{exports:e,tags:r}}function De(t,e){let r=Co(t),n=[];r.walk(i=>{if(i.type!=="atrule")return;let{name:a,params:c}=i;if(a!=="import"&&a!=="use"&&a!=="forward")return;let{specifier:l,alias:p}=Eo(c);if(!l)return;let m={fromPath:e,toPath:"",rawSpecifier:l,isStyle:!0,type:a==="forward"?"re-export":"static",...Fo(l)?{isExternal:!0}:{}};p&&(m.symbols=[p]),n.push(m)});let{exports:s,tags:o}=To(r);return{imports:n,root:r,exports:s,tags:o}}function Po(t){return t.trim().replace(/\s+/g," ")}function Ao(t){try{return t.fileType==="scss"?De(t.source,t.file).root:t.fileType==="less"?Me(t.source,t.file).root:t.fileType==="css"?Ie(t.source,t.file).root:void 0}catch{return}}function No(t){let e=Ao(t);if(!e)return[];let r=[];return e.walkRules(n=>{let s=n.nodes?.filter(p=>p.type==="decl")??[];if(s.length===0)return;let o=s[0],i=s[s.length-1],a=n.source?.start?.line??o?.source?.start?.line,c=i?.source?.end?.line??i?.source?.start?.line??a;if(a===void 0||c===void 0)return;let l=s.map(p=>`${p.prop.trim().toLowerCase()}:${Po(p.value)}`).join(";");r.push({file:t.file,startLine:a,endLine:c,lines:c-a+1,signature:l,declCount:s.length})}),r}function _r(t,e,r=2){let n=new Map;for(let o of t)for(let i of No(o)){if(i.declCount<r||i.lines<e)continue;let a=n.get(i.signature);a?a.push(i):n.set(i.signature,[i])}let s=[];for(let o of n.values())for(let i=0;i<o.length;i++)for(let a=i+1;a<o.length;a++){let c=o[i],l=o[a];if(c.file===l.file&&c.startLine===l.startLine&&c.endLine===l.endLine)continue;let p={file:c.file,startLine:c.startLine,endLine:c.endLine},m={file:l.file,startLine:l.startLine,endLine:l.endLine};s.push({occurrences:[p,m],lines:Math.min(c.lines,l.lines),tokens:c.declCount,family:"style"})}return s.sort((o,i)=>i.lines-o.lines)}var Io={typescript:{line:["//"],block:[["/*","*/"]]},javascript:{line:["//"],block:[["/*","*/"]]},go:{line:["//"],block:[["/*","*/"]]},css:{block:[["/*","*/"]]},scss:{line:["//"],block:[["/*","*/"]]},less:{line:["//"],block:[["/*","*/"]]},stylus:{line:["//"],block:[["/*","*/"]]},python:{line:["#"]},gherkin:{line:["#"]},coffeescript:{line:["#"],block:[["###","###"]]},livescript:{line:["#"],block:[["###","###"]]},lua:{line:["--"],block:[["--[[","]]"]]},markdown:{block:[["<!--","-->"]]}};function Or(t,e,r){let n=t.slice(e,r).replace(/[^\n]/g," ");return t.slice(0,e)+n+t.slice(r)}function Mo(t,e){if(!e)return t;let r=t;for(let[n,s]of e.block??[]){let o=0;for(;;){let i=r.indexOf(n,o);if(i===-1)break;let a=r.indexOf(s,i+n.length),c=a===-1?r.length:a+s.length;r=Or(r,i,c),o=c}}for(let n of e.line??[]){let s=0;for(;;){let o=r.indexOf(n,s);if(o===-1)break;let i=r.indexOf(`
5
+ `,o),a=i===-1?r.length:i;r=Or(r,o,a),s=a}}return r}var Do=["===","!==","...","=>","==","!=","<=",">=","&&","||","::","->","..","+=","-=","*=","/="],bt=new RegExp(`${Do.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")}|[A-Za-z_$][A-Za-z0-9_$]*|\\d+(?:\\.\\d+)?|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|\\S`,"g"),Ro=/^[A-Za-z_$][A-Za-z0-9_$]*$/,jr=/^\d+(?:\.\d+)?$/,Go=/^(".*"|'.*'|`.*`)$/s,Lo=new Set(["if","else","elif","for","while","do","switch","case","default","break","continue","return","function","def","class","struct","interface","const","let","var","local","import","export","from","package","try","catch","except","finally","throw","raise","new","this","self","end","then","yield","async","await","nil","null","None","true","false","True","False","and","or","not","in","of","is"]);function Wr(t,e,r=!0){let n=Mo(t,Io[e]),s=[],o=1,i=0;bt.lastIndex=0;let a=bt.exec(n);for(;a!==null;){for(let p=i;p<a.index;p++)n[p]===`
6
+ `&&o++;i=a.index;let c=a[0],l=c;Ro.test(c)&&!Lo.has(c)?l="ID":r&&(jr.test(c)||Go.test(c))&&(l=jr.test(c)?"NUM":"STR"),s.push({text:l,line:o});for(let p=i;p<a.index+c.length;p++)n[p]===`
7
+ `&&o++;i=a.index+c.length,a=bt.exec(n)}return s}var jo=20,Wo=new Set(["css","scss","less"]);function zo(t){return xt.includes(Re.basename(t))}function Bo(t,e){if(e.length===0)return!1;let r=new Set(e);return t.split(Re.sep).some(n=>r.has(n))}async function kt(t,e,r={}){let{minLines:n=6,windowSize:s=15,ignoreLiterals:o=!0,maxPunctuationRatio:i=.5,maxBucketSize:a,limit:c=50,ignoreDirs:l=j,parallelTokenizing:p=!0}=r,m=[...t.nodes.values()].filter(h=>!zo(h.path)&&!Bo(h.path,l)),d=$o(p,m.length);try{let h=[],S=new Map;await Promise.all(m.map(async x=>{let k;try{k=await _o(Re.join(e,x.path),"utf8")}catch{return}if(Wo.has(x.type)){h.push({file:x.path,source:k,fileType:x.type});return}let T=Nr(x.type),N=d?await d.run({source:k,fileType:x.type,ignoreLiterals:o}):Wr(k,x.type,o),V={file:x.path,tokens:N},re=S.get(T);re?re.push(V):S.set(T,[V])}));let y=_r(h,n),b=0;for(let[x,k]of S){let T=Ir(k,s,n,i,a);b+=T.skippedBuckets;for(let N of T.groups)y.push({...N,family:x})}return{groups:y.sort((x,k)=>k.lines-x.lines).slice(0,c),skippedBuckets:b}}finally{d&&await d.destroy()}}function $o(t,e){if(t===!1)return null;let r=typeof t=="object"?t:{},n=r.minFiles??jo;if(e<n)return null;try{return new Oo({filename:Re.join(u,"duplication-worker.js"),...r.maxThreads!==void 0?{maxThreads:r.maxThreads}:{}})}catch(s){return process.stderr.write(`
8
+ Warning: failed to start duplicate-detection worker pool, falling back to synchronous tokenizing: ${s}
9
+ `),null}}import Ge from"path";function Uo(t){let e=new Map;for(let[r,n]of t){let s=n.imports.filter(o=>o.toPath&&!o.isExternal).length;s>0&&e.set(r,s)}return e}function Ko(t,e,r){let n=new Map;for(let[s,o]of e){if(o<r)continue;let i=t.get(s);if(!i||i.category==="test"||i.category==="barrel")continue;let a=Ge.extname(s),c=Ge.basename(s,a),l=c==="index"?Ge.basename(Ge.dirname(s)):c;n.set(s,{path:s,outDegree:o,tag:`feature:${l}`})}return n}function W(t,e){let r=e?.minOutDegree??5;return Ko(t,Uo(t),r)}var Jo=(t,e)=>t.outDegree-e.outDegree;function Vo(t,e){let r=new Map;for(let n of e.values()){let s=new Set;t.traverse(n.path,o=>(o.path!==n.path&&s.add(o.path),!0),{direction:"outgoing"}),r.set(n.path,s)}return r}function Ho(t,e,r,n){let s=new Map;for(let[o]of t){if(e.has(o))continue;let i=null;for(let a of e.values())r.get(a.path)?.has(o)&&(!i||n(a,i)<0)&&(i=a);i&&s.set(o,i.path)}return s}function Qo(t,e){let r=new Map;for(let n of t.values()){let s=n.tag.replace("feature:",""),o=[];for(let[i,a]of e)a===n.path&&o.push(i);r.set(s,{hub:n.path,outDegree:n.outDegree,files:o})}return r}function qo(t,e,r){let n=[];for(let s of t.keys())!e.has(s)&&!r.has(s)&&n.push(s);return n}function oe(t,e){let r=e?.detectFn??W,n=e?.hubComparator??Jo,s=r(t.nodes,e),o=Vo(t,s),i=Ho(t.nodes,s,o,n);return{features:Qo(s,i),unassigned:qo(t.nodes,s,i)}}var zr=new Set(["typescript","javascript","python","go","scss","less","lua","coffeescript"]),Br=new Set(["typescript","javascript","python"]),Le=new Set(["typescript","javascript","go","python"]);function vt(t){let e=new Map;for(let r of t.nodes.values())e.set(r.type,(e.get(r.type)??0)+1);return[...e.entries()].map(([r,n])=>({type:r,fileCount:n,exportsTracked:zr.has(r),importSymbolsTracked:Br.has(r),callEdgesTracked:Le.has(r)})).sort((r,n)=>n.fileCount-r.fileCount)}var ie=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let r=new Set(this.nodes.keys());return e.filter(n=>!r.has(n))}findHighExportUsage(e){let r=[];for(let n of this.nodes.values()){if(n.maxExportUsage===void 0||n.maxExportUsage<e)continue;let s=n.imports.reduce((o,i)=>(i.exportUsageRatio??0)>(o?.exportUsageRatio??0)?i:o,null);r.push({path:n.path,maxExportUsage:n.maxExportUsage,tightestDep:s?.toPath??""})}return r.sort((n,s)=>s.maxExportUsage-n.maxExportUsage)}findCycles(){let e=[],r=new Set,n=new Set,s=[],o=i=>{r.add(i),n.add(i),s.push(i);let a=this.nodes.get(i);if(a){for(let c of a.imports)if(!(!c.toPath||c.isExternal))if(n.has(c.toPath)){let l=s.indexOf(c.toPath);e.push([...s.slice(l),c.toPath])}else r.has(c.toPath)||o(c.toPath)}n.delete(i),s.pop()};for(let i of this.nodes.keys())r.has(i)||o(i);return e}};var R=class t{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let r=new Map;for(let n of e.nodes)r.set(n.path,n);return new t(r)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let r of this.nodes.values())for(let n of r.imports)if(n.toPath){let s=e.get(n.toPath)||[];s.push(r.path),e.set(n.toPath,s)}return this._incomingEdgesCache=e,e}dfs(e,r,n,s){let o=new Set,i=n.maxDepth??1/0,a=(c,l,p)=>{if(l>i||o.has(c))return;let m=this.nodes.get(c);if(m&&(o.add(c),r(m,l,p)!==!1))for(let d of s(c))a(d,l+1,c)};a(e,0,null)}traverse(e,r,n={}){let s=n.direction??"outgoing",o=s==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,r,n,i=>s==="outgoing"?this.nodes.get(i)?.imports.map(a=>a.toPath).filter(Boolean)??[]:o?.get(i)??[])}getCallIncomingCache(){if(this._callIncomingCache)return this._callIncomingCache;let e=new Map;for(let r of this.nodes.values())for(let n of r.callEdges??[]){let s=e.get(n.toFile)??[];s.push(r.path),e.set(n.toFile,s)}return this._callIncomingCache=e,e}traverseCalls(e,r,n={}){let s=n.direction??"outgoing",o=s==="incoming"?this.getCallIncomingCache():null;this.dfs(e,r,n,i=>s==="outgoing"?this.nodes.get(i)?.callEdges?.map(a=>a.toFile)??[]:o?.get(i)??[])}getCallers(e){let r=[];return this.traverseCalls(e,n=>(n.path!==e&&r.push(n.path),!0),{direction:"incoming",maxDepth:1}),r}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let r=this.nodes.get(e);return r?r.imports.map(n=>this.nodes.get(n.toPath)).filter(n=>n!==void 0):[]}findUnusedFiles(e){return new ie(this.nodes).findUnusedFiles(e)}findCycles(){return new ie(this.nodes).findCycles()}};var z=class{affectedSymbols=new Map;constructor(e,r){this.affectedSymbols.set(e,new Set(["default",...r]))}updateAffectedSymbols(e,r){let n=this.affectedSymbols.get(r)||new Set,s=e.imports.find(c=>c.toPath===r);if(!s)return!1;let o=s.symbols||["*"],i=new Set;for(let c of o)(c==="*"||n.has("*")||n.has(c))&&i.add("*");if(i.size===0)return!1;let a=this.affectedSymbols.get(e.path)||new Set;for(let c of i)a.add(c);return this.affectedSymbols.set(e.path,a),!0}};function ae(t,e){let r=t.nodes.get(e);if(r)return{category:r.category,exports:r.exports.map(n=>n.name)}}function wt(t,e,r=1){let n=[];return t.traverse(e,(s,o,i)=>{if(s.path===e)return!0;let a=i?t.nodes.get(i)?.imports.find(c=>c.toPath===s.path):void 0;return n.push({path:s.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"outgoing",maxDepth:r}),n}function ce(t,e){let r=[];return t.traverse(e,n=>{if(n.path===e)return!0;let s=n.imports.find(o=>o.toPath===e);return r.push({path:n.path,...s?.symbols?{symbols:s.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),r}function Ct(t,e,r={}){let{testsOnly:n=!1,changedSymbols:s}=r,o=s?new z(e,s):null,i=[];return t.traverse(e,(a,c,l)=>{if(a.path===e)return!0;if(o&&l&&!o.updateAffectedSymbols(a,l))return!1;let p=a.category==="test"||a.tags.some(m=>m.name==="test");return(!n||p)&&i.push(a.path),!0},{direction:"incoming"}),i}function Ft(t,e,r={}){let{depth:n=1,withEdgeDetail:s=!1}=r,o=[];return t.traverseCalls(e,i=>{if(i.path===e)return!0;let a={file:i.path};return s&&(a.edges=(i.callEdges??[]).filter(c=>c.toFile===e).map(c=>({from:c.from,to:c.to}))),o.push(a),!0},{direction:"incoming",maxDepth:n}),o}function Et(t,e={}){let{metric:r="cognitiveComplexity",threshold:n=10,limit:s=20}=e;return[...t.nodes.values()].flatMap(o=>(o.functions??[]).filter(i=>i[r]>=n).map(i=>({file:o.path,name:i.name,line:i.line,complexity:i.complexity,cognitiveComplexity:i.cognitiveComplexity}))).sort((o,i)=>i[r]-o[r]).slice(0,s)}function Tt(t){return{nodes:t.nodes.map(r=>({path:r.path,type:r.type,category:r.category,exports:r.exports.map(n=>n.name),tags:r.tags.filter(n=>n.kind==="comment-marker"||n.kind==="import").map(n=>n.name),importsFiles:r.imports.filter(n=>!n.isExternal&&n.toPath).map(n=>n.toPath),...r.description!==void 0&&{description:r.description},...r.testedBy!==void 0&&{testedBy:r.testedBy},...r.coveragePct!==void 0&&{coveragePct:r.coveragePct},...r.avgExportUsage!==void 0&&{avgExportUsage:r.avgExportUsage},...r.maxExportUsage!==void 0&&{maxExportUsage:r.maxExportUsage}})),cycles:t.cycles}}function Pt(t){let e=t.getPackageDependencies(),r=Array.from(t.packages.values()).map(({graph:n,pkg:s})=>({name:s.name,relativeRoot:s.relativeRoot,nodeCount:n.nodes.size,dependsOn:e.get(s.name)??[]}));return{monorepoType:t.type,packageCount:r.length,packages:r}}function At(t){return[...t.nodes.values()].some(e=>e.coveragePct!==void 0)}function $r(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 C(e,"component")||C(e,"components")?"component":C(e,"controller")||C(e,"controllers")?"controller":C(e,"middleware")?"middleware":C(e,"router")||C(e,"routes")||C(e,"route")?"router":C(e,"store")||C(e,"stores")?"store":C(e,"service")||C(e,"services")?"service":C(e,"handler")||C(e,"handlers")?"handler":C(e,"adapter")||C(e,"adapters")?"adapter":C(e,"plugin")||C(e,"plugins")?"plugin":C(e,"api")?"api":C(e,"cli")||C(e,"commands")||le(e)==="cli"?"cli":C(e,"util")||C(e,"utils")||C(e,"helper")||C(e,"helpers")?"util":C(e,"model")||C(e,"models")||le(e)==="model"?"model":C(e,"parser")||C(e,"parsers")||le(e)==="parser"?"parser":le(e)==="builder"?"builder":le(e)==="resolver"?"resolver":"other"}function C(t,e){return t.includes(`/${e}/`)||t.includes(`/${e}.`)}function le(t){let e=t.slice(t.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function Nt(t,e){let r=oe(t,e),n=new Map;for(let[o,i]of r.features){for(let a of i.files)n.set(a,o);n.set(i.hub,o)}let s=new Map;for(let o of t.nodes.values()){let i=n.get(o.path);s.set(o.path,{path:o.path,role:$r(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return s}function It(t,e){let r=[];for(let n of t.nodes.values())if(n.exports.some(s=>s.name===e))if(Le.has(n.type)){let s=[];for(let o of t.nodes.values())for(let i of o.callEdges??[])i.to===e&&s.push({file:o.path,callerFunction:i.from});r.push({path:n.path,category:n.category,precision:"call",callers:s})}else{let s=ce(t,n.path).map(o=>({file:o.path,...o.symbols?{symbols:o.symbols}:{}}));r.push({path:n.path,category:n.category,precision:"file-level",importers:s})}return r}function Yo(t){return t?t.startsWith("interface ")?"interface":t.startsWith("class ")?"class":t.startsWith("enum ")?"enum":"type":"type"}function Xo(t,e){if(e==="type-only")return!0;let r=t.signature??"";return r.startsWith("interface ")||r.startsWith("class ")||r.startsWith("enum ")}function Mt(t){let e=new Map;for(let n of t.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript"))for(let s of n.exports){if(!Xo(s,n.category))continue;let o=`${n.path}::${s.name}`;e.set(o,{name:s.name,file:n.path,kind:Yo(s.signature),...s.doc?{doc:s.doc}:{}})}let r=[];for(let n of t.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript")){for(let s of n.imports)if(!(!s.toPath||s.isExternal||!s.symbols?.length))for(let o of s.symbols)e.has(`${s.toPath}::${o}`)&&r.push({fromFile:n.path,toType:o,toFile:s.toPath})}return{types:e,edges:r}}function 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 n=new Set,s=new Map;for(let o of t.edges)if(o.toType===e&&o.toFile===r.file&&n.add(o.fromFile),o.fromFile===r.file){let i=t.types.get(`${o.toFile}::${o.toType}`);i&&s.set(`${i.file}::${i.name}`,i)}return{type:r,usedByFiles:Array.from(n),uses:Array.from(s.values())}}import pi from"path";import Gt from"fs";import Vr from"path";import pe from"fs";import I from"path";import Ur from"fs";import Vp from"path";function Kr(t){try{return Ur.statSync(t,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function _e(t){try{return Ur.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}function Rt(t,e){let r=I.join(e,"package.json");if(!pe.existsSync(r))return null;let n={};try{n=JSON.parse(pe.readFileSync(r,"utf-8"))}catch{return null}let s=n.name;return s?{name:s,root:e,relativeRoot:I.relative(t,e),entryPoints:Zo(e,n)}:null}function Zo(t,e){let r=[];if(e.exports){let s=e.exports;if(typeof s=="string")r.push(I.join(t,s));else if(typeof s=="object"&&s!==null){let o=s["."];if(typeof o=="string")r.push(I.join(t,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&r.push(I.join(t,i))}}}e.main&&r.push(I.join(t,e.main));for(let s of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])r.push(I.join(t,s));let n=r.filter(_e);return n.length>0?n.slice(0,1):r.slice(0,1)}function Q(t,e){let r=[],n=new Set;for(let s of e){let o=s.replace(/\/$/,"").replace(/^\.\//,"");ei(t,o,n,r)}return r}function ei(t,e,r,n){if(!e.includes("*")){ti(t,e,r,n);return}let s=e.split("/");s.includes("**")?ri(t,s,r,n):ni(t,s,r,n)}function ti(t,e,r,n){let s=I.join(t,e);if(r.has(s)||!Kr(s))return;r.add(s);let o=Rt(t,s);o&&n.push(o)}function ri(t,e,r,n){let s=I.join(t,e[0]==="**"?"":e[0]??"");Jr(t,s,r,n)}function ni(t,e,r,n){let s=e.findIndex(a=>a.includes("*")),o=I.join(t,...e.slice(0,s)),i;try{i=pe.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let c=I.join(o,a.name);if(r.has(c))continue;r.add(c);let l=Rt(t,c);l&&n.push(l)}}function Jr(t,e,r,n){let s;try{s=pe.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of s){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=I.join(e,o.name);if(pe.existsSync(I.join(i,"package.json"))&&!r.has(i)){r.add(i);let a=Rt(t,i);a&&n.push(a)}else Jr(t,i,r,n)}}var Hr={type:"npm",detect(t){let e=Vr.join(t,"package.json");if(!Gt.existsSync(e))return null;let r;try{r=JSON.parse(Gt.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r||Gt.existsSync(Vr.join(t,"yarn.lock")))return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:Q(t,n)}};import q from"fs";import P from"path";var Qr={type:"nx",detect(t){return q.existsSync(P.join(t,"nx.json"))?qr(t,t,new Set,0).map(r=>si(t,r,P.join(r,"project.json"))).filter(r=>r!==null):null}};function qr(t,e,r,n){if(n>4)return[];let s;try{s=q.readdirSync(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let i of s){if(!i.isDirectory())continue;let a=i.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let c=P.join(e,a);q.existsSync(P.join(c,"project.json"))&&!r.has(c)?(r.add(c),o.push(c)):o.push(...qr(t,c,r,n+1))}return o}function si(t,e,r){let n={};try{n=JSON.parse(q.readFileSync(r,"utf-8"))}catch{return null}let s=n.name,o,i,a=P.join(e,"package.json");if(q.existsSync(a))try{let c=JSON.parse(q.readFileSync(a,"utf-8"));s=c.name??s,o=c.main,i=c.exports}catch{}return s?{name:s,root:e,relativeRoot:P.relative(t,e),entryPoints:oi(e,n,o,i)}:null}function oi(t,e,r,n){let s=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=P.resolve(t,"../..");s.push(P.resolve(a,o)),s.push(P.resolve(t,o))}if(n){let a=n;if(typeof a=="string")s.push(P.join(t,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&s.push(P.join(t,c))}}if(r&&s.push(P.join(t,r)),e.sourceRoot){let a=P.resolve(t,"../.."),c=P.resolve(a,e.sourceRoot);s.push(P.join(c,"index.ts"),P.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])s.push(P.join(t,a));let i=s.filter(_e);return i.length>0?i.slice(0,1):s.slice(0,1)}import Yr from"fs";import ii from"path";import{load as ai}from"js-yaml";var Xr={type:"pnpm",detect(t){let e=ii.join(t,"pnpm-workspace.yaml");if(!Yr.existsSync(e))return null;let r=[];try{r=ai(Yr.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return Q(t,r)}};import ci from"fs";import li from"path";var Zr={type:"turborepo",detect(t){return ci.existsSync(li.join(t,"turbo.json"))?[]:null}};import Lt from"fs";import en from"path";var tn={type:"yarn",detect(t){if(!Lt.existsSync(en.join(t,"yarn.lock")))return null;let e=en.join(t,"package.json");if(!Lt.existsSync(e))return null;let r;try{r=JSON.parse(Lt.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r)return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:Q(t,n)}};var rn=[];function G(t){rn.push(t)}function nn(){return rn}G(Zr);G(Qr);G(Xr);G(tn);G(Hr);function ue(t,e=nn()){let r=pi.resolve(t),n=new Map,s=[];for(let i of e){let a=i.detect(r);if(a!==null){s.push(i.type);for(let c of a)n.has(c.name)||n.set(c.name,c)}}if(s.length===0)return{root:r,type:"none",types:[],packages:[],packageMap:new Map};let o=Array.from(n.values());return{root:r,type:s[0],types:s,packages:o,packageMap:new Map(o.map(i=>[i.name,i]))}}var fe=class t{constructor(e,r){this.monorepoRoot=e;this.type=r}monorepoRoot;type;packages=new Map;addPackage(e,r){this.packages.set(e.name,{graph:r,pkg:e})}getPackageForFile(e){for(let{pkg:r}of this.packages.values())if(e===r.relativeRoot||e.startsWith(`${r.relativeRoot}/`))return r}getPackageDependencies(){let e=new Map;for(let{graph:r,pkg:n}of this.packages.values()){let s=new Set;for(let o of r.nodes.values())for(let i of o.imports)i.isWorkspace&&i.workspacePackage&&s.add(i.workspacePackage);e.set(n.name,[...s])}return e}getAffectedAcrossPackages(e){let r=this.getPackageForFile(e);if(!r)return[];let n=this.packages.get(r.name);if(!n)return[];let s=[];n.graph.traverse(e,o=>(o.path!==e&&s.push({file:o.path,package:r.name}),!0),{direction:"incoming"});for(let{graph:o,pkg:i}of this.packages.values())if(i.name!==r.name)for(let a of o.nodes.values())a.imports.some(l=>l.isWorkspace&&l.workspacePackage===r.name)&&s.push({file:a.path,package:i.name});return s}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:r})=>({pkg:{name:r.name,relativeRoot:r.relativeRoot,entryPoints:r.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let r=new t(e.monorepoRoot,e.type);for(let{pkg:n,nodes:s}of e.packages){let o=new Map(s.map(a=>[a.path,a])),i=new R(o);r.packages.set(n.name,{graph:i,pkg:{...n,root:""}})}return r}};var sn=new Map;function Y(t,e){sn.set(t,e)}function on(t){return sn.get(t)}function an(t,e){return e.startsWith("!")?t!==e.slice(1):t===e}function ui(t,e){return e.startsWith("!")?!t.includes(e.slice(1)):t.includes(e)}var fi=(t,e)=>!e.category||an(t.category,e.category),mi=(t,e)=>!e.type||an(t.type,e.type),gi=(t,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?t.lastAuthor!==e.lastAuthor.slice(1):t.lastAuthor!==void 0&&t.lastAuthor===e.lastAuthor:!0,di=(t,e)=>!e.path||ui(t.path,e.path),hi=(t,e)=>e.isExternal===void 0?!0:t.imports.some(n=>n.isExternal)===e.isExternal,yi=(t,e)=>{if(!e.tags||e.tags.length===0)return!0;let r=e.tags.filter(s=>!s.startsWith("!")),n=e.tags.filter(s=>s.startsWith("!")).map(s=>s.slice(1));return!(r.length>0&&!r.some(s=>t.tags.some(o=>o.name===s))||n.some(s=>t.tags.some(o=>o.name===s)))},xi=(t,e)=>!e.allTags?.length||e.allTags.every(r=>t.tags.some(n=>n.name===r)),Si=(t,e)=>!e.importsFile||t.imports.some(r=>r.toPath?.includes(e.importsFile)),bi=(t,e,r)=>e.importedBy===void 0?!0:(r?.get(t.path)??[]).some(s=>s.includes(e.importedBy)),ki=(t,e)=>e.minImports===void 0||t.imports.length>=e.minImports,vi=(t,e)=>e.maxImports===void 0||t.imports.length<=e.maxImports,wi=(t,e)=>e.minSize===void 0||t.size>=e.minSize,Ci=(t,e)=>e.maxSize===void 0||t.size<=e.maxSize,Fi=(t,e)=>e.hasDocstring===void 0||!!t.description===e.hasDocstring,Ei=(t,e)=>e.isDocumented===void 0||!!t.documentedBy?.length===e.isDocumented,Ti=(t,e)=>e.isStale===void 0||!!t.staleFor?.length===e.isStale,Pi=(t,e)=>e.minCoverage===void 0||(t.coveragePct??101)>=e.minCoverage,Ai=(t,e)=>e.maxCoverage===void 0||(t.coveragePct??0)<=e.maxCoverage,Ni=(t,e)=>e.minExportUsage===void 0||(t.avgExportUsage??-1)>=e.minExportUsage,Ii=(t,e)=>e.maxExportUsage===void 0||(t.avgExportUsage??0)<=e.maxExportUsage,Mi=(t,e)=>e.minComplexity===void 0||(t.complexity??-1/0)>=e.minComplexity,Di=(t,e)=>e.maxComplexity===void 0||(t.complexity??0)<=e.maxComplexity,Ri=(t,e)=>e.minCognitiveComplexity===void 0||(t.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,Gi=(t,e)=>e.maxCognitiveComplexity===void 0||(t.cognitiveComplexity??0)<=e.maxCognitiveComplexity,Li=(t,e)=>e.minCommits===void 0||(t.commitCount90d??-1/0)>=e.minCommits,_i=(t,e)=>e.maxCommits===void 0||(t.commitCount90d??0)<=e.maxCommits,Oi=(t,e,r)=>!e.any?.length||e.any.some(n=>me(t,n,r)),ji=[fi,mi,gi,di,hi,yi,xi,Si,bi,ki,vi,wi,Ci,Fi,Ei,Ti,Pi,Ai,Ni,Ii,Mi,Di,Ri,Gi,Li,_i,Oi];function me(t,e,r){return ji.every(n=>n(t,e,r))}function Oe(t,e){let r=new Map;if(e.importedBy!==void 0){for(let i of t.nodes)for(let a of i.imports)if(a.toPath){let c=r.get(a.toPath)??[];c.push(i.path),r.set(a.toPath,c)}}let n=t.nodes.filter(i=>me(i,e,r)),s=new Set(n.map(i=>i.path)),o=n.map(i=>({...i,imports:i.imports.filter(a=>!a.toPath||s.has(a.toPath))}));if(e.sort){let i=e.sortDir==="asc"?-1:1;o.sort((a,c)=>{let l=0;return e.sort==="size"?l=c.size-a.size:e.sort==="imports"?l=c.imports.length-a.imports.length:e.sort==="commitCount90d"?l=(c.commitCount90d??0)-(a.commitCount90d??0):e.sort==="exportUsage"?l=(c.avgExportUsage??0)-(a.avgExportUsage??0):e.sort==="complexity"?l=(c.complexity??0)-(a.complexity??0):e.sort==="cognitiveComplexity"&&(l=(c.cognitiveComplexity??0)-(a.cognitiveComplexity??0)),l*i})}return e.limit!==void 0&&o.splice(e.limit),{nodes:o,cycles:t.cycles?.filter(i=>i.every(a=>s.has(a)))??void 0}}function cn(t,e){let r=e.indexOf(":");if(r===-1)return;let n=e.slice(0,r).trim().toLowerCase(),s=e.slice(r+1).trim();if(!(!n||!s))switch(n){case"category":t.category=s;break;case"type":t.type=s;break;case"tag":case"tags":s.includes("+")?t.allTags=[...t.allTags??[],...s.split("+")]:t.tags=[...t.tags??[],s];break;case"path":t.path=s;break;case"external":t.isExternal=s.toLowerCase()==="true";break;case"importsfile":t.importsFile=s;break;case"importedby":t.importedBy=s;break;case"minimports":t.minImports=parseInt(s,10);break;case"maximports":t.maxImports=parseInt(s,10);break;case"minsize":t.minSize=parseInt(s,10);break;case"maxsize":t.maxSize=parseInt(s,10);break;case"sort":t.sort=s;break;case"sortdir":t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";break;case"limit":t.limit=parseInt(s,10);break;case"hasdocstring":t.hasDocstring=s.toLowerCase()!=="false";break;case"mincoverage":t.minCoverage=parseInt(s,10);break;case"maxcoverage":t.maxCoverage=parseInt(s,10);break;case"minexportusage":t.minExportUsage=parseFloat(s);break;case"maxexportusage":t.maxExportUsage=parseFloat(s);break;case"mincomplexity":t.minComplexity=parseInt(s,10);break;case"maxcomplexity":t.maxComplexity=parseInt(s,10);break;case"mincognitivecomplexity":t.minCognitiveComplexity=parseInt(s,10);break;case"maxcognitivecomplexity":t.maxCognitiveComplexity=parseInt(s,10);break;case"mincommits":t.minCommits=parseInt(s,10);break;case"maxcommits":t.maxCommits=parseInt(s,10);break;case"isdocumented":t.isDocumented=s.toLowerCase()!=="false";break;case"isstale":t.isStale=s.toLowerCase()!=="false";break;case"lastauthor":t.lastAuthor=s;break}}function Wi(t){let e=[];for(let r of t.split("|")){let n=r.trim();if(!n)continue;let s={};cn(s,n),Object.keys(s).length>0&&e.push(s)}return e}function je(t){let e={},r=t.split(",");for(let n of r){let s=n.trim();if(s.toLowerCase().startsWith("any(")&&s.endsWith(")")){let o=s.slice(4,-1),i=Wi(o);i.length>0&&(e.any=[...e.any??[],...i]);continue}cn(e,n)}return e}import hn from"fs/promises";import pa from"path";import Ht from"path";import He from"typescript";import $i from"path";import zi from"path";import E from"typescript";var ln=new Set(["describe","test","it"]);function B(t,e){let r=t[e];if(r===void 0)throw new Error(`Index ${e} out of bounds (length ${t.length})`);return r}function _t(t){let e=[];for(let r of t.statements){if(!E.isExpressionStatement(r))continue;let n=r.expression;if(!E.isCallExpression(n))continue;let s=n.expression;E.isIdentifier(s)&&ln.has(s.text)&&e.push(n),E.isPropertyAccessExpression(s)&&E.isIdentifier(s.expression)&&ln.has(s.expression.text)&&e.push(n)}return e}function Ot(t,e,r){for(let n of t.arguments){if(!E.isObjectLiteralExpression(n))continue;let s=n.properties.find(o=>E.isPropertyAssignment(o)&&E.isIdentifier(o.name)&&o.name.text===e);if(!(!s||!E.isArrayLiteralExpression(s.initializer)))return s.initializer.elements.filter(E.isStringLiteral).map(o=>o.text)}return null}function jt(t,e,r,n){if(t.arguments.length===0)return null;for(let o=1;o<t.arguments.length;o++){let i=B(t.arguments,o);if(!E.isObjectLiteralExpression(i))continue;let a=i.properties.find(l=>E.isPropertyAssignment(l)&&E.isIdentifier(l.name)&&l.name.text===e);if(a)return{start:a.initializer.getStart(n),end:a.initializer.getEnd(),text:r};let c=i.getEnd()-1;return{start:c,end:c,text:`${i.properties.length>0?", ":""}${e}: ${r}`}}let s=B(t.arguments,t.arguments.length-1);return{start:s.getStart(n),end:s.getStart(n),text:`{ ${e}: ${r} }, `}}function Wt(t,e,r){let n=t.arguments;for(let s=1;s<n.length;s++){let o=B(n,s);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:B(n,s-1).getEnd(),end:o.getEnd(),text:""};let a=B(o.properties,i);return i===o.properties.length-1?{start:B(o.properties,i-1).getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(r),end:B(o.properties,i+1).getStart(r),text:""}}return null}function zt(t,e){let r=[...e].sort((s,o)=>o.start-s.start),n=t;for(let s of r)n=n.slice(0,s.start)+s.text+n.slice(s.end);return n}function Bt(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}var D=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function Bi(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}function We(t,e,r,n){let s=E.createSourceFile(zi.basename(t),e,E.ScriptTarget.Latest,!0),o=_t(s),[i]=o;if(!i)return e;let a=Ot(i,n,s),c=[...r].sort();if(a!==null&&JSON.stringify(Bi(a).sort())===JSON.stringify(c))return e;let l=Bt(c.map(m=>`@${m}`)),p=o.flatMap(m=>{let d=r.length===0?Wt(m,n,s):jt(m,n,l,s);return d?[d]:[]});return p.length>0?zt(e,p):e}var ze=class{name="cypress";canHandle(e){return D.has($i.extname(e).toLowerCase())}apply(e,r,n){return We(e,r,n,"tags")}};import Ui from"path";var $t=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,Ut=/^@([a-zA-Z0-9_-]+)/gm;function Ki(t){return`${["# <mokosh-tags>",...t.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
8
10
  `)}
9
11
 
10
- `}function Wi(t){let e=new Set;$t.lastIndex=0;let r=$t.exec(t);for(;r!==null;)r[1]&&e.add(r[1]),r=$t.exec(t);return e}var je=class{name="gherkin";canHandle(e){return Oi.extname(e).toLowerCase()===".feature"}apply(e,r,n){let s=r.replace(zt,""),o=Wi(s),i=n.filter(c=>!o.has(c)),a=i.length>0?ji(i):"";return zt.test(r)?r.replace(zt,a):a?r.replace(/^(Feature:)/m,`${a}$1`):r}};function cn(t,e){let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/"),s="";for(let o=0;o<r.length;o++){let i=r[o];i==="*"?r[o+1]==="*"?(s+=".*",o++):s+="[^/]*":i==="?"?s+="[^/]":i!==void 0&&(s+=i.replace(/[.+^${}()|[\]\\]/g,"\\$&"))}return new RegExp(`^${s}$`).test(n)}import zi from"path";var Bt=/^\/\/go:build mokosh_[^\n]+\n/m,$i=/^package\s+\S+/m;function Bi(t){return`//go:build ${t.map(r=>`mokosh_${r}`).join(" || ")}
11
- `}function Ui(t){let e=Bt.exec(t);if(!e)return null;let r=e[0]??"",n=/mokosh_([a-zA-Z0-9_-]+)/g,s=[],o=n.exec(r);for(;o!==null;)o[1]&&s.push(o[1]),o=n.exec(r);return s}var We=class{name="go";canHandle(e){return zi.basename(e).endsWith("_test.go")}apply(e,r,n){let s=Ui(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return r.replace(Bt,"");let i=Bi(o);if(s!==null)return r.replace(Bt,i);let a=$i.exec(r);if(!a)return r;let c=a.index;return`${r.slice(0,c)+i}
12
- ${r.slice(c)}`}};import Ki from"path";var Ji=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,Ut=/^ \* @group (.+)$/gm;function Vi(t){return`${["/**",...t.map(e=>` * @group ${e}`)," */"].join(`
12
+ `}function Ji(t){let e=new Set;Ut.lastIndex=0;let r=Ut.exec(t);for(;r!==null;)r[1]&&e.add(r[1]),r=Ut.exec(t);return e}var Be=class{name="gherkin";canHandle(e){return Ui.extname(e).toLowerCase()===".feature"}apply(e,r,n){let s=r.replace($t,""),o=Ji(s),i=n.filter(c=>!o.has(c)),a=i.length>0?Ki(i):"";return $t.test(r)?r.replace($t,a):a?r.replace(/^(Feature:)/m,`${a}$1`):r}};function pn(t,e){let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/"),s="";for(let o=0;o<r.length;o++){let i=r[o];i==="*"?r[o+1]==="*"?(s+=".*",o++):s+="[^/]*":i==="?"?s+="[^/]":i!==void 0&&(s+=i.replace(/[.+^${}()|[\]\\]/g,"\\$&"))}return new RegExp(`^${s}$`).test(n)}import Vi from"path";var Kt=/^\/\/go:build mokosh_[^\n]+\n/m,Hi=/^package\s+\S+/m;function Qi(t){return`//go:build ${t.map(r=>`mokosh_${r}`).join(" || ")}
13
+ `}function qi(t){let e=Kt.exec(t);if(!e)return null;let r=e[0]??"",n=/mokosh_([a-zA-Z0-9_-]+)/g,s=[],o=n.exec(r);for(;o!==null;)o[1]&&s.push(o[1]),o=n.exec(r);return s}var $e=class{name="go";canHandle(e){return Vi.basename(e).endsWith("_test.go")}apply(e,r,n){let s=qi(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return r.replace(Kt,"");let i=Qi(o);if(s!==null)return r.replace(Kt,i);let a=Hi.exec(r);if(!a)return r;let c=a.index;return`${r.slice(0,c)+i}
14
+ ${r.slice(c)}`}};import Yi from"path";var Xi=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,Jt=/^ \* @group (.+)$/gm;function Zi(t){return`${["/**",...t.map(e=>` * @group ${e}`)," */"].join(`
13
15
  `)}
14
16
 
15
- `}function Hi(t){let e=[];Ut.lastIndex=0;let r=Ut.exec(t);for(;r!==null;)r[1]&&e.push(r[1]),r=Ut.exec(t);return e}var ze=class{name="jest";canHandle(e){return I.has(Ki.extname(e).toLowerCase())}apply(e,r,n){let s=Ji.exec(r),o=s?Hi(s[0]):null,i=[...n].sort();if(o!==null&&JSON.stringify([...o].sort())===JSON.stringify(i))return r;let a=s?r.slice(s[0].length):r;return n.length===0?a:Vi(i)+a}};import Qi from"path";var $e=class{name="playwright";canHandle(e){return I.has(Qi.extname(e).toLowerCase())}apply(e,r,n){return _e(e,r,n,"tag")}};import qi from"path";var Kt=/^pytestmark\s*=\s*.+$/m,Yi=/^import pytest\s*$/m;function Xi(t){let e=t.map(r=>`pytest.mark.${r}`).join(", ");return t.length===1?`pytestmark = pytest.mark.${t[0]}`:`pytestmark = [${e}]`}function Zi(t){let e=Kt.exec(t);if(!e)return null;let r=e[0],n=[],s=/pytest\.mark\.([a-zA-Z0-9_-]+)/g,o=s.exec(r);for(;o!==null;)o[1]&&n.push(o[1]),o=s.exec(r);return n}var Be=class{name="pytest";canHandle(e){return qi.extname(e).toLowerCase()===".py"}apply(e,r,n){let s=Zi(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return r.replace(Kt,"").replace(/\n{3,}/g,`
17
+ `}function ea(t){let e=[];Jt.lastIndex=0;let r=Jt.exec(t);for(;r!==null;)r[1]&&e.push(r[1]),r=Jt.exec(t);return e}var Ue=class{name="jest";canHandle(e){return D.has(Yi.extname(e).toLowerCase())}apply(e,r,n){let s=Xi.exec(r),o=s?ea(s[0]):null,i=[...n].sort();if(o!==null&&JSON.stringify([...o].sort())===JSON.stringify(i))return r;let a=s?r.slice(s[0].length):r;return n.length===0?a:Zi(i)+a}};import ta from"path";var Ke=class{name="playwright";canHandle(e){return D.has(ta.extname(e).toLowerCase())}apply(e,r,n){return We(e,r,n,"tag")}};import ra from"path";var Vt=/^pytestmark\s*=\s*.+$/m,na=/^import pytest\s*$/m;function sa(t){let e=t.map(r=>`pytest.mark.${r}`).join(", ");return t.length===1?`pytestmark = pytest.mark.${t[0]}`:`pytestmark = [${e}]`}function oa(t){let e=Vt.exec(t);if(!e)return null;let r=e[0],n=[],s=/pytest\.mark\.([a-zA-Z0-9_-]+)/g,o=s.exec(r);for(;o!==null;)o[1]&&n.push(o[1]),o=s.exec(r);return n}var Je=class{name="pytest";canHandle(e){return ra.extname(e).toLowerCase()===".py"}apply(e,r,n){let s=oa(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return r.replace(Vt,"").replace(/\n{3,}/g,`
16
18
 
17
- `);let i=Xi(o);if(s!==null)return r.replace(Kt,i);let a=Yi.test(r),c=ea(r),p=r.slice(0,c),l=r.slice(c),d=a?"":`import pytest
18
- `,f=p.endsWith(`
19
+ `);let i=sa(o);if(s!==null)return r.replace(Vt,i);let a=na.test(r),c=ia(r),l=r.slice(0,c),p=r.slice(c),m=a?"":`import pytest
20
+ `,d=l.endsWith(`
19
21
 
20
22
  `)?"":`
21
- `;return`${p+f+d+i}
22
- ${l}`}};function ea(t){let e=t.split(`
23
- `),r=-1;return e.forEach((s,o)=>{(s.trimStart().startsWith("import ")||s.trimStart().startsWith("from "))&&(r=o)}),r<0?0:e.slice(0,r+1).reduce((s,o)=>s+o.length+1,0)}import pn from"path";import ln from"typescript";var ta=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,Ue=class{name="vitest";canHandle(e){return I.has(pn.extname(e).toLowerCase())}apply(e,r,n){let s=r.replace(ta,""),o=ln.createSourceFile(pn.basename(e),s,ln.ScriptTarget.Latest,!0),i=Gt(o),[a]=i;if(!a)return s;let c=Lt(a,"tags",o),p=[...n].sort();if(c!==null&&JSON.stringify([...c].sort())===JSON.stringify(p))return s;let l=i.flatMap(d=>{let f=n.length===0?Ot(d,"tags",o):_t(d,"tags",Wt(p),o);return f?[f]:[]});return l.length>0?jt(s,l):s}};var un={vitest:()=>new Ue,playwright:()=>new $e,cypress:()=>new Oe,jest:()=>new ze},ra={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function na(t){let e=Ke.createSourceFile("detect.ts",t,Ke.ScriptTarget.Latest,!0);for(let r of e.statements){if(!Ke.isImportDeclaration(r)||!Ke.isStringLiteral(r.moduleSpecifier))continue;let n=ra[r.moduleSpecifier.text];if(n)return n}return null}var Vt=class{constructor(e,r,n){this.rootDir=e;this.defaultFramework=r;this.frameworkOverrides=n}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return I.has(Jt.extname(e).toLowerCase())}apply(e,r,n){let s=na(r)??this.matchOverride(e)??this.defaultFramework;return(un[s]??un.vitest)().apply(e,r,n)}matchOverride(e){let r=Jt.relative(this.rootDir,e).split(Jt.sep).join("/");for(let[n,s]of this.frameworkOverrides)if(cn(n,r))return s;return null}};function fn(t="vitest",e={},r=process.cwd()){return[new je,new Be,new We,new Vt(r,t,Object.entries(e))]}function mn(t,e){return e.find(r=>r.canHandle(t))??null}var oa=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,ia=new Set(["import"]),aa=new Set(["common","fixture","fixtures","helper","helpers","index","main","mock","mocks","setup","shared","spec","test","tests","types","util","utils"]);async function ca(t,e,r,n){let s;try{s=await gn.readFile(t,"utf8")}catch(a){return{path:t,status:"error",error:String(a)}}let o=mn(t,n);if(!o)return{path:t,status:"unchanged"};let i=o.apply(t,s,e);return i===s?{path:t,status:"unchanged"}:(r||await gn.writeFile(t,i,"utf8"),{path:t,status:"updated"})}async function Ht(t,e,r){let n=re(e),s=n.tagApplier?.framework??"vitest",o=n.tagApplier?.frameworkOverrides??{},i=fn(s,o,e),a={updated:0,unchanged:0,errors:0,files:[]};for(let c of t.nodes.values()){if(c.category!=="test")continue;let p=new Set,l=[];for(let h of c.tags)ia.has(h.kind)&&oa.test(h.name)&&(aa.has(h.name.toLowerCase())||p.has(h.name)||(p.add(h.name),l.push(h.name)));l.sort();let d=sa.resolve(e,c.path),f=await ca(d,l,r.dryRun,i);f.path=c.path,a.files.push(f),f.status==="updated"?a.updated++:f.status==="unchanged"?a.unchanged++:a.errors++}return a}var Je=class{isTestNode(e){return e.category==="test"||e.tags.some(r=>r.name==="test")}};import be from"fs";import T from"path";import _c from"piscina";import{execFileSync as Qt}from"child_process";var Ve=class{getChangedFiles(){try{let r=[["diff","--name-only"],["diff","--cached","--name-only"],["ls-files","--others","--exclude-standard"]].flatMap(n=>{try{return Qt("git",n,{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
24
- `).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),[]}}},dn="%x00%H%x09%ae%x09%at",hn=256*1024*1024;function yn(t,e){let r="",n=0;for(let s of t.split(`
25
- `)){if(s.startsWith("\0")){let[,c,p]=s.slice(1).split(" ");r=c??"",n=p?Number(p)*1e3:0;continue}if(s==="")continue;let o=s.split(" "),i=o[0];if(!i)continue;let a=i.startsWith("R")||i.startsWith("C")?o[2]:o[1];a&&e(a,r,n)}}function xn(t){let e=new Map;try{let r=Qt("git",["-C",t,"log","--since=90 days ago","--name-status","-M",`--format=${dn}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:hn});yn(r,(n,s,o)=>{let i=e.get(n);if(i){i.commitCount90d+=1;return}e.set(n,{commitCount90d:1,lastAuthor:s||void 0,lastCommitAt:o||void 0})})}catch{return e}try{let r=Qt("git",["-C",t,"log","--name-status","-M",`--format=${dn}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:hn});yn(r,(n,s,o)=>{e.has(n)||e.set(n,{commitCount90d:0,lastAuthor:void 0,lastCommitAt:o||void 0})})}catch{}return e}import Sn from"path";function G(t){switch(Sn.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 A(t){let e=Sn.extname(t).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}import pa from"coffeescript";function L(t){return t.startsWith("'")||t.startsWith('"')?t.slice(1,-1):t}function Y(t){let e=new Set,r=/@tag\s+([a-zA-Z0-9_-]+)/g,n=r.exec(t);for(;n!==null;)n[1]&&e.add(n[1]),n=r.exec(t);return e}function X(t,e){let r=t.toLowerCase();return r.includes(".test.")||r.includes(".spec.")||e.has("test")?"test":"logic"}function vn(t){if(t){if(typeof t.originalValue=="string")return t.originalValue;if(typeof t.value=="string")return L(t.value)}}function B(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function la(t,e){let r=vn(e.source);return r?{fromPath:t,toPath:"",rawSpecifier:r,isStyle:A(r),type:"static"}:null}function ua(t,e){let r=e.variable?.base?.value==="require",n=vn(e.args?.[0]?.base);return!r||!n?null:{fromPath:t,toPath:"",rawSpecifier:n,isStyle:A(n),type:"require"}}function bn(t,e){if(e)return[{name:e}];let r=t.value;if(r?.constructor?.name==="Class"){let s=B(r.variable);return s?[{name:s}]:[]}if(r?.base?.constructor?.name==="Obj"&&Array.isArray(r.base.properties))return r.base.properties.map(s=>B(s.variable)??B(s)).filter(s=>!!s).map(s=>({name:s}));let n=B(r);return n?[{name:n}]:[]}function fa(t){if(Array.isArray(t.specifiers))return t.specifiers.map(r=>r.identifier??r.original?.value).filter(r=>!!r).map(r=>({name:r}));let e=B(t.variable)??B(t.variable?.base);return e?[{name:e}]:[]}function ma(t,e,r,n){let s=e.constructor?.name;if(s==="ImportDeclaration"){let o=la(t,e);o&&r.push(o)}else if(s==="Call"){let o=ua(t,e);o&&r.push(o)}else if(s==="Assign"){let o=B(e.variable?.base),i=e.variable?.properties?.[0]?.name?.value;o==="module"&&i==="exports"?n.push(...bn(e,void 0)):o==="exports"&&typeof i=="string"&&n.push(...bn(e,i))}else s==="ExportNamedDeclaration"&&e.clause?n.push(...fa(e.clause)):s==="ExportDefaultDeclaration"&&n.push({name:"default"})}function qt(t,e,r,n){if(!(!e||typeof e!="object")){ma(t,e,r,n);for(let s in e){if(s==="locationData")continue;let o=e[s];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let i of o)qt(t,i,r,n);else qt(t,o,r,n)}}}function kn(t,e){let r=Y(e),n=X(t,r),s=[],o=[];try{qt(t,pa.nodes(e),s,o)}catch{}let i=new Set,a=o.filter(c=>i.has(c.name)?!1:(i.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(r).map(c=>({name:c,kind:"comment-marker"})),category:n}}import{AstBuilder as ga,GherkinClassicTokenMatcher as da,Parser as ha}from"@cucumber/gherkin";import{IdGenerator as ya}from"@cucumber/messages";var xa=ya.uuid();function Yt(t,e){let r=new Set;try{let n=new ga(xa),s=new da,i=new ha(n,s).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(c=>{r.add(c.name.startsWith("@")?c.name.slice(1):c.name)}),a.scenario.examples.forEach(c=>{c.tags.forEach(p=>{r.add(p.name.startsWith("@")?p.name.slice(1):p.name)})})),a.rule&&a.rule.children.forEach(c=>{c.scenario&&c.scenario.tags.forEach(p=>{r.add(p.name.startsWith("@")?p.name.slice(1):p.name)})})}))}catch(n){console.warn(`[GherkinParser] Failed to parse ${t}:`,n)}return{imports:[],exports:[],tags:Array.from(r).map(n=>({name:n,kind:"comment-marker"})),category:"test"}}q("gherkin",Yt);import va from"path";import{parser as ka}from"@lezer/go";function U(t){let e=[],r=t.firstChild;for(;r;)e.push(r),r=r.nextSibling;return e}function fe(t,e){let r=1;for(let n=0;n<e&&n<t.length;n++)t[n]===`
26
- `&&r++;return r}function Sa(t,e){let r=1;function n(s){switch(s.type.name){case"IfStatement":case"ForStatement":r++;break;case"Case":{s.firstChild?.type.name==="case"&&r++;break}case"LogicOp":{let i=e.slice(s.from,s.to);(i==="&&"||i==="||")&&r++;break}}let o=s.firstChild;for(;o;)n(o),o=o.nextSibling}return n(t),r}function ba(t,e){let r=0;function n(s,o,i){let a=s.type.name;if(a==="IfStatement"){r+=i?1:1+o;let l=U(s),d=i?o:o+1,f=l[1];f&&f.type.name!=="Block"&&n(f,d,!1);let h=l.find(y=>y.type.name==="Block");h&&n(h,d,!1);let x=l.findIndex(y=>y.type.name==="else");if(x>=0){let y=l[x+1];y?.type.name==="IfStatement"?n(y,o,!0):y&&(r+=1,n(y,o+1,!1))}return}if(a==="ForStatement"||a==="SwitchStatement"||a==="SelectStatement"){r+=1+o;let l=s.firstChild;for(;l;)n(l,o+1,!1),l=l.nextSibling;return}if(a==="LogicOp"){let l=e.slice(s.from,s.to);(l==="&&"||l==="||")&&(r+=1)}if(o>0&&a==="FunctionLiteral"){r+=1+o;let l=s.firstChild;for(;l;)n(l,o+1,!1),l=l.nextSibling;return}let p=s.firstChild;for(;p;)n(p,o,!1),p=p.nextSibling}return n(t,0,!1),r}function He(t,e){return{complexity:Sa(t,e),cognitiveComplexity:ba(t,e)}}function Xt(t,e){let n=t.getChild("Parameters")?.getChild("Parameter"),s=n?.getChild("TypeName")??n?.getChild("PointerType")?.getChild("TypeName");return s?e.slice(s.from,s.to):void 0}function wn(t,e){let r=[],n=t.cursor();do if(n.name==="FunctionDecl"){let s=n.node.getChild("DefName");if(s){let o=e.slice(s.from,s.to),{complexity:i,cognitiveComplexity:a}=He(n.node,e);r.push({name:o,line:fe(e,n.from),complexity:i,cognitiveComplexity:a})}}else if(n.name==="MethodDecl"){let s=n.node.getChild("FieldName");if(s){let o=e.slice(s.from,s.to),i=Xt(n.node,e),a=i?`${i}.${o}`:o,{complexity:c,cognitiveComplexity:p}=He(n.node,e);r.push({name:a,line:fe(e,n.from),complexity:c,cognitiveComplexity:p})}}while(n.next());return r}var wa=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,Ca=/^\/\/go:build\s+(.+)$/,Fa=/^\/\/\s*\+build\s+(.+)$/;function Fn(t,e){let r=[],n=new Map,s=new Set,o=new Set,i=new Map,a=ka.parse(e),c=a.cursor();do switch(c.name){case"LineComment":{let S=e.slice(c.from,c.to),C=S.match(wa);C?.[1]&&s.add(C[1]);let N=S.match(Ca);N&&Cn(N[1],o);let M=S.match(Fa);M&&Cn(M[1],o);break}case"ImportSpec":{let S=c.node.getChild("String");if(S){let N=e.slice(S.from,S.to).slice(1,-1);r.push({fromPath:t,toPath:"",rawSpecifier:N,isExternal:!0,isStyle:!1,type:"static"});let M=c.node.getChild("DefName"),O=M?e.slice(M.from,M.to):N.split("/").pop();O&&O!=="_"&&O!=="."&&i.set(O,N)}break}case"FunctionDecl":case"MethodDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let S=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(S){let C=e.slice(S.from,S.to);C!=="_"&&/^[A-Z]/.test(C)&&!n.has(C)&&n.set(C,{name:C})}break}}while(c.next());let p=r.some(S=>S.rawSpecifier==="testing"),l=va.basename(t).endsWith("_test.go")||s.has("test")||p?"test":"logic",d=new Set([...s,...o]),{complexity:f,cognitiveComplexity:h}=He(a.topNode,e),x=wn(a,e),y=l==="test"?[]:Ea(a,e,i);return{imports:r,exports:Array.from(n.values()),tags:Array.from(d).map(S=>({name:S,kind:"comment-marker"})),category:l,rawCallEdges:y,complexity:f,cognitiveComplexity:h,...x.length>0?{functions:x}:{}}}function Ea(t,e,r){let n=[];function s(i,a){if(i.type.name==="CallExpr"){let p=i.firstChild;if(p?.type.name==="SelectorExpr"){let l=p.firstChild,d=p.getChild("FieldName");if(l?.type.name==="VariableName"&&d){let f=e.slice(l.from,l.to),h=r.get(f);if(h){let x=e.slice(d.from,d.to);n.push({from:a,to:x,toSpecifier:h})}}}}let c=i.firstChild;for(;c;)s(c,a),c=c.nextSibling}let o=t.cursor();do if(o.name==="FunctionDecl"){let i=o.node.getChild("DefName"),a=o.node.getChild("Block");if(i&&a){let c=e.slice(i.from,i.to);/^[A-Z]/.test(c)&&s(a,c)}}else if(o.name==="MethodDecl"){let i=o.node.getChild("FieldName"),a=o.node.getChild("Block");if(i&&a){let c=e.slice(i.from,i.to),p=Xt(o.node,e);s(a,p?`${p}.${c}`:c)}}while(o.next());return n}function Cn(t,e){for(let r of t.split(/[\s,&|!()]+/)){let n=r.trim();n&&n!=="ignore"&&e.add(n)}}import Ta from"livescript";function K(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function Pa(t){if(!t)return[];if(t.constructor?.name==="Class"){let r=K(t.title);return r?[{name:r}]:[]}if(t.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(r=>K(r.key)??K(r.val)).filter(r=>!!r).map(r=>({name:r}));let e=K(t);return e?[{name:e}]:[]}function Aa(t){let e=t.constructor?.name||t.type;if(e==="Assign"&&t.left?.constructor?.name==="Chain"){let r=t.left,n=K(r.head),o=r.tails?.[0]?.key?.name;if(n==="module"&&o==="exports")return Pa(t.right);if(n==="exports"&&typeof o=="string")return[{name:o}];if(r.head?.verb==="out"&&typeof o=="string")return[{name:o}]}if(e==="Import"&&t.left?.verb==="out"){let r=t.right;if(r?.constructor?.name==="Obj"&&Array.isArray(r.items))return r.items.map(n=>K(n.val)??K(n.key)).filter(n=>!!n).map(n=>({name:n}))}return[]}var Na=new Set(["first_line","first_column","last_line","last_column","line","column"]);function Ma(t,e){let r=t.constructor?.name||t.type;if(r==="Import"){let n=t.right?.value;if(typeof n=="string"){let s=L(n);return{fromPath:e,toPath:"",rawSpecifier:s,isStyle:A(s),type:"static"}}}if(r==="Chain"&&t.head?.value==="require"){let n=t.tails?.[0];if(n?.constructor?.name==="Call"||n?.type==="Call"){let s=n.args?.[0]?.value;if(typeof s=="string"){let o=L(s);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:A(o),type:"require"}}}}return null}function Zt(t,e,r){if(!t||typeof t!="object")return[];let n=[],s=Ma(t,e);s&&n.push(s),r.push(...Aa(t));for(let o in t){if(Na.has(o))continue;let i=t[o];if(!(!i||typeof i!="object"))if(Array.isArray(i))for(let a of i)n.push(...Zt(a,e,r));else n.push(...Zt(i,e,r))}return n}function En(t,e){let r=Y(e),n=X(t,r),s=[],o=[];try{s=Zt(Ta.ast(e),t,o)}catch{}let i=new Set,a=o.filter(c=>i.has(c.name)?!1:(i.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(r).map(c=>({name:c,kind:"comment-marker"})),category:n}}import Ia from"luaparse";function Da(t,e){let r=[];function n(s){if(!(!s||typeof s!="object")){if((s.type==="CallExpression"||s.type==="StringCallExpression")&&s.base?.type==="Identifier"&&s.base?.name==="require"){let o;if(s.type==="CallExpression"){let i=s.arguments?.[0];i?.type==="StringLiteral"&&(o=L(i.raw))}else if(s.type==="StringCallExpression"){let i=s.argument;i?.type==="StringLiteral"&&(o=L(i.raw))}o&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:A(o),type:"require"})}for(let o in s){if(o==="loc")continue;let i=s[o];if(i&&typeof i=="object")if(Array.isArray(i))for(let a of i)n(a);else n(i)}}}return n(t),r}function Ra(t){let e=new Set;for(let r of t)r.type==="LocalStatement"&&r.variables.forEach((n,s)=>{r.init[s]?.type==="TableConstructorExpression"&&e.add(n.name)});return e}function Ga(t){let e=t[t.length-1];if(e?.type!=="ReturnStatement")return[];let r=e.arguments[0];if(r?.type!=="TableConstructorExpression")return[];let n=[];for(let s of r.fields)s.type==="TableKeyString"&&n.push({name:s.key.name});return n}function La(t){let e=t.body,r=Ra(e),n=Ga(e);for(let o of e)if(o.type==="FunctionDeclaration")o.identifier?.type==="MemberExpression"?o.identifier.base.type==="Identifier"&&r.has(o.identifier.base.name)&&n.push({name:o.identifier.identifier.name}):o.identifier?.type==="Identifier"&&!o.isLocal&&n.push({name:o.identifier.name});else if(o.type==="AssignmentStatement")for(let i of o.variables)i.type==="MemberExpression"&&i.base.type==="Identifier"&&r.has(i.base.name)&&n.push({name:i.identifier.name});let s=new Set;return n.filter(o=>s.has(o.name)?!1:(s.add(o.name),!0))}function Tn(t,e){let r=Y(e),n=X(t,r),s=[],o=[];try{let i=Ia.parse(e);s=Da(i,t),o=La(i)}catch{}return{imports:s,exports:o,tags:Array.from(r).map(i=>({name:i,kind:"comment-marker"})),category:n}}var _a=["http://","https://","mailto:","//"],Oa="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",ja=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${Oa})\\b`,"g"),Pn;async function Wa(){return Pn??=(async()=>{let{unified:t}=await import("unified"),e=(await import("remark-parse")).default;return t().use(e)})(),Pn}function za(t){let e=t.trim();return e.length===0||e.startsWith("#")||_a.some(r=>e.startsWith(r))}function $a(t,e){let r=t.match(ja);return r?r.map(n=>({fromPath:e,toPath:"",rawSpecifier:n,isStyle:!1,type:"static"})):[]}function An(t,e,r){if(t.type==="link"&&typeof t.url=="string"&&!za(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(...$a(t.value,e)),Array.isArray(t.children))for(let n of t.children)An(n,e,r)}async function Nn(t,e){let n=(await Wa()).parse(e),s=[];An(n,t,s);let o=new Set;return{imports:s.filter(a=>o.has(a.rawSpecifier)?!1:(o.add(a.rawSpecifier),!0)),exports:[],tags:[],category:"other"}}import Ka from"path";import{parser as Ja}from"@lezer/python";function Ba(t){let e=1;function r(n){switch(n.type.name){case"IfStatement":{e+=U(n).filter(o=>o.type.name==="if"||o.type.name==="elif").length;break}case"TryStatement":{e+=U(n).filter(o=>o.type.name==="except").length;break}case"ForStatement":case"WhileStatement":case"ConditionalExpression":e++;break;case"and":case"or":e++;break}let s=n.firstChild;for(;s;)r(s),s=s.nextSibling}return r(t),e}function Ua(t){let e=0;function r(n,s){let o=n.type.name;if(o==="IfStatement"){let c=U(n),p=0,l=0;for(;l<c.length;){let d=c[l];if(d?.type.name==="if"||d?.type.name==="elif"){let f=p>0;e+=f?1:1+s;let h=f?s:s+1,x=c[l+1],y=c[l+2];x&&r(x,h),y&&r(y,h),p++,l+=3}else if(d?.type.name==="else"){e+=1;let f=c[l+1];f&&r(f,s+1),l+=2}else l++}return}if(o==="TryStatement"){let c=U(n),p=0;for(;p<c.length;){let l=c[p];if(l?.type.name==="except"){for(e+=1+s,p++;p<c.length&&c[p]?.type.name!=="Body";)r(c[p],s),p++;p<c.length&&(r(c[p],s),p++)}else l?.type.name==="Body"&&r(l,s),p++}return}if(o==="ForStatement"||o==="WhileStatement"){e+=1+s;let c=n.firstChild;for(;c;)r(c,s+1),c=c.nextSibling;return}if((o==="ConditionalExpression"||o==="and"||o==="or")&&(e+=1),s>0&&(o==="FunctionDefinition"||o==="LambdaExpression")){e+=1+s;let c=n.firstChild;for(;c;)r(c,s+1),c=c.nextSibling;return}let a=n.firstChild;for(;a;)r(a,s),a=a.nextSibling}return r(t,0),e}function er(t){return{complexity:Ba(t),cognitiveComplexity:Ua(t)}}function Mn(t,e){let r=[];function n(i,a){let{complexity:c,cognitiveComplexity:p}=er(i);r.push({name:a,line:fe(e,i.from),complexity:c,cognitiveComplexity:p})}function s(i){let a=i.firstChild;for(;a;)o(a),a=a.nextSibling}function o(i){if(i.type.name==="ClassDefinition"){let a=i.getChild("VariableName"),c=a?e.slice(a.from,a.to):void 0,p=i.getChild("Body");if(p){let l=p.firstChild;for(;l;){if(l.type.name==="FunctionDefinition"){let d=l.getChild("VariableName"),f=d?e.slice(d.from,d.to):void 0;f&&n(l,c?`${c}.${f}`:f),s(l)}else o(l);l=l.nextSibling}}return}if(i.type.name==="FunctionDefinition"){let a=i.getChild("VariableName");a&&n(i,e.slice(a.from,a.to)),s(i);return}s(i)}return o(t.topNode),r}var Va=new Set(["pytest","unittest","nose","hypothesis"]);function In(t,e){let r=[],n=[],s=new Set,o=Ka.basename(t).toLowerCase(),i=Ja.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]&&s.add(h[1]);break}case"ImportStatement":{for(let h of Ha(a.node,e,t))r.push(h);break}case"FunctionDefinition":case"ClassDefinition":{let h=a.node.parent;if(h?.name==="Script"||h?.name==="DecoratedStatement"&&h.parent?.name==="Script"){let y=a.node.getChild("VariableName");y&&n.push({name:e.slice(y.from,y.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let h=a.node.firstChild;h?.name==="VariableName"&&n.push({name:e.slice(h.from,h.to)})}break}}while(a.next());let c=ec(o,r,s);c==="test"&&s.add("test");let{complexity:p,cognitiveComplexity:l}=er(i.topNode),d=Mn(i,e),f=c==="test"?[]:Za(i,e);return{imports:r,exports:n,tags:Array.from(s).map(h=>({name:h,kind:"comment-marker"})),category:c,rawCallEdges:f,complexity:p,cognitiveComplexity:l,...d.length>0?{functions:d}:{}}}function Ha(t,e,r){let n=t.firstChild;return n?n.name==="from"?Qa(t,e,r):qa(t,e,r):[]}function Qa(t,e,r){let n=t.firstChild;if(!n)return[];let s=n.nextSibling;for(;s&&s.name!=="import";)s=s.nextSibling;if(!s)return[];let o=e.slice(n.to,s.from).trim(),i=Ya(s.nextSibling,e);if(!i.length)return[];let a=0;for(;a<o.length&&o[a]===".";)a++;let c=o.slice(a);if(a===0)return[me(r,o,i,!0)];let p=a===1?"./":"../".repeat(a-1);return c?[me(r,p+c.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[me(r,p.slice(0,-1),["*"],!1)]:i.map(l=>me(r,p+l,[l],!1))}function qa(t,e,r){let n=[],s=t.firstChild?.nextSibling??null;for(;s;){if(s.name==="VariableName"){let o=e.slice(s.from,s.to);for(;s.nextSibling?.name==="."&&s.nextSibling.nextSibling?.name==="VariableName";)s=s.nextSibling.nextSibling,o+=`.${e.slice(s.from,s.to)}`;s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling),n.push(me(r,o,["*"],!0))}s=s.nextSibling}return n}function Ya(t,e){let r=[],n=t;for(;n;)n.name==="*"?r.push("*"):n.name==="VariableName"&&(r.push(e.slice(n.from,n.to)),n.nextSibling?.name==="as"&&(n=n.nextSibling.nextSibling??n.nextSibling)),n=n.nextSibling;return r}function Xa(t,e){let r=new Map,n=t.cursor();do{if(n.name!=="ImportStatement")continue;let o=n.node.firstChild;if(o?.type.name!=="from")continue;let i=o.nextSibling;for(;i&&i.type.name!=="import";)i=i.nextSibling;if(!i)continue;let a=e.slice(o.to,i.from).trim(),c=0;for(;c<a.length&&a[c]===".";)c++;let p=a.slice(c),l=c<=1?"./":"../".repeat(c-1),d=i.nextSibling;for(;d;){if(d.type.name==="VariableName"){let f=e.slice(d.from,d.to),h=f;if(d.nextSibling?.type.name==="as"){let y=d.nextSibling.nextSibling;y?.type.name==="VariableName"&&(h=e.slice(y.from,y.to),d=y)}let x=c===0?a:p?l+p.replace(/\./g,"/"):l+f;r.set(h,x)}d=d.nextSibling}}while(n.next());return r}function Za(t,e){let r=Xa(t,e),n=[];function s(a,c){if(a.type.name==="CallExpression"&&a.firstChild?.type.name==="VariableName"){let l=a.firstChild,d=e.slice(l.from,l.to),f=r.get(d);f&&n.push({from:c,to:d,toSpecifier:f})}let p=a.firstChild;for(;p;)s(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 d=l.firstChild;for(;d;){if(d.type.name==="FunctionDefinition"){let f=d.getChild("VariableName"),h=f?e.slice(f.from,f.to):void 0;h&&s(d,p?`${p}.${h}`:h)}else i(d);d=d.nextSibling}}return}if(a.type.name==="FunctionDefinition"){let c=a.getChild("VariableName");c&&s(a,e.slice(c.from,c.to));return}o(a)}return i(t.topNode),n}function me(t,e,r,n){return{fromPath:t,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:n,type:"static",symbols:r.length>0?r:void 0}}function ec(t,e,r){return t.startsWith("test_")||t.endsWith("_test.py")?"test":t==="conftest.py"||t==="setup.py"?"config":r.has("test")||e.some(n=>Va.has(n.rawSpecifier))?"test":"logic"}import Rn from"path";import g from"typescript";import b from"typescript";function tc(t){let e=1;function r(n){switch(n.kind){case b.SyntaxKind.IfStatement:case b.SyntaxKind.ConditionalExpression:case b.SyntaxKind.ForStatement:case b.SyntaxKind.ForInStatement:case b.SyntaxKind.ForOfStatement:case b.SyntaxKind.WhileStatement:case b.SyntaxKind.DoStatement:case b.SyntaxKind.CatchClause:case b.SyntaxKind.CaseClause:e++;break;case b.SyntaxKind.BinaryExpression:{let s=n.operatorToken.kind;(s===b.SyntaxKind.AmpersandAmpersandToken||s===b.SyntaxKind.BarBarToken||s===b.SyntaxKind.QuestionQuestionToken)&&e++;break}}b.forEachChild(n,r)}return r(t),e}function rc(t){let e=0;function r(n,s,o){if(b.isIfStatement(n)){e+=o?1:1+s;let a=o?s:s+1;r(n.expression,a,!1),r(n.thenStatement,a,!1),n.elseStatement&&(b.isIfStatement(n.elseStatement)?r(n.elseStatement,s,!0):(e+=1,r(n.elseStatement,s+1,!1)));return}if(b.isForStatement(n)||b.isForInStatement(n)||b.isForOfStatement(n)||b.isWhileStatement(n)||b.isDoStatement(n)||b.isSwitchStatement(n)){e+=1+s,b.forEachChild(n,a=>r(a,s+1,!1));return}if(b.isCatchClause(n)){e+=1+s,b.forEachChild(n,a=>r(a,s,!1));return}if(b.isConditionalExpression(n)&&(e+=1),b.isBinaryExpression(n)){let a=n.operatorToken.kind;(a===b.SyntaxKind.AmpersandAmpersandToken||a===b.SyntaxKind.BarBarToken||a===b.SyntaxKind.QuestionQuestionToken)&&(e+=1)}if(s>0&&(b.isFunctionDeclaration(n)||b.isFunctionExpression(n)||b.isArrowFunction(n))){e+=1+s,b.forEachChild(n,a=>r(a,s+1,!1));return}b.forEachChild(n,a=>r(a,s,!1))}return r(t,0,!1),e}function tr(t){return{complexity:tc(t),cognitiveComplexity:rc(t)}}import w from"typescript";var rr=new Set(["test","describe","it"]);function Dn(t,e){nc(t,e),oc(t,e),ic(t,e),ac(t,e)}function nc(t,e){if((w.isFunctionDeclaration(t)||w.isVariableDeclaration(t))&&t.name&&w.isIdentifier(t.name)&&sc(t)){let r;if(w.isFunctionDeclaration(t))r="function";else{let n=t.initializer;r=n&&(w.isArrowFunction(n)||w.isFunctionExpression(n))?"function":"variable"}e.tags.add({name:t.name.text,kind:r})}}function sc(t){if(w.isFunctionDeclaration(t))return w.isSourceFile(t.parent);let e=t.parent?.parent;return!!e&&w.isSourceFile(e.parent)}function oc(t,e){if(!w.isStringLiteral(t))return;let r=t.text.match(/@[\w-]+/g);if(r)for(let n of r)e.tags.add({name:n.substring(1),kind:"comment-marker"})}function ic(t,e){if(!w.isSourceFile(t))return;let r=/@tag\s+([a-zA-Z0-9_-]+)/g,n=t.getFullText(),s=r.exec(n);for(;s!==null;)s[1]&&e.tags.add({name:s[1],kind:"comment-marker"}),s=r.exec(n)}function ac(t,e){if(w.isCallExpression(t)&&cc(t.expression))for(let r of t.arguments)w.isObjectLiteralExpression(r)&&pc(r,e)}function cc(t){return w.isIdentifier(t)?rr.has(t.text):!!(w.isPropertyAccessExpression(t)&&(rr.has(t.name.text)||w.isIdentifier(t.expression)&&rr.has(t.expression.text)))}function pc(t,e){for(let r of t.properties){if(!w.isPropertyAssignment(r)||!w.isIdentifier(r.name)||r.name.text!=="tags"&&r.name.text!=="tag")continue;let{initializer:n}=r,s=w.isArrayLiteralExpression(n)?n.elements.filter(w.isStringLiteral):r.name.text==="tag"&&w.isStringLiteral(n)?[n]:[];for(let o of s)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function nr(t,e,r){let n=[],s=new Map,o=new Set,i=g.createSourceFile(t,e,g.ScriptTarget.Latest,!0,r==="typescript"?g.ScriptKind.TSX:g.ScriptKind.JSX),a={filePath:t,imports:n,exports:s,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=y=>{mc(y,a),g.forEachChild(y,c)};c(i);let p=Cc(t,a);(p==="test"||p==="barrel")&&o.add({name:p,kind:"comment-marker"}),p!=="test"&&Fc(a,i);let l=i.statements[0],d=l?Ln(l):void 0,{complexity:f,cognitiveComplexity:h}=tr(i),x=lc(i);return{imports:n,exports:Array.from(s.values()),tags:Array.from(o),category:p,rawCallEdges:a.rawCallEdges??[],complexity:f,cognitiveComplexity:h,...x.length>0?{functions:x}:{},...d!==void 0?{description:d}:{}}}function lc(t){let e=[],r=(s,o)=>{let{complexity:i,cognitiveComplexity:a}=tr(o),c=t.getLineAndCharacterOfPosition(o.getStart(t)).line+1;e.push({name:s,line:c,complexity:i,cognitiveComplexity:a})},n=(s,o)=>{if(g.isFunctionDeclaration(s)&&s.name&&s.body?r(s.name.text,s):g.isVariableDeclaration(s)&&g.isIdentifier(s.name)&&s.initializer&&(g.isArrowFunction(s.initializer)||g.isFunctionExpression(s.initializer))?r(s.name.text,s.initializer):o&&g.isMethodDeclaration(s)&&g.isIdentifier(s.name)&&s.body?r(`${o}.${s.name.text}`,s):o&&g.isConstructorDeclaration(s)&&s.body?r(`${o}.constructor`,s):o&&g.isGetAccessorDeclaration(s)&&g.isIdentifier(s.name)&&s.body?r(`${o}.get ${s.name.text}`,s):o&&g.isSetAccessorDeclaration(s)&&g.isIdentifier(s.name)&&s.body&&r(`${o}.set ${s.name.text}`,s),g.isClassDeclaration(s)&&s.name){let i=s.name.text;g.forEachChild(s,a=>n(a,i));return}g.forEachChild(s,i=>n(i,o))};return n(t,void 0),e}function Gn(t,e,r,n){let s={name:t},o=Ln(r);o!==void 0&&(s.doc=o);let i=uc(e);i!==void 0&&(s.flags=i);let a=fc(e,n);return a!==void 0&&(s.signature=a),s}function Ln(t){let e=g.getJSDocCommentsAndTags(t);for(let r of e)if(g.isJSDoc(r)&&r.comment)return g.getTextOfJSDocComment(r.comment)||void 0}function uc(t){let e=new Set(["deprecated","internal","public","alpha","beta"]),r=g.getJSDocTags(t).map(n=>n.tagName.text).filter(n=>e.has(n));return r.length>0?r:void 0}function fc(t,e){let r=g.createPrinter({removeComments:!0}),n=s=>r.printNode(g.EmitHint.Unspecified,s,e);if(g.isFunctionDeclaration(t)||g.isMethodDeclaration(t)){let s=t.parameters.map(n).join(", "),o=t.type?n(t.type):"void";return`${t.typeParameters?`<${t.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${s}) => ${o}`}if(g.isVariableDeclaration(t)){if(t.type)return n(t.type);if(t.initializer&&(g.isArrowFunction(t.initializer)||g.isFunctionExpression(t.initializer))){let s=t.initializer,o=s.parameters.map(n).join(", "),i=s.type?n(s.type):"unknown";return`(${o}) => ${i}`}return}if(g.isClassDeclaration(t)&&t.name)return`class ${t.name.text}`;if(g.isInterfaceDeclaration(t))return`interface ${t.name.text}`;if(g.isTypeAliasDeclaration(t))return n(t.type);if(g.isEnumDeclaration(t))return`enum ${t.name.text}`}function mc(t,e){gc(t,e),dc(t,e),yc(t,e),xc(t,e),wc(t,e),Dn(t,e)}function gc(t,e){if(!g.isSourceFile(t))return;let r=t.statements.filter(n=>!g.isEmptyStatement(n));e.totalStatements=r.length,e.exportStatements=r.filter(n=>g.isExportDeclaration(n)||g.isExportAssignment(n)||sr(n)).length}function dc(t,e){if(g.isJsxElement(t)||g.isJsxSelfClosingElement(t)||g.isJsxFragment(t)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(g.isFunctionDeclaration(t)||g.isMethodDeclaration(t)||g.isArrowFunction(t)||g.isClassDeclaration(t)||g.isVariableStatement(t)||g.isEnumDeclaration(t)){e.hasTypesOnly=!1;return}g.isExportDeclaration(t)&&!hc(t)&&(e.hasTypesOnly=!1)}function hc(t){return t.isTypeOnly?!0:!t.exportClause||!g.isNamedExports(t.exportClause)?!1:t.exportClause.elements.every(e=>e.isTypeOnly)}function yc(t,e){if(!g.isImportDeclaration(t)||!t.moduleSpecifier||!g.isStringLiteral(t.moduleSpecifier))return;let r=[];if(t.importClause&&(t.importClause.name&&r.push("default"),t.importClause.namedBindings))if(g.isNamedImports(t.importClause.namedBindings))for(let s of t.importClause.namedBindings.elements)r.push(s.name.text);else g.isNamespaceImport(t.importClause.namedBindings)&&r.push("*");let n=r.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.moduleSpecifier.text,isStyle:A(t.moduleSpecifier.text),type:n,symbols:r.length>0?r:void 0})}function xc(t,e){g.isExportDeclaration(t)?Sc(t,e):g.isExportAssignment(t)?e.exports.set("default",{name:"default"}):sr(t)&&kc(t,e)}function Sc(t,e){if(t.moduleSpecifier&&g.isStringLiteral(t.moduleSpecifier))bc(t,t.moduleSpecifier.text,e);else if(t.exportClause&&g.isNamedExports(t.exportClause))for(let r of t.exportClause.elements){let n=r.name.text;e.exports.set(n,{name:n})}}function bc(t,e,r){let n=vc(t),s={fromPath:r.filePath,toPath:"",rawSpecifier:e,isStyle:A(e),type:"re-export"};n.length>0&&(s.symbols=n),r.imports.push(s)}function vc(t){return t.exportClause?g.isNamedExports(t.exportClause)?t.exportClause.elements.map(e=>e.name.text):[]:["*"]}function kc(t,e){if((g.isFunctionDeclaration(t)||g.isClassDeclaration(t)||g.isInterfaceDeclaration(t)||g.isTypeAliasDeclaration(t)||g.isEnumDeclaration(t))&&t.name){let n=t.name.text;e.exports.set(n,Gn(n,t,t,e.sourceFile));return}if(g.isVariableStatement(t)){for(let n of t.declarationList.declarations)if(g.isIdentifier(n.name)){let s=n.name.text;e.exports.set(s,Gn(s,n,t,e.sourceFile))}}}function wc(t,e){if(!g.isCallExpression(t))return;let r=t.arguments[0];!r||!g.isStringLiteral(r)||(t.expression.kind===g.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:A(r.text),type:"dynamic"}):g.isIdentifier(t.expression)&&t.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:A(r.text),type:"require"}))}function Cc(t,e){let r=Rn.basename(t).toLowerCase(),n=Rn.extname(t).toLowerCase();return te().some(o=>r.includes(o))?"test":gr(r)?"config":e.imports.some(o=>rt().some(i=>o.rawSpecifier.includes(i)))?"test":n===".tsx"||n===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>st()?"barrel":"logic"}function sr(t){return g.canHaveModifiers(t)&&g.getModifiers(t)?.some(e=>e.kind===g.SyntaxKind.ExportKeyword)===!0}function Fc(t,e){let r=t.rawCallEdges??[];t.rawCallEdges=r;let n=new Map;for(let s of e.statements){if(!g.isImportDeclaration(s)||!g.isStringLiteral(s.moduleSpecifier))continue;let o=s.moduleSpecifier.text,i=s.importClause;if(i&&(i.name&&n.set(i.name.text,o),i.namedBindings&&g.isNamedImports(i.namedBindings)))for(let a of i.namedBindings.elements)n.set(a.name.text,o)}if(n.size!==0)for(let s of e.statements){let o=Tc(s);if(o){let i=Pc(s);i&&Qe(i,o,n,r);continue}g.isClassDeclaration(s)&&s.name&&Ec(s,s.name.text,n,r)}}function Ec(t,e,r,n){for(let s of t.members)g.isMethodDeclaration(s)&&s.body&&g.isIdentifier(s.name)?Qe(s.body,`${e}.${s.name.text}`,r,n):g.isConstructorDeclaration(s)&&s.body&&Qe(s.body,`${e}.constructor`,r,n)}function Tc(t){if(sr(t)){if(g.isFunctionDeclaration(t)&&t.name)return t.name.text;if(g.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(g.isIdentifier(e.name)&&e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer)))return e.name.text}}}function Pc(t){if(g.isFunctionDeclaration(t))return t.body;if(g.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer)))return e.initializer}}function Qe(t,e,r,n){if(g.isCallExpression(t)&&g.isIdentifier(t.expression)){let s=t.expression.text,o=r.get(s);o&&!n.some(i=>i.from===e&&i.to===s&&i.toSpecifier===o)&&n.push({from:e,to:s,toSpecifier:o})}g.forEachChild(t,s=>Qe(s,e,r,n))}function qe(t,e){if(e.length===0)return"ui";let r=!1;return t.walk(n=>{if(n.type==="rule")return r=!0,!1}),r?"ui":"barrel"}function _n(t,e){let r=[],n=/@require\s+['"]([^'"]+)['"]/g,s=n.exec(t);for(;s!==null;){let i=s[1];i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"require"}),s=n.exec(t)}let o=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(s=o.exec(t);s!==null;){let i=s[1];i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),s=o.exec(t)}return r}function On(t,e){if(e.length===0)return"ui";try{let r=tt("stylus");return new r.Parser(t).parse().nodes.some(o=>o.constructor.name!=="Import")?"ui":"barrel"}catch{return t.replace(/^\s*@?(?:require|import)\b.*/gm,"").trim().length>0?"ui":"barrel"}}function ge(t,e){let r=G(t);if(r==="stylus"){let o=_n(e,t);return{imports:o,exports:[],tags:[],category:On(e,o)}}if(r==="scss"){let{imports:o,root:i,exports:a,tags:c}=Me(e,t);return{imports:o,exports:a,tags:c,category:qe(i,o)}}if(r==="less"){let{imports:o,root:i,exports:a,tags:c}=Ne(e,t);return{imports:o,exports:a,tags:c,category:qe(i,o)}}let{imports:n,root:s}=Ae(e,t);return{imports:n,exports:[],tags:[],category:qe(s,n)}}for(let[t,e]of[["javascript",(r,n)=>nr(r,n,"javascript")],["typescript",(r,n)=>nr(r,n,"typescript")],["css",ge],["scss",ge],["less",ge],["stylus",ge],["coffeescript",kn],["livescript",En],["lua",Tn],["python",In],["go",Fn],["gherkin",Yt],["markdown",Nn]])q(t,e);async function jn(t,e){let r=G(t),n=nn(r);return n?n(t,e):{imports:[],exports:[],tags:[],category:"other"}}import Wn from"path";function $n(t,e){for(let r of t.values()){let n=e.get(r.path);n!==void 0&&(r.coveragePct=n)}}function Bn(t,e){for(let r of t)if(r.isExternal){let n=r.rawSpecifier.startsWith("@")?r.rawSpecifier.split("/").slice(0,2).join("/"):r.rawSpecifier.split("/")[0];n&&!e.some(s=>s.name===n)&&e.push({name:n,kind:"library"})}}function Un(t){for(let e of t.values())if(e.category==="test")for(let r of e.imports){if(r.isExternal||!r.toPath)continue;let n=t.get(r.toPath);n&&(n.category!=="logic"&&n.category!=="barrel"||(n.testedBy??=[],n.testedBy.includes(e.path)||n.testedBy.push(e.path)))}}function Kn(t){for(let e of t.values())if(e.type==="markdown")for(let r of e.imports){if(r.isExternal||!r.toPath)continue;let n=t.get(r.toPath);!n||n===e||(n.documentedBy??=[],n.documentedBy.includes(e.path)||n.documentedBy.push(e.path),n.category==="logic"&&(n.lastCommitAt??0)>(e.lastCommitAt??0)&&(e.staleFor??=[],e.staleFor.includes(n.path)||e.staleFor.push(n.path)))}}function zn(t){return Math.round(t*1e4)/1e4}function Jn(t){for(let e of t.values()){let r=[];for(let n of e.imports){if(n.isExternal||!n.toPath)continue;let s=t.get(n.toPath);if(!s||s.exports.length===0)continue;let o;if(n.symbols===void 0){if(n.type==="side-effect")continue;o=1}else n.symbols.includes("*")?o=1:o=n.symbols.length/s.exports.length;n.exportUsageRatio=zn(Math.min(1,o)),r.push(n.exportUsageRatio)}r.length>0&&(e.avgExportUsage=zn(r.reduce((n,s)=>n+s,0)/r.length),e.maxExportUsage=Math.max(...r))}}function or(t,e,r){e&&(t.some(n=>n.name===e&&n.kind===r)||t.push({name:e,kind:r}))}function Ac(t,e){let r=e.toPath,n=Wn.basename(r,Wn.extname(r)).replace(/\.(test|spec)$/,"");or(t.tags,n,"import")}function Nc(t,e){if(!(!e.symbols||e.symbols.includes("*")))for(let r of e.symbols)or(t.tags,r,"import")}function Mc(t,e,r){let n=r.get(e.toPath);if(!(!n||n.category==="test"))for(let s of n.tags)s.kind==="comment-marker"&&or(t.tags,s.name,"comment-marker")}function Vn(t){for(let e of t.values())if(e.category==="test")for(let r of e.imports)!r.toPath||r.isExternal||(Ac(e,r),Nc(e,r),Mc(e,r,t))}import Ye from"fs";import _ from"path";import qn from"fs";import Z from"path";var de=class{extensions=[".go"];goModCache=new Map;resolve(e,r,n,s){let{mod:o,replaces:i}=this.readGoMod(n);if(!o)return null;let a=this.applyReplace(r,i,n);if(a!==void 0)return Qn(a);if(r!==o&&!r.startsWith(`${o}/`))return null;let c=r.slice(o.length).replace(/^\//,"");return c?Qn(Z.join(n,c)):null}readGoMod(e){let r=this.goModCache.get(e);if(r!==void 0)return r;let n={mod:null,replaces:new Map};try{let s=qn.readFileSync(Z.join(e,"go.mod"),"utf-8"),o=Ic(s,e);return this.goModCache.set(e,o),o}catch{return this.goModCache.set(e,n),n}}applyReplace(e,r,n){for(let[s,o]of r){if(e===s)return o;if(e.startsWith(`${s}/`)){let i=e.slice(s.length+1);return Z.join(o,i)}}}};function Ic(t,e){let r=t.split(`
27
- `),n=null,s=new Map,o=!1;for(let i of r){let a=i.trim();if(a.startsWith("module ")){n=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){o=!0;continue}if(o&&a===")"){o=!1;continue}if(o&&a.includes("=>")){Hn(a,e,s);continue}!o&&/^replace\s+/.test(a)&&a.includes("=>")&&Hn(a.replace(/^replace\s+/,""),e,s)}return{mod:n,replaces:s}}function Hn(t,e,r){let[n,s]=t.split("=>").map(a=>a.trim());if(!n||!s)return;let o=n.split(/\s+/)[0];if(!s.startsWith(".")&&!s.startsWith("/"))return;let i=Z.isAbsolute(s)?s:Z.resolve(e,s);r.set(o,i)}function Qn(t){let e;try{e=qn.readdirSync(t,{withFileTypes:!0})}catch{return null}let r=e.filter(n=>n.isFile()&&n.name.endsWith(".go")&&!n.name.endsWith("_test.go")).map(n=>({path:Z.join(t,n.name),isExternal:!1})).sort((n,s)=>n.path.localeCompare(s.path));return r.length>0?r:null}import Dc from"fs";import ir from"path";var he=class{extensions=[".lua"];resolve(e,r,n,s){let o=r.replace(/\./g,ir.sep),i=[n,ir.join(n,"lib")];for(let a of i){if(!Dc.existsSync(a))continue;let c=s(ir.join(a,"_dummy.lua"),o);if(c)return[c]}return null}};import Rc from"path";var ye=class{extensions=[".md",".mdx"];resolve(e,r,n,s){let o=s(Rc.join(n,"_dummy"),`./${r}`);return o?[o]:null}};import Gc from"fs";import ar from"path";var xe=class{extensions=[".py"];resolve(e,r,n,s){let o=r.replace(/\./g,ar.sep),i=ar.join(n,`${o}.py`);if(Yn(i))return[{path:i,isExternal:!1}];let a=ar.join(n,o,"__init__.py");return Yn(a)?[{path:a,isExternal:!1}]:null}};function Yn(t){try{return Gc.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}import Xn from"path";var Lc=["~","http://","https://","//","data:","sass:"],Se=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,r,n,s){if(Lc.some(l=>r.startsWith(l)))return null;let o=s(e,r);if(o)return[o];let i=Xn.dirname(r),a=Xn.basename(r),c=i==="."?`_${a}`:`${i}/_${a}`,p=s(e,c);return p?[p]:null}};var J=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 xe,new he,new de,new Se,new ye]}rootDir;workspaceMap;tsconfigSearchPaths;pathAliases;langResolvers;resolveAll(e,r){let n=this.resolvePathAlias(r);if(n)return[n];if(r.startsWith(".")||r.startsWith("/")){let i=this.resolveLocalPath(e,r);return i?[i]:[]}let s=(i,a)=>this.resolveLocalPath(i,a);for(let i of this.langResolvers)if(i.extensions.some(a=>e.endsWith(a))){let a=i.resolve(e,r,this.rootDir,s);if(a)return a}let o=this.resolveWorkspaceImport(r);return o?[o]:[{path:r,isExternal:!0}]}resolve(e,r){let n=this.resolvePathAlias(r);if(n)return n;if(r.startsWith(".")||r.startsWith("/"))return this.resolveLocalPath(e,r);let s=(i,a)=>this.resolveLocalPath(i,a);for(let i of this.langResolvers)if(i.extensions.some(a=>e.endsWith(a))){let a=i.resolve(e,r,this.rootDir,s);if(a)return a[0]??null}let o=this.resolveWorkspaceImport(r);return o||{path:r,isExternal:!0}}resolveLocalPath(e,r){let n=_.dirname(e),s=r.startsWith("/")?r:_.resolve(n,r),o=!s.startsWith(this.rootDir),i=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature",".md",".mdx"],a=s.match(/\.(js|mjs|cjs)$/);if(a){let c=s.slice(0,-a[0].length);for(let p of[".ts",".tsx"]){let l=this.tryExtensions(c,p,o);if(l)return l}}for(let c of i){let p=this.tryExtensions(s,c,o);if(p)return p}return o?{path:s,isExternal:!0}:null}tryExtensions(e,r,n){let s=e+r;if(this.isFile(s))return{path:s,isExternal:n};let o=_.join(e,`index${r}`);if(this.isFile(o))return{path:o,isExternal:n};if(r===".py"){let i=_.join(e,"__init__.py");if(this.isFile(i))return{path:i,isExternal:n}}return null}isFile(e){try{return Ye.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){if(this.pathAliases)for(let r in this.pathAliases){let n=this.matchAliasPattern(r,e),s=this.pathAliases[r];if(n&&s){let o=this.tryAliasSubstitutions(s,n[1]||"");if(o)return o}}for(let r of this.tsconfigSearchPaths){let n=_.join(r,"tsconfig.json");if(Ye.existsSync(n))try{let o=JSON.parse(Ye.readFileSync(n,"utf-8")).compilerOptions?.paths;if(!o)continue;for(let i in o){let a=this.matchAliasPattern(i,e);if(a){let c=this.tryAliasSubstitutions(o[i],a[1]||"",r);if(c)return c}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,r){let n=this.aliasRegexCache.get(e);if(!n){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");n=new RegExp(`^${s}$`),this.aliasRegexCache.set(e,n)}return r.match(n)}tryAliasSubstitutions(e,r,n=this.rootDir){let s=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let o of e){let i=o.replace("*",r),a=_.resolve(n,i);for(let c of s){let p=this.tryExtensions(a,c,!1);if(p)return p}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[r,n]of this.workspaceMap){if(e!==r&&!e.startsWith(`${r}/`))continue;let s=e.slice(r.length),o={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:r};if(!s){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let c=_.join(n,a);try{if(Ye.statSync(c,{throwIfNoEntry:!1})?.isFile())return{...o,path:c}}catch{}}return{...o,path:n}}let i=this.resolveLocalPath(_.join(n,"_dummy"),s.slice(1));return i?{...o,path:i.path}:null}return null}};var Oc=["tests","test","__tests__","specs","spec"],Zn=new Set(["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"]),jc=20;function Wc(t,e){if(t.length===0)return e;let r=t.map(i=>T.dirname(i).split(T.sep)),n=r[0]??[];for(let i of r.slice(1)){let a=0;for(;a<n.length&&a<i.length&&n[a]===i[a];)a++;n=n.slice(0,a)}let s=n.join(T.sep)||T.sep,o=T.relative(e,s);return o.startsWith("..")||T.isAbsolute(o)?e:s}var ve=class{constructor(e,r=null,n,s,o=!1,i=new Map,a=!0){this.rootDir=e;this.enableGitStats=o;this.coverageMap=i;this.parallelParsing=a;this.previousGraph=r,this.resolver=n||new J(e),this.lockFile=Tr(e),s&&(this.progressCallback=s)}rootDir;enableGitStats;coverageMap;parallelParsing;graph={nodes:new Map};visited=new Set;queue=[];previousGraph=null;resolver;lockFile=null;progressCallback;pool=null;gitStatsMap=null;async build(e){let r=e.map(n=>T.isAbsolute(n)?n:T.resolve(this.rootDir,n));await this.initPool(),this.enableGitStats&&(this.gitStatsMap=xn(this.rootDir));try{for(let n of r)this.enqueue(n);return await this.drain(),await this.processTestFiles(Wc(r,this.rootDir)),await this.processDocFiles(),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
23
+ `;return`${l+d+m+i}
24
+ ${p}`}};function ia(t){let e=t.split(`
25
+ `),r=-1;return e.forEach((s,o)=>{(s.trimStart().startsWith("import ")||s.trimStart().startsWith("from "))&&(r=o)}),r<0?0:e.slice(0,r+1).reduce((s,o)=>s+o.length+1,0)}import un from"path";import fn from"typescript";var aa=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,Ve=class{name="vitest";canHandle(e){return D.has(un.extname(e).toLowerCase())}apply(e,r,n){let s=r.replace(aa,""),o=fn.createSourceFile(un.basename(e),s,fn.ScriptTarget.Latest,!0),i=_t(o),[a]=i;if(!a)return s;let c=Ot(a,"tags",o),l=[...n].sort();if(c!==null&&JSON.stringify([...c].sort())===JSON.stringify(l))return s;let p=i.flatMap(m=>{let d=n.length===0?Wt(m,"tags",o):jt(m,"tags",Bt(l),o);return d?[d]:[]});return p.length>0?zt(s,p):s}};var mn={vitest:()=>new Ve,playwright:()=>new Ke,cypress:()=>new ze,jest:()=>new Ue},ca={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function la(t){let e=He.createSourceFile("detect.ts",t,He.ScriptTarget.Latest,!0);for(let r of e.statements){if(!He.isImportDeclaration(r)||!He.isStringLiteral(r.moduleSpecifier))continue;let n=ca[r.moduleSpecifier.text];if(n)return n}return null}var Qt=class{constructor(e,r,n){this.rootDir=e;this.defaultFramework=r;this.frameworkOverrides=n}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return D.has(Ht.extname(e).toLowerCase())}apply(e,r,n){let s=la(r)??this.matchOverride(e)??this.defaultFramework;return(mn[s]??mn.vitest)().apply(e,r,n)}matchOverride(e){let r=Ht.relative(this.rootDir,e).split(Ht.sep).join("/");for(let[n,s]of this.frameworkOverrides)if(pn(n,r))return s;return null}};function gn(t="vitest",e={},r=process.cwd()){return[new Be,new Je,new $e,new Qt(r,t,Object.entries(e))]}function dn(t,e){return e.find(r=>r.canHandle(t))??null}var ua=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,fa=new Set(["import"]),ma=new Set(["common","fixture","fixtures","helper","helpers","index","main","mock","mocks","setup","shared","spec","test","tests","types","util","utils"]);async function ga(t,e,r,n){let s;try{s=await hn.readFile(t,"utf8")}catch(a){return{path:t,status:"error",error:String(a)}}let o=dn(t,n);if(!o)return{path:t,status:"unchanged"};let i=o.apply(t,s,e);return i===s?{path:t,status:"unchanged"}:(r||await hn.writeFile(t,i,"utf8"),{path:t,status:"updated"})}async function qt(t,e,r){let n=se(e),s=n.tagApplier?.framework??"vitest",o=n.tagApplier?.frameworkOverrides??{},i=gn(s,o,e),a={updated:0,unchanged:0,errors:0,files:[]};for(let c of t.nodes.values()){if(c.category!=="test")continue;let l=new Set,p=[];for(let h of c.tags)fa.has(h.kind)&&ua.test(h.name)&&(ma.has(h.name.toLowerCase())||l.has(h.name)||(l.add(h.name),p.push(h.name)));p.sort();let m=pa.resolve(e,c.path),d=await ga(m,p,r.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 Qe=class{isTestNode(e){return e.category==="test"||e.tags.some(r=>r.name==="test")}};import ve from"fs";import A from"path";import $c from"piscina";import{execFileSync as Yt}from"child_process";var qe=class{getChangedFiles(){try{let r=[["diff","--name-only"],["diff","--cached","--name-only"],["ls-files","--others","--exclude-standard"]].flatMap(n=>{try{return Yt("git",n,{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
26
+ `).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),[]}}},yn="%x00%H%x09%ae%x09%at",xn=256*1024*1024;function Sn(t,e){let r="",n=0;for(let s of t.split(`
27
+ `)){if(s.startsWith("\0")){let[,c,l]=s.slice(1).split(" ");r=c??"",n=l?Number(l)*1e3:0;continue}if(s==="")continue;let o=s.split(" "),i=o[0];if(!i)continue;let a=i.startsWith("R")||i.startsWith("C")?o[2]:o[1];a&&e(a,r,n)}}function bn(t){let e=new Map;try{let r=Yt("git",["-C",t,"log","--since=90 days ago","--name-status","-M",`--format=${yn}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:xn});Sn(r,(n,s,o)=>{let i=e.get(n);if(i){i.commitCount90d+=1;return}e.set(n,{commitCount90d:1,lastAuthor:s||void 0,lastCommitAt:o||void 0})})}catch{return e}try{let r=Yt("git",["-C",t,"log","--name-status","-M",`--format=${yn}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:xn});Sn(r,(n,s,o)=>{e.has(n)||e.set(n,{commitCount90d:0,lastAuthor:void 0,lastCommitAt:o||void 0})})}catch{}return e}import kn from"path";function L(t){switch(kn.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 M(t){let e=kn.extname(t).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}import da from"coffeescript";function _(t){return t.startsWith("'")||t.startsWith('"')?t.slice(1,-1):t}function X(t){let e=new Set,r=/@tag\s+([a-zA-Z0-9_-]+)/g,n=r.exec(t);for(;n!==null;)n[1]&&e.add(n[1]),n=r.exec(t);return e}function Z(t,e){let r=t.toLowerCase();return r.includes(".test.")||r.includes(".spec.")||e.has("test")?"test":"logic"}function wn(t){if(t){if(typeof t.originalValue=="string")return t.originalValue;if(typeof t.value=="string")return _(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 ha(t,e){let r=wn(e.source);return r?{fromPath:t,toPath:"",rawSpecifier:r,isStyle:M(r),type:"static"}:null}function ya(t,e){let r=e.variable?.base?.value==="require",n=wn(e.args?.[0]?.base);return!r||!n?null:{fromPath:t,toPath:"",rawSpecifier:n,isStyle:M(n),type:"require"}}function vn(t,e){if(e)return[{name:e}];let r=t.value;if(r?.constructor?.name==="Class"){let s=$(r.variable);return s?[{name:s}]:[]}if(r?.base?.constructor?.name==="Obj"&&Array.isArray(r.base.properties))return r.base.properties.map(s=>$(s.variable)??$(s)).filter(s=>!!s).map(s=>({name:s}));let n=$(r);return n?[{name:n}]:[]}function xa(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 Sa(t,e,r,n){let s=e.constructor?.name;if(s==="ImportDeclaration"){let o=ha(t,e);o&&r.push(o)}else if(s==="Call"){let o=ya(t,e);o&&r.push(o)}else if(s==="Assign"){let o=$(e.variable?.base),i=e.variable?.properties?.[0]?.name?.value;o==="module"&&i==="exports"?n.push(...vn(e,void 0)):o==="exports"&&typeof i=="string"&&n.push(...vn(e,i))}else s==="ExportNamedDeclaration"&&e.clause?n.push(...xa(e.clause)):s==="ExportDefaultDeclaration"&&n.push({name:"default"})}function Xt(t,e,r,n){if(!(!e||typeof e!="object")){Sa(t,e,r,n);for(let s in e){if(s==="locationData")continue;let o=e[s];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let i of o)Xt(t,i,r,n);else Xt(t,o,r,n)}}}function Cn(t,e){let r=X(e),n=Z(t,r),s=[],o=[];try{Xt(t,da.nodes(e),s,o)}catch{}let i=new Set,a=o.filter(c=>i.has(c.name)?!1:(i.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(r).map(c=>({name:c,kind:"comment-marker"})),category:n}}import{AstBuilder as ba,GherkinClassicTokenMatcher as ka,Parser as va}from"@cucumber/gherkin";import{IdGenerator as wa}from"@cucumber/messages";var Ca=wa.uuid();function Zt(t,e){let r=new Set;try{let n=new ba(Ca),s=new ka,i=new va(n,s).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(c=>{r.add(c.name.startsWith("@")?c.name.slice(1):c.name)}),a.scenario.examples.forEach(c=>{c.tags.forEach(l=>{r.add(l.name.startsWith("@")?l.name.slice(1):l.name)})})),a.rule&&a.rule.children.forEach(c=>{c.scenario&&c.scenario.tags.forEach(l=>{r.add(l.name.startsWith("@")?l.name.slice(1):l.name)})})}))}catch(n){console.warn(`[GherkinParser] Failed to parse ${t}:`,n)}return{imports:[],exports:[],tags:Array.from(r).map(n=>({name:n,kind:"comment-marker"})),category:"test"}}Y("gherkin",Zt);import Ta from"path";import{parser as Pa}from"@lezer/go";function U(t){let e=[],r=t.firstChild;for(;r;)e.push(r),r=r.nextSibling;return e}function ge(t,e){let r=1;for(let n=0;n<e&&n<t.length;n++)t[n]===`
28
+ `&&r++;return r}function Fa(t,e){let r=1;function n(s){switch(s.type.name){case"IfStatement":case"ForStatement":r++;break;case"Case":{s.firstChild?.type.name==="case"&&r++;break}case"LogicOp":{let i=e.slice(s.from,s.to);(i==="&&"||i==="||")&&r++;break}}let o=s.firstChild;for(;o;)n(o),o=o.nextSibling}return n(t),r}function Ea(t,e){let r=0;function n(s,o,i){let a=s.type.name;if(a==="IfStatement"){r+=i?1:1+o;let p=U(s),m=i?o:o+1,d=p[1];d&&d.type.name!=="Block"&&n(d,m,!1);let h=p.find(y=>y.type.name==="Block");h&&n(h,m,!1);let S=p.findIndex(y=>y.type.name==="else");if(S>=0){let y=p[S+1];y?.type.name==="IfStatement"?n(y,o,!0):y&&(r+=1,n(y,o+1,!1))}return}if(a==="ForStatement"||a==="SwitchStatement"||a==="SelectStatement"){r+=1+o;let p=s.firstChild;for(;p;)n(p,o+1,!1),p=p.nextSibling;return}if(a==="LogicOp"){let p=e.slice(s.from,s.to);(p==="&&"||p==="||")&&(r+=1)}if(o>0&&a==="FunctionLiteral"){r+=1+o;let p=s.firstChild;for(;p;)n(p,o+1,!1),p=p.nextSibling;return}let l=s.firstChild;for(;l;)n(l,o,!1),l=l.nextSibling}return n(t,0,!1),r}function Ye(t,e){return{complexity:Fa(t,e),cognitiveComplexity:Ea(t,e)}}function er(t,e){let n=t.getChild("Parameters")?.getChild("Parameter"),s=n?.getChild("TypeName")??n?.getChild("PointerType")?.getChild("TypeName");return s?e.slice(s.from,s.to):void 0}function Fn(t,e){let r=[],n=t.cursor();do if(n.name==="FunctionDecl"){let s=n.node.getChild("DefName");if(s){let o=e.slice(s.from,s.to),{complexity:i,cognitiveComplexity:a}=Ye(n.node,e);r.push({name:o,line:ge(e,n.from),complexity:i,cognitiveComplexity:a})}}else if(n.name==="MethodDecl"){let s=n.node.getChild("FieldName");if(s){let o=e.slice(s.from,s.to),i=er(n.node,e),a=i?`${i}.${o}`:o,{complexity:c,cognitiveComplexity:l}=Ye(n.node,e);r.push({name:a,line:ge(e,n.from),complexity:c,cognitiveComplexity:l})}}while(n.next());return r}var Aa=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,Na=/^\/\/go:build\s+(.+)$/,Ia=/^\/\/\s*\+build\s+(.+)$/;function Tn(t,e){let r=[],n=new Map,s=new Set,o=new Set,i=new Map,a=Pa.parse(e),c=a.cursor();do switch(c.name){case"LineComment":{let b=e.slice(c.from,c.to),x=b.match(Aa);x?.[1]&&s.add(x[1]);let k=b.match(Na);k&&En(k[1],o);let T=b.match(Ia);T&&En(T[1],o);break}case"ImportSpec":{let b=c.node.getChild("String");if(b){let k=e.slice(b.from,b.to).slice(1,-1);r.push({fromPath:t,toPath:"",rawSpecifier:k,isExternal:!0,isStyle:!1,type:"static"});let T=c.node.getChild("DefName"),N=T?e.slice(T.from,T.to):k.split("/").pop();N&&N!=="_"&&N!=="."&&i.set(N,k)}break}case"FunctionDecl":case"MethodDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let b=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(b){let x=e.slice(b.from,b.to);x!=="_"&&/^[A-Z]/.test(x)&&!n.has(x)&&n.set(x,{name:x})}break}}while(c.next());let l=r.some(b=>b.rawSpecifier==="testing"),p=Ta.basename(t).endsWith("_test.go")||s.has("test")||l?"test":"logic",m=new Set([...s,...o]),{complexity:d,cognitiveComplexity:h}=Ye(a.topNode,e),S=Fn(a,e),y=p==="test"?[]:Ma(a,e,i);return{imports:r,exports:Array.from(n.values()),tags:Array.from(m).map(b=>({name:b,kind:"comment-marker"})),category:p,rawCallEdges:y,complexity:d,cognitiveComplexity:h,...S.length>0?{functions:S}:{}}}function Ma(t,e,r){let n=[];function s(i,a){if(i.type.name==="CallExpr"){let l=i.firstChild;if(l?.type.name==="SelectorExpr"){let p=l.firstChild,m=l.getChild("FieldName");if(p?.type.name==="VariableName"&&m){let d=e.slice(p.from,p.to),h=r.get(d);if(h){let S=e.slice(m.from,m.to);n.push({from:a,to:S,toSpecifier:h})}}}}let c=i.firstChild;for(;c;)s(c,a),c=c.nextSibling}let o=t.cursor();do if(o.name==="FunctionDecl"){let i=o.node.getChild("DefName"),a=o.node.getChild("Block");if(i&&a){let c=e.slice(i.from,i.to);/^[A-Z]/.test(c)&&s(a,c)}}else if(o.name==="MethodDecl"){let i=o.node.getChild("FieldName"),a=o.node.getChild("Block");if(i&&a){let c=e.slice(i.from,i.to),l=er(o.node,e);s(a,l?`${l}.${c}`:c)}}while(o.next());return n}function En(t,e){for(let r of t.split(/[\s,&|!()]+/)){let n=r.trim();n&&n!=="ignore"&&e.add(n)}}import Da from"livescript";function K(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function Ra(t){if(!t)return[];if(t.constructor?.name==="Class"){let r=K(t.title);return r?[{name:r}]:[]}if(t.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(r=>K(r.key)??K(r.val)).filter(r=>!!r).map(r=>({name:r}));let e=K(t);return e?[{name:e}]:[]}function Ga(t){let e=t.constructor?.name||t.type;if(e==="Assign"&&t.left?.constructor?.name==="Chain"){let r=t.left,n=K(r.head),o=r.tails?.[0]?.key?.name;if(n==="module"&&o==="exports")return Ra(t.right);if(n==="exports"&&typeof o=="string")return[{name:o}];if(r.head?.verb==="out"&&typeof o=="string")return[{name:o}]}if(e==="Import"&&t.left?.verb==="out"){let r=t.right;if(r?.constructor?.name==="Obj"&&Array.isArray(r.items))return r.items.map(n=>K(n.val)??K(n.key)).filter(n=>!!n).map(n=>({name:n}))}return[]}var La=new Set(["first_line","first_column","last_line","last_column","line","column"]);function _a(t,e){let r=t.constructor?.name||t.type;if(r==="Import"){let n=t.right?.value;if(typeof n=="string"){let s=_(n);return{fromPath:e,toPath:"",rawSpecifier:s,isStyle:M(s),type:"static"}}}if(r==="Chain"&&t.head?.value==="require"){let n=t.tails?.[0];if(n?.constructor?.name==="Call"||n?.type==="Call"){let s=n.args?.[0]?.value;if(typeof s=="string"){let o=_(s);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:M(o),type:"require"}}}}return null}function tr(t,e,r){if(!t||typeof t!="object")return[];let n=[],s=_a(t,e);s&&n.push(s),r.push(...Ga(t));for(let o in t){if(La.has(o))continue;let i=t[o];if(!(!i||typeof i!="object"))if(Array.isArray(i))for(let a of i)n.push(...tr(a,e,r));else n.push(...tr(i,e,r))}return n}function Pn(t,e){let r=X(e),n=Z(t,r),s=[],o=[];try{s=tr(Da.ast(e),t,o)}catch{}let i=new Set,a=o.filter(c=>i.has(c.name)?!1:(i.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(r).map(c=>({name:c,kind:"comment-marker"})),category:n}}import Oa from"luaparse";function ja(t,e){let r=[];function n(s){if(!(!s||typeof s!="object")){if((s.type==="CallExpression"||s.type==="StringCallExpression")&&s.base?.type==="Identifier"&&s.base?.name==="require"){let o;if(s.type==="CallExpression"){let i=s.arguments?.[0];i?.type==="StringLiteral"&&(o=_(i.raw))}else if(s.type==="StringCallExpression"){let i=s.argument;i?.type==="StringLiteral"&&(o=_(i.raw))}o&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:M(o),type:"require"})}for(let o in s){if(o==="loc")continue;let i=s[o];if(i&&typeof i=="object")if(Array.isArray(i))for(let a of i)n(a);else n(i)}}}return n(t),r}function Wa(t){let e=new Set;for(let r of t)r.type==="LocalStatement"&&r.variables.forEach((n,s)=>{r.init[s]?.type==="TableConstructorExpression"&&e.add(n.name)});return e}function za(t){let e=t[t.length-1];if(e?.type!=="ReturnStatement")return[];let r=e.arguments[0];if(r?.type!=="TableConstructorExpression")return[];let n=[];for(let s of r.fields)s.type==="TableKeyString"&&n.push({name:s.key.name});return n}function Ba(t){let e=t.body,r=Wa(e),n=za(e);for(let o of e)if(o.type==="FunctionDeclaration")o.identifier?.type==="MemberExpression"?o.identifier.base.type==="Identifier"&&r.has(o.identifier.base.name)&&n.push({name:o.identifier.identifier.name}):o.identifier?.type==="Identifier"&&!o.isLocal&&n.push({name:o.identifier.name});else if(o.type==="AssignmentStatement")for(let i of o.variables)i.type==="MemberExpression"&&i.base.type==="Identifier"&&r.has(i.base.name)&&n.push({name:i.identifier.name});let s=new Set;return n.filter(o=>s.has(o.name)?!1:(s.add(o.name),!0))}function An(t,e){let r=X(e),n=Z(t,r),s=[],o=[];try{let i=Oa.parse(e);s=ja(i,t),o=Ba(i)}catch{}return{imports:s,exports:o,tags:Array.from(r).map(i=>({name:i,kind:"comment-marker"})),category:n}}var $a=["http://","https://","mailto:","//"],Ua="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",Ka=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${Ua})\\b`,"g"),Nn;async function Ja(){return Nn??=(async()=>{let{unified:t}=await import("unified"),e=(await import("remark-parse")).default;return t().use(e)})(),Nn}function Va(t){let e=t.trim();return e.length===0||e.startsWith("#")||$a.some(r=>e.startsWith(r))}function Ha(t,e){let r=t.match(Ka);return r?r.map(n=>({fromPath:e,toPath:"",rawSpecifier:n,isStyle:!1,type:"static"})):[]}function In(t,e,r){if(t.type==="link"&&typeof t.url=="string"&&!Va(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(...Ha(t.value,e)),Array.isArray(t.children))for(let n of t.children)In(n,e,r)}async function Mn(t,e){let n=(await Ja()).parse(e),s=[];In(n,t,s);let o=new Set;return{imports:s.filter(a=>o.has(a.rawSpecifier)?!1:(o.add(a.rawSpecifier),!0)),exports:[],tags:[],category:"other"}}import Ya from"path";import{parser as Xa}from"@lezer/python";function Qa(t){let e=1;function r(n){switch(n.type.name){case"IfStatement":{e+=U(n).filter(o=>o.type.name==="if"||o.type.name==="elif").length;break}case"TryStatement":{e+=U(n).filter(o=>o.type.name==="except").length;break}case"ForStatement":case"WhileStatement":case"ConditionalExpression":e++;break;case"and":case"or":e++;break}let s=n.firstChild;for(;s;)r(s),s=s.nextSibling}return r(t),e}function qa(t){let e=0;function r(n,s){let o=n.type.name;if(o==="IfStatement"){let c=U(n),l=0,p=0;for(;p<c.length;){let m=c[p];if(m?.type.name==="if"||m?.type.name==="elif"){let d=l>0;e+=d?1:1+s;let h=d?s:s+1,S=c[p+1],y=c[p+2];S&&r(S,h),y&&r(y,h),l++,p+=3}else if(m?.type.name==="else"){e+=1;let d=c[p+1];d&&r(d,s+1),p+=2}else p++}return}if(o==="TryStatement"){let c=U(n),l=0;for(;l<c.length;){let p=c[l];if(p?.type.name==="except"){for(e+=1+s,l++;l<c.length&&c[l]?.type.name!=="Body";)r(c[l],s),l++;l<c.length&&(r(c[l],s),l++)}else p?.type.name==="Body"&&r(p,s),l++}return}if(o==="ForStatement"||o==="WhileStatement"){e+=1+s;let c=n.firstChild;for(;c;)r(c,s+1),c=c.nextSibling;return}if((o==="ConditionalExpression"||o==="and"||o==="or")&&(e+=1),s>0&&(o==="FunctionDefinition"||o==="LambdaExpression")){e+=1+s;let c=n.firstChild;for(;c;)r(c,s+1),c=c.nextSibling;return}let a=n.firstChild;for(;a;)r(a,s),a=a.nextSibling}return r(t,0),e}function rr(t){return{complexity:Qa(t),cognitiveComplexity:qa(t)}}function Dn(t,e){let r=[];function n(i,a){let{complexity:c,cognitiveComplexity:l}=rr(i);r.push({name:a,line:ge(e,i.from),complexity:c,cognitiveComplexity:l})}function s(i){let a=i.firstChild;for(;a;)o(a),a=a.nextSibling}function o(i){if(i.type.name==="ClassDefinition"){let a=i.getChild("VariableName"),c=a?e.slice(a.from,a.to):void 0,l=i.getChild("Body");if(l){let p=l.firstChild;for(;p;){if(p.type.name==="FunctionDefinition"){let m=p.getChild("VariableName"),d=m?e.slice(m.from,m.to):void 0;d&&n(p,c?`${c}.${d}`:d),s(p)}else o(p);p=p.nextSibling}}return}if(i.type.name==="FunctionDefinition"){let a=i.getChild("VariableName");a&&n(i,e.slice(a.from,a.to)),s(i);return}s(i)}return o(t.topNode),r}var Za=new Set(["pytest","unittest","nose","hypothesis"]);function Rn(t,e){let r=[],n=[],s=new Set,o=Ya.basename(t).toLowerCase(),i=Xa.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]&&s.add(h[1]);break}case"ImportStatement":{for(let h of ec(a.node,e,t))r.push(h);break}case"FunctionDefinition":case"ClassDefinition":{let h=a.node.parent;if(h?.name==="Script"||h?.name==="DecoratedStatement"&&h.parent?.name==="Script"){let y=a.node.getChild("VariableName");y&&n.push({name:e.slice(y.from,y.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let h=a.node.firstChild;h?.name==="VariableName"&&n.push({name:e.slice(h.from,h.to)})}break}}while(a.next());let c=ic(o,r,s);c==="test"&&s.add("test");let{complexity:l,cognitiveComplexity:p}=rr(i.topNode),m=Dn(i,e),d=c==="test"?[]:oc(i,e);return{imports:r,exports:n,tags:Array.from(s).map(h=>({name:h,kind:"comment-marker"})),category:c,rawCallEdges:d,complexity:l,cognitiveComplexity:p,...m.length>0?{functions:m}:{}}}function ec(t,e,r){let n=t.firstChild;return n?n.name==="from"?tc(t,e,r):rc(t,e,r):[]}function tc(t,e,r){let n=t.firstChild;if(!n)return[];let s=n.nextSibling;for(;s&&s.name!=="import";)s=s.nextSibling;if(!s)return[];let o=e.slice(n.to,s.from).trim(),i=nc(s.nextSibling,e);if(!i.length)return[];let a=0;for(;a<o.length&&o[a]===".";)a++;let c=o.slice(a);if(a===0)return[de(r,o,i,!0)];let l=a===1?"./":"../".repeat(a-1);return c?[de(r,l+c.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[de(r,l.slice(0,-1),["*"],!1)]:i.map(p=>de(r,l+p,[p],!1))}function rc(t,e,r){let n=[],s=t.firstChild?.nextSibling??null;for(;s;){if(s.name==="VariableName"){let o=e.slice(s.from,s.to);for(;s.nextSibling?.name==="."&&s.nextSibling.nextSibling?.name==="VariableName";)s=s.nextSibling.nextSibling,o+=`.${e.slice(s.from,s.to)}`;s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling),n.push(de(r,o,["*"],!0))}s=s.nextSibling}return n}function nc(t,e){let r=[],n=t;for(;n;)n.name==="*"?r.push("*"):n.name==="VariableName"&&(r.push(e.slice(n.from,n.to)),n.nextSibling?.name==="as"&&(n=n.nextSibling.nextSibling??n.nextSibling)),n=n.nextSibling;return r}function sc(t,e){let r=new Map,n=t.cursor();do{if(n.name!=="ImportStatement")continue;let o=n.node.firstChild;if(o?.type.name!=="from")continue;let i=o.nextSibling;for(;i&&i.type.name!=="import";)i=i.nextSibling;if(!i)continue;let a=e.slice(o.to,i.from).trim(),c=0;for(;c<a.length&&a[c]===".";)c++;let l=a.slice(c),p=c<=1?"./":"../".repeat(c-1),m=i.nextSibling;for(;m;){if(m.type.name==="VariableName"){let d=e.slice(m.from,m.to),h=d;if(m.nextSibling?.type.name==="as"){let y=m.nextSibling.nextSibling;y?.type.name==="VariableName"&&(h=e.slice(y.from,y.to),m=y)}let S=c===0?a:l?p+l.replace(/\./g,"/"):p+d;r.set(h,S)}m=m.nextSibling}}while(n.next());return r}function oc(t,e){let r=sc(t,e),n=[];function s(a,c){if(a.type.name==="CallExpression"&&a.firstChild?.type.name==="VariableName"){let p=a.firstChild,m=e.slice(p.from,p.to),d=r.get(m);d&&n.push({from:c,to:m,toSpecifier:d})}let l=a.firstChild;for(;l;)s(l,c),l=l.nextSibling}function o(a){let c=a.firstChild;for(;c;)i(c),c=c.nextSibling}function i(a){if(a.type.name==="ClassDefinition"){let c=a.getChild("VariableName"),l=c?e.slice(c.from,c.to):void 0,p=a.getChild("Body");if(p){let m=p.firstChild;for(;m;){if(m.type.name==="FunctionDefinition"){let d=m.getChild("VariableName"),h=d?e.slice(d.from,d.to):void 0;h&&s(m,l?`${l}.${h}`:h)}else i(m);m=m.nextSibling}}return}if(a.type.name==="FunctionDefinition"){let c=a.getChild("VariableName");c&&s(a,e.slice(c.from,c.to));return}o(a)}return i(t.topNode),n}function de(t,e,r,n){return{fromPath:t,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:n,type:"static",symbols:r.length>0?r:void 0}}function ic(t,e,r){return t.startsWith("test_")||t.endsWith("_test.py")?"test":t==="conftest.py"||t==="setup.py"?"config":r.has("test")||e.some(n=>Za.has(n.rawSpecifier))?"test":"logic"}import Ln from"path";import g from"typescript";import v from"typescript";function ac(t){let e=1;function r(n){switch(n.kind){case v.SyntaxKind.IfStatement:case v.SyntaxKind.ConditionalExpression:case v.SyntaxKind.ForStatement:case v.SyntaxKind.ForInStatement:case v.SyntaxKind.ForOfStatement:case v.SyntaxKind.WhileStatement:case v.SyntaxKind.DoStatement:case v.SyntaxKind.CatchClause:case v.SyntaxKind.CaseClause:e++;break;case v.SyntaxKind.BinaryExpression:{let s=n.operatorToken.kind;(s===v.SyntaxKind.AmpersandAmpersandToken||s===v.SyntaxKind.BarBarToken||s===v.SyntaxKind.QuestionQuestionToken)&&e++;break}}v.forEachChild(n,r)}return r(t),e}function cc(t){let e=0;function r(n,s,o){if(v.isIfStatement(n)){e+=o?1:1+s;let a=o?s:s+1;r(n.expression,a,!1),r(n.thenStatement,a,!1),n.elseStatement&&(v.isIfStatement(n.elseStatement)?r(n.elseStatement,s,!0):(e+=1,r(n.elseStatement,s+1,!1)));return}if(v.isForStatement(n)||v.isForInStatement(n)||v.isForOfStatement(n)||v.isWhileStatement(n)||v.isDoStatement(n)||v.isSwitchStatement(n)){e+=1+s,v.forEachChild(n,a=>r(a,s+1,!1));return}if(v.isCatchClause(n)){e+=1+s,v.forEachChild(n,a=>r(a,s,!1));return}if(v.isConditionalExpression(n)&&(e+=1),v.isBinaryExpression(n)){let a=n.operatorToken.kind;(a===v.SyntaxKind.AmpersandAmpersandToken||a===v.SyntaxKind.BarBarToken||a===v.SyntaxKind.QuestionQuestionToken)&&(e+=1)}if(s>0&&(v.isFunctionDeclaration(n)||v.isFunctionExpression(n)||v.isArrowFunction(n))){e+=1+s,v.forEachChild(n,a=>r(a,s+1,!1));return}v.forEachChild(n,a=>r(a,s,!1))}return r(t,0,!1),e}function nr(t){return{complexity:ac(t),cognitiveComplexity:cc(t)}}import F from"typescript";var sr=new Set(["test","describe","it"]);function Gn(t,e){lc(t,e),uc(t,e),fc(t,e),mc(t,e)}function lc(t,e){if((F.isFunctionDeclaration(t)||F.isVariableDeclaration(t))&&t.name&&F.isIdentifier(t.name)&&pc(t)){let r;if(F.isFunctionDeclaration(t))r="function";else{let n=t.initializer;r=n&&(F.isArrowFunction(n)||F.isFunctionExpression(n))?"function":"variable"}e.tags.add({name:t.name.text,kind:r})}}function pc(t){if(F.isFunctionDeclaration(t))return F.isSourceFile(t.parent);let e=t.parent?.parent;return!!e&&F.isSourceFile(e.parent)}function uc(t,e){if(!F.isStringLiteral(t))return;let r=t.text.match(/@[\w-]+/g);if(r)for(let n of r)e.tags.add({name:n.substring(1),kind:"comment-marker"})}function fc(t,e){if(!F.isSourceFile(t))return;let r=/@tag\s+([a-zA-Z0-9_-]+)/g,n=t.getFullText(),s=r.exec(n);for(;s!==null;)s[1]&&e.tags.add({name:s[1],kind:"comment-marker"}),s=r.exec(n)}function mc(t,e){if(F.isCallExpression(t)&&gc(t.expression))for(let r of t.arguments)F.isObjectLiteralExpression(r)&&dc(r,e)}function gc(t){return F.isIdentifier(t)?sr.has(t.text):!!(F.isPropertyAccessExpression(t)&&(sr.has(t.name.text)||F.isIdentifier(t.expression)&&sr.has(t.expression.text)))}function dc(t,e){for(let r of t.properties){if(!F.isPropertyAssignment(r)||!F.isIdentifier(r.name)||r.name.text!=="tags"&&r.name.text!=="tag")continue;let{initializer:n}=r,s=F.isArrayLiteralExpression(n)?n.elements.filter(F.isStringLiteral):r.name.text==="tag"&&F.isStringLiteral(n)?[n]:[];for(let o of s)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function or(t,e,r){let n=[],s=new Map,o=new Set,i=g.createSourceFile(t,e,g.ScriptTarget.Latest,!0,r==="typescript"?g.ScriptKind.TSX:g.ScriptKind.JSX),a={filePath:t,imports:n,exports:s,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=y=>{Sc(y,a),g.forEachChild(y,c)};c(i);let l=Nc(t,a);(l==="test"||l==="barrel")&&o.add({name:l,kind:"comment-marker"}),l!=="test"&&Ic(a,i);let p=i.statements[0],m=p?On(p):void 0,{complexity:d,cognitiveComplexity:h}=nr(i),S=hc(i);return{imports:n,exports:Array.from(s.values()),tags:Array.from(o),category:l,rawCallEdges:a.rawCallEdges??[],complexity:d,cognitiveComplexity:h,...S.length>0?{functions:S}:{},...m!==void 0?{description:m}:{}}}function hc(t){let e=[],r=(s,o)=>{let{complexity:i,cognitiveComplexity:a}=nr(o),c=t.getLineAndCharacterOfPosition(o.getStart(t)).line+1;e.push({name:s,line:c,complexity:i,cognitiveComplexity:a})},n=(s,o)=>{if(g.isFunctionDeclaration(s)&&s.name&&s.body?r(s.name.text,s):g.isVariableDeclaration(s)&&g.isIdentifier(s.name)&&s.initializer&&(g.isArrowFunction(s.initializer)||g.isFunctionExpression(s.initializer))?r(s.name.text,s.initializer):o&&g.isMethodDeclaration(s)&&g.isIdentifier(s.name)&&s.body?r(`${o}.${s.name.text}`,s):o&&g.isConstructorDeclaration(s)&&s.body?r(`${o}.constructor`,s):o&&g.isGetAccessorDeclaration(s)&&g.isIdentifier(s.name)&&s.body?r(`${o}.get ${s.name.text}`,s):o&&g.isSetAccessorDeclaration(s)&&g.isIdentifier(s.name)&&s.body&&r(`${o}.set ${s.name.text}`,s),g.isClassDeclaration(s)&&s.name){let i=s.name.text;g.forEachChild(s,a=>n(a,i));return}g.forEachChild(s,i=>n(i,o))};return n(t,void 0),e}function _n(t,e,r,n){let s={name:t},o=On(r);o!==void 0&&(s.doc=o);let i=yc(e);i!==void 0&&(s.flags=i);let a=xc(e,n);return a!==void 0&&(s.signature=a),s}function On(t){let e=g.getJSDocCommentsAndTags(t);for(let r of e)if(g.isJSDoc(r)&&r.comment)return g.getTextOfJSDocComment(r.comment)||void 0}function yc(t){let e=new Set(["deprecated","internal","public","alpha","beta"]),r=g.getJSDocTags(t).map(n=>n.tagName.text).filter(n=>e.has(n));return r.length>0?r:void 0}function xc(t,e){let r=g.createPrinter({removeComments:!0}),n=s=>r.printNode(g.EmitHint.Unspecified,s,e);if(g.isFunctionDeclaration(t)||g.isMethodDeclaration(t)){let s=t.parameters.map(n).join(", "),o=t.type?n(t.type):"void";return`${t.typeParameters?`<${t.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${s}) => ${o}`}if(g.isVariableDeclaration(t)){if(t.type)return n(t.type);if(t.initializer&&(g.isArrowFunction(t.initializer)||g.isFunctionExpression(t.initializer))){let s=t.initializer,o=s.parameters.map(n).join(", "),i=s.type?n(s.type):"unknown";return`(${o}) => ${i}`}return}if(g.isClassDeclaration(t)&&t.name)return`class ${t.name.text}`;if(g.isInterfaceDeclaration(t))return`interface ${t.name.text}`;if(g.isTypeAliasDeclaration(t))return n(t.type);if(g.isEnumDeclaration(t))return`enum ${t.name.text}`}function Sc(t,e){bc(t,e),kc(t,e),wc(t,e),Cc(t,e),Ac(t,e),Gn(t,e)}function bc(t,e){if(!g.isSourceFile(t))return;let r=t.statements.filter(n=>!g.isEmptyStatement(n));e.totalStatements=r.length,e.exportStatements=r.filter(n=>g.isExportDeclaration(n)||g.isExportAssignment(n)||ir(n)).length}function kc(t,e){if(g.isJsxElement(t)||g.isJsxSelfClosingElement(t)||g.isJsxFragment(t)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(g.isFunctionDeclaration(t)||g.isMethodDeclaration(t)||g.isArrowFunction(t)||g.isClassDeclaration(t)||g.isVariableStatement(t)||g.isEnumDeclaration(t)){e.hasTypesOnly=!1;return}g.isExportDeclaration(t)&&!vc(t)&&(e.hasTypesOnly=!1)}function vc(t){return t.isTypeOnly?!0:!t.exportClause||!g.isNamedExports(t.exportClause)?!1:t.exportClause.elements.every(e=>e.isTypeOnly)}function wc(t,e){if(!g.isImportDeclaration(t)||!t.moduleSpecifier||!g.isStringLiteral(t.moduleSpecifier))return;let r=[];if(t.importClause&&(t.importClause.name&&r.push("default"),t.importClause.namedBindings))if(g.isNamedImports(t.importClause.namedBindings))for(let s of t.importClause.namedBindings.elements)r.push(s.name.text);else g.isNamespaceImport(t.importClause.namedBindings)&&r.push("*");let n=r.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.moduleSpecifier.text,isStyle:M(t.moduleSpecifier.text),type:n,symbols:r.length>0?r:void 0})}function Cc(t,e){g.isExportDeclaration(t)?Fc(t,e):g.isExportAssignment(t)?e.exports.set("default",{name:"default"}):ir(t)&&Pc(t,e)}function Fc(t,e){if(t.moduleSpecifier&&g.isStringLiteral(t.moduleSpecifier))Ec(t,t.moduleSpecifier.text,e);else if(t.exportClause&&g.isNamedExports(t.exportClause))for(let r of t.exportClause.elements){let n=r.name.text;e.exports.set(n,{name:n})}}function Ec(t,e,r){let n=Tc(t),s={fromPath:r.filePath,toPath:"",rawSpecifier:e,isStyle:M(e),type:"re-export"};n.length>0&&(s.symbols=n),r.imports.push(s)}function Tc(t){return t.exportClause?g.isNamedExports(t.exportClause)?t.exportClause.elements.map(e=>e.name.text):[]:["*"]}function Pc(t,e){if((g.isFunctionDeclaration(t)||g.isClassDeclaration(t)||g.isInterfaceDeclaration(t)||g.isTypeAliasDeclaration(t)||g.isEnumDeclaration(t))&&t.name){let n=t.name.text;e.exports.set(n,_n(n,t,t,e.sourceFile));return}if(g.isVariableStatement(t)){for(let n of t.declarationList.declarations)if(g.isIdentifier(n.name)){let s=n.name.text;e.exports.set(s,_n(s,n,t,e.sourceFile))}}}function Ac(t,e){if(!g.isCallExpression(t))return;let r=t.arguments[0];!r||!g.isStringLiteral(r)||(t.expression.kind===g.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:M(r.text),type:"dynamic"}):g.isIdentifier(t.expression)&&t.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:M(r.text),type:"require"}))}function Nc(t,e){let r=Ln.basename(t).toLowerCase(),n=Ln.extname(t).toLowerCase();return ne().some(o=>r.includes(o))?"test":hr(r)?"config":e.imports.some(o=>ot().some(i=>o.rawSpecifier.includes(i)))?"test":n===".tsx"||n===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>at()?"barrel":"logic"}function ir(t){return g.canHaveModifiers(t)&&g.getModifiers(t)?.some(e=>e.kind===g.SyntaxKind.ExportKeyword)===!0}function Ic(t,e){let r=t.rawCallEdges??[];t.rawCallEdges=r;let n=new Map;for(let s of e.statements){if(!g.isImportDeclaration(s)||!g.isStringLiteral(s.moduleSpecifier))continue;let o=s.moduleSpecifier.text,i=s.importClause;if(i&&(i.name&&n.set(i.name.text,o),i.namedBindings&&g.isNamedImports(i.namedBindings)))for(let a of i.namedBindings.elements)n.set(a.name.text,o)}if(n.size!==0)for(let s of e.statements){let o=Dc(s);if(o){let i=Rc(s);i&&Xe(i,o,n,r);continue}g.isClassDeclaration(s)&&s.name&&Mc(s,s.name.text,n,r)}}function Mc(t,e,r,n){for(let s of t.members)g.isMethodDeclaration(s)&&s.body&&g.isIdentifier(s.name)?Xe(s.body,`${e}.${s.name.text}`,r,n):g.isConstructorDeclaration(s)&&s.body&&Xe(s.body,`${e}.constructor`,r,n)}function Dc(t){if(ir(t)){if(g.isFunctionDeclaration(t)&&t.name)return t.name.text;if(g.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(g.isIdentifier(e.name)&&e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer)))return e.name.text}}}function Rc(t){if(g.isFunctionDeclaration(t))return t.body;if(g.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer)))return e.initializer}}function Xe(t,e,r,n){if(g.isCallExpression(t)&&g.isIdentifier(t.expression)){let s=t.expression.text,o=r.get(s);o&&!n.some(i=>i.from===e&&i.to===s&&i.toSpecifier===o)&&n.push({from:e,to:s,toSpecifier:o})}g.forEachChild(t,s=>Xe(s,e,r,n))}function Ze(t,e){if(e.length===0)return"ui";let r=!1;return t.walk(n=>{if(n.type==="rule")return r=!0,!1}),r?"ui":"barrel"}function jn(t,e){let r=[],n=/@require\s+['"]([^'"]+)['"]/g,s=n.exec(t);for(;s!==null;){let i=s[1];i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"require"}),s=n.exec(t)}let o=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(s=o.exec(t);s!==null;){let i=s[1];i&&r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),s=o.exec(t)}return r}function Wn(t,e){if(e.length===0)return"ui";try{let r=st("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 he(t,e){let r=L(t);if(r==="stylus"){let o=jn(e,t);return{imports:o,exports:[],tags:[],category:Wn(e,o)}}if(r==="scss"){let{imports:o,root:i,exports:a,tags:c}=De(e,t);return{imports:o,exports:a,tags:c,category:Ze(i,o)}}if(r==="less"){let{imports:o,root:i,exports:a,tags:c}=Me(e,t);return{imports:o,exports:a,tags:c,category:Ze(i,o)}}let{imports:n,root:s}=Ie(e,t);return{imports:n,exports:[],tags:[],category:Ze(s,n)}}for(let[t,e]of[["javascript",(r,n)=>or(r,n,"javascript")],["typescript",(r,n)=>or(r,n,"typescript")],["css",he],["scss",he],["less",he],["stylus",he],["coffeescript",Cn],["livescript",Pn],["lua",An],["python",Rn],["go",Tn],["gherkin",Zt],["markdown",Mn]])Y(t,e);async function zn(t,e){let r=L(t),n=on(r);return n?n(t,e):{imports:[],exports:[],tags:[],category:"other"}}import Bn from"path";function Un(t,e){for(let r of t.values()){let n=e.get(r.path);n!==void 0&&(r.coveragePct=n)}}function Kn(t,e){for(let r of t)if(r.isExternal){let n=r.rawSpecifier.startsWith("@")?r.rawSpecifier.split("/").slice(0,2).join("/"):r.rawSpecifier.split("/")[0];n&&!e.some(s=>s.name===n)&&e.push({name:n,kind:"library"})}}function Jn(t){for(let e of t.values())if(e.category==="test")for(let r of e.imports){if(r.isExternal||!r.toPath)continue;let n=t.get(r.toPath);n&&(n.category!=="logic"&&n.category!=="barrel"||(n.testedBy??=[],n.testedBy.includes(e.path)||n.testedBy.push(e.path)))}}function Vn(t){for(let e of t.values())if(e.type==="markdown")for(let r of e.imports){if(r.isExternal||!r.toPath)continue;let n=t.get(r.toPath);!n||n===e||(n.documentedBy??=[],n.documentedBy.includes(e.path)||n.documentedBy.push(e.path),n.category==="logic"&&(n.lastCommitAt??0)>(e.lastCommitAt??0)&&(e.staleFor??=[],e.staleFor.includes(n.path)||e.staleFor.push(n.path)))}}function $n(t){return Math.round(t*1e4)/1e4}function Hn(t){for(let e of t.values()){let r=[];for(let n of e.imports){if(n.isExternal||!n.toPath)continue;let s=t.get(n.toPath);if(!s||s.exports.length===0)continue;let o;if(n.symbols===void 0){if(n.type==="side-effect")continue;o=1}else n.symbols.includes("*")?o=1:o=n.symbols.length/s.exports.length;n.exportUsageRatio=$n(Math.min(1,o)),r.push(n.exportUsageRatio)}r.length>0&&(e.avgExportUsage=$n(r.reduce((n,s)=>n+s,0)/r.length),e.maxExportUsage=Math.max(...r))}}function ar(t,e,r){e&&(t.some(n=>n.name===e&&n.kind===r)||t.push({name:e,kind:r}))}function Gc(t,e){let r=e.toPath,n=Bn.basename(r,Bn.extname(r)).replace(/\.(test|spec)$/,"");ar(t.tags,n,"import")}function Lc(t,e){if(!(!e.symbols||e.symbols.includes("*")))for(let r of e.symbols)ar(t.tags,r,"import")}function _c(t,e,r){let n=r.get(e.toPath);if(!(!n||n.category==="test"))for(let s of n.tags)s.kind==="comment-marker"&&ar(t.tags,s.name,"comment-marker")}function Qn(t){for(let e of t.values())if(e.category==="test")for(let r of e.imports)!r.toPath||r.isExternal||(Gc(e,r),Lc(e,r),_c(e,r,t))}import et from"fs";import O from"path";import Xn from"fs";import ee from"path";var ye=class{extensions=[".go"];goModCache=new Map;resolve(e,r,n,s){let{mod:o,replaces:i}=this.readGoMod(n);if(!o)return null;let a=this.applyReplace(r,i,n);if(a!==void 0)return Yn(a);if(r!==o&&!r.startsWith(`${o}/`))return null;let c=r.slice(o.length).replace(/^\//,"");return c?Yn(ee.join(n,c)):null}readGoMod(e){let r=this.goModCache.get(e);if(r!==void 0)return r;let n={mod:null,replaces:new Map};try{let s=Xn.readFileSync(ee.join(e,"go.mod"),"utf-8"),o=Oc(s,e);return this.goModCache.set(e,o),o}catch{return this.goModCache.set(e,n),n}}applyReplace(e,r,n){for(let[s,o]of r){if(e===s)return o;if(e.startsWith(`${s}/`)){let i=e.slice(s.length+1);return ee.join(o,i)}}}};function Oc(t,e){let r=t.split(`
29
+ `),n=null,s=new Map,o=!1;for(let i of r){let a=i.trim();if(a.startsWith("module ")){n=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){o=!0;continue}if(o&&a===")"){o=!1;continue}if(o&&a.includes("=>")){qn(a,e,s);continue}!o&&/^replace\s+/.test(a)&&a.includes("=>")&&qn(a.replace(/^replace\s+/,""),e,s)}return{mod:n,replaces:s}}function qn(t,e,r){let[n,s]=t.split("=>").map(a=>a.trim());if(!n||!s)return;let o=n.split(/\s+/)[0];if(!s.startsWith(".")&&!s.startsWith("/"))return;let i=ee.isAbsolute(s)?s:ee.resolve(e,s);r.set(o,i)}function Yn(t){let e;try{e=Xn.readdirSync(t,{withFileTypes:!0})}catch{return null}let r=e.filter(n=>n.isFile()&&n.name.endsWith(".go")&&!n.name.endsWith("_test.go")).map(n=>({path:ee.join(t,n.name),isExternal:!1})).sort((n,s)=>n.path.localeCompare(s.path));return r.length>0?r:null}import jc from"fs";import cr from"path";var xe=class{extensions=[".lua"];resolve(e,r,n,s){let o=r.replace(/\./g,cr.sep),i=[n,cr.join(n,"lib")];for(let a of i){if(!jc.existsSync(a))continue;let c=s(cr.join(a,"_dummy.lua"),o);if(c)return[c]}return null}};import Wc from"path";var Se=class{extensions=[".md",".mdx"];resolve(e,r,n,s){let o=s(Wc.join(n,"_dummy"),`./${r}`);return o?[o]:null}};import zc from"fs";import lr from"path";var be=class{extensions=[".py"];resolve(e,r,n,s){let o=r.replace(/\./g,lr.sep),i=lr.join(n,`${o}.py`);if(Zn(i))return[{path:i,isExternal:!1}];let a=lr.join(n,o,"__init__.py");return Zn(a)?[{path:a,isExternal:!1}]:null}};function Zn(t){try{return zc.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}import es from"path";var Bc=["~","http://","https://","//","data:","sass:"],ke=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,r,n,s){if(Bc.some(p=>r.startsWith(p)))return null;let o=s(e,r);if(o)return[o];let i=es.dirname(r),a=es.basename(r),c=i==="."?`_${a}`:`${i}/_${a}`,l=s(e,c);return l?[l]:null}};var J=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 be,new xe,new ye,new ke,new Se]}rootDir;workspaceMap;tsconfigSearchPaths;pathAliases;langResolvers;resolveAll(e,r){let n=this.resolvePathAlias(r);if(n)return[n];if(r.startsWith(".")||r.startsWith("/")){let i=this.resolveLocalPath(e,r);return i?[i]:[]}let s=(i,a)=>this.resolveLocalPath(i,a);for(let i of this.langResolvers)if(i.extensions.some(a=>e.endsWith(a))){let a=i.resolve(e,r,this.rootDir,s);if(a)return a}let o=this.resolveWorkspaceImport(r);return o?[o]:[{path:r,isExternal:!0}]}resolve(e,r){let n=this.resolvePathAlias(r);if(n)return n;if(r.startsWith(".")||r.startsWith("/"))return this.resolveLocalPath(e,r);let s=(i,a)=>this.resolveLocalPath(i,a);for(let i of this.langResolvers)if(i.extensions.some(a=>e.endsWith(a))){let a=i.resolve(e,r,this.rootDir,s);if(a)return a[0]??null}let o=this.resolveWorkspaceImport(r);return o||{path:r,isExternal:!0}}resolveLocalPath(e,r){let n=O.dirname(e),s=r.startsWith("/")?r:O.resolve(n,r),o=!s.startsWith(this.rootDir),i=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature",".md",".mdx"],a=s.match(/\.(js|mjs|cjs)$/);if(a){let c=s.slice(0,-a[0].length);for(let l of[".ts",".tsx"]){let p=this.tryExtensions(c,l,o);if(p)return p}}for(let c of i){let l=this.tryExtensions(s,c,o);if(l)return l}return o?{path:s,isExternal:!0}:null}tryExtensions(e,r,n){let s=e+r;if(this.isFile(s))return{path:s,isExternal:n};let o=O.join(e,`index${r}`);if(this.isFile(o))return{path:o,isExternal:n};if(r===".py"){let i=O.join(e,"__init__.py");if(this.isFile(i))return{path:i,isExternal:n}}return null}isFile(e){try{return et.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){if(this.pathAliases)for(let r in this.pathAliases){let n=this.matchAliasPattern(r,e),s=this.pathAliases[r];if(n&&s){let o=this.tryAliasSubstitutions(s,n[1]||"");if(o)return o}}for(let r of this.tsconfigSearchPaths){let n=O.join(r,"tsconfig.json");if(et.existsSync(n))try{let o=JSON.parse(et.readFileSync(n,"utf-8")).compilerOptions?.paths;if(!o)continue;for(let i in o){let a=this.matchAliasPattern(i,e);if(a){let c=this.tryAliasSubstitutions(o[i],a[1]||"",r);if(c)return c}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,r){let n=this.aliasRegexCache.get(e);if(!n){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");n=new RegExp(`^${s}$`),this.aliasRegexCache.set(e,n)}return r.match(n)}tryAliasSubstitutions(e,r,n=this.rootDir){let s=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let o of e){let i=o.replace("*",r),a=O.resolve(n,i);for(let c of s){let l=this.tryExtensions(a,c,!1);if(l)return l}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[r,n]of this.workspaceMap){if(e!==r&&!e.startsWith(`${r}/`))continue;let s=e.slice(r.length),o={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:r};if(!s){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let c=O.join(n,a);try{if(et.statSync(c,{throwIfNoEntry:!1})?.isFile())return{...o,path:c}}catch{}}return{...o,path:n}}let i=this.resolveLocalPath(O.join(n,"_dummy"),s.slice(1));return i?{...o,path:i.path}:null}return null}};var Uc=["tests","test","__tests__","specs","spec"],ts=new Set(["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"]),Kc=20;function Jc(t,e){if(t.length===0)return e;let r=t.map(i=>A.dirname(i).split(A.sep)),n=r[0]??[];for(let i of r.slice(1)){let a=0;for(;a<n.length&&a<i.length&&n[a]===i[a];)a++;n=n.slice(0,a)}let s=n.join(A.sep)||A.sep,o=A.relative(e,s);return o.startsWith("..")||A.isAbsolute(o)?e:s}var we=class{constructor(e,r=null,n,s,o=!1,i=new Map,a=!0){this.rootDir=e;this.enableGitStats=o;this.coverageMap=i;this.parallelParsing=a;this.previousGraph=r,this.resolver=n||new J(e),this.lockFile=Ar(e),s&&(this.progressCallback=s)}rootDir;enableGitStats;coverageMap;parallelParsing;graph={nodes:new Map};visited=new Set;queue=[];previousGraph=null;resolver;lockFile=null;progressCallback;pool=null;gitStatsMap=null;async build(e){let r=e.map(n=>A.isAbsolute(n)?n:A.resolve(this.rootDir,n));await this.initPool(),this.enableGitStats&&(this.gitStatsMap=bn(this.rootDir));try{for(let n of r)this.enqueue(n);return await this.drain(),await this.processTestFiles(Jc(r,this.rootDir)),await this.processDocFiles(),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
28
30
  Done. Total processed: ${this.visited.size} nodes.
29
- `),Vn(this.graph.nodes),Un(this.graph.nodes),Jn(this.graph.nodes),Kn(this.graph.nodes),this.coverageMap.size>0&&$n(this.graph.nodes,this.coverageMap),new D(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??jc;if(!(r>0&&!this.hasAtLeastFiles(this.rootDir,r)))try{let n=T.join(u,"parse-worker.js");this.pool=new _c({filename:n,...e.maxThreads!==void 0?{maxThreads:e.maxThreads}:{}})}catch(n){process.stderr.write(`
31
+ `),Qn(this.graph.nodes),Jn(this.graph.nodes),Hn(this.graph.nodes),Vn(this.graph.nodes),this.coverageMap.size>0&&Un(this.graph.nodes,this.coverageMap),new R(this.graph.nodes)}finally{this.pool&&(await this.pool.destroy(),this.pool=null)}}async initPool(){if(this.parallelParsing===!1)return;let e=typeof this.parallelParsing=="object"?this.parallelParsing:{},r=e.minFiles??Kc;if(!(r>0&&!this.hasAtLeastFiles(this.rootDir,r)))try{let n=A.join(u,"parse-worker.js");this.pool=new $c({filename:n,...e.maxThreads!==void 0?{maxThreads:e.maxThreads}:{}})}catch(n){process.stderr.write(`
30
32
  Warning: failed to start parse worker pool, falling back to synchronous parsing: ${n}
31
- `),this.pool=null}}hasAtLeastFiles(e,r){let n=0,s=[e];for(;s.length>0;){let o=s.pop();if(o===void 0)continue;let i;try{i=be.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let a of i)if(a.isDirectory())Zn.has(a.name)||s.push(T.join(o,a.name));else if(a.isFile()&&(n++,n>=r))return!0}return n>=r}async processTestFiles(e){let r=te(),n=o=>r.some(i=>o.name.includes(i));this.walkProject(e,n);let s=e;for(;s!==this.rootDir;){let o=T.dirname(s);if(o===s)break;for(let i of Oc){let a=T.join(o,i);try{be.statSync(a).isDirectory()&&this.walkProject(a,n)}catch{}}s=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 n;try{n=be.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of n){let o=T.join(e,s.name);s.isDirectory()?Zn.has(s.name)||this.walkProject(o,r):s.isFile()&&r(s)&&this.enqueue(o)}}enqueue(e){this.visited.has(e)||(this.visited.add(e),this.showProgress(),this.queue.push(e))}async drain(){for(;this.queue.length>0;){let e=this.queue;this.queue=[],await Promise.all(e.map(r=>this.finishFile(r)))}}async finishFile(e){let r=be.statSync(e,{throwIfNoEntry:!1});if(!r?.isFile())return;let n=T.relative(this.rootDir,e),s=await this.getNode(e,n,r);s.imports=await this.resolveImports(e,s.imports),Bn(s.imports,s.tags),this.graph.nodes.set(s.path,s)}async getNode(e,r,n){let s=this.previousGraph?.nodes.get(r);if(s&&s.mtime===n.mtimeMs&&s.size===n.size)return{...s};let o=await this.tryParse(e,r);if(!o)return this.makeStubNode(e,r,n);let i=this.resolveCallEdges(e,o.rawCallEdges),a=this.buildNode(e,r,n,o,i);return this.attachGitStats(a,r),a}async tryParse(e,r){let n=be.readFileSync(e,"utf-8");try{return await this.parseContent(e,n)}catch(s){return process.stderr.write(`
33
+ `),this.pool=null}}hasAtLeastFiles(e,r){let n=0,s=[e];for(;s.length>0;){let o=s.pop();if(o===void 0)continue;let i;try{i=ve.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let a of i)if(a.isDirectory())ts.has(a.name)||s.push(A.join(o,a.name));else if(a.isFile()&&(n++,n>=r))return!0}return n>=r}async processTestFiles(e){let r=ne(),n=o=>r.some(i=>o.name.includes(i));this.walkProject(e,n);let s=e;for(;s!==this.rootDir;){let o=A.dirname(s);if(o===s)break;for(let i of Uc){let a=A.join(o,i);try{ve.statSync(a).isDirectory()&&this.walkProject(a,n)}catch{}}s=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 n;try{n=ve.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of n){let o=A.join(e,s.name);s.isDirectory()?ts.has(s.name)||this.walkProject(o,r):s.isFile()&&r(s)&&this.enqueue(o)}}enqueue(e){this.visited.has(e)||(this.visited.add(e),this.showProgress(),this.queue.push(e))}async drain(){for(;this.queue.length>0;){let e=this.queue;this.queue=[],await Promise.all(e.map(r=>this.finishFile(r)))}}async finishFile(e){let r=ve.statSync(e,{throwIfNoEntry:!1});if(!r?.isFile())return;let n=A.relative(this.rootDir,e),s=await this.getNode(e,n,r);s.imports=await this.resolveImports(e,s.imports),Kn(s.imports,s.tags),this.graph.nodes.set(s.path,s)}async getNode(e,r,n){let s=this.previousGraph?.nodes.get(r);if(s&&s.mtime===n.mtimeMs&&s.size===n.size)return{...s};let o=await this.tryParse(e,r);if(!o)return this.makeStubNode(e,r,n);let i=this.resolveCallEdges(e,o.rawCallEdges),a=this.buildNode(e,r,n,o,i);return this.attachGitStats(a,r),a}async tryParse(e,r){let n=ve.readFileSync(e,"utf-8");try{return await this.parseContent(e,n)}catch(s){return process.stderr.write(`
32
34
  Warning: failed to parse ${r}: ${s}
33
- `),null}}parseContent(e,r){return this.pool?this.pool.run({filePath:e,content:r}):jn(e,r)}makeStubNode(e,r,n){return{path:r,type:G(e),category:"other",imports:[],exports:[],tags:[],mtime:n.mtimeMs,size:n.size}}resolveCallEdges(e,r){let n=[];for(let s of r??[])try{let o=this.resolver.resolve(e,s.toSpecifier);o&&!o.isExternal&&n.push({from:s.from,to:s.to,toFile:T.relative(this.rootDir,o.path)})}catch{}return n}buildNode(e,r,n,s,o){let{imports:i,exports:a,tags:c,category:p,description:l,complexity:d,cognitiveComplexity:f,functions:h}=s;return{path:r,type:G(e),category:p,imports:i,exports:a,tags:c,mtime:n.mtimeMs,size:n.size,...l!==void 0?{description:l}:{},...o.length>0?{callEdges:o}:{},...d!==void 0?{complexity:d}:{},...f!==void 0?{cognitiveComplexity:f}:{},...h!==void 0?{functions:h}:{}}}attachGitStats(e,r){let n=this.gitStatsMap?.get(r);n&&(e.commitCount90d=n.commitCount90d,n.lastAuthor!==void 0&&(e.lastAuthor=n.lastAuthor),n.lastCommitAt!==void 0&&(e.lastCommitAt=n.lastCommitAt))}async resolveImports(e,r){let n=[];for(let s of r){let o=this.resolver.resolveAll(e,s.rawSpecifier);if(o.length!==0)for(let i of o){let a={...s,toPath:i.isExternal?i.path:T.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),n.push(a)}}return n}attachLockfileVersion(e){if(!this.lockFile)return;let r=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],n=r?this.lockFile.dependencies[r]:void 0;n&&(e.version=n.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};function es(t,e){return{identifier:e?.identifier??new Je,featureMap:e?.featureDetection===!1?new Map:W(t.nodes,e?.featureDetection??void 0)}}function ts(t,e,r,n,s){for(let o of e){let i=t.nodes.get(o);if(!i)continue;let a=new z(o,["*",...i.exports.map(c=>c.name)]);t.traverse(o,(c,p,l)=>{if(!l)return!0;if(!a.updateAffectedSymbols(c,l))return!1;if(p>0){let d=r.get(c.path);if(d)return n(d),!1}return s(c),!0},{direction:"incoming"})}}function cr(t,e,r){let{identifier:n,featureMap:s}=es(t,r),o=new Set;for(let i of e){let a=s.get(i);a&&o.add(a.tag)}return ts(t,e,s,i=>o.add(i.tag),i=>{if(n.isTestNode(i))for(let a of i.tags)o.add(a.name)}),Array.from(o)}function pr(t,e,r){let{identifier:n,featureMap:s}=es(t,r),o=new Set;return ts(t,e,s,()=>{},i=>{n.isTestNode(i)&&o.add(i.path)}),Array.from(o)}import zc from"fs";import ke from"path";async function rs(t,e,r=null,n={}){let s=n.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},o=ke.resolve(t);return await new ve(o,r,n.pathAliases?new J(o,{pathAliases:n.pathAliases}):void 0,s,n.gitStats??!1,n.coverageMap??new Map,n.parallelParsing??!0).build(e)}async function ns(t,e={}){let r=ke.resolve(t),n=pe(r),s=e.packages?n.packages.filter(a=>e.packages?.includes(a.name)||e.packages?.includes(a.relativeRoot)):n.packages,o=new Map(n.packages.map(a=>[a.name,a.root])),i=new le(r,n.type);for(let a of s){let c=e.silent?void 0:d=>{process.stderr.write(`[${a.name}] Processed ${d} files...\r`)},l=await new ve(r,null,new J(r,{workspaceMap:o,tsconfigSearchPaths:[a.root,r],pathAliases:e.pathAliases}),c,e.gitStats??!1,new Map,e.parallelParsing??!0).build(a.entryPoints);i.addPackage(a,l)}return i}function ss(t,e={}){let r=[],n=new Set([...e.ignoreDirs??j,...e.additionalIgnoreDirs??[]]),s=new Set([...e.extensions??at,...e.additionalExtensions??[]]);function o(i){try{let a=zc.readdirSync(i,{withFileTypes:!0});for(let c of a){let p=ke.join(i,c.name);c.isDirectory()?n.has(c.name)||o(p):c.isFile()&&s.has(ke.extname(c.name).toLowerCase())&&r.push(ke.relative(t,p))}}catch{}}return o(t),r}var os=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;var Xe=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,n=new Map){let s=this.configs.get(e),o=await rs(e,r,this.graphs.get(e)??null,{...V(s),coverageMap:n});return this.graphs.set(e,o),o}require(e){let r=this.graphs.get(e);if(!r)throw new Error('No graph cached for this root. Call "analyze" first.');return r}async getOrBuildWorkspace(e,r={}){let n=this.workspaceGraphs.get(e);if(n)return n;let s=await ns(e,r);return this.workspaceGraphs.set(e,s),s}requireWorkspace(e){let r=this.workspaceGraphs.get(e);if(!r)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return r}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){let r=this.changeImpactCaches.get(e);if(r)return r;let n=this.require(e),s=mt(n);return this.changeImpactCaches.set(e,s),s}storeLastAnalyze(e,r){this.lastAnalyze.set(e,r)}startWatching(e){if(!this.watchers.has(e))try{let r=$c.watch(e,{recursive:!0},(n,s)=>{!s||os.test(s)||this.dirtyRoots.add(e)});r.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,r)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e);let r=this.lastAnalyze.get(e);return r?.kind==="single"?this.getOrBuild(e,r.entryPoints,r.coverageMap):this.require(e)}async ensureFreshWorkspace(e){if(!this.dirtyRoots.has(e))return this.requireWorkspace(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e),this.workspaceGraphs.delete(e);let r=this.configs.get(e);return this.getOrBuildWorkspace(e,V(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 ee from"path";import Bc from"fs";import Uc from"os";import lr from"path";function v(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function is(t){if(!lr.isAbsolute(t))throw new Error("root must be an absolute path");let e=lr.resolve(t),r=Uc.homedir();if(e!==r&&!e.startsWith(r+lr.sep))throw new Error("root must be within the user home directory");let n;try{n=Bc.statSync(e)}catch{throw new Error("root does not exist")}if(!n.isDirectory())throw new Error("root is not a directory")}async function as(t,e){let{root:r,entryPoints:n}=e;if(!t.isConfigured(r)){let f=re(r,{allowJs:!1});it(f),t.storeConfig(r,f)}if(n.length===0){let f=pe(r);if(f.type!=="none"){let h=t.getConfig(r),x=await t.getOrBuildWorkspace(r,V(h));t.storeLastAnalyze(r,{kind:"workspace"}),t.startWatching(r);let y=Array.from(x.packages.values()).map(({graph:S,pkg:C})=>({package:C.name,relativeRoot:C.relativeRoot,nodeCount:S.nodes.size}));return v({monorepoType:f.type,packageCount:x.packages.size,packages:y})}}let s=n.map(f=>ee.resolve(r,f)),o=t.getConfig(r),i=o?.coverageReportPath?ct(r,o.coverageReportPath):new Map,a=await t.getOrBuild(r,s,i);t.storeLastAnalyze(r,{kind:"single",entryPoints:s,coverageMap:i}),t.startWatching(r);let c=a.serialize(),p=c.nodes.reduce((f,h)=>(f[h.category]=(f[h.category]??0)+1,f),{}),l=a.findCycles(),d=bt(a);return v({nodeCount:c.nodes.length,categories:p,cycles:l,languageCoverage:d})}async function cs(t,e){let{root:r,file:n,depth:s=1,withMeta:o=!1}=e,i=await t.ensureFresh(r),a=vt(i,n,s),c=o?a.map(p=>({...p,...oe(i,p.path)})):a;return v({file:n,dependencies:c})}async function ps(t,e){let{root:r,file:n,withMeta:s=!1}=e,o=await t.ensureFresh(r),i=ie(o,n),a=s?i.map(c=>({...c,...oe(o,c.path)})):i;return v({file:n,dependents:a})}async function ls(t,e){let{root:r,file:n,testsOnly:s=!1,cached:o=!1,changedSymbols:i,withMeta:a=!1}=e,c=await t.ensureFresh(r),p=f=>a?f.map(h=>({path:h,...oe(c,h)})):f;if(o){let f=t.getOrBuildChangeImpact(r),h=gt(f,n),x=s?h.filter(S=>c.nodes.get(S)?.category==="test"):h,y=p(x);return v({file:n,affected:y,count:y.length})}let l=kt(c,n,{testsOnly:s,changedSymbols:i}),d=p(l);return v({file:n,affected:d,count:d.length})}async function us(t,e){let{root:r,file:n,depth:s=1,withEdgeDetail:o=!1}=e,i=await t.ensureFresh(r),a=wt(i,n,{depth:s,withEdgeDetail:o});return v({file:n,callers:a,count:a.length})}async function fs(t,e){let{root:r,entryPoints:n}=e,s=n?await t.getOrBuild(r,n.map(a=>ee.resolve(r,a))):await t.ensureFresh(r),o=ss(r),i=s.findUnusedFiles(o);return v({unusedFiles:i,count:i.length})}async function ms(t,e){let{root:r}=e,n=await t.ensureFresh(r),s=new Map;for(let i of n.nodes.values())for(let a of i.tags)s.set(a.name,(s.get(a.name)??0)+1);let o=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count);return v({tags:o,count:o.length})}async function gs(t,e){let{root:r,coverageThreshold:n}=e,s=await t.ensureFresh(r),o=t.getConfig(r),i=n??o?.coverageThreshold??80;if(!Tt(s))return v({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let a=[...s.nodes.values()].filter(c=>c.category!=="test"&&c.category!=="config").filter(c=>c.coveragePct!==void 0&&c.coveragePct<i).map(c=>({file:c.path,coveragePct:c.coveragePct}));return v({threshold:i,uncovered:a,count:a.length})}async function ds(t,e){let{root:r}=e,s=[...(await t.ensureFresh(r)).nodes.values()].filter(o=>o.type==="markdown"&&o.staleFor&&o.staleFor.length>0).map(o=>({doc:o.path,staleFor:o.staleFor}));return v({staleDocs:s,count:s.length})}async function hs(t,e){let{root:r,metric:n="cognitiveComplexity",threshold:s=10,limit:o=20}=e,i=await t.ensureFresh(r),a=Ct(i,{metric:n,threshold:s,limit:o});return v({metric:n,threshold:s,functions:a,count:a.length})}async function ys(t,e){let{root:r,minLines:n=6,ignoreLiterals:s=!0,maxPunctuationRatio:o=.5,limit:i=50}=e,a=await t.ensureFresh(r),c=e.ignoreDirs??[...j,...t.getConfig(r)?.ignoreDirs??[]],p=await St(a,r,{minLines:n,ignoreLiterals:s,maxPunctuationRatio:o,limit:i,ignoreDirs:c});return v({minLines:n,groups:p,count:p.length})}async function xs(t,e){let{root:r,changedFiles:n,featureThreshold:s,format:o="tags"}=e,i=await t.ensureFresh(r),a=n??new Ve().getChangedFiles().map(l=>ee.relative(r,ee.resolve(r,l))),c=s!==void 0?{featureDetection:{minOutDegree:s}}:void 0;if(o==="paths"){let l=pr(i,a,c);return v({changedFiles:a,affectedTests:l,count:l.length})}let p=cr(i,a,c);return v({changedFiles:a,proposedTags:p})}async function Ss(t,e){let{root:r,entryPoints:n,featureThreshold:s}=e,o=n?await t.getOrBuild(r,n.map(c=>ee.resolve(r,c))):await t.ensureFresh(r),i=W(o.nodes,s!==void 0?{minOutDegree:s}:void 0),a=Array.from(i.values()).sort((c,p)=>p.outDegree-c.outDegree);return v({features:a,count:a.length})}async function bs(t,e){let{root:r,entryPoints:n,filter:s,mermaid:o=!1,slim:i=!0}=e,a=n?await t.getOrBuild(r,n.map(p=>ee.resolve(r,p))):await t.ensureFresh(r),c=Ge(a.serialize(),Le(s));return o?v(Ee.serialize(D.deserialize(c))):i?v(Ft(c)):v(c)}async function vs(t,e){let{root:r}=e,n=await t.ensureFreshWorkspace(r);return v(Et(n))}async function ks(t,e){let{root:r,file:n}=e,o=(await t.ensureFreshWorkspace(r)).getAffectedAcrossPackages(n);return v({file:n,affected:o,count:o.length})}function ws(t,e){let{root:r}=e,n=t.invalidate(r);return v({root:r,cleared:n,message:n?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function Cs(t,e){let{root:r,type:n}=e,s=await t.ensureFresh(r),o=Nt(s);if(n)return v(Mt(o,n));let i=Array.from(o.types.values());return v({count:i.length,types:i})}async function Fs(t,e){let{root:r,paths:n,minOutDegree:s}=e,o=await t.ensureFresh(r),i=Pt(o,s!==void 0?{minOutDegree:s}:void 0);if(n?.length){let c=n.map(p=>i.get(p)).filter(Boolean);return v({count:c.length,modules:c})}let a=Array.from(i.values());return v({count:a.length,modules:a})}async function Es(t,e){let{root:r,minOutDegree:n}=e,s=await t.ensureFresh(r),o=ne(s,n!==void 0?{minOutDegree:n}:void 0),i=Object.fromEntries(o.features);return v({features:i,unassigned:o.unassigned})}async function Ts(t,e){let{root:r,function:n}=e,s=await t.ensureFresh(r);return v(ft(s,n))}async function Ps(t,e){let{root:r,name:n}=e,s=await t.ensureFresh(r),o=At(s,n);return v({name:n,matches:o,count:o.length})}async function As(t,e){let{root:r,entryPoints:n}=e,s=await t.ensureFresh(r),o=n?.length?n:lt(s,r);if(o.length===0)throw new Error("No entry points found. Pass entryPoints explicitly or ensure package.json has a main/exports field.");return v(ut(s,o))}async function Ns(t,e){let r=await t.ensureFresh(e.root),n=await Ht(r,e.root,{dryRun:e.dryRun??!1});return v(n)}var Ms=[{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. Omit entryPoints to reuse the cached graph from a prior analyze() call instead of rebuilding.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to reuse the cached graph from a prior analyze() call."}},required:["root"]}},{name:"list_tags",description:"List every distinct tag name present in the graph, with how many nodes carry each one. Call this before querying with tag:<name> to avoid a speculative filter silently returning zero results. Includes all tag kinds \u2014 a superset of what query's slim mode keeps (slim only retains comment-marker and import tags).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_uncovered",description:"Find non-test files whose line coverage is below the configured threshold. Requires a prior analyze() call and coverageReportPath set in mokosh.config. coverageThreshold overrides the config default (default: 80).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},coverageThreshold:{type:"number",description:"Line-coverage % below which a file is considered uncovered. Overrides config value."}},required:["root"]}},{name:"check_doc_drift",description:"Find markdown docs whose referenced files changed more recently than the doc itself \u2014 a commit-recency heuristic for stale documentation, not a content diff. Requires a prior analyze() call with gitStats: true in mokosh.config (otherwise no file has commit-timestamp data and nothing is flagged). See docs/adr-009-markdown-parsing.md for known limitations.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_complex_functions",description:"Find individual functions/methods above a cognitive (or cyclomatic) complexity threshold, sorted worst-first. Requires a prior analyze() call. Populated for TypeScript/JavaScript, Go, and Python.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which score to threshold/sort on (default: cognitiveComplexity)"},threshold:{type:"number",description:"Minimum score to include (default: 10)"},limit:{type:"number",description:"Max results to return, worst-first (default: 20)"}},required:["root"]}},{name:"find_duplicates",description:"Find duplicated code blocks across the project, largest-first. Two matching strategies, picked per file: CSS/SCSS/Less are compared structurally by rule body \u2014 the literal, ordered property:value declarations a rule contains, independent of its selector \u2014 so a genuine copy-pasted declaration list is caught while rules that merely share shape (e.g. display:flex vs display:block) never match. Every other language mokosh parses (TypeScript/JavaScript, Python, Go, CoffeeScript, LiveScript, Lua, Gherkin, Markdown, and Stylus) runs a token-based shingle pipeline instead, partitioned by language family so matching never crosses between Stylus and code languages. Identifiers \u2014 and by default literals \u2014 are normalized before matching in the token-based path, so renamed-variable copies are still caught; blocks that are mostly object/array-literal structural punctuation (e.g. schema/object-literal boilerplate) rather than substantive shared logic are gated out. A block repeated N times across the project is reported once with N occurrences, not as separate pairs. Lock files (package-lock.json, yarn.lock, pnpm-lock.yaml) and files under an ignored directory are always excluded, even if the graph itself contains them. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minLines:{type:"number",description:"Minimum duplicated block size in lines to report (default: 6)"},ignoreLiterals:{type:"boolean",description:"Normalize string/number literals too, not just identifiers, so only structural shape drives a match (default: true). Set false for stricter, exact-text-only matching."},maxPunctuationRatio:{type:"number",description:"Maximum fraction of a token-shingled block's window that may be object/array-literal structural punctuation ({ } : , [ ]) (default: 0.5). Filters out blocks that are mostly schema/object-literal shape instead of substantive shared logic. Does not apply to the CSS/Less/SCSS structural comparator. Set 1 to disable."},ignoreDirs:{type:"array",items:{type:"string"},description:"Directory names to exclude, matched against any path segment (default: DEFAULT_IGNORE_DIRS merged with this root's configured ignoreDirs, if any). Pass [] to disable."},limit:{type:"number",description:"Max duplicate blocks to return, largest-first (default: 50)"}},required:["root"]}},{name:"propose_tags",description:"Propose what to run based on changed files. Pass changedFiles explicitly or omit to use git diff. format='tags' (default) returns test tags for CI tag-filtering; format='paths' returns test file paths ready to pipe directly to a test runner (e.g. vitest). Feature hubs act as traversal boundaries in both modes.",inputSchema:{type:"object",properties:{root:{type:"string"},changedFiles:{type:"array",items:{type:"string"},description:"Changed files relative to root. Omit to read from git diff."},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. Tags are filtered to kinds comment-marker and import only; function/class/variable/type/library tags are dropped in slim output. Use list_tags to see the full tag inventory, or pass slim: false to get every tag kind on matching nodes."}},required:["root","filter"]}},{name:"get_workspace_packages",description:"List all workspace packages detected in a monorepo, with their node counts and inter-package dependencies. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"}},required:["root"]}},{name:"get_workspace_affected",description:"Cross-package blast-radius analysis. Returns every file that could be affected if a given file changes, annotated with the package it belongs to. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"},file:{type:"string",description:"Monorepo-root-relative path of the changed file (e.g. 'packages/shared/src/utils.ts')"}},required:["root","file"]}},{name:"get_type_graph",description:"Return type-level relationships for the project. Without a type name, returns an inventory of all interfaces, classes, enums, and type aliases with their file and kind. With a type name, returns which files import that type (usedByFiles) and which types the defining file imports (uses). Requires a prior analyze() call. Only covers TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},type:{type:"string",description:"Exact exported name of the type to look up (e.g. 'FileNode'). Omit to get the full type inventory."}},required:["root"]}},{name:"get_module_responsibility",description:"Return what each file is responsible for: its semantic role, JSDoc description (when present), exported symbol names, and which feature hub it belongs to. Pass specific paths to filter, or omit paths to get all files. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},paths:{type:"array",items:{type:"string"},description:"Project-relative file paths to include. Omit to return all files."},minOutDegree:{type:"number",description:"Min imports for a file to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_feature_graph",description:"Group files by domain: returns which files each feature hub (high-import orchestrator) transitively owns. Each file is assigned to the most specific hub that can reach it (lowest out-degree wins). Use this instead of a full query when answering 'what files are in the X feature/module?' \u2014 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 ur(){let t=new Xe,e=new Kc({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(Vc,async()=>({tools:Ms})),e.setRequestHandler(Jc,async r=>{let{name:n,arguments:s}=r.params,o=s,a={analyze:c=>as(t,c),get_dependencies:c=>cs(t,c),get_dependents:c=>ps(t,c),get_affected:c=>ls(t,c),get_callers:c=>us(t,c),find_symbol:c=>Ps(t,c),find_unused:c=>fs(t,c),find_uncovered:c=>gs(t,c),list_tags:c=>ms(t,c),check_doc_drift:c=>ds(t,c),find_complex_functions:c=>hs(t,c),find_duplicates:c=>ys(t,c),propose_tags:c=>xs(t,c),detect_features:c=>Ss(t,c),get_type_graph:c=>Cs(t,c),get_module_responsibility:c=>Fs(t,c),get_feature_graph:c=>Es(t,c),get_call_graph:c=>Ts(t,c),get_api_surface:c=>As(t,c),query:c=>bs(t,c),get_workspace_packages:c=>vs(t,c),get_workspace_affected:c=>ks(t,c),clear_cache:c=>ws(t,c),apply_tags:c=>Ns(t,c)}[n];if(!a)throw new Error(`Unknown tool: ${n}`);try{return is(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 Qc(){let t=ur(),e=new Hc;await t.connect(e)}Qc().catch(console.error);export{ur as createMcpServer};
35
+ `),null}}parseContent(e,r){return this.pool?this.pool.run({filePath:e,content:r}):zn(e,r)}makeStubNode(e,r,n){return{path:r,type:L(e),category:"other",imports:[],exports:[],tags:[],mtime:n.mtimeMs,size:n.size}}resolveCallEdges(e,r){let n=[];for(let s of r??[])try{let o=this.resolver.resolve(e,s.toSpecifier);o&&!o.isExternal&&n.push({from:s.from,to:s.to,toFile:A.relative(this.rootDir,o.path)})}catch{}return n}buildNode(e,r,n,s,o){let{imports:i,exports:a,tags:c,category:l,description:p,complexity:m,cognitiveComplexity:d,functions:h}=s;return{path:r,type:L(e),category:l,imports:i,exports:a,tags:c,mtime:n.mtimeMs,size:n.size,...p!==void 0?{description:p}:{},...o.length>0?{callEdges:o}:{},...m!==void 0?{complexity:m}:{},...d!==void 0?{cognitiveComplexity:d}:{},...h!==void 0?{functions:h}:{}}}attachGitStats(e,r){let n=this.gitStatsMap?.get(r);n&&(e.commitCount90d=n.commitCount90d,n.lastAuthor!==void 0&&(e.lastAuthor=n.lastAuthor),n.lastCommitAt!==void 0&&(e.lastCommitAt=n.lastCommitAt))}async resolveImports(e,r){let n=[];for(let s of r){let o=this.resolver.resolveAll(e,s.rawSpecifier);if(o.length!==0)for(let i of o){let a={...s,toPath:i.isExternal?i.path:A.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),n.push(a)}}return n}attachLockfileVersion(e){if(!this.lockFile)return;let r=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],n=r?this.lockFile.dependencies[r]:void 0;n&&(e.version=n.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};function rs(t,e){return{identifier:e?.identifier??new Qe,featureMap:e?.featureDetection===!1?new Map:W(t.nodes,e?.featureDetection??void 0)}}function ns(t,e,r,n,s){for(let o of e){let i=t.nodes.get(o);if(!i)continue;let a=new z(o,["*",...i.exports.map(c=>c.name)]);t.traverse(o,(c,l,p)=>{if(!p)return!0;if(!a.updateAffectedSymbols(c,p))return!1;if(l>0){let m=r.get(c.path);if(m)return n(m),!1}return s(c),!0},{direction:"incoming"})}}function pr(t,e,r){let{identifier:n,featureMap:s}=rs(t,r),o=new Set;for(let i of e){let a=s.get(i);a&&o.add(a.tag)}return ns(t,e,s,i=>o.add(i.tag),i=>{if(n.isTestNode(i))for(let a of i.tags)o.add(a.name)}),Array.from(o)}function ur(t,e,r){let{identifier:n,featureMap:s}=rs(t,r),o=new Set;return ns(t,e,s,()=>{},i=>{n.isTestNode(i)&&o.add(i.path)}),Array.from(o)}import Vc from"fs";import Ce from"path";async function ss(t,e,r=null,n={}){let s=n.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},o=Ce.resolve(t);return await new we(o,r,n.pathAliases?new J(o,{pathAliases:n.pathAliases}):void 0,s,n.gitStats??!1,n.coverageMap??new Map,n.parallelParsing??!0).build(e)}async function os(t,e={}){let r=Ce.resolve(t),n=ue(r),s=e.packages?n.packages.filter(a=>e.packages?.includes(a.name)||e.packages?.includes(a.relativeRoot)):n.packages,o=new Map(n.packages.map(a=>[a.name,a.root])),i=new fe(r,n.type);for(let a of s){let c=e.silent?void 0:m=>{process.stderr.write(`[${a.name}] Processed ${m} files...\r`)},p=await new we(r,null,new J(r,{workspaceMap:o,tsconfigSearchPaths:[a.root,r],pathAliases:e.pathAliases}),c,e.gitStats??!1,new Map,e.parallelParsing??!0).build(a.entryPoints);i.addPackage(a,p)}return i}function is(t,e={}){let r=[],n=new Set([...e.ignoreDirs??j,...e.additionalIgnoreDirs??[]]),s=new Set([...e.extensions??pt,...e.additionalExtensions??[]]);function o(i){try{let a=Vc.readdirSync(i,{withFileTypes:!0});for(let c of a){let l=Ce.join(i,c.name);c.isDirectory()?n.has(c.name)||o(l):c.isFile()&&s.has(Ce.extname(c.name).toLowerCase())&&r.push(Ce.relative(t,l))}}catch{}}return o(t),r}var as=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;var tt=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,n=new Map){let s=this.configs.get(e),o=await ss(e,r,this.graphs.get(e)??null,{...H(s),coverageMap:n});return this.graphs.set(e,o),o}require(e){let r=this.graphs.get(e);if(!r)throw new Error('No graph cached for this root. Call "analyze" first.');return r}async getOrBuildWorkspace(e,r={}){let n=this.workspaceGraphs.get(e);if(n)return n;let s=await os(e,r);return this.workspaceGraphs.set(e,s),s}requireWorkspace(e){let r=this.workspaceGraphs.get(e);if(!r)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return r}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){let r=this.changeImpactCaches.get(e);if(r)return r;let n=this.require(e),s=ht(n);return this.changeImpactCaches.set(e,s),s}storeLastAnalyze(e,r){this.lastAnalyze.set(e,r)}startWatching(e){if(!this.watchers.has(e))try{let r=Hc.watch(e,{recursive:!0},(n,s)=>{!s||as.test(s)||this.dirtyRoots.add(e)});r.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,r)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e);let r=this.lastAnalyze.get(e);return r?.kind==="single"?this.getOrBuild(e,r.entryPoints,r.coverageMap):this.require(e)}async ensureFreshWorkspace(e){if(!this.dirtyRoots.has(e))return this.requireWorkspace(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e),this.workspaceGraphs.delete(e);let r=this.configs.get(e);return this.getOrBuildWorkspace(e,H(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 te from"path";import Qc from"fs";import qc from"os";import fr from"path";function w(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function cs(t){if(!fr.isAbsolute(t))throw new Error("root must be an absolute path");let e=fr.resolve(t),r=qc.homedir();if(e!==r&&!e.startsWith(r+fr.sep))throw new Error("root must be within the user home directory");let n;try{n=Qc.statSync(e)}catch{throw new Error("root does not exist")}if(!n.isDirectory())throw new Error("root is not a directory")}async function ls(t,e){let{root:r,entryPoints:n}=e;if(!t.isConfigured(r)){let d=se(r,{allowJs:!1});lt(d),t.storeConfig(r,d)}if(n.length===0){let d=ue(r);if(d.type!=="none"){let h=t.getConfig(r),S=await t.getOrBuildWorkspace(r,H(h));t.storeLastAnalyze(r,{kind:"workspace"}),t.startWatching(r);let y=Array.from(S.packages.values()).map(({graph:b,pkg:x})=>({package:x.name,relativeRoot:x.relativeRoot,nodeCount:b.nodes.size}));return w({monorepoType:d.type,packageCount:S.packages.size,packages:y})}}let s=n.map(d=>te.resolve(r,d)),o=t.getConfig(r),i=o?.coverageReportPath?ut(r,o.coverageReportPath):new Map,a=await t.getOrBuild(r,s,i);t.storeLastAnalyze(r,{kind:"single",entryPoints:s,coverageMap:i}),t.startWatching(r);let c=a.serialize(),l=c.nodes.reduce((d,h)=>(d[h.category]=(d[h.category]??0)+1,d),{}),p=a.findCycles(),m=vt(a);return w({nodeCount:c.nodes.length,categories:l,cycles:p,languageCoverage:m})}async function ps(t,e){let{root:r,file:n,depth:s=1,withMeta:o=!1}=e,i=await t.ensureFresh(r),a=wt(i,n,s),c=o?a.map(l=>({...l,...ae(i,l.path)})):a;return w({file:n,dependencies:c})}async function us(t,e){let{root:r,file:n,withMeta:s=!1}=e,o=await t.ensureFresh(r),i=ce(o,n),a=s?i.map(c=>({...c,...ae(o,c.path)})):i;return w({file:n,dependents:a})}async function fs(t,e){let{root:r,file:n,testsOnly:s=!1,cached:o=!1,changedSymbols:i,withMeta:a=!1}=e,c=await t.ensureFresh(r),l=d=>a?d.map(h=>({path:h,...ae(c,h)})):d;if(o){let d=t.getOrBuildChangeImpact(r),h=yt(d,n),S=s?h.filter(b=>c.nodes.get(b)?.category==="test"):h,y=l(S);return w({file:n,affected:y,count:y.length})}let p=Ct(c,n,{testsOnly:s,changedSymbols:i}),m=l(p);return w({file:n,affected:m,count:m.length})}async function ms(t,e){let{root:r,file:n,depth:s=1,withEdgeDetail:o=!1}=e,i=await t.ensureFresh(r),a=Ft(i,n,{depth:s,withEdgeDetail:o});return w({file:n,callers:a,count:a.length})}async function gs(t,e){let{root:r,entryPoints:n}=e,s=n?await t.getOrBuild(r,n.map(a=>te.resolve(r,a))):await t.ensureFresh(r),o=is(r),i=s.findUnusedFiles(o);return w({unusedFiles:i,count:i.length})}async function ds(t,e){let{root:r}=e,n=await t.ensureFresh(r),s=new Map;for(let i of n.nodes.values())for(let a of i.tags)s.set(a.name,(s.get(a.name)??0)+1);let o=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count);return w({tags:o,count:o.length})}async function hs(t,e){let{root:r,coverageThreshold:n}=e,s=await t.ensureFresh(r),o=t.getConfig(r),i=n??o?.coverageThreshold??80;if(!At(s))return w({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let a=[...s.nodes.values()].filter(c=>c.category!=="test"&&c.category!=="config").filter(c=>c.coveragePct!==void 0&&c.coveragePct<i).map(c=>({file:c.path,coveragePct:c.coveragePct}));return w({threshold:i,uncovered:a,count:a.length})}async function ys(t,e){let{root:r}=e,s=[...(await t.ensureFresh(r)).nodes.values()].filter(o=>o.type==="markdown"&&o.staleFor&&o.staleFor.length>0).map(o=>({doc:o.path,staleFor:o.staleFor}));return w({staleDocs:s,count:s.length})}async function xs(t,e){let{root:r,metric:n="cognitiveComplexity",threshold:s=10,limit:o=20}=e,i=await t.ensureFresh(r),a=Et(i,{metric:n,threshold:s,limit:o});return w({metric:n,threshold:s,functions:a,count:a.length})}async function Ss(t,e){let{root:r,minLines:n=6,ignoreLiterals:s=!0,maxPunctuationRatio:o=.5,maxBucketSize:i,limit:a=50}=e,c=await t.ensureFresh(r),l=e.ignoreDirs??[...j,...t.getConfig(r)?.ignoreDirs??[]],{groups:p,skippedBuckets:m}=await kt(c,r,{minLines:n,ignoreLiterals:s,maxPunctuationRatio:o,maxBucketSize:i,limit:a,ignoreDirs:l});return w({minLines:n,groups:p,count:p.length,skippedBuckets:m})}async function bs(t,e){let{root:r,changedFiles:n,featureThreshold:s,format:o="tags"}=e,i=await t.ensureFresh(r),a=n??new qe().getChangedFiles().map(p=>te.relative(r,te.resolve(r,p))),c=s!==void 0?{featureDetection:{minOutDegree:s}}:void 0;if(o==="paths"){let p=ur(i,a,c);return w({changedFiles:a,affectedTests:p,count:p.length})}let l=pr(i,a,c);return w({changedFiles:a,proposedTags:l})}async function ks(t,e){let{root:r,entryPoints:n,featureThreshold:s}=e,o=n?await t.getOrBuild(r,n.map(c=>te.resolve(r,c))):await t.ensureFresh(r),i=W(o.nodes,s!==void 0?{minOutDegree:s}:void 0),a=Array.from(i.values()).sort((c,l)=>l.outDegree-c.outDegree);return w({features:a,count:a.length})}async function vs(t,e){let{root:r,entryPoints:n,filter:s,mermaid:o=!1,slim:i=!0}=e,a=n?await t.getOrBuild(r,n.map(l=>te.resolve(r,l))):await t.ensureFresh(r),c=Oe(a.serialize(),je(s));return o?w(Pe.serialize(R.deserialize(c))):i?w(Tt(c)):w(c)}async function ws(t,e){let{root:r}=e,n=await t.ensureFreshWorkspace(r);return w(Pt(n))}async function Cs(t,e){let{root:r,file:n}=e,o=(await t.ensureFreshWorkspace(r)).getAffectedAcrossPackages(n);return w({file:n,affected:o,count:o.length})}function Fs(t,e){let{root:r}=e,n=t.invalidate(r);return w({root:r,cleared:n,message:n?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function Es(t,e){let{root:r,type:n}=e,s=await t.ensureFresh(r),o=Mt(s);if(n)return w(Dt(o,n));let i=Array.from(o.types.values());return w({count:i.length,types:i})}async function Ts(t,e){let{root:r,paths:n,minOutDegree:s}=e,o=await t.ensureFresh(r),i=Nt(o,s!==void 0?{minOutDegree:s}:void 0);if(n?.length){let c=n.map(l=>i.get(l)).filter(Boolean);return w({count:c.length,modules:c})}let a=Array.from(i.values());return w({count:a.length,modules:a})}async function Ps(t,e){let{root:r,minOutDegree:n}=e,s=await t.ensureFresh(r),o=oe(s,n!==void 0?{minOutDegree:n}:void 0),i=Object.fromEntries(o.features);return w({features:i,unassigned:o.unassigned})}async function As(t,e){let{root:r,function:n}=e,s=await t.ensureFresh(r);return w(dt(s,n))}async function Ns(t,e){let{root:r,name:n}=e,s=await t.ensureFresh(r),o=It(s,n);return w({name:n,matches:o,count:o.length})}async function Is(t,e){let{root:r,entryPoints:n}=e,s=await t.ensureFresh(r),o=n?.length?n:mt(s,r);if(o.length===0)throw new Error("No entry points found. Pass entryPoints explicitly or ensure package.json has a main/exports field.");return w(gt(s,o))}async function Ms(t,e){let r=await t.ensureFresh(e.root),n=await qt(r,e.root,{dryRun:e.dryRun??!1});return w(n)}var Ds=[{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. Omit entryPoints to reuse the cached graph from a prior analyze() call instead of rebuilding.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to reuse the cached graph from a prior analyze() call."}},required:["root"]}},{name:"list_tags",description:"List every distinct tag name present in the graph, with how many nodes carry each one. Call this before querying with tag:<name> to avoid a speculative filter silently returning zero results. Includes all tag kinds \u2014 a superset of what query's slim mode keeps (slim only retains comment-marker and import tags).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_uncovered",description:"Find non-test files whose line coverage is below the configured threshold. Requires a prior analyze() call and coverageReportPath set in mokosh.config. coverageThreshold overrides the config default (default: 80).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},coverageThreshold:{type:"number",description:"Line-coverage % below which a file is considered uncovered. Overrides config value."}},required:["root"]}},{name:"check_doc_drift",description:"Find markdown docs whose referenced files changed more recently than the doc itself \u2014 a commit-recency heuristic for stale documentation, not a content diff. Requires a prior analyze() call with gitStats: true in mokosh.config (otherwise no file has commit-timestamp data and nothing is flagged). See docs/adr-009-markdown-parsing.md for known limitations.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_complex_functions",description:"Find individual functions/methods above a cognitive (or cyclomatic) complexity threshold, sorted worst-first. Requires a prior analyze() call. Populated for TypeScript/JavaScript, Go, and Python.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which score to threshold/sort on (default: cognitiveComplexity)"},threshold:{type:"number",description:"Minimum score to include (default: 10)"},limit:{type:"number",description:"Max results to return, worst-first (default: 20)"}},required:["root"]}},{name:"find_duplicates",description:"Find duplicated code blocks across the project, largest-first. Two matching strategies, picked per file: CSS/SCSS/Less are compared structurally by rule body \u2014 the literal, ordered property:value declarations a rule contains, independent of its selector \u2014 so a genuine copy-pasted declaration list is caught while rules that merely share shape (e.g. display:flex vs display:block) never match. Every other language mokosh parses (TypeScript/JavaScript, Python, Go, CoffeeScript, LiveScript, Lua, Gherkin, Markdown, and Stylus) runs a token-based shingle pipeline instead, partitioned by language family so matching never crosses between Stylus and code languages. Identifiers \u2014 and by default literals \u2014 are normalized before matching in the token-based path, so renamed-variable copies are still caught; blocks that are mostly object/array-literal structural punctuation (e.g. schema/object-literal boilerplate) rather than substantive shared logic are gated out. A block repeated N times across the project is reported once with N occurrences, not as separate pairs. Lock files (package-lock.json, yarn.lock, pnpm-lock.yaml) and files under an ignored directory are always excluded, even if the graph itself contains them. On large repos, tokenizing is offloaded to a worker pool and pathologically common token windows are skipped for scan-time safety (reported as skippedBuckets in the result) so the scan stays within a usable response time. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minLines:{type:"number",description:"Minimum duplicated block size in lines to report (default: 6)"},ignoreLiterals:{type:"boolean",description:"Normalize string/number literals too, not just identifiers, so only structural shape drives a match (default: true). Set false for stricter, exact-text-only matching."},maxPunctuationRatio:{type:"number",description:"Maximum fraction of a token-shingled block's window that may be object/array-literal structural punctuation ({ } : , [ ]) (default: 0.5). Filters out blocks that are mostly schema/object-literal shape instead of substantive shared logic. Does not apply to the CSS/Less/SCSS structural comparator. Set 1 to disable."},maxBucketSize:{type:"number",description:"Skip a hash bucket's pairwise comparison once it holds more than this many matching locations (default: 400). Bounds worst-case scan time on large repos where a single pathologically common token window would otherwise blow up quadratically. Set a very large number to disable."},ignoreDirs:{type:"array",items:{type:"string"},description:"Directory names to exclude, matched against any path segment (default: DEFAULT_IGNORE_DIRS merged with this root's configured ignoreDirs, if any). Pass [] to disable."},limit:{type:"number",description:"Max duplicate blocks to return, largest-first (default: 50)"}},required:["root"]}},{name:"propose_tags",description:"Propose what to run based on changed files. Pass changedFiles explicitly or omit to use git diff. format='tags' (default) returns test tags for CI tag-filtering; format='paths' returns test file paths ready to pipe directly to a test runner (e.g. vitest). Feature hubs act as traversal boundaries in both modes.",inputSchema:{type:"object",properties:{root:{type:"string"},changedFiles:{type:"array",items:{type:"string"},description:"Changed files relative to root. Omit to read from git diff."},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. Tags are filtered to kinds comment-marker and import only; function/class/variable/type/library tags are dropped in slim output. Use list_tags to see the full tag inventory, or pass slim: false to get every tag kind on matching nodes."}},required:["root","filter"]}},{name:"get_workspace_packages",description:"List all workspace packages detected in a monorepo, with their node counts and inter-package dependencies. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"}},required:["root"]}},{name:"get_workspace_affected",description:"Cross-package blast-radius analysis. Returns every file that could be affected if a given file changes, annotated with the package it belongs to. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"},file:{type:"string",description:"Monorepo-root-relative path of the changed file (e.g. 'packages/shared/src/utils.ts')"}},required:["root","file"]}},{name:"get_type_graph",description:"Return type-level relationships for the project. Without a type name, returns an inventory of all interfaces, classes, enums, and type aliases with their file and kind. With a type name, returns which files import that type (usedByFiles) and which types the defining file imports (uses). Requires a prior analyze() call. Only covers TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},type:{type:"string",description:"Exact exported name of the type to look up (e.g. 'FileNode'). Omit to get the full type inventory."}},required:["root"]}},{name:"get_module_responsibility",description:"Return what each file is responsible for: its semantic role, JSDoc description (when present), exported symbol names, and which feature hub it belongs to. Pass specific paths to filter, or omit paths to get all files. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},paths:{type:"array",items:{type:"string"},description:"Project-relative file paths to include. Omit to return all files."},minOutDegree:{type:"number",description:"Min imports for a file to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_feature_graph",description:"Group files by domain: returns which files each feature hub (high-import orchestrator) transitively owns. Each file is assigned to the most specific hub that can reach it (lowest out-degree wins). Use this instead of a full query when answering 'what files are in the X feature/module?' \u2014 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 mr(){let t=new tt,e=new Yc({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(Zc,async()=>({tools:Ds})),e.setRequestHandler(Xc,async r=>{let{name:n,arguments:s}=r.params,o=s,a={analyze:c=>ls(t,c),get_dependencies:c=>ps(t,c),get_dependents:c=>us(t,c),get_affected:c=>fs(t,c),get_callers:c=>ms(t,c),find_symbol:c=>Ns(t,c),find_unused:c=>gs(t,c),find_uncovered:c=>hs(t,c),list_tags:c=>ds(t,c),check_doc_drift:c=>ys(t,c),find_complex_functions:c=>xs(t,c),find_duplicates:c=>Ss(t,c),propose_tags:c=>bs(t,c),detect_features:c=>ks(t,c),get_type_graph:c=>Es(t,c),get_module_responsibility:c=>Ts(t,c),get_feature_graph:c=>Ps(t,c),get_call_graph:c=>As(t,c),get_api_surface:c=>Is(t,c),query:c=>vs(t,c),get_workspace_packages:c=>ws(t,c),get_workspace_affected:c=>Cs(t,c),clear_cache:c=>Fs(t,c),apply_tags:c=>Ms(t,c)}[n];if(!a)throw new Error(`Unknown tool: ${n}`);try{return cs(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 tl(){let t=mr(),e=new el;await t.connect(e)}tl().catch(console.error);export{mr as createMcpServer};
34
36
  //# sourceMappingURL=mcp.mjs.map