@lensmcp/core 1.25.16 → 1.25.18
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/lib/ai-content.js +1 -1
- package/lib/answer-budget.js +2 -2
- package/lib/bus-rotation.js +1 -1
- package/lib/event-bus.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 +2 -0
- 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.d.ts +10 -0
- package/lib/key-pattern.js +1 -0
- package/lib/lens-dir.js +1 -1
- package/lib/lens-events.js +2 -2
- package/lib/patterns.js +1 -1
- package/lib/pg-errors.js +1 -1
- package/lib/redact.d.ts +13 -0
- package/lib/redact.js +1 -1
- package/lib/reducer-registry.js +1 -1
- package/lib/replay-store.d.ts +24 -0
- package/lib/replay-store.js +1 -0
- package/lib/resource-store.js +1 -1
- package/lib/route-template.js +1 -1
- package/lib/sql-shape.js +3 -3
- package/lib/sql-values.d.ts +50 -0
- package/lib/sql-values.js +1 -0
- 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/ai-content.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var c=Object.defineProperty;var n=(e,t)=>c(e,"name",{value:t,configurable:!0});var s=Object.defineProperty,i=n((e,t)=>s(e,"name",{value:t,configurable:!0}),"r"),l=Object.defineProperty,o=i((e,t)=>l(e,"name",{value:t,configurable:!0}),"r");import*as d from"node:fs";import{dirname as f,join as a}from"node:path";export const AI_CONTENT_DIR="ai";const u=/^ai_[0-9a-z]{8,40}$/;export const isAiCallId=o(e=>typeof e=="string"&&u.test(e),"isAiCallId");export function aiContentDir(e){return a(f(e),AI_CONTENT_DIR)}n(aiContentDir,"aiContentDir"),i(aiContentDir,"aiContentDir"),o(aiContentDir,"aiContentDir");export function aiContentFile(e,t){if(!isAiCallId(t))throw new Error("invalid ai call id");return a(aiContentDir(e),`${t}.json`)}n(aiContentFile,"aiContentFile"),i(aiContentFile,"aiContentFile"),o(aiContentFile,"aiContentFile");export function readAiContent(e,t){if(isAiCallId(t))try{const r=JSON.parse(d.readFileSync(aiContentFile(e,t),"utf8"));return r&&r.schemaVersion===1&&r.id===t?r:void 0}catch{return}}n(readAiContent,"readAiContent"),i(readAiContent,"readAiContent"),o(readAiContent,"readAiContent");
|
package/lib/answer-budget.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`,r);return i>=r/2&&(r=i),r>0&&(
|
|
1
|
+
"use strict";var G=Object.defineProperty;var d=(t,e)=>G(t,"name",{value:e,configurable:!0});var W=Object.defineProperty,g=d((t,e)=>W(t,"name",{value:e,configurable:!0}),"d"),U=Object.defineProperty,c=g((t,e)=>U(t,"name",{value:e,configurable:!0}),"a");import{boundedClone as z}from"@lensmcp/protocol-types";export const DEFAULT_ANSWER_BUDGET_BYTES=24*1024,ANSWER_BUDGET_ENV="LENSMCP_ANSWER_BUDGET_BYTES",MIN_ANSWER_BUDGET_BYTES=2*1024,ANSWER_CUT_KEY="cutToFit",FITTED_STRING_CHARS=1500,REPEATED_STRING_MIN_CHARS=200;const R=900,V=32,H=new Set(["timestamp","startedAt","startTime","at","emittedAt","lastSeenAt","endedAt","endTime","t","ts","time"]),J=c(t=>typeof t=="number"&&t>=1e11&&t<=1e14,"isEpochMs"),K=.95;export function answerBudgetBytes(t=process.env){const e=t[ANSWER_BUDGET_ENV];if(e===void 0||e.trim()==="")return DEFAULT_ANSWER_BUDGET_BYTES;const r=Number(e);return!Number.isFinite(r)||r<0?DEFAULT_ANSWER_BUDGET_BYTES:r===0?Number.POSITIVE_INFINITY:Math.max(MIN_ANSWER_BUDGET_BYTES,Math.floor(r))}d(answerBudgetBytes,"answerBudgetBytes"),g(answerBudgetBytes,"answerBudgetBytes"),c(answerBudgetBytes,"answerBudgetBytes");export function utf8Bytes(t){let e=0;for(let r=0;r<t.length;r++){const i=t.charCodeAt(r);i<128?e+=1:i<2048?e+=2:i>=55296&&i<=56319&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(e+=4,r+=1):e+=3}return e}d(utf8Bytes,"utf8Bytes"),g(utf8Bytes,"utf8Bytes"),c(utf8Bytes,"utf8Bytes");export function jsonBytes(t){let e;try{e=JSON.stringify(t)}catch{return Number.POSITIVE_INFINITY}return e===void 0?0:utf8Bytes(e)}d(jsonBytes,"jsonBytes"),g(jsonBytes,"jsonBytes"),c(jsonBytes,"jsonBytes");const C=c(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),"isRecord");function N(t){if(!C(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}d(N,"R"),g(N,"D"),c(N,"isPlain");export function newestEndOf(t){const e=t[0];if(t.length<2||!C(e))return;let r;for(const i of Object.keys(e)){if(typeof e[i]!="number"||!(H.has(i)||J(e[i])))continue;let s=0,f=0,l=!0,y=e[i];for(let E=1;E<t.length;E++){const b=t[E],p=C(b)?b[i]:void 0;if(typeof p!="number"){l=!1;break}p>y?s+=1:p<y&&(f+=1),y=p}const S=s+f;if(!l||S===0)continue;const x=Math.max(s,f)/S;x>=K&&(!r||x>r.agreement)&&(r={end:s>=f?"end":"start",agreement:x})}return r?.end}d(newestEndOf,"newestEndOf"),g(newestEndOf,"newestEndOf"),c(newestEndOf,"newestEndOf");export function newestFirst(t){return newestEndOf(t)==="end"?[...t].reverse():t.slice()}d(newestFirst,"newestFirst"),g(newestFirst,"newestFirst"),c(newestFirst,"newestFirst");export function shortenText(t,e){if(t.length<=e)return t;let r=Math.max(0,e);const i=t.lastIndexOf(`
|
|
2
|
+
`,r);return i>=r/2&&(r=i),r>0&&(t.charCodeAt(r-1)&64512)===55296&&(r-=1),`${t.slice(0,r)}\u2026[lensmcp truncated: ${t.length-r} more chars]`}d(shortenText,"shortenText"),g(shortenText,"shortenText"),c(shortenText,"shortenText");export function fitList(t,e,r={}){const i=t.length,s=t.reduce((o,u)=>o+jsonBytes(u)+1,2);if(s<=e)return{items:t.slice(),total:i,returned:i,kept:"all",shortenedStrings:0,repeatedStrings:0,bytes:s};const f=r.newest??newestEndOf(t),l=f??r.keep??"start",y=r.name??"items",S=r.maxStringChars??FITTED_STRING_CHARS,x=l==="start"?t:[...t].reverse(),E=String(Math.max(0,i-1)).length,b=new Map,p=[],h=[];let w=2,A=0,$=0;for(let o=0;o<x.length;o++){const u=new Map,v=[];let j=0;const I=c((a,k,F,Y,D)=>{if(typeof a=="string"){if(a.length>=REPEATED_STRING_MIN_CHARS){const m=b.get(a)??u.get(a);if(m)return v.push({holder:Y,key:D,owner:m.owner,path:m.path}),`\u2026[lensmcp: same text as ${y}[${"9".repeat(E)}]${m.path}]`;u.set(a,{owner:o,path:k})}return a.length>S?(j+=1,shortenText(a,S)):a}if(F>=V)return a;if(Array.isArray(a)){const m=[];return a.forEach((T,P)=>m.push(I(T,`${k}[${P}]`,F+1,m,P))),m}if(N(a)){const m={};for(const T of Object.keys(a))m[T]=I(a[T],`${k}.${T}`,F+1,m,T);return m}return a},"slim"),L=[];let M=I(x[o],"",0,L,0),_=jsonBytes(M)+1;if(h.length===0&&w+_>e)M=O(x[o],Math.max(0,e-w-1)),_=jsonBytes(M)+1,v.length=0,u.clear(),j=1;else if(w+_>e)break;h.push(M),w+=_,A+=j,$+=v.length;for(const[a,k]of u)b.set(a,k);for(const a of v)p.push(a.holder===L?{...a,holder:h,key:h.length-1}:a)}const B=h.length,n=c(o=>l==="start"?o:B-1-o,"indexOf");if(l==="end"){for(const o of p)o.holder===h&&(o.key=n(o.key));h.reverse()}for(const o of p)o.holder[o.key]=`\u2026[lensmcp: same text as ${y}[${n(o.owner)}]${o.path}]`;return{items:h,total:i,returned:B,kept:B===i?"all":f?"newest":l==="start"?"first":"last",shortenedStrings:A,repeatedStrings:$,bytes:jsonBytes(h)}}d(fitList,"fitList"),g(fitList,"fitList"),c(fitList,"fitList");function O(t,e){let r=Math.max(256,e),i=t;for(let s=0;s<6;s++){if(i=z(t,{rawByteLimit:r,maxStringBytes:Math.min(2e3,Math.max(128,Math.floor(r/4))),maxArrayItems:64}).value,jsonBytes(i)<=e)return i;r=Math.floor(r*.6)}return i}d(O,"C"),g(O,"Y"),c(O,"clampTo");export function shareBudget(t,e){const r=t.map((f,l)=>({size:f,index:l})).sort((f,l)=>f.size-l.size),i=new Array(t.length).fill(0);let s=Math.max(0,e);return r.forEach(({size:f,index:l},y)=>{const S=Math.floor(s/(r.length-y));i[l]=Math.min(f,S),s-=i[l]}),i}d(shareBudget,"shareBudget"),g(shareBudget,"shareBudget"),c(shareBudget,"shareBudget");export function fitAnswer(t,e,r={}){if(!Number.isFinite(e)||t===null||typeof t!="object")return{value:t};const i=jsonBytes(t);if(i<=e)return{value:t};const s={limitBytes:e,originalBytes:i,lists:[],shortenedStrings:0,repeatedStrings:0,note:""},f=c(()=>{const n=s.lists.map(o=>`\`${o.list}\` shows the ${o.kept} ${o.returned} of ${o.total}`);s.note=`Cut to fit one tool result (${e} bytes; the whole answer is ${Number.isFinite(i)?i:"larger"}) \u2014 it is still one valid JSON document.`+(n.length?` ${n.join("; ")}; any other count in this document describes the whole list.`:"")+(s.shortenedStrings?` ${s.shortenedStrings} long text${s.shortenedStrings===1?" was":"s were"} cut to the head.`:"")+(s.repeatedStrings?` ${s.repeatedStrings} repeated text${s.repeatedStrings===1?" is":"s are"} stated once and referenced.`:"")+(s.clamped?" Large values outside the lists were shrunk too (see `__lensmcpTruncation`).":"")+(r.more?` ${r.more}`:"")+` Whole answer: start the lens with ${ANSWER_BUDGET_ENV}=0.`},"describe");if(Array.isArray(t)){const n=fitList(t,e);return n.kept!=="all"&&s.lists.push({list:"items",total:n.total,returned:n.returned,kept:n.kept}),s.shortenedStrings=n.shortenedStrings,s.repeatedStrings=n.repeatedStrings,f(),{value:n.items,cut:s}}if(!N(t))return{value:t};const l=Object.keys(t),y=l.filter(n=>Array.isArray(t[n])&&t[n].length>0),S=y.map(n=>jsonBytes(t[n])),x=i-S.reduce((n,o)=>n+o,0),E=shareBudget(S,e-x-R),b={};y.forEach((n,o)=>{if(S[o]<=E[o])return;const u=fitList(t[n],E[o],{name:n,...r.newest?.[n]?{newest:r.newest[n]}:{}});b[n]=u.items,u.kept!=="all"&&s.lists.push({list:n,total:u.total,returned:u.returned,kept:u.kept}),s.shortenedStrings+=u.shortenedStrings,s.repeatedStrings+=u.repeatedStrings});const p=c(n=>(f(),{[ANSWER_CUT_KEY]:s,...n}),"assemble"),h={};for(const n of l)h[n]=n in b?b[n]:t[n];let w=p(h);if(jsonBytes(w)<=e)return{value:w,cut:s};s.clamped=!0;let A=Math.max(512,e-R);for(let n=0;n<6;n++){if(w=p(O(h,A)),jsonBytes(w)<=e)return{value:w,cut:s};A=Math.floor(A*.6)}const $={};let B=R;for(const n of l){const o=t[n];if(o!==null&&typeof o=="object")continue;const u=jsonBytes(o)+utf8Bytes(n)+4;if(B+u>e)break;$[n]=o,B+=u}return{value:p($),cut:s}}d(fitAnswer,"fitAnswer"),g(fitAnswer,"fitAnswer"),c(fitAnswer,"fitAnswer");
|
package/lib/bus-rotation.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var m=Object.defineProperty;var i=(e,r)=>m(e,"name",{value:r,configurable:!0});var S=Object.defineProperty,y=i((e,r)=>S(e,"name",{value:r,configurable:!0}),"i"),f=Object.defineProperty,l=y((e,r)=>f(e,"name",{value:r,configurable:!0}),"u");export const MAX_BUS_GENERATIONS=20,BUS_ROTATE_CHECK_BYTES=1048576;export function busCapsFromEnv(e=process.env){const r=Number(e.LENSMCP_EVENT_MAX_BYTES),t=Number(e.LENSMCP_EVENT_MAX_FILES);return{maxBytes:Number.isFinite(r)&&r>0?r:50*1024*1024,maxFiles:Number.isFinite(t)&&t>=1&&t<=20?Math.floor(t):5}}i(busCapsFromEnv,"busCapsFromEnv"),y(busCapsFromEnv,"busCapsFromEnv"),l(busCapsFromEnv,"busCapsFromEnv");export function rotateBusFile(e,r){const{fs:t,maxBytes:u,maxFiles:a}=r,c=`${e}.rotate.lock`,o=r.staleLockMs??3e4;let s;for(let n=0;n<2&&s===void 0;n++)try{s=t.openSync(c,"wx")}catch{try{if(Date.now()-t.statSync(c).mtimeMs<=o)return"busy";t.unlinkSync(c)}catch{}}if(s===void 0)return"busy";try{try{if(t.statSync(e).size<=u)return"not-needed"}catch{return"not-needed"}try{t.unlinkSync(`${e}.${a}`)}catch{}for(let n=a+1;n<=20;n++)try{t.unlinkSync(`${e}.${n}`)}catch{}for(let n=a-1;n>=1;n--)try{t.renameSync(`${e}.${n}`,`${e}.${n+1}`)}catch{}try{t.renameSync(e,`${e}.1`)}catch{}return"rotated"}finally{try{t.closeSync(s)}catch{}try{t.unlinkSync(c)}catch{}}}i(rotateBusFile,"rotateBusFile"),y(rotateBusFile,"rotateBusFile"),l(rotateBusFile,"rotateBusFile");export function createBusRotator(e,r){const{fs:t,maxBytes:u}=r,a=Math.max(0,Math.min(r.checkEveryBytes??1048576,u));let c=a,o=0;return s=>{if(c>=a||o+c>u)try{o=t.statSync(e).size,c=0,o>u&&rotateBusFile(e,r)==="rotated"&&(o=0)}catch{}c+=s}}i(createBusRotator,"createBusRotator"),y(createBusRotator,"createBusRotator"),l(createBusRotator,"createBusRotator");
|
package/lib/event-bus.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var c=Object.defineProperty;var n=(s,t)=>c(s,"name",{value:t,configurable:!0});var a=Object.defineProperty,o=n((s,t)=>a(s,"name",{value:t,configurable:!0}),"n"),h=Object.defineProperty,u=o((s,t)=>h(s,"name",{value:t,configurable:!0}),"e");export class EventBus{static{n(this,"EventBus")}static{o(this,"EventBus")}static{u(this,"EventBus")}constructor(t={}){this.subs=new Set,this.dropped=0,this.capacity=t.capacity??1e4,this.onDrop=t.onDrop,this.transform=t.transform}publish(t){if(this.subs.size>this.capacity){this.dropped++,this.onDrop?.(1);return}let r=t;if(this.transform)try{r=this.transform(t)??t}catch{r=t}for(const e of this.subs)if(!(e.filter&&!e.filter(r)))try{const i=e.handler(r);i&&typeof i.then=="function"&&i.catch(()=>{})}catch{}}subscribe(t,r){const e={handler:t,filter:r};return this.subs.add(e),()=>{this.subs.delete(e)}}droppedCount(){return this.dropped}subscriberCount(){return this.subs.size}}
|
package/lib/event-redactor.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var m=Object.defineProperty;var o=(e,a)=>m(e,"name",{value:a,configurable:!0});var T=Object.defineProperty,v=o((e,a)=>T(e,"name",{value:a,configurable:!0}),"o"),y=Object.defineProperty,i=v((e,a)=>y(e,"name",{value:a,configurable:!0}),"a");import{MAX_MESSAGE_CHARS as E,MAX_TITLE_CHARS as S,redactDeep as _,redactSqlParams as g,redactText as f,safeText as R,safeTitle as x}from"./redact.js";export const BUS_REDACT_MAX_DEPTH=12;export function createEventRedactor(e={}){const a=e.maxDepth??BUS_REDACT_MAX_DEPTH;let s=0,r=0;return{redact(t){s+=1;const c=t.title===void 0?void 0:x(f(t.title)),n=t.message===void 0?void 0:R(f(t.message),E),d=t.raw===void 0?void 0:p(_(t.raw,0,a)),u=c!==t.title,A=n!==t.message,l=d!==t.raw;return!u&&!A&&!l?t:(r+=1,{...t,...c!==void 0?{title:c}:{},...n!==void 0?{message:n}:{},...d!==void 0?{raw:d}:{}})},stats:i(()=>({inspected:s,redacted:r}),"stats"),reset:i(()=>{s=0,r=0},"reset")}}o(createEventRedactor,"createEventRedactor"),v(createEventRedactor,"createEventRedactor"),i(createEventRedactor,"createEventRedactor");function p(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const a=e,s=a.query,r=a.params;if(typeof s!="string"||!Array.isArray(r))return e;const t=g(s,r);return t===r?e:{...a,params:t}}o(p,"v"),v(p,"T"),i(p,"redactSqlShape");export{S as MAX_TITLE_CHARS};
|
package/lib/fingerprint.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var f=Object.defineProperty;var r=(e,t)=>f(e,"name",{value:t,configurable:!0});var l=Object.defineProperty,n=r((e,t)=>l(e,"name",{value:t,configurable:!0}),"r"),u=Object.defineProperty,o=n((e,t)=>u(e,"name",{value:t,configurable:!0}),"e");const d=2166136261,g=16777619;function a(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}r(a,"o"),n(a,"i"),o(a,"fnv1a32");export function fingerprint(e){const t=[e.kind,e.identity,e.file??"",e.detail??""];return`${e.kind}:${a(t.join("|"))}`}r(fingerprint,"fingerprint"),n(fingerprint,"fingerprint"),o(fingerprint,"fingerprint");
|
package/lib/flow-categories.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var F=Object.defineProperty;var c=(e,t)=>F(e,"name",{value:t,configurable:!0});var T=Object.defineProperty,d=c((e,t)=>T(e,"name",{value:t,configurable:!0}),"c"),S=Object.defineProperty,s=d((e,t)=>S(e,"name",{value:t,configurable:!0}),"s");export const CATEGORY_ORDER=["user-action","page-load","navigation","api","ai","background","test","system","other"];const f=new Map;export function globMatch(e,t){let o=f.get(e);return o||(o=new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")}$`),f.size>500&&f.clear(),f.set(e,o)),o.test(t)}c(globMatch,"globMatch"),d(globMatch,"globMatch"),s(globMatch,"globMatch");const z=s(e=>/^[A-Z]+ /.test(e),"hasMethod");function v(e,t){return t.some(o=>o.route?z(e)?globMatch(e,`${o.method??"GET"} ${o.route}`):globMatch(e,o.route):!1)}c(v,"w"),d(v,"$"),s(v,"routeMatches");function m(e,t){return!([e.flowId,e.originType,e.origin,e.route,e.project].filter(o=>o!==void 0).length===0||e.flowId!==void 0&&!globMatch(e.flowId,t.flowId)||e.originType!==void 0&&e.originType!==t.origin.type||e.origin!==void 0&&!(t.origin.nodeId!==void 0&&globMatch(e.origin,t.origin.nodeId))||e.route!==void 0&&!v(e.route,t.segments)||e.project!==void 0&&!t.segments.some(o=>o.projects.some(r=>globMatch(e.project,r))))}c(m,"m"),d(m,"b"),s(m,"ruleMatches");const b=s(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),l=s(e=>typeof e=="string"&&e!==""?e:void 0,"str"),y=s(e=>b(e.raw)?l(e.raw.kind)??"":"","kindOf"),O=s((e,t)=>{const o=Number(e.timestamp)||0,r=Number(t.timestamp)||0;return o<r||o===r&&e.id<t.id},"earlier");function h(e){let t,o;for(const a of e)y(a)==="flow-origin"&&(!t||O(a,t))&&(t=a),l(a.context?.originType)&&(!o||O(a,o))&&(o=a);const r=t??o;if(!r)return{};const n=b(r.raw)?r.raw:{},i=l(r.context?.originType)??(t?l(r.title):void 0),u=l(n.originNodeId)??l(r.context?.originNodeId);return{...i?{type:i}:{},...u?{nodeId:u}:{}}}c(h,"$"),d(h,"O"),s(h,"originOf");const B=/^(verify|e2e|test|smoke|load)[-_:]/i,A=s((e,t)=>B.test(e)||t!==void 0&&/^(ui:)?(tools|scripts?|e2e)\//.test(t),"isTestFlow"),q={"page-load":"page-load","user-click":"user-action","form-submit":"user-action","input-change":"user-action","double-click":"user-action","context-menu":"user-action","key-press":"user-action","route-load":"navigation","route-change":"navigation",navigation:"navigation","ai-turn":"ai",request:"api",timer:"background",cron:"background",interval:"background",queue:"background",job:"background","websocket-message":"background","hmr-update":"system"},C=new Set(["page-load","user-action","navigation"]),E=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;export function templatePath(e){return e.replace(/[?#].*$/,"").split("/").map(t=>E.test(t)||/^[0-9a-f]{16,}$/i.test(t)||/^\d{2,}$/.test(t)?":id":t).join("/")}c(templatePath,"templatePath"),d(templatePath,"templatePath"),s(templatePath,"templatePath");function w(e){const t=/^ui:(?:.*\/)?([^/:]+?)(?:\.[a-z]+)?:\d+:([A-Za-z]+)$/.exec(e);return t?`${t[1]} \xB7 ${t[2]}`:e}c(w,"I"),d(w,"q"),s(w,"componentOf");export function scriptFamily(e){let t=e.replace(/[-_:][0-9a-f]{6,}(?:-[0-9a-f]+)*$/i,"");return t=t.replace(/[-_:](?=[a-z0-9]*\d)[a-z0-9]{6,}$/i,""),t=t.replace(/[-_:]\d+$/,""),t||e}c(scriptFamily,"scriptFamily"),d(scriptFamily,"scriptFamily"),s(scriptFamily,"scriptFamily");function k(e,t,o,r){const n=t.nodeId,i=n?/^(page|route|ambient):(.*)$/.exec(n):null;if(i)return`${i[1]}:${templatePath(i[2])}`;if(t.type&&q[t.type]==="user-action"&&n)return w(n);if(e==="test")return scriptFamily(o.flowId);const u=o.segments.find(p=>p.kind==="request"&&p.route);if(u?.route)return`${u.method??"GET"} ${templatePath(u.route)}`;const a=r.find(p=>y(p)==="ai-call");return a&&b(a.raw)?`ai \xB7 ${l(a.raw.model)??l(a.raw.provider)??"call"}`:n?templatePath(n):void 0}c(k,"j"),d(k,"R"),s(k,"subjectOf");const R=10,_=1e3,N=3,P=500,G=1e3;function $(e,t){const o=new Set,r=t.segments.filter(i=>i.kind==="request");t.segments.some(i=>i.counts.errors>0)&&o.add("has-error"),r.some(i=>i.durationMs>=_)&&o.add("slow"),r.length>=R&&o.add("fan-out"),new Set(t.segments.flatMap(i=>i.projects)).size>=3&&o.add("multi-service"),e.some(i=>y(i)==="queue-enqueued")&&o.add("queue"),e.some(i=>y(i)==="ai-call"||i.source==="ai")&&o.add("ai"),t.stats.bookkeeping>=P&&t.stats.bookkeeping*2>=t.stats.events&&o.add("storm"),t.stats.events>=G&&o.add("large");const n=new Map;for(const i of r)(!i.part||i.part.index===1)&&n.set(i.label,(n.get(i.label)??0)+1);return[...n.values()].some(i=>i>=N)&&o.add("repeated-requests"),[...o].sort()}c($,"q"),d($,"G"),s($,"tagsOf");export function classifyFlow(e,t,o=[]){const r=h(e),n={flowId:t.flowId,origin:r,segments:t.segments},i=$(e,t),u=s((g,M,x)=>{const j=k(g,r,t,e);return{category:g,decidedBy:M,...x!==void 0?{ruleIndex:x}:{},tags:i,origin:r,...j?{subject:j}:{}}},"done"),a=o.findIndex(g=>g.category&&m(g,n));if(a!==-1)return u(o[a].category,"rule",a);if(A(t.flowId,r.nodeId))return u("test","test");const p=r.type?q[r.type]:void 0;if(p)return u(p,"origin");if(i.includes("ai"))return u("ai","shape");const I=t.segments.filter(g=>g.kind==="request");return I.length>0?u(I.every(g=>g.requestId?.startsWith("job:"))?"background":"api","shape"):t.segments.length>0&&t.segments.every(g=>g.kind==="ambient")?u("system","shape"):u("other","shape")}c(classifyFlow,"classifyFlow"),d(classifyFlow,"classifyFlow"),s(classifyFlow,"classifyFlow");export function categoryOfSegment(e,t,o=[]){const r=o.find(n=>n.category&&(n.route!==void 0||n.project!==void 0)&&n.flowId===void 0&&n.origin===void 0&&n.originType===void 0&&m(n,{flowId:e.flowId,origin:t.origin,segments:[e]}));return r?r.category:e.kind==="request"?e.requestId?.startsWith("job:")?"background":"api":e.kind==="ambient"?"system":e.kind==="origin"&&C.has(t.category)?t.category:"ui"}c(categoryOfSegment,"categoryOfSegment"),d(categoryOfSegment,"categoryOfSegment"),s(categoryOfSegment,"categoryOfSegment");export function groupFlows(e){return groupByCategory(e).map(t=>{const o=new Map;for(const n of t.items){const i=o.get(n.subject);i?i.push(n):o.set(n.subject,[n])}const r=[...o.entries()].sort((n,i)=>(n[0]===void 0?1:0)-(i[0]===void 0?1:0)||i[1].length-n[1].length||String(n[0]).localeCompare(String(i[0]))).map(([n,i])=>({subject:n,count:i.length,items:i}));return{...t,subjects:r}})}c(groupFlows,"groupFlows"),d(groupFlows,"groupFlows"),s(groupFlows,"groupFlows");export function groupByCategory(e){const t=new Map;for(const r of e){const n=t.get(r.category);n?n.push(r):t.set(r.category,[r])}const o=s(r=>{const n=CATEGORY_ORDER.indexOf(r);return n===-1?CATEGORY_ORDER.length:n},"rank");return[...t.entries()].sort((r,n)=>o(r[0])-o(n[0])||(r[0]<n[0]?-1:r[0]>n[0]?1:0)).map(([r,n])=>({category:r,count:n.length,items:n}))}c(groupByCategory,"groupByCategory"),d(groupByCategory,"groupByCategory"),s(groupByCategory,"groupByCategory");
|
package/lib/flow-segments.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Y=Object.defineProperty;var b=(e,t)=>Y(e,"name",{value:t,configurable:!0});var Z=Object.defineProperty,m=b((e,t)=>Z(e,"name",{value:t,configurable:!0}),"h");export const DEFAULT_SEGMENT_OPTIONS={phaseGapMs:1500,burstGapMs:250,attachWindowMs:400,maxSegmentEvents:400,occurrenceSlackMs:10},FLOW_BOOKKEEPING_KINDS=new Set(["subscription-added","subscription-removed","hook-run","store-created","singleton-instance","visual-frame"]),SQL_ACCOUNT_KIND="db-request-account";const ee=new Set(["react","valtio","client-runtime","chrome","visual"]),S=m(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),v=m(e=>typeof e=="string"&&e!==""?e:void 0,"str"),M=m(e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,"num"),W=new WeakMap;function F(e){let t=W.get(e);return t||(t=G(e),W.set(e,t)),t}b(F,"U"),m(F,"itemOf");function G(e){const t=S(e.raw)?e.raw:{},s=S(t.request)?t.request:{},o=S(t.span)?t.span:{},i=e.context??{},n=v(t.kind)??"",p=n===SQL_ACCOUNT_KIND,g=(p?M(t.lastEndedAt):void 0)??M(e.timestamp)??0,q=M(s.startedAt)??M(o.startTime)??M(t.startedAt)??(p?M(t.firstStartedAt):void 0),I=M(s.endedAt)??M(o.endTime)??(q!==void 0&&M(t.durationMs)!==void 0?q+t.durationMs:void 0),w=Math.min(g,q??g),$=Math.max(g,I??g),a=S(t.render)?t.render:{},u=S(t.update)?t.update:{},j=n==="render"?v(a.componentName):n==="state-update"?v(u.path)?.split(".").slice(0,2).join("."):void 0,d=v(t.queue),c=v(t.jobId),f=String(e.source),r=v(t.project)??v(i.projectName),l=n==="fetch-start"||n==="fetch-done"||n==="gateway-request";return{event:e,id:e.id,ts:g,from:w,to:$,kind:n,source:f,requestId:v(i.requestId),parentRequestId:v(i.parentRequestId),queueKey:d&&c?`${d}#${c}`:void 0,browser:ee.has(f)||f==="memory"&&r===void 0,bookkeeping:FLOW_BOOKKEEPING_KINDS.has(n),project:r,subject:j,route:l?T(v(t.url)):n==="server-request"?v(s.route):void 0,method:l?v(t.method):n==="server-request"?v(s.method):void 0}}b(G,"L"),m(G,"readItem");function T(e){if(!e)return;const t=e.search(/[?#]/),s=t===-1?e:e.slice(0,t),o=/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$/i.exec(s);return o?o[1]??"/":s}b(T,"B"),m(T,"pathOnly");const te=m(e=>e.split(".")[0],"rootOf"),_=m((e,t)=>e.reduce((s,o)=>Math.min(s,t(o)),1/0),"minOf"),B=m((e,t)=>e.reduce((s,o)=>Math.max(s,t(o)),-1/0),"maxOf"),O=m((e,t)=>e.ts-t.ts||(e.id<t.id?-1:e.id>t.id?1:0),"compare"),K=m(e=>e.requestId&&!e.requestId.startsWith("job:")?te(e.requestId):void 0,"directFamilyOf");function U(e){if(e.requestId?.startsWith("job:"))return e.requestId.slice(4);if(e.queueKey&&e.kind!=="queue-enqueued"&&!e.requestId)return e.queueKey}b(U,"D"),m(U,"jobKeyOf");function D(e,t){const s=e.filter(n=>!n.parentRequestId&&(n.kind==="server-request"||n.kind==="gateway-request"||n.kind==="fetch-start"||n.kind==="fetch-done")).sort((n,p)=>n.from-p.from||O(n,p));if(s.length<2)return[e];const o=[];for(const n of s){const p=o[o.length-1];p&&n.from<=p.to+t?p.to=Math.max(p.to,n.to):o.push({from:n.from,to:n.to})}if(o.length<2)return[e];const i=o.map(()=>[]);for(const n of e)i[t>=0?z(o,n.ts,t):R(o,n.ts,t)].push(n);return i.filter(n=>n.length>0)}b(D,"z"),m(D,"occurrencesOf");function R(e,t,s){const o=e.findIndex(n=>t>=n.from-s&&t<=n.to+s);if(o!==-1)return o;let i=0;for(let n=0;n<e.length;n+=1)e[n].from<=t&&(i=n);return i}b(R,"P"),m(R,"spanScan");function z(e,t,s){let o=0,i=e.length;for(;o<i;){const n=o+i>>1;e[n].to+s<t?o=n+1:i=n}if(o<e.length&&t>=e[o].from-s)return o;for(o=0,i=e.length;o<i;){const n=o+i>>1;e[n].from<=t?o=n+1:i=n}return Math.max(0,o-1)}b(z,"Q"),m(z,"spanAt");const C={debug:0,info:1,warning:2,error:3,fatal:4};function A(e,t){const s=[];let o=[];for(const i of e){const n=o[o.length-1];n&&i.ts-n.ts>=t&&(s.push(o),o=[]),o.push(i)}return o.length&&s.push(o),s}b(A,"R"),m(A,"runs");export function segmentFlow(e,t={}){const s={...DEFAULT_SEGMENT_OPTIONS};for(const[r,l]of Object.entries(t))typeof l=="number"&&Number.isFinite(l)&&(s[r]=l);const o=new Set,i=[];for(const r of e)o.has(r.id)||(o.add(r.id),i.push(F(r)));i.sort(O);const n=v(i[0]?.event.context?.flowId)??v(i[0]?.event.raw?.flowId)??"",p=new Map;for(const r of i)r.kind==="queue-enqueued"&&r.queueKey&&r.requestId&&!r.requestId.startsWith("job:")&&!p.has(r.queueKey)&&p.set(r.queueKey,r);const g=new Map,q=new Map,I=[];for(const r of i){const l=U(r),h=K(r);if(l!==void 0){const k=q.get(l);k?k.push(r):q.set(l,[r])}else if(h!==void 0){const k=g.get(h);k?k.push(r):g.set(h,[r])}else I.push(r)}const w=[],$=new Map;for(const[r,l]of g)D(l,s.occurrenceSlackMs).forEach((h,k)=>{const x={id:`${n}~r:${r}${k===0?"":`@${k+1}`}`,kind:"request",items:h,requestId:r};if(w.push(x),p.size)for(const y of h)y.kind==="queue-enqueued"&&$.set(y,x)});for(const[r,l]of q){const h=p.get(r),k=h?$.get(h):void 0;k?k.items.push(...l):w.push({id:`${n}~r:job:${r}`,kind:"request",items:l,requestId:`job:${r}`})}const a=i.filter(r=>r.kind==="fetch-done"&&K(r)!==void 0),u=new Map;for(const r of w)r.requestId&&u.set(r.requestId,[...u.get(r.requestId)??[],r]);const j=m((r,l)=>{const h=u.get(r);if(h)return h.find(k=>k.items.some(x=>x.kind==="fetch-done"&&x.ts===l))??h[h.length-1]},"owningUnit"),d=I.filter(r=>r.browser);for(const r of A(d,s.burstGapMs)){const l=r[0].ts,h=a.filter(y=>y.ts<=l&&l-y.ts<=s.attachWindowMs),k=[...new Set(h.map(y=>K(y)))];if(k.length===1){const y=j(k[0],h[h.length-1].ts);if(y){y.items.push(...r);continue}}const x=r.some(y=>y.kind==="flow-origin");w.push({id:`${n}~${x?"o":"u"}:${r[0].id}`,kind:x?"origin":"ui",items:r,...k.length>1?{after:k.sort()}:{}})}for(const r of A(I.filter(l=>!l.browser),s.phaseGapMs))w.push({id:`${n}~a:${r[0].id}`,kind:"ambient",items:r});const c=L(n,i.length,w,s),f=N(i);return f?{...c,sql:f}:c}b(segmentFlow,"segmentFlow"),m(segmentFlow,"segmentFlow");function L(e,t,s,o){for(const a of s)a.items.sort(O);const i=s.map(a=>({unit:a,from:_(a.items,u=>u.from),to:B(a.items,u=>u.to)}));i.sort((a,u)=>a.from-u.from||(a.unit.id<u.unit.id?-1:1));const n=new Map;let p=0,g=-1/0;for(const a of i)(p===0||a.from-g>=o.phaseGapMs)&&(p+=1),g=Math.max(g,a.to),n.set(a.unit,p);const q=[];for(const a of i){const u=P(a.unit.items,o.maxSegmentEvents),j=a.unit.kind==="request"?N(a.unit.items):void 0;u.forEach((d,c)=>{const f=Q(e,a.unit,d,n.get(a.unit),u.length>1?{index:c+1,total:u.length}:void 0);q.push(j&&c===0?{...f,sql:j}:f)})}const I={};for(const a of q)for(const u of a.eventIds)I[u]=a.id;const w=[];for(const a of q){let u=w[a.phase-1];u||(u={index:a.phase,start:a.start,end:a.end,segmentIds:[]},w[a.phase-1]=u),u.start=Math.min(u.start,a.start),u.end=Math.max(u.end,a.end),u.segmentIds.push(a.id)}const $=q.reduce((a,u)=>a+u.counts.signal,0);return{flowId:e,segments:q,phases:w.filter(Boolean),assignment:I,stats:{events:t,signal:$,bookkeeping:t-$,segments:q.length,phases:w.filter(Boolean).length,largestSegment:q.reduce((a,u)=>Math.max(a,u.counts.total),0)}}}b(L,"V"),m(L,"assemble");function P(e,t){if(e.filter(n=>!n.bookkeeping).length<=t)return[e];const s=[];let o=[],i=0;for(const n of e)!n.bookkeeping&&i===t&&(s.push(o),o=[],i=0),o.push(n),n.bookkeeping||(i+=1);return o.length&&s.push(o),s}b(P,"X"),m(P,"chunk");function Q(e,t,s,o,i){const n={total:s.length,signal:0,bookkeeping:0,errors:0,warnings:0},p=new Set;let g="debug";for(const u of s){u.bookkeeping?n.bookkeeping+=1:n.signal+=1;const j=String(u.event.severity);j==="error"||j==="fatal"?n.errors+=1:j==="warning"&&(n.warnings+=1),(C[j]??1)>(C[g]??0)&&(g=j),u.project&&p.add(u.project)}const q=t.kind==="ui"||t.kind==="origin"?J(s):[],I=_(s,u=>u.from),w=B(s,u=>u.to),$=H(t.items),a=t.id;return{id:i&&i.index>1?`${a}#${i.index}`:a,flowId:e,kind:t.kind,label:V(t,s,$,i,q),phase:o,start:I,end:w,durationMs:w-I,eventIds:s.map(u=>u.id),counts:n,projects:[...p].sort(),...$.route?{route:$.route}:{},...$.method?{method:$.method}:{},...t.requestId?{requestId:t.requestId}:{},...t.after?{after:t.after}:{},...q.length?{hot:q}:{},...i?{part:i}:{},worstSeverity:g}}b(Q,"Y"),m(Q,"toSegment");function H(e){const t=e.find(s=>s.kind==="fetch-start"&&s.route)??e.find(s=>s.kind==="server-request"&&!s.parentRequestId&&s.route)??e.find(s=>s.kind==="gateway-request"&&s.route)??e.find(s=>s.kind==="fetch-done"&&s.route);return{...t?.route?{route:t.route}:{},...t?.method?{method:t.method.toUpperCase()}:{}}}b(H,"H"),m(H,"routeOf");function J(e){const t=new Map;for(const s of e)s.subject&&!s.bookkeeping&&t.set(s.subject,(t.get(s.subject)??0)+1);return[...t.entries()].sort((s,o)=>o[1]-s[1]||(s[0]<o[0]?-1:1)).slice(0,3).map(([s,o])=>o>1?`${s} \xD7${o}`:s)}b(J,"J"),m(J,"hotOf");function V(e,t,s,o,i){const n=o?` (part ${o.index}/${o.total})`:"";if(e.kind==="request"){if(s.route)return`${s.method?`${s.method} `:""}${s.route}${n}`;const p=t.find(g=>g.queueKey);return p?`job ${p.queueKey}${n}`:`request ${e.requestId??""}${n}`}return e.kind==="origin"?`${t.find(p=>p.kind==="flow-origin")?.event.title||"start"}${i.length?` \xB7 ${i.join(", ")}`:""}${n}`:e.kind==="ui"?`UI update${i.length?` \xB7 ${i.join(", ")}`:""}${n}`:`background${n}`}b(V,"Z"),m(V,"labelOf");const X=50;export function sqlAccountingOf(e){return E(e,!1)}b(sqlAccountingOf,"sqlAccountingOf"),m(sqlAccountingOf,"sqlAccountingOf");function N(e){return E(e.map(t=>t.event),!0)}b(N,"T"),m(N,"accountSqlOfItems");function E(e,t){const s=new Map,o=new Map,i=t?void 0:new Set;for(const d of e){if(i){if(i.has(d.id))continue;i.add(d.id)}const c=S(d.raw)?d.raw:{},f=v(c.kind),r=v(d.context?.requestId);if(!r)continue;const l=v(c.project)??v(d.context?.projectName);if(f==="db-query"&&d.source==="db"){const h=o.get(r)??{count:0,workMs:0,...l?{project:l}:{}};h.count+=1,h.workMs+=M(c.durationMs)??0,o.set(r,h)}else if(f===SQL_ACCOUNT_KIND){const h=v(c.accountId)??d.id,k=M(c.seq)??0,x=s.get(h);if(x&&x.seq>=k)continue;s.set(h,{requestId:r,...l?{project:l}:{},seq:k,basis:c.basis==="end"?"end":"settled",statements:M(c.statements)??0,failed:M(c.failed)??0,workMs:M(c.workMs)??0,recorded:M(c.recorded)??0,suppressed:M(c.suppressed)??0,unwritten:M(c.unwritten)??0})}}const n=new Map;for(const d of s.values()){const c=n.get(d.requestId);if(!c){n.set(d.requestId,{...d});continue}d.basis==="settled"&&(c.basis="settled"),c.statements+=d.statements,c.failed+=d.failed,c.workMs+=d.workMs,c.recorded+=d.recorded,c.suppressed+=d.suppressed,c.unwritten+=d.unwritten}const p=[...new Set([...o.keys(),...n.keys()])].sort();if(p.length===0)return;const g={statements:0,failed:0,workMs:0,recorded:0,suppressed:0,unwritten:0},q={statements:0,workMs:0},I=[];for(const d of p){const c=o.get(d),f=n.get(d),r=c?.count??0;q.statements+=r,q.workMs+=c?.workMs??0;const l=!f||r>f.statements?"unverified":r===f.statements?"complete":"incomplete";f&&l!=="unverified"&&(g.statements+=f.statements,g.failed+=f.failed,g.workMs+=f.workMs,g.recorded+=f.recorded,g.suppressed+=f.suppressed,g.unwritten+=f.unwritten);const h=c?.project??f?.project;I.push({requestId:d,...h?{project:h}:{},status:l,observed:r,observedWorkMs:c?.workMs??0,...f?{basis:f.basis,statements:f.statements,failed:f.failed,workMs:f.workMs,recorded:f.recorded,suppressed:f.suppressed,unwritten:f.unwritten}:{}})}const w=m(d=>I.filter(c=>c.status===d).length,"tally"),$=w("unverified"),a=w("incomplete"),u=m(d=>(d.statements??0)-d.observed,"missing"),j=I.filter(d=>d.status!=="complete").sort((d,c)=>(d.status==="incomplete"?0:1)-(c.status==="incomplete"?0:1)||u(c)-u(d)||(d.requestId<c.requestId?-1:d.requestId>c.requestId?1:0));return{status:$>0?"unverified":a>0?"incomplete":"complete",requests:I.length,complete:w("complete"),incomplete:a,unverified:$,settled:I.filter(d=>d.status!=="unverified"&&d.basis==="settled").length,observed:q,accounted:g,gaps:j.slice(0,X),gapsTruncated:j.length>X}}b(E,"W"),m(E,"accountSql");
|
|
1
|
+
"use strict";var Z=Object.defineProperty;var b=(e,t)=>Z(e,"name",{value:t,configurable:!0});var ee=Object.defineProperty,I=b((e,t)=>ee(e,"name",{value:t,configurable:!0}),"b"),te=Object.defineProperty,m=I((e,t)=>te(e,"name",{value:t,configurable:!0}),"h");export const DEFAULT_SEGMENT_OPTIONS={phaseGapMs:1500,burstGapMs:250,attachWindowMs:400,maxSegmentEvents:400,occurrenceSlackMs:10},FLOW_BOOKKEEPING_KINDS=new Set(["subscription-added","subscription-removed","hook-run","store-created","singleton-instance","visual-frame"]),SQL_ACCOUNT_KIND="db-request-account";const ne=new Set(["react","valtio","client-runtime","chrome","visual"]),S=m(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),v=m(e=>typeof e=="string"&&e!==""?e:void 0,"str"),$=m(e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,"num"),H=new WeakMap;function E(e){let t=H.get(e);return t||(t=W(e),H.set(e,t)),t}b(E,"F"),I(E,"U"),m(E,"itemOf");function W(e){const t=S(e.raw)?e.raw:{},s=S(t.request)?t.request:{},o=S(t.span)?t.span:{},i=e.context??{},n=v(t.kind)??"",l=n===SQL_ACCOUNT_KIND,g=(l?$(t.lastEndedAt):void 0)??$(e.timestamp)??0,q=$(s.startedAt)??$(o.startTime)??$(t.startedAt)??(l?$(t.firstStartedAt):void 0),M=$(s.endedAt)??$(o.endTime)??(q!==void 0&&$(t.durationMs)!==void 0?q+t.durationMs:void 0),w=Math.min(g,q??g),j=Math.max(g,M??g),a=S(t.render)?t.render:{},u=S(t.update)?t.update:{},y=n==="render"?v(a.componentName):n==="state-update"?v(u.path)?.split(".").slice(0,2).join("."):void 0,d=v(t.queue),c=v(t.jobId),f=String(e.source),r=v(t.project)??v(i.projectName),p=n==="fetch-start"||n==="fetch-done"||n==="gateway-request";return{event:e,id:e.id,ts:g,from:w,to:j,kind:n,source:f,requestId:v(i.requestId),parentRequestId:v(i.parentRequestId),queueKey:d&&c?`${d}#${c}`:void 0,browser:ne.has(f)||f==="memory"&&r===void 0,bookkeeping:FLOW_BOOKKEEPING_KINDS.has(n),project:r,subject:y,route:p?F(v(t.url)):n==="server-request"?v(s.route):void 0,method:p?v(t.method):n==="server-request"?v(s.method):void 0}}b(W,"G"),I(W,"L"),m(W,"readItem");function F(e){if(!e)return;const t=e.search(/[?#]/),s=t===-1?e:e.slice(0,t),o=/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$/i.exec(s);return o?o[1]??"/":s}b(F,"T"),I(F,"B"),m(F,"pathOnly");const se=m(e=>e.split(".")[0],"rootOf"),J=m((e,t)=>e.reduce((s,o)=>Math.min(s,t(o)),1/0),"minOf"),V=m((e,t)=>e.reduce((s,o)=>Math.max(s,t(o)),-1/0),"maxOf"),T=m((e,t)=>e.ts-t.ts||(e.id<t.id?-1:e.id>t.id?1:0),"compare"),G=m(e=>e.requestId&&!e.requestId.startsWith("job:")?se(e.requestId):void 0,"directFamilyOf");function B(e){if(e.requestId?.startsWith("job:"))return e.requestId.slice(4);if(e.queueKey&&e.kind!=="queue-enqueued"&&!e.requestId)return e.queueKey}b(B,"U"),I(B,"D"),m(B,"jobKeyOf");function U(e,t){const s=e.filter(n=>!n.parentRequestId&&(n.kind==="server-request"||n.kind==="gateway-request"||n.kind==="fetch-start"||n.kind==="fetch-done")).sort((n,l)=>n.from-l.from||T(n,l));if(s.length<2)return[e];const o=[];for(const n of s){const l=o[o.length-1];l&&n.from<=l.to+t?l.to=Math.max(l.to,n.to):o.push({from:n.from,to:n.to})}if(o.length<2)return[e];const i=o.map(()=>[]);for(const n of e)i[t>=0?D(o,n.ts,t):_(o,n.ts,t)].push(n);return i.filter(n=>n.length>0)}b(U,"D"),I(U,"z"),m(U,"occurrencesOf");function _(e,t,s){const o=e.findIndex(n=>t>=n.from-s&&t<=n.to+s);if(o!==-1)return o;let i=0;for(let n=0;n<e.length;n+=1)e[n].from<=t&&(i=n);return i}b(_,"R"),I(_,"P"),m(_,"spanScan");function D(e,t,s){let o=0,i=e.length;for(;o<i;){const n=o+i>>1;e[n].to+s<t?o=n+1:i=n}if(o<e.length&&t>=e[o].from-s)return o;for(o=0,i=e.length;o<i;){const n=o+i>>1;e[n].from<=t?o=n+1:i=n}return Math.max(0,o-1)}b(D,"z"),I(D,"Q"),m(D,"spanAt");const X={debug:0,info:1,warning:2,error:3,fatal:4};function A(e,t){const s=[];let o=[];for(const i of e){const n=o[o.length-1];n&&i.ts-n.ts>=t&&(s.push(o),o=[]),o.push(i)}return o.length&&s.push(o),s}b(A,"A"),I(A,"R"),m(A,"runs");export function segmentFlow(e,t={}){const s={...DEFAULT_SEGMENT_OPTIONS};for(const[r,p]of Object.entries(t))typeof p=="number"&&Number.isFinite(p)&&(s[r]=p);const o=new Set,i=[];for(const r of e)o.has(r.id)||(o.add(r.id),i.push(E(r)));i.sort(T);const n=v(i[0]?.event.context?.flowId)??v(i[0]?.event.raw?.flowId)??"",l=new Map;for(const r of i)r.kind==="queue-enqueued"&&r.queueKey&&r.requestId&&!r.requestId.startsWith("job:")&&!l.has(r.queueKey)&&l.set(r.queueKey,r);const g=new Map,q=new Map,M=[];for(const r of i){const p=B(r),h=G(r);if(p!==void 0){const k=q.get(p);k?k.push(r):q.set(p,[r])}else if(h!==void 0){const k=g.get(h);k?k.push(r):g.set(h,[r])}else M.push(r)}const w=[],j=new Map;for(const[r,p]of g)U(p,s.occurrenceSlackMs).forEach((h,k)=>{const O={id:`${n}~r:${r}${k===0?"":`@${k+1}`}`,kind:"request",items:h,requestId:r};if(w.push(O),l.size)for(const x of h)x.kind==="queue-enqueued"&&j.set(x,O)});for(const[r,p]of q){const h=l.get(r),k=h?j.get(h):void 0;k?k.items.push(...p):w.push({id:`${n}~r:job:${r}`,kind:"request",items:p,requestId:`job:${r}`})}const a=i.filter(r=>r.kind==="fetch-done"&&G(r)!==void 0),u=new Map;for(const r of w)r.requestId&&u.set(r.requestId,[...u.get(r.requestId)??[],r]);const y=m((r,p)=>{const h=u.get(r);if(h)return h.find(k=>k.items.some(O=>O.kind==="fetch-done"&&O.ts===p))??h[h.length-1]},"owningUnit"),d=M.filter(r=>r.browser);for(const r of A(d,s.burstGapMs)){const p=r[0].ts,h=a.filter(x=>x.ts<=p&&p-x.ts<=s.attachWindowMs),k=[...new Set(h.map(x=>G(x)))];if(k.length===1){const x=y(k[0],h[h.length-1].ts);if(x){x.items.push(...r);continue}}const O=r.some(x=>x.kind==="flow-origin");w.push({id:`${n}~${O?"o":"u"}:${r[0].id}`,kind:O?"origin":"ui",items:r,...k.length>1?{after:k.sort()}:{}})}for(const r of A(M.filter(p=>!p.browser),s.phaseGapMs))w.push({id:`${n}~a:${r[0].id}`,kind:"ambient",items:r});const c=P(n,i.length,w,s),f=K(i);return f?{...c,sql:f}:c}b(segmentFlow,"segmentFlow"),I(segmentFlow,"segmentFlow"),m(segmentFlow,"segmentFlow");function P(e,t,s,o){for(const a of s)a.items.sort(T);const i=s.map(a=>({unit:a,from:J(a.items,u=>u.from),to:V(a.items,u=>u.to)}));i.sort((a,u)=>a.from-u.from||(a.unit.id<u.unit.id?-1:1));const n=new Map;let l=0,g=-1/0;for(const a of i)(l===0||a.from-g>=o.phaseGapMs)&&(l+=1),g=Math.max(g,a.to),n.set(a.unit,l);const q=[];for(const a of i){const u=R(a.unit.items,o.maxSegmentEvents),y=a.unit.kind==="request"?K(a.unit.items):void 0;u.forEach((d,c)=>{const f=z(e,a.unit,d,n.get(a.unit),u.length>1?{index:c+1,total:u.length}:void 0);q.push(y&&c===0?{...f,sql:y}:f)})}const M={};for(const a of q)for(const u of a.eventIds)M[u]=a.id;const w=[];for(const a of q){let u=w[a.phase-1];u||(u={index:a.phase,start:a.start,end:a.end,segmentIds:[]},w[a.phase-1]=u),u.start=Math.min(u.start,a.start),u.end=Math.max(u.end,a.end),u.segmentIds.push(a.id)}const j=q.reduce((a,u)=>a+u.counts.signal,0);return{flowId:e,segments:q,phases:w.filter(Boolean),assignment:M,stats:{events:t,signal:j,bookkeeping:t-j,segments:q.length,phases:w.filter(Boolean).length,largestSegment:q.reduce((a,u)=>Math.max(a,u.counts.total),0)}}}b(P,"L"),I(P,"V"),m(P,"assemble");function R(e,t){if(e.filter(n=>!n.bookkeeping).length<=t)return[e];const s=[];let o=[],i=0;for(const n of e)!n.bookkeeping&&i===t&&(s.push(o),o=[],i=0),o.push(n),n.bookkeeping||(i+=1);return o.length&&s.push(o),s}b(R,"P"),I(R,"X"),m(R,"chunk");function z(e,t,s,o,i){const n={total:s.length,signal:0,bookkeeping:0,errors:0,warnings:0},l=new Set;let g="debug";for(const u of s){u.bookkeeping?n.bookkeeping+=1:n.signal+=1;const y=String(u.event.severity);y==="error"||y==="fatal"?n.errors+=1:y==="warning"&&(n.warnings+=1),(X[y]??1)>(X[g]??0)&&(g=y),u.project&&l.add(u.project)}const q=t.kind==="ui"||t.kind==="origin"?C(s):[],M=J(s,u=>u.from),w=V(s,u=>u.to),j=L(t.items),a=t.id;return{id:i&&i.index>1?`${a}#${i.index}`:a,flowId:e,kind:t.kind,label:Q(t,s,j,i,q),phase:o,start:M,end:w,durationMs:w-M,eventIds:s.map(u=>u.id),counts:n,projects:[...l].sort(),...j.route?{route:j.route}:{},...j.method?{method:j.method}:{},...t.requestId?{requestId:t.requestId}:{},...t.after?{after:t.after}:{},...q.length?{hot:q}:{},...i?{part:i}:{},worstSeverity:g}}b(z,"Q"),I(z,"Y"),m(z,"toSegment");function L(e){const t=e.find(s=>s.kind==="fetch-start"&&s.route)??e.find(s=>s.kind==="server-request"&&!s.parentRequestId&&s.route)??e.find(s=>s.kind==="gateway-request"&&s.route)??e.find(s=>s.kind==="fetch-done"&&s.route);return{...t?.route?{route:t.route}:{},...t?.method?{method:t.method.toUpperCase()}:{}}}b(L,"H"),I(L,"H"),m(L,"routeOf");function C(e){const t=new Map;for(const s of e)s.subject&&!s.bookkeeping&&t.set(s.subject,(t.get(s.subject)??0)+1);return[...t.entries()].sort((s,o)=>o[1]-s[1]||(s[0]<o[0]?-1:1)).slice(0,3).map(([s,o])=>o>1?`${s} \xD7${o}`:s)}b(C,"J"),I(C,"J"),m(C,"hotOf");function Q(e,t,s,o,i){const n=o?` (part ${o.index}/${o.total})`:"";if(e.kind==="request"){if(s.route)return`${s.method?`${s.method} `:""}${s.route}${n}`;const l=t.find(g=>g.queueKey);return l?`job ${l.queueKey}${n}`:`request ${e.requestId??""}${n}`}return e.kind==="origin"?`${t.find(l=>l.kind==="flow-origin")?.event.title||"start"}${i.length?` \xB7 ${i.join(", ")}`:""}${n}`:e.kind==="ui"?`UI update${i.length?` \xB7 ${i.join(", ")}`:""}${n}`:`background${n}`}b(Q,"V"),I(Q,"Z"),m(Q,"labelOf");const Y=50;export function sqlAccountingOf(e){return N(e,!1)}b(sqlAccountingOf,"sqlAccountingOf"),I(sqlAccountingOf,"sqlAccountingOf"),m(sqlAccountingOf,"sqlAccountingOf");function K(e){return N(e.map(t=>t.event),!0)}b(K,"N"),I(K,"T"),m(K,"accountSqlOfItems");function N(e,t){const s=new Map,o=new Map,i=t?void 0:new Set;for(const d of e){if(i){if(i.has(d.id))continue;i.add(d.id)}const c=S(d.raw)?d.raw:{},f=v(c.kind),r=v(d.context?.requestId);if(!r)continue;const p=v(c.project)??v(d.context?.projectName);if(f==="db-query"&&d.source==="db"){const h=o.get(r)??{count:0,workMs:0,...p?{project:p}:{}};h.count+=1,h.workMs+=$(c.durationMs)??0,o.set(r,h)}else if(f===SQL_ACCOUNT_KIND){const h=v(c.accountId)??d.id,k=$(c.seq)??0,O=s.get(h);if(O&&O.seq>=k)continue;s.set(h,{requestId:r,...p?{project:p}:{},seq:k,basis:c.basis==="end"?"end":"settled",statements:$(c.statements)??0,failed:$(c.failed)??0,workMs:$(c.workMs)??0,recorded:$(c.recorded)??0,suppressed:$(c.suppressed)??0,unwritten:$(c.unwritten)??0})}}const n=new Map;for(const d of s.values()){const c=n.get(d.requestId);if(!c){n.set(d.requestId,{...d});continue}d.basis==="settled"&&(c.basis="settled"),c.statements+=d.statements,c.failed+=d.failed,c.workMs+=d.workMs,c.recorded+=d.recorded,c.suppressed+=d.suppressed,c.unwritten+=d.unwritten}const l=[...new Set([...o.keys(),...n.keys()])].sort();if(l.length===0)return;const g={statements:0,failed:0,workMs:0,recorded:0,suppressed:0,unwritten:0},q={statements:0,workMs:0},M=[];for(const d of l){const c=o.get(d),f=n.get(d),r=c?.count??0;q.statements+=r,q.workMs+=c?.workMs??0;const p=!f||r>f.statements?"unverified":r===f.statements?"complete":"incomplete";f&&p!=="unverified"&&(g.statements+=f.statements,g.failed+=f.failed,g.workMs+=f.workMs,g.recorded+=f.recorded,g.suppressed+=f.suppressed,g.unwritten+=f.unwritten);const h=c?.project??f?.project;M.push({requestId:d,...h?{project:h}:{},status:p,observed:r,observedWorkMs:c?.workMs??0,...f?{basis:f.basis,statements:f.statements,failed:f.failed,workMs:f.workMs,recorded:f.recorded,suppressed:f.suppressed,unwritten:f.unwritten}:{}})}const w=m(d=>M.filter(c=>c.status===d).length,"tally"),j=w("unverified"),a=w("incomplete"),u=m(d=>(d.statements??0)-d.observed,"missing"),y=M.filter(d=>d.status!=="complete").sort((d,c)=>(d.status==="incomplete"?0:1)-(c.status==="incomplete"?0:1)||u(c)-u(d)||(d.requestId<c.requestId?-1:d.requestId>c.requestId?1:0));return{status:j>0?"unverified":a>0?"incomplete":"complete",requests:M.length,complete:w("complete"),incomplete:a,unverified:j,settled:M.filter(d=>d.status!=="unverified"&&d.basis==="settled").length,observed:q,accounted:g,gaps:y.slice(0,Y),gapsTruncated:y.length>Y}}b(N,"E"),I(N,"W"),m(N,"accountSql");
|
package/lib/flow-shape.d.ts
CHANGED
|
@@ -78,6 +78,7 @@ export declare function trimFlowEvent(event: BaseEvent, opts?: FlowShapeOptions)
|
|
|
78
78
|
area: FlowArea;
|
|
79
79
|
jobId?: string | undefined;
|
|
80
80
|
queue?: string | undefined;
|
|
81
|
+
valuesId?: string | undefined;
|
|
81
82
|
method?: string;
|
|
82
83
|
/** The route template (`/companies/:id`): the framework's own when it says, else the path with its ids folded. */
|
|
83
84
|
route?: string;
|
|
@@ -149,6 +150,7 @@ export declare function buildFlowDetail(rawEvents: BaseEvent[], opts?: FlowShape
|
|
|
149
150
|
area: FlowArea;
|
|
150
151
|
jobId?: string | undefined;
|
|
151
152
|
queue?: string | undefined;
|
|
153
|
+
valuesId?: string | undefined;
|
|
152
154
|
method?: string;
|
|
153
155
|
/** The route template (`/companies/:id`): the framework's own when it says, else the path with its ids folded. */
|
|
154
156
|
route?: string;
|
package/lib/flow-shape.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var wt=Object.defineProperty;var C=(i,h)=>wt(i,"name",{value:h,configurable:!0});var qt=Object.defineProperty,y=C((i,h)=>qt(i,"name",{value:h,configurable:!0}),"y");import{redactDeep as Mt,redactText as ot,redactUrlParams as It}from"./redact.js";import{templatisePath as pt}from"./route-template.js";import{SQL_ACCOUNT_KIND as xt,sqlAccountingOf as bt}from"./flow-segments.js";import{boundedClone as jt}from"@lensmcp/protocol-types";export function areaOf(i){const{source:h,category:o,title:w,kind:l}=i;return h==="ai"?"ai":l?.startsWith("memory")||l==="db-query"?"data":h==="gateway"||l==="gateway-request"?"gateway":l==="queue-process"||l==="queue-active"||l==="queue-completed"||l==="queue-failed"?"services":h==="db"||h==="redis"||h==="queue"||l==="redis-op"||l?.startsWith("queue-")?"data":h==="external"||l==="egress"?"network":h==="nestjs"||h==="nest"?/(?:Repository|Repo|Dao|Store|EntityManager|DataSource|QueryRunner|OrmClient)\./.test(w)?"data":"services":h==="valtio"?"state":o==="network"?"network":"browser"}C(areaOf,"areaOf"),y(areaOf,"areaOf");const ft=240,St=new Set(["systemPrompt","prompt","prompts","messages","completion","completions","input","output","draft","text","content","result","arguments","params"]),Bt=new Set(["tenantId","caller","userId","accountId","email","subject"]),At=8;function mt(i){const h=tt(i,0);return jt(Mt({redacted:!0,...h}),{rawByteLimit:16*1024}).value}C(mt,"jt"),y(mt,"aiProjection");function tt(i,h){if(typeof i=="string")return ht(i);if(i===null||typeof i!="object")return i;if(h>=At)return;if(Array.isArray(i))return i.slice(0,32).map(w=>tt(w,h+1));const o={};for(const[w,l]of Object.entries(i))if(!Bt.has(w)){if(St.has(w)){typeof l=="string"?o[`${w}Chars`]=l.length:Array.isArray(l)?o[`${w}Count`]=l.length:l!=null&&(o[`${w}Present`]=!0);continue}o[w]=tt(l,h+1)}return o}C(tt,"rt"),y(tt,"projectAi");function ht(i){return i.length<=ft?ot(i):`${ot(i.slice(0,ft))}\u2026`}C(ht,"vt"),y(ht,"clipText");export function httpFacts(i,h){const o=y(M=>typeof M=="string"&&M.length>0?M:void 0,"str"),w=typeof h.status=="number"?h.status:void 0,l=y(M=>It(M.split("?")[0]??M)||"/","pathOf"),D=y((M,$,b={})=>({...M?{method:M.toUpperCase()}:{},...$?{rawPath:$,route:pt($)}:{},...w!==void 0?{status:w}:{},...b}),"facts");if(i==="gateway-request"){const M=o(h.url);return D(o(h.method),M?l(M):void 0,{...o(h.host)?{host:o(h.host)}:{},...o(h.caller)?{caller:o(h.caller)}:{}})}if(i==="egress"){const M=o(h.path),$=o(h.exchangeId);return D(o(h.method)??"GET",M?l(M):void 0,{...o(h.host)?{host:o(h.host)}:{},...$?{exchangeId:$}:{}})}if(i==="fetch-start"||i==="fetch-done"||i==="fetch-error"){const M=o(h.href)??o(h.url);let $,b;if(M)try{const m=new URL(M,"http://relative.invalid");$=l(m.pathname),m.hostname!=="relative.invalid"&&(b=m.hostname)}catch{}return D(o(h.method)??"GET",$,b?{host:b}:{})}if(i==="ai-call")return{...w!==void 0?{status:w}:{},...h.stream===!0?{streamed:!0}:{}};const f=h.request;if(f&&typeof f=="object"){const M=f,$=o(M.route),b=o(M.method);if(!$&&!b)return{};const m=typeof M.status=="number"?M.status:void 0,T=$?l($):void 0;return{...b?{method:b.toUpperCase()}:{},...T?{rawPath:T,route:T.includes(":")?T:pt(T)}:{},...m!==void 0?{status:m}:{}}}return{}}C(httpFacts,"httpFacts"),y(httpFacts,"httpFacts");export function trimFlowEvent(i,h={}){const o=i.raw??{},w=o.render??{},l=o.span??{},D=o.request??{},f=y(u=>typeof u=="number"?u:void 0,"num"),M=o.loop??{},$=o.effect??{},b=f(o.durationMs)??f(l.durationMs)??f(D.durationMs)??f(M.durationMs)??f(w.actualDurationMs)??f($.durationMs),m=typeof o.kind=="string"?o.kind:void 0,T=m==="fetch-done"||m==="fetch-error",_=f(w.commitTime),z=m==="render"&&_!==void 0&&Math.abs(_-i.timestamp)<6e4,et=T?i.timestamp:z?_:f(o.startedAt)??f(l.startTime)??f(D.startedAt)??f(M.startedAt)??(b!==void 0?i.timestamp-b:i.timestamp);let S;if(typeof o.query=="string"){const u=Array.isArray(o.params)?` [${o.params.join(", ")}]`:"",k=typeof o.result=="string"?` \u2192 ${o.result}`:"";S=o.query+u+k}else if(typeof o.command=="string"){const u=typeof o.value=="string"?` \u2192 ${o.value}`:o.hit===!1?" \u2192 (miss)":"";S=o.command+u}else if(m==="state-update"){const u=o.update??{};let k="";try{k=JSON.stringify(u.preview)}catch{}S=`${u.storeId??""}.${u.path??""} = ${k}`}else if(m==="queue-completed"&&typeof o.returned=="string")S=`returned ${o.returned}`;else if(m==="queue-enqueued")S=`${o.job??"job"}#${o.jobId??"?"} \u2192 ${o.queue??""}${typeof o.data=="string"?" "+o.data:""}`;else if(m==="log"){const u=D.error??{},k=typeof u.stack=="string"?u.stack:typeof o.text=="string"?o.text:void 0;k&&k!==i.title&&(S=k)}let P,G,H,Q;if(m==="span"){const u=l.outcome;if(P=u==="threw"||u==="returned"?u:l.status==="error"?"threw":l.status==="ok"?"returned":void 0,P==="threw"){const R=l.error??{},O=typeof R.name=="string"?R.name:void 0,K=typeof R.message=="string"?R.message:typeof i.message=="string"?i.message:void 0;H=O,G=ot([O,K].filter(Boolean).join(": "))||void 0}const k=typeof l.args=="string"?l.args:void 0,A=typeof l.result=="string"?l.result:void 0;if(k!==void 0||A!==void 0){Q=[...k!==void 0?["args"]:[],...A!==void 0?["result"]:[]];const R=y(O=>O.length>gt?`${O.slice(0,gt)}\u2026`:O,"short");S=[k!==void 0?`args ${R(k)}`:"",A!==void 0?`returned ${R(A)}`:""].filter(Boolean).join(" \u2192 ")}}let W;if(m==="gateway-request")W=`${o.host??""}${String(o.url??"").split("?")[0]}`;else if(m==="fetch-start"||m==="fetch-done"||m==="fetch-error")try{const u=new URL(String(o.href??o.url??""));W=`${u.hostname}${u.pathname}`}catch{}let U;if(m==="gateway-request"&&Array.isArray(o.steps))U=o.steps.map(u=>{const k=[String(u.step)];return u.project&&k.push(String(u.project)),u.prefix&&k.push(String(u.prefix)),u.mode&&k.push(String(u.mode)+(u.ok===!1?" \u2717":u.ok===!0?" \u2713":"")),u.caller&&k.push("by "+String(u.caller)),u.pod&&k.push(String(u.pod)),typeof u.atMs=="number"&&k.push(`@${u.atMs}ms`),k.join(" ")}),S=U.map(u=>u.replace(/ @\d+ms$/,"")).join(" \u2192 ");else if(m==="egress")S=`${o.method??"GET"} ${o.host??""} \u2192 ${o.status??"?"}`;else if(i.source==="ai"){if(m==="ai-call"){const u=o.usage??{},k=u.promptTokens!==void 0||u.completionTokens!==void 0?` \xB7 ${f(u.promptTokens)??"?"}\u2192${f(u.completionTokens)??"?"} tok`:"",A=o.status!==void 0?` \xB7 ${String(o.status)}`:o.error?" \xB7 failed":"",R=f(o.toolCallCount)?` \xB7 ${f(o.toolCallCount)} tool call${f(o.toolCallCount)===1?"":"s"}`:"",O=f(o.durationMs)!==void 0?` \xB7 ${(f(o.durationMs)/1e3).toFixed(1)}s`:"";S=`${o.provider??""}/${o.model??"?"}${k}${A}${R}${O}${o.stream===!0?" \xB7 stream":""}`}else if(m==="ai-round"){const u=o.model??{},k=o.usage??{},A=Array.isArray(o.toolCalls)?o.toolCalls:[],R=`${f(k.promptTokens)??"?"}\u2192${f(k.completionTokens)??"?"} tok`,O=A.length?` \xB7 ${A.length} tool call${A.length===1?"":"s"}`:"",K=f(o.durationMs)!==void 0?` \xB7 ${(f(o.durationMs)/1e3).toFixed(1)}s`:"";S=`${u.provider??""}/${u.model??""} \xB7 ${R}${O}${K}`}else if(m==="ai-turn-start"){const u=Array.isArray(o.tools)?o.tools:[];S=`skill ${o.skill??""} \xB7 ${o.output??""}${u.length?" \xB7 tools: "+u.join(", "):""}`}else if(m==="ai-tool-call"){const u=o.call??{},k=o.result??{},A=f(o.durationMs)!==void 0?` \xB7 ${(f(o.durationMs)/1e3).toFixed(1)}s`:"";S=`${u.name??"tool"} ${k.error!=null?"\u2717 "+String(k.error):"\u2713"}${A}`}else if(m==="ai-turn-end"){const u=o.usage??{},k=f(o.rounds)!==void 0?` \xB7 ${f(o.rounds)} round${f(o.rounds)===1?"":"s"}`:"",A=f(o.durationMs)!==void 0?` \xB7 ${(f(o.durationMs)/1e3).toFixed(1)}s`:"";S=`${o.ok===!1?"FAILED":"ok"} \xB7 ${f(u.promptTokens)??"?"}+${f(u.completionTokens)??"?"} tok${k}${A}`}}let L;m==="db-query"&&typeof o.query=="string"?L=o.query:m==="redis-op"?L=`${o.op??""} ${String(o.key??"").replace(/\d+/g,"#")}`:m==="egress"?L=`${o.method??"GET"} ${o.host??""}`:m==="ai-call"?L=`ai ${o.provider??""} ${o.model??""} ${o.api??""}`:m==="queue-enqueued"?L=`enqueue ${o.queue??""}`:m==="span"&&typeof l.name=="string"?L=l.name:m==="memory-mutation"&&(L=i.title);const N=i.context??{},q=w.commitId??$.commitId??o.commitId,V=Array.isArray(w.why)?w.why.map(u=>typeof u?.type=="string"?u.type:void 0).filter(u=>!!u):[];return{id:i.id,t:i.timestamp,start:et,...L?{sig:L}:{},...W?{urlKey:W}:{},...httpFacts(m,o),...typeof o.queue=="string"?{queue:o.queue}:{},...o.jobId!=null?{jobId:String(o.jobId)}:{},source:i.source,category:i.category,severity:i.severity,title:P==="threw"&&typeof l.name=="string"?`${l.name} \u2014 threw${H?` ${H}`:""}${b!==void 0?` after ${b}ms`:""}`:i.title,kind:m,area:areaOf({source:i.source,category:i.category,title:i.title,kind:m}),...P?{outcome:P}:{},...G?{error:G}:{},...Q?{captured:Q}:{},...typeof l.role=="string"?{role:l.role}:{},...typeof l.spanId=="string"?{spanId:l.spanId}:{},...typeof l.parentSpanId=="string"?{parentSpanId:l.parentSpanId}:{},...m==="log"&&typeof o.level=="string"?{level:o.level}:{},...m==="log"&&typeof o.logger=="string"?{logger:o.logger}:{},...m==="log"&&typeof o.stream=="string"?{stream:o.stream}:{},...typeof N.requestId=="string"?{requestId:N.requestId}:{},...typeof N.parentRequestId=="string"?{parentRequestId:N.parentRequestId}:{},...typeof q=="string"?{commitId:q}:{},...typeof w.componentName=="string"?{component:w.componentName}:{},...typeof w.phase=="string"?{phase:w.phase}:{},...V.length?{why:V}:{},...m==="effect-run"&&typeof $.hookLogicalId=="string"?{hook:$.hookLogicalId}:{},...m==="effect-run"&&$.cleanupRan===!0?{cleanup:!0}:{},...m==="render-commit-truncated"?{renderTotal:f(o.total),renderPublished:f(o.published),...f(o.walkStoppedAt)!==void 0?{renderWalkStoppedAt:f(o.walkStoppedAt)}:{}}:{},...typeof N.projectName=="string"?{project:N.projectName}:typeof o.project=="string"?{project:o.project}:{},...b!==void 0?{durationMs:b}:{},...T&&f(o.startedAt)!==void 0?{fetchStartedAt:f(o.startedAt)}:{},...i.source==="ai"?{ai:h.includeRaw?o:mt(o)}:{},...S?{detail:S}:{},...U?{steps:U}:{}}}C(trimFlowEvent,"trimFlowEvent"),y(trimFlowEvent,"trimFlowEvent");const gt=300;export const OUTLIVED_PARENT_MIN_MS=250;const Rt=new Set(["egress","db-query","redis-op","ai-call","span","gateway-request","server-request"]),$t=1;function yt(i){return i==="flow-origin"?0:i?.endsWith("-start")?1:i==="gateway-request"?2:i==="server-request"?3:i==="span"?4:i==="render"||i==="render-commit-truncated"?6:i==="effect-run"?7:5}C(yt,"Rt"),y(yt,"kindRank");function J(i){return i.kind==="span"&&i.role==="controller"?3.5:i.kind==="queue-process"?3:yt(i.kind)}C(J,"Z"),y(J,"causalRank");export function buildFlowDetail(i,h={}){const o=bt(i),w=i.slice().filter(t=>{const r=t.raw??{},e=typeof r.kind=="string"?r.kind:"";if(e==="subscription-added"||e==="subscription-removed"||e==="hook-run"||e==="store-created"||e==="singleton-instance"||e===xt)return!1;const n=r.span;return!(typeof n?.name=="string"&&n.name.startsWith("nest.request "))}).map(t=>trimFlowEvent(t,h)),l=new Set;for(let t=w.length-1;t>=0;t--)l.has(w[t].id)?w.splice(t,1):l.add(w[t].id);const D=new Map;for(const t of w)(t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&!D.has(t.requestId)&&D.set(t.requestId,t.start);const f=y(t=>t.source!=="react"&&t.source!=="valtio"&&t.requestId&&D.has(t.requestId)?D.get(t.requestId):t.start,"anchorOf");w.sort((t,r)=>f(t)-f(r)||t.start-r.start||J(t)-J(r)||(r.durationMs??0)-(t.durationMs??0)||t.t-r.t);const M=y(t=>(t.kind==="span"||t.kind==="server-request"||t.kind==="gateway-request"||t.kind==="queue-process")&&(t.durationMs??0)>0,"spanLike"),$=w;for(const t of $)t.group=t.source==="react"||t.source==="valtio"||t.source==="client-runtime"||t.source==="visual"?"browser":"server";const b=new Map;for(const t of $)if((t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&t.project){const r=b.get(t.requestId)??[];r.push({project:t.project,start:t.start,end:t.start+(t.durationMs??0)}),b.set(t.requestId,r)}const m=y((t,r)=>{const e=b.get(t);if(e?.length)return e.every(n=>n.project===e[0].project)?e[0].project:e.filter(n=>n.start<=r+1&&n.end>=r-1).sort((n,s)=>s.start-n.start)[0]?.project},"projectOf");for(const t of $)if(!t.project&&t.source==="nestjs"&&t.requestId){const r=m(t.requestId,t.start);r&&(t.project=r)}const T=new Map;for(const t of $)t.spanId&&T.set(t.spanId,t);const _=y((t,r)=>{let e=t.parentSpanId?T.get(t.parentSpanId):void 0;for(let n=0;e&&n<64;n++){if(e===r)return!0;e=e.parentSpanId?T.get(e.parentSpanId):void 0}return!1},"inside");for(const t of $){const r=t.parentSpanId?T.get(t.parentSpanId):void 0;if(r&&r!==t&&r.group===t.group&&r.requestId===t.requestId){t.parent=r.id;continue}let e;const n=t.requestId;for(const s of $){if(s===t||!M(s)||s.group!==t.group||s.requestId!==n)continue;const a=s.project,g=t.project;if(s.kind!=="gateway-request"&&t.kind!=="gateway-request"&&a!==void 0&&g!==void 0&&a!==g)continue;const v=s.durationMs??0,d=t.durationMs??0,c=Math.abs(s.start-t.start)<=$t,p=J(s),I=J(t),B=s.start<=t.start;if(!(s.start+v>t.start&&(B||c&&p<I)&&(!c||(p!==I?p<I:B&&v>d))))continue;const x=e?J(e):-1,E=e?Math.abs(s.start-e.start)<=$t:!1,F=e&&E&&p===x?_(s,e)?1:_(e,s)?-1:0:0;(!e||!E&&s.start>e.start||E&&p>x||F>0||F===0&&E&&p===x&&(s.durationMs??0)<(e.durationMs??0))&&(e=s)}e&&(t.parent=e.id)}for(const t of $)delete t.spanId,delete t.parentSpanId;{const t=new Set($.map(a=>a.id)),r=new Set,e=new Map,n=[],s=y(a=>{const g=[a];for(;g.length;){const v=g.pop();n.push(v),r.add(v.id);const d=e.get(v.id);if(d){e.delete(v.id);for(let c=d.length-1;c>=0;c--)g.push(d[c])}}},"place");for(const a of $)if(a.parent&&a.parent!==a.id&&t.has(a.parent)&&!r.has(a.parent)){const g=e.get(a.parent)??[];g.push(a),e.set(a.parent,g)}else s(a);for(const a of $)r.has(a.id)||(n.push(a),r.add(a.id));for(let a=0;a<n.length;a++)$[a]=n[a]}const z=new Map;for(const t of $){if(!t.requestId)continue;const r=z.get(t.requestId);r?r.push(t):z.set(t.requestId,[t])}const et=new Map($.map(t=>[t.id,t])),S=y((t,r)=>{const e=(z.get(t)??[]).filter(n=>M(n)&&n.start<=r&&n.start+(n.durationMs??0)>=r);if(e.length!==0)return e.sort((n,s)=>s.start-n.start||(n.durationMs??0)-(s.durationMs??0)),e[0]},"callerNodeFor");for(const t of $){if(!t.parentRequestId||t.kind!=="server-request"&&t.kind!=="gateway-request")continue;const r=t.parent?et.get(t.parent):void 0;if(r&&r.requestId===t.requestId)continue;const e=S(t.parentRequestId,t.start);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}const P=$,G=new Map;for(const t of P)t.kind==="gateway-request"&&t.requestId&&!G.has(t.requestId)&&G.set(t.requestId,t);for(const t of P)if(t.group==="server"&&!t.parent&&t.requestId&&t.kind!=="gateway-request"){const r=G.get(t.requestId);r&&r!==t&&r.start<=t.start&&(t.parent=r.id)}const H=new Set,Q=new Set,W=[];for(const t of P){if(t.kind!=="gateway-request")continue;if(!t.requestId){W.push(t);continue}const r=z.get(t.requestId)??[];if(r.filter(s=>s.kind==="gateway-request").sort((s,a)=>s.start-a.start)[0]!==t)continue;const e=r.find(s=>s.kind==="fetch-start"),n=r.find(s=>s.kind==="fetch-done"||s.kind==="fetch-error");if(!e&&!n){W.push(t);continue}e&&(t.fetchStartId=e.id,H.add(e.id)),n&&(t.fetchDoneId=n.id,Q.add(n.id))}const U=new Map;for(const t of P){if(!t.urlKey)continue;const r=U.get(t.urlKey)??{gws:[],starts:[],dones:[]};t.kind==="gateway-request"?W.includes(t)&&r.gws.push(t):t.kind==="fetch-start"?H.has(t.id)||r.starts.push(t):(t.kind==="fetch-done"||t.kind==="fetch-error")&&(Q.has(t.id)||r.dones.push(t)),U.set(t.urlKey,r)}for(const{gws:t,starts:r,dones:e}of U.values()){t.sort((s,a)=>s.start-a.start),r.sort((s,a)=>s.start-a.start);const n=new Set;t.forEach((s,a)=>{const g=r[a];g&&(s.fetchStartId=g.id);const v=g?g.t:s.start;let d,c=1/0;for(const p of e){if(n.has(p.id))continue;const I=p.fetchStartedAt??p.start-(p.durationMs??0),B=Math.abs(I-v);B<c&&(c=B,d=p)}d&&(s.fetchDoneId=d.id,n.add(d.id))})}const L=new Map,N=new Map;for(const t of P)!t.queue||!t.jobId||(t.kind==="queue-enqueued"&&L.set(`${t.queue}#${t.jobId}`,t),t.kind==="queue-process"&&N.set(`${t.queue}#${t.jobId}`,t));for(const t of P){if(!t.queue||!t.jobId)continue;const r=`${t.queue}#${t.jobId}`;if(t.kind==="queue-process"&&!t.parent){const e=L.get(r);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}else if(t.kind==="queue-active"||t.kind==="queue-completed"||t.kind==="queue-failed"){const e=N.get(r);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}}{const t=new Map($.map(r=>[r.id,r]));for(const r of $){if(!r.parent||!Rt.has(r.kind??"")||r.durationMs===void 0)continue;const e=t.get(r.parent);if(!e||e.kind!=="span"||!((e.durationMs??0)>0))continue;const n=Math.round(r.start+r.durationMs-(e.start+e.durationMs));if(n<OUTLIVED_PARENT_MIN_MS)continue;r.outlivedParentMs=n;const s=e.leftRunning??{count:0,longestMs:0};e.leftRunning={count:s.count+1,longestMs:Math.max(s.longestMs,n)}}for(const r of $){const e=[];r.leftRunning&&e.push(`ended before ${r.leftRunning.count===1?"a call":`${r.leftRunning.count} calls`} it started had finished \u2014 ${r.leftRunning.count===1?"it":"the longest"} ran on ${r.leftRunning.longestMs}ms (a timeout that gave up, or work not awaited)`),r.outlivedParentMs!==void 0&&e.push(`ran on ${r.outlivedParentMs}ms after the span that started it had ended`),e.length>0&&(r.detail=[r.detail,...e].filter(Boolean).join(" \xB7 "))}}let q=$;{const t=new Map;for(const e of q)e.kind==="fetch-start"&&t.set(e.id,e);const r=new Map;for(const e of q){if(e.kind!=="fetch-done"&&e.kind!=="fetch-error")continue;const n=[...t.values()].find(g=>g.requestId&&g.requestId===e.requestId)?.id,s=n?t.get(n):void 0;if(!s)continue;const a=e.fetchStartedAt??s.start;s.title=e.title,s.severity=e.severity,s.durationMs=e.durationMs??Math.max(0,e.t-a),s.kind="fetch",e.detail&&!s.detail&&(s.detail=e.detail),r.set(e.id,s.id)}if(r.size>0){q=q.filter(e=>!r.has(e.id));for(const e of q)for(e.fetchDoneId&&r.has(e.fetchDoneId)&&(e.fetchDoneId=r.get(e.fetchDoneId));e.parent&&r.has(e.parent);)e.parent=r.get(e.parent)}}const V=y(t=>!!t.commitId&&(t.kind==="render"||t.kind==="effect-run"||t.kind==="render-commit-truncated"),"commitMember"),u=y(t=>[...new Set(t)],"uniq"),k=y(t=>u(t.map(r=>r.component).filter(r=>!!r)),"named"),A=y(t=>t.length<=2?t.join(" + "):`${t[0]} + ${t.length-1} more`,"nameList"),R=y(t=>{const r=new Map;for(const e of t)e.component&&r.set(e.component,(r.get(e.component)??0)+1);return[...r].map(([e,n])=>n>1?`${e} \xD7${n}`:e).join(", ")},"tally"),O=y(t=>{if(!t)return"effect";const r=/([^/\\]+?):(\d+)(?::\d+)?$/.exec(t);return r?`${r[1]}:${r[2]}`:t},"shortHook"),K=y(t=>`${O(t.hook)}${t.cleanup?" (cleanup)":""}`,"hookLabel"),nt=y(t=>{const r=Math.min(...t.map(n=>n.start)),e=Math.max(...t.map(n=>n.start+(n.durationMs??0)));return{start:r,durationMs:e-r}},"extent"),st=y(t=>(delete t.component,delete t.why,delete t.phase,delete t.hook,delete t.cleanup,delete t.renderTotal,delete t.renderPublished,t),"asGroup");function at(t){const r=t[0],e=t.filter(j=>j.kind==="render"),n=t.filter(j=>j.kind==="effect-run"),s=t.find(j=>j.kind==="render-commit-truncated"),a=[...e].sort((j,Y)=>(Y.durationMs??0)-(j.durationMs??0)),g=a.filter(j=>(j.why??[]).some(Y=>Y!=="parent-render")),v=u(g.flatMap(j=>(j.why??[]).filter(Y=>Y!=="parent-render"))),d=k(g),c=e.filter(j=>j.phase==="mount"),p=e.filter(j=>j.phase!=="mount"&&!g.includes(j)),I=a[0]?.component??"view",B=e.length>0&&c.length===e.length,x=v.length?v.join(" + "):void 0,E=B?"mount":"update",F=d.length?`view update \xB7 ${A(d)} \u2190 ${x}`:B?`view mount \xB7 ${I}`:`view update \xB7 ${I}`,rt=s?.renderTotal??e.length,kt=[c.length?`mounted ${R(c)}`:"",p.length?`re-rendered ${R(p)}`:"",!d.length&&!B&&e.length?"trigger not recorded \u2014 every captured render came from its parent":"",s?.renderWalkStoppedAt!==void 0?`at least ${rt} renders (the walk stopped at ${s.renderWalkStoppedAt} fibers), ${s.renderPublished??e.length} recorded`:s?`${rt} renders, ${s.renderPublished??e.length} recorded (per-commit cap)`:`${e.length} render${e.length===1?"":"s"}`,n.length?`${n.length} effect${n.length===1?"":"s"}: ${n.map(K).join(", ")}`:""].filter(Boolean).join(" \xB7 "),lt=k(e);return st({...r,...nt(t),kind:"view-update",title:F,detail:kt,commitId:r.commitId,viewPhase:E,...x?{cause:x}:{},causeComponents:d,components:lt,mounted:k(c),renderCount:rt,...s?.renderWalkStoppedAt!==void 0?{renderCountAtLeast:!0}:{},recordedRenders:e.length,effects:n.length,effectHooks:n.map(K),memberIds:t.map(j=>j.id),sig:`commit:${E}:${x??"-"}:${d.join(",")}:${lt.slice().sort().join(",")}`,severity:t.some(j=>j.severity==="error")?"error":r.severity})}C(at,"pt"),y(at,"viewUpdateNode");function it(t){const r=t[0],e=t.map(K);return st({...r,...nt(t),kind:"commit-effects",title:t.length===1?`effect \xB7 ${e[0]}`:`effects \xB7 ${e[0]} + ${t.length-1} more`,detail:e.join(", "),commitId:r.commitId,effects:t.length,effectHooks:e,memberIds:t.map(n=>n.id),sig:`effects:${e.slice().sort().join(",")}`})}C(it,"mt"),y(it,"effectsNode");const vt=y(t=>u(t.map(r=>r==="state-update"?"state update":r==="fetch-start"?"request":r==="flow-origin"?"interaction":"response")).join(" + "),"describeInputs");function dt(t,r){const e=t[0],n=t[t.length-1],s=t.length,a=e.detail,g=Math.min(...t.map(p=>p.start)),v=Math.max(...t.map(p=>p.start+(p.durationMs??0))),d=Math.round(t.reduce((p,I)=>p+(I.durationMs??0),0)/s*10)/10,c=Math.round((v-g)*10)/10;e.count=s,e.avgMs=d,e.wallMs=c,e.durationMs=v-g,e.items=t.slice(0,12).map(p=>({start:p.start-g,...p.durationMs!=null?{durationMs:p.durationMs}:{}})),e.memberIds=t.flatMap(p=>p.memberIds??[p.id]),e.title=`\xD7${s} ${e.title}`,t.some(p=>p.severity==="error")&&(e.severity="error"),e.kind==="view-update"?e.detail=[`${s} commits, ${r.length?`one per ${vt(r)}`:"back to back"}`,`avg ${d}ms \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 "):e.kind==="state-update"&&a&&n.detail?e.detail=`${s} updates in a row \xB7 wall ${c}ms \xB7 first ${a} \xB7 last ${n.detail}`:e.detail=[`${s} in a row \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 ")}C(dt,"ht"),y(dt,"collapseRepeat");const Z=[],X=new Map,ut=new Set;for(let t=0;t<q.length;t++){if(ut.has(t))continue;const r=q[t];if(!V(r)){Z.push(r);continue}const e=[t];for(let a=t+1;a<q.length;a++){const g=q[a];if(g.group==="browser"){if(!V(g)||g.commitId!==r.commitId)break;e.push(a)}}for(const a of e)ut.add(a);const n=e.map(a=>q[a]),s=n.some(a=>a.kind!=="effect-run")?at(n):it(n);for(const a of n)a.id!==s.id&&X.set(a.id,s.id);Z.push(s)}if(X.size>0||Z.some(t=>t.kind==="view-update"||t.kind==="commit-effects")){q=Z;for(const t of q)for(;t.parent&&X.has(t.parent);)t.parent=X.get(t.parent)}{const t=new Map;for(const r of q)r.kind==="view-update"&&r.commitId&&!t.has(r.commitId)&&t.set(r.commitId,r);for(const r of q){if(r.kind!=="commit-effects"||r.parent||!r.commitId)continue;const e=t.get(r.commitId);e&&e.start<=r.start&&(r.parent=e.id)}}{const t=new Set(["state-update","fetch","fetch-start","fetch-done","fetch-error","flow-origin"]),r=q.map((d,c)=>d.group==="browser"?c:-1).filter(d=>d>=0),e=y(d=>`${d.kind}|${d.sig??d.title}`,"keyOf"),n=r.map(d=>e(q[d])),s=y((d,c,p)=>{for(let I=0;I<p;I++)if(n[d+I]!==n[c+I])return!1;return!0},"sameBlock"),a=y(d=>n[d].split("|")[0],"kindAt"),g=y(d=>{let c=0,p=1;for(let I=1;I<=4&&d+I<=n.length;I++){let B=1;for(;d+(B+1)*I<=n.length&&s(d,d+B*I,I);)B+=1;B>=3&&I*B>c*p&&(c=I,p=B)}return{k:c,r:p}},"bestBlockAt"),v=new Map;for(let d=0;d<n.length;){const{k:c,r:p}=g(d);if(c===0){d+=1;continue}const I=[...Array(c).keys()].find(x=>t.has(a(d+x)));if(I!==void 0&&I>0){const x=g(d+I);if(x.k===c&&x.r>=3&&x.r>=p-1){d+=I;continue}}const B=n.slice(d,d+c).map(x=>x.split("|")[0]).filter(x=>t.has(x));for(let x=0;x<c;x++){const E=[];for(let F=0;F<p;F++)E.push(q[r[d+x+F*c]]);dt(E,B);for(const F of E.slice(1))v.set(F.id,E[0].id)}d+=c*p}if(v.size>0){q=q.filter(d=>!v.has(d.id));for(const d of q)for(;d.parent&&v.has(d.parent);)d.parent=v.get(d.parent)}}{const t=new Map(q.map(r=>[r.id,r]));for(const r of q){const e=new Set([r.id]);let n=r;for(;n?.parent;){if(e.has(n.parent)){n.parent=void 0;break}e.add(n.parent),n=t.get(n.parent)}}}const ct=y(t=>{const r=new Map;for(const n of q){if(!n.sig||M(n)!==t||n.kind==="server-request"||n.kind==="gateway-request"||n.group==="browser")continue;const s=`${n.parent??"root"}|${n.kind}|${n.sig}`,a=r.get(s);a?a.push(n):r.set(s,[n])}const e=new Map;for(const n of r.values()){if(n.length<3)continue;n.sort((c,p)=>c.start-p.start);const s=n[0];let a=!1;for(let c=0;c+1<n.length;c++)if(n[c+1].start<n[c].start+(n[c].durationMs??0)){a=!0;break}const g=s.start,v=Math.max(...n.map(c=>c.start+(c.durationMs??0))),d=n.reduce((c,p)=>c+(p.durationMs??0),0);s.count=n.length,s.parallel=a,s.avgMs=Math.round(d/n.length*10)/10,s.wallMs=v-g,s.durationMs=v-g,s.title=`\xD7${n.length} ${s.title.replace(/\s*\((?:\d+ rows?, )?\d+ms\)$/,"")}`,s.detail=`${s.sig} \xD7${n.length} ${a?"\u2016 parallel":"\u21BB sequential loop"} \xB7 avg ${s.avgMs}ms \xB7 wall ${s.wallMs}ms`,s.items=n.slice(0,12).map(c=>({start:c.start-g,...c.durationMs!=null?{durationMs:c.durationMs}:{}})),s.memberIds=n.flatMap(c=>c.memberIds??[c.id]),n.some(c=>c.severity==="error")&&(s.severity="error");for(const c of n.slice(1))e.set(c.id,s.id)}if(e.size!==0){q=q.filter(n=>!e.has(n.id));for(const n of q)for(;n.parent&&e.has(n.parent);)n.parent=e.get(n.parent)}},"aggregatePass");ct(!0),ct(!1);for(const t of q){if(!M(t))continue;const r=t.durationMs??0;if(r<40)continue;const e=q.filter(v=>v.parent===t.id&&(v.durationMs??0)>0).map(v=>[v.start,v.start+(v.durationMs??0)]).sort((v,d)=>v[0]-d[0]);let n=0,s=-1,a=-1;for(const[v,d]of e)v>a?(a>s&&(n+=a-s),s=v,a=d):d>a&&(a=d);a>s&&(n+=a-s);const g=Math.max(0,r-n);(g>=50||g/r>=.7&&r>=40)&&(t.selfMs=g,t.detail=`\u26A0 cpu-heavy: ${g}ms self-time of ${r}ms${t.detail?" \xB7 "+t.detail:""}`)}return{events:q,...o?{sql:o}:{}}}C(buildFlowDetail,"buildFlowDetail"),y(buildFlowDetail,"buildFlowDetail");
|
|
1
|
+
"use strict";var qt=Object.defineProperty;var R=(i,f)=>qt(i,"name",{value:f,configurable:!0});var It=Object.defineProperty,P=R((i,f)=>It(i,"name",{value:f,configurable:!0}),"C"),Mt=Object.defineProperty,v=P((i,f)=>Mt(i,"name",{value:f,configurable:!0}),"$");import{redactDeep as bt,redactText as it,redactUrlParams as xt}from"./redact.js";import{templatisePath as ht}from"./route-template.js";import{SQL_ACCOUNT_KIND as jt,sqlAccountingOf as Bt}from"./flow-segments.js";import{boundedClone as St}from"@lensmcp/protocol-types";export function areaOf(i){const{source:f,category:o,title:w,kind:l}=i;return f==="ai"?"ai":l?.startsWith("memory")||l==="db-query"?"data":f==="gateway"||l==="gateway-request"?"gateway":l==="queue-process"||l==="queue-active"||l==="queue-completed"||l==="queue-failed"?"services":f==="db"||f==="redis"||f==="queue"||l==="redis-op"||l?.startsWith("queue-")||f==="fs"||l==="fs-ops"?"data":f==="exec"||l==="exec"?"services":f==="external"||l==="egress"?"network":f==="nestjs"||f==="nest"?/(?:Repository|Repo|Dao|Store|EntityManager|DataSource|QueryRunner|OrmClient)\./.test(w)?"data":"services":f==="valtio"?"state":o==="network"?"network":"browser"}R(areaOf,"areaOf"),P(areaOf,"areaOf"),v(areaOf,"areaOf");const $t=240,At=new Set(["systemPrompt","prompt","prompts","messages","completion","completions","input","output","draft","text","content","result","arguments","params"]),Tt=new Set(["tenantId","caller","userId","accountId","email","subject"]),Rt=8;function dt(i){const f=Y(i,0);return St(bt({redacted:!0,...f}),{rawByteLimit:16*1024}).value}R(dt,"mt"),P(dt,"vt"),v(dt,"aiProjection");function Y(i,f){if(typeof i=="string")return ut(i);if(i===null||typeof i!="object")return i;if(f>=Rt)return;if(Array.isArray(i))return i.slice(0,32).map(w=>Y(w,f+1));const o={};for(const[w,l]of Object.entries(i))if(!Tt.has(w)){if(At.has(w)){typeof l=="string"?o[`${w}Chars`]=l.length:Array.isArray(l)?o[`${w}Count`]=l.length:l!=null&&(o[`${w}Present`]=!0);continue}o[w]=Y(l,f+1)}return o}R(Y,"tt"),P(Y,"rt"),v(Y,"projectAi");function ut(i){return i.length<=$t?it(i):`${it(i.slice(0,$t))}\u2026`}R(ut,"ht"),P(ut,"jt"),v(ut,"clipText");export function httpFacts(i,f){const o=v(I=>typeof I=="string"&&I.length>0?I:void 0,"str"),w=typeof f.status=="number"?f.status:void 0,l=v(I=>xt(I.split("?")[0]??I)||"/","pathOf"),C=v((I,y,x={})=>({...I?{method:I.toUpperCase()}:{},...y?{rawPath:y,route:ht(y)}:{},...w!==void 0?{status:w}:{},...x}),"facts");if(i==="gateway-request"){const I=o(f.url);return C(o(f.method),I?l(I):void 0,{...o(f.host)?{host:o(f.host)}:{},...o(f.caller)?{caller:o(f.caller)}:{}})}if(i==="egress"){const I=o(f.path),y=o(f.exchangeId);return C(o(f.method)??"GET",I?l(I):void 0,{...o(f.host)?{host:o(f.host)}:{},...y?{exchangeId:y}:{}})}if(i==="fetch-start"||i==="fetch-done"||i==="fetch-error"){const I=o(f.href)??o(f.url);let y,x;if(I)try{const p=new URL(I,"http://relative.invalid");y=l(p.pathname),p.hostname!=="relative.invalid"&&(x=p.hostname)}catch{}return C(o(f.method)??"GET",y,x?{host:x}:{})}if(i==="ai-call")return{...w!==void 0?{status:w}:{},...f.stream===!0?{streamed:!0}:{}};const h=f.request;if(h&&typeof h=="object"){const I=h,y=o(I.route),x=o(I.method);if(!y&&!x)return{};const p=typeof I.status=="number"?I.status:void 0,D=y?l(y):void 0;return{...x?{method:x.toUpperCase()}:{},...D?{rawPath:D,route:D.includes(":")?D:ht(D)}:{},...p!==void 0?{status:p}:{}}}return{}}R(httpFacts,"httpFacts"),P(httpFacts,"httpFacts"),v(httpFacts,"httpFacts");export function trimFlowEvent(i,f={}){const o=i.raw??{},w=o.render??{},l=o.span??{},C=o.request??{},h=v(d=>typeof d=="number"?d:void 0,"num"),I=o.loop??{},y=o.effect??{},x=h(o.durationMs)??h(l.durationMs)??h(C.durationMs)??h(I.durationMs)??h(w.actualDurationMs)??h(y.durationMs),p=typeof o.kind=="string"?o.kind:void 0,D=p==="fetch-done"||p==="fetch-error",H=h(w.commitTime),Q=p==="render"&&H!==void 0&&Math.abs(H-i.timestamp)<6e4,rt=D?i.timestamp:Q?H:h(o.startedAt)??h(l.startTime)??h(C.startedAt)??h(I.startedAt)??(x!==void 0?i.timestamp-x:i.timestamp);let j;if(typeof o.query=="string"){const d=Array.isArray(o.params)?` [${o.params.join(", ")}]`:"",m=typeof o.result=="string"?` \u2192 ${o.result}`:"";j=o.query+d+m}else if(typeof o.command=="string"){const d=typeof o.value=="string"?` \u2192 ${o.value}`:o.hit===!1?" \u2192 (miss)":"";j=o.command+d}else if(p==="state-update"){const d=o.update??{};let m="";try{m=JSON.stringify(d.preview)}catch{}j=`${d.storeId??""}.${d.path??""} = ${m}`}else if(p==="fs-ops"&&Array.isArray(o.paths))j=o.paths.slice(0,8).map(d=>{const m=d??{},S=typeof m.n=="number"&&m.n>1?` \xD7${m.n}`:"",T=typeof m.bytes=="number"&&m.bytes>0?` (${m.bytes>=1024?`${(m.bytes/1024).toFixed(1)} KB`:`${m.bytes} B`})`:"";return`${String(m.op??"?")} ${String(m.path??"?")}${S}${T}`}).join(" \xB7 ");else if(p==="exec"&&typeof o.cmd=="string")j=`${o.cmd} \u2192 ${o.code??o.signal??o.error??"?"}`;else if(p==="queue-completed"&&typeof o.returned=="string")j=`returned ${o.returned}`;else if(p==="queue-enqueued")j=`${o.job??"job"}#${o.jobId??"?"} \u2192 ${o.queue??""}${typeof o.data=="string"?" "+o.data:""}`;else if(p==="log"){const d=C.error??{},m=typeof d.stack=="string"?d.stack:typeof o.text=="string"?o.text:void 0;m&&m!==i.title&&(j=m)}let F,G,V,J;if(p==="span"){const d=l.outcome;if(F=d==="threw"||d==="returned"?d:l.status==="error"?"threw":l.status==="ok"?"returned":void 0,F==="threw"){const T=l.error??{},E=typeof T.name=="string"?T.name:void 0,_=typeof T.message=="string"?T.message:typeof i.message=="string"?i.message:void 0;V=E,G=it([E,_].filter(Boolean).join(": "))||void 0}const m=typeof l.args=="string"?l.args:void 0,S=typeof l.result=="string"?l.result:void 0;if(m!==void 0||S!==void 0){J=[...m!==void 0?["args"]:[],...S!==void 0?["result"]:[]];const T=v(E=>E.length>yt?`${E.slice(0,yt)}\u2026`:E,"short");j=[m!==void 0?`args ${T(m)}`:"",S!==void 0?`returned ${T(S)}`:""].filter(Boolean).join(" \u2192 ")}}let W;if(p==="gateway-request")W=`${o.host??""}${String(o.url??"").split("?")[0]}`;else if(p==="fetch-start"||p==="fetch-done"||p==="fetch-error")try{const d=new URL(String(o.href??o.url??""));W=`${d.hostname}${d.pathname}`}catch{}let K;if(p==="gateway-request"&&Array.isArray(o.steps))K=o.steps.map(d=>{const m=[String(d.step)];return d.project&&m.push(String(d.project)),d.prefix&&m.push(String(d.prefix)),d.mode&&m.push(String(d.mode)+(d.ok===!1?" \u2717":d.ok===!0?" \u2713":"")),d.caller&&m.push("by "+String(d.caller)),d.pod&&m.push(String(d.pod)),typeof d.atMs=="number"&&m.push(`@${d.atMs}ms`),m.join(" ")}),j=K.map(d=>d.replace(/ @\d+ms$/,"")).join(" \u2192 ");else if(p==="egress")j=`${o.method??"GET"} ${o.host??""} \u2192 ${o.status??"?"}`;else if(i.source==="ai"){if(p==="ai-call"){const d=o.usage??{},m=d.promptTokens!==void 0||d.completionTokens!==void 0?` \xB7 ${h(d.promptTokens)??"?"}\u2192${h(d.completionTokens)??"?"} tok`:"",S=o.status!==void 0?` \xB7 ${String(o.status)}`:o.error?" \xB7 failed":"",T=h(o.toolCallCount)?` \xB7 ${h(o.toolCallCount)} tool call${h(o.toolCallCount)===1?"":"s"}`:"",E=h(o.durationMs)!==void 0?` \xB7 ${(h(o.durationMs)/1e3).toFixed(1)}s`:"";j=`${o.provider??""}/${o.model??"?"}${m}${S}${T}${E}${o.stream===!0?" \xB7 stream":""}`}else if(p==="ai-round"){const d=o.model??{},m=o.usage??{},S=Array.isArray(o.toolCalls)?o.toolCalls:[],T=`${h(m.promptTokens)??"?"}\u2192${h(m.completionTokens)??"?"} tok`,E=S.length?` \xB7 ${S.length} tool call${S.length===1?"":"s"}`:"",_=h(o.durationMs)!==void 0?` \xB7 ${(h(o.durationMs)/1e3).toFixed(1)}s`:"";j=`${d.provider??""}/${d.model??""} \xB7 ${T}${E}${_}`}else if(p==="ai-turn-start"){const d=Array.isArray(o.tools)?o.tools:[];j=`skill ${o.skill??""} \xB7 ${o.output??""}${d.length?" \xB7 tools: "+d.join(", "):""}`}else if(p==="ai-tool-call"){const d=o.call??{},m=o.result??{},S=h(o.durationMs)!==void 0?` \xB7 ${(h(o.durationMs)/1e3).toFixed(1)}s`:"";j=`${d.name??"tool"} ${m.error!=null?"\u2717 "+String(m.error):"\u2713"}${S}`}else if(p==="ai-turn-end"){const d=o.usage??{},m=h(o.rounds)!==void 0?` \xB7 ${h(o.rounds)} round${h(o.rounds)===1?"":"s"}`:"",S=h(o.durationMs)!==void 0?` \xB7 ${(h(o.durationMs)/1e3).toFixed(1)}s`:"";j=`${o.ok===!1?"FAILED":"ok"} \xB7 ${h(d.promptTokens)??"?"}+${h(d.completionTokens)??"?"} tok${m}${S}`}}let O;p==="db-query"&&typeof o.query=="string"?O=o.query:p==="redis-op"?O=`${o.op??""} ${String(o.key??"").replace(/\d+/g,"#")}`:p==="egress"?O=`${o.method??"GET"} ${o.host??""}`:p==="ai-call"?O=`ai ${o.provider??""} ${o.model??""} ${o.api??""}`:p==="queue-enqueued"?O=`enqueue ${o.queue??""}`:p==="span"&&typeof l.name=="string"?O=l.name:p==="memory-mutation"&&(O=i.title);const U=i.context??{},q=w.commitId??y.commitId??o.commitId,Z=Array.isArray(w.why)?w.why.map(d=>typeof d?.type=="string"?d.type:void 0).filter(d=>!!d):[];return{id:i.id,t:i.timestamp,start:rt,...O?{sig:O}:{},...W?{urlKey:W}:{},...httpFacts(p,o),...(p==="db-query"||p==="redis-op")&&typeof o.valuesId=="string"?{valuesId:o.valuesId}:{},...typeof o.queue=="string"?{queue:o.queue}:{},...o.jobId!=null?{jobId:String(o.jobId)}:{},source:i.source,category:i.category,severity:i.severity,title:F==="threw"&&typeof l.name=="string"?`${l.name} \u2014 threw${V?` ${V}`:""}${x!==void 0?` after ${x}ms`:""}`:i.title,kind:p,area:areaOf({source:i.source,category:i.category,title:i.title,kind:p}),...F?{outcome:F}:{},...G?{error:G}:{},...J?{captured:J}:{},...typeof l.role=="string"?{role:l.role}:{},...typeof l.spanId=="string"?{spanId:l.spanId}:{},...typeof l.parentSpanId=="string"?{parentSpanId:l.parentSpanId}:{},...p==="log"&&typeof o.level=="string"?{level:o.level}:{},...p==="log"&&typeof o.logger=="string"?{logger:o.logger}:{},...p==="log"&&typeof o.stream=="string"?{stream:o.stream}:{},...typeof U.requestId=="string"?{requestId:U.requestId}:{},...typeof U.parentRequestId=="string"?{parentRequestId:U.parentRequestId}:{},...typeof q=="string"?{commitId:q}:{},...typeof w.componentName=="string"?{component:w.componentName}:{},...typeof w.phase=="string"?{phase:w.phase}:{},...Z.length?{why:Z}:{},...p==="effect-run"&&typeof y.hookLogicalId=="string"?{hook:y.hookLogicalId}:{},...p==="effect-run"&&y.cleanupRan===!0?{cleanup:!0}:{},...p==="render-commit-truncated"?{renderTotal:h(o.total),renderPublished:h(o.published),...h(o.walkStoppedAt)!==void 0?{renderWalkStoppedAt:h(o.walkStoppedAt)}:{}}:{},...typeof U.projectName=="string"?{project:U.projectName}:typeof o.project=="string"?{project:o.project}:{},...x!==void 0?{durationMs:x}:{},...D&&h(o.startedAt)!==void 0?{fetchStartedAt:h(o.startedAt)}:{},...i.source==="ai"?{ai:f.includeRaw?o:dt(o)}:{},...j?{detail:j}:{},...K?{steps:K}:{}}}R(trimFlowEvent,"trimFlowEvent"),P(trimFlowEvent,"trimFlowEvent"),v(trimFlowEvent,"trimFlowEvent");const yt=300;export const OUTLIVED_PARENT_MIN_MS=250;const Dt=new Set(["egress","db-query","redis-op","ai-call","span","gateway-request","server-request"]),vt=1;function ct(i){return i==="flow-origin"?0:i?.endsWith("-start")?1:i==="gateway-request"?2:i==="server-request"?3:i==="span"?4:i==="render"||i==="render-commit-truncated"?6:i==="effect-run"?7:5}R(ct,"yt"),P(ct,"Rt"),v(ct,"kindRank");function z(i){return i.kind==="span"&&i.role==="controller"?3.5:i.kind==="queue-process"?3:ct(i.kind)}R(z,"J"),P(z,"Z"),v(z,"causalRank");export function buildFlowDetail(i,f={}){const o=Bt(i),w=i.slice().filter(t=>{const r=t.raw??{},e=typeof r.kind=="string"?r.kind:"";if(e==="subscription-added"||e==="subscription-removed"||e==="hook-run"||e==="store-created"||e==="singleton-instance"||e===jt)return!1;const n=r.span;return!(typeof n?.name=="string"&&n.name.startsWith("nest.request "))}).map(t=>trimFlowEvent(t,f)),l=new Set;for(let t=w.length-1;t>=0;t--)l.has(w[t].id)?w.splice(t,1):l.add(w[t].id);const C=new Map;for(const t of w)(t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&!C.has(t.requestId)&&C.set(t.requestId,t.start);const h=v(t=>t.source!=="react"&&t.source!=="valtio"&&t.requestId&&C.has(t.requestId)?C.get(t.requestId):t.start,"anchorOf");w.sort((t,r)=>h(t)-h(r)||t.start-r.start||z(t)-z(r)||(r.durationMs??0)-(t.durationMs??0)||t.t-r.t);const I=v(t=>(t.kind==="span"||t.kind==="server-request"||t.kind==="gateway-request"||t.kind==="queue-process")&&(t.durationMs??0)>0,"spanLike"),y=w;for(const t of y)t.group=t.source==="react"||t.source==="valtio"||t.source==="client-runtime"||t.source==="visual"?"browser":"server";const x=new Map;for(const t of y)if((t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&t.project){const r=x.get(t.requestId)??[];r.push({project:t.project,start:t.start,end:t.start+(t.durationMs??0)}),x.set(t.requestId,r)}const p=v((t,r)=>{const e=x.get(t);if(e?.length)return e.every(n=>n.project===e[0].project)?e[0].project:e.filter(n=>n.start<=r+1&&n.end>=r-1).sort((n,s)=>s.start-n.start)[0]?.project},"projectOf");for(const t of y)if(!t.project&&t.source==="nestjs"&&t.requestId){const r=p(t.requestId,t.start);r&&(t.project=r)}const D=new Map;for(const t of y)t.spanId&&D.set(t.spanId,t);const H=v((t,r)=>{let e=t.parentSpanId?D.get(t.parentSpanId):void 0;for(let n=0;e&&n<64;n++){if(e===r)return!0;e=e.parentSpanId?D.get(e.parentSpanId):void 0}return!1},"inside");for(const t of y){const r=t.parentSpanId?D.get(t.parentSpanId):void 0;if(r&&r!==t&&r.group===t.group&&r.requestId===t.requestId){t.parent=r.id;continue}let e;const n=t.requestId;for(const s of y){if(s===t||!I(s)||s.group!==t.group||s.requestId!==n)continue;const a=s.project,$=t.project;if(s.kind!=="gateway-request"&&t.kind!=="gateway-request"&&a!==void 0&&$!==void 0&&a!==$)continue;const k=s.durationMs??0,u=t.durationMs??0,c=Math.abs(s.start-t.start)<=vt,g=z(s),M=z(t),A=s.start<=t.start;if(!(s.start+k>t.start&&(A||c&&g<M)&&(!c||(g!==M?g<M:A&&k>u))))continue;const b=e?z(e):-1,L=e?Math.abs(s.start-e.start)<=vt:!1,N=e&&L&&g===b?H(s,e)?1:H(e,s)?-1:0:0;(!e||!L&&s.start>e.start||L&&g>b||N>0||N===0&&L&&g===b&&(s.durationMs??0)<(e.durationMs??0))&&(e=s)}e&&(t.parent=e.id)}for(const t of y)delete t.spanId,delete t.parentSpanId;{const t=new Set(y.map(a=>a.id)),r=new Set,e=new Map,n=[],s=v(a=>{const $=[a];for(;$.length;){const k=$.pop();n.push(k),r.add(k.id);const u=e.get(k.id);if(u){e.delete(k.id);for(let c=u.length-1;c>=0;c--)$.push(u[c])}}},"place");for(const a of y)if(a.parent&&a.parent!==a.id&&t.has(a.parent)&&!r.has(a.parent)){const $=e.get(a.parent)??[];$.push(a),e.set(a.parent,$)}else s(a);for(const a of y)r.has(a.id)||(n.push(a),r.add(a.id));for(let a=0;a<n.length;a++)y[a]=n[a]}const Q=new Map;for(const t of y){if(!t.requestId)continue;const r=Q.get(t.requestId);r?r.push(t):Q.set(t.requestId,[t])}const rt=new Map(y.map(t=>[t.id,t])),j=v((t,r)=>{const e=(Q.get(t)??[]).filter(n=>I(n)&&n.start<=r&&n.start+(n.durationMs??0)>=r);if(e.length!==0)return e.sort((n,s)=>s.start-n.start||(n.durationMs??0)-(s.durationMs??0)),e[0]},"callerNodeFor");for(const t of y){if(!t.parentRequestId||t.kind!=="server-request"&&t.kind!=="gateway-request")continue;const r=t.parent?rt.get(t.parent):void 0;if(r&&r.requestId===t.requestId)continue;const e=j(t.parentRequestId,t.start);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}const F=y,G=new Map;for(const t of F)t.kind==="gateway-request"&&t.requestId&&!G.has(t.requestId)&&G.set(t.requestId,t);for(const t of F)if(t.group==="server"&&!t.parent&&t.requestId&&t.kind!=="gateway-request"){const r=G.get(t.requestId);r&&r!==t&&r.start<=t.start&&(t.parent=r.id)}const V=new Set,J=new Set,W=[];for(const t of F){if(t.kind!=="gateway-request")continue;if(!t.requestId){W.push(t);continue}const r=Q.get(t.requestId)??[];if(r.filter(s=>s.kind==="gateway-request").sort((s,a)=>s.start-a.start)[0]!==t)continue;const e=r.find(s=>s.kind==="fetch-start"),n=r.find(s=>s.kind==="fetch-done"||s.kind==="fetch-error");if(!e&&!n){W.push(t);continue}e&&(t.fetchStartId=e.id,V.add(e.id)),n&&(t.fetchDoneId=n.id,J.add(n.id))}const K=new Map;for(const t of F){if(!t.urlKey)continue;const r=K.get(t.urlKey)??{gws:[],starts:[],dones:[]};t.kind==="gateway-request"?W.includes(t)&&r.gws.push(t):t.kind==="fetch-start"?V.has(t.id)||r.starts.push(t):(t.kind==="fetch-done"||t.kind==="fetch-error")&&(J.has(t.id)||r.dones.push(t)),K.set(t.urlKey,r)}for(const{gws:t,starts:r,dones:e}of K.values()){t.sort((s,a)=>s.start-a.start),r.sort((s,a)=>s.start-a.start);const n=new Set;t.forEach((s,a)=>{const $=r[a];$&&(s.fetchStartId=$.id);const k=$?$.t:s.start;let u,c=1/0;for(const g of e){if(n.has(g.id))continue;const M=g.fetchStartedAt??g.start-(g.durationMs??0),A=Math.abs(M-k);A<c&&(c=A,u=g)}u&&(s.fetchDoneId=u.id,n.add(u.id))})}const O=new Map,U=new Map;for(const t of F)!t.queue||!t.jobId||(t.kind==="queue-enqueued"&&O.set(`${t.queue}#${t.jobId}`,t),t.kind==="queue-process"&&U.set(`${t.queue}#${t.jobId}`,t));for(const t of F){if(!t.queue||!t.jobId)continue;const r=`${t.queue}#${t.jobId}`;if(t.kind==="queue-process"&&!t.parent){const e=O.get(r);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}else if(t.kind==="queue-active"||t.kind==="queue-completed"||t.kind==="queue-failed"){const e=U.get(r);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}}{const t=new Map(y.map(r=>[r.id,r]));for(const r of y){if(!r.parent||!Dt.has(r.kind??"")||r.durationMs===void 0)continue;const e=t.get(r.parent);if(!e||e.kind!=="span"||!((e.durationMs??0)>0))continue;const n=Math.round(r.start+r.durationMs-(e.start+e.durationMs));if(n<OUTLIVED_PARENT_MIN_MS)continue;r.outlivedParentMs=n;const s=e.leftRunning??{count:0,longestMs:0};e.leftRunning={count:s.count+1,longestMs:Math.max(s.longestMs,n)}}for(const r of y){const e=[];r.leftRunning&&e.push(`ended before ${r.leftRunning.count===1?"a call":`${r.leftRunning.count} calls`} it started had finished \u2014 ${r.leftRunning.count===1?"it":"the longest"} ran on ${r.leftRunning.longestMs}ms (a timeout that gave up, or work not awaited)`),r.outlivedParentMs!==void 0&&e.push(`ran on ${r.outlivedParentMs}ms after the span that started it had ended`),e.length>0&&(r.detail=[r.detail,...e].filter(Boolean).join(" \xB7 "))}}let q=y;{const t=new Map;for(const e of q)e.kind==="fetch-start"&&t.set(e.id,e);const r=new Map;for(const e of q){if(e.kind!=="fetch-done"&&e.kind!=="fetch-error")continue;const n=[...t.values()].find($=>$.requestId&&$.requestId===e.requestId)?.id,s=n?t.get(n):void 0;if(!s)continue;const a=e.fetchStartedAt??s.start;s.title=e.title,s.severity=e.severity,s.durationMs=e.durationMs??Math.max(0,e.t-a),s.kind="fetch",e.detail&&!s.detail&&(s.detail=e.detail),r.set(e.id,s.id)}if(r.size>0){q=q.filter(e=>!r.has(e.id));for(const e of q)for(e.fetchDoneId&&r.has(e.fetchDoneId)&&(e.fetchDoneId=r.get(e.fetchDoneId));e.parent&&r.has(e.parent);)e.parent=r.get(e.parent)}}const Z=v(t=>!!t.commitId&&(t.kind==="render"||t.kind==="effect-run"||t.kind==="render-commit-truncated"),"commitMember"),d=v(t=>[...new Set(t)],"uniq"),m=v(t=>d(t.map(r=>r.component).filter(r=>!!r)),"named"),S=v(t=>t.length<=2?t.join(" + "):`${t[0]} + ${t.length-1} more`,"nameList"),T=v(t=>{const r=new Map;for(const e of t)e.component&&r.set(e.component,(r.get(e.component)??0)+1);return[...r].map(([e,n])=>n>1?`${e} \xD7${n}`:e).join(", ")},"tally"),E=v(t=>{if(!t)return"effect";const r=/([^/\\]+?):(\d+)(?::\d+)?$/.exec(t);return r?`${r[1]}:${r[2]}`:t},"shortHook"),_=v(t=>`${E(t.hook)}${t.cleanup?" (cleanup)":""}`,"hookLabel"),lt=v(t=>{const r=Math.min(...t.map(n=>n.start)),e=Math.max(...t.map(n=>n.start+(n.durationMs??0)));return{start:r,durationMs:e-r}},"extent"),pt=v(t=>(delete t.component,delete t.why,delete t.phase,delete t.hook,delete t.cleanup,delete t.renderTotal,delete t.renderPublished,t),"asGroup");function ot(t){const r=t[0],e=t.filter(B=>B.kind==="render"),n=t.filter(B=>B.kind==="effect-run"),s=t.find(B=>B.kind==="render-commit-truncated"),a=[...e].sort((B,X)=>(X.durationMs??0)-(B.durationMs??0)),$=a.filter(B=>(B.why??[]).some(X=>X!=="parent-render")),k=d($.flatMap(B=>(B.why??[]).filter(X=>X!=="parent-render"))),u=m($),c=e.filter(B=>B.phase==="mount"),g=e.filter(B=>B.phase!=="mount"&&!$.includes(B)),M=a[0]?.component??"view",A=e.length>0&&c.length===e.length,b=k.length?k.join(" + "):void 0,L=A?"mount":"update",N=u.length?`view update \xB7 ${S(u)} \u2190 ${b}`:A?`view mount \xB7 ${M}`:`view update \xB7 ${M}`,at=s?.renderTotal??e.length,wt=[c.length?`mounted ${T(c)}`:"",g.length?`re-rendered ${T(g)}`:"",!u.length&&!A&&e.length?"trigger not recorded \u2014 every captured render came from its parent":"",s?.renderWalkStoppedAt!==void 0?`at least ${at} renders (the walk stopped at ${s.renderWalkStoppedAt} fibers), ${s.renderPublished??e.length} recorded`:s?`${at} renders, ${s.renderPublished??e.length} recorded (per-commit cap)`:`${e.length} render${e.length===1?"":"s"}`,n.length?`${n.length} effect${n.length===1?"":"s"}: ${n.map(_).join(", ")}`:""].filter(Boolean).join(" \xB7 "),gt=m(e);return pt({...r,...lt(t),kind:"view-update",title:N,detail:wt,commitId:r.commitId,viewPhase:L,...b?{cause:b}:{},causeComponents:u,components:gt,mounted:m(c),renderCount:at,...s?.renderWalkStoppedAt!==void 0?{renderCountAtLeast:!0}:{},recordedRenders:e.length,effects:n.length,effectHooks:n.map(_),memberIds:t.map(B=>B.id),sig:`commit:${L}:${b??"-"}:${u.join(",")}:${gt.slice().sort().join(",")}`,severity:t.some(B=>B.severity==="error")?"error":r.severity})}R(ot,"at"),P(ot,"pt"),v(ot,"viewUpdateNode");function nt(t){const r=t[0],e=t.map(_);return pt({...r,...lt(t),kind:"commit-effects",title:t.length===1?`effect \xB7 ${e[0]}`:`effects \xB7 ${e[0]} + ${t.length-1} more`,detail:e.join(", "),commitId:r.commitId,effects:t.length,effectHooks:e,memberIds:t.map(n=>n.id),sig:`effects:${e.slice().sort().join(",")}`})}R(nt,"it"),P(nt,"mt"),v(nt,"effectsNode");const kt=v(t=>d(t.map(r=>r==="state-update"?"state update":r==="fetch-start"?"request":r==="flow-origin"?"interaction":"response")).join(" + "),"describeInputs");function st(t,r){const e=t[0],n=t[t.length-1],s=t.length,a=e.detail,$=Math.min(...t.map(g=>g.start)),k=Math.max(...t.map(g=>g.start+(g.durationMs??0))),u=Math.round(t.reduce((g,M)=>g+(M.durationMs??0),0)/s*10)/10,c=Math.round((k-$)*10)/10;e.count=s,e.avgMs=u,e.wallMs=c,e.durationMs=k-$,e.items=t.slice(0,12).map(g=>({start:g.start-$,...g.durationMs!=null?{durationMs:g.durationMs}:{}})),e.memberIds=t.flatMap(g=>g.memberIds??[g.id]),e.title=`\xD7${s} ${e.title}`,t.some(g=>g.severity==="error")&&(e.severity="error"),e.kind==="view-update"?e.detail=[`${s} commits, ${r.length?`one per ${kt(r)}`:"back to back"}`,`avg ${u}ms \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 "):e.kind==="state-update"&&a&&n.detail?e.detail=`${s} updates in a row \xB7 wall ${c}ms \xB7 first ${a} \xB7 last ${n.detail}`:e.detail=[`${s} in a row \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 ")}R(st,"dt"),P(st,"ht"),v(st,"collapseRepeat");const tt=[],et=new Map,ft=new Set;for(let t=0;t<q.length;t++){if(ft.has(t))continue;const r=q[t];if(!Z(r)){tt.push(r);continue}const e=[t];for(let a=t+1;a<q.length;a++){const $=q[a];if($.group==="browser"){if(!Z($)||$.commitId!==r.commitId)break;e.push(a)}}for(const a of e)ft.add(a);const n=e.map(a=>q[a]),s=n.some(a=>a.kind!=="effect-run")?ot(n):nt(n);for(const a of n)a.id!==s.id&&et.set(a.id,s.id);tt.push(s)}if(et.size>0||tt.some(t=>t.kind==="view-update"||t.kind==="commit-effects")){q=tt;for(const t of q)for(;t.parent&&et.has(t.parent);)t.parent=et.get(t.parent)}{const t=new Map;for(const r of q)r.kind==="view-update"&&r.commitId&&!t.has(r.commitId)&&t.set(r.commitId,r);for(const r of q){if(r.kind!=="commit-effects"||r.parent||!r.commitId)continue;const e=t.get(r.commitId);e&&e.start<=r.start&&(r.parent=e.id)}}{const t=new Set(["state-update","fetch","fetch-start","fetch-done","fetch-error","flow-origin"]),r=q.map((u,c)=>u.group==="browser"?c:-1).filter(u=>u>=0),e=v(u=>`${u.kind}|${u.sig??u.title}`,"keyOf"),n=r.map(u=>e(q[u])),s=v((u,c,g)=>{for(let M=0;M<g;M++)if(n[u+M]!==n[c+M])return!1;return!0},"sameBlock"),a=v(u=>n[u].split("|")[0],"kindAt"),$=v(u=>{let c=0,g=1;for(let M=1;M<=4&&u+M<=n.length;M++){let A=1;for(;u+(A+1)*M<=n.length&&s(u,u+A*M,M);)A+=1;A>=3&&M*A>c*g&&(c=M,g=A)}return{k:c,r:g}},"bestBlockAt"),k=new Map;for(let u=0;u<n.length;){const{k:c,r:g}=$(u);if(c===0){u+=1;continue}const M=[...Array(c).keys()].find(b=>t.has(a(u+b)));if(M!==void 0&&M>0){const b=$(u+M);if(b.k===c&&b.r>=3&&b.r>=g-1){u+=M;continue}}const A=n.slice(u,u+c).map(b=>b.split("|")[0]).filter(b=>t.has(b));for(let b=0;b<c;b++){const L=[];for(let N=0;N<g;N++)L.push(q[r[u+b+N*c]]);st(L,A);for(const N of L.slice(1))k.set(N.id,L[0].id)}u+=c*g}if(k.size>0){q=q.filter(u=>!k.has(u.id));for(const u of q)for(;u.parent&&k.has(u.parent);)u.parent=k.get(u.parent)}}{const t=new Map(q.map(r=>[r.id,r]));for(const r of q){const e=new Set([r.id]);let n=r;for(;n?.parent;){if(e.has(n.parent)){n.parent=void 0;break}e.add(n.parent),n=t.get(n.parent)}}}const mt=v(t=>{const r=new Map;for(const n of q){if(!n.sig||I(n)!==t||n.kind==="server-request"||n.kind==="gateway-request"||n.group==="browser")continue;const s=`${n.parent??"root"}|${n.kind}|${n.sig}`,a=r.get(s);a?a.push(n):r.set(s,[n])}const e=new Map;for(const n of r.values()){if(n.length<3)continue;n.sort((c,g)=>c.start-g.start);const s=n[0];let a=!1;for(let c=0;c+1<n.length;c++)if(n[c+1].start<n[c].start+(n[c].durationMs??0)){a=!0;break}const $=s.start,k=Math.max(...n.map(c=>c.start+(c.durationMs??0))),u=n.reduce((c,g)=>c+(g.durationMs??0),0);s.count=n.length,s.parallel=a,s.avgMs=Math.round(u/n.length*10)/10,s.wallMs=k-$,s.durationMs=k-$,s.title=`\xD7${n.length} ${s.title.replace(/\s*\((?:\d+ rows?, )?\d+ms\)$/,"")}`,s.detail=`${s.sig} \xD7${n.length} ${a?"\u2016 parallel":"\u21BB sequential loop"} \xB7 avg ${s.avgMs}ms \xB7 wall ${s.wallMs}ms`,s.items=n.slice(0,12).map(c=>({start:c.start-$,...c.durationMs!=null?{durationMs:c.durationMs}:{}})),s.memberIds=n.flatMap(c=>c.memberIds??[c.id]),n.some(c=>c.severity==="error")&&(s.severity="error");for(const c of n.slice(1))e.set(c.id,s.id)}if(e.size!==0){q=q.filter(n=>!e.has(n.id));for(const n of q)for(;n.parent&&e.has(n.parent);)n.parent=e.get(n.parent)}},"aggregatePass");mt(!0),mt(!1);for(const t of q){if(!I(t))continue;const r=t.durationMs??0;if(r<40)continue;const e=q.filter(k=>k.parent===t.id&&(k.durationMs??0)>0).map(k=>[k.start,k.start+(k.durationMs??0)]).sort((k,u)=>k[0]-u[0]);let n=0,s=-1,a=-1;for(const[k,u]of e)k>a?(a>s&&(n+=a-s),s=k,a=u):u>a&&(a=u);a>s&&(n+=a-s);const $=Math.max(0,r-n);($>=50||$/r>=.7&&r>=40)&&(t.selfMs=$,t.detail=`\u26A0 cpu-heavy: ${$}ms self-time of ${r}ms${t.detail?" \xB7 "+t.detail:""}`)}return{events:q,...o?{sql:o}:{}}}R(buildFlowDetail,"buildFlowDetail"),P(buildFlowDetail,"buildFlowDetail"),v(buildFlowDetail,"buildFlowDetail");
|
package/lib/flows-config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var y=Object.defineProperty;var l=(o,e)=>y(o,"name",{value:e,configurable:!0});var w=Object.defineProperty,c=l((o,e)=>w(o,"name",{value:e,configurable:!0}),"c"),$=Object.defineProperty,p=c((o,e)=>$(o,"name",{value:e,configurable:!0}),"u");import{classifyFlow as h,categoryOfSegment as F}from"./flow-categories.js";import{DEFAULT_SEGMENT_OPTIONS as j,segmentFlow as O}from"./flow-segments.js";export const DEFAULT_FLOWS_CONFIG={categories:[],segments:{},problems:[]};const f=200,b=200,d=64,v=/^[A-Za-z0-9][A-Za-z0-9 ._:/-]*$/,A=["category","flowId","originType","origin","route","project"],S={phaseGapMs:[50,6e5],burstGapMs:[10,6e4],attachWindowMs:[0,6e4],maxSegmentEvents:[20,1e4],occurrenceSlackMs:[0,1e3]},g=p(o=>typeof o=="object"&&o!==null&&!Array.isArray(o),"isObj");function m(o,e){if(!g(o))return{problems:[`${e}: not an object`]};const s=[];for(const t of Object.keys(o))A.includes(t)||s.push(`${e}: unknown field "${t}" ignored`);const n=o.category;if(typeof n!="string"||n.trim()==="")return{problems:[...s,`${e}: "category" must be a non-empty string \u2014 rule dropped`]};const i=n.trim();if(i.length>d||!v.test(i))return{problems:[...s,`${e}: category "${i.slice(0,40)}" is not a usable name (letters, digits, space . _ : / -; up to ${d}) \u2014 rule dropped`]};const u={category:i};let a=0;for(const t of["flowId","originType","origin","route","project"]){const r=o[t];if(r!==void 0){if(typeof r!="string"||r===""||r.length>b)return{problems:[...s,`${e}: "${t}" must be a non-empty string of up to ${b} characters \u2014 rule dropped`]};u[t]=r,a+=1}}return a===0?{problems:[...s,`${e}: "${i}" has no match field (flowId, originType, origin, route or project) \u2014 rule dropped`]}:{rule:u,problems:s}}l(m,"d"),c(m,"w"),p(m,"parseRule");export function parseFlowsConfig(o){if(o==null)return DEFAULT_FLOWS_CONFIG;if(!g(o))return{...DEFAULT_FLOWS_CONFIG,problems:["lensmcp.flows must be an object \u2014 ignored"]};const e=[],s=[],n=o.categories;n!==void 0&&(Array.isArray(n)?(n.length>f&&e.push(`flows.categories has ${n.length} rules; only the first ${f} are used`),n.slice(0,f).forEach((a,t)=>{const r=m(a,`flows.categories[${t}]`);e.push(...r.problems),r.rule&&s.push(r.rule)})):e.push("flows.categories must be an array \u2014 ignored"));const i={},u=o.segments;if(u!==void 0)if(!g(u))e.push("flows.segments must be an object \u2014 ignored");else for(const[a,t]of Object.entries(u)){const r=S[a];if(!r){e.push(`flows.segments.${a}: unknown option ignored`);continue}if(typeof t!="number"||!Number.isFinite(t)||t<r[0]||t>r[1]){e.push(`flows.segments.${a}: ${JSON.stringify(t)} is outside ${r[0]}\u2013${r[1]}; using the default (${j[a]})`);continue}i[a]=t}return{categories:s,segments:i,problems:e}}l(parseFlowsConfig,"parseFlowsConfig"),c(parseFlowsConfig,"parseFlowsConfig"),p(parseFlowsConfig,"parseFlowsConfig");export function analyzeFlow(o,e=DEFAULT_FLOWS_CONFIG){const s=O(o,e.segments),n=h(o,s,e.categories),i={};for(const u of s.segments)i[u.id]=F(u,n,e.categories);return{segmentation:s,classification:n,segmentCategories:i}}l(analyzeFlow,"analyzeFlow"),c(analyzeFlow,"analyzeFlow"),p(analyzeFlow,"analyzeFlow");
|
package/lib/graph-from-events.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var y=Object.defineProperty;var l=(o,r)=>y(o,"name",{value:r,configurable:!0});var b=Object.defineProperty,p=l((o,r)=>b(o,"name",{value:r,configurable:!0}),"p"),I=Object.defineProperty,m=p((o,r)=>I(o,"name",{value:r,configurable:!0}),"l");function f(o){const r=o.raw??null,s=r?.kind,i=o.context,a={id:o.id,parentTraceNodeId:i.causedByNodeId??i.originNodeId,lifecycle:"completed",context:i,startTime:o.timestamp,attributes:{...r??{}}};if(o.source==="react"&&s==="render"){const e=r;return{parentAxis:"render",node:{...a,type:"render",logicalId:e.render?.componentLogicalId,instanceId:e.render?.componentInstanceId,name:`render ${e.render?.componentName??"?"}`,durationMs:e.render?.actualDurationMs}}}if(o.source==="valtio"&&s==="state-update"){const e=r;return{parentAxis:"state",node:{...a,type:"state-update",logicalId:e.update?.storeId,name:`${e.update?.storeId??"?"}.${e.update?.path??"?"}`}}}if(o.source==="nestjs"&&s==="server-request"){const e=r;return{parentAxis:"backend",node:{...a,type:"server-request",name:`${e.request?.method??"?"} ${e.request?.route??"?"}`,durationMs:e.request?.durationMs}}}if(s==="db-query"){const e=r,c=[e.op,e.table].filter(Boolean).join(" ")||(e.name??"query");return{parentAxis:"backend",node:{...a,type:"db-query",logicalId:e.table?`db:${e.op??"query"}:${e.table}`:void 0,name:e.error?`${c} (failed)`:c,durationMs:e.durationMs}}}if(s==="loop")return{parentAxis:"performance",node:{...a,type:"loop",name:"loop",durationMs:r.loop?.durationMs}};if(o.source==="client-runtime"&&s==="user-action"){const e=r;return{parentAxis:"caused",node:{...a,type:"ui-event",logicalId:e.origin?.nodeId,name:e.origin?.label??o.title}}}}l(f,"m"),p(f,"f"),m(f,"eventToNode");export function buildGraphFromEvents(o,r){const s=[...r].sort((n,t)=>n.timestamp-t.timestamp),i=[];for(const n of s){const t=f(n);t&&(o.addNode(t.node),i.push(t))}let a=0;const e=m((n,t,d,u)=>{const g={id:`${d}:${n}->${t}`,from:n,to:t,axis:d,type:u,timestamp:o.getNode(t)?.startTime??0};o.addEdge(g),a++},"addEdge");for(const n of i){const t=n.node.context.causedByNodeId;t&&o.getNode(t)&&e(t,n.node.id,n.parentAxis??"caused","caused-by")}const c=new Map;for(const n of i){const t=n.node.context.flowId;if(!t)continue;let d=c.get(t);d||(d=[],c.set(t,d)),d.push(n)}for(const n of c.values())for(let t=1;t<n.length;t++){const d=n[t-1].node,u=n[t].node;u.context.causedByNodeId!==d.id&&e(d.id,u.id,"caused","flow-sequence")}return{nodeCount:i.length,edgeCount:a}}l(buildGraphFromEvents,"buildGraphFromEvents"),p(buildGraphFromEvents,"buildGraphFromEvents"),m(buildGraphFromEvents,"buildGraphFromEvents");
|
package/lib/graph-store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var w=Object.defineProperty;var l=(
|
|
1
|
+
"use strict";var w=Object.defineProperty;var l=(d,t)=>w(d,"name",{value:t,configurable:!0});var I=Object.defineProperty,y=l((d,t)=>I(d,"name",{value:t,configurable:!0}),"l"),b=Object.defineProperty,m=y((d,t)=>b(d,"name",{value:t,configurable:!0}),"l");const B=4,M=1e3;export class GraphStore{static{l(this,"GraphStore")}static{y(this,"GraphStore")}static{m(this,"GraphStore")}constructor(){this.nodes=new Map,this.edges=new Map,this.byParent=new Map,this.byFlow=new Map,this.byLogical=new Map,this.byInstance=new Map,this.byRequest=new Map,this.outByAxis=new Map,this.inByAxis=new Map}addNode(t){this.nodes.set(t.id,t),t.parentTraceNodeId&&this.addToIndex(this.byParent,t.parentTraceNodeId,t.id),t.context.flowId&&this.addToIndex(this.byFlow,t.context.flowId,t.id),t.logicalId&&this.addToIndex(this.byLogical,t.logicalId,t.id),t.instanceId&&this.addToIndex(this.byInstance,t.instanceId,t.id),t.context.requestId&&this.addToIndex(this.byRequest,t.context.requestId,t.id)}updateNode(t,e){const i=this.nodes.get(t);if(!i)throw new Error(`Unknown node: ${t}`);const s={...i,...e,id:i.id};return this.nodes.set(t,s),s}getNode(t){return this.nodes.get(t)}addEdge(t){this.edges.set(t.id,t);let e=this.outByAxis.get(t.axis);e||(e=new Map,this.outByAxis.set(t.axis,e)),this.addToIndex(e,t.from,t.id);let i=this.inByAxis.get(t.axis);i||(i=new Map,this.inByAxis.set(t.axis,i)),this.addToIndex(i,t.to,t.id)}getEdge(t){return this.edges.get(t)}childrenOf(t){return this.materialiseNodes(this.byParent.get(t))}nodesInFlow(t){return this.materialiseNodes(this.byFlow.get(t))}nodesByLogical(t){return this.materialiseNodes(this.byLogical.get(t))}nodesByInstance(t){return this.materialiseNodes(this.byInstance.get(t))}nodesByRequest(t){return this.materialiseNodes(this.byRequest.get(t))}traverse(t){const e=this.nodes.get(t.from);if(!e)return{nodes:[],edges:[]};const i=Array.isArray(t.lens)?t.lens:[t.lens],s=t.direction??"both",x=t.depth??4,p=t.maxNodes??1e3,o=new Set,g=new Set,c=[{id:e.id,d:0}];for(;c.length&&!(o.size>=p);){const{id:n,d:u}=c.shift();if(!o.has(n)&&(o.add(n),!(u>=x)))for(const f of i){if(s==="out"||s==="both"){const a=this.outByAxis.get(f)?.get(n);if(a)for(const r of a){g.add(r);const h=this.edges.get(r);o.has(h.to)||c.push({id:h.to,d:u+1})}}if(s==="in"||s==="both"){const a=this.inByAxis.get(f)?.get(n);if(a)for(const r of a){g.add(r);const h=this.edges.get(r);o.has(h.from)||c.push({id:h.from,d:u+1})}}}}return{nodes:this.materialiseNodes(o),edges:[...g].map(n=>this.edges.get(n)).filter(n=>!!n)}}nodeCount(){return this.nodes.size}edgeCount(){return this.edges.size}addToIndex(t,e,i){let s=t.get(e);s||(s=new Set,t.set(e,s)),s.add(i)}materialiseNodes(t){if(!t)return[];const e=[];for(const i of t){const s=this.nodes.get(i);s&&e.push(s)}return e}}
|
package/lib/headless-flow.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var l=Object.defineProperty;var t=(e,s)=>l(e,"name",{value:s,configurable:!0});var r=Object.defineProperty,o=t((e,s)=>r(e,"name",{value:s,configurable:!0}),"s"),n=Object.defineProperty,a=o((e,s)=>n(e,"name",{value:s,configurable:!0}),"t");export const HEADLESS_FLOWS_ENV="LENSMCP_HEADLESS_FLOWS";export function headlessFlowsEnabled(e=process.env){return!["0","false","off","no"].includes((e[HEADLESS_FLOWS_ENV]??"").trim().toLowerCase())}t(headlessFlowsEnabled,"headlessFlowsEnabled"),o(headlessFlowsEnabled,"headlessFlowsEnabled"),a(headlessFlowsEnabled,"headlessFlowsEnabled");export const HEADLESS_REQUEST_FLOW_PREFIX="api:",HEADLESS_JOB_FLOW_PREFIX="job:";export function headlessFlowId(e){return`${HEADLESS_REQUEST_FLOW_PREFIX}${e}`}t(headlessFlowId,"headlessFlowId"),o(headlessFlowId,"headlessFlowId"),a(headlessFlowId,"headlessFlowId");export function headlessJobFlowId(e,s){return`${HEADLESS_JOB_FLOW_PREFIX}${e}#${s??"?"}`}t(headlessJobFlowId,"headlessJobFlowId"),o(headlessJobFlowId,"headlessJobFlowId"),a(headlessJobFlowId,"headlessJobFlowId");export function isHeadlessFlowId(e){return e.startsWith(HEADLESS_REQUEST_FLOW_PREFIX)||e.startsWith(HEADLESS_JOB_FLOW_PREFIX)}t(isHeadlessFlowId,"isHeadlessFlowId"),o(isHeadlessFlowId,"isHeadlessFlowId"),a(isHeadlessFlowId,"isHeadlessFlowId");const i=/^\/(?:[^/?#]+\/)*(?:health|healthz|health-check|healthcheck|ready|readyz|readiness|live|livez|liveness|ping|metrics|favicon\.ico)\/?(?:[?#].*)?$/i;export function isProbePath(e){return e?i.test(e)||e.startsWith("/__lensmcp/"):!1}t(isProbePath,"isProbePath"),o(isProbePath,"isProbePath"),a(isProbePath,"isProbePath");
|
package/lib/http-exchange.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var s=Object.defineProperty;var r=(t,e)=>s(t,"name",{value:e,configurable:!0});var h=Object.defineProperty,a=r((t,e)=>h(t,"name",{value:e,configurable:!0}),"n"),p=Object.defineProperty,c=a((t,e)=>p(t,"name",{value:e,configurable:!0}),"r");import*as l from"node:fs";import{dirname as x,join as i}from"node:path";export const HTTP_EXCHANGE_DIR="http",HTTP_EXCHANGE_PLACES=["calls","in","hops"];export function exchangePlace(t){return t.side==="ingress"?"in":/(^|\.)localhost$/i.test(t.host)?"hops":"calls"}r(exchangePlace,"exchangePlace"),a(exchangePlace,"exchangePlace"),c(exchangePlace,"exchangePlace");const g=/^hx_[0-9a-z]{8,40}$/;export const isHttpExchangeId=c(t=>typeof t=="string"&&g.test(t),"isHttpExchangeId");export function httpExchangeDir(t,e="calls"){const n=i(x(t),HTTP_EXCHANGE_DIR);return e==="calls"?n:i(n,e)}r(httpExchangeDir,"httpExchangeDir"),a(httpExchangeDir,"httpExchangeDir"),c(httpExchangeDir,"httpExchangeDir");export function httpExchangeFile(t,e,n="calls"){if(!isHttpExchangeId(e))throw new Error("invalid http exchange id");return i(httpExchangeDir(t,n),`${e}.json`)}r(httpExchangeFile,"httpExchangeFile"),a(httpExchangeFile,"httpExchangeFile"),c(httpExchangeFile,"httpExchangeFile");export function readHttpExchange(t,e){if(isHttpExchangeId(e))for(const n of HTTP_EXCHANGE_PLACES)try{const o=JSON.parse(l.readFileSync(httpExchangeFile(t,e,n),"utf8"));if(o&&o.schemaVersion===1&&o.id===e)return o}catch{}}r(readHttpExchange,"readHttpExchange"),a(readHttpExchange,"readHttpExchange"),c(readHttpExchange,"readHttpExchange");
|
package/lib/http-shape.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var j=Object.defineProperty;var m=(t,n)=>j(t,"name",{value:n,configurable:!0});var k=Object.defineProperty,p=m((t,n)=>k(t,"name",{value:n,configurable:!0}),"m"),S=Object.defineProperty,l=p((t,n)=>S(t,"name",{value:n,configurable:!0}),"a");import{isSecretParam as M}from"./redact.js";const x=6,h=60,F=4,O=[["uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i],["ulid",/^[0-9A-HJKMNP-TV-Z]{26}$/],["date-time",/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/],["date",/^\d{4}-\d{2}-\d{2}$/],["email",/^[^\s@]+@[^\s@]+\.[^\s@]+$/],["url",/^https?:\/\/\S+$/i],["jwt",/^eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$/],["int",/^-?\d{1,30}$/],["decimal",/^-?\d+\.\d+$/],["phone",/^\+\d{7,15}$/],["hex",/^[0-9a-f]{16,}$/i],["base64",/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[A-Za-z0-9+/]{32,}={0,2}$/]];export function stringFormat(t){for(const[n,e]of O)if(e.test(t))return n}m(stringFormat,"stringFormat"),p(stringFormat,"stringFormat"),l(stringFormat,"stringFormat");const $=l(t=>t.length>64||/\s/.test(t)||stringFormat(t)!==void 0&&!/^[a-z]/i.test(t)||/@/.test(t)||/^[0-9a-f]{8}-/i.test(t),"dataKey");export function shapeOf(t,n=0,e=!1){if(t==null)return{t:"null"};if(typeof t=="boolean")return{t:"bool"};if(typeof t=="number")return Number.isInteger(t)?{t:"num",int:!0}:{t:"num"};if(typeof t=="bigint")return{t:"num",int:!0};if(typeof t=="string"){const r=stringFormat(t);return{t:"str",...r?{f:r}:{},...e?{}:{max:t.length}}}if(t instanceof Date)return{t:"str",f:"date-time"};if(n>=x)return Array.isArray(t)?{t:"arr",n:[t.length,t.length]}:{t:"obj",fields:[]};if(Array.isArray(t)){const r=t.slice(0,20).map(a=>shapeOf(a,n+1,e)).reduce((a,i)=>a?mergeShapes(a,i):i,void 0);return{t:"arr",n:[t.length,t.length],...r?{of:r}:{}}}if(typeof t=="object"){const r=Object.entries(t).filter(([,a])=>typeof a!="function");if(r.length&&r.some(([a])=>$(a))){const a=r.slice(0,20).map(([,s])=>shapeOf(s,n+1,e)).reduce((s,c)=>s?mergeShapes(s,c):c,void 0),i=r.map(([s])=>stringFormat(s)).find(Boolean);return{t:"map",n:[r.length,r.length],...i?{key:i}:{},...a?{of:a}:{}}}return{t:"obj",fields:r.slice(0,h).map(([a,i])=>{const s=M(a);return{...shapeOf(i,n+1,e||s),name:a,...s?{cred:!0}:{}}}),...r.length>h?{more:r.length-h}:{}}}return{t:"null"}}m(shapeOf,"shapeOf"),p(shapeOf,"shapeOf"),l(shapeOf,"shapeOf");const v=l((t,n)=>t.t===n.t,"same"),N=new Set(["null","bool","num","str","arr","obj","map","any"]);export function isShape(t,n=0){if(!t||typeof t!="object"||n>x*2)return!1;const e=t;return typeof e.t!="string"||!N.has(e.t)?!1:e.t==="obj"?Array.isArray(e.fields)&&e.fields.every(r=>typeof r?.name=="string"&&isShape(r,n+1)):e.t==="any"?Array.isArray(e.of)&&e.of.every(r=>isShape(r,n+1)):e.t==="arr"||e.t==="map"?Array.isArray(e.n)&&(e.of===void 0||isShape(e.of,n+1)):!0}m(isShape,"isShape"),p(isShape,"isShape"),l(isShape,"isShape");export function fieldShape(t){const n={...t};return delete n.name,delete n.opt,delete n.cred,n}m(fieldShape,"fieldShape"),p(fieldShape,"fieldShape"),l(fieldShape,"fieldShape");export function mergeShapes(t,n){if(t.t==="any"||n.t==="any"){const e=[...t.t==="any"?t.of:[t],...n.t==="any"?n.of:[n]],r=[];for(const a of e){const i=r.findIndex(s=>v(s,a));i>=0?r[i]=mergeShapes(r[i],a):r.push(a)}return r.length===1?r[0]:{t:"any",of:r.slice(0,F)}}if(!v(t,n))return{t:"any",of:[t,n]};switch(t.t){case"num":return t.int&&n.int?t:{t:"num"};case"str":{const e=n,r=t.f===e.f?t.f:void 0;return{t:"str",...r?{f:r}:{},...t.max!==void 0||e.max!==void 0?{max:Math.max(t.max??0,e.max??0)}:{}}}case"arr":{const e=n,r=t.of&&e.of?mergeShapes(t.of,e.of):t.of??e.of;return{t:"arr",n:[Math.min(t.n[0],e.n[0]),Math.max(t.n[1],e.n[1])],...r?{of:r}:{}}}case"map":{const e=n,r=t.of&&e.of?mergeShapes(t.of,e.of):t.of??e.of;return{t:"map",n:[Math.min(t.n[0],e.n[0]),Math.max(t.n[1],e.n[1])],...t.key===e.key&&t.key?{key:t.key}:{},...r?{of:r}:{}}}case"obj":{const e=n,r=new Map(t.fields.map(c=>[c.name,c])),a=new Map(e.fields.map(c=>[c.name,c])),i=[...new Set([...r.keys(),...a.keys()])].slice(0,h).map(c=>{const f=r.get(c),u=a.get(c);return{...f&&u?mergeShapes(fieldShape(f),fieldShape(u)):fieldShape(f??u),name:c,...!f||!u||f.opt||u.opt?{opt:!0}:{},...f?.cred||u?.cred?{cred:!0}:{}}}),s=Math.max(t.more??0,e.more??0);return{t:"obj",fields:i,...s?{more:s}:{}}}default:return t}}m(mergeShapes,"mergeShapes"),p(mergeShapes,"mergeShapes"),l(mergeShapes,"mergeShapes");export function shapeText(t,n=0){switch(t.t){case"null":return"null";case"bool":return"boolean";case"num":return t.int?"int":"number";case"str":return t.f?`string(${t.f})`:"string";case"arr":return`[${t.n[0]===t.n[1]?t.n[0]:`${t.n[0]}..${t.n[1]}`}]${t.of?` ${shapeText(t.of,n+1)}`:""}`;case"map":return`map<${t.key??"string"}, ${t.of?shapeText(t.of,n+1):"?"}> (${t.n[0]===t.n[1]?t.n[0]:`${t.n[0]}..${t.n[1]}`} entries)`;case"any":return t.of.map(e=>shapeText(e,n)).join(" | ");case"obj":return`{ ${t.fields.map(e=>`${e.name}${e.opt?"?":""}${e.cred?" (credential-named)":""}: ${shapeText(fieldShape(e),n+1)}`).join(", ")}${t.more?`, \u2026 ${t.more} more`:""} }`}}m(shapeText,"shapeText"),p(shapeText,"shapeText"),l(shapeText,"shapeText");const o=l((t,n)=>{const e=t[n]??t[n.toLowerCase()];return e===void 0?void 0:Array.isArray(e)?e.join(", "):String(e)},"h"),y=l(t=>t?.split(";")[0]?.trim().toLowerCase()||void 0,"media");export function requestFacts(t,n,e){const r=o(t,"authorization")?.split(/\s+/)[0],a=o(t,"cookie"),i=Number(o(t,"content-length")),s=n?Object.keys(n).filter(f=>!$(f)).slice(0,30):[],c=e?Object.keys(e).slice(0,10):[];return{...y(o(t,"content-type"))?{contentType:y(o(t,"content-type"))}:{},...o(t,"accept")?{accept:o(t,"accept").slice(0,80)}:{},...r?{scheme:/^[A-Za-z][\w-]{1,20}$/.test(r)?r:"other"}:{},...a?{cookies:a.split(";").filter(f=>f.includes("=")).length}:{},...o(t,"if-match")?{ifMatch:!0}:{},...o(t,"if-none-match")?{ifNoneMatch:!0}:{},...o(t,"idempotency-key")?{idempotencyKey:!0}:{},...o(t,"origin")?{origin:!0}:{},...Number.isFinite(i)&&i>0?{bytes:i}:{},...s.length?{query:s}:{},...c.length?{params:c}:{}}}m(requestFacts,"requestFacts"),p(requestFacts,"requestFacts"),l(requestFacts,"requestFacts");export function responseFacts(t,n){const e=o(t,"etag"),r=Number(o(t,"content-length")),a=t["set-cookie"],i=(Array.isArray(a)?a:a!==void 0?[String(a)]:[]).slice(0,10).map(c=>{const[f="",...u]=c.split(";").map(g=>g.trim()),d=l(g=>u.find(A=>A.toLowerCase().startsWith(g)),"a"),w=d("samesite")?.split("=")[1],b=d("path=")?.slice(5);return{name:f.split("=")[0].slice(0,40),...d("secure")?{secure:!0}:{},...d("httponly")?{httpOnly:!0}:{},...w?{sameSite:w}:{},...d("domain=")?{domain:!0}:{},...b?{path:b}:{},...d("max-age=")?{maxAge:!0}:{},...d("expires=")?{expires:!0}:{}}}),s=o(t,"access-control-allow-origin");return{...y(o(t,"content-type"))?{contentType:y(o(t,"content-type"))}:{},...Number.isFinite(r)&&r>=0&&o(t,"content-length")!==void 0?{bytes:r}:{},...o(t,"cache-control")?{cacheControl:o(t,"cache-control").slice(0,120)}:{},...e?{etag:e.startsWith("W/")?"weak":"strong"}:{},...o(t,"last-modified")?{lastModified:!0}:{},...o(t,"location")?{location:!0}:{},...o(t,"vary")?{vary:o(t,"vary").slice(0,120)}:{},...o(t,"retry-after")?{retryAfter:!0}:{},...o(t,"www-authenticate")?{wwwAuthenticate:o(t,"www-authenticate").split(/\s+/)[0].slice(0,20)}:{},...o(t,"allow")?{allow:o(t,"allow").slice(0,80)}:{},...i.length?{cookies:i}:{},...s?{cors:{origin:s==="*"?"*":n&&s===n?"echoed":"fixed",...o(t,"access-control-allow-credentials")==="true"?{creds:!0}:{},...o(t,"access-control-allow-methods")?{methods:o(t,"access-control-allow-methods").slice(0,80)}:{},...o(t,"access-control-allow-headers")?{headers:o(t,"access-control-allow-headers").slice(0,120)}:{}}}:{},...o(t,"strict-transport-security")?{hsts:!0}:{},...o(t,"x-content-type-options")?{nosniff:!0}:{},...o(t,"x-powered-by")||o(t,"server")?{poweredBy:!0}:{},...o(t,"deprecation")?{deprecation:!0}:{},...o(t,"sunset")?{sunset:!0}:{},...o(t,"ratelimit")||o(t,"ratelimit-policy")||o(t,"x-ratelimit-limit")?{rateLimit:!0}:{},...o(t,"x-request-id")?{requestId:!0}:{}}}m(responseFacts,"responseFacts"),p(responseFacts,"responseFacts"),l(responseFacts,"responseFacts");
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A cache key's family — one rule for the Redis tap (its flood bucket per command shape) and the cache catalog (its key
|
|
3
|
+
* patterns), so both group the same keys. Dependency-free: the tap imports it as `@lensmcp/core/key-pattern`.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* A key with its ids folded to `*` — `bull:product-analysis-<uuid>:<uuid>` → `bull:product-analysis-*:*`. An id is
|
|
7
|
+
* a UUID, a whole segment of 16+ id characters with a digit and a letter (a nanoid), a run of 8+ hex characters
|
|
8
|
+
* with a digit in it, or a number of 2+ digits; a word stays a word (`facade`, `product-analysis`).
|
|
9
|
+
*/
|
|
10
|
+
export declare function foldKeyPattern(key: string): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var f=Object.defineProperty;var r=(e,a)=>f(e,"name",{value:a,configurable:!0});var c=Object.defineProperty,t=r((e,a)=>c(e,"name",{value:a,configurable:!0}),"r"),l=Object.defineProperty,n=t((e,a)=>l(e,"name",{value:a,configurable:!0}),"e");const o=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;export function foldKeyPattern(e){return e.replace(o,"*").replace(/(?<=^|[:=/])(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{16,}(?=$|[:=/])/g,"*").replace(/(?<![A-Za-z])(?=[0-9a-f]*\d)[0-9a-f]{8,}(?![A-Za-z])/gi,"*").replace(/(?<![A-Za-z0-9])\d{2,}(?![A-Za-z0-9])/g,"*").replace(/\*(?:[_-]?\*)+/g,"*")}r(foldKeyPattern,"foldKeyPattern"),t(foldKeyPattern,"foldKeyPattern"),n(foldKeyPattern,"foldKeyPattern");
|
package/lib/lens-dir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var t=Object.defineProperty;var r=(e,i)=>t(e,"name",{value:i,configurable:!0});var o=Object.defineProperty,n=r((e,i)=>o(e,"name",{value:i,configurable:!0}),"i"),s=Object.defineProperty,a=n((e,i)=>s(e,"name",{value:i,configurable:!0}),"i");export const LENS_SHARED_DIRS=["sql-review","route-review","flow-review","ui-review","cache-review","queue-review"];export function lensGitignoreLines(e="**/"){return[`${e}.lensmcp/*`,...LENS_SHARED_DIRS.map(i=>`!${e}.lensmcp/${i}/`)]}r(lensGitignoreLines,"lensGitignoreLines"),n(lensGitignoreLines,"lensGitignoreLines"),a(lensGitignoreLines,"lensGitignoreLines");
|
package/lib/lens-events.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var p=Object.defineProperty;var
|
|
2
|
-
`).join("")))}
|
|
1
|
+
"use strict";var p=Object.defineProperty;var r=(e,s)=>p(e,"name",{value:s,configurable:!0});var m=Object.defineProperty,o=r((e,s)=>m(e,"name",{value:s,configurable:!0}),"t"),d=Object.defineProperty,n=o((e,s)=>d(e,"name",{value:s,configurable:!0}),"o");import{appendFileSync as v,closeSync as S,mkdirSync as y,openSync as f,renameSync as I,statSync as N,unlinkSync as _}from"node:fs";import{dirname as g,join as b}from"node:path";import{ERROR_DISMISSED as a,ERROR_RESTORED as c,LENS_EVENT_SOURCE as R}from"@lensmcp/protocol-types";import{rotateBusFile as F}from"./bus-rotation.js";import{ulid as x}from"./ulid.js";export function lensEventFile(e=process.env,s=process.cwd()){return e.LENSMCP_EVENT_FILE??b(s,".lensmcp","events.jsonl")}r(lensEventFile,"lensEventFile"),o(lensEventFile,"lensEventFile"),n(lensEventFile,"lensEventFile");const l=n((e,s,t,i,E)=>({id:x(),sessionId:e,timestamp:s,source:R,category:"runtime",severity:"info",context:{sessionId:e},fingerprint:t,title:i,raw:E}),"lensEvent");export function dismissalEvent(e,s){return l(s,e.until,`${a}:${e.groupId}`,`error dismissed: ${e.title??e.groupId}`,{kind:a,groupId:e.groupId,until:e.until,eventIds:e.eventIds,...e.by?{by:e.by}:{},...e.reason?{reason:e.reason}:{},...e.title?{title:e.title}:{}})}r(dismissalEvent,"dismissalEvent"),o(dismissalEvent,"dismissalEvent"),n(dismissalEvent,"dismissalEvent");export function restoralEvent(e,s,t){return l(s,t,`${c}:${e}`,"error restored",{kind:c,groupId:e})}r(restoralEvent,"restoralEvent"),o(restoralEvent,"restoralEvent"),n(restoralEvent,"restoralEvent");const u=n((e,s,t)=>{const i=Number(process.env[e]);return Number.isFinite(i)&&t(i)?i:s},"envNumber");export function appendBusEvents(e,s){s.length!==0&&(y(g(e),{recursive:!0}),F(e,{maxBytes:u("LENSMCP_EVENT_MAX_BYTES",50*1024*1024,t=>t>0),maxFiles:u("LENSMCP_EVENT_MAX_FILES",5,t=>t>=1&&t<=20),fs:{statSync:N,renameSync:I,unlinkSync:_,openSync:f,closeSync:S}}),v(e,s.map(t=>JSON.stringify(t)+`
|
|
2
|
+
`).join("")))}r(appendBusEvents,"appendBusEvents"),o(appendBusEvents,"appendBusEvents"),n(appendBusEvents,"appendBusEvents");
|
package/lib/patterns.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var y=Object.defineProperty;var u=(o,n)=>y(o,"name",{value:n,configurable:!0});var j=Object.defineProperty,p=u((o,n)=>j(o,"name",{value:n,configurable:!0}),"u"),v=Object.defineProperty,f=p((o,n)=>v(o,"name",{value:n,configurable:!0}),"l");export function detectDbInLoop(o,n={}){const s=n.threshold??5,i=[];for(const t of o){const e=t.raw??null;if(e?.kind!=="loop"||!e.loop)continue;const a=e.loop.dbCallsInsideLoop??0;a>s&&i.push({kind:"db-in-loop",severity:"warning",title:`${a} DB calls inside a loop (${e.loop.iterations??"?"} iterations)`,evidence:[t.id],details:{dbCallsInsideLoop:a,iterations:e.loop.iterations,durationMs:e.loop.durationMs,threshold:s},detectedAt:t.timestamp})}return i}u(detectDbInLoop,"detectDbInLoop"),p(detectDbInLoop,"detectDbInLoop"),f(detectDbInLoop,"detectDbInLoop");const I=new Set(["egress","db-query","redis-op","ai-call"]);function w(o){const n=o.raw??null;if(!n||typeof n.kind!="string"||!I.has(n.kind))return;const s=typeof n.durationMs=="number"?n.durationMs:void 0;if(s===void 0)return;const i=typeof n.startedAt=="number"?n.startedAt:o.timestamp-s,t=o.context??{};return{id:o.id,start:i,end:i+s,label:o.title,...typeof t.requestId=="string"?{requestId:t.requestId}:{},...typeof n.project=="string"?{project:n.project}:typeof t.projectName=="string"?{project:t.projectName}:{}}}u(w,"b"),p(w,"M"),f(w,"timedCall");function M(o){const n=o.raw??null,s=n?.kind==="span"?n.span:void 0;if(!s||typeof s.name!="string"||s.name.startsWith("nest.request "))return;const i=typeof s.durationMs=="number"?s.durationMs:void 0;if(i===void 0||i<=0)return;const t=typeof s.startTime=="number"?s.startTime:o.timestamp-i,e=o.context??{};return{id:o.id,start:t,end:t+i,label:s.name,...typeof e.requestId=="string"?{requestId:e.requestId}:{},...typeof n?.project=="string"?{project:n.project}:typeof e.projectName=="string"?{project:e.projectName}:{}}}u(M,"g"),p(M,"b"),f(M,"timedSpan");export function abandonedAwaitOf(o,n,s={}){const i=s.thresholdMs??250,t=w(o);if(!t||!t.requestId||t.end-t.start<i)return;let e;for(const r of n){const d=M(r);!d||d.requestId!==t.requestId||d.project!==void 0&&t.project!==void 0&&d.project!==t.project||d.start>t.start||d.end<=t.start||(!e||d.start>e.start||d.start===e.start&&d.end<e.end)&&(e=d)}if(!e)return;const a=Math.round(t.end-e.end);if(!(a<i))return{kind:"abandoned-await",severity:"warning",title:`${e.label} ended ${a}ms before a call it started had finished (${t.label})`,evidence:[e.id,t.id],details:{span:e.label,call:t.label,ranOnMs:a,spanMs:Math.round(e.end-e.start),callMs:Math.round(t.end-t.start),thresholdMs:i,...t.project?{project:t.project}:{}},detectedAt:o.timestamp}}u(abandonedAwaitOf,"abandonedAwaitOf"),p(abandonedAwaitOf,"abandonedAwaitOf"),f(abandonedAwaitOf,"abandonedAwaitOf");export function detectAbandonedAwait(o,n={}){const s=[];for(const i of o){const t=abandonedAwaitOf(i,o,n);t&&s.push(t)}return s}u(detectAbandonedAwait,"detectAbandonedAwait"),p(detectAbandonedAwait,"detectAbandonedAwait"),f(detectAbandonedAwait,"detectAbandonedAwait");export function detectNPlusOne(o,n={}){const s=n.threshold??3,i=new Map;for(const e of o){const a=e.raw??null;if(a?.kind!=="db-query"||!a.query?.signature)continue;const r=a.query.signature;let d=i.get(r);d||(d=[],i.set(r,d)),d.push(e)}const t=[];for(const[e,a]of i)a.length>=s&&t.push({kind:"n+1-query",severity:"warning",title:`Query repeated ${a.length}\xD7 \u2014 likely N+1`,evidence:a.map(r=>r.id),details:{signature:e,count:a.length,threshold:s},detectedAt:a[a.length-1].timestamp});return t}u(detectNPlusOne,"detectNPlusOne"),p(detectNPlusOne,"detectNPlusOne"),f(detectNPlusOne,"detectNPlusOne");export function detectRenderStorm(o,n={}){const s=n.threshold??5,i=n.windowMs??250,t=new Map;for(const a of o){if(a.source!=="react")continue;const r=a.raw??null;if(r?.kind!=="render"||!r.render?.componentInstanceId)continue;const d=r.render.componentInstanceId;let c=t.get(d);c||(c=[],t.set(d,c)),c.push(a)}const e=[];for(const[a,r]of t){r.sort((c,m)=>c.timestamp-m.timestamp);let d=0;for(let c=0;c<r.length;c++){for(;r[c].timestamp-r[d].timestamp>i;)d++;const m=c-d+1;if(m>s){const l=r.slice(d,c+1),h=l[0].raw.render?.componentName??a;e.push({kind:"render-storm",severity:"warning",title:`${h} rendered ${m}\xD7 in ${i}ms`,evidence:l.map(b=>b.id),details:{componentInstanceId:a,count:m,windowMs:i,threshold:s},detectedAt:l[l.length-1].timestamp});break}}}return e}u(detectRenderStorm,"detectRenderStorm"),p(detectRenderStorm,"detectRenderStorm"),f(detectRenderStorm,"detectRenderStorm");export function findSlowPath(o,n,s){const i=new Map,t=new Set;function e(r){const d=i.get(r);if(d)return d;if(t.has(r))return{path:[r],totalDurationMs:s(r)};t.add(r);const c=s(r),m=n.get(r)??[];let l;for(const b of m){const g=e(b);(!l||g.totalDurationMs>l.totalDurationMs)&&(l=g)}t.delete(r);const h=l?{path:[r,...l.path],totalDurationMs:c+l.totalDurationMs}:{path:[r],totalDurationMs:c};return i.set(r,h),h}u(e,"e"),p(e,"e"),f(e,"best");let a={path:[],totalDurationMs:0};for(const r of o){const d=e(r);d.totalDurationMs>a.totalDurationMs&&(a=d)}return a}u(findSlowPath,"findSlowPath"),p(findSlowPath,"findSlowPath"),f(findSlowPath,"findSlowPath");
|
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");
|
package/lib/redact.d.ts
CHANGED
|
@@ -65,6 +65,12 @@ export declare const MAX_URL_CHARS = 1024;
|
|
|
65
65
|
* (issues/closed/codex-security-40).
|
|
66
66
|
*/
|
|
67
67
|
export declare function isSecretParam(name: string): boolean;
|
|
68
|
+
/**
|
|
69
|
+
* Is this cache key where an app keeps a credential — a session store (`sess:<id>`), a one-time code (`otp:user:7`), a
|
|
70
|
+
* reset or magic-link token (`reset:<token>`)? Its value is a secret whatever its shape (a session's JSON, six digits),
|
|
71
|
+
* which no value pattern catches. Judged per segment (`:`, `/`, `{`, `}`, `#`), each as a name.
|
|
72
|
+
*/
|
|
73
|
+
export declare function isSecretCacheKey(key: string): boolean;
|
|
68
74
|
/**
|
|
69
75
|
* Strip credentials from a URL — userinfo, then any query OR fragment
|
|
70
76
|
* parameter whose NAME looks like a credential — preserving every other byte
|
|
@@ -107,6 +113,13 @@ export declare function redactUrl(url: string): string;
|
|
|
107
113
|
* comes back byte-identical).
|
|
108
114
|
*/
|
|
109
115
|
export declare function redactText(text: string): string;
|
|
116
|
+
/**
|
|
117
|
+
* Every secret SHAPE — what {@link redactText} knows (URLs, headers, JWTs) plus the keys, PEM private keys and
|
|
118
|
+
* `"password": "…"` / `token=…` pairs a body, a prompt or a typed value is liable to hold. For text that never crosses
|
|
119
|
+
* the bus redactor: the side files a tap writes (AI calls, exchanges, SQL values) and what an agent reads of a
|
|
120
|
+
* recording. Tuned for precision, as `redactText` is; it cannot remove personal data.
|
|
121
|
+
*/
|
|
122
|
+
export declare function redactSecretText(text: string): string;
|
|
110
123
|
/**
|
|
111
124
|
* Bound a string, marking what was removed. Marker text matches
|
|
112
125
|
* `@lensmcp/storage`'s `clampEventRaw` so the two truncations read the same in
|
package/lib/redact.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var v=Object.defineProperty;var f=(e,t)=>v(e,"name",{value:t,configurable:!0});var I=Object.defineProperty,u=f((e,t)=>I(e,"name",{value:t,configurable:!0}),"f"),P=Object.defineProperty,l=u((e,t)=>P(e,"name",{value:t,configurable:!0}),"a");export const REDACTED="REDACTED",MAX_TITLE_CHARS=300,MAX_MESSAGE_CHARS=4096,MAX_URL_CHARS=1024;const Z=["token","secret","password","passwd","apikey","credential","assertion","signature"],R=new Set(["key","auth","authorization","jwt","code","sig","pwd","pass","session","sid","bearer","otp","cookie","set-cookie"]),C=/^(?:(?:prompt|completion|total|input|output|cache|cached|cacheread|cachewrite|reasoning|thinking|max|min|remaining|used|billed)tokens|tokens?(?:count|used|limit|remaining))$/;export function isSecretParam(e){const t=h.get(e);if(t!==void 0)return t;const r=A(e);return e.length<=64&&h.size<N&&h.set(e,r),r}f(isSecretParam,"isSecretParam"),u(isSecretParam,"isSecretParam"),l(isSecretParam,"isSecretParam");const O=new Set(["sess","csrf","xsrf","refresh","nonce","reset","magic","mfa","2fa","verify","verification","invite","login"]);export function isSecretCacheKey(e){for(const t of e.split(/[:/{}#]+/))if(!(!t||t.length>64)){if(isSecretParam(t))return!0;for(const r of t.toLowerCase().split(/[-_.]+/))if(O.has(r))return!0}return!1}f(isSecretCacheKey,"isSecretCacheKey"),u(isSecretCacheKey,"isSecretCacheKey"),l(isSecretCacheKey,"isSecretCacheKey");const N=4096,h=new Map;function A(e){const t=e.toLowerCase();if(C.test(t.replace(/[-_.]+/g,"")))return!1;if(Z.some(r=>t.includes(r)))return!0;for(const r of t.split(/[-_.]+/))if(r&&R.has(r))return!0;return!1}f(A,"m"),u(A,"N"),l(A,"judgeParam");const D=/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@\s]*@/i,U=/([?&#])([^=&#\s]+)=([^&#\s]*)/g;export function redactUrlParams(e){return e&&e.replace(D,`$1${REDACTED}@`).replace(U,(t,r,n)=>isSecretParam(n)?`${r}${n}=${REDACTED}`:t)}f(redactUrlParams,"redactUrlParams"),u(redactUrlParams,"redactUrlParams"),l(redactUrlParams,"redactUrlParams");export function redactUrl(e){return e&&clip(redactUrlParams(e),1024)}f(redactUrl,"redactUrl"),u(redactUrl,"redactUrl"),l(redactUrl,"redactUrl");const K=/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g,M=/\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,L=/[@=:]|eyJ|bearer|basic/i;export function redactText(e){return L.test(e)?redactUrlParams(e).replace(j,(t,r,n,o)=>`${r}${n}${o}${REDACTED}${o}`).replace(K,REDACTED).replace(M,(t,r)=>`${r} ${REDACTED}`):e}f(redactText,"redactText"),u(redactText,"redactText"),l(redactText,"redactText");const q=[/\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],x="-----BEGIN ",H=4096;function m(e){if(!e.includes("PRIVATE KEY-----"))return e;let t="",r=0,n=!1;for(;;){const o=e.indexOf(x,r);if(o===-1)break;const c=e.indexOf("-----",o+x.length);if(c===-1)break;const s=e.slice(o+x.length,c);if(!/^[A-Z ]{0,30}PRIVATE KEY$/.test(s)){t+=e.slice(r,c+5),r=c+5;continue}t+=e.slice(r,o);const i=n?-1:e.indexOf("-----END ",c+5);let a;if(i===-1)n=!0,a=Math.min(e.length,c+5+H);else{const p=e.indexOf("-----",i+9);a=p===-1?e.length:p+5}t+=REDACTED,r=a}return t+e.slice(r)}f(m,"S"),u(m,"y"),l(m,"redactPrivateKeys");const V=/"([A-Za-z0-9_.-]{1,64})"\s*:\s*"((?:[^"\\]|\\.){1,8192})"/g,X=/\b([A-Za-z][A-Za-z0-9_-]{1,40})(\s*[:=]\s*)([^\s"'`,;&)}\]]{8,200})/g,G=/(token|secret|pass(?:word|wd)?|pwd|api[-_]?key|apikey|credential|authorization|bearer)/i;function b(e){return e.replace(V,(t,r)=>isSecretParam(r)?`"${r}": "${REDACTED}"`:t).replace(X,(t,r,n)=>G.test(r)&&isSecretParam(r)?`${r}${n}${REDACTED}`:t)}f(b,"w"),u(b,"U"),l(b,"redactStructured");export function redactSecretText(e){let t=b(redactText(m(e)));for(const r of q)t=t.replace(r,REDACTED);return t}f(redactSecretText,"redactSecretText"),u(redactSecretText,"redactSecretText"),l(redactSecretText,"redactSecretText");export function clip(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026[lensmcp truncated: ${e.length-t} more chars]`}f(clip,"clip"),u(clip,"clip"),l(clip,"clip");export function safeText(e,t=4096){if(e!==void 0)return clip(redactText(e),t)}f(safeText,"safeText"),u(safeText,"safeText"),l(safeText,"safeText");export function safeTitle(e){return clip(redactText(e),300)}f(safeTitle,"safeTitle"),u(safeTitle,"safeTitle"),l(safeTitle,"safeTitle");const J=6,Y=64,B=/^TS\d{1,5}$/,F=l((e,t)=>e==="code"&&typeof t=="string"&&B.test(t),"isDiagnosticCode");export function redactDeep(e,t=0,r=J){if(typeof e=="string")return redactText(e);if(e===null||typeof e!="object"||t>=r)return e;if(Array.isArray(e)){let s;for(let i=0;i<e.length;i++){if(i>=Y){s&&s.push(e[i]);continue}const a=e[i],p=redactDeep(a,t+1,r);s?s.push(p):p!==a&&(s=e.slice(0,i),s.push(p))}return s??e}const n=e,o=Object.keys(n);let c;for(let s=0;s<o.length;s++){const i=o[s],a=n[i],p=isSecretParam(i)&&a!==void 0&&a!==null&&!F(i,a)?REDACTED:redactDeep(a,t+1,r);if(c)c[i]=p;else if(p!==a){c={};for(let d=0;d<s;d++)c[o[d]]=n[o[d]];c[i]=p}}return c??e}f(redactDeep,"redactDeep"),u(redactDeep,"redactDeep"),l(redactDeep,"redactDeep");const S=String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`,$=String.raw`${S}(?:\s*\.\s*${S})*`,W=String.raw`(?:=|<>|!=|<=|>=|<|>|(?:NOT\s+)?I?LIKE|IS\s+(?:NOT\s+)?DISTINCT\s+FROM)`,Q=new RegExp(String.raw`(${$})\s*${W}\s*(?:[A-Za-z_]\w*\s*\(\s*)?\$(\d+)`,"gi"),ee=new RegExp(String.raw`(${$})\s+(?:NOT\s+)?IN\s*\(([^()]*)\)`,"gi"),te=new RegExp(String.raw`\bINSERT\s+INTO\s+${$}\s*\(([^()]*)\)\s*VALUES\s*`,"gi"),re=new RegExp(S,"g"),k=/\$(\d+)/g,E=16384,ne=256,se=4096,g=new Map,w=l(e=>{const t=e.match(re)??[],r=t[t.length-1]??"";return r.startsWith('"')?r.slice(1,-1).replace(/""/g,'"'):r},"lastIdent");function T(e,t){const r=[];let n=t;for(;;){for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!=="(")return r;const o=[];let c=n+1,s=0,i=!1;for(n+=1;n<e.length;n++){const a=e[n];if(i){a==="'"&&(i=!1);continue}if(a==="'")i=!0;else if(a==="(")s++;else if(a===")"){if(s===0)break;s--}else a===","&&s===0&&(o.push(e.slice(c,n)),c=n+1)}if(n>=e.length)return r;for(o.push(e.slice(c,n)),r.push(o),n+=1;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!==",")return r;n+=1}}f(T,"k"),u(T,"q"),l(T,"valuesTuples");function y(e){const t=e.length<=se,r=t?g.get(e):void 0;if(r)return r;const n=e.length>E?e.slice(0,E):e,o=new Set,c=l((s,i)=>{i&&isSecretParam(i)&&o.add(Number(s))},"bind");for(const s of n.matchAll(Q))c(s[2],w(s[1]));for(const s of n.matchAll(ee)){const i=w(s[1]);for(const a of s[2].matchAll(k))c(a[1],i)}for(const s of n.matchAll(te)){const i=s[1].split(",").map(a=>w(a.trim()));for(const a of T(n,(s.index??0)+s[0].length))a.forEach((p,d)=>{const z=i[d];if(z)for(const _ of p.matchAll(k))c(_[1],z)})}if(t){if(g.size>=ne){const s=g.keys().next().value;s!==void 0&&g.delete(s)}g.set(e,o)}return o}f(y,"y"),u(y,"ee"),l(y,"secretPlaceholders");export function redactSqlParams(e,t){if(t.length===0||!e.includes("$"))return t;const r=y(e);if(r.size===0)return t;let n=!1;const o=t.map((c,s)=>c==null||!r.has(s+1)?c:(n=!0,REDACTED));return n?o:t}f(redactSqlParams,"redactSqlParams"),u(redactSqlParams,"redactSqlParams"),l(redactSqlParams,"redactSqlParams");
|
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{}}}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where session replay recordings live (planning/replay/00-plan.md §5, the owner's D4) — one rule for the bridge that
|
|
3
|
+
* writes them and the lens that reads and sweeps them.
|
|
4
|
+
*
|
|
5
|
+
* <root>/<checkout>/<loadId>/ a page load: meta.json, index.jsonl, the chunks
|
|
6
|
+
* <root>/blobs/<sha[0:2]>/ what loads share, stored once by hash
|
|
7
|
+
*/
|
|
8
|
+
export interface ReplayStore {
|
|
9
|
+
/** The workspace's replay root. */
|
|
10
|
+
root: string;
|
|
11
|
+
/** `main`, or a worktree instance's name. */
|
|
12
|
+
checkout: string;
|
|
13
|
+
}
|
|
14
|
+
/** A path segment from the environment: only what is safe in a file name. */
|
|
15
|
+
export declare function replayPathSegment(value: string | undefined): string | undefined;
|
|
16
|
+
/**
|
|
17
|
+
* `LENSMCP_REPLAY_DIR`; else `~/.lensmcp/replay/<workspace>` for a workspace the gateway names; else beside the bus file.
|
|
18
|
+
* The checkout is the worktree instance (`LENSMCP_INSTANCE`) or `main`.
|
|
19
|
+
*
|
|
20
|
+
* The workspace is `LENSMCP_REPLAY_WORKSPACE` — what the gateway hands a lens frontend, its dashboards and its MCP
|
|
21
|
+
* server: the MAIN workspace's key for a worktree instance too, so a removed worktree keeps its recordings — else
|
|
22
|
+
* `LENSMCP_WS_KEY`. (A frontend the gateway started used to get neither, and wrote beside the bus.)
|
|
23
|
+
*/
|
|
24
|
+
export declare function replayStoreFromEnv(env?: Record<string, string | undefined>, cwd?: string): ReplayStore;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var p=Object.defineProperty;var t=(e,r)=>p(e,"name",{value:r,configurable:!0});var i=Object.defineProperty,o=t((e,r)=>i(e,"name",{value:r,configurable:!0}),"o"),c=Object.defineProperty,n=o((e,r)=>c(e,"name",{value:r,configurable:!0}),"e");import{homedir as l}from"node:os";import{dirname as s,join as m}from"node:path";import{lensEventFile as E}from"./lens-events.js";export function replayPathSegment(e){const r=e?.trim().replace(/[^A-Za-z0-9._-]/g,"-").replace(/^[.-]+/,"");return r?r.slice(0,80):void 0}t(replayPathSegment,"replayPathSegment"),o(replayPathSegment,"replayPathSegment"),n(replayPathSegment,"replayPathSegment");export function replayStoreFromEnv(e=process.env,r=process.cwd()){const a=replayPathSegment(e.LENSMCP_REPLAY_WORKSPACE||e.LENSMCP_WS_KEY);return{root:e.LENSMCP_REPLAY_DIR?.trim()||(a?m(e.LENSMCP_HOME||l(),".lensmcp","replay",a):m(s(E(e,r)),"replay")),checkout:replayPathSegment(e.LENSMCP_INSTANCE)??"main"}}t(replayStoreFromEnv,"replayStoreFromEnv"),o(replayStoreFromEnv,"replayStoreFromEnv"),n(replayStoreFromEnv,"replayStoreFromEnv");
|
package/lib/resource-store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var d=Object.defineProperty;var n=(r,t)=>d(r,"name",{value:t,configurable:!0});var l=Object.defineProperty,c=n((r,t)=>l(r,"name",{value:t,configurable:!0}),"a"),p=Object.defineProperty,u=c((r,t)=>p(r,"name",{value:t,configurable:!0}),"a");export class ResourceStore{static{n(this,"ResourceStore")}static{c(this,"ResourceStore")}static{u(this,"ResourceStore")}constructor(t={}){this.entries=new Map,this.subs=new Map,this.queued=new Map,this.lastRun=new Map,this.lastCost=new Map,this.coalesceMs=Math.max(0,t.coalesceMs??0),this.costFactor=Math.max(0,t.costFactor??0),this.maxGapMs=Math.max(0,t.maxGapMs??3e4)}register(t,e){if(this.entries.has(t))throw new Error(`Resource already registered: ${t}`);return this.entries.set(t,{uri:t,produce:e,revision:0}),()=>{this.entries.delete(t),this.subs.delete(t),this.lastRun.delete(t),this.lastCost.delete(t)}}async read(t){const e=this.entries.get(t);if(!e)throw new Error(`Unknown resource: ${t}`);const s=await e.produce();return e.produced={at:Date.now(),value:s},s}async readRecent(t,e){const s=this.entries.get(t);if(!s)throw new Error(`Unknown resource: ${t}`);return s.produced&&Date.now()-s.produced.at<=e?s.produced.value:this.read(t)}list(){return[...this.entries.keys()]}markDirty(t){if(this.coalesceMs===0&&this.costFactor===0)return this.recompute(t);if(!this.entries.has(t))return Promise.resolve();const e=this.queued.get(t);if(e)return e;const s=Math.max(0,(this.lastRun.get(t)??Number.NEGATIVE_INFINITY)+this.gapFor(t)-Date.now()),i=new Promise(o=>{const a=u(()=>{this.queued.delete(t),this.lastRun.set(t,Date.now()),this.recompute(t).then(o,()=>o())},"go");s===0?setImmediate(a):setTimeout(a,s).unref?.()});return this.queued.set(t,i),i}gapFor(t){const e=this.lastCost.get(t)??0;return Math.max(this.coalesceMs,Math.min(this.maxGapMs,this.costFactor*e))}cost(t){return this.lastCost.get(t)}async recompute(t){const e=this.entries.get(t);if(!e)return;const s=performance.now(),i=await e.produce();e.produced={at:Date.now(),value:i};const o=JSON.stringify(i);if(this.lastCost.set(t,performance.now()-s),o===e.lastJson)return;e.lastJson=o,e.revision+=1;const a=this.subs.get(t);if(a)for(const h of a)try{h(t,e.revision)}catch{}}revision(t){return this.entries.get(t)?.revision}subscribe(t,e){let s=this.subs.get(t);return s||(s=new Set,this.subs.set(t,s)),s.add(e),()=>{s?.delete(e)}}}
|
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/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");
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { DashCacheValues, DashKeptValues, DashSqlValues } from '@lensmcp/protocol-types';
|
|
2
|
+
/**
|
|
3
|
+
* Where every value of a SQL run is kept (planning/replay/00-plan.md D8 — the owner: «we need to understand
|
|
4
|
+
* everything»): one rule for the pg tap that writes it and the lens that reads it.
|
|
5
|
+
*
|
|
6
|
+
* The bus keeps what a flow step shows — the first 10 parameters at 80 characters and 2 result rows at 240. The whole of
|
|
7
|
+
* them goes beside the bus file, `<lens dir>/sql/<pid>-<yyyymmddhhmm>.jsonl`, one line per run; the event carries the
|
|
8
|
+
* run's id (`valuesId`), and the id names its file.
|
|
9
|
+
*
|
|
10
|
+
* A cache command's values are kept the same way (the Redis tap keeps 48 characters of an argument, 120 of a reply):
|
|
11
|
+
* `cav_` ids, `<lens dir>/cache/`.
|
|
12
|
+
*/
|
|
13
|
+
export declare const SQL_VALUES_DIR = "sql";
|
|
14
|
+
/** A cache command's values (the Redis tap): the same store, its own folder and id prefix. */
|
|
15
|
+
export declare const CACHE_VALUES_DIR = "cache";
|
|
16
|
+
/** One run's line — what `/api/sql-values?id=` answers. */
|
|
17
|
+
export type SqlValuesLine = DashSqlValues;
|
|
18
|
+
/** One cache command's line. */
|
|
19
|
+
export type CacheValuesLine = DashCacheValues;
|
|
20
|
+
export type KeptValuesLine = DashKeptValues;
|
|
21
|
+
/** `sqv_<yyyymmddhhmm>_<pid>_<n>`: the minute (UTC) and the process name the file. */
|
|
22
|
+
export declare function sqlValuesId(at: number, pid: number, n: number): string;
|
|
23
|
+
/** `cav_<yyyymmddhhmm>_<pid>_<n>`: a cache command's, named as a SQL run's. */
|
|
24
|
+
export declare function cacheValuesId(at: number, pid: number, n: number): string;
|
|
25
|
+
/** The file a kept line is in, under a lens dir — SQL's or a cache command's; `undefined` for anything else. */
|
|
26
|
+
export declare function keptValuesFile(lensDir: string, id: string): string | undefined;
|
|
27
|
+
/** The file a SQL run's line is in; `undefined` for anything that is not such an id. */
|
|
28
|
+
export declare function sqlValuesFile(lensDir: string, id: string): string | undefined;
|
|
29
|
+
export declare function isSqlValuesId(id: unknown): id is string;
|
|
30
|
+
export declare function isCacheValuesId(id: unknown): id is string;
|
|
31
|
+
/**
|
|
32
|
+
* One run's line, or `undefined` — not such an id, not written yet (the tap appends once a second), or pruned (a day).
|
|
33
|
+
* Read line by line and matched by its first field: a busy minute's file is never read whole, nor every line parsed.
|
|
34
|
+
*/
|
|
35
|
+
export declare function readSqlValues(lensDir: string, id: string): Promise<SqlValuesLine | undefined>;
|
|
36
|
+
/** One cache command's line, or `undefined` (as {@link readSqlValues}). */
|
|
37
|
+
export declare function readCacheValues(lensDir: string, id: string): Promise<CacheValuesLine | undefined>;
|
|
38
|
+
/**
|
|
39
|
+
* Several runs' lines at once — each file read once, however many of its runs are asked for (a story names dozens of
|
|
40
|
+
* runs of one minute). What is not there is absent from the map.
|
|
41
|
+
*/
|
|
42
|
+
export declare function readSqlValuesMany(lensDir: string, ids: readonly string[]): Promise<Map<string, SqlValuesLine>>;
|
|
43
|
+
/** {@link readSqlValuesMany} for any kept line — SQL runs' and cache commands' alike. */
|
|
44
|
+
export declare function readKeptValuesMany(lensDir: string, ids: readonly string[]): Promise<Map<string, KeptValuesLine>>;
|
|
45
|
+
/**
|
|
46
|
+
* The statement with one run's values in place of `$1…` — what to paste into psql. A value is a quoted literal
|
|
47
|
+
* Postgres casts to the column's type, `null` is `NULL`, and a `$n` inside a quoted string is left alone.
|
|
48
|
+
* Lock-step with the dashboard's `withValues` (libs/dashboard-ui/src/views/data/sql-model.ts), which cannot import this.
|
|
49
|
+
*/
|
|
50
|
+
export declare function sqlWithValues(sql: string, params: readonly string[] | undefined): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var S=Object.defineProperty;var r=(e,t)=>S(e,"name",{value:t,configurable:!0});var v=Object.defineProperty,l=r((e,t)=>v(e,"name",{value:t,configurable:!0}),"s"),$=Object.defineProperty,c=l((e,t)=>$(e,"name",{value:t,configurable:!0}),"c");import{createReadStream as q}from"node:fs";import{join as _}from"node:path";import{createInterface as g}from"node:readline";export const SQL_VALUES_DIR="sql",CACHE_VALUES_DIR="cache";const h=/^(sqv|cav)_(\d{12})_(\d{1,10})_([0-9a-z]{1,12})$/,x={sqv:SQL_VALUES_DIR,cav:CACHE_VALUES_DIR};export function sqlValuesId(e,t,a){return`sqv_${V(e)}_${t}_${a.toString(36)}`}r(sqlValuesId,"sqlValuesId"),l(sqlValuesId,"sqlValuesId"),c(sqlValuesId,"sqlValuesId");export function cacheValuesId(e,t,a){return`cav_${V(e)}_${t}_${a.toString(36)}`}r(cacheValuesId,"cacheValuesId"),l(cacheValuesId,"cacheValuesId"),c(cacheValuesId,"cacheValuesId");export function keptValuesFile(e,t){const a=h.exec(t);return a?_(e,x[a[1]],`${a[3]}-${a[2]}.jsonl`):void 0}r(keptValuesFile,"keptValuesFile"),l(keptValuesFile,"keptValuesFile"),c(keptValuesFile,"keptValuesFile");export function sqlValuesFile(e,t){return isSqlValuesId(t)?keptValuesFile(e,t):void 0}r(sqlValuesFile,"sqlValuesFile"),l(sqlValuesFile,"sqlValuesFile"),c(sqlValuesFile,"sqlValuesFile");export function isSqlValuesId(e){return typeof e=="string"&&h.test(e)&&e.startsWith("sqv_")}r(isSqlValuesId,"isSqlValuesId"),l(isSqlValuesId,"isSqlValuesId"),c(isSqlValuesId,"isSqlValuesId");export function isCacheValuesId(e){return typeof e=="string"&&h.test(e)&&e.startsWith("cav_")}r(isCacheValuesId,"isCacheValuesId"),l(isCacheValuesId,"isCacheValuesId"),c(isCacheValuesId,"isCacheValuesId");export async function readSqlValues(e,t){return isSqlValuesId(t)?await p(e,t):void 0}r(readSqlValues,"readSqlValues"),l(readSqlValues,"readSqlValues"),c(readSqlValues,"readSqlValues");export async function readCacheValues(e,t){return isCacheValuesId(t)?await p(e,t):void 0}r(readCacheValues,"readCacheValues"),l(readCacheValues,"readCacheValues"),c(readCacheValues,"readCacheValues");async function p(e,t){const a=keptValuesFile(e,t);if(!a)return;const o=`{"id":${JSON.stringify(t)},`,n=q(a,{encoding:"utf8"}),s=g({input:n,crlfDelay:1/0});try{for await(const i of s){if(!i.startsWith(o))continue;const u=JSON.parse(i);return u.id===t?u:void 0}}catch{}finally{s.close(),n.destroy()}}r(p,"p"),l(p,"h"),c(p,"readKeptValues");export async function readSqlValuesMany(e,t){return await readKeptValuesMany(e,t.filter(isSqlValuesId))}r(readSqlValuesMany,"readSqlValuesMany"),l(readSqlValuesMany,"readSqlValuesMany"),c(readSqlValuesMany,"readSqlValuesMany");export async function readKeptValuesMany(e,t){const a=new Map;for(const n of t){const s=keptValuesFile(e,n);if(!s)continue;const i=a.get(s)??new Set;i.add(n),a.set(s,i)}const o=new Map;for(const[n,s]of a){const i=q(n,{encoding:"utf8"}),u=g({input:i,crlfDelay:1/0});let d=s.size;try{for await(const y of u){const f=/^\{"id":"((?:sqv|cav)_[0-9a-z_]+)",/.exec(y);if(!(!f||!s.has(f[1])||o.has(f[1]))){try{o.set(f[1],JSON.parse(y))}catch{continue}if(--d===0)break}}}catch{}finally{u.close(),i.destroy()}}return o}r(readKeptValuesMany,"readKeptValuesMany"),l(readKeptValuesMany,"readKeptValuesMany"),c(readKeptValuesMany,"readKeptValuesMany");export function sqlWithValues(e,t){if(!t?.length)return e;const a=c(s=>s==="null"||s==="undefined"?"NULL":`'${s.replace(/'/g,"''")}'`,"literal");let o="",n=0;for(;n<e.length;){const s=e[n];if(s==="'"){const u=e.indexOf("'",n+1),d=u<0?e.length:u+1;o+=e.slice(n,d),n=d;continue}const i=s==="$"?/^\$(\d+)/.exec(e.slice(n,n+12)):null;if(i){const u=t[Number(i[1])-1];o+=u===void 0?i[0]:a(u),n+=i[0].length;continue}o+=s,n++}return o}r(sqlWithValues,"sqlWithValues"),l(sqlWithValues,"sqlWithValues"),c(sqlWithValues,"sqlWithValues");function V(e){const t=new Date(e),a=c(o=>String(o).padStart(2,"0"),"p");return`${t.getUTCFullYear()}${a(t.getUTCMonth()+1)}${a(t.getUTCDate())}${a(t.getUTCHours())}${a(t.getUTCMinutes())}`}r(V,"V"),l(V,"g"),c(V,"minuteStamp");
|
package/lib/stores.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)):t[r]=i(o.replace(/\s+#.*$/,""))}return t}
|
|
1
|
+
"use strict";var U=Object.defineProperty;var l=(s,e)=>U(s,"name",{value:e,configurable:!0});var j=Object.defineProperty,f=l((s,e)=>j(s,"name",{value:e,configurable:!0}),"p"),R=Object.defineProperty,p=f((s,e)=>R(s,"name",{value:e,configurable:!0}),"u");import{readFileSync as b}from"node:fs";import{join as g}from"node:path";const S=/^[A-Za-z0-9_-]+$/,A=new Set(["kind","url","databases","lens","run"]);export function readStoresDecl(s){let e;try{e=JSON.parse(b(g(s,"nx.json"),"utf8"))}catch{return{stores:{},errors:[],notes:[]}}const t=e?.lensmcp?.stores;return t===void 0?{stores:{},errors:[],notes:[]}:validateStoresDecl(t)}l(readStoresDecl,"readStoresDecl"),f(readStoresDecl,"readStoresDecl"),p(readStoresDecl,"readStoresDecl");export function validateStoresDecl(s){const e=[],t=[],i={};if(!s||typeof s!="object"||Array.isArray(s))return{stores:i,errors:["`lensmcp.stores` must be an object"],notes:t};for(const[n,a]of Object.entries(s)){const r=`stores.${n}`;if(!S.test(n)){e.push(`${r}: a store name is letters, digits, '-' and '_'`);continue}if(!a||typeof a!="object"||Array.isArray(a)){e.push(`${r}: must be an object`);continue}const o=a,m=o.kind;if(m!=="postgres"&&m!=="redis"){e.push(`${r}.kind: one of "postgres", "redis"`);continue}const v=typeof o.url=="string"?o.url.trim():"";if(!v){e.push(`${r}.url: the connection URL is required (e.g. "\${${m==="postgres"?"PG_URL":"REDIS_URL"}}")`);continue}const h=o.databases??[];if(!Array.isArray(h)||!h.every(u=>typeof u=="string"&&u.trim())){e.push(`${r}.databases: a list of URLs or database names`);continue}if(h.length&&m!=="postgres"){e.push(`${r}.databases: only a postgres store has databases`);continue}const d=o.lens??{};if(!d||typeof d!="object"||Array.isArray(d)){e.push(`${r}.lens: must be an object`);continue}const c=d;if(c.url!==void 0&&(typeof c.url!="string"||!c.url.trim())){e.push(`${r}.lens.url: a connection URL`);continue}if(c.read!==void 0&&typeof c.read!="boolean"){e.push(`${r}.lens.read: true or false`);continue}if(c.prepare!==void 0&&typeof c.prepare!="boolean"){e.push(`${r}.lens.prepare: true or false`);continue}o.run!==void 0&&t.push(`${r}.run: planned \u2014 lensmcp does not start stores yet; the store is used as declared`);for(const u of Object.keys(o))A.has(u)||t.push(`${r}.${u}: not a store setting \u2014 ignored`);i[n]={kind:m,url:v,databases:h.map(u=>u.trim()),lens:{...typeof c.url=="string"?{url:c.url.trim()}:{},read:c.read!==!1,prepare:c.prepare!==!1}}}return{stores:i,errors:e,notes:t}}l(validateStoresDecl,"validateStoresDecl"),f(validateStoresDecl,"validateStoresDecl"),p(validateStoresDecl,"validateStoresDecl");export function parseDotenv(s,e={}){const t={},i=p(n=>n.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(a,r)=>t[r]??e[r]??""),"expand");for(const n of s.split(/\r?\n/)){const a=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!a)continue;const r=a[1],o=a[2];o.startsWith("'")&&o.indexOf("'",1)>0?t[r]=o.slice(1,o.indexOf("'",1)):o.startsWith('"')&&o.indexOf('"',1)>0?t[r]=i(o.slice(1,o.indexOf('"',1)).replace(/\\n/g,`
|
|
2
|
+
`)):t[r]=i(o.replace(/\s+#.*$/,""))}return t}l(parseDotenv,"parseDotenv"),f(parseDotenv,"parseDotenv"),p(parseDotenv,"parseDotenv");function $(s,e){try{return parseDotenv(b(s,"utf8"),e)}catch{return{}}}l($,"g"),f($,"$"),p($,"readDotenv");export function checkoutEnv(s,e=process.env){let t={};for(const n of[".env",".env.local"])t={...t,...$(g(s,n),{...t})};const i=Object.fromEntries(Object.entries(e).filter(n=>typeof n[1]=="string"));t={...t,...i};for(const n of[g(".lensmcp","instance.resources.env"),g(".lensmcp","instance.env")])t={...t,...$(g(s,n),{...t})};return t}l(checkoutEnv,"checkoutEnv"),f(checkoutEnv,"checkoutEnv"),p(checkoutEnv,"checkoutEnv");export function expandVars(s,e){const t=[];return{value:s.replace(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(i,n)=>{const a=e[n];return(a===void 0||a==="")&&t.push(n),a??""}),missing:t}}l(expandVars,"expandVars"),f(expandVars,"expandVars"),p(expandVars,"expandVars");const y=p(s=>s.port||(s.protocol.startsWith("redis")?"6379":"5432"),"portOf");export function withDatabase(s,e){const t=new URL(s);return t.pathname=`/${e}`,t.toString()}l(withDatabase,"withDatabase"),f(withDatabase,"withDatabase"),p(withDatabase,"withDatabase");export function redactUrl(s){try{const e=new URL(s);return`${e.protocol}//${e.username?`${decodeURIComponent(e.username)}@`:""}${e.hostname}:${y(e)}${e.pathname}`}catch{return"(not a URL)"}}l(redactUrl,"redactUrl"),f(redactUrl,"redactUrl"),p(redactUrl,"redactUrl");export function resolveStores(s,e){return Object.entries(s).map(([t,i])=>{const n=expandVars(i.url,e),a=[...n.missing];let r;try{r=n.missing.length?void 0:new URL(n.value)}catch{r=void 0}const o=[];if(r&&i.kind==="postgres"){o.push({name:decodeURIComponent(r.pathname.replace(/^\//,""))||"postgres",url:n.value});for(const h of i.databases){const d=expandVars(h,e);if(d.missing.length){a.push(...d.missing);continue}const c=/^[a-z]+:\/\//i.test(d.value)?d.value:withDatabase(n.value,d.value);try{const u=decodeURIComponent(new URL(c).pathname.replace(/^\//,""));u&&!o.some(x=>x.name===u)&&o.push({name:u,url:c})}catch{}}}const m=i.lens.url?expandVars(i.lens.url,e):void 0;m?.missing.length&&a.push(...m.missing);const v=i.lens.read?a.length?`${[...new Set(a)].map(h=>`\${${h}}`).join(", ")} not set in this checkout`:r?void 0:"`url` is not a connection URL":"reading is off (`lens.read: false`)";return{name:t,kind:i.kind,server:r?`${r.hostname}:${y(r)}`:"?",databases:o,...v?{noRead:v}:{readUrl:m?.value||n.value},prepare:i.lens.prepare!==!1,missing:[...new Set(a)]}})}l(resolveStores,"resolveStores"),f(resolveStores,"resolveStores"),p(resolveStores,"resolveStores");
|
package/lib/story.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var I=Object.defineProperty;var u=(t,n)=>I(t,"name",{value:n,configurable:!0});var k=Object.defineProperty,c=u((t,n)=>k(t,"name",{value:n,configurable:!0}),"u"),b=Object.defineProperty,p=c((t,n)=>b(t,"name",{value:n,configurable:!0}),"c");export function groupByFlow(t){const n=new Map;for(const e of t){const o=e.context.flowId;if(!o)continue;let s=n.get(o);s||(s=[],n.set(o,s)),s.push(e)}return n}u(groupByFlow,"groupByFlow"),c(groupByFlow,"groupByFlow"),p(groupByFlow,"groupByFlow");export function compileStory(t,n={}){let e,o;if(n.flowId)o=n.flowId,e=t.filter(r=>r.context.flowId===o);else{const r=t.find(i=>i.context.flowId);if(!r)return;o=r.context.flowId,e=t.filter(i=>i.context.flowId===o)}if(e.length===0)return;e.sort((r,i)=>r.timestamp-i.timestamp);const s=1e3;e.length>s&&(e=[e[0],...e.slice(e.length-(s-1))]);const m=e[0],d=[];let l,v;for(const r of e){const i=f(r);if(i){if(d.push(i),i.kind==="render"||i.kind==="final-render"){const a=r.raw;a?.render&&(l={id:a.render.id,page:a.render.page,route:a.render.route,componentName:a.render.componentName})}else if(r.source==="visual"&&i.kind==="visual-violation"){const a=r.raw;a?.frame&&(v=a.frame.id)}}}for(let r=d.length-1;r>=0;r--)if(d[r].kind==="render"){d[r]={...d[r],kind:"final-render"};break}const g=e[0].timestamp,w=e[e.length-1].timestamp;return{flowId:o,origin:{type:m.context.originType,nodeId:m.context.originNodeId,at:m.timestamp},phases:d,finalState:l?{page:l.page,route:l.route,componentName:l.componentName,renderId:l.id,visualFrameId:v}:void 0,startedAt:g,endedAt:w,eventCount:e.length}}u(compileStory,"compileStory"),c(compileStory,"compileStory"),p(compileStory,"compileStory");function f(t){const n=(t.raw??null)?.kind;if(n==="flow-origin"||t.source==="client-runtime"&&n==="user-action"){const e=t.raw;return{kind:"user-action",at:t.timestamp,label:e?.origin?.label??t.title,eventIds:[t.id]}}if(t.source==="react"&&n==="render"){const e=t.raw;return{kind:"render",at:t.timestamp,label:`render ${e?.render?.componentName??"?"}`,eventIds:[t.id],details:e?.render?{componentName:e.render.componentName,durationMs:e.render.actualDurationMs}:void 0}}if(t.source==="react"&&n==="slot-content-changed"){const e=t.raw,o=e?.slot?.toComponent??"?";return{kind:/spinner|loader|loading/i.test(o)?"loading-ui":"idle-ui",at:t.timestamp,label:`slot ${e?.slot?.slotLogicalId??""} \u2192 ${o}`,eventIds:[t.id]}}if(t.source==="client-runtime"&&n==="route"){const e=t.raw;return{kind:"route-transition",at:t.timestamp,label:`route ${e?.from??""} \u2192 ${e?.url??""}`,eventIds:[t.id]}}if(t.source==="valtio"&&n==="state-update"){const e=t.raw;return{kind:"state-update",at:t.timestamp,label:`${e?.update?.storeId??"?"}.${e?.update?.path??"?"}`,eventIds:[t.id],details:e?.update}}if(t.source==="nestjs"&&n==="server-request"){const e=t.raw;return{kind:"backend-request",at:t.timestamp,label:`${e?.request?.method??"?"} ${e?.request?.route??"?"} \u2192 ${e?.request?.status??"?"}`,eventIds:[t.id],details:e?.request}}if(t.source==="chrome"&&t.category==="network")return{kind:"backend-request",at:t.timestamp,label:t.title,eventIds:[t.id]};if(t.source==="visual"&&n==="visual-violation"){const e=t.raw;return{kind:"visual-violation",at:t.timestamp,label:`${e?.violation?.ruleType??"rule"} ${e?.violation?.ruleId??""}`,eventIds:[t.id]}}}u(f,"f"),c(f,"g"),p(f,"classifyEvent");
|
package/lib/thresholds.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var l=Object.defineProperty;var r=(e,s)=>l(e,"name",{value:s,configurable:!0});var u=Object.defineProperty,t=r((e,s)=>u(e,"name",{value:s,configurable:!0}),"r"),a=Object.defineProperty,c=t((e,s)=>a(e,"name",{value:s,configurable:!0}),"n");export const DEFAULT_THRESHOLDS={dbInLoop:5,nPlusOne:3,renderStorm:5,slowRouteMs:500,slowPageMs:1e3,slowRenderMs:16,slowQueryMs:100,duplicateRequestPeak:3,slowEgressMs:1e3};export function resolveThresholds(e){const s={...DEFAULT_THRESHOLDS};if(e)for(const n of Object.keys(DEFAULT_THRESHOLDS)){const o=e[n];typeof o=="number"&&Number.isFinite(o)&&o>=0&&(s[n]=o)}return s}r(resolveThresholds,"resolveThresholds"),t(resolveThresholds,"resolveThresholds"),c(resolveThresholds,"resolveThresholds");
|
package/lib/ulid.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var s=Object.defineProperty;var o=(e,n)=>s(e,"name",{value:n,configurable:!0});var b=Object.defineProperty,a=o((e,n)=>b(e,"name",{value:n,configurable:!0}),"r"),m=Object.defineProperty,u=a((e,n)=>m(e,"name",{value:n,configurable:!0}),"r");const f="0123456789ABCDEFGHJKMNPQRSTVWXYZ",g=16;function c(e,n){let r="",t=e;for(let l=n-1;l>=0;l--){const d=t%32;r=f[d]+r,t=(t-d)/32}return r}o(c,"l"),a(c,"s"),u(c,"encodeTime");function i(e){const n=new Uint8Array(e);globalThis.crypto.getRandomValues(n);let r="";for(let t=0;t<e;t++)r+=f[(n[t]??0)&31];return r}o(i,"s"),a(i,"a"),u(i,"encodeRandom");export function ulid(e=Date.now()){return c(e,10)+i(16)}o(ulid,"ulid"),a(ulid,"ulid"),u(ulid,"ulid");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lensmcp/core",
|
|
3
|
-
"version": "1.25.
|
|
3
|
+
"version": "1.25.18",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./index.js",
|
|
6
6
|
"module": "./index.js",
|
|
@@ -47,6 +47,21 @@
|
|
|
47
47
|
"import": "./lib/lens-events.js",
|
|
48
48
|
"default": "./lib/lens-events.js"
|
|
49
49
|
},
|
|
50
|
+
"./replay-store": {
|
|
51
|
+
"types": "./lib/replay-store.d.ts",
|
|
52
|
+
"import": "./lib/replay-store.js",
|
|
53
|
+
"default": "./lib/replay-store.js"
|
|
54
|
+
},
|
|
55
|
+
"./sql-values": {
|
|
56
|
+
"types": "./lib/sql-values.d.ts",
|
|
57
|
+
"import": "./lib/sql-values.js",
|
|
58
|
+
"default": "./lib/sql-values.js"
|
|
59
|
+
},
|
|
60
|
+
"./key-pattern": {
|
|
61
|
+
"types": "./lib/key-pattern.d.ts",
|
|
62
|
+
"import": "./lib/key-pattern.js",
|
|
63
|
+
"default": "./lib/key-pattern.js"
|
|
64
|
+
},
|
|
50
65
|
"./ai-content": {
|
|
51
66
|
"types": "./lib/ai-content.d.ts",
|
|
52
67
|
"import": "./lib/ai-content.js",
|
|
@@ -64,7 +79,7 @@
|
|
|
64
79
|
}
|
|
65
80
|
},
|
|
66
81
|
"dependencies": {
|
|
67
|
-
"@lensmcp/protocol-types": "1.25.
|
|
82
|
+
"@lensmcp/protocol-types": "1.25.18",
|
|
68
83
|
"tslib": "^2.3.0"
|
|
69
84
|
},
|
|
70
85
|
"license": "Apache-2.0",
|