scip-query 0.6.6 → 0.6.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -1
- package/dist/chunk-2AUZ3PLO.js +2 -0
- package/dist/{chunk-PIRXZGV6.js → chunk-2CC7RA6B.js} +2 -2
- package/dist/{chunk-OQZF2DQJ.js → chunk-2R7OKZE5.js} +2 -2
- package/dist/{chunk-7PRMSA4Z.js → chunk-2YA36CXK.js} +2 -2
- package/dist/chunk-3A2M7AF3.js +4 -0
- package/dist/chunk-3EJRPTTB.js +2 -0
- package/dist/chunk-3SWWYJPB.js +6 -0
- package/dist/chunk-4M4FEWBL.js +7 -0
- package/dist/{chunk-UUIWMLDX.js → chunk-4Y6KUJDO.js} +2 -2
- package/dist/{chunk-MO65UK5V.js → chunk-55ZJ2FCW.js} +2 -2
- package/dist/chunk-6FLGPRBR.js +5 -0
- package/dist/chunk-6XRB6ATD.js +16 -0
- package/dist/{chunk-VEXS3I3N.js → chunk-7EQ4J66C.js} +2 -2
- package/dist/{chunk-QFBJZHMV.js → chunk-7TGEXAN5.js} +2 -2
- package/dist/chunk-ABLXPGAZ.js +2 -0
- package/dist/{chunk-IKQYNTW3.js → chunk-BG7YU4DJ.js} +2 -2
- package/dist/chunk-D2R6IIEO.js +2 -0
- package/dist/{chunk-YJODB2F5.js → chunk-E47WMJ5F.js} +2 -2
- package/dist/chunk-EEA3R37V.js +11 -0
- package/dist/chunk-FAN2CVZT.js +2 -0
- package/dist/{chunk-HVNVO6UW.js → chunk-FYO3FPFH.js} +2 -2
- package/dist/chunk-G47V5V3U.js +90 -0
- package/dist/chunk-GS55K4WJ.js +85 -0
- package/dist/{chunk-I377UMS2.js → chunk-HADDFTMU.js} +2 -2
- package/dist/chunk-HTJ5BOYP.js +10 -0
- package/dist/chunk-IARIBTCL.js +2 -0
- package/dist/{chunk-E2V5SE6M.js → chunk-IBWYWAWE.js} +2 -2
- package/dist/{chunk-DLWRLPKO.js → chunk-ILQSK2KJ.js} +2 -2
- package/dist/{chunk-KBGFYKOJ.js → chunk-JVMXNDRU.js} +2 -2
- package/dist/{chunk-O6VBAW7P.js → chunk-K345WFTU.js} +2 -2
- package/dist/{chunk-GPY33RTH.js → chunk-K6ULLR7M.js} +2 -2
- package/dist/chunk-KCC3GMCX.js +2 -0
- package/dist/{chunk-7LSCW7NF.js → chunk-KQWFRAQI.js} +2 -2
- package/dist/chunk-KRVRD6KZ.js +5 -0
- package/dist/{chunk-QFZE73XF.js → chunk-KYGNCIJ6.js} +8 -8
- package/dist/chunk-LHLXHH43.js +2 -0
- package/dist/{chunk-IZ4KV37N.js → chunk-M7GBLQG4.js} +2 -2
- package/dist/{chunk-WFDTS7XL.js → chunk-MEVK6R7N.js} +2 -2
- package/dist/{chunk-Q2ALKKSE.js → chunk-OCQN6WF4.js} +2 -2
- package/dist/{chunk-ERRUE5G4.js → chunk-PQTGBYXV.js} +2 -2
- package/dist/{chunk-ZHHMG4UC.js → chunk-QYWGC7JV.js} +2 -2
- package/dist/{chunk-TLRA5TR6.js → chunk-R373SHXM.js} +2 -2
- package/dist/{chunk-MXWC53GJ.js → chunk-RRWPHKZA.js} +2 -2
- package/dist/{chunk-6GPFHZP3.js → chunk-RUAJV3TN.js} +2 -2
- package/dist/{chunk-Q4R2IYA3.js → chunk-S57GUI2T.js} +2 -2
- package/dist/chunk-SVUVC5VS.js +2 -0
- package/dist/{chunk-4TX5IMMK.js → chunk-T426XELO.js} +2 -2
- package/dist/chunk-TX7BHRMT.js +2 -0
- package/dist/{chunk-YXMHTJYY.js → chunk-TYRPQE6R.js} +2 -2
- package/dist/{chunk-Y4DS3MDC.js → chunk-WPY46NIL.js} +2 -2
- package/dist/{chunk-CYJMOTIH.js → chunk-X3Z4KZNX.js} +2 -2
- package/dist/{chunk-7X7FLQC5.js → chunk-ZNNCDAYX.js} +2 -2
- package/dist/cli.js +156 -145
- package/dist/{db-BZPa7dzJ.d.ts → db-DdlToIC-.d.ts} +1 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/queries/affected.d.ts +1 -1
- package/dist/queries/affected.js +1 -1
- package/dist/queries/bottlenecks.d.ts +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +1 -1
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +1 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +1 -1
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/code.d.ts +1 -1
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +2 -1
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +1 -1
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +1 -1
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +1 -1
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +1 -1
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +1 -1
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +1 -1
- package/dist/queries/dead.js +1 -1
- package/dist/queries/deep-chains.d.ts +1 -1
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +1 -1
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-impact.d.ts +20 -2
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/drift.d.ts +1 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -1
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +1 -1
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +1 -1
- package/dist/queries/health-cache-control.d.ts +15 -0
- package/dist/queries/health-cache-control.js +2 -0
- package/dist/queries/health.d.ts +66 -2
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +1 -1
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +1 -1
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +1 -1
- package/dist/queries/imports.js +1 -1
- package/dist/queries/index.d.ts +3 -3
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +1 -1
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/members.d.ts +1 -1
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +1 -1
- package/dist/queries/methods.js +1 -1
- package/dist/queries/outline.d.ts +1 -1
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +2 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +1 -1
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +1 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/similar-chains.d.ts +1 -1
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +1 -1
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +2 -1
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +1 -1
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +4 -2
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +1 -1
- package/dist/queries/surface.d.ts +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +1 -1
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +1 -1
- package/dist/queries/system.js +1 -1
- package/dist/queries/trace.d.ts +1 -1
- package/dist/queries/trace.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +2 -1
- package/dist/queries/wrapper-candidates.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-25HOGELX.js +0 -2
- package/dist/chunk-2TLYCK2L.js +0 -11
- package/dist/chunk-3PVIYZ74.js +0 -84
- package/dist/chunk-6DVA22YE.js +0 -2
- package/dist/chunk-7YI2M2AQ.js +0 -2
- package/dist/chunk-AADJ7MCQ.js +0 -2
- package/dist/chunk-AV7BOODV.js +0 -4
- package/dist/chunk-AXP4H62Q.js +0 -6
- package/dist/chunk-C4C3T4K3.js +0 -2
- package/dist/chunk-CSRPJCWO.js +0 -2
- package/dist/chunk-GBDZY73J.js +0 -2
- package/dist/chunk-KW2F3WSV.js +0 -5
- package/dist/chunk-NIN762LD.js +0 -5
- package/dist/chunk-QPJG6VRT.js +0 -16
- package/dist/chunk-TUV2VI7D.js +0 -7
- package/dist/chunk-UAPNU7UP.js +0 -2
- package/dist/chunk-URCJTFOD.js +0 -2
- package/dist/chunk-VRC3WKKE.js +0 -2
- package/dist/chunk-Z4AMQWVY.js +0 -90
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`),n}function
|
|
2
|
+
var Vl=Object.defineProperty;var Jl=(e,t)=>{for(var n in t)Vl(e,n,{get:t[n],enumerable:!0})};import{program as x}from"commander";import{spawnSync as Hl}from"child_process";import{createRequire as wx}from"module";import{existsSync as jl,realpathSync as Bl}from"fs";import{fileURLToPath as Zr}from"url";import{readFileSync as ql,writeFileSync as zl,existsSync as ti,mkdirSync as Gl}from"fs";import{join as je,resolve as ei}from"path";import{createHash as Kl}from"crypto";import{homedir as Yl}from"os";var ni=".scipquery.json",Ql={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]};function Ee(e){let t=je(e,ni);if(!ti(t))return{};try{let n=ql(t,"utf-8");return JSON.parse(n)}catch{return{}}}function ri(e){return{...Ql,...e.watch}}function Xl(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return jn(n);if(t?.dbPath)return jn(ei(e,t.dbPath));let i=process.env.XDG_CACHE_HOME||je(Yl(),".cache"),s=Kl("sha256").update(ei(e)).digest("hex").slice(0,12),o=je(i,"scip-query","projects",s);return jn(o)}function De(e,t){let n=Xl(e,t);return{cacheDir:n,dbPath:je(n,"index.db"),indexPath:je(n,"index.scip"),metaPath:je(n,"meta.json")}}function ii(e,t){let n=je(e,ni);return ti(n)||zl(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
|
|
3
|
+
`),n}function jn(e){return Gl(e,{recursive:!0}),e}import{execFile as Id,execFileSync as Rd}from"child_process";import{closeSync as Cd,existsSync as Ue,mkdirSync as Vi,mkdtempSync as vd,openSync as Nd,readFileSync as Ed,renameSync as tt,rmSync as nt,writeFileSync as Ji}from"fs";import{cpus as Dd}from"os";import{basename as Xt,dirname as We,extname as Ld,join as se}from"path";import{execFileSync as Wt}from"child_process";import{platform as Ut,arch as Zl}from"os";var si=Ut()==="win32",oi="v0.7.0";function Ht(e){let t=si?"where":"which";try{return Wt(t,[e],{stdio:"pipe"}),!0}catch{return!1}}function Bn(){try{return Wt(si?"where":"which",["scip"],{stdio:"pipe"}),!0}catch{return!1}}function ec(){let e=Ut(),t=Zl(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;case"win32":n="windows",i="zip";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let s=`scip-${n}-${r}.${i}`;return{url:`https://github.com/sourcegraph/scip/releases/download/${oi}/${s}`,filename:s}}function Hn(){let e=ec();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Ut()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
|
|
4
4
|
`),console.log("Or download manually:")):console.log("Download from:"),console.log(e?` ${e.url}
|
|
5
|
-
`:` https://github.com/sourcegraph/scip/releases/tag/${
|
|
6
|
-
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function
|
|
5
|
+
`:` https://github.com/sourcegraph/scip/releases/tag/${oi}
|
|
6
|
+
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function ai(e){if(Ut()==="darwin"&&Ht("brew")){e("Installing scip CLI via Homebrew...");try{if(Wt("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),Ht("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`Homebrew install failed: ${n}`)}}if(Ht("go")){e("Installing scip CLI via go install...");try{if(Wt("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),Ht("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e("Install manually from: https://github.com/sourcegraph/scip/releases"),!1}import fc from"better-sqlite3";import{execFileSync as gc}from"child_process";import{existsSync as hc,readdirSync as yc,readFileSync as bc}from"fs";import{extname as Jt,join as pi}from"path";import tc from"ignore";import{readFileSync as nc,existsSync as Wn}from"fs";import{dirname as Un,isAbsolute as li,join as Vn,relative as rc,resolve as ic}from"path";function Xe(e){let t=tc(),n=!1,r=sc(e);for(let i of r)try{let s=nc(i,"utf-8");t.add(s),n=!0}catch{}return n||t.add(oc),{isIgnored:i=>ci(t,e,i),filter:i=>i.filter(s=>!ci(t,e,s))}}function sc(e){let t=[],n=Vn(e,".gitignore");Wn(n)&&t.push(n);let r=Un(e),i=0;for(;r!==Un(r)&&i<5;){let s=Vn(r,".gitignore");if(Wn(s)&&t.push(s),Wn(Vn(r,".git")))break;r=Un(r),i++}return t}var oc=`
|
|
7
7
|
# Dependencies
|
|
8
8
|
node_modules/
|
|
9
9
|
vendor/
|
|
@@ -60,15 +60,15 @@ Thumbs.db
|
|
|
60
60
|
|
|
61
61
|
# Type definitions (often noise in queries)
|
|
62
62
|
*.d.ts
|
|
63
|
-
`;function
|
|
63
|
+
`;function ci(e,t,n){let r=ac(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function ac(e,t){if(!t||t===".")return null;if(!li(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=li(t)?t:ic(e,t),r=rc(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readdirSync as lc}from"fs";import{extname as ui,join as cc}from"path";function A(e){let t=new WeakMap,n=r=>{let i=t.get(r);return i||(i=new Map,t.set(r,i)),i};return{get(r,i,s){let o=n(r);if(o.has(i))return o.get(i);let a=s();return o.set(i,a),a},invalidate(r,i){t.get(r)?.delete(i)},invalidateAll(r){t.delete(r)},size(r){return t.get(r)?.size??0}}}function Be(e){let t=new WeakMap;return{get(n,r){let i=t.get(n);if(i)return i.value;let s=r();return t.set(n,{value:s}),s},invalidate(n){t.delete(n)},has(n){return t.has(n)}}}function Vt(e){let t=new WeakMap,n=r=>{let i=t.get(r);return i||(i=new Map,t.set(r,i)),i};return{get(r,i,s,o){let a=n(r),l=a.get(i);if(l&&l.source===s)return l.value;let c=o();return a.set(i,{source:s,value:c}),c},invalidate(r,i){t.get(r)?.delete(i)},invalidateAll(r){t.delete(r)}}}var uc=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],di=[".vue"],mi=new Set(uc.map(e=>e.toLowerCase())),dc=[...mi].sort().join(","),Jn=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function Le(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(l=>l.toLowerCase()),s=i?new Set(i):mi,o=i?[...s].sort().join(","):dc,a=`${n?"1":"0"}|${r?"1":"0"}|${o}`;return mc.get(e,a,()=>{let l=new Set;if(n){let c=e.all(`SELECT relative_path
|
|
64
64
|
FROM documents
|
|
65
65
|
WHERE 1 = 1
|
|
66
|
-
${e.pathExclusionsFor("documents")}`);for(let u of c)e.isIgnored(u.relative_path)||s.has(
|
|
67
|
-
VALUES (?, ?, NULL, ?)`),l=i.transaction(u=>{let d=0;for(let m of u){if(s.has(m))continue;let
|
|
68
|
-
`).filter(r=>r&&t.has(
|
|
69
|
-
`)){if(!r)continue;let i=
|
|
70
|
-
`).filter(Boolean)}catch{return null}}function
|
|
71
|
-
`)}function
|
|
66
|
+
${e.pathExclusionsFor("documents")}`);for(let u of c)e.isIgnored(u.relative_path)||s.has(ui(u.relative_path).toLowerCase())&&l.add(u.relative_path)}if(r)for(let c of pc(e.config.projectRoot,s))e.isIgnored(c)||l.add(c);return[...l].sort()})}var mc=A("source-files");function pc(e,t){let n=new Set,r=i=>{let s=i?cc(e,i):e,o;try{o=lc(s,{withFileTypes:!0})}catch{return}for(let a of o)if(!Jn.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(ui(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}function we(e){let t=new Set((e.extensions??di).map(s=>s.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!hc(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Xe(e.projectRoot),r=Sc(e.projectRoot,t).filter(s=>!n.isIgnored(s)),i=new fc(e.dbPath);try{let s=_c(i,r),o=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
67
|
+
VALUES (?, ?, NULL, ?)`),l=i.transaction(u=>{let d=0;for(let m of u){if(s.has(m))continue;let f=bc(pi(e.projectRoot,m),"utf-8"),h=o.run(Ic(m),m,f);d+=Number(h.changes)}return d})(r),c={scanned:r.length,inserted:l,existing:r.length-l};return e.onStatus?.(`Augmented SQLite documents with ${l} auxiliary source file${l===1?"":"s"} (${c.existing} already present).`),c}finally{i.close()}}function Sc(e,t){let n=xc(e,t);if(n)return n;let r=[],i=s=>{let o=s?pi(e,s):e,a;try{a=yc(o,{withFileTypes:!0})}catch{return}for(let l of a){if(Jn.has(l.name))continue;let c=s?`${s}/${l.name}`:l.name;if(l.isDirectory()){i(c);continue}t.has(Jt(l.name).toLowerCase())&&r.push(c)}};return i(""),r.sort()}function xc(e,t){try{return gc("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
|
|
68
|
+
`).filter(r=>r&&t.has(Jt(r).toLowerCase())).sort()}catch{return null}}function _c(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let s=t.slice(i,i+r),o=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${s.map(()=>"?").join(",")})`).all(...s);for(let a of o)n.add(a.relative_path)}return n}function Ic(e){return Jt(e).toLowerCase()===".vue"?"vue":Jt(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as Rc}from"child_process";import{existsSync as Cc,readdirSync as gi}from"fs";import{extname as hi,join as yi}from"path";var vc=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Nc=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function He(e){let t=[],n=Ec(e),r=kc(e);for(let i of Nc){if(Dc(e,i.files)){t.push(i.language);continue}if(Lc(n,i.globs)){t.push(i.language);continue}Oc(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&fi(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&fi(t,"c"),t}function Ec(e){try{return gi(e)}catch{return[]}}function Dc(e,t){return t?.length?t.some(n=>Cc(yi(e,n))):!1}function Lc(e,t){return t?.length?e.some(n=>t.some(r=>wc(n,r))):!1}function wc(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function kc(e){let t=Pc(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let s;try{s=gi(i,{withFileTypes:!0})}catch{continue}for(let o of s){if(o.name.startsWith(".")&&!o.name.endsWith("proj")&&!o.name.endsWith("sln")&&o.isDirectory())continue;let a=yi(i,o.name);if(o.isDirectory()){vc.has(o.name)||r.push(a);continue}let l=hi(o.name).toLowerCase();l&&n.add(l)}}return n}function Pc(e){try{let t=Rc("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
|
|
69
|
+
`)){if(!r)continue;let i=hi(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Oc(e,t){return t?.length?t.some(n=>e.has(n)):!1}function fi(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as bi,readdirSync as Mc}from"fs";import{join as qn}from"path";var Tc={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n})=>{let r=["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&r.splice(1,0,"--pnpm-workspaces"),{binary:n,args:r}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Si(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Si(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=qn(e,"vendor","bin","scip-php"),r=qn(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",bi(r)?r:bi(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function qt(e){return Tc[e]}function Si(e,t){let n;try{n=Mc(e)}catch{return null}for(let r of n)if(t.some(i=>r.endsWith(i)))return qn(e,r);return null}import{readFileSync as Fc,writeFileSync as Ac}from"fs";import{create as zn}from"@bufbuild/protobuf";import{deserializeSCIP as $c,serializeSCIP as jc,DocumentSchema as Bc,IndexSchema as Hc,SymbolInformationSchema as Wc}from"@c4312/scip";function Uc(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Vc(e),n=Jc(e.flatMap(i=>i.documents??[])),r=_i(e.flatMap(i=>i.externalSymbols??[]));return zn(Hc,{metadata:t,documents:n,externalSymbols:r})}function xi(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>$c(Fc(i))),r=Uc(n);return Ac(t,Buffer.from(jc(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function Vc(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function Jc(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,zn(Bc,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:[...r.occurrences,...n.occurrences],symbols:_i([...r.symbols,...n.symbols]),text:zc(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function _i(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,zn(Wc,{symbol:r.symbol,documentation:Gc([...r.documentation,...n.documentation]),relationships:qc([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function qc(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function zc(e,t){return e?t?e.length>=t.length?e:t:e:t}function Gc(e){return[...new Set(e)]}import{execFileSync as Kc}from"child_process";import{createHash as Yc}from"crypto";import{readdirSync as Qc,readFileSync as Xc}from"fs";import{join as Ii}from"path";function Zc(e){return(eu(e)??tu(e)).filter(t=>t&&!Ri(t)).sort()}function zt(e){return Zc(e).map(t=>{let n=Ii(e,t);try{let r=Xc(n);return{path:t,size:r.byteLength,hash:Yc("sha256").update(r).digest("hex")}}catch{return{path:t,size:-1,hash:"unreadable"}}})}function eu(e){try{return Kc("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
|
|
70
|
+
`).filter(Boolean)}catch{return null}}function tu(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Ii(e,r):e,s;try{s=Qc(i,{withFileTypes:!0})}catch{continue}for(let o of s){let a=r?`${r}/${o.name}`:o.name;if(o.isDirectory()){Ri(a)||n.push(a);continue}t.push(a)}}return t}function Ri(e){return e.split("/").some(n=>nu.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var nu=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);import{readFileSync as ru,writeFileSync as iu}from"fs";import{create as Ci}from"@bufbuild/protobuf";import{deserializeSCIP as su,DocumentSchema as ou,IndexSchema as au,serializeSCIP as lu,SymbolRole as cu}from"@c4312/scip";function vi(e){let t;try{t=su(ru(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=uu(t);return n.removedDefinitionOccurrences>0&&iu(e,Buffer.from(lu(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function uu(e){let t=new Set;for(let s of e.documents)for(let o of s.symbols)o.symbol&&t.add(o.symbol);for(let s of e.externalSymbols)s.symbol&&t.add(s.symbol);let n=0,r=0,i=[];for(let s of e.documents){let o=s.occurrences.filter(a=>(a.symbolRoles&cu.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(o.length===s.occurrences.length){i.push(s);continue}r+=1,i.push(Ci(ou,{language:s.language,relativePath:s.relativePath,occurrences:o,symbols:s.symbols,text:s.text,positionEncoding:s.positionEncoding}))}return{index:n===0?e:Ci(au,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{execFileSync as Kt}from"child_process";import{existsSync as Gn,readFileSync as du}from"fs";import{createRequire as mu}from"module";import{platform as Ei}from"os";import{dirname as Ni,join as Gt}from"path";var pu=mu(import.meta.url),fu=Ei()==="win32";function ft(e){let t=fu?"where":"which";try{return Kt(t,[e],{stdio:"pipe"}),!0}catch{return!1}}function Kn(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Yt(e){let t=Kn(e);return t.length===1?t[0]:t.join(" or ")}function Ze(e){for(let t of Kn(e))if(ft(t))return t;return hu(e)}function Di(e){return Ze(e)!==null||gu(e)}function gu(e){return Li(e)!==null}function hu(e){let t=Li(e);if(!t)return null;let r=JSON.parse(du(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Gt(Ni(t),r);for(let i of Kn(e)){let s=r[i];if(s)return Gt(Ni(t),s)}return null}function Li(e){if(!e.bundledNpmPackage)return null;try{return pu.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function Yn(e,t){for(let n of e.projectLocalBinaries??[]){let r=Gt(t,n);if(Gn(r))return r}return null}function yu(e,t){return Yn(e,t)??Ze(e)}function wi(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Qn(n,t))return t;let r=Oi(n,t);return r?{...t,DOTNET_ROOT:r}:t}function ki(e,t){let n=Yt(e),r=t?yu(e,t):Ze(e);if(!r)return{language:e.language,binaryLabel:n,installed:!1,runnable:!1,resolvedBinary:null,installUrl:e.installUrl};if(e.indexerBinary!=="scip-dotnet")return{language:e.language,binaryLabel:n,installed:!0,runnable:!0,resolvedBinary:r};let i=bu(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function Pi(e,t){let n=e.installMethods,r=Yt(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n)if(ft(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Kt(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let s=Ze(e);if(s){let o=s===e.indexerBinary?"":` (using ${s})`;return t(`Successfully installed ${r} via ${i.label}${o}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(s){let o=s instanceof Error?s.message:String(s);t(`${i.label} install failed: ${o}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function bu(e){if(Qn(e,process.env))return{runnable:!0};let t=Oi(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Mi(process.env);return{runnable:!1,note:n.length>0?`.NET 9 runtime still unavailable after checking ${n.join(", ")}`:"binary is present, but scip-dotnet still needs a .NET 9 runtime"}}function Oi(e,t){for(let n of Mi(t))if(Qn(e,{...t,DOTNET_ROOT:n}))return n;return null}function Mi(e){let t=[],n=e.DOTNET_ROOT;if(n&&Gn(n)&&t.push(n),Ei()==="darwin"&&ft("brew"))try{let r=Kt("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=Gt(r,"libexec");Gn(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Qn(e,t){try{return Kt(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import Su from"better-sqlite3";import{createRequire as xu}from"module";import{existsSync as Fi,mkdtempSync as _u,readFileSync as gt,rmSync as Iu,statSync as Ru,writeFileSync as Cu}from"fs";import{cpus as vu,tmpdir as Nu}from"os";import{dirname as Zn,extname as Eu,join as et,relative as Du,resolve as Ai}from"path";import{pathToFileURL as Lu}from"url";import{Worker as wu}from"worker_threads";function er(e){we({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=Ai(e.projectRoot,e.tsconfig);if(!Fi(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Su(e.dbPath);try{let r=Xu(n,e.projectRoot),i=et(Zn(e.dbPath),"augment-vue-meta.json"),s=Ti(n,e.projectRoot,e.tsconfig),o=ku(i,s,e.onStatus);if(o)return o;let a=ad(n,e.projectRoot,r),l=Pu(n,e,t,r,a),c=dd(l.occurrences),u=Ou(n,e,r,a,c);e.onStatus?.(`Resolved ${c.length} Vue references with Volar; inserted ${u} mentions.`);let d=Mu(r,c,u,l,a);return Fu(i,Ti(n,e.projectRoot,e.tsconfig),d),d}finally{n.close()}}function ku(e,t,n){let r=Tu(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function Pu(e,t,n,r,i){if(Vu(r))return Ju({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:t.tsconfig,vueFiles:r});let s=yd(),o=Zu(t.projectRoot,n);return Au({projectRoot:t.projectRoot,vueFiles:o.fileNames.filter(a=>a.endsWith(".vue")),context:o,symbolLookup:id(e,t.projectRoot,s),vueSymbolLookup:i,sourceCache:s})}function Ou(e,t,n,r,i){return ld(e,t.projectRoot,n,r,i)}function Mu(e,t,n,r,i){return{vueFiles:e.length,resolvedReferences:t.length,insertedMentions:n,skippedReferences:r.skippedReferences,syntheticSymbols:i.syntheticSymbols}}function Tu(e,t){try{let n=JSON.parse(gt(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function Fu(e,t,n){Cu(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
|
|
71
|
+
`)}function Ti(e,t,n){let r=e.prepare(`
|
|
72
72
|
SELECT
|
|
73
73
|
(SELECT COUNT(*) FROM documents) AS documents,
|
|
74
74
|
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
@@ -77,7 +77,7 @@ Thumbs.db
|
|
|
77
77
|
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
78
78
|
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
79
79
|
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
80
|
-
`).get();return{version:2,tsconfig:n,files:
|
|
80
|
+
`).get();return{version:2,tsconfig:n,files:zt(t),db:r}}function Au(e){let t=[],n=0,r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let s=$u(e,i);t.push(...s.occurrences),n+=s.skippedReferences}return{occurrences:t,skippedReferences:n}}function $u(e,t){let n=e.context.language.scripts.get(t.fileName),r=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let i=e.sourceCache(t.fileName);if(!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let s=e.context.language.maps.get(r,n),o=ht(e.projectRoot,t.fileName),a=[...pd(i.text)],l={tokens:a.filter(c=>c.start>=t.startOffset&&c.start<t.endOffset),tokenByStart:new Map(a.map(c=>[c.start,c])),tokenTextCounts:Hu(a),processedStarts:new Set};return ju({...e,fileName:t.fileName,sourceInfo:i,sourceFile:o,map:s,tokenContext:l})}function ju(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=fd(e.map,r.start);if(i===null)continue;let o=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!gd(e.projectRoot,l.fileName));if(!o){n++;continue}let a=ud(o,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}$i(t,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),Bu(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function Bu(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of Wu(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(s))continue;let o=t.tokenContext.tokenByStart.get(s);o&&($i(e,t.sourceInfo,t.sourceFile,o,i),t.tokenContext.processedStarts.add(s))}}function $i(e,t,n,r,i){let s=Ui(t,r.start);e.push({sourceFile:n,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+r.text.length,symbolId:i})}function Hu(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Wu(e,t,n,r,i,s){let o=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let l of o)if(l.fileName===t)for(let c of l.highlightSpans){let u=Uu(r,c.textSpan.start,s,i.text);u!==null&&a.push(u)}return a}function Uu(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let s=Wi(e,t);if(s===null)return null;let o=n.get(s);return o?.text===r?o.start:null}function Vu(e){return e.length>=8&&ji(e.length)>1}function Ju(e){let t=ji(e.vueFiles.length),n=zu(e.vueFiles),r=Ku(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),s=_u(et(Nu(),"scip-query-vue-workers-")),o=new SharedArrayBuffer(4),a=new Int32Array(o),l=qu(),c=Date.now();try{for(let d=0;d<r.length;d++)new wu(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[d],resultPath:et(s,`${d}.json`),sharedBuffer:o}});for(;Atomics.load(a,0)<r.length;){if(Date.now()-c>l)throw new Error(`Vue reference workers timed out after ${(l/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let u=r.map((d,m)=>{let f=JSON.parse(gt(et(s,`${m}.json`),"utf-8"));if(!f.ok)throw new Error(`Vue reference worker failed: ${f.error}`);return f.result});return{occurrences:u.flatMap(d=>d.occurrences),skippedReferences:u.reduce((d,m)=>d+m.skippedReferences,0)}}finally{Iu(s,{recursive:!0,force:!0})}}function ji(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:Math.min(8,Math.max(1,vu().length-1));return Math.max(1,Math.min(e,n))}function qu(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function zu(e){let t=Gu(),n=[];for(let r of e){let i=Bi(r),s=Math.max(1,Math.ceil(i/t));for(let o=0;o<s;o++)n.push({fileName:r,startOffset:Math.floor(i*o/s),endOffset:o===s-1?Number.POSITIVE_INFINITY:Math.floor(i*(o+1)/s),countFileSkip:o===0})}return n}function Gu(){return Number.POSITIVE_INFINITY}function Ku(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Yu(i)})).sort((i,s)=>s.weight-i.weight);for(let i of r){let s=n.reduce((o,a)=>a.weight<o.weight?a:o);s.tasks.push(i.task),s.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function Yu(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Bi(e.fileName)-e.startOffset)}function Bi(e){try{return Ru(e).size}catch{return 1}}function Qu(e){e.transaction(()=>{e.prepare(`
|
|
81
81
|
DELETE FROM mentions
|
|
82
82
|
WHERE chunk_id IN (
|
|
83
83
|
SELECT c.id
|
|
@@ -92,12 +92,12 @@ Thumbs.db
|
|
|
92
92
|
FROM documents
|
|
93
93
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
94
94
|
)
|
|
95
|
-
`).run()})()}function
|
|
95
|
+
`).run()})()}function Xu(e,t){return e.prepare(`
|
|
96
96
|
SELECT relative_path AS relativePath
|
|
97
97
|
FROM documents
|
|
98
98
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
99
99
|
ORDER BY relative_path
|
|
100
|
-
`).all().map(r=>
|
|
100
|
+
`).all().map(r=>Ai(t,r.relativePath))}function Zu(e,t){let{vueCore:n,ts:r,volarTs:i}=ed(e),{parsed:s,vueOptions:o}=td(n,r,t),a=Zn(t),l=n.createVueLanguagePlugin(r,s.options,o,f=>f),c=nd(n,r,l),u=rd(a,s),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,c,f=>f,u),m=r.createLanguageService(d);return{ts:r,language:c,languageService:m,fileNames:s.fileNames,configDir:a}}function ed(e){let t=xu(Lu(et(e,"package.json")).href);return{vueCore:Xn(t,"@vue/language-core",e),ts:Xn(t,"typescript",e),volarTs:Xn(t,"@volar/typescript",e)}}function td(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let s=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(s.globalTypesPath=e.createGlobalTypesWriter(s,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,Zn(n),void 0,n,void 0,e.getAllExtensions(s).map(o=>({extension:o.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:s}}function nd(e,t,n){let r={},i=e.createLanguage([n],new Map,s=>{if(!Fi(s))return;let o=gt(s,"utf-8");r.current?.scripts.set(s,t.ScriptSnapshot.fromString(o),n.getLanguageId(s)??hd(s))});return r.current=i,i}function rd(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Xn(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function id(e,t,n){let r=sd(e);return i=>{let s=ht(t,i.fileName),o=n(i.fileName);if(!o)return null;let a=Ui(o,i.textSpan.start),l=r.get(s);if(!l)return null;let c=l.containingByLine.get(a.line);return c!==void 0?c:od(l.starts,a.line,2)}}function sd(e){let t=e.prepare(`
|
|
101
101
|
SELECT
|
|
102
102
|
d.relative_path AS relativePath,
|
|
103
103
|
der.start_line AS startLine,
|
|
@@ -106,31 +106,31 @@ Thumbs.db
|
|
|
106
106
|
FROM defn_enclosing_ranges der
|
|
107
107
|
JOIN documents d ON d.id = der.document_id
|
|
108
108
|
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
109
|
-
`).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId});for(let s=r.startLine;s<=r.endLine;s++)i.containingByLine.set(s,r.symbolId)}for(let r of n.values())r.starts.sort((i,s)=>i.line-s.line);return n}function
|
|
109
|
+
`).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId});for(let s=r.startLine;s<=r.endLine;s++)i.containingByLine.set(s,r.symbolId)}for(let r of n.values())r.starts.sort((i,s)=>i.line-s.line);return n}function od(e,t,n){let r=0,i=e.length-1;for(;r<=i;){let o=Math.floor((r+i)/2);e[o].line<t?r=o+1:i=o-1}let s=null;for(let o of[i,r]){let a=e[o];if(!a)continue;let l=Math.abs(a.line-t);l>n||(!s||l<s.distance)&&(s={distance:l,symbolId:a.symbolId})}return s?.symbolId??null}function ad(e,t,n){let r=xd(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),s=e.prepare(`
|
|
110
110
|
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
111
111
|
VALUES (?, ?, ?, ?)
|
|
112
|
-
`),o=0,a=new Map;return e.transaction(()=>{for(let c of n){let u=
|
|
112
|
+
`),o=0,a=new Map;return e.transaction(()=>{for(let c of n){let u=ht(t,c),d=_d(r.name,r.version,u);s.run(d,"default",7,`Vue component|${u}`);let m=i.get(d);m&&(o++,a.set(c,m.id))}})(),{get(c){return a.get(c)??null},syntheticSymbols:o}}function ld(e,t,n,r,i){return e.transaction(()=>(Qu(e),cd(e,t,n,r),md(e,i)))()}function cd(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),s=e.prepare(`
|
|
113
113
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
114
114
|
VALUES (?, ?, ?, ?, X'00')
|
|
115
115
|
`),o=e.prepare(`
|
|
116
116
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
117
117
|
VALUES (?, ?, 1)
|
|
118
|
-
`);for(let a of n){let l=r.get(a);if(!l)continue;let c=
|
|
118
|
+
`);for(let a of n){let l=r.get(a);if(!l)continue;let c=ht(t,a),u=i.get(c);if(!u)continue;let d=s.run(u.id,-1,0,0);o.run(Number(d.lastInsertRowid),l)}}function ud(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let s=r.language.scripts.get(e.fileName),o=s?.generated?.languagePlugin.typescript?.getServiceScript(s.generated.root)?.code;if(s&&o){let a=r.language.maps.get(o,s);if(Wi(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function dd(e){let t=new Set,n=[];for(let r of e){let i=Hi(r);t.has(i)||(t.add(i),n.push(r))}return n}function Hi(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function md(e,t){let n=Sd(e,[...new Set(t.map(l=>l.sourceFile))]),r=e.prepare(`
|
|
119
119
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
120
120
|
VALUES (?, ?, ?, ?, X'00')
|
|
121
121
|
`),i=e.prepare(`
|
|
122
122
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
123
123
|
VALUES (?, ?, 0)
|
|
124
|
-
`),s=new Set,o=0,a=0;for(let l of t){let c=
|
|
125
|
-
Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!
|
|
126
|
-
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
124
|
+
`),s=new Set,o=0,a=0;for(let l of t){let c=Hi(l);if(s.has(c))continue;s.add(c);let u=n.get(l.sourceFile);if(!u)continue;let d=r.run(u,a++,l.sourceLine,l.sourceLine),m=i.run(Number(d.lastInsertRowid),l.symbolId);o+=Number(m.changes)}return o}function*pd(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function fd(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Wi(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Ui(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let s=Math.floor((n+r)/2);e.lineStarts[s]<=t?n=s+1:r=s-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function gd(e,t){return ht(e,t).startsWith("node_modules/")}function ht(e,t){return Du(e,t).replaceAll("\\","/")}function hd(e){switch(Eu(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function yd(){let e=new Map;return t=>{if(e.has(t))return e.get(t)??null;try{let n=gt(t,"utf-8"),r={text:n,lineStarts:bd(n)};return e.set(t,r),r}catch{return e.set(t,null),null}}}function bd(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Sd(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let s=t.slice(i,i+r),o=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${s.map(()=>"?").join(",")})`).all(...s);for(let a of o)n.set(a.relativePath,a.id)}return n}function xd(e){try{let t=JSON.parse(gt(et(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function _d(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}async function qi(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,s=wd(e),o=Date.now();Vi(We(s.outputScip),{recursive:!0}),Vi(We(s.outputDb),{recursive:!0});let a=e.languages??He(t);if(a.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${a.join(", ")}`);let l=Zd(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),c=zd(se(We(s.outputDb),"index.lock")),u=null;try{let d=kd({opts:e,paths:s,languages:a,fingerprint:l,start:o,onStatus:r});if(d)return d;Fd(i,r);let m=Pd(s);return u=m.runDir,await Od({opts:e,languages:a,projectRoot:t,paths:s,tempPaths:m,fingerprint:l,start:o,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}finally{u&&nt(u,{recursive:!0,force:!0}),c()}}function wd(e){let t=e.outputScip??se(e.projectRoot,"index.scip"),n=e.outputDb??se(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:se(We(n),"meta.json")}}function kd(e){if(e.opts.skipIfUnchanged===!1||!Ue(e.paths.outputScip)||!Ue(e.paths.outputDb)||!em(e.paths.metaPath,e.fingerprint))return null;we({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start;return e.onStatus(`Index unchanged; reused existing SQLite index in ${(t/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:t,reused:!0,skipped:[]}}function Pd(e){let t=vd(se(We(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:se(t,Xt(e.outputScip)),tempOutputDb:se(t,Xt(e.outputDb)),tempMetaPath:se(t,Xt(e.metaPath))}}async function Od(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r}=await Md(e,t);Td(e,t,n,r);let i=Date.now()-e.start;return e.onStatus(`Done in ${(i/1e3).toFixed(1)}s`),{languages:n.map(s=>s.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!1,skipped:r}}async function Md(e,t){let{preparedRuns:n,skippedLanguages:r}=Ad({languages:e.languages,tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),i=await Yd(n,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:s}=jd(i,r);return Bd(s,r,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:s,skippedLanguages:r}}function Td(e,t,n,r){Hd(n,e.tempPaths.tempOutputScip,e.onStatus),Wd(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),we({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),tm(e.tempPaths.tempMetaPath,{version:2,status:r.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,requestedLanguages:e.languages,indexedLanguages:n.map(i=>i.language),skipped:[...r]}),Gd({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath})}function Fd(e,t){if(!ft("scip")){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
125
|
+
Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!ai(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
126
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function Ad(e){let t=[],n=[],r=e.languages.map((i,s)=>({language:i,scipPath:e.languages.length>1?qd(e.tempOutputScip,i,s):e.tempOutputScip}));for(let{language:i,scipPath:s}of r){let o=$d({...e,language:i,scipPath:s});"skipped"in o?n.push(o.skipped):t.push(o.prepared)}return{preparedRuns:t,skippedLanguages:n}}function $d(e){let t=qt(e.language),n=Yt(t),r=Yn(t,e.projectRoot);if(!r&&!Di(t)){if(e.skipAutoInstall){let a=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Pi(t,e.onStatus)){let a=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}}let i=r??Ze(t);if(!i){let a=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}let{binary:s,args:o}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i});return{prepared:{language:e.language,scipPath:e.scipPath,config:t,resolvedBinary:i,binary:s,args:o,env:wi(t,e.env,i)}}}function jd(e,t){let n=[];for(let r of e)r.skipped?t.push(r.skipped):n.push({language:r.language,scipPath:r.scipPath});return{indexedOutputs:n}}function Bd(e,t,n,r,i){if(e.length===0){let s=t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
127
127
|
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
128
128
|
`+s)}if(t.length!==0&&(i(`Indexed ${e.length} of ${n.length} languages; skipped ${t.map(s=>s.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
|
|
129
129
|
`+t.map(s=>` - ${s.language}: ${s.reason}`).join(`
|
|
130
|
-
`))}function
|
|
131
|
-
`),()=>{try{
|
|
132
|
-
`)[0]}`;return n(`Skipping ${e.language}: ${o}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:o}}}finally{
|
|
133
|
-
`)}function
|
|
130
|
+
`))}function Hd(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),xi(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&tt(e[0].scipPath,t)}function Wd(e,t,n,r){if(r("Converting to SQLite..."),!Ue(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=vi(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`),Rd("scip",["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:i})}}function Ud(e,t,n){if(!e.defaultOutputPath)return;let r=se(t,e.defaultOutputPath);n!==r&&Ue(r)&&tt(r,n)}function Vd(e,t,n){if(!e.defaultOutputPath)return null;let r=se(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return nt(i,{force:!0}),Ue(r)?(tt(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Jd(e){e&&(nt(e.defaultOutputPath,{force:!0}),e.backupPath&&Ue(e.backupPath)&&tt(e.backupPath,e.defaultOutputPath))}function qd(e,t,n){let r=Ld(e)||".scip",i=Xt(e,r);return se(We(e),`${i}.${n+1}.${t}${r}`)}function zd(e){let t;try{t=Nd(e,"wx")}catch(n){throw(typeof n=="object"&&n&&"code"in n?n.code:void 0)==="EEXIST"?new Error(`Another scip-query reindex is already running for ${We(e)}.`,{cause:n}):n}return Ji(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
|
|
131
|
+
`),()=>{try{Cd(t)}finally{nt(e,{force:!0})}}}function Gd(e){tr(e.tempOutputScip,e.outputScip),tr(e.tempOutputDb,e.outputDb),tr(e.tempMetaPath,e.metaPath)}function tr(e,t){nt(`${t}.tmp-replace`,{force:!0}),tt(e,`${t}.tmp-replace`),tt(`${t}.tmp-replace`,t)}function Kd(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(2,Math.max(1,Dd().length-1));return Math.max(1,Math.min(e,Math.floor(r)))}async function Yd(e,t,n,r){let i=e.filter(c=>c.config.defaultOutputPath),s=e.filter(c=>!c.config.defaultOutputPath),o=[],a=Kd(s.length,r),l=await Xd(s,a,c=>nr(c,t,n));if(a>1){let c=new Map;for(let u of l.filter(d=>d.skipped)){let d=s.find(m=>m.language===u.language);d&&(n(`Retrying ${d.language} indexer serially after parallel failure...`),c.set(d.language,await nr(d,t,n)))}o.push(...l.map(u=>c.get(u.language)??u))}else o.push(...l);for(let c of i)o.push(await nr(c,t,n));return o.sort((c,u)=>e.findIndex(d=>d.language===c.language)-e.findIndex(d=>d.language===u.language))}async function nr(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),nt(e.scipPath,{force:!0});let r=Vd(e.config,t,e.scipPath);try{await Qd(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),Ud(e.config,t,e.scipPath)}catch(i){let s=i instanceof Error?i.message:String(i),o=`${e.resolvedBinary} indexer failed: ${s.split(`
|
|
132
|
+
`)[0]}`;return n(`Skipping ${e.language}: ${o}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:o}}}finally{Jd(r)}if(!Ue(e.scipPath)){let i=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`;return n(`Skipping ${e.language}: ${i}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:i}}}return{language:e.language,scipPath:e.scipPath}}function Qd(e,t,n){return new Promise((r,i)=>{Id(e,[...t],n,s=>{s?i(s):r()})})}async function Xd(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,s=Math.max(1,Math.min(e.length,t)),o=Array.from({length:s},async()=>{for(;i<e.length;){let a=i++;r[a]=await n(e[a])}});return await Promise.all(o),r}function Zd(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:zt(e)}}function em(e,t){try{let n=JSON.parse(Ed(e,"utf-8"));return n.version===2&&n.status==="complete"&&Qt(n.fingerprint)===Qt(t)&&Qt([...n.indexedLanguages??[]].sort())===Qt(t.languages)}catch{return!1}}function tm(e,t){Ji(e,`${JSON.stringify(t,null,2)}
|
|
133
|
+
`)}function Qt(e){return JSON.stringify(e)}import{createRequire as am}from"module";import{existsSync as yt,readFileSync as nm,readdirSync as rm,statSync as im}from"fs";import $ from"path";var ir=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function sr(e,t){let r=t?$.dirname($.join(e,t)):e,i=$.resolve(e);for(;r.startsWith(i);){for(let o of ir){let a=$.join(r,o);if(yt(a))return a}let s=$.dirname(r);if(s===r)break;r=s}for(let s of ir){let o=$.join(e,s);if(yt(o))return o}return null}function zi(e){let t=e.config.projectRoot,n=new Set(or(t,e.config.semantic?.typescript?.tsconfigs)),r=e.all(`SELECT relative_path
|
|
134
134
|
FROM documents
|
|
135
135
|
WHERE (
|
|
136
136
|
relative_path LIKE '%.ts'
|
|
@@ -142,7 +142,7 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
142
142
|
OR relative_path LIKE '%.mjs'
|
|
143
143
|
OR relative_path LIKE '%.cjs'
|
|
144
144
|
)
|
|
145
|
-
${e.pathExclusionsFor("documents")}`);for(let i of r){if(e.isIgnored(i.relative_path))continue;let s=
|
|
145
|
+
${e.pathExclusionsFor("documents")}`);for(let i of r){if(e.isIgnored(i.relative_path))continue;let s=sr(t,i.relative_path);s&&n.add($.resolve(s))}if(n.size===0){let i=sr(t);i&&n.add($.resolve(i))}return[...n].filter(i=>!Gi(t,i)).sort((i,s)=>i.localeCompare(s))}function or(e,t=[]){let n=new Set;for(let r of t){let i=$.isAbsolute(r)?r:$.join(e,r);yt(i)&&n.add($.resolve(i))}for(let r of sm(e))for(let i of ir){let s=$.join(r,i);yt(s)&&n.add($.resolve(s))}if(n.size===0){let r=sr(e);r&&n.add($.resolve(r))}return[...n].filter(r=>!Gi(e,r)).sort((r,i)=>r.localeCompare(i))}function sm(e){let t=$.join(e,"package.json");if(!yt(t))return[];let n;try{n=JSON.parse(nm(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>om(e,i))}function om(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let o=$.join(e,t);return rr(o)?[o]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),s=$.join(e,r||".");return rr(s)?rm(s).map(o=>$.join(s,o,i)).filter(rr):[]}function rr(e){try{return im(e).isDirectory()}catch{return!1}}function Gi(e,t){let n=$.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}var lm=am(import.meta.url);function ar(e,t=[]){let n=cm(),r=or(e,t),i=r[0];return n?r.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r}:{available:!1,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r,reason:"ts-morph is not installed"}}function cm(){try{return lm.resolve("ts-morph"),!0}catch{return!1}}import{watch as um}from"fs";import{existsSync as Ki,renameSync as Yi}from"fs";import{join as dm,relative as mm}from"path";import{fork as pm}from"child_process";import fm from"ignore";var Zt=class{projectRoot;watchConfig;indexPaths;languages;pnpmWorkspaces;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.watchConfig=ri(t.config),this.indexPaths=De(t.projectRoot,t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Xe(t.projectRoot),this.extraIgnore=fm(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=um(this.projectRoot,{recursive:!0},(n,r)=>{r&&!this.stopped&&this.handleFileChange(r)});this.fsWatchers.push(t)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.setStatus({state:"idle"})}handleFileChange(t){let n=mm(this.projectRoot,dm(this.projectRoot,t));if(this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(".scipquery.json"))return;if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let r=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let r=this.watchConfig.cooldownMs-t;this.dirty=!0;let i=Date.now()+r;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},r);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let i=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(r=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(r instanceof Error?r:new Error(String(r))),this.setStatus({state:"idle"})})}runReindex(){return new Promise((t,n)=>{let r=Date.now(),i=this.indexPaths.dbPath+".tmp",s=gm(this.indexPaths.indexPath),o=pm(new URL("./reindex-worker.js",import.meta.url).pathname,[],{env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s,SCIP_REINDEX_OUTPUT_DB:i,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});o.on("exit",a=>{if(a===0)try{Ki(i)&&Yi(i,this.indexPaths.dbPath),Ki(s)&&Yi(s,this.indexPaths.indexPath),t(Date.now()-r)}catch(l){n(new Error(`Atomic swap failed: ${l}`))}else n(new Error(`Reindex worker exited with code ${a}`))}),o.on("error",n)})}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}};function gm(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}import{existsSync as lr,mkdirSync as hm,symlinkSync as ym,readlinkSync as bm,unlinkSync as Sm}from"fs";import{join as en,dirname as Qi,resolve as cr}from"path";import{homedir as Xi,platform as xm}from"os";import{fileURLToPath as _m}from"url";var Im=xm()==="win32",ur=["concrete-plan","scip-explore","scip-debloat","scip-verify","scip-language-playbook"];function Zi(e={}){let t=e.quiet?()=>{}:console.log,n=_m(import.meta.url),r=cr(Qi(n),"..","skills"),i=[en(Xi(),".claude","skills"),en(Xi(),".codex","skills")],s={installed:[],skipped:[],alreadyLinked:[]};for(let o of i){let a=Qi(o);if(!lr(a))continue;hm(o,{recursive:!0});let l=o.includes(".codex")?"Codex":"Claude";for(let c of ur){let u=en(r,c),d=en(o,c);if(!lr(u)){s.skipped.push(`${l}/${c}`);continue}if(lr(d)){try{let m=bm(d);if(cr(m)===cr(u)){s.alreadyLinked.push(`${l}/${c}`),t(` ok: ${c} \u2192 ${l} (already linked)`);continue}}catch{s.skipped.push(`${l}/${c}`),t(` skip: ${c} \u2192 ${l} (exists, not a symlink)`);continue}Sm(d)}ym(u,d,Im?"junction":"dir"),s.installed.push(`${l}/${c}`),t(` done: ${c} \u2192 ${l}`)}}return s}function xe(e){return e+1}function pe(e,t){return`${xe(e)}-${xe(t)}`}function fe(e,t,n){return`${e}:${pe(t,n)}`}var b={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let s=n(i);s!==r&&(r&&console.log(""),console.log(s),r=s),console.log(t(i))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${n.title} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(n.explanation);for(let r of n.rows)console.log(r)}},table(e,t,n){console.log(` ${e.join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(i)}};import{existsSync as Fl}from"fs";import{join as Ex}from"path";import Rm from"better-sqlite3";var tn=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new Rm(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
|
|
146
146
|
EXISTS (
|
|
147
147
|
SELECT 1
|
|
148
148
|
FROM defn_enclosing_ranges local_der
|
|
@@ -160,11 +160,11 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
160
160
|
${this.pathExclusionsFor("local_d").trimStart()}
|
|
161
161
|
)
|
|
162
162
|
)`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>[`AND ${n}.relative_path NOT LIKE 'node_modules/%'`,`AND ${n}.relative_path NOT LIKE '.git/%'`]).join(`
|
|
163
|
-
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};var
|
|
163
|
+
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};var S={};Jl(S,{HEALTH_PHASES:()=>ll,affected:()=>qa,bottlenecks:()=>Ca,byKind:()=>Na,callGraph:()=>Pa,changeSurface:()=>za,code:()=>El,complexity:()=>Ll,complexityHotspots:()=>Fn,convergence:()=>Cl,coupling:()=>xa,cycles:()=>Nn,dataflow:()=>wl,dead:()=>vn,deepChains:()=>wa,deps:()=>ta,diffImpact:()=>Ka,diffImpactPartial:()=>Vr,diffImpactPlan:()=>Ur,drift:()=>kn,extractCandidates:()=>Ln,fanIn:()=>ha,fanOut:()=>ya,files:()=>es,health:()=>cl,healthPhase:()=>ul,healthReportFromPhases:()=>ml,hierarchy:()=>ka,hotspots:()=>aa,importedBy:()=>ua,imports:()=>ca,isolated:()=>En,kindCounts:()=>Ea,members:()=>ga,mergeDiffImpactPartials:()=>Jr,methods:()=>Xo,outline:()=>fa,passthroughCandidates:()=>Mn,rdeps:()=>na,redundantReexports:()=>Pl,refs:()=>Zo,similar:()=>Ta,similarAll:()=>Dn,similarChains:()=>Va,similarFiles:()=>Wa,similarSignatures:()=>Ml,slice:()=>kl,staleAbstractions:()=>Tn,stats:()=>nn,surface:()=>ia,symbols:()=>vs,system:()=>ra,topCoupling:()=>_a,topFanIn:()=>ba,topFanOut:()=>Sa,trace:()=>ea,unusedImports:()=>da,wrapperCandidates:()=>On});import{statSync as Cm}from"fs";function nn(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...vm(e.config.dbPath)}}function vm(e){try{let t=Cm(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function Nm(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function es(e,t){let n=Nm(t);return e.all(`SELECT relative_path FROM documents
|
|
164
164
|
WHERE relative_path LIKE ?
|
|
165
|
-
ORDER BY relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path}))}import{extname as
|
|
166
|
-
`);for(let s=n-1;s>=0&&s>=n-5;s-=1){let o=(i[s]??"").trim();if(o!==""){if(
|
|
167
|
-
`.repeat(r.startLine)+r.body;try{return
|
|
165
|
+
ORDER BY relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path}))}import{extname as as}from"path";import{createRequire as km}from"module";import{existsSync as Em,readFileSync as Dm}from"fs";import{join as Lm}from"path";var ts=A("source-text");function P(e,t){let n=t.replace(/\\/g,"/");return ts.get(e,n,()=>{let r=Lm(e.config.projectRoot,n);return Em(r)?Dm(r,"utf-8"):""})}function ns(e){ts.invalidateAll(e)}var wm=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale|wrapper|passthrough|drift|extract)?/i;function dr(e,t,n){if(n<=0)return!1;let r=P(e,t);if(!r)return!1;let i=r.split(`
|
|
166
|
+
`);for(let s=n-1;s>=0&&s>=n-5;s-=1){let o=(i[s]??"").trim();if(o!==""){if(wm.test(o))return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}var q=km(import.meta.url),rn=null,rs=!1;function ls(){if(rs)return null;if(rn)return rn;try{return rn=q("tree-sitter"),rn}catch{return rs=!0,null}}var Pm={".rs":"rust",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".java":"java",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".rb":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".cs":"csharp",".php":"php",".vb":"vb"},is=new Map,mr=new Set;function cs(e){if(mr.has(e))return null;let t=is.get(e);if(t)return t;let n;try{switch(e){case"rust":n=q("tree-sitter-rust");break;case"typescript":n=q("tree-sitter-typescript").typescript;break;case"tsx":n=q("tree-sitter-typescript").tsx;break;case"javascript":n=q("tree-sitter-javascript");break;case"python":n=q("tree-sitter-python");break;case"java":n=q("tree-sitter-java");break;case"kotlin":n=q("tree-sitter-kotlin");break;case"scala":n=q("tree-sitter-scala");break;case"ruby":n=q("tree-sitter-ruby");break;case"c":n=q("tree-sitter-c");break;case"cpp":n=q("tree-sitter-cpp");break;case"csharp":n=q("tree-sitter-c-sharp");break;case"php":n=q("tree-sitter-php").php;break;case"vb":{let r=q("tree-sitter-vb-dotnet");n=r.language??r;break}}}catch{return mr.add(e),null}return is.set(e,n),n}var ss=new Map;function us(e){let t=ss.get(e);if(t)return t;let n=cs(e);if(!n)return null;let r=ls();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return mr.add(e),null}return ss.set(e,i),i}function T(e){return Pm[as(e).toLowerCase()]??null}function St(e){return as(e).toLowerCase()===".vue"}var pr=Vt("ast-trees");function ds(e){pr.invalidateAll(e)}function O(e,t){if(St(t))return Om(e,t);let n=T(t);if(!n)return null;let r=P(e,t);return r?pr.get(e,t,r,()=>{let i=us(n);if(!i)return null;try{return ms(i,r)}catch{return null}}):null}function Om(e,t){let n=P(e,t);return n?pr.get(e,t,n,()=>{let r=Mm(n);if(!r)return null;let i=us(r.language);if(!i)return null;let s=`
|
|
167
|
+
`.repeat(r.startLine)+r.body;try{return ms(i,s)}catch{return null}}):null}function ms(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function Mm(e){let t=[],n=/<script\b([^>]*)>([\s\S]*?)<\/script>/g;for(let l of e.matchAll(n))typeof l.index=="number"&&t.push({tagOpen:l[1]??"",body:l[2]??"",openIdx:l.index+(l[0].length-(l[2]?.length??0)-9)});if(t.length===0)return null;let r=t.find(l=>/\bsetup\b/.test(l.tagOpen))??t[0],s=r.tagOpen.match(/\blang\s*=\s*["']?([\w-]+)/)?.[1]?.toLowerCase(),o=s==="ts"||s==="typescript"?"typescript":s==="tsx"?"tsx":"javascript",a=Tm(e,r.openIdx);return{body:r.body,startLine:a,language:o}}function Tm(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}var rt=new Map;function Fm(e,t){let n=`${e}::${t}`;if(rt.has(n))return rt.get(n)??null;let r=cs(e);if(!r)return rt.set(n,null),null;let i=ls();if(!i)return rt.set(n,null),null;try{let s=new i.Query(r,t);return rt.set(n,s),s}catch{return rt.set(n,null),null}}var Am={rust:`
|
|
168
168
|
(function_item name: (identifier) @name) @def
|
|
169
169
|
(function_signature_item name: (identifier) @name) @def
|
|
170
170
|
`,typescript:`
|
|
@@ -190,7 +190,7 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
190
190
|
(variable_declarator name: (identifier) @name value: (function_expression)) @def
|
|
191
191
|
`,python:`
|
|
192
192
|
(function_definition name: (identifier) @name) @def
|
|
193
|
-
`}
|
|
193
|
+
`},$m=new WeakMap;function ps(e,t){return gs(e,t,$m,Am,n=>{let r=[];for(let i of n){let s=null,o=null;for(let a of i.captures)a.name==="name"?s=a.node.text:a.name==="def"&&(o={startLine:a.node.startPosition.row,endLine:a.node.endPosition.row});s&&o&&r.push({name:s,startLine:o.startLine,endLine:o.endLine})}return r})}var jm={rust:`
|
|
194
194
|
(call_expression function: (_) @target) @call
|
|
195
195
|
(macro_invocation macro: (_) @target) @call
|
|
196
196
|
`,typescript:`
|
|
@@ -204,7 +204,7 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
204
204
|
(new_expression constructor: (_) @target) @call
|
|
205
205
|
`,python:`
|
|
206
206
|
(call function: (_) @target) @call
|
|
207
|
-
`},
|
|
207
|
+
`},Bm=new WeakMap;function sn(e,t){return gs(e,t,Bm,jm,n=>{let r=[];for(let i of n){let s=null,o=null;for(let l of i.captures)l.name==="target"?s=l.node:l.name==="call"&&(o=l.node);if(!s||!o)continue;let a=bt(s);a&&r.push({calleeLeaf:a,memberAccess:Hm(s),line:o.startPosition.row})}return r})}function Hm(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function fs(e,t){return on(e,t,Wm,()=>new Map,(n,r,i)=>{let s=(l,c)=>{if(l===c)return;let u=i.get(l);u||(u=new Set,i.set(l,u)),u.add(c)},o=r==="python"?new Set(["identifier"]):new Set(["type_identifier"]),a=(l,c)=>{let u=d=>{o.has(d.type)&&d.text!==c&&s(d.text,c);for(let m of d.children)u(m)};for(let d of l.children)u(d)};if(r==="rust")for(let l of n.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let c=l.namedChildren.find(d=>d.type==="type_identifier")?.text;if(!c)continue;let u=l.namedChildren.find(d=>d.type==="field_declaration_list"||d.type==="enum_variant_list"||d.type==="ordered_field_declaration_list");u&&a(u,c),l.type==="type_item"&&a(l,c)}else if(r==="python")for(let l of n.rootNode.descendantsOfType("class_definition")){let c=l.namedChildren.find(d=>d.type==="identifier")?.text;if(!c)continue;let u=l.namedChildren.find(d=>d.type==="block");if(u)for(let d of u.descendantsOfType("type"))for(let m of d.descendantsOfType("identifier"))m.text!==c&&s(m.text,c)}else for(let l of n.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let c=l.namedChildren.find(u=>u.type==="type_identifier")?.text;c&&a(l,c)}})??new Map}function on(e,t,n,r,i){let s=T(t);if(!s)return null;let o=O(e,t);if(!o)return null;let a=n.get(o);if(a)return a;let l=r();return i(o,s,l),n.set(o,l),l}function gs(e,t,n,r,i){let s=T(t);if(!s)return null;let o=r[s];if(!o)return null;let a=O(e,t);if(!a)return null;let l=n.get(a);if(l)return l;let c=Fm(s,o);if(!c)return null;let u=i(c.matches(a.rootNode));return n.set(a,u),u}var Wm=new WeakMap,os=new WeakMap;function hs(e,t,n,r){let i=T(t);if(!i)return null;let s=O(e,t);if(!s)return null;let o=os.get(s);return o||(o=Um(s,i),os.set(s,o)),o.get(`${n}:${r}`)??null}function Um(e,t){let n=t==="rust"?new Set(["function_item","function_signature_item"]):t==="python"?new Set(["function_definition"]):new Set(["function_declaration","method_definition","arrow_function","function_expression"]),r=new Map,i=s=>{if(n.has(s.type)){let o=s.namedChildren.find(l=>l.type==="parameters"||l.type==="formal_parameters"),a=0;if(o)for(let l of o.namedChildren)l.type==="comment"||l.type==="line_comment"||l.type==="block_comment"||(a+=1);r.set(`${s.startPosition.row}:${s.endPosition.row}`,{paramCount:a})}for(let o of s.children)i(o)};return i(e.rootNode),r}function bt(e){switch(e.type){case"identifier":case"type_identifier":case"property_identifier":case"shorthand_property_identifier":return e.text;case"field_expression":case"member_expression":case"attribute":{let t=e.namedChild(e.namedChildCount-1);return t?bt(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?bt(t):null}case"super":case"self":case"this":return null;default:return null}}var Vm={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function W(e){if(e.startsWith("local "))return{kind:"local",id:e.slice(6),raw:e};let t=e.split(" ");if(t.length<4)return{scheme:t[0]??"",manager:t[1]??"",packageName:t[2]??"",version:"",descriptors:[],raw:e};let n=t[0],r=t[1],i=e.slice(n.length+1+r.length+1),s;if(i.startsWith("`")){let c=i.indexOf("`",1);c===-1?(s=i.slice(1),i=""):(s=i.slice(1,c),i=i.slice(c+2))}else{let c=i.indexOf(" ");c===-1?(s=i,i=""):(s=i.slice(0,c),i=i.slice(c+1))}let o,a=i.indexOf(" ");a===-1?(o=i,i=""):(o=i.slice(0,a),i=i.slice(a+1));let l=Jm(i);return{scheme:n,manager:r,packageName:s,version:o,descriptors:l,raw:e}}function Jm(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="["){let s=e.indexOf("]",n+1);if(s===-1){t.push({name:e.slice(n+1),suffix:"type-param"});break}t.push({name:e.slice(n+1,s),suffix:"type-param"}),n=s+1;continue}if(e[n]==="("&&(t.length===0||n===0||ys(e[n-1]))){let s=e.indexOf(")",n+1);if(s!==-1&&e[s+1]!=="."){t.push({name:e.slice(n+1,s),suffix:"parameter"}),n=s+1;continue}}let r;if(e[n]==="`"){let s=e.indexOf("`",n+1);if(s===-1){r=e.slice(n+1),t.push({name:r,suffix:"term"});break}r=e.slice(n+1,s),n=s+1}else{let s=n;for(;n<e.length&&!ys(e[n]);)n++;r=e.slice(s,n)}if(n>=e.length){r&&t.push({name:r,suffix:"term"});break}let i=e[n];if(i==="("){let s=e.indexOf(")",n+1);s!==-1&&e[s+1]==="."?(t.push({name:r,suffix:"method"}),n=s+2):s!==-1?(t.push({name:r,suffix:"method"}),n=s+1):(t.push({name:r,suffix:"term"}),n++)}else{let s=Vm[i];s&&t.push({name:r,suffix:s}),n+=1}}return t}function ys(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function g(e){let t=W(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let r=[];for(let i of n.descriptors){let s=qm(i);s&&r.push(s)}return r.join(":")}function qm(e){let t=e.suffix==="namespace"?zm(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function zm(e){return e.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"").replace(/\.(py|pyi)$/,"").replace(/\.(rs)$/,"").replace(/\.(java|scala|kt|kts)$/,"").replace(/\.(rb)$/,"").replace(/\.(go)$/,"").replace(/\.(cs|vb)$/,"").replace(/\.(dart)$/,"").replace(/\.(php)$/,"").replace(/\.(c|cc|cpp|cxx|h|hpp)$/,"")}function w(e){let t=W(e);if("kind"in t&&t.kind==="local")return t.id;let n=t;return n.descriptors.length===0?"":n.descriptors[n.descriptors.length-1].name}function U(e){let t=W(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function V(e){return e.endsWith("().")||U(e)==="method"}function H(e){let t=U(e);return t==="method"||t==="term"}function ke(e){return U(e)==="namespace"}var Gm=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function an(e){return Gm.test(e)}var Km=new Set(["test","tests","_tests"]);function Pe(e){let t=W(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let r=t.descriptors[n];if(r?.suffix==="namespace"&&r.name&&Km.has(r.name))return!0}return!1}function bs(e,t){let n=W(e),r=W(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,s=r.descriptors;if(s.length!==i.length+1)return!1;for(let o=0;o<i.length;o++){let a=i[o],l=s[o];if(a.name!==l.name||a.suffix!==l.suffix)return!1}return!0}function Ss(e,t){let n=W(e),r=W(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,s=r.descriptors;if(s.length<=i.length)return!1;for(let o=0;o<i.length;o++){let a=i[o],l=s[o];if(a.name!==l.name||a.suffix!==l.suffix)return!1}return!0}function Ve(e){return!e||!e.trim()?null:e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim()||null}function Je(e){if(!e)return null;let t=xs(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let r=e.slice(n+1);return(xs(r)??r).replace(/\n/g," ")}function xs(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}var Ym=A("file-definitions");function z(e,t){return Ym.get(e,t,()=>{let n=ep(Qm(e,t),Xm(e,t));return np(e,t,n.map(Zm))})}function Qm(e,t){return e.all(`SELECT
|
|
208
208
|
gs.id,
|
|
209
209
|
gs.symbol,
|
|
210
210
|
der.document_id,
|
|
@@ -220,7 +220,7 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
220
220
|
JOIN documents d ON der.document_id = d.id
|
|
221
221
|
WHERE d.relative_path = ?
|
|
222
222
|
${e.symbolNoiseFor("gs")}
|
|
223
|
-
ORDER BY der.start_line, der.end_line`,t)}function
|
|
223
|
+
ORDER BY der.start_line, der.end_line`,t)}function Xm(e,t){return e.all(`SELECT
|
|
224
224
|
gs.id,
|
|
225
225
|
gs.symbol,
|
|
226
226
|
c.document_id,
|
|
@@ -239,18 +239,18 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
239
239
|
AND m.role = 1
|
|
240
240
|
${e.symbolNoiseFor("gs")}
|
|
241
241
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
242
|
-
ORDER BY start_line, end_line`,t)}function
|
|
242
|
+
ORDER BY start_line, end_line`,t)}function Zm(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,endLine:e.end_line,relativePath:e.relative_path,leaf:w(e.symbol),parentTypeName:ze(e.symbol),isFunctionLike:H(e.symbol),isTypeLike:U(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function ep(e,t){let n=new Map;for(let r of t)e.length>0&&!tp(r)||n.set(r.id,r);for(let r of e)n.set(r.id,r);return[...n.values()].sort((r,i)=>r.start_line-i.start_line||r.end_line-i.end_line||r.symbol.localeCompare(i.symbol))}function tp(e){if(ze(e.symbol)!==null)return!1;let n=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(n)}function oe(e,t={}){return fr(e,t.scope)}function fr(e,t){let n=t?`AND relative_path LIKE '%${t}%'`:"";return e.all(`SELECT relative_path
|
|
243
243
|
FROM documents
|
|
244
244
|
WHERE 1 = 1
|
|
245
245
|
${e.pathExclusionsFor("documents")}
|
|
246
246
|
${n}
|
|
247
|
-
ORDER BY relative_path`).flatMap(r=>
|
|
247
|
+
ORDER BY relative_path`).flatMap(r=>z(e,r.relative_path)).filter(r=>!e.isIgnored(r.relativePath))}function it(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>z(e,i)).filter(i=>!e.isIgnored(i.relativePath));return n.onlyDocumented&&(r=r.filter(i=>i.documentation!==null&&i.documentation!=="")),n.sort&&(r=r.sort((i,s)=>i.relativePath.localeCompare(s.relativePath)||i.startLine-s.startLine||i.endLine-s.endLine)),r.map(i=>({startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,shortName:g(i.symbol),signature:Ve(Je(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function ae(e,t){let n=null;for(let r of e)r.startLine>t||r.endLine<t||(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r);return n}function qe(e,t){let n=z(e,t.relative_path).find(r=>r.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,endLine:n.endLine,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,endLine:t.end_line,relativePath:t.relative_path}}function np(e,t,n){let r=P(e,t),i=ps(e,t);return i?lp(n,i,r):r?rp(n,r):n}function rp(e,t){let n=t.split(/\r?\n/),r=ip(e,n),i=sp(e,r),s=op(i,n);return ap(e,s)}function ip(e,t){let n=e.some(i=>ln(i.symbol))?up(t):null,r=new Map;for(let i of e)r.set(i.symbolId,cp(t,n,i));return r}function sp(e,t){return e.filter(n=>ln(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,r)=>n.startLine-r.startLine||n.definition.startLine-r.definition.startLine||n.definition.symbol.localeCompare(r.definition.symbol))}function op(e,t){let n=new Map;for(let r=0;r<e.length;r+=1){let i=e[r],s=e[r+1],o=s?Math.max(i.startLine,s.startLine-1):t.length-1;n.set(i.definition.symbolId,{startLine:i.startLine,endLine:dp(t,i.definition,i.startLine,o)})}return n}function ap(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function lp(e,t,n=null){let r=new Map;for(let i of t){let s=r.get(i.name);s?s.push(i):r.set(i.name,[i])}return e.map(i=>{if(!ln(i.symbol)||!i.leaf)return _s(i,n);let s=r.get(i.leaf);if(!s||s.length===0)return _s(i,n);let o=s[0],a=Math.abs(o.startLine-i.startLine);for(let l=1;l<s.length;l+=1){let c=s[l],u=Math.abs(c.startLine-i.startLine);u<a&&(o=c,a=u)}return{...i,startLine:o.startLine,endLine:o.endLine}})}function _s(e,t){if(!t||!e.leaf||U(e.symbol)!=="term"||ze(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),s=t.split(/\r?\n/).findIndex(o=>r.test(o));return s>=0?{...e,startLine:s,endLine:s}:e}function cp(e,t,n){if(!ln(n.symbol))return n.startLine;let r=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return r;let i=t.get(n.leaf);if(!i||i.length===0)return r;let s=null;for(let o of i){let a=Math.abs(o-n.startLine);(!s||a<s.distance)&&(s={line:o,distance:a})}return s?.line??r}function up(e){let t=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,n=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,r=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\b([A-Za-z_$][\w$]*)\s*\(/g,s=new Map,o=(a,l)=>{let c=s.get(a);if(!c){s.set(a,[l]);return}c[c.length-1]!==l&&c.push(l)};for(let a=0;a<e.length;a+=1){let l=e[a]??"";for(let u of l.matchAll(t))u[1]&&o(u[1],a);for(let u of l.matchAll(n))u[1]&&o(u[1],a);let c=l.match(r);c?.[1]&&o(c[1],a);for(let u of l.matchAll(i))u[1]&&o(u[1],a)}return s}function dp(e,t,n,r){let i=Math.max(n,Math.min(e.length-1,r)),s=Math.max(n,Math.min(i,t.endLine)),o=0,a=0,l=!1;for(let c=n;c<=i;c+=1){let u=mp(e[c]??"");for(let d of u)d==="{"?(o+=1,l=!0):d==="}"?o=Math.max(0,o-1):d==="("?a+=1:d===")"&&(a=Math.max(0,a-1));if(l&&o===0||!l&&a===0&&c>=s)return c}return s}function mp(e){let t="",n=null,r=!1;for(let i=0;i<e.length;i+=1){let s=e[i],o=e[i+1];if(!n&&s==="/"&&o==="/"){t+=" ".repeat(e.length-i);break}if(n){if(r){r=!1,t+=" ";continue}if(s==="\\"){r=!0,t+=" ";continue}s===n&&(n=null),t+=" ";continue}if(s==='"'||s==="'"||s==="`"){n=s,t+=" ";continue}t+=s}return t}function ln(e){return e.includes("().")}function ze(e){let t=W(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let r=t.descriptors[n];if(r?.suffix==="type")return r.name}return null}function gr(e){let t=W(e);if("kind"in t)return[];let n=[];for(let r=t.descriptors.length-2;r>=0;r-=1){let i=t.descriptors[r];i?.suffix==="type"&&i.name&&n.push(i.name)}return n}import{existsSync as Ep}from"fs";import{basename as Is,isAbsolute as Dp,join as Lp}from"path";function L(e,t){let n=ot(e,t.trim());if(n)return n;let r=bp(e,t);if(r)return r;let i=pp(e,t);return i||yp(e,t)}function pp(e,t){let n=br(t),r=yr(n);if(!r)return null;let i=`%${r.path}%`,s=r.leaf,a=fp(e,i,s,n)[0];return a?qe(e,a):null}function fp(e,t,n,r){let i=hr([],[...gp(e,t,n),...hp(e,t,n)]).filter(s=>!e.isIgnored(s.relative_path)).filter(s=>st(s,r)>1);return i.sort((s,o)=>st(o,r)-st(s,r)||s.end_line-s.start_line-(o.end_line-o.start_line)||s.start_line-o.start_line||s.symbol.localeCompare(o.symbol)),i}function gp(e,t,n){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
|
|
248
248
|
FROM global_symbols gs
|
|
249
249
|
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
250
250
|
JOIN documents d ON der.document_id = d.id
|
|
251
251
|
WHERE d.relative_path LIKE ?
|
|
252
252
|
AND (gs.display_name = ? OR gs.symbol LIKE ?)
|
|
253
|
-
${e.pathExclusionsFor("d")}`,t,n,`%/${n}.%`)}function
|
|
253
|
+
${e.pathExclusionsFor("d")}`,t,n,`%/${n}.%`)}function hp(e,t,n){return e.all(`SELECT
|
|
254
254
|
gs.id,
|
|
255
255
|
gs.symbol,
|
|
256
256
|
c.document_id,
|
|
@@ -267,7 +267,7 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
267
267
|
AND d.relative_path LIKE ?
|
|
268
268
|
AND (gs.display_name = ? OR gs.symbol LIKE ?)
|
|
269
269
|
${e.pathExclusionsFor("d")}
|
|
270
|
-
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation`,t,n,`%/${n}.%`)}function
|
|
270
|
+
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation`,t,n,`%/${n}.%`)}function yp(e,t){let n=br(t),r=vp(t),i=Ip(e,r),s=Np(i,t,n);if(s&&!e.isIgnored(s.relative_path))return qe(e,s);let o=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let l=Cp(a,t,n,r);l<=0||(!o||l>o.score)&&(o={row:a,score:l})}return o?qe(e,o.row):null}function bp(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,r,i,s]=n,o=Math.max(0,parseInt(i,10)-1),a=Math.max(o,parseInt(s,10)-1),l=Sp(e,r,o,a)??xp(e,r,o,a);return l&&!e.isIgnored(l.relative_path)?qe(e,l):null}function Sp(e,t,n,r){return e.get(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path
|
|
271
271
|
FROM global_symbols gs
|
|
272
272
|
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
273
273
|
JOIN documents d ON der.document_id = d.id
|
|
@@ -275,7 +275,7 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
275
275
|
AND der.start_line <= ? AND der.end_line >= ?
|
|
276
276
|
${e.pathExclusionsFor("d")}
|
|
277
277
|
ORDER BY (der.end_line - der.start_line) ASC
|
|
278
|
-
LIMIT 1`,`%${t}%`,n,r)}function
|
|
278
|
+
LIMIT 1`,`%${t}%`,n,r)}function xp(e,t,n,r){return e.get(`SELECT gs.id, gs.symbol, c.document_id, MIN(c.start_line) AS start_line, MAX(c.end_line) AS end_line, d.relative_path
|
|
279
279
|
FROM global_symbols gs
|
|
280
280
|
JOIN mentions m ON m.symbol_id = gs.id
|
|
281
281
|
JOIN chunks c ON m.chunk_id = c.id
|
|
@@ -286,7 +286,7 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
286
286
|
${e.pathExclusionsFor("d")}
|
|
287
287
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
288
288
|
ORDER BY (MAX(c.end_line) - MIN(c.start_line)) ASC
|
|
289
|
-
LIMIT 1`,`%${t}%`,n,r)}function
|
|
289
|
+
LIMIT 1`,`%${t}%`,n,r)}function ot(e,t){let r=e.get(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path
|
|
290
290
|
FROM global_symbols gs
|
|
291
291
|
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
292
292
|
JOIN documents d ON der.document_id = d.id
|
|
@@ -309,7 +309,7 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
309
309
|
${e.pathExclusionsFor("d")}
|
|
310
310
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
311
311
|
ORDER BY d.relative_path, start_line
|
|
312
|
-
LIMIT 1`,t);return!r||e.isIgnored(r.relative_path)?null:
|
|
312
|
+
LIMIT 1`,t);return!r||e.isIgnored(r.relative_path)?null:qe(e,r)}function cn(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=_p(e,t.symbolId)[0];return n?qe(e,n):null}function _p(e,t){let n=e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
|
|
313
313
|
FROM global_symbols gs
|
|
314
314
|
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
315
315
|
JOIN documents d ON der.document_id = d.id
|
|
@@ -331,7 +331,7 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
331
331
|
AND m.role = 1
|
|
332
332
|
${e.pathExclusionsFor("d")}
|
|
333
333
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
|
|
334
|
-
ORDER BY start_line, end_line`,t);return
|
|
334
|
+
ORDER BY start_line, end_line`,t);return hr(n,r)}function Ip(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),r=t.flatMap(o=>{let a=`%${o}%`;return[a,a,a]}),i=e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
|
|
335
335
|
FROM global_symbols gs
|
|
336
336
|
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
337
337
|
JOIN documents d ON der.document_id = d.id
|
|
@@ -356,17 +356,17 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
|
356
356
|
AND `)}
|
|
357
357
|
${e.pathExclusionsFor("d")}
|
|
358
358
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
|
|
359
|
-
LIMIT 200`,...r);return
|
|
359
|
+
LIMIT 200`,...r);return hr(i,s)}function hr(e,t){let n=new Map;for(let r of t)e.length>0&&!Rp(r)||n.set(r.id,r);for(let r of e)n.set(r.id,r);return[...n.values()]}function Rp(e){if(ze(e.symbol)!==null)return!1;let n=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(n)}function Cp(e,t,n,r){let i=t.trim(),s=n,o=s.replace(/\(\)$/,""),a=t.toLowerCase(),l=n.toLowerCase(),c=l.replace(/\(\)$/,""),u=e.symbol,d=g(e.symbol),m=w(e.symbol),f=e.display_name??"",h=e.symbol.toLowerCase(),p=d.toLowerCase(),y=m.toLowerCase(),_=f.toLowerCase(),E=e.relative_path.toLowerCase(),F=/[/:.]/.test(n),M=yr(n),C=M?.leaf.toLowerCase(),I=0;return(u===i||u===s)&&(I+=1150),(d===i||d===s)&&(I+=1100),f===o&&(I+=1180),m===o&&(I+=1160),(`${m}()`===i||`${m}()`===s)&&(I+=955),(h===a||h===l)&&(I+=1e3),(p===a||p===l)&&(I+=950),(E===a||E===l)&&(I+=925),(E.endsWith(`/${l}`)||E.endsWith(`/${a}`))&&(I+=875),_===c&&(I+=850),y===c&&(I+=825),(`${y}()`===a||`${y}()`===l)&&(I+=820),(p.endsWith(`:${l}`)||p.endsWith(`:${c}`)||p.endsWith(`:${c}()`))&&(I+=800),h.includes(l)&&(I+=120),p.includes(l)&&(I+=140),E.includes(l)&&(I+=140),_.includes(l)&&(I+=110),r.every(k=>{let D=k.toLowerCase();return h.includes(D)||p.includes(D)||E.includes(D)||_.includes(D)})&&(I+=100+r.length*15),M&&E.includes(M.path.toLowerCase())&&(I+=360,C&&(y===C||`${y}()`===C||`${y}()`==`${C}()`)&&(I+=700),V(e.symbol)&&(I+=180)),H(e.symbol)&&y===c&&(I+=60),!F&&ke(e.symbol)&&(I-=160),I-=Math.min(50,Math.max(0,e.end_line-e.start_line)),I}function yr(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let r=t.slice(n+1).replace(/\(\)$/,"");return!r||r.includes(".")?null:{path:t.slice(0,n),leaf:r}}function br(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function vp(e){let t=br(e),n=t.split(/[^A-Za-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>0);return n.length>0?[...new Set(n)]:[t]}function Np(e,t,n){let r=t.trim(),i=e.filter(s=>{let o=g(s.symbol),a=(s.display_name??"").trim();return s.symbol===r||o===r||o===n||a===r||a===n||`${a}()`===r||st(s,n)>1||s.relative_path===r});return i.length===0?null:(i.sort((s,o)=>st(o,n)-st(s,n)||s.end_line-s.start_line-(o.end_line-o.start_line)||s.relative_path.localeCompare(o.relative_path)||s.symbol.localeCompare(o.symbol)),i[0]??null)}function st(e,t){let n=yr(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=w(e.symbol).toLowerCase(),s=n.path.toLowerCase(),o=n.leaf.toLowerCase();return r.includes(s)?i!==o?1:V(e.symbol)?ze(e.symbol)===null?5:4:ze(e.symbol)===null?3:2:0}function K(e,t){let n=Rs(e,t,{allowMultiple:!1})[0]?.relativePath;return n||wp(e,t)}function Oe(e,t){return Rs(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function wp(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=Dp(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=Lp(e.config.projectRoot,r);return Ep(i)?r:null}function Rs(e,t,n){let r=Cs(t);if(!r)return[];let s=e.all(`SELECT relative_path
|
|
360
360
|
FROM documents
|
|
361
361
|
WHERE 1 = 1
|
|
362
362
|
${e.pathExclusionsFor("documents")}
|
|
363
|
-
ORDER BY relative_path`).filter(l=>!e.isIgnored(l.relative_path)).map(l=>({relativePath:l.relative_path,score:Tm(l.relative_path,r)})).filter(l=>l.score>0).sort((l,c)=>c.score-l.score||l.relativePath.localeCompare(c.relativePath));if(s.length===0){let l=E(e,t);return!l||e.isIgnored(l.relativePath)?[]:[{relativePath:l.relativePath,score:700}]}let o=s.filter(l=>l.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let a=s.filter(l=>l.score>=800);return a.length>0?n.allowMultiple?a:[a[0]]:n.allowMultiple?s:[s[0]]}function Tm(e,t){let n=os(e),r=is(n),i=is(t),s=0;return n===t&&(s+=1200),n.endsWith(`/${t}`)&&(s+=1100),r===i&&(s+=900),n.startsWith(`${t}/`)&&(s+=850),n.includes(t)&&(s+=250),s}function os(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}function as(e,t){let n=we(e,t);return nt(e,n).map(({relativePath:r,...i})=>i)}import{basename as eh}from"path";var bt=new WeakMap;function us(e,t){let n=M(t);return n==="rust"?Wm(e,t):n==="typescript"||n==="tsx"||n==="javascript"?Am(e,t):[]}var $m=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function Am(e,t){let n=P(e,t);if(!n)return[];let r=bt.get(n);if(r)return r;let i=/(^|\/)(pages|app)\/.+\.(tsx?|jsx?)$/.test(t)||/(^|\/)(layout|page|loading|error|not-found|head|template|default)\.(tsx?|jsx?)$/.test(t),s=/(^|\/)src\/(pages|views|routes)\/.+\.(tsx?|jsx?|vue)$/.test(t),o=!1,a=n.rootNode;for(let c of a.namedChildren){if(c.type!=="expression_statement")continue;let u=c.namedChild(0);if(!u||u.type!=="call_expression")continue;let d=u.namedChild(0);if(!d)continue;let m=d.type==="member_expression"?d.namedChild(d.namedChildCount-1)?.text:d.text;if(m&&$m.has(m)){o=!0;break}}let l=[];o&&l.push({startLine:0,endLine:a.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"}),(i||s)&&l.push({startLine:0,endLine:a.endPosition.row,reason:i?"Next.js / Remix route file":"Vite/Vue route component"});for(let c of a.namedChildren){let u=null,d=null;if(c.type==="function_declaration")u=c.namedChild(0)?.text??null,d=c;else if(c.type==="export_statement"){let m=c.namedChild(0);m?.type==="function_declaration"&&(u=m.namedChild(0)?.text??null,d=m)}else if(c.type==="lexical_declaration"){let m=c.namedChild(0);if(m?.type==="variable_declarator"){let g=m.namedChild(0)?.text,p=m.namedChild(1);g&&(p?.type==="arrow_function"||p?.type==="function_expression")&&(u=g,d=m)}}u&&/^use[A-Z]/.test(u)&&d&&l.push({startLine:d.startPosition.row,endLine:d.endPosition.row,reason:"React custom hook (use*)"})}return l.push(...ds(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),bt.set(n,l),l}var jm=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function Bm(e){return jm.test(e)}function ds(e,t,n){let r=[],i=s=>{if(t.has(s.type)&&s.parent){let a=s.parent.children,l=-1;for(let c=0;c<a.length;c+=1)if(a[c].startIndex===s.startIndex&&a[c].type===s.type){l=c;break}if(l>0)for(let c=l-1;c>=0;c-=1){let u=a[c];if(n.has(u.type)){if(Bm(u.text)){r.push({startLine:s.startPosition.row,endLine:s.endPosition.row,reason:"scip-query suppression comment"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let o of s.namedChildren)i(o)};return i(e.rootNode),r}function Wm(e,t){let n=P(e,t);if(!n)return[];let r=bt.get(n);if(r)return r;let i=[],s=Hm(n);return s?(bt.set(n,s),s):(ms(n.rootNode,i,!1,!1),i.push(...ds(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),i.push(...Gm(n.rootNode)),bt.set(n,i),i)}function Hm(e){return Km(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function ms(e,t,n,r){let i=n,s=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(s=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)"})),e.type==="function_item"||e.type==="function_signature_item"?Vm(e,t,n,r):r&&zm(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?Um(e,t,n):e.type==="mod_item"&&pr(e).some(o=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(o))&&(i=!0);for(let o of e.namedChildren)ms(o,t,i,s)}function Vm(e,t,n,r){let i=pr(e),s=null;r?s="trait impl method (dynamic dispatch)":n&&(s="inside #[cfg(test)] mod");for(let o of i){let a=Jm(o);if(a){s=a;break}if(ps(o)){s="#[allow(dead_code)]";break}}s&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:s})}function Um(e,t,n){let r=pr(e),i=e.namedChildren.find(s=>s.type==="type_identifier")?.text;r.some(qm)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(ps)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:i})}function pr(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let s=0;s<n.length;s+=1)if(n[s].startIndex===e.startIndex&&n[s].type===e.type){r=s;break}if(r<=0)return[];let i=[];for(let s=r-1;s>=0;s-=1){let o=n[s];if(o.type==="attribute_item"||o.type==="inner_attribute_item")i.push(o.text);else{if(o.type==="line_comment"||o.type==="block_comment")continue;break}}return i}function Jm(e){return/#\[\s*tauri::command\b/.test(e)?"#[tauri::command]":/#\[\s*command\b/.test(e)?"#[command]":/#\[\s*test\b/.test(e)?"#[test]":/#\[\s*bench\b/.test(e)?"#[bench]":/#\[\s*tokio::test\b/.test(e)?"#[tokio::test]":/#\[\s*async_std::test\b/.test(e)?"#[async_std::test]":/#\[\s*wasm_bindgen\b/.test(e)?"#[wasm_bindgen]":/#\[\s*no_mangle\b/.test(e)?"#[no_mangle]":/#\[\s*napi\b/.test(e)?"#[napi]":/#\[\s*pyfunction\b/.test(e)?"#[pyfunction]":/#\[\s*pymethod\b/.test(e)?"#[pymethod]":/#\[\s*pyo3\b/.test(e)?"#[pyo3]":/#\[\s*cfg\s*\(\s*test\s*\)/.test(e)?"#[cfg(test)]":/#\[\s*doc\s*\(\s*hidden\s*\)/.test(e)?"#[doc(hidden)]":null}function qm(e){return/#\[\s*derive\s*\(/.test(e)?/\bSerialize\b/.test(e)||/\bDeserialize\b/.test(e)||/\bFromRow\b/.test(e)||/\bDeriveEntityModel\b/.test(e)||/\bIntoSchema\b/.test(e)||/\bToSchema\b/.test(e)||/\bDeriveValueType\b/.test(e)||/\bsqlx::FromRow\b/.test(e)||/\bError\b/.test(e)||/\bthiserror::Error\b/.test(e):!1}function ps(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function zm(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function Gm(e){let t=ep(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:i})}return n}function Km(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var Ym=[{key:"default",re:/\bdefault\s*=\s*"([^"]+)"/g},{key:"with",re:/\bwith\s*=\s*"([^"]+)"/g},{key:"serialize_with",re:/\bserialize_with\s*=\s*"([^"]+)"/g},{key:"deserialize_with",re:/\bdeserialize_with\s*=\s*"([^"]+)"/g},{key:"skip_serializing_if",re:/\bskip_serializing_if\s*=\s*"([^"]+)"/g},{key:"getter",re:/\bgetter\s*=\s*"([^"]+)"/g},{key:"rename_all_with",re:/\brename_all_with\s*=\s*"([^"]+)"/g},{key:"schema_with",re:/\bschema_with\s*=\s*"([^"]+)"/g}],fs=/^#!?\[\s*serde\s*\(/,Qm=/^#!?\[\s*schemars\s*\(/,Xm=/^#!?\[\s*validate\s*\(/,ls=/\bwith\s*=\s*"([^"]+)"/g;function st(e,t){return nn(e,t,Zm,()=>new Set,(n,r,i)=>{if(r==="rust"){for(let s of n.rootNode.descendantsOfType("attribute_item"))cs(s.text,i);for(let s of n.rootNode.descendantsOfType("inner_attribute_item"))cs(s.text,i)}})??new Set}var Zm=new WeakMap;function cs(e,t){let n=fs.test(e),r=Qm.test(e),i=Xm.test(e);if(!(!n&&!r&&!i))for(let{re:s}of Ym){s.lastIndex=0;let o;for(;(o=s.exec(e))!==null;){let a=o[1],l=a.split("::").pop()??a;l==="is_none"&&/\bOption\b/.test(a)||l==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||l&&t.add(l)}}}function ep(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!fs.test(n.text))continue;ls.lastIndex=0;let r;for(;(r=ls.exec(n.text))!==null;){let i=r[1],s=i.split("::").pop()??i;s&&t.add(s)}}return t}var tp=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function gs(e,t){return nn(e,t,np,()=>new Set,(n,r,i)=>{if(!(r!=="typescript"&&r!=="tsx"&&r!=="javascript"))for(let s of n.rootNode.descendantsOfType("call_expression")){let o=s.namedChild(0);if(!o)continue;let a=ht(o);if(!a||!tp.has(a))continue;let l=s.namedChildren.find(d=>d.type==="arguments");if(!l)continue;let c=l.namedChild(0);if(!c||c.type!=="string")continue;let u=c.namedChildren.find(d=>d.type==="string_fragment");u&&i.add(u.text)}})??new Set}var np=new WeakMap;function an(e){return e.replace(/'''[\s\S]*?'''/g,Pe).replace(/"""[\s\S]*?"""/g,Pe).replace(/#.*$/gm,Pe).replace(/\/\/.*$/gm,Pe).replace(/\/\*[\s\S]*?\*\//g,Pe).replace(/`(?:\\[\s\S]|[^`])*`/g,Pe).replace(/'(?:\\.|[^'\\\r\n])*'/g,Pe).replace(/"(?:\\.|[^"\\\r\n])*"/g,Pe)}function Pe(e){return e.replace(/[^\r\n]/g," ")}var rp=Wt("stripped-lines");function ys(e,t,n){return rp.get(e,t,n,()=>an(n).split(`
|
|
364
|
-
`))}var
|
|
363
|
+
ORDER BY relative_path`).filter(l=>!e.isIgnored(l.relative_path)).map(l=>({relativePath:l.relative_path,score:kp(l.relative_path,r)})).filter(l=>l.score>0).sort((l,c)=>c.score-l.score||l.relativePath.localeCompare(c.relativePath));if(s.length===0){let l=L(e,t);return!l||e.isIgnored(l.relativePath)?[]:[{relativePath:l.relativePath,score:700}]}let o=s.filter(l=>l.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let a=s.filter(l=>l.score>=800);return a.length>0?n.allowMultiple?a:[a[0]]:n.allowMultiple?s:[s[0]]}function kp(e,t){let n=Cs(e),r=Is(n),i=Is(t),s=0;return n===t&&(s+=1200),n.endsWith(`/${t}`)&&(s+=1100),r===i&&(s+=900),n.startsWith(`${t}/`)&&(s+=850),n.includes(t)&&(s+=250),s}function Cs(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}function vs(e,t){let n=Oe(e,t);return it(e,n).map(({relativePath:r,...i})=>i)}import{basename as Bh}from"path";var xt=new WeakMap;function Ds(e,t){let n=T(t);return n==="rust"?Fp(e,t):n==="typescript"||n==="tsx"||n==="javascript"?Op(e,t):[]}var Pp=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function Op(e,t){let n=O(e,t);if(!n)return[];let r=xt.get(n);if(r)return r;let i=/(^|\/)(pages|app)\/.+\.(tsx?|jsx?)$/.test(t)||/(^|\/)(layout|page|loading|error|not-found|head|template|default)\.(tsx?|jsx?)$/.test(t),s=/(^|\/)src\/(pages|views|routes)\/.+\.(tsx?|jsx?|vue)$/.test(t),o=!1,a=n.rootNode;for(let c of a.namedChildren){if(c.type!=="expression_statement")continue;let u=c.namedChild(0);if(!u||u.type!=="call_expression")continue;let d=u.namedChild(0);if(!d)continue;let m=d.type==="member_expression"?d.namedChild(d.namedChildCount-1)?.text:d.text;if(m&&Pp.has(m)){o=!0;break}}let l=[];o&&l.push({startLine:0,endLine:a.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"}),(i||s)&&l.push({startLine:0,endLine:a.endPosition.row,reason:i?"Next.js / Remix route file":"Vite/Vue route component"});for(let c of a.namedChildren){let u=null,d=null;if(c.type==="function_declaration")u=c.namedChild(0)?.text??null,d=c;else if(c.type==="export_statement"){let m=c.namedChild(0);m?.type==="function_declaration"&&(u=m.namedChild(0)?.text??null,d=m)}else if(c.type==="lexical_declaration"){let m=c.namedChild(0);if(m?.type==="variable_declarator"){let f=m.namedChild(0)?.text,h=m.namedChild(1);f&&(h?.type==="arrow_function"||h?.type==="function_expression")&&(u=f,d=m)}}u&&/^use[A-Z]/.test(u)&&d&&l.push({startLine:d.startPosition.row,endLine:d.endPosition.row,reason:"React custom hook (use*)"})}return l.push(...Ls(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),xt.set(n,l),l}var Mp=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function Tp(e){return Mp.test(e)}function Ls(e,t,n){let r=[],i=s=>{if(t.has(s.type)&&s.parent){let a=s.parent.children,l=-1;for(let c=0;c<a.length;c+=1)if(a[c].startIndex===s.startIndex&&a[c].type===s.type){l=c;break}if(l>0)for(let c=l-1;c>=0;c-=1){let u=a[c];if(n.has(u.type)){if(Tp(u.text)){r.push({startLine:s.startPosition.row,endLine:s.endPosition.row,reason:"scip-query suppression comment"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let o of s.namedChildren)i(o)};return i(e.rootNode),r}function Fp(e,t){let n=O(e,t);if(!n)return[];let r=xt.get(n);if(r)return r;let i=[],s=Ap(n);return s?(xt.set(n,s),s):(ws(n.rootNode,i,!1,!1),i.push(...Ls(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),i.push(...Up(n.rootNode)),xt.set(n,i),i)}function Ap(e){return Vp(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function ws(e,t,n,r){let i=n,s=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(s=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)"})),e.type==="function_item"||e.type==="function_signature_item"?$p(e,t,n,r):r&&Wp(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?jp(e,t,n):e.type==="mod_item"&&Sr(e).some(o=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(o))&&(i=!0);for(let o of e.namedChildren)ws(o,t,i,s)}function $p(e,t,n,r){let i=Sr(e),s=null;r?s="trait impl method (dynamic dispatch)":n&&(s="inside #[cfg(test)] mod");for(let o of i){let a=Bp(o);if(a){s=a;break}if(ks(o)){s="#[allow(dead_code)]";break}}s&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:s})}function jp(e,t,n){let r=Sr(e),i=e.namedChildren.find(s=>s.type==="type_identifier")?.text;r.some(Hp)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(ks)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:i})}function Sr(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let s=0;s<n.length;s+=1)if(n[s].startIndex===e.startIndex&&n[s].type===e.type){r=s;break}if(r<=0)return[];let i=[];for(let s=r-1;s>=0;s-=1){let o=n[s];if(o.type==="attribute_item"||o.type==="inner_attribute_item")i.push(o.text);else{if(o.type==="line_comment"||o.type==="block_comment")continue;break}}return i}function Bp(e){return/#\[\s*tauri::command\b/.test(e)?"#[tauri::command]":/#\[\s*command\b/.test(e)?"#[command]":/#\[\s*test\b/.test(e)?"#[test]":/#\[\s*bench\b/.test(e)?"#[bench]":/#\[\s*tokio::test\b/.test(e)?"#[tokio::test]":/#\[\s*async_std::test\b/.test(e)?"#[async_std::test]":/#\[\s*wasm_bindgen\b/.test(e)?"#[wasm_bindgen]":/#\[\s*no_mangle\b/.test(e)?"#[no_mangle]":/#\[\s*napi\b/.test(e)?"#[napi]":/#\[\s*pyfunction\b/.test(e)?"#[pyfunction]":/#\[\s*pymethod\b/.test(e)?"#[pymethod]":/#\[\s*pyo3\b/.test(e)?"#[pyo3]":/#\[\s*cfg\s*\(\s*test\s*\)/.test(e)?"#[cfg(test)]":/#\[\s*doc\s*\(\s*hidden\s*\)/.test(e)?"#[doc(hidden)]":null}function Hp(e){return/#\[\s*derive\s*\(/.test(e)?/\bSerialize\b/.test(e)||/\bDeserialize\b/.test(e)||/\bFromRow\b/.test(e)||/\bDeriveEntityModel\b/.test(e)||/\bIntoSchema\b/.test(e)||/\bToSchema\b/.test(e)||/\bDeriveValueType\b/.test(e)||/\bsqlx::FromRow\b/.test(e)||/\bError\b/.test(e)||/\bthiserror::Error\b/.test(e):!1}function ks(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function Wp(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function Up(e){let t=Kp(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:i})}return n}function Vp(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var Jp=[{key:"default",re:/\bdefault\s*=\s*"([^"]+)"/g},{key:"with",re:/\bwith\s*=\s*"([^"]+)"/g},{key:"serialize_with",re:/\bserialize_with\s*=\s*"([^"]+)"/g},{key:"deserialize_with",re:/\bdeserialize_with\s*=\s*"([^"]+)"/g},{key:"skip_serializing_if",re:/\bskip_serializing_if\s*=\s*"([^"]+)"/g},{key:"getter",re:/\bgetter\s*=\s*"([^"]+)"/g},{key:"rename_all_with",re:/\brename_all_with\s*=\s*"([^"]+)"/g},{key:"schema_with",re:/\bschema_with\s*=\s*"([^"]+)"/g}],Ps=/^#!?\[\s*serde\s*\(/,qp=/^#!?\[\s*schemars\s*\(/,zp=/^#!?\[\s*validate\s*\(/,Ns=/\bwith\s*=\s*"([^"]+)"/g;function at(e,t){return on(e,t,Gp,()=>new Set,(n,r,i)=>{if(r==="rust"){for(let s of n.rootNode.descendantsOfType("attribute_item"))Es(s.text,i);for(let s of n.rootNode.descendantsOfType("inner_attribute_item"))Es(s.text,i)}})??new Set}var Gp=new WeakMap;function Es(e,t){let n=Ps.test(e),r=qp.test(e),i=zp.test(e);if(!(!n&&!r&&!i))for(let{re:s}of Jp){s.lastIndex=0;let o;for(;(o=s.exec(e))!==null;){let a=o[1],l=a.split("::").pop()??a;l==="is_none"&&/\bOption\b/.test(a)||l==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||l&&t.add(l)}}}function Kp(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!Ps.test(n.text))continue;Ns.lastIndex=0;let r;for(;(r=Ns.exec(n.text))!==null;){let i=r[1],s=i.split("::").pop()??i;s&&t.add(s)}}return t}var Yp=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Os(e,t){return on(e,t,Qp,()=>new Set,(n,r,i)=>{if(!(r!=="typescript"&&r!=="tsx"&&r!=="javascript"))for(let s of n.rootNode.descendantsOfType("call_expression")){let o=s.namedChild(0);if(!o)continue;let a=bt(o);if(!a||!Yp.has(a))continue;let l=s.namedChildren.find(d=>d.type==="arguments");if(!l)continue;let c=l.namedChild(0);if(!c||c.type!=="string")continue;let u=c.namedChildren.find(d=>d.type==="string_fragment");u&&i.add(u.text)}})??new Set}var Qp=new WeakMap;function dn(e){return e.replace(/'''[\s\S]*?'''/g,Me).replace(/"""[\s\S]*?"""/g,Me).replace(/#.*$/gm,Me).replace(/\/\/.*$/gm,Me).replace(/\/\*[\s\S]*?\*\//g,Me).replace(/`(?:\\[\s\S]|[^`])*`/g,Me).replace(/'(?:\\.|[^'\\\r\n])*'/g,Me).replace(/"(?:\\.|[^"\\\r\n])*"/g,Me)}function Me(e){return e.replace(/[^\r\n]/g," ")}var Ms=Vt("stripped-lines");function Ts(e,t,n){return Ms.get(e,t,n,()=>dn(n).split(`
|
|
364
|
+
`))}function Fs(e){Ms.invalidateAll(e),xr=null,un=""}var xr=null,un="";function Xp(e){return xr===e||(xr=e,un=dn(e)),un}function Te(e,t,n){let r=Xp(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function Y(e,t){return new RegExp(`\\b${mn(t)}\\b`,"m").test(e)}function lt(e,t){let n=new Set,r=new RegExp(`\\b${mn(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let i of e.matchAll(r)){let s=i[1];s&&n.add(s)}return[...n]}function mn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Zp=new Set(["identifier","type_identifier","field_identifier"]),ef=new Set(["identifier"]),tf=new Set(["identifier","property_identifier","type_identifier"]),nf=new Set(["rust","python"]),rf=/\{([^{}]*)\}/g,sf=/\b([A-Za-z_][\w]*)\b/g;function pn(e,t,n,r={}){if(!n)return[];let i=P(e,t);if(!i)return[];if(i.indexOf(n)===-1)return[];if(T(t))return(Ge(e,t).get(n)??[]).filter(u=>!As(u,r));let s=Ts(e,t,i),o=new RegExp(`\\b${mn(n)}\\b`),a=[];for(let l=0;l<s.length;l++)As(l,r)||o.test(s[l]??"")&&a.push(l);return a}function As(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var $s=A("file-identifiers");function js(e,t){return $s.get(e,t,()=>new Set(Ge(e,t).keys()))}var Bs=A("file-ident-lines");function Ge(e,t){return Bs.get(e,t,()=>of(e,t))}var Hs=A("file-idents-by-line");function Ws(e,t){return Hs.get(e,t,()=>{let n=Ge(e,t),r=0;for(let s of n.values()){let o=s[s.length-1];o!==void 0&&o>r&&(r=o)}let i=new Array(r+1);for(let s=0;s<=r;s+=1)i[s]=new Set;for(let[s,o]of n)for(let a of o)i[a].add(s);return i})}function Us(e){$s.invalidateAll(e),Bs.invalidateAll(e),Hs.invalidateAll(e)}function of(e,t){let n=new Map,r=(a,l)=>{let c=n.get(a);if(!c){n.set(a,[l]);return}c[c.length-1]!==l&&c.push(l)};if(T(t)){let a=O(e,t);if(a){let l=T(t),c=l==="rust"?Zp:l==="python"?ef:tf,u=d=>{if(c.has(d.type)&&r(d.text,d.startPosition.row),l&&nf.has(l)&&d.type==="string_content"){let m=d.startPosition.row;for(let f of d.text.matchAll(rf)){let h=f[1]??"";for(let p of h.matchAll(sf))p[1]&&r(p[1],m)}}for(let m of d.children)u(m)};return u(a.rootNode),n}}let i=P(e,t);if(!i)return n;let s=dn(i).split(/\r?\n/),o=/\b([A-Za-z_$][\w$]*)\b/g;for(let a=0;a<s.length;a+=1){let l=s[a]??"";for(let c of l.matchAll(o))c[1]&&r(c[1],a)}return n}import{existsSync as fn}from"fs";import{basename as af,dirname as Fe,extname as _e,join as le,relative as _t,resolve as te}from"path";var lf=Be("indexed-paths"),It=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Vs=[".py",".pyi"],ce=[".java",".scala",".kt",".kts"],Js=[".rs"],qs=[".rb"],zs=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],ct=[".cs",".vb"],Gs=[".dart"],Rt=[".php"],cf=new Set(It),_r=new Set(Vs),Ks=new Set(ce),Ir=new Set(Js),Rr=new Set(qs),Ys=new Set(zs),Qs=new Set(ct),Cr=new Set(Gs),Xs=new Set(Rt),uf=[{extensions:It,lookup:cf},{extensions:Vs,lookup:_r},{extensions:ce,lookup:Ks},{extensions:Js,lookup:Ir},{extensions:qs,lookup:Rr},{extensions:zs,lookup:Ys},{extensions:ct,lookup:Qs},{extensions:Gs,lookup:Cr},{extensions:Rt,lookup:Xs}];function Ae(e,t){return t.has(_e(e).toLowerCase())}function df(e){return Ae(e,_r)}function mf(e){return Ae(e,Ks)}function pf(e){return Ae(e,Ir)}function ff(e){return Ae(e,Rr)}function gf(e){return Ae(e,Ys)}function hf(e){return Ae(e,Qs)}function Zs(e){return _e(e).toLowerCase()===".vb"}function yf(e){return Ae(e,Cr)}function bf(e){return Ae(e,Xs)}function vr(e){let t=_e(e).toLowerCase();for(let n of uf)if(n.lookup.has(t))return n.extensions;return It}function Sf(e){return mf(e)||hf(e)||bf(e)}function he(e,t,n){return df(t)?ut(e,t,n):pf(t)?Ie(e,t,n):ff(t)?gn(e,t,n):gf(t)?hn(e,t,n):Sf(t)?j(e,n.replace(/\\/g,"."),vr(t)):yf(t)?yn(e,t,n):xf(e,t,n)}function xf(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let r=Fe(le(e.config.projectRoot,t)),i=te(r,n),s=Ct(e);for(let o of vf(i)){let a=ge(_t(e.config.projectRoot,o));if(s.has(a)||fn(o))return a}return ge(_t(e.config.projectRoot,i))}function ut(e,t,n){let r=Ct(e),i;if(n.startsWith(".")){let s=n.match(/^(\.+)(.*)$/);if(!s)return null;let o=s[1].length,a=s[2].replace(/^\./,""),l=Fe(le(e.config.projectRoot,t));for(let c=1;c<o;c++)l=Fe(l);i=a?te(l,a.replace(/\./g,"/")):l}else i=te(e.config.projectRoot,n.replace(/\./g,"/"));for(let s of _f(i)){let o=ge(_t(e.config.projectRoot,s));if(r.has(o)||fn(s))return o}return null}function Ie(e,t,n){if(!n)return null;let r=n.replace(/\s+as\s+.+$/,"").trim();if(!r.startsWith("crate::")&&!r.startsWith("self::")&&!r.startsWith("super::"))return null;let i=Fe(le(e.config.projectRoot,t)),s;return r.startsWith("crate::")?s=te(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?s=te(i,r.slice(6).replace(/::/g,"/")):s=te(Fe(i),r.slice(7).replace(/::/g,"/")),Nr(e,If(s))}function gn(e,t,n){let r=Fe(le(e.config.projectRoot,t)),i=te(r,n);return Nr(e,Rf(i))}function hn(e,t,n){let r=Fe(le(e.config.projectRoot,t)),i=[te(r,n),te(e.config.projectRoot,n),te(e.config.projectRoot,"include",n),te(e.config.projectRoot,"src",n)];return Nr(e,i)}function j(e,t,n){let r=Ct(e),i=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),s=i.replace(/\./g,"/"),o=i.split(".").pop()??i;for(let l of n){let c=`${s}${l}`,u=[...r].find(d=>d.endsWith(c));if(u)return u}for(let l of n){let c=[...r].find(u=>af(u)===`${o}${l}`);if(c)return c}let a=[...r].filter(l=>n.includes(_e(l).toLowerCase())).filter(l=>l.includes(`/${s}/`)||l.includes(`/${o}/`)).sort((l,c)=>l.localeCompare(c));return a.length===1?a[0]:null}function yn(e,t,n){let r=Ct(e);if(n.startsWith("package:")){let o=n.slice(8),a=o.indexOf("/");if(a<0)return null;let l=o.slice(a+1),c=ge(l.startsWith("lib/")?l:`lib/${l}`);return r.has(c)?c:null}let i=Fe(le(e.config.projectRoot,t)),s=te(i,n);for(let o of Cf(s)){let a=ge(_t(e.config.projectRoot,o));if(r.has(a)||fn(o))return a}return null}function _f(e){let t=_e(e);return _r.has(t)?[e]:[`${e}.py`,`${e}.pyi`,le(e,"__init__.py"),le(e,"__init__.pyi")]}function Nr(e,t){let n=Ct(e);for(let r of t){let i=ge(_t(e.config.projectRoot,r));if(n.has(i)||fn(r))return i}return null}function If(e){let t=_e(e);return Ir.has(t)?[e]:[`${e}.rs`,le(e,"mod.rs")]}function Rf(e){let t=_e(e);return Rr.has(t)?[e]:[`${e}.rb`,le(e,"index.rb")]}function Cf(e){let t=_e(e);return Cr.has(t)?[e]:[`${e}.dart`,e]}function vf(e){let t=_e(e),n=new Set;if(t){n.add(e);for(let r of It)n.add(e.slice(0,-t.length)+r)}else for(let r of It)n.add(`${e}${r}`),n.add(le(e,`index${r}`));return[...n]}function Ct(e){return lf.get(e,()=>new Set(e.all(`SELECT relative_path
|
|
365
365
|
FROM documents
|
|
366
366
|
WHERE 1 = 1
|
|
367
|
-
${e.pathExclusionsFor("documents")}`).map(t=>fe(t.relative_path)).filter(t=>!e.isIgnored(t))))}function fe(e){return e.replace(/\\/g,"/")}var Mp=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function X(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let s=e[i];(s==="{"||s==="["||s==="(")&&n++,(s==="}"||s==="]"||s===")")&&n--,s===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function ne(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function B(e,t){let n=new Set,r=(i,s)=>{let o=s||t.has(i.type);!o&&Mp.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,o)};return r(e.rootNode,!1),n}function he(e,t,n,r,i,s,o){return{importedName:i,localName:s,sourcePath:o??j(e,r,Sr(t)),kind:"named",used:K(n,s),usedMembers:[]}}function re(e,t,n){let r=[];for(let i of e.matchAll(t)){let s=i[0];if(!s||typeof i.index!="number")continue;let o=Oe(e,i.index,i.index+s.length);for(let a of n(i,o))r.push(a)}return r}function Ps(e,t,n){let r=P(e,t);return r?Fp(e,t,r):zp(n).flatMap(i=>Gp(e,t,i.clause,i.specifier,i.start,i.end,n))}function Fp(e,t,n){let r=Tp(e,t,n),i=[];for(let s of n.rootNode.descendantsOfType("import_statement"))i.push(...$p(e,t,n,s,r));return i}function Tp(e,t,n){let r=B(n,new Set(["import_statement"]));if(yt(t))for(let i of af(e,t))r.add(i);return r}function $p(e,t,n,r,i){let s=Vp(r);if(!s)return[];let o=ge(e,t,s),a=ne(r,"import_clause");return a?Ap(n,a,o,i,Up(r.text)):[jp(o)]}function Ap(e,t,n,r,i){let s=[];for(let o of t.namedChildren)if(o.type==="identifier")s.push(Bp(o.text,n,r,i));else if(o.type==="namespace_import"){let a=Wp(e,o,n,r,i);a&&s.push(a)}else o.type==="named_imports"&&s.push(...Hp(o,n,r,i));return s}function jp(e){return{importedName:"*",localName:null,sourcePath:e,kind:"side-effect",used:!0,usedMembers:[]}}function Bp(e,t,n,r){return{importedName:"default",localName:e,sourcePath:t,kind:"default",used:n.has(e),usedMembers:[],isTypeOnly:r}}function Wp(e,t,n,r,i){let o=ne(t,"identifier")?.text??"";if(!o)return null;let a=qp(e,o);return{importedName:"*",localName:o,sourcePath:n,kind:"namespace",used:a.length>0||r.has(o),usedMembers:a,isTypeOnly:i}}function Hp(e,t,n,r){let i=[];for(let s of e.namedChildren){if(s.type!=="import_specifier")continue;let o=s.namedChild(0),a=s.namedChild(1);if(!o)continue;let l=o.text,c=a?.text??l;i.push({importedName:l,localName:c,sourcePath:t,kind:"named",used:n.has(c),usedMembers:[],isTypeOnly:r||Jp(s.text)})}return i}function Vp(e){let t=ne(e,"string");if(!t)return null;let n=ne(t,"string_fragment");return n?n.text:null}function Up(e){return/^\s*import\s+type\b/.test(e)}function Jp(e){return/^\s*type\b/.test(e.trim())}function qp(e,t){let n=new Set;for(let r of e.rootNode.descendantsOfType("member_expression")){let i=r.namedChild(0),s=r.namedChild(1);!i||!s||i.type!=="identifier"||i.text!==t||(s.type==="property_identifier"||s.type==="identifier")&&n.add(s.text)}return[...n]}function zp(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(n)){let s=i[0],o=i[1],a=i[2];!s||!a||typeof i.index!="number"||t.push({clause:o,specifier:a,start:i.index,end:i.index+s.length})}let r=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(r)){let s=i[0],o=i[1];!s||!o||typeof i.index!="number"||t.push({clause:null,specifier:o,start:i.index,end:i.index+s.length})}return t.sort((i,s)=>i.start-s.start)}function Gp(e,t,n,r,i,s,o){let a=ge(e,t,r),l=Oe(o,i,s);return n?Kp(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=ot(l,u.localName);return{...u,used:d.length>0||K(l,u.localName),usedMembers:d}}return u.kind==="side-effect"?{...u,used:!0,usedMembers:[]}:{...u,used:u.localName?K(l,u.localName):!1,usedMembers:[]}}):[{importedName:"*",localName:null,sourcePath:a,kind:"side-effect",used:!0,usedMembers:[]}]}function Kp(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,s]=Yp(r),o=[];return i&&o.push(...ws(i,n)),s&&o.push(...ws(s,n)),o}function ws(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?X(r).map(i=>{let s=i.trim(),o=t||/^type\b/.test(s),a=s.replace(/^type\s+/,""),[l,c]=a.split(/\s+as\s+/);return{importedName:l.trim(),localName:(c??l).trim(),kind:"named",isTypeOnly:o}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function Yp(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="{"&&t++,r==="}"&&t--,r===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function Os(e,t){let n=P(e,t);if(n)return nf(e,t,n);let r=w(e,t);return r?Qp(e,t,r):[]}function Qp(e,t,n){return[...Xp(e,t,n),...Zp(e,t,n),...ef(e,t,n)]}function Xp(e,t,n){let r=[],i=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let s of n.matchAll(i)){if(typeof s.index!="number")continue;let o=s[1]??"",a=s[2]??"",l=X(o).map(d=>tf(d.trim())).filter(d=>!!d),c=ct(n,s.index),u=ct(n,s.index+s[0].length-1);r.push({kind:"named",sourcePath:ge(e,t,a),names:l,startLine:c,endLine:u})}return r}function Zp(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let s of n.matchAll(i)){if(typeof s.index!="number")continue;let o=s[2]??"",a=ct(n,s.index),l=ct(n,s.index+s[0].length-1);r.push({kind:"star-as",sourcePath:ge(e,t,o),names:[],startLine:a,endLine:l})}return r}function ef(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let s of n.matchAll(i)){if(typeof s.index!="number")continue;let o=s[1]??"",a=ct(n,s.index),l=ct(n,s.index+s[0].length-1);r.push({kind:"star",sourcePath:ge(e,t,o),names:[],startLine:a,endLine:l})}return r}function tf(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let r=t.match(/^(\w+)$/);return r?r[1]??null:null}function ct(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function nf(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let s=rf(e,t,i);if(s===void 0)continue;let o=i.startPosition.row,a=i.endPosition.row,l=sf(i,s,o,a);r.push(l)}return r}function rf(e,t,n){let r=ne(n,"string");if(!r)return;let i=ne(r,"string_fragment");if(i)return ge(e,t,i.text)}function sf(e,t,n,r){let i=ne(e,"export_clause");if(i){let o=[];for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let l=a.namedChild(0),c=a.namedChild(1);l&&o.push((c??l).text)}return{kind:"named",sourcePath:t,names:o,startLine:n,endLine:r}}return ne(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}var of=$("vue-non-script-identifiers");function af(e,t){return of.get(e,t,()=>{let n=new Set,r=w(e,t);if(!r)return n;let s=r.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,o=>o.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,o=>o.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,o=>o.replace(/[^\r\n]/g," "));for(let o of s.matchAll(/[A-Za-z_$][\w$]*/g))n.add(o[0]);return n})}import{basename as Ms}from"path";function Fs(e,t,n){let r=P(e,t);return r?lf(e,t,r):re(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(i,s)=>{let o=i[1]?.trim();if(!o)return[];let a=Ms(o).replace(/\.[^.]+$/,"");return[{importedName:o,localName:a,sourcePath:mn(e,t,o),kind:"named",used:K(s,a),usedMembers:[]}]})}function lf(e,t,n){let r=B(n,new Set(["preproc_include"])),i=[];for(let s of n.rootNode.descendantsOfType("preproc_include")){let o=null;for(let l of s.namedChildren){if(l.type==="system_lib_string"){o=l.text.replace(/^<|>$/g,"");break}if(l.type==="string_literal"){o=l.namedChildren.find(u=>u.type==="string_content")?.text??l.text.replace(/^"|"$/g,"");break}}if(!o)continue;let a=Ms(o).replace(/\.[^.]+$/,"");i.push({importedName:o,localName:a,sourcePath:mn(e,t,o),kind:"named",used:r.has(a),usedMembers:[]})}return i}function Ts(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let s=i[1]?.trim(),o=i[2]?.trim()??null,a=i[0];if(!s||!a||typeof i.index!="number")continue;let l=Oe(n,i.index,i.index+a.length);r.push({importedName:s,localName:o,sourcePath:pn(e,t,s),kind:o?"namespace":"side-effect",used:o?K(l,o):!0,usedMembers:o?ot(l,o):[]})}return r}function $s(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let s=i[1]?.trim();s&&r.push({specifier:s,sourcePath:pn(e,t,s)})}return r}function As(e,t,n){let r=P(e,t),i=M(t);if(r&&i==="csharp")return uf(e,t,r);if(r&&i==="vb")return cf(e,t,r);let s=ks(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return re(n,s,(o,a)=>{let l=o[1]?.trim();if(!l)return[];let[c,u]=l.split(/\s*=\s*/),d=!!u,m=(d?u:c)?.trim()??l,g=m.split(".").pop()??m,p=d?c?.trim()??g:g;return[he(e,t,a,m,g,p,j(e,m,at))]})}function cf(e,t,n){let r=B(n,new Set(["imports_statement"])),i=[];for(let s of n.rootNode.descendantsOfType("imports_statement")){let o=s.namedChildren.filter(m=>m.type==="namespace_name");if(o.length===0)continue;let a=o[o.length-1],l=o.length>1?o[0]:null,c=a.text,u=c.split(".").pop()??c,d=l?.text??u;i.push({importedName:u,localName:d,sourcePath:j(e,c,at),kind:l?"namespace":"named",used:r.has(d),usedMembers:[]})}return i}function uf(e,t,n){let r=B(n,new Set(["using_directive"])),i=[];for(let s of n.rootNode.descendantsOfType("using_directive")){let o=s.namedChildren;if(o.length===0)continue;let a=null,l;o.length>=2&&o[0].type==="identifier"&&(o[1].type==="qualified_name"||o[1].type==="identifier")?(a=o[0],l=o[1]):l=o[o.length-1];let c=l.text,u=c.split(".").pop()??c,d=a?.text??u;i.push({importedName:u,localName:d,sourcePath:j(e,c,at),kind:a?"namespace":"named",used:r.has(d),usedMembers:[]})}return i}function js(e,t,n){let r=P(e,t),i=M(t);return r&&i==="java"?df(e,t,r):r&&i==="kotlin"?mf(e,t,r):r&&i==="scala"?pf(e,t,r):re(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(s,o)=>{let a=s[1]?.trim();return a?ff(e,t,a,o):[]})}function df(e,t,n){let r=B(n,new Set(["import_declaration"])),i=[];for(let s of n.rootNode.descendantsOfType("import_declaration")){let o=s.children.some(d=>d.type==="asterisk"),l=s.namedChildren.find(d=>d.type==="scoped_identifier")??s.namedChildren.find(d=>d.type==="identifier");if(!l)continue;let c=l.text;if(o){i.push({importedName:"*",localName:null,sourcePath:j(e,c,ce),kind:"namespace",used:!0,usedMembers:[]});continue}let u=c.split(".").pop()??c;i.push({importedName:u,localName:u,sourcePath:j(e,c,ce),kind:"named",used:r.has(u),usedMembers:[]})}return i}function mf(e,t,n){let r=B(n,new Set(["import_header","import_list"])),i=[];for(let s of n.rootNode.descendantsOfType("import_header")){let o=s.namedChildren.find(g=>g.type==="identifier");if(!o)continue;let a=s.namedChildren.some(g=>g.type==="wildcard_import"),l=s.namedChildren.find(g=>g.type==="import_alias");if(a){i.push({importedName:"*",localName:null,sourcePath:j(e,o.text,ce),kind:"namespace",used:!0,usedMembers:[]});continue}let c=o.text,u=c.split(".").pop()??c,m=l?.namedChild(0)?.text??u;i.push({importedName:u,localName:m,sourcePath:j(e,c,ce),kind:"named",used:r.has(m),usedMembers:[]})}return i}function pf(e,t,n){let r=B(n,new Set(["import_declaration"])),i=[];for(let s of n.rootNode.descendantsOfType("import_declaration")){let o=s.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=s.namedChildren.filter(d=>d!==o&&(d.type==="identifier"||d.type==="stable_identifier")),l=a.map(d=>d.text).join(".");if(!l)continue;if(o?.type==="namespace_wildcard"){i.push({importedName:"*",localName:null,sourcePath:j(e,l,ce),kind:"namespace",used:!0,usedMembers:[]});continue}if(o?.type==="namespace_selectors"){for(let d of o.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,g]=d.namedChildren;if(!m)continue;let p=m.text,f=g?.text??p;if(p==="_")continue;i.push({importedName:p,localName:f,sourcePath:j(e,`${l}.${p}`,ce),kind:"named",used:r.has(f),usedMembers:[]})}else if(d.type==="identifier"){let m=d.text;i.push({importedName:m,localName:m,sourcePath:j(e,`${l}.${m}`,ce),kind:"named",used:r.has(m),usedMembers:[]})}continue}let c=a[a.length-1]?.text??l,u=a.slice(0,-1).map(d=>d.text).join(".")||l;i.push({importedName:c,localName:c,sourcePath:j(e,u&&a.length>1?`${u}.${c}`:l,ce),kind:"named",used:r.has(c),usedMembers:[]})}return i}function ff(e,t,n,r){if(n.includes("{")&&n.includes("}")){let i=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),s=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return X(s).flatMap(o=>{let a=o.trim();if(!a)return[];let[l,c]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=l?.trim();if(!u||u==="_")return[];let d=(c??u.split(".").pop()??u).trim(),m=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[he(e,t,r,m,u,d)]})}return[he(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Ws(e,t,n){let r=P(e,t);return r?gf(e,t,r):re(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,s)=>{let o=i[1]?.trim();return o?X(o).flatMap(a=>{let l=a.trim();if(!l)return[];let[c,u]=l.split(/\s+as\s+/i),d=c?.trim()??l,m=d.split("\\").pop()??d,g=(u??m).trim();return[he(e,t,s,d,m,g,j(e,d.replace(/\\/g,"."),_t))]}):[]})}function gf(e,t,n){let r=B(n,new Set(["namespace_use_declaration"])),i=[],s=(o,a,l)=>{i.push({importedName:a,localName:l,sourcePath:j(e,o.replace(/\\/g,"."),_t),kind:"named",used:r.has(l),usedMembers:[]})};for(let o of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=o.namedChildren.find(l=>l.type==="namespace_use_group");if(a){let l=o.namedChildren.find(c=>c.type==="namespace_name")?.text??"";for(let c of a.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:u,localName:d,qualified:m}=Bs(c,l);u&&s(m,u,d)}continue}for(let l of o.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:c,localName:u,qualified:d}=Bs(l,"");c&&s(d,c,u)}}return i}function Bs(e,t){let n=e.namedChildren.find(c=>c.type==="qualified_name"),r=e.namedChildren.filter(c=>c.type==="name"),i="";n?i=n.text:r.length>=1&&(i=r[0].text);let s=n&&r.length>0?r[r.length-1]:null,o=i.split("\\").pop()??i,a=s?.text??o,l=t?`${t}\\${i}`:i;return{importedName:o,localName:a,qualified:l}}function Us(e,t,n){let r=P(e,t);return r?hf(e,t,r):bf(n).flatMap(i=>xf(e,t,i,n))}function hf(e,t,n){let r=B(n,new Set(["import_statement","import_from_statement"])),i=[];for(let s of n.rootNode.descendantsOfType("import_statement"))for(let o of s.namedChildren){let a=Hs(o);if(!a)continue;let l=lt(e,t,a.qualifiedName);i.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:l,kind:"namespace",used:r.has(a.localName),usedMembers:[]})}for(let s of n.rootNode.descendantsOfType("import_from_statement")){let o=s.namedChild(0);if(!o)continue;let a=yf(o);if(a===null)continue;let l=lt(e,t,a);for(let c=1;c<s.namedChildCount;c+=1){let u=s.namedChild(c);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:l,kind:"side-effect",used:!0,usedMembers:[]});continue}let d=Hs(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:l,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function Hs(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function yf(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=ne(e,"import_prefix")?.text??"",n=ne(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function bf(e){let t=e.split(`
|
|
368
|
-
`),n=[],r=0;for(let i=0;i<t.length;i++){let s=t[i],o=s.trimStart(),a=r;if(r+=s.length+1,!o.startsWith("import ")&&!o.startsWith("from "))continue;let l=s,c=a+s.length,u=
|
|
369
|
-
${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,end:c})}return n}function Sf(e){let t=e.replace(/\\\s*\n/g," ").trim();if(t.startsWith("import "))return{kind:"import",module:null,clause:t.slice(7).trim()};let n=t.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);if(!n)return null;let r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function xf(e,t,n,r){let i=Oe(r,n.start,n.end),s=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return X(s).flatMap(l=>{let c=l.trim().replace(/,$/,"");if(!c)return[];let[u,d]=c.split(/\s+as\s+/),m=u.trim(),g=(d??m.split(".")[0]??m).trim(),p=lt(e,t,m),f=ot(i,g);return[{importedName:m,localName:g,sourcePath:p,kind:"namespace",used:K(i,g)||f.length>0,usedMembers:f}]});let o=n.module?lt(e,t,n.module):null,a=[];for(let l of X(s)){let c=l.trim().replace(/,$/,"");if(!c)continue;if(c==="*"){a.push({importedName:"*",localName:null,sourcePath:o,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=c.split(/\s+as\s+/),m=(d??u).trim();a.push({importedName:u.trim(),localName:m,sourcePath:o,kind:"named",used:K(i,m),usedMembers:[]})}return a}function Vs(e){let t=0;for(let n of e)n==="("&&t++,n===")"&&t--;return t}import{basename as _f}from"path";function Js(e,t,n){let r=P(e,t);return r?If(e,t,r):re(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(i,s)=>{let o=i[1],a=i[2];if(!o||!a)return[];let l=o==="require_relative"?dn(e,t,a):null;if(l){let c=qs(a);return[{importedName:c,localName:c,sourcePath:l,kind:"named",used:K(s,c),usedMembers:[]}]}return[{importedName:a,localName:null,sourcePath:l,kind:"side-effect",used:!0,usedMembers:[]}]})}function If(e,t,n){let r=B(n,new Set([])),i=[],s=new Set(["require","require_relative","load"]);for(let o of n.rootNode.descendantsOfType("call")){let a=o.namedChild(0);if(!a||a.type!=="identifier"||!s.has(a.text))continue;let c=o.namedChildren.find(g=>g.type==="argument_list")?.namedChild(0);if(!c||c.type!=="string")continue;let d=c.namedChildren.find(g=>g.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?dn(e,t,d):null;if(m){let g=qs(d);i.push({importedName:g,localName:g,sourcePath:m,kind:"named",used:r.has(g),usedMembers:[]})}else i.push({importedName:d,localName:null,sourcePath:m,kind:"side-effect",used:!0,usedMembers:[]})}return i}function qs(e){return _f(e).replace(/\.[^.]+$/,"").split("_").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function zs(e,t,n){let r=P(e,t);return r?Rf(e,t,r):re(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,s)=>{let o=i[1]?.trim();return o?Cf(e,t,o,s):[]})}function Rf(e,t,n){let r=B(n,new Set(["use_declaration"])),i=[];for(let s of n.rootNode.descendantsOfType("use_declaration")){let o=s.namedChild(0);if(o)for(let a of Rt(o,"")){if(!a.importedName||a.importedName==="*")continue;let l=xe(e,t,a.qualifiedName)??xe(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push({importedName:a.importedName,localName:a.localName,sourcePath:l,kind:"named",used:r.has(a.localName),usedMembers:[]})}}return i}function Rt(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:fn(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:fn(t,n),importedName:r,localName:r}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=fn(t,n.text),s=[];for(let o of r.namedChildren)s.push(...Rt(o,i));return s}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...Rt(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Rt(n,t),s=r.text;return i.map(o=>({...o,localName:s}))}case"use_wildcard":{let n=e.namedChild(0),r=n?n.text:"";return[{qualifiedName:fn(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function fn(e,t){return e?t?`${e}::${t}`:e:t}function Cf(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),d=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return X(d).flatMap(m=>{let g=m.trim();if(!g||g==="self")return[];let[p,f]=g.split(/\s+as\s+/),y=p?.trim();if(!y)return[];let L=(f??y.split("::").pop()??y).trim(),k=`${u}::${y}`.replace(/::::/g,"::");return[he(e,t,r,k,y.split("::").pop()??y,L,xe(e,t,u))]})}let[s,o]=i.split(/\s+as\s+/),a=s?.trim()??i,l=(o??a.split("::").pop()??a).trim(),c=xe(e,t,a)??xe(e,t,a.split("::").slice(0,-1).join("::"));return[he(e,t,r,a,a.split("::").pop()??a,l,c)]}function Gs(e,t,n){let r=P(e,t);if(r)return vf(e,t,r);let i=[];for(let s of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let o=s[1]?.trim();o&&i.push(...Ef(e,t,o))}return i}function vf(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!Nf(i))continue;let s=i.namedChildren.find(o=>o.type!=="visibility_modifier");if(s)for(let o of Rt(s,""))o.importedName&&r.push(_r(e,t,o.qualifiedName))}return r}function Nf(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function Ef(e,t,n){let r=n.trim();if(r.includes("{")&&r.includes("}")){let i=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),s=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return X(s).flatMap(o=>{let a=o.trim();if(!a||a==="self")return[];let[l]=a.split(/\s+as\s+/),c=`${i}::${l?.trim()??a}`.replace(/::::/g,"::");return[_r(e,t,c)]})}return[_r(e,t,r)]}function _r(e,t,n){return{specifier:n,sourcePath:xe(e,t,n)??xe(e,t,n.split("::").slice(0,-1).join("::"))}}function Ks(e,t){let n=t.toLowerCase();for(let r of e)for(let i of r.extensions)if(n.endsWith(i))return r;return null}var Df={language:"javascript",extensions:[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],parseImports:Ps},Lf={language:"python",extensions:[".py",".pyi"],parseImports:Us},kf={language:"jvm",extensions:[".java",".scala",".kt",".kts"],parseImports:js},wf={language:"rust",extensions:[".rs"],parseImports:zs,parseExports:Gs},Pf={language:"ruby",extensions:[".rb"],parseImports:Js},Of={language:"c/cpp",extensions:[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],parseImports:Fs},Mf={language:"dotnet",extensions:[".cs",".vb"],parseImports:As},Ff={language:"dart",extensions:[".dart"],parseImports:Ts,parseExports:$s},Tf={language:"php",extensions:[".php"],parseImports:Ws},$f=[Df,Lf,kf,wf,Pf,Of,Mf,Ff,Tf];function Ir(e){return Ks($f,e)}function Ys(e,t){return Os(e,t)}var Af=$("source-imports"),jf=$("source-exports");function J(e,t){let n=fe(t);return Af.get(e,n,()=>{let r=Ir(n);if(!r)return[];let i=w(e,n);return i?r.parseImports(e,n,i):[]})}function Rr(e,t){let n=fe(t);return jf.get(e,n,()=>{let r=Ir(n);if(!r?.parseExports)return[];let i=w(e,n);return i?r.parseExports(e,n,i):[]})}import ue from"path";import{createRequire as Bf}from"module";import{existsSync as gn,readdirSync as Wf,readFileSync as eo}from"fs";var Hf=Bf(import.meta.url),Ct;function to(e,t){let n=Vf();if(!n)return Cr("ts-morph is not installed");let r=wi(e);if(r.length===0)return Cr("no tsconfig found");try{let i=r.map(s=>({tsconfigPath:s,project:new n.Project({tsConfigFilePath:s,skipFileDependencyResolution:!1})}));return new vr(e,n,i)}catch(i){return Cr(i instanceof Error?i.message:String(i),r[0],r)}}function Vf(){if(Ct!==void 0)return Ct;try{Ct=Hf("ts-morph")}catch{Ct=null}return Ct}function Cr(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}var vr=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Gf(t.config.projectRoot)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;sourceFileCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return _e(this.importUsageCache,t,()=>{let n=this.sourceFile(t);if(!n)return[];let r=[];for(let i of n.getImportDeclarations())for(let s of this.importUsageForDeclaration(t,i))r.push(s);return r})}referencesFor(t){return _e(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?tg(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return _e(this.calleesCache,t.symbolId,()=>_e(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return _e(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(o=>{let a=o.getDeclarations()[0],l=a?o.getTypeAtLocation(a).getText(a):o.getValueDeclaration()?.getType().getText()??"unknown";return Zs(l)}),s=r.getReturnType().getText(n);return`(${i.join(",")})=>${Zs(s)}`})}importUsageForDeclaration(t,n){let r=ge(this.db,t,n.getModuleSpecifierValue()),i=Qs(n);return n.getImportClause()?.isTypeOnly()?i.map(s=>qf(t,r,s)):i.map(s=>this.valueImportUsageForEntry(t,r,s))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],s=[];for(let c of i)for(let u of ng(c,t,r.identifier,this.db.config.projectRoot))s.push(u);let o=s.some(c=>!Xs(c.node)),a=s.some(c=>Xs(c.node)),l=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:l,isUsed:l||s.length>0,isTypeUsed:l||a,isValueUsed:o,references:s.map(c=>c.location)}}sourceFile(t){return this.sourceFileMatch(t)?.sourceFile??null}sourceFileMatch(t){return ug(t)?_e(this.sourceFileCache,t,()=>{let n=ue.join(this.db.config.projectRoot,t);for(let{project:r}of this.projects){let i=r.getSourceFile(n)??r.addSourceFileAtPathIfExists(n)??null;if(i)return{project:r,sourceFile:i}}return null}):null}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,Nr(i));return this.packageImportReferenceIndex=t,t}indexedTypeScriptLikeDocuments(){return this.db.all(`SELECT relative_path
|
|
367
|
+
${e.pathExclusionsFor("documents")}`).map(t=>ge(t.relative_path)).filter(t=>!e.isIgnored(t))))}function ge(e){return e.replace(/\\/g,"/")}var Nf=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function X(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let s=e[i];(s==="{"||s==="["||s==="(")&&n++,(s==="}"||s==="]"||s===")")&&n--,s===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function ne(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function B(e,t){let n=new Set,r=(i,s)=>{let o=s||t.has(i.type);!o&&Nf.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,o)};return r(e.rootNode,!1),n}function ye(e,t,n,r,i,s,o){return{importedName:i,localName:s,sourcePath:o??j(e,r,vr(t)),kind:"named",used:Y(n,s),usedMembers:[]}}function re(e,t,n){let r=[];for(let i of e.matchAll(t)){let s=i[0];if(!s||typeof i.index!="number")continue;let o=Te(e,i.index,i.index+s.length);for(let a of n(i,o))r.push(a)}return r}function to(e,t,n){let r=O(e,t);return r?Ef(e,t,r):jf(n).flatMap(i=>Bf(e,t,i.clause,i.specifier,i.start,i.end,n))}function Ef(e,t,n){let r=Df(e,t,n),i=[];for(let s of n.rootNode.descendantsOfType("import_statement"))i.push(...Lf(e,t,n,s,r));return i}function Df(e,t,n){let r=B(n,new Set(["import_statement"]));if(St(t))for(let i of Xf(e,t))r.add(i);return r}function Lf(e,t,n,r,i){let s=Tf(r);if(!s)return[];let o=he(e,t,s),a=ne(r,"import_clause");return a?wf(n,a,o,i,Ff(r.text)):[kf(o)]}function wf(e,t,n,r,i){let s=[];for(let o of t.namedChildren)if(o.type==="identifier")s.push(Pf(o.text,n,r,i));else if(o.type==="namespace_import"){let a=Of(e,o,n,r,i);a&&s.push(a)}else o.type==="named_imports"&&s.push(...Mf(o,n,r,i));return s}function kf(e){return{importedName:"*",localName:null,sourcePath:e,kind:"side-effect",used:!0,usedMembers:[]}}function Pf(e,t,n,r){return{importedName:"default",localName:e,sourcePath:t,kind:"default",used:n.has(e),usedMembers:[],isTypeOnly:r}}function Of(e,t,n,r,i){let o=ne(t,"identifier")?.text??"";if(!o)return null;let a=$f(e,o);return{importedName:"*",localName:o,sourcePath:n,kind:"namespace",used:a.length>0||r.has(o),usedMembers:a,isTypeOnly:i}}function Mf(e,t,n,r){let i=[];for(let s of e.namedChildren){if(s.type!=="import_specifier")continue;let o=s.namedChild(0),a=s.namedChild(1);if(!o)continue;let l=o.text,c=a?.text??l;i.push({importedName:l,localName:c,sourcePath:t,kind:"named",used:n.has(c),usedMembers:[],isTypeOnly:r||Af(s.text)})}return i}function Tf(e){let t=ne(e,"string");if(!t)return null;let n=ne(t,"string_fragment");return n?n.text:null}function Ff(e){return/^\s*import\s+type\b/.test(e)}function Af(e){return/^\s*type\b/.test(e.trim())}function $f(e,t){let n=new Set;for(let r of e.rootNode.descendantsOfType("member_expression")){let i=r.namedChild(0),s=r.namedChild(1);!i||!s||i.type!=="identifier"||i.text!==t||(s.type==="property_identifier"||s.type==="identifier")&&n.add(s.text)}return[...n]}function jf(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(n)){let s=i[0],o=i[1],a=i[2];!s||!a||typeof i.index!="number"||t.push({clause:o,specifier:a,start:i.index,end:i.index+s.length})}let r=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(r)){let s=i[0],o=i[1];!s||!o||typeof i.index!="number"||t.push({clause:null,specifier:o,start:i.index,end:i.index+s.length})}return t.sort((i,s)=>i.start-s.start)}function Bf(e,t,n,r,i,s,o){let a=he(e,t,r),l=Te(o,i,s);return n?Hf(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=lt(l,u.localName);return{...u,used:d.length>0||Y(l,u.localName),usedMembers:d}}return u.kind==="side-effect"?{...u,used:!0,usedMembers:[]}:{...u,used:u.localName?Y(l,u.localName):!1,usedMembers:[]}}):[{importedName:"*",localName:null,sourcePath:a,kind:"side-effect",used:!0,usedMembers:[]}]}function Hf(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,s]=Wf(r),o=[];return i&&o.push(...eo(i,n)),s&&o.push(...eo(s,n)),o}function eo(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?X(r).map(i=>{let s=i.trim(),o=t||/^type\b/.test(s),a=s.replace(/^type\s+/,""),[l,c]=a.split(/\s+as\s+/);return{importedName:l.trim(),localName:(c??l).trim(),kind:"named",isTypeOnly:o}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function Wf(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="{"&&t++,r==="}"&&t--,r===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function no(e,t){let n=O(e,t);if(n)return Gf(e,t,n);let r=P(e,t);return r?Uf(e,t,r):[]}function Uf(e,t,n){return[...Vf(e,t,n),...Jf(e,t,n),...qf(e,t,n)]}function Vf(e,t,n){let r=[],i=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let s of n.matchAll(i)){if(typeof s.index!="number")continue;let o=s[1]??"",a=s[2]??"",l=X(o).map(d=>zf(d.trim())).filter(d=>!!d),c=dt(n,s.index),u=dt(n,s.index+s[0].length-1);r.push({kind:"named",sourcePath:he(e,t,a),names:l,startLine:c,endLine:u})}return r}function Jf(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let s of n.matchAll(i)){if(typeof s.index!="number")continue;let o=s[2]??"",a=dt(n,s.index),l=dt(n,s.index+s[0].length-1);r.push({kind:"star-as",sourcePath:he(e,t,o),names:[],startLine:a,endLine:l})}return r}function qf(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let s of n.matchAll(i)){if(typeof s.index!="number")continue;let o=s[1]??"",a=dt(n,s.index),l=dt(n,s.index+s[0].length-1);r.push({kind:"star",sourcePath:he(e,t,o),names:[],startLine:a,endLine:l})}return r}function zf(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let r=t.match(/^(\w+)$/);return r?r[1]??null:null}function dt(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Gf(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let s=Kf(e,t,i);if(s===void 0)continue;let o=i.startPosition.row,a=i.endPosition.row,l=Yf(i,s,o,a);r.push(l)}return r}function Kf(e,t,n){let r=ne(n,"string");if(!r)return;let i=ne(r,"string_fragment");if(i)return he(e,t,i.text)}function Yf(e,t,n,r){let i=ne(e,"export_clause");if(i){let o=[];for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let l=a.namedChild(0),c=a.namedChild(1);l&&o.push((c??l).text)}return{kind:"named",sourcePath:t,names:o,startLine:n,endLine:r}}return ne(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}var Qf=A("vue-non-script-identifiers");function Xf(e,t){return Qf.get(e,t,()=>{let n=new Set,r=P(e,t);if(!r)return n;let s=r.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,o=>o.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,o=>o.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,o=>o.replace(/[^\r\n]/g," "));for(let o of s.matchAll(/[A-Za-z_$][\w$]*/g))n.add(o[0]);return n})}import{basename as ro}from"path";function io(e,t,n){let r=O(e,t);return r?Zf(e,t,r):re(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(i,s)=>{let o=i[1]?.trim();if(!o)return[];let a=ro(o).replace(/\.[^.]+$/,"");return[{importedName:o,localName:a,sourcePath:hn(e,t,o),kind:"named",used:Y(s,a),usedMembers:[]}]})}function Zf(e,t,n){let r=B(n,new Set(["preproc_include"])),i=[];for(let s of n.rootNode.descendantsOfType("preproc_include")){let o=null;for(let l of s.namedChildren){if(l.type==="system_lib_string"){o=l.text.replace(/^<|>$/g,"");break}if(l.type==="string_literal"){o=l.namedChildren.find(u=>u.type==="string_content")?.text??l.text.replace(/^"|"$/g,"");break}}if(!o)continue;let a=ro(o).replace(/\.[^.]+$/,"");i.push({importedName:o,localName:a,sourcePath:hn(e,t,o),kind:"named",used:r.has(a),usedMembers:[]})}return i}function so(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let s=i[1]?.trim(),o=i[2]?.trim()??null,a=i[0];if(!s||!a||typeof i.index!="number")continue;let l=Te(n,i.index,i.index+a.length);r.push({importedName:s,localName:o,sourcePath:yn(e,t,s),kind:o?"namespace":"side-effect",used:o?Y(l,o):!0,usedMembers:o?lt(l,o):[]})}return r}function oo(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let s=i[1]?.trim();s&&r.push({specifier:s,sourcePath:yn(e,t,s)})}return r}function ao(e,t,n){let r=O(e,t),i=T(t);if(r&&i==="csharp")return tg(e,t,r);if(r&&i==="vb")return eg(e,t,r);let s=Zs(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return re(n,s,(o,a)=>{let l=o[1]?.trim();if(!l)return[];let[c,u]=l.split(/\s*=\s*/),d=!!u,m=(d?u:c)?.trim()??l,f=m.split(".").pop()??m,h=d?c?.trim()??f:f;return[ye(e,t,a,m,f,h,j(e,m,ct))]})}function eg(e,t,n){let r=B(n,new Set(["imports_statement"])),i=[];for(let s of n.rootNode.descendantsOfType("imports_statement")){let o=s.namedChildren.filter(m=>m.type==="namespace_name");if(o.length===0)continue;let a=o[o.length-1],l=o.length>1?o[0]:null,c=a.text,u=c.split(".").pop()??c,d=l?.text??u;i.push({importedName:u,localName:d,sourcePath:j(e,c,ct),kind:l?"namespace":"named",used:r.has(d),usedMembers:[]})}return i}function tg(e,t,n){let r=B(n,new Set(["using_directive"])),i=[];for(let s of n.rootNode.descendantsOfType("using_directive")){let o=s.namedChildren;if(o.length===0)continue;let a=null,l;o.length>=2&&o[0].type==="identifier"&&(o[1].type==="qualified_name"||o[1].type==="identifier")?(a=o[0],l=o[1]):l=o[o.length-1];let c=l.text,u=c.split(".").pop()??c,d=a?.text??u;i.push({importedName:u,localName:d,sourcePath:j(e,c,ct),kind:a?"namespace":"named",used:r.has(d),usedMembers:[]})}return i}function lo(e,t,n){let r=O(e,t),i=T(t);return r&&i==="java"?ng(e,t,r):r&&i==="kotlin"?rg(e,t,r):r&&i==="scala"?ig(e,t,r):re(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(s,o)=>{let a=s[1]?.trim();return a?sg(e,t,a,o):[]})}function ng(e,t,n){let r=B(n,new Set(["import_declaration"])),i=[];for(let s of n.rootNode.descendantsOfType("import_declaration")){let o=s.children.some(d=>d.type==="asterisk"),l=s.namedChildren.find(d=>d.type==="scoped_identifier")??s.namedChildren.find(d=>d.type==="identifier");if(!l)continue;let c=l.text;if(o){i.push({importedName:"*",localName:null,sourcePath:j(e,c,ce),kind:"namespace",used:!0,usedMembers:[]});continue}let u=c.split(".").pop()??c;i.push({importedName:u,localName:u,sourcePath:j(e,c,ce),kind:"named",used:r.has(u),usedMembers:[]})}return i}function rg(e,t,n){let r=B(n,new Set(["import_header","import_list"])),i=[];for(let s of n.rootNode.descendantsOfType("import_header")){let o=s.namedChildren.find(f=>f.type==="identifier");if(!o)continue;let a=s.namedChildren.some(f=>f.type==="wildcard_import"),l=s.namedChildren.find(f=>f.type==="import_alias");if(a){i.push({importedName:"*",localName:null,sourcePath:j(e,o.text,ce),kind:"namespace",used:!0,usedMembers:[]});continue}let c=o.text,u=c.split(".").pop()??c,m=l?.namedChild(0)?.text??u;i.push({importedName:u,localName:m,sourcePath:j(e,c,ce),kind:"named",used:r.has(m),usedMembers:[]})}return i}function ig(e,t,n){let r=B(n,new Set(["import_declaration"])),i=[];for(let s of n.rootNode.descendantsOfType("import_declaration")){let o=s.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=s.namedChildren.filter(d=>d!==o&&(d.type==="identifier"||d.type==="stable_identifier")),l=a.map(d=>d.text).join(".");if(!l)continue;if(o?.type==="namespace_wildcard"){i.push({importedName:"*",localName:null,sourcePath:j(e,l,ce),kind:"namespace",used:!0,usedMembers:[]});continue}if(o?.type==="namespace_selectors"){for(let d of o.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,f]=d.namedChildren;if(!m)continue;let h=m.text,p=f?.text??h;if(h==="_")continue;i.push({importedName:h,localName:p,sourcePath:j(e,`${l}.${h}`,ce),kind:"named",used:r.has(p),usedMembers:[]})}else if(d.type==="identifier"){let m=d.text;i.push({importedName:m,localName:m,sourcePath:j(e,`${l}.${m}`,ce),kind:"named",used:r.has(m),usedMembers:[]})}continue}let c=a[a.length-1]?.text??l,u=a.slice(0,-1).map(d=>d.text).join(".")||l;i.push({importedName:c,localName:c,sourcePath:j(e,u&&a.length>1?`${u}.${c}`:l,ce),kind:"named",used:r.has(c),usedMembers:[]})}return i}function sg(e,t,n,r){if(n.includes("{")&&n.includes("}")){let i=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),s=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return X(s).flatMap(o=>{let a=o.trim();if(!a)return[];let[l,c]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=l?.trim();if(!u||u==="_")return[];let d=(c??u.split(".").pop()??u).trim(),m=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[ye(e,t,r,m,u,d)]})}return[ye(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function uo(e,t,n){let r=O(e,t);return r?og(e,t,r):re(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,s)=>{let o=i[1]?.trim();return o?X(o).flatMap(a=>{let l=a.trim();if(!l)return[];let[c,u]=l.split(/\s+as\s+/i),d=c?.trim()??l,m=d.split("\\").pop()??d,f=(u??m).trim();return[ye(e,t,s,d,m,f,j(e,d.replace(/\\/g,"."),Rt))]}):[]})}function og(e,t,n){let r=B(n,new Set(["namespace_use_declaration"])),i=[],s=(o,a,l)=>{i.push({importedName:a,localName:l,sourcePath:j(e,o.replace(/\\/g,"."),Rt),kind:"named",used:r.has(l),usedMembers:[]})};for(let o of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=o.namedChildren.find(l=>l.type==="namespace_use_group");if(a){let l=o.namedChildren.find(c=>c.type==="namespace_name")?.text??"";for(let c of a.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:u,localName:d,qualified:m}=co(c,l);u&&s(m,u,d)}continue}for(let l of o.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:c,localName:u,qualified:d}=co(l,"");c&&s(d,c,u)}}return i}function co(e,t){let n=e.namedChildren.find(c=>c.type==="qualified_name"),r=e.namedChildren.filter(c=>c.type==="name"),i="";n?i=n.text:r.length>=1&&(i=r[0].text);let s=n&&r.length>0?r[r.length-1]:null,o=i.split("\\").pop()??i,a=s?.text??o,l=t?`${t}\\${i}`:i;return{importedName:o,localName:a,qualified:l}}function fo(e,t,n){let r=O(e,t);return r?ag(e,t,r):cg(n).flatMap(i=>dg(e,t,i,n))}function ag(e,t,n){let r=B(n,new Set(["import_statement","import_from_statement"])),i=[];for(let s of n.rootNode.descendantsOfType("import_statement"))for(let o of s.namedChildren){let a=mo(o);if(!a)continue;let l=ut(e,t,a.qualifiedName);i.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:l,kind:"namespace",used:r.has(a.localName),usedMembers:[]})}for(let s of n.rootNode.descendantsOfType("import_from_statement")){let o=s.namedChild(0);if(!o)continue;let a=lg(o);if(a===null)continue;let l=ut(e,t,a);for(let c=1;c<s.namedChildCount;c+=1){let u=s.namedChild(c);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:l,kind:"side-effect",used:!0,usedMembers:[]});continue}let d=mo(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:l,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function mo(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function lg(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=ne(e,"import_prefix")?.text??"",n=ne(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function cg(e){let t=e.split(`
|
|
368
|
+
`),n=[],r=0;for(let i=0;i<t.length;i++){let s=t[i],o=s.trimStart(),a=r;if(r+=s.length+1,!o.startsWith("import ")&&!o.startsWith("from "))continue;let l=s,c=a+s.length,u=po(s);for(;i+1<t.length&&(u>0||l.trimEnd().endsWith("\\"));){i++;let m=t[i];l+=`
|
|
369
|
+
${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,end:c})}return n}function ug(e){let t=e.replace(/\\\s*\n/g," ").trim();if(t.startsWith("import "))return{kind:"import",module:null,clause:t.slice(7).trim()};let n=t.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);if(!n)return null;let r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function dg(e,t,n,r){let i=Te(r,n.start,n.end),s=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return X(s).flatMap(l=>{let c=l.trim().replace(/,$/,"");if(!c)return[];let[u,d]=c.split(/\s+as\s+/),m=u.trim(),f=(d??m.split(".")[0]??m).trim(),h=ut(e,t,m),p=lt(i,f);return[{importedName:m,localName:f,sourcePath:h,kind:"namespace",used:Y(i,f)||p.length>0,usedMembers:p}]});let o=n.module?ut(e,t,n.module):null,a=[];for(let l of X(s)){let c=l.trim().replace(/,$/,"");if(!c)continue;if(c==="*"){a.push({importedName:"*",localName:null,sourcePath:o,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=c.split(/\s+as\s+/),m=(d??u).trim();a.push({importedName:u.trim(),localName:m,sourcePath:o,kind:"named",used:Y(i,m),usedMembers:[]})}return a}function po(e){let t=0;for(let n of e)n==="("&&t++,n===")"&&t--;return t}import{basename as mg}from"path";function go(e,t,n){let r=O(e,t);return r?pg(e,t,r):re(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(i,s)=>{let o=i[1],a=i[2];if(!o||!a)return[];let l=o==="require_relative"?gn(e,t,a):null;if(l){let c=ho(a);return[{importedName:c,localName:c,sourcePath:l,kind:"named",used:Y(s,c),usedMembers:[]}]}return[{importedName:a,localName:null,sourcePath:l,kind:"side-effect",used:!0,usedMembers:[]}]})}function pg(e,t,n){let r=B(n,new Set([])),i=[],s=new Set(["require","require_relative","load"]);for(let o of n.rootNode.descendantsOfType("call")){let a=o.namedChild(0);if(!a||a.type!=="identifier"||!s.has(a.text))continue;let c=o.namedChildren.find(f=>f.type==="argument_list")?.namedChild(0);if(!c||c.type!=="string")continue;let d=c.namedChildren.find(f=>f.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?gn(e,t,d):null;if(m){let f=ho(d);i.push({importedName:f,localName:f,sourcePath:m,kind:"named",used:r.has(f),usedMembers:[]})}else i.push({importedName:d,localName:null,sourcePath:m,kind:"side-effect",used:!0,usedMembers:[]})}return i}function ho(e){return mg(e).replace(/\.[^.]+$/,"").split("_").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function yo(e,t,n){let r=O(e,t);return r?fg(e,t,r):re(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,s)=>{let o=i[1]?.trim();return o?gg(e,t,o,s):[]})}function fg(e,t,n){let r=B(n,new Set(["use_declaration"])),i=[];for(let s of n.rootNode.descendantsOfType("use_declaration")){let o=s.namedChild(0);if(o)for(let a of vt(o,"")){if(!a.importedName||a.importedName==="*")continue;let l=Ie(e,t,a.qualifiedName)??Ie(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push({importedName:a.importedName,localName:a.localName,sourcePath:l,kind:"named",used:r.has(a.localName),usedMembers:[]})}}return i}function vt(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:bn(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:bn(t,n),importedName:r,localName:r}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=bn(t,n.text),s=[];for(let o of r.namedChildren)s.push(...vt(o,i));return s}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...vt(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=vt(n,t),s=r.text;return i.map(o=>({...o,localName:s}))}case"use_wildcard":{let n=e.namedChild(0),r=n?n.text:"";return[{qualifiedName:bn(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function bn(e,t){return e?t?`${e}::${t}`:e:t}function gg(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),d=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return X(d).flatMap(m=>{let f=m.trim();if(!f||f==="self")return[];let[h,p]=f.split(/\s+as\s+/),y=h?.trim();if(!y)return[];let _=(p??y.split("::").pop()??y).trim(),E=`${u}::${y}`.replace(/::::/g,"::");return[ye(e,t,r,E,y.split("::").pop()??y,_,Ie(e,t,u))]})}let[s,o]=i.split(/\s+as\s+/),a=s?.trim()??i,l=(o??a.split("::").pop()??a).trim(),c=Ie(e,t,a)??Ie(e,t,a.split("::").slice(0,-1).join("::"));return[ye(e,t,r,a,a.split("::").pop()??a,l,c)]}function bo(e,t,n){let r=O(e,t);if(r)return hg(e,t,r);let i=[];for(let s of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let o=s[1]?.trim();o&&i.push(...bg(e,t,o))}return i}function hg(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!yg(i))continue;let s=i.namedChildren.find(o=>o.type!=="visibility_modifier");if(s)for(let o of vt(s,""))o.importedName&&r.push(Er(e,t,o.qualifiedName))}return r}function yg(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function bg(e,t,n){let r=n.trim();if(r.includes("{")&&r.includes("}")){let i=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),s=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return X(s).flatMap(o=>{let a=o.trim();if(!a||a==="self")return[];let[l]=a.split(/\s+as\s+/),c=`${i}::${l?.trim()??a}`.replace(/::::/g,"::");return[Er(e,t,c)]})}return[Er(e,t,r)]}function Er(e,t,n){return{specifier:n,sourcePath:Ie(e,t,n)??Ie(e,t,n.split("::").slice(0,-1).join("::"))}}function So(e,t){let n=t.toLowerCase();for(let r of e)for(let i of r.extensions)if(n.endsWith(i))return r;return null}var Sg={language:"javascript",extensions:[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],parseImports:to},xg={language:"python",extensions:[".py",".pyi"],parseImports:fo},_g={language:"jvm",extensions:[".java",".scala",".kt",".kts"],parseImports:lo},Ig={language:"rust",extensions:[".rs"],parseImports:yo,parseExports:bo},Rg={language:"ruby",extensions:[".rb"],parseImports:go},Cg={language:"c/cpp",extensions:[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],parseImports:io},vg={language:"dotnet",extensions:[".cs",".vb"],parseImports:ao},Ng={language:"dart",extensions:[".dart"],parseImports:so,parseExports:oo},Eg={language:"php",extensions:[".php"],parseImports:uo},Dg=[Sg,xg,_g,Ig,Rg,Cg,vg,Ng,Eg];function Dr(e){return So(Dg,e)}function xo(e,t){return no(e,t)}var _o=A("source-imports"),Io=A("source-exports");function J(e,t){let n=ge(t);return _o.get(e,n,()=>{let r=Dr(n);if(!r)return[];let i=P(e,n);return i?r.parseImports(e,n,i):[]})}function Lr(e,t){let n=ge(t);return Io.get(e,n,()=>{let r=Dr(n);if(!r?.parseExports)return[];let i=P(e,n);return i?r.parseExports(e,n,i):[]})}function Ro(e){_o.invalidateAll(e),Io.invalidateAll(e)}import ue from"path";import{createRequire as Lg}from"module";import{existsSync as Sn,readdirSync as wg,readFileSync as Eo}from"fs";var kg=Lg(import.meta.url),Nt;function Do(e,t){let n=Pg();if(!n)return wr("ts-morph is not installed");let r=zi(e);if(r.length===0)return wr("no tsconfig found");try{let i=r.map(s=>({tsconfigPath:s,project:new n.Project({tsConfigFilePath:s,skipFileDependencyResolution:!1})}));return new kr(e,n,i)}catch(i){return wr(i instanceof Error?i.message:String(i),r[0],r)}}function Pg(){if(Nt!==void 0)return Nt;try{Nt=kg("ts-morph")}catch{Nt=null}return Nt}function wr(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}var kr=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Ag(t.config.projectRoot)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;sourceFileCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return Re(this.importUsageCache,t,()=>{let n=this.sourceFile(t);if(!n)return[];let r=[];for(let i of n.getImportDeclarations())for(let s of this.importUsageForDeclaration(t,i))r.push(s);return r})}referencesFor(t){return Re(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?Vg(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return Re(this.calleesCache,t.symbolId,()=>Re(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return Re(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(o=>{let a=o.getDeclarations()[0],l=a?o.getTypeAtLocation(a).getText(a):o.getValueDeclaration()?.getType().getText()??"unknown";return No(l)}),s=r.getReturnType().getText(n);return`(${i.join(",")})=>${No(s)}`})}importUsageForDeclaration(t,n){let r=he(this.db,t,n.getModuleSpecifierValue()),i=Co(n);return n.getImportClause()?.isTypeOnly()?i.map(s=>Tg(t,r,s)):i.map(s=>this.valueImportUsageForEntry(t,r,s))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],s=[];for(let c of i)for(let u of Jg(c,t,r.identifier,this.db.config.projectRoot))s.push(u);let o=s.some(c=>!vo(c.node)),a=s.some(c=>vo(c.node)),l=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:l,isUsed:l||s.length>0,isTypeUsed:l||a,isValueUsed:o,references:s.map(c=>c.location)}}sourceFile(t){return this.sourceFileMatch(t)?.sourceFile??null}sourceFileMatch(t){return Zg(t)?Re(this.sourceFileCache,t,()=>{let n=ue.join(this.db.config.projectRoot,t);for(let{project:r}of this.projects){let i=r.getSourceFile(n)??r.addSourceFileAtPathIfExists(n)??null;if(i)return{project:r,sourceFile:i}}return null}):null}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,Pr(i));return this.packageImportReferenceIndex=t,t}indexedTypeScriptLikeDocuments(){return this.db.all(`SELECT relative_path
|
|
370
370
|
FROM documents
|
|
371
371
|
WHERE (
|
|
372
372
|
relative_path LIKE '%.ts'
|
|
@@ -378,8 +378,8 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
378
378
|
OR relative_path LIKE '%.mjs'
|
|
379
379
|
OR relative_path LIKE '%.cjs'
|
|
380
380
|
)
|
|
381
|
-
${this.db.pathExclusionsFor("documents")}`).map(t=>t.relative_path)}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFileMatch(r);if(i)for(let s of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,s)}addPackageImportReferencesForDeclaration(t,n,r,i){let s=
|
|
382
|
-
`),l=[];for(let c=0;c<a.length;c++){if(c===i)continue;let u=a[c]??"";o.lastIndex=0;let d;for(;(d=o.exec(u))!==null;)l.push({file:t,line:c,column:d.index})}return
|
|
381
|
+
${this.db.pathExclusionsFor("documents")}`).map(t=>t.relative_path)}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFileMatch(r);if(i)for(let s of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,s)}addPackageImportReferencesForDeclaration(t,n,r,i){let s=Bg(this.workspacePackages,i.getModuleSpecifierValue());if(!s)return;let o=n.get(s);if(o)for(let a of Co(i)){if(a.kind!=="named"||!a.identifier)continue;let l=o.get(a.importedName);if(!l||l.size===0)continue;let c=qg(a.identifier,r,this.db.config.projectRoot);c.length>0&&Qg(t,l,c)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let r=new Map;for(let i of Hg(n))this.collectPackageExports(n,i,r,new Set);r.size>0&&t.set(n.name,r)}return this.packageExportIndex=t,t}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let s=this.sourceFile(n);if(s)for(let o of s.getExportDeclarations()){let a=o.getModuleSpecifierValue(),l=a?he(this.db,n,a):n;if(!l||!l.startsWith(`${t.sourceRootRelative}/`))continue;let c=o.getNamedExports();if(c.length===0){if(o.isNamespaceExport())continue;this.collectPackageExports(t,l,r,i);continue}for(let u of c){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,f=this.indexedDefinitionByLeaf(l,d);if(!f)continue;let h=r.get(m);h||(h=new Set,r.set(m,h)),h.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return Re(this.indexedDefinitionLeafCache,t,()=>Kg(this.db,t)).get(n)??null}nodeForDefinition(t){return Re(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Re(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFile(t);if(!n)return new Map;let r=Og(this.db,t);return r.size===0?new Map:Mg(this.tsMorph,n,r)})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),s=_n(this.db.config.projectRoot,i.getFilePath());if(!s||this.db.isIgnored(s))continue;let o=xn(i,r),a=Gg(this.db,s,o,t.getName());if(a)return{symbol:a.symbol,file:a.relativePath,line:a.startLine}}return null}calleeMapForFile(t){let n=this.sourceFile(t);if(!n)return new Map;let r=z(this.db,t).sort((s,o)=>s.startLine-o.startLine||o.endLine-s.endLine);if(r.length===0)return new Map;let i=new Map;n.forEachDescendant(s=>{if(!this.tsMorph.Node.isCallExpression(s)&&!this.tsMorph.Node.isNewExpression(s))return;let o=this.semanticCalleeForCallNode(n,r,s);o&&Fg(i,o.callerId,o.target)});for(let[s,o]of i)i.set(s,Xg(o));return i}semanticCalleeForCallNode(t,n,r){let i=Yg(n,xn(t,r));if(!i)return null;let s=r.getExpression(),o=s.getSymbol()??s.getType().getSymbol(),a=o?this.definitionFromSymbol(o):null;return a?{callerId:i.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function Co(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let s=i.getNameNode(),a=i.getAliasNode()??(s.getKindName()==="Identifier"?s:null);t.push({identifier:a,importedName:s.getText(),localName:a?.getText()??s.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function Og(e,t){let n=new Map;for(let r of z(e,t)){let i=w(r.symbol)??r.leaf;if(!i)continue;let s=n.get(i);s||(s=[],n.set(i,s)),s.push(r)}return n}function Mg(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(s=>{for(let o of zg(e,s)){let a=n.get(o);if(!a)continue;let l=xn(t,s);for(let c of a){if(l<c.startLine-1||l>c.endLine+1)continue;let u=Math.abs(l-c.startLine),d=i.get(c.symbolId);d!==void 0&&d<=u||(i.set(c.symbolId,u),r.set(c.symbolId,s))}}}),r}function Tg(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function Fg(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function Ag(e){let t=ue.join(e,"package.json");if(!Sn(t))return[];let n;try{n=JSON.parse(Eo(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>$g(e,i)).flatMap(i=>jg(e,i))}function $g(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let o=ue.join(e,t);return Sn(ue.join(o,"package.json"))?[o]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),s=ue.join(e,r||".");if(!Sn(s))return[];try{return wg(s).map(o=>ue.join(s,o,i)).filter(o=>Sn(ue.join(o,"package.json")))}catch{return[]}}function jg(e,t){try{let n=JSON.parse(Eo(ue.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=ue.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function Bg(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Hg(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}function Wg(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Lo(r,t)})}function Ug(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Vg(e,t,n,r){let i=[];for(let s of Ug(e))for(let o of Wg(s,r))o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||i.push(o);for(let s of n)i.push(s);return Pr(i)}function Jg(e,t,n,r){let i=[],s=n?.getStart();for(let o of e.getReferences()){let a=o.getNode();_n(r,a.getSourceFile().getFilePath())===t&&(s!==void 0&&a.getStart()===s||i.push({location:Lo(a,r),node:a}))}return i}function Lo(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:_n(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function qg(e,t,n){let r=e.getSourceFile(),i=xn(r,e),s=e.getText(),o=new RegExp(`\\b${eh(s)}\\b`,"g"),a=r.getFullText().split(`
|
|
382
|
+
`),l=[];for(let c=0;c<a.length;c++){if(c===i)continue;let u=a[c]??"";o.lastIndex=0;let d;for(;(d=o.exec(u))!==null;)l.push({file:t,line:c,column:d.index})}return Pr(l.filter(c=>_n(n,ue.join(n,c.file))===t))}function vo(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function zg(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}function Gg(e,t,n,r){return e.all(`SELECT
|
|
383
383
|
gs.id AS symbolId,
|
|
384
384
|
gs.symbol,
|
|
385
385
|
d.relative_path AS relativePath,
|
|
@@ -399,7 +399,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
399
399
|
WHERE d.relative_path = ?
|
|
400
400
|
AND COALESCE(gs.display_name, gs.symbol) LIKE ?
|
|
401
401
|
ORDER BY ABS(COALESCE(der.start_line, c.start_line) - ?)
|
|
402
|
-
LIMIT 5`,t,`%${r}%`,n)[0]??null}function
|
|
402
|
+
LIMIT 5`,t,`%${r}%`,n)[0]??null}function Kg(e,t){let n=e.all(`SELECT
|
|
403
403
|
d.id AS documentId,
|
|
404
404
|
gs.id AS symbolId,
|
|
405
405
|
gs.symbol,
|
|
@@ -439,7 +439,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
439
439
|
WHERE d.relative_path = ?
|
|
440
440
|
AND m.role = 1
|
|
441
441
|
GROUP BY gs.id, gs.symbol, d.id, d.relative_path, gs.display_name, gs.kind, gs.documentation, gs.enclosing_symbol
|
|
442
|
-
ORDER BY startLine, endLine`,t,t),r=new Set,i=new Map;for(let s of n){if(r.has(s.symbolId))continue;r.add(s.symbolId);let o=s.leaf||
|
|
442
|
+
ORDER BY startLine, endLine`,t,t),r=new Set,i=new Map;for(let s of n){if(r.has(s.symbolId))continue;r.add(s.symbolId);let o=s.leaf||w(s.symbol);!o||i.has(o)||i.set(o,{...s,leaf:o})}return i}function Yg(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function xn(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Pr(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function Qg(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function Xg(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}`;t.has(i)||(t.add(i),n.push(r))}return n}function Re(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}function _n(e,t){let n=ue.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function Zg(e){return/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(e)}function No(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}function eh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Or=new WeakMap;function Mr(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=Or.get(e);r||(r=new Map,Or.set(e,r));let i=r.get(n);if(i)return i;let s=Do(e,t);return r.set(n,s),s}function Tr(e){Or.delete(e)}function Et(e,t){let n=In(e,t);return n?n.importUsage(t):[]}function Dt(e,t){let n=In(e,t.relativePath);return n?n.referencesFor(t):[]}function mt(e,t){let n=new Map;for(let r of t)for(let i of Dt(e,r)){if(i.file===r.relativePath||e.isIgnored(i.file))continue;let s=n.get(r.symbolId);s||(s=new Set,n.set(r.symbolId,s)),s.add(i.file)}return n}function wo(e,t){let n=new Map;for(let r of t){let i=In(e,r.relativePath);if(!i)continue;let s=i.calleesFor(r);s.length>0&&n.set(r.symbolId,s)}return n}function ko(e,t){let n=In(e,t.relativePath);return n?n.signatureFor(t):null}function In(e,t){if(!th(t))return null;let n=Mr(e,t);return n.availability().available?n:null}function th(e){return/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(e)}var To=A("file-dep-graph");function Fo(e){To.invalidateAll(e),Ao.invalidate(e),Bo.invalidate(e)}function Q(e,t){return To.get(e,t??"",()=>{let n=new Map,r=rh(e),i=(s,o)=>ih(e,n,r,s,o);for(let s of nh(e,t))i(s.from_file,s.to_file);for(let s of r)if(!(t&&!s.includes(t)))for(let o of J(e,s))o.sourcePath&&i(s,o.sourcePath);return n})}function nh(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
|
|
443
443
|
d1.relative_path AS from_file,
|
|
444
444
|
d2.relative_path AS to_file
|
|
445
445
|
FROM mentions m
|
|
@@ -457,11 +457,11 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
457
457
|
WHERE d1.id != d2.id
|
|
458
458
|
AND m.role != 1
|
|
459
459
|
${e.pathExclusionsFor("d1","d2")}
|
|
460
|
-
${n}`)}function
|
|
460
|
+
${n}`)}function rh(e){return new Set(e.all(`SELECT relative_path
|
|
461
461
|
FROM documents
|
|
462
462
|
WHERE 1 = 1
|
|
463
463
|
${e.pathExclusionsFor("documents")}
|
|
464
|
-
ORDER BY relative_path`).map(t=>t.relative_path).filter(t=>!e.isIgnored(t)))}function
|
|
464
|
+
ORDER BY relative_path`).map(t=>t.relative_path).filter(t=>!e.isIgnored(t)))}function ih(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let s=t.get(r);s||(s=new Set,t.set(r,s)),s.add(i)}function Z(e,t,n={}){let r=Rn(e,[t],{additive:n.additive}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(s=>V(s.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function ie(e,t,n={}){let r=oh(e)?lh(e,t):ah(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var Ao=Be("caller-rows"),sh=2e4;function oh(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>sh}function ah(e){return Ao.get(e,()=>{let t=oe(e),n=Rn(e,t),r=new Map;for(let o of t)r.set(o.symbol,o.symbolId);let i=new Map,s=new Map;for(let o of t){let a=n.get(o.symbolId);if(!(!a||a.length===0))for(let l of a){let c=r.get(l.symbol);if(c===void 0||c===o.symbolId)continue;let u=i.get(c);u||(u=[],i.set(c,u),s.set(c,new Set));let d=`${o.symbol}|${o.relativePath}`;s.get(c).has(d)||(s.get(c).add(d),u.push({symbol:o.symbol,file:o.relativePath}))}}return i})}function lh(e,t){let n=[],r=new Set,i=o=>{if(o.symbol===t.symbol)return;let a=`${o.symbol}|${o.file}`;r.has(a)||(r.add(a),n.push(o))};for(let o of Ce(e,t))o.file!==t.relativePath&&i({symbol:o.enclosingSymbol??o.file,file:o.file});let s=ch(e,t);if(s)for(let o of Dt(e,s)){if(o.file===t.relativePath||e.isIgnored(o.file))continue;let a=ae(z(e,o.file),o.line);i({symbol:a?.symbol??o.file,file:o.file})}return n}function ch(e,t){return e.get(`SELECT
|
|
465
465
|
d.id AS documentId,
|
|
466
466
|
gs.id AS symbolId,
|
|
467
467
|
gs.symbol,
|
|
@@ -480,14 +480,14 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
480
480
|
LEFT JOIN chunks c ON c.document_id = der.document_id
|
|
481
481
|
JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
|
|
482
482
|
WHERE gs.id = ?
|
|
483
|
-
LIMIT 1`,t.symbolId)??null}function
|
|
483
|
+
LIMIT 1`,t.symbolId)??null}function Ce(e,t){let n=fh(e,t);return n?gh(e,uh(e,n.match,n.identifier)):[]}function uh(e,t,n){let r=new Map;for(let[i,s]of dh(e,t.symbolId))r.set(i,mh(e,i,s,t,n));return r}function dh(e,t){let n=new Map,r=e.all(`SELECT DISTINCT d.relative_path, c.start_line, c.end_line
|
|
484
484
|
FROM mentions m
|
|
485
485
|
JOIN chunks c ON m.chunk_id = c.id
|
|
486
486
|
JOIN documents d ON c.document_id = d.id
|
|
487
487
|
WHERE m.symbol_id = ?
|
|
488
488
|
AND m.role != 1
|
|
489
489
|
${e.pathExclusionsFor("d")}
|
|
490
|
-
ORDER BY d.relative_path, c.start_line`,t);for(let i of r){if(e.isIgnored(i.relative_path))continue;let s=n.get(i.relative_path);s||(s=[],n.set(i.relative_path,s)),s.push({start_line:i.start_line,end_line:i.end_line})}return n}function
|
|
490
|
+
ORDER BY d.relative_path, c.start_line`,t);for(let i of r){if(e.isIgnored(i.relative_path))continue;let s=n.get(i.relative_path);s||(s=[],n.set(i.relative_path,s)),s.push({start_line:i.start_line,end_line:i.end_line})}return n}function mh(e,t,n,r,i){let s=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},o=i?pn(e,t,i,s):[];return n.flatMap(a=>ph(o,a))}function ph(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function fh(e,t){let n=cn(e,t);return n?{match:n,identifier:w(n.symbol)||null}:null}function gh(e,t){let n=[],r=new Set;for(let[i,s]of t){let o=z(e,i);for(let a of s){let l=ae(o,a),c=`${i}|${a}|${l?.symbol??""}`;r.has(c)||(r.add(c),n.push({file:i,line:a,enclosingSymbol:l?.symbol??null}))}}return n}function Rn(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],s=[];for(let u of t)T(u.relativePath)&&sn(e,u.relativePath)!==null?i.push(u):s.push(u);let o=new Map,a=new Map,l=u=>{for(let[d,m]of u){let f=o.get(d);f||(f=[],o.set(d,f));let h=a.get(d);h||(h=new Set,a.set(d,h));for(let p of m){let y=`${p.symbol}|${p.chunkId}`;h.has(y)||(h.add(y),f.push(p))}}};i.length>0&&l(hh(e,i)),l(Lh(wo(e,t)));let c=r?t:s;return c.length>0&&l(_h(e,c)),o}function hh(e,t){let n=new Map,r=yh(t,n),i=Lt(e);for(let[s,o]of r){let a=sn(e,s);if(a)for(let l of a){let c=bh(o,l.line);if(!c)continue;let u=Sh(e,s,i,l.calleeLeaf,l.memberAccess);u&&u.symbol!==c.symbol&&n.get(c.symbolId).push({symbol:u.symbol,file:u.file,chunkId:l.line})}}return n}function yh(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,s)=>i.endLine-i.startLine-(s.endLine-s.startLine));return n}function bh(e,t){return e.find(n=>t>=n.startLine&&t<=n.endLine)??null}function Sh(e,t,n,r,i){let s=$o(t,n.get(r)??[]);return s.length===0?null:jo(e,t,s,i)}function $o(e,t){let n=Po(e);return n?t.filter(r=>Po(r.file)===n):t}function jo(e,t,n,r){let i=n.find(s=>s.file===t);if(i)return i;if(r){let s=new Set(J(e,t).map(o=>o.sourcePath).filter(o=>!!o));for(let o of n)for(let a of s)if(xh(a,o.file))return o;return null}return n.length===1?n[0]:null}function xh(e,t){let n=r=>r.replace(/\\/g,"/").replace(/^\.\//,"");return n(e)===n(t)}function Po(e){let t=T(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var Bo=Be("global-leaf-index");function Lt(e){return Bo.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
|
|
491
491
|
COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
|
|
492
492
|
FROM global_symbols gs
|
|
493
493
|
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
@@ -501,7 +501,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
501
501
|
GROUP BY m.symbol_id
|
|
502
502
|
) mention_doc ON mention_doc.symbol_id = gs.id
|
|
503
503
|
WHERE 1 = 1
|
|
504
|
-
${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=
|
|
504
|
+
${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=w(r.symbol);if(!i)continue;let s=n.get(i);s||(s=[],n.set(i,s)),s.some(o=>o.symbolId===r.id)||s.push({symbol:r.symbol,symbolId:r.id,file:r.relative_path})}return n})}function _h(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
|
|
505
505
|
FROM mentions m
|
|
506
506
|
JOIN chunks c ON m.chunk_id = c.id
|
|
507
507
|
WHERE m.role != 1`),r=new Map;for(let c of n)r.has(c.document_id)||r.set(c.document_id,[]),r.get(c.document_id).push(c);let i=new Map(e.all("SELECT id, relative_path FROM documents").map(c=>[c.id,c.relative_path])),s=new Map,o=e.all(`SELECT gs.id AS symbol_id, gs.symbol,
|
|
@@ -514,21 +514,22 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
514
514
|
JOIN chunks c ON m.chunk_id = c.id
|
|
515
515
|
WHERE m.role = 1
|
|
516
516
|
GROUP BY m.symbol_id
|
|
517
|
-
) def_chunk ON def_chunk.symbol_id = gs.id`);for(let c of o)s.has(c.symbol_id)||s.set(c.symbol_id,{symbol:c.symbol,file:c.document_id!==null?i.get(c.document_id)??"":""});let a=new Map,l=i;for(let c of t){let u=r.get(c.documentId)??[],d=new Set,m=[],
|
|
518
|
-
WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`),i=
|
|
517
|
+
) def_chunk ON def_chunk.symbol_id = gs.id`);for(let c of o)s.has(c.symbol_id)||s.set(c.symbol_id,{symbol:c.symbol,file:c.document_id!==null?i.get(c.document_id)??"":""});let a=new Map,l=i;for(let c of t){let u=r.get(c.documentId)??[],d=new Set,m=[],f=null,h=()=>{if(f)return f;let p=l.get(c.documentId)??"",y=new Set;if(p){let _=Ws(e,p),E=Math.max(0,c.startLine),F=Math.min(_.length-1,c.endLine);for(let M=E;M<=F;M+=1)for(let C of _[M])y.add(C)}return f=y,y};for(let p of u){if(p.symbol_id===c.symbolId)continue;let y=s.get(p.symbol_id);if(!y)continue;if(!(p.start_line>=c.startLine&&p.end_line<=c.endLine)){if(!(p.start_line<=c.endLine&&p.end_line>=c.startLine))continue;let M=w(y.symbol);if(!M||!h().has(M))continue}let E=`${y.symbol}|${p.chunk_id}`;d.has(E)||(d.add(E),m.push({...y,chunkId:p.chunk_id}))}a.set(c.symbolId,m)}return a}function Ho(e,t){let n=new Map;if(t&&t.length===0)return n;let r=e.all(`SELECT relative_path FROM documents
|
|
518
|
+
WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`),i=Lt(e),s=t??oe(e),o=new Set(s.map(a=>a.symbolId));return Ih(e,n,r,i,o),Rh(e,n,s,o),Eh(e,n,r,i,o),wh(n,mt(e,Dh(s))),n}function Ih(e,t,n,r,i){for(let s of n){if(!T(s.relative_path)||e.isIgnored(s.relative_path))continue;let o=sn(e,s.relative_path);if(o)for(let a of o){let l=$o(s.relative_path,r.get(a.calleeLeaf)??[]);if(!l||l.length===0)continue;let c=jo(e,s.relative_path,l,a.memberAccess);c&&i.has(c.symbolId)&&c.file!==s.relative_path&&Fr(t,c.symbolId,s.relative_path)}}}function Rh(e,t,n,r){let i=vh(n);for(let s of Ch(e,r))e.isIgnored(s.relative_path)||Nh(s,i.get(s.symbol_id))||Fr(t,s.symbol_id,s.relative_path)}function Ch(e,t){if(!t)return Mo(e);let n=[...t];if(n.length===0)return[];let r=[];for(let i=0;i<n.length;i+=Oo)r.push(...Mo(e,n.slice(i,i+Oo)));return r}var Oo=750;function Mo(e,t){let n=t&&t.length>0?`AND m.symbol_id IN (${t.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
|
|
519
519
|
c.start_line AS chunk_start, c.end_line AS chunk_end
|
|
520
520
|
FROM mentions m
|
|
521
521
|
JOIN chunks c ON m.chunk_id = c.id
|
|
522
522
|
JOIN documents d ON c.document_id = d.id
|
|
523
523
|
WHERE m.role != 1
|
|
524
|
-
${
|
|
524
|
+
${n}
|
|
525
|
+
${e.pathExclusionsFor("d")}`,...t??[])}function vh(e){let t=new Map;for(let n of e)t.set(n.symbolId,{docId:n.documentId,startLine:n.startLine,endLine:n.endLine});return t}function Nh(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function Eh(e,t,n,r,i){for(let s of n){if(e.isIgnored(s.relative_path)||T(s.relative_path)!=="rust")continue;let o=at(e,s.relative_path);if(o.size!==0)for(let a of o){let l=r.get(a);if(l)for(let c of l)i.has(c.symbolId)&&c.file!==s.relative_path&&Fr(t,c.symbolId,s.relative_path)}}}function Fr(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Dh(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function Lh(e){let t=new Map;for(let[n,r]of e){let i=[];for(let s of r)i.push({symbol:s.symbol,file:s.file,chunkId:-1});t.set(n,i)}return t}function wh(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let s of r)i.add(s)}}function ee(e){let t=wt(e);return Ph(t)?"test":Oh(t)?"worker":Mh(t)?"entry":Th(t)?"barrel":"source"}function Cn(e){return ee(e)==="barrel"}function Uo(e){return kh.get(e,()=>{let t=Q(e),n=Le(e).filter(s=>{let o=ee(s);return o==="entry"||o==="worker"}),r=new Set,i=new Set;for(;n.length>0;){let s=n.shift();if(!r.has(s)){r.add(s),ee(s)==="barrel"&&i.add(s);for(let o of t.get(s)??[])r.has(o)||n.push(o)}}return i})}var kh=Be("live-barrels");function Ar(e,t){return Uo(e).has(wt(t))}function Vo(e){let t=Uo(e);return Le(e).filter(n=>Cn(n)&&!t.has(n))}function Ke(e,t){let n=ee(t);return n==="entry"||n==="worker"||Ar(e,t)}function kt(e,t,n){let r=e.config.entryRoots;if(!r)return!1;let i=wt(n);return!!(r.files?.some(s=>wt(s)===i)||r.pathPrefixes?.some(s=>i.startsWith(wt(s)))||r.qualifiedVars?.some(s=>Fh(t,s))||r.symbolPatterns?.some(s=>{try{return new RegExp(s).test(t)}catch{return!1}}))}var Jo=["%/__tests__/%","%.test.%","%.spec.%","%/test/%","%/tests/%","%_test.%","%_spec.%","%/test_%.%","%/spec_%.%"],qo=["%/test-utils/%"];function Ph(e){return!!(/\.(?:test|spec)\.[a-z0-9]+$/i.test(e)||/(?:^|\/)(?:_)?test_[^/]+$/i.test(e)||/(?:^|\/)spec_[^/]+$/i.test(e)||/(?:^|\/)[^/]+_test\.[a-z0-9]+$/i.test(e)||/(?:^|\/)[^/]+_tests\.rs$/i.test(e)||/(?:^|\/)tests\.rs$/i.test(e)||/(?:^|\/)[^/]+_spec\.[a-z0-9]+$/i.test(e)||/(?:^|\/)__tests__\//i.test(e)||/(?:^|\/)test\//i.test(e)||/(?:^|\/)tests\//i.test(e)||/(?:^|\/)__fixtures__\//i.test(e)||/(?:^|\/)__mocks__\//i.test(e)||/(?:^|\/)test-support\//i.test(e)||/(?:^|\/)test-utils\//i.test(e)||/(?:^|\/)testing\//i.test(e))}function Oh(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function Mh(e){let t=e.split("/"),n=t[t.length-1]??e;return n==="cli.ts"||n==="cli.js"||n==="postinstall.ts"||n==="postinstall.js"||n==="main.ts"||n==="main.js"||n==="main.rs"||n==="main.go"||n==="main.py"||n==="build.rs"||n==="lib.rs"||/\bsrc\/bin\/[^/]+\.rs$/.test(e)||/(?:^|\/)examples\/[^/]+\.rs$/.test(e)||/(?:^|\/)tests\/[^/]+\.rs$/.test(e)||/(?:^|\/)benches\/[^/]+\.rs$/.test(e)?!0:n==="index.ts"||n==="index.js"?/(?:^|\/)(?:apps|services)\/[^/]+\/src\/index\.(?:ts|js)$/.test(e)?!0:t.length<=2:!1}function Th(e){return e==="index.ts"||e==="index.js"||e.endsWith("/index.ts")||e.endsWith("/index.js")||e.endsWith("/mod.rs")||e.endsWith("/__init__.py")}function wt(e){return e.replace(/\\/g,"/")}function Fh(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(Wo(r)+"/")&&e.includes(Wo(i)+".")}function Wo(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function pt(e,t,n){let r=Lt(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[Pt(r[0])];let i=r.filter(l=>l.file===t);if(i.length>0)return i.map(Pt);let s=Ah(e,t),o=s.get(n);if(o)for(let l of o){let c=r.filter(u=>zo(l,u.file));if(c.length>0)return c.map(Pt)}let a=new Set;for(let l of s.values())for(let c of l)a.add(c);for(let l of a){let c=r.filter(u=>zo(l,u.file));if(c.length>0&&c.length===r.length)return c.map(Pt)}return[]}function Ko(e,t,n){let r=pt(e,t,n);if(r.length>0)return r;let i=Lt(e).get(n);return!i||i.length===0?[]:i.map(Pt)}function $e(e,t){let n=cn(e,t);if(!n)return[];let r=w(n.symbol);if(!r)return[];let i=Dt(e,{...n,leaf:r,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(i.length>0){let o=new Map;for(let a of i){let l=o.get(a.file)??[];l.push(a.line),o.set(a.file,l)}return Go(e,o)}let s=new Map;for(let o of Le(e)){let a=P(e,o);if(!a||a.indexOf(r)===-1||o!==n.relativePath&&!pt(e,o,r).some(u=>u.symbolId===n.symbolId))continue;let l=pn(e,o,r,o===n.relativePath?{excludeStartLine:n.startLine,excludeEndLine:n.endLine}:{});l.length>0&&s.set(o,l)}return Go(e,s)}function Yo(e,t){let n=new Map;for(let s of t){if(!s.leaf)continue;let o=n.get(s.leaf)??[];o.push(s),n.set(s.leaf,o)}if(n.size===0)return new Map;let r=new Set(t.map(s=>s.symbolId)),i=new Map;for(let s of Le(e)){let o=js(e,s);if(o.size!==0){for(let a of o)if(n.has(a))for(let l of pt(e,s,a)){if(!r.has(l.symbolId)||s===l.relativePath)continue;let c=i.get(l.symbolId);c||(c=new Set,i.set(l.symbolId,c)),c.add(s)}}}return i}function Ah(e,t){let n=new Map;for(let r of J(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i){let s=n.get(i);s||(s=new Set,n.set(i,s)),s.add(r.sourcePath)}if(r.kind==="namespace")for(let s of r.usedMembers){let o=n.get(s);o||(o=new Set,n.set(s,o)),o.add(r.sourcePath)}}return n}function zo(e,t){let n=r=>r.replace(/\\/g,"/").replace(/^\.\//,"");return n(e)===n(t)}function Pt(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Go(e,t){let n=[],r=new Set;for(let[i,s]of t){let o=z(e,i);for(let a of s){let l=ae(o,a),c=`${i}|${a}|${l?.symbol??""}`;r.has(c)||(r.add(c),n.push({file:i,line:a,enclosingSymbol:l?.symbol??null}))}}return n}function Qo(e,t,n){let r=t.identifierResolution==="strict"?pt:Ko;for(let i of t.paths){let s=T(i);if(!s&&!(t.includeVueSfc&&St(i))||e.isIgnored(i)||t.skipPath?.(i))continue;let o=Ge(e,i);for(let[a,l]of o)for(let c of r(e,i,a))n({sourceFile:i,name:a,target:c,occurrences:l.length,kind:"identifier"});if(t.includeCrossLanguageDispatchNames)for(let a of Os(e,i))for(let l of pt(e,i,a))n({sourceFile:i,name:a,target:l,occurrences:1,kind:"cross-language-dispatch"});if(t.includeRustAttributeNames&&s==="rust")for(let a of at(e,i))for(let l of r(e,i,a))n({sourceFile:i,name:a,target:l,occurrences:1,kind:"rust-attribute"})}}var v=class{constructor(t){this.db=t}db;scopedDefinitions(t){return fr(this.db,t)}definitionsForFile(t){return z(this.db,t)}productionCallableDefinitions(t={}){let{scope:n,minLoc:r=1,maxLoc:i=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:o=!1,excludeTypesFiles:a=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:c=!1,excludeRustTraitImplMembers:u=!1,includeSuppressed:d=!1,sortByLocDesc:m=!1}=t,f=[];for(let h of this.scopedDefinitions(n)){let p=h.relativePath;if(this.db.isIgnored(p)||o&&Ke(this.db,p)||!$h(h,{requireFunctionLikeSymbol:l,requireCallableSymbol:c})||s!==void 0&&h.symbol===s)continue;let y=$r(h);y<r||y>i||a&&jh(p)||u&&an(h.symbol)||ee(p)!=="test"&&(Pe(h.symbol)||!d&&dr(this.db,p,h.startLine)||f.push(h))}return m?f.sort((h,p)=>$r(p)-$r(h)):f}calleeMap(t,n={}){return Rn(this.db,t,n)}crossFileCallerMap(t){return Ho(this.db,t)}sourceFallbackCallerFiles(t){return Yo(this.db,t)}fileDependencyGraph(t){return Q(this.db,t)}fileKind(t){return ee(t)}hasSuppressionComment(t){return dr(this.db,t.relativePath,t.startLine)}sourceFiles(){return Le(this.db)}scanSourceReferences(t,n){Qo(this.db,t,n)}callableSignature(t){return hs(this.db,t.relativePath,t.startLine,t.endLine)}};function $r(e){return e.endLine-e.startLine+1}function $h(e,t){return t.requireCallableSymbol?V(e.symbol):t.requireFunctionLikeSymbol?H(e.symbol):e.isFunctionLike}function jh(e){return(e.split("/").pop()??"").includes("types")}function Xo(e,t){let n=L(e,t);if(!n)return[];let r=w(n.symbol),s=new v(e).definitionsForFile(n.relativePath).filter(l=>V(l.symbol)),o=s.filter(l=>l.parentTypeName===r||l.symbol.includes(r));return(o.length>0?o:Hh(Bh(n.relativePath))===r?s.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:w(l.symbol)}))}function Hh(e){return e.replace(/\.[^.]+$/,"")}function Zo(e,t){let n=L(e,t);if(!n)return[];let i=!H(n.symbol)&&!e.isIgnored(n.relativePath)?[{relativePath:n.relativePath,line:n.startLine}]:[],s=$e(e,n),o=(s.length>0?s:Ce(e,n)).filter(u=>!e.isIgnored(u.file)).map(u=>({relativePath:u.file,line:u.line})),a=Wh(e,n),l=new Set,c=[];for(let u of[...i,...o,...a]){let d=`${u.relativePath}:${u.line}`;l.has(d)||(l.add(d),c.push(u))}return c}function Wh(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=Uh(t.symbol);if(n.length===0)return[];let r=e.all(`SELECT relative_path
|
|
525
526
|
FROM documents
|
|
526
527
|
WHERE relative_path LIKE '%.rb'
|
|
527
528
|
${e.pathExclusionsFor("documents")}
|
|
528
|
-
ORDER BY relative_path`),i=[];for(let s of r){if(e.isIgnored(s.relative_path))continue;let o=
|
|
529
|
-
`);for(let l=0;l<a.length;l++){let c=a[l]??"";n.some(u=>new RegExp(`@${u}\\b|\\b${u}:`).test(c))&&i.push({relativePath:s.relative_path,line:l})}}return i}function
|
|
529
|
+
ORDER BY relative_path`),i=[];for(let s of r){if(e.isIgnored(s.relative_path))continue;let o=P(e,s.relative_path);if(!o)continue;let a=o.split(`
|
|
530
|
+
`);for(let l=0;l<a.length;l++){let c=a[l]??"";n.some(u=>new RegExp(`@${u}\\b|\\b${u}:`).test(c))&&i.push({relativePath:s.relative_path,line:l})}}return i}function Uh(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}function ea(e,t){let n=L(e,t);if(!n)return{definitions:[],referencedBy:[]};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",n.symbolId),i=Je(r?.documentation??null),s=e.isIgnored(n.relativePath)?[]:[{relativePath:n.relativePath,startLine:n.startLine,endLine:n.endLine,signature:Jh(i,r?.display_name??null,n.symbol),source:Vh(e,n.relativePath,n.startLine,n.endLine)}],o=$e(e,n),l=(o.length>0?o:Ce(e,n)).filter(c=>!e.isIgnored(c.file)).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?g(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:l}}function Vh(e,t,n,r){let i=P(e,t);if(!i)return null;let o=i.split(`
|
|
530
531
|
`).slice(n,r+1).join(`
|
|
531
|
-
`).trimEnd();return o.length>0?o:null}function
|
|
532
|
+
`).trimEnd();return o.length>0?o:null}function Jh(e,t,n){let r=Ve(e);if(r&&!qh(r))return r;let i=(t??"").trim();return i?H(n)&&!i.endsWith("()")?`${i}()`:i:g(n)}function qh(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function ta(e,t){let n=K(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
|
|
532
533
|
FROM mentions m
|
|
533
534
|
JOIN chunks c ON m.chunk_id = c.id
|
|
534
535
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -544,7 +545,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
544
545
|
WHERE d1.relative_path = ?
|
|
545
546
|
AND d2.relative_path <> d1.relative_path
|
|
546
547
|
AND ${e.localSymbolPredicate}
|
|
547
|
-
ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function
|
|
548
|
+
ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function na(e,t){let n=K(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
|
|
548
549
|
FROM mentions m
|
|
549
550
|
JOIN chunks c ON m.chunk_id = c.id
|
|
550
551
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -559,9 +560,9 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
559
560
|
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
560
561
|
WHERE d2.relative_path = ?
|
|
561
562
|
AND d1.relative_path != ?
|
|
562
|
-
ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function
|
|
563
|
+
ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function ra(e,t){let n=Oe(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),s=e.all(`SELECT relative_path FROM documents
|
|
563
564
|
WHERE relative_path IN (${r})
|
|
564
|
-
ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),o=
|
|
565
|
+
ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),o=it(e,s,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...m})=>m),l=e.all(`SELECT DISTINCT d2.relative_path
|
|
565
566
|
FROM mentions m
|
|
566
567
|
JOIN chunks c ON m.chunk_id = c.id
|
|
567
568
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -592,7 +593,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
592
593
|
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
593
594
|
WHERE d2.relative_path IN (${r})
|
|
594
595
|
AND d1.relative_path NOT IN (${r})
|
|
595
|
-
ORDER BY d1.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d));return{files:s,symbols:o,dependsOn:l,dependedOnBy:u}}function
|
|
596
|
+
ORDER BY d1.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d));return{files:s,symbols:o,dependsOn:l,dependedOnBy:u}}function ia(e,t){let n=Oe(e,t);return n.length===0?[]:Kh([...zh(e,n),...Gh(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(Yh)}function zh(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
|
|
596
597
|
FROM mentions m
|
|
597
598
|
JOIN chunks c ON m.chunk_id = c.id
|
|
598
599
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -619,7 +620,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
619
620
|
AND m.role != 1
|
|
620
621
|
AND ${e.localSymbolPredicate}
|
|
621
622
|
${e.pathExclusionsFor("d1")}
|
|
622
|
-
ORDER BY d1.relative_path`,...t,...t,...t)}function
|
|
623
|
+
ORDER BY d1.relative_path`,...t,...t,...t)}function Gh(e,t){let n=new v(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>V(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function Kh(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function Yh(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:g(e.symbol)}}function vn(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:s=!1,includeMembers:o=!1}=t,a=s?new Set(Vo(e)):new Set,l=Qh(e,a);ny(e,l,a);let c=Xh(e,{scope:n,minLoc:r,includeTests:i,includeMembers:o});return ly(e,c,l,{includeTests:i,inactiveBarrelPaths:a}),ty(e,Zh(c,l))}function Qh(e,t){let n=e.all(`SELECT
|
|
623
624
|
m.symbol_id,
|
|
624
625
|
d.relative_path,
|
|
625
626
|
COUNT(*) AS ref_count
|
|
@@ -628,8 +629,8 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
628
629
|
JOIN documents d ON c.document_id = d.id
|
|
629
630
|
WHERE m.role != 1
|
|
630
631
|
${e.pathExclusionsFor("d")}
|
|
631
|
-
GROUP BY m.symbol_id, d.relative_path`),r=new Map;for(let i of n){if(e.isIgnored(i.relative_path)||t.has(i.relative_path))continue;let s=r.get(i.symbol_id);s||(s=new Map,r.set(i.symbol_id,s)),s.set(i.relative_path,i.ref_count)}return r}function
|
|
632
|
-
WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`);return new Set(t.map(n=>n.relative_path))}function
|
|
632
|
+
GROUP BY m.symbol_id, d.relative_path`),r=new Map;for(let i of n){if(e.isIgnored(i.relative_path)||t.has(i.relative_path))continue;let s=r.get(i.symbol_id);s||(s=new Map,r.set(i.symbol_id,s)),s.set(i.relative_path,i.ref_count)}return r}function Xh(e,t){let n=cy(e);return oe(e,{scope:t.scope}).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>!ke(r.symbol)).filter(r=>sa(r.symbol)).filter(r=>r.isFunctionLike||!r.enclosingSymbol||!sa(r.enclosingSymbol)).filter(r=>t.includeTests||oa(r.relativePath)).filter(r=>t.includeTests||!n(r.relativePath,r.startLine,r.symbol,r.parentTypeName)).filter(r=>!an(r.symbol)).filter(r=>!Pe(r.symbol)).filter(r=>t.includeMembers||dy(r)).filter(r=>r.endLine-r.startLine+1>=t.minLoc)}function Zh(e,t){return e.map(n=>ey(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function ey(e,t){let n=t.get(e.symbolId)??new Map,r=n.get(e.relativePath)??0,i=0;for(let[s,o]of n)s!==e.relativePath&&(i+=o);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,same_file_refs:r,cross_file_refs:i}}function ty(e,t){let n=[],r=0,i=0,s=0;for(let o of t){if(e.isIgnored(o.relative_path)||Ke(e,o.relative_path)||kt(e,o.symbol,o.relative_path))continue;let a=o.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?r++:i++,s+=o.loc,n.push({relativePath:o.relative_path,startLine:o.start_line,endLine:o.end_line,loc:o.loc,symbol:o.symbol,shortName:g(o.symbol),sameFileRefs:o.same_file_refs,kind:a})}return{symbols:n,totalCount:n.length,deadCodeCount:r,fileInternalCount:i,totalLoc:s}}function ny(e,t,n){let r=new v(e),i=new Set(r.sourceFiles());for(let s of ry(e))i.add(s);r.scanSourceReferences({paths:i,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",skipPath:s=>n.has(s)},s=>{iy(e,s)||oy(t,s.target.symbolId,s.sourceFile,sy(s))})}function ry(e){let t=e.all(`SELECT relative_path FROM documents
|
|
633
|
+
WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`);return new Set(t.map(n=>n.relative_path))}function iy(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&ay(e,t)}function sy(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function oy(e,t,n,r){if(r<=0)return;let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(n,(i.get(n)??0)+r)}function ay(e,t){return t.occurrences>1?!1:J(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function ly(e,t,n,r){for(let i of t){let s=ie(e,i);if(s.length===0)continue;let o=n.get(i.symbolId);o||(o=new Map,n.set(i.symbolId,o));for(let a of s){let l=a.file;l===i.relativePath||e.isIgnored(l)||r.inactiveBarrelPaths.has(l)||!r.includeTests&&!oa(l)||o.set(l,Math.max(1,o.get(l)??0))}}}function cy(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let s=Ds(e,r);return i={ranges:s.map(o=>({startLine:o.startLine,endLine:o.endLine})),containers:new Set(s.map(o=>o.containerName).filter(o=>!!o))},t.set(r,i),i};return(r,i,s,o)=>{let a=n(r);for(let l of a.ranges)if(i>=l.startLine&&i<=l.endLine)return!0;if(o&&a.containers.has(o))return!0;for(let l of gr(s))if(a.containers.has(l))return!0;return!1}}function oa(e){return[...new Set([...Jo,...qo])].every(n=>!uy(e,n))}function uy(e,t){return new RegExp(`^${t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".")}$`).test(e)}function sa(e){return H(e)||e.endsWith("().")||e.endsWith(".")}function dy(e){return V(e.symbol)||gr(e.symbol).length===0}function aa(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",o=e.all(`SELECT
|
|
633
634
|
gs.symbol,
|
|
634
635
|
COUNT(*) AS ref_count,
|
|
635
636
|
COUNT(DISTINCT ref_d.id) AS file_count,
|
|
@@ -652,18 +653,18 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
652
653
|
${i}
|
|
653
654
|
GROUP BY gs.id
|
|
654
655
|
ORDER BY ref_count DESC
|
|
655
|
-
LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:
|
|
656
|
+
LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:g(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return o.length>0?o:my(e,r,n)}function my(e,t,n){return oe(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>py(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function py(e,t){let n=ie(e,t,{limit:500});return{symbol:t.symbol,shortName:g(t.symbol),refCount:n.length,fileCount:new Set(n.map(r=>r.file)).size,definedIn:t.relativePath}}function ca(e,t){return ma(e,t)?.map(n=>({symbol:n.symbol,shortName:n.shortName,fromFile:n.fromFile}))??[]}function ua(e,t){let n=fy(e,t);return n.length>0?n:gy(e,t)}function da(e,t){return ma(e,t)?.filter(n=>!n.used).map(n=>({symbol:n.symbol,shortName:n.shortName,importedIn:n.importer}))??[]}function fy(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
|
|
656
657
|
FROM mentions m
|
|
657
658
|
JOIN chunks c ON m.chunk_id = c.id
|
|
658
659
|
JOIN documents d ON c.document_id = d.id
|
|
659
660
|
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
660
661
|
WHERE gs.symbol LIKE ?
|
|
661
662
|
AND m.role = 2
|
|
662
|
-
ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:
|
|
663
|
+
ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:g(r.symbol),fromFile:r.importer}))}function gy(e,t){let n=L(e,t),r=n?.relativePath??null,i=n?w(n.symbol):t.replace(/\(\)$/,""),s=n?ke(n.symbol):!1,o=e.all(`SELECT relative_path
|
|
663
664
|
FROM documents
|
|
664
665
|
WHERE 1 = 1
|
|
665
666
|
${e.pathExclusionsFor("documents")}
|
|
666
|
-
ORDER BY relative_path`),a=new Set;for(let l of o)if(!e.isIgnored(l.relative_path))for(let c of J(e,l.relative_path))
|
|
667
|
+
ORDER BY relative_path`),a=new Set;for(let l of o)if(!e.isIgnored(l.relative_path))for(let c of J(e,l.relative_path))hy(c,l.relative_path,{targetFile:r,targetLeaf:i,targetIsModule:s})&&a.add(l.relative_path);return[...a].sort().map(l=>({symbol:n?.symbol??i,shortName:n?g(n.symbol):i,fromFile:l}))}function hy(e,t,n){return!e.sourcePath||n.targetFile&&la(e.sourcePath)!==la(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&xy(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function ma(e,t){let n=K(e,t);return n?yy(e,n)??by(e,n)??Sy(e,n):null}function yy(e,t){let r=e.all(`SELECT DISTINCT
|
|
667
668
|
gs.symbol,
|
|
668
669
|
def_d.relative_path AS from_file,
|
|
669
670
|
imp_d.relative_path AS importer,
|
|
@@ -689,11 +690,11 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
689
690
|
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
690
691
|
WHERE imp_d.relative_path = ?
|
|
691
692
|
AND m.role = 2
|
|
692
|
-
ORDER BY def_d.relative_path, gs.symbol`,t).filter(i=>!e.isIgnored(i.importer));if(r.length>0){let i=
|
|
693
|
+
ORDER BY def_d.relative_path, gs.symbol`,t).filter(i=>!e.isIgnored(i.importer));if(r.length>0){let i=Et(e,t);return r.map(s=>({symbol:s.symbol,shortName:g(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||i.some(o=>o.isUsed&&o.sourcePath===s.from_file)}))}return null}function by(e,t){let n=Et(e,t);return n.length>0?n.map(r=>{let i=pa(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function Sy(e,t){return J(e,t).map(n=>{let r=pa(n.importedName,n.localName,n.kind),i=n.kind==="side-effect"?!0:n.used;return{symbol:r,shortName:r,fromFile:n.sourcePath??"(external)",importer:t,used:i}})}function pa(e,t,n){return n==="namespace"&&e==="*"&&t?`* as ${t}`:n==="default"&&t?`default as ${t}`:n==="side-effect"?"(side effect import)":t&&t!==e?`${e} as ${t}`:e}function la(e){return e.replace(/\\/g,"/")}function xy(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function fa(e,t){let n=Oe(e,t),r=it(e,n,{sort:!0});if(r.length===0)return[];let i=r.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,children:[]})),s=new Map;for(let a of i)s.set(a.symbol,a);let o=[];for(let a=0;a<r.length;a++){let l=r[a],c=i[a];if(l.enclosingSymbol&&s.has(l.enclosingSymbol)){s.get(l.enclosingSymbol).children.push(c);continue}let u=null,d=1/0;for(let m of i)if(m!==c&&m.startLine<=c.startLine&&m.endLine>=c.endLine){if(m.startLine===c.startLine&&m.endLine===c.endLine&&!Ss(m.symbol,c.symbol))continue;let h=m.endLine-m.startLine;h<d&&(d=h,u=m)}u?u.children.push(c):o.push(c)}return o}function ga(e,t){let n=L(e,t);return n?new v(e).definitionsForFile(n.relativePath).filter(i=>i.symbol!==n.symbol).filter(i=>bs(n.symbol,i.symbol)).sort((i,s)=>i.startLine-s.startLine||i.endLine-s.endLine).map(i=>({symbol:i.symbol,shortName:g(i.symbol),startLine:i.startLine,endLine:i.endLine,kind:U(i.symbol)??"unknown"})):[]}function ha(e,t){let n=L(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
|
|
693
694
|
FROM mentions m
|
|
694
695
|
JOIN chunks c ON m.chunk_id = c.id
|
|
695
696
|
WHERE m.symbol_id = ?
|
|
696
|
-
AND m.role != 1`,n.symbolId);return[{name:
|
|
697
|
+
AND m.role != 1`,n.symbolId);return[{name:g(n.symbol),count:r?.file_count??0}]}function ya(e,t){let n=K(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
697
698
|
FROM mentions m
|
|
698
699
|
JOIN chunks c ON m.chunk_id = c.id
|
|
699
700
|
JOIN documents d ON c.document_id = d.id
|
|
@@ -710,7 +711,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
710
711
|
AND m.role != 1
|
|
711
712
|
AND def_d.id != d.id
|
|
712
713
|
GROUP BY d.id
|
|
713
|
-
ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let o=
|
|
714
|
+
ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let o=Q(e).get(n);return!o||o.size===0?[]:[{name:n,count:o.size}]}function ba(e,t={}){return _y(e,t).map(n=>({name:g(n.symbol),count:n.file_count}))}function _y(e,t){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
|
|
714
715
|
FROM mentions m
|
|
715
716
|
JOIN chunks c ON m.chunk_id = c.id
|
|
716
717
|
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
@@ -729,7 +730,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
729
730
|
GROUP BY gs.id
|
|
730
731
|
HAVING file_count > 1
|
|
731
732
|
ORDER BY file_count DESC
|
|
732
|
-
LIMIT ?`,n)}function
|
|
733
|
+
LIMIT ?`,n)}function Sa(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
733
734
|
FROM mentions m
|
|
734
735
|
JOIN chunks c ON m.chunk_id = c.id
|
|
735
736
|
JOIN documents d ON c.document_id = d.id
|
|
@@ -749,7 +750,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
749
750
|
${i}
|
|
750
751
|
GROUP BY d.id
|
|
751
752
|
ORDER BY symbol_count DESC
|
|
752
|
-
LIMIT ?`,n).filter(o=>!e.isIgnored(o.relative_path)).map(o=>({name:o.relative_path,count:o.symbol_count}))}function
|
|
753
|
+
LIMIT ?`,n).filter(o=>!e.isIgnored(o.relative_path)).map(o=>({name:o.relative_path,count:o.symbol_count}))}function xa(e,t,n){let r=K(e,t)??t,i=K(e,n)??n,s=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
|
|
753
754
|
FROM global_symbols gs
|
|
754
755
|
WHERE (
|
|
755
756
|
-- Defined in file1, referenced in file2
|
|
@@ -781,7 +782,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
781
782
|
JOIN documents d ON c.document_id = d.id
|
|
782
783
|
WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
|
|
783
784
|
)
|
|
784
|
-
)`,r,i,i,r);return{file1:r,file2:i,sharedSymbols:s?.shared??0}}function
|
|
785
|
+
)`,r,i,i,r);return{file1:r,file2:i,sharedSymbols:s?.shared??0}}function _a(e,t={}){let{limit:n=20,scope:r}=t,i=r?`AND d1.relative_path LIKE '%${r}%' AND d2.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT
|
|
785
786
|
def_d.relative_path AS file1,
|
|
786
787
|
ref_d.relative_path AS file2,
|
|
787
788
|
COUNT(DISTINCT gs.id) AS shared
|
|
@@ -803,35 +804,43 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
803
804
|
${i}
|
|
804
805
|
GROUP BY def_d.id, ref_d.id
|
|
805
806
|
ORDER BY shared DESC
|
|
806
|
-
LIMIT ?`,n).filter(o=>!e.isIgnored(o.file1)&&!e.isIgnored(o.file2)).map(o=>({file1:o.file1,file2:o.file2,sharedSymbols:o.shared}))}function
|
|
807
|
-
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:
|
|
807
|
+
LIMIT ?`,n).filter(o=>!e.isIgnored(o.file1)&&!e.isIgnored(o.file2)).map(o=>({file1:o.file1,file2:o.file2,sharedSymbols:o.shared}))}function Nn(e,t={}){let{scope:n,maxDepth:r=10}=t,i=Q(e,n),s=[],o=new Set,a=new Set,l=[];function c(d,m){if(m>r)return;if(a.has(d)){let h=l.indexOf(d);if(h!==-1){let p=l.slice(h).concat(d),y=p.indexOf(p.reduce((F,M)=>F<M?F:M)),_=[...p.slice(y,-1),...p.slice(0,y),p[y]],E=_.join(" -> ");u.has(E)||(u.add(E),s.push({path:_,kind:Iy(_)}))}return}if(o.has(d))return;o.add(d),a.add(d),l.push(d);let f=i.get(d);if(f)for(let h of f)c(h,m+1);l.pop(),a.delete(d)}let u=new Set;for(let d of i.keys())o.has(d)||c(d,0);return s.sort((d,m)=>d.kind!==m.kind?d.kind==="real"?-1:1:d.path.length-m.path.length),s}function Iy(e){for(let r of e){let i=ee(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Cn(t)||Cn(n)||Ia(t,n)||Ia(n,t)||Ra(t,n)||Ra(n,t)||ee(t)==="entry"||ee(n)==="entry"?"module-hierarchy":"real"}function Ia(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function Ra(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),s=t.split("/");if(i.length===s.length&&i.includes("tests")&&s.includes("src")){let o=i[i.length-1],a=s[s.length-1];if(o&&o===a)return!0}return!1}function Ca(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:s=2}=t;return new v(e).productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0}).map(l=>Ry(e,l)).filter(l=>l.fanIn>=i&&l.fanOut>=s).sort((l,c)=>c.score-l.score||c.fanIn-l.fanIn).slice(0,n)}function Ry(e,t){let n=new Set(ie(e,t,{limit:500}).map(i=>i.file)).size,r=new Set(Z(e,t,{limit:500}).filter(i=>i.file!==t.relativePath).map(i=>`${i.symbol}|${i.file}`)).size;return{symbol:t.symbol,shortName:g(t.symbol),fanIn:n,fanOut:r,score:n*r,definedIn:t.relativePath}}function En(e,t={}){let{scope:n,minLoc:r=3}=t,i=new v(e),s=i.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0}),o=i.crossFileCallerMap(s),a=new Set(o.keys()),l=new Map;for(let p of s){let y=w(p.symbol);if(!y)continue;let _=l.get(y)??[];_.push(p.symbolId),l.set(y,_)}let c=e.all(`SELECT relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`);for(let p of c){if(e.isIgnored(p.relative_path)||T(p.relative_path)!=="rust")continue;let y=at(e,p.relative_path);for(let _ of y){let E=l.get(_);if(E)for(let F of E)a.add(F)}}let u=va(i,s,{additive:!1}),d=s.filter(p=>!a.has(p.symbolId)).filter(p=>!u.has(p.symbolId)),m=i.sourceFallbackCallerFiles(d);for(let p of m.keys())a.add(p);let f=d.filter(p=>!a.has(p.symbolId)),h=va(i,f,{additive:!0});for(let p of h)u.add(p);return f.filter(p=>!u.has(p.symbolId)).sort((p,y)=>y.endLine-y.startLine-(p.endLine-p.startLine)||p.relativePath.localeCompare(y.relativePath)||p.startLine-y.startLine).map(p=>({symbol:p.symbol,shortName:g(p.symbol),relativePath:p.relativePath,startLine:p.startLine,endLine:p.endLine,loc:p.endLine-p.startLine+1}))}function va(e,t,n){if(t.length===0)return new Set;let r=new Map(t.map(s=>[s.symbolId,s.symbol])),i=e.calleeMap(t,{additive:n.additive});return new Set([...i.entries()].filter(([s,o])=>{let a=r.get(s);return o.some(l=>l.symbol!==a)}).map(([s])=>s))}var Br={0:"UnspecifiedKind",1:"AbstractMethod",2:"Accessor",3:"Array",4:"Assertion",5:"AssociatedType",6:"Attribute",7:"Axiom",8:"Boolean",9:"Class",10:"Constant",11:"Constructor",12:"Contract",13:"DataFamily",14:"DefinitionMacro",15:"Delegate",16:"Enum",17:"EnumMember",18:"Error",19:"Event",20:"Fact",21:"Field",22:"File",23:"Function",24:"Getter",25:"Grammar",26:"Instance",27:"Interface",28:"Key",29:"Lang",30:"Lemma",31:"Library",32:"Macro",33:"Method",34:"MethodAlias",35:"MethodReceiver",36:"MethodSpecification",37:"Message",38:"Modifier",39:"Module",40:"Namespace",41:"Null",42:"Number",43:"Object",44:"Operator",45:"Package",46:"PackageObject",47:"Parameter",48:"ParameterLabel",49:"Pattern",50:"Predicate",51:"Property",52:"Protocol",53:"ProtocolMethod",54:"PureVirtualMethod",55:"Quasiquoter",56:"SelfParameter",57:"Setter",58:"Signature",59:"SingletonClass",60:"SingletonMethod",61:"StaticDataMember",62:"StaticEvent",63:"StaticField",64:"StaticMethod",65:"StaticProperty",66:"StaticVariable",67:"String",68:"Struct",69:"Subscript",70:"Tactic",71:"Theorem",72:"ThisParameter",73:"Trait",74:"TraitMethod",75:"Type",76:"TypeAlias",77:"TypeClass",78:"TypeClassMethod",79:"TypeFamily",80:"TypeParameter",81:"Union",82:"Value",83:"Variable"},jr=new Map;for(let[e,t]of Object.entries(Br))jr.set(t.toLowerCase(),Number(e));function Cy(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=jr.get(n);if(r!==void 0)return r;for(let[i,s]of jr)if(i.includes(n))return s;return null}function Na(e,t,n={}){let{scope:r,limit:i=100}=n,s=Cy(t);return s===null?[]:Da(e,r).map(a=>({row:a,resolvedKind:La(a)})).filter(a=>a.resolvedKind===s).slice(0,i).map(({row:a,resolvedKind:l})=>({symbol:a.symbol,shortName:g(a.symbol),kind:l,kindName:Br[l]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function Ea(e,t={}){let n=new Map;for(let r of Da(e,t.scope)){let i=La(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:Br[r]??"Unknown",count:i}))}function Da(e,t){return oe(e,{scope:t}).map(vy)}function vy(e){return{symbol:e.symbol,kind:e.kind,documentation:e.documentation,enclosing_symbol:e.enclosingSymbol,relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine}}function La(e){return e.kind!==null&&e.kind!==0?Ny(e.kind,e.symbol,e.documentation):Ey(e.symbol,e.documentation,e.enclosing_symbol)}function Ny(e,t,n){let r=(n??"").toLowerCase();if(U(t)==="type"){if(r.includes("type "))return 76;if(r.includes("interface "))return 27;if(r.includes("struct "))return 68;if(r.includes("trait "))return 73;if(r.includes("class "))return 9}return e}function Ey(e,t,n){let r=W(e);if("kind"in r)return null;let i=r.descriptors,s=i[i.length-2]??null,o=U(e),a=(t??"").toLowerCase();return o==="type"?a.includes("type ")?76:a.includes("interface ")?27:a.includes("struct ")?68:a.includes("trait ")?73:(a.includes("class "),9):o==="method"?s?.suffix==="type"?33:23:o==="namespace"?39:o!=="term"?null:a.includes("async def ")||a.includes("def ")?23:(n?U(n):s?.suffix??null)==="type"?21:83}function wa(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,s=Q(e,r),o=new Map,a=[],l=new Map,c=new Map,u=new Set,d=[],m=0;for(let C of s.keys()){if(l.has(C))continue;let I=[],k=(s.get(C)??new Set).values();for(l.set(C,m),c.set(C,m),m+=1,d.push(C),u.add(C),I.push({node:C,iter:k,pendingChild:null});I.length>0;){let D=I[I.length-1];if(D.pendingChild!==null){let Qe=D.pendingChild;D.pendingChild=null,c.set(D.node,Math.min(c.get(D.node),c.get(Qe)))}let G=D.iter.next();if(G.done){if(c.get(D.node)===l.get(D.node)){let Qe=[];for(;;){let Bt=d.pop();if(u.delete(Bt),Qe.push(Bt),o.set(Bt,a.length),Bt===D.node)break}a.push(Qe)}I.pop();continue}let me=G.value;if(l.has(me))u.has(me)&&c.set(D.node,Math.min(c.get(D.node),l.get(me)));else{l.set(me,m),c.set(me,m),m+=1,d.push(me),u.add(me);let Qe=(s.get(me)??new Set).values();D.pendingChild=me,I.push({node:me,iter:Qe,pendingChild:null})}}}let f=new Map,h=new Array(a.length);for(let C=0;C<a.length;C++)h[C]=a[C].length,f.set(C,new Set);for(let[C,I]of s){let k=o.get(C);for(let D of I){let G=o.get(D);G!==k&&f.get(k).add(G)}}let p=new Array(a.length),y=new Array(a.length);for(let C=0;C<a.length;C++){let I=[],k=0;for(let D of f.get(C)){let G=y[D];G>k&&(k=G,I=p[D])}p[C]=[C,...I],y[C]=h[C]+k}function _(C){return p[C]}let E=a.map(C=>[...C].sort()),F=new Set,M=[];for(let C=0;C<a.length;C++){let I=_(C),k=[];for(let G of I)k.push(...E[G]);if(k.length<i)continue;let D=k.join(" ");F.has(D)||(F.add(D),M.push({chain:k,depth:k.length}))}return M.sort((C,I)=>I.depth-C.depth),M.slice(0,n)}function ka(e,t){let n=L(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
|
|
808
|
+
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:g(r.symbol),depth:0}],s=r.enclosing_symbol,o=1,a=new Set([r.symbol]);for(;s&&!a.has(s)&&o<20;){a.add(s);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",s);if(!d)break;i.push({symbol:d.symbol,shortName:g(d.symbol),depth:o}),s=d.enclosing_symbol,o++}if(i.length>1)return i;let l=W(r.symbol);if("kind"in l)return i;let c=l.descriptors;if(c.length<=1)return i;let u=[i[0]];for(let d=c.length-2,m=1;d>=0;d--,m++){let h=c.slice(0,d+1).map(p=>p.suffix==="method"?`${p.name}()`:p.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:h,shortName:h,depth:m})}return u}function Pa(e,t){let n=L(e,t);if(!n)return null;let r=ie(e,n,{limit:50}),i=Dy(Z(e,n,{limit:50,additive:!0,callableOnly:!0}));return{symbol:n.symbol,shortName:g(n.symbol),callers:r.map(s=>({symbol:s.symbol,shortName:g(s.symbol),file:s.file})),callees:i.map(s=>({symbol:s.symbol,shortName:g(s.symbol),file:s.file}))}}function Dy(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function Ot(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Mt(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function Oa(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function Hr(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let i of e)for(let s of i)n.set(s,(n.get(s)??0)+1);let r=new Map;for(let[i,s]of n)r.set(i,Math.log(t/s));return r}function Ly(e){let t=[...e.values()].sort((r,i)=>r-i);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Ma(e,t,n){let r=Ot(e,t);if(r.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let i=0,s=0,o=0,a=new Set([...e,...t]);for(let f of a){let h=n.get(f)??0,p=e.has(f)?h:0,y=t.has(f)?h:0;i+=p*y,s+=p*p,o+=y*y}let l=Math.sqrt(s)*Math.sqrt(o),c=l>0?i/l:0,u=Ly(n),d=[],m=[];for(let f of r)(n.get(f)??0)>=u?d.push(f):m.push(f);return d.sort((f,h)=>(n.get(h)??0)-(n.get(f)??0)),{similarity:c,significantShared:d,trivialShared:m}}function Ta(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,s=Py(e,t);if(!s)return[];if(!H(s.symbol))return[];let o=wy(e,s,r);return o.length>0?o.slice(0,i):Ty(e,t,{minSimilarity:r,limit:i})}function wy(e,t,n){let r=Aa(e,{minCallees:3,excludeSymbol:t.symbol}),i=Hr([t,...r].map(o=>o.callees)),s=[];for(let o of r){if(o.callees.size<3)continue;let a=Fa(t,o,i,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});a&&s.push(a)}return s.sort((o,a)=>a.similarity-o.similarity),s}function Fa(e,t,n,r){let{similarity:i,significantShared:s}=Ma(e.callees,t.callees,n);if(i<r.minSimilarity)return null;let o=Ot(e.callees,t.callees).size;if(s.length<r.requireSignificantShared&&o<r.requireSharedCount)return null;let a=s.length>0?s:[...Ot(e.callees,t.callees)];return{symbolA:e.symbol,shortNameA:g(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:g(t.symbol),fileB:t.file,similarity:i,similarityBasis:"callees",sharedCallees:a.map(g),uniqueToA:[...Mt(e.callees,t.callees)].map(g),uniqueToB:[...Mt(t.callees,e.callees)].map(g)}}function Dn(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:s=4,crossFileOnly:o=!1,scanLimit:a}=t,l=Aa(e,{minCallees:s,scope:i,scanLimit:a}),c=Hr(l.map(p=>p.callees)),u=new Map;for(let p of l)for(let y of p.callees)u.set(y,(u.get(y)??0)+1);let d=Math.max(8,Math.ceil(Math.sqrt(l.length))),m=new Map;for(let p=0;p<l.length;p+=1)for(let y of l[p].callees){if((u.get(y)??0)>d)continue;let _=m.get(y);_||(_=[],m.set(y,_)),_.push(p)}let f=[],h=new Set;e:for(let p=0;p<l.length;p+=1){let y=l[p],_=new Set;for(let E of y.callees){let F=m.get(E);if(F)for(let M of F)M>p&&_.add(M)}for(let E of _){let F=`${p}|${E}`;if(h.has(F))continue;h.add(F);let M=l[E];if(o&&y.file===M.file)continue;if(y.paramCount>=0&&M.paramCount>=0){let I=Math.abs(y.paramCount-M.paramCount),k=Math.max(2,Math.ceil(Math.max(y.paramCount,M.paramCount)*.5));if(I>k)continue}let C=Fa(y,M,c,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});if(C&&(f.push(C),f.length>r*5))break e}}return f.sort((p,y)=>y.similarity-p.similarity),f.slice(0,r)}var ky=["ScipDatabase#all","ScipDatabase#get","ScipDatabase#prepare","ScipDatabase#pathExclusionsFor","ScipDatabase#isIgnored","ScipDatabase#symbolNoiseFor","PerDbValue#get","PerDbValue#has",":storage:db:ScipDatabase:all",":storage:db:ScipDatabase:get",":storage:db:ScipDatabase:prepare",":storage:db:ScipDatabase:pathExclusionsFor",":storage:db:ScipDatabase:isIgnored",":storage:db:ScipDatabase:symbolNoiseFor",":storage:per-db-cache:PerDbValue:get",":storage:per-db-cache:PerDbValue:has"];function Py(e,t){let n=L(e,t),r=new v(e);if(!n)return null;let i=Z(e,n);return{symbol:n.symbol,file:n.relativePath,callees:$a(i.map(s=>s.symbol)),paramCount:r.callableSignature(n)?.paramCount??-1}}function Aa(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:s}=t,o=new v(e),a=Oy(o.productionCallableDefinitions({scope:r,minLoc:5,excludeSymbol:i,sortByLocDesc:typeof s=="number"&&s>0}),s),l=o.calleeMap(a);return a.map(c=>({symbol:c.symbol,file:c.relativePath,callees:$a((l.get(c.symbolId)??[]).map(u=>u.symbol)),paramCount:o.callableSignature(c)?.paramCount??-1})).filter(c=>c.callees.size>=n)}function Oy(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function $a(e){return new Set([...e].filter(t=>!My(t)))}function My(e){return ky.some(t=>e.includes(t))}function Ty(e,t,n){let r=Fy(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,s=[];for(let o of $y(e)){if(o.symbol===r.symbol||o.tokens.size<3)continue;let a=Ot(r.tokens,o.tokens);if(a.size<2)continue;let l=new Set([...r.tokens,...o.tokens]),c=l.size>0?a.size/l.size:0;c<i||s.push({symbolA:r.symbol,shortNameA:g(r.symbol),fileA:r.file,symbolB:o.symbol,shortNameB:g(o.symbol),fileB:o.file,similarity:c,similarityBasis:"source-tokens",sharedCallees:[...a].sort(),uniqueToA:[...Mt(r.tokens,o.tokens)].sort(),uniqueToB:[...Mt(o.tokens,r.tokens)].sort()})}return s.sort((o,a)=>a.similarity-o.similarity||o.shortNameB.localeCompare(a.shortNameB)),s.slice(0,n.limit)}function Fy(e,t){let n=L(e,t);if(!n||!H(n.symbol))return null;let r=Ay(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function Ay(e,t){let n=w(t.symbol),r=ja(e,t.relativePath,t.startLine,t.endLine,n),i=Ba(r,n);return i.size>0?i:null}function $y(e){let t=new v(e);return t.scopedDefinitions().filter(n=>n.isFunctionLike).filter(n=>t.fileKind(n.relativePath)!=="test").filter(n=>!Pe(n.symbol)).map(n=>({symbol:n.symbol,file:n.relativePath,tokens:Ba(ja(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function ja(e,t,n,r,i){let s=P(e,t);if(!s)return"";let o=s.split(`
|
|
808
809
|
`);if(r>=n&&r-n<=12)return o.slice(n,r+1).join(`
|
|
809
|
-
`);let a=[new RegExp(`\\bdef\\s+${
|
|
810
|
+
`);let a=[new RegExp(`\\bdef\\s+${Tt(i)}\\b`),new RegExp(`\\bfun\\s+${Tt(i)}\\b`),new RegExp(`\\bfn\\s+${Tt(i)}\\b`),new RegExp(`\\bfunction\\s+${Tt(i)}\\b`),new RegExp(`\\b${Tt(i)}\\s*\\(`)],l=o.findIndex(c=>a.some(u=>u.test(c)));if(l>=0){let c=l;for(let u=l+1;u<o.length&&u<=l+8;u++){let d=o[u]??"";if(u>l&&By(d)||(c=u,d.trim()===""&&u>l+1))break}return o.slice(l,c+1).join(`
|
|
810
811
|
`)}return o.slice(n,Math.min(o.length,n+8)).join(`
|
|
811
|
-
`)}function
|
|
812
|
+
`)}function Ba(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),r=jy(t),s=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(o=>o.trim()).filter(o=>o.length>1).filter(o=>!n.has(o)).filter(o=>!r.has(o));return new Set(s)}function jy(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(t=>t.toLowerCase()).filter(t=>t.length>1))}function By(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Tt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wa(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:s}=t,o=t.minDeps??(s?1:3),a=Hy(e,{scope:i,minDeps:o}),l=[];if(s){let c=a.find(u=>u.file.includes(s));if(!c)return[];for(let u of a){if(u.file===c.file)continue;let d=Ha(c,u,n);d&&l.push(d)}}else for(let c=0;c<a.length;c++){for(let u=c+1;u<a.length;u++){let d=Ha(a[c],a[u],n);d&&l.push(d)}if(l.length>r*5)break}return l.sort((c,u)=>u.similarity-c.similarity),l.slice(0,r)}function Hy(e,t){let{scope:n,minDeps:r}=t,i=Q(e,n),s=Wy(i),o=[];for(let[a,l]of i)l.size>=r&&o.push({file:a,deps:new Set([...l].filter(c=>!s.has(c)))});return o}function Wy(e){let t=new Set,n=e.size;if(n===0)return t;let r=new Map;for(let i of e.values())for(let s of i)r.set(s,(r.get(s)??0)+1);for(let[i,s]of r)s>=5&&s/n>.3&&t.add(i);return t}function Ha(e,t,n){let r=new Set;for(let a of e.deps)t.deps.has(a)&&r.add(a);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let i=Oa(e.deps,t.deps);if(i<n)return null;let s=[];for(let a of e.deps)t.deps.has(a)||s.push(a);let o=[];for(let a of t.deps)e.deps.has(a)||o.push(a);return{fileA:e.file,fileB:t.file,similarity:i,sharedDeps:[...r],uniqueToA:s,uniqueToB:o}}function Va(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:s=3,maxChainLength:o=8}=t,a=Q(e,i),l=Yy(a,s,o);if(l.length===0)return[];let c=Uy(l);return c.length<2?[]:Ky(qy(c,n,r),r)}function Uy(e){let t=Vy(e),n=[];for(let r of e){let i=r.filter(s=>!t.has(s));i.length>=2&&n.push({original:r,filtered:i})}return n}function Vy(e){let{nodeFreq:t,tailFreq:n}=Jy(e),r=e.length*.9,i=e.length*.8,s=new Set;for(let[a,l]of t)l>r&&s.add(a);for(let[a,l]of n)l>i&&s.add(a);let o=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let l=a.split("/").pop()??"";o.includes(l)&&s.add(a)}return s}function Jy(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let s of r)i.has(s)||(t.set(s,(t.get(s)??0)+1),i.add(s));for(let s=Math.max(0,r.length-2);s<r.length;s++)n.set(r[s],(n.get(r[s])??0)+1)}return{nodeFreq:t,tailFreq:n}}function qy(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let s=i+1;s<e.length;s++){let o=zy(e[i],e[s],t);o&&r.push(o)}if(r.length>n*10)break}return r.sort((i,s)=>Math.abs(s.similarity-i.similarity)>.01?s.similarity-i.similarity:i.divergencePoints.length-s.divergencePoints.length),r}function zy(e,t,n){if(!Gy(e.filtered,t.filtered))return null;let{distance:r,ops:i}=Qy(e.filtered,t.filtered),s=Math.max(e.filtered.length,t.filtered.length);if(s===0)return null;let o=1-r/s;if(o<n||r===0)return null;let a=i.filter(c=>c.type==="substitute").map(c=>({index:c.indexA,nodeA:e.filtered[c.indexA],nodeB:t.filtered[c.indexB]}));return a.length===0||i.filter(c=>c.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:o,editDistance:r,divergencePoints:a,commonPrefix:Xy(e.original,t.original),commonSuffix:Zy(e.original,t.original)}}function Gy(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function Ky(e,t){let n=[];for(let r of e)if(n.some(s=>Ua(r.chainA,s.chainA)&&Ua(r.chainB,s.chainB))||n.push(r),n.length>=t)break;return n}function Yy(e,t,n){let r=[];for(let s of e.keys()){if(r.length>=500)break;Ja(e,s,[s],new Set([s]),t,n,r,500)}return r}function Ja(e,t,n,r,i,s,o,a){if(o.length>=a)return;if(n.length>=s){n.length>=i&&o.push([...n]);return}let l=e.get(t);if(!l||l.size===0){n.length>=i&&o.push([...n]);return}let c=!1;for(let u of l)if(!r.has(u)&&(r.add(u),n.push(u),Ja(e,u,n,r,i,s,o,a),n.pop(),r.delete(u),c=!0,o.length>=a))return;!c&&n.length>=i&&o.push([...n])}function Qy(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let l=0;l<=n;l++)i[l][0]=l;for(let l=0;l<=r;l++)i[0][l]=l;for(let l=1;l<=n;l++)for(let c=1;c<=r;c++)e[l-1]===t[c-1]?i[l][c]=i[l-1][c-1]:i[l][c]=1+Math.min(i[l-1][c],i[l][c-1],i[l-1][c-1]);let s=[],o=n,a=r;for(;o>0||a>0;)o>0&&a>0&&e[o-1]===t[a-1]?(s.unshift({type:"match",indexA:o-1,indexB:a-1}),o--,a--):o>0&&a>0&&i[o][a]===i[o-1][a-1]+1?(s.unshift({type:"substitute",indexA:o-1,indexB:a-1}),o--,a--):a>0&&i[o][a]===i[o][a-1]+1?(s.unshift({type:"insert",indexA:o,indexB:a-1}),a--):(s.unshift({type:"delete",indexA:o-1,indexB:a}),o--);return{distance:i[n][r],ops:s}}function Xy(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function Zy(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function Ua(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function Ln(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:s=20,scanLimit:o}=t,a=new v(e),l=a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),c=ob(l,o),u=a.calleeMap(c),d=[];for(let m of c){let f=eb(m,u.get(m.symbolId)??[],i);f&&d.push(f)}return d.sort((m,f)=>f.clusters.length-m.clusters.length||f.loc-m.loc),d.slice(0,s)}function eb(e,t,n){let r=new Set(t.map(a=>a.symbol));if(r.size<n)return null;let i=tb(r,t),s=nb(r,i);if(s.length<2)return null;let o=rb(s,i);return o.length===0?null:{symbol:e.symbol,shortName:g(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:sb(e),totalCallees:r.size,clusters:o}}function tb(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let s=r.get(i.chunkId);s||(s=new Set,r.set(i.chunkId,s)),s.add(i.symbol)}for(let i of r.values()){let s=[...i];for(let o=0;o<s.length;o++)for(let a=o+1;a<s.length;a++)n.get(s[o]).add(s[a]),n.get(s[a]).add(s[o])}return n}function nb(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let s=new Set,o=[i];for(;o.length>0;){let a=o.pop();if(!n.has(a)){n.add(a),s.add(a);for(let l of t.get(a)??[])n.has(l)||o.push(l)}}r.push(s)}return r}function rb(e,t){return e.filter(n=>n.size>=3).map(n=>ib(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function ib(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let l of a)r.add(l);let i=0;for(let a of e)for(let l of n.get(a)??[])r.has(l)&&i++;let s=e.size*r.size,o=s>0?1-i/s:1;return{callees:[...e].map(g),isolation:o}}function sb(e){return e.endLine-e.startLine+1}function ob(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function qa(e,t,n={}){let{maxDepth:r=5,scope:i}=n,s=L(e,t);if(!s)return[];let o=[],a=new Set([s.symbolId]),l=new Set,c=[s];for(let u=1;u<=r&&c.length!==0;u++){let d=[];for(let m of c)for(let f of ab(e,m,i)){let h=`${f.file}|${f.shortName}`;if(f.symbolId!==null){if(a.has(f.symbolId))continue;a.add(f.symbolId)}else if(l.has(h))continue;l.add(h),o.push({symbol:f.symbol,shortName:f.shortName,file:f.file,depth:u}),f.symbolId!==null&&f.symbolMatch&&d.push(f.symbolMatch)}c=d}return o.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),o}function ab(e,t,n){let r=ie(e,t,{limit:500}).filter(c=>!e.isIgnored(c.file)).filter(c=>!n||c.file.includes(n)),i=new Set(r.map(c=>c.file)),s=[];for(let c of lb(e,t,n)){if(i.has(c))continue;let u=z(e,c),d=u.length>0?ae(u,u[0].startLine):null;s.push({symbol:d?.symbol??c,file:c})}let o=[...r,...s],a=[],l=new Set;for(let c of o){let u=ot(e,c.symbol);if(!u){let m=`${c.file}|${c.symbol}`;if(l.has(m))continue;l.add(m),a.push({symbolId:null,symbol:c.symbol,shortName:g(c.symbol),file:c.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!cb(u.symbol))continue;let d=`${u.symbolId}|${u.relativePath}`;l.has(d)||(l.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:g(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function lb(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
813
|
+
FROM mentions m
|
|
814
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
815
|
+
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
816
|
+
WHERE m.symbol_id = ?
|
|
817
|
+
AND m.role != 1
|
|
818
|
+
AND c.document_id != ?
|
|
819
|
+
${e.pathExclusionsFor("consumer_d")}
|
|
820
|
+
${r}`,...i).map(s=>s.relative_path).filter(s=>!e.isIgnored(s)))}function cb(e){let t=U(e);return t==="method"||t==="type"||e.endsWith("().")}function za(e,t){let n=K(e,t);if(!n)return null;let r=ub(e,n);if(!r||e.isIgnored(r.relative_path))return null;let i=[],s=0,o=db(e,r.relative_path),a=mt(e,o);for(let l of o){let c=mb(e,r,l,a.get(l.symbolId)??new Set);s+=c,i.push({symbol:l.symbol,shortName:g(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:c,riskLevel:pb(c)})}return{file:r.relative_path,symbols:i,totalExternalConsumers:s}}function ub(e,t){return e.get(`SELECT id, relative_path FROM documents
|
|
812
821
|
WHERE relative_path = ?
|
|
813
822
|
${e.pathExclusionsFor("documents")}
|
|
814
|
-
LIMIT 1`,t)??null}function
|
|
823
|
+
LIMIT 1`,t)??null}function db(e,t){return new v(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function mb(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
815
824
|
FROM mentions m
|
|
816
825
|
JOIN chunks c ON m.chunk_id = c.id
|
|
817
826
|
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
818
827
|
WHERE m.symbol_id = ?
|
|
819
828
|
AND m.role != 1
|
|
820
|
-
AND c.document_id != ?`,n.symbolId,t.id)
|
|
821
|
-
`)).map(s=>s.trim()).filter(s=>s.length>0))]}function
|
|
829
|
+
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(s=>s.relative_path),...[...r].filter(s=>s!==t.relative_path)]).size}function pb(e){return e>10?"high":e>0?"medium":"low"}import{execFileSync as Wr}from"child_process";function Ka(e,t={}){let n=Ur(e,t);return n.note?fb(n.note,n.changedFileLines):n.changedFiles.length===0?gb(n.changedFileLines):Jr(n.changedFiles,[Vr(e,n.changedFiles,n.changedFiles)])}function Ur(e,t={}){let{base:n="HEAD"}=t;try{let r=hb(e.config.projectRoot,n);return{changedFileLines:r,changedFiles:yb(e,r),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],note:"Unable to compute git diff."}}}function Vr(e,t,n){let r=new v(e),i=new Set(n),s=[],o=new Map,a=t.flatMap(c=>r.definitionsForFile(c)).filter(Ib).sort((c,u)=>c.relativePath.localeCompare(u.relativePath)||c.startLine-u.startLine),l=mt(e,a);for(let c of a)bb(e,c,n,i,s,o,l.get(c.symbolId)??new Set);return{changedSymbols:s,consumerEntries:[...o.entries()].map(([c,u])=>({file:c,symbols:[...u].sort()}))}}function Jr(e,t){let n=new Map,r=t.flatMap(s=>s.changedSymbols);for(let s of t)for(let o of s.consumerEntries){let a=n.get(o.file);a||(a=new Set,n.set(o.file,a));for(let l of o.symbols)a.add(l)}let i=_b(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function fb(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function gb(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function hb(e,t){let n=Wr("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=Wr("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=Wr("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(s=>s.split(`
|
|
830
|
+
`)).map(s=>s.trim()).filter(s=>s.length>0))]}function yb(e,t){let n=[];for(let r of t){let i=e.get(`SELECT relative_path FROM documents
|
|
822
831
|
WHERE relative_path LIKE ?
|
|
823
|
-
LIMIT 1`,`%${r}`);i&&!e.isIgnored(i.relative_path)&&n.push(i.relative_path)}return n}function
|
|
832
|
+
LIMIT 1`,`%${r}`);i&&!e.isIgnored(i.relative_path)&&n.push(i.relative_path)}return n}function bb(e,t,n,r,i,s,o){let a=Math.max(Sb(e,t.symbolId),o.size);if(!Rb(t,a))return;let l=g(t.symbol);i.push({symbol:t.symbol,shortName:l,file:t.relativePath,fanIn:a});for(let c of xb(e,t.symbolId,n))Ga(e,r,s,c,l);for(let c of o)Ga(e,r,s,c,l)}function Sb(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS fan_in
|
|
824
833
|
FROM mentions m
|
|
825
834
|
JOIN chunks c ON m.chunk_id = c.id
|
|
826
835
|
WHERE m.symbol_id = ?
|
|
827
|
-
AND m.role != 1`,t)?.fan_in??0}function
|
|
836
|
+
AND m.role != 1`,t)?.fan_in??0}function xb(e,t,n){return n.length===0?[]:e.all(`SELECT DISTINCT ref_d.relative_path
|
|
828
837
|
FROM mentions m
|
|
829
838
|
JOIN chunks c ON m.chunk_id = c.id
|
|
830
839
|
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
831
840
|
WHERE m.symbol_id = ?
|
|
832
841
|
AND m.role != 1
|
|
833
842
|
AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
|
|
834
|
-
${e.pathExclusionsFor("ref_d")}`,t,...n).map(i=>i.relative_path)}function
|
|
843
|
+
${e.pathExclusionsFor("ref_d")}`,t,...n).map(i=>i.relative_path)}function Ga(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let s=n.get(r);s||(s=new Set,n.set(r,s)),s.add(i)}function _b(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function Ib(e){return!(ke(e.symbol)||e.parentTypeName!==null&&!V(e.symbol))}function Rb(e,t){return V(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}import Ft from"path";function Ye(e){let n=e.replace(/\\/g,"/").split("/").filter(Boolean);return n.length<=1?"(root)":n.length>=3&&["src","lib","app","server","client"].includes(n[0])?`${n[0]}/${n[1]}`:n[0]}function qr(e,t){if(e===t)return"ok";let n=wn(e),r=wn(t);return n&&r?Cb(n,r)?"ok":"violation":vb(e,t)}function Ya(e,t){let n=wn(Ye(e)),r=wn(Ye(t));return!!n&&!!r}function wn(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function Cb(e,t){return t==="domain"?!0:e==="domain"?!1:{analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),"language-parsers":new Set(["domain","resolution","source","storage"]),queries:new Set(["analysis","core","domain","language-parsers","resolution","semantic","source","storage","symbols"]),reindex:new Set(["domain","language-parsers","resolution","runtime","source","storage","symbols"]),resolution:new Set(["domain","source","storage","symbols"]),runtime:new Set(["domain","queries","reindex","resolution","source","storage","symbols"]),semantic:new Set(["domain","resolution","storage","symbols"]),source:new Set(["domain","storage"]),storage:new Set(["domain","source"]),symbols:new Set(["analysis","domain","language-parsers","resolution","semantic","source","storage"])}[e]?.has(t)??!1}function vb(e,t){if(t==="shared")return"ok";let n={app:new Set(["core","shared","ui"]),core:new Set(["shared"]),infra:new Set(["core","shared"]),ui:new Set(["core","shared"])};return n[e]?n[e].has(t)?"ok":"violation":null}function kn(e,t){let{scope:n,minDeviation:r=5}=t??{},s=new v(e).fileDependencyGraph(n),o=Pb(e,n);return Lb([...Nb(e,s,o),...Eb(s),...Db(s,r)])}function Nb(e,t,n){let r=[];for(let[i,s]of t){if(ve(i))continue;let o=n.get(i)??new Set;for(let a of s)if(!ve(a)&&!o.has(a)){if($b(e,i,a)||jb(e,i,a)||Bb(e,i,a)||Ab(a)||Wb(e,i,a)||Hb(a))continue;r.push({file:i,kind:"unused-import",description:`Depends on ${a} but references none of its symbols`,dep:a})}}return r}function Eb(e){let t=[],n=Fb(e);for(let[r,i]of e){if(ve(r))continue;let s=Ye(r);for(let o of i){if(ve(o))continue;let a=Ye(o);if(s===a)continue;(qr(s,a)??n.get(`${s}->${a}`))==="violation"&&t.push({file:r,kind:"layer-violation",description:`Imports from ${a}/ (${o}) \u2014 may cross architectural boundary`,dep:o,detail:`${s}/ should not depend on ${a}/`})}}return t}function Db(e,t){let n=[];for(let[r,i]of wb(e)){let s=i.filter(a=>!ve(a));if(s.length<t)continue;let o=kb(e,s);for(let a of s)for(let l of e.get(a)??[])ve(l)||(o.get(l)??0)===1&&Ft.dirname(l)!==r&&Ft.dirname(l)!==Ft.dirname(r)&&(Ya(a,l)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${l}`,dep:l}))}return n}function Lb(e){return{results:e,unusedImports:e.filter(t=>t.kind==="unused-import").length,layerViolations:e.filter(t=>t.kind==="layer-violation").length,patternDeviations:e.filter(t=>t.kind==="pattern-deviation").length}}function wb(e){let t=new Map;for(let n of e.keys()){let r=Ft.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function kb(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])ve(i)||n.set(i,(n.get(i)??0)+1);return n}function Pb(e,t){let n=new Map;return Ob(e,n,t),Tb(e,n),n}function Ob(e,t,n){for(let r of Mb(e,n))Qa(e,t,r.from_file,r.to_file)}function Mb(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
|
|
835
844
|
FROM mentions m
|
|
836
845
|
JOIN chunks c ON m.chunk_id = c.id
|
|
837
846
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -847,25 +856,25 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
847
856
|
WHERE d1.id != d2.id
|
|
848
857
|
AND m.role != 1
|
|
849
858
|
${e.pathExclusionsFor("d1","d2")}
|
|
850
|
-
${n}`)}function
|
|
851
|
-
WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`);n.scanSourceReferences({paths:r.map(i=>i.relative_path),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||
|
|
859
|
+
${n}`)}function Tb(e,t){let n=new v(e),r=e.all(`SELECT relative_path FROM documents
|
|
860
|
+
WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`);n.scanSourceReferences({paths:r.map(i=>i.relative_path),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||Qa(e,t,i.sourceFile,i.target.relativePath))})}function Qa(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function Fb(e){let t=new Map;for(let[r,i]of e){if(ve(r))continue;let s=Ye(r);for(let o of i){if(ve(o))continue;let a=Ye(o);if(s===a||qr(s,a))continue;let l=`${s}->${a}`;t.set(l,(t.get(l)??0)+1)}}let n=new Map;for(let[r,i]of t)n.set(r,i<=2?"violation":"ok");return n}function Ab(e){return e.includes("types")||e.endsWith(".d.ts")}function $b(e,t,n){let r=Et(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function jb(e,t,n){let r=J(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function Bb(e,t,n){let r=J(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function Hb(e){return e.endsWith(".vue")}function Wb(e,t,n){let r=J(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function ve(e){let t=ee(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||Ub(Ft.basename(e)))}function Ub(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}import{basename as At,extname as Pn}from"path";function On(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:s}=t??{},o=new v(e),a=Xb(o.fileDependencyGraph(n)),l=eS(Jb(o,n,r).sort((d,m)=>zr(d)-zr(m)||d.relativePath.localeCompare(m.relativePath)),s),c=Qb(o.crossFileCallerMap(l),o.sourceFallbackCallerFiles(l)),u=[];for(let d of l){let m=Vb(e,o,d,{callerFileMap:c,reverseFanIn:a});m&&u.push(m)}return u.sort((d,m)=>m.callerFanIn-d.callerFanIn||m.loc-d.loc),u.slice(0,i)}function Vb(e,t,n,r){let i=qb(t,n,r.callerFileMap);if(i.length!==1)return null;let s=i[0],o=zb(e,n.symbolId,s);if(!o)return null;let a=Gb(t,e,s,n.symbol,o);if(a&&Pe(a.symbol))return null;let l=Kb(r.callerFileMap,r.reverseFanIn,s,a);return l<=3?null:{symbol:n.symbol,shortName:g(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:zr(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?g(a.symbol):At(s),callerFanIn:l}}function zr(e){return e.endLine-e.startLine+1}function Jb(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0})}function qb(e,t,n){let r=At(t.relativePath,Pn(t.relativePath));return[...n.get(t.symbolId)??[]].filter(i=>i!==t.relativePath).filter(i=>At(i,Pn(i))!==r).filter(i=>{let s=e.fileKind(i);return s!=="barrel"&&s!=="entry"&&s!=="test"})}function zb(e,t,n){return e.get(`SELECT c.start_line, c.end_line
|
|
852
861
|
FROM mentions m
|
|
853
862
|
JOIN chunks c ON m.chunk_id = c.id
|
|
854
863
|
JOIN documents d ON c.document_id = d.id
|
|
855
864
|
WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
|
|
856
|
-
LIMIT 1`,t,n)}function
|
|
857
|
-
`),c=0;for(let u=0;u<l.length;u++){if(!a.test(l[u]??""))continue;if(c++,!s.find(m=>m.startLine<=u&&u<=m.endLine))return!1}return c>0}function
|
|
858
|
-
`),s=Math.max(0,n-2),o=Math.min(i.length-1,n+2);for(let a=s;a<=o;a++){let c=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(c))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(c))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(c))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(c))return"enum"}return"other"}function
|
|
859
|
-
`);for(let a=0;a<o.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&s.test(o[a]??""))return!0;return!1}function $b(e,t,n){return e===0?{confidence:"high",reason:"unused \u2014 no consumers and defining file has no real usage"}:e===1&&t==="class"?{confidence:"low",reason:"1 consumer + class kind \u2014 likely 1:1 encapsulation, not over-abstraction"}:e===1&&!n?{confidence:"high",reason:"1 consumer + defining file never uses it \u2014 type belongs with its consumer"}:{confidence:"medium",reason:"1 consumer \u2014 single-use abstraction"}}function Fr(e){return e.endLine-e.startLine+1}function Da(...e){let t=new Map;for(let n of e)for(let[r,i]of n){let s=t.get(r);s||(s=new Set,t.set(r,s));for(let o of i)s.add(o)}return t}function Pn(e,t){let{scope:n,minLoc:r=10,limit:i=30}=t??{},{definitions:s,callerMap:o,calleeMap:a}=Ab(e,n);return s.map(l=>{let c=l.endLine-l.startLine+1,u=o.get(l.symbolId)?.size??0,d=a.get(l.symbolId)??[],m=d.filter(f=>f.file!==l.relativePath),g=new Set(m.map(f=>`${f.symbol}|${f.file}`)).size,p=new Set(d.map(f=>`${f.symbol}|${f.file}`)).size;return{symbol:l.symbol,shortName:h(l.symbol),file:l.relativePath,startLine:l.startLine,endLine:l.endLine,loc:c,fanIn:u,fanOut:g,calleeCount:p,score:Math.round(c/50*(u/5)*Math.max(g/5,1)*100)/100}}).filter(l=>l.loc>=r).sort((l,c)=>c.score-l.score||c.loc-l.loc).slice(0,i)}function Ab(e,t){let n=new C(e),r=n.productionCallableDefinitions({scope:t,requireCallableSymbol:!0,includeSuppressed:!0});return{definitions:r,callerMap:n.crossFileCallerMap(r),calleeMap:n.calleeMap(r)}}var jb=50;function La(e,t={}){let n=Bb(e,t.scope),r=Wb(e,n),i=Hb(n,r);return{score:Vb(n,r),overview:{documents:n.statsResult.documents,symbols:n.statsResult.symbols,indexSizeBytes:n.statsResult.indexSizeBytes},findings:{deadSymbols:r.trueDeadCount,deadLoc:r.trueDeadLoc,isolatedSymbols:r.trueIsolatedCount,isolatedLoc:r.trueIsolatedLoc,cycles:r.realCycleCount,similarPairs:r.trueSimilarCount,extractionCandidates:n.extractResult.length,wrappers:n.wrapperResult.length,passthroughs:n.passthroughResult.length,staleTypes:r.trueStaleCount,driftedFiles:r.trueDriftCount,complexityHotspotCount:ka(n)},actions:i,topComplexity:n.complexResult.slice(0,5).map(o=>({symbol:o.shortName,score:o.score}))}}function Bb(e,t){return{statsResult:Zt(e),deadResult:_n(e,{scope:t,minLoc:3,skipBarrels:!0}),isolatedResult:Rn(e,{scope:t,minLoc:3}),cycleResult:In(e,{scope:t}),similarResult:Cn(e,{scope:t,minSimilarity:.6,limit:50,minCallees:4}),extractResult:vn(e,{scope:t,minLoc:15,minCallees:5,limit:50}),wrapperResult:Ln(e,{scope:t,maxLoc:15,limit:50}),passthroughResult:kn(e,{scope:t,maxLoc:15,limit:50}),staleResult:wn(e,{scope:t,minLoc:3,limit:50}),driftResult:En(e,{scope:t}),complexResult:Pn(e,{scope:t,minLoc:10,limit:10})}}function Wb(e,t){let n=t.deadResult.symbols.filter(i=>!ze(e,i.relativePath)&&!Lt(e,i.symbol,i.relativePath)&&i.kind==="dead-code"),r=t.isolatedResult.filter(i=>!ze(e,i.relativePath)&&!Lt(e,i.symbol,i.relativePath));return{trueDeadCount:n.length,trueDeadLoc:n.reduce((i,s)=>i+s.loc,0),trueIsolatedCount:r.length,trueIsolatedLoc:r.reduce((i,s)=>i+s.loc,0),trueStaleCount:t.staleResult.length,trueDriftCount:t.driftResult.unusedImports+t.driftResult.layerViolations,trueSimilarCount:t.similarResult.length,realCycleCount:t.cycleResult.filter(i=>i.kind==="real").length}}function Hb(e,t){let n=[];if(t.trueDeadCount>0&&n.push({category:"Dead code",description:`${t.trueDeadCount} symbols with zero references anywhere \u2014 safe to delete`,effort:"low",impact:"high",count:t.trueDeadCount,locRecoverable:t.trueDeadLoc}),t.trueIsolatedCount>0&&n.push({category:"Isolated symbols",description:`${t.trueIsolatedCount} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:t.trueIsolatedCount,locRecoverable:t.trueIsolatedLoc}),t.realCycleCount>0&&n.push({category:"Circular dependencies",description:`${t.realCycleCount} cycle(s) \u2014 break with dependency inversion or module restructuring`,effort:"medium",impact:"high",count:t.realCycleCount,locRecoverable:0}),t.trueSimilarCount>0&&n.push({category:"Similar functions",description:`${t.trueSimilarCount} pairs with real logic overlap (beyond shared imports) \u2014 consolidation candidates`,effort:"medium",impact:"medium",count:t.trueSimilarCount,locRecoverable:0}),e.extractResult.length>0&&n.push({category:"Extraction candidates",description:`${e.extractResult.length} large functions with isolated callee clusters \u2014 extract method opportunities`,effort:"medium",impact:"medium",count:e.extractResult.length,locRecoverable:0}),e.wrapperResult.length>0&&n.push({category:"Wrapper functions",description:`${e.wrapperResult.length} single-consumer symbols that could be inlined`,effort:"low",impact:"low",count:e.wrapperResult.length,locRecoverable:e.wrapperResult.reduce((s,o)=>s+o.loc,0)}),e.passthroughResult.length>0&&n.push({category:"Passthrough functions",description:`${e.passthroughResult.length} functions that just forward to one callee \u2014 unnecessary indirection`,effort:"low",impact:"low",count:e.passthroughResult.length,locRecoverable:e.passthroughResult.reduce((s,o)=>s+o.loc,0)}),t.trueStaleCount>0){let s=e.staleResult.filter(l=>l.consumers===0).length,o=t.trueStaleCount-s,a=[];s>0&&a.push(`${s} unused`),o>0&&a.push(`${o} single-consumer (not in types file)`),n.push({category:"Stale abstractions",description:`${a.join(", ")} \u2014 premature abstraction`,effort:"low",impact:"medium",count:t.trueStaleCount,locRecoverable:e.staleResult.reduce((l,c)=>l+c.loc,0)})}if(t.trueDriftCount>0){let s=[];e.driftResult.unusedImports>0&&s.push(`${e.driftResult.unusedImports} unused imports`),e.driftResult.layerViolations>0&&s.push(`${e.driftResult.layerViolations} layer violations`),n.push({category:"Structural drift",description:s.join(", "),effort:e.driftResult.layerViolations>0?"medium":"low",impact:e.driftResult.layerViolations>0?"medium":"low",count:t.trueDriftCount,locRecoverable:0})}let r={high:3,medium:2,low:1},i={low:3,medium:2,high:1};return n.sort((s,o)=>{let a=r[s.impact]*i[s.effort];return r[o.impact]*i[o.effort]-a}),n}function Vb(e,t){let n=Math.max(e.statsResult.documents,1),r=Math.max(e.statsResult.symbols,1),i=100,s=t.trueDeadCount/r;i-=Math.min(20,Math.round(s*200));let o=t.trueIsolatedCount/r;i-=Math.min(10,Math.round(o*200)),i-=Math.min(15,t.realCycleCount*5);let a=t.trueSimilarCount/r*1e3;i-=Math.min(10,Math.round(a));let l=e.extractResult.length/r*1e3;i-=Math.min(5,Math.round(l/2)),i-=Math.min(3,e.wrapperResult.length),i-=Math.min(3,e.passthroughResult.length);let c=t.trueStaleCount/Math.max(r*.1,1);i-=Math.min(8,Math.round(c*10));let u=t.trueDriftCount/n;i-=Math.min(5,Math.round(u*50));let d=ka(e);return i-=Math.min(5,d*2),Math.max(0,Math.min(100,i))}function ka(e){return e.complexResult.filter(t=>t.score>jb).length}function wa(e,t,n){let r=E(e,t),i=E(e,n);if(!r||!i)return null;let s=new Set(Z(e,r).map(f=>f.symbol)),o=new Set(Z(e,i).map(f=>f.symbol)),a=[];for(let f of s)o.has(f)&&a.push(f);let l=[];for(let f of s)o.has(f)||l.push(f);let c=[];for(let f of o)s.has(f)||c.push(f);let u=new Set([...s,...o]),d=u.size>0?a.length/u.size:0,m;u.size===0?m="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":a.length===0?m="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&c.length===0?m="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":l.length===0?m="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":c.length===0?m="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":l.length<=2&&c.length<=2?m=`Create a shared function with the ${a.length} common callees. Pass the ${l.length+c.length} divergent callees as parameters or strategy callbacks.`:m=`Extract the ${a.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${c.length} in B).`;let g=r.endLine-r.startLine+1,p=i.endLine-i.startLine+1;return{symbolA:{symbol:r.symbol,shortName:h(r.symbol),file:r.relativePath,loc:g},symbolB:{symbol:i.symbol,shortName:h(i.symbol),file:i.relativePath,loc:p},similarity:d,sharedCallees:a.map(h),uniqueToA:l.map(h),uniqueToB:c.map(h),consolidationStrategy:m}}import{readFileSync as Pa}from"fs";import{extname as Ub,join as Oa}from"path";function Ma(e,t,n={}){let{context:r=0}=n,i=Jb(t);if(i)return zb(e,i.filePath,i.startLine,i.endLine,r);let s=E(e,t);return s?qb(e,s,r):null}function Jb(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);return t?{filePath:t[1],startLine:parseInt(t[2],10),endLine:parseInt(t[3],10)}:null}function qb(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=Oa(e.config.projectRoot,t.relativePath),s;try{s=Pa(i,"utf-8")}catch{return null}let o=s.split(`
|
|
865
|
+
LIMIT 1`,t,n)}function Gb(e,t,n,r,i){let s=e.definitionsForFile(n),o=Yb(t,n,r,i.start_line,i.end_line);return ae(s,o)}function Kb(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(s=>s!==r.relativePath);if(i.length>0)return i.length}return Zb(t,n)}function Yb(e,t,n,r,i){let s=w(n);if(!s)return r;let o=Ge(e,t).get(s);if(!o||o.length===0)return r;for(let a of o)if(a>=r&&a<=i)return a;return r}function Qb(...e){let t=new Map;for(let n of e)for(let[r,i]of n){let s=t.get(r);s||(s=new Set,t.set(r,s));for(let o of i)s.add(o)}return t}function Xb(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function Zb(e,t){let n=e.get(t)??0;if(n>0)return n;let r=At(t,Pn(t)),i=0;for(let[s,o]of e)s!==t&&At(s,Pn(s))===r&&o>i&&(i=o);return i}function eS(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Za(e,t,n,r){let i=T(t);if(!i)return!0;let s=O(e,t);if(!s)return!0;let o=Xa.get(s);return o||(o=tS(s,i),Xa.set(s,o)),o.get(`${n}:${r}`)??!0}var Xa=new WeakMap;function tS(e,t){let n=t==="rust"?new Set(["function_item","function_signature_item"]):t==="python"?new Set(["function_definition"]):new Set(["function_declaration","method_definition","arrow_function","function_expression"]),r=new Map,i=s=>{n.has(s.type)&&r.set(`${s.startPosition.row}:${s.endPosition.row}`,nS(s,t));for(let o of s.children)i(o)};return i(e.rootNode),r}function nS(e,t){let n=e.namedChildren.find(d=>d.type==="block"||d.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(d=>d.type!=="comment"&&d.type!=="line_comment"&&d.type!=="block_comment");if(r.length!==1)return!1;let i=r[0],s=null;if(i.type==="return_statement"||i.type==="expression_statement"?s=i.namedChild(0)??null:t==="rust"&&(i.type==="call_expression"||i.type==="macro_invocation")&&(s=i),!s)return!1;let o=t==="python"?"call":"call_expression";if(s.type!==o)return!1;let a=s.namedChildren.find(d=>d.type==="arguments"||d.type==="argument_list");if(!a)return!1;let l=a.namedChildren.filter(d=>d.type!=="comment"),c=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!c)return!1;let u=[];for(let d of c.namedChildren)if(d.type==="identifier")u.push(d.text);else{let m=d.namedChildren.find(f=>f.type==="identifier");m&&u.push(m.text)}if(l.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let m=l[d];if(m.type!=="identifier"||m.text!==u[d])return!1}return!0}function Mn(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:s}=t??{},o=new v(e),a=oS(sS(o,n,r).sort((u,d)=>Gr(u)-Gr(d)||u.relativePath.localeCompare(d.relativePath)),s),l=o.calleeMap(a),c=[];for(let u of a){let d=rS(e,u,l.get(u.symbolId)??[]);d&&c.push(d)}return c.sort((u,d)=>u.loc-d.loc||u.file.localeCompare(d.file)),c.slice(0,i)}function rS(e,t,n){let r=iS(n);if(r.size!==1||!Za(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0];return{symbol:t.symbol,shortName:g(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:Gr(t),forwardsTo:i.symbol,forwardsToShort:g(i.symbol),forwardsToFile:i.file}}function iS(e){let t=e.some(r=>H(r.symbol))?e.filter(r=>H(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function sS(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0})}function Gr(e){return e.endLine-e.startLine+1}function oS(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Tn(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:s=30,includeLowConfidence:o=!1,scanLimit:a}=t??{},l=new v(e),c=l.scopedDefinitions(n),u=bS(l,n),d=CS(aS(e,l,c,{minLoc:r,maxLoc:i}).sort((_,E)=>$t(E)-$t(_)||_.relativePath.localeCompare(E.relativePath)),a),m=lS(l,d),f=mS(e,l,c,d),h=cS(d);return uS(e,d,m,h).filter(_=>!f.has(_.definition.symbolId)).filter(_=>!_.transitivelyReachable).filter(_=>_.realConsumers.length<=1).filter(_=>!(_.realConsumers.length===0&&_.barrelConsumers>0)).filter(_=>xS(_.definition,_.realConsumers.length,u)).map(_=>dS(e,_)).filter(_=>o||_.confidence!=="low").sort((_,E)=>{let F={high:0,medium:1,low:2};return F[_.confidence]-F[E.confidence]||E.loc-_.loc||_.file.localeCompare(E.file)||_.startLine-E.startLine}).slice(0,s)}function aS(e,t,n,r){return n.filter(i=>i.isTypeLike&&$t(i)>=r.minLoc).filter(i=>$t(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!SS(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function lS(e,t){return ol(e.crossFileCallerMap(t),e.sourceFallbackCallerFiles(t))}function cS(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=w(n.symbol);i&&r.set(i,n)}return t}function uS(e,t,n,r){return t.map(i=>{let o=[...n.get(i.symbolId)??new Set].filter(u=>u!==i.relativePath&&!e.isIgnored(u)),{realConsumers:a,barrelConsumers:l}=_S(e,i.relativePath,i.symbol,o),c=IS(e,i,n,r);return{definition:i,realConsumers:a,barrelConsumers:l,transitivelyReachable:c}})}function dS(e,t){let n=sl(e,t.definition.relativePath,t.definition.startLine),r=tl(t.definition.relativePath)?!0:NS(e,t.definition),{confidence:i,reason:s}=ES(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:g(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:$t(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:s}}function mS(e,t,n,r){let i=fS(e,pS(n),r),s=i.map(l=>l.singleton);if(i.length===0)return new Set;let o=ol(t.crossFileCallerMap(s),t.sourceFallbackCallerFiles(s)),a=new Set;for(let{singleton:l,classId:c}of i)hS(e,l,o)&&a.add(c);return a}function pS(e){let t=new Map;for(let n of e){let r=w(n.symbol);r&&t.set(el(n.relativePath,r),n)}return t}function fS(e,t,n){let r=[];for(let i of n){let s=gS(e,t,i);s&&r.push({singleton:s,classId:i.symbolId})}return r}function gS(e,t,n){if(sl(e,n.relativePath,n.startLine)!=="class")return null;let r=w(n.symbol);if(!r)return null;let i=yS(e,n.relativePath,r);return i?t.get(el(n.relativePath,i))??null:null}function hS(e,t,n){let r=w(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(s=>s!==t.relativePath&&!e.isIgnored(s)&&!rl(e,s,r))}function el(e,t){return`${e}\0${t}`}function yS(e,t,n){let r=P(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(s)?.[1]??null}function bS(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function SS(e){let t=W(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function tl(e){let n=(e.split("/").pop()??"").replace(/\.[^.]+$/,"");return!!(n==="types"||n==="models"||n==="schema"||n==="common"||n==="protocol"||n==="proto"||n==="dto"||n==="mod"||/(^|\/)types(\/|\.)/.test(e)||/(^|\/)models?(\/|\.)/.test(e)||/(^|\/)proto(?:col)?(\/|\.)/.test(e)||/(^|\/)schema(\/|\.)/.test(e))}function xS(e,t,n){return!(tl(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function _S(e,t,n,r){let i=[],s=0,o=w(n);for(let a of r)vS(e,a,t,o)||rl(e,a,o)?s++:i.push(a);return{realConsumers:i,barrelConsumers:s}}function IS(e,t,n,r){let i=fs(e,t.relativePath),s=w(t.symbol);if(!s)return!1;let o=i.get(s);if(!o||o.size===0)return!1;let a=r.get(t.relativePath);if(!a)return!1;for(let l of o){let c=a.get(l);if(!c)continue;let u=n.get(c.symbolId);if(u){for(let d of u)if(d!==t.relativePath&&!e.isIgnored(d))return!0}}return!1}var nl=A("stale-abs-file-usage");function rl(e,t,n){if(!n)return!1;let r=T(t);if(!r)return!1;let i=nl.get(e,t,()=>RS(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function RS(e,t,n){let r=new Set,i=new Set,s=O(e,t);if(!s)return{importedLeaves:r,usedLeaves:i};let o=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),a=(l,c)=>{let u=c||o.has(l.type);(l.type==="identifier"||l.type==="type_identifier"||l.type==="property_identifier"||l.type==="field_identifier")&&(u?r.add(l.text):i.add(l.text));for(let d of l.children)a(d,u)};return a(s.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function CS(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function il(e){nl.invalidateAll(e)}function vS(e,t,n,r){if(!r)return!1;let i=P(e,t);if(!i)return!1;let s=xo(e,t);if(s.length===0)return!1;let o=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${o}\\b`),l=i.split(`
|
|
866
|
+
`),c=0;for(let u=0;u<l.length;u++){if(!a.test(l[u]??""))continue;if(c++,!s.find(m=>m.startLine<=u&&u<=m.endLine))return!1}return c>0}function sl(e,t,n){let r=P(e,t);if(!r)return"other";let i=r.split(`
|
|
867
|
+
`),s=Math.max(0,n-2),o=Math.min(i.length-1,n+2);for(let a=s;a<=o;a++){let c=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(c))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(c))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(c))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(c))return"enum"}return"other"}function NS(e,t){let n=P(e,t.relativePath);if(!n)return!1;let r=w(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`),o=n.split(`
|
|
868
|
+
`);for(let a=0;a<o.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&s.test(o[a]??""))return!0;return!1}function ES(e,t,n){return e===0?{confidence:"high",reason:"unused \u2014 no consumers and defining file has no real usage"}:e===1&&t==="class"?{confidence:"low",reason:"1 consumer + class kind \u2014 likely 1:1 encapsulation, not over-abstraction"}:e===1&&!n?{confidence:"high",reason:"1 consumer + defining file never uses it \u2014 type belongs with its consumer"}:{confidence:"medium",reason:"1 consumer \u2014 single-use abstraction"}}function $t(e){return e.endLine-e.startLine+1}function ol(...e){let t=new Map;for(let n of e)for(let[r,i]of n){let s=t.get(r);s||(s=new Set,t.set(r,s));for(let o of i)s.add(o)}return t}function Fn(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:s}=t??{},{definitions:o,callerMap:a,calleeMap:l}=DS(e,n,s);return o.map(c=>{let u=c.endLine-c.startLine+1,d=a.get(c.symbolId)?.size??0,m=l.get(c.symbolId)??[],f=m.filter(y=>y.file!==c.relativePath),h=new Set(f.map(y=>`${y.symbol}|${y.file}`)).size,p=new Set(m.map(y=>`${y.symbol}|${y.file}`)).size;return{symbol:c.symbol,shortName:g(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:u,fanIn:d,fanOut:h,calleeCount:p,score:Math.round(u/50*(d/5)*Math.max(h/5,1)*100)/100}}).filter(c=>c.loc>=r).sort((c,u)=>u.score-c.score||u.loc-c.loc).slice(0,i)}function DS(e,t,n){let r=new v(e),i=LS(r.productionCallableDefinitions({scope:t,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof n=="number"&&n>0}),n);return{definitions:i,callerMap:r.crossFileCallerMap(i),calleeMap:r.calleeMap(i)}}function LS(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}import{getHeapStatistics as wS}from"v8";var kS=64*1024*1024;function Kr(e,t={}){Fo(e),t.semanticProvider===!0&&Tr(e),Us(e),Ro(e),Fs(e),ds(e),ns(e)}function Yr(){let e=globalThis.gc;if(!e)return;let t=wS();t.heap_size_limit-t.used_heap_size<kS||e()}var PS=50,OS=75e3,MS=5e3,al=2500,ll=["overview","dead","isolated","cycles","similar","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots"],TS={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:fl(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:gl(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:hl(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:yl(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:bl(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:Sl(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:xl(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:_l(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:Il(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:Rl(e,t,n)})};function cl(e,t={}){return dl(e,t.full===!0,(n,r)=>{let i=FS(e,t.scope,n,r);return pl(i)})}function ul(e,t,n={}){return dl(e,n.full===!0,(r,i)=>TS[t](e,n.scope,i,r))}function dl(e,t,n){let r=nn(e),i=WS(r,t);try{return n(r,i)}finally{Kr(e,{semanticProvider:!0}),Yr()}}function ml(e){let t=de(e,"overview"),n={statsResult:t.statsResult,warnings:t.warnings,dead:de(e,"dead").dead,isolated:de(e,"isolated").isolated,realCycleCount:de(e,"cycles").realCycleCount,similarCount:de(e,"similar").similarCount,extractCount:de(e,"extract-candidates").extractCount,wrappers:de(e,"wrapper-candidates").wrappers,passthroughs:de(e,"passthrough-candidates").passthroughs,stale:de(e,"stale-abstractions").stale,drift:de(e,"drift").drift,complexity:de(e,"complexity-hotspots").complexity};return pl(n)}function de(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function pl(e){let t=BS(e);return{score:HS(e),overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount},actions:t,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function FS(e,t,n,r){let i=AS(e,t,r),s=$S(e,t,r),o=jS(e,t,r);return{statsResult:n,warnings:r.warnings,...i,...s,...o}}function AS(e,t,n){return{dead:fl(e,t,n),isolated:gl(e,t,n),realCycleCount:hl(e,t,n)}}function $S(e,t,n){return{similarCount:yl(e,t,n),extractCount:bl(e,t,n),wrappers:Sl(e,t,n),passthroughs:xl(e,t,n),stale:_l(e,t,n)}}function jS(e,t,n){return{drift:Il(e,t,n),complexity:Rl(e,t,n)}}function fl(e,t,n){return be(e,n,"dead",()=>{let r=vn(e,{scope:t,minLoc:3,skipBarrels:!0});return An(JS(e,r.symbols))})}function gl(e,t,n){return be(e,n,"isolated",()=>{let r=En(e,{scope:t,minLoc:3});return An(qS(e,r))})}function hl(e,t,n){return be(e,n,"cycles",()=>Nn(e,{scope:t}).filter(i=>i.kind==="real").length)}function yl(e,t,n){return be(e,n,"similar",()=>Dn(e,{scope:t,minSimilarity:.6,limit:50,minCallees:4,scanLimit:n.candidateScanLimit}).length)}function bl(e,t,n){return be(e,n,"extract-candidates",()=>Ln(e,{scope:t,minLoc:15,minCallees:5,limit:50,scanLimit:n.candidateScanLimit}).length)}function Sl(e,t,n){return be(e,n,"wrapper-candidates",()=>An(On(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit})))}function xl(e,t,n){return be(e,n,"passthrough-candidates",()=>An(Mn(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit})))}function _l(e,t,n){return be(e,n,"stale-abstractions",()=>{let r=Tn(e,{scope:t,minLoc:3,limit:50,scanLimit:n.candidateScanLimit}),i=r.filter(s=>s.consumers===0).length;return{count:r.length,loc:r.reduce((s,o)=>s+o.loc,0),unused:i,singleUse:r.length-i}})}function Il(e,t,n){return be(e,n,"drift",()=>{let r=kn(e,{scope:t});return{count:r.unusedImports+r.layerViolations,unusedImports:r.unusedImports,layerViolations:r.layerViolations}})}function Rl(e,t,n){return be(e,n,"complexity-hotspots",()=>{let r=Fn(e,{scope:t,minLoc:10,limit:10,scanLimit:n.candidateScanLimit});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score})),extremeCount:r.filter(i=>i.score>PS).length}})}function BS(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",description:`${e.dead.count} symbols with zero references anywhere \u2014 safe to delete`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",description:`${e.realCycleCount} cycle(s) \u2014 break with dependency inversion or module restructuring`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",description:`${e.similarCount} pairs with real logic overlap (beyond shared imports) \u2014 consolidation candidates`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",description:`${e.extractCount} large functions with isolated callee clusters \u2014 extract method opportunities`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",description:`${e.wrappers.count} single-consumer symbols that could be inlined`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",description:`${e.passthroughs.count} functions that just forward to one callee \u2014 unnecessary indirection`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",description:`${i.join(", ")} \u2014 premature abstraction`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&i.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",description:i.join(", "),effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}let n={high:3,medium:2,low:1},r={low:3,medium:2,high:1};return t.sort((i,s)=>{let o=n[i.impact]*r[i.effort];return n[s.impact]*r[s.effort]-o}),t}function HS(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=100,i=e.dead.count/n;r-=Math.min(20,Math.round(i*200));let s=e.isolated.count/n;r-=Math.min(10,Math.round(s*200)),r-=Math.min(15,e.realCycleCount*5);let o=e.similarCount/n*1e3;r-=Math.min(10,Math.round(o));let a=e.extractCount/n*1e3;r-=Math.min(5,Math.round(a/2)),r-=Math.min(3,e.wrappers.count),r-=Math.min(3,e.passthroughs.count);let l=e.stale.count/Math.max(n*.1,1);r-=Math.min(8,Math.round(l*10));let c=e.drift.count/t;return r-=Math.min(5,Math.round(c*50)),r-=Math.min(5,e.complexity.extremeCount*2),Math.max(0,Math.min(100,r))}function WS(e,t){return e.symbols>=OS||e.documents>=MS?t?{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:["Large index detected; running unbounded health analyses because --full was supplied."]}:{candidateScanLimit:al,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${al} symbols. Run "scip-query health --full" for unbounded candidate counts.`]}:{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:[]}}function US(e,t){t.releaseCachesBetweenPhases&&(il(e),Kr(e),Yr())}function be(e,t,n,r){VS(n);try{return r()}finally{US(e,t)}}function VS(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function JS(e,t){return t.filter(n=>!Ke(e,n.relativePath)&&!kt(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function qS(e,t){return t.filter(n=>!Ke(e,n.relativePath)&&!kt(e,n.symbol,n.relativePath))}function An(e){return{count:e.length,loc:e.reduce((t,n)=>t+n.loc,0)}}function Cl(e,t,n){let r=L(e,t),i=L(e,n);if(!r||!i)return null;let s=new Set(Z(e,r).map(p=>p.symbol)),o=new Set(Z(e,i).map(p=>p.symbol)),a=[];for(let p of s)o.has(p)&&a.push(p);let l=[];for(let p of s)o.has(p)||l.push(p);let c=[];for(let p of o)s.has(p)||c.push(p);let u=new Set([...s,...o]),d=u.size>0?a.length/u.size:0,m;u.size===0?m="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":a.length===0?m="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&c.length===0?m="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":l.length===0?m="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":c.length===0?m="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":l.length<=2&&c.length<=2?m=`Create a shared function with the ${a.length} common callees. Pass the ${l.length+c.length} divergent callees as parameters or strategy callbacks.`:m=`Extract the ${a.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${c.length} in B).`;let f=r.endLine-r.startLine+1,h=i.endLine-i.startLine+1;return{symbolA:{symbol:r.symbol,shortName:g(r.symbol),file:r.relativePath,loc:f},symbolB:{symbol:i.symbol,shortName:g(i.symbol),file:i.relativePath,loc:h},similarity:d,sharedCallees:a.map(g),uniqueToA:l.map(g),uniqueToB:c.map(g),consolidationStrategy:m}}import{readFileSync as vl}from"fs";import{extname as zS,join as Nl}from"path";function El(e,t,n={}){let{context:r=0}=n,i=GS(t);if(i)return YS(e,i.filePath,i.startLine,i.endLine,r);let s=L(e,t);return s?KS(e,s,r):null}function GS(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);return t?{filePath:t[1],startLine:parseInt(t[2],10),endLine:parseInt(t[3],10)}:null}function KS(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=Nl(e.config.projectRoot,t.relativePath),s;try{s=vl(i,"utf-8")}catch{return null}let o=s.split(`
|
|
860
869
|
`),a=Math.max(0,t.startLine-n),l=Math.min(o.length-1,t.endLine+n),c=o.slice(a,l+1).join(`
|
|
861
|
-
`);return{symbol:t.symbol,shortName:
|
|
870
|
+
`);return{symbol:t.symbol,shortName:g(t.symbol),relativePath:t.relativePath,startLine:a,endLine:l,language:r?.language??Dl(t.relativePath),source:c}}function YS(e,t,n,r,i){let s=K(e,t);if(!s)return null;let o=e.get("SELECT relative_path, language FROM documents WHERE relative_path = ?",s);if(!o)return null;let a=Nl(e.config.projectRoot,o.relative_path),l;try{l=vl(a,"utf-8")}catch{return null}let c=l.split(`
|
|
862
871
|
`),u=Math.max(0,n-1-i),d=Math.min(c.length-1,r-1+i),m=c.slice(u,d+1).join(`
|
|
863
|
-
`);return{symbol:`${o.relative_path}:${n}-${r}`,shortName:`${o.relative_path}:${n}-${r}`,relativePath:o.relative_path,startLine:u,endLine:d,language:o.language??
|
|
872
|
+
`);return{symbol:`${o.relative_path}:${n}-${r}`,shortName:`${o.relative_path}:${n}-${r}`,relativePath:o.relative_path,startLine:u,endLine:d,language:o.language??Dl(o.relative_path),source:m}}function Dl(e){switch(zS(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}import{readFileSync as QS}from"fs";import{join as XS}from"path";function Ll(e,t){let n=L(e,t);if(!n)return null;let r=new v(e),i=rx(ex(e,n.relativePath,n.startLine,n.endLine),ZS(e,n.relativePath)),s=n.endLine-n.startLine+1,a=r.calleeMap([n],{additive:!0}).get(n.symbolId)??[],l=new Set(a.map(c=>c.symbol));return{symbol:n.symbol,shortName:g(n.symbol),relativePath:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:s,branches:i,cyclomaticEstimate:i+1,calleeCount:l.size,fanIn:tx(e,n.symbolId),fanOut:nx(a,n.relativePath)}}function ZS(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function ex(e,t,n,r){try{return QS(XS(e.config.projectRoot,t),"utf-8").split(`
|
|
864
873
|
`).slice(n,r+1).join(`
|
|
865
|
-
`)}catch{return""}}function
|
|
874
|
+
`)}catch{return""}}function tx(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
|
|
866
875
|
FROM mentions m
|
|
867
876
|
JOIN chunks c ON m.chunk_id = c.id
|
|
868
|
-
WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function
|
|
877
|
+
WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function nx(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function rx(e,t){let n=ix(e),r=0,i=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let s of i){let o=n.match(s);o&&(r+=o.length)}if(t==="python"){let s=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let o of s){let a=n.match(o);a&&(r+=a.length)}}else if(t==="rust"){let s=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let o of s){let a=n.match(o);a&&(r+=a.length)}}else if(t==="ruby"){let s=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let o of s){let a=n.match(o);a&&(r+=a.length)}}else if(t==="go"){let s=[/\bselect\b/g,/\bdefer\b/g];for(let o of s){let a=n.match(o);a&&(r+=a.length)}}return r}function ix(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*/g,"").replace(/#.*/g,"").replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/'(?:[^'\\]|\\.)*'/g,"''").replace(/`(?:[^`\\]|\\.)*`/g,"``")}function wl(e,t){let n=L(e,t);if(!n)return null;let r=[{file:n.relativePath,line:n.startLine}],i=$e(e,n),o=(i.length>0?i:Ce(e,n)).filter(c=>!e.isIgnored(c.file)).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?g(c.enclosingSymbol):"(top-level)"})),{producers:a,consumers:l}=sx(e,n,o);return{symbol:n.symbol,shortName:g(n.symbol),relativePath:n.relativePath,definitionSites:r.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:g(c.symbol),file:c.file})),consumers:l.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":g(c.symbol),file:c.file}))}}function sx(e,t,n){let r=Qr(Z(e,t,{limit:30}).map(o=>({symbol:o.symbol,file:o.file}))),i=Qr(ie(e,t,{limit:30})),s=i.length>0?i:Qr(n.map(o=>({symbol:o.enclosingSymbol==="(top-level)"?o.file:o.enclosingSymbol,file:o.file})));return{producers:r,consumers:s}}function Qr(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function kl(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,s=L(e,t);return s?r==="backward"?ox(e,s,i):ax(e,s):null}function ox(e,t,n){let r=[],i=new Set([t.symbol]),s=[t];for(let o=1;o<=n&&s.length!==0;o++){let a=[];for(let l of s){let c=Z(e,l);for(let u of c){if(i.has(u.symbol))continue;i.add(u.symbol),r.push({symbol:u.symbol,shortName:g(u.symbol),file:u.file,relationship:o===1?"referenced within definition (callee)":`depth ${o} callee`});let d=ot(e,u.symbol);d&&!e.isIgnored(d.relativePath)&&a.push(d)}}s=a}return{symbol:t.symbol,shortName:g(t.symbol),direction:"backward",connectedSymbols:r}}function ax(e,t){let n=$e(e,t),r=n.length>0?n:Ce(e,t),i=new Set,s=[],o=new v(e);for(let a of r){if(s.length>=30)break;if(e.isIgnored(a.file))continue;let l=a.enclosingSymbol??ae(o.definitionsForFile(a.file),a.line)?.symbol??null;if(!l||l===t.symbol)continue;let c=ot(e,l);!c||e.isIgnored(c.relativePath)||i.has(c.symbol)||(i.add(c.symbol),s.push({symbol:c.symbol,shortName:g(c.symbol),file:c.relativePath,relationship:`references target at ${a.file}:${a.line+1}`}))}return s.sort((a,l)=>a.file.localeCompare(l.file)),{symbol:t.symbol,shortName:g(t.symbol),direction:"forward",connectedSymbols:s}}function Pl(e,t={}){let{scope:n,limit:r}=t,i=new v(e),s=hx([...lx(e,n),...dx(e,i,n)]);return yx(s),r?s.slice(0,r):s}function lx(e,t){let n=[];for(let r of cx(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Ar(e,r.barrel_path))continue;let i=ux(e,r),s=i?.barrel_consumers??0,o=i?.direct_consumers??0;s!==0||o!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:g(r.symbol),originalFile:r.original_path,barrelConsumers:s,directConsumers:o})}return n}function cx(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
|
|
869
878
|
barrel_d.id AS barrel_doc_id,
|
|
870
879
|
barrel_d.relative_path AS barrel_path,
|
|
871
880
|
gs.id AS symbol_id,
|
|
@@ -895,7 +904,7 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
895
904
|
-- Only function-level symbols (ending with ().), not module-level
|
|
896
905
|
AND gs.symbol LIKE '%().'
|
|
897
906
|
${n}
|
|
898
|
-
ORDER BY barrel_d.relative_path, gs.symbol`)}function
|
|
907
|
+
ORDER BY barrel_d.relative_path, gs.symbol`)}function ux(e,t){return e.get(`SELECT
|
|
899
908
|
SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
|
|
900
909
|
SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
|
|
901
910
|
FROM (
|
|
@@ -924,93 +933,95 @@ ${m}`,c+=1+m.length,u+=Vs(m),r+=m.length+1}let d=Sf(l);d&&n.push({...d,start:a,e
|
|
|
924
933
|
AND consumer_d.id != ?
|
|
925
934
|
${e.pathExclusionsFor("consumer_d")}
|
|
926
935
|
GROUP BY consumer_d.id
|
|
927
|
-
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function
|
|
936
|
+
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function dx(e,t,n){let r=[];for(let i of mx(e,n))Ol(e,i,i)>0||r.push(...px(e,t,i));return r}function mx(e,t){return e.all(`SELECT relative_path
|
|
928
937
|
FROM documents
|
|
929
938
|
WHERE 1 = 1
|
|
930
939
|
${t?"AND relative_path LIKE ?":""}
|
|
931
940
|
${e.pathExclusionsFor("documents")}
|
|
932
|
-
ORDER BY relative_path`,...t?[`%${t}%`]:[]).map(r=>r.relative_path).filter(r=>!e.isIgnored(r)).filter(r=>
|
|
941
|
+
ORDER BY relative_path`,...t?[`%${t}%`]:[]).map(r=>r.relative_path).filter(r=>!e.isIgnored(r)).filter(r=>Lr(e,r).length>0)}function px(e,t,n){return Lr(e,n).filter(r=>r.sourcePath&&!e.isIgnored(r.sourcePath)).flatMap(r=>fx(e,t,n,r.sourcePath))}function fx(e,t,n,r){let i=gx(t,r);return i?[{barrelFile:n,symbol:i.symbol,shortName:g(i.symbol),originalFile:r,barrelConsumers:0,directConsumers:Ol(e,r,n)}]:[]}function Ol(e,t,n){let r=e.all(`SELECT relative_path
|
|
933
942
|
FROM documents
|
|
934
943
|
WHERE 1 = 1
|
|
935
944
|
${e.pathExclusionsFor("documents")}
|
|
936
|
-
ORDER BY relative_path`),i=new Set;for(let s of r)if(!(e.isIgnored(s.relative_path)||s.relative_path===n))for(let o of J(e,s.relative_path))o.sourcePath===t&&i.add(s.relative_path);return i.size}function
|
|
937
|
-
`)}
|
|
938
|
-
`).
|
|
939
|
-
|
|
945
|
+
ORDER BY relative_path`),i=new Set;for(let s of r)if(!(e.isIgnored(s.relative_path)||s.relative_path===n))for(let o of J(e,s.relative_path))o.sourcePath===t&&i.add(s.relative_path);return i.size}function gx(e,t){let n=e.definitionsForFile(t);return n.find(r=>U(r.symbol)==="method")??n[0]??null}function hx(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function yx(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function Ml(e,t={}){let{scope:n,minLoc:r=1,limit:i}=t,s=new Map;for(let a of oe(e,{scope:n})){if(!a.isFunctionLike||e.isIgnored(a.relativePath))continue;let l=a.endLine-a.startLine+1;if(l<r)continue;let c=bx(e,a);if(!c)continue;let u={symbol:a.symbol,shortName:g(a.symbol),file:a.relativePath,startLine:a.startLine,endLine:a.endLine,loc:l},d=s.get(c);d?d.push(u):s.set(c,[u])}let o=[];for(let[a,l]of s)l.length<2||o.push({signature:a,functions:l});return o.sort((a,l)=>{let c=l.functions.length-a.functions.length;if(c!==0)return c;let u=a.functions.reduce((m,f)=>m+f.loc,0);return l.functions.reduce((m,f)=>m+f.loc,0)-u}),i?o.slice(0,i):o}function bx(e,t){let n=ko(e,t);if(n)return n;let r=Sx(t.documentation),i=r?Ix(r):null;return i||Rx(xx(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function Sx(e){return Ve(Je(e))}function xx(e,t,n,r,i){let s=P(e,t);if(!s)return null;let o=s.split(/\r?\n/),a=vx(o,n,r,i);for(let l of a){let c=Math.min(o.length-1,Math.max(l,l+4)),u="";for(let d=l;d<=c;d+=1){let m=o[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,_x(u)))return u}if(u&&u.includes("("))return u}return null}function _x(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Nx(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function Ix(e){if(!e||!e.trim())return null;let t=e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim(),n=t.indexOf("(");return n===-1||(t=t.slice(n),t=t.replace(/\s+/g,"").toLowerCase(),t.length<3)?null:t}function Rx(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),o=new RegExp(`\\b${Tl(t)}\\b`,"i").exec(i);o&&typeof o.index=="number"&&(i=i.slice(0,o.index)),i=i.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=Cx(n.slice(r)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let l=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return l.length>=3?l:null}function Cx(e){let t=0,n=0,r=0,i=0,s=null,o=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(s){if(o){o=!1;continue}if(l==="\\"){o=!0;continue}l===s&&(s=null);continue}if(l==='"'||l==="'"||l==="`"){s=l;continue}if(l==="(")t+=1;else if(l===")")t=Math.max(0,t-1);else if(l==="[")r+=1;else if(l==="]")r=Math.max(0,r-1);else if(l==="<")i+=1;else if(l===">")i=Math.max(0,i-1);else if(l==="{"){if(t===0&&r===0&&i===0)return e.slice(0,a);n+=1}else if(l==="}")n=Math.max(0,n-1);else if(l==="="&&e[a+1]===">"&&t===0&&n===0&&r===0&&i===0)return e.slice(0,a)}return e}function vx(e,t,n,r){let i=Tl(r),s=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),o=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],l=new Set,c=Math.max(0,Math.min(t,e.length-1)),u=Math.max(c,Math.min(e.length-1,Math.max(n,t+4)));for(let d=c;d<=u;d+=1){let m=e[d]??"";(s.test(m)||o.test(m))&&!l.has(d)&&(l.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(s.test(m)||o.test(m))&&!l.has(d)&&(l.add(d),a.push(d))}return a}function Nx(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}function Tl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ne(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function jt(e){let t=Ee(e),n=De(e,t);return process.env.SCIP_QUERY_INDEX_DB??(Fl(n.dbPath)?n.dbPath:Ex(e,"index.db"))}function Dx(){let e=Ne(),t=Ee(e),n=De(e,t),r=jt(e);Fl(r)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let i={dbPath:r,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic},s=Xe(e);return new tn(i,s)}function R(e){let t=Dx();try{return e(t)}finally{t.close()}}function Al(e,t){return t.concat([e])}function N(e){return parseInt(e,10)}function Xr(e){let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}function $n(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function $l(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;default:return Lx(e)}}function Lx(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}var kx=wx(import.meta.url),{version:Px}=Mx(),Wl="__health-phase",Ul="__diff-impact-batch",Ox=10;function Mx(){for(let e of["../package.json","../../package.json"])try{return kx(e)}catch{}return{version:"0.0.0"}}function Se(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
|
|
946
|
+
`)}function Tx(e){let t=S.HEALTH_PHASES.map(n=>Fx(n,e));return S.healthReportFromPhases(t)}function Fx(e,t){let n=process.argv[1]??Zr(import.meta.url),r=[...process.execArgv,n,Wl,e];t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full");let i=Hl(process.execPath,r,{cwd:process.cwd(),env:process.env,encoding:"utf8",maxBuffer:10*1024*1024});if(i.status!==0){let s=i.stderr.trim();throw new Error(`Health phase "${e}" failed${s?`:
|
|
947
|
+
${s}`:""}`)}return JSON.parse(i.stdout)}function Ax(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
|
|
948
|
+
Codebase Health Score: ${e.score}/100
|
|
949
|
+
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${$n(e.overview.indexSizeBytes)}
|
|
950
|
+
`),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let r of e.warnings)console.log(` ${r}`);console.log("")}console.log(" Findings:");let n=e.findings;if(n.deadSymbols>0&&console.log(` Dead code: ${n.deadSymbols} symbols (${n.deadLoc} LOC)`),n.isolatedSymbols>0&&console.log(` Isolated symbols: ${n.isolatedSymbols} (${n.isolatedLoc} LOC)`),n.cycles>0&&console.log(` Circular deps: ${n.cycles}`),n.similarPairs>0&&console.log(` Similar pairs: ${n.similarPairs}`),n.extractionCandidates>0&&console.log(` Extract candidates: ${n.extractionCandidates}`),n.wrappers>0&&console.log(` Wrapper functions: ${n.wrappers}`),n.passthroughs>0&&console.log(` Passthroughs: ${n.passthroughs}`),n.staleTypes>0&&console.log(` Stale abstractions: ${n.staleTypes}`),n.driftedFiles>0&&console.log(` Pattern drift: ${n.driftedFiles} files`),n.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${n.complexityHotspotCount}`),e.actions.length>0){console.log(`
|
|
951
|
+
Prioritized Actions (highest impact + lowest effort first):`);for(let r=0;r<e.actions.length;r++){let i=e.actions[r],s=i.locRecoverable>0?` (~${i.locRecoverable} LOC recoverable)`:"";console.log(` ${r+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${s}`)}}if(e.topComplexity.length>0){console.log(`
|
|
952
|
+
Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}e.actions.length===0&&console.log(`
|
|
953
|
+
No issues found. Codebase is clean.`)}function $x(e){return R(t=>{let n=S.diffImpactPlan(t,{base:e.base});if(n.note)return S.diffImpact(t,{base:e.base});if(n.changedFiles.length===0)return S.diffImpact(t,{base:e.base});let r=[];for(let i of Hx(n.changedFiles,Ox))r.push(jx(i,e));return S.mergeDiffImpactPartials(n.changedFiles,r)})}function jx(e,t){let n=process.argv[1]??Zr(import.meta.url),r=[...process.execArgv,n,Ul];t.base&&r.push("--base",t.base);let i=Hl(process.execPath,r,{cwd:process.cwd(),env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},encoding:"utf8",maxBuffer:10*1024*1024});if(i.status!==0){let s=i.stderr.trim();throw new Error(`Diff-impact batch failed${s?`:
|
|
954
|
+
${s}`:""}`)}return JSON.parse(i.stdout)}function Bx(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`),console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),b.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
|
|
955
|
+
Affected consumer files:`),b.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}function Hx(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}x.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(Px);x.command("reindex").description("Index the codebase and convert to SQLite").option("-l, --language <lang>","Index only this language (can be repeated)",Al,[]).option("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)").option("--force","Rebuild even if source inputs are unchanged").option("--allow-partial","Write an incomplete index when one or more detected languages fail").option("--indexer-concurrency <n>","Number of language indexers to run at once",Xr).action(async e=>{let t=Ne(),n=Ee(t),r=De(t,n);try{let i=await qi({projectRoot:t,languages:e.language.length>0?e.language:n.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:e.pnpmWorkspaces||n.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!e.force,allowPartial:e.allowPartial,indexerConcurrency:e.indexerConcurrency});console.log(`${i.reused?"Reused":"Indexed"} ${i.languages.join(", ")} in ${(i.durationMs/1e3).toFixed(1)}s`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}});x.command("augment-sources").description("Add source files skipped by upstream SCIP indexers to the SQLite documents table").action(()=>{let e=Ne(),t=jt(e);try{let n=we({projectRoot:e,dbPath:t,onStatus:r=>console.log(r)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}});x.command("augment-vue").description("Add compiler-resolved Vue SFC references to the SQLite index using Volar").option("--project <tsconfig>","Vue tsconfig path","frontend/tsconfig.scip.json").action(e=>{let t=Ne(),n=jt(t);try{let r=er({projectRoot:t,dbPath:n,tsconfig:e.project,onStatus:i=>console.log(i)});console.log(`Vue files: ${r.vueFiles}; resolved references: ${r.resolvedReferences}; inserted mentions: ${r.insertedMentions}.`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exit(1)}});x.command("stats").description("Show index statistics").action(()=>R(e=>{let t=S.stats(e);console.log(`Documents: ${t.documents}`),console.log(`Symbols: ${t.symbols}`),console.log(`Definitions: ${t.definitions}`),console.log(`References: ${t.references}`),console.log(`Index size: ${$n(t.indexSizeBytes)}`),t.lastBuilt&&console.log(`Last built: ${t.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}));x.command("files <pattern>").description("Find files matching a pattern").action(e=>R(t=>{b.list(S.files(t,e),n=>n.relativePath)}));x.command("symbols <file>").description("List symbols defined in a file (with line ranges + signatures)").action(e=>R(t=>{b.list(S.symbols(t,e),n=>{let r=n.signature?` \u2014 ${n.signature}`:"";return` ${pe(n.startLine,n.endLine)} ${n.shortName}${r}`})}));x.command("methods <className>").description("List methods of a class (with line ranges)").action(e=>R(t=>{b.list(S.methods(t,e),n=>` ${pe(n.startLine,n.endLine)} ${n.name}`)}));x.command("refs <symbol>").description("Find all files referencing a symbol").action(e=>R(t=>{b.groupedByFile(S.refs(t,e),n=>` line ${xe(n.line)}`)}));x.command("trace <symbol>").description("Trace a symbol: definition + all references").action(e=>R(t=>{let n=S.trace(t,e),r=[];for(let o of n.definitions){let a=o.signature?` \u2014 ${o.signature}`:"";r.push(` ${fe(o.relativePath,o.startLine,o.endLine)}${a}`),o.source&&r.push(o.source.split(`
|
|
956
|
+
`).map((l,c)=>` ${xe(o.startLine+c)} ${l}`).join(`
|
|
957
|
+
`))}let i=[],s="";for(let o of n.referencedBy)o.relativePath!==s&&(s&&i.push(""),i.push(` ${o.relativePath}`),s=o.relativePath),i.push(` line ${xe(o.line)} in ${o.enclosingShort}`);b.sectionedReport([{title:"DEFINITION",rows:r},{title:"REFERENCED BY",rows:i}])}));x.command("deps <file>").description("Files this file depends on (internal)").action(e=>R(t=>{b.list(S.deps(t,e),n=>n.relativePath)}));x.command("rdeps <file>").description("Files that depend on this file/module").action(e=>R(t=>{b.list(S.rdeps(t,e),n=>n.relativePath)}));x.command("system <module>").description("Full module map: files, symbols, deps in/out").action(e=>R(t=>{let n=S.system(t,e);b.sectionedReport([{title:"FILES",rows:n.files},{title:"EXPORTED SYMBOLS",rows:n.symbols.map(r=>` ${pe(r.startLine,r.endLine)} ${r.shortName}`)},{title:"DEPENDS ON (internal)",rows:n.dependsOn.map(r=>` ${r}`)},{title:"DEPENDED ON BY",rows:n.dependedOnBy.map(r=>` ${r}`)}])}));x.command("surface <module>").description("What symbols consumers actually use from this module").action(e=>R(t=>{b.list(S.surface(t,e),n=>` ${n.consumer} \u2192 ${n.shortName}`)}));x.command("dead [scope]").description("Find dead code and file-internal symbols (no cross-file consumers)").option("--min-loc <n>","Only show symbols >= N lines",N,1).option("--include-tests","Include test files").option("--skip-barrels","Ignore refs from barrel re-export files").option("--include-members","Include class members").option("--only-dead","Show only [dead code] symbols (skip [file-internal only])").option("--only-internal","Show only [file-internal only] symbols (skip [dead code])").action((e,t)=>R(n=>{let r={scope:e||void 0,minLoc:t.minLoc,includeTests:t.includeTests,skipBarrels:t.skipBarrels,includeMembers:t.includeMembers},i=S.dead(n,r),s=i.symbols.filter(p=>p.kind==="dead-code"),o=i.symbols.filter(p=>p.kind!=="dead-code"),a=!t.onlyInternal,l=!t.onlyDead,c=a?s:[],u=l?o:[];if(c.length===0&&u.length===0)return b.empty("No matching dead-code symbols found.");let d=(p,y,_,E)=>{console.log(`\u2550\u2550\u2550 ${y} (${p.length}, ${E} LOC) \u2550\u2550\u2550`),console.log(_),console.log("");let F=new Map;for(let I of p){let k=F.get(I.relativePath)??[];k.push(I),F.set(I.relativePath,k)}let M=[...F.entries()].map(([I,k])=>({file:I,bucket:k,totalLoc:k.reduce((D,G)=>D+G.loc,0)})).sort((I,k)=>k.totalLoc-I.totalLoc||I.file.localeCompare(k.file)),C=!0;for(let{file:I,bucket:k}of M){C||console.log(""),C=!1,console.log(` ${I}`),k.sort((D,G)=>D.startLine-G.startLine);for(let D of k)console.log(` ${pe(D.startLine,D.endLine)} (${D.loc} LOC) ${D.shortName}`)}},m=c.reduce((p,y)=>p+y.loc,0),f=u.reduce((p,y)=>p+y.loc,0);c.length>0&&d(c,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
|
|
940
958
|
Safe to delete.`,m),u.length>0&&(c.length>0&&console.log(""),d(u,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
|
|
941
959
|
single-use helper, an abstraction-in-progress, or a callback registered
|
|
942
960
|
through a framework path that static analysis cannot trace (signal
|
|
943
961
|
handlers, event listeners, dependency injection). NOT necessarily dead \u2014
|
|
944
|
-
review case by case.`,
|
|
945
|
-
\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${c.length+u.length} symbols \u2014 ${
|
|
946
|
-
${n.length} unused import(s)`)}));
|
|
962
|
+
review case by case.`,f));let h=[];a&&h.push(`${c.length} dead code (${m} LOC)`),l&&h.push(`${u.length} file-internal (${f} LOC)`),console.log(`
|
|
963
|
+
\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${c.length+u.length} symbols \u2014 ${h.join(" + ")}`)}));x.command("hotspots").description("Most-referenced symbols in the codebase (choke points)").option("-n, --limit <n>","Number of results",N,30).option("-s, --scope <path>","Limit to files matching path").action(e=>R(t=>{let n=S.hotspots(t,{limit:e.limit,scope:e.scope});b.table(["refs","files","symbol"],n.map(r=>` ${String(r.refCount).padStart(4)} ${String(r.fileCount).padStart(5)} ${r.shortName}`))}));x.command("imports <file>").description("What symbols does this file import?").action(e=>R(t=>{let n=S.imports(t,e);if(n.length===0){b.empty("No imports found (indexer may not emit role=2 for this language).");return}b.list(n,r=>` ${r.shortName} \u2190 ${r.fromFile}`)}));x.command("imported-by <symbol>").description("Which files import this symbol?").action(e=>R(t=>{b.list(S.importedBy(t,e),n=>` ${n.fromFile}`)}));x.command("unused-imports <file>").description("Find imports not referenced in the same file").action(e=>R(t=>{let n=S.unusedImports(t,e);if(n.length===0)return b.empty("No unused imports found.");b.list(n,r=>` ${r.shortName} in ${r.importedIn}`),console.log(`
|
|
964
|
+
${n.length} unused import(s)`)}));x.command("outline <file>").description("Tree view of symbols in a file (using nesting hierarchy)").action(e=>R(t=>{let n=S.outline(t,e);function r(i,s){for(let o of i){let a=" ".repeat(s);console.log(`${a}${pe(o.startLine,o.endLine)} ${o.shortName}`),r(o.children,s+1)}}r(n,0)}));x.command("members <symbol>").description("All children of a symbol (methods, fields, nested types)").action(e=>R(t=>{b.list(S.members(t,e),n=>` ${pe(n.startLine,n.endLine)} [${n.kind}] ${n.shortName}`)}));x.command("fan-in [symbol]").description("How many files reference a symbol (or top fan-in across codebase)").option("-n, --limit <n>","Number of results for top mode",N,30).option("-s, --scope <path>","Limit to files matching path").action((e,t)=>R(n=>{if(e){let r=S.fanIn(n,e);if(r.length===0)return b.empty(`No fan-in for ${e}.`);b.list(r,i=>` ${String(i.count).padStart(4)} files ${i.name}`)}else b.table(["files","symbol"],S.topFanIn(n,{limit:t.limit,scope:t.scope}).map(r=>` ${String(r.count).padStart(5)} ${r.name}`))}));x.command("fan-out [file]").description("How many external symbols a file uses (or top fan-out across codebase)").option("-n, --limit <n>","Number of results for top mode",N,30).option("-s, --scope <path>","Limit to files matching path").action((e,t)=>R(n=>{if(e){let r=S.fanOut(n,e);if(r.length===0)return b.empty(`No fan-out for ${e}.`);b.list(r,i=>` ${String(i.count).padStart(4)} symbols ${i.name}`)}else b.table(["symbols","file"],S.topFanOut(n,{limit:t.limit,scope:t.scope}).map(r=>` ${String(r.count).padStart(7)} ${r.name}`))}));x.command("coupling [file1] [file2]").description("Coupling between two files, or top coupled pairs in codebase").option("-n, --limit <n>","Number of results for top mode",N,20).option("-s, --scope <path>","Limit to files matching path").action((e,t,n)=>R(r=>{if(e&&t){let i=S.coupling(r,e,t);console.log(`${i.file1} \u2194 ${i.file2}: ${i.sharedSymbols} shared symbols`)}else b.table(["shared","file1 \u2192 file2"],S.topCoupling(r,{limit:n.limit,scope:n.scope}).map(i=>` ${String(i.sharedSymbols).padStart(6)} ${i.file1} \u2192 ${i.file2}`))}));x.command("cycles").description("Detect circular dependency chains between files").option("-s, --scope <path>","Limit to files matching path").option("--max-depth <n>","Maximum cycle depth",N,10).action(e=>R(t=>{let n=S.cycles(t,{scope:e.scope,maxDepth:e.maxDepth});if(n.length===0)return b.empty("No circular dependencies found.");let r=n.filter(s=>s.kind==="real"),i=n.filter(s=>s.kind==="module-hierarchy");for(let s=0;s<r.length;s++){console.log(`
|
|
947
965
|
Cycle ${s+1} (${r[s].path.length-1} files):`);for(let o=0;o<r[s].path.length;o++){let a=o<r[s].path.length-1?" \u2192":" (cycle)";console.log(` ${r[s].path[o]}${a}`)}}r.length===0?console.log("No real circular dependencies found."):console.log(`
|
|
948
|
-
${r.length} real cycle(s) found.`),i.length>0&&console.log(`(${i.length} module-hierarchy cycle(s) hidden \u2014 barrel files participating in normal parent/child re-export patterns. Pass --include-module-hierarchy to see them.)`)}));
|
|
949
|
-
${n.length} isolated symbol(s)`)}));
|
|
950
|
-
${r.length} symbol(s)`)}));
|
|
951
|
-
Chain ${r+1} (depth ${n[r].depth}):`);for(let i of n[r].chain)console.log(` \u2192 ${i}`)}}));
|
|
952
|
-
`),b.sectionedReport([{title:`CALLERS (${n.callers.length})`,rows:n.callers.map(r=>` ${r.file} ${r.shortName}`)},{title:`CALLEES (${n.callees.length})`,rows:n.callees.map(r=>` ${r.file} ${r.shortName}`)}])}));
|
|
966
|
+
${r.length} real cycle(s) found.`),i.length>0&&console.log(`(${i.length} module-hierarchy cycle(s) hidden \u2014 barrel files participating in normal parent/child re-export patterns. Pass --include-module-hierarchy to see them.)`)}));x.command("bottlenecks").description("Find coupling hubs: high fan-in AND high fan-out").option("-n, --limit <n>","Number of results",N,20).option("-s, --scope <path>","Limit to files matching path").option("--min-fan-in <n>","Minimum fan-in",N,2).option("--min-fan-out <n>","Minimum fan-out",N,2).action(e=>R(t=>{let n=S.bottlenecks(t,{limit:e.limit,scope:e.scope,minFanIn:e.minFanIn,minFanOut:e.minFanOut});if(n.length===0)return b.empty("No bottlenecks found.");b.table(["score","fan-in","fan-out","symbol"],n.map(r=>` ${String(r.score).padStart(5)} ${String(r.fanIn).padStart(6)} ${String(r.fanOut).padStart(7)} ${r.shortName}`))}));x.command("isolated").description("Find completely orphaned symbols (no references at all)").option("-s, --scope <path>","Limit to files matching path").option("--min-loc <n>","Minimum lines of code",N,3).action(e=>R(t=>{let n=S.isolated(t,{scope:e.scope,minLoc:e.minLoc});if(n.length===0)return b.empty("No isolated symbols found.");b.groupedByFile(n,r=>` ${pe(r.startLine,r.endLine)} (${r.loc} LOC) ${r.shortName}`),console.log(`
|
|
967
|
+
${n.length} isolated symbol(s)`)}));x.command("by-kind <kind>").description("Find symbols by SCIP kind (class, interface, enum, function, etc.)").option("-s, --scope <path>","Limit to files matching path").option("-n, --limit <n>","Number of results",N,100).action((e,t)=>R(n=>{let r=S.byKind(n,e,{scope:t.scope,limit:t.limit});if(r.length===0)return b.empty(`No symbols found for kind "${e}". Use "kind-counts" to see available kinds.`);b.list(r,i=>` ${fe(i.relativePath,i.startLine,i.endLine)} [${i.kindName}] ${i.shortName}`),console.log(`
|
|
968
|
+
${r.length} symbol(s)`)}));x.command("kind-counts").description("Histogram of symbol kinds in the codebase").option("-s, --scope <path>","Limit to files matching path").action(e=>R(t=>{let n=S.kindCounts(t,{scope:e.scope});b.table(["count","kind"],n.map(r=>` ${String(r.count).padStart(5)} ${r.kindName} (${r.kind})`))}));x.command("deep-chains").description("Find the longest transitive dependency chains").option("-n, --limit <n>","Number of chains to show",N,10).option("-s, --scope <path>","Limit to files matching path").option("--min-depth <n>","Minimum chain depth",N,3).action(e=>R(t=>{let n=S.deepChains(t,{limit:e.limit,scope:e.scope,minDepth:e.minDepth});if(n.length===0)return b.empty("No deep chains found.");for(let r=0;r<n.length;r++){console.log(`
|
|
969
|
+
Chain ${r+1} (depth ${n[r].depth}):`);for(let i of n[r].chain)console.log(` \u2192 ${i}`)}}));x.command("hierarchy <symbol>").description("Show a symbol's ancestry chain (method \u2192 class \u2192 module)").action(e=>R(t=>{let n=S.hierarchy(t,e);if(n.length===0)return b.empty("Symbol not found.");b.list(n,r=>`${" ".repeat(r.depth)}${r.shortName}`)}));x.command("call-graph <symbol>").description("Show incoming callers and outgoing callees for a symbol").action(e=>R(t=>{let n=S.callGraph(t,e);if(!n)return b.empty("Symbol not found.");console.log(`Symbol: ${n.shortName}
|
|
970
|
+
`),b.sectionedReport([{title:`CALLERS (${n.callers.length})`,rows:n.callers.map(r=>` ${r.file} ${r.shortName}`)},{title:`CALLEES (${n.callees.length})`,rows:n.callees.map(r=>` ${r.file} ${r.shortName}`)}])}));x.command("similar [symbol]").description("Find heuristic function similarity candidates from callee fingerprints").option("--min-similarity <n>","Minimum Jaccard similarity (0-1)",parseFloat,.4).option("-n, --limit <n>","Number of results",N,20).option("-s, --scope <path>","Limit to files matching path").option("--min-callees <n>","Minimum callees to consider",N,4).option("--cross-file-only","Only show cross-file pairs (skip same-file matches)").action((e,t)=>R(n=>{if(e){let r=S.similar(n,e,{minSimilarity:t.minSimilarity,limit:t.limit});if(r.length===0)return b.empty("No similar symbols found.");Se("similarity candidates"),b.list(r,i=>{let s=i.similarityBasis??"callees",o=s==="source-tokens"?"Shared source tokens":"Shared callees",a=s==="source-tokens"?"Only tokens in":"Only in",l=[`
|
|
953
971
|
${Math.round(i.similarity*100)}% similar:`,` A: ${i.shortNameA} (${i.fileA})`,` B: ${i.shortNameB} (${i.fileB})`,` ${o}: ${i.sharedCallees.join(", ")}`];return i.uniqueToA.length&&l.push(` ${a} A: ${i.uniqueToA.join(", ")}`),i.uniqueToB.length&&l.push(` ${a} B: ${i.uniqueToB.join(", ")}`),l.join(`
|
|
954
|
-
`)})}else{let r=
|
|
972
|
+
`)})}else{let r=S.similarAll(n,{minSimilarity:t.minSimilarity,limit:t.limit,scope:t.scope,minCallees:t.minCallees,crossFileOnly:t.crossFileOnly});if(r.length===0)return b.empty("No similar symbol pairs found.");Se("similarity candidates"),b.list(r,i=>`
|
|
955
973
|
${Math.round(i.similarity*100)}% similar:
|
|
956
974
|
A: ${i.shortNameA} (${i.fileA})
|
|
957
975
|
B: ${i.shortNameB} (${i.fileB})
|
|
958
976
|
Shared ${i.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${i.sharedCallees.join(", ")}`),console.log(`
|
|
959
|
-
${r.length} similar pair(s) found.`)}}));
|
|
977
|
+
${r.length} similar pair(s) found.`)}}));x.command("similar-files [file]").description("Find heuristic similar-file candidates from dependency profiles").option("--min-similarity <n>","Minimum Jaccard similarity (0-1)",parseFloat,.5).option("-n, --limit <n>","Number of results",N,20).option("-s, --scope <path>","Limit to files matching path").option("--min-deps <n>","Minimum dependencies to consider",N).action((e,t)=>R(n=>{let r=S.similarFiles(n,{minSimilarity:t.minSimilarity,limit:t.limit,scope:t.scope,minDeps:t.minDeps,filePattern:e});if(r.length===0)return b.empty("No similar file pairs found.");Se("similar file candidates"),b.list(r,i=>{let s=[`
|
|
960
978
|
${Math.round(i.similarity*100)}% similar:`,` ${i.fileA}`,` ${i.fileB}`,` Shared deps (${i.sharedDeps.length}): ${i.sharedDeps.join(", ")}`];return i.uniqueToA.length&&s.push(` Only in first: ${i.uniqueToA.join(", ")}`),i.uniqueToB.length&&s.push(` Only in second: ${i.uniqueToB.join(", ")}`),s.join(`
|
|
961
979
|
`)}),console.log(`
|
|
962
|
-
${r.length} similar pair(s) found.`)}));
|
|
980
|
+
${r.length} similar pair(s) found.`)}));x.command("similar-chains").description("Find heuristic similar-chain candidates from dependency flows").option("--min-similarity <n>","Minimum chain similarity (0-1)",parseFloat,.5).option("-n, --limit <n>","Number of results",N,15).option("-s, --scope <path>","Limit to files matching path").option("--min-length <n>","Minimum chain length",N,3).option("--max-length <n>","Maximum chain length",N,8).action(e=>R(t=>{let n=S.similarChains(t,{minSimilarity:e.minSimilarity,limit:e.limit,scope:e.scope,minChainLength:e.minLength,maxChainLength:e.maxLength});if(n.length===0)return b.empty("No similar chains found.");Se("similar chain candidates");for(let r=0;r<n.length;r++){let i=n[r];console.log(`
|
|
963
981
|
\u2500\u2500 Chain pair ${r+1} (${Math.round(i.similarity*100)}% similar, ${i.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${i.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${i.chainB.join(" \u2192 ")}`),i.commonPrefix.length&&console.log(` Common prefix: ${i.commonPrefix.join(" \u2192 ")}`),i.commonSuffix.length&&console.log(` Common suffix: ${i.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let s of i.divergencePoints)console.log(` [${s.index}] ${s.nodeA} \u2194 ${s.nodeB}`)}console.log(`
|
|
964
|
-
${n.length} similar chain pair(s) found.`)}));
|
|
965
|
-
${
|
|
966
|
-
${n.length} extraction candidate(s) found.`)}));
|
|
982
|
+
${n.length} similar chain pair(s) found.`)}));x.command("extract-candidates").description("Find heuristic extraction candidates from isolated callee clusters").option("-s, --scope <path>","Limit to files matching path").option("--min-loc <n>","Minimum function LOC",N,10).option("--min-callees <n>","Minimum callees to analyze",N,6).option("-n, --limit <n>","Number of results",N,20).action(e=>R(t=>{let n=S.extractCandidates(t,{scope:e.scope,minLoc:e.minLoc,minCallees:e.minCallees,limit:e.limit});if(n.length===0)return b.empty("No extraction candidates found.");Se("extraction candidates");for(let r of n){console.log(`
|
|
983
|
+
${fe(r.relativePath,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC, ${r.totalCallees} callees)`);for(let i=0;i<r.clusters.length;i++){let s=r.clusters[i];console.log(` Cluster ${i+1} (${Math.round(s.isolation*100)}% isolated, ${s.callees.length} callees):`);for(let o of s.callees)console.log(` ${o}`)}}console.log(`
|
|
984
|
+
${n.length} extraction candidate(s) found.`)}));x.command("affected <symbol>").description("Transitive closure of symbols that could break if this symbol changes").option("--max-depth <n>","Maximum traversal depth",N,5).option("-s, --scope <path>","Limit to files matching path").action((e,t)=>R(n=>{let r=S.affected(n,e,{maxDepth:t.maxDepth,scope:t.scope});if(r.length===0)return b.empty("No affected symbols found.");let i=-1;for(let s of r)s.depth!==i&&(console.log(`
|
|
967
985
|
\u2500\u2500 Depth ${s.depth} \u2500\u2500`),i=s.depth),console.log(` ${s.file} ${s.shortName}`);console.log(`
|
|
968
|
-
${r.length} affected symbol(s) across ${new Set(r.map(s=>s.file)).size} files.`)}));
|
|
969
|
-
`),b.list(n.symbols,r=>{let i=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"";return` ${
|
|
970
|
-
Affected consumer files:`),b.list(n.affectedConsumers,r=>` ${r.file} (${r.consumedSymbols} symbol(s))`))}));S.command("drift [module]").description("Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations").option("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",$r,5).action((e,t)=>I(n=>{let r=x.drift(n,{scope:e,minDeviation:t.minDeviation});if(r.results.length===0)return b.empty("No drift detected.");ye("drift candidates"),console.log(""),b.groupedByFile(r.results,i=>{let o=` [${i.kind==="unused-import"?"UNUSED":i.kind==="layer-violation"?"LAYER":"UNIQUE"}] ${i.description}`;return i.detail?`${o}
|
|
986
|
+
${r.length} affected symbol(s) across ${new Set(r.map(s=>s.file)).size} files.`)}));x.command("change-surface <file>").description("Pre-change briefing: exports, consumers, and blast-radius risk").action(e=>R(t=>{let n=S.changeSurface(t,e);if(!n)return b.empty("File not found in index.");console.log(`File: ${n.file}`),console.log(`External consumers: ${n.totalExternalConsumers}
|
|
987
|
+
`),b.list(n.symbols,r=>{let i=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"";return` ${pe(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`})}));x.command(Ul,{hidden:!0}).option("--base <ref>","Git ref to diff against (default: HEAD)").action(e=>R(t=>{let n=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),r=S.diffImpactPlan(t,{base:e.base}),i=S.diffImpactPartial(t,n,r.changedFiles);console.log(JSON.stringify(i))}));x.command("diff-impact").description("Compute changed symbols and downstream consumers from current git diff").option("--base <ref>","Git ref to diff against (default: HEAD)").action(e=>{try{Bx($x({base:e.base}))}catch(t){console.error(`error: ${t instanceof Error?t.message:t}`),process.exit(1)}});x.command("drift [module]").description("Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations").option("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Xr,5).action((e,t)=>R(n=>{let r=S.drift(n,{scope:e,minDeviation:t.minDeviation});if(r.results.length===0)return b.empty("No drift detected.");Se("drift candidates"),console.log(""),b.groupedByFile(r.results,i=>{let o=` [${i.kind==="unused-import"?"UNUSED":i.kind==="layer-violation"?"LAYER":"UNIQUE"}] ${i.description}`;return i.detail?`${o}
|
|
971
988
|
${i.detail}`:o},i=>i.file),console.log(`
|
|
972
|
-
${r.unusedImports} unused import(s), ${r.layerViolations} layer violation(s), ${r.patternDeviations} pattern deviation(s)`)}));
|
|
989
|
+
${r.unusedImports} unused import(s), ${r.layerViolations} layer violation(s), ${r.patternDeviations} pattern deviation(s)`)}));x.command("wrapper-candidates").description("Find heuristic wrapper candidates only called by one consumer").option("-s, --scope <path>","Limit to files matching path").option("--max-loc <n>","Maximum LOC for candidates",N,15).option("-n, --limit <n>","Number of results",N,30).action(e=>R(t=>{let n=S.wrapperCandidates(t,{scope:e.scope,maxLoc:e.maxLoc,limit:e.limit});if(n.length===0)return b.empty("No wrapper candidates found.");Se("wrapper candidates"),b.list(n,r=>` ${fe(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)
|
|
973
990
|
Only called by: ${r.singleCallerShort} (fan-in: ${r.callerFanIn})`),console.log(`
|
|
974
|
-
${n.length} wrapper candidate(s).`)}));
|
|
991
|
+
${n.length} wrapper candidate(s).`)}));x.command("passthrough-candidates").description("Find heuristic passthrough candidates that forward to one callee").option("-s, --scope <path>","Limit to files matching path").option("--max-loc <n>","Maximum LOC for candidates",N,15).option("-n, --limit <n>","Number of results",N,30).action(e=>R(t=>{let n=S.passthroughCandidates(t,{scope:e.scope,maxLoc:e.maxLoc,limit:e.limit});if(n.length===0)return b.empty("No passthrough candidates found.");Se("passthrough candidates"),b.list(n,r=>` ${fe(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)
|
|
975
992
|
Forwards to: ${r.forwardsToShort} (${r.forwardsToFile})`),console.log(`
|
|
976
|
-
${n.length} passthrough candidate(s).`)}));
|
|
993
|
+
${n.length} passthrough candidate(s).`)}));x.command("stale-abstractions").description("Find heuristic stale abstraction candidates with 0-1 consumers").option("-s, --scope <path>","Limit to files matching path").option("--min-loc <n>","Minimum LOC",N,3).option("-n, --limit <n>","Number of results",N,30).option("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",!1).action(e=>R(t=>{let n=S.staleAbstractions(t,{scope:e.scope,minLoc:e.minLoc,limit:e.limit,includeLowConfidence:!!e.includeLowConfidence});if(n.length===0)return b.empty("No stale abstractions found.");Se("stale abstraction candidates"),b.list(n,r=>{let i=r.consumers===0?"unused":`${r.consumers} consumer`,s=r.barrelConsumers>0?`, +${r.barrelConsumers} barrel`:"";return` [${r.confidence}] ${fe(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.kind}, ${r.loc} LOC, ${i}${s})
|
|
977
994
|
${r.reason}`}),console.log(`
|
|
978
|
-
${n.length} stale abstraction(s).`)}));
|
|
979
|
-
Codebase Health Score: ${n.score}/100
|
|
980
|
-
`),console.log(` ${n.overview.documents} files | ${n.overview.symbols} symbols | ${On(n.overview.indexSizeBytes)}
|
|
981
|
-
`),console.log(" Findings:");let r=n.findings;if(r.deadSymbols>0&&console.log(` Dead code: ${r.deadSymbols} symbols (${r.deadLoc} LOC)`),r.isolatedSymbols>0&&console.log(` Isolated symbols: ${r.isolatedSymbols} (${r.isolatedLoc} LOC)`),r.cycles>0&&console.log(` Circular deps: ${r.cycles}`),r.similarPairs>0&&console.log(` Similar pairs: ${r.similarPairs}`),r.extractionCandidates>0&&console.log(` Extract candidates: ${r.extractionCandidates}`),r.wrappers>0&&console.log(` Wrapper functions: ${r.wrappers}`),r.passthroughs>0&&console.log(` Passthroughs: ${r.passthroughs}`),r.staleTypes>0&&console.log(` Stale abstractions: ${r.staleTypes}`),r.driftedFiles>0&&console.log(` Pattern drift: ${r.driftedFiles} files`),r.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${r.complexityHotspotCount}`),n.actions.length>0){console.log(`
|
|
982
|
-
Prioritized Actions (highest impact + lowest effort first):`);for(let i=0;i<n.actions.length;i++){let s=n.actions[i],o=s.locRecoverable>0?` (~${s.locRecoverable} LOC recoverable)`:"";console.log(` ${i+1}. [${s.effort} effort / ${s.impact} impact] ${s.description}${o}`)}}if(n.topComplexity.length>0){console.log(`
|
|
983
|
-
Top Complexity Hotspots:`);for(let i of n.topComplexity)console.log(` ${i.score.toFixed(1).padStart(6)} ${i.symbol}`)}n.actions.length===0&&console.log(`
|
|
984
|
-
No issues found. Codebase is clean.`)}));S.command("convergence <symbol1> <symbol2>").description("Show what a consolidated version of two similar functions would look like").action((e,t)=>I(n=>{let r=x.convergence(n,e,t);if(!r)return b.empty("One or both symbols not found.");console.log(`
|
|
995
|
+
${n.length} stale abstraction(s).`)}));x.command("complexity-hotspots").description("Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out").option("-s, --scope <path>","Limit to files matching path").option("--min-loc <n>","Minimum LOC",N,10).option("-n, --limit <n>","Number of results",N,20).action(e=>R(t=>{let n=S.complexityHotspots(t,{scope:e.scope,minLoc:e.minLoc,limit:e.limit});if(n.length===0)return b.empty("No complexity hotspots found.");Se("complexity hotspot candidates"),b.table(["score"," LOC","fan-in","fan-out","callees","symbol"],n.map(r=>` ${r.score.toFixed(1).padStart(5)} ${String(r.loc).padStart(4)} ${String(r.fanIn).padStart(6)} ${String(r.fanOut).padStart(7)} ${String(r.calleeCount).padStart(7)} ${r.shortName}`),[5,4,6,7,7,6])}));x.command(Wl,{hidden:!0}).argument("<phase>").option("-s, --scope <path>","Limit to files matching path").option("--full","Run unbounded candidate analyses on large indexes").action((e,t)=>R(n=>{S.HEALTH_PHASES.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let r=S.healthPhase(n,e,{scope:t.scope,full:!!t.full});console.log(JSON.stringify(r))}));x.command("health").description("Composite codebase health report with prioritized action list").option("-s, --scope <path>","Limit to files matching path").option("--full","Run unbounded candidate analyses on large indexes").option("--json","Output as JSON for programmatic consumption").action(e=>{try{let t=Tx({scope:e.scope,full:!!e.full,json:!!e.json});Ax(t,!!e.json)}catch(t){console.error(`error: ${t instanceof Error?t.message:t}`),process.exit(1)}});x.command("convergence <symbol1> <symbol2>").description("Show what a consolidated version of two similar functions would look like").action((e,t)=>R(n=>{let r=S.convergence(n,e,t);if(!r)return b.empty("One or both symbols not found.");console.log(`
|
|
985
996
|
${Math.round(r.similarity*100)}% callee overlap
|
|
986
997
|
`),console.log(` A: ${r.symbolA.shortName} (${r.symbolA.file}, ${r.symbolA.loc} LOC)`),console.log(` B: ${r.symbolB.shortName} (${r.symbolB.file}, ${r.symbolB.loc} LOC)
|
|
987
998
|
`),console.log(` Shared callees (${r.sharedCallees.length}):`);for(let i of r.sharedCallees)console.log(` ${i}`);if(r.uniqueToA.length>0){console.log(`
|
|
988
999
|
Unique to A (${r.uniqueToA.length}):`);for(let i of r.uniqueToA)console.log(` ${i}`)}if(r.uniqueToB.length>0){console.log(`
|
|
989
1000
|
Unique to B (${r.uniqueToB.length}):`);for(let i of r.uniqueToB)console.log(` ${i}`)}console.log(`
|
|
990
|
-
Strategy: ${r.consolidationStrategy}`)}));
|
|
1001
|
+
Strategy: ${r.consolidationStrategy}`)}));x.command("code <symbol>").description("Read the source code for a symbol (bounded to its definition range)").option("-C, --context <n>","Extra lines of context above/below",N,0).action((e,t)=>R(n=>{let r=S.code(n,e,{context:t.context});if(!r)return b.empty("Symbol not found or file unreadable.");console.log(`${fe(r.relativePath,r.startLine,r.endLine)} ${r.shortName} [${r.language??"unknown"}]
|
|
991
1002
|
`);let i=r.source.split(`
|
|
992
|
-
`);for(let s=0;s<i.length;s++)console.log(` ${String(
|
|
993
|
-
`),console.log(` LOC: ${n.loc}`),console.log(` Branches: ${n.branches}`),console.log(` Cyclomatic estimate: ${n.cyclomaticEstimate}`),console.log(` Callees: ${n.calleeCount}`),console.log(` Fan-in: ${n.fanIn}`),console.log(` Fan-out: ${n.fanOut}`)}));
|
|
994
|
-
`),n.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let r of n.definitionSites)console.log(` ${r.file}:${
|
|
995
|
-
\u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let r of n.usageSites)console.log(` ${r.file}:${
|
|
1003
|
+
`);for(let s=0;s<i.length;s++)console.log(` ${String(xe(r.startLine+s)).padStart(4)} ${i[s]}`)}));x.command("complexity <symbol>").description("Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees").action(e=>R(t=>{let n=S.complexity(t,e);if(!n)return b.empty("Symbol not found.");console.log(`${fe(n.relativePath,n.startLine,n.endLine)} ${n.shortName}
|
|
1004
|
+
`),console.log(` LOC: ${n.loc}`),console.log(` Branches: ${n.branches}`),console.log(` Cyclomatic estimate: ${n.cyclomaticEstimate}`),console.log(` Callees: ${n.calleeCount}`),console.log(` Fan-in: ${n.fanIn}`),console.log(` Fan-out: ${n.fanOut}`)}));x.command("dataflow <symbol>").description("Reference-level dataflow: definition sites, usage sites, producers, consumers").action(e=>R(t=>{let n=S.dataflow(t,e);if(!n)return b.empty("Symbol not found.");if(console.log(`${n.shortName} (${n.relativePath})
|
|
1005
|
+
`),n.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let r of n.definitionSites)console.log(` ${r.file}:${xe(r.line)}`)}if(n.usageSites.length>0){console.log(`
|
|
1006
|
+
\u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let r of n.usageSites)console.log(` ${r.file}:${xe(r.line)} in ${r.enclosingShort}`)}if(n.producers.length>0){console.log(`
|
|
996
1007
|
\u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let r of n.producers)console.log(` ${r.file} ${r.shortName}`)}if(n.consumers.length>0){console.log(`
|
|
997
|
-
\u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let r of n.consumers)console.log(` ${r.file} ${r.shortName}`)}}));
|
|
1008
|
+
\u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let r of n.consumers)console.log(` ${r.file} ${r.shortName}`)}}));x.command("slice <symbol>").description("Reference-level program slice: what affects this (backward) or what this affects (forward)").option("--forward","Forward slice (what does this affect). Default is backward.").option("--depth <n>","Max transitive depth for backward slice",N,3).action((e,t)=>R(n=>{let r=t.forward?"forward":"backward",i=S.slice(n,e,{direction:r,maxDepth:t.depth});if(!i)return b.empty("Symbol not found.");if(console.log(`${i.direction} slice of ${i.shortName}
|
|
998
1009
|
`),i.connectedSymbols.length===0){console.log(" No connected symbols found.");return}b.list(i.connectedSymbols,s=>` ${s.file} ${s.shortName}
|
|
999
1010
|
${s.relationship}`),console.log(`
|
|
1000
|
-
${i.connectedSymbols.length} connected symbol(s).`)}));
|
|
1001
|
-
${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")});
|
|
1011
|
+
${i.connectedSymbols.length} connected symbol(s).`)}));x.command("install-skills").description(`Install skills (${ur.join(", ")}) into Claude Code and Codex`).action(()=>{let e=Zi(),t=e.installed.length+e.alreadyLinked.length;console.log(`
|
|
1012
|
+
${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")});x.command("check-deps").description("Check whether scip-query and the detected language indexers are actually runnable").action(()=>{let e=!1;Bn()?console.log("scip CLI: installed"):(Hn(),e=!0);let t=Ne(),n=Ee(t),r=n.languages??He(t);if(r.length===0){console.log(`
|
|
1002
1013
|
No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
|
|
1003
1014
|
Detected languages: ${r.join(", ")}`),console.log(`
|
|
1004
|
-
Indexer readiness:`);for(let i of r){let s=
|
|
1005
|
-
Semantic provider readiness:`),console.log(`${s} typescript: ts-morph${o}`),i.reason&&console.log(` ${i.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0});
|
|
1015
|
+
Indexer readiness:`);for(let i of r){let s=ki(qt(i),t),o=s.runnable?" OK":s.installed?" WARN":" MISSING",a=s.resolvedBinary?` (${s.resolvedBinary})`:"";console.log(`${o} ${i}: ${s.binaryLabel}${a}`),s.note&&console.log(` ${s.note}`),!s.installed&&s.installUrl&&console.log(` install: ${s.installUrl}`),s.runnable||(e=!0)}if(r.includes("typescript")){let i=ar(t,n.semantic?.typescript?.tsconfigs),s=i.available?" OK":i.dependencyAvailable?" WARN":" MISSING",o=i.tsconfigPaths&&i.tsconfigPaths.length>1?` (${i.tsconfigPaths.length} tsconfigs)`:i.tsconfigPath?` (${i.tsconfigPath})`:"";console.log(`
|
|
1016
|
+
Semantic provider readiness:`),console.log(`${s} typescript: ts-morph${o}`),i.reason&&console.log(` ${i.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0});x.command("redundant-reexports").description("Find barrel re-exports that nobody imports through").option("-s, --scope <path>","Limit to files matching path").option("-n, --limit <n>","Number of results",N,30).action(e=>R(t=>{let n=S.redundantReexports(t,{scope:e.scope,limit:e.limit});if(n.length===0)return b.empty("No redundant re-exports found.");b.groupedByFile(n,r=>` ${r.shortName} (from ${r.originalFile})
|
|
1006
1017
|
barrel: ${r.barrelConsumers} consumer(s) | direct: ${r.directConsumers} consumer(s)`,r=>r.barrelFile),console.log(`
|
|
1007
|
-
${n.length} redundant re-export(s).`)}));
|
|
1008
|
-
Signature: ${r.signature} (${r.functions.length} functions)`,s=r.functions.map(o=>` ${
|
|
1018
|
+
${n.length} redundant re-export(s).`)}));x.command("similar-signatures").description("Find functions with near-identical type signatures (same shape)").option("-s, --scope <path>","Limit to files matching path").option("--min-loc <n>","Minimum LOC per function",N,3).option("-n, --limit <n>","Number of groups",N,20).action(e=>R(t=>{let n=S.similarSignatures(t,{scope:e.scope,minLoc:e.minLoc,limit:e.limit});if(n.length===0)return b.empty("No same-shape function groups found.");b.list(n,r=>{let i=`
|
|
1019
|
+
Signature: ${r.signature} (${r.functions.length} functions)`,s=r.functions.map(o=>` ${fe(o.file,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC)`).join(`
|
|
1009
1020
|
`);return`${i}
|
|
1010
1021
|
${s}`}),console.log(`
|
|
1011
|
-
${n.length} group(s) found.`)}));
|
|
1022
|
+
${n.length} group(s) found.`)}));x.command("init").description("Create a .scipquery.json config file for this project").action(()=>{let e=Ne(),t=He(e),n=ii(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)});x.command("watch").description("Watch for file changes and reindex automatically").option("--debounce <ms>","Ms to wait after last change (default: 30000)",parseInt).option("--cooldown <ms>","Min ms between reindexes (default: 60000)",parseInt).action(e=>{let t=Ne(),n=Ee(t);e.debounce&&((n.watch??={}).debounceMs=e.debounce),e.cooldown&&((n.watch??={}).cooldownMs=e.cooldown);let r=new Zt({projectRoot:t,config:n,languages:n.languages,onStatus:i=>{process.stdout.write(`\r\x1B[K${$l(i)}`)},onReindexComplete:i=>{console.log(`
|
|
1012
1023
|
Reindex complete in ${(i/1e3).toFixed(1)}s`)},onError:i=>{console.error(`
|
|
1013
1024
|
Watch error: ${i.message}`)}});console.log(`Watching ${t}`),console.log(`Debounce: ${n.watch?.debounceMs??3e4}ms | Cooldown: ${n.watch?.cooldownMs??6e4}ms`),console.log(`Press Ctrl+C to stop.
|
|
1014
1025
|
`),r.start(),process.on("SIGINT",()=>{r.stop(),console.log(`
|
|
1015
|
-
Stopped.`),process.exit(0)})});
|
|
1026
|
+
Stopped.`),process.exit(0)})});x.command("status").description("Show index status for this project").action(()=>{let e=Ne(),t=Ee(e),n=De(e,t),r=jt(e);if(console.log(`Project: ${e}`),console.log(`DB path: ${r}`),r!==n.dbPath&&console.log(`Config: ${n.dbPath} (fallback to project root index.db)`),(t.languages??He(e)).includes("typescript")){let i=ar(e,t.semantic?.typescript?.tsconfigs),s=i.available?"available":"fallback",o=i.tsconfigPaths&&i.tsconfigPaths.length>1?` (${i.tsconfigPaths.length} tsconfigs)`:i.tsconfigPath?` (${i.tsconfigPath})`:"";console.log(`TS sem: ${s}${o}`),i.reason&&console.log(`TS note: ${i.reason}`)}console.log(`Exists: ${jl(r)?"yes":"no"}`),jl(r)&&R(i=>{let s=S.stats(i);if(console.log(`Symbols: ${s.symbols}`),console.log(`Files: ${s.documents}`),console.log(`Size: ${$n(s.indexSizeBytes)}`),s.lastBuilt){let o=Math.round((Date.now()-s.lastBuilt.getTime())/1e3);console.log(`Built: ${o}s ago`)}})});Wx()&&x.parse();function Wx(){if(!process.argv[1])return!1;let e=Zr(import.meta.url);try{return Bl(e)===Bl(process.argv[1])}catch{return e===process.argv[1]}}export{x as program,Se as renderHeuristicNotice};
|
|
1016
1027
|
//# sourceMappingURL=cli.js.map
|