scip-query 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/README.md +40 -9
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-WN6XEYVX.js → chunk-27YDE22N.js} +2 -2
- package/dist/{chunk-VLSI5MYU.js → chunk-2DBY4MO7.js} +2 -2
- package/dist/{chunk-YSUD2S7T.js → chunk-2HCWAL42.js} +2 -2
- package/dist/{chunk-YCVYOV4A.js → chunk-34RCSYMZ.js} +2 -2
- package/dist/{chunk-3LAKH6BV.js → chunk-3CJXFMR5.js} +2 -2
- package/dist/{chunk-2EU6WVR3.js → chunk-3EBDPBBU.js} +2 -2
- package/dist/{chunk-6EVORGCB.js → chunk-42YU6TEB.js} +2 -2
- package/dist/{chunk-3YAZH3JU.js → chunk-45QWQSWS.js} +2 -2
- package/dist/{chunk-5XDNFOAH.js → chunk-4FLF7BHJ.js} +2 -2
- package/dist/{chunk-JRFCWCOD.js → chunk-4L4X66GE.js} +2 -2
- package/dist/{chunk-NLRWGGPY.js → chunk-5CJ6AQN7.js} +2 -2
- package/dist/{chunk-CM4EZLW4.js → chunk-5GAUXLOE.js} +2 -2
- package/dist/{chunk-QB7NRST4.js → chunk-5N5ZC566.js} +2 -2
- package/dist/{chunk-P5QZILZ4.js → chunk-5ODF4JGH.js} +2 -2
- package/dist/{chunk-OYGKBDAD.js → chunk-6G3GQWTK.js} +2 -2
- package/dist/{chunk-IRIM3SUR.js → chunk-75H6GOND.js} +2 -2
- package/dist/{chunk-VSQRU3AP.js → chunk-7CHIAMKS.js} +2 -2
- package/dist/{chunk-L27UIF3E.js → chunk-7MT6UM4D.js} +2 -2
- package/dist/{chunk-OO6S4ECV.js → chunk-7XP7ZRSI.js} +2 -2
- package/dist/{chunk-5TVNLPUM.js → chunk-7Z5UT44B.js} +2 -2
- package/dist/{chunk-A46JTKTM.js → chunk-A4KRWTXD.js} +2 -2
- package/dist/{chunk-BFWVHD2P.js → chunk-ABRWGVC6.js} +2 -2
- package/dist/{chunk-7II7NFRV.js → chunk-AQ34B63A.js} +2 -2
- package/dist/{chunk-EVCSXWER.js → chunk-BBBZB5WY.js} +2 -2
- package/dist/{chunk-MZB3DTHW.js → chunk-BGUYAA3Q.js} +2 -2
- package/dist/{chunk-ZHGUZKJL.js → chunk-CMLHZWRS.js} +2 -2
- package/dist/{chunk-3I34FZ6R.js → chunk-CYDOV3AQ.js} +2 -2
- package/dist/{chunk-GWWYLYD3.js → chunk-DQYG5JHT.js} +2 -2
- package/dist/{chunk-W3ZVRLCH.js → chunk-EPDV3SQD.js} +2 -2
- package/dist/{chunk-U6BJVXWQ.js → chunk-GRHA5NGF.js} +2 -2
- package/dist/{chunk-YD37KSEK.js → chunk-H4SMB657.js} +2 -2
- package/dist/{chunk-XBPAJASV.js → chunk-H4T2AST4.js} +2 -2
- package/dist/{chunk-SOCS3467.js → chunk-HGO3D2JD.js} +2 -2
- package/dist/{chunk-RLB7FZKR.js → chunk-HV4N3UBV.js} +2 -2
- package/dist/{chunk-VZCR3VQY.js → chunk-IK2NG76R.js} +2 -2
- package/dist/{chunk-CS3FXTUC.js → chunk-J4HK7PQS.js} +2 -2
- package/dist/{chunk-QSNG3NHQ.js → chunk-J7WYG63U.js} +2 -2
- package/dist/{chunk-7RAS466A.js → chunk-JJAH2VLD.js} +2 -2
- package/dist/{chunk-NLVKD45E.js → chunk-JLZUM476.js} +2 -2
- package/dist/{chunk-JQ2PCFZW.js → chunk-JUADXGUH.js} +2 -2
- package/dist/{chunk-DKK2H4D7.js → chunk-JVTMRIKU.js} +2 -2
- package/dist/{chunk-YFEJIYWH.js → chunk-JYBF5CPE.js} +2 -2
- package/dist/{chunk-S5RZQA6V.js → chunk-K3UVTL3J.js} +2 -2
- package/dist/{chunk-363TZ64I.js → chunk-KAOWSWEX.js} +2 -2
- package/dist/{chunk-RPMT6MTX.js → chunk-KLFCCRI7.js} +2 -2
- package/dist/{chunk-6GZ7LM7S.js → chunk-KO2TFDIP.js} +2 -2
- package/dist/{chunk-S5MTSES5.js → chunk-KTZACYL6.js} +2 -2
- package/dist/{chunk-6DNE65QS.js → chunk-KYUYAWKA.js} +2 -2
- package/dist/{chunk-PCCMMI2M.js → chunk-KZ2LZBQT.js} +2 -2
- package/dist/chunk-L7UITWFE.js +120 -0
- package/dist/{chunk-CVBS2FD4.js → chunk-LC57FSPX.js} +2 -2
- package/dist/{chunk-S3IXCXW2.js → chunk-LG33DNTZ.js} +2 -2
- package/dist/chunk-M2TRDR25.js +84 -0
- package/dist/{chunk-2Y7YX54K.js → chunk-MVFNACWB.js} +2 -2
- package/dist/{chunk-Q65QYKU7.js → chunk-NJBARXRO.js} +2 -2
- package/dist/{chunk-5UKDCXVC.js → chunk-OP5JXGDV.js} +2 -2
- package/dist/{chunk-SEEJPIWG.js → chunk-OP5RO2CF.js} +2 -2
- package/dist/{chunk-EBSSCVR4.js → chunk-OQRMCT2N.js} +5 -5
- package/dist/{chunk-CKIAEVGM.js → chunk-PA2MQKXD.js} +2 -2
- package/dist/{chunk-XC6PUFNN.js → chunk-PVXSHZLW.js} +2 -2
- package/dist/{chunk-AAMZRDJT.js → chunk-PYOZHG6A.js} +2 -2
- package/dist/{chunk-G4KQ7S74.js → chunk-QEIGJJBC.js} +2 -2
- package/dist/{chunk-DA34GNNO.js → chunk-QNCVN5EH.js} +2 -2
- package/dist/chunk-RSZ4KX4B.js +7 -0
- package/dist/{chunk-HGUNWXJX.js → chunk-RUQE7DZT.js} +2 -2
- package/dist/{chunk-VYQY75NA.js → chunk-RZEVUYMG.js} +2 -2
- package/dist/chunk-SMBIGBGN.js +67 -0
- package/dist/{chunk-AMPN2VMF.js → chunk-SREWDA7Q.js} +2 -2
- package/dist/{chunk-S2FZILCF.js → chunk-TAB7AWKO.js} +2 -2
- package/dist/{chunk-UO4IADXJ.js → chunk-TCOWAGR2.js} +2 -2
- package/dist/{chunk-BVHP2B4D.js → chunk-TL2IXVGH.js} +2 -2
- package/dist/{chunk-MCNWCJYL.js → chunk-TLTLJ4SW.js} +2 -2
- package/dist/{chunk-JXAJDINF.js → chunk-TR7C5HOC.js} +2 -2
- package/dist/{chunk-3OPIMH42.js → chunk-U244OVE6.js} +2 -2
- package/dist/chunk-U3JW5AYG.js +2 -0
- package/dist/{chunk-2HFXPIBT.js → chunk-UWR52GNZ.js} +2 -2
- package/dist/{chunk-62Y3PC27.js → chunk-VCOAUTSI.js} +2 -2
- package/dist/{chunk-BVUA3GZC.js → chunk-VCRMI56V.js} +2 -2
- package/dist/{chunk-753JWTUH.js → chunk-VDHEX6YO.js} +2 -2
- package/dist/{chunk-RYFIRFYJ.js → chunk-VPVAQRHM.js} +2 -2
- package/dist/{chunk-RQWNF2RM.js → chunk-VT2KFEPG.js} +2 -2
- package/dist/{chunk-LT6AHYVY.js → chunk-WH65EY7U.js} +2 -2
- package/dist/{chunk-HLRWOFXC.js → chunk-X566NT42.js} +2 -2
- package/dist/{chunk-ZEKBAMCN.js → chunk-XKWEMFHP.js} +2 -2
- package/dist/{chunk-KI4WPR7Q.js → chunk-Y3DG4J6A.js} +2 -2
- package/dist/{chunk-KP2DJY7D.js → chunk-Y5BOEWAE.js} +2 -2
- package/dist/{chunk-2LGPMYS2.js → chunk-YD7GGLGE.js} +2 -2
- package/dist/{chunk-K32ZOW3P.js → chunk-ZMD4O5UP.js} +2 -2
- package/dist/cli.js +321 -303
- package/dist/{config-types-SVkUIufk.d.ts → config-types-70s7NxKB.d.ts} +2 -0
- package/dist/{db-CS0TuVH6.d.ts → db-BBmJ0v3b.d.ts} +1 -1
- package/dist/{health-Btal3mQi.d.ts → health-CWpFL_6z.d.ts} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/bottlenecks.d.ts +2 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +2 -2
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +2 -2
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +2 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +2 -2
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +2 -2
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +2 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +2 -2
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +2 -2
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +2 -2
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +2 -2
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +2 -2
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +2 -2
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +2 -2
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +2 -2
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +2 -2
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +3 -3
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +2 -2
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +2 -2
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +2 -2
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.d.ts +2 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +2 -2
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +2 -2
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +2 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +2 -2
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +2 -2
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +2 -2
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +2 -2
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +2 -2
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +2 -2
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +2 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +2 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +2 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +2 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +2 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +2 -2
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +2 -2
- package/dist/queries/surface.d.ts +2 -2
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +2 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +2 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +2 -2
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.d.ts +2 -2
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +2 -2
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +2 -2
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.d.ts +2 -2
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +2 -2
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +2 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +2 -2
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +2 -2
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +2 -2
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +26 -26
- package/dist/reindex.d.ts +3 -3
- package/dist/reindex.js +38 -34
- package/dist/runtime.d.ts +3 -3
- package/dist/runtime.js +1 -2
- package/dist/{scip-cli-BKL-26TZ.d.ts → scip-cli-CoMzb7Zu.d.ts} +1 -1
- package/dist/watch-server.js +4 -4
- package/docs/COMMAND_REFERENCE.md +1 -1
- package/package.json +1 -1
- package/skills/_shared/SKILL.md +2 -2
- package/skills/scip-calibrate/SKILL.md +5 -4
- package/skills/scip-verify/SKILL.md +3 -2
- package/dist/chunk-5P26M63Y.js +0 -2
- package/dist/chunk-FFIYGYQR.js +0 -67
- package/dist/chunk-WFRZGMWJ.js +0 -71
- package/dist/chunk-XAEU4ROB.js +0 -101
- package/dist/chunk-Y42DMR6F.js +0 -6
package/dist/reindex.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
|
|
3
|
-
`).
|
|
1
|
+
import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k as jn,l as _n}from"./chunk-RSZ4KX4B.js";import{a as Fn}from"./chunk-YZXV3CU3.js";import{A as En,B as ke,C as Tn,E as Dn,a as Co,b as ve,c as rt,d as it,e as ot,f as at,g as st,h as ct,i as T,j as b,o as xn,p as In,q as Pe,r as vn,s as Pn,t as wn,u as ut,v as dt,y as kn,z as we}from"./chunk-OQRMCT2N.js";import"./chunk-P5XHIJHI.js";import{a as Ie}from"./chunk-QEIGJJBC.js";import{a as Ao}from"./chunk-QVZSWLLZ.js";import"./chunk-7XP7ZRSI.js";import"./chunk-JLZUM476.js";import{J as bn,K as Rn,d as K}from"./chunk-TLTLJ4SW.js";import{a as xe}from"./chunk-64MNV6AB.js";import{s as Z,t as ee}from"./chunk-M2TRDR25.js";import{execFileSync as od}from"child_process";import{createHash as ad}from"crypto";import{closeSync as sd,copyFileSync as Ze,existsSync as O,mkdirSync as Ke,mkdtempSync as cd,openSync as ud,readdirSync as dd,readFileSync as et,renameSync as xo,rmSync as W,statSync as ld,writeFileSync as pd}from"fs";import{basename as Xe,dirname as h,extname as gd,join as I,resolve as fo}from"path";import{platform as fd}from"os";import{randomUUID as Cn}from"crypto";import{closeSync as An,mkdirSync as Lo,openSync as Ln,readFileSync as Mn,unlinkSync as Nn,writeFileSync as $n}from"fs";import{dirname as Mo,join as No}from"path";function Gn(e,t={}){return te(No(e,"gc.lock"),t)}function te(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;Lo(Mo(e),{recursive:!0});do{let a=Cn();try{let s=Ln(e,"wx");try{let c={version:1,pid:process.pid,token:a,startedAt:new Date(i()).toISOString()};$n(s,`${JSON.stringify(c)}
|
|
2
|
+
`)}finally{An(s)}return{release:()=>Un(e,a)}}catch(s){if(s.code!=="EEXIST")return null;let c=Vn(e);if(c&&(c.pid===void 0||!T(c.pid))){$o(e,c);continue}if(Date.now()>=o)return null;Go(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function Vn(e){try{let t=Mn(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function $o(e,t){let n=`${e}.reclaim`,r=Cn(),i;try{i=Ln(n,"wx")}catch{return!1}try{$n(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
|
|
3
|
+
`)}finally{An(i)}try{let o=Vn(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Nn(e),!0)}catch{return!1}finally{Un(n,r)}}function Un(e,t){try{let n=JSON.parse(Mn(e,"utf8"));n.pid===process.pid&&n.token===t&&Nn(e)}catch{}}function Go(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import Vo from"better-sqlite3";import{execFileSync as Uo}from"child_process";import{existsSync as Wo,readdirSync as Bo,readFileSync as Jo}from"fs";import{extname as Te,join as Wn}from"path";function J(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Bn({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Bn(e){let t=new Set((e.extensions??bn).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Wo(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Fn(e.projectRoot),r=Ho(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Vo(e.dbPath);try{let o=zo(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=Jo(Wn(e.projectRoot,l),"utf-8"),g=a.run(Yo(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 Ho(e,t){let n=qo(e,t);if(n)return n;let r=[],i=o=>{let a=o?Wn(e,o):e,s;try{s=Bo(a,{withFileTypes:!0})}catch{return}for(let c of s){if(Rn.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(Te(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function qo(e,t){try{return Uo("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
|
|
5
|
+
`).filter(r=>r&&t.has(Te(r).toLowerCase())).sort()}catch{return null}}function zo(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 Yo(e){return Te(e).toLowerCase()===".vue"?"vue":Te(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Qo}from"crypto";import{appendFileSync as Xo,existsSync as Ko,mkdirSync as Zo,readFileSync as pl}from"fs";import{dirname as qn,join as Jn}from"path";var ea="<global-symbols>";function ta(e){let t=[];for(let n of e.all(`
|
|
4
6
|
SELECT relative_path, language, position_encoding, text
|
|
5
7
|
FROM documents
|
|
6
8
|
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
@@ -27,7 +29,7 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
27
29
|
FROM defn_enclosing_ranges r
|
|
28
30
|
JOIN documents d ON d.id = r.document_id
|
|
29
31
|
JOIN global_symbols g ON g.id = r.symbol_id
|
|
30
|
-
`))t.push({relativePath:n.relative_path,kind:"definition",values:
|
|
32
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:gt(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
31
33
|
SELECT d.relative_path,
|
|
32
34
|
c.chunk_index,
|
|
33
35
|
m.role,
|
|
@@ -42,7 +44,7 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
42
44
|
JOIN chunks c ON c.id = m.chunk_id
|
|
43
45
|
JOIN documents d ON d.id = c.document_id
|
|
44
46
|
JOIN global_symbols g ON g.id = m.symbol_id
|
|
45
|
-
`))t.push({relativePath:n.relative_path,kind:"mention",values:
|
|
47
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:gt(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
46
48
|
SELECT g.symbol,
|
|
47
49
|
g.display_name,
|
|
48
50
|
g.kind,
|
|
@@ -56,10 +58,10 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
56
58
|
) AND NOT EXISTS (
|
|
57
59
|
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
58
60
|
)
|
|
59
|
-
`))t.push({relativePath:
|
|
60
|
-
`);n.set(r,o.digest("hex"))}return n}function
|
|
61
|
-
`)},writeLatest:(e,t)=>
|
|
62
|
-
`)){if(!r||r.split("/").some(o=>en.has(o)))continue;let i=Kt(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Ji(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Qt(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readFileSync as rn,writeFileSync as on}from"fs";import{create as Je}from"@bufbuild/protobuf";import{deserializeSCIP as an,serializeSCIP as sn,DocumentSchema as to,IndexSchema as no,SymbolInformationSchema as ro}from"@c4312/scip";import{readFileSync as zi,writeFileSync as Yi}from"fs";import{create as tn}from"@bufbuild/protobuf";import{deserializeSCIP as Qi,DocumentSchema as Xi,IndexSchema as Ki,serializeSCIP as Zi,SymbolRole as eo}from"@c4312/scip";function nn(e){let t;try{t=Qi(zi(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=qe(t);return n.removedDefinitionOccurrences>0&&Yi(e,Buffer.from(Zi(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function qe(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&eo.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(tn(Xi,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:tn(Ki,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function ze(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=io(e),n=oo(e.flatMap(i=>i.documents??[])),r=un(e.flatMap(i=>i.externalSymbols??[]));return Je(no,{metadata:t,documents:n,externalSymbols:r})}function Ye(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>an(rn(i))),r=ze(n);return on(t,Buffer.from(sn(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function cn(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>an(rn(i))),r=qe(ze(n));return on(t,Buffer.from(sn(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function io(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 oo(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,Je(to,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:ao([...r.occurrences,...n.occurrences]),symbols:un([...r.symbols,...n.symbols]),text:co(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function ao(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 un(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,Je(ro,{symbol:r.symbol,documentation:uo([...r.documentation,...n.documentation]),relationships:so([...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 so(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 co(e,t){return e?t?e.length>=t.length?e:t:e:t}function uo(e){return[...new Set(e)]}import{createHash as lo}from"crypto";import{copyFileSync as po,existsSync as ln,rmSync as dn}from"fs";import{resolve as go}from"path";import fn from"better-sqlite3";var fo={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}]},mo={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 mn(e){let t=Date.now(),n=ho(e.affectedFiles);if(yo(e.previousDbPath,e.miniDbPath,e.candidateDbPath),dn(e.candidateDbPath,{force:!0}),!ln(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!ln(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");pn(e.previousDbPath,"previous SQLite generation",!1),pn(e.miniDbPath,"incremental SQLite mini database"),po(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new fn(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Qe(r,"main","candidate SQLite generation"),Qe(r,"incremental","incremental SQLite mini database"),So(r,n),bo(r,n.length);let i=Xe(r,"main",!0),o=j(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Ro(r),xo(r),vo(r),e.onStage?.("after-delete"),Po(r),e.onStage?.("after-symbol-reconciliation"),Io(r),e.onStage?.("after-insert"),wo(r),To(r,n.length,o),e.onStage?.("before-commit")}).immediate(),hn(r,"main","candidate SQLite generation");let c=[...Eo(r)].filter(([u,l])=>i.get(u)!==l).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{dn(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function ho(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 yo(e,t,n){let r=[e,t,n].map(i=>go(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function pn(e,t,n=!0){let r=new fn(e,{readonly:!0,fileMustExist:!0});try{Qe(r,"main",t),n&&hn(r,"main",t)}finally{r.close()}}function Qe(e,t,n){for(let[r,i]of Object.entries(fo)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:l})=>({name:s,type:c.toUpperCase(),notnull:u,pk:l}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(mo)){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}`)}gn(e,t,"documents",["relative_path"],n),gn(e,t,"global_symbols",["symbol"],n)}function gn(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 hn(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 So(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 bo(e,t){let n=j(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=j(e,`SELECT COUNT(*) AS value
|
|
61
|
+
`))t.push({relativePath:ea,kind:"global-symbol",values:gt(n)});return na(t)}function na(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=Qo("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 ra(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 ft(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 mt(e,t=oa){let n=t.now();if(!t.databaseExists(e.previousDbPath))return De(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return De(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=we(e.previousSnapshot,e.currentSnapshot),s=new Set(o),c=a.changes.length>0&&!En(a).fullProject&&a.changes.every(l=>s.has(l.path)),u=ke(a,c?t.dependencyGraph(r):new Map,o),d=ra(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:ft(u,d,o.length)}}catch(o){return De(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{Hn(r),Hn(i)}}function zn(e,t,n,r=Date.now()){return De(e,t,r,r,n)}function ia(e){let t=qn(e);return{latestPath:Jn(t,"affected-shadow-latest.json"),historyPath:Jn(t,"affected-shadow.jsonl")}}function Yn(e,t,n=aa){let r=ia(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function gt(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 oa={now:()=>Date.now(),databaseExists:e=>Ko(e),openDatabase:(e,t,n)=>new B({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>xe(e),dependencyGraph:e=>Ie(e),factDigests:e=>ta(e)},aa={appendHistory:(e,t)=>{Zo(qn(e),{recursive:!0}),Xo(e,`${JSON.stringify(t)}
|
|
63
|
+
`)},writeLatest:(e,t)=>b(e,t,{spacing:2,trailingNewline:!0})};function De(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 Hn(e){try{e?.close()}catch{}}import{execFileSync as sa}from"child_process";import{existsSync as ca,readdirSync as Xn}from"fs";import{extname as Kn,join as Zn}from"path";var er=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),ua=[{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 ht(e){let t=[],n=da(e),r=fa(e);for(let i of ua){if(la(e,i.files)){t.push(i.language);continue}if(pa(n,i.globs)){t.push(i.language);continue}ha(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Qn(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Qn(t,"c"),t}function da(e){try{return Xn(e)}catch{return[]}}function la(e,t){return t?.length?t.some(n=>ca(Zn(e,n))):!1}function pa(e,t){return t?.length?e.some(n=>t.some(r=>ga(n,r))):!1}function ga(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 fa(e){let t=ma(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=Xn(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=Zn(i,a.name);if(a.isDirectory()){er.has(a.name)||r.push(s);continue}let c=Kn(a.name).toLowerCase();c&&n.add(c)}}return n}function ma(e){try{let t=sa("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=>er.has(o)))continue;let i=Kn(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function ha(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Qn(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readFileSync as St,writeFileSync as bt}from"fs";import{create as ne}from"@bufbuild/protobuf";import{deserializeSCIP as Rt,serializeSCIP as xt,DocumentSchema as Pa,IndexSchema as rr,MetadataSchema as wa,SymbolInformationSchema as ka}from"@c4312/scip";import{readFileSync as ya,writeFileSync as Sa}from"fs";import{create as tr}from"@bufbuild/protobuf";import{deserializeSCIP as ba,DocumentSchema as Ra,IndexSchema as xa,serializeSCIP as Ia,SymbolRole as va}from"@c4312/scip";function nr(e){let t;try{t=ba(ya(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=yt(t);return n.removedDefinitionOccurrences>0&&Sa(e,Buffer.from(Ia(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function yt(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&va.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(tr(Ra,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:tr(xa,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function It(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Ta(e),n=Da(e.flatMap(i=>i.documents??[])),r=ar(e.flatMap(i=>i.externalSymbols??[]));return ne(rr,{metadata:t,documents:n,externalSymbols:r})}function vt(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Rt(St(i))),r=It(n);return bt(t,Buffer.from(xt(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function ir(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Rt(St(i))),r=yt(It(n));return bt(t,Buffer.from(xt(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function Ea(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 ne(rr,{metadata:ne(wa,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function or(e,t,n){let r=Rt(St(e)),i=Ea(r,t,n);bt(e,Buffer.from(xt(i)))}function Ta(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 Da(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,ne(Pa,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Fa([...r.occurrences,...n.occurrences]),symbols:ar([...r.symbols,...n.symbols]),text:ja(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Fa(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 ar(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,ne(ka,{symbol:r.symbol,documentation:_a([...r.documentation,...n.documentation]),relationships:Oa([...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 Oa(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 ja(e,t){return e?t?e.length>=t.length?e:t:e:t}function _a(e){return[...new Set(e)]}import{createHash as Ca}from"crypto";import{copyFileSync as Aa,existsSync as sr,rmSync as cr}from"fs";import{resolve as La}from"path";import lr from"better-sqlite3";var Ma={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}]},Na={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=$a(e.affectedFiles);if(Ga(e.previousDbPath,e.miniDbPath,e.candidateDbPath),cr(e.candidateDbPath,{force:!0}),!sr(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!sr(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");ur(e.previousDbPath,"previous SQLite generation",!1),ur(e.miniDbPath,"incremental SQLite mini database"),Aa(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new lr(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Pt(r,"main","candidate SQLite generation"),Pt(r,"incremental","incremental SQLite mini database"),Va(r,n),Ua(r,n.length);let i=wt(r,"main",!0),o=M(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Wa(r),Ba(r),Ja(r),e.onStage?.("after-delete"),Ha(r),e.onStage?.("after-symbol-reconciliation"),qa(r),e.onStage?.("after-insert"),za(r),Ya(r,n.length,o),e.onStage?.("before-commit")}).immediate(),gr(r,"main","candidate SQLite generation");let c=[...Qa(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{cr(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function $a(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 Ga(e,t,n){let r=[e,t,n].map(i=>La(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function ur(e,t,n=!0){let r=new lr(e,{readonly:!0,fileMustExist:!0});try{Pt(r,"main",t),n&&gr(r,"main",t)}finally{r.close()}}function Pt(e,t,n){for(let[r,i]of Object.entries(Ma)){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(Na)){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}`)}dr(e,t,"documents",["relative_path"],n),dr(e,t,"global_symbols",["symbol"],n)}function dr(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 gr(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 Va(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 Ua(e,t){let n=M(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=M(e,`SELECT COUNT(*) AS value
|
|
63
65
|
FROM main.documents d
|
|
64
66
|
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
|
|
65
67
|
FROM temp.incremental_affected_paths p
|
|
@@ -69,7 +71,7 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
69
71
|
FROM incremental.documents d
|
|
70
72
|
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
71
73
|
WHERE p.relative_path IS NULL
|
|
72
|
-
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 Wa(e){e.exec(`
|
|
73
75
|
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
74
76
|
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
75
77
|
SELECT g.symbol
|
|
@@ -96,7 +98,7 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
96
98
|
FROM incremental.mentions m
|
|
97
99
|
JOIN incremental.global_symbols g ON g.id = m.symbol_id
|
|
98
100
|
WHERE m.role = 1;
|
|
99
|
-
`)}function
|
|
101
|
+
`)}function Ba(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
100
102
|
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
101
103
|
UNION
|
|
102
104
|
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
@@ -119,7 +121,7 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
119
121
|
SELECT u.symbol
|
|
120
122
|
FROM unaffected_definitions u
|
|
121
123
|
JOIN changed_symbols c ON c.symbol = u.symbol
|
|
122
|
-
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 Ja(e){e.exec(`
|
|
123
125
|
DELETE FROM main.mentions
|
|
124
126
|
WHERE chunk_id IN (
|
|
125
127
|
SELECT c.id
|
|
@@ -141,7 +143,7 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
141
143
|
);
|
|
142
144
|
DELETE FROM main.documents
|
|
143
145
|
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
144
|
-
`)}function
|
|
146
|
+
`)}function Ha(e){e.exec(`
|
|
145
147
|
UPDATE main.global_symbols
|
|
146
148
|
SET display_name = NULL,
|
|
147
149
|
kind = NULL,
|
|
@@ -183,7 +185,7 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
183
185
|
WHERE source.symbol = main.global_symbols.symbol
|
|
184
186
|
)
|
|
185
187
|
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
186
|
-
`)}function
|
|
188
|
+
`)}function qa(e){let t=M(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=M(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=M(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)
|
|
187
189
|
SELECT id + ?, language, relative_path, position_encoding, text
|
|
188
190
|
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
189
191
|
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
@@ -198,15 +200,15 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
198
200
|
r.start_line, r.start_char, r.end_line, r.end_char
|
|
199
201
|
FROM incremental.defn_enclosing_ranges r
|
|
200
202
|
JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
201
|
-
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 za(e){e.exec(`
|
|
202
204
|
DELETE FROM main.global_symbols
|
|
203
205
|
WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
204
206
|
AND NOT EXISTS (
|
|
205
207
|
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
206
208
|
);
|
|
207
|
-
`)}function
|
|
209
|
+
`)}function Ya(e,t,n){let r=M(e,"SELECT COUNT(*) AS value FROM main.documents"),i=M(e,`SELECT COUNT(*) AS value
|
|
208
210
|
FROM main.documents d
|
|
209
|
-
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 Qa(e){let t=wt(e,"main",!0),n=wt(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 wt(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
|
|
210
212
|
FROM ${t}.documents d
|
|
211
213
|
${r}
|
|
212
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
|
|
@@ -228,11 +230,13 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
228
230
|
JOIN ${t}.documents d ON d.id = c.document_id
|
|
229
231
|
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
230
232
|
${r}
|
|
231
|
-
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[
|
|
232
|
-
`);u.set(l
|
|
233
|
-
`)}function
|
|
234
|
-
`;)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 nt(e){try{let t=_o(e,"utf-8"),n=JSON.parse(Ho(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as qo}from"crypto";import{copyFileSync as En,existsSync as _,linkSync as Jo,mkdirSync as kn,readFileSync as jn,readdirSync as Dn,renameSync as it,rmSync as pe,statSync as zo}from"fs";import{basename as de,dirname as q,join as S,relative as Fn}from"path";var ge=1,Yo=".scipquery-generations";function On(e){let t=me(e.outputDb),n=Qo(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||rt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),rt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),rt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=he(e.metaPath,e.outputDb),i={version:ge,currentGeneration:r,...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:(e.now??(()=>new Date))().toISOString()};return R(S(t,"state.json"),i,{spacing:2,trailingNewline:!0}),{currentGeneration:r,...n?{previousGeneration:n}:{}}}function _n(e){try{let t=JSON.parse(jn(S(me(e),"state.json"),"utf8"));return t.version!==ge||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!Zo(t.previousGeneration)||!ea(t.publication)?null:t}catch{return null}}function Mn(e,t,n=()=>new Date){if(!_(e)||!_(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=_n(e),i={version:ge,currentGeneration:he(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return R(S(me(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function fe(e,t=S(q(e),"meta.json")){let n=S(me(e),"state.json");if(!_(n))return{state:"legacy",statePath:n};let r=_n(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=he(t,e),o=r.currentGeneration===i,a=r.previousGeneration?_(S(q(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 me(e){return S(q(e),Yo)}function Qo(e,t){if(!_(e.outputDb))return;let n=he(e.metaPath,e.outputDb),r=S(t,n),i=S(r,de(e.outputDb)),o=_(e.metaPath)?S(r,de(e.metaPath)):void 0;if(!_(i)){let a=`${r}.${process.pid}.${Date.now()}.tmp`;pe(a,{recursive:!0,force:!0}),kn(a,{recursive:!0});let s=S(a,de(e.outputDb));try{Jo(e.outputDb,s)}catch{En(e.outputDb,s)}o&&En(e.metaPath,S(a,de(e.metaPath))),kn(t,{recursive:!0}),it(a,r)}return Xo(t,n),{generationIdentity:n,databasePath:Fn(q(e.outputDb),i),...o?{metadataPath:Fn(q(e.outputDb),o)}:{}}}function Xo(e,t){for(let n of Dn(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||pe(S(e,n.name),{recursive:!0,force:!0});for(let n of Dn(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&pe(S(e,n.name),{recursive:!0,force:!0})}function he(e,t){let n=qo("sha256").update(`sqlite-generation-v${ge}\0`);_(e)&&n.update(Ko(jn(e,"utf8")));let r=zo(t);return n.update(`\0${r.size}`),n.digest("hex")}function Ko(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 rt(e,t){pe(`${t}.tmp-replace`,{force:!0}),it(e,`${t}.tmp-replace`),it(`${t}.tmp-replace`,t)}function Zo(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 ea(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")}import{createHash as la}from"crypto";import{existsSync as J,mkdirSync as da,readFileSync as Y,readdirSync as ut,renameSync as pa,rmSync as tr,writeFileSync as ga}from"fs";import{join as I}from"path";import{createHash as ta}from"crypto";import{existsSync as at,mkdirSync as na,readFileSync as ye,readdirSync as Ku,renameSync as ra,rmSync as Zu,writeFileSync as ia}from"fs";import{join as $}from"path";import{create as Cn,fromBinary as An,toBinary as oa}from"@bufbuild/protobuf";import{deserializeSCIP as Se,DocumentSchema as st,IndexSchema as Nn,serializeSCIP as Vn}from"@c4312/scip";var $n=1,aa="typescript-scip-fragments";function Gn(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=A(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=An(st,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Vn(Cn(Nn,{documents:n,externalSymbols:[]})),i=Se(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function be(e){let t=$(e,aa);return{rootDir:t,blobDir:$(t,"blobs"),generationDir:$(t,"generations")}}function sa(e){let t=Se(e.indexBytes);Zn(t.metadata,er(e)),Kn(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=A(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=oa(st,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?N(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:N(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(zn(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Yn(e,r);return Qn(e.cacheDir,i),i}function Un(e){let t=be(e.cacheDir);if(!at(ct(t,e.generationIdentity)))return sa(e);let n=Wn({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 Bn(e){let t=Wn({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=A(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,zn(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Yn(e,[...n.values()]);return Qn(e.cacheDir,i),i}function Wn(e){let t=be(e.cacheDir),n=ct(t,e.generationIdentity),r;try{r=Xn(ye(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=$(t.blobDir,`${o.blobHash}.scipdoc`),s=ye(a);if(s.byteLength!==o.byteLength||N(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Hn(e){let t=Jn(e);return ot(t.baseIndex,t.completeDocuments,"assembled")}function qn(e){let t=Jn(e);return ca(t.deletedAffectedPaths),{completeIndexBytes:ot(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:ot(t.baseIndex,t.affectedDocuments,"affected")}}function Jn(e){let t=Se(e.baseIndexBytes);Zn(t.metadata,er(e)),Kn(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=A(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=A(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 l=An(st,u.bytes);if(l.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${l.relativePath}`);i.push(l),o.push(l)}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 ot(e,t,n){let r=Vn(Cn(Nn,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Se(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function ca(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function zn(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=A(t.relativePath),i=Buffer.from(t.bytes),o=N(i),a=be(e);na(a.blobDir,{recursive:!0});let s=$(a.blobDir,`${o}.scipdoc`);if(at(s)){let c=ye(s);if(c.byteLength!==i.byteLength||N(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;ia(c,i),ra(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Yn(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:$n,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Qn(e,t){let n=be(e),r=ct(n,t.generationIdentity);if(at(r)){let i=Xn(ye(r,"utf8"));if(Ln(i)!==Ln(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}R(r,t,{spacing:2,trailingNewline:!0})}function Ln(e){return N(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Xn(e){let t=JSON.parse(e);if(t.version!==$n||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(A(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function ct(e,t){return $(e.generationDir,ua(t))}function ua(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${N(e)}.json`}function Kn(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Zn(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 er(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function A(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 N(e){return ta("sha256").update(e).digest("hex")}var rr=1,ir=64*1024*1024,fa="typescript-scip-overlays";function or(e){let t=cr(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=pt(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,ma(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:rr,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 ha(e.cacheDir,i),i}function ar(e){let t=cr(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=Y(I(Q(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||z(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 Hn({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function sr(e,t){let n=Q(e),r=I(n,"generations");if(!J(r))return;let i=new Set(t.map(dt)),o=new Set;for(let s of ut(r).filter(c=>i.has(c))){let c=lt(Y(I(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of ut(r))i.has(s)||tr(I(r,s),{force:!0});let a=I(n,"blobs");if(J(a))for(let s of ut(a))o.has(s)||tr(I(a,s),{force:!0})}function cr(e,t){let n=I(Q(e),"generations",dt(t));if(!J(n))return null;let r=lt(Y(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function ma(e,t){let n=pt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=z(r),o=I(Q(e),"blobs");da(o,{recursive:!0});let a=I(o,`${i}.scipdoc`);if(J(a)){let s=Y(a);if(s.byteLength!==r.byteLength||z(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;ga(s,r),pa(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function ha(e,t){let n=I(Q(e),"generations",dt(t.generationIdentity));if(J(n)){let r=lt(Y(n,"utf8"));if(nr(r)!==nr(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}R(n,t,{spacing:2,trailingNewline:!0})}function lt(e){let t=JSON.parse(e);if(t.version!==rr||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(pt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function Q(e){return I(e,fa)}function dt(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${z(e)}.json`}function nr(e){return z(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function pt(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 z(e){return la("sha256").update(e).digest("hex")}import{existsSync as ya,readFileSync as Sa,readdirSync as ba,statSync as Ra}from"fs";import h from"path";var xa=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function X(e,t=[]){let n=h.resolve(e),r=t.flatMap(c=>Pa(n,c));if(r.length>0)return ur(n,lr(r));let i=va(n),o=lr(i),a=wa(n,o)?[n,...o]:o,s=a.length>0?a:[n];return ur(n,s)}function ur(e,t){return[...new Set(t.map(n=>Ea(e,n)))].sort((n,r)=>n.localeCompare(r))}function va(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=ba(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=h.join(r,o.name);if(o.isDirectory()){!xa.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Ia(a)&&t.push(h.dirname(a))}}return t}function Pa(e,t){let n=t.trim();if(!n)return[];let r=h.resolve(e,n);if(!U(e,r))return[];try{let i=Ra(r);if(i.isDirectory())return[r];if(i.isFile()&&dr(h.basename(r)))return[h.dirname(r)]}catch{return[]}return[]}function Ia(e){if(!dr(h.basename(e)))return!1;let t=pr(e);return t?h.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function dr(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function lr(e){let t=[...new Set(e.map(n=>h.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&ka(n,r)))}function wa(e,t){if(t.length===0||t.some(r=>h.resolve(r)===e))return!1;let n=h.join(e,"tsconfig.json");return ya(n)&&Ta(n)}function Ta(e){let n=pr(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!h.extname(r))):!1}function pr(e){try{let t=JSON.parse(Sa(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Ea(e,t){let n=h.relative(e,t);return n?n.split(h.sep).join("/"):"."}function ka(e,t){let n=h.relative(e,t);return!!n&&!n.startsWith("..")&&!h.isAbsolute(n)}import{createHash as Ya}from"crypto";import{existsSync as mt,readFileSync as Ir,statSync as Qa,writeFileSync as ht}from"fs";import{join as Xa}from"path";import{readFileSync as gr}from"fs";import{createRequire as Da}from"module";import{dirname as Fa,isAbsolute as Sl,relative as bl,resolve as Rl,sep as xl}from"path";var fr=Da(import.meta.url),ja=1,mr="0.4.0";function gt(){let e=Oa();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Oa(){try{let e=fr.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(gr(e,"utf8"));if(t.version!==mr)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${mr}`};let n=Fa(e),r=fr.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(gr(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:_a(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function _a(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${ja}`}import{createHash as Ma}from"crypto";import{readFileSync as La}from"fs";import{dirname as Ca,join as Re}from"path";var xe=2,Aa="typescript-index";function hr(e){let t=Re(e,Aa);return{rootDir:t,requestDir:Re(t,"requests"),responseDir:Re(t,"responses")}}function yr(e){try{let t=JSON.parse(La(Re(Ca(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Ma("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 Na}from"crypto";import{existsSync as Va,mkdirSync as Sr,readFileSync as $a,rmSync as br}from"fs";import{resolve as ft}from"path";var Ga=12e4,Ua=5,ve=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=ft(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Ja(),this.runtime=n.runtime??za}request(t){let n=At(this.cacheDir),r=hr(this.cacheDir),i=Ne(n.statePath);if(!Rr(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),a=ft(r.requestDir,`${o}.json`),s=ft(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;Sr(r.requestDir,{recursive:!0}),Sr(r.responseDir,{recursive:!0}),R(a,{protocolVersion:xe,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Va(s))return Ba($a(s,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=Ne(n.statePath);if(!Rr(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Ua)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{br(a,{force:!0}),br(s,{force:!0})}}};function Rr(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Ct,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===xe&&n.isProcessAlive(e.pid)&&(r||i)}function Ba(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==xe||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=Wa(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 Wa(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(Ha)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:qa(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 Ha(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 qa(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Ja(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Ga}var za={now:Date.now,randomId:Na,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:V};function Ka(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=ae(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"||!Ve(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=se(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=Za([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=xr(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=xr(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=Pr(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=Pr(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:vr(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:vr(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 Za(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 wr(e){let t=Date.now();try{if(!mt(e.previousDbPath)||!mt(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=gt();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new L({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=re(o,{includeIgnored:!1}).filter(Ve).sort(),s=ie(o)}finally{o.close()}let c=performance.now()-n,u=Ka({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?X(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:mt(Xa(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let l=yr(e.previousDbPath);if(!l)throw new Error("published TypeScript base generation unavailable");n=performance.now();let d=new ve({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:l}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),f=performance.now()-n,g=Qa(e.previousShardPath).size>=ir;n=performance.now();let w=g?null:Ir(e.previousShardPath),D=g?{completeIndexBytes:null,affectedIndexBytes:Gn(d.fragments)}:qn({packageVersion:r.packageVersion,baseIndexBytes:w,fragments:d.fragments}),F=performance.now()-n;n=performance.now(),g?or({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:d.fragments}):(Un({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:w,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),Bn({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:d.fragments,documentIdentities:u.nextDocumentIdentities}));let y=performance.now()-n;n=performance.now(),D.completeIndexBytes&&ht(e.candidateShardPath,D.completeIndexBytes),ht(e.candidateAffectedScipPath,D.affectedIndexBytes);let x=performance.now()-n,v={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:d.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(d.fragments.map(ne=>[ne.relativePath,ne.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:d.durationMs,assemblyMs:F,fragmentStoreMs:y,writeMs:x}};return e.onStatus(`Incremental TypeScript index emitted ${v.affectedFiles.length} affected document(s) in ${(v.durationMs/1e3).toFixed(3)}s (${v.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${F.toFixed(0)}ms, fragments ${y.toFixed(0)}ms, write ${x.toFixed(0)}ms).`),v}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 Tr(e){let t=gt();if(!t.available)throw new Error(t.reason);let n=ar({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Ir(e.baseShardPath),packageVersion:t.packageVersion});ht(e.candidateShardPath,n)}function xr(e,t,n){let r=e.files.filter(i=>Lt(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 yt(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function vr(e,t){return yt(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function Pr(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=$t({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,yt(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function yt(e){return Ya("sha256").update(e).digest("hex")}import{execFile as es}from"child_process";import{existsSync as Pe,renameSync as bt,rmSync as Rt,statSync as ts}from"fs";import{cpus as ns}from"os";import{join as Er}from"path";function rs(e,t,n){if(!e.defaultOutputPath)return;let r=Er(t,e.defaultOutputPath);n!==r&&Pe(r)&&bt(r,n)}function is(e,t,n){if(!e.defaultOutputPath)return null;let r=Er(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Rt(i,{force:!0}),Pe(r)?(bt(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function os(e){e&&(Rt(e.defaultOutputPath,{force:!0}),e.backupPath&&Pe(e.backupPath)&&bt(e.backupPath,e.defaultOutputPath))}function as(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,ns().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function kr(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=as(o.length,r),c=await cs(o,s,u=>St(u,t,n));if(s>1){let u=new Map;for(let l of c.filter(p=>p.skipped)){let p=o.find(d=>d.id===l.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),u.set(p.id,await St(p,t,n)))}a.push(...c.map(l=>u.get(l.id)??l))}else a.push(...c);for(let u of i)a.push(await St(u,t,n));return a.sort((u,l)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===l.id))}async function St(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Rt(e.scipPath,{force:!0});let r=is(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{await ss(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),rs(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),u=`${e.resolvedBinary} indexer failed: ${c.split(`
|
|
235
|
-
`)
|
|
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=Ca("sha256");for(let m of p.sort())l.update(m).update(`
|
|
234
|
+
`);u.set(d,l.digest("hex"))}return u}function M(e,t){return e.prepare(t).get().value}import{readFileSync as Xa,writeFileSync as Ka}from"fs";function N(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function mr(e){let t=e.readFingerprint(),n=Za(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return es(e.cachePath,e.readFingerprint(),r),r}function Za(e,t){try{let n=JSON.parse(Xa(e,"utf-8"));return fr(n.fingerprint)===fr(t)?{result:n.result}:null}catch{return null}}function es(e,t,n){Ka(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
235
|
+
`)}function fr(e){return JSON.stringify(e)}import{createHash as ts}from"crypto";import{existsSync as kt,readFileSync as ns,readdirSync as rs}from"fs";import{dirname as Et,join as Fe,relative as is,resolve as Tt,sep as hr}from"path";function yr(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=xr(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Sr(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=xr(s,e);c&&c!==i&&a.add(c)}}return os(e,r)}function br(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 Dt(e){if(e===".")return"root";let t=ts("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Rr(e,t){let n=Tt(e),r={};for(let i of t)r[i]=as(n,i);return r}function xr(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 os(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 as(e,t){let n=t==="."?e:Fe(e,t),r=ss(n),i=cs(n),o=i?us(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 ss(e){let t=Fe(e,"package.json");if(!kt(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Ft(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 cs(e){let t=Fe(e,"tsconfig.json");if(kt(t))return t;let n;try{n=rs(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Fe(e,n[0]):void 0}function us(e,t){let n=Ft(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=ds(n.value,e,t),i=Ir(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function ds(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Et(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=vr(s,i,n);c&&o.add(c)}return[...o]}function Ir(e,t,n,r){let i=ls(t);if(i)return{pathsTargets:ps(i,Et(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=gs(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=Ft(o);return a.ok?Ir(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function ls(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 ps(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=vr(o,t,n);a&&r.add(a)}return[...r]}function gs(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=Tt(Et(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(hr).includes("node_modules")&&K(n,i)&&kt(i))return i}function vr(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Tt(t,r===""?".":r);if(!K(n,i))return;let a=is(n,i).split(hr).join("/");return a===""?".":a}function fs(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 Ft(e){try{let t=ns(e,"utf-8"),n=JSON.parse(fs(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as li,randomUUID as Jt}from"crypto";import{closeSync as pi,constants as Hs,copyFileSync as si,existsSync as U,lstatSync as qs,mkdirSync as C,mkdtempSync as gi,openSync as fi,readdirSync as zs,readFileSync as F,realpathSync as Ys,renameSync as z,rmSync as V,statSync as Qs,unlinkSync as Wt,writeFileSync as mi}from"fs";import{dirname as hi,join as f,resolve as pe}from"path";import{setTimeout as Xs}from"timers/promises";import{pathToFileURL as ci}from"url";import{deserializeSCIP as yi}from"@c4312/scip";import Ks from"better-sqlite3";import{createRequire as ms}from"module";var hs=ms(import.meta.url),Pr=ys().version;function ys(){for(let e of["../package.json","../../package.json"])try{return hs(e)}catch{}return{version:"0.0.0"}}import{lstatSync as js,readdirSync as _s}from"fs";import{join as Cs,relative as As,resolve as $t,sep as Ls}from"path";import{createHash as Ss}from"crypto";import{existsSync as jt,mkdirSync as bs,readFileSync as Oe,readdirSync as Yl,renameSync as Rs,rmSync as Ql,writeFileSync as xs}from"fs";import{join as Y}from"path";import{create as kr,fromBinary as Er,toBinary as Is}from"@bufbuild/protobuf";import{deserializeSCIP as je,DocumentSchema as _t,IndexSchema as Tr,serializeSCIP as Dr}from"@c4312/scip";var _e=1,re="typescript-scip-fragments";function Fr(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=H(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=Er(_t,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Dr(kr(Tr,{documents:n,externalSymbols:[]})),i=je(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Ce(e){let t=Y(e,re);return{rootDir:t,blobDir:Y(t,"blobs"),generationDir:Y(t,"generations")}}function vs(e){let t=je(e.indexBytes);Ur(t.metadata,Wr(e)),Vr(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=H(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=Is(_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(Mr(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Nr(e,r);return $r(e.cacheDir,i),i}function Or(e){let t=Ce(e.cacheDir);if(!jt(Ct(t,e.generationIdentity)))return vs(e);let n=_r({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 jr(e){let t=_r({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=H(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,Mr(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Nr(e,[...n.values()]);return $r(e.cacheDir,i),i}function _r(e){let t=Ce(e.cacheDir),n=Ct(t,e.generationIdentity),r;try{r=Gr(Oe(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=Y(t.blobDir,`${o.blobHash}.scipdoc`),s=Oe(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 Cr(e){let t=Lr(e);return Ot(t.baseIndex,t.completeDocuments,"assembled")}function Ar(e){let t=Lr(e);return Ps(t.deletedAffectedPaths),{completeIndexBytes:Ot(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Ot(t.baseIndex,t.affectedDocuments,"affected")}}function Lr(e){let t=je(e.baseIndexBytes);Ur(t.metadata,Wr(e)),Vr(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=H(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=H(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=Er(_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 Ot(e,t,n){let r=Dr(kr(Tr,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=je(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Ps(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Mr(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=H(t.relativePath),i=Buffer.from(t.bytes),o=q(i),a=Ce(e);bs(a.blobDir,{recursive:!0});let s=Y(a.blobDir,`${o}.scipdoc`);if(jt(s)){let c=Oe(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`;xs(c,i),Rs(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Nr(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:_e,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function $r(e,t){let n=Ce(e),r=Ct(n,t.generationIdentity);if(jt(r)){let i=Gr(Oe(r,"utf8"));if(wr(i)!==wr(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}b(r,t,{spacing:2,trailingNewline:!0})}function wr(e){return q(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Gr(e){let t=JSON.parse(e);if(t.version!==_e||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(H(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Ct(e,t){return Y(e.generationDir,ws(t))}function ws(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${q(e)}.json`}function Vr(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Ur(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 Wr(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function H(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 Ss("sha256").update(e).digest("hex")}import{createHash as ks}from"crypto";import{existsSync as ie,mkdirSync as Es,readFileSync as ae,readdirSync as At,renameSync as Ts,rmSync as Br,writeFileSync as Ds}from"fs";import{join as D}from"path";var Ae=1,Hr=64*1024*1024,se="typescript-scip-overlays";function qr(e){let t=Qr(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=Nt(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,Fs(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Ae,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 Os(e.cacheDir,i),i}function zr(e){let t=Qr(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=ae(D(ce(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||oe(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 Cr({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function Yr(e,t){let n=ce(e),r=D(n,"generations");if(!ie(r))return;let i=new Set(t.map(Mt)),o=new Set;for(let s of At(r).filter(c=>i.has(c))){let c=Lt(ae(D(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of At(r))i.has(s)||Br(D(r,s),{force:!0});let a=D(n,"blobs");if(ie(a))for(let s of At(a))o.has(s)||Br(D(a,s),{force:!0})}function Qr(e,t){let n=D(ce(e),"generations",Mt(t));if(!ie(n))return null;let r=Lt(ae(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Fs(e,t){let n=Nt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=oe(r),o=D(ce(e),"blobs");Es(o,{recursive:!0});let a=D(o,`${i}.scipdoc`);if(ie(a)){let s=ae(a);if(s.byteLength!==r.byteLength||oe(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Ds(s,r),Ts(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Os(e,t){let n=D(ce(e),"generations",Mt(t.generationIdentity));if(ie(n)){let r=Lt(ae(n,"utf8"));if(Jr(r)!==Jr(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}b(n,t,{spacing:2,trailingNewline:!0})}function Lt(e){let t=JSON.parse(e);if(t.version!==Ae||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(Nt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function ce(e){return D(e,se)}function Mt(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${oe(e)}.json`}function Jr(e){return oe(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Nt(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 oe(e){return ks("sha256").update(e).digest("hex")}var ue=1,Gt="language-indexes",Xr=["index.db","index.scip","meta.json"],Kr=[Gt,re,se];function Le(e){let t=[];for(let n of Xr)Ms(e,n),t.push(n);for(let n of Kr)Zr(e,n,t);return{version:ue,files:t.sort()}}function Me(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(!Xr.includes(e)&&!Kr.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function j(e,t){let n=Me(t),r=$t(e),i=$t(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Ls}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function Zr(e,t,n){let r=Cs(e,t),i;try{i=_s(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()?Zr(e,a,n):o.isFile()&&n.push(Me(a))}}function Ms(e,t){let n=j(e,t),r;try{r=js(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(As($t(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as Ns}from"crypto";import{copyFileSync as ei,existsSync as $,linkSync as $s,mkdirSync as ti,readFileSync as ii,readdirSync as ni,renameSync as Ut,rmSync as $e,statSync as Gs}from"fs";import{basename as Ne,dirname as de,join as P,relative as ri}from"path";var Q=1,Ge=".scipquery-generations";function Ve(e){let t=Ue(e.outputDb),n=Vs(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||Vt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Vt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Vt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=We(e.metaPath,e.outputDb),i={version:Q,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 oi(e){try{let t=JSON.parse(ii(P(Ue(e),"state.json"),"utf8"));return t.version!==Q||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!Bs(t.previousGeneration)||!Js(t.publication)?null:t}catch{return null}}function ai(e,t,n=()=>new Date){if(!$(e)||!$(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=oi(e),i={version:Q,currentGeneration:We(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return b(P(Ue(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function G(e,t=P(de(e),"meta.json")){let n=P(Ue(e),"state.json");if(!$(n))return{state:"legacy",statePath:n};let r=oi(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=We(t,e),o=r.currentGeneration===i,a=r.previousGeneration?$(P(de(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 Ue(e){return P(de(e),Ge)}function Vs(e,t){if(!$(e.outputDb))return;let n=We(e.metaPath,e.outputDb),r=P(t,n),i=P(r,Ne(e.outputDb)),o=$(e.metaPath)?P(r,Ne(e.metaPath)):void 0;if(!$(i)){let a=`${r}.${process.pid}.${Date.now()}.tmp`;$e(a,{recursive:!0,force:!0}),ti(a,{recursive:!0});let s=P(a,Ne(e.outputDb));try{$s(e.outputDb,s)}catch{ei(e.outputDb,s)}o&&ei(e.metaPath,P(a,Ne(e.metaPath))),ti(t,{recursive:!0}),Ut(a,r)}return Us(t,n),{generationIdentity:n,databasePath:ri(de(e.outputDb),i),...o?{metadataPath:ri(de(e.outputDb),o)}:{}}}function Us(e,t){for(let n of ni(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||$e(P(e,n.name),{recursive:!0,force:!0});for(let n of ni(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&$e(P(e,n.name),{recursive:!0,force:!0})}function We(e,t){let n=Ns("sha256").update(`sqlite-generation-v${Q}\0`);$(e)&&n.update(Ws(ii(e,"utf8")));let r=Gs(t);return n.update(`\0${r.size}`),n.digest("hex")}function Ws(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 Vt(e,t){$e(`${t}.tmp-replace`,{force:!0}),Ut(e,`${t}.tmp-replace`),Ut(`${t}.tmp-replace`,t)}function Bs(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 Js(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 Ht=1,ui="SCIP_QUERY_SHARED_CACHE",Bt=JSON.stringify({cliVersion:Pr,artifactCatalogVersion:ue,sqliteGenerationStoreVersion:Q,typescriptFragmentStoreVersion:_e,typescriptOverlayStoreVersion:Ae}),Si="manifest.json",Zs="shared-cache.json",qt=[Gt,re,se];function Be(e,t){if(!e.clean||!e.treeOid)return;let n=fe(JSON.stringify({version:Ht,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Bt}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Bt,generationId:n,repositoryCacheDir:jn(e.repositoryId)}}function bi(e,t,n){if(process.env[ui]==="0")return`${ui}=0`;if(!_n(n))return"explicit cache or database override";if(pe(t)!==pe(f(On(e),"index.db")))return"index database is outside the managed worktree cache"}function _(e,t=!0){let n=Yt(e),r;try{r=tc(F(f(n,Si),"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=Qs(o);if(!a.isFile()||a.size!==i.size||fe(F(o))!==i.sha256)return null}}catch{return null}return r}function Ri(e){let t=_(e.snapshot);if(t)return t;if(!Pi(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=di(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=Le(e.sourceCacheDir),i=f(e.snapshot.repositoryCacheDir,"generations");C(i,{recursive:!0});let o=gi(f(i,`.tmp-${process.pid}-`));try{let a=[];for(let p of r.files){let l=j(e.sourceCacheDir,p),m=j(o,p);ge(l,m);let g=F(m);a.push({path:p,size:g.byteLength,sha256:fe(g)})}let s=yi(F(f(o,"index.scip"))).metadata?.projectRoot;if(!s)throw new Error("shared SCIP generation has no project root metadata");let c=Qt(e.sourceProjectRoot);if(s!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(di(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Ht,artifactCatalogVersion:ue,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,Si),u,{spacing:2,trailingNewline:!0});let d=Yt(e.snapshot);try{if(U(d)&&!_(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=_(e.snapshot);if(l)return l;throw p}return u}finally{V(o,{recursive:!0,force:!0})}}function zt(e){let t=Yt(e.snapshot);C(e.targetCacheDir,{recursive:!0});let n=te(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=gi(f(e.targetCacheDir,".shared-hydrate-")),uc(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=j(t,c.path),d=j(r,c.path);ge(u,d);let p=F(d);if(p.byteLength!==c.size||fe(p)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Qt(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&or(j(r,c.path),e.manifest.scipProjectRoot,a);if(!Pi(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=ac(e.targetCacheDir,r),o=!0,sc(r,e.targetCacheDir,i),Ve({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}`);Je(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&cc(e.targetCacheDir,i),a}finally{r&&V(r,{recursive:!0,force:!0}),n.release()}}async function xi(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(C(a,{recursive:!0});i()<=o;){if(_(e))return{kind:"generation-ready"};let c=Jt();try{let u=fi(s,"wx");try{mi(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&&Wt(s)}catch{}}}}catch(u){if(u.code!=="EEXIST")return{kind:"timeout"};let d=Ii(s);if(d&&(d.pid===void 0||!T(d.pid))){ic(s,d);continue}await Xs(r)}}return _(e)?{kind:"generation-ready"}:{kind:"timeout"}}function Je(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:ec(i)};return oc(e.repositoryCacheDir,o,!0),o}function ec(e){return fe(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:pe(e.projectRoot),localCacheDir:pe(e.localCacheDir)}))}function tc(e){let t=JSON.parse(e);if(t.version!==Ht||t.artifactCatalogVersion!==ue||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!==Bt||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(Me(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 ge(e,t){C(hi(t),{recursive:!0});try{si(e,t,Hs.COPYFILE_FICLONE)}catch{si(e,t)}}function nc(e,t,n){C(e,{recursive:!0}),b(f(e,Zs),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function di(e){try{let t=Le(e),n=li("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 rc(e){try{return JSON.parse(F(f(e,"meta.json"),"utf8"))}catch{return}}function Yt(e){return f(e.repositoryCacheDir,"generations",e.generationId)}function Ii(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 ic(e,t){let n=`${e}.reclaim`,r=Jt(),i;try{i=fi(n,"wx")}catch{return!1}try{mi(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
|
|
238
|
+
`)}finally{pi(i)}try{let o=Ii(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Wt(e),!0)}catch{return!1}finally{try{let o=JSON.parse(F(n,"utf8"));o.pid===process.pid&&o.token===r&&Wt(n)}catch{}}}function oc(e,t,n){let r=Gn(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");C(i,{recursive:!0}),b(f(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),nc(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function ac(e,t){let n=f(t,".rollback"),r=new Map,i=new Map;C(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&&ge(c,f(n,"stable",s))}for(let s of qt){let c=f(e,s),u=U(c);if(u){let d=qs(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,Ge),a=U(o);return a&&vi(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);C(hi(a),{recursive:!0}),z(i,a)}let o=f(e,r);U(o)&&z(o,i)}}function cc(e,t){for(let i of qt){let o=f(e,i),a=f(t.root,"managed",i);t.managedDirectories.get(i)?U(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-${Jt()}`;ge(f(t.root,"stable",i),s),V(a,{force:!0}),z(s,a)}let n=f(e,Ge);V(n,{recursive:!0,force:!0});let r=f(t.root,"sqlite-generations");t.generationStoreExisted&&U(r)&&z(r,n)}function vi(e,t){C(t,{recursive:!0});for(let n of zs(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()?vi(r,i):n.isFile()&&ge(r,i)}}function uc(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 Pi(e,t,n,r=!0,i=!0){try{let o=rc(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return le("source validation rejected metadata"),!1;let a=Le(e),s=G(f(e,"index.db"),f(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return le(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new Ks(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=Qt(t),p=(i?a.files.filter(l=>l.endsWith(".scip")):["index.scip"]).every(l=>{let m=yi(F(j(e,l))).metadata?.projectRoot;return m!==u&&le(`source validation rejected SCIP root for ${l}: ${String(m)}`),m===u});return p||le("source validation rejected SCIP project roots"),p}catch(o){return le(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function le(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Qt(e){try{return ci(Ys(e)).href}catch{return ci(pe(e)).href}}function fe(e){return li("sha256").update(e).digest("hex")}import{existsSync as dc,readFileSync as lc,readdirSync as pc,statSync as gc}from"fs";import x from"path";var fc=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function me(e,t=[]){let n=x.resolve(e),r=t.flatMap(c=>hc(n,c));if(r.length>0)return wi(n,ki(r));let i=mc(n),o=ki(i),a=Sc(n,o)?[n,...o]:o,s=a.length>0?a:[n];return wi(n,s)}function wi(e,t){return[...new Set(t.map(n=>Rc(e,n)))].sort((n,r)=>n.localeCompare(r))}function mc(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=pc(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=x.join(r,o.name);if(o.isDirectory()){!fc.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&yc(a)&&t.push(x.dirname(a))}}return t}function hc(e,t){let n=t.trim();if(!n)return[];let r=x.resolve(e,n);if(!K(e,r))return[];try{let i=gc(r);if(i.isDirectory())return[r];if(i.isFile()&&Ei(x.basename(r)))return[x.dirname(r)]}catch{return[]}return[]}function yc(e){if(!Ei(x.basename(e)))return!1;let t=Ti(e);return t?x.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Ei(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function ki(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&&xc(n,r)))}function Sc(e,t){if(t.length===0||t.some(r=>x.resolve(r)===e))return!1;let n=x.join(e,"tsconfig.json");return dc(n)&&bc(n)}function bc(e){let n=Ti(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 Ti(e){try{let t=JSON.parse(lc(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Rc(e,t){let n=x.relative(e,t);return n?n.split(x.sep).join("/"):"."}function xc(e,t){let n=x.relative(e,t);return!!n&&!n.startsWith("..")&&!x.isAbsolute(n)}import{createHash as Uc}from"crypto";import{existsSync as Zt,readFileSync as Gi,statSync as Wc,writeFileSync as en}from"fs";import{join as Bc}from"path";import{readFileSync as Di}from"fs";import{createRequire as Ic}from"module";import{dirname as vc,isAbsolute as Wp,relative as Bp,resolve as Jp,sep as Hp}from"path";var Fi=Ic(import.meta.url),Pc=1,Oi="0.4.0";function Xt(){let e=wc();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function wc(){try{let e=Fi.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(Di(e,"utf8"));if(t.version!==Oi)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${Oi}`};let n=vc(e),r=Fi.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(Di(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:kc(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function kc(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Pc}`}import{createHash as Ec}from"crypto";import{readFileSync as Tc}from"fs";import{dirname as Dc,join as He}from"path";var qe=2,Fc="typescript-index";function ji(e){let t=He(e,Fc);return{rootDir:t,requestDir:He(t,"requests"),responseDir:He(t,"responses")}}function _i(e){try{let t=JSON.parse(Tc(He(Dc(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Ec("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 Oc}from"crypto";import{existsSync as jc,mkdirSync as Ci,readFileSync as _c,rmSync as Ai}from"fs";import{resolve as Kt}from"path";var Cc=12e4,Ac=5,ze=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=Kt(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Gc(),this.runtime=n.runtime??Vc}request(t){let n=wn(this.cacheDir),r=ji(this.cacheDir),i=ut(n.statePath);if(!Li(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),a=Kt(r.requestDir,`${o}.json`),s=Kt(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;Ci(r.requestDir,{recursive:!0}),Ci(r.responseDir,{recursive:!0}),b(a,{protocolVersion:qe,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(jc(s))return Lc(_c(s,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=ut(n.statePath);if(!Li(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Ac)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{Ai(a,{force:!0}),Ai(s,{force:!0})}}};function Li(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Pn,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 Lc(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=Mc(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 Mc(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(Nc)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:$c(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 Nc(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 $c(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Gc(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Cc}var Vc={now:Date.now,randomId:Oc,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:T};function Jc(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=we(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"||!dt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=ke(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=Hc([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Mi(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=Mi(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=$i(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=$i(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Ni(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Ni(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 Hc(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 Vi(e){let t=Date.now();try{if(!Zt(e.previousDbPath)||!Zt(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Xt();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new B({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=xe(o,{includeIgnored:!1}).filter(dt).sort(),s=Ie(o)}finally{o.close()}let c=performance.now()-n,u=Jc({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?me(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:Zt(Bc(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=_i(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let l=new ze({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=Wc(e.previousShardPath).size>=Hr;n=performance.now();let v=g?null:Gi(e.previousShardPath),S=g?{completeIndexBytes:null,affectedIndexBytes:Fr(l.fragments)}:Ar({packageVersion:r.packageVersion,baseIndexBytes:v,fragments:l.fragments}),R=performance.now()-n;n=performance.now(),g?qr({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:l.fragments}):(Or({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:v,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),jr({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&&en(e.candidateShardPath,S.completeIndexBytes),en(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(Re=>[Re.relativePath,Re.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 Ui(e){let t=Xt();if(!t.available)throw new Error(t.reason);let n=zr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Gi(e.baseShardPath),packageVersion:t.packageVersion});en(e.candidateShardPath,n)}function Mi(e,t,n){let r=e.files.filter(i=>xn(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 tn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Ni(e,t){return tn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function $i(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=Tn({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,tn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function tn(e){return Uc("sha256").update(e).digest("hex")}import{execFile as qc}from"child_process";import{existsSync as Ye,renameSync as rn,rmSync as on,statSync as zc}from"fs";import{cpus as Yc}from"os";import{join as Wi}from"path";function Qc(e,t,n){if(!e.defaultOutputPath)return;let r=Wi(t,e.defaultOutputPath);n!==r&&Ye(r)&&rn(r,n)}function Xc(e,t,n){if(!e.defaultOutputPath)return null;let r=Wi(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return on(i,{force:!0}),Ye(r)?(rn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Kc(e){e&&(on(e.defaultOutputPath,{force:!0}),e.backupPath&&Ye(e.backupPath)&&rn(e.backupPath,e.defaultOutputPath))}function Zc(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,Yc().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Bi(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=Zc(o.length,r),c=await tu(o,s,u=>nn(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 nn(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 nn(u,t,n));return a.sort((u,d)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===d.id))}async function nn(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),on(e.scipPath,{force:!0});let r=Xc(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{await eu(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),Qc(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{Kc(r)}if(!Ye(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=zc(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 eu(e,t,n){return new Promise((r,i)=>{qc(e,[...t],n,o=>{o?i(o):r()})})}async function tu(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 Lu from"better-sqlite3";import{existsSync as Mu}from"fs";import{dirname as Nu,join as $u,resolve as Gu}from"path";import{readFileSync as ru,rmSync as iu,statSync as ou,mkdtempSync as au}from"fs";import{tmpdir as su}from"os";import{join as an}from"path";import{Worker as cu}from"worker_threads";function nu(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function X(){return{skippedReferences:0,skippedReferenceReasons:nu(),skippedReferenceSamples:[]}}function Qe(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 Ji(e){return e.length>=8&&qi(e.length)>1}function Hi(e){let t=qi(e.vueFiles.length),n=du(e.vueFiles),r=pu(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=au(an(su(),"scip-query-vue-workers-")),a=new SharedArrayBuffer(4),s=new Int32Array(a),c=uu(),u=Date.now();try{for(let l=0;l<r.length;l++)new cu(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[l],resultPath:an(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(ru(an(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),...X()};for(let l of d)Qe(p,l);return p}finally{iu(o,{recursive:!0,force:!0})}}function qi(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 uu(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function du(e){let t=lu(),n=[];for(let r of e){let i=zi(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 lu(){return Number.POSITIVE_INFINITY}function pu(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:gu(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 gu(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,zi(e.fileName)-e.startOffset)}function zi(e){try{return ou(e).size}catch{return 1}}import{createRequire as fu}from"module";import{existsSync as mu,readFileSync as cn}from"fs";import{dirname as Yi,extname as hu,join as Qi,relative as yu,resolve as Su}from"path";import{pathToFileURL as bu}from"url";function Ru(e){e.transaction(()=>{e.prepare(`
|
|
236
240
|
DELETE FROM mentions
|
|
237
241
|
WHERE chunk_id IN (
|
|
238
242
|
SELECT c.id
|
|
@@ -247,12 +251,12 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
247
251
|
FROM documents
|
|
248
252
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
249
253
|
)
|
|
250
|
-
`).run()})()}function
|
|
254
|
+
`).run()})()}function Xi(e,t){return e.prepare(`
|
|
251
255
|
SELECT relative_path AS relativePath
|
|
252
256
|
FROM documents
|
|
253
257
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
254
258
|
ORDER BY relative_path
|
|
255
|
-
`).all().map(r=>
|
|
259
|
+
`).all().map(r=>Su(t,r.relativePath))}function Ki(e,t){let{vueCore:n,ts:r,volarTs:i}=xu(e),{parsed:o,vueOptions:a}=Iu(n,r,t),s=Yi(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),u=vu(n,r,c),d=Pu(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 xu(e){let t=fu(bu(Qi(e,"package.json")).href);return{vueCore:sn(t,"@vue/language-core",e),ts:sn(t,"typescript",e),volarTs:sn(t,"@volar/typescript",e)}}function Iu(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,Yi(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function vu(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!mu(o))return;let a=cn(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Fu(o))});return r.current=i,i}function Pu(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function sn(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 Zi(e,t,n){let r=wu(e);return i=>{if(!i.name)return null;let o=A(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:ku(c.starts,s.line,2,i.name)}}function wu(e){let t=e.prepare(`
|
|
256
260
|
SELECT
|
|
257
261
|
d.relative_path AS relativePath,
|
|
258
262
|
der.start_line AS startLine,
|
|
@@ -263,22 +267,22 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
263
267
|
JOIN documents d ON d.id = der.document_id
|
|
264
268
|
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
265
269
|
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
266
|
-
`).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 ku(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 eo(e,t,n){let r=_u(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
267
271
|
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
268
272
|
VALUES (?, ?, ?, ?)
|
|
269
|
-
`),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let
|
|
273
|
+
`),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=A(t,u),p=uo(r.name,r.version,d);o.run(p,"default",7,`Vue component|${d}`);let l=Cu(i,r,t,u);l&&(a++,s.set(u,l))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function to(e,t,n,r,i){return e.transaction(()=>(Ru(e),Eu(e,t,n,r),Tu(e,i)))()}function Eu(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
270
274
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
271
275
|
VALUES (?, ?, ?, ?, X'00')
|
|
272
276
|
`),a=e.prepare(`
|
|
273
277
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
274
278
|
VALUES (?, ?, 1)
|
|
275
|
-
`);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=A(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 no(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(un(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function ro(e){let t=new Set,n=[];for(let r of e){let i=io(r);t.has(i)||(t.add(i),n.push(r))}return n}function io(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Tu(e,t){let n=ju(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
|
|
276
280
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
277
281
|
VALUES (?, ?, ?, ?, X'00')
|
|
278
282
|
`),i=e.prepare(`
|
|
279
283
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
280
284
|
VALUES (?, ?, 0)
|
|
281
|
-
`),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=io(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*oo(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 ao(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function un(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Du(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 so(e,t){return A(e,t).startsWith("node_modules/")}function A(e,t){return yu(e,t).replaceAll("\\","/")}function Fu(e){switch(hu(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 co(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=cn(t,"utf-8"),r={text:n,lineStarts:Ou(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Du}}function Ou(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function ju(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 _u(e){try{let t=JSON.parse(cn(Qi(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 Cu(e,t,n,r){let i=A(n,r),o=uo(t.name,t.version,i);return e.get(o)?.id??null}function uo(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function po(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Uu({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Vu(e){return N(J(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),N(po({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function Uu(e){let t=Gu(e.projectRoot,e.tsconfig);if(!Mu(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Lu(e.dbPath);try{let r=Xi(n,e.projectRoot),i=$u(Nu(e.dbPath),"augment-vue-meta.json");return mr({cachePath:i,readFingerprint:()=>Ju(n,e.projectRoot,e.tsconfig),compute:()=>Wu({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 Wu(e){let t=eo(e.db,e.projectRoot,e.vueFiles),n=Bu(e,t),r=ro(n.occurrences),i=to(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:ed(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Zu(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Bu(e,t){if(Ji(e.vueFiles))return Hi({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=Hu({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return qu({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Ju(e,t,n){let r=e.prepare(`
|
|
282
286
|
SELECT
|
|
283
287
|
(SELECT COUNT(*) FROM documents) AS documents,
|
|
284
288
|
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
@@ -287,13 +291,13 @@ import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42D
|
|
|
287
291
|
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
288
292
|
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
289
293
|
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
290
|
-
`).get();return{version:3,tsconfig:n,files:
|
|
291
|
-
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function ic(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function zr(e,t,n){let r=G();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:T(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function wt(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 Tt(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 oc(e,t){let n=Tt(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=Tt(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function ac(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(...Tt(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function sc(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return oc(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function cc(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of lc(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&&(Qr(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function Qr(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 uc(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function lc(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 l=dc(r,u.textSpan.start,o,i.text);l!==null&&s.push(l)}return s}function dc(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=It(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function ep(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=vc(e),a=Date.now();Te(m(o.outputScip),{recursive:!0}),Te(m(o.outputDb),{recursive:!0});let s=e.languages??He(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=B("reindex.fingerprint",()=>tu(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),u=await W("reindex.lock",()=>zc(b(m(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:s.length}),l=null;try{let p=null,d=B("reindex.reuse-check",()=>(p=Pc({opts:e,paths:o,languages:s,fingerprint:c,start:a,onStatus:r}),p),()=>({languages:s.length,reused:p!==null}));if(d)return d;await W("reindex.scip-cli-ready",()=>$c(i,r));let f=wc(o);l=f.runDir;let g;return await W("reindex.fresh",async()=>(g=await Tc({opts:e,languages:s,projectRoot:t,paths:o,tempPaths:f,fingerprint:c,start:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),g),()=>({languages:s.length,reused:g?.reused,skipped:g?.skipped.length}))}catch(p){throw gi(o.metaPath,Fe({trigger:e.trigger,result:"failed",start:a,error:p instanceof Error?p.message:String(p)})),p}finally{l&&M(l,{recursive:!0,force:!0}),u()}}function vc(e){let t=e.outputScip??b(e.projectRoot,"index.scip"),n=e.outputDb??b(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:b(m(n),"meta.json")}}function Pc(e){let t=fe(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!k(e.paths.outputScip)||!k(e.paths.outputDb)||!nu(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;O(C(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=Fe({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return gi(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:Ic(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Ic(e,t,n,r){let i=ui(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:K(i[o]),outputBytes:Z(Dt(e.outputDb,o)),durationMs:0}))}function wc(e){let t=mc(b(m(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:b(t,we(e.outputScip)),tempOutputDb:b(t,we(e.outputDb)),tempMetaPath:b(t,we(e.metaPath))}}async function Tc(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await W("reindex.language-indexers",async()=>(n=await kc(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:l}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Ec({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=B("reindex.publish",()=>Ac(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(w=>w.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:f,shards:c}}let p=B("reindex.publish",()=>Cc(e,t,i,o,a,s,u,l),{mode:l?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),d=p.durationMs;return e.onStatus(`Done in ${(d/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:d,reused:!1,skipped:o,lastRefresh:p,shards:c}}function Ec(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!k(e.run.paths.outputScip)||!k(e.run.paths.outputDb))return!1;let t=fe(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 kc(e,t){let n=_c({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[P,Ot]of n)Ot.reused&&(r.push({language:P,scipPath:Ot.scipPath}),i.add(P));for(let P of i)e.onStatus(`Reusing cached ${P} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=fe(e.paths.outputDb,e.paths.metaPath),s=te(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),l=o&&!o.reused&&c?wr({projectRoot:e.projectRoot,cacheDir:m(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:ee(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:ee(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:kt(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(l?["typescript"]:[]),d=l?void 0:Dc(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:w}=Gc({languages:e.languages.filter(P=>!i.has(P)&&!p.has(P)),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:d?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),D=d?f.filter(P=>P.language!=="typescript"||d.missedProjectIds.has(P.id)):f,F=await kr(D,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),y=[];if(d){jc(e.paths.outputDb,F);let P=w.typescript??e.tempPaths.tempOutputScip;y=Oc({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:P,reusedProjects:d.reusedProjects})}let x=[...F,...y],{indexedOutputs:v}=Bc(x,g),ne=l?[{language:"typescript",scipPath:l.scipPath}]:[],jt=[...r,...ne,...v];Wc(jt,g,e.languages,e.opts.allowPartial,e.onStatus);let fi=l?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:l.scipPath,outputScipPath:l.scipPath,durationMs:l.durationMs,command:"watch-service:typescript-index",outputBytes:Z(l.scipPath)??void 0}]:[],mi=Mc(n,[...F,...fi],d?{outputDb:e.paths.outputDb,classification:d.classification}:void 0);return{indexedOutputs:jt,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Lc(n,e.languages),shards:mi,typescriptProjectShardContext:d?{projects:d.allProjects,fingerprints:d.fingerprints}:void 0,incrementalTypeScript:l??void 0}}function Dc(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=X(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Pn(e.projectRoot,r),o=Rn(n.fingerprint.files,r),a=xn(r,i),s=vn(r,o,a),c=te(e.paths.metaPath),l=Fc(c,s,g=>k(De(e.paths.outputDb,g))),p=[...l.entries()].filter(([,g])=>g.reused).map(([g])=>g),d=new Set(p),f=new Set(r.filter(g=>!d.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:p,missedProjectIds:f}}function Fc(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(E(a)!==E(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 jc(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=De(e,r);Te(m(i),{recursive:!0}),Ee(n.scipPath,i)}}function Oc(e){return e.reusedProjects.map((t,n)=>{let r=De(e.outputDb,t),i=ee(e.tempOutputScip,"typescript-project-cached",n);return Ee(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Z(i)??void 0}})}function _c(e){let t=te(e.paths.metaPath),n=ui(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Dt(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(!k(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(E(s)!==E(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 Mc(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:K(o.fingerprint),outputBytes:Z(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?K(s.fingerprint):o?K(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:K(o.fingerprint),outputBytes:Z(De(n.outputDb,i)),durationMs:0});return r}function K(e){return gc("sha256").update(E(e)).digest("hex").slice(0,16)}function Z(e){try{return Sc(e).size}catch{return null}}function Lc(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Cc(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(Xr(e.paths.outputDb,n),u=Kr(n,e.tempPaths.tempOutputScip,e.onStatus));let l=Hc({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..."),Tr({cacheDir:m(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let y=n.map(x=>x.language==="typescript"?{language:x.language,scipPath:s.candidateScipPath}:x);return Xr(e.paths.outputDb,y),u=Kr(y,e.tempPaths.tempOutputScip,e.onStatus),u}});if(O(C(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),l.mode==="incremental"&&s){let y=null,x=null;try{y=new L({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),x=new L({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let v=Gt(y,e.fingerprint,s.referenceFragmentsByFile,x);e.onStatus(`Cached exact TypeScript reference fragments for ${v} affected document(s).`)}catch(v){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${v instanceof Error?v.message:String(v)}.`)}finally{y?.close(),x?.close()}}let p=kt(e.paths.metaPath),d=l.mode==="incremental"&&s?Jc(s,l.changedDocumentPaths):We({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"}),f=Fe({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(y=>y.language),skipped:[...r]}),g=l.mode==="incremental"&&l.scipCompanion==="deferred",w={...o};g&&delete w.typescript;let{metadata:D,pruneProjects:F}=ii({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:w,typescriptProjectShardContext:a,lastRefresh:f});return D.scipCompanion=g?"deferred":"current",oi(e.paths.outputDb,F),Ft(e.tempPaths.tempMetaPath,D),On({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:l.mode==="incremental"&&l.scipCompanion==="deferred",publication:l.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:l.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:l.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:l.patchDurationMs,scipCompanion:l.scipCompanion,...l.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:l.converterDurationMs,scipCompanion:"current",...l.fallbackReason?{fallbackReason:l.fallbackReason}:{}}}),sr(m(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),ri(e.paths.outputDb,d,e.onStatus),f}function Ac(e,t,n,r,i,o){let a=kt(e.paths.metaPath),s=null;try{Ee(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){s=zt("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}O(C(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),s??=We({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=Fe({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:l}=ii({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return oi(e.paths.outputDb,l),Ft(e.paths.metaPath,u),Mn(e.paths.outputDb,e.paths.metaPath),ri(e.paths.outputDb,s,e.onStatus),c}function kt(e){return Nt(te(e)?.fingerprint)}function ri(e,t,n){try{Yt(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 ii(e){let t=Nc({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 Nc(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=te(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 oi(e,t){let n=pi(e);if(t===null){M(n,{recursive:!0,force:!0});return}let r;try{r=yc(n)}catch{return}for(let i of Vc(r,t))M(b(n,i),{force:!0})}function Vc(e,t){let n=new Set(t.map(r=>`${tt(r)}.scip`));return e.filter(r=>!n.has(r))}function Xr(e,t){for(let n of t){let r=Dt(e,n.language);Te(m(r),{recursive:!0}),n.scipPath!==r&&Ee(n.scipPath,r)}}async function $c(e,t){if(!$e()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
292
|
-
Install from: https://github.com/sourcegraph/scip/releases`);if(
|
|
293
|
-
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
294
|
+
`).get();return{version:3,tsconfig:n,files:Pe(t),db:r}}function Hu(e){let t=co();return{projectRoot:e.projectRoot,context:Ki(e.projectRoot,e.configPath),symbolLookup:Zi(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function qu(e){let t=[],n=X(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=zu(e,i);t.push(...o.occurrences),Qe(n,o)}return{occurrences:t,...n}}function zu(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return lo(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 lo(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=A(e.projectRoot,t.fileName),s=[...oo(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:nd(s),processedStarts:new Set};return Yu({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Yu(e){let t=[],n=X();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||Qu(e.sourceInfo.text,r.start))continue;let i=ao(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!so(e.projectRoot,d.fileName));if(!a){dn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=A(e.projectRoot,a.fileName),c=Xu(e.sourceFile,r.text,s);if(c){dn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=no(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){dn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}go(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),td(t,e,r,i,s,u)}return{occurrences:t,...n}}function Qu(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 Xu(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function lo(e,t,n){let r=X();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 dn(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 ln(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 Ku(e,t){let n=ln(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=ln(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Zu(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(...ln(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function ed(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Ku(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function td(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of rd(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&&(go(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function go(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 nd(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function rd(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=id(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function id(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=un(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function Df(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=hd(e),a=Date.now();Ke(h(o.outputScip),{recursive:!0}),Ke(h(o.outputDb),{recursive:!0});let s=e.languages??ht(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=Z("reindex.fingerprint",()=>Yd(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),u,d;if(e.skipIfUnchanged!==!1&&!bi(t,o.outputDb)&&fo(o.outputScip)===fo(I(h(o.outputDb),"index.scip"))){let g=Ee(t);if(u=g?Be(g,c):void 0,u){let v=_(u);if(v){if(!md(o,c))try{zt({snapshot:u,manifest:v,targetCacheDir:h(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(S){r(`Shared generation attach failed; continuing locally: ${gn(S)}`)}}else{let S=await xi(u);if(S.kind==="owner")d=S.release;else if(S.kind==="generation-ready"){let R=_(u);if(R)try{zt({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: ${gn(y)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=te(I(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 ee("reindex.lock",()=>Ud(I(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,v=Z("reindex.reuse-check",()=>(g=yd({opts:e,paths:o,languages:s,fingerprint:c,start:a,onStatus:r}),g),()=>({languages:s.length,reused:g!==null}));if(v)return mo({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),v;await ee("reindex.scip-cli-ready",()=>Cd(i,r));let S=bd(o);m=S.runDir;let R,y=await ee("reindex.fresh",async()=>(R=await Rd({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 mo({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),y}catch(g){throw Oo(o.metaPath,nt({trigger:e.trigger,result:"failed",start:a,error:g instanceof Error?g.message:String(g)})),g}finally{m&&W(m,{recursive:!0,force:!0}),l(),p.release(),d?.()}}function mo(e){if(e.snapshot){if(_(e.snapshot)){Je(e.snapshot,h(e.paths.outputDb),"local-fresh");return}try{let t=Ee(e.projectRoot),n=t?Be(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}Ri({snapshot:e.snapshot,sourceCacheDir:h(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=Ee(e.projectRoot);return(r?Be(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Je(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: ${gn(t)}`)}}}function md(e,t){if(!O(e.outputScip)||!O(e.outputDb)||!Fo(e.metaPath,t))return!1;let n=G(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function gn(e){return e instanceof Error?e.message:String(e)}function hd(e){let t=e.outputScip??I(e.projectRoot,"index.scip"),n=e.outputDb??I(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:I(h(n),"meta.json")}}function yd(e){let t=G(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!O(e.paths.outputScip)||!O(e.paths.outputDb)||!Fo(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=nt({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return Oo(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:Sd(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Sd(e,t,n,r){let i=To(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:he(i[o]),outputBytes:ye(mn(e.outputDb,o)),durationMs:0}))}function bd(e){let t=cd(I(h(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:I(t,Xe(e.outputScip)),tempOutputDb:I(t,Xe(e.outputDb)),tempMetaPath:I(t,Xe(e.metaPath))}}async function Rd(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await ee("reindex.language-indexers",async()=>(n=await Id(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(", ")}`),xd({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=Z("reindex.publish",()=>Od(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(v=>v.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c}}let p=Z("reindex.publish",()=>Fd(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 xd(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=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 Id(e,t){let n=Ed({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,Sn]of n)Sn.reused&&(r.push({language:E,scipPath:Sn.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=be(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?Vi({projectRoot:e.projectRoot,cacheDir:h(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Se(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Se(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:fn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),l=d?void 0:vd(e,n),{preparedRuns:m,skippedLanguages:g,languageOutputScipPaths:v}=Ad({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 Bi(S,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),y=[];if(l){wd(e.paths.outputDb,R);let E=v.typescript??e.tempPaths.tempOutputScip;y=kd({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:E,reusedProjects:l.reusedProjects})}let w=[...R,...y],{indexedOutputs:k}=Md(w,g),Re=d?[{language:"typescript",scipPath:d.scipPath}]:[],yn=[...r,...Re,...k];Nd(yn,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:ye(d.scipPath)??void 0}]:[],_o=Td(n,[...R,...jo],l?{outputDb:e.paths.outputDb,classification:l.classification}:void 0);return{indexedOutputs:yn,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Dd(n,e.languages),shards:_o,typescriptProjectShardContext:l?{projects:l.allProjects,fingerprints:l.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function vd(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=me(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Rr(e.projectRoot,r),o=yr(n.fingerprint.files,r),a=Sr(r,i),s=br(r,o,a),c=be(e.paths.metaPath),d=Pd(c,s,g=>O(tt(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 Pd(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 wd(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=tt(e,r);Ke(h(i),{recursive:!0}),Ze(n.scipPath,i)}}function kd(e){return e.reusedProjects.map((t,n)=>{let r=tt(e.outputDb,t),i=Se(e.tempOutputScip,"typescript-project-cached",n);return Ze(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:ye(i)??void 0}})}function Ed(e){let t=be(e.paths.metaPath),n=To(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=mn(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 Td(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:he(o.fingerprint),outputBytes:ye(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?he(s.fingerprint):o?he(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:he(o.fingerprint),outputBytes:ye(tt(n.outputDb,i)),durationMs:0});return r}function he(e){return ad("sha256").update(L(e)).digest("hex").slice(0,16)}function ye(e){try{return ld(e).size}catch{return null}}function Dd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Fd(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(ho(e.paths.outputDb,n),u=yo(n,e.tempPaths.tempOutputScip,e.onStatus));let d=$d({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..."),Ui({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 ho(e.paths.outputDb,y),u=yo(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 B({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),w=new B({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let k=Dn(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=fn(e.paths.metaPath),l=d.mode==="incremental"&&s?Vd(s,d.changedDocumentPaths):mt({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=nt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(y=>y.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",v={...o};g&&delete v.typescript;let{metadata:S,pruneProjects:R}=vo({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:v,typescriptProjectShardContext:a,lastRefresh:m});return S.scipCompanion=g?"deferred":"current",Po(e.paths.outputDb,R),hn(e.tempPaths.tempMetaPath,S),Ve({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}:{}}}),Yr(h(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),Io(e.paths.outputDb,l,e.onStatus),m}function Od(e,t,n,r,i,o){let a=fn(e.paths.metaPath),s=null;try{Ze(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??=mt({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=nt({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=vo({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Po(e.paths.outputDb,d),hn(e.paths.metaPath,u),ai(e.paths.outputDb,e.paths.metaPath),Io(e.paths.outputDb,s,e.onStatus),c}function fn(e){return kn(be(e)?.fingerprint)}function Io(e,t,n){try{Yn(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 vo(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=be(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 Po(e,t){let n=Do(e);if(t===null){W(n,{recursive:!0,force:!0});return}let r;try{r=dd(n)}catch{return}for(let i of _d(r,t))W(I(n,i),{force:!0})}function _d(e,t){let n=new Set(t.map(r=>`${Dt(r)}.scip`));return e.filter(r=>!n.has(r))}function ho(e,t){for(let n of t){let r=mn(e,n.language);Ke(h(r),{recursive:!0}),n.scipPath!==r&&Ze(n.scipPath,r)}}async function Cd(e,t){if(!lt()){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(fd()==="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..."),!pt(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 Ad(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?Se(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=Ld({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?wo(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Ld(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[pn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??me(e.projectRoot,e.typescriptProjects);return t.length===0?[pn({...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)=>pn({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Se(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function pn(e){let t=ve(e.language),n=rt(t),r=at(t,e.projectRoot);if(!r&&!ot(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...`),!ct(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??it(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:st(t,e.env,i)}}}function Md(e,t){let n=new Map;for(let i of e)if(i.skipped)wo(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)vt(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&xo(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function wo(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 Nd(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
|
|
294
298
|
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
295
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.
|
|
296
300
|
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
297
|
-
`))}function
|
|
298
|
-
`),()=>{try{
|
|
301
|
+
`))}function yo(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=ir(e.map(o=>o.scipPath),t);return Eo(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&xo(e[0].scipPath,t);return!1}function $d(e){let t;if(Gd(e)){let i=I(e.run.tempPaths.runDir,"typescript-affected.db");try{ko(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();So(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),W(i,{force:!0}),W(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 So(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Gd(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 Vd(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:ft(e.plan,o,e.projectFileCount)}}function So(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||ko(e,r);let o=lt();if(!o)throw new Error("scip CLI is not available");od(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 ko(e,t){let n=nr(e);Eo(n,t)}function Eo(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Se(e,t,n){let r=gd(e)||".scip",i=Xe(e,r);return I(h(e),`${i}.${n+1}.${t}${r}`)}async function Ud(e,t){for(let n=0;n<2;n++){let r=Wd(e,t);if(r)return r;let i=Bd(e);if(i&&Jd(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await qd(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.`);W(e,{force:!0});continue}if(i&&!T(i.pid)){W(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 Wd(e,t){let n;try{n=ud(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 pd(n,JSON.stringify(r)+`
|
|
302
|
+
`),()=>{try{sd(n)}finally{W(e,{force:!0})}}}function Bd(e){try{let t=JSON.parse(et(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 Jd(e,t){return e?.kind==="manual-cli"&&Hd(t?.trigger)}function Hd(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function qd(e){return bo(e,"SIGTERM"),await Ro(e,2e3)?!0:(bo(e,"SIGKILL"),Ro(e,1e3))}function bo(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Ro(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!T(e))return!0;await zd(50)}return!T(e)}function zd(e){return new Promise(t=>setTimeout(t,e))}function Yd(e,t,n){return vn(e,t,n)}function To(e,t,n){return Object.fromEntries(t.map(r=>{let i=ve(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:In(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?Qd(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Xd(n),...o,clojureConfigPath:a,files:Pe(e,{language:r,markerFiles:i})}]}))}function Qd(e){return e?.trim()||void 0}function Xd(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function mn(e,t){return I(h(e),"language-indexes",`${t}.scip`)}function Do(e){return I(h(e),"language-indexes","typescript-projects")}function tt(e,t){return I(Do(e),`${Dt(t)}.scip`)}function be(e){try{return JSON.parse(et(e,"utf-8"))}catch{return null}}function Fo(e,t){try{let n=JSON.parse(et(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 hn(e,t){b(e,t,{spacing:2,trailingNewline:!0})}function Oo(e,t){try{let n=JSON.parse(et(e,"utf-8"));if(n.version!==2&&n.version!==3)return;hn(e,{...n,lastRefresh:t})}catch{}}function nt(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{Co as INDEXER_CONFIGS,Bn as augmentAuxiliaryDocuments,Vu as augmentVueResolvedReferences,J as auxiliaryDocumentsAugmentationStage,rt as describeIndexerBinary,ht as detectLanguages,ve as getIndexerConfig,st as getIndexerExecutionEnv,Ao as isBinaryAvailable,ot as isIndexerInstalled,vt as mergeScipFiles,It as mergeScipIndexes,Df as reindex,it as resolveIndexerBinary,at as resolveProjectLocalIndexerBinary,N as runPostIndexAugmentation,ct as tryInstallIndexer,pt as tryInstallScipCli,po as vueResolvedReferencesAugmentationStage};
|
|
299
303
|
//# sourceMappingURL=reindex.js.map
|