@aceshooting/lyra-ui 30.1.0 → 30.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -0
- package/dist/ai/adapters/a2ui.d.ts +10 -4
- package/dist/ai/adapters/a2ui.js +1 -1
- package/dist/ai/adapters/ag-ui.d.ts +17 -4
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/ai/adapters/ai-sdk.js +1 -1
- package/dist/ai/runtime.js +1 -1
- package/dist/components/agent-tools/mcp-app/mcp-app-protocol.d.ts +15 -0
- package/dist/components/agent-tools/mcp-app/mcp-app-protocol.js +36 -0
- package/dist/components/agent-tools/mcp-app/mcp-app.class.d.ts +31 -4
- package/dist/components/agent-tools/mcp-app/mcp-app.class.js +4 -4
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
- package/dist/components/charts/chart/chart-prepared-data.d.ts +3 -1
- package/dist/components/charts/chart/chart-prepared-data.js +1 -1
- package/dist/components/charts/chart/chart.class.js +2 -2
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +13 -4
- package/dist/components/conversation/message-parts/message-parts.class.js +12 -10
- package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
- package/dist/components/conversation/message-parts/message-parts.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -1
- package/dist/components/forms/checkbox/checkbox.class.js +2 -2
- package/dist/components/forms/combobox/option.class.d.ts +1 -1
- package/dist/components/forms/combobox/option.class.js +2 -2
- package/dist/components/forms/radio/radio.class.d.ts +1 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +1 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/media/file-input/file-input.styles.js +1 -1
- package/dist/components/media/map/map-anchor-controller.js +1 -1
- package/dist/components/media/map/map-control-chrome.js +1 -0
- package/dist/components/media/map/map-control-options.d.ts +6 -2
- package/dist/components/media/map/map-control-options.js +1 -1
- package/dist/components/media/map/map-controls-lifecycle.js +1 -1
- package/dist/components/media/map/map-controls-readiness.js +1 -0
- package/dist/components/media/map/map.class.d.ts +39 -2
- package/dist/components/media/map/map.class.js +13 -7
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.d.ts +11 -11
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/events.d.ts +10 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/accessible-text-controller.js +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/default-label-forwarding.js +1 -0
- package/dist/internal/hierarchy-summary-source.js +1 -0
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.d.ts +8 -0
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/llms/components/lr-file-input.md +5 -0
- package/llms/components/lr-map.md +87 -14
- package/llms/components/lr-mcp-app.md +94 -4
- package/llms/components/lr-message-parts.md +18 -0
- package/llms/components/lr-pptx-viewer.md +9 -5
- package/llms/components/lr-select.md +3 -2
- package/llms/index.md +1 -1
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +77 -3
- package/llms/shared/events-and-types.md +25 -1
- package/llms/shared/localization-and-rtl.md +29 -0
- package/llms/shared.md +131 -4
- package/locales.json +1 -1
- package/package.json +12 -8
- package/registrations.json +1 -1
- package/skills/compose-lyra-interfaces/SKILL.md +5 -3
- package/skills/compose-lyra-interfaces/references/composition-patterns.md +8 -1
- package/skills/lyra-ui/SKILL.md +16 -8
- package/skills/lyra-ui/lyra-gen.md +86 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{finiteRange}from"../../../internal/numbers.js";import{resolveCssLength}from"../../../internal/css-length.js";import{LyraElement}from"../../../internal/lyra-element.js";import{safeFrameSrc}from"../../../internal/safe-url.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{styles}from"./mcp-app.styles.js";import{purposeAccessibleLabel}from"../semantic-owner.js";import{LYRA_DEFAULT_mcpAppLabel,LYRA_DEFAULT_mcpAppLoading,LYRA_DEFAULT_mcpAppUnavailable}from"../../../internal/default-strings/agent-tools.generated.js";function record(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:null}function resolveResource(resource){const value=record(resource);if(!value||typeof value.uri!="string")return null;const uri=value.uri.trim();if(!uri)return null;const ownsHtml=Object.prototype.hasOwnProperty.call(value,"html"),ownsSrc=Object.prototype.hasOwnProperty.call(value,"src");if(ownsHtml===ownsSrc)return null;if(ownsHtml)return typeof value.html!="string"||value.html.length===0?null:{resource,uri,html:value.html};const src=safeFrameSrc(value.src);return src?{resource,uri,src}:null}function sameAppDocument(a,b){if(!a||!b||a.uri!==b.uri||a.html!==b.html||a.src!==b.src)return!1;const policy=({csp,permissions,metadata})=>JSON.stringify([csp,permissions,metadata]);try{return policy(a.resource)===policy(b.resource)}catch{return!1}}const CSP_HOST=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])$/i;function cspSources(values){return(values??[]).flatMap(value=>{try{const url=new URL(value);return(url.protocol==="https:"||url.protocol==="http:")&&CSP_HOST.test(url.hostname)?[url.origin]:[]}catch{return[]}})}function buildCsp(csp){const resources=cspSources(csp?.resourceDomains),connections=cspSources(csp?.connectDomains),frames=cspSources(csp?.frameDomains);return["default-src 'none'","script-src 'unsafe-inline'","style-src 'unsafe-inline'",`img-src data: blob: ${resources.join(" ")}`.trim(),`font-src data: ${resources.join(" ")}`.trim(),`media-src data: blob: ${resources.join(" ")}`.trim(),`connect-src ${connections.length?connections.join(" "):"'none'"}`,`frame-src ${frames.length?frames.join(" "):"'none'"}`,"base-uri 'none'","form-action 'none'"].join("; ")}function withCsp(htmlSource,csp){return`${`<meta http-equiv="Content-Security-Policy" content="${buildCsp(csp)}">`}${htmlSource}`}function absoluteLinkHref(value){try{const url=new URL(typeof value=="string"?value:"");return["http:","https:","mailto:"].includes(url.protocol)?url.href:null}catch{return null}}const heightAttributeConverter={fromAttribute(value){if(value===null)return null;const numeric=Number(value);return Number.isFinite(numeric)?numeric:value.trim()}};function permissionPolicy(permissions){return[permissions?.camera?"camera":"",permissions?.microphone?"microphone":"",permissions?.geolocation?"geolocation":"",permissions?.clipboardRead?"clipboard-read":"",permissions?.clipboardWrite?"clipboard-write":""].filter(Boolean).map(permission=>`${permission} *`).join("; ")}class LyraMcpApp extends LyraElement{constructor(){super(...arguments),this.resource=null,this.height=320,this.maxHeight=800,this.label="",this.accessibleLabel=null,this.loaded=!1,this.frameHeight=320,this.frameGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.suppressNextResourceAnnouncement=!0,this.onPortMessage=event=>{this.handleMessage(event.data)}}static{this.defaultStrings={...super.defaultStrings,mcpAppLabel:LYRA_DEFAULT_mcpAppLabel,mcpAppLoading:LYRA_DEFAULT_mcpAppLoading,mcpAppUnavailable:LYRA_DEFAULT_mcpAppUnavailable}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["resource"])}static{this.styles=[LyraElement.styles,styles]}resourceAvailable(resource){return resolveResource(resource)!==null}invalidateFrame(){this.closeFramePort(),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.frameNonce=this.resourceAvailable(this.resource)?this.createFrameNonce():void 0,this.loaded=!1,this.frameGeneration++,this.requestUpdate()}closeFramePort(){this.framePort?.removeEventListener("message",this.onPortMessage),this.framePort?.close(),this.framePort=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.suppressNextResourceAnnouncement=!0,this.requestUpdate())}disconnectedCallback(){this.invalidateFrame(),this.suppressNextResourceAnnouncement=!0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.invalidateFrame(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed);const keptFrame=changed.has("resource")&&this.hasUpdated&&sameAppDocument(resolveResource(changed.get("resource")),resolveResource(this.resource));if(changed.has("resource")&&!keptFrame){if(this.hasUpdated&&!this.suppressNextResourceAnnouncement){const wasAvailable=this.resourceAvailable(changed.get("resource"));this.resourceAvailable(this.resource)?this.announcements.announcePolite(this.localize("mcpAppLoading")):wasAvailable&&this.announcements.announceAssertive(this.localize("mcpAppUnavailable"))}this.loaded=!1,this.closeFramePort(),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.frameNonce=this.resourceAvailable(this.resource)?this.createFrameNonce():void 0,this.frameGeneration++}(changed.has("resource")&&!keptFrame||changed.has("height")||changed.has("maxHeight"))&&(this.frameHeight=finiteRange(this.heightPx(),320,120,this.maxHeightPx()))}updated(_changed){super.updated(_changed),this.suppressNextResourceAnnouncement=!1}createFrameNonce(){return crypto.randomUUID()}onLoad(event,frameGeneration,resource){if(!this.isConnected||frameGeneration!==this.frameGeneration||event.currentTarget!==this.frame)return;const currentResource=resolveResource(this.resource);if(!currentResource||currentResource.resource!==resource.resource&&!sameAppDocument(currentResource,resource))return;if(this.loaded){this.invalidateFrame();return}this.frameNonce??=this.createFrameNonce();const frame=event.currentTarget,port=new MessageChannel;this.framePort=port.port1,this.framePort.addEventListener("message",this.onPortMessage),this.framePort.start(),this.loaded=!0,this.bootstrapPort={frame,port:port.port2},this.postHostContext({resource:{uri:resource.uri,metadata:resource.resource.metadata},locale:this.effectiveLocale,direction:this.effectiveDirection}),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.emit("lr-mcp-ready",{uri:resource.uri})}heightPx(){return resolveCssLength(this.height,{host:this})??Number.NaN}maxHeightPx(){return finiteRange(resolveCssLength(this.maxHeight,{host:this})??Number.NaN,800,120,1e4)}handleMessage(data){const message=record(data);if(!(typeof this.frameNonce!="string"||message?.nonce!==this.frameNonce)&&!(message?.channel!=="lyra-mcp-app"||message.version!==1||typeof message.type!="string"))switch(message.type){case"resize":{const requested=typeof message.height=="number"?message.height:this.heightPx(),height=finiteRange(requested,this.heightPx(),120,this.maxHeightPx());this.frameHeight=height,this.emit("lr-mcp-resize",{height});break}case"tool-call":typeof message.name=="string"&&this.emit("lr-mcp-tool-call",{requestId:typeof message.requestId=="string"?message.requestId:void 0,name:message.name,args:message.args,frameGeneration:this.frameGeneration});break;case"send-message":this.emit("lr-mcp-send-message",{message:message.message});break;case"open-link":{const href=absoluteLinkHref(message.href);href&&this.emit("lr-mcp-open-link",{href})}break;case"log":this.emit("lr-mcp-log",{level:typeof message.level=="string"?message.level:"info",value:message.value});break}}post(message,frame=this.frame,transferPort){const nonce=this.frameNonce;if(typeof nonce=="string"){if(transferPort){const target=frame?.contentWindow;if(!target)return;target.postMessage({...message,nonce},"*",[transferPort]);return}this.framePort?.postMessage({...message,nonce})}}postHostContext(context){const bootstrap=this.bootstrapPort;this.bootstrapPort=void 0,this.post({channel:"lyra-mcp-app",version:1,type:"host-context",context},bootstrap?.frame,bootstrap?.port)}postToolResult(requestId,options){const value=record(options);if(typeof requestId!="string"||!requestId.trim()||!value)return;const frameGeneration=value.frameGeneration;if(typeof frameGeneration!="number"||!Number.isSafeInteger(frameGeneration)||frameGeneration!==this.frameGeneration)return;const hasResult=Object.prototype.hasOwnProperty.call(value,"result"),hasError=Object.prototype.hasOwnProperty.call(value,"error");hasResult!==hasError&&(hasError&&(typeof value.error!="string"||!value.error.trim())||this.post({channel:"lyra-mcp-app",version:1,type:"tool-result",requestId,...hasResult?{result:value.result}:{},...hasError?{error:value.error}:{}}))}render(){const resource=resolveResource(this.resource);if(!resource)return html`<div part="base"><p part="error">${this.localize("mcpAppUnavailable")}</p></div>`;const fallbackLabel=(!this.hasAttribute("aria-label")&&typeof this.accessibleLabel=="string"?this.accessibleLabel:"")||this.label||resource.resource.title||this.localize("mcpAppLabel"),label=purposeAccessibleLabel(this,fallbackLabel),frameGeneration=this.frameGeneration;return html`<div part="base">
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{finiteRange}from"../../../internal/numbers.js";import{resolveCssLength}from"../../../internal/css-length.js";import{LyraElement}from"../../../internal/lyra-element.js";import{safeFrameSrc}from"../../../internal/safe-url.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{styles}from"./mcp-app.styles.js";import{McpAppSession,MCP_APP_PROXY_DOCUMENT,mcpRecord}from"./mcp-app-protocol.js";import{purposeAccessibleLabel}from"../semantic-owner.js";import{LYRA_DEFAULT_mcpAppLabel,LYRA_DEFAULT_mcpAppLoading,LYRA_DEFAULT_mcpAppUnavailable}from"../../../internal/default-strings/agent-tools.generated.js";function record(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:null}function resolveResource(resource){const value=record(resource);if(!value||typeof value.uri!="string")return null;const uri=value.uri.trim();if(!uri)return null;const ownsHtml=Object.prototype.hasOwnProperty.call(value,"html"),ownsSrc=Object.prototype.hasOwnProperty.call(value,"src");if(ownsHtml===ownsSrc)return null;if(ownsHtml)return typeof value.html!="string"||value.html.length===0?null:{resource,uri,html:value.html};const src=safeFrameSrc(value.src);return src?{resource,uri,src}:null}function sameAppDocument(a,b){if(!a||!b||a.uri!==b.uri||a.html!==b.html||a.src!==b.src)return!1;const policy=({csp,permissions,metadata})=>JSON.stringify([csp,permissions,metadata]);try{return policy(a.resource)===policy(b.resource)}catch{return!1}}const CSP_HOST=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])$/i;function cspSources(values){return(values??[]).flatMap(value=>{try{const url=new URL(value);return(url.protocol==="https:"||url.protocol==="http:")&&CSP_HOST.test(url.hostname)?[url.origin]:[]}catch{return[]}})}function buildCsp(csp,externalAssets){const resources=cspSources(csp?.resourceDomains),connections=cspSources(csp?.connectDomains),frames=cspSources(csp?.frameDomains);return["default-src 'none'",`script-src 'unsafe-inline' ${externalAssets?resources.join(" "):""}`.trim(),`style-src 'unsafe-inline' ${externalAssets?resources.join(" "):""}`.trim(),`img-src data: blob: ${resources.join(" ")}`.trim(),`font-src data: ${resources.join(" ")}`.trim(),`media-src data: blob: ${resources.join(" ")}`.trim(),`connect-src ${connections.length?connections.join(" "):"'none'"}`,`frame-src ${frames.length?frames.join(" "):"'none'"}`,"base-uri 'none'","form-action 'none'"].join("; ")}function withCsp(htmlSource,csp,externalAssets=!1){return`${`<meta http-equiv="Content-Security-Policy" content="${buildCsp(csp,externalAssets)}">`}${htmlSource}`}function absoluteLinkHref(value){try{const url=new URL(typeof value=="string"?value:"");return["http:","https:","mailto:"].includes(url.protocol)?url.href:null}catch{return null}}const heightAttributeConverter={fromAttribute(value){if(value===null)return null;const numeric=Number(value);return Number.isFinite(numeric)?numeric:value.trim()}};function permissionPolicy(permissions){return[permissions?.camera?"camera":"",permissions?.microphone?"microphone":"",permissions?.geolocation?"geolocation":"",permissions?.clipboardRead?"clipboard-read":"",permissions?.clipboardWrite?"clipboard-write":""].filter(Boolean).map(permission=>`${permission} *`).join("; ")}class LyraMcpApp extends LyraElement{constructor(){super(...arguments),this.resource=null,this.protocol="legacy",this.hostCapabilities={},this.height=320,this.maxHeight=800,this.label="",this.accessibleLabel=null,this.loaded=!1,this.frameHeight=320,this.frameGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.suppressNextResourceAnnouncement=!0,this.onPortMessage=event=>{this.handleMessage(event.data)}}static{this.defaultStrings={...super.defaultStrings,mcpAppLabel:LYRA_DEFAULT_mcpAppLabel,mcpAppLoading:LYRA_DEFAULT_mcpAppLoading,mcpAppUnavailable:LYRA_DEFAULT_mcpAppUnavailable}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["resource","hostCapabilities"])}static{this.styles=[LyraElement.styles,styles]}resourceAvailable(resource){return resolveResource(resource)!==null}invalidateFrame(){this.closeFramePort(),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.frameNonce=this.resourceAvailable(this.resource)?this.createFrameNonce():void 0,this.loaded=!1,this.frameGeneration++,this.requestUpdate()}closeFramePort(){this.deliveredEnvironment=void 0,this.protocolSession?.close(),this.protocolSession=void 0,this.framePort?.removeEventListener("message",this.onPortMessage),this.framePort?.close(),this.framePort=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.suppressNextResourceAnnouncement=!0,this.requestUpdate())}disconnectedCallback(){this.invalidateFrame(),this.suppressNextResourceAnnouncement=!0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.invalidateFrame(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed);const keptFrame=changed.has("resource")&&this.hasUpdated&&sameAppDocument(resolveResource(changed.get("resource")),resolveResource(this.resource));if(changed.has("resource")&&!keptFrame||changed.has("protocol")||changed.has("hostCapabilities")){if(this.hasUpdated&&!this.suppressNextResourceAnnouncement){const wasAvailable=this.resourceAvailable(changed.get("resource"));this.resourceAvailable(this.resource)?this.announcements.announcePolite(this.localize("mcpAppLoading")):wasAvailable&&this.announcements.announceAssertive(this.localize("mcpAppUnavailable"))}this.loaded=!1,this.closeFramePort(),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.frameNonce=this.resourceAvailable(this.resource)?this.createFrameNonce():void 0,this.frameGeneration++}(changed.has("resource")&&!keptFrame||changed.has("height")||changed.has("maxHeight"))&&(this.frameHeight=finiteRange(this.heightPx(),320,120,this.maxHeightPx())),this.pendingEnvironment=this.loaded?{locale:this.effectiveLocale,direction:this.effectiveDirection}:void 0}updated(_changed){super.updated(_changed),this.suppressNextResourceAnnouncement=!1;const context=this.pendingEnvironment;this.pendingEnvironment=void 0,this.loaded&&this.deliveredEnvironment&&context&&(context.locale!==this.deliveredEnvironment.locale||context.direction!==this.deliveredEnvironment.direction)&&(this.deliveredEnvironment=context,this.postHostContext(context))}createFrameNonce(){return crypto.randomUUID()}onLoad(event,frameGeneration,resource){if(!this.isConnected||frameGeneration!==this.frameGeneration||event.currentTarget!==this.frame)return;const currentResource=resolveResource(this.resource);if(!currentResource||currentResource.resource!==resource.resource&&!sameAppDocument(currentResource,resource))return;if(this.loaded){this.invalidateFrame();return}this.frameNonce??=this.createFrameNonce();const frame=event.currentTarget,port=new MessageChannel;this.framePort=port.port1,this.framePort.addEventListener("message",this.onPortMessage),this.framePort.start(),this.loaded=!0,this.bootstrapPort={frame,port:port.port2},this.deliveredEnvironment={locale:this.effectiveLocale,direction:this.effectiveDirection},this.postHostContext({resource:{uri:resource.uri,metadata:resource.resource.metadata},...this.deliveredEnvironment}),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.protocol==="mcp-apps"&&(this.protocolSession=new McpAppSession({generation:frameGeneration,capabilities:this.hostCapabilities,context:{locale:this.effectiveLocale,displayMode:"inline",availableDisplayModes:["inline"]},send:message=>this.post({channel:"lyra-mcp-app",version:1,type:"mcp-apps",message}),request:detail=>this.emit("lr-mcp-request",detail),initialized:()=>this.emit("lr-mcp-initialized",{uri:resource.uri,frameGeneration}),resize:requested=>{const height=finiteRange(requested,this.heightPx(),120,this.maxHeightPx());this.frameHeight=height,this.emit("lr-mcp-resize",{height})},log:(level,value)=>this.emit("lr-mcp-log",{level,value})}),this.post({channel:"lyra-mcp-app",version:1,type:"mcp-resource",title:this.frame?.title??this.localize("mcpAppLabel"),allow:permissionPolicy(resource.resource.permissions),...resource.html?{html:withCsp(resource.html,resource.resource.csp,!0)}:{src:resource.src}})),this.emit("lr-mcp-ready",{uri:resource.uri})}heightPx(){return resolveCssLength(this.height,{host:this})??Number.NaN}maxHeightPx(){return finiteRange(resolveCssLength(this.maxHeight,{host:this})??Number.NaN,800,120,1e4)}handleMessage(data){const message=record(data);if(!(typeof this.frameNonce!="string"||message?.nonce!==this.frameNonce)&&!(message?.channel!=="lyra-mcp-app"||message.version!==1||typeof message.type!="string")){if(this.protocol==="mcp-apps"){message.type==="mcp-apps"?this.protocolSession?.receive(message.message):message.type==="mcp-navigation"&&this.invalidateFrame();return}switch(message.type){case"resize":{const requested=typeof message.height=="number"?message.height:this.heightPx(),height=finiteRange(requested,this.heightPx(),120,this.maxHeightPx());this.frameHeight=height,this.emit("lr-mcp-resize",{height});break}case"tool-call":typeof message.name=="string"&&this.emit("lr-mcp-tool-call",{requestId:typeof message.requestId=="string"?message.requestId:void 0,name:message.name,args:message.args,frameGeneration:this.frameGeneration});break;case"send-message":this.emit("lr-mcp-send-message",{message:message.message});break;case"open-link":{const href=absoluteLinkHref(message.href);href&&this.emit("lr-mcp-open-link",{href})}break;case"log":this.emit("lr-mcp-log",{level:typeof message.level=="string"?message.level:"info",value:message.value});break}}}post(message,frame=this.frame,transferPort){const nonce=this.frameNonce;if(typeof nonce=="string"){if(transferPort){const target=frame?.contentWindow;if(!target)return;target.postMessage({...message,nonce},"*",[transferPort]);return}this.framePort?.postMessage({...message,nonce})}}postHostContext(context){const bootstrap=this.bootstrapPort;if(this.bootstrapPort=void 0,this.protocol==="mcp-apps"&&!bootstrap){const params=mcpRecord(context);params&&this.protocolSession?.updateHostContext(params);return}this.post({channel:"lyra-mcp-app",version:1,type:"host-context",context},bootstrap?.frame,bootstrap?.port)}postMcpResponse(requestId,options){return this.protocolSession?.respond(requestId,options)??!1}postMcpNotification(method,params,frameGeneration){return frameGeneration!==this.frameGeneration?!1:this.protocolSession?.notify(method,params)??!1}teardownApp(){return this.protocolSession?.teardownResource()??Promise.resolve(!1)}postToolResult(requestId,options){const value=record(options);if(typeof requestId!="string"||!requestId.trim()||!value)return;const frameGeneration=value.frameGeneration;if(typeof frameGeneration!="number"||!Number.isSafeInteger(frameGeneration)||frameGeneration!==this.frameGeneration)return;const hasResult=Object.prototype.hasOwnProperty.call(value,"result"),hasError=Object.prototype.hasOwnProperty.call(value,"error");hasResult!==hasError&&(hasError&&(typeof value.error!="string"||!value.error.trim())||this.post({channel:"lyra-mcp-app",version:1,type:"tool-result",requestId,...hasResult?{result:value.result}:{},...hasError?{error:value.error}:{}}))}proxyDocument(resource){let policy=resource.resource.csp;if(resource.src){let origin;try{origin=new URL(resource.src,this.ownerDocument.baseURI).origin}catch{}policy={frameDomains:origin?[origin]:[]}}return withCsp(MCP_APP_PROXY_DOCUMENT,policy,!0)}render(){const resource=resolveResource(this.resource);if(!resource)return html`<div part="base"><p part="error">${this.localize("mcpAppUnavailable")}</p></div>`;const fallbackLabel=(!this.hasAttribute("aria-label")&&typeof this.accessibleLabel=="string"?this.accessibleLabel:"")||this.label||resource.resource.title||this.localize("mcpAppLabel"),label=purposeAccessibleLabel(this,fallbackLabel),frameGeneration=this.frameGeneration;return html`<div part="base">
|
|
2
2
|
${this.loaded?nothing:html`<p part="loading">${this.localize("mcpAppLoading")}</p>`}
|
|
3
3
|
${keyed(frameGeneration,html`<iframe
|
|
4
4
|
part="frame"
|
|
@@ -6,9 +6,9 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
6
6
|
sandbox="allow-forms allow-scripts"
|
|
7
7
|
referrerpolicy="no-referrer"
|
|
8
8
|
allow=${permissionPolicy(resource.resource.permissions)}
|
|
9
|
-
src=${resource.src??nothing}
|
|
10
|
-
.srcdoc=${resource.html?withCsp(resource.html,resource.resource.csp):nothing}
|
|
9
|
+
src=${this.protocol==="mcp-apps"?nothing:resource.src??nothing}
|
|
10
|
+
.srcdoc=${this.protocol==="mcp-apps"?this.proxyDocument(resource):resource.html?withCsp(resource.html,resource.resource.csp):nothing}
|
|
11
11
|
style=${styleMap({height:`${this.frameHeight}px`})}
|
|
12
12
|
@load=${event=>this.onLoad(event,frameGeneration,resource)}
|
|
13
13
|
></iframe>`)}
|
|
14
|
-
</div>`}}__decorate([property({attribute:!1})],LyraMcpApp.prototype,"resource",void 0),__decorate([property({converter:heightAttributeConverter})],LyraMcpApp.prototype,"height",void 0),__decorate([property({attribute:"max-height",converter:heightAttributeConverter})],LyraMcpApp.prototype,"maxHeight",void 0),__decorate([property()],LyraMcpApp.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraMcpApp.prototype,"accessibleLabel",void 0),__decorate([state()],LyraMcpApp.prototype,"loaded",void 0),__decorate([state()],LyraMcpApp.prototype,"frameHeight",void 0),__decorate([query("iframe")],LyraMcpApp.prototype,"frame",void 0);export{LyraMcpApp};
|
|
14
|
+
</div>`}}__decorate([property({attribute:!1})],LyraMcpApp.prototype,"resource",void 0),__decorate([property()],LyraMcpApp.prototype,"protocol",void 0),__decorate([property({attribute:!1})],LyraMcpApp.prototype,"hostCapabilities",void 0),__decorate([property({converter:heightAttributeConverter})],LyraMcpApp.prototype,"height",void 0),__decorate([property({attribute:"max-height",converter:heightAttributeConverter})],LyraMcpApp.prototype,"maxHeight",void 0),__decorate([property()],LyraMcpApp.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraMcpApp.prototype,"accessibleLabel",void 0),__decorate([state()],LyraMcpApp.prototype,"loaded",void 0),__decorate([state()],LyraMcpApp.prototype,"frameHeight",void 0),__decorate([query("iframe")],LyraMcpApp.prototype,"frame",void 0);export{LyraMcpApp};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteNumber,finiteRatio,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{formatShortDuration}from"../../../internal/duration.js";import{styles}from"./span-waterfall.styles.js";import{normalizeLyraSpanKind,normalizeLyraSpanStatus}from"../trace-tree/span.js";import{projectLyraSpans}from"../trace-tree/span-projection.js";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_spanKindAgent,LYRA_DEFAULT_spanKindEmbedding,LYRA_DEFAULT_spanKindLlm,LYRA_DEFAULT_spanKindOther,LYRA_DEFAULT_spanKindRetriever,LYRA_DEFAULT_spanKindTool,LYRA_DEFAULT_spanStartedAtOffset,LYRA_DEFAULT_spanWaterfall,LYRA_DEFAULT_spanWaterfallLimit}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_expand,LYRA_DEFAULT_item,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_statusUnknown,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";const SOURCE_QUERY=Object.freeze({search:"",hiddenKinds:Object.freeze([])}),KIND_LABEL_KEY={agent:"spanKindAgent",llm:"spanKindLlm",tool:"spanKindTool",retriever:"spanKindRetriever",embedding:"spanKindEmbedding",other:"spanKindOther"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied",incomplete:"statusIncomplete",unknown:"statusUnknown"},STATUS_TONE={success:"success",error:"danger",denied:"warning",running:"accent",pending:"neutral",incomplete:"neutral",unknown:"neutral"};function niceStep(span,count){if(span<=0)return 1;const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function axisTicks(start,end,count=5){const step=niceStep(end-start,count);if(!Number.isFinite(step)||step<=0)return[start,end];const first=Math.ceil(start/step)*step;if(!Number.isFinite(first))return[start,end];const ticks=[];for(let index=0;index<=count+2;index++){const value=first+index*step;if(!Number.isFinite(value)||value>end+step/2)break;const rounded=Math.round(value/step)*step;Number.isFinite(rounded)&&(ticks.length===0||rounded>ticks[ticks.length-1])&&ticks.push(rounded)}return ticks}class LyraSpanWaterfall extends LyraElement{constructor(){super(...arguments),this._treeSource=void 0,this.sourceVersion=0,this.sourcePaintVersion=0,this.sourceSummaries=new WeakMap,this.sourceControl=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceSpan(value,key),payload:{maxUnits:2e6,maxRowUnits:65536,unitsOf:span=>span.id.length+span.name.length},onChange:()=>{const old=this.sourcePaintVersion++;this.requestUpdate("sourcePaintVersion",old)},accepted:(action,_row,_state,current)=>{!current()||this.treeSource===void 0||action.type==="select"&&this.emit("lr-span-select",{spanId:action.key})}}),this.spans=[],this.activeSpanId=null,this.viewStartMs=null,this.viewEndMs=null,this.withoutAxis=!1,this.focusedId=null,this.sortedActiveSpanId=null,this.sortedCache=[],this.sortedCacheTruncated=!1,this.sortedCacheExtentEndMs=0,this.axisSignature="",this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.onKeyDown=e=>{if(this.treeSource!==void 0||e.currentTarget!==this.renderRoot.querySelector("[role=list]"))return;const view=this.viewWindow(),rows=this.sortedSpans().filter(span=>this.barGeometry(span,view).visible);if(rows.length===0)return;const currentIndex=rows.findIndex(s=>s.id===this.focusedId),idx=currentIndex>=0?currentIndex:0;switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(rows[Math.min(rows.length-1,idx+1)]);break;case"ArrowUp":e.preventDefault(),this.focusRow(rows[Math.max(0,idx-1)]);break;case"Home":e.preventDefault(),this.focusRow(rows[0]);break;case"End":e.preventDefault(),this.focusRow(rows[rows.length-1]);break;case"Enter":case" ":e.preventDefault(),this.selectRow(rows[idx].id);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,expand:LYRA_DEFAULT_expand,item:LYRA_DEFAULT_item,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,spanKindAgent:LYRA_DEFAULT_spanKindAgent,spanKindEmbedding:LYRA_DEFAULT_spanKindEmbedding,spanKindLlm:LYRA_DEFAULT_spanKindLlm,spanKindOther:LYRA_DEFAULT_spanKindOther,spanKindRetriever:LYRA_DEFAULT_spanKindRetriever,spanKindTool:LYRA_DEFAULT_spanKindTool,spanStartedAtOffset:LYRA_DEFAULT_spanStartedAtOffset,spanWaterfall:LYRA_DEFAULT_spanWaterfall,spanWaterfallLimit:LYRA_DEFAULT_spanWaterfallLimit,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusIncomplete:LYRA_DEFAULT_statusIncomplete,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,statusUnknown:LYRA_DEFAULT_statusUnknown,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["spans"])}static{this.identityCollectionProperties=Object.freeze(["spans"])}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.sourceVersion++,this.sourceReveal=void 0,this.sourceWrapper=value===void 0?void 0:this.wrapSource(value),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.sourceControl.reveal(key)}syncSource(force=!1){this.sourceControl?.update(this.sourceWrapper,this.effectiveLocale,force,SOURCE_QUERY)}wrapSource(source){const host=this;return{get revision(){return source.revision},async project(request){const version=host.sourceVersion,owner=host.ownerDocument,owned=()=>host._treeSource===source&&host.sourceVersion===version&&host.ownerDocument===owner&&host.isConnected&&!request.signal.aborted,current=()=>{if(!owned())return!1;const revision=source.revision;return owned()&&revision===request.revision},check=()=>{if(!current())throw new Error("Trace source changed")};check();const project=source.project;check();const result=await project.call(source,request);check();const summary=result.summary;check();const startMs=hierarchyField(summary,"startMs");check();const endMs=hierarchyField(summary,"endMs");if(check(),typeof startMs!="number"||typeof endMs!="number"||!Number.isFinite(startMs)||!Number.isFinite(endMs)||startMs<0||endMs<startMs||!Number.isFinite(endMs-startMs))throw new TypeError("Invalid trace extent");const view=result.rows;check();const count=view.count;check();const hasItemAt="itemAt"in view;check();const itemAt=hasItemAt?view.itemAt:void 0;check();let wrapped;if(typeof itemAt=="function"){const indexed=view;wrapped={count,itemAt(index){check();const method=indexed.itemAt;check();const value=method.call(indexed,index);return check(),value},keyAt(index){check();const method=indexed.keyAt;check();const value=method.call(indexed,index);return check(),value},indexOfKey(key){check();const method=indexed.indexOfKey;check();const value=method.call(indexed,key);return check(),value}}}else{const ranged=view;wrapped={count,async read(range){const active=()=>{if(check(),range.signal.aborted)throw new Error("Trace range changed")};active();const method=ranged.read;active();const value=await method.call(ranged,range);return active(),value},async indexOfKey(key,context){const active=()=>{if(check(),context.signal.aborted)throw new Error("Trace navigation changed")};active();const method=ranged.indexOfKey;active();const value=await method.call(ranged,key,context);return active(),value}}}const state=result.state;check();const total=result.total;check();const focusIndex=result.focusIndex;return check(),host.sourceSummaries.set(wrapped,Object.freeze({startMs,endMs,current})),{state,total,rows:wrapped,...focusIndex===void 0?{}:{focusIndex}}}}}normalizeSourceSpan(value,key){const source=this.treeSource,version=this.sourceVersion,owner=this.ownerDocument,control=this.sourceControl,epoch=control.epoch,projection=control.projection,owned=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceVersion===version&&this.sourceControl===control&&control.epoch===epoch&&control.projection===projection&&!control.loading,accepted=projection?this.sourceSummaries.get(projection.rows):void 0,current=()=>owned()&&!!accepted?.current()&&owned(),field=name=>{if(!current())throw new Error("Trace source changed");const result=hierarchyField(value,name);if(!current())throw new Error("Trace source changed");return result},id=hierarchyKey(field("id"));if(id!==key)throw new TypeError("Trace key mismatch");const startMs=field("startMs"),endMs=field("endMs");if(typeof startMs!="number"||!Number.isFinite(startMs)||startMs<0||endMs!==void 0&&(typeof endMs!="number"||!Number.isFinite(endMs)||endMs<startMs))throw new TypeError("Invalid span timing");return Object.freeze({id,name:hierarchyText(field("name")),kind:normalizeLyraSpanKind(field("kind")),status:normalizeLyraSpanStatus(field("status")),startMs,...endMs===void 0?{}:{endMs}})}requestUpdate(name,oldValue){this._treeSource!==void 0&&name===void 0&&(this.sourceVersion++,this.sourceReveal=void 0,this.syncSource(!0)),super.requestUpdate(name,oldValue)}sourceSummary(){const projection=this.sourceControl.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}updateSourceEffects(){const source=this.treeSource,binding=this.sourceWrapper,version=this.sourceVersion,epoch=this.sourceControl.epoch,owner=this.ownerDocument,projection=this.sourceControl.projection,{error,loading,rowError,rowsObserved}=this.sourceControl,bound=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceWrapper===binding&&this.sourceVersion===version&&this.sourceControl.epoch===epoch,current=()=>bound()&&this.sourceControl.projection===projection&&this.sourceControl.error===error&&this.sourceControl.loading===loading&&this.sourceControl.rowError===rowError&&this.sourceControl.rowsObserved===rowsObserved;if(!current())return;for(const row of this.renderRoot.querySelectorAll("[data-source-key]")){const active=row.dataset.sourceKey===this.activeSpanId;row.setAttribute("aria-current",String(active)),row.toggleAttribute("data-active",active)}const status=error?this.localize("treeSourceError"):loading?this.localize("loading"):this.sourceSummary();if(!current()||this.sourceAnnouncement!==void 0&&status!==this.sourceAnnouncement&&(this.announcements.announcePolite(status),!current()))return;if(rowsObserved){const message=rowError?this.localize("treeSourceError"):"";if(!current()||(this.announcements.transition("source-rows",rowError?"error":"ready",message),!current()))return}this.sourceAnnouncement=status;const key=this.activeSpanId;!key||this.sourceReveal?.[0]===epoch&&this.sourceReveal[1]===key||(this.sourceReveal=[epoch,key],this.sourceControl.whenReady().then(ready=>{ready&&bound()&&this.activeSpanId===key&&this.sourceControl.reveal(key)}))}connectedCallback(){super.connectedCallback(),this.limitAnnouncementInitialized=this.hasUpdated,this.previouslyTruncated=this.sortedCacheTruncated,this.hasUpdated&&(this.observeAxis(),this.fitAxisLabels())}disconnectedCallback(){this.sourceVersion++,this.sourceReveal=void 0,this.sourceAnnouncement=void 0,this.axisObserver?.disconnect(),this.axisObserver=void 0,this.observedAxis=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted(),this.sourceVersion++,this.sourceReveal=void 0,this.sourceAnnouncement=void 0,this.sourceControl.adopted(),this.syncSource(!0)}sortedSpans(){if(this.sortedSource===this.spans&&this.sortedActiveSpanId===this.activeSpanId)return this.sortedCache;this.sortedSource=this.spans,this.sortedActiveSpanId=this.activeSpanId;const projection=projectLyraSpans(this.spans,this.activeSpanId);return this.sortedCacheTruncated=projection.truncated||publicCollectionTruncation(this,"spans")!==void 0,this.sortedCacheExtentEndMs=projection.extentEndMs,this.sortedProjection===projection.spans?this.sortedCache:(this.sortedProjection=projection.spans,this.sortedCache=projection.spans.map((s,i)=>({s,i})).sort((a,b)=>a.s.startMs-b.s.startMs||a.i-b.i).map(x=>x.s),this.sortedCache)}viewWindow(){const projection=this.sourceControl.projection,summary=this.treeSource!==void 0&&projection?this.sourceSummaries.get(projection.rows):void 0;this.treeSource===void 0&&this.sortedSpans();const fallbackStart=summary?.startMs??0,fallbackEnd=summary?.endMs??(this.treeSource===void 0?Math.max(finiteNumber(this.sortedCacheExtentEndMs,0),1):1),start=this.viewStartMs==null?fallbackStart:finiteRange(this.viewStartMs,fallbackStart,0,Number.MAX_SAFE_INTEGER-1),end=this.viewEndMs==null?fallbackEnd:finiteRange(this.viewEndMs,fallbackEnd,0,Number.MAX_SAFE_INTEGER);return{start,end:end>start?end:start+1}}barGeometry(span,view){const endMs=span.endMs??(span.status==="running"?view.end:span.startMs),visible=span.startMs<=view.end&&endMs>=view.start,clampedStart=Math.max(view.start,span.startMs),clampedEnd=Math.min(view.end,Math.max(endMs,span.startMs)),startPct=finiteRatio(clampedStart,view.start,view.end)*100,endPct=finiteRatio(clampedEnd,view.start,view.end)*100;return{startPct,widthPct:Math.max(0,endPct-startPct),visible}}formatDuration(ms){return ms==null||!Number.isFinite(ms)?"":formatShortDuration(this.localize.bind(this),this.effectiveLocale,ms)}projectionLimitText(){const number=getNumberFormat(this.effectiveLocale);return this.localize("spanWaterfallLimit",void 0,{shown:number.format(this.sortedCache.length),total:number.format(publicCollectionTruncation(this,"spans")?.source??this.spans.length)})}focusRow(span){if(!span)return;const previous=this.renderRoot.querySelector('[part="bar"][tabindex="0"]');this.focusedId=span.id,previous?.setAttribute("tabindex","-1");const next=this.renderedBarById(span.id);next?.setAttribute("tabindex","0"),next?.focus()}selectRow(id){this.treeSource!==void 0||!this.isConnected||(this.focusedId=id,this.emit("lr-span-select",{spanId:id}))}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.treeSource===void 0&&(changed.has("treeSource")&&(this.sourceAnnouncement=void 0,this.sourceReveal=void 0,changed.set("spans",void 0)),changed.has("spans")||changed.has("viewStartMs")||changed.has("viewEndMs")||changed.has("activeSpanId"))){const view=this.viewWindow(),ids=new Set(this.sortedSpans().filter(span=>this.barGeometry(span,view).visible).map(span=>span.id));(this.focusedId==null||!ids.has(this.focusedId))&&(this.focusedId=this.activeSpanId&&ids.has(this.activeSpanId)?this.activeSpanId:this.sortedSpans()[0]?.id??null),this.focusedId!==null&&!ids.has(this.focusedId)&&(this.focusedId=this.sortedSpans().find(span=>ids.has(span.id))?.id??null),changed.has("activeSpanId")&&this.activeSpanId&&ids.has(this.activeSpanId)&&(this.focusedId=this.activeSpanId)}}renderedBarById(id){const ownerCss=this.ownerDocument.defaultView?.CSS;return typeof ownerCss?.escape=="function"?this.renderRoot.querySelector(`[data-id="${ownerCss.escape(id)}"]`):Array.from(this.renderRoot.querySelectorAll("[data-id]")).find(element=>element.dataset.id===id)??null}updated(changed){if(super.updated(changed),this.treeSource!==void 0){const version2=this.sourceVersion;if(this.updateSourceEffects(),version2!==this.sourceVersion||this.treeSource===void 0||!this.isConnected)return;this.observeAxis(),this.fitAxisLabels();return}const version=this.sourceVersion,owner=this.ownerDocument,current=()=>this.isConnected&&this.ownerDocument===owner&&this.sourceVersion===version&&this.treeSource===void 0;if(changed.has("activeSpanId")&&this.activeSpanId){const bar=this.renderedBarById(this.activeSpanId);if(bar&&!bar.hidden){const reducedMotion=!bar.ownerDocument.defaultView||prefersReducedMotion(this);bar.scrollIntoView({block:"nearest",behavior:reducedMotion?"auto":"smooth"})}}if(this.limitAnnouncementInitialized&&this.sortedCacheTruncated&&!this.previouslyTruncated){const message=this.projectionLimitText();if(!current()||(this.announcements.announcePolite(message),!current()))return}this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.sortedCacheTruncated,this.observeAxis();const view=this.viewWindow(),axisSignature=`${view.start}|${view.end}|${this.effectiveLocale}`;axisSignature!==this.axisSignature&&(this.axisSignature=axisSignature,this.fitAxisLabels())}observeAxis(){if(!this.isConnected)return;const axis=this.renderRoot.querySelector('[part="axis"]')??void 0;if(axis===this.observedAxis)return;this.axisObserver?.disconnect(),this.observedAxis=axis;const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;if(!axis||!ResizeObserverCtor)return;const observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.axisObserver!==observer||this.fitAxisLabels()});this.axisObserver=observer,observer.observe(axis)}fitAxisLabels(){if(!this.isConnected)return;const axis=this.renderRoot.querySelector('[part="axis"]');if(!axis)return;const ticks=Array.from(axis.querySelectorAll('[part="tick"]')),labels=ticks.map(tick=>tick.querySelector('[part="tick-label"]'));for(const tick of ticks)tick.removeAttribute("data-fit");for(const label of labels)label.removeAttribute("data-collapsed");const axisRect=axis.getBoundingClientRect();if(axisRect.width<=0)return;const rtl=this.ownerDocument.defaultView?.getComputedStyle(axis).direction==="rtl",span=rect=>rtl?{start:-rect.right,end:-rect.left}:{start:rect.left,end:rect.right},axisSpan=span(axisRect),rects=labels.map(label=>label.getBoundingClientRect());ticks.forEach((tick,index)=>{span(rects[index]).end>axisSpan.end+.5&&tick.setAttribute("data-fit","end")});const placed=labels.map(label=>{const{start,end}=span(label.getBoundingClientRect());return{label,start,end}}).sort((a,b)=>a.start-b.start),kept=[];placed.forEach((entry,index)=>{const isTerminal=index===placed.length-1;for(;kept.length>1&&isTerminal&&entry.start<kept[kept.length-1].end;)kept.pop().label.setAttribute("data-collapsed","");const previous=kept[kept.length-1];previous&&entry.start<previous.end?entry.label.setAttribute("data-collapsed",""):kept.push(entry)})}renderAxis(view){const ticks=axisTicks(view.start,view.end);return html`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteNumber,finiteRatio,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{formatShortDuration}from"../../../internal/duration.js";import{styles}from"./span-waterfall.styles.js";import{normalizeLyraSpanKind,normalizeLyraSpanStatus}from"../trace-tree/span.js";import{projectLyraSpans}from"../trace-tree/span-projection.js";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{createHierarchySummarySource,captureHierarchySourceEffects,traceSourceSummary}from"../../../internal/hierarchy-summary-source.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_spanKindAgent,LYRA_DEFAULT_spanKindEmbedding,LYRA_DEFAULT_spanKindLlm,LYRA_DEFAULT_spanKindOther,LYRA_DEFAULT_spanKindRetriever,LYRA_DEFAULT_spanKindTool,LYRA_DEFAULT_spanStartedAtOffset,LYRA_DEFAULT_spanWaterfall,LYRA_DEFAULT_spanWaterfallLimit}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_expand,LYRA_DEFAULT_item,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_statusUnknown,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";const SOURCE_QUERY=Object.freeze({search:"",hiddenKinds:Object.freeze([])}),KIND_LABEL_KEY={agent:"spanKindAgent",llm:"spanKindLlm",tool:"spanKindTool",retriever:"spanKindRetriever",embedding:"spanKindEmbedding",other:"spanKindOther"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied",incomplete:"statusIncomplete",unknown:"statusUnknown"},STATUS_TONE={success:"success",error:"danger",denied:"warning",running:"accent",pending:"neutral",incomplete:"neutral",unknown:"neutral"};function niceStep(span,count){if(span<=0)return 1;const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function axisTicks(start,end,count=5){const step=niceStep(end-start,count);if(!Number.isFinite(step)||step<=0)return[start,end];const first=Math.ceil(start/step)*step;if(!Number.isFinite(first))return[start,end];const ticks=[];for(let index=0;index<=count+2;index++){const value=first+index*step;if(!Number.isFinite(value)||value>end+step/2)break;const rounded=Math.round(value/step)*step;Number.isFinite(rounded)&&(ticks.length===0||rounded>ticks[ticks.length-1])&&ticks.push(rounded)}return ticks}class LyraSpanWaterfall extends LyraElement{constructor(){super(...arguments),this._treeSource=void 0,this.sourceVersion=0,this.sourcePaintVersion=0,this.sourceSummaries=new WeakMap,this.sourceControl=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceSpan(value,key),payload:{maxUnits:2e6,maxRowUnits:65536,unitsOf:span=>span.id.length+span.name.length},onChange:()=>{const old=this.sourcePaintVersion++;this.requestUpdate("sourcePaintVersion",old)},accepted:(action,_row,_state,current)=>{!current()||this.treeSource===void 0||action.type==="select"&&this.emit("lr-span-select",{spanId:action.key})}}),this.spans=[],this.activeSpanId=null,this.viewStartMs=null,this.viewEndMs=null,this.withoutAxis=!1,this.focusedId=null,this.sortedActiveSpanId=null,this.sortedCache=[],this.sortedCacheTruncated=!1,this.sortedCacheExtentEndMs=0,this.axisSignature="",this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.onKeyDown=e=>{if(this.treeSource!==void 0||e.currentTarget!==this.renderRoot.querySelector("[role=list]"))return;const view=this.viewWindow(),rows=this.sortedSpans().filter(span=>this.barGeometry(span,view).visible);if(rows.length===0)return;const currentIndex=rows.findIndex(s=>s.id===this.focusedId),idx=currentIndex>=0?currentIndex:0;switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(rows[Math.min(rows.length-1,idx+1)]);break;case"ArrowUp":e.preventDefault(),this.focusRow(rows[Math.max(0,idx-1)]);break;case"Home":e.preventDefault(),this.focusRow(rows[0]);break;case"End":e.preventDefault(),this.focusRow(rows[rows.length-1]);break;case"Enter":case" ":e.preventDefault(),this.selectRow(rows[idx].id);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,expand:LYRA_DEFAULT_expand,item:LYRA_DEFAULT_item,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,spanKindAgent:LYRA_DEFAULT_spanKindAgent,spanKindEmbedding:LYRA_DEFAULT_spanKindEmbedding,spanKindLlm:LYRA_DEFAULT_spanKindLlm,spanKindOther:LYRA_DEFAULT_spanKindOther,spanKindRetriever:LYRA_DEFAULT_spanKindRetriever,spanKindTool:LYRA_DEFAULT_spanKindTool,spanStartedAtOffset:LYRA_DEFAULT_spanStartedAtOffset,spanWaterfall:LYRA_DEFAULT_spanWaterfall,spanWaterfallLimit:LYRA_DEFAULT_spanWaterfallLimit,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusIncomplete:LYRA_DEFAULT_statusIncomplete,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,statusUnknown:LYRA_DEFAULT_statusUnknown,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["spans"])}static{this.identityCollectionProperties=Object.freeze(["spans"])}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.sourceVersion++,this.sourceReveal=void 0,this.sourceWrapper=value===void 0?void 0:this.wrapSource(value),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.sourceControl.reveal(key)}syncSource(force=!1){this.sourceControl?.update(this.sourceWrapper,this.effectiveLocale,force,SOURCE_QUERY)}wrapSource(source){return createHierarchySummarySource(this,source,{captureBinding:()=>{const version=this.sourceVersion;return()=>this._treeSource===source&&this.sourceVersion===version},summary:traceSourceSummary,accepted:(rows,summary,current)=>this.sourceSummaries.set(rows,Object.freeze({...summary,current})),changedMessage:"Trace source changed",rangeChangedMessage:"Trace range changed",navigationChangedMessage:"Trace navigation changed"})}normalizeSourceSpan(value,key){const source=this.treeSource,version=this.sourceVersion,owner=this.ownerDocument,control=this.sourceControl,epoch=control.epoch,projection=control.projection,owned=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceVersion===version&&this.sourceControl===control&&control.epoch===epoch&&control.projection===projection&&!control.loading,accepted=projection?this.sourceSummaries.get(projection.rows):void 0,current=()=>owned()&&!!accepted?.current()&&owned(),field=name=>{if(!current())throw new Error("Trace source changed");const result=hierarchyField(value,name);if(!current())throw new Error("Trace source changed");return result},id=hierarchyKey(field("id"));if(id!==key)throw new TypeError("Trace key mismatch");const startMs=field("startMs"),endMs=field("endMs");if(typeof startMs!="number"||!Number.isFinite(startMs)||startMs<0||endMs!==void 0&&(typeof endMs!="number"||!Number.isFinite(endMs)||endMs<startMs))throw new TypeError("Invalid span timing");return Object.freeze({id,name:hierarchyText(field("name")),kind:normalizeLyraSpanKind(field("kind")),status:normalizeLyraSpanStatus(field("status")),startMs,...endMs===void 0?{}:{endMs}})}requestUpdate(name,oldValue){this._treeSource!==void 0&&name===void 0&&(this.sourceVersion++,this.sourceReveal=void 0,this.syncSource(!0)),super.requestUpdate(name,oldValue)}sourceSummary(){const projection=this.sourceControl.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}updateSourceEffects(){const source=this.treeSource,binding=this.sourceWrapper,version=this.sourceVersion,{epoch,error,loading,rowError,rowsObserved,bound,current}=captureHierarchySourceEffects(this,this.sourceControl,()=>this.treeSource===source&&this.sourceWrapper===binding&&this.sourceVersion===version);if(!current())return;for(const row of this.renderRoot.querySelectorAll("[data-source-key]")){const active=row.dataset.sourceKey===this.activeSpanId;row.setAttribute("aria-current",String(active)),row.toggleAttribute("data-active",active)}const status=error?this.localize("treeSourceError"):loading?this.localize("loading"):this.sourceSummary();if(!current()||this.sourceAnnouncement!==void 0&&status!==this.sourceAnnouncement&&(this.announcements.announcePolite(status),!current()))return;if(rowsObserved){const message=rowError?this.localize("treeSourceError"):"";if(!current()||(this.announcements.transition("source-rows",rowError?"error":"ready",message),!current()))return}this.sourceAnnouncement=status;const key=this.activeSpanId;!key||this.sourceReveal?.[0]===epoch&&this.sourceReveal[1]===key||(this.sourceReveal=[epoch,key],this.sourceControl.whenReady().then(ready=>{ready&&bound()&&this.activeSpanId===key&&this.sourceControl.reveal(key)}))}connectedCallback(){super.connectedCallback(),this.limitAnnouncementInitialized=this.hasUpdated,this.previouslyTruncated=this.sortedCacheTruncated,this.hasUpdated&&(this.observeAxis(),this.fitAxisLabels())}disconnectedCallback(){this.sourceVersion++,this.sourceReveal=void 0,this.sourceAnnouncement=void 0,this.axisObserver?.disconnect(),this.axisObserver=void 0,this.observedAxis=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted(),this.sourceVersion++,this.sourceReveal=void 0,this.sourceAnnouncement=void 0,this.sourceControl.adopted(),this.syncSource(!0)}sortedSpans(){if(this.sortedSource===this.spans&&this.sortedActiveSpanId===this.activeSpanId)return this.sortedCache;this.sortedSource=this.spans,this.sortedActiveSpanId=this.activeSpanId;const projection=projectLyraSpans(this.spans,this.activeSpanId);return this.sortedCacheTruncated=projection.truncated||publicCollectionTruncation(this,"spans")!==void 0,this.sortedCacheExtentEndMs=projection.extentEndMs,this.sortedProjection===projection.spans?this.sortedCache:(this.sortedProjection=projection.spans,this.sortedCache=projection.spans.map((s,i)=>({s,i})).sort((a,b)=>a.s.startMs-b.s.startMs||a.i-b.i).map(x=>x.s),this.sortedCache)}viewWindow(){const projection=this.sourceControl.projection,summary=this.treeSource!==void 0&&projection?this.sourceSummaries.get(projection.rows):void 0;this.treeSource===void 0&&this.sortedSpans();const fallbackStart=summary?.startMs??0,fallbackEnd=summary?.endMs??(this.treeSource===void 0?Math.max(finiteNumber(this.sortedCacheExtentEndMs,0),1):1),start=this.viewStartMs==null?fallbackStart:finiteRange(this.viewStartMs,fallbackStart,0,Number.MAX_SAFE_INTEGER-1),end=this.viewEndMs==null?fallbackEnd:finiteRange(this.viewEndMs,fallbackEnd,0,Number.MAX_SAFE_INTEGER);return{start,end:end>start?end:start+1}}barGeometry(span,view){const endMs=span.endMs??(span.status==="running"?view.end:span.startMs),visible=span.startMs<=view.end&&endMs>=view.start,clampedStart=Math.max(view.start,span.startMs),clampedEnd=Math.min(view.end,Math.max(endMs,span.startMs)),startPct=finiteRatio(clampedStart,view.start,view.end)*100,endPct=finiteRatio(clampedEnd,view.start,view.end)*100;return{startPct,widthPct:Math.max(0,endPct-startPct),visible}}formatDuration(ms){return ms==null||!Number.isFinite(ms)?"":formatShortDuration(this.localize.bind(this),this.effectiveLocale,ms)}projectionLimitText(){const number=getNumberFormat(this.effectiveLocale);return this.localize("spanWaterfallLimit",void 0,{shown:number.format(this.sortedCache.length),total:number.format(publicCollectionTruncation(this,"spans")?.source??this.spans.length)})}focusRow(span){if(!span)return;const previous=this.renderRoot.querySelector('[part="bar"][tabindex="0"]');this.focusedId=span.id,previous?.setAttribute("tabindex","-1");const next=this.renderedBarById(span.id);next?.setAttribute("tabindex","0"),next?.focus()}selectRow(id){this.treeSource!==void 0||!this.isConnected||(this.focusedId=id,this.emit("lr-span-select",{spanId:id}))}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.treeSource===void 0&&(changed.has("treeSource")&&(this.sourceAnnouncement=void 0,this.sourceReveal=void 0,changed.set("spans",void 0)),changed.has("spans")||changed.has("viewStartMs")||changed.has("viewEndMs")||changed.has("activeSpanId"))){const view=this.viewWindow(),ids=new Set(this.sortedSpans().filter(span=>this.barGeometry(span,view).visible).map(span=>span.id));(this.focusedId==null||!ids.has(this.focusedId))&&(this.focusedId=this.activeSpanId&&ids.has(this.activeSpanId)?this.activeSpanId:this.sortedSpans()[0]?.id??null),this.focusedId!==null&&!ids.has(this.focusedId)&&(this.focusedId=this.sortedSpans().find(span=>ids.has(span.id))?.id??null),changed.has("activeSpanId")&&this.activeSpanId&&ids.has(this.activeSpanId)&&(this.focusedId=this.activeSpanId)}}renderedBarById(id){const ownerCss=this.ownerDocument.defaultView?.CSS;return typeof ownerCss?.escape=="function"?this.renderRoot.querySelector(`[data-id="${ownerCss.escape(id)}"]`):Array.from(this.renderRoot.querySelectorAll("[data-id]")).find(element=>element.dataset.id===id)??null}updated(changed){if(super.updated(changed),this.treeSource!==void 0){const version2=this.sourceVersion;if(this.updateSourceEffects(),version2!==this.sourceVersion||this.treeSource===void 0||!this.isConnected)return;this.observeAxis(),this.fitAxisLabels();return}const version=this.sourceVersion,owner=this.ownerDocument,current=()=>this.isConnected&&this.ownerDocument===owner&&this.sourceVersion===version&&this.treeSource===void 0;if(changed.has("activeSpanId")&&this.activeSpanId){const bar=this.renderedBarById(this.activeSpanId);if(bar&&!bar.hidden){const reducedMotion=!bar.ownerDocument.defaultView||prefersReducedMotion(this);bar.scrollIntoView({block:"nearest",behavior:reducedMotion?"auto":"smooth"})}}if(this.limitAnnouncementInitialized&&this.sortedCacheTruncated&&!this.previouslyTruncated){const message=this.projectionLimitText();if(!current()||(this.announcements.announcePolite(message),!current()))return}this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.sortedCacheTruncated,this.observeAxis();const view=this.viewWindow(),axisSignature=`${view.start}|${view.end}|${this.effectiveLocale}`;axisSignature!==this.axisSignature&&(this.axisSignature=axisSignature,this.fitAxisLabels())}observeAxis(){if(!this.isConnected)return;const axis=this.renderRoot.querySelector('[part="axis"]')??void 0;if(axis===this.observedAxis)return;this.axisObserver?.disconnect(),this.observedAxis=axis;const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;if(!axis||!ResizeObserverCtor)return;const observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.axisObserver!==observer||this.fitAxisLabels()});this.axisObserver=observer,observer.observe(axis)}fitAxisLabels(){if(!this.isConnected)return;const axis=this.renderRoot.querySelector('[part="axis"]');if(!axis)return;const ticks=Array.from(axis.querySelectorAll('[part="tick"]')),labels=ticks.map(tick=>tick.querySelector('[part="tick-label"]'));for(const tick of ticks)tick.removeAttribute("data-fit");for(const label of labels)label.removeAttribute("data-collapsed");const axisRect=axis.getBoundingClientRect();if(axisRect.width<=0)return;const rtl=this.ownerDocument.defaultView?.getComputedStyle(axis).direction==="rtl",span=rect=>rtl?{start:-rect.right,end:-rect.left}:{start:rect.left,end:rect.right},axisSpan=span(axisRect),rects=labels.map(label=>label.getBoundingClientRect());ticks.forEach((tick,index)=>{span(rects[index]).end>axisSpan.end+.5&&tick.setAttribute("data-fit","end")});const placed=labels.map(label=>{const{start,end}=span(label.getBoundingClientRect());return{label,start,end}}).sort((a,b)=>a.start-b.start),kept=[];placed.forEach((entry,index)=>{const isTerminal=index===placed.length-1;for(;kept.length>1&&isTerminal&&entry.start<kept[kept.length-1].end;)kept.pop().label.setAttribute("data-collapsed","");const previous=kept[kept.length-1];previous&&entry.start<previous.end?entry.label.setAttribute("data-collapsed",""):kept.push(entry)})}renderAxis(view){const ticks=axisTicks(view.start,view.end);return html`
|
|
2
2
|
<div part="axis" aria-hidden="true">
|
|
3
3
|
${ticks.map(t=>{const pct=finiteRatio(t,view.start,view.end)*100;return pct<0||pct>100?nothing:html`<span
|
|
4
4
|
part="tick"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{readOwnDataValue}from"../../../internal/data-descriptors.js";import{finiteCount}from"../../../internal/numbers.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,svg,nothing}from"lit";import{repeat}from"lit/directives/repeat.js";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{chevronIcon}from"../../../internal/icons.js";import{styles}from"./task-list.styles.js";import{LYRA_DEFAULT_taskListCompletedOfTotal,LYRA_DEFAULT_taskListLabel,LYRA_DEFAULT_taskListLimit,LYRA_DEFAULT_taskListStepCompletedAnnounce,LYRA_DEFAULT_taskListStepFailedAnnounce,LYRA_DEFAULT_taskListStepIncompleteAnnounce,LYRA_DEFAULT_taskListStepStartedAnnounce}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_item,LYRA_DEFAULT_items,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_treeNodeMoved,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";function normalizeTaskStatus(value){return value==="running"||value==="success"||value==="error"||value==="incomplete"?value:"pending"}const DEEP_NESTING_WARNING_KEY="lyra-task-list-nesting-depth",DEEP_NESTING_WARNING="<lr-task-list>: task nesting deeper than one level is ignored.",MAX_RENDERED_TASKS=500,canonicalTaskArrays=new WeakSet;function validTaskItems(value){return value&&typeof value=="object"&&canonicalTaskArrays.has(value)?value:[]}function isTaskArray(value){try{return Array.isArray(value)}catch{return!1}}function isTaskRecord(value){try{return value!==null&&typeof value=="object"&&!Array.isArray(value)}catch{return!1}}function taskArrayLength(values){const value=readOwnDataValue(values,"length");return finiteCount(typeof value=="number"?value:0,0)}function projectTaskItems(source){let childBudget=1e4,valid=!0,deep=!1,truncated=!1;const copy=(values,depth)=>{const result=[];try{if(!isTaskArray(values))return result;const length=taskArrayLength(values),count=Math.min(length,depth===0?1e4:childBudget);count<length&&(truncated=!0,valid=!1),depth>0&&(childBudget-=count);for(let index=0;index<count;index++){const value=readOwnDataValue(values,String(index));if(!isTaskRecord(value)){valid=!1;continue}const id=readOwnDataValue(value,"id");if(typeof id!="string"||!id.trim()){valid=!1;continue}const label=readOwnDataValue(value,"label"),detail=readOwnDataValue(value,"detail"),children=readOwnDataValue(value,"children");depth>0&&isTaskArray(children)&&taskArrayLength(children)>0&&(deep=!0);const item={id,label:typeof label=="string"?label:"",status:normalizeTaskStatus(readOwnDataValue(value,"status")),...typeof detail=="string"?{detail}:{},...depth===0&&isTaskArray(children)?{children:copy(children,1)}:{}};result.push(Object.freeze(item))}}catch{valid=!1}return canonicalTaskArrays.add(result),Object.freeze(result),result},items=copy(source,0),flat=[];let completed=0,unique=!0;const ids=new Set;for(const item of items)item.status==="success"&&completed++,flat.push(item,...item.children??[]);for(const item of flat)ids.has(item.id)&&(unique=!1),ids.add(item.id);return{source,items,flat,valid,unique,completed,deep,truncated}}const SOURCE_QUERY=Object.freeze({search:"",hiddenKinds:Object.freeze([])}),ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
1
|
+
import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{createHierarchySummarySource,captureHierarchySourceEffects}from"../../../internal/hierarchy-summary-source.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{readOwnDataValue}from"../../../internal/data-descriptors.js";import{finiteCount}from"../../../internal/numbers.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,svg,nothing}from"lit";import{repeat}from"lit/directives/repeat.js";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{chevronIcon}from"../../../internal/icons.js";import{styles}from"./task-list.styles.js";import{LYRA_DEFAULT_taskListCompletedOfTotal,LYRA_DEFAULT_taskListLabel,LYRA_DEFAULT_taskListLimit,LYRA_DEFAULT_taskListStepCompletedAnnounce,LYRA_DEFAULT_taskListStepFailedAnnounce,LYRA_DEFAULT_taskListStepIncompleteAnnounce,LYRA_DEFAULT_taskListStepStartedAnnounce}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_item,LYRA_DEFAULT_items,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_treeNodeMoved,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";function normalizeTaskStatus(value){return value==="running"||value==="success"||value==="error"||value==="incomplete"?value:"pending"}const DEEP_NESTING_WARNING_KEY="lyra-task-list-nesting-depth",DEEP_NESTING_WARNING="<lr-task-list>: task nesting deeper than one level is ignored.",MAX_RENDERED_TASKS=500,canonicalTaskArrays=new WeakSet;function validTaskItems(value){return value&&typeof value=="object"&&canonicalTaskArrays.has(value)?value:[]}function isTaskArray(value){try{return Array.isArray(value)}catch{return!1}}function isTaskRecord(value){try{return value!==null&&typeof value=="object"&&!Array.isArray(value)}catch{return!1}}function taskArrayLength(values){const value=readOwnDataValue(values,"length");return finiteCount(typeof value=="number"?value:0,0)}function projectTaskItems(source){let childBudget=1e4,valid=!0,deep=!1,truncated=!1;const copy=(values,depth)=>{const result=[];try{if(!isTaskArray(values))return result;const length=taskArrayLength(values),count=Math.min(length,depth===0?1e4:childBudget);count<length&&(truncated=!0,valid=!1),depth>0&&(childBudget-=count);for(let index=0;index<count;index++){const value=readOwnDataValue(values,String(index));if(!isTaskRecord(value)){valid=!1;continue}const id=readOwnDataValue(value,"id");if(typeof id!="string"||!id.trim()){valid=!1;continue}const label=readOwnDataValue(value,"label"),detail=readOwnDataValue(value,"detail"),children=readOwnDataValue(value,"children");depth>0&&isTaskArray(children)&&taskArrayLength(children)>0&&(deep=!0);const item={id,label:typeof label=="string"?label:"",status:normalizeTaskStatus(readOwnDataValue(value,"status")),...typeof detail=="string"?{detail}:{},...depth===0&&isTaskArray(children)?{children:copy(children,1)}:{}};result.push(Object.freeze(item))}}catch{valid=!1}return canonicalTaskArrays.add(result),Object.freeze(result),result},items=copy(source,0),flat=[];let completed=0,unique=!0;const ids=new Set;for(const item of items)item.status==="success"&&completed++,flat.push(item,...item.children??[]);for(const item of flat)ids.has(item.id)&&(unique=!1),ids.add(item.id);return{source,items,flat,valid,unique,completed,deep,truncated}}const SOURCE_QUERY=Object.freeze({search:"",hiddenKinds:Object.freeze([])}),ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -15,7 +15,7 @@ import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hi
|
|
|
15
15
|
<circle cx="12" cy="12" r="9"></circle>
|
|
16
16
|
<line x1="9" y1="9" x2="15" y2="15"></line>
|
|
17
17
|
<line x1="15" y1="9" x2="9" y2="15"></line>
|
|
18
|
-
`)}function incompleteIcon(){return icon(svg`<circle cx="12" cy="12" r="9"></circle><line x1="8" y1="12" x2="16" y2="12"></line>`)}const STATUS_ICON={pending:pendingIcon,running:runningIcon,success:successIcon,error:errorIcon,incomplete:incompleteIcon},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",incomplete:"statusIncomplete"};class LyraTaskList extends LyraElement{constructor(){super(...arguments),this._treeSource=void 0,this.sourceVersion=0,this.sourcePaintVersion=0,this.sourceSummaries=new WeakMap,this.sourceControl=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceTask(value,key),payload:{maxUnits:2e6,maxRowUnits:65536,unitsOf:item=>item.id.length+item.label.length+(item.detail?.length??0)},onChange:()=>{const old=this.sourcePaintVersion++;this.requestUpdate("sourcePaintVersion",old)},accepted:()=>{}}),this.items=[],this.maxNodes=500,this.reorderable=!1,this.headingLevel="none",this.collapsed=!1,this.withoutCollapse=!1,this.size="m",this.frame="card",this.headerId=nextId("task-list-header"),this.bodyId=nextId("task-list-body"),this.isMounting=!0,this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.previouslyTruncated=!1,this.renderedTasksTruncated=!1,this.previousStatusById=new Map,this.pendingFocusId=null,this.toggle=()=>{if(this.withoutCollapse)return;const expanded=this.collapsed,version=this.sourceVersion,owner=this.ownerDocument;this.emit("lr-toggle-request",{expanded},{cancelable:!0}).defaultPrevented||!this.isConnected||this.ownerDocument!==owner||this.sourceVersion!==version||this.withoutCollapse||this.collapsed!==expanded||(this.collapsed=!expanded,this.emit("lr-toggle",{expanded}))}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,item:LYRA_DEFAULT_item,items:LYRA_DEFAULT_items,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,statusError:LYRA_DEFAULT_statusError,statusIncomplete:LYRA_DEFAULT_statusIncomplete,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,taskListCompletedOfTotal:LYRA_DEFAULT_taskListCompletedOfTotal,taskListLabel:LYRA_DEFAULT_taskListLabel,taskListLimit:LYRA_DEFAULT_taskListLimit,taskListStepCompletedAnnounce:LYRA_DEFAULT_taskListStepCompletedAnnounce,taskListStepFailedAnnounce:LYRA_DEFAULT_taskListStepFailedAnnounce,taskListStepIncompleteAnnounce:LYRA_DEFAULT_taskListStepIncompleteAnnounce,taskListStepStartedAnnounce:LYRA_DEFAULT_taskListStepStartedAnnounce,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["items"])}static{this.identityCollectionProperties=Object.freeze(["items"])}static{this.styles=[LyraElement.styles,srOnly,hierarchySourceStyles,styles]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.sourceVersion++,this.clearPendingReorder(),this.previousStatusById.clear(),this.sourceWrapper=value===void 0?void 0:this.wrapSource(value),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.sourceControl.reveal(key)}syncSource(force=!1){this.sourceControl?.update(this.sourceWrapper,this.effectiveLocale,force,SOURCE_QUERY)}wrapSource(source){const host=this;return{get revision(){return source.revision},async project(request){const version=host.sourceVersion,owner=host.ownerDocument,owned=()=>host._treeSource===source&&host.sourceVersion===version&&host.ownerDocument===owner&&host.isConnected&&!request.signal.aborted,current=()=>{if(!owned())return!1;const revision=source.revision;return owned()&&revision===request.revision},check=()=>{if(!current())throw new Error("Task source changed")};check();const project=source.project;check();const result=await project.call(source,request);check();const summary=result.summary;check();const taskTotal=hierarchyField(summary,"total");check();const completed=hierarchyField(summary,"completed");if(check(),typeof taskTotal!="number"||typeof completed!="number"||!Number.isSafeInteger(taskTotal)||!Number.isSafeInteger(completed)||taskTotal<0||completed<0||completed>taskTotal)throw new TypeError("Invalid task summary");const validateRow=value=>{const copy={};for(const name of["key","parentKey","level","position","setSize","childCount","expanded","selected","disabled","selectionState","value"])check(),copy[name]=hierarchyField(value,name),check();const{level,parentKey,childCount}=copy;if(!(level===1&&parentKey===null||level===2&&typeof parentKey=="string"&&parentKey.length>0&&childCount===0))throw new TypeError("Invalid task depth");return Object.freeze(copy)},view=result.rows;check();const count=view.count;check();const hasItemAt="itemAt"in view;check();const itemAt=hasItemAt?view.itemAt:void 0;check();let wrapped;if(typeof itemAt=="function"){const indexed=view;wrapped={count,itemAt(index){check();const method=indexed.itemAt;check();const value=method.call(indexed,index);return check(),validateRow(value)},keyAt(index){check();const method=indexed.keyAt;check();const value=method.call(indexed,index);return check(),value},indexOfKey(key){check();const method=indexed.indexOfKey;check();const value=method.call(indexed,key);return check(),value}}}else{const ranged=view;wrapped={count,async read(range){const active=()=>{if(check(),range.signal.aborted)throw new Error("Task range changed")};active();const method=ranged.read;active();const value=await method.call(ranged,range);active();const length=hierarchyField(value,"length");if(active(),!Array.isArray(value)||typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>range.limit)throw new TypeError("Invalid task range");const rows=[];for(let index=0;index<length;index++){active();const row=hierarchyField(value,String(index));active(),rows.push(validateRow(row))}return active(),rows},async indexOfKey(key,context){const active=()=>{if(check(),context.signal.aborted)throw new Error("Task navigation changed")};active();const method=ranged.indexOfKey;active();const value=await method.call(ranged,key,context);return active(),value}}}const state=result.state;check();const total=result.total;if(check(),typeof total!="number"||taskTotal>total)throw new TypeError("Invalid task summary total");const focusIndex=result.focusIndex;return check(),host.sourceSummaries.set(wrapped,Object.freeze({total:taskTotal,completed,current})),{state,total,rows:wrapped,...focusIndex===void 0?{}:{focusIndex}}}}}normalizeSourceTask(value,key){const source=this.treeSource,version=this.sourceVersion,owner=this.ownerDocument,control=this.sourceControl,epoch=control.epoch,projection=control.projection,owned=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceVersion===version&&this.sourceControl===control&&control.epoch===epoch&&control.projection===projection&&!control.loading,accepted=projection?this.sourceSummaries.get(projection.rows):void 0,current=()=>owned()&&!!accepted?.current()&&owned(),field=name=>{if(!current())throw new Error("Task source changed");const result=hierarchyField(value,name);if(!current())throw new Error("Task source changed");return result},id=hierarchyKey(field("id"));if(id!==key)throw new TypeError("Task key mismatch");const label=hierarchyText(field("label")),status=normalizeTaskStatus(field("status")),detail=field("detail");return Object.freeze({id,label,status,...detail===void 0?{}:{detail:hierarchyText(detail)}})}get effectiveMaxNodes(){return Math.max(1,Math.min(5e3,finiteCount(this.maxNodes,MAX_RENDERED_TASKS)))}taskModel(){return this.taskProjection?.source!==this.items&&(this.taskProjection=projectTaskItems(this.items)),this.taskProjection}visibleTaskItems(){const model=this.taskModel(),limit=this.effectiveMaxNodes;if(this.renderedProjection?.model!==model||this.renderedProjection.limit!==limit){const items=this.renderedTaskItems(model.items);this.renderedProjection={model,limit,items,truncated:this.renderedTasksTruncated}}return this.renderedTasksTruncated=this.renderedProjection.truncated||model.truncated||!!publicCollectionTruncation(this,"items"),this.renderedProjection.items}requestUpdate(...args){this._treeSource!==void 0&&args[0]===void 0&&(this.sourceVersion++,this.syncSource(!0)),this._treeSource===void 0&&args[0]==="items"&&this.taskProjection?.source!==this.items&&(this.taskProjection=void 0,this.taskModel()),super.requestUpdate(...args)}sourceSummary(){const projection=this.sourceControl.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}updateSourceEffects(){const source=this.treeSource,binding=this.sourceWrapper,version=this.sourceVersion,epoch=this.sourceControl.epoch,owner=this.ownerDocument,projection=this.sourceControl.projection,{error,loading,rowError,rowsObserved}=this.sourceControl,bound=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceWrapper===binding&&this.sourceVersion===version&&this.sourceControl.epoch===epoch,current=()=>bound()&&this.sourceControl.projection===projection&&this.sourceControl.error===error&&this.sourceControl.loading===loading&&this.sourceControl.rowError===rowError&&this.sourceControl.rowsObserved===rowsObserved;if(!current())return;const status=error?this.localize("treeSourceError"):loading?this.localize("loading"):this.sourceSummary();if(current()&&!(this.sourceAnnouncement!==void 0&&status!==this.sourceAnnouncement&&(this.limitAnnouncements.announcePolite(status),!current()))){if(rowsObserved){const message=rowError?this.localize("treeSourceError"):"";if(!current()||(this.limitAnnouncements.transition("source-rows",rowError?"error":"ready",message),!current()))return}this.sourceAnnouncement=status}}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.treeSource!==void 0){this.clearPendingReorder();return}changed.has("reorderable")&&!this.reorderable&&this.clearPendingReorder(),changed.has("items")&&(this.taskModel().deep&&devWarnOnce(DEEP_NESTING_WARNING_KEY,DEEP_NESTING_WARNING),this.capturePendingReorderFocus())}updated(changed){super.updated(changed);const wasMounting=this.isMounting||!this.isConnected;if(this.isMounting=!this.isConnected,this.treeSource!==void 0){this.updateSourceEffects();return}changed.has("items")&&(this.diffAndAnnounce(wasMounting),this.confirmPendingReorder()),!wasMounting&&this.renderedTasksTruncated&&!this.previouslyTruncated&&this.limitAnnouncements.announcePolite(this.localize("taskListLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(this.effectiveMaxNodes)})),this.previouslyTruncated=this.renderedTasksTruncated}disconnectedCallback(){this.sourceVersion++,this.sourceAnnouncement=void 0,super.disconnectedCallback(),this.isMounting=!0,this.previousStatusById.clear(),this.clearPendingReorder()}connectedCallback(){const reconnecting=this.hasUpdated;this.isMounting=!0,this.previousStatusById.clear(),super.connectedCallback(),reconnecting&&this.requestUpdate("items")}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncements.adopted(),this.sourceVersion++,this.sourceAnnouncement=void 0,this.sourceControl.adopted(),this.syncSource(!0)}renderedTaskItems(items){const rendered=[];let remaining=this.effectiveMaxNodes,truncated=!1;for(const item of items){if(remaining===0){truncated=!0;break}remaining--;const children=validTaskItems(item.children),visibleChildren=children.slice(0,remaining);canonicalTaskArrays.add(visibleChildren),remaining-=visibleChildren.length,visibleChildren.length<children.length&&(truncated=!0),rendered.push(visibleChildren.length===children.length?item:{...item,children:visibleChildren})}return this.renderedTasksTruncated=truncated,rendered}diffAndAnnounce(firstSight){const region=this.liveRegion,nextMap=new Map;for(const item of this.taskModel().flat){const status=normalizeTaskStatus(item.status);if(nextMap.set(item.id,status),!firstSight&®ion){const previous=this.previousStatusById.get(item.id);previous!==void 0&&previous!==status&&(status==="running"?(region.mode="polite",region.announce(this.localize("taskListStepStartedAnnounce",void 0,{label:item.label}),{force:!0})):status==="success"?(region.mode="polite",region.announce(this.localize("taskListStepCompletedAnnounce",void 0,{label:item.label}),{force:!0})):status==="error"?(region.mode="assertive",region.announce(this.localize("taskListStepFailedAnnounce",void 0,{label:item.label}),{force:!0})):status==="incomplete"&&(region.mode="polite",region.announce(this.localize("taskListStepIncompleteAnnounce",void 0,{label:item.label,status:this.localize("statusIncomplete")}),{force:!0})))}}this.previousStatusById=nextMap}idsAreUnique(){return this.taskModel().unique}canReorderItems(){if(this.treeSource!==void 0)return!1;const model=this.taskModel();return this.reorderable&&model.valid&&model.unique}siblingItems(parentId){return parentId===null?this.taskModel().items:this.taskModel().items.find(item=>item.id===parentId)?.children}requestReorder(item,parentId,delta){if(!this.canReorderItems())return;const siblings=this.siblingItems(parentId);if(!siblings)return;const fromIndex=siblings.findIndex(candidate=>candidate.id===item.id),toIndex=fromIndex+delta;fromIndex<0||toIndex<0||toIndex>=siblings.length||(this.pendingReorder={id:item.id,parentId,originalSiblingIds:siblings.map(candidate=>candidate.id),targetSiblingId:siblings[toIndex].id,fromIndex,toIndex},this.pendingFocusId=null,this.emit("lr-reorder",{taskId:item.id,parentTaskId:parentId,fromIndex,toIndex}))}onItemKeyDown(event,item,parentId){this.treeSource!==void 0||!event.currentTarget?.isConnected||event.composedPath()[0]!==event.currentTarget||!this.canReorderItems()||!(event.ctrlKey||event.metaKey)||event.key!=="ArrowUp"&&event.key!=="ArrowDown"||(event.preventDefault(),this.requestReorder(item,parentId,event.key==="ArrowDown"?1:-1))}capturePendingReorderFocus(){const pending=this.pendingReorder;if(!pending)return;const active=shadowFocusTarget(this);this.pendingFocusId=active instanceof HTMLElement&&active.getAttribute("part")==="item"&&active.dataset.id===pending.id?pending.id:null}confirmPendingReorder(){const pending=this.pendingReorder;if(!pending)return;const siblings=this.siblingItems(pending.parentId);if(!siblings||!this.idsAreUnique()){this.clearPendingReorder();return}const siblingIds=siblings.map(item=>item.id);if(!(siblingIds.length!==pending.originalSiblingIds.length||siblingIds.some((id,index)=>id!==pending.originalSiblingIds[index])))return;this.pendingReorder=void 0;const restoreFocus=this.pendingFocusId===pending.id;if(this.pendingFocusId=null,siblingIds[pending.toIndex]!==pending.id||siblingIds[pending.fromIndex]!==pending.targetSiblingId)return;const moved=siblings[pending.toIndex],region=this.liveRegion;region&&(region.mode="polite",region.announce(this.localize("treeNodeMoved",void 0,{label:moved.label,index:getNumberFormat(this.effectiveLocale).format(pending.toIndex+1),total:getNumberFormat(this.effectiveLocale).format(siblings.length)}),{force:!0})),restoreFocus&&this.focusItem(pending.id)}focusItem(id){[...this.shadowRoot?.querySelectorAll('[part="item"]')??[]].find(candidate=>candidate.dataset.id===id)?.focus()}clearPendingReorder(){this.pendingReorder=void 0,this.pendingFocusId=null}renderItem(item,depth,parentId,canReorder){const status=normalizeTaskStatus(item.status),children=depth===0?validTaskItems(item.children):[],hasChildren=children.length>0;return html`
|
|
18
|
+
`)}function incompleteIcon(){return icon(svg`<circle cx="12" cy="12" r="9"></circle><line x1="8" y1="12" x2="16" y2="12"></line>`)}const STATUS_ICON={pending:pendingIcon,running:runningIcon,success:successIcon,error:errorIcon,incomplete:incompleteIcon},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",incomplete:"statusIncomplete"};class LyraTaskList extends LyraElement{constructor(){super(...arguments),this._treeSource=void 0,this.sourceVersion=0,this.sourcePaintVersion=0,this.sourceSummaries=new WeakMap,this.sourceControl=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceTask(value,key),payload:{maxUnits:2e6,maxRowUnits:65536,unitsOf:item=>item.id.length+item.label.length+(item.detail?.length??0)},onChange:()=>{const old=this.sourcePaintVersion++;this.requestUpdate("sourcePaintVersion",old)},accepted:()=>{}}),this.items=[],this.maxNodes=500,this.reorderable=!1,this.headingLevel="none",this.collapsed=!1,this.withoutCollapse=!1,this.size="m",this.frame="card",this.headerId=nextId("task-list-header"),this.bodyId=nextId("task-list-body"),this.isMounting=!0,this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.previouslyTruncated=!1,this.renderedTasksTruncated=!1,this.previousStatusById=new Map,this.pendingFocusId=null,this.toggle=()=>{if(this.withoutCollapse)return;const expanded=this.collapsed,version=this.sourceVersion,owner=this.ownerDocument;this.emit("lr-toggle-request",{expanded},{cancelable:!0}).defaultPrevented||!this.isConnected||this.ownerDocument!==owner||this.sourceVersion!==version||this.withoutCollapse||this.collapsed!==expanded||(this.collapsed=!expanded,this.emit("lr-toggle",{expanded}))}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,item:LYRA_DEFAULT_item,items:LYRA_DEFAULT_items,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,statusError:LYRA_DEFAULT_statusError,statusIncomplete:LYRA_DEFAULT_statusIncomplete,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,taskListCompletedOfTotal:LYRA_DEFAULT_taskListCompletedOfTotal,taskListLabel:LYRA_DEFAULT_taskListLabel,taskListLimit:LYRA_DEFAULT_taskListLimit,taskListStepCompletedAnnounce:LYRA_DEFAULT_taskListStepCompletedAnnounce,taskListStepFailedAnnounce:LYRA_DEFAULT_taskListStepFailedAnnounce,taskListStepIncompleteAnnounce:LYRA_DEFAULT_taskListStepIncompleteAnnounce,taskListStepStartedAnnounce:LYRA_DEFAULT_taskListStepStartedAnnounce,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["items"])}static{this.identityCollectionProperties=Object.freeze(["items"])}static{this.styles=[LyraElement.styles,srOnly,hierarchySourceStyles,styles]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.sourceVersion++,this.clearPendingReorder(),this.previousStatusById.clear(),this.sourceWrapper=value===void 0?void 0:this.wrapSource(value),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.sourceControl.reveal(key)}syncSource(force=!1){this.sourceControl?.update(this.sourceWrapper,this.effectiveLocale,force,SOURCE_QUERY)}wrapSource(source){return createHierarchySummarySource(this,source,{captureBinding:()=>{const version=this.sourceVersion;return()=>this._treeSource===source&&this.sourceVersion===version},summary:(value,check)=>{const total=hierarchyField(value,"total");check();const completed=hierarchyField(value,"completed");if(check(),typeof total!="number"||typeof completed!="number"||!Number.isSafeInteger(total)||!Number.isSafeInteger(completed)||total<0||completed<0||completed>total)throw new TypeError("Invalid task summary");return{total,completed}},row:(value,check)=>{const copy={};for(const name of["key","parentKey","level","position","setSize","childCount","expanded","selected","disabled","selectionState","value"])check(),copy[name]=hierarchyField(value,name),check();const{level,parentKey,childCount}=copy;if(!(level===1&&parentKey===null||level===2&&typeof parentKey=="string"&&parentKey.length>0&&childCount===0))throw new TypeError("Invalid task depth");return Object.freeze(copy)},range:(value,range,active,validateRow)=>{const length=hierarchyField(value,"length");if(active(),!Array.isArray(value)||typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>range.limit)throw new TypeError("Invalid task range");const rows=[];for(let index=0;index<length;index++){active();const row=hierarchyField(value,String(index));active(),rows.push(validateRow(row))}return active(),rows},total:(summary,total)=>{if(typeof total!="number"||summary.total>total)throw new TypeError("Invalid task summary total")},accepted:(rows,summary,current)=>this.sourceSummaries.set(rows,Object.freeze({...summary,current})),changedMessage:"Task source changed",rangeChangedMessage:"Task range changed",navigationChangedMessage:"Task navigation changed"})}normalizeSourceTask(value,key){const source=this.treeSource,version=this.sourceVersion,owner=this.ownerDocument,control=this.sourceControl,epoch=control.epoch,projection=control.projection,owned=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceVersion===version&&this.sourceControl===control&&control.epoch===epoch&&control.projection===projection&&!control.loading,accepted=projection?this.sourceSummaries.get(projection.rows):void 0,current=()=>owned()&&!!accepted?.current()&&owned(),field=name=>{if(!current())throw new Error("Task source changed");const result=hierarchyField(value,name);if(!current())throw new Error("Task source changed");return result},id=hierarchyKey(field("id"));if(id!==key)throw new TypeError("Task key mismatch");const label=hierarchyText(field("label")),status=normalizeTaskStatus(field("status")),detail=field("detail");return Object.freeze({id,label,status,...detail===void 0?{}:{detail:hierarchyText(detail)}})}get effectiveMaxNodes(){return Math.max(1,Math.min(5e3,finiteCount(this.maxNodes,MAX_RENDERED_TASKS)))}taskModel(){return this.taskProjection?.source!==this.items&&(this.taskProjection=projectTaskItems(this.items)),this.taskProjection}visibleTaskItems(){const model=this.taskModel(),limit=this.effectiveMaxNodes;if(this.renderedProjection?.model!==model||this.renderedProjection.limit!==limit){const items=this.renderedTaskItems(model.items);this.renderedProjection={model,limit,items,truncated:this.renderedTasksTruncated}}return this.renderedTasksTruncated=this.renderedProjection.truncated||model.truncated||!!publicCollectionTruncation(this,"items"),this.renderedProjection.items}requestUpdate(...args){this._treeSource!==void 0&&args[0]===void 0&&(this.sourceVersion++,this.syncSource(!0)),this._treeSource===void 0&&args[0]==="items"&&this.taskProjection?.source!==this.items&&(this.taskProjection=void 0,this.taskModel()),super.requestUpdate(...args)}sourceSummary(){const projection=this.sourceControl.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}updateSourceEffects(){const source=this.treeSource,binding=this.sourceWrapper,version=this.sourceVersion,{error,loading,rowError,rowsObserved,current}=captureHierarchySourceEffects(this,this.sourceControl,()=>this.treeSource===source&&this.sourceWrapper===binding&&this.sourceVersion===version);if(!current())return;const status=error?this.localize("treeSourceError"):loading?this.localize("loading"):this.sourceSummary();if(current()&&!(this.sourceAnnouncement!==void 0&&status!==this.sourceAnnouncement&&(this.limitAnnouncements.announcePolite(status),!current()))){if(rowsObserved){const message=rowError?this.localize("treeSourceError"):"";if(!current()||(this.limitAnnouncements.transition("source-rows",rowError?"error":"ready",message),!current()))return}this.sourceAnnouncement=status}}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.treeSource!==void 0){this.clearPendingReorder();return}changed.has("reorderable")&&!this.reorderable&&this.clearPendingReorder(),changed.has("items")&&(this.taskModel().deep&&devWarnOnce(DEEP_NESTING_WARNING_KEY,DEEP_NESTING_WARNING),this.capturePendingReorderFocus())}updated(changed){super.updated(changed);const wasMounting=this.isMounting||!this.isConnected;if(this.isMounting=!this.isConnected,this.treeSource!==void 0){this.updateSourceEffects();return}changed.has("items")&&(this.diffAndAnnounce(wasMounting),this.confirmPendingReorder()),!wasMounting&&this.renderedTasksTruncated&&!this.previouslyTruncated&&this.limitAnnouncements.announcePolite(this.localize("taskListLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(this.effectiveMaxNodes)})),this.previouslyTruncated=this.renderedTasksTruncated}disconnectedCallback(){this.sourceVersion++,this.sourceAnnouncement=void 0,super.disconnectedCallback(),this.isMounting=!0,this.previousStatusById.clear(),this.clearPendingReorder()}connectedCallback(){const reconnecting=this.hasUpdated;this.isMounting=!0,this.previousStatusById.clear(),super.connectedCallback(),reconnecting&&this.requestUpdate("items")}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncements.adopted(),this.sourceVersion++,this.sourceAnnouncement=void 0,this.sourceControl.adopted(),this.syncSource(!0)}renderedTaskItems(items){const rendered=[];let remaining=this.effectiveMaxNodes,truncated=!1;for(const item of items){if(remaining===0){truncated=!0;break}remaining--;const children=validTaskItems(item.children),visibleChildren=children.slice(0,remaining);canonicalTaskArrays.add(visibleChildren),remaining-=visibleChildren.length,visibleChildren.length<children.length&&(truncated=!0),rendered.push(visibleChildren.length===children.length?item:{...item,children:visibleChildren})}return this.renderedTasksTruncated=truncated,rendered}diffAndAnnounce(firstSight){const region=this.liveRegion,nextMap=new Map;for(const item of this.taskModel().flat){const status=normalizeTaskStatus(item.status);if(nextMap.set(item.id,status),!firstSight&®ion){const previous=this.previousStatusById.get(item.id);previous!==void 0&&previous!==status&&(status==="running"?(region.mode="polite",region.announce(this.localize("taskListStepStartedAnnounce",void 0,{label:item.label}),{force:!0})):status==="success"?(region.mode="polite",region.announce(this.localize("taskListStepCompletedAnnounce",void 0,{label:item.label}),{force:!0})):status==="error"?(region.mode="assertive",region.announce(this.localize("taskListStepFailedAnnounce",void 0,{label:item.label}),{force:!0})):status==="incomplete"&&(region.mode="polite",region.announce(this.localize("taskListStepIncompleteAnnounce",void 0,{label:item.label,status:this.localize("statusIncomplete")}),{force:!0})))}}this.previousStatusById=nextMap}idsAreUnique(){return this.taskModel().unique}canReorderItems(){if(this.treeSource!==void 0)return!1;const model=this.taskModel();return this.reorderable&&model.valid&&model.unique}siblingItems(parentId){return parentId===null?this.taskModel().items:this.taskModel().items.find(item=>item.id===parentId)?.children}requestReorder(item,parentId,delta){if(!this.canReorderItems())return;const siblings=this.siblingItems(parentId);if(!siblings)return;const fromIndex=siblings.findIndex(candidate=>candidate.id===item.id),toIndex=fromIndex+delta;fromIndex<0||toIndex<0||toIndex>=siblings.length||(this.pendingReorder={id:item.id,parentId,originalSiblingIds:siblings.map(candidate=>candidate.id),targetSiblingId:siblings[toIndex].id,fromIndex,toIndex},this.pendingFocusId=null,this.emit("lr-reorder",{taskId:item.id,parentTaskId:parentId,fromIndex,toIndex}))}onItemKeyDown(event,item,parentId){this.treeSource!==void 0||!event.currentTarget?.isConnected||event.composedPath()[0]!==event.currentTarget||!this.canReorderItems()||!(event.ctrlKey||event.metaKey)||event.key!=="ArrowUp"&&event.key!=="ArrowDown"||(event.preventDefault(),this.requestReorder(item,parentId,event.key==="ArrowDown"?1:-1))}capturePendingReorderFocus(){const pending=this.pendingReorder;if(!pending)return;const active=shadowFocusTarget(this);this.pendingFocusId=active instanceof HTMLElement&&active.getAttribute("part")==="item"&&active.dataset.id===pending.id?pending.id:null}confirmPendingReorder(){const pending=this.pendingReorder;if(!pending)return;const siblings=this.siblingItems(pending.parentId);if(!siblings||!this.idsAreUnique()){this.clearPendingReorder();return}const siblingIds=siblings.map(item=>item.id);if(!(siblingIds.length!==pending.originalSiblingIds.length||siblingIds.some((id,index)=>id!==pending.originalSiblingIds[index])))return;this.pendingReorder=void 0;const restoreFocus=this.pendingFocusId===pending.id;if(this.pendingFocusId=null,siblingIds[pending.toIndex]!==pending.id||siblingIds[pending.fromIndex]!==pending.targetSiblingId)return;const moved=siblings[pending.toIndex],region=this.liveRegion;region&&(region.mode="polite",region.announce(this.localize("treeNodeMoved",void 0,{label:moved.label,index:getNumberFormat(this.effectiveLocale).format(pending.toIndex+1),total:getNumberFormat(this.effectiveLocale).format(siblings.length)}),{force:!0})),restoreFocus&&this.focusItem(pending.id)}focusItem(id){[...this.shadowRoot?.querySelectorAll('[part="item"]')??[]].find(candidate=>candidate.dataset.id===id)?.focus()}clearPendingReorder(){this.pendingReorder=void 0,this.pendingFocusId=null}renderItem(item,depth,parentId,canReorder){const status=normalizeTaskStatus(item.status),children=depth===0?validTaskItems(item.children):[],hasChildren=children.length>0;return html`
|
|
19
19
|
<div
|
|
20
20
|
part="item"
|
|
21
21
|
role="listitem"
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{formatShortDuration}from"../../../internal/duration.js";import{isRtl}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{chevronIcon}from"../../../internal/icons.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{styles}from"./trace-tree.styles.js";import{normalizeLyraSpanKind,normalizeLyraSpanStatus}from"./span.js";import{projectLyraSpans}from"./span-projection.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_cost,LYRA_DEFAULT_spanKindAgent,LYRA_DEFAULT_spanKindEmbedding,LYRA_DEFAULT_spanKindLlm,LYRA_DEFAULT_spanKindOther,LYRA_DEFAULT_spanKindRetriever,LYRA_DEFAULT_spanKindTool,LYRA_DEFAULT_spanProjectionLimit,LYRA_DEFAULT_traceTree,LYRA_DEFAULT_traceTreeMetricLabel,LYRA_DEFAULT_traceTreeSpanStatus}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_duration,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_expand,LYRA_DEFAULT_item,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_statusUnknown,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function glyph(paths){return svg`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{formatShortDuration}from"../../../internal/duration.js";import{isRtl}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{chevronIcon}from"../../../internal/icons.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{styles}from"./trace-tree.styles.js";import{normalizeLyraSpanKind,normalizeLyraSpanStatus}from"./span.js";import{projectLyraSpans}from"./span-projection.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{createHierarchySummarySource,captureHierarchySourceEffects,traceSourceSummary}from"../../../internal/hierarchy-summary-source.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_cost,LYRA_DEFAULT_spanKindAgent,LYRA_DEFAULT_spanKindEmbedding,LYRA_DEFAULT_spanKindLlm,LYRA_DEFAULT_spanKindOther,LYRA_DEFAULT_spanKindRetriever,LYRA_DEFAULT_spanKindTool,LYRA_DEFAULT_spanProjectionLimit,LYRA_DEFAULT_traceTree,LYRA_DEFAULT_traceTreeMetricLabel,LYRA_DEFAULT_traceTreeSpanStatus}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_duration,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_expand,LYRA_DEFAULT_item,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_statusUnknown,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function glyph(paths){return svg`
|
|
2
2
|
<svg width="1em" height="1em" viewBox=${ICON_VIEW_BOX} fill="none" stroke="currentColor"
|
|
3
3
|
stroke-width=${ICON_STROKE_WIDTH} stroke-linecap="round" stroke-linejoin="round"
|
|
4
4
|
aria-hidden="true" focusable="false">${paths}</svg>
|
|
5
|
-
`}function agentIcon(){return glyph(svg`<rect x="5" y="8" width="14" height="10" rx="2"></rect><circle cx="9.5" cy="13" r="1"></circle><circle cx="14.5" cy="13" r="1"></circle><path d="M12 8V5"></path><circle cx="12" cy="4" r="1"></circle>`)}function llmIcon(){return glyph(svg`<path d="M12 3l1.6 4.4L18 9l-4.4 1.6L12 15l-1.6-4.4L6 9l4.4-1.6z"></path><path d="M18.5 15l.7 1.9 1.9.7-1.9.7-.7 1.9-.7-1.9-1.9-.7 1.9-.7z"></path>`)}function toolIcon(){return glyph(svg`<path d="M14.7 6.3a4 4 0 0 1-5.4 5.4L4 17l3 3 5.3-5.3a4 4 0 0 1 5.4-5.4l-2.3 2.3-2-2z"></path>`)}function retrieverIcon(){return glyph(svg`<circle cx="10.5" cy="10.5" r="6.5"></circle><line x1="15.5" y1="15.5" x2="20" y2="20"></line>`)}function embeddingIcon(){return glyph(svg`<circle cx="6" cy="6" r="1.6"></circle><circle cx="18" cy="6" r="1.6"></circle><circle cx="6" cy="18" r="1.6"></circle><circle cx="18" cy="18" r="1.6"></circle><circle cx="12" cy="12" r="1.6"></circle><line x1="7.3" y1="7.3" x2="10.8" y2="10.8"></line><line x1="16.7" y1="7.3" x2="13.2" y2="10.8"></line><line x1="7.3" y1="16.7" x2="10.8" y2="13.2"></line><line x1="16.7" y1="16.7" x2="13.2" y2="13.2"></line>`)}function otherIcon(){return glyph(svg`<circle cx="12" cy="12" r="8"></circle>`)}const KIND_ICON={agent:agentIcon,llm:llmIcon,tool:toolIcon,retriever:retrieverIcon,embedding:embeddingIcon,other:otherIcon},KIND_LABEL_KEY={agent:"spanKindAgent",llm:"spanKindLlm",tool:"spanKindTool",retriever:"spanKindRetriever",embedding:"spanKindEmbedding",other:"spanKindOther"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied",incomplete:"statusIncomplete",unknown:"statusUnknown"};class LyraTraceTree extends LyraElement{constructor(){super(...arguments),this._treeSource=void 0,this.sourceVersion=0,this.sourcePaintVersion=0,this.sourceSummaries=new WeakMap,this.wasSource=!1,this.sourceControl=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceSpan(value,key),payload:{maxUnits:2e6,maxRowUnits:65536,unitsOf:span=>span.id.length+span.name.length+(span.detail?.length??0)+(span.costText?.length??0)},onChange:()=>{const old=this.sourcePaintVersion++;this.requestUpdate("sourcePaintVersion",old)},accepted:(action,_row,_state,current)=>{!current()||this.treeSource===void 0||(action.type==="toggle"?this.emit("lr-span-toggle",{spanId:action.key,expanded:action.expanded}):action.type==="select"&&this.emit("lr-span-select",{spanId:action.key}))}}),this.spans=[],this.maxNodes=500,this.hiddenKinds=[],this.activeSpanId=null,this.withTokens=!1,this.withCost=!1,this.withoutBars=!1,this.collapsedIds=new Set,this.focusedId=null,this.previousStatuses=new Map,this.pendingAnnouncements=[],this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.renderedProjectionTruncated=!1,this.onKeyDown=e=>{if(this.treeSource!==void 0||e.currentTarget!==this.renderRoot.querySelector("[role=tree]"))return;const rows=this.buildRows();if(rows.length===0)return;const currentIndex=rows.findIndex(r=>r.span.id===this.focusedId),current=currentIndex>=0?rows[currentIndex]:rows[0];if(!current)return;const rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(rows[Math.min(rows.length-1,currentIndex+1)]);break;case"ArrowUp":e.preventDefault(),this.focusRow(rows[Math.max(0,currentIndex-1)]);break;case"Home":e.preventDefault(),this.focusRow(rows[0]);break;case"End":e.preventDefault(),this.focusRow(rows[rows.length-1]);break;case expandKey:if(e.preventDefault(),!current.hasChildren)break;if(this.collapsedIds.has(current.span.id))this.toggleSpan(current.span.id);else{const child=rows[currentIndex+1];child&&child.depth>current.depth&&this.focusRow(child)}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&!this.collapsedIds.has(current.span.id))this.toggleSpan(current.span.id);else for(let i=currentIndex-1;i>=0;i--){const row=rows[i];if(row&&row.depth<current.depth){this.focusRow(row);break}}break;case"Enter":case" ":e.preventDefault(),this.selectRow(current.span.id);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,cost:LYRA_DEFAULT_cost,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,duration:LYRA_DEFAULT_duration,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,expand:LYRA_DEFAULT_expand,item:LYRA_DEFAULT_item,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,spanKindAgent:LYRA_DEFAULT_spanKindAgent,spanKindEmbedding:LYRA_DEFAULT_spanKindEmbedding,spanKindLlm:LYRA_DEFAULT_spanKindLlm,spanKindOther:LYRA_DEFAULT_spanKindOther,spanKindRetriever:LYRA_DEFAULT_spanKindRetriever,spanKindTool:LYRA_DEFAULT_spanKindTool,spanProjectionLimit:LYRA_DEFAULT_spanProjectionLimit,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusIncomplete:LYRA_DEFAULT_statusIncomplete,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,statusUnknown:LYRA_DEFAULT_statusUnknown,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut,traceTree:LYRA_DEFAULT_traceTree,traceTreeMetricLabel:LYRA_DEFAULT_traceTreeMetricLabel,traceTreeSpanStatus:LYRA_DEFAULT_traceTreeSpanStatus,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["spans","hiddenKinds"])}static{this.identityCollectionProperties=Object.freeze(["spans"])}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.sourceVersion++,this.sourceReveal=void 0,this.sourceWrapper=value===void 0?void 0:this.wrapSource(value),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.sourceControl.reveal(key)}syncSource(force=!1){this.sourceControl?.update(this.sourceWrapper,this.effectiveLocale,force,{search:"",hiddenKinds:this.hiddenKinds??[]})}wrapSource(source){const host=this;return{get revision(){return source.revision},async project(request){const version=host.sourceVersion,owner=host.ownerDocument,owned=()=>host._treeSource===source&&host.sourceVersion===version&&host.ownerDocument===owner&&host.isConnected&&!request.signal.aborted,current=()=>{if(!owned())return!1;const revision=source.revision;return owned()&&revision===request.revision},check=()=>{if(!current())throw new Error("Trace source changed")};check();const project=source.project;check();const result=await project.call(source,request);check();const summary=result.summary;check();const startMs=hierarchyField(summary,"startMs");check();const endMs=hierarchyField(summary,"endMs");if(check(),typeof startMs!="number"||typeof endMs!="number"||!Number.isFinite(startMs)||!Number.isFinite(endMs)||startMs<0||endMs<startMs||!Number.isFinite(endMs-startMs))throw new TypeError("Invalid trace extent");const view=result.rows;check();const count=view.count;check();const hasItemAt="itemAt"in view;check();const itemAt=hasItemAt?view.itemAt:void 0;check();let wrapped;if(typeof itemAt=="function"){const indexed=view;wrapped={count,itemAt(index){check();const method=indexed.itemAt;check();const value=method.call(indexed,index);return check(),value},keyAt(index){check();const method=indexed.keyAt;check();const value=method.call(indexed,index);return check(),value},indexOfKey(key){check();const method=indexed.indexOfKey;check();const value=method.call(indexed,key);return check(),value}}}else{const ranged=view;wrapped={count,async read(range){const active=()=>{if(check(),range.signal.aborted)throw new Error("Trace range changed")};active();const method=ranged.read;active();const value=await method.call(ranged,range);return active(),value},async indexOfKey(key,context){const active=()=>{if(check(),context.signal.aborted)throw new Error("Trace navigation changed")};active();const method=ranged.indexOfKey;active();const value=await method.call(ranged,key,context);return active(),value}}}const state2=result.state;check();const total=result.total;check();const focusIndex=result.focusIndex;return check(),host.sourceSummaries.set(wrapped,Object.freeze({startMs,endMs,current})),{state:state2,total,rows:wrapped,...focusIndex===void 0?{}:{focusIndex}}}}}normalizeSourceSpan(value,key){const source=this.treeSource,version=this.sourceVersion,owner=this.ownerDocument,epoch=this.sourceControl.epoch,projection=this.sourceControl.projection,owned=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceVersion===version&&this.sourceControl.epoch===epoch&&this.sourceControl.projection===projection&&!this.sourceControl.loading,accepted=projection?this.sourceSummaries.get(projection.rows):void 0,current=()=>owned()&&!!accepted?.current()&&owned(),field=name=>{if(!current())throw new Error("Trace source changed");const result=hierarchyField(value,name);if(!current())throw new Error("Trace source changed");return result},id=hierarchyKey(field("id"));if(id!==key)throw new TypeError("Trace key mismatch");const startMs=field("startMs"),endMs=field("endMs");if(typeof startMs!="number"||!Number.isFinite(startMs)||startMs<0||endMs!==void 0&&(typeof endMs!="number"||!Number.isFinite(endMs)||endMs<startMs))throw new TypeError("Invalid span timing");const tokensIn=field("tokensIn"),tokensOut=field("tokensOut");return Object.freeze({id,name:hierarchyText(field("name")),detail:hierarchyText(field("detail")),costText:hierarchyText(field("costText")),kind:normalizeLyraSpanKind(field("kind")),status:normalizeLyraSpanStatus(field("status")),startMs,...endMs===void 0?{}:{endMs},...typeof tokensIn=="number"&&this.validTokenMetric(tokensIn)?{tokensIn}:{},...typeof tokensOut=="number"&&this.validTokenMetric(tokensOut)?{tokensOut}:{}})}requestUpdate(name,oldValue){this._treeSource!==void 0&&(name===void 0||name==="hiddenKinds")&&(this.sourceVersion++,this.sourceReveal=void 0,this.syncSource(!0)),super.requestUpdate(name,oldValue)}disconnectedCallback(){this.sourceVersion++,this.sourceReveal=void 0,this.sourceAnnouncement=void 0,this.pendingAnnouncements=[],super.disconnectedCallback()}sourceSummary(){const projection=this.sourceControl.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}updateSourceEffects(){const source=this.treeSource,binding=this.sourceWrapper,version=this.sourceVersion,epoch=this.sourceControl.epoch,owner=this.ownerDocument,projection=this.sourceControl.projection,{error,loading,rowError,rowsObserved}=this.sourceControl,bound=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceWrapper===binding&&this.sourceVersion===version&&this.sourceControl.epoch===epoch,current=()=>bound()&&this.sourceControl.projection===projection&&this.sourceControl.error===error&&this.sourceControl.loading===loading&&this.sourceControl.rowError===rowError&&this.sourceControl.rowsObserved===rowsObserved;if(!current())return;for(const row of this.renderRoot.querySelectorAll("[data-source-key]")){const active=row.dataset.sourceKey===this.activeSpanId;row.setAttribute("aria-current",String(active)),row.toggleAttribute("data-active",active)}const status=error?this.localize("treeSourceError"):loading?this.localize("loading"):this.sourceSummary();if(!current()||this.sourceAnnouncement!==void 0&&status!==this.sourceAnnouncement&&(this.announcements.announcePolite(status),!current()))return;if(rowsObserved){const message=rowError?this.localize("treeSourceError"):"";if(!current()||(this.announcements.transition("source-rows",rowError?"error":"ready",message),!current()))return}this.sourceAnnouncement=status;const key=this.activeSpanId;!key||this.sourceReveal?.[0]===epoch&&this.sourceReveal[1]===key||(this.sourceReveal=[epoch,key],this.sourceControl.whenReady().then(ready=>{ready&&bound()&&this.activeSpanId===key&&this.sourceControl.reveal(key)}))}sourceSpanLabel(span){const fragments=[span.name,span.detail??"",this.localize(KIND_LABEL_KEY[span.kind]),this.localize(STATUS_LABEL_KEY[span.status]),this.formatDuration(span.endMs===void 0?void 0:span.endMs-span.startMs)];return this.withTokens&&(this.validTokenMetric(span.tokensIn)&&fragments.push(this.localize("traceTreeMetricLabel",void 0,{label:this.localize("tokensIn"),value:this.formatNumber(span.tokensIn)})),this.validTokenMetric(span.tokensOut)&&fragments.push(this.localize("traceTreeMetricLabel",void 0,{label:this.localize("tokensOut"),value:this.formatNumber(span.tokensOut)}))),this.withCost&&span.costText&&fragments.push(this.localize("traceTreeMetricLabel",void 0,{label:this.localize("cost"),value:span.costText})),fragments.filter(Boolean).join(this.localize("accessibleLabelSeparator"))}renderSourceSpan(span){const projection=this.sourceControl.projection,summary=projection&&this.sourceSummaries.get(projection.rows);if(!summary)return html``;const extent=summary.endMs-summary.startMs||1,start=Math.max(0,Math.min(span.status==="running"?99:100,(span.startMs-summary.startMs)/extent*100)),end=span.endMs??(span.status==="running"?summary.endMs:span.startMs),width=Math.max(span.status==="running"?1:0,Math.min(100-start,(end-span.startMs)/extent*100));return html`<span class="source-span" ?data-active=${this.activeSpanId===span.id}>
|
|
5
|
+
`}function agentIcon(){return glyph(svg`<rect x="5" y="8" width="14" height="10" rx="2"></rect><circle cx="9.5" cy="13" r="1"></circle><circle cx="14.5" cy="13" r="1"></circle><path d="M12 8V5"></path><circle cx="12" cy="4" r="1"></circle>`)}function llmIcon(){return glyph(svg`<path d="M12 3l1.6 4.4L18 9l-4.4 1.6L12 15l-1.6-4.4L6 9l4.4-1.6z"></path><path d="M18.5 15l.7 1.9 1.9.7-1.9.7-.7 1.9-.7-1.9-1.9-.7 1.9-.7z"></path>`)}function toolIcon(){return glyph(svg`<path d="M14.7 6.3a4 4 0 0 1-5.4 5.4L4 17l3 3 5.3-5.3a4 4 0 0 1 5.4-5.4l-2.3 2.3-2-2z"></path>`)}function retrieverIcon(){return glyph(svg`<circle cx="10.5" cy="10.5" r="6.5"></circle><line x1="15.5" y1="15.5" x2="20" y2="20"></line>`)}function embeddingIcon(){return glyph(svg`<circle cx="6" cy="6" r="1.6"></circle><circle cx="18" cy="6" r="1.6"></circle><circle cx="6" cy="18" r="1.6"></circle><circle cx="18" cy="18" r="1.6"></circle><circle cx="12" cy="12" r="1.6"></circle><line x1="7.3" y1="7.3" x2="10.8" y2="10.8"></line><line x1="16.7" y1="7.3" x2="13.2" y2="10.8"></line><line x1="7.3" y1="16.7" x2="10.8" y2="13.2"></line><line x1="16.7" y1="16.7" x2="13.2" y2="13.2"></line>`)}function otherIcon(){return glyph(svg`<circle cx="12" cy="12" r="8"></circle>`)}const KIND_ICON={agent:agentIcon,llm:llmIcon,tool:toolIcon,retriever:retrieverIcon,embedding:embeddingIcon,other:otherIcon},KIND_LABEL_KEY={agent:"spanKindAgent",llm:"spanKindLlm",tool:"spanKindTool",retriever:"spanKindRetriever",embedding:"spanKindEmbedding",other:"spanKindOther"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied",incomplete:"statusIncomplete",unknown:"statusUnknown"};class LyraTraceTree extends LyraElement{constructor(){super(...arguments),this._treeSource=void 0,this.sourceVersion=0,this.sourcePaintVersion=0,this.sourceSummaries=new WeakMap,this.wasSource=!1,this.sourceControl=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceSpan(value,key),payload:{maxUnits:2e6,maxRowUnits:65536,unitsOf:span=>span.id.length+span.name.length+(span.detail?.length??0)+(span.costText?.length??0)},onChange:()=>{const old=this.sourcePaintVersion++;this.requestUpdate("sourcePaintVersion",old)},accepted:(action,_row,_state,current)=>{!current()||this.treeSource===void 0||(action.type==="toggle"?this.emit("lr-span-toggle",{spanId:action.key,expanded:action.expanded}):action.type==="select"&&this.emit("lr-span-select",{spanId:action.key}))}}),this.spans=[],this.maxNodes=500,this.hiddenKinds=[],this.activeSpanId=null,this.withTokens=!1,this.withCost=!1,this.withoutBars=!1,this.collapsedIds=new Set,this.focusedId=null,this.previousStatuses=new Map,this.pendingAnnouncements=[],this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.renderedProjectionTruncated=!1,this.onKeyDown=e=>{if(this.treeSource!==void 0||e.currentTarget!==this.renderRoot.querySelector("[role=tree]"))return;const rows=this.buildRows();if(rows.length===0)return;const currentIndex=rows.findIndex(r=>r.span.id===this.focusedId),current=currentIndex>=0?rows[currentIndex]:rows[0];if(!current)return;const rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(rows[Math.min(rows.length-1,currentIndex+1)]);break;case"ArrowUp":e.preventDefault(),this.focusRow(rows[Math.max(0,currentIndex-1)]);break;case"Home":e.preventDefault(),this.focusRow(rows[0]);break;case"End":e.preventDefault(),this.focusRow(rows[rows.length-1]);break;case expandKey:if(e.preventDefault(),!current.hasChildren)break;if(this.collapsedIds.has(current.span.id))this.toggleSpan(current.span.id);else{const child=rows[currentIndex+1];child&&child.depth>current.depth&&this.focusRow(child)}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&!this.collapsedIds.has(current.span.id))this.toggleSpan(current.span.id);else for(let i=currentIndex-1;i>=0;i--){const row=rows[i];if(row&&row.depth<current.depth){this.focusRow(row);break}}break;case"Enter":case" ":e.preventDefault(),this.selectRow(current.span.id);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,cost:LYRA_DEFAULT_cost,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,duration:LYRA_DEFAULT_duration,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,expand:LYRA_DEFAULT_expand,item:LYRA_DEFAULT_item,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,spanKindAgent:LYRA_DEFAULT_spanKindAgent,spanKindEmbedding:LYRA_DEFAULT_spanKindEmbedding,spanKindLlm:LYRA_DEFAULT_spanKindLlm,spanKindOther:LYRA_DEFAULT_spanKindOther,spanKindRetriever:LYRA_DEFAULT_spanKindRetriever,spanKindTool:LYRA_DEFAULT_spanKindTool,spanProjectionLimit:LYRA_DEFAULT_spanProjectionLimit,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusIncomplete:LYRA_DEFAULT_statusIncomplete,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,statusUnknown:LYRA_DEFAULT_statusUnknown,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut,traceTree:LYRA_DEFAULT_traceTree,traceTreeMetricLabel:LYRA_DEFAULT_traceTreeMetricLabel,traceTreeSpanStatus:LYRA_DEFAULT_traceTreeSpanStatus,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["spans","hiddenKinds"])}static{this.identityCollectionProperties=Object.freeze(["spans"])}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.sourceVersion++,this.sourceReveal=void 0,this.sourceWrapper=value===void 0?void 0:this.wrapSource(value),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.treeSource===void 0?Promise.resolve(!1):this.sourceControl.reveal(key)}syncSource(force=!1){this.sourceControl?.update(this.sourceWrapper,this.effectiveLocale,force,{search:"",hiddenKinds:this.hiddenKinds??[]})}wrapSource(source){return createHierarchySummarySource(this,source,{captureBinding:()=>{const version=this.sourceVersion;return()=>this._treeSource===source&&this.sourceVersion===version},summary:traceSourceSummary,accepted:(rows,summary,current)=>this.sourceSummaries.set(rows,Object.freeze({...summary,current})),changedMessage:"Trace source changed",rangeChangedMessage:"Trace range changed",navigationChangedMessage:"Trace navigation changed"})}normalizeSourceSpan(value,key){const source=this.treeSource,version=this.sourceVersion,owner=this.ownerDocument,epoch=this.sourceControl.epoch,projection=this.sourceControl.projection,owned=()=>this.isConnected&&this.ownerDocument===owner&&this.treeSource===source&&this.sourceVersion===version&&this.sourceControl.epoch===epoch&&this.sourceControl.projection===projection&&!this.sourceControl.loading,accepted=projection?this.sourceSummaries.get(projection.rows):void 0,current=()=>owned()&&!!accepted?.current()&&owned(),field=name=>{if(!current())throw new Error("Trace source changed");const result=hierarchyField(value,name);if(!current())throw new Error("Trace source changed");return result},id=hierarchyKey(field("id"));if(id!==key)throw new TypeError("Trace key mismatch");const startMs=field("startMs"),endMs=field("endMs");if(typeof startMs!="number"||!Number.isFinite(startMs)||startMs<0||endMs!==void 0&&(typeof endMs!="number"||!Number.isFinite(endMs)||endMs<startMs))throw new TypeError("Invalid span timing");const tokensIn=field("tokensIn"),tokensOut=field("tokensOut");return Object.freeze({id,name:hierarchyText(field("name")),detail:hierarchyText(field("detail")),costText:hierarchyText(field("costText")),kind:normalizeLyraSpanKind(field("kind")),status:normalizeLyraSpanStatus(field("status")),startMs,...endMs===void 0?{}:{endMs},...typeof tokensIn=="number"&&this.validTokenMetric(tokensIn)?{tokensIn}:{},...typeof tokensOut=="number"&&this.validTokenMetric(tokensOut)?{tokensOut}:{}})}requestUpdate(name,oldValue){this._treeSource!==void 0&&(name===void 0||name==="hiddenKinds")&&(this.sourceVersion++,this.sourceReveal=void 0,this.syncSource(!0)),super.requestUpdate(name,oldValue)}disconnectedCallback(){this.sourceVersion++,this.sourceReveal=void 0,this.sourceAnnouncement=void 0,this.pendingAnnouncements=[],super.disconnectedCallback()}sourceSummary(){const projection=this.sourceControl.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}updateSourceEffects(){const source=this.treeSource,binding=this.sourceWrapper,version=this.sourceVersion,{epoch,error,loading,rowError,rowsObserved,bound,current}=captureHierarchySourceEffects(this,this.sourceControl,()=>this.treeSource===source&&this.sourceWrapper===binding&&this.sourceVersion===version);if(!current())return;for(const row of this.renderRoot.querySelectorAll("[data-source-key]")){const active=row.dataset.sourceKey===this.activeSpanId;row.setAttribute("aria-current",String(active)),row.toggleAttribute("data-active",active)}const status=error?this.localize("treeSourceError"):loading?this.localize("loading"):this.sourceSummary();if(!current()||this.sourceAnnouncement!==void 0&&status!==this.sourceAnnouncement&&(this.announcements.announcePolite(status),!current()))return;if(rowsObserved){const message=rowError?this.localize("treeSourceError"):"";if(!current()||(this.announcements.transition("source-rows",rowError?"error":"ready",message),!current()))return}this.sourceAnnouncement=status;const key=this.activeSpanId;!key||this.sourceReveal?.[0]===epoch&&this.sourceReveal[1]===key||(this.sourceReveal=[epoch,key],this.sourceControl.whenReady().then(ready=>{ready&&bound()&&this.activeSpanId===key&&this.sourceControl.reveal(key)}))}sourceSpanLabel(span){const fragments=[span.name,span.detail??"",this.localize(KIND_LABEL_KEY[span.kind]),this.localize(STATUS_LABEL_KEY[span.status]),this.formatDuration(span.endMs===void 0?void 0:span.endMs-span.startMs)];return this.withTokens&&(this.validTokenMetric(span.tokensIn)&&fragments.push(this.localize("traceTreeMetricLabel",void 0,{label:this.localize("tokensIn"),value:this.formatNumber(span.tokensIn)})),this.validTokenMetric(span.tokensOut)&&fragments.push(this.localize("traceTreeMetricLabel",void 0,{label:this.localize("tokensOut"),value:this.formatNumber(span.tokensOut)}))),this.withCost&&span.costText&&fragments.push(this.localize("traceTreeMetricLabel",void 0,{label:this.localize("cost"),value:span.costText})),fragments.filter(Boolean).join(this.localize("accessibleLabelSeparator"))}renderSourceSpan(span){const projection=this.sourceControl.projection,summary=projection&&this.sourceSummaries.get(projection.rows);if(!summary)return html``;const extent=summary.endMs-summary.startMs||1,start=Math.max(0,Math.min(span.status==="running"?99:100,(span.startMs-summary.startMs)/extent*100)),end=span.endMs??(span.status==="running"?summary.endMs:span.startMs),width=Math.max(span.status==="running"?1:0,Math.min(100-start,(end-span.startMs)/extent*100));return html`<span class="source-span" ?data-active=${this.activeSpanId===span.id}>
|
|
6
6
|
<span part="icon">${KIND_ICON[span.kind]()}</span><span part="name">${span.name}</span>
|
|
7
7
|
<span part="detail">${span.detail??""}</span>
|
|
8
8
|
<span part="status-text" data-status=${span.status}>${this.localize(STATUS_LABEL_KEY[span.status])}</span>
|
|
@@ -4,6 +4,8 @@ export declare function prepareChartModel(source:unknown,type:string,limit:numbe
|
|
|
4
4
|
/** Overlays one exact observation without reconnecting an omitted path segment.*/
|
|
5
5
|
export declare function withPreparedPoint(model:PreparedChartModel,ref:LyraSeriesPointRef,point:LyraSeriesObservation):PreparedChartModel;
|
|
6
6
|
/** Resolves promptly on cancellation even when a host reader ignores its signal.*/
|
|
7
|
-
export declare function preparedResponse<T>(response:LyraSourceValue<T>,signal:AbortSignal):Promise<T>;
|
|
7
|
+
export declare function preparedResponse<T>(response:LyraSourceValue<T>,signal:AbortSignal):Promise<T>;export type PreparedPointRevealResult={readonly status:'ready';readonly model:PreparedChartModel;}|{readonly status:'absent'|'stale';};
|
|
8
|
+
/** Resolves one exact point and optional bounded refinement without owning renderer effects.*/
|
|
9
|
+
export declare function revealPreparedSourcePoint(model:PreparedChartModel,ref:LyraSeriesPointRef,signal:AbortSignal,isCurrent:()=>boolean):Promise<PreparedPointRevealResult>;
|
|
8
10
|
/** Validates a bounded indexed refinement while preserving the snapshot's full domains/counts.*/
|
|
9
11
|
export declare function withPreparedRange(model:PreparedChartModel,request:LyraSeriesRangeRequest,values:readonly LyraSeriesSample[]):PreparedChartModel;export{};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sourceCount,sourceRevision}from"../../../internal/source-request-controller.js";function field(value,key){if(!value||typeof value!="object")throw new TypeError("Invalid prepared record");const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor||!("value"in descriptor))throw new TypeError("Prepared fields must be own data properties");return descriptor.value}function array(value,maximum){if(!Array.isArray(value))throw new RangeError("Invalid prepared array");const length=sourceCount(field(value,"length"));if(length>maximum)throw new RangeError("Prepared array budget exceeded");const result=[];for(let index=0;index<length;index++)result.push(field(value,String(index)));return result}function number(value){if(typeof value!="number"||!Number.isFinite(value))throw new TypeError("Invalid prepared number");return value}function text(value,maximum,nonblank=!1){if(typeof value!="string"||value.length>maximum||nonblank&&!value.trim())throw new TypeError("Invalid prepared metadata");return value}function counts(value){const source=sourceCount(field(value,"sourceCount")),valid=sourceCount(field(value,"validCount")),invalid=sourceCount(field(value,"invalidCount"));if(valid>source||invalid!==source-valid)throw new RangeError("Invalid prepared counts");return Object.freeze({sourceCount:source,validCount:valid,invalidCount:invalid})}function domain(value,valid){if(valid===0&&value===null)return null;const min=number(field(value,"min")),max=number(field(value,"max"));if(!valid||max<min)throw new RangeError("Invalid prepared domain");return Object.freeze({min,max})}function addCount(a,b){return sourceCount(a+b)}function sample(value,count,x,y){const sourceIndex=sourceCount(field(value,"sourceIndex")),pointX=number(field(value,"x")),pointY=number(field(value,"y")),breakBefore=field(value,"breakBefore");if(sourceIndex>=count.sourceCount||!x||!y||pointX<x.min||pointX>x.max||pointY<y.min||pointY>y.max||typeof breakBefore!="boolean")throw new RangeError("Invalid prepared sample");return Object.freeze({x:pointX,y:pointY,sourceIndex,breakBefore})}function finish(model){let displayedCount=0,peerCount=0,rowCount=0;for(const series of model.series){const size=model.kind==="series"?series.samples.length:series.values.length;displayedCount+=model.kind==="series"?series.samples.reduce((sum,point)=>sum+ +(point!==null),0):size,peerCount+=size,rowCount=Math.max(rowCount,size)}if(peerCount>model.limit||rowCount*model.series.length>1e3||displayedCount>9e3)throw new RangeError("Prepared rendering budget exceeded");return Object.freeze({...model,series:Object.freeze(model.series),displayedCount,peerCount,rowCount})}function prepareChartModel(source,type,limit){const kind=field(source,"kind"),revision=sourceRevision(field(source,"revision"));if(kind!=="series"&&kind!=="categories")throw new TypeError("Incompatible prepared kind");if(kind==="series"?!["line","bar"].includes(type):!["bar","pie","doughnut","radar","polarArea"].includes(type))throw new TypeError("Incompatible prepared chart type");const entries=array(field(source,"series"),1e3);if(!entries.length)throw new RangeError("Prepared series are required");const identifiers=new Set;let metadataUnits=0,validCount=0,invalidCount=0;const metadata=value=>{const id=text(field(value,"id"),256,!0),label=text(field(value,"label"),1024);if(metadataUnits+=id.length+label.length,metadataUnits>65536)throw new RangeError("Prepared metadata budget exceeded");return{id,label}},categories=[],categoryCounts=[];let categoryTotals;if(kind==="categories"){categoryTotals=counts(field(source,"counts")),validCount=categoryTotals.validCount,invalidCount=categoryTotals.invalidCount;const ids=new Set;for(const value of array(field(source,"categories"),1e3)){const category=metadata(value);if(ids.has(category.id))throw new TypeError("Duplicate prepared category ID");ids.add(category.id),categories.push(category)}const rawCounts=array(field(source,"categoryCounts"),1e3);if(rawCounts.length!==categories.length)throw new RangeError("Prepared category count mismatch");let total=0;for(const value of rawCounts){const count=sourceCount(value);total=addCount(total,count),categoryCounts.push(count)}if(total!==validCount)throw new RangeError("Prepared category counts do not conserve observations");if(!["count","sum","mean","host-defined"].includes(String(field(source,"aggregation"))))throw new TypeError("Invalid prepared aggregation")}else if(limit<5||typeof field(source,"getPoint")!="function")throw new RangeError("Prepared series require an exact reader and overlay capacity");const result=[];let admittedEntries=0;for(const value of entries){const meta=metadata(value);if(identifiers.has(meta.id))throw new TypeError("Duplicate prepared series ID");if(identifiers.add(meta.id),kind==="categories"){const values=array(field(value,"values"),Math.min(limit-admittedEntries,1e3)).map(number);if(admittedEntries+=values.length,values.length!==categories.length)throw new RangeError("Prepared category values mismatch");result.push(Object.freeze({...meta,counts:categoryTotals,xDomain:null,yDomain:null,samples:Object.freeze([]),values:Object.freeze(values)}))}else{const totals=counts(field(value,"counts"));validCount=addCount(validCount,totals.validCount),invalidCount=addCount(invalidCount,totals.invalidCount);const x=domain(field(value,"xDomain"),totals.validCount),y=domain(field(value,"yDomain"),totals.validCount),raw=array(field(value,"samples"),Math.min(limit-admittedEntries-2,1e3));if(raw.length>totals.validCount||totals.validCount>0&&!raw.length)throw new RangeError("Invalid prepared sample count");const samples=[];let previous=-1;for(const value2 of raw){const point=sample(value2,totals,x,y);if(point.sourceIndex<=previous||previous<0&&!point.breakBefore)throw new RangeError("Prepared samples must preserve ordered source indices");if(type==="line"&&previous>=0&&point.breakBefore&&samples.push(null),samples.push(point),previous=point.sourceIndex,admittedEntries+samples.length+2>limit)throw new RangeError("Prepared rendering budget exceeded")}admittedEntries+=samples.length,result.push(Object.freeze({...meta,counts:totals,xDomain:x,yDomain:y,samples:Object.freeze(samples),values:Object.freeze([])}))}}const model=finish({source,type,revision,kind,labels:Object.freeze(categories.map(value=>value.label)),categoryIds:Object.freeze(categories.map(value=>value.id)),categoryCounts:Object.freeze(categoryCounts),series:result,validCount,invalidCount,limit}),reserve=kind==="series"?2:0;if(model.peerCount+reserve>limit||model.displayedCount+ +(kind==="series")>9e3||(model.rowCount+reserve)*entries.length>1e3)throw new RangeError("Prepared overlay capacity exceeded");return model}function withPreparedPoint(model,ref,point){if(model.kind!=="series")throw new TypeError("Exact points require prepared series");const index=model.series.findIndex(entry2=>entry2.id===ref.seriesId),entry=model.series[index];if(!entry)throw new RangeError("Unknown prepared series");const value=sample({x:field(point,"x"),y:field(point,"y"),sourceIndex:ref.sourceIndex,breakBefore:!0},entry.counts,entry.xDomain,entry.yDomain);if(entry.samples.some(sample2=>sample2?.sourceIndex===ref.sourceIndex))return model;const series=[...model.series];return series[index]=Object.freeze({...entry,samples:Object.freeze([...entry.samples,...entry.samples.length?[null]:[],value])}),finish({...model,series})}async function preparedResponse(response,signal){let abort;try{return await new Promise((resolve,reject)=>{abort=()=>reject(signal.reason),signal.addEventListener("abort",abort,{once:!0}),Promise.resolve(response).then(resolve,reject),signal.aborted&&abort()})}finally{abort&&signal.removeEventListener("abort",abort)}}function withPreparedRange(model,request,values){if(model.kind!=="series"||model.source.kind!=="series")throw new TypeError("Refinement requires prepared series");const index=model.series.findIndex(series=>series.id===request.seriesId),entry=model.series[index];if(!entry)throw new RangeError("Unknown prepared series");const points=array(values,request.maxPoints).map(value=>sample(value,entry.counts,entry.xDomain,entry.yDomain));for(const point of points)if(point.sourceIndex<request.startIndex||point.sourceIndex>=request.endIndex)throw new RangeError("Refinement outside requested range");const source={kind:"series",revision:model.revision,getPoint:model.source.getPoint,series:model.series.map((series,position)=>({id:series.id,label:series.label,counts:series.counts,xDomain:series.xDomain,yDomain:series.yDomain,samples:position===index?points:series.samples.filter(point=>point!==null)}))},refined=prepareChartModel(source,model.type,model.limit);return Object.freeze({...refined,source:model.source})}export{prepareChartModel,preparedResponse,withPreparedPoint,withPreparedRange};
|
|
1
|
+
import{sourceCount,sourceRevision}from"../../../internal/source-request-controller.js";function field(value,key){if(!value||typeof value!="object")throw new TypeError("Invalid prepared record");const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor||!("value"in descriptor))throw new TypeError("Prepared fields must be own data properties");return descriptor.value}function array(value,maximum){if(!Array.isArray(value))throw new RangeError("Invalid prepared array");const length=sourceCount(field(value,"length"));if(length>maximum)throw new RangeError("Prepared array budget exceeded");const result=[];for(let index=0;index<length;index++)result.push(field(value,String(index)));return result}function number(value){if(typeof value!="number"||!Number.isFinite(value))throw new TypeError("Invalid prepared number");return value}function text(value,maximum,nonblank=!1){if(typeof value!="string"||value.length>maximum||nonblank&&!value.trim())throw new TypeError("Invalid prepared metadata");return value}function counts(value){const source=sourceCount(field(value,"sourceCount")),valid=sourceCount(field(value,"validCount")),invalid=sourceCount(field(value,"invalidCount"));if(valid>source||invalid!==source-valid)throw new RangeError("Invalid prepared counts");return Object.freeze({sourceCount:source,validCount:valid,invalidCount:invalid})}function domain(value,valid){if(valid===0&&value===null)return null;const min=number(field(value,"min")),max=number(field(value,"max"));if(!valid||max<min)throw new RangeError("Invalid prepared domain");return Object.freeze({min,max})}function addCount(a,b){return sourceCount(a+b)}function sample(value,count,x,y){const sourceIndex=sourceCount(field(value,"sourceIndex")),pointX=number(field(value,"x")),pointY=number(field(value,"y")),breakBefore=field(value,"breakBefore");if(sourceIndex>=count.sourceCount||!x||!y||pointX<x.min||pointX>x.max||pointY<y.min||pointY>y.max||typeof breakBefore!="boolean")throw new RangeError("Invalid prepared sample");return Object.freeze({x:pointX,y:pointY,sourceIndex,breakBefore})}function finish(model){let displayedCount=0,peerCount=0,rowCount=0;for(const series of model.series){const size=model.kind==="series"?series.samples.length:series.values.length;displayedCount+=model.kind==="series"?series.samples.reduce((sum,point)=>sum+ +(point!==null),0):size,peerCount+=size,rowCount=Math.max(rowCount,size)}if(peerCount>model.limit||rowCount*model.series.length>1e3||displayedCount>9e3)throw new RangeError("Prepared rendering budget exceeded");return Object.freeze({...model,series:Object.freeze(model.series),displayedCount,peerCount,rowCount})}function prepareChartModel(source,type,limit){const kind=field(source,"kind"),revision=sourceRevision(field(source,"revision"));if(kind!=="series"&&kind!=="categories")throw new TypeError("Incompatible prepared kind");if(kind==="series"?!["line","bar"].includes(type):!["bar","pie","doughnut","radar","polarArea"].includes(type))throw new TypeError("Incompatible prepared chart type");const entries=array(field(source,"series"),1e3);if(!entries.length)throw new RangeError("Prepared series are required");const identifiers=new Set;let metadataUnits=0,validCount=0,invalidCount=0;const metadata=value=>{const id=text(field(value,"id"),256,!0),label=text(field(value,"label"),1024);if(metadataUnits+=id.length+label.length,metadataUnits>65536)throw new RangeError("Prepared metadata budget exceeded");return{id,label}},categories=[],categoryCounts=[];let categoryTotals;if(kind==="categories"){categoryTotals=counts(field(source,"counts")),validCount=categoryTotals.validCount,invalidCount=categoryTotals.invalidCount;const ids=new Set;for(const value of array(field(source,"categories"),1e3)){const category=metadata(value);if(ids.has(category.id))throw new TypeError("Duplicate prepared category ID");ids.add(category.id),categories.push(category)}const rawCounts=array(field(source,"categoryCounts"),1e3);if(rawCounts.length!==categories.length)throw new RangeError("Prepared category count mismatch");let total=0;for(const value of rawCounts){const count=sourceCount(value);total=addCount(total,count),categoryCounts.push(count)}if(total!==validCount)throw new RangeError("Prepared category counts do not conserve observations");if(!["count","sum","mean","host-defined"].includes(String(field(source,"aggregation"))))throw new TypeError("Invalid prepared aggregation")}else if(limit<5||typeof field(source,"getPoint")!="function")throw new RangeError("Prepared series require an exact reader and overlay capacity");const result=[];let admittedEntries=0;for(const value of entries){const meta=metadata(value);if(identifiers.has(meta.id))throw new TypeError("Duplicate prepared series ID");if(identifiers.add(meta.id),kind==="categories"){const values=array(field(value,"values"),Math.min(limit-admittedEntries,1e3)).map(number);if(admittedEntries+=values.length,values.length!==categories.length)throw new RangeError("Prepared category values mismatch");result.push(Object.freeze({...meta,counts:categoryTotals,xDomain:null,yDomain:null,samples:Object.freeze([]),values:Object.freeze(values)}))}else{const totals=counts(field(value,"counts"));validCount=addCount(validCount,totals.validCount),invalidCount=addCount(invalidCount,totals.invalidCount);const x=domain(field(value,"xDomain"),totals.validCount),y=domain(field(value,"yDomain"),totals.validCount),raw=array(field(value,"samples"),Math.min(limit-admittedEntries-2,1e3));if(raw.length>totals.validCount||totals.validCount>0&&!raw.length)throw new RangeError("Invalid prepared sample count");const samples=[];let previous=-1;for(const value2 of raw){const point=sample(value2,totals,x,y);if(point.sourceIndex<=previous||previous<0&&!point.breakBefore)throw new RangeError("Prepared samples must preserve ordered source indices");if(type==="line"&&previous>=0&&point.breakBefore&&samples.push(null),samples.push(point),previous=point.sourceIndex,admittedEntries+samples.length+2>limit)throw new RangeError("Prepared rendering budget exceeded")}admittedEntries+=samples.length,result.push(Object.freeze({...meta,counts:totals,xDomain:x,yDomain:y,samples:Object.freeze(samples),values:Object.freeze([])}))}}const model=finish({source,type,revision,kind,labels:Object.freeze(categories.map(value=>value.label)),categoryIds:Object.freeze(categories.map(value=>value.id)),categoryCounts:Object.freeze(categoryCounts),series:result,validCount,invalidCount,limit}),reserve=kind==="series"?2:0;if(model.peerCount+reserve>limit||model.displayedCount+ +(kind==="series")>9e3||(model.rowCount+reserve)*entries.length>1e3)throw new RangeError("Prepared overlay capacity exceeded");return model}function withPreparedPoint(model,ref,point){if(model.kind!=="series")throw new TypeError("Exact points require prepared series");const index=model.series.findIndex(entry2=>entry2.id===ref.seriesId),entry=model.series[index];if(!entry)throw new RangeError("Unknown prepared series");const value=sample({x:field(point,"x"),y:field(point,"y"),sourceIndex:ref.sourceIndex,breakBefore:!0},entry.counts,entry.xDomain,entry.yDomain);if(entry.samples.some(sample2=>sample2?.sourceIndex===ref.sourceIndex))return model;const series=[...model.series];return series[index]=Object.freeze({...entry,samples:Object.freeze([...entry.samples,...entry.samples.length?[null]:[],value])}),finish({...model,series})}async function preparedResponse(response,signal){let abort;try{return await new Promise((resolve,reject)=>{abort=()=>reject(signal.reason),signal.addEventListener("abort",abort,{once:!0}),Promise.resolve(response).then(resolve,reject),signal.aborted&&abort()})}finally{abort&&signal.removeEventListener("abort",abort)}}async function revealPreparedSourcePoint(model,ref,signal,isCurrent){const series=model.series.find(series2=>series2.id===ref.seriesId);if(!series)throw new RangeError("Unknown prepared series");const source=model.source;if(source.kind!=="series"||source.revision!==model.revision)throw new Error("Prepared source revision changed");const response=source.getPoint(ref,{signal}),point=await preparedResponse(response,signal);if(!isCurrent()||source.revision!==model.revision)return{status:"stale"};if(point===null)return{status:"absent"};let next=model;const refinement=Object.getOwnPropertyDescriptor(source,"queryRange");if(refinement){if(!("value"in refinement)||typeof refinement.value!="function")throw new TypeError("Invalid indexed refinement");const otherEntries=model.peerCount-series.samples.length,entryBudget=Math.min(model.limit-otherEntries,Math.floor(1e3/model.series.length)),maxPoints=Math.max(1,Math.floor((entryBudget-1)/2)),startIndex=Math.max(0,ref.sourceIndex-maxPoints),endIndex=Math.min(series.counts.sourceCount,ref.sourceIndex+Math.min(maxPoints+1,series.counts.sourceCount-ref.sourceIndex)),request={seriesId:ref.seriesId,startIndex,endIndex,maxPoints,signal},points=await preparedResponse(source.queryRange(request),signal);if(!isCurrent()||source.revision!==model.revision)return{status:"stale"};next=withPreparedRange(model,request,points)}const overlay=withPreparedPoint(next,ref,point);return!isCurrent()||source.revision!==model.revision?{status:"stale"}:{status:"ready",model:overlay}}function withPreparedRange(model,request,values){if(model.kind!=="series"||model.source.kind!=="series")throw new TypeError("Refinement requires prepared series");const index=model.series.findIndex(series=>series.id===request.seriesId),entry=model.series[index];if(!entry)throw new RangeError("Unknown prepared series");const points=array(values,request.maxPoints).map(value=>sample(value,entry.counts,entry.xDomain,entry.yDomain));for(const point of points)if(point.sourceIndex<request.startIndex||point.sourceIndex>=request.endIndex)throw new RangeError("Refinement outside requested range");const source={kind:"series",revision:model.revision,getPoint:model.source.getPoint,series:model.series.map((series,position)=>({id:series.id,label:series.label,counts:series.counts,xDomain:series.xDomain,yDomain:series.yDomain,samples:position===index?points:series.samples.filter(point=>point!==null)}))},refined=prepareChartModel(source,model.type,model.limit);return Object.freeze({...refined,source:model.source})}export{prepareChartModel,preparedResponse,revealPreparedSourcePoint,withPreparedPoint,withPreparedRange};
|