scip-query 0.19.0 → 0.19.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +17 -1
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-YHYTDWFT.js → chunk-24ET4VLC.js} +2 -2
- package/dist/{chunk-GBB2RUDN.js → chunk-26JI77AY.js} +130 -130
- package/dist/{chunk-MFBXBLHA.js → chunk-2E7QY4B5.js} +2 -2
- package/dist/{chunk-PXJIEMND.js → chunk-2ROSOG2I.js} +2 -2
- package/dist/{chunk-XKWEMFHP.js → chunk-2WCXKANA.js} +2 -2
- package/dist/{chunk-EZGT3NJX.js → chunk-33RLKB6L.js} +2 -2
- package/dist/{chunk-GJ3FR5WG.js → chunk-34MLC6UI.js} +2 -2
- package/dist/{chunk-G6RQVDTI.js → chunk-4BUMNEYQ.js} +2 -2
- package/dist/{chunk-XTSVYYAL.js → chunk-4CZJ4YJB.js} +2 -2
- package/dist/{chunk-TCVRJ56J.js → chunk-4FMT4HPC.js} +2 -2
- package/dist/{chunk-7FG5M53V.js → chunk-53SUJOJA.js} +2 -2
- package/dist/{chunk-AEDB4WXE.js → chunk-5FUAFNMP.js} +2 -2
- package/dist/chunk-5GCAM4JE.js +122 -0
- package/dist/{chunk-YBAC3RON.js → chunk-5GOBZI34.js} +2 -2
- package/dist/{chunk-LJD7V7UO.js → chunk-5OR4QRPR.js} +2 -2
- package/dist/{chunk-X36LKKVG.js → chunk-5OZCNAVM.js} +2 -2
- package/dist/{chunk-7EI4MU5A.js → chunk-5TZ2MQBG.js} +2 -2
- package/dist/{chunk-GNJHHPZE.js → chunk-64QITTX7.js} +2 -2
- package/dist/{chunk-HOXI4F5I.js → chunk-6EWBPAA3.js} +2 -2
- package/dist/{chunk-EZHARAL4.js → chunk-6FIA5BEB.js} +2 -2
- package/dist/{chunk-4ZCNFENR.js → chunk-77IOFJVY.js} +2 -2
- package/dist/{chunk-T5CSWYAZ.js → chunk-AD7WUFFT.js} +2 -2
- package/dist/{chunk-OGHGTD6Z.js → chunk-AEM24WSF.js} +2 -2
- package/dist/{chunk-S65OEY2G.js → chunk-AFVU2GB2.js} +2 -2
- package/dist/{chunk-SATRCB5O.js → chunk-AOSFSYEA.js} +2 -2
- package/dist/{chunk-3OSRXJKK.js → chunk-APLNTJPJ.js} +2 -2
- package/dist/{chunk-TDGCALH6.js → chunk-AYRHVJXW.js} +2 -2
- package/dist/{chunk-MDDF67O2.js → chunk-B26UX7ZD.js} +2 -2
- package/dist/{chunk-JFGUBZWE.js → chunk-C3KCSAQ4.js} +2 -2
- package/dist/{chunk-XESK6725.js → chunk-C3VQZFP2.js} +2 -2
- package/dist/{chunk-FLIF3JWA.js → chunk-CAKPEQZB.js} +2 -2
- package/dist/{chunk-PKAPOFF5.js → chunk-CIYUFF24.js} +2 -2
- package/dist/{chunk-J3U47L4Q.js → chunk-DO775SYA.js} +2 -2
- package/dist/{chunk-AM2LGOEX.js → chunk-EGKWRX5I.js} +2 -2
- package/dist/{chunk-PAZFJMXB.js → chunk-EHU4TZJJ.js} +2 -2
- package/dist/{chunk-YYR7ADNB.js → chunk-EII5ZHL2.js} +2 -2
- package/dist/{chunk-F5L7WEZF.js → chunk-EYF5HOUZ.js} +2 -2
- package/dist/{chunk-RIGY5DDE.js → chunk-FB6IKAKZ.js} +2 -2
- package/dist/{chunk-BGUYAA3Q.js → chunk-FBUNGRKI.js} +2 -2
- package/dist/{chunk-M2TRDR25.js → chunk-FC5K7T35.js} +1 -1
- package/dist/{chunk-KWBA6FDD.js → chunk-FRXB74RQ.js} +2 -2
- package/dist/{chunk-BYPVNKJT.js → chunk-FTRNGQGR.js} +2 -2
- package/dist/{chunk-54UYBTZW.js → chunk-FUFNRZFJ.js} +2 -2
- package/dist/{chunk-TDZXQAH7.js → chunk-FYE4PWWP.js} +2 -2
- package/dist/{chunk-QNMOZ3CJ.js → chunk-GAE7WCBK.js} +2 -2
- package/dist/{chunk-2ZNZSNVW.js → chunk-HAC5EI2T.js} +2 -2
- package/dist/{chunk-WT7TOU2C.js → chunk-HCSTQGQE.js} +2 -2
- package/dist/{chunk-UXOVHGT6.js → chunk-HFBNIIZX.js} +2 -2
- package/dist/{chunk-JHK2DMUQ.js → chunk-HGFDYOVB.js} +1 -1
- package/dist/{chunk-UJL3N6TC.js → chunk-HHOJH3RJ.js} +2 -2
- package/dist/{chunk-X65VYV2S.js → chunk-HNTLCR4F.js} +2 -2
- package/dist/{chunk-RJLU7IMR.js → chunk-IICQP2DY.js} +2 -2
- package/dist/{chunk-J65FQLDL.js → chunk-IXAALOUP.js} +2 -2
- package/dist/{chunk-XDVT7QPG.js → chunk-J4MYRIYT.js} +2 -2
- package/dist/{chunk-TAB7AWKO.js → chunk-J5XJWCB3.js} +2 -2
- package/dist/{chunk-DWN7QDTV.js → chunk-JFO2UVQP.js} +2 -2
- package/dist/{chunk-FMC3BI4I.js → chunk-JRCJEHRG.js} +2 -2
- package/dist/{chunk-4XTPZ5CR.js → chunk-KMOMNTB4.js} +2 -2
- package/dist/{chunk-ZL5Y23AJ.js → chunk-LM72NQ7T.js} +1 -1
- package/dist/{chunk-4ZHJAHLE.js → chunk-LSJDKJIB.js} +2 -2
- package/dist/{chunk-VV5WJLRO.js → chunk-MP43RX4O.js} +1 -1
- package/dist/{chunk-D5OXYOJP.js → chunk-MQ2B33LQ.js} +1 -1
- package/dist/{chunk-MTFHE7ZO.js → chunk-MRYPDVOS.js} +2 -2
- package/dist/{chunk-GMZYT44R.js → chunk-NLNZK7RL.js} +5 -5
- package/dist/{chunk-ZXWFN7CK.js → chunk-OAM22BCR.js} +2 -2
- package/dist/{chunk-TOYQTO44.js → chunk-OLG2YPLS.js} +2 -2
- package/dist/{chunk-PBADFBRR.js → chunk-OQ6TCHBB.js} +2 -2
- package/dist/{chunk-3KQOIXLO.js → chunk-PCIFZHWS.js} +2 -2
- package/dist/{chunk-KD6TPIXM.js → chunk-PJENL245.js} +2 -2
- package/dist/{chunk-F334Z5UA.js → chunk-PLDIXTKR.js} +2 -2
- package/dist/{chunk-BOXAKNN6.js → chunk-PNESKY2Z.js} +2 -2
- package/dist/{chunk-QHOUNTDZ.js → chunk-PTYQQHZM.js} +2 -2
- package/dist/{chunk-2FAJTZSX.js → chunk-QKW7ISEW.js} +2 -2
- package/dist/{chunk-AWSRND4W.js → chunk-QNO3QIMN.js} +2 -2
- package/dist/{chunk-DV6B262O.js → chunk-SJ6XSCG7.js} +2 -2
- package/dist/{chunk-XPYXEEDO.js → chunk-SOS256TP.js} +2 -2
- package/dist/{chunk-DQIJMKNE.js → chunk-TDUU63FC.js} +2 -2
- package/dist/chunk-TOIS2VAI.js +4 -0
- package/dist/{chunk-TC3X33N6.js → chunk-TYEGFDOP.js} +2 -2
- package/dist/chunk-UJKZQLDB.js +2 -0
- package/dist/chunk-V27BEQJN.js +7 -0
- package/dist/{chunk-J6BR4MD6.js → chunk-VIKEPD4D.js} +2 -2
- package/dist/{chunk-XDSB47KO.js → chunk-WAU7HVDI.js} +2 -2
- package/dist/chunk-WFWQWQK6.js +3 -0
- package/dist/chunk-WWCZCH7W.js +3 -0
- package/dist/{chunk-QB5WSOTY.js → chunk-XAMVIPE2.js} +2 -2
- package/dist/{chunk-A45K6VUK.js → chunk-XWE7PZQH.js} +2 -2
- package/dist/{chunk-547VY366.js → chunk-XWJ3JYRG.js} +2 -2
- package/dist/{chunk-QN67MWDU.js → chunk-XYBNOILR.js} +2 -2
- package/dist/{chunk-IWK562KR.js → chunk-XYNWAZ6J.js} +2 -2
- package/dist/{chunk-UVMME4FI.js → chunk-YGBHQOB2.js} +2 -2
- package/dist/{chunk-ZNSLF5AC.js → chunk-YGQBJUS6.js} +2 -2
- package/dist/{chunk-6DHPQS72.js → chunk-YILKXTIY.js} +2 -2
- package/dist/{chunk-X3OOU7CF.js → chunk-Z7M7X3ZG.js} +2 -2
- package/dist/{chunk-G6QQCX45.js → chunk-ZJGZCBYT.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{command-descriptors-SWFWGIFK.js → command-descriptors-QJEYYND2.js} +168 -166
- package/dist/direct-navigation-TT23TDBS.js +3 -0
- package/dist/index.js +1 -1
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.js +1 -1
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +24 -24
- package/dist/reindex.js +38 -38
- package/dist/runtime.d.ts +6 -1
- package/dist/runtime.js +2 -2
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/watch-server.js +5 -5
- package/package.json +1 -1
- package/dist/chunk-42QYU6FD.js +0 -3
- package/dist/chunk-6SHX42QQ.js +0 -6
- package/dist/chunk-AERYQJ52.js +0 -3
- package/dist/chunk-IXORBCMR.js +0 -120
- package/dist/chunk-NEG77KKH.js +0 -4
- package/dist/chunk-OYYZLJVT.js +0 -2
- package/dist/direct-navigation-RKMPBXMI.js +0 -3
package/dist/reindex.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as W}from"./chunk-NH7WNNQC.js";import{a as
|
|
2
|
-
`)}finally{
|
|
3
|
-
`)}finally{
|
|
4
|
-
VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let p=0;for(let l of d){if(o.has(l))continue;let m=
|
|
5
|
-
`).filter(r=>r&&t.has(
|
|
1
|
+
import{a as W}from"./chunk-NH7WNNQC.js";import{a as gt,e as ft,g as mt,h as Mn,i as Nn,j as $n,k as Gn}from"./chunk-V27BEQJN.js";import{a as Ln}from"./chunk-YZXV3CU3.js";import{A as _n,a as Y,b as ne,c as re,d as ct,e as ut,f as dt,g as T,h as R,m as En,n as Tn,o as Ee,p as Dn,q as Te,r as Fn,s as On,t as jn,u as lt,v as pt,y as An}from"./chunk-NLNZK7RL.js";import"./chunk-P5XHIJHI.js";import{a as st,b as kn,d as De,g as Cn}from"./chunk-LM72NQ7T.js";import{a as ke}from"./chunk-AOSFSYEA.js";import"./chunk-AYRHVJXW.js";import"./chunk-GAE7WCBK.js";import{J as Pn,K as wn,d as Z}from"./chunk-WAU7HVDI.js";import{s as ee,t as te}from"./chunk-FC5K7T35.js";import{a as we}from"./chunk-64MNV6AB.js";import{execFileSync as Td}from"child_process";import{createHash as Dd}from"crypto";import{closeSync as Fd,copyFileSync as rt,existsSync as O,mkdirSync as nt,mkdtempSync as Od,openSync as jd,readdirSync as Ao,readFileSync as it,renameSync as _o,rmSync as M,statSync as Cd,writeFileSync as Ad}from"fs";import{basename as tt,dirname as h,extname as _d,join as x,resolve as Eo}from"path";import{platform as Ld}from"os";import{randomUUID as Vn}from"crypto";import{closeSync as Bn,mkdirSync as zo,openSync as Un,readFileSync as Wn,unlinkSync as Hn,writeFileSync as Jn}from"fs";import{dirname as Yo,join as Xo}from"path";function qn(e,t={}){return ie(Xo(e,"gc.lock"),t)}function ie(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;zo(Yo(e),{recursive:!0});do{let a=Vn();try{let s=Un(e,"wx");try{let c={version:1,pid:process.pid,token:a,startedAt:new Date(i()).toISOString()};Jn(s,`${JSON.stringify(c)}
|
|
2
|
+
`)}finally{Bn(s)}return{release:()=>Yn(e,a)}}catch(s){if(s.code!=="EEXIST")return null;let c=zn(e);if(c&&(c.pid===void 0||!T(c.pid))){Qo(e,c);continue}if(Date.now()>=o)return null;Ko(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function zn(e){try{let t=Wn(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 Qo(e,t){let n=`${e}.reclaim`,r=Vn(),i;try{i=Un(n,"wx")}catch{return!1}try{Jn(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
|
|
3
|
+
`)}finally{Bn(i)}try{let o=zn(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Hn(e),!0)}catch{return!1}finally{Yn(n,r)}}function Yn(e,t){try{let n=JSON.parse(Wn(e,"utf8"));n.pid===process.pid&&n.token===t&&Hn(e)}catch{}}function Ko(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import Zo from"better-sqlite3";import{execFileSync as ea}from"child_process";import{existsSync as ta,readdirSync as na,readFileSync as ra}from"fs";import{extname as Fe,join as Xn}from"path";function H(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Qn({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Qn(e){let t=new Set((e.extensions??Pn).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!ta(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Ln(e.projectRoot),r=ia(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Zo(e.dbPath);try{let o=aa(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
4
|
+
VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let p=0;for(let l of d){if(o.has(l))continue;let m=ra(Xn(e.projectRoot,l),"utf-8"),g=a.run(sa(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 ia(e,t){let n=oa(e,t);if(n)return n;let r=[],i=o=>{let a=o?Xn(e,o):e,s;try{s=na(a,{withFileTypes:!0})}catch{return}for(let c of s){if(wn.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(Fe(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function oa(e,t){try{return ea("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
|
|
5
|
+
`).filter(r=>r&&t.has(Fe(r).toLowerCase())).sort()}catch{return null}}function aa(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.add(s.relative_path)}return n}function sa(e){return Fe(e).toLowerCase()===".vue"?"vue":Fe(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as ua}from"crypto";import{appendFileSync as da,existsSync as tr,mkdirSync as la,readFileSync as _l,renameSync as pa,rmSync as yt,statSync as ga}from"fs";import{dirname as nr,join as Zn}from"path";function ht(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function Oe(e,t,n){let r=e.changes.map(s=>s.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=ht(e),a=new Set(o.reasons);return r.some(s=>!i.has(s))&&a.add("changed-file-outside-project"),t===null?(a.add("dependency-graph-unavailable"),Kn(r,i,a)):a.size>0?Kn(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ca(r,t,i),reasons:[]}}function Kn(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ca(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let u=r.get(c)??new Set;u.add(a),r.set(c,u)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var fa="<global-symbols>";function ma(e){let t=[];for(let n of e.all(`
|
|
6
6
|
SELECT relative_path, language, position_encoding, text
|
|
7
7
|
FROM documents
|
|
8
8
|
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
@@ -29,7 +29,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
29
29
|
FROM defn_enclosing_ranges r
|
|
30
30
|
JOIN documents d ON d.id = r.document_id
|
|
31
31
|
JOIN global_symbols g ON g.id = r.symbol_id
|
|
32
|
-
`))t.push({relativePath:n.relative_path,kind:"definition",values:
|
|
32
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:St(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
33
33
|
SELECT d.relative_path,
|
|
34
34
|
c.chunk_index,
|
|
35
35
|
m.role,
|
|
@@ -44,7 +44,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
44
44
|
JOIN chunks c ON c.id = m.chunk_id
|
|
45
45
|
JOIN documents d ON d.id = c.document_id
|
|
46
46
|
JOIN global_symbols g ON g.id = m.symbol_id
|
|
47
|
-
`))t.push({relativePath:n.relative_path,kind:"mention",values:
|
|
47
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:St(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
48
48
|
SELECT g.symbol,
|
|
49
49
|
g.display_name,
|
|
50
50
|
g.kind,
|
|
@@ -58,10 +58,10 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
58
58
|
) AND NOT EXISTS (
|
|
59
59
|
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
60
60
|
)
|
|
61
|
-
`))t.push({relativePath:
|
|
62
|
-
`);n.set(r,o.digest("hex"))}return n}function
|
|
63
|
-
|
|
64
|
-
`)){if(!r||r.split("/").some(o=>or.has(o)))continue;let i=rr(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Pa(e,t){return t?.length?t.some(n=>e.has(n)):!1}function tr(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as ar,readdirSync as wa}from"fs";import{isAbsolute as ka,join as bt,resolve as Ea}from"path";var cr={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:Y.language,indexerBinary:Y.indexerBinary,checkCommand:`${Y.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Y.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:Y.installUrl},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",ka(r)?r:Ea(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",sr(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",sr(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=bt(e,"vendor","bin","scip-php"),r=bt(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",ar(r)?r:ar(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Oe(e){return cr[e]}function sr(e,t){let n;try{n=wa(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return bt(e,i);return null}import{readFileSync as xt,writeFileSync as vt}from"fs";import{create as oe}from"@bufbuild/protobuf";import{deserializeSCIP as It,serializeSCIP as Pt,DocumentSchema as Aa,IndexSchema as lr,MetadataSchema as La,SymbolInformationSchema as Ma}from"@c4312/scip";import{readFileSync as Ta,writeFileSync as Da}from"fs";import{create as ur}from"@bufbuild/protobuf";import{deserializeSCIP as Fa,DocumentSchema as ja,IndexSchema as Oa,serializeSCIP as Ca,SymbolRole as _a}from"@c4312/scip";function dr(e){let t;try{t=Fa(Ta(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Rt(t);return n.removedDefinitionOccurrences>0&&Da(e,Buffer.from(Ca(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Rt(e){let t=new Set;for(let o of e.documents)for(let a of o.symbols)a.symbol&&t.add(a.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&_a.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(ur(ja,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:ur(Oa,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function wt(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=$a(e),n=Ga(e.flatMap(i=>i.documents??[])),r=fr(e.flatMap(i=>i.externalSymbols??[]));return oe(lr,{metadata:t,documents:n,externalSymbols:r})}function kt(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>It(xt(i))),r=wt(n);return vt(t,Buffer.from(Pt(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function pr(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>It(xt(i))),r=Rt(wt(n));return vt(t,Buffer.from(Pt(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function Na(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return oe(lr,{metadata:oe(La,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function gr(e,t,n){let r=It(xt(e)),i=Na(r,t,n);vt(e,Buffer.from(Pt(i)))}function $a(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function Ga(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,oe(Aa,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Va([...r.occurrences,...n.occurrences]),symbols:fr([...r.symbols,...n.symbols]),text:Ua(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Va(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function fr(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,oe(Ma,{symbol:r.symbol,documentation:Wa([...r.documentation,...n.documentation]),relationships:Ba([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function Ba(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function Ua(e,t){return e?t?e.length>=t.length?e:t:e:t}function Wa(e){return[...new Set(e)]}import{createHash as Ja}from"crypto";import{copyFileSync as qa,existsSync as mr,rmSync as hr}from"fs";import{resolve as Ha}from"path";import br from"better-sqlite3";var za={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},Ya={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Rr(e){let t=Date.now(),n=Qa(e.affectedFiles);if(Xa(e.previousDbPath,e.miniDbPath,e.candidateDbPath),hr(e.candidateDbPath,{force:!0}),!mr(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!mr(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");yr(e.previousDbPath,"previous SQLite generation",!1),yr(e.miniDbPath,"incremental SQLite mini database"),qa(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new br(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Et(r,"main","candidate SQLite generation"),Et(r,"incremental","incremental SQLite mini database"),Ka(r,n),Za(r,n.length);let i=Tt(r,"main",!0),o=M(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{es(r),ts(r),ns(r),e.onStage?.("after-delete"),rs(r),e.onStage?.("after-symbol-reconciliation"),is(r),e.onStage?.("after-insert"),os(r),as(r,n.length,o),e.onStage?.("before-commit")}).immediate(),xr(r,"main","candidate SQLite generation");let c=[...ss(r)].filter(([u,d])=>i.get(u)!==d).map(([u])=>u).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{hr(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function Qa(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function Xa(e,t,n){let r=[e,t,n].map(i=>Ha(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function yr(e,t,n=!0){let r=new br(e,{readonly:!0,fileMustExist:!0});try{Et(r,"main",t),n&&xr(r,"main",t)}finally{r.close()}}function Et(e,t,n){for(let[r,i]of Object.entries(za)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:d})=>({name:s,type:c.toUpperCase(),notnull:u,pk:d}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Ya)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),a=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(o?.tbl_name!==i.table||JSON.stringify(a)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}Sr(e,t,"documents",["relative_path"],n),Sr(e,t,"global_symbols",["symbol"],n)}function Sr(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(u=>u.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function xr(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function Ka(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function Za(e,t){let n=M(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=M(e,`SELECT COUNT(*) AS value
|
|
61
|
+
`))t.push({relativePath:fa,kind:"global-symbol",values:St(n)});return ha(t)}function ha(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[a])=>o.localeCompare(a))){let o=ua("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
|
|
62
|
+
`);n.set(r,o.digest("hex"))}return n}function ya(e,t){let n=[],r=[],i=[],o=[],a=new Set([...e.keys(),...t.keys()]);for(let s of[...a].sort()){let c=e.get(s),u=t.get(s);c===void 0?n.push(s):u===void 0?i.push(s):c!==u?r.push(s):o.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function bt(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),a=e.affectedFiles.filter(c=>!i.has(c)).sort(),s=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:s/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:a}}function Rt(e,t=Ia){let n=t.now();if(!t.databaseExists(e.previousDbPath))return je(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return je(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),a=Ee(e.previousSnapshot,e.currentSnapshot),s=new Set(o),c=a.changes.length>0&&!ht(a).fullProject&&a.changes.every(l=>s.has(l.path)),u=Oe(a,c?t.dependencyGraph(r):new Map,o),d=ya(t.factDigests(r),t.factDigests(i)),p=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(p).toISOString(),durationMs:Math.max(0,p-n),manifest:a,plan:u,comparison:d,evaluation:bt(u,d,o.length)}}catch(o){return je(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{er(r),er(i)}}function rr(e,t,n,r=Date.now()){return je(e,t,r,r,n)}function Sa(e){let t=nr(e);return{latestPath:Zn(t,"affected-shadow-latest.json"),historyPath:Zn(t,"affected-shadow.jsonl")}}function ir(e,t,n=Pa){let r=Sa(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var ba=8*1024*1024,Ra=".previous";function xa(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function va(e,t,n=ba){let r=`${JSON.stringify(xa(t))}
|
|
63
|
+
`,i=Math.max(1,Math.floor(n)),o=`${e}${Ra}`;if(la(nr(e),{recursive:!0}),tr(e)){let a=ga(e).size;a>i?(yt(e,{force:!0}),yt(o,{force:!0})):a+Buffer.byteLength(r)>i&&(yt(o,{force:!0}),pa(e,o))}da(e,r)}function St(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var Ia={now:()=>Date.now(),databaseExists:e=>tr(e),openDatabase:(e,t,n)=>new W({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>we(e),dependencyGraph:e=>ke(e),factDigests:e=>ma(e)},Pa={appendHistory:va,writeLatest:(e,t)=>R(e,t,{spacing:2,trailingNewline:!0})};function je(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function er(e){try{e?.close()}catch{}}import{execFileSync as wa}from"child_process";import{existsSync as ka,readdirSync as ar}from"fs";import{extname as sr,join as cr}from"path";var ur=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Ea=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function xt(e){let t=[],n=Ta(e),r=ja(e);for(let i of Ea){if(Da(e,i.files)){t.push(i.language);continue}if(Fa(n,i.globs)){t.push(i.language);continue}Aa(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&or(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&or(t,"c"),t}function Ta(e){try{return ar(e)}catch{return[]}}function Da(e,t){return t?.length?t.some(n=>ka(cr(e,n))):!1}function Fa(e,t){return t?.length?e.some(n=>t.some(r=>Oa(n,r))):!1}function Oa(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function ja(e){let t=Ca(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=ar(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")&&!a.name.endsWith("proj")&&!a.name.endsWith("sln")&&a.isDirectory())continue;let s=cr(i,a.name);if(a.isDirectory()){ur.has(a.name)||r.push(s);continue}let c=sr(a.name).toLowerCase();c&&n.add(c)}}return n}function Ca(e){try{let t=wa("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
|
|
64
|
+
`)){if(!r||r.split("/").some(o=>ur.has(o)))continue;let i=sr(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Aa(e,t){return t?.length?t.some(n=>e.has(n)):!1}function or(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as dr,readdirSync as _a}from"fs";import{isAbsolute as La,join as vt,resolve as Ma}from"path";var pr={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:Y.language,indexerBinary:Y.indexerBinary,checkCommand:`${Y.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Y.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:Y.installUrl},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",La(r)?r:Ma(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",lr(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",lr(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=vt(e,"vendor","bin","scip-php"),r=vt(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",dr(r)?r:dr(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Ce(e){return pr[e]}function lr(e,t){let n;try{n=_a(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return vt(e,i);return null}import{readFileSync as Pt,writeFileSync as wt}from"fs";import{create as oe}from"@bufbuild/protobuf";import{deserializeSCIP as kt,serializeSCIP as Et,DocumentSchema as Ha,IndexSchema as mr,MetadataSchema as Ja,SymbolInformationSchema as qa}from"@c4312/scip";import{readFileSync as Na,writeFileSync as $a}from"fs";import{create as gr}from"@bufbuild/protobuf";import{deserializeSCIP as Ga,DocumentSchema as Va,IndexSchema as Ba,serializeSCIP as Ua,SymbolRole as Wa}from"@c4312/scip";function fr(e){let t;try{t=Ga(Na(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=It(t);return n.removedDefinitionOccurrences>0&&$a(e,Buffer.from(Ua(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function It(e){let t=new Set;for(let o of e.documents)for(let a of o.symbols)a.symbol&&t.add(a.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&Wa.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(gr(Va,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:gr(Ba,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function Tt(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Ya(e),n=Xa(e.flatMap(i=>i.documents??[])),r=Sr(e.flatMap(i=>i.externalSymbols??[]));return oe(mr,{metadata:t,documents:n,externalSymbols:r})}function Dt(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>kt(Pt(i))),r=Tt(n);return wt(t,Buffer.from(Et(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function hr(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>kt(Pt(i))),r=It(Tt(n));return wt(t,Buffer.from(Et(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function za(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return oe(mr,{metadata:oe(Ja,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function yr(e,t,n){let r=kt(Pt(e)),i=za(r,t,n);wt(e,Buffer.from(Et(i)))}function Ya(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function Xa(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,oe(Ha,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Qa([...r.occurrences,...n.occurrences]),symbols:Sr([...r.symbols,...n.symbols]),text:Za(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Qa(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function Sr(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,oe(qa,{symbol:r.symbol,documentation:es([...r.documentation,...n.documentation]),relationships:Ka([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function Ka(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function Za(e,t){return e?t?e.length>=t.length?e:t:e:t}function es(e){return[...new Set(e)]}import{createHash as ts}from"crypto";import{copyFileSync as ns,existsSync as br,rmSync as Rr}from"fs";import{resolve as rs}from"path";import Ir from"better-sqlite3";var is={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},os={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Pr(e){let t=Date.now(),n=as(e.affectedFiles);if(ss(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Rr(e.candidateDbPath,{force:!0}),!br(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!br(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");xr(e.previousDbPath,"previous SQLite generation",!1),xr(e.miniDbPath,"incremental SQLite mini database"),ns(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Ir(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Ft(r,"main","candidate SQLite generation"),Ft(r,"incremental","incremental SQLite mini database"),cs(r,n),us(r,n.length);let i=Ot(r,"main",!0),o=N(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{ds(r),ls(r),ps(r),e.onStage?.("after-delete"),gs(r),e.onStage?.("after-symbol-reconciliation"),fs(r),e.onStage?.("after-insert"),ms(r),hs(r,n.length,o),e.onStage?.("before-commit")}).immediate(),wr(r,"main","candidate SQLite generation");let c=[...ys(r)].filter(([u,d])=>i.get(u)!==d).map(([u])=>u).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{Rr(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function as(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function ss(e,t,n){let r=[e,t,n].map(i=>rs(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function xr(e,t,n=!0){let r=new Ir(e,{readonly:!0,fileMustExist:!0});try{Ft(r,"main",t),n&&wr(r,"main",t)}finally{r.close()}}function Ft(e,t,n){for(let[r,i]of Object.entries(is)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:d})=>({name:s,type:c.toUpperCase(),notnull:u,pk:d}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(os)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),a=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(o?.tbl_name!==i.table||JSON.stringify(a)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}vr(e,t,"documents",["relative_path"],n),vr(e,t,"global_symbols",["symbol"],n)}function vr(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(u=>u.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function wr(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function cs(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function us(e,t){let n=N(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=N(e,`SELECT COUNT(*) AS value
|
|
65
65
|
FROM main.documents d
|
|
66
66
|
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
|
|
67
67
|
FROM temp.incremental_affected_paths p
|
|
@@ -71,7 +71,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
71
71
|
FROM incremental.documents d
|
|
72
72
|
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
73
73
|
WHERE p.relative_path IS NULL
|
|
74
|
-
LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function
|
|
74
|
+
LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function ds(e){e.exec(`
|
|
75
75
|
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
76
76
|
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
77
77
|
SELECT g.symbol
|
|
@@ -98,7 +98,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
98
98
|
FROM incremental.mentions m
|
|
99
99
|
JOIN incremental.global_symbols g ON g.id = m.symbol_id
|
|
100
100
|
WHERE m.role = 1;
|
|
101
|
-
`)}function
|
|
101
|
+
`)}function ls(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
102
102
|
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
103
103
|
UNION
|
|
104
104
|
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
@@ -121,7 +121,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
121
121
|
SELECT u.symbol
|
|
122
122
|
FROM unaffected_definitions u
|
|
123
123
|
JOIN changed_symbols c ON c.symbol = u.symbol
|
|
124
|
-
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function
|
|
124
|
+
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function ps(e){e.exec(`
|
|
125
125
|
DELETE FROM main.mentions
|
|
126
126
|
WHERE chunk_id IN (
|
|
127
127
|
SELECT c.id
|
|
@@ -143,7 +143,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
143
143
|
);
|
|
144
144
|
DELETE FROM main.documents
|
|
145
145
|
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
146
|
-
`)}function
|
|
146
|
+
`)}function gs(e){e.exec(`
|
|
147
147
|
UPDATE main.global_symbols
|
|
148
148
|
SET display_name = NULL,
|
|
149
149
|
kind = NULL,
|
|
@@ -185,7 +185,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
185
185
|
WHERE source.symbol = main.global_symbols.symbol
|
|
186
186
|
)
|
|
187
187
|
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
188
|
-
`)}function
|
|
188
|
+
`)}function fs(e){let t=N(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=N(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=N(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
|
|
189
189
|
SELECT id + ?, language, relative_path, position_encoding, text
|
|
190
190
|
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
191
191
|
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
@@ -200,15 +200,15 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
200
200
|
r.start_line, r.start_char, r.end_line, r.end_char
|
|
201
201
|
FROM incremental.defn_enclosing_ranges r
|
|
202
202
|
JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
203
|
-
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function
|
|
203
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function ms(e){e.exec(`
|
|
204
204
|
DELETE FROM main.global_symbols
|
|
205
205
|
WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
206
206
|
AND NOT EXISTS (
|
|
207
207
|
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
208
208
|
);
|
|
209
|
-
`)}function
|
|
209
|
+
`)}function hs(e,t,n){let r=N(e,"SELECT COUNT(*) AS value FROM main.documents"),i=N(e,`SELECT COUNT(*) AS value
|
|
210
210
|
FROM main.documents d
|
|
211
|
-
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),a=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||a!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function
|
|
211
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),a=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||a!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function ys(e){let t=Ot(e,"main",!0),n=Ot(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function Ot(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
|
|
212
212
|
FROM ${t}.documents d
|
|
213
213
|
${r}
|
|
214
214
|
ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
|
|
@@ -230,13 +230,13 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
230
230
|
JOIN ${t}.documents d ON d.id = c.document_id
|
|
231
231
|
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
232
232
|
${r}
|
|
233
|
-
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,p]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let l of p){let m=JSON.stringify([d,l]),g=c.get(l.relative_path)??[];g.push(m),c.set(l.relative_path,g)}let u=new Map;for(let[d,p]of[...c].sort(([l],[m])=>l.localeCompare(m))){let l=
|
|
234
|
-
`);u.set(d,l.digest("hex"))}return u}function
|
|
235
|
-
`)}function
|
|
236
|
-
`;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function Ct(e){try{let t=gs(e,"utf-8"),n=JSON.parse(ws(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as bi,randomUUID as zt}from"crypto";import{closeSync as Ri,constants as rc,copyFileSync as mi,existsSync as B,lstatSync as ic,mkdirSync as _,mkdtempSync as xi,openSync as vi,readdirSync as oc,readFileSync as F,realpathSync as ac,renameSync as z,rmSync as V,statSync as sc,unlinkSync as qt,writeFileSync as Ii}from"fs";import{dirname as Pi,join as f,resolve as me}from"path";import{setTimeout as cc}from"timers/promises";import{pathToFileURL as hi}from"url";import{deserializeSCIP as wi}from"@c4312/scip";import uc from"better-sqlite3";import{createRequire as ks}from"module";var Es=ks(import.meta.url),Or=Ts().version;function Ts(){for(let e of["../package.json","../../package.json"])try{return Es(e)}catch{}return{version:"0.0.0"}}import{lstatSync as Us,readdirSync as Ws}from"fs";import{join as Js,relative as qs,resolve as Bt,sep as Hs}from"path";import{createHash as Ds}from"crypto";import{existsSync as At,mkdirSync as Fs,readFileSync as _e,readdirSync as fp,renameSync as js,rmSync as mp,writeFileSync as Os}from"fs";import{join as Q}from"path";import{create as _r,fromBinary as Ar,toBinary as Cs}from"@bufbuild/protobuf";import{deserializeSCIP as Ae,DocumentSchema as Lt,IndexSchema as Lr,serializeSCIP as Mr}from"@c4312/scip";var Le=1,ae="typescript-scip-fragments";function Nr(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let a=q(o.relativePath);if(t.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(t.add(a),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${a}`);let s=Ar(Lt,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Mr(_r(Lr,{documents:n,externalSymbols:[]})),i=Ae(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Me(e){let t=Q(e,ae);return{rootDir:t,blobDir:Q(t,"blobs"),generationDir:Q(t,"generations")}}function _s(e){let t=Ae(e.indexBytes);Qr(t.metadata,Xr(e)),Yr(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=q(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=Cs(Lt,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?H(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:H(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Jr(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=qr(e,r);return Hr(e.cacheDir,i),i}function $r(e){let t=Me(e.cacheDir);if(!At(Mt(t,e.generationIdentity)))return _s(e);let n=Vr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function Gr(e){let t=Vr({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=q(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(r.add(a),!n.has(a))throw new Error(`TypeScript fragment replacement has no prior document: ${a}`);let s=e.documentIdentities.get(a);if(!s)throw new Error(`missing TypeScript document identity: ${a}`);o.bytes===null?n.delete(a):n.set(a,Jr(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=qr(e,[...n.values()]);return Hr(e.cacheDir,i),i}function Vr(e){let t=Me(e.cacheDir),n=Mt(t,e.generationIdentity),r;try{r=zr(_e(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let a=Q(t.blobDir,`${o.blobHash}.scipdoc`),s=_e(a);if(s.byteLength!==o.byteLength||H(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Br(e){let t=Wr(e);return _t(t.baseIndex,t.completeDocuments,"assembled")}function Ur(e){let t=Wr(e);return As(t.deletedAffectedPaths),{completeIndexBytes:_t(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:_t(t.baseIndex,t.affectedDocuments,"affected")}}function Wr(e){let t=Ae(e.baseIndexBytes);Qr(t.metadata,Xr(e)),Yr(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=q(s.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,s)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],a=[];for(let s of t.documents){let c=q(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let u=n.get(c);if(!u){i.push(s);continue}if(n.delete(c),u.bytes===null){a.push(c);continue}let d=Ar(Lt,u.bytes);if(d.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${d.relativePath}`);i.push(d),o.push(d)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function _t(e,t,n){let r=Mr(_r(Lr,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Ae(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function As(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Jr(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=q(t.relativePath),i=Buffer.from(t.bytes),o=H(i),a=Me(e);Fs(a.blobDir,{recursive:!0});let s=Q(a.blobDir,`${o}.scipdoc`);if(At(s)){let c=_e(s);if(c.byteLength!==i.byteLength||H(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;Os(c,i),js(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function qr(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:Le,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Hr(e,t){let n=Me(e),r=Mt(n,t.generationIdentity);if(At(r)){let i=zr(_e(r,"utf8"));if(Cr(i)!==Cr(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}b(r,t,{spacing:2,trailingNewline:!0})}function Cr(e){return H(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function zr(e){let t=JSON.parse(e);if(t.version!==Le||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(q(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Mt(e,t){return Q(e.generationDir,Ls(t))}function Ls(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${H(e)}.json`}function Yr(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Qr(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function Xr(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function q(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function H(e){return Ds("sha256").update(e).digest("hex")}import{createHash as Ms}from"crypto";import{existsSync as se,mkdirSync as Ns,readFileSync as ue,readdirSync as Nt,renameSync as $s,rmSync as Kr,writeFileSync as Gs}from"fs";import{join as D}from"path";var Ne=1,ei=64*1024*1024,de="typescript-scip-overlays";function ti(e){let t=ii(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=Vt(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,Vs(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Ne,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,a)=>o.relativePath.localeCompare(a.relativePath))};return Bs(e.cacheDir,i),i}function ni(e){let t=ii(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=ue(D(le(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||ce(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return Br({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function ri(e,t){let n=le(e),r=D(n,"generations");if(!se(r))return;let i=new Set(t.map(Gt)),o=new Set;for(let s of Nt(r).filter(c=>i.has(c))){let c=$t(ue(D(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of Nt(r))i.has(s)||Kr(D(r,s),{force:!0});let a=D(n,"blobs");if(se(a))for(let s of Nt(a))o.has(s)||Kr(D(a,s),{force:!0})}function ii(e,t){let n=D(le(e),"generations",Gt(t));if(!se(n))return null;let r=$t(ue(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Vs(e,t){let n=Vt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=ce(r),o=D(le(e),"blobs");Ns(o,{recursive:!0});let a=D(o,`${i}.scipdoc`);if(se(a)){let s=ue(a);if(s.byteLength!==r.byteLength||ce(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Gs(s,r),$s(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Bs(e,t){let n=D(le(e),"generations",Gt(t.generationIdentity));if(se(n)){let r=$t(ue(n,"utf8"));if(Zr(r)!==Zr(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}b(n,t,{spacing:2,trailingNewline:!0})}function $t(e){let t=JSON.parse(e);if(t.version!==Ne||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(Vt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function le(e){return D(e,de)}function Gt(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${ce(e)}.json`}function Zr(e){return ce(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Vt(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function ce(e){return Ms("sha256").update(e).digest("hex")}var pe=1,Ut="language-indexes",oi=["index.db","index.scip","meta.json"],ai=[Ut,ae,de];function $e(e){let t=[];for(let n of oi)zs(e,n),t.push(n);for(let n of ai)si(e,n,t);return{version:pe,files:t.sort()}}function Ge(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!oi.includes(e)&&!ai.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function O(e,t){let n=Ge(t),r=Bt(e),i=Bt(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Hs}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function si(e,t,n){let r=Js(e,t),i;try{i=Ws(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let a=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${a}`);o.isDirectory()?si(e,a,n):o.isFile()&&n.push(Ge(a))}}function zs(e,t){let n=O(e,t),r;try{r=Us(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(qs(Bt(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as Ys}from"crypto";import{copyFileSync as ci,existsSync as $,linkSync as Qs,mkdirSync as ui,readFileSync as pi,readdirSync as di,renameSync as Jt,rmSync as Be,statSync as Xs}from"fs";import{basename as Ve,dirname as ge,join as P,relative as li}from"path";var X=1,Ue=".scipquery-generations";function We(e){let t=Je(e.outputDb),n=Ks(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||Wt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Wt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Wt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=qe(e.metaPath,e.outputDb),i={version:X,currentGeneration:r,...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:(e.now??(()=>new Date))().toISOString()};return b(P(t,"state.json"),i,{spacing:2,trailingNewline:!0}),{currentGeneration:r,...n?{previousGeneration:n}:{}}}function gi(e){try{let t=JSON.parse(pi(P(Je(e),"state.json"),"utf8"));return t.version!==X||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!tc(t.previousGeneration)||!nc(t.publication)?null:t}catch{return null}}function fi(e,t,n=()=>new Date){if(!$(e)||!$(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=gi(e),i={version:X,currentGeneration:qe(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return b(P(Je(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function G(e,t=P(ge(e),"meta.json")){let n=P(Je(e),"state.json");if(!$(n))return{state:"legacy",statePath:n};let r=gi(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=qe(t,e),o=r.currentGeneration===i,a=r.previousGeneration?$(P(ge(e),r.previousGeneration.databasePath)):!0;return!o||!a?{state:"drifted",statePath:n,currentMatches:o,recoveryExists:a,generation:r,reason:o?"retained recovery database is missing":"stable database or metadata no longer matches the published generation"}:{state:"current",statePath:n,currentMatches:o,recoveryExists:a,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function Je(e){return P(ge(e),Ue)}function Ks(e,t){if(!$(e.outputDb))return;let n=qe(e.metaPath,e.outputDb),r=P(t,n),i=P(r,Ve(e.outputDb)),o=$(e.metaPath)?P(r,Ve(e.metaPath)):void 0;if(!$(i)){let a=`${r}.${process.pid}.${Date.now()}.tmp`;Be(a,{recursive:!0,force:!0}),ui(a,{recursive:!0});let s=P(a,Ve(e.outputDb));try{Qs(e.outputDb,s)}catch{ci(e.outputDb,s)}o&&ci(e.metaPath,P(a,Ve(e.metaPath))),ui(t,{recursive:!0}),Jt(a,r)}return Zs(t,n),{generationIdentity:n,databasePath:li(ge(e.outputDb),i),...o?{metadataPath:li(ge(e.outputDb),o)}:{}}}function Zs(e,t){for(let n of di(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||Be(P(e,n.name),{recursive:!0,force:!0});for(let n of di(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&Be(P(e,n.name),{recursive:!0,force:!0})}function qe(e,t){let n=Ys("sha256").update(`sqlite-generation-v${X}\0`);$(e)&&n.update(ec(pi(e,"utf8")));let r=Xs(t);return n.update(`\0${r.size}`),n.digest("hex")}function ec(e){try{let t=JSON.parse(e);if((t.version===2||t.version===3)&&t.status==="complete"&&typeof t.updatedAt=="string"&&t.fingerprint!==void 0)return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion})}catch{}return e}function Wt(e,t){Be(`${t}.tmp-replace`,{force:!0}),Jt(e,`${t}.tmp-replace`),Jt(`${t}.tmp-replace`,t)}function tc(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function nc(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,n=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(r=>r!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&n.every(r=>typeof r=="number"&&Number.isFinite(r)&&r>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}var Yt=1,yi="SCIP_QUERY_SHARED_CACHE",Ht=JSON.stringify({cliVersion:Or,artifactCatalogVersion:pe,sqliteGenerationStoreVersion:X,typescriptFragmentStoreVersion:Le,typescriptOverlayStoreVersion:Ne}),ki="manifest.json",dc="shared-cache.json",Qt=[Ut,ae,de];function He(e,t){if(!e.clean||!e.treeOid)return;let n=ye(JSON.stringify({version:Yt,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Ht}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Ht,generationId:n,repositoryCacheDir:Ln(e.repositoryId)}}function Ei(e,t,n){if(process.env[yi]==="0")return`${yi}=0`;if(!Mn(n))return"explicit cache or database override";if(me(t)!==me(f(An(e),"index.db")))return"index database is outside the managed worktree cache"}function C(e,t=!0){let n=Kt(e),r;try{r=pc(F(f(n,ki),"utf8"))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=O(n,i.path),a=sc(o);if(!a.isFile()||a.size!==i.size||ye(F(o))!==i.sha256)return null}}catch{return null}return r}function Ti(e){let t=C(e.snapshot);if(t)return t;if(!Oi(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Si(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=$e(e.sourceCacheDir),i=f(e.snapshot.repositoryCacheDir,"generations");_(i,{recursive:!0});let o=xi(f(i,`.tmp-${process.pid}-`));try{let a=[];for(let p of r.files){let l=O(e.sourceCacheDir,p),m=O(o,p);he(l,m);let g=F(m);a.push({path:p,size:g.byteLength,sha256:ye(g)})}let s=wi(F(f(o,"index.scip"))).metadata?.projectRoot;if(!s)throw new Error("shared SCIP generation has no project root metadata");let c=Zt(e.sourceProjectRoot);if(s!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(Si(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Yt,artifactCatalogVersion:pe,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:s,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:a.sort((p,l)=>p.path.localeCompare(l.path))};b(f(o,ki),u,{spacing:2,trailingNewline:!0});let d=Kt(e.snapshot);try{if(B(d)&&!C(e.snapshot)){let p=`${d}.corrupt-${process.pid}-${Date.now()}`;z(d,p),V(p,{recursive:!0,force:!0})}z(o,d)}catch(p){let l=C(e.snapshot);if(l)return l;throw p}return u}finally{V(o,{recursive:!0,force:!0})}}function Xt(e){let t=Kt(e.snapshot);_(e.targetCacheDir,{recursive:!0});let n=ie(f(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=xi(f(e.targetCacheDir,".shared-hydrate-")),Rc(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=O(t,c.path),d=O(r,c.path);he(u,d);let p=F(d);if(p.byteLength!==c.size||ye(p)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Zt(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&gr(O(r,c.path),e.manifest.scipProjectRoot,a);if(!Oi(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=yc(e.targetCacheDir,r),o=!0,Sc(r,e.targetCacheDir,i),We({tempOutputScip:f(r,"index.scip"),tempOutputDb:f(r,"index.db"),tempMetaPath:f(r,"meta.json"),outputScip:f(e.targetCacheDir,"index.scip"),outputDb:f(e.targetCacheDir,"index.db"),metaPath:f(e.targetCacheDir,"meta.json"),now:e.now});let s=G(f(e.targetCacheDir,"index.db"),f(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);ze(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&bc(e.targetCacheDir,i),a}finally{r&&V(r,{recursive:!0,force:!0}),n.release()}}async function Di(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??Date.now,o=i()+n,a=f(e.repositoryCacheDir,"locks"),s=f(a,`${e.generationId}.lock`);for(_(a,{recursive:!0});i()<=o;){if(C(e))return{kind:"generation-ready"};let c=zt();try{let u=vi(s,"wx");try{Ii(u,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
|
|
237
|
-
`)}finally{
|
|
238
|
-
`)}finally{Ri(i)}try{let o=Fi(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(qt(e),!0)}catch{return!1}finally{try{let o=JSON.parse(F(n,"utf8"));o.pid===process.pid&&o.token===r&&qt(n)}catch{}}}function hc(e,t,n){let r=Wn(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!B(f(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=f(e,"worktrees");_(i,{recursive:!0}),b(f(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),gc(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function yc(e,t){let n=f(t,".rollback"),r=new Map,i=new Map;_(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=f(e,s),u=B(c);r.set(s,u),u&&he(c,f(n,"stable",s))}for(let s of Qt){let c=f(e,s),u=B(c);if(u){let d=ic(c);if(!d.isDirectory()||d.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,u)}let o=f(e,Ue),a=B(o);return a&&ji(o,f(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function Sc(e,t,n){for(let r of Qt){let i=f(t,r);if(n.managedDirectories.get(r)){let a=f(n.root,"managed",r);_(Pi(a),{recursive:!0}),z(i,a)}let o=f(e,r);B(o)&&z(o,i)}}function bc(e,t){for(let i of Qt){let o=f(e,i),a=f(t.root,"managed",i);t.managedDirectories.get(i)?B(a)&&(V(o,{recursive:!0,force:!0}),z(a,o)):V(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=f(e,i);if(!o){V(a,{force:!0});continue}let s=`${a}.shared-restore-${zt()}`;he(f(t.root,"stable",i),s),V(a,{force:!0}),z(s,a)}let n=f(e,Ue);V(n,{recursive:!0,force:!0});let r=f(t.root,"sqlite-generations");t.generationStoreExisted&&B(r)&&z(r,n)}function ji(e,t){_(t,{recursive:!0});for(let n of oc(e,{withFileTypes:!0})){let r=f(e,n.name),i=f(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?ji(r,i):n.isFile()&&he(r,i)}}function Rc(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Oi(e,t,n,r=!0,i=!0){try{let o=fc(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return fe("source validation rejected metadata"),!1;let a=$e(e),s=G(f(e,"index.db"),f(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return fe(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new uc(f(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let u=Zt(t),p=(i?a.files.filter(l=>l.endsWith(".scip")):["index.scip"]).every(l=>{let m=wi(F(O(e,l))).metadata?.projectRoot;return m!==u&&fe(`source validation rejected SCIP root for ${l}: ${String(m)}`),m===u});return p||fe("source validation rejected SCIP project roots"),p}catch(o){return fe(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function fe(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Zt(e){try{return hi(ac(e)).href}catch{return hi(me(e)).href}}function ye(e){return bi("sha256").update(e).digest("hex")}import{existsSync as xc,readFileSync as vc,readdirSync as Ic,statSync as Pc}from"fs";import x from"path";var wc=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Se(e,t=[]){let n=x.resolve(e),r=t.flatMap(c=>Ec(n,c));if(r.length>0)return Ci(n,_i(r));let i=kc(n),o=_i(i),a=Dc(n,o)?[n,...o]:o,s=a.length>0?a:[n];return Ci(n,s)}function Ci(e,t){return[...new Set(t.map(n=>jc(e,n)))].sort((n,r)=>n.localeCompare(r))}function kc(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Ic(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=x.join(r,o.name);if(o.isDirectory()){!wc.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Tc(a)&&t.push(x.dirname(a))}}return t}function Ec(e,t){let n=t.trim();if(!n)return[];let r=x.resolve(e,n);if(!Z(e,r))return[];try{let i=Pc(r);if(i.isDirectory())return[r];if(i.isFile()&&Ai(x.basename(r)))return[x.dirname(r)]}catch{return[]}return[]}function Tc(e){if(!Ai(x.basename(e)))return!1;let t=Li(e);return t?x.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Ai(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function _i(e){let t=[...new Set(e.map(n=>x.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Oc(n,r)))}function Dc(e,t){if(t.length===0||t.some(r=>x.resolve(r)===e))return!1;let n=x.join(e,"tsconfig.json");return xc(n)&&Fc(n)}function Fc(e){let n=Li(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!x.extname(r))):!1}function Li(e){try{let t=JSON.parse(vc(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function jc(e,t){let n=x.relative(e,t);return n?n.split(x.sep).join("/"):"."}function Oc(e,t){let n=x.relative(e,t);return!!n&&!n.startsWith("..")&&!x.isAbsolute(n)}import{createHash as Zc}from"crypto";import{existsSync as tn,readFileSync as Yi,statSync as eu,writeFileSync as nn}from"fs";import{join as tu}from"path";import{readFileSync as Mi}from"fs";import{createRequire as Cc}from"module";import{dirname as _c,isAbsolute as cg,relative as ug,resolve as dg,sep as lg}from"path";var Ni=Cc(import.meta.url),Ac=1,$i="0.4.0";function en(){let e=Lc();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Lc(){try{let e=Ni.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(Mi(e,"utf8"));if(t.version!==$i)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${$i}`};let n=_c(e),r=Ni.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(Mi(r,"utf8"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:Mc(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Mc(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Ac}`}import{createHash as Nc}from"crypto";import{readFileSync as $c}from"fs";import{dirname as Gc,join as Ye}from"path";var Qe=2,Vc="typescript-index";function Gi(e){let t=Ye(e,Vc);return{rootDir:t,requestDir:Ye(t,"requests"),responseDir:Ye(t,"responses")}}function Vi(e){try{let t=JSON.parse($c(Ye(Gc(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Nc("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}import{randomUUID as Bc}from"crypto";import{existsSync as Uc,mkdirSync as Bi,readFileSync as Wc,rmSync as Ui}from"fs";import{resolve as Wi}from"path";var Jc=12e4,qc=5,Xe=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=jn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Xc(),this.runtime=n.runtime??Kc}request(t){let n=Fn(this.cacheDir),r=Gi(this.cacheDir),i=dt(n.statePath);if(!Ji(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),a=Wi(r.requestDir,`${o}.json`),s=Wi(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;Bi(r.requestDir,{recursive:!0}),Bi(r.responseDir,{recursive:!0}),b(a,{protocolVersion:Qe,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Uc(s))return Hc(Wc(s,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=dt(n.statePath);if(!Ji(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(qc)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{Ui(a,{force:!0}),Ui(s,{force:!0})}}};function Ji(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Dn,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Qe&&n.isProcessAlive(e.pid)&&(r||i)}function Hc(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==Qe||o.id!==t||o.ok===!0&&o.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"TypeScript index service request failed.");let a=zc(o.response,r),s=[...new Set(i)].sort(),c=a.fragments.map(u=>u.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(s))throw new Error("TypeScript index service omitted or added an affected document.");return a}function zc(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(Yc)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Qc(o.bytesBase64);return{relativePath:o.relativePath,bytes:a,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function Yc(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function Qc(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Xc(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Jc}var Kc={now:Date.now,randomId:Bc,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:T};function nu(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=ke(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(u=>u.kind!=="modified"||u.inputKind!=="source"||!lt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Fe(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=ru([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=qi(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=qi(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=zi(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=zi(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Hi(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Hi(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:s,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function ru(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function Qi(e){let t=Date.now();try{if(!tn(e.previousDbPath)||!tn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=en();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new W({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=Pe(o,{includeIgnored:!1}).filter(lt).sort(),s=we(o)}finally{o.close()}let c=performance.now()-n,u=nu({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Se(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:tn(tu(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=Vi(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let l=new Xe({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),m=performance.now()-n,g=eu(e.previousShardPath).size>=ei;n=performance.now();let I=g?null:Yi(e.previousShardPath),S=g?{completeIndexBytes:null,affectedIndexBytes:Nr(l.fragments)}:Ur({packageVersion:r.packageVersion,baseIndexBytes:I,fragments:l.fragments}),R=performance.now()-n;n=performance.now(),g?ti({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:l.fragments}):($r({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:I,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),Gr({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:l.fragments,documentIdentities:u.nextDocumentIdentities}));let y=performance.now()-n;n=performance.now(),S.completeIndexBytes&&nn(e.candidateShardPath,S.completeIndexBytes),nn(e.candidateAffectedScipPath,S.affectedIndexBytes);let w=performance.now()-n,k={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:l.cold,changedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:u.previousFragmentGeneration,nextFragmentGeneration:u.nextFragmentGeneration,manifest:u.manifest,plan:u.plan,projectFileCount:a.length,referenceFragmentsByFile:new Map(l.fragments.map(Ie=>[Ie.relativePath,Ie.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:m,serviceMs:l.durationMs,assemblyMs:R,fragmentStoreMs:y,writeMs:w}};return e.onStatus(`Incremental TypeScript index emitted ${k.affectedFiles.length} affected document(s) in ${(k.durationMs/1e3).toFixed(3)}s (${k.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${m.toFixed(0)}ms, assembly ${R.toFixed(0)}ms, fragments ${y.toFixed(0)}ms, write ${w.toFixed(0)}ms).`),k}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function Xi(e){let t=en();if(!t.available)throw new Error(t.reason);let n=ni({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Yi(e.baseShardPath),packageVersion:t.packageVersion});nn(e.candidateShardPath,n)}function qi(e,t,n){let r=e.files.filter(i=>wn(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return rn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Hi(e,t){return rn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function zi(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=On({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let u=a.identityFor(c,"typescript-scip-document-v1");if(u.key){s.set(c,u.key);continue}if(o.has(c))return null;s.set(c,rn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function rn(e){return Zc("sha256").update(e).digest("hex")}import{execFile as iu}from"child_process";import{existsSync as Ke,renameSync as an,rmSync as sn,statSync as ou}from"fs";import{cpus as au}from"os";import{join as Ki}from"path";function su(e,t,n){if(!e.defaultOutputPath)return;let r=Ki(t,e.defaultOutputPath);n!==r&&Ke(r)&&an(r,n)}function cu(e,t,n){if(!e.defaultOutputPath)return null;let r=Ki(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return sn(i,{force:!0}),Ke(r)?(an(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function uu(e){e&&(sn(e.defaultOutputPath,{force:!0}),e.backupPath&&Ke(e.backupPath)&&an(e.backupPath,e.defaultOutputPath))}function du(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,au().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Zi(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=du(o.length,r),c=await pu(o,s,u=>on(u,t,n));if(s>1){let u=new Map;for(let d of c.filter(p=>p.skipped)){let p=o.find(l=>l.id===d.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),u.set(p.id,await on(p,t,n)))}a.push(...c.map(d=>u.get(d.id)??d))}else a.push(...c);for(let u of i)a.push(await on(u,t,n));return a.sort((u,d)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===d.id))}async function on(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),sn(e.scipPath,{force:!0});let r=cu(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let s=Pn(e.binary,e.args);await lu(s.binary,s.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),su(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),u=`${e.resolvedBinary} indexer failed: ${c.split(`
|
|
239
|
-
`)[0]}`,d=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{
|
|
233
|
+
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,p]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let l of p){let m=JSON.stringify([d,l]),g=c.get(l.relative_path)??[];g.push(m),c.set(l.relative_path,g)}let u=new Map;for(let[d,p]of[...c].sort(([l],[m])=>l.localeCompare(m))){let l=ts("sha256");for(let m of p.sort())l.update(m).update(`
|
|
234
|
+
`);u.set(d,l.digest("hex"))}return u}function N(e,t){return e.prepare(t).get().value}import{readFileSync as Ss,writeFileSync as bs}from"fs";function $(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function Er(e){let t=e.readFingerprint(),n=Rs(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return xs(e.cachePath,e.readFingerprint(),r),r}function Rs(e,t){try{let n=JSON.parse(Ss(e,"utf-8"));return kr(n.fingerprint)===kr(t)?{result:n.result}:null}catch{return null}}function xs(e,t,n){bs(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
235
|
+
`)}function kr(e){return JSON.stringify(e)}import{createHash as vs}from"crypto";import{existsSync as jt,readFileSync as Is,readdirSync as Ps}from"fs";import{dirname as Ct,join as Ae,relative as ws,resolve as At,sep as Tr}from"path";function Dr(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=Cr(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Fr(e,t){let n=new Map;for(let i of e){let o=t[i]?.packageName;o&&n.set(o,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let o=t[i],a=r.get(i);if(!o||o.parseFailed){for(let s of e)s!==i&&a.add(s);continue}for(let s of o.dependencyNames){let c=n.get(s);c&&c!==i&&a.add(c)}for(let s of[...o.pathsTargets,...o.referencesPaths]){let c=Cr(s,e);c&&c!==i&&a.add(c)}}return ks(e,r)}function Or(e,t,n){let r={};for(let i of e){let o=new Map;for(let a of t.files[i]??[])o.set(a.path,a);for(let a of n[i]??[])for(let s of t.files[a]??[])o.set(s.path,s);for(let a of t.shared)o.set(a.path,a);r[i]={files:[...o.values()].sort((a,s)=>a.path.localeCompare(s.path))}}return r}function _t(e){if(e===".")return"root";let t=vs("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function jr(e,t){let n=At(e),r={};for(let i of t)r[i]=Es(n,i);return r}function Cr(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function ks(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let a=o.pop();if(!(a===r||i.has(a))){i.add(a);for(let s of t.get(a)??[])s!==r&&!i.has(s)&&o.push(s)}}n[r]=[...i].sort((a,s)=>a.localeCompare(s))}return n}function Es(e,t){let n=t==="."?e:Ae(e,t),r=Ts(n),i=Ds(n),o=i?Fs(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:r.failed||o.failed}}function Ts(e){let t=Ae(e,"package.json");if(!jt(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Lt(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let o of["dependencies","devDependencies","peerDependencies"]){let a=n.value[o];if(a&&typeof a=="object"&&!Array.isArray(a))for(let s of Object.keys(a))i.add(s)}return{name:r,dependencyNames:[...i],failed:!1}}function Ds(e){let t=Ae(e,"tsconfig.json");if(jt(t))return t;let n;try{n=Ps(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Ae(e,n[0]):void 0}function Fs(e,t){let n=Lt(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Os(n.value,e,t),i=Ar(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Os(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Ct(t),o=new Set;for(let a of r){if(!a||typeof a!="object")continue;let s=a.path;if(typeof s!="string"||s.trim()==="")continue;let c=_r(s,i,n);c&&o.add(c)}return[...o]}function Ar(e,t,n,r){let i=js(t);if(i)return{pathsTargets:Cs(i,Ct(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=As(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=Lt(o);return a.ok?Ar(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function js(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Cs(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let o of i){if(typeof o!="string")continue;let a=_r(o,t,n);a&&r.add(a)}return[...r]}function As(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=At(Ct(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Tr).includes("node_modules")&&Z(n,i)&&jt(i))return i}function _r(e,t,n){let r=e.replace(/\/?\*+$/,""),i=At(t,r===""?".":r);if(!Z(n,i))return;let a=ws(n,i).split(Tr).join("/");return a===""?".":a}function _s(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
|
|
236
|
+
`;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function Lt(e){try{let t=Is(e,"utf-8"),n=JSON.parse(_s(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as Ii,randomUUID as Qt}from"crypto";import{closeSync as Pi,constants as gc,copyFileSync as bi,existsSync as U,lstatSync as fc,mkdirSync as A,mkdtempSync as wi,openSync as ki,readdirSync as mc,readFileSync as F,realpathSync as hc,renameSync as z,rmSync as B,statSync as yc,unlinkSync as Yt,writeFileSync as Ei}from"fs";import{dirname as Ti,join as f,resolve as me}from"path";import{setTimeout as Sc}from"timers/promises";import{pathToFileURL as Ri}from"url";import{deserializeSCIP as Di}from"@c4312/scip";import bc from"better-sqlite3";import{createRequire as Ls}from"module";var Ms=Ls(import.meta.url),Lr=Ns().version;function Ns(){for(let e of["../package.json","../../package.json"])try{return Ms(e)}catch{}return{version:"0.0.0"}}import{lstatSync as Zs,readdirSync as ec}from"fs";import{join as tc,relative as nc,resolve as Ht,sep as rc}from"path";import{createHash as $s}from"crypto";import{existsSync as Nt,mkdirSync as Gs,readFileSync as _e,readdirSync as Ip,renameSync as Vs,rmSync as Pp,writeFileSync as Bs}from"fs";import{join as X}from"path";import{create as Nr,fromBinary as $r,toBinary as Us}from"@bufbuild/protobuf";import{deserializeSCIP as Le,DocumentSchema as $t,IndexSchema as Gr,serializeSCIP as Vr}from"@c4312/scip";var Me=1,ae="typescript-scip-fragments";function Br(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let a=J(o.relativePath);if(t.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(t.add(a),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${a}`);let s=$r($t,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Vr(Nr(Gr,{documents:n,externalSymbols:[]})),i=Le(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Ne(e){let t=X(e,ae);return{rootDir:t,blobDir:X(t,"blobs"),generationDir:X(t,"generations")}}function Ws(e){let t=Le(e.indexBytes);ei(t.metadata,ti(e)),Zr(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=J(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=Us($t,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?q(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:q(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Yr(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Xr(e,r);return Qr(e.cacheDir,i),i}function Ur(e){let t=Ne(e.cacheDir);if(!Nt(Gt(t,e.generationIdentity)))return Ws(e);let n=Hr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function Wr(e){let t=Hr({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=J(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(r.add(a),!n.has(a))throw new Error(`TypeScript fragment replacement has no prior document: ${a}`);let s=e.documentIdentities.get(a);if(!s)throw new Error(`missing TypeScript document identity: ${a}`);o.bytes===null?n.delete(a):n.set(a,Yr(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Xr(e,[...n.values()]);return Qr(e.cacheDir,i),i}function Hr(e){let t=Ne(e.cacheDir),n=Gt(t,e.generationIdentity),r;try{r=Kr(_e(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let a=X(t.blobDir,`${o.blobHash}.scipdoc`),s=_e(a);if(s.byteLength!==o.byteLength||q(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Jr(e){let t=zr(e);return Mt(t.baseIndex,t.completeDocuments,"assembled")}function qr(e){let t=zr(e);return Hs(t.deletedAffectedPaths),{completeIndexBytes:Mt(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Mt(t.baseIndex,t.affectedDocuments,"affected")}}function zr(e){let t=Le(e.baseIndexBytes);ei(t.metadata,ti(e)),Zr(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=J(s.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,s)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],a=[];for(let s of t.documents){let c=J(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let u=n.get(c);if(!u){i.push(s);continue}if(n.delete(c),u.bytes===null){a.push(c);continue}let d=$r($t,u.bytes);if(d.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${d.relativePath}`);i.push(d),o.push(d)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function Mt(e,t,n){let r=Vr(Nr(Gr,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Le(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Hs(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Yr(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=J(t.relativePath),i=Buffer.from(t.bytes),o=q(i),a=Ne(e);Gs(a.blobDir,{recursive:!0});let s=X(a.blobDir,`${o}.scipdoc`);if(Nt(s)){let c=_e(s);if(c.byteLength!==i.byteLength||q(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;Bs(c,i),Vs(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Xr(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:Me,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Qr(e,t){let n=Ne(e),r=Gt(n,t.generationIdentity);if(Nt(r)){let i=Kr(_e(r,"utf8"));if(Mr(i)!==Mr(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}R(r,t,{spacing:2,trailingNewline:!0})}function Mr(e){return q(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Kr(e){let t=JSON.parse(e);if(t.version!==Me||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(J(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Gt(e,t){return X(e.generationDir,Js(t))}function Js(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${q(e)}.json`}function Zr(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function ei(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function ti(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function J(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function q(e){return $s("sha256").update(e).digest("hex")}import{createHash as qs}from"crypto";import{existsSync as se,mkdirSync as zs,readFileSync as ue,readdirSync as Vt,renameSync as Ys,rmSync as ni,writeFileSync as Xs}from"fs";import{join as D}from"path";var $e=1,ii=64*1024*1024,de="typescript-scip-overlays";function oi(e){let t=ci(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=Wt(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,Qs(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:$e,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,a)=>o.relativePath.localeCompare(a.relativePath))};return Ks(e.cacheDir,i),i}function ai(e){let t=ci(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=ue(D(le(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||ce(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return Jr({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function si(e,t){let n=le(e),r=D(n,"generations");if(!se(r))return;let i=new Set(t.map(Ut)),o=new Set;for(let s of Vt(r).filter(c=>i.has(c))){let c=Bt(ue(D(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of Vt(r))i.has(s)||ni(D(r,s),{force:!0});let a=D(n,"blobs");if(se(a))for(let s of Vt(a))o.has(s)||ni(D(a,s),{force:!0})}function ci(e,t){let n=D(le(e),"generations",Ut(t));if(!se(n))return null;let r=Bt(ue(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Qs(e,t){let n=Wt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=ce(r),o=D(le(e),"blobs");zs(o,{recursive:!0});let a=D(o,`${i}.scipdoc`);if(se(a)){let s=ue(a);if(s.byteLength!==r.byteLength||ce(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Xs(s,r),Ys(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Ks(e,t){let n=D(le(e),"generations",Ut(t.generationIdentity));if(se(n)){let r=Bt(ue(n,"utf8"));if(ri(r)!==ri(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}R(n,t,{spacing:2,trailingNewline:!0})}function Bt(e){let t=JSON.parse(e);if(t.version!==$e||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(Wt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function le(e){return D(e,de)}function Ut(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${ce(e)}.json`}function ri(e){return ce(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Wt(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function ce(e){return qs("sha256").update(e).digest("hex")}var pe=1,Jt="language-indexes",ui=["index.db","index.scip","meta.json"],di=[Jt,ae,de];function Ge(e){let t=[];for(let n of ui)ic(e,n),t.push(n);for(let n of di)li(e,n,t);return{version:pe,files:t.sort()}}function Ve(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!ui.includes(e)&&!di.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function j(e,t){let n=Ve(t),r=Ht(e),i=Ht(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${rc}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function li(e,t,n){let r=tc(e,t),i;try{i=ec(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let a=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${a}`);o.isDirectory()?li(e,a,n):o.isFile()&&n.push(Ve(a))}}function ic(e,t){let n=j(e,t),r;try{r=Zs(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(nc(Ht(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as oc}from"crypto";import{copyFileSync as pi,existsSync as G,linkSync as ac,mkdirSync as gi,readFileSync as hi,readdirSync as fi,renameSync as zt,rmSync as Ue,statSync as sc}from"fs";import{basename as Be,dirname as ge,join as k,relative as mi}from"path";var Q=1,We=".scipquery-generations";function He(e){let t=Je(e.outputDb),n=cc(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||qt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),qt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),qt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=qe(e.metaPath,e.outputDb),i={version:Q,currentGeneration:r,...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:(e.now??(()=>new Date))().toISOString()};return R(k(t,"state.json"),i,{spacing:2,trailingNewline:!0}),{currentGeneration:r,...n?{previousGeneration:n}:{}}}function yi(e){try{let t=JSON.parse(hi(k(Je(e),"state.json"),"utf8"));return t.version!==Q||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!lc(t.previousGeneration)||!pc(t.publication)?null:t}catch{return null}}function Si(e,t,n=()=>new Date){if(!G(e)||!G(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=yi(e),i={version:Q,currentGeneration:qe(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return R(k(Je(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function V(e,t=k(ge(e),"meta.json")){let n=k(Je(e),"state.json");if(!G(n))return{state:"legacy",statePath:n};let r=yi(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=qe(t,e),o=r.currentGeneration===i,a=r.previousGeneration?G(k(ge(e),r.previousGeneration.databasePath)):!0;return!o||!a?{state:"drifted",statePath:n,currentMatches:o,recoveryExists:a,generation:r,reason:o?"retained recovery database is missing":"stable database or metadata no longer matches the published generation"}:{state:"current",statePath:n,currentMatches:o,recoveryExists:a,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function Je(e){return k(ge(e),We)}function cc(e,t){if(!G(e.outputDb))return;let n=qe(e.metaPath,e.outputDb),r=k(t,n),i=k(r,Be(e.outputDb)),o=G(e.metaPath)?k(r,Be(e.metaPath)):void 0;if(!G(i)){let a=`${r}.${process.pid}.${Date.now()}.tmp`;Ue(a,{recursive:!0,force:!0}),gi(a,{recursive:!0});let s=k(a,Be(e.outputDb));try{ac(e.outputDb,s)}catch{pi(e.outputDb,s)}o&&pi(e.metaPath,k(a,Be(e.metaPath))),gi(t,{recursive:!0}),zt(a,r)}return uc(t,n),{generationIdentity:n,databasePath:mi(ge(e.outputDb),i),...o?{metadataPath:mi(ge(e.outputDb),o)}:{}}}function uc(e,t){for(let n of fi(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||Ue(k(e,n.name),{recursive:!0,force:!0});for(let n of fi(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&Ue(k(e,n.name),{recursive:!0,force:!0})}function qe(e,t){let n=oc("sha256").update(`sqlite-generation-v${Q}\0`);G(e)&&n.update(dc(hi(e,"utf8")));let r=sc(t);return n.update(`\0${r.size}`),n.digest("hex")}function dc(e){try{let t=JSON.parse(e);if((t.version===2||t.version===3)&&t.status==="complete"&&typeof t.updatedAt=="string"&&t.fingerprint!==void 0)return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion})}catch{}return e}function qt(e,t){Ue(`${t}.tmp-replace`,{force:!0}),zt(e,`${t}.tmp-replace`),zt(`${t}.tmp-replace`,t)}function lc(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function pc(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,n=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(r=>r!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&n.every(r=>typeof r=="number"&&Number.isFinite(r)&&r>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}var Kt=1,xi="SCIP_QUERY_SHARED_CACHE",Xt=JSON.stringify({cliVersion:Lr,artifactCatalogVersion:pe,sqliteGenerationStoreVersion:Q,typescriptFragmentStoreVersion:Me,typescriptOverlayStoreVersion:$e}),Fi="manifest.json",Rc="shared-cache.json",Zt=[Jt,ae,de];function ze(e,t){if(!e.clean||!e.treeOid)return;let n=ye(JSON.stringify({version:Kt,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Xt}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Xt,generationId:n,repositoryCacheDir:$n(e.repositoryId)}}function Oi(e,t,n){if(process.env[xi]==="0")return`${xi}=0`;if(!Gn(n))return"explicit cache or database override";if(me(t)!==me(f(Nn(e),"index.db")))return"index database is outside the managed worktree cache"}function C(e,t=!0){let n=tn(e),r;try{r=vc(F(f(n,Fi),"utf8"))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=j(n,i.path),a=yc(o);if(!a.isFile()||a.size!==i.size||ye(F(o))!==i.sha256)return null}}catch{return null}return r}function ji(e){let t=C(e.snapshot);if(t)return t;if(!Li(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=vi(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=Ge(e.sourceCacheDir),i=f(e.snapshot.repositoryCacheDir,"generations");A(i,{recursive:!0});let o=wi(f(i,`.tmp-${process.pid}-`));try{let a=[];for(let p of r.files){let l=j(e.sourceCacheDir,p),m=j(o,p);he(l,m);let g=F(m);a.push({path:p,size:g.byteLength,sha256:ye(g)})}let s=Di(F(f(o,"index.scip"))).metadata?.projectRoot;if(!s)throw new Error("shared SCIP generation has no project root metadata");let c=nn(e.sourceProjectRoot);if(s!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(vi(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Kt,artifactCatalogVersion:pe,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:s,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:a.sort((p,l)=>p.path.localeCompare(l.path))};R(f(o,Fi),u,{spacing:2,trailingNewline:!0});let d=tn(e.snapshot);try{if(U(d)&&!C(e.snapshot)){let p=`${d}.corrupt-${process.pid}-${Date.now()}`;z(d,p),B(p,{recursive:!0,force:!0})}z(o,d)}catch(p){let l=C(e.snapshot);if(l)return l;throw p}return u}finally{B(o,{recursive:!0,force:!0})}}function en(e){let t=tn(e.snapshot);A(e.targetCacheDir,{recursive:!0});let n=ie(f(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=wi(f(e.targetCacheDir,".shared-hydrate-")),Fc(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=j(t,c.path),d=j(r,c.path);he(u,d);let p=F(d);if(p.byteLength!==c.size||ye(p)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=nn(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&yr(j(r,c.path),e.manifest.scipProjectRoot,a);if(!Li(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=Ec(e.targetCacheDir,r),o=!0,Tc(r,e.targetCacheDir,i),He({tempOutputScip:f(r,"index.scip"),tempOutputDb:f(r,"index.db"),tempMetaPath:f(r,"meta.json"),outputScip:f(e.targetCacheDir,"index.scip"),outputDb:f(e.targetCacheDir,"index.db"),metaPath:f(e.targetCacheDir,"meta.json"),now:e.now});let s=V(f(e.targetCacheDir,"index.db"),f(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);Ye(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&Dc(e.targetCacheDir,i),a}finally{r&&B(r,{recursive:!0,force:!0}),n.release()}}async function Ci(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??Date.now,o=i()+n,a=f(e.repositoryCacheDir,"locks"),s=f(a,`${e.generationId}.lock`);for(A(a,{recursive:!0});i()<=o;){if(C(e))return{kind:"generation-ready"};let c=Qt();try{let u=ki(s,"wx");try{Ei(u,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
|
|
237
|
+
`)}finally{Pi(u)}return{kind:"owner",release:()=>{try{let d=JSON.parse(F(s,"utf8"));d.pid===process.pid&&d.token===c&&Yt(s)}catch{}}}}catch(u){if(u.code!=="EEXIST")return{kind:"timeout"};let d=Ai(s);if(d&&(d.pid===void 0||!T(d.pid))){wc(s,d);continue}await Sc(r)}}return C(e)?{kind:"generation-ready"}:{kind:"timeout"}}function Ye(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:xc(i)};return kc(e.repositoryCacheDir,o,!0),o}function xc(e){return ye(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:me(e.projectRoot),localCacheDir:me(e.localCacheDir)}))}function vc(e){let t=JSON.parse(e);if(t.version!==Kt||t.artifactCatalogVersion!==pe||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==Xt||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(Ve(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function he(e,t){A(Ti(t),{recursive:!0});try{bi(e,t,gc.COPYFILE_FICLONE)}catch{bi(e,t)}}function Ic(e,t,n){A(e,{recursive:!0}),R(f(e,Rc),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function vi(e){try{let t=Ge(e),n=Ii("sha256");for(let r of t.files){let i=F(j(e,r));n.update(r).update("\0").update(String(i.byteLength)).update("\0").update(i).update("\0")}return n.digest("hex")}catch{return null}}function Pc(e){try{return JSON.parse(F(f(e,"meta.json"),"utf8"))}catch{return}}function tn(e){return f(e.repositoryCacheDir,"generations",e.generationId)}function Ai(e){try{let t=F(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 wc(e,t){let n=`${e}.reclaim`,r=Qt(),i;try{i=ki(n,"wx")}catch{return!1}try{Ei(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
|
|
238
|
+
`)}finally{Pi(i)}try{let o=Ai(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Yt(e),!0)}catch{return!1}finally{try{let o=JSON.parse(F(n,"utf8"));o.pid===process.pid&&o.token===r&&Yt(n)}catch{}}}function kc(e,t,n){let r=qn(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!U(f(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=f(e,"worktrees");A(i,{recursive:!0}),R(f(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),Ic(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function Ec(e,t){let n=f(t,".rollback"),r=new Map,i=new Map;A(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=f(e,s),u=U(c);r.set(s,u),u&&he(c,f(n,"stable",s))}for(let s of Zt){let c=f(e,s),u=U(c);if(u){let d=fc(c);if(!d.isDirectory()||d.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,u)}let o=f(e,We),a=U(o);return a&&_i(o,f(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function Tc(e,t,n){for(let r of Zt){let i=f(t,r);if(n.managedDirectories.get(r)){let a=f(n.root,"managed",r);A(Ti(a),{recursive:!0}),z(i,a)}let o=f(e,r);U(o)&&z(o,i)}}function Dc(e,t){for(let i of Zt){let o=f(e,i),a=f(t.root,"managed",i);t.managedDirectories.get(i)?U(a)&&(B(o,{recursive:!0,force:!0}),z(a,o)):B(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=f(e,i);if(!o){B(a,{force:!0});continue}let s=`${a}.shared-restore-${Qt()}`;he(f(t.root,"stable",i),s),B(a,{force:!0}),z(s,a)}let n=f(e,We);B(n,{recursive:!0,force:!0});let r=f(t.root,"sqlite-generations");t.generationStoreExisted&&U(r)&&z(r,n)}function _i(e,t){A(t,{recursive:!0});for(let n of mc(e,{withFileTypes:!0})){let r=f(e,n.name),i=f(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?_i(r,i):n.isFile()&&he(r,i)}}function Fc(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Li(e,t,n,r=!0,i=!0){try{let o=Pc(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return fe("source validation rejected metadata"),!1;let a=Ge(e),s=V(f(e,"index.db"),f(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return fe(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new bc(f(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let u=nn(t),p=(i?a.files.filter(l=>l.endsWith(".scip")):["index.scip"]).every(l=>{let m=Di(F(j(e,l))).metadata?.projectRoot;return m!==u&&fe(`source validation rejected SCIP root for ${l}: ${String(m)}`),m===u});return p||fe("source validation rejected SCIP project roots"),p}catch(o){return fe(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function fe(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function nn(e){try{return Ri(hc(e)).href}catch{return Ri(me(e)).href}}function ye(e){return Ii("sha256").update(e).digest("hex")}import{existsSync as Oc,readFileSync as jc,readdirSync as Cc,statSync as Ac}from"fs";import v from"path";var _c=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Se(e,t=[]){let n=v.resolve(e),r=t.flatMap(c=>Mc(n,c));if(r.length>0)return Mi(n,Ni(r));let i=Lc(n),o=Ni(i),a=$c(n,o)?[n,...o]:o,s=a.length>0?a:[n];return Mi(n,s)}function Mi(e,t){return[...new Set(t.map(n=>Vc(e,n)))].sort((n,r)=>n.localeCompare(r))}function Lc(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Cc(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=v.join(r,o.name);if(o.isDirectory()){!_c.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Nc(a)&&t.push(v.dirname(a))}}return t}function Mc(e,t){let n=t.trim();if(!n)return[];let r=v.resolve(e,n);if(!Z(e,r))return[];try{let i=Ac(r);if(i.isDirectory())return[r];if(i.isFile()&&$i(v.basename(r)))return[v.dirname(r)]}catch{return[]}return[]}function Nc(e){if(!$i(v.basename(e)))return!1;let t=Gi(e);return t?v.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function $i(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Ni(e){let t=[...new Set(e.map(n=>v.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Bc(n,r)))}function $c(e,t){if(t.length===0||t.some(r=>v.resolve(r)===e))return!1;let n=v.join(e,"tsconfig.json");return Oc(n)&&Gc(n)}function Gc(e){let n=Gi(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!v.extname(r))):!1}function Gi(e){try{let t=JSON.parse(jc(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Vc(e,t){let n=v.relative(e,t);return n?n.split(v.sep).join("/"):"."}function Bc(e,t){let n=v.relative(e,t);return!!n&&!n.startsWith("..")&&!v.isAbsolute(n)}import{createHash as uu}from"crypto";import{existsSync as on,readFileSync as Zi,statSync as du,writeFileSync as an}from"fs";import{join as lu}from"path";import{readFileSync as Vi}from"fs";import{createRequire as Uc}from"module";import{dirname as Wc,isAbsolute as yg,relative as Sg,resolve as bg,sep as Rg}from"path";var Bi=Uc(import.meta.url),Hc=1,Ui="0.4.0";function rn(){let e=Jc();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Jc(){try{let e=Bi.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(Vi(e,"utf8"));if(t.version!==Ui)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${Ui}`};let n=Wc(e),r=Bi.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(Vi(r,"utf8"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:qc(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function qc(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Hc}`}import{createHash as zc}from"crypto";import{readFileSync as Yc}from"fs";import{dirname as Xc,join as Xe}from"path";var Qe=2,Qc="typescript-index";function Wi(e){let t=Xe(e,Qc);return{rootDir:t,requestDir:Xe(t,"requests"),responseDir:Xe(t,"responses")}}function Hi(e){try{let t=JSON.parse(Yc(Xe(Xc(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:zc("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}import{randomUUID as Kc}from"crypto";import{existsSync as Zc,mkdirSync as Ji,readFileSync as eu,rmSync as qi}from"fs";import{resolve as zi}from"path";var tu=12e4,nu=5,Ke=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=Cn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??su(),this.runtime=n.runtime??cu}request(t){let n=jn(this.cacheDir),r=Wi(this.cacheDir),i=lt(n.statePath);if(!Yi(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),a=zi(r.requestDir,`${o}.json`),s=zi(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;Ji(r.requestDir,{recursive:!0}),Ji(r.responseDir,{recursive:!0}),R(a,{protocolVersion:Qe,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Zc(s))return ru(eu(s,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=lt(n.statePath);if(!Yi(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(nu)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{qi(a,{force:!0}),qi(s,{force:!0})}}};function Yi(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=On,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Qe&&n.isProcessAlive(e.pid)&&(r||i)}function ru(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==Qe||o.id!==t||o.ok===!0&&o.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"TypeScript index service request failed.");let a=iu(o.response,r),s=[...new Set(i)].sort(),c=a.fragments.map(u=>u.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(s))throw new Error("TypeScript index service omitted or added an affected document.");return a}function iu(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(ou)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:au(o.bytesBase64);return{relativePath:o.relativePath,bytes:a,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function ou(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function au(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function su(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:tu}var cu={now:Date.now,randomId:Kc,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:T};function pu(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=Ee(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(u=>u.kind!=="modified"||u.inputKind!=="source"||!pt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Oe(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=gu([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Xi(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=Xi(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=Ki(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=Ki(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Qi(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Qi(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:s,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function gu(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function eo(e){let t=Date.now();try{if(!on(e.previousDbPath)||!on(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=rn();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new W({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=we(o,{includeIgnored:!1}).filter(pt).sort(),s=ke(o)}finally{o.close()}let c=performance.now()-n,u=pu({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Se(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:on(lu(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=Hi(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let l=new Ke({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),m=performance.now()-n,g=du(e.previousShardPath).size>=ii;n=performance.now();let S=g?null:Zi(e.previousShardPath),b=g?{completeIndexBytes:null,affectedIndexBytes:Br(l.fragments)}:qr({packageVersion:r.packageVersion,baseIndexBytes:S,fragments:l.fragments}),P=performance.now()-n;n=performance.now(),g?oi({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:l.fragments}):(Ur({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:S,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),Wr({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:l.fragments,documentIdentities:u.nextDocumentIdentities}));let y=performance.now()-n;n=performance.now(),b.completeIndexBytes&&an(e.candidateShardPath,b.completeIndexBytes),an(e.candidateAffectedScipPath,b.affectedIndexBytes);let I=performance.now()-n,w={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:l.cold,changedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:u.previousFragmentGeneration,nextFragmentGeneration:u.nextFragmentGeneration,manifest:u.manifest,plan:u.plan,projectFileCount:a.length,referenceFragmentsByFile:new Map(l.fragments.map(Pe=>[Pe.relativePath,Pe.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:m,serviceMs:l.durationMs,assemblyMs:P,fragmentStoreMs:y,writeMs:I}};return e.onStatus(`Incremental TypeScript index emitted ${w.affectedFiles.length} affected document(s) in ${(w.durationMs/1e3).toFixed(3)}s (${w.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${m.toFixed(0)}ms, assembly ${P.toFixed(0)}ms, fragments ${y.toFixed(0)}ms, write ${I.toFixed(0)}ms).`),w}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function to(e){let t=rn();if(!t.available)throw new Error(t.reason);let n=ai({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Zi(e.baseShardPath),packageVersion:t.packageVersion});an(e.candidateShardPath,n)}function Xi(e,t,n){let r=e.files.filter(i=>En(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return sn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Qi(e,t){return sn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function Ki(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=An({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let u=a.identityFor(c,"typescript-scip-document-v1");if(u.key){s.set(c,u.key);continue}if(o.has(c))return null;s.set(c,sn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function sn(e){return uu("sha256").update(e).digest("hex")}import{execFile as fu}from"child_process";import{existsSync as Ze,renameSync as un,rmSync as dn,statSync as mu}from"fs";import{cpus as hu}from"os";import{join as no}from"path";function yu(e,t,n){if(!e.defaultOutputPath)return;let r=no(t,e.defaultOutputPath);n!==r&&Ze(r)&&un(r,n)}function Su(e,t,n){if(!e.defaultOutputPath)return null;let r=no(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return dn(i,{force:!0}),Ze(r)?(un(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function bu(e){e&&(dn(e.defaultOutputPath,{force:!0}),e.backupPath&&Ze(e.backupPath)&&un(e.backupPath,e.defaultOutputPath))}function Ru(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,hu().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function ro(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=Ru(o.length,r),c=await vu(o,s,u=>cn(u,t,n));if(s>1){let u=new Map;for(let d of c.filter(p=>p.skipped)){let p=o.find(l=>l.id===d.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),u.set(p.id,await cn(p,t,n)))}a.push(...c.map(d=>u.get(d.id)??d))}else a.push(...c);for(let u of i)a.push(await cn(u,t,n));return a.sort((u,d)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===d.id))}async function cn(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),dn(e.scipPath,{force:!0});let r=Su(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let s=kn(e.binary,e.args);await xu(s.binary,s.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),yu(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),u=`${e.resolvedBinary} indexer failed: ${c.split(`
|
|
239
|
+
`)[0]}`,d=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{bu(r)}if(!Ze(e.scipPath)){let s=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:c}}}let a;try{a=mu(e.scipPath).size}catch{a=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,outputBytes:a}}function xu(e,t,n){return new Promise((r,i)=>{fu(e,[...t],n,o=>{o?i(o):r()})})}async function vu(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),a=Array.from({length:o},async()=>{for(;i<e.length;){let s=i++;r[s]=await n(e[s])}});return await Promise.all(a),r}import{execFileSync as Iu}from"child_process";import{platform as Pu}from"os";function ln(e,t){let n=e.installMethods,r=ne(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(st(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Iu(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Pu()==="win32"});let o=re(e);if(o){let a=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${r} via ${i.label}${a}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(o){let a=o instanceof Error?o.message:String(o);t(`${i.label} install failed: ${a}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}import od from"better-sqlite3";import{existsSync as ad}from"fs";import{dirname as sd,join as cd,resolve as ud}from"path";import{readFileSync as ku,rmSync as Eu,statSync as Tu,mkdtempSync as Du}from"fs";import{tmpdir as Fu}from"os";import{join as pn}from"path";import{Worker as Ou}from"worker_threads";function wu(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function K(){return{skippedReferences:0,skippedReferenceReasons:wu(),skippedReferenceSamples:[]}}function et(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}function io(e){return e.length>=8&&ao(e.length)>1}function oo(e){let t=ao(e.vueFiles.length),n=Cu(e.vueFiles),r=_u(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=Du(pn(Fu(),"scip-query-vue-workers-")),a=new SharedArrayBuffer(4),s=new Int32Array(a),c=ju(),u=Date.now();try{for(let l=0;l<r.length;l++)new Ou(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[l],resultPath:pn(o,`${l}.json`),sharedBuffer:a}});for(;Atomics.load(s,0)<r.length;){if(Date.now()-u>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(s,0,Atomics.load(s,0),100)}let d=r.map((l,m)=>{let g=JSON.parse(ku(pn(o,`${m}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),p={occurrences:d.flatMap(l=>l.occurrences),...K()};for(let l of d)et(p,l);return p}finally{Eu(o,{recursive:!0,force:!0})}}function ao(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function ju(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function Cu(e){let t=Au(),n=[];for(let r of e){let i=so(r),o=Math.max(1,Math.ceil(i/t));for(let a=0;a<o;a++)n.push({fileName:r,startOffset:Math.floor(i*a/o),endOffset:a===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(a+1)/o),countFileSkip:a===0})}return n}function Au(){return Number.POSITIVE_INFINITY}function _u(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Lu(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((a,s)=>s.weight<a.weight?s:a);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function Lu(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,so(e.fileName)-e.startOffset)}function so(e){try{return Tu(e).size}catch{return 1}}import{createRequire as Mu}from"module";import{existsSync as Nu,readFileSync as fn}from"fs";import{dirname as co,extname as $u,join as uo,relative as Gu,resolve as Vu}from"path";import{pathToFileURL as Bu}from"url";function Uu(e){e.transaction(()=>{e.prepare(`
|
|
240
240
|
DELETE FROM mentions
|
|
241
241
|
WHERE chunk_id IN (
|
|
242
242
|
SELECT c.id
|
|
@@ -251,12 +251,12 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
251
251
|
FROM documents
|
|
252
252
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
253
253
|
)
|
|
254
|
-
`).run()})()}function
|
|
254
|
+
`).run()})()}function lo(e,t){return e.prepare(`
|
|
255
255
|
SELECT relative_path AS relativePath
|
|
256
256
|
FROM documents
|
|
257
257
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
258
258
|
ORDER BY relative_path
|
|
259
|
-
`).all().map(r=>
|
|
259
|
+
`).all().map(r=>Vu(t,r.relativePath))}function po(e,t){let{vueCore:n,ts:r,volarTs:i}=Wu(e),{parsed:o,vueOptions:a}=Hu(n,r,t),s=co(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),u=Ju(n,r,c),d=qu(s,o),{languageServiceHost:p}=i.createLanguageServiceHost(r,r.sys,u,m=>m,d),l=r.createLanguageService(p);return{ts:r,language:u,languageService:l,fileNames:o.fileNames,configDir:s}}function Wu(e){let t=Mu(Bu(uo(e,"package.json")).href);return{vueCore:gn(t,"@vue/language-core",e),ts:gn(t,"typescript",e),volarTs:gn(t,"@volar/typescript",e)}}function Hu(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,co(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Ju(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Nu(o))return;let a=fn(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Zu(o))});return r.current=i,i}function qu(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function gn(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function go(e,t,n){let r=zu(e);return i=>{if(!i.name)return null;let o=_(t,i.fileName),a=n.get(i.fileName);if(!a)return null;let s=n.positionAt(a,i.textSpan.start),c=r.get(o);if(!c)return null;let u=c.starts.find(p=>p.line===s.line&&p.displayName===i.name);if(u)return u.symbolId;let d=c.containingByLine.get(s.line);return d&&d.displayName===i.name?d.symbolId:Yu(c.starts,s.line,2,i.name)}}function zu(e){let t=e.prepare(`
|
|
260
260
|
SELECT
|
|
261
261
|
d.relative_path AS relativePath,
|
|
262
262
|
der.start_line AS startLine,
|
|
@@ -267,22 +267,22 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
267
267
|
JOIN documents d ON d.id = der.document_id
|
|
268
268
|
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
269
269
|
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
270
|
-
`).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function
|
|
270
|
+
`).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function Yu(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let u=Math.abs(c.line-t);u>n||(!a||u<a.distance)&&(a={distance:u,symbolId:c.symbolId})}return a?.symbolId??null}function fo(e,t,n){let r=nd(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
271
271
|
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
272
272
|
VALUES (?, ?, ?, ?)
|
|
273
|
-
`),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=
|
|
273
|
+
`),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=_(t,u),p=Io(r.name,r.version,d);o.run(p,"default",7,`Vue component|${d}`);let l=rd(i,r,t,u);l&&(a++,s.set(u,l))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function mo(e,t,n,r,i){return e.transaction(()=>(Uu(e),Xu(e,t,n,r),Qu(e,i)))()}function Xu(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
274
274
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
275
275
|
VALUES (?, ?, ?, ?, X'00')
|
|
276
276
|
`),a=e.prepare(`
|
|
277
277
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
278
278
|
VALUES (?, ?, 1)
|
|
279
|
-
`);for(let s of n){let c=r.get(s);if(!c)continue;let u=
|
|
279
|
+
`);for(let s of n){let c=r.get(s);if(!c)continue;let u=_(t,s),d=i.get(u);if(!d)continue;let p=o.run(d.id,-1,0,0);a.run(Number(p.lastInsertRowid),c)}}function ho(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),a=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&a){let s=r.language.maps.get(a,o);if(mn(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function yo(e){let t=new Set,n=[];for(let r of e){let i=So(r);t.has(i)||(t.add(i),n.push(r))}return n}function So(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Qu(e,t){let n=td(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
|
|
280
280
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
281
281
|
VALUES (?, ?, ?, ?, X'00')
|
|
282
282
|
`),i=e.prepare(`
|
|
283
283
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
284
284
|
VALUES (?, ?, 0)
|
|
285
|
-
`),o=new Set,a=0,s=0;for(let c of t){let u=
|
|
285
|
+
`),o=new Set,a=0,s=0;for(let c of t){let u=So(c);if(o.has(u))continue;o.add(u);let d=n.get(c.sourceFile);if(!d)continue;let p=r.run(d,s++,c.sourceLine,c.sourceLine),l=i.run(Number(p.lastInsertRowid),c.symbolId);a+=Number(l.changes)}return a}function*bo(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function Ro(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function mn(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Ku(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function xo(e,t){return _(e,t).startsWith("node_modules/")}function _(e,t){return Gu(e,t).replaceAll("\\","/")}function Zu(e){switch($u(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function vo(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=fn(t,"utf-8"),r={text:n,lineStarts:ed(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Ku}}function ed(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function td(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.set(s.relativePath,s.id)}return n}function nd(e){try{let t=JSON.parse(fn(uo(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function rd(e,t,n,r){let i=_(n,r),o=Io(t.name,t.version,i);return e.get(o)?.id??null}function Io(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function wo(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>ld({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function dd(e){return $(H(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),$(wo({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function ld(e){let t=ud(e.projectRoot,e.tsconfig);if(!ad(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new od(e.dbPath);try{let r=lo(n,e.projectRoot),i=cd(sd(e.dbPath),"augment-vue-meta.json");return Er({cachePath:i,readFingerprint:()=>fd(n,e.projectRoot,e.tsconfig),compute:()=>pd({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function pd(e){let t=fo(e.db,e.projectRoot,e.vueFiles),n=gd(e,t),r=yo(n.occurrences),i=mo(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:Id(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:vd(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function gd(e,t){if(io(e.vueFiles))return oo({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=md({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return hd({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function fd(e,t,n){let r=e.prepare(`
|
|
286
286
|
SELECT
|
|
287
287
|
(SELECT COUNT(*) FROM documents) AS documents,
|
|
288
288
|
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
@@ -291,13 +291,13 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
|
|
|
291
291
|
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
292
292
|
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
293
293
|
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
294
|
-
`).get();return{version:3,tsconfig:n,files:
|
|
295
|
-
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function dd(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Ro(e,t,n){let r=K();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:A(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function gn(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(s=>s.reason===o&&s.sourceFile===r).length>=2)return;let a=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,token:i.text,reason:o})}function fn(e,t){let n=new Map;for(let o of e){let a=n.get(o.sourceFile)??[];a.push(o),n.set(o.sourceFile,a)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let a=!1;for(let s of r){let c=n.get(s)?.[o];if(c&&(i.push(c),a=!0,i.length===t))break}if(!a)break}return i}function ld(e,t){let n=fn(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=fn(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function pd(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let a=n.length-i,s=Math.ceil((t-r.length)/a);r.push(...fn(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function gd(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return ld(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function fd(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of hd(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(a))continue;let s=t.tokenContext.tokenByStart.get(a);s&&(vo(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function vo(e,t,n,r,i,o,a){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:a})}function md(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function hd(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let d=yd(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function yd(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=pn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function nm(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=Dd(e),a=Date.now();tt(h(o.outputScip),{recursive:!0}),tt(h(o.outputDb),{recursive:!0});let s=e.languages??St(t);if(s.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${s.join(", ")}`);let c=ee("reindex.fingerprint",()=>cl(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),u,d;if(e.skipIfUnchanged!==!1&&!Ei(t,o.outputDb)&&Io(o.outputScip)===Io(v(h(o.outputDb),"index.scip"))){let g=Te(t);if(u=g?He(g,c):void 0,u){let I=C(u);if(I){if(!Td(o,c))try{Xt({snapshot:u,manifest:I,targetCacheDir:h(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(S){r(`Shared generation attach failed; continuing locally: ${hn(S)}`)}}else{let S=await Di(u);if(S.kind==="owner")d=S.release;else if(S.kind==="generation-ready"){let R=C(u);if(R)try{Xt({snapshot:u,manifest:R,targetCacheDir:h(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(y){r(`Shared generation attach failed after waiting; continuing locally: ${hn(y)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=ie(v(h(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${h(o.outputDb)}.`);let l;try{l=await te("reindex.lock",()=>tl(v(h(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:s.length})}catch(g){throw p.release(),d?.(),g}let m=null;try{let g=null,I=ee("reindex.reuse-check",()=>(g=Fd({opts:e,paths:o,languages:s,fingerprint:c,start:a,onStatus:r}),g),()=>({languages:s.length,reused:g!==null}));if(I)return Po({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),I;await te("reindex.scip-cli-ready",()=>Hd(i,r));let S=Od(o);m=S.runDir;let R,y=await te("reindex.fresh",async()=>(R=await Cd({opts:e,languages:s,projectRoot:t,paths:o,tempPaths:S,fingerprint:c,start:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),R),()=>({languages:s.length,reused:R?.reused,skipped:R?.skipped.length}));return Po({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),y}catch(g){throw Go(o.metaPath,ot({trigger:e.trigger,result:"failed",start:a,error:g instanceof Error?g.message:String(g)})),g}finally{m&&U(m,{recursive:!0,force:!0}),l(),p.release(),d?.()}}function Po(e){if(e.snapshot){if(C(e.snapshot)){ze(e.snapshot,h(e.paths.outputDb),"local-fresh");return}try{let t=Te(e.projectRoot),n=t?He(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}Ti({snapshot:e.snapshot,sourceCacheDir:h(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=Te(e.projectRoot);return(r?He(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),ze(e.snapshot,h(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${hn(t)}`)}}}function Td(e,t){if(!j(e.outputScip)||!j(e.outputDb)||!$o(e.metaPath,t))return!1;let n=G(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function hn(e){return e instanceof Error?e.message:String(e)}function Dd(e){let t=e.outputScip??v(e.projectRoot,"index.scip"),n=e.outputDb??v(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:v(h(n),"meta.json")}}function Fd(e){let t=G(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!j(e.paths.outputScip)||!j(e.paths.outputDb)||!$o(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;N(J(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=ot({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return Go(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:jd(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function jd(e,t,n,r){let i=Mo(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:be(i[o]),outputBytes:Re(Sn(e.outputDb,o)),durationMs:0}))}function Od(e){let t=xd(v(h(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:v(t,et(e.outputScip)),tempOutputDb:v(t,et(e.outputDb)),tempMetaPath:v(t,et(e.metaPath))}}async function Cd(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await te("reindex.language-indexers",async()=>(n=await Ad(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:d}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),_d({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=ee("reindex.publish",()=>Wd(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(I=>I.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c}}let p=ee("reindex.publish",()=>Ud(e,t,i,o,a,s,u,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),l=p.durationMs;return e.onStatus(`Done in ${(l/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:l,reused:!1,skipped:o,lastRefresh:p,shards:c}}function _d(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!j(e.run.paths.outputScip)||!j(e.run.paths.outputDb))return!1;let t=G(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function Ad(e,t){let n=Gd({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[E,xn]of n)xn.reused&&(r.push({language:E,scipPath:xn.scipPath}),i.add(E));for(let E of i)e.onStatus(`Reusing cached ${E} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=G(e.paths.outputDb,e.paths.metaPath),s=ve(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?Qi({projectRoot:e.projectRoot,cacheDir:h(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:xe(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:xe(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:yn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),l=d?void 0:Ld(e,n),{preparedRuns:m,skippedLanguages:g,languageOutputScipPaths:I}=zd({languages:e.languages.filter(E=>!i.has(E)&&!p.has(E)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:l?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),S=l?m.filter(E=>E.language!=="typescript"||l.missedProjectIds.has(E.id)):m,R=await Zi(S,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),y=[];if(l){Nd(e.paths.outputDb,R);let E=I.typescript??e.tempPaths.tempOutputScip;y=$d({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:E,reusedProjects:l.reusedProjects})}let w=[...R,...y],{indexedOutputs:k}=Qd(w,g),Ie=d?[{language:"typescript",scipPath:d.scipPath}]:[],Rn=[...r,...Ie,...k];Xd(Rn,g,e.languages,e.opts.allowPartial,e.onStatus);let Vo=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:Re(d.scipPath)??void 0}]:[],Bo=Vd(n,[...R,...Vo],l?{outputDb:e.paths.outputDb,classification:l.classification}:void 0);return{indexedOutputs:Rn,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Bd(n,e.languages),shards:Bo,typescriptProjectShardContext:l?{projects:l.allProjects,fingerprints:l.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function Ld(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Se(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Tr(e.projectRoot,r),o=wr(n.fingerprint.files,r),a=kr(r,i),s=Er(r,o,a),c=ve(e.paths.metaPath),d=Md(c,s,g=>j(it(e.paths.outputDb,g))),p=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),l=new Set(p),m=new Set(r.filter(g=>!l.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:d,reusedProjects:p,missedProjectIds:m}}function Md(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let a=e.typescriptProjectShards?.[i];if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(L(a)!==L(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function Nd(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=it(e,r);tt(h(i),{recursive:!0}),nt(n.scipPath,i)}}function $d(e){return e.reusedProjects.map((t,n)=>{let r=it(e.outputDb,t),i=xe(e.tempOutputScip,"typescript-project-cached",n);return nt(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Re(i)??void 0}})}function Gd(e){let t=ve(e.paths.metaPath),n=Mo(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Sn(e.paths.outputDb,i),a=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a,scipPath:o});continue}if(t.version!==3){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:a,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:a,scipPath:o});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:a,scipPath:o});continue}let s=t.languageFingerprints[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:a,scipPath:o});continue}if(!j(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(L(s)!==L(a)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:a,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:a,scipPath:o})}return r}function Vd(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:be(o.fingerprint),outputBytes:Re(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??o?.reason??i.skipped?.reason,fingerprint:s?be(s.fingerprint):o?be(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:be(o.fingerprint),outputBytes:Re(it(n.outputDb,i)),durationMs:0});return r}function be(e){return bd("sha256").update(L(e)).digest("hex").slice(0,16)}function Re(e){try{return Pd(e).size}catch{return null}}function Bd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Ud(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(wo(e.paths.outputDb,n),u=ko(n,e.tempPaths.tempOutputScip,e.onStatus));let d=Kd({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:()=>{if(!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Xi({cacheDir:h(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let y=n.map(w=>w.language==="typescript"?{language:w.language,scipPath:s.candidateScipPath}:w);return wo(e.paths.outputDb,y),u=ko(y,e.tempPaths.tempOutputScip,e.onStatus),u}});if(N(J(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&s){let y=null,w=null;try{y=new W({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),w=new W({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let k=Cn(y,e.fingerprint,s.referenceFragmentsByFile,w);e.onStatus(`Cached exact TypeScript reference fragments for ${k} affected document(s).`)}catch(k){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${k instanceof Error?k.message:String(k)}.`)}finally{y?.close(),w?.close()}}let p=yn(e.paths.metaPath),l=d.mode==="incremental"&&s?el(s,d.changedDocumentPaths):yt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),m=ot({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(y=>y.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",I={...o};g&&delete I.typescript;let{metadata:S,pruneProjects:R}=Oo({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:I,typescriptProjectShardContext:a,lastRefresh:m});return S.scipCompanion=g?"deferred":"current",Co(e.paths.outputDb,R),bn(e.tempPaths.tempMetaPath,S),We({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),ri(h(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),jo(e.paths.outputDb,l,e.onStatus),m}function Wd(e,t,n,r,i,o){let a=yn(e.paths.metaPath),s=null;try{nt(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){s=Zn("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}N(J(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),s??=yt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=ot({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=Oo({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Co(e.paths.outputDb,d),bn(e.paths.metaPath,u),fi(e.paths.outputDb,e.paths.metaPath),jo(e.paths.outputDb,s,e.onStatus),c}function yn(e){return kn(ve(e)?.fingerprint)}function jo(e,t,n){try{er(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function Oo(e){let t=Jd({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:3,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function Jd(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=ve(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Co(e,t){let n=No(e);if(t===null){U(n,{recursive:!0,force:!0});return}let r;try{r=Id(n)}catch{return}for(let i of qd(r,t))U(v(n,i),{force:!0})}function qd(e,t){let n=new Set(t.map(r=>`${Ot(r)}.scip`));return e.filter(r=>!n.has(r))}function wo(e,t){for(let n of t){let r=Sn(e,n.language);tt(h(r),{recursive:!0}),n.scipPath!==r&&nt(n.scipPath,r)}}async function Hd(e,t){if(!pt()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
296
|
-
Install from: https://github.com/sourcegraph/scip/releases`);if(
|
|
297
|
-
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
294
|
+
`).get();return{version:3,tsconfig:n,files:Te(t),db:r}}function md(e){let t=vo();return{projectRoot:e.projectRoot,context:po(e.projectRoot,e.configPath),symbolLookup:go(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function hd(e){let t=[],n=K(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=yd(e,i);t.push(...o.occurrences),et(n,o)}return{occurrences:t,...n}}function yd(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Po(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return Po(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=_(e.projectRoot,t.fileName),s=[...bo(n.text)],c={tokens:s.filter(u=>u.start>=t.startOffset&&u.start<t.endOffset),tokenByStart:new Map(s.map(u=>[u.start,u])),tokenTextCounts:wd(s),processedStarts:new Set};return Sd({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Sd(e){let t=[],n=K();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||bd(e.sourceInfo.text,r.start))continue;let i=Ro(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!xo(e.projectRoot,d.fileName));if(!a){hn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=_(e.projectRoot,a.fileName),c=Rd(e.sourceFile,r.text,s);if(c){hn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=ho(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){hn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}ko(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),Pd(t,e,r,i,s,u)}return{occurrences:t,...n}}function bd(e,t){let n=e.lastIndexOf(`
|
|
295
|
+
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Rd(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Po(e,t,n){let r=K();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:_(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function hn(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(s=>s.reason===o&&s.sourceFile===r).length>=2)return;let a=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,token:i.text,reason:o})}function yn(e,t){let n=new Map;for(let o of e){let a=n.get(o.sourceFile)??[];a.push(o),n.set(o.sourceFile,a)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let a=!1;for(let s of r){let c=n.get(s)?.[o];if(c&&(i.push(c),a=!0,i.length===t))break}if(!a)break}return i}function xd(e,t){let n=yn(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=yn(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function vd(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let a=n.length-i,s=Math.ceil((t-r.length)/a);r.push(...yn(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function Id(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return xd(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Pd(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of kd(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(a))continue;let s=t.tokenContext.tokenByStart.get(a);s&&(ko(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function ko(e,t,n,r,i,o,a){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:a})}function wd(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function kd(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let d=Ed(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function Ed(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=mn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function pm(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=Nd(e),a=Date.now();nt(h(o.outputScip),{recursive:!0}),nt(h(o.outputDb),{recursive:!0});let s=e.languages??xt(t);if(s.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${s.join(", ")}`);let c=ee("reindex.fingerprint",()=>Fn(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),u,d;if(e.skipIfUnchanged!==!1&&!Oi(t,o.outputDb)&&Eo(o.outputScip)===Eo(x(h(o.outputDb),"index.scip"))){let g=De(t);if(u=g?ze(g,c):void 0,u){let S=C(u);if(S){if(!Md(o,c))try{en({snapshot:u,manifest:S,targetCacheDir:h(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(b){r(`Shared generation attach failed; continuing locally: ${Re(b)}`)}}else{let b=await Ci(u);if(b.kind==="owner")d=b.release;else if(b.kind==="generation-ready"){let P=C(u);if(P)try{en({snapshot:u,manifest:P,targetCacheDir:h(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(y){r(`Shared generation attach failed after waiting; continuing locally: ${Re(y)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=ie(x(h(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${h(o.outputDb)}.`);let l;try{l=await te("reindex.lock",()=>ll(x(h(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:s.length})}catch(g){throw p.release(),d?.(),g}let m=null;try{let g=Bd(h(o.outputDb));g.removed>0&&r(`Removed ${g.removed} abandoned reindex workspace(s)`);for(let w of g.errors)r(`Could not remove abandoned reindex workspace: ${w}`);let S=null,b=ee("reindex.reuse-check",()=>(S=$d({opts:e,paths:o,languages:s,fingerprint:c,start:a,onStatus:r}),S),()=>({languages:s.length,reused:S!==null}));if(b)return To({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),mt(o.outputDb,b),b;await te("reindex.scip-cli-ready",()=>rl(i,r));let P=Vd(o);m=P.runDir;let y,I=await te("reindex.fresh",async()=>(y=await Ud({opts:e,languages:s,projectRoot:t,paths:o,tempPaths:P,fingerprint:c,start:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),y),()=>({languages:s.length,reused:y?.reused,skipped:y?.skipped.length}));return To({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),mt(o.outputDb,I),I}catch(g){let S=at({trigger:e.trigger,result:"failed",start:a,error:g instanceof Error?g.message:String(g)});throw Ho(o.metaPath,S),Mn(o.outputDb,S),g}finally{m&&M(m,{recursive:!0,force:!0}),l(),p.release(),d?.()}}function To(e){if(e.snapshot){if(C(e.snapshot)){Ye(e.snapshot,h(e.paths.outputDb),"local-fresh");return}try{let t=De(e.projectRoot),n=t?ze(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}ji({snapshot:e.snapshot,sourceCacheDir:h(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=De(e.projectRoot);return(r?ze(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Ye(e.snapshot,h(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${Re(t)}`)}}}function Md(e,t){if(!O(e.outputScip)||!O(e.outputDb)||!Wo(e.metaPath,t))return!1;let n=V(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Re(e){return e instanceof Error?e.message:String(e)}function Nd(e){let t=e.outputScip??x(e.projectRoot,"index.scip"),n=e.outputDb??x(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:x(h(n),"meta.json")}}function $d(e){let t=V(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!O(e.paths.outputScip)||!O(e.paths.outputDb)||!Wo(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;$(H(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=at({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return Ho(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:Gd(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Gd(e,t,n,r){let i=Bo(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:be(i[o]),outputBytes:xe(Rn(e.outputDb,o)),durationMs:0}))}function Vd(e){let t=Od(x(h(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:x(t,tt(e.outputScip)),tempOutputDb:x(t,tt(e.outputDb)),tempMetaPath:x(t,tt(e.metaPath))}}function Bd(e){let t=[],n;try{n=Ao(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[Re(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{M(x(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${Re(o)}`)}return{removed:r,errors:t}}async function Ud(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await te("reindex.language-indexers",async()=>(n=await Hd(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:d}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Wd({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=ee("reindex.publish",()=>el(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(S=>S.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c}}let p=ee("reindex.publish",()=>Zd(e,t,i,o,a,s,u,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),l=p.durationMs;return e.onStatus(`Done in ${(l/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:l,reused:!1,skipped:o,lastRefresh:p,shards:c}}function Wd(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!O(e.run.paths.outputScip)||!O(e.run.paths.outputDb))return!1;let t=V(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function Hd(e,t){let n=Xd({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[E,In]of n)In.reused&&(r.push({language:E,scipPath:In.scipPath}),i.add(E));for(let E of i)e.onStatus(`Reusing cached ${E} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=V(e.paths.outputDb,e.paths.metaPath),s=Ie(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?eo({projectRoot:e.projectRoot,cacheDir:h(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:ve(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:ve(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:bn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),l=d?void 0:Jd(e,n),{preparedRuns:m,skippedLanguages:g,languageOutputScipPaths:S}=il({languages:e.languages.filter(E=>!i.has(E)&&!p.has(E)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:l?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),b=l?m.filter(E=>E.language!=="typescript"||l.missedProjectIds.has(E.id)):m,P=await ro(b,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),y=[];if(l){zd(e.paths.outputDb,P);let E=S.typescript??e.tempPaths.tempOutputScip;y=Yd({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:E,reusedProjects:l.reusedProjects})}let I=[...P,...y],{indexedOutputs:w}=al(I,g),Pe=d?[{language:"typescript",scipPath:d.scipPath}]:[],vn=[...r,...Pe,...w];sl(vn,g,e.languages,e.opts.allowPartial,e.onStatus);let Jo=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:xe(d.scipPath)??void 0}]:[],qo=Qd(n,[...P,...Jo],l?{outputDb:e.paths.outputDb,classification:l.classification}:void 0);return{indexedOutputs:vn,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Kd(n,e.languages),shards:qo,typescriptProjectShardContext:l?{projects:l.allProjects,fingerprints:l.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function Jd(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Se(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=jr(e.projectRoot,r),o=Dr(n.fingerprint.files,r),a=Fr(r,i),s=Or(r,o,a),c=Ie(e.paths.metaPath),d=qd(c,s,g=>O(ot(e.paths.outputDb,g))),p=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),l=new Set(p),m=new Set(r.filter(g=>!l.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:d,reusedProjects:p,missedProjectIds:m}}function qd(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let a=e.typescriptProjectShards?.[i];if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(L(a)!==L(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function zd(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=ot(e,r);nt(h(i),{recursive:!0}),rt(n.scipPath,i)}}function Yd(e){return e.reusedProjects.map((t,n)=>{let r=ot(e.outputDb,t),i=ve(e.tempOutputScip,"typescript-project-cached",n);return rt(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:xe(i)??void 0}})}function Xd(e){let t=Ie(e.paths.metaPath),n=Bo(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Rn(e.paths.outputDb,i),a=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a,scipPath:o});continue}if(t.version!==3){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:a,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:a,scipPath:o});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:a,scipPath:o});continue}let s=t.languageFingerprints[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:a,scipPath:o});continue}if(!O(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(L(s)!==L(a)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:a,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:a,scipPath:o})}return r}function Qd(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:be(o.fingerprint),outputBytes:xe(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??o?.reason??i.skipped?.reason,fingerprint:s?be(s.fingerprint):o?be(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:be(o.fingerprint),outputBytes:xe(ot(n.outputDb,i)),durationMs:0});return r}function be(e){return Dd("sha256").update(L(e)).digest("hex").slice(0,16)}function xe(e){try{return Cd(e).size}catch{return null}}function Kd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Zd(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(Do(e.paths.outputDb,n),u=Fo(n,e.tempPaths.tempOutputScip,e.onStatus));let d=cl({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:()=>{if(!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),to({cacheDir:h(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let y=n.map(I=>I.language==="typescript"?{language:I.language,scipPath:s.candidateScipPath}:I);return Do(e.paths.outputDb,y),u=Fo(y,e.tempPaths.tempOutputScip,e.onStatus),u}});if($(H(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&s){let y=null,I=null;try{y=new W({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),I=new W({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let w=_n(y,e.fingerprint,s.referenceFragmentsByFile,I);e.onStatus(`Cached exact TypeScript reference fragments for ${w} affected document(s).`)}catch(w){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${w instanceof Error?w.message:String(w)}.`)}finally{y?.close(),I?.close()}}let p=bn(e.paths.metaPath),l=d.mode==="incremental"&&s?dl(s,d.changedDocumentPaths):Rt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),m=at({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(y=>y.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",S={...o};g&&delete S.typescript;let{metadata:b,pruneProjects:P}=Mo({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:S,typescriptProjectShardContext:a,lastRefresh:m});return b.scipCompanion=g?"deferred":"current",No(e.paths.outputDb,P),xn(e.tempPaths.tempMetaPath,b),He({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),si(h(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),Lo(e.paths.outputDb,l,e.onStatus),m}function el(e,t,n,r,i,o){let a=bn(e.paths.metaPath),s=null;try{rt(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){s=rr("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}$(H(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),s??=Rt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=at({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=Mo({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return No(e.paths.outputDb,d),xn(e.paths.metaPath,u),Si(e.paths.outputDb,e.paths.metaPath),Lo(e.paths.outputDb,s,e.onStatus),c}function bn(e){return Tn(Ie(e)?.fingerprint)}function Lo(e,t,n){try{ir(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function Mo(e){let t=tl({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:3,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function tl(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=Ie(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function No(e,t){let n=Uo(e);if(t===null){M(n,{recursive:!0,force:!0});return}let r;try{r=Ao(n)}catch{return}for(let i of nl(r,t))M(x(n,i),{force:!0})}function nl(e,t){let n=new Set(t.map(r=>`${_t(r)}.scip`));return e.filter(r=>!n.has(r))}function Do(e,t){for(let n of t){let r=Rn(e,n.language);nt(h(r),{recursive:!0}),n.scipPath!==r&&rt(n.scipPath,r)}}async function rl(e,t){if(!gt()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
296
|
+
Install from: https://github.com/sourcegraph/scip/releases`);if(Ld()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall with optional dependencies enabled, run 'npm install -g scip-query-scip-windows', or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(t("scip CLI not found on PATH. Attempting auto-install..."),!ft(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
297
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function il(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?ve(e.tempOutputScip,o,a):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:o,scipPath:a})=>[o,a]));for(let{language:o,scipPath:a}of r){let s=ol({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?$o(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function ol(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Sn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??Se(e.projectRoot,e.typescriptProjects);return t.length===0?[Sn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>Sn({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:ve(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Sn(e){let t=Ce(e.language),n=ne(t),r=ut(t,e.projectRoot);if(!r&&!ct(t)){if(e.skipAutoInstall){let s=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!ln(t,e.onStatus)){let s=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}}let i=r??re(t);if(!i){let s=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}let{binary:o,args:a}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});return{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:i,binary:o,args:a,env:dt(t,e.env,i)}}}function al(e,t){let n=new Map;for(let i of e)if(i.skipped)$o(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,a=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};a.scipPaths.push(i.scipPath),n.set(o,a)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)Dt(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&_o(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function $o(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function sl(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
|
|
298
298
|
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
299
299
|
`+o)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(o=>o.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
|
|
300
300
|
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
301
|
-
`))}function
|
|
302
|
-
`),()=>{try{
|
|
301
|
+
`))}function Fo(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=hr(e.map(o=>o.scipPath),t);return Vo(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&_o(e[0].scipPath,t);return!1}function cl(e){let t;if(ul(e)){let i=x(e.run.tempPaths.runDir,"typescript-affected.db");try{Go(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Oo(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let a=Pr({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${a.affectedDocumentCount} SQLite document(s) in ${(a.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:a.changedDocumentPaths,patchDurationMs:a.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),M(i,{force:!0}),M(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return Oo(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function ul(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!O(e.run.paths.outputDb)||!O(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function dl(e,t){let n=Date.now(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(a=>!i.has(a)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:Date.now()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:bt(e.plan,o,e.projectFileCount)}}function Oo(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!O(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||Go(e,r);let o=gt();if(!o)throw new Error("scip CLI is not available");Td(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${a}`,{cause:o})}}function Go(e,t){let n=fr(e);Vo(n,t)}function Vo(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function ve(e,t,n){let r=_d(e)||".scip",i=tt(e,r);return x(h(e),`${i}.${n+1}.${t}${r}`)}async function ll(e,t){for(let n=0;n<2;n++){let r=pl(e,t);if(r)return r;let i=gl(e);if(i&&fl(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await hl(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${h(e)}; refusing to steal an active lock.`);M(e,{force:!0});continue}if(i&&!T(i.pid)){M(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${h(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${h(e)}.`)}function pl(e,t){let n;try{n=jd(e,"wx")}catch(i){if((typeof i=="object"&&i&&"code"in i?i.code:void 0)==="EEXIST")return null;throw i}let r={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return Ad(n,JSON.stringify(r)+`
|
|
302
|
+
`),()=>{try{Fd(n)}finally{M(e,{force:!0})}}}function gl(e){try{let t=JSON.parse(it(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:{version:1,pid:t.pid,projectRoot:typeof t.projectRoot=="string"?t.projectRoot:h(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function fl(e,t){return e?.kind==="manual-cli"&&ml(t?.trigger)}function ml(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function hl(e){return jo(e,"SIGTERM"),await Co(e,2e3)?!0:(jo(e,"SIGKILL"),Co(e,1e3))}function jo(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Co(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!T(e))return!0;await yl(50)}return!T(e)}function yl(e){return new Promise(t=>setTimeout(t,e))}function Bo(e,t,n){return Object.fromEntries(t.map(r=>{let i=Ce(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Dn(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?Sl(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&bl(n),...o,clojureConfigPath:a,files:Te(e,{language:r,markerFiles:i})}]}))}function Sl(e){return e?.trim()||void 0}function bl(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Rn(e,t){return x(h(e),"language-indexes",`${t}.scip`)}function Uo(e){return x(h(e),"language-indexes","typescript-projects")}function ot(e,t){return x(Uo(e),`${_t(t)}.scip`)}function Ie(e){try{return JSON.parse(it(e,"utf-8"))}catch{return null}}function Wo(e,t){try{let n=JSON.parse(it(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&L(n.fingerprint)===L(t)&&L([...n.indexedLanguages??[]].sort())===L(t.languages)}catch{return!1}}function xn(e,t){R(e,t,{spacing:2,trailingNewline:!0})}function Ho(e,t){try{let n=JSON.parse(it(e,"utf-8"));if(n.version!==2&&n.version!==3)return;xn(e,{...n,lastRefresh:t})}catch{}}function at(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-e.start,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function L(e){return JSON.stringify(e)}export{pr as INDEXER_CONFIGS,Qn as augmentAuxiliaryDocuments,dd as augmentVueResolvedReferences,H as auxiliaryDocumentsAugmentationStage,ne as describeIndexerBinary,xt as detectLanguages,Ce as getIndexerConfig,dt as getIndexerExecutionEnv,st as isBinaryAvailable,ct as isIndexerInstalled,Dt as mergeScipFiles,Tt as mergeScipIndexes,pm as reindex,re as resolveIndexerBinary,ut as resolveProjectLocalIndexerBinary,$ as runPostIndexAugmentation,ln as tryInstallIndexer,ft as tryInstallScipCli,wo as vueResolvedReferencesAugmentationStage};
|
|
303
303
|
//# sourceMappingURL=reindex.js.map
|