@lensmcp/cluster 1.26.2 → 1.26.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/build-host.js +1 -1
  2. package/devserver-host.d.ts +5 -0
  3. package/devserver-host.js +1 -1
  4. package/executors/gateway/runtime/auth.js +1 -1
  5. package/executors/gateway/runtime/control.d.ts +25 -0
  6. package/executors/gateway/runtime/control.js +2 -2
  7. package/executors/gateway/runtime/discovery.js +1 -1
  8. package/executors/gateway/runtime/docker-sweep.d.ts +51 -0
  9. package/executors/gateway/runtime/docker-sweep.js +1 -0
  10. package/executors/gateway/runtime/edge.d.ts +2 -0
  11. package/executors/gateway/runtime/edge.js +1 -1
  12. package/executors/gateway/runtime/frontend-updates.d.ts +24 -0
  13. package/executors/gateway/runtime/frontend-updates.js +1 -0
  14. package/executors/gateway/runtime/handler.js +1 -1
  15. package/executors/gateway/runtime/legacy-dashboard-link.d.ts +10 -0
  16. package/executors/gateway/runtime/legacy-dashboard-link.js +1 -0
  17. package/executors/gateway/runtime/lens-children.d.ts +9 -0
  18. package/executors/gateway/runtime/lens-children.js +1 -1
  19. package/executors/gateway/runtime/lifecycle.d.ts +2 -0
  20. package/executors/gateway/runtime/lifecycle.js +4 -4
  21. package/executors/gateway/runtime/peer-hub.d.ts +54 -0
  22. package/executors/gateway/runtime/peer-hub.js +1 -0
  23. package/executors/gateway/runtime/proxy.js +1 -1
  24. package/executors/gateway/runtime/remote-instances.d.ts +167 -0
  25. package/executors/gateway/runtime/remote-instances.js +1 -0
  26. package/executors/gateway/runtime/run-routes.d.ts +186 -0
  27. package/executors/gateway/runtime/run-routes.js +1 -0
  28. package/executors/gateway/runtime/server.js +2 -2
  29. package/executors/gateway/runtime/service-updates.d.ts +44 -0
  30. package/executors/gateway/runtime/service-updates.js +1 -0
  31. package/executors/gateway/runtime/shared-build.d.ts +8 -1
  32. package/executors/gateway/runtime/shared-build.js +4 -4
  33. package/executors/gateway/runtime/types.d.ts +54 -0
  34. package/executors/gateway/runtime/update-wiring.d.ts +57 -0
  35. package/executors/gateway/runtime/update-wiring.js +2 -0
  36. package/executors/gateway/runtime/updates.d.ts +148 -0
  37. package/executors/gateway/runtime/updates.js +1 -0
  38. package/executors/gateway/runtime/upgrade.js +1 -1
  39. package/executors/serve/serve.impl.js +1 -1
  40. package/executors/serve/updates-gate.d.ts +147 -0
  41. package/executors/serve/updates-gate.js +2 -0
  42. package/main.devserver.js +10 -10
  43. package/package.json +5 -5
  44. package/program-id.d.ts +4 -0
  45. package/program-id.js +1 -0
  46. package/shared-build/host.d.ts +102 -2
  47. package/shared-build/host.js +3 -3
  48. package/shared-build/protocol.d.ts +59 -3
  49. package/shared-build/protocol.js +1 -1
  50. package/shared-build/shared-compilation.d.ts +21 -0
  51. package/shared-build/shared-compilation.js +3 -3
  52. package/static-checks-record.d.ts +391 -0
  53. package/static-checks-record.js +5 -0
  54. package/tsgo-check-plugin.d.ts +107 -43
  55. package/tsgo-check-plugin.js +4 -5
  56. package/tsgo-shim.d.ts +112 -0
  57. package/tsgo-shim.js +2 -0
  58. package/typecheck-bus.d.ts +36 -5
  59. package/typecheck-bus.js +4 -4
  60. package/typecheck-memory.d.ts +187 -0
  61. package/typecheck-memory.js +1 -0
  62. package/typecheck-queue.d.ts +41 -3
  63. package/typecheck-queue.js +1 -1
@@ -0,0 +1,5 @@
1
+ "use strict";var S=Object.defineProperty;var u=(e,t)=>S(e,"name",{value:t,configurable:!0});var y=Object.defineProperty,c=u((e,t)=>y(e,"name",{value:t,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.RunOutput=exports.MAX_RECORD_DIAGNOSTICS=exports.RECORD_SCHEMA=void 0,exports.toWorkspacePath=toWorkspacePath,exports.typecheckRecordsDir=typecheckRecordsDir,exports.programFiles=programFiles,exports.statFile=statFile,exports.sameStat=sameStat,exports.hashFile=hashFile,exports.declaredReferences=declaredReferences,exports.configInputs=configInputs,exports.changedInputs=changedInputs,exports.compilerVersion=compilerVersion,exports.trustBuildInfo=trustBuildInfo,exports.dropBuildInfo=dropBuildInfo,exports.settleBuildInfo=settleBuildInfo,exports.readLock=readLock,exports.tryLock=tryLock,exports.readHead=readHead,exports.concludeRun=concludeRun,exports.programInputFiles=programInputFiles,exports.statAtStart=statAtStart,exports.stampAfterRun=stampAfterRun,exports.stampsHashOf=stampsHashOf,exports.inputsHashOf=inputsHashOf,exports.writeVerdict=writeVerdict,exports.readRecord=readRecord,exports.readStamps=readStamps,exports.beginRun=beginRun,exports.recordUnrun=recordUnrun,exports.finishRun=finishRun;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),node_crypto_1=require("node:crypto"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),node_string_decoder_1=require("node:string_decoder"),tsgo_shim_1=require("./tsgo-shim");exports.RECORD_SCHEMA=1,exports.MAX_RECORD_DIAGNOSTICS=5e4;const sha256=c(e=>(0,node_crypto_1.createHash)("sha256").update(e).digest("hex"),"sha256");function toWorkspacePath(e,t){const o=path.relative(e,path.resolve(e,t));return(path.sep==="/"?o:o.split(path.sep).join("/"))||"."}u(toWorkspacePath,"toWorkspacePath"),c(toWorkspacePath,"toWorkspacePath");function typecheckRecordsDir(e){return path.join(e,".lensmcp","static-checks","typecheck")}u(typecheckRecordsDir,"typecheckRecordsDir"),c(typecheckRecordsDir,"typecheckRecordsDir");function programFiles(e,t){const o=(0,tsgo_shim_1.tsgoShimDir)(e),n=typecheckRecordsDir(e);return{shim:path.join(o,`${t}.tsconfig.json`),buildInfo:path.join(o,`${t}.tsbuildinfo`),trust:path.join(o,`${t}.trust.json`),lock:path.join(o,`${t}.lock`),record:path.join(n,`${t}.json`),stamps:path.join(n,`${t}.stamps`)}}u(programFiles,"programFiles"),c(programFiles,"programFiles");function writeAtomic(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const o=`${e}.${process.pid}.${(0,node_crypto_1.randomBytes)(4).toString("hex")}.tmp`;try{fs.writeFileSync(o,t),fs.renameSync(o,e)}catch(n){throw fs.rmSync(o,{force:!0}),n}}u(writeAtomic,"writeAtomic"),c(writeAtomic,"writeAtomic");function readJson(e){try{return JSON.parse(fs.readFileSync(e,"utf8"))}catch{return}}u(readJson,"readJson"),c(readJson,"readJson");const isObj=c(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isObj");function statFile(e,t){try{const o=fs.statSync(path.resolve(e,t));return o.isFile()?{mtimeMs:o.mtimeMs,ctimeMs:o.ctimeMs,size:o.size,ino:o.ino}:null}catch{return null}}u(statFile,"statFile"),c(statFile,"statFile");function sameStat(e,t){return e.mtimeMs===t.mtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size&&e.ino===t.ino}u(sameStat,"sameStat"),c(sameStat,"sameStat");const HASH_LENGTH=32;function hashFile(e,t){try{return sha256(fs.readFileSync(path.resolve(e,t))).slice(0,HASH_LENGTH)}catch{return null}}u(hashFile,"hashFile"),c(hashFile,"hashFile");async function hashFileLater(e,t){try{return sha256(await fs.promises.readFile(path.resolve(e,t))).slice(0,HASH_LENGTH)}catch{return null}}u(hashFileLater,"hashFileLater"),c(hashFileLater,"hashFileLater");const LOCKFILES=["yarn.lock","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","bun.lock","bun.lockb"],contentHashes=new Map;function inputHash(e){const t=statFile(path.dirname(e),e);if(!t)return"gone";const o=contentHashes.get(e);if(o&&sameStat(o.stat,t))return o.hash;const n=hashFile(path.dirname(e),e)??"unreadable";return contentHashes.size>4096&&contentHashes.clear(),contentHashes.set(e,{stat:t,hash:n}),n}u(inputHash,"inputHash"),c(inputHash,"inputHash");function declaredReferences(e){const t=(0,tsgo_shim_1.readTsconfig)(e)?.references;if(!Array.isArray(t))return[];const o=[];for(const n of t){if(!isObj(n)||typeof n.path!="string")continue;const r=path.resolve(path.dirname(e),n.path);let s=!1;try{s=fs.statSync(r).isDirectory()}catch{}o.push(s?path.join(r,"tsconfig.json"):r)}return o}u(declaredReferences,"declaredReferences"),c(declaredReferences,"declaredReferences");function configInputs(e){const t=[];let o=e.compiler.bin;try{o=fs.realpathSync(o)}catch{}t.push(["compiler",`tsgo ${e.compiler.version} ${o}`]),t.push(["route",e.route==="tsgo-shim"?`tsgo-shim v${tsgo_shim_1.SHIM_VERSION}${e.pinsOnly?" (pins only)":""}`:"tsgo"]),t.push(["flags",(e.flags??[]).join(" ")]);const n=new Set,r=c((s,i)=>{const a=`${s}:${toWorkspacePath(e.root,i)}`;n.has(a)||(n.add(a),t.push([a,inputHash(i)]))},"add");for(const s of(0,tsgo_shim_1.tsconfigChain)(e.tsconfig))r("config",s);for(const s of declaredReferences(e.tsconfig).sort())for(const i of(0,tsgo_shim_1.tsconfigChain)(s))r("reference",i);for(const s of LOCKFILES){const i=path.join(e.root,s);fs.existsSync(i)&&r("lockfile",i)}return{key:sha256(JSON.stringify([exports.RECORD_SCHEMA,t])),inputs:t}}u(configInputs,"configInputs"),c(configInputs,"configInputs");function changedInputs(e,t){const o=new Map(e),n=new Map(t),r=[];for(const s of new Set([...o.keys(),...n.keys()])){if(o.get(s)===n.get(s))continue;const i=s.indexOf(":");r.push(i===-1?s==="flags"?"the options its command adds":`the ${s}`:s.slice(i+1))}return[...new Set(r)].sort()}u(changedInputs,"changedInputs"),c(changedInputs,"changedInputs");const versions=new Map;function compilerVersion(e){const t=statFile(path.dirname(e),e),o=`${e}\0${t?`${t.mtimeMs}:${t.size}:${t.ino}`:""}`;if(versions.has(o))return versions.get(o);let n;try{const r=(0,node_child_process_1.execFileSync)(e,["--version"],{encoding:"utf8",timeout:15e3,stdio:["ignore","pipe","ignore"]});n=/(\d+\.\d+\.\d+\S*)/.exec(r)?.[1]}catch{n=void 0}return versions.size>64&&versions.clear(),versions.set(o,n),n}u(compilerVersion,"compilerVersion"),c(compilerVersion,"compilerVersion");function trustBuildInfo(e,t,o){const n=readJson(e.trust),r=isObj(n)&&n.schema===exports.RECORD_SCHEMA&&n.id===t&&n.configKey===o&&fs.existsSync(e.buildInfo);return r||fs.rmSync(e.buildInfo,{force:!0}),fs.rmSync(e.trust,{force:!0}),r}u(trustBuildInfo,"trustBuildInfo"),c(trustBuildInfo,"trustBuildInfo");function dropBuildInfo(e){try{fs.rmSync(e.buildInfo,{force:!0}),fs.rmSync(e.trust,{force:!0})}catch{}}u(dropBuildInfo,"dropBuildInfo"),c(dropBuildInfo,"dropBuildInfo");function settleBuildInfo(e,t,o,n,r=Date.now){if(!n||!o||!fs.existsSync(e.buildInfo))return dropBuildInfo(e);try{const s={schema:exports.RECORD_SCHEMA,id:t,configKey:o,at:r()};writeAtomic(e.trust,JSON.stringify(s))}catch{dropBuildInfo(e)}}u(settleBuildInfo,"settleBuildInfo"),c(settleBuildInfo,"settleBuildInfo");const LOCK_SLACK_MS=6e4,UNREADABLE_LOCK_MS=1e4;function pidAlive(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}u(pidAlive,"pidAlive"),c(pidAlive,"pidAlive");function readLock(e){const t=readJson(e);return!isObj(t)||typeof t.pid!="number"||typeof t.token!="string"||typeof t.until!="number"?null:{pid:t.pid,token:t.token,who:typeof t.who=="string"?t.who:"",at:typeof t.at=="number"?t.at:0,until:t.until}}u(readLock,"readLock"),c(readLock,"readLock");function tryLock(e,t){const o=(t.now??Date.now)(),n=(0,node_crypto_1.randomBytes)(8).toString("hex"),r={pid:process.pid,token:n,who:t.who,at:o,until:o+t.holdMs+LOCK_SLACK_MS};fs.mkdirSync(path.dirname(e),{recursive:!0});for(let s=0;s<3;s++){try{return fs.writeFileSync(e,JSON.stringify(r),{flag:"wx"}),{token:n,release(){try{readLock(e)?.token===n&&fs.unlinkSync(e)}catch{}}}}catch(l){if(l.code!=="EEXIST")throw l}let i;try{i=fs.statSync(e)}catch{continue}const a=readLock(e);if(!(a?!(t.isAlive??pidAlive)(a.pid)||o>a.until:o-i.mtimeMs>UNREADABLE_LOCK_MS))return null;try{fs.statSync(e).ino===i.ino&&fs.unlinkSync(e)}catch{}}return null}u(tryLock,"tryLock"),c(tryLock,"tryLock");function readHead(e){return new Promise(t=>{(0,node_child_process_1.execFile)("git",["--no-optional-locks","status","--porcelain=v2","--branch","--","."],{cwd:e,encoding:"utf8",timeout:2e4,maxBuffer:64*1024*1024,env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}},(o,n)=>{if(o)return t({sha:"",dirty:!0});let r="",s=!1;for(const i of String(n).split(`
2
+ `))i.startsWith("# branch.oid ")?r=/^[0-9a-f]{40,64}$/.test(i.slice(13).trim())?i.slice(13).trim():"":i&&!i.startsWith("# ")&&(s=!0);t({sha:r,dirty:s||!r})})})}u(readHead,"readHead"),c(readHead,"readHead");const DIAGNOSTIC_LINE=/^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$/,PROGRAM_ERROR_LINE=/\berror\s+(TS\d+):?\s*(.*)$/,CONFIG_FILE=/\.json$/i,ANSI_CSI=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");class RunOutput{static{u(this,"RunOutput")}static{c(this,"RunOutput")}constructor(t){this.root=t,this.diagnostics=[],this.programErrors=[],this.errorCount=0,this.warningCount=0,this.dropped=0,this.firstLine="",this.rest=""}push(t){this.rest+=t;for(let o=this.rest.indexOf(`
3
+ `);o!==-1;o=this.rest.indexOf(`
4
+ `))this.line(this.rest.slice(0,o)),this.rest=this.rest.slice(o+1)}end(){return this.rest&&this.line(this.rest),this.rest="",this}line(t){const o=t.replace(ANSI_CSI,"").trim();if(!o)return;this.firstLine||(this.firstLine=o.slice(0,300));const n=DIAGNOSTIC_LINE.exec(o);if(n){const[,l="",p="",d="",f="",m="",h=""]=n;if(f==="error"&&CONFIG_FILE.test(l)){this.programErrors.push({code:m,message:h,source:l,line:Number(p),col:Number(d)});return}f==="error"?this.errorCount++:this.warningCount++,this.diagnostics.length>=exports.MAX_RECORD_DIAGNOSTICS?this.dropped++:this.diagnostics.push({file:toWorkspacePath(this.root,l),line:Number(p),col:Number(d),code:m,severity:f==="warning"?"warning":"error",message:h});return}const r=PROGRAM_ERROR_LINE.exec(o);if(!r)return;const[,s="",i=""]=r,a=o.slice(0,r.index).replace(/[\s:]+$/,"");this.programErrors.push({code:s,message:i,...a?{source:a}:{}})}}exports.RunOutput=RunOutput;function concludeRun(e){if(e.spawnError)return{outcome:"tool-error",kind:"spawn-failed",detail:e.spawnError};if(e.timedOut)return{outcome:"tool-error",kind:"timeout",detail:`the check was killed after ${Math.round(e.timeoutMs/1e3)}s without finishing`};if(e.signal)return{outcome:"tool-error",kind:"signal",detail:`the check was ended by ${e.signal} from outside before it finished`};const{programErrors:t}=e.output,o=t[0];if(o){const n=t.some(i=>i.line!==void 0||/^TS5\d{3}$/.test(i.code)),r=t.length>1?` (+${t.length-1} more)`:"",s=e.exitCode===null?"":` (exit ${e.exitCode})`;return{outcome:"tool-error",kind:n?"config-refused":"program-error",code:o.code,detail:`tsgo could not check the program${s}: ${`${o.code}: ${o.message}`.slice(0,300)}${r}`}}return e.exitCode!==0&&e.output.errorCount===0?{outcome:"tool-error",kind:"exit-without-diagnostics",detail:`tsgo exited ${e.exitCode} with no diagnostics: ${e.output.firstLine}`}:{outcome:"verdict"}}u(concludeRun,"concludeRun"),c(concludeRun,"concludeRun");const MAX_BUILD_INFO_HEAD=64*1024*1024;function buildInfoFileNames(e){let t;try{t=fs.openSync(e,"r")}catch{return null}try{const o=Buffer.allocUnsafe(262144),n=new node_string_decoder_1.StringDecoder("utf8");let r="",s=-1,i=0,a=!1;for(let l=0;l<=MAX_BUILD_INFO_HEAD;){const p=fs.readSync(t,o,0,o.length,null);if(p<=0)return null;if(l+=p,r+=n.write(o.subarray(0,p)),s===-1){const d=/"fileNames"\s*:\s*\[/.exec(r);if(!d)continue;s=d.index+d[0].length-1,i=s+1}for(;i<r.length;i++){const d=r.charCodeAt(i);if(a)d===92?i++:d===34&&(a=!1);else if(d===34)a=!0;else if(d===93){const f=JSON.parse(r.slice(s,i+1));return Array.isArray(f)?f:null}}}return null}catch{return null}finally{fs.closeSync(t)}}u(buildInfoFileNames,"buildInfoFileNames"),c(buildInfoFileNames,"buildInfoFileNames");function programInputFiles(e,t){const o=buildInfoFileNames(e);if(!o)return null;const n=path.dirname(e),r=new Set;for(const i of o){if(typeof i!="string"||!i||/^lib\.[\w.]*d\.ts$/.test(i))continue;const a=toWorkspacePath(t,path.resolve(n,i));a.split("/").includes("node_modules")||r.add(a)}const s=[...r].sort();return ignoresCase(t)?[...new Set(namesOnDisk(t,s))].sort():s}u(programInputFiles,"programInputFiles"),c(programInputFiles,"programInputFiles");const caseBlind=new Map;function ignoresCase(e){let t=caseBlind.get(e);if(t===void 0){const o=e===e.toLowerCase()?e.toUpperCase():e.toLowerCase();try{const n=fs.statSync(e),r=fs.statSync(o);t=o!==e&&n.ino===r.ino&&n.dev===r.dev}catch{t=!1}caseBlind.set(e,t)}return t}u(ignoresCase,"ignoresCase"),c(ignoresCase,"ignoresCase");function namesOnDisk(e,t){const o=new Map,n=c(r=>{let s=o.get(r);if(s===void 0){try{s=new Map(fs.readdirSync(path.join(e,r)).map(i=>[i.toLowerCase(),i]))}catch{s=null}o.set(r,s)}return s},"entries");return t.map(r=>{if(r===".."||r.startsWith("../"))return r;const s=[];for(const i of r.split("/"))s.push(n(s.join("/"))?.get(i.toLowerCase())??i);return s.join("/")})}u(namesOnDisk,"namesOnDisk"),c(namesOnDisk,"namesOnDisk");const RECENT_MS=2e3;function statAtStart(e,t,o){const n=new Map,r=new Map;for(const s of t){const i=statFile(e,s);if(n.set(s,i),i&&Math.max(i.mtimeMs,i.ctimeMs)>=o-RECENT_MS){const a=hashFile(e,s);a&&r.set(s,a)}}return{at:o,stats:n,recent:r}}u(statAtStart,"statAtStart"),c(statAtStart,"statAtStart");async function stampAfterRun(e){const{root:t,start:o}=e,n=[],r=[],s=[];for(const i of e.files){const a=statFile(t,i),l=o.stats.get(i),p=!!a&&(l===void 0?Math.max(a.mtimeMs,a.ctimeMs)<o.at-RECENT_MS:l!==null&&sameStat(l,a));if(!a||!p){n.push(i);continue}const d=o.recent.get(i),f=e.previous?.get(i);!d&&f?.hash&&sameStat(f,a)?s.push({file:i,...a,hash:f.hash}):r.push({file:i,stat:a,...d?{expect:d}:{}})}for(const{file:i,stat:a,expect:l}of r){const p=await hashFileLater(t,i),d=statFile(t,i);!p||!d||!sameStat(a,d)||l!==void 0&&l!==p?n.push(i):s.push({file:i,...a,hash:p})}return s.sort((i,a)=>i.file<a.file?-1:i.file>a.file?1:0),{stamps:s,changed:n.sort()}}u(stampAfterRun,"stampAfterRun"),c(stampAfterRun,"stampAfterRun");const MAX_CHANGED_NAMED=20,unvouched=c(e=>({file:e,mtimeMs:0,ctimeMs:0,size:0,ino:0,hash:""}),"unvouched");function stampsHashOf(e){const t=(0,node_crypto_1.createHash)("sha256");for(const o of e)o.hash&&t.update(`${o.file}\0${o.hash}
5
+ `);return t.digest("hex")}u(stampsHashOf,"stampsHashOf"),c(stampsHashOf,"stampsHashOf");function inputsHashOf(e){return e.files?sha256(`${e.configKey}\0${e.files.hash}`):""}u(inputsHashOf,"inputsHashOf"),c(inputsHashOf,"inputsHashOf");function writeVerdict(e,t,o){const n=readRecord(e,t.id);if(n&&n.startedAt>t.startedAt)return!1;if(o){const r={schema:exports.RECORD_SCHEMA,id:t.id,startedAt:t.startedAt,files:o.map(s=>[s.file,s.mtimeMs,s.ctimeMs,s.size,s.ino,s.hash])};writeAtomic(e.stamps,JSON.stringify(r))}else fs.rmSync(e.stamps,{force:!0});return writeAtomic(e.record,JSON.stringify(t)),!0}u(writeVerdict,"writeVerdict"),c(writeVerdict,"writeVerdict");function readRecord(e,t){const o=readJson(e.record);return!isObj(o)||o.schema!==exports.RECORD_SCHEMA||o.id!==t||typeof o.startedAt!="number"||!Array.isArray(o.diagnostics)||o.outcome!=="verdict"&&o.outcome!=="tool-error"?null:o}u(readRecord,"readRecord"),c(readRecord,"readRecord");function readStampsOfAnyRun(e,t,o){const n=readJson(e.stamps);if(!isObj(n)||n.schema!==exports.RECORD_SCHEMA||n.id!==t||!Array.isArray(n.files)||o!==void 0&&n.startedAt!==o)return null;const r=new Map;for(const s of n.files){if(!Array.isArray(s)||typeof s[0]!="string")return null;const[i,a,l,p,d,f]=s;r.set(i,{file:i,mtimeMs:a,ctimeMs:l,size:p,ino:d,hash:f})}return r}u(readStampsOfAnyRun,"readStampsOfAnyRun"),c(readStampsOfAnyRun,"readStampsOfAnyRun");function readStamps(e,t){return readStampsOfAnyRun(e,t.id,t.startedAt)}u(readStamps,"readStamps"),c(readStamps,"readStamps");function beginRun(e){const t=e.now??Date.now,o=programFiles(e.root,e.id),n=configInputs(e);let r=!1;e.buildInfo==="kept"?r=trustBuildInfo(o,e.id,n.key):e.buildInfo==="cold"&&dropBuildInfo(o);let s=e.tsconfig;e.route==="tsgo-shim"&&((0,tsgo_shim_1.writeShim)(o.shim,e.tsconfig,{flags:e.flags??[],...e.pinsOnly?{pinsOnly:!0}:{}}),s=o.shim);const i=readStampsOfAnyRun(o,e.id),a=new Set([...(r?programInputFiles(o.buildInfo,e.root):null)??[],...i?.keys()??[],...e.knownFiles??[]]),l=t();return{root:e.root,id:e.id,tsconfig:toWorkspacePath(e.root,e.tsconfig),route:e.route,flags:[...e.flags??[]],compilerVersion:e.compiler.version,who:e.who,files:o,project:s,config:n,buildInfo:e.buildInfo,warm:r,startedAt:l,start:statAtStart(e.root,[...a],l),previous:i,head:readHead(e.root),now:t}}u(beginRun,"beginRun"),c(beginRun,"beginRun");function recordUnrun(e){const t=(e.now??Date.now)(),o=programFiles(e.root,e.id),n={schema:exports.RECORD_SCHEMA,id:e.id,tsconfig:toWorkspacePath(e.root,e.tsconfig),route:e.route,...e.flags?.length?{flags:[...e.flags]}:{},compiler:{name:"tsgo",version:e.compilerVersion??""},configKey:"",inputs:[],by:{who:e.who,pid:process.pid},startedAt:t,endedAt:t,durationMs:0,outcome:"tool-error",toolError:{kind:"spawn-failed",detail:e.detail},head:{sha:"",dirty:!0},errorCount:0,warningCount:0,diagnostics:[],changedDuringRun:!1,files:null};let r=null;try{return!e.locked&&(r=tryLock(o.lock,{holdMs:0,who:e.who,...e.now?{now:e.now}:{}}),!r)?{record:n,kept:!1}:(dropBuildInfo(o),{record:n,kept:writeVerdict(o,n,null)})}catch{return{record:n,kept:!1}}finally{r?.release()}}u(recordUnrun,"recordUnrun"),c(recordUnrun,"recordUnrun");function finishRun(e,t,o={}){const n=e.now(),r=t.conclusion.outcome==="verdict";let s,i=null;if(e.buildInfo!=="none"){try{s=fs.statSync(e.files.buildInfo).size,r&&(i=programInputFiles(e.files.buildInfo,e.root))}catch{s=void 0}settleBuildInfo(e.files,e.id,e.buildInfo==="kept"?e.config.key:void 0,r,e.now)}const a=i?stampAfterRun({root:e.root,start:e.start,files:i,previous:e.previous}):Promise.resolve(null);return(async()=>{const l=await a,p=await e.head,d=l?.changed.length??0,f={schema:exports.RECORD_SCHEMA,id:e.id,tsconfig:e.tsconfig,route:e.route,...e.flags.length?{flags:e.flags}:{},compiler:{name:"tsgo",version:e.compilerVersion},...e.route==="tsgo-shim"?{shimVersion:tsgo_shim_1.SHIM_VERSION}:{},configKey:e.config.key,inputs:e.config.inputs,by:{who:e.who,pid:process.pid},startedAt:e.startedAt,endedAt:n,durationMs:Math.max(0,n-e.startedAt),...t.peakMb!==void 0?{peakMb:t.peakMb,...t.peakHow?{peakHow:t.peakHow}:{}}:{},outcome:t.conclusion.outcome,...t.conclusion.outcome==="tool-error"?{toolError:{kind:t.conclusion.kind,...t.conclusion.code?{code:t.conclusion.code}:{},detail:t.conclusion.detail}}:{},head:p,errorCount:r?t.errorCount:0,warningCount:r?t.warningCount:0,diagnostics:r?t.diagnostics.slice(0,exports.MAX_RECORD_DIAGNOSTICS):[],...r&&(t.dropped??0)+Math.max(0,t.diagnostics.length-exports.MAX_RECORD_DIAGNOSTICS)>0?{droppedDiagnostics:(t.dropped??0)+Math.max(0,t.diagnostics.length-exports.MAX_RECORD_DIAGNOSTICS)}:{},changedDuringRun:d>0,...l&&d>0?{changed:l.changed.slice(0,MAX_CHANGED_NAMED),changedCount:d}:{},files:l?{count:l.stamps.length+d,hash:stampsHashOf(l.stamps)}:null,...r&&s!==void 0?{buildInfo:{bytes:s,warm:e.warm}}:{}};if(o.keep&&!o.keep())return{record:f,kept:!1};try{const m=l?[...l.stamps,...l.changed.map(unvouched)].sort((h,g)=>h.file<g.file?-1:h.file>g.file?1:0):null;return{record:f,kept:writeVerdict(e.files,f,m)}}catch{return{record:f,kept:!1}}})()}u(finishRun,"finishRun"),c(finishRun,"finishRun");
@@ -22,14 +22,43 @@
22
22
  *
23
23
  * INCREMENTAL (issues/closed/foodguard-94). Cold was the design — and on foodguard every save to a shared library
24
24
  * re-checked all of it once per service: 1,054 checks in 12 hours, up to 5.9GB each. So a check keeps what it learnt
25
- * in a build-info file beside its shim (`tmp/lensmcp-tsgo/<app>.tsbuildinfo`, `--incremental --tsBuildInfoFile`): the
25
+ * in a build-info file beside its shim (`tmp/lensmcp-tsgo/<id>.tsbuildinfo`, `--incremental --tsBuildInfoFile`): the
26
26
  * next one re-checks only the files a change can affect, and reports the errors of the rest from that file. Still
27
27
  * nothing is resident between saves — the knowledge is on disk. A run that gave no verdict (killed at its timeout or from
28
- * outside, a position-less program error such as TS18003, the checker failing) deletes the file, so a bad one is never
29
- * read twice. `LENSMCP_TSGO_INCREMENTAL=0` checks cold.
28
+ * outside, a program error such as TS18003 or an option the compiler refuses, the checker failing) deletes the file, so
29
+ * a bad one is never read twice. `LENSMCP_TSGO_INCREMENTAL=0` checks cold.
30
30
  * And a check's turn waits for memory: the queue holds it while the machine has little free, and it says so
31
31
  * (`[tsgo] <app>: check held …`, and a `phase: 'held'` event the lens shows in `service_state`).
32
32
  *
33
+ * ONE PROGRAM, WHOEVER CHECKS IT (planning/checks/00-plan.md § 5–6; issues: overseer-75). A service's check is a check
34
+ * of one program of the workspace's census — its app tsconfig, through the shim — and `lensmcp typecheck` checks that
35
+ * program too. So its files are named by the program's id (`program-id.ts`), not by the service: one shim, one build
36
+ * info, one lock and one verdict record between the two. What that adds to a check here (`static-checks-record.ts`,
37
+ * the same file in `@lensmcp/static-checks`):
38
+ * - the build info is read only when its trust record names the inputs as they are now — the compiler, the shim's
39
+ * version, every file of the tsconfig chain, the lockfile. Any of them changed: this check starts cold;
40
+ * - the program's lock is taken for the length of the check. While `lensmcp typecheck` checks this program, the
41
+ * service's check gives its slot back and asks again a second later;
42
+ * - every check leaves a record in `.lensmcp/static-checks/typecheck/<id>.json` — its diagnostics, uncapped, the
43
+ * commit, and each input file as it was when the check started — and a run with no verdict leaves one that says
44
+ * so. `lensmcp typecheck` answers from it without starting a compiler while nothing changed.
45
+ *
46
+ * ITS OWN MEMORY (planning/checks/00-plan.md § Memory bounds, slice C6). The turn used to wait for one amount of free
47
+ * memory whatever the service; a check of FoodGuard's engine holds 5.9 GB and started on two. Now a check says what its
48
+ * program's last check held (`typecheck-memory.ts`, the same file in `@lensmcp/static-checks`) and its turn waits for
49
+ * that and a quarter more — more after a cold start than a warm one — and a service whose check held more than
50
+ * `LENSMCP_TYPECHECK_CHECKERS_ABOVE_MB` is checked with `--checkers 2`: `GOMAXPROCS` bounds the threads, not the four
51
+ * checkers and their type tables. Three things are deliberately NOT done to a service's check:
52
+ * - it is not wrapped in `time`, as `lensmcp typecheck`'s is. This process stops a checker by killing the process it
53
+ * started; under a wrapper that is the wrapper, and the compiler would run on with nobody waiting for it — unless
54
+ * it led a process group of its own, which the gateway's stop of this service's group would then no longer reach.
55
+ * So the peak is READ while the check runs: one `ps` now and every half second, the largest resident size seen —
56
+ * a lower bound, and recorded as `sampled`;
57
+ * - with no figure of its own program — a first check, or a Node whose launcher keeps the compiler as a child, where
58
+ * `ps` of what was started says nothing — it waits for the line's least amount, as before. Nobody waits for this
59
+ * check, so nobody would be told that a guess held it;
60
+ * - nothing here may disturb a build: every read of what is known is swallowed, and the check then runs as it did.
61
+ *
33
62
  * The output CONTRACT is the point: `--pretty false` prints classic `file.ts(1,2): error TS1234:`
34
63
  * lines to the executor's console, which the gateway sniffs (`error TS\d+`) into the lens
35
64
  * "service error" signal — the same wire the fork-ts-checker fed. Advisory like
@@ -40,12 +69,8 @@
40
69
  *
41
70
  * SHIM tsconfig: tsgo is TS7 — `moduleResolution: node10` (what node-app tsconfigs often pin) is
42
71
  * REMOVED there, so the check runs against a generated shim extending the app tsconfig with
43
- * `{ module: 'preserve', moduleResolution: 'bundler', isolatedModules: false }`. `extends` is an
44
- * ABSOLUTE path and tsconfig path-options resolve relative to the file they ORIGINATE in, so the
45
- * shim lives in the workspace's git-ignored `tmp/` (in-tree, so @types resolution still walks up to
46
- * the workspace node_modules — see writeShimTsconfig). `isolatedModules: false` because
47
- * `module: preserve` + `emitDecoratorMetadata` otherwise flags TS1272 on decorated signatures —
48
- * an emit-safety rule that doesn't apply here (this checker never emits; webpack owns emit).
72
+ * `{ module: 'preserve', moduleResolution: 'bundler', isolatedModules: false }` and the other changes
73
+ * `tsgo-shim.ts` lists (it says why each, and why the shim lives in the workspace's git-ignored `tmp/`).
49
74
  * Parity was verified per adopting workspace (0-error parity with tsc on all spot-checked apps);
50
75
  * tsgo is a PREVIEW compiler; it was opt-in until the queue, the memory hold and incremental checks made it the safer
51
76
  * default (1.25.49) — `LENSMCP_TYPECHECK=tsc` keeps fork-ts-checker for a workspace that needs it.
@@ -59,7 +84,9 @@
59
84
  * reports itself onto the lens bus instead of only warning into a log nobody reads.
60
85
  */
61
86
  import { spawn } from 'node:child_process';
87
+ import { type ProgramFiles } from './static-checks-record';
62
88
  import { type TypecheckQueue } from './typecheck-queue';
89
+ export { effectivePaths, tsconfigChain, writeShimTsconfig } from './tsgo-shim';
63
90
  export interface TsgoCheckPluginOptions {
64
91
  appName: string;
65
92
  /** Absolute path to the app tsconfig the check covers. */
@@ -86,15 +113,34 @@ export interface TsgoCheckPluginOptions {
86
113
  maxProcs?: number;
87
114
  /** Keep a build-info file between checks (see the header). Default {@link tsgoIncremental}. */
88
115
  incremental?: boolean;
116
+ /**
117
+ * How the running checker's resident size is read, for its peak (see the header); `false`: it is not, and the check
118
+ * keeps the line's least amount. Default: `ps`, where what is started becomes the compiler. Injectable for tests.
119
+ */
120
+ readRssMb?: ((pid: number) => Promise<number | undefined>) | false;
89
121
  }
90
122
  /** `LENSMCP_TYPECHECK_GOMAXPROCS`, else {@link DEFAULT_MAX_PROCS}. An explicit `GOMAXPROCS` in the env wins over both. */
91
123
  export declare function checkerMaxProcs(env?: NodeJS.ProcessEnv): number;
92
124
  /** `LENSMCP_TSGO_INCREMENTAL` — on unless it is `0`/`false`/`off`. */
93
125
  export declare function tsgoIncremental(env?: NodeJS.ProcessEnv): boolean;
94
- /** Where a service's check keeps what it learnt: beside its shim, in the workspace's git-ignored `tmp/`. */
95
- export declare function tsgoBuildInfoPath(appName: string, workspaceRoot: string): string;
96
- /** The checker's arguments. `--pretty false` is the output contract (see the header); the build info is optional. */
97
- export declare function tsgoCheckArgs(shimPath: string, buildInfo?: string): string[];
126
+ /**
127
+ * The program a service's check is — its tsconfig, through the shim — and where its files are: the shim, the build
128
+ * info and the lock in the workspace's git-ignored `tmp/`, the verdict record in `.lensmcp/`. Named by the program's id,
129
+ * which `lensmcp typecheck` computes the same way for the same tsconfig, so the two share them.
130
+ *
131
+ * «Through the shim» is the shim that MIGRATES (tsgo-shim.ts): with it comes everything of the shim's list — since v3
132
+ * the workspace compiler's defaults too, where that compiler is older than TypeScript 6. A tsconfig TS7 takes as it is
133
+ * is another program in the census (the tsconfig as it is, or through the shim of the pins alone), under another id.
134
+ */
135
+ export declare function tsgoProgram(tsConfig: string, workspaceRoot: string): {
136
+ id: string;
137
+ files: ProgramFiles;
138
+ };
139
+ /**
140
+ * The checker's arguments. `--pretty false` is the output contract (see the header); the build info is optional, and
141
+ * so is what bounds its memory (`--checkers 2`, `--singleThreaded` — typecheck-memory.ts `chooseCheckers`).
142
+ */
143
+ export declare function tsgoCheckArgs(shimPath: string, buildInfo?: string, memory?: readonly string[]): string[];
98
144
  /** The npm package that ships the tsgo compiler — a real `dependency` of `@lensmcp/cluster`. */
99
145
  /**
100
146
  * The checker `LENSMCP_TYPECHECK` asks for (planning/modules/03-settings-pages.md): `tsgo` unless it says otherwise —
@@ -166,33 +212,6 @@ export declare function reportTsgoUnavailable(args: {
166
212
  /** Override the lens bus file. Injectable for tests. */
167
213
  eventFile?: string;
168
214
  }): void;
169
- /**
170
- * The `paths` in effect for a config, and the directory they are anchored at.
171
- *
172
- * Walks the `extends` chain leaf-first; the nearest declaration wins (tsconfig REPLACES `paths`,
173
- * it does not merge them). The anchor is the nearest `baseUrl`, resolved against the file that
174
- * declared IT — or, with no baseUrl anywhere, the file that declared the paths.
175
- */
176
- export declare function effectivePaths(tsConfig: string, seen?: Set<string>): {
177
- paths: Record<string, string[]>;
178
- anchorDir: string;
179
- } | null;
180
- /**
181
- * The tsconfig and every file it extends, as {@link effectivePaths} walks them — what a check's configuration is read
182
- * from (issues/closed/foodguard-115). The tsconfig itself is always listed, even when it cannot be read: a half-saved
183
- * file is watched until the next save. A file extended from node_modules changes only with an install, and is left
184
- * out, as `configFilesOf` leaves it out. Read with this file's own parser, so a service that type-checks with tsgo
185
- * never loads TypeScript into its process just to list its config files.
186
- */
187
- export declare function tsconfigChain(tsConfig: string): string[];
188
- /**
189
- * Write the shim for one check, and return its path. Called before EVERY check (issues/closed/foodguard-115): the
190
- * shim's `paths` REPLACE the ones the tsconfig chain declares, so they are the one part of the configuration tsgo
191
- * does not read for itself. Written once, a shim kept the aliases the chain had when the service started: FoodGuard
192
- * added `@foodguard-shared/execution-graph` to `tsconfig.base.json`, the bundle built with it, and every check for
193
- * the next 80 minutes still reported «TS2307: Cannot find module». The file is left alone when it would not change.
194
- */
195
- export declare function writeShimTsconfig(appName: string, tsConfig: string, workspaceRoot: string): string;
196
215
  export declare class TsgoCheckPlugin {
197
216
  private readonly opts;
198
217
  private readonly spawnImpl;
@@ -206,8 +225,16 @@ export declare class TsgoCheckPlugin {
206
225
  private inflight;
207
226
  private askedAt;
208
227
  private shimPath;
209
- /** The build-info file the checks keep, when they are incremental. */
210
- private readonly buildInfo;
228
+ /** The program this service's check is, and its files (see {@link tsgoProgram}). */
229
+ private readonly program;
230
+ /** The checks keep a build-info file between them. */
231
+ private readonly incremental;
232
+ /** The program's lock, for as long as this plugin's checker runs. */
233
+ private lock;
234
+ /** What the check now in line waits for, when its program was measured: said when its turn is held for it. */
235
+ private need;
236
+ /** A flag this compiler does not take is said once, not at every check. */
237
+ private saidUntaken;
211
238
  private disabled;
212
239
  private disposed;
213
240
  constructor(opts: TsgoCheckPluginOptions);
@@ -221,8 +248,37 @@ export declare class TsgoCheckPlugin {
221
248
  * it cannot be stopped politely, and alone it is done in seconds.
222
249
  */
223
250
  private request;
251
+ /**
252
+ * What this check's turn waits for, from what its program's last checks held — more after a cold start than a warm
253
+ * one, so it reads which this one will be: the build info's trust record, under the inputs as they are now.
254
+ * Undefined — the line's least amount — when the program was never measured, and when anything here fails: a
255
+ * service's check is not held on a guess (see the header), and never stopped by this read.
256
+ */
257
+ private memoryNeed;
258
+ /** How many checkers this check runs with (typecheck-memory.ts): the compiler's own number unless its program's checks held too much — and when the read fails. */
259
+ private checkers;
260
+ /** Look at the checker's memory while it runs (see the header). Null where that would say nothing, or is turned off. */
261
+ private sample;
262
+ /** A check that gave a verdict says what it held: kept for the next one's turn (typecheck-memory.ts), and in its record. */
263
+ private measured;
224
264
  /** Its turn came and waits for memory: said once, so a check that has not run reads «held», not «slow». */
225
265
  private held;
266
+ /**
267
+ * Another check of this program is running — `lensmcp typecheck`'s, or a second service's on the same tsconfig. Two
268
+ * compilers would write one build info, so this one gives its slot back and asks again shortly; a build that lands
269
+ * meanwhile asks in its place.
270
+ */
271
+ private waitForLock;
272
+ /**
273
+ * What a finished run leaves on disk (static-checks-record.ts): its build info settled — kept under the inputs it
274
+ * was made with after a verdict, deleted after anything else, so a bad one is never read twice — and its record,
275
+ * which `lensmcp typecheck` answers from. The settling and a look at every input file happen before this returns,
276
+ * so the check that follows at once starts from a build info it may trust; the record itself is written a moment
277
+ * later, off the build's path. Strictly passive, like {@link publish}: nothing here may disturb a build.
278
+ */
279
+ private record;
280
+ /** A check that could not start leaves a record that says so, in place of the verdict before it. */
281
+ private recordUnrun;
226
282
  /** A run that gave no verdict may have left a build-info file nobody should trust: the next check starts cold. */
227
283
  private forgetBuildInfo;
228
284
  /** Asked through a method on purpose: `run()` may have moved the phase inside the call above. */
@@ -233,10 +289,18 @@ export declare class TsgoCheckPlugin {
233
289
  * contract webpack/the gateway rely on, this is pure observation on top.
234
290
  */
235
291
  private publish;
236
- /** This service's turn in the line. */
292
+ /**
293
+ * This service's turn in the line. A check that is to be given a flag (`--checkers 2`) needs the compiler asked
294
+ * whether it takes it — once per compiler, some tens of milliseconds, seconds on a starved machine. That question is
295
+ * never asked on this service's thread: the turn is this service's already, and its check starts when the answer is in.
296
+ */
237
297
  private run;
298
+ /** The compiler asked what it takes, where this check wants a flag and nobody asked yet. Undefined: nothing to wait for. */
299
+ private askCompiler;
300
+ private start;
238
301
  /** The check is over: give the slot back, and check once more if a build landed meanwhile. */
239
302
  private finish;
303
+ /** Give back the slot in the line — and the program's lock, held only while this plugin's checker runs. */
240
304
  private leave;
241
305
  /** The dev server is going away: leave the line, and stop the checker for real (it ignores SIGTERM). */
242
306
  dispose(): void;
@@ -1,5 +1,4 @@
1
- "use strict";var v=Object.defineProperty;var l=(e,t)=>v(e,"name",{value:t,configurable:!0});var y=Object.defineProperty,c=l((e,t)=>y(e,"name",{value:t,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.TsgoCheckPlugin=exports.TSGO_MISSING_CAUSE=exports.TSGO_PACKAGE=void 0,exports.checkerMaxProcs=checkerMaxProcs,exports.tsgoIncremental=tsgoIncremental,exports.tsgoBuildInfoPath=tsgoBuildInfoPath,exports.tsgoCheckArgs=tsgoCheckArgs,exports.typecheckMode=typecheckMode,exports.resolveTsgoPackageDir=resolveTsgoPackageDir,exports.resolveTsgoBin=resolveTsgoBin,exports.reportTsgoUnavailable=reportTsgoUnavailable,exports.effectivePaths=effectivePaths,exports.tsconfigChain=tsconfigChain,exports.writeShimTsconfig=writeShimTsconfig;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),typecheck_bus_1=require("./typecheck-bus"),typecheck_queue_1=require("./typecheck-queue"),DEFAULT_TIMEOUT_MS=12e4,DEFAULT_MAX_PROCS=4;function checkerMaxProcs(e=process.env){const t=Number(e.LENSMCP_TYPECHECK_GOMAXPROCS);return Number.isInteger(t)&&t>=1?t:DEFAULT_MAX_PROCS}l(checkerMaxProcs,"checkerMaxProcs"),c(checkerMaxProcs,"checkerMaxProcs");function tsgoIncremental(e=process.env){const t=(e.LENSMCP_TSGO_INCREMENTAL??"").trim().toLowerCase();return!(t==="0"||t==="false"||t==="off"||t==="no")}l(tsgoIncremental,"tsgoIncremental"),c(tsgoIncremental,"tsgoIncremental");function tsgoBuildInfoPath(e,t){return path.join(t,"tmp","lensmcp-tsgo",`${e}.tsbuildinfo`)}l(tsgoBuildInfoPath,"tsgoBuildInfoPath"),c(tsgoBuildInfoPath,"tsgoBuildInfoPath");function tsgoCheckArgs(e,t){return["--noEmit","--pretty","false",...t?["--incremental","--tsBuildInfoFile",t]:[],"-p",e]}l(tsgoCheckArgs,"tsgoCheckArgs"),c(tsgoCheckArgs,"tsgoCheckArgs");const livePlugins=new Set;let exitHooked=!1;function stopWithTheProcess(e){livePlugins.add(e),!exitHooked&&(exitHooked=!0,process.once("exit",()=>{for(const t of livePlugins)t.dispose()}))}l(stopWithTheProcess,"stopWithTheProcess"),c(stopWithTheProcess,"stopWithTheProcess");function typecheckMode(e=process.env){const t=e.LENSMCP_TYPECHECK;return t===void 0||t===""||t==="tsgo"?"tsgo":t==="off"?"off":"tsc"}l(typecheckMode,"typecheckMode"),c(typecheckMode,"typecheckMode"),exports.TSGO_PACKAGE="@typescript/native-preview";function shimNames(e){return e==="win32"?["tsgo.cmd","tsgo.exe"]:["tsgo"]}l(shimNames,"shimNames"),c(shimNames,"shimNames");function isExecutableFile(e,t){try{if(!fs.statSync(e).isFile())return!1}catch{return!1}if(t==="win32")return!0;try{return fs.accessSync(e,fs.constants.X_OK),!0}catch{return!1}}l(isExecutableFile,"isExecutableFile"),c(isExecutableFile,"isExecutableFile");function resolveTsgoPackageDir(){try{return path.dirname(require.resolve(`${exports.TSGO_PACKAGE}/package.json`))}catch{}try{let e=path.dirname(require.resolve(exports.TSGO_PACKAGE));for(let t=0;t<6;t++){const o=path.join(e,"package.json");if(fs.existsSync(o))try{const{name:s}=JSON.parse(fs.readFileSync(o,"utf8"));if(s===exports.TSGO_PACKAGE)return e}catch{}const r=path.dirname(e);if(r===e)break;e=r}}catch{}return null}l(resolveTsgoPackageDir,"resolveTsgoPackageDir"),c(resolveTsgoPackageDir,"resolveTsgoPackageDir");function packageDeclaredBin(e){try{const{bin:t}=JSON.parse(fs.readFileSync(path.join(e,"package.json"),"utf8")),o=typeof t=="string"?t:t?.tsgo;return o?path.join(e,o):null}catch{return null}}l(packageDeclaredBin,"packageDeclaredBin"),c(packageDeclaredBin,"packageDeclaredBin");function ownBinCandidates(e,t){const o=path.resolve(e,"..","..",".bin"),r=shimNames(t).map(i=>path.join(o,i)),s=t==="win32"?null:packageDeclaredBin(e);return s?[s,...r]:r}l(ownBinCandidates,"ownBinCandidates"),c(ownBinCandidates,"ownBinCandidates");function resolveTsgoBin(e,t,o={}){const r=o.platform??process.platform,s=o.isExecutable??(n=>isExecutableFile(n,r));if(t)return s(t)?t:null;for(const n of shimNames(r)){const a=path.join(e,"node_modules",".bin",n);if(s(a))return a}const i=(o.ownPackageDir??resolveTsgoPackageDir)();return i?ownBinCandidates(i,r).find(s)??null:null}l(resolveTsgoBin,"resolveTsgoBin"),c(resolveTsgoBin,"resolveTsgoBin"),exports.TSGO_MISSING_CAUSE=`tsgo binary not found \u2014 @lensmcp/cluster depends on ${exports.TSGO_PACKAGE}, so an absent binary means an incomplete install (reinstall node_modules), a platform with no ${exports.TSGO_PACKAGE} build, or a LENSMCP_TSGO_BIN override pointing at a missing or non-executable file`;function reportTsgoUnavailable(e){try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:e.workspaceRoot,project:e.appName,tool:"tsgo",tsConfig:e.tsConfig,output:"",durationMs:0,toolError:e.detail,...e.eventFile?{eventFile:e.eventFile}:{}})}catch{}}l(reportTsgoUnavailable,"reportTsgoUnavailable"),c(reportTsgoUnavailable,"reportTsgoUnavailable");function parseJsonc(e){let t="",o=!1,r=!1,s=!1;for(let i=0;i<e.length;i++){const n=e[i],a=e[i+1];if(r){n===`
2
- `&&(r=!1,t+=n);continue}if(s){n==="*"&&a==="/"&&(s=!1,i++);continue}if(o){t+=n,n==="\\"?(t+=a??"",i++):n==='"'&&(o=!1);continue}if(n==='"'){o=!0,t+=n;continue}if(n==="/"&&a==="/"){r=!0,i++;continue}if(n==="/"&&a==="*"){s=!0,i++;continue}t+=n}try{return JSON.parse(t.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}l(parseJsonc,"parseJsonc"),c(parseJsonc,"parseJsonc");function resolveExtends(e,t){if(!e.startsWith(".")&&!path.isAbsolute(e))return null;const o=path.isAbsolute(e)?e:path.resolve(t,e);for(const r of[o,`${o}.json`,path.join(o,"tsconfig.json")])try{if(fs.statSync(r).isFile())return r}catch{}return null}l(resolveExtends,"resolveExtends"),c(resolveExtends,"resolveExtends");function effectivePaths(e,t=new Set){if(t.has(e))return null;t.add(e);let o;try{o=fs.readFileSync(e,"utf8")}catch{return null}const r=parseJsonc(o);if(!r)return null;const s=path.dirname(e),i=r.compilerOptions??{},n=Array.isArray(r.extends)?r.extends.filter(p=>typeof p=="string"):typeof r.extends=="string"?[r.extends]:[],a=c(()=>{for(const p of[...n].reverse()){const d=resolveExtends(p,s);if(!d)continue;const g=effectivePaths(d,t);if(g)return g}return null},"inherited"),u=i.paths,h=typeof i.baseUrl=="string"?path.resolve(s,i.baseUrl):void 0;if(!u){const p=a();return p?{paths:p.paths,anchorDir:h??p.anchorDir}:null}return{paths:u,anchorDir:h??a()?.anchorDir??s}}l(effectivePaths,"effectivePaths"),c(effectivePaths,"effectivePaths");function tsconfigChain(e){const t=[],o=c(r=>{if(t.includes(r))return;t.push(r);let s;try{s=parseJsonc(fs.readFileSync(r,"utf8"))}catch{return}const i=s?.extends,n=Array.isArray(i)?i.filter(a=>typeof a=="string"):typeof i=="string"?[i]:[];for(const a of n){const u=resolveExtends(a,path.dirname(r));u&&!u.split(path.sep).includes("node_modules")&&o(u)}},"visit");return o(path.resolve(e)),t}l(tsconfigChain,"tsconfigChain"),c(tsconfigChain,"tsconfigChain");function writeShimTsconfig(e,t,o){const r=path.join(o,"tmp","lensmcp-tsgo");fs.mkdirSync(r,{recursive:!0});const s=path.join(r,`${e}.tsconfig.json`),i=effectivePaths(t),n=i?Object.fromEntries(Object.entries(i.paths).map(([h,p])=>[h,(Array.isArray(p)?p:[]).map(d=>path.isAbsolute(d)?d:path.resolve(i.anchorDir,d))])):void 0,a=JSON.stringify({extends:t,compilerOptions:{module:"preserve",moduleResolution:"bundler",isolatedModules:!1,baseUrl:null,...n&&Object.keys(n).length?{paths:n}:{}}},null,2);let u;try{u=fs.readFileSync(s,"utf8")}catch{}return u!==a&&fs.writeFileSync(s,a),s}l(writeShimTsconfig,"writeShimTsconfig"),c(writeShimTsconfig,"writeShimTsconfig");class TsgoCheckPlugin{static{l(this,"TsgoCheckPlugin")}static{c(this,"TsgoCheckPlugin")}constructor(t){this.timer=null,this.phase="idle",this.dirty=!1,this.ticket=null,this.inflight=null,this.askedAt=0,this.shimPath=null,this.disabled=!1,this.disposed=!1,this.opts=t,this.spawnImpl=t.spawnImpl??node_child_process_1.spawn,this.queue=t.queue??(0,typecheck_queue_1.machineTypecheckQueue)(),this.buildInfo=t.incremental??tsgoIncremental()?tsgoBuildInfoPath(t.appName,t.workspaceRoot):void 0}apply(t){t.hooks.done.tap("TsgoCheckPlugin",o=>{o.hasErrors()||this.schedule()}),t.hooks.shutdown?.tap?.("TsgoCheckPlugin",()=>this.dispose()),t.hooks.watchClose?.tap?.("TsgoCheckPlugin",()=>this.dispose()),stopWithTheProcess(this)}schedule(){this.disabled||this.disposed||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.request(),this.opts.debounceMs??500),this.timer.unref?.())}request(){if(this.disabled||this.disposed)return;if(this.phase==="running"){this.dirty=!0;return}if(this.phase==="waiting")return;this.phase="waiting",this.askedAt=Date.now();const t=this.queue(this.opts.appName,()=>this.run(),{onHold:c(o=>this.held(o),"onHold")});this.isIdle()?t.release():this.ticket=t}held(t){if(!this.disposed&&(console.log(`[tsgo] ${this.opts.appName}: check held \u2014 ${t.availableMb} MB free, it waits for ${t.minFreeMb} MB (LENSMCP_TYPECHECK_MIN_FREE_MB)`),this.opts.publishEvents!==!1))try{(0,typecheck_bus_1.publishTypecheckHeld)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"tsgo",tsConfig:this.opts.tsConfig,availableMb:t.availableMb,minFreeMb:t.minFreeMb,...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}}forgetBuildInfo(){if(this.buildInfo)try{fs.rmSync(this.buildInfo,{force:!0})}catch{}}isIdle(){return this.phase==="idle"}publish(t){if(this.opts.publishEvents!==!1)try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"tsgo",tsConfig:this.opts.tsConfig,output:t.output,durationMs:t.durationMs,...t.toolError?{toolError:t.toolError}:{},...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}}run(){if(this.disposed)return this.leave();let t;try{t=resolveTsgoBin(this.opts.workspaceRoot,this.opts.binPath),t&&(this.shimPath=writeShimTsconfig(this.opts.appName,this.opts.tsConfig,this.opts.workspaceRoot))}catch(h){return console.warn(`[tsgo] ${this.opts.appName}: could not prepare the check \u2014 ${h.message}`),this.publish({output:"",durationMs:0,toolError:`could not prepare the check: ${h.message}`}),this.leave()}if(!t){this.disabled=!0;const h=`${exports.TSGO_MISSING_CAUSE}. Type checking is disabled for the rest of this session`;return console.warn(`[tsgo] ${this.opts.appName}: ${h}.`),this.publish({output:"",durationMs:0,toolError:h}),this.leave()}this.phase="running",this.dirty=!1;const o=Date.now(),r=o-this.askedAt,s=this.spawnImpl(t,tsgoCheckArgs(this.shimPath,this.buildInfo),{cwd:this.opts.workspaceRoot,stdio:["ignore","pipe","pipe"],env:{...process.env,GOMAXPROCS:process.env.GOMAXPROCS??String(this.opts.maxProcs??checkerMaxProcs())}});this.inflight=s;let i="",n=!1;const a=this.opts.timeoutMs??DEFAULT_TIMEOUT_MS,u=setTimeout(()=>{n=!0,s.kill("SIGKILL")},a);u.unref?.(),s.stdout?.on("data",h=>{i+=h.toString()}),s.stderr?.on("data",h=>{i+=h.toString()}),s.on("error",()=>{clearTimeout(u),this.inflight===s&&(console.warn(`[tsgo] ${this.opts.appName}: failed to spawn ${t}`),this.forgetBuildInfo(),this.publish({output:"",durationMs:Date.now()-o,toolError:`failed to spawn ${t}`}),this.finish(s))}),s.on("close",(h,p)=>{if(clearTimeout(u),this.inflight!==s)return;const d=Date.now()-o,g=(d/1e3).toFixed(1),b=r>=1e3?`${g}s, waited ${(r/1e3).toFixed(1)}s`:`${g}s`;if(this.disposed)return this.finish(s);if(n){const f=`the check was killed after ${Math.round(a/1e3)}s without finishing`;return console.warn(`[tsgo] ${this.opts.appName}: ${f} \u2014 no verdict.`),this.forgetBuildInfo(),this.publish({output:"",durationMs:d,toolError:f}),this.finish(s)}if(p){const f=`the check was ended by ${p} from outside before it finished`;return console.warn(`[tsgo] ${this.opts.appName}: ${f} \u2014 no verdict.`),this.forgetBuildInfo(),this.publish({output:"",durationMs:d,toolError:f}),this.finish(s)}if(h===0)return console.log(`[tsgo] ${this.opts.appName}: types clean (${b})`),this.publish({output:"",durationMs:d}),this.finish(s);i.trim()&&process.stdout.write(i.endsWith(`
3
- `)?i:`${i}
4
- `);const k=(0,typecheck_bus_1.parseTscProgramErrors)(i);if(k.length){const f=(0,typecheck_bus_1.programErrorDetail)("tsgo",k,h);return console.warn(`[tsgo] ${this.opts.appName}: ${f} \u2014 no verdict.`),this.forgetBuildInfo(),this.publish({output:i,durationMs:d,toolError:f}),this.finish(s)}const m=(0,typecheck_bus_1.parseTscOutput)(i).filter(f=>f.severity==="error").length;console.log(`[tsgo] ${this.opts.appName}: ${m} type error${m===1?"":"s"} (${b})`),m===0&&this.forgetBuildInfo(),this.publish({output:i,durationMs:d,...m===0?{toolError:`tsgo exited ${h} with no diagnostics: ${firstLine(i)}`}:{}}),this.finish(s)})}finish(t){this.inflight===t&&(this.inflight=null),this.leave(),this.dirty&&!this.disposed&&(this.dirty=!1,this.request())}leave(){this.phase="idle",this.ticket?.release(),this.ticket=null}dispose(){this.disposed||(this.disposed=!0,livePlugins.delete(this),this.timer&&clearTimeout(this.timer),this.inflight&&(this.inflight.kill("SIGKILL"),this.forgetBuildInfo()),this.ticket?.release(),this.ticket=null)}}exports.TsgoCheckPlugin=TsgoCheckPlugin;function firstLine(e){return e.trim().split(`
5
- `)[0]?.slice(0,300)??""}l(firstLine,"firstLine"),c(firstLine,"firstLine");
1
+ "use strict";var _=Object.defineProperty;var h=(s,t)=>_(s,"name",{value:t,configurable:!0});var C=Object.defineProperty,i=h((s,t)=>C(s,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.TsgoCheckPlugin=exports.TSGO_MISSING_CAUSE=exports.TSGO_PACKAGE=exports.writeShimTsconfig=exports.tsconfigChain=exports.effectivePaths=void 0,exports.checkerMaxProcs=checkerMaxProcs,exports.tsgoIncremental=tsgoIncremental,exports.tsgoProgram=tsgoProgram,exports.tsgoCheckArgs=tsgoCheckArgs,exports.typecheckMode=typecheckMode,exports.resolveTsgoPackageDir=resolveTsgoPackageDir,exports.resolveTsgoBin=resolveTsgoBin,exports.reportTsgoUnavailable=reportTsgoUnavailable;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),program_id_1=require("./program-id"),static_checks_record_1=require("./static-checks-record"),typecheck_bus_1=require("./typecheck-bus"),typecheck_memory_1=require("./typecheck-memory"),typecheck_queue_1=require("./typecheck-queue");var tsgo_shim_1=require("./tsgo-shim");Object.defineProperty(exports,"effectivePaths",{enumerable:!0,get:i(function(){return tsgo_shim_1.effectivePaths},"get")}),Object.defineProperty(exports,"tsconfigChain",{enumerable:!0,get:i(function(){return tsgo_shim_1.tsconfigChain},"get")}),Object.defineProperty(exports,"writeShimTsconfig",{enumerable:!0,get:i(function(){return tsgo_shim_1.writeShimTsconfig},"get")});const DEFAULT_TIMEOUT_MS=12e4,LOCK_RETRY_MS=1e3,DEFAULT_MAX_PROCS=4;function checkerMaxProcs(s=process.env){const t=Number(s.LENSMCP_TYPECHECK_GOMAXPROCS);return Number.isInteger(t)&&t>=1?t:DEFAULT_MAX_PROCS}h(checkerMaxProcs,"checkerMaxProcs"),i(checkerMaxProcs,"checkerMaxProcs");function tsgoIncremental(s=process.env){const t=(s.LENSMCP_TSGO_INCREMENTAL??"").trim().toLowerCase();return!(t==="0"||t==="false"||t==="off"||t==="no")}h(tsgoIncremental,"tsgoIncremental"),i(tsgoIncremental,"tsgoIncremental");function tsgoProgram(s,t){const e=(0,program_id_1.programId)((0,static_checks_record_1.toWorkspacePath)(t,s),"tsgo-shim");return{id:e,files:(0,static_checks_record_1.programFiles)(t,e)}}h(tsgoProgram,"tsgoProgram"),i(tsgoProgram,"tsgoProgram");function tsgoCheckArgs(s,t,e=[]){return["--noEmit","--pretty","false",...t?["--incremental","--tsBuildInfoFile",t]:[],"-p",s,...e]}h(tsgoCheckArgs,"tsgoCheckArgs"),i(tsgoCheckArgs,"tsgoCheckArgs");const launcherBecomesCompiler=i(()=>typeof process.execve=="function","launcherBecomesCompiler"),livePlugins=new Set;let exitHooked=!1;function stopWithTheProcess(s){livePlugins.add(s),!exitHooked&&(exitHooked=!0,process.once("exit",()=>{for(const t of livePlugins)t.dispose()}))}h(stopWithTheProcess,"stopWithTheProcess"),i(stopWithTheProcess,"stopWithTheProcess");function typecheckMode(s=process.env){const t=s.LENSMCP_TYPECHECK;return t===void 0||t===""||t==="tsgo"?"tsgo":t==="off"?"off":"tsc"}h(typecheckMode,"typecheckMode"),i(typecheckMode,"typecheckMode"),exports.TSGO_PACKAGE="@typescript/native-preview";function shimNames(s){return s==="win32"?["tsgo.cmd","tsgo.exe"]:["tsgo"]}h(shimNames,"shimNames"),i(shimNames,"shimNames");function isExecutableFile(s,t){try{if(!fs.statSync(s).isFile())return!1}catch{return!1}if(t==="win32")return!0;try{return fs.accessSync(s,fs.constants.X_OK),!0}catch{return!1}}h(isExecutableFile,"isExecutableFile"),i(isExecutableFile,"isExecutableFile");function resolveTsgoPackageDir(){try{return path.dirname(require.resolve(`${exports.TSGO_PACKAGE}/package.json`))}catch{}try{let s=path.dirname(require.resolve(exports.TSGO_PACKAGE));for(let t=0;t<6;t++){const e=path.join(s,"package.json");if(fs.existsSync(e))try{const{name:a}=JSON.parse(fs.readFileSync(e,"utf8"));if(a===exports.TSGO_PACKAGE)return s}catch{}const o=path.dirname(s);if(o===s)break;s=o}}catch{}return null}h(resolveTsgoPackageDir,"resolveTsgoPackageDir"),i(resolveTsgoPackageDir,"resolveTsgoPackageDir");function packageDeclaredBin(s){try{const{bin:t}=JSON.parse(fs.readFileSync(path.join(s,"package.json"),"utf8")),e=typeof t=="string"?t:t?.tsgo;return e?path.join(s,e):null}catch{return null}}h(packageDeclaredBin,"packageDeclaredBin"),i(packageDeclaredBin,"packageDeclaredBin");function ownBinCandidates(s,t){const e=path.resolve(s,"..","..",".bin"),o=shimNames(t).map(p=>path.join(e,p)),a=t==="win32"?null:packageDeclaredBin(s);return a?[a,...o]:o}h(ownBinCandidates,"ownBinCandidates"),i(ownBinCandidates,"ownBinCandidates");function resolveTsgoBin(s,t,e={}){const o=e.platform??process.platform,a=e.isExecutable??(r=>isExecutableFile(r,o));if(t)return a(t)?t:null;for(const r of shimNames(o)){const n=path.join(s,"node_modules",".bin",r);if(a(n))return n}const p=(e.ownPackageDir??resolveTsgoPackageDir)();return p?ownBinCandidates(p,o).find(a)??null:null}h(resolveTsgoBin,"resolveTsgoBin"),i(resolveTsgoBin,"resolveTsgoBin"),exports.TSGO_MISSING_CAUSE=`tsgo binary not found \u2014 @lensmcp/cluster depends on ${exports.TSGO_PACKAGE}, so an absent binary means an incomplete install (reinstall node_modules), a platform with no ${exports.TSGO_PACKAGE} build, or a LENSMCP_TSGO_BIN override pointing at a missing or non-executable file`;function reportTsgoUnavailable(s){try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:s.workspaceRoot,project:s.appName,tool:"tsgo",tsConfig:s.tsConfig,output:"",durationMs:0,toolError:s.detail,toolErrorKind:"spawn-failed",...s.eventFile?{eventFile:s.eventFile}:{}})}catch{}}h(reportTsgoUnavailable,"reportTsgoUnavailable"),i(reportTsgoUnavailable,"reportTsgoUnavailable");class TsgoCheckPlugin{static{h(this,"TsgoCheckPlugin")}static{i(this,"TsgoCheckPlugin")}constructor(t){this.timer=null,this.phase="idle",this.dirty=!1,this.ticket=null,this.inflight=null,this.askedAt=0,this.shimPath=null,this.lock=null,this.saidUntaken=!1,this.disabled=!1,this.disposed=!1,this.opts=t,this.spawnImpl=t.spawnImpl??node_child_process_1.spawn,this.queue=t.queue??(0,typecheck_queue_1.machineTypecheckQueue)(),this.program=tsgoProgram(t.tsConfig,t.workspaceRoot),this.incremental=t.incremental??tsgoIncremental()}apply(t){t.hooks.done.tap("TsgoCheckPlugin",e=>{e.hasErrors()||this.schedule()}),t.hooks.shutdown?.tap?.("TsgoCheckPlugin",()=>this.dispose()),t.hooks.watchClose?.tap?.("TsgoCheckPlugin",()=>this.dispose()),stopWithTheProcess(this)}schedule(){this.disabled||this.disposed||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.request(),this.opts.debounceMs??500),this.timer.unref?.())}request(){if(this.disabled||this.disposed)return;if(this.phase==="running"){this.dirty=!0;return}if(this.phase==="waiting")return;this.phase="waiting",this.askedAt=Date.now(),this.need=this.memoryNeed();const t=this.queue(this.opts.appName,()=>this.run(),{onHold:i(e=>this.held(e),"onHold"),...this.need?{needMb:this.need.mb}:{}});this.isIdle()?t.release():this.ticket=t}memoryNeed(){try{const t=(0,typecheck_memory_1.knownPeaks)(this.opts.workspaceRoot,this.program.id);if(!t)return;const e=this.incremental?resolveTsgoBin(this.opts.workspaceRoot,this.opts.binPath):null,o=!!e&&(0,typecheck_memory_1.startsWarm)(this.program.files,this.program.id,(0,static_checks_record_1.configInputs)({root:this.opts.workspaceRoot,tsconfig:this.opts.tsConfig,route:"tsgo-shim",compiler:{version:(0,static_checks_record_1.compilerVersion)(e)??"unknown",bin:e}}).key);return(0,typecheck_memory_1.memoryNeed)({known:t,warm:o,unmeasured:"floor"})}catch{return}}checkers(t){try{let e=!1;const o=i(p=>{const r=(0,typecheck_memory_1.compilerTakesKnown)(t,p);return r===void 0&&(e=!0),r??!1},"takes"),a=(0,typecheck_memory_1.chooseCheckers)({peaks:(0,typecheck_memory_1.knownPeaks)(this.opts.workspaceRoot,this.program.id)?.peaks??null,bin:t,takes:o});return e?{args:[]}:(a.untaken&&!this.saidUntaken&&(this.saidUntaken=!0,console.log(`[tsgo] ${this.opts.appName}: ${(0,typecheck_memory_1.untakenText)(a.untaken,"this tsgo")}`)),a)}catch{return{args:[]}}}sample(t){const e=this.opts.readRssMb;if(e===!1||t.pid===void 0||!e&&!launcherBecomesCompiler())return null;try{return(0,typecheck_memory_1.sampleRss)(t.pid,e?{read:e}:{})}catch{return null}}measured(t,e,o){if(!(!t||o===void 0||this.disposed))return(0,typecheck_memory_1.notePeak)(this.opts.workspaceRoot,{id:this.program.id,tsconfig:t.tsconfig,warm:t.warm,...e.checkers!==void 0?{checkers:e.checkers}:{},peakMb:o,peakHow:"sampled"}),{peakMb:o,peakHow:"sampled"}}held(t){if(!this.disposed&&(console.log(`[tsgo] ${this.opts.appName}: check held \u2014 ${(0,typecheck_memory_1.holdText)(t,this.need)}`),this.opts.publishEvents!==!1))try{(0,typecheck_bus_1.publishTypecheckHeld)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"tsgo",tsConfig:this.opts.tsConfig,availableMb:t.availableMb,minFreeMb:t.minFreeMb,...t.own&&this.need?{reason:(0,typecheck_memory_1.needReason)(this.need)}:{},...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}}waitForLock(){this.leave(),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.request(),LOCK_RETRY_MS),this.timer.unref?.()}record(t,e,o=[],a){if(t)try{const p=o.filter(r=>r.severity==="error").length;(0,static_checks_record_1.finishRun)(t,{conclusion:e,diagnostics:o.map(r=>({file:(0,static_checks_record_1.toWorkspacePath)(this.opts.workspaceRoot,r.file),line:r.line,col:r.column,code:r.code,severity:r.severity,message:r.message})),errorCount:p,warningCount:o.length-p,...a??{}},{keep:i(()=>!this.disposed,"keep")}).catch(()=>{})}catch{this.forgetBuildInfo()}}recordUnrun(t){try{(0,static_checks_record_1.recordUnrun)({root:this.opts.workspaceRoot,id:this.program.id,tsconfig:this.opts.tsConfig,route:"tsgo-shim",who:"dev-checker",detail:t,locked:!!this.lock})}catch{}}forgetBuildInfo(){if(this.incremental)try{(0,static_checks_record_1.dropBuildInfo)(this.program.files)}catch{}}isIdle(){return this.phase==="idle"}publish(t){if(this.opts.publishEvents!==!1)try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"tsgo",tsConfig:this.opts.tsConfig,output:t.output,durationMs:t.durationMs,...t.toolError?{toolError:t.toolError}:{},...t.toolErrorKind?{toolErrorKind:t.toolErrorKind}:{},...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}}run(){if(this.disposed)return this.leave();const t=this.askCompiler();if(!t)return this.start();t.then(()=>this.start(),()=>this.start())}askCompiler(){try{const t=(0,typecheck_memory_1.wantedFlag)({peaks:(0,typecheck_memory_1.knownPeaks)(this.opts.workspaceRoot,this.program.id)?.peaks??null});if(!t)return;const e=resolveTsgoBin(this.opts.workspaceRoot,this.opts.binPath);return!e||(0,typecheck_memory_1.compilerTakesKnown)(e,t)!==void 0?void 0:(0,typecheck_memory_1.askCompilerTakes)(e,t)}catch{return}}start(){if(this.disposed)return this.leave();let t,e=null;const o=this.opts.timeoutMs??DEFAULT_TIMEOUT_MS;try{if(t=resolveTsgoBin(this.opts.workspaceRoot,this.opts.binPath),t){const c=(0,static_checks_record_1.tryLock)(this.program.files.lock,{holdMs:o,who:"dev-checker"});if(!c)return this.waitForLock();this.lock=c,e=(0,static_checks_record_1.beginRun)({root:this.opts.workspaceRoot,id:this.program.id,tsconfig:this.opts.tsConfig,route:"tsgo-shim",compiler:{version:(0,static_checks_record_1.compilerVersion)(t)??"unknown",bin:t},who:"dev-checker",buildInfo:this.incremental?"kept":"none"}),this.shimPath=e.project}}catch(c){return console.warn(`[tsgo] ${this.opts.appName}: could not prepare the check \u2014 ${c.message}`),this.publish({output:"",durationMs:0,toolError:`could not prepare the check: ${c.message}`,toolErrorKind:"spawn-failed"}),this.recordUnrun(`could not prepare the check: ${c.message}`),this.leave()}if(!t){this.disabled=!0;const c=`${exports.TSGO_MISSING_CAUSE}. Type checking is disabled for the rest of this session`;return console.warn(`[tsgo] ${this.opts.appName}: ${c}.`),this.publish({output:"",durationMs:0,toolError:c,toolErrorKind:"spawn-failed"}),this.recordUnrun(c),this.leave()}this.phase="running",this.dirty=!1;const a=Date.now(),p=a-this.askedAt,r=this.checkers(t),n=this.spawnImpl(t,tsgoCheckArgs(this.shimPath,this.incremental?this.program.files.buildInfo:void 0,r.args),{cwd:this.opts.workspaceRoot,stdio:["ignore","pipe","pipe"],env:{...process.env,GOMAXPROCS:process.env.GOMAXPROCS??String(this.opts.maxProcs??checkerMaxProcs())}});this.inflight=n;const w=this.sample(n);let u="",v=!1;const f=setTimeout(()=>{v=!0,n.kill("SIGKILL")},o);f.unref?.(),n.stdout?.on("data",c=>{u+=c.toString()}),n.stderr?.on("data",c=>{u+=c.toString()}),n.on("error",()=>{clearTimeout(f),w?.stop(),this.inflight===n&&(console.warn(`[tsgo] ${this.opts.appName}: failed to spawn ${t}`),this.record(e,{outcome:"tool-error",kind:"spawn-failed",detail:`failed to spawn ${t}`}),this.publish({output:"",durationMs:Date.now()-a,toolError:`failed to spawn ${t}`,toolErrorKind:"spawn-failed"}),this.finish(n))}),n.on("close",(c,b)=>{clearTimeout(f);const y=w?.stop();if(this.inflight!==n)return;const d=Date.now()-a,T=(d/1e3).toFixed(1),P=p>=1e3?`${T}s, waited ${(p/1e3).toFixed(1)}s`:`${T}s`;if(this.disposed)return this.finish(n);if(v){const l=`the check was killed after ${Math.round(o/1e3)}s without finishing`;return console.warn(`[tsgo] ${this.opts.appName}: ${l} \u2014 no verdict.`),this.record(e,{outcome:"tool-error",kind:"timeout",detail:l}),this.publish({output:"",durationMs:d,toolError:l,toolErrorKind:"timeout"}),this.finish(n)}if(b){const l=`the check was ended by ${b} from outside before it finished`;return console.warn(`[tsgo] ${this.opts.appName}: ${l} \u2014 no verdict.`),this.record(e,{outcome:"tool-error",kind:"signal",detail:l}),this.publish({output:"",durationMs:d,toolError:l,toolErrorKind:"signal"}),this.finish(n)}if(c===0)return console.log(`[tsgo] ${this.opts.appName}: types clean (${P})`),this.record(e,{outcome:"verdict"},[],this.measured(e,r,y)),this.publish({output:"",durationMs:d}),this.finish(n);u.trim()&&process.stdout.write(u.endsWith(`
2
+ `)?u:`${u}
3
+ `);const g=(0,typecheck_bus_1.parseTscProgramErrors)(u);if(g.length){const l=(0,typecheck_bus_1.programErrorDetail)("tsgo",g,c);return console.warn(`[tsgo] ${this.opts.appName}: ${l} \u2014 no verdict.`),this.record(e,{outcome:"tool-error",kind:(0,typecheck_bus_1.programErrorKind)(g),...g[0]?{code:g[0].code}:{},detail:l}),this.publish({output:u,durationMs:d,toolError:l,toolErrorKind:(0,typecheck_bus_1.programErrorKind)(g)}),this.finish(n)}const E=(0,typecheck_bus_1.parseTscOutput)(u),k=E.filter(l=>l.severity==="error").length;console.log(`[tsgo] ${this.opts.appName}: ${k} type error${k===1?"":"s"} (${P})`);const m=k===0?`tsgo exited ${c} with no diagnostics: ${firstLine(u)}`:void 0;this.record(e,m?{outcome:"tool-error",kind:"exit-without-diagnostics",detail:m}:{outcome:"verdict"},m?[]:E,m?void 0:this.measured(e,r,y)),this.publish({output:u,durationMs:d,...m?{toolError:m,toolErrorKind:"exit-without-diagnostics"}:{}}),this.finish(n)})}finish(t){this.inflight===t&&(this.inflight=null),this.leave(),this.dirty&&!this.disposed&&(this.dirty=!1,this.request())}leave(){this.phase="idle",this.ticket?.release(),this.ticket=null,this.lock?.release(),this.lock=null}dispose(){this.disposed||(this.disposed=!0,livePlugins.delete(this),this.timer&&clearTimeout(this.timer),this.inflight&&(this.inflight.kill("SIGKILL"),this.forgetBuildInfo()),this.ticket?.release(),this.ticket=null,this.lock?.release(),this.lock=null)}}exports.TsgoCheckPlugin=TsgoCheckPlugin;function firstLine(s){return s.trim().split(`
4
+ `)[0]?.slice(0,300)??""}h(firstLine,"firstLine"),i(firstLine,"firstLine");
package/tsgo-shim.d.ts ADDED
@@ -0,0 +1,112 @@
1
+ /** The shim's version: it moves when the list of changes does, and is part of what a build info is trusted with. */
2
+ export declare const SHIM_VERSION = 3;
3
+ /** tsconfig files are JSONC: `//` and block comments, and trailing commas. */
4
+ export declare function parseJsonc(text: string): Record<string, unknown> | null;
5
+ /** A tsconfig file as an object, or null when it cannot be read. */
6
+ export declare function readTsconfig(file: string): Record<string, unknown> | null;
7
+ /**
8
+ * The `paths` in effect for a config, and the directory they are anchored at.
9
+ *
10
+ * Walks the `extends` chain leaf-first; the nearest declaration wins (tsconfig REPLACES `paths`,
11
+ * it does not merge them). The anchor is the nearest `baseUrl`, resolved against the file that
12
+ * declared IT — or, with no baseUrl anywhere, the file that declared the paths.
13
+ */
14
+ export declare function effectivePaths(tsConfig: string, seen?: Set<string>): {
15
+ paths: Record<string, string[]>;
16
+ anchorDir: string;
17
+ } | null;
18
+ /**
19
+ * The tsconfig and every file it extends, as {@link effectivePaths} walks them — what a check's configuration is read
20
+ * from (issues/closed/foodguard-115). The tsconfig itself is always listed, even when it cannot be read: a half-saved
21
+ * file is watched until the next save. A file extended from node_modules changes only with an install, and is left
22
+ * out, as `configFilesOf` leaves it out.
23
+ */
24
+ export declare function tsconfigChain(tsConfig: string): string[];
25
+ /**
26
+ * The `compilerOptions` in effect for a config, as its chain declares them: a file's own value over the ones it
27
+ * extends, a later `extends` entry over an earlier one. A value is kept as written (`null` unsets, as tsc reads it),
28
+ * and a preset extended from node_modules is not read. Enough to say what a shim changes; the compiler's own answer is
29
+ * `tsgo --showConfig`.
30
+ */
31
+ export declare function effectiveCompilerOptions(tsConfig: string, above?: readonly string[]): Record<string, unknown>;
32
+ /** The TypeScript a folder resolves: the nearest `node_modules/typescript` on the way up. */
33
+ export interface WorkspaceTypeScript {
34
+ version: string;
35
+ major: number;
36
+ }
37
+ /**
38
+ * The workspace's own compiler, for a tsconfig in `dir` — read with `fs`, never loaded: this file is one module of an
39
+ * ES-module package and of a CommonJS one, and a service that checks with tsgo never loads TypeScript. Null when there
40
+ * is none on the way up, or its version cannot be read: then nothing is pinned, and tsgo's own defaults stand.
41
+ */
42
+ export declare function workspaceTypeScript(dir: string): WorkspaceTypeScript | null;
43
+ /** How a shim is made for a program. */
44
+ export interface ShimOptions {
45
+ /** The compiler options the program's command adds: an option named there is not silent. */
46
+ flags?: readonly string[];
47
+ /**
48
+ * The shim of a program TS7 takes as it is: the v3 pins and nothing of v1 or v2, and the program's `references` and
49
+ * its default `include` written out — a config file's place decides them, and the shim is in another.
50
+ */
51
+ pinsOnly?: boolean;
52
+ }
53
+ /** What the shim of one tsconfig holds, and what it changes. */
54
+ export interface ShimPlan {
55
+ version: number;
56
+ /** The shim's own `compilerOptions`, over the tsconfig it extends. */
57
+ compilerOptions: Record<string, unknown>;
58
+ /**
59
+ * Each change that applies to this tsconfig: `moduleResolution:node10→bundler`, `baseUrl→null`, `paths→absolute`, and
60
+ * since v3 a default in the caller's words — «types: the workspace's TypeScript 5.9.3 includes every visible @types
61
+ * package where none are named — 59 named» — and `types→absolute`, the entries the shim's place would lose.
62
+ */
63
+ changes: string[];
64
+ /** v3: the options pinned to the workspace compiler's default that make another program than TS7 checks as it is. */
65
+ pins?: string[];
66
+ /** v3: the workspace compiler's defaults TS7 refuses, so the program is checked under TS7's — each with why. */
67
+ notPinned?: string[];
68
+ /** Pins only: what the tsconfig's place decided, written out. */
69
+ include?: string[];
70
+ references?: Array<Record<string, unknown>>;
71
+ }
72
+ /**
73
+ * The shim for one tsconfig, were it written in `shimDir`. Made from the chain as it is NOW (see {@link writeShim}).
74
+ *
75
+ * `baseUrl: null` unsets the inherited baseUrl, because TS7 removed the option outright
76
+ * (TS5102). This used to be the whole story, on the belief that TS7 would re-anchor the
77
+ * inherited non-relative `paths` at the config that declared them. It does not — it rejects
78
+ * a non-relative `paths` target outright:
79
+ *
80
+ * error TS5090: Non-relative paths are not allowed. Did you forget a leading './'?
81
+ *
82
+ * and a tsconfig that fails to parse checks NOTHING. So in every workspace with the ordinary
83
+ * Nx layout (`baseUrl: "."` plus `"paths": { "@scope/lib": ["libs/lib/src/index.ts"] }`) the
84
+ * entire type-check reported exactly one bogus error and zero real ones — a service could be
85
+ * saved with three type errors in it and `typecheck://` would show the same single TS5090.
86
+ *
87
+ * So the anchoring baseUrl did is done HERE, by rewriting the targets absolute. All of them,
88
+ * not only the non-relative ones: a relative target is anchored at the file that declared it,
89
+ * and overriding `paths` in the shim would silently re-anchor those at the shim's own
90
+ * directory instead.
91
+ */
92
+ export declare function planShim(tsConfig: string, shimDir: string, opts?: ShimOptions): ShimPlan;
93
+ /** The shim file's text for a plan. */
94
+ export declare function shimText(tsConfig: string, plan: ShimPlan): string;
95
+ /**
96
+ * Write the shim of one tsconfig at `file`, and return its plan. Called before EVERY check
97
+ * (issues/closed/foodguard-115): the shim's `paths` REPLACE the ones the tsconfig chain declares, so they are the one
98
+ * part of the configuration tsgo does not read for itself. Written once, a shim kept the aliases the chain had when
99
+ * the service started: FoodGuard added `@foodguard-shared/execution-graph` to `tsconfig.base.json`, the bundle built
100
+ * with it, and every check for the next 80 minutes still reported «TS2307: Cannot find module». The file is left alone
101
+ * when it would not change. Since v3 the same holds for the `types` it names: they are the `@types` folders there are
102
+ * at the check.
103
+ */
104
+ export declare function writeShim(file: string, tsConfig: string, opts?: ShimOptions): ShimPlan;
105
+ /** Where the shims and build infos of a checkout live: its git-ignored `tmp/`, in-tree (see the header). */
106
+ export declare function tsgoShimDir(workspaceRoot: string): string;
107
+ /**
108
+ * A shim under a name of the caller's — `<root>/tmp/lensmcp-tsgo/<name>.tsconfig.json` — written as {@link writeShim}
109
+ * writes it; returns its path. The dev checker named its shim after its service this way, until a program's files went
110
+ * by the program's id (static-checks-record.ts `programFiles`): a check writes `<id>.tsconfig.json` now.
111
+ */
112
+ export declare function writeShimTsconfig(appName: string, tsConfig: string, workspaceRoot: string): string;
package/tsgo-shim.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var k=Object.defineProperty;var d=(e,t)=>k(e,"name",{value:t,configurable:!0});var $=Object.defineProperty,u=d((e,t)=>$(e,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SHIM_VERSION=void 0,exports.parseJsonc=parseJsonc,exports.readTsconfig=readTsconfig,exports.effectivePaths=effectivePaths,exports.tsconfigChain=tsconfigChain,exports.effectiveCompilerOptions=effectiveCompilerOptions,exports.workspaceTypeScript=workspaceTypeScript,exports.planShim=planShim,exports.shimText=shimText,exports.writeShim=writeShim,exports.tsgoShimDir=tsgoShimDir,exports.writeShimTsconfig=writeShimTsconfig;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path"));exports.SHIM_VERSION=3;const DEFAULTS_CHANGED_IN=6;function parseJsonc(e){let t="",s=!1,n=!1,i=!1;for(let o=0;o<e.length;o++){const r=e[o],c=e[o+1];if(n){r===`
2
+ `&&(n=!1,t+=r);continue}if(i){r==="*"&&c==="/"&&(i=!1,o++);continue}if(s){t+=r,r==="\\"?(t+=c??"",o++):r==='"'&&(s=!1);continue}if(r==='"'){s=!0,t+=r;continue}if(r==="/"&&c==="/"){n=!0,o++;continue}if(r==="/"&&c==="*"){i=!0,o++;continue}t+=r}try{const o=JSON.parse(t.replace(/,(\s*[}\]])/g,"$1"));return o&&typeof o=="object"&&!Array.isArray(o)?o:null}catch{return null}}d(parseJsonc,"parseJsonc"),u(parseJsonc,"parseJsonc");function readTsconfig(e){try{return parseJsonc(fs.readFileSync(e,"utf8"))}catch{return null}}d(readTsconfig,"readTsconfig"),u(readTsconfig,"readTsconfig");function resolveExtends(e,t){if(!e.startsWith(".")&&!path.isAbsolute(e))return null;const s=path.isAbsolute(e)?e:path.resolve(t,e);for(const n of[s,`${s}.json`,path.join(s,"tsconfig.json")])try{if(fs.statSync(n).isFile())return n}catch{}return null}d(resolveExtends,"resolveExtends"),u(resolveExtends,"resolveExtends");function extendsOf(e){const t=e?.extends;return Array.isArray(t)?t.filter(s=>typeof s=="string"):typeof t=="string"?[t]:[]}d(extendsOf,"extendsOf"),u(extendsOf,"extendsOf");function effectivePaths(e,t=new Set){if(t.has(e))return null;t.add(e);const s=readTsconfig(e);if(!s)return null;const n=path.dirname(e),i=s.compilerOptions??{},o=extendsOf(s),r=u(()=>{for(const m of[...o].reverse()){const a=resolveExtends(m,n);if(!a)continue;const p=effectivePaths(a,t);if(p)return p}return null},"inherited"),c=i.paths,l=typeof i.baseUrl=="string"?path.resolve(n,i.baseUrl):void 0;if(!c){const m=r();return m?{paths:m.paths,anchorDir:l??m.anchorDir}:null}return{paths:c,anchorDir:l??r()?.anchorDir??n}}d(effectivePaths,"effectivePaths"),u(effectivePaths,"effectivePaths");function tsconfigChain(e){const t=[],s=u(n=>{if(!t.includes(n)){t.push(n);for(const i of extendsOf(readTsconfig(n))){const o=resolveExtends(i,path.dirname(n));o&&!o.split(path.sep).includes("node_modules")&&s(o)}}},"visit");return s(path.resolve(e)),t}d(tsconfigChain,"tsconfigChain"),u(tsconfigChain,"tsconfigChain");function effectiveCompilerOptions(e,t=[]){return readChain(e,!1,t).options}d(effectiveCompilerOptions,"effectiveCompilerOptions"),u(effectiveCompilerOptions,"effectiveCompilerOptions");function readChain(e,t,s=[]){const n={options:{},origin:{},inputs:!1,unread:[]};if(s.includes(e))return n;const i=readTsconfig(e);if(!i)return n;for(const r of extendsOf(i)){const c=resolveExtends(r,path.dirname(e))??(t?resolvePreset(r,path.dirname(e)):null);if(!c){n.unread.push(r);continue}const l=readChain(c,t,[...s,e]);Object.assign(n.options,l.options),Object.assign(n.origin,l.origin),n.inputs||=l.inputs,n.unread.push(...l.unread)}const o=i.compilerOptions;if(o&&typeof o=="object"&&!Array.isArray(o))for(const[r,c]of Object.entries(o))n.options[r]=c,n.origin[r]=e;return(i.files!==void 0||i.include!==void 0)&&(n.inputs=!0),n}d(readChain,"readChain"),u(readChain,"readChain");function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}d(isFile,"isFile"),u(isFile,"isFile");function resolvePreset(e,t){const s=e.split("/"),n=e.startsWith("@")?2:1,i=s.slice(0,n).join("/"),o=s.slice(n).join("/");if(!i||i.startsWith(".")||path.isAbsolute(e))return null;for(let r=path.resolve(t);;r=path.dirname(r)){const c=path.join(r,"node_modules",i),l=o?[path.join(c,o),path.join(c,`${o}.json`),path.join(c,o,"tsconfig.json")]:[];if(!o){const a=readTsconfig(path.join(c,"package.json"))?.tsconfig;typeof a=="string"&&l.push(path.join(c,a)),l.push(path.join(c,"tsconfig.json"))}const m=l.find(isFile);if(m)return m;if(path.dirname(r)===r)return null}}d(resolvePreset,"resolvePreset"),u(resolvePreset,"resolvePreset");function typeRootsAbove(e){const t=[];for(let s=path.resolve(e);;s=path.dirname(s)){const n=path.join(s,"node_modules","@types");try{fs.statSync(n).isDirectory()&&t.push(n)}catch{}if(path.dirname(s)===s)return t}}d(typeRootsAbove,"typeRootsAbove"),u(typeRootsAbove,"typeRootsAbove");function workspaceTypeScript(e){for(let t=path.resolve(e);;t=path.dirname(t)){const s=readTsconfig(path.join(t,"node_modules","typescript","package.json"))?.version;if(typeof s=="string"){const n=Number.parseInt(s,10);return Number.isFinite(n)?{version:s,major:n}:null}if(path.dirname(t)===t)return null}}d(workspaceTypeScript,"workspaceTypeScript"),u(workspaceTypeScript,"workspaceTypeScript");function automaticTypes(e){const t=[];for(const s of e)for(const n of typesIn(s))t.includes(n)||t.push(n);return t}d(automaticTypes,"automaticTypes"),u(automaticTypes,"automaticTypes");const typesOfRoot=new Map;function typesIn(e){let t,s;try{s=fs.readdirSync(e,{withFileTypes:!0}),t=`${fs.statSync(e).mtimeMs}\0${s.map(r=>r.name).join("\0")}`}catch{return[]}const n=typesOfRoot.get(e);if(n&&n.listed===t)return n.names;const i=[];for(const r of s){let c=r.isDirectory();if(r.isSymbolicLink())try{c=fs.statSync(path.join(e,r.name)).isDirectory()}catch{c=!1}c&&i.push(r.name)}const o=[];for(const r of i.sort()){if(r.startsWith("."))continue;const c=path.join(e,r,"package.json"),l=isFile(c)?readTsconfig(c):null;l&&"typings"in l&&l.typings===null||o.push(r)}return typesOfRoot.size>256&&typesOfRoot.clear(),typesOfRoot.set(e,{listed:t,names:o}),o}d(typesIn,"typesIn"),u(typesIn,"typesIn");function hasLibReplacement(e){for(let t=path.resolve(e);;t=path.dirname(t)){try{if(fs.readdirSync(path.join(t,"node_modules","@typescript")).some(s=>s.startsWith("lib-")))return!0}catch{}if(path.dirname(t)===t)return!1}}d(hasLibReplacement,"hasLibReplacement"),u(hasLibReplacement,"hasLibReplacement");const FLAG_OPTIONS=["alwaysStrict","composite","customConditions","declarationDir","esModuleInterop","libReplacement","mapRoot","module","moduleDetection","moduleResolution","moduleSuffixes","noDtsResolution","noUncheckedSideEffectImports","outDir","resolveJsonModule","resolvePackageJsonExports","resolvePackageJsonImports","rootDir","sourceRoot","strict","target","typeRoots","types","useDefineForClassFields"],LIST_OPTIONS=new Set(["customConditions","moduleSuffixes","typeRoots","types"]);function flagOptions(e){const t=new Map(FLAG_OPTIONS.map(n=>[n.toLowerCase(),n])),s={};for(let n=0;n<e.length;n++){const i=e[n];if(!i.startsWith("-"))continue;const o=e[n+1],r=o!==void 0&&!o.startsWith("-")?e[++n]:void 0,c=t.get(i.replace(/^--?/,"").toLowerCase());c&&(s[c]=r===void 0||r==="true"?!0:r==="false"?!1:LIST_OPTIONS.has(c)?r.split(",").filter(Boolean):r)}return s}d(flagOptions,"flagOptions"),u(flagOptions,"flagOptions");const lower=u(e=>typeof e=="string"?e.toLowerCase():void 0,"lower"),silent=u(e=>e==null,"silent"),TARGET_UNDER_MODULE=new Map([["node16","es2022"],["node18","es2022"],["node20","es2023"],["nodenext","esnext"]]);function computedOptions(e){const t=lower(e.target)==="es3"?void 0:lower(e.target),s=lower(e.module),n=t??(s?TARGET_UNDER_MODULE.get(s):void 0)??"es5",i=s??(n==="es5"?"commonjs":"es2015"),o=TARGET_UNDER_MODULE.has(i),r=lower(e.moduleResolution)==="node"?"node10":lower(e.moduleResolution);return{targetSaid:t,moduleSaid:s,target:n,moduleKind:i,nodeModule:o,resolutionSaid:r,resolution:r??(i==="commonjs"?"node10":i==="nodenext"?"nodenext":o?"node16":i==="preserve"?"bundler":"classic")}}d(computedOptions,"computedOptions"),u(computedOptions,"computedOptions");function workspaceDefaults(e,t,s,n,i){const o={options:{},changes:[],pins:[],notPinned:[]},r=path.dirname(e),c=`TypeScript ${n.version}`,l=u((y,x,g,v=!0)=>{o.options[y]=x,o.changes.push(`${y}: ${g}`),v&&o.pins.push(y)},"pin"),{targetSaid:m,moduleSaid:a,target:p,moduleKind:f,nodeModule:h,resolutionSaid:j,resolution:S}=computedOptions(t);if(silent(t.types)){const y=Array.isArray(t.typeRoots)?t.typeRoots.filter(g=>typeof g=="string").map(g=>path.resolve(s,g)):typeRootsAbove(r),x=automaticTypes(y);x.length&&l("types",x,`the workspace's ${c} includes every visible @types package where none are named \u2014 ${x.length} named`)}if(silent(t.strict)&&l("strict",!1,`off in ${c} where it is not named \u2014 false`),silent(t.noUncheckedSideEffectImports)&&l("noUncheckedSideEffectImports",!1,`off in ${c} where it is not named \u2014 false`),silent(t.libReplacement)&&hasLibReplacement(r)&&l("libReplacement",!0,`on in ${c} where it is not named \u2014 true`),i&&!a&&l("module",f,`${f} in ${c} where none is named \u2014 ${f}`),m||(h&&f!=="nodenext"?l("target",p,`${p} in ${c} under module ${f} where none is named \u2014 ${p}`):p==="es5"&&o.notPinned.push(`target: ${c} checks as es5 and with es5's library where none is named; TS7 refuses es5`),p==="es5"&&silent(t.useDefineForClassFields)&&l("useDefineForClassFields",!1,`off in ${c} below es2022 where it is not named \u2014 false`)),S==="node10")for(const y of["resolvePackageJsonExports","resolvePackageJsonImports","resolveJsonModule"])silent(t[y])&&l(y,!1,`off in ${c} under node10 \u2014 false`);if(i&&!j&&(S==="node10"||S==="classic")&&o.notPinned.push(`moduleResolution: ${S} in ${c} where none is named (module ${f}); TS7 refuses it and resolves as bundler`),silent(t.esModuleInterop)&&!h&&f!=="preserve"&&o.notPinned.push(`esModuleInterop: off in ${c} where it is not named (module ${f}); TS7 refuses off and has it on`),silent(t.alwaysStrict)&&t.strict!==!0&&(lower(t.moduleDetection)??(h?"force":"auto"))!=="force"&&o.notPinned.push(`alwaysStrict: off in ${c} where strict is not on; TS7 refuses off and reads every file in strict mode`),silent(t.rootDir))if(t.composite===!0)l("rootDir",r,`the tsconfig's own folder as ${c} takes it for a composite project where none is named`,!1);else{const y=["outDir","declarationDir","sourceRoot","mapRoot"].some(x=>!silent(t[x]));l("rootDir",path.parse(r).root,`${c} takes the folder its files share where none is named so no file is outside it \u2014 the file system's root named`,y)}return o}d(workspaceDefaults,"workspaceDefaults"),u(workspaceDefaults,"workspaceDefaults");function typesLookup(e,t){const s=e==="node16"||e==="nodenext"||e==="bundler";if(!(t.resolvePackageJsonExports===!0||s&&t.resolvePackageJsonExports!==!1))return{conditions:null,trailers:s};if(e==="node10")return{conditions:[],trailers:s};const n=Array.isArray(t.customConditions)?t.customConditions.filter(o=>typeof o=="string"):[],i=t.noDtsResolution===!0?[]:["types"];return{conditions:[e==="bundler"?"import":"require",...i,...e==="bundler"?[]:["node"],...n],trailers:s}}d(typesLookup,"typesLookup"),u(typesLookup,"typesLookup");function typesResolution(e,t){const s=computedOptions(e);return s.resolutionSaid?s.resolutionSaid:t?s.resolution:s.moduleSaid==="nodenext"?"nodenext":s.moduleSaid&&TARGET_UNDER_MODULE.has(s.moduleSaid)?"node16":"bundler"}d(typesResolution,"typesResolution"),u(typesResolution,"typesResolution");const UNREAD=Symbol("unread"),DECLARATION_EXTENSIONS=[".d.ts",".d.mts",".d.cts"],KNOWN_EXTENSIONS=[".d.ts",".d.mts",".d.cts",".mjs",".mts",".cjs",".cts",".ts",".js",".tsx",".jsx",".json"],extensionOf=u((e,t)=>t.find(s=>e.length>s.length&&e.endsWith(s)),"extensionOf"),isDeclarationFile=u(e=>extensionOf(e,DECLARATION_EXTENSIONS)!==void 0||e.endsWith(".ts")&&path.basename(e).includes(".d."),"isDeclarationFile"),hasOwn=u((e,t)=>!!e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,t),"hasOwn");function isDirectory(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}d(isDirectory,"isDirectory"),u(isDirectory,"isDirectory");function packageJsonIn(e){const t=path.join(e,"package.json");return isFile(t)?readTsconfig(t)??{}:void 0}d(packageJsonIn,"packageJsonIn"),u(packageJsonIn,"packageJsonIn");const hasTypesVersions=u(e=>{const t=e.typesVersions;return!!t&&typeof t=="object"&&Object.keys(t).length>0},"hasTypesVersions");function withExtension(e,t,s){const n=u(o=>o.map(r=>e+r).find(isFile),"first"),i=u((...o)=>s?o:[],"ts");switch(t){case".mjs":case".mts":case".d.mts":return n([...i(".mts"),".d.mts"]);case".cjs":case".cts":case".d.cts":return n([...i(".cts"),".d.cts"]);case".json":return n([".d.json.ts"]);case".tsx":case".jsx":return n([...i(".tsx",".ts"),".d.ts"]);case".ts":case".d.ts":case".js":case"":return n([...i(".ts",".tsx"),".d.ts"]);default:return isDeclarationFile(e+t)?void 0:n([`.d${t}.ts`])}}d(withExtension,"withExtension"),u(withExtension,"withExtension");function replacedExtension(e,t){if(!path.basename(e).includes("."))return;const s=extensionOf(e,KNOWN_EXTENSIONS),n=s?e.slice(0,-s.length):e.slice(0,e.lastIndexOf("."));return withExtension(n,e.slice(n.length),t)}d(replacedExtension,"replacedExtension"),u(replacedExtension,"replacedExtension");const fileAt=u((e,t)=>replacedExtension(e,t)??withExtension(e,"",t),"fileAt"),fieldFile=u(e=>extensionOf(e,DECLARATION_EXTENSIONS)?isFile(e)?e:void 0:replacedExtension(e,!1),"fieldFile");function folderFile(e,t){if(t&&hasTypesVersions(t.json))return UNREAD;const s=t&&path.resolve(t.dir)===path.resolve(e)?["typings","types","main"].map(n=>t.json[n]).find(n=>typeof n=="string"&&n!==""):void 0;if(s!==void 0){const n=path.resolve(e,s),i=(/[\\/]$/.test(s)?void 0:fieldFile(n)??fileAt(n,!0))??(isDirectory(n)?fileAt(path.join(n,"index"),!0):void 0);if(i)return isDeclarationFile(i)?i:UNREAD}return fileAt(path.join(e,"index"),!1)}d(folderFile,"folderFile"),u(folderFile,"folderFile");function packageNameOf(e){let t=e.indexOf("/");return e.startsWith("@")&&(t=e.indexOf("/",t+1)),t===-1?{packageName:e,rest:""}:{packageName:e.slice(0,t),rest:e.slice(t+1)}}d(packageNameOf,"packageNameOf"),u(packageNameOf,"packageNameOf");const mangled=u(e=>e.startsWith("@")&&e.includes("/")?e.replace("/","__").slice(1):e,"mangled");function comparePatternKeys(e,t){const s=e.indexOf("*"),n=t.indexOf("*"),i=s===-1?e.length:s+1,o=n===-1?t.length:n+1;return i!==o?o-i:s===-1?1:n===-1?-1:t.length-e.length}d(comparePatternKeys,"comparePatternKeys"),u(comparePatternKeys,"comparePatternKeys");function exportsFile(e,t,s,n){const i=n.conditions??[],o=u((a,p,f)=>{if(typeof a=="string"){if(!f&&p.length>0&&!a.endsWith("/")||!a.startsWith("./"))return{value:void 0};const h=u(S=>S.some(y=>y===".."||y==="."||y==="node_modules"),"invalid");if(h(a.split(/[\\/]/).slice(1))||h(p.split(/[\\/]/)))return{value:void 0};const j=`${t}/${a}`;return{value:fieldFile(path.resolve(f?j.replace(/\*/g,p):j+p))}}if(Array.isArray(a)){for(const h of a){const j=o(h,p,f);if(j)return j}return{value:void 0}}if(a&&typeof a=="object"){for(const[h,j]of Object.entries(a))if(h==="default"||i.includes(h)){const S=o(j,p,f);if(S)return S}else if(h.startsWith("types@")&&i.includes("types"))return{value:UNREAD};return}return{value:void 0}},"target"),r=!!e&&typeof e=="object"&&!Array.isArray(e),c=r?Object.keys(e):[];if(s==="."){const a=!r||!c.some(p=>p.startsWith("."))?e:hasOwn(e,".")?e["."]:void 0;return a?o(a,"",!1)?.value:void 0}if(!r||!c.every(a=>a.startsWith(".")))return;const l=e;if(!s.endsWith("/")&&!s.includes("*")&&hasOwn(l,s))return o(l[s],"",!1)?.value;const m=c.filter(a=>a.includes("*")&&a.indexOf("*")===a.lastIndexOf("*")||a.endsWith("/")).sort(comparePatternKeys);for(const a of m){const p=a.indexOf("*");if(n.trailers&&p!==-1&&!a.endsWith("*")&&s.startsWith(a.slice(0,p))&&s.endsWith(a.slice(p+1)))return o(l[a],s.substring(p,s.length-(a.length-1-p)),!0)?.value;if(a.endsWith("*")&&s.startsWith(a.slice(0,-1)))return o(l[a],s.substring(a.length-1),!0)?.value;if(s.startsWith(a))return o(l[a],s.substring(a.length),!1)?.value}}d(exportsFile,"exportsFile"),u(exportsFile,"exportsFile");function packageFile(e,t,s){const n=path.join(t,e),{packageName:i,rest:o}=packageNameOf(e),r=path.join(t,i),c=packageJsonIn(n);if(o!==""&&c&&(s.conditions===null||!hasOwn(packageJsonIn(r),"exports")))return fileAt(n,!1)??folderFile(n,{dir:n,json:c});const l=o===""?c:packageJsonIn(r);return l?.exports&&s.conditions!==null?exportsFile(l.exports,r,o===""?".":`./${o}`,s):o!==""&&l&&hasTypesVersions(l)?UNREAD:fileAt(n,!1)??folderFile(n,l?{dir:r,json:l}:void 0)}d(packageFile,"packageFile"),u(packageFile,"packageFile");function ancestorsOf(e){const t=[];for(let s=path.resolve(e);;s=path.dirname(s))if(t.push(s),path.dirname(s)===s)return t}d(ancestorsOf,"ancestorsOf"),u(ancestorsOf,"ancestorsOf");function typesEntryFrom(e,t,s){if(path.isAbsolute(t))return;for(const i of typeRootsAbove(e)){const o=path.join(i,mangled(t)),r=packageJsonIn(o);if(folderFile(o,r?{dir:o,json:r}:void 0)!==void 0)return"primary"}const n=u((i,o)=>typeof i=="string"?{file:i,...o?{at:o}:{}}:i,"asFile");if(/^\.\.?(?:$|[\\/])/.test(t)){const i=path.resolve(e,t),o=packageJsonIn(i),r=/(?:^|[\\/])\.\.?$|[\\/]$/.test(t);return n((r?void 0:fileAt(i,!1))??folderFile(i,o?{dir:i,json:o}:void 0))}for(const i of ancestorsOf(e)){const o=path.join(i,"node_modules");if(path.basename(i)==="node_modules"||!isDirectory(o))continue;const r=path.join(o,"@types"),c=packageFile(t,o,s)??(isDirectory(r)?packageFile(mangled(t),r,s):void 0);if(c!==void 0)return n(c,i)}}d(typesEntryFrom,"typesEntryFrom"),u(typesEntryFrom,"typesEntryFrom");function placedTypes(e,t,s,n,i){const o=ancestorsOf(t),r=ancestorsOf(s),c=u(f=>isDirectory(path.join(f,"node_modules")),"hasNodeModules"),l=r.some(f=>!o.includes(f)&&c(f)),m=e.some(f=>typeof f=="string"&&/^\.\.?(?:$|[\\/])/.test(f));if(!n&&!l&&!m&&!o.some(f=>!r.includes(f)&&c(f)))return;let a=!1;const p=e.map(f=>{if(typeof f!="string")return f;const h=typesEntryFrom(t,f,i);return h===void 0||h==="primary"||h===UNREAD||!extensionOf(h.file,DECLARATION_EXTENSIONS)||h.at!==void 0&&!n&&!l&&r.includes(h.at)?f:(a=!0,h.file)});return a?p:void 0}d(placedTypes,"placedTypes"),u(placedTypes,"placedTypes");function planShim(e,t,s={}){const n=effectiveCompilerOptions(e),i=[],o={};if(!s.pinsOnly){Object.assign(o,{module:"preserve",moduleResolution:"bundler",isolatedModules:!1,baseUrl:null});const g=lower(n.module);g!=="preserve"&&i.push(g?`module:${g}\u2192preserve`:"module\u2192preserve");const v=lower(n.moduleResolution);v!=="bundler"&&i.push(v?`moduleResolution:${v}\u2192bundler`:"moduleResolution\u2192bundler"),n.isolatedModules===!0&&i.push("isolatedModules:true\u2192false"),typeof n.baseUrl=="string"&&i.push("baseUrl\u2192null");const O=effectivePaths(e),b=O?Object.fromEntries(Object.entries(O.paths).map(([A,w])=>[A,(Array.isArray(w)?w:[]).map(R=>path.isAbsolute(R)?R:path.resolve(O.anchorDir,R))])):void 0;b&&Object.keys(b).length&&(o.paths=b,i.push("paths\u2192absolute")),n.esModuleInterop===!1&&(o.esModuleInterop=null,i.push("esModuleInterop:false\u2192null"))}const r=path.dirname(e),c=workspaceTypeScript(r),l=c&&c.major<DEFAULTS_CHANGED_IN?c:null,m=l||s.pinsOnly?readChain(e,!0):null,a=flagOptions(s.flags??[]);let p=[],f=[],h=Array.isArray(n.typeRoots);if(l&&m)if(m.unread.length)f=[`the defaults of TypeScript ${l.version}: the chain extends ${m.unread.join(" and ")} which was not found to read, so what it names is not known`];else{const g={...m.options,...a},v=workspaceDefaults(e,g,path.dirname(m.origin.typeRoots??e),l,!!s.pinsOnly);Object.assign(o,v.options),i.push(...v.changes),{pins:p,notPinned:f}=v,h||=Array.isArray(g.typeRoots)}const j=m?.options??n;h||=Array.isArray(j.typeRoots)||Array.isArray(a.typeRoots);const S=o.types??j.types;if(Array.isArray(S)&&S.length>0&&!h){const g=typeRootsAbove(r),v=new Set(typeRootsAbove(t)),O=g.some(w=>!v.has(w));O&&(o.typeRoots=g,i.push("typeRoots\u2192absolute"));const b={...j,...o,...a},A=b.moduleSuffixes;if(o.types===void 0&&a.types===void 0&&!m?.unread.length&&!(Array.isArray(A)&&A.some(w=>w!==""))){const w=placedTypes(S,r,t,O,typesLookup(typesResolution(b,!!l),b));w&&(o.types=w,i.push("types\u2192absolute"))}}let y,x;if(s.pinsOnly&&m){m.inputs||(y=[path.join(r,"**","*")],i.push("include\u2192the tsconfig's folder"));const g=readTsconfig(e)?.references,v=(Array.isArray(g)?g:[]).flatMap(O=>{const b=O&&typeof O=="object"&&!Array.isArray(O)?O:null;return b&&typeof b.path=="string"?[{...b,path:path.resolve(r,b.path)}]:[]});v.length&&(x=v,i.push("references\u2192absolute"))}return{version:exports.SHIM_VERSION,compilerOptions:o,changes:i,...p.length?{pins:p}:{},...f.length?{notPinned:f}:{},...y?{include:y}:{},...x?{references:x}:{}}}d(planShim,"planShim"),u(planShim,"planShim");function shimText(e,t){return JSON.stringify({extends:e,compilerOptions:t.compilerOptions,...t.include?{include:t.include}:{},...t.references?{references:t.references}:{}},null,2)}d(shimText,"shimText"),u(shimText,"shimText");function writeShim(e,t,s={}){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=planShim(t,path.dirname(e),s),i=shimText(t,n);let o;try{o=fs.readFileSync(e,"utf8")}catch{}return o!==i&&fs.writeFileSync(e,i),n}d(writeShim,"writeShim"),u(writeShim,"writeShim");function tsgoShimDir(e){return path.join(e,"tmp","lensmcp-tsgo")}d(tsgoShimDir,"tsgoShimDir"),u(tsgoShimDir,"tsgoShimDir");function writeShimTsconfig(e,t,s){const n=path.join(tsgoShimDir(s),`${e}.tsconfig.json`);return writeShim(n,t),n}d(writeShimTsconfig,"writeShimTsconfig"),u(writeShimTsconfig,"writeShimTsconfig");