@lensmcp/core 1.26.0 → 1.26.1

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 +1 @@
1
- "use strict";var I=Object.defineProperty;var l=(o,n)=>I(o,"name",{value:n,configurable:!0});var y=Object.defineProperty,p=l((o,n)=>y(o,"name",{value:n,configurable:!0}),"l"),b=Object.defineProperty,m=p((o,n)=>b(o,"name",{value:n,configurable:!0}),"l");function f(o){const n=o.raw??null,s=n?.kind,d=o.context,a={id:o.id,parentTraceNodeId:d.causedByNodeId??d.originNodeId,lifecycle:"completed",context:d,startTime:o.timestamp,attributes:{...n??{}}};if(o.source==="react"&&s==="render"){const e=n;return{parentAxis:"render",node:{...a,type:"render",logicalId:e.render?.componentLogicalId,instanceId:e.render?.componentInstanceId,name:`render ${e.render?.componentName??"?"}`,durationMs:e.render?.actualDurationMs}}}if(o.source==="valtio"&&s==="state-update"){const e=n;return{parentAxis:"state",node:{...a,type:"state-update",logicalId:e.update?.storeId,name:`${e.update?.storeId??"?"}.${e.update?.path??"?"}`}}}if(o.source==="nestjs"&&s==="server-request"){const e=n;return{parentAxis:"backend",node:{...a,type:"server-request",name:`${e.request?.method??"?"} ${e.request?.route??"?"}`,durationMs:e.request?.durationMs}}}if(s==="db-query"){const e=n,c=[e.op,e.table].filter(Boolean).join(" ")||(e.name??"query");return{parentAxis:"backend",node:{...a,type:"db-query",logicalId:e.table?`db:${e.op??"query"}:${e.table}`:void 0,name:e.error?`${c} (failed)`:c,durationMs:e.durationMs}}}if(s==="loop")return{parentAxis:"performance",node:{...a,type:"loop",name:"loop",durationMs:n.loop?.durationMs}};if(s==="flow-origin"&&(o.source==="react"||o.source==="client-runtime")){const e=d.originNodeId??(typeof n?.originNodeId=="string"?n.originNodeId:void 0);return{parentAxis:"caused",node:{...a,parentTraceNodeId:d.causedByNodeId,type:"ui-event",logicalId:e,name:e?`${o.title} ${e}`:o.title}}}if(o.source==="client-runtime"&&s==="user-action"){const e=n;return{parentAxis:"caused",node:{...a,type:"ui-event",logicalId:e.origin?.nodeId,name:e.origin?.label??o.title}}}}l(f,"m"),p(f,"m"),m(f,"eventToNode");export function buildGraphFromEvents(o,n){const s=[...n].sort((r,t)=>r.timestamp-t.timestamp),d=[];for(const r of s){const t=f(r);t&&(o.addNode(t.node),d.push(t))}let a=0;const e=m((r,t,i,u)=>{const g={id:`${i}:${r}->${t}`,from:r,to:t,axis:i,type:u,timestamp:o.getNode(t)?.startTime??0};o.addEdge(g),a++},"addEdge");for(const r of d){const t=r.node.context.causedByNodeId;t&&o.getNode(t)&&e(t,r.node.id,r.parentAxis??"caused","caused-by")}const c=new Map;for(const r of d){const t=r.node.context.flowId;if(!t)continue;let i=c.get(t);i||(i=[],c.set(t,i)),i.push(r)}for(const r of c.values())for(let t=1;t<r.length;t++){const i=r[t-1].node,u=r[t].node;u.context.causedByNodeId!==i.id&&e(i.id,u.id,"caused","flow-sequence")}return{nodeCount:d.length,edgeCount:a}}l(buildGraphFromEvents,"buildGraphFromEvents"),p(buildGraphFromEvents,"buildGraphFromEvents"),m(buildGraphFromEvents,"buildGraphFromEvents");
1
+ "use strict";var g=Object.defineProperty;var l=(t,r)=>g(t,"name",{value:r,configurable:!0});var I=Object.defineProperty,p=l((t,r)=>I(t,"name",{value:r,configurable:!0}),"l");function m(t){const r=t.raw??null,s=r?.kind,d=t.context,a={id:t.id,parentTraceNodeId:d.causedByNodeId??d.originNodeId,lifecycle:"completed",context:d,startTime:t.timestamp,attributes:{...r??{}}};if(t.source==="react"&&s==="render"){const e=r;return{parentAxis:"render",node:{...a,type:"render",logicalId:e.render?.componentLogicalId,instanceId:e.render?.componentInstanceId,name:`render ${e.render?.componentName??"?"}`,durationMs:e.render?.actualDurationMs}}}if(t.source==="valtio"&&s==="state-update"){const e=r;return{parentAxis:"state",node:{...a,type:"state-update",logicalId:e.update?.storeId,name:`${e.update?.storeId??"?"}.${e.update?.path??"?"}`}}}if(t.source==="nestjs"&&s==="server-request"){const e=r;return{parentAxis:"backend",node:{...a,type:"server-request",name:`${e.request?.method??"?"} ${e.request?.route??"?"}`,durationMs:e.request?.durationMs}}}if(s==="db-query"){const e=r,c=[e.op,e.table].filter(Boolean).join(" ")||(e.name??"query");return{parentAxis:"backend",node:{...a,type:"db-query",logicalId:e.table?`db:${e.op??"query"}:${e.table}`:void 0,name:e.error?`${c} (failed)`:c,durationMs:e.durationMs}}}if(s==="loop")return{parentAxis:"performance",node:{...a,type:"loop",name:"loop",durationMs:r.loop?.durationMs}};if(s==="flow-origin"&&(t.source==="react"||t.source==="client-runtime")){const e=d.originNodeId??(typeof r?.originNodeId=="string"?r.originNodeId:void 0);return{parentAxis:"caused",node:{...a,parentTraceNodeId:d.causedByNodeId,type:"ui-event",logicalId:e,name:e?`${t.title} ${e}`:t.title}}}if(t.source==="client-runtime"&&s==="user-action"){const e=r;return{parentAxis:"caused",node:{...a,type:"ui-event",logicalId:e.origin?.nodeId,name:e.origin?.label??t.title}}}}l(m,"m"),p(m,"eventToNode");export function buildGraphFromEvents(t,r){const s=[...r].sort((o,n)=>o.timestamp-n.timestamp),d=[];for(const o of s){const n=m(o);n&&(t.addNode(n.node),d.push(n))}let a=0;const e=p((o,n,i,u)=>{const f={id:`${i}:${o}->${n}`,from:o,to:n,axis:i,type:u,timestamp:t.getNode(n)?.startTime??0};t.addEdge(f),a++},"addEdge");for(const o of d){const n=o.node.context.causedByNodeId;n&&t.getNode(n)&&e(n,o.node.id,o.parentAxis??"caused","caused-by")}const c=new Map;for(const o of d){const n=o.node.context.flowId;if(!n)continue;let i=c.get(n);i||(i=[],c.set(n,i)),i.push(o)}for(const o of c.values())for(let n=1;n<o.length;n++){const i=o[n-1].node,u=o[n].node;u.context.causedByNodeId!==i.id&&e(i.id,u.id,"caused","flow-sequence")}return{nodeCount:d.length,edgeCount:a}}l(buildGraphFromEvents,"buildGraphFromEvents"),p(buildGraphFromEvents,"buildGraphFromEvents");
@@ -1 +1 @@
1
- "use strict";var w=Object.defineProperty;var l=(d,t)=>w(d,"name",{value:t,configurable:!0});var I=Object.defineProperty,y=l((d,t)=>I(d,"name",{value:t,configurable:!0}),"l"),b=Object.defineProperty,m=y((d,t)=>b(d,"name",{value:t,configurable:!0}),"l");const B=4,M=1e3;export class GraphStore{static{l(this,"GraphStore")}static{y(this,"GraphStore")}static{m(this,"GraphStore")}constructor(){this.nodes=new Map,this.edges=new Map,this.byParent=new Map,this.byFlow=new Map,this.byLogical=new Map,this.byInstance=new Map,this.byRequest=new Map,this.outByAxis=new Map,this.inByAxis=new Map}addNode(t){this.nodes.set(t.id,t),t.parentTraceNodeId&&this.addToIndex(this.byParent,t.parentTraceNodeId,t.id),t.context.flowId&&this.addToIndex(this.byFlow,t.context.flowId,t.id),t.logicalId&&this.addToIndex(this.byLogical,t.logicalId,t.id),t.instanceId&&this.addToIndex(this.byInstance,t.instanceId,t.id),t.context.requestId&&this.addToIndex(this.byRequest,t.context.requestId,t.id)}updateNode(t,e){const i=this.nodes.get(t);if(!i)throw new Error(`Unknown node: ${t}`);const s={...i,...e,id:i.id};return this.nodes.set(t,s),s}getNode(t){return this.nodes.get(t)}addEdge(t){this.edges.set(t.id,t);let e=this.outByAxis.get(t.axis);e||(e=new Map,this.outByAxis.set(t.axis,e)),this.addToIndex(e,t.from,t.id);let i=this.inByAxis.get(t.axis);i||(i=new Map,this.inByAxis.set(t.axis,i)),this.addToIndex(i,t.to,t.id)}getEdge(t){return this.edges.get(t)}childrenOf(t){return this.materialiseNodes(this.byParent.get(t))}nodesInFlow(t){return this.materialiseNodes(this.byFlow.get(t))}nodesByLogical(t){return this.materialiseNodes(this.byLogical.get(t))}nodesByInstance(t){return this.materialiseNodes(this.byInstance.get(t))}nodesByRequest(t){return this.materialiseNodes(this.byRequest.get(t))}traverse(t){const e=this.nodes.get(t.from);if(!e)return{nodes:[],edges:[]};const i=Array.isArray(t.lens)?t.lens:[t.lens],s=t.direction??"both",x=t.depth??4,p=t.maxNodes??1e3,o=new Set,g=new Set,c=[{id:e.id,d:0}];for(;c.length&&!(o.size>=p);){const{id:n,d:u}=c.shift();if(!o.has(n)&&(o.add(n),!(u>=x)))for(const f of i){if(s==="out"||s==="both"){const a=this.outByAxis.get(f)?.get(n);if(a)for(const r of a){g.add(r);const h=this.edges.get(r);o.has(h.to)||c.push({id:h.to,d:u+1})}}if(s==="in"||s==="both"){const a=this.inByAxis.get(f)?.get(n);if(a)for(const r of a){g.add(r);const h=this.edges.get(r);o.has(h.from)||c.push({id:h.from,d:u+1})}}}}return{nodes:this.materialiseNodes(o),edges:[...g].map(n=>this.edges.get(n)).filter(n=>!!n)}}nodeCount(){return this.nodes.size}edgeCount(){return this.edges.size}addToIndex(t,e,i){let s=t.get(e);s||(s=new Set,t.set(e,s)),s.add(i)}materialiseNodes(t){if(!t)return[];const e=[];for(const i of t){const s=this.nodes.get(i);s&&e.push(s)}return e}}
1
+ "use strict";var w=Object.defineProperty;var l=(h,e)=>w(h,"name",{value:e,configurable:!0});var p=Object.defineProperty,I=l((h,e)=>p(h,"name",{value:e,configurable:!0}),"l");const m=4,N=1e3;export class GraphStore{static{l(this,"GraphStore")}static{I(this,"GraphStore")}constructor(){this.nodes=new Map,this.edges=new Map,this.byParent=new Map,this.byFlow=new Map,this.byLogical=new Map,this.byInstance=new Map,this.byRequest=new Map,this.outByAxis=new Map,this.inByAxis=new Map}addNode(e){this.nodes.set(e.id,e),e.parentTraceNodeId&&this.addToIndex(this.byParent,e.parentTraceNodeId,e.id),e.context.flowId&&this.addToIndex(this.byFlow,e.context.flowId,e.id),e.logicalId&&this.addToIndex(this.byLogical,e.logicalId,e.id),e.instanceId&&this.addToIndex(this.byInstance,e.instanceId,e.id),e.context.requestId&&this.addToIndex(this.byRequest,e.context.requestId,e.id)}updateNode(e,s){const i=this.nodes.get(e);if(!i)throw new Error(`Unknown node: ${e}`);const t={...i,...s,id:i.id};return this.nodes.set(e,t),t}getNode(e){return this.nodes.get(e)}addEdge(e){this.edges.set(e.id,e);let s=this.outByAxis.get(e.axis);s||(s=new Map,this.outByAxis.set(e.axis,s)),this.addToIndex(s,e.from,e.id);let i=this.inByAxis.get(e.axis);i||(i=new Map,this.inByAxis.set(e.axis,i)),this.addToIndex(i,e.to,e.id)}getEdge(e){return this.edges.get(e)}childrenOf(e){return this.materialiseNodes(this.byParent.get(e))}nodesInFlow(e){return this.materialiseNodes(this.byFlow.get(e))}nodesByLogical(e){return this.materialiseNodes(this.byLogical.get(e))}nodesByInstance(e){return this.materialiseNodes(this.byInstance.get(e))}nodesByRequest(e){return this.materialiseNodes(this.byRequest.get(e))}traverse(e){const s=this.nodes.get(e.from);if(!s)return{nodes:[],edges:[]};const i=Array.isArray(e.lens)?e.lens:[e.lens],t=e.direction??"both",f=e.depth??4,x=e.maxNodes??1e3,n=new Set,g=new Set,c=[{id:s.id,d:0}];for(;c.length&&!(n.size>=x);){const{id:d,d:u}=c.shift();if(!n.has(d)&&(n.add(d),!(u>=f)))for(const y of i){if(t==="out"||t==="both"){const o=this.outByAxis.get(y)?.get(d);if(o)for(const a of o){g.add(a);const r=this.edges.get(a);n.has(r.to)||c.push({id:r.to,d:u+1})}}if(t==="in"||t==="both"){const o=this.inByAxis.get(y)?.get(d);if(o)for(const a of o){g.add(a);const r=this.edges.get(a);n.has(r.from)||c.push({id:r.from,d:u+1})}}}}return{nodes:this.materialiseNodes(n),edges:[...g].map(d=>this.edges.get(d)).filter(d=>!!d)}}nodeCount(){return this.nodes.size}edgeCount(){return this.edges.size}addToIndex(e,s,i){let t=e.get(s);t||(t=new Set,e.set(s,t)),t.add(i)}materialiseNodes(e){if(!e)return[];const s=[];for(const i of e){const t=this.nodes.get(i);t&&s.push(t)}return s}}
@@ -1 +1 @@
1
- "use strict";var l=Object.defineProperty;var t=(e,s)=>l(e,"name",{value:s,configurable:!0});var r=Object.defineProperty,o=t((e,s)=>r(e,"name",{value:s,configurable:!0}),"s"),n=Object.defineProperty,a=o((e,s)=>n(e,"name",{value:s,configurable:!0}),"t");export const HEADLESS_FLOWS_ENV="LENSMCP_HEADLESS_FLOWS";export function headlessFlowsEnabled(e=process.env){return!["0","false","off","no"].includes((e[HEADLESS_FLOWS_ENV]??"").trim().toLowerCase())}t(headlessFlowsEnabled,"headlessFlowsEnabled"),o(headlessFlowsEnabled,"headlessFlowsEnabled"),a(headlessFlowsEnabled,"headlessFlowsEnabled");export const HEADLESS_REQUEST_FLOW_PREFIX="api:",HEADLESS_JOB_FLOW_PREFIX="job:";export function headlessFlowId(e){return`${HEADLESS_REQUEST_FLOW_PREFIX}${e}`}t(headlessFlowId,"headlessFlowId"),o(headlessFlowId,"headlessFlowId"),a(headlessFlowId,"headlessFlowId");export function headlessJobFlowId(e,s){return`${HEADLESS_JOB_FLOW_PREFIX}${e}#${s??"?"}`}t(headlessJobFlowId,"headlessJobFlowId"),o(headlessJobFlowId,"headlessJobFlowId"),a(headlessJobFlowId,"headlessJobFlowId");export function isHeadlessFlowId(e){return e.startsWith(HEADLESS_REQUEST_FLOW_PREFIX)||e.startsWith(HEADLESS_JOB_FLOW_PREFIX)}t(isHeadlessFlowId,"isHeadlessFlowId"),o(isHeadlessFlowId,"isHeadlessFlowId"),a(isHeadlessFlowId,"isHeadlessFlowId");const i=/^\/(?:[^/?#]+\/)*(?:health|healthz|health-check|healthcheck|ready|readyz|readiness|live|livez|liveness|ping|metrics|favicon\.ico)\/?(?:[?#].*)?$/i;export function isProbePath(e){return e?i.test(e)||e.startsWith("/__lensmcp/"):!1}t(isProbePath,"isProbePath"),o(isProbePath,"isProbePath"),a(isProbePath,"isProbePath");
1
+ "use strict";var r=Object.defineProperty;var s=(e,t)=>r(e,"name",{value:t,configurable:!0});var a=Object.defineProperty,o=s((e,t)=>a(e,"name",{value:t,configurable:!0}),"t");export const HEADLESS_FLOWS_ENV="LENSMCP_HEADLESS_FLOWS";export function headlessFlowsEnabled(e=process.env){return!["0","false","off","no"].includes((e[HEADLESS_FLOWS_ENV]??"").trim().toLowerCase())}s(headlessFlowsEnabled,"headlessFlowsEnabled"),o(headlessFlowsEnabled,"headlessFlowsEnabled");export const HEADLESS_REQUEST_FLOW_PREFIX="api:",HEADLESS_JOB_FLOW_PREFIX="job:";export function headlessFlowId(e){return`${HEADLESS_REQUEST_FLOW_PREFIX}${e}`}s(headlessFlowId,"headlessFlowId"),o(headlessFlowId,"headlessFlowId");export function headlessJobFlowId(e,t){return`${HEADLESS_JOB_FLOW_PREFIX}${e}#${t??"?"}`}s(headlessJobFlowId,"headlessJobFlowId"),o(headlessJobFlowId,"headlessJobFlowId");export function isHeadlessFlowId(e){return e.startsWith(HEADLESS_REQUEST_FLOW_PREFIX)||e.startsWith(HEADLESS_JOB_FLOW_PREFIX)}s(isHeadlessFlowId,"isHeadlessFlowId"),o(isHeadlessFlowId,"isHeadlessFlowId");const n=/^\/(?:[^/?#]+\/)*(?:health|healthz|health-check|healthcheck|ready|readyz|readiness|live|livez|liveness|ping|metrics|favicon\.ico)\/?(?:[?#].*)?$/i;export function isProbePath(e){return e?n.test(e)||e.startsWith("/__lensmcp/"):!1}s(isProbePath,"isProbePath"),o(isProbePath,"isProbePath");
@@ -1 +1 @@
1
- "use strict";var s=Object.defineProperty;var r=(t,e)=>s(t,"name",{value:e,configurable:!0});var h=Object.defineProperty,a=r((t,e)=>h(t,"name",{value:e,configurable:!0}),"n"),p=Object.defineProperty,c=a((t,e)=>p(t,"name",{value:e,configurable:!0}),"n");import*as l from"node:fs";import{dirname as x,join as o}from"node:path";export{isServiceHopHost,LENS_REQUEST_ID_HEADER}from"./service-hop.js";export const HTTP_EXCHANGE_DIR="http",HTTP_EXCHANGE_PLACES=["calls","ai","in","hops"];export function exchangePlace(t){return t.side==="ingress"?"in":t.ai?"ai":/(^|\.)localhost$/i.test(t.host)?"hops":"calls"}r(exchangePlace,"exchangePlace"),a(exchangePlace,"exchangePlace"),c(exchangePlace,"exchangePlace");const E=/^hx_[0-9a-z]{8,40}$/;export const isHttpExchangeId=c(t=>typeof t=="string"&&E.test(t),"isHttpExchangeId");export function httpExchangeDir(t,e="calls"){const n=o(x(t),HTTP_EXCHANGE_DIR);return e==="calls"?n:o(n,e)}r(httpExchangeDir,"httpExchangeDir"),a(httpExchangeDir,"httpExchangeDir"),c(httpExchangeDir,"httpExchangeDir");export function httpExchangeFile(t,e,n="calls"){if(!isHttpExchangeId(e))throw new Error("invalid http exchange id");return o(httpExchangeDir(t,n),`${e}.json`)}r(httpExchangeFile,"httpExchangeFile"),a(httpExchangeFile,"httpExchangeFile"),c(httpExchangeFile,"httpExchangeFile");export function readHttpExchange(t,e){if(isHttpExchangeId(e))for(const n of HTTP_EXCHANGE_PLACES)try{const i=JSON.parse(l.readFileSync(httpExchangeFile(t,e,n),"utf8"));if(i&&i.schemaVersion===1&&i.id===e)return i}catch{}}r(readHttpExchange,"readHttpExchange"),a(readHttpExchange,"readHttpExchange"),c(readHttpExchange,"readHttpExchange");
1
+ "use strict";var i=Object.defineProperty;var n=(t,e)=>i(t,"name",{value:e,configurable:!0});var s=Object.defineProperty,a=n((t,e)=>s(t,"name",{value:e,configurable:!0}),"n");import*as p from"node:fs";import{dirname as h,join as c}from"node:path";export{isServiceHopHost,LENS_REQUEST_ID_HEADER}from"./service-hop.js";export const HTTP_EXCHANGE_DIR="http",HTTP_EXCHANGE_PLACES=["calls","ai","in","hops"];export function exchangePlace(t){return t.side==="ingress"?"in":t.ai?"ai":/(^|\.)localhost$/i.test(t.host)?"hops":"calls"}n(exchangePlace,"exchangePlace"),a(exchangePlace,"exchangePlace");const l=/^hx_[0-9a-z]{8,40}$/;export const isHttpExchangeId=a(t=>typeof t=="string"&&l.test(t),"isHttpExchangeId");export function httpExchangeDir(t,e="calls"){const r=c(h(t),HTTP_EXCHANGE_DIR);return e==="calls"?r:c(r,e)}n(httpExchangeDir,"httpExchangeDir"),a(httpExchangeDir,"httpExchangeDir");export function httpExchangeFile(t,e,r="calls"){if(!isHttpExchangeId(e))throw new Error("invalid http exchange id");return c(httpExchangeDir(t,r),`${e}.json`)}n(httpExchangeFile,"httpExchangeFile"),a(httpExchangeFile,"httpExchangeFile");export function readHttpExchange(t,e){if(isHttpExchangeId(e))for(const r of HTTP_EXCHANGE_PLACES)try{const o=JSON.parse(p.readFileSync(httpExchangeFile(t,e,r),"utf8"));if(o&&o.schemaVersion===1&&o.id===e)return o}catch{}}n(readHttpExchange,"readHttpExchange"),a(readHttpExchange,"readHttpExchange");
package/lib/http-shape.js CHANGED
@@ -1 +1 @@
1
- "use strict";var j=Object.defineProperty;var m=(t,n)=>j(t,"name",{value:n,configurable:!0});var k=Object.defineProperty,p=m((t,n)=>k(t,"name",{value:n,configurable:!0}),"m"),S=Object.defineProperty,l=p((t,n)=>S(t,"name",{value:n,configurable:!0}),"a");import{isSecretParam as M}from"./redact.js";const x=6,h=60,F=4,O=[["uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i],["ulid",/^[0-9A-HJKMNP-TV-Z]{26}$/],["date-time",/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/],["date",/^\d{4}-\d{2}-\d{2}$/],["email",/^[^\s@]+@[^\s@]+\.[^\s@]+$/],["url",/^https?:\/\/\S+$/i],["jwt",/^eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$/],["int",/^-?\d{1,30}$/],["decimal",/^-?\d+\.\d+$/],["phone",/^\+\d{7,15}$/],["hex",/^[0-9a-f]{16,}$/i],["base64",/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[A-Za-z0-9+/]{32,}={0,2}$/]];export function stringFormat(t){for(const[n,e]of O)if(e.test(t))return n}m(stringFormat,"stringFormat"),p(stringFormat,"stringFormat"),l(stringFormat,"stringFormat");const $=l(t=>t.length>64||/\s/.test(t)||stringFormat(t)!==void 0&&!/^[a-z]/i.test(t)||/@/.test(t)||/^[0-9a-f]{8}-/i.test(t),"dataKey");export function shapeOf(t,n=0,e=!1){if(t==null)return{t:"null"};if(typeof t=="boolean")return{t:"bool"};if(typeof t=="number")return Number.isInteger(t)?{t:"num",int:!0}:{t:"num"};if(typeof t=="bigint")return{t:"num",int:!0};if(typeof t=="string"){const r=stringFormat(t);return{t:"str",...r?{f:r}:{},...e?{}:{max:t.length}}}if(t instanceof Date)return{t:"str",f:"date-time"};if(n>=x)return Array.isArray(t)?{t:"arr",n:[t.length,t.length]}:{t:"obj",fields:[]};if(Array.isArray(t)){const r=t.slice(0,20).map(a=>shapeOf(a,n+1,e)).reduce((a,i)=>a?mergeShapes(a,i):i,void 0);return{t:"arr",n:[t.length,t.length],...r?{of:r}:{}}}if(typeof t=="object"){const r=Object.entries(t).filter(([,a])=>typeof a!="function");if(r.length&&r.some(([a])=>$(a))){const a=r.slice(0,20).map(([,s])=>shapeOf(s,n+1,e)).reduce((s,c)=>s?mergeShapes(s,c):c,void 0),i=r.map(([s])=>stringFormat(s)).find(Boolean);return{t:"map",n:[r.length,r.length],...i?{key:i}:{},...a?{of:a}:{}}}return{t:"obj",fields:r.slice(0,h).map(([a,i])=>{const s=M(a);return{...shapeOf(i,n+1,e||s),name:a,...s?{cred:!0}:{}}}),...r.length>h?{more:r.length-h}:{}}}return{t:"null"}}m(shapeOf,"shapeOf"),p(shapeOf,"shapeOf"),l(shapeOf,"shapeOf");const v=l((t,n)=>t.t===n.t,"same"),N=new Set(["null","bool","num","str","arr","obj","map","any"]);export function isShape(t,n=0){if(!t||typeof t!="object"||n>x*2)return!1;const e=t;return typeof e.t!="string"||!N.has(e.t)?!1:e.t==="obj"?Array.isArray(e.fields)&&e.fields.every(r=>typeof r?.name=="string"&&isShape(r,n+1)):e.t==="any"?Array.isArray(e.of)&&e.of.every(r=>isShape(r,n+1)):e.t==="arr"||e.t==="map"?Array.isArray(e.n)&&(e.of===void 0||isShape(e.of,n+1)):!0}m(isShape,"isShape"),p(isShape,"isShape"),l(isShape,"isShape");export function fieldShape(t){const n={...t};return delete n.name,delete n.opt,delete n.cred,n}m(fieldShape,"fieldShape"),p(fieldShape,"fieldShape"),l(fieldShape,"fieldShape");export function mergeShapes(t,n){if(t.t==="any"||n.t==="any"){const e=[...t.t==="any"?t.of:[t],...n.t==="any"?n.of:[n]],r=[];for(const a of e){const i=r.findIndex(s=>v(s,a));i>=0?r[i]=mergeShapes(r[i],a):r.push(a)}return r.length===1?r[0]:{t:"any",of:r.slice(0,F)}}if(!v(t,n))return{t:"any",of:[t,n]};switch(t.t){case"num":return t.int&&n.int?t:{t:"num"};case"str":{const e=n,r=t.f===e.f?t.f:void 0;return{t:"str",...r?{f:r}:{},...t.max!==void 0||e.max!==void 0?{max:Math.max(t.max??0,e.max??0)}:{}}}case"arr":{const e=n,r=t.of&&e.of?mergeShapes(t.of,e.of):t.of??e.of;return{t:"arr",n:[Math.min(t.n[0],e.n[0]),Math.max(t.n[1],e.n[1])],...r?{of:r}:{}}}case"map":{const e=n,r=t.of&&e.of?mergeShapes(t.of,e.of):t.of??e.of;return{t:"map",n:[Math.min(t.n[0],e.n[0]),Math.max(t.n[1],e.n[1])],...t.key===e.key&&t.key?{key:t.key}:{},...r?{of:r}:{}}}case"obj":{const e=n,r=new Map(t.fields.map(c=>[c.name,c])),a=new Map(e.fields.map(c=>[c.name,c])),i=[...new Set([...r.keys(),...a.keys()])].slice(0,h).map(c=>{const f=r.get(c),u=a.get(c);return{...f&&u?mergeShapes(fieldShape(f),fieldShape(u)):fieldShape(f??u),name:c,...!f||!u||f.opt||u.opt?{opt:!0}:{},...f?.cred||u?.cred?{cred:!0}:{}}}),s=Math.max(t.more??0,e.more??0);return{t:"obj",fields:i,...s?{more:s}:{}}}default:return t}}m(mergeShapes,"mergeShapes"),p(mergeShapes,"mergeShapes"),l(mergeShapes,"mergeShapes");export function shapeText(t,n=0){switch(t.t){case"null":return"null";case"bool":return"boolean";case"num":return t.int?"int":"number";case"str":return t.f?`string(${t.f})`:"string";case"arr":return`[${t.n[0]===t.n[1]?t.n[0]:`${t.n[0]}..${t.n[1]}`}]${t.of?` ${shapeText(t.of,n+1)}`:""}`;case"map":return`map<${t.key??"string"}, ${t.of?shapeText(t.of,n+1):"?"}> (${t.n[0]===t.n[1]?t.n[0]:`${t.n[0]}..${t.n[1]}`} entries)`;case"any":return t.of.map(e=>shapeText(e,n)).join(" | ");case"obj":return`{ ${t.fields.map(e=>`${e.name}${e.opt?"?":""}${e.cred?" (credential-named)":""}: ${shapeText(fieldShape(e),n+1)}`).join(", ")}${t.more?`, \u2026 ${t.more} more`:""} }`}}m(shapeText,"shapeText"),p(shapeText,"shapeText"),l(shapeText,"shapeText");const o=l((t,n)=>{const e=t[n]??t[n.toLowerCase()];return e===void 0?void 0:Array.isArray(e)?e.join(", "):String(e)},"h"),y=l(t=>t?.split(";")[0]?.trim().toLowerCase()||void 0,"media");export function requestFacts(t,n,e){const r=o(t,"authorization")?.split(/\s+/)[0],a=o(t,"cookie"),i=Number(o(t,"content-length")),s=n?Object.keys(n).filter(f=>!$(f)).slice(0,30):[],c=e?Object.keys(e).slice(0,10):[];return{...y(o(t,"content-type"))?{contentType:y(o(t,"content-type"))}:{},...o(t,"accept")?{accept:o(t,"accept").slice(0,80)}:{},...r?{scheme:/^[A-Za-z][\w-]{1,20}$/.test(r)?r:"other"}:{},...a?{cookies:a.split(";").filter(f=>f.includes("=")).length}:{},...o(t,"if-match")?{ifMatch:!0}:{},...o(t,"if-none-match")?{ifNoneMatch:!0}:{},...o(t,"idempotency-key")?{idempotencyKey:!0}:{},...o(t,"origin")?{origin:!0}:{},...Number.isFinite(i)&&i>0?{bytes:i}:{},...s.length?{query:s}:{},...c.length?{params:c}:{}}}m(requestFacts,"requestFacts"),p(requestFacts,"requestFacts"),l(requestFacts,"requestFacts");export function responseFacts(t,n){const e=o(t,"etag"),r=Number(o(t,"content-length")),a=t["set-cookie"],i=(Array.isArray(a)?a:a!==void 0?[String(a)]:[]).slice(0,10).map(c=>{const[f="",...u]=c.split(";").map(g=>g.trim()),d=l(g=>u.find(A=>A.toLowerCase().startsWith(g)),"a"),w=d("samesite")?.split("=")[1],b=d("path=")?.slice(5);return{name:f.split("=")[0].slice(0,40),...d("secure")?{secure:!0}:{},...d("httponly")?{httpOnly:!0}:{},...w?{sameSite:w}:{},...d("domain=")?{domain:!0}:{},...b?{path:b}:{},...d("max-age=")?{maxAge:!0}:{},...d("expires=")?{expires:!0}:{}}}),s=o(t,"access-control-allow-origin");return{...y(o(t,"content-type"))?{contentType:y(o(t,"content-type"))}:{},...Number.isFinite(r)&&r>=0&&o(t,"content-length")!==void 0?{bytes:r}:{},...o(t,"cache-control")?{cacheControl:o(t,"cache-control").slice(0,120)}:{},...e?{etag:e.startsWith("W/")?"weak":"strong"}:{},...o(t,"last-modified")?{lastModified:!0}:{},...o(t,"location")?{location:!0}:{},...o(t,"vary")?{vary:o(t,"vary").slice(0,120)}:{},...o(t,"retry-after")?{retryAfter:!0}:{},...o(t,"www-authenticate")?{wwwAuthenticate:o(t,"www-authenticate").split(/\s+/)[0].slice(0,20)}:{},...o(t,"allow")?{allow:o(t,"allow").slice(0,80)}:{},...i.length?{cookies:i}:{},...s?{cors:{origin:s==="*"?"*":n&&s===n?"echoed":"fixed",...o(t,"access-control-allow-credentials")==="true"?{creds:!0}:{},...o(t,"access-control-allow-methods")?{methods:o(t,"access-control-allow-methods").slice(0,80)}:{},...o(t,"access-control-allow-headers")?{headers:o(t,"access-control-allow-headers").slice(0,120)}:{}}}:{},...o(t,"strict-transport-security")?{hsts:!0}:{},...o(t,"x-content-type-options")?{nosniff:!0}:{},...o(t,"x-powered-by")||o(t,"server")?{poweredBy:!0}:{},...o(t,"deprecation")?{deprecation:!0}:{},...o(t,"sunset")?{sunset:!0}:{},...o(t,"ratelimit")||o(t,"ratelimit-policy")||o(t,"x-ratelimit-limit")?{rateLimit:!0}:{},...o(t,"x-request-id")?{requestId:!0}:{}}}m(responseFacts,"responseFacts"),p(responseFacts,"responseFacts"),l(responseFacts,"responseFacts");
1
+ "use strict";var v=Object.defineProperty;var m=(e,r)=>v(e,"name",{value:r,configurable:!0});var k=Object.defineProperty,l=m((e,r)=>k(e,"name",{value:r,configurable:!0}),"a");import{isSecretParam as j}from"./redact.js";const b=6,d=60,S=4,M=[["uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i],["ulid",/^[0-9A-HJKMNP-TV-Z]{26}$/],["date-time",/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/],["date",/^\d{4}-\d{2}-\d{2}$/],["email",/^[^\s@]+@[^\s@]+\.[^\s@]+$/],["url",/^https?:\/\/\S+$/i],["jwt",/^eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$/],["int",/^-?\d{1,30}$/],["decimal",/^-?\d+\.\d+$/],["phone",/^\+\d{7,15}$/],["hex",/^[0-9a-f]{16,}$/i],["base64",/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[A-Za-z0-9+/]{32,}={0,2}$/]];export function stringFormat(e){for(const[r,n]of M)if(n.test(e))return r}m(stringFormat,"stringFormat"),l(stringFormat,"stringFormat");const x=l(e=>e.length>64||/\s/.test(e)||stringFormat(e)!==void 0&&!/^[a-z]/i.test(e)||/@/.test(e)||/^[0-9a-f]{8}-/i.test(e),"dataKey");export function shapeOf(e,r=0,n=!1){if(e==null)return{t:"null"};if(typeof e=="boolean")return{t:"bool"};if(typeof e=="number")return Number.isInteger(e)?{t:"num",int:!0}:{t:"num"};if(typeof e=="bigint")return{t:"num",int:!0};if(typeof e=="string"){const t=stringFormat(e);return{t:"str",...t?{f:t}:{},...n?{}:{max:e.length}}}if(e instanceof Date)return{t:"str",f:"date-time"};if(r>=b)return Array.isArray(e)?{t:"arr",n:[e.length,e.length]}:{t:"obj",fields:[]};if(Array.isArray(e)){const t=e.slice(0,20).map(o=>shapeOf(o,r+1,n)).reduce((o,i)=>o?mergeShapes(o,i):i,void 0);return{t:"arr",n:[e.length,e.length],...t?{of:t}:{}}}if(typeof e=="object"){const t=Object.entries(e).filter(([,o])=>typeof o!="function");if(t.length&&t.some(([o])=>x(o))){const o=t.slice(0,20).map(([,s])=>shapeOf(s,r+1,n)).reduce((s,c)=>s?mergeShapes(s,c):c,void 0),i=t.map(([s])=>stringFormat(s)).find(Boolean);return{t:"map",n:[t.length,t.length],...i?{key:i}:{},...o?{of:o}:{}}}return{t:"obj",fields:t.slice(0,d).map(([o,i])=>{const s=j(o);return{...shapeOf(i,r+1,n||s),name:o,...s?{cred:!0}:{}}}),...t.length>d?{more:t.length-d}:{}}}return{t:"null"}}m(shapeOf,"shapeOf"),l(shapeOf,"shapeOf");const $=l((e,r)=>e.t===r.t,"same"),F=new Set(["null","bool","num","str","arr","obj","map","any"]);export function isShape(e,r=0){if(!e||typeof e!="object"||r>b*2)return!1;const n=e;return typeof n.t!="string"||!F.has(n.t)?!1:n.t==="obj"?Array.isArray(n.fields)&&n.fields.every(t=>typeof t?.name=="string"&&isShape(t,r+1)):n.t==="any"?Array.isArray(n.of)&&n.of.every(t=>isShape(t,r+1)):n.t==="arr"||n.t==="map"?Array.isArray(n.n)&&(n.of===void 0||isShape(n.of,r+1)):!0}m(isShape,"isShape"),l(isShape,"isShape");export function fieldShape(e){const r={...e};return delete r.name,delete r.opt,delete r.cred,r}m(fieldShape,"fieldShape"),l(fieldShape,"fieldShape");export function mergeShapes(e,r){if(e.t==="any"||r.t==="any"){const n=[...e.t==="any"?e.of:[e],...r.t==="any"?r.of:[r]],t=[];for(const o of n){const i=t.findIndex(s=>$(s,o));i>=0?t[i]=mergeShapes(t[i],o):t.push(o)}return t.length===1?t[0]:{t:"any",of:t.slice(0,S)}}if(!$(e,r))return{t:"any",of:[e,r]};switch(e.t){case"num":return e.int&&r.int?e:{t:"num"};case"str":{const n=r,t=e.f===n.f?e.f:void 0;return{t:"str",...t?{f:t}:{},...e.max!==void 0||n.max!==void 0?{max:Math.max(e.max??0,n.max??0)}:{}}}case"arr":{const n=r,t=e.of&&n.of?mergeShapes(e.of,n.of):e.of??n.of;return{t:"arr",n:[Math.min(e.n[0],n.n[0]),Math.max(e.n[1],n.n[1])],...t?{of:t}:{}}}case"map":{const n=r,t=e.of&&n.of?mergeShapes(e.of,n.of):e.of??n.of;return{t:"map",n:[Math.min(e.n[0],n.n[0]),Math.max(e.n[1],n.n[1])],...e.key===n.key&&e.key?{key:e.key}:{},...t?{of:t}:{}}}case"obj":{const n=r,t=new Map(e.fields.map(c=>[c.name,c])),o=new Map(n.fields.map(c=>[c.name,c])),i=[...new Set([...t.keys(),...o.keys()])].slice(0,d).map(c=>{const f=t.get(c),u=o.get(c);return{...f&&u?mergeShapes(fieldShape(f),fieldShape(u)):fieldShape(f??u),name:c,...!f||!u||f.opt||u.opt?{opt:!0}:{},...f?.cred||u?.cred?{cred:!0}:{}}}),s=Math.max(e.more??0,n.more??0);return{t:"obj",fields:i,...s?{more:s}:{}}}default:return e}}m(mergeShapes,"mergeShapes"),l(mergeShapes,"mergeShapes");export function shapeText(e,r=0){switch(e.t){case"null":return"null";case"bool":return"boolean";case"num":return e.int?"int":"number";case"str":return e.f?`string(${e.f})`:"string";case"arr":return`[${e.n[0]===e.n[1]?e.n[0]:`${e.n[0]}..${e.n[1]}`}]${e.of?` ${shapeText(e.of,r+1)}`:""}`;case"map":return`map<${e.key??"string"}, ${e.of?shapeText(e.of,r+1):"?"}> (${e.n[0]===e.n[1]?e.n[0]:`${e.n[0]}..${e.n[1]}`} entries)`;case"any":return e.of.map(n=>shapeText(n,r)).join(" | ");case"obj":return`{ ${e.fields.map(n=>`${n.name}${n.opt?"?":""}${n.cred?" (credential-named)":""}: ${shapeText(fieldShape(n),r+1)}`).join(", ")}${e.more?`, \u2026 ${e.more} more`:""} }`}}m(shapeText,"shapeText"),l(shapeText,"shapeText");const a=l((e,r)=>{const n=e[r]??e[r.toLowerCase()];return n===void 0?void 0:Array.isArray(n)?n.join(", "):String(n)},"h"),y=l(e=>e?.split(";")[0]?.trim().toLowerCase()||void 0,"media");export function requestFacts(e,r,n){const t=a(e,"authorization")?.split(/\s+/)[0],o=a(e,"cookie"),i=Number(a(e,"content-length")),s=r?Object.keys(r).filter(f=>!x(f)).slice(0,30):[],c=n?Object.keys(n).slice(0,10):[];return{...y(a(e,"content-type"))?{contentType:y(a(e,"content-type"))}:{},...a(e,"accept")?{accept:a(e,"accept").slice(0,80)}:{},...t?{scheme:/^[A-Za-z][\w-]{1,20}$/.test(t)?t:"other"}:{},...o?{cookies:o.split(";").filter(f=>f.includes("=")).length}:{},...a(e,"if-match")?{ifMatch:!0}:{},...a(e,"if-none-match")?{ifNoneMatch:!0}:{},...a(e,"idempotency-key")?{idempotencyKey:!0}:{},...a(e,"origin")?{origin:!0}:{},...Number.isFinite(i)&&i>0?{bytes:i}:{},...s.length?{query:s}:{},...c.length?{params:c}:{}}}m(requestFacts,"requestFacts"),l(requestFacts,"requestFacts");export function responseFacts(e,r){const n=a(e,"etag"),t=Number(a(e,"content-length")),o=e["set-cookie"],i=(Array.isArray(o)?o:o!==void 0?[String(o)]:[]).slice(0,10).map(c=>{const[f="",...u]=c.split(";").map(h=>h.trim()),p=l(h=>u.find(A=>A.toLowerCase().startsWith(h)),"a"),g=p("samesite")?.split("=")[1],w=p("path=")?.slice(5);return{name:f.split("=")[0].slice(0,40),...p("secure")?{secure:!0}:{},...p("httponly")?{httpOnly:!0}:{},...g?{sameSite:g}:{},...p("domain=")?{domain:!0}:{},...w?{path:w}:{},...p("max-age=")?{maxAge:!0}:{},...p("expires=")?{expires:!0}:{}}}),s=a(e,"access-control-allow-origin");return{...y(a(e,"content-type"))?{contentType:y(a(e,"content-type"))}:{},...Number.isFinite(t)&&t>=0&&a(e,"content-length")!==void 0?{bytes:t}:{},...a(e,"cache-control")?{cacheControl:a(e,"cache-control").slice(0,120)}:{},...n?{etag:n.startsWith("W/")?"weak":"strong"}:{},...a(e,"last-modified")?{lastModified:!0}:{},...a(e,"location")?{location:!0}:{},...a(e,"vary")?{vary:a(e,"vary").slice(0,120)}:{},...a(e,"retry-after")?{retryAfter:!0}:{},...a(e,"www-authenticate")?{wwwAuthenticate:a(e,"www-authenticate").split(/\s+/)[0].slice(0,20)}:{},...a(e,"allow")?{allow:a(e,"allow").slice(0,80)}:{},...i.length?{cookies:i}:{},...s?{cors:{origin:s==="*"?"*":r&&s===r?"echoed":"fixed",...a(e,"access-control-allow-credentials")==="true"?{creds:!0}:{},...a(e,"access-control-allow-methods")?{methods:a(e,"access-control-allow-methods").slice(0,80)}:{},...a(e,"access-control-allow-headers")?{headers:a(e,"access-control-allow-headers").slice(0,120)}:{}}}:{},...a(e,"strict-transport-security")?{hsts:!0}:{},...a(e,"x-content-type-options")?{nosniff:!0}:{},...a(e,"x-powered-by")||a(e,"server")?{poweredBy:!0}:{},...a(e,"deprecation")?{deprecation:!0}:{},...a(e,"sunset")?{sunset:!0}:{},...a(e,"ratelimit")||a(e,"ratelimit-policy")||a(e,"x-ratelimit-limit")?{rateLimit:!0}:{},...a(e,"x-request-id")?{requestId:!0}:{}}}m(responseFacts,"responseFacts"),l(responseFacts,"responseFacts");
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var r=(e,a)=>f(e,"name",{value:a,configurable:!0});var c=Object.defineProperty,t=r((e,a)=>c(e,"name",{value:a,configurable:!0}),"r"),l=Object.defineProperty,n=t((e,a)=>l(e,"name",{value:a,configurable:!0}),"e");const o=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;export function foldKeyPattern(e){return e.replace(o,"*").replace(/(?<=^|[:=/])(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{16,}(?=$|[:=/])/g,"*").replace(/(?<![A-Za-z])(?=[0-9a-f]*\d)[0-9a-f]{8,}(?![A-Za-z])/gi,"*").replace(/(?<![A-Za-z0-9])\d{2,}(?![A-Za-z0-9])/g,"*").replace(/\*(?:[_-]?\*)+/g,"*")}r(foldKeyPattern,"foldKeyPattern"),t(foldKeyPattern,"foldKeyPattern"),n(foldKeyPattern,"foldKeyPattern");
1
+ "use strict";var f=Object.defineProperty;var r=(a,e)=>f(a,"name",{value:e,configurable:!0});var t=Object.defineProperty,c=r((a,e)=>t(a,"name",{value:e,configurable:!0}),"e");const l=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;export function foldKeyPattern(a){return a.replace(l,"*").replace(/(?<=^|[:=/])(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{16,}(?=$|[:=/])/g,"*").replace(/(?<![A-Za-z])(?=[0-9a-f]*\d)[0-9a-f]{8,}(?![A-Za-z])/gi,"*").replace(/(?<![A-Za-z0-9])\d{2,}(?![A-Za-z0-9])/g,"*").replace(/\*(?:[_-]?\*)+/g,"*")}r(foldKeyPattern,"foldKeyPattern"),c(foldKeyPattern,"foldKeyPattern");
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var e=(n,o)=>p(n,"name",{value:o,configurable:!0});var u=Object.defineProperty,i=e((n,o)=>u(n,"name",{value:o,configurable:!0}),"e"),l=Object.defineProperty,t=i((n,o)=>l(n,"name",{value:o,configurable:!0}),"e");import{existsSync as f,readFileSync as j}from"node:fs";import{dirname as g,join as r}from"node:path";const m=t(n=>!!n&&typeof n=="object"&&!Array.isArray(n),"isObj");function c(n,o){try{const s=JSON.parse(j(n,"utf8"))?.[o];return m(s)?s:{}}catch{return{}}}e(c,"i"),i(c,"t"),t(c,"block");export function readWorkspaceConfig(n){return{...c(r(n,"nx.json"),"lensmcp"),...c(r(n,"lensmcp.json"),"config")}}e(readWorkspaceConfig,"readWorkspaceConfig"),i(readWorkspaceConfig,"readWorkspaceConfig"),t(readWorkspaceConfig,"readWorkspaceConfig");export function workspaceConfigSource(n,o){return o in c(r(n,"lensmcp.json"),"config")?"lensmcp.json":o in c(r(n,"nx.json"),"lensmcp")?"nx.json":void 0}e(workspaceConfigSource,"workspaceConfigSource"),i(workspaceConfigSource,"workspaceConfigSource"),t(workspaceConfigSource,"workspaceConfigSource");export function findWorkspaceConfigRoot(n){let o=n;for(let s=0;s<8;s++){if(f(r(o,"nx.json"))||f(r(o,"lensmcp.json")))return o;const a=g(o);if(a===o)break;o=a}}e(findWorkspaceConfigRoot,"findWorkspaceConfigRoot"),i(findWorkspaceConfigRoot,"findWorkspaceConfigRoot"),t(findWorkspaceConfigRoot,"findWorkspaceConfigRoot");
1
+ "use strict";var f=Object.defineProperty;var e=(o,n)=>f(o,"name",{value:n,configurable:!0});var p=Object.defineProperty,c=e((o,n)=>p(o,"name",{value:n,configurable:!0}),"e");import{existsSync as a,readFileSync as u}from"node:fs";import{dirname as j,join as r}from"node:path";const l=c(o=>!!o&&typeof o=="object"&&!Array.isArray(o),"isObj");function i(o,n){try{const s=JSON.parse(u(o,"utf8"))?.[n];return l(s)?s:{}}catch{return{}}}e(i,"t"),c(i,"block");export function readWorkspaceConfig(o){return{...i(r(o,"nx.json"),"lensmcp"),...i(r(o,"lensmcp.json"),"config")}}e(readWorkspaceConfig,"readWorkspaceConfig"),c(readWorkspaceConfig,"readWorkspaceConfig");export function workspaceConfigSource(o,n){return n in i(r(o,"lensmcp.json"),"config")?"lensmcp.json":n in i(r(o,"nx.json"),"lensmcp")?"nx.json":void 0}e(workspaceConfigSource,"workspaceConfigSource"),c(workspaceConfigSource,"workspaceConfigSource");export function findWorkspaceConfigRoot(o){let n=o;for(let s=0;s<8;s++){if(a(r(n,"nx.json"))||a(r(n,"lensmcp.json")))return n;const t=j(n);if(t===n)break;n=t}}e(findWorkspaceConfigRoot,"findWorkspaceConfigRoot"),c(findWorkspaceConfigRoot,"findWorkspaceConfigRoot");
package/lib/lens-dir.js CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";var p=Object.defineProperty;var s=(n,e)=>p(n,"name",{value:e,configurable:!0});var f=Object.defineProperty,c=s((n,e)=>f(n,"name",{value:e,configurable:!0}),"n"),$=Object.defineProperty,u=c((n,e)=>$(n,"name",{value:e,configurable:!0}),"c");export const LENS_SHARED_DIRS=["sql-review","route-review","flow-review","ui-review","cache-review","queue-review","ai-review","ai-names","team","team-design"],LENS_SHARED_FILES=["team/skills/a-skill/SKILL.md","team/skills/a-skill/sources.json","team/skills/a-skill/references/more.md"];export function lensGitignoreLines(n="**/"){return[`${n}.lensmcp/*`,...LENS_SHARED_DIRS.map(e=>`!${n}.lensmcp/${e}/`)]}s(lensGitignoreLines,"lensGitignoreLines"),c(lensGitignoreLines,"lensGitignoreLines"),u(lensGitignoreLines,"lensGitignoreLines");const g="# LensMCP: this machine's runtime state is ignored; the team's analyzer instructions are kept";export function fixLensGitignore(n){const e=n.split(`
2
- `),a=/^(\/|\*\*\/)?\.lensmcp\/?(\*)?$/;let i=e.findIndex(t=>a.test(t.trim())),r=!1;if(i<0){const t=n.length&&!n.endsWith(`
3
- `)?`${n}
4
- `:n;return{text:`${t}${t.trim()?`
5
- `:""}${g}
1
+ "use strict";var u=Object.defineProperty;var n=(i,e)=>u(i,"name",{value:e,configurable:!0});var p=Object.defineProperty,m=n((i,e)=>p(i,"name",{value:e,configurable:!0}),"c");export const LENS_SHARED_DIRS=["sql-review","route-review","flow-review","ui-review","cache-review","queue-review","ai-review","ai-names","team","team-design"],LENS_SHARED_FILES=["team/skills/a-skill/SKILL.md","team/skills/a-skill/sources.json","team/skills/a-skill/references/more.md"];export function lensGitignoreLines(i="**/"){return[`${i}.lensmcp/*`,...LENS_SHARED_DIRS.map(e=>`!${i}.lensmcp/${e}/`)]}n(lensGitignoreLines,"lensGitignoreLines"),m(lensGitignoreLines,"lensGitignoreLines");const $="# LensMCP: this machine's runtime state is ignored; the team's analyzer instructions are kept";export function fixLensGitignore(i){const e=i.split(`
2
+ `),c=/^(\/|\*\*\/)?\.lensmcp\/?(\*)?$/;let s=e.findIndex(t=>c.test(t.trim())),r=!1;if(s<0){const t=i.length&&!i.endsWith(`
3
+ `)?`${i}
4
+ `:i;return{text:`${t}${t.trim()?`
5
+ `:""}${$}
6
6
  ${lensGitignoreLines().join(`
7
7
  `)}
8
- `,changed:!0}}const o=a.exec(e[i].trim())[1]==="/"?"/":"**/";e[i].trim()!==`${o}.lensmcp/*`&&(e[i]=`${o}.lensmcp/*`,r=!0);for(const t of LENS_SHARED_DIRS){const l=`!${o}.lensmcp/${t}/`;e.some(m=>m.trim()===l||m.trim()===l.slice(0,-1))||(e.splice(++i,0,l),r=!0)}return{text:e.join(`
9
- `),changed:r}}s(fixLensGitignore,"fixLensGitignore"),c(fixLensGitignore,"fixLensGitignore"),u(fixLensGitignore,"fixLensGitignore");
8
+ `,changed:!0}}const l=c.exec(e[s].trim())[1]==="/"?"/":"**/";e[s].trim()!==`${l}.lensmcp/*`&&(e[s]=`${l}.lensmcp/*`,r=!0);for(const t of LENS_SHARED_DIRS){const o=`!${l}.lensmcp/${t}/`;e.some(a=>a.trim()===o||a.trim()===o.slice(0,-1))||(e.splice(++s,0,o),r=!0)}return{text:e.join(`
9
+ `),changed:r}}n(fixLensGitignore,"fixLensGitignore"),m(fixLensGitignore,"fixLensGitignore");
@@ -1,2 +1,2 @@
1
- "use strict";var u=Object.defineProperty;var r=(e,s)=>u(e,"name",{value:s,configurable:!0});var d=Object.defineProperty,a=r((e,s)=>d(e,"name",{value:s,configurable:!0}),"r"),m=Object.defineProperty,i=a((e,s)=>m(e,"name",{value:s,configurable:!0}),"o");import{appendFileSync as v,closeSync as S,mkdirSync as y,openSync as f,renameSync as g,statSync as I,unlinkSync as _}from"node:fs";import{dirname as b,join as N}from"node:path";import{ERROR_DISMISSED as l,ERROR_RESTORED as E,LENS_EVENT_SOURCE as R,METRICS_RESET as $,metricsIdBatches as x}from"@lensmcp/protocol-types";import{rotateBusFile as k}from"./bus-rotation.js";import{ulid as B}from"./ulid.js";export function lensEventFile(e=process.env,s=process.cwd()){return e.LENSMCP_EVENT_FILE??N(s,".lensmcp","events.jsonl")}r(lensEventFile,"lensEventFile"),a(lensEventFile,"lensEventFile"),i(lensEventFile,"lensEventFile");const c=i((e,s,t,n,o)=>({id:B(),sessionId:e,timestamp:s,source:R,category:"runtime",severity:"info",context:{sessionId:e},fingerprint:t,title:n,raw:o}),"lensEvent");export function dismissalEvent(e,s){return c(s,e.until,`${l}:${e.groupId}`,`error dismissed: ${e.title??e.groupId}`,{kind:l,groupId:e.groupId,until:e.until,eventIds:e.eventIds,...e.by?{by:e.by}:{},...e.reason?{reason:e.reason}:{},...e.title?{title:e.title}:{}})}r(dismissalEvent,"dismissalEvent"),a(dismissalEvent,"dismissalEvent"),i(dismissalEvent,"dismissalEvent");export function restoralEvent(e,s,t){return c(s,t,`${E}:${e}`,"error restored",{kind:E,groupId:e})}r(restoralEvent,"restoralEvent"),a(restoralEvent,"restoralEvent"),i(restoralEvent,"restoralEvent");export function metricsChangeEvents(e,s,t){const n=e.kind===$;return(e.ids?x(e.ids):[void 0]).map(o=>c(s,t,`${e.kind}:${e.scope}`,`${n?"numbers reset":"numbers counted whole again"}: ${e.scope}${o?` \xB7 ${o.length}`:" \xB7 all"}`,{kind:e.kind,scope:e.scope,...n?{at:t}:{},...o?{ids:o}:{}}))}r(metricsChangeEvents,"metricsChangeEvents"),a(metricsChangeEvents,"metricsChangeEvents"),i(metricsChangeEvents,"metricsChangeEvents");const p=i((e,s,t)=>{const n=Number(process.env[e]);return Number.isFinite(n)&&t(n)?n:s},"envNumber");export function appendBusEvents(e,s){s.length!==0&&(y(b(e),{recursive:!0}),k(e,{maxBytes:p("LENSMCP_EVENT_MAX_BYTES",50*1024*1024,t=>t>0),maxFiles:p("LENSMCP_EVENT_MAX_FILES",5,t=>t>=1&&t<=20),fs:{statSync:I,renameSync:g,unlinkSync:_,openSync:f,closeSync:S}}),v(e,s.map(t=>JSON.stringify(t)+`
2
- `).join("")))}r(appendBusEvents,"appendBusEvents"),a(appendBusEvents,"appendBusEvents"),i(appendBusEvents,"appendBusEvents");
1
+ "use strict";var u=Object.defineProperty;var r=(n,e)=>u(n,"name",{value:e,configurable:!0});var E=Object.defineProperty,i=r((n,e)=>E(n,"name",{value:e,configurable:!0}),"o");import{appendFileSync as l,closeSync as m,mkdirSync as S,openSync as v,renameSync as y,statSync as f,unlinkSync as I}from"node:fs";import{dirname as g,join as _}from"node:path";import{ERROR_DISMISSED as c,ERROR_RESTORED as p,LENS_EVENT_SOURCE as N,METRICS_RESET as R,metricsIdBatches as $}from"@lensmcp/protocol-types";import{rotateBusFile as b}from"./bus-rotation.js";import{ulid as x}from"./ulid.js";export function lensEventFile(n=process.env,e=process.cwd()){return n.LENSMCP_EVENT_FILE??_(e,".lensmcp","events.jsonl")}r(lensEventFile,"lensEventFile"),i(lensEventFile,"lensEventFile");const a=i((n,e,s,t,o)=>({id:x(),sessionId:n,timestamp:e,source:N,category:"runtime",severity:"info",context:{sessionId:n},fingerprint:s,title:t,raw:o}),"lensEvent");export function dismissalEvent(n,e){return a(e,n.until,`${c}:${n.groupId}`,`error dismissed: ${n.title??n.groupId}`,{kind:c,groupId:n.groupId,until:n.until,eventIds:n.eventIds,...n.by?{by:n.by}:{},...n.reason?{reason:n.reason}:{},...n.title?{title:n.title}:{}})}r(dismissalEvent,"dismissalEvent"),i(dismissalEvent,"dismissalEvent");export function restoralEvent(n,e,s){return a(e,s,`${p}:${n}`,"error restored",{kind:p,groupId:n})}r(restoralEvent,"restoralEvent"),i(restoralEvent,"restoralEvent");export function metricsChangeEvents(n,e,s){const t=n.kind===R;return(n.ids?$(n.ids):[void 0]).map(o=>a(e,s,`${n.kind}:${n.scope}`,`${t?"numbers reset":"numbers counted whole again"}: ${n.scope}${o?` \xB7 ${o.length}`:" \xB7 all"}`,{kind:n.kind,scope:n.scope,...t?{at:s}:{},...o?{ids:o}:{}}))}r(metricsChangeEvents,"metricsChangeEvents"),i(metricsChangeEvents,"metricsChangeEvents");const d=i((n,e,s)=>{const t=Number(process.env[n]);return Number.isFinite(t)&&s(t)?t:e},"envNumber");export function appendBusEvents(n,e){e.length!==0&&(S(g(n),{recursive:!0}),b(n,{maxBytes:d("LENSMCP_EVENT_MAX_BYTES",50*1024*1024,s=>s>0),maxFiles:d("LENSMCP_EVENT_MAX_FILES",5,s=>s>=1&&s<=20),fs:{statSync:f,renameSync:y,unlinkSync:I,openSync:v,closeSync:m}}),l(n,e.map(s=>JSON.stringify(s)+`
2
+ `).join("")))}r(appendBusEvents,"appendBusEvents"),i(appendBusEvents,"appendBusEvents");
package/lib/lens-store.js CHANGED
@@ -1 +1 @@
1
- "use strict";var N=Object.defineProperty;var i=(e,t)=>N(e,"name",{value:t,configurable:!0});var b=Object.defineProperty,u=i((e,t)=>b(e,"name",{value:t,configurable:!0}),"i"),E=Object.defineProperty,o=u((e,t)=>E(e,"name",{value:t,configurable:!0}),"s");import{existsSync as O,readdirSync as x,readFileSync as S,readlinkSync as k,realpathSync as F}from"node:fs";import{homedir as _}from"node:os";import{basename as C,join as p,sep as d}from"node:path";export const lensStoreHome=o((e=process.env)=>e.LENSMCP_HOME||p(_(),".lensmcp"),"lensStoreHome");const h=o(e=>{try{return F(e)}catch{return e}},"realOr");export function storedLensmcp(e,t){const r=p(e,"versions",t),n=p(r,"node_modules","lensmcp"),s=p(n,"bin.js");if(O(s)){try{if(JSON.parse(S(p(n,"package.json"),"utf8")).version!==t)return}catch{return}return{home:e,version:t,dir:r,pkg:n,cli:s,launcher:p(e,"bin","lensmcp")}}}i(storedLensmcp,"storedLensmcp"),u(storedLensmcp,"storedLensmcp"),o(storedLensmcp,"storedLensmcp");export function storeCurrent(e=process.env){if(e.LENSMCP_NO_STORE==="1")return;const t=lensStoreHome(e);let r;try{r=C(k(p(t,"current")))}catch{return}return storedLensmcp(t,r)}i(storeCurrent,"storeCurrent"),u(storeCurrent,"storeCurrent"),o(storeCurrent,"storeCurrent");export function inLensStore(e,t=process.env){const r=p(lensStoreHome(t),"versions");return e.startsWith(r+d)||h(e).startsWith(h(r)+d)}i(inLensStore,"inLensStore"),u(inLensStore,"inLensStore"),o(inLensStore,"inLensStore");const g=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;export function storeVersionOf(e,t=process.env){const r=lensStoreHome(t),n=p(r,"versions");for(const[s,a]of[[e,n],[h(e),h(n)]]){if(!s.startsWith(a+d))continue;const m=s.slice(a.length+1).split(d,1)[0]??"";if(g.test(m))return storedLensmcp(r,m)}}i(storeVersionOf,"storeVersionOf"),u(storeVersionOf,"storeVersionOf"),o(storeVersionOf,"storeVersionOf");export function storeOwnOrCurrent(e=process.argv[1],t=process.env){if(t.LENSMCP_NO_STORE!=="1")return e&&inLensStore(e,t)?storeVersionOf(e,t):storeCurrent(t)}i(storeOwnOrCurrent,"storeOwnOrCurrent"),u(storeOwnOrCurrent,"storeOwnOrCurrent"),o(storeOwnOrCurrent,"storeOwnOrCurrent");export const LENS_OPTIONAL_PACKAGES=["@lensmcp/terminals","@lensmcp/vite-plugin","@lensmcp/bridge","@lensmcp/client-runtime","@lensmcp/react-instrumentation","@lensmcp/valtio-instrumentation"];export function storedOptionalNames(e,t){return LENS_OPTIONAL_PACKAGES.filter(r=>O(p(e,"versions",t,"node_modules",r,"package.json")))}i(storedOptionalNames,"storedOptionalNames"),u(storedOptionalNames,"storedOptionalNames"),o(storedOptionalNames,"storedOptionalNames");export function compareLensVersions(e,t){const r=o(c=>{const l=c.indexOf("-");return{nums:(l<0?c:c.slice(0,l)).split(".").map(f=>Number(f)||0),pre:l<0?void 0:c.slice(l+1)}},"parse"),n=r(e),s=r(t);for(let c=0;c<3;c++){const l=(n.nums[c]??0)-(s.nums[c]??0);if(l)return l<0?-1:1}if(n.pre===s.pre)return 0;if(n.pre===void 0)return 1;if(s.pre===void 0)return-1;const a=n.pre.split("."),m=s.pre.split(".");for(let c=0;c<Math.max(a.length,m.length);c++){const l=a[c],f=m[c];if(l===void 0)return-1;if(f===void 0)return 1;if(l===f)continue;const v=/^\d+$/.test(l),y=/^\d+$/.test(f);return v&&y?Number(l)<Number(f)?-1:1:v!==y?v?-1:1:l<f?-1:1}return 0}i(compareLensVersions,"compareLensVersions"),u(compareLensVersions,"compareLensVersions"),o(compareLensVersions,"compareLensVersions");export function storedVersionNames(e){let t;try{t=x(p(e,"versions"))}catch{return[]}return t.filter(r=>g.test(r)&&storedLensmcp(e,r)!==void 0).sort(compareLensVersions)}i(storedVersionNames,"storedVersionNames"),u(storedVersionNames,"storedVersionNames"),o(storedVersionNames,"storedVersionNames");const L=o(e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},"pidAlive");export function storeForwardedRunning(e){const t=new Map,r=p(e,"versions",".running");let n;try{n=x(r)}catch{return t}for(const s of n){const a=Number(s);if(!Number.isInteger(a)||a<=0||!L(a))continue;let m;try{m=S(p(r,s),"utf8").trim()}catch{continue}g.test(m)&&t.set(m,[...t.get(m)??[],a])}return t}i(storeForwardedRunning,"storeForwardedRunning"),u(storeForwardedRunning,"storeForwardedRunning"),o(storeForwardedRunning,"storeForwardedRunning");export function linkedCheckout(e){if(!O(p(e,"package.json")))return!1;const t=h(e).split(d);return t[t.length-1]!=="lensmcp"||t[t.length-2]!=="node_modules"}i(linkedCheckout,"linkedCheckout"),u(linkedCheckout,"linkedCheckout"),o(linkedCheckout,"linkedCheckout");export function storeFirst(e,t=process.env,r=process.argv[1]){const n=storeOwnOrCurrent(r,t);return!n||e&&linkedCheckout(e)?e?[e]:[]:e?[n.pkg,e]:[n.pkg]}i(storeFirst,"storeFirst"),u(storeFirst,"storeFirst"),o(storeFirst,"storeFirst");export 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 ';export function storeFirstMcpEntry(e){return{command:"sh",args:["-c",`${STORE_FIRST_MCP}${e.join(" ")}`]}}i(storeFirstMcpEntry,"storeFirstMcpEntry"),u(storeFirstMcpEntry,"storeFirstMcpEntry"),o(storeFirstMcpEntry,"storeFirstMcpEntry");export function storeFirstFallback(e){if(!e||typeof e!="object"||Array.isArray(e))return;const{command:t,args:r,...n}=e;if(t!=="sh"||Object.keys(n).length>0||!Array.isArray(r)||r.length!==2||r[0]!=="-c")return;const s=r[1];if(typeof s!="string"||!s.startsWith(STORE_FIRST_MCP))return;const a=s.slice(STORE_FIRST_MCP.length).split(" ");return a.every(m=>/^[\w@.-]+$/.test(m))?a:void 0}i(storeFirstFallback,"storeFirstFallback"),u(storeFirstFallback,"storeFirstFallback"),o(storeFirstFallback,"storeFirstFallback");
1
+ "use strict";var S=Object.defineProperty;var i=(r,t)=>S(r,"name",{value:t,configurable:!0});var N=Object.defineProperty,o=i((r,t)=>N(r,"name",{value:t,configurable:!0}),"s");import{existsSync as v,readdirSync as x,readFileSync as y,readlinkSync as b,realpathSync as E}from"node:fs";import{homedir as _}from"node:os";import{basename as k,join as u,sep as f}from"node:path";export const lensStoreHome=o((r=process.env)=>r.LENSMCP_HOME||u(_(),".lensmcp"),"lensStoreHome");const d=o(r=>{try{return E(r)}catch{return r}},"realOr");export function storedLensmcp(r,t){const e=u(r,"versions",t),n=u(e,"node_modules","lensmcp"),s=u(n,"bin.js");if(v(s)){try{if(JSON.parse(y(u(n,"package.json"),"utf8")).version!==t)return}catch{return}return{home:r,version:t,dir:e,pkg:n,cli:s,launcher:u(r,"bin","lensmcp")}}}i(storedLensmcp,"storedLensmcp"),o(storedLensmcp,"storedLensmcp");export function storeCurrent(r=process.env){if(r.LENSMCP_NO_STORE==="1")return;const t=lensStoreHome(r);let e;try{e=k(b(u(t,"current")))}catch{return}return storedLensmcp(t,e)}i(storeCurrent,"storeCurrent"),o(storeCurrent,"storeCurrent");export function inLensStore(r,t=process.env){const e=u(lensStoreHome(t),"versions");return r.startsWith(e+f)||d(r).startsWith(d(e)+f)}i(inLensStore,"inLensStore"),o(inLensStore,"inLensStore");const g=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;export function storeVersionOf(r,t=process.env){const e=lensStoreHome(t),n=u(e,"versions");for(const[s,p]of[[r,n],[d(r),d(n)]]){if(!s.startsWith(p+f))continue;const l=s.slice(p.length+1).split(f,1)[0]??"";if(g.test(l))return storedLensmcp(e,l)}}i(storeVersionOf,"storeVersionOf"),o(storeVersionOf,"storeVersionOf");export function storeOwnOrCurrent(r=process.argv[1],t=process.env){if(t.LENSMCP_NO_STORE!=="1")return r&&inLensStore(r,t)?storeVersionOf(r,t):storeCurrent(t)}i(storeOwnOrCurrent,"storeOwnOrCurrent"),o(storeOwnOrCurrent,"storeOwnOrCurrent");export const LENS_OPTIONAL_PACKAGES=["@lensmcp/terminals","@lensmcp/vite-plugin","@lensmcp/bridge","@lensmcp/client-runtime","@lensmcp/react-instrumentation","@lensmcp/valtio-instrumentation"];export function storedOptionalNames(r,t){return LENS_OPTIONAL_PACKAGES.filter(e=>v(u(r,"versions",t,"node_modules",e,"package.json")))}i(storedOptionalNames,"storedOptionalNames"),o(storedOptionalNames,"storedOptionalNames");export function compareLensVersions(r,t){const e=o(c=>{const a=c.indexOf("-");return{nums:(a<0?c:c.slice(0,a)).split(".").map(m=>Number(m)||0),pre:a<0?void 0:c.slice(a+1)}},"parse"),n=e(r),s=e(t);for(let c=0;c<3;c++){const a=(n.nums[c]??0)-(s.nums[c]??0);if(a)return a<0?-1:1}if(n.pre===s.pre)return 0;if(n.pre===void 0)return 1;if(s.pre===void 0)return-1;const p=n.pre.split("."),l=s.pre.split(".");for(let c=0;c<Math.max(p.length,l.length);c++){const a=p[c],m=l[c];if(a===void 0)return-1;if(m===void 0)return 1;if(a===m)continue;const h=/^\d+$/.test(a),O=/^\d+$/.test(m);return h&&O?Number(a)<Number(m)?-1:1:h!==O?h?-1:1:a<m?-1:1}return 0}i(compareLensVersions,"compareLensVersions"),o(compareLensVersions,"compareLensVersions");export function storedVersionNames(r){let t;try{t=x(u(r,"versions"))}catch{return[]}return t.filter(e=>g.test(e)&&storedLensmcp(r,e)!==void 0).sort(compareLensVersions)}i(storedVersionNames,"storedVersionNames"),o(storedVersionNames,"storedVersionNames");const M=o(r=>{try{return process.kill(r,0),!0}catch(t){return t.code==="EPERM"}},"pidAlive");export function storeForwardedRunning(r){const t=new Map,e=u(r,"versions",".running");let n;try{n=x(e)}catch{return t}for(const s of n){const p=Number(s);if(!Number.isInteger(p)||p<=0||!M(p))continue;let l;try{l=y(u(e,s),"utf8").trim()}catch{continue}g.test(l)&&t.set(l,[...t.get(l)??[],p])}return t}i(storeForwardedRunning,"storeForwardedRunning"),o(storeForwardedRunning,"storeForwardedRunning");export function linkedCheckout(r){if(!v(u(r,"package.json")))return!1;const t=d(r).split(f);return t[t.length-1]!=="lensmcp"||t[t.length-2]!=="node_modules"}i(linkedCheckout,"linkedCheckout"),o(linkedCheckout,"linkedCheckout");export function storeFirst(r,t=process.env,e=process.argv[1]){const n=storeOwnOrCurrent(e,t);return!n||r&&linkedCheckout(r)?r?[r]:[]:r?[n.pkg,r]:[n.pkg]}i(storeFirst,"storeFirst"),o(storeFirst,"storeFirst");export 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 ';export function storeFirstMcpEntry(r){return{command:"sh",args:["-c",`${STORE_FIRST_MCP}${r.join(" ")}`]}}i(storeFirstMcpEntry,"storeFirstMcpEntry"),o(storeFirstMcpEntry,"storeFirstMcpEntry");export function storeFirstFallback(r){if(!r||typeof r!="object"||Array.isArray(r))return;const{command:t,args:e,...n}=r;if(t!=="sh"||Object.keys(n).length>0||!Array.isArray(e)||e.length!==2||e[0]!=="-c")return;const s=e[1];if(typeof s!="string"||!s.startsWith(STORE_FIRST_MCP))return;const p=s.slice(STORE_FIRST_MCP.length).split(" ");return p.every(l=>/^[\w@.-]+$/.test(l))?p:void 0}i(storeFirstFallback,"storeFirstFallback"),o(storeFirstFallback,"storeFirstFallback");
package/lib/patterns.js CHANGED
@@ -1 +1 @@
1
- "use strict";var g=Object.defineProperty;var p=(e,n)=>g(e,"name",{value:n,configurable:!0});var I=Object.defineProperty,u=p((e,n)=>I(e,"name",{value:n,configurable:!0}),"p"),v=Object.defineProperty,f=u((e,n)=>v(e,"name",{value:n,configurable:!0}),"u");export function loopDbCalls(e){const n=typeof e.dbCallsInsideLoop=="number"?e.dbCallsInsideLoop:0;return e.stream===!0&&typeof e.dbBurst=="number"?Math.min(n,e.dbBurst):n}p(loopDbCalls,"loopDbCalls"),u(loopDbCalls,"loopDbCalls"),f(loopDbCalls,"loopDbCalls");export const DB_WORK_CLASSES=["loop","repeated-read","sequential"];export function dbLoopClass(e){return DB_WORK_CLASSES.includes(e.class)?e.class:void 0}p(dbLoopClass,"dbLoopClass"),u(dbLoopClass,"dbLoopClass"),f(dbLoopClass,"dbLoopClass");export const loopRepeatsLimit=f(e=>Math.min(e.nPlusOne,e.dbInLoop+1),"loopRepeatsLimit");export function dbLoopBreaks(e,n){const d=dbLoopClass(e),i=loopDbCalls(e);return d==="loop"?i>=loopRepeatsLimit(n):d==="repeated-read"?i>n.dbInLoop:!1}p(dbLoopBreaks,"dbLoopBreaks"),u(dbLoopBreaks,"dbLoopBreaks"),f(dbLoopBreaks,"dbLoopBreaks");export function detectDbInLoop(e,n={}){const d=n.threshold??5,i={dbInLoop:d,nPlusOne:n.nPlusOne??3},o=[];for(const r of e){const t=r.raw??null;if(t?.kind!=="loop"||!t.loop||!dbLoopBreaks(t.loop,i))continue;const s=loopDbCalls(t.loop),a=t.loop.dbCallsInsideLoop??0,l=s<a,m=dbLoopClass(t.loop),c=typeof t.loop.calls=="number"&&typeof t.loop.distinctStatements=="number"?` \u2014 ${t.loop.calls} DB calls, ${t.loop.distinctStatements} statements`:"";o.push({kind:"db-in-loop",severity:"warning",title:l?`one statement ${s}\xD7 within two seconds of a stream's loop (${a} over its life)${c}`:`${m==="loop"?"loop":"repeated read"}: one statement ${s}\xD7 inside one method${c}`,evidence:[r.id],details:{class:m,dbCallsInsideLoop:a,...l?{dbBurst:s,stream:!0}:{},...t.loop.sqlId?{sqlId:t.loop.sqlId}:{},...typeof t.loop.calls=="number"?{calls:t.loop.calls}:{},...typeof t.loop.distinctStatements=="number"?{distinctStatements:t.loop.distinctStatements}:{},...typeof t.loop.distinctValues=="number"?{distinctValues:t.loop.distinctValues}:{},iterations:t.loop.iterations,durationMs:t.loop.durationMs,threshold:d},detectedAt:r.timestamp})}return o}p(detectDbInLoop,"detectDbInLoop"),u(detectDbInLoop,"detectDbInLoop"),f(detectDbInLoop,"detectDbInLoop");const j=new Set(["egress","db-query","redis-op","ai-call"]);function y(e){const n=e.raw??null;if(!n||typeof n.kind!="string"||!j.has(n.kind))return;const d=typeof n.durationMs=="number"?n.durationMs:void 0;if(d===void 0)return;const i=typeof n.startedAt=="number"?n.startedAt:e.timestamp-d,o=e.context??{};return{id:e.id,start:i,end:i+d,label:e.title,...typeof o.requestId=="string"?{requestId:o.requestId}:{},...typeof n.project=="string"?{project:n.project}:typeof o.projectName=="string"?{project:o.projectName}:{}}}p(y,"y"),u(y,"M"),f(y,"timedCall");function w(e){const n=e.raw??null,d=n?.kind==="span"?n.span:void 0;if(!d||typeof d.name!="string"||d.name.startsWith("nest.request "))return;const i=typeof d.durationMs=="number"?d.durationMs:void 0;if(i===void 0||i<=0)return;const o=typeof d.startTime=="number"?d.startTime:e.timestamp-i,r=e.context??{};return{id:e.id,start:o,end:o+i,label:d.name,...typeof r.requestId=="string"?{requestId:r.requestId}:{},...typeof n?.project=="string"?{project:n.project}:typeof r.projectName=="string"?{project:r.projectName}:{}}}p(w,"M"),u(w,"g"),f(w,"timedSpan");export function abandonedAwaitOf(e,n,d={}){const i=d.thresholdMs??250,o=y(e);if(!o||!o.requestId||o.end-o.start<i)return;let r;for(const s of n){const a=w(s);!a||a.requestId!==o.requestId||a.project!==void 0&&o.project!==void 0&&a.project!==o.project||a.start>o.start||a.end<=o.start||(!r||a.start>r.start||a.start===r.start&&a.end<r.end)&&(r=a)}if(!r)return;const t=Math.round(o.end-r.end);if(!(t<i))return{kind:"abandoned-await",severity:"warning",title:`${r.label} ended ${t}ms before a call it started had finished (${o.label})`,evidence:[r.id,o.id],details:{span:r.label,call:o.label,ranOnMs:t,spanMs:Math.round(r.end-r.start),callMs:Math.round(o.end-o.start),thresholdMs:i,...o.project?{project:o.project}:{}},detectedAt:e.timestamp}}p(abandonedAwaitOf,"abandonedAwaitOf"),u(abandonedAwaitOf,"abandonedAwaitOf"),f(abandonedAwaitOf,"abandonedAwaitOf");export function detectAbandonedAwait(e,n={}){const d=[];for(const i of e){const o=abandonedAwaitOf(i,e,n);o&&d.push(o)}return d}p(detectAbandonedAwait,"detectAbandonedAwait"),u(detectAbandonedAwait,"detectAbandonedAwait"),f(detectAbandonedAwait,"detectAbandonedAwait");export function detectNPlusOne(e,n={}){const d=n.threshold??3,i=new Map;for(const r of e){const t=r.raw??null;if(t?.kind!=="db-query"||!t.query?.signature)continue;const s=t.query.signature;let a=i.get(s);a||(a=[],i.set(s,a)),a.push(r)}const o=[];for(const[r,t]of i)t.length>=d&&o.push({kind:"n+1-query",severity:"warning",title:`Query repeated ${t.length}\xD7 \u2014 likely N+1`,evidence:t.map(s=>s.id),details:{signature:r,count:t.length,threshold:d},detectedAt:t[t.length-1].timestamp});return o}p(detectNPlusOne,"detectNPlusOne"),u(detectNPlusOne,"detectNPlusOne"),f(detectNPlusOne,"detectNPlusOne");export function detectRenderStorm(e,n={}){const d=n.threshold??5,i=n.windowMs??250,o=new Map;for(const t of e){if(t.source!=="react")continue;const s=t.raw??null;if(s?.kind!=="render"||!s.render?.componentInstanceId)continue;const a=s.render.componentInstanceId;let l=o.get(a);l||(l=[],o.set(a,l)),l.push(t)}const r=[];for(const[t,s]of o){s.sort((l,m)=>l.timestamp-m.timestamp);let a=0;for(let l=0;l<s.length;l++){for(;s[l].timestamp-s[a].timestamp>i;)a++;const m=l-a+1;if(m>d){const c=s.slice(a,l+1),b=c[0].raw.render?.componentName??t;r.push({kind:"render-storm",severity:"warning",title:`${b} rendered ${m}\xD7 in ${i}ms`,evidence:c.map(h=>h.id),details:{componentInstanceId:t,count:m,windowMs:i,threshold:d},detectedAt:c[c.length-1].timestamp});break}}}return r}p(detectRenderStorm,"detectRenderStorm"),u(detectRenderStorm,"detectRenderStorm"),f(detectRenderStorm,"detectRenderStorm");export function findSlowPath(e,n,d){const i=new Map,o=new Set;function r(s){const a=i.get(s);if(a)return a;if(o.has(s))return{path:[s],totalDurationMs:d(s)};o.add(s);const l=d(s),m=n.get(s)??[];let c;for(const h of m){const M=r(h);(!c||M.totalDurationMs>c.totalDurationMs)&&(c=M)}o.delete(s);const b=c?{path:[s,...c.path],totalDurationMs:l+c.totalDurationMs}:{path:[s],totalDurationMs:l};return i.set(s,b),b}p(r,"s"),u(r,"a"),f(r,"best");let t={path:[],totalDurationMs:0};for(const s of e){const a=r(s);a.totalDurationMs>t.totalDurationMs&&(t=a)}return t}p(findSlowPath,"findSlowPath"),u(findSlowPath,"findSlowPath"),f(findSlowPath,"findSlowPath");
1
+ "use strict";var w=Object.defineProperty;var p=(e,n)=>w(e,"name",{value:n,configurable:!0});var g=Object.defineProperty,u=p((e,n)=>g(e,"name",{value:n,configurable:!0}),"u");export function loopDbCalls(e){const n=typeof e.dbCallsInsideLoop=="number"?e.dbCallsInsideLoop:0;return e.stream===!0&&typeof e.dbBurst=="number"?Math.min(n,e.dbBurst):n}p(loopDbCalls,"loopDbCalls"),u(loopDbCalls,"loopDbCalls");export const DB_WORK_CLASSES=["loop","repeated-read","sequential"];export function dbLoopClass(e){return DB_WORK_CLASSES.includes(e.class)?e.class:void 0}p(dbLoopClass,"dbLoopClass"),u(dbLoopClass,"dbLoopClass");export const loopRepeatsLimit=u(e=>Math.min(e.nPlusOne,e.dbInLoop+1),"loopRepeatsLimit");export function dbLoopBreaks(e,n){const i=dbLoopClass(e),d=loopDbCalls(e);return i==="loop"?d>=loopRepeatsLimit(n):i==="repeated-read"?d>n.dbInLoop:!1}p(dbLoopBreaks,"dbLoopBreaks"),u(dbLoopBreaks,"dbLoopBreaks");export function detectDbInLoop(e,n={}){const i=n.threshold??5,d={dbInLoop:i,nPlusOne:n.nPlusOne??3},o=[];for(const s of e){const t=s.raw??null;if(t?.kind!=="loop"||!t.loop||!dbLoopBreaks(t.loop,d))continue;const r=loopDbCalls(t.loop),a=t.loop.dbCallsInsideLoop??0,l=r<a,f=dbLoopClass(t.loop),c=typeof t.loop.calls=="number"&&typeof t.loop.distinctStatements=="number"?` \u2014 ${t.loop.calls} DB calls, ${t.loop.distinctStatements} statements`:"";o.push({kind:"db-in-loop",severity:"warning",title:l?`one statement ${r}\xD7 within two seconds of a stream's loop (${a} over its life)${c}`:`${f==="loop"?"loop":"repeated read"}: one statement ${r}\xD7 inside one method${c}`,evidence:[s.id],details:{class:f,dbCallsInsideLoop:a,...l?{dbBurst:r,stream:!0}:{},...t.loop.sqlId?{sqlId:t.loop.sqlId}:{},...typeof t.loop.calls=="number"?{calls:t.loop.calls}:{},...typeof t.loop.distinctStatements=="number"?{distinctStatements:t.loop.distinctStatements}:{},...typeof t.loop.distinctValues=="number"?{distinctValues:t.loop.distinctValues}:{},iterations:t.loop.iterations,durationMs:t.loop.durationMs,threshold:i},detectedAt:s.timestamp})}return o}p(detectDbInLoop,"detectDbInLoop"),u(detectDbInLoop,"detectDbInLoop");const I=new Set(["egress","db-query","redis-op","ai-call"]);function y(e){const n=e.raw??null;if(!n||typeof n.kind!="string"||!I.has(n.kind))return;const i=typeof n.durationMs=="number"?n.durationMs:void 0;if(i===void 0)return;const d=typeof n.startedAt=="number"?n.startedAt:e.timestamp-i,o=e.context??{};return{id:e.id,start:d,end:d+i,label:e.title,...typeof o.requestId=="string"?{requestId:o.requestId}:{},...typeof n.project=="string"?{project:n.project}:typeof o.projectName=="string"?{project:o.projectName}:{}}}p(y,"M"),u(y,"timedCall");function M(e){const n=e.raw??null,i=n?.kind==="span"?n.span:void 0;if(!i||typeof i.name!="string"||i.name.startsWith("nest.request "))return;const d=typeof i.durationMs=="number"?i.durationMs:void 0;if(d===void 0||d<=0)return;const o=typeof i.startTime=="number"?i.startTime:e.timestamp-d,s=e.context??{};return{id:e.id,start:o,end:o+d,label:i.name,...typeof s.requestId=="string"?{requestId:s.requestId}:{},...typeof n?.project=="string"?{project:n.project}:typeof s.projectName=="string"?{project:s.projectName}:{}}}p(M,"g"),u(M,"timedSpan");export function abandonedAwaitOf(e,n,i={}){const d=i.thresholdMs??250,o=y(e);if(!o||!o.requestId||o.end-o.start<d)return;let s;for(const r of n){const a=M(r);!a||a.requestId!==o.requestId||a.project!==void 0&&o.project!==void 0&&a.project!==o.project||a.start>o.start||a.end<=o.start||(!s||a.start>s.start||a.start===s.start&&a.end<s.end)&&(s=a)}if(!s)return;const t=Math.round(o.end-s.end);if(!(t<d))return{kind:"abandoned-await",severity:"warning",title:`${s.label} ended ${t}ms before a call it started had finished (${o.label})`,evidence:[s.id,o.id],details:{span:s.label,call:o.label,ranOnMs:t,spanMs:Math.round(s.end-s.start),callMs:Math.round(o.end-o.start),thresholdMs:d,...o.project?{project:o.project}:{}},detectedAt:e.timestamp}}p(abandonedAwaitOf,"abandonedAwaitOf"),u(abandonedAwaitOf,"abandonedAwaitOf");export function detectAbandonedAwait(e,n={}){const i=[];for(const d of e){const o=abandonedAwaitOf(d,e,n);o&&i.push(o)}return i}p(detectAbandonedAwait,"detectAbandonedAwait"),u(detectAbandonedAwait,"detectAbandonedAwait");export function detectNPlusOne(e,n={}){const i=n.threshold??3,d=new Map;for(const s of e){const t=s.raw??null;if(t?.kind!=="db-query"||!t.query?.signature)continue;const r=t.query.signature;let a=d.get(r);a||(a=[],d.set(r,a)),a.push(s)}const o=[];for(const[s,t]of d)t.length>=i&&o.push({kind:"n+1-query",severity:"warning",title:`Query repeated ${t.length}\xD7 \u2014 likely N+1`,evidence:t.map(r=>r.id),details:{signature:s,count:t.length,threshold:i},detectedAt:t[t.length-1].timestamp});return o}p(detectNPlusOne,"detectNPlusOne"),u(detectNPlusOne,"detectNPlusOne");export function detectRenderStorm(e,n={}){const i=n.threshold??5,d=n.windowMs??250,o=new Map;for(const t of e){if(t.source!=="react")continue;const r=t.raw??null;if(r?.kind!=="render"||!r.render?.componentInstanceId)continue;const a=r.render.componentInstanceId;let l=o.get(a);l||(l=[],o.set(a,l)),l.push(t)}const s=[];for(const[t,r]of o){r.sort((l,f)=>l.timestamp-f.timestamp);let a=0;for(let l=0;l<r.length;l++){for(;r[l].timestamp-r[a].timestamp>d;)a++;const f=l-a+1;if(f>i){const c=r.slice(a,l+1),m=c[0].raw.render?.componentName??t;s.push({kind:"render-storm",severity:"warning",title:`${m} rendered ${f}\xD7 in ${d}ms`,evidence:c.map(b=>b.id),details:{componentInstanceId:t,count:f,windowMs:d,threshold:i},detectedAt:c[c.length-1].timestamp});break}}}return s}p(detectRenderStorm,"detectRenderStorm"),u(detectRenderStorm,"detectRenderStorm");export function findSlowPath(e,n,i){const d=new Map,o=new Set;function s(r){const a=d.get(r);if(a)return a;if(o.has(r))return{path:[r],totalDurationMs:i(r)};o.add(r);const l=i(r),f=n.get(r)??[];let c;for(const b of f){const h=s(b);(!c||h.totalDurationMs>c.totalDurationMs)&&(c=h)}o.delete(r);const m=c?{path:[r,...c.path],totalDurationMs:l+c.totalDurationMs}:{path:[r],totalDurationMs:l};return d.set(r,m),m}p(s,"a"),u(s,"best");let t={path:[],totalDurationMs:0};for(const r of e){const a=s(r);a.totalDurationMs>t.totalDurationMs&&(t=a)}return t}p(findSlowPath,"findSlowPath"),u(findSlowPath,"findSlowPath");
@@ -1,2 +1,2 @@
1
- "use strict";var N=Object.defineProperty;var M=(n,o)=>N(n,"name",{value:o,configurable:!0});var A=Object.defineProperty,b=M((n,o)=>A(n,"name",{value:o,configurable:!0}),"M"),Q=Object.defineProperty,v=b((n,o)=>Q(n,"name",{value:o,configurable:!0}),"m");import{dbLoopBreaks as T,dbLoopClass as B,loopDbCalls as D,loopRepeatsLimit as C}from"./patterns.js";import{resolveThresholds as _}from"./thresholds.js";export const SQL_DROPS_KIND="db-dropped",PERFORMANCE_EVENT_KINDS=["server-request","db-query",SQL_DROPS_KIND,"loop","page-visit"];export function performanceLimits(...n){let o={};for(const i of n)i&&(o={...o,...z(i)});const s=_(o);return{slowRouteMs:s.slowRouteMs,slowQueryMs:s.slowQueryMs,nPlusOne:s.nPlusOne,dbInLoop:s.dbInLoop,slowPageMs:s.slowPageMs}}M(performanceLimits,"performanceLimits"),b(performanceLimits,"performanceLimits"),v(performanceLimits,"performanceLimits");function z(n){const o={};for(const[s,i]of Object.entries(n))typeof i=="number"&&Number.isFinite(i)&&i>=0&&(o[s]=i);return o}M(z,"I"),b(z,"F"),v(z,"resolveThresholdsOnly");const y=v(n=>n&&typeof n=="object"?n:{},"obj"),f=v(n=>typeof n=="string"&&n?n:void 0,"str"),g=v(n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,"num"),U=2e3,k=5e3,P=2e4,K=1e3,V=4,G=2e3,H=1e3,X=1024,J=12,Y=200;function R(n){let o=0;for(const[s,i]of n)o=Math.max(o,i+(n.get(s+1)??0));return o}M(R,"W"),b(R,"V"),v(R,"burstOf");const I=v(()=>({count:0,times:[],slow:0,max:0,evidence:[]}),"newTiming");function O(n,o,s,i){if(n.max=Math.max(n.max,o),o>=s&&(n.slow+=1,n.evidence.length<5&&n.evidence.push(i)),n.times.length<U)n.times.push(o);else{let t=0;for(let a=1;a<n.times.length;a++)n.times[a]<n.times[t]&&(t=a);o>n.times[t]&&(n.times[t]=o)}}M(O,"L"),b(O,"k"),v(O,"time");function S(n,o){return n.length?n[Math.min(n.length-1,Math.floor(n.length*o))]:0}M(S,"z"),b(S,"E"),v(S,"percentile");function L(n){const o=[...n.times].sort((s,i)=>s-i);return{count:n.count,timed:n.times.length,p50Ms:Math.round(S(o,.5)),p95Ms:Math.round(S(o,.95)),maxMs:Math.round(n.max),slow:n.slow}}M(L,"O"),b(L,"O"),v(L,"timing");function x(n,o,s){return n.includes("*")?new RegExp(`^${n.split("*").map(i=>i.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`).test(o):s?o===n:o.includes(n)}M(x,"j"),b(x,"S"),v(x,"matches");export class PerformanceWindow{static{M(this,"PerformanceWindow")}static{b(this,"PerformanceWindow")}static{v(this,"PerformanceWindow")}constructor(o,s=[]){this.events=0,this.from=1/0,this.to=0,this.routes=new Map,this.sql=new Map,this.drops={runs:0,slow:0,failed:0},this.pages=new Map,this.open=new Map,this.routeOf=new Map,this.streams=new Set,this.repeated=new Map,this.loops=new Map,this.loopsWaiting=new Map,this.unjudgedLoops=0,this.sqlFiles=new Map,this.sqlUnlocated=new Set,this.routeSql=new Map,this.mostRuns=new Map,this.limits=o,this.waivers=s.filter(i=>typeof i?.why=="string"&&(i.route||i.sql||i.page))}add(o){const s=y(o.raw),i=s.kind;if(i!=="server-request"&&i!=="db-query"&&i!==SQL_DROPS_KIND&&i!=="loop"&&i!=="page-visit")return;this.events+=1,this.from=Math.min(this.from,o.timestamp),this.to=Math.max(this.to,o.timestamp);const t=y(o.context),a=f(t.projectName)??f(s.project),l=f(t.requestId);i==="server-request"?this.request(o,s,a,l):i==="db-query"?this.statement(o,s,a,l):i===SQL_DROPS_KIND?this.dropped(o,s,a):i==="loop"?this.loop(o,s,l):this.page(o,s)}request(o,s,i,t){const a=y(s.request),l=f(a.method)??"?",u=f(a.route)??"?",h=`${l} ${u}`;let p=this.routes.get(h);if(!p){if(this.routes.size>=k)return;p={...I(),method:l,route:u,...i?{project:i}:{},errors:0,streaming:0},this.routes.set(h,p)}p.count+=1;const d=g(a.status);d!==void 0&&d>=500&&(p.errors+=1);const w=g(a.durationMs);if(a.streaming===!0?p.streaming+=1:w!==void 0&&O(p,w,this.limits.slowRouteMs,o.id),t){this.routeOf.set(t,h),this.routeOf.size>P&&this.routeOf.delete(this.routeOf.keys().next().value),a.streaming===!0&&(this.streams.add(t),this.streams.size>P&&this.streams.delete(this.streams.keys().next().value)),this.close(t);const m=this.loopsWaiting.get(t);if(m){this.loopsWaiting.delete(t);for(const $ of m)this.foldLoop(h,$)}}}sqlEntry(o,s,i){let t=this.sql.get(o);if(!t&&this.sql.size<k){t={...I(),failed:0,dropped:0};const a=f(s.sqlName),l=f(s.op),u=f(s.table);a&&(t.name=a),i&&(t.project=i),l&&(t.op=l),u&&(t.table=u),this.sql.set(o,t)}return t}statement(o,s,i,t){const a=f(s.statement)??f(s.query),l=f(s.sqlId)??a?.slice(0,300);if(!l)return;const u=1+Math.max(0,g(s.floodSuppressed)??0),h=this.sqlEntry(l,s,i);if(h){this.located(l,s.site),h.count+=u,!h.text&&a&&(h.text=a.slice(0,300)),s.error!==void 0&&s.error!==null&&(h.failed+=1);const $=g(s.durationMs);$!==void 0&&O(h,$,this.limits.slowQueryMs,o.id)}if(!t)return;let p=this.open.get(t);p||(this.open.size>=P&&this.close(this.open.keys().next().value),p=new Map,this.open.set(t,p));let d=p.get(l);d?d.n+=u:p.set(l,d={n:u,first:o.id,seconds:new Map,values:new Set}),d.values.size<V&&d.values.add(Array.isArray(s.params)?s.params.map(String).join(""):"");const w=Math.floor(o.timestamp/K),m=d.seconds.get(w);m!==void 0?d.seconds.set(w,m+u):d.seconds.size<X&&d.seconds.set(w,u)}located(o,s){const i=(Array.isArray(y(s).frames)?y(s).frames:[]).slice(0,3).map(a=>f(y(a).file)).filter(a=>!!a);if(!i.length){this.sqlUnlocated.add(o);return}let t=this.sqlFiles.get(o);t||this.sqlFiles.set(o,t=new Set);for(const a of i)t.size<J&&t.add(a.slice(0,1024))}dropped(o,s,i){const t=g(s.slowMs)??-1/0,a=v((p,d)=>Math.max(this.limits.slowQueryMs<=t?Math.max(0,g(p.slow)??0):0,d>=this.limits.slowQueryMs?1:0),"slowOf"),l=Array.isArray(s.shapes)?s.shapes:[];for(const p of l){const d=y(p),w=f(d.sqlId),m=Math.max(0,g(d.runs)??0);if(!w||!m)continue;const $=Math.max(0,g(d.maxMs)??0),e=Math.max(0,g(d.failed)??0),r=a(d,$);this.drops.runs+=m,this.drops.slow+=r,this.drops.failed+=e;const c=this.sqlEntry(w,d,i);if(c){if(c.count+=m,c.dropped+=m,c.failed+=e,c.max=Math.max(c.max,$),!c.text){const q=f(d.query);q&&(c.text=q.slice(0,300))}r&&(c.slow+=r,c.evidence.length<5&&c.evidence.push(o.id))}}const u=y(s.overflow),h=Math.max(0,g(u.runs)??0);if(h){const p=Math.max(0,g(u.maxMs)??0);this.drops.runs+=h,this.drops.slow+=a(u,p),this.drops.failed+=Math.max(0,g(u.failed)??0)}}close(o){const s=this.open.get(o);if(!s)return;this.open.delete(o);const i=this.routeOf.get(o),t=i??"a request with no route seen",a=this.streams.delete(o);let l=i?this.routeSql.get(i):void 0;i&&!l&&this.routeSql.size<k&&this.routeSql.set(i,l=new Set);for(const[u,{n:h,first:p,seconds:d,values:w}]of s){const m=a?R(d):h;l&&l.size<Y&&l.add(u);const $=`${t}\0${u}`;if(m>(this.mostRuns.get($)??0)&&(this.mostRuns.has($)||this.mostRuns.size<k*4)&&this.mostRuns.set($,m),m<this.limits.nPlusOne)continue;const e=`${t}\0${u}`,r=this.repeated.get(e)??{route:t,sql:u,worst:0,requests:0,streams:0,varying:0,evidence:[]};r.worst=Math.max(r.worst,m),r.requests+=1,a&&(r.streams+=1),w.size>1&&(r.varying+=1),r.evidence.length<5&&r.evidence.push(p),this.repeated.set(e,r)}}loop(o,s,i){const t=y(s.loop),a=B(t);if(!a){D(t)>this.limits.dbInLoop&&(this.unjudgedLoops+=1);return}if(!T(t,this.limits))return;const l=f(t.method)??/^(?:loop|repeated read) in (\S+) \(/.exec(o.title??"")?.[1]??"?",u={id:o.id,...i?{requestId:i}:{},sql:f(t.sqlId)??"?",site:l,class:a,value:D(t),total:g(t.dbCallsInsideLoop)??0,calls:g(t.calls),distinct:g(t.distinctStatements)},h=i?this.routeOf.get(i):void 0;if(h||!i){this.foldLoop(h??"work outside a request",u);return}let p=this.loopsWaiting.get(i);if(!p){if(this.loopsWaiting.size>=P){const[d,w]=this.loopsWaiting.entries().next().value;this.loopsWaiting.delete(d);for(const m of w)this.foldLoop("a request with no route seen",m)}this.loopsWaiting.set(i,p=[])}p.length<50&&p.push(u)}foldLoop(o,s){const i=`${o}\0${s.sql}\0${s.site}`;let t=this.loops.get(i);if(!t){if(this.loops.size>=G)return;this.loops.set(i,t={route:o,sql:s.sql,site:s.site,class:s.class,worst:0,total:0,requests:new Set,seen:0,evidence:[]})}t.seen+=1,s.requestId&&t.requests.size<H&&t.requests.add(s.requestId),s.class==="loop"&&(t.class="loop"),s.value>t.worst&&(t.worst=s.value,t.total=s.total,s.calls!==void 0&&(t.calls=s.calls),s.distinct!==void 0&&(t.distinct=s.distinct)),t.evidence.length<5&&t.evidence.push(s.id)}page(o,s){if(s.phase!=="ready"||s.cause==="hmr")return;const i=f(s.app)??"?",t=f(s.pattern)??f(s.path)??"?",a=`${i} ${t}`;let l=this.pages.get(a);if(!l){if(this.pages.size>=k)return;l={...I(),app:i,path:t},this.pages.set(a,l)}l.count+=1;const u=s.nav==="hard"?g(s.appReadyMs)??g(s.readyMs):g(s.readyMs);u!==void 0&&O(l,u,this.limits.slowPageMs,o.id)}waiverOf(o){for(const s of this.waivers)if(s.route&&o.route&&x(s.route,o.route,!0)||s.sql&&o.sql&&(x(s.sql,o.sql,!1)||o.sqlText!==void 0&&x(s.sql,o.sqlText,!1))||s.page&&o.page&&x(s.page,o.page,!0))return s.why}report(o){for(const e of[...this.open.keys()])this.close(e);for(const[e,r]of[...this.loopsWaiting]){this.loopsWaiting.delete(e);for(const c of r)this.foldLoop("a request with no route seen",c)}const s=this.limits,i=[],t=v((e,r="runs")=>`p95 ${e.p95Ms} ms, max ${e.maxMs} ms \u2014 ${e.slow} of ${e.timed} ${r} at or above`,"slowWords"),a=[...this.routes.entries()].map(([e,r])=>({key:e,method:r.method,route:r.route,...r.project?{project:r.project}:{},errors:r.errors,streaming:r.streaming,...L(r),evidence:r.evidence}));for(const e of a)e.slow>1&&i.push({breach:{id:`slow-route:${e.key}`,kind:"slow-route",subject:e.key,measured:t(e),limit:`${s.slowRouteMs} ms (slowRouteMs)`,evidence:e.evidence,about:{route:e.key},value:e.p95Ms},about:{route:e.key}});const l=[...this.sql.entries()].map(([e,r])=>({key:e,...r.name?{name:r.name}:{},...r.project?{project:r.project}:{},...r.op?{op:r.op}:{},...r.table?{table:r.table}:{},...r.text?{text:r.text}:{},failed:r.failed,...r.dropped?{dropped:r.dropped}:{},...L(r),evidence:r.evidence}));for(const e of l){const r=e.dropped?`p95 ${e.p95Ms} ms, max ${e.maxMs} ms \u2014 ${e.slow} of ${e.count} runs at or above (${e.dropped} counted from the service's drop record, not timed)`:t(e);e.slow>1&&i.push({breach:{id:`slow-query:${e.key}`,kind:"slow-query",subject:e.name??e.key,measured:r,limit:`${s.slowQueryMs} ms (slowQueryMs)`,evidence:e.evidence,about:{sql:e.key},value:e.p95Ms},about:{sql:e.key,...e.text?{sqlText:e.text}:{}}})}const u=new Map;for(const e of this.loops.values()){const r=`${e.route}\0${e.sql}`;this.repeated.has(r)&&u.set(r,[...u.get(r)??[],e])}const h=v(e=>e.calls!==void 0&&e.distinct!==void 0?` (its ${e.calls} DB calls, ${e.distinct} statement${e.distinct===1?"":"s"})`:"","ofCalls");for(const e of this.repeated.values()){const r=this.sql.get(e.sql),c=(u.get(`${e.route}\0${e.sql}`)??[]).sort((j,F)=>F.worst-j.worst),q=c[0],W=e.varying>0||c.some(j=>j.class==="loop")?"loop":"repeated-read",E=q?`; in ${c.map(j=>j.site).slice(0,3).join(", ")}${h(q)}`:"";i.push({breach:{id:`n+1-query:${e.route}:${e.sql}`,kind:"n+1-query",subject:`${e.route} runs ${r?.name??e.sql}`,measured:`${e.streams===e.requests?`up to ${e.worst}\xD7 in one burst of a stream, within two seconds (${e.streams} stream${e.streams===1?"":"s"})`:`up to ${e.worst}\xD7 in one request (${e.requests} request${e.requests===1?"":"s"})`}, ${W==="loop"?"varying values":"the same values each time"}${E}`,limit:`fewer than ${s.nPlusOne} (nPlusOne)`,evidence:e.evidence,about:{route:e.route,sql:e.sql},value:Math.max(e.worst,q?.worst??0),class:W,requests:e.requests,...q?{site:q.site,...q.calls!==void 0?{calls:q.calls}:{},...q.distinct!==void 0?{distinctStatements:q.distinct}:{}}:{}},about:{route:e.route,sql:e.sql,...r?.text?{sqlText:r.text}:{}}})}for(const e of this.loops.values()){if(this.repeated.has(`${e.route}\0${e.sql}`))continue;const r=this.sql.get(e.sql),c=e.requests.size,q=e.worst<e.total?`up to ${e.worst}\xD7 within two seconds of one call of a stream's ${e.site} (${e.total} over its life)`:`up to ${e.worst}\xD7 in one call of ${e.site}`;i.push({breach:{id:`db-in-loop:${e.route}:${e.sql}:${e.site}`,kind:"db-in-loop",subject:`${e.route} runs ${r?.name??e.sql} in ${e.site}`,measured:`${e.class==="loop"?"loop":"repeated read"}: one statement ${q}, ${e.class==="loop"?"varying values":"the same values each time"}${h(e)} \u2014 ${e.seen} time${e.seen===1?"":"s"}${c?`, \xD7${c} request${c===1?"":"s"}`:""}`,limit:e.class==="loop"?`fewer than ${C(s)} repeats of one statement in one method (nPlusOne)`:`at most ${s.dbInLoop} repeats of one statement with the same values (dbInLoop)`,evidence:e.evidence,about:{route:e.route,sql:e.sql},value:e.worst,class:e.class,requests:c,site:e.site,...e.calls!==void 0?{calls:e.calls}:{},...e.distinct!==void 0?{distinctStatements:e.distinct}:{}},about:{route:e.route,sql:e.sql,...r?.text?{sqlText:r.text}:{}}})}const p=[...this.pages.entries()].map(([e,r])=>({key:e,app:r.app,path:r.path,...L(r),evidence:r.evidence}));for(const e of p)e.slow>1&&i.push({breach:{id:`slow-page:${e.key}`,kind:"slow-page",subject:e.key,measured:t(e,"visits"),limit:`${s.slowPageMs} ms (slowPageMs)`,evidence:e.evidence,about:{page:e.key},value:e.p95Ms},about:{page:e.path}});const d=[],w=[];for(const{breach:e,about:r}of i){const c=this.waiverOf(r);c?w.push({...e,waived:c}):d.push(e)}const m=v(e=>{const{evidence:r,...c}=e;return c},"strip"),$=this.routes.size+this.sql.size+this.pages.size+this.drops.runs>0;return{window:o??{from:Number.isFinite(this.from)?this.from:0,to:this.to},events:this.events,limits:{...s},verdict:d.length?"fail":$?"pass":"unmeasured",breaches:d,waived:w,...this.drops.runs?{dropped:{...this.drops}}:{},...this.unjudgedLoops?{unjudgedLoops:this.unjudgedLoops}:{},routes:a.map(m).sort((e,r)=>r.p95Ms-e.p95Ms),sql:l.map(m).sort((e,r)=>r.p95Ms-e.p95Ms),pages:p.map(m).sort((e,r)=>r.p95Ms-e.p95Ms)}}locate(o){if(!o||o.page)return;const s=v(a=>this.sqlUnlocated.has(a)||!this.sqlFiles.get(a)?.size?void 0:[...this.sqlFiles.get(a)],"ofSql");if(o.sql)return s(o.sql);if(!o.route)return;const i=this.routeSql.get(o.route);if(!i?.size)return;const t=new Set;for(const a of i){const l=s(a);if(!l)return;for(const u of l)t.add(u)}return[...t]}baseline(o){const s=this.report(o),i={};for(const t of this.loops.values()){const a=`${t.route}\0${t.sql}`;t.worst>(i[a]??0)&&(i[a]=t.worst)}return{limits:{...this.limits},window:s.window,events:s.events,routes:Object.fromEntries(s.routes.filter(t=>t.timed).map(t=>[t.key,t.p95Ms])),sql:Object.fromEntries(s.sql.filter(t=>t.timed).map(t=>[t.key,t.p95Ms])),pages:Object.fromEntries(s.pages.filter(t=>t.timed).map(t=>[t.key,t.p95Ms])),repeats:Object.fromEntries(this.mostRuns),loops:i}}}export function describePerformance(n,o=12){const s=n.limits,i=[n.verdict==="unmeasured"?"Performance: unmeasured \u2014 no request, statement or page ran in the window.":`Performance: ${n.verdict==="pass"?"PASS":`FAIL \u2014 ${n.breaches.length} breach${n.breaches.length===1?"":"es"}`} over ${n.routes.length} route${n.routes.length===1?"":"s"}, ${n.sql.length} statement${n.sql.length===1?"":"s"}, ${n.pages.length} page${n.pages.length===1?"":"s"} (limits: route ${s.slowRouteMs} ms, query ${s.slowQueryMs} ms, N+1 ${s.nPlusOne}, DB in a loop ${s.dbInLoop}, page ${s.slowPageMs} ms).`],t=n.dropped;t&&i.push(`${t.runs} statement run${t.runs===1?"":"s"} reached the lens only as counts (the services' flood guards): ${t.slow} slow, ${t.failed} failed \u2014 counted above, not in the percentiles.`);for(const a of n.breaches.slice(0,o))i.push(`- ${a.kind}${a.class?` [${a.class}]`:""} \xB7 ${a.subject}: ${a.measured}; limit ${a.limit}`);return n.breaches.length>o&&i.push(`- \u2026 ${n.breaches.length-o} more`),n.unjudgedLoops&&i.push(`${n.unjudgedLoops} loop report${n.unjudgedLoops===1?"":"s"} from an older @lensmcp/nest-instrumentation not judged: it counted every DB call of a method, so it could not tell a loop from straight-line code (N+1s are still judged per request).`),n.waived.length&&i.push(`Waived by .lensmcp/team/performance.json: ${n.waived.map(a=>`${a.kind} \xB7 ${a.subject} (${a.waived})`).slice(0,o).join("; ")}`),i.join(`
2
- `)}M(describePerformance,"describePerformance"),b(describePerformance,"describePerformance"),v(describePerformance,"describePerformance");
1
+ "use strict";var N=Object.defineProperty;var M=(r,o)=>N(r,"name",{value:o,configurable:!0});var F=Object.defineProperty,w=M((r,o)=>F(r,"name",{value:o,configurable:!0}),"m");import{dbLoopBreaks as A,dbLoopClass as Q,loopDbCalls as R,loopRepeatsLimit as T}from"./patterns.js";import{resolveThresholds as B}from"./thresholds.js";export const SQL_DROPS_KIND="db-dropped",PERFORMANCE_EVENT_KINDS=["server-request","db-query",SQL_DROPS_KIND,"loop","page-visit"];export function performanceLimits(...r){let o={};for(const i of r)i&&(o={...o,...I(i)});const s=B(o);return{slowRouteMs:s.slowRouteMs,slowQueryMs:s.slowQueryMs,nPlusOne:s.nPlusOne,dbInLoop:s.dbInLoop,slowPageMs:s.slowPageMs}}M(performanceLimits,"performanceLimits"),w(performanceLimits,"performanceLimits");function I(r){const o={};for(const[s,i]of Object.entries(r))typeof i=="number"&&Number.isFinite(i)&&i>=0&&(o[s]=i);return o}M(I,"F"),w(I,"resolveThresholdsOnly");const b=w(r=>r&&typeof r=="object"?r:{},"obj"),f=w(r=>typeof r=="string"&&r?r:void 0,"str"),g=w(r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,"num"),C=2e3,x=5e3,k=2e4,_=1e3,U=4,K=2e3,V=1e3,X=1024,G=12,H=200;function W(r){let o=0;for(const[s,i]of r)o=Math.max(o,i+(r.get(s+1)??0));return o}M(W,"V"),w(W,"burstOf");const S=w(()=>({count:0,times:[],slow:0,max:0,evidence:[]}),"newTiming");function L(r,o,s,i){if(r.max=Math.max(r.max,o),o>=s&&(r.slow+=1,r.evidence.length<5&&r.evidence.push(i)),r.times.length<C)r.times.push(o);else{let t=0;for(let n=1;n<r.times.length;n++)r.times[n]<r.times[t]&&(t=n);o>r.times[t]&&(r.times[t]=o)}}M(L,"k"),w(L,"time");function z(r,o){return r.length?r[Math.min(r.length-1,Math.floor(r.length*o))]:0}M(z,"E"),w(z,"percentile");function O(r){const o=[...r.times].sort((s,i)=>s-i);return{count:r.count,timed:r.times.length,p50Ms:Math.round(z(o,.5)),p95Ms:Math.round(z(o,.95)),maxMs:Math.round(r.max),slow:r.slow}}M(O,"O"),w(O,"timing");function j(r,o,s){return r.includes("*")?new RegExp(`^${r.split("*").map(i=>i.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`).test(o):s?o===r:o.includes(r)}M(j,"S"),w(j,"matches");export class PerformanceWindow{static{M(this,"PerformanceWindow")}static{w(this,"PerformanceWindow")}constructor(o,s=[]){this.events=0,this.from=1/0,this.to=0,this.routes=new Map,this.sql=new Map,this.drops={runs:0,slow:0,failed:0},this.pages=new Map,this.open=new Map,this.routeOf=new Map,this.streams=new Set,this.repeated=new Map,this.loops=new Map,this.loopsWaiting=new Map,this.unjudgedLoops=0,this.sqlFiles=new Map,this.sqlUnlocated=new Set,this.routeSql=new Map,this.mostRuns=new Map,this.limits=o,this.waivers=s.filter(i=>typeof i?.why=="string"&&(i.route||i.sql||i.page))}add(o){const s=b(o.raw),i=s.kind;if(i!=="server-request"&&i!=="db-query"&&i!==SQL_DROPS_KIND&&i!=="loop"&&i!=="page-visit")return;this.events+=1,this.from=Math.min(this.from,o.timestamp),this.to=Math.max(this.to,o.timestamp);const t=b(o.context),n=f(t.projectName)??f(s.project),l=f(t.requestId);i==="server-request"?this.request(o,s,n,l):i==="db-query"?this.statement(o,s,n,l):i===SQL_DROPS_KIND?this.dropped(o,s,n):i==="loop"?this.loop(o,s,l):this.page(o,s)}request(o,s,i,t){const n=b(s.request),l=f(n.method)??"?",u=f(n.route)??"?",h=`${l} ${u}`;let p=this.routes.get(h);if(!p){if(this.routes.size>=x)return;p={...S(),method:l,route:u,...i?{project:i}:{},errors:0,streaming:0},this.routes.set(h,p)}p.count+=1;const d=g(n.status);d!==void 0&&d>=500&&(p.errors+=1);const v=g(n.durationMs);if(n.streaming===!0?p.streaming+=1:v!==void 0&&L(p,v,this.limits.slowRouteMs,o.id),t){this.routeOf.set(t,h),this.routeOf.size>k&&this.routeOf.delete(this.routeOf.keys().next().value),n.streaming===!0&&(this.streams.add(t),this.streams.size>k&&this.streams.delete(this.streams.keys().next().value)),this.close(t);const m=this.loopsWaiting.get(t);if(m){this.loopsWaiting.delete(t);for(const $ of m)this.foldLoop(h,$)}}}sqlEntry(o,s,i){let t=this.sql.get(o);if(!t&&this.sql.size<x){t={...S(),failed:0,dropped:0};const n=f(s.sqlName),l=f(s.op),u=f(s.table);n&&(t.name=n),i&&(t.project=i),l&&(t.op=l),u&&(t.table=u),this.sql.set(o,t)}return t}statement(o,s,i,t){const n=f(s.statement)??f(s.query),l=f(s.sqlId)??n?.slice(0,300);if(!l)return;const u=1+Math.max(0,g(s.floodSuppressed)??0),h=this.sqlEntry(l,s,i);if(h){this.located(l,s.site),h.count+=u,!h.text&&n&&(h.text=n.slice(0,300)),s.error!==void 0&&s.error!==null&&(h.failed+=1);const $=g(s.durationMs);$!==void 0&&L(h,$,this.limits.slowQueryMs,o.id)}if(!t)return;let p=this.open.get(t);p||(this.open.size>=k&&this.close(this.open.keys().next().value),p=new Map,this.open.set(t,p));let d=p.get(l);d?d.n+=u:p.set(l,d={n:u,first:o.id,seconds:new Map,values:new Set}),d.values.size<U&&d.values.add(Array.isArray(s.params)?s.params.map(String).join(""):"");const v=Math.floor(o.timestamp/_),m=d.seconds.get(v);m!==void 0?d.seconds.set(v,m+u):d.seconds.size<X&&d.seconds.set(v,u)}located(o,s){const i=(Array.isArray(b(s).frames)?b(s).frames:[]).slice(0,3).map(n=>f(b(n).file)).filter(n=>!!n);if(!i.length){this.sqlUnlocated.add(o);return}let t=this.sqlFiles.get(o);t||this.sqlFiles.set(o,t=new Set);for(const n of i)t.size<G&&t.add(n.slice(0,1024))}dropped(o,s,i){const t=g(s.slowMs)??-1/0,n=w((p,d)=>Math.max(this.limits.slowQueryMs<=t?Math.max(0,g(p.slow)??0):0,d>=this.limits.slowQueryMs?1:0),"slowOf"),l=Array.isArray(s.shapes)?s.shapes:[];for(const p of l){const d=b(p),v=f(d.sqlId),m=Math.max(0,g(d.runs)??0);if(!v||!m)continue;const $=Math.max(0,g(d.maxMs)??0),e=Math.max(0,g(d.failed)??0),a=n(d,$);this.drops.runs+=m,this.drops.slow+=a,this.drops.failed+=e;const c=this.sqlEntry(v,d,i);if(c){if(c.count+=m,c.dropped+=m,c.failed+=e,c.max=Math.max(c.max,$),!c.text){const q=f(d.query);q&&(c.text=q.slice(0,300))}a&&(c.slow+=a,c.evidence.length<5&&c.evidence.push(o.id))}}const u=b(s.overflow),h=Math.max(0,g(u.runs)??0);if(h){const p=Math.max(0,g(u.maxMs)??0);this.drops.runs+=h,this.drops.slow+=n(u,p),this.drops.failed+=Math.max(0,g(u.failed)??0)}}close(o){const s=this.open.get(o);if(!s)return;this.open.delete(o);const i=this.routeOf.get(o),t=i??"a request with no route seen",n=this.streams.delete(o);let l=i?this.routeSql.get(i):void 0;i&&!l&&this.routeSql.size<x&&this.routeSql.set(i,l=new Set);for(const[u,{n:h,first:p,seconds:d,values:v}]of s){const m=n?W(d):h;l&&l.size<H&&l.add(u);const $=`${t}\0${u}`;if(m>(this.mostRuns.get($)??0)&&(this.mostRuns.has($)||this.mostRuns.size<x*4)&&this.mostRuns.set($,m),m<this.limits.nPlusOne)continue;const e=`${t}\0${u}`,a=this.repeated.get(e)??{route:t,sql:u,worst:0,requests:0,streams:0,varying:0,evidence:[]};a.worst=Math.max(a.worst,m),a.requests+=1,n&&(a.streams+=1),v.size>1&&(a.varying+=1),a.evidence.length<5&&a.evidence.push(p),this.repeated.set(e,a)}}loop(o,s,i){const t=b(s.loop),n=Q(t);if(!n){R(t)>this.limits.dbInLoop&&(this.unjudgedLoops+=1);return}if(!A(t,this.limits))return;const l=f(t.method)??/^(?:loop|repeated read) in (\S+) \(/.exec(o.title??"")?.[1]??"?",u={id:o.id,...i?{requestId:i}:{},sql:f(t.sqlId)??"?",site:l,class:n,value:R(t),total:g(t.dbCallsInsideLoop)??0,calls:g(t.calls),distinct:g(t.distinctStatements)},h=i?this.routeOf.get(i):void 0;if(h||!i){this.foldLoop(h??"work outside a request",u);return}let p=this.loopsWaiting.get(i);if(!p){if(this.loopsWaiting.size>=k){const[d,v]=this.loopsWaiting.entries().next().value;this.loopsWaiting.delete(d);for(const m of v)this.foldLoop("a request with no route seen",m)}this.loopsWaiting.set(i,p=[])}p.length<50&&p.push(u)}foldLoop(o,s){const i=`${o}\0${s.sql}\0${s.site}`;let t=this.loops.get(i);if(!t){if(this.loops.size>=K)return;this.loops.set(i,t={route:o,sql:s.sql,site:s.site,class:s.class,worst:0,total:0,requests:new Set,seen:0,evidence:[]})}t.seen+=1,s.requestId&&t.requests.size<V&&t.requests.add(s.requestId),s.class==="loop"&&(t.class="loop"),s.value>t.worst&&(t.worst=s.value,t.total=s.total,s.calls!==void 0&&(t.calls=s.calls),s.distinct!==void 0&&(t.distinct=s.distinct)),t.evidence.length<5&&t.evidence.push(s.id)}page(o,s){if(s.phase!=="ready"||s.cause==="hmr")return;const i=f(s.app)??"?",t=f(s.pattern)??f(s.path)??"?",n=`${i} ${t}`;let l=this.pages.get(n);if(!l){if(this.pages.size>=x)return;l={...S(),app:i,path:t},this.pages.set(n,l)}l.count+=1;const u=s.nav==="hard"?g(s.appReadyMs)??g(s.readyMs):g(s.readyMs);u!==void 0&&L(l,u,this.limits.slowPageMs,o.id)}waiverOf(o){for(const s of this.waivers)if(s.route&&o.route&&j(s.route,o.route,!0)||s.sql&&o.sql&&(j(s.sql,o.sql,!1)||o.sqlText!==void 0&&j(s.sql,o.sqlText,!1))||s.page&&o.page&&j(s.page,o.page,!0))return s.why}report(o){for(const e of[...this.open.keys()])this.close(e);for(const[e,a]of[...this.loopsWaiting]){this.loopsWaiting.delete(e);for(const c of a)this.foldLoop("a request with no route seen",c)}const s=this.limits,i=[],t=w((e,a="runs")=>`p95 ${e.p95Ms} ms, max ${e.maxMs} ms \u2014 ${e.slow} of ${e.timed} ${a} at or above`,"slowWords"),n=[...this.routes.entries()].map(([e,a])=>({key:e,method:a.method,route:a.route,...a.project?{project:a.project}:{},errors:a.errors,streaming:a.streaming,...O(a),evidence:a.evidence}));for(const e of n)e.slow>1&&i.push({breach:{id:`slow-route:${e.key}`,kind:"slow-route",subject:e.key,measured:t(e),limit:`${s.slowRouteMs} ms (slowRouteMs)`,evidence:e.evidence,about:{route:e.key},value:e.p95Ms},about:{route:e.key}});const l=[...this.sql.entries()].map(([e,a])=>({key:e,...a.name?{name:a.name}:{},...a.project?{project:a.project}:{},...a.op?{op:a.op}:{},...a.table?{table:a.table}:{},...a.text?{text:a.text}:{},failed:a.failed,...a.dropped?{dropped:a.dropped}:{},...O(a),evidence:a.evidence}));for(const e of l){const a=e.dropped?`p95 ${e.p95Ms} ms, max ${e.maxMs} ms \u2014 ${e.slow} of ${e.count} runs at or above (${e.dropped} counted from the service's drop record, not timed)`:t(e);e.slow>1&&i.push({breach:{id:`slow-query:${e.key}`,kind:"slow-query",subject:e.name??e.key,measured:a,limit:`${s.slowQueryMs} ms (slowQueryMs)`,evidence:e.evidence,about:{sql:e.key},value:e.p95Ms},about:{sql:e.key,...e.text?{sqlText:e.text}:{}}})}const u=new Map;for(const e of this.loops.values()){const a=`${e.route}\0${e.sql}`;this.repeated.has(a)&&u.set(a,[...u.get(a)??[],e])}const h=w(e=>e.calls!==void 0&&e.distinct!==void 0?` (its ${e.calls} DB calls, ${e.distinct} statement${e.distinct===1?"":"s"})`:"","ofCalls");for(const e of this.repeated.values()){const a=this.sql.get(e.sql),c=(u.get(`${e.route}\0${e.sql}`)??[]).sort((y,E)=>E.worst-y.worst),q=c[0],P=e.varying>0||c.some(y=>y.class==="loop")?"loop":"repeated-read",D=q?`; in ${c.map(y=>y.site).slice(0,3).join(", ")}${h(q)}`:"";i.push({breach:{id:`n+1-query:${e.route}:${e.sql}`,kind:"n+1-query",subject:`${e.route} runs ${a?.name??e.sql}`,measured:`${e.streams===e.requests?`up to ${e.worst}\xD7 in one burst of a stream, within two seconds (${e.streams} stream${e.streams===1?"":"s"})`:`up to ${e.worst}\xD7 in one request (${e.requests} request${e.requests===1?"":"s"})`}, ${P==="loop"?"varying values":"the same values each time"}${D}`,limit:`fewer than ${s.nPlusOne} (nPlusOne)`,evidence:e.evidence,about:{route:e.route,sql:e.sql},value:Math.max(e.worst,q?.worst??0),class:P,requests:e.requests,...q?{site:q.site,...q.calls!==void 0?{calls:q.calls}:{},...q.distinct!==void 0?{distinctStatements:q.distinct}:{}}:{}},about:{route:e.route,sql:e.sql,...a?.text?{sqlText:a.text}:{}}})}for(const e of this.loops.values()){if(this.repeated.has(`${e.route}\0${e.sql}`))continue;const a=this.sql.get(e.sql),c=e.requests.size,q=e.worst<e.total?`up to ${e.worst}\xD7 within two seconds of one call of a stream's ${e.site} (${e.total} over its life)`:`up to ${e.worst}\xD7 in one call of ${e.site}`;i.push({breach:{id:`db-in-loop:${e.route}:${e.sql}:${e.site}`,kind:"db-in-loop",subject:`${e.route} runs ${a?.name??e.sql} in ${e.site}`,measured:`${e.class==="loop"?"loop":"repeated read"}: one statement ${q}, ${e.class==="loop"?"varying values":"the same values each time"}${h(e)} \u2014 ${e.seen} time${e.seen===1?"":"s"}${c?`, \xD7${c} request${c===1?"":"s"}`:""}`,limit:e.class==="loop"?`fewer than ${T(s)} repeats of one statement in one method (nPlusOne)`:`at most ${s.dbInLoop} repeats of one statement with the same values (dbInLoop)`,evidence:e.evidence,about:{route:e.route,sql:e.sql},value:e.worst,class:e.class,requests:c,site:e.site,...e.calls!==void 0?{calls:e.calls}:{},...e.distinct!==void 0?{distinctStatements:e.distinct}:{}},about:{route:e.route,sql:e.sql,...a?.text?{sqlText:a.text}:{}}})}const p=[...this.pages.entries()].map(([e,a])=>({key:e,app:a.app,path:a.path,...O(a),evidence:a.evidence}));for(const e of p)e.slow>1&&i.push({breach:{id:`slow-page:${e.key}`,kind:"slow-page",subject:e.key,measured:t(e,"visits"),limit:`${s.slowPageMs} ms (slowPageMs)`,evidence:e.evidence,about:{page:e.key},value:e.p95Ms},about:{page:e.path}});const d=[],v=[];for(const{breach:e,about:a}of i){const c=this.waiverOf(a);c?v.push({...e,waived:c}):d.push(e)}const m=w(e=>{const{evidence:a,...c}=e;return c},"strip"),$=this.routes.size+this.sql.size+this.pages.size+this.drops.runs>0;return{window:o??{from:Number.isFinite(this.from)?this.from:0,to:this.to},events:this.events,limits:{...s},verdict:d.length?"fail":$?"pass":"unmeasured",breaches:d,waived:v,...this.drops.runs?{dropped:{...this.drops}}:{},...this.unjudgedLoops?{unjudgedLoops:this.unjudgedLoops}:{},routes:n.map(m).sort((e,a)=>a.p95Ms-e.p95Ms),sql:l.map(m).sort((e,a)=>a.p95Ms-e.p95Ms),pages:p.map(m).sort((e,a)=>a.p95Ms-e.p95Ms)}}locate(o){if(!o||o.page)return;const s=w(n=>this.sqlUnlocated.has(n)||!this.sqlFiles.get(n)?.size?void 0:[...this.sqlFiles.get(n)],"ofSql");if(o.sql)return s(o.sql);if(!o.route)return;const i=this.routeSql.get(o.route);if(!i?.size)return;const t=new Set;for(const n of i){const l=s(n);if(!l)return;for(const u of l)t.add(u)}return[...t]}baseline(o){const s=this.report(o),i={};for(const t of this.loops.values()){const n=`${t.route}\0${t.sql}`;t.worst>(i[n]??0)&&(i[n]=t.worst)}return{limits:{...this.limits},window:s.window,events:s.events,routes:Object.fromEntries(s.routes.filter(t=>t.timed).map(t=>[t.key,t.p95Ms])),sql:Object.fromEntries(s.sql.filter(t=>t.timed).map(t=>[t.key,t.p95Ms])),pages:Object.fromEntries(s.pages.filter(t=>t.timed).map(t=>[t.key,t.p95Ms])),repeats:Object.fromEntries(this.mostRuns),loops:i}}}export function describePerformance(r,o=12){const s=r.limits,i=[r.verdict==="unmeasured"?"Performance: unmeasured \u2014 no request, statement or page ran in the window.":`Performance: ${r.verdict==="pass"?"PASS":`FAIL \u2014 ${r.breaches.length} breach${r.breaches.length===1?"":"es"}`} over ${r.routes.length} route${r.routes.length===1?"":"s"}, ${r.sql.length} statement${r.sql.length===1?"":"s"}, ${r.pages.length} page${r.pages.length===1?"":"s"} (limits: route ${s.slowRouteMs} ms, query ${s.slowQueryMs} ms, N+1 ${s.nPlusOne}, DB in a loop ${s.dbInLoop}, page ${s.slowPageMs} ms).`],t=r.dropped;t&&i.push(`${t.runs} statement run${t.runs===1?"":"s"} reached the lens only as counts (the services' flood guards): ${t.slow} slow, ${t.failed} failed \u2014 counted above, not in the percentiles.`);for(const n of r.breaches.slice(0,o))i.push(`- ${n.kind}${n.class?` [${n.class}]`:""} \xB7 ${n.subject}: ${n.measured}; limit ${n.limit}`);return r.breaches.length>o&&i.push(`- \u2026 ${r.breaches.length-o} more`),r.unjudgedLoops&&i.push(`${r.unjudgedLoops} loop report${r.unjudgedLoops===1?"":"s"} from an older @lensmcp/nest-instrumentation not judged: it counted every DB call of a method, so it could not tell a loop from straight-line code (N+1s are still judged per request).`),r.waived.length&&i.push(`Waived by .lensmcp/team/performance.json: ${r.waived.map(n=>`${n.kind} \xB7 ${n.subject} (${n.waived})`).slice(0,o).join("; ")}`),i.join(`
2
+ `)}M(describePerformance,"describePerformance"),w(describePerformance,"describePerformance");
package/lib/pg-errors.js CHANGED
@@ -1 +1 @@
1
- "use strict";var u=Object.defineProperty;var t=(o,e)=>u(o,"name",{value:e,configurable:!0});var l=Object.defineProperty,a=t((o,e)=>l(o,"name",{value:e,configurable:!0}),"n"),f=Object.defineProperty,p=a((o,e)=>f(o,"name",{value:e,configurable:!0}),"t");export const PG_CONNECT_MEANING={"pool-wait-timeout":"waited for a free connection in the service\u2019s own pool and the wait ran out \u2014 not Postgres refusing","connect-timeout":"opening a new connection to Postgres took longer than the limit","server-full":"Postgres is at its max_connections and refused a new connection","server-unreachable":"nothing answered at the database\u2019s address","pool-ended":"the code used a pool that had already been closed (an app being shut down)","auth-failed":"Postgres refused the user or password"};const r=[["pool-wait-timeout",/timeout exceeded when trying to connect/i],["connect-timeout",/Connection terminated due to connection timeout/i],["server-full",/sorry, too many clients already|remaining connection slots are reserved|too many connections for role/i],["pool-ended",/Cannot use a pool after calling end on the pool/i],["auth-failed",/password authentication failed|no pg_hba\.conf entry/i],["server-unreachable",/connect (ECONNREFUSED|EHOSTUNREACH|ETIMEDOUT)|getaddrinfo ENOTFOUND/i]],s={53300:"server-full","28P01":"auth-failed",28e3:"auth-failed",ECONNREFUSED:"server-unreachable",EHOSTUNREACH:"server-unreachable",ENOTFOUND:"server-unreachable"};export const PG_CONNECT_TEXT=new RegExp(r.map(([,o])=>o.source).join("|"),"i");export function pgConnectReason(o){const e=o,n=typeof e=="object"&&e&&typeof e.code=="string"?e.code:void 0;if(n&&s[n])return s[n];const i=typeof e=="string"?e:typeof e=="object"&&e&&typeof e.message=="string"?e.message:"";for(const[c,d]of r)if(d.test(i))return c}t(pgConnectReason,"pgConnectReason"),a(pgConnectReason,"pgConnectReason"),p(pgConnectReason,"pgConnectReason");
1
+ "use strict";var d=Object.defineProperty;var n=(o,e)=>d(o,"name",{value:e,configurable:!0});var u=Object.defineProperty,l=n((o,e)=>u(o,"name",{value:e,configurable:!0}),"t");export const PG_CONNECT_MEANING={"pool-wait-timeout":"waited for a free connection in the service\u2019s own pool and the wait ran out \u2014 not Postgres refusing","connect-timeout":"opening a new connection to Postgres took longer than the limit","server-full":"Postgres is at its max_connections and refused a new connection","server-unreachable":"nothing answered at the database\u2019s address","pool-ended":"the code used a pool that had already been closed (an app being shut down)","auth-failed":"Postgres refused the user or password"};const a=[["pool-wait-timeout",/timeout exceeded when trying to connect/i],["connect-timeout",/Connection terminated due to connection timeout/i],["server-full",/sorry, too many clients already|remaining connection slots are reserved|too many connections for role/i],["pool-ended",/Cannot use a pool after calling end on the pool/i],["auth-failed",/password authentication failed|no pg_hba\.conf entry/i],["server-unreachable",/connect (ECONNREFUSED|EHOSTUNREACH|ETIMEDOUT)|getaddrinfo ENOTFOUND/i]],r={53300:"server-full","28P01":"auth-failed",28e3:"auth-failed",ECONNREFUSED:"server-unreachable",EHOSTUNREACH:"server-unreachable",ENOTFOUND:"server-unreachable"};export const PG_CONNECT_TEXT=new RegExp(a.map(([,o])=>o.source).join("|"),"i");export function pgConnectReason(o){const e=o,t=typeof e=="object"&&e&&typeof e.code=="string"?e.code:void 0;if(t&&r[t])return r[t];const s=typeof e=="string"?e:typeof e=="object"&&e&&typeof e.message=="string"?e.message:"";for(const[i,c]of a)if(c.test(s))return i}n(pgConnectReason,"pgConnectReason"),l(pgConnectReason,"pgConnectReason");
@@ -1 +1 @@
1
- "use strict";var g=Object.defineProperty;var n=(e,t)=>g(e,"name",{value:t,configurable:!0});var f=Object.defineProperty,o=n((e,t)=>f(e,"name",{value:t,configurable:!0}),"i"),p=Object.defineProperty,i=o((e,t)=>p(e,"name",{value:t,configurable:!0}),"n");export const QUEUE_SIGNALS=["delayed","waiting-children","rate-limited","waiting"];const c=new Map([["DelayedError","delayed"],["WaitingChildrenError","waiting-children"],["WaitingError","waiting"]]);export const RATE_LIMIT_MESSAGE="bullmq:rateLimitExceeded";export function isControlFlowThrow(e){try{if(!e||typeof e!="object")return;const t=e;if(t.message===RATE_LIMIT_MESSAGE)return"rate-limited";const a=typeof t.name=="string"?c.get(t.name):void 0;if(a)return a;for(let r=Object.getPrototypeOf(e),u=0;r&&r!==Error.prototype&&u<8;r=Object.getPrototypeOf(r),u+=1){const l=r.constructor?.name,d=typeof l=="string"?c.get(l):void 0;if(d)return d}}catch{return}}n(isControlFlowThrow,"isControlFlowThrow"),o(isControlFlowThrow,"isControlFlowThrow"),i(isControlFlowThrow,"isControlFlowThrow");export function queueSignalOf(e){return typeof e=="string"&&QUEUE_SIGNALS.includes(e)?e:void 0}n(queueSignalOf,"queueSignalOf"),o(queueSignalOf,"queueSignalOf"),i(queueSignalOf,"queueSignalOf");const s={delayed:"re-delayed","waiting-children":"waiting for its children","rate-limited":"rate-limited",waiting:"back to wait"};export const queueSignalTitle=i(e=>s[e],"queueSignalTitle");const y=i(e=>e<1e3?`${Math.round(e)} ms`:e<6e4?`${Math.round(e/1e3)} s`:e<36e5?`${Math.round(e/6e4)} min`:`${Math.round(e/36e5)} h`,"span");export function queueSignalWords(e,t){return e!=="delayed"?s[e]:`asked to run again${typeof t=="number"&&Number.isFinite(t)&&t>=0?` in ${y(t)}`:""}`}n(queueSignalWords,"queueSignalWords"),o(queueSignalWords,"queueSignalWords"),i(queueSignalWords,"queueSignalWords");
1
+ "use strict";var s=Object.defineProperty;var i=(e,t)=>s(e,"name",{value:t,configurable:!0});var g=Object.defineProperty,n=i((e,t)=>g(e,"name",{value:t,configurable:!0}),"n");export const QUEUE_SIGNALS=["delayed","waiting-children","rate-limited","waiting"];const l=new Map([["DelayedError","delayed"],["WaitingChildrenError","waiting-children"],["WaitingError","waiting"]]);export const RATE_LIMIT_MESSAGE="bullmq:rateLimitExceeded";export function isControlFlowThrow(e){try{if(!e||typeof e!="object")return;const t=e;if(t.message===RATE_LIMIT_MESSAGE)return"rate-limited";const o=typeof t.name=="string"?l.get(t.name):void 0;if(o)return o;for(let r=Object.getPrototypeOf(e),a=0;r&&r!==Error.prototype&&a<8;r=Object.getPrototypeOf(r),a+=1){const u=r.constructor?.name,d=typeof u=="string"?l.get(u):void 0;if(d)return d}}catch{return}}i(isControlFlowThrow,"isControlFlowThrow"),n(isControlFlowThrow,"isControlFlowThrow");export function queueSignalOf(e){return typeof e=="string"&&QUEUE_SIGNALS.includes(e)?e:void 0}i(queueSignalOf,"queueSignalOf"),n(queueSignalOf,"queueSignalOf");const c={delayed:"re-delayed","waiting-children":"waiting for its children","rate-limited":"rate-limited",waiting:"back to wait"};export const queueSignalTitle=n(e=>c[e],"queueSignalTitle");const f=n(e=>e<1e3?`${Math.round(e)} ms`:e<6e4?`${Math.round(e/1e3)} s`:e<36e5?`${Math.round(e/6e4)} min`:`${Math.round(e/36e5)} h`,"span");export function queueSignalWords(e,t){return e!=="delayed"?c[e]:`asked to run again${typeof t=="number"&&Number.isFinite(t)&&t>=0?` in ${f(t)}`:""}`}i(queueSignalWords,"queueSignalWords"),n(queueSignalWords,"queueSignalWords");
package/lib/redact.js CHANGED
@@ -1 +1 @@
1
- "use strict";var P=Object.defineProperty;var f=(t,e)=>P(t,"name",{value:e,configurable:!0});var O=Object.defineProperty,u=f((t,e)=>O(t,"name",{value:e,configurable:!0}),"f"),R=Object.defineProperty,l=u((t,e)=>R(t,"name",{value:e,configurable:!0}),"a");export const REDACTED="REDACTED",MAX_TITLE_CHARS=300,MAX_MESSAGE_CHARS=4096,MAX_URL_CHARS=1024;const C=["token","secret","password","passwd","apikey","credential","assertion","signature"],Z=new Set(["key","auth","authorization","jwt","code","sig","pwd","pass","session","sid","bearer","otp","cookie","set-cookie"]),D=/^(?:(?:prompt|completion|total|input|output|cache|cached|cacheread|cachewrite|reasoning|thinking|max|min|remaining|used|billed)tokens|tokens?(?:count|used|limit|remaining))$/;export function isSecretParam(t){const e=h.get(t);if(e!==void 0)return e;const r=x(t);return t.length<=64&&h.size<j&&h.set(t,r),r}f(isSecretParam,"isSecretParam"),u(isSecretParam,"isSecretParam"),l(isSecretParam,"isSecretParam");const N=new Set(["sess","csrf","xsrf","refresh","nonce","reset","magic","mfa","2fa","verify","verification","invite","login"]);export function isSecretCacheKey(t){for(const e of t.split(/[:/{}#]+/))if(!(!e||e.length>64)){if(isSecretParam(e))return!0;for(const r of e.toLowerCase().split(/[-_.]+/))if(N.has(r))return!0}return!1}f(isSecretCacheKey,"isSecretCacheKey"),u(isSecretCacheKey,"isSecretCacheKey"),l(isSecretCacheKey,"isSecretCacheKey");const j=4096,h=new Map;function x(t){const e=t.toLowerCase();if(D.test(e.replace(/[-_.]+/g,"")))return!1;if(C.some(r=>e.includes(r)))return!0;for(const r of e.split(/[-_.]+/))if(r&&Z.has(r))return!0;return!1}f(x,"m"),u(x,"$"),l(x,"judgeParam");const U=/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@\s]*@/i,K=/([?&#])([^=&#\s]+)=([^&#\s]*)/g;export function redactUrlParams(t){return t&&t.replace(U,`$1${REDACTED}@`).replace(K,(e,r,n)=>isSecretParam(n)?`${r}${n}=${REDACTED}`:e)}f(redactUrlParams,"redactUrlParams"),u(redactUrlParams,"redactUrlParams"),l(redactUrlParams,"redactUrlParams");export function redactUrl(t){return t&&clip(redactUrlParams(t),1024)}f(redactUrl,"redactUrl"),u(redactUrl,"redactUrl"),l(redactUrl,"redactUrl");const M=/[A-Za-z0-9_.-]{15,}/g;function A(t){for(let e=0;;){const r=t.indexOf("eyJ",e);if(r===-1||t.length-r-3<6)return-1;if(r===0||t.charCodeAt(r-1)===45)return r;e=r+1}}f(A,"S"),u(A,"D"),l(A,"jwtStart");function m(t){if(t.indexOf("eyJ")===-1||t.indexOf(".")===-1)return t;const e=t.split(".");let r="";for(let n=0;n<e.length;n++){const c=e[n];if(n+2<e.length&&e[n+1].length>=4){const i=A(c);if(i!==-1){r+=c.slice(0,i)+REDACTED,n+=2,n<e.length-1&&(r+=".");continue}}r+=c,n<e.length-1&&(r+=".")}return r}f(m,"w"),u(m,"x"),l(m,"redactJwtRun");const L=/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi,J=/\b(authorization|x-api-key|api-key|cookie|set-cookie|proxy-authorization)\b(\s*[:=]\s*)(["']?)((?:(?:bearer|basic)\s+)?[^\s"',;]{4,})\3/gi,q=/[@=:]|eyJ|bearer|basic/i;export function redactText(t){return q.test(t)?redactUrlParams(t).replace(J,(e,r,n,c)=>`${r}${n}${c}${REDACTED}${c}`).replace(M,m).replace(L,(e,r)=>`${r} ${REDACTED}`):t}f(redactText,"redactText"),u(redactText,"redactText"),l(redactText,"redactText");const H=[/\bsk-(?:ant-|proj-|live-|test-)?[A-Za-z0-9_-]{20,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/\bgh[pousr]_[A-Za-z0-9]{30,}/g,/\bxox[abprs]-[A-Za-z0-9-]{10,}/g,/\bAIza[0-9A-Za-z_-]{35}\b/g],S="-----BEGIN ",V=4096;function b(t){if(!t.includes("PRIVATE KEY-----"))return t;let e="",r=0,n=!1;for(;;){const c=t.indexOf(S,r);if(c===-1)break;const i=t.indexOf("-----",c+S.length);if(i===-1)break;const s=t.slice(c+S.length,i);if(!/^[A-Z ]{0,30}PRIVATE KEY$/.test(s)){e+=t.slice(r,i+5),r=i+5;continue}e+=t.slice(r,c);const o=n?-1:t.indexOf("-----END ",i+5);let a;if(o===-1)n=!0,a=Math.min(t.length,i+5+V);else{const p=t.indexOf("-----",o+9);a=p===-1?t.length:p+5}e+=REDACTED,r=a}return e+t.slice(r)}f(b,"T"),u(b,"U"),l(b,"redactPrivateKeys");const X=/"([A-Za-z0-9_.-]{1,64})"\s*:\s*"((?:[^"\\]|\\.){1,8192})"/g,G=/\b([A-Za-z][A-Za-z0-9_-]{1,40})(\s*[:=]\s*)([^\s"'`,;&)}\]]{8,200})/g,Y=/(token|secret|pass(?:word|wd)?|pwd|api[-_]?key|apikey|credential|authorization|bearer)/i;function $(t){return t.replace(X,(e,r)=>isSecretParam(r)?`"${r}": "${REDACTED}"`:e).replace(G,(e,r,n)=>Y.test(r)&&isSecretParam(r)?`${r}${n}${REDACTED}`:e)}f($,"y"),u($,"j"),l($,"redactStructured");export function redactSecretText(t){let e=$(redactText(b(t)));for(const r of H)e=e.replace(r,REDACTED);return e}f(redactSecretText,"redactSecretText"),u(redactSecretText,"redactSecretText"),l(redactSecretText,"redactSecretText");export function clip(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026[lensmcp truncated: ${t.length-e} more chars]`}f(clip,"clip"),u(clip,"clip"),l(clip,"clip");export function safeText(t,e=4096){if(t!==void 0)return clip(redactText(t),e)}f(safeText,"safeText"),u(safeText,"safeText"),l(safeText,"safeText");export function safeTitle(t){return clip(redactText(t),300)}f(safeTitle,"safeTitle"),u(safeTitle,"safeTitle"),l(safeTitle,"safeTitle");const B=6,F=64,W=/^TS\d{1,5}$/,Q=l((t,e)=>t==="code"&&typeof e=="string"&&W.test(e),"isDiagnosticCode");export function redactDeep(t,e=0,r=B){if(typeof t=="string")return redactText(t);if(t===null||typeof t!="object"||e>=r)return t;if(Array.isArray(t)){let s;for(let o=0;o<t.length;o++){if(o>=F){s&&s.push(t[o]);continue}const a=t[o],p=redactDeep(a,e+1,r);s?s.push(p):p!==a&&(s=t.slice(0,o),s.push(p))}return s??t}const n=t,c=Object.keys(n);let i;for(let s=0;s<c.length;s++){const o=c[s],a=n[o],p=isSecretParam(o)&&a!==void 0&&a!==null&&!Q(o,a)?REDACTED:redactDeep(a,e+1,r);if(i)i[o]=p;else if(p!==a){i={};for(let g=0;g<s;g++)i[c[g]]=n[c[g]];i[o]=p}}return i??t}f(redactDeep,"redactDeep"),u(redactDeep,"redactDeep"),l(redactDeep,"redactDeep");const w=String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`,T=String.raw`${w}(?:\s*\.\s*${w})*`,tt=String.raw`(?:=|<>|!=|<=|>=|<|>|(?:NOT\s+)?I?LIKE|IS\s+(?:NOT\s+)?DISTINCT\s+FROM)`,et=new RegExp(String.raw`(${T})\s*${tt}\s*(?:[A-Za-z_]\w*\s*\(\s*)?\$(\d+)`,"gi"),rt=new RegExp(String.raw`(${T})\s+(?:NOT\s+)?IN\s*\(([^()]*)\)`,"gi"),nt=new RegExp(String.raw`\bINSERT\s+INTO\s+${T}\s*\(([^()]*)\)\s*VALUES\s*`,"gi"),st=new RegExp(w,"g"),_=/\$(\d+)/g,v=16384,it=256,ct=4096,d=new Map,y=l(t=>{const e=t.match(st)??[],r=e[e.length-1]??"";return r.startsWith('"')?r.slice(1,-1).replace(/""/g,'"'):r},"lastIdent");function k(t,e){const r=[];let n=e;for(;;){for(;n<t.length&&/\s/.test(t[n]);)n++;if(t[n]!=="(")return r;const c=[];let i=n+1,s=0,o=!1;for(n+=1;n<t.length;n++){const a=t[n];if(o){a==="'"&&(o=!1);continue}if(a==="'")o=!0;else if(a==="(")s++;else if(a===")"){if(s===0)break;s--}else a===","&&s===0&&(c.push(t.slice(i,n)),i=n+1)}if(n>=t.length)return r;for(c.push(t.slice(i,n)),r.push(c),n+=1;n<t.length&&/\s/.test(t[n]);)n++;if(t[n]!==",")return r;n+=1}}f(k,"E"),u(k,"et"),l(k,"valuesTuples");function z(t){const e=t.length<=ct,r=e?d.get(t):void 0;if(r)return r;const n=t.length>v?t.slice(0,v):t,c=new Set,i=l((s,o)=>{o&&isSecretParam(o)&&c.add(Number(s))},"bind");for(const s of n.matchAll(et))i(s[2],y(s[1]));for(const s of n.matchAll(rt)){const o=y(s[1]);for(const a of s[2].matchAll(_))i(a[1],o)}for(const s of n.matchAll(nt)){const o=s[1].split(",").map(a=>y(a.trim()));for(const a of k(n,(s.index??0)+s[0].length))a.forEach((p,g)=>{const E=o[g];if(E)for(const I of p.matchAll(_))i(I[1],E)})}if(e){if(d.size>=it){const s=d.keys().next().value;s!==void 0&&d.delete(s)}d.set(t,c)}return c}f(z,"_"),u(z,"nt"),l(z,"secretPlaceholders");export function redactSqlParams(t,e){if(e.length===0||!t.includes("$"))return e;const r=z(t);if(r.size===0)return e;let n=!1;const c=e.map((i,s)=>i==null||!r.has(s+1)?i:(n=!0,REDACTED));return n?c:e}f(redactSqlParams,"redactSqlParams"),u(redactSqlParams,"redactSqlParams"),l(redactSqlParams,"redactSqlParams");
1
+ "use strict";var v=Object.defineProperty;var f=(e,t)=>v(e,"name",{value:t,configurable:!0});var R=Object.defineProperty,l=f((e,t)=>R(e,"name",{value:t,configurable:!0}),"a");export const REDACTED="REDACTED",MAX_TITLE_CHARS=300,MAX_MESSAGE_CHARS=4096,MAX_URL_CHARS=1024;const O=["token","secret","password","passwd","apikey","credential","assertion","signature"],Z=new Set(["key","auth","authorization","jwt","code","sig","pwd","pass","session","sid","bearer","otp","cookie","set-cookie"]),C=/^(?:(?:prompt|completion|total|input|output|cache|cached|cacheread|cachewrite|reasoning|thinking|max|min|remaining|used|billed)tokens|tokens?(?:count|used|limit|remaining))$/;export function isSecretParam(e){const t=d.get(e);if(t!==void 0)return t;const r=m(e);return e.length<=64&&d.size<N&&d.set(e,r),r}f(isSecretParam,"isSecretParam"),l(isSecretParam,"isSecretParam");const P=new Set(["sess","csrf","xsrf","refresh","nonce","reset","magic","mfa","2fa","verify","verification","invite","login"]);export function isSecretCacheKey(e){for(const t of e.split(/[:/{}#]+/))if(!(!t||t.length>64)){if(isSecretParam(t))return!0;for(const r of t.toLowerCase().split(/[-_.]+/))if(P.has(r))return!0}return!1}f(isSecretCacheKey,"isSecretCacheKey"),l(isSecretCacheKey,"isSecretCacheKey");const N=4096,d=new Map;function m(e){const t=e.toLowerCase();if(C.test(t.replace(/[-_.]+/g,"")))return!1;if(O.some(r=>t.includes(r)))return!0;for(const r of t.split(/[-_.]+/))if(r&&Z.has(r))return!0;return!1}f(m,"$"),l(m,"judgeParam");const D=/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@\s]*@/i,M=/([?&#])([^=&#\s]+)=([^&#\s]*)/g;export function redactUrlParams(e){return e&&e.replace(D,`$1${REDACTED}@`).replace(M,(t,r,n)=>isSecretParam(n)?`${r}${n}=${REDACTED}`:t)}f(redactUrlParams,"redactUrlParams"),l(redactUrlParams,"redactUrlParams");export function redactUrl(e){return e&&clip(redactUrlParams(e),1024)}f(redactUrl,"redactUrl"),l(redactUrl,"redactUrl");const j=/[A-Za-z0-9_.-]{15,}/g;function S(e){for(let t=0;;){const r=e.indexOf("eyJ",t);if(r===-1||e.length-r-3<6)return-1;if(r===0||e.charCodeAt(r-1)===45)return r;t=r+1}}f(S,"D"),l(S,"jwtStart");function w(e){if(e.indexOf("eyJ")===-1||e.indexOf(".")===-1)return e;const t=e.split(".");let r="";for(let n=0;n<t.length;n++){const o=t[n];if(n+2<t.length&&t[n+1].length>=4){const i=S(o);if(i!==-1){r+=o.slice(0,i)+REDACTED,n+=2,n<t.length-1&&(r+=".");continue}}r+=o,n<t.length-1&&(r+=".")}return r}f(w,"x"),l(w,"redactJwtRun");const K=/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi,L=/\b(authorization|x-api-key|api-key|cookie|set-cookie|proxy-authorization)\b(\s*[:=]\s*)(["']?)((?:(?:bearer|basic)\s+)?[^\s"',;]{4,})\3/gi,U=/[@=:]|eyJ|bearer|basic/i;export function redactText(e){return U.test(e)?redactUrlParams(e).replace(L,(t,r,n,o)=>`${r}${n}${o}${REDACTED}${o}`).replace(j,w).replace(K,(t,r)=>`${r} ${REDACTED}`):e}f(redactText,"redactText"),l(redactText,"redactText");const J=[/\bsk-(?:ant-|proj-|live-|test-)?[A-Za-z0-9_-]{20,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/\bgh[pousr]_[A-Za-z0-9]{30,}/g,/\bxox[abprs]-[A-Za-z0-9-]{10,}/g,/\bAIza[0-9A-Za-z_-]{35}\b/g],h="-----BEGIN ",H=4096;function T(e){if(!e.includes("PRIVATE KEY-----"))return e;let t="",r=0,n=!1;for(;;){const o=e.indexOf(h,r);if(o===-1)break;const i=e.indexOf("-----",o+h.length);if(i===-1)break;const s=e.slice(o+h.length,i);if(!/^[A-Z ]{0,30}PRIVATE KEY$/.test(s)){t+=e.slice(r,i+5),r=i+5;continue}t+=e.slice(r,o);const c=n?-1:e.indexOf("-----END ",i+5);let a;if(c===-1)n=!0,a=Math.min(e.length,i+5+H);else{const u=e.indexOf("-----",c+9);a=u===-1?e.length:u+5}t+=REDACTED,r=a}return t+e.slice(r)}f(T,"U"),l(T,"redactPrivateKeys");const V=/"([A-Za-z0-9_.-]{1,64})"\s*:\s*"((?:[^"\\]|\\.){1,8192})"/g,X=/\b([A-Za-z][A-Za-z0-9_-]{1,40})(\s*[:=]\s*)([^\s"'`,;&)}\]]{8,200})/g,q=/(token|secret|pass(?:word|wd)?|pwd|api[-_]?key|apikey|credential|authorization|bearer)/i;function y(e){return e.replace(V,(t,r)=>isSecretParam(r)?`"${r}": "${REDACTED}"`:t).replace(X,(t,r,n)=>q.test(r)&&isSecretParam(r)?`${r}${n}${REDACTED}`:t)}f(y,"j"),l(y,"redactStructured");export function redactSecretText(e){let t=y(redactText(T(e)));for(const r of J)t=t.replace(r,REDACTED);return t}f(redactSecretText,"redactSecretText"),l(redactSecretText,"redactSecretText");export function clip(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026[lensmcp truncated: ${e.length-t} more chars]`}f(clip,"clip"),l(clip,"clip");export function safeText(e,t=4096){if(e!==void 0)return clip(redactText(e),t)}f(safeText,"safeText"),l(safeText,"safeText");export function safeTitle(e){return clip(redactText(e),300)}f(safeTitle,"safeTitle"),l(safeTitle,"safeTitle");const G=6,Y=64,B=/^TS\d{1,5}$/,F=l((e,t)=>e==="code"&&typeof t=="string"&&B.test(t),"isDiagnosticCode");export function redactDeep(e,t=0,r=G){if(typeof e=="string")return redactText(e);if(e===null||typeof e!="object"||t>=r)return e;if(Array.isArray(e)){let s;for(let c=0;c<e.length;c++){if(c>=Y){s&&s.push(e[c]);continue}const a=e[c],u=redactDeep(a,t+1,r);s?s.push(u):u!==a&&(s=e.slice(0,c),s.push(u))}return s??e}const n=e,o=Object.keys(n);let i;for(let s=0;s<o.length;s++){const c=o[s],a=n[c],u=isSecretParam(c)&&a!==void 0&&a!==null&&!F(c,a)?REDACTED:redactDeep(a,t+1,r);if(i)i[c]=u;else if(u!==a){i={};for(let p=0;p<s;p++)i[o[p]]=n[o[p]];i[c]=u}}return i??e}f(redactDeep,"redactDeep"),l(redactDeep,"redactDeep");const A=String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`,x=String.raw`${A}(?:\s*\.\s*${A})*`,W=String.raw`(?:=|<>|!=|<=|>=|<|>|(?:NOT\s+)?I?LIKE|IS\s+(?:NOT\s+)?DISTINCT\s+FROM)`,Q=new RegExp(String.raw`(${x})\s*${W}\s*(?:[A-Za-z_]\w*\s*\(\s*)?\$(\d+)`,"gi"),ee=new RegExp(String.raw`(${x})\s+(?:NOT\s+)?IN\s*\(([^()]*)\)`,"gi"),te=new RegExp(String.raw`\bINSERT\s+INTO\s+${x}\s*\(([^()]*)\)\s*VALUES\s*`,"gi"),re=new RegExp(A,"g"),k=/\$(\d+)/g,z=16384,ne=256,se=4096,g=new Map,$=l(e=>{const t=e.match(re)??[],r=t[t.length-1]??"";return r.startsWith('"')?r.slice(1,-1).replace(/""/g,'"'):r},"lastIdent");function E(e,t){const r=[];let n=t;for(;;){for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!=="(")return r;const o=[];let i=n+1,s=0,c=!1;for(n+=1;n<e.length;n++){const a=e[n];if(c){a==="'"&&(c=!1);continue}if(a==="'")c=!0;else if(a==="(")s++;else if(a===")"){if(s===0)break;s--}else a===","&&s===0&&(o.push(e.slice(i,n)),i=n+1)}if(n>=e.length)return r;for(o.push(e.slice(i,n)),r.push(o),n+=1;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!==",")return r;n+=1}}f(E,"et"),l(E,"valuesTuples");function _(e){const t=e.length<=se,r=t?g.get(e):void 0;if(r)return r;const n=e.length>z?e.slice(0,z):e,o=new Set,i=l((s,c)=>{c&&isSecretParam(c)&&o.add(Number(s))},"bind");for(const s of n.matchAll(Q))i(s[2],$(s[1]));for(const s of n.matchAll(ee)){const c=$(s[1]);for(const a of s[2].matchAll(k))i(a[1],c)}for(const s of n.matchAll(te)){const c=s[1].split(",").map(a=>$(a.trim()));for(const a of E(n,(s.index??0)+s[0].length))a.forEach((u,p)=>{const b=c[p];if(b)for(const I of u.matchAll(k))i(I[1],b)})}if(t){if(g.size>=ne){const s=g.keys().next().value;s!==void 0&&g.delete(s)}g.set(e,o)}return o}f(_,"nt"),l(_,"secretPlaceholders");export function redactSqlParams(e,t){if(t.length===0||!e.includes("$"))return t;const r=_(e);if(r.size===0)return t;let n=!1;const o=t.map((i,s)=>i==null||!r.has(s+1)?i:(n=!0,REDACTED));return n?o:t}f(redactSqlParams,"redactSqlParams"),l(redactSqlParams,"redactSqlParams");
@@ -1 +1 @@
1
- "use strict";var k=Object.defineProperty;var o=(n,e)=>k(n,"name",{value:e,configurable:!0});var E=Object.defineProperty,c=o((n,e)=>E(n,"name",{value:e,configurable:!0}),"o"),a=Object.defineProperty,p=c((n,e)=>a(n,"name",{value:e,configurable:!0}),"k");export function redisExpiry(n,e){const t=n.toLowerCase();if(t==="setex"||t==="psetex")return e.length===3&&/^\d+$/.test(String(e[1]))&&Number(e[1])>0?"set":"unknown";if(t==="getset"||t==="setnx"||t==="mset"||t==="msetnx")return"none";if(t!=="set"&&t!=="getex")return"unknown";const f=t==="set"?2:1;if(e.length<f)return"unknown";let u=t==="set"?"none":"kept",i=!1,l=!1,g=!1;for(let r=f;r<e.length;r++){const s=String(e[r]).toUpperCase();if(["EX","PX","EXAT","PXAT"].includes(s)){if(i||r+1>=e.length||!/^\d+$/.test(String(e[++r]))||Number(e[r])<=0)return"unknown";i=!0,u="set"}else if(t==="set"&&s==="KEEPTTL"||t==="getex"&&s==="PERSIST"){if(i)return"unknown";i=!0,u=s==="KEEPTTL"?"kept":"none"}else if(t==="set"&&["NX","XX"].includes(s)){if(l)return"unknown";l=!0}else if(t==="set"&&s==="GET"){if(g)return"unknown";g=!0}else return"unknown"}return u}o(redisExpiry,"redisExpiry"),c(redisExpiry,"redisExpiry"),p(redisExpiry,"redisExpiry");
1
+ "use strict";var k=Object.defineProperty;var o=(s,n)=>k(s,"name",{value:n,configurable:!0});var c=Object.defineProperty,E=o((s,n)=>c(s,"name",{value:n,configurable:!0}),"k");export function redisExpiry(s,n){const e=s.toLowerCase();if(e==="setex"||e==="psetex")return n.length===3&&/^\d+$/.test(String(n[1]))&&Number(n[1])>0?"set":"unknown";if(e==="getset"||e==="setnx"||e==="mset"||e==="msetnx")return"none";if(e!=="set"&&e!=="getex")return"unknown";const f=e==="set"?2:1;if(n.length<f)return"unknown";let i=e==="set"?"none":"kept",u=!1,l=!1,g=!1;for(let t=f;t<n.length;t++){const r=String(n[t]).toUpperCase();if(["EX","PX","EXAT","PXAT"].includes(r)){if(u||t+1>=n.length||!/^\d+$/.test(String(n[++t]))||Number(n[t])<=0)return"unknown";u=!0,i="set"}else if(e==="set"&&r==="KEEPTTL"||e==="getex"&&r==="PERSIST"){if(u)return"unknown";u=!0,i=r==="KEEPTTL"?"kept":"none"}else if(e==="set"&&["NX","XX"].includes(r)){if(l)return"unknown";l=!0}else if(e==="set"&&r==="GET"){if(g)return"unknown";g=!0}else return"unknown"}return i}o(redisExpiry,"redisExpiry"),E(redisExpiry,"redisExpiry");
@@ -1 +1 @@
1
- "use strict";var a=Object.defineProperty;var c=(r,e)=>a(r,"name",{value:e,configurable:!0});var u=Object.defineProperty,i=c((r,e)=>u(r,"name",{value:e,configurable:!0}),"c"),n=Object.defineProperty,d=i((r,e)=>n(r,"name",{value:e,configurable:!0}),"c");export class ReducerRegistry{static{c(this,"ReducerRegistry")}static{i(this,"ReducerRegistry")}static{d(this,"ReducerRegistry")}constructor(){this.reducers=[]}register(e,s){if(this.reducers.some(t=>t.name===e))throw new Error(`Reducer already registered: ${e}`);this.reducers.push({name:e,reducer:s})}list(){return this.reducers}async dispatch(e){for(const{reducer:s}of this.reducers)try{const t=s(e);t&&typeof t.then=="function"&&await t}catch{}}}
1
+ "use strict";var i=Object.defineProperty;var c=(t,e)=>i(t,"name",{value:e,configurable:!0});var u=Object.defineProperty,a=c((t,e)=>u(t,"name",{value:e,configurable:!0}),"c");export class ReducerRegistry{static{c(this,"ReducerRegistry")}static{a(this,"ReducerRegistry")}constructor(){this.reducers=[]}register(e,s){if(this.reducers.some(r=>r.name===e))throw new Error(`Reducer already registered: ${e}`);this.reducers.push({name:e,reducer:s})}list(){return this.reducers}async dispatch(e){for(const{reducer:s}of this.reducers)try{const r=s(e);r&&typeof r.then=="function"&&await r}catch{}}}
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var t=(e,r)=>p(e,"name",{value:r,configurable:!0});var i=Object.defineProperty,o=t((e,r)=>i(e,"name",{value:r,configurable:!0}),"o"),c=Object.defineProperty,n=o((e,r)=>c(e,"name",{value:r,configurable:!0}),"e");import{homedir as l}from"node:os";import{dirname as s,join as m}from"node:path";import{lensEventFile as E}from"./lens-events.js";export function replayPathSegment(e){const r=e?.trim().replace(/[^A-Za-z0-9._-]/g,"-").replace(/^[.-]+/,"");return r?r.slice(0,80):void 0}t(replayPathSegment,"replayPathSegment"),o(replayPathSegment,"replayPathSegment"),n(replayPathSegment,"replayPathSegment");export function replayStoreFromEnv(e=process.env,r=process.cwd()){const a=replayPathSegment(e.LENSMCP_REPLAY_WORKSPACE||e.LENSMCP_WS_KEY);return{root:e.LENSMCP_REPLAY_DIR?.trim()||(a?m(e.LENSMCP_HOME||l(),".lensmcp","replay",a):m(s(E(e,r)),"replay")),checkout:replayPathSegment(e.LENSMCP_INSTANCE)??"main"}}t(replayStoreFromEnv,"replayStoreFromEnv"),o(replayStoreFromEnv,"replayStoreFromEnv"),n(replayStoreFromEnv,"replayStoreFromEnv");
1
+ "use strict";var c=Object.defineProperty;var o=(e,r)=>c(e,"name",{value:r,configurable:!0});var i=Object.defineProperty,n=o((e,r)=>i(e,"name",{value:r,configurable:!0}),"e");import{homedir as m}from"node:os";import{dirname as p,join as a}from"node:path";import{lensEventFile as s}from"./lens-events.js";export function replayPathSegment(e){const r=e?.trim().replace(/[^A-Za-z0-9._-]/g,"-").replace(/^[.-]+/,"");return r?r.slice(0,80):void 0}o(replayPathSegment,"replayPathSegment"),n(replayPathSegment,"replayPathSegment");export function replayStoreFromEnv(e=process.env,r=process.cwd()){const t=replayPathSegment(e.LENSMCP_REPLAY_WORKSPACE||e.LENSMCP_WS_KEY);return{root:e.LENSMCP_REPLAY_DIR?.trim()||(t?a(e.LENSMCP_HOME||m(),".lensmcp","replay",t):a(p(s(e,r)),"replay")),checkout:replayPathSegment(e.LENSMCP_INSTANCE)??"main"}}o(replayStoreFromEnv,"replayStoreFromEnv"),n(replayStoreFromEnv,"replayStoreFromEnv");
@@ -1 +1 @@
1
- "use strict";var w=Object.defineProperty;var u=(i,e)=>w(i,"name",{value:e,configurable:!0});var p=Object.defineProperty,l=u((i,e)=>p(i,"name",{value:e,configurable:!0}),"u"),m=Object.defineProperty,d=l((i,e)=>m(i,"name",{value:e,configurable:!0}),"c");export class ResourceStore{static{u(this,"ResourceStore")}static{l(this,"ResourceStore")}static{d(this,"ResourceStore")}constructor(e={}){this.entries=new Map,this.subs=new Map,this.queued=new Map,this.lastRun=new Map,this.lastCost=new Map,this.coalesceMs=Math.max(0,e.coalesceMs??0),this.costFactor=Math.max(0,e.costFactor??0),this.maxGapMs=Math.max(0,e.maxGapMs??3e4),this.work=e.work,this.lazy=e.lazy===!0}register(e,t){if(this.entries.has(e))throw new Error(`Resource already registered: ${e}`);return this.entries.set(e,{uri:e,produce:t,revision:0}),()=>{this.entries.delete(e),this.subs.delete(e),this.lastRun.delete(e),this.lastCost.delete(e)}}async read(e){const t=this.entries.get(e);if(!t)throw new Error(`Unknown resource: ${e}`);if(t.stale)return this.recompute(e);const s=await t.produce();return t.produced={at:Date.now(),value:s},s}async readRecent(e,t){const s=this.entries.get(e);if(!s)throw new Error(`Unknown resource: ${e}`);return s.produced&&Date.now()-s.produced.at<=t?s.produced.value:this.read(e)}latest(e){const t=this.entries.get(e);if(!t)throw new Error(`Unknown resource: ${e}`);return t.produced?.value}isStale(e){return this.entries.get(e)?.stale===!0}list(){return[...this.entries.keys()]}markDirty(e){const t=this.entries.get(e);if(t&&this.lazy&&!this.subs.get(e)?.size)return t.stale=!0,Promise.resolve();if(this.coalesceMs===0&&this.costFactor===0)return this.recompute(e).then(()=>{});if(!t)return Promise.resolve();const s=this.queued.get(e);if(s)return s;const n=Math.max(0,(this.lastRun.get(e)??Number.NEGATIVE_INFINITY)+this.gapFor(e)-Date.now()),o=new Promise(r=>{const a=d(()=>{this.queued.delete(e),this.lastRun.set(e,Date.now()),this.recompute(e).then(()=>r(),()=>r())},"go");n===0?setImmediate(a):setTimeout(a,n).unref?.()});return this.queued.set(e,o),o}gapFor(e){const t=this.lastCost.get(e)??0;return Math.max(this.coalesceMs,Math.min(this.maxGapMs,this.costFactor*t))}cost(e){return this.lastCost.get(e)}async recompute(e){const t=this.entries.get(e);if(!t)return;const s=performance.now(),n=this.work?.(`recompute ${e}`),o=t.stale===!0;t.stale=!1;let r,a;try{r=await t.produce(),t.produced={at:Date.now(),value:r},a=JSON.stringify(r)}catch(c){throw o&&(t.stale=!0),c}finally{n?.()}if(this.lastCost.set(e,performance.now()-s),a===t.lastJson)return r;t.lastJson=a,t.revision+=1;const h=this.subs.get(e);if(h)for(const c of h)try{c(e,t.revision)}catch{}return r}revision(e){return this.entries.get(e)?.revision}subscribe(e,t){let s=this.subs.get(e);return s||(s=new Set,this.subs.set(e,s)),s.add(t),this.entries.get(e)?.stale&&this.markDirty(e).catch(()=>{}),()=>{s?.delete(t)}}}
1
+ "use strict";var d=Object.defineProperty;var u=(o,t)=>d(o,"name",{value:t,configurable:!0});var w=Object.defineProperty,l=u((o,t)=>w(o,"name",{value:t,configurable:!0}),"c");export class ResourceStore{static{u(this,"ResourceStore")}static{l(this,"ResourceStore")}constructor(t={}){this.entries=new Map,this.subs=new Map,this.queued=new Map,this.lastRun=new Map,this.lastCost=new Map,this.coalesceMs=Math.max(0,t.coalesceMs??0),this.costFactor=Math.max(0,t.costFactor??0),this.maxGapMs=Math.max(0,t.maxGapMs??3e4),this.work=t.work,this.lazy=t.lazy===!0}register(t,e){if(this.entries.has(t))throw new Error(`Resource already registered: ${t}`);return this.entries.set(t,{uri:t,produce:e,revision:0}),()=>{this.entries.delete(t),this.subs.delete(t),this.lastRun.delete(t),this.lastCost.delete(t)}}async read(t){const e=this.entries.get(t);if(!e)throw new Error(`Unknown resource: ${t}`);if(e.stale)return this.recompute(t);const s=await e.produce();return e.produced={at:Date.now(),value:s},s}async readRecent(t,e){const s=this.entries.get(t);if(!s)throw new Error(`Unknown resource: ${t}`);return s.produced&&Date.now()-s.produced.at<=e?s.produced.value:this.read(t)}latest(t){const e=this.entries.get(t);if(!e)throw new Error(`Unknown resource: ${t}`);return e.produced?.value}isStale(t){return this.entries.get(t)?.stale===!0}list(){return[...this.entries.keys()]}markDirty(t){const e=this.entries.get(t);if(e&&this.lazy&&!this.subs.get(t)?.size)return e.stale=!0,Promise.resolve();if(this.coalesceMs===0&&this.costFactor===0)return this.recompute(t).then(()=>{});if(!e)return Promise.resolve();const s=this.queued.get(t);if(s)return s;const n=Math.max(0,(this.lastRun.get(t)??Number.NEGATIVE_INFINITY)+this.gapFor(t)-Date.now()),a=new Promise(r=>{const i=l(()=>{this.queued.delete(t),this.lastRun.set(t,Date.now()),this.recompute(t).then(()=>r(),()=>r())},"go");n===0?setImmediate(i):setTimeout(i,n).unref?.()});return this.queued.set(t,a),a}gapFor(t){const e=this.lastCost.get(t)??0;return Math.max(this.coalesceMs,Math.min(this.maxGapMs,this.costFactor*e))}cost(t){return this.lastCost.get(t)}async recompute(t){const e=this.entries.get(t);if(!e)return;const s=performance.now(),n=this.work?.(`recompute ${t}`),a=e.stale===!0;e.stale=!1;let r,i;try{r=await e.produce(),e.produced={at:Date.now(),value:r},i=JSON.stringify(r)}catch(c){throw a&&(e.stale=!0),c}finally{n?.()}if(this.lastCost.set(t,performance.now()-s),i===e.lastJson)return r;e.lastJson=i,e.revision+=1;const h=this.subs.get(t);if(h)for(const c of h)try{c(t,e.revision)}catch{}return r}revision(t){return this.entries.get(t)?.revision}subscribe(t,e){let s=this.subs.get(t);return s||(s=new Set,this.subs.set(t,s)),s.add(e),this.entries.get(t)?.stale&&this.markDirty(t).catch(()=>{}),()=>{s?.delete(e)}}}
@@ -1 +1 @@
1
- "use strict";var u=Object.defineProperty;var n=(e,t)=>u(e,"name",{value:t,configurable:!0});var c=Object.defineProperty,r=n((e,t)=>c(e,"name",{value:t,configurable:!0}),"s"),p=Object.defineProperty,l=r((e,t)=>p(e,"name",{value:t,configurable:!0}),"r");function s(e){return e.length===0?!1:!!(/^\d{2,}$/.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^[A-Z][A-Z0-9]*-\d+$/.test(e)||e.length>=16&&/^[A-Za-z0-9_-]+$/.test(e)&&/\d/.test(e))}n(s,"f"),r(s,"a"),l(s,"isIdSegment");export function templatisePath(e){const[t="/"]=e.split("?"),o=t.split("/"),a=[];for(const f of o){if(a.length>12){a.push("\u2026");break}a.push(s(f)?":id":f)}const i=a.join("/");return i.length===0?"/":i}n(templatisePath,"templatisePath"),r(templatisePath,"templatisePath"),l(templatisePath,"templatisePath");
1
+ "use strict";var u=Object.defineProperty;var s=(t,e)=>u(t,"name",{value:e,configurable:!0});var l=Object.defineProperty,r=s((t,e)=>l(t,"name",{value:e,configurable:!0}),"r");function f(t){return t.length===0?!1:!!(/^\d{2,}$/.test(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[A-Z][A-Z0-9]*-\d+$/.test(t)||t.length>=16&&/^[A-Za-z0-9_-]+$/.test(t)&&/\d/.test(t))}s(f,"a"),r(f,"isIdSegment");export function templatisePath(t){const[e="/"]=t.split("?"),o=e.split("/"),n=[];for(const i of o){if(n.length>12){n.push("\u2026");break}n.push(f(i)?":id":i)}const a=n.join("/");return a.length===0?"/":a}s(templatisePath,"templatisePath"),r(templatisePath,"templatisePath");
@@ -1 +1 @@
1
- "use strict";var c=Object.defineProperty;var t=(e,r)=>c(e,"name",{value:r,configurable:!0});var i=Object.defineProperty,o=t((e,r)=>i(e,"name",{value:r,configurable:!0}),"r"),s=Object.defineProperty,a=o((e,r)=>s(e,"name",{value:r,configurable:!0}),"t");export function isServiceHopHost(e){return e?/.\.localhost$/i.test(e.replace(/\.$/,"")):!1}t(isServiceHopHost,"isServiceHopHost"),o(isServiceHopHost,"isServiceHopHost"),a(isServiceHopHost,"isServiceHopHost");export const LENS_REQUEST_ID_HEADER="x-lensmcp-request-id";
1
+ "use strict";var o=Object.defineProperty;var r=(e,t)=>o(e,"name",{value:t,configurable:!0});var s=Object.defineProperty,c=r((e,t)=>s(e,"name",{value:t,configurable:!0}),"t");export function isServiceHopHost(e){return e?/.\.localhost$/i.test(e.replace(/\.$/,"")):!1}r(isServiceHopHost,"isServiceHopHost"),c(isServiceHopHost,"isServiceHopHost");export const LENS_REQUEST_ID_HEADER="x-lensmcp-request-id";