@lensmcp/nx-plugin 1.25.78 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var j=Object.defineProperty;var d=(e,n)=>j(e,"name",{value:n,configurable:!0});var T=Object.defineProperty,t=d((e,n)=>T(e,"name",{value:n,configurable:!0}),"t");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=agentDevExecutor,exports.signalChild=signalChild,exports.resolveAgentDevMcpMode=resolveAgentDevMcpMode,exports.readShimLine=readShimLine,exports.mcpAuthHint=mcpAuthHint,exports.isLocalCaptureTarget=isLocalCaptureTarget;const node_child_process_1=require("node:child_process"),node_fs_1=require("node:fs"),node_path_1=require("node:path"),node_readline_1=require("node:readline"),lens_frontend_1=require("../../lens-frontend");async function agentDevExecutor(e,n){const o={kind:e.kind??"vite-react",chrome:e.chrome??!0,headless:e.headless??!0,node:e.node??!0,devTarget:e.devTarget,projectRoot:e.projectRoot,port:e.port,openUrl:e.openUrl,devCommand:e.devCommand,wsPort:e.wsPort,mcp:resolveAgentDevMcpMode(e.mcp,process.env,n.root)};if(o.kind!=="vite-react"&&o.kind!=="nestjs"&&o.kind!=="imported")return console.error(`[agent-dev] supported kinds are "vite-react", "nestjs", "imported" (got "${o.kind}").`),{success:!1};const r=n.projectName,g=o.projectRoot?(0,node_path_1.resolve)(n.root,o.projectRoot):r&&n.projectsConfigurations?(0,node_path_1.resolve)(n.root,n.projectsConfigurations.projects[r]?.root??"."):n.root;if(o.kind==="nestjs")return runNestjs(g,n);if(o.kind==="imported")return runImported(g,n,{devCommand:o.devCommand,chrome:o.chrome,headless:o.headless,openUrl:o.openUrl,wsPort:o.wsPort??5747,node:o.node,mcp:o.mcp});const p=(0,lens_frontend_1.findMcpBundle)(n.root);p||console.warn("[agent-dev] No lensmcp-mcp bundle found \u2014 skipping MCP server. Install the self-contained CLI: `npm i -D lensmcp` (it ships `bundled/main.js`).");const u=[],c=new Map;let a=!1;function v(i,h,C,s,m=!1,f){const P=(0,node_child_process_1.spawn)(h,C,{cwd:g,env:{...process.env,...s??{}},stdio:"inherit"});return u.push(P),onSpawnFailure(P,i,()=>{m||l()}),P.on("exit",(E,M)=>{if(!a){if(m){const w=c.get(i)??0;if(f&&w<f.max){c.set(i,w+1),console.warn(`[agent-dev] ${i} exited (code=${E} sig=${M}); respawning in ${Math.round(f.delayMs/1e3)}s (${w+1}/${f.max}).`),setTimeout(()=>{a||v(i,h,C,s,m,f)},f.delayMs).unref?.();return}console.warn(`[agent-dev] ${i} exited (code=${E} sig=${M}); continuing.`);return}console.warn(`[agent-dev] ${i} exited unexpectedly (code=${E} sig=${M}); shutting down others.`),l()}}),P}d(v,"g"),t(v,"spawnChild");function l(){if(!a){a=!0;for(const i of u)signalChild(i,"SIGTERM")}}d(l,"p"),t(l,"shutdown"),process.on("SIGINT",l),process.on("SIGTERM",l);const S=process.env.LENSMCP_EVENT_FILE??(0,node_path_1.join)(n.root,".lensmcp","events.jsonl");try{(0,node_fs_1.mkdirSync)((0,node_path_1.dirname)(S),{recursive:!0});const i=(0,node_fs_1.statSync)(S,{throwIfNoEntry:!1});!i||Date.now()-i.mtimeMs>6e4?(0,node_fs_1.writeFileSync)(S,""):console.log("[agent-dev] event bridge is active (written <60s ago) \u2014 appending, not truncating.")}catch{}console.log(`[agent-dev] event bridge \u2192 ${S}`);try{(0,lens_frontend_1.spawnLensFrontend)({projectRoot:g,workspaceRoot:n.root,...r?{project:r}:{},eventFile:S,...o.port!==void 0?{port:o.port}:{},chrome:o.chrome,headless:o.headless,...o.openUrl?{openUrl:o.openUrl}:{},log:t(i=>console.log(i),"log")},v)}catch(i){return console.error(i.message),l(),{success:!1}}return p&&startMcp({mcpBundle:p,workspaceRoot:n.root,eventFile:S,mode:o.mcp,spawnChild:t((i,h,C,s)=>v(i,h,C,s),"spawnChild"),track:t(i=>{u.push(i)},"track")}),new Promise(i=>{const h=t(()=>{a?Promise.allSettled(u.map(exited)).then(()=>i({success:!0})):setTimeout(h,500)},"tick");h()})}d(agentDevExecutor,"agentDevExecutor"),t(agentDevExecutor,"agentDevExecutor");async function runNestjs(e,n){const o=n.projectName,r=(o?n.projectsConfigurations?.projects[o]?.targets?.build:void 0)?.options?.outputPath,g=[...typeof r=="string"?[(0,node_path_1.join)(n.root,r,"main.js")]:[],(0,node_path_1.join)(e,"dist","main.js"),(0,node_path_1.join)(n.root,"dist",(0,node_path_1.relative)(n.root,e),"main.js")],p=g.find(c=>(0,node_fs_1.existsSync)(c));if(!p)return console.error(`[agent-dev] No built NestJS entry found. Looked in:
2
- `+g.map(c=>` \u2022 ${c}`).join(`
1
+ "use strict";var j=Object.defineProperty;var d=(e,n)=>j(e,"name",{value:n,configurable:!0});var $=Object.defineProperty,r=d((e,n)=>$(e,"name",{value:n,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=agentDevExecutor,exports.signalChild=signalChild,exports.resolveAgentDevMcpMode=resolveAgentDevMcpMode,exports.readShimLine=readShimLine,exports.mcpAuthHint=mcpAuthHint,exports.isLocalCaptureTarget=isLocalCaptureTarget;const node_child_process_1=require("node:child_process"),node_fs_1=require("node:fs"),node_path_1=require("node:path"),node_readline_1=require("node:readline"),lens_frontend_1=require("../../lens-frontend");async function agentDevExecutor(e,n){const o={kind:e.kind??"vite-react",chrome:e.chrome??!0,headless:e.headless??!0,node:e.node??!0,devTarget:e.devTarget,projectRoot:e.projectRoot,port:e.port,openUrl:e.openUrl,devCommand:e.devCommand,wsPort:e.wsPort,mcp:resolveAgentDevMcpMode(e.mcp,process.env,n.root)};if(o.kind!=="vite-react"&&o.kind!=="nestjs"&&o.kind!=="imported")return console.error(`[agent-dev] supported kinds are "vite-react", "nestjs", "imported" (got "${o.kind}").`),{success:!1};const s=(0,lens_frontend_1.lensmcpJsonProblem)(n.root);if(s)return console.error(`[agent-dev] ${s}`),{success:!1};const m=n.projectName,l=o.projectRoot?(0,node_path_1.resolve)(n.root,o.projectRoot):m&&n.projectsConfigurations?(0,node_path_1.resolve)(n.root,n.projectsConfigurations.projects[m]?.root??"."):n.root;if(o.kind==="nestjs")return runNestjs(l,n);if(o.kind==="imported")return runImported(l,n,{devCommand:o.devCommand,chrome:o.chrome,headless:o.headless,openUrl:o.openUrl,wsPort:o.wsPort??5747,node:o.node,mcp:o.mcp});const p=(0,lens_frontend_1.findMcpBundle)(n.root);p||console.warn("[agent-dev] No lensmcp-mcp bundle found \u2014 skipping MCP server. Install the self-contained CLI: `npm i -D lensmcp` (it ships `bundled/main.js`).");const c=[],g=new Map;let v=!1;function u(i,M,t,a,C=!1,h){const E=(0,node_child_process_1.spawn)(M,t,{cwd:l,env:{...process.env,...a??{}},stdio:"inherit"});return c.push(E),onSpawnFailure(E,i,()=>{C||f()}),E.on("exit",(S,_)=>{if(!v){if(C){const w=g.get(i)??0;if(h&&w<h.max){g.set(i,w+1),console.warn(`[agent-dev] ${i} exited (code=${S} sig=${_}); respawning in ${Math.round(h.delayMs/1e3)}s (${w+1}/${h.max}).`),setTimeout(()=>{v||u(i,M,t,a,C,h)},h.delayMs).unref?.();return}console.warn(`[agent-dev] ${i} exited (code=${S} sig=${_}); continuing.`);return}console.warn(`[agent-dev] ${i} exited unexpectedly (code=${S} sig=${_}); shutting down others.`),f()}}),E}d(u,"f"),r(u,"spawnChild");function f(){if(!v){v=!0;for(const i of c)signalChild(i,"SIGTERM")}}d(f,"g"),r(f,"shutdown"),process.on("SIGINT",f),process.on("SIGTERM",f);const P=process.env.LENSMCP_EVENT_FILE??(0,node_path_1.join)(n.root,".lensmcp","events.jsonl");try{(0,node_fs_1.mkdirSync)((0,node_path_1.dirname)(P),{recursive:!0});const i=(0,node_fs_1.statSync)(P,{throwIfNoEntry:!1});!i||Date.now()-i.mtimeMs>6e4?(0,node_fs_1.writeFileSync)(P,""):console.log("[agent-dev] event bridge is active (written <60s ago) \u2014 appending, not truncating.")}catch{}console.log(`[agent-dev] event bridge \u2192 ${P}`);try{(0,lens_frontend_1.spawnLensFrontend)({projectRoot:l,workspaceRoot:n.root,...m?{project:m}:{},eventFile:P,...o.port!==void 0?{port:o.port}:{},chrome:o.chrome,headless:o.headless,...o.openUrl?{openUrl:o.openUrl}:{},log:r(i=>console.log(i),"log")},u)}catch(i){return console.error(i.message),f(),{success:!1}}return p&&startMcp({mcpBundle:p,workspaceRoot:n.root,eventFile:P,mode:o.mcp,spawnChild:r((i,M,t,a)=>u(i,M,t,a),"spawnChild"),track:r(i=>{c.push(i)},"track")}),new Promise(i=>{const M=r(()=>{v?Promise.allSettled(c.map(exited)).then(()=>i({success:!0})):setTimeout(M,500)},"tick");M()})}d(agentDevExecutor,"agentDevExecutor"),r(agentDevExecutor,"agentDevExecutor");async function runNestjs(e,n){const o=n.projectName,s=(o?n.projectsConfigurations?.projects[o]?.targets?.build:void 0)?.options?.outputPath,m=[...typeof s=="string"?[(0,node_path_1.join)(n.root,s,"main.js")]:[],(0,node_path_1.join)(e,"dist","main.js"),(0,node_path_1.join)(n.root,"dist",(0,node_path_1.relative)(n.root,e),"main.js")],l=m.find(c=>(0,node_fs_1.existsSync)(c));if(!l)return console.error(`[agent-dev] No built NestJS entry found. Looked in:
2
+ `+m.map(c=>` \u2022 ${c}`).join(`
3
3
  `)+`
4
- Build first: \`nx build ${o??"<project>"}\`.`),{success:!1};console.log(`[agent-dev] node ${p}`);const u=(0,node_child_process_1.spawn)(process.execPath,[p],{cwd:e,stdio:"inherit",env:{...process.env,LENSMCP_TRANSPORT:process.env.LENSMCP_TRANSPORT??"http",LENSMCP_EVENT_FILE:process.env.LENSMCP_EVENT_FILE??(0,node_path_1.join)(n.root,".lensmcp","events.jsonl")}});return new Promise(c=>{const a=t(()=>{signalChild(u,"SIGTERM")},"onSignal");process.on("SIGINT",a),process.on("SIGTERM",a);const v=t(l=>{process.off("SIGINT",a),process.off("SIGTERM",a),c({success:l})},"done");onSpawnFailure(u,"nestjs",()=>v(!1)),u.on("exit",l=>v(l===0))})}d(runNestjs,"runNestjs"),t(runNestjs,"runNestjs");async function runImported(e,n,o){if(!o.devCommand)return console.error('[agent-dev] kind="imported" needs a `devCommand` (your dev-server command, e.g. "npm run dev").\n Add it to the agent-dev target options, or pass `--devCommand "npm run dev"`.'),{success:!1};const r=(0,lens_frontend_1.findBridgeBundle)(n.root);if(!r)return console.error("[agent-dev] No lensmcp bridge bundle found. Install the self-contained CLI: `npm i -D lensmcp` (it ships `bundled/bridge.js`)."),{success:!1};const g=(0,lens_frontend_1.findMcpBundle)(n.root);g||console.warn("[agent-dev] No lensmcp-mcp bundle found \u2014 skipping MCP server. Install the self-contained CLI: `npm i -D lensmcp`.");const p=[],u=new Map;let c=!1;function a(s,m,f,P,E=!1,M,w=!1){const _=(0,node_child_process_1.spawn)(m,f,{cwd:e,env:{...process.env,...P??{}},stdio:"inherit",shell:w});return p.push(_),onSpawnFailure(_,s,()=>{E||v()}),_.on("exit",(N,L)=>{if(!c){if(E){const $=u.get(s)??0;if(M&&$<M.max){u.set(s,$+1),console.warn(`[agent-dev] ${s} exited (code=${N} sig=${L}); respawning in ${Math.round(M.delayMs/1e3)}s (${$+1}/${M.max}).`),setTimeout(()=>{c||a(s,m,f,P,E,M,w)},M.delayMs).unref?.();return}console.warn(`[agent-dev] ${s} exited (code=${N} sig=${L}); continuing.`);return}console.warn(`[agent-dev] ${s} exited unexpectedly (code=${N} sig=${L}); shutting down others.`),v()}}),_}d(a,"a"),t(a,"spawnChild");function v(){if(!c){c=!0;for(const s of p)signalChild(s,"SIGTERM")}}d(v,"g"),t(v,"shutdown"),process.on("SIGINT",v),process.on("SIGTERM",v);const l=process.env.LENSMCP_EVENT_FILE??(0,node_path_1.join)(n.root,".lensmcp","events.jsonl");try{(0,node_fs_1.mkdirSync)((0,node_path_1.dirname)(l),{recursive:!0});const s=(0,node_fs_1.statSync)(l,{throwIfNoEntry:!1});!s||Date.now()-s.mtimeMs>6e4?(0,node_fs_1.writeFileSync)(l,""):console.log("[agent-dev] event bridge is active (written <60s ago) \u2014 appending, not truncating.")}catch{}const S={LENSMCP_EVENT_FILE:l};console.log(`[agent-dev] event bridge \u2192 ${l}`);const i=Object.values(n.projectsConfigurations?.projects??{}).map(s=>s.root),h=(0,lens_frontend_1.standaloneBridgeOrigins)(n.root,i);console.log(`[agent-dev] starting bridge \u2192 ws://127.0.0.1:${o.wsPort}`),h.hosts.length>0&&console.log(`[agent-dev] bridge admits this workspace's cluster hosts: ${h.hosts.join(", ")}`),a("bridge",process.execPath,[r],{...S,LENSMCP_WS_HOST:process.env.LENSMCP_WS_HOST??"127.0.0.1",LENSMCP_WS_PORT:String(o.wsPort),...h.allowedOrigins?{LENSMCP_BRIDGE_ALLOWED_ORIGINS:h.allowedOrigins}:{}}),g&&startMcp({mcpBundle:g,workspaceRoot:n.root,eventFile:l,mode:o.mcp,spawnChild:t((s,m,f,P)=>a(s,m,f,P),"spawnChild"),track:t(s=>{p.push(s)},"track")});const C={...S,LENSMCP_WS_PORT:String(o.wsPort)};if(o.node)if([e,n.root].some(s=>(0,node_fs_1.existsSync)((0,node_path_1.join)(s,"node_modules","@lensmcp","node-instrumentation")))){const s="--import @lensmcp/node-instrumentation/register";C.NODE_OPTIONS=process.env.NODE_OPTIONS?`${process.env.NODE_OPTIONS} ${s}`:s,console.log("[agent-dev] backend taps: NODE_OPTIONS += --import @lensmcp/node-instrumentation/register")}else console.warn("[agent-dev] @lensmcp/node-instrumentation not installed \u2014 skipping backend taps. Add it: `npm i -D @lensmcp/node-instrumentation`.");if(console.log(`[agent-dev] front-end seam: add \`import '@lensmcp/client-runtime/auto'\` to your app entry (connects to ws://127.0.0.1:${o.wsPort}).`),console.log(`[agent-dev] starting dev command: ${o.devCommand}`),a("dev",o.devCommand,[],C,!1,void 0,!0),o.chrome){const s=(0,lens_frontend_1.findCaptureRunner)(n.root),m=o.openUrl;s?m?(console.log(`[agent-dev] starting browser capture \u2192 ${m}`),a("browser-capture",process.execPath,[s],{...S,LENSMCP_DEV_URL:m,LENSMCP_TOKENS_FILE:(0,node_path_1.join)(n.root,"lensmcp.tokens.json"),LENSMCP_RULES_FILE:(0,node_path_1.join)(n.root,"lensmcp.rules.json"),LENSMCP_HEADLESS:o.headless===!1?"false":"true"},!0,{delayMs:1e4,max:5})):console.warn("[agent-dev] no `openUrl` provided \u2014 skipping Chrome capture (set openUrl to your dev URL)."):console.warn("[agent-dev] browser-capture runner not found \u2014 skipping live capture. Install the self-contained CLI: `npm i -D lensmcp`.")}return new Promise(s=>{const m=t(()=>{c?Promise.allSettled(p.map(exited)).then(()=>s({success:!0})):setTimeout(m,500)},"tick");m()})}d(runImported,"runImported"),t(runImported,"runImported");function signalChild(e,n){if(e.pid===void 0)return!1;try{return e.kill(n)}catch{return!1}}d(signalChild,"signalChild"),t(signalChild,"signalChild");function onSpawnFailure(e,n,o){e.on("error",r=>{if(e.pid!==void 0){console.warn(`[agent-dev] ${n}: ${r.message}`);return}console.error(`[agent-dev] ${n} failed to start: ${r.message}`),o()})}d(onSpawnFailure,"onSpawnFailure"),t(onSpawnFailure,"onSpawnFailure");function exited(e){return e.exitCode!==null||e.signalCode!==null||e.pid===void 0?Promise.resolve():new Promise(n=>e.once("exit",()=>n()))}d(exited,"exited"),t(exited,"exited");function resolveAgentDevMcpMode(e,n,o){for(const r of[e,n.LENSMCP_MCP_MODE,configuredMcpMode(o)])if(r==="shared"||r==="embedded")return r;return"shared"}d(resolveAgentDevMcpMode,"resolveAgentDevMcpMode"),t(resolveAgentDevMcpMode,"resolveAgentDevMcpMode");function configuredMcpMode(e){try{return JSON.parse((0,node_fs_1.readFileSync)((0,node_path_1.join)(e,".lensmcp","config.json"),"utf8"))?.mcp?.mode}catch{return}}d(configuredMcpMode,"configuredMcpMode"),t(configuredMcpMode,"configuredMcpMode");function startMcp(e){const n=e.mode==="shared"?sharedShimBeside(e.mcpBundle):void 0;if(n){e.track(ensureSharedMcpServer(n,e.workspaceRoot,e.eventFile));return}e.mode==="shared"&&console.warn(`[agent-dev] no shared-mode shim beside ${e.mcpBundle} (a lensmcp before shared mode) \u2014 starting agent-dev's own MCP server.`),console.log(`[agent-dev] starting LensMCP MCP server (${e.mcpBundle})`),console.log(mcpAuthHint()),e.spawnChild("lensmcp-mcp",process.execPath,[e.mcpBundle],{LENSMCP_EVENT_FILE:e.eventFile,LENSMCP_TRANSPORT:process.env.LENSMCP_TRANSPORT??"http",LENSMCP_PORT:process.env.LENSMCP_PORT??"3000"})}d(startMcp,"startMcp"),t(startMcp,"startMcp");function sharedShimBeside(e){const n=(0,node_path_1.join)((0,node_path_1.dirname)(e),"shim.js");return(0,node_fs_1.existsSync)(n)?n:void 0}d(sharedShimBeside,"sharedShimBeside"),t(sharedShimBeside,"sharedShimBeside");function ensureSharedMcpServer(e,n,o){console.log(`[agent-dev] MCP: attaching this workspace's shared server (${e})`);const r=(0,node_child_process_1.spawn)(process.execPath,[e,"--cwd",n],{cwd:n,env:{...process.env,LENSMCP_EVENT_FILE:o},stdio:["ignore","ignore","pipe"]});onSpawnFailure(r,"shared MCP shim",()=>{});let g,p=!1;return r.stderr&&(0,node_readline_1.createInterface)({input:r.stderr}).on("line",u=>{console.error(u);const c=readShimLine(u);c?.kind==="scope"&&(g=c.url),c?.kind==="attached"&&(p=!0,console.log(`[agent-dev] MCP: this workspace's shared server \u2192 ${g??"(url not reported)"} (${c.outcome})`),console.log(mcpAuthHint())),c?.kind==="unavailable"&&(p=!0,console.warn(`[agent-dev] MCP: this workspace's shared server is unavailable (${c.reason}). agent-dev starts no server of its own in shared mode; agent sessions fall back to an embedded one. For one here: LENSMCP_MCP_MODE=embedded, or the target option \`"mcp": "embedded"\`.`))}),r.on("exit",(u,c)=>{!p&&c===null&&console.warn(`[agent-dev] MCP: the shim exited (code=${u}) without reporting the shared server.`)}),r}d(ensureSharedMcpServer,"ensureSharedMcpServer"),t(ensureSharedMcpServer,"ensureSharedMcpServer");function readShimLine(e){const n=/\bshim → workspace ".*" \(.*\) → (\S+)$/.exec(e);if(n?.[1])return{kind:"scope",url:n[1]};const o=/\bshim: shared server (\S+) \(\d+ms\)$/.exec(e);if(o?.[1])return{kind:"attached",outcome:o[1]};const r=/\bshared MCP server unavailable \((.*)\) — falling back to an embedded server\.$/.exec(e);if(r?.[1]!==void 0)return{kind:"unavailable",reason:r[1]}}d(readShimLine,"readShimLine"),t(readShimLine,"readShimLine");function mcpAuthHint(e=process.env){return e.LENSMCP_ALLOW_INSECURE==="1"?"[agent-dev] MCP server: LENSMCP_ALLOW_INSECURE=1 \u2014 no credential required.":`[agent-dev] MCP server requires a bearer token (${e.LENSMCP_MCP_TOKEN?"LENSMCP_MCP_TOKEN":`${e.LENSMCP_HOME||"~"}/.lensmcp/mcp-token`}). The stdio \`lensmcp mcp\` entry sends it for you; an HTTP client entry needs "headers": { "Authorization": "Bearer \${LENSMCP_MCP_TOKEN}" }.`}d(mcpAuthHint,"mcpAuthHint"),t(mcpAuthHint,"mcpAuthHint");function isLocalCaptureTarget(e,n=process.env){if(n.LENSMCP_CAPTURE_ALLOW_REMOTE==="1")return!0;let o;try{o=new URL(e)}catch{return!1}if(o.protocol!=="http:"&&o.protocol!=="https:")return!1;const r=o.hostname.toLowerCase();return r==="localhost"||r==="[::1]"||r==="::1"?!0:/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(r)}d(isLocalCaptureTarget,"isLocalCaptureTarget"),t(isLocalCaptureTarget,"isLocalCaptureTarget");
4
+ Build first: \`nx build ${o??"<project>"}\`.`),{success:!1};console.log(`[agent-dev] node ${l}`);const p=(0,node_child_process_1.spawn)(process.execPath,[l],{cwd:e,stdio:"inherit",env:{...process.env,LENSMCP_TRANSPORT:process.env.LENSMCP_TRANSPORT??"http",LENSMCP_EVENT_FILE:process.env.LENSMCP_EVENT_FILE??(0,node_path_1.join)(n.root,".lensmcp","events.jsonl")}});return new Promise(c=>{const g=r(()=>{signalChild(p,"SIGTERM")},"onSignal");process.on("SIGINT",g),process.on("SIGTERM",g);const v=r(u=>{process.off("SIGINT",g),process.off("SIGTERM",g),c({success:u})},"done");onSpawnFailure(p,"nestjs",()=>v(!1)),p.on("exit",u=>v(u===0))})}d(runNestjs,"runNestjs"),r(runNestjs,"runNestjs");async function runImported(e,n,o){if(!o.devCommand)return console.error('[agent-dev] kind="imported" needs a `devCommand` (your dev-server command, e.g. "npm run dev").\n Add it to the agent-dev target options, or pass `--devCommand "npm run dev"`.'),{success:!1};const s=(0,lens_frontend_1.findBridgeBundle)(n.root);if(!s)return console.error("[agent-dev] No lensmcp bridge bundle found. Install the self-contained CLI: `npm i -D lensmcp` (it ships `bundled/bridge.js`)."),{success:!1};const m=(0,lens_frontend_1.findMcpBundle)(n.root);m||console.warn("[agent-dev] No lensmcp-mcp bundle found \u2014 skipping MCP server. Install the self-contained CLI: `npm i -D lensmcp`.");const l=[],p=new Map;let c=!1;function g(t,a,C,h,E=!1,S,_=!1){const w=(0,node_child_process_1.spawn)(a,C,{cwd:e,env:{...process.env,...h??{}},stdio:"inherit",shell:_});return l.push(w),onSpawnFailure(w,t,()=>{E||v()}),w.on("exit",(N,L)=>{if(!c){if(E){const T=p.get(t)??0;if(S&&T<S.max){p.set(t,T+1),console.warn(`[agent-dev] ${t} exited (code=${N} sig=${L}); respawning in ${Math.round(S.delayMs/1e3)}s (${T+1}/${S.max}).`),setTimeout(()=>{c||g(t,a,C,h,E,S,_)},S.delayMs).unref?.();return}console.warn(`[agent-dev] ${t} exited (code=${N} sig=${L}); continuing.`);return}console.warn(`[agent-dev] ${t} exited unexpectedly (code=${N} sig=${L}); shutting down others.`),v()}}),w}d(g,"m"),r(g,"spawnChild");function v(){if(!c){c=!0;for(const t of l)signalChild(t,"SIGTERM")}}d(v,"u"),r(v,"shutdown"),process.on("SIGINT",v),process.on("SIGTERM",v);const u=process.env.LENSMCP_EVENT_FILE??(0,node_path_1.join)(n.root,".lensmcp","events.jsonl");try{(0,node_fs_1.mkdirSync)((0,node_path_1.dirname)(u),{recursive:!0});const t=(0,node_fs_1.statSync)(u,{throwIfNoEntry:!1});!t||Date.now()-t.mtimeMs>6e4?(0,node_fs_1.writeFileSync)(u,""):console.log("[agent-dev] event bridge is active (written <60s ago) \u2014 appending, not truncating.")}catch{}const f={LENSMCP_EVENT_FILE:u};console.log(`[agent-dev] event bridge \u2192 ${u}`);const P=Object.entries(n.projectsConfigurations?.projects??{}).map(([t,a])=>({name:t,root:a.root})),i=(0,lens_frontend_1.standaloneBridgeOrigins)(n.root,P);console.log(`[agent-dev] starting bridge \u2192 ws://127.0.0.1:${o.wsPort}`),i.hosts.length>0&&console.log(`[agent-dev] bridge admits this workspace's cluster hosts: ${i.hosts.join(", ")}`),g("bridge",process.execPath,[s],{...f,LENSMCP_WS_HOST:process.env.LENSMCP_WS_HOST??"127.0.0.1",LENSMCP_WS_PORT:String(o.wsPort),...i.allowedOrigins?{LENSMCP_BRIDGE_ALLOWED_ORIGINS:i.allowedOrigins}:{}}),m&&startMcp({mcpBundle:m,workspaceRoot:n.root,eventFile:u,mode:o.mcp,spawnChild:r((t,a,C,h)=>g(t,a,C,h),"spawnChild"),track:r(t=>{l.push(t)},"track")});const M={...f,LENSMCP_WS_PORT:String(o.wsPort)};if(o.node)if([e,n.root].some(t=>(0,node_fs_1.existsSync)((0,node_path_1.join)(t,"node_modules","@lensmcp","node-instrumentation")))){const t="--import @lensmcp/node-instrumentation/register";M.NODE_OPTIONS=process.env.NODE_OPTIONS?`${process.env.NODE_OPTIONS} ${t}`:t,console.log("[agent-dev] backend taps: NODE_OPTIONS += --import @lensmcp/node-instrumentation/register")}else console.warn("[agent-dev] @lensmcp/node-instrumentation not installed \u2014 skipping backend taps. Add it: `npm i -D @lensmcp/node-instrumentation`.");if(console.log(`[agent-dev] front-end seam: add \`import '@lensmcp/client-runtime/auto'\` to your app entry (connects to ws://127.0.0.1:${o.wsPort}).`),console.log(`[agent-dev] starting dev command: ${o.devCommand}`),g("dev",o.devCommand,[],M,!1,void 0,!0),o.chrome){const t=(0,lens_frontend_1.findCaptureRunner)(n.root),a=o.openUrl;t?a?(console.log(`[agent-dev] starting browser capture \u2192 ${a}`),g("browser-capture",process.execPath,[t],{...f,LENSMCP_DEV_URL:a,LENSMCP_TOKENS_FILE:(0,node_path_1.join)(n.root,"lensmcp.tokens.json"),LENSMCP_RULES_FILE:(0,node_path_1.join)(n.root,"lensmcp.rules.json"),LENSMCP_HEADLESS:o.headless===!1?"false":"true"},!0,{delayMs:1e4,max:5})):console.warn("[agent-dev] no `openUrl` provided \u2014 skipping Chrome capture (set openUrl to your dev URL)."):console.warn("[agent-dev] browser-capture runner not found \u2014 skipping live capture. Install the self-contained CLI: `npm i -D lensmcp`.")}return new Promise(t=>{const a=r(()=>{c?Promise.allSettled(l.map(exited)).then(()=>t({success:!0})):setTimeout(a,500)},"tick");a()})}d(runImported,"runImported"),r(runImported,"runImported");function signalChild(e,n){if(e.pid===void 0)return!1;try{return e.kill(n)}catch{return!1}}d(signalChild,"signalChild"),r(signalChild,"signalChild");function onSpawnFailure(e,n,o){e.on("error",s=>{if(e.pid!==void 0){console.warn(`[agent-dev] ${n}: ${s.message}`);return}console.error(`[agent-dev] ${n} failed to start: ${s.message}`),o()})}d(onSpawnFailure,"onSpawnFailure"),r(onSpawnFailure,"onSpawnFailure");function exited(e){return e.exitCode!==null||e.signalCode!==null||e.pid===void 0?Promise.resolve():new Promise(n=>e.once("exit",()=>n()))}d(exited,"exited"),r(exited,"exited");function resolveAgentDevMcpMode(e,n,o){for(const s of[e,n.LENSMCP_MCP_MODE,configuredMcpMode(o)])if(s==="shared"||s==="embedded")return s;return"shared"}d(resolveAgentDevMcpMode,"resolveAgentDevMcpMode"),r(resolveAgentDevMcpMode,"resolveAgentDevMcpMode");function configuredMcpMode(e){try{return JSON.parse((0,node_fs_1.readFileSync)((0,node_path_1.join)(e,".lensmcp","config.json"),"utf8"))?.mcp?.mode}catch{return}}d(configuredMcpMode,"configuredMcpMode"),r(configuredMcpMode,"configuredMcpMode");function startMcp(e){const n=e.mode==="shared"?sharedShimBeside(e.mcpBundle):void 0;if(n){e.track(ensureSharedMcpServer(n,e.workspaceRoot,e.eventFile));return}e.mode==="shared"&&console.warn(`[agent-dev] no shared-mode shim beside ${e.mcpBundle} (a lensmcp before shared mode) \u2014 starting agent-dev's own MCP server.`),console.log(`[agent-dev] starting LensMCP MCP server (${e.mcpBundle})`),console.log(mcpAuthHint()),e.spawnChild("lensmcp-mcp",process.execPath,[e.mcpBundle],{LENSMCP_EVENT_FILE:e.eventFile,LENSMCP_TRANSPORT:process.env.LENSMCP_TRANSPORT??"http",LENSMCP_PORT:process.env.LENSMCP_PORT??"3000"})}d(startMcp,"startMcp"),r(startMcp,"startMcp");function sharedShimBeside(e){const n=(0,node_path_1.join)((0,node_path_1.dirname)(e),"shim.js");return(0,node_fs_1.existsSync)(n)?n:void 0}d(sharedShimBeside,"sharedShimBeside"),r(sharedShimBeside,"sharedShimBeside");function ensureSharedMcpServer(e,n,o){console.log(`[agent-dev] MCP: attaching this workspace's shared server (${e})`);const s=(0,node_child_process_1.spawn)(process.execPath,[e,"--cwd",n],{cwd:n,env:{...process.env,LENSMCP_EVENT_FILE:o},stdio:["ignore","ignore","pipe"]});onSpawnFailure(s,"shared MCP shim",()=>{});let m,l=!1;return s.stderr&&(0,node_readline_1.createInterface)({input:s.stderr}).on("line",p=>{console.error(p);const c=readShimLine(p);c?.kind==="scope"&&(m=c.url),c?.kind==="attached"&&(l=!0,console.log(`[agent-dev] MCP: this workspace's shared server \u2192 ${m??"(url not reported)"} (${c.outcome})`),console.log(mcpAuthHint())),c?.kind==="unavailable"&&(l=!0,console.warn(`[agent-dev] MCP: this workspace's shared server is unavailable (${c.reason}). agent-dev starts no server of its own in shared mode; agent sessions fall back to an embedded one. For one here: LENSMCP_MCP_MODE=embedded, or the target option \`"mcp": "embedded"\`.`))}),s.on("exit",(p,c)=>{!l&&c===null&&console.warn(`[agent-dev] MCP: the shim exited (code=${p}) without reporting the shared server.`)}),s}d(ensureSharedMcpServer,"ensureSharedMcpServer"),r(ensureSharedMcpServer,"ensureSharedMcpServer");function readShimLine(e){const n=/\bshim → workspace ".*" \(.*\) → (\S+)$/.exec(e);if(n?.[1])return{kind:"scope",url:n[1]};const o=/\bshim: shared server (\S+) \(\d+ms\)$/.exec(e);if(o?.[1])return{kind:"attached",outcome:o[1]};const s=/\bshared MCP server unavailable \((.*)\) — falling back to an embedded server\.$/.exec(e);if(s?.[1]!==void 0)return{kind:"unavailable",reason:s[1]}}d(readShimLine,"readShimLine"),r(readShimLine,"readShimLine");function mcpAuthHint(e=process.env){return e.LENSMCP_ALLOW_INSECURE==="1"?"[agent-dev] MCP server: LENSMCP_ALLOW_INSECURE=1 \u2014 no credential required.":`[agent-dev] MCP server requires a bearer token (${e.LENSMCP_MCP_TOKEN?"LENSMCP_MCP_TOKEN":`${e.LENSMCP_HOME||"~"}/.lensmcp/mcp-token`}). The stdio \`lensmcp mcp\` entry sends it for you; an HTTP client entry needs "headers": { "Authorization": "Bearer \${LENSMCP_MCP_TOKEN}" }.`}d(mcpAuthHint,"mcpAuthHint"),r(mcpAuthHint,"mcpAuthHint");function isLocalCaptureTarget(e,n=process.env){if(n.LENSMCP_CAPTURE_ALLOW_REMOTE==="1")return!0;let o;try{o=new URL(e)}catch{return!1}if(o.protocol!=="http:"&&o.protocol!=="https:")return!1;const s=o.hostname.toLowerCase();return s==="localhost"||s==="[::1]"||s==="::1"?!0:/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(s)}d(isLocalCaptureTarget,"isLocalCaptureTarget"),r(isLocalCaptureTarget,"isLocalCaptureTarget");
@@ -48,6 +48,7 @@ export declare function initGenerator(tree: Tree, rawOptions?: InitGeneratorSche
48
48
  export declare function mcpServerEntry(workspaceRoot: string, deps?: {
49
49
  exists?: (p: string) => boolean;
50
50
  version?: string;
51
+ store?: boolean;
51
52
  }): McpServerEntry;
52
53
  /**
53
54
  * This plugin's own version, for the pin above. Walks up from the compiled module rather than
@@ -78,6 +79,9 @@ export declare function isGeneratedMcpEntry(entry: unknown): entry is McpServerE
78
79
  * the workspace's own install. Refreshed: a generated entry when the fresh one calls the local install
79
80
  * (`--no`), and the unpinned legacy forms always. A pinned entry with still no local install is a pin,
80
81
  * and is left as it is; so is anything a user customised.
82
+ *
83
+ * The store's launcher (planning/global G2) wraps the npx form: once written it stays, since a machine without a
84
+ * store runs the npx form inside it; the npx form inside follows the rules above.
81
85
  */
82
86
  export declare function refreshedMcpEntry(existing: unknown, fresh: McpServerEntry): McpServerEntry | undefined;
83
87
  export default initGenerator;
@@ -1,13 +1,13 @@
1
- "use strict";var S=Object.defineProperty;var c=(e,s)=>S(e,"name",{value:s,configurable:!0});var g=Object.defineProperty,a=c((e,s)=>g(e,"name",{value:s,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_SHARED_DIRS=void 0,exports.fixLensGitignore=fixLensGitignore,exports.initGenerator=initGenerator,exports.mcpServerEntry=mcpServerEntry,exports.pluginVersion=pluginVersion,exports.isGeneratedMcpEntry=isGeneratedMcpEntry,exports.refreshedMcpEntry=refreshedMcpEntry;const node_fs_1=require("node:fs"),node_path_1=require("node:path"),devkit_1=require("@nx/devkit"),DEFAULT_LENSMCP_CONFIG={schemaVersion:1,storage:"memory",transport:"stdio",retention:{sessions:5,events:5e3,screenshots:50,buildReports:20,visualFrames:200,heapSnapshots:3,tracesWithErrors:20,verifications:10},redaction:{headers:["authorization","cookie","set-cookie","x-api-key"],paths:["password","token","secret","apiKey","api_key"]},channels:{blockingStatusChanged:{enabled:!0,minSeverity:"error"},memoryLeakSuspected:{enabled:!0,minSeverity:"warning"},bundleRegression:{enabled:!0,minSeverity:"warning"},visualViolationBlocking:{enabled:!0,minSeverity:"error"},verificationCompleted:{enabled:!0,minSeverity:"info"}},thresholds:{dbInLoop:5,nPlusOne:3,renderStorm:5,slowRouteMs:500,slowRenderMs:16}},LENSMCP_GITIGNORE_MARKER="# LensMCP: this machine's runtime state is ignored; the team's analyzer instructions are kept";exports.LENS_SHARED_DIRS=["sql-review","route-review","flow-review","ui-review","cache-review","queue-review","ai-review","ai-names","team","team-design"];function fixLensGitignore(e){const s=e.split(`
2
- `),r=/^(\/|\*\*\/)?\.lensmcp\/?(\*)?$/;let n=s.findIndex(o=>r.test(o.trim())),t=!1;if(n<0){const o=e.length&&!e.endsWith(`
1
+ "use strict";var x=Object.defineProperty;var c=(e,r)=>x(e,"name",{value:r,configurable:!0});var g=Object.defineProperty,a=c((e,r)=>g(e,"name",{value:r,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_SHARED_DIRS=void 0,exports.fixLensGitignore=fixLensGitignore,exports.initGenerator=initGenerator,exports.mcpServerEntry=mcpServerEntry,exports.pluginVersion=pluginVersion,exports.isGeneratedMcpEntry=isGeneratedMcpEntry,exports.refreshedMcpEntry=refreshedMcpEntry;const node_fs_1=require("node:fs"),node_path_1=require("node:path"),devkit_1=require("@nx/devkit"),lens_store_1=require("../../lens-store"),DEFAULT_LENSMCP_CONFIG={schemaVersion:1,storage:"memory",transport:"stdio",retention:{sessions:5,events:5e3,screenshots:50,buildReports:20,visualFrames:200,heapSnapshots:3,tracesWithErrors:20,verifications:10},redaction:{headers:["authorization","cookie","set-cookie","x-api-key"],paths:["password","token","secret","apiKey","api_key"]},channels:{blockingStatusChanged:{enabled:!0,minSeverity:"error"},memoryLeakSuspected:{enabled:!0,minSeverity:"warning"},bundleRegression:{enabled:!0,minSeverity:"warning"},visualViolationBlocking:{enabled:!0,minSeverity:"error"},verificationCompleted:{enabled:!0,minSeverity:"info"}},thresholds:{dbInLoop:5,nPlusOne:3,renderStorm:5,slowRouteMs:500,slowRenderMs:16}},LENSMCP_GITIGNORE_MARKER="# LensMCP: this machine's runtime state is ignored; the team's analyzer instructions are kept";exports.LENS_SHARED_DIRS=["sql-review","route-review","flow-review","ui-review","cache-review","queue-review","ai-review","ai-names","team","team-design"];function fixLensGitignore(e){const r=e.split(`
2
+ `),s=/^(\/|\*\*\/)?\.lensmcp\/?(\*)?$/;let n=r.findIndex(o=>s.test(o.trim())),t=!1;if(n<0){const o=e.length&&!e.endsWith(`
3
3
  `)?`${e}
4
4
  `:e;return{text:`${o}${o.trim()?`
5
5
  `:""}${LENSMCP_GITIGNORE_MARKER}
6
6
  **/.lensmcp/*
7
- ${exports.LENS_SHARED_DIRS.map(l=>`!**/.lensmcp/${l}/`).join(`
7
+ ${exports.LENS_SHARED_DIRS.map(p=>`!**/.lensmcp/${p}/`).join(`
8
8
  `)}
9
- `,changed:!0}}const i=r.exec(s[n].trim())[1]==="/"?"/":"**/";s[n].trim()!==`${i}.lensmcp/*`&&(s[n]=`${i}.lensmcp/*`,t=!0);for(const o of exports.LENS_SHARED_DIRS){const l=`!${i}.lensmcp/${o}/`;s.some(m=>m.trim()===l||m.trim()===l.slice(0,-1))||(s.splice(++n,0,l),t=!0)}return{text:s.join(`
10
- `),changed:t}}c(fixLensGitignore,"fixLensGitignore"),a(fixLensGitignore,"fixLensGitignore");async function initGenerator(e,s={}){const r={skipFormat:s.skipFormat??!1,registerHostConfig:s.registerHostConfig??"auto"},n=[];if(e.exists("nx.json")){const d=(0,devkit_1.readJson)(e,"nx.json"),p=JSON.parse(JSON.stringify(d));p.plugins=Array.isArray(p.plugins)?p.plugins:[],p.plugins.some(u=>typeof u=="string"?u==="@lensmcp/nx-plugin":u&&typeof u=="object"&&"plugin"in u?u.plugin==="@lensmcp/nx-plugin":!1)||(p.plugins.push("@lensmcp/nx-plugin"),n.push("nx.json: registered @lensmcp/nx-plugin"));const y=p.lensmcp??{};p.lensmcp=mergeDeep(DEFAULT_LENSMCP_CONFIG,y),(!("lensmcp"in p)||Object.keys(y).length===0)&&n.push("nx.json: added workspace-wide `lensmcp` config block"),canonicalJson(p)!==canonicalJson(d)&&(0,devkit_1.writeJson)(e,"nx.json",p)}else throw new Error("No nx.json found at the workspace root. Are you in a Nx workspace?");const t=".gitignore",i=e.exists(t)?e.read(t,"utf-8")??"":"",o=fixLensGitignore(i);o.changed&&(e.write(t,o.text),n.push(`${t}: ignores **/.lensmcp/* and keeps ${exports.LENS_SHARED_DIRS.map(d=>`.lensmcp/${d}/`).join(", ")}`));const l=(0,devkit_1.joinPathFragments)(".lensmcp",".keep");e.exists(l)||(e.write(l,""),n.push(`${l}: created`));const m=(0,devkit_1.joinPathFragments)(".lensmcp","install-trail.json"),f=(e.exists(m)?JSON.parse(e.read(m,"utf-8")??"{}"):void 0)??{schemaVersion:1,installedAt:new Date().toISOString(),steps:[]};f.steps.push(...n),e.write(m,JSON.stringify(f,null,2)+`
11
- `),r.registerHostConfig!=="never"&&registerWorkspaceMcpConfig(e,n),r.skipFormat||await(0,devkit_1.formatFiles)(e)}c(initGenerator,"initGenerator"),a(initGenerator,"initGenerator");function mcpServerEntry(e,s={}){if((s.exists??node_fs_1.existsSync)((0,node_path_1.join)(e,"node_modules",".bin","lensmcp")))return{command:"npx",args:["--no","lensmcp","mcp"]};const r="version"in s?s.version:pluginVersion();return{command:"npx",args:["--yes",r?`lensmcp@${r}`:"lensmcp","mcp"]}}c(mcpServerEntry,"mcpServerEntry"),a(mcpServerEntry,"mcpServerEntry");function pluginVersion(e=__dirname){let s=e;for(let r=0;r<6;r++){const n=(0,node_path_1.join)(s,"package.json");try{if((0,node_fs_1.existsSync)(n)){const i=JSON.parse((0,node_fs_1.readFileSync)(n,"utf-8"));if(i.name==="@lensmcp/nx-plugin"&&typeof i.version=="string")return i.version}}catch{}const t=(0,node_path_1.dirname)(s);if(t===s)break;s=t}}c(pluginVersion,"pluginVersion"),a(pluginVersion,"pluginVersion");const PINNED_SPECIFIER=/^lensmcp@\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;function isGeneratedMcpEntry(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const{command:s,args:r,...n}=e;if(s!=="npx"||Object.keys(n).length>0||!Array.isArray(r)||r.length!==3)return!1;const[t,i,o]=r;return o!=="mcp"||typeof i!="string"?!1:t==="--no"?i==="lensmcp":t==="-y"||t==="--yes"?i==="lensmcp"||PINNED_SPECIFIER.test(i):!1}c(isGeneratedMcpEntry,"isGeneratedMcpEntry"),a(isGeneratedMcpEntry,"isGeneratedMcpEntry");function refreshedMcpEntry(e,s){if(!isGeneratedMcpEntry(e)||e.args.join(" ")===s.args.join(" "))return;const r=e.args[0]!=="--no"&&e.args[1]==="lensmcp";return s.args[0]==="--no"||r?s:void 0}c(refreshedMcpEntry,"refreshedMcpEntry"),a(refreshedMcpEntry,"refreshedMcpEntry");function registerWorkspaceMcpConfig(e,s){const r=".mcp.json";let n={};if(e.exists(r))try{n=JSON.parse(e.read(r,"utf-8")??"{}")}catch{n={}}(!n||typeof n!="object")&&(n={}),(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});const t=n.mcpServers.lensmcp,i=mcpServerEntry(e.root);if(t){const o=refreshedMcpEntry(t,i);if(!o)return;n.mcpServers.lensmcp=o,e.write(r,JSON.stringify(n,null,2)+`
12
- `),s.push(`.mcp.json: refreshed the generated lensmcp MCP entry (${t.args.join(" ")} \u2192 ${o.args.join(" ")})`);return}n.mcpServers.lensmcp=i,e.write(r,JSON.stringify(n,null,2)+`
13
- `),s.push(`.mcp.json: registered lensmcp MCP server (stdio, ${i.args.join(" ")})`)}c(registerWorkspaceMcpConfig,"registerWorkspaceMcpConfig"),a(registerWorkspaceMcpConfig,"registerWorkspaceMcpConfig"),exports.default=initGenerator;function canonicalJson(e){return JSON.stringify(e,(s,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).sort(([n],[t])=>n<t?-1:n>t?1:0)):r)}c(canonicalJson,"canonicalJson"),a(canonicalJson,"canonicalJson");function mergeDeep(e,s){const r={...e};for(const[n,t]of Object.entries(s))t!==null&&typeof t=="object"&&!Array.isArray(t)&&r[n]!==null&&typeof r[n]=="object"&&!Array.isArray(r[n])?r[n]=mergeDeep(r[n],t):r[n]=t;return r}c(mergeDeep,"mergeDeep"),a(mergeDeep,"mergeDeep");
9
+ `,changed:!0}}const i=s.exec(r[n].trim())[1]==="/"?"/":"**/";r[n].trim()!==`${i}.lensmcp/*`&&(r[n]=`${i}.lensmcp/*`,t=!0);for(const o of exports.LENS_SHARED_DIRS){const p=`!${i}.lensmcp/${o}/`;r.some(l=>l.trim()===p||l.trim()===p.slice(0,-1))||(r.splice(++n,0,p),t=!0)}return{text:r.join(`
10
+ `),changed:t}}c(fixLensGitignore,"fixLensGitignore"),a(fixLensGitignore,"fixLensGitignore");async function initGenerator(e,r={}){const s={skipFormat:r.skipFormat??!1,registerHostConfig:r.registerHostConfig??"auto"},n=[];if(e.exists("nx.json")){const d=(0,devkit_1.readJson)(e,"nx.json"),m=JSON.parse(JSON.stringify(d));m.plugins=Array.isArray(m.plugins)?m.plugins:[],m.plugins.some(u=>typeof u=="string"?u==="@lensmcp/nx-plugin":u&&typeof u=="object"&&"plugin"in u?u.plugin==="@lensmcp/nx-plugin":!1)||(m.plugins.push("@lensmcp/nx-plugin"),n.push("nx.json: registered @lensmcp/nx-plugin"));const y=m.lensmcp??{};m.lensmcp=mergeDeep(DEFAULT_LENSMCP_CONFIG,y),(!("lensmcp"in m)||Object.keys(y).length===0)&&n.push("nx.json: added workspace-wide `lensmcp` config block"),canonicalJson(m)!==canonicalJson(d)&&(0,devkit_1.writeJson)(e,"nx.json",m)}else throw new Error("No nx.json found at the workspace root. Are you in a Nx workspace?");const t=".gitignore",i=e.exists(t)?e.read(t,"utf-8")??"":"",o=fixLensGitignore(i);o.changed&&(e.write(t,o.text),n.push(`${t}: ignores **/.lensmcp/* and keeps ${exports.LENS_SHARED_DIRS.map(d=>`.lensmcp/${d}/`).join(", ")}`));const p=(0,devkit_1.joinPathFragments)(".lensmcp",".keep");e.exists(p)||(e.write(p,""),n.push(`${p}: created`));const l=(0,devkit_1.joinPathFragments)(".lensmcp","install-trail.json"),f=(e.exists(l)?JSON.parse(e.read(l,"utf-8")??"{}"):void 0)??{schemaVersion:1,installedAt:new Date().toISOString(),steps:[]};f.steps.push(...n),e.write(l,JSON.stringify(f,null,2)+`
11
+ `),s.registerHostConfig!=="never"&&registerWorkspaceMcpConfig(e,n),s.skipFormat||await(0,devkit_1.formatFiles)(e)}c(initGenerator,"initGenerator"),a(initGenerator,"initGenerator");function mcpServerEntry(e,r={}){const s=r.exists??node_fs_1.existsSync,n="version"in r?r.version:pluginVersion(),t=s((0,node_path_1.join)(e,"node_modules",".bin","lensmcp"))?{command:"npx",args:["--no","lensmcp","mcp"]}:{command:"npx",args:["--yes",n?`lensmcp@${n}`:"lensmcp","mcp"]};return r.store??(0,lens_store_1.storeCurrent)()!==void 0?(0,lens_store_1.storeFirstMcpEntry)(t.args):t}c(mcpServerEntry,"mcpServerEntry"),a(mcpServerEntry,"mcpServerEntry");function pluginVersion(e=__dirname){let r=e;for(let s=0;s<6;s++){const n=(0,node_path_1.join)(r,"package.json");try{if((0,node_fs_1.existsSync)(n)){const i=JSON.parse((0,node_fs_1.readFileSync)(n,"utf-8"));if(i.name==="@lensmcp/nx-plugin"&&typeof i.version=="string")return i.version}}catch{}const t=(0,node_path_1.dirname)(r);if(t===r)break;r=t}}c(pluginVersion,"pluginVersion"),a(pluginVersion,"pluginVersion");const PINNED_SPECIFIER=/^lensmcp@\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;function isGeneratedMcpEntry(e){const r=(0,lens_store_1.storeFirstFallback)(e);return isGeneratedNpx(r?{command:"npx",args:r}:e)}c(isGeneratedMcpEntry,"isGeneratedMcpEntry"),a(isGeneratedMcpEntry,"isGeneratedMcpEntry");function isGeneratedNpx(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const{command:r,args:s,...n}=e;if(r!=="npx"||Object.keys(n).length>0||!Array.isArray(s)||s.length!==3)return!1;const[t,i,o]=s;return o!=="mcp"||typeof i!="string"?!1:t==="--no"?i==="lensmcp":t==="-y"||t==="--yes"?i==="lensmcp"||PINNED_SPECIFIER.test(i):!1}c(isGeneratedNpx,"isGeneratedNpx"),a(isGeneratedNpx,"isGeneratedNpx");function refreshedMcpEntry(e,r){if(!isGeneratedMcpEntry(e))return;const s=(0,lens_store_1.storeFirstFallback)(e),n=(0,lens_store_1.storeFirstFallback)(r),t=s?{command:"npx",args:s}:e,i=n?{command:"npx",args:n}:r,o=t.args[0]!=="--no"&&t.args[1]==="lensmcp",p=t.args.join(" ")!==i.args.join(" ")&&(i.args[0]==="--no"||o)?i:t,l=s||n?(0,lens_store_1.storeFirstMcpEntry)(p.args):p;return l.command===e.command&&l.args.join("\0")===e.args.join("\0")?void 0:l}c(refreshedMcpEntry,"refreshedMcpEntry"),a(refreshedMcpEntry,"refreshedMcpEntry");function describeMcpEntry(e){const r=(0,lens_store_1.storeFirstFallback)(e);return r?`the store's launcher, else npx ${r.join(" ")}`:e.args.join(" ")}c(describeMcpEntry,"describeMcpEntry"),a(describeMcpEntry,"describeMcpEntry");function registerWorkspaceMcpConfig(e,r){const s=".mcp.json";let n={};if(e.exists(s))try{n=JSON.parse(e.read(s,"utf-8")??"{}")}catch{n={}}(!n||typeof n!="object")&&(n={}),(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});const t=n.mcpServers.lensmcp,i=mcpServerEntry(e.root);if(t){const o=refreshedMcpEntry(t,i);if(!o)return;n.mcpServers.lensmcp=o,e.write(s,JSON.stringify(n,null,2)+`
12
+ `),r.push(`.mcp.json: refreshed the generated lensmcp MCP entry (${describeMcpEntry(t)} \u2192 ${describeMcpEntry(o)})`);return}n.mcpServers.lensmcp=i,e.write(s,JSON.stringify(n,null,2)+`
13
+ `),r.push(`.mcp.json: registered lensmcp MCP server (stdio, ${describeMcpEntry(i)})`)}c(registerWorkspaceMcpConfig,"registerWorkspaceMcpConfig"),a(registerWorkspaceMcpConfig,"registerWorkspaceMcpConfig"),exports.default=initGenerator;function canonicalJson(e){return JSON.stringify(e,(r,s)=>s&&typeof s=="object"&&!Array.isArray(s)?Object.fromEntries(Object.entries(s).sort(([n],[t])=>n<t?-1:n>t?1:0)):s)}c(canonicalJson,"canonicalJson"),a(canonicalJson,"canonicalJson");function mergeDeep(e,r){const s={...e};for(const[n,t]of Object.entries(r))t!==null&&typeof t=="object"&&!Array.isArray(t)&&s[n]!==null&&typeof s[n]=="object"&&!Array.isArray(s[n])?s[n]=mergeDeep(s[n],t):s[n]=t;return s}c(mergeDeep,"mergeDeep"),a(mergeDeep,"mergeDeep");
@@ -102,7 +102,21 @@ export interface StandaloneBridgeOrigins {
102
102
  export declare function clusterPageHosts(decls: readonly ClusterPageDecl[]): string[];
103
103
  /** `existing` (a caller's own allowlist) plus `hosts`, comma-joined and de-duplicated; undefined when both are empty. */
104
104
  export declare function withBridgeAllowedOrigins(existing: string | undefined, hosts: readonly string[]): string | undefined;
105
- /** The `cluster` (or legacy `davnx`) declarations in each project's `project.json`; unreadable ones are skipped. */
106
- export declare function readClusterPageDecls(workspaceRoot: string, projectRoots: readonly string[]): ClusterPageDecl[];
105
+ /** Why `<root>/lensmcp.json` cannot be read, when it is there and is not a JSON object (as the no-nx daemon refuses it). */
106
+ export declare function lensmcpJsonProblem(root: string): string | undefined;
107
+ /** The services `<root>/lensmcp.json` declares — read before a project's own `project.json` (lock-step with @lensmcp/cluster runtime/services-decl.ts). */
108
+ export declare function lensmcpServices(root: string): Record<string, unknown>;
109
+ /** A project's declaration: lensmcp.json `services` first (`false` turns it off), then its `cluster`, then `davnx`. */
110
+ export declare function declFor<D>(services: Readonly<Record<string, unknown>>, name: string | undefined, raw: {
111
+ cluster?: D;
112
+ davnx?: D;
113
+ } | undefined): D | undefined;
114
+ /** A project by its root, or by its name and root (the name lensmcp.json `services` keys on; else project.json `name`, else the folder). */
115
+ export type ProjectRef = string | {
116
+ name: string;
117
+ root: string;
118
+ };
119
+ /** Each project's declaration — lensmcp.json `services` first, then its `project.json` `cluster` / `davnx`; unreadable ones are skipped. */
120
+ export declare function readClusterPageDecls(workspaceRoot: string, projects: readonly ProjectRef[]): ClusterPageDecl[];
107
121
  /** What a standalone bridge started for this workspace should admit, given the caller's environment. */
108
- export declare function standaloneBridgeOrigins(workspaceRoot: string, projectRoots: readonly string[], env?: NodeJS.ProcessEnv): StandaloneBridgeOrigins;
122
+ export declare function standaloneBridgeOrigins(workspaceRoot: string, projectRoots: readonly ProjectRef[], env?: NodeJS.ProcessEnv): StandaloneBridgeOrigins;
package/lens-frontend.js CHANGED
@@ -1 +1 @@
1
- "use strict";var h=Object.defineProperty;var r=(e,n)=>h(e,"name",{value:n,configurable:!0});var m=Object.defineProperty,o=r((e,n)=>m(e,"name",{value:n,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.spawnLensFrontend=spawnLensFrontend,exports.locateBin=locateBin,exports.resolveFirstExisting=resolveFirstExisting,exports.globalNodeModules=globalNodeModules,exports.findMcpBundle=findMcpBundle,exports.findDashboardBundle=findDashboardBundle,exports.findCaptureRunner=findCaptureRunner,exports.findBridgeBundle=findBridgeBundle,exports.clusterPageHosts=clusterPageHosts,exports.withBridgeAllowedOrigins=withBridgeAllowedOrigins,exports.readClusterPageDecls=readClusterPageDecls,exports.standaloneBridgeOrigins=standaloneBridgeOrigins;const node_child_process_1=require("node:child_process"),node_fs_1=require("node:fs"),node_path_1=require("node:path");function spawnLensFrontend(e,n){const t=e.log??(u=>console.log(u)),{projectRoot:s,workspaceRoot:i,eventFile:c}=e,a=e.chrome!==!1,v=e.headless!==!1,p=e.viteBin??locateBin("vite",[s,i]);if(!p)throw new Error("[lens] Could not find the vite binary in node_modules/.bin.");const d=e.port??(a?5173:void 0),f=["--config",resolveFirstExisting(["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs","vite.config.cts","vite.config.cjs"],s)??(0,node_path_1.join)(s,"vite.config.ts"),s];d!==void 0&&f.push("--port",String(d),"--strictPort");const g={LENSMCP_EVENT_FILE:c,...e.project?{LENSMCP_APP:e.project}:{},...e.viteEnv??{}},j=e.labelPrefix??"";t(`[lens] starting Vite for ${e.project??s}${d?` on :${d}`:""}`);const b=n(`${j}vite`,p,f,g),l=e.openUrl??(d?`http://localhost:${d}/`:void 0);if(a){const u=findCaptureRunner(i);u?l?(t(`[lens] starting browser capture \u2192 ${l}`),n(`${j}browser-capture`,process.execPath,[u],{...g,LENSMCP_DEV_URL:l,LENSMCP_TOKENS_FILE:(0,node_path_1.join)(i,"lensmcp.tokens.json"),LENSMCP_RULES_FILE:(0,node_path_1.join)(i,"lensmcp.rules.json"),LENSMCP_HEADLESS:v===!1?"false":"true"},!0,{delayMs:1e4,max:5})):t("[lens] no dev URL/port resolved \u2014 skipping live capture."):t("[lens] browser-capture runner not found \u2014 skipping live capture. Install the self-contained CLI: `npm i -D lensmcp` (it ships `bundled/capture-runner.js`).")}return{...d!==void 0?{devPort:d}:{},...l?{devUrl:l}:{},vite:b}}r(spawnLensFrontend,"spawnLensFrontend"),o(spawnLensFrontend,"spawnLensFrontend");function locateBin(e,n){for(const t of n){const s=(0,node_path_1.join)(t,"node_modules",".bin",e);if((0,node_fs_1.existsSync)(s))return s}}r(locateBin,"locateBin"),o(locateBin,"locateBin");function resolveFirstExisting(e,n){for(const t of e){const s=(0,node_path_1.join)(n,t);if((0,node_fs_1.existsSync)(s))return s}}r(resolveFirstExisting,"resolveFirstExisting"),o(resolveFirstExisting,"resolveFirstExisting");let cachedGlobalRoot;function globalNodeModules(){if(cachedGlobalRoot!==void 0)return cachedGlobalRoot??void 0;const e=(0,node_path_1.resolve)((0,node_path_1.dirname)(process.execPath),"..","lib","node_modules");if((0,node_fs_1.existsSync)(e))return cachedGlobalRoot=e,e;try{const n=(0,node_child_process_1.execSync)("npm root -g",{encoding:"utf8",timeout:5e3}).trim();cachedGlobalRoot=n&&(0,node_fs_1.existsSync)(n)?n:null}catch{cachedGlobalRoot=null}return cachedGlobalRoot??void 0}r(globalNodeModules,"globalNodeModules"),o(globalNodeModules,"globalNodeModules");function findMcpBundle(e){const n=globalNodeModules();return firstExisting([(0,node_path_1.join)(e,"node_modules","lensmcp","bundled","main.js"),...n?[(0,node_path_1.join)(n,"lensmcp","bundled","main.js")]:[],(0,node_path_1.join)(e,"servers","lensmcp-mcp","dist","main.js")])}r(findMcpBundle,"findMcpBundle"),o(findMcpBundle,"findMcpBundle");function findDashboardBundle(e){const n=globalNodeModules();return firstExisting([(0,node_path_1.join)(e,"node_modules","lensmcp","bundled","dashboard.js"),...n?[(0,node_path_1.join)(n,"lensmcp","bundled","dashboard.js")]:[],(0,node_path_1.join)(e,"servers","lensmcp-mcp","dist","dashboard.js")])}r(findDashboardBundle,"findDashboardBundle"),o(findDashboardBundle,"findDashboardBundle");function findCaptureRunner(e){const n=globalNodeModules();return firstExisting([(0,node_path_1.join)(e,"node_modules","lensmcp","bundled","capture-runner.js"),...n?[(0,node_path_1.join)(n,"lensmcp","bundled","capture-runner.js")]:[],(0,node_path_1.join)(e,"libs","browser-capture","dist","capture-runner.js")])}r(findCaptureRunner,"findCaptureRunner"),o(findCaptureRunner,"findCaptureRunner");function findBridgeBundle(e){const n=globalNodeModules();return firstExisting([(0,node_path_1.join)(e,"node_modules","lensmcp","bundled","bridge.js"),...n?[(0,node_path_1.join)(n,"lensmcp","bundled","bridge.js")]:[],(0,node_path_1.join)(e,"libs","bridge","dist","main.js")])}r(findBridgeBundle,"findBridgeBundle"),o(findBridgeBundle,"findBridgeBundle");function firstExisting(e){for(const n of e)if((0,node_fs_1.existsSync)(n))return n}r(firstExisting,"firstExisting"),o(firstExisting,"firstExisting");function clusterPageHosts(e){const n=new Set;for(const t of e){if(t.service||typeof t.host!="string")continue;const s=t.host.trim().toLowerCase();s&&n.add(s.startsWith("*.")?s.slice(1):s)}return[...n]}r(clusterPageHosts,"clusterPageHosts"),o(clusterPageHosts,"clusterPageHosts");function withBridgeAllowedOrigins(e,n){const t=[...new Set([...(e??"").split(/[\s,]+/).filter(Boolean),...n])];return t.length>0?t.join(","):void 0}r(withBridgeAllowedOrigins,"withBridgeAllowedOrigins"),o(withBridgeAllowedOrigins,"withBridgeAllowedOrigins");function readClusterPageDecls(e,n){const t=[];for(const s of n)try{const i=JSON.parse((0,node_fs_1.readFileSync)((0,node_path_1.join)(e,s,"project.json"),"utf8")),c=i.cluster??i.davnx;c&&typeof c=="object"&&t.push(c)}catch{}return t}r(readClusterPageDecls,"readClusterPageDecls"),o(readClusterPageDecls,"readClusterPageDecls");function standaloneBridgeOrigins(e,n,t=process.env){const s=clusterPageHosts(readClusterPageDecls(e,n)),i=withBridgeAllowedOrigins(t.LENSMCP_BRIDGE_ALLOWED_ORIGINS,s);return i?{hosts:s,allowedOrigins:i}:{hosts:s}}r(standaloneBridgeOrigins,"standaloneBridgeOrigins"),o(standaloneBridgeOrigins,"standaloneBridgeOrigins");
1
+ "use strict";var h=Object.defineProperty;var r=(e,n)=>h(e,"name",{value:n,configurable:!0});var b=Object.defineProperty,s=r((e,n)=>b(e,"name",{value:n,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.spawnLensFrontend=spawnLensFrontend,exports.locateBin=locateBin,exports.resolveFirstExisting=resolveFirstExisting,exports.globalNodeModules=globalNodeModules,exports.findMcpBundle=findMcpBundle,exports.findDashboardBundle=findDashboardBundle,exports.findCaptureRunner=findCaptureRunner,exports.findBridgeBundle=findBridgeBundle,exports.clusterPageHosts=clusterPageHosts,exports.withBridgeAllowedOrigins=withBridgeAllowedOrigins,exports.lensmcpJsonProblem=lensmcpJsonProblem,exports.lensmcpServices=lensmcpServices,exports.declFor=declFor,exports.readClusterPageDecls=readClusterPageDecls,exports.standaloneBridgeOrigins=standaloneBridgeOrigins;const node_child_process_1=require("node:child_process"),node_fs_1=require("node:fs"),node_path_1=require("node:path"),lens_store_1=require("./lens-store");function spawnLensFrontend(e,n){const o=e.log??(p=>console.log(p)),{projectRoot:t,workspaceRoot:i,eventFile:a}=e,c=e.chrome!==!1,f=e.headless!==!1,d=e.viteBin??locateBin("vite",[t,i]);if(!d)throw new Error("[lens] Could not find the vite binary in node_modules/.bin.");const l=e.port??(c?5173:void 0),g=["--config",resolveFirstExisting(["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs","vite.config.cts","vite.config.cjs"],t)??(0,node_path_1.join)(t,"vite.config.ts"),t];l!==void 0&&g.push("--port",String(l),"--strictPort");const m={LENSMCP_EVENT_FILE:a,...e.project?{LENSMCP_APP:e.project}:{},...e.viteEnv??{}},j=e.labelPrefix??"";o(`[lens] starting Vite for ${e.project??t}${l?` on :${l}`:""}`);const v=n(`${j}vite`,d,g,m),u=e.openUrl??(l?`http://localhost:${l}/`:void 0);if(c){const p=findCaptureRunner(i);p?u?(o(`[lens] starting browser capture \u2192 ${u}`),n(`${j}browser-capture`,process.execPath,[p],{...m,LENSMCP_DEV_URL:u,LENSMCP_TOKENS_FILE:(0,node_path_1.join)(i,"lensmcp.tokens.json"),LENSMCP_RULES_FILE:(0,node_path_1.join)(i,"lensmcp.rules.json"),LENSMCP_HEADLESS:f===!1?"false":"true"},!0,{delayMs:1e4,max:5})):o("[lens] no dev URL/port resolved \u2014 skipping live capture."):o("[lens] browser-capture runner not found \u2014 skipping live capture. Install the self-contained CLI: `npm i -D lensmcp` (it ships `bundled/capture-runner.js`).")}return{...l!==void 0?{devPort:l}:{},...u?{devUrl:u}:{},vite:v}}r(spawnLensFrontend,"spawnLensFrontend"),s(spawnLensFrontend,"spawnLensFrontend");function locateBin(e,n){for(const o of n){const t=(0,node_path_1.join)(o,"node_modules",".bin",e);if((0,node_fs_1.existsSync)(t))return t}}r(locateBin,"locateBin"),s(locateBin,"locateBin");function resolveFirstExisting(e,n){for(const o of e){const t=(0,node_path_1.join)(n,o);if((0,node_fs_1.existsSync)(t))return t}}r(resolveFirstExisting,"resolveFirstExisting"),s(resolveFirstExisting,"resolveFirstExisting");let cachedGlobalRoot;function globalNodeModules(){if(cachedGlobalRoot!==void 0)return cachedGlobalRoot??void 0;const e=(0,node_path_1.resolve)((0,node_path_1.dirname)(process.execPath),"..","lib","node_modules");if((0,node_fs_1.existsSync)(e))return cachedGlobalRoot=e,e;try{const n=(0,node_child_process_1.execSync)("npm root -g",{encoding:"utf8",timeout:5e3}).trim();cachedGlobalRoot=n&&(0,node_fs_1.existsSync)(n)?n:null}catch{cachedGlobalRoot=null}return cachedGlobalRoot??void 0}r(globalNodeModules,"globalNodeModules"),s(globalNodeModules,"globalNodeModules");function lensmcpPackages(e){return(0,lens_store_1.storeFirst)((0,node_path_1.join)(e,"node_modules","lensmcp"))}r(lensmcpPackages,"lensmcpPackages"),s(lensmcpPackages,"lensmcpPackages");function findMcpBundle(e){const n=globalNodeModules();return firstExisting([...lensmcpPackages(e).map(o=>(0,node_path_1.join)(o,"bundled","main.js")),...n?[(0,node_path_1.join)(n,"lensmcp","bundled","main.js")]:[],(0,node_path_1.join)(e,"servers","lensmcp-mcp","dist","main.js")])}r(findMcpBundle,"findMcpBundle"),s(findMcpBundle,"findMcpBundle");function findDashboardBundle(e){const n=globalNodeModules();return firstExisting([...lensmcpPackages(e).map(o=>(0,node_path_1.join)(o,"bundled","dashboard.js")),...n?[(0,node_path_1.join)(n,"lensmcp","bundled","dashboard.js")]:[],(0,node_path_1.join)(e,"servers","lensmcp-mcp","dist","dashboard.js")])}r(findDashboardBundle,"findDashboardBundle"),s(findDashboardBundle,"findDashboardBundle");function findCaptureRunner(e){const n=globalNodeModules();return firstExisting([...lensmcpPackages(e).map(o=>(0,node_path_1.join)(o,"bundled","capture-runner.js")),...n?[(0,node_path_1.join)(n,"lensmcp","bundled","capture-runner.js")]:[],(0,node_path_1.join)(e,"libs","browser-capture","dist","capture-runner.js")])}r(findCaptureRunner,"findCaptureRunner"),s(findCaptureRunner,"findCaptureRunner");function findBridgeBundle(e){const n=globalNodeModules();return firstExisting([...lensmcpPackages(e).map(o=>(0,node_path_1.join)(o,"bundled","bridge.js")),...n?[(0,node_path_1.join)(n,"lensmcp","bundled","bridge.js")]:[],(0,node_path_1.join)(e,"libs","bridge","dist","main.js")])}r(findBridgeBundle,"findBridgeBundle"),s(findBridgeBundle,"findBridgeBundle");function firstExisting(e){for(const n of e)if((0,node_fs_1.existsSync)(n))return n}r(firstExisting,"firstExisting"),s(firstExisting,"firstExisting");function clusterPageHosts(e){const n=new Set;for(const o of e){if(o.service||typeof o.host!="string")continue;const t=o.host.trim().toLowerCase();t&&n.add(t.startsWith("*.")?t.slice(1):t)}return[...n]}r(clusterPageHosts,"clusterPageHosts"),s(clusterPageHosts,"clusterPageHosts");function withBridgeAllowedOrigins(e,n){const o=[...new Set([...(e??"").split(/[\s,]+/).filter(Boolean),...n])];return o.length>0?o.join(","):void 0}r(withBridgeAllowedOrigins,"withBridgeAllowedOrigins"),s(withBridgeAllowedOrigins,"withBridgeAllowedOrigins");function lensmcpJsonProblem(e){const n=(0,node_path_1.join)(e,"lensmcp.json");let o;try{o=(0,node_fs_1.readFileSync)(n,"utf8")}catch{return}try{const t=JSON.parse(o);return t&&typeof t=="object"&&!Array.isArray(t)?void 0:`${n} is not a JSON object \u2014 fix it, or remove it`}catch(t){return`${n} is not valid JSON (${t instanceof Error?t.message:String(t)}) \u2014 fix it, or remove it`}}r(lensmcpJsonProblem,"lensmcpJsonProblem"),s(lensmcpJsonProblem,"lensmcpJsonProblem");function lensmcpServices(e){try{const n=JSON.parse((0,node_fs_1.readFileSync)((0,node_path_1.join)(e,"lensmcp.json"),"utf8")).services;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}r(lensmcpServices,"lensmcpServices"),s(lensmcpServices,"lensmcpServices");function declFor(e,n,o){const t=n===void 0?void 0:e[n];if(t!==!1)return t&&typeof t=="object"&&!Array.isArray(t)?t:o?.cluster??o?.davnx}r(declFor,"declFor"),s(declFor,"declFor");function readClusterPageDecls(e,n){const o=lensmcpServices(e),t=[];for(const i of n){const a=typeof i=="string"?i:i.root;let c;try{c=JSON.parse((0,node_fs_1.readFileSync)((0,node_path_1.join)(e,a,"project.json"),"utf8"))}catch{c=void 0}const f=typeof i=="string"?typeof c?.name=="string"&&c.name?c.name:(0,node_path_1.basename)((0,node_path_1.resolve)(e,a)):i.name,d=declFor(o,f,c);d&&typeof d=="object"&&t.push(d)}return t}r(readClusterPageDecls,"readClusterPageDecls"),s(readClusterPageDecls,"readClusterPageDecls");function standaloneBridgeOrigins(e,n,o=process.env){const t=clusterPageHosts(readClusterPageDecls(e,n)),i=withBridgeAllowedOrigins(o.LENSMCP_BRIDGE_ALLOWED_ORIGINS,t);return i?{hosts:t,allowedOrigins:i}:{hosts:t}}r(standaloneBridgeOrigins,"standaloneBridgeOrigins"),s(standaloneBridgeOrigins,"standaloneBridgeOrigins");
@@ -0,0 +1,37 @@
1
+ export interface StoredLensmcp {
2
+ home: string;
3
+ version: string;
4
+ dir: string;
5
+ pkg: string;
6
+ cli: string;
7
+ launcher: string;
8
+ }
9
+ export declare const lensStoreHome: (env?: NodeJS.ProcessEnv) => string;
10
+ export declare function storedLensmcp(home: string, version: string): StoredLensmcp | undefined;
11
+ export declare function storeCurrent(env?: NodeJS.ProcessEnv): StoredLensmcp | undefined;
12
+ export declare function inLensStore(path: string, env?: NodeJS.ProcessEnv): boolean;
13
+ /** The stored version a path lies in (as named, or as it really is through `current`), when it is a whole one. */
14
+ export declare function storeVersionOf(path: string, env?: NodeJS.ProcessEnv): StoredLensmcp | undefined;
15
+ /**
16
+ * The stored lensmcp a process hands out: a process that runs from the store keeps its own version until it restarts
17
+ * (owner, 2026-11-10); only one that runs from elsewhere takes the store's current version.
18
+ */
19
+ export declare function storeOwnOrCurrent(entry?: string | undefined, env?: NodeJS.ProcessEnv): StoredLensmcp | undefined;
20
+ /** The published packages installed beside lensmcp in every version folder (libs/cli store.ts OPTIONAL_PACKAGES). */
21
+ export declare const LENS_OPTIONAL_PACKAGES: readonly string[];
22
+ /** The optional packages a version folder holds. */
23
+ export declare function storedOptionalNames(home: string, version: string): string[];
24
+ /** Semver order, a pre-release before its release and `rc.9` before `rc.10` (libs/cli store.ts compareVersions). */
25
+ export declare function compareLensVersions(a: string, b: string): number;
26
+ /** Every whole version the store holds, oldest first. */
27
+ export declare function storedVersionNames(home: string): string[];
28
+ /** The versions forwarded lensmcp processes run (`versions/.running/<pid>`, libs/cli store.ts markForwarded), by pid; gone pids are left out. */
29
+ export declare function storeForwardedRunning(home: string): Map<string, number[]>;
30
+ export declare function linkedCheckout(pkg: string): boolean;
31
+ export declare function storeFirst(project: string | undefined, env?: NodeJS.ProcessEnv, entry?: string | undefined): string[];
32
+ export declare const STORE_FIRST_MCP = "h=\"${LENSMCP_HOME:-$HOME/.lensmcp}\"; [ \"${LENSMCP_NO_STORE:-}\" != 1 ] && [ -x \"$h/bin/lensmcp\" ] && [ -f \"$h/current/node_modules/lensmcp/bin.js\" ] && exec \"$h/bin/lensmcp\" mcp; exec npx ";
33
+ export declare function storeFirstMcpEntry(fallback: readonly string[]): {
34
+ command: string;
35
+ args: string[];
36
+ };
37
+ export declare function storeFirstFallback(entry: unknown): string[] | undefined;
package/lens-store.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var S=Object.defineProperty;var i=(e,r)=>S(e,"name",{value:r,configurable:!0});var a=Object.defineProperty,s=i((e,r)=>a(e,"name",{value:r,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.STORE_FIRST_MCP=exports.LENS_OPTIONAL_PACKAGES=exports.lensStoreHome=void 0,exports.storedLensmcp=storedLensmcp,exports.storeCurrent=storeCurrent,exports.inLensStore=inLensStore,exports.storeVersionOf=storeVersionOf,exports.storeOwnOrCurrent=storeOwnOrCurrent,exports.storedOptionalNames=storedOptionalNames,exports.compareLensVersions=compareLensVersions,exports.storedVersionNames=storedVersionNames,exports.storeForwardedRunning=storeForwardedRunning,exports.linkedCheckout=linkedCheckout,exports.storeFirst=storeFirst,exports.storeFirstMcpEntry=storeFirstMcpEntry,exports.storeFirstFallback=storeFirstFallback;const node_fs_1=require("node:fs"),node_os_1=require("node:os"),node_path_1=require("node:path"),lensStoreHome=s((e=process.env)=>e.LENSMCP_HOME||(0,node_path_1.join)((0,node_os_1.homedir)(),".lensmcp"),"lensStoreHome");exports.lensStoreHome=lensStoreHome;const realOr=s(e=>{try{return(0,node_fs_1.realpathSync)(e)}catch{return e}},"realOr");function storedLensmcp(e,r){const t=(0,node_path_1.join)(e,"versions",r),n=(0,node_path_1.join)(t,"node_modules","lensmcp"),o=(0,node_path_1.join)(n,"bin.js");if((0,node_fs_1.existsSync)(o)){try{if(JSON.parse((0,node_fs_1.readFileSync)((0,node_path_1.join)(n,"package.json"),"utf8")).version!==r)return}catch{return}return{home:e,version:r,dir:t,pkg:n,cli:o,launcher:(0,node_path_1.join)(e,"bin","lensmcp")}}}i(storedLensmcp,"storedLensmcp"),s(storedLensmcp,"storedLensmcp");function storeCurrent(e=process.env){if(e.LENSMCP_NO_STORE==="1")return;const r=(0,exports.lensStoreHome)(e);let t;try{t=(0,node_path_1.basename)((0,node_fs_1.readlinkSync)((0,node_path_1.join)(r,"current")))}catch{return}return storedLensmcp(r,t)}i(storeCurrent,"storeCurrent"),s(storeCurrent,"storeCurrent");function inLensStore(e,r=process.env){const t=(0,node_path_1.join)((0,exports.lensStoreHome)(r),"versions");return e.startsWith(t+node_path_1.sep)||realOr(e).startsWith(realOr(t)+node_path_1.sep)}i(inLensStore,"inLensStore"),s(inLensStore,"inLensStore");const VERSION=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;function storeVersionOf(e,r=process.env){const t=(0,exports.lensStoreHome)(r),n=(0,node_path_1.join)(t,"versions");for(const[o,p]of[[e,n],[realOr(e),realOr(n)]]){if(!o.startsWith(p+node_path_1.sep))continue;const l=o.slice(p.length+1).split(node_path_1.sep,1)[0]??"";if(VERSION.test(l))return storedLensmcp(t,l)}}i(storeVersionOf,"storeVersionOf"),s(storeVersionOf,"storeVersionOf");function storeOwnOrCurrent(e=process.argv[1],r=process.env){if(r.LENSMCP_NO_STORE!=="1")return e&&inLensStore(e,r)?storeVersionOf(e,r):storeCurrent(r)}i(storeOwnOrCurrent,"storeOwnOrCurrent"),s(storeOwnOrCurrent,"storeOwnOrCurrent"),exports.LENS_OPTIONAL_PACKAGES=["@lensmcp/terminals","@lensmcp/vite-plugin","@lensmcp/bridge","@lensmcp/client-runtime","@lensmcp/react-instrumentation","@lensmcp/valtio-instrumentation"];function storedOptionalNames(e,r){return exports.LENS_OPTIONAL_PACKAGES.filter(t=>(0,node_fs_1.existsSync)((0,node_path_1.join)(e,"versions",r,"node_modules",t,"package.json")))}i(storedOptionalNames,"storedOptionalNames"),s(storedOptionalNames,"storedOptionalNames");function compareLensVersions(e,r){const t=s(c=>{const u=c.indexOf("-");return{nums:(u<0?c:c.slice(0,u)).split(".").map(d=>Number(d)||0),pre:u<0?void 0:c.slice(u+1)}},"parse"),n=t(e),o=t(r);for(let c=0;c<3;c++){const u=(n.nums[c]??0)-(o.nums[c]??0);if(u)return u<0?-1:1}if(n.pre===o.pre)return 0;if(n.pre===void 0)return 1;if(o.pre===void 0)return-1;const p=n.pre.split("."),l=o.pre.split(".");for(let c=0;c<Math.max(p.length,l.length);c++){const u=p[c],d=l[c];if(u===void 0)return-1;if(d===void 0)return 1;if(u===d)continue;const m=/^\d+$/.test(u),f=/^\d+$/.test(d);return m&&f?Number(u)<Number(d)?-1:1:m!==f?m?-1:1:u<d?-1:1}return 0}i(compareLensVersions,"compareLensVersions"),s(compareLensVersions,"compareLensVersions");function storedVersionNames(e){let r;try{r=(0,node_fs_1.readdirSync)((0,node_path_1.join)(e,"versions"))}catch{return[]}return r.filter(t=>VERSION.test(t)&&storedLensmcp(e,t)!==void 0).sort(compareLensVersions)}i(storedVersionNames,"storedVersionNames"),s(storedVersionNames,"storedVersionNames");const pidAlive=s(e=>{try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}},"pidAlive");function storeForwardedRunning(e){const r=new Map,t=(0,node_path_1.join)(e,"versions",".running");let n;try{n=(0,node_fs_1.readdirSync)(t)}catch{return r}for(const o of n){const p=Number(o);if(!Number.isInteger(p)||p<=0||!pidAlive(p))continue;let l;try{l=(0,node_fs_1.readFileSync)((0,node_path_1.join)(t,o),"utf8").trim()}catch{continue}VERSION.test(l)&&r.set(l,[...r.get(l)??[],p])}return r}i(storeForwardedRunning,"storeForwardedRunning"),s(storeForwardedRunning,"storeForwardedRunning");function linkedCheckout(e){if(!(0,node_fs_1.existsSync)((0,node_path_1.join)(e,"package.json")))return!1;const r=realOr(e).split(node_path_1.sep);return r[r.length-1]!=="lensmcp"||r[r.length-2]!=="node_modules"}i(linkedCheckout,"linkedCheckout"),s(linkedCheckout,"linkedCheckout");function storeFirst(e,r=process.env,t=process.argv[1]){const n=storeOwnOrCurrent(t,r);return!n||e&&linkedCheckout(e)?e?[e]:[]:e?[n.pkg,e]:[n.pkg]}i(storeFirst,"storeFirst"),s(storeFirst,"storeFirst"),exports.STORE_FIRST_MCP='h="${LENSMCP_HOME:-$HOME/.lensmcp}"; [ "${LENSMCP_NO_STORE:-}" != 1 ] && [ -x "$h/bin/lensmcp" ] && [ -f "$h/current/node_modules/lensmcp/bin.js" ] && exec "$h/bin/lensmcp" mcp; exec npx ';function storeFirstMcpEntry(e){return{command:"sh",args:["-c",`${exports.STORE_FIRST_MCP}${e.join(" ")}`]}}i(storeFirstMcpEntry,"storeFirstMcpEntry"),s(storeFirstMcpEntry,"storeFirstMcpEntry");function storeFirstFallback(e){if(!e||typeof e!="object"||Array.isArray(e))return;const{command:r,args:t,...n}=e;if(r!=="sh"||Object.keys(n).length>0||!Array.isArray(t)||t.length!==2||t[0]!=="-c")return;const o=t[1];if(typeof o!="string"||!o.startsWith(exports.STORE_FIRST_MCP))return;const p=o.slice(exports.STORE_FIRST_MCP.length).split(" ");return p.every(l=>/^[\w@.-]+$/.test(l))?p:void 0}i(storeFirstFallback,"storeFirstFallback"),s(storeFirstFallback,"storeFirstFallback");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lensmcp/nx-plugin",
3
- "version": "1.25.78",
3
+ "version": "1.26.0",
4
4
  "main": "./index.js",
5
5
  "module": "./index.js",
6
6
  "types": "./index.d.ts",