@lensmcp/core 1.26.0 → 1.26.2

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 CHANGED
@@ -1 +1 @@
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");
1
+ "use strict";var a=Object.defineProperty;var r=(t,i)=>a(t,"name",{value:i,configurable:!0});var s=Object.defineProperty,n=r((t,i)=>s(t,"name",{value:i,configurable:!0}),"r");import*as c from"node:fs";import{dirname as l,join as o}from"node:path";export const AI_CONTENT_DIR="ai";const d=/^ai_[0-9a-z]{8,40}$/;export const isAiCallId=n(t=>typeof t=="string"&&d.test(t),"isAiCallId");export function aiContentDir(t){return o(l(t),AI_CONTENT_DIR)}r(aiContentDir,"aiContentDir"),n(aiContentDir,"aiContentDir");export function aiContentFile(t,i){if(!isAiCallId(i))throw new Error("invalid ai call id");return o(aiContentDir(t),`${i}.json`)}r(aiContentFile,"aiContentFile"),n(aiContentFile,"aiContentFile");export function readAiContent(t,i){if(isAiCallId(i))try{const e=JSON.parse(c.readFileSync(aiContentFile(t,i),"utf8"));return e&&e.schemaVersion===1&&e.id===i?e:void 0}catch{return}}r(readAiContent,"readAiContent"),n(readAiContent,"readAiContent");
@@ -1,2 +1,2 @@
1
- "use strict";var z=Object.defineProperty;var p=(t,n)=>z(t,"name",{value:n,configurable:!0});var G=Object.defineProperty,y=p((t,n)=>G(t,"name",{value:n,configurable:!0}),"m"),V=Object.defineProperty,f=y((t,n)=>V(t,"name",{value:n,configurable:!0}),"h");import{boundedClone as H}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",MAX_CUT_NOTE_BYTES=120,FITTED_STRING_CHARS=1500,REPEATED_STRING_MIN_CHARS=200;const F=600,K=32,J=new Set(["timestamp","startedAt","startTime","at","emittedAt","lastSeenAt","endedAt","endTime","t","ts","time"]),X=f(t=>typeof t=="number"&&t>=1e11&&t<=1e14,"isEpochMs"),q=.95;export function answerBudgetBytes(t=process.env){const n=t[ANSWER_BUDGET_ENV];if(n===void 0||n.trim()==="")return DEFAULT_ANSWER_BUDGET_BYTES;const r=Number(n);return!Number.isFinite(r)||r<0?DEFAULT_ANSWER_BUDGET_BYTES:r===0?Number.POSITIVE_INFINITY:Math.max(MIN_ANSWER_BUDGET_BYTES,Math.floor(r))}p(answerBudgetBytes,"answerBudgetBytes"),y(answerBudgetBytes,"answerBudgetBytes"),f(answerBudgetBytes,"answerBudgetBytes");export function utf8Bytes(t){let n=0;for(let r=0;r<t.length;r++){const o=t.charCodeAt(r);o<128?n+=1:o<2048?n+=2:o>=55296&&o<=56319&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(n+=4,r+=1):n+=3}return n}p(utf8Bytes,"utf8Bytes"),y(utf8Bytes,"utf8Bytes"),f(utf8Bytes,"utf8Bytes");export function jsonBytes(t){let n;try{n=JSON.stringify(t)}catch{return Number.POSITIVE_INFINITY}return n===void 0?0:utf8Bytes(n)}p(jsonBytes,"jsonBytes"),y(jsonBytes,"jsonBytes"),f(jsonBytes,"jsonBytes");const P=f(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),"isRecord");function _(t){if(!P(t))return!1;const n=Object.getPrototypeOf(t);return n===Object.prototype||n===null}p(_,"O"),y(_,"C"),f(_,"isPlain");export function newestEndOf(t){const n=t[0];if(t.length<2||!P(n))return;let r;for(const o of Object.keys(n)){if(typeof n[o]!="number"||!(J.has(o)||X(n[o])))continue;let s=0,i=0,u=!0,a=n[o];for(let x=1;x<t.length;x++){const b=t[x],d=P(b)?b[o]:void 0;if(typeof d!="number"){u=!1;break}d>a?s+=1:d<a&&(i+=1),a=d}const h=s+i;if(!u||h===0)continue;const l=Math.max(s,i)/h;l>=q&&(!r||l>r.agreement)&&(r={end:s>=i?"end":"start",agreement:l})}return r?.end}p(newestEndOf,"newestEndOf"),y(newestEndOf,"newestEndOf"),f(newestEndOf,"newestEndOf");export function newestFirst(t){return newestEndOf(t)==="end"?[...t].reverse():t.slice()}p(newestFirst,"newestFirst"),y(newestFirst,"newestFirst"),f(newestFirst,"newestFirst");export function shortenText(t,n){if(t.length<=n)return t;let r=Math.max(0,n);const o=t.lastIndexOf(`
2
- `,r);return o>=r/2&&(r=o),r>0&&(t.charCodeAt(r-1)&64512)===55296&&(r-=1),`${t.slice(0,r)}\u2026[lensmcp truncated: ${t.length-r} more chars]`}p(shortenText,"shortenText"),y(shortenText,"shortenText"),f(shortenText,"shortenText");export function fitList(t,n,r={}){const o=t.length,s=t.reduce((c,E)=>c+jsonBytes(E)+1,2);if(s<=n)return{items:t.slice(),total:o,returned:o,kept:"all",shortenedStrings:0,repeatedStrings:0,bytes:s};const i=r.newest??newestEndOf(t),u=i??r.keep??"start",a=r.name??"items",h=r.maxStringChars??FITTED_STRING_CHARS,l=u==="start"?t:[...t].reverse(),x=String(Math.max(0,o-1)).length,b=new Map,d=[],w=[];let A=2,I=0,C=0;for(let c=0;c<l.length;c++){const E=new Map,v=[];let B=0;const T=f((e,m,g,L,W)=>{if(typeof e=="string"){if(e.length>=REPEATED_STRING_MIN_CHARS){const S=b.get(e)??E.get(e);if(S)return v.push({holder:L,key:W,owner:S.owner,path:S.path}),`\u2026[lensmcp: same text as ${a}[${"9".repeat(x)}]${S.path}]`;E.set(e,{owner:c,path:m})}return e.length>h?(B+=1,shortenText(e,h)):e}if(g>=K)return e;if(Array.isArray(e)){const S=[];return e.forEach((j,D)=>S.push(T(j,`${m}[${D}]`,g+1,S,D))),S}if(_(e)){const S={};for(const j of Object.keys(e))S[j]=T(e[j],`${m}.${j}`,g+1,S,j);return S}return e},"slim"),O=[];let N=T(l[c],"",0,O,0),M=jsonBytes(N)+1;if(w.length===0&&A+M>n)N=R(l[c],Math.max(0,n-A-1)),M=jsonBytes(N)+1,v.length=0,E.clear(),B=1;else if(A+M>n)break;w.push(N),A+=M,I+=B,C+=v.length;for(const[e,m]of E)b.set(e,m);for(const e of v)d.push(e.holder===O?{...e,holder:w,key:w.length-1}:e)}const k=w.length,$=f(c=>u==="start"?c:k-1-c,"indexOf");if(u==="end"){for(const c of d)c.holder===w&&(c.key=$(c.key));w.reverse()}for(const c of d)c.holder[c.key]=`\u2026[lensmcp: same text as ${a}[${$(c.owner)}]${c.path}]`;return{items:w,total:o,returned:k,kept:k===o?"all":i?"newest":u==="start"?"first":"last",shortenedStrings:I,repeatedStrings:C,bytes:jsonBytes(w)}}p(fitList,"fitList"),y(fitList,"fitList"),f(fitList,"fitList");function R(t,n){let r=Math.max(256,n),o=t;for(let s=0;s<6;s++){if(o=H(t,{rawByteLimit:r,maxStringBytes:Math.min(2e3,Math.max(128,Math.floor(r/4))),maxArrayItems:64}).value,jsonBytes(o)<=n)return o;r=Math.floor(r*.6)}return o}p(R,"F"),y(R,"D"),f(R,"clampTo");export function shareBudget(t,n){const r=t.map((i,u)=>({size:i,index:u})).sort((i,u)=>i.size-u.size),o=new Array(t.length).fill(0);let s=Math.max(0,n);return r.forEach(({size:i,index:u},a)=>{const h=Math.floor(s/(r.length-a));o[u]=Math.min(i,h),s-=o[u]}),o}p(shareBudget,"shareBudget"),y(shareBudget,"shareBudget"),f(shareBudget,"shareBudget");export function cutNote(t){return(t.lists?.length?"Cut to fit: each list in `lists` shows `returned` of `total`; every other count is of the whole.":"Cut to fit: large values were shortened; every count is of the whole.")+(t.more?" Rest: see `more`.":"")}p(cutNote,"cutNote"),y(cutNote,"cutNote"),f(cutNote,"cutNote");function U(t,n){const r={...t},o=new WeakSet([r]),s=[];let i=0;for(const u of n){const a=u.split("."),h=a[a.length-1];let l=r;for(const x of a.slice(0,-1)){const b=l[x];if(!_(b)){l=void 0;break}const d=o.has(b)?b:{...b};o.add(d),l[x]=d,l=d}!l||l[h]===void 0||l[h]===null||(s.push({keys:a,value:l[h]}),i+=jsonBytes(l[h]),l[h]=null)}return s.length?{body:r,parts:s,bytes:i}:void 0}p(U,"P"),y(U,"K"),f(U,"holdWhole");function Y(t,n){for(const{keys:r,value:o}of n){let s=t;for(const i of r.slice(0,-1)){const u=s[i],a=_(u)?u:{};s[i]=a,s=a}s[r[r.length-1]]=o}return t}p(Y,"U"),y(Y,"z"),f(Y,"putBack");export function fitAnswer(t,n,r={}){if(!Number.isFinite(n)||t===null||typeof t!="object")return{value:t};const o=jsonBytes(t);if(o<=n)return{value:t};const s=r.whole?.length&&_(t)?U(t,r.whole):void 0,i=s?s.body:t,u=s?jsonBytes(i):o,a=s?Math.max(MIN_ANSWER_BUDGET_BYTES,n-s.bytes):n;if(u<=a)return{value:t};const h=[];let l=0,x=0,b=!1,d;const w=f(()=>(d={budget:n,original:o,...h.length?{lists:h}:{},...l?{shortened:l}:{},...x?{repeated:x}:{},...b?{clamped:!0}:{},...s?{whole:s.parts.map(e=>e.keys.join("."))}:{},...r.more?{more:r.more}:{},note:cutNote({lists:h,more:r.more})},d),"describe"),A=f(e=>({value:s?Y(e,s.parts):e,cut:d}),"done");if(Array.isArray(i)){const e=fitList(i,a);return e.kept!=="all"&&h.push({list:"items",total:e.total,returned:e.returned,kept:e.kept}),l=e.shortenedStrings,x=e.repeatedStrings,w(),A(e.items)}if(!_(i))return{value:t};const I=Object.keys(i),C=I.filter(e=>Array.isArray(i[e])&&i[e].length>0),k=C.map(e=>jsonBytes(i[e])),$=u-k.reduce((e,m)=>e+m,0),c=shareBudget(k,a-$-F),E={};C.forEach((e,m)=>{if(k[m]<=c[m])return;const g=fitList(i[e],c[m],{name:e,...r.newest?.[e]?{newest:r.newest[e]}:{}});E[e]=g.items,g.kept!=="all"&&h.push({list:e,total:g.total,returned:g.returned,kept:g.kept}),l+=g.shortenedStrings,x+=g.repeatedStrings});const v=f(e=>({[ANSWER_CUT_KEY]:w(),...e}),"assemble"),B={};for(const e of I)B[e]=e in E?E[e]:i[e];let T=v(B);if(jsonBytes(T)<=a)return A(T);b=!0;let O=Math.max(512,a-F);for(let e=0;e<6;e++){if(T=v(R(B,O)),jsonBytes(T)<=a)return A(T);O=Math.floor(O*.6)}const N={};let M=F;for(const e of I){const m=i[e];if(m!==null&&typeof m=="object")continue;const g=jsonBytes(m)+utf8Bytes(e)+4;if(M+g>a)break;N[e]=m,M+=g}return A(v(N))}p(fitAnswer,"fitAnswer"),y(fitAnswer,"fitAnswer"),f(fitAnswer,"fitAnswer");
1
+ "use strict";var L=Object.defineProperty;var m=(e,n)=>L(e,"name",{value:n,configurable:!0});var Y=Object.defineProperty,f=m((e,n)=>Y(e,"name",{value:n,configurable:!0}),"h");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",MAX_CUT_NOTE_BYTES=120,FITTED_STRING_CHARS=1500,REPEATED_STRING_MIN_CHARS=200;const C=600,V=32,H=new Set(["timestamp","startedAt","startTime","at","emittedAt","lastSeenAt","endedAt","endTime","t","ts","time"]),K=f(e=>typeof e=="number"&&e>=1e11&&e<=1e14,"isEpochMs"),J=.95;export function answerBudgetBytes(e=process.env){const n=e[ANSWER_BUDGET_ENV];if(n===void 0||n.trim()==="")return DEFAULT_ANSWER_BUDGET_BYTES;const r=Number(n);return!Number.isFinite(r)||r<0?DEFAULT_ANSWER_BUDGET_BYTES:r===0?Number.POSITIVE_INFINITY:Math.max(MIN_ANSWER_BUDGET_BYTES,Math.floor(r))}m(answerBudgetBytes,"answerBudgetBytes"),f(answerBudgetBytes,"answerBudgetBytes");export function utf8Bytes(e){let n=0;for(let r=0;r<e.length;r++){const o=e.charCodeAt(r);o<128?n+=1:o<2048?n+=2:o>=55296&&o<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(n+=4,r+=1):n+=3}return n}m(utf8Bytes,"utf8Bytes"),f(utf8Bytes,"utf8Bytes");export function jsonBytes(e){let n;try{n=JSON.stringify(e)}catch{return Number.POSITIVE_INFINITY}return n===void 0?0:utf8Bytes(n)}m(jsonBytes,"jsonBytes"),f(jsonBytes,"jsonBytes");const R=f(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isRecord");function O(e){if(!R(e))return!1;const n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}m(O,"C"),f(O,"isPlain");export function newestEndOf(e){const n=e[0];if(e.length<2||!R(n))return;let r;for(const o of Object.keys(n)){if(typeof n[o]!="number"||!(H.has(o)||K(n[o])))continue;let s=0,i=0,u=!0,a=n[o];for(let y=1;y<e.length;y++){const x=e[y],d=R(x)?x[o]:void 0;if(typeof d!="number"){u=!1;break}d>a?s+=1:d<a&&(i+=1),a=d}const h=s+i;if(!u||h===0)continue;const l=Math.max(s,i)/h;l>=J&&(!r||l>r.agreement)&&(r={end:s>=i?"end":"start",agreement:l})}return r?.end}m(newestEndOf,"newestEndOf"),f(newestEndOf,"newestEndOf");export function newestFirst(e){return newestEndOf(e)==="end"?[...e].reverse():e.slice()}m(newestFirst,"newestFirst"),f(newestFirst,"newestFirst");export function shortenText(e,n){if(e.length<=n)return e;let r=Math.max(0,n);const o=e.lastIndexOf(`
2
+ `,r);return o>=r/2&&(r=o),r>0&&(e.charCodeAt(r-1)&64512)===55296&&(r-=1),`${e.slice(0,r)}\u2026[lensmcp truncated: ${e.length-r} more chars]`}m(shortenText,"shortenText"),f(shortenText,"shortenText");export function fitList(e,n,r={}){const o=e.length,s=e.reduce((c,w)=>c+jsonBytes(w)+1,2);if(s<=n)return{items:e.slice(),total:o,returned:o,kept:"all",shortenedStrings:0,repeatedStrings:0,bytes:s};const i=r.newest??newestEndOf(e),u=i??r.keep??"start",a=r.name??"items",h=r.maxStringChars??FITTED_STRING_CHARS,l=u==="start"?e:[...e].reverse(),y=String(Math.max(0,o-1)).length,x=new Map,d=[],b=[];let E=2,_=0,$=0;for(let c=0;c<l.length;c++){const w=new Map,T=[];let M=0;const A=f((t,p,g,G,W)=>{if(typeof t=="string"){if(t.length>=REPEATED_STRING_MIN_CHARS){const S=x.get(t)??w.get(t);if(S)return T.push({holder:G,key:W,owner:S.owner,path:S.path}),`\u2026[lensmcp: same text as ${a}[${"9".repeat(y)}]${S.path}]`;w.set(t,{owner:c,path:p})}return t.length>h?(M+=1,shortenText(t,h)):t}if(g>=V)return t;if(Array.isArray(t)){const S=[];return t.forEach((I,D)=>S.push(A(I,`${p}[${D}]`,g+1,S,D))),S}if(O(t)){const S={};for(const I of Object.keys(t))S[I]=A(t[I],`${p}.${I}`,g+1,S,I);return S}return t},"slim"),B=[];let N=A(l[c],"",0,B,0),v=jsonBytes(N)+1;if(b.length===0&&E+v>n)N=F(l[c],Math.max(0,n-E-1)),v=jsonBytes(N)+1,T.length=0,w.clear(),M=1;else if(E+v>n)break;b.push(N),E+=v,_+=M,$+=T.length;for(const[t,p]of w)x.set(t,p);for(const t of T)d.push(t.holder===B?{...t,holder:b,key:b.length-1}:t)}const k=b.length,j=f(c=>u==="start"?c:k-1-c,"indexOf");if(u==="end"){for(const c of d)c.holder===b&&(c.key=j(c.key));b.reverse()}for(const c of d)c.holder[c.key]=`\u2026[lensmcp: same text as ${a}[${j(c.owner)}]${c.path}]`;return{items:b,total:o,returned:k,kept:k===o?"all":i?"newest":u==="start"?"first":"last",shortenedStrings:_,repeatedStrings:$,bytes:jsonBytes(b)}}m(fitList,"fitList"),f(fitList,"fitList");function F(e,n){let r=Math.max(256,n),o=e;for(let s=0;s<6;s++){if(o=z(e,{rawByteLimit:r,maxStringBytes:Math.min(2e3,Math.max(128,Math.floor(r/4))),maxArrayItems:64}).value,jsonBytes(o)<=n)return o;r=Math.floor(r*.6)}return o}m(F,"D"),f(F,"clampTo");export function shareBudget(e,n){const r=e.map((i,u)=>({size:i,index:u})).sort((i,u)=>i.size-u.size),o=new Array(e.length).fill(0);let s=Math.max(0,n);return r.forEach(({size:i,index:u},a)=>{const h=Math.floor(s/(r.length-a));o[u]=Math.min(i,h),s-=o[u]}),o}m(shareBudget,"shareBudget"),f(shareBudget,"shareBudget");export function cutNote(e){return(e.lists?.length?"Cut to fit: each list in `lists` shows `returned` of `total`; every other count is of the whole.":"Cut to fit: large values were shortened; every count is of the whole.")+(e.more?" Rest: see `more`.":"")}m(cutNote,"cutNote"),f(cutNote,"cutNote");function P(e,n){const r={...e},o=new WeakSet([r]),s=[];let i=0;for(const u of n){const a=u.split("."),h=a[a.length-1];let l=r;for(const y of a.slice(0,-1)){const x=l[y];if(!O(x)){l=void 0;break}const d=o.has(x)?x:{...x};o.add(d),l[y]=d,l=d}!l||l[h]===void 0||l[h]===null||(s.push({keys:a,value:l[h]}),i+=jsonBytes(l[h]),l[h]=null)}return s.length?{body:r,parts:s,bytes:i}:void 0}m(P,"K"),f(P,"holdWhole");function U(e,n){for(const{keys:r,value:o}of n){let s=e;for(const i of r.slice(0,-1)){const u=s[i],a=O(u)?u:{};s[i]=a,s=a}s[r[r.length-1]]=o}return e}m(U,"z"),f(U,"putBack");export function fitAnswer(e,n,r={}){if(!Number.isFinite(n)||e===null||typeof e!="object")return{value:e};const o=jsonBytes(e);if(o<=n)return{value:e};const s=r.whole?.length&&O(e)?P(e,r.whole):void 0,i=s?s.body:e,u=s?jsonBytes(i):o,a=s?Math.max(MIN_ANSWER_BUDGET_BYTES,n-s.bytes):n;if(u<=a)return{value:e};const h=[];let l=0,y=0,x=!1,d;const b=f(()=>(d={budget:n,original:o,...h.length?{lists:h}:{},...l?{shortened:l}:{},...y?{repeated:y}:{},...x?{clamped:!0}:{},...s?{whole:s.parts.map(t=>t.keys.join("."))}:{},...r.more?{more:r.more}:{},note:cutNote({lists:h,more:r.more})},d),"describe"),E=f(t=>({value:s?U(t,s.parts):t,cut:d}),"done");if(Array.isArray(i)){const t=fitList(i,a);return t.kept!=="all"&&h.push({list:"items",total:t.total,returned:t.returned,kept:t.kept}),l=t.shortenedStrings,y=t.repeatedStrings,b(),E(t.items)}if(!O(i))return{value:e};const _=Object.keys(i),$=_.filter(t=>Array.isArray(i[t])&&i[t].length>0),k=$.map(t=>jsonBytes(i[t])),j=u-k.reduce((t,p)=>t+p,0),c=shareBudget(k,a-j-C),w={};$.forEach((t,p)=>{if(k[p]<=c[p])return;const g=fitList(i[t],c[p],{name:t,...r.newest?.[t]?{newest:r.newest[t]}:{}});w[t]=g.items,g.kept!=="all"&&h.push({list:t,total:g.total,returned:g.returned,kept:g.kept}),l+=g.shortenedStrings,y+=g.repeatedStrings});const T=f(t=>({[ANSWER_CUT_KEY]:b(),...t}),"assemble"),M={};for(const t of _)M[t]=t in w?w[t]:i[t];let A=T(M);if(jsonBytes(A)<=a)return E(A);x=!0;let B=Math.max(512,a-C);for(let t=0;t<6;t++){if(A=T(F(M,B)),jsonBytes(A)<=a)return E(A);B=Math.floor(B*.6)}const N={};let v=C;for(const t of _){const p=i[t];if(p!==null&&typeof p=="object")continue;const g=jsonBytes(p)+utf8Bytes(t)+4;if(v+g>a)break;N[t]=p,v+=g}return E(T(N))}m(fitAnswer,"fitAnswer"),f(fitAnswer,"fitAnswer");
@@ -1 +1 @@
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");
1
+ "use strict";var l=Object.defineProperty;var i=(t,r)=>l(t,"name",{value:r,configurable:!0});var S=Object.defineProperty,u=i((t,r)=>S(t,"name",{value:r,configurable:!0}),"u");export const MAX_BUS_GENERATIONS=20,BUS_ROTATE_CHECK_BYTES=1048576;export function busCapsFromEnv(t=process.env){const r=Number(t.LENSMCP_EVENT_MAX_BYTES),e=Number(t.LENSMCP_EVENT_MAX_FILES);return{maxBytes:Number.isFinite(r)&&r>0?r:50*1024*1024,maxFiles:Number.isFinite(e)&&e>=1&&e<=20?Math.floor(e):5}}i(busCapsFromEnv,"busCapsFromEnv"),u(busCapsFromEnv,"busCapsFromEnv");export function rotateBusFile(t,r){const{fs:e,maxBytes:y,maxFiles:a}=r,n=`${t}.rotate.lock`,o=r.staleLockMs??3e4;let s;for(let c=0;c<2&&s===void 0;c++)try{s=e.openSync(n,"wx")}catch{try{if(Date.now()-e.statSync(n).mtimeMs<=o)return"busy";e.unlinkSync(n)}catch{}}if(s===void 0)return"busy";try{try{if(e.statSync(t).size<=y)return"not-needed"}catch{return"not-needed"}try{e.unlinkSync(`${t}.${a}`)}catch{}for(let c=a+1;c<=20;c++)try{e.unlinkSync(`${t}.${c}`)}catch{}for(let c=a-1;c>=1;c--)try{e.renameSync(`${t}.${c}`,`${t}.${c+1}`)}catch{}try{e.renameSync(t,`${t}.1`)}catch{}return"rotated"}finally{try{e.closeSync(s)}catch{}try{e.unlinkSync(n)}catch{}}}i(rotateBusFile,"rotateBusFile"),u(rotateBusFile,"rotateBusFile");export function createBusRotator(t,r){const{fs:e,maxBytes:y}=r,a=Math.max(0,Math.min(r.checkEveryBytes??1048576,y));let n=a,o=0;return s=>{if(n>=a||o+n>y)try{o=e.statSync(t).size,n=0,o>y&&rotateBusFile(t,r)==="rotated"&&(o=0)}catch{}n+=s}}i(createBusRotator,"createBusRotator"),u(createBusRotator,"createBusRotator");
@@ -1 +1 @@
1
- "use strict";var A=Object.defineProperty;var s=(r,e)=>A(r,"name",{value:e,configurable:!0});var S=Object.defineProperty,p=s((r,e)=>S(r,"name",{value:e,configurable:!0}),"s"),g=Object.defineProperty,n=p((r,e)=>g(r,"name",{value:e,configurable:!0}),"s");export const CAPTURE_FILE_NAME="capture.json",CAPTURE_OFF_EVERY_MS=2e3;export function readCaptureOff(r){return readCapture(r).off}s(readCaptureOff,"readCaptureOff"),p(readCaptureOff,"readCaptureOff"),n(readCaptureOff,"readCaptureOff");export function readCapture(r){const e=new Map;try{const t=JSON.parse(r);if(t.parts&&typeof t.parts=="object"&&!Array.isArray(t.parts))for(const[o,u]of Object.entries(t.parts))Array.isArray(u)&&e.set(o,new Set(u.filter(c=>typeof c=="string")));return{off:new Set(Array.isArray(t.off)?t.off.filter(o=>typeof o=="string"&&o.length>0):[]),parts:e}}catch{return{off:new Set,parts:e}}}s(readCapture,"readCapture"),p(readCapture,"readCapture"),n(readCapture,"readCapture");export function isRecordOff(r,e,t){return!r.size||typeof e!="string"?!1:r.has(e)||typeof t=="string"&&r.has(`${e}:${t}`)}s(isRecordOff,"isRecordOff"),p(isRecordOff,"isRecordOff"),n(isRecordOff,"isRecordOff");export function createCaptureOff(r,e,t={}){const o=t.everyMs??2e3,u=t.now??(()=>Date.now());let c=-1/0,y,O=new Set,d=new Map;const i=n(()=>{y=void 0,O=new Set,d=new Map},"none"),C=n(a=>{c=a;const f=r();if(!f)return i();let h;try{h=e.statSync(f).mtimeMs}catch{return i()}if(h!==y)try{({off:O,parts:d}=readCapture(e.readFileSync(f,"utf8"))),y=h}catch{i()}},"refresh"),w=n(()=>{const a=u();a-c>=o&&C(a)},"look"),l=n(((a,f)=>{try{return w(),isRecordOff(O,a,f)}catch{return!1}}),"ask");return l.part=(a,f)=>{try{return w(),!!a&&d.get(a)?.has(f)===!0}catch{return!1}},l.reset=()=>{c=-1/0,i()},l}s(createCaptureOff,"createCaptureOff"),p(createCaptureOff,"createCaptureOff"),n(createCaptureOff,"createCaptureOff");
1
+ "use strict";var d=Object.defineProperty;var s=(r,t)=>d(r,"name",{value:t,configurable:!0});var S=Object.defineProperty,a=s((r,t)=>S(r,"name",{value:t,configurable:!0}),"s");export const CAPTURE_FILE_NAME="capture.json",CAPTURE_OFF_EVERY_MS=2e3;export function readCaptureOff(r){return readCapture(r).off}s(readCaptureOff,"readCaptureOff"),a(readCaptureOff,"readCaptureOff");export function readCapture(r){const t=new Map;try{const e=JSON.parse(r);if(e.parts&&typeof e.parts=="object"&&!Array.isArray(e.parts))for(const[o,p]of Object.entries(e.parts))Array.isArray(p)&&t.set(o,new Set(p.filter(c=>typeof c=="string")));return{off:new Set(Array.isArray(e.off)?e.off.filter(o=>typeof o=="string"&&o.length>0):[]),parts:t}}catch{return{off:new Set,parts:t}}}s(readCapture,"readCapture"),a(readCapture,"readCapture");export function isRecordOff(r,t,e){return!r.size||typeof t!="string"?!1:r.has(t)||typeof e=="string"&&r.has(`${t}:${e}`)}s(isRecordOff,"isRecordOff"),a(isRecordOff,"isRecordOff");export function createCaptureOff(r,t,e={}){const o=e.everyMs??2e3,p=e.now??(()=>Date.now());let c=-1/0,u,y=new Set,h=new Map;const i=a(()=>{u=void 0,y=new Set,h=new Map},"none"),O=a(n=>{c=n;const f=r();if(!f)return i();let l;try{l=t.statSync(f).mtimeMs}catch{return i()}if(l!==u)try{({off:y,parts:h}=readCapture(t.readFileSync(f,"utf8"))),u=l}catch{i()}},"refresh"),A=a(()=>{const n=p();n-c>=o&&O(n)},"look"),w=a(((n,f)=>{try{return A(),isRecordOff(y,n,f)}catch{return!1}}),"ask");return w.part=(n,f)=>{try{return A(),!!n&&h.get(n)?.has(f)===!0}catch{return!1}},w.reset=()=>{c=-1/0,i()},w}s(createCaptureOff,"createCaptureOff"),a(createCaptureOff,"createCaptureOff");
package/lib/event-bus.js CHANGED
@@ -1 +1 @@
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}}
1
+ "use strict";var o=Object.defineProperty;var n=(e,t)=>o(e,"name",{value:t,configurable:!0});var c=Object.defineProperty,h=n((e,t)=>c(e,"name",{value:t,configurable:!0}),"e");export class EventBus{static{n(this,"EventBus")}static{h(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 s=t;if(this.transform)try{s=this.transform(t)??t}catch{s=t}for(const r of this.subs)if(!(r.filter&&!r.filter(s)))try{const i=r.handler(s);i&&typeof i.then=="function"&&i.catch(()=>{})}catch{}}subscribe(t,s){const r={handler:t,filter:s};return this.subs.add(r),()=>{this.subs.delete(r)}}droppedCount(){return this.dropped}subscriberCount(){return this.subs.size}}
@@ -1 +1 @@
1
- "use strict";var g=Object.defineProperty;var c=(e,o)=>g(e,"name",{value:o,configurable:!0});var x=Object.defineProperty,m=c((e,o)=>x(e,"name",{value:o,configurable:!0}),"m"),v=Object.defineProperty,p=m((e,o)=>v(e,"name",{value:o,configurable:!0}),"u");import{LOOP_STARTUP_MS as O,loopStartedAt as b}from"@lensmcp/protocol-types";export const LOOP_SAMPLE_MS=5e3,LOOP_ROLLUP_MS=3e5,LOOP_SAMPLE_HOURS=6;const L=720,f=p(e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,"finite");export function parseLoopSamples(e){if(!Array.isArray(e))return[];const o=new Map;for(const r of e.slice(-L)){if(!Array.isArray(r)||r.length<5)continue;const[a,s,t,i,n]=r;!f(a)||a<=0||!f(s)||!f(t)||!f(i)||!f(n)||o.set(a,[a,s,t,i,Math.min(1,n)])}return[...o.values()].sort((r,a)=>r[0]-a[0])}c(parseLoopSamples,"parseLoopSamples"),m(parseLoopSamples,"parseLoopSamples"),p(parseLoopSamples,"parseLoopSamples");export const rollupOf=p(e=>({at:e[0],n:1,meanSum:e[1],p99:e[2],max:e[3],utilSum:e[4]}),"rollupOf");export function bucketRollups(e,o){const r=Math.max(1,Math.floor(o)),a=new Map;for(const t of e){if(!(t.n>0))continue;const i=Math.floor(t.at/r)*r,n=a.get(i);n?(n.n+=t.n,n.meanSum+=t.meanSum,n.utilSum+=t.utilSum,n.p99=Math.max(n.p99,t.p99),n.max=Math.max(n.max,t.max)):a.set(i,{...t,at:i})}const s=p((t,i)=>Number(t.toFixed(i)),"round");return[...a.values()].sort((t,i)=>t.at-i.at).map(t=>[t.at,s(t.meanSum/t.n,2),s(t.p99,2),s(t.max,2),s(t.utilSum/t.n,4)])}c(bucketRollups,"bucketRollups"),m(bucketRollups,"bucketRollups"),p(bucketRollups,"bucketRollups");const d=[5,10,15,30,60,120,300,600,900,1800,3600,7200,21600,43200,86400].map(e=>e*1e3);export function historyStep(e,o){const r=Math.max(o.minMs,o.requestedMs??0,e/(o.maxPoints??400));return d.find(a=>a>=r&&a%o.minMs===0)??d[d.length-1]}c(historyStep,"historyStep"),m(historyStep,"historyStep"),p(historyStep,"historyStep");export function historySource(e,o,r=LOOP_SAMPLE_HOURS){return e>=o-r*36e5-6e4?"samples":"rollups"}c(historySource,"historySource"),m(historySource,"historySource"),p(historySource,"historySource");export function bucketStalls(e,o){const r=Math.max(1,Math.floor(o)),a=new Map;for(const s of e){const t=Math.floor(s.startAt/r)*r,i=b(s.loopId),n=i!==void 0&&s.startAt<i+O,l=`${s.loopId}\0${t}\0${n}`,u=a.get(l);u?(u.count++,u.longestMs=Math.max(u.longestMs,s.durationMs),u.unresponsive||=s.unresponsive):a.set(l,{loopId:s.loopId,project:s.project,runtime:s.runtime,at:t,count:1,longestMs:s.durationMs,unresponsive:s.unresponsive,...n?{startup:!0}:{}})}return[...a.values()].sort((s,t)=>s.at-t.at||s.loopId.localeCompare(t.loopId)||+!!s.startup-+!!t.startup)}c(bucketStalls,"bucketStalls"),m(bucketStalls,"bucketStalls"),p(bucketStalls,"bucketStalls");export class LoopSampleRing{static{c(this,"LoopSampleRing")}static{m(this,"LoopSampleRing")}static{p(this,"LoopSampleRing")}constructor(o=36e5,r=4e4){this.keepMs=o,this.maxSamples=r,this.rings=new Map,this.total=0,this.touches=0}add(o,r,a=Date.now()){const s=a-this.keepMs;let t=this.rings.get(o.id),i=0;for(const n of r){if(n[0]<s)continue;t||this.rings.set(o.id,t={loop:o,samples:[],touched:0});const l=t.samples,u=l[l.length-1];if(!u||n[0]>u[0])l.push(n);else{let h=0,S=l.length;for(;h<S;){const M=h+S>>1;l[M][0]<n[0]?h=M+1:S=M}if(l[h]?.[0]===n[0])continue;l.splice(h,0,n)}i++}return t&&i&&(t.loop=o,t.touched=++this.touches,this.total+=i),this.trim(s),i}read(o,r,a=Date.now()){this.trim(a-this.keepMs);const s=[];for(const t of this.rings.values()){const i=t.samples.filter(n=>n[0]>=o&&n[0]<r);i.length&&s.push({loop:t.loop,samples:i})}return s}get size(){return this.total}trim(o){for(const[r,a]of this.rings){let s=0;for(;s<a.samples.length&&a.samples[s][0]<o;)s++;s&&(a.samples.splice(0,s),this.total-=s),a.samples.length||this.rings.delete(r)}if(!(this.total<=this.maxSamples))for(const r of[...this.rings.values()].sort((a,s)=>a.touched-s.touched)){if(this.total<=this.maxSamples)break;this.total-=r.samples.length,this.rings.delete(r.loop.id)}}}
1
+ "use strict";var d=Object.defineProperty;var m=(n,e)=>d(n,"name",{value:e,configurable:!0});var g=Object.defineProperty,p=m((n,e)=>g(n,"name",{value:e,configurable:!0}),"u");import{LOOP_STARTUP_MS as x,loopStartedAt as v}from"@lensmcp/protocol-types";export const LOOP_SAMPLE_MS=5e3,LOOP_ROLLUP_MS=3e5,LOOP_SAMPLE_HOURS=6;const O=720,h=p(n=>typeof n=="number"&&Number.isFinite(n)&&n>=0,"finite");export function parseLoopSamples(n){if(!Array.isArray(n))return[];const e=new Map;for(const a of n.slice(-O)){if(!Array.isArray(a)||a.length<5)continue;const[o,s,t,r,i]=a;!h(o)||o<=0||!h(s)||!h(t)||!h(r)||!h(i)||e.set(o,[o,s,t,r,Math.min(1,i)])}return[...e.values()].sort((a,o)=>a[0]-o[0])}m(parseLoopSamples,"parseLoopSamples"),p(parseLoopSamples,"parseLoopSamples");export const rollupOf=p(n=>({at:n[0],n:1,meanSum:n[1],p99:n[2],max:n[3],utilSum:n[4]}),"rollupOf");export function bucketRollups(n,e){const a=Math.max(1,Math.floor(e)),o=new Map;for(const t of n){if(!(t.n>0))continue;const r=Math.floor(t.at/a)*a,i=o.get(r);i?(i.n+=t.n,i.meanSum+=t.meanSum,i.utilSum+=t.utilSum,i.p99=Math.max(i.p99,t.p99),i.max=Math.max(i.max,t.max)):o.set(r,{...t,at:r})}const s=p((t,r)=>Number(t.toFixed(r)),"round");return[...o.values()].sort((t,r)=>t.at-r.at).map(t=>[t.at,s(t.meanSum/t.n,2),s(t.p99,2),s(t.max,2),s(t.utilSum/t.n,4)])}m(bucketRollups,"bucketRollups"),p(bucketRollups,"bucketRollups");const S=[5,10,15,30,60,120,300,600,900,1800,3600,7200,21600,43200,86400].map(n=>n*1e3);export function historyStep(n,e){const a=Math.max(e.minMs,e.requestedMs??0,n/(e.maxPoints??400));return S.find(o=>o>=a&&o%e.minMs===0)??S[S.length-1]}m(historyStep,"historyStep"),p(historyStep,"historyStep");export function historySource(n,e,a=LOOP_SAMPLE_HOURS){return n>=e-a*36e5-6e4?"samples":"rollups"}m(historySource,"historySource"),p(historySource,"historySource");export function bucketStalls(n,e){const a=Math.max(1,Math.floor(e)),o=new Map;for(const s of n){const t=Math.floor(s.startAt/a)*a,r=v(s.loopId),i=r!==void 0&&s.startAt<r+x,l=`${s.loopId}\0${t}\0${i}`,u=o.get(l);u?(u.count++,u.longestMs=Math.max(u.longestMs,s.durationMs),u.unresponsive||=s.unresponsive):o.set(l,{loopId:s.loopId,project:s.project,runtime:s.runtime,at:t,count:1,longestMs:s.durationMs,unresponsive:s.unresponsive,...i?{startup:!0}:{}})}return[...o.values()].sort((s,t)=>s.at-t.at||s.loopId.localeCompare(t.loopId)||+!!s.startup-+!!t.startup)}m(bucketStalls,"bucketStalls"),p(bucketStalls,"bucketStalls");export class LoopSampleRing{static{m(this,"LoopSampleRing")}static{p(this,"LoopSampleRing")}constructor(e=36e5,a=4e4){this.keepMs=e,this.maxSamples=a,this.rings=new Map,this.total=0,this.touches=0}add(e,a,o=Date.now()){const s=o-this.keepMs;let t=this.rings.get(e.id),r=0;for(const i of a){if(i[0]<s)continue;t||this.rings.set(e.id,t={loop:e,samples:[],touched:0});const l=t.samples,u=l[l.length-1];if(!u||i[0]>u[0])l.push(i);else{let c=0,f=l.length;for(;c<f;){const M=c+f>>1;l[M][0]<i[0]?c=M+1:f=M}if(l[c]?.[0]===i[0])continue;l.splice(c,0,i)}r++}return t&&r&&(t.loop=e,t.touched=++this.touches,this.total+=r),this.trim(s),r}read(e,a,o=Date.now()){this.trim(o-this.keepMs);const s=[];for(const t of this.rings.values()){const r=t.samples.filter(i=>i[0]>=e&&i[0]<a);r.length&&s.push({loop:t.loop,samples:r})}return s}get size(){return this.total}trim(e){for(const[a,o]of this.rings){let s=0;for(;s<o.samples.length&&o.samples[s][0]<e;)s++;s&&(o.samples.splice(0,s),this.total-=s),o.samples.length||this.rings.delete(a)}if(!(this.total<=this.maxSamples))for(const a of[...this.rings.values()].sort((o,s)=>o.touched-s.touched)){if(this.total<=this.maxSamples)break;this.total-=a.samples.length,this.rings.delete(a.loop.id)}}}
package/lib/event-loop.js CHANGED
@@ -1 +1 @@
1
- "use strict";var q=Object.defineProperty;var v=(n,e)=>q(n,"name",{value:e,configurable:!0});var z=Object.defineProperty,b=v((n,e)=>z(n,"name",{value:e,configurable:!0}),"v"),C=Object.defineProperty,l=b((n,e)=>C(n,"name",{value:e,configurable:!0}),"l");import{lensOwnWork as L}from"@lensmcp/protocol-types";import{LoopSampleRing as N,parseLoopSamples as O}from"./event-loop-history.js";const I=l(n=>n&&typeof n=="object"&&!Array.isArray(n)?n:{},"object"),i=l(n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?n:void 0,"number"),r=l((n,e=250)=>typeof n=="string"&&n?n.slice(0,e):void 0,"text"),S=40;export function eventLoopIdentity(n){const e=I(n),t=r(e.id),o=r(e.project);if(!(!t||!o||e.runtime!=="node"&&e.runtime!=="browser"))return{id:t,project:o,runtime:e.runtime,...i(e.pid)!==void 0?{pid:i(e.pid)}:{},...i(e.threadId)!==void 0?{threadId:i(e.threadId)}:{},...r(e.tabId)?{tabId:r(e.tabId)}:{},...r(e.loadId)?{loadId:r(e.loadId)}:{}}}v(eventLoopIdentity,"eventLoopIdentity"),b(eventLoopIdentity,"eventLoopIdentity"),l(eventLoopIdentity,"eventLoopIdentity");export function eventLoopIncident(n){const e=I(n.raw);if(e.kind!=="event-loop-stall")return;const t=eventLoopIdentity(e.loop),o=i(e.startedAt),c=i(e.durationMs),s=e.mechanism;if(!t||o===void 0||c===void 0||!["callback","heartbeat","long-animation-frame","longtask"].includes(String(s)))return;const A=e.state==="unresponsive"?"unresponsive":e.state==="unknown"?"unknown":"recovered",m=[];for(const k of Array.isArray(e.scripts)?e.scripts.slice(0,8):[]){const u=I(k),a=r(u.url,512);a&&m.push({url:a,durationMs:i(u.durationMs)??0,startAt:i(u.startAt)??o,...r(u.functionName)?{functionName:r(u.functionName)}:{},...r(u.invoker)?{invoker:r(u.invoker)}:{}})}const f=r(e.cause,64),M=i(e.lensMs),x=i(e.deferredMs),h=L({durationMs:c,...f?{cause:f}:{},...M!==void 0?{lensMs:M}:{}}),w=s==="callback"&&!h?r(n.context?.flowId):void 0,g=h?void 0:r(n.context?.requestId);return{id:r(e.incidentId)??n.id,loop:t,startAt:o,durationMs:c,observedAt:n.timestamp,...A==="recovered"?{endAt:o+c}:{},state:A,mechanism:s,severity:h?"info":c>=1e3?"error":"warning",...w?{flowId:w}:{},...g?{requestId:g}:{},...r(e.callbackType)?{callbackType:r(e.callbackType)}:{},...f?{cause:f}:{},...M!==void 0?{lensMs:M}:{},...x?{deferredMs:x}:{},scripts:m,evidence:[],evidenceTruncated:e.scriptsTruncated===!0||(i(e.droppedIncidents)??0)>0||(i(e.floodSuppressed)??0)>0,explanation:h?`${h}. The pause is the lens's, not the app's: no flow ran it. What overlapped it waited behind it.`:s==="callback"?"Synchronous callback wall time, including any GC or process descheduling. Execution context identifies the flow; overlapping operations are not proven causes.":s==="heartbeat"?"The loop missed its heartbeat. The observer cannot identify executing code; overlapping work may have been delayed.":"Browser-measured main-thread work. Script timings identify contributing scripts where supported; overlapping flows are associated by time only."}}v(eventLoopIncident,"eventLoopIncident"),b(eventLoopIncident,"eventLoopIncident"),l(eventLoopIncident,"eventLoopIncident");export const HEARTBEAT_SETTLE_MS=5e3;const E=l(n=>n.endAt??Math.max(n.observedAt,n.startAt+n.durationMs),"endOf");function y(n,e){return n.loop.id!==e.loop.id||e.durationMs<=0?!1:Math.min(E(n),E(e))-Math.max(n.startAt,e.startAt)>=e.durationMs/2}v(y,"x"),b(y,"T"),l(y,"sameStall");export class EventLoopIndex{static{v(this,"EventLoopIndex")}static{b(this,"EventLoopIndex")}static{l(this,"EventLoopIndex")}constructor(e=()=>{},t=()=>{}){this.onChange=e,this.onSamples=t,this.incidents=new Map,this.unsettled=new Set,this.loops=new Map,this.recent=[],this.history=new N}ingest(e){const t=I(e.raw),o=r(t.kind)??e.source,c=eventLoopIdentity(t.loop);if(c){const a=this.loops.get(c.id);if(!a||e.timestamp>=a.lastSeen)for(this.loops.set(c.id,{loop:c,lastSeen:e.timestamp,state:t.state==="unresponsive"?"unresponsive":t.state==="unknown"?"unknown":"observed",coverage:r(t.coverage,500)??a?.coverage??(c.runtime==="node"?"Instrumented Node thread":"Browser main thread; supported PerformanceObserver entries"),...a?{meanMs:a.meanMs,maxMs:a.maxMs,p99Ms:a.p99Ms,utilization:a.utilization}:{},...i(t.lagMs)!==void 0?{meanMs:i(t.lagMs),maxMs:i(t.maxMs),p99Ms:i(t.p99Ms),utilization:i(t.utilization)}:{}});this.loops.size>200;)this.loops.delete(this.loops.keys().next().value);if(o==="event-loop-lag"){const d=O(t.samples);d.length&&(this.history.add(c,d),this.onSamples(c,d))}}const s=eventLoopIncident(e);if(s){if(this.settle(e.timestamp),s.mechanism==="heartbeat"){const d=[...this.incidents.values()].find(p=>p.mechanism==="callback"&&y(p,s));if(d){d.heartbeatMs!==s.durationMs&&(d.heartbeatMs=s.durationMs,this.onChange(d));return}}const a=this.incidents.get(s.id);if(a&&a.observedAt>s.observedAt)return;if(a&&(s.evidence=a.evidence.slice(),s.evidenceTruncated||=a.evidenceTruncated),s.mechanism==="callback")for(const[d,p]of this.incidents)p.mechanism!=="heartbeat"||!y(s,p)||(s.heartbeatMs=Math.max(s.heartbeatMs??0,p.durationMs),s.evidence=[...new Map([...p.evidence,...s.evidence].map(T=>[T.eventId,T])).values()].slice(0,S),s.evidenceTruncated||=p.evidenceTruncated,this.unsettled.delete(d)||(s.id=d,s.observedAt=Math.max(s.observedAt,p.observedAt+1)),this.incidents.delete(d));for(const d of this.recent)this.attach(s,d);for(this.incidents.set(s.id,s);this.incidents.size>200;){const d=this.incidents.keys().next().value;this.keep(d),this.incidents.delete(d)}s.mechanism==="heartbeat"?this.unsettled.add(s.id):this.onChange(s);return}if(o.startsWith("event-loop-"))return;const A=r(t.loopId);if(!A)return;const m=I(t.span),f=I(t.request),M=I(t.render),x=i(t.durationMs)??i(m.durationMs)??i(f.durationMs)??i(M.actualDurationMs)??0,h=i(t.startedAt)??i(m.startTime)??i(f.startedAt)??e.timestamp-x,w=i(m.syncDurationMs),g=i(m.syncStartedAt),k=w!==void 0&&w>=50&&g!==void 0,u={loopId:A,eventId:e.id,title:(e.title??o).slice(0,250),kind:o,startAt:k?g:h,endAt:k?g+w:h+x,...e.context?.flowId?{flowId:e.context.flowId}:{},...e.context?.requestId?{requestId:e.context.requestId}:{},relation:k?"executing":"overlap"};this.recent.push(u),this.recent.length>2e3&&this.recent.splice(0,this.recent.length-2e3);for(const a of this.incidents.values())this.attach(a,u)&&!this.unsettled.has(a.id)&&this.onChange(a)}keep(e){const t=this.incidents.get(e);t&&this.unsettled.delete(e)&&this.onChange(t)}settle(e=Date.now()){for(const t of[...this.unsettled]){const o=this.incidents.get(t);(!o||e-o.observedAt>=HEARTBEAT_SETTLE_MS)&&this.keep(t),o||this.unsettled.delete(t)}}attach(e,t){if(t.loopId!==e.loop.id||t.endAt<e.startAt||t.startAt>(e.endAt??e.observedAt)||e.evidence.some(s=>s.eventId===t.eventId))return!1;if(e.evidence.length>=S){const s=!e.evidenceTruncated;return e.evidenceTruncated=!0,s}const{loopId:o,...c}=t;return e.evidence.push(c),!0}statuses(e=Date.now()){return[...this.loops.values()].map(t=>({...t,state:e-t.lastSeen>9e4?"unknown":t.state})).sort((t,o)=>o.lastSeen-t.lastSeen)}list(e){return[...this.incidents.values()].filter(t=>!e||!L(t)&&(t.flowId===e||t.evidence.some(o=>o.flowId===e))).sort((t,o)=>o.startAt-t.startAt)}}let j=l(()=>[],"readIncidents");export function setFlowLoopIncidents(n){j=n}v(setFlowLoopIncidents,"setFlowLoopIncidents"),b(setFlowLoopIncidents,"setFlowLoopIncidents"),l(setFlowLoopIncidents,"setFlowLoopIncidents");export function flowLoopIncidents(n){return j(n)}v(flowLoopIncidents,"flowLoopIncidents"),b(flowLoopIncidents,"flowLoopIncidents"),l(flowLoopIncidents,"flowLoopIncidents");
1
+ "use strict";var q=Object.defineProperty;var v=(s,e)=>q(s,"name",{value:e,configurable:!0});var C=Object.defineProperty,l=v((s,e)=>C(s,"name",{value:e,configurable:!0}),"l");import{lensOwnWork as T}from"@lensmcp/protocol-types";import{LoopSampleRing as z,parseLoopSamples as j}from"./event-loop-history.js";const M=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"object"),i=l(s=>typeof s=="number"&&Number.isFinite(s)&&s>=0?s:void 0,"number"),a=l((s,e=250)=>typeof s=="string"&&s?s.slice(0,e):void 0,"text"),S=40;export function eventLoopIdentity(s){const e=M(s),t=a(e.id),o=a(e.project);if(!(!t||!o||e.runtime!=="node"&&e.runtime!=="browser"))return{id:t,project:o,runtime:e.runtime,...i(e.pid)!==void 0?{pid:i(e.pid)}:{},...i(e.threadId)!==void 0?{threadId:i(e.threadId)}:{},...a(e.tabId)?{tabId:a(e.tabId)}:{},...a(e.loadId)?{loadId:a(e.loadId)}:{}}}v(eventLoopIdentity,"eventLoopIdentity"),l(eventLoopIdentity,"eventLoopIdentity");export function eventLoopIncident(s){const e=M(s.raw);if(e.kind!=="event-loop-stall")return;const t=eventLoopIdentity(e.loop),o=i(e.startedAt),c=i(e.durationMs),n=e.mechanism;if(!t||o===void 0||c===void 0||!["callback","heartbeat","long-animation-frame","longtask"].includes(String(n)))return;const g=e.state==="unresponsive"?"unresponsive":e.state==="unknown"?"unknown":"recovered",m=[];for(const k of Array.isArray(e.scripts)?e.scripts.slice(0,8):[]){const u=M(k),r=a(u.url,512);r&&m.push({url:r,durationMs:i(u.durationMs)??0,startAt:i(u.startAt)??o,...a(u.functionName)?{functionName:a(u.functionName)}:{},...a(u.invoker)?{invoker:a(u.invoker)}:{}})}const f=a(e.cause,64),b=i(e.lensMs),A=i(e.deferredMs),h=T({durationMs:c,...f?{cause:f}:{},...b!==void 0?{lensMs:b}:{}}),I=n==="callback"&&!h?a(s.context?.flowId):void 0,w=h?void 0:a(s.context?.requestId);return{id:a(e.incidentId)??s.id,loop:t,startAt:o,durationMs:c,observedAt:s.timestamp,...g==="recovered"?{endAt:o+c}:{},state:g,mechanism:n,severity:h?"info":c>=1e3?"error":"warning",...I?{flowId:I}:{},...w?{requestId:w}:{},...a(e.callbackType)?{callbackType:a(e.callbackType)}:{},...f?{cause:f}:{},...b!==void 0?{lensMs:b}:{},...A?{deferredMs:A}:{},scripts:m,evidence:[],evidenceTruncated:e.scriptsTruncated===!0||(i(e.droppedIncidents)??0)>0||(i(e.floodSuppressed)??0)>0,explanation:h?`${h}. The pause is the lens's, not the app's: no flow ran it. What overlapped it waited behind it.`:n==="callback"?"Synchronous callback wall time, including any GC or process descheduling. Execution context identifies the flow; overlapping operations are not proven causes.":n==="heartbeat"?"The loop missed its heartbeat. The observer cannot identify executing code; overlapping work may have been delayed.":"Browser-measured main-thread work. Script timings identify contributing scripts where supported; overlapping flows are associated by time only."}}v(eventLoopIncident,"eventLoopIncident"),l(eventLoopIncident,"eventLoopIncident");export const HEARTBEAT_SETTLE_MS=5e3;const L=l(s=>s.endAt??Math.max(s.observedAt,s.startAt+s.durationMs),"endOf");function x(s,e){return s.loop.id!==e.loop.id||e.durationMs<=0?!1:Math.min(L(s),L(e))-Math.max(s.startAt,e.startAt)>=e.durationMs/2}v(x,"T"),l(x,"sameStall");export class EventLoopIndex{static{v(this,"EventLoopIndex")}static{l(this,"EventLoopIndex")}constructor(e=()=>{},t=()=>{}){this.onChange=e,this.onSamples=t,this.incidents=new Map,this.unsettled=new Set,this.loops=new Map,this.recent=[],this.history=new z}ingest(e){const t=M(e.raw),o=a(t.kind)??e.source,c=eventLoopIdentity(t.loop);if(c){const r=this.loops.get(c.id);if(!r||e.timestamp>=r.lastSeen)for(this.loops.set(c.id,{loop:c,lastSeen:e.timestamp,state:t.state==="unresponsive"?"unresponsive":t.state==="unknown"?"unknown":"observed",coverage:a(t.coverage,500)??r?.coverage??(c.runtime==="node"?"Instrumented Node thread":"Browser main thread; supported PerformanceObserver entries"),...r?{meanMs:r.meanMs,maxMs:r.maxMs,p99Ms:r.p99Ms,utilization:r.utilization}:{},...i(t.lagMs)!==void 0?{meanMs:i(t.lagMs),maxMs:i(t.maxMs),p99Ms:i(t.p99Ms),utilization:i(t.utilization)}:{}});this.loops.size>200;)this.loops.delete(this.loops.keys().next().value);if(o==="event-loop-lag"){const d=j(t.samples);d.length&&(this.history.add(c,d),this.onSamples(c,d))}}const n=eventLoopIncident(e);if(n){if(this.settle(e.timestamp),n.mechanism==="heartbeat"){const d=[...this.incidents.values()].find(p=>p.mechanism==="callback"&&x(p,n));if(d){d.heartbeatMs!==n.durationMs&&(d.heartbeatMs=n.durationMs,this.onChange(d));return}}const r=this.incidents.get(n.id);if(r&&r.observedAt>n.observedAt)return;if(r&&(n.evidence=r.evidence.slice(),n.evidenceTruncated||=r.evidenceTruncated),n.mechanism==="callback")for(const[d,p]of this.incidents)p.mechanism!=="heartbeat"||!x(n,p)||(n.heartbeatMs=Math.max(n.heartbeatMs??0,p.durationMs),n.evidence=[...new Map([...p.evidence,...n.evidence].map(y=>[y.eventId,y])).values()].slice(0,S),n.evidenceTruncated||=p.evidenceTruncated,this.unsettled.delete(d)||(n.id=d,n.observedAt=Math.max(n.observedAt,p.observedAt+1)),this.incidents.delete(d));for(const d of this.recent)this.attach(n,d);for(this.incidents.set(n.id,n);this.incidents.size>200;){const d=this.incidents.keys().next().value;this.keep(d),this.incidents.delete(d)}n.mechanism==="heartbeat"?this.unsettled.add(n.id):this.onChange(n);return}if(o.startsWith("event-loop-"))return;const g=a(t.loopId);if(!g)return;const m=M(t.span),f=M(t.request),b=M(t.render),A=i(t.durationMs)??i(m.durationMs)??i(f.durationMs)??i(b.actualDurationMs)??0,h=i(t.startedAt)??i(m.startTime)??i(f.startedAt)??e.timestamp-A,I=i(m.syncDurationMs),w=i(m.syncStartedAt),k=I!==void 0&&I>=50&&w!==void 0,u={loopId:g,eventId:e.id,title:(e.title??o).slice(0,250),kind:o,startAt:k?w:h,endAt:k?w+I:h+A,...e.context?.flowId?{flowId:e.context.flowId}:{},...e.context?.requestId?{requestId:e.context.requestId}:{},relation:k?"executing":"overlap"};this.recent.push(u),this.recent.length>2e3&&this.recent.splice(0,this.recent.length-2e3);for(const r of this.incidents.values())this.attach(r,u)&&!this.unsettled.has(r.id)&&this.onChange(r)}keep(e){const t=this.incidents.get(e);t&&this.unsettled.delete(e)&&this.onChange(t)}settle(e=Date.now()){for(const t of[...this.unsettled]){const o=this.incidents.get(t);(!o||e-o.observedAt>=HEARTBEAT_SETTLE_MS)&&this.keep(t),o||this.unsettled.delete(t)}}attach(e,t){if(t.loopId!==e.loop.id||t.endAt<e.startAt||t.startAt>(e.endAt??e.observedAt)||e.evidence.some(n=>n.eventId===t.eventId))return!1;if(e.evidence.length>=S){const n=!e.evidenceTruncated;return e.evidenceTruncated=!0,n}const{loopId:o,...c}=t;return e.evidence.push(c),!0}statuses(e=Date.now()){return[...this.loops.values()].map(t=>({...t,state:e-t.lastSeen>9e4?"unknown":t.state})).sort((t,o)=>o.lastSeen-t.lastSeen)}list(e){return[...this.incidents.values()].filter(t=>!e||!T(t)&&(t.flowId===e||t.evidence.some(o=>o.flowId===e))).sort((t,o)=>o.startAt-t.startAt)}}let E=l(()=>[],"readIncidents");export function setFlowLoopIncidents(s){E=s}v(setFlowLoopIncidents,"setFlowLoopIncidents"),l(setFlowLoopIncidents,"setFlowLoopIncidents");export function flowLoopIncidents(s){return E(s)}v(flowLoopIncidents,"flowLoopIncidents"),l(flowLoopIncidents,"flowLoopIncidents");
@@ -1 +1 @@
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};
1
+ "use strict";var u=Object.defineProperty;var o=(r,t)=>u(r,"name",{value:t,configurable:!0});var l=Object.defineProperty,i=o((r,t)=>l(r,"name",{value:t,configurable:!0}),"a");import{MAX_MESSAGE_CHARS as S,MAX_TITLE_CHARS as T,redactDeep as y,redactSqlParams as _,redactText as p,safeText as E,safeTitle as g}from"./redact.js";export const BUS_REDACT_MAX_DEPTH=12;export function createEventRedactor(r={}){const t=r.maxDepth??BUS_REDACT_MAX_DEPTH;let s=0,a=0;return{redact(e){s+=1;const c=e.title===void 0?void 0:g(p(e.title)),n=e.message===void 0?void 0:E(p(e.message),S),d=e.raw===void 0?void 0:v(y(e.raw,0,t)),A=c!==e.title,f=n!==e.message,m=d!==e.raw;return!A&&!f&&!m?e:(a+=1,{...e,...c!==void 0?{title:c}:{},...n!==void 0?{message:n}:{},...d!==void 0?{raw:d}:{}})},stats:i(()=>({inspected:s,redacted:a}),"stats"),reset:i(()=>{s=0,a=0},"reset")}}o(createEventRedactor,"createEventRedactor"),i(createEventRedactor,"createEventRedactor");function v(r){if(!r||typeof r!="object"||Array.isArray(r))return r;const t=r,s=t.query,a=t.params;if(typeof s!="string"||!Array.isArray(a))return r;const e=_(s,a);return e===a?r:{...t,params:e}}o(v,"T"),i(v,"redactSqlShape");export{T as MAX_TITLE_CHARS};
@@ -1 +1 @@
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");
1
+ "use strict";var a=Object.defineProperty;var r=(n,e)=>a(n,"name",{value:e,configurable:!0});var f=Object.defineProperty,i=r((n,e)=>f(n,"name",{value:e,configurable:!0}),"e");const l=2166136261,u=16777619;function o(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}r(o,"i"),i(o,"fnv1a32");export function fingerprint(n){const e=[n.kind,n.identity,n.file??"",n.detail??""];return`${n.kind}:${o(e.join("|"))}`}r(fingerprint,"fingerprint"),i(fingerprint,"fingerprint");
@@ -1 +1 @@
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");
1
+ "use strict";var M=Object.defineProperty;var c=(e,t)=>M(e,"name",{value:t,configurable:!0});var T=Object.defineProperty,s=c((e,t)=>T(e,"name",{value:t,configurable:!0}),"s");export const CATEGORY_ORDER=["user-action","page-load","navigation","api","ai","background","test","system","other"];const p=new Map;export function globMatch(e,t){let o=p.get(e);return o||(o=new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")}$`),p.size>500&&p.clear(),p.set(e,o)),o.test(t)}c(globMatch,"globMatch"),s(globMatch,"globMatch");const F=s(e=>/^[A-Z]+ /.test(e),"hasMethod");function w(e,t){return t.some(o=>o.route?F(e)?globMatch(e,`${o.method??"GET"} ${o.route}`):globMatch(e,o.route):!1)}c(w,"$"),s(w,"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&&!w(e.route,t.segments)||e.project!==void 0&&!t.segments.some(o=>o.projects.some(n=>globMatch(e.project,n))))}c(m,"b"),s(m,"ruleMatches");const y=s(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),g=s(e=>typeof e=="string"&&e!==""?e:void 0,"str"),f=s(e=>y(e.raw)?g(e.raw.kind)??"":"","kindOf"),k=s((e,t)=>{const o=Number(e.timestamp)||0,n=Number(t.timestamp)||0;return o<n||o===n&&e.id<t.id},"earlier");function $(e){let t,o;for(const a of e)f(a)==="flow-origin"&&(!t||k(a,t))&&(t=a),g(a.context?.originType)&&(!o||k(a,o))&&(o=a);const n=t??o;if(!n)return{};const r=y(n.raw)?n.raw:{},i=g(n.context?.originType)??(t?g(n.title):void 0),u=g(r.originNodeId)??g(n.context?.originNodeId);return{...i?{type:i}:{},...u?{nodeId:u}:{}}}c($,"O"),s($,"originOf");const S=/^(verify|e2e|test|smoke|load)[-_:]/i,z=s((e,t)=>S.test(e)||t!==void 0&&/^(ui:)?(tools|scripts?|e2e)\//.test(t),"isTestFlow"),x={"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"},A=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"),s(templatePath,"templatePath");function I(e){const t=/^ui:(?:.*\/)?([^/:]+?)(?:\.[a-z]+)?:\d+:([A-Za-z]+)$/.exec(e);return t?`${t[1]} \xB7 ${t[2]}`:e}c(I,"q"),s(I,"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"),s(scriptFamily,"scriptFamily");function j(e,t,o,n){const r=t.nodeId,i=r?/^(page|route|ambient):(.*)$/.exec(r):null;if(i)return`${i[1]}:${templatePath(i[2])}`;if(t.type&&x[t.type]==="user-action"&&r)return I(r);if(e==="test")return scriptFamily(o.flowId);const u=o.segments.find(l=>l.kind==="request"&&l.route);if(u?.route)return`${u.method??"GET"} ${templatePath(u.route)}`;const a=n.find(l=>f(l)==="ai-call");return a&&y(a.raw)?`ai \xB7 ${g(a.raw.model)??g(a.raw.provider)??"call"}`:r?templatePath(r):void 0}c(j,"R"),s(j,"subjectOf");const _=10,B=1e3,N=3,R=500,C=1e3;function q(e,t){const o=new Set,n=t.segments.filter(i=>i.kind==="request");t.segments.some(i=>i.counts.errors>0)&&o.add("has-error"),n.some(i=>i.durationMs>=B)&&o.add("slow"),n.length>=_&&o.add("fan-out"),new Set(t.segments.flatMap(i=>i.projects)).size>=3&&o.add("multi-service"),e.some(i=>f(i)==="queue-enqueued")&&o.add("queue"),e.some(i=>f(i)==="ai-call"||i.source==="ai")&&o.add("ai"),t.stats.bookkeeping>=R&&t.stats.bookkeeping*2>=t.stats.events&&o.add("storm"),t.stats.events>=C&&o.add("large");const r=new Map;for(const i of n)(!i.part||i.part.index===1)&&r.set(i.label,(r.get(i.label)??0)+1);return[...r.values()].some(i=>i>=N)&&o.add("repeated-requests"),[...o].sort()}c(q,"G"),s(q,"tagsOf");export function classifyFlow(e,t,o=[]){const n=$(e),r={flowId:t.flowId,origin:n,segments:t.segments},i=q(e,t),u=s((d,O,b)=>{const h=j(d,n,t,e);return{category:d,decidedBy:O,...b!==void 0?{ruleIndex:b}:{},tags:i,origin:n,...h?{subject:h}:{}}},"done"),a=o.findIndex(d=>d.category&&m(d,r));if(a!==-1)return u(o[a].category,"rule",a);if(z(t.flowId,n.nodeId))return u("test","test");const l=n.type?x[n.type]:void 0;if(l)return u(l,"origin");if(i.includes("ai"))return u("ai","shape");const v=t.segments.filter(d=>d.kind==="request");return v.length>0?u(v.every(d=>d.requestId?.startsWith("job:"))?"background":"api","shape"):t.segments.length>0&&t.segments.every(d=>d.kind==="ambient")?u("system","shape"):u("other","shape")}c(classifyFlow,"classifyFlow"),s(classifyFlow,"classifyFlow");export function categoryOfSegment(e,t,o=[]){const n=o.find(r=>r.category&&(r.route!==void 0||r.project!==void 0)&&r.flowId===void 0&&r.origin===void 0&&r.originType===void 0&&m(r,{flowId:e.flowId,origin:t.origin,segments:[e]}));return n?n.category:e.kind==="request"?e.requestId?.startsWith("job:")?"background":"api":e.kind==="ambient"?"system":e.kind==="origin"&&A.has(t.category)?t.category:"ui"}c(categoryOfSegment,"categoryOfSegment"),s(categoryOfSegment,"categoryOfSegment");export function groupFlows(e){return groupByCategory(e).map(t=>{const o=new Map;for(const r of t.items){const i=o.get(r.subject);i?i.push(r):o.set(r.subject,[r])}const n=[...o.entries()].sort((r,i)=>(r[0]===void 0?1:0)-(i[0]===void 0?1:0)||i[1].length-r[1].length||String(r[0]).localeCompare(String(i[0]))).map(([r,i])=>({subject:r,count:i.length,items:i}));return{...t,subjects:n}})}c(groupFlows,"groupFlows"),s(groupFlows,"groupFlows");export function groupByCategory(e){const t=new Map;for(const n of e){const r=t.get(n.category);r?r.push(n):t.set(n.category,[n])}const o=s(n=>{const r=CATEGORY_ORDER.indexOf(n);return r===-1?CATEGORY_ORDER.length:r},"rank");return[...t.entries()].sort((n,r)=>o(n[0])-o(r[0])||(n[0]<r[0]?-1:n[0]>r[0]?1:0)).map(([n,r])=>({category:n,count:r.length,items:r}))}c(groupByCategory,"groupByCategory"),s(groupByCategory,"groupByCategory");
@@ -1 +1 @@
1
- "use strict";var ne=Object.defineProperty;var k=(e,t)=>ne(e,"name",{value:t,configurable:!0});var se=Object.defineProperty,w=k((e,t)=>se(e,"name",{value:t,configurable:!0}),"w"),oe=Object.defineProperty,p=w((e,t)=>oe(e,"name",{value:t,configurable:!0}),"p");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 re=new Set(["react","valtio","client-runtime","chrome","visual"]),O=p(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),b=p(e=>typeof e=="string"&&e!==""?e:void 0,"str"),$=p(e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,"num"),Y=new WeakMap;function A(e){let t=Y.get(e);return t||(t=T(e),Y.set(e,t)),t}k(A,"A"),w(A,"K"),p(A,"itemOf");function T(e){const t=O(e.raw)?e.raw:{},n=O(t.request)?t.request:{},o=O(t.span)?t.span:{},r=e.context??{},s=b(t.kind)??"",l=s===SQL_ACCOUNT_KIND,g=(l?$(t.lastEndedAt):void 0)??$(e.timestamp)??0,I=$(n.startedAt)??$(o.startTime)??$(t.startedAt)??(l?$(t.firstStartedAt):void 0),q=$(n.endedAt)??$(o.endTime)??(I!==void 0&&$(t.durationMs)!==void 0?I+t.durationMs:void 0),M=Math.min(g,I??g),j=Math.max(g,q??g),y=O(t.render)?t.render:{},c=O(t.update)?t.update:{},a=s==="render"?b(y.componentName):s==="state-update"?b(c.path)?.split(".").slice(0,2).join("."):void 0,d=b(t.queue),u=b(t.jobId),f=String(e.source),i=b(t.project)??b(r.projectName),m=s==="fetch-start"||s==="fetch-done"||s==="gateway-request";return{event:e,id:e.id,ts:g,from:M,to:j,kind:s,source:f,requestId:b(r.requestId),parentRequestId:b(r.parentRequestId),queueKey:d&&u?`${d}#${u}`:void 0,browser:re.has(f)||f==="memory"&&i===void 0,bookkeeping:FLOW_BOOKKEEPING_KINDS.has(s),project:i,subject:a,route:m?G(b(t.url)):s==="server-request"?b(n.route):void 0,method:m?b(t.method):s==="server-request"?b(n.method):void 0}}k(T,"_"),w(T,"C"),p(T,"readItem");function G(e){if(!e)return;const t=e.search(/[?#]/),n=t===-1?e:e.slice(0,t),o=/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$/i.exec(n);return o?o[1]??"/":n}k(G,"B"),w(G,"P"),p(G,"pathOnly");const ie=p(e=>e.split(".")[0],"rootOf"),Z=p((e,t)=>e.reduce((n,o)=>Math.min(n,t(o)),1/0),"minOf"),H=p((e,t)=>e.reduce((n,o)=>Math.max(n,t(o)),-1/0),"maxOf"),_=p((e,t)=>e.ts-t.ts||(e.id<t.id?-1:e.id>t.id?1:0),"compare"),K=p(e=>e.requestId&&!e.requestId.startsWith("job:")?ie(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}k(B,"z"),w(B,"Q"),p(B,"jobKeyOf");function D(e,t){const n=e.filter(s=>!s.parentRequestId&&(s.kind==="server-request"||s.kind==="gateway-request"||s.kind==="fetch-start"||s.kind==="fetch-done")).sort((s,l)=>s.from-l.from||_(s,l));if(n.length<2)return[e];const o=[];for(const s of n){const l=o[o.length-1];l&&s.from<=l.to+t?l.to=Math.max(l.to,s.to):o.push({from:s.from,to:s.to})}if(o.length<2)return[e];const r=o.map(()=>[]);for(const s of e)r[t>=0?U(o,s.ts,t):P(o,s.ts,t)].push(s);return r.filter(s=>s.length>0)}k(D,"C"),w(D,"V"),p(D,"occurrencesOf");function P(e,t,n){const o=e.findIndex(s=>t>=s.from-n&&t<=s.to+n);if(o!==-1)return o;let r=0;for(let s=0;s<e.length;s+=1)e[s].from<=t&&(r=s);return r}k(P,"L"),w(P,"X"),p(P,"spanScan");function U(e,t,n){let o=0,r=e.length;for(;o<r;){const s=o+r>>1;e[s].to+n<t?o=s+1:r=s}if(o<e.length&&t>=e[o].from-n)return o;for(o=0,r=e.length;o<r;){const s=o+r>>1;e[s].from<=t?o=s+1:r=s}return Math.max(0,o-1)}k(U,"P"),w(U,"Y"),p(U,"spanAt");const ue=new Set(["server-request","gateway-request","fetch-done","fetch-error","queue-process"]),C="event-loop-stall";function N(e){let t=-1/0,n=!1;for(const r of e)ue.has(r.kind)?t=Math.max(t,r.to):r.kind===C&&(n=!0);if(!n||!Number.isFinite(t))return;let o;for(const r of e)r.kind===C&&r.from>=t&&(o??=new Map).set(r,Math.round(r.from-t));return o}k(N,"E"),w(N,"_"),p(N,"lateStallsOf");export function stallsAfterResponse(e){const t=new Map;if(!e.some(o=>O(o.raw)&&o.raw.kind===C))return t;const n=new Map;for(const o of e){const r=A(o),s=r.requestId?.startsWith("job:")?r.requestId:K(r);if(s===void 0)continue;const l=n.get(s);l?l.push(r):n.set(s,[r])}for(const o of n.values())for(const[r,s]of N(o)??[])t.set(r.id,s);return t}k(stallsAfterResponse,"stallsAfterResponse"),w(stallsAfterResponse,"stallsAfterResponse"),p(stallsAfterResponse,"stallsAfterResponse");function E(e,t){if(!t)return e;const n=e.filter(o=>!t.has(o));return n.length?n:e}k(E,"W"),w(E,"T"),p(E,"timedItems");const ee={debug:0,info:1,warning:2,error:3,fatal:4};function F(e,t){const n=[];let o=[];for(const r of e){const s=o[o.length-1];s&&r.ts-s.ts>=t&&(n.push(o),o=[]),o.push(r)}return o.length&&n.push(o),n}k(F,"F"),w(F,"F"),p(F,"runs");export function segmentFlow(e,t={}){const n={...DEFAULT_SEGMENT_OPTIONS};for(const[i,m]of Object.entries(t))typeof m=="number"&&Number.isFinite(m)&&(n[i]=m);const o=new Set,r=[];for(const i of e)o.has(i.id)||(o.add(i.id),r.push(A(i)));r.sort(_);const s=b(r[0]?.event.context?.flowId)??b(r[0]?.event.raw?.flowId)??"",l=new Map;for(const i of r)i.kind==="queue-enqueued"&&i.queueKey&&i.requestId&&!i.requestId.startsWith("job:")&&!l.has(i.queueKey)&&l.set(i.queueKey,i);const g=new Map,I=new Map,q=[];for(const i of r){const m=B(i),h=K(i);if(m!==void 0){const v=I.get(m);v?v.push(i):I.set(m,[i])}else if(h!==void 0){const v=g.get(h);v?v.push(i):g.set(h,[i])}else q.push(i)}const M=[],j=new Map;for(const[i,m]of g)D(m,n.occurrenceSlackMs).forEach((h,v)=>{const S={id:`${s}~r:${i}${v===0?"":`@${v+1}`}`,kind:"request",items:h,requestId:i};if(M.push(S),l.size)for(const x of h)x.kind==="queue-enqueued"&&j.set(x,S)});for(const[i,m]of I){const h=l.get(i),v=h?j.get(h):void 0;v?v.items.push(...m):M.push({id:`${s}~r:job:${i}`,kind:"request",items:m,requestId:`job:${i}`})}const y=r.filter(i=>i.kind==="fetch-done"&&K(i)!==void 0),c=new Map;for(const i of M)i.requestId&&c.set(i.requestId,[...c.get(i.requestId)??[],i]);const a=p((i,m)=>{const h=c.get(i);if(h)return h.find(v=>v.items.some(S=>S.kind==="fetch-done"&&S.ts===m))??h[h.length-1]},"owningUnit"),d=q.filter(i=>i.browser);for(const i of F(d,n.burstGapMs)){const m=i[0].ts,h=y.filter(x=>x.ts<=m&&m-x.ts<=n.attachWindowMs),v=[...new Set(h.map(x=>K(x)))];if(v.length===1){const x=a(v[0],h[h.length-1].ts);if(x){x.items.push(...i);continue}}const S=i.some(x=>x.kind==="flow-origin");M.push({id:`${s}~${S?"o":"u"}:${i[0].id}`,kind:S?"origin":"ui",items:i,...v.length>1?{after:v.sort()}:{}})}for(const i of F(q.filter(m=>!m.browser),n.phaseGapMs))M.push({id:`${s}~a:${i[0].id}`,kind:"ambient",items:i});const u=L(s,r.length,M,n),f=W(r);return f?{...u,sql:f}:u}k(segmentFlow,"segmentFlow"),w(segmentFlow,"segmentFlow"),p(segmentFlow,"segmentFlow");function L(e,t,n,o){for(const c of n)c.items.sort(_);const r=new Map;for(const c of n){const a=c.kind==="request"?N(c.items):void 0;a&&r.set(c,a)}const s=n.map(c=>{const a=E(c.items,r.get(c));return{unit:c,from:Z(a,d=>d.from),to:H(a,d=>d.to)}});s.sort((c,a)=>c.from-a.from||(c.unit.id<a.unit.id?-1:1));const l=new Map;let g=0,I=-1/0;for(const c of s)(g===0||c.from-I>=o.phaseGapMs)&&(g+=1),I=Math.max(I,c.to),l.set(c.unit,g);const q=[];for(const c of s){const a=z(c.unit.items,o.maxSegmentEvents),d=c.unit.kind==="request"?W(c.unit.items):void 0;a.forEach((u,f)=>{const i=Q(e,c.unit,u,l.get(c.unit),a.length>1?{index:f+1,total:a.length}:void 0,r.get(c.unit));q.push(d&&f===0?{...i,sql:d}:i)})}const M={};for(const c of q)for(const a of c.eventIds)M[a]=c.id;const j=[];for(const c of q){let a=j[c.phase-1];a||(a={index:c.phase,start:c.start,end:c.end,segmentIds:[]},j[c.phase-1]=a),a.start=Math.min(a.start,c.start),a.end=Math.max(a.end,c.end),a.segmentIds.push(c.id)}const y=q.reduce((c,a)=>c+a.counts.signal,0);return{flowId:e,segments:q,phases:j.filter(Boolean),assignment:M,stats:{events:t,signal:y,bookkeeping:t-y,segments:q.length,phases:j.filter(Boolean).length,largestSegment:q.reduce((c,a)=>Math.max(c,a.counts.total),0)}}}k(L,"H"),w(L,"J"),p(L,"assemble");function z(e,t){if(e.filter(s=>!s.bookkeeping).length<=t)return[e];const n=[];let o=[],r=0;for(const s of e)!s.bookkeeping&&r===t&&(n.push(o),o=[],r=0),o.push(s),s.bookkeeping||(r+=1);return o.length&&n.push(o),n}k(z,"J"),w(z,"Z"),p(z,"chunk");function Q(e,t,n,o,r,s){const l={total:n.length,signal:0,bookkeeping:0,errors:0,warnings:0},g=new Set;let I="debug";for(const u of n){u.bookkeeping?l.bookkeeping+=1:l.signal+=1;const f=String(u.event.severity);f==="error"||f==="fatal"?l.errors+=1:f==="warning"&&(l.warnings+=1),(ee[f]??1)>(ee[I]??0)&&(I=f),u.project&&g.add(u.project)}const q=t.kind==="ui"||t.kind==="origin"?V(n):[],M=E(n,s),j=Z(M,u=>u.from),y=H(M,u=>u.to),c=s?n.filter(u=>s.has(u)).length:0,a=J(t.items),d=t.id;return{id:r&&r.index>1?`${d}#${r.index}`:d,flowId:e,kind:t.kind,label:X(t,n,a,r,q),phase:o,start:j,end:y,durationMs:y-j,eventIds:n.map(u=>u.id),counts:l,projects:[...g].sort(),...a.route?{route:a.route}:{},...a.method?{method:a.method}:{},...t.requestId?{requestId:t.requestId}:{},...t.after?{after:t.after}:{},...q.length?{hot:q}:{},...r?{part:r}:{},...c?{stallsAfterResponse:c}:{},worstSeverity:I}}k(Q,"V"),w(Q,"ee"),p(Q,"toSegment");function J(e){const t=e.find(n=>n.kind==="fetch-start"&&n.route)??e.find(n=>n.kind==="server-request"&&!n.parentRequestId&&n.route)??e.find(n=>n.kind==="gateway-request"&&n.route)??e.find(n=>n.kind==="fetch-done"&&n.route);return{...t?.route?{route:t.route}:{},...t?.method?{method:t.method.toUpperCase()}:{}}}k(J,"X"),w(J,"te"),p(J,"routeOf");function V(e){const t=new Map;for(const n of e)n.subject&&!n.bookkeeping&&t.set(n.subject,(t.get(n.subject)??0)+1);return[...t.entries()].sort((n,o)=>o[1]-n[1]||(n[0]<o[0]?-1:1)).slice(0,3).map(([n,o])=>o>1?`${n} \xD7${o}`:n)}k(V,"Y"),w(V,"ne"),p(V,"hotOf");function X(e,t,n,o,r){const s=o?` (part ${o.index}/${o.total})`:"";if(e.kind==="request"){if(n.route)return`${n.method?`${n.method} `:""}${n.route}${s}`;const l=t.find(g=>g.queueKey);return l?`job ${l.queueKey}${s}`:`request ${e.requestId??""}${s}`}return e.kind==="origin"?`${t.find(l=>l.kind==="flow-origin")?.event.title||"start"}${r.length?` \xB7 ${r.join(", ")}`:""}${s}`:e.kind==="ui"?`UI update${r.length?` \xB7 ${r.join(", ")}`:""}${s}`:`background${s}`}k(X,"Z"),w(X,"se"),p(X,"labelOf");const te=50;export function sqlAccountingOf(e){return R(e,!1)}k(sqlAccountingOf,"sqlAccountingOf"),w(sqlAccountingOf,"sqlAccountingOf"),p(sqlAccountingOf,"sqlAccountingOf");function W(e){return R(e.map(t=>t.event),!0)}k(W,"G"),w(W,"L"),p(W,"accountSqlOfItems");function R(e,t){const n=new Map,o=new Map,r=t?void 0:new Set;for(const d of e){if(r){if(r.has(d.id))continue;r.add(d.id)}const u=O(d.raw)?d.raw:{},f=b(u.kind),i=b(d.context?.requestId);if(!i)continue;const m=b(u.project)??b(d.context?.projectName);if(f==="db-query"&&d.source==="db"){const h=o.get(i)??{count:0,workMs:0,...m?{project:m}:{}};h.count+=1,h.workMs+=$(u.durationMs)??0,o.set(i,h)}else if(f===SQL_ACCOUNT_KIND){const h=b(u.accountId)??d.id,v=$(u.seq)??0,S=n.get(h);if(S&&S.seq>=v)continue;n.set(h,{requestId:i,...m?{project:m}:{},seq:v,basis:u.basis==="end"?"end":"settled",statements:$(u.statements)??0,failed:$(u.failed)??0,workMs:$(u.workMs)??0,recorded:$(u.recorded)??0,suppressed:$(u.suppressed)??0,unwritten:$(u.unwritten)??0})}}const s=new Map;for(const d of n.values()){const u=s.get(d.requestId);if(!u){s.set(d.requestId,{...d});continue}d.basis==="settled"&&(u.basis="settled"),u.statements+=d.statements,u.failed+=d.failed,u.workMs+=d.workMs,u.recorded+=d.recorded,u.suppressed+=d.suppressed,u.unwritten+=d.unwritten}const l=[...new Set([...o.keys(),...s.keys()])].sort();if(l.length===0)return;const g={statements:0,failed:0,workMs:0,recorded:0,suppressed:0,unwritten:0},I={statements:0,workMs:0},q=[];for(const d of l){const u=o.get(d),f=s.get(d),i=u?.count??0;I.statements+=i,I.workMs+=u?.workMs??0;const m=!f||i>f.statements?"unverified":i===f.statements?"complete":"incomplete";f&&m!=="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=u?.project??f?.project;q.push({requestId:d,...h?{project:h}:{},status:m,observed:i,observedWorkMs:u?.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 M=p(d=>q.filter(u=>u.status===d).length,"tally"),j=M("unverified"),y=M("incomplete"),c=p(d=>(d.statements??0)-d.observed,"missing"),a=q.filter(d=>d.status!=="complete").sort((d,u)=>(d.status==="incomplete"?0:1)-(u.status==="incomplete"?0:1)||c(u)-c(d)||(d.requestId<u.requestId?-1:d.requestId>u.requestId?1:0));return{status:j>0?"unverified":y>0?"incomplete":"complete",requests:q.length,complete:M("complete"),incomplete:y,unverified:j,settled:q.filter(d=>d.status!=="unverified"&&d.basis==="settled").length,observed:I,accounted:g,gaps:a.slice(0,te),gapsTruncated:a.length>te}}k(R,"R"),w(R,"D"),p(R,"accountSql");
1
+ "use strict";var te=Object.defineProperty;var w=(e,t)=>te(e,"name",{value:t,configurable:!0});var se=Object.defineProperty,p=w((e,t)=>se(e,"name",{value:t,configurable:!0}),"p");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"]),x=p(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj"),b=p(e=>typeof e=="string"&&e!==""?e:void 0,"str"),M=p(e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,"num"),T=new WeakMap;function A(e){let t=T.get(e);return t||(t=_(e),T.set(e,t)),t}w(A,"K"),p(A,"itemOf");function _(e){const t=x(e.raw)?e.raw:{},s=x(t.request)?t.request:{},o=x(t.span)?t.span:{},r=e.context??{},n=b(t.kind)??"",l=n===SQL_ACCOUNT_KIND,g=(l?M(t.lastEndedAt):void 0)??M(e.timestamp)??0,v=M(s.startedAt)??M(o.startTime)??M(t.startedAt)??(l?M(t.firstStartedAt):void 0),q=M(s.endedAt)??M(o.endTime)??(v!==void 0&&M(t.durationMs)!==void 0?v+t.durationMs:void 0),I=Math.min(g,v??g),$=Math.max(g,q??g),j=x(t.render)?t.render:{},a=x(t.update)?t.update:{},c=n==="render"?b(j.componentName):n==="state-update"?b(a.path)?.split(".").slice(0,2).join("."):void 0,d=b(t.queue),u=b(t.jobId),f=String(e.source),i=b(t.project)??b(r.projectName),m=n==="fetch-start"||n==="fetch-done"||n==="gateway-request";return{event:e,id:e.id,ts:g,from:I,to:$,kind:n,source:f,requestId:b(r.requestId),parentRequestId:b(r.parentRequestId),queueKey:d&&u?`${d}#${u}`:void 0,browser:ne.has(f)||f==="memory"&&i===void 0,bookkeeping:FLOW_BOOKKEEPING_KINDS.has(n),project:i,subject:c,route:m?B(b(t.url)):n==="server-request"?b(s.route):void 0,method:m?b(t.method):n==="server-request"?b(s.method):void 0}}w(_,"C"),p(_,"readItem");function B(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}w(B,"P"),p(B,"pathOnly");const oe=p(e=>e.split(".")[0],"rootOf"),U=p((e,t)=>e.reduce((s,o)=>Math.min(s,t(o)),1/0),"minOf"),D=p((e,t)=>e.reduce((s,o)=>Math.max(s,t(o)),-1/0),"maxOf"),K=p((e,t)=>e.ts-t.ts||(e.id<t.id?-1:e.id>t.id?1:0),"compare"),O=p(e=>e.requestId&&!e.requestId.startsWith("job:")?oe(e.requestId):void 0,"directFamilyOf");function z(e){if(e.requestId?.startsWith("job:"))return e.requestId.slice(4);if(e.queueKey&&e.kind!=="queue-enqueued"&&!e.requestId)return e.queueKey}w(z,"Q"),p(z,"jobKeyOf");function C(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||K(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 r=o.map(()=>[]);for(const n of e)r[t>=0?P(o,n.ts,t):L(o,n.ts,t)].push(n);return r.filter(n=>n.length>0)}w(C,"V"),p(C,"occurrencesOf");function L(e,t,s){const o=e.findIndex(n=>t>=n.from-s&&t<=n.to+s);if(o!==-1)return o;let r=0;for(let n=0;n<e.length;n+=1)e[n].from<=t&&(r=n);return r}w(L,"X"),p(L,"spanScan");function P(e,t,s){let o=0,r=e.length;for(;o<r;){const n=o+r>>1;e[n].to+s<t?o=n+1:r=n}if(o<e.length&&t>=e[o].from-s)return o;for(o=0,r=e.length;o<r;){const n=o+r>>1;e[n].from<=t?o=n+1:r=n}return Math.max(0,o-1)}w(P,"Y"),p(P,"spanAt");const re=new Set(["server-request","gateway-request","fetch-done","fetch-error","queue-process"]),N="event-loop-stall";function E(e){let t=-1/0,s=!1;for(const r of e)re.has(r.kind)?t=Math.max(t,r.to):r.kind===N&&(s=!0);if(!s||!Number.isFinite(t))return;let o;for(const r of e)r.kind===N&&r.from>=t&&(o??=new Map).set(r,Math.round(r.from-t));return o}w(E,"_"),p(E,"lateStallsOf");export function stallsAfterResponse(e){const t=new Map;if(!e.some(o=>x(o.raw)&&o.raw.kind===N))return t;const s=new Map;for(const o of e){const r=A(o),n=r.requestId?.startsWith("job:")?r.requestId:O(r);if(n===void 0)continue;const l=s.get(n);l?l.push(r):s.set(n,[r])}for(const o of s.values())for(const[r,n]of E(o)??[])t.set(r.id,n);return t}w(stallsAfterResponse,"stallsAfterResponse"),p(stallsAfterResponse,"stallsAfterResponse");function W(e,t){if(!t)return e;const s=e.filter(o=>!t.has(o));return s.length?s:e}w(W,"T"),p(W,"timedItems");const Q={debug:0,info:1,warning:2,error:3,fatal:4};function F(e,t){const s=[];let o=[];for(const r of e){const n=o[o.length-1];n&&r.ts-n.ts>=t&&(s.push(o),o=[]),o.push(r)}return o.length&&s.push(o),s}w(F,"F"),p(F,"runs");export function segmentFlow(e,t={}){const s={...DEFAULT_SEGMENT_OPTIONS};for(const[i,m]of Object.entries(t))typeof m=="number"&&Number.isFinite(m)&&(s[i]=m);const o=new Set,r=[];for(const i of e)o.has(i.id)||(o.add(i.id),r.push(A(i)));r.sort(K);const n=b(r[0]?.event.context?.flowId)??b(r[0]?.event.raw?.flowId)??"",l=new Map;for(const i of r)i.kind==="queue-enqueued"&&i.queueKey&&i.requestId&&!i.requestId.startsWith("job:")&&!l.has(i.queueKey)&&l.set(i.queueKey,i);const g=new Map,v=new Map,q=[];for(const i of r){const m=z(i),h=O(i);if(m!==void 0){const k=v.get(m);k?k.push(i):v.set(m,[i])}else if(h!==void 0){const k=g.get(h);k?k.push(i):g.set(h,[i])}else q.push(i)}const I=[],$=new Map;for(const[i,m]of g)C(m,s.occurrenceSlackMs).forEach((h,k)=>{const S={id:`${n}~r:${i}${k===0?"":`@${k+1}`}`,kind:"request",items:h,requestId:i};if(I.push(S),l.size)for(const y of h)y.kind==="queue-enqueued"&&$.set(y,S)});for(const[i,m]of v){const h=l.get(i),k=h?$.get(h):void 0;k?k.items.push(...m):I.push({id:`${n}~r:job:${i}`,kind:"request",items:m,requestId:`job:${i}`})}const j=r.filter(i=>i.kind==="fetch-done"&&O(i)!==void 0),a=new Map;for(const i of I)i.requestId&&a.set(i.requestId,[...a.get(i.requestId)??[],i]);const c=p((i,m)=>{const h=a.get(i);if(h)return h.find(k=>k.items.some(S=>S.kind==="fetch-done"&&S.ts===m))??h[h.length-1]},"owningUnit"),d=q.filter(i=>i.browser);for(const i of F(d,s.burstGapMs)){const m=i[0].ts,h=j.filter(y=>y.ts<=m&&m-y.ts<=s.attachWindowMs),k=[...new Set(h.map(y=>O(y)))];if(k.length===1){const y=c(k[0],h[h.length-1].ts);if(y){y.items.push(...i);continue}}const S=i.some(y=>y.kind==="flow-origin");I.push({id:`${n}~${S?"o":"u"}:${i[0].id}`,kind:S?"origin":"ui",items:i,...k.length>1?{after:k.sort()}:{}})}for(const i of F(q.filter(m=>!m.browser),s.phaseGapMs))I.push({id:`${n}~a:${i[0].id}`,kind:"ambient",items:i});const u=H(n,r.length,I,s),f=G(r);return f?{...u,sql:f}:u}w(segmentFlow,"segmentFlow"),p(segmentFlow,"segmentFlow");function H(e,t,s,o){for(const a of s)a.items.sort(K);const r=new Map;for(const a of s){const c=a.kind==="request"?E(a.items):void 0;c&&r.set(a,c)}const n=s.map(a=>{const c=W(a.items,r.get(a));return{unit:a,from:U(c,d=>d.from),to:D(c,d=>d.to)}});n.sort((a,c)=>a.from-c.from||(a.unit.id<c.unit.id?-1:1));const l=new Map;let g=0,v=-1/0;for(const a of n)(g===0||a.from-v>=o.phaseGapMs)&&(g+=1),v=Math.max(v,a.to),l.set(a.unit,g);const q=[];for(const a of n){const c=J(a.unit.items,o.maxSegmentEvents),d=a.unit.kind==="request"?G(a.unit.items):void 0;c.forEach((u,f)=>{const i=V(e,a.unit,u,l.get(a.unit),c.length>1?{index:f+1,total:c.length}:void 0,r.get(a.unit));q.push(d&&f===0?{...i,sql:d}:i)})}const I={};for(const a of q)for(const c of a.eventIds)I[c]=a.id;const $=[];for(const a of q){let c=$[a.phase-1];c||(c={index:a.phase,start:a.start,end:a.end,segmentIds:[]},$[a.phase-1]=c),c.start=Math.min(c.start,a.start),c.end=Math.max(c.end,a.end),c.segmentIds.push(a.id)}const j=q.reduce((a,c)=>a+c.counts.signal,0);return{flowId:e,segments:q,phases:$.filter(Boolean),assignment:I,stats:{events:t,signal:j,bookkeeping:t-j,segments:q.length,phases:$.filter(Boolean).length,largestSegment:q.reduce((a,c)=>Math.max(a,c.counts.total),0)}}}w(H,"J"),p(H,"assemble");function J(e,t){if(e.filter(n=>!n.bookkeeping).length<=t)return[e];const s=[];let o=[],r=0;for(const n of e)!n.bookkeeping&&r===t&&(s.push(o),o=[],r=0),o.push(n),n.bookkeeping||(r+=1);return o.length&&s.push(o),s}w(J,"Z"),p(J,"chunk");function V(e,t,s,o,r,n){const l={total:s.length,signal:0,bookkeeping:0,errors:0,warnings:0},g=new Set;let v="debug";for(const u of s){u.bookkeeping?l.bookkeeping+=1:l.signal+=1;const f=String(u.event.severity);f==="error"||f==="fatal"?l.errors+=1:f==="warning"&&(l.warnings+=1),(Q[f]??1)>(Q[v]??0)&&(v=f),u.project&&g.add(u.project)}const q=t.kind==="ui"||t.kind==="origin"?Y(s):[],I=W(s,n),$=U(I,u=>u.from),j=D(I,u=>u.to),a=n?s.filter(u=>n.has(u)).length:0,c=X(t.items),d=t.id;return{id:r&&r.index>1?`${d}#${r.index}`:d,flowId:e,kind:t.kind,label:Z(t,s,c,r,q),phase:o,start:$,end:j,durationMs:j-$,eventIds:s.map(u=>u.id),counts:l,projects:[...g].sort(),...c.route?{route:c.route}:{},...c.method?{method:c.method}:{},...t.requestId?{requestId:t.requestId}:{},...t.after?{after:t.after}:{},...q.length?{hot:q}:{},...r?{part:r}:{},...a?{stallsAfterResponse:a}:{},worstSeverity:v}}w(V,"ee"),p(V,"toSegment");function X(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()}:{}}}w(X,"te"),p(X,"routeOf");function Y(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)}w(Y,"ne"),p(Y,"hotOf");function Z(e,t,s,o,r){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"}${r.length?` \xB7 ${r.join(", ")}`:""}${n}`:e.kind==="ui"?`UI update${r.length?` \xB7 ${r.join(", ")}`:""}${n}`:`background${n}`}w(Z,"se"),p(Z,"labelOf");const ee=50;export function sqlAccountingOf(e){return R(e,!1)}w(sqlAccountingOf,"sqlAccountingOf"),p(sqlAccountingOf,"sqlAccountingOf");function G(e){return R(e.map(t=>t.event),!0)}w(G,"L"),p(G,"accountSqlOfItems");function R(e,t){const s=new Map,o=new Map,r=t?void 0:new Set;for(const d of e){if(r){if(r.has(d.id))continue;r.add(d.id)}const u=x(d.raw)?d.raw:{},f=b(u.kind),i=b(d.context?.requestId);if(!i)continue;const m=b(u.project)??b(d.context?.projectName);if(f==="db-query"&&d.source==="db"){const h=o.get(i)??{count:0,workMs:0,...m?{project:m}:{}};h.count+=1,h.workMs+=M(u.durationMs)??0,o.set(i,h)}else if(f===SQL_ACCOUNT_KIND){const h=b(u.accountId)??d.id,k=M(u.seq)??0,S=s.get(h);if(S&&S.seq>=k)continue;s.set(h,{requestId:i,...m?{project:m}:{},seq:k,basis:u.basis==="end"?"end":"settled",statements:M(u.statements)??0,failed:M(u.failed)??0,workMs:M(u.workMs)??0,recorded:M(u.recorded)??0,suppressed:M(u.suppressed)??0,unwritten:M(u.unwritten)??0})}}const n=new Map;for(const d of s.values()){const u=n.get(d.requestId);if(!u){n.set(d.requestId,{...d});continue}d.basis==="settled"&&(u.basis="settled"),u.statements+=d.statements,u.failed+=d.failed,u.workMs+=d.workMs,u.recorded+=d.recorded,u.suppressed+=d.suppressed,u.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},v={statements:0,workMs:0},q=[];for(const d of l){const u=o.get(d),f=n.get(d),i=u?.count??0;v.statements+=i,v.workMs+=u?.workMs??0;const m=!f||i>f.statements?"unverified":i===f.statements?"complete":"incomplete";f&&m!=="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=u?.project??f?.project;q.push({requestId:d,...h?{project:h}:{},status:m,observed:i,observedWorkMs:u?.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 I=p(d=>q.filter(u=>u.status===d).length,"tally"),$=I("unverified"),j=I("incomplete"),a=p(d=>(d.statements??0)-d.observed,"missing"),c=q.filter(d=>d.status!=="complete").sort((d,u)=>(d.status==="incomplete"?0:1)-(u.status==="incomplete"?0:1)||a(u)-a(d)||(d.requestId<u.requestId?-1:d.requestId>u.requestId?1:0));return{status:$>0?"unverified":j>0?"incomplete":"complete",requests:q.length,complete:I("complete"),incomplete:j,unverified:$,settled:q.filter(d=>d.status!=="unverified"&&d.basis==="settled").length,observed:v,accounted:g,gaps:c.slice(0,ee),gapsTruncated:c.length>ee}}w(R,"D"),p(R,"accountSql");
@@ -76,9 +76,9 @@ export declare function trimFlowEvent(event: BaseEvent, opts?: FlowShapeOptions)
76
76
  outcome?: "returned" | "threw" | "signalled" | undefined;
77
77
  calleeRequestId?: string | undefined;
78
78
  hop?: true | undefined;
79
- source: "gateway" | "ai" | "db" | "redis" | "queue" | "external" | "visual" | "react" | "memory" | "lens" | "nx" | "vite" | "typescript" | "eslint" | "rollup" | "client-runtime" | "chrome" | "valtio" | "nestjs" | "nextjs" | "perf" | "security" | "custom";
80
- category: "ai" | "db" | "visual" | "memory" | "security" | "test" | "typecheck" | "lint" | "build" | "state" | "agent" | "network" | "cluster" | "trace" | "runtime" | "render" | "backend" | "performance" | "deps";
81
- severity: "error" | "info" | "warning" | "debug" | "fatal";
79
+ source: "nx" | "vite" | "typescript" | "eslint" | "rollup" | "client-runtime" | "chrome" | "react" | "valtio" | "nestjs" | "nextjs" | "db" | "redis" | "queue" | "memory" | "visual" | "perf" | "security" | "gateway" | "external" | "ai" | "lens" | "custom";
80
+ category: "db" | "memory" | "visual" | "security" | "ai" | "build" | "lint" | "typecheck" | "test" | "runtime" | "render" | "trace" | "state" | "network" | "backend" | "performance" | "deps" | "cluster" | "agent";
81
+ severity: "error" | "debug" | "info" | "warning" | "fatal";
82
82
  title: string;
83
83
  kind: string | undefined;
84
84
  area: FlowArea;
@@ -153,9 +153,9 @@ export declare function buildFlowDetail(rawEvents: BaseEvent[], opts?: FlowShape
153
153
  outcome?: "returned" | "threw" | "signalled" | undefined;
154
154
  calleeRequestId?: string | undefined;
155
155
  hop?: true | undefined;
156
- source: "gateway" | "ai" | "db" | "redis" | "queue" | "external" | "visual" | "react" | "memory" | "lens" | "nx" | "vite" | "typescript" | "eslint" | "rollup" | "client-runtime" | "chrome" | "valtio" | "nestjs" | "nextjs" | "perf" | "security" | "custom";
157
- category: "ai" | "db" | "visual" | "memory" | "security" | "test" | "typecheck" | "lint" | "build" | "state" | "agent" | "network" | "cluster" | "trace" | "runtime" | "render" | "backend" | "performance" | "deps";
158
- severity: "error" | "info" | "warning" | "debug" | "fatal";
156
+ source: "nx" | "vite" | "typescript" | "eslint" | "rollup" | "client-runtime" | "chrome" | "react" | "valtio" | "nestjs" | "nextjs" | "db" | "redis" | "queue" | "memory" | "visual" | "perf" | "security" | "gateway" | "external" | "ai" | "lens" | "custom";
157
+ category: "db" | "memory" | "visual" | "security" | "ai" | "build" | "lint" | "typecheck" | "test" | "runtime" | "render" | "trace" | "state" | "network" | "backend" | "performance" | "deps" | "cluster" | "agent";
158
+ severity: "error" | "debug" | "info" | "warning" | "fatal";
159
159
  title: string;
160
160
  kind: string | undefined;
161
161
  area: FlowArea;
package/lib/flow-shape.js CHANGED
@@ -1 +1 @@
1
- "use strict";var Ae=Object.defineProperty;var R=(i,f)=>Ae(i,"name",{value:f,configurable:!0});var Re=Object.defineProperty,D=R((i,f)=>Re(i,"name",{value:f,configurable:!0}),"R"),Te=Object.defineProperty,q=D((i,f)=>Te(i,"name",{value:f,configurable:!0}),"I");import{redactDeep as Ce,redactText as ce,redactUrlParams as De}from"./redact.js";import{templatisePath as ke}from"./route-template.js";import{SQL_ACCOUNT_KIND as Fe,sqlAccountingOf as Oe,stallsAfterResponse as Pe}from"./flow-segments.js";import{isServiceHopHost as we}from"./service-hop.js";import{queueSignalOf as Ie,queueSignalWords as Ne}from"./queue-signals.js";import{boundedClone as Ee}from"@lensmcp/protocol-types";export function areaOf(i){const{source:f,category:s,title:M,kind:l}=i;return f==="ai"?"ai":f==="perf"&&l==="event-loop-stall"?"services":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"||l==="egress"&&we(i.host)?"services":f==="external"||l==="egress"?"network":f==="nestjs"||f==="nest"?/(?:Repository|Repo|Dao|Store|EntityManager|DataSource|QueryRunner|OrmClient)\./.test(M)?"data":"services":f==="valtio"?"state":s==="network"?"network":"browser"}R(areaOf,"areaOf"),D(areaOf,"areaOf"),q(areaOf,"areaOf");const Me=240,Le=new Set(["systemPrompt","prompt","prompts","messages","completion","completions","input","output","draft","text","content","result","arguments","params"]),We=new Set(["tenantId","caller","userId","accountId","email","subject"]),Ue=8;function le(i){const f=te(i,0);return Ee(Ce({redacted:!0,...f}),{rawByteLimit:16*1024}).value}R(le,"qt"),D(le,"Be"),q(le,"aiProjection");function te(i,f){if(typeof i=="string")return pe(i);if(i===null||typeof i!="object")return i;if(f>=Ue)return;if(Array.isArray(i))return i.slice(0,32).map(M=>te(M,f+1));const s={};for(const[M,l]of Object.entries(i))if(!We.has(M)){if(Le.has(M)){typeof l=="string"?s[`${M}Chars`]=l.length:Array.isArray(l)?s[`${M}Count`]=l.length:l!=null&&(s[`${M}Present`]=!0);continue}s[M]=te(l,f+1)}return s}R(te,"st"),D(te,"ae"),q(te,"projectAi");function pe(i){return i.length<=Me?ce(i):`${ce(i.slice(0,Me))}\u2026`}R(pe,"wt"),D(pe,"_e"),q(pe,"clipText");export function httpFacts(i,f){const s=q(I=>typeof I=="string"&&I.length>0?I:void 0,"str"),M=typeof f.status=="number"?f.status:void 0,l=q(I=>De(I.split("?")[0]??I)||"/","pathOf"),N=q((I,b,y={})=>({...I?{method:I.toUpperCase()}:{},...b?{rawPath:b,route:ke(b)}:{},...M!==void 0?{status:M}:{},...y}),"facts");if(i==="gateway-request"){const I=s(f.url);return N(s(f.method),I?l(I):void 0,{...s(f.host)?{host:s(f.host)}:{},...s(f.caller)?{caller:s(f.caller)}:{}})}if(i==="egress"){const I=s(f.path),b=s(f.exchangeId);return N(s(f.method)??"GET",I?l(I):void 0,{...s(f.host)?{host:s(f.host)}:{},...b?{exchangeId:b}:{}})}if(i==="fetch-start"||i==="fetch-done"||i==="fetch-error"){const I=s(f.href)??s(f.url);let b,y;if(I)try{const p=new URL(I,"http://relative.invalid");b=l(p.pathname),p.hostname!=="relative.invalid"&&(y=p.hostname)}catch{}return N(s(f.method)??"GET",b,y?{host:y}:{})}if(i==="ai-call")return{...M!==void 0?{status:M}:{},...f.stream===!0?{streamed:!0}:{}};const g=f.request;if(g&&typeof g=="object"){const I=g,b=s(I.route),y=s(I.method);if(!b&&!y)return{};const p=typeof I.status=="number"?I.status:void 0,E=b?l(b):void 0;return{...y?{method:y.toUpperCase()}:{},...E?{rawPath:E,route:E.includes(":")?E:ke(E)}:{},...p!==void 0?{status:p}:{}}}return{}}R(httpFacts,"httpFacts"),D(httpFacts,"httpFacts"),q(httpFacts,"httpFacts");export function trimFlowEvent(i,f={}){const s=i.raw??{},M=s.render??{},l=s.span??{},N=s.request??{},g=q(d=>typeof d=="number"?d:void 0,"num"),I=s.loop??{},b=s.effect??{},y=g(s.durationMs)??g(l.durationMs)??g(N.durationMs)??g(I.durationMs)??g(M.actualDurationMs)??g(b.durationMs),p=typeof s.kind=="string"?s.kind:void 0,E=p==="fetch-done"||p==="fetch-error",U=g(M.commitTime),re=p==="render"&&U!==void 0&&Math.abs(U-i.timestamp)<6e4,Q=E?i.timestamp:re?U:g(s.startedAt)??g(l.startTime)??g(N.startedAt)??g(I.startedAt)??(y!==void 0?i.timestamp-y:i.timestamp);let x;if(typeof s.query=="string"){const d=Array.isArray(s.params)?` [${s.params.join(", ")}]`:"",h=typeof s.result=="string"?` \u2192 ${s.result}`:"";x=s.query+d+h}else if(typeof s.command=="string"){const d=typeof s.value=="string"?` \u2192 ${s.value}`:s.hit===!1?" \u2192 (miss)":"";x=s.command+d}else if(p==="state-update"){const d=s.update??{};let h="";try{h=JSON.stringify(d.preview)}catch{}x=`${d.storeId??""}.${d.path??""} = ${h}`}else if(p==="fs-ops"&&Array.isArray(s.paths))x=s.paths.slice(0,8).map(d=>{const h=d??{},B=typeof h.n=="number"&&h.n>1?` \xD7${h.n}`:"",m=typeof h.bytes=="number"&&h.bytes>0?` (${h.bytes>=1024?`${(h.bytes/1024).toFixed(1)} KB`:`${h.bytes} B`})`:"";return`${String(h.op??"?")} ${String(h.path??"?")}${B}${m}`}).join(" \xB7 ");else if(p==="exec"&&typeof s.cmd=="string")x=`${s.cmd} \u2192 ${s.code??s.signal??s.error??"?"}`;else if(p==="queue-completed"&&typeof s.returned=="string")x=`returned ${s.returned}`;else if(p==="queue-enqueued")x=`${s.job??"job"}#${s.jobId??"?"} \u2192 ${s.queue??""}${typeof s.data=="string"?" "+s.data:""}`;else if(p==="log"){const d=N.error??{},h=typeof d.stack=="string"?d.stack:typeof s.text=="string"?s.text:void 0;h&&h!==i.title&&(x=h)}let K,L;p==="queue-process"&&(L=Ie(s.status));let _,Y,z;if(p==="span"){const d=l.outcome;if(L=d==="signalled"?Ie(l.signal):void 0,K=L?"signalled":d==="threw"||d==="returned"?d:l.status==="error"?"threw":l.status==="ok"?"returned":void 0,K==="threw"){const m=l.error??{},C=typeof m.name=="string"?m.name:void 0,G=typeof m.message=="string"?m.message:typeof i.message=="string"?i.message:void 0;Y=C,_=ce([C,G].filter(Boolean).join(": "))||void 0}const h=typeof l.args=="string"?l.args:void 0,B=typeof l.result=="string"?l.result:void 0;if(h!==void 0||B!==void 0){z=[...h!==void 0?["args"]:[],...B!==void 0?["result"]:[]];const m=q(C=>C.length>be?`${C.slice(0,be)}\u2026`:C,"short");x=[h!==void 0?`args ${m(h)}`:"",B!==void 0?`returned ${m(B)}`:""].filter(Boolean).join(" \u2192 ")}}let J;if(p==="gateway-request")J=`${s.host??""}${String(s.url??"").split("?")[0]}`;else if(p==="fetch-start"||p==="fetch-done"||p==="fetch-error")try{const d=new URL(String(s.href??s.url??""));J=`${d.hostname}${d.pathname}`}catch{}let O;if(p==="gateway-request"&&Array.isArray(s.steps))O=s.steps.map(d=>{const h=[String(d.step)];return d.project&&h.push(String(d.project)),d.prefix&&h.push(String(d.prefix)),d.mode&&h.push(String(d.mode)+(d.ok===!1?" \u2717":d.ok===!0?" \u2713":"")),d.caller&&h.push("by "+String(d.caller)),d.pod&&h.push(String(d.pod)),typeof d.atMs=="number"&&h.push(`@${d.atMs}ms`),h.join(" ")}),x=O.map(d=>d.replace(/ @\d+ms$/,"")).join(" \u2192 ");else if(p==="egress")x=`${s.method??"GET"} ${s.host??""} \u2192 ${s.status??"?"}`;else if(i.source==="ai"){if(p==="ai-call"){const d=s.usage??{},h=d.promptTokens!==void 0||d.completionTokens!==void 0?` \xB7 ${g(d.promptTokens)??"?"}\u2192${g(d.completionTokens)??"?"} tok`:"",B=s.status!==void 0?` \xB7 ${String(s.status)}`:s.error?" \xB7 failed":"",m=g(s.toolCallCount)?` \xB7 ${g(s.toolCallCount)} tool call${g(s.toolCallCount)===1?"":"s"}`:"",C=g(s.durationMs)!==void 0?` \xB7 ${(g(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${s.provider??""}/${s.model??"?"}${h}${B}${m}${C}${s.stream===!0?" \xB7 stream":""}`}else if(p==="ai-round"){const d=s.model??{},h=s.usage??{},B=Array.isArray(s.toolCalls)?s.toolCalls:[],m=`${g(h.promptTokens)??"?"}\u2192${g(h.completionTokens)??"?"} tok`,C=B.length?` \xB7 ${B.length} tool call${B.length===1?"":"s"}`:"",G=g(s.durationMs)!==void 0?` \xB7 ${(g(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${d.provider??""}/${d.model??""} \xB7 ${m}${C}${G}`}else if(p==="ai-turn-start"){const d=Array.isArray(s.tools)?s.tools:[];x=`skill ${s.skill??""} \xB7 ${s.output??""}${d.length?" \xB7 tools: "+d.join(", "):""}`}else if(p==="ai-tool-call"){const d=s.call??{},h=s.result??{},B=g(s.durationMs)!==void 0?` \xB7 ${(g(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${d.name??"tool"} ${h.error!=null?"\u2717 "+String(h.error):"\u2713"}${B}`}else if(p==="ai-turn-end"){const d=s.usage??{},h=g(s.rounds)!==void 0?` \xB7 ${g(s.rounds)} round${g(s.rounds)===1?"":"s"}`:"",B=g(s.durationMs)!==void 0?` \xB7 ${(g(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${s.ok===!1?"FAILED":"ok"} \xB7 ${g(d.promptTokens)??"?"}+${g(d.completionTokens)??"?"} tok${h}${B}`}}let T;p==="db-query"&&typeof s.query=="string"?T=s.query:p==="redis-op"?T=`${s.op??""} ${String(s.key??"").replace(/\d+/g,"#")}`:p==="egress"?T=`${s.method??"GET"} ${s.host??""}`:p==="ai-call"?T=`ai ${s.provider??""} ${s.model??""} ${s.api??""}`:p==="queue-enqueued"?T=`enqueue ${s.queue??""}`:p==="span"&&typeof l.name=="string"?T=l.name:p==="memory-mutation"&&(T=i.title);const W=i.context??{},X=M.commitId??b.commitId??s.commitId,Z=Array.isArray(M.why)?M.why.map(d=>typeof d?.type=="string"?d.type:void 0).filter(d=>!!d):[];return{id:i.id,t:i.timestamp,start:Q,...T?{sig:T}:{},...J?{urlKey:J}:{},...httpFacts(p,s),...(p==="db-query"||p==="redis-op")&&typeof s.valuesId=="string"?{valuesId:s.valuesId}:{},...p==="db-query"&&typeof s.name=="string"&&s.name!=="postgres"?{db:s.name}:{},...p?.startsWith("queue-")&&typeof s.broker=="string"?{broker:s.broker}:{},...typeof s.queue=="string"?{queue:s.queue}:{},...s.jobId!=null?{jobId:String(s.jobId)}:{},source:i.source,category:i.category,severity:i.severity,title:K==="threw"&&typeof l.name=="string"?`${l.name} \u2014 threw${Y?` ${Y}`:""}${y!==void 0?` after ${y}ms`:""}`:p==="queue-process"&&L?`process ${String(s.job??"job")}#${String(s.jobId??"?")} \u2014 ran, ${Ne(L,g(s.delayMs))}${y!==void 0?` (${y}ms)`:""}`:i.title,kind:p,area:areaOf({source:i.source,category:i.category,title:i.title,kind:p,...typeof s.host=="string"?{host:s.host}:{}}),...p==="egress"&&we(typeof s.host=="string"?s.host:void 0)?{hop:!0}:{},...p==="egress"&&typeof s.calleeRequestId=="string"?{calleeRequestId:s.calleeRequestId}:{},...K?{outcome:K}:{},...L?{signal:L}:{},..._?{error:_}:{},...z?{captured:z}:{},...typeof l.role=="string"?{role:l.role}:{},...typeof l.spanId=="string"?{spanId:l.spanId}:{},...typeof l.parentSpanId=="string"?{parentSpanId:l.parentSpanId}:{},...p==="log"&&typeof s.level=="string"?{level:s.level}:{},...p==="log"&&typeof s.logger=="string"?{logger:s.logger}:{},...p==="log"&&typeof s.stream=="string"?{stream:s.stream}:{},...typeof W.requestId=="string"?{requestId:W.requestId}:{},...typeof W.parentRequestId=="string"?{parentRequestId:W.parentRequestId}:{},...typeof X=="string"?{commitId:X}:{},...typeof M.componentName=="string"?{component:M.componentName}:{},...typeof M.phase=="string"?{phase:M.phase}:{},...Z.length?{why:Z}:{},...p==="effect-run"&&typeof b.hookLogicalId=="string"?{hook:b.hookLogicalId}:{},...p==="effect-run"&&b.cleanupRan===!0?{cleanup:!0}:{},...p==="render-commit-truncated"?{renderTotal:g(s.total),renderPublished:g(s.published),...g(s.walkStoppedAt)!==void 0?{renderWalkStoppedAt:g(s.walkStoppedAt)}:{}}:{},...typeof W.projectName=="string"?{project:W.projectName}:typeof s.project=="string"?{project:s.project}:{},...y!==void 0?{durationMs:y}:{},...E&&g(s.startedAt)!==void 0?{fetchStartedAt:g(s.startedAt)}:{},...i.source==="ai"?{ai:f.includeRaw?s:le(s)}:{},...x?{detail:x}:{},...O?{steps:O}:{}}}R(trimFlowEvent,"trimFlowEvent"),D(trimFlowEvent,"trimFlowEvent"),q(trimFlowEvent,"trimFlowEvent");const be=300;export const OUTLIVED_PARENT_MIN_MS=250;const Ke=new Set(["egress","db-query","redis-op","ai-call","span","gateway-request","server-request"]),fe=1;function ge(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(ge,"It"),D(ge,"Oe"),q(ge,"kindRank");function H(i){return i.kind==="span"&&i.role==="controller"?3.5:i.kind==="queue-process"?3:ge(i.kind)}R(H,"V"),D(H,"Z"),q(H,"causalRank");export function buildFlowDetail(i,f={}){const s=Oe(i),M=Pe(i),l=i.slice().filter(e=>{const r=e.raw??{},t=typeof r.kind=="string"?r.kind:"";if(t==="subscription-added"||t==="subscription-removed"||t==="hook-run"||t==="store-created"||t==="singleton-instance"||t===Fe)return!1;const o=r.span;return!(typeof o?.name=="string"&&o.name.startsWith("nest.request "))}).map(e=>trimFlowEvent(e,f)),N=new Set;for(let e=l.length-1;e>=0;e--)N.has(l[e].id)?l.splice(e,1):N.add(l[e].id);const g=new Map;for(const e of l)(e.kind==="gateway-request"||e.kind==="queue-process")&&e.requestId&&!g.has(e.requestId)&&g.set(e.requestId,e.start);const I=q(e=>e.source!=="react"&&e.source!=="valtio"&&e.requestId&&g.has(e.requestId)?g.get(e.requestId):e.start,"anchorOf");l.sort((e,r)=>I(e)-I(r)||e.start-r.start||H(e)-H(r)||(r.durationMs??0)-(e.durationMs??0)||e.t-r.t);const b=q(e=>(e.kind==="span"||e.kind==="server-request"||e.kind==="gateway-request"||e.kind==="queue-process")&&(e.durationMs??0)>0,"spanLike"),y=l;for(const e of y)e.group=e.source==="react"||e.source==="valtio"||e.source==="client-runtime"||e.source==="visual"?"browser":"server";const p=new Map;for(const e of y)if((e.kind==="gateway-request"||e.kind==="queue-process")&&e.requestId&&e.project){const r=p.get(e.requestId)??[];r.push({project:e.project,start:e.start,end:e.start+(e.durationMs??0)}),p.set(e.requestId,r)}const E=q((e,r)=>{const t=p.get(e);if(t?.length)return t.every(o=>o.project===t[0].project)?t[0].project:t.filter(o=>o.start<=r+1&&o.end>=r-1).sort((o,n)=>n.start-o.start)[0]?.project},"projectOf");for(const e of y)if(!e.project&&e.source==="nestjs"&&e.requestId){const r=E(e.requestId,e.start);r&&(e.project=r)}const U=new Map;for(const e of y)e.spanId&&U.set(e.spanId,e);const re=q((e,r)=>{let t=e.parentSpanId?U.get(e.parentSpanId):void 0;for(let o=0;t&&o<64;o++){if(t===r)return!0;t=t.parentSpanId?U.get(t.parentSpanId):void 0}return!1},"inside"),Q=new Map(y.map((e,r)=>[e,r])),x=new Map,K=q(e=>{let r=x.get(e.group);r||x.set(e.group,r=new Map);const t=e.requestId;let o=r.get(t);return o||r.set(t,o={spans:[],next:0,alive:[]}),o},"legOf");for(const e of y)b(e)&&Number.isFinite(e.start)&&K(e).spans.push(e);for(const e of x.values())for(const r of e.values())r.spans.sort((t,o)=>t.start-o.start||Q.get(t)-Q.get(o));const L=q(e=>Number.isFinite(e.start)?e.start:1/0,"startOf");for(const e of y.slice().sort((r,t)=>L(r)-L(t))){const r=e.parentSpanId?U.get(e.parentSpanId):void 0;if(r&&r!==e&&r.group===e.group&&r.requestId===e.requestId){e.parent=r.id;continue}if(!Number.isFinite(e.start))continue;const t=K(e);for(;t.next<t.spans.length&&t.spans[t.next].start<=e.start+fe;)t.alive.push(t.spans[t.next++]);t.alive=t.alive.filter(a=>a.start+(a.durationMs??0)>e.start);const o=t.alive.length>1?t.alive.slice().sort((a,$)=>Q.get(a)-Q.get($)):t.alive;let n;for(const a of o){if(a===e)continue;const $=a.project,k=e.project;if(a.kind!=="gateway-request"&&e.kind!=="gateway-request"&&$!==void 0&&k!==void 0&&$!==k)continue;const u=a.durationMs??0,c=e.durationMs??0,v=Math.abs(a.start-e.start)<=fe,w=H(a),A=H(e),j=a.start<=e.start;if(!(a.start+u>e.start&&(j||v&&w<A)&&(!v||(w!==A?w<A:j&&u>c))))continue;const P=n?H(n):-1,F=n?Math.abs(a.start-n.start)<=fe:!1,V=n&&F&&w===P?re(a,n)?1:re(n,a)?-1:0:0;(!n||!F&&a.start>n.start||F&&w>P||V>0||V===0&&F&&w===P&&(a.durationMs??0)<(n.durationMs??0))&&(n=a)}n&&(e.parent=n.id)}for(const e of y)delete e.spanId,delete e.parentSpanId;{const e=new Set(y.map(a=>a.id)),r=new Set,t=new Map,o=[],n=q(a=>{const $=[a];for(;$.length;){const k=$.pop();o.push(k),r.add(k.id);const u=t.get(k.id);if(u){t.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&&e.has(a.parent)&&!r.has(a.parent)){const $=t.get(a.parent)??[];$.push(a),t.set(a.parent,$)}else n(a);for(const a of y)r.has(a.id)||(o.push(a),r.add(a.id));for(let a=0;a<o.length;a++)y[a]=o[a]}const _=new Map;for(const e of y){if(!e.requestId)continue;const r=_.get(e.requestId);r?r.push(e):_.set(e.requestId,[e])}const Y=new Map(y.map(e=>[e.id,e])),z=new Map;for(const e of y)e.calleeRequestId&&!z.has(e.calleeRequestId)&&z.set(e.calleeRequestId,e);const J=q((e,r)=>{const t=(_.get(e)??[]).filter(o=>b(o)&&o.start<=r&&o.start+(o.durationMs??0)>=r);if(t.length!==0)return t.sort((o,n)=>n.start-o.start||(o.durationMs??0)-(n.durationMs??0)),t[0]},"callerNodeFor");for(const e of y){if(!e.parentRequestId||e.kind!=="server-request"&&e.kind!=="gateway-request")continue;const r=e.parent?Y.get(e.parent):void 0;if(r&&r.requestId===e.requestId)continue;const t=e.requestId?z.get(e.requestId):void 0,o=t&&t.start<=e.start?t:J(e.parentRequestId,e.start);o&&o!==e&&o.start<=e.start&&(e.parent=o.id)}const O=y,T=new Map;for(const e of O)e.kind==="gateway-request"&&e.requestId&&!T.has(e.requestId)&&T.set(e.requestId,e);for(const e of O)if(e.group==="server"&&!e.parent&&e.requestId&&e.kind!=="gateway-request"){const r=T.get(e.requestId);r&&r!==e&&r.start<=e.start&&(e.parent=r.id)}const W=new Set,X=new Set,Z=[];for(const e of O){if(e.kind!=="gateway-request")continue;if(!e.requestId){Z.push(e);continue}const r=_.get(e.requestId)??[];if(r.filter(n=>n.kind==="gateway-request").sort((n,a)=>n.start-a.start)[0]!==e)continue;const t=r.find(n=>n.kind==="fetch-start"),o=r.find(n=>n.kind==="fetch-done"||n.kind==="fetch-error");if(!t&&!o){Z.push(e);continue}t&&(e.fetchStartId=t.id,W.add(t.id)),o&&(e.fetchDoneId=o.id,X.add(o.id))}const d=new Map;for(const e of O){if(!e.urlKey)continue;const r=d.get(e.urlKey)??{gws:[],starts:[],dones:[]};e.kind==="gateway-request"?Z.includes(e)&&r.gws.push(e):e.kind==="fetch-start"?W.has(e.id)||r.starts.push(e):(e.kind==="fetch-done"||e.kind==="fetch-error")&&(X.has(e.id)||r.dones.push(e)),d.set(e.urlKey,r)}for(const{gws:e,starts:r,dones:t}of d.values()){e.sort((n,a)=>n.start-a.start),r.sort((n,a)=>n.start-a.start);const o=new Set;e.forEach((n,a)=>{const $=r[a];$&&(n.fetchStartId=$.id);const k=$?$.t:n.start;let u,c=1/0;for(const v of t){if(o.has(v.id))continue;const w=v.fetchStartedAt??v.start-(v.durationMs??0),A=Math.abs(w-k);A<c&&(c=A,u=v)}u&&(n.fetchDoneId=u.id,o.add(u.id))})}const h=new Map,B=new Map;for(const e of O)!e.queue||!e.jobId||(e.kind==="queue-enqueued"&&h.set(`${e.queue}#${e.jobId}`,e),e.kind==="queue-process"&&B.set(`${e.queue}#${e.jobId}`,e));for(const e of O){if(!e.queue||!e.jobId)continue;const r=`${e.queue}#${e.jobId}`;if(e.kind==="queue-process"&&!e.parent){const t=h.get(r);t&&t!==e&&t.start<=e.start&&(e.parent=t.id)}else if(e.kind==="queue-active"||e.kind==="queue-completed"||e.kind==="queue-failed"){const t=B.get(r);t&&t!==e&&t.start<=e.start&&(e.parent=t.id)}}{const e=new Map(y.map(r=>[r.id,r]));for(const r of y){if(!r.parent||!Ke.has(r.kind??"")||r.durationMs===void 0)continue;const t=e.get(r.parent);if(!t||t.kind!=="span"||!((t.durationMs??0)>0))continue;const o=Math.round(r.start+r.durationMs-(t.start+t.durationMs));if(o<OUTLIVED_PARENT_MIN_MS)continue;r.outlivedParentMs=o;const n=t.leftRunning??{count:0,longestMs:0};t.leftRunning={count:n.count+1,longestMs:Math.max(n.longestMs,o)}}for(const r of y){const t=[];r.leftRunning&&t.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&&t.push(`ran on ${r.outlivedParentMs}ms after the span that started it had ended`),t.length>0&&(r.detail=[r.detail,...t].filter(Boolean).join(" \xB7 "))}}if(M.size>0)for(const e of y){const r=M.get(e.id);r!==void 0&&(e.afterResponseMs=r,e.detail=[e.detail,`began ${r}ms after the request's response had finished \u2014 not part of the request's time`].filter(Boolean).join(" \xB7 "))}let m=y;{const e=new Map;for(const t of m)t.kind==="fetch-start"&&e.set(t.id,t);const r=new Map;for(const t of m){if(t.kind!=="fetch-done"&&t.kind!=="fetch-error")continue;const o=[...e.values()].find($=>$.requestId&&$.requestId===t.requestId)?.id,n=o?e.get(o):void 0;if(!n)continue;const a=t.fetchStartedAt??n.start;n.title=t.title,n.severity=t.severity,n.durationMs=t.durationMs??Math.max(0,t.t-a),n.kind="fetch",t.detail&&!n.detail&&(n.detail=t.detail),r.set(t.id,n.id)}if(r.size>0){m=m.filter(t=>!r.has(t.id));for(const t of m)for(t.fetchDoneId&&r.has(t.fetchDoneId)&&(t.fetchDoneId=r.get(t.fetchDoneId));t.parent&&r.has(t.parent);)t.parent=r.get(t.parent)}}const C=q(e=>!!e.commitId&&(e.kind==="render"||e.kind==="effect-run"||e.kind==="render-commit-truncated"),"commitMember"),G=q(e=>[...new Set(e)],"uniq"),ne=q(e=>G(e.map(r=>r.component).filter(r=>!!r)),"named"),xe=q(e=>e.length<=2?e.join(" + "):`${e[0]} + ${e.length-1} more`,"nameList"),he=q(e=>{const r=new Map;for(const t of e)t.component&&r.set(t.component,(r.get(t.component)??0)+1);return[...r].map(([t,o])=>o>1?`${t} \xD7${o}`:t).join(", ")},"tally"),je=q(e=>{if(!e)return"effect";const r=/([^/\\]+?):(\d+)(?::\d+)?$/.exec(e);return r?`${r[1]}:${r[2]}`:e},"shortHook"),ae=q(e=>`${je(e.hook)}${e.cleanup?" (cleanup)":""}`,"hookLabel"),me=q(e=>{const r=Math.min(...e.map(o=>o.start)),t=Math.max(...e.map(o=>o.start+(o.durationMs??0)));return{start:r,durationMs:t-r}},"extent"),$e=q(e=>(delete e.component,delete e.why,delete e.phase,delete e.hook,delete e.cleanup,delete e.renderTotal,delete e.renderPublished,e),"asGroup");function ie(e){const r=e[0],t=e.filter(S=>S.kind==="render"),o=e.filter(S=>S.kind==="effect-run"),n=e.find(S=>S.kind==="render-commit-truncated"),a=[...t].sort((S,ee)=>(ee.durationMs??0)-(S.durationMs??0)),$=a.filter(S=>(S.why??[]).some(ee=>ee!=="parent-render")),k=G($.flatMap(S=>(S.why??[]).filter(ee=>ee!=="parent-render"))),u=ne($),c=t.filter(S=>S.phase==="mount"),v=t.filter(S=>S.phase!=="mount"&&!$.includes(S)),w=a[0]?.component??"view",A=t.length>0&&c.length===t.length,j=k.length?k.join(" + "):void 0,P=A?"mount":"update",F=u.length?`view update \xB7 ${xe(u)} \u2190 ${j}`:A?`view mount \xB7 ${w}`:`view update \xB7 ${w}`,V=n?.renderTotal??t.length,Be=[c.length?`mounted ${he(c)}`:"",v.length?`re-rendered ${he(v)}`:"",!u.length&&!A&&t.length?"trigger not recorded \u2014 every captured render came from its parent":"",n?.renderWalkStoppedAt!==void 0?`at least ${V} renders (the walk stopped at ${n.renderWalkStoppedAt} fibers), ${n.renderPublished??t.length} recorded`:n?`${V} renders, ${n.renderPublished??t.length} recorded (per-commit cap)`:`${t.length} render${t.length===1?"":"s"}`,o.length?`${o.length} effect${o.length===1?"":"s"}: ${o.map(ae).join(", ")}`:""].filter(Boolean).join(" \xB7 "),qe=ne(t);return $e({...r,...me(e),kind:"view-update",title:F,detail:Be,commitId:r.commitId,viewPhase:P,...j?{cause:j}:{},causeComponents:u,components:qe,mounted:ne(c),renderCount:V,...n?.renderWalkStoppedAt!==void 0?{renderCountAtLeast:!0}:{},recordedRenders:t.length,effects:o.length,effectHooks:o.map(ae),memberIds:e.map(S=>S.id),sig:`commit:${P}:${j??"-"}:${u.join(",")}:${qe.slice().sort().join(",")}`,severity:e.some(S=>S.severity==="error")?"error":r.severity})}R(ie,"lt"),D(ie,"ke"),q(ie,"viewUpdateNode");function de(e){const r=e[0],t=e.map(ae);return $e({...r,...me(e),kind:"commit-effects",title:e.length===1?`effect \xB7 ${t[0]}`:`effects \xB7 ${t[0]} + ${e.length-1} more`,detail:t.join(", "),commitId:r.commitId,effects:e.length,effectHooks:t,memberIds:e.map(o=>o.id),sig:`effects:${t.slice().sort().join(",")}`})}R(de,"pt"),D(de,"Me"),q(de,"effectsNode");const Se=q(e=>G(e.map(r=>r==="state-update"?"state update":r==="fetch-start"?"request":r==="flow-origin"?"interaction":"response")).join(" + "),"describeInputs");function ue(e,r){const t=e[0],o=e[e.length-1],n=e.length,a=t.detail,$=Math.min(...e.map(v=>v.start)),k=Math.max(...e.map(v=>v.start+(v.durationMs??0))),u=Math.round(e.reduce((v,w)=>v+(w.durationMs??0),0)/n*10)/10,c=Math.round((k-$)*10)/10;t.count=n,t.avgMs=u,t.wallMs=c,t.durationMs=k-$,t.items=e.slice(0,12).map(v=>({start:v.start-$,...v.durationMs!=null?{durationMs:v.durationMs}:{}})),t.memberIds=e.flatMap(v=>v.memberIds??[v.id]),t.title=`\xD7${n} ${t.title}`,e.some(v=>v.severity==="error")&&(t.severity="error"),t.kind==="view-update"?t.detail=[`${n} commits, ${r.length?`one per ${Se(r)}`:"back to back"}`,`avg ${u}ms \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 "):t.kind==="state-update"&&a&&o.detail?t.detail=`${n} updates in a row \xB7 wall ${c}ms \xB7 first ${a} \xB7 last ${o.detail}`:t.detail=[`${n} in a row \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 ")}R(ue,"ft"),D(ue,"be"),q(ue,"collapseRepeat");const se=[],oe=new Map,ye=new Set;for(let e=0;e<m.length;e++){if(ye.has(e))continue;const r=m[e];if(!C(r)){se.push(r);continue}const t=[e];for(let a=e+1;a<m.length;a++){const $=m[a];if($.group==="browser"){if(!C($)||$.commitId!==r.commitId)break;t.push(a)}}for(const a of t)ye.add(a);const o=t.map(a=>m[a]),n=o.some(a=>a.kind!=="effect-run")?ie(o):de(o);for(const a of o)a.id!==n.id&&oe.set(a.id,n.id);se.push(n)}if(oe.size>0||se.some(e=>e.kind==="view-update"||e.kind==="commit-effects")){m=se;for(const e of m)for(;e.parent&&oe.has(e.parent);)e.parent=oe.get(e.parent)}{const e=new Map;for(const r of m)r.kind==="view-update"&&r.commitId&&!e.has(r.commitId)&&e.set(r.commitId,r);for(const r of m){if(r.kind!=="commit-effects"||r.parent||!r.commitId)continue;const t=e.get(r.commitId);t&&t.start<=r.start&&(r.parent=t.id)}}{const e=new Set(["state-update","fetch","fetch-start","fetch-done","fetch-error","flow-origin"]),r=m.map((u,c)=>u.group==="browser"?c:-1).filter(u=>u>=0),t=q(u=>`${u.kind}|${u.sig??u.title}`,"keyOf"),o=r.map(u=>t(m[u])),n=q((u,c,v)=>{for(let w=0;w<v;w++)if(o[u+w]!==o[c+w])return!1;return!0},"sameBlock"),a=q(u=>o[u].split("|")[0],"kindAt"),$=q(u=>{let c=0,v=1;for(let w=1;w<=4&&u+w<=o.length;w++){let A=1;for(;u+(A+1)*w<=o.length&&n(u,u+A*w,w);)A+=1;A>=3&&w*A>c*v&&(c=w,v=A)}return{k:c,r:v}},"bestBlockAt"),k=new Map;for(let u=0;u<o.length;){const{k:c,r:v}=$(u);if(c===0){u+=1;continue}const w=[...Array(c).keys()].find(j=>e.has(a(u+j)));if(w!==void 0&&w>0){const j=$(u+w);if(j.k===c&&j.r>=3&&j.r>=v-1){u+=w;continue}}const A=o.slice(u,u+c).map(j=>j.split("|")[0]).filter(j=>e.has(j));for(let j=0;j<c;j++){const P=[];for(let F=0;F<v;F++)P.push(m[r[u+j+F*c]]);ue(P,A);for(const F of P.slice(1))k.set(F.id,P[0].id)}u+=c*v}if(k.size>0){m=m.filter(u=>!k.has(u.id));for(const u of m)for(;u.parent&&k.has(u.parent);)u.parent=k.get(u.parent)}}{const e=new Map(m.map(r=>[r.id,r]));for(const r of m){const t=new Set([r.id]);let o=r;for(;o?.parent;){if(t.has(o.parent)){o.parent=void 0;break}t.add(o.parent),o=e.get(o.parent)}}}const ve=q(e=>{const r=new Map;for(const o of m){if(!o.sig||b(o)!==e||o.kind==="server-request"||o.kind==="gateway-request"||o.group==="browser")continue;const n=`${o.parent??"root"}|${o.kind}|${o.sig}`,a=r.get(n);a?a.push(o):r.set(n,[o])}const t=new Map;for(const o of r.values()){if(o.length<3)continue;o.sort((c,v)=>c.start-v.start);const n=o[0];let a=!1;for(let c=0;c+1<o.length;c++)if(o[c+1].start<o[c].start+(o[c].durationMs??0)){a=!0;break}const $=n.start,k=Math.max(...o.map(c=>c.start+(c.durationMs??0))),u=o.reduce((c,v)=>c+(v.durationMs??0),0);n.count=o.length,n.parallel=a,n.avgMs=Math.round(u/o.length*10)/10,n.wallMs=k-$,n.durationMs=k-$,n.title=`\xD7${o.length} ${n.title.replace(/\s*\((?:\d+ rows?, )?\d+ms\)$/,"")}`,n.detail=`${n.sig} \xD7${o.length} ${a?"\u2016 parallel":"\u21BB sequential loop"} \xB7 avg ${n.avgMs}ms \xB7 wall ${n.wallMs}ms`,n.items=o.slice(0,12).map(c=>({start:c.start-$,...c.durationMs!=null?{durationMs:c.durationMs}:{}})),n.memberIds=o.flatMap(c=>c.memberIds??[c.id]),o.some(c=>c.severity==="error")&&(n.severity="error");for(const c of o.slice(1))t.set(c.id,n.id)}if(t.size!==0){m=m.filter(o=>!t.has(o.id));for(const o of m)for(;o.parent&&t.has(o.parent);)o.parent=t.get(o.parent)}},"aggregatePass");ve(!0),ve(!1);for(const e of m){if(!b(e))continue;const r=e.durationMs??0;if(r<40)continue;const t=m.filter(k=>k.parent===e.id&&(k.durationMs??0)>0).map(k=>[k.start,k.start+(k.durationMs??0)]).sort((k,u)=>k[0]-u[0]);let o=0,n=-1,a=-1;for(const[k,u]of t)k>a?(a>n&&(o+=a-n),n=k,a=u):u>a&&(a=u);a>n&&(o+=a-n);const $=Math.max(0,r-o);($>=50||$/r>=.7&&r>=40)&&(e.selfMs=$,e.detail=`\u26A0 cpu-heavy: ${$}ms self-time of ${r}ms${e.detail?" \xB7 "+e.detail:""}`)}return{events:m,...s?{sql:s}:{}}}R(buildFlowDetail,"buildFlowDetail"),D(buildFlowDetail,"buildFlowDetail"),q(buildFlowDetail,"buildFlowDetail");
1
+ "use strict";var Bt=Object.defineProperty;var R=(i,m)=>Bt(i,"name",{value:m,configurable:!0});var At=Object.defineProperty,k=R((i,m)=>At(i,"name",{value:m,configurable:!0}),"I");import{redactDeep as Rt,redactText as at,redactUrlParams as Tt}from"./redact.js";import{templatisePath as $t}from"./route-template.js";import{SQL_ACCOUNT_KIND as Dt,sqlAccountingOf as Ct,stallsAfterResponse as Pt}from"./flow-segments.js";import{isServiceHopHost as yt}from"./service-hop.js";import{queueSignalOf as vt,queueSignalWords as Ot}from"./queue-signals.js";import{boundedClone as Ft}from"@lensmcp/protocol-types";export function areaOf(i){const{source:m,category:s,title:I,kind:l}=i;return m==="ai"?"ai":m==="perf"&&l==="event-loop-stall"?"services":l?.startsWith("memory")||l==="db-query"?"data":m==="gateway"||l==="gateway-request"?"gateway":l==="queue-process"||l==="queue-active"||l==="queue-completed"||l==="queue-failed"?"services":m==="db"||m==="redis"||m==="queue"||l==="redis-op"||l?.startsWith("queue-")||m==="fs"||l==="fs-ops"?"data":m==="exec"||l==="exec"||l==="egress"&&yt(i.host)?"services":m==="external"||l==="egress"?"network":m==="nestjs"||m==="nest"?/(?:Repository|Repo|Dao|Store|EntityManager|DataSource|QueryRunner|OrmClient)\./.test(I)?"data":"services":m==="valtio"?"state":s==="network"?"network":"browser"}R(areaOf,"areaOf"),k(areaOf,"areaOf");const kt=240,Nt=new Set(["systemPrompt","prompt","prompts","messages","completion","completions","input","output","draft","text","content","result","arguments","params"]),Et=new Set(["tenantId","caller","userId","accountId","email","subject"]),Lt=8;function qt(i){const m=st(i,0);return Ft(Rt({redacted:!0,...m}),{rawByteLimit:16*1024}).value}R(qt,"Be"),k(qt,"aiProjection");function st(i,m){if(typeof i=="string")return wt(i);if(i===null||typeof i!="object")return i;if(m>=Lt)return;if(Array.isArray(i))return i.slice(0,32).map(I=>st(I,m+1));const s={};for(const[I,l]of Object.entries(i))if(!Et.has(I)){if(Nt.has(I)){typeof l=="string"?s[`${I}Chars`]=l.length:Array.isArray(l)?s[`${I}Count`]=l.length:l!=null&&(s[`${I}Present`]=!0);continue}s[I]=st(l,m+1)}return s}R(st,"ae"),k(st,"projectAi");function wt(i){return i.length<=kt?at(i):`${at(i.slice(0,kt))}\u2026`}R(wt,"_e"),k(wt,"clipText");export function httpFacts(i,m){const s=k(M=>typeof M=="string"&&M.length>0?M:void 0,"str"),I=typeof m.status=="number"?m.status:void 0,l=k(M=>Tt(M.split("?")[0]??M)||"/","pathOf"),F=k((M,b,y={})=>({...M?{method:M.toUpperCase()}:{},...b?{rawPath:b,route:$t(b)}:{},...I!==void 0?{status:I}:{},...y}),"facts");if(i==="gateway-request"){const M=s(m.url);return F(s(m.method),M?l(M):void 0,{...s(m.host)?{host:s(m.host)}:{},...s(m.caller)?{caller:s(m.caller)}:{}})}if(i==="egress"){const M=s(m.path),b=s(m.exchangeId);return F(s(m.method)??"GET",M?l(M):void 0,{...s(m.host)?{host:s(m.host)}:{},...b?{exchangeId:b}:{}})}if(i==="fetch-start"||i==="fetch-done"||i==="fetch-error"){const M=s(m.href)??s(m.url);let b,y;if(M)try{const p=new URL(M,"http://relative.invalid");b=l(p.pathname),p.hostname!=="relative.invalid"&&(y=p.hostname)}catch{}return F(s(m.method)??"GET",b,y?{host:y}:{})}if(i==="ai-call")return{...I!==void 0?{status:I}:{},...m.stream===!0?{streamed:!0}:{}};const f=m.request;if(f&&typeof f=="object"){const M=f,b=s(M.route),y=s(M.method);if(!b&&!y)return{};const p=typeof M.status=="number"?M.status:void 0,N=b?l(b):void 0;return{...y?{method:y.toUpperCase()}:{},...N?{rawPath:N,route:N.includes(":")?N:$t(N)}:{},...p!==void 0?{status:p}:{}}}return{}}R(httpFacts,"httpFacts"),k(httpFacts,"httpFacts");export function trimFlowEvent(i,m={}){const s=i.raw??{},I=s.render??{},l=s.span??{},F=s.request??{},f=k(d=>typeof d=="number"?d:void 0,"num"),M=s.loop??{},b=s.effect??{},y=f(s.durationMs)??f(l.durationMs)??f(F.durationMs)??f(M.durationMs)??f(I.actualDurationMs)??f(b.durationMs),p=typeof s.kind=="string"?s.kind:void 0,N=p==="fetch-done"||p==="fetch-error",W=f(I.commitTime),tt=p==="render"&&W!==void 0&&Math.abs(W-i.timestamp)<6e4,z=N?i.timestamp:tt?W:f(s.startedAt)??f(l.startTime)??f(F.startedAt)??f(M.startedAt)??(y!==void 0?i.timestamp-y:i.timestamp);let x;if(typeof s.query=="string"){const d=Array.isArray(s.params)?` [${s.params.join(", ")}]`:"",g=typeof s.result=="string"?` \u2192 ${s.result}`:"";x=s.query+d+g}else if(typeof s.command=="string"){const d=typeof s.value=="string"?` \u2192 ${s.value}`:s.hit===!1?" \u2192 (miss)":"";x=s.command+d}else if(p==="state-update"){const d=s.update??{};let g="";try{g=JSON.stringify(d.preview)}catch{}x=`${d.storeId??""}.${d.path??""} = ${g}`}else if(p==="fs-ops"&&Array.isArray(s.paths))x=s.paths.slice(0,8).map(d=>{const g=d??{},B=typeof g.n=="number"&&g.n>1?` \xD7${g.n}`:"",h=typeof g.bytes=="number"&&g.bytes>0?` (${g.bytes>=1024?`${(g.bytes/1024).toFixed(1)} KB`:`${g.bytes} B`})`:"";return`${String(g.op??"?")} ${String(g.path??"?")}${B}${h}`}).join(" \xB7 ");else if(p==="exec"&&typeof s.cmd=="string")x=`${s.cmd} \u2192 ${s.code??s.signal??s.error??"?"}`;else if(p==="queue-completed"&&typeof s.returned=="string")x=`returned ${s.returned}`;else if(p==="queue-enqueued")x=`${s.job??"job"}#${s.jobId??"?"} \u2192 ${s.queue??""}${typeof s.data=="string"?" "+s.data:""}`;else if(p==="log"){const d=F.error??{},g=typeof d.stack=="string"?d.stack:typeof s.text=="string"?s.text:void 0;g&&g!==i.title&&(x=g)}let U,E;p==="queue-process"&&(E=vt(s.status));let _,Y,H;if(p==="span"){const d=l.outcome;if(E=d==="signalled"?vt(l.signal):void 0,U=E?"signalled":d==="threw"||d==="returned"?d:l.status==="error"?"threw":l.status==="ok"?"returned":void 0,U==="threw"){const h=l.error??{},D=typeof h.name=="string"?h.name:void 0,K=typeof h.message=="string"?h.message:typeof i.message=="string"?i.message:void 0;Y=D,_=at([D,K].filter(Boolean).join(": "))||void 0}const g=typeof l.args=="string"?l.args:void 0,B=typeof l.result=="string"?l.result:void 0;if(g!==void 0||B!==void 0){H=[...g!==void 0?["args"]:[],...B!==void 0?["result"]:[]];const h=k(D=>D.length>Mt?`${D.slice(0,Mt)}\u2026`:D,"short");x=[g!==void 0?`args ${h(g)}`:"",B!==void 0?`returned ${h(B)}`:""].filter(Boolean).join(" \u2192 ")}}let G;if(p==="gateway-request")G=`${s.host??""}${String(s.url??"").split("?")[0]}`;else if(p==="fetch-start"||p==="fetch-done"||p==="fetch-error")try{const d=new URL(String(s.href??s.url??""));G=`${d.hostname}${d.pathname}`}catch{}let P;if(p==="gateway-request"&&Array.isArray(s.steps))P=s.steps.map(d=>{const g=[String(d.step)];return d.project&&g.push(String(d.project)),d.prefix&&g.push(String(d.prefix)),d.mode&&g.push(String(d.mode)+(d.ok===!1?" \u2717":d.ok===!0?" \u2713":"")),d.caller&&g.push("by "+String(d.caller)),d.pod&&g.push(String(d.pod)),typeof d.atMs=="number"&&g.push(`@${d.atMs}ms`),g.join(" ")}),x=P.map(d=>d.replace(/ @\d+ms$/,"")).join(" \u2192 ");else if(p==="egress")x=`${s.method??"GET"} ${s.host??""} \u2192 ${s.status??"?"}`;else if(i.source==="ai"){if(p==="ai-call"){const d=s.usage??{},g=d.promptTokens!==void 0||d.completionTokens!==void 0?` \xB7 ${f(d.promptTokens)??"?"}\u2192${f(d.completionTokens)??"?"} tok`:"",B=s.status!==void 0?` \xB7 ${String(s.status)}`:s.error?" \xB7 failed":"",h=f(s.toolCallCount)?` \xB7 ${f(s.toolCallCount)} tool call${f(s.toolCallCount)===1?"":"s"}`:"",D=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${s.provider??""}/${s.model??"?"}${g}${B}${h}${D}${s.stream===!0?" \xB7 stream":""}`}else if(p==="ai-round"){const d=s.model??{},g=s.usage??{},B=Array.isArray(s.toolCalls)?s.toolCalls:[],h=`${f(g.promptTokens)??"?"}\u2192${f(g.completionTokens)??"?"} tok`,D=B.length?` \xB7 ${B.length} tool call${B.length===1?"":"s"}`:"",K=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${d.provider??""}/${d.model??""} \xB7 ${h}${D}${K}`}else if(p==="ai-turn-start"){const d=Array.isArray(s.tools)?s.tools:[];x=`skill ${s.skill??""} \xB7 ${s.output??""}${d.length?" \xB7 tools: "+d.join(", "):""}`}else if(p==="ai-tool-call"){const d=s.call??{},g=s.result??{},B=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${d.name??"tool"} ${g.error!=null?"\u2717 "+String(g.error):"\u2713"}${B}`}else if(p==="ai-turn-end"){const d=s.usage??{},g=f(s.rounds)!==void 0?` \xB7 ${f(s.rounds)} round${f(s.rounds)===1?"":"s"}`:"",B=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${s.ok===!1?"FAILED":"ok"} \xB7 ${f(d.promptTokens)??"?"}+${f(d.completionTokens)??"?"} tok${g}${B}`}}let T;p==="db-query"&&typeof s.query=="string"?T=s.query:p==="redis-op"?T=`${s.op??""} ${String(s.key??"").replace(/\d+/g,"#")}`:p==="egress"?T=`${s.method??"GET"} ${s.host??""}`:p==="ai-call"?T=`ai ${s.provider??""} ${s.model??""} ${s.api??""}`:p==="queue-enqueued"?T=`enqueue ${s.queue??""}`:p==="span"&&typeof l.name=="string"?T=l.name:p==="memory-mutation"&&(T=i.title);const L=i.context??{},Z=I.commitId??b.commitId??s.commitId,Q=Array.isArray(I.why)?I.why.map(d=>typeof d?.type=="string"?d.type:void 0).filter(d=>!!d):[];return{id:i.id,t:i.timestamp,start:z,...T?{sig:T}:{},...G?{urlKey:G}:{},...httpFacts(p,s),...(p==="db-query"||p==="redis-op")&&typeof s.valuesId=="string"?{valuesId:s.valuesId}:{},...p==="db-query"&&typeof s.name=="string"&&s.name!=="postgres"?{db:s.name}:{},...p?.startsWith("queue-")&&typeof s.broker=="string"?{broker:s.broker}:{},...typeof s.queue=="string"?{queue:s.queue}:{},...s.jobId!=null?{jobId:String(s.jobId)}:{},source:i.source,category:i.category,severity:i.severity,title:U==="threw"&&typeof l.name=="string"?`${l.name} \u2014 threw${Y?` ${Y}`:""}${y!==void 0?` after ${y}ms`:""}`:p==="queue-process"&&E?`process ${String(s.job??"job")}#${String(s.jobId??"?")} \u2014 ran, ${Ot(E,f(s.delayMs))}${y!==void 0?` (${y}ms)`:""}`:i.title,kind:p,area:areaOf({source:i.source,category:i.category,title:i.title,kind:p,...typeof s.host=="string"?{host:s.host}:{}}),...p==="egress"&&yt(typeof s.host=="string"?s.host:void 0)?{hop:!0}:{},...p==="egress"&&typeof s.calleeRequestId=="string"?{calleeRequestId:s.calleeRequestId}:{},...U?{outcome:U}:{},...E?{signal:E}:{},..._?{error:_}:{},...H?{captured:H}:{},...typeof l.role=="string"?{role:l.role}:{},...typeof l.spanId=="string"?{spanId:l.spanId}:{},...typeof l.parentSpanId=="string"?{parentSpanId:l.parentSpanId}:{},...p==="log"&&typeof s.level=="string"?{level:s.level}:{},...p==="log"&&typeof s.logger=="string"?{logger:s.logger}:{},...p==="log"&&typeof s.stream=="string"?{stream:s.stream}:{},...typeof L.requestId=="string"?{requestId:L.requestId}:{},...typeof L.parentRequestId=="string"?{parentRequestId:L.parentRequestId}:{},...typeof Z=="string"?{commitId:Z}:{},...typeof I.componentName=="string"?{component:I.componentName}:{},...typeof I.phase=="string"?{phase:I.phase}:{},...Q.length?{why:Q}:{},...p==="effect-run"&&typeof b.hookLogicalId=="string"?{hook:b.hookLogicalId}:{},...p==="effect-run"&&b.cleanupRan===!0?{cleanup:!0}:{},...p==="render-commit-truncated"?{renderTotal:f(s.total),renderPublished:f(s.published),...f(s.walkStoppedAt)!==void 0?{renderWalkStoppedAt:f(s.walkStoppedAt)}:{}}:{},...typeof L.projectName=="string"?{project:L.projectName}:typeof s.project=="string"?{project:s.project}:{},...y!==void 0?{durationMs:y}:{},...N&&f(s.startedAt)!==void 0?{fetchStartedAt:f(s.startedAt)}:{},...i.source==="ai"?{ai:m.includeRaw?s:qt(s)}:{},...x?{detail:x}:{},...P?{steps:P}:{}}}R(trimFlowEvent,"trimFlowEvent"),k(trimFlowEvent,"trimFlowEvent");const Mt=300;export const OUTLIVED_PARENT_MIN_MS=250;const Wt=new Set(["egress","db-query","redis-op","ai-call","span","gateway-request","server-request"]),it=1;function It(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(It,"Oe"),k(It,"kindRank");function V(i){return i.kind==="span"&&i.role==="controller"?3.5:i.kind==="queue-process"?3:It(i.kind)}R(V,"Z"),k(V,"causalRank");export function buildFlowDetail(i,m={}){const s=Ct(i),I=Pt(i),l=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===Dt)return!1;const o=r.span;return!(typeof o?.name=="string"&&o.name.startsWith("nest.request "))}).map(t=>trimFlowEvent(t,m)),F=new Set;for(let t=l.length-1;t>=0;t--)F.has(l[t].id)?l.splice(t,1):F.add(l[t].id);const f=new Map;for(const t of l)(t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&!f.has(t.requestId)&&f.set(t.requestId,t.start);const M=k(t=>t.source!=="react"&&t.source!=="valtio"&&t.requestId&&f.has(t.requestId)?f.get(t.requestId):t.start,"anchorOf");l.sort((t,r)=>M(t)-M(r)||t.start-r.start||V(t)-V(r)||(r.durationMs??0)-(t.durationMs??0)||t.t-r.t);const b=k(t=>(t.kind==="span"||t.kind==="server-request"||t.kind==="gateway-request"||t.kind==="queue-process")&&(t.durationMs??0)>0,"spanLike"),y=l;for(const t of y)t.group=t.source==="react"||t.source==="valtio"||t.source==="client-runtime"||t.source==="visual"?"browser":"server";const p=new Map;for(const t of y)if((t.kind==="gateway-request"||t.kind==="queue-process")&&t.requestId&&t.project){const r=p.get(t.requestId)??[];r.push({project:t.project,start:t.start,end:t.start+(t.durationMs??0)}),p.set(t.requestId,r)}const N=k((t,r)=>{const e=p.get(t);if(e?.length)return e.every(o=>o.project===e[0].project)?e[0].project:e.filter(o=>o.start<=r+1&&o.end>=r-1).sort((o,n)=>n.start-o.start)[0]?.project},"projectOf");for(const t of y)if(!t.project&&t.source==="nestjs"&&t.requestId){const r=N(t.requestId,t.start);r&&(t.project=r)}const W=new Map;for(const t of y)t.spanId&&W.set(t.spanId,t);const tt=k((t,r)=>{let e=t.parentSpanId?W.get(t.parentSpanId):void 0;for(let o=0;e&&o<64;o++){if(e===r)return!0;e=e.parentSpanId?W.get(e.parentSpanId):void 0}return!1},"inside"),z=new Map(y.map((t,r)=>[t,r])),x=new Map,U=k(t=>{let r=x.get(t.group);r||x.set(t.group,r=new Map);const e=t.requestId;let o=r.get(e);return o||r.set(e,o={spans:[],next:0,alive:[]}),o},"legOf");for(const t of y)b(t)&&Number.isFinite(t.start)&&U(t).spans.push(t);for(const t of x.values())for(const r of t.values())r.spans.sort((e,o)=>e.start-o.start||z.get(e)-z.get(o));const E=k(t=>Number.isFinite(t.start)?t.start:1/0,"startOf");for(const t of y.slice().sort((r,e)=>E(r)-E(e))){const r=t.parentSpanId?W.get(t.parentSpanId):void 0;if(r&&r!==t&&r.group===t.group&&r.requestId===t.requestId){t.parent=r.id;continue}if(!Number.isFinite(t.start))continue;const e=U(t);for(;e.next<e.spans.length&&e.spans[e.next].start<=t.start+it;)e.alive.push(e.spans[e.next++]);e.alive=e.alive.filter(a=>a.start+(a.durationMs??0)>t.start);const o=e.alive.length>1?e.alive.slice().sort((a,$)=>z.get(a)-z.get($)):e.alive;let n;for(const a of o){if(a===t)continue;const $=a.project,q=t.project;if(a.kind!=="gateway-request"&&t.kind!=="gateway-request"&&$!==void 0&&q!==void 0&&$!==q)continue;const u=a.durationMs??0,c=t.durationMs??0,v=Math.abs(a.start-t.start)<=it,w=V(a),A=V(t),j=a.start<=t.start;if(!(a.start+u>t.start&&(j||v&&w<A)&&(!v||(w!==A?w<A:j&&u>c))))continue;const O=n?V(n):-1,C=n?Math.abs(a.start-n.start)<=it:!1,J=n&&C&&w===O?tt(a,n)?1:tt(n,a)?-1:0:0;(!n||!C&&a.start>n.start||C&&w>O||J>0||J===0&&C&&w===O&&(a.durationMs??0)<(n.durationMs??0))&&(n=a)}n&&(t.parent=n.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,o=[],n=k(a=>{const $=[a];for(;$.length;){const q=$.pop();o.push(q),r.add(q.id);const u=e.get(q.id);if(u){e.delete(q.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 n(a);for(const a of y)r.has(a.id)||(o.push(a),r.add(a.id));for(let a=0;a<o.length;a++)y[a]=o[a]}const _=new Map;for(const t of y){if(!t.requestId)continue;const r=_.get(t.requestId);r?r.push(t):_.set(t.requestId,[t])}const Y=new Map(y.map(t=>[t.id,t])),H=new Map;for(const t of y)t.calleeRequestId&&!H.has(t.calleeRequestId)&&H.set(t.calleeRequestId,t);const G=k((t,r)=>{const e=(_.get(t)??[]).filter(o=>b(o)&&o.start<=r&&o.start+(o.durationMs??0)>=r);if(e.length!==0)return e.sort((o,n)=>n.start-o.start||(o.durationMs??0)-(n.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?Y.get(t.parent):void 0;if(r&&r.requestId===t.requestId)continue;const e=t.requestId?H.get(t.requestId):void 0,o=e&&e.start<=t.start?e:G(t.parentRequestId,t.start);o&&o!==t&&o.start<=t.start&&(t.parent=o.id)}const P=y,T=new Map;for(const t of P)t.kind==="gateway-request"&&t.requestId&&!T.has(t.requestId)&&T.set(t.requestId,t);for(const t of P)if(t.group==="server"&&!t.parent&&t.requestId&&t.kind!=="gateway-request"){const r=T.get(t.requestId);r&&r!==t&&r.start<=t.start&&(t.parent=r.id)}const L=new Set,Z=new Set,Q=[];for(const t of P){if(t.kind!=="gateway-request")continue;if(!t.requestId){Q.push(t);continue}const r=_.get(t.requestId)??[];if(r.filter(n=>n.kind==="gateway-request").sort((n,a)=>n.start-a.start)[0]!==t)continue;const e=r.find(n=>n.kind==="fetch-start"),o=r.find(n=>n.kind==="fetch-done"||n.kind==="fetch-error");if(!e&&!o){Q.push(t);continue}e&&(t.fetchStartId=e.id,L.add(e.id)),o&&(t.fetchDoneId=o.id,Z.add(o.id))}const d=new Map;for(const t of P){if(!t.urlKey)continue;const r=d.get(t.urlKey)??{gws:[],starts:[],dones:[]};t.kind==="gateway-request"?Q.includes(t)&&r.gws.push(t):t.kind==="fetch-start"?L.has(t.id)||r.starts.push(t):(t.kind==="fetch-done"||t.kind==="fetch-error")&&(Z.has(t.id)||r.dones.push(t)),d.set(t.urlKey,r)}for(const{gws:t,starts:r,dones:e}of d.values()){t.sort((n,a)=>n.start-a.start),r.sort((n,a)=>n.start-a.start);const o=new Set;t.forEach((n,a)=>{const $=r[a];$&&(n.fetchStartId=$.id);const q=$?$.t:n.start;let u,c=1/0;for(const v of e){if(o.has(v.id))continue;const w=v.fetchStartedAt??v.start-(v.durationMs??0),A=Math.abs(w-q);A<c&&(c=A,u=v)}u&&(n.fetchDoneId=u.id,o.add(u.id))})}const g=new Map,B=new Map;for(const t of P)!t.queue||!t.jobId||(t.kind==="queue-enqueued"&&g.set(`${t.queue}#${t.jobId}`,t),t.kind==="queue-process"&&B.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=g.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=B.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||!Wt.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 o=Math.round(r.start+r.durationMs-(e.start+e.durationMs));if(o<OUTLIVED_PARENT_MIN_MS)continue;r.outlivedParentMs=o;const n=e.leftRunning??{count:0,longestMs:0};e.leftRunning={count:n.count+1,longestMs:Math.max(n.longestMs,o)}}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 "))}}if(I.size>0)for(const t of y){const r=I.get(t.id);r!==void 0&&(t.afterResponseMs=r,t.detail=[t.detail,`began ${r}ms after the request's response had finished \u2014 not part of the request's time`].filter(Boolean).join(" \xB7 "))}let h=y;{const t=new Map;for(const e of h)e.kind==="fetch-start"&&t.set(e.id,e);const r=new Map;for(const e of h){if(e.kind!=="fetch-done"&&e.kind!=="fetch-error")continue;const o=[...t.values()].find($=>$.requestId&&$.requestId===e.requestId)?.id,n=o?t.get(o):void 0;if(!n)continue;const a=e.fetchStartedAt??n.start;n.title=e.title,n.severity=e.severity,n.durationMs=e.durationMs??Math.max(0,e.t-a),n.kind="fetch",e.detail&&!n.detail&&(n.detail=e.detail),r.set(e.id,n.id)}if(r.size>0){h=h.filter(e=>!r.has(e.id));for(const e of h)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 D=k(t=>!!t.commitId&&(t.kind==="render"||t.kind==="effect-run"||t.kind==="render-commit-truncated"),"commitMember"),K=k(t=>[...new Set(t)],"uniq"),ot=k(t=>K(t.map(r=>r.component).filter(r=>!!r)),"named"),bt=k(t=>t.length<=2?t.join(" + "):`${t[0]} + ${t.length-1} more`,"nameList"),dt=k(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,o])=>o>1?`${e} \xD7${o}`:e).join(", ")},"tally"),xt=k(t=>{if(!t)return"effect";const r=/([^/\\]+?):(\d+)(?::\d+)?$/.exec(t);return r?`${r[1]}:${r[2]}`:t},"shortHook"),nt=k(t=>`${xt(t.hook)}${t.cleanup?" (cleanup)":""}`,"hookLabel"),ut=k(t=>{const r=Math.min(...t.map(o=>o.start)),e=Math.max(...t.map(o=>o.start+(o.durationMs??0)));return{start:r,durationMs:e-r}},"extent"),ct=k(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 lt(t){const r=t[0],e=t.filter(S=>S.kind==="render"),o=t.filter(S=>S.kind==="effect-run"),n=t.find(S=>S.kind==="render-commit-truncated"),a=[...e].sort((S,X)=>(X.durationMs??0)-(S.durationMs??0)),$=a.filter(S=>(S.why??[]).some(X=>X!=="parent-render")),q=K($.flatMap(S=>(S.why??[]).filter(X=>X!=="parent-render"))),u=ot($),c=e.filter(S=>S.phase==="mount"),v=e.filter(S=>S.phase!=="mount"&&!$.includes(S)),w=a[0]?.component??"view",A=e.length>0&&c.length===e.length,j=q.length?q.join(" + "):void 0,O=A?"mount":"update",C=u.length?`view update \xB7 ${bt(u)} \u2190 ${j}`:A?`view mount \xB7 ${w}`:`view update \xB7 ${w}`,J=n?.renderTotal??e.length,St=[c.length?`mounted ${dt(c)}`:"",v.length?`re-rendered ${dt(v)}`:"",!u.length&&!A&&e.length?"trigger not recorded \u2014 every captured render came from its parent":"",n?.renderWalkStoppedAt!==void 0?`at least ${J} renders (the walk stopped at ${n.renderWalkStoppedAt} fibers), ${n.renderPublished??e.length} recorded`:n?`${J} renders, ${n.renderPublished??e.length} recorded (per-commit cap)`:`${e.length} render${e.length===1?"":"s"}`,o.length?`${o.length} effect${o.length===1?"":"s"}: ${o.map(nt).join(", ")}`:""].filter(Boolean).join(" \xB7 "),ht=ot(e);return ct({...r,...ut(t),kind:"view-update",title:C,detail:St,commitId:r.commitId,viewPhase:O,...j?{cause:j}:{},causeComponents:u,components:ht,mounted:ot(c),renderCount:J,...n?.renderWalkStoppedAt!==void 0?{renderCountAtLeast:!0}:{},recordedRenders:e.length,effects:o.length,effectHooks:o.map(nt),memberIds:t.map(S=>S.id),sig:`commit:${O}:${j??"-"}:${u.join(",")}:${ht.slice().sort().join(",")}`,severity:t.some(S=>S.severity==="error")?"error":r.severity})}R(lt,"ke"),k(lt,"viewUpdateNode");function pt(t){const r=t[0],e=t.map(nt);return ct({...r,...ut(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(o=>o.id),sig:`effects:${e.slice().sort().join(",")}`})}R(pt,"Me"),k(pt,"effectsNode");const jt=k(t=>K(t.map(r=>r==="state-update"?"state update":r==="fetch-start"?"request":r==="flow-origin"?"interaction":"response")).join(" + "),"describeInputs");function ft(t,r){const e=t[0],o=t[t.length-1],n=t.length,a=e.detail,$=Math.min(...t.map(v=>v.start)),q=Math.max(...t.map(v=>v.start+(v.durationMs??0))),u=Math.round(t.reduce((v,w)=>v+(w.durationMs??0),0)/n*10)/10,c=Math.round((q-$)*10)/10;e.count=n,e.avgMs=u,e.wallMs=c,e.durationMs=q-$,e.items=t.slice(0,12).map(v=>({start:v.start-$,...v.durationMs!=null?{durationMs:v.durationMs}:{}})),e.memberIds=t.flatMap(v=>v.memberIds??[v.id]),e.title=`\xD7${n} ${e.title}`,t.some(v=>v.severity==="error")&&(e.severity="error"),e.kind==="view-update"?e.detail=[`${n} commits, ${r.length?`one per ${jt(r)}`:"back to back"}`,`avg ${u}ms \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 "):e.kind==="state-update"&&a&&o.detail?e.detail=`${n} updates in a row \xB7 wall ${c}ms \xB7 first ${a} \xB7 last ${o.detail}`:e.detail=[`${n} in a row \xB7 wall ${c}ms`,a??""].filter(Boolean).join(" \xB7 ")}R(ft,"be"),k(ft,"collapseRepeat");const et=[],rt=new Map,mt=new Set;for(let t=0;t<h.length;t++){if(mt.has(t))continue;const r=h[t];if(!D(r)){et.push(r);continue}const e=[t];for(let a=t+1;a<h.length;a++){const $=h[a];if($.group==="browser"){if(!D($)||$.commitId!==r.commitId)break;e.push(a)}}for(const a of e)mt.add(a);const o=e.map(a=>h[a]),n=o.some(a=>a.kind!=="effect-run")?lt(o):pt(o);for(const a of o)a.id!==n.id&&rt.set(a.id,n.id);et.push(n)}if(rt.size>0||et.some(t=>t.kind==="view-update"||t.kind==="commit-effects")){h=et;for(const t of h)for(;t.parent&&rt.has(t.parent);)t.parent=rt.get(t.parent)}{const t=new Map;for(const r of h)r.kind==="view-update"&&r.commitId&&!t.has(r.commitId)&&t.set(r.commitId,r);for(const r of h){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=h.map((u,c)=>u.group==="browser"?c:-1).filter(u=>u>=0),e=k(u=>`${u.kind}|${u.sig??u.title}`,"keyOf"),o=r.map(u=>e(h[u])),n=k((u,c,v)=>{for(let w=0;w<v;w++)if(o[u+w]!==o[c+w])return!1;return!0},"sameBlock"),a=k(u=>o[u].split("|")[0],"kindAt"),$=k(u=>{let c=0,v=1;for(let w=1;w<=4&&u+w<=o.length;w++){let A=1;for(;u+(A+1)*w<=o.length&&n(u,u+A*w,w);)A+=1;A>=3&&w*A>c*v&&(c=w,v=A)}return{k:c,r:v}},"bestBlockAt"),q=new Map;for(let u=0;u<o.length;){const{k:c,r:v}=$(u);if(c===0){u+=1;continue}const w=[...Array(c).keys()].find(j=>t.has(a(u+j)));if(w!==void 0&&w>0){const j=$(u+w);if(j.k===c&&j.r>=3&&j.r>=v-1){u+=w;continue}}const A=o.slice(u,u+c).map(j=>j.split("|")[0]).filter(j=>t.has(j));for(let j=0;j<c;j++){const O=[];for(let C=0;C<v;C++)O.push(h[r[u+j+C*c]]);ft(O,A);for(const C of O.slice(1))q.set(C.id,O[0].id)}u+=c*v}if(q.size>0){h=h.filter(u=>!q.has(u.id));for(const u of h)for(;u.parent&&q.has(u.parent);)u.parent=q.get(u.parent)}}{const t=new Map(h.map(r=>[r.id,r]));for(const r of h){const e=new Set([r.id]);let o=r;for(;o?.parent;){if(e.has(o.parent)){o.parent=void 0;break}e.add(o.parent),o=t.get(o.parent)}}}const gt=k(t=>{const r=new Map;for(const o of h){if(!o.sig||b(o)!==t||o.kind==="server-request"||o.kind==="gateway-request"||o.group==="browser")continue;const n=`${o.parent??"root"}|${o.kind}|${o.sig}`,a=r.get(n);a?a.push(o):r.set(n,[o])}const e=new Map;for(const o of r.values()){if(o.length<3)continue;o.sort((c,v)=>c.start-v.start);const n=o[0];let a=!1;for(let c=0;c+1<o.length;c++)if(o[c+1].start<o[c].start+(o[c].durationMs??0)){a=!0;break}const $=n.start,q=Math.max(...o.map(c=>c.start+(c.durationMs??0))),u=o.reduce((c,v)=>c+(v.durationMs??0),0);n.count=o.length,n.parallel=a,n.avgMs=Math.round(u/o.length*10)/10,n.wallMs=q-$,n.durationMs=q-$,n.title=`\xD7${o.length} ${n.title.replace(/\s*\((?:\d+ rows?, )?\d+ms\)$/,"")}`,n.detail=`${n.sig} \xD7${o.length} ${a?"\u2016 parallel":"\u21BB sequential loop"} \xB7 avg ${n.avgMs}ms \xB7 wall ${n.wallMs}ms`,n.items=o.slice(0,12).map(c=>({start:c.start-$,...c.durationMs!=null?{durationMs:c.durationMs}:{}})),n.memberIds=o.flatMap(c=>c.memberIds??[c.id]),o.some(c=>c.severity==="error")&&(n.severity="error");for(const c of o.slice(1))e.set(c.id,n.id)}if(e.size!==0){h=h.filter(o=>!e.has(o.id));for(const o of h)for(;o.parent&&e.has(o.parent);)o.parent=e.get(o.parent)}},"aggregatePass");gt(!0),gt(!1);for(const t of h){if(!b(t))continue;const r=t.durationMs??0;if(r<40)continue;const e=h.filter(q=>q.parent===t.id&&(q.durationMs??0)>0).map(q=>[q.start,q.start+(q.durationMs??0)]).sort((q,u)=>q[0]-u[0]);let o=0,n=-1,a=-1;for(const[q,u]of e)q>a?(a>n&&(o+=a-n),n=q,a=u):u>a&&(a=u);a>n&&(o+=a-n);const $=Math.max(0,r-o);($>=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:h,...s?{sql:s}:{}}}R(buildFlowDetail,"buildFlowDetail"),k(buildFlowDetail,"buildFlowDetail");
@@ -1 +1 @@
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");
1
+ "use strict";var b=Object.defineProperty;var c=(s,e)=>b(s,"name",{value:e,configurable:!0});var y=Object.defineProperty,l=c((s,e)=>y(s,"name",{value:e,configurable:!0}),"u");import{classifyFlow as $,categoryOfSegment as h}from"./flow-categories.js";import{DEFAULT_SEGMENT_OPTIONS as w,segmentFlow as j}from"./flow-segments.js";export const DEFAULT_FLOWS_CONFIG={categories:[],segments:{},problems:[]};const p=200,f=200,m=64,F=/^[A-Za-z0-9][A-Za-z0-9 ._:/-]*$/,O=["category","flowId","originType","origin","route","project"],A={phaseGapMs:[50,6e5],burstGapMs:[10,6e4],attachWindowMs:[0,6e4],maxSegmentEvents:[20,1e4],occurrenceSlackMs:[0,1e3]},g=l(s=>typeof s=="object"&&s!==null&&!Array.isArray(s),"isObj");function d(s,e){if(!g(s))return{problems:[`${e}: not an object`]};const o=[];for(const t of Object.keys(s))O.includes(t)||o.push(`${e}: unknown field "${t}" ignored`);const n=s.category;if(typeof n!="string"||n.trim()==="")return{problems:[...o,`${e}: "category" must be a non-empty string \u2014 rule dropped`]};const i=n.trim();if(i.length>m||!F.test(i))return{problems:[...o,`${e}: category "${i.slice(0,40)}" is not a usable name (letters, digits, space . _ : / -; up to ${m}) \u2014 rule dropped`]};const u={category:i};let a=0;for(const t of["flowId","originType","origin","route","project"]){const r=s[t];if(r!==void 0){if(typeof r!="string"||r===""||r.length>f)return{problems:[...o,`${e}: "${t}" must be a non-empty string of up to ${f} characters \u2014 rule dropped`]};u[t]=r,a+=1}}return a===0?{problems:[...o,`${e}: "${i}" has no match field (flowId, originType, origin, route or project) \u2014 rule dropped`]}:{rule:u,problems:o}}c(d,"w"),l(d,"parseRule");export function parseFlowsConfig(s){if(s==null)return DEFAULT_FLOWS_CONFIG;if(!g(s))return{...DEFAULT_FLOWS_CONFIG,problems:["lensmcp.flows must be an object \u2014 ignored"]};const e=[],o=[],n=s.categories;n!==void 0&&(Array.isArray(n)?(n.length>p&&e.push(`flows.categories has ${n.length} rules; only the first ${p} are used`),n.slice(0,p).forEach((a,t)=>{const r=d(a,`flows.categories[${t}]`);e.push(...r.problems),r.rule&&o.push(r.rule)})):e.push("flows.categories must be an array \u2014 ignored"));const i={},u=s.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=A[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 (${w[a]})`);continue}i[a]=t}return{categories:o,segments:i,problems:e}}c(parseFlowsConfig,"parseFlowsConfig"),l(parseFlowsConfig,"parseFlowsConfig");export function analyzeFlow(s,e=DEFAULT_FLOWS_CONFIG){const o=j(s,e.segments),n=$(s,o,e.categories),i={};for(const u of o.segments)i[u.id]=h(u,n,e.categories);return{segmentation:o,classification:n,segmentCategories:i}}c(analyzeFlow,"analyzeFlow"),l(analyzeFlow,"analyzeFlow");