@lensmcp/core 1.25.79 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/index.d.ts +1 -0
  2. package/index.js +1 -1
  3. package/lib/ai-content.js +1 -1
  4. package/lib/answer-budget.js +2 -2
  5. package/lib/bus-rotation.js +1 -1
  6. package/lib/capture-off.js +1 -1
  7. package/lib/event-bus.js +1 -1
  8. package/lib/event-loop-history.js +1 -1
  9. package/lib/event-loop.d.ts +9 -1
  10. package/lib/event-loop.js +1 -1
  11. package/lib/event-redactor.js +1 -1
  12. package/lib/fingerprint.js +1 -1
  13. package/lib/flow-categories.js +1 -1
  14. package/lib/flow-segments.js +1 -1
  15. package/lib/flow-shape.d.ts +15 -8
  16. package/lib/flow-shape.js +1 -1
  17. package/lib/flows-config.js +1 -1
  18. package/lib/graph-from-events.js +1 -1
  19. package/lib/graph-store.js +1 -1
  20. package/lib/headless-flow.js +1 -1
  21. package/lib/http-exchange.js +1 -1
  22. package/lib/http-shape.js +1 -1
  23. package/lib/key-pattern.js +1 -1
  24. package/lib/lens-config.d.ts +14 -0
  25. package/lib/lens-config.js +1 -0
  26. package/lib/lens-dir.d.ts +9 -0
  27. package/lib/lens-dir.js +7 -7
  28. package/lib/lens-events.js +2 -2
  29. package/lib/lens-store.d.ts +37 -0
  30. package/lib/lens-store.js +1 -0
  31. package/lib/patterns.d.ts +28 -12
  32. package/lib/patterns.js +1 -1
  33. package/lib/performance-window.d.ts +20 -3
  34. package/lib/performance-window.js +2 -2
  35. package/lib/pg-errors.js +1 -1
  36. package/lib/queue-signals.d.ts +7 -0
  37. package/lib/queue-signals.js +1 -0
  38. package/lib/redact.js +1 -1
  39. package/lib/redis-expiry.js +1 -1
  40. package/lib/reducer-registry.js +1 -1
  41. package/lib/replay-store.js +1 -1
  42. package/lib/resource-store.js +1 -1
  43. package/lib/route-template.js +1 -1
  44. package/lib/service-hop.js +1 -1
  45. package/lib/settings.js +2 -2
  46. package/lib/sql-shape.js +3 -3
  47. package/lib/sql-values.js +1 -1
  48. package/lib/stores.js +2 -2
  49. package/lib/story.js +1 -1
  50. package/lib/thresholds.js +1 -1
  51. package/lib/ulid.js +1 -1
  52. package/package.json +17 -2
package/lib/flow-shape.js CHANGED
@@ -1 +1 @@
1
- "use strict";var St=Object.defineProperty;var P=(i,g)=>St(i,"name",{value:g,configurable:!0});var Bt=Object.defineProperty,v=P((i,g)=>Bt(i,"name",{value:g,configurable:!0}),"y");import{redactDeep as At,redactText as at,redactUrlParams as Rt}from"./redact.js";import{templatisePath as $t}from"./route-template.js";import{SQL_ACCOUNT_KIND as Tt,sqlAccountingOf as Pt,stallsAfterResponse as Dt}from"./flow-segments.js";import{isServiceHopHost as yt}from"./service-hop.js";import{boundedClone as Ct}from"@lensmcp/protocol-types";export function areaOf(i){const{source:g,category:s,title:I,kind:l}=i;return g==="ai"?"ai":g==="perf"&&l==="event-loop-stall"?"services":l?.startsWith("memory")||l==="db-query"?"data":g==="gateway"||l==="gateway-request"?"gateway":l==="queue-process"||l==="queue-active"||l==="queue-completed"||l==="queue-failed"?"services":g==="db"||g==="redis"||g==="queue"||l==="redis-op"||l?.startsWith("queue-")||g==="fs"||l==="fs-ops"?"data":g==="exec"||l==="exec"||l==="egress"&&yt(i.host)?"services":g==="external"||l==="egress"?"network":g==="nestjs"||g==="nest"?/(?:Repository|Repo|Dao|Store|EntityManager|DataSource|QueryRunner|OrmClient)\./.test(I)?"data":"services":g==="valtio"?"state":s==="network"?"network":"browser"}P(areaOf,"areaOf"),v(areaOf,"areaOf");const vt=240,Nt=new Set(["systemPrompt","prompt","prompts","messages","completion","completions","input","output","draft","text","content","result","arguments","params"]),Ft=new Set(["tenantId","caller","userId","accountId","email","subject"]),Ot=8;function kt(i){const g=rt(i,0);return Ct(At({redacted:!0,...g}),{rawByteLimit:16*1024}).value}P(kt,"Ee"),v(kt,"aiProjection");function rt(i,g){if(typeof i=="string")return wt(i);if(i===null||typeof i!="object")return i;if(g>=Ot)return;if(Array.isArray(i))return i.slice(0,32).map(I=>rt(I,g+1));const s={};for(const[I,l]of Object.entries(i))if(!Ft.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]=rt(l,g+1)}return s}P(rt,"ae"),v(rt,"projectAi");function wt(i){return i.length<=vt?at(i):`${at(i.slice(0,vt))}\u2026`}P(wt,"Ne"),v(wt,"clipText");export function httpFacts(i,g){const s=v(q=>typeof q=="string"&&q.length>0?q:void 0,"str"),I=typeof g.status=="number"?g.status:void 0,l=v(q=>Rt(q.split("?")[0]??q)||"/","pathOf"),N=v((q,b,k={})=>({...q?{method:q.toUpperCase()}:{},...b?{rawPath:b,route:$t(b)}:{},...I!==void 0?{status:I}:{},...k}),"facts");if(i==="gateway-request"){const q=s(g.url);return N(s(g.method),q?l(q):void 0,{...s(g.host)?{host:s(g.host)}:{},...s(g.caller)?{caller:s(g.caller)}:{}})}if(i==="egress"){const q=s(g.path),b=s(g.exchangeId);return N(s(g.method)??"GET",q?l(q):void 0,{...s(g.host)?{host:s(g.host)}:{},...b?{exchangeId:b}:{}})}if(i==="fetch-start"||i==="fetch-done"||i==="fetch-error"){const q=s(g.href)??s(g.url);let b,k;if(q)try{const p=new URL(q,"http://relative.invalid");b=l(p.pathname),p.hostname!=="relative.invalid"&&(k=p.hostname)}catch{}return N(s(g.method)??"GET",b,k?{host:k}:{})}if(i==="ai-call")return{...I!==void 0?{status:I}:{},...g.stream===!0?{streamed:!0}:{}};const f=g.request;if(f&&typeof f=="object"){const q=f,b=s(q.route),k=s(q.method);if(!b&&!k)return{};const p=typeof q.status=="number"?q.status:void 0,F=b?l(b):void 0;return{...k?{method:k.toUpperCase()}:{},...F?{rawPath:F,route:F.includes(":")?F:$t(F)}:{},...p!==void 0?{status:p}:{}}}return{}}P(httpFacts,"httpFacts"),v(httpFacts,"httpFacts");export function trimFlowEvent(i,g={}){const s=i.raw??{},I=s.render??{},l=s.span??{},N=s.request??{},f=v(d=>typeof d=="number"?d:void 0,"num"),q=s.loop??{},b=s.effect??{},k=f(s.durationMs)??f(l.durationMs)??f(N.durationMs)??f(q.durationMs)??f(I.actualDurationMs)??f(b.durationMs),p=typeof s.kind=="string"?s.kind:void 0,F=p==="fetch-done"||p==="fetch-error",E=f(I.commitTime),X=p==="render"&&E!==void 0&&Math.abs(E-i.timestamp)<6e4,_=F?i.timestamp:X?E:f(s.startedAt)??f(l.startTime)??f(N.startedAt)??f(q.startedAt)??(k!==void 0?i.timestamp-k:i.timestamp);let x;if(typeof s.query=="string"){const d=Array.isArray(s.params)?` [${s.params.join(", ")}]`:"",m=typeof s.result=="string"?` \u2192 ${s.result}`:"";x=s.query+d+m}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 m="";try{m=JSON.stringify(d.preview)}catch{}x=`${d.storeId??""}.${d.path??""} = ${m}`}else if(p==="fs-ops"&&Array.isArray(s.paths))x=s.paths.slice(0,8).map(d=>{const m=d??{},B=typeof m.n=="number"&&m.n>1?` \xD7${m.n}`:"",T=typeof m.bytes=="number"&&m.bytes>0?` (${m.bytes>=1024?`${(m.bytes/1024).toFixed(1)} KB`:`${m.bytes} B`})`:"";return`${String(m.op??"?")} ${String(m.path??"?")}${B}${T}`}).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??{},m=typeof d.stack=="string"?d.stack:typeof s.text=="string"?s.text:void 0;m&&m!==i.title&&(x=m)}let L,z,U,V;if(p==="span"){const d=l.outcome;if(L=d==="threw"||d==="returned"?d:l.status==="error"?"threw":l.status==="ok"?"returned":void 0,L==="threw"){const T=l.error??{},y=typeof T.name=="string"?T.name:void 0,G=typeof T.message=="string"?T.message:typeof i.message=="string"?i.message:void 0;U=y,z=at([y,G].filter(Boolean).join(": "))||void 0}const m=typeof l.args=="string"?l.args:void 0,B=typeof l.result=="string"?l.result:void 0;if(m!==void 0||B!==void 0){V=[...m!==void 0?["args"]:[],...B!==void 0?["result"]:[]];const T=v(y=>y.length>Mt?`${y.slice(0,Mt)}\u2026`:y,"short");x=[m!==void 0?`args ${T(m)}`:"",B!==void 0?`returned ${T(B)}`:""].filter(Boolean).join(" \u2192 ")}}let W;if(p==="gateway-request")W=`${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??""));W=`${d.hostname}${d.pathname}`}catch{}let K;if(p==="gateway-request"&&Array.isArray(s.steps))K=s.steps.map(d=>{const m=[String(d.step)];return d.project&&m.push(String(d.project)),d.prefix&&m.push(String(d.prefix)),d.mode&&m.push(String(d.mode)+(d.ok===!1?" \u2717":d.ok===!0?" \u2713":"")),d.caller&&m.push("by "+String(d.caller)),d.pod&&m.push(String(d.pod)),typeof d.atMs=="number"&&m.push(`@${d.atMs}ms`),m.join(" ")}),x=K.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??{},m=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":"",T=f(s.toolCallCount)?` \xB7 ${f(s.toolCallCount)} tool call${f(s.toolCallCount)===1?"":"s"}`:"",y=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${s.provider??""}/${s.model??"?"}${m}${B}${T}${y}${s.stream===!0?" \xB7 stream":""}`}else if(p==="ai-round"){const d=s.model??{},m=s.usage??{},B=Array.isArray(s.toolCalls)?s.toolCalls:[],T=`${f(m.promptTokens)??"?"}\u2192${f(m.completionTokens)??"?"} tok`,y=B.length?` \xB7 ${B.length} tool call${B.length===1?"":"s"}`:"",G=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${d.provider??""}/${d.model??""} \xB7 ${T}${y}${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??{},m=s.result??{},B=f(s.durationMs)!==void 0?` \xB7 ${(f(s.durationMs)/1e3).toFixed(1)}s`:"";x=`${d.name??"tool"} ${m.error!=null?"\u2717 "+String(m.error):"\u2713"}${B}`}else if(p==="ai-turn-end"){const d=s.usage??{},m=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${m}${B}`}}let R;p==="db-query"&&typeof s.query=="string"?R=s.query:p==="redis-op"?R=`${s.op??""} ${String(s.key??"").replace(/\d+/g,"#")}`:p==="egress"?R=`${s.method??"GET"} ${s.host??""}`:p==="ai-call"?R=`ai ${s.provider??""} ${s.model??""} ${s.api??""}`:p==="queue-enqueued"?R=`enqueue ${s.queue??""}`:p==="span"&&typeof l.name=="string"?R=l.name:p==="memory-mutation"&&(R=i.title);const O=i.context??{},Q=I.commitId??b.commitId??s.commitId,Y=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:_,...R?{sig:R}:{},...W?{urlKey:W}:{},...httpFacts(p,s),...(p==="db-query"||p==="redis-op")&&typeof s.valuesId=="string"?{valuesId:s.valuesId}:{},...typeof s.queue=="string"?{queue:s.queue}:{},...s.jobId!=null?{jobId:String(s.jobId)}:{},source:i.source,category:i.category,severity:i.severity,title:L==="threw"&&typeof l.name=="string"?`${l.name} \u2014 threw${U?` ${U}`:""}${k!==void 0?` after ${k}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}:{},...L?{outcome:L}:{},...z?{error:z}:{},...V?{captured:V}:{},...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 O.requestId=="string"?{requestId:O.requestId}:{},...typeof O.parentRequestId=="string"?{parentRequestId:O.parentRequestId}:{},...typeof Q=="string"?{commitId:Q}:{},...typeof I.componentName=="string"?{component:I.componentName}:{},...typeof I.phase=="string"?{phase:I.phase}:{},...Y.length?{why:Y}:{},...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 O.projectName=="string"?{project:O.projectName}:typeof s.project=="string"?{project:s.project}:{},...k!==void 0?{durationMs:k}:{},...F&&f(s.startedAt)!==void 0?{fetchStartedAt:f(s.startedAt)}:{},...i.source==="ai"?{ai:g.includeRaw?s:kt(s)}:{},...x?{detail:x}:{},...K?{steps:K}:{}}}P(trimFlowEvent,"trimFlowEvent"),v(trimFlowEvent,"trimFlowEvent");const Mt=300;export const OUTLIVED_PARENT_MIN_MS=250;const Et=new Set(["egress","db-query","redis-op","ai-call","span","gateway-request","server-request"]),it=1;function qt(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}P(qt,"_e"),v(qt,"kindRank");function J(i){return i.kind==="span"&&i.role==="controller"?3.5:i.kind==="queue-process"?3:qt(i.kind)}P(J,"X"),v(J,"causalRank");export function buildFlowDetail(i,g={}){const s=Pt(i),I=Dt(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===Tt)return!1;const o=r.span;return!(typeof o?.name=="string"&&o.name.startsWith("nest.request "))}).map(t=>trimFlowEvent(t,g)),N=new Set;for(let t=l.length-1;t>=0;t--)N.has(l[t].id)?l.splice(t,1):N.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 q=v(t=>t.source!=="react"&&t.source!=="valtio"&&t.requestId&&f.has(t.requestId)?f.get(t.requestId):t.start,"anchorOf");l.sort((t,r)=>q(t)-q(r)||t.start-r.start||J(t)-J(r)||(r.durationMs??0)-(t.durationMs??0)||t.t-r.t);const b=v(t=>(t.kind==="span"||t.kind==="server-request"||t.kind==="gateway-request"||t.kind==="queue-process")&&(t.durationMs??0)>0,"spanLike"),k=l;for(const t of k)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 k)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 F=v((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 k)if(!t.project&&t.source==="nestjs"&&t.requestId){const r=F(t.requestId,t.start);r&&(t.project=r)}const E=new Map;for(const t of k)t.spanId&&E.set(t.spanId,t);const X=v((t,r)=>{let e=t.parentSpanId?E.get(t.parentSpanId):void 0;for(let o=0;e&&o<64;o++){if(e===r)return!0;e=e.parentSpanId?E.get(e.parentSpanId):void 0}return!1},"inside"),_=new Map(k.map((t,r)=>[t,r])),x=new Map,L=v(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 k)b(t)&&Number.isFinite(t.start)&&L(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||_.get(e)-_.get(o));const z=v(t=>Number.isFinite(t.start)?t.start:1/0,"startOf");for(const t of k.slice().sort((r,e)=>z(r)-z(e))){const r=t.parentSpanId?E.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=L(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,h)=>_.get(a)-_.get(h)):e.alive;let n;for(const a of o){if(a===t)continue;const h=a.project,w=t.project;if(a.kind!=="gateway-request"&&t.kind!=="gateway-request"&&h!==void 0&&w!==void 0&&h!==w)continue;const u=a.durationMs??0,c=t.durationMs??0,$=Math.abs(a.start-t.start)<=it,M=J(a),A=J(t),j=a.start<=t.start;if(!(a.start+u>t.start&&(j||$&&M<A)&&(!$||(M!==A?M<A:j&&u>c))))continue;const C=n?J(n):-1,D=n?Math.abs(a.start-n.start)<=it:!1,H=n&&D&&M===C?X(a,n)?1:X(n,a)?-1:0:0;(!n||!D&&a.start>n.start||D&&M>C||H>0||H===0&&D&&M===C&&(a.durationMs??0)<(n.durationMs??0))&&(n=a)}n&&(t.parent=n.id)}for(const t of k)delete t.spanId,delete t.parentSpanId;{const t=new Set(k.map(a=>a.id)),r=new Set,e=new Map,o=[],n=v(a=>{const h=[a];for(;h.length;){const w=h.pop();o.push(w),r.add(w.id);const u=e.get(w.id);if(u){e.delete(w.id);for(let c=u.length-1;c>=0;c--)h.push(u[c])}}},"place");for(const a of k)if(a.parent&&a.parent!==a.id&&t.has(a.parent)&&!r.has(a.parent)){const h=e.get(a.parent)??[];h.push(a),e.set(a.parent,h)}else n(a);for(const a of k)r.has(a.id)||(o.push(a),r.add(a.id));for(let a=0;a<o.length;a++)k[a]=o[a]}const U=new Map;for(const t of k){if(!t.requestId)continue;const r=U.get(t.requestId);r?r.push(t):U.set(t.requestId,[t])}const V=new Map(k.map(t=>[t.id,t])),W=new Map;for(const t of k)t.calleeRequestId&&!W.has(t.calleeRequestId)&&W.set(t.calleeRequestId,t);const K=v((t,r)=>{const e=(U.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 k){if(!t.parentRequestId||t.kind!=="server-request"&&t.kind!=="gateway-request")continue;const r=t.parent?V.get(t.parent):void 0;if(r&&r.requestId===t.requestId)continue;const e=t.requestId?W.get(t.requestId):void 0,o=e&&e.start<=t.start?e:K(t.parentRequestId,t.start);o&&o!==t&&o.start<=t.start&&(t.parent=o.id)}const R=k,O=new Map;for(const t of R)t.kind==="gateway-request"&&t.requestId&&!O.has(t.requestId)&&O.set(t.requestId,t);for(const t of R)if(t.group==="server"&&!t.parent&&t.requestId&&t.kind!=="gateway-request"){const r=O.get(t.requestId);r&&r!==t&&r.start<=t.start&&(t.parent=r.id)}const Q=new Set,Y=new Set,d=[];for(const t of R){if(t.kind!=="gateway-request")continue;if(!t.requestId){d.push(t);continue}const r=U.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){d.push(t);continue}e&&(t.fetchStartId=e.id,Q.add(e.id)),o&&(t.fetchDoneId=o.id,Y.add(o.id))}const m=new Map;for(const t of R){if(!t.urlKey)continue;const r=m.get(t.urlKey)??{gws:[],starts:[],dones:[]};t.kind==="gateway-request"?d.includes(t)&&r.gws.push(t):t.kind==="fetch-start"?Q.has(t.id)||r.starts.push(t):(t.kind==="fetch-done"||t.kind==="fetch-error")&&(Y.has(t.id)||r.dones.push(t)),m.set(t.urlKey,r)}for(const{gws:t,starts:r,dones:e}of m.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 h=r[a];h&&(n.fetchStartId=h.id);const w=h?h.t:n.start;let u,c=1/0;for(const $ of e){if(o.has($.id))continue;const M=$.fetchStartedAt??$.start-($.durationMs??0),A=Math.abs(M-w);A<c&&(c=A,u=$)}u&&(n.fetchDoneId=u.id,o.add(u.id))})}const B=new Map,T=new Map;for(const t of R)!t.queue||!t.jobId||(t.kind==="queue-enqueued"&&B.set(`${t.queue}#${t.jobId}`,t),t.kind==="queue-process"&&T.set(`${t.queue}#${t.jobId}`,t));for(const t of R){if(!t.queue||!t.jobId)continue;const r=`${t.queue}#${t.jobId}`;if(t.kind==="queue-process"&&!t.parent){const e=B.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=T.get(r);e&&e!==t&&e.start<=t.start&&(t.parent=e.id)}}{const t=new Map(k.map(r=>[r.id,r]));for(const r of k){if(!r.parent||!Et.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 k){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 k){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 y=k;{const t=new Map;for(const e of y)e.kind==="fetch-start"&&t.set(e.id,e);const r=new Map;for(const e of y){if(e.kind!=="fetch-done"&&e.kind!=="fetch-error")continue;const o=[...t.values()].find(h=>h.requestId&&h.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){y=y.filter(e=>!r.has(e.id));for(const e of y)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 G=v(t=>!!t.commitId&&(t.kind==="render"||t.kind==="effect-run"||t.kind==="render-commit-truncated"),"commitMember"),st=v(t=>[...new Set(t)],"uniq"),ot=v(t=>st(t.map(r=>r.component).filter(r=>!!r)),"named"),It=v(t=>t.length<=2?t.join(" + "):`${t[0]} + ${t.length-1} more`,"nameList"),dt=v(t=>{const r=new Map;for(const e of t)e.component&&r.set(e.component,(r.get(e.component)??0)+1);return[...r].map(([e,o])=>o>1?`${e} \xD7${o}`:e).join(", ")},"tally"),bt=v(t=>{if(!t)return"effect";const r=/([^/\\]+?):(\d+)(?::\d+)?$/.exec(t);return r?`${r[1]}:${r[2]}`:t},"shortHook"),nt=v(t=>`${bt(t.hook)}${t.cleanup?" (cleanup)":""}`,"hookLabel"),ut=v(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=v(t=>(delete t.component,delete t.why,delete t.phase,delete t.hook,delete t.cleanup,delete t.renderTotal,delete t.renderPublished,t),"asGroup");function 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,Z)=>(Z.durationMs??0)-(S.durationMs??0)),h=a.filter(S=>(S.why??[]).some(Z=>Z!=="parent-render")),w=st(h.flatMap(S=>(S.why??[]).filter(Z=>Z!=="parent-render"))),u=ot(h),c=e.filter(S=>S.phase==="mount"),$=e.filter(S=>S.phase!=="mount"&&!h.includes(S)),M=a[0]?.component??"view",A=e.length>0&&c.length===e.length,j=w.length?w.join(" + "):void 0,C=A?"mount":"update",D=u.length?`view update \xB7 ${It(u)} \u2190 ${j}`:A?`view mount \xB7 ${M}`:`view update \xB7 ${M}`,H=n?.renderTotal??e.length,jt=[c.length?`mounted ${dt(c)}`:"",$.length?`re-rendered ${dt($)}`:"",!u.length&&!A&&e.length?"trigger not recorded \u2014 every captured render came from its parent":"",n?.renderWalkStoppedAt!==void 0?`at least ${H} renders (the walk stopped at ${n.renderWalkStoppedAt} fibers), ${n.renderPublished??e.length} recorded`:n?`${H} 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:D,detail:jt,commitId:r.commitId,viewPhase:C,...j?{cause:j}:{},causeComponents:u,components:ht,mounted:ot(c),renderCount:H,...n?.renderWalkStoppedAt!==void 0?{renderCountAtLeast:!0}:{},recordedRenders:e.length,effects:o.length,effectHooks:o.map(nt),memberIds:t.map(S=>S.id),sig:`commit:${C}:${j??"-"}:${u.join(",")}:${ht.slice().sort().join(",")}`,severity:t.some(S=>S.severity==="error")?"error":r.severity})}P(lt,"Me"),v(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(",")}`})}P(pt,"ke"),v(pt,"effectsNode");const xt=v(t=>st(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,h=Math.min(...t.map($=>$.start)),w=Math.max(...t.map($=>$.start+($.durationMs??0))),u=Math.round(t.reduce(($,M)=>$+(M.durationMs??0),0)/n*10)/10,c=Math.round((w-h)*10)/10;e.count=n,e.avgMs=u,e.wallMs=c,e.durationMs=w-h,e.items=t.slice(0,12).map($=>({start:$.start-h,...$.durationMs!=null?{durationMs:$.durationMs}:{}})),e.memberIds=t.flatMap($=>$.memberIds??[$.id]),e.title=`\xD7${n} ${e.title}`,t.some($=>$.severity==="error")&&(e.severity="error"),e.kind==="view-update"?e.detail=[`${n} commits, ${r.length?`one per ${xt(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 ")}P(ft,"we"),v(ft,"collapseRepeat");const tt=[],et=new Map,mt=new Set;for(let t=0;t<y.length;t++){if(mt.has(t))continue;const r=y[t];if(!G(r)){tt.push(r);continue}const e=[t];for(let a=t+1;a<y.length;a++){const h=y[a];if(h.group==="browser"){if(!G(h)||h.commitId!==r.commitId)break;e.push(a)}}for(const a of e)mt.add(a);const o=e.map(a=>y[a]),n=o.some(a=>a.kind!=="effect-run")?lt(o):pt(o);for(const a of o)a.id!==n.id&&et.set(a.id,n.id);tt.push(n)}if(et.size>0||tt.some(t=>t.kind==="view-update"||t.kind==="commit-effects")){y=tt;for(const t of y)for(;t.parent&&et.has(t.parent);)t.parent=et.get(t.parent)}{const t=new Map;for(const r of y)r.kind==="view-update"&&r.commitId&&!t.has(r.commitId)&&t.set(r.commitId,r);for(const r of y){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=y.map((u,c)=>u.group==="browser"?c:-1).filter(u=>u>=0),e=v(u=>`${u.kind}|${u.sig??u.title}`,"keyOf"),o=r.map(u=>e(y[u])),n=v((u,c,$)=>{for(let M=0;M<$;M++)if(o[u+M]!==o[c+M])return!1;return!0},"sameBlock"),a=v(u=>o[u].split("|")[0],"kindAt"),h=v(u=>{let c=0,$=1;for(let M=1;M<=4&&u+M<=o.length;M++){let A=1;for(;u+(A+1)*M<=o.length&&n(u,u+A*M,M);)A+=1;A>=3&&M*A>c*$&&(c=M,$=A)}return{k:c,r:$}},"bestBlockAt"),w=new Map;for(let u=0;u<o.length;){const{k:c,r:$}=h(u);if(c===0){u+=1;continue}const M=[...Array(c).keys()].find(j=>t.has(a(u+j)));if(M!==void 0&&M>0){const j=h(u+M);if(j.k===c&&j.r>=3&&j.r>=$-1){u+=M;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 C=[];for(let D=0;D<$;D++)C.push(y[r[u+j+D*c]]);ft(C,A);for(const D of C.slice(1))w.set(D.id,C[0].id)}u+=c*$}if(w.size>0){y=y.filter(u=>!w.has(u.id));for(const u of y)for(;u.parent&&w.has(u.parent);)u.parent=w.get(u.parent)}}{const t=new Map(y.map(r=>[r.id,r]));for(const r of y){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=v(t=>{const r=new Map;for(const o of y){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,$)=>c.start-$.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 h=n.start,w=Math.max(...o.map(c=>c.start+(c.durationMs??0))),u=o.reduce((c,$)=>c+($.durationMs??0),0);n.count=o.length,n.parallel=a,n.avgMs=Math.round(u/o.length*10)/10,n.wallMs=w-h,n.durationMs=w-h,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-h,...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){y=y.filter(o=>!e.has(o.id));for(const o of y)for(;o.parent&&e.has(o.parent);)o.parent=e.get(o.parent)}},"aggregatePass");gt(!0),gt(!1);for(const t of y){if(!b(t))continue;const r=t.durationMs??0;if(r<40)continue;const e=y.filter(w=>w.parent===t.id&&(w.durationMs??0)>0).map(w=>[w.start,w.start+(w.durationMs??0)]).sort((w,u)=>w[0]-u[0]);let o=0,n=-1,a=-1;for(const[w,u]of e)w>a?(a>n&&(o+=a-n),n=w,a=u):u>a&&(a=u);a>n&&(o+=a-n);const h=Math.max(0,r-o);(h>=50||h/r>=.7&&r>=40)&&(t.selfMs=h,t.detail=`\u26A0 cpu-heavy: ${h}ms self-time of ${r}ms${t.detail?" \xB7 "+t.detail:""}`)}return{events:y,...s?{sql:s}:{}}}P(buildFlowDetail,"buildFlowDetail"),v(buildFlowDetail,"buildFlowDetail");
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 +1 @@
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");
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 +1 @@
1
- "use strict";var g=Object.defineProperty;var l=(t,r)=>g(t,"name",{value:r,configurable:!0});var I=Object.defineProperty,p=l((t,r)=>I(t,"name",{value:r,configurable:!0}),"l");function m(t){const r=t.raw??null,s=r?.kind,d=t.context,a={id:t.id,parentTraceNodeId:d.causedByNodeId??d.originNodeId,lifecycle:"completed",context:d,startTime:t.timestamp,attributes:{...r??{}}};if(t.source==="react"&&s==="render"){const e=r;return{parentAxis:"render",node:{...a,type:"render",logicalId:e.render?.componentLogicalId,instanceId:e.render?.componentInstanceId,name:`render ${e.render?.componentName??"?"}`,durationMs:e.render?.actualDurationMs}}}if(t.source==="valtio"&&s==="state-update"){const e=r;return{parentAxis:"state",node:{...a,type:"state-update",logicalId:e.update?.storeId,name:`${e.update?.storeId??"?"}.${e.update?.path??"?"}`}}}if(t.source==="nestjs"&&s==="server-request"){const e=r;return{parentAxis:"backend",node:{...a,type:"server-request",name:`${e.request?.method??"?"} ${e.request?.route??"?"}`,durationMs:e.request?.durationMs}}}if(s==="db-query"){const e=r,c=[e.op,e.table].filter(Boolean).join(" ")||(e.name??"query");return{parentAxis:"backend",node:{...a,type:"db-query",logicalId:e.table?`db:${e.op??"query"}:${e.table}`:void 0,name:e.error?`${c} (failed)`:c,durationMs:e.durationMs}}}if(s==="loop")return{parentAxis:"performance",node:{...a,type:"loop",name:"loop",durationMs:r.loop?.durationMs}};if(s==="flow-origin"&&(t.source==="react"||t.source==="client-runtime")){const e=d.originNodeId??(typeof r?.originNodeId=="string"?r.originNodeId:void 0);return{parentAxis:"caused",node:{...a,parentTraceNodeId:d.causedByNodeId,type:"ui-event",logicalId:e,name:e?`${t.title} ${e}`:t.title}}}if(t.source==="client-runtime"&&s==="user-action"){const e=r;return{parentAxis:"caused",node:{...a,type:"ui-event",logicalId:e.origin?.nodeId,name:e.origin?.label??t.title}}}}l(m,"m"),p(m,"eventToNode");export function buildGraphFromEvents(t,r){const s=[...r].sort((o,n)=>o.timestamp-n.timestamp),d=[];for(const o of s){const n=m(o);n&&(t.addNode(n.node),d.push(n))}let a=0;const e=p((o,n,i,u)=>{const f={id:`${i}:${o}->${n}`,from:o,to:n,axis:i,type:u,timestamp:t.getNode(n)?.startTime??0};t.addEdge(f),a++},"addEdge");for(const o of d){const n=o.node.context.causedByNodeId;n&&t.getNode(n)&&e(n,o.node.id,o.parentAxis??"caused","caused-by")}const c=new Map;for(const o of d){const n=o.node.context.flowId;if(!n)continue;let i=c.get(n);i||(i=[],c.set(n,i)),i.push(o)}for(const o of c.values())for(let n=1;n<o.length;n++){const i=o[n-1].node,u=o[n].node;u.context.causedByNodeId!==i.id&&e(i.id,u.id,"caused","flow-sequence")}return{nodeCount:d.length,edgeCount:a}}l(buildGraphFromEvents,"buildGraphFromEvents"),p(buildGraphFromEvents,"buildGraphFromEvents");
1
+ "use strict";var I=Object.defineProperty;var l=(o,n)=>I(o,"name",{value:n,configurable:!0});var y=Object.defineProperty,p=l((o,n)=>y(o,"name",{value:n,configurable:!0}),"l"),b=Object.defineProperty,m=p((o,n)=>b(o,"name",{value:n,configurable:!0}),"l");function f(o){const n=o.raw??null,s=n?.kind,d=o.context,a={id:o.id,parentTraceNodeId:d.causedByNodeId??d.originNodeId,lifecycle:"completed",context:d,startTime:o.timestamp,attributes:{...n??{}}};if(o.source==="react"&&s==="render"){const e=n;return{parentAxis:"render",node:{...a,type:"render",logicalId:e.render?.componentLogicalId,instanceId:e.render?.componentInstanceId,name:`render ${e.render?.componentName??"?"}`,durationMs:e.render?.actualDurationMs}}}if(o.source==="valtio"&&s==="state-update"){const e=n;return{parentAxis:"state",node:{...a,type:"state-update",logicalId:e.update?.storeId,name:`${e.update?.storeId??"?"}.${e.update?.path??"?"}`}}}if(o.source==="nestjs"&&s==="server-request"){const e=n;return{parentAxis:"backend",node:{...a,type:"server-request",name:`${e.request?.method??"?"} ${e.request?.route??"?"}`,durationMs:e.request?.durationMs}}}if(s==="db-query"){const e=n,c=[e.op,e.table].filter(Boolean).join(" ")||(e.name??"query");return{parentAxis:"backend",node:{...a,type:"db-query",logicalId:e.table?`db:${e.op??"query"}:${e.table}`:void 0,name:e.error?`${c} (failed)`:c,durationMs:e.durationMs}}}if(s==="loop")return{parentAxis:"performance",node:{...a,type:"loop",name:"loop",durationMs:n.loop?.durationMs}};if(s==="flow-origin"&&(o.source==="react"||o.source==="client-runtime")){const e=d.originNodeId??(typeof n?.originNodeId=="string"?n.originNodeId:void 0);return{parentAxis:"caused",node:{...a,parentTraceNodeId:d.causedByNodeId,type:"ui-event",logicalId:e,name:e?`${o.title} ${e}`:o.title}}}if(o.source==="client-runtime"&&s==="user-action"){const e=n;return{parentAxis:"caused",node:{...a,type:"ui-event",logicalId:e.origin?.nodeId,name:e.origin?.label??o.title}}}}l(f,"m"),p(f,"m"),m(f,"eventToNode");export function buildGraphFromEvents(o,n){const s=[...n].sort((r,t)=>r.timestamp-t.timestamp),d=[];for(const r of s){const t=f(r);t&&(o.addNode(t.node),d.push(t))}let a=0;const e=m((r,t,i,u)=>{const g={id:`${i}:${r}->${t}`,from:r,to:t,axis:i,type:u,timestamp:o.getNode(t)?.startTime??0};o.addEdge(g),a++},"addEdge");for(const r of d){const t=r.node.context.causedByNodeId;t&&o.getNode(t)&&e(t,r.node.id,r.parentAxis??"caused","caused-by")}const c=new Map;for(const r of d){const t=r.node.context.flowId;if(!t)continue;let i=c.get(t);i||(i=[],c.set(t,i)),i.push(r)}for(const r of c.values())for(let t=1;t<r.length;t++){const i=r[t-1].node,u=r[t].node;u.context.causedByNodeId!==i.id&&e(i.id,u.id,"caused","flow-sequence")}return{nodeCount:d.length,edgeCount:a}}l(buildGraphFromEvents,"buildGraphFromEvents"),p(buildGraphFromEvents,"buildGraphFromEvents"),m(buildGraphFromEvents,"buildGraphFromEvents");
@@ -1 +1 @@
1
- "use strict";var w=Object.defineProperty;var l=(h,e)=>w(h,"name",{value:e,configurable:!0});var p=Object.defineProperty,I=l((h,e)=>p(h,"name",{value:e,configurable:!0}),"l");const m=4,N=1e3;export class GraphStore{static{l(this,"GraphStore")}static{I(this,"GraphStore")}constructor(){this.nodes=new Map,this.edges=new Map,this.byParent=new Map,this.byFlow=new Map,this.byLogical=new Map,this.byInstance=new Map,this.byRequest=new Map,this.outByAxis=new Map,this.inByAxis=new Map}addNode(e){this.nodes.set(e.id,e),e.parentTraceNodeId&&this.addToIndex(this.byParent,e.parentTraceNodeId,e.id),e.context.flowId&&this.addToIndex(this.byFlow,e.context.flowId,e.id),e.logicalId&&this.addToIndex(this.byLogical,e.logicalId,e.id),e.instanceId&&this.addToIndex(this.byInstance,e.instanceId,e.id),e.context.requestId&&this.addToIndex(this.byRequest,e.context.requestId,e.id)}updateNode(e,s){const i=this.nodes.get(e);if(!i)throw new Error(`Unknown node: ${e}`);const t={...i,...s,id:i.id};return this.nodes.set(e,t),t}getNode(e){return this.nodes.get(e)}addEdge(e){this.edges.set(e.id,e);let s=this.outByAxis.get(e.axis);s||(s=new Map,this.outByAxis.set(e.axis,s)),this.addToIndex(s,e.from,e.id);let i=this.inByAxis.get(e.axis);i||(i=new Map,this.inByAxis.set(e.axis,i)),this.addToIndex(i,e.to,e.id)}getEdge(e){return this.edges.get(e)}childrenOf(e){return this.materialiseNodes(this.byParent.get(e))}nodesInFlow(e){return this.materialiseNodes(this.byFlow.get(e))}nodesByLogical(e){return this.materialiseNodes(this.byLogical.get(e))}nodesByInstance(e){return this.materialiseNodes(this.byInstance.get(e))}nodesByRequest(e){return this.materialiseNodes(this.byRequest.get(e))}traverse(e){const s=this.nodes.get(e.from);if(!s)return{nodes:[],edges:[]};const i=Array.isArray(e.lens)?e.lens:[e.lens],t=e.direction??"both",f=e.depth??4,x=e.maxNodes??1e3,n=new Set,g=new Set,c=[{id:s.id,d:0}];for(;c.length&&!(n.size>=x);){const{id:d,d:u}=c.shift();if(!n.has(d)&&(n.add(d),!(u>=f)))for(const y of i){if(t==="out"||t==="both"){const o=this.outByAxis.get(y)?.get(d);if(o)for(const a of o){g.add(a);const r=this.edges.get(a);n.has(r.to)||c.push({id:r.to,d:u+1})}}if(t==="in"||t==="both"){const o=this.inByAxis.get(y)?.get(d);if(o)for(const a of o){g.add(a);const r=this.edges.get(a);n.has(r.from)||c.push({id:r.from,d:u+1})}}}}return{nodes:this.materialiseNodes(n),edges:[...g].map(d=>this.edges.get(d)).filter(d=>!!d)}}nodeCount(){return this.nodes.size}edgeCount(){return this.edges.size}addToIndex(e,s,i){let t=e.get(s);t||(t=new Set,e.set(s,t)),t.add(i)}materialiseNodes(e){if(!e)return[];const s=[];for(const i of e){const t=this.nodes.get(i);t&&s.push(t)}return s}}
1
+ "use strict";var w=Object.defineProperty;var l=(d,t)=>w(d,"name",{value:t,configurable:!0});var I=Object.defineProperty,y=l((d,t)=>I(d,"name",{value:t,configurable:!0}),"l"),b=Object.defineProperty,m=y((d,t)=>b(d,"name",{value:t,configurable:!0}),"l");const B=4,M=1e3;export class GraphStore{static{l(this,"GraphStore")}static{y(this,"GraphStore")}static{m(this,"GraphStore")}constructor(){this.nodes=new Map,this.edges=new Map,this.byParent=new Map,this.byFlow=new Map,this.byLogical=new Map,this.byInstance=new Map,this.byRequest=new Map,this.outByAxis=new Map,this.inByAxis=new Map}addNode(t){this.nodes.set(t.id,t),t.parentTraceNodeId&&this.addToIndex(this.byParent,t.parentTraceNodeId,t.id),t.context.flowId&&this.addToIndex(this.byFlow,t.context.flowId,t.id),t.logicalId&&this.addToIndex(this.byLogical,t.logicalId,t.id),t.instanceId&&this.addToIndex(this.byInstance,t.instanceId,t.id),t.context.requestId&&this.addToIndex(this.byRequest,t.context.requestId,t.id)}updateNode(t,e){const i=this.nodes.get(t);if(!i)throw new Error(`Unknown node: ${t}`);const s={...i,...e,id:i.id};return this.nodes.set(t,s),s}getNode(t){return this.nodes.get(t)}addEdge(t){this.edges.set(t.id,t);let e=this.outByAxis.get(t.axis);e||(e=new Map,this.outByAxis.set(t.axis,e)),this.addToIndex(e,t.from,t.id);let i=this.inByAxis.get(t.axis);i||(i=new Map,this.inByAxis.set(t.axis,i)),this.addToIndex(i,t.to,t.id)}getEdge(t){return this.edges.get(t)}childrenOf(t){return this.materialiseNodes(this.byParent.get(t))}nodesInFlow(t){return this.materialiseNodes(this.byFlow.get(t))}nodesByLogical(t){return this.materialiseNodes(this.byLogical.get(t))}nodesByInstance(t){return this.materialiseNodes(this.byInstance.get(t))}nodesByRequest(t){return this.materialiseNodes(this.byRequest.get(t))}traverse(t){const e=this.nodes.get(t.from);if(!e)return{nodes:[],edges:[]};const i=Array.isArray(t.lens)?t.lens:[t.lens],s=t.direction??"both",x=t.depth??4,p=t.maxNodes??1e3,o=new Set,g=new Set,c=[{id:e.id,d:0}];for(;c.length&&!(o.size>=p);){const{id:n,d:u}=c.shift();if(!o.has(n)&&(o.add(n),!(u>=x)))for(const f of i){if(s==="out"||s==="both"){const a=this.outByAxis.get(f)?.get(n);if(a)for(const r of a){g.add(r);const h=this.edges.get(r);o.has(h.to)||c.push({id:h.to,d:u+1})}}if(s==="in"||s==="both"){const a=this.inByAxis.get(f)?.get(n);if(a)for(const r of a){g.add(r);const h=this.edges.get(r);o.has(h.from)||c.push({id:h.from,d:u+1})}}}}return{nodes:this.materialiseNodes(o),edges:[...g].map(n=>this.edges.get(n)).filter(n=>!!n)}}nodeCount(){return this.nodes.size}edgeCount(){return this.edges.size}addToIndex(t,e,i){let s=t.get(e);s||(s=new Set,t.set(e,s)),s.add(i)}materialiseNodes(t){if(!t)return[];const e=[];for(const i of t){const s=this.nodes.get(i);s&&e.push(s)}return e}}
@@ -1 +1 @@
1
- "use strict";var r=Object.defineProperty;var s=(e,t)=>r(e,"name",{value:t,configurable:!0});var a=Object.defineProperty,o=s((e,t)=>a(e,"name",{value:t,configurable:!0}),"t");export const HEADLESS_FLOWS_ENV="LENSMCP_HEADLESS_FLOWS";export function headlessFlowsEnabled(e=process.env){return!["0","false","off","no"].includes((e[HEADLESS_FLOWS_ENV]??"").trim().toLowerCase())}s(headlessFlowsEnabled,"headlessFlowsEnabled"),o(headlessFlowsEnabled,"headlessFlowsEnabled");export const HEADLESS_REQUEST_FLOW_PREFIX="api:",HEADLESS_JOB_FLOW_PREFIX="job:";export function headlessFlowId(e){return`${HEADLESS_REQUEST_FLOW_PREFIX}${e}`}s(headlessFlowId,"headlessFlowId"),o(headlessFlowId,"headlessFlowId");export function headlessJobFlowId(e,t){return`${HEADLESS_JOB_FLOW_PREFIX}${e}#${t??"?"}`}s(headlessJobFlowId,"headlessJobFlowId"),o(headlessJobFlowId,"headlessJobFlowId");export function isHeadlessFlowId(e){return e.startsWith(HEADLESS_REQUEST_FLOW_PREFIX)||e.startsWith(HEADLESS_JOB_FLOW_PREFIX)}s(isHeadlessFlowId,"isHeadlessFlowId"),o(isHeadlessFlowId,"isHeadlessFlowId");const n=/^\/(?:[^/?#]+\/)*(?:health|healthz|health-check|healthcheck|ready|readyz|readiness|live|livez|liveness|ping|metrics|favicon\.ico)\/?(?:[?#].*)?$/i;export function isProbePath(e){return e?n.test(e)||e.startsWith("/__lensmcp/"):!1}s(isProbePath,"isProbePath"),o(isProbePath,"isProbePath");
1
+ "use strict";var l=Object.defineProperty;var t=(e,s)=>l(e,"name",{value:s,configurable:!0});var r=Object.defineProperty,o=t((e,s)=>r(e,"name",{value:s,configurable:!0}),"s"),n=Object.defineProperty,a=o((e,s)=>n(e,"name",{value:s,configurable:!0}),"t");export const HEADLESS_FLOWS_ENV="LENSMCP_HEADLESS_FLOWS";export function headlessFlowsEnabled(e=process.env){return!["0","false","off","no"].includes((e[HEADLESS_FLOWS_ENV]??"").trim().toLowerCase())}t(headlessFlowsEnabled,"headlessFlowsEnabled"),o(headlessFlowsEnabled,"headlessFlowsEnabled"),a(headlessFlowsEnabled,"headlessFlowsEnabled");export const HEADLESS_REQUEST_FLOW_PREFIX="api:",HEADLESS_JOB_FLOW_PREFIX="job:";export function headlessFlowId(e){return`${HEADLESS_REQUEST_FLOW_PREFIX}${e}`}t(headlessFlowId,"headlessFlowId"),o(headlessFlowId,"headlessFlowId"),a(headlessFlowId,"headlessFlowId");export function headlessJobFlowId(e,s){return`${HEADLESS_JOB_FLOW_PREFIX}${e}#${s??"?"}`}t(headlessJobFlowId,"headlessJobFlowId"),o(headlessJobFlowId,"headlessJobFlowId"),a(headlessJobFlowId,"headlessJobFlowId");export function isHeadlessFlowId(e){return e.startsWith(HEADLESS_REQUEST_FLOW_PREFIX)||e.startsWith(HEADLESS_JOB_FLOW_PREFIX)}t(isHeadlessFlowId,"isHeadlessFlowId"),o(isHeadlessFlowId,"isHeadlessFlowId"),a(isHeadlessFlowId,"isHeadlessFlowId");const i=/^\/(?:[^/?#]+\/)*(?:health|healthz|health-check|healthcheck|ready|readyz|readiness|live|livez|liveness|ping|metrics|favicon\.ico)\/?(?:[?#].*)?$/i;export function isProbePath(e){return e?i.test(e)||e.startsWith("/__lensmcp/"):!1}t(isProbePath,"isProbePath"),o(isProbePath,"isProbePath"),a(isProbePath,"isProbePath");
@@ -1 +1 @@
1
- "use strict";var i=Object.defineProperty;var n=(t,e)=>i(t,"name",{value:e,configurable:!0});var s=Object.defineProperty,a=n((t,e)=>s(t,"name",{value:e,configurable:!0}),"n");import*as p from"node:fs";import{dirname as h,join as c}from"node:path";export{isServiceHopHost,LENS_REQUEST_ID_HEADER}from"./service-hop.js";export const HTTP_EXCHANGE_DIR="http",HTTP_EXCHANGE_PLACES=["calls","ai","in","hops"];export function exchangePlace(t){return t.side==="ingress"?"in":t.ai?"ai":/(^|\.)localhost$/i.test(t.host)?"hops":"calls"}n(exchangePlace,"exchangePlace"),a(exchangePlace,"exchangePlace");const l=/^hx_[0-9a-z]{8,40}$/;export const isHttpExchangeId=a(t=>typeof t=="string"&&l.test(t),"isHttpExchangeId");export function httpExchangeDir(t,e="calls"){const r=c(h(t),HTTP_EXCHANGE_DIR);return e==="calls"?r:c(r,e)}n(httpExchangeDir,"httpExchangeDir"),a(httpExchangeDir,"httpExchangeDir");export function httpExchangeFile(t,e,r="calls"){if(!isHttpExchangeId(e))throw new Error("invalid http exchange id");return c(httpExchangeDir(t,r),`${e}.json`)}n(httpExchangeFile,"httpExchangeFile"),a(httpExchangeFile,"httpExchangeFile");export function readHttpExchange(t,e){if(isHttpExchangeId(e))for(const r of HTTP_EXCHANGE_PLACES)try{const o=JSON.parse(p.readFileSync(httpExchangeFile(t,e,r),"utf8"));if(o&&o.schemaVersion===1&&o.id===e)return o}catch{}}n(readHttpExchange,"readHttpExchange"),a(readHttpExchange,"readHttpExchange");
1
+ "use strict";var s=Object.defineProperty;var r=(t,e)=>s(t,"name",{value:e,configurable:!0});var h=Object.defineProperty,a=r((t,e)=>h(t,"name",{value:e,configurable:!0}),"n"),p=Object.defineProperty,c=a((t,e)=>p(t,"name",{value:e,configurable:!0}),"n");import*as l from"node:fs";import{dirname as x,join as o}from"node:path";export{isServiceHopHost,LENS_REQUEST_ID_HEADER}from"./service-hop.js";export const HTTP_EXCHANGE_DIR="http",HTTP_EXCHANGE_PLACES=["calls","ai","in","hops"];export function exchangePlace(t){return t.side==="ingress"?"in":t.ai?"ai":/(^|\.)localhost$/i.test(t.host)?"hops":"calls"}r(exchangePlace,"exchangePlace"),a(exchangePlace,"exchangePlace"),c(exchangePlace,"exchangePlace");const E=/^hx_[0-9a-z]{8,40}$/;export const isHttpExchangeId=c(t=>typeof t=="string"&&E.test(t),"isHttpExchangeId");export function httpExchangeDir(t,e="calls"){const n=o(x(t),HTTP_EXCHANGE_DIR);return e==="calls"?n:o(n,e)}r(httpExchangeDir,"httpExchangeDir"),a(httpExchangeDir,"httpExchangeDir"),c(httpExchangeDir,"httpExchangeDir");export function httpExchangeFile(t,e,n="calls"){if(!isHttpExchangeId(e))throw new Error("invalid http exchange id");return o(httpExchangeDir(t,n),`${e}.json`)}r(httpExchangeFile,"httpExchangeFile"),a(httpExchangeFile,"httpExchangeFile"),c(httpExchangeFile,"httpExchangeFile");export function readHttpExchange(t,e){if(isHttpExchangeId(e))for(const n of HTTP_EXCHANGE_PLACES)try{const i=JSON.parse(l.readFileSync(httpExchangeFile(t,e,n),"utf8"));if(i&&i.schemaVersion===1&&i.id===e)return i}catch{}}r(readHttpExchange,"readHttpExchange"),a(readHttpExchange,"readHttpExchange"),c(readHttpExchange,"readHttpExchange");
package/lib/http-shape.js CHANGED
@@ -1 +1 @@
1
- "use strict";var v=Object.defineProperty;var m=(e,r)=>v(e,"name",{value:r,configurable:!0});var k=Object.defineProperty,l=m((e,r)=>k(e,"name",{value:r,configurable:!0}),"a");import{isSecretParam as j}from"./redact.js";const b=6,d=60,S=4,M=[["uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i],["ulid",/^[0-9A-HJKMNP-TV-Z]{26}$/],["date-time",/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/],["date",/^\d{4}-\d{2}-\d{2}$/],["email",/^[^\s@]+@[^\s@]+\.[^\s@]+$/],["url",/^https?:\/\/\S+$/i],["jwt",/^eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$/],["int",/^-?\d{1,30}$/],["decimal",/^-?\d+\.\d+$/],["phone",/^\+\d{7,15}$/],["hex",/^[0-9a-f]{16,}$/i],["base64",/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[A-Za-z0-9+/]{32,}={0,2}$/]];export function stringFormat(e){for(const[r,n]of M)if(n.test(e))return r}m(stringFormat,"stringFormat"),l(stringFormat,"stringFormat");const x=l(e=>e.length>64||/\s/.test(e)||stringFormat(e)!==void 0&&!/^[a-z]/i.test(e)||/@/.test(e)||/^[0-9a-f]{8}-/i.test(e),"dataKey");export function shapeOf(e,r=0,n=!1){if(e==null)return{t:"null"};if(typeof e=="boolean")return{t:"bool"};if(typeof e=="number")return Number.isInteger(e)?{t:"num",int:!0}:{t:"num"};if(typeof e=="bigint")return{t:"num",int:!0};if(typeof e=="string"){const t=stringFormat(e);return{t:"str",...t?{f:t}:{},...n?{}:{max:e.length}}}if(e instanceof Date)return{t:"str",f:"date-time"};if(r>=b)return Array.isArray(e)?{t:"arr",n:[e.length,e.length]}:{t:"obj",fields:[]};if(Array.isArray(e)){const t=e.slice(0,20).map(o=>shapeOf(o,r+1,n)).reduce((o,i)=>o?mergeShapes(o,i):i,void 0);return{t:"arr",n:[e.length,e.length],...t?{of:t}:{}}}if(typeof e=="object"){const t=Object.entries(e).filter(([,o])=>typeof o!="function");if(t.length&&t.some(([o])=>x(o))){const o=t.slice(0,20).map(([,s])=>shapeOf(s,r+1,n)).reduce((s,c)=>s?mergeShapes(s,c):c,void 0),i=t.map(([s])=>stringFormat(s)).find(Boolean);return{t:"map",n:[t.length,t.length],...i?{key:i}:{},...o?{of:o}:{}}}return{t:"obj",fields:t.slice(0,d).map(([o,i])=>{const s=j(o);return{...shapeOf(i,r+1,n||s),name:o,...s?{cred:!0}:{}}}),...t.length>d?{more:t.length-d}:{}}}return{t:"null"}}m(shapeOf,"shapeOf"),l(shapeOf,"shapeOf");const $=l((e,r)=>e.t===r.t,"same"),F=new Set(["null","bool","num","str","arr","obj","map","any"]);export function isShape(e,r=0){if(!e||typeof e!="object"||r>b*2)return!1;const n=e;return typeof n.t!="string"||!F.has(n.t)?!1:n.t==="obj"?Array.isArray(n.fields)&&n.fields.every(t=>typeof t?.name=="string"&&isShape(t,r+1)):n.t==="any"?Array.isArray(n.of)&&n.of.every(t=>isShape(t,r+1)):n.t==="arr"||n.t==="map"?Array.isArray(n.n)&&(n.of===void 0||isShape(n.of,r+1)):!0}m(isShape,"isShape"),l(isShape,"isShape");export function fieldShape(e){const r={...e};return delete r.name,delete r.opt,delete r.cred,r}m(fieldShape,"fieldShape"),l(fieldShape,"fieldShape");export function mergeShapes(e,r){if(e.t==="any"||r.t==="any"){const n=[...e.t==="any"?e.of:[e],...r.t==="any"?r.of:[r]],t=[];for(const o of n){const i=t.findIndex(s=>$(s,o));i>=0?t[i]=mergeShapes(t[i],o):t.push(o)}return t.length===1?t[0]:{t:"any",of:t.slice(0,S)}}if(!$(e,r))return{t:"any",of:[e,r]};switch(e.t){case"num":return e.int&&r.int?e:{t:"num"};case"str":{const n=r,t=e.f===n.f?e.f:void 0;return{t:"str",...t?{f:t}:{},...e.max!==void 0||n.max!==void 0?{max:Math.max(e.max??0,n.max??0)}:{}}}case"arr":{const n=r,t=e.of&&n.of?mergeShapes(e.of,n.of):e.of??n.of;return{t:"arr",n:[Math.min(e.n[0],n.n[0]),Math.max(e.n[1],n.n[1])],...t?{of:t}:{}}}case"map":{const n=r,t=e.of&&n.of?mergeShapes(e.of,n.of):e.of??n.of;return{t:"map",n:[Math.min(e.n[0],n.n[0]),Math.max(e.n[1],n.n[1])],...e.key===n.key&&e.key?{key:e.key}:{},...t?{of:t}:{}}}case"obj":{const n=r,t=new Map(e.fields.map(c=>[c.name,c])),o=new Map(n.fields.map(c=>[c.name,c])),i=[...new Set([...t.keys(),...o.keys()])].slice(0,d).map(c=>{const f=t.get(c),u=o.get(c);return{...f&&u?mergeShapes(fieldShape(f),fieldShape(u)):fieldShape(f??u),name:c,...!f||!u||f.opt||u.opt?{opt:!0}:{},...f?.cred||u?.cred?{cred:!0}:{}}}),s=Math.max(e.more??0,n.more??0);return{t:"obj",fields:i,...s?{more:s}:{}}}default:return e}}m(mergeShapes,"mergeShapes"),l(mergeShapes,"mergeShapes");export function shapeText(e,r=0){switch(e.t){case"null":return"null";case"bool":return"boolean";case"num":return e.int?"int":"number";case"str":return e.f?`string(${e.f})`:"string";case"arr":return`[${e.n[0]===e.n[1]?e.n[0]:`${e.n[0]}..${e.n[1]}`}]${e.of?` ${shapeText(e.of,r+1)}`:""}`;case"map":return`map<${e.key??"string"}, ${e.of?shapeText(e.of,r+1):"?"}> (${e.n[0]===e.n[1]?e.n[0]:`${e.n[0]}..${e.n[1]}`} entries)`;case"any":return e.of.map(n=>shapeText(n,r)).join(" | ");case"obj":return`{ ${e.fields.map(n=>`${n.name}${n.opt?"?":""}${n.cred?" (credential-named)":""}: ${shapeText(fieldShape(n),r+1)}`).join(", ")}${e.more?`, \u2026 ${e.more} more`:""} }`}}m(shapeText,"shapeText"),l(shapeText,"shapeText");const a=l((e,r)=>{const n=e[r]??e[r.toLowerCase()];return n===void 0?void 0:Array.isArray(n)?n.join(", "):String(n)},"h"),y=l(e=>e?.split(";")[0]?.trim().toLowerCase()||void 0,"media");export function requestFacts(e,r,n){const t=a(e,"authorization")?.split(/\s+/)[0],o=a(e,"cookie"),i=Number(a(e,"content-length")),s=r?Object.keys(r).filter(f=>!x(f)).slice(0,30):[],c=n?Object.keys(n).slice(0,10):[];return{...y(a(e,"content-type"))?{contentType:y(a(e,"content-type"))}:{},...a(e,"accept")?{accept:a(e,"accept").slice(0,80)}:{},...t?{scheme:/^[A-Za-z][\w-]{1,20}$/.test(t)?t:"other"}:{},...o?{cookies:o.split(";").filter(f=>f.includes("=")).length}:{},...a(e,"if-match")?{ifMatch:!0}:{},...a(e,"if-none-match")?{ifNoneMatch:!0}:{},...a(e,"idempotency-key")?{idempotencyKey:!0}:{},...a(e,"origin")?{origin:!0}:{},...Number.isFinite(i)&&i>0?{bytes:i}:{},...s.length?{query:s}:{},...c.length?{params:c}:{}}}m(requestFacts,"requestFacts"),l(requestFacts,"requestFacts");export function responseFacts(e,r){const n=a(e,"etag"),t=Number(a(e,"content-length")),o=e["set-cookie"],i=(Array.isArray(o)?o:o!==void 0?[String(o)]:[]).slice(0,10).map(c=>{const[f="",...u]=c.split(";").map(h=>h.trim()),p=l(h=>u.find(A=>A.toLowerCase().startsWith(h)),"a"),g=p("samesite")?.split("=")[1],w=p("path=")?.slice(5);return{name:f.split("=")[0].slice(0,40),...p("secure")?{secure:!0}:{},...p("httponly")?{httpOnly:!0}:{},...g?{sameSite:g}:{},...p("domain=")?{domain:!0}:{},...w?{path:w}:{},...p("max-age=")?{maxAge:!0}:{},...p("expires=")?{expires:!0}:{}}}),s=a(e,"access-control-allow-origin");return{...y(a(e,"content-type"))?{contentType:y(a(e,"content-type"))}:{},...Number.isFinite(t)&&t>=0&&a(e,"content-length")!==void 0?{bytes:t}:{},...a(e,"cache-control")?{cacheControl:a(e,"cache-control").slice(0,120)}:{},...n?{etag:n.startsWith("W/")?"weak":"strong"}:{},...a(e,"last-modified")?{lastModified:!0}:{},...a(e,"location")?{location:!0}:{},...a(e,"vary")?{vary:a(e,"vary").slice(0,120)}:{},...a(e,"retry-after")?{retryAfter:!0}:{},...a(e,"www-authenticate")?{wwwAuthenticate:a(e,"www-authenticate").split(/\s+/)[0].slice(0,20)}:{},...a(e,"allow")?{allow:a(e,"allow").slice(0,80)}:{},...i.length?{cookies:i}:{},...s?{cors:{origin:s==="*"?"*":r&&s===r?"echoed":"fixed",...a(e,"access-control-allow-credentials")==="true"?{creds:!0}:{},...a(e,"access-control-allow-methods")?{methods:a(e,"access-control-allow-methods").slice(0,80)}:{},...a(e,"access-control-allow-headers")?{headers:a(e,"access-control-allow-headers").slice(0,120)}:{}}}:{},...a(e,"strict-transport-security")?{hsts:!0}:{},...a(e,"x-content-type-options")?{nosniff:!0}:{},...a(e,"x-powered-by")||a(e,"server")?{poweredBy:!0}:{},...a(e,"deprecation")?{deprecation:!0}:{},...a(e,"sunset")?{sunset:!0}:{},...a(e,"ratelimit")||a(e,"ratelimit-policy")||a(e,"x-ratelimit-limit")?{rateLimit:!0}:{},...a(e,"x-request-id")?{requestId:!0}:{}}}m(responseFacts,"responseFacts"),l(responseFacts,"responseFacts");
1
+ "use strict";var j=Object.defineProperty;var m=(t,n)=>j(t,"name",{value:n,configurable:!0});var k=Object.defineProperty,p=m((t,n)=>k(t,"name",{value:n,configurable:!0}),"m"),S=Object.defineProperty,l=p((t,n)=>S(t,"name",{value:n,configurable:!0}),"a");import{isSecretParam as M}from"./redact.js";const x=6,h=60,F=4,O=[["uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i],["ulid",/^[0-9A-HJKMNP-TV-Z]{26}$/],["date-time",/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/],["date",/^\d{4}-\d{2}-\d{2}$/],["email",/^[^\s@]+@[^\s@]+\.[^\s@]+$/],["url",/^https?:\/\/\S+$/i],["jwt",/^eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$/],["int",/^-?\d{1,30}$/],["decimal",/^-?\d+\.\d+$/],["phone",/^\+\d{7,15}$/],["hex",/^[0-9a-f]{16,}$/i],["base64",/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[A-Za-z0-9+/]{32,}={0,2}$/]];export function stringFormat(t){for(const[n,e]of O)if(e.test(t))return n}m(stringFormat,"stringFormat"),p(stringFormat,"stringFormat"),l(stringFormat,"stringFormat");const $=l(t=>t.length>64||/\s/.test(t)||stringFormat(t)!==void 0&&!/^[a-z]/i.test(t)||/@/.test(t)||/^[0-9a-f]{8}-/i.test(t),"dataKey");export function shapeOf(t,n=0,e=!1){if(t==null)return{t:"null"};if(typeof t=="boolean")return{t:"bool"};if(typeof t=="number")return Number.isInteger(t)?{t:"num",int:!0}:{t:"num"};if(typeof t=="bigint")return{t:"num",int:!0};if(typeof t=="string"){const r=stringFormat(t);return{t:"str",...r?{f:r}:{},...e?{}:{max:t.length}}}if(t instanceof Date)return{t:"str",f:"date-time"};if(n>=x)return Array.isArray(t)?{t:"arr",n:[t.length,t.length]}:{t:"obj",fields:[]};if(Array.isArray(t)){const r=t.slice(0,20).map(a=>shapeOf(a,n+1,e)).reduce((a,i)=>a?mergeShapes(a,i):i,void 0);return{t:"arr",n:[t.length,t.length],...r?{of:r}:{}}}if(typeof t=="object"){const r=Object.entries(t).filter(([,a])=>typeof a!="function");if(r.length&&r.some(([a])=>$(a))){const a=r.slice(0,20).map(([,s])=>shapeOf(s,n+1,e)).reduce((s,c)=>s?mergeShapes(s,c):c,void 0),i=r.map(([s])=>stringFormat(s)).find(Boolean);return{t:"map",n:[r.length,r.length],...i?{key:i}:{},...a?{of:a}:{}}}return{t:"obj",fields:r.slice(0,h).map(([a,i])=>{const s=M(a);return{...shapeOf(i,n+1,e||s),name:a,...s?{cred:!0}:{}}}),...r.length>h?{more:r.length-h}:{}}}return{t:"null"}}m(shapeOf,"shapeOf"),p(shapeOf,"shapeOf"),l(shapeOf,"shapeOf");const v=l((t,n)=>t.t===n.t,"same"),N=new Set(["null","bool","num","str","arr","obj","map","any"]);export function isShape(t,n=0){if(!t||typeof t!="object"||n>x*2)return!1;const e=t;return typeof e.t!="string"||!N.has(e.t)?!1:e.t==="obj"?Array.isArray(e.fields)&&e.fields.every(r=>typeof r?.name=="string"&&isShape(r,n+1)):e.t==="any"?Array.isArray(e.of)&&e.of.every(r=>isShape(r,n+1)):e.t==="arr"||e.t==="map"?Array.isArray(e.n)&&(e.of===void 0||isShape(e.of,n+1)):!0}m(isShape,"isShape"),p(isShape,"isShape"),l(isShape,"isShape");export function fieldShape(t){const n={...t};return delete n.name,delete n.opt,delete n.cred,n}m(fieldShape,"fieldShape"),p(fieldShape,"fieldShape"),l(fieldShape,"fieldShape");export function mergeShapes(t,n){if(t.t==="any"||n.t==="any"){const e=[...t.t==="any"?t.of:[t],...n.t==="any"?n.of:[n]],r=[];for(const a of e){const i=r.findIndex(s=>v(s,a));i>=0?r[i]=mergeShapes(r[i],a):r.push(a)}return r.length===1?r[0]:{t:"any",of:r.slice(0,F)}}if(!v(t,n))return{t:"any",of:[t,n]};switch(t.t){case"num":return t.int&&n.int?t:{t:"num"};case"str":{const e=n,r=t.f===e.f?t.f:void 0;return{t:"str",...r?{f:r}:{},...t.max!==void 0||e.max!==void 0?{max:Math.max(t.max??0,e.max??0)}:{}}}case"arr":{const e=n,r=t.of&&e.of?mergeShapes(t.of,e.of):t.of??e.of;return{t:"arr",n:[Math.min(t.n[0],e.n[0]),Math.max(t.n[1],e.n[1])],...r?{of:r}:{}}}case"map":{const e=n,r=t.of&&e.of?mergeShapes(t.of,e.of):t.of??e.of;return{t:"map",n:[Math.min(t.n[0],e.n[0]),Math.max(t.n[1],e.n[1])],...t.key===e.key&&t.key?{key:t.key}:{},...r?{of:r}:{}}}case"obj":{const e=n,r=new Map(t.fields.map(c=>[c.name,c])),a=new Map(e.fields.map(c=>[c.name,c])),i=[...new Set([...r.keys(),...a.keys()])].slice(0,h).map(c=>{const f=r.get(c),u=a.get(c);return{...f&&u?mergeShapes(fieldShape(f),fieldShape(u)):fieldShape(f??u),name:c,...!f||!u||f.opt||u.opt?{opt:!0}:{},...f?.cred||u?.cred?{cred:!0}:{}}}),s=Math.max(t.more??0,e.more??0);return{t:"obj",fields:i,...s?{more:s}:{}}}default:return t}}m(mergeShapes,"mergeShapes"),p(mergeShapes,"mergeShapes"),l(mergeShapes,"mergeShapes");export function shapeText(t,n=0){switch(t.t){case"null":return"null";case"bool":return"boolean";case"num":return t.int?"int":"number";case"str":return t.f?`string(${t.f})`:"string";case"arr":return`[${t.n[0]===t.n[1]?t.n[0]:`${t.n[0]}..${t.n[1]}`}]${t.of?` ${shapeText(t.of,n+1)}`:""}`;case"map":return`map<${t.key??"string"}, ${t.of?shapeText(t.of,n+1):"?"}> (${t.n[0]===t.n[1]?t.n[0]:`${t.n[0]}..${t.n[1]}`} entries)`;case"any":return t.of.map(e=>shapeText(e,n)).join(" | ");case"obj":return`{ ${t.fields.map(e=>`${e.name}${e.opt?"?":""}${e.cred?" (credential-named)":""}: ${shapeText(fieldShape(e),n+1)}`).join(", ")}${t.more?`, \u2026 ${t.more} more`:""} }`}}m(shapeText,"shapeText"),p(shapeText,"shapeText"),l(shapeText,"shapeText");const o=l((t,n)=>{const e=t[n]??t[n.toLowerCase()];return e===void 0?void 0:Array.isArray(e)?e.join(", "):String(e)},"h"),y=l(t=>t?.split(";")[0]?.trim().toLowerCase()||void 0,"media");export function requestFacts(t,n,e){const r=o(t,"authorization")?.split(/\s+/)[0],a=o(t,"cookie"),i=Number(o(t,"content-length")),s=n?Object.keys(n).filter(f=>!$(f)).slice(0,30):[],c=e?Object.keys(e).slice(0,10):[];return{...y(o(t,"content-type"))?{contentType:y(o(t,"content-type"))}:{},...o(t,"accept")?{accept:o(t,"accept").slice(0,80)}:{},...r?{scheme:/^[A-Za-z][\w-]{1,20}$/.test(r)?r:"other"}:{},...a?{cookies:a.split(";").filter(f=>f.includes("=")).length}:{},...o(t,"if-match")?{ifMatch:!0}:{},...o(t,"if-none-match")?{ifNoneMatch:!0}:{},...o(t,"idempotency-key")?{idempotencyKey:!0}:{},...o(t,"origin")?{origin:!0}:{},...Number.isFinite(i)&&i>0?{bytes:i}:{},...s.length?{query:s}:{},...c.length?{params:c}:{}}}m(requestFacts,"requestFacts"),p(requestFacts,"requestFacts"),l(requestFacts,"requestFacts");export function responseFacts(t,n){const e=o(t,"etag"),r=Number(o(t,"content-length")),a=t["set-cookie"],i=(Array.isArray(a)?a:a!==void 0?[String(a)]:[]).slice(0,10).map(c=>{const[f="",...u]=c.split(";").map(g=>g.trim()),d=l(g=>u.find(A=>A.toLowerCase().startsWith(g)),"a"),w=d("samesite")?.split("=")[1],b=d("path=")?.slice(5);return{name:f.split("=")[0].slice(0,40),...d("secure")?{secure:!0}:{},...d("httponly")?{httpOnly:!0}:{},...w?{sameSite:w}:{},...d("domain=")?{domain:!0}:{},...b?{path:b}:{},...d("max-age=")?{maxAge:!0}:{},...d("expires=")?{expires:!0}:{}}}),s=o(t,"access-control-allow-origin");return{...y(o(t,"content-type"))?{contentType:y(o(t,"content-type"))}:{},...Number.isFinite(r)&&r>=0&&o(t,"content-length")!==void 0?{bytes:r}:{},...o(t,"cache-control")?{cacheControl:o(t,"cache-control").slice(0,120)}:{},...e?{etag:e.startsWith("W/")?"weak":"strong"}:{},...o(t,"last-modified")?{lastModified:!0}:{},...o(t,"location")?{location:!0}:{},...o(t,"vary")?{vary:o(t,"vary").slice(0,120)}:{},...o(t,"retry-after")?{retryAfter:!0}:{},...o(t,"www-authenticate")?{wwwAuthenticate:o(t,"www-authenticate").split(/\s+/)[0].slice(0,20)}:{},...o(t,"allow")?{allow:o(t,"allow").slice(0,80)}:{},...i.length?{cookies:i}:{},...s?{cors:{origin:s==="*"?"*":n&&s===n?"echoed":"fixed",...o(t,"access-control-allow-credentials")==="true"?{creds:!0}:{},...o(t,"access-control-allow-methods")?{methods:o(t,"access-control-allow-methods").slice(0,80)}:{},...o(t,"access-control-allow-headers")?{headers:o(t,"access-control-allow-headers").slice(0,120)}:{}}}:{},...o(t,"strict-transport-security")?{hsts:!0}:{},...o(t,"x-content-type-options")?{nosniff:!0}:{},...o(t,"x-powered-by")||o(t,"server")?{poweredBy:!0}:{},...o(t,"deprecation")?{deprecation:!0}:{},...o(t,"sunset")?{sunset:!0}:{},...o(t,"ratelimit")||o(t,"ratelimit-policy")||o(t,"x-ratelimit-limit")?{rateLimit:!0}:{},...o(t,"x-request-id")?{requestId:!0}:{}}}m(responseFacts,"responseFacts"),p(responseFacts,"responseFacts"),l(responseFacts,"responseFacts");
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var r=(a,e)=>f(a,"name",{value:e,configurable:!0});var t=Object.defineProperty,c=r((a,e)=>t(a,"name",{value:e,configurable:!0}),"e");const l=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;export function foldKeyPattern(a){return a.replace(l,"*").replace(/(?<=^|[:=/])(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{16,}(?=$|[:=/])/g,"*").replace(/(?<![A-Za-z])(?=[0-9a-f]*\d)[0-9a-f]{8,}(?![A-Za-z])/gi,"*").replace(/(?<![A-Za-z0-9])\d{2,}(?![A-Za-z0-9])/g,"*").replace(/\*(?:[_-]?\*)+/g,"*")}r(foldKeyPattern,"foldKeyPattern"),c(foldKeyPattern,"foldKeyPattern");
1
+ "use strict";var f=Object.defineProperty;var r=(e,a)=>f(e,"name",{value:a,configurable:!0});var c=Object.defineProperty,t=r((e,a)=>c(e,"name",{value:a,configurable:!0}),"r"),l=Object.defineProperty,n=t((e,a)=>l(e,"name",{value:a,configurable:!0}),"e");const o=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;export function foldKeyPattern(e){return e.replace(o,"*").replace(/(?<=^|[:=/])(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{16,}(?=$|[:=/])/g,"*").replace(/(?<![A-Za-z])(?=[0-9a-f]*\d)[0-9a-f]{8,}(?![A-Za-z])/gi,"*").replace(/(?<![A-Za-z0-9])\d{2,}(?![A-Za-z0-9])/g,"*").replace(/\*(?:[_-]?\*)+/g,"*")}r(foldKeyPattern,"foldKeyPattern"),t(foldKeyPattern,"foldKeyPattern"),n(foldKeyPattern,"foldKeyPattern");
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The workspace's lens configuration (planning/global Z1): `lensmcp.json` → `config` first, then `nx.json` → `lensmcp`,
3
+ * key by key — retention, redaction, channels, thresholds, flows, stores, instances, tests, ai, key. A project detached
4
+ * from Nx wiring keeps it in `lensmcp.json` alone; one set up before keeps it in `nx.json`. Lock-step copy: libs/cli
5
+ * lens-config.ts (the CLI imports no package), byte for byte.
6
+ */
7
+ export type WorkspaceConfig = Record<string, unknown>;
8
+ export type WorkspaceConfigSource = 'lensmcp.json' | 'nx.json';
9
+ /** The merged configuration at `root`: a key `lensmcp.json` → `config` sets wins over the same key in `nx.json` → `lensmcp`. */
10
+ export declare function readWorkspaceConfig(root: string): WorkspaceConfig;
11
+ /** Which file a key of the configuration comes from, or undefined when neither sets it. */
12
+ export declare function workspaceConfigSource(root: string, key: string): WorkspaceConfigSource | undefined;
13
+ /** The nearest folder at or above `from` (8 levels at most) holding `nx.json` or `lensmcp.json` — the workspace whose configuration applies. */
14
+ export declare function findWorkspaceConfigRoot(from: string): string | undefined;
@@ -0,0 +1 @@
1
+ "use strict";var p=Object.defineProperty;var e=(n,o)=>p(n,"name",{value:o,configurable:!0});var u=Object.defineProperty,i=e((n,o)=>u(n,"name",{value:o,configurable:!0}),"e"),l=Object.defineProperty,t=i((n,o)=>l(n,"name",{value:o,configurable:!0}),"e");import{existsSync as f,readFileSync as j}from"node:fs";import{dirname as g,join as r}from"node:path";const m=t(n=>!!n&&typeof n=="object"&&!Array.isArray(n),"isObj");function c(n,o){try{const s=JSON.parse(j(n,"utf8"))?.[o];return m(s)?s:{}}catch{return{}}}e(c,"i"),i(c,"t"),t(c,"block");export function readWorkspaceConfig(n){return{...c(r(n,"nx.json"),"lensmcp"),...c(r(n,"lensmcp.json"),"config")}}e(readWorkspaceConfig,"readWorkspaceConfig"),i(readWorkspaceConfig,"readWorkspaceConfig"),t(readWorkspaceConfig,"readWorkspaceConfig");export function workspaceConfigSource(n,o){return o in c(r(n,"lensmcp.json"),"config")?"lensmcp.json":o in c(r(n,"nx.json"),"lensmcp")?"nx.json":void 0}e(workspaceConfigSource,"workspaceConfigSource"),i(workspaceConfigSource,"workspaceConfigSource"),t(workspaceConfigSource,"workspaceConfigSource");export function findWorkspaceConfigRoot(n){let o=n;for(let s=0;s<8;s++){if(f(r(o,"nx.json"))||f(r(o,"lensmcp.json")))return o;const a=g(o);if(a===o)break;o=a}}e(findWorkspaceConfigRoot,"findWorkspaceConfigRoot"),i(findWorkspaceConfigRoot,"findWorkspaceConfigRoot"),t(findWorkspaceConfigRoot,"findWorkspaceConfigRoot");
package/lib/lens-dir.d.ts CHANGED
@@ -10,6 +10,9 @@
10
10
  * And `.lensmcp/ai-names/`: the names people gave the AI calls page's agents and actions, so the team sees the same
11
11
  * (the AI agent review's own instructions are `.lensmcp/ai-review/`). And `.lensmcp/team/`: the agent team's role files
12
12
  * and its flow of hand-offs (`@lensmcp/storage` team-files.ts), so every agent on the repository works by the same rules —
13
+ * and, under it, `.lensmcp/team/skills/<name>/`: the project's own skills, each a SKILL.md with its references and the
14
+ * pins of the sources it was written from (`@lensmcp/storage` skill-layers.ts). `team` lets the whole folder back in,
15
+ * so the skills need no line of their own (lens-dir.spec.ts holds that) —
13
16
  * and `.lensmcp/team-design/`: the project's own instructions to the run that designs that team.
14
17
  *
15
18
  * The .gitignore that keeps both right ignores the folder's children — at any depth, as `.lensmcp/` did — and lets
@@ -24,6 +27,12 @@
24
27
  * Lock-step copies: `@lensmcp/nx-plugin` init (writes the lines) and `lensmcp doctor` (checks them).
25
28
  */
26
29
  export declare const LENS_SHARED_DIRS: readonly string[];
30
+ /**
31
+ * The team's files that sit deeper than a shared folder's root — a project skill's SKILL.md, its pins and a reference:
32
+ * the lines above must let each through (lens-dir.spec.ts), and `lensmcp doctor` says when a line of the repository's
33
+ * own keeps one out. Lock-step with the CLI's lens-ignore.ts LENS_SHARED_FILES.
34
+ */
35
+ export declare const LENS_SHARED_FILES: readonly string[];
27
36
  /** The .gitignore lines for `.lensmcp/`: at any depth (prefix `**\/`), or at the root only (`/`). */
28
37
  export declare function lensGitignoreLines(prefix?: '**/' | '/'): string[];
29
38
  /**
package/lib/lens-dir.js CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";var u=Object.defineProperty;var r=(t,e)=>u(t,"name",{value:e,configurable:!0});var p=Object.defineProperty,l=r((t,e)=>p(t,"name",{value:e,configurable:!0}),"c");export const LENS_SHARED_DIRS=["sql-review","route-review","flow-review","ui-review","cache-review","queue-review","ai-review","ai-names","team","team-design"];export function lensGitignoreLines(t="**/"){return[`${t}.lensmcp/*`,...LENS_SHARED_DIRS.map(e=>`!${t}.lensmcp/${e}/`)]}r(lensGitignoreLines,"lensGitignoreLines"),l(lensGitignoreLines,"lensGitignoreLines");const $="# LensMCP: this machine's runtime state is ignored; the team's analyzer instructions are kept";export function fixLensGitignore(t){const e=t.split(`
2
- `),m=/^(\/|\*\*\/)?\.lensmcp\/?(\*)?$/;let n=e.findIndex(i=>m.test(i.trim())),s=!1;if(n<0){const i=t.length&&!t.endsWith(`
3
- `)?`${t}
4
- `:t;return{text:`${i}${i.trim()?`
5
- `:""}${$}
1
+ "use strict";var p=Object.defineProperty;var s=(n,e)=>p(n,"name",{value:e,configurable:!0});var f=Object.defineProperty,c=s((n,e)=>f(n,"name",{value:e,configurable:!0}),"n"),$=Object.defineProperty,u=c((n,e)=>$(n,"name",{value:e,configurable:!0}),"c");export const LENS_SHARED_DIRS=["sql-review","route-review","flow-review","ui-review","cache-review","queue-review","ai-review","ai-names","team","team-design"],LENS_SHARED_FILES=["team/skills/a-skill/SKILL.md","team/skills/a-skill/sources.json","team/skills/a-skill/references/more.md"];export function lensGitignoreLines(n="**/"){return[`${n}.lensmcp/*`,...LENS_SHARED_DIRS.map(e=>`!${n}.lensmcp/${e}/`)]}s(lensGitignoreLines,"lensGitignoreLines"),c(lensGitignoreLines,"lensGitignoreLines"),u(lensGitignoreLines,"lensGitignoreLines");const g="# LensMCP: this machine's runtime state is ignored; the team's analyzer instructions are kept";export function fixLensGitignore(n){const e=n.split(`
2
+ `),a=/^(\/|\*\*\/)?\.lensmcp\/?(\*)?$/;let i=e.findIndex(t=>a.test(t.trim())),r=!1;if(i<0){const t=n.length&&!n.endsWith(`
3
+ `)?`${n}
4
+ `:n;return{text:`${t}${t.trim()?`
5
+ `:""}${g}
6
6
  ${lensGitignoreLines().join(`
7
7
  `)}
8
- `,changed:!0}}const c=m.exec(e[n].trim())[1]==="/"?"/":"**/";e[n].trim()!==`${c}.lensmcp/*`&&(e[n]=`${c}.lensmcp/*`,s=!0);for(const i of LENS_SHARED_DIRS){const o=`!${c}.lensmcp/${i}/`;e.some(a=>a.trim()===o||a.trim()===o.slice(0,-1))||(e.splice(++n,0,o),s=!0)}return{text:e.join(`
9
- `),changed:s}}r(fixLensGitignore,"fixLensGitignore"),l(fixLensGitignore,"fixLensGitignore");
8
+ `,changed:!0}}const o=a.exec(e[i].trim())[1]==="/"?"/":"**/";e[i].trim()!==`${o}.lensmcp/*`&&(e[i]=`${o}.lensmcp/*`,r=!0);for(const t of LENS_SHARED_DIRS){const l=`!${o}.lensmcp/${t}/`;e.some(m=>m.trim()===l||m.trim()===l.slice(0,-1))||(e.splice(++i,0,l),r=!0)}return{text:e.join(`
9
+ `),changed:r}}s(fixLensGitignore,"fixLensGitignore"),c(fixLensGitignore,"fixLensGitignore"),u(fixLensGitignore,"fixLensGitignore");
@@ -1,2 +1,2 @@
1
- "use strict";var u=Object.defineProperty;var r=(n,e)=>u(n,"name",{value:e,configurable:!0});var E=Object.defineProperty,i=r((n,e)=>E(n,"name",{value:e,configurable:!0}),"o");import{appendFileSync as l,closeSync as m,mkdirSync as S,openSync as v,renameSync as y,statSync as f,unlinkSync as I}from"node:fs";import{dirname as g,join as _}from"node:path";import{ERROR_DISMISSED as c,ERROR_RESTORED as p,LENS_EVENT_SOURCE as N,METRICS_RESET as R,metricsIdBatches as $}from"@lensmcp/protocol-types";import{rotateBusFile as b}from"./bus-rotation.js";import{ulid as x}from"./ulid.js";export function lensEventFile(n=process.env,e=process.cwd()){return n.LENSMCP_EVENT_FILE??_(e,".lensmcp","events.jsonl")}r(lensEventFile,"lensEventFile"),i(lensEventFile,"lensEventFile");const a=i((n,e,s,t,o)=>({id:x(),sessionId:n,timestamp:e,source:N,category:"runtime",severity:"info",context:{sessionId:n},fingerprint:s,title:t,raw:o}),"lensEvent");export function dismissalEvent(n,e){return a(e,n.until,`${c}:${n.groupId}`,`error dismissed: ${n.title??n.groupId}`,{kind:c,groupId:n.groupId,until:n.until,eventIds:n.eventIds,...n.by?{by:n.by}:{},...n.reason?{reason:n.reason}:{},...n.title?{title:n.title}:{}})}r(dismissalEvent,"dismissalEvent"),i(dismissalEvent,"dismissalEvent");export function restoralEvent(n,e,s){return a(e,s,`${p}:${n}`,"error restored",{kind:p,groupId:n})}r(restoralEvent,"restoralEvent"),i(restoralEvent,"restoralEvent");export function metricsChangeEvents(n,e,s){const t=n.kind===R;return(n.ids?$(n.ids):[void 0]).map(o=>a(e,s,`${n.kind}:${n.scope}`,`${t?"numbers reset":"numbers counted whole again"}: ${n.scope}${o?` \xB7 ${o.length}`:" \xB7 all"}`,{kind:n.kind,scope:n.scope,...t?{at:s}:{},...o?{ids:o}:{}}))}r(metricsChangeEvents,"metricsChangeEvents"),i(metricsChangeEvents,"metricsChangeEvents");const d=i((n,e,s)=>{const t=Number(process.env[n]);return Number.isFinite(t)&&s(t)?t:e},"envNumber");export function appendBusEvents(n,e){e.length!==0&&(S(g(n),{recursive:!0}),b(n,{maxBytes:d("LENSMCP_EVENT_MAX_BYTES",50*1024*1024,s=>s>0),maxFiles:d("LENSMCP_EVENT_MAX_FILES",5,s=>s>=1&&s<=20),fs:{statSync:f,renameSync:y,unlinkSync:I,openSync:v,closeSync:m}}),l(n,e.map(s=>JSON.stringify(s)+`
2
- `).join("")))}r(appendBusEvents,"appendBusEvents"),i(appendBusEvents,"appendBusEvents");
1
+ "use strict";var u=Object.defineProperty;var r=(e,s)=>u(e,"name",{value:s,configurable:!0});var d=Object.defineProperty,a=r((e,s)=>d(e,"name",{value:s,configurable:!0}),"r"),m=Object.defineProperty,i=a((e,s)=>m(e,"name",{value:s,configurable:!0}),"o");import{appendFileSync as v,closeSync as S,mkdirSync as y,openSync as f,renameSync as g,statSync as I,unlinkSync as _}from"node:fs";import{dirname as b,join as N}from"node:path";import{ERROR_DISMISSED as l,ERROR_RESTORED as E,LENS_EVENT_SOURCE as R,METRICS_RESET as $,metricsIdBatches as x}from"@lensmcp/protocol-types";import{rotateBusFile as k}from"./bus-rotation.js";import{ulid as B}from"./ulid.js";export function lensEventFile(e=process.env,s=process.cwd()){return e.LENSMCP_EVENT_FILE??N(s,".lensmcp","events.jsonl")}r(lensEventFile,"lensEventFile"),a(lensEventFile,"lensEventFile"),i(lensEventFile,"lensEventFile");const c=i((e,s,t,n,o)=>({id:B(),sessionId:e,timestamp:s,source:R,category:"runtime",severity:"info",context:{sessionId:e},fingerprint:t,title:n,raw:o}),"lensEvent");export function dismissalEvent(e,s){return c(s,e.until,`${l}:${e.groupId}`,`error dismissed: ${e.title??e.groupId}`,{kind:l,groupId:e.groupId,until:e.until,eventIds:e.eventIds,...e.by?{by:e.by}:{},...e.reason?{reason:e.reason}:{},...e.title?{title:e.title}:{}})}r(dismissalEvent,"dismissalEvent"),a(dismissalEvent,"dismissalEvent"),i(dismissalEvent,"dismissalEvent");export function restoralEvent(e,s,t){return c(s,t,`${E}:${e}`,"error restored",{kind:E,groupId:e})}r(restoralEvent,"restoralEvent"),a(restoralEvent,"restoralEvent"),i(restoralEvent,"restoralEvent");export function metricsChangeEvents(e,s,t){const n=e.kind===$;return(e.ids?x(e.ids):[void 0]).map(o=>c(s,t,`${e.kind}:${e.scope}`,`${n?"numbers reset":"numbers counted whole again"}: ${e.scope}${o?` \xB7 ${o.length}`:" \xB7 all"}`,{kind:e.kind,scope:e.scope,...n?{at:t}:{},...o?{ids:o}:{}}))}r(metricsChangeEvents,"metricsChangeEvents"),a(metricsChangeEvents,"metricsChangeEvents"),i(metricsChangeEvents,"metricsChangeEvents");const p=i((e,s,t)=>{const n=Number(process.env[e]);return Number.isFinite(n)&&t(n)?n:s},"envNumber");export function appendBusEvents(e,s){s.length!==0&&(y(b(e),{recursive:!0}),k(e,{maxBytes:p("LENSMCP_EVENT_MAX_BYTES",50*1024*1024,t=>t>0),maxFiles:p("LENSMCP_EVENT_MAX_FILES",5,t=>t>=1&&t<=20),fs:{statSync:I,renameSync:g,unlinkSync:_,openSync:f,closeSync:S}}),v(e,s.map(t=>JSON.stringify(t)+`
2
+ `).join("")))}r(appendBusEvents,"appendBusEvents"),a(appendBusEvents,"appendBusEvents"),i(appendBusEvents,"appendBusEvents");
@@ -0,0 +1,37 @@
1
+ export interface StoredLensmcp {
2
+ home: string;
3
+ version: string;
4
+ dir: string;
5
+ pkg: string;
6
+ cli: string;
7
+ launcher: string;
8
+ }
9
+ export declare const lensStoreHome: (env?: NodeJS.ProcessEnv) => string;
10
+ export declare function storedLensmcp(home: string, version: string): StoredLensmcp | undefined;
11
+ export declare function storeCurrent(env?: NodeJS.ProcessEnv): StoredLensmcp | undefined;
12
+ export declare function inLensStore(path: string, env?: NodeJS.ProcessEnv): boolean;
13
+ /** The stored version a path lies in (as named, or as it really is through `current`), when it is a whole one. */
14
+ export declare function storeVersionOf(path: string, env?: NodeJS.ProcessEnv): StoredLensmcp | undefined;
15
+ /**
16
+ * The stored lensmcp a process hands out: a process that runs from the store keeps its own version until it restarts
17
+ * (owner, 2026-11-10); only one that runs from elsewhere takes the store's current version.
18
+ */
19
+ export declare function storeOwnOrCurrent(entry?: string | undefined, env?: NodeJS.ProcessEnv): StoredLensmcp | undefined;
20
+ /** The published packages installed beside lensmcp in every version folder (libs/cli store.ts OPTIONAL_PACKAGES). */
21
+ export declare const LENS_OPTIONAL_PACKAGES: readonly string[];
22
+ /** The optional packages a version folder holds. */
23
+ export declare function storedOptionalNames(home: string, version: string): string[];
24
+ /** Semver order, a pre-release before its release and `rc.9` before `rc.10` (libs/cli store.ts compareVersions). */
25
+ export declare function compareLensVersions(a: string, b: string): number;
26
+ /** Every whole version the store holds, oldest first. */
27
+ export declare function storedVersionNames(home: string): string[];
28
+ /** The versions forwarded lensmcp processes run (`versions/.running/<pid>`, libs/cli store.ts markForwarded), by pid; gone pids are left out. */
29
+ export declare function storeForwardedRunning(home: string): Map<string, number[]>;
30
+ export declare function linkedCheckout(pkg: string): boolean;
31
+ export declare function storeFirst(project: string | undefined, env?: NodeJS.ProcessEnv, entry?: string | undefined): string[];
32
+ export declare const STORE_FIRST_MCP = "h=\"${LENSMCP_HOME:-$HOME/.lensmcp}\"; [ \"${LENSMCP_NO_STORE:-}\" != 1 ] && [ -x \"$h/bin/lensmcp\" ] && [ -f \"$h/current/node_modules/lensmcp/bin.js\" ] && exec \"$h/bin/lensmcp\" mcp; exec npx ";
33
+ export declare function storeFirstMcpEntry(fallback: readonly string[]): {
34
+ command: string;
35
+ args: string[];
36
+ };
37
+ export declare function storeFirstFallback(entry: unknown): string[] | undefined;
@@ -0,0 +1 @@
1
+ "use strict";var N=Object.defineProperty;var i=(e,t)=>N(e,"name",{value:t,configurable:!0});var b=Object.defineProperty,u=i((e,t)=>b(e,"name",{value:t,configurable:!0}),"i"),E=Object.defineProperty,o=u((e,t)=>E(e,"name",{value:t,configurable:!0}),"s");import{existsSync as O,readdirSync as x,readFileSync as S,readlinkSync as k,realpathSync as F}from"node:fs";import{homedir as _}from"node:os";import{basename as C,join as p,sep as d}from"node:path";export const lensStoreHome=o((e=process.env)=>e.LENSMCP_HOME||p(_(),".lensmcp"),"lensStoreHome");const h=o(e=>{try{return F(e)}catch{return e}},"realOr");export function storedLensmcp(e,t){const r=p(e,"versions",t),n=p(r,"node_modules","lensmcp"),s=p(n,"bin.js");if(O(s)){try{if(JSON.parse(S(p(n,"package.json"),"utf8")).version!==t)return}catch{return}return{home:e,version:t,dir:r,pkg:n,cli:s,launcher:p(e,"bin","lensmcp")}}}i(storedLensmcp,"storedLensmcp"),u(storedLensmcp,"storedLensmcp"),o(storedLensmcp,"storedLensmcp");export function storeCurrent(e=process.env){if(e.LENSMCP_NO_STORE==="1")return;const t=lensStoreHome(e);let r;try{r=C(k(p(t,"current")))}catch{return}return storedLensmcp(t,r)}i(storeCurrent,"storeCurrent"),u(storeCurrent,"storeCurrent"),o(storeCurrent,"storeCurrent");export function inLensStore(e,t=process.env){const r=p(lensStoreHome(t),"versions");return e.startsWith(r+d)||h(e).startsWith(h(r)+d)}i(inLensStore,"inLensStore"),u(inLensStore,"inLensStore"),o(inLensStore,"inLensStore");const g=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;export function storeVersionOf(e,t=process.env){const r=lensStoreHome(t),n=p(r,"versions");for(const[s,a]of[[e,n],[h(e),h(n)]]){if(!s.startsWith(a+d))continue;const m=s.slice(a.length+1).split(d,1)[0]??"";if(g.test(m))return storedLensmcp(r,m)}}i(storeVersionOf,"storeVersionOf"),u(storeVersionOf,"storeVersionOf"),o(storeVersionOf,"storeVersionOf");export function storeOwnOrCurrent(e=process.argv[1],t=process.env){if(t.LENSMCP_NO_STORE!=="1")return e&&inLensStore(e,t)?storeVersionOf(e,t):storeCurrent(t)}i(storeOwnOrCurrent,"storeOwnOrCurrent"),u(storeOwnOrCurrent,"storeOwnOrCurrent"),o(storeOwnOrCurrent,"storeOwnOrCurrent");export const LENS_OPTIONAL_PACKAGES=["@lensmcp/terminals","@lensmcp/vite-plugin","@lensmcp/bridge","@lensmcp/client-runtime","@lensmcp/react-instrumentation","@lensmcp/valtio-instrumentation"];export function storedOptionalNames(e,t){return LENS_OPTIONAL_PACKAGES.filter(r=>O(p(e,"versions",t,"node_modules",r,"package.json")))}i(storedOptionalNames,"storedOptionalNames"),u(storedOptionalNames,"storedOptionalNames"),o(storedOptionalNames,"storedOptionalNames");export function compareLensVersions(e,t){const r=o(c=>{const l=c.indexOf("-");return{nums:(l<0?c:c.slice(0,l)).split(".").map(f=>Number(f)||0),pre:l<0?void 0:c.slice(l+1)}},"parse"),n=r(e),s=r(t);for(let c=0;c<3;c++){const l=(n.nums[c]??0)-(s.nums[c]??0);if(l)return l<0?-1:1}if(n.pre===s.pre)return 0;if(n.pre===void 0)return 1;if(s.pre===void 0)return-1;const a=n.pre.split("."),m=s.pre.split(".");for(let c=0;c<Math.max(a.length,m.length);c++){const l=a[c],f=m[c];if(l===void 0)return-1;if(f===void 0)return 1;if(l===f)continue;const v=/^\d+$/.test(l),y=/^\d+$/.test(f);return v&&y?Number(l)<Number(f)?-1:1:v!==y?v?-1:1:l<f?-1:1}return 0}i(compareLensVersions,"compareLensVersions"),u(compareLensVersions,"compareLensVersions"),o(compareLensVersions,"compareLensVersions");export function storedVersionNames(e){let t;try{t=x(p(e,"versions"))}catch{return[]}return t.filter(r=>g.test(r)&&storedLensmcp(e,r)!==void 0).sort(compareLensVersions)}i(storedVersionNames,"storedVersionNames"),u(storedVersionNames,"storedVersionNames"),o(storedVersionNames,"storedVersionNames");const L=o(e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},"pidAlive");export function storeForwardedRunning(e){const t=new Map,r=p(e,"versions",".running");let n;try{n=x(r)}catch{return t}for(const s of n){const a=Number(s);if(!Number.isInteger(a)||a<=0||!L(a))continue;let m;try{m=S(p(r,s),"utf8").trim()}catch{continue}g.test(m)&&t.set(m,[...t.get(m)??[],a])}return t}i(storeForwardedRunning,"storeForwardedRunning"),u(storeForwardedRunning,"storeForwardedRunning"),o(storeForwardedRunning,"storeForwardedRunning");export function linkedCheckout(e){if(!O(p(e,"package.json")))return!1;const t=h(e).split(d);return t[t.length-1]!=="lensmcp"||t[t.length-2]!=="node_modules"}i(linkedCheckout,"linkedCheckout"),u(linkedCheckout,"linkedCheckout"),o(linkedCheckout,"linkedCheckout");export function storeFirst(e,t=process.env,r=process.argv[1]){const n=storeOwnOrCurrent(r,t);return!n||e&&linkedCheckout(e)?e?[e]:[]:e?[n.pkg,e]:[n.pkg]}i(storeFirst,"storeFirst"),u(storeFirst,"storeFirst"),o(storeFirst,"storeFirst");export const STORE_FIRST_MCP='h="${LENSMCP_HOME:-$HOME/.lensmcp}"; [ "${LENSMCP_NO_STORE:-}" != 1 ] && [ -x "$h/bin/lensmcp" ] && [ -f "$h/current/node_modules/lensmcp/bin.js" ] && exec "$h/bin/lensmcp" mcp; exec npx ';export function storeFirstMcpEntry(e){return{command:"sh",args:["-c",`${STORE_FIRST_MCP}${e.join(" ")}`]}}i(storeFirstMcpEntry,"storeFirstMcpEntry"),u(storeFirstMcpEntry,"storeFirstMcpEntry"),o(storeFirstMcpEntry,"storeFirstMcpEntry");export function storeFirstFallback(e){if(!e||typeof e!="object"||Array.isArray(e))return;const{command:t,args:r,...n}=e;if(t!=="sh"||Object.keys(n).length>0||!Array.isArray(r)||r.length!==2||r[0]!=="-c")return;const s=r[1];if(typeof s!="string"||!s.startsWith(STORE_FIRST_MCP))return;const a=s.slice(STORE_FIRST_MCP.length).split(" ");return a.every(m=>/^[\w@.-]+$/.test(m))?a:void 0}i(storeFirstFallback,"storeFirstFallback"),u(storeFirstFallback,"storeFirstFallback"),o(storeFirstFallback,"storeFirstFallback");
package/lib/patterns.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * call them on demand.
6
6
  *
7
7
  * Detectors covered (Phase 7):
8
- * - db-in-loop — a `loop` node completed with dbCallsInsideLoop > N
8
+ * - db-in-loop — a `loop` node: one statement shape repeated inside one method (`dbLoopBreaks`)
9
9
  * - n+1-query — the same query signature repeated ≥ N times in a window
10
10
  * - slow-path — the longest cumulative duration on the caused/async axis
11
11
  * - render-storm — one componentInstanceId rendered > N times in < T ms
@@ -24,24 +24,40 @@ export interface PatternMatch {
24
24
  detectedAt: number;
25
25
  }
26
26
  export interface DbInLoopOptions {
27
- /** Minimum DB calls inside a loop before it's flagged. Default 5. */
27
+ /** `dbInLoop`: a statement run with the SAME values more often than this inside one method is a repeated read. Default 5. */
28
28
  threshold?: number;
29
+ /** `nPlusOne`: a statement run with varying values this often inside one method is a loop. Default 3. */
30
+ nPlusOne?: number;
29
31
  }
30
- /**
31
- * The DB calls a loop is judged by (`dbInLoop`): all it made — or, for a loop of a stream that says how many fell within
32
- * two neighbouring seconds (`dbBurst`), those. A stream's pump reads every few seconds for as long as the stream is open:
33
- * only a burst inside it is a loop's work (issues/closed/foodguard-148).
34
- */
32
+ /** The runs of the one statement a loop repeated — a stream's, within two seconds (`dbBurst`, foodguard-148). */
35
33
  export declare function loopDbCalls(loop: {
36
34
  dbCallsInsideLoop?: unknown;
37
35
  dbBurst?: unknown;
38
36
  stream?: unknown;
39
37
  }): number;
40
- /**
41
- * Flag `loop` events whose DB calls (`loopDbCalls`) exceed the threshold.
42
- * Events are expected to carry `raw.kind === 'loop'` with a `loop`
43
- * attribute matching `LoopAttrs`.
44
- */
38
+ /** A method's DB work: one shape with varying values (`loop`), the same values (`repeated-read`), or distinct ones (`sequential`). */
39
+ export type DbWorkClass = 'loop' | 'repeated-read' | 'sequential';
40
+ export declare const DB_WORK_CLASSES: readonly DbWorkClass[];
41
+ /** A `loop` event's class — undefined from a tap before statement shapes, which counted every DB call of the method. */
42
+ export declare function dbLoopClass(loop: {
43
+ class?: unknown;
44
+ }): DbWorkClass | undefined;
45
+ /** The repeats of one shape with varying values that make a loop: `nPlusOne`, or fewer when `dbInLoop` is set lower. */
46
+ export declare const loopRepeatsLimit: (l: {
47
+ nPlusOne: number;
48
+ dbInLoop: number;
49
+ }) => number;
50
+ /** A loop from `loopRepeatsLimit` repeats, a repeated read above `dbInLoop`; sequential or class-less (an older tap) never (overseer-73). */
51
+ export declare function dbLoopBreaks(loop: {
52
+ class?: unknown;
53
+ dbCallsInsideLoop?: unknown;
54
+ dbBurst?: unknown;
55
+ stream?: unknown;
56
+ }, l: {
57
+ nPlusOne: number;
58
+ dbInLoop: number;
59
+ }): boolean;
60
+ /** Flag `loop` events (`raw.loop`, `LoopAttrs`) whose DB work breaks the limits (`dbLoopBreaks`). */
45
61
  export declare function detectDbInLoop(events: readonly BaseEvent[], options?: DbInLoopOptions): PatternMatch[];
46
62
  export interface AbandonedAwaitOptions {
47
63
  /** How long a call must run past the end of the method that started it. Default 250 ms. */