scip-query 0.17.1 → 0.17.2

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.
Files changed (143) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/{chunk-HZVG4KID.js → chunk-2A7LUMZP.js} +2 -2
  3. package/dist/{chunk-WENI5ZDR.js → chunk-4H7T7FIM.js} +2 -2
  4. package/dist/{chunk-V7MX6YUF.js → chunk-4QBRVI7D.js} +2 -2
  5. package/dist/chunk-4XTPZ5CR.js +9 -0
  6. package/dist/chunk-6AITNECC.js +928 -0
  7. package/dist/chunk-6JSTKSZH.js +3 -0
  8. package/dist/{chunk-2DUWNJKE.js → chunk-7LERNHDG.js} +2 -2
  9. package/dist/{chunk-75H6GOND.js → chunk-7ROLM67J.js} +2 -2
  10. package/dist/{chunk-RPPV6Y4K.js → chunk-7VR5TNOI.js} +2 -2
  11. package/dist/chunk-A2GX3PYV.js +5 -0
  12. package/dist/{chunk-E5HPTSRD.js → chunk-APCXCRED.js} +2 -2
  13. package/dist/{chunk-5QSMW5IO.js → chunk-ATC4MEVA.js} +2 -2
  14. package/dist/chunk-AWYKDRYV.js +2 -0
  15. package/dist/{chunk-QYBCGCY5.js → chunk-AY44MGWS.js} +2 -2
  16. package/dist/{chunk-WT34AUWL.js → chunk-BEGHYHOQ.js} +2 -2
  17. package/dist/{chunk-JYBP5ZIR.js → chunk-BPMBOZAN.js} +2 -2
  18. package/dist/{chunk-BW4VDICR.js → chunk-C7MBQSIC.js} +2 -2
  19. package/dist/{chunk-KWQKWY6M.js → chunk-CHJ3QROR.js} +2 -2
  20. package/dist/{chunk-BBTVIIOI.js → chunk-CVWX24IY.js} +2 -2
  21. package/dist/chunk-DJI446FQ.js +18 -0
  22. package/dist/{chunk-CSMPXDYE.js → chunk-ELLPMCWA.js} +2 -2
  23. package/dist/{chunk-35DURZXI.js → chunk-FVLZB54V.js} +2 -2
  24. package/dist/{chunk-WGDIA2TU.js → chunk-G6DDSHMD.js} +2 -2
  25. package/dist/{chunk-OP5JXGDV.js → chunk-IG6X65MG.js} +2 -2
  26. package/dist/{chunk-KZ2LZBQT.js → chunk-IKMOYFUM.js} +2 -2
  27. package/dist/{chunk-G4IUQW27.js → chunk-IS7DZ7TB.js} +2 -2
  28. package/dist/{chunk-HGO3D2JD.js → chunk-J7IMQRCU.js} +2 -2
  29. package/dist/{chunk-OBPR6E5Z.js → chunk-K4XL4HOK.js} +2 -2
  30. package/dist/{chunk-W3HSUCRG.js → chunk-K53GNKY3.js} +2 -2
  31. package/dist/{chunk-5N5ZC566.js → chunk-K65T4TJS.js} +2 -2
  32. package/dist/{chunk-OC7XDK62.js → chunk-KA7RMBVU.js} +2 -2
  33. package/dist/{chunk-IKAJI4SI.js → chunk-KJOKTZUE.js} +2 -2
  34. package/dist/chunk-KSD6IWF4.js +38 -0
  35. package/dist/{chunk-SQJ72PQW.js → chunk-LEKXKHIQ.js} +4 -4
  36. package/dist/{chunk-2TM23JYJ.js → chunk-LFPQFRCX.js} +2 -2
  37. package/dist/{chunk-Y5BOEWAE.js → chunk-LL5NQB5V.js} +2 -2
  38. package/dist/{chunk-FY6RCFDH.js → chunk-MBVHEPHQ.js} +2 -2
  39. package/dist/{chunk-SSH2NPYS.js → chunk-MFIA6EIT.js} +2 -2
  40. package/dist/{chunk-HYRSGWFX.js → chunk-N3JH45WR.js} +2 -2
  41. package/dist/{chunk-KWMRY4RN.js → chunk-NJD4C5G5.js} +3 -3
  42. package/dist/{chunk-UKUISUS6.js → chunk-NJTIAQY7.js} +2 -2
  43. package/dist/{chunk-LG33DNTZ.js → chunk-NX2YAXVQ.js} +2 -2
  44. package/dist/{chunk-VDHEX6YO.js → chunk-O5A7BTMA.js} +2 -2
  45. package/dist/{chunk-FZXN37RN.js → chunk-O7NA5FCA.js} +2 -2
  46. package/dist/{chunk-U3JW5AYG.js → chunk-OINSINYW.js} +2 -2
  47. package/dist/{chunk-CKRVVBM6.js → chunk-OQFA2SUQ.js} +2 -2
  48. package/dist/{chunk-DQYG5JHT.js → chunk-OQFPCIXO.js} +2 -2
  49. package/dist/{chunk-PPAT3XUL.js → chunk-P6FOIU7O.js} +2 -2
  50. package/dist/{chunk-7H37Z4UO.js → chunk-PQD7P6WB.js} +2 -2
  51. package/dist/{chunk-Y4BBVPRK.js → chunk-Q4GKL4CC.js} +2 -2
  52. package/dist/{chunk-IZLWLO4X.js → chunk-ROMKXEUM.js} +2 -2
  53. package/dist/{chunk-BTYDBDX5.js → chunk-RUV4KHWA.js} +2 -2
  54. package/dist/{chunk-O56VBJKB.js → chunk-S22ICAWV.js} +2 -2
  55. package/dist/chunk-SALRDXWM.js +121 -0
  56. package/dist/{chunk-MON5XXTG.js → chunk-SON6DQNK.js} +2 -2
  57. package/dist/{chunk-W2I4QAW7.js → chunk-SSGACGAD.js} +2 -2
  58. package/dist/{chunk-PA2MQKXD.js → chunk-SUYCF4SX.js} +2 -2
  59. package/dist/chunk-SXDXR5FH.js +2 -0
  60. package/dist/{chunk-TR7C5HOC.js → chunk-T4P27T6S.js} +2 -2
  61. package/dist/{chunk-O27267B6.js → chunk-U4G4UYLB.js} +2 -2
  62. package/dist/{chunk-MBDBNQBW.js → chunk-W7FNZKX5.js} +2 -2
  63. package/dist/chunk-WD3PAQJT.js +10 -0
  64. package/dist/{chunk-623AZLTE.js → chunk-XLJORP6N.js} +2 -2
  65. package/dist/chunk-XTF6ELXT.js +3 -0
  66. package/dist/{chunk-7Z5UT44B.js → chunk-YMFHC5J2.js} +2 -2
  67. package/dist/{chunk-HJYHSTCP.js → chunk-YYYERNQL.js} +2 -2
  68. package/dist/chunk-Z4MCFCGX.js +3 -0
  69. package/dist/cli.js +3 -1528
  70. package/dist/command-descriptors-7UUURHWT.js +599 -0
  71. package/dist/direct-navigation-CVCFER5G.js +3 -0
  72. package/dist/index.js +1 -1
  73. package/dist/queries/affected.js +1 -1
  74. package/dist/queries/bottlenecks.js +1 -1
  75. package/dist/queries/call-graph.js +1 -1
  76. package/dist/queries/change-surface.js +1 -1
  77. package/dist/queries/cleanup-plan.js +1 -1
  78. package/dist/queries/co-change.d.ts +2 -0
  79. package/dist/queries/co-change.js +1 -1
  80. package/dist/queries/code.js +1 -1
  81. package/dist/queries/complexity-hotspots.js +1 -1
  82. package/dist/queries/complexity.js +1 -1
  83. package/dist/queries/convergence.js +1 -1
  84. package/dist/queries/coupling.js +1 -1
  85. package/dist/queries/dataflow.js +1 -1
  86. package/dist/queries/dead.js +1 -1
  87. package/dist/queries/decorative-checkers.js +1 -1
  88. package/dist/queries/deps.js +1 -1
  89. package/dist/queries/diff-gate.js +1 -1
  90. package/dist/queries/diff-impact.js +1 -1
  91. package/dist/queries/doc-drift.js +1 -1
  92. package/dist/queries/drift.js +1 -1
  93. package/dist/queries/duplicate-bodies.js +1 -1
  94. package/dist/queries/extract-candidates.js +1 -1
  95. package/dist/queries/fan.js +1 -1
  96. package/dist/queries/health.js +1 -1
  97. package/dist/queries/hierarchy.js +1 -1
  98. package/dist/queries/hotspots.js +1 -1
  99. package/dist/queries/imports.js +1 -1
  100. package/dist/queries/incomplete-migration.js +1 -1
  101. package/dist/queries/index.js +1 -1
  102. package/dist/queries/isolated.js +1 -1
  103. package/dist/queries/locality-candidates.js +1 -1
  104. package/dist/queries/members.js +1 -1
  105. package/dist/queries/methods.js +1 -1
  106. package/dist/queries/not-implemented.js +1 -1
  107. package/dist/queries/outline.js +1 -1
  108. package/dist/queries/passthrough-candidates.js +1 -1
  109. package/dist/queries/plan-context.d.ts +2 -0
  110. package/dist/queries/plan-context.js +1 -1
  111. package/dist/queries/recent-duplicates.js +1 -1
  112. package/dist/queries/redundant-reexports.js +1 -1
  113. package/dist/queries/refs.js +1 -1
  114. package/dist/queries/self-audit.js +1 -1
  115. package/dist/queries/similar-signatures.js +1 -1
  116. package/dist/queries/similar.js +1 -1
  117. package/dist/queries/slice.js +1 -1
  118. package/dist/queries/stale-abstractions.js +1 -1
  119. package/dist/queries/surface.js +1 -1
  120. package/dist/queries/symbols.js +1 -1
  121. package/dist/queries/system.js +1 -1
  122. package/dist/queries/test-quality.js +1 -1
  123. package/dist/queries/trace.js +1 -1
  124. package/dist/queries/twin-ab.js +1 -1
  125. package/dist/queries/twin-drift.js +1 -1
  126. package/dist/queries/unused-imports.js +1 -1
  127. package/dist/queries/unused-params.js +1 -1
  128. package/dist/queries/wrapper-candidates.js +1 -1
  129. package/dist/reindex-worker.js +1 -1
  130. package/dist/reindex.js +1 -1
  131. package/dist/runtime.js +1 -1
  132. package/dist/watch-server.js +4 -4
  133. package/docs/COMMAND_REFERENCE.md +3 -0
  134. package/package.json +1 -1
  135. package/dist/chunk-2HCWAL42.js +0 -3
  136. package/dist/chunk-3YEBIYXL.js +0 -38
  137. package/dist/chunk-6TJERPN3.js +0 -2
  138. package/dist/chunk-E7BTIEAY.js +0 -2
  139. package/dist/chunk-EUMETOTD.js +0 -21
  140. package/dist/chunk-GRHA5NGF.js +0 -2
  141. package/dist/chunk-IHD2CHMX.js +0 -10
  142. package/dist/chunk-U267E6YN.js +0 -120
  143. package/dist/chunk-X566NT42.js +0 -9
@@ -1,4 +1,4 @@
1
- import{a as Z,b as ee}from"./chunk-4L4X66GE.js";import{a as ot}from"./chunk-P5XHIJHI.js";import{$ as bt,Aa as Re,C as st,Ca as re,Da as Ot,E as ut,F as pt,Fa as Mt,I as be,O as $,Q as gt,U as ft,V as Y,W as mt,X as K,Y as ht,Z as yt,_ as St,a as X,e as Ze,g as et,ga as Pt,h as T,ha as xt,i as C,ia as Rt,ja as It,k as rt,ka as vt,la as Et,m as it,ma as Ft,n as at,na as jt,o as Q,oa as wt,pa as _t,qa as B,ra as te,sa as Dt,u as A,ua as ne,va as Tt,wa as Pe,xa as kt,ya as xe}from"./chunk-U267E6YN.js";import{b as tt,c as nt,f as w,g as V,h as ct,i as lt,j as dt}from"./chunk-SMBIGBGN.js";import{a as k,b as O}from"./chunk-3M2UCPFS.js";import{e as F,f as L}from"./chunk-JHK2DMUQ.js";import{a as z,b as Se,c as Ke}from"./chunk-TFWDJDGO.js";import{execFileSync as aa}from"child_process";import{createHash as sa}from"crypto";import{closeSync as oa,copyFileSync as fe,existsSync as E,mkdirSync as ge,mkdtempSync as ca,openSync as la,readdirSync as da,readFileSync as me,renameSync as An,rmSync as D,statSync as ua,writeFileSync as pa}from"fs";import{basename as pe,dirname as h,extname as ga,join as R,resolve as Tn}from"path";import{platform as fa}from"os";import{existsSync as Nt,readdirSync as ir}from"fs";import{isAbsolute as ar,join as Ie,resolve as sr}from"path";var or={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},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"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",ar(r)?r:sr(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},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",Lt(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",Lt(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=Ie(e,"vendor","bin","scip-php"),r=Ie(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Nt(r)?r:Nt(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function ve(e){return or[e]}function Lt(e,t){let n;try{n=ir(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Ie(e,i);return null}import{execFileSync as Fe}from"child_process";import{existsSync as Ee,readFileSync as cr}from"fs";import{createRequire as lr}from"module";import{platform as dr}from"os";import{dirname as Ct,join as ie}from"path";var ur=lr(import.meta.url);function je(e){return[e.indexerBinary,...e.binaryAliases??[]]}function we(e){let t=je(e);return t.length===1?t[0]:t.join(" or ")}function ae(e){for(let t of je(e))if(z(t))return t;return gr(e)}function At(e){return ae(e)!==null||pr(e)}function pr(e){return $t(e)!==null}function gr(e){let t=$t(e);if(!t)return null;let r=JSON.parse(cr(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return ie(Ct(t),r);for(let i of je(e)){let a=r[i];if(a)return ie(Ct(t),a)}return null}function $t(e){if(!e.bundledNpmPackage)return null;try{return ur.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function Bt(e,t){for(let n of e.projectLocalBinaries??[]){let r=ie(t,n);if(Ee(r))return r}return null}function Gt(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Jt(n,t))return t;let r=fr(n,t);return r?{...t,DOTNET_ROOT:r}:t}function Ut(e,t){let n=e.installMethods,r=we(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(z(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Fe(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let a=ae(e);if(a){let s=a===e.indexerBinary?"":` (using ${a})`;return t(`Successfully installed ${r} via ${i.label}${s}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(a){let s=a instanceof Error?a.message:String(a);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function fr(e,t){for(let n of mr(t))if(Jt(e,{...t,DOTNET_ROOT:n}))return n;return null}function mr(e){let t=[],n=e.DOTNET_ROOT;if(n&&Ee(n)&&t.push(n),dr()==="darwin"&&z("brew"))try{let r=Fe("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=ie(r,"libexec");Ee(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Jt(e,t){try{return Fe(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import{readFileSync as Fs}from"fs";import{dirname as ws,join as _s}from"path";var Wt=at({kind:"file-dependency-graph",invalidation:Q("file-dependency-graph"),serialize:e=>JSON.stringify(e),deserialize:Rr}),hr=tt("file-dep-graph",{clearGroups:["whole-project"]});function M(e,t,n={}){let r=n.scipEdges??"all-references";return hr.get(e,`${r}:${t??""}`,()=>{let i=new Set(w(e,{includeIgnored:!1})),a=rt(e),s=br(t,r),o=0,l=0,c=null,d=!1,u=0,g=0;return F("file-dep-graph.product",()=>{if(a){let f=Wt.read(e,s,a);if(f){d=!0;let b=xr(f);return o=f.sourceFileCount,l=f.sourceEdgeCount,u=f.scipEdgeCount,g=b.size,c=f.sourceImportFingerprint,b}}let m=F("file-dep-graph.source-imports",()=>{let f=yr(e,i,t);return o=f.files.length,l=f.edges.length,c=f.fingerprint,f},()=>({scope:t??null,files:o,edges:l})),p=new Map,S=(f,b)=>Fr(e,p,i,f,b);F("file-dep-graph.scip-edges",()=>{for(let f of Er(e,t,r))u+=1,S(f.from_file,f.to_file)},()=>({scope:t??null,edges:u}));for(let f of m.edges)S(f.fromFile,f.toFile);return g=p.size,a&&Wt.write(e,s,a,{sourceImportFingerprint:m.fingerprint,sourceFileCount:m.files.length,sourceEdgeCount:m.edges.length,scipEdgeCount:u,graph:Pr(p)}),p},()=>({scope:t??null,available:a!==null,hit:d,files:o,sourceEdges:l,scipEdges:u,graphFiles:g,sourceImportFingerprint:c}))})}function yr(e,t,n){let r=[],i=[];for(let a of t)if(!(n&&!a.includes(n))){r.push(a);for(let s of st(e,a))s.sourcePath&&i.push({fromFile:a,toFile:s.sourcePath})}return{files:r,edges:i,fingerprint:Sr(r,i)}}function Sr(e,t){let n=t.map(r=>`${r.fromFile}\0${r.toFile}`).sort();return C(JSON.stringify({files:e,edges:n}))}function br(e,t){return`edge-mode-v2:${t}:${e??"<all>"}`}function Pr(e){return[...e].map(([t,n])=>[t,[...n]])}function xr(e){return new Map(e.graph.map(([t,n])=>[t,new Set(n)]))}function Rr(e){let t=JSON.parse(e);return Ir(t)?t:null}function Ir(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.sourceImportFingerprint=="string"&&typeof t.sourceFileCount=="number"&&typeof t.sourceEdgeCount=="number"&&typeof t.scipEdgeCount=="number"&&Array.isArray(t.graph)&&t.graph.every(vr)}function vr(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&Array.isArray(e[1])&&e[1].every(t=>typeof t=="string")}function Er(e,t,n){let r=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[],a=n==="imports-only"?"AND m.role = 2":"AND m.role != 1";return e.all(`SELECT DISTINCT
1
+ import{a as Z,b as ee}from"./chunk-4L4X66GE.js";import{a as ot}from"./chunk-P5XHIJHI.js";import{$ as bt,Aa as Re,C as st,Ca as re,Da as Ot,E as ut,F as pt,Fa as Mt,I as be,O as $,Q as gt,U as ft,V as Y,W as mt,X as K,Y as ht,Z as yt,_ as St,a as X,e as Ze,g as et,ga as Pt,h as T,ha as xt,i as C,ia as Rt,ja as It,k as rt,ka as vt,la as Et,m as it,ma as Ft,n as at,na as jt,o as Q,oa as wt,pa as _t,qa as B,ra as te,sa as Dt,u as A,ua as ne,va as Tt,wa as Pe,xa as kt,ya as xe}from"./chunk-SALRDXWM.js";import{b as tt,c as nt,f as w,g as V,h as ct,i as lt,j as dt}from"./chunk-SMBIGBGN.js";import{a as k,b as O}from"./chunk-3M2UCPFS.js";import{e as F,f as L}from"./chunk-JHK2DMUQ.js";import{a as z,b as Se,c as Ke}from"./chunk-TFWDJDGO.js";import{execFileSync as aa}from"child_process";import{createHash as sa}from"crypto";import{closeSync as oa,copyFileSync as fe,existsSync as E,mkdirSync as ge,mkdtempSync as ca,openSync as la,readdirSync as da,readFileSync as me,renameSync as An,rmSync as D,statSync as ua,writeFileSync as pa}from"fs";import{basename as pe,dirname as h,extname as ga,join as R,resolve as Tn}from"path";import{platform as fa}from"os";import{existsSync as Nt,readdirSync as ir}from"fs";import{isAbsolute as ar,join as Ie,resolve as sr}from"path";var or={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},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"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",ar(r)?r:sr(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},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",Lt(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",Lt(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=Ie(e,"vendor","bin","scip-php"),r=Ie(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Nt(r)?r:Nt(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function ve(e){return or[e]}function Lt(e,t){let n;try{n=ir(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Ie(e,i);return null}import{execFileSync as Fe}from"child_process";import{existsSync as Ee,readFileSync as cr}from"fs";import{createRequire as lr}from"module";import{platform as dr}from"os";import{dirname as Ct,join as ie}from"path";var ur=lr(import.meta.url);function je(e){return[e.indexerBinary,...e.binaryAliases??[]]}function we(e){let t=je(e);return t.length===1?t[0]:t.join(" or ")}function ae(e){for(let t of je(e))if(z(t))return t;return gr(e)}function At(e){return ae(e)!==null||pr(e)}function pr(e){return $t(e)!==null}function gr(e){let t=$t(e);if(!t)return null;let r=JSON.parse(cr(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return ie(Ct(t),r);for(let i of je(e)){let a=r[i];if(a)return ie(Ct(t),a)}return null}function $t(e){if(!e.bundledNpmPackage)return null;try{return ur.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function Bt(e,t){for(let n of e.projectLocalBinaries??[]){let r=ie(t,n);if(Ee(r))return r}return null}function Gt(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Jt(n,t))return t;let r=fr(n,t);return r?{...t,DOTNET_ROOT:r}:t}function Ut(e,t){let n=e.installMethods,r=we(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(z(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Fe(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let a=ae(e);if(a){let s=a===e.indexerBinary?"":` (using ${a})`;return t(`Successfully installed ${r} via ${i.label}${s}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(a){let s=a instanceof Error?a.message:String(a);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function fr(e,t){for(let n of mr(t))if(Jt(e,{...t,DOTNET_ROOT:n}))return n;return null}function mr(e){let t=[],n=e.DOTNET_ROOT;if(n&&Ee(n)&&t.push(n),dr()==="darwin"&&z("brew"))try{let r=Fe("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=ie(r,"libexec");Ee(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Jt(e,t){try{return Fe(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import{readFileSync as Fs}from"fs";import{dirname as ws,join as _s}from"path";var Wt=at({kind:"file-dependency-graph",invalidation:Q("file-dependency-graph"),serialize:e=>JSON.stringify(e),deserialize:Rr}),hr=tt("file-dep-graph",{clearGroups:["whole-project"]});function M(e,t,n={}){let r=n.scipEdges??"all-references";return hr.get(e,`${r}:${t??""}`,()=>{let i=new Set(w(e,{includeIgnored:!1})),a=rt(e),s=br(t,r),o=0,l=0,c=null,d=!1,u=0,g=0;return F("file-dep-graph.product",()=>{if(a){let f=Wt.read(e,s,a);if(f){d=!0;let b=xr(f);return o=f.sourceFileCount,l=f.sourceEdgeCount,u=f.scipEdgeCount,g=b.size,c=f.sourceImportFingerprint,b}}let m=F("file-dep-graph.source-imports",()=>{let f=yr(e,i,t);return o=f.files.length,l=f.edges.length,c=f.fingerprint,f},()=>({scope:t??null,files:o,edges:l})),p=new Map,S=(f,b)=>Fr(e,p,i,f,b);F("file-dep-graph.scip-edges",()=>{for(let f of Er(e,t,r))u+=1,S(f.from_file,f.to_file)},()=>({scope:t??null,edges:u}));for(let f of m.edges)S(f.fromFile,f.toFile);return g=p.size,a&&Wt.write(e,s,a,{sourceImportFingerprint:m.fingerprint,sourceFileCount:m.files.length,sourceEdgeCount:m.edges.length,scipEdgeCount:u,graph:Pr(p)}),p},()=>({scope:t??null,available:a!==null,hit:d,files:o,sourceEdges:l,scipEdges:u,graphFiles:g,sourceImportFingerprint:c}))})}function yr(e,t,n){let r=[],i=[];for(let a of t)if(!(n&&!a.includes(n))){r.push(a);for(let s of st(e,a))s.sourcePath&&i.push({fromFile:a,toFile:s.sourcePath})}return{files:r,edges:i,fingerprint:Sr(r,i)}}function Sr(e,t){let n=t.map(r=>`${r.fromFile}\0${r.toFile}`).sort();return C(JSON.stringify({files:e,edges:n}))}function br(e,t){return`edge-mode-v2:${t}:${e??"<all>"}`}function Pr(e){return[...e].map(([t,n])=>[t,[...n]])}function xr(e){return new Map(e.graph.map(([t,n])=>[t,new Set(n)]))}function Rr(e){let t=JSON.parse(e);return Ir(t)?t:null}function Ir(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.sourceImportFingerprint=="string"&&typeof t.sourceFileCount=="number"&&typeof t.sourceEdgeCount=="number"&&typeof t.scipEdgeCount=="number"&&Array.isArray(t.graph)&&t.graph.every(vr)}function vr(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&Array.isArray(e[1])&&e[1].every(t=>typeof t=="string")}function Er(e,t,n){let r=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[],a=n==="imports-only"?"AND m.role = 2":"AND m.role != 1";return e.all(`SELECT DISTINCT
2
2
  d1.relative_path AS from_file,
3
3
  d2.relative_path AS to_file
4
4
  FROM mentions m
package/dist/reindex.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,h as On,i as jn,j as _n}from"./chunk-MON5XXTG.js";import{a as Fn}from"./chunk-YZXV3CU3.js";import{A as En,B as Ee,C as Tn,E as Dn,a as Ao,b as ve,c as rt,d as it,e as ot,f as at,g as st,h as ct,i as T,j as b,o as Rn,p as xn,q as Pe,r as In,s as Pn,t as wn,u as ut,v as dt,y as kn,z as ke}from"./chunk-SQJ72PQW.js";import"./chunk-P5XHIJHI.js";import{a as Ie}from"./chunk-QEIGJJBC.js";import{a as Lo,b as we,e as vn}from"./chunk-E7BTIEAY.js";import"./chunk-7XP7ZRSI.js";import"./chunk-JLZUM476.js";import{J as Sn,K as bn,d as K}from"./chunk-TLTLJ4SW.js";import{a as xe}from"./chunk-64MNV6AB.js";import{s as Z,t as ee}from"./chunk-M2TRDR25.js";import{execFileSync as ad}from"child_process";import{createHash as sd}from"crypto";import{closeSync as cd,copyFileSync as Ze,existsSync as O,mkdirSync as Ke,mkdtempSync as ud,openSync as dd,readdirSync as ld,readFileSync as et,renameSync as Io,rmSync as W,statSync as pd,writeFileSync as gd}from"fs";import{basename as Xe,dirname as h,extname as fd,join as I,resolve as mo}from"path";import{platform as md}from"os";import{randomUUID as Cn}from"crypto";import{closeSync as An,mkdirSync as Mo,openSync as Ln,readFileSync as Mn,unlinkSync as Nn,writeFileSync as $n}from"fs";import{dirname as No,join as $o}from"path";function Gn(e,t={}){return te($o(e,"gc.lock"),t)}function te(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;Mo(No(e),{recursive:!0});do{let a=Cn();try{let s=Ln(e,"wx");try{let c={version:1,pid:process.pid,token:a,startedAt:new Date(i()).toISOString()};$n(s,`${JSON.stringify(c)}
1
+ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,h as On,i as jn,j as _n}from"./chunk-SON6DQNK.js";import{a as Fn}from"./chunk-YZXV3CU3.js";import{A as En,B as Ee,C as Tn,E as Dn,a as Ao,b as ve,c as rt,d as it,e as ot,f as at,g as st,h as ct,i as T,j as b,o as Rn,p as xn,q as Pe,r as In,s as Pn,t as wn,u as ut,v as dt,y as kn,z as ke}from"./chunk-LEKXKHIQ.js";import"./chunk-P5XHIJHI.js";import{a as Ie}from"./chunk-QEIGJJBC.js";import{a as Lo,b as we,e as vn}from"./chunk-Z4MCFCGX.js";import"./chunk-7XP7ZRSI.js";import"./chunk-JLZUM476.js";import{J as Sn,K as bn,d as K}from"./chunk-TLTLJ4SW.js";import{a as xe}from"./chunk-64MNV6AB.js";import{s as Z,t as ee}from"./chunk-M2TRDR25.js";import{execFileSync as ad}from"child_process";import{createHash as sd}from"crypto";import{closeSync as cd,copyFileSync as Ze,existsSync as O,mkdirSync as Ke,mkdtempSync as ud,openSync as dd,readdirSync as ld,readFileSync as et,renameSync as Io,rmSync as W,statSync as pd,writeFileSync as gd}from"fs";import{basename as Xe,dirname as h,extname as fd,join as I,resolve as mo}from"path";import{platform as md}from"os";import{randomUUID as Cn}from"crypto";import{closeSync as An,mkdirSync as Mo,openSync as Ln,readFileSync as Mn,unlinkSync as Nn,writeFileSync as $n}from"fs";import{dirname as No,join as $o}from"path";function Gn(e,t={}){return te($o(e,"gc.lock"),t)}function te(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;Mo(No(e),{recursive:!0});do{let a=Cn();try{let s=Ln(e,"wx");try{let c={version:1,pid:process.pid,token:a,startedAt:new Date(i()).toISOString()};$n(s,`${JSON.stringify(c)}
2
2
  `)}finally{An(s)}return{release:()=>Un(e,a)}}catch(s){if(s.code!=="EEXIST")return null;let c=Vn(e);if(c&&(c.pid===void 0||!T(c.pid))){Go(e,c);continue}if(Date.now()>=o)return null;Vo(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function Vn(e){try{let t=Mn(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function Go(e,t){let n=`${e}.reclaim`,r=Cn(),i;try{i=Ln(n,"wx")}catch{return!1}try{$n(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
3
3
  `)}finally{An(i)}try{let o=Vn(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Nn(e),!0)}catch{return!1}finally{Un(n,r)}}function Un(e,t){try{let n=JSON.parse(Mn(e,"utf8"));n.pid===process.pid&&n.token===t&&Nn(e)}catch{}}function Vo(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import Uo from"better-sqlite3";import{execFileSync as Wo}from"child_process";import{existsSync as Bo,readdirSync as Jo,readFileSync as Ho}from"fs";import{extname as Te,join as Wn}from"path";function J(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Bn({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Bn(e){let t=new Set((e.extensions??Sn).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Bo(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Fn(e.projectRoot),r=qo(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Uo(e.dbPath);try{let o=Yo(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
4
4
  VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let p=0;for(let l of d){if(o.has(l))continue;let m=Ho(Wn(e.projectRoot,l),"utf-8"),g=a.run(Qo(l),l,m);p+=Number(g.changes)}return p})(r),u={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${u.existing} already present).`),u}finally{i.close()}}function qo(e,t){let n=zo(e,t);if(n)return n;let r=[],i=o=>{let a=o?Wn(e,o):e,s;try{s=Jo(a,{withFileTypes:!0})}catch{return}for(let c of s){if(bn.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(Te(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function zo(e,t){try{return Wo("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
package/dist/runtime.js CHANGED
@@ -1,2 +1,2 @@
1
- import{b as j,c as b,d as D,f,g as T,k as m,l as W}from"./chunk-MON5XXTG.js";import{a as k}from"./chunk-YZXV3CU3.js";import{c as g,d as y}from"./chunk-E7BTIEAY.js";import{fork as $}from"child_process";import{statSync as _}from"fs";import{isAbsolute as F,join as G,relative as M}from"path";import{watch as N}from"chokidar";import A from"ignore";var S=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=T(t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(e=>console.error(e.message)),this.gitignoreFilter=k(t.projectRoot),this.extraIgnore=A(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=N(this.projectRoot,{ignoreInitial:!0,ignored:(e,i)=>this.isIgnoredWatchPath(e,i?.isDirectory()??!1)});t.on("all",(e,i)=>{this.stopped||this.handleFileChange(i)}),t.on("error",e=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}),this.fsWatchers.push(t)}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(t,e={}){if(!e.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=P(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}isIgnoredWatchPath(t,e){let i=this.relativeWatchPath(t);if(!i)return!1;let r=e?`${i}/`:i;return r===".git/"||r.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)}handleFileChange(t){let e=this.relativeWatchPath(t);!e||e===".."||e.startsWith("../")||e===".git"||e.startsWith(".git/")||this.gitignoreFilter.isIgnored(e)||this.extraIgnore.ignores(e)||e.endsWith("index.db")||e.endsWith("index.scip")||e.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:e})}relativeWatchPath(t){let e=F(t)?t:G(this.projectRoot,t);return M(this.projectRoot,e).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=P(this.pendingTrigger,t),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 e=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:e}),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 o=Date.now()+r;this.setStatus({state:"cooldown",until:o,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 e=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let i=Date.now();this.setStatus({state:"indexing",startedAt:i}),this.runReindex(e).then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,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(t){return new Promise((e,i)=>{let r=Date.now(),o=f(this.projectRoot),n=Object.keys(o).length>0?o:this.config,c=m(this.projectRoot,n),a=n.indexer?.typescript,l=n.indexer?.clojure,h=$(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:c.indexPath,SCIP_REINDEX_OUTPUT_DB:c.dbPath,SCIP_REINDEX_LANGUAGES:(n.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(n.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:a?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:a?.projectMode??this.typescriptProjectMode,projects:a?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});h.on("exit",d=>{d===0?e(Date.now()-r):i(new Error(`Reindex worker exited with code ${d}`))}),h.on("error",i)})}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)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let t=this.lastGitState,e=this.readGitState();if(!t||!e||this.stopped){this.lastGitState=e;return}this.lastGitState=e;let i=t.head!==e.head,r=t.indexPath!==e.indexPath||t.indexMtimeMs!==e.indexMtimeMs||t.indexSize!==e.indexSize;i&&r?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):i?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):r&&this.scheduleReindex({kind:"watch-git-index",detail:e.indexPath??"index changed"})}readGitState(){let t=g(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let e=y(this.projectRoot,t),i={head:g(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:e};try{let r=_(e);i.indexMtimeMs=r.mtimeMs,i.indexSize=r.size}catch{i.indexMtimeMs=void 0,i.indexSize=void 0}return i}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function P(s,t){return s?s.kind===t.kind?s.detail===t.detail?s:{kind:s.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${s.kind}, ${t.kind}`}:t}import{existsSync as x,mkdirSync as O,symlinkSync as L,readlinkSync as I,unlinkSync as w,readdirSync as U}from"fs";import{join as p,dirname as R,resolve as u,relative as X,isAbsolute as q}from"path";import{homedir as v,platform as H}from"os";import{fileURLToPath as z}from"url";var J=H()==="win32",C=["_shared","scip-query","scip-setup","scip-calibrate","scip-cleanup-audit","scip-cleanup-improve","scip-integrity-audit","scip-twin-drift","scip-claim-audit","scip-probe-reachability","scip-hyper-optimization","scip-api-impact","scip-concrete-plan","scip-conductor","scip-debug","scip-explore","scip-triage-issue","scip-diagram","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook","scip-tla-model-system"];function K(s={}){let t=s.quiet?()=>{}:console.log,e=z(import.meta.url),i=u(R(e),"..","skills"),r=[p(v(),".claude","skills"),p(v(),".codex","skills"),p(v(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let n of r){let c=R(n);if(!x(c))continue;O(n,{recursive:!0});let a=Y(n);B(n,i,a,o,t);for(let l of C){let h=p(i,l),d=p(n,l);if(!x(h)){o.skipped.push(`${a}/${l}`);continue}if(x(d)){try{let E=I(d);if(u(E)===u(h)){o.alreadyLinked.push(`${a}/${l}`),t(` ok: ${l} \u2192 ${a} (already linked)`);continue}}catch{o.skipped.push(`${a}/${l}`),t(` skip: ${l} \u2192 ${a} (exists, not a symlink)`);continue}w(d)}L(h,d,J?"junction":"dir"),o.installed.push(`${a}/${l}`),t(` done: ${l} \u2192 ${a}`)}}return o}function B(s,t,e,i,r){let o=new Set(C);for(let n of U(s)){if(o.has(n))continue;let c=p(s,n),a;try{a=u(R(c),I(c))}catch{continue}V(a,t)&&(w(c),i.pruned.push(`${e}/${n}`),r(` prune: ${n} \u2192 ${e} (removed stale scip-query skill link)`))}}function V(s,t){let e=X(u(t),u(s));return e===""||!e.startsWith("..")&&!q(e)}function Y(s){return s.includes(".codex")?"Codex":s.includes(".agents")?"Agents":"Claude"}export{S as Watcher,b as getScipVersion,W as initProjectConfig,K as installSkills,j as isScipInstalled,f as loadProjectConfig,D as printScipInstallInstructions,m as resolveIndexStoragePaths};
1
+ import{b as j,c as b,d as D,f,g as T,k as m,l as W}from"./chunk-SON6DQNK.js";import{a as k}from"./chunk-YZXV3CU3.js";import{c as g,d as y}from"./chunk-Z4MCFCGX.js";import{fork as $}from"child_process";import{statSync as _}from"fs";import{isAbsolute as F,join as G,relative as M}from"path";import{watch as N}from"chokidar";import A from"ignore";var S=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=T(t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(e=>console.error(e.message)),this.gitignoreFilter=k(t.projectRoot),this.extraIgnore=A(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=N(this.projectRoot,{ignoreInitial:!0,ignored:(e,i)=>this.isIgnoredWatchPath(e,i?.isDirectory()??!1)});t.on("all",(e,i)=>{this.stopped||this.handleFileChange(i)}),t.on("error",e=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}),this.fsWatchers.push(t)}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(t,e={}){if(!e.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=P(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}isIgnoredWatchPath(t,e){let i=this.relativeWatchPath(t);if(!i)return!1;let r=e?`${i}/`:i;return r===".git/"||r.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)}handleFileChange(t){let e=this.relativeWatchPath(t);!e||e===".."||e.startsWith("../")||e===".git"||e.startsWith(".git/")||this.gitignoreFilter.isIgnored(e)||this.extraIgnore.ignores(e)||e.endsWith("index.db")||e.endsWith("index.scip")||e.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:e})}relativeWatchPath(t){let e=F(t)?t:G(this.projectRoot,t);return M(this.projectRoot,e).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=P(this.pendingTrigger,t),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 e=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:e}),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 o=Date.now()+r;this.setStatus({state:"cooldown",until:o,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 e=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let i=Date.now();this.setStatus({state:"indexing",startedAt:i}),this.runReindex(e).then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,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(t){return new Promise((e,i)=>{let r=Date.now(),o=f(this.projectRoot),n=Object.keys(o).length>0?o:this.config,c=m(this.projectRoot,n),a=n.indexer?.typescript,l=n.indexer?.clojure,h=$(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:c.indexPath,SCIP_REINDEX_OUTPUT_DB:c.dbPath,SCIP_REINDEX_LANGUAGES:(n.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(n.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:a?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:a?.projectMode??this.typescriptProjectMode,projects:a?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});h.on("exit",d=>{d===0?e(Date.now()-r):i(new Error(`Reindex worker exited with code ${d}`))}),h.on("error",i)})}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)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let t=this.lastGitState,e=this.readGitState();if(!t||!e||this.stopped){this.lastGitState=e;return}this.lastGitState=e;let i=t.head!==e.head,r=t.indexPath!==e.indexPath||t.indexMtimeMs!==e.indexMtimeMs||t.indexSize!==e.indexSize;i&&r?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):i?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):r&&this.scheduleReindex({kind:"watch-git-index",detail:e.indexPath??"index changed"})}readGitState(){let t=g(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let e=y(this.projectRoot,t),i={head:g(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:e};try{let r=_(e);i.indexMtimeMs=r.mtimeMs,i.indexSize=r.size}catch{i.indexMtimeMs=void 0,i.indexSize=void 0}return i}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function P(s,t){return s?s.kind===t.kind?s.detail===t.detail?s:{kind:s.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${s.kind}, ${t.kind}`}:t}import{existsSync as x,mkdirSync as O,symlinkSync as L,readlinkSync as I,unlinkSync as w,readdirSync as U}from"fs";import{join as p,dirname as R,resolve as u,relative as X,isAbsolute as q}from"path";import{homedir as v,platform as H}from"os";import{fileURLToPath as z}from"url";var J=H()==="win32",C=["_shared","scip-query","scip-setup","scip-calibrate","scip-cleanup-audit","scip-cleanup-improve","scip-integrity-audit","scip-twin-drift","scip-claim-audit","scip-probe-reachability","scip-hyper-optimization","scip-api-impact","scip-concrete-plan","scip-conductor","scip-debug","scip-explore","scip-triage-issue","scip-diagram","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook","scip-tla-model-system"];function K(s={}){let t=s.quiet?()=>{}:console.log,e=z(import.meta.url),i=u(R(e),"..","skills"),r=[p(v(),".claude","skills"),p(v(),".codex","skills"),p(v(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let n of r){let c=R(n);if(!x(c))continue;O(n,{recursive:!0});let a=Y(n);B(n,i,a,o,t);for(let l of C){let h=p(i,l),d=p(n,l);if(!x(h)){o.skipped.push(`${a}/${l}`);continue}if(x(d)){try{let E=I(d);if(u(E)===u(h)){o.alreadyLinked.push(`${a}/${l}`),t(` ok: ${l} \u2192 ${a} (already linked)`);continue}}catch{o.skipped.push(`${a}/${l}`),t(` skip: ${l} \u2192 ${a} (exists, not a symlink)`);continue}w(d)}L(h,d,J?"junction":"dir"),o.installed.push(`${a}/${l}`),t(` done: ${l} \u2192 ${a}`)}}return o}function B(s,t,e,i,r){let o=new Set(C);for(let n of U(s)){if(o.has(n))continue;let c=p(s,n),a;try{a=u(R(c),I(c))}catch{continue}V(a,t)&&(w(c),i.pruned.push(`${e}/${n}`),r(` prune: ${n} \u2192 ${e} (removed stale scip-query skill link)`))}}function V(s,t){let e=X(u(t),u(s));return e===""||!e.startsWith("..")&&!q(e)}function Y(s){return s.includes(".codex")?"Codex":s.includes(".agents")?"Agents":"Claude"}export{S as Watcher,b as getScipVersion,W as initProjectConfig,K as installSkills,j as isScipInstalled,f as loadProjectConfig,D as printScipInstallInstructions,m as resolveIndexStoragePaths};
2
2
  //# sourceMappingURL=runtime.js.map
@@ -1,4 +1,4 @@
1
- import{A as Q,B as yt,Ba as _t,C as St,Ca as de,D as xt,Da as Ot,Ea as Wt,F as oe,Fa as Gt,G as It,H as vt,J as Rt,K as Mt,L as Dt,M as Tt,N as se,O as ae,P as Pt,R as Ct,S as Fe,T as kt,U as Ft,V as wt,Y as Et,a as et,aa as H,b as tt,ba as le,c as De,ca as we,d as nt,da as Lt,ea as Nt,f as rt,fa as B,g as it,h as ot,j as Te,k as Pe,l as st,m as at,o as ct,p as lt,q as dt,qa as jt,r as pt,s as ut,t as ft,ta as Ee,v as mt,w as ht,x as Ce,y as ke,z as gt,za as At}from"./chunk-U267E6YN.js";import{b as K,f as q,j as bt,k as ce}from"./chunk-SMBIGBGN.js";import{a as V,b as j}from"./chunk-3M2UCPFS.js";import{a as ie,c as Ze,d as Me,e as N}from"./chunk-JHK2DMUQ.js";import T from"process";import{rmSync as jn}from"fs";import{resolve as Ii}from"path";import{pathToFileURL as vi}from"url";import{existsSync as $t,readFileSync as On}from"fs";function Le(n,e,t){let r=new Date().toISOString();if(!$t(t.dbPath))return{state:"missing",checkedAt:r,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!$t(t.metaPath))return{state:"unknown",checkedAt:r,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(On(t.metaPath,"utf-8")),o=e.languages??Et(n),a=Wn(n,o,e),s=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(a)&&JSON.stringify(s)===JSON.stringify(a.languages),l=jt(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",p=c&&!d;return{state:p?"fresh":"stale",checkedAt:r,metaPath:t.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:d?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:p?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:r,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function Wn(n,e,t){return bt(n,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{fork as Gn}from"child_process";import{statSync as $n}from"fs";import{isAbsolute as qn,join as Hn,relative as Bn}from"path";import{watch as Un}from"chokidar";import zn from"ignore";var pe=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=le(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=ce(e.projectRoot),this.extraIgnore=zn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let e=Un(this.projectRoot,{ignoreInitial:!0,ignored:(t,r)=>this.isIgnoredWatchPath(t,r?.isDirectory()??!1)});e.on("all",(t,r)=>{this.stopped||this.handleFileChange(r)}),e.on("error",t=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}),this.fsWatchers.push(e)}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=qt(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}isIgnoredWatchPath(e,t){let r=this.relativeWatchPath(e);if(!r)return!1;let i=t?`${r}/`:r;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=qn(e)?e:Hn(this.projectRoot,e);return Bn(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=qt(this.pendingTrigger,e),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 t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=Date.now();this.setStatus({state:"indexing",startedAt:r}),this.runReindex(t).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,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(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,r)=>{let i=Date.now(),o=H(this.projectRoot),a=Object.keys(o).length>0?o:this.config,s=B(this.projectRoot,a),c=a.indexer?.typescript,l=a.indexer?.clojure,d=Gn(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s.indexPath,SCIP_REINDEX_OUTPUT_DB:s.dbPath,SCIP_REINDEX_LANGUAGES:(a.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(a.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?t(Date.now()-i):r(new Error(`Reindex worker exited with code ${p}`))}),d.on("error",r)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let r=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;r&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):r?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=De(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=nt(this.projectRoot,e),r={head:De(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=$n(t);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function qt(n,e){return n?n.kind===e.kind?n.detail===e.detail?n:{kind:n.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${n.kind}, ${e.kind}`}:e}import{existsSync as Ht,statSync as Jn}from"fs";import{join as Vn}from"path";function Kn(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function Qn(n=Kn()){let e=H(n),t=B(n,e),r=process.env.SCIP_QUERY_INDEX_DB;if(r)return{projectRoot:n,config:e,paths:t,dbPath:r,dbPathSource:"env"};if(Ht(t.dbPath))return{projectRoot:n,config:e,paths:t,dbPath:t.dbPath,dbPathSource:"configured"};let i=Vn(n,"index.db");return{projectRoot:n,config:e,paths:t,dbPath:i,dbPathSource:"root-fallback",rootFallbackWarning:Yn(i,t.dbPath)}}function Bt(n,e={}){let{config:t,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:a}=Qn(n);if(!Ht(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&a&&console.error(a);let s={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:n,sharedEvidenceDbPath:Ee(n,t),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,coverageContracts:t.coverageContracts,docs:t.docs},c=ce(n);return new ot(s,c)}function Yn(n,e){let t="unknown time";try{t=Jn(n).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${n}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{mkdirSync as Rn,readFileSync as Mn,readdirSync as ni,rmSync as ri}from"fs";import{resolve as Se}from"path";import{resolve as yn}from"path";import{performance as y}from"perf_hooks";function ue(n){return{forFile(e,t){return Ut(n,e,t)},forFiles(e,t){let r=new Map;for(let i of e)r.set(i,Ut(n,i,t));return r}}}function Ut(n,e,t){let r={file:e},i=t.facts||t.identifiers;if(t.text&&(r.text=lt(n,e)),t.lines&&(r.lines=dt(n,e)),t.ast&&(r.ast=pt(n,e)),t.imports&&(r.imports=St(n,e)),t.reexports&&(r.reexports=yt(n,e)),i){let o=ut(n,e),a=o.facts;t.facts&&(r.facts=a),o.unavailable&&(r.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(r.identifiers=a.fileIdentifiers,r.identifierLineMap=a.identifierLineMap)}return r}var Xn={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function fe(n){if(n.startsWith("local "))return{kind:"local",id:n.slice(6),raw:n};let e=n.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:n};let t=e[0],r=e[1],i=n.slice(t.length+1+r.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let a,s=i.indexOf(" ");s===-1?(a=i,i=""):(a=i.slice(0,s),i=i.slice(s+1));let c=Zn(i);return{scheme:t,manager:r,packageName:o,version:a,descriptors:c,raw:n}}function U(n){let e=fe(n);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let r=e.descriptors[t];if(r?.suffix==="type")return r.name}return null}function Zn(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="["){let o=n.indexOf("]",t+1);if(o===-1){e.push({name:n.slice(t+1),suffix:"type-param"});break}e.push({name:n.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(n[t]==="("&&(e.length===0||t===0||zt(n[t-1]))){let o=n.indexOf(")",t+1);if(o!==-1&&n[o+1]!=="."){e.push({name:n.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let r;if(n[t]==="`"){let o=n.indexOf("`",t+1);if(o===-1){r=n.slice(t+1),e.push({name:r,suffix:"term"});break}r=n.slice(t+1,o),t=o+1}else{let o=t;for(;t<n.length&&!zt(n[t]);)t++;r=n.slice(o,t)}if(t>=n.length){r&&e.push({name:r,suffix:"term"});break}let i=n[t];if(i==="("){let o=n.indexOf(")",t+1);o!==-1&&n[o+1]==="."?(e.push({name:r,suffix:"method"}),t=o+2):o!==-1?(e.push({name:r,suffix:"method"}),t=o+1):(e.push({name:r,suffix:"term"}),t++)}else{let o=Xn[i];o&&e.push({name:r,suffix:o}),t+=1}}return e}function zt(n){return n==="/"||n==="#"||n==="."||n==="("||n==="["||n===":"||n==="!"}function A(n){let e=fe(n);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function _(n){let e=fe(n);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function Jt(n){let e=_(n);return e==="method"?!0:e!=="term"?!1:n.endsWith("().")?!0:n.startsWith("rust-analyzer ")&&n.includes("#")?!1:n.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(n):!0}function er(n,e={}){if(U(n.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(n.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function Vt(n,e,t={}){let r=new Map;for(let o of e)n.length>0&&!er(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||r.set(o.id,o);for(let o of n)r.set(o.id,o);let i=[...r.values()];return t.sort?i.sort((o,a)=>o.start_line-a.start_line||o.end_line-a.end_line||o.symbol.localeCompare(a.symbol)):i}var tr=K("file-definitions",{clearGroups:["definition-catalog"]}),Io=K("file-function-like-definitions",{clearGroups:["definition-catalog"]});function O(n,e,t={}){return t.includeClassMemberFallbacks?Kt(n,e,void 0,{includeClassMemberFallbacks:!0}):tr.get(n,e,()=>{let r=nr(n,e);if(r)return r;let i=Kt(n,e),o=Pe(n),a=ue(n).forFile(e,{text:!0}).text;return o&&a&&Yt.write(n,e,Te(n,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var Yt=at({kind:"file-definitions",invalidation:ct("file-definitions"),serialize:rr,deserialize:ir});function nr(n,e){let t=Pe(n);if(!t)return null;let r=ue(n).forFile(e,{text:!0}).text;if(!r)return null;let i=Yt.read(n,e,Te(n,e,r));return i?or(i,t,e):null}function rr(n){return JSON.stringify(n)}function ir(n){try{let e=JSON.parse(n);return!ke(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function or(n,e,t){if(n.projectFingerprint!==e)return null;let r=[];for(let i of n.definitions){let o=sr(i,t);if(!o)return null;r.push(o)}return r}function sr(n,e){return!ke(n)||typeof n.symbolId!="number"||typeof n.symbol!="string"||typeof n.documentId!="number"||typeof n.startLine!="number"||typeof n.startChar!="number"&&n.startChar!==void 0||typeof n.endLine!="number"||typeof n.endChar!="number"&&n.endChar!==void 0||n.relativePath!==e||typeof n.leaf!="string"||typeof n.parentTypeName!="string"&&n.parentTypeName!==null||typeof n.isFunctionLike!="boolean"||typeof n.isTypeLike!="boolean"||typeof n.kind!="number"&&n.kind!==null||typeof n.documentation!="string"&&n.documentation!==null||typeof n.enclosingSymbol!="string"&&n.enclosingSymbol!==null?null:{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,startChar:n.startChar,endLine:n.endLine,endChar:n.endChar,relativePath:n.relativePath,leaf:n.leaf,parentTypeName:n.parentTypeName,isFunctionLike:n.isFunctionLike,isTypeLike:n.isTypeLike,kind:n.kind,documentation:n.documentation,enclosingSymbol:n.enclosingSymbol}}function Kt(n,e,t,r={}){let i=Vt(ar(n,e),cr(n,e),{sort:!0,includeClassMemberFallbacks:r.includeClassMemberFallbacks}).map(lr);return t&&(i=i.filter(t)),pr(n,e,i)}function ar(n,e){return n.all(`SELECT
1
+ import{A as Q,B as bt,Ba as Gt,C as xt,Ca as pe,D as vt,Da as Wt,Ea as $t,F as se,Fa as qt,G as Rt,H as Mt,J as Dt,K as Tt,L as Pt,M as Ct,N as ae,O as ce,P as kt,R as Ft,S as Ee,T as wt,U as Et,V as Lt,Y as Nt,a as nt,aa as H,b as rt,ba as de,c as Pe,ca as Le,d as it,da as jt,ea as At,f as ot,fa as B,g as st,h as at,j as Ce,k as ke,l as ct,m as lt,o as dt,p as pt,q as ut,qa as _t,r as ft,s as mt,t as ht,ta as Ne,v as gt,w as yt,x as Fe,y as we,z as St,za as Ot}from"./chunk-SALRDXWM.js";import{b as K,f as q,j as It,k as le}from"./chunk-SMBIGBGN.js";import{a as V,b as j}from"./chunk-3M2UCPFS.js";import{a as oe,c as tt,d as Te,e as N}from"./chunk-JHK2DMUQ.js";import C from"process";import{rmSync as _n}from"fs";import{resolve as Ri}from"path";import{pathToFileURL as Mi}from"url";import{existsSync as Ht,readFileSync as Wn}from"fs";function je(n,e,t){let r=new Date().toISOString();if(!Ht(t.dbPath))return{state:"missing",checkedAt:r,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Ht(t.metaPath))return{state:"unknown",checkedAt:r,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(Wn(t.metaPath,"utf-8")),o=e.languages??Nt(n),a=$n(n,o,e),s=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(a)&&JSON.stringify(s)===JSON.stringify(a.languages),l=_t(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",p=c&&!d;return{state:p?"fresh":"stale",checkedAt:r,metaPath:t.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:d?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:p?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:r,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function $n(n,e,t){return It(n,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{fork as qn}from"child_process";import{statSync as Hn}from"fs";import{isAbsolute as Bn,join as Un,relative as zn}from"path";import{watch as Jn}from"chokidar";import Vn from"ignore";var ue=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=de(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=le(e.projectRoot),this.extraIgnore=Vn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let e=Jn(this.projectRoot,{ignoreInitial:!0,ignored:(t,r)=>this.isIgnoredWatchPath(t,r?.isDirectory()??!1)});e.on("all",(t,r)=>{this.stopped||this.handleFileChange(r)}),e.on("error",t=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}),this.fsWatchers.push(e)}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=Bt(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}isIgnoredWatchPath(e,t){let r=this.relativeWatchPath(e);if(!r)return!1;let i=t?`${r}/`:r;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=Bn(e)?e:Un(this.projectRoot,e);return zn(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Bt(this.pendingTrigger,e),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 t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=Date.now();this.setStatus({state:"indexing",startedAt:r}),this.runReindex(t).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,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(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,r)=>{let i=Date.now(),o=H(this.projectRoot),a=Object.keys(o).length>0?o:this.config,s=B(this.projectRoot,a),c=a.indexer?.typescript,l=a.indexer?.clojure,d=qn(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s.indexPath,SCIP_REINDEX_OUTPUT_DB:s.dbPath,SCIP_REINDEX_LANGUAGES:(a.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(a.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?t(Date.now()-i):r(new Error(`Reindex worker exited with code ${p}`))}),d.on("error",r)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let r=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;r&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):r?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=Pe(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=it(this.projectRoot,e),r={head:Pe(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=Hn(t);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Bt(n,e){return n?n.kind===e.kind?n.detail===e.detail?n:{kind:n.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${n.kind}, ${e.kind}`}:e}import{existsSync as Qt,statSync as tr}from"fs";import{join as nr}from"path";import{createHash as Kn}from"crypto";import{readFileSync as Qn}from"fs";import{dirname as Yn,join as fe}from"path";var Y=2,Xn="typescript-semantic";function zt(n){let e=fe(n,Xn);return{rootDir:e,requestDir:fe(e,"requests"),responseDir:fe(e,"responses")}}function X(n){try{let e=JSON.parse(Qn(fe(Yn(n),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:Kn("sha256").update(JSON.stringify({version:e.version,status:e.status,updatedAt:e.updatedAt,fingerprint:e.fingerprint,indexedLanguages:e.indexedLanguages})).digest("hex")}catch{return null}}function Jt(n){let e=JSON.parse(n);if(e.protocolVersion!==Y||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!Zn(e.profileEnvironment)||!e.request||!er(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function Zn(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string"||e===null)}function er(n){if(!n||typeof n!="object"||!("kind"in n))return!1;let e=n;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return St(e.files)!==null;case"references":return Ut(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Ut(e.definitions);case"signature":return Vt(e.definition);default:return!1}}function Ut(n){return Array.isArray(n)&&n.every(Vt)}function Vt(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}function rr(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var Kt;function ir(n=rr(),e=void 0){if(e===void 0&&Kt?.projectRoot===n)return Kt;let t=H(n),r=B(n,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:n,config:t,paths:r,dbPath:i,dbPathSource:"env",gitContext:e};if(Qt(r.dbPath))return{projectRoot:n,config:t,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:e};let o=nr(n,"index.db");return{projectRoot:n,config:t,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:or(o,r.dbPath),gitContext:e}}function Yt(n,e={}){let{config:t,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=ir(n);if(!Qt(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&a&&console.error(a);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:n,sharedEvidenceDbPath:Ne(n,t,s),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,coverageContracts:t.coverageContracts,docs:t.docs},l=le(n);return new at(c,l)}function or(n,e){let t="unknown time";try{t=tr(n).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${n}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{mkdirSync as Dn,readFileSync as Tn,readdirSync as ii,rmSync as oi}from"fs";import{resolve as be}from"path";import{resolve as Mn}from"path";import{performance as y}from"perf_hooks";function me(n){return{forFile(e,t){return Xt(n,e,t)},forFiles(e,t){let r=new Map;for(let i of e)r.set(i,Xt(n,i,t));return r}}}function Xt(n,e,t){let r={file:e},i=t.facts||t.identifiers;if(t.text&&(r.text=pt(n,e)),t.lines&&(r.lines=ut(n,e)),t.ast&&(r.ast=ft(n,e)),t.imports&&(r.imports=xt(n,e)),t.reexports&&(r.reexports=bt(n,e)),i){let o=mt(n,e),a=o.facts;t.facts&&(r.facts=a),o.unavailable&&(r.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(r.identifiers=a.fileIdentifiers,r.identifierLineMap=a.identifierLineMap)}return r}var sr={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function he(n){if(n.startsWith("local "))return{kind:"local",id:n.slice(6),raw:n};let e=n.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:n};let t=e[0],r=e[1],i=n.slice(t.length+1+r.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let a,s=i.indexOf(" ");s===-1?(a=i,i=""):(a=i.slice(0,s),i=i.slice(s+1));let c=ar(i);return{scheme:t,manager:r,packageName:o,version:a,descriptors:c,raw:n}}function U(n){let e=he(n);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let r=e.descriptors[t];if(r?.suffix==="type")return r.name}return null}function ar(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="["){let o=n.indexOf("]",t+1);if(o===-1){e.push({name:n.slice(t+1),suffix:"type-param"});break}e.push({name:n.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(n[t]==="("&&(e.length===0||t===0||Zt(n[t-1]))){let o=n.indexOf(")",t+1);if(o!==-1&&n[o+1]!=="."){e.push({name:n.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let r;if(n[t]==="`"){let o=n.indexOf("`",t+1);if(o===-1){r=n.slice(t+1),e.push({name:r,suffix:"term"});break}r=n.slice(t+1,o),t=o+1}else{let o=t;for(;t<n.length&&!Zt(n[t]);)t++;r=n.slice(o,t)}if(t>=n.length){r&&e.push({name:r,suffix:"term"});break}let i=n[t];if(i==="("){let o=n.indexOf(")",t+1);o!==-1&&n[o+1]==="."?(e.push({name:r,suffix:"method"}),t=o+2):o!==-1?(e.push({name:r,suffix:"method"}),t=o+1):(e.push({name:r,suffix:"term"}),t++)}else{let o=sr[i];o&&e.push({name:r,suffix:o}),t+=1}}return e}function Zt(n){return n==="/"||n==="#"||n==="."||n==="("||n==="["||n===":"||n==="!"}function A(n){let e=he(n);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function _(n){let e=he(n);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function en(n){let e=_(n);return e==="method"?!0:e!=="term"?!1:n.endsWith("().")?!0:n.startsWith("rust-analyzer ")&&n.includes("#")?!1:n.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(n):!0}function cr(n,e={}){if(U(n.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(n.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function tn(n,e,t={}){let r=new Map;for(let o of e)n.length>0&&!cr(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||r.set(o.id,o);for(let o of n)r.set(o.id,o);let i=[...r.values()];return t.sort?i.sort((o,a)=>o.start_line-a.start_line||o.end_line-a.end_line||o.symbol.localeCompare(a.symbol)):i}var lr=K("file-definitions",{clearGroups:["definition-catalog"]}),Co=K("file-function-like-definitions",{clearGroups:["definition-catalog"]});function O(n,e,t={}){return t.includeClassMemberFallbacks?nn(n,e,void 0,{includeClassMemberFallbacks:!0}):lr.get(n,e,()=>{let r=dr(n,e);if(r)return r;let i=nn(n,e),o=ke(n),a=me(n).forFile(e,{text:!0}).text;return o&&a&&on.write(n,e,Ce(n,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var on=lt({kind:"file-definitions",invalidation:dt("file-definitions"),serialize:pr,deserialize:ur});function dr(n,e){let t=ke(n);if(!t)return null;let r=me(n).forFile(e,{text:!0}).text;if(!r)return null;let i=on.read(n,e,Ce(n,e,r));return i?fr(i,t,e):null}function pr(n){return JSON.stringify(n)}function ur(n){try{let e=JSON.parse(n);return!we(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function fr(n,e,t){if(n.projectFingerprint!==e)return null;let r=[];for(let i of n.definitions){let o=mr(i,t);if(!o)return null;r.push(o)}return r}function mr(n,e){return!we(n)||typeof n.symbolId!="number"||typeof n.symbol!="string"||typeof n.documentId!="number"||typeof n.startLine!="number"||typeof n.startChar!="number"&&n.startChar!==void 0||typeof n.endLine!="number"||typeof n.endChar!="number"&&n.endChar!==void 0||n.relativePath!==e||typeof n.leaf!="string"||typeof n.parentTypeName!="string"&&n.parentTypeName!==null||typeof n.isFunctionLike!="boolean"||typeof n.isTypeLike!="boolean"||typeof n.kind!="number"&&n.kind!==null||typeof n.documentation!="string"&&n.documentation!==null||typeof n.enclosingSymbol!="string"&&n.enclosingSymbol!==null?null:{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,startChar:n.startChar,endLine:n.endLine,endChar:n.endChar,relativePath:n.relativePath,leaf:n.leaf,parentTypeName:n.parentTypeName,isFunctionLike:n.isFunctionLike,isTypeLike:n.isTypeLike,kind:n.kind,documentation:n.documentation,enclosingSymbol:n.enclosingSymbol}}function nn(n,e,t,r={}){let i=tn(hr(n,e),gr(n,e),{sort:!0,includeClassMemberFallbacks:r.includeClassMemberFallbacks}).map(yr);return t&&(i=i.filter(t)),br(n,e,i)}function hr(n,e){return n.all(`SELECT
2
2
  gs.id,
3
3
  gs.symbol,
4
4
  der.document_id,
@@ -16,7 +16,7 @@ import{A as Q,B as yt,Ba as _t,C as St,Ca as de,D as xt,Da as Ot,Ea as Wt,F as o
16
16
  JOIN documents d ON der.document_id = d.id
17
17
  WHERE d.relative_path = ?
18
18
  ${n.symbolNoiseFor("gs")}
19
- ORDER BY der.start_line, der.end_line`,e)}function cr(n,e){return n.all(`SELECT
19
+ ORDER BY der.start_line, der.end_line`,e)}function gr(n,e){return n.all(`SELECT
20
20
  gs.id,
21
21
  gs.symbol,
22
22
  c.document_id,
@@ -37,6 +37,6 @@ import{A as Q,B as yt,Ba as _t,C as St,Ca as de,D as xt,Da as Ot,Ea as Wt,F as o
37
37
  AND m.role = 1
38
38
  ${n.symbolNoiseFor("gs")}
39
39
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
40
- ORDER BY start_line, end_line`,e)}function lr(n){return{symbolId:n.id,symbol:n.symbol,documentId:n.document_id,startLine:n.start_line,startChar:n.start_char??0,endLine:n.end_line,endChar:n.end_char??0,relativePath:n.relative_path,leaf:A(n.symbol),parentTypeName:U(n.symbol),isFunctionLike:Jt(n.symbol),isTypeLike:_(n.symbol)==="type",kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosing_symbol??null}}function Xt(n,e={}){return dr(n,e.scope)}function dr(n,e){return q(n,{scope:e,includeIgnored:!1}).flatMap(t=>O(n,t)).filter(t=>!n.isIgnored(t.relativePath))}function pr(n,e,t){let r=ue(n).forFile(e,{text:!0}).text,i=ft(n,e);return i?yr(t,i,r):r?ur(t,r):t}function ur(n,e){let t=e.split(/\r?\n/),r=fr(n,t),i=mr(n,r),o=hr(i,t);return gr(n,o)}function fr(n,e){let t=n.some(i=>me(i.symbol))?Mr(e):null,r=new Map;for(let i of n)r.set(i.symbolId,Rr(e,t,i));return r}function mr(n,e){return n.filter(t=>me(t.symbol)).map(t=>({definition:t,startLine:e.get(t.symbolId)??t.startLine})).sort((t,r)=>t.startLine-r.startLine||t.definition.startLine-r.definition.startLine||t.definition.symbol.localeCompare(r.definition.symbol))}function hr(n,e){let t=new Map;for(let r=0;r<n.length;r+=1){let i=n[r],o=n[r+1],a=o?Math.max(i.startLine,o.startLine-1):e.length-1;t.set(i.definition.symbolId,{startLine:i.startLine,endLine:Dr(e,i.definition,i.startLine,a)})}return t}function gr(n,e){return n.map(t=>{let r=e.get(t.symbolId);return r?{...t,startLine:r.startLine,endLine:r.endLine}:t})}function yr(n,e,t=null){let r=new Map;for(let i of e){let o=r.get(i.name);o?o.push(i):r.set(i.name,[i])}return n.map(i=>{if(!vr(i)||!i.leaf)return Qt(i,t);let o=r.get(i.leaf);if(!o||o.length===0)return Qt(i,t);let a=t?Sr(i,o,t):null;if(a)return{...i,startLine:a.startLine,endLine:a.endLine};let s=o[0],c=Math.abs(s.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let d=o[l],p=Math.abs(d.startLine-i.startLine);p<c&&(s=d,c=p)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function Sr(n,e,t){let r=br(n.symbol);if(!r)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${Q(r)}\\b`);for(let a of e){let s=xr(i,a.startLine);if(s&&o.test(s))return a}return null}function br(n){return n.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function xr(n,e){for(let t=e;t>=0;t-=1){let r=n[t]?.trim()??"";if(r){if(/^impl\b/.test(r))return Ir(n,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(r))return null}}return null}function Ir(n,e,t){let r=[];for(let i=e;i<=t;i+=1){let o=n[i]??"";if(r.push(o),o.includes("{"))break}return r.join(" ")}function vr(n){return me(n.symbol)?!0:_(n.symbol)==="term"&&U(n.symbol)===null}function Qt(n,e){if(!e||!n.leaf||_(n.symbol)!=="term"||U(n.symbol)!==null)return n;let t=Q(n.leaf),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${t}\\b`),o=e.split(/\r?\n/).findIndex(a=>r.test(a));return o>=0?{...n,startLine:o,endLine:o}:n}function Rr(n,e,t){if(!me(t.symbol))return t.startLine;let r=Math.max(0,Math.min(t.startLine,n.length-1));if(!e)return r;let i=e.get(t.leaf);if(!i||i.length===0)return r;let o=null;for(let a of i){let s=Math.abs(a-t.startLine);(!o||s<o.distance)&&(o={line:a,distance:s})}return o?.line??r}function Mr(n){let e=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,t=/\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,o=new Map,a=(s,c)=>{let l=o.get(s);if(!l){o.set(s,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let s=0;s<n.length;s+=1){let c=n[s]??"";for(let d of c.matchAll(e))d[1]&&a(d[1],s);for(let d of c.matchAll(t))d[1]&&a(d[1],s);let l=c.match(r);l?.[1]&&a(l[1],s);for(let d of c.matchAll(i))d[1]&&a(d[1],s)}return o}function Dr(n,e,t,r){let i=Math.max(t,Math.min(n.length-1,r)),o=Math.max(t,Math.min(i,e.endLine)),a=0,s=0,c=!1;for(let l=t;l<=i;l+=1){let d=Tr(n[l]??"");for(let p of d)p==="{"?(a+=1,c=!0):p==="}"?a=Math.max(0,a-1):p==="("?s+=1:p===")"&&(s=Math.max(0,s-1));if(c&&a===0||!c&&s===0&&l>=o)return l}return o}function Tr(n){let e="",t=null,r=!1;for(let i=0;i<n.length;i+=1){let o=n[i],a=n[i+1];if(!t&&o==="/"&&a==="/"){e+=" ".repeat(n.length-i);break}if(t){if(r){r=!1,e+=" ";continue}if(o==="\\"){r=!0,e+=" ";continue}o===t&&(t=null),e+=" ";continue}if(o==='"'||o==="'"||o==="`"){t=o,e+=" ";continue}e+=o}return e}function me(n){return n.includes("().")}function D(n,e,t){if(n.has(e))return n.get(e);let r=t();return n.set(e,r),r}import Zt from"path";function Pr(n,e){return n.getReferences().map(t=>{let r=t.getNode();return he(r,e)})}function Cr(n){let e=n;return typeof e.findReferences=="function"?e.findReferences():[]}function en(n,e,t,r){let i=[];for(let o of Cr(n))for(let a of Pr(o,r))a.file===e.relativePath&&a.line>=e.startLine&&a.line<=e.endLine||i.push(a);for(let o of t)i.push(o);return z(i)}function tn(n,e,t,r){let i=[],o=t?.getStart();for(let a of n.getReferences()){let s=a.getNode();J(r,s.getSourceFile().getFilePath())===e&&(o!==void 0&&s.getStart()===o||i.push({location:he(s,r),node:s}))}return i}function he(n,e){let t=n.getSourceFile(),r=t.getLineAndColumnAtPos(n.getStart());return{file:J(e,t.getFilePath())??t.getBaseName(),line:r.line-1,column:r.column-1}}function nn(n,e,t){let r=n.getSourceFile(),i=je(r,n),o=n.getText(),a=new RegExp(`\\b${Q(o)}\\b`,"g"),s=r.getFullText().split(`
41
- `),c=[];for(let l=0;l<s.length;l++){if(l===i)continue;let d=s[l]??"";a.lastIndex=0;let p;for(;(p=a.exec(d))!==null;)c.push({file:e,line:l,column:p.index})}return z(c.filter(l=>J(t,Zt.join(t,l.file))===e))}function Ne(n){for(let e=n;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function je(n,e){return n.getLineAndColumnAtPos(e.getStart()).line-1}function z(n){let e=new Set,t=[];for(let r of n){let i=`${r.file}:${r.line}:${r.column}`;e.has(i)||(e.add(i),t.push(r))}return t}function J(n,e){let t=Zt.relative(n||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function rn(n,e,t,r){let i=kr(e,r);return i.size===0?new Map:Fr(n,t,i)}function kr(n,e){let t=new Map;for(let r of O(n,e)){let i=A(r.symbol)??r.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(r)}return t}function Fr(n,e,t){let r=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of wr(n,o)){let s=t.get(a);if(!s)continue;let c=je(e,o);for(let l of s){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),p=i.get(l.symbolId);p!==void 0&&p<=d||(i.set(l.symbolId,d),r.set(l.symbolId,o))}}}),r}function wr(n,e){let t=[],r=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();r(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();r(i)}return n.Node.isIdentifier(e)&&r(e.getText()),t}var Er=K("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function on(n,e,t,r){let i=Oe(n,e),o=Ae(i.get(r)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||A(c.symbol)||"").includes(r)||c.symbol.includes(r))&&a.push(c);return Ae(a,t)}function _e(n,e,t,r){return Ae(Oe(n,e).get(r)??[],t)}function sn(n,e){let t=new Map;for(let[r,i]of Oe(n,e)){let o=i[0];o&&t.set(r,o)}return t}function Oe(n,e){return Er.get(n,e,()=>{let t=new Map;for(let r of O(n,e)){let i=r.leaf||A(r.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...r,leaf:i})}for(let r of t.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function Ae(n,e){let t=null,r=Number.POSITIVE_INFINITY;for(let i of n){let o=Math.abs(i.startLine-e);(o<r||o===r&&t&&i.startLine<t.startLine)&&(t=i,r=o)}return t}import We from"path";function an(n,e){let t=new Map,r=null,i=null,o=()=>(i??=q(n,{extensions:se}),i),a=()=>(r??=N("typescript.source-file-index",()=>Lr(n.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),r),s=c=>ae(c)?D(t,c,()=>{let l=Y(We.resolve(n.config.projectRoot,c));for(let{project:d,sourceFiles:p}of a()){let u=p.get(l)??null;if(u||(u=d.addSourceFileAtPathIfExists(l)??null,u&&p.set(Y(u.getFilePath()),u)),u)return{project:d,sourceFile:u}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function Lr(n,e,t){let r=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[Y(o.getFilePath()),o]))}));for(let i of t){let o=Y(We.resolve(n,i));for(let a of r){if(a.sourceFiles.has(o))break;let s=a.project.addSourceFileAtPathIfExists(o)??null;if(s){a.sourceFiles.set(Y(s.getFilePath()),s);break}}}return r}function Y(n){return We.resolve(n)}function Ge(n,e){for(let t of n)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function cn(n){let e=`${n.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as X,readFileSync as Nr}from"fs";import b from"path";var $e=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function qe(n,e){let r=e?b.dirname(b.join(n,e)):n,i=b.resolve(n);for(;r.startsWith(i);){for(let a of $e){let s=b.join(r,a);if(X(s))return s}let o=b.dirname(r);if(o===r)break;r=o}for(let o of $e){let a=b.join(n,o);if(X(a))return a}return null}function ln(n){let e=n.config.projectRoot,t=new Set(jr(e,n.config.semantic?.typescript?.tsconfigs)),r=q(n,{includeIgnored:!1,extensions:se});for(let i of r){let o=qe(e,i);o&&t.add(b.resolve(o))}if(t.size===0){let i=qe(e);i&&t.add(b.resolve(i))}return[...t].filter(i=>!dn(e,i)).sort((i,o)=>i.localeCompare(o))}function jr(n,e=[]){let t=new Set;for(let r of e){let i=b.isAbsolute(r)?r:b.join(n,r);X(i)&&t.add(b.resolve(i))}for(let r of Ar(n))for(let i of $e){let o=b.join(r,i);X(o)&&t.add(b.resolve(o))}if(t.size===0){let r=qe(n);r&&t.add(b.resolve(r))}return[...t].filter(r=>!dn(n,r)).sort((r,i)=>r.localeCompare(i))}function Ar(n){let e=b.join(n,"package.json");if(!X(e))return[];let t;try{t=JSON.parse(Nr(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>ht(n,i))}function dn(n,e){let t=b.relative(n,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var _r=32;function gn(n,e,t,r={}){return N("typescript.provider.construct",()=>new Be(n,e,t),()=>({tsconfigs:t.length,reusedProjects:r.reusedProjects===!0}))}var Be=class{constructor(e,t,r){this.db=e;this.tsMorph=t;this.projects=r;this.workspacePackages=mt(e.config.projectRoot),this.sourceFiles=an(e,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return D(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let r=Wr();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,r),()=>({file:e,...r}))})}referencesFor(e){return D(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let r=new Map,i=ie(),o=[];for(let d of e){let p=this.referencesCache.get(d.symbolId);p?r.set(d.symbolId,p):o.push(d)}if(o.length===0)return r;let a=o,s=t.exact?[]:o.filter(d=>!un(d));if(s.length>=_r){let d=this.referencesForDefinitionsBySymbolScan(s);for(let p of s){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),r.set(p.symbolId,u)}if(a=o.filter(p=>un(p)),a.length===0)return r}let c=new Map;for(let d of a){let p=c.get(d.relativePath);p?p.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,p]of c){let u=fn();N("typescript.references-map.file",()=>{let g=this.definitionNodesForFile(d);for(let f of p){i&&(u.cacheMisses+=1);let m=g.get(f.symbolId)??null;i&&(m?u.nodeHits+=1:u.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,m,i?u:void 0);this.referencesCache.set(f.symbolId,h),r.set(f.symbolId,h)}catch{u.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:p.length,...mn(u)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let p of l){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),r.set(p.symbolId,u)}}return r}referenceFragmentsForFiles(e){let t=Xt(this.db).filter(o=>ae(o.relativePath)),r=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,r);return kt(t,i,r)}referencesForDefinitionsBySymbolScan(e,t){let r=ie(),i=fn(),o=new Map,a=new Set(e.map(c=>c.symbolId)),s=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=r?y.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let h of e){let S=l.get(h.symbolId)??[];if(S.length>0){let R=o.get(h.symbolId)??[];R.push(...S),o.set(h.symbolId,R)}r&&(i.packageReferenceCount+=S.length)}r&&(i.packageRefsMs+=y.now()-c);let d=new Map,p=new Map,u=this.hierarchyTargetsForDefinitions(e),g=new Set(e.map(h=>h.leaf).filter(Boolean)),f=r?y.now():0;for(let h of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let S=this.sourceFiles.sourceFile(h);S&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,h,a,s,u,g,d,p,o,r?i:void 0))}r&&(i.scanMs+=y.now()-f);let m=r?y.now():0;this.addHierarchyMemberReferences(e,o,r?i:void 0),r&&(i.hierarchyMs+=y.now()-m);for(let[h,S]of o){let R=z(S);o.set(h,R),r&&(i.referenceCount+=R.length)}},()=>({definitions:e.length,...mn(i)})),o}addReferencesFromSourceFileScan(e,t,r,i,o,a,s,c,l,d){let p=this.compilerCheckerForSourceFile(e),u=e.compilerNode,g=qr(e),f=m=>{if(this.tsMorph.ts.isIdentifier(m)){if(d&&(d.identifiers+=1),!a.has(m.text)&&!g.has(m.text)){this.tsMorph.ts.forEachChild(m,f);return}let h=this.compilerReferenceSymbol(p,m,d);if(h){let S;s.has(h)?S=s.get(h)??null:(S=this.referenceDefinitionFromCompilerSymbol(h),s.set(h,S)),d&&(S?d.targetHits+=1:d.targetMisses+=1);let R=D(c,h,()=>this.compilerSymbolKeys(h)),E=null,P=null,C=S&&r.has(S.symbolId)?i.get(S.symbolId):void 0;if(C&&(E=He(u,m),!pn(C,t,E))){let M=u.getLineAndCharacterOfPosition(m.getStart(u));P={file:t,line:M.line,column:M.character};let k=l.get(C.symbolId)??[];k.push(P),l.set(C.symbolId,k),d&&(d.requestedHits+=1)}for(let M of R)for(let k of o.get(M)?.values()??[]){if(E??=He(u,m),pn(k,t,E))continue;if(!P){let I=u.getLineAndCharacterOfPosition(m.getStart(u));P={file:t,line:I.line,column:I.character}}let x=l.get(k.symbolId)??[];x.push(P),l.set(k.symbolId,x),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(m,f)};f(u)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let r of e){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let a=o.parent;if(!this.isHierarchyContainer(a))continue;let s=this.compilerCheckerForSourceFile(i.getSourceFile()),c=s.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(s,a,c))for(let d of this.compilerSymbolKeys(l)){let p=t.get(d)??new Map;p.set(r.symbolId,r),t.set(d,p)}}return t}hierarchyMemberSymbols(e,t,r){let i=new Set,o=new Set,a=(s,c,l)=>{if(!o.has(s)){o.add(s),i.add(c);for(let d of l){let p=d.getProperty(r.name);p&&a(d,p,this.hierarchyAncestorTypesForType(e,d))}}};return a(e.getTypeAtLocation(t),r,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,r){let i=new Map;for(let o of e){let a=this.nodeForDefinition(o),s=a?.compilerNode;if(!s||!this.isHierarchyMethod(s))continue;let c=s.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(a.getSourceFile()),d=l.getSymbolAtLocation(s.name);if(!d)continue;let p=s.getSourceFile(),u=p.getLineAndCharacterOfPosition(s.name.getStart(p)),g={definition:o,location:{file:o.relativePath,line:u.line,column:u.character}},f=t.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,d))if(h!==d)for(let S of this.compilerSymbolLocations(h))f.push(S),r&&(r.hierarchyReferences+=1);t.set(o.symbolId,f);let m=this.hierarchyRootMemberSymbols(l,c,d);for(let h of m){let S=i.get(h)??new Map;S.set(o.symbolId,g),i.set(h,S)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:a}of o.values()){let s=t.get(a.symbolId)??[];for(let c of o.values())c.definition.symbolId!==a.symbolId&&(s.push(c.location),r&&(r.hierarchyReferences+=1));t.set(a.symbolId,s)}}}hierarchyRootMemberSymbols(e,t,r){let i=new Set,o=new Set,a=(s,c,l)=>{if(o.has(s))return;o.add(s);let d=!1;for(let p of l){let u=p.getProperty(r.name);u&&(d=!0,a(p,u,this.hierarchyAncestorTypesForType(e,p)))}if(!d)for(let p of this.compilerSymbolKeys(c))i.add(p)};return a(e.getTypeAtLocation(t),r,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let r=t.getSourceFile();return`${r.fileName}\0${t.getStart(r)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let r of e.declarations??[]){let i=r.getSourceFile(),o=J(this.db.config.projectRoot,i.fileName);if(!o)continue;let a=r.name,s=i.getLineAndCharacterOfPosition((a??r).getStart(i));t.push({file:o,line:s.line,column:s.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let r=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)r.add(e.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(e,t){let r=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let a of o.types)r.add(e.getTypeAtLocation(a));return[...r]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,r){r&&(r.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return D(this.calleesCache,e.symbolId,()=>D(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,r=new Map;for(let i of e){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let a=this.fileCalleesCache.get(i),s=new Set(o.map(l=>l.symbolId)),c=a??this.calleeMapForFile(i,s);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,r){let i=r?y.now():0,o=this.packageImportReferencesForDefinition(e);if(r&&(r.packageRefsMs+=y.now()-i,r.packageReferenceCount+=o.length),!t)return o;let a=r?y.now():0,s=en(t,e,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=y.now()-a,r.referenceCount+=s.length),s}signatureFor(e){return D(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let r=t.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(a=>{let s=a.getDeclarations()[0],c=s?a.getTypeAtLocation(s).getText(s):a.getValueDeclaration()?.getType().getText()??"unknown";return hn(c)}),o=r.getReturnType().getText(t);return`(${i.join(",")})=>${hn(o)}`})}importUsageForSourceFile(e,t,r){let i=[],o=new Map;for(let a of t.getImportDeclarations()){r.declarations+=1;let s=Ce(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of Ue(a)){r.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let p={sourcePath:s,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(p),c||!l.localName||!d)continue;let u=o.get(l.localName);u?u.push(p):o.set(l.localName,[p])}}return o.size>0&&t.forEachDescendant(a=>{if(a.getKindName()!=="Identifier")return;let s=o.get(a.getText());if(!s||Gr(a))return;r.scannedIdentifiers+=1;let c=a.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of s)if(l.bindingSymbol===c){l.references.push({location:he(a,this.db.config.projectRoot),node:a}),r.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?Or(e,a.sourcePath,a.entry):a.entry.identifier&&!a.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(e,a.sourcePath,a.entry)):this.valueImportUsageFromLocations(e,a.sourcePath,a.entry,a.references))}valueImportUsageForEntry(e,t,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let a of i)for(let s of tn(a,e,r.identifier,this.db.config.projectRoot))o.push(s);return this.valueImportUsageFromLocations(e,t,r,o)}valueImportUsageFromLocations(e,t,r,i){let o=i.some(c=>!Ne(c.node)),a=i.some(c=>Ne(c.node)),s=r.isTypeOnly;return{importer:e,sourcePath:t,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:s,isUsed:s||i.length>0,isTypeUsed:s||a,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,r=new Set;for(let o of e){let a=this.sourceFiles.sourceFile(o);if(a)for(let s of a.getImportDeclarations()){let c=Ge(this.workspacePackages,s.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return t;let i=this.packageExportsForNames(r);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,a]of t)t.set(o,z(a));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,r);for(let[r,i]of e)e.set(r,z(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,r,o)}addPackageImportReferencesForDeclaration(e,t,r,i){let o=Ge(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of Ue(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=nn(s.identifier,r,this.db.config.projectRoot);l.length>0&&zr(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let r of this.workspacePackages){if(!e.has(r.name))continue;let i=new Map;for(let o of cn(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&t.set(r.name,i)}return t}collectPackageExports(e,t,r,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let a of o.getExportDeclarations()){let s=a.getModuleSpecifierValue(),c=s?Ce(this.db,t,s):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=a.getNamedExports();if(l.length===0){if(a.isNamespaceExport())continue;this.collectPackageExports(e,c,r,i);continue}for(let d of l){let p=d.getNameNode().getText(),u=d.getAliasNode()?.getText()??p,g=this.indexedDefinitionByLeaf(c,p);if(!g)continue;let f=r.get(u);f||(f=new Set,r.set(u,f)),f.add(g.symbolId)}}}indexedDefinitionByLeaf(e,t){return D(this.indexedDefinitionLeafCache,e,()=>sn(this.db,e)).get(t)??null}nodeForDefinition(e){return D(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return D(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?rn(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,r=!1){let i=e.name,o=t?y.now():0,a=e.declarations??[];t&&(t.declarationsMs+=y.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?y.now():0,l=s.getSourceFile(),d=J(this.db.config.projectRoot,l.fileName),p=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=y.now()-c),!d||this.db.isIgnored(d))continue;let u=t?y.now():0,g=this.compilerDeclarationName(s),f=r?_e(this.db,d,p,i)??(g&&g!==i?_e(this.db,d,p,g):null):on(this.db,d,p,i);if(t&&(t.indexedLookupMs+=y.now()-u),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let r=ie(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,p=0,u=r?Br():void 0;return N("typescript.callee-map.file",()=>{let g=r?y.now():0,f=this.sourceFiles.sourceFile(e);if(r&&(c=Math.round(y.now()-g)),!f)return new Map;let m=r?y.now():0,h=O(this.db,e).sort((x,I)=>x.startLine-I.startLine||I.endLine-x.endLine);if(r&&(l=Math.round(y.now()-m)),i=h.length,h.length===0)return new Map;let S=new Map,R=r?y.now():0,E=this.compilerCheckerForSourceFile(f),P=f.compilerNode;r&&(d=Math.round(y.now()-R));let C=new Map,M=x=>{if(this.tsMorph.ts.isCallExpression(x)||this.tsMorph.ts.isNewExpression(x)){r&&(o+=1);let I=this.semanticCalleeForCallNode(E,P,h,x,C,t,u);I&&(r&&(a+=1),$r(S,I.callerId,I.target))}this.tsMorph.ts.forEachChild(x,M)},k=r?y.now():0;M(P),r&&(p=Math.round(y.now()-k));for(let[x,I]of S)S.set(x,Jr(I));return s=S.size,S},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:p,...u?Ur(u):{}}))}semanticCalleeForCallNode(e,t,r,i,o,a,s){let c=s?y.now():0,l=Hr(r,He(t,i));if(s&&(s.callerLookupMs+=y.now()-c),!l)return null;if(a&&!a.has(l.symbolId))return s&&(s.skippedUnrequestedCallers+=1),null;let d=i.expression,p=this.compilerSymbolForExpression(e,d,s),u=null;if(p)if(s&&(s.targetSymbolHits+=1),o.has(p))s&&(s.compilerSymbolCacheHits+=1),u=o.get(p)??null;else{s&&(s.compilerSymbolCacheMisses+=1);let g=s?y.now():0;u=this.definitionFromCompilerSymbol(p,s),s&&(s.targetLookupMs+=y.now()-g),o.set(p,u)}else s&&(s.targetMisses+=1);return u?{callerId:l.symbolId,target:{symbol:u.symbol,file:u.file,line:u.line}}:null}compilerSymbolForExpression(e,t,r){let i=r?y.now():0,o=e.getSymbolAtLocation(t);if(r&&(r.expressionSymbolMs+=y.now()-i),o)return o;r&&(r.typeFallbacks+=1);let a=r?y.now():0,s=e.getTypeAtLocation(t).getSymbol();return r&&(r.typeSymbolMs+=y.now()-a),s}compilerCheckerForSourceFile(e){let t=e.getProject(),r=this.compilerCheckerCache.get(t);return r||(r=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,r)),r}};function Ue(n){let e=[],t=n.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:n.getImportClause()?.isTypeOnly()??!1});let r=n.getNamespaceImport();r&&e.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:n.getImportClause()?.isTypeOnly()??!1});for(let i of n.getNamedImports()){let o=i.getNameNode(),s=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:s,importedName:o.getText(),localName:s?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(n.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function Or(n,e,t){return{importer:n,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function Wr(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function Gr(n){for(let e=n;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function $r(n,e,t){let r=n.get(e);r||(r=[],n.set(e,r)),r.push(t)}function qr(n){let e=new Set;for(let t of n.getImportDeclarations())for(let r of Ue(t))r.localName&&e.add(r.localName);return e}function Hr(n,e){let t=null;for(let r of n)e<r.startLine||e>r.endLine||(!t||r.startLine>=t.startLine)&&(t=r);return t}function He(n,e){return n.getLineAndCharacterOfPosition(e.getStart(n)).line}function pn(n,e,t){return e===n.relativePath&&t>=n.startLine&&t<=n.endLine}function un(n){return n.symbol.includes("#")?_(n.symbol)==="type"&&n.relativePath.endsWith(".d.ts"):!1}function Br(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function Ur(n){return{...n,callerLookupMs:Math.round(n.callerLookupMs),expressionSymbolMs:Math.round(n.expressionSymbolMs),typeSymbolMs:Math.round(n.typeSymbolMs),targetLookupMs:Math.round(n.targetLookupMs),declarationsMs:Math.round(n.declarationsMs),declarationLocationMs:Math.round(n.declarationLocationMs),indexedLookupMs:Math.round(n.indexedLookupMs)}}function fn(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function mn(n){return{...n,scanMs:Math.round(n.scanMs),packageRefsMs:Math.round(n.packageRefsMs),semanticRefsMs:Math.round(n.semanticRefsMs),hierarchyMs:Math.round(n.hierarchyMs)}}function zr(n,e,t){for(let r of e){let i=n.get(r)??[];i.push(...t),n.set(r,i)}}function Jr(n){let e=new Set,t=[];for(let r of n){let i=`${r.symbol}|${r.file}|${r.line}`;e.has(i)||(e.add(i),t.push(r))}return t}function hn(n){return n.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var ge=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??Pt,this.discoverTsconfigs=t.discoverTsconfigs??ln,this.createProjects=t.createProjects??Ct,this.createProvider=t.createProvider??((r,i,o)=>gn(r,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let r=Vr(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?r.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,r):(r.mode==="refresh"&&(Kr(this.projects,e.config.projectRoot,r),this.stats.sessionsRefreshed+=1),r):r}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=Fe("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=Fe("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function Vr(n){let e=new Set;n.projectIdentityChanged&&e.add("project-identity-changed");for(let o of n.uncertainty)e.add(o);for(let o of n.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=ze(n.changes,"added"),r=ze(n.changes,"modified"),i=ze(n.changes,"deleted");return{mode:t.length+r.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:r,deletedFiles:i,reasons:[]}}function ze(n,e){return n.filter(t=>t.kind===e).map(t=>t.path).sort()}function Kr(n,e,t){for(let r of n){for(let i of t.deletedFiles)r.project.getSourceFile(yn(e,i))?.forget();for(let i of t.modifiedFiles){let o=r.project.getSourceFile(yn(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&r.project.addSourceFilesFromTsConfig(r.tsconfigPath)}}import{createHash as Qr}from"crypto";import{readFileSync as Yr}from"fs";import{dirname as Xr,join as ye}from"path";var Z=2,Zr="typescript-semantic";function bn(n){let e=ye(n,Zr);return{rootDir:e,requestDir:ye(e,"requests"),responseDir:ye(e,"responses")}}function xn(n){try{let e=JSON.parse(Yr(ye(Xr(n),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:Qr("sha256").update(JSON.stringify({version:e.version,status:e.status,updatedAt:e.updatedAt,fingerprint:e.fingerprint,indexedLanguages:e.indexedLanguages})).digest("hex")}catch{return null}}function In(n){let e=JSON.parse(n);if(e.protocolVersion!==Z||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!ei(e.profileEnvironment)||!e.request||!ti(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function ei(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string"||e===null)}function ti(n){if(!n||typeof n!="object"||!("kind"in n))return!1;let e=n;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return gt(e.files)!==null;case"references":return Sn(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Sn(e.definitions);case"signature":return vn(e.definition);default:return!1}}function Sn(n){return Array.isArray(n)&&n.every(vn)}function vn(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}var be=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new ge(t)),this.generationIdentity=e.generationIdentity??xn,this.readSnapshot=e.readSnapshot??si,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let r=this.host.semanticProvider();switch(this.available=r.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return r.availability();case"import-usage":return r.importUsage(t.file);case"references":return[...ii(r,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!r.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...r.referenceFragmentsForFiles(t.files)];case"callees":return[...oi(r,t.definitions)];case"signature":return r.signatureFor(t.definition);default:return ci(t)}}catch(r){throw this.lastError=r instanceof Error?r.message:String(r),r}}status(){let e=this.host?.snapshotStats();return{protocolVersion:Z,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:e?.sessionsCreated??0,sessionsReused:e?.sessionsReused??0,sessionsRefreshed:e?.sessionsRefreshed??0,sessionsReplaced:e?.sessionsReplaced??0,projectsCreated:e?.projectsCreated??0}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),r=this.generationIdentity(t.config.dbPath);if(!r||r!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t.config.dbPath);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,ai(this.snapshot,i)),this.db=t,o.close()}this.generation=r,this.snapshot=i,this.available=null}};function Je(n){Rn(n.requestDir,{recursive:!0}),Rn(n.responseDir,{recursive:!0})}function Dn(n,e,t={}){Je(n);let r=0;for(let i of ni(n.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Se(n.requestDir,i),a=i.slice(0,-5),s=null;try{let c=In(Mn(o,"utf8"));if(a=c.id,c.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript semantic request expired before processing.");s=Ze(),Me(c.profileEnvironment??{}),t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.generation,c.request);j(Se(n.responseDir,`${a}.json`),{ok:!0,protocolVersion:Z,id:a,generation:c.generation,response:l})}catch(c){j(Se(n.responseDir,`${a}.json`),{ok:!1,protocolVersion:Z,id:a,error:c instanceof Error?c.message:String(c)})}finally{s&&Me(s),t.afterRequest?.(),ri(o,{force:!0}),r+=1}}return r}function ii(n,e,t){return n.referencesForDefinitions?.(e,t)??new Map(e.map(r=>[r.symbolId,n.referencesFor(r)]))}function oi(n,e){return n.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,n.calleesFor(t)]))}function si(n){try{let e=JSON.parse(Mn(Se(n,"..","meta.json"),"utf8"));return Ft(e.fingerprint)}catch{return null}}function ai(n,e){return e?wt(n,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function ci(n){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(n)}`)}import{mkdirSync as Tn,readFileSync as li,readdirSync as di,rmSync as pi}from"fs";import{resolve as xe}from"path";var Ie=class{projectRoot;currentGeneration;createEmitter;now;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=xe(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??_t,this.now=e.now??Date.now}handle(e,t){let r=this.now();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),s=this.now()-r;return this.requests+=1,this.lastRequestAtMs=this.now(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(){let e=this.active?.emitter.snapshotStats();return{protocolVersion:de,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:e?.initializations??0,programUpdates:e?.programUpdates??0,documentsEmitted:e?.documentsEmitted??0,documentsRemoved:e?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let r=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!r.available)throw this.unavailable=!0,new Error(r.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:r.emitter},this.sessionsCreated+=1,this.active}};function Ve(n){Tn(n.requestDir,{recursive:!0}),Tn(n.responseDir,{recursive:!0})}function Pn(n,e,t={}){Ve(n);let r=0;for(let i of di(n.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=xe(n.requestDir,i),a=i.slice(0,-5);try{let s=Wt(li(o,"utf8"));if(a=s.id,s.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(s.deadlineAtMs);let c=e.handle(s.baseGeneration,s.request);j(xe(n.responseDir,`${a}.json`),{ok:!0,protocolVersion:de,id:a,baseGeneration:s.baseGeneration,response:c})}catch(s){j(xe(n.responseDir,`${a}.json`),{ok:!1,protocolVersion:de,id:a,error:s instanceof Error?s.message:String(s)})}finally{t.afterRequest?.(),pi(o,{force:!0}),r+=1}}return r}import{existsSync as wn,lstatSync as ve,readFileSync as Xe,readdirSync as En,realpathSync as Cn,rmSync as ee,statSync as ui}from"fs";import{join as v,resolve as W,sep as kn}from"path";var fi=3600*1e3,mi=2*1024*1024*1024,hi=300*1e3;function gi(n){let e=n.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=yi(n.leases,n.locks),r={};for(let s of n.generations)t.has(s.generationId)||(r[s.generationId]=s.unreferencedAt??n.nowMs);let i=n.generations.filter(s=>!t.has(s.generationId)).sort((s,c)=>r[s.generationId]-r[c.generationId]||s.generationId.localeCompare(c.generationId)),o=new Set;for(let s of i)n.nowMs-r[s.generationId]>=n.policy.generationTtlMs&&o.add(s.generationId);let a=n.generations.filter(s=>!o.has(s.generationId)).reduce((s,c)=>s+c.size,0);for(let s of i){if(a<=n.policy.budgetBytes)break;o.has(s.generationId)||(o.add(s.generationId),a-=s.size)}for(let s of o)delete r[s];return{deleteWorktrees:e,deleteGenerations:n.generations.filter(s=>o.has(s.generationId)),deleteLocks:n.locks.filter(s=>!s.live),deleteTemporaries:n.temporaries.filter(s=>!s.live),protectedGenerationIds:[...t].sort(),unreferencedSince:r}}function yi(n,e){let t=new Set(n.filter(r=>r.managed&&(r.live||r.busy)).flatMap(r=>[r.lease.baseGenerationId,r.lease.activeGenerationId]).filter(r=>r!==void 0));for(let r of e)r.live&&t.add(r.generationId);return t}function Ln(n,e,t={}){if(!Nt())return{kind:"disabled"};let r=et(n);if(!r)return{kind:"unavailable"};let i=v(we(),"repositories",r.repositoryId);if(!wn(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=v(i,"gc-state.json"),s=xi(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<hi)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=rt(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=Si(n,i,r.repositoryId,s?.unreferencedSince??{}),d=gi({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??fi,budgetBytes:t.policy?.budgetBytes??mi}}),p=0,u=0;for(let m of d.deleteWorktrees){if(!Nn(m.lease))continue;let h=it(v(m.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(Qe(m.lease,!0))continue;try{vt({projectRoot:m.lease.projectRoot,cacheDir:m.lease.localCacheDir,cliVersion:e})}catch{continue}if(Qe(m.lease,!0))continue;ee(m.lease.localCacheDir,{recursive:!0,force:!0}),ee(m.leasePath,{force:!0}),u+=1}finally{h.release()}}for(let m of d.deleteLocks)ee(m.path,{force:!0});for(let m of d.deleteTemporaries)ee(m.path,{recursive:!0,force:!0});for(let m of d.deleteGenerations)ee(m.path,{recursive:!0,force:!0}),p+=m.size;st(v(i,"evidence.db"));let g={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:u,deletedGenerations:d.deleteGenerations.length,deletedBytes:p,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:g.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:g};return j(a,f,{spacing:2,trailingNewline:!0}),g}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function Si(n,e,t,r){let i=new Set(tt(n).map(l=>W(l.path))),o=[];for(let l of Ke(v(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=v(e,"worktrees",l),p=bi(d);if(!p)continue;let u=W(p.projectRoot);o.push({leasePath:d,lease:p,managed:p.repositoryId===t&&Nn(p),live:i.has(u)||wn(u),busy:Qe(p)})}let a=[];for(let l of Ke(v(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let p=v(e,"locks",l),u=Ye(p),g=u!==void 0&&V(u),f=d[1];a.push({generationId:f,path:p,live:g})}let s=[],c=[];for(let l of Ke(v(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let g=v(e,"generations",l),f=Number(d[1]);try{c.push({path:g,size:Fn(g),live:Number.isSafeInteger(f)&&V(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let p=v(e,"generations",l),u;try{u=ve(p)}catch{continue}!u.isDirectory()||u.isSymbolicLink()||s.push({generationId:l,path:p,size:Fn(p),...r[l]===void 0?{}:{unreferencedAt:r[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function Nn(n){if(n.ownershipChecksum!==At(n)||W(n.localCacheDir)!==W(Lt(n.projectRoot)))return!1;let e=W(we()),t=W(v(e,"projects")),r=W(n.localCacheDir);if(!r.startsWith(`${t}${kn}`))return!1;try{let i=ve(e),o=ve(t),a=ve(r);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=Cn(t);return Cn(r).startsWith(`${s}${kn}`)}catch{return!1}}function Qe(n,e=!1){for(let r of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Ye(v(n.localCacheDir,r));if(i!==void 0&&V(i))return!0}let t=Ye(oe(n.localCacheDir).lockPath);return t!==void 0&&V(t)}function bi(n){try{let e=JSON.parse(Xe(n,"utf8"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function Ye(n){try{let e=JSON.parse(Xe(n,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function xi(n){try{let e=JSON.parse(Xe(n,"utf8"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function Ke(n){try{return En(n)}catch{return[]}}function Fn(n){let e=0,t=[n];for(;t.length>0;){let r=t.pop();for(let i of En(r,{withFileTypes:!0})){let o=v(r,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=ui(o).size)}}return e}var Ri=1e3,Mi=250,Di=10;function Ti(n){return n==="fresh"?null:{kind:"watch-startup",detail:`index ${n} when watch service started`}}async function Pi(n,e,t={}){let r=It(n,e),i=r.projectRoot,o=H(i);o.watch={...o.watch,...t};let a=le(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=B(i,o),c=oe(s.cacheDir),l=Dt(c.lockPath,i);if(!l.acquired)return;let d=Date.now(),p=d,u={state:"idle"},g,f,m=!1,h=!1,S=0,R=0,E=0,P=0,C,M,k=bn(s.cacheDir),x=Ot(s.cacheDir);Je(k),Ve(x);let I=new be({openDb:()=>Bt(i)}),Re=new Ie({projectRoot:i,currentGeneration:()=>Gt(s.dbPath)}),w=(L=!1)=>{if(!h)return;let $=Date.now();!L&&$-R<Ri||(R=$,Rt(c.statePath,{version:1,protocolVersion:xt,pid:T.pid,projectRoot:i,...r.worktreeId?{worktreeId:r.worktreeId}:{},cliVersion:e,startedAt:new Date(d).toISOString(),heartbeatAt:new Date($).toISOString(),lastActivityAt:new Date(p).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(p+a.idleTimeoutMs).toISOString()},watcher:u,...g?{lastRefresh:g}:{},...f?{lastError:f}:{},typescriptSemantic:{...I.status(),...C===void 0?{}:{busyUntil:new Date(C).toISOString()}},typescriptIndex:{...Re.status(),...M===void 0?{}:{busyUntil:new Date(M).toISOString()}}}))},G=()=>{p=Date.now()},te=new pe({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(L){u=L,L.state!=="idle"&&G(),w(!0)},onReindexComplete(){G(),g=Le(i,o,s).lastRefresh,f=void 0,w(!0)},onError(L){G(),f={at:new Date().toISOString(),message:L.message},w(!0)}}),ne=()=>{m=!0};T.once("SIGINT",ne),T.once("SIGTERM",ne);try{te.start();let L=Le(i,o,s);g=L.lastRefresh;let $=Ti(L.state);for($&&te.requestRefresh($,{immediate:!0}),G(),h=!0,w(!0);!m;){let An=Pn(x,Re,{beforeRequest(F){M=F+5e3,w(!0)},afterRequest(){M=void 0,w(!0)}}),_n=Dn(k,I,{beforeRequest(F){C=F+5e3,w(!0)},afterRequest(){C=void 0,w(!0)}}),re=Date.now();if(re-P>=6e4&&(P=re,Ln(i,e)),re-E>=Mi){E=re;let F=Mt(c.activityPath);F&&F.atMs>p&&(p=F.atMs),F?.refreshRequestedAtMs!==void 0&&F.refreshRequestedAtMs>S&&(S=F.refreshRequestedAtMs,G(),te.requestRefresh({kind:"watch-demand",detail:F.refreshDetail??"stale index observed by a command"},{immediate:!0}))}if((_n>0||An>0)&&(G(),w(!0)),w(),Tt({watcher:u,lastActivityAtMs:p,nowMs:Date.now(),idleTimeoutMs:a.idleTimeoutMs}))break;await Ci(Di)}}finally{T.off("SIGINT",ne),T.off("SIGTERM",ne),I.closeTypeScriptService(),Re.close(),te.stop(),jn(c.statePath,{force:!0}),jn(c.activityPath,{force:!0}),l.release()}}function Ci(n){return new Promise(e=>setTimeout(e,n))}var ki=T.argv[1]?vi(Ii(T.argv[1])).href:null;if(ki===import.meta.url){let n=T.argv[2],e=T.argv[3],t=Fi(T.argv[4]);if(!n||!e)console.error("watch-service: expected <project-root> <cli-version>"),T.exitCode=1;else try{await Pi(n,e,t)}catch(r){console.error(`watch-service: ${r instanceof Error?r.message:String(r)}`),T.exitCode=1}}function Fi(n){if(!n)return{};try{let e=JSON.parse(n);return e&&typeof e=="object"?e:{}}catch{return{}}}export{Pi as runWatchServiceServer,Ti as startupRefreshTrigger};
40
+ ORDER BY start_line, end_line`,e)}function yr(n){return{symbolId:n.id,symbol:n.symbol,documentId:n.document_id,startLine:n.start_line,startChar:n.start_char??0,endLine:n.end_line,endChar:n.end_char??0,relativePath:n.relative_path,leaf:A(n.symbol),parentTypeName:U(n.symbol),isFunctionLike:en(n.symbol),isTypeLike:_(n.symbol)==="type",kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosing_symbol??null}}function sn(n,e={}){return Sr(n,e.scope)}function Sr(n,e){return q(n,{scope:e,includeIgnored:!1}).flatMap(t=>O(n,t)).filter(t=>!n.isIgnored(t.relativePath))}function br(n,e,t){let r=me(n).forFile(e,{text:!0}).text,i=ht(n,e);return i?Dr(t,i,r):r?xr(t,r):t}function xr(n,e){let t=e.split(/\r?\n/),r=Ir(n,t),i=vr(n,r),o=Rr(i,t);return Mr(n,o)}function Ir(n,e){let t=n.some(i=>ge(i.symbol))?Er(e):null,r=new Map;for(let i of n)r.set(i.symbolId,wr(e,t,i));return r}function vr(n,e){return n.filter(t=>ge(t.symbol)).map(t=>({definition:t,startLine:e.get(t.symbolId)??t.startLine})).sort((t,r)=>t.startLine-r.startLine||t.definition.startLine-r.definition.startLine||t.definition.symbol.localeCompare(r.definition.symbol))}function Rr(n,e){let t=new Map;for(let r=0;r<n.length;r+=1){let i=n[r],o=n[r+1],a=o?Math.max(i.startLine,o.startLine-1):e.length-1;t.set(i.definition.symbolId,{startLine:i.startLine,endLine:Lr(e,i.definition,i.startLine,a)})}return t}function Mr(n,e){return n.map(t=>{let r=e.get(t.symbolId);return r?{...t,startLine:r.startLine,endLine:r.endLine}:t})}function Dr(n,e,t=null){let r=new Map;for(let i of e){let o=r.get(i.name);o?o.push(i):r.set(i.name,[i])}return n.map(i=>{if(!Fr(i)||!i.leaf)return rn(i,t);let o=r.get(i.leaf);if(!o||o.length===0)return rn(i,t);let a=t?Tr(i,o,t):null;if(a)return{...i,startLine:a.startLine,endLine:a.endLine};let s=o[0],c=Math.abs(s.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let d=o[l],p=Math.abs(d.startLine-i.startLine);p<c&&(s=d,c=p)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function Tr(n,e,t){let r=Pr(n.symbol);if(!r)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${Q(r)}\\b`);for(let a of e){let s=Cr(i,a.startLine);if(s&&o.test(s))return a}return null}function Pr(n){return n.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function Cr(n,e){for(let t=e;t>=0;t-=1){let r=n[t]?.trim()??"";if(r){if(/^impl\b/.test(r))return kr(n,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(r))return null}}return null}function kr(n,e,t){let r=[];for(let i=e;i<=t;i+=1){let o=n[i]??"";if(r.push(o),o.includes("{"))break}return r.join(" ")}function Fr(n){return ge(n.symbol)?!0:_(n.symbol)==="term"&&U(n.symbol)===null}function rn(n,e){if(!e||!n.leaf||_(n.symbol)!=="term"||U(n.symbol)!==null)return n;let t=Q(n.leaf),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${t}\\b`),o=e.split(/\r?\n/).findIndex(a=>r.test(a));return o>=0?{...n,startLine:o,endLine:o}:n}function wr(n,e,t){if(!ge(t.symbol))return t.startLine;let r=Math.max(0,Math.min(t.startLine,n.length-1));if(!e)return r;let i=e.get(t.leaf);if(!i||i.length===0)return r;let o=null;for(let a of i){let s=Math.abs(a-t.startLine);(!o||s<o.distance)&&(o={line:a,distance:s})}return o?.line??r}function Er(n){let e=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,t=/\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,o=new Map,a=(s,c)=>{let l=o.get(s);if(!l){o.set(s,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let s=0;s<n.length;s+=1){let c=n[s]??"";for(let d of c.matchAll(e))d[1]&&a(d[1],s);for(let d of c.matchAll(t))d[1]&&a(d[1],s);let l=c.match(r);l?.[1]&&a(l[1],s);for(let d of c.matchAll(i))d[1]&&a(d[1],s)}return o}function Lr(n,e,t,r){let i=Math.max(t,Math.min(n.length-1,r)),o=Math.max(t,Math.min(i,e.endLine)),a=0,s=0,c=!1;for(let l=t;l<=i;l+=1){let d=Nr(n[l]??"");for(let p of d)p==="{"?(a+=1,c=!0):p==="}"?a=Math.max(0,a-1):p==="("?s+=1:p===")"&&(s=Math.max(0,s-1));if(c&&a===0||!c&&s===0&&l>=o)return l}return o}function Nr(n){let e="",t=null,r=!1;for(let i=0;i<n.length;i+=1){let o=n[i],a=n[i+1];if(!t&&o==="/"&&a==="/"){e+=" ".repeat(n.length-i);break}if(t){if(r){r=!1,e+=" ";continue}if(o==="\\"){r=!0,e+=" ";continue}o===t&&(t=null),e+=" ";continue}if(o==='"'||o==="'"||o==="`"){t=o,e+=" ";continue}e+=o}return e}function ge(n){return n.includes("().")}function P(n,e,t){if(n.has(e))return n.get(e);let r=t();return n.set(e,r),r}import an from"path";function jr(n,e){return n.getReferences().map(t=>{let r=t.getNode();return ye(r,e)})}function Ar(n){let e=n;return typeof e.findReferences=="function"?e.findReferences():[]}function cn(n,e,t,r){let i=[];for(let o of Ar(n))for(let a of jr(o,r))a.file===e.relativePath&&a.line>=e.startLine&&a.line<=e.endLine||i.push(a);for(let o of t)i.push(o);return z(i)}function ln(n,e,t,r){let i=[],o=t?.getStart();for(let a of n.getReferences()){let s=a.getNode();J(r,s.getSourceFile().getFilePath())===e&&(o!==void 0&&s.getStart()===o||i.push({location:ye(s,r),node:s}))}return i}function ye(n,e){let t=n.getSourceFile(),r=t.getLineAndColumnAtPos(n.getStart());return{file:J(e,t.getFilePath())??t.getBaseName(),line:r.line-1,column:r.column-1}}function dn(n,e,t){let r=n.getSourceFile(),i=_e(r,n),o=n.getText(),a=new RegExp(`\\b${Q(o)}\\b`,"g"),s=r.getFullText().split(`
41
+ `),c=[];for(let l=0;l<s.length;l++){if(l===i)continue;let d=s[l]??"";a.lastIndex=0;let p;for(;(p=a.exec(d))!==null;)c.push({file:e,line:l,column:p.index})}return z(c.filter(l=>J(t,an.join(t,l.file))===e))}function Ae(n){for(let e=n;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function _e(n,e){return n.getLineAndColumnAtPos(e.getStart()).line-1}function z(n){let e=new Set,t=[];for(let r of n){let i=`${r.file}:${r.line}:${r.column}`;e.has(i)||(e.add(i),t.push(r))}return t}function J(n,e){let t=an.relative(n||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function pn(n,e,t,r){let i=_r(e,r);return i.size===0?new Map:Or(n,t,i)}function _r(n,e){let t=new Map;for(let r of O(n,e)){let i=A(r.symbol)??r.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(r)}return t}function Or(n,e,t){let r=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of Gr(n,o)){let s=t.get(a);if(!s)continue;let c=_e(e,o);for(let l of s){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),p=i.get(l.symbolId);p!==void 0&&p<=d||(i.set(l.symbolId,d),r.set(l.symbolId,o))}}}),r}function Gr(n,e){let t=[],r=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();r(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();r(i)}return n.Node.isIdentifier(e)&&r(e.getText()),t}var Wr=K("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function un(n,e,t,r){let i=We(n,e),o=Oe(i.get(r)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||A(c.symbol)||"").includes(r)||c.symbol.includes(r))&&a.push(c);return Oe(a,t)}function Ge(n,e,t,r){return Oe(We(n,e).get(r)??[],t)}function fn(n,e){let t=new Map;for(let[r,i]of We(n,e)){let o=i[0];o&&t.set(r,o)}return t}function We(n,e){return Wr.get(n,e,()=>{let t=new Map;for(let r of O(n,e)){let i=r.leaf||A(r.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...r,leaf:i})}for(let r of t.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function Oe(n,e){let t=null,r=Number.POSITIVE_INFINITY;for(let i of n){let o=Math.abs(i.startLine-e);(o<r||o===r&&t&&i.startLine<t.startLine)&&(t=i,r=o)}return t}import $e from"path";function mn(n,e){let t=new Map,r=null,i=null,o=()=>(i??=q(n,{extensions:ae}),i),a=()=>(r??=N("typescript.source-file-index",()=>$r(n.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),r),s=c=>ce(c)?P(t,c,()=>{let l=Z($e.resolve(n.config.projectRoot,c));for(let{project:d,sourceFiles:p}of a()){let u=p.get(l)??null;if(u||(u=d.addSourceFileAtPathIfExists(l)??null,u&&p.set(Z(u.getFilePath()),u)),u)return{project:d,sourceFile:u}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function $r(n,e,t){let r=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[Z(o.getFilePath()),o]))}));for(let i of t){let o=Z($e.resolve(n,i));for(let a of r){if(a.sourceFiles.has(o))break;let s=a.project.addSourceFileAtPathIfExists(o)??null;if(s){a.sourceFiles.set(Z(s.getFilePath()),s);break}}}return r}function Z(n){return $e.resolve(n)}function qe(n,e){for(let t of n)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function hn(n){let e=`${n.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as ee,readFileSync as qr}from"fs";import b from"path";var He=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Be(n,e){let r=e?b.dirname(b.join(n,e)):n,i=b.resolve(n);for(;r.startsWith(i);){for(let a of He){let s=b.join(r,a);if(ee(s))return s}let o=b.dirname(r);if(o===r)break;r=o}for(let o of He){let a=b.join(n,o);if(ee(a))return a}return null}function gn(n){let e=n.config.projectRoot,t=new Set(Hr(e,n.config.semantic?.typescript?.tsconfigs)),r=q(n,{includeIgnored:!1,extensions:ae});for(let i of r){let o=Be(e,i);o&&t.add(b.resolve(o))}if(t.size===0){let i=Be(e);i&&t.add(b.resolve(i))}return[...t].filter(i=>!yn(e,i)).sort((i,o)=>i.localeCompare(o))}function Hr(n,e=[]){let t=new Set;for(let r of e){let i=b.isAbsolute(r)?r:b.join(n,r);ee(i)&&t.add(b.resolve(i))}for(let r of Br(n))for(let i of He){let o=b.join(r,i);ee(o)&&t.add(b.resolve(o))}if(t.size===0){let r=Be(n);r&&t.add(b.resolve(r))}return[...t].filter(r=>!yn(n,r)).sort((r,i)=>r.localeCompare(i))}function Br(n){let e=b.join(n,"package.json");if(!ee(e))return[];let t;try{t=JSON.parse(qr(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>yt(n,i))}function yn(n,e){let t=b.relative(n,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var Ur=32;function Rn(n,e,t,r={}){return N("typescript.provider.construct",()=>new ze(n,e,t),()=>({tsconfigs:t.length,reusedProjects:r.reusedProjects===!0}))}var ze=class{constructor(e,t,r){this.db=e;this.tsMorph=t;this.projects=r;this.workspacePackages=gt(e.config.projectRoot),this.sourceFiles=mn(e,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return P(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let r=Jr();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,r),()=>({file:e,...r}))})}referencesFor(e){return P(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let r=new Map,i=oe(),o=[];for(let d of e){let p=this.referencesCache.get(d.symbolId);p?r.set(d.symbolId,p):o.push(d)}if(o.length===0)return r;let a=o,s=t.exact?[]:o.filter(d=>!bn(d));if(s.length>=Ur){let d=this.referencesForDefinitionsBySymbolScan(s);for(let p of s){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),r.set(p.symbolId,u)}if(a=o.filter(p=>bn(p)),a.length===0)return r}let c=new Map;for(let d of a){let p=c.get(d.relativePath);p?p.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,p]of c){let u=xn();N("typescript.references-map.file",()=>{let g=this.definitionNodesForFile(d);for(let f of p){i&&(u.cacheMisses+=1);let m=g.get(f.symbolId)??null;i&&(m?u.nodeHits+=1:u.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,m,i?u:void 0);this.referencesCache.set(f.symbolId,h),r.set(f.symbolId,h)}catch{u.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:p.length,...In(u)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let p of l){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),r.set(p.symbolId,u)}}return r}referenceFragmentsForFiles(e){let t=sn(this.db).filter(o=>ce(o.relativePath)),r=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,r);return wt(t,i,r)}referencesForDefinitionsBySymbolScan(e,t){let r=oe(),i=xn(),o=new Map,a=new Set(e.map(c=>c.symbolId)),s=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=r?y.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let h of e){let S=l.get(h.symbolId)??[];if(S.length>0){let D=o.get(h.symbolId)??[];D.push(...S),o.set(h.symbolId,D)}r&&(i.packageReferenceCount+=S.length)}r&&(i.packageRefsMs+=y.now()-c);let d=new Map,p=new Map,u=this.hierarchyTargetsForDefinitions(e),g=new Set(e.map(h=>h.leaf).filter(Boolean)),f=r?y.now():0;for(let h of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let S=this.sourceFiles.sourceFile(h);S&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,h,a,s,u,g,d,p,o,r?i:void 0))}r&&(i.scanMs+=y.now()-f);let m=r?y.now():0;this.addHierarchyMemberReferences(e,o,r?i:void 0),r&&(i.hierarchyMs+=y.now()-m);for(let[h,S]of o){let D=z(S);o.set(h,D),r&&(i.referenceCount+=D.length)}},()=>({definitions:e.length,...In(i)})),o}addReferencesFromSourceFileScan(e,t,r,i,o,a,s,c,l,d){let p=this.compilerCheckerForSourceFile(e),u=e.compilerNode,g=Qr(e),f=m=>{if(this.tsMorph.ts.isIdentifier(m)){if(d&&(d.identifiers+=1),!a.has(m.text)&&!g.has(m.text)){this.tsMorph.ts.forEachChild(m,f);return}let h=this.compilerReferenceSymbol(p,m,d);if(h){let S;s.has(h)?S=s.get(h)??null:(S=this.referenceDefinitionFromCompilerSymbol(h),s.set(h,S)),d&&(S?d.targetHits+=1:d.targetMisses+=1);let D=P(c,h,()=>this.compilerSymbolKeys(h)),E=null,k=null,L=S&&r.has(S.symbolId)?i.get(S.symbolId):void 0;if(L&&(E=Ue(u,m),!Sn(L,t,E))){let T=u.getLineAndCharacterOfPosition(m.getStart(u));k={file:t,line:T.line,column:T.character};let M=l.get(L.symbolId)??[];M.push(k),l.set(L.symbolId,M),d&&(d.requestedHits+=1)}for(let T of D)for(let M of o.get(T)?.values()??[]){if(E??=Ue(u,m),Sn(M,t,E))continue;if(!k){let I=u.getLineAndCharacterOfPosition(m.getStart(u));k={file:t,line:I.line,column:I.character}}let x=l.get(M.symbolId)??[];x.push(k),l.set(M.symbolId,x),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(m,f)};f(u)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let r of e){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let a=o.parent;if(!this.isHierarchyContainer(a))continue;let s=this.compilerCheckerForSourceFile(i.getSourceFile()),c=s.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(s,a,c))for(let d of this.compilerSymbolKeys(l)){let p=t.get(d)??new Map;p.set(r.symbolId,r),t.set(d,p)}}return t}hierarchyMemberSymbols(e,t,r){let i=new Set,o=new Set,a=(s,c,l)=>{if(!o.has(s)){o.add(s),i.add(c);for(let d of l){let p=d.getProperty(r.name);p&&a(d,p,this.hierarchyAncestorTypesForType(e,d))}}};return a(e.getTypeAtLocation(t),r,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,r){let i=new Map;for(let o of e){let a=this.nodeForDefinition(o),s=a?.compilerNode;if(!s||!this.isHierarchyMethod(s))continue;let c=s.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(a.getSourceFile()),d=l.getSymbolAtLocation(s.name);if(!d)continue;let p=s.getSourceFile(),u=p.getLineAndCharacterOfPosition(s.name.getStart(p)),g={definition:o,location:{file:o.relativePath,line:u.line,column:u.character}},f=t.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,d))if(h!==d)for(let S of this.compilerSymbolLocations(h))f.push(S),r&&(r.hierarchyReferences+=1);t.set(o.symbolId,f);let m=this.hierarchyRootMemberSymbols(l,c,d);for(let h of m){let S=i.get(h)??new Map;S.set(o.symbolId,g),i.set(h,S)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:a}of o.values()){let s=t.get(a.symbolId)??[];for(let c of o.values())c.definition.symbolId!==a.symbolId&&(s.push(c.location),r&&(r.hierarchyReferences+=1));t.set(a.symbolId,s)}}}hierarchyRootMemberSymbols(e,t,r){let i=new Set,o=new Set,a=(s,c,l)=>{if(o.has(s))return;o.add(s);let d=!1;for(let p of l){let u=p.getProperty(r.name);u&&(d=!0,a(p,u,this.hierarchyAncestorTypesForType(e,p)))}if(!d)for(let p of this.compilerSymbolKeys(c))i.add(p)};return a(e.getTypeAtLocation(t),r,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let r=t.getSourceFile();return`${r.fileName}\0${t.getStart(r)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let r of e.declarations??[]){let i=r.getSourceFile(),o=J(this.db.config.projectRoot,i.fileName);if(!o)continue;let a=r.name,s=i.getLineAndCharacterOfPosition((a??r).getStart(i));t.push({file:o,line:s.line,column:s.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let r=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)r.add(e.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(e,t){let r=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let a of o.types)r.add(e.getTypeAtLocation(a));return[...r]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,r){r&&(r.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return P(this.calleesCache,e.symbolId,()=>P(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,r=new Map;for(let i of e){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let a=this.fileCalleesCache.get(i),s=new Set(o.map(l=>l.symbolId)),c=a??this.calleeMapForFile(i,s);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,r){let i=r?y.now():0,o=this.packageImportReferencesForDefinition(e);if(r&&(r.packageRefsMs+=y.now()-i,r.packageReferenceCount+=o.length),!t)return o;let a=r?y.now():0,s=cn(t,e,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=y.now()-a,r.referenceCount+=s.length),s}signatureFor(e){return P(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let r=t.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(a=>{let s=a.getDeclarations()[0],c=s?a.getTypeAtLocation(s).getText(s):a.getValueDeclaration()?.getType().getText()??"unknown";return vn(c)}),o=r.getReturnType().getText(t);return`(${i.join(",")})=>${vn(o)}`})}importUsageForSourceFile(e,t,r){let i=[],o=new Map;for(let a of t.getImportDeclarations()){r.declarations+=1;let s=Fe(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of Je(a)){r.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let p={sourcePath:s,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(p),c||!l.localName||!d)continue;let u=o.get(l.localName);u?u.push(p):o.set(l.localName,[p])}}return o.size>0&&t.forEachDescendant(a=>{if(a.getKindName()!=="Identifier")return;let s=o.get(a.getText());if(!s||Vr(a))return;r.scannedIdentifiers+=1;let c=a.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of s)if(l.bindingSymbol===c){l.references.push({location:ye(a,this.db.config.projectRoot),node:a}),r.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?zr(e,a.sourcePath,a.entry):a.entry.identifier&&!a.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(e,a.sourcePath,a.entry)):this.valueImportUsageFromLocations(e,a.sourcePath,a.entry,a.references))}valueImportUsageForEntry(e,t,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let a of i)for(let s of ln(a,e,r.identifier,this.db.config.projectRoot))o.push(s);return this.valueImportUsageFromLocations(e,t,r,o)}valueImportUsageFromLocations(e,t,r,i){let o=i.some(c=>!Ae(c.node)),a=i.some(c=>Ae(c.node)),s=r.isTypeOnly;return{importer:e,sourcePath:t,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:s,isUsed:s||i.length>0,isTypeUsed:s||a,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,r=new Set;for(let o of e){let a=this.sourceFiles.sourceFile(o);if(a)for(let s of a.getImportDeclarations()){let c=qe(this.workspacePackages,s.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return t;let i=this.packageExportsForNames(r);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,a]of t)t.set(o,z(a));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,r);for(let[r,i]of e)e.set(r,z(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,r,o)}addPackageImportReferencesForDeclaration(e,t,r,i){let o=qe(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of Je(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=dn(s.identifier,r,this.db.config.projectRoot);l.length>0&&ei(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let r of this.workspacePackages){if(!e.has(r.name))continue;let i=new Map;for(let o of hn(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&t.set(r.name,i)}return t}collectPackageExports(e,t,r,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let a of o.getExportDeclarations()){let s=a.getModuleSpecifierValue(),c=s?Fe(this.db,t,s):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=a.getNamedExports();if(l.length===0){if(a.isNamespaceExport())continue;this.collectPackageExports(e,c,r,i);continue}for(let d of l){let p=d.getNameNode().getText(),u=d.getAliasNode()?.getText()??p,g=this.indexedDefinitionByLeaf(c,p);if(!g)continue;let f=r.get(u);f||(f=new Set,r.set(u,f)),f.add(g.symbolId)}}}indexedDefinitionByLeaf(e,t){return P(this.indexedDefinitionLeafCache,e,()=>fn(this.db,e)).get(t)??null}nodeForDefinition(e){return P(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return P(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?pn(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,r=!1){let i=e.name,o=t?y.now():0,a=e.declarations??[];t&&(t.declarationsMs+=y.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?y.now():0,l=s.getSourceFile(),d=J(this.db.config.projectRoot,l.fileName),p=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=y.now()-c),!d||this.db.isIgnored(d))continue;let u=t?y.now():0,g=this.compilerDeclarationName(s),f=r?Ge(this.db,d,p,i)??(g&&g!==i?Ge(this.db,d,p,g):null):un(this.db,d,p,i);if(t&&(t.indexedLookupMs+=y.now()-u),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let r=oe(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,p=0,u=r?Xr():void 0;return N("typescript.callee-map.file",()=>{let g=r?y.now():0,f=this.sourceFiles.sourceFile(e);if(r&&(c=Math.round(y.now()-g)),!f)return new Map;let m=r?y.now():0,h=O(this.db,e).sort((x,I)=>x.startLine-I.startLine||I.endLine-x.endLine);if(r&&(l=Math.round(y.now()-m)),i=h.length,h.length===0)return new Map;let S=new Map,D=r?y.now():0,E=this.compilerCheckerForSourceFile(f),k=f.compilerNode;r&&(d=Math.round(y.now()-D));let L=new Map,T=x=>{if(this.tsMorph.ts.isCallExpression(x)||this.tsMorph.ts.isNewExpression(x)){r&&(o+=1);let I=this.semanticCalleeForCallNode(E,k,h,x,L,t,u);I&&(r&&(a+=1),Kr(S,I.callerId,I.target))}this.tsMorph.ts.forEachChild(x,T)},M=r?y.now():0;T(k),r&&(p=Math.round(y.now()-M));for(let[x,I]of S)S.set(x,ti(I));return s=S.size,S},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:p,...u?Zr(u):{}}))}semanticCalleeForCallNode(e,t,r,i,o,a,s){let c=s?y.now():0,l=Yr(r,Ue(t,i));if(s&&(s.callerLookupMs+=y.now()-c),!l)return null;if(a&&!a.has(l.symbolId))return s&&(s.skippedUnrequestedCallers+=1),null;let d=i.expression,p=this.compilerSymbolForExpression(e,d,s),u=null;if(p)if(s&&(s.targetSymbolHits+=1),o.has(p))s&&(s.compilerSymbolCacheHits+=1),u=o.get(p)??null;else{s&&(s.compilerSymbolCacheMisses+=1);let g=s?y.now():0;u=this.definitionFromCompilerSymbol(p,s),s&&(s.targetLookupMs+=y.now()-g),o.set(p,u)}else s&&(s.targetMisses+=1);return u?{callerId:l.symbolId,target:{symbol:u.symbol,file:u.file,line:u.line}}:null}compilerSymbolForExpression(e,t,r){let i=r?y.now():0,o=e.getSymbolAtLocation(t);if(r&&(r.expressionSymbolMs+=y.now()-i),o)return o;r&&(r.typeFallbacks+=1);let a=r?y.now():0,s=e.getTypeAtLocation(t).getSymbol();return r&&(r.typeSymbolMs+=y.now()-a),s}compilerCheckerForSourceFile(e){let t=e.getProject(),r=this.compilerCheckerCache.get(t);return r||(r=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,r)),r}};function Je(n){let e=[],t=n.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:n.getImportClause()?.isTypeOnly()??!1});let r=n.getNamespaceImport();r&&e.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:n.getImportClause()?.isTypeOnly()??!1});for(let i of n.getNamedImports()){let o=i.getNameNode(),s=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:s,importedName:o.getText(),localName:s?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(n.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function zr(n,e,t){return{importer:n,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function Jr(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function Vr(n){for(let e=n;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function Kr(n,e,t){let r=n.get(e);r||(r=[],n.set(e,r)),r.push(t)}function Qr(n){let e=new Set;for(let t of n.getImportDeclarations())for(let r of Je(t))r.localName&&e.add(r.localName);return e}function Yr(n,e){let t=null;for(let r of n)e<r.startLine||e>r.endLine||(!t||r.startLine>=t.startLine)&&(t=r);return t}function Ue(n,e){return n.getLineAndCharacterOfPosition(e.getStart(n)).line}function Sn(n,e,t){return e===n.relativePath&&t>=n.startLine&&t<=n.endLine}function bn(n){return n.symbol.includes("#")?_(n.symbol)==="type"&&n.relativePath.endsWith(".d.ts"):!1}function Xr(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function Zr(n){return{...n,callerLookupMs:Math.round(n.callerLookupMs),expressionSymbolMs:Math.round(n.expressionSymbolMs),typeSymbolMs:Math.round(n.typeSymbolMs),targetLookupMs:Math.round(n.targetLookupMs),declarationsMs:Math.round(n.declarationsMs),declarationLocationMs:Math.round(n.declarationLocationMs),indexedLookupMs:Math.round(n.indexedLookupMs)}}function xn(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function In(n){return{...n,scanMs:Math.round(n.scanMs),packageRefsMs:Math.round(n.packageRefsMs),semanticRefsMs:Math.round(n.semanticRefsMs),hierarchyMs:Math.round(n.hierarchyMs)}}function ei(n,e,t){for(let r of e){let i=n.get(r)??[];i.push(...t),n.set(r,i)}}function ti(n){let e=new Set,t=[];for(let r of n){let i=`${r.symbol}|${r.file}|${r.line}`;e.has(i)||(e.add(i),t.push(r))}return t}function vn(n){return n.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Se=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??kt,this.discoverTsconfigs=t.discoverTsconfigs??gn,this.createProjects=t.createProjects??Ft,this.createProvider=t.createProvider??((r,i,o)=>Rn(r,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let r=ni(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?r.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,r):(r.mode==="refresh"&&(ri(this.projects,e.config.projectRoot,r),this.stats.sessionsRefreshed+=1),r):r}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=Ee("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=Ee("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function ni(n){let e=new Set;n.projectIdentityChanged&&e.add("project-identity-changed");for(let o of n.uncertainty)e.add(o);for(let o of n.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=Ve(n.changes,"added"),r=Ve(n.changes,"modified"),i=Ve(n.changes,"deleted");return{mode:t.length+r.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:r,deletedFiles:i,reasons:[]}}function Ve(n,e){return n.filter(t=>t.kind===e).map(t=>t.path).sort()}function ri(n,e,t){for(let r of n){for(let i of t.deletedFiles)r.project.getSourceFile(Mn(e,i))?.forget();for(let i of t.modifiedFiles){let o=r.project.getSourceFile(Mn(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&r.project.addSourceFilesFromTsConfig(r.tsconfigPath)}}var xe=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new Se(t)),this.generationIdentity=e.generationIdentity??X,this.readSnapshot=e.readSnapshot??ci,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let r=this.host.semanticProvider();switch(this.available=r.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return r.availability();case"import-usage":return r.importUsage(t.file);case"references":return[...si(r,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!r.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...r.referenceFragmentsForFiles(t.files)];case"callees":return[...ai(r,t.definitions)];case"signature":return r.signatureFor(t.definition);default:return di(t)}}catch(r){throw this.lastError=r instanceof Error?r.message:String(r),r}}status(){let e=this.host?.snapshotStats();return{protocolVersion:Y,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:e?.sessionsCreated??0,sessionsReused:e?.sessionsReused??0,sessionsRefreshed:e?.sessionsRefreshed??0,sessionsReplaced:e?.sessionsReplaced??0,projectsCreated:e?.projectsCreated??0}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),r=this.generationIdentity(t.config.dbPath);if(!r||r!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t.config.dbPath);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,li(this.snapshot,i)),this.db=t,o.close()}this.generation=r,this.snapshot=i,this.available=null}};function Ke(n){Dn(n.requestDir,{recursive:!0}),Dn(n.responseDir,{recursive:!0})}function Pn(n,e,t={}){Ke(n);let r=0;for(let i of ii(n.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=be(n.requestDir,i),a=i.slice(0,-5),s=null;try{let c=Jt(Tn(o,"utf8"));if(a=c.id,c.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript semantic request expired before processing.");s=tt(),Te(c.profileEnvironment??{}),t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.generation,c.request);j(be(n.responseDir,`${a}.json`),{ok:!0,protocolVersion:Y,id:a,generation:c.generation,response:l})}catch(c){j(be(n.responseDir,`${a}.json`),{ok:!1,protocolVersion:Y,id:a,error:c instanceof Error?c.message:String(c)})}finally{s&&Te(s),t.afterRequest?.(),oi(o,{force:!0}),r+=1}}return r}function si(n,e,t){return n.referencesForDefinitions?.(e,t)??new Map(e.map(r=>[r.symbolId,n.referencesFor(r)]))}function ai(n,e){return n.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,n.calleesFor(t)]))}function ci(n){try{let e=JSON.parse(Tn(be(n,"..","meta.json"),"utf8"));return Et(e.fingerprint)}catch{return null}}function li(n,e){return e?Lt(n,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function di(n){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(n)}`)}import{mkdirSync as Cn,readFileSync as pi,readdirSync as ui,rmSync as fi}from"fs";import{resolve as Ie}from"path";var ve=class{projectRoot;currentGeneration;createEmitter;now;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=Ie(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Gt,this.now=e.now??Date.now}handle(e,t){let r=this.now();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),s=this.now()-r;return this.requests+=1,this.lastRequestAtMs=this.now(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(){let e=this.active?.emitter.snapshotStats();return{protocolVersion:pe,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:e?.initializations??0,programUpdates:e?.programUpdates??0,documentsEmitted:e?.documentsEmitted??0,documentsRemoved:e?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let r=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!r.available)throw this.unavailable=!0,new Error(r.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:r.emitter},this.sessionsCreated+=1,this.active}};function Qe(n){Cn(n.requestDir,{recursive:!0}),Cn(n.responseDir,{recursive:!0})}function kn(n,e,t={}){Qe(n);let r=0;for(let i of ui(n.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Ie(n.requestDir,i),a=i.slice(0,-5);try{let s=$t(pi(o,"utf8"));if(a=s.id,s.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(s.deadlineAtMs);let c=e.handle(s.baseGeneration,s.request);j(Ie(n.responseDir,`${a}.json`),{ok:!0,protocolVersion:pe,id:a,baseGeneration:s.baseGeneration,response:c})}catch(s){j(Ie(n.responseDir,`${a}.json`),{ok:!1,protocolVersion:pe,id:a,error:s instanceof Error?s.message:String(s)})}finally{t.afterRequest?.(),fi(o,{force:!0}),r+=1}}return r}import{existsSync as Ln,lstatSync as Re,readFileSync as et,readdirSync as Nn,realpathSync as Fn,rmSync as te,statSync as mi}from"fs";import{join as R,resolve as G,sep as wn}from"path";var hi=3600*1e3,gi=2*1024*1024*1024,yi=300*1e3;function Si(n){let e=n.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=bi(n.leases,n.locks),r={};for(let s of n.generations)t.has(s.generationId)||(r[s.generationId]=s.unreferencedAt??n.nowMs);let i=n.generations.filter(s=>!t.has(s.generationId)).sort((s,c)=>r[s.generationId]-r[c.generationId]||s.generationId.localeCompare(c.generationId)),o=new Set;for(let s of i)n.nowMs-r[s.generationId]>=n.policy.generationTtlMs&&o.add(s.generationId);let a=n.generations.filter(s=>!o.has(s.generationId)).reduce((s,c)=>s+c.size,0);for(let s of i){if(a<=n.policy.budgetBytes)break;o.has(s.generationId)||(o.add(s.generationId),a-=s.size)}for(let s of o)delete r[s];return{deleteWorktrees:e,deleteGenerations:n.generations.filter(s=>o.has(s.generationId)),deleteLocks:n.locks.filter(s=>!s.live),deleteTemporaries:n.temporaries.filter(s=>!s.live),protectedGenerationIds:[...t].sort(),unreferencedSince:r}}function bi(n,e){let t=new Set(n.filter(r=>r.managed&&(r.live||r.busy)).flatMap(r=>[r.lease.baseGenerationId,r.lease.activeGenerationId]).filter(r=>r!==void 0));for(let r of e)r.live&&t.add(r.generationId);return t}function jn(n,e,t={}){if(!At())return{kind:"disabled"};let r=nt(n);if(!r)return{kind:"unavailable"};let i=R(Le(),"repositories",r.repositoryId);if(!Ln(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=R(i,"gc-state.json"),s=vi(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<yi)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=ot(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=xi(n,i,r.repositoryId,s?.unreferencedSince??{}),d=Si({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??hi,budgetBytes:t.policy?.budgetBytes??gi}}),p=0,u=0;for(let m of d.deleteWorktrees){if(!An(m.lease))continue;let h=st(R(m.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(Xe(m.lease,!0))continue;try{Mt({projectRoot:m.lease.projectRoot,cacheDir:m.lease.localCacheDir,cliVersion:e})}catch{continue}if(Xe(m.lease,!0))continue;te(m.lease.localCacheDir,{recursive:!0,force:!0}),te(m.leasePath,{force:!0}),u+=1}finally{h.release()}}for(let m of d.deleteLocks)te(m.path,{force:!0});for(let m of d.deleteTemporaries)te(m.path,{recursive:!0,force:!0});for(let m of d.deleteGenerations)te(m.path,{recursive:!0,force:!0}),p+=m.size;ct(R(i,"evidence.db"));let g={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:u,deletedGenerations:d.deleteGenerations.length,deletedBytes:p,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:g.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:g};return j(a,f,{spacing:2,trailingNewline:!0}),g}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function xi(n,e,t,r){let i=new Set(rt(n).map(l=>G(l.path))),o=[];for(let l of Ye(R(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=R(e,"worktrees",l),p=Ii(d);if(!p)continue;let u=G(p.projectRoot);o.push({leasePath:d,lease:p,managed:p.repositoryId===t&&An(p),live:i.has(u)||Ln(u),busy:Xe(p)})}let a=[];for(let l of Ye(R(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let p=R(e,"locks",l),u=Ze(p),g=u!==void 0&&V(u),f=d[1];a.push({generationId:f,path:p,live:g})}let s=[],c=[];for(let l of Ye(R(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let g=R(e,"generations",l),f=Number(d[1]);try{c.push({path:g,size:En(g),live:Number.isSafeInteger(f)&&V(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let p=R(e,"generations",l),u;try{u=Re(p)}catch{continue}!u.isDirectory()||u.isSymbolicLink()||s.push({generationId:l,path:p,size:En(p),...r[l]===void 0?{}:{unreferencedAt:r[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function An(n){if(n.ownershipChecksum!==Ot(n)||G(n.localCacheDir)!==G(jt(n.projectRoot)))return!1;let e=G(Le()),t=G(R(e,"projects")),r=G(n.localCacheDir);if(!r.startsWith(`${t}${wn}`))return!1;try{let i=Re(e),o=Re(t),a=Re(r);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=Fn(t);return Fn(r).startsWith(`${s}${wn}`)}catch{return!1}}function Xe(n,e=!1){for(let r of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Ze(R(n.localCacheDir,r));if(i!==void 0&&V(i))return!0}let t=Ze(se(n.localCacheDir).lockPath);return t!==void 0&&V(t)}function Ii(n){try{let e=JSON.parse(et(n,"utf8"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function Ze(n){try{let e=JSON.parse(et(n,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function vi(n){try{let e=JSON.parse(et(n,"utf8"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function Ye(n){try{return Nn(n)}catch{return[]}}function En(n){let e=0,t=[n];for(;t.length>0;){let r=t.pop();for(let i of Nn(r,{withFileTypes:!0})){let o=R(r,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=mi(o).size)}}return e}var Di=1e3,Ti=250,Pi=10;function Ci(n){return n==="fresh"?null:{kind:"watch-startup",detail:`index ${n} when watch service started`}}async function ki(n,e,t={}){let r=Rt(n,e),i=r.projectRoot,o=H(i);o.watch={...o.watch,...t};let a=de(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=B(i,o),c=se(s.cacheDir),l=Pt(c.lockPath,i);if(!l.acquired)return;let d=Date.now(),p=d,u={state:"idle"},g,f,m,h=!1,S=!1,D=0,E=0,k=0,L=0,T,M,x=zt(s.cacheDir),I=Wt(s.cacheDir);Ke(x),Qe(I);let Me=new xe({openDb:()=>Yt(i)}),De=new ve({projectRoot:i,currentGeneration:()=>qt(s.dbPath)}),w=(v=!1)=>{if(!S)return;let $=Date.now();!v&&$-E<Di||(E=$,Dt(c.statePath,{version:1,protocolVersion:vt,pid:C.pid,projectRoot:i,...r.worktreeId?{worktreeId:r.worktreeId}:{},cliVersion:e,startedAt:new Date(d).toISOString(),heartbeatAt:new Date($).toISOString(),lastActivityAt:new Date(p).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(p+a.idleTimeoutMs).toISOString()},watcher:u,...u.state==="idle"&&g?{indexGeneration:g}:{},...f?{lastRefresh:f}:{},...m?{lastError:m}:{},typescriptSemantic:{...Me.status(),...T===void 0?{}:{busyUntil:new Date(T).toISOString()}},typescriptIndex:{...De.status(),...M===void 0?{}:{busyUntil:new Date(M).toISOString()}}}))},W=()=>{p=Date.now()},ne=new ue({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(v){u=v,v.state!=="idle"&&(g=void 0),v.state!=="idle"&&W(),w(!0)},onReindexComplete(){W();let v=je(i,o,s);f=v.lastRefresh,g=v.state==="fresh"?X(s.dbPath)??void 0:void 0,m=void 0,w(!0)},onError(v){W(),g=void 0,m={at:new Date().toISOString(),message:v.message},w(!0)}}),re=()=>{h=!0};C.once("SIGINT",re),C.once("SIGTERM",re);try{ne.start();let v=je(i,o,s);f=v.lastRefresh,g=v.state==="fresh"?X(s.dbPath)??void 0:void 0;let $=Ci(v.state);for($&&ne.requestRefresh($,{immediate:!0}),W(),S=!0,w(!0);!h;){let On=kn(I,De,{beforeRequest(F){M=F+5e3,w(!0)},afterRequest(){M=void 0,w(!0)}}),Gn=Pn(x,Me,{beforeRequest(F){T=F+5e3,w(!0)},afterRequest(){T=void 0,w(!0)}}),ie=Date.now();if(ie-L>=6e4&&(L=ie,jn(i,e)),ie-k>=Ti){k=ie;let F=Tt(c.activityPath);F&&F.atMs>p&&(p=F.atMs),F?.refreshRequestedAtMs!==void 0&&F.refreshRequestedAtMs>D&&(D=F.refreshRequestedAtMs,W(),ne.requestRefresh({kind:"watch-demand",detail:F.refreshDetail??"stale index observed by a command"},{immediate:!0}))}if((Gn>0||On>0)&&(W(),w(!0)),w(),Ct({watcher:u,lastActivityAtMs:p,nowMs:Date.now(),idleTimeoutMs:a.idleTimeoutMs}))break;await Fi(Pi)}}finally{C.off("SIGINT",re),C.off("SIGTERM",re),Me.closeTypeScriptService(),De.close(),ne.stop(),_n(c.statePath,{force:!0}),_n(c.activityPath,{force:!0}),l.release()}}function Fi(n){return new Promise(e=>setTimeout(e,n))}var wi=C.argv[1]?Mi(Ri(C.argv[1])).href:null;if(wi===import.meta.url){let n=C.argv[2],e=C.argv[3],t=Ei(C.argv[4]);if(!n||!e)console.error("watch-service: expected <project-root> <cli-version>"),C.exitCode=1;else try{await ki(n,e,t)}catch(r){console.error(`watch-service: ${r instanceof Error?r.message:String(r)}`),C.exitCode=1}}function Ei(n){if(!n)return{};try{let e=JSON.parse(n);return e&&typeof e=="object"?e:{}}catch{return{}}}export{ki as runWatchServiceServer,Ci as startupRefreshTrigger};
42
42
  //# sourceMappingURL=watch-server.js.map
@@ -180,6 +180,9 @@ even though its per-pair classification loop in `queries.coChange`
180
180
  candidate-pair count on a large repository. It now flows through `budgetedDbCommand` and
181
181
  `coChange` accepts a `scanLimit` option that truncates the (already priority-sorted) candidate
182
182
  pairs before classification, so the disclosed budget is truthful rather than cosmetic.
183
+ Composite planning also passes its already-resolved invocation HEAD through `coChange`'s
184
+ internal options, keeping history reads on one Git snapshot without another `rev-parse`
185
+ subprocess; standalone command behavior is unchanged.
183
186
  The setup-scope follow-up rechecked this implementation citation; extracting
184
187
  shared hook outcome recording changed imports in the same runtime module but
185
188
  did not change the `co-change` budget boundary described here.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scip-query",
3
- "version": "0.17.1",
3
+ "version": "0.17.2",
4
4
  "description": "Evidence and verification for AI coding agents: map code, reuse concepts, finish migrations, and gate diffs.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1,3 +0,0 @@
1
- import{A as C,c as M,d as L,e as Q,g as I,h as E,i as K,n as y,o as d,r as b}from"./chunk-7XP7ZRSI.js";function se(e,n){return O(e,n).match}function O(e,n){let t=z(e,n.trim()).filter(r=>!e.isIgnored(r.relative_path));if(t.length>0)return S(e,t);let o=G(e,n);if(o&&!e.isIgnored(o.relative_path))return S(e,[o]);let i=W(e,n);return i.length>0?S(e,i):X(e,n)}function W(e,n){let t=N(n),o=x(t);if(!o)return[];let i=`%${o.path}%`,r=o.leaf;return j(e,i,r,t)}function j(e,n,t,o){let i=b([],[...q(e,n,t),...T(e,n,t)]).filter(r=>!e.isIgnored(r.relative_path)).filter(r=>f(r,o)>1);return i.sort((r,a)=>f(a,o)-f(r,o)||r.end_line-r.start_line-(a.end_line-a.start_line)||r.start_line-a.start_line||r.symbol.localeCompare(a.symbol)),i}function q(e,n,t){return y(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[n,t,`%/${t}.%`]})}function T(e,n,t){return d(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[n,t,`%/${t}.%`]})}function X(e,n){let t=N(n),o=P(n),i=V(e,o),r=ee(i,n,t).filter(s=>!e.isIgnored(s.relative_path));if(r.length>0)return S(e,r);let a=[];for(let s of i){if(e.isIgnored(s.relative_path))continue;let c=Y(s,n,t,o);c<=0||a.push({row:s,score:c})}return a.sort((s,c)=>c.score-s.score||s.row.end_line-s.row.start_line-(c.row.end_line-c.row.start_line)||s.row.relative_path.localeCompare(c.row.relative_path)||s.row.symbol.localeCompare(c.row.symbol)),S(e,a.map(s=>s.row))}function S(e,n){let t=n.map(i=>C(e,i)),o=t[0]??null;return{match:o,candidates:o?Z(t,o):[],total:t.length}}function Z(e,n){let t=new Set([`${n.symbolId}:${n.relativePath}:${n.startLine}`]),o=[];for(let i of e){let r=`${i.symbolId}:${i.relativePath}:${i.startLine}`;if(!t.has(r)&&(t.add(r),o.push({symbol:i.symbol,shortName:L(i.symbol),relativePath:i.relativePath,startLine:i.startLine}),o.length>=5))break}return o}function G(e,n){let t=n.match(/^(.+):(\d+)-(\d+)$/);if(!t)return;let[,o,i,r]=t,a=Math.max(0,parseInt(i,10)-1),s=Math.max(a,parseInt(r,10)-1);return H(e,o,a,s)??J(e,o,a,s)}function H(e,n,t,o){return y(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${n}%`,t,o],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function J(e,n,t,o){return d(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${n}%`,t,o],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function le(e,n){let t=z(e,n).find(o=>!e.isIgnored(o.relative_path));return t?C(e,t):null}function z(e,n){let t=y(e,{where:"gs.symbol = ?",params:[n],orderBy:"d.relative_path, der.start_line"}),o=t.length>0?[]:d(e,{where:"gs.symbol = ?",params:[n],orderBy:"d.relative_path, start_line"});return b(t,o)}function ce(e,n){if("symbol"in n&&"relativePath"in n)return n;let t=U(e,n.symbolId)[0];return t?C(e,t):null}function U(e,n){let t=y(e,{where:"gs.id = ?",params:[n],orderBy:"der.start_line, der.end_line"}),o=d(e,{where:"gs.id = ?",params:[n],orderBy:"start_line, end_line"});return b(t,o)}function V(e,n){let t=n.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),o=n.flatMap(s=>{let c=`%${s}%`;return[c,c,c]}),i=t.join(`
2
- AND `),r=y(e,{where:i,params:o,limit:200}),a=d(e,{where:i,params:o,limit:200});return b(r,a)}function Y(e,n,t,o){let i=n.trim(),r=t,a=r.replace(/\(\)$/,""),s=n.toLowerCase(),c=t.toLowerCase(),h=c.replace(/\(\)$/,""),k=e.symbol,v=L(e.symbol),g=Q(e.symbol),A=e.display_name??"",w=e.symbol.toLowerCase(),m=v.toLowerCase(),u=g.toLowerCase(),D=A.toLowerCase(),p=e.relative_path.toLowerCase(),F=/[/:.]/.test(t),$=x(t),_=$?.leaf.toLowerCase(),l=0;return(k===i||k===r)&&(l+=1150),(v===i||v===r)&&(l+=1100),A===a&&(l+=1180),g===a&&(l+=1160),(`${g}()`===i||`${g}()`===r)&&(l+=955),(w===s||w===c)&&(l+=1e3),(m===s||m===c)&&(l+=950),(p===s||p===c)&&(l+=925),(p.endsWith(`/${c}`)||p.endsWith(`/${s}`))&&(l+=875),D===h&&(l+=850),u===h&&(l+=825),(`${u}()`===s||`${u}()`===c)&&(l+=820),(m.endsWith(`:${c}`)||m.endsWith(`:${h}`)||m.endsWith(`:${h}()`))&&(l+=800),w.includes(c)&&(l+=120),m.includes(c)&&(l+=140),p.includes(c)&&(l+=140),D.includes(c)&&(l+=110),o.every(B=>{let R=B.toLowerCase();return w.includes(R)||m.includes(R)||p.includes(R)||D.includes(R)})&&(l+=100+o.length*15),$&&p.includes($.path.toLowerCase())&&(l+=360,_&&(u===_||`${u}()`===_||`${u}()`==`${_}()`)&&(l+=700),I(e.symbol)&&(l+=180)),E(e.symbol)&&u===h&&(l+=60),!F&&K(e.symbol)&&(l-=160),l-=Math.min(50,Math.max(0,e.end_line-e.start_line)),l}function x(e){let n=e.trim().replace(/\\/g,"/"),t=n.lastIndexOf("/");if(t<=0||t===n.length-1)return null;let o=n.slice(t+1).replace(/\(\)$/,"");return!o||o.includes(".")?null:{path:n.slice(0,t),leaf:o}}function N(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function P(e){let n=N(e),t=n.split(/[^A-Za-z0-9_]+/).map(o=>o.trim()).filter(o=>o.length>0);return t.length>0?[...new Set(t)]:[n]}function ee(e,n,t){let o=n.trim(),i=e.filter(r=>{let a=L(r.symbol),s=(r.display_name??"").trim();return r.symbol===o||a===o||a===t||s===o||s===t||`${s}()`===o||f(r,t)>1||r.relative_path===o});return i.length===0?[]:(i.sort((r,a)=>f(a,t)-f(r,t)||r.end_line-r.start_line-(a.end_line-a.start_line)||r.relative_path.localeCompare(a.relative_path)||r.symbol.localeCompare(a.symbol)),i)}function f(e,n){let t=x(n);if(!t)return 0;let o=e.relative_path.toLowerCase(),i=Q(e.symbol).toLowerCase(),r=t.path.toLowerCase(),a=t.leaf.toLowerCase();return o.includes(r)?i!==a?1:I(e.symbol)?M(e.symbol)===null?5:4:M(e.symbol)===null?3:2:0}export{se as a,O as b,le as c,ce as d};
3
- //# sourceMappingURL=chunk-2HCWAL42.js.map