afv-library/plugins/builder/salesforce-development/bin/lsp-doctor.bundled.js

12 lines
16 KiB
JavaScript
Generated

"use strict";var ye=Object.create;var M=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,xe=Object.prototype.hasOwnProperty;var Re=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ve(e))!xe.call(t,s)&&s!==r&&M(t,s,{get:()=>e[s],enumerable:!(n=Se(e,s))||n.enumerable});return t};var l=(t,e,r)=>(r=t!=null?ye(ke(t)):{},Re(e||!t||!t.__esModule?M(r,"default",{value:t,enumerable:!0}):r,t));var A=l(require("node:path"));var f=l(require("node:fs")),y=l(require("node:path"));async function F(t){let e=[];for(let r of t.bundles)e.push(N(`bundle: ${r.name}`,r.path));for(let r of t.vendor)e.push(N(`vendor: ${r.name}`,r.path));return e.push(Pe(t.cacheRoot)),e.push(...await Ce(t)),{ok:e.every(r=>r.status!=="fail"),checks:e}}function N(t,e){return f.existsSync(e)?{name:t,status:"pass",detail:e}:{name:t,status:"fail",detail:`missing: ${e}`}}function Pe(t){let e="schema cache";if(!f.existsSync(t))return{name:e,status:"pass",detail:`no cache yet (${t})`};let r=0,n=0,s=[],i;try{i=f.readdirSync(t,{withFileTypes:!0})}catch(a){return{name:e,status:"fail",detail:`unreadable: ${De(a)}`}}for(let a of i){if(!a.isDirectory())continue;r++;let c=y.join(t,a.name),g;try{g=f.readdirSync(c).filter(w=>w.endsWith(".json"))}catch{continue}for(let w of g){n++;let be=y.join(c,w);try{JSON.parse(f.readFileSync(be,"utf8"))}catch{s.push(y.join(a.name,w))}}}return s.length>0?{name:e,status:"fail",detail:`${s.length} corrupt entr${s.length===1?"y":"ies"}: ${s.join(", ")}`}:{name:e,status:"pass",detail:`${r} org(s), ${n} cached describe(s)`}}async function Ce(t){if(!t.spawn)return[{name:"spawn probe",status:"skip",detail:"skipped (--no-spawn)"}];if(t.killSwitch==="disabled")return[{name:"spawn probe",status:"skip",detail:"skipped (kill switch: disabled)"}];let e=[];for(let r of t.languages){let n=await t.probeSpawn(r),s=n.status==="pass"&&typeof n.ms=="number"?`ready in ${n.ms}ms`:n.detail;e.push({name:`spawn: ${r}`,status:n.status,detail:s})}return e}function De(t){return t instanceof Error?t.message:String(t)}function q(t){let e={pass:"\u2713",fail:"\u2717",skip:"\u2013"},r=t.checks.map(i=>` ${e[i.status]} ${i.name}${i.detail?` \u2014 ${i.detail}`:""}`),n=t.checks.filter(i=>i.status==="fail").length;return[t.ok?"lsp-doctor: healthy":`lsp-doctor: ${n} check${n===1?"":"s"} failed`,...r].join(`
`)}var S=class{failures=0;openedAt=0;threshold;cooldownMs;now;constructor(e={}){this.threshold=e.threshold??3,this.cooldownMs=e.cooldownMs??3e4,this.now=e.now??Date.now}state(){return this.failures<this.threshold?"closed":this.now()-this.openedAt>=this.cooldownMs?"half-open":"open"}canAttempt(){return this.state()!=="open"}recordSuccess(){this.failures=0,this.openedAt=0}recordFailure(){this.failures++,this.failures>=this.threshold&&(this.openedAt=this.now())}};var I=process.env.SFDX_LSP_DEBUG==="1";function v(t,e){let r=e.map(n=>typeof n=="string"?n:je(n));process.stderr.write(`[sf-lsp-host] ${t} ${r.join(" ")}
`)}function je(t){try{return JSON.stringify(t)}catch{return String(t)}}var o={info(...t){v("info",t)},warn(...t){v("warn",t)},error(...t){v("error",t)},debug(...t){I&&v("debug",t)},get debugEnabled(){return I}};function T(t){switch((t??"").trim().toLowerCase()){case"":case"all":return"all";case"apex-only":return"apex-only";case"disabled":return"disabled";default:return o.warn(`unknown SFDX_LSP value '${t}', defaulting to 'all'`),"all"}}function W(t,e){return t==="disabled"?!1:t==="apex-only"?e==="apex":!0}var Oe=t=>{process.stderr.write(t+`
`)},E=class{enabled;sink;now;constructor(e={}){this.enabled=e.enabled??process.env.SFDX_LSP_DEBUG==="1",this.sink=e.sink??Oe,this.now=e.now??Date.now}clock(){return this.now()}emit(e){this.enabled&&this.sink(JSON.stringify({telemetry:!0,ts:this.now(),...e}))}async time(e,r){if(!this.enabled)return r();let n=this.now();try{let s=await r();return this.emit({event:"request",tool:e,ms:this.now()-n,outcome:"ok"}),s}catch(s){throw this.emit({event:"request",tool:e,ms:this.now()-n,outcome:"error",error:s instanceof Error?s.message:String(s)}),s}}},$=new E({enabled:!1});var Te=5e3,u=class extends Error{constructor(r){super(r);this.code=r;this.name="LspUnavailableError"}code},k=class{constructor(e,r){this.specs=e;this.options=r;this.spawnTimeoutMs=r.spawnTimeoutMs??Te,this.now=r.now??Date.now,this.telemetry=r.telemetry??$;for(let n of e)this.entries.set(n.language,{spec:n,status:"idle",lastUsedAt:0}),this.breakers.set(n.language,new S({now:this.now}))}specs;options;entries=new Map;breakers=new Map;spawnTimeoutMs;now;telemetry;snapshot(){return[...this.entries.values()].map(e=>({language:e.spec.language,status:e.status,lastError:e.lastError,lastSpawnMs:e.lastSpawnMs,breaker:this.breakers.get(e.spec.language).state()}))}async getReadyClient(e,r){let n=this.entries.get(e);if(!n)throw new u("unknown_language");if(!W(this.options.killSwitch,e))throw new u("lsp_disabled");if(n.status==="ready"&&n.client&&!n.client.hasExited)return this.telemetry.emit({event:"client_cache",language:e,result:"hit"}),this.touch(n),n.client;if(n.status==="spawning"&&n.initPromise)return n.initPromise;let s=this.breakers.get(e);if(!s.canAttempt())throw new u("circuit_open");this.telemetry.emit({event:"client_cache",language:e,result:"miss"}),n.status="spawning";let i=this.bringUp(n,s,r);return n.initPromise=i,i}async bringUp(e,r,n){let s=await e.spec.gate(n);if(!s.ok)throw e.status="idle",e.initPromise=void 0,new u(s.error??"gate_failed");let i=e.spec.language,a=this.now();try{let c=await this.spawnWithTimeout(e,n);return e.client=c,e.status="ready",e.initPromise=void 0,e.lastError=void 0,e.lastSpawnMs=this.now()-a,this.recordBreaker(r,i,()=>r.recordSuccess()),this.telemetry.emit({event:"spawn",language:i,ms:e.lastSpawnMs,outcome:"ok"}),this.touch(e),o.debug(`${i} LSP ready`,{coldMs:e.lastSpawnMs}),c}catch(c){throw e.status="failed",e.initPromise=void 0,e.client=void 0,e.lastError=c instanceof Error?c.message:String(c),this.recordBreaker(r,i,()=>r.recordFailure()),this.telemetry.emit({event:"spawn",language:i,ms:this.now()-a,outcome:"error",error:e.lastError}),c instanceof u?c:new u("spawn_timeout")}}recordBreaker(e,r,n){let s=e.state();n();let i=e.state();s!==i&&this.telemetry.emit({event:"circuit",language:r,from:s,to:i})}spawnWithTimeout(e,r){let n=e.spec.createClient(r),s=new Promise((i,a)=>{let c=setTimeout(()=>a(new u("spawn_timeout")),this.spawnTimeoutMs);typeof c.unref=="function"&&c.unref()});return Promise.race([n,s])}touch(e){e.lastUsedAt=this.now(),this.armIdleTimer(e)}armIdleTimer(e){e.idleTimer&&clearTimeout(e.idleTimer);let r=setTimeout(()=>this.reap(e),e.spec.idleMs);typeof r.unref=="function"&&r.unref(),e.idleTimer=r}reap(e){if(e.status==="ready"){o.debug(`reaping idle ${e.spec.language} LSP`);try{e.client?.dispose()}catch(r){o.debug("LSP client dispose failed",{err:r.message})}e.client=void 0,e.status="idle",e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=void 0}}shutdownAll(){for(let e of this.entries.values())this.reap(e)}};var B=require("node:child_process"),x=l(require("node:fs")),d=l(require("node:path"));function Ee(t){let e=d.resolve(t);for(let r=0;r<64;r++){if(x.existsSync(d.join(e,"sfdx-project.json")))return e;let n=d.dirname(e);if(n===e)break;e=n}}function Le(t){try{let r=(0,B.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return r.length>0?r:void 0}catch{return}}function _e(t){try{let e=x.readFileSync(d.join(t,"sfdx-project.json"),"utf8"),n=(JSON.parse(e).packageDirectories??[]).map(s=>s?.path).filter(s=>typeof s=="string"&&s.length>0).map(s=>d.resolve(t,s));return n.length>0?Ae(n):[t]}catch{return[t]}}function Ae(t){return Array.from(new Set(t))}function G(t=process.cwd()){let e=Ee(t);if(e)return{root:e,packageDirs:_e(e),source:"sfdx-project"};let r=Le(t);if(r)return{root:r,packageDirs:[r],source:"git-root"};let n=d.resolve(t);return{root:n,packageDirs:[n],source:"cwd"}}var X=l(require("node:path")),Q=require("node:url");var L=`\r
\r
`,Me=/Content-Length:\s*(\d+)/i,R=class{buffer=Buffer.alloc(0);push(e){this.buffer=Buffer.concat([this.buffer,e]);let r=[];for(;;){let n=this.buffer.indexOf(L);if(n===-1)break;let s=this.buffer.toString("utf8",0,n),i=Me.exec(s);if(!i){this.buffer=this.buffer.subarray(n+L.length);continue}let a=Number(i[1]),c=n+L.length,g=c+a;if(this.buffer.length<g)break;let w=this.buffer.toString("utf8",c,g);this.buffer=this.buffer.subarray(g);try{r.push(JSON.parse(w))}catch{}}return r}};function U(t){let e=JSON.stringify(t),r=Buffer.from(e,"utf8"),n=Buffer.from(`Content-Length: ${r.length}\r
\r
`,"ascii");return Buffer.concat([n,r])}var P=class{constructor(e){this.transport=e}transport;nextId=1;pending=new Map;notificationHandlers=new Map;serverRequestHandlers=new Map;request(e,r){let n=this.nextId++,s={jsonrpc:"2.0",id:n,method:e,params:r};return new Promise((i,a)=>{this.pending.set(n,{resolve:i,reject:a}),this.transport.send(s)})}notify(e,r){let n={jsonrpc:"2.0",method:e,params:r};this.transport.send(n)}onNotification(e,r){let n=this.notificationHandlers.get(e)??[];return n.push(r),this.notificationHandlers.set(e,n),()=>{let s=this.notificationHandlers.get(e);if(!s)return;let i=s.indexOf(r);i>=0&&s.splice(i,1)}}onServerRequest(e,r){this.serverRequestHandlers.set(e,r)}handleMessage(e){let r=e;if(r.id!==void 0&&r.method===void 0){let n=this.pending.get(r.id);if(!n)return;this.pending.delete(r.id),r.error?n.reject(new Error(`LSP error ${r.error.code}: ${r.error.message}`)):n.resolve(r.result);return}if(r.id!==void 0&&r.method!==void 0){let n=this.serverRequestHandlers.get(r.method),s=n?n(r.params):null,i={jsonrpc:"2.0",id:r.id,result:s};this.transport.send(i);return}if(r.method!==void 0){let n=this.notificationHandlers.get(r.method);if(n)for(let s of n.slice())s(r.params)}}rejectAll(e){for(let[,r]of this.pending)r.reject(new Error(e));this.pending.clear()}};var h=class{constructor(e){this.child=e;let r={send:n=>{if(!this.exited)try{this.child.stdin.write(U(n))}catch(s){o.debug("LSP child stdin write failed",{err:s.message})}}};this.rpc=new P(r),this.child.stdin.on("error",n=>{o.debug("LSP child stdin error",{err:n.message})}),this.child.stdout.on("data",n=>{for(let s of this.decoder.push(n))this.rpc.handleMessage(s)}),this.rpc.onServerRequest("client/registerCapability",()=>null),this.rpc.onServerRequest("client/unregisterCapability",()=>null),this.rpc.onServerRequest("workspace/configuration",n=>(n?.items??[]).map(()=>null)),this.rpc.onServerRequest("window/workDoneProgress/create",()=>null),this.child.on("exit",n=>{this.exited=!0,this.rpc.rejectAll(`LSP child exited (code ${n})`),o.debug("LSP child exited",{code:n})})}child;decoder=new R;rpc;exited=!1;request(e,r){return this.rpc.request(e,r)}notify(e,r){this.rpc.notify(e,r)}onNotification(e,r){return this.rpc.onNotification(e,r)}onServerRequest(e,r){this.rpc.onServerRequest(e,r)}get hasExited(){return this.exited}dispose(){if(!this.exited){try{this.rpc.notify("shutdown"),this.rpc.notify("exit")}catch{}try{this.child.kill()}catch{}}}};var V=require("node:child_process");function b(t){let e=(0,V.spawn)(t.command,t.args,{cwd:t.cwd,stdio:["pipe","pipe","pipe"]});return e.stderr.on("data",r=>{o.debugEnabled&&process.stderr.write(`[lsp:${t.label}] ${r.toString("utf8")}`)}),e.on("error",r=>{o.error(`failed to spawn LSP child '${t.label}'`,r.message)}),e}var J=l(require("node:fs")),p=l(require("node:path"));function Ne(t){return J.existsSync(p.join(t,".claude-plugin","plugin.json"))}function Fe(t){for(let e=t;;){if(Ne(e))return e;let r=p.dirname(e);if(r===e)break;e=r}return p.resolve(t,"..")}function m(){let t=process.env.CLAUDE_PLUGIN_ROOT;return t&&t.length>0?t:Fe(__dirname)}function C(){return p.join(m(),"vendor","apex-ls","dist","server.node.js")}function z(){return p.join(m(),"vendor","apex-ls","VERSION")}function D(){return p.join(m(),"bin","soql-lsp.bundled.js")}function j(){return p.join(m(),"vendor","lwc-language-server","node_modules","@salesforce","lwc-language-server","lib","server.js")}function H(){return p.join(m(),"vendor","lwc-language-server","VERSION.json")}function K(t){return(0,Q.pathToFileURL)(t).toString()}function qe(t){return{processId:process.pid,rootUri:K(t.root),workspaceFolders:t.packageDirs.map(e=>({uri:K(e),name:X.basename(e)})),capabilities:{textDocument:{diagnostic:{dynamicRegistration:!1,relatedDocumentSupport:!1},publishDiagnostics:{relatedInformation:!0},synchronization:{didSave:!0,dynamicRegistration:!1}},workspace:{workspaceFolders:!0,configuration:!0,diagnostics:{refreshSupport:!0}}},initializationOptions:{apex:{environment:{serverMode:"development"},detailLevel:"public-api"}}}}async function Y(t){let e=C(),r=b({command:"node",args:[e,"--stdio"],cwd:t.root,label:"apex"}),n=new h(r);return await n.request("initialize",qe(t)),n.notify("initialized",{}),o.debug("apex-ls initialized",{root:t.root}),n}var Z=l(require("node:fs")),O=l(require("node:path")),Ie=new Set(["node_modules",".git",".sfdx",".sf","dist","out","coverage"]);function ee(t,e=0){if(e>12)return!1;let r;try{r=Z.readdirSync(t,{withFileTypes:!0})}catch{return!1}let n=O.basename(t)==="classes";for(let s of r)if(s.isFile()&&n&&s.name.endsWith(".cls"))return!0;for(let s of r)if(s.isDirectory()&&!Ie.has(s.name)&&ee(O.join(t,s.name),e+1))return!0;return!1}function We(t){return t.packageDirs.some(e=>ee(e))}function te(t){return We(t)?{ok:!0}:{ok:!1,error:"no_apex_workspace"}}var $e=900*1e3,re={language:"apex",idleMs:$e,gate:te,createClient:Y};var se=l(require("node:path")),ie=require("node:url");function ne(t){return(0,ie.pathToFileURL)(t).toString()}function Be(t){return{processId:process.pid,rootUri:ne(t.root),workspaceFolders:t.packageDirs.map(e=>({uri:ne(e),name:se.basename(e)})),capabilities:{textDocument:{synchronization:{didSave:!0,dynamicRegistration:!1},completion:{dynamicRegistration:!1}}}}}async function oe(t){let e=D(),r=b({command:"node",args:[e,"--stdio"],cwd:t.root,label:"soql"}),n=new h(r);return await n.request("initialize",Be(t)),n.notify("initialized",{}),o.debug("soql-ls initialized",{root:t.root}),n}function ae(t){return{ok:!0}}var Ge=300*1e3,ce={language:"soql",idleMs:Ge,gate:ae,createClient:oe};var le=require("node:url");function Ue(t){return(0,le.pathToFileURL)(t).toString()}function Ve(t){let e=Ue(t.root);return{processId:process.pid,rootUri:e,rootPath:t.root,workspaceFolders:[{uri:e,name:"sfdx"}],capabilities:{textDocument:{synchronization:{didSave:!0,dynamicRegistration:!1},completion:{dynamicRegistration:!1},hover:{dynamicRegistration:!1},definition:{dynamicRegistration:!1}},workspace:{workspaceFolders:!0,configuration:!0}}}}async function ue(t){let e=j(),r=b({command:"node",args:[e,"--stdio"],cwd:t.root,label:"lwc"}),n=new h(r);return await n.request("initialize",Ve(t)),n.notify("initialized",{}),o.debug("lwc-ls initialized",{root:t.root}),n}var pe=l(require("node:fs")),de=l(require("node:path")),Je=new Set(["node_modules",".git",".sfdx",".sf","dist","out","coverage"]);function fe(t,e=!1,r=0){if(r>12)return!1;let n;try{n=pe.readdirSync(t,{withFileTypes:!0})}catch{return!1}if(e){for(let s of n)if(s.isFile()&&s.name.endsWith(".js"))return!0}for(let s of n)if(s.isDirectory()&&!Je.has(s.name)){let i=e||s.name==="lwc";if(fe(de.join(t,s.name),i,r+1))return!0}return!1}function ze(t){return t.packageDirs.some(e=>fe(e))}function he(t){return ze(t)?{ok:!0}:{ok:!1,error:"no_lwc_bundles"}}var He=900*1e3,me={language:"lwc",idleMs:He,gate:he,createClient:ue};var ge=l(require("node:os")),_=l(require("node:path"));var ir=1440*60*1e3;function we(){return _.join(ge.homedir(),".sfdx","claude","soql-schema")}var Ke=new Set(["no_apex_workspace","no_soql_workspace","no_lwc_bundles","lsp_disabled"]);function Xe(){let t=T(process.env.SFDX_LSP),e=G(),r=new k([re,ce,me],{killSwitch:t});return async n=>{try{return await r.getReadyClient(n,e),{status:"pass",ms:r.snapshot().find(i=>i.language===n)?.lastSpawnMs}}catch(s){let i=s instanceof u?s.code:void 0;return i&&Ke.has(i)?{status:"skip",detail:i}:{status:"fail",detail:i??(s instanceof Error?s.message:String(s))}}}}async function Qe(){let t=process.argv.slice(2),e=t.includes("--json"),r=!t.includes("--no-spawn"),n=m(),s=r?Xe():async()=>({status:"skip"}),i={bundles:[{name:"sf-lsp-host",path:A.join(n,"bin","sf-lsp-host.bundled.js")},{name:"lsp-precheck",path:A.join(n,"bin","lsp-precheck.bundled.js")},{name:"soql-lsp",path:D()}],vendor:[{name:"apex-ls server",path:C()},{name:"apex-ls VERSION",path:z()},{name:"lwc-ls server",path:j()},{name:"lwc-ls VERSION",path:H()}],cacheRoot:we(),killSwitch:T(process.env.SFDX_LSP),languages:["apex","soql","lwc"],spawn:r,probeSpawn:s},a=await F(i);e?process.stdout.write(JSON.stringify(a,null,2)+`
`):process.stdout.write(q(a)+`
`),process.exit(a.ok?0:1)}Qe().catch(t=>{process.stderr.write(`lsp-doctor: ${t instanceof Error?t.message:String(t)}
`),process.exit(1)});