@lensmcp/core 1.25.78 → 1.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +1 -0
- package/index.js +1 -1
- package/lib/ai-content.js +1 -1
- package/lib/answer-budget.js +2 -2
- package/lib/bus-rotation.js +1 -1
- package/lib/capture-off.js +1 -1
- package/lib/event-bus.js +1 -1
- package/lib/event-loop-history.js +1 -1
- package/lib/event-loop.d.ts +9 -1
- package/lib/event-loop.js +1 -1
- package/lib/event-redactor.js +1 -1
- package/lib/fingerprint.js +1 -1
- package/lib/flow-categories.js +1 -1
- package/lib/flow-segments.js +1 -1
- package/lib/flow-shape.d.ts +15 -8
- package/lib/flow-shape.js +1 -1
- package/lib/flows-config.js +1 -1
- package/lib/graph-from-events.js +1 -1
- package/lib/graph-store.js +1 -1
- package/lib/headless-flow.js +1 -1
- package/lib/http-exchange.js +1 -1
- package/lib/http-shape.js +1 -1
- package/lib/key-pattern.js +1 -1
- package/lib/lens-config.d.ts +14 -0
- package/lib/lens-config.js +1 -0
- package/lib/lens-dir.d.ts +9 -0
- package/lib/lens-dir.js +7 -7
- package/lib/lens-events.js +2 -2
- package/lib/lens-store.d.ts +37 -0
- package/lib/lens-store.js +1 -0
- package/lib/patterns.d.ts +28 -12
- package/lib/patterns.js +1 -1
- package/lib/performance-window.d.ts +20 -3
- package/lib/performance-window.js +2 -2
- package/lib/pg-errors.js +1 -1
- package/lib/queue-signals.d.ts +7 -0
- package/lib/queue-signals.js +1 -0
- package/lib/redact.js +1 -1
- package/lib/redis-expiry.js +1 -1
- package/lib/reducer-registry.js +1 -1
- package/lib/replay-store.js +1 -1
- package/lib/resource-store.js +1 -1
- package/lib/route-template.js +1 -1
- package/lib/service-hop.js +1 -1
- package/lib/settings.js +2 -2
- package/lib/sql-shape.js +3 -3
- package/lib/sql-values.js +1 -1
- package/lib/stores.js +2 -2
- package/lib/story.js +1 -1
- package/lib/thresholds.js +1 -1
- package/lib/ulid.js +1 -1
- package/package.json +17 -2
package/lib/patterns.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var g=Object.defineProperty;var
|
|
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,4 +1,5 @@
|
|
|
1
1
|
import type { BaseEvent } from '@lensmcp/protocol-types';
|
|
2
|
+
import { type DbWorkClass } from './patterns.js';
|
|
2
3
|
import { type LensmcpThresholds } from './thresholds.js';
|
|
3
4
|
/**
|
|
4
5
|
* How one checkout performed over one window — the routes it served, the statements it ran, the pages it loaded — and
|
|
@@ -12,8 +13,11 @@ import { type LensmcpThresholds } from './thresholds.js';
|
|
|
12
13
|
* - a route, a statement or a page is slow when it ran at or above its limit MORE THAN ONCE (the perf reducer's rule —
|
|
13
14
|
* a one-off spike, the first call after a rebuild, is not a breach; it is still in the numbers);
|
|
14
15
|
* - N+1: one request ran the same statement `nPlusOne` times or more — a streaming one, within one burst: its reads
|
|
15
|
-
* seconds apart are a stream's periodic work over its life, not a loop (issues/closed/foodguard-147)
|
|
16
|
-
*
|
|
16
|
+
* seconds apart are a stream's periodic work over its life, not a loop (issues/closed/foodguard-147). Its class says
|
|
17
|
+
* whether the values varied (`loop`) or not (`repeated-read`: the same row re-read at fixed steps);
|
|
18
|
+
* - DB in a loop: ONE statement shape repeated inside one method (`dbLoopBreaks`) — never many different statements
|
|
19
|
+
* run once each, which is straight-line code (issues/closed/overseer-73). Folded per route, statement and method,
|
|
20
|
+
* with the requests it ran in; one that names the statement an N+1 of the same route names is folded into it.
|
|
17
21
|
* A streaming response's time is how long it stayed open, not how slow it was: it is counted, never timed. A page the dev
|
|
18
22
|
* server reloaded (`cause: 'hmr'`) is left out, and a hard load is timed from the app's entry (`appReadyMs`), not from
|
|
19
23
|
* the dev server serving it.
|
|
@@ -93,6 +97,12 @@ export interface PerformanceBreach {
|
|
|
93
97
|
limit: string;
|
|
94
98
|
/** Up to five event ids that show it. */
|
|
95
99
|
evidence: string[];
|
|
100
|
+
/** An N+1's or DB loop's class, the method's DB calls and statements, its requests and method (overseer-73). */
|
|
101
|
+
class?: DbWorkClass;
|
|
102
|
+
calls?: number;
|
|
103
|
+
distinctStatements?: number;
|
|
104
|
+
requests?: number;
|
|
105
|
+
site?: string;
|
|
96
106
|
/** Waived by the person: why. A waived breach does not fail the window. */
|
|
97
107
|
waived?: string;
|
|
98
108
|
/**
|
|
@@ -109,7 +119,7 @@ export interface PerformanceBreach {
|
|
|
109
119
|
/**
|
|
110
120
|
* A window's numbers by subject, kept small: what a later window is compared with — main's, for a QA run's breaches
|
|
111
121
|
* (issues/closed/foodguard-181). Timings are p95 ms; `repeats` the most runs of a statement in one request of a route
|
|
112
|
-
* (`<route>\0<sql>`), at any count; `loops` the most
|
|
122
|
+
* (`<route>\0<sql>`), at any count; `loops` the most repeats of one statement in one method, by route and statement (`<route>\0<sql>`).
|
|
113
123
|
*/
|
|
114
124
|
export interface PerformanceBaseline {
|
|
115
125
|
limits: PerformanceLimits;
|
|
@@ -145,6 +155,8 @@ export interface PerformanceReport {
|
|
|
145
155
|
slow: number;
|
|
146
156
|
failed: number;
|
|
147
157
|
};
|
|
158
|
+
/** Class-less `loop` events of an older tap, not judged: they counted every DB call of the method. */
|
|
159
|
+
unjudgedLoops?: number;
|
|
148
160
|
/** Slowest p95 first. */
|
|
149
161
|
routes: RouteStat[];
|
|
150
162
|
sql: SqlStat[];
|
|
@@ -170,7 +182,10 @@ export declare class PerformanceWindow {
|
|
|
170
182
|
private readonly streams;
|
|
171
183
|
/** N+1 per route and statement: the worst count, and where — and how many of its requests were streams. */
|
|
172
184
|
private readonly repeated;
|
|
185
|
+
/** DB loops by route, statement and method — and those whose request has not ended yet (its route not known). */
|
|
173
186
|
private readonly loops;
|
|
187
|
+
private readonly loopsWaiting;
|
|
188
|
+
private unjudgedLoops;
|
|
174
189
|
/** Where each statement runs (planning/code-locations `raw.site`): the files of its frames, and whether a run carried none. */
|
|
175
190
|
private readonly sqlFiles;
|
|
176
191
|
private readonly sqlUnlocated;
|
|
@@ -198,6 +213,8 @@ export declare class PerformanceWindow {
|
|
|
198
213
|
*/
|
|
199
214
|
private close;
|
|
200
215
|
private loop;
|
|
216
|
+
/** One DB loop under its route: one finding per route, statement and method, its worst, and the requests it ran in. */
|
|
217
|
+
private foldLoop;
|
|
201
218
|
private page;
|
|
202
219
|
/** The person's why for a breach, when a waiver matches what it is about; undefined: it stands. */
|
|
203
220
|
private waiverOf;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var E=Object.defineProperty;var M=(i,t)=>E(i,"name",{value:t,configurable:!0});var I=Object.defineProperty,c=M((i,t)=>I(i,"name",{value:t,configurable:!0}),"f");import{loopDbCalls as L}from"./patterns.js";import{resolveThresholds as F}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(...i){let t={};for(const r of i)r&&(t={...t,...S(r)});const e=F(t);return{slowRouteMs:e.slowRouteMs,slowQueryMs:e.slowQueryMs,nPlusOne:e.nPlusOne,dbInLoop:e.dbInLoop,slowPageMs:e.slowPageMs}}M(performanceLimits,"performanceLimits"),c(performanceLimits,"performanceLimits");function S(i){const t={};for(const[e,r]of Object.entries(i))typeof r=="number"&&Number.isFinite(r)&&r>=0&&(t[e]=r);return t}M(S,"P"),c(S,"resolveThresholdsOnly");const q=c(i=>i&&typeof i=="object"?i:{},"obj"),m=c(i=>typeof i=="string"&&i?i:void 0,"str"),f=c(i=>typeof i=="number"&&Number.isFinite(i)?i:void 0,"num"),N=2e3,b=5e3,k=2e4,D=1e3,Q=1024,T=12,A=200;function z(i){let t=0;for(const[e,r]of i)t=Math.max(t,r+(i.get(e+1)??0));return t}M(z,"L"),c(z,"burstOf");const O=c(()=>({count:0,times:[],slow:0,max:0,evidence:[]}),"newTiming");function y(i,t,e,r){if(i.max=Math.max(i.max,t),t>=e&&(i.slow+=1,i.evidence.length<5&&i.evidence.push(r)),i.times.length<N)i.times.push(t);else{let o=0;for(let n=1;n<i.times.length;n++)i.times[n]<i.times[o]&&(o=n);t>i.times[o]&&(i.times[o]=t)}}M(y,"S"),c(y,"time");function P(i,t){return i.length?i[Math.min(i.length-1,Math.floor(i.length*t))]:0}M(P,"j"),c(P,"percentile");function x(i){const t=[...i.times].sort((e,r)=>e-r);return{count:i.count,timed:i.times.length,p50Ms:Math.round(P(t,.5)),p95Ms:Math.round(P(t,.95)),maxMs:Math.round(i.max),slow:i.slow}}M(x,"k"),c(x,"timing");function $(i,t,e){return i.includes("*")?new RegExp(`^${i.split("*").map(r=>r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`).test(t):e?t===i:t.includes(i)}M($,"y"),c($,"matches");export class PerformanceWindow{static{M(this,"PerformanceWindow")}static{c(this,"PerformanceWindow")}constructor(t,e=[]){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=[],this.sqlFiles=new Map,this.sqlUnlocated=new Set,this.routeSql=new Map,this.mostRuns=new Map,this.limits=t,this.waivers=e.filter(r=>typeof r?.why=="string"&&(r.route||r.sql||r.page))}add(t){const e=q(t.raw),r=e.kind;if(r!=="server-request"&&r!=="db-query"&&r!==SQL_DROPS_KIND&&r!=="loop"&&r!=="page-visit")return;this.events+=1,this.from=Math.min(this.from,t.timestamp),this.to=Math.max(this.to,t.timestamp);const o=q(t.context),n=m(o.projectName)??m(e.project),u=m(o.requestId);r==="server-request"?this.request(t,e,n,u):r==="db-query"?this.statement(t,e,n,u):r===SQL_DROPS_KIND?this.dropped(t,e,n):r==="loop"?this.loop(t,e,u):this.page(t,e)}request(t,e,r,o){const n=q(e.request),u=m(n.method)??"?",l=m(n.route)??"?",d=`${u} ${l}`;let p=this.routes.get(d);if(!p){if(this.routes.size>=b)return;p={...O(),method:u,route:l,...r?{project:r}:{},errors:0,streaming:0},this.routes.set(d,p)}p.count+=1;const h=f(n.status);h!==void 0&&h>=500&&(p.errors+=1);const w=f(n.durationMs);n.streaming===!0?p.streaming+=1:w!==void 0&&y(p,w,this.limits.slowRouteMs,t.id),o&&(this.routeOf.set(o,d),this.routeOf.size>k&&this.routeOf.delete(this.routeOf.keys().next().value),n.streaming===!0&&(this.streams.add(o),this.streams.size>k&&this.streams.delete(this.streams.keys().next().value)),this.close(o))}sqlEntry(t,e,r){let o=this.sql.get(t);if(!o&&this.sql.size<b){o={...O(),failed:0,dropped:0};const n=m(e.sqlName),u=m(e.op),l=m(e.table);n&&(o.name=n),r&&(o.project=r),u&&(o.op=u),l&&(o.table=l),this.sql.set(t,o)}return o}statement(t,e,r,o){const n=m(e.statement)??m(e.query),u=m(e.sqlId)??n?.slice(0,300);if(!u)return;const l=1+Math.max(0,f(e.floodSuppressed)??0),d=this.sqlEntry(u,e,r);if(d){this.located(u,e.site),d.count+=l,!d.text&&n&&(d.text=n.slice(0,300)),e.error!==void 0&&e.error!==null&&(d.failed+=1);const a=f(e.durationMs);a!==void 0&&y(d,a,this.limits.slowQueryMs,t.id)}if(!o)return;let p=this.open.get(o);p||(this.open.size>=k&&this.close(this.open.keys().next().value),p=new Map,this.open.set(o,p));let h=p.get(u);h?h.n+=l:p.set(u,h={n:l,first:t.id,seconds:new Map});const w=Math.floor(t.timestamp/D),s=h.seconds.get(w);s!==void 0?h.seconds.set(w,s+l):h.seconds.size<Q&&h.seconds.set(w,l)}located(t,e){const r=(Array.isArray(q(e).frames)?q(e).frames:[]).slice(0,3).map(n=>m(q(n).file)).filter(n=>!!n);if(!r.length){this.sqlUnlocated.add(t);return}let o=this.sqlFiles.get(t);o||this.sqlFiles.set(t,o=new Set);for(const n of r)o.size<T&&o.add(n.slice(0,1024))}dropped(t,e,r){const o=f(e.slowMs)??-1/0,n=c((p,h)=>Math.max(this.limits.slowQueryMs<=o?Math.max(0,f(p.slow)??0):0,h>=this.limits.slowQueryMs?1:0),"slowOf"),u=Array.isArray(e.shapes)?e.shapes:[];for(const p of u){const h=q(p),w=m(h.sqlId),s=Math.max(0,f(h.runs)??0);if(!w||!s)continue;const a=Math.max(0,f(h.maxMs)??0),g=Math.max(0,f(h.failed)??0),j=n(h,a);this.drops.runs+=s,this.drops.slow+=j,this.drops.failed+=g;const v=this.sqlEntry(w,h,r);if(v){if(v.count+=s,v.dropped+=s,v.failed+=g,v.max=Math.max(v.max,a),!v.text){const R=m(h.query);R&&(v.text=R.slice(0,300))}j&&(v.slow+=j,v.evidence.length<5&&v.evidence.push(t.id))}}const l=q(e.overflow),d=Math.max(0,f(l.runs)??0);if(d){const p=Math.max(0,f(l.maxMs)??0);this.drops.runs+=d,this.drops.slow+=n(l,p),this.drops.failed+=Math.max(0,f(l.failed)??0)}}close(t){const e=this.open.get(t);if(!e)return;this.open.delete(t);const r=this.routeOf.get(t),o=r??"a request with no route seen",n=this.streams.delete(t);let u=r?this.routeSql.get(r):void 0;r&&!u&&this.routeSql.size<b&&this.routeSql.set(r,u=new Set);for(const[l,{n:d,first:p,seconds:h}]of e){const w=n?z(h):d;u&&u.size<A&&u.add(l);const s=`${o}\0${l}`;if(w>(this.mostRuns.get(s)??0)&&(this.mostRuns.has(s)||this.mostRuns.size<b*4)&&this.mostRuns.set(s,w),w<this.limits.nPlusOne)continue;const a=`${o}\0${l}`,g=this.repeated.get(a)??{route:o,sql:l,worst:0,requests:0,streams:0,evidence:[]};g.worst=Math.max(g.worst,w),g.requests+=1,n&&(g.streams+=1),g.evidence.length<5&&g.evidence.push(p),this.repeated.set(a,g)}}loop(t,e,r){const o=q(e.loop),n=L(o);if(n<=this.limits.dbInLoop)return;const u=f(o.dbCallsInsideLoop)??0,l=(r&&this.routeOf.get(r))??t.title??"a loop";this.loops.length>=200||this.loops.push({id:`db-in-loop:${l}`,kind:"db-in-loop",subject:l,measured:n<u?`${n} DB calls within two seconds of one loop of a stream (${u} over its life)`:`${n} DB calls inside one loop (${f(o.iterations)??"?"} iterations)`,limit:`more than ${this.limits.dbInLoop} (dbInLoop)`,evidence:[t.id],about:{route:l},value:n})}page(t,e){if(e.phase!=="ready"||e.cause==="hmr")return;const r=m(e.app)??"?",o=m(e.pattern)??m(e.path)??"?",n=`${r} ${o}`;let u=this.pages.get(n);if(!u){if(this.pages.size>=b)return;u={...O(),app:r,path:o},this.pages.set(n,u)}u.count+=1;const l=e.nav==="hard"?f(e.appReadyMs)??f(e.readyMs):f(e.readyMs);l!==void 0&&y(u,l,this.limits.slowPageMs,t.id)}waiverOf(t){for(const e of this.waivers)if(e.route&&t.route&&$(e.route,t.route,!0)||e.sql&&t.sql&&($(e.sql,t.sql,!1)||t.sqlText!==void 0&&$(e.sql,t.sqlText,!1))||e.page&&t.page&&$(e.page,t.page,!0))return e.why}report(t){for(const s of[...this.open.keys()])this.close(s);const e=this.limits,r=[],o=c((s,a="runs")=>`p95 ${s.p95Ms} ms, max ${s.maxMs} ms \u2014 ${s.slow} of ${s.timed} ${a} at or above`,"slowWords"),n=[...this.routes.entries()].map(([s,a])=>({key:s,method:a.method,route:a.route,...a.project?{project:a.project}:{},errors:a.errors,streaming:a.streaming,...x(a),evidence:a.evidence}));for(const s of n)s.slow>1&&r.push({breach:{id:`slow-route:${s.key}`,kind:"slow-route",subject:s.key,measured:o(s),limit:`${e.slowRouteMs} ms (slowRouteMs)`,evidence:s.evidence,about:{route:s.key},value:s.p95Ms},about:{route:s.key}});const u=[...this.sql.entries()].map(([s,a])=>({key:s,...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}:{},...x(a),evidence:a.evidence}));for(const s of u){const a=s.dropped?`p95 ${s.p95Ms} ms, max ${s.maxMs} ms \u2014 ${s.slow} of ${s.count} runs at or above (${s.dropped} counted from the service's drop record, not timed)`:o(s);s.slow>1&&r.push({breach:{id:`slow-query:${s.key}`,kind:"slow-query",subject:s.name??s.key,measured:a,limit:`${e.slowQueryMs} ms (slowQueryMs)`,evidence:s.evidence,about:{sql:s.key},value:s.p95Ms},about:{sql:s.key,...s.text?{sqlText:s.text}:{}}})}for(const s of this.repeated.values()){const a=this.sql.get(s.sql);r.push({breach:{id:`n+1-query:${s.route}:${s.sql}`,kind:"n+1-query",subject:`${s.route} runs ${a?.name??s.sql}`,measured:s.streams===s.requests?`up to ${s.worst}\xD7 in one burst of a stream, within two seconds (${s.streams} stream${s.streams===1?"":"s"})`:`up to ${s.worst}\xD7 in one request (${s.requests} request${s.requests===1?"":"s"})`,limit:`fewer than ${e.nPlusOne} (nPlusOne)`,evidence:s.evidence,about:{route:s.route,sql:s.sql},value:s.worst},about:{route:s.route,sql:s.sql,...a?.text?{sqlText:a.text}:{}}})}for(const s of this.loops)r.push({breach:s,about:{route:s.subject}});const l=[...this.pages.entries()].map(([s,a])=>({key:s,app:a.app,path:a.path,...x(a),evidence:a.evidence}));for(const s of l)s.slow>1&&r.push({breach:{id:`slow-page:${s.key}`,kind:"slow-page",subject:s.key,measured:o(s,"visits"),limit:`${e.slowPageMs} ms (slowPageMs)`,evidence:s.evidence,about:{page:s.key},value:s.p95Ms},about:{page:s.path}});const d=[],p=[];for(const{breach:s,about:a}of r){const g=this.waiverOf(a);g?p.push({...s,waived:g}):d.push(s)}const h=c(s=>{const{evidence:a,...g}=s;return g},"strip"),w=this.routes.size+this.sql.size+this.pages.size+this.drops.runs>0;return{window:t??{from:Number.isFinite(this.from)?this.from:0,to:this.to},events:this.events,limits:{...e},verdict:d.length?"fail":w?"pass":"unmeasured",breaches:d,waived:p,...this.drops.runs?{dropped:{...this.drops}}:{},routes:n.map(h).sort((s,a)=>a.p95Ms-s.p95Ms),sql:u.map(h).sort((s,a)=>a.p95Ms-s.p95Ms),pages:l.map(h).sort((s,a)=>a.p95Ms-s.p95Ms)}}locate(t){if(!t||t.page)return;const e=c(n=>this.sqlUnlocated.has(n)||!this.sqlFiles.get(n)?.size?void 0:[...this.sqlFiles.get(n)],"ofSql");if(t.sql)return e(t.sql);if(!t.route)return;const r=this.routeSql.get(t.route);if(!r?.size)return;const o=new Set;for(const n of r){const u=e(n);if(!u)return;for(const l of u)o.add(l)}return[...o]}baseline(t){const e=this.report(t),r={};for(const o of this.loops)o.about?.route&&(o.value??0)>(r[o.about.route]??0)&&(r[o.about.route]=o.value??0);return{limits:{...this.limits},window:e.window,events:e.events,routes:Object.fromEntries(e.routes.filter(o=>o.timed).map(o=>[o.key,o.p95Ms])),sql:Object.fromEntries(e.sql.filter(o=>o.timed).map(o=>[o.key,o.p95Ms])),pages:Object.fromEntries(e.pages.filter(o=>o.timed).map(o=>[o.key,o.p95Ms])),repeats:Object.fromEntries(this.mostRuns),loops:r}}}export function describePerformance(i,t=12){const e=i.limits,r=[i.verdict==="unmeasured"?"Performance: unmeasured \u2014 no request, statement or page ran in the window.":`Performance: ${i.verdict==="pass"?"PASS":`FAIL \u2014 ${i.breaches.length} breach${i.breaches.length===1?"":"es"}`} over ${i.routes.length} route${i.routes.length===1?"":"s"}, ${i.sql.length} statement${i.sql.length===1?"":"s"}, ${i.pages.length} page${i.pages.length===1?"":"s"} (limits: route ${e.slowRouteMs} ms, query ${e.slowQueryMs} ms, N+1 ${e.nPlusOne}, DB in a loop ${e.dbInLoop}, page ${e.slowPageMs} ms).`],o=i.dropped;o&&r.push(`${o.runs} statement run${o.runs===1?"":"s"} reached the lens only as counts (the services' flood guards): ${o.slow} slow, ${o.failed} failed \u2014 counted above, not in the percentiles.`);for(const n of i.breaches.slice(0,t))r.push(`- ${n.kind} \xB7 ${n.subject}: ${n.measured}; limit ${n.limit}`);return i.breaches.length>t&&r.push(`- \u2026 ${i.breaches.length-t} more`),i.waived.length&&r.push(`Waived by .lensmcp/team/performance.json: ${i.waived.map(n=>`${n.kind} \xB7 ${n.subject} (${n.waived})`).slice(0,t).join("; ")}`),r.join(`
|
|
2
|
-
`)}M(describePerformance,"describePerformance"),
|
|
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");
|
package/lib/pg-errors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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");
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type QueueSignal = 'delayed' | 'waiting-children' | 'rate-limited' | 'waiting';
|
|
2
|
+
export declare const QUEUE_SIGNALS: readonly QueueSignal[];
|
|
3
|
+
export declare const RATE_LIMIT_MESSAGE = "bullmq:rateLimitExceeded";
|
|
4
|
+
export declare function isControlFlowThrow(err: unknown): QueueSignal | undefined;
|
|
5
|
+
export declare function queueSignalOf(status: unknown): QueueSignal | undefined;
|
|
6
|
+
export declare const queueSignalTitle: (signal: QueueSignal) => string;
|
|
7
|
+
export declare function queueSignalWords(signal: QueueSignal, delayMs?: number): string;
|
|
@@ -0,0 +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");
|
package/lib/redact.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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");
|
package/lib/redis-expiry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var k=Object.defineProperty;var o=(
|
|
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");
|
package/lib/reducer-registry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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{}}}
|
package/lib/replay-store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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");
|
package/lib/resource-store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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)}}}
|
package/lib/route-template.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var u=Object.defineProperty;var
|
|
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");
|
package/lib/service-hop.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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";
|
package/lib/settings.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var M=Object.defineProperty;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});var N=Object.defineProperty,s=l((t,e)=>N(t,"name",{value:e,configurable:!0}),"n");import{readFileSync as y,renameSync as L,statSync as C,unlinkSync as A,writeFileSync as O,mkdirSync as P}from"node:fs";import{availableParallelism as T,homedir as R}from"node:os";import{dirname as x,join as g}from"node:path";const I=[{value:"on",label:"On"},{value:"off",label:"Off"}],m=s(t=>t==="0"?"off":"on","zeroIsOff"),b=s(t=>/^(0|off|false|no)$/i.test(t.trim())?"off":"on","wordIsOff"),o=s(t=>{if(t.trim()==="")return;const e=Number(t);return Number.isFinite(e)?e:void 0},"num"),f={kind:"toggle",options:I,write:{on:"1",off:"0"}};export const SETTINGS=[{env:"LENSMCP_HTTP_CAPTURE",page:"capture",section:"Requests",title:"What each request keeps",desc:"For every request a service serves or makes: its headers, the query and the first 64 KB of each body; its headers only; or nothing.",kept:"repository",applies:"service",kind:"choice",options:[{value:"bodies",label:"Headers and bodies"},{value:"headers",label:"Headers"},{value:"off",label:"Nothing"}],default:"bodies",parse:s(t=>/^(off|0|false|none)$/i.test(t.trim())?"off":t.trim().toLowerCase()==="headers"?"headers":"bodies","parse")},{env:"LENSMCP_HTTP_MAX_FILES",page:"capture",section:"Requests",title:"Exchanges kept in each place",desc:"How many exchanges are kept for third-party calls, for requests served, and for calls between services. The oldest go first; AI calls are kept.",kept:"machine",applies:"service",kind:"number",number:{unit:"exchanges",min:10},default:1e4,parse:s(t=>{const e=o(t);return e!==void 0&&e>=10?Math.floor(e):void 0},"parse")},{env:"LENSMCP_LOGS",page:"capture",section:"Logs",...f,title:"Mirror the services\u2019 logs",desc:"What each service prints, and what its handlers give the Nest Logger, goes on the lens as logs. Off: Logs shows nothing of the services.",kept:"repository",applies:"service",default:"on",parse:m},{env:"LENSMCP_EVENT_LOOP",page:"capture",section:"Event loops",...f,title:"Measure the services\u2019 event loops",desc:"Samples each service\u2019s event-loop delay, measures slow callbacks and watches for a loop that stops answering. Off: Cluster \u203A Event loops has nothing.",kept:"repository",applies:"service",default:"on",parse:m},{env:"LENSMCP_TRACE_FLOWLESS_MIN_MS",page:"capture",section:"Traces",title:"Shortest traced call outside a request",desc:"A traced method that runs outside any request, flow or job and returns faster than this leaves no span \u2014 a timer that runs every second would otherwise fill the history.",kept:"repository",applies:"service",kind:"number",number:{unit:"ms",min:0,zero:"keep every one"},default:10,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_EVENT_HISTORY_DAYS",page:"history",section:"Event history",title:"Keep the history for",desc:"Rows older than this go. Whichever comes first, this or the size below, decides.",kept:"machine",applies:"lens",kind:"number",number:{unit:"days",min:0,zero:"keep by size only"},default:30,parse:s(t=>{const e=o(t);return e===void 0?void 0:e>0?e:0},"parse")},{env:"LENSMCP_EVENT_HISTORY_MAX_GB",page:"history",section:"Event history",title:"Most history kept",desc:"Past this size the oldest rows go, whatever their age. A busy workspace reaches it in days.",kept:"machine",applies:"lens",kind:"number",number:{unit:"GB",min:0,zero:"no limit"},default:16,parse:s(t=>{const e=o(t);return e===void 0?void 0:e>0?e:0},"parse")},{env:"LENSMCP_EVENT_LOOP_DAYS",page:"history",section:"Event history",title:"Keep event-loop stalls for",desc:"How long a stall and its evidence stay in the history.",kept:"machine",applies:"lens",kind:"number",number:{unit:"days",min:1},default:30,parse:s(t=>{const e=o(t);return e!==void 0&&e>0?e:void 0},"parse")},{env:"LENSMCP_EVENT_MAX_BYTES",page:"history",section:"The event bus",title:"Size of one bus file",desc:"The events every process writes go to .lensmcp/events.jsonl; past this size it is rotated.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"MB",scale:1048576,min:1048576},default:52428800,parse:s(t=>{const e=o(t);return e!==void 0&&e>0?e:void 0},"parse")},{env:"LENSMCP_EVENT_MAX_FILES",page:"history",section:"The event bus",title:"Bus files kept",desc:"How many rotated bus files are kept beside the one being written.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"files",min:1,max:20},default:5,parse:s(t=>{const e=o(t);return e!==void 0&&e>=1&&e<=20?Math.floor(e):void 0},"parse")},{env:"LENSMCP_TYPECHECK",page:"typecheck",section:"The checker",title:"Type checker",desc:"tsgo checks a service after each build with the native compiler and keeps nothing in memory between saves. fork-ts-checker keeps a whole TypeScript program in memory for each service, 1\u20133 GB on a large one. Off: no type errors on the lens.",kept:"repository",applies:"service",kind:"choice",options:[{value:"tsgo",label:"tsgo"},{value:"tsc",label:"fork-ts-checker"},{value:"off",label:"Off"}],default:"tsgo",parse:s(t=>t==="off"?"off":t==="tsgo"||t===""?"tsgo":"tsc","parse")},{env:"LENSMCP_TYPECHECK_MIN_FREE_MB",page:"typecheck",section:"tsgo",title:"Wait for free memory",desc:"A check waits while the machine has less than this free, and the lens says it is held. Each check of a large service takes 1.5\u20133.5 GB while it runs.",kept:"machine",applies:"service",kind:"number",number:{unit:"MB",min:0,zero:"never wait"},default:2048,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?Math.round(e):void 0},"parse")},{env:"LENSMCP_TYPECHECK_CONCURRENCY",page:"typecheck",section:"tsgo",title:"Checks at once on this machine",desc:"How many services are checked at the same time, every workspace\u2019s together. The rest wait their turn.",kept:"machine",applies:"service",kind:"number",number:{unit:"checks",min:1,max:8},default:1,parse:s(t=>{const e=o(t);return e!==void 0&&Number.isInteger(e)&&e>=1?Math.min(e,8):void 0},"parse")},{env:"LENSMCP_TSGO_INCREMENTAL",page:"typecheck",section:"tsgo",...f,title:"Check only what a change affects",desc:"Each service keeps what its last check learnt on disk (tmp/lensmcp-tsgo) and checks again only the files a change can affect. Off: every check is a full one.",kept:"repository",applies:"service",default:"on",parse:b},{env:"LENSMCP_PERF_RULES",page:"performance",section:"Rules",...f,title:"Performance rules",desc:"The rules that flag a barrel import that compiles a whole library, and a pod over its memory budget. Off: Performance shows none of their findings.",kept:"repository",applies:"service",default:"on",parse:b},{env:"LENSMCP_POD_HEAP_BUDGET_MB",page:"performance",section:"Rules",title:"A pod\u2019s memory budget",desc:"The live heap after a full collection above which a pod is flagged as over its budget. A service\u2019s own perfRules in .lensmcp/config.json wins.",kept:"repository",applies:"lens",kind:"number",number:{unit:"MB",min:16,max:1e6},default:512,parse:s(t=>{const e=o(t);return e!==void 0&&e>=16&&e<=1e6?e:void 0},"parse")},{env:"LENSMCP_MAX_COLD_STARTS",page:"services",section:"Starting",title:"Services starting at once",desc:"How many services may cold start together, every workspace\u2019s and worktree\u2019s counted. The rest wait their turn. Fewer start slower but keep a loaded machine answering.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"services",min:0,zero:"no limit"},default:s(()=>Math.max(2,Math.floor(T()/2)),"default"),parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_POD_RESPONSE_TIMEOUT_MS",page:"services",section:"Answering",title:"Wait for a first byte",desc:"How long the gateway waits for a pod\u2019s first byte before it checks the pod is alive. A service\u2019s own cluster.firstByteMs wins.",kept:"repository",applies:"gateway",kind:"number",number:{unit:"s",scale:1e3,min:1e3},default:3e4,parse:s(t=>{const e=o(t);return e!==void 0&&e>0?e:void 0},"parse")},{env:"LENSMCP_POD_RECYCLE",page:"services",section:"Recycling",...f,title:"Recycle a pod that missed a change",desc:"A pod whose watcher missed a file added or removed is replaced by a fresh one. Off: a pod keeps serving its old code until you restart it.",kept:"repository",applies:"gateway",default:"on",parse:m},{env:"LENSMCP_POD_MAX_AGE_MS",page:"services",section:"Recycling",title:"Recycle a pod older than",desc:"A pod this old is replaced even with no change seen \u2014 the one whose watcher went quiet.",kept:"repository",applies:"gateway",kind:"number",number:{unit:"h",scale:36e5,min:0,zero:"never"},default:144e5,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_SWAP_MODE",page:"services",section:"A new build",title:"How a pod takes a new build",desc:"A fresh pod takes each new build and the old one finishes its work. In the same pod: the app is swapped inside the running process \u2014 faster, but a module that holds state can leak.",kept:"repository",applies:"service",kind:"choice",options:[{value:"process",label:"A fresh pod"},{value:"in-process",label:"In the same pod"}],default:"process",parse:s(t=>/^(in-process|inprocess|hot)$/i.test(t.trim())?"in-process":"process","parse")},{env:"LENSMCP_SWAP_DRAIN_MS",page:"services",section:"A new build",title:"Let the old app finish for",desc:"How long the previous app may finish its requests and background jobs before it is closed anyway.",kept:"repository",applies:"service",kind:"number",number:{unit:"min",scale:6e4,min:0,zero:"close at once"},default:9e5,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_SHARED_COMPILER",page:"builds",section:"Compiling",...f,title:"One compilation for every service",desc:"The services of a checkout share one webpack compilation: a shared library is compiled once, not once per service. Off: each service has its own watcher again.",kept:"repository",applies:"service",default:"on",parse:s(t=>/^(0|off|false|no)$/i.test(t.trim())?"off":"on","parse")},{env:"LENSMCP_BUILD_HOST_IDLE_SEC",page:"builds",section:"Compiling",title:"Stop an idle build host after",desc:"How long a checkout\u2019s build host keeps running once none of its services runs.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"min",scale:60,min:0,zero:"never"},default:300,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_DEV_DEVTOOL",page:"builds",section:"Source maps",title:"Source maps in development",desc:"eval is the fastest to build. A full source map gives exact lines in stack traces and costs build time and memory. A serve target\u2019s own devtool wins.",kept:"repository",applies:"service",kind:"choice",options:[{value:"eval",label:"eval"},{value:"eval-cheap-module-source-map",label:"eval-cheap-module-source-map"},{value:"cheap-module-source-map",label:"cheap-module-source-map"},{value:"source-map",label:"source-map"},{value:"off",label:"None"}],default:"eval",parse:s(t=>{const e=t.trim();return e?/^(false|off|none|0)$/i.test(e)?"off":/^(?:eval|(?:inline-|hidden-|eval-)?(?:nosources-)?(?:cheap-(?:module-)?)?source-map(?:-debugids)?)$/.test(e)?e:"eval":"eval"},"parse")},{env:"LENSMCP_WARM_MIN_FREE_MB",page:"worktrees",section:"Starting",title:"Start a worktree\u2019s services only with free memory",desc:"When a worktree registers, its always-warm services start one at a time, each only while the machine has this much free. The rest start on their first request.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"MB",min:0,zero:"no floor"},default:4096,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_WORKTREE_RUN_MAX",page:"worktrees",section:"Starting",title:"On-demand worktrees running at once",desc:"At most this many on-demand worktrees run at the same time. One more is refused, naming those that run and when each parks. The main checkout does not count.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"worktrees",min:0,zero:"no cap"},default:2,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?Math.floor(e):void 0},"parse")},{env:"LENSMCP_WORKTREE_IDLE_SEC",page:"worktrees",section:"Sleeping",title:"Stop an unused worktree service after",desc:"A worktree\u2019s service with no request for this long stops, and starts again on the next one.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"min",scale:60,min:0,zero:"never"},default:1800,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_WORKTREE_RUN_IDLE_SEC",page:"worktrees",section:"Sleeping",title:"Park an unused on-demand worktree after",desc:"An on-demand worktree that runs is parked after this long with no request and no hold: its services, frontends and dashboard stop, and its data is kept. It runs again when asked.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"min",scale:60,min:60},default:900,parse:s(t=>{const e=o(t);return e!==void 0&&e>=60?e:void 0},"parse")},{env:"LENSMCP_DASHBOARD_IDLE_SEC",page:"worktrees",section:"Sleeping",title:"Stop an unused worktree dashboard after",desc:"A worktree\u2019s dashboard starts on its first request and stops after this long with none.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"min",scale:60,min:0,zero:"always up"},default:600,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_GUEST_REPLAY",page:"worktrees",section:"After a restart",...f,title:"Host the worktrees again after a restart",desc:"A restarted gateway hosts again every worktree and workspace registered with it before. Off: each registers again when its lens starts.",kept:"machine",applies:"gateway",default:"on",parse:m},{env:"LENSMCP_GUEST_MIDDLEWARE",page:"worktrees",section:"Requests",title:"Whose middleware runs on a worktree\u2019s routes",desc:"Its own \u2014 the middleware its gateway target declares; the main checkout\u2019s, on every route; or none.",kept:"machine",applies:"gateway",kind:"choice",options:[{value:"own",label:"Its own"},{value:"owner",label:"The main checkout\u2019s"},{value:"none",label:"None"}],default:"own",parse:s(t=>t==="owner"||t==="none"?t:"own","parse")},{env:"LENSMCP_MAIN_ALWAYS_UP",page:"worktrees",section:"Main checkout",...f,title:"Keep the main checkout always up",desc:"Every main service starts when the gateway does \u2014 the always-warm ones first, then the rest one at a time while memory holds \u2014 and none stops for idleness. Off: the rest start on their first request.",kept:"machine",applies:"gateway",default:"on",parse:b},{env:"LENSMCP_GW_ACT",page:"gateway",section:"Acting as a user",...f,title:"Let agents act as a signed-in user",desc:"An agent may call the services as a user who signed in on this machine, through a ticket the gateway checks. Off: every ticket is refused.",kept:"machine",applies:"gateway",default:"on",parse:m},{env:"LENSMCP_MAX_CONNECTIONS",page:"gateway",section:"Limits",title:"Most connections at once",desc:"The front door\u2019s ceiling on open connections. Past it, new ones wait.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"connections",min:0,zero:"no limit"},default:512,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?Math.floor(e):void 0},"parse")},{env:"LENSMCP_ANSWER_BUDGET_BYTES",page:"answers",section:"Size",title:"Largest answer to an agent",desc:"Every answer, and every page result_query reads, fits this. A bigger one is folded, or cut when folding is off.",kept:"repository",applies:"lens",kind:"number",number:{unit:"KB",scale:1024,min:2048,zero:"no limit (folding off)"},default:24576,parse:s(t=>{const e=o(t);return e===void 0||e<0?void 0:e===0?0:Math.max(2048,Math.floor(e))},"parse")},{env:"LENSMCP_RESULT_HANDLES_THRESHOLD_BYTES",page:"answers",section:"Size",title:"Fold answers larger than",desc:"An answer at or under this goes to the agent as it is; a larger one goes as a preview and a handle.",kept:"repository",applies:"lens",kind:"number",number:{unit:"KB",scale:1024,min:1024},default:8192,parse:s(t=>{const e=o(t);return e!==void 0&&e>=1024?Math.floor(e):void 0},"parse")}];const w=new Map(SETTINGS.map(t=>[t.env,t]));export const settingOf=s(t=>w.get(t),"settingOf"),defaultOf=s(t=>typeof t.default=="function"?t.default():t.default,"defaultOf");export function valueOf(t,e){const r=t.parse?t.parse(e):e;return r===void 0?defaultOf(t):r}l(valueOf,"valueOf"),s(valueOf,"valueOf");export function textFor(t,e){if(t.kind==="toggle")return e!=="on"&&e!=="off"?{refused:`${t.env} is on or off`}:{text:e==="on"?t.write.on:t.write.off};if(t.kind==="choice"){const a=t.options?.find(i=>i.value===e);return a?{text:a.value}:{refused:`${t.env} is one of ${t.options.map(i=>i.value).join(", ")}`}}const r=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN,n=t.number;return Number.isFinite(r)?r===0&&n.zero?{text:"0"}:n.min!==void 0&&r<n.min?{refused:`${t.env} is at least ${n.min}${n.zero?`, or 0 (${n.zero})`:""}`}:n.max!==void 0&&r>n.max?{refused:`${t.env} is at most ${n.max}`}:{text:String(r)}:{refused:`${t.env} is a number`}}l(textFor,"textFor"),s(textFor,"textFor");export const PROJECT_FILE_NAME="lensmcp.json";export function machineSettingsFile(t=process.env){return g(t.LENSMCP_HOME||R(),".lensmcp","settings.json")}l(machineSettingsFile,"machineSettingsFile"),s(machineSettingsFile,"machineSettingsFile");const k=new Map;function E(t){let e;try{const a=C(t);e=`${a.size}:${a.mtimeMs}`}catch{return k.delete(t),{}}const r=k.get(t);if(r?.stamp===e)return r.settings;const n={};try{const a=JSON.parse(y(t,"utf8"));if(a.settings&&typeof a.settings=="object"&&!Array.isArray(a.settings))for(const[i,c]of Object.entries(a.settings))w.has(i)&&(typeof c=="string"||typeof c=="number")&&(n[i]=String(c))}catch{}return k.set(t,{stamp:e,settings:n}),n}l(E,"b"),s(E,"fileSettings");export function readKeptSettings(t,e=process.env){const r=E(g(t,PROJECT_FILE_NAME)),n=E(machineSettingsFile(e)),a=s((i,c)=>Object.fromEntries(Object.entries(i).filter(([d])=>w.get(d)?.kept===c)),"pick");return{repository:a(r,"repository"),machine:a(n,"machine")}}l(readKeptSettings,"readKeptSettings"),s(readKeptSettings,"readKeptSettings");export function keptEnv(t,e=process.env){const r=readKeptSettings(t,e);return{...r.machine,...r.repository}}l(keptEnv,"keptEnv"),s(keptEnv,"keptEnv");export const KEPT_MARK="LENSMCP_KEPT_SETTINGS";const S=s(t=>new Set((t[KEPT_MARK]??"").split(",").filter(Boolean)),"markedNames");export const fromSettings=s((t,e=process.env)=>e[t]!==void 0&&S(e).has(t),"fromSettings"),DOTENV_FILES=[".env.local",".local.env",".env"];export function dotenvKeys(t){const e=new Map;for(const r of DOTENV_FILES){let n;try{n=y(g(t,r),"utf8")}catch{continue}for(const a of n.matchAll(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/gm))e.has(a[1])||e.set(a[1],r)}return e}l(dotenvKeys,"dotenvKeys"),s(dotenvKeys,"dotenvKeys");export const dotenvDeclaring=s((t,e)=>dotenvKeys(t).get(e),"dotenvDeclaring");export function withKeptSettings(t,e,r=process.env){const n={...e},a=keptEnv(t,r),i=S(e),c=dotenvKeys(t),d=[];for(const h of SETTINGS){const u=h.env;if(n[u]!==void 0&&!i.has(u))continue;const v=a[u];v===void 0||c.has(u)?delete n[u]:(n[u]=v,d.push(u))}return d.length?n[KEPT_MARK]=d.join(","):delete n[KEPT_MARK],n}l(withKeptSettings,"withKeptSettings"),s(withKeptSettings,"withKeptSettings");export function applyKeptSettings(t,e=process.env){const r=withKeptSettings(t,e,e);for(const n of[...SETTINGS.map(a=>a.env),KEPT_MARK])r[n]===void 0?delete e[n]:e[n]=r[n];return[...S(e)]}l(applyKeptSettings,"applyKeptSettings"),s(applyKeptSettings,"applyKeptSettings");export function resolveSetting(t,e,r=process.env,n=readKeptSettings(e,r)){const a=n[t.kept][t.env],i=r[t.env];return i!==void 0&&!fromSettings(t.env,r)?{value:valueOf(t,i),source:"env",envFrom:dotenvDeclaring(e,t.env)??"shell",...a!==void 0?{kept:a}:{}}:a!==void 0?{value:valueOf(t,a),source:t.kept}:{value:defaultOf(t),source:"default"}}l(resolveSetting,"resolveSetting"),s(resolveSetting,"resolveSetting");export function writeKeptSetting(t,e,r,n=process.env){const a=w.get(e);if(!a)throw new Error(`${e} is not a setting`);const i=a.kept==="repository"?g(t,PROJECT_FILE_NAME):machineSettingsFile(n);let c={},d=!0;try{const p=JSON.parse(y(i,"utf8"));if(!p||typeof p!="object"||Array.isArray(p))throw new Error(`${i} is not a JSON object \u2014 fix it by hand first`);c=p}catch(p){if(p.code!=="ENOENT")throw p instanceof SyntaxError?new Error(`${i} is not valid JSON (${p.message}) \u2014 fix it by hand first`):p;d=!1}const h=c.settings&&typeof c.settings=="object"&&!Array.isArray(c.settings)?{...c.settings}:{},u=typeof h[e]=="string"||typeof h[e]=="number"?String(h[e]):null;if(r===null?delete h[e]:h[e]=r,Object.keys(h).length?c.settings=Object.fromEntries(Object.entries(h).sort(([p],[_])=>p.localeCompare(_))):delete c.settings,!d&&!c.settings)return u;d||(c={schemaVersion:1,...c}),P(x(i),{recursive:!0});const v=`${i}.${process.pid}.tmp`;try{O(v,`${JSON.stringify(c,null,2)}
|
|
2
|
-
`),
|
|
1
|
+
"use strict";var N=Object.defineProperty;var l=(t,e)=>N(t,"name",{value:e,configurable:!0});var L=Object.defineProperty,u=l((t,e)=>L(t,"name",{value:e,configurable:!0}),"l"),O=Object.defineProperty,s=u((t,e)=>O(t,"name",{value:e,configurable:!0}),"n");import{readFileSync as E,renameSync as C,statSync as P,unlinkSync as A,writeFileSync as T,mkdirSync as R}from"node:fs";import{availableParallelism as x,homedir as I}from"node:os";import{dirname as K,join as w}from"node:path";const z=[{value:"on",label:"On"},{value:"off",label:"Off"}],g=s(t=>t==="0"?"off":"on","zeroIsOff"),S=s(t=>/^(0|off|false|no)$/i.test(t.trim())?"off":"on","wordIsOff"),o=s(t=>{if(t.trim()==="")return;const e=Number(t);return Number.isFinite(e)?e:void 0},"num"),v={kind:"toggle",options:z,write:{on:"1",off:"0"}};export const SETTINGS=[{env:"LENSMCP_HTTP_CAPTURE",page:"capture",section:"Requests",title:"What each request keeps",desc:"For every request a service serves or makes: its headers, the query and the first 64 KB of each body; its headers only; or nothing.",kept:"repository",applies:"service",kind:"choice",options:[{value:"bodies",label:"Headers and bodies"},{value:"headers",label:"Headers"},{value:"off",label:"Nothing"}],default:"bodies",parse:s(t=>/^(off|0|false|none)$/i.test(t.trim())?"off":t.trim().toLowerCase()==="headers"?"headers":"bodies","parse")},{env:"LENSMCP_HTTP_MAX_FILES",page:"capture",section:"Requests",title:"Exchanges kept in each place",desc:"How many exchanges are kept for third-party calls, for requests served, and for calls between services. The oldest go first; AI calls are kept.",kept:"machine",applies:"service",kind:"number",number:{unit:"exchanges",min:10},default:1e4,parse:s(t=>{const e=o(t);return e!==void 0&&e>=10?Math.floor(e):void 0},"parse")},{env:"LENSMCP_LOGS",page:"capture",section:"Logs",...v,title:"Mirror the services\u2019 logs",desc:"What each service prints, and what its handlers give the Nest Logger, goes on the lens as logs. Off: Logs shows nothing of the services.",kept:"repository",applies:"service",default:"on",parse:g},{env:"LENSMCP_EVENT_LOOP",page:"capture",section:"Event loops",...v,title:"Measure the services\u2019 event loops",desc:"Samples each service\u2019s event-loop delay, measures slow callbacks and watches for a loop that stops answering. Off: Cluster \u203A Event loops has nothing.",kept:"repository",applies:"service",default:"on",parse:g},{env:"LENSMCP_TRACE_FLOWLESS_MIN_MS",page:"capture",section:"Traces",title:"Shortest traced call outside a request",desc:"A traced method that runs outside any request, flow or job and returns faster than this leaves no span \u2014 a timer that runs every second would otherwise fill the history.",kept:"repository",applies:"service",kind:"number",number:{unit:"ms",min:0,zero:"keep every one"},default:10,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_EVENT_HISTORY_DAYS",page:"history",section:"Event history",title:"Keep the history for",desc:"Rows older than this go. Whichever comes first, this or the size below, decides.",kept:"machine",applies:"lens",kind:"number",number:{unit:"days",min:0,zero:"keep by size only"},default:30,parse:s(t=>{const e=o(t);return e===void 0?void 0:e>0?e:0},"parse")},{env:"LENSMCP_EVENT_HISTORY_MAX_GB",page:"history",section:"Event history",title:"Most history kept",desc:"Past this size the oldest rows go, whatever their age. A busy workspace reaches it in days.",kept:"machine",applies:"lens",kind:"number",number:{unit:"GB",min:0,zero:"no limit"},default:16,parse:s(t=>{const e=o(t);return e===void 0?void 0:e>0?e:0},"parse")},{env:"LENSMCP_EVENT_LOOP_DAYS",page:"history",section:"Event history",title:"Keep event-loop stalls for",desc:"How long a stall and its evidence stay in the history.",kept:"machine",applies:"lens",kind:"number",number:{unit:"days",min:1},default:30,parse:s(t=>{const e=o(t);return e!==void 0&&e>0?e:void 0},"parse")},{env:"LENSMCP_EVENT_MAX_BYTES",page:"history",section:"The event bus",title:"Size of one bus file",desc:"The events every process writes go to .lensmcp/events.jsonl; past this size it is rotated.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"MB",scale:1048576,min:1048576},default:52428800,parse:s(t=>{const e=o(t);return e!==void 0&&e>0?e:void 0},"parse")},{env:"LENSMCP_EVENT_MAX_FILES",page:"history",section:"The event bus",title:"Bus files kept",desc:"How many rotated bus files are kept beside the one being written.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"files",min:1,max:20},default:5,parse:s(t=>{const e=o(t);return e!==void 0&&e>=1&&e<=20?Math.floor(e):void 0},"parse")},{env:"LENSMCP_TYPECHECK",page:"typecheck",section:"The checker",title:"Type checker",desc:"tsgo checks a service after each build with the native compiler and keeps nothing in memory between saves. fork-ts-checker keeps a whole TypeScript program in memory for each service, 1\u20133 GB on a large one. Off: no type errors on the lens.",kept:"repository",applies:"service",kind:"choice",options:[{value:"tsgo",label:"tsgo"},{value:"tsc",label:"fork-ts-checker"},{value:"off",label:"Off"}],default:"tsgo",parse:s(t=>t==="off"?"off":t==="tsgo"||t===""?"tsgo":"tsc","parse")},{env:"LENSMCP_TYPECHECK_MIN_FREE_MB",page:"typecheck",section:"tsgo",title:"Wait for free memory",desc:"A check waits while the machine has less than this free, and the lens says it is held. Each check of a large service takes 1.5\u20133.5 GB while it runs.",kept:"machine",applies:"service",kind:"number",number:{unit:"MB",min:0,zero:"never wait"},default:2048,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?Math.round(e):void 0},"parse")},{env:"LENSMCP_TYPECHECK_CONCURRENCY",page:"typecheck",section:"tsgo",title:"Checks at once on this machine",desc:"How many services are checked at the same time, every workspace\u2019s together. The rest wait their turn.",kept:"machine",applies:"service",kind:"number",number:{unit:"checks",min:1,max:8},default:1,parse:s(t=>{const e=o(t);return e!==void 0&&Number.isInteger(e)&&e>=1?Math.min(e,8):void 0},"parse")},{env:"LENSMCP_TSGO_INCREMENTAL",page:"typecheck",section:"tsgo",...v,title:"Check only what a change affects",desc:"Each service keeps what its last check learnt on disk (tmp/lensmcp-tsgo) and checks again only the files a change can affect. Off: every check is a full one.",kept:"repository",applies:"service",default:"on",parse:S},{env:"LENSMCP_PERF_RULES",page:"performance",section:"Rules",...v,title:"Performance rules",desc:"The rules that flag a barrel import that compiles a whole library, and a pod over its memory budget. Off: Performance shows none of their findings.",kept:"repository",applies:"service",default:"on",parse:S},{env:"LENSMCP_POD_HEAP_BUDGET_MB",page:"performance",section:"Rules",title:"A pod\u2019s memory budget",desc:"The live heap after a full collection above which a pod is flagged as over its budget. A service\u2019s own perfRules in .lensmcp/config.json wins.",kept:"repository",applies:"lens",kind:"number",number:{unit:"MB",min:16,max:1e6},default:512,parse:s(t=>{const e=o(t);return e!==void 0&&e>=16&&e<=1e6?e:void 0},"parse")},{env:"LENSMCP_MAX_COLD_STARTS",page:"services",section:"Starting",title:"Services starting at once",desc:"How many services may cold start together, every workspace\u2019s and worktree\u2019s counted. The rest wait their turn. Fewer start slower but keep a loaded machine answering.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"services",min:0,zero:"no limit"},default:s(()=>Math.max(2,Math.floor(x()/2)),"default"),parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_POD_RESPONSE_TIMEOUT_MS",page:"services",section:"Answering",title:"Wait for a first byte",desc:"How long the gateway waits for a pod\u2019s first byte before it checks the pod is alive. A service\u2019s own cluster.firstByteMs wins.",kept:"repository",applies:"gateway",kind:"number",number:{unit:"s",scale:1e3,min:1e3},default:3e4,parse:s(t=>{const e=o(t);return e!==void 0&&e>0?e:void 0},"parse")},{env:"LENSMCP_POD_RECYCLE",page:"services",section:"Recycling",...v,title:"Recycle a pod that missed a change",desc:"A pod whose watcher missed a file added or removed is replaced by a fresh one. Off: a pod keeps serving its old code until you restart it.",kept:"repository",applies:"gateway",default:"on",parse:g},{env:"LENSMCP_POD_MAX_AGE_MS",page:"services",section:"Recycling",title:"Recycle a pod older than",desc:"A pod this old is replaced even with no change seen \u2014 the one whose watcher went quiet.",kept:"repository",applies:"gateway",kind:"number",number:{unit:"h",scale:36e5,min:0,zero:"never"},default:144e5,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_SWAP_MODE",page:"services",section:"A new build",title:"How a pod takes a new build",desc:"A fresh pod takes each new build and the old one finishes its work. In the same pod: the app is swapped inside the running process \u2014 faster, but a module that holds state can leak.",kept:"repository",applies:"service",kind:"choice",options:[{value:"process",label:"A fresh pod"},{value:"in-process",label:"In the same pod"}],default:"process",parse:s(t=>/^(in-process|inprocess|hot)$/i.test(t.trim())?"in-process":"process","parse")},{env:"LENSMCP_SWAP_DRAIN_MS",page:"services",section:"A new build",title:"Let the old app finish for",desc:"How long the previous app may finish its requests and background jobs before it is closed anyway.",kept:"repository",applies:"service",kind:"number",number:{unit:"min",scale:6e4,min:0,zero:"close at once"},default:9e5,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_SHARED_COMPILER",page:"builds",section:"Compiling",...v,title:"One compilation for every service",desc:"The services of a checkout share one webpack compilation: a shared library is compiled once, not once per service. Off: each service has its own watcher again.",kept:"repository",applies:"service",default:"on",parse:s(t=>/^(0|off|false|no)$/i.test(t.trim())?"off":"on","parse")},{env:"LENSMCP_BUILD_HOST_IDLE_SEC",page:"builds",section:"Compiling",title:"Stop an idle build host after",desc:"How long a checkout\u2019s build host keeps running once none of its services runs.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"min",scale:60,min:0,zero:"never"},default:300,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_DEV_DEVTOOL",page:"builds",section:"Source maps",title:"Source maps in development",desc:"eval is the fastest to build. A full source map gives exact lines in stack traces and costs build time and memory. A serve target\u2019s own devtool wins.",kept:"repository",applies:"service",kind:"choice",options:[{value:"eval",label:"eval"},{value:"eval-cheap-module-source-map",label:"eval-cheap-module-source-map"},{value:"cheap-module-source-map",label:"cheap-module-source-map"},{value:"source-map",label:"source-map"},{value:"off",label:"None"}],default:"eval",parse:s(t=>{const e=t.trim();return e?/^(false|off|none|0)$/i.test(e)?"off":/^(?:eval|(?:inline-|hidden-|eval-)?(?:nosources-)?(?:cheap-(?:module-)?)?source-map(?:-debugids)?)$/.test(e)?e:"eval":"eval"},"parse")},{env:"LENSMCP_WARM_MIN_FREE_MB",page:"worktrees",section:"Starting",title:"Start a worktree\u2019s services only with free memory",desc:"When a worktree registers, its always-warm services start one at a time, each only while the machine has this much free. The rest start on their first request.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"MB",min:0,zero:"no floor"},default:4096,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_WORKTREE_RUN_MAX",page:"worktrees",section:"Starting",title:"On-demand worktrees running at once",desc:"At most this many on-demand worktrees run at the same time. One more is refused, naming those that run and when each parks. The main checkout does not count.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"worktrees",min:0,zero:"no cap"},default:2,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?Math.floor(e):void 0},"parse")},{env:"LENSMCP_WORKTREE_IDLE_SEC",page:"worktrees",section:"Sleeping",title:"Stop an unused worktree service after",desc:"A worktree\u2019s service with no request for this long stops, and starts again on the next one.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"min",scale:60,min:0,zero:"never"},default:1800,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_WORKTREE_RUN_IDLE_SEC",page:"worktrees",section:"Sleeping",title:"Park an unused on-demand worktree after",desc:"An on-demand worktree that runs is parked after this long with no request and no hold: its services, frontends and dashboard stop, and its data is kept. It runs again when asked.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"min",scale:60,min:60},default:900,parse:s(t=>{const e=o(t);return e!==void 0&&e>=60?e:void 0},"parse")},{env:"LENSMCP_DASHBOARD_IDLE_SEC",page:"worktrees",section:"Sleeping",title:"Stop an unused worktree dashboard after",desc:"A worktree\u2019s dashboard starts on its first request and stops after this long with none.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"min",scale:60,min:0,zero:"always up"},default:600,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?e:void 0},"parse")},{env:"LENSMCP_GUEST_REPLAY",page:"worktrees",section:"After a restart",...v,title:"Host the worktrees again after a restart",desc:"A restarted gateway hosts again every worktree and workspace registered with it before. Off: each registers again when its lens starts.",kept:"machine",applies:"gateway",default:"on",parse:g},{env:"LENSMCP_GUEST_MIDDLEWARE",page:"worktrees",section:"Requests",title:"Whose middleware runs on a worktree\u2019s routes",desc:"Its own \u2014 the middleware its gateway target declares; the main checkout\u2019s, on every route; or none.",kept:"machine",applies:"gateway",kind:"choice",options:[{value:"own",label:"Its own"},{value:"owner",label:"The main checkout\u2019s"},{value:"none",label:"None"}],default:"own",parse:s(t=>t==="owner"||t==="none"?t:"own","parse")},{env:"LENSMCP_MAIN_ALWAYS_UP",page:"worktrees",section:"Main checkout",...v,title:"Keep the main checkout always up",desc:"Every main service starts when the gateway does \u2014 the always-warm ones first, then the rest one at a time while memory holds \u2014 and none stops for idleness. Off: the rest start on their first request.",kept:"machine",applies:"gateway",default:"on",parse:S},{env:"LENSMCP_GW_ACT",page:"gateway",section:"Acting as a user",...v,title:"Let agents act as a signed-in user",desc:"An agent may call the services as a user who signed in on this machine, through a ticket the gateway checks. Off: every ticket is refused.",kept:"machine",applies:"gateway",default:"on",parse:g},{env:"LENSMCP_MAX_CONNECTIONS",page:"gateway",section:"Limits",title:"Most connections at once",desc:"The front door\u2019s ceiling on open connections. Past it, new ones wait.",kept:"machine",applies:"gateway",kind:"number",number:{unit:"connections",min:0,zero:"no limit"},default:512,parse:s(t=>{const e=o(t);return e!==void 0&&e>=0?Math.floor(e):void 0},"parse")},{env:"LENSMCP_ANSWER_BUDGET_BYTES",page:"answers",section:"Size",title:"Largest answer to an agent",desc:"Every answer, and every page result_query reads, fits this. A bigger one is folded, or cut when folding is off.",kept:"repository",applies:"lens",kind:"number",number:{unit:"KB",scale:1024,min:2048,zero:"no limit (folding off)"},default:24576,parse:s(t=>{const e=o(t);return e===void 0||e<0?void 0:e===0?0:Math.max(2048,Math.floor(e))},"parse")},{env:"LENSMCP_RESULT_HANDLES_THRESHOLD_BYTES",page:"answers",section:"Size",title:"Fold answers larger than",desc:"An answer at or under this goes to the agent as it is; a larger one goes as a preview and a handle.",kept:"repository",applies:"lens",kind:"number",number:{unit:"KB",scale:1024,min:1024},default:8192,parse:s(t=>{const e=o(t);return e!==void 0&&e>=1024?Math.floor(e):void 0},"parse")}];const y=new Map(SETTINGS.map(t=>[t.env,t]));export const settingOf=s(t=>y.get(t),"settingOf"),defaultOf=s(t=>typeof t.default=="function"?t.default():t.default,"defaultOf");export function valueOf(t,e){const r=t.parse?t.parse(e):e;return r===void 0?defaultOf(t):r}l(valueOf,"valueOf"),u(valueOf,"valueOf"),s(valueOf,"valueOf");export function textFor(t,e){if(t.kind==="toggle")return e!=="on"&&e!=="off"?{refused:`${t.env} is on or off`}:{text:e==="on"?t.write.on:t.write.off};if(t.kind==="choice"){const a=t.options?.find(i=>i.value===e);return a?{text:a.value}:{refused:`${t.env} is one of ${t.options.map(i=>i.value).join(", ")}`}}const r=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN,n=t.number;return Number.isFinite(r)?r===0&&n.zero?{text:"0"}:n.min!==void 0&&r<n.min?{refused:`${t.env} is at least ${n.min}${n.zero?`, or 0 (${n.zero})`:""}`}:n.max!==void 0&&r>n.max?{refused:`${t.env} is at most ${n.max}`}:{text:String(r)}:{refused:`${t.env} is a number`}}l(textFor,"textFor"),u(textFor,"textFor"),s(textFor,"textFor");export const PROJECT_FILE_NAME="lensmcp.json";export function machineSettingsFile(t=process.env){return w(t.LENSMCP_HOME||I(),".lensmcp","settings.json")}l(machineSettingsFile,"machineSettingsFile"),u(machineSettingsFile,"machineSettingsFile"),s(machineSettingsFile,"machineSettingsFile");const k=new Map;function b(t){let e;try{const a=P(t);e=`${a.size}:${a.mtimeMs}`}catch{return k.delete(t),{}}const r=k.get(t);if(r?.stamp===e)return r.settings;const n={};try{const a=JSON.parse(E(t,"utf8"));if(a.settings&&typeof a.settings=="object"&&!Array.isArray(a.settings))for(const[i,c]of Object.entries(a.settings))y.has(i)&&(typeof c=="string"||typeof c=="number")&&(n[i]=String(c))}catch{}return k.set(t,{stamp:e,settings:n}),n}l(b,"E"),u(b,"b"),s(b,"fileSettings");export function readKeptSettings(t,e=process.env){const r=b(w(t,PROJECT_FILE_NAME)),n=b(machineSettingsFile(e)),a=s((i,c)=>Object.fromEntries(Object.entries(i).filter(([h])=>y.get(h)?.kept===c)),"pick");return{repository:a(r,"repository"),machine:a(n,"machine")}}l(readKeptSettings,"readKeptSettings"),u(readKeptSettings,"readKeptSettings"),s(readKeptSettings,"readKeptSettings");export function keptEnv(t,e=process.env){const r=readKeptSettings(t,e);return{...r.machine,...r.repository}}l(keptEnv,"keptEnv"),u(keptEnv,"keptEnv"),s(keptEnv,"keptEnv");export const KEPT_MARK="LENSMCP_KEPT_SETTINGS";const _=s(t=>new Set((t[KEPT_MARK]??"").split(",").filter(Boolean)),"markedNames");export const fromSettings=s((t,e=process.env)=>e[t]!==void 0&&_(e).has(t),"fromSettings"),DOTENV_FILES=[".env.local",".local.env",".env"];export function dotenvKeys(t){const e=new Map;for(const r of DOTENV_FILES){let n;try{n=E(w(t,r),"utf8")}catch{continue}for(const a of n.matchAll(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/gm))e.has(a[1])||e.set(a[1],r)}return e}l(dotenvKeys,"dotenvKeys"),u(dotenvKeys,"dotenvKeys"),s(dotenvKeys,"dotenvKeys");export const dotenvDeclaring=s((t,e)=>dotenvKeys(t).get(e),"dotenvDeclaring");export function withKeptSettings(t,e,r=process.env){const n={...e},a=keptEnv(t,r),i=_(e),c=dotenvKeys(t),h=[];for(const f of SETTINGS){const d=f.env;if(n[d]!==void 0&&!i.has(d))continue;const m=a[d];m===void 0||c.has(d)?delete n[d]:(n[d]=m,h.push(d))}return h.length?n[KEPT_MARK]=h.join(","):delete n[KEPT_MARK],n}l(withKeptSettings,"withKeptSettings"),u(withKeptSettings,"withKeptSettings"),s(withKeptSettings,"withKeptSettings");export function applyKeptSettings(t,e=process.env){const r=withKeptSettings(t,e,e);for(const n of[...SETTINGS.map(a=>a.env),KEPT_MARK])r[n]===void 0?delete e[n]:e[n]=r[n];return[..._(e)]}l(applyKeptSettings,"applyKeptSettings"),u(applyKeptSettings,"applyKeptSettings"),s(applyKeptSettings,"applyKeptSettings");export function resolveSetting(t,e,r=process.env,n=readKeptSettings(e,r)){const a=n[t.kept][t.env],i=r[t.env];return i!==void 0&&!fromSettings(t.env,r)?{value:valueOf(t,i),source:"env",envFrom:dotenvDeclaring(e,t.env)??"shell",...a!==void 0?{kept:a}:{}}:a!==void 0?{value:valueOf(t,a),source:t.kept}:{value:defaultOf(t),source:"default"}}l(resolveSetting,"resolveSetting"),u(resolveSetting,"resolveSetting"),s(resolveSetting,"resolveSetting");export function writeKeptSetting(t,e,r,n=process.env){const a=y.get(e);if(!a)throw new Error(`${e} is not a setting`);const i=a.kept==="repository"?w(t,PROJECT_FILE_NAME):machineSettingsFile(n);let c={},h=!0;try{const p=JSON.parse(E(i,"utf8"));if(!p||typeof p!="object"||Array.isArray(p))throw new Error(`${i} is not a JSON object \u2014 fix it by hand first`);c=p}catch(p){if(p.code!=="ENOENT")throw p instanceof SyntaxError?new Error(`${i} is not valid JSON (${p.message}) \u2014 fix it by hand first`):p;h=!1}const f=c.settings&&typeof c.settings=="object"&&!Array.isArray(c.settings)?{...c.settings}:{},d=typeof f[e]=="string"||typeof f[e]=="number"?String(f[e]):null;if(r===null?delete f[e]:f[e]=r,Object.keys(f).length?c.settings=Object.fromEntries(Object.entries(f).sort(([p],[M])=>p.localeCompare(M))):delete c.settings,!h&&!c.settings)return d;h||(c={schemaVersion:1,...c}),R(K(i),{recursive:!0});const m=`${i}.${process.pid}.tmp`;try{T(m,`${JSON.stringify(c,null,2)}
|
|
2
|
+
`),C(m,i)}catch(p){try{A(m)}catch{}throw p}return k.delete(i),d}l(writeKeptSetting,"writeKeptSetting"),u(writeKeptSetting,"writeKeptSetting"),s(writeKeptSetting,"writeKeptSetting");
|
package/lib/sql-shape.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`||
|
|
3
|
-
`,s);
|
|
1
|
+
"use strict";var b=Object.defineProperty;var f=(e,n)=>b(e,"name",{value:n,configurable:!0});var $=Object.defineProperty,T=f((e,n)=>$(e,"name",{value:n,configurable:!0}),"a"),F=Object.defineProperty,p=T((e,n)=>F(e,"name",{value:n,configurable:!0}),"p");const G=/[A-Za-z_\u0080-]/,v=/[A-Za-z0-9_$\u0080-]/;function N(e){const n=[],u=[];let l=0;const o=e.length;let s=0;const r=p((i,t)=>n.push({kind:i,text:t,up:i==="word"?t.toUpperCase():t}),"push");for(;s<o;){const i=e[s];if(i===" "||i===`
|
|
2
|
+
`||i===" "||i==="\r")s++;else if(i==="-"&&e[s+1]==="-"){l++;const t=e.indexOf(`
|
|
3
|
+
`,s);u.push(e.slice(s+2,t<0?o:t).trim()),s=t<0?o:t+1}else if(i==="/"&&e[s+1]==="*"){const t=e.indexOf("*/",s+2);u.push(e.slice(s+2,t<0?o:t).trim()),s=t<0?o:t+2}else if(i==="'"||(i==="E"||i==="e")&&e[s+1]==="'"){let t=i==="'"?s+1:s+2;for(;t<o;)if(e[t]==="\\"&&i!=="'")t+=2;else if(e[t]==="'"&&e[t+1]==="'")t+=2;else{if(e[t]==="'")break;t++}r("string",e.slice(s,t+1)),s=t+1}else if(i==="$"&&/[0-9]/.test(e[s+1]??"")){let t=s+1;for(;t<o&&/[0-9]/.test(e[t]);)t++;r("param",e.slice(s,t)),s=t}else if(i==="$"){const t=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(s,s+64));if(t){const a=e.indexOf(t[0],s+t[0].length),A=a<0?o:a+t[0].length;r("string",e.slice(s,A)),s=A}else r("punct",i),s++}else if(i==='"'){let t=s+1;for(;t<o&&!(e[t]==='"'&&e[t+1]!=='"');)t+=e[t]==='"'?2:1;t<o&&r("qident",e.slice(s,t+1)),s=t+1}else if(/[0-9]/.test(i)||i==="."&&/[0-9]/.test(e[s+1]??"")){let t=s;for(;t<o&&/[0-9.eE]/.test(e[t]);)t++;r("number",e.slice(s,t)),s=t}else if(G.test(i)){let t=s;for(;t<o&&v.test(e[t]);)t++;r("word",e.slice(s,t)),s=t}else if("(),;[].".includes(i))r("punct",i),s++;else{let t=s;for(;t<o&&/[+\-*/<>=~!@#%^&|`?:]/.test(e[t])&&!(e[t]==="-"&&e[t+1]==="-")&&!(e[t]==="/"&&e[t+1]==="*");)t++;t===s&&(t=s+1),r("op",e.slice(s,t)),s=t}}return{tokens:n,comments:u,lineComments:l}}f(N,"I"),T(N,"I"),p(N,"lex");function g(e){const n=new Map,u=[],l=[],o=[];e.forEach((s,r)=>{if(s.text===")"||s.text==="]"){const i=o.pop();i!==void 0&&n.set(i,r)}u.push(o.length),l.push(o[o.length-1]??-1),(s.text==="("||s.text==="[")&&o.push(r)});for(const s of o)n.set(s,e.length);return{close:n,depth:u,opener:l}}f(g,"U"),T(g,"D"),p(g,"structure");const H=new Set(["SELECT","INSERT","UPDATE","DELETE","MERGE","VALUES","TABLE"]),k=new Set(["SELECT","FROM","WHERE","JOIN","LEFT","RIGHT","INNER","OUTER","FULL","CROSS","NATURAL","ON","USING","GROUP","ORDER","BY","HAVING","LIMIT","OFFSET","FETCH","UNION","EXCEPT","INTERSECT","RETURNING","SET","VALUES","WINDOW","FOR","LATERAL","ONLY","AS","WITH","INTO","UPDATE","DELETE","INSERT","DEFAULT","DO","NOTHING","CONFLICT","AND","OR","NOT","IS","NULL","IN","EXISTS","CASE","WHEN","THEN","ELSE","END","TABLESAMPLE","OVERRIDING","MATCHED","MERGE"]);function m(e,n,u=!1){const l=p(r=>r?r.kind==="qident"?r.text.slice(1,-1).replace(/""/g,'"'):r.kind==="word"&&!k.has(r.up)?r.text:void 0:void 0,"part");let o=l(e[n]);if(!o)return;let s=n+1;for(;e[s]?.text==="."&&l(e[s+1]);)o=`${o}.${l(e[s+1])}`,s+=2;if(!(e[s]?.text==="("&&!u))return{name:o.replace(/^public\./i,""),next:s}}f(m,"O"),T(m,"g"),p(m,"tableAt");function U(e,n,u){e[n]?.up==="AS"&&n++;const l=e[n];return l&&(l.kind==="qident"||l.kind==="word"&&!k.has(l.up))&&(n++,e[n]?.text==="("&&(n=(u.get(n)??n)+1)),n}f(U,"C"),T(U,"k"),p(U,"skipAlias");function O(e){let n=2166136261,u=16777619;for(let l=0;l<e.length;l++){const o=e.charCodeAt(l);n=Math.imul(n^o,16777619)>>>0,u=Math.imul(u^o,1540483477)>>>0}return(n.toString(16).padStart(8,"0")+u.toString(16).padStart(8,"0")).slice(0,12)}f(O,"m"),T(O,"w"),p(O,"hashId");function C(e,n){const u=p((r,i)=>r.kind==="string"||r.kind==="number"||r.kind==="param"||[",","::","-","[","]"].includes(r.text)||r.kind==="word"&&(/^(NULL|TRUE|FALSE|DEFAULT)$/i.test(r.text)||i?.text==="::"),"isValue"),l=[];let o=0;for(;o<e.length;){const r=e[o],i=e[o-1];if(r.text==="("&&(i?.up==="IN"||i?.up==="VALUES")){const t=n.get(o)??e.length,a=e.slice(o+1,t);if(a.length&&a.every((A,L)=>u(A,a[L-1]))){if(l.push({kind:"punct",text:"(\u2026)",up:"(\u2026)"}),o=t+1,i.up==="VALUES")for(;e[o]?.text===","&&e[o+1]?.text==="(";)o=(n.get(o+1)??e.length)+1;continue}}l.push(r.kind==="string"||r.kind==="number"?{kind:"op",text:"?",up:"?"}:r),o++}let s="";return l.forEach((r,i)=>{const t=l[i-1],a=!t||["(","[",".","::"].includes(t.text)||[")","]",",",".","::"].includes(r.text)||(r.text==="("||r.text==="(\u2026)"||r.text==="[")&&(t.kind==="qident"||t.kind==="word"&&!k.has(t.up));s+=(a?"":" ")+r.text}),s.trim()}f(C,"w"),T(C,"$"),p(C,"templateOf");const I=new Map,q=512;export function sqlShape(e){const n=I.get(e);if(n)return n;let u;try{u=w(e)}catch{u={id:O(e),template:e.trim().replace(/\s+/g," "),verb:"QUERY",tables:[]}}return I.set(e,u),I.size>q&&I.delete(I.keys().next().value),u}f(sqlShape,"sqlShape"),T(sqlShape,"sqlShape"),p(sqlShape,"sqlShape");function w(e){const{tokens:n,comments:u}=N(e),{close:l,depth:o,opener:s}=g(n);let r=n.find(E=>E.kind==="word")?.up??"QUERY";const i=new Set;n.forEach((E,d)=>{if(E.up!=="WITH"||n[d-1]?.up==="START")return;let c=d+1;for(n[c]?.up==="RECURSIVE"&&c++;;){const S=n[c];if(!S||S.kind!=="word"&&S.kind!=="qident"||(i.add(S.kind==="qident"?S.text.slice(1,-1):S.text),c++,n[c]?.text==="("&&(c=(l.get(c)??c)+1),n[c]?.up!=="AS")||(c++,n[c]?.up==="NOT"&&c++,n[c]?.up==="MATERIALIZED"&&c++,n[c]?.text!=="(")||(c=(l.get(c)??n.length)+1,n[c]?.text!==","))break;c++}}),r==="WITH"&&(r=n.find((E,d)=>o[d]===0&&H.has(E.up)&&d>0)?.up??"SELECT");const t=[];let a;const A=p(E=>{i.has(E)||/^\$/.test(E)||t.includes(E)||t.push(E)},"add");if(n.forEach((E,d)=>{const c=n[d-1]?.up,S=E.up==="FROM"||E.up==="JOIN",M=E.up==="INTO"&&(c==="INSERT"||c==="MERGE")||E.up==="UPDATE"&&c!=="DO"&&c!=="FOR"&&c!=="KEY"&&c!=="NO"||E.up==="USING"||E.up==="TABLE"&&d===0;if(!S&&!M)return;const x=s[d]??-1;if(S&&x>=0&&n[x-1]?.kind==="word"&&!["IN","EXISTS","ANY","ALL","AS","FROM","JOIN","LATERAL","SOME","ARRAY"].includes(n[x-1].up)&&n[x+1]?.up!=="SELECT"&&n[x+1]?.up!=="WITH")return;let h=d+1;for(;n[h]?.up==="ONLY"||n[h]?.up==="LATERAL";)h++;for(;;){const R=m(n,h,E.up==="INTO");if(!R||(A(R.name),M&&!a&&E.up!=="USING"&&(a=R.name),h=U(n,R.next,l),!S||n[h]?.text!==","))break;h++}}),(r==="DELETE"||r==="UPDATE"||r==="INSERT"||r==="MERGE")&&!a){const E=n.findIndex((d,c)=>d.up==="FROM"&&n[c-1]?.up==="DELETE");E>=0&&(a=m(n,E+1)?.name)}const L=C(n,l),D=u.find(E=>/^[\w.\-/:]{3,80}$/.test(E));return{id:O(`${r} ${L.replace(/\$\d+/g,"$?")}`),template:L,verb:r,tables:t,...a?{target:a}:{},...D?{name:D}:{}}}f(w,"D"),T(w,"G"),p(w,"compute");export function statementCount(e){let n=0,u=!1;for(const l of N(e).tokens)l.text===";"?(u&&n++,u=!1):u=!0;return n+(u?1:0)}f(statementCount,"statementCount"),T(statementCount,"statementCount"),p(statementCount,"statementCount");export function shapeMatchKey(e){const n=sqlShape(e),u=n.template.replace(/"(?:[^"]|"")*"|[^"]+/g,l=>l.startsWith('"')?l:l.toLowerCase());return`${n.verb} ${u.replace(/\$\d+/g,"?").replace(/\b(?:true|false)\b/g,"?")}`}f(shapeMatchKey,"shapeMatchKey"),T(shapeMatchKey,"shapeMatchKey"),p(shapeMatchKey,"shapeMatchKey");export function lineCommentSwallows(e){return!/\n/.test(e)&&N(e).lineComments>0}f(lineCommentSwallows,"lineCommentSwallows"),T(lineCommentSwallows,"lineCommentSwallows"),p(lineCommentSwallows,"lineCommentSwallows");
|