@luxalgo/vela 0.6.19 → 0.6.21

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.
@@ -1,6 +1,6 @@
1
1
  var Vela=(function(exports){'use strict';function Ms(r){return r===true?90:typeof r!="number"||!Number.isFinite(r)||r<=0?0:Math.min(r,1e3)}function Tp(r){return typeof r=="boolean"?{animZoom:r,animPan:r,animLiveBar:0}:{animZoom:r?.zoom??true,animPan:r?.pan??true,animLiveBar:Ms(r?.liveBar)}}function Ne(r){return r.kind!=="candle"&&r.kind!=="bar"&&r.kind!=="markers"}var qn=class{constructor(){this.handlers=new Map;}on(e,t){let n=this.handlers.get(e);n||(n=new Set,this.handlers.set(e,n));let i=n;return i.add(t),()=>{i.delete(t);}}off(e,t){this.handlers.get(e)?.delete(t);}hasListeners(e){return (this.handlers.get(e)?.size??0)>0}emit(e,t){let n=this.handlers.get(e);if(n)for(let i of n)try{i(t);}catch(o){console.error(`[vela] event handler error for "${String(e)}"`,o);}}clear(){this.handlers.clear();}};var ks=class{constructor(){this.records=new Map;this.counter=0;}nextId(e="ind"){return this.counter+=1,`${e}-${this.counter}`}add(e){this.records.set(e.id,e);}get(e){return this.records.get(e)}remove(e){let t=this.records.get(e);return this.records.delete(e),t}all(){return [...this.records.values()]}};var zi=new Map;function Ln(r){zi.set(r.type,r);}function Ep(r){zi.delete(r);}function $i(r){return zi.get(r)}function Pp(){return [...zi.keys()]}function Is(){return [...zi.values()]}var As=class{constructor(e,t,n){this.feed=e;this.market=t;this.onBar=n;this.unsubscribe=null;}start(){this.unsubscribe||(this.unsubscribe=this.feed.subscribe(this.market,this.onBar));}stop(){this.unsubscribe?.(),this.unsubscribe=null;}};var _r=class{constructor(e,t,n,i,o){this.controller=n;this.schema=[];this.propsSchema=[];this.visibleState=true;this.bus=new qn;this.id=e,this.title=t,i!==void 0&&(this.source=i),o!==void 0&&(this.nativeType=o);}get inputs(){return this.schema}get props(){return this.propsSchema}get visible(){return this.visibleState}inputValues(){return this.controller.inputValuesOf(this.id)}propValues(){return this.controller.propValuesOf(this.id)}setInput(e,t){this.controller.applyInputs(this.id,{[e]:t});}setInputs(e){this.controller.applyInputs(this.id,e);}setProp(e,t){this.controller.applyProps(this.id,{[e]:t});}setProps(e){this.controller.applyProps(this.id,e);}setVisible(e){this.controller.setVisible(this.id,e);}moveTo(e){this.controller.moveIndicator(this.id,e);}on(e,t){return this.bus.on(e,t)}context(e){return this.controller.getIndicatorContext(this.id,e)}remove(){this.controller.removeIndicator(this.id);}setSchema(e){this.schema=e;}setPropsSchema(e){this.propsSchema=e;}setVisibleState(e){this.visibleState=e;}emit(e,t){this.bus.emit(e,t);}};function Ux(r){let e={};for(let i of r.series)e[i.kind]=(e[i.kind]??0)+1;let t=i=>i?.filter(o=>o.overlay===true).length??0,n=t(r.series)+t(r.fills)+t(r.backgrounds)+t(r.lines)+t(r.boxes)+t(r.labels)+t(r.polylines)+t(r.linefills)+t(r.tables);return {id:r.id,title:r.title,overlay:r.overlay,paneId:r.paneId,native:!!r.native,nativeType:r.native?.type,series:e,fills:r.fills.length,backgrounds:r.backgrounds.length,priceLines:r.priceLines.length,lines:r.lines?.length??0,boxes:r.boxes?.length??0,labels:r.labels?.length??0,polylines:r.polylines?.length??0,linefills:r.linefills?.length??0,tables:r.tables?.length??0,barColors:r.barColors?.length??0,trades:r.trades?.length??0,inputs:r.inputs.length,forcedOverlay:n}}function Lp(r){let e=r.map(Ux),t=n=>e.reduce((i,o)=>i+n(o),0);return {indicators:e,totals:{panes:new Set(e.map(n=>n.paneId??"price")).size,series:t(n=>Object.values(n.series).reduce((i,o)=>i+o,0)),fills:t(n=>n.fills),backgrounds:t(n=>n.backgrounds),priceLines:t(n=>n.priceLines),lines:t(n=>n.lines),boxes:t(n=>n.boxes),labels:t(n=>n.labels),polylines:t(n=>n.polylines),linefills:t(n=>n.linefills),tables:t(n=>n.tables),barColors:t(n=>n.barColors),trades:t(n=>n.trades),forcedOverlay:t(n=>n.forcedOverlay)}}}var Yx={"1D":864e5,"1W":6048e5,"1M":2592e6,"3M":7776e6,"6M":15552e6,"1Y":31536e6,"5Y":15768e7};function Mp(r,e){if(e.length===0)return null;let t=e[0].time,n=e[e.length-1].time;if(r==="ALL")return {from:t,to:n};let i;return r==="YTD"?i=Date.UTC(new Date(n).getUTCFullYear(),0,1):i=n-Yx[r],{from:Math.max(t,i),to:n}}var Ye="#2962ff",Br="#38c0fd",z="#089981",W="#f23645",J="#787b86",kp="#e0b400",de="#ff9800",Je="#5b9cf6",Ip="#ff5d00",Ds="#0ecb81",Os="#f6465d",v2="#f97316",y2="#0ea5e9",w2="#9ca3af",_="#3b82f6",Ap="#9aa0ad",Rp="#1e293b",Dp="#475569",Op="#595959",Np=Ye,Fp=W,Vp="#d500f9",Rs=[Ye,z,W,de,"#7e57c2","#26a69a",Je,"#e573b5"];function x2(r){let e=0;for(let t=0;t<r.length;t++)e=e*31+r.charCodeAt(t)>>>0;return Rs[e%Rs.length]}var O=Br;function dd(){return {lineColor:O,lineWidth:2,lineStyle:"solid"}}function sn(r=""){return {value:r,size:"normal",hAlign:"left",vAlign:"top"}}var Ns=class Ns{constructor(e){this.locked=false;this.visible=true;this.zIndex=0;this.id=e.id??`dw-${Ns.seq+=1}`,this.paneId=e.paneId,this.anchors=(e.anchors??[]).map(t=>({time:t.time,price:t.price})),this.style=e.style?{...e.style}:dd(),this.text=e.text?{...e.text}:void 0,this.locked=e.locked??false,this.visible=e.visible??true,this.zIndex=e.zIndex??0,this.createdAt=e.createdAt??Date.now(),e.props&&this.readProps(e.props);}isComplete(){return this.anchors.length>=this.anchorSchema().min}placementMode(){return "click"}onPlaced(e){}constrainHandleDrag(e){}translateBody(e,t,n){return n.map(i=>({time:i.time+e,price:i.price+t}))}timeExtent(){if(this.anchors.length===0)return null;let e=1/0,t=-1/0;for(let n of this.anchors)n.time<e&&(e=n.time),n.time>t&&(t=n.time);return {min:e,max:t}}editableLevels(){return null}applySettings(e){for(let[t,n]of Object.entries(e))t.startsWith("text.")&&!this.text&&(this.text=sn()),_p(this,t,n);}applyProps(e){this.readProps(e);}serialize(){return {id:this.id,type:this.type,paneId:this.paneId,anchors:this.anchors.map(e=>({time:e.time,price:e.price})),style:{...this.style},text:this.text?{...this.text}:void 0,locked:this.locked,visible:this.visible,zIndex:this.zIndex,createdAt:this.createdAt,props:this.writeProps()}}writeProps(){}readProps(e){}};Ns.seq=0;var G=Ns;function _p(r,e,t){let n=e.split("."),i=r;for(let o=0;o<n.length-1;o+=1){let s=n[o],a=i[s];(a==null||typeof a!="object")&&(a={},i[s]=a),i=a;}i[n[n.length-1]]=t;}var ud=new Map;function N(r,e){ud.set(r,e);}function Fs(r){return ud.get(r)??null}function Z(r){return ud.get(r)??""}function ye(r,e){return Z(r).replace("<svg ",`<svg width="${e}" height="${e}" `)}function Bp(r,e=""){return `<svg viewBox="0 0 16 16" width="1em" height="1em" ${e?e+" ":""}fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">${r}</svg>`}function R(r,e=""){return `<svg viewBox="0 0 24 24" width="1em" height="1em" ${e?e+" ":""}fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">${r}</svg>`}function hd(r){return `<svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" stroke="none">${r}</svg>`}var U=Bp;N("style-candles",U('<path d="M4.5 2v2M4.5 12v2M11.5 2v1.5M11.5 11v3"/><rect x="2.8" y="4" width="3.4" height="8" rx="0.6" fill="currentColor" fill-opacity="0.25"/><rect x="9.8" y="3.5" width="3.4" height="7.5" rx="0.6" fill="currentColor"/>'));N("style-bars",U('<path d="M4.5 2.5v11M2.5 5h2M4.5 11h2"/><path d="M11.5 2.5v11M9.5 4.5h2M11.5 10.5h2"/>'));N("style-line",U('<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/>'));N("style-area",U('<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/><path d="M1.5 11.5 5.5 7l3 2.5 5-6V13.5h-12z" fill="currentColor" fill-opacity="0.25" stroke="none"/>'));N("style-baseline",U('<path d="M1.5 8h13" stroke-dasharray="2 2"/><path d="M2.5 8 5.25 4.5 8 8h-5.5z" fill="currentColor" fill-opacity="0.25" stroke="none"/><path d="M2.5 8 5.25 4.5 8 8"/><path d="M8 8l2.75 3.5L13.5 8h-5.5z" fill="currentColor" fill-opacity="0.25" stroke="none"/><path d="M8 8l2.75 3.5L13.5 8"/>'));N("style-heikinashi",U('<path d="M4.5 12v2M11.5 2v2"/><rect x="2.8" y="5" width="3.4" height="7" rx="0.6" fill="currentColor" fill-opacity="0.25"/><rect x="9.8" y="4" width="3.4" height="7" rx="0.6" fill="currentColor"/>'));N("indicators",U('<path d="M1.5 12.5 5 7l2.5 3.5L11 4l3.5 5"/><circle cx="11" cy="4" r="1.4" fill="currentColor" stroke="none"/>'));N("undo",U('<path d="M6.2 9.5 2.7 6l3.5-3.5"/><path d="M2.7 6h6.8a3.65 3.65 0 0 1 0 7.3H7.5"/>'));N("redo",U('<path d="M9.8 9.5 13.3 6 9.8 2.5"/><path d="M13.3 6H6.5a3.65 3.65 0 0 0 0 7.3h2"/>'));N("objects",U('<path d="M8 1.8 14 5 8 8.2 2 5z"/><path d="M2 8l6 3.2L14 8" opacity="0.7"/><path d="M2 11l6 3.2 6-3.2" opacity="0.4"/>'));N("clock",U('<circle cx="8" cy="8" r="6.2"/><path d="M8 4.8V8l2.4 1.6"/>'));N("calendar",U('<rect x="2.2" y="3.2" width="11.6" height="10.6" rx="1.4"/><path d="M5.2 1.8v2.8M10.8 1.8v2.8M2.2 6.8h11.6"/>'));N("datawindow",U('<rect x="1.8" y="2.5" width="12.4" height="11" rx="1.5"/><path d="M4.5 5.5h4M4.5 8h7M4.5 10.5h5.5"/>'));N("camera",U('<path d="M5.5 4 6.5 2.5h3L10.5 4h3A1 1 0 0 1 14.5 5v7.5a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z"/><circle cx="8" cy="8.5" r="2.6"/>'));N("gear",U('<path d="M6.55 1.4h2.9l.32 1.72c.48.14.92.38 1.3.7l1.66-.55 1.45 2.5-1.35 1.1c.08.34.12.7.12 1.07s-.04.73-.12 1.07l1.35 1.1-1.45 2.5-1.66-.55a4.3 4.3 0 0 1-1.3.7L9.45 14.6h-2.9l-.32-1.72a4.3 4.3 0 0 1-1.3-.7l-1.66.55-1.45-2.5 1.35-1.1A4.4 4.4 0 0 1 3.05 7.94c0-.37.04-.73.12-1.07l-1.35-1.1 1.45-2.5 1.66.55c.38-.32.82-.56 1.3-.7L6.55 1.4z"/><circle cx="8" cy="8" r="2.2"/>'));N("search",U('<circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3.5 3.5"/>'));N("bell",U('<path d="M8 2a4 4 0 0 0-4 4v2.5L2.5 11v1h11v-1L12 8.5V6a4 4 0 0 0-4-4z"/><path d="M6.5 13.5a1.5 1.5 0 0 0 3 0"/>'));N("market-open",R('<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>'));N("market-pre",R('<path d="M12 2v8"/><path d="m4.93 10.93 1.41 1.41"/><path d="M2 18h2"/><path d="M20 18h2"/><path d="m19.07 10.93-1.41 1.41"/><path d="M22 22H2"/><path d="m8 6 4-4 4 4"/><path d="M16 18a4 4 0 0 0-8 0"/>'));N("market-post",R('<path d="M12 10V2"/><path d="m4.93 10.93 1.41 1.41"/><path d="M2 18h2"/><path d="M20 18h2"/><path d="m19.07 10.93-1.41 1.41"/><path d="M22 22H2"/><path d="m16 14-4 4-4-4"/><path d="M16 6a4 4 0 0 0-8 0"/>'));N("market-extended",R('<path d="M22 22H2"/><path d="M12 3a5 5 0 0 0 7.5 7.5A7.5 7.5 0 1 1 12 3Z"/>'));N("market-closed",R('<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>'));N("market-holiday",R('<path d="m10 20-1.25-2.5L6 16"/><path d="M10 4 8.75 6.5 6 8"/><path d="m14 20 1.25-2.5L18 16"/><path d="m14 4 1.25 2.5L18 8"/><path d="m17 10-5 5-5-5"/><path d="M4 12h16"/>'));N("chevron-right",U('<path d="m6 3.5 4.5 4.5L6 12.5"/>'));N("chevron-left",U('<path d="M10 3.5 5.5 8l4.5 4.5"/>'));N("chevron-down",U('<path d="M3.5 6 8 10.5 12.5 6"/>'));N("chevron-up",U('<path d="M3.5 10 8 5.5 12.5 10"/>'));N("chevrons-right",U('<path d="m4 3.5 4.5 4.5L4 12.5"/><path d="m8.5 3.5 4.5 4.5-4.5 4.5"/>'));N("chevrons-left",U('<path d="M12 3.5 7.5 8l4.5 4.5"/><path d="M7.5 3.5 3 8l4.5 4.5"/>'));N("check",U('<path d="m2.8 8.4 3.4 3.4 7-7.6"/>'));N("close",U('<path d="m3.8 3.8 8.4 8.4M12.2 3.8l-8.4 8.4"/>'));N("pin",U('<path d="M5.6 2.5h4.8M6.4 2.5v3.6L4.4 8.4v.9h7.2v-.9L9.6 6.1V2.5M8 9.3v4.2"/>'));N("pin-filled",U('<path d="M5.6 2.5h4.8M6.4 2.5v3.6L4.4 8.4v.9h7.2v-.9L9.6 6.1V2.5M8 9.3v4.2"/><path d="M6.4 2.5h3.2v3.6l2 2.3v.9H4.4v-.9l2-2.3z" fill="currentColor" stroke="none"/>'));N("eye",U('<path d="M1.5 8s2.5-5.4 6.5-5.4S14.5 8 14.5 8 12 13.4 8 13.4 1.5 8 1.5 8z"/><circle cx="8" cy="8" r="1.8"/>'));N("eye-off",U('<path d="M1.5 8s2.5-5.4 6.5-5.4S14.5 8 14.5 8 12 13.4 8 13.4 1.5 8 1.5 8z" opacity="0.45"/><path d="m3 13 10-10"/>'));N("lock",U('<rect x="3.2" y="7" width="9.6" height="6.6" rx="1.2"/><path d="M5.6 7V5.2a2.4 2.4 0 0 1 4.8 0V7"/>'));N("unlock",U('<rect x="3.2" y="7" width="9.6" height="6.6" rx="1.2"/><path d="M5.6 7V5.2a2.4 2.4 0 0 1 4.7-.7"/>'));N("trash",U('<path d="M2.5 4.3h11M6.2 4.3V3.1a1 1 0 0 1 1-1h1.6a1 1 0 0 1 1 1v1.2M4.2 4.3l.5 9.1a1.15 1.15 0 0 0 1.15 1.1h4.3a1.15 1.15 0 0 0 1.15-1.1l.5-9.1M6.5 7v4.5M9.5 7v4.5"/>'));N("group",U('<path d="M1.8 4.5V2.4a.6.6 0 0 1 .6-.6h2.1M11.5 1.8h2.1a.6.6 0 0 1 .6.6v2.1M14.2 11.5v2.1a.6.6 0 0 1-.6.6h-2.1M4.5 14.2H2.4a.6.6 0 0 1-.6-.6v-2.1"/><rect x="4" y="4" width="4.2" height="4.2" rx="0.7"/><rect x="7.8" y="7.8" width="4.2" height="4.2" rx="0.7"/>'));N("ungroup",U('<rect x="1.6" y="1.6" width="6.2" height="6.2" rx="0.9"/><rect x="8.2" y="8.2" width="6.2" height="6.2" rx="0.9" stroke-dasharray="2 1.5"/>'));N("clone",U('<rect x="5.5" y="5.5" width="9" height="9" rx="1.2"/><path d="M11 5.5v-3a1 1 0 0 0-1-1H2.5a1 1 0 0 0-1 1V10a1 1 0 0 0 1 1h3"/>'));N("arrow-up",U('<path d="M8 13.2V3M4.2 6.8 8 3l3.8 3.8"/>'));N("arrow-down",U('<path d="M8 2.8V13M4.2 9.2 8 13l3.8-3.8"/>'));N("move-vertical",U('<path d="M8 2.5v11M5 5.5 8 2.5l3 3M5 10.5l3 3 3-3"/>'));N("move",U('<path d="M8 1.8v12.4M1.8 8h12.4M5.6 4.2 8 1.8l2.4 2.4M5.6 11.8 8 14.2l2.4-2.4M4.2 5.6 1.8 8l2.4 2.4M11.8 5.6 14.2 8l-2.4 2.4"/>'));N("pen",U('<path d="m10.8 2.2 3 3-8 8-3.6.6.6-3.6z"/><path d="m9.2 3.8 3 3"/>'));N("wave",U('<path d="M1.5 10.4c1.6 0 1.9-4.8 3.4-4.8s1.8 4.8 3.4 4.8 1.8-4.8 3.4-4.8 1.6 4.8 2.8 4.8"/>'));N("folder-plus",U('<path d="M1.6 4.4a1 1 0 0 1 1-1h2.7l1.3 1.7h6.8a1 1 0 0 1 1 1v6.5a1 1 0 0 1-1 1h-10.8a1 1 0 0 1-1-1z"/><path d="M8 7.6v3.6M6.2 9.4h3.6"/>'));N("folder-minus",U('<path d="M1.6 4.4a1 1 0 0 1 1-1h2.7l1.3 1.7h6.8a1 1 0 0 1 1 1v6.5a1 1 0 0 1-1 1h-10.8a1 1 0 0 1-1-1z"/><path d="M6.2 9.4h3.6"/>'));N("collapse",U('<path d="M3 8h10"/>'));N("expand",U('<rect x="2.2" y="2.2" width="11.6" height="11.6" rx="1.4"/><path d="M8 5.4v5.2M5.4 8h5.2"/>'));N("plus",U('<path d="M8 2.8v10.4M2.8 8h10.4"/>'));N("minus",U('<path d="M2.8 8h10.4"/>'));N("maximize",U('<path d="M2.5 6V3a.5.5 0 0 1 .5-.5h3M10 2.5h3a.5.5 0 0 1 .5.5v3M13.5 10v3a.5.5 0 0 1-.5.5h-3M6 13.5H3a.5.5 0 0 1-.5-.5v-3"/>'));N("restore",U('<path d="M6.2 2.5v3.7H2.5M9.8 13.5V9.8h3.7M13.5 6.2H9.8V2.5M2.5 9.8h3.7v3.7"/>'));N("star",U('<path d="M8 2.2l1.75 3.55 3.9.55-2.8 2.75.65 3.9L8 11.1l-3.5 1.85.65-3.9-2.8-2.75 3.9-.55z"/>'));N("star-filled",U('<path d="M8 2.2l1.75 3.55 3.9.55-2.8 2.75.65 3.9L8 11.1l-3.5 1.85.65-3.9-2.8-2.75 3.9-.55z"/>','fill="currentColor"'));N("grip",U('<circle cx="6" cy="3.5" r="1"/><circle cx="10" cy="3.5" r="1"/><circle cx="6" cy="8" r="1"/><circle cx="10" cy="8" r="1"/><circle cx="6" cy="12.5" r="1"/><circle cx="10" cy="12.5" r="1"/>','fill="currentColor" stroke="none"'));N("kebab",U('<circle cx="8" cy="3.2" r="1.2"/><circle cx="8" cy="8" r="1.2"/><circle cx="8" cy="12.8" r="1.2"/>','fill="currentColor" stroke="none"'));N("burger",U('<path d="M2.5 4.5h11M2.5 8h11M2.5 11.5h11"/>'));N("info",U('<path d="M8 7.4v4.4"/><circle cx="8" cy="4.6" r="0.9" fill="currentColor" stroke="none"/>'));N("reset",U('<path d="M2 8a6 6 0 1 0 6-6 6.5 6.5 0 0 0-4.5 1.83L2 5.33"/><path d="M2 2v3.33h3.33"/>'));N("pane-collapse",U('<path d="M2.6 9.4h4v4M13.4 6.6h-4v-4"/><path d="m9.4 6.6 4.2-4.2M2.4 13.6l4.2-4.2"/>'));N("pane-expand",U('<path d="M9.8 2.4h3.8v3.8M6.2 13.6H2.4V9.8"/><path d="m13.6 2.4-4.4 4.4M2.4 13.6l4.4-4.4"/>'));N("cursor",R('<path d="M5 3l6 16 2-6 6-2z"/>','fill="currentColor" stroke="none"'));N("ruler",R('<path d="M21.3 15.3 8.7 2.7a1 1 0 0 0-1.4 0L2.7 7.3a1 1 0 0 0 0 1.4l12.6 12.6a1 1 0 0 0 1.4 0l4.6-4.6a1 1 0 0 0 0-1.4Z"/><path d="m7.5 10.5 2 2"/><path d="m10.5 7.5 2 2"/><path d="m13.5 4.5 2 2"/><path d="m4.5 13.5 2 2"/>'));N("magnet",R('<path d="m6 15-4-4 6.75-6.77a7.79 7.79 0 0 1 11 11L13 22l-4-4 6.39-6.36a2.14 2.14 0 0 0-3-3L6 15"/><path d="m5 8 4 4"/><path d="m12 15 4 4"/>'));N("eraser",R('<path d="m7 21-4.3-4.3a1 1 0 0 1 0-1.4L13 5a2 2 0 0 1 2.8 0l4.2 4.2a2 2 0 0 1 0 2.8L12 20"/><path d="M22 21H7"/><path d="m5 11 9 9"/>'));N("pen-lock",R('<path d="M13.8 4.2a2.1 2.1 0 0 1 3 3L8.5 15.5l-3.5 1 1-3.5Z"/><rect x="13" y="14.5" width="8" height="6" rx="1.2"/><path d="M15 14.5v-1.6a2 2 0 0 1 4 0v1.6"/>'));N("pen-sync",R('<path d="M13.8 4.2a2.1 2.1 0 0 1 3 3L8.5 15.5l-3.5 1 1-3.5Z"/><rect x="12.5" y="13.5" width="6" height="4.8" rx="1"/><path d="M15.5 18.3v1a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1v-2.8a1 1 0 0 0-1-1h-1"/>'));N("brush",R('<path d="M9.5 12 17 4.5a2.12 2.12 0 0 1 3 3L12.5 15"/><path d="M7 14a3 3 0 0 0-3 3c0 1.3-1.2 1.5-1.5 2 .8.9 2 1.5 3.5 1.5a3.5 3.5 0 0 0 3.5-3.5 3 3 0 0 0-2.5-3Z"/>'));N("bucket",R('<path d="m18.5 11.5-7-7L4 12a1.8 1.8 0 0 0 0 2.5l5 5a1.8 1.8 0 0 0 2.5 0Z"/><path d="m5 5 4 4"/><path d="M3.5 13.5h13"/><path d="M21 17.5c0 1.1-.9 2-2 2s-2-.9-2-2c0-1 1.2-1.7 2-3 .8 1.3 2 2 2 3Z"/>'));N("type",R('<path d="M5 6V4.5h14V6"/><path d="M12 4.5v15"/><path d="M9.5 19.5h5"/>'));N("bold",R('<path d="M7 5h6a3.5 3.5 0 0 1 0 7H7Z"/><path d="M7 12h7a3.5 3.5 0 0 1 0 7H7Z"/>','stroke-width="2.4"'));N("italic",R('<path d="M15 5h-5M14 19H9M14.5 5 10 19"/>','stroke-width="2.2"'));N("price-delta",R('<path d="M12 4v16"/><path d="M8 8l4-4 4 4"/><path d="M8 16l4 4 4-4"/>'));N("date-delta",R('<path d="M4 12h16"/><path d="M8 8l-4 4 4 4"/><path d="M16 8l4 4-4 4"/>'));N("bring-front",R('<rect x="8.5" y="8.5" width="7" height="7" rx="1.5"/><path d="M4.5 10.5V6a1.5 1.5 0 0 1 1.5-1.5h4.5"/><path d="M19.5 13.5V18a1.5 1.5 0 0 1-1.5 1.5h-4.5"/>'));N("send-back",R('<rect x="8.5" y="8.5" width="7" height="7" rx="1.5" fill="currentColor" stroke="none" opacity="0.35"/><path d="M4.5 10.5V6a1.5 1.5 0 0 1 1.5-1.5h4.5"/><path d="M19.5 13.5V18a1.5 1.5 0 0 1-1.5 1.5h-4.5"/><rect x="8.5" y="8.5" width="7" height="7" rx="1.5"/>'));N("r-squared",'<svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" stroke="none"><text x="2.5" y="17.5" font-size="14" font-family="serif">R\xB2</text></svg>');N("bands",R('<path d="M3 6h18"/><path d="M3 18h18"/><path d="M3 12h18" stroke-dasharray="3 3"/>'));N("dedekind",R('<path d="M2 20h20"/><path d="M4 20a8 8 0 0 1 16 0"/><path d="M8 20a4 4 0 0 1 8 0"/><path d="M12 4v16"/>'));N("sonic",R('<circle cx="15" cy="12" r="4"/><circle cx="12" cy="12" r="2.5"/><path d="M8 5v14"/>'));N("supersonic",R('<circle cx="16" cy="12" r="3.5"/><path d="M6 12 15 6M6 12 15 18"/>'));var Ke=[{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"}],B=[{path:"style.lineColor",label:"Line color",kind:"color",group:"line"},{path:"style.lineWidth",label:"Line width",kind:"number",min:1,max:10,step:1,group:"line"},{path:"style.lineStyle",label:"Line style",kind:"lineStyle",options:Ke,group:"line"}],ue=[{path:"style.fillColor",label:"Fill color",kind:"color",group:"fill"}],Ct=[{value:"small",label:"Small"},{value:"normal",label:"Normal"},{value:"large",label:"Large"},{value:"huge",label:"Huge"}],H=[{path:"text.value",label:"Text",kind:"text",group:"text"},{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Ct,group:"text"},{path:"text.bold",label:"Bold",kind:"boolean",group:"text"},{path:"text.italic",label:"Italic",kind:"boolean",group:"text"}];function ne(r,e,t,n,i,o){let s=i-t,a=o-n,l=s*s+a*a;if(l<=1e-9)return Math.hypot(r-t,e-n);let c=((r-t)*s+(e-n)*a)/l;return c=c<0?0:c>1?1:c,Math.hypot(r-(t+c*s),e-(n+c*a))}function Hr(r,e,t){let n=1/0;for(let i=1;i<t.length;i+=1){let o=t[i-1],s=t[i],a=ne(r,e,o[0],o[1],s[0],s[1]);a<n&&(n=a);}return n}function Fe(r,e,t,n,i,o,s=0){let a=Math.min(t,i)-s,l=Math.max(t,i)+s,c=Math.min(n,o)-s,d=Math.max(n,o)+s;return r>=a&&r<=l&&e>=c&&e<=d}function Vt(r,e,t){let n=false;for(let i=0,o=t.length-1;i<t.length;o=i,i+=1){let s=t[i],a=t[o];s[1]>e!=a[1]>e&&r<(a[0]-s[0])*(e-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}return n}function pd(r,e,t,n,i,o,s,a){let l=t-r,c=n-e,d=s-i,u=a-o,h=d*c-u*l;if(Math.abs(h)<1e-9)return null;let p=((o-e)*l-(i-r)*c)/h;return p<0||p>1?null:[i+p*d,o+p*u]}function Y(r,e,t,n=6){for(let i=0;i<t.length;i+=1){let o=t[i];if(Math.hypot(r-o[0],e-o[1])<=n)return i}return -1}function xe(r,e,t,n,i,o,s){if(i==="none")return [r,e,t,n];let a=t-r,l=i==="left"||i==="both",c=i==="right"||i==="both";if(Math.abs(a)<1e-6){if(l&&c)return [r,0,t,s];let m=n>=e;return c?m?[r,e,t,s]:[r,e,t,0]:m?[r,0,t,n]:[r,s,t,n]}let d=(n-e)/a,u=m=>e+d*(m-r),h=l?-2:Math.min(r,t),p=c?o+2:Math.max(r,t);return [h,u(h),p,u(p)]}var Vs=class extends G{constructor(){super(...arguments);this.type="trendline";}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?null:[t.xOf(n.time),o,t.xOf(i.time),s]}hitTest(t,n,i,o){let s=this.pixels(i);return s!=null&&ne(t,n,s[0],s[1],s[2],s[3])<=o}handlePoints(t){let n=this.pixels(t);return n?[[n[0],n[1]],[n[2],n[3]]]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.pixels(t);if(!n)return null;let i=Math.min(n[0],n[2]),o=Math.min(n[1],n[3]);return {x:i,y:o,w:Math.abs(n[2]-n[0]),h:Math.abs(n[3]-n[1])}}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,{path:"style.arrowRight",label:"Arrow",kind:"boolean",group:"line"},...H]}}};var _s=class extends G{constructor(){super(...arguments);this.type="hline";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"y"}]}}y(t){let n=this.anchors[0];return n?t.yOf(n.price,this.paneId):null}hitTest(t,n,i,o){let s=this.y(i);return s!=null&&Math.abs(n-s)<=o}handlePoints(t){let n=this.anchors[0],i=this.y(t);return !n||i==null?[]:[[t.xOf(n.time),i]]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.y(t);return n==null?null:{x:0,y:n-1,w:t.width,h:2}}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){return null}schema(){return {fields:[...B,...H]}}};var Bs=class extends G{constructor(){super(...arguments);this.type="ray";}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?null:[t.xOf(n.time),o,t.xOf(i.time),s]}hitTest(t,n,i,o){let s=this.pixels(i);if(!s)return false;let[a,l,c,d]=xe(s[0],s[1],s[2],s[3],"right",i.width,i.height);return ne(t,n,a,l,c,d)<=o}handlePoints(t){let n=this.pixels(t);return n?[[n[0],n[1]],[n[2],n[3]]]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.pixels(t);return n?{x:Math.min(n[0],n[2]),y:Math.min(n[1],n[3]),w:Math.abs(n[2]-n[0]),h:Math.abs(n[3]-n[1])}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,...H]}}};var Mn=class extends G{anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=e.yOf(t.price,this.paneId),o=e.yOf(n.price,this.paneId);return i==null||o==null?null:[e.xOf(t.time),i,e.xOf(n.time),o]}hitTest(e,t,n,i){let o=this.pixels(n);return o!=null&&ne(e,t,o[0],o[1],o[2],o[3])<=i}handlePoints(e){let t=this.pixels(e);return t?[[t[0],t[1]],[t[2],t[3]]]:[]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.pixels(e);return t?{x:Math.min(t[0],t[2]),y:Math.min(t[1],t[3]),w:Math.abs(t[2]-t[0]),h:Math.abs(t[3]-t[1])}:null}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[...B,...H]}}};var Hs=class extends Mn{constructor(){super(...arguments);this.type="extendedline";}hitTest(t,n,i,o){let s=this.pixels(i);if(!s)return false;let[a,l,c,d]=xe(s[0],s[1],s[2],s[3],"both",i.width,i.height);return ne(t,n,a,l,c,d)<=o}timeExtent(){return null}};var zs=class extends G{constructor(){super(...arguments);this.type="vline";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"x"}]}}x(t){let n=this.anchors[0];return n?t.xOf(n.time):null}hitTest(t,n,i,o){let s=this.x(i);return s!=null&&Math.abs(t-s)<=o}handlePoints(t){let n=this.anchors[0],i=this.x(t);if(!n||i==null)return [];let o=t.yOf(n.price,this.paneId);return o==null?[]:[[i,o]]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.x(t);return n==null?null:{x:n-1,y:0,w:2,h:t.height}}priceRange(){return null}schema(){return {fields:[...B,...H]}}};var $s=class extends G{constructor(){super(...arguments);this.type="hray";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}pt(t){let n=this.anchors[0];if(!n)return null;let i=t.yOf(n.price,this.paneId);return i==null?null:[t.xOf(n.time),i]}hitTest(t,n,i,o){let s=this.pt(i);return s!=null&&ne(t,n,s[0],s[1],i.width,s[1])<=o}handlePoints(t){let n=this.pt(t);return n?[n]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.pt(t);return n?{x:n[0],y:n[1]-1,w:Math.max(0,t.width-n[0]),h:2}:null}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){let t=this.anchors[0];return t?{min:t.time,max:Number.POSITIVE_INFINITY}:null}schema(){return {fields:[...B,...H]}}};var Ws=class extends G{constructor(){super(...arguments);this.type="crossline";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}pt(t){let n=this.anchors[0];if(!n)return null;let i=t.yOf(n.price,this.paneId);return i==null?null:[t.xOf(n.time),i]}hitTest(t,n,i,o){let s=this.pt(i);return s!=null&&(Math.abs(n-s[1])<=o||Math.abs(t-s[0])<=o)}handlePoints(t){let n=this.pt(t);return n?[n]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.pt(t);return n?{x:n[0]-1,y:n[1]-1,w:2,h:2}:null}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){return null}schema(){return {fields:[...B,...H]}}};var Gs=class extends Mn{constructor(){super(...arguments);this.type="infoline";}};var Us=class extends Mn{constructor(){super(...arguments);this.type="trendangle";}};var Ys=class extends G{constructor(){super(...arguments);this.type="box";}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}rect(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?null:{x1:t.xOf(n.time),y1:o,x2:t.xOf(i.time),y2:s}}hitTest(t,n,i,o){let s=this.rect(i);return s?this.style.fillColor&&Fe(t,n,s.x1,s.y1,s.x2,s.y2)?true:[[s.x1,s.y1,s.x2,s.y1],[s.x2,s.y1,s.x2,s.y2],[s.x2,s.y2,s.x1,s.y2],[s.x1,s.y2,s.x1,s.y1]].some(l=>ne(t,n,l[0],l[1],l[2],l[3])<=o):false}handlePoints(t){let n=this.rect(t);return n?[[n.x1,n.y1],[n.x2,n.y2]]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.rect(t);return n?{x:Math.min(n.x1,n.x2),y:Math.min(n.y1,n.y2),w:Math.abs(n.x2-n.x1),h:Math.abs(n.y2-n.y1)}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B.map(t=>({...t,label:t.label.replace("Line","Border")})),{path:"style.fillColor",label:"Fill color",kind:"color",group:"fill"},...H]}}};var Kx={tiny:10,small:12,normal:14,large:18,huge:24,auto:14},kn=class extends G{defaultLabel(){return "Text"}labelText(){return this.text?.value??this.defaultLabel()}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}box(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);if(n==null)return null;let i=Kx[this.text?.size??"normal"]??14,o=this.labelText().split(`
2
2
  `),s=Math.max(1,...o.map(a=>a.length));return {x:e.xOf(t.time),y:n,w:Math.max(12,s*i*.6)+8,h:o.length*i*1.4+4}}hitTest(e,t,n,i){let o=this.box(n);return o!=null&&Fe(e,t,o.x,o.y,o.x+o.w,o.y+o.h)}handlePoints(e){let t=this.anchors[0],n=t?e.yOf(t.price,this.paneId):null;return t&&n!=null?[[e.xOf(t.time),n]]:[]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){return this.box(e)}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}};var an=class extends kn{constructor(t){super(t);this.type="text";this.text||(this.text={...sn(),size:"large"});}schema(){return {fields:[...H],textIsContent:true}}};var Zn=class extends kn{constructor(t){super(t);this.type="note";this.text||(this.text=sn("Note"));}defaultLabel(){return "Note"}schema(){return {fields:[...B,...ue,...H],textIsContent:true}}};var Jn=class extends kn{constructor(){super(...arguments);this.type="pricelabel";}labelText(){let t=this.anchors[0]?.price;return t==null?"0.00":t.toFixed(2)}schema(){return {fields:[...B,...ue,...H.filter(t=>t.path!=="text.value")]}}};var Xx={tiny:10,small:12,normal:14,large:18,huge:24,auto:14},ut=class extends G{constructor(e){super(e),this.text||(this.text=sn(this.defaultLabel()));}defaultLabel(){return "Callout"}labelText(){return this.text?.value??this.defaultLabel()}anchorSchema(){return {min:2,max:2,slots:[{role:"target",free:"both"},{role:"box",free:"both"}]}}box(e){let t=this.anchors[1];if(!t)return null;let n=e.yOf(t.price,this.paneId);if(n==null)return null;let i=Xx[this.text?.size??"normal"]??14,o=this.labelText().split(`
3
- `),s=Math.max(1,...o.map(c=>c.length)),a=Math.max(20,s*i*.6)+16,l=o.length*i*1.4+12;return {x:e.xOf(t.time)-a/2,y:n-l/2,w:a,h:l}}points(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=e.yOf(t.price,this.paneId),o=e.yOf(n.price,this.paneId);return i==null||o==null?null:[[e.xOf(t.time),i],[e.xOf(n.time),o]]}hitTest(e,t,n,i){let o=this.box(n);if(o&&Fe(e,t,o.x,o.y,o.x+o.w,o.y+o.h,i))return true;let s=this.points(n);return s!=null&&ne(e,t,s[0][0],s[0][1],s[1][0],s[1][1])<=i}handlePoints(e){let t=this.points(e);return t?[t[0]]:[]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}translateBody(e,t,n){let i=n[0],o=n[1];return !i||!o?n.map(s=>({time:s.time+e,price:s.price+t})):[{time:i.time,price:i.price},{time:o.time+e,price:o.price+t}]}bounds(e){return this.box(e)}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[...B,...ue,...H],textIsContent:true}}};var _t=class extends ut{constructor(){super(...arguments);this.type="callout";}};var Qn=class extends ut{constructor(){super(...arguments);this.type="pricenote";}defaultLabel(){return ""}labelText(){let t=this.anchors[0]?.price;return t==null?"0.00":t.toFixed(2)}schema(){return {fields:[...B,...ue,...H.filter(t=>t.path!=="text.value")]}}};var er=class extends ut{constructor(){super(...arguments);this.type="comment";}defaultLabel(){return "Comment"}};var tr=class extends ut{constructor(){super(...arguments);this.type="signpost";}defaultLabel(){return "Signpost"}};var he=class extends G{hitTest(e,t,n,i){let o=this.geometry(n);return o?this.style.fillColor&&o.fill&&Vt(e,t,o.fill)?true:o.segments.some(s=>ne(e,t,s[0],s[1],s[2],s[3])<=i):false}handlePoints(e){let t=[];for(let n of this.anchors){let i=e.yOf(n.price,this.paneId);if(i==null)return [];t.push([e.xOf(n.time),i]);}return t}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),i=t.map(a=>a[1]),o=Math.min(...n),s=Math.min(...i);return {x:o,y:s,w:Math.max(...n)-o,h:Math.max(...i)-s}}};var Ks=class extends he{constructor(){super(...arguments);this.type="parallelchannel";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"offset",free:"y"}]}}offset(){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[2];return !t||!n||!i?0:i.price-(t.price+n.price)/2}handlePoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return [];let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return [];let a=[[t.xOf(n.time),o],[t.xOf(i.time),s]],l=this.anchors[2];if(l){let c=t.yOf(l.price,this.paneId);c!=null&&a.push([t.xOf((n.time+i.time)/2),c]);}return a}timeExtent(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.time,n.time),max:Math.max(t.time,n.time)}}geometry(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=this.offset(),s=t.xOf(n.time),a=t.xOf(i.time),l=t.yOf(n.price,this.paneId),c=t.yOf(i.price,this.paneId),d=t.yOf(n.price+o,this.paneId),u=t.yOf(i.price+o,this.paneId);return l==null||c==null||d==null||u==null?null:{segments:[[s,l,a,c],[s,d,a,u]],fill:[[s,l],[a,c],[a,u],[s,d]]}}priceRange(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=this.offset(),o=[t.price,n.price,t.price+i,n.price+i],s=this.anchors[2];return s&&o.push(s.price),{min:Math.min(...o),max:Math.max(...o)}}schema(){return {fields:[...B,...ue,...H]}}};var Xs=class extends he{constructor(){super(...arguments);this.type="disjointchannel";}anchorSchema(){return {min:4,max:4,slots:[{role:"top1",free:"both"},{role:"top2",free:"both"},{role:"bot1",free:"both"},{role:"bot2",free:"both"}]}}seg(t,n,i){let o=this.anchors[t],s=this.anchors[n];if(!o||!s)return null;let a=i.yOf(o.price,this.paneId),l=i.yOf(s.price,this.paneId);return a==null||l==null?null:[i.xOf(o.time),a,i.xOf(s.time),l]}geometry(t){let n=this.seg(0,1,t),i=this.seg(2,3,t),o=[n,i].filter(a=>a!=null);if(o.length===0)return null;let s=n&&i?[[n[0],n[1]],[n[2],n[3]],[i[2],i[3]],[i[0],i[1]]]:null;return {segments:o,fill:s}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B,...ue,...H]}}};var js=class extends he{constructor(){super(...arguments);this.type="flattopbottom";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"flat",free:"y"}]}}handlePoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return [];let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return [];let a=[[t.xOf(n.time),o],[t.xOf(i.time),s]],l=this.anchors[2];if(l){let c=t.yOf(l.price,this.paneId);c!=null&&a.push([t.xOf((n.time+i.time)/2),c]);}return a}timeExtent(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.time,n.time),max:Math.max(t.time,n.time)}}geometry(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.xOf(n.time),s=t.xOf(i.time),a=t.yOf(n.price,this.paneId),l=t.yOf(i.price,this.paneId);if(a==null||l==null)return null;let c=this.anchors[2];if(!c)return {segments:[[o,a,s,l]],fill:null};let d=t.yOf(c.price,this.paneId);return d==null?null:{segments:[[o,a,s,l],[o,d,s,d]],fill:[[o,a],[s,l],[s,d],[o,d]]}}priceRange(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=[t.price,n.price],o=this.anchors[2];return o&&i.push(o.price),{min:Math.min(...i),max:Math.max(...i)}}schema(){return {fields:[...B,...ue,...H]}}};var jx=2;function Hp(){return {midColor:J,midStyle:"solid",upperColor:z,upperStyle:"solid",lowerColor:W,lowerStyle:"solid",upperFill:`${z}26`,lowerFill:`${W}26`,showR2:true}}function zp(r){let e=r.length;if(e<2)return null;let t=0,n=0,i=0,o=0,s=0;for(let m=0;m<e;m+=1){let f=r[m].close;t+=m,n+=f,i+=m*f,o+=m*m,s+=f*f;}let a=e*o-t*t,l=a===0?0:(e*i-t*n)/a,c=(n-l*t)/e,d=0;for(let m=0;m<e;m+=1){let f=r[m].close-(c+l*m);d+=f*f;}let u=Math.sqrt(d/e),h=Math.sqrt(a*(e*s-n*n)),p=h===0?0:(e*i-t*n)/h;return {t0:r[0].time,t1:r[e-1].time,mid0:c,mid1:c+l*(e-1),dev:jx*u,r2:Math.max(0,Math.min(1,p*p)),n:e}}var ln=class extends G{constructor(t){super(t);this.type="regressionchannel";this.cachedRange=null;this.reg||(this.reg=Hp());}anchorSchema(){return {min:2,max:2,slots:[{role:"start",free:"x"},{role:"end",free:"x"}]}}fit(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=Math.min(n.time,i.time),s=Math.max(n.time,i.time),a=t.barsInRange?.(o,s)??null,l=a?zp(a):null;return l&&(this.cachedRange={min:Math.min(l.mid0,l.mid1)-l.dev,max:Math.max(l.mid0,l.mid1)+l.dev}),l}layout(t){let n=this.fit(t);if(!n)return null;let i=t.yOf(n.mid0,this.paneId),o=t.yOf(n.mid1,this.paneId),s=t.yOf(n.mid0+n.dev,this.paneId),a=t.yOf(n.mid1+n.dev,this.paneId),l=t.yOf(n.mid0-n.dev,this.paneId),c=t.yOf(n.mid1-n.dev,this.paneId);return i==null||o==null||s==null||a==null||l==null||c==null?null:{x0:t.xOf(n.t0),x1:t.xOf(n.t1),midY0:i,midY1:o,upperY0:s,upperY1:a,lowerY0:l,lowerY1:c,r2:n.r2,showR2:this.reg.showR2}}band(t){let n=this.layout(t);return n?[[n.x0,n.upperY0],[n.x1,n.upperY1],[n.x1,n.lowerY1],[n.x0,n.lowerY0]]:null}hitTest(t,n,i,o){let s=this.layout(i);if(!s)return false;let a=[[s.x0,s.upperY0],[s.x1,s.upperY1],[s.x1,s.lowerY1],[s.x0,s.lowerY0]];return Vt(t,n,a)?true:[[s.x0,s.midY0,s.x1,s.midY1],[s.x0,s.upperY0,s.x1,s.upperY1],[s.x0,s.lowerY0,s.x1,s.lowerY1]].some(c=>ne(t,n,c[0],c[1],c[2],c[3])<=o)}handlePoints(t){let n=this.layout(t);if(n)return [[n.x0,n.midY0],[n.x1,n.midY1]];let i=[];for(let o of this.anchors){let s=t.yOf(o.price,this.paneId);if(s==null)return [];i.push([t.xOf(o.time),s]);}return i}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.band(t);if(!n)return null;let i=n.map(l=>l[0]),o=n.map(l=>l[1]),s=Math.min(...i),a=Math.min(...o);return {x:s,y:a,w:Math.max(...i)-s,h:Math.max(...o)-a}}priceRange(){if(this.cachedRange)return this.cachedRange;let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[{path:"reg.midColor",label:"Midline color",kind:"color",group:"line"},{path:"reg.midStyle",label:"Midline style",kind:"lineStyle",group:"line"},{path:"reg.upperColor",label:"Upper line color",kind:"color",group:"line"},{path:"reg.upperStyle",label:"Upper line style",kind:"lineStyle",group:"line"},{path:"reg.lowerColor",label:"Lower line color",kind:"color",group:"line"},{path:"reg.lowerStyle",label:"Lower line style",kind:"lineStyle",group:"line"},{path:"reg.upperFill",label:"Upper fill",kind:"color",group:"fill"},{path:"reg.lowerFill",label:"Lower fill",kind:"color",group:"fill"},{path:"reg.showR2",label:"Show R\xB2",kind:"boolean",group:"behavior"}]}}writeProps(){return {...this.reg}}readProps(t){this.reg={...Hp(),...t};}};var $p=`${Je}00`;function Wp(){return {midColor:Je,midStyle:"solid",multiplier:1,upperColor:$p,upperStyle:"solid",lowerColor:$p,lowerStyle:"solid",bandFill:`${Je}33`}}function Gp(r,e){let t=r.length;if(t<1)return null;let n=0;for(let c of r)n+=c.volume>0?c.volume:0;let i=n>0,o=0,s=0,a=0,l=[];for(let c=0;c<t;c+=1){let d=r[c],u=(d.high+d.low+d.close)/3,h=i?Math.max(0,d.volume):1;o+=h,s+=u*h,a+=u*u*h;let p=o>0?s/o:u,m=o>0?Math.max(0,a/o-p*p):0,f=Math.sqrt(m)*e;l.push({time:d.time,mid:p,upper:p+f,lower:p-f});}return l}var nr=class extends G{constructor(t){super(t);this.type="anchoredvwap";this.cachedRange=null;this.cachedExtent=null;this.vwap||(this.vwap=Wp());}anchorSchema(){return {min:1,max:1,slots:[{role:"anchor",free:"x"}]}}series(t){let n=this.anchors[0];if(!n)return null;let i=t.barsInRange?.(n.time,Number.POSITIVE_INFINITY)??null;if(!i||i.length<1)return null;let o=Gp(i.map(s=>({time:s.time,high:s.high,low:s.low,close:s.close,volume:s.volume??0})),this.vwap.multiplier);if(o&&o.length>0){let s=1/0,a=-1/0;for(let l of o)l.lower<s&&(s=l.lower),l.upper>a&&(a=l.upper);this.cachedRange={min:s,max:a},this.cachedExtent={min:o[0].time,max:o[o.length-1].time};}return o}layout(t){let n=this.series(t);if(!n)return null;let i=[],o=[],s=[];for(let a of n){let l=t.xOf(a.time),c=t.yOf(a.mid,this.paneId),d=t.yOf(a.upper,this.paneId),u=t.yOf(a.lower,this.paneId);c==null||d==null||u==null||(i.push([l,c]),o.push([l,d]),s.push([l,u]));}return i.length>0?{mid:i,upper:o,lower:s}:null}bandPolygon(t){return [...t.upper,...[...t.lower].reverse()]}hitTest(t,n,i,o){let s=this.layout(i);return s?Vt(t,n,this.bandPolygon(s))?true:md(t,n,s.mid,o)||md(t,n,s.upper,o)||md(t,n,s.lower,o):false}handlePoints(t){let n=this.layout(t);if(n&&n.mid.length>0)return [n.mid[0]];let i=this.anchors[0];if(!i)return [];let o=t.yOf(i.price,this.paneId);return o==null?[]:[[t.xOf(i.time),o]]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.layout(t);if(!n)return null;let i=[...n.upper,...n.lower],o=i.map(c=>c[0]),s=i.map(c=>c[1]),a=Math.min(...o),l=Math.min(...s);return {x:a,y:l,w:Math.max(...o)-a,h:Math.max(...s)-l}}priceRange(){return this.cachedRange}timeExtent(){return this.cachedExtent}schema(){return {fields:[{path:"vwap.midColor",label:"VWAP color",kind:"color",group:"line"},{path:"vwap.midStyle",label:"VWAP style",kind:"lineStyle",group:"line"},{path:"vwap.multiplier",label:"Band multiplier",kind:"number",min:.5,max:5,step:.5,group:"behavior"},{path:"vwap.upperColor",label:"Upper band color",kind:"color",group:"line"},{path:"vwap.lowerColor",label:"Lower band color",kind:"color",group:"line"},{path:"vwap.bandFill",label:"Band fill",kind:"color",group:"fill"}]}}writeProps(){return {...this.vwap}}readProps(t){this.vwap={...Wp(),...t};}};function md(r,e,t,n){for(let i=1;i<t.length;i+=1)if(ne(r,e,t[i-1][0],t[i-1][1],t[i][0],t[i][1])<=n)return true;return false}var qx=`${z}66`,Zx=`${W}66`,Jx=`${z}BF`,Qx=`${W}BF`;function Up(){return {rows:24,valueAreaPct:70,widthPct:35,anchor:"left",upColor:qx,downColor:Zx,vaUpColor:Jx,vaDownColor:Qx,showVah:true,vahColor:J,vahStyle:"solid",showVal:true,valColor:J,valStyle:"solid",showPoc:true,pocColor:void 0,pocStyle:"solid",showDevelopingPoc:false,developingPocColor:Ye,developingPocStyle:"dotted",showDevelopingVa:false,developingVaColor:Ye,developingVaStyle:"dotted"}}function e0(r,e){return r<0?0:r>=e?e-1:r}function Yp(r,e,t){let n=r.length,i=0,o=0;for(let d=0;d<n;d+=1){let u=r[d].up+r[d].down;i+=u,u>o&&(o=u);}let s=i*Math.min(1,Math.max(0,t)),a=e,l=e,c=o;for(;c<s&&(a>0||l<n-1);){let d=a>0?r[a-1].up+r[a-1].down:-1,u=l<n-1?r[l+1].up+r[l+1].down:-1;u>d?(l+=1,c+=u):(a-=1,c+=d);}return {vaFrom:a,vaTo:l}}function Kp(r,e,t,n){let i=n.volume;if(!(i>0))return;let o=r.length,s=n.close>=n.open?"up":"down",a=new Set;for(let l of [n.open,n.high,n.low,n.close])a.add(e0(Math.floor((l-e)/t),o));for(let l of a)r[l][s]+=i;}function Xp(r){let e=0,t=0;for(let n=0;n<r.length;n+=1){let i=r[n].up+r[n].down;i>e&&(e=i,t=n);}return e>0?{poc:t,maxTotal:e}:null}function jp(r,e,t){let n=1/0,i=-1/0;for(let p of r)p.volume>0&&(p.low<n&&(n=p.low),p.high>i&&(i=p.high));if(!Number.isFinite(n))return null;let o=i>n?Math.max(1,Math.round(e)):1,s=i>n?(i-n)/o:1,a=Array.from({length:o},(p,m)=>({price:n+m*s,up:0,down:0}));for(let p of r)Kp(a,n,s,p);let l=Xp(a);if(!l)return null;let{poc:c,maxTotal:d}=l,{vaFrom:u,vaTo:h}=Yp(a,c,t);return {rows:a,rowH:s,min:n,maxTotal:d,poc:c,vaFrom:u,vaTo:h}}function qp(r,e,t,n){let i=jp(r,e,t);if(!i)return null;if(!n||r.length<1)return {profile:i,developingPoc:[],developingVaHigh:[],developingVaLow:[]};let{min:o,rowH:s}=i,a=i.rows.length,l=Array.from({length:a},(h,p)=>({price:o+p*s,up:0,down:0})),c=[],d=[],u=[];for(let h of r){Kp(l,o,s,h);let p=Xp(l);if(!p)continue;let{poc:m}=p,{vaFrom:f,vaTo:g}=Yp(l,m,t);c.push({time:h.time,price:l[m].price+s/2}),d.push({time:h.time,price:l[g].price+s}),u.push({time:h.time,price:l[f].price});}return {profile:i,developingPoc:c,developingVaHigh:d,developingVaLow:u}}var at=class extends G{constructor(t){super(t);this.type="fixedrangevp";this.cachedRange=null;this.frvp||(this.frvp=Up());}anchorSchema(){return {min:2,max:2,slots:[{role:"start",free:"x"},{role:"end",free:"x"}]}}barsInSpan(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=Math.min(n.time,i.time),s=Math.max(n.time,i.time),a=t.barsInRange?.(o,s)??null;return !a||a.length<1?null:a.map(l=>({time:l.time,open:l.open,high:l.high,low:l.low,close:l.close,volume:l.volume??0}))}compute(t){let n=this.barsInSpan(t);if(!n)return null;let i=this.frvp,o=i.showDevelopingPoc||i.showDevelopingVa,s=qp(n,i.rows,i.valueAreaPct/100,o);if(s){let{profile:a}=s;this.cachedRange={min:a.min,max:a.min+a.rowH*a.rows.length};}return s}layout(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=this.compute(t);if(!o)return null;let{profile:s}=o,a=Math.min(n.time,i.time),l=Math.max(n.time,i.time),c=t.xOf(a),d=t.xOf(l),u=Math.abs(d-c),h=Math.max(1,Math.min(100,Math.max(0,this.frvp.widthPct))/100*u),p=this.frvp.anchor==="left",m=p?Math.min(c,d):Math.max(c,d),f=p?1:-1,g=[];for(let T=0;T<=s.rows.length;T+=1){let E=t.yOf(s.min+T*s.rowH,this.paneId);if(E==null)return null;g.push(E);}let b=T=>t.yOf(T,this.paneId),y=s.rows[s.vaTo].price+s.rowH,v=s.rows[s.vaFrom].price,S=s.rows[s.poc].price+s.rowH/2,P=T=>{let E=[];for(let x of T){let L=b(x.price);L!=null&&E.push([t.xOf(x.time),L]);}return E};return {x0:Math.min(c,d),x1:Math.max(c,d),anchorX:m,maxW:h,grow:f,profile:s,yEdges:g,vahY:b(y),valY:b(v),pocY:b(S),developingPoc:P(o.developingPoc),developingVaHigh:P(o.developingVaHigh),developingVaLow:P(o.developingVaLow)}}hitTest(t,n,i,o){let s=this.layout(i);if(!s)return false;let a=s.grow===1?s.anchorX:s.anchorX-s.maxW,l=s.grow===1?s.anchorX+s.maxW:s.anchorX,c=Math.min(s.yEdges[0],s.yEdges[s.yEdges.length-1]),d=Math.max(s.yEdges[0],s.yEdges[s.yEdges.length-1]);if(Vt(t,n,[[a,c],[l,c],[l,d],[a,d]]))return true;let u=[[s.x0,s.vahY],[s.x0,s.valY],[s.x0,s.pocY]];for(let[,h]of u)if(h!=null&&ne(t,n,s.x0,h,s.x1,h)<=o)return true;for(let h of [s.developingPoc,s.developingVaHigh,s.developingVaLow])for(let p=1;p<h.length;p+=1)if(ne(t,n,h[p-1][0],h[p-1][1],h[p][0],h[p][1])<=o)return true;return false}handlePoints(t){let n=this.layout(t);if(n&&n.pocY!=null)return [[n.x0,n.pocY],[n.x1,n.pocY]];let i=[];for(let o of this.anchors){let s=t.yOf(o.price,this.paneId);if(s==null)return [];i.push([t.xOf(o.time),s]);}return i}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.layout(t);if(!n)return null;let i=Math.min(n.x0,n.grow===1?n.anchorX:n.anchorX-n.maxW),o=Math.max(n.x1,n.grow===1?n.anchorX+n.maxW:n.anchorX),s=Math.min(n.yEdges[0],n.yEdges[n.yEdges.length-1]),a=Math.max(n.yEdges[0],n.yEdges[n.yEdges.length-1]);return {x:i,y:s,w:o-i,h:a-s}}priceRange(){if(this.cachedRange)return this.cachedRange;let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[{path:"frvp.rows",label:"Rows",kind:"number",min:1,max:500,step:1,group:"behavior"},{path:"frvp.valueAreaPct",label:"Value Area",kind:"number",min:0,max:100,step:1,group:"behavior"},{path:"frvp.widthPct",label:"Width %",kind:"number",min:0,max:100,step:1,group:"behavior"},{path:"frvp.anchor",label:"Anchor",kind:"select",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}],group:"behavior"},{path:"frvp.upColor",label:"Up Volume",kind:"color",group:"fill"},{path:"frvp.downColor",label:"Down Volume",kind:"color",group:"fill"},{path:"frvp.vaUpColor",label:"Value Area Up",kind:"color",group:"fill"},{path:"frvp.vaDownColor",label:"Value Area Down",kind:"color",group:"fill"},{path:"frvp.showVah",label:"VAH",kind:"boolean",group:"line"},{path:"frvp.vahColor",label:"VAH color",kind:"color",group:"line"},{path:"frvp.vahStyle",label:"VAH style",kind:"lineStyle",options:Ke,group:"line"},{path:"frvp.showVal",label:"VAL",kind:"boolean",group:"line"},{path:"frvp.valColor",label:"VAL color",kind:"color",group:"line"},{path:"frvp.valStyle",label:"VAL style",kind:"lineStyle",options:Ke,group:"line"},{path:"frvp.showPoc",label:"POC",kind:"boolean",group:"line"},{path:"frvp.pocColor",label:"POC color",kind:"color",group:"line"},{path:"frvp.pocStyle",label:"POC style",kind:"lineStyle",options:Ke,group:"line"},{path:"frvp.showDevelopingPoc",label:"Developing POC",kind:"boolean",group:"line"},{path:"frvp.developingPocColor",label:"Developing POC color",kind:"color",group:"line"},{path:"frvp.developingPocStyle",label:"Developing POC style",kind:"lineStyle",options:Ke,group:"line"},{path:"frvp.showDevelopingVa",label:"Developing VA",kind:"boolean",group:"line"},{path:"frvp.developingVaColor",label:"Developing VA color",kind:"color",group:"line"},{path:"frvp.developingVaStyle",label:"Developing VA style",kind:"lineStyle",options:Ke,group:"line"}]}}writeProps(){return {...this.frvp}}readProps(t){this.frvp={...Up(),...t};}};var qs=class extends he{constructor(){super(...arguments);this.type="pitchfork";}anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return null;let s=g=>{let b=t.yOf(g.price,this.paneId);return b==null?null:[t.xOf(g.time),b]},a=s(n),l=s(i),c=s(o);if(!a||!l||!c)return null;let d=(l[0]+c[0])/2,u=(l[1]+c[1])/2,h=d-a[0],p=u-a[1],m=t.width,f=t.height;return {segments:[xe(a[0],a[1],d,u,"right",m,f),xe(l[0],l[1],l[0]+h,l[1]+p,"right",m,f),xe(c[0],c[1],c[0]+h,c[1]+p,"right",m,f),[l[0],l[1],c[0],c[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B,...H]}}};var zr=class extends he{anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(e){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[2];if(!t||!n||!i)return null;let o=f=>{let g=e.yOf(f.price,this.paneId);return g==null?null:[e.xOf(f.time),g]},s=o(this.medianStart(t,n,i)),a=o(n),l=o(i);if(!s||!a||!l)return null;let c=(a[0]+l[0])/2,d=(a[1]+l[1])/2,u=c-s[0],h=d-s[1],p=e.width,m=e.height;return {segments:[xe(s[0],s[1],c,d,"right",p,m),xe(a[0],a[1],a[0]+u,a[1]+h,"right",p,m),xe(l[0],l[1],l[0]+u,l[1]+h,"right",p,m),[a[0],a[1],l[0],l[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}schema(){return {fields:[...B,...H]}}};var Zs=class extends zr{constructor(){super(...arguments);this.type="schiffpitchfork";}medianStart(t,n){return {time:t.time,price:(t.price+n.price)/2}}};var Js=class extends zr{constructor(){super(...arguments);this.type="modifiedschiffpitchfork";}medianStart(t,n){return {time:(t.time+n.time)/2,price:(t.price+n.price)/2}}};var Qs=class extends he{constructor(){super(...arguments);this.type="insidepitchfork";}anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return null;let s=b=>{let y=t.yOf(b.price,this.paneId);return y==null?null:[t.xOf(b.time),y]},a=s({time:(n.time+i.time)/2,price:(n.price+i.price)/2}),l=s(n),c=s(i),d=s(o);if(!a||!l||!c||!d)return null;let u=(c[0]+d[0])/2,h=(c[1]+d[1])/2,p=d[0]-a[0],m=d[1]-a[1],f=t.width,g=t.height;return {segments:[xe(u,h,u+p,h+m,"right",f,g),xe(c[0],c[1],c[0]+p,c[1]+m,"right",f,g),xe(d[0],d[1],d[0]+p,d[1]+m,"right",f,g),[c[0],c[1],d[0],d[1]],[a[0],a[1],d[0],d[1]],[l[0],l[1],c[0],c[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B,...H]}}};var ea=class extends G{constructor(){super(...arguments);this.type="arrow";}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?null:[t.xOf(n.time),o,t.xOf(i.time),s]}hitTest(t,n,i,o){let s=this.pixels(i);return s!=null&&ne(t,n,s[0],s[1],s[2],s[3])<=o}handlePoints(t){let n=this.pixels(t);return n?[[n[0],n[1]],[n[2],n[3]]]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.pixels(t);return n?{x:Math.min(n[0],n[2]),y:Math.min(n[1],n[3]),w:Math.abs(n[2]-n[0]),h:Math.abs(n[3]-n[1])}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,{path:"style.arrowRight",label:"Head (end)",kind:"boolean",group:"line"},{path:"style.arrowLeft",label:"Head (start)",kind:"boolean",group:"line"},...H]}}};var Zp=48,ta=class extends G{constructor(){super(...arguments);this.type="ellipse";}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}oval(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time);return {cx:(a+l)/2,cy:(o+s)/2,rx:Math.abs(l-a)/2,ry:Math.abs(s-o)/2}}perimeter(t){let n=[];for(let i=0;i<=Zp;i+=1){let o=i/Zp*Math.PI*2;n.push([t.cx+t.rx*Math.cos(o),t.cy+t.ry*Math.sin(o)]);}return n}hitTest(t,n,i,o){let s=this.oval(i);if(!s||s.rx<1||s.ry<1)return false;let a=((t-s.cx)/s.rx)**2+((n-s.cy)/s.ry)**2;return this.style.fillColor&&a<=1?true:Hr(t,n,this.perimeter(s))<=o}handlePoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return [];let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?[]:[[t.xOf(n.time),o],[t.xOf(i.time),s]]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.oval(t);return n?{x:n.cx-n.rx,y:n.cy-n.ry,w:n.rx*2,h:n.ry*2}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,...ue,...H]}}};var na=class extends he{constructor(){super(...arguments);this.type="triangle";}anchorSchema(){return {min:3,max:3,slots:[{role:"v1",free:"both"},{role:"v2",free:"both"},{role:"v3",free:"both"}]}}geometry(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return null;let s=d=>{let u=t.yOf(d.price,this.paneId);return u==null?null:[t.xOf(d.time),u]},a=s(n),l=s(i),c=s(o);return !a||!l||!c?null:{segments:[[a[0],a[1],l[0],l[1]],[l[0],l[1],c[0],c[1]],[c[0],c[1],a[0],a[1]]],fill:[a,l,c]}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B,...ue,...H]}}};var t0=512,In=class extends he{anchorSchema(){return {min:2,max:t0,slots:[]}}geometry(e){let t=[];for(let i of this.anchors){let o=e.yOf(i.price,this.paneId);if(o==null)return null;t.push([e.xOf(i.time),o]);}if(t.length<2)return null;let n=[];for(let i=1;i<t.length;i+=1)n.push([t[i-1][0],t[i-1][1],t[i][0],t[i][1]]);return {segments:n,fill:null}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}schema(){return {fields:[...B,...H]}}};var ra=class extends In{constructor(){super(...arguments);this.type="polyline";}};var Wi=class extends In{placementMode(){return "freehand"}handlePoints(e){return []}bounds(e){let t=[],n=[];for(let s of this.anchors){let a=e.yOf(s.price,this.paneId);a!=null&&(t.push(e.xOf(s.time)),n.push(a));}if(t.length===0)return null;let i=Math.min(...t),o=Math.min(...n);return {x:i,y:o,w:Math.max(...t)-i,h:Math.max(...n)-o}}},ia=class extends Wi{constructor(){super(...arguments);this.type="freehand";}};var n0=[{path:"style.lineColor",label:"Color",kind:"color",group:"line"},{path:"style.lineWidth",label:"Width",kind:"number",min:4,max:60,step:1,group:"line"}],oa=class extends Wi{constructor(){super(...arguments);this.type="highlighter";}schema(){return {fields:n0}}};var sa=class extends G{constructor(){super(...arguments);this.type="circle";}anchorSchema(){return {min:2,max:2,slots:[{role:"center",free:"both"},{role:"edge",free:"both"}]}}geom(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time);return {cx:a,cy:o,r:Math.hypot(l-a,s-o)}}hitTest(t,n,i,o){let s=this.geom(i);if(!s||s.r<1)return false;let a=Math.hypot(t-s.cx,n-s.cy);return this.style.fillColor&&a<=s.r?true:Math.abs(a-s.r)<=o}handlePoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return [];let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?[]:[[t.xOf(n.time),o],[t.xOf(i.time),s]]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.geom(t);return n?{x:n.cx-n.r,y:n.cy-n.r,w:n.r*2,h:n.r*2}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,...ue,...H]}}};var aa=class extends he{constructor(){super(...arguments);this.type="rotatedrect";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"w",free:"both"}]}}px(t,n){let i=this.anchors[n];if(!i)return null;let o=t.yOf(i.price,this.paneId);return o==null?null:[t.xOf(i.time),o]}geometry(t){let n=this.px(t,0),i=this.px(t,1);if(!n||!i)return null;let o=this.px(t,2);if(!o||this.anchors.length<3)return {segments:[[n[0],n[1],i[0],i[1]]],fill:null};let s=i[0]-n[0],a=i[1]-n[1],l=Math.hypot(s,a);if(l<1e-6)return {segments:[[n[0],n[1],i[0],i[1]]],fill:null};let c=-a/l,d=s/l,u=(o[0]-n[0])*c+(o[1]-n[1])*d,h=c*u,p=d*u,m=n,f=i,g=[i[0]+h,i[1]+p],b=[n[0]+h,n[1]+p];return {segments:[[m[0],m[1],f[0],f[1]],[f[0],f[1],g[0],g[1]],[g[0],g[1],b[0],b[1]],[b[0],b[1],m[0],m[1]]],fill:[m,f,g,b]}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B.map(t=>({...t,label:t.label.replace("Line","Border")})),...ue,...H]}}};var la=class extends In{constructor(){super(...arguments);this.type="path";}};var Jp=40,ca=class extends he{constructor(){super(...arguments);this.type="arc";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"apex",free:"both"}]}}pinApex(){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[2];t&&n&&i&&(i.time=(t.time+n.time)/2);}onPlaced(){this.pinApex();}constrainHandleDrag(){this.pinApex();}px(t,n){let i=this.anchors[n];if(!i)return null;let o=t.yOf(i.price,this.paneId);return o==null?null:[t.xOf(i.time),o]}geometry(t){let n=this.px(t,0),i=this.px(t,1);if(!n||!i)return null;let o=this.anchors[2];if(!o||this.anchors.length<3)return {segments:[[n[0],n[1],i[0],i[1]]],fill:null};let s=t.yOf(o.price,this.paneId);if(s==null)return null;let a=(n[0]+i[0])/2,l=(n[1]+i[1])/2,c=(i[0]-n[0])/2,d=(i[1]-n[1])/2,u=Math.hypot(c,d);if(u<1e-6)return {segments:[[n[0],n[1],i[0],i[1]]],fill:null};let h=-d/u,p=c/u,m=(s-l)*p;m<0&&(h=-h,p=-p);let f=Math.abs(m),g=[];for(let y=0;y<=Jp;y+=1){let v=y/Jp*Math.PI,S=Math.cos(v),P=Math.sin(v);g.push([a+S*c+P*f*h,l+S*d+P*f*p]);}let b=[];for(let y=1;y<g.length;y+=1)b.push([g[y-1][0],g[y-1][1],g[y][0],g[y][1]]);return b.push([g[g.length-1][0],g[g.length-1][1],g[0][0],g[0][1]]),{segments:b,fill:g}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B.map(t=>({...t,label:t.label.replace("Line","Border")})),...ue,...H]}}};var Qp=40,da=class extends he{constructor(){super(...arguments);this.type="curve";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"control",free:"both"}]}}px(t,n){let i=this.anchors[n];if(!i)return null;let o=t.yOf(i.price,this.paneId);return o==null?null:[t.xOf(i.time),o]}geometry(t){let n=this.px(t,0),i=this.px(t,1);if(!n||!i)return null;let o=this.px(t,2);if(!o||this.anchors.length<3)return {segments:[[n[0],n[1],i[0],i[1]]],fill:null};let s=[];for(let l=0;l<=Qp;l+=1){let c=l/Qp,d=1-c;s.push([d*d*n[0]+2*d*c*o[0]+c*c*i[0],d*d*n[1]+2*d*c*o[1]+c*c*i[1]]);}let a=[];for(let l=1;l<s.length;l+=1)a.push([s[l-1][0],s[l-1][1],s[l][0],s[l][1]]);return {segments:a,fill:s}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B,...ue,...H]}}};var r0={head:11,headW:9,stemW:3.5,len:22},rr=class extends G{anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}glyphPoints(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);if(n==null)return null;let i=e.xOf(t.time),{head:o,headW:s,stemW:a,len:l}=r0,c=[[0,0],[-s,o],[-a,o],[-a,l],[a,l],[a,o],[s,o]],d=this.dir(),u=([h,p])=>{switch(d){case "up":return [h,p];case "down":return [h,-p];case "left":return [p,h];default:return [-p,h]}};return c.map(h=>{let[p,m]=u(h);return [i+p,n+m]})}hitTest(e,t,n,i){let o=this.glyphPoints(n);return o!=null&&Vt(e,t,o)}handlePoints(e){let t=this.anchors[0];if(!t)return [];let n=e.yOf(t.price,this.paneId);return n==null?[]:[[e.xOf(t.time),n]]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.glyphPoints(e);if(!t)return null;let n=t.map(a=>a[0]),i=t.map(a=>a[1]),o=Math.min(...n),s=Math.min(...i);return {x:o,y:s,w:Math.max(...n)-o,h:Math.max(...i)-s}}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}schema(){return {fields:[{path:"style.lineColor",label:"Color",kind:"color",group:"line"},...H]}}},Gi=class extends rr{constructor(){super(...arguments);this.type="arrowmarkup";}dir(){return "up"}},Ui=class extends rr{constructor(){super(...arguments);this.type="arrowmarkdown";}dir(){return "down"}};var Xi=["\u2605","\u2606","\u25CF","\u25C6","\u25B2","\u25BC","\u27A4","\u2691","\u271A","\u2715","\u2764","\u2666"],ua=["small","normal","large","huge"],em={small:16,normal:22,large:32,huge:44},ir=class extends G{constructor(e){super(e),this.glyph||(this.glyph=this.defaultGlyph()),this.size||(this.size="normal");}sizePx(){return em[this.size]??em.normal}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}center(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);return n==null?null:[e.xOf(t.time),n]}hitTest(e,t,n,i){let o=this.center(n);if(!o)return false;let s=this.sizePx()/2+i;return Math.abs(e-o[0])<=s&&Math.abs(t-o[1])<=s}handlePoints(e){let t=this.center(e);return t?[t]:[]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.center(e);if(!t)return null;let n=this.sizePx();return {x:t[0]-n/2,y:t[1]-n/2,w:n,h:n}}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}schema(){return {fields:[{path:"glyph",label:"Icon",kind:"select",options:Xi.map(e=>({value:e,label:e})),group:"line"},{path:"size",label:"Size",kind:"select",options:ua.map(e=>({value:e,label:e})),group:"line"},{path:"style.lineColor",label:"Color",kind:"color",group:"line"},...H]}}writeProps(){return {glyph:this.glyph,size:this.size}}readProps(e){typeof e.glyph=="string"&&(this.glyph=e.glyph),typeof e.size=="string"&&(this.size=e.size);}},Yi=class extends ir{constructor(){super(...arguments);this.type="flagmark";}defaultGlyph(){return "\u2691"}},Ki=class extends ir{constructor(){super(...arguments);this.type="iconstamp";}defaultGlyph(){return "\u2605"}};var tm=r=>r==="small"||r==="normal"||r==="large"||r==="huge";function i0(r){if(!r||typeof r!="object")return null;let e=r;return typeof e.ratio!="number"||typeof e.color!="string"?null:{ratio:e.ratio,color:e.color,enabled:e.enabled!==false,...typeof e.label=="string"&&e.label?{label:e.label}:{}}}var me=class extends G{constructor(e){super(e),this.levels||(this.levels=this.defaultLevels().map(t=>({...t}))),this.numbersSize||(this.numbersSize="small"),this.labelsSize||(this.labelsSize="normal");}fillBands(e){return []}editableLevels(){return this.levels}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}hitTest(e,t,n,i){let o=this.entryLines(n);return o!=null&&o.some(s=>ne(e,t,s.x1,s.y1,s.x2,s.y2)<=i)}handlePoints(e){let t=[];for(let n of this.anchors){let i=e.yOf(n.price,this.paneId);if(i==null)return [];t.push([e.xOf(n.time),i]);}return t}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),i=t.map(a=>a[1]),o=Math.min(...n),s=Math.min(...i);return {x:o,y:s,w:Math.max(...n)-o,h:Math.max(...i)-s}}schema(){return {fields:B.filter(e=>e.path!=="style.lineColor")}}writeProps(){return {levels:this.levels.map(e=>({...e})),numbersSize:this.numbersSize,labelsSize:this.labelsSize}}readProps(e){if(Array.isArray(e.levels)){let t=e.levels.map(i0).filter(n=>n!=null);t.length&&(this.levels=t);}tm(e.numbersSize)&&(this.numbersSize=e.numbersSize),tm(e.labelsSize)&&(this.labelsSize=e.labelsSize);}};var $r=class extends me{levelLines(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=e.xOf(t.time),o=e.xOf(n.time),s=Math.min(i,o),a=Math.max(i,o),l=n.price-t.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let u=t.price+d.ratio*l,h=e.yOf(u,this.paneId);h!=null&&c.push({ratio:d.ratio,color:d.color,label:d.label,price:u,x1:s,x2:a,y:h});}return c}entryLines(e){let t=this.levelLines(e);return t?t.map(n=>({color:n.color,label:n.label,x1:n.x1,y1:n.y,x2:n.x2,y2:n.y,numberText:`${n.ratio} (${n.price.toFixed(2)})`,numberX:n.x1+4,numberY:n.y-7,numberAlign:"left",labelX:(n.x1+n.x2)/2,labelY:n.y-7})):null}fillBands(e){let t=this.levelLines(e);if(!t)return [];let n=[];for(let i=1;i<t.length;i+=1){let o=t[i-1],s=t[i];n.push({color:s.color,x:o.x1,y:Math.min(o.y,s.y),w:o.x2-o.x1,h:Math.abs(s.y-o.y)});}return n}priceRange(){let e=this.anchors[0],t=this.anchors[1];if(!e||!t)return null;let n=t.price-e.price,i=this.levels.filter(o=>o.enabled).map(o=>e.price+o.ratio*n);return i.length===0?null:{min:Math.min(...i),max:Math.max(...i)}}};var or=J,Bt=W,Ht=de,sr="#4caf50",An=z,cn=Je,ar="#9c27b0",o0="#e91e63",fd="#26a69a",s0="#ab47bc",a0="#ef5350",nm="#ffb74d",l0="#38c0fd",ha="#b2b5be",Wr=[l0,cn,An,sr,Ht,Bt,o0,ar,or,fd,s0,a0];function rm(r){return Wr[(r%Wr.length+Wr.length)%Wr.length]}var c0=[[0,or],[.125,Bt],[.236,Bt],[.25,Bt],[.382,Ht],[.5,sr],[.618,An],[.75,cn],[.786,cn],[1,or],[1.272,cn],[1.382,Ht],[1.618,Bt],[2,or],[2.382,Ht],[2.618,Ht],[3,or],[4.236,sr],[6.854,An],[11.09,cn]];function d0(r,e=0){return c0.find(([t])=>t===r)?.[1]??rm(e)}function pe(r){return r.map((e,t)=>{let n=typeof e=="number"?{ratio:e}:e;return {ratio:n.ratio,color:n.color??d0(n.ratio,t),enabled:n.enabled!==false,...n.label?{label:n.label}:{}}})}function im(r,e=r){return Array.from({length:r},(t,n)=>({ratio:n+1,color:rm(n),enabled:n<e,label:String(n+1)}))}var u0=pe([0,.236,.382,.5,.618,.786,1]),pa=class extends $r{constructor(){super(...arguments);this.type="fibretracement";}defaultLevels(){return u0}};var h0=pe([0,.382,.618,1,1.272,1.618,{ratio:2.618,color:ar}]),ma=class extends $r{constructor(){super(...arguments);this.type="fibextension";}defaultLevels(){return h0}};var p0=pe([0,.382,.5,.618,1,1.618,{ratio:2.618,color:ar}]),fa=class extends me{constructor(){super(...arguments);this.type="fibextensiontrend";}anchorSchema(){return {min:3,max:3,slots:[{role:"a",free:"both"},{role:"b",free:"both"},{role:"c",free:"both"}]}}defaultLevels(){return p0}entryLines(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return null;let s=i.price-n.price,a=[t.xOf(n.time),t.xOf(i.time),t.xOf(o.time)],l=Math.min(...a),c=Math.max(...a),d=[];for(let u of this.levels){if(!u.enabled)continue;let h=o.price+u.ratio*s,p=t.yOf(h,this.paneId);p!=null&&d.push({color:u.color,label:u.label,x1:l,y1:p,x2:c,y2:p,numberText:`${u.ratio} (${h.toFixed(2)})`,numberX:l+4,numberY:p-7,numberAlign:"left",labelX:(l+c)/2,labelY:p-7});}return d}priceRange(){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[2];if(!t||!n||!i)return null;let o=n.price-t.price,s=this.levels.filter(a=>a.enabled).map(a=>i.price+a.ratio*o);return s.push(t.price,n.price,i.price),{min:Math.min(...s),max:Math.max(...s)}}};var m0=pe([.236,.382,.5,.618,.786,1]),ga=class extends me{constructor(){super(...arguments);this.type="fibfan";}defaultLevels(){return m0}fanLines(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.xOf(n.time),s=t.yOf(n.price,this.paneId);if(s==null)return null;let a=t.xOf(i.time),l=i.price-n.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let u=t.yOf(n.price+d.ratio*l,this.paneId);if(u==null)continue;let[h,p,m,f]=xe(o,s,a,u,"right",t.width,t.height);c.push({ratio:d.ratio,color:d.color,label:d.label,x1:h,y1:p,x2:m,y2:f,labelX:a+5,labelY:u});}return c}entryLines(t){let n=this.fanLines(t);return n?n.map(i=>({color:i.color,label:i.label,x1:i.x1,y1:i.y1,x2:i.x2,y2:i.y2,numberText:String(i.ratio),numberX:i.labelX,numberY:i.labelY,numberAlign:"left",labelX:i.labelX,labelY:i.labelY+13})):null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var f0=[0,1,2,3,5,8,13,21,34].map(r=>({ratio:r,color:O,enabled:true})),ba=class extends me{constructor(){super(...arguments);this.type="fibtimezones";}defaultLevels(){return f0}zoneLines(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=i.time-n.time;if(Math.abs(o)<1e-9)return null;let s=[];for(let a of this.levels)a.enabled&&s.push({n:a.ratio,color:a.color,label:a.label,x:t.xOf(n.time+a.ratio*o)});return s}entryLines(t){let n=this.zoneLines(t);if(!n)return null;let i=t.height;return n.map(o=>({color:o.color,label:o.label,x1:o.x,y1:0,x2:o.x,y2:i,numberText:String(o.n),numberX:o.x,numberY:9,numberAlign:"center",labelX:o.x,labelY:24}))}priceRange(){return null}timeExtent(){return null}};var g0=pe([0,.236,.382,.5,.618,.786,1,1.618,2.618]),va=class extends me{constructor(){super(...arguments);this.type="fibchannel";}defaultLevels(){return g0}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"offset",free:"both"}]}}entryLines(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time),c=0,d=0,u=this.anchors[2];if(u){let p=t.yOf(u.price,this.paneId);if(p==null)return null;c=t.xOf(u.time)-a,d=p-o;}let h=[];for(let p of this.levels){if(!p.enabled)continue;let m=p.ratio*c,f=p.ratio*d,g=l+m,b=s+f;h.push({color:p.color,label:p.label,x1:a+m,y1:o+f,x2:g,y2:b,numberText:String(p.ratio),numberX:g+5,numberY:b,numberAlign:"left",labelX:g+5,labelY:b+13});}return h}priceRange(){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[2];if(!t||!n)return null;let o=i?i.price-t.price:0,s=1/0,a=-1/0;for(let l of this.levels)if(l.enabled)for(let c of [t.price,n.price]){let d=c+l.ratio*o;d<s&&(s=d),d>a&&(a=d);}return s<=a?{min:s,max:a}:null}};var b0=pe([0,.236,.382,.5,.618,.786,1]),ya=class extends me{constructor(){super(...arguments);this.type="fibspeedfan";}defaultLevels(){return b0}entryLines(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),c=t.xOf(i.time)-a,d=s-o,u=c>=0?"right":"left",h=t.width,p=t.height,m=[];for(let f of this.levels){if(!f.enabled)continue;let g=a+c,b=o+d*f.ratio,y=xe(a,o,g,b,u,h,p);if(m.push({color:f.color,label:f.label,x1:y[0],y1:y[1],x2:y[2],y2:y[3],numberText:String(f.ratio),numberX:u==="right"?g+5:g-5,numberY:b,numberAlign:u==="right"?"left":"right",labelX:g,labelY:b}),f.ratio===1)continue;let v=a+c*f.ratio,S=o+d,P=xe(a,o,v,S,u,h,p);m.push({color:f.color,label:f.label,x1:P[0],y1:P[1],x2:P[2],y2:P[3],numberText:String(f.ratio),numberX:v,numberY:S+(d>=0?12:-12),numberAlign:"center",labelX:v,labelY:S+12});}return m}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var v0=pe([0,.382,{ratio:.5,enabled:false},.618,1,1.382,1.618,2,2.382,2.618,3]),wa=class extends me{constructor(){super(...arguments);this.type="trendfibtime";}defaultLevels(){return v0}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"p3",free:"both"}]}}entryLines(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return null;let s=i.time-n.time;if(Math.abs(s)<1e-9)return null;let a=t.height,l=[];for(let c of this.levels){if(!c.enabled)continue;let d=t.xOf(o.time+c.ratio*s);l.push({color:c.color,label:c.label,x1:d,y1:0,x2:d,y2:a,numberText:String(c.ratio),numberX:d,numberY:9,numberAlign:"center",labelX:d,labelY:24});}return l}priceRange(){return null}timeExtent(){return null}};function y0(r,e,t){if(t-e>=Math.PI*2-.001)return true;let n=r-e,i=Math.PI*2;for(;n<0;)n+=i;for(;n>=i;)n-=i;return n<=t-e+1e-6}var Tt=class extends me{boundingLines(e){return []}entryLines(e){return []}hitTest(e,t,n,i){let o=this.radial(n);if(o){let s=Math.hypot(e-o.cx,t-o.cy),a=Math.atan2(t-o.cy,e-o.cx);if(y0(a,o.a0,o.a1)){for(let l of this.levels)if(l.enabled&&Math.abs(s-o.R0*l.ratio)<=i)return true}}return this.boundingLines(n).some(s=>ne(e,t,s[0],s[1],s[2],s[3])<=i)}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}};var w0=pe([.236,.382,.5,.618,.786,1,1.618,2.618]),xa=class extends Tt{constructor(){super(...arguments);this.type="fibcircles";}defaultLevels(){return w0}radial(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time);return {cx:a,cy:o,R0:Math.hypot(l-a,s-o),a0:0,a1:Math.PI*2}}};var x0=pe([.236,.382,.5,.618,.786,1,1.618,2.618]),Sa=class extends Tt{constructor(){super(...arguments);this.type="fibarcs";}defaultLevels(){return x0}pts(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?null:{cx:t.xOf(n.time),cy:o,ex:t.xOf(i.time),ey:s}}radial(t){let n=this.pts(t);if(!n)return null;let i=Math.hypot(n.ex-n.cx,n.ey-n.cy),o=Math.atan2(n.ey-n.cy,n.ex-n.cx);return {cx:n.cx,cy:n.cy,R0:i,a0:o-Math.PI/2,a1:o+Math.PI/2}}boundingLines(t){let n=this.pts(t);return n?[[n.cx,n.cy,n.ex,n.ey]]:[]}};var S0=pe([.236,.382,.5,.618,.786,1]),Ca=class extends Tt{constructor(){super(...arguments);this.type="fibwedge";}defaultLevels(){return S0}anchorSchema(){return {min:3,max:3,slots:[{role:"apex",free:"both"},{role:"radius",free:"both"},{role:"angle",free:"both"}]}}px(t,n){let i=this.anchors[n];if(!i)return null;let o=t.yOf(i.price,this.paneId);return o==null?null:[t.xOf(i.time),o]}radial(t){let n=this.px(t,0),i=this.px(t,1),o=this.px(t,2);if(!n||!i||!o)return null;let s=Math.hypot(i[0]-n[0],i[1]-n[1]);if(s<1)return null;let a=Math.atan2(i[1]-n[1],i[0]-n[0]),l=Math.atan2(o[1]-n[1],o[0]-n[0]),c=Math.min(a,l),d=Math.max(a,l);return d-c>Math.PI&&([c,d]=[d,c+Math.PI*2]),{cx:n[0],cy:n[1],R0:s,a0:c,a1:d}}boundingLines(t){let n=this.px(t,0),i=this.px(t,1);if(!n||!i)return [];let o=[[n[0],n[1],i[0],i[1]]],s=this.px(t,2);if(s){let a=Math.hypot(i[0]-n[0],i[1]-n[1]),l=Math.hypot(s[0]-n[0],s[1]-n[1]);l>1e-6&&o.push([n[0],n[1],n[0]+(s[0]-n[0])/l*a,n[1]+(s[1]-n[1])/l*a]);}return o}};var C0=1.6180339887,om=Math.log(C0)/(Math.PI/2),T0=Math.PI/64,E0=Math.PI,P0=.5,lr=class extends G{constructor(){super(...arguments);this.type="fibspiral";}anchorSchema(){return {min:2,max:2,slots:[{role:"center",free:"both"},{role:"edge",free:"both"}]}}spiralPoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time),c=Math.hypot(l-a,s-o);if(c<1)return null;let d=Math.atan2(s-o,l-a),u=Math.max(Math.log(P0/c)/om,-8*Math.PI*2),h=[];for(let p=u;p<=E0;p+=T0){let m=c*Math.exp(om*p),f=d+p;h.push([a+m*Math.cos(f),o+m*Math.sin(f)]);}return h}hitTest(t,n,i,o){let s=this.spiralPoints(i);return s!=null&&s.length>=2&&Hr(t,n,s)<=o}handlePoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return [];let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?[]:[[t.xOf(n.time),o],[t.xOf(i.time),s]]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.handlePoints(t);if(n.length<2)return null;let i=n.map(l=>l[0]),o=n.map(l=>l[1]),s=Math.min(...i),a=Math.min(...o);return {x:s,y:a,w:Math.max(...i)-s,h:Math.max(...o)-a}}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,...H]}}};var L0=pe([{ratio:.125,color:Bt,label:"1/8"},{ratio:.25,color:Ht,label:"1/4"},{ratio:.333,color:nm,label:"1/3"},{ratio:.5,color:sr,label:"1/2"},{ratio:1,color:ha,label:"1/1"},{ratio:2,color:An,label:"2/1"},{ratio:3,color:cn,label:"3/1"},{ratio:4,color:fd,label:"4/1"},{ratio:8,color:ar,label:"8/1"}]),Ta=class extends me{constructor(){super(...arguments);this.type="gannfan";}defaultLevels(){return L0}entryLines(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.xOf(n.time),s=t.yOf(n.price,this.paneId);if(s==null)return null;let a=t.xOf(i.time),l=i.price-n.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let u=t.yOf(n.price+l*d.ratio,this.paneId);if(u==null)continue;let[h,p,m,f]=xe(o,s,a,u,"right",t.width,t.height);c.push({color:d.color,x1:h,y1:p,x2:m,y2:f,numberText:d.label??String(d.ratio),numberX:a+5,numberY:u,numberAlign:"left",labelX:a+5,labelY:u});}return c}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var M0=pe([0,.25,.382,.5,.618,.75,1].map(r=>({ratio:r,label:String(r)}))),Ea=class extends me{constructor(){super(...arguments);this.type="gannbox";}defaultLevels(){return M0}corners(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.xOf(n.time),s=t.xOf(i.time),a=t.yOf(n.price,this.paneId),l=t.yOf(i.price,this.paneId);return a==null||l==null?null:{c1:n,c2:i,left:Math.min(o,s),right:Math.max(o,s),top:Math.min(a,l),bot:Math.max(a,l)}}entryLines(t){let n=this.corners(t);if(!n)return null;let{c1:i,c2:o,left:s,right:a,top:l,bot:c}=n,d=[];for(let h of this.levels){if(!h.enabled)continue;let p=t.yOf(i.price+h.ratio*(o.price-i.price),this.paneId);p!=null&&d.push({color:h.color,x1:s,y1:p,x2:a,y2:p,numberText:h.label??String(h.ratio),numberX:s-5,numberY:p,numberAlign:"right",labelX:s,labelY:p});let m=t.xOf(i.time+h.ratio*(o.time-i.time));d.push({color:h.color,x1:m,y1:l,x2:m,y2:c,numberText:"",numberX:m,numberY:l,numberAlign:"center",labelX:m,labelY:l});}let u=this.levels.find(h=>h.ratio===1)?.color??or;return d.push({color:u,x1:s,y1:l,x2:a,y2:c,numberText:"",numberX:0,numberY:0,numberAlign:"left",labelX:0,labelY:0}),d.push({color:u,x1:s,y1:c,x2:a,y2:l,numberText:"",numberX:0,numberY:0,numberAlign:"left",labelX:0,labelY:0}),d}hitTest(t,n,i,o){let s=this.corners(i);return s!=null&&Fe(t,n,s.left,s.top,s.right,s.bot,o)}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var k0=pe([0,.25,.382,.5,.618,.75,1].map(r=>({ratio:r,label:String(r)}))),I0=[{label:"3x1",x:3,y:1,color:Bt},{label:"2x1",x:2,y:1,color:Ht},{label:"1x1",x:1,y:1,color:ha},{label:"1x2",x:1,y:2,color:An},{label:"1x3",x:1,y:3,color:cn}],gd=[{k:.25,color:Bt},{k:.5,color:Ht},{k:.75,color:sr},{k:1,color:An}],cr=class extends me{constructor(){super(...arguments);this.type="gannsquare";}defaultLevels(){return k0}box(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time);return {ox:a,oy:o,bx:l-a,py:s-o,left:Math.min(a,l),top:Math.min(o,s),right:Math.max(a,l),bot:Math.max(o,s)}}arcGeom(t){let n=this.box(t);return n?{ox:n.ox,oy:n.oy,bx:n.bx,py:n.py}:null}entryLines(t){let n=this.box(t);if(!n)return null;let i=this.anchors[0],o=this.anchors[1],s=[];for(let a of this.levels){if(!a.enabled)continue;let l=t.yOf(i.price+a.ratio*(o.price-i.price),this.paneId);l!=null&&s.push({color:a.color,x1:n.left,y1:l,x2:n.right,y2:l,numberText:a.label??String(a.ratio),numberX:n.left-5,numberY:l,numberAlign:"right",labelX:n.left,labelY:l});let c=t.xOf(i.time+a.ratio*(o.time-i.time));s.push({color:a.color,x1:c,y1:n.top,x2:c,y2:n.bot,numberText:"",numberX:c,numberY:n.top,numberAlign:"center",labelX:c,labelY:n.top});}for(let a of I0){let l,c;a.x>a.y?(l=n.ox+n.bx,c=n.oy+a.y/a.x*n.py):(c=n.oy+n.py,l=n.ox+a.x/a.y*n.bx),s.push({color:a.color,x1:n.ox,y1:n.oy,x2:l,y2:c,numberText:a.label,numberX:l+4,numberY:c,numberAlign:"left",labelX:l+4,labelY:c});}return s}hitTest(t,n,i,o){let s=this.box(i);return s!=null&&Fe(t,n,s.left,s.top,s.right,s.bot,o)}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var bd=[4,8,12,16,24,32,48,64],A0=24,R0=.75;function sm(r,e){if(!Number.isInteger(r)||!Number.isInteger(e)||e<=0)return false;let t=r*r-1;return e%2===1?t%e===0:e%8===0?t%e!==0?false:t/e%2!==0:false}function am(r){let e=[];for(let t=0;t<r;t+=1)sm(t,r)&&e.push(t);return e}var dr=class extends G{constructor(t){super(t);this.type="dedekind";this.maxCurvature===void 0&&(this.maxCurvature=A0);}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}box(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=Math.min(t.xOf(n.time),t.xOf(i.time)),l=Math.max(t.xOf(n.time),t.xOf(i.time)),c=Math.min(o,s),d=Math.max(o,s),u=l-a,h=d-c;if(u<1||h<1)return null;let p=h,m=u/p;return {left:a,right:l,top:c,bot:d,unitPx:p,x0:0,realSpan:m}}geodesics(t){let n=this.box(t);if(!n)return null;let{left:i,top:o,bot:s,unitPx:a,x0:l,realSpan:c}=n,d=Math.max(1,Math.min(64,Math.round(this.maxCurvature))),u=l-1/d,h=l+c+1/d,p=i+c*a,m=[],f=Math.floor(u*2),g=Math.ceil(h*2);for(let b=f;b<=g;b+=1){if(b%2===0)continue;let y=i+(b/2-l)*a;y<i-.5||y>p+.5||m.push({kind:"vline",x:y,y0:s,y1:o});}for(let b=1;b<=d;b+=1){let y=1/b,v=y*a;if(v<R0)continue;let S=am(b);if(S.length===0)continue;let P=Math.floor(u)-1,T=Math.ceil(h)+1;for(let E=P;E<=T;E+=1)for(let x of S){let L=x/b+E;if(L+y<u||L-y>h)continue;let w=i+(L-l)*a;w+v<i-1||w-v>p+1||m.push({kind:"arc",cx:w,cy:s,r:v});}}return m}hitTest(t,n,i,o){let s=this.box(i);return s!=null&&Fe(t,n,s.left,s.top,s.right,s.bot,o)}handlePoints(t){let n=this.box(t);return n?[[n.left,n.top],[n.right,n.bot]]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.box(t);return n?{x:n.left,y:n.top,w:n.right-n.left,h:n.bot-n.top}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,{path:"maxCurvature",label:"Max curvature",kind:"number",min:4,max:64,step:4,group:"behavior"},...H]}}writeProps(){return {maxCurvature:this.maxCurvature}}readProps(t){typeof t.maxCurvature=="number"&&Number.isFinite(t.maxCurvature)&&(this.maxCurvature=Math.max(1,Math.min(64,Math.round(t.maxCurvature))));}};var vd=[3,4,5,6,8,10,12],yd=[1.5,2,2.5,3,4,5],Pa=6,D0=2;function wd(r=Pa){return [...im(Wr.length,r)]}function O0(r){if(!r||typeof r!="object")return null;let e=r;return typeof e.ratio!="number"||typeof e.color!="string"?null:{ratio:e.ratio,color:e.color,enabled:e.enabled!==false,...typeof e.label=="string"&&e.label?{label:e.label}:{}}}var Gr={path:"showRatios",label:"Show ratios",kind:"boolean",group:"behavior"},Qe=class extends G{constructor(e){super(e),this.waveCount===void 0&&(this.waveCount=Pa),this.showRatios===void 0&&(this.showRatios=true);let t=Array.isArray(e.props?.levels);this.levels||(this.levels=this.defaultLevels().map(n=>({...n}))),!t&&this.shouldSyncWaveCount()&&this.syncLevelsToWaveCount();}shouldSyncWaveCount(){return true}syncLevelsToWaveCount(){let e=Math.max(1,Math.min(this.levels.length,Math.round(this.waveCount)));this.waveCount=e;for(let t=0;t<this.levels.length;t+=1)this.levels[t].enabled=t<e;}editableLevels(){return this.levels}anchorSchema(){return {min:2,max:2,slots:[{role:"d1",free:"both"},{role:"d2",free:"both"}]}}geom(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=e.yOf(t.price,this.paneId),o=e.yOf(n.price,this.paneId);if(i==null||o==null)return null;let s=e.xOf(t.time),a=e.xOf(n.time),l=(s+a)/2,c=(i+o)/2,d=Math.hypot(a-s,o-i)/2;if(d<1)return null;let u=a-s,h=o-i,p=Math.hypot(u,h);p<1e-9?(u=1,h=0):(u/=p,h/=p);let m=this.levels.filter(T=>T.enabled&&T.ratio>0).slice().sort((T,E)=>T.ratio-E.ratio);if(m.length===0)return null;let f=Math.max(1,this.machNumber()),g=[];for(let T of m){let E=T.ratio*d;g.push({cx:l+f*(E-d)*u,cy:c+f*(E-d)*h,r:E,color:T.color,ratio:T.ratio});}let b=l-f*d*u,y=c-f*d*h,v=g[g.length-1].r,S=f*v+2*d,P=[];if(f<=1+1e-9){let T=-h,E=u;P.push([b-T*S,y-E*S,b+T*S,y+E*S]);}else {let T=Math.asin(1/f),E=Math.cos(T),x=Math.sin(T),L=(A,$,ie)=>[A*E-$*ie*x,A*ie*x+$*E],[w,M]=L(u,h,1),[k,C]=L(u,h,-1);P.push([b,y,b+w*S,y+M*S]),P.push([b,y,b+k*S,y+C*S]);}return {c0x:l,c0y:c,R:d,fx:u,fy:h,noseX:b,noseY:y,circles:g,rays:P}}hitTest(e,t,n,i){let o=this.geom(n);if(!o)return false;for(let s of o.circles)if(Math.abs(Math.hypot(e-s.cx,t-s.cy)-s.r)<=i)return true;return o.rays.some(s=>ne(e,t,s[0],s[1],s[2],s[3])<=i)}handlePoints(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return [];let i=e.yOf(t.price,this.paneId),o=e.yOf(n.price,this.paneId);return i==null||o==null?[]:[[e.xOf(t.time),i],[e.xOf(n.time),o]]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.geom(e);if(!t)return null;let n=t.noseX,i=t.noseX,o=t.noseY,s=t.noseY;for(let a of t.circles)n=Math.min(n,a.cx-a.r),i=Math.max(i,a.cx+a.r),o=Math.min(o,a.cy-a.r),s=Math.max(s,a.cy+a.r);for(let a of t.rays)n=Math.min(n,a[0],a[2]),i=Math.max(i,a[0],a[2]),o=Math.min(o,a[1],a[3]),s=Math.max(s,a[1],a[3]);return {x:n,y:o,w:i-n,h:s-o}}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}applySettings(e){if(super.applySettings(e),Object.prototype.hasOwnProperty.call(e,"waveCount")&&typeof this.waveCount=="number"){let t=Math.max(1,Math.min(this.levels.length,Math.round(this.waveCount)));this.waveCount=t;for(let n=0;n<this.levels.length;n+=1)this.levels[n].enabled=n<t;}}schema(){return {fields:[...B,{path:"waveCount",label:"Waves",kind:"number",min:3,max:12,step:1,group:"behavior"},Gr,...H]}}writeProps(){return {waveCount:this.waveCount,showRatios:this.showRatios,levels:this.levels.map(e=>({...e}))}}readProps(e){if(typeof e.waveCount=="number"&&Number.isFinite(e.waveCount)&&(this.waveCount=Math.max(2,Math.min(12,Math.round(e.waveCount)))),typeof e.showRatios=="boolean"&&(this.showRatios=e.showRatios),Array.isArray(e.levels)){let t=e.levels.map(O0).filter(n=>n!=null);t.length&&(this.levels=t);}}},ji=class extends Qe{constructor(){super(...arguments);this.type="sonic";}defaultLevels(){return wd(Pa)}machNumber(){return 1}},qi=class extends Qe{constructor(t){super(t);this.type="supersonic";this.mach===void 0&&(this.mach=D0);}defaultLevels(){return wd(Pa)}machNumber(){return Math.max(1.01,this.mach)}schema(){return {fields:[...B,{path:"mach",label:"Mach number",kind:"number",min:1.5,max:5,step:.5,group:"behavior"},{path:"waveCount",label:"Waves",kind:"number",min:3,max:12,step:1,group:"behavior"},Gr,...H]}}writeProps(){return {...super.writeProps(),mach:this.mach}}readProps(t){super.readProps(t),typeof t.mach=="number"&&Number.isFinite(t.mach)&&(this.mach=Math.max(1.01,Math.min(20,t.mach)));}};var lm=pe([.236,.382,.5,.618,.786,1,1.618,2.618,4.236,6.854,11.09]),N0=2,La=class extends Qe{constructor(){super(...arguments);this.type="goldensonic";}shouldSyncWaveCount(){return false}defaultLevels(){return lm}machNumber(){return 1}schema(){return {fields:[...B,Gr,...H]}}},Ma=class extends Qe{constructor(t){super(t);this.type="goldensupersonic";this.mach===void 0&&(this.mach=N0);}shouldSyncWaveCount(){return false}defaultLevels(){return lm}machNumber(){return Math.max(1.01,this.mach)}schema(){return {fields:[...B,{path:"mach",label:"Mach number",kind:"number",min:1.5,max:5,step:.5,group:"behavior"},Gr,...H]}}writeProps(){return {...super.writeProps(),mach:this.mach}}readProps(t){super.readProps(t),typeof t.mach=="number"&&Number.isFinite(t.mach)&&(this.mach=Math.max(1.01,Math.min(20,t.mach)));}};var Oe=class extends G{legRatios(){return false}fillTriangles(){return []}necklineIndices(){return null}anchorSchema(){let e=this.vertexLabels().length,t=[];for(let n=0;n<e;n+=1)t.push({role:`p${n}`,free:"both"});return {min:e,max:e,slots:t}}handlePoints(e){let t=[];for(let n of this.anchors){let i=e.yOf(n.price,this.paneId);if(i==null)return [];t.push([e.xOf(n.time),i]);}return t}hitTest(e,t,n,i){let o=this.handlePoints(n);return o.length>=2&&Hr(e,t,o)<=i}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),i=t.map(a=>a[1]),o=Math.min(...n),s=Math.min(...i);return {x:o,y:s,w:Math.max(...n)-o,h:Math.max(...i)-s}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}patternName(){return null}ratioOk(e){return null}valid(){return null}ratioAt(e){let t=this.anchors[e-2],n=this.anchors[e-1],i=this.anchors[e];if(!t||!n||!i)return null;let o=Math.abs(n.price-t.price);return o<1e-9?null:Math.abs(i.price-n.price)/o}schema(){return {fields:[...B,...this.fillTriangles().length?ue:[]]}}};var ka=class extends Oe{constructor(){super(...arguments);this.type="xabcd";}vertexLabels(){return ["X","A","B","C","D"]}legRatios(){return true}fillTriangles(){return [[0,1,2],[2,3,4]]}};var Ia=class extends Oe{constructor(){super(...arguments);this.type="abcd";}vertexLabels(){return ["A","B","C","D"]}legRatios(){return true}};var Aa=class extends Oe{constructor(){super(...arguments);this.type="elliottimpulse";}vertexLabels(){return ["1","2","3","4","5"]}};var Ra=class extends Oe{constructor(){super(...arguments);this.type="elliottcorrection";}vertexLabels(){return ["A","B","C"]}};var Da=class extends Oe{constructor(){super(...arguments);this.type="headshoulders";}vertexLabels(){return ["","LS","","H","","RS",""]}necklineIndices(){return [2,4]}};var et=class extends Oe{vertexLabels(){return ["X","A","B","C","D"]}legRatios(){return true}fillTriangles(){return [[0,1,2],[2,3,4]]}legValue(e){let[t,n,i,o,s]=this.anchors;if(!t||!n||!i||!o||!s)return null;let a=(u,h)=>Math.abs(h.price-u.price),l=a(t,n),c=a(n,i),d=a(i,o);switch(e){case "ab":return l<1e-9?null:c/l;case "bc":return c<1e-9?null:d/c;case "cd":return d<1e-9?null:a(o,s)/d;default:return l<1e-9?null:a(n,s)/l}}inBand(e,t){return e!=null&&e>=t.min&&e<=t.max}ratioOk(e){let t=this.ranges();return e===2?this.inBand(this.legValue("ab"),t.ab):e===3?this.inBand(this.legValue("bc"),t.bc):e===4?this.inBand(this.legValue("cd"),t.cd):null}valid(){if(this.anchors.length<5)return null;let e=this.ranges();return this.inBand(this.legValue("ab"),e.ab)&&this.inBand(this.legValue("bc"),e.bc)&&this.inBand(this.legValue("cd"),e.cd)&&this.inBand(this.legValue("ad"),e.ad)}};var Oa=class extends et{constructor(){super(...arguments);this.type="gartley";}patternName(){return "Gartley"}ranges(){return {ab:{min:.55,max:.68},bc:{min:.382,max:.886},cd:{min:1.13,max:1.618},ad:{min:.74,max:.83}}}};var Na=class extends et{constructor(){super(...arguments);this.type="bat";}patternName(){return "Bat"}ranges(){return {ab:{min:.382,max:.5},bc:{min:.382,max:.886},cd:{min:1.618,max:2.618},ad:{min:.84,max:.92}}}};var Fa=class extends et{constructor(){super(...arguments);this.type="butterfly";}patternName(){return "Butterfly"}ranges(){return {ab:{min:.74,max:.83},bc:{min:.382,max:.886},cd:{min:1.618,max:2.618},ad:{min:1.272,max:1.618}}}};var Va=class extends et{constructor(){super(...arguments);this.type="crab";}patternName(){return "Crab"}ranges(){return {ab:{min:.382,max:.618},bc:{min:.382,max:.886},cd:{min:2.618,max:3.618},ad:{min:1.55,max:1.69}}}};var _a=class extends et{constructor(){super(...arguments);this.type="shark";}patternName(){return "Shark"}ranges(){return {ab:{min:.382,max:.618},bc:{min:1.13,max:1.618},cd:{min:1.618,max:2.24},ad:{min:.886,max:1.13}}}};var F0={min:1.272,max:1.414},V0={min:.74,max:.83},Ba=class extends et{constructor(){super(...arguments);this.type="cypher";}patternName(){return "Cypher"}ranges(){return {ab:{min:.382,max:.618},bc:{min:0,max:1/0},cd:{min:0,max:1/0},ad:{min:0,max:1/0}}}xcOverXa(){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[3];if(!t||!n||!i)return null;let o=Math.abs(n.price-t.price);return o<1e-9?null:Math.abs(i.price-t.price)/o}cdOverXc(){let t=this.anchors[0],n=this.anchors[3],i=this.anchors[4];if(!t||!n||!i)return null;let o=Math.abs(n.price-t.price);return o<1e-9?null:Math.abs(i.price-n.price)/o}ratioOk(t){return t===2?this.inBand(this.legValue("ab"),this.ranges().ab):null}valid(){return this.anchors.length<5?null:this.inBand(this.legValue("ab"),this.ranges().ab)&&this.inBand(this.xcOverXa(),F0)&&this.inBand(this.cdOverXc(),V0)}};function cm(r){return `${r>=0?"+":""}${r.toFixed(2)}`}function Zi(r){let e=Math.abs(r),t=864e5,n=36e5,i=6e4;if(e>=t){let o=Math.floor(e/t),s=Math.round(e%t/n);return s?`${o}d ${s}h`:`${o}d`}if(e>=n){let o=Math.floor(e/n),s=Math.round(e%n/i);return s?`${o}h ${s}m`:`${o}h`}return e>=i?`${Math.round(e/i)}m`:`${Math.round(e/1e3)}s`}var ur=class extends G{constructor(e){super(e),this.showPrice===void 0&&(this.showPrice=true),this.showDate===void 0&&(this.showDate=true);}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}measureLabel(e){let t=[];return this.showPrice&&t.push(this.priceLabel()),this.showDate&&t.push(this.timeLabel(e)),t}isUp(){let e=this.anchors[0],t=this.anchors[1];return e!=null&&t!=null&&t.price>=e.price}priceLabel(){let e=this.anchors[0],t=this.anchors[1];if(!e||!t)return "";let n=t.price-e.price,i=e.price!==0?n/e.price*100:0;return `${cm(n)} (${cm(i)}%)`}timeLabel(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return "";let i=Zi(n.time-t.time),o=e.barsBetween?Math.round(e.barsBetween(t.time,n.time)):null;return o!=null?`${o} bars, ${i}`:i}rect(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=e.yOf(t.price,this.paneId),o=e.yOf(n.price,this.paneId);return i==null||o==null?null:{x1:e.xOf(t.time),y1:i,x2:e.xOf(n.time),y2:o}}hitTest(e,t,n,i){let o=this.rect(n);return o!=null&&Fe(e,t,o.x1,o.y1,o.x2,o.y2,i)}handlePoints(e){let t=this.rect(e);return t?[[t.x1,t.y1],[t.x2,t.y2]]:[]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.rect(e);return t?{x:Math.min(t.x1,t.x2),y:Math.min(t.y1,t.y2),w:Math.abs(t.x2-t.x1),h:Math.abs(t.y2-t.y1)}:null}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[{path:"showPrice",label:"Show price",kind:"boolean",group:"behavior"},{path:"showDate",label:"Show date",kind:"boolean",group:"behavior"},...B.filter(e=>e.path!=="style.lineColor"),{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Ct,group:"text"}]}}writeProps(){return {showPrice:this.showPrice,showDate:this.showDate}}readProps(e){typeof e.showPrice=="boolean"&&(this.showPrice=e.showPrice),typeof e.showDate=="boolean"&&(this.showDate=e.showDate);}};var Ha=class extends ur{constructor(){super(...arguments);this.type="datepricerange";}};var za=[{value:"long",label:"Long"},{value:"short",label:"Short"}],Ee=class Ee extends G{constructor(t){super(t);this.type="position";this.riskPercent===void 0&&(this.riskPercent=Ee.DEFAULT_RISK_PERCENT),this.accountBalance===void 0&&(this.accountBalance=Ee.DEFAULT_ACCOUNT_BALANCE),this.showText===void 0&&(this.showText=true),this.showHeader===void 0&&(this.showHeader=true),this.showPrices===void 0&&(this.showPrices=false),this.showLossSize===void 0&&(this.showLossSize=true),this.showTargetLabel===void 0&&(this.showTargetLabel=true),this.showStopLabel===void 0&&(this.showStopLabel=true),this.profitColor===void 0&&(this.profitColor=Ee.DEFAULT_PROFIT_COLOR),this.lossColor===void 0&&(this.lossColor=Ee.DEFAULT_LOSS_COLOR);}directionLabel(){let t=this.prices();return t&&t.target>=t.entry?"LONG":"SHORT"}get direction(){return this.directionLabel()==="LONG"?"long":"short"}set direction(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];!n||!i||!o||(t==="long"||t==="short")&&t!==this.direction&&(i.price=2*n.price-i.price,o.price=2*n.price-o.price);}get quantity(){return this.positionSize()}set quantity(t){let n=this.prices();if(!n||!Number.isFinite(t)||t<0)return;let i=Math.abs(n.entry-n.stop);i<1e-9||this.accountBalance<=0||(this.riskPercent=t*i/this.accountBalance*100);}get entryPrice(){return this.anchors[0]?.price??0}set entryPrice(t){let n=this.anchors[0];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(0));}get stopPrice(){return this.anchors[1]?.price??0}set stopPrice(t){let n=this.anchors[1];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(1));}get targetPrice(){return this.anchors[2]?.price??0}set targetPrice(t){let n=this.anchors[2];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(2));}anchorSchema(){return {min:2,max:2,slots:[{role:"entry",free:"both"},{role:"stop",free:"both"},{role:"target",free:"both"}]}}onPlaced(t){let n=this.anchors[0];if(!n)return;let i=t.xOf(n.time),o=t.yOf(n.price,this.paneId);if(o==null)return;let s=this.anchors[1],a=s?t.yOf(s.price,this.paneId):null,l,c;s&&a!=null&&Math.abs(a-o)>=Ee.MIN_DRAG_PX?(l=a,c=i+Math.max(Math.abs(t.xOf(s.time)-i),Ee.MIN_WIDTH_PX)):(l=o-Ee.DEFAULT_RISK_PX*Ee.DEFAULT_RR,c=i+Ee.DEFAULT_WIDTH_PX);let d=o-(l-o)/Ee.DEFAULT_RR,u=t.pxToPoint(c,o,this.paneId).time;this.anchors=[{time:n.time,price:n.price},{time:u,price:t.pxToPoint(i,d,this.paneId).price},{time:u,price:t.pxToPoint(i,l,this.paneId).price}];}constrainHandleDrag(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return;let s=Math.sign(i.price-n.price),a=Math.sign(o.price-n.price);s===0||a===0||s!==a||(t===2?i.price=2*n.price-i.price:o.price=2*n.price-o.price);}resolved(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;if(this.anchors[2])return [t,n,this.anchors[2]];let i={time:n.time,price:t.price-(n.price-t.price)/Ee.DEFAULT_RR};return [t,i,n]}prices(){let t=this.resolved();return t?{entry:t[0].price,stop:t[1].price,target:t[2].price}:null}rr(){let t=this.prices();if(!t)return 0;let n=Math.abs(t.entry-t.stop);return n<1e-9?0:Math.abs(t.target-t.entry)/n}rewardPct(){let t=this.prices();return t&&t.entry!==0?Math.abs(t.target-t.entry)/t.entry*100:0}riskPct(){let t=this.prices();return t&&t.entry!==0?Math.abs(t.entry-t.stop)/t.entry*100:0}dollarLoss(){return Math.max(0,this.accountBalance)*(Math.max(0,this.riskPercent)/100)}positionSize(){let t=this.prices();if(!t)return 0;let n=Math.abs(t.entry-t.stop);return n<1e-9?0:this.dollarLoss()/n}headerLabel(){return `${this.directionLabel()} \xB7 R:R ${this.rr().toFixed(2)}`}lossSizeLabel(){return `Loss $${_0(this.dollarLoss())} \xB7 Size ${B0(this.positionSize())}`}targetLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${dm(t.target)}`:"";return `Target +${this.rewardPct().toFixed(2)}%${n}`}stopLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${dm(t.stop)}`:"";return `Stop \u2212${this.riskPct().toFixed(2)}%${n}`}levelDisplayValue(t,n){let i=this.prices();if(!i)return 0;let o=t==="stop"?i.stop:i.target;return um(n==="price"?o:Math.abs(o-i.entry))}levelPriceFromDisplay(t,n,i){let o=this.prices();if(!o||n==="price")return i;let s=t==="stop"?o.stop:o.target,a=Math.sign(s-o.entry);return a===0&&(a=(t==="target"?1:-1)*(this.direction==="long"?1:-1)),o.entry+a*Math.abs(i)}box(t){let n=this.handlePoints(t);if(n.length<3)return null;let i=n.map(o=>o[0]);return {x1:Math.min(...i),x2:Math.max(...i),ey:n[0][1],sy:n[1][1],ty:n[2][1]}}layout(t){return this.box(t)}hitTest(t,n,i,o){let s=this.box(i);if(!s)return false;let a=Math.min(s.ey,s.sy,s.ty),l=Math.max(s.ey,s.sy,s.ty);return Fe(t,n,s.x1,a,s.x2,l,o)}handlePoints(t){let n=this.resolved();if(!n)return [];let i=[];for(let o of n){let s=t.yOf(o.price,this.paneId);if(s==null)return [];i.push([t.xOf(o.time),s]);}return i}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.box(t);if(!n)return null;let i=Math.min(n.ey,n.sy,n.ty);return {x:n.x1,y:i,w:n.x2-n.x1,h:Math.max(n.ey,n.sy,n.ty)-i}}priceRange(){let t=this.resolved();if(!t)return null;let n=t.map(i=>i.price);return {min:Math.min(...n),max:Math.max(...n)}}schema(){return {fields:[{path:"riskPercent",label:"Risk %",kind:"number",min:0,max:100,step:.1,group:"behavior"},{path:"accountBalance",label:"Account balance",kind:"number",min:0,max:1e12,step:1,group:"behavior"},{path:"quantity",label:"Position size",kind:"number",group:"behavior"},{path:"direction",label:"Direction",kind:"select",options:za,group:"behavior"},{path:"entryPrice",label:"Entry price",kind:"number",group:"behavior"},{path:"stopPrice",label:"Stop price",kind:"number",group:"behavior"},{path:"targetPrice",label:"Target price",kind:"number",group:"behavior"},{path:"showText",label:"Show text",kind:"boolean",group:"behavior"},{path:"showHeader",label:"Show direction & ratio",kind:"boolean",group:"behavior"},{path:"showLossSize",label:"Show loss & size",kind:"boolean",group:"behavior"},{path:"showTargetLabel",label:"Show target label",kind:"boolean",group:"behavior"},{path:"showStopLabel",label:"Show stop label",kind:"boolean",group:"behavior"},{path:"showPrices",label:"Show level prices",kind:"boolean",group:"behavior"},{path:"profitColor",label:"Profit zone",kind:"color",group:"fill"},{path:"lossColor",label:"Loss zone",kind:"color",group:"fill"},...B.filter(t=>t.path!=="style.lineColor"),{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Ct,group:"text"}]}}writeProps(){return {riskPercent:this.riskPercent,accountBalance:this.accountBalance,showText:this.showText,showHeader:this.showHeader,showPrices:this.showPrices,showLossSize:this.showLossSize,showTargetLabel:this.showTargetLabel,showStopLabel:this.showStopLabel,profitColor:this.profitColor,lossColor:this.lossColor}}readProps(t){typeof t.riskPercent=="number"&&Number.isFinite(t.riskPercent)&&(this.riskPercent=t.riskPercent),typeof t.accountBalance=="number"&&Number.isFinite(t.accountBalance)&&(this.accountBalance=t.accountBalance),typeof t.showText=="boolean"&&(this.showText=t.showText),typeof t.showHeader=="boolean"&&(this.showHeader=t.showHeader),typeof t.showPrices=="boolean"&&(this.showPrices=t.showPrices),typeof t.showLossSize=="boolean"&&(this.showLossSize=t.showLossSize),typeof t.showTargetLabel=="boolean"&&(this.showTargetLabel=t.showTargetLabel),typeof t.showStopLabel=="boolean"&&(this.showStopLabel=t.showStopLabel),typeof t.profitColor=="string"&&(this.profitColor=t.profitColor),typeof t.lossColor=="string"&&(this.lossColor=t.lossColor);}};Ee.DEFAULT_RR=2,Ee.MIN_DRAG_PX=6,Ee.DEFAULT_RISK_PX=64,Ee.DEFAULT_WIDTH_PX=150,Ee.MIN_WIDTH_PX=48,Ee.DEFAULT_RISK_PERCENT=1,Ee.DEFAULT_ACCOUNT_BALANCE=1e4,Ee.DEFAULT_PROFIT_COLOR=Ds,Ee.DEFAULT_LOSS_COLOR=Os;var ht=Ee;function _0(r){if(!Number.isFinite(r))return "0";let e=Math.round(r*100)/100;return Number.isInteger(e)?String(e):e.toFixed(2)}function B0(r){return !Number.isFinite(r)||r===0?"0":r>=100?r.toFixed(2):r>=1?r.toFixed(4).replace(/\.?0+$/,""):r.toPrecision(4).replace(/\.?0+$/,"")}function dm(r){return Number.isFinite(r)?Math.abs(r)>=1?r.toFixed(2):r.toPrecision(4).replace(/\.?0+$/,""):"0"}function um(r){return Math.round(r*1e8)/1e8}var hr=[{value:"auto",label:"Auto",ms:0},{value:"1",label:"1m",ms:6e4},{value:"5",label:"5m",ms:3e5},{value:"15",label:"15m",ms:9e5},{value:"30",label:"30m",ms:18e5},{value:"60",label:"1h",ms:36e5},{value:"240",label:"4h",ms:144e5},{value:"D",label:"1D",ms:864e5}];function Ji(r){let e=hr.find(n=>n.value===r);if(e)return e.label;let t=Number(r);return Number.isFinite(t)&&t>0?t%1440===0?`${t/1440}D`:t%60===0?`${t/60}h`:`${t}m`:r}function hm(){return {timeframe:"auto",upColor:"",downColor:""}}var tt=class extends G{constructor(t){super(t);this.type="magnifier";this.chipRect=null;this.magnifier||(this.magnifier=hm());}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}placementMode(){return "drag"}rect(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?null:{x1:t.xOf(n.time),y1:o,x2:t.xOf(i.time),y2:s}}hitTest(t,n,i,o){let s=this.rect(i);return s?Fe(t,n,s.x1,s.y1,s.x2,s.y2)?true:[[s.x1,s.y1,s.x2,s.y1],[s.x2,s.y1,s.x2,s.y2],[s.x2,s.y2,s.x1,s.y2],[s.x1,s.y2,s.x1,s.y1]].some(l=>ne(t,n,l[0],l[1],l[2],l[3])<=o):false}handlePoints(t){let n=this.rect(t);return n?[[n.x1,n.y1],[n.x2,n.y2]]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.rect(t);return n?{x:Math.min(n.x1,n.x2),y:Math.min(n.y1,n.y2),w:Math.abs(n.x2-n.x1),h:Math.abs(n.y2-n.y1)}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[{path:"magnifier.timeframe",label:"Timeframe",kind:"select",options:hr,group:"behavior"},...B.map(t=>({...t,label:t.label.replace("Line","Border")})),{path:"magnifier.upColor",label:"Up candles",kind:"color",group:"fill"},{path:"magnifier.downColor",label:"Down candles",kind:"color",group:"fill"}]}}writeProps(){return {...this.magnifier}}readProps(t){this.magnifier={...hm(),...t};}};var Qi=new Map;function V(r){Qi.set(r.type,r);}function Et(r){return Qi.get(r)}function $a(){return [...Qi.values()]}function Rn(r,e){let t=Qi.get(r);if(!t)return null;let n={...t.defaultStyle,...e.style??{}};return t.create({...e,style:n})}function Wa(r){let e=Rn(r.type,{paneId:r.paneId});if(!e)return;r.style={...e.style};let t=r.text?.value;e.text?(r.text={...e.text},t!==void 0&&(r.text.value=t)):r.text=void 0;let n=e.serialize().props;n!==void 0&&r.applyProps(n);}function pt(r){let e=Qi.get(r.type);return e?e.create(r):null}var H0=R('<line x1="4" y1="19" x2="20" y2="5"/>'),z0=R('<line x1="3" y1="12" x2="21" y2="12"/>');V({type:"trendline",group:"lines",label:"Trend Line",icon:H0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Vs(r)});V({type:"hline",group:"lines",label:"Horizontal Line",icon:z0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"dashed"},create:r=>new _s(r)});var $0=R('<line x1="3" y1="20" x2="21" y2="6"/><circle cx="3" cy="20" r="1.6" fill="currentColor"/>'),W0=R('<rect x="4" y="6" width="16" height="12" rx="1"/>'),G0=R('<path d="M5 6h14M12 6v13"/>');V({type:"ray",group:"lines",label:"Ray",icon:$0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Bs(r)});var U0=R('<path d="M5 19 19 5"/><path d="M5 19 8.5 19M5 19 5 15.5"/><path d="M19 5 15.5 5M19 5 19 8.5"/>'),Y0=R('<line x1="12" y1="3" x2="12" y2="21"/>'),K0=R('<line x1="5" y1="12" x2="21" y2="12"/><circle cx="5" cy="12" r="1.6" fill="currentColor"/>'),X0=R('<line x1="3" y1="12" x2="21" y2="12"/><line x1="12" y1="3" x2="12" y2="21"/>'),j0=R('<path d="M4 20 20 4"/><rect x="9" y="9" width="9" height="6" rx="1"/>'),q0=R('<path d="M4 20 20 6"/><path d="M4 20 15 20"/><path d="M11 20a7 7 0 0 0-2-4.9"/>');V({type:"extendedline",group:"lines",label:"Extended Line",icon:U0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Hs(r)});V({type:"vline",group:"lines",label:"Vertical Line",icon:Y0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new zs(r)});V({type:"hray",group:"lines",label:"Horizontal Ray",icon:K0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new $s(r)});V({type:"crossline",group:"lines",label:"Cross Line",icon:X0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ws(r)});V({type:"infoline",group:"lines",label:"Info Line",icon:j0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Gs(r)});V({type:"trendangle",group:"lines",label:"Trend Angle",icon:q0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Us(r)});V({type:"box",group:"shapes",label:"Rectangle",icon:W0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}26`},create:r=>new Ys(r)});V({type:"text",group:"annotations",label:"Text",icon:G0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new an(r)});var Z0=R('<path d="M5 4h14a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-6l-5 5v-5H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z"/>');V({type:"callout",group:"annotations",label:"Callout",icon:Z0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new _t(r)});var J0=R('<path d="M5 4h14a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-7l-4 4v-4H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Z"/><path d="M8 8.5h8M8 12h5"/>'),Q0=R('<rect x="10" y="4.5" width="11" height="8" rx="1.5"/><path d="M10 8.5 4 16"/><circle cx="3.5" cy="16.5" r="1.6" fill="currentColor" stroke="none"/>'),eS=R('<path d="M5 4.5h14a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-7l-4 4v-4H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2Z"/>'),tS=R('<path d="M3 12 7 8h12a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H7Z"/><path d="M10.5 12.5h6" stroke-width="1.4"/>'),nS=R('<path d="M12 11.5V21"/><rect x="5" y="4" width="14" height="7" rx="1"/><path d="M9 7.5h6"/>');V({type:"note",group:"annotations",label:"Note",icon:J0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new Zn(r)});V({type:"pricenote",group:"annotations",label:"Price Note",icon:Q0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new Qn(r)});V({type:"comment",group:"annotations",label:"Comment",icon:eS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new er(r)});V({type:"pricelabel",group:"annotations",label:"Price Label",icon:tS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new Jn(r)});V({type:"signpost",group:"annotations",label:"Signpost",icon:nS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new tr(r)});var rS=R('<line x1="3" y1="16" x2="21" y2="8"/><line x1="3" y1="21" x2="21" y2="13"/>'),iS=R('<line x1="3" y1="7" x2="21" y2="10"/><line x1="3" y1="18" x2="21" y2="14"/>'),oS=R('<circle cx="4" cy="12" r="1.6" fill="currentColor"/><line x1="4" y1="12" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>');V({type:"parallelchannel",group:"channels",label:"Parallel Channel",icon:rS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new Ks(r)});V({type:"disjointchannel",group:"channels",label:"Disjoint Channel",icon:iS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new Xs(r)});var sS=R('<line x1="3" y1="7" x2="21" y2="7"/><line x1="3" y1="18" x2="21" y2="11"/>');V({type:"flattopbottom",group:"channels",label:"Flat Top/Bottom",icon:sS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new js(r)});var aS=R('<line x1="3" y1="8" x2="21" y2="4"/><line x1="3" y1="16" x2="21" y2="12"/><line x1="3" y1="12" x2="21" y2="8" stroke-dasharray="3 3"/>');V({type:"regressionchannel",group:"channels",label:"Linear Regression",icon:aS,defaultStyle:{lineColor:J,lineWidth:1,lineStyle:"solid"},create:r=>new ln(r)});V({type:"pitchfork",group:"pitchforks",label:"Pitchfork",icon:oS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new qs(r)});var lS=R('<circle cx="4" cy="8" r="1.6" fill="currentColor"/><line x1="4" y1="8" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>'),cS=R('<circle cx="6" cy="9" r="1.6" fill="currentColor"/><line x1="6" y1="9" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>'),dS=R('<line x1="4" y1="12" x2="10" y2="12"/><line x1="10" y1="8" x2="10" y2="16"/><line x1="10" y1="8" x2="21" y2="8"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="16" x2="21" y2="16"/>');V({type:"schiffpitchfork",group:"pitchforks",label:"Schiff Pitchfork",icon:lS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Zs(r)});V({type:"modifiedschiffpitchfork",group:"pitchforks",label:"Modified Schiff Pitchfork",icon:cS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Js(r)});V({type:"insidepitchfork",group:"pitchforks",label:"Inside Pitchfork",icon:dS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Qs(r)});var uS=R('<path d="M7 7h10v10"/><path d="M7 17 17 7"/>'),hS=R('<ellipse cx="12" cy="12" rx="9" ry="6"/>'),pS=R('<path d="M12 4 20 19 4 19Z"/>');V({type:"arrow",group:"shapes",label:"Arrow",icon:uS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",arrowRight:true},create:r=>new ea(r)});V({type:"ellipse",group:"shapes",label:"Ellipse",icon:hS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new ta(r)});V({type:"triangle",group:"shapes",label:"Triangle",icon:pS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new na(r)});var mS=R('<polyline points="3 17 9 10 13 14 21 5"/>'),fS=R('<path d="M9.5 12 17 4.5a2.12 2.12 0 0 1 3 3L12.5 15"/><path d="M7 14a3 3 0 0 0-3 3c0 1.3-1.2 1.5-1.5 2 .8.9 2 1.5 3.5 1.5a3.5 3.5 0 0 0 3.5-3.5 3 3 0 0 0-2.5-3Z"/>'),gS=R('<path d="M9 11 15 5l4 4-6 6H9Z"/><path d="M9 15l-2 2"/><path d="M4 21h6"/>');V({type:"polyline",group:"shapes",label:"Polyline",icon:mS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new ra(r)});V({type:"freehand",group:"shapes",label:"Brush",icon:fS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new ia(r)});V({type:"highlighter",group:"shapes",label:"Highlighter",icon:gS,defaultStyle:{lineColor:`${Ip}59`,lineWidth:14,lineStyle:"solid"},create:r=>new oa(r)});var bS=R('<circle cx="12" cy="12" r="8"/>'),vS=R('<path d="M5 14 9.5 5 19 10 14.5 19 Z"/>'),yS=R('<path d="M4 19 9 11 13 14 17 8 20 4"/><path d="M17.2 5.5 20 4 19.4 7.1"/>'),wS=R('<path d="M4 17a8 8 0 0 1 16 0"/><path d="M4 17 20 17"/>'),xS=R('<path d="M4 18Q12 1 20 14"/>'),SS=R('<path d="M12 5 12 19"/><path d="M6 11 12 5 18 11"/>'),CS=R('<path d="M12 5 12 19"/><path d="M6 13 12 19 18 13"/>');V({type:"circle",group:"shapes",label:"Circle",icon:bS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new sa(r)});V({type:"rotatedrect",group:"shapes",label:"Rotated Rectangle",icon:vS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}26`},create:r=>new aa(r)});V({type:"path",group:"shapes",label:"Path",icon:yS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new la(r)});V({type:"arc",group:"shapes",label:"Arc",icon:wS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}26`},create:r=>new ca(r)});V({type:"curve",group:"shapes",label:"Curve",icon:xS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new da(r)});V({type:"arrowmarkup",group:"shapes",label:"Arrow Mark Up",icon:SS,defaultStyle:{lineColor:z,lineWidth:1,lineStyle:"solid"},create:r=>new Gi(r)});V({type:"arrowmarkdown",group:"shapes",label:"Arrow Mark Down",icon:CS,defaultStyle:{lineColor:W,lineWidth:1,lineStyle:"solid"},create:r=>new Ui(r)});var TS=R('<path d="M6 21V4"/><path d="M6 5h11l-2.5 3.5L17 12H6" fill="currentColor" stroke="none"/>'),ES=R('<path d="m12 3 2.6 5.8 6.4.6-4.8 4.2 1.4 6.2L12 16.9 6.4 19.8 7.8 13.6 3 9.4l6.4-.6Z"/>');V({type:"flagmark",group:"stamps",label:"Flag",icon:TS,defaultStyle:{lineColor:Ye,lineWidth:1,lineStyle:"solid"},create:r=>new Yi(r)});V({type:"iconstamp",group:"stamps",label:"Icon",icon:ES,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ki(r)});var PS=R('<line x1="3" y1="5" x2="21" y2="5"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="3" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/>'),LS=R('<line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="11" x2="21" y2="11"/><line x1="3" y1="15" x2="14" y2="15"/><line x1="3" y1="20" x2="14" y2="20"/>');V({type:"fibretracement",group:"fibonacci",label:"Fib Retracement",icon:PS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new pa(r)});V({type:"fibextension",group:"fibonacci",label:"Fib Extension",icon:LS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ma(r)});var MS=R('<path d="M3 20 10 9l4 5"/><path d="M14 14h7M14 9h7M14 4h7"/>');V({type:"fibextensiontrend",group:"fibonacci",label:"Trend-Based Fib Extension",icon:MS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new fa(r)});var kS=R('<path d="M4 20 20 5M4 20 21 11M4 20 21 17M4 20 20 20"/>'),IS=R('<path d="M3 5v14M6 5v14M11 5v14M19 5v14"/>');V({type:"fibfan",group:"fibonacci",label:"Fib Fan",icon:kS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ga(r)});V({type:"fibtimezones",group:"fibonacci",label:"Fib Time Zones",icon:IS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"dashed"},create:r=>new ba(r)});var AS=R('<path d="M3 18 18 9M5 21 20 12M6 13 21 4"/>'),RS=R('<path d="M4 4 20 20M4 4 20 12M4 4 12 20M4 4 20 4M4 4 4 20"/>'),DS=R('<path d="M3 19 9 8M9 8 12 5v14M14 5v14M18 5v14M21 5v14"/>');V({type:"fibchannel",group:"fibonacci",label:"Fib Channel",icon:AS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new va(r)});V({type:"fibspeedfan",group:"fibonacci",label:"Fib Speed Resistance Fan",icon:RS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ya(r)});V({type:"trendfibtime",group:"fibonacci",label:"Trend-Based Fib Time",icon:DS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"dashed"},create:r=>new wa(r)});var OS=R('<circle cx="12" cy="12" r="3"/><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="10"/>'),NS=R('<path d="M8 20a4 4 0 0 1 8 0"/><path d="M4.5 20a7.5 7.5 0 0 1 15 0"/><circle cx="12" cy="20" r="1.4" fill="currentColor" stroke="none"/>'),FS=R('<path d="M4 20 20 16M4 20 14 4"/><path d="M11.8 18.1A8 8 0 0 0 8.2 13.2"/><path d="M16.6 16.9A13 13 0 0 0 10.9 9"/>'),VS=R('<path d="M13 12a2 2 0 1 1-2-2 4 4 0 0 1 4 4 6 6 0 0 1-9 5.2 9 9 0 0 1 .5-15"/>');V({type:"fibcircles",group:"fibonacci",label:"Fib Circles",icon:OS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new xa(r)});V({type:"fibarcs",group:"fibonacci",label:"Fib Speed Resistance Arcs",icon:NS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Sa(r)});V({type:"fibwedge",group:"fibonacci",label:"Fib Wedge",icon:FS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ca(r)});V({type:"fibspiral",group:"fibonacci",label:"Fib Spiral",icon:VS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new lr(r)});var _S=R('<path d="M4 20 20 20M4 20 20 13M4 20 20 6M4 20 15 4M4 20 9 4M4 20 4 4"/>'),BS=R('<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 12h16M12 4v16M4 4 20 20" opacity="0.6"/>');V({type:"gannfan",group:"fibonacci",label:"Gann Fan",icon:_S,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ta(r)});V({type:"gannbox",group:"fibonacci",label:"Gann Box",icon:BS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ea(r)});var HS=R('<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 20 20 4M4 20 20 12M4 20 12 4" opacity="0.7"/><path d="M4 20a16 16 0 0 1 16-16" opacity="0.5"/>');V({type:"gannsquare",group:"fibonacci",label:"Gann Square",icon:HS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new cr(r)});var zS=R('<path d="M2 20h20"/><path d="M4 20a8 8 0 0 1 16 0" opacity="0.9"/><path d="M6 20a4 4 0 0 1 8 0" opacity="0.75"/><path d="M10 20a2 2 0 0 1 4 0" opacity="0.6"/><path d="M8 20v-6M12 20v-9M16 20v-6" opacity="0.45"/>');V({type:"dedekind",group:"geometry",label:"Dedekind Tessellation",icon:zS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new dr(r)});var $S=R('<circle cx="16" cy="12" r="5" opacity="0.55"/><circle cx="13" cy="12" r="3.5" opacity="0.75"/><circle cx="10.5" cy="12" r="2"/><path d="M8 4v16"/>'),WS=R('<circle cx="17" cy="12" r="4.5" opacity="0.45"/><circle cx="13" cy="12" r="3" opacity="0.7"/><circle cx="10" cy="12" r="1.6"/><path d="M6 12 16 5M6 12 16 19"/>');V({type:"sonic",group:"geometry",label:"Sonic",icon:$S,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ji(r)});V({type:"supersonic",group:"geometry",label:"Supersonic",icon:WS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new qi(r)});var GS=R('<circle cx="16" cy="12" r="5" opacity="0.4"/><circle cx="13" cy="12" r="3.2" opacity="0.65"/><circle cx="10.8" cy="12" r="1.8"/><path d="M8 4v16"/><path d="M15 8.5h2M12.5 10h2" opacity="0.5"/>'),US=R('<circle cx="17" cy="12" r="4.5" opacity="0.4"/><circle cx="12.5" cy="12" r="2.8" opacity="0.65"/><circle cx="9.8" cy="12" r="1.4"/><path d="M6 12 16 5M6 12 16 19"/>');V({type:"goldensonic",group:"geometry",label:"Golden Sonic",icon:GS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new La(r)});V({type:"goldensupersonic",group:"geometry",label:"Golden Supersonic",icon:US,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ma(r)});var YS=R('<path d="M3 18 7 8 11 14 15 6 20 16"/>'),KS=R('<path d="M4 17 9 7 14 15 20 5"/>'),XS=R('<path d="M3 19 8 9 12 13 17 5 21 9"/>'),jS=R('<path d="M4 7 11 16 20 9"/>'),qS=R('<path d="M3 18 6 12 9 16 12 5 15 16 18 12 21 18"/>');V({type:"xabcd",group:"patterns",label:"XABCD Pattern",icon:YS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ka(r)});V({type:"abcd",group:"patterns",label:"ABCD Pattern",icon:KS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ia(r)});V({type:"elliottimpulse",group:"patterns",label:"Elliott Impulse Wave (1-5)",icon:XS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Aa(r)});V({type:"elliottcorrection",group:"patterns",label:"Elliott Correction Wave (ABC)",icon:jS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ra(r)});V({type:"headshoulders",group:"patterns",label:"Head & Shoulders",icon:qS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Da(r)});var ZS=R('<path d="M3 17 7 6 12 14 17 5 21 16"/><path d="M3 17 21 16" opacity="0.45"/>'),Ur={group:"patterns",icon:ZS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"}};V({type:"gartley",label:"Gartley",...Ur,create:r=>new Oa(r)});V({type:"bat",label:"Bat",...Ur,create:r=>new Na(r)});V({type:"butterfly",label:"Butterfly",...Ur,create:r=>new Fa(r)});V({type:"crab",label:"Crab",...Ur,create:r=>new Va(r)});V({type:"shark",label:"Shark",...Ur,create:r=>new _a(r)});V({type:"cypher",label:"Cypher",...Ur,create:r=>new Ba(r)});var JS=R('<rect x="4" y="6" width="16" height="12" rx="1"/><path d="M4 18 20 6" opacity="0.5"/>');V({type:"datepricerange",group:"measure",label:"Date & Price Range",icon:JS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ha(r)});var QS=R('<rect x="4.5" y="4.5" width="15" height="7.5" rx="1" fill="currentColor" fill-opacity="0.25"/><rect x="4.5" y="12" width="15" height="7.5" rx="1"/>');V({type:"position",group:"measure",label:"Long/Short Position",icon:QS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ht(r)});var eC=R('<circle cx="10.5" cy="10.5" r="6.5"/><path d="m15.3 15.3 5.2 5.2"/><path d="M8 12.5v-3M10.5 13.5v-5.5M13 12v-2"/>');V({type:"magnifier",group:"measure",label:"Magnifier",icon:eC,defaultStyle:{lineColor:"",lineWidth:1,lineStyle:"solid"},coversSeries:true,placementHint:"Drag an area on the chart to view it at a lower timeframe",create:r=>new tt(r)});var tC=R('<line x1="5" y1="3" x2="5" y2="21"/><path d="M5 16c4 0 5-9 8-9s3 5 8 3"/>');V({type:"anchoredvwap",group:"measure",label:"Anchored VWAP",icon:tC,defaultStyle:{lineColor:Je,lineWidth:2,lineStyle:"solid"},create:r=>new nr(r)});var nC=R('<path d="M4 4v16"/><path d="M4 8h10"/><path d="M4 12h14"/><path d="M4 16h8"/><path d="M4 20h12"/>');V({type:"fixedrangevp",group:"measure",label:"Fixed Range Volume Profile",icon:nC,defaultStyle:{lineColor:z,lineWidth:1,lineStyle:"solid"},create:r=>new at(r)});var rC=["fibretracement","fibextension","fibextensiontrend","fibfan","fibtimezones","fibchannel","fibspeedfan","trendfibtime","fibcircles","fibarcs","fibwedge","fibspiral"],iC=["gannfan","gannbox","gannsquare"],oC=["dedekind","sonic","supersonic","goldensonic","goldensupersonic"],sC=["xabcd","abcd","headshoulders"],aC=["elliottimpulse","elliottcorrection"],lC=["gartley","bat","butterfly","crab","shark","cypher"],cC=["position","datepricerange","magnifier"],dC=["anchoredvwap","fixedrangevp"],uC=["freehand","highlighter"],hC=["arrow","arrowmarkup","arrowmarkdown"],pC=["box","ellipse","triangle","polyline","circle","rotatedrect","path","arc","curve"],mC=["text","callout","note","pricenote","comment","pricelabel","signpost"],fC=["flagmark","iconstamp"],gC=[{id:"lines-channels-pitchforks",label:"Lines",sections:[{label:"Lines",registryGroup:"lines"},{label:"Channels",registryGroup:"channels"},{label:"Pitchforks",registryGroup:"pitchforks"}]},{id:"fibonacci-gann",label:"Fibonacci",sections:[{label:"Fibonacci",types:rC},{label:"Gann",types:iC},{label:"Geometry",types:oC}]},{id:"patterns-waves-harmonics",label:"Patterns",sections:[{label:"Patterns",types:sC},{label:"Elliott Waves",types:aC},{label:"Harmonics",types:lC}]},{id:"measurements",label:"Measurements",sections:[{label:"Measurements",types:cC},{label:"Volume",types:dC}]},{id:"brushes-arrows-shapes",label:"Shapes",sections:[{label:"Brushes",types:uC},{label:"Arrows",types:hC},{label:"Shapes",types:pC}]},{id:"text",label:"Text",sections:[{label:"Text",types:mC}]},{id:"icons",label:"Icons",sections:[{label:"Icons",types:fC}]}];function bC(r){let e=Et(r);return e?{type:e.type,label:e.label,icon:e.icon}:null}function vC(r){let e=new Map;for(let t of $a()){if(r&&!r.has(t.type))continue;let n={type:t.type,label:t.label,icon:t.icon};e.has(t.group)||e.set(t.group,[]),e.get(t.group).push(n);}return e}function yC(r,e,t){return "registryGroup"in r?e.get(r.registryGroup)??[]:r.types.map(n=>t.get(n)).filter(n=>n!=null)}function pm(r){let e=vC(r),t=new Map;for(let i of e.values())for(let o of i)t.set(o.type,o);let n=[];for(let i of gC){let o=[],s=[];for(let a of i.sections){let l=yC(a,e,t);l.length!==0&&(o.push({label:a.label,tools:l}),s.push(...l));}s.length!==0&&n.push({id:i.id,label:i.label,tools:s,sections:o.length>0?o:void 0});}return {groups:n}}function wC(r){let e=new Set;for(let t of r)Et(t)&&e.add(t);return pm(e)}function xC(r){let e=[];for(let t of r){let n=t.tools.map(bC).filter(i=>i!=null);n.length>0&&e.push({id:t.id,label:t.label,tools:n});}return {groups:e}}function eo(){return pm()}function to(r){if(r===false)return {definition:eo(),visible:false};if(r===void 0||r===true)return {definition:eo(),visible:true};let e=r.toolbar??true;return r.groups?{definition:xC(r.groups),visible:e}:r.tools?{definition:wC(r.tools),visible:e}:{definition:eo(),visible:e}}function zt(r){let e=globalThis.structuredClone;return e?e(r):JSON.parse(JSON.stringify(r))}function mm(r){if(!r||typeof r!="object")return false;let e=r;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.paneId=="string"&&Array.isArray(e.anchors)&&e.anchors.every(t=>t&&typeof t.time=="number"&&typeof t.price=="number")&&!!e.style&&typeof e.style=="object"}function xd(r){let e=r;return !e||typeof e!="object"||e.version!==1||!Array.isArray(e.drawings)?{version:1,drawings:[]}:{version:1,drawings:e.drawings.filter(mm)}}var Yr=class{constructor(){this.byId=new Map;this.seq=0;this.zCounter=1;this.listeners=new Set;}nextId(){return this.seq+=1,`dw-${this.seq}`}add(e){return e.zIndex||(e.zIndex=this.zCounter),this.zCounter=Math.max(this.zCounter,Math.ceil(e.zIndex))+1,this.byId.set(e.id,e),this.emit(),e}remove(e){let t=this.byId.delete(e);return t&&this.emit(),t}get(e){return this.byId.get(e)}has(e){return this.byId.has(e)}update(e,t){let n=this.byId.get(e);return n?(t.anchors&&(n.anchors=t.anchors.map(i=>({time:i.time,price:i.price}))),t.style&&(n.style={...t.style}),t.text!==void 0&&(n.text=t.text?{...t.text}:void 0),t.paneId!==void 0&&(n.paneId=t.paneId),t.locked!==void 0&&(n.locked=t.locked),t.visible!==void 0&&(n.visible=t.visible),t.zIndex!==void 0&&(n.zIndex=t.zIndex),t.props!==void 0&&n.applyProps(t.props),this.emit(),n):null}all(){return [...this.byId.values()].sort((e,t)=>e.zIndex-t.zIndex)}byPane(e){return this.all().filter(t=>t.paneId===e)}bringToFront(e,t=0){let n=this.byId.get(e);n&&(n.zIndex=Math.max(this.zCounter,Math.floor(t)+1),this.zCounter=n.zIndex+1,this.emit());}sendToBack(e,t=1){let n=this.byId.get(e);if(!n)return;let i=Math.min(...[...this.byId.values()].map(o=>o.zIndex),Math.ceil(t));n.zIndex=i-1,this.emit();}setLocked(e,t){let n=this.byId.get(e);n&&(n.locked=t,this.emit());}setVisible(e,t){let n=this.byId.get(e);n&&(n.visible=t,this.emit());}clear(){this.byId.size!==0&&(this.byId.clear(),this.emit());}serialize(){return {version:1,drawings:this.all().map(e=>e.serialize())}}load(e){let t=xd(e);this.byId.clear(),this.seq=0,this.zCounter=1;for(let n of t.drawings){let i=pt(n);i&&(this.byId.set(i.id,i),this.zCounter=Math.max(this.zCounter,i.zIndex)+1,this.bumpSeqPast(i.id));}this.emit();}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}bumpSeqPast(e){let t=/^dw-(\d+)$/.exec(e);t&&(this.seq=Math.max(this.seq,Number(t[1])));}emit(){for(let e of this.listeners)e();}};var Ga=class{constructor(e=100){this.cap=e;this.undoStack=[];this.redoStack=[];this.pending=null;this.dirtied=false;this.depth=0;}begin(e){this.depth+=1,this.depth===1&&(this.pending=zt(e),this.dirtied=false);}markDirty(){this.depth===0||this.dirtied||!this.pending||(this.push(this.pending),this.dirtied=true);}commit(){this.depth!==0&&(this.depth-=1,this.depth===0&&(this.pending=null,this.dirtied=false));}abort(){this.commit();}record(e){if(this.depth>0){this.markDirty();return}this.push(zt(e));}undo(e){let t=this.undoStack.pop();return t?(this.redoStack.push(zt(e)),t):null}redo(e){let t=this.redoStack.pop();return t?(this.undoStack.push(zt(e)),t):null}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[],this.pending=null,this.dirtied=false,this.depth=0;}push(e){this.undoStack.push(e),this.undoStack.length>this.cap&&this.undoStack.shift(),this.redoStack=[];}};var Ua=class{constructor(e,t,n,i){this.events=t;this.store=new Yr;this.history=new Ga;this.activeTool=null;this.snapMode="off";this.stayInDrawingMode=false;this.mode=null;this.favs=new Set;this.selectedIds=[];this.clipboard=[];this.lastStyle=new Map;this.subs=[];if(this.enabled=!!e.capabilities.userDrawings&&!!e.userDrawingsPort,this.port=this.enabled?e.userDrawingsPort:null,this.port){let{definition:o,visible:s}=to(n);this.port.setToolbar(o),this.port.showToolbar(s),i&&this.port.setSeriesGateway?.(i),this.subs.push(this.port.onDrawingIntent(a=>this.onIntent(a))),this.subs.push(this.store.onChange(()=>this.sync()));}}get supported(){return this.enabled}setTool(e){if(!this.port)return;let t=e!==this.activeTool;this.activeTool=e,this.port.setActiveTool(e,e?this.lastStyle.get(e):void 0),t&&this.events.emit("drawing:tool",{type:e});}getTool(){return this.activeTool}getSnapMode(){return this.snapMode}setSnapMode(e){!this.port||e===this.snapMode||(this.snapMode=e,this.port.setSnapMode?.(e),this.events.emit("drawing:snap",{mode:e}));}getStayMode(){return this.stayInDrawingMode}setStayMode(e){!this.port||e===this.stayInDrawingMode||(this.stayInDrawingMode=e,this.port.setStayMode?.(e),this.events.emit("drawing:stay",{on:e}));}getMode(){return this.mode}setMode(e){!this.port||e===this.mode||(this.mode=e,this.port.setMode?.(e),this.events.emit("drawing:mode",{mode:e}));}showToolbar(e){this.port?.showToolbar(e);}favorites(){return [...this.favs]}isFavorite(e){return this.favs.has(e)}setFavorite(e,t){Et(e)&&t!==this.favs.has(e)&&(t?this.favs.add(e):this.favs.delete(e),this.pushFavorites());}setFavorites(e){let t=e.filter(n=>Et(n)!=null);t.length===this.favs.size&&t.every(n=>this.favs.has(n))||(this.favs=new Set(t),this.pushFavorites());}pushFavorites(){let e=[...this.favs];this.port?.setFavorites?.(e),this.events.emit("drawing:favorites",{favorites:e});}setToolbar(e){this.port?.setToolbar(to(e).definition);}setExternalGhost(e){this.port?.setExternalGhost?.(e);}setToolShortcuts(e){this.port?.setToolShortcuts?.(e);}add(e,t={}){if(!this.enabled)return null;let i={...this.lastStyle.get(e)??{},...t.style??{}},o=Rn(e,{id:this.store.nextId(),paneId:t.paneId??"price",anchors:t.anchors,style:i,text:t.text,props:t.props,zIndex:t.zIndex??this.startZ(e,t.paneId??"price")});return o?(this.history.record(this.store.serialize()),this.store.add(o),this.captureStyle(o.id),this.events.emit("drawing:created",{id:o.id}),o):null}remove(e){this.deleteMany([e]);}update(e,t){let n=this.store.serialize(),i=t.style?this.store.get(e):void 0,o=t.style&&i?{...t,style:{...i.style,...t.style}}:t;this.store.update(e,o)&&(this.history.record(n),this.captureStyle(e),this.events.emit("drawing:edited",{id:e}));}updateMany(e){this.history.begin(this.store.serialize());for(let{id:t,patch:n}of e)this.store.update(t,n)&&(this.history.markDirty(),this.events.emit("drawing:edited",{id:t}));this.history.commit();}removeMany(e){this.deleteMany(e);}setLocked(e,t){let n=this.store.serialize();this.history.record(n),this.store.setLocked(e,t),this.events.emit("drawing:edited",{id:e});}setVisible(e,t){let n=this.store.serialize();this.history.record(n),this.store.setVisible(e,t),this.events.emit("drawing:edited",{id:e});}bringToFront(e){let t=this.store.serialize();this.history.record(t),this.store.bringToFront(e,this.seriesTopZ(this.store.get(e)?.paneId)),this.events.emit("drawing:edited",{id:e});}sendToBack(e){let t=this.store.serialize();this.history.record(t),this.store.sendToBack(e,this.seriesBottomZ(this.store.get(e)?.paneId)),this.events.emit("drawing:edited",{id:e});}seriesTopZ(e){return e!==void 0?this.port?.stackRange?.(e)?.front??0:0}seriesBottomZ(e){return e!==void 0?this.port?.stackRange?.(e)?.back??1:1}startZ(e,t){let n=this.port?.stackRange?.(t);if(n)return Et(e)?.coversSeries?n.front+.5:(n.price??n.front)-.5}select(e,t=false){this.setSelection(e,t);}openSettings(e){this.port?.openSettings(e);}undo(){let e=this.history.undo(this.store.serialize());e&&this.restoreSnapshot(e);}redo(){let e=this.history.redo(this.store.serialize());e&&this.restoreSnapshot(e);}canUndo(){return this.history.canUndo()}canRedo(){return this.history.canRedo()}duplicate(e){if(!this.enabled)return [];let t=this.resolve(e);return t.length===0?[]:this.insertClones(t.map(n=>n.serialize()))}clone(e){return this.duplicate([e])[0]??null}copy(e){let t=this.resolve(e).map(n=>zt(n.serialize()));t.length&&(this.clipboard=t);}paste(){return !this.enabled||this.clipboard.length===0?[]:this.insertClones(this.clipboard)}all(){return this.store.serialize().drawings}toJSON(){return this.store.serialize()}fromJSON(e){this.history.clear(),this.selectedIds=[],this.store.load(e);}destroy(){for(let e of this.subs)e();this.subs.length=0;}setSelection(e,t=false){let n;if(t){n=[...this.selectedIds];for(let i of e){let o=n.indexOf(i);o>=0?n.splice(o,1):n.push(i);}}else n=[...e];this.selectedIds=n.filter(i=>this.store.has(i)),this.announceSelection();}announceSelection(){this.port?.setSelection(this.selectedIds),this.events.emit("drawing:selected",{id:this.selectedIds[0]??null,ids:[...this.selectedIds]});}restoreSnapshot(e){this.store.load(e),this.selectedIds=this.selectedIds.filter(t=>this.store.has(t)),this.announceSelection();}deleteMany(e){this.history.begin(this.store.serialize());let t=[];for(let i of e)this.store.remove(i)&&t.push(i),this.history.markDirty();if(this.history.commit(),t.length===0)return;let n=this.selectedIds.filter(i=>this.store.has(i));n.length!==this.selectedIds.length&&this.setSelection(n);for(let i of t)this.events.emit("drawing:removed",{id:i});}insertClones(e){this.history.begin(this.store.serialize());let t=[];for(let n of e){let i=pt({...n,id:this.store.nextId()});i&&(this.store.add(i),this.history.markDirty(),t.push(i));}if(this.history.commit(),t.length){this.setSelection(t.map(n=>n.id));for(let n of t)this.events.emit("drawing:created",{id:n.id});}return t}resolve(e){return e.map(t=>this.store.get(t)).filter(t=>t!=null)}captureStyle(e){let t=this.store.get(e);t&&this.lastStyle.set(t.type,{...t.style});}sync(){this.port?.syncDrawings(this.store.serialize().drawings);}onIntent(e){switch(e.kind){case "arm":this.setTool(e.type);break;case "draft":this.events.emit("drawing:draft",{doc:e.doc});break;case "create":{let t=this.store.serialize(),n=this.lastStyle.get(e.doc.type),i=n?{...e.doc.style,...n}:e.doc.style,o=pt({...e.doc,id:this.store.nextId(),style:i});if(!o)return;o.zIndex||(o.zIndex=this.startZ(o.type,o.paneId)??0),this.history.record(t),this.store.add(o),this.captureStyle(o.id),this.events.emit("drawing:created",{id:o.id});break}case "edit":{let t=this.store.serialize();this.store.update(e.doc.id,e.doc)&&(this.history.record(t),this.captureStyle(e.doc.id),this.events.emit("drawing:edited",{id:e.doc.id}));break}case "edit-many":{this.history.begin(this.store.serialize());for(let t of e.docs)this.store.update(t.id,t)&&(this.history.markDirty(),this.events.emit("drawing:edited",{id:t.id}));this.history.commit();break}case "select":this.setSelection(e.ids,e.additive);break;case "delete":this.deleteMany(e.ids);break;case "reorder":e.to==="front"?this.bringToFront(e.id):this.sendToBack(e.id);break;case "settings":this.events.emit("drawing:settings",{id:e.id});break;case "favorite":this.setFavorite(e.type,e.on);break;case "snap-mode":e.mode!==this.snapMode&&(this.snapMode=e.mode,this.events.emit("drawing:snap",{mode:e.mode}));break;case "stay-mode":e.on!==this.stayInDrawingMode&&(this.stayInDrawingMode=e.on,this.events.emit("drawing:stay",{on:e.on}));break;case "mode":e.mode!==this.mode&&(this.mode=e.mode,this.events.emit("drawing:mode",{mode:e.mode}));break;case "tool-finished":!this.stayInDrawingMode&&e.type!=="freehand"&&e.type!=="highlighter"&&this.setTool(null);break;case "undo":this.undo();break;case "redo":this.redo();break;case "duplicate":this.duplicate(e.ids);break;case "clone":this.enabled&&e.docs.length&&this.insertClones(e.docs);break;case "copy":this.copy(e.ids);break;case "paste":this.paste();break}}};var gm={D:864e5,W:6048e5,M:2592e6};function Pt(r){let e=r.trim();if(gm[e])return gm[e];let t=/^(\d+)\s*(m|h|d|w)?$/i.exec(e);if(t){let n=parseInt(t[1],10),i=(t[2]??"m").toLowerCase();return n*(i==="m"?6e4:i==="h"?36e5:i==="d"?864e5:6048e5)}return 36e5}var SC=5e3,CC=.25,TC=16,EC=15e3,Sd=["240","60","30","15","5","1"],Ya=class{constructor(e){this.deps=e;this.cache=new Map;this.listeners=new Set;}seriesInRange(e,t,n){if(!this.deps.canFetch())return {state:"unavailable",reason:"no-source"};let i=this.resolveTimeframe(e);if(typeof i!="string")return {state:"unavailable",reason:i.reason};let o=Pt(i),s=Math.min(t,n),a=Math.max(t,n);if(!(a>s)||!(o>0))return {state:"unavailable",reason:"not-lower"};if((a-s)/o>SC)return {state:"unavailable",reason:"too-wide"};let l=`${this.deps.marketKey()}|${i}`,c=this.cache.get(l)??[],d=c.find(u=>u.from<=s&&u.to>=a);if(d){if(d.pending)return this.loading(c,i,o,s,a);if(d.failedAt>0){if(Date.now()-d.failedAt<EC)return this.loading(c,i,o,s,a);c.splice(c.indexOf(d),1);}else return this.maybeRefresh(l,d,i,o,a),{state:"ready",bars:this.slice(d.bars,s,a),timeframe:i,barMs:o}}return this.fetchWindow(l,c,i,s,a),this.loading(c,i,o,s,a)}onUpdate(e){return this.listeners.add(e),()=>this.listeners.delete(e)}resolveTimeframe(e){let t=Pt(this.deps.chartTimeframe()),n=Sd[Sd.length-1];if(Pt(n)>=t)return {reason:"none-lower"};let i=e.trim()||"auto";if(i==="auto"){for(let o of Sd)if(Pt(o)<=t/4)return o;return n}return Pt(i)<t?i:{reason:"not-lower"}}loading(e,t,n,i,o){let s=new Map;for(let l of e)if(!(l.pending||l.failedAt>0)&&!(l.to<i||l.from>o))for(let c of this.slice(l.bars,i,o))s.set(c.time,c);if(s.size===0)return {state:"loading",timeframe:t,barMs:n};let a=[...s.values()].sort((l,c)=>l.time-c.time);return {state:"loading",timeframe:t,barMs:n,bars:a}}fetchWindow(e,t,n,i,o){if(t.some(l=>l.pending&&l.to>=i&&l.from<=o))return;let s=(o-i)*CC,a={from:i-s,to:o+s,bars:[],fetchedAt:0,pending:true,failedAt:0};t.push(a),this.cache.set(e,t),this.evict(),this.deps.fetchBars(n,{from:a.from,to:a.to}).then(l=>{a.bars=l,a.fetchedAt=Date.now(),a.pending=false,this.absorbOverlaps(e,a),this.fire();}).catch(()=>{a.pending=false,a.failedAt=Date.now(),this.fire();});}maybeRefresh(e,t,n,i,o){if(t.pending)return;let s=t.bars.length>0?t.bars[t.bars.length-1].time:t.from;o<s||Date.now()-t.fetchedAt<i||(t.pending=true,this.deps.fetchBars(n,{from:t.from,to:t.to}).then(a=>{t.bars=a,t.fetchedAt=Date.now(),t.pending=false,this.fire();}).catch(()=>{t.pending=false,t.fetchedAt=Date.now();}));}absorbOverlaps(e,t){let n=this.cache.get(e);if(n)for(let i=n.length-1;i>=0;i-=1){let o=n[i];if(o===t||o.pending||o.failedAt>0||o.to<t.from||o.from>t.to)continue;let s=new Map;for(let a of o.bars)s.set(a.time,a);for(let a of t.bars)s.set(a.time,a);t.bars=[...s.values()].sort((a,l)=>a.time-l.time),t.from=Math.min(t.from,o.from),t.to=Math.max(t.to,o.to),t.fetchedAt=Math.min(t.fetchedAt,o.fetchedAt||t.fetchedAt),n.splice(i,1);}}evict(){let e=0;for(let t of this.cache.values())e+=t.length;for(;e>TC;){let t=null,n=-1,i=1/0;for(let[s,a]of this.cache)for(let l=0;l<a.length;l+=1){let c=a[l];if(c.pending)continue;let d=c.fetchedAt||c.failedAt;d<i&&(t=s,n=l,i=d);}if(t==null)return;let o=this.cache.get(t);o.splice(n,1),o.length===0&&this.cache.delete(t),e-=1;}}slice(e,t,n){let i=[];for(let o of e)if(!(o.time<t)){if(o.time>n)break;i.push(o);}return i}fire(){for(let e of [...this.listeners])e();}};function no(r){return r.group!=null&&r.ticker===r.group}function bm(r){return `${(r.prefix??r.provider??"").toLowerCase()}:${(r.group??"").toUpperCase()}`}function PC(r,e){let t=bm(e);return r.filter(n=>n.group!=null&&!no(n)&&bm(n)===t)}function vm(r,e){let t=PC(r,e),n=t.filter(i=>i.default);return (n.length===1?n[0]:t[0])??null}var $t=r=>r.trim().toLowerCase(),dn=r=>r.trim().toUpperCase();function Wt(r){let e=r.trim(),t=/^(?:([A-Za-z0-9_.]+):)?(.+)$/.exec(e);if(!t)return {provider:null,ticker:e};let n=t[1]?$t(t[1]):null,i=t[2],o=i.lastIndexOf("."),s=o>0?i.slice(o+1):void 0;return {provider:n,ticker:i,ext:s}}var Ka=class{constructor(){this.entries=new Map;this.changeListeners=new Set;this.waits=new Set;this.unresolvedCbs=new Set;}register(e,t){let n=$t(e),i={name:n,provider:t,index:null,prefixIndex:null,byTicker:null,descriptors:[],settled:false,settle:Promise.resolve()};return this.entries.set(n,i),i.settle=this.buildIndex(i),queueMicrotask(()=>this.notify(false)),i.settle}async buildIndex(e){await Promise.resolve();try{if(e.provider.listSymbols){let t=await e.provider.listSymbols();e.descriptors=t,e.index=new Set(t.map(n=>dn(n.ticker))),e.byTicker=new Map(t.map(n=>[dn(n.ticker),n])),e.prefixIndex=new Map;for(let n of t)n.prefix&&e.prefixIndex.set(`${$t(n.prefix)}:${dn(n.ticker)}`,n);}}catch{e.index=null;}finally{e.settled=true,this.notify(true);}}notify(e){for(let t of [...this.changeListeners])t(e);}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}unregister(e){this.entries.delete($t(e)),this.notify(false);}has(e){return this.entries.has($t(e))}get(e){return this.entries.get($t(e))?.provider}names(){return [...this.entries.keys()]}parse(e){return Wt(e)}resolve(e,t={}){let{provider:n,ticker:i}=this.parse(e);if(n){if(this.entries.has(n)){let a=this.entries.get(n).byTicker?.get(dn(i));return {provider:n,ticker:a!=null&&no(a)?this.loadableTicker(n,a):i}}let s=`${n}:${dn(i)}`;for(let a of this.candidateOrder(t.default)){let l=this.entries.get(a).prefixIndex?.get(s);if(l)return {provider:a,ticker:this.loadableTicker(a,l)}}return null}let o=dn(i);for(let s of this.candidateOrder(t.default)){let a=this.entries.get(s);if(a.index?.has(o)){let l=a.byTicker?.get(o);return {provider:s,ticker:l!=null&&no(l)?this.loadableTicker(s,l):i}}}if(t.lenient&&this.entries.size===1){let s=this.names()[0],a=this.entries.get(s);if(a.settled&&a.index==null)return {provider:s,ticker:i}}return null}loadableTicker(e,t){return no(t)?vm(this.entries.get(e)?.descriptors??[],t)?.ticker??t.ticker:t.ticker}whenResolvable(e,t={}){let n=this.resolve(e,{...t,lenient:true});return n?Promise.resolve(n):new Promise(i=>{let o=this.onChange(a=>{let l=this.resolve(e,{...t,lenient:true});l?(s(),i(l)):a&&this.allSettled()&&this.reportUnresolved(e);}),s=()=>{o(),this.waits.delete(s);};this.waits.add(s);})}allSettled(){for(let e of this.entries.values())if(!e.settled)return false;return true}cancelWaits(){for(let e of [...this.waits])e();}onUnresolved(e){return this.unresolvedCbs.add(e),()=>this.unresolvedCbs.delete(e)}reportUnresolved(e){let t=this.names();console.warn(`[vela] symbol "${e}" not yet resolvable \u2014 registered providers: [${t.join(", ")||"none"}]. Register a provider that serves it.`);for(let n of this.unresolvedCbs)n({symbol:e,providers:t});}candidateOrder(e){let t=this.names();if(e){let n=$t(e);if(this.entries.has(n))return [n,...t.filter(i=>i!==n)]}return t}displayPrefixOf(e){return this.entries.get(e.provider)?.byTicker?.get(dn(e.ticker))?.prefix??e.provider}canonicalSymbol(e){let t=this.entries.get(e.provider)?.byTicker?.get(dn(e.ticker));return `${t?.prefix??e.provider}:${t?.ticker??e.ticker}`}symbolIconOf(e){let t=e.provider?$t(e.provider):[...this.entries.keys()][0],n=t!==void 0?this.entries.get(t):void 0;try{return n?.provider.resolveSymbolIcon?.(e)??void 0}catch{return}}symbolIcon(e){if(!e)return;let t=this.entries.get(e.provider)?.byTicker?.get(dn(e.ticker));return this.symbolIconOf({...t??{ticker:e.ticker},provider:t?.provider??e.provider})}symbolsOf(e){return e!=null?this.entries.get($t(e))?.descriptors??[]:[...this.entries.entries()].flatMap(([t,n])=>n.descriptors.map(i=>({...i,provider:t})))}infoOf(e){let t=$t(e),n=this.entries.get(t);if(!n)return {name:t,capabilities:{enumerate:false,stream:false,symbolInfo:false}};let i=n.provider;return i.info?.()??{name:n.name,capabilities:{enumerate:!!i.listSymbols,stream:!!i.subscribe,symbolInfo:!!i.getSymbolInfo}}}indexReady(){return Promise.all([...this.entries.values()].map(e=>e.settle)).then(()=>{})}};function Kr(r){switch(r.kind){case "row":return {label:r.label,toggle:r.toggle,controls:r.controls,when:r.when};case "toggle":{let e=[];r.number&&e.push({kind:"number",...r.number});for(let t of r.colors??[])e.push({kind:"color",...t});return r.width&&e.push({kind:"width",...r.width}),{label:r.label,toggle:{key:r.key,defval:r.defval},controls:e,when:r.when}}case "number":return {label:r.label,controls:[{kind:"number",key:r.key,label:r.label,defval:r.defval,min:r.min,max:r.max,step:r.step}],when:r.when};case "color":return {label:r.label,controls:[{kind:"color",key:r.key,label:r.label,defval:r.defval}],when:r.when};case "select":return {label:r.label,controls:[{kind:"select",key:r.key,label:r.label,options:r.options,defval:r.defval}],when:r.when};case "range":return {label:r.label,controls:[{kind:"number",key:r.minKey,label:`${r.label} \u2014 min`,defval:r.defval,min:r.min,max:r.max,step:r.step,placeholder:r.placeholder},{kind:"hint",text:"\u2013"},{kind:"number",key:r.maxKey,label:`${r.label} \u2014 max`,defval:r.defval,min:r.min,max:r.max,step:r.step,placeholder:r.placeholder}],when:r.when}}}function ro(r){if(r.kind==="heading"||r.kind==="header")return [];let e=Kr(r),t=[];e.toggle&&t.push({key:e.toggle.key,type:"boolean",defval:e.toggle.defval});for(let n of e.controls)n.kind!=="hint"&&(n.kind==="color"||n.kind==="select"?t.push({key:n.key,type:"string",defval:n.defval}):t.push({key:n.key,type:"number",defval:n.defval}));return t}function pr(r,e){return r?(Array.isArray(r)?r:[r]).every(n=>n.anyOf?n.anyOf.some(i=>i===e[n.key]):e[n.key]===n.equals):true}var io=new Map;function Cd(r){io.set(r.id,r);}function LC(r){io.delete(r);}function un(r){return typeof r=="string"?io.get(r):void 0}function Lt(){return [...io.values()]}function Td(){return [...io.values()].filter(r=>r.tickerModifier??r.barTransform!=null).map(r=>r.id)}function Xr(r){return un(r)?.barTransform??null}function ym(r){let e=r.lastIndexOf(";");if(e<=0||e===r.length-1)return {symbol:r,modifier:null,transform:null};let t=r.slice(e+1).toLowerCase();return t!=="standard"&&!Td().includes(t)?{symbol:r,modifier:null,transform:null}:{symbol:r.slice(0,e),modifier:t,transform:Xr(t)}}var Gt={background:"#151619",textColor:"#b2b5be",gridColor:"#20222c",borderColor:"#2a2b30",upColor:z,downColor:W,fontFamily:"sans-serif"},oo={background:"#ffffff",textColor:"#1e293b",gridColor:"#cccccc",borderColor:"#d4dae3",upColor:z,downColor:W,fontFamily:"sans-serif"};function jr(r){return !r||r==="dark"?Gt:r==="light"?oo:r}var MC=150,kC=1e3,IC=300,AC=5e3,wm=1e4,RC=20,DC=1.5,xm=5e3,Xa=class r{constructor(e,t,n,i,o,s){this.renderer=t;this.feed=n;this.config=o;this.dataControl=s;this.events=new qn;this.registry=new ks;this.paneOrder=["price"];this.collapsedPanes=new Set;this.maximizedPaneId=null;this.paneActionUnsub=null;this.handles=new Map;this.engines=new Map;this.live=null;this.bars=[];this.rawBars=[];this.barTransform=null;this.typeEngines=new Map;this.typeSettings=new Map;this.activeEngineStyle=null;this.priceStyle="candles";this.unresolvedUnsub=null;this.visibleRange=null;this.viewportUnsub=null;this.viewportTimer=null;this.healing=false;this.healBuffer=[];this.lastHealAt=0;this.onVisible=null;this.barCause="tick";this.historyState="complete";this.generation=0;this.progressiveAbort=null;this.supersedeWaiters=[];this.historyCompleted=false;this.historyCompletePromise=new Promise(e=>{this.resolveHistoryComplete=e;});this.switchingMarket=false;this.loadingUp=false;this.volumeOptedOut=false;this.contextEmitAt=new Map;this.runEmitAt=new Map;for(let c of i)this.registerEngine(c.language,c);this.defaultLanguage=o.defaultLanguage,this.renderer.mount(e,o.theme),this.renderer.onInputChange(c=>c.kind==="prop"?this.applyProps(c.indicatorId,{[c.key]:c.value}):this.applyInputs(c.indicatorId,{[c.key]:c.value})),this.renderer.onRemoveIndicator(c=>this.removeIndicator(c)),this.renderer.onToggleIndicatorVisible?.((c,d)=>this.setVisible(c,d)),this.paneActionUnsub=this.renderer.onPaneAction?.(c=>this.handlePaneAction(c))??null,this.renderer.onChartTypeSettingsChange?.((c,d)=>{this.typeSettings.set(c,d),this.typeEngines.get(c)?.onSettings?.(d);}),this.renderer.onMoveIndicator?.((c,d)=>this.moveIndicator(c,d)),this.renderer.onThemeSelect?.(c=>this.setTheme(jr(c))),this.viewportUnsub=this.renderer.onViewportChange(c=>this.onViewportChange(c)),this.renderer.onPriceStyleChange?.(c=>this.syncPriceStyle(c));let a=this.renderer.readFeature("priceStyle");typeof a=="string"&&(this.priceStyle=a),this.barTransform=Xr(a);let l=new Ya({fetchBars:(c,d)=>this.fetchSeries(this.config.market.symbol??"",c,d),canFetch:()=>!!this.feed.loadRange&&!this.config.market.data?.length&&!!this.config.market.symbol,chartTimeframe:()=>this.config.market.timeframe??"60",marketKey:()=>`${this.config.market.symbol??""}|${this.config.market.session??""}`});this.drawings=new Ua(this.renderer,this.events,o.drawings,l),this.unresolvedUnsub=this.feed.onUnresolved?.(c=>{this.endLoad(),this.events.emit("data:unresolved",c);})??null,this.readyPromise=this.init(),un(a)?.dataEngine&&this.syncChartTypeEngine(a);}currentVisibleRange(){if(this.visibleRange)return this.visibleRange;let e=this.renderer.getVisibleRange();return e?{left:e.from,right:e.to}:void 0}engineFor(e){let t=e??this.defaultLanguage,n=this.engines.get(t);if(!n)throw new Error(`[vela] no scripting engine registered for language "${t}". Vela ships none \u2014 install one (Pine Script: @luxalgo/vela-pinets) and register it before addIndicator, e.g. chart.registerEngine('pine', new PineEngine()).`);return n}market(){return {symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",symbolInfo:this.feed.symbolInfo?.(this.config.market),chartStyle:this.priceStyle}}async fetchSeries(e,t,n){let i=ym(e),o={symbol:i.symbol,timeframe:t},s=await(this.feed.loadRange?this.feed.loadRange(o,n):this.feed.load({...o,bars:n.limit}));return i.transform?i.transform.full(s):s}onViewportChange(e){this.visibleRange={left:e.from,right:e.to},this.events.emit("viewport:changed",{from:e.from,to:e.to}),this.viewportTimer!=null&&clearTimeout(this.viewportTimer),this.viewportTimer=setTimeout(()=>{if(this.viewportTimer=null,this.switchingMarket)return;let t=this.visibleRange;if(t){for(let n of this.registry.all())!n.renderHandle||n.hidden||(n.session&&n.prepared?.reactsToViewport?(n.pendingCause="viewport",n.session.setVisibleRange(t)):n.native?.descriptor.reactsToViewport&&n.native.instance.onViewport({from:t.left,to:t.right}));this.activeEngineStyle&&this.typeEngines.get(this.activeEngineStyle)?.onViewport?.({from:t.left,to:t.right});}},MC);}async init(){let e=this.bumpGeneration();this.beginLoad(true),await this.loadMarket(e,{firstLoad:true}),this.generation===e&&(this.startLive(),this.events.emit("ready",void 0));}bumpGeneration(){let e=++this.generation;this.progressiveAbort?.abort(),this.progressiveAbort=null;for(let t of this.supersedeWaiters.splice(0))t();return e}beginLoad(e){if(this.loadingUp)return;this.loadingUp=true,this.renderer.setLoading?.(true);let t=this.config.market;this.events.emit("load:start",{symbol:t.symbol??"TEST",timeframe:t.timeframe??"60",firstLoad:e});}endLoad(){if(!this.loadingUp)return;this.loadingUp=false,this.renderer.setLoading?.(false);let e=this.config.market;this.events.emit("load:end",{symbol:e.symbol??"TEST",timeframe:e.timeframe??"60",bars:this.bars.length});}async loadMarket(e,t){try{await this.loadMarketInner(e,t);}finally{this.generation===e&&this.endLoad();}}async loadMarketInner(e,t){let n=this.config.market,i=n.bars??500,o=n.visibleRange,s=!n.data?.length&&o==null&&i>AC,a=false;if(!n.data?.length&&o==null&&this.feed.loadProgressive){let l=false,c=(u,h)=>{this.generation!==e||!h&&u.length===0||!l&&!h&&u.length<Math.min(i,RC)||(this.setBarSeries(u,l?{preserveView:true}:void 0),!l&&u.length>0&&(l=true,t.firstLoad&&this.activateBarLayers(),h||(this.historyState="backfill")));},d=new AbortController;this.progressiveAbort=d,a=await new Promise(u=>{let h=false,p=m=>{h||(h=true,u(m));};d.signal.addEventListener("abort",()=>p(true),{once:true}),this.feed.loadProgressive(n,m=>{c(m,false),l&&p(true);},{signal:d.signal}).then(m=>{if(this.progressiveAbort===d&&(this.progressiveAbort=null),m==null)return p(false);if(this.generation!==e)return p(true);c(m,true),this.completeHistory(m.length>=i?"depth":"genesis"),p(true);}).catch(()=>{this.progressiveAbort===d&&(this.progressiveAbort=null),this.generation===e&&this.completeHistory("aborted"),p(true);});});}if(!a)if(s&&this.feed.loadRange){let l=await this.feed.load({...n,bars:Math.min(i,wm)});if(this.generation!==e)return;this.setBarSeries(l),t.firstLoad&&this.activateBarLayers(),l.length>0&&i>l.length?(this.historyState="backfill",this.backfillHistory(e,i)):this.completeHistory("depth");}else if(s){let l=await this.feed.load({...n,bars:IC});if(this.generation!==e)return;this.setBarSeries(l),t.firstLoad&&this.activateBarLayers();let c=await this.feed.load(n);if(this.generation!==e)return;this.setBarSeries(c,{preserveView:true}),this.completeHistory("depth");}else {let l=await this.feed.load(n);if(this.generation!==e)return;this.setBarSeries(l),t.firstLoad&&this.activateBarLayers(),this.completeHistory("depth");}o!=null&&(typeof o=="string"?this.setVisibleRangePreset(o):this.renderer.setVisibleRange(o)),this.refreshPriceFormat(),this.ensurePriceFormat();}startLive(){this.config.live&&(this.live=new As(this.feed,this.config.market,e=>this.onBar(e)),this.live.start(),typeof document<"u"&&(this.onVisible=()=>{if(document.visibilityState!=="visible")return;let e=this.bars[this.bars.length-1];!e||this.healing||!this.canHeal()||Date.now()-this.lastHealAt<=xm||this.healGap(e.time);},document.addEventListener("visibilitychange",this.onVisible)));}stopLive(){this.live?.stop(),this.live=null,this.onVisible&&typeof document<"u"&&document.removeEventListener("visibilitychange",this.onVisible),this.onVisible=null,this.healing=false,this.healBuffer=[],this.lastHealAt=0;}resetHistoryTracking(){this.resolveHistoryComplete(),this.historyCompleted=false,this.historyState="complete",this.historyCompletePromise=new Promise(e=>{this.resolveHistoryComplete=e;});}marketSnapshot(){let e=this.config.market;return {symbol:e.symbol,provider:Wt(e.symbol??"").provider??void 0,timeframe:e.timeframe,bars:e.bars,session:e.session,offline:e.data!==void 0}}async setMarket(e){let t=this.config.market,n=e.symbol!==void 0&&e.symbol!==t.symbol||e.timeframe!==void 0&&e.timeframe!==t.timeframe||e.session!==void 0&&e.session!==t.session||e.data!==void 0,i=e.bars!==void 0&&e.bars!==t.bars,o=i&&!n&&this.rawBars.length>0&&!t.data?.length&&((e.bars??0)<=this.rawBars.length||typeof this.feed.loadRange=="function");if(!n&&!i){typeof e.visibleRange=="string"?this.setVisibleRangePreset(e.visibleRange):e.visibleRange&&this.renderer.setVisibleRange(e.visibleRange);return}let s={symbol:t.symbol??"TEST",timeframe:t.timeframe??"60"},l=n&&e.session!==void 0&&e.data===void 0&&(e.symbol===void 0||e.symbol===t.symbol)&&(e.timeframe===void 0||e.timeframe===t.timeframe)&&e.visibleRange===void 0?this.currentVisibleRange():void 0,c=l?this.rawBars.filter(u=>u.time>=l.left&&u.time<=l.right).length:0,d=this.bumpGeneration();this.switchingMarket=true;try{if(this.stopLive(),this.viewportTimer!=null&&(clearTimeout(this.viewportTimer),this.viewportTimer=null),this.visibleRange=null,this.resetHistoryTracking(),e.symbol!==void 0&&(t.symbol=e.symbol),e.timeframe!==void 0&&(t.timeframe=e.timeframe),e.bars!==void 0&&(t.bars=e.bars),e.session!==void 0&&(t.session=e.session),l){let u=Math.min(Math.ceil((Date.now()-l.left)/this.barIntervalMs())+50,5e3);u>(t.bars??500)&&(t.bars=u);}if(e.data!==void 0?t.data=e.data:e.symbol!==void 0&&delete t.data,t.visibleRange=e.visibleRange??(l?{from:l.left,to:l.right}:void 0),n&&(this.beginLoad(!1),this.setBarSeries([],{clearing:!0}),this.activeEngineStyle&&(this.typeEngines.get(this.activeEngineStyle)?.suspend(),this.renderer.setNativeData?.(this.activeEngineStyle,void 0),this.renderer.setNativeData?.(`${this.activeEngineStyle}-pending`,[]))),o?this.extendDepth(d,t.bars??500):await Promise.race([this.loadMarket(d,{firstLoad:!1}),new Promise(u=>this.supersedeWaiters.push(u))]),this.generation!==d)return}finally{this.generation===d&&(this.switchingMarket=false);}if(l&&c>=2&&this.rawBars.length>0){let u=this.rawBars,h=u.length-1;for(;h>0&&u[h].time>l.right;)h-=1;let p=u[Math.max(0,h-(c-1))].time;this.renderer.setVisibleRange({from:p,to:Math.max(l.right,u[h].time+1)});}o||(this.restartNativeIndicators(),this.restartChartTypeEngine(),this.reexecuteIndicators()),this.startLive(),n&&this.events.emit("market:changed",{symbol:t.symbol??"TEST",timeframe:t.timeframe??"60",prev:s});}restartNativeIndicators(){for(let e of this.registry.all())if(e.native)if(e.native.instance.stop(),e.native.instance=e.native.descriptor.create(),e.pendingStructural=true,e.hidden)e.native.stale=true;else {let t=this.handles.get(e.id);t&&this.startNativeIndicator(e.id,t);}}restartChartTypeEngine(){for(let e of this.typeEngines.values())e.stop();this.typeEngines.clear(),this.activeEngineStyle&&this.startChartTypeEngine(this.activeEngineStyle);}activateBarLayers(){this.maybeAutoAddVolume();}extendDepth(e,t){if(this.rawBars.length>t){this.setBarSeries(this.rawBars.slice(this.rawBars.length-t),{preserveView:true}),this.completeHistory("depth");return}if(this.rawBars.length===t){this.completeHistory("depth");return}this.historyState="backfill",this.backfillHistory(e,t);}async backfillHistory(e,t){try{for(;this.generation===e&&this.rawBars.length<t&&this.rawBars.length>0;){let n=t-this.rawBars.length,i=wm,o=await this.feed.loadRange(this.config.market,{to:this.rawBars[0].time,limit:Math.min(i,n)+1});if(this.generation!==e)return;let s=this.rawBars[0].time,a=o.filter(l=>l.time<s);if(a.length===0){this.completeHistory("genesis");return}for(let l=1;l<a.length;l+=1)if(a[l].time<=a[l-1].time){console.warn("[vela] non-monotonic history chunk \u2014 stopping the backfill"),this.completeHistory("aborted");return}this.setBarSeries([...a,...this.rawBars],{preserveView:!0}),this.notifySessionsBars("backfill"),this.events.emit("history:progress",{loaded:this.rawBars.length,target:t});}this.generation===e&&this.completeHistory("depth");}catch(n){console.warn(`[vela] history backfill failed \u2014 keeping ${this.rawBars.length} bars (${n instanceof Error?n.message:String(n)})`),this.generation===e&&this.completeHistory("aborted");}}completeHistory(e){this.historyCompleted||(this.historyCompleted=true,this.historyState="complete",this.notifySessionsBars("complete"),this.events.emit("history:complete",{reason:e,oldestTime:this.rawBars[0]?.time??0,barsLoaded:this.rawBars.length}),this.resolveHistoryComplete());}historyComplete(){return this.historyCompletePromise}qualifiedSymbol(){let e=this.config.market;return e.symbol?e.symbol:null}refreshPriceFormat(){if(!this.renderer.setPricePrecision)return;let e=this.feed.symbolInfo?.(this.config.market)?.mintick;this.renderer.setPricePrecision(typeof e=="number"&&e>0?e:void 0);}async ensurePriceFormat(){if(!this.renderer.setPricePrecision)return;let e=this.qualifiedSymbol();if(e)try{await this.dataControl.symbolInfo(e),this.refreshPriceFormat();}catch{}}maybeAutoAddVolume(){!this.config.volume||this.volumeOptedOut||!this.renderer.setNativeData||$i("volume")&&this.addNativeIndicator("volume");}syncPriceStyle(e){typeof e=="string"&&(this.priceStyle=e),this.syncBarTransform(e),this.syncChartTypeEngine(e);}syncChartTypeEngine(e){let t=typeof e=="string"?e:null,i=un(t)?.dataEngine?t:null;i!==this.activeEngineStyle&&(this.activeEngineStyle&&this.typeEngines.get(this.activeEngineStyle)?.suspend(),this.activeEngineStyle=i,i&&this.startChartTypeEngine(i));}async startChartTypeEngine(e){if(!this.renderer.setNativeData||(await this.readyPromise,this.activeEngineStyle!==e))return;let t=this.typeEngines.get(e);if(t){t.resume();return}let n=un(e);if(!n?.dataEngine)return;let i=n.dataEngine();this.typeEngines.set(e,i);let o=this.typeSettings.get(e);o&&i.onSettings?.(o),i.start({symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",live:this.config.live??false,session:this.config.market.session,bars:()=>this.bars,data:this.dataControl,pushData:s=>this.renderer.setNativeData?.(e,s),pushPending:s=>this.renderer.setNativeData?.(`${e}-pending`,s)});}syncBarTransform(e){let t=Xr(e);t!==this.barTransform&&(this.barTransform=t,this.rawBars.length!==0&&(this.bars=t?t.full(this.rawBars):this.rawBars,this.renderer.setBars(this.bars,{preserveView:true}),this.reexecuteIndicators()));}reexecuteIndicators(){for(let e of this.registry.all()){if(e.hidden||!e.session)continue;e.session.stop(),e.session=void 0,e.pendingStructural=true,e.pendingCause="market",this.setLoading(e,true);let t=this.handles.get(e.id);t&&this.executeIndicator(e.id,t);}}onBar(e){if(this.healing){this.healBuffer.push(e);return}let t=this.rawBars[this.rawBars.length-1];if(t&&this.canHeal()&&e.time>t.time+this.barIntervalMs()*DC&&Date.now()-this.lastHealAt>xm){this.healBuffer.push(e),this.healGap(t.time);return}this.applyBar(e);}setBarSeries(e,t){this.rawBars=e,this.bars=this.barTransform?this.barTransform.full(e):e,this.renderer.setBars(this.bars,{preserveView:t?.preserveView}),!t?.clearing&&this.bars.length>0&&this.endLoad();}applyBar(e,t=true){let n=this.rawBars[this.rawBars.length-1],i=e;if(n&&e.time===n.time)this.rawBars[this.rawBars.length-1]=e,this.barCause="tick",this.barTransform&&(i=this.barTransform.next(e,this.bars[this.bars.length-2]),this.bars[this.bars.length-1]=i);else if(!n||e.time>n.time)this.rawBars.push(e),this.barCause="bar",this.barTransform&&(i=this.barTransform.next(e,this.bars[this.bars.length-1]),this.bars.push(i));else return;this.renderer.updateBar(i),this.events.emit("bar",e),t&&this.notifySessionsBars(this.historyState==="backfill"?"backfill":void 0);}notifySessionsBars(e){if(this.switchingMarket)return;let t=e?"history":this.barCause;for(let n of this.registry.all())!n.renderHandle||n.hidden||(n.session?(n.pendingCause=t,n.session.notifyBars(e)):n.native&&n.native.instance.onBars());}canHeal(){return !!this.feed.loadRange&&!this.config.market.data?.length}barIntervalMs(){return Pt(this.config.market.timeframe??"60")}async healGap(e){let t=this.generation;this.healing=true,this.lastHealAt=Date.now();try{let n=await this.feed.loadRange(this.config.market,{from:e});if(this.generation!==t)return;for(let i of n)this.applyBar(i,!1);}catch{}finally{if(this.generation===t){this.healing=false;let n=this.healBuffer;this.healBuffer=[];for(let i of n)this.applyBar(i,false);this.notifySessionsBars(this.historyState==="backfill"?"backfill":void 0);}}}registerEngine(e,t){let n=this.engines.get(e);n&&n!==t&&console.warn(`[vela] re-registering scripting engine for language "${e}"; replacing ${n.constructor.name} with ${t.constructor.name}.`),this.engines.set(e,t);}addIndicator(e,t={}){let n=this.registry.nextId(),i=t.title??"Indicator",o=new _r(n,i,this,e);return this.handles.set(n,o),this.registry.add({id:n,title:i,source:e,options:t,inputValues:{...t.inputs??{}},propValues:{...t.props??{}}}),this.startIndicator(n,e,t,o),o}addNativeIndicator(e,t={}){let n=$i(e);if(!n?.multiInstance){let l=this.registry.all().find(c=>c.native?.type===e);if(l)return this.handles.get(l.id)??new _r(l.id,l.title,this,void 0,e)}let i=this.registry.nextId("native"),o=n?.title??e,s=new _r(i,o,this,void 0,e);if(this.handles.set(i,s),!n)return console.warn(`[vela] addNativeIndicator("${e}") \u2014 no native indicator registered for this type.`),s;let a={...n.defaultInputs(),...t.inputs??{}};return this.registry.add({id:i,title:o,source:e,inputValues:a,propValues:{},native:{type:e,instance:n.create(),descriptor:n}}),s.setSchema(n.inputsSchema()),this.startNativeIndicator(i,s),s}presentNativeIndicators(){return this.registry.all().map(e=>e.native?.type).filter(e=>!!e)}async availableNativeIndicators(){let e=this.qualifiedSymbol(),t=new Set(this.presentNativeIndicators());return Promise.all(Is().map(async n=>({type:n.type,title:n.title,supported:await this.isNativeSupported(n,e),present:t.has(n.type),beta:n.beta,...n.multiInstance?{multiInstance:true}:{}})))}async isNativeSupported(e,t){if(!e.isSupported)return true;if(!t)return false;try{return await e.isSupported(t,this.dataControl)}catch{return false}}applyInputs(e,t){let n=this.registry.get(e);!n||!n.session&&!n.native||(n.inputValues={...n.inputValues,...t},n.renderHandle&&this.renderer.setIndicatorInputs(n.renderHandle,n.inputValues),n.pendingStructural=true,!n.hidden&&!n.native&&this.setLoading(n,true),n.pendingCause="inputs",n.session?n.session.update(n.inputValues):n.native&&!n.hidden&&n.native.instance.setInputs(n.inputValues),this.events.emit("indicator:inputs",{id:e}));}inputValuesOf(e){return {...this.registry.get(e)?.inputValues}}propValuesOf(e){return {...this.registry.get(e)?.propValues}}applyProps(e,t){let n=this.registry.get(e);n?.session&&(n.propValues={...n.propValues,...t},n.renderHandle&&this.renderer.setIndicatorInputs(n.renderHandle,n.inputValues,n.propValues),n.pendingStructural=true,n.hidden||this.setLoading(n,true),n.pendingCause="inputs",n.session.update(n.inputValues,n.propValues),this.events.emit("indicator:inputs",{id:e}));}listIndicators(){return [...this.handles.values()]}getIndicatorContext(e,t){return this.registry.get(e)?.session?.getContext?.(t)??Promise.resolve(null)}removeIndicator(e){let t=this.registry.remove(e);t?.native?.type==="volume"&&(this.volumeOptedOut=true),t?.session?.stop(),t?.native?.instance.stop(),this.handles.delete(e),t?.renderHandle&&this.renderer.removeIndicator(t.renderHandle);let n=t?.model?.paneId;n&&n!=="price"&&!this.paneStillUsed(n)&&(this.renderer.removePane(n),this.forgetPane(n),this.events.emit("pane:changed",void 0)),this.events.emit("indicator:removed",{id:e});}setVisible(e,t){let n=this.registry.get(e);if(!(!n||n.hidden===!t)){if(n.hidden=!t,this.handles.get(e)?.setVisibleState(t),!t)n.session?.stop(),n.session=void 0,n.native?.instance.suspend(),n.renderHandle&&this.renderer.setIndicatorVisible?.(n.renderHandle,false);else if(n.renderHandle&&this.renderer.setIndicatorVisible?.(n.renderHandle,true),n.pendingStructural=true,n.native)if(n.native.stale){n.native.stale=false;let i=this.handles.get(e);i&&this.startNativeIndicator(e,i);}else n.native.instance.resume();else {this.setLoading(n,true);let i=this.handles.get(e);i&&this.executeIndicator(e,i);}this.events.emit("indicator:visibility",{id:e,visible:t});}}ready(){return this.readyPromise}inspect(){let e=[...this.registry.all()].filter(t=>!t.loading).sort((t,n)=>(n.native?1:0)-(t.native?1:0));return Lp(e.map(t=>t.model).filter(t=>t!=null))}resize(){this.renderer.resize();}setTheme(e){let t=this.config.theme;Object.keys(e).every(n=>e[n]===t[n])||(this.config.theme=e,this.renderer.setTheme(e),this.events.emit("theme:changed",e));}getVisibleRange(){return this.renderer.getVisibleRange()}setVisibleRange(e){this.renderer.setVisibleRange(e);}panBy(e){if(this.renderer.panBy){this.renderer.panBy(e);return}let t=this.renderer.getVisibleRange();if(!t)return;let n=(t.to-t.from)*e;this.renderer.setVisibleRange({from:t.from+n,to:t.to+n});}setVisibleRangePreset(e){let t=Mp(e,this.bars);t&&this.renderer.setVisibleRange(t);}destroy(){this.bumpGeneration(),this.resolveHistoryComplete(),this.stopLive(),this.viewportTimer!=null&&clearTimeout(this.viewportTimer),this.viewportUnsub?.(),this.paneActionUnsub?.();for(let e of this.registry.all())e.session?.stop(),e.native?.instance.stop();for(let e of this.typeEngines.values())e.stop();this.typeEngines.clear(),this.activeEngineStyle=null,this.unresolvedUnsub?.(),this.unresolvedUnsub=null,this.feed.destroy?.(),this.drawings.destroy(),this.renderer.destroy(),this.events.clear();}async startIndicator(e,t,n,i){try{if(await this.readyPromise,!this.registry.get(e))return;await OC();let o=this.registry.get(e);if(!o)return;let s=this.engineFor(n.language);o.engine=s;let a=await s.prepare(t,e);o.prepared=a;let l={};for(let d of a.inputs)l[d.key]=d.defval;o.inputValues={...l,...o.inputValues},i.setSchema(a.inputs);let c={};for(let d of a.props??[])c[d.key]=d.defval;o.propValues={...c,...o.propValues},i.setPropsSchema(a.props??[]),this.mountLoadingPlaceholder(e,o),this.executeIndicator(e,i);}catch(o){this.fail(e,i,o);}}executeIndicator(e,t){let n=this.registry.get(e);if(!n||!n.engine||!n.prepared||n.hidden)return;let i=this.config.live&&!n.prepared.reactsToViewport&&n.engine.capabilities.streaming?"live":"static";n.session=n.engine.execute({prepared:n.prepared,market:this.market(),bars:this.bars,getBars:()=>this.bars,fetchSeries:(o,s,a)=>this.fetchSeries(o,s,a),inputs:n.inputValues,props:n.propValues,visibleRange:this.currentVisibleRange(),mode:i,historyState:this.historyState},{onModel:o=>{let s=!n.announced,a=n.pendingCause??"history";this.applyModel(e,o)&&(n.pendingCause=void 0,this.emitContextChanged(e),this.emitScriptRun(e,a,s));},onAlert:o=>{let s=n.options?.title??n.prepared?.meta.title??n.title;this.events.emit("alert",{...o,indicator:s}),t.emit("alert",{id:o.id,message:o.message,title:o.title,time:o.time});},onWarning:o=>this.events.emit("warning",o),onError:o=>this.fail(e,t,o)}),this.emitContextChanged(e);}async startNativeIndicator(e,t){try{await this.readyPromise;let n=this.registry.get(e);if(!n?.native||n.hidden)return;let i={symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",live:this.config.live,session:this.config.market.session,bars:()=>this.bars,data:this.dataControl,emit:o=>this.applyModel(e,this.buildNativeModel(n,o)),pushData:o=>this.renderer.setNativeData?.(n.native.type,o),setStatus:o=>{n.renderHandle&&!n.hidden&&this.renderer.setIndicatorStatus?.(n.renderHandle,o);}};n.native.instance.start(i,n.inputValues);}catch(n){this.fail(e,t,n);}}buildNativeModel(e,t){let n=e.native.descriptor;return {id:e.id,title:e.title,...n.shortTitle?{shorttitle:n.shortTitle}:{},overlay:n.overlay,paneHint:n.paneHint,native:{type:e.native.type},...t.paneAxis!=null?{paneAxis:t.paneAxis}:{},series:t.series??[],fills:t.fills??[],backgrounds:t.backgrounds??[],priceLines:t.priceLines??[],...t.lines?{lines:t.lines}:{},...t.boxes?{boxes:t.boxes}:{},...t.labels?{labels:t.labels}:{},...t.polylines?{polylines:t.polylines}:{},...t.linefills?{linefills:t.linefills}:{},...t.tables?{tables:t.tables}:{},inputs:n.inputsSchema(),inputValues:e.inputValues}}mountLoadingPlaceholder(e,t){if(t.renderHandle||t.hidden||!t.prepared)return;let n=t.prepared.meta,i={id:e,title:t.options?.title??n.title,overlay:n.overlay,paneHint:n.overlay?"price":"new",series:[],fills:[],backgrounds:[],priceLines:[],inputs:t.prepared.inputs,inputValues:t.inputValues,...t.prepared.props?{props:t.prepared.props,propValues:t.propValues}:{}},o=this.routePane(e,i,t.options??{});this.placeModel(i,e,o),t.model=i,this.ensurePaneFor(o),t.renderHandle=this.renderer.mountIndicator(i),t.pendingStructural=true,this.setLoading(t,true);}setLoading(e,t){e.loading=t,e.renderHandle&&!e.hidden&&this.renderer.setIndicatorStatus?.(e.renderHandle,t?"loading":"idle");}ensurePaneFor(e){this.paneOrder.includes(e)||this.paneOrder.push(e),this.renderer.ensurePane({id:e,kind:e==="price"?"price":"study",order:this.paneOrder.indexOf(e)});}paneStillUsed(e){for(let t of this.registry.all())if(t.model?.paneId===e)return true;return false}forgetPane(e){let t=this.paneOrder.indexOf(e);t>0&&this.paneOrder.splice(t,1),this.collapsedPanes.delete(e),this.maximizedPaneId===e&&(this.maximizedPaneId=null);}paneManagementSupported(){return this.renderer.capabilities.paneManagement===true&&typeof this.renderer.setIndicatorPane=="function"}listPanes(){let e=new Map;for(let n of this.registry.all()){let i=n.model;if(!i)continue;let o=i.paneId??"price";e.has(o)||e.set(o,[]),e.get(o).push({id:n.id,title:i.title||n.title,...i.shorttitle?{shorttitle:i.shorttitle}:{},ownScale:i.ownScale===true});}let t=[];for(let n of this.paneOrder)n!=="price"&&!e.has(n)||t.push({id:n,kind:n==="price"?"price":"study",order:t.length,collapsed:this.collapsedPanes.has(n),maximized:this.maximizedPaneId===n,indicators:e.get(n)??[]});return t}movePane(e,t){if(e==="price")return;let n=this.existingPaneIds(),i=n.indexOf(e);if(i<0)return;let o=t==="up"?i-1:i+1;o<=0||o>=n.length||([n[i],n[o]]=[n[o],n[i]],this.reorderPanes(n),this.events.emit("pane:moved",{paneId:e,dir:t}));}removePaneAndIndicators(e){if(e!=="price")for(let t of [...this.registry.all()])t.model?.paneId===e&&this.removeIndicator(t.id);}collapsePane(e,t){t?this.collapsedPanes.add(e):this.collapsedPanes.delete(e),this.renderer.setPaneCollapsed?.(e,t),this.events.emit("pane:changed",void 0);}maximizePane(e){this.maximizedPaneId=e,this.renderer.setPaneMaximized?.(e),this.events.emit("pane:changed",void 0);}moveIndicator(e,t){if(!this.paneManagementSupported()||!this.renderer.setIndicatorPane){console.warn("[vela] the active renderer does not support moving indicators between panes.");return}let n=this.registry.get(e);if(!n?.renderHandle||!n.model)return;let i=n.model,o=i.paneId??"price",s=this.resolveMoveTarget(e,i,t);if(!s)return;let{paneId:a,ownScale:l,insert:c}=s;a===o&&i.ownScale===true===l||(c?this.insertPaneOrder(a,c):this.paneOrder.includes(a)||this.paneOrder.push(a),i.ownScale=l,n.paneLocked=true,this.placeModel(i,e,a),this.ensurePaneFor(a),this.renderer.setIndicatorPane(n.renderHandle,a,{ownScale:l}),o!=="price"&&o!==a&&!this.paneStillUsed(o)&&(this.renderer.removePane(o),this.forgetPane(o)),this.reorderPanes(this.existingPaneIds()),this.events.emit("indicator:moved",{id:e,paneId:a}),this.events.emit("pane:changed",void 0));}resolveMoveTarget(e,t,n){if(n==="price"||typeof n=="object"&&"pane"in n&&n.pane==="price")return {paneId:"price",ownScale:!t.overlay};if("pane"in n)return this.existingPaneIds().includes(n.pane)?{paneId:n.pane,ownScale:true}:null;let i=n.newPane===true?{}:n.newPane;return {paneId:this.freshPaneId(e,t.paneId??"price"),ownScale:false,insert:i}}freshPaneId(e,t){let n=new Set(this.existingPaneIds()),i=`pane-${e}`;for(let o=2;i===t||n.has(i);o+=1)i=`pane-${e}-${o}`;return i}insertPaneOrder(e,t){let n=this.paneOrder.indexOf(e);n>0&&this.paneOrder.splice(n,1);let i=this.paneOrder.length;t.before&&this.paneOrder.includes(t.before)?i=this.paneOrder.indexOf(t.before):t.after&&this.paneOrder.includes(t.after)&&(i=this.paneOrder.indexOf(t.after)+1),i<1&&(i=1),this.paneOrder.splice(i,0,e);}existingPaneIds(){return this.paneOrder.filter(e=>e==="price"||this.paneStillUsed(e))}reorderPanes(e){this.paneOrder.length=0,this.paneOrder.push(...e),this.renderer.orderPanes?.(e),this.events.emit("pane:changed",void 0);}handlePaneAction(e){switch(e.type){case "remove":this.removePaneAndIndicators(e.paneId);break;case "move":{let t=this.existingPaneIds(),n=t.indexOf(e.paneId),i=e.dir==="up"?n-1:n+1;n>0&&i>0&&i<t.length&&([t[n],t[i]]=[t[i],t[n]],this.paneOrder.length=0,this.paneOrder.push(...t),this.events.emit("pane:changed",void 0),this.events.emit("pane:moved",{paneId:e.paneId,dir:e.dir}));break}case "collapse":e.collapsed?this.collapsedPanes.add(e.paneId):this.collapsedPanes.delete(e.paneId),this.events.emit("pane:changed",void 0);break;case "maximize":this.maximizedPaneId=e.maximized?e.paneId:null,this.events.emit("pane:changed",void 0);break}}announce(e,t){e.announced||(e.announced=true,this.events.emit("indicator:added",{id:e.id}),this.emitContextChanged(e.id),t?.emit("ready",void 0));}applyModel(e,t){let n=this.registry.get(e);if(!n||n.hidden)return true;if(n.loading&&this.bars.length===0&&!r.modelHasOutput(t))return false;let i=this.handles.get(e);if(!n.renderHandle){let a=this.routePane(e,t,n.options??{});return this.placeModel(t,e,a),n.model=t,this.ensurePaneFor(a),n.renderHandle=this.renderer.mountIndicator(t),n.pendingStructural=false,this.announce(n,i),true}let o=n.model?.paneId??"price",s=n.model?.ownScale===true;if(n.loading&&!n.paneLocked){let a=this.routePane(e,t,n.options??{});a!==o&&(o!=="price"&&(this.renderer.removePane(o),this.forgetPane(o)),this.ensurePaneFor(a),n.pendingStructural=true,o=a);}return this.placeModel(t,e,o),n.paneLocked&&(t.ownScale=s),n.model=t,n.pendingStructural?(n.renderHandle=this.renderer.mountIndicator(t),this.renderer.setIndicatorInputs(n.renderHandle,n.inputValues,n.propValues),n.pendingStructural=false):this.renderer.updateIndicator(n.renderHandle,NC(t)),n.loading&&this.setLoading(n,false),this.announce(n,i),true}static modelHasOutput(e){return e.series.length>0||e.fills.length>0||e.backgrounds.length>0||e.priceLines.length>0||(e.lines?.length??0)>0||(e.boxes?.length??0)>0||(e.labels?.length??0)>0||(e.polylines?.length??0)>0||(e.linefills?.length??0)>0||(e.tables?.length??0)>0||(e.barColors?.length??0)>0||(e.trades?.length??0)>0}routePane(e,t,n){return n.pane==="new"?`pane-${e}`:n.pane==="price"||(n.overlay??t.overlay)?"price":`pane-${e}`}static plotsAtLastBar(e){let t={};for(let n of e.series)Ne(n)&&(t[n.title]=n.points[n.points.length-1]?.value??null);return t}placeModel(e,t,n){e.id=t,e.paneId=n;let i=o=>o.overlay===true?"price":n;for(let o of e.series)o.paneId=i(o);for(let o of e.fills)o.paneId=i(o);for(let o of e.backgrounds)o.paneId=i(o);for(let o of e.priceLines)o.paneId=n;if(e.lines)for(let o of e.lines)o.paneId=i(o);if(e.boxes)for(let o of e.boxes)o.paneId=i(o);if(e.labels)for(let o of e.labels)o.paneId=i(o);if(e.polylines)for(let o of e.polylines)o.paneId=i(o);if(e.linefills)for(let o of e.linefills)o.paneId=i(o);if(e.tables)for(let o of e.tables)o.paneId=i(o);}emitContextChanged(e){if(!this.registry.get(e)?.session?.getContext)return;let t=Date.now();t-(this.contextEmitAt.get(e)??0)<1e3||(this.contextEmitAt.set(e,t),this.events.emit("context:changed",{id:e}));}emitScriptRun(e,t,n){let i=this.registry.get(e);if(!i||i.native||!this.events.hasListeners("script:run"))return;let o=Date.now();t==="tick"&&o-(this.runEmitAt.get(e)??0)<kC||(this.runEmitAt.set(e,o),Promise.resolve().then(()=>this.buildScriptRun(i,t,n)).then(s=>{s&&this.registry.get(e)&&this.events.emit("script:run",s);}));}async buildScriptRun(e,t,n){let i=e.model;if(!i)return null;let o=await this.pullContext(e,["variables","strategy","warnings"]),s=this.bars[this.bars.length-1];return {id:e.id,title:i.title,kind:o?.strategy||(i.trades?.length??0)>0?"strategy":"indicator",cause:t,first:n,bar:Math.max(0,this.bars.length-1),time:s?.time??0,forming:this.config.live&&this.bars.length>0,complete:this.historyState!=="backfill",plots:r.plotsAtLastBar(i),vars:o?.variables??{},...o?.strategy?{strategy:o.strategy}:{},warnings:o?.warnings??[],trades:async()=>(await this.pullContext(e,["trades"]))?.trades??[],series:async a=>((await this.pullContext(e,["plots"]))?.plots?.[a]??[]).map(c=>({time:c.time,value:typeof c.value=="number"?c.value:null}))}}async pullContext(e,t){try{return await e.session?.getContext?.(t)??null}catch{return null}}fail(e,t,n){let i=this.registry.get(e);i?.loading&&this.setLoading(i,false);let o=n instanceof Error?n:new Error(String(n));console.error(`[vela] indicator "${e}" failed:`,o.message),this.events.emit("indicator:error",{id:e,error:o}),t?.emit("error",{error:o});}};function OC(){return typeof requestAnimationFrame=="function"?new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(()=>r()))):new Promise(r=>setTimeout(r,0))}function NC(r){let e=[],t=Number.POSITIVE_INFINITY,n=0;for(let i of r.series)if(i.kind==="candle"||i.kind==="bar"){e.push({seriesId:i.id,kind:"bars",bars:i.bars});for(let o of i.bars)o.time<t&&(t=o.time),o.time>n&&(n=o.time);}else if(Ne(i)){e.push({seriesId:i.id,kind:"points",points:i.points});for(let o of i.points)o.time<t&&(t=o.time),o.time>n&&(n=o.time);}return {kind:"value",indicatorId:r.id,dirty:{from:Number.isFinite(t)?t:0,to:n},anchorTime:r.anchorTime??null,series:e,lines:r.lines??[],boxes:r.boxes??[],labels:r.labels??[],polylines:r.polylines??[],linefills:r.linefills??[],tables:r.tables??[],trades:r.trades??[]}}var so=class{constructor(e){this.renderer=e;}get name(){return this.renderer.name}get capabilities(){return this.renderer.capabilities}supports(e){return this.renderer.features.includes(e)}get(e){return this.renderer.readFeature(e)}set(e,t){let n=typeof e=="string"?[[e,t]]:Object.entries(e);for(let[i,o]of n)this.renderer.features.includes(i)?this.renderer.applyFeature(i,o):console.warn(`[vela] renderer "${this.renderer.name}" has no feature "${i}" \u2014 set ignored.`);return this}setLegendActions(e){this.renderer.setLegendActions?.(e);}setLegendCallouts(e){this.renderer.setLegendCallouts?.(e);}setLegendOverviewAction(e){return this.renderer.setLegendOverviewAction?.(e),this}get supportsIndicatorSettings(){return typeof this.renderer.openIndicatorSettings=="function"}openIndicatorSettings(e){return this.renderer.openIndicatorSettings?.(e),this}screenshot(){return typeof this.renderer.screenshot=="function"?this.renderer.screenshot():(console.warn(`[vela] renderer "${this.renderer.name}" does not support screenshot().`),null)}screenshotCanvas(){return typeof this.renderer.screenshotCanvas=="function"?this.renderer.screenshotCanvas():null}getConfig(){return typeof this.renderer.getConfig=="function"?this.renderer.getConfig():(console.warn(`[vela] renderer "${this.renderer.name}" does not support getConfig().`),null)}applyConfig(e){return typeof this.renderer.applyConfig=="function"?this.renderer.applyConfig(e):console.warn(`[vela] renderer "${this.renderer.name}" does not support applyConfig().`),this}onConfigChanged(e){return this.renderer.onConfigChanged?.(e)??(()=>{})}onCrosshairMove(e){return this.renderer.onCrosshairMove(e)}onAxisLongPress(e){return this.renderer.onAxisLongPress?.(e)??(()=>{})}dataWindowReadout(){return this.renderer.getDataWindowReadout?.()??null}setSymbolPicker(e){return typeof this.renderer.setSymbolPicker=="function"?this.renderer.setSymbolPicker(e):console.warn(`[vela] renderer "${this.renderer.name}" does not support setSymbolPicker().`),this}focus(){return this.renderer.focus?.(),this}get supportsExternalCrosshair(){return typeof this.renderer.setExternalCrosshair=="function"}setExternalCrosshair(e,t=null){return this.renderer.setExternalCrosshair?.(e,t),this}closeDialogs(){return this.renderer.closeDialogs?.(),this}openSettings(e){return this.renderer.openSettingsDialog?.(e),this}setSettingsSections(e){return this.renderer.setSettingsSections?.(e),this}setSettingsVisibility(e){return this.renderer.setSettingsVisibility?.(e),this}listSettingsIds(){return this.renderer.listSettingsIds?.()??[]}setLayoutMode(e){return this.renderer.setLayoutMode?.(e),this}};var qr=new Map;function FC(r){let e=Object.entries(r);for(let[t,n]of e)qr.set(t,n);return ()=>{for(let[t,n]of e)qr.get(t)===n&&qr.delete(t);}}function VC(...r){if(r.length===0)qr.clear();else for(let e of r)qr.delete(e);}function Ed(){return Object.fromEntries(qr)}var ja=class{constructor(e){this.controller=e;}get supported(){return this.controller.paneManagementSupported()}list(){return this.controller.listPanes()}move(e,t){return this.guard()&&this.controller.movePane(e,t),this}remove(e){return this.guard()&&this.controller.removePaneAndIndicators(e),this}collapse(e,t=true){return this.guard()&&this.controller.collapsePane(e,t),this}maximize(e){return this.guard()&&this.controller.maximizePane(e),this}moveIndicator(e,t){return this.guard()&&this.controller.moveIndicator(e,t),this}guard(){return this.controller.paneManagementSupported()?true:(console.warn("[vela] the active renderer does not support pane management \u2014 chart.panes mutation ignored."),false)}};function Sm(r,e,t,n){return `${r}|${e}|${t}${n&&n!=="regular"?`|${n}`:""}`}function _C(r){return r.split("|")[1]??""}var qa=class{constructor(){this.series=new Map;this.coveredFrom=new Map;this.retained=new Set;this.retainedByOwner=new Map;}get(e){return this.series.get(e)}markCovered(e,t){this.coveredFrom.set(e,Math.min(this.coveredFrom.get(e)??1/0,t));}coveredFromOf(e){return this.coveredFrom.get(e)}merge(e,t){if(t.length===0)return this.series.get(e)??[];let n=new Map;for(let o of this.series.get(e)??[])n.set(o.time,o);for(let o of t)n.set(o.time,o);let i=[...n.values()].sort((o,s)=>o.time-s.time);return this.series.set(e,i),i}retainSymbol(e){this.currentSymbol!==e&&(this.currentSymbol=e,this.purgeOutside(e));}retain(e,t="default"){e.size===0?this.retainedByOwner.delete(t):this.retainedByOwner.set(t,new Set(e));let n=new Set;for(let i of this.retainedByOwner.values())for(let o of i)n.add(o);this.retained=n,this.purgeOutside(this.currentSymbol);}purgeOutside(e){for(let t of [...this.series.keys()]){let n=_C(t);n!==e&&!this.retained.has(n)&&(this.series.delete(t),this.coveredFrom.delete(t));}}clear(){this.series.clear(),this.coveredFrom.clear();}},ao=new qa;function Pd(r,e,t){let{provider:n,ticker:i}=Wt(r);return Sm(n??"",i,e,t)}var co=1e4,BC=co+1,uo=class{constructor(e,t=ao){this.inner=e;this.store=t;}async load(e){if(e.data&&e.data.length>0)return this.inner.load(e);let t=e.symbol??"TEST",n=Pd(t,e.timeframe??"60",e.session);this.store.retainSymbol(t);let i=this.store.get(n),o=e.bars??500,s=i?.[i.length-1];if(i&&s&&i.length>=o-1&&this.inner.loadRange){let{bars:l}=await this.fetchRange(e,{from:s.time}),c=this.store.merge(n,lo(l));return Cm(c,l[l.length-1]).slice(-o)}let a=await this.inner.load(e);return this.store.merge(n,lo(a)),a}async loadProgressive(e,t,n){if(e.data&&e.data.length>0)return this.inner.load(e);if(!this.inner.loadProgressive)return null;let i=e.symbol??"TEST",o=Pd(i,e.timeframe??"60",e.session),s=this.store.get(o),a=e.bars??500,l=s?.[s.length-1];if(s&&l&&s.length>=a-1&&this.inner.loadRange)return this.load(e);this.store.retainSymbol(i);let c=await this.inner.loadProgressive(e,t,n);return c==null?null:(this.store.merge(o,lo(c)),c)}async loadRange(e,t){if(!this.inner.loadRange)return this.inner.load(e);let n=Pd(e.symbol??"TEST",e.timeframe??"60",e.session),i=this.store.get(n),o=i?.[i.length-1];if(t.to!=null&&o&&t.to<o.time){let d=i.filter(f=>f.time<=t.to),u=this.store.coveredFromOf(n)??1/0;if(t.limit!=null?d.length>=t.limit&&(t.from==null||u<=t.from):t.from!=null&&u<=t.from){let f=t.from!=null?d.filter(g=>g.time>=t.from):d;return t.limit!=null&&f.length>t.limit&&(f=f.slice(-t.limit)),f}let p=await this.fetchRange(e,t),m=p.bars.filter(f=>f.time<=t.to);return m.length>0&&(this.store.merge(n,m),this.store.markCovered(n,p.coveredDownTo??m[0].time)),m}if(o&&t.from!=null){let d=this.store.coveredFromOf(n);if(d!=null&&d>t.from){let{bars:u,coveredDownTo:h}=await this.fetchRange(e,{from:t.from,to:d});this.store.merge(n,u.filter(p=>p.time<=d)),this.store.markCovered(n,h??t.from),i=this.store.get(n),o=i?.[i.length-1];}}let s=this.store.coveredFromOf(n);if(!!i&&i.length>0&&!!o&&(t.from!=null?s!=null&&s<=t.from:t.limit==null||i.length>=t.limit)&&o){let{bars:d}=await this.fetchRange(e,{from:o.time,to:t.to,limit:t.limit}),u=this.store.merge(n,lo(d)),h=Cm(u,d[d.length-1]),p=t.from!=null?h.filter(m=>m.time>=t.from):h;return t.to!=null&&(p=p.filter(m=>m.time<=t.to)),p}let{bars:l,coveredDownTo:c}=await this.fetchRange(e,t);return this.store.merge(n,lo(l)),this.store.markCovered(n,c??t.from??l[0]?.time??0),l}async fetchRange(e,t){let n=Pt(e.timeframe??"60"),i=HC(t,n);if(i<=BC){let c=await this.inner.loadRange(e,{...t,limit:t.limit??i});return {bars:c,coveredDownTo:t.from??c[0]?.time}}let o=new Map,s=t.to??Date.now();for(;!(t.from!=null&&s<t.from);){let c=t.limit!=null?t.limit-o.size:co;if(c<=0)break;let d=await this.inner.loadRange(e,{to:s,limit:Math.min(co,c)}),u=1/0;for(let h of d)h.time<u&&(u=h.time),h.time<=s&&(t.from==null||h.time>=t.from)&&o.set(h.time,h);if(d.length===0){if(t.from==null)break;s-=co*n;continue}if(u-1>=s)break;s=u-1;}let a=[...o.values()].sort((c,d)=>c.time-d.time),l=t.from!=null&&s<t.from;return {bars:a,coveredDownTo:l?t.from:a[0]?.time}}subscribe(e,t){return this.inner.subscribe(e,t)}symbolInfo(e){return this.inner.symbolInfo?.(e)}};function HC(r,e){if(r.limit!=null)return r.limit;if(r.from==null)return co;let t=Math.max(0,(r.to??Date.now())-r.from);return Math.ceil(t/e*1.1)+2}function lo(r){return r.length>0?r.slice(0,-1):r}function Cm(r,e){if(!e)return r;let t=r[r.length-1];return !t||e.time>t.time?[...r,e]:r}function zC(r){return {"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,"1M":2592e6,1:6e4,5:3e5,15:9e5,30:18e5,60:36e5,240:144e5,D:864e5,W:6048e5,M:2592e6}[r]??36e5}var mr=class{constructor(e=ao){this.registry=new Ka;this.primaryProvider=null;this.liveBars=[];this.symInfoCache=new Map;this.cache=new uo(new Md(this.registry),e);}registerProvider(e,t){return this.registry.register(e,t)}unregisterProvider(e){this.registry.unregister(e);}providers(){return this.registry.names().map(e=>this.registry.infoOf(e))}resolveSymbol(e){return this.registry.resolve(e,{default:this.primaryProvider})}displayPrefix(e){let t=this.resolveSymbol(e);return t?this.registry.displayPrefixOf(t):null}canonicalSymbol(e){let t=this.resolveSymbol(e);return t?this.registry.canonicalSymbol(t):null}providerInstance(e){return this.registry.get(e)}symbolIconOf(e){return this.registry.symbolIconOf(e)}symbolIcon(e){return this.registry.symbolIcon(this.resolveSymbol(e))}symbols(e){return this.registry.symbolsOf(e)}onUnresolved(e){return this.registry.onUnresolved(e)}destroy(){this.registry.cancelWaits();}ready(){return this.registry.indexReady()}async symbolInfoFor(e){let t=this.registry.resolve(e,{default:this.primaryProvider});if(!t)return;let n=await this.registry.get(t.provider)?.getSymbolInfo?.(t.ticker);return n&&this.symInfoCache.set(Ld(t),n),n}capabilitiesFor(e){let t=this.registry.resolve(e,{default:this.primaryProvider});if(!t)return null;let n=this.registry.get(t.provider);return n?n.capabilitiesFor?.(t.ticker)??this.registry.infoOf(t.provider).capabilities:null}async load(e){if(e.data&&e.data.length>0)return this.liveBars=e.data.map(n=>({...n})),e.data;let t=await this.registry.whenResolvable(ho(e),{default:this.primaryProvider});return this.primaryProvider=t.provider,this.prefetchSymbolInfo(t),this.cache.load(Za(e,t))}async loadProgressive(e,t,n){if(e.data&&e.data.length>0)return this.liveBars=e.data.map(o=>({...o})),e.data;let i=await this.registry.whenResolvable(ho(e),{default:this.primaryProvider});return this.primaryProvider=i.provider,this.prefetchSymbolInfo(i),this.cache.loadProgressive(Za(e,i),t,n)}symbolInfo(e){if(e.data&&e.data.length>0)return;let t=this.registry.resolve(ho(e),{default:this.primaryProvider});return t?this.symInfoCache.get(Ld(t)):void 0}prefetchSymbolInfo(e){let t=Ld(e);if(this.symInfoCache.has(t))return;let n=this.registry.get(e.provider);n?.getSymbolInfo&&n.getSymbolInfo(e.ticker).then(i=>{i&&this.symInfoCache.set(t,i);}).catch(()=>{});}async loadRange(e,t){if(e.data&&e.data.length>0)return this.cache.loadRange(e,t);let n=this.registry.resolve(ho(e),{default:this.primaryProvider});return n?this.cache.loadRange(Za(e,n),t):[]}subscribe(e,t){if(e.data&&e.data.length>0)return this.synthesizeTicks(e,t);let n=this.registry.resolve(ho(e),{default:this.primaryProvider});return n?this.cache.subscribe(Za(e,n),t):()=>{}}synthesizeTicks(e,t){if(this.liveBars.length===0)return ()=>{};let n=zC(e.timeframe??"60"),i=setInterval(()=>{let o=this.liveBars,s=o[o.length-1];if(!s)return;let a=s.close*.0015*(Math.random()-.5)*2,l=Math.max(0,s.close+a),c={...s,close:l,high:Math.max(s.high,l),low:Math.min(s.low,l)};if(o[o.length-1]=c,t(c),Math.random()<.12){let d={time:c.time+n,open:c.close,high:c.close,low:c.close,close:c.close,volume:0};o.push(d),t(d);}},1e3);return ()=>clearInterval(i)}};function ho(r){return r.symbol??""}function Za(r,e){return {...r,symbol:`${e.provider}:${e.ticker}`}}function Ld(r){return `${r.provider}|${r.ticker}`}async function Tm(r,e,t,n){try{return await r.getBars(e,t,n)}catch(i){return console.warn(`[vela] data fetch failed for ${e} ${t} \u2014 ${i instanceof Error?i.message:String(i)}`),[]}}var Md=class{constructor(e){this.registry=e;}load(e){let{provider:t,ticker:n}=Wt(e.symbol??""),i=this.registry.get(t??"");return i?Tm(i,n,e.timeframe??"60",{limit:e.bars??500,session:e.session}):Promise.resolve([])}async loadProgressive(e,t,n){let{provider:i,ticker:o}=Wt(e.symbol??""),s=this.registry.get(i??"");if(!s)return [];if(!s.getBarsProgressive)return null;try{return await s.getBarsProgressive(o,e.timeframe??"60",{limit:e.bars??500,session:e.session},t,n)}catch(a){return console.warn(`[vela] progressive fetch failed for ${o} ${e.timeframe??"60"} \u2014 ${a instanceof Error?a.message:String(a)}`),[]}}loadRange(e,t){let{provider:n,ticker:i}=Wt(e.symbol??""),o=this.registry.get(n??"");return o?Tm(o,i,e.timeframe??"60",{...t,session:e.session}):Promise.resolve([])}subscribe(e,t){let{provider:n,ticker:i}=Wt(e.symbol??""),o=this.registry.get(n??"");if(!o)return ()=>{};let s=e.timeframe??"60";if(o.subscribe)return o.subscribe(i,s,t,e.session?{session:e.session}:void 0);let a=false,l=null,c=async()=>{if(!a){try{let d=await o.getBars(i,s,{limit:2,session:e.session});if(a)return;for(let u of d)t(u);}catch{}a||(l=setTimeout(()=>{c();},3e3));}};return l=setTimeout(()=>{c();},3e3),()=>{a=true,l&&clearTimeout(l);}}};var po=class{constructor(e){this.registry=e instanceof mr?e:null;}registerProvider(e,t){return this.registry?(this.registry.registerProvider(e,t),this):(console.warn(`[vela] chart.data.registerProvider("${e}") ignored \u2014 the active data feed is a custom feed (deps.dataFeed), not the default provider registry.`),this)}unregisterProvider(e){return this.registry?.unregisterProvider(e),this}providers(){return this.registry?.providers()??[]}resolve(e){return this.registry?.resolveSymbol(e)??null}displayPrefix(e){return this.registry?.displayPrefix(e)??null}canonicalSymbol(e){return this.registry?.canonicalSymbol(e)??null}providerInstance(e){return this.registry?.providerInstance(e)}symbols(e){return this.registry?.symbols(e)??[]}symbolIcon(e){return this.registry?.symbolIcon(e)}symbolInfo(e){return this.registry?.symbolInfoFor(e)??Promise.resolve(void 0)}capabilities(e){return this.registry?.capabilitiesFor(e)??null}ready(){return this.registry?.ready()??Promise.resolve()}};var mo=class{constructor(e){this.ctrl=e;}get supported(){return this.ctrl.supported}setTool(e){return this.ok("setTool")&&this.ctrl.setTool(e),this}getTool(){return this.ctrl.getTool()}setSnapMode(e){return this.ok("setSnapMode")&&this.ctrl.setSnapMode(e),this}getSnapMode(){return this.ctrl.getSnapMode()}setStayMode(e){return this.ok("setStayMode")&&this.ctrl.setStayMode(e),this}getStayMode(){return this.ctrl.getStayMode()}setMode(e){return this.ok("setMode")&&this.ctrl.setMode(e),this}getMode(){return this.ctrl.getMode()}showToolbar(e=true){return this.ok("showToolbar")&&this.ctrl.showToolbar(e),this}setToolbar(e){return this.ok("setToolbar")&&this.ctrl.setToolbar(e),this}setToolShortcuts(e){return this.ok("setToolShortcuts")&&this.ctrl.setToolShortcuts(e),this}setExternalGhost(e){return this.ctrl.setExternalGhost(e),this}add(e,t={}){return this.ok("add")?this.ctrl.add(e,t):null}remove(e){return this.ctrl.remove(e),this}update(e,t){return this.ctrl.update(e,t),this}updateMany(e){return this.ctrl.updateMany(e),this}removeMany(e){return this.ctrl.removeMany(e),this}lock(e,t=true){return this.ctrl.setLocked(e,t),this}show(e,t=true){return this.ctrl.setVisible(e,t),this}select(e){return this.ok("select")&&this.ctrl.select(e==null?[]:typeof e=="string"?[e]:e),this}openSettings(e){return this.ok("openSettings")&&this.ctrl.openSettings(e),this}bringToFront(e){return this.ctrl.bringToFront(e),this}sendToBack(e){return this.ctrl.sendToBack(e),this}undo(){return this.ctrl.undo(),this}redo(){return this.ctrl.redo(),this}canUndo(){return this.ctrl.canUndo()}canRedo(){return this.ctrl.canRedo()}clone(e){return this.ok("clone")&&this.ctrl.clone(e),this}duplicate(e){return this.ok("duplicate")&&this.ctrl.duplicate(e),this}copyToClipboard(e){return this.ok("copy")&&this.ctrl.copy(e),this}paste(){return this.ok("paste")&&this.ctrl.paste(),this}all(){return this.ctrl.all()}toJSON(){return this.ctrl.toJSON()}fromJSON(e){return this.ctrl.fromJSON(e),this}favorites(){return this.ctrl.favorites()}isFavorite(e){return this.ctrl.isFavorite(e)}setFavorite(e,t){return this.ok("setFavorite")&&this.ctrl.setFavorite(e,t),this}setFavorites(e){return this.ok("setFavorites")&&this.ctrl.setFavorites([...e]),this}getConfig(){return this.ctrl.toJSON()}applyConfig(e){return this.ctrl.fromJSON(e),this}ok(e){return this.ctrl.supported?true:(console.warn(`[vela] chart.drawings.${e}() ignored \u2014 the active renderer has no userDrawings capability.`),false)}};function Ja(r){let e=r.trim(),t=/^#([0-9a-f]{3})$/i.exec(e);if(t){let i=t[1];return {r:parseInt(i[0]+i[0],16),g:parseInt(i[1]+i[1],16),b:parseInt(i[2]+i[2],16)}}if(t=/^#([0-9a-f]{6})[0-9a-f]{0,2}$/i.exec(e),t){let i=t[1];return {r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16)}}let n=/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i.exec(e);return n?{r:parseFloat(n[1]),g:parseFloat(n[2]),b:parseFloat(n[3])}:null}function q(r,e){let t=Ja(r);return t?`rgba(${t.r},${t.g},${t.b},${e})`:r}function Em(r,e,t){let n=Ja(r),i=Ja(e);if(!n||!i)return r;let o=(s,a)=>Math.round(s+(a-s)*t);return `rgb(${o(n.r,i.r)},${o(n.g,i.g)},${o(n.b,i.b)})`}function lt(r){let e=Ja(r);return e?.2126*e.r+.7152*e.g+.0722*e.b<128:true}var Qa={"--vela-space-1":"4px","--vela-space-2":"8px","--vela-space-3":"12px","--vela-space-4":"16px","--vela-radius-sm":"4px","--vela-radius-md":"6px","--vela-radius-lg":"10px","--vela-z-tooltip":"60","--vela-z-menu":"50","--vela-z-dialog":"40","--vela-z-popover":"6000","--vela-ease":"cubic-bezier(0.22, 1, 0.36, 1)","--vela-dur-fast":"90ms","--vela-dur-med":"160ms","--vela-font-size-sm":"11px","--vela-font-size-md":"12px","--vela-font-size-lg":"14px"};function el(r){let e=lt(r.background),t=i=>e?`rgba(255,255,255,${i})`:q(r.textColor,i+.02),n=Em(r.background,e?"#ffffff":r.textColor,e?.03:.05);return {"--vela-font":r.fontFamily,"--vela-bg":r.background,"--vela-fg":e?"#d1d4dc":r.textColor,"--vela-fg-muted":e?"#868a96":q(r.textColor,.62),"--vela-fg-faint":q(r.textColor,.35),"--vela-fg-bright":e?"#f0f3fa":"#000000","--vela-surface":r.background,"--vela-surface-elev":n,"--vela-surface-overlay":n,"--vela-surface-sunken":r.background,"--vela-border":r.borderColor,"--vela-border-strong":e?"#34353b":q(r.textColor,.28),"--vela-border-soft":r.borderColor,"--vela-border-faint":q(r.textColor,.08),"--vela-hover":t(.06),"--vela-active":t(.1),"--vela-hover-strong":t(.16),"--vela-focus":q(r.textColor,.5),"--vela-focus-soft":q(r.textColor,.12),"--vela-separator-hover-band":q(r.textColor,.1),"--vela-separator-hover-line":q(r.textColor,.55),"--vela-scroll":q(r.textColor,.3),"--vela-accent":Ye,"--vela-accent-bright":Br,"--vela-highlight":kp,"--vela-selected-bg":e?"#f0f3fa":r.textColor,"--vela-selected-fg":e?r.background:"#ffffff","--vela-fg-on-fill":"#ffffff","--vela-up":r.upColor,"--vela-down":r.downColor,"--vela-danger":r.downColor,"--vela-shadow":"0 8px 30px rgba(0,0,0,0.5)","--vela-shadow-dialog":"0 20px 60px rgba(0,0,0,0.5)","--vela-backdrop":"rgba(0,0,0,0.45)"}}function Ae(r,e){let t=n=>{for(let i in n)r.style.setProperty(i,n[i]);};t(Qa),t(el(e));}function Ut(r,e){let t=null,n=null,i=()=>{t!==null&&(clearTimeout(t),t=null),n?.remove(),n=null;},o=()=>{let a=e.text();if(!a)return;n=r.ownerDocument.createElement("div"),n.textContent=a,n.style.cssText="position:absolute;z-index:var(--vela-z-tooltip);pointer-events:none;background:var(--vela-bg);border:1px solid var(--vela-border);color:var(--vela-fg);border-radius:var(--vela-radius-md);padding:4px 9px;box-shadow:var(--vela-shadow);font:var(--vela-font-size-md) var(--vela-font);"+(e.wrap?"max-width:260px;":"white-space:nowrap;"),Ae(n,e.theme()),e.host.appendChild(n);let c=r.getBoundingClientRect(),d=e.host.getBoundingClientRect();if(e.placement==="right")n.style.left=`${c.right-d.left+8}px`,n.style.top=`${c.top-d.top+(c.height-n.offsetHeight)/2}px`;else {let u=Math.min(c.left-d.left,Math.max(0,d.width-n.offsetWidth-4));n.style.left=`${Math.max(0,u)}px`,n.style.top=e.placement==="above"?`${Math.max(0,c.top-d.top-n.offsetHeight-6)}px`:`${c.bottom-d.top+6}px`;}},s=a=>{a.pointerType==="mouse"&&(i(),t=window.setTimeout(o,e.delayMs??700));};return r.addEventListener("pointerenter",s),r.addEventListener("pointerleave",i),r.addEventListener("pointerdown",i),()=>{r.removeEventListener("pointerenter",s),r.removeEventListener("pointerleave",i),r.removeEventListener("pointerdown",i),i();}}function tl(r,e){let t=e.size??16,n=document.createElement("span");n.className="vela-hint",n.setAttribute("role","img"),n.setAttribute("aria-label",r),n.innerHTML=ye("info",t),n.style.cssText=`flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:${t}px;height:${t}px;border-radius:50%;cursor:help;user-select:none;background:var(--vela-hover);color:var(--vela-fg-muted);transition:background var(--vela-dur-fast) ease,color var(--vela-dur-fast) ease;`;let i=s=>{n.style.background=s?"var(--vela-active)":"var(--vela-hover)",n.style.color=s?"var(--vela-fg-bright)":"var(--vela-fg-muted)";};n.addEventListener("pointerenter",()=>i(true)),n.addEventListener("pointerleave",()=>i(false));let o=Ut(n,{host:e.host,theme:e.theme,text:()=>r,wrap:true,delayMs:250});return {el:n,dispose:o}}var $C=Object.defineProperty,WC=(r,e,t)=>e in r?$C(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t,le=(r,e,t)=>WC(r,typeof e!="symbol"?e+"":e,t);function Pm(r){return r==null?[]:Array.isArray(r)?r:[r]}var Lm=r=>r[0],Mm=r=>r[r.length-1];function km(r,e,t={}){let{step:n=1,loop:i=true}=t,o=e+n,s=r.length,a=s-1;return e===-1?n>0?0:a:o<0?i?a:0:o>=s?i?0:e>s?s:e:o}function Im(r,e,t={}){return r[km(r,e,t)]}function GC(r,e,t={}){let{step:n=1,loop:i=true}=t;return km(r,e,{step:-n,loop:i})}function Am(r,e,t={}){return r[GC(r,e,t)]}var Rm=r=>r?.constructor.name==="Array",UC=(r,e)=>{if(r.length!==e.length)return false;for(let t=0;t<r.length;t++)if(!Zr(r[t],e[t]))return false;return true},Zr=(r,e)=>{if(Object.is(r,e))return true;if(r==null&&e!=null||r!=null&&e==null)return false;if(typeof r?.isEqual=="function"&&typeof e?.isEqual=="function")return r.isEqual(e);if(typeof r=="function"&&typeof e=="function")return r.toString()===e.toString();if(Rm(r)&&Rm(e))return UC(Array.from(r),Array.from(e));if(typeof r!="object"||typeof e!="object")return false;let t=Object.keys(e??Object.create(null)),n=t.length;for(let i=0;i<n;i++)if(!Reflect.has(r,t[i]))return false;for(let i=0;i<n;i++){let o=t[i];if(!Zr(r[o],e[o]))return false}return true};var YC=r=>r!=null&&typeof r=="object";var Jr=r=>typeof r=="string",nt=r=>typeof r=="function",Dm=r=>r==null,fo=(r,e)=>Object.prototype.hasOwnProperty.call(r,e),KC=r=>Object.prototype.toString.call(r),Om=Function.prototype.toString,XC=Om.call(Object),fr=r=>{if(!YC(r)||KC(r)!="[object Object]"||ZC(r))return false;let e=Object.getPrototypeOf(r);if(e===null)return true;let t=fo(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Om.call(t)==XC},jC=r=>typeof r=="object"&&r!==null&&"$$typeof"in r&&"props"in r,qC=r=>typeof r=="object"&&r!==null&&"__v_isVNode"in r,ZC=r=>jC(r)||qC(r);var go=(r,...e)=>(typeof r=="function"?r(...e):r)??void 0,kd=r=>r,Nm=r=>r(),Id=()=>{},Dn=(...r)=>(...e)=>{r.forEach(function(t){t?.(...e);});};function On(r){if(!fr(r)||r===void 0)return r;let e=Reflect.ownKeys(r).filter(n=>typeof n=="string"),t={};for(let n of e){let i=r[n];i!==void 0&&(t[n]=On(i));}return t}function Qr(...r){r.length===1?r[0]:r[1];r.length===2?r[0]:true;}function Ad(...r){r.length===1?r[0]:r[1];r.length===2?r[0]:true;}function bo(r,e){if(r==null)throw new Error(e())}var JC=(...r)=>r.map(e=>e?.trim?.()).filter(Boolean).join(" "),QC=/((?:--)?(?:\w+-?)+)\s*:\s*([^;]*)/g,Fm=r=>{let e={},t;for(;t=QC.exec(r);)e[t[1]]=t[2];return e},e1=(r,e)=>{if(Jr(r)){if(Jr(e))return `${r};${e}`;r=Fm(r);}else Jr(e)&&(e=Fm(e));return Object.assign({},r??{},e??{})};function Vm(...r){let e={};for(let t of r){if(!t)continue;for(let i in e){if(i.startsWith("on")&&typeof e[i]=="function"&&typeof t[i]=="function"){e[i]=Dn(t[i],e[i]);continue}if(i==="className"||i==="class"){e[i]=JC(e[i],t[i]);continue}if(i==="style"){e[i]=e1(e[i],t[i]);continue}e[i]=t[i]!==void 0?t[i]:e[i];}for(let i in t)e[i]===void 0&&(e[i]=t[i]);let n=Object.getOwnPropertySymbols(t);for(let i of n)e[i]=t[i];}return e}var Nn=".",Hm="#",_m=new WeakMap,zm=new WeakMap;function Rd(r){return r.join(Nn)}function t1(r){return r.includes(Nn)}function $m(r){return r.startsWith(Hm)}function n1(r){return r.startsWith(Nn)}function r1(r){return $m(r)?r.slice(Hm.length):r}function Dd(r,e){return r?`${r}${Nn}${e}`:e}function i1(r){let e=new Map,t=new Map,n=(i,o)=>{e.set(i,o);let s=o.id;s&&(t.has(s)&&Ad(`[zag-js] Duplicate state id: "${s}"`),t.set(s,i));let a=o.states;if(a){bo(o.initial,()=>`[zag-js] Compound state "${i}" has child states but no "initial" property`),o.initial in a||Ad(`[zag-js] Compound state "${i}" has initial "${String(o.initial)}" which is not a child state`);for(let[l,c]of Object.entries(a)){if(!c)continue;let d=Dd(i,l);n(d,c);}}};for(let[i,o]of Object.entries(r.states))o&&n(i,o);return {index:e,idIndex:t}}function ei(r){let e=_m.get(r);if(e)return e;let{index:t,idIndex:n}=i1(r);return _m.set(r,t),zm.set(r,n),t}function o1(r,e){return ei(r),zm.get(r)?.get(e)}function Od(r){return r?String(r).split(Nn).filter(Boolean):[]}function nl(r,e){if(!e)return [];let t=ei(r),n=Od(e),i=[],o=[];for(let s of n){o.push(s);let a=Rd(o),l=t.get(a);if(!l)break;i.push({path:a,state:l});}return i}function vo(r,e){let t=ei(r),n=Od(e);if(!n.length)return e;let i=[];for(let a of n){i.push(a);let l=Rd(i);if(!t.has(l))return e}let o=Rd(i),s=t.get(o);for(;s?.initial;){let a=`${o}${Nn}${s.initial}`,l=t.get(a);if(!l)break;o=a,s=l;}return o}function Bm(r,e){return ei(r).has(e)}function Nd(r,e,t){let n=String(e);if($m(n)){let i=r1(n),o=o1(r,i);return bo(o,()=>`[zag-js] Unknown state id: "${i}"`),vo(r,o)}if(n1(n)&&t){let i=Dd(t,n.slice(1));return vo(r,i)}if(!t1(n)&&t){let i=Od(t);for(let o=i.length-1;o>=1;o--){let s=i.slice(0,o).join(Nn),a=Dd(s,n);if(Bm(r,a))return vo(r,a)}if(Bm(r,n))return vo(r,n)}return vo(r,n)}function Wm(r,e,t){let n=nl(r,e);for(let o=n.length-1;o>=0;o--){let a=n[o]?.state.on?.[t];if(a)return {transitions:a,source:n[o]?.path}}return {transitions:r.on?.[t],source:void 0}}function Gm(r,e,t,n){let i=e?nl(r,e):[],o=nl(r,t),s=0;for(;s<i.length&&s<o.length&&i[s]?.path===o[s]?.path;)s+=1;let a=i.slice(s).reverse(),l=o.slice(s),c=i.at(-1)?.path===o.at(-1)?.path;return n&&c&&(a=i.slice().reverse(),l=o),{exiting:a,entering:l}}function Um(r,e){return r?r===e||r.startsWith(`${e}${Nn}`):false}function Ym(r,e,t){return nl(r,e).some(n=>n.state.tags?.includes(t))}function Km(){return {and:(...r)=>function(t){return r.every(n=>t.guard(n))},or:(...r)=>function(t){return r.some(n=>t.guard(n))},not:r=>function(t){return !t.guard(r)}}}function rl(r){return ei(r),r}var ti=(r=>(r.NotStarted="Not Started",r.Started="Started",r.Stopped="Stopped",r))(ti||{}),yo="__init__";var s1=Object.defineProperty,a1=(r,e,t)=>e in r?s1(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t,il=(r,e,t)=>a1(r,typeof e!="symbol"?e+"":e,t);var Xm=(r,e)=>r.map((t,n)=>r[(Math.max(e,0)+n)%r.length]);var wo=()=>{},xo=r=>typeof r=="object"&&r!==null;var mt=r=>r?"":void 0,Fd=r=>r?"true":void 0;var l1=1,c1=9,d1=11;var ce=r=>xo(r)&&r.nodeType===l1&&typeof r.nodeName=="string",So=r=>xo(r)&&r.nodeType===c1,u1=r=>xo(r)&&r===r.window;var jm=r=>ce(r)?r.localName||"":"#document";function qm(r){return ["html","body","#document"].includes(jm(r))}var Zm=r=>xo(r)&&r.nodeType!==void 0,gr=r=>Zm(r)&&r.nodeType===d1&&"host"in r,Vd=r=>ce(r)&&r.localName==="input",Jm=r=>!!r?.matches("a[href]"),Qm=r=>ce(r)?r.offsetWidth>0||r.offsetHeight>0||r.getClientRects().length>0:false;function Co(r){if(!r)return false;let e=r.getRootNode();return Yt(e)===r}var h1=/(textarea|select)/;function ni(r){if(r==null||!ce(r))return false;try{return Vd(r)&&r.selectionStart!=null||h1.test(r.localName)||r.isContentEditable||r.getAttribute("contenteditable")==="true"||r.getAttribute("contenteditable")===""}catch{return false}}function rt(r,e){if(!r||!e||!ce(r)||!Zm(e))return false;if(ce(e)&&r===e||r.contains(e))return true;let t=e.getRootNode?.();if(t&&gr(t)){let n=e;for(;n;){if(r===n)return true;n=n.parentNode||n.host;}}return false}function Pe(r){return So(r)?r:u1(r)?r.document:r?.ownerDocument??document}function p1(r){return Pe(r).documentElement}function Se(r){return gr(r)?Se(r.host):So(r)?r.defaultView??window:ce(r)?r.ownerDocument?.defaultView??window:window}function Yt(r){let e=r.activeElement;for(;e?.shadowRoot;){let t=e.shadowRoot.activeElement;if(!t||t===e)break;e=t;}return e}function ef(r){if(jm(r)==="html")return r;let e=r.assignedSlot||r.parentNode||gr(r)&&r.host||p1(r);return gr(e)?e.host:e}function ol(r){let e;try{if(e=r.getRootNode({composed:!0}),So(e)||gr(e))return e}catch{}return r.ownerDocument??document}var _d=new WeakMap;function ri(r){return _d.has(r)||_d.set(r,Se(r).getComputedStyle(r)),_d.get(r)}var Bd=new Set(["menu","listbox","dialog","grid","tree","region","application"]),m1=r=>Bd.has(r),tf=r=>r.getAttribute("aria-controls")?.split(" ")||[];function sl(r,e){let t=new Set,n=ol(r),i=o=>{let s=o.querySelectorAll("[aria-controls]");for(let a of s){if(a.getAttribute("aria-expanded")!=="true")continue;let l=tf(a);for(let c of l){if(!c||t.has(c))continue;t.add(c);let d=n.getElementById(c);if(d){let u=d.getAttribute("role"),h=d.getAttribute("aria-modal")==="true";if(u&&m1(u)&&!h&&(d===e||d.contains(e)||i(d)))return true}}}return false};return i(r)}function Hd(r,e){let t=ol(r),n=new Set,i=o=>{let s=o.querySelectorAll("[aria-controls]");for(let a of s){if(a.getAttribute("aria-expanded")!=="true")continue;let l=tf(a);for(let c of l){if(!c||n.has(c))continue;n.add(c);let d=t.getElementById(c);if(d){let u=d.getAttribute("role"),h=d.getAttribute("aria-modal")==="true";u&&Bd.has(u)&&!h&&(e(d),i(d));}}}};i(r);}function nf(r){let e=new Set;return Hd(r,t=>{r.contains(t)||e.add(t);}),Array.from(e)}function f1(r){let e=r.getAttribute("role");return !!(e&&Bd.has(e))}function g1(r){return r.hasAttribute("aria-controls")&&r.getAttribute("aria-expanded")==="true"}function rf(r){return g1(r)?true:!!r.querySelector?.('[aria-controls][aria-expanded="true"]')}function of(r){if(!r.id)return false;let e=ol(r),t=CSS.escape(r.id),n=`[aria-controls~="${t}"][aria-expanded="true"], [aria-controls="${t}"][aria-expanded="true"]`;return !!(e.querySelector(n)&&f1(r))}var zd=()=>typeof document<"u";function b1(){return navigator.userAgentData?.platform??navigator.platform}function v1(){let r=navigator.userAgentData;return r&&Array.isArray(r.brands)?r.brands.map(({brand:e,version:t})=>`${e}/${t}`).join(" "):navigator.userAgent}var $d=r=>zd()&&r.test(b1()),sf=r=>zd()&&r.test(v1());var Wd=()=>zd()&&!!navigator.maxTouchPoints,y1=()=>$d(/^iPhone/i),w1=()=>$d(/^iPad/i)||ii()&&navigator.maxTouchPoints>1,af=()=>y1()||w1();var ii=()=>$d(/^Mac/i);var lf=()=>sf(/Firefox/i);var cf=()=>sf(/Android/i);function x1(r){return r.composedPath?.()??r.nativeEvent?.composedPath?.()}function Re(r){return x1(r)?.[0]??r.target}function Gd(r){let e=r.currentTarget;if(!e||!e.matches("a[href], button[type='submit'], input[type='submit']"))return false;let n=r.button===1,i=S1(r);return n||i}function Ud(r){let e=r.currentTarget;if(!e)return false;let t=e.localName;return r.altKey?t==="a"||t==="button"&&e.type==="submit"||t==="input"&&e.type==="submit":false}function S1(r){return ii()?r.metaKey:r.ctrlKey}function uf(r){return r.key.length===1&&!r.ctrlKey&&!r.metaKey}function hf(r){return r.pointerType===""&&r.isTrusted?true:cf()&&r.pointerType?r.type==="click"&&r.buttons===1:r.detail===0&&!r.pointerType}var al=r=>r.button===2||ii()&&r.ctrlKey&&r.button===0,pf=r=>r.ctrlKey||r.altKey||r.metaKey,C1=r=>"touches"in r&&r.touches.length>0,T1={Up:"ArrowUp",Down:"ArrowDown",Esc:"Escape"," ":"Space",",":"Comma",Left:"ArrowLeft",Right:"ArrowRight"},df={ArrowLeft:"ArrowRight",ArrowRight:"ArrowLeft"};function Yd(r,e={}){let{dir:t="ltr",orientation:n="horizontal"}=e,i=r.key;return i=T1[i]??i,t==="rtl"&&n==="horizontal"&&i in df&&(i=df[i]),i}function oi(r,e="client"){let t=C1(r)?r.touches[0]||r.changedTouches[0]:r;return {x:t[`${e}X`],y:t[`${e}Y`]}}var Xe=(r,e,t,n)=>{let i=typeof r=="function"?r():r;return i?.addEventListener(e,t,n),()=>{i?.removeEventListener(e,t,n);}};var mf=r=>ce(r)&&r.tagName==="IFRAME",E1=/^(audio|video|details)$/;function ff(r){let e=r.getAttribute("tabindex");return e?parseInt(e,10):NaN}var P1=r=>!Number.isNaN(ff(r)),L1=r=>ff(r)<0;function M1(r){return Vd(r)&&r.type==="radio"}function k1(r){if(!M1(r)||!r.name||r.checked)return true;let e=`input[type="radio"][name="${CSS.escape(r.name)}"]`,t=r.form??r.ownerDocument,n=Array.from(t.querySelectorAll(e)).filter(o=>o.form===r.form&&ft(o)),i=n.find(o=>o.checked);return i?i===r:n[0]===r}function I1(r,e){if(!e)return null;if(e===true)return r.shadowRoot||null;let t=e(r);return (t===true?r.shadowRoot:t)||null}function gf(r,e,t){let n=[...r],i=[...r],o=new Set,s=new Map;r.forEach((l,c)=>s.set(l,c));let a=0;for(;a<i.length;){let l=i[a++];if(!l||o.has(l))continue;o.add(l);let c=I1(l,e);if(c){let d=Array.from(c.querySelectorAll(ll)).filter(t),u=s.get(l);if(u!==void 0){let h=u+1;n.splice(h,0,...d),d.forEach((p,m)=>{s.set(p,h+m);});for(let p=h+d.length;p<n.length;p++)s.set(n[p],p);}else {let h=n.length;n.push(...d),d.forEach((p,m)=>{s.set(p,h+m);});}i.push(...d);}}return n}var ll="input:not([type='hidden']):not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], button:not([disabled]), [tabindex], iframe, object, embed, area[href], audio[controls], video[controls], [contenteditable]:not([contenteditable='false']), details > summary:first-of-type",Kd=(r,e={})=>{if(!r)return [];let{includeContainer:t=false,getShadowRoot:n}=e,i=Array.from(r.querySelectorAll(ll));(t==true||t=="if-empty"&&i.length===0)&&ce(r)&&ft(r)&&i.unshift(r);let s=[];for(let a of i)if(ft(a)){if(mf(a)&&a.contentDocument){let l=a.contentDocument.body;s.push(...Kd(l,{getShadowRoot:n}));continue}s.push(a);}return n?gf(s,n,ft):s};function ft(r){return !ce(r)||r.closest("[inert]")?false:r.matches(ll)&&Qm(r)}function si(r,e={}){if(!r)return [];let{includeContainer:t,getShadowRoot:n}=e,i=Array.from(r.querySelectorAll(ll));t&&Fn(r)&&i.unshift(r);let o=[];for(let s of i)if(Fn(s)){if(mf(s)&&s.contentDocument){let a=s.contentDocument.body;o.push(...si(a,{getShadowRoot:n}));continue}o.push(s);}if(n){let s=gf(o,n,Fn);return !s.length&&t?i:s}return !o.length&&t?i:o}function Fn(r){return ce(r)&&r.tabIndex>0?true:!ft(r)||L1(r)?false:k1(r)}function bf(r,e={}){let t=si(r,e),n=t[0]||null,i=t[t.length-1]||null;return [n,i]}function ai(r){return r.tabIndex<0&&(E1.test(r.localName)||ni(r))&&!P1(r)?0:r.tabIndex}function cl(r){let{root:e,getInitialEl:t,filter:n,enabled:i=true}=r;if(!i)return;let o=null;if(o||(o=typeof t=="function"?t():t),o||(o=e?.querySelector("[data-autofocus],[autofocus]")),!o){let s=si(e);o=n?s.filter(n)[0]:s[0];}return o||e||void 0}function vf(r){let e=r.currentTarget;if(!e)return false;let[t,n]=bf(e);return !(Co(t)&&r.shiftKey||Co(n)&&!r.shiftKey||!t&&!n)}var A1=class yf{constructor(){il(this,"id",null),il(this,"fn_cleanup"),il(this,"cleanup",()=>{this.cancel();});}static create(){return new yf}request(e){this.cancel(),this.id=globalThis.requestAnimationFrame(()=>{this.id=null,this.fn_cleanup=e?.();});}cancel(){this.id!==null&&(globalThis.cancelAnimationFrame(this.id),this.id=null),this.fn_cleanup?.(),this.fn_cleanup=void 0;}isActive(){return this.id!==null}};function Me(r){let e=A1.create();return e.request(r),e.cleanup}function wf(r){let e=new Set;function t(n){let i=globalThis.requestAnimationFrame(n);e.add(()=>globalThis.cancelAnimationFrame(i));}return t(()=>t(r)),function(){e.forEach(i=>i());}}function xf(r,e,t){let n=Me(()=>{r.removeEventListener(e,i,true),t();}),i=()=>{n(),t();};return r.addEventListener(e,i,{once:true,capture:true}),n}function R1(r,e){if(!r)return;let{attributes:t,callback:n}=e,i=r.ownerDocument.defaultView||window,o=new i.MutationObserver(s=>{for(let a of s)a.type==="attributes"&&a.attributeName&&t.includes(a.attributeName)&&n(a);});return o.observe(r,{attributes:true,attributeFilter:t}),()=>o.disconnect()}function Sf(r,e){let n=Me,i=[];return i.push(n(()=>{let o=typeof r=="function"?r():r;i.push(R1(o,e));})),()=>{i.forEach(o=>o?.());}}function Cf(r){let e=()=>{let t=Se(r);r.dispatchEvent(new t.MouseEvent("click"));};lf()?xf(r,"keyup",e):queueMicrotask(e);}function dl(r){let e=ef(r);return qm(e)?Pe(e).body:ce(e)&&Xd(e)?e:dl(e)}var D1=/auto|scroll|overlay|hidden|clip/,O1=new Set(["inline","contents"]);function Xd(r){let e=Se(r),{overflow:t,overflowX:n,overflowY:i,display:o}=e.getComputedStyle(r);return D1.test(t+i+n)&&!O1.has(o)}function li(r,e){return Array.from(r?.querySelectorAll(e)??[])}var ul=r=>r.id;function N1(r,e,t=ul){return r.find(n=>t(n)===e)}function Tf(r,e,t=ul){let n=N1(r,e,t);return n?r.indexOf(n):-1}function F1(r){return r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth}function Ef(r,e){let{rootEl:t,...n}=e||{};!r||!t||!Xd(t)||!F1(t)||r.scrollIntoView(n);}var V1=r=>r.split("").map(e=>{let t=e.charCodeAt(0);return t>0&&t<128?e:t>=128&&t<=255?`/x${t.toString(16)}`.replace("/","\\"):""}).join("").trim(),_1=r=>V1(r.dataset?.valuetext??r.textContent??""),B1=(r,e)=>r.trim().toLowerCase().startsWith(e.toLowerCase());function Pf(r,e,t,n=ul){let i=t?Tf(r,t,n):-1,o=t?Xm(r,i):r;return e.length===1&&(o=o.filter(a=>n(a)!==t)),o.find(a=>B1(_1(a),e))}function To(r,e){if(!r)return wo;let t=Object.keys(e).reduce((n,i)=>(n[i]=r.style.getPropertyValue(i),n),{});return H1(t,e)?wo:(Object.assign(r.style,e),()=>{Object.assign(r.style,t),r.style.length===0&&r.removeAttribute("style");})}function Lf(r,e,t){if(!r)return wo;let n=r.style.getPropertyValue(e);return n===t?wo:(r.style.setProperty(e,t),()=>{r.style.setProperty(e,n),r.style.length===0&&r.removeAttribute("style");})}function H1(r,e){return Object.keys(r).every(t=>r[t]===e[t])}function z1(r,e){let{state:t,activeId:n,key:i,timeout:o=350,itemToId:s}=e,a=t.keysSoFar+i,c=a.length>1&&Array.from(a).every(m=>m===a[0])?a[0]:a,d=r.slice(),u=Pf(d,c,n,s);function h(){clearTimeout(t.timer),t.timer=-1;}function p(m){t.keysSoFar=m,h(),m!==""&&(t.timer=+setTimeout(()=>{p(""),h();},o));}return p(a),u}var hl=Object.assign(z1,{defaultOptions:{keysSoFar:"",timer:-1},isValidEvent:$1});function $1(r){return r.key.length===1&&!r.ctrlKey&&!r.metaKey}function W1(r,e,t){let{signal:n}=e;return [new Promise((s,a)=>{let l=setTimeout(()=>{a(new Error(`Timeout of ${t}ms exceeded`));},t);n.addEventListener("abort",()=>{clearTimeout(l),a(new DOMException("Promise aborted","AbortError"));}),r.then(c=>{n.aborted||(clearTimeout(l),s(c));}).catch(c=>{n.aborted||(clearTimeout(l),a(c));});}),()=>e.abort()]}function Mf(r,e){let{timeout:t,rootNode:n}=e,i=Se(n),o=Pe(n),s=new i.AbortController;return W1(new Promise(a=>{let l=r();if(l){a(l);return}let c=new i.MutationObserver(()=>{let d=r();d&&d.isConnected&&(c.disconnect(),a(d));});c.observe(o.body,{childList:true,subtree:true});}),s,t)}function kf(r){let e=()=>r.getRootNode?.()??document,t=()=>Pe(e());return {...r,getRootNode:e,getDoc:t,getWin:()=>t().defaultView??window,getActiveElement:()=>Yt(e()),isActiveElement:Co,getById:s=>e().getElementById(s)}}function If(r){return new Proxy({},{get(e,t){return t==="style"?n=>r({style:n}).style:r}})}var Af={onFocus:"onFocusin",onBlur:"onFocusout",onChange:"onInput",onDoubleClick:"onDblclick",htmlFor:"for",className:"class",defaultValue:"value",defaultChecked:"checked"},G1=new Set(["viewBox","preserveAspectRatio"]),U1=r=>{let e="";for(let t in r){let n=r[t];n!=null&&(t.startsWith("--")||(t=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)),e+=`${t}:${n};`);}return e},ci=If(r=>Object.entries(r).reduce((e,[t,n])=>{if(n===void 0)return e;if(t in Af&&(t=Af[t]),t==="style"&&typeof n=="object")return e.style=U1(n),e;let i=G1.has(t)?t:t.toLowerCase();return e[i]=n,e},{}));var pl=new WeakMap,Rf=new Set(["value","checked","selected"]),Y1=new Set(["viewBox","preserveAspectRatio","clipPath","clipRule","fillRule","strokeWidth","strokeLinecap","strokeLinejoin","strokeDasharray","strokeDashoffset","strokeMiterlimit"]),K1=r=>r.tagName==="svg"||r.namespaceURI==="http://www.w3.org/2000/svg",ml=(r,e)=>K1(r)&&Y1.has(e)?e:e.toLowerCase();function it(r,e,t){let n=t||"default",i=pl.get(r);i||(i=new Map,pl.set(r,i));let o=i.get(n)||{},s=Object.keys(e),a=(f,g)=>{r.addEventListener(f.toLowerCase(),g);},l=(f,g)=>{r.removeEventListener(f.toLowerCase(),g);},c=f=>f.startsWith("on"),d=f=>!f.startsWith("on"),u=f=>a(f.substring(2),e[f]),h=f=>l(f.substring(2),e[f]),p=f=>{let g=e[f],b=o[f];if(g!==b){if(f==="class"){r.className=g??"";return}if(Rf.has(f)){r[f]=g??"";return}if(typeof g=="boolean"&&!f.includes("aria-")){r.toggleAttribute(ml(r,f),g);return}if(f==="children"){r.innerHTML=g;return}if(g!=null){r.setAttribute(ml(r,f),g);return}r.removeAttribute(ml(r,f));}};for(let f in o)e[f]==null&&(f==="class"?r.className="":Rf.has(f)?r[f]="":r.removeAttribute(ml(r,f)));return Object.keys(o).filter(c).forEach(f=>{l(f.substring(2),o[f]);}),s.filter(c).forEach(u),s.filter(d).forEach(p),i.set(n,e),function(){s.filter(c).forEach(h);let g=pl.get(r);g&&(g.delete(n),g.size===0&&pl.delete(r));}}function X1(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function jd(r,e){let t=X1();return t?(t[r]||(t[r]=e()),t[r]):e()}var di=jd("__zag__refSet",()=>new WeakSet);var j1=r=>typeof r=="object"&&r!==null&&"$$typeof"in r&&"props"in r,q1=r=>typeof r=="object"&&r!==null&&"__v_isVNode"in r,Z1=r=>typeof r=="object"&&r!==null&&"nodeType"in r&&typeof r.nodeName=="string",J1=r=>j1(r)||q1(r)||Z1(r),fl=r=>r!==null&&typeof r=="object",qd=r=>fl(r)&&!di.has(r)&&(Array.isArray(r)||!(Symbol.iterator in r))&&!J1(r)&&!(r instanceof WeakMap)&&!(r instanceof WeakSet)&&!(r instanceof Error)&&!(r instanceof Number)&&!(r instanceof Date)&&!(r instanceof String)&&!(r instanceof RegExp)&&!(r instanceof ArrayBuffer)&&!(r instanceof Promise)&&!(r instanceof File)&&!(r instanceof Blob)&&!(r instanceof AbortController);var Q1=Symbol();var Df=Object.getPrototypeOf,Zd=new WeakMap,eT=r=>r&&(Zd.has(r)?Zd.get(r):Df(r)===Object.prototype||Df(r)===Array.prototype);var Of=r=>eT(r)&&r[Q1]||null,Jd=(r,e=true)=>{Zd.set(r,e);};var br=jd("__zag__proxyStateMap",()=>new WeakMap),tT=(r=Object.is,e=(a,l)=>new Proxy(a,l),t=new WeakMap,n=(a,l)=>{let c=t.get(a);if(c?.[0]===l)return c[1];let d=Array.isArray(a)?[]:Object.create(Object.getPrototypeOf(a));return Jd(d,true),t.set(a,[l,d]),Reflect.ownKeys(a).forEach(u=>{let h=Reflect.get(a,u);di.has(h)?(Jd(h,false),d[u]=h):br.has(h)?d[u]=Nf(h):d[u]=h;}),Object.freeze(d)},i=new WeakMap,o=[1,1],s=a=>{if(!fl(a))throw new Error("object required");let l=i.get(a);if(l)return l;let c=o[0],d=new Set,u=(E,x=++o[0])=>{c!==x&&(c=x,d.forEach(L=>L(E,x)));},h=o[1],p=(E=++o[1])=>(h!==E&&!d.size&&(h=E,f.forEach(([x])=>{let L=x[1](E);L>c&&(c=L);})),c),m=E=>(x,L)=>{let w=[...x];w[1]=[E,...w[1]],u(w,L);},f=new Map,g=(E,x)=>{if(d.size){let L=x[3](m(E));f.set(E,[x,L]);}else f.set(E,[x]);},b=E=>{let x=f.get(E);x&&(f.delete(E),x[1]?.());},y=E=>(d.add(E),d.size===1&&f.forEach(([L,w],M)=>{let k=L[3](m(M));f.set(M,[L,k]);}),()=>{d.delete(E),d.size===0&&f.forEach(([L,w],M)=>{w&&(w(),f.set(M,[L]));});}),v=Array.isArray(a)?[]:Object.create(Object.getPrototypeOf(a)),P=e(v,{deleteProperty(E,x){let L=Reflect.get(E,x);b(x);let w=Reflect.deleteProperty(E,x);return w&&u(["delete",[x],L]),w},set(E,x,L,w){let M=Reflect.has(E,x),k=Reflect.get(E,x,w);if(M&&(r(k,L)||i.has(L)&&r(k,i.get(L))))return true;b(x),fl(L)&&(L=Of(L)||L);let C=L;if(!Object.getOwnPropertyDescriptor(E,x)?.set){!br.has(L)&&qd(L)&&(C=gl(L));let A=!di.has(C)&&br.get(C);A&&g(x,A);}return Reflect.set(E,x,C,w),u(["set",[x],L,k]),true}});i.set(a,P);let T=[v,p,n,y];return br.set(P,T),Reflect.ownKeys(a).forEach(E=>{let x=Object.getOwnPropertyDescriptor(a,E);x.get||x.set?Object.defineProperty(v,E,x):P[E]=a[E];}),P})=>[s,br,di,r,e,qd,t,n,i,o],[nT]=tT();function gl(r={}){return nT(r)}function bl(r,e,t){let n=br.get(r);let i,o=[],s=n[3],a=false,c=s(d=>{if(o.push(d),t);i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(o.splice(0));}));});return a=true,()=>{a=false,c();}}function Nf(r){let e=br.get(r);let[t,n,i]=e;return i(t,n())}function Po(r){let e=r().value??r().defaultValue;r().debug&&console.log(`[bindable > ${r().debug}] initial`,e);let t=r().isEqual??Object.is,n=gl({value:e}),i=()=>r().value!==void 0;return {initial:e,ref:n,get(){return i()?r().value:n.value},set(o){let s=i()?r().value:n.value,a=nt(o)?o(s):o;r().debug&&console.log(`[bindable > ${r().debug}] setValue`,{next:a,prev:s}),i()||(n.value=a),t(a,s)||r().onChange?.(a,s);},invoke(o,s){r().onChange?.(o,s);},hash(o){return r().hash?.(o)??String(o)}}}Po.cleanup=r=>{};Po.ref=r=>{let e=r;return {get:()=>e,set:t=>{e=t;}}};function Ff(r){let e={current:r};return {get(t){return e.current[t]},set(t,n){e.current[t]=n;}}}function Qd(r,e){if(!fr(r)||!fr(e))return e===void 0?r:e;let t={...r};for(let n of Object.keys(e)){let i=e[n],o=r[n];i!==void 0&&(fr(o)&&fr(i)?t[n]=Qd(o,i):t[n]=i);}return t}var eu=class{constructor(r,e={}){le(this,"machine",r),le(this,"scope"),le(this,"context"),le(this,"prop"),le(this,"state"),le(this,"refs"),le(this,"computed"),le(this,"event",{type:""}),le(this,"previousEvent",{type:""}),le(this,"effects",new Map),le(this,"transition",null),le(this,"cleanups",[]),le(this,"subscriptions",[]),le(this,"userPropsRef"),le(this,"getEvent",()=>({...this.event,current:()=>this.event,previous:()=>this.previousEvent})),le(this,"getState",()=>({...this.state,matches:(...u)=>u.some(h=>Um(this.state.get(),h)),hasTag:u=>Ym(this.machine,this.state.get(),u)})),le(this,"debug",(...u)=>{this.machine.debug&&console.log(...u);}),le(this,"notify",()=>{this.publish();}),le(this,"send",u=>{this.status===ti.Started&&queueMicrotask(()=>{if(!u)return;this.previousEvent=this.event,this.event=u,this.debug("send",u);let h=this.state.get(),p=u.type,{transitions:m,source:f}=Wm(this.machine,h,p),g=this.choose(m);if(!g)return;this.transition=g;let b=Nd(this.machine,g.target??h,f);this.debug("transition",g),b!==h?this.state.set(b):g.reenter?this.state.invoke(h,h):this.action(g.actions);});}),le(this,"action",u=>{let h=nt(u)?u(this.getParams()):u;if(!h)return;let p=h.map(m=>{let f=this.machine.implementations?.actions?.[m];return f||Qr(`[zag-js] No implementation found for action "${JSON.stringify(m)}"`),f});for(let m of p)m?.(this.getParams());}),le(this,"guard",u=>{if(nt(u))return u(this.getParams());let h=this.machine.implementations?.guards?.[u];return h||Qr(`[zag-js] No implementation found for guard "${JSON.stringify(u)}"`),h?.(this.getParams())}),le(this,"effect",u=>{let h=nt(u)?u(this.getParams()):u;if(!h)return;let p=h.map(f=>{let g=this.machine.implementations?.effects?.[f];return g||Qr(`[zag-js] No implementation found for effect "${JSON.stringify(f)}"`),g}),m=[];for(let f of p){let g=f?.(this.getParams());g&&m.push(g);}return ()=>m.forEach(f=>f?.())}),le(this,"choose",u=>Pm(u).find(h=>{let p=!h.guard;return Jr(h.guard)?p=!!this.guard(h.guard):nt(h.guard)&&(p=h.guard(this.getParams())),p})),le(this,"subscribe",u=>(this.subscriptions.push(u),()=>{let h=this.subscriptions.indexOf(u);h>-1&&this.subscriptions.splice(h,1);})),le(this,"status",ti.NotStarted),le(this,"publish",()=>{this.callTrackers(),this.subscriptions.forEach(u=>u(this.service));}),le(this,"trackers",[]),le(this,"setupTrackers",()=>{this.machine.watch?.(this.getParams());}),le(this,"callTrackers",()=>{this.trackers.forEach(({deps:u,fn:h})=>{let p=u.map(m=>m());Zr(h.prev,p)||(h(),h.prev=p);});}),le(this,"getParams",()=>({state:this.getState(),context:this.context,event:this.getEvent(),prop:this.prop,send:this.send,action:this.action,guard:this.guard,track:(u,h)=>{h.prev=u.map(p=>p()),this.trackers.push({deps:u,fn:h});},refs:this.refs,computed:this.computed,flush:Nm,scope:this.scope,choose:this.choose})),this.userPropsRef={current:e};let{id:t,ids:n,getRootNode:i}=go(e);this.scope=kf({id:t,ids:n,getRootNode:i});let o=u=>{let h=go(this.userPropsRef.current);return (r.props?.({props:On(h),scope:this.scope})??h)[u]};this.prop=o;let s=r.context?.({prop:o,bindable:Po,scope:this.scope,flush(u){queueMicrotask(u);},getContext(){return a},getComputed(){return l},getRefs(){return c},getEvent:this.getEvent.bind(this)});s&&Object.values(s).forEach(u=>{let h=bl(u.ref,()=>this.notify());this.cleanups.push(h);});let a={get(u){return s?.[u].get()},set(u,h){s?.[u].set(h);},initial(u){return s?.[u].initial},hash(u){let h=s?.[u].get();return s?.[u].hash(h)}};this.context=a;let l=u=>(bo(r.computed,()=>"[zag-js] No computed object found on machine"),r.computed[u]({context:a,event:this.getEvent(),prop:o,refs:this.refs,scope:this.scope,computed:l}));this.computed=l;let c=Ff(r.refs?.({prop:o,context:a})??{});this.refs=c;let d=Po(()=>({defaultValue:Nd(r,r.initialState({prop:o})),onChange:(u,h)=>{let{exiting:p,entering:m}=Gm(this.machine,h,u,this.transition?.reenter);if(p.forEach(f=>{this.effects.get(f.path)?.(),this.effects.delete(f.path);}),p.forEach(f=>{this.action(f.state?.exit);}),this.action(this.transition?.actions),m.forEach(f=>{let g=this.effect(f.state?.effects);if(g){let b=this.effects.get(f.path);this.effects.set(f.path,b?Dn(b,g):g);}}),h===yo){this.action(r.entry);let f=this.effect(r.effects);if(f){let g=this.effects.get(yo);this.effects.set(yo,g?Dn(g,f):f);}}m.forEach(f=>{this.action(f.state?.entry);});}}));this.state=d,this.cleanups.push(bl(this.state.ref,()=>this.notify()));}updateProps(r){let e=this.userPropsRef.current;this.userPropsRef.current=()=>{let t=go(e),n=go(r);return Qd(t,n)},this.notify();}start(){this.status=ti.Started,this.debug("initializing..."),this.state.invoke(this.state.initial,yo),this.setupTrackers();}stop(){this.effects.forEach(r=>r?.()),this.effects.clear(),this.transition=null,this.action(this.machine.exit),this.cleanups.forEach(r=>r()),this.cleanups=[],this.subscriptions=[],this.status=ti.Stopped,this.debug("unmounting...");}get service(){return {state:this.getState(),send:this.send,context:this.context,prop:this.prop,scope:this.scope,refs:this.refs,computed:this.computed,event:this.getEvent(),getStatus:()=>this.status}}};function vl(r,e,t){let n=new eu(r,e),i=n.subscribe(t);return n.start(),t(n.service),{service:n.service,flush:()=>t(n.service),stop:()=>{i(),n.stop();}}}var rT=0;function yl(r){return `${r}-${++rT}`}function vr(r,e=8){return `${r}::-webkit-scrollbar{width:${e}px;height:${e}px;}${r}::-webkit-scrollbar-thumb{background:var(--vela-scroll);border-radius:4px;border:2px solid transparent;background-clip:padding-box;}${r}::-webkit-scrollbar-track{background:transparent;}${r}::-webkit-scrollbar-button{display:none;width:0;height:0;}`}var Vf="outline:none;transition:border-color .12s ease,box-shadow .12s ease;",_f="border-color:var(--vela-focus);box-shadow:0 0 0 3px var(--vela-focus-soft);";function ge(r,e,t=document){if(typeof document>"u")return;let n=t instanceof Document?t.head:t;if(t.getElementById?.(r)??n.querySelector(`#${CSS.escape(r)}`))return;let i=document.createElement("style");i.id=r,i.textContent=e,n.appendChild(i);}function je(r,e=document){let t=e.createElement("span");t.className="vela-icon",t.setAttribute("aria-hidden","true");let n=Fs(r);return n&&(t.innerHTML=n),t}var hn=(r,e=[])=>({parts:(...t)=>{if(iT(e))return hn(r,t);throw new Error("createAnatomy().parts(...) should only be called once. Did you mean to use .extendWith(...) ?")},extendWith:(...t)=>hn(r,[...e,...t]),omit:(...t)=>hn(r,e.filter(n=>!t.includes(n))),rename:t=>hn(t,e),keys:()=>e,build:()=>[...new Set(e)].reduce((t,n)=>Object.assign(t,{[n]:{selector:[`&[data-scope="${ui(r)}"][data-part="${ui(n)}"]`,`& [data-scope="${ui(r)}"][data-part="${ui(n)}"]`].join(", "),attrs:{"data-scope":ui(r),"data-part":ui(n)}}}),{})}),ui=r=>r.replace(/([A-Z])([A-Z])/g,"$1-$2").replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase(),iT=r=>r.length===0;var oT=hn("menu").parts("arrow","arrowTip","content","contextTrigger","indicator","item","itemGroup","itemGroupLabel","itemIndicator","itemText","positioner","separator","trigger","triggerItem"),ze=oT.build();var zf=["top","right","bottom","left"];var Kt=Math.min,Mt=Math.max,Mo=Math.round,ko=Math.floor,Xt=r=>({x:r,y:r}),sT={left:"right",right:"left",bottom:"top",top:"bottom"};function tu(r,e,t){return Mt(r,Kt(e,t))}function jt(r,e){return typeof r=="function"?r(e):r}function pn(r){return r.split("-")[0]}function yr(r){return r.split("-")[1]}function xl(r){return r==="x"?"y":"x"}function Sl(r){return r==="y"?"height":"width"}function kt(r){let e=r[0];return e==="t"||e==="b"?"y":"x"}function Cl(r){return xl(kt(r))}function $f(r,e,t){t===void 0&&(t=false);let n=yr(r),i=Cl(r),o=Sl(i),s=i==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(s=Lo(s)),[s,Lo(s)]}function Wf(r){let e=Lo(r);return [wl(r),e,wl(e)]}function wl(r){return r.includes("start")?r.replace("start","end"):r.replace("end","start")}var Bf=["left","right"],Hf=["right","left"],aT=["top","bottom"],lT=["bottom","top"];function cT(r,e,t){switch(r){case "top":case "bottom":return t?e?Hf:Bf:e?Bf:Hf;case "left":case "right":return e?aT:lT;default:return []}}function Gf(r,e,t,n){let i=yr(r),o=cT(pn(r),t==="start",n);return i&&(o=o.map(s=>s+"-"+i),e&&(o=o.concat(o.map(wl)))),o}function Lo(r){let e=pn(r);return sT[e]+r.slice(e.length)}function dT(r){var e,t,n,i;return {top:(e=r.top)!=null?e:0,right:(t=r.right)!=null?t:0,bottom:(n=r.bottom)!=null?n:0,left:(i=r.left)!=null?i:0}}function nu(r){return typeof r!="number"?dT(r):{top:r,right:r,bottom:r,left:r}}function wr(r){let{x:e,y:t,width:n,height:i}=r;return {width:n,height:i,top:t,left:e,right:e+n,bottom:t+i,x:e,y:t}}function Uf(r,e,t){let{reference:n,floating:i}=r,o=kt(e),s=Cl(e),a=Sl(s),l=pn(e),c=o==="y",d=n.x+n.width/2-i.width/2,u=n.y+n.height/2-i.height/2,h=n[a]/2-i[a]/2,p;switch(l){case "top":p={x:d,y:n.y-i.height};break;case "bottom":p={x:d,y:n.y+n.height};break;case "right":p={x:n.x+n.width,y:u};break;case "left":p={x:n.x-i.width,y:u};break;default:p={x:n.x,y:n.y};}let m=yr(e);return m&&(p[s]+=h*(m==="end"?1:-1)*(t&&c?-1:1)),p}async function Xf(r,e){var t;e===void 0&&(e={});let{x:n,y:i,platform:o,rects:s,elements:a,strategy:l}=r,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=false,padding:p=0}=jt(e,r),m=nu(p),g=a[h?u==="floating"?"reference":"floating":u],b=wr(await o.getClippingRect({element:(t=await(o.isElement==null?void 0:o.isElement(g)))==null||t?g:g.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),y=u==="floating"?{x:n,y:i,width:s.floating.width,height:s.floating.height}:s.reference,v=await(o.getOffsetParent==null?void 0:o.getOffsetParent(a.floating)),S=await(o.isElement==null?void 0:o.isElement(v))&&await(o.getScale==null?void 0:o.getScale(v))||{x:1,y:1},P=wr(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:y,offsetParent:v,strategy:l}):y);return {top:(b.top-P.top+m.top)/S.y,bottom:(P.bottom-b.bottom+m.bottom)/S.y,left:(b.left-P.left+m.left)/S.x,right:(P.right-b.right+m.right)/S.x}}var uT=50,jf=async(r,e,t)=>{let{placement:n="bottom",strategy:i="absolute",middleware:o=[],platform:s}=t,a=s.detectOverflow?s:{...s,detectOverflow:Xf},l=await(s.isRTL==null?void 0:s.isRTL(e)),c=await s.getElementRects({reference:r,floating:e,strategy:i}),{x:d,y:u}=Uf(c,n,l),h=n,p=0,m={};for(let f=0;f<o.length;f++){let g=o[f];if(!g)continue;let{name:b,fn:y}=g,{x:v,y:S,data:P,reset:T}=await y({x:d,y:u,initialPlacement:n,placement:h,strategy:i,middlewareData:m,rects:c,platform:a,elements:{reference:r,floating:e}});d=v??d,u=S??u,m[b]={...m[b],...P},T&&p<uT&&(p++,typeof T=="object"&&(T.placement&&(h=T.placement),T.rects&&(c=T.rects===true?await s.getElementRects({reference:r,floating:e,strategy:i}):T.rects),{x:d,y:u}=Uf(c,h,l)),f=-1);}return {x:d,y:u,placement:h,strategy:i,middlewareData:m}},qf=r=>({name:"arrow",options:r,async fn(e){let{x:t,y:n,placement:i,rects:o,platform:s,elements:a,middlewareData:l}=e,{element:c,padding:d=0}=jt(r,e)||{};if(c==null)return {};let u=nu(d),h={x:t,y:n},p=Cl(i),m=Sl(p),f=await s.getDimensions(c),g=p==="y",b=g?"top":"left",y=g?"bottom":"right",v=g?"clientHeight":"clientWidth",S=o.reference[m]+o.reference[p]-h[p]-o.floating[m],P=h[p]-o.reference[p],T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(c)),E=T?T[v]:0;(!E||!await(s.isElement==null?void 0:s.isElement(T)))&&(E=a.floating[v]||o.floating[m]);let x=S/2-P/2,L=E/2-f[m]/2-1,w=Kt(u[b],L),M=Kt(u[y],L),k=E-f[m]-M,C=E/2-f[m]/2+x,A=tu(w,C,k),$=!l.arrow&&yr(i)!=null&&C!==A&&o.reference[m]/2-(C<w?w:M)-f[m]/2<0,ie=$?C<w?C-w:C-k:0;return {[p]:h[p]+ie,data:{[p]:A,centerOffset:C-A-ie,...$&&{alignmentOffset:ie}},reset:$}}});var Zf=function(r){return r===void 0&&(r={}),{name:"flip",options:r,async fn(e){var t,n;let{placement:i,middlewareData:o,rects:s,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:d=true,crossAxis:u=true,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:f=true,...g}=jt(r,e);if((t=o.arrow)!=null&&t.alignmentOffset)return {};let b=pn(i),y=kt(a),v=pn(a)===a,S=await(l.isRTL==null?void 0:l.isRTL(c.floating)),P=h||(v||!f?[Lo(a)]:Wf(a)),T=m!=="none";!h&&T&&P.push(...Gf(a,f,m,S));let E=[a,...P],x=await l.detectOverflow(e,g),L=[],w=((n=o.flip)==null?void 0:n.overflows)||[];if(d&&L.push(x[b]),u){let A=$f(i,s,S);L.push(x[A[0]],x[A[1]]);}if(w=[...w,{placement:i,overflows:L}],!L.every(A=>A<=0)){var M,k;let A=(((M=o.flip)==null?void 0:M.index)||0)+1,$=E[A];if($&&(!(u==="alignment"?y!==kt($):false)||w.every(j=>kt(j.placement)===y?j.overflows[0]>0:true)))return {data:{index:A,overflows:w},reset:{placement:$}};let ie=(k=w.filter(oe=>oe.overflows[0]<=0).sort((oe,j)=>oe.overflows[1]-j.overflows[1])[0])==null?void 0:k.placement;if(!ie)switch(p){case "bestFit":{var C;let oe=(C=w.filter(j=>{if(T){let dt=kt(j.placement);return dt===y||dt==="y"}return true}).map(j=>[j.placement,j.overflows.filter(dt=>dt>0).reduce((dt,Gx)=>dt+Gx,0)]).sort((j,dt)=>j[1]-dt[1])[0])==null?void 0:C[0];oe&&(ie=oe);break}case "initialPlacement":ie=a;break}if(i!==ie)return {reset:{placement:ie}}}return {}}}};function Yf(r,e){return {top:r.top-e.height,right:r.right-e.width,bottom:r.bottom-e.height,left:r.left-e.width}}function Kf(r){return zf.some(e=>r[e]>=0)}var Jf=function(r){return r===void 0&&(r={}),{name:"hide",options:r,async fn(e){let{rects:t,platform:n}=e,{strategy:i="referenceHidden",...o}=jt(r,e);switch(i){case "referenceHidden":{let s=await n.detectOverflow(e,{...o,elementContext:"reference"}),a=Yf(s,t.reference);return {data:{referenceHiddenOffsets:a,referenceHidden:Kf(a)}}}case "escaped":{let s=await n.detectOverflow(e,{...o,altBoundary:true}),a=Yf(s,t.floating);return {data:{escapedOffsets:a,escaped:Kf(a)}}}default:return {}}}}};var Qf=new Set(["left","top"]);async function hT(r,e){let{placement:t,platform:n,elements:i}=r,o=await(n.isRTL==null?void 0:n.isRTL(i.floating)),s=pn(t),a=yr(t),l=kt(t)==="y",c=Qf.has(s)?-1:1,d=o&&l?-1:1,u=jt(e,r),{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}var eg=function(r){return r===void 0&&(r=0),{name:"offset",options:r,async fn(e){var t,n;let{x:i,y:o,placement:s,middlewareData:a}=e,l=await hT(e,r);return s===((t=a.offset)==null?void 0:t.placement)&&(n=a.arrow)!=null&&n.alignmentOffset?{}:{x:i+l.x,y:o+l.y,data:{...l,placement:s}}}}},tg=function(r){return r===void 0&&(r={}),{name:"shift",options:r,async fn(e){let{x:t,y:n,placement:i,platform:o}=e,{mainAxis:s=true,crossAxis:a=false,limiter:l={fn:y=>{let{x:v,y:S}=y;return {x:v,y:S}}},...c}=jt(r,e),d={x:t,y:n},u=await o.detectOverflow(e,c),h=kt(i),p=xl(h),m=d[p],f=d[h],g=(y,v)=>tu(v+u[y==="y"?"top":"left"],v,v-u[y==="y"?"bottom":"right"]);s&&(m=g(p,m)),a&&(f=g(h,f));let b=l.fn({...e,[p]:m,[h]:f});return {...b,data:{x:b.x-t,y:b.y-n,enabled:{[p]:s,[h]:a}}}}}},ng=function(r){return r===void 0&&(r={}),{options:r,fn(e){var t,n;let{x:i,y:o,placement:s,rects:a,middlewareData:l}=e,{offset:c=0,mainAxis:d=true,crossAxis:u=true}=jt(r,e),h={x:i,y:o},p=kt(s),m=xl(p),f=h[m],g=h[p],b=jt(c,e),y=typeof b=="number"?{mainAxis:b,crossAxis:0}:{mainAxis:(t=b.mainAxis)!=null?t:0,crossAxis:(n=b.crossAxis)!=null?n:0};if(d){let P=m==="y"?"height":"width",T=a.reference[m]-a.floating[P]+y.mainAxis,E=a.reference[m]+a.reference[P]-y.mainAxis;f<T?f=T:f>E&&(f=E);}if(u){var v,S;let P=m==="y"?"width":"height",T=Qf.has(pn(s)),E=a.reference[p]-a.floating[P]+(T&&((v=l.offset)==null?void 0:v[p])||0)+(T?0:y.crossAxis),x=a.reference[p]+a.reference[P]+(T?0:((S=l.offset)==null?void 0:S[p])||0)-(T?y.crossAxis:0);g<E?g=E:g>x&&(g=x);}return {[m]:f,[p]:g}}}},rg=function(r){return r===void 0&&(r={}),{name:"size",options:r,async fn(e){let{placement:t,rects:n,platform:i,elements:o}=e,{apply:s=()=>{},...a}=jt(r,e),l=await i.detectOverflow(e,a),c=pn(t),d=yr(t),u=kt(t)==="y",{width:h,height:p}=n.floating,m,f;c==="top"||c==="bottom"?(m=c,f=d===(await(i.isRTL==null?void 0:i.isRTL(o.floating))?"start":"end")?"left":"right"):(f=c,m=d==="end"?"top":"bottom");let g=p-l.top-l.bottom,b=h-l.left-l.right,y=Kt(p-l[m],g),v=Kt(h-l[f],b),S=e.middlewareData.shift,P=!S,T=y,E=v;S!=null&&S.enabled.x&&(E=b),S!=null&&S.enabled.y&&(T=g),P&&!d&&(u?E=h-2*Mt(l.left,l.right):T=p-2*Mt(l.top,l.bottom)),await s({...e,availableWidth:E,availableHeight:T});let x=await i.getDimensions(o.floating);return h!==x.width||p!==x.height?{reset:{rects:true}}:{}}}};function Tl(){return typeof window<"u"}function Sr(r){return og(r)?(r.nodeName||"").toLowerCase():"#document"}function qe(r){var e;return (r==null||(e=r.ownerDocument)==null?void 0:e.defaultView)||window}function qt(r){var e;return (e=(og(r)?r.ownerDocument:r.document)||window.document)==null?void 0:e.documentElement}function og(r){return Tl()?r instanceof Node||r instanceof qe(r).Node:false}function It(r){return Tl()?r instanceof Element||r instanceof qe(r).Element:false}function mn(r){return Tl()?r instanceof HTMLElement||r instanceof qe(r).HTMLElement:false}function ig(r){return !Tl()||typeof ShadowRoot>"u"?false:r instanceof ShadowRoot||r instanceof qe(r).ShadowRoot}function Io(r){let{overflow:e,overflowX:t,overflowY:n,display:i}=At(r);return /auto|scroll|overlay|hidden|clip/.test(e+n+t)&&i!=="inline"&&i!=="contents"}function sg(r){return /^(table|td|th)$/.test(Sr(r))}function Ao(r){try{if(r.matches(":popover-open"))return !0}catch{}try{return r.matches(":modal")}catch{return false}}var pT=/transform|translate|scale|rotate|perspective|filter/,mT=/paint|layout|strict|content/,xr=r=>!!r&&r!=="none",ru;function El(r){let e=It(r)?At(r):r;return xr(e.transform)||xr(e.translate)||xr(e.scale)||xr(e.rotate)||xr(e.perspective)||!Pl()&&(xr(e.backdropFilter)||xr(e.filter))||pT.test(e.willChange||"")||mT.test(e.contain||"")}function ag(r){let e=Vn(r);for(;mn(e)&&!pi(e);){if(El(e))return e;if(Ao(e))return null;e=Vn(e);}return null}function Pl(){return ru==null&&(ru=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),ru}function pi(r){return /^(html|body|#document)$/.test(Sr(r))}function At(r){return qe(r).getComputedStyle(r)}function Ro(r){return It(r)?{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}:{scrollLeft:r.scrollX,scrollTop:r.scrollY}}function Vn(r){if(Sr(r)==="html")return r;let e=r.assignedSlot||r.parentNode||ig(r)&&r.host||qt(r);return ig(e)?e.host:e}function lg(r){let e=Vn(r);return pi(e)?(r.ownerDocument||r).body:mn(e)&&Io(e)?e:lg(e)}function hi(r,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=true);let i=lg(r),o=i===((n=r.ownerDocument)==null?void 0:n.body),s=qe(i);if(o){let a=Ll(s);return e.concat(s,s.visualViewport||[],Io(i)?i:[],a&&t?hi(a):[])}else return e.concat(i,hi(i,[],t))}function Ll(r){return r.parent&&Object.getPrototypeOf(r.parent)?r.frameElement:null}function ug(r){let e=At(r),t=parseFloat(e.width)||0,n=parseFloat(e.height)||0,i=mn(r),o=i?r.offsetWidth:t,s=i?r.offsetHeight:n,a=Mo(t)!==o||Mo(n)!==s;return a&&(t=o,n=s),{width:t,height:n,$:a}}function ou(r){return It(r)?r:r.contextElement}function mi(r){let e=ou(r);if(!mn(e))return Xt(1);let t=e.getBoundingClientRect(),{width:n,height:i,$:o}=ug(e),s=(o?Mo(t.width):t.width)/n,a=(o?Mo(t.height):t.height)/i;return (!s||!Number.isFinite(s))&&(s=1),(!a||!Number.isFinite(a))&&(a=1),{x:s,y:a}}var fT=Xt(0);function hg(r){let e=qe(r);return !Pl()||!e.visualViewport?fT:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function gT(r,e,t){return e===void 0&&(e=false),!!t&&e&&t===qe(r)}function Cr(r,e,t,n){e===void 0&&(e=false),t===void 0&&(t=false);let i=r.getBoundingClientRect(),o=ou(r),s=Xt(1);e&&(n?It(n)&&(s=mi(n)):s=mi(r));let a=gT(o,t,n)?hg(o):Xt(0),l=(i.left+a.x)/s.x,c=(i.top+a.y)/s.y,d=i.width/s.x,u=i.height/s.y;if(o&&n){let h=qe(o),p=It(n)?qe(n):n,m=h,f=Ll(m);for(;f&&p!==m;){let g=mi(f),b=f.getBoundingClientRect(),y=At(f),v=b.left+(f.clientLeft+parseFloat(y.paddingLeft))*g.x,S=b.top+(f.clientTop+parseFloat(y.paddingTop))*g.y;l*=g.x,c*=g.y,d*=g.x,u*=g.y,l+=v,c+=S,m=qe(f),f=Ll(m);}}return wr({width:d,height:u,x:l,y:c})}function Ml(r,e){let t=Ro(r).scrollLeft;return e?e.left+t:Cr(qt(r)).left+t}function pg(r,e){let t=r.getBoundingClientRect(),n=t.left+e.scrollLeft-Ml(r,t),i=t.top+e.scrollTop;return {x:n,y:i}}function bT(r){let{elements:e,rect:t,offsetParent:n,strategy:i}=r,o=i==="fixed",s=qt(n),a=e?Ao(e.floating):false;if(n===s||a&&o)return t;let l={scrollLeft:0,scrollTop:0},c=Xt(1),d=Xt(0),u=mn(n);if((u||!o)&&((Sr(n)!=="body"||Io(s))&&(l=Ro(n)),u)){let p=Cr(n);c=mi(n),d.x=p.x+n.clientLeft,d.y=p.y+n.clientTop;}let h=s&&!u&&!o?pg(s,l):Xt(0);return {width:t.width*c.x,height:t.height*c.y,x:t.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:t.y*c.y-l.scrollTop*c.y+d.y+h.y}}function vT(r){return r.getClientRects?Array.from(r.getClientRects()):[]}function yT(r){let e=Ro(r),t=r.ownerDocument.body,n=Mt(r.scrollWidth,r.clientWidth,t.scrollWidth,t.clientWidth),i=Mt(r.scrollHeight,r.clientHeight,t.scrollHeight,t.clientHeight),o=-e.scrollLeft+Ml(r),s=-e.scrollTop;return At(t).direction==="rtl"&&(o+=Mt(r.clientWidth,t.clientWidth)-n),{width:n,height:i,x:o,y:s}}var wT=25;function xT(r,e,t){t===void 0&&(t="viewport");let n=t==="layoutViewport",i=qe(r),o=qt(r),s=i.visualViewport,a=o.clientWidth,l=o.clientHeight,c=0,d=0;if(s){let h=!Pl()||e==="fixed";n?h||(c=-s.offsetLeft,d=-s.offsetTop):(a=s.width,l=s.height,h&&(c=s.offsetLeft,d=s.offsetTop));}if(Ml(o)<=0){let h=o.ownerDocument,p=h.body,m=getComputedStyle(p),f=h.compatMode==="CSS1Compat"&&parseFloat(m.marginLeft)+parseFloat(m.marginRight)||0,g=Math.abs(o.clientWidth-p.clientWidth-f),b=getComputedStyle(o).scrollbarGutter==="stable both-edges"?g/2:g;b<=wT&&(a-=b);}return {width:a,height:l,x:c,y:d}}function ST(r,e){let t=Cr(r,true,e==="fixed"),n=t.top+r.clientTop,i=t.left+r.clientLeft,o=mi(r),s=r.clientWidth*o.x,a=r.clientHeight*o.y,l=i*o.x,c=n*o.y;return {width:s,height:a,x:l,y:c}}function cg(r,e,t){let n;if(e==="viewport"||e==="layoutViewport")n=xT(r,t,e);else if(e==="document")n=yT(qt(r));else if(It(e))n=ST(e,t);else {let i=hg(r);n={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height};}return wr(n)}function CT(r,e){let t=e.get(r);if(t)return t;let n=hi(r,[],false).filter(a=>It(a)&&Sr(a)!=="body"),i=null,o=At(r).position==="fixed",s=o?Vn(r):r;for(;It(s)&&!pi(s);){let a=At(s),l=El(s),c=i?i.position:o?"fixed":"";!l&&(c==="fixed"||c==="absolute"&&a.position==="static")?n=n.filter(u=>u!==s):i=a,s=Vn(s);}return e.set(r,n),n}function TT(r){let{element:e,boundary:t,rootBoundary:n,strategy:i}=r,s=[...t==="clippingAncestors"?Ao(e)?[]:CT(e,this._c):[].concat(t),n],a=cg(e,s[0],i),l=a.top,c=a.right,d=a.bottom,u=a.left;for(let h=1;h<s.length;h++){let p=cg(e,s[h],i);l=Mt(p.top,l),c=Kt(p.right,c),d=Kt(p.bottom,d),u=Mt(p.left,u);}return {width:c-u,height:d-l,x:u,y:l}}function ET(r){let{width:e,height:t}=ug(r);return {width:e,height:t}}function PT(r,e,t){let n=mn(e),i=qt(e),o=t==="fixed",s=Cr(r,true,o,e),a={scrollLeft:0,scrollTop:0},l=Xt(0);if((n||!o)&&((Sr(e)!=="body"||Io(i))&&(a=Ro(e)),n)){let h=Cr(e,true,o,e);l.x=h.x+e.clientLeft,l.y=h.y+e.clientTop;}!n&&i&&(l.x=Ml(i));let c=i&&!n&&!o?pg(i,a):Xt(0),d=s.left+a.scrollLeft-l.x-c.x,u=s.top+a.scrollTop-l.y-c.y;return {x:d,y:u,width:s.width,height:s.height}}function iu(r){return At(r).position==="static"}function dg(r,e){if(!mn(r)||At(r).position==="fixed")return null;if(e)return e(r);let t=r.offsetParent;return qt(r)===t&&(t=t.ownerDocument.body),t}function mg(r,e){let t=qe(r);if(Ao(r))return t;if(!mn(r)){let i=Vn(r);for(;i&&!pi(i);){if(It(i)&&!iu(i))return i;i=Vn(i);}return t}let n=dg(r,e);for(;n&&sg(n)&&iu(n);)n=dg(n,e);return n&&pi(n)&&iu(n)&&!El(n)?t:n||ag(r)||t}var LT=async function(r){let e=this.getOffsetParent||mg,t=this.getDimensions,n=await t(r.floating);return {reference:PT(r.reference,await e(r.floating),r.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function MT(r){return At(r).direction==="rtl"}var kT={convertOffsetParentRelativeRectToViewportRelativeRect:bT,getDocumentElement:qt,getClippingRect:TT,getOffsetParent:mg,getElementRects:LT,getClientRects:vT,getDimensions:ET,getScale:mi,isElement:It,isRTL:MT};function fg(r,e){return r.x===e.x&&r.y===e.y&&r.width===e.width&&r.height===e.height}function IT(r,e,t){let n=null,i,o=qt(r);function s(){var d;clearTimeout(i),(d=n)==null||d.disconnect(),n=null;}function a(d,u){d===void 0&&(d=false),u===void 0&&(u=1),s();let h=r.getBoundingClientRect(),{left:p,top:m,width:f,height:g}=h;if(d||e(),!f||!g)return;let b=ko(m),y=ko(o.clientWidth-(p+f)),v=ko(o.clientHeight-(m+g)),S=ko(p),T={rootMargin:-b+"px "+-y+"px "+-v+"px "+-S+"px",threshold:Mt(0,Kt(1,u))||1},E=true;function x(L){let w=L[0].intersectionRatio;if(!fg(h,r.getBoundingClientRect()))return a();if(w!==u){if(!E)return a();w?a(false,w):i=setTimeout(()=>{a(false,1e-7);},1e3);}E=false;}try{n=new IntersectionObserver(x,{...T,root:o.ownerDocument});}catch{n=new IntersectionObserver(x,T);}n.observe(r);}let l=qe(r),c=()=>a(t);return l.addEventListener("resize",c),a(true),()=>{l.removeEventListener("resize",c),s();}}function gg(r,e,t,n){n===void 0&&(n={});let{ancestorScroll:i=true,ancestorResize:o=true,elementResize:s=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=false}=n,c=ou(r),d=i||o?[...c?hi(c):[],...e?hi(e):[]]:[];d.forEach(b=>{i&&b.addEventListener("scroll",t),o&&b.addEventListener("resize",t);});let u=c&&a?IT(c,t,o):null,h=-1,p=null;s&&(p=new ResizeObserver(b=>{let[y]=b;y&&y.target===c&&p&&e&&(p.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var v;(v=p)==null||v.observe(e);})),t();}),c&&!l&&p.observe(c),e&&p.observe(e));let m,f=l?Cr(r):null;l&&g();function g(){let b=Cr(r);f&&!fg(f,b)&&t(),f=b,m=requestAnimationFrame(g);}return t(),()=>{var b;d.forEach(y=>{i&&y.removeEventListener("scroll",t),o&&y.removeEventListener("resize",t);}),u?.(),(b=p)==null||b.disconnect(),p=null,l&&cancelAnimationFrame(m);}}var bg=eg;var vg=tg,yg=Zf,wg=rg,xg=Jf,Sg=qf;var Cg=ng,Tg=(r,e,t)=>{let n=new Map,i=t??{},o={...kT,...i.platform,_c:n};return jf(r,e,{...i,platform:o})};function Eg(r=0,e=0,t=0,n=0){if(typeof DOMRect=="function")return new DOMRect(r,e,t,n);let i={x:r,y:e,width:t,height:n,top:e,right:r+t,bottom:e+n,left:r};return {...i,toJSON:()=>i}}function AT(r){if(!r)return Eg();let{x:e,y:t,width:n,height:i}=r;return Eg(e,t,n,i)}function Pg(r,e){return {contextElement:ce(r)?r:r?.contextElement,getBoundingClientRect:()=>{let t=r,n=e?.(t);return n||!t?AT(n):t.getBoundingClientRect()}}}var Do=r=>({variable:r,reference:`var(${r})`}),Zt={arrowSize:Do("--arrow-size"),arrowSizeHalf:Do("--arrow-size-half"),arrowBg:Do("--arrow-background"),transformOrigin:Do("--transform-origin"),arrowOffset:Do("--arrow-offset")},RT=r=>r==="top"||r==="bottom"?"y":"x";function Lg(r,e){return {name:"transformOrigin",fn(t){let{elements:n,middlewareData:i,placement:o,rects:s,y:a}=t,l=o.split("-")[0],c=RT(l),d=i.arrow?.x||0,u=i.arrow?.y||0,h=e?.clientWidth||0,p=e?.clientHeight||0,m=d+h/2,f=u+p/2,g=Math.abs(i.shift?.y||0),b=s.reference.height/2,y=p/2,v=r.offset?.mainAxis??r.gutter,S=typeof v=="number"?v+y:v??y,P=g>S,T={top:`${m}px calc(100% + ${S}px)`,bottom:`${m}px ${-S}px`,left:`calc(100% + ${S}px) ${f}px`,right:`${-S}px ${f}px`}[l],E=`${m}px ${s.reference.y+b-a}px`,x=!!r.overlap&&c==="y"&&P;return n.floating.style.setProperty(Zt.transformOrigin.variable,x?E:T),{data:{transformOrigin:x?E:T}}}}}var Mg={name:"rects",fn({rects:r}){return {data:r}}},kg=r=>{if(r)return {name:"shiftArrow",fn({placement:e,middlewareData:t}){if(!t.arrow)return {};let{x:n,y:i}=t.arrow,o=e.split("-")[0];return Object.assign(r.style,{left:n!=null?`${n}px`:"",top:i!=null?`${i}px`:"",[o]:`calc(100% + ${Zt.arrowOffset.reference})`}),{}}}};function Ig(r){let[e,t]=r.split("-");return {side:e,align:t,hasAlign:t!=null}}function Oo(r){return r.split("-")[0]}var DT={strategy:"absolute",placement:"bottom",listeners:true,restoreStyles:false,gutter:8,flip:true,slide:true,overlap:false,sameWidth:false,fitViewport:false,overflowPadding:8,arrowPadding:4};function Ag(r,e){let t=r.devicePixelRatio||1;return Math.round(e*t)/t}function fi(r,e){return r!=null&&Math.abs(r-e)<.5}function kl(r){return typeof r=="function"?r():r==="clipping-ancestors"?"clippingAncestors":r}function OT(r,e,t){let n=r||e.createElement("div");return Sg({element:n,padding:t.arrowPadding})}function NT(r,e){if(!Dm(e.offset??e.gutter))return bg(({placement:t})=>{let n=(r?.clientHeight||0)/2,i=e.offset?.mainAxis??e.gutter,o=typeof i=="number"?i+n:i??n,{hasAlign:s}=Ig(t),a=s?void 0:e.shift,l=e.offset?.crossAxis??a;return On({crossAxis:l,mainAxis:o,alignmentAxis:e.shift})})}function FT(r){if(r.flip)return yg(()=>{let e=kl(r.boundary);return {...e?{boundary:e}:void 0,padding:r.overflowPadding,fallbackPlacements:r.flip===true?void 0:r.flip}})}function VT(r){if(!(!r.slide&&!r.overlap))return vg(()=>{let e=kl(r.boundary);return {...e?{boundary:e}:void 0,mainAxis:r.slide,crossAxis:r.overlap,padding:r.overflowPadding,limiter:Cg()}})}function _T(r){if(r.sizeMiddleware===false&&!r.sameWidth&&!r.fitViewport)return;let e,t,n,i;return wg(()=>{let o=kl(r.boundary);return {padding:r.overflowPadding,...o?{boundary:o}:void 0,apply({elements:s,rects:a,availableHeight:l,availableWidth:c}){let d=s.floating,u=Math.round(a.reference.width),h=Math.round(a.reference.height);c=Math.floor(c),l=Math.floor(l),fi(e,u)||(d.style.setProperty("--reference-width",`${u}px`),e=u),fi(t,h)||(d.style.setProperty("--reference-height",`${h}px`),t=h),fi(n,c)||(d.style.setProperty("--available-width",`${c}px`),n=c),fi(i,l)||(d.style.setProperty("--available-height",`${l}px`),i=l);}}})}function BT(r){if(r.hideWhenDetached)return xg(()=>({strategy:"referenceHidden",boundary:kl(r.boundary)??"clippingAncestors"}))}function HT(r){return r?r===true?{ancestorResize:true,ancestorScroll:true,elementResize:true,layoutShift:true}:r:{}}var zT=["transform","visibility","pointer-events","--x","--y","--z-index","--reference-width","--reference-height","--available-width","--available-height","--transform-origin"],$T=["top","right","bottom","left"];function Rg(r,e){if(!r)return Id;let t=new Map(e.map(n=>[n,r.style.getPropertyValue(n)]));return ()=>{t.forEach((n,i)=>{n?r.style.setProperty(i,n):r.style.removeProperty(i);}),r.style.length===0&&r.removeAttribute("style");}}function Dg(r){return r==null?null:ce(r)?r:typeof r=="object"&&r&&"contextElement"in r&&r.contextElement?r.contextElement:r}function WT(r,e,t={}){let n=()=>(typeof e=="function"?e():e)??null,i=()=>{let w=typeof r=="function"?r():r;return t.getAnchorElement?.()??w},o=()=>{let w=i();return !w&&!t.getAnchorRect?null:Pg(w,t.getAnchorRect)},s=Object.assign({},DT,t),a=[],l=null,c,d;function u(w){c?.(),d?.(),l=w,c=s.restoreStyles?Rg(w,zT):void 0;let M=w.querySelector("[data-part=arrow]");d=s.restoreStyles?Rg(M,$T):void 0,a=[NT(M,s),FT(s),VT(s),OT(M,w.ownerDocument,s),kg(M),Lg({gutter:s.gutter,offset:s.offset,overlap:s.overlap},M),_T(s),BT(s),Mg];}let{placement:h,strategy:p,onComplete:m,onPositioned:f}=s,g,b,y=false,v,S,P=Id,T=HT(s.listeners);function E(){if(!s.listeners)return;let w=i(),M=o(),k=n();if(!M||!k)return;(Dg(w)!==Dg(v)||k!==S)&&(P(),v=w,S=k,P=gg(M,k,L,T));}async function x(){E();let w=n();if(!w)return;w!==l&&(u(w),y=false);let M=o();if(!M)return;let k=await Tg(M,w,{placement:h,middleware:a,strategy:p});m?.(k);let C=Se(w),A=Ag(C,k.x),$=Ag(C,k.y);if(fi(g,A)||(w.style.setProperty("--x",`${A}px`),g=A),fi(b,$)||(w.style.setProperty("--y",`${$}px`),b=$),s.hideWhenDetached&&(k.middlewareData.hide?.referenceHidden?(w.style.setProperty("visibility","hidden"),w.style.setProperty("pointer-events","none")):(w.style.removeProperty("visibility"),w.style.removeProperty("pointer-events"))),!y){let ie=w.firstElementChild;ie&&(w.style.setProperty("--z-index",ri(ie).zIndex),y=true);}}async function L(){t.updatePosition?(await t.updatePosition({updatePosition:x,floatingElement:n()}),f?.({placed:true})):await x();}return L(),()=>{P(),d?.(),c?.(),f?.({placed:false});}}function Il(r,e,t={}){let{defer:n,...i}=t,o=n?Me:a=>a(),s=[];return s.push(o(()=>{s.push(WT(r,e,i));})),()=>{s.forEach(a=>a?.());}}var GT={bottom:"rotate(45deg)",left:"rotate(135deg)",top:"rotate(225deg)",right:"rotate(315deg)"};function su(r={}){let{placement:e,sameWidth:t,fitViewport:n,strategy:i="absolute"}=r;return {arrow:{position:"absolute",width:Zt.arrowSize.reference,height:Zt.arrowSize.reference,[Zt.arrowSizeHalf.variable]:`calc(${Zt.arrowSize.reference} / 2)`,[Zt.arrowOffset.variable]:`calc(${Zt.arrowSizeHalf.reference} * -1)`},arrowTip:{transform:e?GT[e.split("-")[0]]:void 0,background:Zt.arrowBg.reference,top:"0",left:"0",width:"100%",height:"100%",position:"absolute",zIndex:"inherit"},floating:{position:i,isolation:"isolate",minWidth:t?void 0:"max-content",width:t?"var(--reference-width)":void 0,maxWidth:n?"var(--available-width)":void 0,maxHeight:n?"var(--available-height)":void 0,pointerEvents:e?void 0:"none",top:"0px",left:"0px",transform:e?"translate3d(var(--x), var(--y), 0)":"translate3d(0, -100vh, 0)",zIndex:"var(--z-index)"}}}var Jt=(r,e)=>{let t=r.ids?.trigger;return t!=null?nt(t)?t(e):t:e?`menu:${r.id}:trigger:${e}`:`menu:${r.id}:trigger`},Al=(r,e)=>{let t=r.ids?.contextTrigger;return t!=null?nt(t)?t(e):t:e?`menu:${r.id}:ctx-trigger:${e}`:`menu:${r.id}:ctx-trigger`},_n=r=>r.ids?.content??`menu:${r.id}:content`,Og=r=>r.ids?.arrow??`menu:${r.id}:arrow`,au=r=>r.ids?.positioner??`menu:${r.id}:popper`,Ng=(r,e)=>r.ids?.group?.(e)??`menu:${r.id}:group:${e}`,Tr=(r,e)=>`${r.id}/${e}`,Bn=r=>r?.dataset.value??null,lu=(r,e)=>r.ids?.groupLabel?.(e)??`menu:${r.id}:group-label:${e}`,Rt=r=>r.getById(_n(r)),cu=r=>r.getById(au(r)),du=r=>r.getById(Jt(r)),Fg=(r,e)=>e?r.getById(Tr(r,e)):null;var Vg=r=>r.getById(Al(r)),uu=r=>li(r.getRootNode(),`[data-scope="menu"][data-part="trigger"][data-ownedby="${r.id}"]`),hu=r=>li(r.getRootNode(),`[data-scope="menu"][data-part="context-trigger"][data-ownedby="${r.id}"]`),No=(r,e)=>e==null?du(r)??uu(r)[0]:r.getById(Jt(r,e)),Fo=r=>{let t=`[role^="menuitem"][data-ownedby=${CSS.escape(_n(r))}]:not([data-disabled])`;return li(Rt(r),t)},_g=r=>Lm(Fo(r)),Bg=r=>Mm(Fo(r)),pu=(r,e)=>e?r.id===e||r.dataset.value===e:false,Hg=(r,e)=>{let t=Fo(r),n=t.findIndex(i=>pu(i,e.value));return Im(t,n,{loop:e.loop??e.loopFocus})},zg=(r,e)=>{let t=Fo(r),n=t.findIndex(i=>pu(i,e.value));return Am(t,n,{loop:e.loop??e.loopFocus})},$g=(r,e)=>{let t=Fo(r),n=t.find(i=>pu(i,e.value));return hl(t,{state:e.typeaheadState,key:e.key,activeId:n?.id??null})},Vo=r=>ce(r)&&(r.dataset.disabled===""||r.hasAttribute("disabled")),mu=r=>!!r?.getAttribute("role")?.startsWith("menuitem")&&!!r?.hasAttribute("data-controls");var Rl="menu:select";function Wg(r,e){if(!r)return;let t=Se(r),n=new t.CustomEvent(Rl,{detail:{value:e}});r.dispatchEvent(n);}function UT(r){let e=_n(r);return Rt(r)??r.getDoc().getElementById(e)}function fu(r,e){if(!ce(r))return false;for(let t in e){let n=e[t],i=UT(n.scope);if(i&&rt(i,r))return true;let o=n.refs.get("children");if(Object.keys(o).length>0&&fu(r,o))return true}return false}var _o=(r,e)=>({x:r,y:e});function Gg(r){let{x:e,y:t,width:n,height:i}=r,o=e+n/2,s=t+i/2;return {x:e,y:t,width:n,height:i,minX:e,minY:t,maxX:e+n,maxY:t+i,midX:o,midY:s,center:_o(o,s)}}function Ug(r){let e=_o(r.minX,r.minY),t=_o(r.maxX,r.minY),n=_o(r.maxX,r.maxY),i=_o(r.minX,r.maxY);return {top:e,right:t,bottom:n,left:i}}function Yg(r,e){let t=Gg(r),{top:n,right:i,left:o,bottom:s}=Ug(t),[a]=e.split("-");return {top:[o,n,i,s],right:[n,i,s,o],bottom:[n,o,s,i],left:[i,n,o,s]}[a]}function Dl(r,e){let{x:t,y:n}=e,i=false;for(let o=0,s=r.length-1;o<r.length;s=o++){let a=r[o].x,l=r[o].y,c=r[s].x,d=r[s].y;l>n!=d>n&&t<(c-a)*(n-l)/(d-l)+a&&(i=!i);}return i}function bu(r){let e=r.parent;for(;e&&e.context.get("isSubmenu");)e=e.refs.get("parent");e?.send({type:"CLOSE"});}function Kg(r,e){return r?Dl(r,e):false}function Xg(r,e,t){let n=Object.keys(r).length>0;if(!e)return null;if(!n)return Tr(t,e);for(let i in r){let o=r[i],s=Jt(o.scope);if(s===e)return s}return Tr(t,e)}function Hn(r,e){r&&(r.refs.set("pointerRoutingLocked",e),r.context.set("pointerRoutingMode",e?"locked":"interactive"));}function jg(r){let e=r.context.get("highlightedValue");if(!e)return false;let t=r.refs.get("children");for(let n in t){let i=t[n];if(i.state.hasTag("open")&&Jt(i.scope)===e)return true}return false}function qg(r,e){r&&(r.refs.get("pointerRoutingLocked")||e&&jg(r)||Hn(r,false));}function Zg(r){r&&(jg(r)||Hn(r,false));}function vu(r,e){let{context:t,send:n,state:i,computed:o,prop:s,scope:a}=r,l=i.hasTag("open"),c=t.get("isSubmenu"),d=o("isTypingAhead"),u=s("composite"),h=t.get("currentPlacement"),p=h?Oo(h):void 0,m=t.get("anchorPoint"),f=t.get("highlightedValue"),g=t.get("triggerValue"),b=su({...s("positioning"),placement:h});function y(T){return {id:Tr(a,T.value),disabled:!!T.disabled,highlighted:f===T.value}}function v(T){let E=T.valueText??T.value;return {...T,id:T.value,valueText:E}}function S(T){return {...y(v(T)),checked:!!T.checked}}function P(T){let{closeOnSelect:E,valueText:x,value:L}=T,w=y(T),M=Tr(a,L);return e.element({...ze.item.attrs,id:M,role:"menuitem","aria-disabled":Fd(w.disabled),"data-disabled":mt(w.disabled),"data-ownedby":_n(a),"data-highlighted":mt(w.highlighted),"data-value":L,"data-valuetext":x,onDragStart(k){k.currentTarget.matches("a[href]")&&k.preventDefault();},onPointerMove(k){if(w.disabled||k.pointerType!=="mouse")return;let C=k.currentTarget;if(w.highlighted)return;let A=oi(k);n({type:"ITEM_POINTERMOVE",id:M,target:C,closeOnSelect:E,point:A});},onPointerLeave(k){if(w.disabled||k.pointerType!=="mouse"||!r.event.previous()?.type.includes("POINTER"))return;let A=k.currentTarget;n({type:"ITEM_POINTERLEAVE",id:M,target:A,closeOnSelect:E});},onPointerDown(k){if(w.disabled)return;let C=k.currentTarget;n({type:"ITEM_POINTERDOWN",target:C,id:M,closeOnSelect:E});},onClick(k){if(Ud(k)||Gd(k)||w.disabled)return;let C=k.currentTarget;n({type:"ITEM_CLICK",target:C,id:M,closeOnSelect:E});}})}return {highlightedValue:f,open:l,setOpen(T){i.hasTag("open")!==T&&n({type:T?"OPEN":"CLOSE"});},triggerValue:g,setTriggerValue(T){n({type:"TRIGGER_VALUE.SET",value:T});},setHighlightedValue(T){n({type:"HIGHLIGHTED.SET",value:T});},setParent(T){n({type:"PARENT.SET",value:T,id:T.prop("id")});},setChild(T){n({type:"CHILD.SET",value:T,id:T.prop("id")});},reposition(T={}){n({type:"POSITIONING.SET",options:T});},addItemListener(T){let E=a.getById(T.id);if(!E)return;let x=()=>T.onSelect?.();return E.addEventListener(Rl,x),()=>E.removeEventListener(Rl,x)},getContextTriggerProps(T={}){let{value:E}=T,x=E==null?false:g===E,L=Al(a,E);return e.element({...ze.contextTrigger.attrs,dir:s("dir"),id:L,"data-ownedby":a.id,"data-value":E,"data-current":mt(x),"data-state":l?"open":"closed",onPointerDown(w){if(w.pointerType==="mouse")return;let M=oi(w);n({type:"CONTEXT_MENU_START",point:M,value:E});},onPointerCancel(w){w.pointerType!=="mouse"&&n({type:"CONTEXT_MENU_CANCEL"});},onPointerMove(w){w.pointerType!=="mouse"&&n({type:"CONTEXT_MENU_CANCEL"});},onPointerUp(w){w.pointerType!=="mouse"&&n({type:"CONTEXT_MENU_CANCEL"});},onContextMenu(w){let M=oi(w),k=l&&E!=null&&!x;n({type:k?"TRIGGER_VALUE.SET":"CONTEXT_MENU",point:M,value:E}),w.preventDefault();},style:{WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"}})},getTriggerItemProps(T){let E=T.getTriggerProps();return Vm(P({value:E.id}),E)},getTriggerProps(T={}){let{value:E}=T,x=E==null?false:g===E,L=Jt(a,E);return e.button({...c?ze.triggerItem.attrs:ze.trigger.attrs,"data-placement":h,"data-side":p,type:"button",dir:s("dir"),id:L,...E!=null&&{"data-ownedby":a.id,"data-value":E,"data-current":mt(x)},"data-uid":s("id"),"aria-haspopup":u?"menu":"dialog","aria-controls":_n(a),"data-controls":_n(a),"aria-expanded":E==null?l:l&&x,"data-state":l?"open":"closed",onPointerMove(w){if(w.pointerType!=="mouse"||Vo(w.currentTarget)||!c)return;let k=oi(w);n({type:"TRIGGER_POINTERMOVE",target:w.currentTarget,point:k});},onPointerLeave(w){if(Vo(w.currentTarget)||w.pointerType!=="mouse"||!c)return;Hn(r.refs.get("parent"),true);let M=oi(w);n({type:"TRIGGER_POINTERLEAVE",target:w.currentTarget,point:M});},onPointerDown(w){Vo(w.currentTarget)||al(w)||w.preventDefault();},onClick(w){if(w.defaultPrevented||Vo(w.currentTarget))return;let M=l&&E!=null&&!x;n({type:M?"TRIGGER_VALUE.SET":"TRIGGER_CLICK",target:w.currentTarget,value:E});},onBlur(){n({type:"TRIGGER_BLUR"});},onFocus(){n({type:"TRIGGER_FOCUS"});},onKeyDown(w){if(w.defaultPrevented)return;let M={ArrowDown(){n({type:"ARROW_DOWN",value:E});},ArrowUp(){n({type:"ARROW_UP",value:E});},Enter(){n({type:"ARROW_DOWN",src:"enter",value:E});},Space(){n({type:"ARROW_DOWN",src:"space",value:E});}},k=Yd(w,{orientation:"vertical",dir:s("dir")}),C=M[k];C&&(w.preventDefault(),C(w));}})},getIndicatorProps(){return e.element({...ze.indicator.attrs,dir:s("dir"),"data-state":l?"open":"closed"})},getPositionerProps(){return e.element({...ze.positioner.attrs,dir:s("dir"),id:au(a),style:b.floating})},getArrowProps(){return e.element({id:Og(a),...ze.arrow.attrs,dir:s("dir"),style:b.arrow})},getArrowTipProps(){return e.element({...ze.arrowTip.attrs,dir:s("dir"),style:b.arrowTip})},getContentProps(){return e.element({...ze.content.attrs,id:_n(a),"aria-label":s("aria-label"),hidden:!l,"data-state":l?"open":"closed",role:u?"menu":"dialog",tabIndex:0,dir:s("dir"),"aria-activedescendant":o("highlightedId")||void 0,"aria-labelledby":m?Al(a,g??void 0):Jt(a,g??void 0),"data-placement":h,"data-side":p,onPointerEnter(T){T.pointerType==="mouse"&&n({type:"MENU_POINTERENTER"});},onKeyDown(T){if(T.defaultPrevented||!rt(T.currentTarget,Re(T)))return;let E=Re(T);if(!(E?.closest("[role=menu]")===T.currentTarget||E===T.currentTarget))return;if(T.key==="Tab"&&!vf(T)){T.preventDefault();return}let L={ArrowDown(){n({type:"ARROW_DOWN"});},ArrowUp(){n({type:"ARROW_UP"});},ArrowLeft(){n({type:"ARROW_LEFT"});},ArrowRight(){n({type:"ARROW_RIGHT"});},Enter(){n({type:"ENTER"});},Space(k){d?n({type:"TYPEAHEAD",key:k.key}):L.Enter?.(k);},Home(){n({type:"HOME"});},End(){n({type:"END"});}},w=Yd(T,{dir:s("dir")}),M=L[w];if(M){M(T),T.stopPropagation(),T.preventDefault();return}s("typeahead")&&uf(T)&&(pf(T)||ni(E)||(n({type:"TYPEAHEAD",key:T.key}),T.preventDefault()));}})},getSeparatorProps(){return e.element({...ze.separator.attrs,role:"separator",dir:s("dir"),"aria-orientation":"horizontal"})},getItemState:y,getItemProps:P,getOptionItemState:S,getOptionItemProps(T){let{type:E,disabled:x,closeOnSelect:L}=T,w=v(T),M=S(T);return {...P(w),...e.element({"data-type":E,...ze.item.attrs,dir:s("dir"),"data-value":w.value,role:`menuitem${E}`,"aria-checked":!!M.checked,"data-state":M.checked?"checked":"unchecked",onClick(k){if(x||Ud(k)||Gd(k))return;let C=k.currentTarget;n({type:"ITEM_CLICK",target:C,option:w,closeOnSelect:L});}})}},getItemIndicatorProps(T){let E=S(kd(T)),x=E.checked?"checked":"unchecked";return e.element({...ze.itemIndicator.attrs,dir:s("dir"),"data-disabled":mt(E.disabled),"data-highlighted":mt(E.highlighted),"data-state":fo(T,"checked")?x:void 0,hidden:fo(T,"checked")?!E.checked:void 0})},getItemTextProps(T){let E=S(kd(T)),x=E.checked?"checked":"unchecked";return e.element({...ze.itemText.attrs,dir:s("dir"),"data-disabled":mt(E.disabled),"data-highlighted":mt(E.highlighted),"data-state":fo(T,"checked")?x:void 0})},getItemGroupLabelProps(T){return e.element({...ze.itemGroupLabel.attrs,id:lu(a,T.htmlFor),dir:s("dir")})},getItemGroupProps(T){return e.element({id:Ng(a,T.id),...ze.itemGroup.attrs,dir:s("dir"),"aria-labelledby":lu(a,T.id),role:"group"})}}}function Jg(r){let e={each(t){for(let n=0;n<r.frames?.length;n+=1){let i=r.frames[n];i&&t(i);}},addEventListener(t,n,i){return e.each(o=>{try{o.document.addEventListener(t,n,i);}catch{}}),()=>{try{e.removeEventListener(t,n,i);}catch{}}},removeEventListener(t,n,i){e.each(o=>{try{o.document.removeEventListener(t,n,i);}catch{}});}};return e}function Qg(r){let e=r.frameElement!=null?r.parent:null;return {addEventListener:(t,n,i)=>{try{e?.addEventListener(t,n,i);}catch{}return ()=>{try{e?.removeEventListener(t,n,i);}catch{}}},removeEventListener:(t,n,i)=>{try{e?.removeEventListener(t,n,i);}catch{}}}}var eb="pointerdown.outside",tb="focus.outside";function YT(r){for(let e of r)if(ce(e)&&ft(e))return true;return false}var ib=r=>"clientY"in r;function KT(r,e){if(!ib(e)||!r)return false;let t=r.getBoundingClientRect();return t.width===0||t.height===0?false:t.top<=e.clientY&&e.clientY<=t.top+t.height&&t.left<=e.clientX&&e.clientX<=t.left+t.width}function XT(r,e){return r.y<=e.y&&e.y<=r.y+r.height&&r.x<=e.x&&e.x<=r.x+r.width}function nb(r,e){if(!e||!ib(r))return false;let t=e.scrollHeight>e.clientHeight,n=t&&r.clientX>e.offsetLeft+e.clientWidth,i=e.scrollWidth>e.clientWidth,o=i&&r.clientY>e.offsetTop+e.clientHeight,s={x:e.offsetLeft,y:e.offsetTop,width:e.clientWidth+(t?16:0),height:e.clientHeight+(i?16:0)},a={x:r.clientX,y:r.clientY};return XT(s,a)?n||o:false}function jT(r,e){let{exclude:t,onFocusOutside:n,onPointerDownOutside:i,onInteractOutside:o,defer:s,followControlledElements:a=true}=e;if(!r)return;let l=Pe(r),c=Se(r),d=Jg(c),u=Qg(c);function h(S,P){if(!ce(P)||!P.isConnected||rt(r,P)||KT(r,S)||a&&sl(r,P))return false;let T=l.querySelector(`[aria-controls="${r.id}"]`);if(T){let x=dl(T);if(nb(S,x))return false}let E=dl(r);return nb(S,E)?false:!t?.(P)}let p=new Set,m=gr(r?.getRootNode()),f=false;function g(S){f=true;let P=()=>{f=false;};l.addEventListener("pointerup",P,{once:true}),c.addEventListener("pointerup",P,{once:true});function T(E){let x=s&&!Wd()?Me:M=>M(),L=E??S,w=L?.composedPath?.()??[L?.target];x(()=>{let M=m?w[0]:Re(S);if(!(!r||!h(S,M))){if(i||o){let k=Dn(i,o);r.addEventListener(eb,k,{once:true});}rb(r,eb,{bubbles:false,cancelable:true,detail:{originalEvent:L,contextmenu:al(L),focusable:YT(w),target:M}});}});}S.pointerType==="touch"?(p.forEach(E=>E()),p.add(Xe(l,"click",T,{once:true})),p.add(u.addEventListener("click",T,{once:true})),p.add(d.addEventListener("click",T,{once:true}))):T();}let b=new Set,y=setTimeout(()=>{b.add(Xe(l,"pointerdown",g,true)),b.add(u.addEventListener("pointerdown",g,true)),b.add(d.addEventListener("pointerdown",g,true));},0);function v(S){if(f)return;(s?Me:T=>T())(()=>{let T=S?.composedPath?.()??[S?.target],E=m?T[0]:Re(S);if(!(!r||!h(S,E))){if(n||o){let x=Dn(n,o);r.addEventListener(tb,x,{once:true});}rb(r,tb,{bubbles:false,cancelable:true,detail:{originalEvent:S,contextmenu:false,focusable:ft(E),target:E}});}});}return Wd()||(b.add(Xe(l,"focusin",v,true)),b.add(u.addEventListener("focusin",v,true)),b.add(d.addEventListener("focusin",v,true))),()=>{clearTimeout(y),p.forEach(S=>S()),b.forEach(S=>S());}}function ob(r,e){let{defer:t}=e,n=t?Me:o=>o(),i=[];return i.push(n(()=>{let o=typeof r=="function"?r():r;i.push(jT(o,e));})),()=>{i.forEach(o=>o?.());}}function rb(r,e,t){let n=r.ownerDocument.defaultView||window,i=new n.CustomEvent(e,t);return r.dispatchEvent(i)}function sb(r,e){let t=n=>{n.key==="Escape"&&(n.isComposing||e?.(n));};return Xe(Pe(r),"keydown",t,{capture:true})}var ab="layer:request-dismiss",$e={layers:[],branches:[],recentlyRemoved:new Set,count(){return this.layers.length},pointerBlockingLayers(){return this.layers.filter(r=>r.pointerBlocking)},topMostPointerBlockingLayer(){return [...this.pointerBlockingLayers()].slice(-1)[0]},hasPointerBlockingLayer(){return this.pointerBlockingLayers().length>0},isBelowPointerBlockingLayer(r){let e=this.indexOf(r),t=this.topMostPointerBlockingLayer()?this.indexOf(this.topMostPointerBlockingLayer()?.node):-1;return e<t},isTopMost(r){return this.layers[this.count()-1]?.node===r},getNestedLayers(r){return Array.from(this.layers).slice(this.indexOf(r)+1)},getLayersByType(r){return this.layers.filter(e=>e.type===r)},getNestedLayersByType(r,e){let t=this.indexOf(r);return t===-1?[]:this.layers.slice(t+1).filter(n=>n.type===e)},getParentLayerOfType(r,e){let t=this.indexOf(r);if(!(t<=0))return this.layers.slice(0,t).reverse().find(n=>n.type===e)},countNestedLayersOfType(r,e){return this.getNestedLayersByType(r,e).length},isInNestedLayer(r,e){return !!(this.getNestedLayers(r).some(n=>rt(n.node,e))||this.recentlyRemoved.size>0)},isInBranch(r){return Array.from(this.branches).some(e=>rt(e,r))},add(r){let e=this.indexOf(r.node);e!==-1&&this.layers.splice(e,1),this.layers.push(r),this.syncLayers();},addBranch(r){this.branches.push(r);},remove(r){let e=this.indexOf(r);if(e<0)return;this.layers[e].styleTargets?.forEach(n=>{let i=n();i&&qT(i);}),this.recentlyRemoved.add(r),wf(()=>this.recentlyRemoved.delete(r)),e<this.count()-1&&this.getNestedLayers(r).forEach(i=>$e.dismiss(i.node,r)),this.layers.splice(e,1),this.syncLayers();},removeBranch(r){let e=this.branches.indexOf(r);e>=0&&this.branches.splice(e,1);},syncLayers(){this.layers.forEach((r,e)=>{lb(r,e,r.node),r.styleTargets?.forEach(t=>{let n=t();if(!n||n===r.node)return;lb(r,e,n);let{zIndex:i}=ri(r.node);n.style.setProperty("--z-index",i);});});},indexOf(r){return this.layers.findIndex(e=>e.node===r)},dismiss(r,e){let t=this.indexOf(r);if(t===-1)return;let n=this.layers[t];JT(r,ab,i=>{n.requestDismiss?.(i),i.defaultPrevented||n?.dismiss();}),ZT(r,ab,{originalLayer:r,targetLayer:e,originalIndex:t,targetIndex:e?this.indexOf(e):-1}),this.syncLayers();},clear(){this.remove(this.layers[0].node);}};function lb(r,e,t){t.style.setProperty("--layer-index",`${e}`),t.removeAttribute("data-nested"),t.removeAttribute("data-has-nested"),$e.getParentLayerOfType(r.node,r.type)&&t.setAttribute("data-nested",r.type);let i=$e.countNestedLayersOfType(r.node,r.type);i>0&&t.setAttribute("data-has-nested",r.type),t.style.setProperty("--nested-layer-count",`${i}`);}function qT(r){r.style.removeProperty("--layer-index"),r.style.removeProperty("--nested-layer-count"),r.style.removeProperty("--z-index"),r.removeAttribute("data-nested"),r.removeAttribute("data-has-nested");}function ZT(r,e,t){let n=r.ownerDocument.defaultView||window,i=new n.CustomEvent(e,{cancelable:true,bubbles:true,detail:t});return r.dispatchEvent(i)}function JT(r,e,t){r.addEventListener(e,t,{once:true});}var yu=new WeakMap,Bo=new WeakMap;function QT(r){return $e.isBelowPointerBlockingLayer(r)?"none":"auto"}function cb(r){let e=QT(r);r.style.pointerEvents!==e&&(r.style.pointerEvents=e);}function eE(r){if(Bo.has(r))return;let e=Se(r);if(typeof e.MutationObserver>"u")return;let t=new e.MutationObserver(()=>{Bo.has(r)&&cb(r);});t.observe(r,{attributes:true,attributeFilter:["style"]}),Bo.set(r,t);}function wu(){$e.layers.forEach(({node:r})=>{cb(r),eE(r);});}function db(r){let e=Bo.get(r);e&&(e.disconnect(),Bo.delete(r)),r.style.pointerEvents="";}function ub(r,e){let t=Pe(r),n=[];return $e.hasPointerBlockingLayer()&&!t.body.hasAttribute("data-inert")&&(yu.set(t.body,t.body.style.pointerEvents),queueMicrotask(()=>{let i=t.body;i&&(i.style.pointerEvents="none",i.setAttribute("data-inert",""));})),e?.forEach(i=>{let[o,s]=Mf(()=>{let a=i();return ce(a)?a:null},{timeout:1e3});o.then(a=>n.push(To(a,{pointerEvents:"auto"}))),n.push(s);}),()=>{$e.hasPointerBlockingLayer()||(queueMicrotask(()=>{let i=t.body;if(!i)return;let o=yu.get(i);o!==void 0&&(i.style.pointerEvents=o,yu.delete(i)),i.removeAttribute("data-inert"),i.style.length===0&&i.removeAttribute("style");}),n.forEach(i=>i()));}}function tE(r,e){let{warnOnMissingNode:t=true}=e;if(t&&!r){Qr("[@zag-js/dismissable] node is `null` or `undefined`");return}if(!r)return;let{onDismiss:n,onRequestDismiss:i,pointerBlocking:o,exclude:s,debug:a,type:l="dialog",layerStyleTargets:c}=e,d={dismiss:n,node:r,type:l,pointerBlocking:o,requestDismiss:i,styleTargets:c};$e.add(d),wu();function u(g){let b=Re(g.detail.originalEvent);$e.isBelowPointerBlockingLayer(r)||$e.isInBranch(b)||(e.onPointerDownOutside?.(g),e.onInteractOutside?.(g),!g.defaultPrevented&&(a&&console.log("onPointerDownOutside:",g.detail.originalEvent),n?.()));}function h(g){let b=Re(g.detail.originalEvent);$e.isInBranch(b)||(e.onFocusOutside?.(g),e.onInteractOutside?.(g),!g.defaultPrevented&&(a&&console.log("onFocusOutside:",g.detail.originalEvent),n?.()));}function p(g){$e.isTopMost(r)&&(e.onEscapeKeyDown?.(g),!g.defaultPrevented&&n&&(g.preventDefault(),n()));}function m(g){if(!r)return false;let b=typeof s=="function"?s():s,y=Array.isArray(b)?b:[b],v=e.persistentElements?.map(S=>S()).filter(ce);return v&&y.push(...v),y.some(S=>rt(S,g))||$e.isInNestedLayer(r,g)}let f=[o?ub(r,e.persistentElements):void 0,sb(r,p),ob(r,{exclude:m,onFocusOutside:h,onPointerDownOutside:u,defer:e.defer})];return ()=>{$e.remove(r),wu(),db(r),f.forEach(g=>g?.());}}function Ol(r,e){let{defer:t}=e,n=t?Me:o=>o(),i=[];return i.push(n(()=>{let o=nt(r)?r():r;i.push(tE(o,e));})),()=>{i.forEach(o=>o?.());}}function nE(r){return !(r.metaKey||!ii()&&r.altKey||r.ctrlKey||r.key==="Control"||r.key==="Shift"||r.key==="Meta")}var rE=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function iE(r,e,t){let n=t?Re(t):null,i=Pe(n),o=Se(n),s=Yt(i);return r=r||s instanceof o.HTMLInputElement&&!rE.has(s?.type)||s instanceof o.HTMLTextAreaElement||s instanceof o.HTMLElement&&s.isContentEditable,!(r&&e==="keyboard"&&t instanceof o.KeyboardEvent&&!Reflect.has(oE,t.key))}var fn=null,xu=new Set,Nl=new Map,Er=false,Su=false,pb=false,oE={Tab:true,Escape:true};function Vl(r,e){for(let t of xu)t(r,e);}function Fl(r){Er=true,nE(r)&&(fn="keyboard",Vl("keyboard",r));}function gt(r){fn="pointer",(r.type==="mousedown"||r.type==="pointerdown")&&(Er=true,Vl("pointer",r));}function mb(r){hf(r)&&(Er=true,fn="virtual");}function fb(r){let e=Re(r);e===Se(e)||e===Pe(e)||pb||!r.isTrusted||(!Er&&!Su&&(fn="virtual",Vl("virtual",r)),Er=false,Su=false);}function gb(){(Er=false,Su=true);}function sE(r){if(typeof window>"u"||Nl.get(Se(r)))return;let e=Se(r),t=Pe(r),n=e.HTMLElement.prototype.focus;function i(){Er=true,n.apply(this,arguments);}try{Object.defineProperty(e.HTMLElement.prototype,"focus",{configurable:!0,value:i});}catch{}t.addEventListener("keydown",Fl,true),t.addEventListener("keyup",Fl,true),t.addEventListener("click",mb,true),e.addEventListener("focus",fb,true),e.addEventListener("blur",gb,false),typeof e.PointerEvent<"u"?(t.addEventListener("pointerdown",gt,true),t.addEventListener("pointermove",gt,true),t.addEventListener("pointerup",gt,true)):(t.addEventListener("mousedown",gt,true),t.addEventListener("mousemove",gt,true),t.addEventListener("mouseup",gt,true)),e.addEventListener("beforeunload",()=>{aE(r);},{once:true}),Nl.set(e,{focus:n});}var aE=(r,e)=>{let t=Se(r),n=Pe(r);let i=Nl.get(t);if(i){try{Object.defineProperty(t.HTMLElement.prototype,"focus",{configurable:!0,value:i.focus});}catch{}n.removeEventListener("keydown",Fl,true),n.removeEventListener("keyup",Fl,true),n.removeEventListener("click",mb,true),t.removeEventListener("focus",fb,true),t.removeEventListener("blur",gb,false),typeof t.PointerEvent<"u"?(n.removeEventListener("pointerdown",gt,true),n.removeEventListener("pointermove",gt,true),n.removeEventListener("pointerup",gt,true)):(n.removeEventListener("mousedown",gt,true),n.removeEventListener("mousemove",gt,true),n.removeEventListener("mouseup",gt,true)),Nl.delete(t);}};function bb(){return fn}function vb(r){fn=r,Vl(r,null);}function hb(){return fn==="keyboard"||fn==="virtual"}function yb(r={}){let{isTextInput:e,autoFocus:t,onChange:n,root:i}=r;sE(i),n?.({isFocusVisible:t||hb(),modality:fn});let o=(s,a)=>{iE(!!e,s,a)&&n?.({isFocusVisible:hb(),modality:s});};return xu.add(o),()=>{xu.delete(o);}}var{not:bt,and:gi,or:lE}=Km(),Cu=rl({props({props:r}){return {closeOnSelect:true,typeahead:true,composite:true,loopFocus:false,navigate(e){Cf(e.node);},...r,positioning:{placement:"bottom-start",gutter:8,...r.positioning}}},initialState({prop:r}){return r("open")||r("defaultOpen")?"open":"idle"},context({bindable:r,prop:e,scope:t}){return {highlightedValue:r(()=>({defaultValue:e("defaultHighlightedValue")||null,value:e("highlightedValue"),onChange(n){e("onHighlightChange")?.({highlightedValue:n});}})),lastHighlightedValue:r(()=>({defaultValue:null})),currentPlacement:r(()=>({defaultValue:void 0})),intentPolygon:r(()=>({defaultValue:null})),anchorPoint:r(()=>({defaultValue:null,hash(n){return `x: ${n?.x}, y: ${n?.y}`}})),isSubmenu:r(()=>({defaultValue:false})),triggerValue:r(()=>({defaultValue:e("defaultTriggerValue")??null,value:e("triggerValue"),onChange(n){let i=e("onTriggerValueChange");if(!i)return;let o=No(t,n);i({value:n,triggerElement:o});}})),pointerRoutingMode:r(()=>({defaultValue:"interactive"}))}},refs(){return {parent:null,children:{},pointerRoutingLocked:false,typeaheadState:{...hl.defaultOptions},positioningOverride:{}}},computed:{isRtl:({prop:r})=>r("dir")==="rtl",isTypingAhead:({refs:r})=>r.get("typeaheadState").keysSoFar!=="",highlightedId:({context:r,scope:e,refs:t})=>Xg(t.get("children"),r.get("highlightedValue"),e)},watch({track:r,action:e,context:t,prop:n}){r([()=>t.get("isSubmenu")],()=>{e(["setSubmenuPlacement"]);}),r([()=>t.hash("anchorPoint")],()=>{t.get("anchorPoint")&&e(["reposition"]);}),r([()=>n("open")],()=>{e(["toggleVisibility"]);});},on:{"TRIGGER_VALUE.SET":{actions:["setTriggerValue","setAnchorPoint","reposition","focusMenu"]},"PARENT.SET":{actions:["setParentMenu"]},"CHILD.SET":{actions:["setChildMenu"]},OPEN:[{guard:"isOpenControlled",actions:["setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setTriggerValue","invokeOnOpen"]}],OPEN_AUTOFOCUS:[{guard:"isOpenControlled",actions:["setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setTriggerValue","highlightFirstItem","invokeOnOpen"]}],CLOSE:[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["invokeOnClose","releaseParentRoutingLock","focusTrigger"]}],"HIGHLIGHTED.RESTORE":{actions:["restoreHighlightedItem"]},"HIGHLIGHTED.SET":{actions:["setHighlightedItem"]},"HIGHLIGHTED.SUGGEST":{actions:["suggestHighlightedItem"]}},states:{idle:{tags:["closed"],on:{"CONTROLLED.OPEN":{target:"open"},"CONTROLLED.CLOSE":{target:"closed"},CONTEXT_MENU_START:{target:"opening:contextmenu",actions:["setAnchorPoint","setTriggerValue"]},CONTEXT_MENU:[{guard:"isOpenControlled",actions:["setAnchorPoint","setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setAnchorPoint","setTriggerValue","invokeOnOpen"]}],TRIGGER_CLICK:[{guard:"isOpenControlled",actions:["invokeOnOpen","setTriggerValue"]},{target:"open",actions:["invokeOnOpen","setTriggerValue"]}],TRIGGER_FOCUS:{guard:bt("isSubmenu"),target:"closed"},TRIGGER_POINTERMOVE:{guard:"isSubmenu",target:"opening"}}},"opening:contextmenu":{tags:["closed"],effects:["waitForLongPress"],on:{"CONTROLLED.OPEN":{target:"open",actions:["reposition"]},"CONTROLLED.CLOSE":{target:"closed",actions:["focusTrigger"]},CONTEXT_MENU_CANCEL:[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["invokeOnClose","releaseParentRoutingLock","focusTrigger"]}],"LONG_PRESS.OPEN":[{guard:"isOpenControlled",actions:["setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setTriggerValue","invokeOnOpen","reposition"]}]}},opening:{tags:["closed"],effects:["waitForOpenDelay"],on:{"CONTROLLED.OPEN":{target:"open"},"CONTROLLED.CLOSE":{target:"closed",actions:["focusTrigger"]},BLUR:[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["invokeOnClose","releaseParentRoutingLock","focusTrigger"]}],TRIGGER_POINTERLEAVE:[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["invokeOnClose","releaseParentRoutingLock","focusTrigger"]}],"DELAY.OPEN":[{guard:"isOpenControlled",actions:["invokeOnOpen"]},{target:"open",actions:["invokeOnOpen"]}]}},closing:{tags:["open"],effects:["trackPointerMove","trackInteractOutside","waitForCloseDelay"],on:{"CONTROLLED.OPEN":{target:"open"},"CONTROLLED.CLOSE":{target:"closed",actions:["focusParentMenu","restoreParentHighlightedItem"]},MENU_POINTERENTER:{target:"open",actions:["clearIntentPolygon"]},POINTER_MOVED_AWAY_FROM_SUBMENU:[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["focusParentMenu","restoreParentHighlightedItem"]}],"DELAY.CLOSE":[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["focusParentMenu","restoreParentHighlightedItem","invokeOnClose","releaseParentRoutingLock"]}]}},closed:{tags:["closed"],entry:["clearHighlightedItem","unlockParentOnClose","clearAnchorPoint"],on:{"CONTROLLED.OPEN":[{guard:lE("isOpenAutoFocusEvent","isArrowDownEvent"),target:"open",actions:["highlightFirstItem"]},{guard:"isArrowUpEvent",target:"open",actions:["highlightLastItem"]},{target:"open"}],CONTEXT_MENU_START:{target:"opening:contextmenu",actions:["setAnchorPoint","setTriggerValue"]},CONTEXT_MENU:[{guard:"isOpenControlled",actions:["setAnchorPoint","setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setAnchorPoint","setTriggerValue","invokeOnOpen"]}],TRIGGER_CLICK:[{guard:"isOpenControlled",actions:["invokeOnOpen","setTriggerValue"]},{target:"open",actions:["invokeOnOpen","setTriggerValue"]}],TRIGGER_POINTERMOVE:{guard:"isTriggerItem",target:"opening"},TRIGGER_BLUR:{target:"idle"},ARROW_DOWN:[{guard:"isOpenControlled",actions:["setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setTriggerValue","highlightFirstItem","invokeOnOpen"]}],ARROW_UP:[{guard:"isOpenControlled",actions:["setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setTriggerValue","highlightLastItem","invokeOnOpen"]}]}},open:{tags:["open"],effects:["trackInteractOutside","trackFocusVisible","trackPositioning","scrollToHighlightedItem"],entry:["focusMenu","unlockParentOnOpen"],on:{"CONTROLLED.CLOSE":[{target:"closed",guard:"isArrowLeftEvent",actions:["focusParentMenu"]},{target:"closed",actions:["focusTrigger"]}],TRIGGER_CLICK:[{guard:gi(bt("isTriggerItem"),"isOpenControlled"),actions:["invokeOnClose","releaseParentRoutingLock"]},{guard:bt("isTriggerItem"),target:"closed",actions:["invokeOnClose","releaseParentRoutingLock","focusTrigger"]}],CONTEXT_MENU:{actions:["setAnchorPoint","setTriggerValue","focusMenu"]},ARROW_UP:{actions:["highlightPrevItem","focusMenu"]},ARROW_DOWN:{actions:["highlightNextItem","focusMenu"]},ARROW_LEFT:[{guard:gi("isSubmenu","isOpenControlled"),actions:["invokeOnClose","releaseParentRoutingLock"]},{guard:"isSubmenu",target:"closed",actions:["focusParentMenu","invokeOnClose","releaseParentRoutingLock"]}],HOME:{actions:["highlightFirstItem","focusMenu"]},END:{actions:["highlightLastItem","focusMenu"]},ARROW_RIGHT:{guard:"isTriggerItemHighlighted",actions:["openSubmenu"]},ENTER:[{guard:"isTriggerItemHighlighted",actions:["openSubmenu"]},{actions:["clickHighlightedItem"]}],ITEM_POINTERMOVE:[{guard:bt("isPointerRoutingLocked"),actions:["setHighlightedItem","focusMenu","closeSiblingMenus"]},{actions:["setLastHighlightedItem","closeSiblingMenus"]}],ITEM_POINTERLEAVE:{guard:gi(bt("isPointerRoutingLocked"),bt("isTriggerItem")),actions:["clearHighlightedItem"]},ITEM_CLICK:[{guard:gi(bt("isTriggerItemHighlighted"),bt("isHighlightedItemEditable"),"closeOnSelect","isOpenControlled"),actions:["invokeOnSelect","setOptionState","closeRootMenu","invokeOnClose","releaseParentRoutingLock"]},{guard:gi(bt("isTriggerItemHighlighted"),bt("isHighlightedItemEditable"),"closeOnSelect"),target:"closed",actions:["invokeOnSelect","setOptionState","closeRootMenu","invokeOnClose","releaseParentRoutingLock","focusTrigger"]},{guard:gi(bt("isTriggerItemHighlighted"),bt("isHighlightedItemEditable")),actions:["invokeOnSelect","setOptionState"]},{actions:["setHighlightedItem"]}],TRIGGER_POINTERMOVE:{guard:"isTriggerItem",actions:["setIntentPolygon"]},TRIGGER_POINTERLEAVE:{target:"closing",actions:["setIntentPolygon"]},ITEM_POINTERDOWN:{actions:["setHighlightedItem"]},TYPEAHEAD:{actions:["highlightMatchedItem"]},FOCUS_MENU:{actions:["focusMenu"]},"POSITIONING.SET":{actions:["reposition"]}}}},implementations:{guards:{closeOnSelect:({prop:r,event:e})=>!!(e?.closeOnSelect??r("closeOnSelect")),isTriggerItem:({event:r})=>mu(r.target),isTriggerItemHighlighted:({event:r,scope:e,computed:t})=>!!(r.target??e.getById(t("highlightedId")))?.hasAttribute("data-controls"),isSubmenu:({context:r})=>r.get("isSubmenu"),isPointerRoutingLocked:({refs:r})=>r.get("pointerRoutingLocked"),isHighlightedItemEditable:({scope:r,computed:e})=>ni(r.getById(e("highlightedId"))),isOpenControlled:({prop:r})=>r("open")!==void 0,isArrowLeftEvent:({event:r})=>r.previousEvent?.type==="ARROW_LEFT",isArrowUpEvent:({event:r})=>r.previousEvent?.type==="ARROW_UP",isArrowDownEvent:({event:r})=>r.previousEvent?.type==="ARROW_DOWN",isOpenAutoFocusEvent:({event:r})=>r.previousEvent?.type==="OPEN_AUTOFOCUS"},effects:{waitForOpenDelay({send:r}){let e=setTimeout(()=>{r({type:"DELAY.OPEN"});},200);return ()=>clearTimeout(e)},waitForCloseDelay({send:r}){let e=setTimeout(()=>{r({type:"DELAY.CLOSE"});},100);return ()=>clearTimeout(e)},waitForLongPress({send:r}){let e=setTimeout(()=>{r({type:"LONG_PRESS.OPEN"});},700);return ()=>clearTimeout(e)},trackFocusVisible({scope:r}){return yb({root:r.getRootNode?.()})},trackPositioning({context:r,prop:e,scope:t,refs:n}){if(Vg(t)||hu(t).length>0)return;let o={...e("positioning"),...n.get("positioningOverride")};return r.set("currentPlacement",o.placement),Il(()=>No(t,r.get("triggerValue")),()=>cu(t),{...o,defer:true,onComplete(l){r.set("currentPlacement",l.placement);}})},trackInteractOutside({refs:r,scope:e,prop:t,context:n,send:i}){let o=()=>Rt(e),s=true,a=l=>hu(e).some(c=>rt(c,l));return Ol(o,{type:"menu",defer:true,exclude:[du(e),...uu(e)].filter(Boolean),onInteractOutside:t("onInteractOutside"),onRequestDismiss:t("onRequestDismiss"),onFocusOutside(l){t("onFocusOutside")?.(l);let c=Re(l.detail.originalEvent);if(a(c)){l.preventDefault();return}if(fu(c,r.get("children"))){l.preventDefault();return}},onEscapeKeyDown(l){t("onEscapeKeyDown")?.(l),n.get("isSubmenu")&&l.preventDefault(),bu({parent:r.get("parent")});},onPointerDownOutside(l){t("onPointerDownOutside")?.(l);let c=Re(l.detail.originalEvent);if(a(c)&&l.detail.contextmenu){l.preventDefault();return}s=!l.detail.focusable;},onDismiss(){i({type:"CLOSE",src:"interact-outside",restoreFocus:s});}})},trackPointerMove({context:r,scope:e,send:t,refs:n}){let i=n.get("parent");if(!i)return;Hn(i,true);let o=e.getDoc();return Xe(o,"pointermove",s=>{Kg(r.get("intentPolygon"),{x:s.clientX,y:s.clientY})||(t({type:"POINTER_MOVED_AWAY_FROM_SUBMENU"}),Hn(i,false));})},scrollToHighlightedItem({scope:r,computed:e}){let t=()=>{if(bb()==="pointer")return;let o=r.getById(e("highlightedId")),s=Rt(r);Ef(o,{rootEl:s,block:"nearest"});};return Me(()=>{vb("virtual"),t();}),Sf(()=>Rt(r),{attributes:["aria-activedescendant"],callback:t})}},actions:{setAnchorPoint({context:r,event:e}){r.set("anchorPoint",t=>Zr(t,e.point)?t:e.point);},setSubmenuPlacement({context:r,computed:e,refs:t}){if(!r.get("isSubmenu"))return;let n=e("isRtl")?"left-start":"right-start";t.set("positioningOverride",{placement:n,gutter:0});},reposition({context:r,scope:e,prop:t,event:n,refs:i}){let o=()=>cu(e),s=n.point??r.get("anchorPoint"),a=s?()=>({width:0,height:0,...s}):void 0,l={...t("positioning"),...i.get("positioningOverride")},c=n.value??r.get("triggerValue");Il(()=>No(e,c),o,{...l,defer:true,getAnchorRect:a,...n.options??{},listeners:false,onComplete(u){r.set("currentPlacement",u.placement);}});},setOptionState({event:r}){if(!r.option)return;let{checked:e,onCheckedChange:t,type:n}=r.option;n==="radio"?t?.(true):n==="checkbox"&&t?.(!e);},clickHighlightedItem({scope:r,computed:e,prop:t,context:n}){let i=r.getById(e("highlightedId"));if(!i||i.dataset.disabled)return;let o=n.get("highlightedValue");Jm(i)?t("navigate")?.({value:o,node:i,href:i.href}):queueMicrotask(()=>i.click());},setIntentPolygon({context:r,scope:e,event:t}){let n=Rt(e),i=r.get("currentPlacement");if(!n||!i)return;let o=n.getBoundingClientRect(),s=Yg(o,i);if(!s)return;let l=Oo(i)==="right"?-5:5;r.set("intentPolygon",[{...t.point,x:t.point.x+l},...s]);},clearIntentPolygon({context:r}){r.set("intentPolygon",null);},clearAnchorPoint({context:r}){r.set("anchorPoint",null);},unlockParentOnOpen({refs:r,context:e,scope:t}){let n=r.get("parent");if(e.get("isSubmenu")){let i=Jt(t);n?.send({type:"HIGHLIGHTED.SUGGEST",value:i});}Hn(n,false);},unlockParentOnClose({refs:r,context:e}){qg(r.get("parent"),e.get("isSubmenu"));},setHighlightedItem({context:r,event:e}){let t=e.value||Bn(e.target);r.set("highlightedValue",t);},clearHighlightedItem({context:r}){r.set("highlightedValue",null);},focusMenu({scope:r}){Me(()=>{let e=Rt(r);cl({root:e,enabled:!rt(e,r.getActiveElement()),filter(n){return !n.role?.startsWith("menuitem")}})?.focus({preventScroll:true});});},highlightFirstItem({context:r,scope:e}){(Rt(e)?queueMicrotask:Me)(()=>{let n=_g(e);n&&r.set("highlightedValue",Bn(n));});},highlightLastItem({context:r,scope:e}){(Rt(e)?queueMicrotask:Me)(()=>{let n=Bg(e);n&&r.set("highlightedValue",Bn(n));});},highlightNextItem({context:r,scope:e,event:t,prop:n}){let i=Hg(e,{loop:t.loop,value:r.get("highlightedValue"),loopFocus:n("loopFocus")});r.set("highlightedValue",Bn(i));},highlightPrevItem({context:r,scope:e,event:t,prop:n}){let i=zg(e,{loop:t.loop,value:r.get("highlightedValue"),loopFocus:n("loopFocus")});r.set("highlightedValue",Bn(i));},invokeOnSelect({context:r,prop:e,scope:t}){let n=r.get("highlightedValue");if(n==null)return;let i=Fg(t,n);Wg(i,n),e("onSelect")?.({value:n});},focusTrigger({scope:r,context:e,event:t}){e.get("isSubmenu")||e.get("anchorPoint")||t.restoreFocus===false||queueMicrotask(()=>{No(r,e.get("triggerValue"))?.focus({preventScroll:true});});},highlightMatchedItem({scope:r,context:e,event:t,refs:n}){let i=$g(r,{key:t.key,value:e.get("highlightedValue"),typeaheadState:n.get("typeaheadState")});i&&e.set("highlightedValue",Bn(i));},setParentMenu({refs:r,event:e,context:t}){r.set("parent",e.value),t.set("isSubmenu",true);},setChildMenu({refs:r,event:e}){let t=r.get("children");t[e.id]=e.value,r.set("children",t);},closeSiblingMenus({refs:r,event:e,scope:t}){let n=e.target;if(!mu(n))return;let i=n?.getAttribute("data-uid"),o=r.get("children");for(let s in o){if(s===i)continue;let a=o[s],l=a.context.get("intentPolygon");l&&e.point&&Dl(l,e.point)||(Rt(t)?.focus({preventScroll:true}),a.send({type:"CLOSE"}));}},closeRootMenu({refs:r}){bu({parent:r.get("parent")});},openSubmenu({refs:r,scope:e,computed:t}){let i=e.getById(t("highlightedId"))?.getAttribute("data-uid"),o=r.get("children");(i?o[i]:null)?.send({type:"OPEN_AUTOFOCUS"});},focusParentMenu({refs:r}){r.get("parent")?.send({type:"FOCUS_MENU"});},setLastHighlightedItem({context:r,event:e}){r.set("lastHighlightedValue",Bn(e.target));},suggestHighlightedItem({context:r,event:e}){let t=e.value;if(t){if(r.get("highlightedValue")!=null){r.set("lastHighlightedValue",t);return}r.set("highlightedValue",t);}},restoreHighlightedItem({context:r}){let e=r.get("lastHighlightedValue");r.set("lastHighlightedValue",null),e&&r.set("highlightedValue",e);},restoreParentHighlightedItem({refs:r}){r.get("parent")?.send({type:"HIGHLIGHTED.RESTORE"});},invokeOnOpen({prop:r}){r("onOpenChange")?.({open:true});},invokeOnClose({prop:r}){r("onOpenChange")?.({open:false});},releaseParentRoutingLock({refs:r,context:e}){e.get("isSubmenu")&&Zg(r.get("parent"));},toggleVisibility({prop:r,event:e,send:t}){t({type:r("open")?"CONTROLLED.OPEN":"CONTROLLED.CLOSE",previousEvent:e});},setTriggerValue({context:r,event:e}){e.value!==void 0&&r.set("triggerValue",e.value);}}}});function wb(r){return {machine:Cu,props:{id:r.id??yl("vela-menu"),ids:r.triggerId?{trigger:r.triggerId}:void 0,positioning:{placement:r.placement??"bottom-start",...r.getAnchorRect?{getAnchorRect:()=>r.getAnchorRect()}:{}},onSelect:e=>r.onSelect?.(e.value),onOpenChange:e=>r.onOpenChange?.(e.open)},connect:e=>vu(e,ci)}}var xb="vela-ui-menu",Sb=`
3
+ `),s=Math.max(1,...o.map(c=>c.length)),a=Math.max(20,s*i*.6)+16,l=o.length*i*1.4+12;return {x:e.xOf(t.time)-a/2,y:n-l/2,w:a,h:l}}points(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=e.yOf(t.price,this.paneId),o=e.yOf(n.price,this.paneId);return i==null||o==null?null:[[e.xOf(t.time),i],[e.xOf(n.time),o]]}hitTest(e,t,n,i){let o=this.box(n);if(o&&Fe(e,t,o.x,o.y,o.x+o.w,o.y+o.h,i))return true;let s=this.points(n);return s!=null&&ne(e,t,s[0][0],s[0][1],s[1][0],s[1][1])<=i}handlePoints(e){let t=this.points(e);return t?[t[0]]:[]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}translateBody(e,t,n){let i=n[0],o=n[1];return !i||!o?n.map(s=>({time:s.time+e,price:s.price+t})):[{time:i.time,price:i.price},{time:o.time+e,price:o.price+t}]}bounds(e){return this.box(e)}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[...B,...ue,...H],textIsContent:true}}};var _t=class extends ut{constructor(){super(...arguments);this.type="callout";}};var Qn=class extends ut{constructor(){super(...arguments);this.type="pricenote";}defaultLabel(){return ""}labelText(){let t=this.anchors[0]?.price;return t==null?"0.00":t.toFixed(2)}schema(){return {fields:[...B,...ue,...H.filter(t=>t.path!=="text.value")]}}};var er=class extends ut{constructor(){super(...arguments);this.type="comment";}defaultLabel(){return "Comment"}};var tr=class extends ut{constructor(){super(...arguments);this.type="signpost";}defaultLabel(){return "Signpost"}};var he=class extends G{hitTest(e,t,n,i){let o=this.geometry(n);return o?this.style.fillColor&&o.fill&&Vt(e,t,o.fill)?true:o.segments.some(s=>ne(e,t,s[0],s[1],s[2],s[3])<=i):false}handlePoints(e){let t=[];for(let n of this.anchors){let i=e.yOf(n.price,this.paneId);if(i==null)return [];t.push([e.xOf(n.time),i]);}return t}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),i=t.map(a=>a[1]),o=Math.min(...n),s=Math.min(...i);return {x:o,y:s,w:Math.max(...n)-o,h:Math.max(...i)-s}}};var Ks=class extends he{constructor(){super(...arguments);this.type="parallelchannel";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"offset",free:"y"}]}}offset(){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[2];return !t||!n||!i?0:i.price-(t.price+n.price)/2}handlePoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return [];let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return [];let a=[[t.xOf(n.time),o],[t.xOf(i.time),s]],l=this.anchors[2];if(l){let c=t.yOf(l.price,this.paneId);c!=null&&a.push([t.xOf((n.time+i.time)/2),c]);}return a}timeExtent(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.time,n.time),max:Math.max(t.time,n.time)}}geometry(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=this.offset(),s=t.xOf(n.time),a=t.xOf(i.time),l=t.yOf(n.price,this.paneId),c=t.yOf(i.price,this.paneId),d=t.yOf(n.price+o,this.paneId),u=t.yOf(i.price+o,this.paneId);return l==null||c==null||d==null||u==null?null:{segments:[[s,l,a,c],[s,d,a,u]],fill:[[s,l],[a,c],[a,u],[s,d]]}}priceRange(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=this.offset(),o=[t.price,n.price,t.price+i,n.price+i],s=this.anchors[2];return s&&o.push(s.price),{min:Math.min(...o),max:Math.max(...o)}}schema(){return {fields:[...B,...ue,...H]}}};var Xs=class extends he{constructor(){super(...arguments);this.type="disjointchannel";}anchorSchema(){return {min:4,max:4,slots:[{role:"top1",free:"both"},{role:"top2",free:"both"},{role:"bot1",free:"both"},{role:"bot2",free:"both"}]}}seg(t,n,i){let o=this.anchors[t],s=this.anchors[n];if(!o||!s)return null;let a=i.yOf(o.price,this.paneId),l=i.yOf(s.price,this.paneId);return a==null||l==null?null:[i.xOf(o.time),a,i.xOf(s.time),l]}geometry(t){let n=this.seg(0,1,t),i=this.seg(2,3,t),o=[n,i].filter(a=>a!=null);if(o.length===0)return null;let s=n&&i?[[n[0],n[1]],[n[2],n[3]],[i[2],i[3]],[i[0],i[1]]]:null;return {segments:o,fill:s}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B,...ue,...H]}}};var js=class extends he{constructor(){super(...arguments);this.type="flattopbottom";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"flat",free:"y"}]}}handlePoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return [];let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return [];let a=[[t.xOf(n.time),o],[t.xOf(i.time),s]],l=this.anchors[2];if(l){let c=t.yOf(l.price,this.paneId);c!=null&&a.push([t.xOf((n.time+i.time)/2),c]);}return a}timeExtent(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.time,n.time),max:Math.max(t.time,n.time)}}geometry(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.xOf(n.time),s=t.xOf(i.time),a=t.yOf(n.price,this.paneId),l=t.yOf(i.price,this.paneId);if(a==null||l==null)return null;let c=this.anchors[2];if(!c)return {segments:[[o,a,s,l]],fill:null};let d=t.yOf(c.price,this.paneId);return d==null?null:{segments:[[o,a,s,l],[o,d,s,d]],fill:[[o,a],[s,l],[s,d],[o,d]]}}priceRange(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=[t.price,n.price],o=this.anchors[2];return o&&i.push(o.price),{min:Math.min(...i),max:Math.max(...i)}}schema(){return {fields:[...B,...ue,...H]}}};var jx=2;function Hp(){return {midColor:J,midStyle:"solid",upperColor:z,upperStyle:"solid",lowerColor:W,lowerStyle:"solid",upperFill:`${z}26`,lowerFill:`${W}26`,showR2:true}}function zp(r){let e=r.length;if(e<2)return null;let t=0,n=0,i=0,o=0,s=0;for(let m=0;m<e;m+=1){let f=r[m].close;t+=m,n+=f,i+=m*f,o+=m*m,s+=f*f;}let a=e*o-t*t,l=a===0?0:(e*i-t*n)/a,c=(n-l*t)/e,d=0;for(let m=0;m<e;m+=1){let f=r[m].close-(c+l*m);d+=f*f;}let u=Math.sqrt(d/e),h=Math.sqrt(a*(e*s-n*n)),p=h===0?0:(e*i-t*n)/h;return {t0:r[0].time,t1:r[e-1].time,mid0:c,mid1:c+l*(e-1),dev:jx*u,r2:Math.max(0,Math.min(1,p*p)),n:e}}var ln=class extends G{constructor(t){super(t);this.type="regressionchannel";this.cachedRange=null;this.reg||(this.reg=Hp());}anchorSchema(){return {min:2,max:2,slots:[{role:"start",free:"x"},{role:"end",free:"x"}]}}fit(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=Math.min(n.time,i.time),s=Math.max(n.time,i.time),a=t.barsInRange?.(o,s)??null,l=a?zp(a):null;return l&&(this.cachedRange={min:Math.min(l.mid0,l.mid1)-l.dev,max:Math.max(l.mid0,l.mid1)+l.dev}),l}layout(t){let n=this.fit(t);if(!n)return null;let i=t.yOf(n.mid0,this.paneId),o=t.yOf(n.mid1,this.paneId),s=t.yOf(n.mid0+n.dev,this.paneId),a=t.yOf(n.mid1+n.dev,this.paneId),l=t.yOf(n.mid0-n.dev,this.paneId),c=t.yOf(n.mid1-n.dev,this.paneId);return i==null||o==null||s==null||a==null||l==null||c==null?null:{x0:t.xOf(n.t0),x1:t.xOf(n.t1),midY0:i,midY1:o,upperY0:s,upperY1:a,lowerY0:l,lowerY1:c,r2:n.r2,showR2:this.reg.showR2}}band(t){let n=this.layout(t);return n?[[n.x0,n.upperY0],[n.x1,n.upperY1],[n.x1,n.lowerY1],[n.x0,n.lowerY0]]:null}hitTest(t,n,i,o){let s=this.layout(i);if(!s)return false;let a=[[s.x0,s.upperY0],[s.x1,s.upperY1],[s.x1,s.lowerY1],[s.x0,s.lowerY0]];return Vt(t,n,a)?true:[[s.x0,s.midY0,s.x1,s.midY1],[s.x0,s.upperY0,s.x1,s.upperY1],[s.x0,s.lowerY0,s.x1,s.lowerY1]].some(c=>ne(t,n,c[0],c[1],c[2],c[3])<=o)}handlePoints(t){let n=this.layout(t);if(n)return [[n.x0,n.midY0],[n.x1,n.midY1]];let i=[];for(let o of this.anchors){let s=t.yOf(o.price,this.paneId);if(s==null)return [];i.push([t.xOf(o.time),s]);}return i}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.band(t);if(!n)return null;let i=n.map(l=>l[0]),o=n.map(l=>l[1]),s=Math.min(...i),a=Math.min(...o);return {x:s,y:a,w:Math.max(...i)-s,h:Math.max(...o)-a}}priceRange(){if(this.cachedRange)return this.cachedRange;let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[{path:"reg.midColor",label:"Midline color",kind:"color",group:"line"},{path:"reg.midStyle",label:"Midline style",kind:"lineStyle",group:"line"},{path:"reg.upperColor",label:"Upper line color",kind:"color",group:"line"},{path:"reg.upperStyle",label:"Upper line style",kind:"lineStyle",group:"line"},{path:"reg.lowerColor",label:"Lower line color",kind:"color",group:"line"},{path:"reg.lowerStyle",label:"Lower line style",kind:"lineStyle",group:"line"},{path:"reg.upperFill",label:"Upper fill",kind:"color",group:"fill"},{path:"reg.lowerFill",label:"Lower fill",kind:"color",group:"fill"},{path:"reg.showR2",label:"Show R\xB2",kind:"boolean",group:"behavior"}]}}writeProps(){return {...this.reg}}readProps(t){this.reg={...Hp(),...t};}};var $p=`${Je}00`;function Wp(){return {midColor:Je,midStyle:"solid",multiplier:1,upperColor:$p,upperStyle:"solid",lowerColor:$p,lowerStyle:"solid",bandFill:`${Je}33`}}function Gp(r,e){let t=r.length;if(t<1)return null;let n=0;for(let c of r)n+=c.volume>0?c.volume:0;let i=n>0,o=0,s=0,a=0,l=[];for(let c=0;c<t;c+=1){let d=r[c],u=(d.high+d.low+d.close)/3,h=i?Math.max(0,d.volume):1;o+=h,s+=u*h,a+=u*u*h;let p=o>0?s/o:u,m=o>0?Math.max(0,a/o-p*p):0,f=Math.sqrt(m)*e;l.push({time:d.time,mid:p,upper:p+f,lower:p-f});}return l}var nr=class extends G{constructor(t){super(t);this.type="anchoredvwap";this.cachedRange=null;this.cachedExtent=null;this.vwap||(this.vwap=Wp());}anchorSchema(){return {min:1,max:1,slots:[{role:"anchor",free:"x"}]}}series(t){let n=this.anchors[0];if(!n)return null;let i=t.barsInRange?.(n.time,Number.POSITIVE_INFINITY)??null;if(!i||i.length<1)return null;let o=Gp(i.map(s=>({time:s.time,high:s.high,low:s.low,close:s.close,volume:s.volume??0})),this.vwap.multiplier);if(o&&o.length>0){let s=1/0,a=-1/0;for(let l of o)l.lower<s&&(s=l.lower),l.upper>a&&(a=l.upper);this.cachedRange={min:s,max:a},this.cachedExtent={min:o[0].time,max:o[o.length-1].time};}return o}layout(t){let n=this.series(t);if(!n)return null;let i=[],o=[],s=[];for(let a of n){let l=t.xOf(a.time),c=t.yOf(a.mid,this.paneId),d=t.yOf(a.upper,this.paneId),u=t.yOf(a.lower,this.paneId);c==null||d==null||u==null||(i.push([l,c]),o.push([l,d]),s.push([l,u]));}return i.length>0?{mid:i,upper:o,lower:s}:null}bandPolygon(t){return [...t.upper,...[...t.lower].reverse()]}hitTest(t,n,i,o){let s=this.layout(i);return s?Vt(t,n,this.bandPolygon(s))?true:md(t,n,s.mid,o)||md(t,n,s.upper,o)||md(t,n,s.lower,o):false}handlePoints(t){let n=this.layout(t);if(n&&n.mid.length>0)return [n.mid[0]];let i=this.anchors[0];if(!i)return [];let o=t.yOf(i.price,this.paneId);return o==null?[]:[[t.xOf(i.time),o]]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.layout(t);if(!n)return null;let i=[...n.upper,...n.lower],o=i.map(c=>c[0]),s=i.map(c=>c[1]),a=Math.min(...o),l=Math.min(...s);return {x:a,y:l,w:Math.max(...o)-a,h:Math.max(...s)-l}}priceRange(){return this.cachedRange}timeExtent(){return this.cachedExtent}schema(){return {fields:[{path:"vwap.midColor",label:"VWAP color",kind:"color",group:"line"},{path:"vwap.midStyle",label:"VWAP style",kind:"lineStyle",group:"line"},{path:"vwap.multiplier",label:"Band multiplier",kind:"number",min:.5,max:5,step:.5,group:"behavior"},{path:"vwap.upperColor",label:"Upper band color",kind:"color",group:"line"},{path:"vwap.lowerColor",label:"Lower band color",kind:"color",group:"line"},{path:"vwap.bandFill",label:"Band fill",kind:"color",group:"fill"}]}}writeProps(){return {...this.vwap}}readProps(t){this.vwap={...Wp(),...t};}};function md(r,e,t,n){for(let i=1;i<t.length;i+=1)if(ne(r,e,t[i-1][0],t[i-1][1],t[i][0],t[i][1])<=n)return true;return false}var qx=`${z}66`,Zx=`${W}66`,Jx=`${z}BF`,Qx=`${W}BF`;function Up(){return {rows:24,valueAreaPct:70,widthPct:35,anchor:"left",upColor:qx,downColor:Zx,vaUpColor:Jx,vaDownColor:Qx,showVah:true,vahColor:J,vahStyle:"solid",showVal:true,valColor:J,valStyle:"solid",showPoc:true,pocColor:void 0,pocStyle:"solid",showDevelopingPoc:false,developingPocColor:Ye,developingPocStyle:"dotted",showDevelopingVa:false,developingVaColor:Ye,developingVaStyle:"dotted"}}function e0(r,e){return r<0?0:r>=e?e-1:r}function Yp(r,e,t){let n=r.length,i=0,o=0;for(let d=0;d<n;d+=1){let u=r[d].up+r[d].down;i+=u,u>o&&(o=u);}let s=i*Math.min(1,Math.max(0,t)),a=e,l=e,c=o;for(;c<s&&(a>0||l<n-1);){let d=a>0?r[a-1].up+r[a-1].down:-1,u=l<n-1?r[l+1].up+r[l+1].down:-1;u>d?(l+=1,c+=u):(a-=1,c+=d);}return {vaFrom:a,vaTo:l}}function Kp(r,e,t,n){let i=n.volume;if(!(i>0))return;let o=r.length,s=n.close>=n.open?"up":"down",a=new Set;for(let l of [n.open,n.high,n.low,n.close])a.add(e0(Math.floor((l-e)/t),o));for(let l of a)r[l][s]+=i;}function Xp(r){let e=0,t=0;for(let n=0;n<r.length;n+=1){let i=r[n].up+r[n].down;i>e&&(e=i,t=n);}return e>0?{poc:t,maxTotal:e}:null}function jp(r,e,t){let n=1/0,i=-1/0;for(let p of r)p.volume>0&&(p.low<n&&(n=p.low),p.high>i&&(i=p.high));if(!Number.isFinite(n))return null;let o=i>n?Math.max(1,Math.round(e)):1,s=i>n?(i-n)/o:1,a=Array.from({length:o},(p,m)=>({price:n+m*s,up:0,down:0}));for(let p of r)Kp(a,n,s,p);let l=Xp(a);if(!l)return null;let{poc:c,maxTotal:d}=l,{vaFrom:u,vaTo:h}=Yp(a,c,t);return {rows:a,rowH:s,min:n,maxTotal:d,poc:c,vaFrom:u,vaTo:h}}function qp(r,e,t,n){let i=jp(r,e,t);if(!i)return null;if(!n||r.length<1)return {profile:i,developingPoc:[],developingVaHigh:[],developingVaLow:[]};let{min:o,rowH:s}=i,a=i.rows.length,l=Array.from({length:a},(h,p)=>({price:o+p*s,up:0,down:0})),c=[],d=[],u=[];for(let h of r){Kp(l,o,s,h);let p=Xp(l);if(!p)continue;let{poc:m}=p,{vaFrom:f,vaTo:g}=Yp(l,m,t);c.push({time:h.time,price:l[m].price+s/2}),d.push({time:h.time,price:l[g].price+s}),u.push({time:h.time,price:l[f].price});}return {profile:i,developingPoc:c,developingVaHigh:d,developingVaLow:u}}var at=class extends G{constructor(t){super(t);this.type="fixedrangevp";this.cachedRange=null;this.frvp||(this.frvp=Up());}anchorSchema(){return {min:2,max:2,slots:[{role:"start",free:"x"},{role:"end",free:"x"}]}}barsInSpan(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=Math.min(n.time,i.time),s=Math.max(n.time,i.time),a=t.barsInRange?.(o,s)??null;return !a||a.length<1?null:a.map(l=>({time:l.time,open:l.open,high:l.high,low:l.low,close:l.close,volume:l.volume??0}))}compute(t){let n=this.barsInSpan(t);if(!n)return null;let i=this.frvp,o=i.showDevelopingPoc||i.showDevelopingVa,s=qp(n,i.rows,i.valueAreaPct/100,o);if(s){let{profile:a}=s;this.cachedRange={min:a.min,max:a.min+a.rowH*a.rows.length};}return s}layout(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=this.compute(t);if(!o)return null;let{profile:s}=o,a=Math.min(n.time,i.time),l=Math.max(n.time,i.time),c=t.xOf(a),d=t.xOf(l),u=Math.abs(d-c),h=Math.max(1,Math.min(100,Math.max(0,this.frvp.widthPct))/100*u),p=this.frvp.anchor==="left",m=p?Math.min(c,d):Math.max(c,d),f=p?1:-1,g=[];for(let T=0;T<=s.rows.length;T+=1){let E=t.yOf(s.min+T*s.rowH,this.paneId);if(E==null)return null;g.push(E);}let b=T=>t.yOf(T,this.paneId),y=s.rows[s.vaTo].price+s.rowH,v=s.rows[s.vaFrom].price,S=s.rows[s.poc].price+s.rowH/2,P=T=>{let E=[];for(let x of T){let L=b(x.price);L!=null&&E.push([t.xOf(x.time),L]);}return E};return {x0:Math.min(c,d),x1:Math.max(c,d),anchorX:m,maxW:h,grow:f,profile:s,yEdges:g,vahY:b(y),valY:b(v),pocY:b(S),developingPoc:P(o.developingPoc),developingVaHigh:P(o.developingVaHigh),developingVaLow:P(o.developingVaLow)}}hitTest(t,n,i,o){let s=this.layout(i);if(!s)return false;let a=s.grow===1?s.anchorX:s.anchorX-s.maxW,l=s.grow===1?s.anchorX+s.maxW:s.anchorX,c=Math.min(s.yEdges[0],s.yEdges[s.yEdges.length-1]),d=Math.max(s.yEdges[0],s.yEdges[s.yEdges.length-1]);if(Vt(t,n,[[a,c],[l,c],[l,d],[a,d]]))return true;let u=[[s.x0,s.vahY],[s.x0,s.valY],[s.x0,s.pocY]];for(let[,h]of u)if(h!=null&&ne(t,n,s.x0,h,s.x1,h)<=o)return true;for(let h of [s.developingPoc,s.developingVaHigh,s.developingVaLow])for(let p=1;p<h.length;p+=1)if(ne(t,n,h[p-1][0],h[p-1][1],h[p][0],h[p][1])<=o)return true;return false}handlePoints(t){let n=this.layout(t);if(n&&n.pocY!=null)return [[n.x0,n.pocY],[n.x1,n.pocY]];let i=[];for(let o of this.anchors){let s=t.yOf(o.price,this.paneId);if(s==null)return [];i.push([t.xOf(o.time),s]);}return i}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.layout(t);if(!n)return null;let i=Math.min(n.x0,n.grow===1?n.anchorX:n.anchorX-n.maxW),o=Math.max(n.x1,n.grow===1?n.anchorX+n.maxW:n.anchorX),s=Math.min(n.yEdges[0],n.yEdges[n.yEdges.length-1]),a=Math.max(n.yEdges[0],n.yEdges[n.yEdges.length-1]);return {x:i,y:s,w:o-i,h:a-s}}priceRange(){if(this.cachedRange)return this.cachedRange;let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[{path:"frvp.rows",label:"Rows",kind:"number",min:1,max:500,step:1,group:"behavior"},{path:"frvp.valueAreaPct",label:"Value Area",kind:"number",min:0,max:100,step:1,group:"behavior"},{path:"frvp.widthPct",label:"Width %",kind:"number",min:0,max:100,step:1,group:"behavior"},{path:"frvp.anchor",label:"Anchor",kind:"select",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}],group:"behavior"},{path:"frvp.upColor",label:"Up Volume",kind:"color",group:"fill"},{path:"frvp.downColor",label:"Down Volume",kind:"color",group:"fill"},{path:"frvp.vaUpColor",label:"Value Area Up",kind:"color",group:"fill"},{path:"frvp.vaDownColor",label:"Value Area Down",kind:"color",group:"fill"},{path:"frvp.showVah",label:"VAH",kind:"boolean",group:"line"},{path:"frvp.vahColor",label:"VAH color",kind:"color",group:"line"},{path:"frvp.vahStyle",label:"VAH style",kind:"lineStyle",options:Ke,group:"line"},{path:"frvp.showVal",label:"VAL",kind:"boolean",group:"line"},{path:"frvp.valColor",label:"VAL color",kind:"color",group:"line"},{path:"frvp.valStyle",label:"VAL style",kind:"lineStyle",options:Ke,group:"line"},{path:"frvp.showPoc",label:"POC",kind:"boolean",group:"line"},{path:"frvp.pocColor",label:"POC color",kind:"color",group:"line"},{path:"frvp.pocStyle",label:"POC style",kind:"lineStyle",options:Ke,group:"line"},{path:"frvp.showDevelopingPoc",label:"Developing POC",kind:"boolean",group:"line"},{path:"frvp.developingPocColor",label:"Developing POC color",kind:"color",group:"line"},{path:"frvp.developingPocStyle",label:"Developing POC style",kind:"lineStyle",options:Ke,group:"line"},{path:"frvp.showDevelopingVa",label:"Developing VA",kind:"boolean",group:"line"},{path:"frvp.developingVaColor",label:"Developing VA color",kind:"color",group:"line"},{path:"frvp.developingVaStyle",label:"Developing VA style",kind:"lineStyle",options:Ke,group:"line"}]}}writeProps(){return {...this.frvp}}readProps(t){this.frvp={...Up(),...t};}};var qs=class extends he{constructor(){super(...arguments);this.type="pitchfork";}anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return null;let s=g=>{let b=t.yOf(g.price,this.paneId);return b==null?null:[t.xOf(g.time),b]},a=s(n),l=s(i),c=s(o);if(!a||!l||!c)return null;let d=(l[0]+c[0])/2,u=(l[1]+c[1])/2,h=d-a[0],p=u-a[1],m=t.width,f=t.height;return {segments:[xe(a[0],a[1],d,u,"right",m,f),xe(l[0],l[1],l[0]+h,l[1]+p,"right",m,f),xe(c[0],c[1],c[0]+h,c[1]+p,"right",m,f),[l[0],l[1],c[0],c[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B,...H]}}};var zr=class extends he{anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(e){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[2];if(!t||!n||!i)return null;let o=f=>{let g=e.yOf(f.price,this.paneId);return g==null?null:[e.xOf(f.time),g]},s=o(this.medianStart(t,n,i)),a=o(n),l=o(i);if(!s||!a||!l)return null;let c=(a[0]+l[0])/2,d=(a[1]+l[1])/2,u=c-s[0],h=d-s[1],p=e.width,m=e.height;return {segments:[xe(s[0],s[1],c,d,"right",p,m),xe(a[0],a[1],a[0]+u,a[1]+h,"right",p,m),xe(l[0],l[1],l[0]+u,l[1]+h,"right",p,m),[a[0],a[1],l[0],l[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}schema(){return {fields:[...B,...H]}}};var Zs=class extends zr{constructor(){super(...arguments);this.type="schiffpitchfork";}medianStart(t,n){return {time:t.time,price:(t.price+n.price)/2}}};var Js=class extends zr{constructor(){super(...arguments);this.type="modifiedschiffpitchfork";}medianStart(t,n){return {time:(t.time+n.time)/2,price:(t.price+n.price)/2}}};var Qs=class extends he{constructor(){super(...arguments);this.type="insidepitchfork";}anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return null;let s=b=>{let y=t.yOf(b.price,this.paneId);return y==null?null:[t.xOf(b.time),y]},a=s({time:(n.time+i.time)/2,price:(n.price+i.price)/2}),l=s(n),c=s(i),d=s(o);if(!a||!l||!c||!d)return null;let u=(c[0]+d[0])/2,h=(c[1]+d[1])/2,p=d[0]-a[0],m=d[1]-a[1],f=t.width,g=t.height;return {segments:[xe(u,h,u+p,h+m,"right",f,g),xe(c[0],c[1],c[0]+p,c[1]+m,"right",f,g),xe(d[0],d[1],d[0]+p,d[1]+m,"right",f,g),[c[0],c[1],d[0],d[1]],[a[0],a[1],d[0],d[1]],[l[0],l[1],c[0],c[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B,...H]}}};var ea=class extends G{constructor(){super(...arguments);this.type="arrow";}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?null:[t.xOf(n.time),o,t.xOf(i.time),s]}hitTest(t,n,i,o){let s=this.pixels(i);return s!=null&&ne(t,n,s[0],s[1],s[2],s[3])<=o}handlePoints(t){let n=this.pixels(t);return n?[[n[0],n[1]],[n[2],n[3]]]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.pixels(t);return n?{x:Math.min(n[0],n[2]),y:Math.min(n[1],n[3]),w:Math.abs(n[2]-n[0]),h:Math.abs(n[3]-n[1])}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,{path:"style.arrowRight",label:"Head (end)",kind:"boolean",group:"line"},{path:"style.arrowLeft",label:"Head (start)",kind:"boolean",group:"line"},...H]}}};var Zp=48,ta=class extends G{constructor(){super(...arguments);this.type="ellipse";}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}oval(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time);return {cx:(a+l)/2,cy:(o+s)/2,rx:Math.abs(l-a)/2,ry:Math.abs(s-o)/2}}perimeter(t){let n=[];for(let i=0;i<=Zp;i+=1){let o=i/Zp*Math.PI*2;n.push([t.cx+t.rx*Math.cos(o),t.cy+t.ry*Math.sin(o)]);}return n}hitTest(t,n,i,o){let s=this.oval(i);if(!s||s.rx<1||s.ry<1)return false;let a=((t-s.cx)/s.rx)**2+((n-s.cy)/s.ry)**2;return this.style.fillColor&&a<=1?true:Hr(t,n,this.perimeter(s))<=o}handlePoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return [];let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?[]:[[t.xOf(n.time),o],[t.xOf(i.time),s]]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.oval(t);return n?{x:n.cx-n.rx,y:n.cy-n.ry,w:n.rx*2,h:n.ry*2}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,...ue,...H]}}};var na=class extends he{constructor(){super(...arguments);this.type="triangle";}anchorSchema(){return {min:3,max:3,slots:[{role:"v1",free:"both"},{role:"v2",free:"both"},{role:"v3",free:"both"}]}}geometry(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return null;let s=d=>{let u=t.yOf(d.price,this.paneId);return u==null?null:[t.xOf(d.time),u]},a=s(n),l=s(i),c=s(o);return !a||!l||!c?null:{segments:[[a[0],a[1],l[0],l[1]],[l[0],l[1],c[0],c[1]],[c[0],c[1],a[0],a[1]]],fill:[a,l,c]}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B,...ue,...H]}}};var t0=512,In=class extends he{anchorSchema(){return {min:2,max:t0,slots:[]}}geometry(e){let t=[];for(let i of this.anchors){let o=e.yOf(i.price,this.paneId);if(o==null)return null;t.push([e.xOf(i.time),o]);}if(t.length<2)return null;let n=[];for(let i=1;i<t.length;i+=1)n.push([t[i-1][0],t[i-1][1],t[i][0],t[i][1]]);return {segments:n,fill:null}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}schema(){return {fields:[...B,...H]}}};var ra=class extends In{constructor(){super(...arguments);this.type="polyline";}};var Wi=class extends In{placementMode(){return "freehand"}handlePoints(e){return []}bounds(e){let t=[],n=[];for(let s of this.anchors){let a=e.yOf(s.price,this.paneId);a!=null&&(t.push(e.xOf(s.time)),n.push(a));}if(t.length===0)return null;let i=Math.min(...t),o=Math.min(...n);return {x:i,y:o,w:Math.max(...t)-i,h:Math.max(...n)-o}}},ia=class extends Wi{constructor(){super(...arguments);this.type="freehand";}};var n0=[{path:"style.lineColor",label:"Color",kind:"color",group:"line"},{path:"style.lineWidth",label:"Width",kind:"number",min:4,max:60,step:1,group:"line"}],oa=class extends Wi{constructor(){super(...arguments);this.type="highlighter";}schema(){return {fields:n0}}};var sa=class extends G{constructor(){super(...arguments);this.type="circle";}anchorSchema(){return {min:2,max:2,slots:[{role:"center",free:"both"},{role:"edge",free:"both"}]}}geom(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time);return {cx:a,cy:o,r:Math.hypot(l-a,s-o)}}hitTest(t,n,i,o){let s=this.geom(i);if(!s||s.r<1)return false;let a=Math.hypot(t-s.cx,n-s.cy);return this.style.fillColor&&a<=s.r?true:Math.abs(a-s.r)<=o}handlePoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return [];let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?[]:[[t.xOf(n.time),o],[t.xOf(i.time),s]]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.geom(t);return n?{x:n.cx-n.r,y:n.cy-n.r,w:n.r*2,h:n.r*2}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,...ue,...H]}}};var aa=class extends he{constructor(){super(...arguments);this.type="rotatedrect";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"w",free:"both"}]}}px(t,n){let i=this.anchors[n];if(!i)return null;let o=t.yOf(i.price,this.paneId);return o==null?null:[t.xOf(i.time),o]}geometry(t){let n=this.px(t,0),i=this.px(t,1);if(!n||!i)return null;let o=this.px(t,2);if(!o||this.anchors.length<3)return {segments:[[n[0],n[1],i[0],i[1]]],fill:null};let s=i[0]-n[0],a=i[1]-n[1],l=Math.hypot(s,a);if(l<1e-6)return {segments:[[n[0],n[1],i[0],i[1]]],fill:null};let c=-a/l,d=s/l,u=(o[0]-n[0])*c+(o[1]-n[1])*d,h=c*u,p=d*u,m=n,f=i,g=[i[0]+h,i[1]+p],b=[n[0]+h,n[1]+p];return {segments:[[m[0],m[1],f[0],f[1]],[f[0],f[1],g[0],g[1]],[g[0],g[1],b[0],b[1]],[b[0],b[1],m[0],m[1]]],fill:[m,f,g,b]}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B.map(t=>({...t,label:t.label.replace("Line","Border")})),...ue,...H]}}};var la=class extends In{constructor(){super(...arguments);this.type="path";}};var Jp=40,ca=class extends he{constructor(){super(...arguments);this.type="arc";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"apex",free:"both"}]}}pinApex(){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[2];t&&n&&i&&(i.time=(t.time+n.time)/2);}onPlaced(){this.pinApex();}constrainHandleDrag(){this.pinApex();}px(t,n){let i=this.anchors[n];if(!i)return null;let o=t.yOf(i.price,this.paneId);return o==null?null:[t.xOf(i.time),o]}geometry(t){let n=this.px(t,0),i=this.px(t,1);if(!n||!i)return null;let o=this.anchors[2];if(!o||this.anchors.length<3)return {segments:[[n[0],n[1],i[0],i[1]]],fill:null};let s=t.yOf(o.price,this.paneId);if(s==null)return null;let a=(n[0]+i[0])/2,l=(n[1]+i[1])/2,c=(i[0]-n[0])/2,d=(i[1]-n[1])/2,u=Math.hypot(c,d);if(u<1e-6)return {segments:[[n[0],n[1],i[0],i[1]]],fill:null};let h=-d/u,p=c/u,m=(s-l)*p;m<0&&(h=-h,p=-p);let f=Math.abs(m),g=[];for(let y=0;y<=Jp;y+=1){let v=y/Jp*Math.PI,S=Math.cos(v),P=Math.sin(v);g.push([a+S*c+P*f*h,l+S*d+P*f*p]);}let b=[];for(let y=1;y<g.length;y+=1)b.push([g[y-1][0],g[y-1][1],g[y][0],g[y][1]]);return b.push([g[g.length-1][0],g[g.length-1][1],g[0][0],g[0][1]]),{segments:b,fill:g}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B.map(t=>({...t,label:t.label.replace("Line","Border")})),...ue,...H]}}};var Qp=40,da=class extends he{constructor(){super(...arguments);this.type="curve";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"control",free:"both"}]}}px(t,n){let i=this.anchors[n];if(!i)return null;let o=t.yOf(i.price,this.paneId);return o==null?null:[t.xOf(i.time),o]}geometry(t){let n=this.px(t,0),i=this.px(t,1);if(!n||!i)return null;let o=this.px(t,2);if(!o||this.anchors.length<3)return {segments:[[n[0],n[1],i[0],i[1]]],fill:null};let s=[];for(let l=0;l<=Qp;l+=1){let c=l/Qp,d=1-c;s.push([d*d*n[0]+2*d*c*o[0]+c*c*i[0],d*d*n[1]+2*d*c*o[1]+c*c*i[1]]);}let a=[];for(let l=1;l<s.length;l+=1)a.push([s[l-1][0],s[l-1][1],s[l][0],s[l][1]]);return {segments:a,fill:s}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...B,...ue,...H]}}};var r0={head:11,headW:9,stemW:3.5,len:22},rr=class extends G{anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}glyphPoints(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);if(n==null)return null;let i=e.xOf(t.time),{head:o,headW:s,stemW:a,len:l}=r0,c=[[0,0],[-s,o],[-a,o],[-a,l],[a,l],[a,o],[s,o]],d=this.dir(),u=([h,p])=>{switch(d){case "up":return [h,p];case "down":return [h,-p];case "left":return [p,h];default:return [-p,h]}};return c.map(h=>{let[p,m]=u(h);return [i+p,n+m]})}hitTest(e,t,n,i){let o=this.glyphPoints(n);return o!=null&&Vt(e,t,o)}handlePoints(e){let t=this.anchors[0];if(!t)return [];let n=e.yOf(t.price,this.paneId);return n==null?[]:[[e.xOf(t.time),n]]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.glyphPoints(e);if(!t)return null;let n=t.map(a=>a[0]),i=t.map(a=>a[1]),o=Math.min(...n),s=Math.min(...i);return {x:o,y:s,w:Math.max(...n)-o,h:Math.max(...i)-s}}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}schema(){return {fields:[{path:"style.lineColor",label:"Color",kind:"color",group:"line"},...H]}}},Gi=class extends rr{constructor(){super(...arguments);this.type="arrowmarkup";}dir(){return "up"}},Ui=class extends rr{constructor(){super(...arguments);this.type="arrowmarkdown";}dir(){return "down"}};var Xi=["\u2605","\u2606","\u25CF","\u25C6","\u25B2","\u25BC","\u27A4","\u2691","\u271A","\u2715","\u2764","\u2666"],ua=["small","normal","large","huge"],em={small:16,normal:22,large:32,huge:44},ir=class extends G{constructor(e){super(e),this.glyph||(this.glyph=this.defaultGlyph()),this.size||(this.size="normal");}sizePx(){return em[this.size]??em.normal}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}center(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);return n==null?null:[e.xOf(t.time),n]}hitTest(e,t,n,i){let o=this.center(n);if(!o)return false;let s=this.sizePx()/2+i;return Math.abs(e-o[0])<=s&&Math.abs(t-o[1])<=s}handlePoints(e){let t=this.center(e);return t?[t]:[]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.center(e);if(!t)return null;let n=this.sizePx();return {x:t[0]-n/2,y:t[1]-n/2,w:n,h:n}}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}schema(){return {fields:[{path:"glyph",label:"Icon",kind:"select",options:Xi.map(e=>({value:e,label:e})),group:"line"},{path:"size",label:"Size",kind:"select",options:ua.map(e=>({value:e,label:e})),group:"line"},{path:"style.lineColor",label:"Color",kind:"color",group:"line"},...H]}}writeProps(){return {glyph:this.glyph,size:this.size}}readProps(e){typeof e.glyph=="string"&&(this.glyph=e.glyph),typeof e.size=="string"&&(this.size=e.size);}},Yi=class extends ir{constructor(){super(...arguments);this.type="flagmark";}defaultGlyph(){return "\u2691"}},Ki=class extends ir{constructor(){super(...arguments);this.type="iconstamp";}defaultGlyph(){return "\u2605"}};var tm=r=>r==="small"||r==="normal"||r==="large"||r==="huge";function i0(r){if(!r||typeof r!="object")return null;let e=r;return typeof e.ratio!="number"||typeof e.color!="string"?null:{ratio:e.ratio,color:e.color,enabled:e.enabled!==false,...typeof e.label=="string"&&e.label?{label:e.label}:{}}}var me=class extends G{constructor(e){super(e),this.levels||(this.levels=this.defaultLevels().map(t=>({...t}))),this.numbersSize||(this.numbersSize="small"),this.labelsSize||(this.labelsSize="normal");}fillBands(e){return []}editableLevels(){return this.levels}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}hitTest(e,t,n,i){let o=this.entryLines(n);return o!=null&&o.some(s=>ne(e,t,s.x1,s.y1,s.x2,s.y2)<=i)}handlePoints(e){let t=[];for(let n of this.anchors){let i=e.yOf(n.price,this.paneId);if(i==null)return [];t.push([e.xOf(n.time),i]);}return t}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),i=t.map(a=>a[1]),o=Math.min(...n),s=Math.min(...i);return {x:o,y:s,w:Math.max(...n)-o,h:Math.max(...i)-s}}schema(){return {fields:B.filter(e=>e.path!=="style.lineColor")}}writeProps(){return {levels:this.levels.map(e=>({...e})),numbersSize:this.numbersSize,labelsSize:this.labelsSize}}readProps(e){if(Array.isArray(e.levels)){let t=e.levels.map(i0).filter(n=>n!=null);t.length&&(this.levels=t);}tm(e.numbersSize)&&(this.numbersSize=e.numbersSize),tm(e.labelsSize)&&(this.labelsSize=e.labelsSize);}};var $r=class extends me{levelLines(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=e.xOf(t.time),o=e.xOf(n.time),s=Math.min(i,o),a=Math.max(i,o),l=n.price-t.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let u=t.price+d.ratio*l,h=e.yOf(u,this.paneId);h!=null&&c.push({ratio:d.ratio,color:d.color,label:d.label,price:u,x1:s,x2:a,y:h});}return c}entryLines(e){let t=this.levelLines(e);return t?t.map(n=>({color:n.color,label:n.label,x1:n.x1,y1:n.y,x2:n.x2,y2:n.y,numberText:`${n.ratio} (${n.price.toFixed(2)})`,numberX:n.x1+4,numberY:n.y-7,numberAlign:"left",labelX:(n.x1+n.x2)/2,labelY:n.y-7})):null}fillBands(e){let t=this.levelLines(e);if(!t)return [];let n=[];for(let i=1;i<t.length;i+=1){let o=t[i-1],s=t[i];n.push({color:s.color,x:o.x1,y:Math.min(o.y,s.y),w:o.x2-o.x1,h:Math.abs(s.y-o.y)});}return n}priceRange(){let e=this.anchors[0],t=this.anchors[1];if(!e||!t)return null;let n=t.price-e.price,i=this.levels.filter(o=>o.enabled).map(o=>e.price+o.ratio*n);return i.length===0?null:{min:Math.min(...i),max:Math.max(...i)}}};var or=J,Bt=W,Ht=de,sr="#4caf50",An=z,cn=Je,ar="#9c27b0",o0="#e91e63",fd="#26a69a",s0="#ab47bc",a0="#ef5350",nm="#ffb74d",l0="#38c0fd",ha="#b2b5be",Wr=[l0,cn,An,sr,Ht,Bt,o0,ar,or,fd,s0,a0];function rm(r){return Wr[(r%Wr.length+Wr.length)%Wr.length]}var c0=[[0,or],[.125,Bt],[.236,Bt],[.25,Bt],[.382,Ht],[.5,sr],[.618,An],[.75,cn],[.786,cn],[1,or],[1.272,cn],[1.382,Ht],[1.618,Bt],[2,or],[2.382,Ht],[2.618,Ht],[3,or],[4.236,sr],[6.854,An],[11.09,cn]];function d0(r,e=0){return c0.find(([t])=>t===r)?.[1]??rm(e)}function pe(r){return r.map((e,t)=>{let n=typeof e=="number"?{ratio:e}:e;return {ratio:n.ratio,color:n.color??d0(n.ratio,t),enabled:n.enabled!==false,...n.label?{label:n.label}:{}}})}function im(r,e=r){return Array.from({length:r},(t,n)=>({ratio:n+1,color:rm(n),enabled:n<e,label:String(n+1)}))}var u0=pe([0,.236,.382,.5,.618,.786,1]),pa=class extends $r{constructor(){super(...arguments);this.type="fibretracement";}defaultLevels(){return u0}};var h0=pe([0,.382,.618,1,1.272,1.618,{ratio:2.618,color:ar}]),ma=class extends $r{constructor(){super(...arguments);this.type="fibextension";}defaultLevels(){return h0}};var p0=pe([0,.382,.5,.618,1,1.618,{ratio:2.618,color:ar}]),fa=class extends me{constructor(){super(...arguments);this.type="fibextensiontrend";}anchorSchema(){return {min:3,max:3,slots:[{role:"a",free:"both"},{role:"b",free:"both"},{role:"c",free:"both"}]}}defaultLevels(){return p0}entryLines(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return null;let s=i.price-n.price,a=[t.xOf(n.time),t.xOf(i.time),t.xOf(o.time)],l=Math.min(...a),c=Math.max(...a),d=[];for(let u of this.levels){if(!u.enabled)continue;let h=o.price+u.ratio*s,p=t.yOf(h,this.paneId);p!=null&&d.push({color:u.color,label:u.label,x1:l,y1:p,x2:c,y2:p,numberText:`${u.ratio} (${h.toFixed(2)})`,numberX:l+4,numberY:p-7,numberAlign:"left",labelX:(l+c)/2,labelY:p-7});}return d}priceRange(){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[2];if(!t||!n||!i)return null;let o=n.price-t.price,s=this.levels.filter(a=>a.enabled).map(a=>i.price+a.ratio*o);return s.push(t.price,n.price,i.price),{min:Math.min(...s),max:Math.max(...s)}}};var m0=pe([.236,.382,.5,.618,.786,1]),ga=class extends me{constructor(){super(...arguments);this.type="fibfan";}defaultLevels(){return m0}fanLines(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.xOf(n.time),s=t.yOf(n.price,this.paneId);if(s==null)return null;let a=t.xOf(i.time),l=i.price-n.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let u=t.yOf(n.price+d.ratio*l,this.paneId);if(u==null)continue;let[h,p,m,f]=xe(o,s,a,u,"right",t.width,t.height);c.push({ratio:d.ratio,color:d.color,label:d.label,x1:h,y1:p,x2:m,y2:f,labelX:a+5,labelY:u});}return c}entryLines(t){let n=this.fanLines(t);return n?n.map(i=>({color:i.color,label:i.label,x1:i.x1,y1:i.y1,x2:i.x2,y2:i.y2,numberText:String(i.ratio),numberX:i.labelX,numberY:i.labelY,numberAlign:"left",labelX:i.labelX,labelY:i.labelY+13})):null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var f0=[0,1,2,3,5,8,13,21,34].map(r=>({ratio:r,color:O,enabled:true})),ba=class extends me{constructor(){super(...arguments);this.type="fibtimezones";}defaultLevels(){return f0}zoneLines(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=i.time-n.time;if(Math.abs(o)<1e-9)return null;let s=[];for(let a of this.levels)a.enabled&&s.push({n:a.ratio,color:a.color,label:a.label,x:t.xOf(n.time+a.ratio*o)});return s}entryLines(t){let n=this.zoneLines(t);if(!n)return null;let i=t.height;return n.map(o=>({color:o.color,label:o.label,x1:o.x,y1:0,x2:o.x,y2:i,numberText:String(o.n),numberX:o.x,numberY:9,numberAlign:"center",labelX:o.x,labelY:24}))}priceRange(){return null}timeExtent(){return null}};var g0=pe([0,.236,.382,.5,.618,.786,1,1.618,2.618]),va=class extends me{constructor(){super(...arguments);this.type="fibchannel";}defaultLevels(){return g0}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"offset",free:"both"}]}}entryLines(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time),c=0,d=0,u=this.anchors[2];if(u){let p=t.yOf(u.price,this.paneId);if(p==null)return null;c=t.xOf(u.time)-a,d=p-o;}let h=[];for(let p of this.levels){if(!p.enabled)continue;let m=p.ratio*c,f=p.ratio*d,g=l+m,b=s+f;h.push({color:p.color,label:p.label,x1:a+m,y1:o+f,x2:g,y2:b,numberText:String(p.ratio),numberX:g+5,numberY:b,numberAlign:"left",labelX:g+5,labelY:b+13});}return h}priceRange(){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[2];if(!t||!n)return null;let o=i?i.price-t.price:0,s=1/0,a=-1/0;for(let l of this.levels)if(l.enabled)for(let c of [t.price,n.price]){let d=c+l.ratio*o;d<s&&(s=d),d>a&&(a=d);}return s<=a?{min:s,max:a}:null}};var b0=pe([0,.236,.382,.5,.618,.786,1]),ya=class extends me{constructor(){super(...arguments);this.type="fibspeedfan";}defaultLevels(){return b0}entryLines(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),c=t.xOf(i.time)-a,d=s-o,u=c>=0?"right":"left",h=t.width,p=t.height,m=[];for(let f of this.levels){if(!f.enabled)continue;let g=a+c,b=o+d*f.ratio,y=xe(a,o,g,b,u,h,p);if(m.push({color:f.color,label:f.label,x1:y[0],y1:y[1],x2:y[2],y2:y[3],numberText:String(f.ratio),numberX:u==="right"?g+5:g-5,numberY:b,numberAlign:u==="right"?"left":"right",labelX:g,labelY:b}),f.ratio===1)continue;let v=a+c*f.ratio,S=o+d,P=xe(a,o,v,S,u,h,p);m.push({color:f.color,label:f.label,x1:P[0],y1:P[1],x2:P[2],y2:P[3],numberText:String(f.ratio),numberX:v,numberY:S+(d>=0?12:-12),numberAlign:"center",labelX:v,labelY:S+12});}return m}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var v0=pe([0,.382,{ratio:.5,enabled:false},.618,1,1.382,1.618,2,2.382,2.618,3]),wa=class extends me{constructor(){super(...arguments);this.type="trendfibtime";}defaultLevels(){return v0}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"p3",free:"both"}]}}entryLines(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return null;let s=i.time-n.time;if(Math.abs(s)<1e-9)return null;let a=t.height,l=[];for(let c of this.levels){if(!c.enabled)continue;let d=t.xOf(o.time+c.ratio*s);l.push({color:c.color,label:c.label,x1:d,y1:0,x2:d,y2:a,numberText:String(c.ratio),numberX:d,numberY:9,numberAlign:"center",labelX:d,labelY:24});}return l}priceRange(){return null}timeExtent(){return null}};function y0(r,e,t){if(t-e>=Math.PI*2-.001)return true;let n=r-e,i=Math.PI*2;for(;n<0;)n+=i;for(;n>=i;)n-=i;return n<=t-e+1e-6}var Tt=class extends me{boundingLines(e){return []}entryLines(e){return []}hitTest(e,t,n,i){let o=this.radial(n);if(o){let s=Math.hypot(e-o.cx,t-o.cy),a=Math.atan2(t-o.cy,e-o.cx);if(y0(a,o.a0,o.a1)){for(let l of this.levels)if(l.enabled&&Math.abs(s-o.R0*l.ratio)<=i)return true}}return this.boundingLines(n).some(s=>ne(e,t,s[0],s[1],s[2],s[3])<=i)}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}};var w0=pe([.236,.382,.5,.618,.786,1,1.618,2.618]),xa=class extends Tt{constructor(){super(...arguments);this.type="fibcircles";}defaultLevels(){return w0}radial(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time);return {cx:a,cy:o,R0:Math.hypot(l-a,s-o),a0:0,a1:Math.PI*2}}};var x0=pe([.236,.382,.5,.618,.786,1,1.618,2.618]),Sa=class extends Tt{constructor(){super(...arguments);this.type="fibarcs";}defaultLevels(){return x0}pts(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?null:{cx:t.xOf(n.time),cy:o,ex:t.xOf(i.time),ey:s}}radial(t){let n=this.pts(t);if(!n)return null;let i=Math.hypot(n.ex-n.cx,n.ey-n.cy),o=Math.atan2(n.ey-n.cy,n.ex-n.cx);return {cx:n.cx,cy:n.cy,R0:i,a0:o-Math.PI/2,a1:o+Math.PI/2}}boundingLines(t){let n=this.pts(t);return n?[[n.cx,n.cy,n.ex,n.ey]]:[]}};var S0=pe([.236,.382,.5,.618,.786,1]),Ca=class extends Tt{constructor(){super(...arguments);this.type="fibwedge";}defaultLevels(){return S0}anchorSchema(){return {min:3,max:3,slots:[{role:"apex",free:"both"},{role:"radius",free:"both"},{role:"angle",free:"both"}]}}px(t,n){let i=this.anchors[n];if(!i)return null;let o=t.yOf(i.price,this.paneId);return o==null?null:[t.xOf(i.time),o]}radial(t){let n=this.px(t,0),i=this.px(t,1),o=this.px(t,2);if(!n||!i||!o)return null;let s=Math.hypot(i[0]-n[0],i[1]-n[1]);if(s<1)return null;let a=Math.atan2(i[1]-n[1],i[0]-n[0]),l=Math.atan2(o[1]-n[1],o[0]-n[0]),c=Math.min(a,l),d=Math.max(a,l);return d-c>Math.PI&&([c,d]=[d,c+Math.PI*2]),{cx:n[0],cy:n[1],R0:s,a0:c,a1:d}}boundingLines(t){let n=this.px(t,0),i=this.px(t,1);if(!n||!i)return [];let o=[[n[0],n[1],i[0],i[1]]],s=this.px(t,2);if(s){let a=Math.hypot(i[0]-n[0],i[1]-n[1]),l=Math.hypot(s[0]-n[0],s[1]-n[1]);l>1e-6&&o.push([n[0],n[1],n[0]+(s[0]-n[0])/l*a,n[1]+(s[1]-n[1])/l*a]);}return o}};var C0=1.6180339887,om=Math.log(C0)/(Math.PI/2),T0=Math.PI/64,E0=Math.PI,P0=.5,lr=class extends G{constructor(){super(...arguments);this.type="fibspiral";}anchorSchema(){return {min:2,max:2,slots:[{role:"center",free:"both"},{role:"edge",free:"both"}]}}spiralPoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time),c=Math.hypot(l-a,s-o);if(c<1)return null;let d=Math.atan2(s-o,l-a),u=Math.max(Math.log(P0/c)/om,-8*Math.PI*2),h=[];for(let p=u;p<=E0;p+=T0){let m=c*Math.exp(om*p),f=d+p;h.push([a+m*Math.cos(f),o+m*Math.sin(f)]);}return h}hitTest(t,n,i,o){let s=this.spiralPoints(i);return s!=null&&s.length>=2&&Hr(t,n,s)<=o}handlePoints(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return [];let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?[]:[[t.xOf(n.time),o],[t.xOf(i.time),s]]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.handlePoints(t);if(n.length<2)return null;let i=n.map(l=>l[0]),o=n.map(l=>l[1]),s=Math.min(...i),a=Math.min(...o);return {x:s,y:a,w:Math.max(...i)-s,h:Math.max(...o)-a}}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,...H]}}};var L0=pe([{ratio:.125,color:Bt,label:"1/8"},{ratio:.25,color:Ht,label:"1/4"},{ratio:.333,color:nm,label:"1/3"},{ratio:.5,color:sr,label:"1/2"},{ratio:1,color:ha,label:"1/1"},{ratio:2,color:An,label:"2/1"},{ratio:3,color:cn,label:"3/1"},{ratio:4,color:fd,label:"4/1"},{ratio:8,color:ar,label:"8/1"}]),Ta=class extends me{constructor(){super(...arguments);this.type="gannfan";}defaultLevels(){return L0}entryLines(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.xOf(n.time),s=t.yOf(n.price,this.paneId);if(s==null)return null;let a=t.xOf(i.time),l=i.price-n.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let u=t.yOf(n.price+l*d.ratio,this.paneId);if(u==null)continue;let[h,p,m,f]=xe(o,s,a,u,"right",t.width,t.height);c.push({color:d.color,x1:h,y1:p,x2:m,y2:f,numberText:d.label??String(d.ratio),numberX:a+5,numberY:u,numberAlign:"left",labelX:a+5,labelY:u});}return c}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var M0=pe([0,.25,.382,.5,.618,.75,1].map(r=>({ratio:r,label:String(r)}))),Ea=class extends me{constructor(){super(...arguments);this.type="gannbox";}defaultLevels(){return M0}corners(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.xOf(n.time),s=t.xOf(i.time),a=t.yOf(n.price,this.paneId),l=t.yOf(i.price,this.paneId);return a==null||l==null?null:{c1:n,c2:i,left:Math.min(o,s),right:Math.max(o,s),top:Math.min(a,l),bot:Math.max(a,l)}}entryLines(t){let n=this.corners(t);if(!n)return null;let{c1:i,c2:o,left:s,right:a,top:l,bot:c}=n,d=[];for(let h of this.levels){if(!h.enabled)continue;let p=t.yOf(i.price+h.ratio*(o.price-i.price),this.paneId);p!=null&&d.push({color:h.color,x1:s,y1:p,x2:a,y2:p,numberText:h.label??String(h.ratio),numberX:s-5,numberY:p,numberAlign:"right",labelX:s,labelY:p});let m=t.xOf(i.time+h.ratio*(o.time-i.time));d.push({color:h.color,x1:m,y1:l,x2:m,y2:c,numberText:"",numberX:m,numberY:l,numberAlign:"center",labelX:m,labelY:l});}let u=this.levels.find(h=>h.ratio===1)?.color??or;return d.push({color:u,x1:s,y1:l,x2:a,y2:c,numberText:"",numberX:0,numberY:0,numberAlign:"left",labelX:0,labelY:0}),d.push({color:u,x1:s,y1:c,x2:a,y2:l,numberText:"",numberX:0,numberY:0,numberAlign:"left",labelX:0,labelY:0}),d}hitTest(t,n,i,o){let s=this.corners(i);return s!=null&&Fe(t,n,s.left,s.top,s.right,s.bot,o)}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var k0=pe([0,.25,.382,.5,.618,.75,1].map(r=>({ratio:r,label:String(r)}))),I0=[{label:"3x1",x:3,y:1,color:Bt},{label:"2x1",x:2,y:1,color:Ht},{label:"1x1",x:1,y:1,color:ha},{label:"1x2",x:1,y:2,color:An},{label:"1x3",x:1,y:3,color:cn}],gd=[{k:.25,color:Bt},{k:.5,color:Ht},{k:.75,color:sr},{k:1,color:An}],cr=class extends me{constructor(){super(...arguments);this.type="gannsquare";}defaultLevels(){return k0}box(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=t.xOf(n.time),l=t.xOf(i.time);return {ox:a,oy:o,bx:l-a,py:s-o,left:Math.min(a,l),top:Math.min(o,s),right:Math.max(a,l),bot:Math.max(o,s)}}arcGeom(t){let n=this.box(t);return n?{ox:n.ox,oy:n.oy,bx:n.bx,py:n.py}:null}entryLines(t){let n=this.box(t);if(!n)return null;let i=this.anchors[0],o=this.anchors[1],s=[];for(let a of this.levels){if(!a.enabled)continue;let l=t.yOf(i.price+a.ratio*(o.price-i.price),this.paneId);l!=null&&s.push({color:a.color,x1:n.left,y1:l,x2:n.right,y2:l,numberText:a.label??String(a.ratio),numberX:n.left-5,numberY:l,numberAlign:"right",labelX:n.left,labelY:l});let c=t.xOf(i.time+a.ratio*(o.time-i.time));s.push({color:a.color,x1:c,y1:n.top,x2:c,y2:n.bot,numberText:"",numberX:c,numberY:n.top,numberAlign:"center",labelX:c,labelY:n.top});}for(let a of I0){let l,c;a.x>a.y?(l=n.ox+n.bx,c=n.oy+a.y/a.x*n.py):(c=n.oy+n.py,l=n.ox+a.x/a.y*n.bx),s.push({color:a.color,x1:n.ox,y1:n.oy,x2:l,y2:c,numberText:a.label,numberX:l+4,numberY:c,numberAlign:"left",labelX:l+4,labelY:c});}return s}hitTest(t,n,i,o){let s=this.box(i);return s!=null&&Fe(t,n,s.left,s.top,s.right,s.bot,o)}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var bd=[4,8,12,16,24,32,48,64],A0=24,R0=.75;function sm(r,e){if(!Number.isInteger(r)||!Number.isInteger(e)||e<=0)return false;let t=r*r-1;return e%2===1?t%e===0:e%8===0?t%e!==0?false:t/e%2!==0:false}function am(r){let e=[];for(let t=0;t<r;t+=1)sm(t,r)&&e.push(t);return e}var dr=class extends G{constructor(t){super(t);this.type="dedekind";this.maxCurvature===void 0&&(this.maxCurvature=A0);}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}box(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);if(o==null||s==null)return null;let a=Math.min(t.xOf(n.time),t.xOf(i.time)),l=Math.max(t.xOf(n.time),t.xOf(i.time)),c=Math.min(o,s),d=Math.max(o,s),u=l-a,h=d-c;if(u<1||h<1)return null;let p=h,m=u/p;return {left:a,right:l,top:c,bot:d,unitPx:p,x0:0,realSpan:m}}geodesics(t){let n=this.box(t);if(!n)return null;let{left:i,top:o,bot:s,unitPx:a,x0:l,realSpan:c}=n,d=Math.max(1,Math.min(64,Math.round(this.maxCurvature))),u=l-1/d,h=l+c+1/d,p=i+c*a,m=[],f=Math.floor(u*2),g=Math.ceil(h*2);for(let b=f;b<=g;b+=1){if(b%2===0)continue;let y=i+(b/2-l)*a;y<i-.5||y>p+.5||m.push({kind:"vline",x:y,y0:s,y1:o});}for(let b=1;b<=d;b+=1){let y=1/b,v=y*a;if(v<R0)continue;let S=am(b);if(S.length===0)continue;let P=Math.floor(u)-1,T=Math.ceil(h)+1;for(let E=P;E<=T;E+=1)for(let x of S){let L=x/b+E;if(L+y<u||L-y>h)continue;let w=i+(L-l)*a;w+v<i-1||w-v>p+1||m.push({kind:"arc",cx:w,cy:s,r:v});}}return m}hitTest(t,n,i,o){let s=this.box(i);return s!=null&&Fe(t,n,s.left,s.top,s.right,s.bot,o)}handlePoints(t){let n=this.box(t);return n?[[n.left,n.top],[n.right,n.bot]]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.box(t);return n?{x:n.left,y:n.top,w:n.right-n.left,h:n.bot-n.top}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...B,{path:"maxCurvature",label:"Max curvature",kind:"number",min:4,max:64,step:4,group:"behavior"},...H]}}writeProps(){return {maxCurvature:this.maxCurvature}}readProps(t){typeof t.maxCurvature=="number"&&Number.isFinite(t.maxCurvature)&&(this.maxCurvature=Math.max(1,Math.min(64,Math.round(t.maxCurvature))));}};var vd=[3,4,5,6,8,10,12],yd=[1.5,2,2.5,3,4,5],Pa=6,D0=2;function wd(r=Pa){return [...im(Wr.length,r)]}function O0(r){if(!r||typeof r!="object")return null;let e=r;return typeof e.ratio!="number"||typeof e.color!="string"?null:{ratio:e.ratio,color:e.color,enabled:e.enabled!==false,...typeof e.label=="string"&&e.label?{label:e.label}:{}}}var Gr={path:"showRatios",label:"Show ratios",kind:"boolean",group:"behavior"},Qe=class extends G{constructor(e){super(e),this.waveCount===void 0&&(this.waveCount=Pa),this.showRatios===void 0&&(this.showRatios=true);let t=Array.isArray(e.props?.levels);this.levels||(this.levels=this.defaultLevels().map(n=>({...n}))),!t&&this.shouldSyncWaveCount()&&this.syncLevelsToWaveCount();}shouldSyncWaveCount(){return true}syncLevelsToWaveCount(){let e=Math.max(1,Math.min(this.levels.length,Math.round(this.waveCount)));this.waveCount=e;for(let t=0;t<this.levels.length;t+=1)this.levels[t].enabled=t<e;}editableLevels(){return this.levels}anchorSchema(){return {min:2,max:2,slots:[{role:"d1",free:"both"},{role:"d2",free:"both"}]}}geom(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=e.yOf(t.price,this.paneId),o=e.yOf(n.price,this.paneId);if(i==null||o==null)return null;let s=e.xOf(t.time),a=e.xOf(n.time),l=(s+a)/2,c=(i+o)/2,d=Math.hypot(a-s,o-i)/2;if(d<1)return null;let u=a-s,h=o-i,p=Math.hypot(u,h);p<1e-9?(u=1,h=0):(u/=p,h/=p);let m=this.levels.filter(T=>T.enabled&&T.ratio>0).slice().sort((T,E)=>T.ratio-E.ratio);if(m.length===0)return null;let f=Math.max(1,this.machNumber()),g=[];for(let T of m){let E=T.ratio*d;g.push({cx:l+f*(E-d)*u,cy:c+f*(E-d)*h,r:E,color:T.color,ratio:T.ratio});}let b=l-f*d*u,y=c-f*d*h,v=g[g.length-1].r,S=f*v+2*d,P=[];if(f<=1+1e-9){let T=-h,E=u;P.push([b-T*S,y-E*S,b+T*S,y+E*S]);}else {let T=Math.asin(1/f),E=Math.cos(T),x=Math.sin(T),L=(A,$,ie)=>[A*E-$*ie*x,A*ie*x+$*E],[w,M]=L(u,h,1),[k,C]=L(u,h,-1);P.push([b,y,b+w*S,y+M*S]),P.push([b,y,b+k*S,y+C*S]);}return {c0x:l,c0y:c,R:d,fx:u,fy:h,noseX:b,noseY:y,circles:g,rays:P}}hitTest(e,t,n,i){let o=this.geom(n);if(!o)return false;for(let s of o.circles)if(Math.abs(Math.hypot(e-s.cx,t-s.cy)-s.r)<=i)return true;return o.rays.some(s=>ne(e,t,s[0],s[1],s[2],s[3])<=i)}handlePoints(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return [];let i=e.yOf(t.price,this.paneId),o=e.yOf(n.price,this.paneId);return i==null||o==null?[]:[[e.xOf(t.time),i],[e.xOf(n.time),o]]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.geom(e);if(!t)return null;let n=t.noseX,i=t.noseX,o=t.noseY,s=t.noseY;for(let a of t.circles)n=Math.min(n,a.cx-a.r),i=Math.max(i,a.cx+a.r),o=Math.min(o,a.cy-a.r),s=Math.max(s,a.cy+a.r);for(let a of t.rays)n=Math.min(n,a[0],a[2]),i=Math.max(i,a[0],a[2]),o=Math.min(o,a[1],a[3]),s=Math.max(s,a[1],a[3]);return {x:n,y:o,w:i-n,h:s-o}}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}applySettings(e){if(super.applySettings(e),Object.prototype.hasOwnProperty.call(e,"waveCount")&&typeof this.waveCount=="number"){let t=Math.max(1,Math.min(this.levels.length,Math.round(this.waveCount)));this.waveCount=t;for(let n=0;n<this.levels.length;n+=1)this.levels[n].enabled=n<t;}}schema(){return {fields:[...B,{path:"waveCount",label:"Waves",kind:"number",min:3,max:12,step:1,group:"behavior"},Gr,...H]}}writeProps(){return {waveCount:this.waveCount,showRatios:this.showRatios,levels:this.levels.map(e=>({...e}))}}readProps(e){if(typeof e.waveCount=="number"&&Number.isFinite(e.waveCount)&&(this.waveCount=Math.max(2,Math.min(12,Math.round(e.waveCount)))),typeof e.showRatios=="boolean"&&(this.showRatios=e.showRatios),Array.isArray(e.levels)){let t=e.levels.map(O0).filter(n=>n!=null);t.length&&(this.levels=t);}}},ji=class extends Qe{constructor(){super(...arguments);this.type="sonic";}defaultLevels(){return wd(Pa)}machNumber(){return 1}},qi=class extends Qe{constructor(t){super(t);this.type="supersonic";this.mach===void 0&&(this.mach=D0);}defaultLevels(){return wd(Pa)}machNumber(){return Math.max(1.01,this.mach)}schema(){return {fields:[...B,{path:"mach",label:"Mach number",kind:"number",min:1.5,max:5,step:.5,group:"behavior"},{path:"waveCount",label:"Waves",kind:"number",min:3,max:12,step:1,group:"behavior"},Gr,...H]}}writeProps(){return {...super.writeProps(),mach:this.mach}}readProps(t){super.readProps(t),typeof t.mach=="number"&&Number.isFinite(t.mach)&&(this.mach=Math.max(1.01,Math.min(20,t.mach)));}};var lm=pe([.236,.382,.5,.618,.786,1,1.618,2.618,4.236,6.854,11.09]),N0=2,La=class extends Qe{constructor(){super(...arguments);this.type="goldensonic";}shouldSyncWaveCount(){return false}defaultLevels(){return lm}machNumber(){return 1}schema(){return {fields:[...B,Gr,...H]}}},Ma=class extends Qe{constructor(t){super(t);this.type="goldensupersonic";this.mach===void 0&&(this.mach=N0);}shouldSyncWaveCount(){return false}defaultLevels(){return lm}machNumber(){return Math.max(1.01,this.mach)}schema(){return {fields:[...B,{path:"mach",label:"Mach number",kind:"number",min:1.5,max:5,step:.5,group:"behavior"},Gr,...H]}}writeProps(){return {...super.writeProps(),mach:this.mach}}readProps(t){super.readProps(t),typeof t.mach=="number"&&Number.isFinite(t.mach)&&(this.mach=Math.max(1.01,Math.min(20,t.mach)));}};var Oe=class extends G{legRatios(){return false}fillTriangles(){return []}necklineIndices(){return null}anchorSchema(){let e=this.vertexLabels().length,t=[];for(let n=0;n<e;n+=1)t.push({role:`p${n}`,free:"both"});return {min:e,max:e,slots:t}}handlePoints(e){let t=[];for(let n of this.anchors){let i=e.yOf(n.price,this.paneId);if(i==null)return [];t.push([e.xOf(n.time),i]);}return t}hitTest(e,t,n,i){let o=this.handlePoints(n);return o.length>=2&&Hr(e,t,o)<=i}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),i=t.map(a=>a[1]),o=Math.min(...n),s=Math.min(...i);return {x:o,y:s,w:Math.max(...n)-o,h:Math.max(...i)-s}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}patternName(){return null}ratioOk(e){return null}valid(){return null}ratioAt(e){let t=this.anchors[e-2],n=this.anchors[e-1],i=this.anchors[e];if(!t||!n||!i)return null;let o=Math.abs(n.price-t.price);return o<1e-9?null:Math.abs(i.price-n.price)/o}schema(){return {fields:[...B,...this.fillTriangles().length?ue:[]]}}};var ka=class extends Oe{constructor(){super(...arguments);this.type="xabcd";}vertexLabels(){return ["X","A","B","C","D"]}legRatios(){return true}fillTriangles(){return [[0,1,2],[2,3,4]]}};var Ia=class extends Oe{constructor(){super(...arguments);this.type="abcd";}vertexLabels(){return ["A","B","C","D"]}legRatios(){return true}};var Aa=class extends Oe{constructor(){super(...arguments);this.type="elliottimpulse";}vertexLabels(){return ["1","2","3","4","5"]}};var Ra=class extends Oe{constructor(){super(...arguments);this.type="elliottcorrection";}vertexLabels(){return ["A","B","C"]}};var Da=class extends Oe{constructor(){super(...arguments);this.type="headshoulders";}vertexLabels(){return ["","LS","","H","","RS",""]}necklineIndices(){return [2,4]}};var et=class extends Oe{vertexLabels(){return ["X","A","B","C","D"]}legRatios(){return true}fillTriangles(){return [[0,1,2],[2,3,4]]}legValue(e){let[t,n,i,o,s]=this.anchors;if(!t||!n||!i||!o||!s)return null;let a=(u,h)=>Math.abs(h.price-u.price),l=a(t,n),c=a(n,i),d=a(i,o);switch(e){case "ab":return l<1e-9?null:c/l;case "bc":return c<1e-9?null:d/c;case "cd":return d<1e-9?null:a(o,s)/d;default:return l<1e-9?null:a(n,s)/l}}inBand(e,t){return e!=null&&e>=t.min&&e<=t.max}ratioOk(e){let t=this.ranges();return e===2?this.inBand(this.legValue("ab"),t.ab):e===3?this.inBand(this.legValue("bc"),t.bc):e===4?this.inBand(this.legValue("cd"),t.cd):null}valid(){if(this.anchors.length<5)return null;let e=this.ranges();return this.inBand(this.legValue("ab"),e.ab)&&this.inBand(this.legValue("bc"),e.bc)&&this.inBand(this.legValue("cd"),e.cd)&&this.inBand(this.legValue("ad"),e.ad)}};var Oa=class extends et{constructor(){super(...arguments);this.type="gartley";}patternName(){return "Gartley"}ranges(){return {ab:{min:.55,max:.68},bc:{min:.382,max:.886},cd:{min:1.13,max:1.618},ad:{min:.74,max:.83}}}};var Na=class extends et{constructor(){super(...arguments);this.type="bat";}patternName(){return "Bat"}ranges(){return {ab:{min:.382,max:.5},bc:{min:.382,max:.886},cd:{min:1.618,max:2.618},ad:{min:.84,max:.92}}}};var Fa=class extends et{constructor(){super(...arguments);this.type="butterfly";}patternName(){return "Butterfly"}ranges(){return {ab:{min:.74,max:.83},bc:{min:.382,max:.886},cd:{min:1.618,max:2.618},ad:{min:1.272,max:1.618}}}};var Va=class extends et{constructor(){super(...arguments);this.type="crab";}patternName(){return "Crab"}ranges(){return {ab:{min:.382,max:.618},bc:{min:.382,max:.886},cd:{min:2.618,max:3.618},ad:{min:1.55,max:1.69}}}};var _a=class extends et{constructor(){super(...arguments);this.type="shark";}patternName(){return "Shark"}ranges(){return {ab:{min:.382,max:.618},bc:{min:1.13,max:1.618},cd:{min:1.618,max:2.24},ad:{min:.886,max:1.13}}}};var F0={min:1.272,max:1.414},V0={min:.74,max:.83},Ba=class extends et{constructor(){super(...arguments);this.type="cypher";}patternName(){return "Cypher"}ranges(){return {ab:{min:.382,max:.618},bc:{min:0,max:1/0},cd:{min:0,max:1/0},ad:{min:0,max:1/0}}}xcOverXa(){let t=this.anchors[0],n=this.anchors[1],i=this.anchors[3];if(!t||!n||!i)return null;let o=Math.abs(n.price-t.price);return o<1e-9?null:Math.abs(i.price-t.price)/o}cdOverXc(){let t=this.anchors[0],n=this.anchors[3],i=this.anchors[4];if(!t||!n||!i)return null;let o=Math.abs(n.price-t.price);return o<1e-9?null:Math.abs(i.price-n.price)/o}ratioOk(t){return t===2?this.inBand(this.legValue("ab"),this.ranges().ab):null}valid(){return this.anchors.length<5?null:this.inBand(this.legValue("ab"),this.ranges().ab)&&this.inBand(this.xcOverXa(),F0)&&this.inBand(this.cdOverXc(),V0)}};function cm(r){return `${r>=0?"+":""}${r.toFixed(2)}`}function Zi(r){let e=Math.abs(r),t=864e5,n=36e5,i=6e4;if(e>=t){let o=Math.floor(e/t),s=Math.round(e%t/n);return s?`${o}d ${s}h`:`${o}d`}if(e>=n){let o=Math.floor(e/n),s=Math.round(e%n/i);return s?`${o}h ${s}m`:`${o}h`}return e>=i?`${Math.round(e/i)}m`:`${Math.round(e/1e3)}s`}var ur=class extends G{constructor(e){super(e),this.showPrice===void 0&&(this.showPrice=true),this.showDate===void 0&&(this.showDate=true);}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}measureLabel(e){let t=[];return this.showPrice&&t.push(this.priceLabel()),this.showDate&&t.push(this.timeLabel(e)),t}isUp(){let e=this.anchors[0],t=this.anchors[1];return e!=null&&t!=null&&t.price>=e.price}priceLabel(){let e=this.anchors[0],t=this.anchors[1];if(!e||!t)return "";let n=t.price-e.price,i=e.price!==0?n/e.price*100:0;return `${cm(n)} (${cm(i)}%)`}timeLabel(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return "";let i=Zi(n.time-t.time),o=e.barsBetween?Math.round(e.barsBetween(t.time,n.time)):null;return o!=null?`${o} bars, ${i}`:i}rect(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let i=e.yOf(t.price,this.paneId),o=e.yOf(n.price,this.paneId);return i==null||o==null?null:{x1:e.xOf(t.time),y1:i,x2:e.xOf(n.time),y2:o}}hitTest(e,t,n,i){let o=this.rect(n);return o!=null&&Fe(e,t,o.x1,o.y1,o.x2,o.y2,i)}handlePoints(e){let t=this.rect(e);return t?[[t.x1,t.y1],[t.x2,t.y2]]:[]}hitHandle(e,t,n,i){return Y(e,t,this.handlePoints(n),i+3)}bounds(e){let t=this.rect(e);return t?{x:Math.min(t.x1,t.x2),y:Math.min(t.y1,t.y2),w:Math.abs(t.x2-t.x1),h:Math.abs(t.y2-t.y1)}:null}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[{path:"showPrice",label:"Show price",kind:"boolean",group:"behavior"},{path:"showDate",label:"Show date",kind:"boolean",group:"behavior"},...B.filter(e=>e.path!=="style.lineColor"),{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Ct,group:"text"}]}}writeProps(){return {showPrice:this.showPrice,showDate:this.showDate}}readProps(e){typeof e.showPrice=="boolean"&&(this.showPrice=e.showPrice),typeof e.showDate=="boolean"&&(this.showDate=e.showDate);}};var Ha=class extends ur{constructor(){super(...arguments);this.type="datepricerange";}};var za=[{value:"long",label:"Long"},{value:"short",label:"Short"}],Ee=class Ee extends G{constructor(t){super(t);this.type="position";this.riskPercent===void 0&&(this.riskPercent=Ee.DEFAULT_RISK_PERCENT),this.accountBalance===void 0&&(this.accountBalance=Ee.DEFAULT_ACCOUNT_BALANCE),this.showText===void 0&&(this.showText=true),this.showHeader===void 0&&(this.showHeader=true),this.showPrices===void 0&&(this.showPrices=false),this.showLossSize===void 0&&(this.showLossSize=true),this.showTargetLabel===void 0&&(this.showTargetLabel=true),this.showStopLabel===void 0&&(this.showStopLabel=true),this.profitColor===void 0&&(this.profitColor=Ee.DEFAULT_PROFIT_COLOR),this.lossColor===void 0&&(this.lossColor=Ee.DEFAULT_LOSS_COLOR);}directionLabel(){let t=this.prices();return t&&t.target>=t.entry?"LONG":"SHORT"}get direction(){return this.directionLabel()==="LONG"?"long":"short"}set direction(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];!n||!i||!o||(t==="long"||t==="short")&&t!==this.direction&&(i.price=2*n.price-i.price,o.price=2*n.price-o.price);}get quantity(){return this.positionSize()}set quantity(t){let n=this.prices();if(!n||!Number.isFinite(t)||t<0)return;let i=Math.abs(n.entry-n.stop);i<1e-9||this.accountBalance<=0||(this.riskPercent=t*i/this.accountBalance*100);}get entryPrice(){return this.anchors[0]?.price??0}set entryPrice(t){let n=this.anchors[0];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(0));}get stopPrice(){return this.anchors[1]?.price??0}set stopPrice(t){let n=this.anchors[1];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(1));}get targetPrice(){return this.anchors[2]?.price??0}set targetPrice(t){let n=this.anchors[2];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(2));}anchorSchema(){return {min:2,max:2,slots:[{role:"entry",free:"both"},{role:"stop",free:"both"},{role:"target",free:"both"}]}}onPlaced(t){let n=this.anchors[0];if(!n)return;let i=t.xOf(n.time),o=t.yOf(n.price,this.paneId);if(o==null)return;let s=this.anchors[1],a=s?t.yOf(s.price,this.paneId):null,l,c;s&&a!=null&&Math.abs(a-o)>=Ee.MIN_DRAG_PX?(l=a,c=i+Math.max(Math.abs(t.xOf(s.time)-i),Ee.MIN_WIDTH_PX)):(l=o-Ee.DEFAULT_RISK_PX*Ee.DEFAULT_RR,c=i+Ee.DEFAULT_WIDTH_PX);let d=o-(l-o)/Ee.DEFAULT_RR,u=t.pxToPoint(c,o,this.paneId).time;this.anchors=[{time:n.time,price:n.price},{time:u,price:t.pxToPoint(i,d,this.paneId).price},{time:u,price:t.pxToPoint(i,l,this.paneId).price}];}constrainHandleDrag(t){let n=this.anchors[0],i=this.anchors[1],o=this.anchors[2];if(!n||!i||!o)return;let s=Math.sign(i.price-n.price),a=Math.sign(o.price-n.price);s===0||a===0||s!==a||(t===2?i.price=2*n.price-i.price:o.price=2*n.price-o.price);}resolved(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;if(this.anchors[2])return [t,n,this.anchors[2]];let i={time:n.time,price:t.price-(n.price-t.price)/Ee.DEFAULT_RR};return [t,i,n]}prices(){let t=this.resolved();return t?{entry:t[0].price,stop:t[1].price,target:t[2].price}:null}rr(){let t=this.prices();if(!t)return 0;let n=Math.abs(t.entry-t.stop);return n<1e-9?0:Math.abs(t.target-t.entry)/n}rewardPct(){let t=this.prices();return t&&t.entry!==0?Math.abs(t.target-t.entry)/t.entry*100:0}riskPct(){let t=this.prices();return t&&t.entry!==0?Math.abs(t.entry-t.stop)/t.entry*100:0}dollarLoss(){return Math.max(0,this.accountBalance)*(Math.max(0,this.riskPercent)/100)}positionSize(){let t=this.prices();if(!t)return 0;let n=Math.abs(t.entry-t.stop);return n<1e-9?0:this.dollarLoss()/n}headerLabel(){return `${this.directionLabel()} \xB7 R:R ${this.rr().toFixed(2)}`}lossSizeLabel(){return `Loss $${_0(this.dollarLoss())} \xB7 Size ${B0(this.positionSize())}`}targetLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${dm(t.target)}`:"";return `Target +${this.rewardPct().toFixed(2)}%${n}`}stopLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${dm(t.stop)}`:"";return `Stop \u2212${this.riskPct().toFixed(2)}%${n}`}levelDisplayValue(t,n){let i=this.prices();if(!i)return 0;let o=t==="stop"?i.stop:i.target;return um(n==="price"?o:Math.abs(o-i.entry))}levelPriceFromDisplay(t,n,i){let o=this.prices();if(!o||n==="price")return i;let s=t==="stop"?o.stop:o.target,a=Math.sign(s-o.entry);return a===0&&(a=(t==="target"?1:-1)*(this.direction==="long"?1:-1)),o.entry+a*Math.abs(i)}box(t){let n=this.handlePoints(t);if(n.length<3)return null;let i=n.map(o=>o[0]);return {x1:Math.min(...i),x2:Math.max(...i),ey:n[0][1],sy:n[1][1],ty:n[2][1]}}layout(t){return this.box(t)}hitTest(t,n,i,o){let s=this.box(i);if(!s)return false;let a=Math.min(s.ey,s.sy,s.ty),l=Math.max(s.ey,s.sy,s.ty);return Fe(t,n,s.x1,a,s.x2,l,o)}handlePoints(t){let n=this.resolved();if(!n)return [];let i=[];for(let o of n){let s=t.yOf(o.price,this.paneId);if(s==null)return [];i.push([t.xOf(o.time),s]);}return i}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.box(t);if(!n)return null;let i=Math.min(n.ey,n.sy,n.ty);return {x:n.x1,y:i,w:n.x2-n.x1,h:Math.max(n.ey,n.sy,n.ty)-i}}priceRange(){let t=this.resolved();if(!t)return null;let n=t.map(i=>i.price);return {min:Math.min(...n),max:Math.max(...n)}}schema(){return {fields:[{path:"riskPercent",label:"Risk %",kind:"number",min:0,max:100,step:.1,group:"behavior"},{path:"accountBalance",label:"Account balance",kind:"number",min:0,max:1e12,step:1,group:"behavior"},{path:"quantity",label:"Position size",kind:"number",group:"behavior"},{path:"direction",label:"Direction",kind:"select",options:za,group:"behavior"},{path:"entryPrice",label:"Entry price",kind:"number",group:"behavior"},{path:"stopPrice",label:"Stop price",kind:"number",group:"behavior"},{path:"targetPrice",label:"Target price",kind:"number",group:"behavior"},{path:"showText",label:"Show text",kind:"boolean",group:"behavior"},{path:"showHeader",label:"Show direction & ratio",kind:"boolean",group:"behavior"},{path:"showLossSize",label:"Show loss & size",kind:"boolean",group:"behavior"},{path:"showTargetLabel",label:"Show target label",kind:"boolean",group:"behavior"},{path:"showStopLabel",label:"Show stop label",kind:"boolean",group:"behavior"},{path:"showPrices",label:"Show level prices",kind:"boolean",group:"behavior"},{path:"profitColor",label:"Profit zone",kind:"color",group:"fill"},{path:"lossColor",label:"Loss zone",kind:"color",group:"fill"},...B.filter(t=>t.path!=="style.lineColor"),{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Ct,group:"text"}]}}writeProps(){return {riskPercent:this.riskPercent,accountBalance:this.accountBalance,showText:this.showText,showHeader:this.showHeader,showPrices:this.showPrices,showLossSize:this.showLossSize,showTargetLabel:this.showTargetLabel,showStopLabel:this.showStopLabel,profitColor:this.profitColor,lossColor:this.lossColor}}readProps(t){typeof t.riskPercent=="number"&&Number.isFinite(t.riskPercent)&&(this.riskPercent=t.riskPercent),typeof t.accountBalance=="number"&&Number.isFinite(t.accountBalance)&&(this.accountBalance=t.accountBalance),typeof t.showText=="boolean"&&(this.showText=t.showText),typeof t.showHeader=="boolean"&&(this.showHeader=t.showHeader),typeof t.showPrices=="boolean"&&(this.showPrices=t.showPrices),typeof t.showLossSize=="boolean"&&(this.showLossSize=t.showLossSize),typeof t.showTargetLabel=="boolean"&&(this.showTargetLabel=t.showTargetLabel),typeof t.showStopLabel=="boolean"&&(this.showStopLabel=t.showStopLabel),typeof t.profitColor=="string"&&(this.profitColor=t.profitColor),typeof t.lossColor=="string"&&(this.lossColor=t.lossColor);}};Ee.DEFAULT_RR=2,Ee.MIN_DRAG_PX=6,Ee.DEFAULT_RISK_PX=64,Ee.DEFAULT_WIDTH_PX=150,Ee.MIN_WIDTH_PX=48,Ee.DEFAULT_RISK_PERCENT=1,Ee.DEFAULT_ACCOUNT_BALANCE=1e4,Ee.DEFAULT_PROFIT_COLOR=Ds,Ee.DEFAULT_LOSS_COLOR=Os;var ht=Ee;function _0(r){if(!Number.isFinite(r))return "0";let e=Math.round(r*100)/100;return Number.isInteger(e)?String(e):e.toFixed(2)}function B0(r){return !Number.isFinite(r)||r===0?"0":r>=100?r.toFixed(2):r>=1?r.toFixed(4).replace(/\.?0+$/,""):r.toPrecision(4).replace(/\.?0+$/,"")}function dm(r){return Number.isFinite(r)?Math.abs(r)>=1?r.toFixed(2):r.toPrecision(4).replace(/\.?0+$/,""):"0"}function um(r){return Math.round(r*1e8)/1e8}var hr=[{value:"auto",label:"Auto",ms:0},{value:"1",label:"1m",ms:6e4},{value:"5",label:"5m",ms:3e5},{value:"15",label:"15m",ms:9e5},{value:"30",label:"30m",ms:18e5},{value:"60",label:"1h",ms:36e5},{value:"240",label:"4h",ms:144e5},{value:"D",label:"1D",ms:864e5}];function Ji(r){let e=hr.find(n=>n.value===r);if(e)return e.label;let t=Number(r);return Number.isFinite(t)&&t>0?t%1440===0?`${t/1440}D`:t%60===0?`${t/60}h`:`${t}m`:r}function hm(){return {timeframe:"auto",upColor:"",downColor:""}}var tt=class extends G{constructor(t){super(t);this.type="magnifier";this.chipRect=null;this.magnifier||(this.magnifier=hm());}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}placementMode(){return "drag"}rect(t){let n=this.anchors[0],i=this.anchors[1];if(!n||!i)return null;let o=t.yOf(n.price,this.paneId),s=t.yOf(i.price,this.paneId);return o==null||s==null?null:{x1:t.xOf(n.time),y1:o,x2:t.xOf(i.time),y2:s}}hitTest(t,n,i,o){let s=this.rect(i);return s?Fe(t,n,s.x1,s.y1,s.x2,s.y2)?true:[[s.x1,s.y1,s.x2,s.y1],[s.x2,s.y1,s.x2,s.y2],[s.x2,s.y2,s.x1,s.y2],[s.x1,s.y2,s.x1,s.y1]].some(l=>ne(t,n,l[0],l[1],l[2],l[3])<=o):false}handlePoints(t){let n=this.rect(t);return n?[[n.x1,n.y1],[n.x2,n.y2]]:[]}hitHandle(t,n,i,o){return Y(t,n,this.handlePoints(i),o+3)}bounds(t){let n=this.rect(t);return n?{x:Math.min(n.x1,n.x2),y:Math.min(n.y1,n.y2),w:Math.abs(n.x2-n.x1),h:Math.abs(n.y2-n.y1)}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[{path:"magnifier.timeframe",label:"Timeframe",kind:"select",options:hr,group:"behavior"},...B.map(t=>({...t,label:t.label.replace("Line","Border")})),{path:"magnifier.upColor",label:"Up candles",kind:"color",group:"fill"},{path:"magnifier.downColor",label:"Down candles",kind:"color",group:"fill"}]}}writeProps(){return {...this.magnifier}}readProps(t){this.magnifier={...hm(),...t};}};var Qi=new Map;function V(r){Qi.set(r.type,r);}function Et(r){return Qi.get(r)}function $a(){return [...Qi.values()]}function Rn(r,e){let t=Qi.get(r);if(!t)return null;let n={...t.defaultStyle,...e.style??{}};return t.create({...e,style:n})}function Wa(r){let e=Rn(r.type,{paneId:r.paneId});if(!e)return;r.style={...e.style};let t=r.text?.value;e.text?(r.text={...e.text},t!==void 0&&(r.text.value=t)):r.text=void 0;let n=e.serialize().props;n!==void 0&&r.applyProps(n);}function pt(r){let e=Qi.get(r.type);return e?e.create(r):null}var H0=R('<line x1="4" y1="19" x2="20" y2="5"/>'),z0=R('<line x1="3" y1="12" x2="21" y2="12"/>');V({type:"trendline",group:"lines",label:"Trend Line",icon:H0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Vs(r)});V({type:"hline",group:"lines",label:"Horizontal Line",icon:z0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"dashed"},create:r=>new _s(r)});var $0=R('<line x1="3" y1="20" x2="21" y2="6"/><circle cx="3" cy="20" r="1.6" fill="currentColor"/>'),W0=R('<rect x="4" y="6" width="16" height="12" rx="1"/>'),G0=R('<path d="M5 6h14M12 6v13"/>');V({type:"ray",group:"lines",label:"Ray",icon:$0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Bs(r)});var U0=R('<path d="M5 19 19 5"/><path d="M5 19 8.5 19M5 19 5 15.5"/><path d="M19 5 15.5 5M19 5 19 8.5"/>'),Y0=R('<line x1="12" y1="3" x2="12" y2="21"/>'),K0=R('<line x1="5" y1="12" x2="21" y2="12"/><circle cx="5" cy="12" r="1.6" fill="currentColor"/>'),X0=R('<line x1="3" y1="12" x2="21" y2="12"/><line x1="12" y1="3" x2="12" y2="21"/>'),j0=R('<path d="M4 20 20 4"/><rect x="9" y="9" width="9" height="6" rx="1"/>'),q0=R('<path d="M4 20 20 6"/><path d="M4 20 15 20"/><path d="M11 20a7 7 0 0 0-2-4.9"/>');V({type:"extendedline",group:"lines",label:"Extended Line",icon:U0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Hs(r)});V({type:"vline",group:"lines",label:"Vertical Line",icon:Y0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new zs(r)});V({type:"hray",group:"lines",label:"Horizontal Ray",icon:K0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new $s(r)});V({type:"crossline",group:"lines",label:"Cross Line",icon:X0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ws(r)});V({type:"infoline",group:"lines",label:"Info Line",icon:j0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Gs(r)});V({type:"trendangle",group:"lines",label:"Trend Angle",icon:q0,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Us(r)});V({type:"box",group:"shapes",label:"Rectangle",icon:W0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}26`},create:r=>new Ys(r)});V({type:"text",group:"annotations",label:"Text",icon:G0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new an(r)});var Z0=R('<path d="M5 4h14a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-6l-5 5v-5H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z"/>');V({type:"callout",group:"annotations",label:"Callout",icon:Z0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new _t(r)});var J0=R('<path d="M5 4h14a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-7l-4 4v-4H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Z"/><path d="M8 8.5h8M8 12h5"/>'),Q0=R('<rect x="10" y="4.5" width="11" height="8" rx="1.5"/><path d="M10 8.5 4 16"/><circle cx="3.5" cy="16.5" r="1.6" fill="currentColor" stroke="none"/>'),eS=R('<path d="M5 4.5h14a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-7l-4 4v-4H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2Z"/>'),tS=R('<path d="M3 12 7 8h12a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H7Z"/><path d="M10.5 12.5h6" stroke-width="1.4"/>'),nS=R('<path d="M12 11.5V21"/><rect x="5" y="4" width="14" height="7" rx="1"/><path d="M9 7.5h6"/>');V({type:"note",group:"annotations",label:"Note",icon:J0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new Zn(r)});V({type:"pricenote",group:"annotations",label:"Price Note",icon:Q0,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new Qn(r)});V({type:"comment",group:"annotations",label:"Comment",icon:eS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new er(r)});V({type:"pricelabel",group:"annotations",label:"Price Label",icon:tS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new Jn(r)});V({type:"signpost",group:"annotations",label:"Signpost",icon:nS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid",fillColor:`${O}d9`},create:r=>new tr(r)});var rS=R('<line x1="3" y1="16" x2="21" y2="8"/><line x1="3" y1="21" x2="21" y2="13"/>'),iS=R('<line x1="3" y1="7" x2="21" y2="10"/><line x1="3" y1="18" x2="21" y2="14"/>'),oS=R('<circle cx="4" cy="12" r="1.6" fill="currentColor"/><line x1="4" y1="12" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>');V({type:"parallelchannel",group:"channels",label:"Parallel Channel",icon:rS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new Ks(r)});V({type:"disjointchannel",group:"channels",label:"Disjoint Channel",icon:iS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new Xs(r)});var sS=R('<line x1="3" y1="7" x2="21" y2="7"/><line x1="3" y1="18" x2="21" y2="11"/>');V({type:"flattopbottom",group:"channels",label:"Flat Top/Bottom",icon:sS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new js(r)});var aS=R('<line x1="3" y1="8" x2="21" y2="4"/><line x1="3" y1="16" x2="21" y2="12"/><line x1="3" y1="12" x2="21" y2="8" stroke-dasharray="3 3"/>');V({type:"regressionchannel",group:"channels",label:"Linear Regression",icon:aS,defaultStyle:{lineColor:J,lineWidth:1,lineStyle:"solid"},create:r=>new ln(r)});V({type:"pitchfork",group:"pitchforks",label:"Pitchfork",icon:oS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new qs(r)});var lS=R('<circle cx="4" cy="8" r="1.6" fill="currentColor"/><line x1="4" y1="8" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>'),cS=R('<circle cx="6" cy="9" r="1.6" fill="currentColor"/><line x1="6" y1="9" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>'),dS=R('<line x1="4" y1="12" x2="10" y2="12"/><line x1="10" y1="8" x2="10" y2="16"/><line x1="10" y1="8" x2="21" y2="8"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="16" x2="21" y2="16"/>');V({type:"schiffpitchfork",group:"pitchforks",label:"Schiff Pitchfork",icon:lS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Zs(r)});V({type:"modifiedschiffpitchfork",group:"pitchforks",label:"Modified Schiff Pitchfork",icon:cS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Js(r)});V({type:"insidepitchfork",group:"pitchforks",label:"Inside Pitchfork",icon:dS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new Qs(r)});var uS=R('<path d="M7 7h10v10"/><path d="M7 17 17 7"/>'),hS=R('<ellipse cx="12" cy="12" rx="9" ry="6"/>'),pS=R('<path d="M12 4 20 19 4 19Z"/>');V({type:"arrow",group:"shapes",label:"Arrow",icon:uS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",arrowRight:true},create:r=>new ea(r)});V({type:"ellipse",group:"shapes",label:"Ellipse",icon:hS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new ta(r)});V({type:"triangle",group:"shapes",label:"Triangle",icon:pS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new na(r)});var mS=R('<polyline points="3 17 9 10 13 14 21 5"/>'),fS=R('<path d="M9.5 12 17 4.5a2.12 2.12 0 0 1 3 3L12.5 15"/><path d="M7 14a3 3 0 0 0-3 3c0 1.3-1.2 1.5-1.5 2 .8.9 2 1.5 3.5 1.5a3.5 3.5 0 0 0 3.5-3.5 3 3 0 0 0-2.5-3Z"/>'),gS=R('<path d="M9 11 15 5l4 4-6 6H9Z"/><path d="M9 15l-2 2"/><path d="M4 21h6"/>');V({type:"polyline",group:"shapes",label:"Polyline",icon:mS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new ra(r)});V({type:"freehand",group:"shapes",label:"Brush",icon:fS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new ia(r)});V({type:"highlighter",group:"shapes",label:"Highlighter",icon:gS,defaultStyle:{lineColor:`${Ip}59`,lineWidth:14,lineStyle:"solid"},create:r=>new oa(r)});var bS=R('<circle cx="12" cy="12" r="8"/>'),vS=R('<path d="M5 14 9.5 5 19 10 14.5 19 Z"/>'),yS=R('<path d="M4 19 9 11 13 14 17 8 20 4"/><path d="M17.2 5.5 20 4 19.4 7.1"/>'),wS=R('<path d="M4 17a8 8 0 0 1 16 0"/><path d="M4 17 20 17"/>'),xS=R('<path d="M4 18Q12 1 20 14"/>'),SS=R('<path d="M12 5 12 19"/><path d="M6 11 12 5 18 11"/>'),CS=R('<path d="M12 5 12 19"/><path d="M6 13 12 19 18 13"/>');V({type:"circle",group:"shapes",label:"Circle",icon:bS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}1a`},create:r=>new sa(r)});V({type:"rotatedrect",group:"shapes",label:"Rotated Rectangle",icon:vS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}26`},create:r=>new aa(r)});V({type:"path",group:"shapes",label:"Path",icon:yS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new la(r)});V({type:"arc",group:"shapes",label:"Arc",icon:wS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid",fillColor:`${O}26`},create:r=>new ca(r)});V({type:"curve",group:"shapes",label:"Curve",icon:xS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new da(r)});V({type:"arrowmarkup",group:"shapes",label:"Arrow Mark Up",icon:SS,defaultStyle:{lineColor:z,lineWidth:1,lineStyle:"solid"},create:r=>new Gi(r)});V({type:"arrowmarkdown",group:"shapes",label:"Arrow Mark Down",icon:CS,defaultStyle:{lineColor:W,lineWidth:1,lineStyle:"solid"},create:r=>new Ui(r)});var TS=R('<path d="M6 21V4"/><path d="M6 5h11l-2.5 3.5L17 12H6" fill="currentColor" stroke="none"/>'),ES=R('<path d="m12 3 2.6 5.8 6.4.6-4.8 4.2 1.4 6.2L12 16.9 6.4 19.8 7.8 13.6 3 9.4l6.4-.6Z"/>');V({type:"flagmark",group:"stamps",label:"Flag",icon:TS,defaultStyle:{lineColor:Ye,lineWidth:1,lineStyle:"solid"},create:r=>new Yi(r)});V({type:"iconstamp",group:"stamps",label:"Icon",icon:ES,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ki(r)});var PS=R('<line x1="3" y1="5" x2="21" y2="5"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="3" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/>'),LS=R('<line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="11" x2="21" y2="11"/><line x1="3" y1="15" x2="14" y2="15"/><line x1="3" y1="20" x2="14" y2="20"/>');V({type:"fibretracement",group:"fibonacci",label:"Fib Retracement",icon:PS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new pa(r)});V({type:"fibextension",group:"fibonacci",label:"Fib Extension",icon:LS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ma(r)});var MS=R('<path d="M3 20 10 9l4 5"/><path d="M14 14h7M14 9h7M14 4h7"/>');V({type:"fibextensiontrend",group:"fibonacci",label:"Trend-Based Fib Extension",icon:MS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new fa(r)});var kS=R('<path d="M4 20 20 5M4 20 21 11M4 20 21 17M4 20 20 20"/>'),IS=R('<path d="M3 5v14M6 5v14M11 5v14M19 5v14"/>');V({type:"fibfan",group:"fibonacci",label:"Fib Fan",icon:kS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ga(r)});V({type:"fibtimezones",group:"fibonacci",label:"Fib Time Zones",icon:IS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"dashed"},create:r=>new ba(r)});var AS=R('<path d="M3 18 18 9M5 21 20 12M6 13 21 4"/>'),RS=R('<path d="M4 4 20 20M4 4 20 12M4 4 12 20M4 4 20 4M4 4 4 20"/>'),DS=R('<path d="M3 19 9 8M9 8 12 5v14M14 5v14M18 5v14M21 5v14"/>');V({type:"fibchannel",group:"fibonacci",label:"Fib Channel",icon:AS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new va(r)});V({type:"fibspeedfan",group:"fibonacci",label:"Fib Speed Resistance Fan",icon:RS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ya(r)});V({type:"trendfibtime",group:"fibonacci",label:"Trend-Based Fib Time",icon:DS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"dashed"},create:r=>new wa(r)});var OS=R('<circle cx="12" cy="12" r="3"/><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="10"/>'),NS=R('<path d="M8 20a4 4 0 0 1 8 0"/><path d="M4.5 20a7.5 7.5 0 0 1 15 0"/><circle cx="12" cy="20" r="1.4" fill="currentColor" stroke="none"/>'),FS=R('<path d="M4 20 20 16M4 20 14 4"/><path d="M11.8 18.1A8 8 0 0 0 8.2 13.2"/><path d="M16.6 16.9A13 13 0 0 0 10.9 9"/>'),VS=R('<path d="M13 12a2 2 0 1 1-2-2 4 4 0 0 1 4 4 6 6 0 0 1-9 5.2 9 9 0 0 1 .5-15"/>');V({type:"fibcircles",group:"fibonacci",label:"Fib Circles",icon:OS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new xa(r)});V({type:"fibarcs",group:"fibonacci",label:"Fib Speed Resistance Arcs",icon:NS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Sa(r)});V({type:"fibwedge",group:"fibonacci",label:"Fib Wedge",icon:FS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ca(r)});V({type:"fibspiral",group:"fibonacci",label:"Fib Spiral",icon:VS,defaultStyle:{lineColor:O,lineWidth:2,lineStyle:"solid"},create:r=>new lr(r)});var _S=R('<path d="M4 20 20 20M4 20 20 13M4 20 20 6M4 20 15 4M4 20 9 4M4 20 4 4"/>'),BS=R('<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 12h16M12 4v16M4 4 20 20" opacity="0.6"/>');V({type:"gannfan",group:"fibonacci",label:"Gann Fan",icon:_S,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ta(r)});V({type:"gannbox",group:"fibonacci",label:"Gann Box",icon:BS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ea(r)});var HS=R('<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 20 20 4M4 20 20 12M4 20 12 4" opacity="0.7"/><path d="M4 20a16 16 0 0 1 16-16" opacity="0.5"/>');V({type:"gannsquare",group:"fibonacci",label:"Gann Square",icon:HS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new cr(r)});var zS=R('<path d="M2 20h20"/><path d="M4 20a8 8 0 0 1 16 0" opacity="0.9"/><path d="M6 20a4 4 0 0 1 8 0" opacity="0.75"/><path d="M10 20a2 2 0 0 1 4 0" opacity="0.6"/><path d="M8 20v-6M12 20v-9M16 20v-6" opacity="0.45"/>');V({type:"dedekind",group:"geometry",label:"Dedekind Tessellation",icon:zS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new dr(r)});var $S=R('<circle cx="16" cy="12" r="5" opacity="0.55"/><circle cx="13" cy="12" r="3.5" opacity="0.75"/><circle cx="10.5" cy="12" r="2"/><path d="M8 4v16"/>'),WS=R('<circle cx="17" cy="12" r="4.5" opacity="0.45"/><circle cx="13" cy="12" r="3" opacity="0.7"/><circle cx="10" cy="12" r="1.6"/><path d="M6 12 16 5M6 12 16 19"/>');V({type:"sonic",group:"geometry",label:"Sonic",icon:$S,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ji(r)});V({type:"supersonic",group:"geometry",label:"Supersonic",icon:WS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new qi(r)});var GS=R('<circle cx="16" cy="12" r="5" opacity="0.4"/><circle cx="13" cy="12" r="3.2" opacity="0.65"/><circle cx="10.8" cy="12" r="1.8"/><path d="M8 4v16"/><path d="M15 8.5h2M12.5 10h2" opacity="0.5"/>'),US=R('<circle cx="17" cy="12" r="4.5" opacity="0.4"/><circle cx="12.5" cy="12" r="2.8" opacity="0.65"/><circle cx="9.8" cy="12" r="1.4"/><path d="M6 12 16 5M6 12 16 19"/>');V({type:"goldensonic",group:"geometry",label:"Golden Sonic",icon:GS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new La(r)});V({type:"goldensupersonic",group:"geometry",label:"Golden Supersonic",icon:US,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ma(r)});var YS=R('<path d="M3 18 7 8 11 14 15 6 20 16"/>'),KS=R('<path d="M4 17 9 7 14 15 20 5"/>'),XS=R('<path d="M3 19 8 9 12 13 17 5 21 9"/>'),jS=R('<path d="M4 7 11 16 20 9"/>'),qS=R('<path d="M3 18 6 12 9 16 12 5 15 16 18 12 21 18"/>');V({type:"xabcd",group:"patterns",label:"XABCD Pattern",icon:YS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ka(r)});V({type:"abcd",group:"patterns",label:"ABCD Pattern",icon:KS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ia(r)});V({type:"elliottimpulse",group:"patterns",label:"Elliott Impulse Wave (1-5)",icon:XS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Aa(r)});V({type:"elliottcorrection",group:"patterns",label:"Elliott Correction Wave (ABC)",icon:jS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ra(r)});V({type:"headshoulders",group:"patterns",label:"Head & Shoulders",icon:qS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Da(r)});var ZS=R('<path d="M3 17 7 6 12 14 17 5 21 16"/><path d="M3 17 21 16" opacity="0.45"/>'),Ur={group:"patterns",icon:ZS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"}};V({type:"gartley",label:"Gartley",...Ur,create:r=>new Oa(r)});V({type:"bat",label:"Bat",...Ur,create:r=>new Na(r)});V({type:"butterfly",label:"Butterfly",...Ur,create:r=>new Fa(r)});V({type:"crab",label:"Crab",...Ur,create:r=>new Va(r)});V({type:"shark",label:"Shark",...Ur,create:r=>new _a(r)});V({type:"cypher",label:"Cypher",...Ur,create:r=>new Ba(r)});var JS=R('<rect x="4" y="6" width="16" height="12" rx="1"/><path d="M4 18 20 6" opacity="0.5"/>');V({type:"datepricerange",group:"measure",label:"Date & Price Range",icon:JS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new Ha(r)});var QS=R('<rect x="4.5" y="4.5" width="15" height="7.5" rx="1" fill="currentColor" fill-opacity="0.25"/><rect x="4.5" y="12" width="15" height="7.5" rx="1"/>');V({type:"position",group:"measure",label:"Long/Short Position",icon:QS,defaultStyle:{lineColor:O,lineWidth:1,lineStyle:"solid"},create:r=>new ht(r)});var eC=R('<circle cx="10.5" cy="10.5" r="6.5"/><path d="m15.3 15.3 5.2 5.2"/><path d="M8 12.5v-3M10.5 13.5v-5.5M13 12v-2"/>');V({type:"magnifier",group:"measure",label:"Magnifier",icon:eC,defaultStyle:{lineColor:"",lineWidth:1,lineStyle:"solid"},coversSeries:true,placementHint:"Drag an area on the chart to view it at a lower timeframe",create:r=>new tt(r)});var tC=R('<line x1="5" y1="3" x2="5" y2="21"/><path d="M5 16c4 0 5-9 8-9s3 5 8 3"/>');V({type:"anchoredvwap",group:"measure",label:"Anchored VWAP",icon:tC,defaultStyle:{lineColor:Je,lineWidth:2,lineStyle:"solid"},create:r=>new nr(r)});var nC=R('<path d="M4 4v16"/><path d="M4 8h10"/><path d="M4 12h14"/><path d="M4 16h8"/><path d="M4 20h12"/>');V({type:"fixedrangevp",group:"measure",label:"Fixed Range Volume Profile",icon:nC,defaultStyle:{lineColor:z,lineWidth:1,lineStyle:"solid"},create:r=>new at(r)});var rC=["fibretracement","fibextension","fibextensiontrend","fibfan","fibtimezones","fibchannel","fibspeedfan","trendfibtime","fibcircles","fibarcs","fibwedge","fibspiral"],iC=["gannfan","gannbox","gannsquare"],oC=["dedekind","sonic","supersonic","goldensonic","goldensupersonic"],sC=["xabcd","abcd","headshoulders"],aC=["elliottimpulse","elliottcorrection"],lC=["gartley","bat","butterfly","crab","shark","cypher"],cC=["position","datepricerange","magnifier"],dC=["anchoredvwap","fixedrangevp"],uC=["freehand","highlighter"],hC=["arrow","arrowmarkup","arrowmarkdown"],pC=["box","ellipse","triangle","polyline","circle","rotatedrect","path","arc","curve"],mC=["text","callout","note","pricenote","comment","pricelabel","signpost"],fC=["flagmark","iconstamp"],gC=[{id:"lines-channels-pitchforks",label:"Lines",sections:[{label:"Lines",registryGroup:"lines"},{label:"Channels",registryGroup:"channels"},{label:"Pitchforks",registryGroup:"pitchforks"}]},{id:"fibonacci-gann",label:"Fibonacci",sections:[{label:"Fibonacci",types:rC},{label:"Gann",types:iC},{label:"Geometry",types:oC}]},{id:"patterns-waves-harmonics",label:"Patterns",sections:[{label:"Patterns",types:sC},{label:"Elliott Waves",types:aC},{label:"Harmonics",types:lC}]},{id:"measurements",label:"Measurements",sections:[{label:"Measurements",types:cC},{label:"Volume",types:dC}]},{id:"brushes-arrows-shapes",label:"Shapes",sections:[{label:"Brushes",types:uC},{label:"Arrows",types:hC},{label:"Shapes",types:pC}]},{id:"text",label:"Text",sections:[{label:"Text",types:mC}]},{id:"icons",label:"Icons",sections:[{label:"Icons",types:fC}]}];function bC(r){let e=Et(r);return e?{type:e.type,label:e.label,icon:e.icon}:null}function vC(r){let e=new Map;for(let t of $a()){if(r&&!r.has(t.type))continue;let n={type:t.type,label:t.label,icon:t.icon};e.has(t.group)||e.set(t.group,[]),e.get(t.group).push(n);}return e}function yC(r,e,t){return "registryGroup"in r?e.get(r.registryGroup)??[]:r.types.map(n=>t.get(n)).filter(n=>n!=null)}function pm(r){let e=vC(r),t=new Map;for(let i of e.values())for(let o of i)t.set(o.type,o);let n=[];for(let i of gC){let o=[],s=[];for(let a of i.sections){let l=yC(a,e,t);l.length!==0&&(o.push({label:a.label,tools:l}),s.push(...l));}s.length!==0&&n.push({id:i.id,label:i.label,tools:s,sections:o.length>0?o:void 0});}return {groups:n}}function wC(r){let e=new Set;for(let t of r)Et(t)&&e.add(t);return pm(e)}function xC(r){let e=[];for(let t of r){let n=t.tools.map(bC).filter(i=>i!=null);n.length>0&&e.push({id:t.id,label:t.label,tools:n});}return {groups:e}}function eo(){return pm()}function to(r){if(r===false)return {definition:eo(),visible:false};if(r===void 0||r===true)return {definition:eo(),visible:true};let e=r.toolbar??true;return r.groups?{definition:xC(r.groups),visible:e}:r.tools?{definition:wC(r.tools),visible:e}:{definition:eo(),visible:e}}function zt(r){let e=globalThis.structuredClone;return e?e(r):JSON.parse(JSON.stringify(r))}function mm(r){if(!r||typeof r!="object")return false;let e=r;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.paneId=="string"&&Array.isArray(e.anchors)&&e.anchors.every(t=>t&&typeof t.time=="number"&&typeof t.price=="number")&&!!e.style&&typeof e.style=="object"}function xd(r){let e=r;return !e||typeof e!="object"||e.version!==1||!Array.isArray(e.drawings)?{version:1,drawings:[]}:{version:1,drawings:e.drawings.filter(mm)}}var Yr=class{constructor(){this.byId=new Map;this.seq=0;this.zCounter=1;this.listeners=new Set;}nextId(){return this.seq+=1,`dw-${this.seq}`}add(e){return e.zIndex||(e.zIndex=this.zCounter),this.zCounter=Math.max(this.zCounter,Math.ceil(e.zIndex))+1,this.byId.set(e.id,e),this.emit(),e}remove(e){let t=this.byId.delete(e);return t&&this.emit(),t}get(e){return this.byId.get(e)}has(e){return this.byId.has(e)}update(e,t){let n=this.byId.get(e);return n?(t.anchors&&(n.anchors=t.anchors.map(i=>({time:i.time,price:i.price}))),t.style&&(n.style={...t.style}),t.text!==void 0&&(n.text=t.text?{...t.text}:void 0),t.paneId!==void 0&&(n.paneId=t.paneId),t.locked!==void 0&&(n.locked=t.locked),t.visible!==void 0&&(n.visible=t.visible),t.zIndex!==void 0&&(n.zIndex=t.zIndex),t.props!==void 0&&n.applyProps(t.props),this.emit(),n):null}all(){return [...this.byId.values()].sort((e,t)=>e.zIndex-t.zIndex)}byPane(e){return this.all().filter(t=>t.paneId===e)}bringToFront(e,t=0){let n=this.byId.get(e);n&&(n.zIndex=Math.max(this.zCounter,Math.floor(t)+1),this.zCounter=n.zIndex+1,this.emit());}sendToBack(e,t=1){let n=this.byId.get(e);if(!n)return;let i=Math.min(...[...this.byId.values()].map(o=>o.zIndex),Math.ceil(t));n.zIndex=i-1,this.emit();}setLocked(e,t){let n=this.byId.get(e);n&&(n.locked=t,this.emit());}setVisible(e,t){let n=this.byId.get(e);n&&(n.visible=t,this.emit());}clear(){this.byId.size!==0&&(this.byId.clear(),this.emit());}serialize(){return {version:1,drawings:this.all().map(e=>e.serialize())}}load(e){let t=xd(e);this.byId.clear(),this.seq=0,this.zCounter=1;for(let n of t.drawings){let i=pt(n);i&&(this.byId.set(i.id,i),this.zCounter=Math.max(this.zCounter,i.zIndex)+1,this.bumpSeqPast(i.id));}this.emit();}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}bumpSeqPast(e){let t=/^dw-(\d+)$/.exec(e);t&&(this.seq=Math.max(this.seq,Number(t[1])));}emit(){for(let e of this.listeners)e();}};var Ga=class{constructor(e=100){this.cap=e;this.undoStack=[];this.redoStack=[];this.pending=null;this.dirtied=false;this.depth=0;}begin(e){this.depth+=1,this.depth===1&&(this.pending=zt(e),this.dirtied=false);}markDirty(){this.depth===0||this.dirtied||!this.pending||(this.push(this.pending),this.dirtied=true);}commit(){this.depth!==0&&(this.depth-=1,this.depth===0&&(this.pending=null,this.dirtied=false));}abort(){this.commit();}record(e){if(this.depth>0){this.markDirty();return}this.push(zt(e));}undo(e){let t=this.undoStack.pop();return t?(this.redoStack.push(zt(e)),t):null}redo(e){let t=this.redoStack.pop();return t?(this.undoStack.push(zt(e)),t):null}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[],this.pending=null,this.dirtied=false,this.depth=0;}push(e){this.undoStack.push(e),this.undoStack.length>this.cap&&this.undoStack.shift(),this.redoStack=[];}};var Ua=class{constructor(e,t,n,i){this.events=t;this.store=new Yr;this.history=new Ga;this.activeTool=null;this.snapMode="off";this.stayInDrawingMode=false;this.mode=null;this.favs=new Set;this.selectedIds=[];this.clipboard=[];this.lastStyle=new Map;this.subs=[];if(this.enabled=!!e.capabilities.userDrawings&&!!e.userDrawingsPort,this.port=this.enabled?e.userDrawingsPort:null,this.port){let{definition:o,visible:s}=to(n);this.port.setToolbar(o),this.port.showToolbar(s),i&&this.port.setSeriesGateway?.(i),this.subs.push(this.port.onDrawingIntent(a=>this.onIntent(a))),this.subs.push(this.store.onChange(()=>this.sync()));}}get supported(){return this.enabled}setTool(e){if(!this.port)return;let t=e!==this.activeTool;this.activeTool=e,this.port.setActiveTool(e,e?this.lastStyle.get(e):void 0),t&&this.events.emit("drawing:tool",{type:e});}getTool(){return this.activeTool}getSnapMode(){return this.snapMode}setSnapMode(e){!this.port||e===this.snapMode||(this.snapMode=e,this.port.setSnapMode?.(e),this.events.emit("drawing:snap",{mode:e}));}getStayMode(){return this.stayInDrawingMode}setStayMode(e){!this.port||e===this.stayInDrawingMode||(this.stayInDrawingMode=e,this.port.setStayMode?.(e),this.events.emit("drawing:stay",{on:e}));}getMode(){return this.mode}setMode(e){!this.port||e===this.mode||(this.mode=e,this.port.setMode?.(e),this.events.emit("drawing:mode",{mode:e}));}showToolbar(e){this.port?.showToolbar(e);}favorites(){return [...this.favs]}isFavorite(e){return this.favs.has(e)}setFavorite(e,t){Et(e)&&t!==this.favs.has(e)&&(t?this.favs.add(e):this.favs.delete(e),this.pushFavorites());}setFavorites(e){let t=e.filter(n=>Et(n)!=null);t.length===this.favs.size&&t.every(n=>this.favs.has(n))||(this.favs=new Set(t),this.pushFavorites());}pushFavorites(){let e=[...this.favs];this.port?.setFavorites?.(e),this.events.emit("drawing:favorites",{favorites:e});}setToolbar(e){this.port?.setToolbar(to(e).definition);}setExternalGhost(e){this.port?.setExternalGhost?.(e);}setToolShortcuts(e){this.port?.setToolShortcuts?.(e);}add(e,t={}){if(!this.enabled)return null;let i={...this.lastStyle.get(e)??{},...t.style??{}},o=Rn(e,{id:this.store.nextId(),paneId:t.paneId??"price",anchors:t.anchors,style:i,text:t.text,props:t.props,zIndex:t.zIndex??this.startZ(e,t.paneId??"price")});return o?(this.history.record(this.store.serialize()),this.store.add(o),this.captureStyle(o.id),this.events.emit("drawing:created",{id:o.id}),o):null}remove(e){this.deleteMany([e]);}update(e,t){let n=this.store.serialize(),i=t.style?this.store.get(e):void 0,o=t.style&&i?{...t,style:{...i.style,...t.style}}:t;this.store.update(e,o)&&(this.history.record(n),this.captureStyle(e),this.events.emit("drawing:edited",{id:e}));}updateMany(e){this.history.begin(this.store.serialize());for(let{id:t,patch:n}of e)this.store.update(t,n)&&(this.history.markDirty(),this.events.emit("drawing:edited",{id:t}));this.history.commit();}removeMany(e){this.deleteMany(e);}setLocked(e,t){let n=this.store.serialize();this.history.record(n),this.store.setLocked(e,t),this.events.emit("drawing:edited",{id:e});}setVisible(e,t){let n=this.store.serialize();this.history.record(n),this.store.setVisible(e,t),this.events.emit("drawing:edited",{id:e});}bringToFront(e){let t=this.store.serialize();this.history.record(t),this.store.bringToFront(e,this.seriesTopZ(this.store.get(e)?.paneId)),this.events.emit("drawing:edited",{id:e});}sendToBack(e){let t=this.store.serialize();this.history.record(t),this.store.sendToBack(e,this.seriesBottomZ(this.store.get(e)?.paneId)),this.events.emit("drawing:edited",{id:e});}seriesTopZ(e){return e!==void 0?this.port?.stackRange?.(e)?.front??0:0}seriesBottomZ(e){return e!==void 0?this.port?.stackRange?.(e)?.back??1:1}startZ(e,t){let n=this.port?.stackRange?.(t);if(n)return Et(e)?.coversSeries?n.front+.5:(n.price??n.front)-.5}select(e,t=false){this.setSelection(e,t);}openSettings(e){this.port?.openSettings(e);}undo(){let e=this.history.undo(this.store.serialize());e&&this.restoreSnapshot(e);}redo(){let e=this.history.redo(this.store.serialize());e&&this.restoreSnapshot(e);}canUndo(){return this.history.canUndo()}canRedo(){return this.history.canRedo()}duplicate(e){if(!this.enabled)return [];let t=this.resolve(e);return t.length===0?[]:this.insertClones(t.map(n=>n.serialize()))}clone(e){return this.duplicate([e])[0]??null}copy(e){let t=this.resolve(e).map(n=>zt(n.serialize()));t.length&&(this.clipboard=t);}paste(){return !this.enabled||this.clipboard.length===0?[]:this.insertClones(this.clipboard)}all(){return this.store.serialize().drawings}toJSON(){return this.store.serialize()}fromJSON(e){this.history.clear(),this.selectedIds=[],this.store.load(e);}destroy(){for(let e of this.subs)e();this.subs.length=0;}setSelection(e,t=false){let n;if(t){n=[...this.selectedIds];for(let i of e){let o=n.indexOf(i);o>=0?n.splice(o,1):n.push(i);}}else n=[...e];this.selectedIds=n.filter(i=>this.store.has(i)),this.announceSelection();}announceSelection(){this.port?.setSelection(this.selectedIds),this.events.emit("drawing:selected",{id:this.selectedIds[0]??null,ids:[...this.selectedIds]});}restoreSnapshot(e){this.store.load(e),this.selectedIds=this.selectedIds.filter(t=>this.store.has(t)),this.announceSelection();}deleteMany(e){this.history.begin(this.store.serialize());let t=[];for(let i of e)this.store.remove(i)&&t.push(i),this.history.markDirty();if(this.history.commit(),t.length===0)return;let n=this.selectedIds.filter(i=>this.store.has(i));n.length!==this.selectedIds.length&&this.setSelection(n);for(let i of t)this.events.emit("drawing:removed",{id:i});}insertClones(e){this.history.begin(this.store.serialize());let t=[];for(let n of e){let i=pt({...n,id:this.store.nextId()});i&&(this.store.add(i),this.history.markDirty(),t.push(i));}if(this.history.commit(),t.length){this.setSelection(t.map(n=>n.id));for(let n of t)this.events.emit("drawing:created",{id:n.id});}return t}resolve(e){return e.map(t=>this.store.get(t)).filter(t=>t!=null)}captureStyle(e){let t=this.store.get(e);t&&this.lastStyle.set(t.type,{...t.style});}sync(){this.port?.syncDrawings(this.store.serialize().drawings);}onIntent(e){switch(e.kind){case "arm":this.setTool(e.type);break;case "draft":this.events.emit("drawing:draft",{doc:e.doc});break;case "create":{let t=this.store.serialize(),n=this.lastStyle.get(e.doc.type),i=n?{...e.doc.style,...n}:e.doc.style,o=pt({...e.doc,id:this.store.nextId(),style:i});if(!o)return;o.zIndex||(o.zIndex=this.startZ(o.type,o.paneId)??0),this.history.record(t),this.store.add(o),this.captureStyle(o.id),this.events.emit("drawing:created",{id:o.id});break}case "edit":{let t=this.store.serialize();this.store.update(e.doc.id,e.doc)&&(this.history.record(t),this.captureStyle(e.doc.id),this.events.emit("drawing:edited",{id:e.doc.id}));break}case "edit-many":{this.history.begin(this.store.serialize());for(let t of e.docs)this.store.update(t.id,t)&&(this.history.markDirty(),this.events.emit("drawing:edited",{id:t.id}));this.history.commit();break}case "select":this.setSelection(e.ids,e.additive);break;case "delete":this.deleteMany(e.ids);break;case "reorder":e.to==="front"?this.bringToFront(e.id):this.sendToBack(e.id);break;case "settings":this.events.emit("drawing:settings",{id:e.id});break;case "favorite":this.setFavorite(e.type,e.on);break;case "snap-mode":e.mode!==this.snapMode&&(this.snapMode=e.mode,this.events.emit("drawing:snap",{mode:e.mode}));break;case "stay-mode":e.on!==this.stayInDrawingMode&&(this.stayInDrawingMode=e.on,this.events.emit("drawing:stay",{on:e.on}));break;case "mode":e.mode!==this.mode&&(this.mode=e.mode,this.events.emit("drawing:mode",{mode:e.mode}));break;case "tool-finished":!this.stayInDrawingMode&&e.type!=="freehand"&&e.type!=="highlighter"&&this.setTool(null);break;case "undo":this.undo();break;case "redo":this.redo();break;case "duplicate":this.duplicate(e.ids);break;case "clone":this.enabled&&e.docs.length&&this.insertClones(e.docs);break;case "copy":this.copy(e.ids);break;case "paste":this.paste();break}}};var gm={D:864e5,W:6048e5,M:2592e6};function Pt(r){let e=r.trim();if(gm[e])return gm[e];let t=/^(\d+)\s*(m|h|d|w)?$/i.exec(e);if(t){let n=parseInt(t[1],10),i=(t[2]??"m").toLowerCase();return n*(i==="m"?6e4:i==="h"?36e5:i==="d"?864e5:6048e5)}return 36e5}var SC=5e3,CC=.25,TC=16,EC=15e3,Sd=["240","60","30","15","5","1"],Ya=class{constructor(e){this.deps=e;this.cache=new Map;this.listeners=new Set;}seriesInRange(e,t,n){if(!this.deps.canFetch())return {state:"unavailable",reason:"no-source"};let i=this.resolveTimeframe(e);if(typeof i!="string")return {state:"unavailable",reason:i.reason};let o=Pt(i),s=Math.min(t,n),a=Math.max(t,n);if(!(a>s)||!(o>0))return {state:"unavailable",reason:"not-lower"};if((a-s)/o>SC)return {state:"unavailable",reason:"too-wide"};let l=`${this.deps.marketKey()}|${i}`,c=this.cache.get(l)??[],d=c.find(u=>u.from<=s&&u.to>=a);if(d){if(d.pending)return this.loading(c,i,o,s,a);if(d.failedAt>0){if(Date.now()-d.failedAt<EC)return this.loading(c,i,o,s,a);c.splice(c.indexOf(d),1);}else return this.maybeRefresh(l,d,i,o,a),{state:"ready",bars:this.slice(d.bars,s,a),timeframe:i,barMs:o}}return this.fetchWindow(l,c,i,s,a),this.loading(c,i,o,s,a)}onUpdate(e){return this.listeners.add(e),()=>this.listeners.delete(e)}resolveTimeframe(e){let t=Pt(this.deps.chartTimeframe()),n=Sd[Sd.length-1];if(Pt(n)>=t)return {reason:"none-lower"};let i=e.trim()||"auto";if(i==="auto"){for(let o of Sd)if(Pt(o)<=t/4)return o;return n}return Pt(i)<t?i:{reason:"not-lower"}}loading(e,t,n,i,o){let s=new Map;for(let l of e)if(!(l.pending||l.failedAt>0)&&!(l.to<i||l.from>o))for(let c of this.slice(l.bars,i,o))s.set(c.time,c);if(s.size===0)return {state:"loading",timeframe:t,barMs:n};let a=[...s.values()].sort((l,c)=>l.time-c.time);return {state:"loading",timeframe:t,barMs:n,bars:a}}fetchWindow(e,t,n,i,o){if(t.some(l=>l.pending&&l.to>=i&&l.from<=o))return;let s=(o-i)*CC,a={from:i-s,to:o+s,bars:[],fetchedAt:0,pending:true,failedAt:0};t.push(a),this.cache.set(e,t),this.evict(),this.deps.fetchBars(n,{from:a.from,to:a.to}).then(l=>{a.bars=l,a.fetchedAt=Date.now(),a.pending=false,this.absorbOverlaps(e,a),this.fire();}).catch(()=>{a.pending=false,a.failedAt=Date.now(),this.fire();});}maybeRefresh(e,t,n,i,o){if(t.pending)return;let s=t.bars.length>0?t.bars[t.bars.length-1].time:t.from;o<s||Date.now()-t.fetchedAt<i||(t.pending=true,this.deps.fetchBars(n,{from:t.from,to:t.to}).then(a=>{t.bars=a,t.fetchedAt=Date.now(),t.pending=false,this.fire();}).catch(()=>{t.pending=false,t.fetchedAt=Date.now();}));}absorbOverlaps(e,t){let n=this.cache.get(e);if(n)for(let i=n.length-1;i>=0;i-=1){let o=n[i];if(o===t||o.pending||o.failedAt>0||o.to<t.from||o.from>t.to)continue;let s=new Map;for(let a of o.bars)s.set(a.time,a);for(let a of t.bars)s.set(a.time,a);t.bars=[...s.values()].sort((a,l)=>a.time-l.time),t.from=Math.min(t.from,o.from),t.to=Math.max(t.to,o.to),t.fetchedAt=Math.min(t.fetchedAt,o.fetchedAt||t.fetchedAt),n.splice(i,1);}}evict(){let e=0;for(let t of this.cache.values())e+=t.length;for(;e>TC;){let t=null,n=-1,i=1/0;for(let[s,a]of this.cache)for(let l=0;l<a.length;l+=1){let c=a[l];if(c.pending)continue;let d=c.fetchedAt||c.failedAt;d<i&&(t=s,n=l,i=d);}if(t==null)return;let o=this.cache.get(t);o.splice(n,1),o.length===0&&this.cache.delete(t),e-=1;}}slice(e,t,n){let i=[];for(let o of e)if(!(o.time<t)){if(o.time>n)break;i.push(o);}return i}fire(){for(let e of [...this.listeners])e();}};function no(r){return r.group!=null&&r.ticker===r.group}function bm(r){return `${(r.prefix??r.provider??"").toLowerCase()}:${(r.group??"").toUpperCase()}`}function PC(r,e){let t=bm(e);return r.filter(n=>n.group!=null&&!no(n)&&bm(n)===t)}function vm(r,e){let t=PC(r,e),n=t.filter(i=>i.default);return (n.length===1?n[0]:t[0])??null}var $t=r=>r.trim().toLowerCase(),dn=r=>r.trim().toUpperCase();function Wt(r){let e=r.trim(),t=/^(?:([A-Za-z0-9_.]+):)?(.+)$/.exec(e);if(!t)return {provider:null,ticker:e};let n=t[1]?$t(t[1]):null,i=t[2],o=i.lastIndexOf("."),s=o>0?i.slice(o+1):void 0;return {provider:n,ticker:i,ext:s}}var Ka=class{constructor(){this.entries=new Map;this.changeListeners=new Set;this.waits=new Set;this.unresolvedCbs=new Set;}register(e,t){let n=$t(e),i={name:n,provider:t,index:null,prefixIndex:null,byTicker:null,descriptors:[],settled:false,settle:Promise.resolve()};return this.entries.set(n,i),i.settle=this.buildIndex(i),queueMicrotask(()=>this.notify(false)),i.settle}async buildIndex(e){await Promise.resolve();try{if(e.provider.listSymbols){let t=await e.provider.listSymbols();e.descriptors=t,e.index=new Set(t.map(n=>dn(n.ticker))),e.byTicker=new Map(t.map(n=>[dn(n.ticker),n])),e.prefixIndex=new Map;for(let n of t)n.prefix&&e.prefixIndex.set(`${$t(n.prefix)}:${dn(n.ticker)}`,n);}}catch{e.index=null;}finally{e.settled=true,this.notify(true);}}notify(e){for(let t of [...this.changeListeners])t(e);}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}unregister(e){this.entries.delete($t(e)),this.notify(false);}has(e){return this.entries.has($t(e))}get(e){return this.entries.get($t(e))?.provider}names(){return [...this.entries.keys()]}parse(e){return Wt(e)}resolve(e,t={}){let{provider:n,ticker:i}=this.parse(e);if(n){if(this.entries.has(n)){let a=this.entries.get(n).byTicker?.get(dn(i));return {provider:n,ticker:a!=null&&no(a)?this.loadableTicker(n,a):i}}let s=`${n}:${dn(i)}`;for(let a of this.candidateOrder(t.default)){let l=this.entries.get(a).prefixIndex?.get(s);if(l)return {provider:a,ticker:this.loadableTicker(a,l)}}return null}let o=dn(i);for(let s of this.candidateOrder(t.default)){let a=this.entries.get(s);if(a.index?.has(o)){let l=a.byTicker?.get(o);return {provider:s,ticker:l!=null&&no(l)?this.loadableTicker(s,l):i}}}if(t.lenient&&this.entries.size===1){let s=this.names()[0],a=this.entries.get(s);if(a.settled&&a.index==null)return {provider:s,ticker:i}}return null}loadableTicker(e,t){return no(t)?vm(this.entries.get(e)?.descriptors??[],t)?.ticker??t.ticker:t.ticker}whenResolvable(e,t={}){let n=this.resolve(e,{...t,lenient:true});return n?Promise.resolve(n):new Promise(i=>{let o=this.onChange(a=>{let l=this.resolve(e,{...t,lenient:true});l?(s(),i(l)):a&&this.allSettled()&&this.reportUnresolved(e);}),s=()=>{o(),this.waits.delete(s);};this.waits.add(s);})}allSettled(){for(let e of this.entries.values())if(!e.settled)return false;return true}cancelWaits(){for(let e of [...this.waits])e();}onUnresolved(e){return this.unresolvedCbs.add(e),()=>this.unresolvedCbs.delete(e)}reportUnresolved(e){let t=this.names();console.warn(`[vela] symbol "${e}" not yet resolvable \u2014 registered providers: [${t.join(", ")||"none"}]. Register a provider that serves it.`);for(let n of this.unresolvedCbs)n({symbol:e,providers:t});}candidateOrder(e){let t=this.names();if(e){let n=$t(e);if(this.entries.has(n))return [n,...t.filter(i=>i!==n)]}return t}displayPrefixOf(e){return this.entries.get(e.provider)?.byTicker?.get(dn(e.ticker))?.prefix??e.provider}canonicalSymbol(e){let t=this.entries.get(e.provider)?.byTicker?.get(dn(e.ticker));return `${t?.prefix??e.provider}:${t?.ticker??e.ticker}`}symbolIconOf(e){let t=e.provider?$t(e.provider):[...this.entries.keys()][0],n=t!==void 0?this.entries.get(t):void 0;try{return n?.provider.resolveSymbolIcon?.(e)??void 0}catch{return}}symbolIcon(e){if(!e)return;let t=this.entries.get(e.provider)?.byTicker?.get(dn(e.ticker));return this.symbolIconOf({...t??{ticker:e.ticker},provider:t?.provider??e.provider})}symbolsOf(e){return e!=null?this.entries.get($t(e))?.descriptors??[]:[...this.entries.entries()].flatMap(([t,n])=>n.descriptors.map(i=>({...i,provider:t})))}infoOf(e){let t=$t(e),n=this.entries.get(t);if(!n)return {name:t,capabilities:{enumerate:false,stream:false,symbolInfo:false}};let i=n.provider;return i.info?.()??{name:n.name,capabilities:{enumerate:!!i.listSymbols,stream:!!i.subscribe,symbolInfo:!!i.getSymbolInfo}}}indexReady(){return Promise.all([...this.entries.values()].map(e=>e.settle)).then(()=>{})}};function Kr(r){switch(r.kind){case "row":return {label:r.label,toggle:r.toggle,controls:r.controls,when:r.when};case "toggle":{let e=[];r.number&&e.push({kind:"number",...r.number});for(let t of r.colors??[])e.push({kind:"color",...t});return r.width&&e.push({kind:"width",...r.width}),{label:r.label,toggle:{key:r.key,defval:r.defval},controls:e,when:r.when}}case "number":return {label:r.label,controls:[{kind:"number",key:r.key,label:r.label,defval:r.defval,min:r.min,max:r.max,step:r.step}],when:r.when};case "color":return {label:r.label,controls:[{kind:"color",key:r.key,label:r.label,defval:r.defval}],when:r.when};case "select":return {label:r.label,controls:[{kind:"select",key:r.key,label:r.label,options:r.options,defval:r.defval}],when:r.when};case "range":return {label:r.label,controls:[{kind:"number",key:r.minKey,label:`${r.label} \u2014 min`,defval:r.defval,min:r.min,max:r.max,step:r.step,placeholder:r.placeholder},{kind:"hint",text:"\u2013"},{kind:"number",key:r.maxKey,label:`${r.label} \u2014 max`,defval:r.defval,min:r.min,max:r.max,step:r.step,placeholder:r.placeholder}],when:r.when}}}function ro(r){if(r.kind==="heading"||r.kind==="header")return [];let e=Kr(r),t=[];e.toggle&&t.push({key:e.toggle.key,type:"boolean",defval:e.toggle.defval});for(let n of e.controls)n.kind!=="hint"&&(n.kind==="color"||n.kind==="select"?t.push({key:n.key,type:"string",defval:n.defval}):t.push({key:n.key,type:"number",defval:n.defval}));return t}function pr(r,e){return r?(Array.isArray(r)?r:[r]).every(n=>n.anyOf?n.anyOf.some(i=>i===e[n.key]):e[n.key]===n.equals):true}var io=new Map;function Cd(r){io.set(r.id,r);}function LC(r){io.delete(r);}function un(r){return typeof r=="string"?io.get(r):void 0}function Lt(){return [...io.values()]}function Td(){return [...io.values()].filter(r=>r.tickerModifier??r.barTransform!=null).map(r=>r.id)}function Xr(r){return un(r)?.barTransform??null}function ym(r){let e=r.lastIndexOf(";");if(e<=0||e===r.length-1)return {symbol:r,modifier:null,transform:null};let t=r.slice(e+1).toLowerCase();return t!=="standard"&&!Td().includes(t)?{symbol:r,modifier:null,transform:null}:{symbol:r.slice(0,e),modifier:t,transform:Xr(t)}}var Gt={background:"#151619",textColor:"#b2b5be",gridColor:"#20222c",borderColor:"#2a2b30",upColor:z,downColor:W,fontFamily:"sans-serif"},oo={background:"#ffffff",textColor:"#1e293b",gridColor:"#cccccc",borderColor:"#d4dae3",upColor:z,downColor:W,fontFamily:"sans-serif"};function jr(r){return !r||r==="dark"?Gt:r==="light"?oo:r}var MC=150,kC=1e3,IC=300,AC=5e3,wm=1e4,RC=20,DC=1.5,xm=5e3,Xa=class r{constructor(e,t,n,i,o,s){this.renderer=t;this.feed=n;this.config=o;this.dataControl=s;this.events=new qn;this.registry=new ks;this.paneOrder=["price"];this.collapsedPanes=new Set;this.maximizedPaneId=null;this.paneActionUnsub=null;this.handles=new Map;this.engines=new Map;this.live=null;this.bars=[];this.rawBars=[];this.barTransform=null;this.typeEngines=new Map;this.typeSettings=new Map;this.activeEngineStyle=null;this.priceStyle="candles";this.unresolvedUnsub=null;this.visibleRange=null;this.viewportUnsub=null;this.viewportTimer=null;this.healing=false;this.healBuffer=[];this.lastHealAt=0;this.onVisible=null;this.barCause="tick";this.historyState="complete";this.generation=0;this.progressiveAbort=null;this.supersedeWaiters=[];this.historyCompleted=false;this.historyCompletePromise=new Promise(e=>{this.resolveHistoryComplete=e;});this.switchingMarket=false;this.loadingUp=false;this.volumeOptedOut=false;this.contextEmitAt=new Map;this.runEmitAt=new Map;for(let c of i)this.registerEngine(c.language,c);this.defaultLanguage=o.defaultLanguage,this.renderer.mount(e,o.theme),this.renderer.onInputChange(c=>c.kind==="prop"?this.applyProps(c.indicatorId,{[c.key]:c.value}):this.applyInputs(c.indicatorId,{[c.key]:c.value})),this.renderer.onRemoveIndicator(c=>this.removeIndicator(c)),this.renderer.onToggleIndicatorVisible?.((c,d)=>this.setVisible(c,d)),this.paneActionUnsub=this.renderer.onPaneAction?.(c=>this.handlePaneAction(c))??null,this.renderer.onChartTypeSettingsChange?.((c,d)=>{this.typeSettings.set(c,d),this.typeEngines.get(c)?.onSettings?.(d);}),this.renderer.onMoveIndicator?.((c,d)=>this.moveIndicator(c,d)),this.renderer.onThemeSelect?.(c=>this.setTheme(jr(c))),this.viewportUnsub=this.renderer.onViewportChange(c=>this.onViewportChange(c)),this.renderer.onPriceStyleChange?.(c=>this.syncPriceStyle(c));let a=this.renderer.readFeature("priceStyle");typeof a=="string"&&(this.priceStyle=a),this.barTransform=Xr(a);let l=new Ya({fetchBars:(c,d)=>this.fetchSeries(this.config.market.symbol??"",c,d),canFetch:()=>!!this.feed.loadRange&&!this.config.market.data?.length&&!!this.config.market.symbol,chartTimeframe:()=>this.config.market.timeframe??"60",marketKey:()=>`${this.config.market.symbol??""}|${this.config.market.session??""}`});this.drawings=new Ua(this.renderer,this.events,o.drawings,l),this.unresolvedUnsub=this.feed.onUnresolved?.(c=>{this.endLoad(),this.events.emit("data:unresolved",c);})??null,this.readyPromise=this.init(),un(a)?.dataEngine&&this.syncChartTypeEngine(a);}currentVisibleRange(){if(this.visibleRange)return this.visibleRange;let e=this.renderer.getVisibleRange();return e?{left:e.from,right:e.to}:void 0}engineFor(e){let t=e??this.defaultLanguage,n=this.engines.get(t);if(!n)throw new Error(`[vela] no scripting engine registered for language "${t}". Vela ships none \u2014 install one (Pine Script: @luxalgo/vela-pinets) and register it before addIndicator, e.g. chart.registerEngine('pine', new PineEngine()).`);return n}market(){return {symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",symbolInfo:this.feed.symbolInfo?.(this.config.market),chartStyle:this.priceStyle}}async fetchSeries(e,t,n){let i=ym(e),o={symbol:i.symbol,timeframe:t},s=await(this.feed.loadRange?this.feed.loadRange(o,n):this.feed.load({...o,bars:n.limit}));return i.transform?i.transform.full(s):s}onViewportChange(e){this.visibleRange={left:e.from,right:e.to},this.events.emit("viewport:changed",{from:e.from,to:e.to}),this.viewportTimer!=null&&clearTimeout(this.viewportTimer),this.viewportTimer=setTimeout(()=>{if(this.viewportTimer=null,this.switchingMarket)return;let t=this.visibleRange;if(t){for(let n of this.registry.all())!n.renderHandle||n.hidden||(n.session&&n.prepared?.reactsToViewport?(n.pendingCause="viewport",n.session.setVisibleRange(t)):n.native?.descriptor.reactsToViewport&&n.native.instance.onViewport({from:t.left,to:t.right}));this.activeEngineStyle&&this.typeEngines.get(this.activeEngineStyle)?.onViewport?.({from:t.left,to:t.right});}},MC);}async init(){let e=this.bumpGeneration();this.beginLoad(true),await this.loadMarket(e,{firstLoad:true}),this.generation===e&&(this.startLive(),this.events.emit("ready",void 0));}bumpGeneration(){let e=++this.generation;this.progressiveAbort?.abort(),this.progressiveAbort=null;for(let t of this.supersedeWaiters.splice(0))t();return e}beginLoad(e){if(this.loadingUp)return;this.loadingUp=true,this.renderer.setLoading?.(true);let t=this.config.market;this.events.emit("load:start",{symbol:t.symbol??"TEST",timeframe:t.timeframe??"60",firstLoad:e});}endLoad(){if(!this.loadingUp)return;this.loadingUp=false,this.renderer.setLoading?.(false);let e=this.config.market;this.events.emit("load:end",{symbol:e.symbol??"TEST",timeframe:e.timeframe??"60",bars:this.bars.length});}async loadMarket(e,t){try{await this.loadMarketInner(e,t);}finally{this.generation===e&&this.endLoad();}}async loadMarketInner(e,t){let n=this.config.market,i=n.bars??500,o=n.visibleRange,s=!n.data?.length&&o==null&&i>AC,a=false;if(!n.data?.length&&o==null&&this.feed.loadProgressive){let l=false,c=(u,h)=>{this.generation!==e||!h&&u.length===0||!l&&!h&&u.length<Math.min(i,RC)||(this.setBarSeries(u,l?{preserveView:true}:void 0),!l&&u.length>0&&(l=true,t.firstLoad&&this.activateBarLayers(),h||(this.historyState="backfill")));},d=new AbortController;this.progressiveAbort=d,a=await new Promise(u=>{let h=false,p=m=>{h||(h=true,u(m));};d.signal.addEventListener("abort",()=>p(true),{once:true}),this.feed.loadProgressive(n,m=>{c(m,false),l&&p(true);},{signal:d.signal}).then(m=>{if(this.progressiveAbort===d&&(this.progressiveAbort=null),m==null)return p(false);if(this.generation!==e)return p(true);c(m,true),this.completeHistory(m.length>=i?"depth":"genesis"),p(true);}).catch(()=>{this.progressiveAbort===d&&(this.progressiveAbort=null),this.generation===e&&this.completeHistory("aborted"),p(true);});});}if(!a)if(s&&this.feed.loadRange){let l=await this.feed.load({...n,bars:Math.min(i,wm)});if(this.generation!==e)return;this.setBarSeries(l),t.firstLoad&&this.activateBarLayers(),l.length>0&&i>l.length?(this.historyState="backfill",this.backfillHistory(e,i)):this.completeHistory("depth");}else if(s){let l=await this.feed.load({...n,bars:IC});if(this.generation!==e)return;this.setBarSeries(l),t.firstLoad&&this.activateBarLayers();let c=await this.feed.load(n);if(this.generation!==e)return;this.setBarSeries(c,{preserveView:true}),this.completeHistory("depth");}else {let l=await this.feed.load(n);if(this.generation!==e)return;this.setBarSeries(l),t.firstLoad&&this.activateBarLayers(),this.completeHistory("depth");}o!=null&&(typeof o=="string"?this.setVisibleRangePreset(o):this.renderer.setVisibleRange(o)),this.refreshPriceFormat(),this.ensurePriceFormat();}startLive(){this.config.live&&(this.live=new As(this.feed,this.config.market,e=>this.onBar(e)),this.live.start(),typeof document<"u"&&(this.onVisible=()=>{if(document.visibilityState!=="visible")return;let e=this.bars[this.bars.length-1];!e||this.healing||!this.canHeal()||Date.now()-this.lastHealAt<=xm||this.healGap(e.time);},document.addEventListener("visibilitychange",this.onVisible)));}stopLive(){this.live?.stop(),this.live=null,this.onVisible&&typeof document<"u"&&document.removeEventListener("visibilitychange",this.onVisible),this.onVisible=null,this.healing=false,this.healBuffer=[],this.lastHealAt=0;}resetHistoryTracking(){this.resolveHistoryComplete(),this.historyCompleted=false,this.historyState="complete",this.historyCompletePromise=new Promise(e=>{this.resolveHistoryComplete=e;});}marketSnapshot(){let e=this.config.market;return {symbol:e.symbol,provider:Wt(e.symbol??"").provider??void 0,timeframe:e.timeframe,bars:e.bars,session:e.session,offline:e.data!==void 0}}async setMarket(e){let t=this.config.market,n=e.symbol!==void 0&&e.symbol!==t.symbol||e.timeframe!==void 0&&e.timeframe!==t.timeframe||e.session!==void 0&&e.session!==t.session||e.data!==void 0,i=e.bars!==void 0&&e.bars!==t.bars,o=i&&!n&&this.rawBars.length>0&&!t.data?.length&&((e.bars??0)<=this.rawBars.length||typeof this.feed.loadRange=="function");if(!n&&!i){typeof e.visibleRange=="string"?this.setVisibleRangePreset(e.visibleRange):e.visibleRange&&this.renderer.setVisibleRange(e.visibleRange);return}let s={symbol:t.symbol??"TEST",timeframe:t.timeframe??"60"},l=n&&e.session!==void 0&&e.data===void 0&&(e.symbol===void 0||e.symbol===t.symbol)&&(e.timeframe===void 0||e.timeframe===t.timeframe)&&e.visibleRange===void 0?this.currentVisibleRange():void 0,c=l?this.rawBars.filter(u=>u.time>=l.left&&u.time<=l.right).length:0,d=this.bumpGeneration();this.switchingMarket=true;try{if(this.stopLive(),this.viewportTimer!=null&&(clearTimeout(this.viewportTimer),this.viewportTimer=null),this.visibleRange=null,this.resetHistoryTracking(),e.symbol!==void 0&&(t.symbol=e.symbol),e.timeframe!==void 0&&(t.timeframe=e.timeframe),e.bars!==void 0&&(t.bars=e.bars),e.session!==void 0&&(t.session=e.session),l){let u=Math.min(Math.ceil((Date.now()-l.left)/this.barIntervalMs())+50,5e3);u>(t.bars??500)&&(t.bars=u);}if(e.data!==void 0?t.data=e.data:e.symbol!==void 0&&delete t.data,t.visibleRange=e.visibleRange??(l?{from:l.left,to:l.right}:void 0),n&&(this.beginLoad(!1),this.setBarSeries([],{clearing:!0}),this.activeEngineStyle&&(this.typeEngines.get(this.activeEngineStyle)?.suspend(),this.renderer.setNativeData?.(this.activeEngineStyle,void 0),this.renderer.setNativeData?.(`${this.activeEngineStyle}-pending`,[]))),o?this.extendDepth(d,t.bars??500):await Promise.race([this.loadMarket(d,{firstLoad:!1}),new Promise(u=>this.supersedeWaiters.push(u))]),this.generation!==d)return}finally{this.generation===d&&(this.switchingMarket=false);}if(l&&c>=2&&this.rawBars.length>0){let u=this.rawBars,h=u.length-1;for(;h>0&&u[h].time>l.right;)h-=1;let p=u[Math.max(0,h-(c-1))].time;this.renderer.setVisibleRange({from:p,to:Math.max(l.right,u[h].time+1)});}o||(this.restartNativeIndicators(),this.restartChartTypeEngine(),this.reexecuteIndicators()),this.startLive(),n&&this.events.emit("market:changed",{symbol:t.symbol??"TEST",timeframe:t.timeframe??"60",prev:s});}restartNativeIndicators(){for(let e of this.registry.all())if(e.native)if(e.native.instance.stop(),e.native.instance=e.native.descriptor.create(),e.native.started=false,e.pendingStructural=true,e.hidden)e.native.stale=true;else {let t=this.handles.get(e.id);t&&this.startNativeIndicator(e.id,t);}}restartChartTypeEngine(){for(let e of this.typeEngines.values())e.stop();this.typeEngines.clear(),this.activeEngineStyle&&this.startChartTypeEngine(this.activeEngineStyle);}activateBarLayers(){this.maybeAutoAddVolume();}extendDepth(e,t){if(this.rawBars.length>t){this.setBarSeries(this.rawBars.slice(this.rawBars.length-t),{preserveView:true}),this.completeHistory("depth");return}if(this.rawBars.length===t){this.completeHistory("depth");return}this.historyState="backfill",this.backfillHistory(e,t);}async backfillHistory(e,t){try{for(;this.generation===e&&this.rawBars.length<t&&this.rawBars.length>0;){let n=t-this.rawBars.length,i=wm,o=await this.feed.loadRange(this.config.market,{to:this.rawBars[0].time,limit:Math.min(i,n)+1});if(this.generation!==e)return;let s=this.rawBars[0].time,a=o.filter(l=>l.time<s);if(a.length===0){this.completeHistory("genesis");return}for(let l=1;l<a.length;l+=1)if(a[l].time<=a[l-1].time){console.warn("[vela] non-monotonic history chunk \u2014 stopping the backfill"),this.completeHistory("aborted");return}this.setBarSeries([...a,...this.rawBars],{preserveView:!0}),this.notifySessionsBars("backfill"),this.events.emit("history:progress",{loaded:this.rawBars.length,target:t});}this.generation===e&&this.completeHistory("depth");}catch(n){console.warn(`[vela] history backfill failed \u2014 keeping ${this.rawBars.length} bars (${n instanceof Error?n.message:String(n)})`),this.generation===e&&this.completeHistory("aborted");}}completeHistory(e){this.historyCompleted||(this.historyCompleted=true,this.historyState="complete",this.notifySessionsBars("complete"),this.events.emit("history:complete",{reason:e,oldestTime:this.rawBars[0]?.time??0,barsLoaded:this.rawBars.length}),this.resolveHistoryComplete());}historyComplete(){return this.historyCompletePromise}qualifiedSymbol(){let e=this.config.market;return e.symbol?e.symbol:null}refreshPriceFormat(){if(!this.renderer.setPricePrecision)return;let e=this.feed.symbolInfo?.(this.config.market)?.mintick;this.renderer.setPricePrecision(typeof e=="number"&&e>0?e:void 0);}async ensurePriceFormat(){if(!this.renderer.setPricePrecision)return;let e=this.qualifiedSymbol();if(e)try{await this.dataControl.symbolInfo(e),this.refreshPriceFormat();}catch{}}maybeAutoAddVolume(){!this.config.volume||this.volumeOptedOut||!this.renderer.setNativeData||$i("volume")&&this.addNativeIndicator("volume");}syncPriceStyle(e){typeof e=="string"&&(this.priceStyle=e),this.syncBarTransform(e),this.syncChartTypeEngine(e);}syncChartTypeEngine(e){let t=typeof e=="string"?e:null,i=un(t)?.dataEngine?t:null;i!==this.activeEngineStyle&&(this.activeEngineStyle&&this.typeEngines.get(this.activeEngineStyle)?.suspend(),this.activeEngineStyle=i,i&&this.startChartTypeEngine(i));}async startChartTypeEngine(e){if(!this.renderer.setNativeData||(await this.readyPromise,this.activeEngineStyle!==e))return;let t=this.typeEngines.get(e);if(t){t.resume();return}let n=un(e);if(!n?.dataEngine)return;let i=n.dataEngine();this.typeEngines.set(e,i);let o=this.typeSettings.get(e);o&&i.onSettings?.(o),i.start({symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",live:this.config.live??false,session:this.config.market.session,bars:()=>this.bars,data:this.dataControl,pushData:s=>this.renderer.setNativeData?.(e,s),pushPending:s=>this.renderer.setNativeData?.(`${e}-pending`,s)});}syncBarTransform(e){let t=Xr(e);t!==this.barTransform&&(this.barTransform=t,this.rawBars.length!==0&&(this.bars=t?t.full(this.rawBars):this.rawBars,this.renderer.setBars(this.bars,{preserveView:true}),this.reexecuteIndicators()));}reexecuteIndicators(){for(let e of this.registry.all()){if(e.hidden||!e.session)continue;e.session.stop(),e.session=void 0,e.pendingStructural=true,e.pendingCause="market",this.setLoading(e,true);let t=this.handles.get(e.id);t&&this.executeIndicator(e.id,t);}}onBar(e){if(this.healing){this.healBuffer.push(e);return}let t=this.rawBars[this.rawBars.length-1];if(t&&this.canHeal()&&e.time>t.time+this.barIntervalMs()*DC&&Date.now()-this.lastHealAt>xm){this.healBuffer.push(e),this.healGap(t.time);return}this.applyBar(e);}setBarSeries(e,t){this.rawBars=e,this.bars=this.barTransform?this.barTransform.full(e):e,this.renderer.setBars(this.bars,{preserveView:t?.preserveView}),!t?.clearing&&this.bars.length>0&&this.endLoad();}applyBar(e,t=true){let n=this.rawBars[this.rawBars.length-1],i=e;if(n&&e.time===n.time)this.rawBars[this.rawBars.length-1]=e,this.barCause="tick",this.barTransform&&(i=this.barTransform.next(e,this.bars[this.bars.length-2]),this.bars[this.bars.length-1]=i);else if(!n||e.time>n.time)this.rawBars.push(e),this.barCause="bar",this.barTransform&&(i=this.barTransform.next(e,this.bars[this.bars.length-1]),this.bars.push(i));else return;this.renderer.updateBar(i),this.events.emit("bar",e),t&&this.notifySessionsBars(this.historyState==="backfill"?"backfill":void 0);}notifySessionsBars(e){if(this.switchingMarket)return;let t=e?"history":this.barCause;for(let n of this.registry.all())!n.renderHandle||n.hidden||(n.session?(n.pendingCause=t,n.session.notifyBars(e)):n.native&&n.native.instance.onBars());}canHeal(){return !!this.feed.loadRange&&!this.config.market.data?.length}barIntervalMs(){return Pt(this.config.market.timeframe??"60")}async healGap(e){let t=this.generation;this.healing=true,this.lastHealAt=Date.now();try{let n=await this.feed.loadRange(this.config.market,{from:e});if(this.generation!==t)return;for(let i of n)this.applyBar(i,!1);}catch{}finally{if(this.generation===t){this.healing=false;let n=this.healBuffer;this.healBuffer=[];for(let i of n)this.applyBar(i,false);this.notifySessionsBars(this.historyState==="backfill"?"backfill":void 0);}}}registerEngine(e,t){let n=this.engines.get(e);n&&n!==t&&console.warn(`[vela] re-registering scripting engine for language "${e}"; replacing ${n.constructor.name} with ${t.constructor.name}.`),this.engines.set(e,t);}addIndicator(e,t={}){let n=this.registry.nextId(),i=t.title??"Indicator",o=new _r(n,i,this,e);return this.handles.set(n,o),this.registry.add({id:n,title:i,source:e,options:t,inputValues:{...t.inputs??{}},propValues:{...t.props??{}}}),this.startIndicator(n,e,t,o),o}addNativeIndicator(e,t={}){let n=$i(e);if(!n?.multiInstance){let l=this.registry.all().find(c=>c.native?.type===e);if(l)return this.handles.get(l.id)??new _r(l.id,l.title,this,void 0,e)}let i=this.registry.nextId("native"),o=n?.title??e,s=new _r(i,o,this,void 0,e);if(this.handles.set(i,s),!n)return console.warn(`[vela] addNativeIndicator("${e}") \u2014 no native indicator registered for this type.`),s;let a={...n.defaultInputs(),...t.inputs??{}};return this.registry.add({id:i,title:o,source:e,inputValues:a,propValues:{},native:{type:e,instance:n.create(),descriptor:n}}),s.setSchema(n.inputsSchema()),this.startNativeIndicator(i,s),s}presentNativeIndicators(){return this.registry.all().map(e=>e.native?.type).filter(e=>!!e)}async availableNativeIndicators(){let e=this.qualifiedSymbol(),t=new Set(this.presentNativeIndicators());return Promise.all(Is().map(async n=>({type:n.type,title:n.title,supported:await this.isNativeSupported(n,e),present:t.has(n.type),beta:n.beta,...n.multiInstance?{multiInstance:true}:{}})))}async isNativeSupported(e,t){if(!e.isSupported)return true;if(!t)return false;try{return await e.isSupported(t,this.dataControl)}catch{return false}}applyInputs(e,t){let n=this.registry.get(e);!n||!n.session&&!n.native||(n.inputValues={...n.inputValues,...t},n.renderHandle&&this.renderer.setIndicatorInputs(n.renderHandle,n.inputValues),n.pendingStructural=true,!n.hidden&&!n.native&&this.setLoading(n,true),n.pendingCause="inputs",n.session?n.session.update(n.inputValues):n.native&&!n.hidden&&n.native.instance.setInputs(n.inputValues),this.events.emit("indicator:inputs",{id:e}));}inputValuesOf(e){return {...this.registry.get(e)?.inputValues}}propValuesOf(e){return {...this.registry.get(e)?.propValues}}applyProps(e,t){let n=this.registry.get(e);n?.session&&(n.propValues={...n.propValues,...t},n.renderHandle&&this.renderer.setIndicatorInputs(n.renderHandle,n.inputValues,n.propValues),n.pendingStructural=true,n.hidden||this.setLoading(n,true),n.pendingCause="inputs",n.session.update(n.inputValues,n.propValues),this.events.emit("indicator:inputs",{id:e}));}listIndicators(){return [...this.handles.values()]}getIndicatorContext(e,t){return this.registry.get(e)?.session?.getContext?.(t)??Promise.resolve(null)}removeIndicator(e){let t=this.registry.remove(e);t?.native?.type==="volume"&&(this.volumeOptedOut=true),t?.session?.stop(),t?.native?.instance.stop(),this.handles.delete(e),t?.renderHandle&&this.renderer.removeIndicator(t.renderHandle);let n=t?.model?.paneId;n&&n!=="price"&&!this.paneStillUsed(n)&&(this.renderer.removePane(n),this.forgetPane(n),this.events.emit("pane:changed",void 0)),this.events.emit("indicator:removed",{id:e});}setVisible(e,t){let n=this.registry.get(e);if(!(!n||n.hidden===!t)){if(n.hidden=!t,this.handles.get(e)?.setVisibleState(t),!t)n.session?.stop(),n.session=void 0,n.native?.instance.suspend(),n.renderHandle&&this.renderer.setIndicatorVisible?.(n.renderHandle,false);else if(n.renderHandle&&this.renderer.setIndicatorVisible?.(n.renderHandle,true),n.pendingStructural=true,n.native)if(n.native.stale||!n.native.started){n.native.stale=false;let i=this.handles.get(e);i&&this.startNativeIndicator(e,i);}else n.native.instance.resume();else {this.setLoading(n,true);let i=this.handles.get(e);i&&this.executeIndicator(e,i);}this.events.emit("indicator:visibility",{id:e,visible:t});}}ready(){return this.readyPromise}inspect(){let e=[...this.registry.all()].filter(t=>!t.loading).sort((t,n)=>(n.native?1:0)-(t.native?1:0));return Lp(e.map(t=>t.model).filter(t=>t!=null))}resize(){this.renderer.resize();}setTheme(e){let t=this.config.theme;Object.keys(e).every(n=>e[n]===t[n])||(this.config.theme=e,this.renderer.setTheme(e),this.events.emit("theme:changed",e));}getVisibleRange(){return this.renderer.getVisibleRange()}setVisibleRange(e){this.renderer.setVisibleRange(e);}panBy(e){if(this.renderer.panBy){this.renderer.panBy(e);return}let t=this.renderer.getVisibleRange();if(!t)return;let n=(t.to-t.from)*e;this.renderer.setVisibleRange({from:t.from+n,to:t.to+n});}setVisibleRangePreset(e){let t=Mp(e,this.bars);t&&this.renderer.setVisibleRange(t);}destroy(){this.bumpGeneration(),this.resolveHistoryComplete(),this.stopLive(),this.viewportTimer!=null&&clearTimeout(this.viewportTimer),this.viewportUnsub?.(),this.paneActionUnsub?.();for(let e of this.registry.all())e.session?.stop(),e.native?.instance.stop();for(let e of this.typeEngines.values())e.stop();this.typeEngines.clear(),this.activeEngineStyle=null,this.unresolvedUnsub?.(),this.unresolvedUnsub=null,this.feed.destroy?.(),this.drawings.destroy(),this.renderer.destroy(),this.events.clear();}async startIndicator(e,t,n,i){try{if(await this.readyPromise,!this.registry.get(e))return;await OC();let o=this.registry.get(e);if(!o)return;let s=this.engineFor(n.language);o.engine=s;let a=await s.prepare(t,e);o.prepared=a;let l={};for(let d of a.inputs)l[d.key]=d.defval;o.inputValues={...l,...o.inputValues},i.setSchema(a.inputs);let c={};for(let d of a.props??[])c[d.key]=d.defval;o.propValues={...c,...o.propValues},i.setPropsSchema(a.props??[]),this.mountLoadingPlaceholder(e,o),this.executeIndicator(e,i);}catch(o){this.fail(e,i,o);}}executeIndicator(e,t){let n=this.registry.get(e);if(!n||!n.engine||!n.prepared||n.hidden)return;let i=this.config.live&&!n.prepared.reactsToViewport&&n.engine.capabilities.streaming?"live":"static";n.session=n.engine.execute({prepared:n.prepared,market:this.market(),bars:this.bars,getBars:()=>this.bars,fetchSeries:(o,s,a)=>this.fetchSeries(o,s,a),inputs:n.inputValues,props:n.propValues,visibleRange:this.currentVisibleRange(),mode:i,historyState:this.historyState},{onModel:o=>{let s=!n.announced,a=n.pendingCause??"history";this.applyModel(e,o)&&(n.pendingCause=void 0,this.emitContextChanged(e),this.emitScriptRun(e,a,s));},onAlert:o=>{let s=n.options?.title??n.prepared?.meta.title??n.title;this.events.emit("alert",{...o,indicator:s}),t.emit("alert",{id:o.id,message:o.message,title:o.title,time:o.time});},onWarning:o=>this.events.emit("warning",o),onError:o=>this.fail(e,t,o)}),this.emitContextChanged(e);}async startNativeIndicator(e,t){try{await this.readyPromise;let n=this.registry.get(e);if(!n?.native||n.hidden)return;let i={symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",live:this.config.live,session:this.config.market.session,bars:()=>this.bars,data:this.dataControl,emit:o=>this.applyModel(e,this.buildNativeModel(n,o)),pushData:o=>this.renderer.setNativeData?.(n.native.type,o),setStatus:o=>{n.renderHandle&&!n.hidden&&this.renderer.setIndicatorStatus?.(n.renderHandle,o);}};n.native.instance.start(i,n.inputValues),n.native.started=!0;}catch(n){this.fail(e,t,n);}}buildNativeModel(e,t){let n=e.native.descriptor;return {id:e.id,title:e.title,...n.shortTitle?{shorttitle:n.shortTitle}:{},overlay:n.overlay,paneHint:n.paneHint,native:{type:e.native.type},...t.paneAxis!=null?{paneAxis:t.paneAxis}:{},series:t.series??[],fills:t.fills??[],backgrounds:t.backgrounds??[],priceLines:t.priceLines??[],...t.lines?{lines:t.lines}:{},...t.boxes?{boxes:t.boxes}:{},...t.labels?{labels:t.labels}:{},...t.polylines?{polylines:t.polylines}:{},...t.linefills?{linefills:t.linefills}:{},...t.tables?{tables:t.tables}:{},inputs:n.inputsSchema(),inputValues:e.inputValues}}mountLoadingPlaceholder(e,t){if(t.renderHandle||t.hidden||!t.prepared)return;let n=t.prepared.meta,i={id:e,title:t.options?.title??n.title,overlay:n.overlay,paneHint:n.overlay?"price":"new",series:[],fills:[],backgrounds:[],priceLines:[],inputs:t.prepared.inputs,inputValues:t.inputValues,...t.prepared.props?{props:t.prepared.props,propValues:t.propValues}:{}},o=this.routePane(e,i,t.options??{});this.placeModel(i,e,o),t.model=i,this.ensurePaneFor(o),t.renderHandle=this.renderer.mountIndicator(i),t.pendingStructural=true,this.setLoading(t,true);}setLoading(e,t){e.loading=t,e.renderHandle&&!e.hidden&&this.renderer.setIndicatorStatus?.(e.renderHandle,t?"loading":"idle");}ensurePaneFor(e){this.paneOrder.includes(e)||this.paneOrder.push(e),this.renderer.ensurePane({id:e,kind:e==="price"?"price":"study",order:this.paneOrder.indexOf(e)});}paneStillUsed(e){for(let t of this.registry.all())if(t.model?.paneId===e)return true;return false}forgetPane(e){let t=this.paneOrder.indexOf(e);t>0&&this.paneOrder.splice(t,1),this.collapsedPanes.delete(e),this.maximizedPaneId===e&&(this.maximizedPaneId=null);}paneManagementSupported(){return this.renderer.capabilities.paneManagement===true&&typeof this.renderer.setIndicatorPane=="function"}listPanes(){let e=new Map;for(let n of this.registry.all()){let i=n.model;if(!i)continue;let o=i.paneId??"price";e.has(o)||e.set(o,[]),e.get(o).push({id:n.id,title:i.title||n.title,...i.shorttitle?{shorttitle:i.shorttitle}:{},ownScale:i.ownScale===true});}let t=[];for(let n of this.paneOrder)n!=="price"&&!e.has(n)||t.push({id:n,kind:n==="price"?"price":"study",order:t.length,collapsed:this.collapsedPanes.has(n),maximized:this.maximizedPaneId===n,indicators:e.get(n)??[]});return t}movePane(e,t){if(e==="price")return;let n=this.existingPaneIds(),i=n.indexOf(e);if(i<0)return;let o=t==="up"?i-1:i+1;o<=0||o>=n.length||([n[i],n[o]]=[n[o],n[i]],this.reorderPanes(n),this.events.emit("pane:moved",{paneId:e,dir:t}));}removePaneAndIndicators(e){if(e!=="price")for(let t of [...this.registry.all()])t.model?.paneId===e&&this.removeIndicator(t.id);}collapsePane(e,t){t?this.collapsedPanes.add(e):this.collapsedPanes.delete(e),this.renderer.setPaneCollapsed?.(e,t),this.events.emit("pane:changed",void 0);}maximizePane(e){this.maximizedPaneId=e,this.renderer.setPaneMaximized?.(e),this.events.emit("pane:changed",void 0);}moveIndicator(e,t){if(!this.paneManagementSupported()||!this.renderer.setIndicatorPane){console.warn("[vela] the active renderer does not support moving indicators between panes.");return}let n=this.registry.get(e);if(!n?.renderHandle||!n.model)return;let i=n.model,o=i.paneId??"price",s=this.resolveMoveTarget(e,i,t);if(!s)return;let{paneId:a,ownScale:l,insert:c}=s;a===o&&i.ownScale===true===l||(c?this.insertPaneOrder(a,c):this.paneOrder.includes(a)||this.paneOrder.push(a),i.ownScale=l,n.paneLocked=true,this.placeModel(i,e,a),this.ensurePaneFor(a),this.renderer.setIndicatorPane(n.renderHandle,a,{ownScale:l}),o!=="price"&&o!==a&&!this.paneStillUsed(o)&&(this.renderer.removePane(o),this.forgetPane(o)),this.reorderPanes(this.existingPaneIds()),this.events.emit("indicator:moved",{id:e,paneId:a}),this.events.emit("pane:changed",void 0));}resolveMoveTarget(e,t,n){if(n==="price"||typeof n=="object"&&"pane"in n&&n.pane==="price")return {paneId:"price",ownScale:!t.overlay};if("pane"in n)return this.existingPaneIds().includes(n.pane)?{paneId:n.pane,ownScale:true}:null;let i=n.newPane===true?{}:n.newPane;return {paneId:this.freshPaneId(e,t.paneId??"price"),ownScale:false,insert:i}}freshPaneId(e,t){let n=new Set(this.existingPaneIds()),i=`pane-${e}`;for(let o=2;i===t||n.has(i);o+=1)i=`pane-${e}-${o}`;return i}insertPaneOrder(e,t){let n=this.paneOrder.indexOf(e);n>0&&this.paneOrder.splice(n,1);let i=this.paneOrder.length;t.before&&this.paneOrder.includes(t.before)?i=this.paneOrder.indexOf(t.before):t.after&&this.paneOrder.includes(t.after)&&(i=this.paneOrder.indexOf(t.after)+1),i<1&&(i=1),this.paneOrder.splice(i,0,e);}existingPaneIds(){return this.paneOrder.filter(e=>e==="price"||this.paneStillUsed(e))}reorderPanes(e){this.paneOrder.length=0,this.paneOrder.push(...e),this.renderer.orderPanes?.(e),this.events.emit("pane:changed",void 0);}handlePaneAction(e){switch(e.type){case "remove":this.removePaneAndIndicators(e.paneId);break;case "move":{let t=this.existingPaneIds(),n=t.indexOf(e.paneId),i=e.dir==="up"?n-1:n+1;n>0&&i>0&&i<t.length&&([t[n],t[i]]=[t[i],t[n]],this.paneOrder.length=0,this.paneOrder.push(...t),this.events.emit("pane:changed",void 0),this.events.emit("pane:moved",{paneId:e.paneId,dir:e.dir}));break}case "collapse":e.collapsed?this.collapsedPanes.add(e.paneId):this.collapsedPanes.delete(e.paneId),this.events.emit("pane:changed",void 0);break;case "maximize":this.maximizedPaneId=e.maximized?e.paneId:null,this.events.emit("pane:changed",void 0);break}}announce(e,t){e.announced||(e.announced=true,this.events.emit("indicator:added",{id:e.id}),this.emitContextChanged(e.id),t?.emit("ready",void 0));}applyModel(e,t){let n=this.registry.get(e);if(!n||n.hidden)return true;if(n.loading&&this.bars.length===0&&!r.modelHasOutput(t))return false;let i=this.handles.get(e);if(!n.renderHandle){let a=this.routePane(e,t,n.options??{});return this.placeModel(t,e,a),n.model=t,this.ensurePaneFor(a),n.renderHandle=this.renderer.mountIndicator(t),n.pendingStructural=false,this.announce(n,i),true}let o=n.model?.paneId??"price",s=n.model?.ownScale===true;if(n.loading&&!n.paneLocked){let a=this.routePane(e,t,n.options??{});a!==o&&(o!=="price"&&(this.renderer.removePane(o),this.forgetPane(o)),this.ensurePaneFor(a),n.pendingStructural=true,o=a);}return this.placeModel(t,e,o),n.paneLocked&&(t.ownScale=s),n.model=t,n.pendingStructural?(n.renderHandle=this.renderer.mountIndicator(t),this.renderer.setIndicatorInputs(n.renderHandle,n.inputValues,n.propValues),n.pendingStructural=false):this.renderer.updateIndicator(n.renderHandle,NC(t)),n.loading&&this.setLoading(n,false),this.announce(n,i),true}static modelHasOutput(e){return e.series.length>0||e.fills.length>0||e.backgrounds.length>0||e.priceLines.length>0||(e.lines?.length??0)>0||(e.boxes?.length??0)>0||(e.labels?.length??0)>0||(e.polylines?.length??0)>0||(e.linefills?.length??0)>0||(e.tables?.length??0)>0||(e.barColors?.length??0)>0||(e.trades?.length??0)>0}routePane(e,t,n){return n.pane==="new"?`pane-${e}`:n.pane==="price"||(n.overlay??t.overlay)?"price":`pane-${e}`}static plotsAtLastBar(e){let t={};for(let n of e.series)Ne(n)&&(t[n.title]=n.points[n.points.length-1]?.value??null);return t}placeModel(e,t,n){e.id=t,e.paneId=n;let i=o=>o.overlay===true?"price":n;for(let o of e.series)o.paneId=i(o);for(let o of e.fills)o.paneId=i(o);for(let o of e.backgrounds)o.paneId=i(o);for(let o of e.priceLines)o.paneId=n;if(e.lines)for(let o of e.lines)o.paneId=i(o);if(e.boxes)for(let o of e.boxes)o.paneId=i(o);if(e.labels)for(let o of e.labels)o.paneId=i(o);if(e.polylines)for(let o of e.polylines)o.paneId=i(o);if(e.linefills)for(let o of e.linefills)o.paneId=i(o);if(e.tables)for(let o of e.tables)o.paneId=i(o);}emitContextChanged(e){if(!this.registry.get(e)?.session?.getContext)return;let t=Date.now();t-(this.contextEmitAt.get(e)??0)<1e3||(this.contextEmitAt.set(e,t),this.events.emit("context:changed",{id:e}));}emitScriptRun(e,t,n){let i=this.registry.get(e);if(!i||i.native||!this.events.hasListeners("script:run"))return;let o=Date.now();t==="tick"&&o-(this.runEmitAt.get(e)??0)<kC||(this.runEmitAt.set(e,o),Promise.resolve().then(()=>this.buildScriptRun(i,t,n)).then(s=>{s&&this.registry.get(e)&&this.events.emit("script:run",s);}));}async buildScriptRun(e,t,n){let i=e.model;if(!i)return null;let o=await this.pullContext(e,["variables","strategy","warnings"]),s=this.bars[this.bars.length-1];return {id:e.id,title:i.title,kind:o?.strategy||(i.trades?.length??0)>0?"strategy":"indicator",cause:t,first:n,bar:Math.max(0,this.bars.length-1),time:s?.time??0,forming:this.config.live&&this.bars.length>0,complete:this.historyState!=="backfill",plots:r.plotsAtLastBar(i),vars:o?.variables??{},...o?.strategy?{strategy:o.strategy}:{},warnings:o?.warnings??[],trades:async()=>(await this.pullContext(e,["trades"]))?.trades??[],series:async a=>((await this.pullContext(e,["plots"]))?.plots?.[a]??[]).map(c=>({time:c.time,value:typeof c.value=="number"?c.value:null}))}}async pullContext(e,t){try{return await e.session?.getContext?.(t)??null}catch{return null}}fail(e,t,n){let i=this.registry.get(e);i?.loading&&this.setLoading(i,false);let o=n instanceof Error?n:new Error(String(n));console.error(`[vela] indicator "${e}" failed:`,o.message),this.events.emit("indicator:error",{id:e,error:o}),t?.emit("error",{error:o});}};function OC(){return typeof requestAnimationFrame=="function"?new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(()=>r()))):new Promise(r=>setTimeout(r,0))}function NC(r){let e=[],t=Number.POSITIVE_INFINITY,n=0;for(let i of r.series)if(i.kind==="candle"||i.kind==="bar"){e.push({seriesId:i.id,kind:"bars",bars:i.bars});for(let o of i.bars)o.time<t&&(t=o.time),o.time>n&&(n=o.time);}else if(Ne(i)){e.push({seriesId:i.id,kind:"points",points:i.points});for(let o of i.points)o.time<t&&(t=o.time),o.time>n&&(n=o.time);}return {kind:"value",indicatorId:r.id,dirty:{from:Number.isFinite(t)?t:0,to:n},anchorTime:r.anchorTime??null,series:e,lines:r.lines??[],boxes:r.boxes??[],labels:r.labels??[],polylines:r.polylines??[],linefills:r.linefills??[],tables:r.tables??[],trades:r.trades??[]}}var so=class{constructor(e){this.renderer=e;}get name(){return this.renderer.name}get capabilities(){return this.renderer.capabilities}supports(e){return this.renderer.features.includes(e)}get(e){return this.renderer.readFeature(e)}set(e,t){let n=typeof e=="string"?[[e,t]]:Object.entries(e);for(let[i,o]of n)this.renderer.features.includes(i)?this.renderer.applyFeature(i,o):console.warn(`[vela] renderer "${this.renderer.name}" has no feature "${i}" \u2014 set ignored.`);return this}setLegendActions(e){this.renderer.setLegendActions?.(e);}setLegendCallouts(e){this.renderer.setLegendCallouts?.(e);}setLegendOverviewAction(e){return this.renderer.setLegendOverviewAction?.(e),this}get supportsIndicatorSettings(){return typeof this.renderer.openIndicatorSettings=="function"}openIndicatorSettings(e){return this.renderer.openIndicatorSettings?.(e),this}screenshot(){return typeof this.renderer.screenshot=="function"?this.renderer.screenshot():(console.warn(`[vela] renderer "${this.renderer.name}" does not support screenshot().`),null)}screenshotCanvas(){return typeof this.renderer.screenshotCanvas=="function"?this.renderer.screenshotCanvas():null}getConfig(){return typeof this.renderer.getConfig=="function"?this.renderer.getConfig():(console.warn(`[vela] renderer "${this.renderer.name}" does not support getConfig().`),null)}applyConfig(e){return typeof this.renderer.applyConfig=="function"?this.renderer.applyConfig(e):console.warn(`[vela] renderer "${this.renderer.name}" does not support applyConfig().`),this}onConfigChanged(e){return this.renderer.onConfigChanged?.(e)??(()=>{})}onCrosshairMove(e){return this.renderer.onCrosshairMove(e)}onAxisLongPress(e){return this.renderer.onAxisLongPress?.(e)??(()=>{})}dataWindowReadout(){return this.renderer.getDataWindowReadout?.()??null}setSymbolPicker(e){return typeof this.renderer.setSymbolPicker=="function"?this.renderer.setSymbolPicker(e):console.warn(`[vela] renderer "${this.renderer.name}" does not support setSymbolPicker().`),this}focus(){return this.renderer.focus?.(),this}get supportsExternalCrosshair(){return typeof this.renderer.setExternalCrosshair=="function"}setExternalCrosshair(e,t=null){return this.renderer.setExternalCrosshair?.(e,t),this}closeDialogs(){return this.renderer.closeDialogs?.(),this}openSettings(e){return this.renderer.openSettingsDialog?.(e),this}setSettingsSections(e){return this.renderer.setSettingsSections?.(e),this}setSettingsVisibility(e){return this.renderer.setSettingsVisibility?.(e),this}listSettingsIds(){return this.renderer.listSettingsIds?.()??[]}setLayoutMode(e){return this.renderer.setLayoutMode?.(e),this}};var qr=new Map;function FC(r){let e=Object.entries(r);for(let[t,n]of e)qr.set(t,n);return ()=>{for(let[t,n]of e)qr.get(t)===n&&qr.delete(t);}}function VC(...r){if(r.length===0)qr.clear();else for(let e of r)qr.delete(e);}function Ed(){return Object.fromEntries(qr)}var ja=class{constructor(e){this.controller=e;}get supported(){return this.controller.paneManagementSupported()}list(){return this.controller.listPanes()}move(e,t){return this.guard()&&this.controller.movePane(e,t),this}remove(e){return this.guard()&&this.controller.removePaneAndIndicators(e),this}collapse(e,t=true){return this.guard()&&this.controller.collapsePane(e,t),this}maximize(e){return this.guard()&&this.controller.maximizePane(e),this}moveIndicator(e,t){return this.guard()&&this.controller.moveIndicator(e,t),this}guard(){return this.controller.paneManagementSupported()?true:(console.warn("[vela] the active renderer does not support pane management \u2014 chart.panes mutation ignored."),false)}};function Sm(r,e,t,n){return `${r}|${e}|${t}${n&&n!=="regular"?`|${n}`:""}`}function _C(r){return r.split("|")[1]??""}var qa=class{constructor(){this.series=new Map;this.coveredFrom=new Map;this.retained=new Set;this.retainedByOwner=new Map;}get(e){return this.series.get(e)}markCovered(e,t){this.coveredFrom.set(e,Math.min(this.coveredFrom.get(e)??1/0,t));}coveredFromOf(e){return this.coveredFrom.get(e)}merge(e,t){if(t.length===0)return this.series.get(e)??[];let n=new Map;for(let o of this.series.get(e)??[])n.set(o.time,o);for(let o of t)n.set(o.time,o);let i=[...n.values()].sort((o,s)=>o.time-s.time);return this.series.set(e,i),i}retainSymbol(e){this.currentSymbol!==e&&(this.currentSymbol=e,this.purgeOutside(e));}retain(e,t="default"){e.size===0?this.retainedByOwner.delete(t):this.retainedByOwner.set(t,new Set(e));let n=new Set;for(let i of this.retainedByOwner.values())for(let o of i)n.add(o);this.retained=n,this.purgeOutside(this.currentSymbol);}purgeOutside(e){for(let t of [...this.series.keys()]){let n=_C(t);n!==e&&!this.retained.has(n)&&(this.series.delete(t),this.coveredFrom.delete(t));}}clear(){this.series.clear(),this.coveredFrom.clear();}},ao=new qa;function Pd(r,e,t){let{provider:n,ticker:i}=Wt(r);return Sm(n??"",i,e,t)}var co=1e4,BC=co+1,uo=class{constructor(e,t=ao){this.inner=e;this.store=t;}async load(e){if(e.data&&e.data.length>0)return this.inner.load(e);let t=e.symbol??"TEST",n=Pd(t,e.timeframe??"60",e.session);this.store.retainSymbol(t);let i=this.store.get(n),o=e.bars??500,s=i?.[i.length-1];if(i&&s&&i.length>=o-1&&this.inner.loadRange){let{bars:l}=await this.fetchRange(e,{from:s.time}),c=this.store.merge(n,lo(l));return Cm(c,l[l.length-1]).slice(-o)}let a=await this.inner.load(e);return this.store.merge(n,lo(a)),a}async loadProgressive(e,t,n){if(e.data&&e.data.length>0)return this.inner.load(e);if(!this.inner.loadProgressive)return null;let i=e.symbol??"TEST",o=Pd(i,e.timeframe??"60",e.session),s=this.store.get(o),a=e.bars??500,l=s?.[s.length-1];if(s&&l&&s.length>=a-1&&this.inner.loadRange)return this.load(e);this.store.retainSymbol(i);let c=await this.inner.loadProgressive(e,t,n);return c==null?null:(this.store.merge(o,lo(c)),c)}async loadRange(e,t){if(!this.inner.loadRange)return this.inner.load(e);let n=Pd(e.symbol??"TEST",e.timeframe??"60",e.session),i=this.store.get(n),o=i?.[i.length-1];if(t.to!=null&&o&&t.to<o.time){let d=i.filter(f=>f.time<=t.to),u=this.store.coveredFromOf(n)??1/0;if(t.limit!=null?d.length>=t.limit&&(t.from==null||u<=t.from):t.from!=null&&u<=t.from){let f=t.from!=null?d.filter(g=>g.time>=t.from):d;return t.limit!=null&&f.length>t.limit&&(f=f.slice(-t.limit)),f}let p=await this.fetchRange(e,t),m=p.bars.filter(f=>f.time<=t.to);return m.length>0&&(this.store.merge(n,m),this.store.markCovered(n,p.coveredDownTo??m[0].time)),m}if(o&&t.from!=null){let d=this.store.coveredFromOf(n);if(d!=null&&d>t.from){let{bars:u,coveredDownTo:h}=await this.fetchRange(e,{from:t.from,to:d});this.store.merge(n,u.filter(p=>p.time<=d)),this.store.markCovered(n,h??t.from),i=this.store.get(n),o=i?.[i.length-1];}}let s=this.store.coveredFromOf(n);if(!!i&&i.length>0&&!!o&&(t.from!=null?s!=null&&s<=t.from:t.limit==null||i.length>=t.limit)&&o){let{bars:d}=await this.fetchRange(e,{from:o.time,to:t.to,limit:t.limit}),u=this.store.merge(n,lo(d)),h=Cm(u,d[d.length-1]),p=t.from!=null?h.filter(m=>m.time>=t.from):h;return t.to!=null&&(p=p.filter(m=>m.time<=t.to)),p}let{bars:l,coveredDownTo:c}=await this.fetchRange(e,t);return this.store.merge(n,lo(l)),this.store.markCovered(n,c??t.from??l[0]?.time??0),l}async fetchRange(e,t){let n=Pt(e.timeframe??"60"),i=HC(t,n);if(i<=BC){let c=await this.inner.loadRange(e,{...t,limit:t.limit??i});return {bars:c,coveredDownTo:t.from??c[0]?.time}}let o=new Map,s=t.to??Date.now();for(;!(t.from!=null&&s<t.from);){let c=t.limit!=null?t.limit-o.size:co;if(c<=0)break;let d=await this.inner.loadRange(e,{to:s,limit:Math.min(co,c)}),u=1/0;for(let h of d)h.time<u&&(u=h.time),h.time<=s&&(t.from==null||h.time>=t.from)&&o.set(h.time,h);if(d.length===0){if(t.from==null)break;s-=co*n;continue}if(u-1>=s)break;s=u-1;}let a=[...o.values()].sort((c,d)=>c.time-d.time),l=t.from!=null&&s<t.from;return {bars:a,coveredDownTo:l?t.from:a[0]?.time}}subscribe(e,t){return this.inner.subscribe(e,t)}symbolInfo(e){return this.inner.symbolInfo?.(e)}};function HC(r,e){if(r.limit!=null)return r.limit;if(r.from==null)return co;let t=Math.max(0,(r.to??Date.now())-r.from);return Math.ceil(t/e*1.1)+2}function lo(r){return r.length>0?r.slice(0,-1):r}function Cm(r,e){if(!e)return r;let t=r[r.length-1];return !t||e.time>t.time?[...r,e]:r}function zC(r){return {"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,"1M":2592e6,1:6e4,5:3e5,15:9e5,30:18e5,60:36e5,240:144e5,D:864e5,W:6048e5,M:2592e6}[r]??36e5}var mr=class{constructor(e=ao){this.registry=new Ka;this.primaryProvider=null;this.liveBars=[];this.symInfoCache=new Map;this.cache=new uo(new Md(this.registry),e);}registerProvider(e,t){return this.registry.register(e,t)}unregisterProvider(e){this.registry.unregister(e);}providers(){return this.registry.names().map(e=>this.registry.infoOf(e))}resolveSymbol(e){return this.registry.resolve(e,{default:this.primaryProvider})}displayPrefix(e){let t=this.resolveSymbol(e);return t?this.registry.displayPrefixOf(t):null}canonicalSymbol(e){let t=this.resolveSymbol(e);return t?this.registry.canonicalSymbol(t):null}providerInstance(e){return this.registry.get(e)}symbolIconOf(e){return this.registry.symbolIconOf(e)}symbolIcon(e){return this.registry.symbolIcon(this.resolveSymbol(e))}symbols(e){return this.registry.symbolsOf(e)}onUnresolved(e){return this.registry.onUnresolved(e)}destroy(){this.registry.cancelWaits();}ready(){return this.registry.indexReady()}async symbolInfoFor(e){let t=this.registry.resolve(e,{default:this.primaryProvider});if(!t)return;let n=await this.registry.get(t.provider)?.getSymbolInfo?.(t.ticker);return n&&this.symInfoCache.set(Ld(t),n),n}capabilitiesFor(e){let t=this.registry.resolve(e,{default:this.primaryProvider});if(!t)return null;let n=this.registry.get(t.provider);return n?n.capabilitiesFor?.(t.ticker)??this.registry.infoOf(t.provider).capabilities:null}async load(e){if(e.data&&e.data.length>0)return this.liveBars=e.data.map(n=>({...n})),e.data;let t=await this.registry.whenResolvable(ho(e),{default:this.primaryProvider});return this.primaryProvider=t.provider,this.prefetchSymbolInfo(t),this.cache.load(Za(e,t))}async loadProgressive(e,t,n){if(e.data&&e.data.length>0)return this.liveBars=e.data.map(o=>({...o})),e.data;let i=await this.registry.whenResolvable(ho(e),{default:this.primaryProvider});return this.primaryProvider=i.provider,this.prefetchSymbolInfo(i),this.cache.loadProgressive(Za(e,i),t,n)}symbolInfo(e){if(e.data&&e.data.length>0)return;let t=this.registry.resolve(ho(e),{default:this.primaryProvider});return t?this.symInfoCache.get(Ld(t)):void 0}prefetchSymbolInfo(e){let t=Ld(e);if(this.symInfoCache.has(t))return;let n=this.registry.get(e.provider);n?.getSymbolInfo&&n.getSymbolInfo(e.ticker).then(i=>{i&&this.symInfoCache.set(t,i);}).catch(()=>{});}async loadRange(e,t){if(e.data&&e.data.length>0)return this.cache.loadRange(e,t);let n=this.registry.resolve(ho(e),{default:this.primaryProvider});return n?this.cache.loadRange(Za(e,n),t):[]}subscribe(e,t){if(e.data&&e.data.length>0)return this.synthesizeTicks(e,t);let n=this.registry.resolve(ho(e),{default:this.primaryProvider});return n?this.cache.subscribe(Za(e,n),t):()=>{}}synthesizeTicks(e,t){if(this.liveBars.length===0)return ()=>{};let n=zC(e.timeframe??"60"),i=setInterval(()=>{let o=this.liveBars,s=o[o.length-1];if(!s)return;let a=s.close*.0015*(Math.random()-.5)*2,l=Math.max(0,s.close+a),c={...s,close:l,high:Math.max(s.high,l),low:Math.min(s.low,l)};if(o[o.length-1]=c,t(c),Math.random()<.12){let d={time:c.time+n,open:c.close,high:c.close,low:c.close,close:c.close,volume:0};o.push(d),t(d);}},1e3);return ()=>clearInterval(i)}};function ho(r){return r.symbol??""}function Za(r,e){return {...r,symbol:`${e.provider}:${e.ticker}`}}function Ld(r){return `${r.provider}|${r.ticker}`}async function Tm(r,e,t,n){try{return await r.getBars(e,t,n)}catch(i){return console.warn(`[vela] data fetch failed for ${e} ${t} \u2014 ${i instanceof Error?i.message:String(i)}`),[]}}var Md=class{constructor(e){this.registry=e;}load(e){let{provider:t,ticker:n}=Wt(e.symbol??""),i=this.registry.get(t??"");return i?Tm(i,n,e.timeframe??"60",{limit:e.bars??500,session:e.session}):Promise.resolve([])}async loadProgressive(e,t,n){let{provider:i,ticker:o}=Wt(e.symbol??""),s=this.registry.get(i??"");if(!s)return [];if(!s.getBarsProgressive)return null;try{return await s.getBarsProgressive(o,e.timeframe??"60",{limit:e.bars??500,session:e.session},t,n)}catch(a){return console.warn(`[vela] progressive fetch failed for ${o} ${e.timeframe??"60"} \u2014 ${a instanceof Error?a.message:String(a)}`),[]}}loadRange(e,t){let{provider:n,ticker:i}=Wt(e.symbol??""),o=this.registry.get(n??"");return o?Tm(o,i,e.timeframe??"60",{...t,session:e.session}):Promise.resolve([])}subscribe(e,t){let{provider:n,ticker:i}=Wt(e.symbol??""),o=this.registry.get(n??"");if(!o)return ()=>{};let s=e.timeframe??"60";if(o.subscribe)return o.subscribe(i,s,t,e.session?{session:e.session}:void 0);let a=false,l=null,c=async()=>{if(!a){try{let d=await o.getBars(i,s,{limit:2,session:e.session});if(a)return;for(let u of d)t(u);}catch{}a||(l=setTimeout(()=>{c();},3e3));}};return l=setTimeout(()=>{c();},3e3),()=>{a=true,l&&clearTimeout(l);}}};var po=class{constructor(e){this.registry=e instanceof mr?e:null;}registerProvider(e,t){return this.registry?(this.registry.registerProvider(e,t),this):(console.warn(`[vela] chart.data.registerProvider("${e}") ignored \u2014 the active data feed is a custom feed (deps.dataFeed), not the default provider registry.`),this)}unregisterProvider(e){return this.registry?.unregisterProvider(e),this}providers(){return this.registry?.providers()??[]}resolve(e){return this.registry?.resolveSymbol(e)??null}displayPrefix(e){return this.registry?.displayPrefix(e)??null}canonicalSymbol(e){return this.registry?.canonicalSymbol(e)??null}providerInstance(e){return this.registry?.providerInstance(e)}symbols(e){return this.registry?.symbols(e)??[]}symbolIcon(e){return this.registry?.symbolIcon(e)}symbolInfo(e){return this.registry?.symbolInfoFor(e)??Promise.resolve(void 0)}capabilities(e){return this.registry?.capabilitiesFor(e)??null}ready(){return this.registry?.ready()??Promise.resolve()}};var mo=class{constructor(e){this.ctrl=e;}get supported(){return this.ctrl.supported}setTool(e){return this.ok("setTool")&&this.ctrl.setTool(e),this}getTool(){return this.ctrl.getTool()}setSnapMode(e){return this.ok("setSnapMode")&&this.ctrl.setSnapMode(e),this}getSnapMode(){return this.ctrl.getSnapMode()}setStayMode(e){return this.ok("setStayMode")&&this.ctrl.setStayMode(e),this}getStayMode(){return this.ctrl.getStayMode()}setMode(e){return this.ok("setMode")&&this.ctrl.setMode(e),this}getMode(){return this.ctrl.getMode()}showToolbar(e=true){return this.ok("showToolbar")&&this.ctrl.showToolbar(e),this}setToolbar(e){return this.ok("setToolbar")&&this.ctrl.setToolbar(e),this}setToolShortcuts(e){return this.ok("setToolShortcuts")&&this.ctrl.setToolShortcuts(e),this}setExternalGhost(e){return this.ctrl.setExternalGhost(e),this}add(e,t={}){return this.ok("add")?this.ctrl.add(e,t):null}remove(e){return this.ctrl.remove(e),this}update(e,t){return this.ctrl.update(e,t),this}updateMany(e){return this.ctrl.updateMany(e),this}removeMany(e){return this.ctrl.removeMany(e),this}lock(e,t=true){return this.ctrl.setLocked(e,t),this}show(e,t=true){return this.ctrl.setVisible(e,t),this}select(e){return this.ok("select")&&this.ctrl.select(e==null?[]:typeof e=="string"?[e]:e),this}openSettings(e){return this.ok("openSettings")&&this.ctrl.openSettings(e),this}bringToFront(e){return this.ctrl.bringToFront(e),this}sendToBack(e){return this.ctrl.sendToBack(e),this}undo(){return this.ctrl.undo(),this}redo(){return this.ctrl.redo(),this}canUndo(){return this.ctrl.canUndo()}canRedo(){return this.ctrl.canRedo()}clone(e){return this.ok("clone")&&this.ctrl.clone(e),this}duplicate(e){return this.ok("duplicate")&&this.ctrl.duplicate(e),this}copyToClipboard(e){return this.ok("copy")&&this.ctrl.copy(e),this}paste(){return this.ok("paste")&&this.ctrl.paste(),this}all(){return this.ctrl.all()}toJSON(){return this.ctrl.toJSON()}fromJSON(e){return this.ctrl.fromJSON(e),this}favorites(){return this.ctrl.favorites()}isFavorite(e){return this.ctrl.isFavorite(e)}setFavorite(e,t){return this.ok("setFavorite")&&this.ctrl.setFavorite(e,t),this}setFavorites(e){return this.ok("setFavorites")&&this.ctrl.setFavorites([...e]),this}getConfig(){return this.ctrl.toJSON()}applyConfig(e){return this.ctrl.fromJSON(e),this}ok(e){return this.ctrl.supported?true:(console.warn(`[vela] chart.drawings.${e}() ignored \u2014 the active renderer has no userDrawings capability.`),false)}};function Ja(r){let e=r.trim(),t=/^#([0-9a-f]{3})$/i.exec(e);if(t){let i=t[1];return {r:parseInt(i[0]+i[0],16),g:parseInt(i[1]+i[1],16),b:parseInt(i[2]+i[2],16)}}if(t=/^#([0-9a-f]{6})[0-9a-f]{0,2}$/i.exec(e),t){let i=t[1];return {r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16)}}let n=/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i.exec(e);return n?{r:parseFloat(n[1]),g:parseFloat(n[2]),b:parseFloat(n[3])}:null}function q(r,e){let t=Ja(r);return t?`rgba(${t.r},${t.g},${t.b},${e})`:r}function Em(r,e,t){let n=Ja(r),i=Ja(e);if(!n||!i)return r;let o=(s,a)=>Math.round(s+(a-s)*t);return `rgb(${o(n.r,i.r)},${o(n.g,i.g)},${o(n.b,i.b)})`}function lt(r){let e=Ja(r);return e?.2126*e.r+.7152*e.g+.0722*e.b<128:true}var Qa={"--vela-space-1":"4px","--vela-space-2":"8px","--vela-space-3":"12px","--vela-space-4":"16px","--vela-radius-sm":"4px","--vela-radius-md":"6px","--vela-radius-lg":"10px","--vela-z-tooltip":"60","--vela-z-menu":"50","--vela-z-dialog":"40","--vela-z-popover":"6000","--vela-ease":"cubic-bezier(0.22, 1, 0.36, 1)","--vela-dur-fast":"90ms","--vela-dur-med":"160ms","--vela-font-size-sm":"11px","--vela-font-size-md":"12px","--vela-font-size-lg":"14px"};function el(r){let e=lt(r.background),t=i=>e?`rgba(255,255,255,${i})`:q(r.textColor,i+.02),n=Em(r.background,e?"#ffffff":r.textColor,e?.03:.05);return {"--vela-font":r.fontFamily,"--vela-bg":r.background,"--vela-fg":e?"#d1d4dc":r.textColor,"--vela-fg-muted":e?"#868a96":q(r.textColor,.62),"--vela-fg-faint":q(r.textColor,.35),"--vela-fg-bright":e?"#f0f3fa":"#000000","--vela-surface":r.background,"--vela-surface-elev":n,"--vela-surface-overlay":n,"--vela-surface-sunken":r.background,"--vela-border":r.borderColor,"--vela-border-strong":e?"#34353b":q(r.textColor,.28),"--vela-border-soft":r.borderColor,"--vela-border-faint":q(r.textColor,.08),"--vela-hover":t(.06),"--vela-active":t(.1),"--vela-hover-strong":t(.16),"--vela-focus":q(r.textColor,.5),"--vela-focus-soft":q(r.textColor,.12),"--vela-separator-hover-band":q(r.textColor,.1),"--vela-separator-hover-line":q(r.textColor,.55),"--vela-scroll":q(r.textColor,.3),"--vela-accent":Ye,"--vela-accent-bright":Br,"--vela-highlight":kp,"--vela-selected-bg":e?"#f0f3fa":r.textColor,"--vela-selected-fg":e?r.background:"#ffffff","--vela-fg-on-fill":"#ffffff","--vela-up":r.upColor,"--vela-down":r.downColor,"--vela-danger":r.downColor,"--vela-shadow":"0 8px 30px rgba(0,0,0,0.5)","--vela-shadow-dialog":"0 20px 60px rgba(0,0,0,0.5)","--vela-backdrop":"rgba(0,0,0,0.45)"}}function Ae(r,e){let t=n=>{for(let i in n)r.style.setProperty(i,n[i]);};t(Qa),t(el(e));}function Ut(r,e){let t=null,n=null,i=()=>{t!==null&&(clearTimeout(t),t=null),n?.remove(),n=null;},o=()=>{let a=e.text();if(!a)return;n=r.ownerDocument.createElement("div"),n.textContent=a,n.style.cssText="position:absolute;z-index:var(--vela-z-tooltip);pointer-events:none;background:var(--vela-bg);border:1px solid var(--vela-border);color:var(--vela-fg);border-radius:var(--vela-radius-md);padding:4px 9px;box-shadow:var(--vela-shadow);font:var(--vela-font-size-md) var(--vela-font);"+(e.wrap?"max-width:260px;":"white-space:nowrap;"),Ae(n,e.theme()),e.host.appendChild(n);let c=r.getBoundingClientRect(),d=e.host.getBoundingClientRect();if(e.placement==="right")n.style.left=`${c.right-d.left+8}px`,n.style.top=`${c.top-d.top+(c.height-n.offsetHeight)/2}px`;else {let u=Math.min(c.left-d.left,Math.max(0,d.width-n.offsetWidth-4));n.style.left=`${Math.max(0,u)}px`,n.style.top=e.placement==="above"?`${Math.max(0,c.top-d.top-n.offsetHeight-6)}px`:`${c.bottom-d.top+6}px`;}},s=a=>{a.pointerType==="mouse"&&(i(),t=window.setTimeout(o,e.delayMs??700));};return r.addEventListener("pointerenter",s),r.addEventListener("pointerleave",i),r.addEventListener("pointerdown",i),()=>{r.removeEventListener("pointerenter",s),r.removeEventListener("pointerleave",i),r.removeEventListener("pointerdown",i),i();}}function tl(r,e){let t=e.size??16,n=document.createElement("span");n.className="vela-hint",n.setAttribute("role","img"),n.setAttribute("aria-label",r),n.innerHTML=ye("info",t),n.style.cssText=`flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:${t}px;height:${t}px;border-radius:50%;cursor:help;user-select:none;background:var(--vela-hover);color:var(--vela-fg-muted);transition:background var(--vela-dur-fast) ease,color var(--vela-dur-fast) ease;`;let i=s=>{n.style.background=s?"var(--vela-active)":"var(--vela-hover)",n.style.color=s?"var(--vela-fg-bright)":"var(--vela-fg-muted)";};n.addEventListener("pointerenter",()=>i(true)),n.addEventListener("pointerleave",()=>i(false));let o=Ut(n,{host:e.host,theme:e.theme,text:()=>r,wrap:true,delayMs:250});return {el:n,dispose:o}}var $C=Object.defineProperty,WC=(r,e,t)=>e in r?$C(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t,le=(r,e,t)=>WC(r,typeof e!="symbol"?e+"":e,t);function Pm(r){return r==null?[]:Array.isArray(r)?r:[r]}var Lm=r=>r[0],Mm=r=>r[r.length-1];function km(r,e,t={}){let{step:n=1,loop:i=true}=t,o=e+n,s=r.length,a=s-1;return e===-1?n>0?0:a:o<0?i?a:0:o>=s?i?0:e>s?s:e:o}function Im(r,e,t={}){return r[km(r,e,t)]}function GC(r,e,t={}){let{step:n=1,loop:i=true}=t;return km(r,e,{step:-n,loop:i})}function Am(r,e,t={}){return r[GC(r,e,t)]}var Rm=r=>r?.constructor.name==="Array",UC=(r,e)=>{if(r.length!==e.length)return false;for(let t=0;t<r.length;t++)if(!Zr(r[t],e[t]))return false;return true},Zr=(r,e)=>{if(Object.is(r,e))return true;if(r==null&&e!=null||r!=null&&e==null)return false;if(typeof r?.isEqual=="function"&&typeof e?.isEqual=="function")return r.isEqual(e);if(typeof r=="function"&&typeof e=="function")return r.toString()===e.toString();if(Rm(r)&&Rm(e))return UC(Array.from(r),Array.from(e));if(typeof r!="object"||typeof e!="object")return false;let t=Object.keys(e??Object.create(null)),n=t.length;for(let i=0;i<n;i++)if(!Reflect.has(r,t[i]))return false;for(let i=0;i<n;i++){let o=t[i];if(!Zr(r[o],e[o]))return false}return true};var YC=r=>r!=null&&typeof r=="object";var Jr=r=>typeof r=="string",nt=r=>typeof r=="function",Dm=r=>r==null,fo=(r,e)=>Object.prototype.hasOwnProperty.call(r,e),KC=r=>Object.prototype.toString.call(r),Om=Function.prototype.toString,XC=Om.call(Object),fr=r=>{if(!YC(r)||KC(r)!="[object Object]"||ZC(r))return false;let e=Object.getPrototypeOf(r);if(e===null)return true;let t=fo(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Om.call(t)==XC},jC=r=>typeof r=="object"&&r!==null&&"$$typeof"in r&&"props"in r,qC=r=>typeof r=="object"&&r!==null&&"__v_isVNode"in r,ZC=r=>jC(r)||qC(r);var go=(r,...e)=>(typeof r=="function"?r(...e):r)??void 0,kd=r=>r,Nm=r=>r(),Id=()=>{},Dn=(...r)=>(...e)=>{r.forEach(function(t){t?.(...e);});};function On(r){if(!fr(r)||r===void 0)return r;let e=Reflect.ownKeys(r).filter(n=>typeof n=="string"),t={};for(let n of e){let i=r[n];i!==void 0&&(t[n]=On(i));}return t}function Qr(...r){r.length===1?r[0]:r[1];r.length===2?r[0]:true;}function Ad(...r){r.length===1?r[0]:r[1];r.length===2?r[0]:true;}function bo(r,e){if(r==null)throw new Error(e())}var JC=(...r)=>r.map(e=>e?.trim?.()).filter(Boolean).join(" "),QC=/((?:--)?(?:\w+-?)+)\s*:\s*([^;]*)/g,Fm=r=>{let e={},t;for(;t=QC.exec(r);)e[t[1]]=t[2];return e},e1=(r,e)=>{if(Jr(r)){if(Jr(e))return `${r};${e}`;r=Fm(r);}else Jr(e)&&(e=Fm(e));return Object.assign({},r??{},e??{})};function Vm(...r){let e={};for(let t of r){if(!t)continue;for(let i in e){if(i.startsWith("on")&&typeof e[i]=="function"&&typeof t[i]=="function"){e[i]=Dn(t[i],e[i]);continue}if(i==="className"||i==="class"){e[i]=JC(e[i],t[i]);continue}if(i==="style"){e[i]=e1(e[i],t[i]);continue}e[i]=t[i]!==void 0?t[i]:e[i];}for(let i in t)e[i]===void 0&&(e[i]=t[i]);let n=Object.getOwnPropertySymbols(t);for(let i of n)e[i]=t[i];}return e}var Nn=".",Hm="#",_m=new WeakMap,zm=new WeakMap;function Rd(r){return r.join(Nn)}function t1(r){return r.includes(Nn)}function $m(r){return r.startsWith(Hm)}function n1(r){return r.startsWith(Nn)}function r1(r){return $m(r)?r.slice(Hm.length):r}function Dd(r,e){return r?`${r}${Nn}${e}`:e}function i1(r){let e=new Map,t=new Map,n=(i,o)=>{e.set(i,o);let s=o.id;s&&(t.has(s)&&Ad(`[zag-js] Duplicate state id: "${s}"`),t.set(s,i));let a=o.states;if(a){bo(o.initial,()=>`[zag-js] Compound state "${i}" has child states but no "initial" property`),o.initial in a||Ad(`[zag-js] Compound state "${i}" has initial "${String(o.initial)}" which is not a child state`);for(let[l,c]of Object.entries(a)){if(!c)continue;let d=Dd(i,l);n(d,c);}}};for(let[i,o]of Object.entries(r.states))o&&n(i,o);return {index:e,idIndex:t}}function ei(r){let e=_m.get(r);if(e)return e;let{index:t,idIndex:n}=i1(r);return _m.set(r,t),zm.set(r,n),t}function o1(r,e){return ei(r),zm.get(r)?.get(e)}function Od(r){return r?String(r).split(Nn).filter(Boolean):[]}function nl(r,e){if(!e)return [];let t=ei(r),n=Od(e),i=[],o=[];for(let s of n){o.push(s);let a=Rd(o),l=t.get(a);if(!l)break;i.push({path:a,state:l});}return i}function vo(r,e){let t=ei(r),n=Od(e);if(!n.length)return e;let i=[];for(let a of n){i.push(a);let l=Rd(i);if(!t.has(l))return e}let o=Rd(i),s=t.get(o);for(;s?.initial;){let a=`${o}${Nn}${s.initial}`,l=t.get(a);if(!l)break;o=a,s=l;}return o}function Bm(r,e){return ei(r).has(e)}function Nd(r,e,t){let n=String(e);if($m(n)){let i=r1(n),o=o1(r,i);return bo(o,()=>`[zag-js] Unknown state id: "${i}"`),vo(r,o)}if(n1(n)&&t){let i=Dd(t,n.slice(1));return vo(r,i)}if(!t1(n)&&t){let i=Od(t);for(let o=i.length-1;o>=1;o--){let s=i.slice(0,o).join(Nn),a=Dd(s,n);if(Bm(r,a))return vo(r,a)}if(Bm(r,n))return vo(r,n)}return vo(r,n)}function Wm(r,e,t){let n=nl(r,e);for(let o=n.length-1;o>=0;o--){let a=n[o]?.state.on?.[t];if(a)return {transitions:a,source:n[o]?.path}}return {transitions:r.on?.[t],source:void 0}}function Gm(r,e,t,n){let i=e?nl(r,e):[],o=nl(r,t),s=0;for(;s<i.length&&s<o.length&&i[s]?.path===o[s]?.path;)s+=1;let a=i.slice(s).reverse(),l=o.slice(s),c=i.at(-1)?.path===o.at(-1)?.path;return n&&c&&(a=i.slice().reverse(),l=o),{exiting:a,entering:l}}function Um(r,e){return r?r===e||r.startsWith(`${e}${Nn}`):false}function Ym(r,e,t){return nl(r,e).some(n=>n.state.tags?.includes(t))}function Km(){return {and:(...r)=>function(t){return r.every(n=>t.guard(n))},or:(...r)=>function(t){return r.some(n=>t.guard(n))},not:r=>function(t){return !t.guard(r)}}}function rl(r){return ei(r),r}var ti=(r=>(r.NotStarted="Not Started",r.Started="Started",r.Stopped="Stopped",r))(ti||{}),yo="__init__";var s1=Object.defineProperty,a1=(r,e,t)=>e in r?s1(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t,il=(r,e,t)=>a1(r,typeof e!="symbol"?e+"":e,t);var Xm=(r,e)=>r.map((t,n)=>r[(Math.max(e,0)+n)%r.length]);var wo=()=>{},xo=r=>typeof r=="object"&&r!==null;var mt=r=>r?"":void 0,Fd=r=>r?"true":void 0;var l1=1,c1=9,d1=11;var ce=r=>xo(r)&&r.nodeType===l1&&typeof r.nodeName=="string",So=r=>xo(r)&&r.nodeType===c1,u1=r=>xo(r)&&r===r.window;var jm=r=>ce(r)?r.localName||"":"#document";function qm(r){return ["html","body","#document"].includes(jm(r))}var Zm=r=>xo(r)&&r.nodeType!==void 0,gr=r=>Zm(r)&&r.nodeType===d1&&"host"in r,Vd=r=>ce(r)&&r.localName==="input",Jm=r=>!!r?.matches("a[href]"),Qm=r=>ce(r)?r.offsetWidth>0||r.offsetHeight>0||r.getClientRects().length>0:false;function Co(r){if(!r)return false;let e=r.getRootNode();return Yt(e)===r}var h1=/(textarea|select)/;function ni(r){if(r==null||!ce(r))return false;try{return Vd(r)&&r.selectionStart!=null||h1.test(r.localName)||r.isContentEditable||r.getAttribute("contenteditable")==="true"||r.getAttribute("contenteditable")===""}catch{return false}}function rt(r,e){if(!r||!e||!ce(r)||!Zm(e))return false;if(ce(e)&&r===e||r.contains(e))return true;let t=e.getRootNode?.();if(t&&gr(t)){let n=e;for(;n;){if(r===n)return true;n=n.parentNode||n.host;}}return false}function Pe(r){return So(r)?r:u1(r)?r.document:r?.ownerDocument??document}function p1(r){return Pe(r).documentElement}function Se(r){return gr(r)?Se(r.host):So(r)?r.defaultView??window:ce(r)?r.ownerDocument?.defaultView??window:window}function Yt(r){let e=r.activeElement;for(;e?.shadowRoot;){let t=e.shadowRoot.activeElement;if(!t||t===e)break;e=t;}return e}function ef(r){if(jm(r)==="html")return r;let e=r.assignedSlot||r.parentNode||gr(r)&&r.host||p1(r);return gr(e)?e.host:e}function ol(r){let e;try{if(e=r.getRootNode({composed:!0}),So(e)||gr(e))return e}catch{}return r.ownerDocument??document}var _d=new WeakMap;function ri(r){return _d.has(r)||_d.set(r,Se(r).getComputedStyle(r)),_d.get(r)}var Bd=new Set(["menu","listbox","dialog","grid","tree","region","application"]),m1=r=>Bd.has(r),tf=r=>r.getAttribute("aria-controls")?.split(" ")||[];function sl(r,e){let t=new Set,n=ol(r),i=o=>{let s=o.querySelectorAll("[aria-controls]");for(let a of s){if(a.getAttribute("aria-expanded")!=="true")continue;let l=tf(a);for(let c of l){if(!c||t.has(c))continue;t.add(c);let d=n.getElementById(c);if(d){let u=d.getAttribute("role"),h=d.getAttribute("aria-modal")==="true";if(u&&m1(u)&&!h&&(d===e||d.contains(e)||i(d)))return true}}}return false};return i(r)}function Hd(r,e){let t=ol(r),n=new Set,i=o=>{let s=o.querySelectorAll("[aria-controls]");for(let a of s){if(a.getAttribute("aria-expanded")!=="true")continue;let l=tf(a);for(let c of l){if(!c||n.has(c))continue;n.add(c);let d=t.getElementById(c);if(d){let u=d.getAttribute("role"),h=d.getAttribute("aria-modal")==="true";u&&Bd.has(u)&&!h&&(e(d),i(d));}}}};i(r);}function nf(r){let e=new Set;return Hd(r,t=>{r.contains(t)||e.add(t);}),Array.from(e)}function f1(r){let e=r.getAttribute("role");return !!(e&&Bd.has(e))}function g1(r){return r.hasAttribute("aria-controls")&&r.getAttribute("aria-expanded")==="true"}function rf(r){return g1(r)?true:!!r.querySelector?.('[aria-controls][aria-expanded="true"]')}function of(r){if(!r.id)return false;let e=ol(r),t=CSS.escape(r.id),n=`[aria-controls~="${t}"][aria-expanded="true"], [aria-controls="${t}"][aria-expanded="true"]`;return !!(e.querySelector(n)&&f1(r))}var zd=()=>typeof document<"u";function b1(){return navigator.userAgentData?.platform??navigator.platform}function v1(){let r=navigator.userAgentData;return r&&Array.isArray(r.brands)?r.brands.map(({brand:e,version:t})=>`${e}/${t}`).join(" "):navigator.userAgent}var $d=r=>zd()&&r.test(b1()),sf=r=>zd()&&r.test(v1());var Wd=()=>zd()&&!!navigator.maxTouchPoints,y1=()=>$d(/^iPhone/i),w1=()=>$d(/^iPad/i)||ii()&&navigator.maxTouchPoints>1,af=()=>y1()||w1();var ii=()=>$d(/^Mac/i);var lf=()=>sf(/Firefox/i);var cf=()=>sf(/Android/i);function x1(r){return r.composedPath?.()??r.nativeEvent?.composedPath?.()}function Re(r){return x1(r)?.[0]??r.target}function Gd(r){let e=r.currentTarget;if(!e||!e.matches("a[href], button[type='submit'], input[type='submit']"))return false;let n=r.button===1,i=S1(r);return n||i}function Ud(r){let e=r.currentTarget;if(!e)return false;let t=e.localName;return r.altKey?t==="a"||t==="button"&&e.type==="submit"||t==="input"&&e.type==="submit":false}function S1(r){return ii()?r.metaKey:r.ctrlKey}function uf(r){return r.key.length===1&&!r.ctrlKey&&!r.metaKey}function hf(r){return r.pointerType===""&&r.isTrusted?true:cf()&&r.pointerType?r.type==="click"&&r.buttons===1:r.detail===0&&!r.pointerType}var al=r=>r.button===2||ii()&&r.ctrlKey&&r.button===0,pf=r=>r.ctrlKey||r.altKey||r.metaKey,C1=r=>"touches"in r&&r.touches.length>0,T1={Up:"ArrowUp",Down:"ArrowDown",Esc:"Escape"," ":"Space",",":"Comma",Left:"ArrowLeft",Right:"ArrowRight"},df={ArrowLeft:"ArrowRight",ArrowRight:"ArrowLeft"};function Yd(r,e={}){let{dir:t="ltr",orientation:n="horizontal"}=e,i=r.key;return i=T1[i]??i,t==="rtl"&&n==="horizontal"&&i in df&&(i=df[i]),i}function oi(r,e="client"){let t=C1(r)?r.touches[0]||r.changedTouches[0]:r;return {x:t[`${e}X`],y:t[`${e}Y`]}}var Xe=(r,e,t,n)=>{let i=typeof r=="function"?r():r;return i?.addEventListener(e,t,n),()=>{i?.removeEventListener(e,t,n);}};var mf=r=>ce(r)&&r.tagName==="IFRAME",E1=/^(audio|video|details)$/;function ff(r){let e=r.getAttribute("tabindex");return e?parseInt(e,10):NaN}var P1=r=>!Number.isNaN(ff(r)),L1=r=>ff(r)<0;function M1(r){return Vd(r)&&r.type==="radio"}function k1(r){if(!M1(r)||!r.name||r.checked)return true;let e=`input[type="radio"][name="${CSS.escape(r.name)}"]`,t=r.form??r.ownerDocument,n=Array.from(t.querySelectorAll(e)).filter(o=>o.form===r.form&&ft(o)),i=n.find(o=>o.checked);return i?i===r:n[0]===r}function I1(r,e){if(!e)return null;if(e===true)return r.shadowRoot||null;let t=e(r);return (t===true?r.shadowRoot:t)||null}function gf(r,e,t){let n=[...r],i=[...r],o=new Set,s=new Map;r.forEach((l,c)=>s.set(l,c));let a=0;for(;a<i.length;){let l=i[a++];if(!l||o.has(l))continue;o.add(l);let c=I1(l,e);if(c){let d=Array.from(c.querySelectorAll(ll)).filter(t),u=s.get(l);if(u!==void 0){let h=u+1;n.splice(h,0,...d),d.forEach((p,m)=>{s.set(p,h+m);});for(let p=h+d.length;p<n.length;p++)s.set(n[p],p);}else {let h=n.length;n.push(...d),d.forEach((p,m)=>{s.set(p,h+m);});}i.push(...d);}}return n}var ll="input:not([type='hidden']):not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], button:not([disabled]), [tabindex], iframe, object, embed, area[href], audio[controls], video[controls], [contenteditable]:not([contenteditable='false']), details > summary:first-of-type",Kd=(r,e={})=>{if(!r)return [];let{includeContainer:t=false,getShadowRoot:n}=e,i=Array.from(r.querySelectorAll(ll));(t==true||t=="if-empty"&&i.length===0)&&ce(r)&&ft(r)&&i.unshift(r);let s=[];for(let a of i)if(ft(a)){if(mf(a)&&a.contentDocument){let l=a.contentDocument.body;s.push(...Kd(l,{getShadowRoot:n}));continue}s.push(a);}return n?gf(s,n,ft):s};function ft(r){return !ce(r)||r.closest("[inert]")?false:r.matches(ll)&&Qm(r)}function si(r,e={}){if(!r)return [];let{includeContainer:t,getShadowRoot:n}=e,i=Array.from(r.querySelectorAll(ll));t&&Fn(r)&&i.unshift(r);let o=[];for(let s of i)if(Fn(s)){if(mf(s)&&s.contentDocument){let a=s.contentDocument.body;o.push(...si(a,{getShadowRoot:n}));continue}o.push(s);}if(n){let s=gf(o,n,Fn);return !s.length&&t?i:s}return !o.length&&t?i:o}function Fn(r){return ce(r)&&r.tabIndex>0?true:!ft(r)||L1(r)?false:k1(r)}function bf(r,e={}){let t=si(r,e),n=t[0]||null,i=t[t.length-1]||null;return [n,i]}function ai(r){return r.tabIndex<0&&(E1.test(r.localName)||ni(r))&&!P1(r)?0:r.tabIndex}function cl(r){let{root:e,getInitialEl:t,filter:n,enabled:i=true}=r;if(!i)return;let o=null;if(o||(o=typeof t=="function"?t():t),o||(o=e?.querySelector("[data-autofocus],[autofocus]")),!o){let s=si(e);o=n?s.filter(n)[0]:s[0];}return o||e||void 0}function vf(r){let e=r.currentTarget;if(!e)return false;let[t,n]=bf(e);return !(Co(t)&&r.shiftKey||Co(n)&&!r.shiftKey||!t&&!n)}var A1=class yf{constructor(){il(this,"id",null),il(this,"fn_cleanup"),il(this,"cleanup",()=>{this.cancel();});}static create(){return new yf}request(e){this.cancel(),this.id=globalThis.requestAnimationFrame(()=>{this.id=null,this.fn_cleanup=e?.();});}cancel(){this.id!==null&&(globalThis.cancelAnimationFrame(this.id),this.id=null),this.fn_cleanup?.(),this.fn_cleanup=void 0;}isActive(){return this.id!==null}};function Me(r){let e=A1.create();return e.request(r),e.cleanup}function wf(r){let e=new Set;function t(n){let i=globalThis.requestAnimationFrame(n);e.add(()=>globalThis.cancelAnimationFrame(i));}return t(()=>t(r)),function(){e.forEach(i=>i());}}function xf(r,e,t){let n=Me(()=>{r.removeEventListener(e,i,true),t();}),i=()=>{n(),t();};return r.addEventListener(e,i,{once:true,capture:true}),n}function R1(r,e){if(!r)return;let{attributes:t,callback:n}=e,i=r.ownerDocument.defaultView||window,o=new i.MutationObserver(s=>{for(let a of s)a.type==="attributes"&&a.attributeName&&t.includes(a.attributeName)&&n(a);});return o.observe(r,{attributes:true,attributeFilter:t}),()=>o.disconnect()}function Sf(r,e){let n=Me,i=[];return i.push(n(()=>{let o=typeof r=="function"?r():r;i.push(R1(o,e));})),()=>{i.forEach(o=>o?.());}}function Cf(r){let e=()=>{let t=Se(r);r.dispatchEvent(new t.MouseEvent("click"));};lf()?xf(r,"keyup",e):queueMicrotask(e);}function dl(r){let e=ef(r);return qm(e)?Pe(e).body:ce(e)&&Xd(e)?e:dl(e)}var D1=/auto|scroll|overlay|hidden|clip/,O1=new Set(["inline","contents"]);function Xd(r){let e=Se(r),{overflow:t,overflowX:n,overflowY:i,display:o}=e.getComputedStyle(r);return D1.test(t+i+n)&&!O1.has(o)}function li(r,e){return Array.from(r?.querySelectorAll(e)??[])}var ul=r=>r.id;function N1(r,e,t=ul){return r.find(n=>t(n)===e)}function Tf(r,e,t=ul){let n=N1(r,e,t);return n?r.indexOf(n):-1}function F1(r){return r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth}function Ef(r,e){let{rootEl:t,...n}=e||{};!r||!t||!Xd(t)||!F1(t)||r.scrollIntoView(n);}var V1=r=>r.split("").map(e=>{let t=e.charCodeAt(0);return t>0&&t<128?e:t>=128&&t<=255?`/x${t.toString(16)}`.replace("/","\\"):""}).join("").trim(),_1=r=>V1(r.dataset?.valuetext??r.textContent??""),B1=(r,e)=>r.trim().toLowerCase().startsWith(e.toLowerCase());function Pf(r,e,t,n=ul){let i=t?Tf(r,t,n):-1,o=t?Xm(r,i):r;return e.length===1&&(o=o.filter(a=>n(a)!==t)),o.find(a=>B1(_1(a),e))}function To(r,e){if(!r)return wo;let t=Object.keys(e).reduce((n,i)=>(n[i]=r.style.getPropertyValue(i),n),{});return H1(t,e)?wo:(Object.assign(r.style,e),()=>{Object.assign(r.style,t),r.style.length===0&&r.removeAttribute("style");})}function Lf(r,e,t){if(!r)return wo;let n=r.style.getPropertyValue(e);return n===t?wo:(r.style.setProperty(e,t),()=>{r.style.setProperty(e,n),r.style.length===0&&r.removeAttribute("style");})}function H1(r,e){return Object.keys(r).every(t=>r[t]===e[t])}function z1(r,e){let{state:t,activeId:n,key:i,timeout:o=350,itemToId:s}=e,a=t.keysSoFar+i,c=a.length>1&&Array.from(a).every(m=>m===a[0])?a[0]:a,d=r.slice(),u=Pf(d,c,n,s);function h(){clearTimeout(t.timer),t.timer=-1;}function p(m){t.keysSoFar=m,h(),m!==""&&(t.timer=+setTimeout(()=>{p(""),h();},o));}return p(a),u}var hl=Object.assign(z1,{defaultOptions:{keysSoFar:"",timer:-1},isValidEvent:$1});function $1(r){return r.key.length===1&&!r.ctrlKey&&!r.metaKey}function W1(r,e,t){let{signal:n}=e;return [new Promise((s,a)=>{let l=setTimeout(()=>{a(new Error(`Timeout of ${t}ms exceeded`));},t);n.addEventListener("abort",()=>{clearTimeout(l),a(new DOMException("Promise aborted","AbortError"));}),r.then(c=>{n.aborted||(clearTimeout(l),s(c));}).catch(c=>{n.aborted||(clearTimeout(l),a(c));});}),()=>e.abort()]}function Mf(r,e){let{timeout:t,rootNode:n}=e,i=Se(n),o=Pe(n),s=new i.AbortController;return W1(new Promise(a=>{let l=r();if(l){a(l);return}let c=new i.MutationObserver(()=>{let d=r();d&&d.isConnected&&(c.disconnect(),a(d));});c.observe(o.body,{childList:true,subtree:true});}),s,t)}function kf(r){let e=()=>r.getRootNode?.()??document,t=()=>Pe(e());return {...r,getRootNode:e,getDoc:t,getWin:()=>t().defaultView??window,getActiveElement:()=>Yt(e()),isActiveElement:Co,getById:s=>e().getElementById(s)}}function If(r){return new Proxy({},{get(e,t){return t==="style"?n=>r({style:n}).style:r}})}var Af={onFocus:"onFocusin",onBlur:"onFocusout",onChange:"onInput",onDoubleClick:"onDblclick",htmlFor:"for",className:"class",defaultValue:"value",defaultChecked:"checked"},G1=new Set(["viewBox","preserveAspectRatio"]),U1=r=>{let e="";for(let t in r){let n=r[t];n!=null&&(t.startsWith("--")||(t=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)),e+=`${t}:${n};`);}return e},ci=If(r=>Object.entries(r).reduce((e,[t,n])=>{if(n===void 0)return e;if(t in Af&&(t=Af[t]),t==="style"&&typeof n=="object")return e.style=U1(n),e;let i=G1.has(t)?t:t.toLowerCase();return e[i]=n,e},{}));var pl=new WeakMap,Rf=new Set(["value","checked","selected"]),Y1=new Set(["viewBox","preserveAspectRatio","clipPath","clipRule","fillRule","strokeWidth","strokeLinecap","strokeLinejoin","strokeDasharray","strokeDashoffset","strokeMiterlimit"]),K1=r=>r.tagName==="svg"||r.namespaceURI==="http://www.w3.org/2000/svg",ml=(r,e)=>K1(r)&&Y1.has(e)?e:e.toLowerCase();function it(r,e,t){let n=t||"default",i=pl.get(r);i||(i=new Map,pl.set(r,i));let o=i.get(n)||{},s=Object.keys(e),a=(f,g)=>{r.addEventListener(f.toLowerCase(),g);},l=(f,g)=>{r.removeEventListener(f.toLowerCase(),g);},c=f=>f.startsWith("on"),d=f=>!f.startsWith("on"),u=f=>a(f.substring(2),e[f]),h=f=>l(f.substring(2),e[f]),p=f=>{let g=e[f],b=o[f];if(g!==b){if(f==="class"){r.className=g??"";return}if(Rf.has(f)){r[f]=g??"";return}if(typeof g=="boolean"&&!f.includes("aria-")){r.toggleAttribute(ml(r,f),g);return}if(f==="children"){r.innerHTML=g;return}if(g!=null){r.setAttribute(ml(r,f),g);return}r.removeAttribute(ml(r,f));}};for(let f in o)e[f]==null&&(f==="class"?r.className="":Rf.has(f)?r[f]="":r.removeAttribute(ml(r,f)));return Object.keys(o).filter(c).forEach(f=>{l(f.substring(2),o[f]);}),s.filter(c).forEach(u),s.filter(d).forEach(p),i.set(n,e),function(){s.filter(c).forEach(h);let g=pl.get(r);g&&(g.delete(n),g.size===0&&pl.delete(r));}}function X1(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function jd(r,e){let t=X1();return t?(t[r]||(t[r]=e()),t[r]):e()}var di=jd("__zag__refSet",()=>new WeakSet);var j1=r=>typeof r=="object"&&r!==null&&"$$typeof"in r&&"props"in r,q1=r=>typeof r=="object"&&r!==null&&"__v_isVNode"in r,Z1=r=>typeof r=="object"&&r!==null&&"nodeType"in r&&typeof r.nodeName=="string",J1=r=>j1(r)||q1(r)||Z1(r),fl=r=>r!==null&&typeof r=="object",qd=r=>fl(r)&&!di.has(r)&&(Array.isArray(r)||!(Symbol.iterator in r))&&!J1(r)&&!(r instanceof WeakMap)&&!(r instanceof WeakSet)&&!(r instanceof Error)&&!(r instanceof Number)&&!(r instanceof Date)&&!(r instanceof String)&&!(r instanceof RegExp)&&!(r instanceof ArrayBuffer)&&!(r instanceof Promise)&&!(r instanceof File)&&!(r instanceof Blob)&&!(r instanceof AbortController);var Q1=Symbol();var Df=Object.getPrototypeOf,Zd=new WeakMap,eT=r=>r&&(Zd.has(r)?Zd.get(r):Df(r)===Object.prototype||Df(r)===Array.prototype);var Of=r=>eT(r)&&r[Q1]||null,Jd=(r,e=true)=>{Zd.set(r,e);};var br=jd("__zag__proxyStateMap",()=>new WeakMap),tT=(r=Object.is,e=(a,l)=>new Proxy(a,l),t=new WeakMap,n=(a,l)=>{let c=t.get(a);if(c?.[0]===l)return c[1];let d=Array.isArray(a)?[]:Object.create(Object.getPrototypeOf(a));return Jd(d,true),t.set(a,[l,d]),Reflect.ownKeys(a).forEach(u=>{let h=Reflect.get(a,u);di.has(h)?(Jd(h,false),d[u]=h):br.has(h)?d[u]=Nf(h):d[u]=h;}),Object.freeze(d)},i=new WeakMap,o=[1,1],s=a=>{if(!fl(a))throw new Error("object required");let l=i.get(a);if(l)return l;let c=o[0],d=new Set,u=(E,x=++o[0])=>{c!==x&&(c=x,d.forEach(L=>L(E,x)));},h=o[1],p=(E=++o[1])=>(h!==E&&!d.size&&(h=E,f.forEach(([x])=>{let L=x[1](E);L>c&&(c=L);})),c),m=E=>(x,L)=>{let w=[...x];w[1]=[E,...w[1]],u(w,L);},f=new Map,g=(E,x)=>{if(d.size){let L=x[3](m(E));f.set(E,[x,L]);}else f.set(E,[x]);},b=E=>{let x=f.get(E);x&&(f.delete(E),x[1]?.());},y=E=>(d.add(E),d.size===1&&f.forEach(([L,w],M)=>{let k=L[3](m(M));f.set(M,[L,k]);}),()=>{d.delete(E),d.size===0&&f.forEach(([L,w],M)=>{w&&(w(),f.set(M,[L]));});}),v=Array.isArray(a)?[]:Object.create(Object.getPrototypeOf(a)),P=e(v,{deleteProperty(E,x){let L=Reflect.get(E,x);b(x);let w=Reflect.deleteProperty(E,x);return w&&u(["delete",[x],L]),w},set(E,x,L,w){let M=Reflect.has(E,x),k=Reflect.get(E,x,w);if(M&&(r(k,L)||i.has(L)&&r(k,i.get(L))))return true;b(x),fl(L)&&(L=Of(L)||L);let C=L;if(!Object.getOwnPropertyDescriptor(E,x)?.set){!br.has(L)&&qd(L)&&(C=gl(L));let A=!di.has(C)&&br.get(C);A&&g(x,A);}return Reflect.set(E,x,C,w),u(["set",[x],L,k]),true}});i.set(a,P);let T=[v,p,n,y];return br.set(P,T),Reflect.ownKeys(a).forEach(E=>{let x=Object.getOwnPropertyDescriptor(a,E);x.get||x.set?Object.defineProperty(v,E,x):P[E]=a[E];}),P})=>[s,br,di,r,e,qd,t,n,i,o],[nT]=tT();function gl(r={}){return nT(r)}function bl(r,e,t){let n=br.get(r);let i,o=[],s=n[3],a=false,c=s(d=>{if(o.push(d),t);i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(o.splice(0));}));});return a=true,()=>{a=false,c();}}function Nf(r){let e=br.get(r);let[t,n,i]=e;return i(t,n())}function Po(r){let e=r().value??r().defaultValue;r().debug&&console.log(`[bindable > ${r().debug}] initial`,e);let t=r().isEqual??Object.is,n=gl({value:e}),i=()=>r().value!==void 0;return {initial:e,ref:n,get(){return i()?r().value:n.value},set(o){let s=i()?r().value:n.value,a=nt(o)?o(s):o;r().debug&&console.log(`[bindable > ${r().debug}] setValue`,{next:a,prev:s}),i()||(n.value=a),t(a,s)||r().onChange?.(a,s);},invoke(o,s){r().onChange?.(o,s);},hash(o){return r().hash?.(o)??String(o)}}}Po.cleanup=r=>{};Po.ref=r=>{let e=r;return {get:()=>e,set:t=>{e=t;}}};function Ff(r){let e={current:r};return {get(t){return e.current[t]},set(t,n){e.current[t]=n;}}}function Qd(r,e){if(!fr(r)||!fr(e))return e===void 0?r:e;let t={...r};for(let n of Object.keys(e)){let i=e[n],o=r[n];i!==void 0&&(fr(o)&&fr(i)?t[n]=Qd(o,i):t[n]=i);}return t}var eu=class{constructor(r,e={}){le(this,"machine",r),le(this,"scope"),le(this,"context"),le(this,"prop"),le(this,"state"),le(this,"refs"),le(this,"computed"),le(this,"event",{type:""}),le(this,"previousEvent",{type:""}),le(this,"effects",new Map),le(this,"transition",null),le(this,"cleanups",[]),le(this,"subscriptions",[]),le(this,"userPropsRef"),le(this,"getEvent",()=>({...this.event,current:()=>this.event,previous:()=>this.previousEvent})),le(this,"getState",()=>({...this.state,matches:(...u)=>u.some(h=>Um(this.state.get(),h)),hasTag:u=>Ym(this.machine,this.state.get(),u)})),le(this,"debug",(...u)=>{this.machine.debug&&console.log(...u);}),le(this,"notify",()=>{this.publish();}),le(this,"send",u=>{this.status===ti.Started&&queueMicrotask(()=>{if(!u)return;this.previousEvent=this.event,this.event=u,this.debug("send",u);let h=this.state.get(),p=u.type,{transitions:m,source:f}=Wm(this.machine,h,p),g=this.choose(m);if(!g)return;this.transition=g;let b=Nd(this.machine,g.target??h,f);this.debug("transition",g),b!==h?this.state.set(b):g.reenter?this.state.invoke(h,h):this.action(g.actions);});}),le(this,"action",u=>{let h=nt(u)?u(this.getParams()):u;if(!h)return;let p=h.map(m=>{let f=this.machine.implementations?.actions?.[m];return f||Qr(`[zag-js] No implementation found for action "${JSON.stringify(m)}"`),f});for(let m of p)m?.(this.getParams());}),le(this,"guard",u=>{if(nt(u))return u(this.getParams());let h=this.machine.implementations?.guards?.[u];return h||Qr(`[zag-js] No implementation found for guard "${JSON.stringify(u)}"`),h?.(this.getParams())}),le(this,"effect",u=>{let h=nt(u)?u(this.getParams()):u;if(!h)return;let p=h.map(f=>{let g=this.machine.implementations?.effects?.[f];return g||Qr(`[zag-js] No implementation found for effect "${JSON.stringify(f)}"`),g}),m=[];for(let f of p){let g=f?.(this.getParams());g&&m.push(g);}return ()=>m.forEach(f=>f?.())}),le(this,"choose",u=>Pm(u).find(h=>{let p=!h.guard;return Jr(h.guard)?p=!!this.guard(h.guard):nt(h.guard)&&(p=h.guard(this.getParams())),p})),le(this,"subscribe",u=>(this.subscriptions.push(u),()=>{let h=this.subscriptions.indexOf(u);h>-1&&this.subscriptions.splice(h,1);})),le(this,"status",ti.NotStarted),le(this,"publish",()=>{this.callTrackers(),this.subscriptions.forEach(u=>u(this.service));}),le(this,"trackers",[]),le(this,"setupTrackers",()=>{this.machine.watch?.(this.getParams());}),le(this,"callTrackers",()=>{this.trackers.forEach(({deps:u,fn:h})=>{let p=u.map(m=>m());Zr(h.prev,p)||(h(),h.prev=p);});}),le(this,"getParams",()=>({state:this.getState(),context:this.context,event:this.getEvent(),prop:this.prop,send:this.send,action:this.action,guard:this.guard,track:(u,h)=>{h.prev=u.map(p=>p()),this.trackers.push({deps:u,fn:h});},refs:this.refs,computed:this.computed,flush:Nm,scope:this.scope,choose:this.choose})),this.userPropsRef={current:e};let{id:t,ids:n,getRootNode:i}=go(e);this.scope=kf({id:t,ids:n,getRootNode:i});let o=u=>{let h=go(this.userPropsRef.current);return (r.props?.({props:On(h),scope:this.scope})??h)[u]};this.prop=o;let s=r.context?.({prop:o,bindable:Po,scope:this.scope,flush(u){queueMicrotask(u);},getContext(){return a},getComputed(){return l},getRefs(){return c},getEvent:this.getEvent.bind(this)});s&&Object.values(s).forEach(u=>{let h=bl(u.ref,()=>this.notify());this.cleanups.push(h);});let a={get(u){return s?.[u].get()},set(u,h){s?.[u].set(h);},initial(u){return s?.[u].initial},hash(u){let h=s?.[u].get();return s?.[u].hash(h)}};this.context=a;let l=u=>(bo(r.computed,()=>"[zag-js] No computed object found on machine"),r.computed[u]({context:a,event:this.getEvent(),prop:o,refs:this.refs,scope:this.scope,computed:l}));this.computed=l;let c=Ff(r.refs?.({prop:o,context:a})??{});this.refs=c;let d=Po(()=>({defaultValue:Nd(r,r.initialState({prop:o})),onChange:(u,h)=>{let{exiting:p,entering:m}=Gm(this.machine,h,u,this.transition?.reenter);if(p.forEach(f=>{this.effects.get(f.path)?.(),this.effects.delete(f.path);}),p.forEach(f=>{this.action(f.state?.exit);}),this.action(this.transition?.actions),m.forEach(f=>{let g=this.effect(f.state?.effects);if(g){let b=this.effects.get(f.path);this.effects.set(f.path,b?Dn(b,g):g);}}),h===yo){this.action(r.entry);let f=this.effect(r.effects);if(f){let g=this.effects.get(yo);this.effects.set(yo,g?Dn(g,f):f);}}m.forEach(f=>{this.action(f.state?.entry);});}}));this.state=d,this.cleanups.push(bl(this.state.ref,()=>this.notify()));}updateProps(r){let e=this.userPropsRef.current;this.userPropsRef.current=()=>{let t=go(e),n=go(r);return Qd(t,n)},this.notify();}start(){this.status=ti.Started,this.debug("initializing..."),this.state.invoke(this.state.initial,yo),this.setupTrackers();}stop(){this.effects.forEach(r=>r?.()),this.effects.clear(),this.transition=null,this.action(this.machine.exit),this.cleanups.forEach(r=>r()),this.cleanups=[],this.subscriptions=[],this.status=ti.Stopped,this.debug("unmounting...");}get service(){return {state:this.getState(),send:this.send,context:this.context,prop:this.prop,scope:this.scope,refs:this.refs,computed:this.computed,event:this.getEvent(),getStatus:()=>this.status}}};function vl(r,e,t){let n=new eu(r,e),i=n.subscribe(t);return n.start(),t(n.service),{service:n.service,flush:()=>t(n.service),stop:()=>{i(),n.stop();}}}var rT=0;function yl(r){return `${r}-${++rT}`}function vr(r,e=8){return `${r}::-webkit-scrollbar{width:${e}px;height:${e}px;}${r}::-webkit-scrollbar-thumb{background:var(--vela-scroll);border-radius:4px;border:2px solid transparent;background-clip:padding-box;}${r}::-webkit-scrollbar-track{background:transparent;}${r}::-webkit-scrollbar-button{display:none;width:0;height:0;}`}var Vf="outline:none;transition:border-color .12s ease,box-shadow .12s ease;",_f="border-color:var(--vela-focus);box-shadow:0 0 0 3px var(--vela-focus-soft);";function ge(r,e,t=document){if(typeof document>"u")return;let n=t instanceof Document?t.head:t;if(t.getElementById?.(r)??n.querySelector(`#${CSS.escape(r)}`))return;let i=document.createElement("style");i.id=r,i.textContent=e,n.appendChild(i);}function je(r,e=document){let t=e.createElement("span");t.className="vela-icon",t.setAttribute("aria-hidden","true");let n=Fs(r);return n&&(t.innerHTML=n),t}var hn=(r,e=[])=>({parts:(...t)=>{if(iT(e))return hn(r,t);throw new Error("createAnatomy().parts(...) should only be called once. Did you mean to use .extendWith(...) ?")},extendWith:(...t)=>hn(r,[...e,...t]),omit:(...t)=>hn(r,e.filter(n=>!t.includes(n))),rename:t=>hn(t,e),keys:()=>e,build:()=>[...new Set(e)].reduce((t,n)=>Object.assign(t,{[n]:{selector:[`&[data-scope="${ui(r)}"][data-part="${ui(n)}"]`,`& [data-scope="${ui(r)}"][data-part="${ui(n)}"]`].join(", "),attrs:{"data-scope":ui(r),"data-part":ui(n)}}}),{})}),ui=r=>r.replace(/([A-Z])([A-Z])/g,"$1-$2").replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase(),iT=r=>r.length===0;var oT=hn("menu").parts("arrow","arrowTip","content","contextTrigger","indicator","item","itemGroup","itemGroupLabel","itemIndicator","itemText","positioner","separator","trigger","triggerItem"),ze=oT.build();var zf=["top","right","bottom","left"];var Kt=Math.min,Mt=Math.max,Mo=Math.round,ko=Math.floor,Xt=r=>({x:r,y:r}),sT={left:"right",right:"left",bottom:"top",top:"bottom"};function tu(r,e,t){return Mt(r,Kt(e,t))}function jt(r,e){return typeof r=="function"?r(e):r}function pn(r){return r.split("-")[0]}function yr(r){return r.split("-")[1]}function xl(r){return r==="x"?"y":"x"}function Sl(r){return r==="y"?"height":"width"}function kt(r){let e=r[0];return e==="t"||e==="b"?"y":"x"}function Cl(r){return xl(kt(r))}function $f(r,e,t){t===void 0&&(t=false);let n=yr(r),i=Cl(r),o=Sl(i),s=i==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(s=Lo(s)),[s,Lo(s)]}function Wf(r){let e=Lo(r);return [wl(r),e,wl(e)]}function wl(r){return r.includes("start")?r.replace("start","end"):r.replace("end","start")}var Bf=["left","right"],Hf=["right","left"],aT=["top","bottom"],lT=["bottom","top"];function cT(r,e,t){switch(r){case "top":case "bottom":return t?e?Hf:Bf:e?Bf:Hf;case "left":case "right":return e?aT:lT;default:return []}}function Gf(r,e,t,n){let i=yr(r),o=cT(pn(r),t==="start",n);return i&&(o=o.map(s=>s+"-"+i),e&&(o=o.concat(o.map(wl)))),o}function Lo(r){let e=pn(r);return sT[e]+r.slice(e.length)}function dT(r){var e,t,n,i;return {top:(e=r.top)!=null?e:0,right:(t=r.right)!=null?t:0,bottom:(n=r.bottom)!=null?n:0,left:(i=r.left)!=null?i:0}}function nu(r){return typeof r!="number"?dT(r):{top:r,right:r,bottom:r,left:r}}function wr(r){let{x:e,y:t,width:n,height:i}=r;return {width:n,height:i,top:t,left:e,right:e+n,bottom:t+i,x:e,y:t}}function Uf(r,e,t){let{reference:n,floating:i}=r,o=kt(e),s=Cl(e),a=Sl(s),l=pn(e),c=o==="y",d=n.x+n.width/2-i.width/2,u=n.y+n.height/2-i.height/2,h=n[a]/2-i[a]/2,p;switch(l){case "top":p={x:d,y:n.y-i.height};break;case "bottom":p={x:d,y:n.y+n.height};break;case "right":p={x:n.x+n.width,y:u};break;case "left":p={x:n.x-i.width,y:u};break;default:p={x:n.x,y:n.y};}let m=yr(e);return m&&(p[s]+=h*(m==="end"?1:-1)*(t&&c?-1:1)),p}async function Xf(r,e){var t;e===void 0&&(e={});let{x:n,y:i,platform:o,rects:s,elements:a,strategy:l}=r,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=false,padding:p=0}=jt(e,r),m=nu(p),g=a[h?u==="floating"?"reference":"floating":u],b=wr(await o.getClippingRect({element:(t=await(o.isElement==null?void 0:o.isElement(g)))==null||t?g:g.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),y=u==="floating"?{x:n,y:i,width:s.floating.width,height:s.floating.height}:s.reference,v=await(o.getOffsetParent==null?void 0:o.getOffsetParent(a.floating)),S=await(o.isElement==null?void 0:o.isElement(v))&&await(o.getScale==null?void 0:o.getScale(v))||{x:1,y:1},P=wr(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:y,offsetParent:v,strategy:l}):y);return {top:(b.top-P.top+m.top)/S.y,bottom:(P.bottom-b.bottom+m.bottom)/S.y,left:(b.left-P.left+m.left)/S.x,right:(P.right-b.right+m.right)/S.x}}var uT=50,jf=async(r,e,t)=>{let{placement:n="bottom",strategy:i="absolute",middleware:o=[],platform:s}=t,a=s.detectOverflow?s:{...s,detectOverflow:Xf},l=await(s.isRTL==null?void 0:s.isRTL(e)),c=await s.getElementRects({reference:r,floating:e,strategy:i}),{x:d,y:u}=Uf(c,n,l),h=n,p=0,m={};for(let f=0;f<o.length;f++){let g=o[f];if(!g)continue;let{name:b,fn:y}=g,{x:v,y:S,data:P,reset:T}=await y({x:d,y:u,initialPlacement:n,placement:h,strategy:i,middlewareData:m,rects:c,platform:a,elements:{reference:r,floating:e}});d=v??d,u=S??u,m[b]={...m[b],...P},T&&p<uT&&(p++,typeof T=="object"&&(T.placement&&(h=T.placement),T.rects&&(c=T.rects===true?await s.getElementRects({reference:r,floating:e,strategy:i}):T.rects),{x:d,y:u}=Uf(c,h,l)),f=-1);}return {x:d,y:u,placement:h,strategy:i,middlewareData:m}},qf=r=>({name:"arrow",options:r,async fn(e){let{x:t,y:n,placement:i,rects:o,platform:s,elements:a,middlewareData:l}=e,{element:c,padding:d=0}=jt(r,e)||{};if(c==null)return {};let u=nu(d),h={x:t,y:n},p=Cl(i),m=Sl(p),f=await s.getDimensions(c),g=p==="y",b=g?"top":"left",y=g?"bottom":"right",v=g?"clientHeight":"clientWidth",S=o.reference[m]+o.reference[p]-h[p]-o.floating[m],P=h[p]-o.reference[p],T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(c)),E=T?T[v]:0;(!E||!await(s.isElement==null?void 0:s.isElement(T)))&&(E=a.floating[v]||o.floating[m]);let x=S/2-P/2,L=E/2-f[m]/2-1,w=Kt(u[b],L),M=Kt(u[y],L),k=E-f[m]-M,C=E/2-f[m]/2+x,A=tu(w,C,k),$=!l.arrow&&yr(i)!=null&&C!==A&&o.reference[m]/2-(C<w?w:M)-f[m]/2<0,ie=$?C<w?C-w:C-k:0;return {[p]:h[p]+ie,data:{[p]:A,centerOffset:C-A-ie,...$&&{alignmentOffset:ie}},reset:$}}});var Zf=function(r){return r===void 0&&(r={}),{name:"flip",options:r,async fn(e){var t,n;let{placement:i,middlewareData:o,rects:s,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:d=true,crossAxis:u=true,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:f=true,...g}=jt(r,e);if((t=o.arrow)!=null&&t.alignmentOffset)return {};let b=pn(i),y=kt(a),v=pn(a)===a,S=await(l.isRTL==null?void 0:l.isRTL(c.floating)),P=h||(v||!f?[Lo(a)]:Wf(a)),T=m!=="none";!h&&T&&P.push(...Gf(a,f,m,S));let E=[a,...P],x=await l.detectOverflow(e,g),L=[],w=((n=o.flip)==null?void 0:n.overflows)||[];if(d&&L.push(x[b]),u){let A=$f(i,s,S);L.push(x[A[0]],x[A[1]]);}if(w=[...w,{placement:i,overflows:L}],!L.every(A=>A<=0)){var M,k;let A=(((M=o.flip)==null?void 0:M.index)||0)+1,$=E[A];if($&&(!(u==="alignment"?y!==kt($):false)||w.every(j=>kt(j.placement)===y?j.overflows[0]>0:true)))return {data:{index:A,overflows:w},reset:{placement:$}};let ie=(k=w.filter(oe=>oe.overflows[0]<=0).sort((oe,j)=>oe.overflows[1]-j.overflows[1])[0])==null?void 0:k.placement;if(!ie)switch(p){case "bestFit":{var C;let oe=(C=w.filter(j=>{if(T){let dt=kt(j.placement);return dt===y||dt==="y"}return true}).map(j=>[j.placement,j.overflows.filter(dt=>dt>0).reduce((dt,Gx)=>dt+Gx,0)]).sort((j,dt)=>j[1]-dt[1])[0])==null?void 0:C[0];oe&&(ie=oe);break}case "initialPlacement":ie=a;break}if(i!==ie)return {reset:{placement:ie}}}return {}}}};function Yf(r,e){return {top:r.top-e.height,right:r.right-e.width,bottom:r.bottom-e.height,left:r.left-e.width}}function Kf(r){return zf.some(e=>r[e]>=0)}var Jf=function(r){return r===void 0&&(r={}),{name:"hide",options:r,async fn(e){let{rects:t,platform:n}=e,{strategy:i="referenceHidden",...o}=jt(r,e);switch(i){case "referenceHidden":{let s=await n.detectOverflow(e,{...o,elementContext:"reference"}),a=Yf(s,t.reference);return {data:{referenceHiddenOffsets:a,referenceHidden:Kf(a)}}}case "escaped":{let s=await n.detectOverflow(e,{...o,altBoundary:true}),a=Yf(s,t.floating);return {data:{escapedOffsets:a,escaped:Kf(a)}}}default:return {}}}}};var Qf=new Set(["left","top"]);async function hT(r,e){let{placement:t,platform:n,elements:i}=r,o=await(n.isRTL==null?void 0:n.isRTL(i.floating)),s=pn(t),a=yr(t),l=kt(t)==="y",c=Qf.has(s)?-1:1,d=o&&l?-1:1,u=jt(e,r),{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}var eg=function(r){return r===void 0&&(r=0),{name:"offset",options:r,async fn(e){var t,n;let{x:i,y:o,placement:s,middlewareData:a}=e,l=await hT(e,r);return s===((t=a.offset)==null?void 0:t.placement)&&(n=a.arrow)!=null&&n.alignmentOffset?{}:{x:i+l.x,y:o+l.y,data:{...l,placement:s}}}}},tg=function(r){return r===void 0&&(r={}),{name:"shift",options:r,async fn(e){let{x:t,y:n,placement:i,platform:o}=e,{mainAxis:s=true,crossAxis:a=false,limiter:l={fn:y=>{let{x:v,y:S}=y;return {x:v,y:S}}},...c}=jt(r,e),d={x:t,y:n},u=await o.detectOverflow(e,c),h=kt(i),p=xl(h),m=d[p],f=d[h],g=(y,v)=>tu(v+u[y==="y"?"top":"left"],v,v-u[y==="y"?"bottom":"right"]);s&&(m=g(p,m)),a&&(f=g(h,f));let b=l.fn({...e,[p]:m,[h]:f});return {...b,data:{x:b.x-t,y:b.y-n,enabled:{[p]:s,[h]:a}}}}}},ng=function(r){return r===void 0&&(r={}),{options:r,fn(e){var t,n;let{x:i,y:o,placement:s,rects:a,middlewareData:l}=e,{offset:c=0,mainAxis:d=true,crossAxis:u=true}=jt(r,e),h={x:i,y:o},p=kt(s),m=xl(p),f=h[m],g=h[p],b=jt(c,e),y=typeof b=="number"?{mainAxis:b,crossAxis:0}:{mainAxis:(t=b.mainAxis)!=null?t:0,crossAxis:(n=b.crossAxis)!=null?n:0};if(d){let P=m==="y"?"height":"width",T=a.reference[m]-a.floating[P]+y.mainAxis,E=a.reference[m]+a.reference[P]-y.mainAxis;f<T?f=T:f>E&&(f=E);}if(u){var v,S;let P=m==="y"?"width":"height",T=Qf.has(pn(s)),E=a.reference[p]-a.floating[P]+(T&&((v=l.offset)==null?void 0:v[p])||0)+(T?0:y.crossAxis),x=a.reference[p]+a.reference[P]+(T?0:((S=l.offset)==null?void 0:S[p])||0)-(T?y.crossAxis:0);g<E?g=E:g>x&&(g=x);}return {[m]:f,[p]:g}}}},rg=function(r){return r===void 0&&(r={}),{name:"size",options:r,async fn(e){let{placement:t,rects:n,platform:i,elements:o}=e,{apply:s=()=>{},...a}=jt(r,e),l=await i.detectOverflow(e,a),c=pn(t),d=yr(t),u=kt(t)==="y",{width:h,height:p}=n.floating,m,f;c==="top"||c==="bottom"?(m=c,f=d===(await(i.isRTL==null?void 0:i.isRTL(o.floating))?"start":"end")?"left":"right"):(f=c,m=d==="end"?"top":"bottom");let g=p-l.top-l.bottom,b=h-l.left-l.right,y=Kt(p-l[m],g),v=Kt(h-l[f],b),S=e.middlewareData.shift,P=!S,T=y,E=v;S!=null&&S.enabled.x&&(E=b),S!=null&&S.enabled.y&&(T=g),P&&!d&&(u?E=h-2*Mt(l.left,l.right):T=p-2*Mt(l.top,l.bottom)),await s({...e,availableWidth:E,availableHeight:T});let x=await i.getDimensions(o.floating);return h!==x.width||p!==x.height?{reset:{rects:true}}:{}}}};function Tl(){return typeof window<"u"}function Sr(r){return og(r)?(r.nodeName||"").toLowerCase():"#document"}function qe(r){var e;return (r==null||(e=r.ownerDocument)==null?void 0:e.defaultView)||window}function qt(r){var e;return (e=(og(r)?r.ownerDocument:r.document)||window.document)==null?void 0:e.documentElement}function og(r){return Tl()?r instanceof Node||r instanceof qe(r).Node:false}function It(r){return Tl()?r instanceof Element||r instanceof qe(r).Element:false}function mn(r){return Tl()?r instanceof HTMLElement||r instanceof qe(r).HTMLElement:false}function ig(r){return !Tl()||typeof ShadowRoot>"u"?false:r instanceof ShadowRoot||r instanceof qe(r).ShadowRoot}function Io(r){let{overflow:e,overflowX:t,overflowY:n,display:i}=At(r);return /auto|scroll|overlay|hidden|clip/.test(e+n+t)&&i!=="inline"&&i!=="contents"}function sg(r){return /^(table|td|th)$/.test(Sr(r))}function Ao(r){try{if(r.matches(":popover-open"))return !0}catch{}try{return r.matches(":modal")}catch{return false}}var pT=/transform|translate|scale|rotate|perspective|filter/,mT=/paint|layout|strict|content/,xr=r=>!!r&&r!=="none",ru;function El(r){let e=It(r)?At(r):r;return xr(e.transform)||xr(e.translate)||xr(e.scale)||xr(e.rotate)||xr(e.perspective)||!Pl()&&(xr(e.backdropFilter)||xr(e.filter))||pT.test(e.willChange||"")||mT.test(e.contain||"")}function ag(r){let e=Vn(r);for(;mn(e)&&!pi(e);){if(El(e))return e;if(Ao(e))return null;e=Vn(e);}return null}function Pl(){return ru==null&&(ru=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),ru}function pi(r){return /^(html|body|#document)$/.test(Sr(r))}function At(r){return qe(r).getComputedStyle(r)}function Ro(r){return It(r)?{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}:{scrollLeft:r.scrollX,scrollTop:r.scrollY}}function Vn(r){if(Sr(r)==="html")return r;let e=r.assignedSlot||r.parentNode||ig(r)&&r.host||qt(r);return ig(e)?e.host:e}function lg(r){let e=Vn(r);return pi(e)?(r.ownerDocument||r).body:mn(e)&&Io(e)?e:lg(e)}function hi(r,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=true);let i=lg(r),o=i===((n=r.ownerDocument)==null?void 0:n.body),s=qe(i);if(o){let a=Ll(s);return e.concat(s,s.visualViewport||[],Io(i)?i:[],a&&t?hi(a):[])}else return e.concat(i,hi(i,[],t))}function Ll(r){return r.parent&&Object.getPrototypeOf(r.parent)?r.frameElement:null}function ug(r){let e=At(r),t=parseFloat(e.width)||0,n=parseFloat(e.height)||0,i=mn(r),o=i?r.offsetWidth:t,s=i?r.offsetHeight:n,a=Mo(t)!==o||Mo(n)!==s;return a&&(t=o,n=s),{width:t,height:n,$:a}}function ou(r){return It(r)?r:r.contextElement}function mi(r){let e=ou(r);if(!mn(e))return Xt(1);let t=e.getBoundingClientRect(),{width:n,height:i,$:o}=ug(e),s=(o?Mo(t.width):t.width)/n,a=(o?Mo(t.height):t.height)/i;return (!s||!Number.isFinite(s))&&(s=1),(!a||!Number.isFinite(a))&&(a=1),{x:s,y:a}}var fT=Xt(0);function hg(r){let e=qe(r);return !Pl()||!e.visualViewport?fT:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function gT(r,e,t){return e===void 0&&(e=false),!!t&&e&&t===qe(r)}function Cr(r,e,t,n){e===void 0&&(e=false),t===void 0&&(t=false);let i=r.getBoundingClientRect(),o=ou(r),s=Xt(1);e&&(n?It(n)&&(s=mi(n)):s=mi(r));let a=gT(o,t,n)?hg(o):Xt(0),l=(i.left+a.x)/s.x,c=(i.top+a.y)/s.y,d=i.width/s.x,u=i.height/s.y;if(o&&n){let h=qe(o),p=It(n)?qe(n):n,m=h,f=Ll(m);for(;f&&p!==m;){let g=mi(f),b=f.getBoundingClientRect(),y=At(f),v=b.left+(f.clientLeft+parseFloat(y.paddingLeft))*g.x,S=b.top+(f.clientTop+parseFloat(y.paddingTop))*g.y;l*=g.x,c*=g.y,d*=g.x,u*=g.y,l+=v,c+=S,m=qe(f),f=Ll(m);}}return wr({width:d,height:u,x:l,y:c})}function Ml(r,e){let t=Ro(r).scrollLeft;return e?e.left+t:Cr(qt(r)).left+t}function pg(r,e){let t=r.getBoundingClientRect(),n=t.left+e.scrollLeft-Ml(r,t),i=t.top+e.scrollTop;return {x:n,y:i}}function bT(r){let{elements:e,rect:t,offsetParent:n,strategy:i}=r,o=i==="fixed",s=qt(n),a=e?Ao(e.floating):false;if(n===s||a&&o)return t;let l={scrollLeft:0,scrollTop:0},c=Xt(1),d=Xt(0),u=mn(n);if((u||!o)&&((Sr(n)!=="body"||Io(s))&&(l=Ro(n)),u)){let p=Cr(n);c=mi(n),d.x=p.x+n.clientLeft,d.y=p.y+n.clientTop;}let h=s&&!u&&!o?pg(s,l):Xt(0);return {width:t.width*c.x,height:t.height*c.y,x:t.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:t.y*c.y-l.scrollTop*c.y+d.y+h.y}}function vT(r){return r.getClientRects?Array.from(r.getClientRects()):[]}function yT(r){let e=Ro(r),t=r.ownerDocument.body,n=Mt(r.scrollWidth,r.clientWidth,t.scrollWidth,t.clientWidth),i=Mt(r.scrollHeight,r.clientHeight,t.scrollHeight,t.clientHeight),o=-e.scrollLeft+Ml(r),s=-e.scrollTop;return At(t).direction==="rtl"&&(o+=Mt(r.clientWidth,t.clientWidth)-n),{width:n,height:i,x:o,y:s}}var wT=25;function xT(r,e,t){t===void 0&&(t="viewport");let n=t==="layoutViewport",i=qe(r),o=qt(r),s=i.visualViewport,a=o.clientWidth,l=o.clientHeight,c=0,d=0;if(s){let h=!Pl()||e==="fixed";n?h||(c=-s.offsetLeft,d=-s.offsetTop):(a=s.width,l=s.height,h&&(c=s.offsetLeft,d=s.offsetTop));}if(Ml(o)<=0){let h=o.ownerDocument,p=h.body,m=getComputedStyle(p),f=h.compatMode==="CSS1Compat"&&parseFloat(m.marginLeft)+parseFloat(m.marginRight)||0,g=Math.abs(o.clientWidth-p.clientWidth-f),b=getComputedStyle(o).scrollbarGutter==="stable both-edges"?g/2:g;b<=wT&&(a-=b);}return {width:a,height:l,x:c,y:d}}function ST(r,e){let t=Cr(r,true,e==="fixed"),n=t.top+r.clientTop,i=t.left+r.clientLeft,o=mi(r),s=r.clientWidth*o.x,a=r.clientHeight*o.y,l=i*o.x,c=n*o.y;return {width:s,height:a,x:l,y:c}}function cg(r,e,t){let n;if(e==="viewport"||e==="layoutViewport")n=xT(r,t,e);else if(e==="document")n=yT(qt(r));else if(It(e))n=ST(e,t);else {let i=hg(r);n={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height};}return wr(n)}function CT(r,e){let t=e.get(r);if(t)return t;let n=hi(r,[],false).filter(a=>It(a)&&Sr(a)!=="body"),i=null,o=At(r).position==="fixed",s=o?Vn(r):r;for(;It(s)&&!pi(s);){let a=At(s),l=El(s),c=i?i.position:o?"fixed":"";!l&&(c==="fixed"||c==="absolute"&&a.position==="static")?n=n.filter(u=>u!==s):i=a,s=Vn(s);}return e.set(r,n),n}function TT(r){let{element:e,boundary:t,rootBoundary:n,strategy:i}=r,s=[...t==="clippingAncestors"?Ao(e)?[]:CT(e,this._c):[].concat(t),n],a=cg(e,s[0],i),l=a.top,c=a.right,d=a.bottom,u=a.left;for(let h=1;h<s.length;h++){let p=cg(e,s[h],i);l=Mt(p.top,l),c=Kt(p.right,c),d=Kt(p.bottom,d),u=Mt(p.left,u);}return {width:c-u,height:d-l,x:u,y:l}}function ET(r){let{width:e,height:t}=ug(r);return {width:e,height:t}}function PT(r,e,t){let n=mn(e),i=qt(e),o=t==="fixed",s=Cr(r,true,o,e),a={scrollLeft:0,scrollTop:0},l=Xt(0);if((n||!o)&&((Sr(e)!=="body"||Io(i))&&(a=Ro(e)),n)){let h=Cr(e,true,o,e);l.x=h.x+e.clientLeft,l.y=h.y+e.clientTop;}!n&&i&&(l.x=Ml(i));let c=i&&!n&&!o?pg(i,a):Xt(0),d=s.left+a.scrollLeft-l.x-c.x,u=s.top+a.scrollTop-l.y-c.y;return {x:d,y:u,width:s.width,height:s.height}}function iu(r){return At(r).position==="static"}function dg(r,e){if(!mn(r)||At(r).position==="fixed")return null;if(e)return e(r);let t=r.offsetParent;return qt(r)===t&&(t=t.ownerDocument.body),t}function mg(r,e){let t=qe(r);if(Ao(r))return t;if(!mn(r)){let i=Vn(r);for(;i&&!pi(i);){if(It(i)&&!iu(i))return i;i=Vn(i);}return t}let n=dg(r,e);for(;n&&sg(n)&&iu(n);)n=dg(n,e);return n&&pi(n)&&iu(n)&&!El(n)?t:n||ag(r)||t}var LT=async function(r){let e=this.getOffsetParent||mg,t=this.getDimensions,n=await t(r.floating);return {reference:PT(r.reference,await e(r.floating),r.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function MT(r){return At(r).direction==="rtl"}var kT={convertOffsetParentRelativeRectToViewportRelativeRect:bT,getDocumentElement:qt,getClippingRect:TT,getOffsetParent:mg,getElementRects:LT,getClientRects:vT,getDimensions:ET,getScale:mi,isElement:It,isRTL:MT};function fg(r,e){return r.x===e.x&&r.y===e.y&&r.width===e.width&&r.height===e.height}function IT(r,e,t){let n=null,i,o=qt(r);function s(){var d;clearTimeout(i),(d=n)==null||d.disconnect(),n=null;}function a(d,u){d===void 0&&(d=false),u===void 0&&(u=1),s();let h=r.getBoundingClientRect(),{left:p,top:m,width:f,height:g}=h;if(d||e(),!f||!g)return;let b=ko(m),y=ko(o.clientWidth-(p+f)),v=ko(o.clientHeight-(m+g)),S=ko(p),T={rootMargin:-b+"px "+-y+"px "+-v+"px "+-S+"px",threshold:Mt(0,Kt(1,u))||1},E=true;function x(L){let w=L[0].intersectionRatio;if(!fg(h,r.getBoundingClientRect()))return a();if(w!==u){if(!E)return a();w?a(false,w):i=setTimeout(()=>{a(false,1e-7);},1e3);}E=false;}try{n=new IntersectionObserver(x,{...T,root:o.ownerDocument});}catch{n=new IntersectionObserver(x,T);}n.observe(r);}let l=qe(r),c=()=>a(t);return l.addEventListener("resize",c),a(true),()=>{l.removeEventListener("resize",c),s();}}function gg(r,e,t,n){n===void 0&&(n={});let{ancestorScroll:i=true,ancestorResize:o=true,elementResize:s=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=false}=n,c=ou(r),d=i||o?[...c?hi(c):[],...e?hi(e):[]]:[];d.forEach(b=>{i&&b.addEventListener("scroll",t),o&&b.addEventListener("resize",t);});let u=c&&a?IT(c,t,o):null,h=-1,p=null;s&&(p=new ResizeObserver(b=>{let[y]=b;y&&y.target===c&&p&&e&&(p.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var v;(v=p)==null||v.observe(e);})),t();}),c&&!l&&p.observe(c),e&&p.observe(e));let m,f=l?Cr(r):null;l&&g();function g(){let b=Cr(r);f&&!fg(f,b)&&t(),f=b,m=requestAnimationFrame(g);}return t(),()=>{var b;d.forEach(y=>{i&&y.removeEventListener("scroll",t),o&&y.removeEventListener("resize",t);}),u?.(),(b=p)==null||b.disconnect(),p=null,l&&cancelAnimationFrame(m);}}var bg=eg;var vg=tg,yg=Zf,wg=rg,xg=Jf,Sg=qf;var Cg=ng,Tg=(r,e,t)=>{let n=new Map,i=t??{},o={...kT,...i.platform,_c:n};return jf(r,e,{...i,platform:o})};function Eg(r=0,e=0,t=0,n=0){if(typeof DOMRect=="function")return new DOMRect(r,e,t,n);let i={x:r,y:e,width:t,height:n,top:e,right:r+t,bottom:e+n,left:r};return {...i,toJSON:()=>i}}function AT(r){if(!r)return Eg();let{x:e,y:t,width:n,height:i}=r;return Eg(e,t,n,i)}function Pg(r,e){return {contextElement:ce(r)?r:r?.contextElement,getBoundingClientRect:()=>{let t=r,n=e?.(t);return n||!t?AT(n):t.getBoundingClientRect()}}}var Do=r=>({variable:r,reference:`var(${r})`}),Zt={arrowSize:Do("--arrow-size"),arrowSizeHalf:Do("--arrow-size-half"),arrowBg:Do("--arrow-background"),transformOrigin:Do("--transform-origin"),arrowOffset:Do("--arrow-offset")},RT=r=>r==="top"||r==="bottom"?"y":"x";function Lg(r,e){return {name:"transformOrigin",fn(t){let{elements:n,middlewareData:i,placement:o,rects:s,y:a}=t,l=o.split("-")[0],c=RT(l),d=i.arrow?.x||0,u=i.arrow?.y||0,h=e?.clientWidth||0,p=e?.clientHeight||0,m=d+h/2,f=u+p/2,g=Math.abs(i.shift?.y||0),b=s.reference.height/2,y=p/2,v=r.offset?.mainAxis??r.gutter,S=typeof v=="number"?v+y:v??y,P=g>S,T={top:`${m}px calc(100% + ${S}px)`,bottom:`${m}px ${-S}px`,left:`calc(100% + ${S}px) ${f}px`,right:`${-S}px ${f}px`}[l],E=`${m}px ${s.reference.y+b-a}px`,x=!!r.overlap&&c==="y"&&P;return n.floating.style.setProperty(Zt.transformOrigin.variable,x?E:T),{data:{transformOrigin:x?E:T}}}}}var Mg={name:"rects",fn({rects:r}){return {data:r}}},kg=r=>{if(r)return {name:"shiftArrow",fn({placement:e,middlewareData:t}){if(!t.arrow)return {};let{x:n,y:i}=t.arrow,o=e.split("-")[0];return Object.assign(r.style,{left:n!=null?`${n}px`:"",top:i!=null?`${i}px`:"",[o]:`calc(100% + ${Zt.arrowOffset.reference})`}),{}}}};function Ig(r){let[e,t]=r.split("-");return {side:e,align:t,hasAlign:t!=null}}function Oo(r){return r.split("-")[0]}var DT={strategy:"absolute",placement:"bottom",listeners:true,restoreStyles:false,gutter:8,flip:true,slide:true,overlap:false,sameWidth:false,fitViewport:false,overflowPadding:8,arrowPadding:4};function Ag(r,e){let t=r.devicePixelRatio||1;return Math.round(e*t)/t}function fi(r,e){return r!=null&&Math.abs(r-e)<.5}function kl(r){return typeof r=="function"?r():r==="clipping-ancestors"?"clippingAncestors":r}function OT(r,e,t){let n=r||e.createElement("div");return Sg({element:n,padding:t.arrowPadding})}function NT(r,e){if(!Dm(e.offset??e.gutter))return bg(({placement:t})=>{let n=(r?.clientHeight||0)/2,i=e.offset?.mainAxis??e.gutter,o=typeof i=="number"?i+n:i??n,{hasAlign:s}=Ig(t),a=s?void 0:e.shift,l=e.offset?.crossAxis??a;return On({crossAxis:l,mainAxis:o,alignmentAxis:e.shift})})}function FT(r){if(r.flip)return yg(()=>{let e=kl(r.boundary);return {...e?{boundary:e}:void 0,padding:r.overflowPadding,fallbackPlacements:r.flip===true?void 0:r.flip}})}function VT(r){if(!(!r.slide&&!r.overlap))return vg(()=>{let e=kl(r.boundary);return {...e?{boundary:e}:void 0,mainAxis:r.slide,crossAxis:r.overlap,padding:r.overflowPadding,limiter:Cg()}})}function _T(r){if(r.sizeMiddleware===false&&!r.sameWidth&&!r.fitViewport)return;let e,t,n,i;return wg(()=>{let o=kl(r.boundary);return {padding:r.overflowPadding,...o?{boundary:o}:void 0,apply({elements:s,rects:a,availableHeight:l,availableWidth:c}){let d=s.floating,u=Math.round(a.reference.width),h=Math.round(a.reference.height);c=Math.floor(c),l=Math.floor(l),fi(e,u)||(d.style.setProperty("--reference-width",`${u}px`),e=u),fi(t,h)||(d.style.setProperty("--reference-height",`${h}px`),t=h),fi(n,c)||(d.style.setProperty("--available-width",`${c}px`),n=c),fi(i,l)||(d.style.setProperty("--available-height",`${l}px`),i=l);}}})}function BT(r){if(r.hideWhenDetached)return xg(()=>({strategy:"referenceHidden",boundary:kl(r.boundary)??"clippingAncestors"}))}function HT(r){return r?r===true?{ancestorResize:true,ancestorScroll:true,elementResize:true,layoutShift:true}:r:{}}var zT=["transform","visibility","pointer-events","--x","--y","--z-index","--reference-width","--reference-height","--available-width","--available-height","--transform-origin"],$T=["top","right","bottom","left"];function Rg(r,e){if(!r)return Id;let t=new Map(e.map(n=>[n,r.style.getPropertyValue(n)]));return ()=>{t.forEach((n,i)=>{n?r.style.setProperty(i,n):r.style.removeProperty(i);}),r.style.length===0&&r.removeAttribute("style");}}function Dg(r){return r==null?null:ce(r)?r:typeof r=="object"&&r&&"contextElement"in r&&r.contextElement?r.contextElement:r}function WT(r,e,t={}){let n=()=>(typeof e=="function"?e():e)??null,i=()=>{let w=typeof r=="function"?r():r;return t.getAnchorElement?.()??w},o=()=>{let w=i();return !w&&!t.getAnchorRect?null:Pg(w,t.getAnchorRect)},s=Object.assign({},DT,t),a=[],l=null,c,d;function u(w){c?.(),d?.(),l=w,c=s.restoreStyles?Rg(w,zT):void 0;let M=w.querySelector("[data-part=arrow]");d=s.restoreStyles?Rg(M,$T):void 0,a=[NT(M,s),FT(s),VT(s),OT(M,w.ownerDocument,s),kg(M),Lg({gutter:s.gutter,offset:s.offset,overlap:s.overlap},M),_T(s),BT(s),Mg];}let{placement:h,strategy:p,onComplete:m,onPositioned:f}=s,g,b,y=false,v,S,P=Id,T=HT(s.listeners);function E(){if(!s.listeners)return;let w=i(),M=o(),k=n();if(!M||!k)return;(Dg(w)!==Dg(v)||k!==S)&&(P(),v=w,S=k,P=gg(M,k,L,T));}async function x(){E();let w=n();if(!w)return;w!==l&&(u(w),y=false);let M=o();if(!M)return;let k=await Tg(M,w,{placement:h,middleware:a,strategy:p});m?.(k);let C=Se(w),A=Ag(C,k.x),$=Ag(C,k.y);if(fi(g,A)||(w.style.setProperty("--x",`${A}px`),g=A),fi(b,$)||(w.style.setProperty("--y",`${$}px`),b=$),s.hideWhenDetached&&(k.middlewareData.hide?.referenceHidden?(w.style.setProperty("visibility","hidden"),w.style.setProperty("pointer-events","none")):(w.style.removeProperty("visibility"),w.style.removeProperty("pointer-events"))),!y){let ie=w.firstElementChild;ie&&(w.style.setProperty("--z-index",ri(ie).zIndex),y=true);}}async function L(){t.updatePosition?(await t.updatePosition({updatePosition:x,floatingElement:n()}),f?.({placed:true})):await x();}return L(),()=>{P(),d?.(),c?.(),f?.({placed:false});}}function Il(r,e,t={}){let{defer:n,...i}=t,o=n?Me:a=>a(),s=[];return s.push(o(()=>{s.push(WT(r,e,i));})),()=>{s.forEach(a=>a?.());}}var GT={bottom:"rotate(45deg)",left:"rotate(135deg)",top:"rotate(225deg)",right:"rotate(315deg)"};function su(r={}){let{placement:e,sameWidth:t,fitViewport:n,strategy:i="absolute"}=r;return {arrow:{position:"absolute",width:Zt.arrowSize.reference,height:Zt.arrowSize.reference,[Zt.arrowSizeHalf.variable]:`calc(${Zt.arrowSize.reference} / 2)`,[Zt.arrowOffset.variable]:`calc(${Zt.arrowSizeHalf.reference} * -1)`},arrowTip:{transform:e?GT[e.split("-")[0]]:void 0,background:Zt.arrowBg.reference,top:"0",left:"0",width:"100%",height:"100%",position:"absolute",zIndex:"inherit"},floating:{position:i,isolation:"isolate",minWidth:t?void 0:"max-content",width:t?"var(--reference-width)":void 0,maxWidth:n?"var(--available-width)":void 0,maxHeight:n?"var(--available-height)":void 0,pointerEvents:e?void 0:"none",top:"0px",left:"0px",transform:e?"translate3d(var(--x), var(--y), 0)":"translate3d(0, -100vh, 0)",zIndex:"var(--z-index)"}}}var Jt=(r,e)=>{let t=r.ids?.trigger;return t!=null?nt(t)?t(e):t:e?`menu:${r.id}:trigger:${e}`:`menu:${r.id}:trigger`},Al=(r,e)=>{let t=r.ids?.contextTrigger;return t!=null?nt(t)?t(e):t:e?`menu:${r.id}:ctx-trigger:${e}`:`menu:${r.id}:ctx-trigger`},_n=r=>r.ids?.content??`menu:${r.id}:content`,Og=r=>r.ids?.arrow??`menu:${r.id}:arrow`,au=r=>r.ids?.positioner??`menu:${r.id}:popper`,Ng=(r,e)=>r.ids?.group?.(e)??`menu:${r.id}:group:${e}`,Tr=(r,e)=>`${r.id}/${e}`,Bn=r=>r?.dataset.value??null,lu=(r,e)=>r.ids?.groupLabel?.(e)??`menu:${r.id}:group-label:${e}`,Rt=r=>r.getById(_n(r)),cu=r=>r.getById(au(r)),du=r=>r.getById(Jt(r)),Fg=(r,e)=>e?r.getById(Tr(r,e)):null;var Vg=r=>r.getById(Al(r)),uu=r=>li(r.getRootNode(),`[data-scope="menu"][data-part="trigger"][data-ownedby="${r.id}"]`),hu=r=>li(r.getRootNode(),`[data-scope="menu"][data-part="context-trigger"][data-ownedby="${r.id}"]`),No=(r,e)=>e==null?du(r)??uu(r)[0]:r.getById(Jt(r,e)),Fo=r=>{let t=`[role^="menuitem"][data-ownedby=${CSS.escape(_n(r))}]:not([data-disabled])`;return li(Rt(r),t)},_g=r=>Lm(Fo(r)),Bg=r=>Mm(Fo(r)),pu=(r,e)=>e?r.id===e||r.dataset.value===e:false,Hg=(r,e)=>{let t=Fo(r),n=t.findIndex(i=>pu(i,e.value));return Im(t,n,{loop:e.loop??e.loopFocus})},zg=(r,e)=>{let t=Fo(r),n=t.findIndex(i=>pu(i,e.value));return Am(t,n,{loop:e.loop??e.loopFocus})},$g=(r,e)=>{let t=Fo(r),n=t.find(i=>pu(i,e.value));return hl(t,{state:e.typeaheadState,key:e.key,activeId:n?.id??null})},Vo=r=>ce(r)&&(r.dataset.disabled===""||r.hasAttribute("disabled")),mu=r=>!!r?.getAttribute("role")?.startsWith("menuitem")&&!!r?.hasAttribute("data-controls");var Rl="menu:select";function Wg(r,e){if(!r)return;let t=Se(r),n=new t.CustomEvent(Rl,{detail:{value:e}});r.dispatchEvent(n);}function UT(r){let e=_n(r);return Rt(r)??r.getDoc().getElementById(e)}function fu(r,e){if(!ce(r))return false;for(let t in e){let n=e[t],i=UT(n.scope);if(i&&rt(i,r))return true;let o=n.refs.get("children");if(Object.keys(o).length>0&&fu(r,o))return true}return false}var _o=(r,e)=>({x:r,y:e});function Gg(r){let{x:e,y:t,width:n,height:i}=r,o=e+n/2,s=t+i/2;return {x:e,y:t,width:n,height:i,minX:e,minY:t,maxX:e+n,maxY:t+i,midX:o,midY:s,center:_o(o,s)}}function Ug(r){let e=_o(r.minX,r.minY),t=_o(r.maxX,r.minY),n=_o(r.maxX,r.maxY),i=_o(r.minX,r.maxY);return {top:e,right:t,bottom:n,left:i}}function Yg(r,e){let t=Gg(r),{top:n,right:i,left:o,bottom:s}=Ug(t),[a]=e.split("-");return {top:[o,n,i,s],right:[n,i,s,o],bottom:[n,o,s,i],left:[i,n,o,s]}[a]}function Dl(r,e){let{x:t,y:n}=e,i=false;for(let o=0,s=r.length-1;o<r.length;s=o++){let a=r[o].x,l=r[o].y,c=r[s].x,d=r[s].y;l>n!=d>n&&t<(c-a)*(n-l)/(d-l)+a&&(i=!i);}return i}function bu(r){let e=r.parent;for(;e&&e.context.get("isSubmenu");)e=e.refs.get("parent");e?.send({type:"CLOSE"});}function Kg(r,e){return r?Dl(r,e):false}function Xg(r,e,t){let n=Object.keys(r).length>0;if(!e)return null;if(!n)return Tr(t,e);for(let i in r){let o=r[i],s=Jt(o.scope);if(s===e)return s}return Tr(t,e)}function Hn(r,e){r&&(r.refs.set("pointerRoutingLocked",e),r.context.set("pointerRoutingMode",e?"locked":"interactive"));}function jg(r){let e=r.context.get("highlightedValue");if(!e)return false;let t=r.refs.get("children");for(let n in t){let i=t[n];if(i.state.hasTag("open")&&Jt(i.scope)===e)return true}return false}function qg(r,e){r&&(r.refs.get("pointerRoutingLocked")||e&&jg(r)||Hn(r,false));}function Zg(r){r&&(jg(r)||Hn(r,false));}function vu(r,e){let{context:t,send:n,state:i,computed:o,prop:s,scope:a}=r,l=i.hasTag("open"),c=t.get("isSubmenu"),d=o("isTypingAhead"),u=s("composite"),h=t.get("currentPlacement"),p=h?Oo(h):void 0,m=t.get("anchorPoint"),f=t.get("highlightedValue"),g=t.get("triggerValue"),b=su({...s("positioning"),placement:h});function y(T){return {id:Tr(a,T.value),disabled:!!T.disabled,highlighted:f===T.value}}function v(T){let E=T.valueText??T.value;return {...T,id:T.value,valueText:E}}function S(T){return {...y(v(T)),checked:!!T.checked}}function P(T){let{closeOnSelect:E,valueText:x,value:L}=T,w=y(T),M=Tr(a,L);return e.element({...ze.item.attrs,id:M,role:"menuitem","aria-disabled":Fd(w.disabled),"data-disabled":mt(w.disabled),"data-ownedby":_n(a),"data-highlighted":mt(w.highlighted),"data-value":L,"data-valuetext":x,onDragStart(k){k.currentTarget.matches("a[href]")&&k.preventDefault();},onPointerMove(k){if(w.disabled||k.pointerType!=="mouse")return;let C=k.currentTarget;if(w.highlighted)return;let A=oi(k);n({type:"ITEM_POINTERMOVE",id:M,target:C,closeOnSelect:E,point:A});},onPointerLeave(k){if(w.disabled||k.pointerType!=="mouse"||!r.event.previous()?.type.includes("POINTER"))return;let A=k.currentTarget;n({type:"ITEM_POINTERLEAVE",id:M,target:A,closeOnSelect:E});},onPointerDown(k){if(w.disabled)return;let C=k.currentTarget;n({type:"ITEM_POINTERDOWN",target:C,id:M,closeOnSelect:E});},onClick(k){if(Ud(k)||Gd(k)||w.disabled)return;let C=k.currentTarget;n({type:"ITEM_CLICK",target:C,id:M,closeOnSelect:E});}})}return {highlightedValue:f,open:l,setOpen(T){i.hasTag("open")!==T&&n({type:T?"OPEN":"CLOSE"});},triggerValue:g,setTriggerValue(T){n({type:"TRIGGER_VALUE.SET",value:T});},setHighlightedValue(T){n({type:"HIGHLIGHTED.SET",value:T});},setParent(T){n({type:"PARENT.SET",value:T,id:T.prop("id")});},setChild(T){n({type:"CHILD.SET",value:T,id:T.prop("id")});},reposition(T={}){n({type:"POSITIONING.SET",options:T});},addItemListener(T){let E=a.getById(T.id);if(!E)return;let x=()=>T.onSelect?.();return E.addEventListener(Rl,x),()=>E.removeEventListener(Rl,x)},getContextTriggerProps(T={}){let{value:E}=T,x=E==null?false:g===E,L=Al(a,E);return e.element({...ze.contextTrigger.attrs,dir:s("dir"),id:L,"data-ownedby":a.id,"data-value":E,"data-current":mt(x),"data-state":l?"open":"closed",onPointerDown(w){if(w.pointerType==="mouse")return;let M=oi(w);n({type:"CONTEXT_MENU_START",point:M,value:E});},onPointerCancel(w){w.pointerType!=="mouse"&&n({type:"CONTEXT_MENU_CANCEL"});},onPointerMove(w){w.pointerType!=="mouse"&&n({type:"CONTEXT_MENU_CANCEL"});},onPointerUp(w){w.pointerType!=="mouse"&&n({type:"CONTEXT_MENU_CANCEL"});},onContextMenu(w){let M=oi(w),k=l&&E!=null&&!x;n({type:k?"TRIGGER_VALUE.SET":"CONTEXT_MENU",point:M,value:E}),w.preventDefault();},style:{WebkitTouchCallout:"none",WebkitUserSelect:"none",userSelect:"none"}})},getTriggerItemProps(T){let E=T.getTriggerProps();return Vm(P({value:E.id}),E)},getTriggerProps(T={}){let{value:E}=T,x=E==null?false:g===E,L=Jt(a,E);return e.button({...c?ze.triggerItem.attrs:ze.trigger.attrs,"data-placement":h,"data-side":p,type:"button",dir:s("dir"),id:L,...E!=null&&{"data-ownedby":a.id,"data-value":E,"data-current":mt(x)},"data-uid":s("id"),"aria-haspopup":u?"menu":"dialog","aria-controls":_n(a),"data-controls":_n(a),"aria-expanded":E==null?l:l&&x,"data-state":l?"open":"closed",onPointerMove(w){if(w.pointerType!=="mouse"||Vo(w.currentTarget)||!c)return;let k=oi(w);n({type:"TRIGGER_POINTERMOVE",target:w.currentTarget,point:k});},onPointerLeave(w){if(Vo(w.currentTarget)||w.pointerType!=="mouse"||!c)return;Hn(r.refs.get("parent"),true);let M=oi(w);n({type:"TRIGGER_POINTERLEAVE",target:w.currentTarget,point:M});},onPointerDown(w){Vo(w.currentTarget)||al(w)||w.preventDefault();},onClick(w){if(w.defaultPrevented||Vo(w.currentTarget))return;let M=l&&E!=null&&!x;n({type:M?"TRIGGER_VALUE.SET":"TRIGGER_CLICK",target:w.currentTarget,value:E});},onBlur(){n({type:"TRIGGER_BLUR"});},onFocus(){n({type:"TRIGGER_FOCUS"});},onKeyDown(w){if(w.defaultPrevented)return;let M={ArrowDown(){n({type:"ARROW_DOWN",value:E});},ArrowUp(){n({type:"ARROW_UP",value:E});},Enter(){n({type:"ARROW_DOWN",src:"enter",value:E});},Space(){n({type:"ARROW_DOWN",src:"space",value:E});}},k=Yd(w,{orientation:"vertical",dir:s("dir")}),C=M[k];C&&(w.preventDefault(),C(w));}})},getIndicatorProps(){return e.element({...ze.indicator.attrs,dir:s("dir"),"data-state":l?"open":"closed"})},getPositionerProps(){return e.element({...ze.positioner.attrs,dir:s("dir"),id:au(a),style:b.floating})},getArrowProps(){return e.element({id:Og(a),...ze.arrow.attrs,dir:s("dir"),style:b.arrow})},getArrowTipProps(){return e.element({...ze.arrowTip.attrs,dir:s("dir"),style:b.arrowTip})},getContentProps(){return e.element({...ze.content.attrs,id:_n(a),"aria-label":s("aria-label"),hidden:!l,"data-state":l?"open":"closed",role:u?"menu":"dialog",tabIndex:0,dir:s("dir"),"aria-activedescendant":o("highlightedId")||void 0,"aria-labelledby":m?Al(a,g??void 0):Jt(a,g??void 0),"data-placement":h,"data-side":p,onPointerEnter(T){T.pointerType==="mouse"&&n({type:"MENU_POINTERENTER"});},onKeyDown(T){if(T.defaultPrevented||!rt(T.currentTarget,Re(T)))return;let E=Re(T);if(!(E?.closest("[role=menu]")===T.currentTarget||E===T.currentTarget))return;if(T.key==="Tab"&&!vf(T)){T.preventDefault();return}let L={ArrowDown(){n({type:"ARROW_DOWN"});},ArrowUp(){n({type:"ARROW_UP"});},ArrowLeft(){n({type:"ARROW_LEFT"});},ArrowRight(){n({type:"ARROW_RIGHT"});},Enter(){n({type:"ENTER"});},Space(k){d?n({type:"TYPEAHEAD",key:k.key}):L.Enter?.(k);},Home(){n({type:"HOME"});},End(){n({type:"END"});}},w=Yd(T,{dir:s("dir")}),M=L[w];if(M){M(T),T.stopPropagation(),T.preventDefault();return}s("typeahead")&&uf(T)&&(pf(T)||ni(E)||(n({type:"TYPEAHEAD",key:T.key}),T.preventDefault()));}})},getSeparatorProps(){return e.element({...ze.separator.attrs,role:"separator",dir:s("dir"),"aria-orientation":"horizontal"})},getItemState:y,getItemProps:P,getOptionItemState:S,getOptionItemProps(T){let{type:E,disabled:x,closeOnSelect:L}=T,w=v(T),M=S(T);return {...P(w),...e.element({"data-type":E,...ze.item.attrs,dir:s("dir"),"data-value":w.value,role:`menuitem${E}`,"aria-checked":!!M.checked,"data-state":M.checked?"checked":"unchecked",onClick(k){if(x||Ud(k)||Gd(k))return;let C=k.currentTarget;n({type:"ITEM_CLICK",target:C,option:w,closeOnSelect:L});}})}},getItemIndicatorProps(T){let E=S(kd(T)),x=E.checked?"checked":"unchecked";return e.element({...ze.itemIndicator.attrs,dir:s("dir"),"data-disabled":mt(E.disabled),"data-highlighted":mt(E.highlighted),"data-state":fo(T,"checked")?x:void 0,hidden:fo(T,"checked")?!E.checked:void 0})},getItemTextProps(T){let E=S(kd(T)),x=E.checked?"checked":"unchecked";return e.element({...ze.itemText.attrs,dir:s("dir"),"data-disabled":mt(E.disabled),"data-highlighted":mt(E.highlighted),"data-state":fo(T,"checked")?x:void 0})},getItemGroupLabelProps(T){return e.element({...ze.itemGroupLabel.attrs,id:lu(a,T.htmlFor),dir:s("dir")})},getItemGroupProps(T){return e.element({id:Ng(a,T.id),...ze.itemGroup.attrs,dir:s("dir"),"aria-labelledby":lu(a,T.id),role:"group"})}}}function Jg(r){let e={each(t){for(let n=0;n<r.frames?.length;n+=1){let i=r.frames[n];i&&t(i);}},addEventListener(t,n,i){return e.each(o=>{try{o.document.addEventListener(t,n,i);}catch{}}),()=>{try{e.removeEventListener(t,n,i);}catch{}}},removeEventListener(t,n,i){e.each(o=>{try{o.document.removeEventListener(t,n,i);}catch{}});}};return e}function Qg(r){let e=r.frameElement!=null?r.parent:null;return {addEventListener:(t,n,i)=>{try{e?.addEventListener(t,n,i);}catch{}return ()=>{try{e?.removeEventListener(t,n,i);}catch{}}},removeEventListener:(t,n,i)=>{try{e?.removeEventListener(t,n,i);}catch{}}}}var eb="pointerdown.outside",tb="focus.outside";function YT(r){for(let e of r)if(ce(e)&&ft(e))return true;return false}var ib=r=>"clientY"in r;function KT(r,e){if(!ib(e)||!r)return false;let t=r.getBoundingClientRect();return t.width===0||t.height===0?false:t.top<=e.clientY&&e.clientY<=t.top+t.height&&t.left<=e.clientX&&e.clientX<=t.left+t.width}function XT(r,e){return r.y<=e.y&&e.y<=r.y+r.height&&r.x<=e.x&&e.x<=r.x+r.width}function nb(r,e){if(!e||!ib(r))return false;let t=e.scrollHeight>e.clientHeight,n=t&&r.clientX>e.offsetLeft+e.clientWidth,i=e.scrollWidth>e.clientWidth,o=i&&r.clientY>e.offsetTop+e.clientHeight,s={x:e.offsetLeft,y:e.offsetTop,width:e.clientWidth+(t?16:0),height:e.clientHeight+(i?16:0)},a={x:r.clientX,y:r.clientY};return XT(s,a)?n||o:false}function jT(r,e){let{exclude:t,onFocusOutside:n,onPointerDownOutside:i,onInteractOutside:o,defer:s,followControlledElements:a=true}=e;if(!r)return;let l=Pe(r),c=Se(r),d=Jg(c),u=Qg(c);function h(S,P){if(!ce(P)||!P.isConnected||rt(r,P)||KT(r,S)||a&&sl(r,P))return false;let T=l.querySelector(`[aria-controls="${r.id}"]`);if(T){let x=dl(T);if(nb(S,x))return false}let E=dl(r);return nb(S,E)?false:!t?.(P)}let p=new Set,m=gr(r?.getRootNode()),f=false;function g(S){f=true;let P=()=>{f=false;};l.addEventListener("pointerup",P,{once:true}),c.addEventListener("pointerup",P,{once:true});function T(E){let x=s&&!Wd()?Me:M=>M(),L=E??S,w=L?.composedPath?.()??[L?.target];x(()=>{let M=m?w[0]:Re(S);if(!(!r||!h(S,M))){if(i||o){let k=Dn(i,o);r.addEventListener(eb,k,{once:true});}rb(r,eb,{bubbles:false,cancelable:true,detail:{originalEvent:L,contextmenu:al(L),focusable:YT(w),target:M}});}});}S.pointerType==="touch"?(p.forEach(E=>E()),p.add(Xe(l,"click",T,{once:true})),p.add(u.addEventListener("click",T,{once:true})),p.add(d.addEventListener("click",T,{once:true}))):T();}let b=new Set,y=setTimeout(()=>{b.add(Xe(l,"pointerdown",g,true)),b.add(u.addEventListener("pointerdown",g,true)),b.add(d.addEventListener("pointerdown",g,true));},0);function v(S){if(f)return;(s?Me:T=>T())(()=>{let T=S?.composedPath?.()??[S?.target],E=m?T[0]:Re(S);if(!(!r||!h(S,E))){if(n||o){let x=Dn(n,o);r.addEventListener(tb,x,{once:true});}rb(r,tb,{bubbles:false,cancelable:true,detail:{originalEvent:S,contextmenu:false,focusable:ft(E),target:E}});}});}return Wd()||(b.add(Xe(l,"focusin",v,true)),b.add(u.addEventListener("focusin",v,true)),b.add(d.addEventListener("focusin",v,true))),()=>{clearTimeout(y),p.forEach(S=>S()),b.forEach(S=>S());}}function ob(r,e){let{defer:t}=e,n=t?Me:o=>o(),i=[];return i.push(n(()=>{let o=typeof r=="function"?r():r;i.push(jT(o,e));})),()=>{i.forEach(o=>o?.());}}function rb(r,e,t){let n=r.ownerDocument.defaultView||window,i=new n.CustomEvent(e,t);return r.dispatchEvent(i)}function sb(r,e){let t=n=>{n.key==="Escape"&&(n.isComposing||e?.(n));};return Xe(Pe(r),"keydown",t,{capture:true})}var ab="layer:request-dismiss",$e={layers:[],branches:[],recentlyRemoved:new Set,count(){return this.layers.length},pointerBlockingLayers(){return this.layers.filter(r=>r.pointerBlocking)},topMostPointerBlockingLayer(){return [...this.pointerBlockingLayers()].slice(-1)[0]},hasPointerBlockingLayer(){return this.pointerBlockingLayers().length>0},isBelowPointerBlockingLayer(r){let e=this.indexOf(r),t=this.topMostPointerBlockingLayer()?this.indexOf(this.topMostPointerBlockingLayer()?.node):-1;return e<t},isTopMost(r){return this.layers[this.count()-1]?.node===r},getNestedLayers(r){return Array.from(this.layers).slice(this.indexOf(r)+1)},getLayersByType(r){return this.layers.filter(e=>e.type===r)},getNestedLayersByType(r,e){let t=this.indexOf(r);return t===-1?[]:this.layers.slice(t+1).filter(n=>n.type===e)},getParentLayerOfType(r,e){let t=this.indexOf(r);if(!(t<=0))return this.layers.slice(0,t).reverse().find(n=>n.type===e)},countNestedLayersOfType(r,e){return this.getNestedLayersByType(r,e).length},isInNestedLayer(r,e){return !!(this.getNestedLayers(r).some(n=>rt(n.node,e))||this.recentlyRemoved.size>0)},isInBranch(r){return Array.from(this.branches).some(e=>rt(e,r))},add(r){let e=this.indexOf(r.node);e!==-1&&this.layers.splice(e,1),this.layers.push(r),this.syncLayers();},addBranch(r){this.branches.push(r);},remove(r){let e=this.indexOf(r);if(e<0)return;this.layers[e].styleTargets?.forEach(n=>{let i=n();i&&qT(i);}),this.recentlyRemoved.add(r),wf(()=>this.recentlyRemoved.delete(r)),e<this.count()-1&&this.getNestedLayers(r).forEach(i=>$e.dismiss(i.node,r)),this.layers.splice(e,1),this.syncLayers();},removeBranch(r){let e=this.branches.indexOf(r);e>=0&&this.branches.splice(e,1);},syncLayers(){this.layers.forEach((r,e)=>{lb(r,e,r.node),r.styleTargets?.forEach(t=>{let n=t();if(!n||n===r.node)return;lb(r,e,n);let{zIndex:i}=ri(r.node);n.style.setProperty("--z-index",i);});});},indexOf(r){return this.layers.findIndex(e=>e.node===r)},dismiss(r,e){let t=this.indexOf(r);if(t===-1)return;let n=this.layers[t];JT(r,ab,i=>{n.requestDismiss?.(i),i.defaultPrevented||n?.dismiss();}),ZT(r,ab,{originalLayer:r,targetLayer:e,originalIndex:t,targetIndex:e?this.indexOf(e):-1}),this.syncLayers();},clear(){this.remove(this.layers[0].node);}};function lb(r,e,t){t.style.setProperty("--layer-index",`${e}`),t.removeAttribute("data-nested"),t.removeAttribute("data-has-nested"),$e.getParentLayerOfType(r.node,r.type)&&t.setAttribute("data-nested",r.type);let i=$e.countNestedLayersOfType(r.node,r.type);i>0&&t.setAttribute("data-has-nested",r.type),t.style.setProperty("--nested-layer-count",`${i}`);}function qT(r){r.style.removeProperty("--layer-index"),r.style.removeProperty("--nested-layer-count"),r.style.removeProperty("--z-index"),r.removeAttribute("data-nested"),r.removeAttribute("data-has-nested");}function ZT(r,e,t){let n=r.ownerDocument.defaultView||window,i=new n.CustomEvent(e,{cancelable:true,bubbles:true,detail:t});return r.dispatchEvent(i)}function JT(r,e,t){r.addEventListener(e,t,{once:true});}var yu=new WeakMap,Bo=new WeakMap;function QT(r){return $e.isBelowPointerBlockingLayer(r)?"none":"auto"}function cb(r){let e=QT(r);r.style.pointerEvents!==e&&(r.style.pointerEvents=e);}function eE(r){if(Bo.has(r))return;let e=Se(r);if(typeof e.MutationObserver>"u")return;let t=new e.MutationObserver(()=>{Bo.has(r)&&cb(r);});t.observe(r,{attributes:true,attributeFilter:["style"]}),Bo.set(r,t);}function wu(){$e.layers.forEach(({node:r})=>{cb(r),eE(r);});}function db(r){let e=Bo.get(r);e&&(e.disconnect(),Bo.delete(r)),r.style.pointerEvents="";}function ub(r,e){let t=Pe(r),n=[];return $e.hasPointerBlockingLayer()&&!t.body.hasAttribute("data-inert")&&(yu.set(t.body,t.body.style.pointerEvents),queueMicrotask(()=>{let i=t.body;i&&(i.style.pointerEvents="none",i.setAttribute("data-inert",""));})),e?.forEach(i=>{let[o,s]=Mf(()=>{let a=i();return ce(a)?a:null},{timeout:1e3});o.then(a=>n.push(To(a,{pointerEvents:"auto"}))),n.push(s);}),()=>{$e.hasPointerBlockingLayer()||(queueMicrotask(()=>{let i=t.body;if(!i)return;let o=yu.get(i);o!==void 0&&(i.style.pointerEvents=o,yu.delete(i)),i.removeAttribute("data-inert"),i.style.length===0&&i.removeAttribute("style");}),n.forEach(i=>i()));}}function tE(r,e){let{warnOnMissingNode:t=true}=e;if(t&&!r){Qr("[@zag-js/dismissable] node is `null` or `undefined`");return}if(!r)return;let{onDismiss:n,onRequestDismiss:i,pointerBlocking:o,exclude:s,debug:a,type:l="dialog",layerStyleTargets:c}=e,d={dismiss:n,node:r,type:l,pointerBlocking:o,requestDismiss:i,styleTargets:c};$e.add(d),wu();function u(g){let b=Re(g.detail.originalEvent);$e.isBelowPointerBlockingLayer(r)||$e.isInBranch(b)||(e.onPointerDownOutside?.(g),e.onInteractOutside?.(g),!g.defaultPrevented&&(a&&console.log("onPointerDownOutside:",g.detail.originalEvent),n?.()));}function h(g){let b=Re(g.detail.originalEvent);$e.isInBranch(b)||(e.onFocusOutside?.(g),e.onInteractOutside?.(g),!g.defaultPrevented&&(a&&console.log("onFocusOutside:",g.detail.originalEvent),n?.()));}function p(g){$e.isTopMost(r)&&(e.onEscapeKeyDown?.(g),!g.defaultPrevented&&n&&(g.preventDefault(),n()));}function m(g){if(!r)return false;let b=typeof s=="function"?s():s,y=Array.isArray(b)?b:[b],v=e.persistentElements?.map(S=>S()).filter(ce);return v&&y.push(...v),y.some(S=>rt(S,g))||$e.isInNestedLayer(r,g)}let f=[o?ub(r,e.persistentElements):void 0,sb(r,p),ob(r,{exclude:m,onFocusOutside:h,onPointerDownOutside:u,defer:e.defer})];return ()=>{$e.remove(r),wu(),db(r),f.forEach(g=>g?.());}}function Ol(r,e){let{defer:t}=e,n=t?Me:o=>o(),i=[];return i.push(n(()=>{let o=nt(r)?r():r;i.push(tE(o,e));})),()=>{i.forEach(o=>o?.());}}function nE(r){return !(r.metaKey||!ii()&&r.altKey||r.ctrlKey||r.key==="Control"||r.key==="Shift"||r.key==="Meta")}var rE=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function iE(r,e,t){let n=t?Re(t):null,i=Pe(n),o=Se(n),s=Yt(i);return r=r||s instanceof o.HTMLInputElement&&!rE.has(s?.type)||s instanceof o.HTMLTextAreaElement||s instanceof o.HTMLElement&&s.isContentEditable,!(r&&e==="keyboard"&&t instanceof o.KeyboardEvent&&!Reflect.has(oE,t.key))}var fn=null,xu=new Set,Nl=new Map,Er=false,Su=false,pb=false,oE={Tab:true,Escape:true};function Vl(r,e){for(let t of xu)t(r,e);}function Fl(r){Er=true,nE(r)&&(fn="keyboard",Vl("keyboard",r));}function gt(r){fn="pointer",(r.type==="mousedown"||r.type==="pointerdown")&&(Er=true,Vl("pointer",r));}function mb(r){hf(r)&&(Er=true,fn="virtual");}function fb(r){let e=Re(r);e===Se(e)||e===Pe(e)||pb||!r.isTrusted||(!Er&&!Su&&(fn="virtual",Vl("virtual",r)),Er=false,Su=false);}function gb(){(Er=false,Su=true);}function sE(r){if(typeof window>"u"||Nl.get(Se(r)))return;let e=Se(r),t=Pe(r),n=e.HTMLElement.prototype.focus;function i(){Er=true,n.apply(this,arguments);}try{Object.defineProperty(e.HTMLElement.prototype,"focus",{configurable:!0,value:i});}catch{}t.addEventListener("keydown",Fl,true),t.addEventListener("keyup",Fl,true),t.addEventListener("click",mb,true),e.addEventListener("focus",fb,true),e.addEventListener("blur",gb,false),typeof e.PointerEvent<"u"?(t.addEventListener("pointerdown",gt,true),t.addEventListener("pointermove",gt,true),t.addEventListener("pointerup",gt,true)):(t.addEventListener("mousedown",gt,true),t.addEventListener("mousemove",gt,true),t.addEventListener("mouseup",gt,true)),e.addEventListener("beforeunload",()=>{aE(r);},{once:true}),Nl.set(e,{focus:n});}var aE=(r,e)=>{let t=Se(r),n=Pe(r);let i=Nl.get(t);if(i){try{Object.defineProperty(t.HTMLElement.prototype,"focus",{configurable:!0,value:i.focus});}catch{}n.removeEventListener("keydown",Fl,true),n.removeEventListener("keyup",Fl,true),n.removeEventListener("click",mb,true),t.removeEventListener("focus",fb,true),t.removeEventListener("blur",gb,false),typeof t.PointerEvent<"u"?(n.removeEventListener("pointerdown",gt,true),n.removeEventListener("pointermove",gt,true),n.removeEventListener("pointerup",gt,true)):(n.removeEventListener("mousedown",gt,true),n.removeEventListener("mousemove",gt,true),n.removeEventListener("mouseup",gt,true)),Nl.delete(t);}};function bb(){return fn}function vb(r){fn=r,Vl(r,null);}function hb(){return fn==="keyboard"||fn==="virtual"}function yb(r={}){let{isTextInput:e,autoFocus:t,onChange:n,root:i}=r;sE(i),n?.({isFocusVisible:t||hb(),modality:fn});let o=(s,a)=>{iE(!!e,s,a)&&n?.({isFocusVisible:hb(),modality:s});};return xu.add(o),()=>{xu.delete(o);}}var{not:bt,and:gi,or:lE}=Km(),Cu=rl({props({props:r}){return {closeOnSelect:true,typeahead:true,composite:true,loopFocus:false,navigate(e){Cf(e.node);},...r,positioning:{placement:"bottom-start",gutter:8,...r.positioning}}},initialState({prop:r}){return r("open")||r("defaultOpen")?"open":"idle"},context({bindable:r,prop:e,scope:t}){return {highlightedValue:r(()=>({defaultValue:e("defaultHighlightedValue")||null,value:e("highlightedValue"),onChange(n){e("onHighlightChange")?.({highlightedValue:n});}})),lastHighlightedValue:r(()=>({defaultValue:null})),currentPlacement:r(()=>({defaultValue:void 0})),intentPolygon:r(()=>({defaultValue:null})),anchorPoint:r(()=>({defaultValue:null,hash(n){return `x: ${n?.x}, y: ${n?.y}`}})),isSubmenu:r(()=>({defaultValue:false})),triggerValue:r(()=>({defaultValue:e("defaultTriggerValue")??null,value:e("triggerValue"),onChange(n){let i=e("onTriggerValueChange");if(!i)return;let o=No(t,n);i({value:n,triggerElement:o});}})),pointerRoutingMode:r(()=>({defaultValue:"interactive"}))}},refs(){return {parent:null,children:{},pointerRoutingLocked:false,typeaheadState:{...hl.defaultOptions},positioningOverride:{}}},computed:{isRtl:({prop:r})=>r("dir")==="rtl",isTypingAhead:({refs:r})=>r.get("typeaheadState").keysSoFar!=="",highlightedId:({context:r,scope:e,refs:t})=>Xg(t.get("children"),r.get("highlightedValue"),e)},watch({track:r,action:e,context:t,prop:n}){r([()=>t.get("isSubmenu")],()=>{e(["setSubmenuPlacement"]);}),r([()=>t.hash("anchorPoint")],()=>{t.get("anchorPoint")&&e(["reposition"]);}),r([()=>n("open")],()=>{e(["toggleVisibility"]);});},on:{"TRIGGER_VALUE.SET":{actions:["setTriggerValue","setAnchorPoint","reposition","focusMenu"]},"PARENT.SET":{actions:["setParentMenu"]},"CHILD.SET":{actions:["setChildMenu"]},OPEN:[{guard:"isOpenControlled",actions:["setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setTriggerValue","invokeOnOpen"]}],OPEN_AUTOFOCUS:[{guard:"isOpenControlled",actions:["setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setTriggerValue","highlightFirstItem","invokeOnOpen"]}],CLOSE:[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["invokeOnClose","releaseParentRoutingLock","focusTrigger"]}],"HIGHLIGHTED.RESTORE":{actions:["restoreHighlightedItem"]},"HIGHLIGHTED.SET":{actions:["setHighlightedItem"]},"HIGHLIGHTED.SUGGEST":{actions:["suggestHighlightedItem"]}},states:{idle:{tags:["closed"],on:{"CONTROLLED.OPEN":{target:"open"},"CONTROLLED.CLOSE":{target:"closed"},CONTEXT_MENU_START:{target:"opening:contextmenu",actions:["setAnchorPoint","setTriggerValue"]},CONTEXT_MENU:[{guard:"isOpenControlled",actions:["setAnchorPoint","setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setAnchorPoint","setTriggerValue","invokeOnOpen"]}],TRIGGER_CLICK:[{guard:"isOpenControlled",actions:["invokeOnOpen","setTriggerValue"]},{target:"open",actions:["invokeOnOpen","setTriggerValue"]}],TRIGGER_FOCUS:{guard:bt("isSubmenu"),target:"closed"},TRIGGER_POINTERMOVE:{guard:"isSubmenu",target:"opening"}}},"opening:contextmenu":{tags:["closed"],effects:["waitForLongPress"],on:{"CONTROLLED.OPEN":{target:"open",actions:["reposition"]},"CONTROLLED.CLOSE":{target:"closed",actions:["focusTrigger"]},CONTEXT_MENU_CANCEL:[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["invokeOnClose","releaseParentRoutingLock","focusTrigger"]}],"LONG_PRESS.OPEN":[{guard:"isOpenControlled",actions:["setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setTriggerValue","invokeOnOpen","reposition"]}]}},opening:{tags:["closed"],effects:["waitForOpenDelay"],on:{"CONTROLLED.OPEN":{target:"open"},"CONTROLLED.CLOSE":{target:"closed",actions:["focusTrigger"]},BLUR:[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["invokeOnClose","releaseParentRoutingLock","focusTrigger"]}],TRIGGER_POINTERLEAVE:[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["invokeOnClose","releaseParentRoutingLock","focusTrigger"]}],"DELAY.OPEN":[{guard:"isOpenControlled",actions:["invokeOnOpen"]},{target:"open",actions:["invokeOnOpen"]}]}},closing:{tags:["open"],effects:["trackPointerMove","trackInteractOutside","waitForCloseDelay"],on:{"CONTROLLED.OPEN":{target:"open"},"CONTROLLED.CLOSE":{target:"closed",actions:["focusParentMenu","restoreParentHighlightedItem"]},MENU_POINTERENTER:{target:"open",actions:["clearIntentPolygon"]},POINTER_MOVED_AWAY_FROM_SUBMENU:[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["focusParentMenu","restoreParentHighlightedItem"]}],"DELAY.CLOSE":[{guard:"isOpenControlled",actions:["invokeOnClose","releaseParentRoutingLock"]},{target:"closed",actions:["focusParentMenu","restoreParentHighlightedItem","invokeOnClose","releaseParentRoutingLock"]}]}},closed:{tags:["closed"],entry:["clearHighlightedItem","unlockParentOnClose","clearAnchorPoint"],on:{"CONTROLLED.OPEN":[{guard:lE("isOpenAutoFocusEvent","isArrowDownEvent"),target:"open",actions:["highlightFirstItem"]},{guard:"isArrowUpEvent",target:"open",actions:["highlightLastItem"]},{target:"open"}],CONTEXT_MENU_START:{target:"opening:contextmenu",actions:["setAnchorPoint","setTriggerValue"]},CONTEXT_MENU:[{guard:"isOpenControlled",actions:["setAnchorPoint","setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setAnchorPoint","setTriggerValue","invokeOnOpen"]}],TRIGGER_CLICK:[{guard:"isOpenControlled",actions:["invokeOnOpen","setTriggerValue"]},{target:"open",actions:["invokeOnOpen","setTriggerValue"]}],TRIGGER_POINTERMOVE:{guard:"isTriggerItem",target:"opening"},TRIGGER_BLUR:{target:"idle"},ARROW_DOWN:[{guard:"isOpenControlled",actions:["setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setTriggerValue","highlightFirstItem","invokeOnOpen"]}],ARROW_UP:[{guard:"isOpenControlled",actions:["setTriggerValue","invokeOnOpen"]},{target:"open",actions:["setTriggerValue","highlightLastItem","invokeOnOpen"]}]}},open:{tags:["open"],effects:["trackInteractOutside","trackFocusVisible","trackPositioning","scrollToHighlightedItem"],entry:["focusMenu","unlockParentOnOpen"],on:{"CONTROLLED.CLOSE":[{target:"closed",guard:"isArrowLeftEvent",actions:["focusParentMenu"]},{target:"closed",actions:["focusTrigger"]}],TRIGGER_CLICK:[{guard:gi(bt("isTriggerItem"),"isOpenControlled"),actions:["invokeOnClose","releaseParentRoutingLock"]},{guard:bt("isTriggerItem"),target:"closed",actions:["invokeOnClose","releaseParentRoutingLock","focusTrigger"]}],CONTEXT_MENU:{actions:["setAnchorPoint","setTriggerValue","focusMenu"]},ARROW_UP:{actions:["highlightPrevItem","focusMenu"]},ARROW_DOWN:{actions:["highlightNextItem","focusMenu"]},ARROW_LEFT:[{guard:gi("isSubmenu","isOpenControlled"),actions:["invokeOnClose","releaseParentRoutingLock"]},{guard:"isSubmenu",target:"closed",actions:["focusParentMenu","invokeOnClose","releaseParentRoutingLock"]}],HOME:{actions:["highlightFirstItem","focusMenu"]},END:{actions:["highlightLastItem","focusMenu"]},ARROW_RIGHT:{guard:"isTriggerItemHighlighted",actions:["openSubmenu"]},ENTER:[{guard:"isTriggerItemHighlighted",actions:["openSubmenu"]},{actions:["clickHighlightedItem"]}],ITEM_POINTERMOVE:[{guard:bt("isPointerRoutingLocked"),actions:["setHighlightedItem","focusMenu","closeSiblingMenus"]},{actions:["setLastHighlightedItem","closeSiblingMenus"]}],ITEM_POINTERLEAVE:{guard:gi(bt("isPointerRoutingLocked"),bt("isTriggerItem")),actions:["clearHighlightedItem"]},ITEM_CLICK:[{guard:gi(bt("isTriggerItemHighlighted"),bt("isHighlightedItemEditable"),"closeOnSelect","isOpenControlled"),actions:["invokeOnSelect","setOptionState","closeRootMenu","invokeOnClose","releaseParentRoutingLock"]},{guard:gi(bt("isTriggerItemHighlighted"),bt("isHighlightedItemEditable"),"closeOnSelect"),target:"closed",actions:["invokeOnSelect","setOptionState","closeRootMenu","invokeOnClose","releaseParentRoutingLock","focusTrigger"]},{guard:gi(bt("isTriggerItemHighlighted"),bt("isHighlightedItemEditable")),actions:["invokeOnSelect","setOptionState"]},{actions:["setHighlightedItem"]}],TRIGGER_POINTERMOVE:{guard:"isTriggerItem",actions:["setIntentPolygon"]},TRIGGER_POINTERLEAVE:{target:"closing",actions:["setIntentPolygon"]},ITEM_POINTERDOWN:{actions:["setHighlightedItem"]},TYPEAHEAD:{actions:["highlightMatchedItem"]},FOCUS_MENU:{actions:["focusMenu"]},"POSITIONING.SET":{actions:["reposition"]}}}},implementations:{guards:{closeOnSelect:({prop:r,event:e})=>!!(e?.closeOnSelect??r("closeOnSelect")),isTriggerItem:({event:r})=>mu(r.target),isTriggerItemHighlighted:({event:r,scope:e,computed:t})=>!!(r.target??e.getById(t("highlightedId")))?.hasAttribute("data-controls"),isSubmenu:({context:r})=>r.get("isSubmenu"),isPointerRoutingLocked:({refs:r})=>r.get("pointerRoutingLocked"),isHighlightedItemEditable:({scope:r,computed:e})=>ni(r.getById(e("highlightedId"))),isOpenControlled:({prop:r})=>r("open")!==void 0,isArrowLeftEvent:({event:r})=>r.previousEvent?.type==="ARROW_LEFT",isArrowUpEvent:({event:r})=>r.previousEvent?.type==="ARROW_UP",isArrowDownEvent:({event:r})=>r.previousEvent?.type==="ARROW_DOWN",isOpenAutoFocusEvent:({event:r})=>r.previousEvent?.type==="OPEN_AUTOFOCUS"},effects:{waitForOpenDelay({send:r}){let e=setTimeout(()=>{r({type:"DELAY.OPEN"});},200);return ()=>clearTimeout(e)},waitForCloseDelay({send:r}){let e=setTimeout(()=>{r({type:"DELAY.CLOSE"});},100);return ()=>clearTimeout(e)},waitForLongPress({send:r}){let e=setTimeout(()=>{r({type:"LONG_PRESS.OPEN"});},700);return ()=>clearTimeout(e)},trackFocusVisible({scope:r}){return yb({root:r.getRootNode?.()})},trackPositioning({context:r,prop:e,scope:t,refs:n}){if(Vg(t)||hu(t).length>0)return;let o={...e("positioning"),...n.get("positioningOverride")};return r.set("currentPlacement",o.placement),Il(()=>No(t,r.get("triggerValue")),()=>cu(t),{...o,defer:true,onComplete(l){r.set("currentPlacement",l.placement);}})},trackInteractOutside({refs:r,scope:e,prop:t,context:n,send:i}){let o=()=>Rt(e),s=true,a=l=>hu(e).some(c=>rt(c,l));return Ol(o,{type:"menu",defer:true,exclude:[du(e),...uu(e)].filter(Boolean),onInteractOutside:t("onInteractOutside"),onRequestDismiss:t("onRequestDismiss"),onFocusOutside(l){t("onFocusOutside")?.(l);let c=Re(l.detail.originalEvent);if(a(c)){l.preventDefault();return}if(fu(c,r.get("children"))){l.preventDefault();return}},onEscapeKeyDown(l){t("onEscapeKeyDown")?.(l),n.get("isSubmenu")&&l.preventDefault(),bu({parent:r.get("parent")});},onPointerDownOutside(l){t("onPointerDownOutside")?.(l);let c=Re(l.detail.originalEvent);if(a(c)&&l.detail.contextmenu){l.preventDefault();return}s=!l.detail.focusable;},onDismiss(){i({type:"CLOSE",src:"interact-outside",restoreFocus:s});}})},trackPointerMove({context:r,scope:e,send:t,refs:n}){let i=n.get("parent");if(!i)return;Hn(i,true);let o=e.getDoc();return Xe(o,"pointermove",s=>{Kg(r.get("intentPolygon"),{x:s.clientX,y:s.clientY})||(t({type:"POINTER_MOVED_AWAY_FROM_SUBMENU"}),Hn(i,false));})},scrollToHighlightedItem({scope:r,computed:e}){let t=()=>{if(bb()==="pointer")return;let o=r.getById(e("highlightedId")),s=Rt(r);Ef(o,{rootEl:s,block:"nearest"});};return Me(()=>{vb("virtual"),t();}),Sf(()=>Rt(r),{attributes:["aria-activedescendant"],callback:t})}},actions:{setAnchorPoint({context:r,event:e}){r.set("anchorPoint",t=>Zr(t,e.point)?t:e.point);},setSubmenuPlacement({context:r,computed:e,refs:t}){if(!r.get("isSubmenu"))return;let n=e("isRtl")?"left-start":"right-start";t.set("positioningOverride",{placement:n,gutter:0});},reposition({context:r,scope:e,prop:t,event:n,refs:i}){let o=()=>cu(e),s=n.point??r.get("anchorPoint"),a=s?()=>({width:0,height:0,...s}):void 0,l={...t("positioning"),...i.get("positioningOverride")},c=n.value??r.get("triggerValue");Il(()=>No(e,c),o,{...l,defer:true,getAnchorRect:a,...n.options??{},listeners:false,onComplete(u){r.set("currentPlacement",u.placement);}});},setOptionState({event:r}){if(!r.option)return;let{checked:e,onCheckedChange:t,type:n}=r.option;n==="radio"?t?.(true):n==="checkbox"&&t?.(!e);},clickHighlightedItem({scope:r,computed:e,prop:t,context:n}){let i=r.getById(e("highlightedId"));if(!i||i.dataset.disabled)return;let o=n.get("highlightedValue");Jm(i)?t("navigate")?.({value:o,node:i,href:i.href}):queueMicrotask(()=>i.click());},setIntentPolygon({context:r,scope:e,event:t}){let n=Rt(e),i=r.get("currentPlacement");if(!n||!i)return;let o=n.getBoundingClientRect(),s=Yg(o,i);if(!s)return;let l=Oo(i)==="right"?-5:5;r.set("intentPolygon",[{...t.point,x:t.point.x+l},...s]);},clearIntentPolygon({context:r}){r.set("intentPolygon",null);},clearAnchorPoint({context:r}){r.set("anchorPoint",null);},unlockParentOnOpen({refs:r,context:e,scope:t}){let n=r.get("parent");if(e.get("isSubmenu")){let i=Jt(t);n?.send({type:"HIGHLIGHTED.SUGGEST",value:i});}Hn(n,false);},unlockParentOnClose({refs:r,context:e}){qg(r.get("parent"),e.get("isSubmenu"));},setHighlightedItem({context:r,event:e}){let t=e.value||Bn(e.target);r.set("highlightedValue",t);},clearHighlightedItem({context:r}){r.set("highlightedValue",null);},focusMenu({scope:r}){Me(()=>{let e=Rt(r);cl({root:e,enabled:!rt(e,r.getActiveElement()),filter(n){return !n.role?.startsWith("menuitem")}})?.focus({preventScroll:true});});},highlightFirstItem({context:r,scope:e}){(Rt(e)?queueMicrotask:Me)(()=>{let n=_g(e);n&&r.set("highlightedValue",Bn(n));});},highlightLastItem({context:r,scope:e}){(Rt(e)?queueMicrotask:Me)(()=>{let n=Bg(e);n&&r.set("highlightedValue",Bn(n));});},highlightNextItem({context:r,scope:e,event:t,prop:n}){let i=Hg(e,{loop:t.loop,value:r.get("highlightedValue"),loopFocus:n("loopFocus")});r.set("highlightedValue",Bn(i));},highlightPrevItem({context:r,scope:e,event:t,prop:n}){let i=zg(e,{loop:t.loop,value:r.get("highlightedValue"),loopFocus:n("loopFocus")});r.set("highlightedValue",Bn(i));},invokeOnSelect({context:r,prop:e,scope:t}){let n=r.get("highlightedValue");if(n==null)return;let i=Fg(t,n);Wg(i,n),e("onSelect")?.({value:n});},focusTrigger({scope:r,context:e,event:t}){e.get("isSubmenu")||e.get("anchorPoint")||t.restoreFocus===false||queueMicrotask(()=>{No(r,e.get("triggerValue"))?.focus({preventScroll:true});});},highlightMatchedItem({scope:r,context:e,event:t,refs:n}){let i=$g(r,{key:t.key,value:e.get("highlightedValue"),typeaheadState:n.get("typeaheadState")});i&&e.set("highlightedValue",Bn(i));},setParentMenu({refs:r,event:e,context:t}){r.set("parent",e.value),t.set("isSubmenu",true);},setChildMenu({refs:r,event:e}){let t=r.get("children");t[e.id]=e.value,r.set("children",t);},closeSiblingMenus({refs:r,event:e,scope:t}){let n=e.target;if(!mu(n))return;let i=n?.getAttribute("data-uid"),o=r.get("children");for(let s in o){if(s===i)continue;let a=o[s],l=a.context.get("intentPolygon");l&&e.point&&Dl(l,e.point)||(Rt(t)?.focus({preventScroll:true}),a.send({type:"CLOSE"}));}},closeRootMenu({refs:r}){bu({parent:r.get("parent")});},openSubmenu({refs:r,scope:e,computed:t}){let i=e.getById(t("highlightedId"))?.getAttribute("data-uid"),o=r.get("children");(i?o[i]:null)?.send({type:"OPEN_AUTOFOCUS"});},focusParentMenu({refs:r}){r.get("parent")?.send({type:"FOCUS_MENU"});},setLastHighlightedItem({context:r,event:e}){r.set("lastHighlightedValue",Bn(e.target));},suggestHighlightedItem({context:r,event:e}){let t=e.value;if(t){if(r.get("highlightedValue")!=null){r.set("lastHighlightedValue",t);return}r.set("highlightedValue",t);}},restoreHighlightedItem({context:r}){let e=r.get("lastHighlightedValue");r.set("lastHighlightedValue",null),e&&r.set("highlightedValue",e);},restoreParentHighlightedItem({refs:r}){r.get("parent")?.send({type:"HIGHLIGHTED.RESTORE"});},invokeOnOpen({prop:r}){r("onOpenChange")?.({open:true});},invokeOnClose({prop:r}){r("onOpenChange")?.({open:false});},releaseParentRoutingLock({refs:r,context:e}){e.get("isSubmenu")&&Zg(r.get("parent"));},toggleVisibility({prop:r,event:e,send:t}){t({type:r("open")?"CONTROLLED.OPEN":"CONTROLLED.CLOSE",previousEvent:e});},setTriggerValue({context:r,event:e}){e.value!==void 0&&r.set("triggerValue",e.value);}}}});function wb(r){return {machine:Cu,props:{id:r.id??yl("vela-menu"),ids:r.triggerId?{trigger:r.triggerId}:void 0,positioning:{placement:r.placement??"bottom-start",...r.getAnchorRect?{getAnchorRect:()=>r.getAnchorRect()}:{}},onSelect:e=>r.onSelect?.(e.value),onOpenChange:e=>r.onOpenChange?.(e.open)},connect:e=>vu(e,ci)}}var xb="vela-ui-menu",Sb=`
4
4
  .vela-menu {
5
5
  /* The list is a <ul>: without this, block rows (the separator) paint a ::marker dot. */
6
6
  list-style: none;
@@ -1004,5 +1004,5 @@ ${vr(".vela-sd-pane")}
1004
1004
  [data-layout='mobile'] .vela-attribution .vela-attr-wordmark svg { height: 21px; }
1005
1005
  [data-vela-layout='mobile'] .vela-attribution:hover .vela-attr-wordmark,
1006
1006
  [data-layout='mobile'] .vela-attribution:hover .vela-attr-wordmark { transform: translateX(0); }
1007
- `;function UM(r){let e=r.getElementById(_w);e||(e=r.createElement("style"),e.id=_w,r.head.appendChild(e)),e.textContent=GM;}function _h(r){return lt(r)?"#ffffff":"#000000"}function Bh(r,e){let t=lt(e);r.style.color=t?"#ffffff":"#000000",r.style.setProperty("--vela-attr-shadow",t?"rgba(0,0,0,0.45)":"rgba(255,255,255,0.55)");}function Bw(r,e,t){let n=r.createElement("div");return n.className="vela-attribution-custom",Object.assign(n.style,{position:"absolute",zIndex:"6",pointerEvents:"auto",display:"flex",alignItems:"center",lineHeight:"1"}),n.style.color=_h(t),n.innerHTML=e,n.dataset.velaScreenshot="1",n}function Hw(r,e){UM(r);let t=r.createElement("a");t.className="vela-attribution",t.href=WM,t.target="_blank",t.rel="noopener",t.title="Charting by Vela",t.setAttribute("aria-label","Charting by Vela"),Object.assign(t.style,{position:"absolute",zIndex:"6",pointerEvents:"auto",cursor:"pointer"}),Bh(t,e),t.dataset.velaScreenshot="1";let n=r.createElement("span");n.className="vela-attr-symbol",n.setAttribute("aria-hidden","true"),n.innerHTML=Fw;let i=r.createElement("span");return i.className="vela-attr-wordmark",i.innerHTML=Vw,t.append(n,i),t}function Uc(r){if(!r||r==="transparent")return false;let e=/rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*,\s*([\d.]+)\s*\)/.exec(r);return e?parseFloat(e[1])>.001:true}function zw(r,e,t){let n=r.borderTopLeftRadius,i=parseFloat(n)||0,o=n.endsWith("%")?i/100*Math.min(e,t):i;return Math.max(0,Math.min(o,Math.min(e,t)/2))}function Hh(r,e,t,n,i,o){r.beginPath(),o>0&&typeof r.roundRect=="function"?r.roundRect(e,t,n,i,o):r.rect(e,t,n,i);}function YM(r){try{let e=r.ownerDocument.createElement("canvas");e.width=1,e.height=1;let t=e.getContext("2d");return t?(t.drawImage(r,0,0,1,1),e.toDataURL(),!0):!1}catch{return false}}function Yc(r,e,t){let n=e.ownerDocument.defaultView;if(!n)return;r.save(),r.scale(t.dpr,t.dpr);let i=(c,d,u)=>{let h=c.textContent?.replace(/\s+/g," ").trim();if(!h)return;let p=c.ownerDocument.createRange();p.selectNodeContents(c);let m=p.getBoundingClientRect();m.width<=0||m.height<=0||(r.globalAlpha=u,r.fillStyle=d.color,r.font=`${d.fontStyle} ${d.fontWeight} ${d.fontSize} ${d.fontFamily}`,r.textBaseline="middle",r.textAlign="left",r.fillText(h,m.left-t.left,m.top-t.top+m.height/2));},o=(c,d,u)=>{if(!c.complete||c.naturalWidth<=0||!YM(c))return;let h=c.getBoundingClientRect();if(h.width<=0||h.height<=0)return;let p=h.left-t.left,m=h.top-t.top;r.save(),r.globalAlpha=u,Hh(r,p,m,h.width,h.height,zw(d,h.width,h.height)),r.clip(),r.drawImage(c,p,m,h.width,h.height),r.restore();},s=(c,d)=>{for(let u of c.children){if(u.hasAttribute("transform"))continue;let h=u.tagName.toLowerCase();if(h==="g"){s(u,d);continue}let p=b=>parseFloat(u.getAttribute(b)??"0")||0,m=null;if(h==="path"){let b=u.getAttribute("d");b&&(m=new Path2D(b));}else if(h==="circle")m=new Path2D,m.arc(p("cx"),p("cy"),p("r"),0,Math.PI*2);else if(h==="ellipse")m=new Path2D,m.ellipse(p("cx"),p("cy"),p("rx"),p("ry"),0,0,Math.PI*2);else if(h==="rect")m=new Path2D,m.rect(p("x"),p("y"),p("width"),p("height"));else if(h==="line")m=new Path2D,m.moveTo(p("x1"),p("y1")),m.lineTo(p("x2"),p("y2"));else if(h==="polyline"||h==="polygon"){let b=(u.getAttribute("points")??"").trim().split(/[\s,]+/).map(Number);if(b.length<4||b.some(Number.isNaN))continue;m=new Path2D,m.moveTo(b[0],b[1]);for(let y=2;y+1<b.length;y+=2)m.lineTo(b[y],b[y+1]);h==="polygon"&&m.closePath();}if(!m)continue;let f=n.getComputedStyle(u);f.fill&&f.fill!=="none"&&Uc(f.fill)&&(r.globalAlpha=d*(parseFloat(f.fillOpacity)||1),r.fillStyle=f.fill,r.fill(m));let g=parseFloat(f.strokeWidth)||0;f.stroke&&f.stroke!=="none"&&Uc(f.stroke)&&g>0&&(r.globalAlpha=d*(parseFloat(f.strokeOpacity)||1),r.strokeStyle=f.stroke,r.lineWidth=g,(f.strokeLinecap==="round"||f.strokeLinecap==="square"||f.strokeLinecap==="butt")&&(r.lineCap=f.strokeLinecap),(f.strokeLinejoin==="round"||f.strokeLinejoin==="bevel"||f.strokeLinejoin==="miter")&&(r.lineJoin=f.strokeLinejoin),r.stroke(m));}},a=(c,d)=>{let u=c.getBoundingClientRect();if(u.width<=0||u.height<=0)return;let h=n.getComputedStyle(c);if(h.display==="none"||h.visibility==="hidden")return;let p=d*(parseFloat(h.opacity)||1);if(p<=.001)return;let m=c.viewBox.baseVal,f=m&&m.width>0?m.width:u.width,g=m&&m.height>0?m.height:u.height;r.save(),r.translate(u.left-t.left,u.top-t.top),r.scale(u.width/f,u.height/g),m&&r.translate(-m.x,-m.y),s(c,p),r.restore();},l=(c,d)=>{let u=n.getComputedStyle(c);if(u.display==="none"||u.visibility==="hidden")return;let h=d*(parseFloat(u.opacity)||1);if(h<=.001)return;let p=c.getBoundingClientRect();if(p.width>0&&p.height>0){let m=p.left-t.left,f=p.top-t.top,g=zw(u,p.width,p.height);Uc(u.backgroundColor)&&(r.globalAlpha=h,r.fillStyle=u.backgroundColor,Hh(r,m,f,p.width,p.height,g),r.fill());let b=parseFloat(u.borderTopWidth)||0;b>0&&u.borderTopStyle!=="none"&&Uc(u.borderTopColor)&&(r.globalAlpha=h,r.strokeStyle=u.borderTopColor,r.lineWidth=b,Hh(r,m+b/2,f+b/2,p.width-b,p.height-b,Math.max(0,g-b/2)),r.stroke());}for(let m of c.childNodes)m.nodeType===3?i(m,u,h):m instanceof n.HTMLImageElement?o(m,n.getComputedStyle(m),h):m instanceof n.SVGSVGElement?a(m,h):m instanceof n.HTMLElement&&l(m,h);};e instanceof n.HTMLElement&&l(e,1),r.restore();}function $w(r,e,t,n,i){let o=Math.max(0,e),s=Math.min(r.length-1,t);if(o>s)return null;let a=1/0,l=-1/0;for(let v=o;v<=s;v+=1){let S=r[v];S.volume!=null&&S.volume>0&&(S.low<a&&(a=S.low),S.high>l&&(l=S.high));}if(!Number.isFinite(a))return null;let c=l>a?Math.max(1,Math.round(n)):1,d=l>a?(l-a)/c:1,u=Array.from({length:c},(v,S)=>({price:a+S*d,up:0,down:0}));for(let v=o;v<=s;v+=1){let S=r[v],P=S.volume;if(!(P!=null&&P>0))continue;let T=S.close>=S.open?"up":"down",E=S.high-S.low;if(E<=0){let w=zh(Math.floor((S.low-a)/d),c);u[w][T]+=P;continue}let x=zh(Math.floor((S.low-a)/d),c),L=zh(Math.floor((S.high-a)/d-1e-9),c);for(let w=x;w<=L;w+=1){let M=a+w*d,k=Math.min(S.high,M+d)-Math.max(S.low,M);k>0&&(u[w][T]+=P*k/E);}}let h=0,p=0,m=0;for(let v=0;v<c;v+=1){let S=u[v].up+u[v].down;h+=S,S>p&&(p=S,m=v);}if(p<=0)return null;let f=h*Math.min(1,Math.max(0,i)),g=m,b=m,y=p;for(;y<f&&(g>0||b<c-1);){let v=g>0?u[g-1].up+u[g-1].down:-1,S=b<c-1?u[b+1].up+u[b+1].down:-1;S>v?(b+=1,y+=S):(g-=1,y+=v);}return {rows:u,rowH:d,min:a,maxTotal:p,poc:m,vaFrom:g,vaTo:b}}function zh(r,e){return r<0?0:r>=e?e-1:r}function Ww(r,e,t,n){let{rows:i,rowH:o,maxTotal:s,poc:a,vaFrom:l,vaTo:c}=e,{rightX:d,maxW:u,yOf:h}=t;if(!(s<=0||u<=0)){for(let p=0;p<i.length;p+=1){let m=i[p],f=m.up+m.down;if(f<=0)continue;let g=h(m.price+o),b=Math.max(1,h(m.price)-g-1),y=f/s*u,v=m.up/f*y;r.globalAlpha=p>=l&&p<=c?.62:.28,v>0&&(r.fillStyle=n.upColor,r.fillRect(d-y,g,v,b)),y-v>0&&(r.fillStyle=n.downColor,r.fillRect(d-y+v,g,y-v,b));}if(n.showPoc){let p=i[a],m=h(p.price+o),f=Math.max(1,h(p.price)-m-1);r.globalAlpha=.9,r.strokeStyle=n.pocColor,r.lineWidth=1,r.strokeRect(d-u+.5,m+.5,u-1,f);}r.globalAlpha=1;}}var Kc=class{constructor(){this.canvas=null;this.ctx=null;this.memoKey="";this.memo=null;}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}destroy(){this.canvas=null,this.ctx=null,this.memoKey="",this.memo=null;}render(e){let t=this.ctx,n=this.canvas;if(!t||!n)return;let{bars:i,data:o,visible:s,coords:a,scale:l,bounds:c,theme:d}=e,u=a.dpr;if(t.setTransform(u,0,0,u,0,0),t.clearRect(0,0,n.width/u,n.height/u),!o||!s||i.length===0||c.height<=0)return;let h=a.visibleLogicalRange(),p=Math.max(0,Math.floor(h.from)),m=Math.min(i.length-1,Math.ceil(h.to));if(p>m)return;let f=i[m],g=`${p}:${m}:${i.length}:${f.high}:${f.low}:${f.close}:${f.volume??0}:${o.rows}:${o.valueAreaFrac}`;g!==this.memoKey&&(this.memoKey=g,this.memo=$w(i,p,m,o.rows,o.valueAreaFrac));let b=this.memo;b&&(t.save(),t.beginPath(),t.rect(0,c.top,a.width,c.height),t.clip(),Ww(t,b,{rightX:a.width,maxW:a.width*o.widthFrac,yOf:y=>a.priceToY(y,l,c)},{upColor:o.upColor,downColor:o.downColor,showPoc:o.showPoc,pocColor:d.textColor}),t.restore());}};var Be="price",ZM=8,JM="rgba(0,0,0,0)",Xc=64,QM=56,Gw=26,Vi=22,vs=26,$h=24,ek=5,tk="0 2px 8px rgba(0,0,0,0.4)",nk=12,jw=12,Uw=Xc+jw,Wh=Vi+14,rk=120,ik=2,Yw=6,ok=70,Fi=80,sk=110,ak=130,lk=.02,ck=.004,dk=.2,uk=4,ys=class{constructor(e){this.capabilities=Qv;this.surfaceBackground=Gt.background;this.surfaceTextColor=Gt.textColor;this.toolbarGutter=0;this.mountContainer=null;this.userDrawings=null;this.backdropRenderer=new Wc;this.volumeRenderer=new Gc;this.extLayers=[];this.layerOrderSig="";this.attributionEl=null;this.attributionEnabled=true;this.attributionHtml=null;this.vpvrRenderer=new Kc;this.resizeObserver=null;this.dprMedia=null;this.plotDeviceSize=null;this.coords=new pc;this.scene=new yc;this.backendMode="auto";this.glowAmount=0;this.chrome=new Pc;this.indicatorSlices=new zc;this.labelTooltip=null;this.crosshairLayer=new Mc;this.countdownTimer=null;this.symbolPicker=null;this.indicatorTitlesOn=true;this.indicatorValuesOn=true;this.legendActionsProvider=null;this.legendCalloutsProvider=null;this.legendOverviewAction=null;this.keyboard=null;this.keyboardEnabled=true;this.historyChordsEnabled=true;this.liveRegion=null;this.animZoom=true;this.animPan=true;this.animLiveBarMs=0;this.animLiveBarOnMs=90;this.candleUp=z;this.candleDown=W;this.introStyle="settle";this.introPlayed=false;this.introRaf=null;this.loadingEl=null;this.modelAlpha=1;this.targetBarSpacing=0;this.zoomAnchorLogical=0;this.zoomAnchorX=0;this.zoomAnchorMode="right";this.panVelocity=0;this.bars=[];this.didInitialFit=false;this.paintedData=false;this.skeletonClockMs=0;this.candleBodyAlpha=1;this.candleStructureAlpha=1;this.lastPointer=null;this.volumeActive=false;this.volumeHidden=false;this.vpvrActive=false;this.vpvrHidden=false;this.liveEaseTime=0;this.liveEaseHigh=0;this.liveEaseLow=0;this.liveEaseClose=0;this.axisDragEnabled=true;this.scaleDragHolder=null;this.scaleDragHeight=0;this.scaleDragStart=null;this.paneResizeEnabled=true;this.resizeAbove=null;this.resizeBelow=null;this.resizeSplitStart=null;this.hoverSeparatorY=null;this.maximizedPaneId=null;this.rightAxisW=Xc;this.paneControls=null;this.axisScaleButtons=null;this.paneActionCbs=new Set;this.hoverLogical=null;this.settingsDialog=null;this.hiddenSettings=[];this.dialogHost=null;this.settingsButton=null;this.settingsEnabled=false;this.scrollButton=null;this.pointerNearScrollBtn=false;this.scrollTargetRO=null;this.scrollBtnBottomPx=Wh;this.scrollBtnRightPx=Uw;this.layoutMode="desktop";this.viewportCbs=new Set;this.crosshairCbs=new Set;this.chartTypeSettingsCbs=new Set;this.configChangedCbs=new Set;this.themeSelectCbs=new Set;this.factoryConfig=null;this.hostSettingsSections=[];this.clickCbs=new Set;this.axisLongPressCbs=new Set;this.inputChangeCbs=new Set;this.removeIndicatorCbs=new Set;this.toggleVisibleCbs=new Set;this.moveIndicatorCbs=new Set;this.priceStyleCbs=new Set;this.name="native";this.features=["logScale","currentPriceLine","priceLabel","countdown","upColor","downColor","glow","animZoom","animPan","animLiveBar","intro","zoomAnchor","axisDrag","paneResize","candleZOrder","candleVisible","seriesOrder","highlights","sessionZones","gridlines","axisLabels","scaleMode","invertScale","paneScales","autoScale","timezone","keyboard","historyChords","priceStyle","priceBaseline","baselinePrice","settings","attribution","dialogHost","tradeMarkers","indicatorTitles","indicatorValues"];this.onScrollProximityMove=e=>{if(!this.scrollButton||!this.plot)return;let t=this.plot.getBoundingClientRect(),n=t.width-this.scrollBtnRightPx-vs/2,i=t.height-this.scrollBtnBottomPx-vs/2,o=Math.hypot(e.clientX-t.left-n,e.clientY-t.top-i)<=rk;o!==this.pointerNearScrollBtn&&(this.pointerNearScrollBtn=o,this.updateScrollToRealtimeButton());};this.onScrollProximityLeave=()=>{this.pointerNearScrollBtn&&(this.pointerNearScrollBtn=false,this.updateScrollToRealtimeButton());};this.onDprChange=()=>{this.watchDpr(),this.resize();};this.externalCross=null;this.snapMode="off";e&&(this.scene.showPriceLine=e.currentPriceLine,this.scene.logScale=e.logScale,this.backendMode=e.nativeBackend,this.animZoom=e.animZoom,this.animPan=e.animPan,this.setLiveBarEase(Ms(e.animLiveBar)),this.glowAmount=e.glow,this.candleUp=e.upColor,this.candleDown=e.downColor,this.scene.priceStyle=e.priceStyle,this.scene.basePainting=Zu(e.priceStyle),this.scene.candleOverride=cc(e.priceStyle,this.scene.style.chartTypes)),this.theme=this.deriveTheme(Gt);}applyFeature(e,t){switch(e){case "logScale":if(t&&typeof t=="object"){let n=t;this.setPaneLog(n.pane??Be,!!n.value);return}this.scene.logScale=!!t;break;case "currentPriceLine":this.scene.showPriceLine=!!t;break;case "priceLabel":this.scene.showPriceLabel=!!t;break;case "countdown":this.scene.showCountdown=!!t,this.syncCountdownTimer();break;case "upColor":this.candleUp=String(t),this.theme&&(this.theme=this.deriveTheme(this.theme));break;case "downColor":this.candleDown=String(t),this.theme&&(this.theme=this.deriveTheme(this.theme));break;case "glow":this.glowAmount=Number(t)||0,this.backend&&"glow"in this.backend&&(this.backend.glow=this.glowAmount);break;case "animZoom":this.animZoom=!!t;return;case "animPan":this.animPan=!!t;return;case "animLiveBar":this.setLiveBarEase(Ms(t));return;case "intro":{let n=t===false||t==="none"||t==="off"||t==null?"":String(t);this.introStyle=n,n&&this.playIntro(n);return}case "zoomAnchor":this.zoomAnchorMode=t==="right"?"right":"cursor",this.input&&(this.input.rightEdgeZoom=this.zoomAnchorMode==="right");return;case "axisDrag":this.axisDragEnabled=!!t,this.input&&(this.input.axisDrag=this.axisDragEnabled);return;case "paneResize":this.paneResizeEnabled=!!t,this.input&&(this.input.paneResize=this.paneResizeEnabled);return;case "candleZOrder":this.scene.candleZ=Number(t)||0;break;case "candleVisible":this.scene.candlesHidden=t===false;break;case "seriesOrder":this.applySeriesOrder(t);break;case "highlights":this.scene.highlights=fk(t);break;case "sessionZones":this.scene.sessionZones=gk(t);break;case "gridlines":this.scene.showGrid=!!t;break;case "axisLabels":this.scene.showAxisLabels=!!t;break;case "scaleMode":if(t&&typeof t=="object"){let n=t;this.setPaneScaleMode(n.pane??Be,Kw(n.mode));return}this.scene.scaleMode=Kw(t);break;case "invertScale":if(t&&typeof t=="object"){let n=t;this.setPaneInvert(n.pane??Be,!!n.value);return}this.scene.invertScale=!!t;break;case "autoScale":for(let n of this.scene.panes.values())n.manualScale=t?null:{...n.scale};break;case "timezone":this.scene.timezone=typeof t=="string"&&t?t:"UTC";break;case "priceStyle":this.setPriceStyle(bk(t)?t:"candles");break;case "priceBaseline":this.scene.baselineValue=t==null?null:Number(t);break;case "tradeMarkers":this.scene.tradeMarkers=Cy(this.scene.tradeMarkers,t);break;case "keyboard":this.setKeyboardEnabled(!!t);return;case "historyChords":this.historyChordsEnabled=!!t,this.userDrawings&&(this.userDrawings.historyChords=this.historyChordsEnabled);return;case "settings":this.setSettingsEnabled(!!t);return;case "indicatorTitles":this.indicatorTitlesOn=t!==false,this.inputsUI?.setTitlesVisible(this.indicatorTitlesOn);return;case "indicatorValues":this.indicatorValuesOn=t!==false,this.inputsUI?.setValuesVisible(this.indicatorValuesOn);return;case "attribution":this.attributionHtml=typeof t=="string"&&t.trim()?t:null,this.attributionEnabled=this.attributionHtml!==null||!!t,this.rebuildAttribution();return;case "dialogHost":this.dialogHost=t instanceof HTMLElement?t:null,this.settingsDialog?.close(),this.settingsDialog=null,this.inputsUI?.setDialogHost(this.dialogHost);return;default:return}this.scheduler?.invalidate(4);}readFeature(e){switch(e){case "logScale":return this.scene.logScale;case "currentPriceLine":return this.scene.showPriceLine;case "priceLabel":return this.scene.showPriceLabel;case "countdown":return this.scene.showCountdown;case "upColor":return this.candleUp;case "downColor":return this.candleDown;case "glow":return this.glowAmount;case "animZoom":return this.animZoom;case "animPan":return this.animPan;case "animLiveBar":return this.animLiveBarMs;case "intro":return this.introStyle;case "zoomAnchor":return this.zoomAnchorMode;case "axisDrag":return this.input?this.input.axisDrag:this.axisDragEnabled;case "paneResize":return this.input?this.input.paneResize:this.paneResizeEnabled;case "candleZOrder":return this.scene.candleZ;case "candleVisible":return !this.scene.candlesHidden;case "seriesOrder":return this.scene.indicatorZOrder();case "highlights":return this.scene.highlights;case "sessionZones":return this.scene.sessionZones;case "gridlines":return this.scene.showGrid;case "axisLabels":return this.scene.showAxisLabels;case "scaleMode":return this.scene.scaleMode;case "invertScale":return this.scene.invertScale;case "paneScales":return this.paneScaleInfos();case "autoScale":{let t=this.scene.orderedPanes().find(n=>n.kind==="price");return t?t.manualScale==null:true}case "timezone":return this.scene.timezone;case "priceStyle":return this.scene.priceStyle;case "priceBaseline":return this.scene.baselineValue;case "baselinePrice":{let t=this.scene.panes.get(Be);return t?this.scene.baselinePriceFor(t.scale):this.scene.baselineValue}case "tradeMarkers":return {...this.scene.tradeMarkers,colors:{...this.scene.tradeMarkers.colors}};case "keyboard":return this.keyboardEnabled;case "historyChords":return this.historyChordsEnabled;case "settings":return this.settingsEnabled;case "indicatorTitles":return this.indicatorTitlesOn;case "indicatorValues":return this.indicatorValuesOn;case "attribution":return this.attributionHtml??this.attributionEnabled;case "dialogHost":return this.dialogHost??void 0;default:return}}setNativeData(e,t){e==="volume"?(this.scene.volumeLayer=t??null,this.scheduler?.invalidate(3)):e==="vpvr"?(this.scene.vpvrLayer=t??null,this.scheduler?.invalidate(3)):e.endsWith("-pending")?(this.scene.nativePending.set(e.slice(0,-8),t??[]),this.scheduler?.invalidate(3)):(this.scene.nativeData.set(e,t),this.scheduler?.invalidate(3));}setIndicatorStatus(e,t){this.inputsUI.setStatus(e.id,t);}setLoading(e){if(!e||!this.wrapper){this.loadingEl?.remove(),this.loadingEl=null;return}if(this.loadingEl)return;let t=this.wrapper.ownerDocument,n=t.createElement("div");n.className="vela-loading",Object.assign(n.style,{position:"absolute",inset:"0",display:"flex",alignItems:"center",justifyContent:"center",gap:"7px",pointerEvents:"none"});for(let i=0;i<3;i+=1){let o=t.createElement("span");Object.assign(o.style,{width:"7px",height:"7px",borderRadius:"50%",background:this.chromeTheme().textColor,opacity:"0.15"}),o.animate([{opacity:.12},{opacity:.55}],{duration:800,iterations:1/0,direction:"alternate",easing:"ease-in-out",delay:-i*260}),n.appendChild(o);}this.wrapper.appendChild(n),this.loadingEl=n;}setPricePrecision(e){let t=typeof e=="number"&&e>0?e:void 0;t!==this.scene.priceMintick&&(this.scene.priceMintick=t,this.scheduler?.invalidate(4));}getConfig(){let e=this.scene.style,t=Object.fromEntries(Object.entries(e.chartTypes).map(([i,o])=>[i,{...o}])),n=this.theme;return {version:qu,chartTypes:t,layout:{background:n.background,textColor:n.textColor,fontFamily:n.fontFamily,fontSize:e.fontSize},grid:{vertLines:{visible:e.gridVert.visible,color:e.gridVert.color??n.gridColor},horzLines:{visible:e.gridHorz.visible,color:e.gridHorz.color??n.gridColor}},crosshair:{color:e.crosshair.color??n.textColor,width:e.crosshair.width,style:e.crosshair.style,opacity:e.crosshair.opacity,labelBackground:e.crosshair.labelBackground??n.textColor},priceScale:{mode:this.scene.scaleMode,log:this.scene.logScale,invert:this.scene.invertScale,borderColor:e.borderColor??n.borderColor,labelsVisible:this.scene.showAxisLabels,currentPriceLine:this.scene.showPriceLine,priceLabel:this.scene.showPriceLabel,countdown:this.scene.showCountdown,animateLastPrice:this.animLiveBarMs>0},panes:{separatorColor:e.separatorColor??n.borderColor},trades:{visible:this.scene.tradeMarkers.visible,labels:this.scene.tradeMarkers.labels,qty:this.scene.tradeMarkers.qty,longColor:this.scene.tradeMarkers.colors.long,shortColor:this.scene.tradeMarkers.colors.short,exitColor:this.scene.tradeMarkers.colors.exit},timeScale:{timezone:this.scene.timezone},candles:{upColor:this.candleUp,downColor:this.candleDown,bodyVisible:e.candle.bodyVisible,borderVisible:e.candle.borderVisible,borderUpColor:e.candle.borderUpColor??this.candleUp,borderDownColor:e.candle.borderDownColor??this.candleDown,wickVisible:e.candle.wickVisible,wickUpColor:e.candle.wickUpColor??this.candleUp,wickDownColor:e.candle.wickDownColor??this.candleDown},bars:{upColor:e.bars.upColor??this.candleUp,downColor:e.bars.downColor??this.candleDown},line:{color:e.line.color??this.candleUp,width:e.line.width},stacking:{candles:this.scene.candleZ,series:Object.fromEntries(this.scene.indicatorZOrder().map(({id:i,z:o})=>[i,o]))},area:(()=>{let i=e.area.lineColor??this.candleUp;return {lineColor:i,width:e.area.width,topColor:e.area.topColor??i,bottomColor:e.area.bottomColor??JM}})(),baseline:(()=>{let i=e.baseline.topLineColor??Si,o=e.baseline.bottomLineColor??Ci;return {topLineColor:i,bottomLineColor:o,topFillColor:e.baseline.topFillColor??q(i,xn),topFillColor2:e.baseline.topFillColor2??q(i,Sn),bottomFillColor:e.baseline.bottomFillColor??q(o,xn),bottomFillColor2:e.baseline.bottomFillColor2??q(o,Sn),width:e.baseline.width,baselineLevel:e.baseline.baselineLevel}})(),series:{style:this.scene.priceStyle,baseline:this.scene.baselineValue,spacing:this.coords.spacingScale},sessions:{premarketColor:e.sessions.premarketColor,postmarketColor:e.sessions.postmarketColor,extendedColor:e.sessions.extendedColor}}}applyConfig(e){let t=oy(this.getConfig(),e),n=this.scene.style;for(let[d,u]of Object.entries(t.chartTypes))if(JSON.stringify(n.chartTypes[d])!==JSON.stringify(u)){this.scene.nativeData.set(`${d}-settings`,{...u});for(let h of this.chartTypeSettingsCbs)h(d,{...u});}n.chartTypes=Object.fromEntries(Object.entries(t.chartTypes).map(([d,u])=>[d,{...u}]));let i=e&&typeof e=="object"?e.layout:void 0,o=i&&typeof i=="object"?i.textColor:void 0,s=typeof o=="string"&&o.trim().length>0,a=this.theme,l={textColor:t.layout.textColor,gridColor:a.gridColor,borderColor:a.borderColor};if(!s&&lt(t.layout.textColor)===lt(t.layout.background)){let d=lt(t.layout.background)?Gt:oo;l={textColor:d.textColor,gridColor:d.gridColor,borderColor:d.borderColor};}this.theme={...this.theme,background:t.layout.background,textColor:l.textColor,gridColor:l.gridColor,borderColor:l.borderColor,fontFamily:t.layout.fontFamily},n.fontSize=t.layout.fontSize;let c=(d,u,h)=>d===null&&u===h?null:u;n.gridVert={visible:t.grid.vertLines.visible,color:c(n.gridVert.color,t.grid.vertLines.color,a.gridColor)},n.gridHorz={visible:t.grid.horzLines.visible,color:c(n.gridHorz.color,t.grid.horzLines.color,a.gridColor)},n.crosshair={color:t.crosshair.color,width:t.crosshair.width,style:t.crosshair.style,opacity:t.crosshair.opacity,labelBackground:t.crosshair.labelBackground},this.scene.scaleMode=t.priceScale.mode,this.scene.logScale=t.priceScale.log,this.scene.invertScale=t.priceScale.invert,n.borderColor=c(n.borderColor,t.priceScale.borderColor,a.borderColor),this.scene.showAxisLabels=t.priceScale.labelsVisible,this.scene.showPriceLine=t.priceScale.currentPriceLine,this.scene.showPriceLabel=t.priceScale.priceLabel,this.scene.showCountdown=t.priceScale.countdown,this.syncCountdownTimer(),this.animLiveBarMs=t.priceScale.animateLastPrice?this.animLiveBarOnMs:0,n.separatorColor=c(n.separatorColor,t.panes.separatorColor,a.borderColor),this.scene.tradeMarkers={visible:t.trades.visible,labels:t.trades.labels,qty:t.trades.qty,colors:{long:t.trades.longColor,short:t.trades.shortColor,exit:t.trades.exitColor}},this.scene.timezone=t.timeScale.timezone,this.candleUp=t.candles.upColor,this.candleDown=t.candles.downColor,n.candle={bodyVisible:t.candles.bodyVisible,borderVisible:t.candles.borderVisible,borderUpColor:t.candles.borderUpColor,borderDownColor:t.candles.borderDownColor,wickVisible:t.candles.wickVisible,wickUpColor:t.candles.wickUpColor,wickDownColor:t.candles.wickDownColor},this.scene.candleZ=t.stacking.candles;for(let[d,u]of Object.entries(t.stacking.series))this.scene.setIndicatorZ(d,u);n.bars={upColor:t.bars.upColor,downColor:t.bars.downColor},n.line={color:t.line.color,width:t.line.width},n.area={lineColor:t.area.lineColor,width:t.area.width,topColor:t.area.topColor,bottomColor:t.area.bottomColor},n.baseline={topLineColor:t.baseline.topLineColor,bottomLineColor:t.baseline.bottomLineColor,topFillColor:t.baseline.topFillColor,topFillColor2:t.baseline.topFillColor2,bottomFillColor:t.baseline.bottomFillColor,bottomFillColor2:t.baseline.bottomFillColor2,width:t.baseline.width,baselineLevel:t.baseline.baselineLevel},n.sessions={premarketColor:t.sessions.premarketColor,postmarketColor:t.sessions.postmarketColor,extendedColor:t.sessions.extendedColor},this.setPriceStyle(t.series.style),this.scene.candleOverride=cc(this.scene.priceStyle,n.chartTypes),this.scene.baselineValue=t.series.baseline,this.coords.setPitchScale(t.series.spacing),this.coords.setViewport(this.clampViewport(this.coords.getViewport().barSpacing,this.coords.getViewport().rightOffset)),this.targetBarSpacing=this.coords.getViewport().barSpacing,this.theme=this.deriveTheme(this.theme),this.wrapper&&(Ae(this.wrapper,this.chromeTheme()),this.applyBackground()),this.inputsUI?.setTheme(this.theme),this.paneControls?.setTheme(this.theme),this.axisScaleButtons?.setTheme(this.theme),this.userDrawings?.setTheme(this.chromeTheme()),this.refreshScrollButtonTheme(),this.refreshAttributionColor(),this.scheduler?.invalidate(4);for(let d of this.configChangedCbs)d();}applySeriesOrder(e){if(!e||typeof e!="object")return;let t=e;typeof t.id=="string"&&(typeof t.z=="number"?this.scene.setIndicatorZ(t.id,t.z):t.to==="front"?this.scene.bringIndicatorToFront(t.id):t.to==="back"&&this.scene.sendIndicatorToBack(t.id));}setSettingsEnabled(e){this.settingsEnabled=e,e?(this.plot&&!this.settingsButton&&(this.settingsButton=this.makeSettingsButton(),this.plot.appendChild(this.settingsButton)),this.settingsButton&&(this.settingsButton.style.display="flex"),this.plot&&!this.settingsDialog&&(this.settingsDialog=new us(this.dialogHost??this.plot,this.theme))):(this.settingsButton?.style.setProperty("display","none"),this.settingsDialog?.close());}makeSettingsButton(){let e=document.createElement("button");return e.type="button",e.title="Chart settings",e.innerHTML=ye("gear",14),Object.assign(e.style,{position:"absolute",bottom:`${Vi+10}px`,right:`${Xc+10}px`,zIndex:"6",width:"26px",height:"26px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:"50%",border:`1px solid ${this.theme.borderColor}`,background:this.theme.background,color:this.theme.textColor,fontSize:"14px",lineHeight:"1",opacity:"0.75",pointerEvents:"auto",padding:"0"}),e.addEventListener("mouseenter",()=>e.style.opacity="1"),e.addEventListener("mouseleave",()=>e.style.opacity="0.75"),e.addEventListener("click",()=>this.toggleSettingsDialog()),e}openSettingsDialog(e){!this.settingsDialog&&this.plot&&(this.settingsDialog=new us(this.dialogHost??this.plot,this.theme),this.settingsDialog.setLayoutMode(this.layoutMode)),this.toggleSettingsDialog(e);}syncThemeControl(){this.settingsDialog?.setThemeControl(lt(this.surfaceBackground)?"dark":"light",e=>{for(let t of this.themeSelectCbs)t(e);});}toggleSettingsDialog(e){if(this.settingsDialog){if(e!==void 0&&this.settingsDialog.isOpen()){this.settingsDialog.showSection(e);return}this.settingsDialog.setTheme(this.theme),this.settingsDialog.setHostSections(this.hostSettingsSections),this.settingsDialog.setHiddenSettings(this.hiddenSettings),this.syncThemeControl(),this.settingsDialog.toggle(this.getConfig(),t=>this.applyConfig(t),t=>this.applyConfig(t),()=>{this.factoryConfig&&this.applyConfig(iy(this.factoryConfig)),this.settingsDialog?.close(),this.openSettingsDialog();},e);}}closeDialogs(){this.inputsUI?.closeOpenDialog(),this.settingsDialog?.close();}makeScrollToRealtimeButton(){let e=document.createElement("button");return e.type="button",e.title="Scroll to most recent bar (Alt+Shift+\u2192)",e.setAttribute("aria-label","Scroll to most recent bar"),e.innerHTML=this.scrollButtonIcon(),Object.assign(e.style,{position:"absolute",bottom:`${Wh}px`,right:`${Uw}px`,zIndex:"6",width:`${vs}px`,height:`${vs}px`,boxSizing:"border-box",display:"none",alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:`${ek}px`,border:`1px solid ${this.theme.borderColor}`,boxShadow:tk,background:this.scrollButtonSurface(),color:this.theme.textColor,lineHeight:"0",opacity:"0.85",pointerEvents:"auto",padding:"0"}),e.addEventListener("mouseenter",()=>e.style.opacity="1"),e.addEventListener("mouseleave",()=>e.style.opacity="0.85"),e.addEventListener("click",()=>this.scrollToRealtime()),e}scrollButtonIcon(){return ye("chevrons-right",nk)}scrollButtonSurface(){return q(this.theme.background,.5)}refreshScrollButtonTheme(){this.scrollButton&&(this.scrollButton.style.background=this.scrollButtonSurface(),this.scrollButton.style.color=this.theme.textColor,this.scrollButton.style.borderColor=this.theme.borderColor);}updateScrollToRealtimeButton(){let e=this.scrollButton;if(!e)return;let t=this.coords.barCount>0&&this.coords.getViewport().rightOffset<0;if(this.layoutMode==="mobile"){e.style.display=t?"flex":"none";return}e.style.display=t&&this.pointerNearScrollBtn?"flex":"none";}scrollToRealtime(){this.coords.barCount!==0&&this.glideRightOffset(Yw);}glideRightOffset(e){let t=this.coords.getViewport();if(!this.animPan){this.applyViewport({barSpacing:t.barSpacing,rightOffset:e});return}this.panVelocity=0,this.targetBarSpacing=t.barSpacing,this.scrollTargetRO=e,this.animator.start();}screenshotCanvas(){if(!this.dataCanvas)return null;this.computeScales(),this.paintData();let e=document.createElement("canvas");e.width=this.dataCanvas.width,e.height=this.dataCanvas.height;let t=e.getContext("2d");if(!t)return null;t.fillStyle=this.theme.background,t.fillRect(0,0,e.width,e.height);let n=this.plot?.getBoundingClientRect(),i=n&&n.width>0?{left:n.left,top:n.top,dpr:e.width/n.width}:null,o=[...this.mountContainer?.querySelectorAll("[data-vela-screenshot]")??[]];if(i)for(let s of o)s.getAttribute("data-vela-screenshot")==="under"&&Yc(t,s,i);for(let s of [...this.canvasPile(),this.chromeCanvas,this.drawingsCanvas])s&&s.width>0&&s.height>0&&t.drawImage(s,0,0);if(i){for(let s of this.plot?.querySelectorAll("[data-vela-pane]")??[])Yc(t,s,i);for(let s of o)s.getAttribute("data-vela-screenshot")!=="under"&&Yc(t,s,i);}return e}screenshot(){return this.screenshotCanvas()?.toDataURL("image/png")??null}playIntro(e){this.introRaf!=null&&cancelAnimationFrame(this.introRaf),this.introRaf=null;let t=this.bars,n=t.length;if(n===0)return;this.computeScales();for(let a of this.scene.panes.values())a.scale={...a.scaleTarget};this.modelAlpha=0;let i=650,o=performance.now(),s=a=>{let l=Math.min(1,(a-o)/i);this.scene.bars=l>=1?t:t.map((c,d)=>this.revealCandle(c,d,l,n,e)),this.paintData(),l<1?this.introRaf=requestAnimationFrame(s):(this.scene.bars=t,this.fadeInModels());};this.introRaf=requestAnimationFrame(s);}fadeInModels(){let t=performance.now(),n=i=>{this.modelAlpha=Math.min(1,(i-t)/350),this.paintData(),this.modelAlpha<1?this.introRaf=requestAnimationFrame(n):(this.modelAlpha=1,this.introRaf=null);};this.introRaf=requestAnimationFrame(n);}revealCandle(e,t,n,i,o){let a=Math.max(0,Math.min(1,(n-t/Math.max(1,i-1)*.55)/.44999999999999996)),l;if(o==="settle"){let u=a-1;l=1+(1.70158+1)*u*u*u+1.70158*u*u;}else {let d=1-a;l=1-d*d*d;}let c=e.open;return {...e,high:c+(e.high-c)*l,low:c+(e.low-c)*l,close:c+(e.close-c)*l}}deriveTheme(e){return {...e,upColor:this.candleUp,downColor:this.candleDown}}chromeTheme(){return {...this.theme,background:this.surfaceBackground,textColor:this.surfaceTextColor,borderColor:lt(this.surfaceBackground)?Gt.borderColor:oo.borderColor}}axisSurface(){return {background:this.theme.background,textColor:this.theme.textColor}}mount(e,t){this.mountContainer=e,this.publishGutters(),this.theme=this.deriveTheme(t),this.surfaceBackground=t.background,this.surfaceTextColor=t.textColor,this.wrapper=document.createElement("div"),Object.assign(this.wrapper.style,{position:"relative",width:"100%",height:"100%",overflow:"hidden",cursor:"crosshair",userSelect:"none",webkitUserSelect:"none"}),Ae(this.wrapper,this.chromeTheme()),this.backdropCanvas=document.createElement("canvas"),Object.assign(this.backdropCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.volumeCanvas=document.createElement("canvas"),Object.assign(this.volumeCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.dataCanvas=this.createGeometryBackend(),this.vpvrCanvas=document.createElement("canvas"),Object.assign(this.vpvrCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.chromeCanvas=document.createElement("canvas"),Object.assign(this.chromeCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.drawingsCanvas=document.createElement("canvas"),Object.assign(this.drawingsCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.cursorCanvas=document.createElement("canvas"),Object.assign(this.cursorCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.overlayRoot=document.createElement("div"),Object.assign(this.overlayRoot.style,{position:"absolute",inset:"0",pointerEvents:"none"}),this.plot=document.createElement("div"),Object.assign(this.plot.style,{position:"absolute",top:"0",right:"0",bottom:"0",left:"0"}),this.extLayers=Vh().map(o=>{let s=document.createElement("canvas");return Object.assign(s.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),{def:o,instance:o.create(),canvas:s}});let n=this.extLayers.filter(o=>o.def.placement==="below-data").map(o=>o.canvas),i=this.extLayers.filter(o=>o.def.placement!=="below-data").map(o=>o.canvas);this.plot.append(this.backdropCanvas,...n,this.dataCanvas,this.volumeCanvas,this.vpvrCanvas,...i,this.chromeCanvas,this.drawingsCanvas,this.cursorCanvas,this.overlayRoot),this.layerOrderSig="",this.wrapper.appendChild(this.plot),this.factoryConfig=this.getConfig(),this.attributionEl=this.buildAttributionEl(),this.attributionEnabled||(this.attributionEl.style.display="none"),this.positionAttribution(),this.wrapper.appendChild(this.attributionEl),e.appendChild(this.wrapper),this.applyBackground(),this.backdropRenderer.mount(this.backdropCanvas),this.volumeRenderer.mount(this.volumeCanvas),this.vpvrRenderer.mount(this.vpvrCanvas);for(let o of this.extLayers)o.instance.mount(o.canvas);this.chrome.mount(this.chromeCanvas),this.crosshairLayer.mount(this.cursorCanvas),this.coords.setViewport(ns()),this.scene.ensurePane(Be,"price",0,3),this.scheduler=new mc(o=>this.renderFrame(o)),this.animator=new fc(o=>this.animTick(o)),this.targetBarSpacing=this.coords.getViewport().barSpacing,this.input=new gc({getCoords:()=>this.coords,apply:o=>this.applyViewport(o),zoomTo:(o,s,a)=>this.zoomTo(o,s,a),fling:o=>this.fling(o),onPointerMove:(o,s)=>this.handlePointerMove(o,s),onClick:o=>{this.userDrawings?.deselect(),this.handleClick(o);},onAxisLongPress:(o,s,a)=>{for(let l of this.axisLongPressCbs)l({axis:o,x:s,y:a});},beginPriceScale:(o,s)=>this.beginPriceScale(o,s),priceScaleBy:o=>this.priceScaleBy(o),beginPricePan:o=>this.beginPricePan(o),pricePanBy:o=>this.pricePanBy(o),resetPriceScale:(o,s)=>this.resetPriceScale(o,s),dataDblClick:(o,s)=>this.dataDblClick(o,s),paneSeparatorAt:o=>this.paneSeparatorAt(o),beginPaneResize:o=>this.beginPaneResize(o),paneResizeBy:o=>this.paneResizeBy(o),resetPaneSize:o=>this.resetPaneSize(o),resetView:()=>this.resetView(),drawingsClaim:(o,s)=>this.userDrawings?.claim(o,s)??false,drawingsMeasureStart:(o,s,a)=>this.userDrawings?.beginMeasureAt(o,s,a)??false,drawingsMarqueeStart:(o,s)=>this.userDrawings?.beginMarqueeAt(o,s)??false,drawingsDeleteAt:(o,s)=>this.userDrawings?.deleteAt(o,s,true)??false,drawingsCancelPlacement:()=>this.userDrawings?.cancelPlacement()??false,drawingsSnapMode:()=>this.snapMode,drawingsPointerDown:(o,s,a,l,c)=>this.userDrawings?.pointerDown(o,s,a,l,c),drawingsPointerMove:(o,s,a,l,c)=>this.userDrawings?.pointerMove(o,s,a,l,c),drawingsPointerUp:(o,s,a)=>this.userDrawings?.pointerUp(o,s,a),drawingsCursor:(o,s)=>this.userDrawings?.cursorAt(o,s)??null,drawingsDblClick:(o,s)=>this.userDrawings?.dblClick(o,s)??false,drawingsClearTransient:()=>this.userDrawings?.clearTransient()}),this.input.rightEdgeZoom=this.zoomAnchorMode==="right",this.input.axisDrag=this.axisDragEnabled,this.input.paneResize=this.paneResizeEnabled,this.input.attach(this.dataCanvas),this.settingsEnabled&&this.setSettingsEnabled(true),this.syncCountdownTimer(),this.scrollButton=this.makeScrollToRealtimeButton(),this.plot.appendChild(this.scrollButton),this.plot.addEventListener("pointermove",this.onScrollProximityMove),this.plot.addEventListener("pointerleave",this.onScrollProximityLeave),this.labelTooltip=new Lc(this.plot,{theme:()=>this.chromeTheme(),lookup:(o,s)=>this.indicatorSlices.labelTooltipAt(o,s)}),this.userDrawings=new Bc(this.wrapper,this.plot,this.drawingsCanvas,{projector:()=>this.drawingProjector(),dpr:()=>this.coords.dpr,theme:()=>this.theme,requestScaleUpdate:()=>this.scheduler.invalidate(3),seriesBoundaries:o=>this.scene.seriesBoundaries(o),priceZ:o=>o===Be?this.scene.candleZ:null,requestDataPaint:()=>this.scheduler.invalidate(3),seriesLook:()=>{let o=this.scene.style,s=Ti(o.candle,this.scene.candleOverride,this.theme.upColor,this.theme.downColor),a=o.bars.upColor??this.theme.upColor,l=o.bars.downColor??this.theme.downColor,c=this.scene.priceStyle;return {style:c,upColor:c==="bars"?a:s.up,downColor:c==="bars"?l:s.down,lineColor:c==="area"?o.area.lineColor??this.theme.upColor:o.line.color??this.theme.upColor}},chartBarMs:()=>this.coords.barInterval,snap:(o,s,a,l)=>this.snapToCandle(o,s,a,l),setSnapMode:o=>this.setSnapMode(o),setToolbarGutter:o=>this.setToolbarGutter(o)}),this.userDrawings.historyChords=this.historyChordsEnabled,this.layoutMode==="mobile"&&(this.mountContainer?.setAttribute("data-vela-layout",this.layoutMode),this.userDrawings.setLayoutMode(this.layoutMode),this.scrollButton&&(this.scrollButton.style.width=`${$h}px`,this.scrollButton.style.height=`${$h}px`)),this.keyboard=new bc({panByBars:o=>this.panByBars(o),zoomByStep:o=>this.zoomByStep(o),stepCrosshair:o=>this.stepCrosshair(o),jumpToEdge:o=>this.focusBar(o==="first"?0:this.coords.barCount-1),resetView:()=>this.resetView(),scrollToRealtime:()=>this.scrollToRealtime(),clearCrosshair:()=>this.handlePointerMove(null,null),preempt:o=>this.userDrawings?.handleKey(o)??false}),this.setKeyboardEnabled(this.keyboardEnabled),this.inputsUI=new ic(this.plot,t,o=>this.paneBoundsFor(o)),this.inputsUI.setLayoutMode(this.layoutMode),this.inputsUI.setTitlesVisible(this.indicatorTitlesOn),this.inputsUI.setValuesVisible(this.indicatorValuesOn),this.inputsUI.setDialogHost(this.dialogHost),this.inputsUI.setSymbolPicker(this.symbolPicker),this.inputsUI.setLegendActions(this.legendActionsProvider),this.inputsUI.setLegendCallouts(this.legendCalloutsProvider),this.inputsUI.setLegendOverviewAction(this.legendOverviewAction),this.inputsUI.setOnChange(o=>{for(let s of this.inputChangeCbs)s({indicatorId:o.indicatorId,key:o.key,value:o.value,...o.kind?{kind:o.kind}:{}});}),this.inputsUI.setOnRemove(o=>{for(let s of this.removeIndicatorCbs)s(o);}),this.inputsUI.setOnToggleVisible((o,s)=>{for(let a of this.toggleVisibleCbs)a(o,s);}),this.inputsUI.setMoveApi({panes:()=>this.scene.orderedPanes().map((o,s)=>({id:o.id,kind:o.kind,label:o.kind==="price"?"Main chart":this.paneMasterTitle(o.id)??`Pane ${s}`,top:o.bounds.top,height:o.bounds.height})),move:(o,s)=>{for(let a of this.moveIndicatorCbs)a(o,s);}}),this.paneControls=new oc(this.plot,t,{panes:()=>this.paneControlViews(),rightAxis:()=>this.rightAxisW,onMove:(o,s)=>this.movePaneLocal(o,s),onToggleCollapse:o=>{let s=this.scene.panes.get(o);if(!s)return;let a=!s.collapsed;s.collapsed=a,this.afterPaneLayoutChange(),this.emitPaneAction({type:"collapse",paneId:o,collapsed:a});},onToggleMaximize:o=>{let s=this.maximizedPaneId!==o;this.maximizedPaneId=s?o:null,this.afterPaneLayoutChange(),this.emitPaneAction({type:"maximize",paneId:o,maximized:s});}}),this.paneControls.setSuspended(this.layoutMode==="mobile"),this.axisScaleButtons=new sc(this.plot,t,{panes:()=>this.axisScaleViews(),rightAxis:()=>this.rightAxisW,onToggleAuto:o=>this.togglePaneAuto(o),onToggleLog:o=>{let s=this.scene.panes.get(o);s&&this.setPaneLog(o,!Mi(this.scene,s));}}),this.resizeObserver=new ResizeObserver(o=>{for(let s of o){if(s.target!==this.plot)continue;let a=s.devicePixelContentBoxSize?.[0];a&&(this.plotDeviceSize={width:a.inlineSize,height:a.blockSize});}this.resize();}),this.resizeObserver.observe(this.wrapper);try{this.resizeObserver.observe(this.plot,{box:"device-pixel-content-box"});}catch{}this.watchDpr(),this.syncSize();}makeDataCanvas(){let e=document.createElement("canvas");return Object.assign(e.style,{position:"absolute",inset:"0",width:"100%",height:"100%"}),e}createGeometryBackend(){if((this.backendMode==="auto"||this.backendMode==="webgl2")&&ey()){let n=this.makeDataCanvas(),i=new hc;if(i.glow=this.glowAmount,i.onNeedsRedraw=()=>this.scheduler?.invalidate(4),i.onContextFailed=()=>this.swapToCanvas2dFallback(),i.mount(n),i.ok)return this.backend=i,n;i.destroy();}let e=this.makeDataCanvas(),t=new rs;return t.mount(e),this.backend=t,e}swapToCanvas2dFallback(){if(this.backend.kind==="canvas2d")return;let e=this.dataCanvas;this.input?.detach(),this.backend.destroy();let t=this.makeDataCanvas(),n=new rs;n.mount(t),this.backend=n,e.replaceWith(t),this.dataCanvas=t,this.input?.attach(t),this.syncSize();}watchDpr(){typeof window.matchMedia=="function"&&(this.dprMedia?.removeEventListener("change",this.onDprChange),this.dprMedia=window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.dprMedia.addEventListener("change",this.onDprChange,{once:true}));}setTheme(e){this.theme=this.deriveTheme(e),this.surfaceBackground=e.background,this.surfaceTextColor=e.textColor,this.wrapper&&Ae(this.wrapper,this.chromeTheme()),this.applyBackground(),this.inputsUI.setTheme(e),this.paneControls?.setTheme(this.theme),this.axisScaleButtons?.setTheme(this.theme),this.settingsDialog?.refreshConfig(this.getConfig()),this.syncThemeControl(),this.settingsDialog?.setTheme(this.theme),this.settingsButton&&(this.settingsButton.style.background=this.theme.background,this.settingsButton.style.color=this.theme.textColor,this.settingsButton.style.borderColor=this.theme.borderColor),this.refreshScrollButtonTheme(),this.userDrawings?.setTheme(this.chromeTheme()),this.refreshAttributionColor(),this.scheduler.invalidate(4);}resize(){this.syncSize();}syncCountdownTimer(){this.scene.showCountdown?this.countdownTimer==null&&(this.countdownTimer=setInterval(()=>{this.scene.showCountdown&&this.scene.bars.length>0&&this.scheduler?.invalidate(2);},1e3)):this.countdownTimer!=null&&(clearInterval(this.countdownTimer),this.countdownTimer=null);}destroy(){this.introRaf!=null&&cancelAnimationFrame(this.introRaf),this.loadingEl?.remove(),this.loadingEl=null,this.countdownTimer!=null&&(clearInterval(this.countdownTimer),this.countdownTimer=null),this.scheduler?.destroy(),this.animator?.stop(),this.input?.detach(),this.keyboard?.detach(),this.keyboard=null,this.liveRegion=null,this.inputsUI?.destroy(),this.paneControls?.destroy(),this.axisScaleButtons?.destroy(),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.dprMedia?.removeEventListener("change",this.onDprChange),this.dprMedia=null,this.userDrawings?.destroy(),this.userDrawings=null,this.settingsDialog?.destroy(),this.settingsDialog=null,this.settingsButton?.remove(),this.settingsButton=null,this.plot?.removeEventListener("pointermove",this.onScrollProximityMove),this.plot?.removeEventListener("pointerleave",this.onScrollProximityLeave),this.labelTooltip?.destroy(),this.labelTooltip=null,this.scrollButton?.remove(),this.scrollButton=null;for(let e of this.extLayers)e.instance.destroy?.();this.extLayers=[],this.backdropRenderer.destroy(),this.volumeRenderer.destroy(),this.vpvrRenderer.destroy(),this.backend.destroy(),this.chrome.destroy(),this.crosshairLayer.destroy(),this.attributionEl?.remove(),this.attributionEl=null,this.mountContainer?.style.removeProperty("--vela-toolbar-gutter"),this.mountContainer?.style.removeProperty("--vela-scale-gutter"),this.mountContainer?.style.removeProperty("--vela-bottom-gutter"),this.mountContainer?.style.removeProperty("--vela-price-pane-top"),this.mountContainer?.style.removeProperty("--vela-price-pane-bottom"),this.mountContainer=null,this.wrapper?.remove();}setBars(e,t){this.introRaf!=null&&(cancelAnimationFrame(this.introRaf),this.introRaf=null,this.modelAlpha=1),this.liveEaseTime=0;let n=this.bars,i=n[0]?.time;this.bars=vk(e),this.scene.bars=this.bars,this.coords.setBars(this.bars.map(s=>s.time));for(let s of this.scene.indicators.values())this.refreshAnchorOffset(s);if(t?.preserveView===true&&i!=null&&this.bars.length>0){let s=this.bars[0].time,a=0;if(s!==i){let l=this.bars.findIndex(c=>c.time===i);if(l>0)a=l;else {let c=n.findIndex(d=>d.time===s);c>0&&(a=-c);}}a!==0&&(this.zoomAnchorLogical+=a,this.hoverLogical!=null&&(this.hoverLogical+=a));}let o=t?.preserveView===true&&this.didInitialFit;if(this.coords.width>0&&!o&&(this.didInitialFit?this.reframeKeepZoom():this.fitContent(),this.didInitialFit=true),!this.introPlayed&&this.bars.length>0&&(this.introPlayed=true,this.introStyle)){this.playIntro(this.introStyle);return}this.scheduler.invalidate(4);}updateBar(e){let t=this.bars.length,n=this.bars[t-1];if(n&&e.time===n.time)this.bars[t-1]=e,this.animLiveBarMs<=0||this.liveEaseTime!==e.time?this.syncLiveEase(e):this.animator.start();else if(!n||e.time>n.time)this.bars.push(e),this.syncLiveEase(e),this.coords.barInterval>0?this.coords.appendBar(e.time):this.coords.setBars(this.bars.map(i=>i.time));else return;this.scene.bars=this.bars,this.scheduler.invalidate(4);}setLiveBarEase(e){this.animLiveBarMs=e,e>0&&(this.animLiveBarOnMs=e);}syncLiveEase(e){this.liveEaseTime=e.time,this.liveEaseHigh=e.high,this.liveEaseLow=e.low,this.liveEaseClose=e.close;}easeLiveBar(e){let t=this.bars[this.bars.length-1];if(!t||this.liveEaseTime!==t.time)return false;let n=Math.max(1e-9,Math.abs(t.close)*1e-6),i=this.animLiveBarMs,o=vt(this.liveEaseHigh,t.high,e,i),s=vt(this.liveEaseLow,t.low,e,i),a=vt(this.liveEaseClose,t.close,e,i),l=Math.abs(o-t.high)>n||Math.abs(s-t.low)>n||Math.abs(a-t.close)>n;return this.liveEaseHigh=l?o:t.high,this.liveEaseLow=l?s:t.low,this.liveEaseClose=l?a:t.close,l}ensurePane(e){this.scene.ensurePane(e.id,e.kind,e.order,e.heightWeight??(e.kind==="price"?3:1)),this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}removePane(e){e!==Be&&(this.scene.removePane(e),this.maximizedPaneId===e&&(this.maximizedPaneId=null),this.refreshAxisWidth(),this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}setIndicatorPane(e,t,n){let i=this.scene.indicators.get(e.id);i&&(i.paneId=t,i.ownScale=n?.ownScale===true,i.ownScale||this.scene.dropIndicatorScale(e.id),this.inputsUI.setPane(e.id,t),this.refreshAnchorOffset(i),this.refreshAxisWidth(),this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}orderPanes(e){this.scene.orderPanes(e),this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}setPaneCollapsed(e,t){let n=this.scene.panes.get(e);!n||n.collapsed===t||(n.collapsed=t,this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}setPaneMaximized(e){e!==null&&!this.scene.panes.has(e)&&(e=null),this.maximizedPaneId=e,this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}onPaneAction(e){return this.paneActionCbs.add(e),()=>this.paneActionCbs.delete(e)}emitPaneAction(e){for(let t of this.paneActionCbs)t(e);}onMoveIndicator(e){return this.moveIndicatorCbs.add(e),()=>this.moveIndicatorCbs.delete(e)}maxOwnScaleColumns(){let e=0;for(let t of this.scene.panes.values()){let n=this.scene.ownScaleIndicatorsForPane(t.id).length;n>e&&(e=n);}return e}refreshAxisWidth(){let e=Xc+QM*this.maxOwnScaleColumns();return e===this.rightAxisW?false:(this.rightAxisW=e,this.publishGutters(),this.coords.width>0&&this.syncSize(),true)}refreshAnchorOffset(e){let t=e.anchorTime;if(t==null||this.bars.length===0){this.scene.setAnchorOffset(e.id,0);return}let n=this.bars[0].time;if(t===n){this.scene.setAnchorOffset(e.id,0);return}if(t<n){let a=hk(e,n);if(a==null){console.warn(`[vela] indicator "${e.id}" starts before the first bar with no series to align on \u2014 rendering unanchored`),this.scene.setAnchorOffset(e.id,0);return}this.scene.setAnchorOffset(e.id,-a);return}let i=0,o=this.bars.length-1,s=this.bars.length;for(;i<=o;){let a=i+o>>1;this.bars[a].time>=t?(s=a,o=a-1):i=a+1;}if(s>=this.bars.length||this.bars[s].time!==t){console.warn(`[vela] indicator "${e.id}" anchorTime matches no chart bar \u2014 rendering unanchored`),this.scene.setAnchorOffset(e.id,0);return}this.scene.setAnchorOffset(e.id,s);}mountIndicator(e){return this.scene.indicators.set(e.id,e),this.refreshAnchorOffset(e),e.native&&this.extLayers.some(t=>t.def.id===e.native.type)?this.scene.assignIndicatorZTop(e.id):this.scene.assignIndicatorZ(e.id),this.inputsUI.upsert(e.id,e.shorttitle??e.title,e.inputs,e.inputValues,e.paneId,{native:!!e.native,...e.props?{props:e.props,propValues:e.propValues??{}}:{}}),e.native?.type==="volume"?(this.volumeActive=true,this.volumeHidden=false):e.native?.type==="vpvr"&&(this.vpvrActive=true,this.vpvrHidden=false),e.ownScale&&this.refreshAxisWidth(),this.paneControls?.refresh(),this.scheduler.invalidate(4),{id:e.id}}updateIndicator(e,t){let n=this.scene.indicators.get(e.id);if(n){if(t.kind==="value"&&t.anchorTime!==void 0){let i=t.anchorTime??void 0;i!==n.anchorTime&&(n.anchorTime=i,this.refreshAnchorOffset(n));}pk(n,t),this.scheduler.invalidate(3);}}removeIndicator(e){let t=this.scene.indicators.get(e.id)?.native?.type;t==="volume"?(this.volumeActive=false,this.volumeHidden=false,this.scene.volumeLayer=null):t==="vpvr"&&(this.vpvrActive=false,this.vpvrHidden=false,this.scene.vpvrLayer=null),this.scene.indicators.delete(e.id),this.scene.forgetIndicatorZ(e.id),this.scene.forgetAnchorOffset(e.id),this.scene.dropIndicatorScale(e.id),this.inputsUI.remove(e.id),this.refreshAxisWidth(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}setIndicatorInputs(e,t,n){this.inputsUI.setValues(e.id,t,n);}setSymbolPicker(e){this.symbolPicker=e,this.inputsUI?.setSymbolPicker(e);}setLegendActions(e){this.legendActionsProvider=e,this.inputsUI?.setLegendActions(e);}setLegendCallouts(e){this.legendCalloutsProvider=e,this.inputsUI?.setLegendCallouts(e);}setLegendOverviewAction(e){this.legendOverviewAction=e,this.inputsUI?.setLegendOverviewAction(e);}openIndicatorSettings(e){this.inputsUI?.openSettingsFor(e);}setIndicatorVisible(e,t){let n=this.scene.indicators.get(e.id)?.native?.type;if(n==="volume"||n==="vpvr"){n==="volume"?this.volumeHidden=!t:this.vpvrHidden=!t,this.inputsUI.setVisible(e.id,t),this.scheduler.invalidate(4);return}t||this.scene.indicators.delete(e.id),this.inputsUI.setVisible(e.id,t),this.scheduler.invalidate(4);}onInputChange(e){return this.inputChangeCbs.add(e),()=>this.inputChangeCbs.delete(e)}onToggleIndicatorVisible(e){return this.toggleVisibleCbs.add(e),()=>this.toggleVisibleCbs.delete(e)}onPriceStyleChange(e){return this.priceStyleCbs.add(e),()=>this.priceStyleCbs.delete(e)}setPriceStyle(e){if(e!==this.scene.priceStyle){this.scene.priceStyle=e,this.scene.basePainting=Zu(e),this.scene.candleOverride=cc(e,this.scene.style.chartTypes);for(let t of this.priceStyleCbs)t(e);}}onRemoveIndicator(e){return this.removeIndicatorCbs.add(e),()=>this.removeIndicatorCbs.delete(e)}setLayoutMode(e){if(e!==this.layoutMode){if(this.layoutMode=e,this.mountContainer?.setAttribute("data-vela-layout",e),this.userDrawings?.setLayoutMode(e),this.settingsDialog?.setLayoutMode(e),this.inputsUI?.setLayoutMode(e),this.paneControls?.setSuspended(e==="mobile"),this.scrollButton){let t=e==="mobile"?$h:vs;this.scrollButton.style.width=`${t}px`,this.scrollButton.style.height=`${t}px`;}this.updateScrollToRealtimeButton();}}setSettingsSections(e){this.hostSettingsSections=e,this.settingsDialog?.setHostSections(e);}setSettingsVisibility(e){this.hiddenSettings=[...e.hidden??[]],this.settingsDialog?.setHiddenSettings(this.hiddenSettings);}listSettingsIds(){return Uy(this.hostSettingsSections)}onChartTypeSettingsChange(e){return this.chartTypeSettingsCbs.add(e),()=>this.chartTypeSettingsCbs.delete(e)}onConfigChanged(e){return this.configChangedCbs.add(e),()=>this.configChangedCbs.delete(e)}onThemeSelect(e){return this.themeSelectCbs.add(e),()=>this.themeSelectCbs.delete(e)}onCrosshairMove(e){return this.crosshairCbs.add(e),()=>this.crosshairCbs.delete(e)}onClick(e){return this.clickCbs.add(e),()=>this.clickCbs.delete(e)}onAxisLongPress(e){return this.axisLongPressCbs.add(e),()=>this.axisLongPressCbs.delete(e)}onViewportChange(e){return this.viewportCbs.add(e),()=>this.viewportCbs.delete(e)}getVisibleRange(){let e=this.coords.barCount;if(e===0||this.coords.width===0)return null;let t=this.coords.visibleLogicalRange(),n=Math.max(0,Math.ceil(t.from)),i=Math.min(e-1,Math.floor(t.to));return i<n?null:{from:this.coords.logicalToTime(n),to:this.coords.logicalToTime(i)}}setVisibleRange(e){let t=this.coords.timeToLogical(e.from),n=this.coords.timeToLogical(e.to),i=Math.max(1e-6,n-t),o=tn(this.coords.width/(i*this.coords.spacingScale)),s=n-(this.coords.barCount-1);this.applyViewport({barSpacing:o,rightOffset:s});}panBy(e){if(this.coords.barCount===0||this.coords.width===0)return;let t=this.coords.getViewport(),n=this.coords.width/this.coords.pxPerBar(),i=this.scrollTargetRO??t.rightOffset;this.glideRightOffset(this.clampViewport(t.barSpacing,i+e*n).rightOffset);}applyViewport(e){this.animator.stop(),this.panVelocity=0,this.scrollTargetRO=null;let t=this.clampViewport(e.barSpacing,e.rightOffset);this.coords.setViewport(t),this.targetBarSpacing=t.barSpacing,this.scheduler.invalidate(4),this.emitViewportChange();}zoomTo(e,t,n){let i=this.clampViewport(e,this.coords.getViewport().rightOffset).barSpacing;if(this.zoomAnchorLogical=t,this.zoomAnchorX=n,this.panVelocity=0,this.scrollTargetRO=null,!this.animZoom){let o=this.clampViewport(i,this.anchoredRightOffset(i));this.coords.setViewport(o),this.targetBarSpacing=o.barSpacing,this.scheduler.invalidate(4),this.emitViewportChange();return}this.targetBarSpacing=i,this.animator.start();}fling(e){this.animPan&&(this.scrollTargetRO=null,this.panVelocity=e,this.animator.start());}anchoredRightOffset(e){let t=e*this.coords.spacingScale;return this.zoomAnchorLogical+(this.coords.width-this.zoomAnchorX)/t-(this.coords.barCount-1)}clampViewport(e,t){let n=this.coords.barCount,i=this.coords.width;if(n<=1||i<=0)return {barSpacing:tn(e),rightOffset:t};let o=Math.min(ik,n),s=this.coords.spacingScale,a=Math.min(1e3,i/(o*s)),l=Math.max(.5,Math.min(a,i/((n+Yw)*s))),c=Math.max(l,Math.min(a,e)),u=i/(c*s)-(o-1),h=o-n,p=Math.max(h,Math.min(u,t));return {barSpacing:c,rightOffset:p}}animTick(e){let t=this.coords.getViewport(),n=t.barSpacing,i=t.rightOffset,o=false,s=this.targetBarSpacing;Math.abs(n-s)>s*.001?(n=tn(vt(n,s,e,ok)),i=this.anchoredRightOffset(n),o=true):n!==s&&(n=s,i=this.anchoredRightOffset(n));let a=lk/Math.max(1e-6,n*this.coords.spacingScale);if(Math.abs(this.panVelocity)>a&&(i+=this.panVelocity*e,this.panVelocity*=Math.exp(-e/sk),Math.abs(this.panVelocity)<=a?this.panVelocity=0:o=true),this.scrollTargetRO!=null){let c=this.scrollTargetRO,d=vt(i,c,e,ak);Math.abs(d-c)<.001?(i=c,this.scrollTargetRO=null):(i=d,o=true);}let l=this.clampViewport(n,i);return l.barSpacing!==n&&(this.targetBarSpacing=l.barSpacing),this.scrollTargetRO!=null&&l.rightOffset!==i&&(this.scrollTargetRO=l.rightOffset),this.coords.setViewport(l),this.computeScales(),this.easeScales(e)&&(o=true),this.easeLiveBar(e)&&(o=true),this.skeletonClockMs+=e,this.paintData(),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx()),this.updateLegendValues(),this.emitViewportChange(),o}easeScales(e){let t=false;for(let n of this.scene.panes.values()){let i=n.scaleTarget,o=n.scale;if(i.log&&o.min>0&&i.min>0){let c=Math.log(i.min),d=Math.log(i.max),u=Math.max(1e-9,Math.abs(d-c)),h=vt(Math.log(o.min),c,e,Fi),p=vt(Math.log(o.max),d,e,Fi);Math.abs(h-c)<=u*.001&&Math.abs(p-d)<=u*.001?n.scale={min:i.min,max:i.max,log:true}:(t=true,n.scale={min:Math.exp(h),max:Math.exp(p),log:true});continue}let s=Math.max(1e-9,Math.abs(i.max-i.min)),a=vt(o.min,i.min,e,Fi),l=vt(o.max,i.max,e,Fi);Math.abs(a-i.min)<=s*.001&&Math.abs(l-i.max)<=s*.001?(a=i.min,l=i.max):t=true,n.scale={min:a,max:l,log:i.log};}for(let n of this.scene.indicatorScales.values()){let i=n.scaleTarget,o=n.scale,s=Math.max(1e-9,Math.abs(i.max-i.min)),a=vt(o.min,i.min,e,Fi),l=vt(o.max,i.max,e,Fi);Math.abs(a-i.min)<=s*.001&&Math.abs(l-i.max)<=s*.001?(a=i.min,l=i.max):t=true,n.scale={min:a,max:l};}return t}emitViewportChange(){this.updateScrollToRealtimeButton();let e=this.getVisibleRange();if(e)for(let t of this.viewportCbs)t(e);}handlePointerMove(e,t){if(e===null||t===null||this.coords.barCount===0){this.scene.crosshair=null,this.hoverSeparatorY=null,this.lastPointer=null,this.scheduler.invalidate(1),this.hoverLogical=null;let p={time:null,price:null,paneKind:null,values:new Map,ohlc:null};for(let m of this.crosshairCbs)m(p);return}let n=e>=0&&t>=0&&e<=this.coords.width&&t<=this.coords.height;this.scene.crosshair=n?{x:e,y:t}:null,this.lastPointer=n?{x:e,y:t}:null,this.hoverSeparatorY=e>=0&&t>=0&&t<=this.coords.height?this.separatorHoverY(t):null,this.scheduler.invalidate(1);let i=Math.round(this.coords.xToLogical(e)),o=i>=0&&i<this.coords.barCount,s=o?this.coords.logicalToTime(i):null,a=this.paneNodeAtY(t),l=n&&a?this.coords.yToPrice(t,a.scale,a.bounds):null,c=new Map;if(o)for(let p of this.scene.indicators.values()){let m=this.scene.offsetOf(p.id);for(let f of p.series)if(Ne(f)){let g=f.points[i-m]?.value;g!=null&&c.set(f.id,g);}}let d=o?this.bars[i]:void 0,u=d?{time:d.time,open:d.open,high:d.high,low:d.low,close:d.close,volume:d.volume}:null;this.hoverLogical=o?i:null;let h={time:s,price:l,paneKind:n&&a?a.kind:null,values:c,ohlc:u};for(let p of this.crosshairCbs)p(h);}handleClick(e){if(this.coords.barCount===0)return;let t=Math.round(this.coords.xToLogical(e)),n=t>=0&&t<this.coords.barCount;for(let i of this.clickCbs)i({time:n?this.coords.logicalToTime(t):null,price:null});}paneAtY(e){return this.paneNodeAtY(e)}paneNodeAtY(e){for(let t of this.scene.panes.values())if(e>=t.bounds.top&&e<=t.bounds.top+t.bounds.height)return t;return null}nearestPaneToY(e){let t=null,n=1/0;for(let i of this.scene.panes.values()){let o=e<i.bounds.top?i.bounds.top-e:e-(i.bounds.top+i.bounds.height);o<n&&(n=o,t=i);}return t}resolveScaleHolder(e,t){let n=this.paneNodeAtY(t);if(!n)return null;let i=this.coords.width,o=this.scene.ownScaleIndicatorsForPane(n.id);if(e>=i+64&&o.length>0){let s=Math.floor((e-i-64)/56),a=o[s];if(a)return {holder:this.scene.ensureIndicatorScale(a.id,n.scaleTarget),height:n.bounds.height}}return {holder:n,height:n.bounds.height}}beginPriceScale(e,t){let n=this.resolveScaleHolder(e,t);n&&(this.scaleDragHolder=n.holder,this.scaleDragHeight=n.height,this.scaleDragStart={...n.holder.scale},n.holder.manualScale={...n.holder.scale},this.axisScaleButtons?.reposition(),this.scheduler.invalidate(4));}priceScaleBy(e){let t=this.scaleDragHolder,n=this.scaleDragStart;!t||!n||this.setManualScale(t,Iw(n,Math.exp(e*ck)));}beginPricePan(e){let t=this.paneNodeAtY(e);return !t||!t.manualScale?false:(this.scaleDragHolder=t,this.scaleDragHeight=t.bounds.height,this.scaleDragStart={...t.scale},true)}pricePanBy(e){let t=this.scaleDragHolder,n=this.scaleDragStart;!t||!n||this.setManualScale(t,Aw(n,e,this.scaleDragHeight));}resetPriceScale(e,t){let n=this.resolveScaleHolder(e,t);n&&(n.holder.manualScale=null,this.axisScaleButtons?.reposition(),this.scheduler.invalidate(4));}dataDblClick(e,t){let n=this.paneNodeAtY(t)??this.nearestPaneToY(t);if(!n)return;let i=this.maximizedPaneId!==n.id;this.maximizedPaneId=i?n.id:null,this.afterPaneLayoutChange(),this.emitPaneAction({type:"maximize",paneId:n.id,maximized:i});}resetView(){this.fitContent(),this.scheduler.invalidate(4),this.emitViewportChange();}setManualScale(e,t){e.manualScale=t,e.scale={...t},e.scaleTarget={...t},e.initialized=true,this.scheduler.invalidate(4);}afterPaneLayoutChange(){this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}paneControlViews(){let e=this.scene.orderedPanes();return e.map((t,n)=>({id:t.id,kind:t.kind,collapsed:t.collapsed,maximized:this.maximizedPaneId===t.id,top:t.bounds.top,height:t.bounds.height,index:n,count:e.length}))}movePaneLocal(e,t){let n=this.scene.orderedPanes(),i=n.findIndex(l=>l.id===e);if(i<0)return;let o=t==="up"?i-1:i+1;if(o<1||o>=n.length)return;let s=n.map(l=>l.id),a=s[i];s[i]=s[o],s[o]=a,this.scene.orderPanes(s),this.afterPaneLayoutChange(),this.emitPaneAction({type:"move",paneId:e,dir:t});}paneSeparatorAt(e){return this.separatorPaneIndexAt(e)!==null}separatorHoverY(e){if(!this.paneResizeEnabled)return null;let t=this.separatorPaneIndexAt(e);return t===null?null:this.scene.orderedPanes()[t].bounds.top}separatorPaneIndexAt(e){let t=this.scene.orderedPanes();for(let n=1;n<t.length;n++)if(Math.abs(e-t[n].bounds.top)<=uk)return n;return null}beginPaneResize(e){let t=this.separatorPaneIndexAt(e);if(t===null)return;let n=this.scene.orderedPanes(),i=n[t-1],o=n[t];this.resizeAbove=i,this.resizeBelow=o,this.resizeSplitStart={combinedTop:i.bounds.top,combinedHeight:i.bounds.height+o.bounds.height,combinedWeight:i.heightWeight+o.heightWeight,startBoundaryY:o.bounds.top};}paneResizeBy(e){let t=this.resizeAbove,n=this.resizeBelow,i=this.resizeSplitStart;if(!t||!n||!i)return;let o=Rw(i,e);t.heightWeight=o.above,n.heightWeight=o.below,this.layoutPanes(),this.scheduler.invalidate(4);}resetPaneSize(e){let t=this.separatorPaneIndexAt(e);if(t===null)return;let n=this.scene.orderedPanes(),i=n[t-1],o=n[t],s=(i.heightWeight+o.heightWeight)/2;i.heightWeight=s,o.heightWeight=s,this.layoutPanes(),this.scheduler.invalidate(4);}setKeyboardEnabled(e){this.keyboardEnabled=e,!(!this.dataCanvas||!this.keyboard)&&(e?(this.dataCanvas.tabIndex=0,this.dataCanvas.setAttribute("role","application"),this.dataCanvas.setAttribute("aria-label","Interactive price chart. Use Left/Right arrows to move between bars, Shift+Arrow to pan, plus/minus to zoom, Home/End to jump, 0 to reset."),!this.liveRegion&&this.wrapper&&(this.liveRegion=document.createElement("div"),this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("role","status"),Object.assign(this.liveRegion.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:"0"}),this.wrapper.appendChild(this.liveRegion)),this.keyboard.attach(this.dataCanvas)):(this.keyboard.detach(),this.dataCanvas.removeAttribute("tabindex"),this.dataCanvas.removeAttribute("role"),this.dataCanvas.removeAttribute("aria-label")));}panByBars(e){let t=this.coords.getViewport();this.applyViewport({barSpacing:t.barSpacing,rightOffset:t.rightOffset+e});}zoomByStep(e){let t=this.coords.getViewport(),n=tn(t.barSpacing*Math.exp(e*dk));this.zoomTo(n,this.coords.rightEdgeLogical,this.coords.width);}stepCrosshair(e){let t=this.coords.barCount;if(t===0)return;let n=this.hoverLogical??Math.min(t-1,Math.round(this.coords.xToLogical(this.coords.width)));this.focusBar(n+e);}focusBar(e){let t=this.coords.barCount;if(t===0)return;let n=Math.max(0,Math.min(t-1,e)),i=this.coords.getViewport(),o=2,s=this.coords.xToLogical(0),a=this.coords.xToLogical(this.coords.width),l=i.rightOffset;n<s+o?l-=s+o-n:n>a-o&&(l+=n-(a-o)),l!==i.rightOffset&&this.applyViewport({barSpacing:i.barSpacing,rightOffset:l});let c=this.scene.orderedPanes().find(u=>u.kind==="price")??this.scene.orderedPanes()[0]??null,d=this.scene.crosshair?.y??(c?c.bounds.top+c.bounds.height/2:this.coords.height/2);this.handlePointerMove(this.coords.logicalToX(n),d),this.announceBar(n);}announceBar(e){if(!this.liveRegion)return;let t=this.bars[e],n=this.dataWindowPricePane(),i=this.dataWindowOHLC(t,n),o=[];t&&o.push(mk(t.time,this.scene.timezone)),i&&o.push(`Open ${i.o}, High ${i.h}, Low ${i.l}, Close ${i.c}`);for(let s of this.dataWindowGroups(e,n))for(let a of s.rows)o.push(`${a.label} ${a.value}`);this.liveRegion.textContent=o.join(". ");}getDataWindowReadout(){let e=this.bars.length;if(e===0)return {date:"",time:"",ohlc:null,groups:[]};let t=this.hoverLogical!=null?this.hoverLogical:e-1,n=this.bars[t],i=this.dataWindowPricePane(),o=n?qw(n.time,this.scene.timezone):{date:"",time:""};return {date:o.date,time:o.time,ohlc:this.dataWindowOHLC(n,i),groups:this.dataWindowGroups(t,i)}}dataWindowPricePane(){return this.scene.orderedPanes().find(e=>e.kind==="price")??null}dataWindowFmt(e,t){return t?Tc(t.scale,t.bounds.height,e,this.scene.priceMintick):String(e)}dataWindowOHLC(e,t){return e?{o:this.dataWindowFmt(e.open,t),h:this.dataWindowFmt(e.high,t),l:this.dataWindowFmt(e.low,t),c:this.dataWindowFmt(e.close,t),vol:e.volume!=null?Xw(e.volume):void 0,up:e.close>=e.open}:null}dataWindowGroups(e,t){let n=[];for(let i of this.scene.indicators.values()){let o=this.dataWindowRowsFor(i,e,t);o.length&&n.push({name:i.title,rows:o});}return n}dataWindowRowsFor(e,t,n){if(e.native?.type==="volume")return this.volumeReadoutRows(e,t);let i=(e.paneId?this.scene.panes.get(e.paneId):null)??n,o=this.scene.offsetOf(e.id),s=[];for(let a of e.series){let l,c;if(a.kind==="candle"||a.kind==="bar")l=a.bars[t-o]?.close,c=a.style?.up??this.theme.upColor;else if(Ne(a)){if(a.visible===false)continue;l=a.points[t-o]?.value,c=a.points[t-o]?.color??a.style.color;}else continue;l==null||!Number.isFinite(l)||s.push({label:a.title||e.title,value:this.dataWindowFmt(l,i),color:c});}return s}volumeReadoutRows(e,t){if(this.volumeHidden)return [];let n=this.bars[t],i=n?.volume;if(n==null||i==null||!Number.isFinite(i))return [];let o=this.scene.volumeLayer,s=n.close>=n.open?o?.upColor??this.theme.upColor:o?.downColor??this.theme.downColor;return [{label:e.title,value:Xw(i),color:s}]}updateLegendValues(){if(!this.inputsUI)return;let e=this.bars.length,t=new Map;if(e>0){let n=this.hoverLogical!=null?this.hoverLogical:e-1,i=this.dataWindowPricePane();for(let o of this.scene.indicators.values())t.set(o.id,this.dataWindowRowsFor(o,n,i).map(s=>({value:s.value,color:s.color})));}this.inputsUI.setPlotValues(t);}renderFrame(e){this.animator.active||(nh(e)?(this.computeScales(),this.paintData()):my(e)&&this.paintedData&&(this.chrome.prepare(this.scene,this.coords,this.theme),this.chrome.render(this.scene,this.coords,this.theme,this.axisSurface())),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx()),!nh(e)&&this.paintedData&&this.repaintCursorLayers(),this.updateLegendValues());}repaintCursorLayers(){let e=this.scene.panes.get(Be);if(!e)return;let t=typeof performance<"u"?performance.now():Date.now();for(let n of this.extLayers){if(!n.def.repaintOnCursor)continue;let i=this.layerPane(n.def.id)??e;i.collapsed||(n.instance.render(this.extLayerArgs(n.def.id,i.scale,i.bounds,t)),this.animZoom&&n.instance.animating?.()&&this.animator.start());}}clearLayerCanvas(e){e.width===0||e.height===0||e.getContext("2d")?.clearRect(0,0,e.width,e.height);}extLayerArgs(e,t,n,i){return {bars:this.scene.bars,data:this.scene.nativeData.get(e),settings:this.scene.nativeData.get(`${e}-settings`)??{},pending:this.scene.nativePending.get(e)??[],coords:this.coords,scale:t,bounds:n,theme:this.theme,priceStyle:this.scene.priceStyle,nowMs:i,cursor:this.lastPointer}}paintData(){this.syncLayerCanvasOrder(),this.stampScaleInvert(),this.backend.modelAlpha=this.modelAlpha,this.backend.candleBodyAlpha=this.candleBodyAlpha,this.backend.candleStructureAlpha=this.candleStructureAlpha;let e=1,t=1;this.backend.candleBodyScale=t;let n=this.scene.panes.get(Be);if(n){let a=this.nativeLayerPane("volume")??n;this.volumeRenderer.render({bars:this.scene.bars,data:this.scene.volumeLayer,visible:this.volumeActive&&!this.volumeHidden&&!a.collapsed,coords:this.coords,bounds:a.bounds,fillPane:a.kind!=="price"}),this.vpvrRenderer.render({bars:this.scene.bars,data:this.scene.vpvrLayer,visible:this.vpvrActive&&!this.vpvrHidden,coords:this.coords,scale:n.scale,bounds:n.bounds,theme:this.theme});let l=typeof performance<"u"?performance.now():Date.now(),c=null;for(let d of this.extLayers){let u=this.layerPane(d.def.id)??n;if(u.collapsed){this.clearLayerCanvas(d.canvas);continue}let h=this.extLayerArgs(d.def.id,u.scale,u.bounds,l);d.instance.render(h),u===n&&(c=Ow(c,d.instance.modulateBase?.(h)??null)),this.animZoom&&d.instance.animating?.()&&this.animator.start();}c&&(c.candleBodyScale!=null&&(this.backend.candleBodyScale=Gh(c.candleBodyScale)||.01),c.candleBodyAlpha!=null&&(this.backend.candleBodyAlpha=Gh(c.candleBodyAlpha)*this.candleBodyAlpha),c.gridAlpha!=null&&(e=Gh(c.gridAlpha)));}let i=this.bars.length-1,o=i>=0?this.bars[i]:void 0,s=!!o&&this.liveEaseTime===o.time&&(o.high!==this.liveEaseHigh||o.low!==this.liveEaseLow||o.close!==this.liveEaseClose);s&&o&&(this.bars[i]={...o,high:this.liveEaseHigh,low:this.liveEaseLow,close:this.liveEaseClose}),this.scene.drawingSlices=Cw(this.indicatorSlices.prepare(this.scene,this.coords,this.theme,this.dataCanvas),this.userDrawings?.prepareSlices(this.scene.orderedPanes().map(a=>a.id))??new Map),this.backdropRenderer.render(this.scene,this.coords,this.theme,e),this.backend.render(this.scene,this.coords,this.theme),this.chrome.render(this.scene,this.coords,this.theme,this.axisSurface()),this.userDrawings?.render(),s&&o&&(this.bars[i]=o),this.paintedData=true;}drawingProjector(){return Tw(this.coords,e=>{let t=this.scene.panes.get(e);return t?{scale:t.scale,bounds:t.bounds,collapsed:t.collapsed}:null},e=>this.paneNodeAtY(e)?.id??null,(e,t)=>this.barsInTimeRange(e,t),this.userDrawings?.seriesGateway?(e,t,n)=>this.userDrawings.seriesGateway.seriesInRange(e,t,n):void 0)}barsInTimeRange(e,t){let n=Math.min(e,t),i=Math.max(e,t),o=[];for(let s of this.bars)if(!(s.time<n)){if(s.time>i)break;o.push(s);}return o}get userDrawingsPort(){return this.userDrawings??void 0}focus(){this.dataCanvas?.focus({preventScroll:true});}setExternalCrosshair(e,t=null){let n=e==null?null:{time:e,price:t},i=this.externalCross;!n&&!i||n&&i&&i.time===n.time&&i.price===n.price||(this.externalCross=n,this.scheduler.invalidate(1));}externalCrossPx(){let e=this.externalCross;if(!e||this.coords.barCount===0)return null;let t=Math.floor(this.coords.timeToLogical(e.time));if(t<0||t>=this.coords.barCount)return null;let n=this.coords.logicalToX(t);if(!Number.isFinite(n)||n<0||n>this.coords.width)return null;let i=null;if(e.price!=null){let o=this.scene.orderedPanes().find(s=>s.kind==="price");o&&(i=this.coords.priceToY(e.price,o.scale,o.bounds),(!Number.isFinite(i)||i<o.bounds.top||i>o.bounds.top+o.bounds.height)&&(i=null));}return {x:n,y:i,time:this.coords.logicalToTime(t),price:i!=null?e.price:null}}setSnapMode(e){this.snapMode=e;}snapToCandle(e,t,n="strong",i){if(n==="off")return e;let o=this.bars.length;if(o===0)return e;let s=Math.max(0,Math.min(o-1,Math.round(this.coords.timeToLogical(e.time)))),a=this.bars[s];if(!a)return e;let l;if(t!==Be)l={time:a.time,price:e.price};else {let c=a.open;for(let d of [a.high,a.low,a.close])Math.abs(d-e.price)<Math.abs(c-e.price)&&(c=d);l={time:a.time,price:c};}if(n==="weak"&&i){let c=this.drawingProjector(),d=c.yOf(l.price,t);if(Math.hypot(c.xOf(l.time)-i.x,(d??i.y)-i.y)>ZM)return e}return l}computeScales(){let e=this.coords.barCount;if(e===0)return;let t=this.coords.visibleLogicalRange(),n=Math.max(0,Math.floor(t.from)),i=Math.min(e-1,Math.ceil(t.to));if(i<n)return;this.scene.percentBaseline=this.bars[n]?.close??0;let o=this.scene.orderedPanes(),s=o.find(l=>l.kind==="price")??null;this.chrome.prepare(this.scene,this.coords,this.theme);let a=this.animator.active;for(let l of o){if(l.manualScale){l.scaleTarget=l.manualScale,l.scale={...l.manualScale},l.initialized=true;continue}let d=this.scene.indicatorsForPane(l.id).filter(p=>p.ownScale!==true),u=this.chrome.paneDrawingsRange(d,this.scene,l===s,t);if(l===s){let p=Mw(this.scene.indicators.values(),n,i,m=>this.scene.offsetOf(m));p&&(u=u?{min:Math.min(u.min,p.min),max:Math.max(u.max,p.max)}:p);}let h=l.kind==="price"&&!this.scene.candlesHidden;if(l.scaleTarget=$c(d,this.bars,h,n,i,u,Mi(this.scene,l),p=>this.scene.offsetOf(p)),l.percentBaseline=l.kind==="price"?this.bars[n]?.close??0:this.firstVisibleValue(d,n),l.axisFormat=void 0,l.axisBands=void 0,this.volumeOwnsPane(l,d)){let p=this.maxVisibleVolume(n,i);p>0&&(l.scaleTarget={min:0,max:p/Oh},l.axisFormat="volume");}else if(this.layerNativesOwnPane(l,d)&&(l.scaleTarget=$c([],this.bars,true,n,i,u,Mi(this.scene,l),p=>this.scene.offsetOf(p)),l.percentBaseline=this.bars[n]?.close??0,d.every(p=>p.paneAxis!=null))){l.axisFormat="none";let p=d.find(m=>typeof m.paneAxis=="object");l.axisBands=p?p.paneAxis.bands:void 0;}if(l===s&&this.scene.tradeMarkers.visible&&l.bounds.height>0){let p=this.tradesScaleHints(t);if(p){let m=l.scaleTarget,f={...m,min:Math.min(m.min,p.min),max:Math.max(m.max,p.max)};l.scaleTarget=kw(f,l.bounds.height,p.abovePx,p.belowPx);}}(!a||!l.initialized)&&(l.scale={...l.scaleTarget},l.initialized=true);for(let p of this.scene.ownScaleIndicatorsForPane(l.id)){let m=this.scene.ensureIndicatorScale(p.id,l.scaleTarget);if(m.manualScale){m.scaleTarget=m.manualScale,m.scale={...m.manualScale},m.initialized=true;continue}let f=this.chrome.paneDrawingsRange([p],this.scene,false,t);m.scaleTarget=$c([p],this.bars,false,n,i,f,false,g=>this.scene.offsetOf(g)),(!a||!m.initialized)&&(m.scale={...m.scaleTarget},m.initialized=true);}}}tradesScaleHints(e){let t=null,n={timeToLogical:i=>this.coords.timeToLogical(i),barAt:i=>{let o=this.bars[Math.round(i)];return o?{high:o.high,low:o.low}:null}};for(let i of this.scene.indicators.values()){if(!i.trades?.length)continue;let o=Ly(i.trades,this.scene.tradeMarkers,n,e.from,e.to,this.scene.style.fontSize);o&&(t=t?{min:Math.min(t.min,o.min),max:Math.max(t.max,o.max),abovePx:Math.max(t.abovePx,o.abovePx),belowPx:Math.max(t.belowPx,o.belowPx)}:o);}return t}fitContent(){let e=this.coords.barCount,t=this.coords.width;if(e<=0||t<=0)return;this.animator?.stop(),this.panVelocity=0;for(let s of this.scene.panes.values())s.manualScale=null;for(let s of this.scene.indicatorScales.values())s.manualScale=null;let n=Math.min(e,200),i=6,o=this.clampViewport(t/((n+i)*this.coords.spacingScale),i);this.coords.setViewport(o),this.targetBarSpacing=o.barSpacing;}reframeKeepZoom(){this.animator?.stop(),this.panVelocity=0;for(let t of this.scene.panes.values())t.manualScale=null;for(let t of this.scene.indicatorScales.values())t.manualScale=null;let e={barSpacing:tn(this.coords.getViewport().barSpacing),rightOffset:ns().rightOffset};this.coords.setViewport(e),this.targetBarSpacing=e.barSpacing;}paneBoundsFor(e){let t=this.scene.panes.get(e);return {top:t?.bounds.top??0,height:t?.bounds.height??0,rightAxis:this.rightAxisW}}paneMasterTitle(e){let t=this.scene.orderedIndicatorsForPane(e);return (t.find(i=>i.ownScale!==true)??t[0])?.title||null}nativeLayerPane(e){for(let t of this.scene.indicators.values())if(t.native?.type===e)return this.scene.panes.get(t.paneId??Be)??null;return null}layerOwner(e){for(let t of this.scene.indicators.values())if(t.native?.type===e)return t;return null}layerPane(e){let t=this.layerOwner(e),n=t?t.paneId??Be:Be;return this.scene.panes.get(n)??null}orderedLayerCanvases(){let e=new Map(this.extLayers.map(i=>[i.def.id,i.canvas])),{below:t,above:n}=Nw(this.extLayers.map(i=>{let o=this.layerOwner(i.def.id);return {id:i.def.id,placement:i.def.placement==="below-data"?"below-data":"above-data",ownerZ:o?this.scene.zOf(o.id):null}}),this.scene.candleZ);return {below:t.map(i=>e.get(i)),above:n.map(i=>e.get(i))}}canvasPile(){let{below:e,above:t}=this.orderedLayerCanvases();return [this.backdropCanvas,...e,this.dataCanvas,this.volumeCanvas,this.vpvrCanvas,...t]}syncLayerCanvasOrder(){if(this.extLayers.length===0||!this.plot)return;let{below:e,above:t}=this.orderedLayerCanvases(),n=[...e.map(i=>this.extLayers.find(o=>o.canvas===i).def.id),"|",...t.map(i=>this.extLayers.find(o=>o.canvas===i).def.id)].join(",");if(n!==this.layerOrderSig){this.layerOrderSig=n;for(let i of e)this.plot.insertBefore(i,this.dataCanvas);for(let i of t)this.plot.insertBefore(i,this.chromeCanvas);}}volumeOwnsPane(e,t){return e.kind==="price"||!this.volumeActive||this.volumeHidden||!this.scene.volumeLayer||this.nativeLayerPane("volume")!==e?false:t.every(n=>n.native?.type==="volume")}layerNativesOwnPane(e,t){return e.kind==="price"||t.length===0?false:t.every(n=>n.series.length===0&&!!n.native&&this.extLayers.some(i=>i.def.id===n.native.type))}paneScaleInfos(){return this.scene.orderedPanes().map(e=>({id:e.id,kind:e.kind,top:e.bounds.top,height:e.bounds.height,mode:ah(this.scene,e),log:Mi(this.scene,e),invert:lh(this.scene,e)}))}axisScaleViews(){return this.scene.orderedPanes().map(e=>({id:e.id,top:e.bounds.top,height:e.bounds.height,collapsed:e.collapsed,auto:e.manualScale==null,log:Mi(this.scene,e)}))}togglePaneAuto(e){let t=this.scene.panes.get(e);t&&(t.manualScale=t.manualScale==null?{...t.scale}:null,this.scheduler?.invalidate(4));}setPaneScaleMode(e,t){if(e===Be)this.scene.scaleMode=t;else {let n=this.scene.panes.get(e);if(!n)return;n.scaleMode=t;}this.scheduler?.invalidate(4);}setPaneLog(e,t){let n=e===Be?this.scene.orderedPanes().find(i=>i.kind==="price"):this.scene.panes.get(e);if(e===Be)this.scene.logScale=t;else {if(!n)return;n.logScale=t;}n?.manualScale&&(n.manualScale.log=t),this.scheduler?.invalidate(4);}setPaneInvert(e,t){if(e===Be)this.scene.invertScale=t;else {let n=this.scene.panes.get(e);if(!n)return;n.invert=t;}this.scheduler?.invalidate(4);}stampScaleInvert(){for(let e of this.scene.panes.values()){let t=lh(this.scene,e);e.scale.invert=t,e.scaleTarget.invert=t,e.manualScale&&(e.manualScale.invert=t);for(let n of this.scene.ownScaleIndicatorsForPane(e.id)){let i=this.scene.indicatorScales.get(n.id);i&&(i.scale.invert=t,i.scaleTarget.invert=t,i.manualScale&&(i.manualScale.invert=t));}}}firstVisibleValue(e,t){for(let n of e){let i=this.scene.offsetOf(n.id);for(let o of n.series)if(o.overlay!==true){if(Ne(o)){let s=o.points[t-i]?.value;if(s!=null&&Number.isFinite(s))return s}else if(o.kind==="candle"||o.kind==="bar"){let s=o.bars[t-i];if(s&&Number.isFinite(s.close))return s.close}}}return 0}maxVisibleVolume(e,t){let n=0;for(let i=e;i<=t;i+=1){let o=this.bars[i]?.volume;o!=null&&o>n&&(n=o);}return n}layoutPanes(){let e=this.scene.orderedPanes(),t=this.coords.height;this.inputsUI?.setCollapsedPanes(this.collapsedMasterMap());let n=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null;if(n){let d=0;for(let u of e)u===n?u.bounds={top:0,height:t}:u.bounds={top:t,height:0},d+=u.bounds.height;this.inputsUI?.reposition(),this.paneControls?.reposition(),this.axisScaleButtons?.reposition(),this.repositionScrollButton(),this.positionAttribution(),this.publishPricePaneBounds();return}let i=e.filter(d=>d.collapsed),o=e.filter(d=>!d.collapsed),s=i.length*Gw,a=Math.max(0,t-s),l=o.reduce((d,u)=>d+(u.heightWeight||1),0)||1,c=0;for(let d of e){let u=d.collapsed?Gw:a*(d.heightWeight||1)/l;d.bounds={top:c,height:u},c+=u;}this.inputsUI?.reposition(),this.paneControls?.reposition(),this.axisScaleButtons?.reposition(),this.repositionScrollButton(),this.positionAttribution(),this.publishPricePaneBounds();}repositionScrollButton(){let e=this.coords.height;if(e<=0)return;let t=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null,n=t?[t]:this.scene.orderedPanes().filter(o=>!o.collapsed),i=n.length?Math.max(...n.map(o=>o.bounds.top+o.bounds.height)):e;this.scrollBtnBottomPx=Wh+Math.max(0,e-i),this.mountContainer?.style.setProperty("--vela-bottom-gutter",`${Vi+Math.max(0,e-i)}px`),this.scrollBtnRightPx=this.rightAxisW+jw,this.scrollButton&&(this.scrollButton.style.bottom=`${this.scrollBtnBottomPx}px`,this.scrollButton.style.right=`${this.scrollBtnRightPx}px`);}collapsedMasterMap(){let e=new Map;for(let t of this.scene.panes.values()){if(!t.collapsed)continue;let n=this.scene.orderedIndicatorsForPane(t.id),i=new Set(this.scene.ownScaleIndicatorsForPane(t.id).map(s=>s.id)),o=n.find(s=>!i.has(s.id))??n[0];e.set(t.id,o?.id??null);}return e}setToolbarGutter(e){e!==this.toolbarGutter&&(this.toolbarGutter=e,this.publishGutters(),this.positionAttribution(),this.syncSize());}publishGutters(){this.mountContainer?.style.setProperty("--vela-toolbar-gutter",`${this.toolbarGutter}px`),this.mountContainer?.style.setProperty("--vela-scale-gutter",`${this.rightAxisW}px`);}publishPricePaneBounds(){if(!this.mountContainer)return;let e=this.coords.height+Vi,t=this.scene.panes.get(Be),n=t?t.bounds.top:0,i=t?t.bounds.height:this.coords.height,o=Math.max(0,e-(n+i));this.mountContainer.style.setProperty("--vela-price-pane-top",`${n}px`),this.mountContainer.style.setProperty("--vela-price-pane-bottom",`${o}px`);}buildAttributionEl(){return this.attributionHtml!==null?Bw(document,this.attributionHtml,this.theme.background):Hw(document,this.theme.background)}rebuildAttribution(){this.attributionEl&&(this.attributionEl.remove(),this.attributionEl=this.buildAttributionEl(),this.attributionEnabled||(this.attributionEl.style.display="none"),this.positionAttribution(),this.wrapper.appendChild(this.attributionEl));}positionAttribution(){if(!this.attributionEl)return;let e=this.coords?.height??0,t=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null,n=t?[t]:this.scene.orderedPanes().filter(o=>!o.collapsed),i=e>0&&n.length?Math.max(...n.map(o=>o.bounds.top+o.bounds.height)):e;Object.assign(this.attributionEl.style,{left:`${(this.toolbarGutter||0)+12}px`,bottom:`${Vi+10+Math.max(0,e-i)}px`});}refreshAttributionColor(){this.attributionEl&&(this.attributionHtml!==null?this.attributionEl.style.color=_h(this.theme.background):Bh(this.attributionEl,this.theme.background));}syncSize(){let e=this.wrapper.clientWidth,t=this.wrapper.clientHeight;if(e<=0||t<=0)return;let n=window.devicePixelRatio||1;this.plot.style.left=`${this.toolbarGutter}px`;let i=this.plot.getBoundingClientRect(),o=Math.max(1,Math.round(i.width*n)),s=Math.max(1,Math.round(i.height*n)),a=this.plotDeviceSize;a&&Math.abs(a.width-i.width*n)<=1&&Math.abs(a.height-i.height*n)<=1&&(o=Math.max(1,a.width),s=Math.max(1,a.height));let l=o/n,c=s/n,d=u=>{u.width=o,u.height=s,u.style.width=`${l}px`,u.style.height=`${c}px`;};d(this.dataCanvas),d(this.backdropCanvas),d(this.volumeCanvas);for(let u of this.extLayers)d(u.canvas);d(this.vpvrCanvas),d(this.chromeCanvas),d(this.drawingsCanvas),d(this.cursorCanvas),this.coords.setSize(Math.max(1,l-this.rightAxisW),Math.max(1,c-Vi),n),this.scene.crosshair=null,this.layoutPanes(),this.userDrawings?.onResize(),!this.didInitialFit&&this.coords.barCount>0&&(this.fitContent(),this.didInitialFit=true),this.animator.active?(this.computeScales(),this.paintData(),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx())):this.scheduler.flushNow(4);}applyBackground(){this.wrapper.style.background=this.theme.background;}};function hk(r,e){for(let t of r.series){let n=t.kind==="candle"||t.kind==="bar"?t.bars:Ne(t)?t.points:null;if(!n||n.length===0)continue;let i=0,o=n.length;for(;i<o;){let s=i+o>>1;n[s].time<e?i=s+1:o=s;}return i}return null}function pk(r,e){if(e.kind==="value"){for(let t of e.series){let n=r.series.find(i=>i.id===t.seriesId);n&&(t.kind==="points"&&Ne(n)?n.points=t.points:t.kind==="bars"&&(n.kind==="candle"||n.kind==="bar")&&(n.bars=t.bars));}e.lines&&(r.lines=e.lines),e.boxes&&(r.boxes=e.boxes),e.labels&&(r.labels=e.labels),e.polylines&&(r.polylines=e.polylines),e.linefills&&(r.linefills=e.linefills),e.tables&&(r.tables=e.tables),e.trades&&(r.trades=e.trades);return}for(let t of e.removed){let n=r.series.findIndex(i=>i.id===t);n>=0&&r.series.splice(n,1);}for(let t of e.added)r.series.push(t);}function qw(r,e){let t=wc(r,e),n=i=>i<10?`0${i}`:String(i);return {date:`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())}`,time:`${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}}function mk(r,e){let{date:t,time:n}=qw(r,e);return `${t} ${n}`}function fk(r){if(!Array.isArray(r))return [];let e=[];for(let t of r){if(!t||typeof t!="object")continue;let n=t,i=Number(n.from),o=Number(n.to);!Number.isFinite(i)||!Number.isFinite(o)||o<=i||e.push({from:i,to:o,color:typeof n.color=="string"?n.color:"rgba(120,130,160,0.10)"});}return e.sort((t,n)=>t.from-n.from)}function gk(r){if(r==null||typeof r!="object")return null;let e=r,t=n=>{if(!Array.isArray(n))return [];let i=[];for(let o of n){if(!Array.isArray(o))continue;let s=Number(o[0]),a=Number(o[1]);Number.isFinite(s)&&Number.isFinite(a)&&a>s&&i.push([s,a]);}return i.sort((o,s)=>o[0]-s[0])};return {pre:t(e.pre),post:t(e.post),extended:t(e.extended)}}function Gh(r){return Math.max(0,Math.min(1,r))}function bk(r){return typeof r=="string"&&Ei().includes(r)}function Kw(r){return r==="percent"||r==="indexed"?r:"price"}function Xw(r){let e=Math.abs(r);return e>=1e9?`${(r/1e9).toFixed(2)}B`:e>=1e6?`${(r/1e6).toFixed(2)}M`:e>=1e3?`${(r/1e3).toFixed(2)}K`:r.toFixed(2)}function vk(r){let e=[...r].sort((n,i)=>n.time-i.time),t=[];for(let n of e){let i=t[t.length-1];i&&i.time===n.time?t[t.length-1]=n:t.push(n);}return t}function Uh(r,e){let t=(r.open+r.high+r.low+r.close)/4,n=e?(e.open+e.close)/2:(r.open+r.close)/2;return {time:r.time,open:n,high:Math.max(r.high,n,t),low:Math.min(r.low,n,t),close:t,...r.volume!=null?{volume:r.volume}:{}}}function Zw(r){let e=new Array(r.length),t;for(let n=0;n<r.length;n+=1)t=Uh(r[n],t),e[n]=t;return e}var yk={full:Zw,next:Uh};function Jw(){Cd({id:"heikinashi",label:"Heikin Ashi",barTransform:yk});}var Yh=z,Kh=W,Xh=20;function wk(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function Qw(r,e){return typeof r=="string"&&r!==""?r:e}function jc(r){return {upColor:Qw(r.upColor,Yh),downColor:Qw(r.downColor,Kh),heightFrac:Math.min(.5,Math.max(.05,wk(r.heightPct,Xh)/100))}}var jh=class{constructor(){this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData(jc(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx.pushData(jc(e));}suspend(){}resume(){this.ctx.pushData(jc(this.inputs));}stop(){}},ex={type:"volume",title:"Volume",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"upColor",title:"Up color",type:"color",defval:Yh},{key:"downColor",title:"Down color",type:"color",defval:Kh},{key:"heightPct",title:"Height %",type:"int",defval:Xh,min:5,max:50,step:1,tooltip:"Pane height the tallest visible bar occupies"}],defaultInputs:()=>({upColor:Yh,downColor:Kh,heightPct:Xh}),create:()=>new jh};function qh(){Ln(ex);}var Jh=24,Qh=30,ep=Ye,tp=W,np=70;function Zh(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function tx(r,e){return typeof r=="string"&&r!==""?r:e}function qc(r){return {rows:Math.round(Math.min(400,Math.max(2,Zh(r.rows,Jh)))),widthFrac:Math.min(.9,Math.max(.05,Zh(r.widthPct,Qh)/100)),upColor:tx(r.upColor,ep),downColor:tx(r.downColor,tp),showPoc:r.showPoc!==false,valueAreaFrac:Math.min(1,Math.max(0,Zh(r.valueAreaPct,np)/100))}}var rp=class{constructor(){this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData(qc(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx.pushData(qc(e));}suspend(){}resume(){this.ctx.pushData(qc(this.inputs));}stop(){}},nx={type:"vpvr",title:"Visible Range Volume Profile",shortTitle:"VRVP",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"rows",title:"Rows",type:"int",defval:Jh,min:2,max:400,step:1},{key:"widthPct",title:"Width %",type:"int",defval:Qh,min:5,max:90,step:1,tooltip:"Pane width the largest row occupies"},{key:"upColor",title:"Up color",type:"color",defval:ep},{key:"downColor",title:"Down color",type:"color",defval:tp},{key:"showPoc",title:"Point of control",type:"bool",defval:true},{key:"valueAreaPct",title:"Value area %",type:"int",defval:np,min:0,max:100,step:1}],defaultInputs:()=>({rows:Jh,widthPct:Qh,upColor:ep,downColor:tp,showPoc:true,valueAreaPct:np}),create:()=>new rp};function ip(){Ln(nx);}function Xn(r){let e=r.title.trim().toLowerCase().replace(/\s+/g,"-");return `${r.instanceId}:${r.kind}:${e}#${r.ordinal}`}function I(r,e,t){let n=r[e];return typeof n=="number"&&Number.isFinite(n)?n:t}function F(r,e,t){let n=r[e];return typeof n=="string"&&n!==""?n:t}function sp(r,e,t){let n=r[e];return typeof n=="boolean"?n:t}function xk(r,e,t){let n=new Array(r.length);for(let i=0;i<r.length;i++){let o=e[i],s={time:r[i].time,value:o!=null&&Number.isFinite(o)?o:null},a=t?.[i];a!=null&&(s.color=a),n[i]=s;}return n}var op=class{constructor(e){this.spec=e;this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,this.recompute();}onBars(){this.recompute();}onViewport(){}setInputs(e){this.inputs=e,this.recompute();}suspend(){}resume(){this.recompute();}stop(){}recompute(){let e=this.ctx.bars(),t=this.spec.compute(e,this.inputs),n=this.spec.type,i=[],o=new Map;t.plots.forEach((c,d)=>{let u=c.kind??"line",h=Xn({instanceId:n,kind:u,title:c.title,ordinal:d});o.set(c.key,h),i.push({id:h,title:c.title,paneId:"",kind:u,points:xk(e,c.values,c.colors),style:{color:c.color,width:c.width??1,lineStyle:c.lineStyle??"solid",...c.base!=null?{base:c.base}:{}},...c.overlay?{overlay:true}:{}});}),t.markers&&t.markers.length>0&&i.push({id:Xn({instanceId:n,kind:"markers",title:"markers",ordinal:0}),title:this.spec.shortTitle??this.spec.title,paneId:"",kind:"markers",markers:t.markers});let s=(t.bands??[]).flatMap((c,d)=>{let u=o.get(c.from),h=o.get(c.to);return !u||!h?[]:[{id:Xn({instanceId:n,kind:"fill",title:c.key,ordinal:d}),paneId:"",fromSeriesId:u,toSeriesId:h,color:c.color}]}),a=(t.levels??[]).map((c,d)=>({id:Xn({instanceId:n,kind:"hline",title:c.key,ordinal:d}),paneId:"",price:c.price,...c.color!=null?{color:c.color}:{},lineStyle:c.lineStyle??"dashed",width:1,...c.title!=null?{title:c.title}:{}})),l=(t.polylines??[]).map((c,d)=>{let{key:u,...h}=c;return {id:Xn({instanceId:n,kind:"polyline",title:u,ordinal:d}),paneId:"",...h}});this.ctx.emit({series:i,fills:s,priceLines:a,polylines:l}),this.ctx.setStatus("idle");}};function rx(r){return {type:r.type,title:r.title,...r.shortTitle!=null?{shortTitle:r.shortTitle}:{},paneHint:r.overlay?"price":"new",overlay:r.overlay,multiInstance:true,inputsSchema:()=>r.inputs,defaultInputs:()=>Object.fromEntries(r.inputs.map(e=>[e.key,e.defval])),create:()=>new op(r)}}var ix=["Close","Open","High","Low","HL2","HLC3","OHLC4","HLCC4"];function ee(r,e){let t=new Array(r.length);for(let n=0;n<r.length;n++){let i=r[n];switch(e){case "Open":t[n]=i.open;break;case "High":t[n]=i.high;break;case "Low":t[n]=i.low;break;case "HL2":t[n]=(i.high+i.low)/2;break;case "HLC3":t[n]=(i.high+i.low+i.close)/3;break;case "OHLC4":t[n]=(i.open+i.high+i.low+i.close)/4;break;case "HLCC4":t[n]=(i.high+i.low+i.close+i.close)/4;break;default:t[n]=i.close;}}return t}function xt(r){return r.map(e=>e.volume!=null&&Number.isFinite(e.volume)?e.volume:Number.NaN)}function Ge(r){return r.map(e=>e.high)}function Ue(r){return r.map(e=>e.low)}function De(r){return r.map(e=>e.close)}function ox(r){return r.map(e=>e.open)}function K(r,e,t){let n=new Array(r.length);for(let i=0;i<r.length;i++){let o=r[i],s=e[i];n[i]=Number.isFinite(o)&&Number.isFinite(s)?t(o,s):Number.NaN;}return n}function ae(r,e){let t=new Array(r.length);for(let n=0;n<r.length;n++){let i=r[n];t[n]=Number.isFinite(i)?e(i):Number.NaN;}return t}function Te(r,e){return K(r,e,(t,n)=>t-n)}function En(r,e,t){let n=new Array(r.length).fill(Number.NaN);if(e<=0)return n;let i=0;for(let o=0;o<r.length;o++)i=Number.isFinite(r[o])?i+1:0,i>=e&&(n[o]=t(r,o-e+1,o));return n}function we(r,e){return En(r,e,(t,n,i)=>{let o=0;for(let s=n;s<=i;s++)o+=t[s];return o})}function fe(r,e){return En(r,e,(t,n,i)=>{let o=0;for(let s=n;s<=i;s++)o+=t[s];return o/e})}function Zc(r,e){let t=e*(e+1)/2;return En(r,e,(n,i,o)=>{let s=0;for(let a=i;a<=o;a++)s+=n[a]*(a-i+1);return s/t})}function sx(r,e,t){let n=K(r,e,(i,o)=>i*o);return K(we(n,t),we(e,t),(i,o)=>o>0?i/o:Number.NaN)}function rn(r,e){return En(r,e,(t,n,i)=>{let o=0;for(let l=n;l<=i;l++)o+=t[l];let s=o/e,a=0;for(let l=n;l<=i;l++){let c=t[l]-s;a+=c*c;}return Math.sqrt(a/e)})}function ct(r,e){return En(r,e,(t,n,i)=>{let o=-1/0;for(let s=n;s<=i;s++)t[s]>o&&(o=t[s]);return o})}function St(r,e){return En(r,e,(t,n,i)=>{let o=1/0;for(let s=n;s<=i;s++)t[s]<o&&(o=t[s]);return o})}function ax(r,e){return En(r,e,(t,n,i)=>{let o=-1/0,s=i;for(let a=n;a<=i;a++)t[a]>=o&&(o=t[a],s=a);return i-s})}function lx(r,e){return En(r,e,(t,n,i)=>{let o=1/0,s=i;for(let a=n;a<=i;a++)t[a]<=o&&(o=t[a],s=a);return i-s})}function cx(r,e,t){let n=new Array(r.length).fill(Number.NaN),i=0,o=Number.NaN;for(let s=0;s<r.length;s++){let a=r[s];if(!Number.isFinite(a)){i=0,o=Number.NaN;continue}if(i+=1,Number.isFinite(o))o=t*a+(1-t)*o,n[s]=o;else if(i>=e){let l=0;for(let c=s-e+1;c<=s;c++)l+=r[c];o=l/e,n[s]=o;}}return n}function Q(r,e){return cx(r,e,2/(e+1))}function Le(r,e){return cx(r,e,1/e)}function He(r,e=1){let t=new Array(r.length).fill(Number.NaN);for(let n=e;n<r.length;n++){let i=r[n],o=r[n-e];Number.isFinite(i)&&Number.isFinite(o)&&(t[n]=i-o);}return t}function Ft(r,e){let t=new Array(r.length).fill(Number.NaN);for(let n=e;n<r.length;n++){let i=r[n],o=r[n-e];Number.isFinite(i)&&Number.isFinite(o)&&o!==0&&(t[n]=100*(i-o)/o);}return t}function ot(r,e){let t=new Array(r.length).fill(Number.NaN);for(let n=0;n<r.length;n++){let i=n-e;i>=0&&i<r.length&&(t[n]=r[i]);}return t}function jn(r){let e=new Array(r.length).fill(Number.NaN);for(let t=0;t<r.length;t++){let n=r[t];if(t===0){e[t]=n.high-n.low;continue}let i=r[t-1].close;e[t]=Math.max(n.high-n.low,Math.abs(n.high-i),Math.abs(n.low-i));}return e}function Vr(r,e){return Le(jn(r),e)}function ws(r,e){let t=He(r),n=ae(t,o=>Math.max(o,0)),i=ae(t,o=>Math.max(-o,0));return K(Le(n,e),Le(i,e),(o,s)=>s===0?100:100-100/(1+o/s))}function Jc(r,e,t,n){let i=ct(e,n),o=St(t,n),s=new Array(r.length).fill(Number.NaN);for(let a=0;a<r.length;a++){let l=r[a],c=i[a],d=o[a];!Number.isFinite(l)||!Number.isFinite(c)||!Number.isFinite(d)||(s[a]=c===d?50:100*(l-d)/(c-d));}return s}function Qc(r,e){let t=(e-1)*e/2,n=(e-1)*e*(2*e-1)/6,i=e*n-t*t;return En(r,e,(o,s,a)=>{let l=0,c=0;for(let h=s;h<=a;h++){let p=h-s;l+=o[h],c+=p*o[h];}let d=i===0?0:(e*c-t*l)/i;return (l-d*t)/e+d*(e-1)})}function ed(r){let e=new Array(r.length).fill(Number.NaN);for(let t=3;t<r.length;t++){let n=r[t-3],i=r[t-2],o=r[t-1],s=r[t];Number.isFinite(n)&&Number.isFinite(i)&&Number.isFinite(o)&&Number.isFinite(s)&&(e[t]=(n+2*i+2*o+s)/6);}return e}function dx(r,e){let t=new Array(r.length).fill(Number.NaN);for(let n=e;n<r.length;n++){let i=r[n];if(!Number.isFinite(i))continue;let o=0,s=0;for(let a=n-e;a<n;a++){let l=r[a];if(!Number.isFinite(l)){s=-1;break}s+=1,l<=i&&(o+=1);}s===e&&(t[n]=100*o/e);}return t}function xs(r){let e=new Array(r.length).fill(Number.NaN),t=0,n=false;for(let i=0;i<r.length;i++){let o=r[i];Number.isFinite(o)&&(t+=o,n=true),n&&(e[i]=t);}return e}function D(r,e="length",t="Length",n=5e3){return {key:e,title:t,type:"int",defval:r,min:1,max:n,step:1}}function be(r="Close"){return {key:"source",title:"Source",type:"string",defval:r,options:ix}}function X(r=_,e="Color",t="color"){return {key:t,title:e,type:"color",defval:r}}function Pn(r,e=.08){let t=/^#([0-9a-f]{6})$/i.exec(r.trim());if(!t)return r;let n=Math.round(e*255).toString(16).padStart(2,"0");return `#${t[1]}${n}`}var Sk=["SMA","EMA","WMA","RMA","VWMA"],ux={key:"offset",title:"Offset",type:"int",defval:0,min:-500,max:500,step:1};function hx(r,e,t,n){return {type:r,title:e,shortTitle:t,overlay:true,inputs:[D(20),be(),ux,X()],compute:(i,o)=>{let s=I(o,"length",20),a=n(ee(i,F(o,"source","Close")),s),l=Math.trunc(I(o,"offset",0));return l!==0&&(a=ot(a,l)),{plots:[{key:t.toLowerCase(),title:t,values:a,color:F(o,"color",_),width:2}]}}}}var Ck=hx("sma","Simple Moving Average","SMA",fe),Tk=hx("ema","Exponential Moving Average","EMA",Q),Ek={type:"moving-average",title:"Moving Average",shortTitle:"MA",overlay:true,inputs:[{key:"maType",title:"Type",type:"string",defval:"SMA",options:Sk},D(20),be(),ux,X()],compute:(r,e)=>{let t=I(e,"length",20),n=ee(r,F(e,"source","Close")),i=F(e,"maType","SMA"),o;switch(i){case "EMA":o=Q(n,t);break;case "WMA":o=Zc(n,t);break;case "RMA":o=Le(n,t);break;case "VWMA":o=sx(n,xt(r),t);break;default:o=fe(n,t);}let s=Math.trunc(I(e,"offset",0));return s!==0&&(o=ot(o,s)),{plots:[{key:"ma",title:i,values:o,color:F(e,"color",_),width:2}]}}},Pk={type:"rma",title:"Smoothed Moving Average",shortTitle:"RMA",overlay:true,inputs:[D(14),be(),X()],compute:(r,e)=>({plots:[{key:"rma",title:"RMA",values:Le(ee(r,F(e,"source","Close")),I(e,"length",14)),color:F(e,"color",_),width:2}]})},Lk={type:"zlema",title:"Zero-Lag Exponential Moving Average",shortTitle:"ZLEMA",overlay:true,inputs:[D(14),be(),X()],compute:(r,e)=>{let t=I(e,"length",14),n=ee(r,F(e,"source","Close")),i=Math.floor((t-1)/2),o=ot(n,i),s=K(n,o,(a,l)=>2*a-l);return {plots:[{key:"zlema",title:"ZLEMA",values:Q(s,t),color:F(e,"color",_),width:2}]}}},Mk={type:"vidya",title:"Variable Index Dynamic Average",shortTitle:"VIDYA",overlay:true,inputs:[D(14),{key:"cmoLength",title:"Momentum length",type:"int",defval:9,min:1,max:500,step:1},be(),X()],compute:(r,e)=>{let t=I(e,"length",14),n=I(e,"cmoLength",9),i=ee(r,F(e,"source","Close")),o=He(i),s=new Array(i.length).fill(Number.NaN),a=new Array(i.length).fill(Number.NaN);for(let u=n;u<i.length;u++){let h=0,p=0,m=true;for(let f=u-n+1;f<=u;f++){let g=o[f];if(!Number.isFinite(g)){m=false;break}g>0?h+=g:p-=g;}m&&(s[u]=h,a[u]=p);}let l=2/(t+1),c=new Array(i.length).fill(Number.NaN),d=Number.NaN;for(let u=0;u<i.length;u++){let h=i[u],p=s[u],m=a[u];if(!Number.isFinite(h)||!Number.isFinite(p)||!Number.isFinite(m))continue;let f=p+m,g=f===0?0:Math.abs((p-m)/f);d=Number.isFinite(d)?l*g*h+(1-l*g)*d:h,c[u]=d;}return {plots:[{key:"vidya",title:"VIDYA",values:c,color:F(e,"color",_),width:2}]}}},kk={type:"ma-envelope",title:"Moving Average Envelope",shortTitle:"MA Env",overlay:true,inputs:[{key:"maType",title:"Type",type:"string",defval:"SMA",options:["SMA","EMA"]},D(20),be(),{key:"percent",title:"Percent",type:"float",defval:2.5,min:.01,max:50,step:.1},X()],compute:(r,e)=>{let t=I(e,"length",20),n=ee(r,F(e,"source","Close")),i=F(e,"maType","SMA")==="EMA"?Q(n,t):fe(n,t),o=I(e,"percent",2.5)/100,s=F(e,"color",_);return {plots:[{key:"basis",title:"Basis",values:i,color:s,width:2},{key:"upper",title:"Upper",values:ae(i,a=>a*(1+o)),color:s},{key:"lower",title:"Lower",values:ae(i,a=>a*(1-o)),color:s}],bands:[{key:"envelope",from:"upper",to:"lower",color:Pn(s)}]}}},Ik={type:"linear-regression",title:"Linear Regression Curve",shortTitle:"LinReg",overlay:true,inputs:[D(14),be(),X()],compute:(r,e)=>({plots:[{key:"linreg",title:"LinReg",values:Qc(ee(r,F(e,"source","Close")),I(e,"length",14)),color:F(e,"color",_),width:2}]})},px=[Ck,Tk,Ek,Pk,Lk,Mk,kk,Ik];function ap(r,e){let t=I(e,"length",20),n=I(e,"mult",2),i=ee(r,F(e,"source","Close")),o=fe(i,t),s=ae(rn(i,t),a=>a*n);return {basis:o,upper:K(o,s,(a,l)=>a+l),lower:K(o,s,(a,l)=>a-l)}}var lp=[D(20),be(),{key:"mult",title:"StdDev",type:"float",defval:2,min:.1,max:50,step:.1}],Ak={type:"bollinger-bands",title:"Bollinger Bands",shortTitle:"BB",overlay:true,inputs:[...lp,X()],compute:(r,e)=>{let{basis:t,upper:n,lower:i}=ap(r,e),o=F(e,"color",_);return {plots:[{key:"basis",title:"Basis",values:t,color:de},{key:"upper",title:"Upper",values:n,color:o},{key:"lower",title:"Lower",values:i,color:o}],bands:[{key:"bb",from:"upper",to:"lower",color:Pn(o)}]}}},Rk={type:"percent-b",title:"Bollinger Bands %B",shortTitle:"%B",overlay:false,inputs:[...lp,X()],compute:(r,e)=>{let{upper:t,lower:n}=ap(r,e);return {plots:[{key:"pb",title:"%B",values:ee(r,F(e,"source","Close")).map((s,a)=>{let l=t[a],c=n[a];return Number.isFinite(l)&&Number.isFinite(c)&&l!==c?(s-c)/(l-c):Number.NaN}),color:F(e,"color",_),width:2}],levels:[{key:"upper",price:1,color:J},{key:"middle",price:.5,color:J,lineStyle:"dotted"},{key:"lower",price:0,color:J}]}}},Dk={type:"bandwidth",title:"Bollinger Bands Width",shortTitle:"BandWidth",overlay:false,inputs:[...lp,X()],compute:(r,e)=>{let{basis:t,upper:n,lower:i}=ap(r,e);return {plots:[{key:"bbw",title:"BBW",values:t.map((s,a)=>{let l=n[a],c=i[a];return Number.isFinite(s)&&s!==0&&Number.isFinite(l)&&Number.isFinite(c)?(l-c)/s*100:Number.NaN}),color:F(e,"color",_),width:2}]}}},Ok={type:"keltner-channels",title:"Keltner Channels",shortTitle:"KC",overlay:true,inputs:[D(20),{key:"mult",title:"Multiplier",type:"float",defval:2,min:.1,max:50,step:.1},{key:"atrLength",title:"ATR length",type:"int",defval:10,min:1,max:500,step:1},be(),X()],compute:(r,e)=>{let t=I(e,"length",20),n=I(e,"mult",2),i=Q(ee(r,F(e,"source","Close")),t),o=ae(Vr(r,I(e,"atrLength",10)),a=>a*n),s=F(e,"color",_);return {plots:[{key:"basis",title:"Basis",values:i,color:de},{key:"upper",title:"Upper",values:K(i,o,(a,l)=>a+l),color:s},{key:"lower",title:"Lower",values:K(i,o,(a,l)=>a-l),color:s}],bands:[{key:"kc",from:"upper",to:"lower",color:Pn(s)}]}}},Nk={type:"donchian-channels",title:"Donchian Channels",shortTitle:"DC",overlay:true,inputs:[D(20),X()],compute:(r,e)=>{let t=I(e,"length",20),n=ct(Ge(r),t),i=St(Ue(r),t),o=F(e,"color",_);return {plots:[{key:"basis",title:"Basis",values:K(n,i,(s,a)=>(s+a)/2),color:de},{key:"upper",title:"Upper",values:n,color:o},{key:"lower",title:"Lower",values:i,color:o}],bands:[{key:"dc",from:"upper",to:"lower",color:Pn(o)}]}}},Fk={type:"chandelier-exit",title:"Chandelier Exit",shortTitle:"CE",overlay:true,inputs:[D(22),{key:"mult",title:"ATR multiplier",type:"float",defval:3,min:.1,max:50,step:.1}],compute:(r,e)=>{let t=I(e,"length",22),n=ae(Vr(r,t),s=>s*I(e,"mult",3)),i=K(ct(Ge(r),t),n,(s,a)=>s-a),o=K(St(Ue(r),t),n,(s,a)=>s+a);return {plots:[{key:"long",title:"Long stop",values:i,color:z},{key:"short",title:"Short stop",values:o,color:W}]}}},Vk={type:"chande-kroll-stop",title:"Chande Kroll Stop",shortTitle:"CKS",overlay:true,inputs:[{key:"p",title:"ATR length",type:"int",defval:10,min:1,max:500,step:1},{key:"x",title:"ATR multiplier",type:"float",defval:1,min:.1,max:50,step:.1},{key:"q",title:"Stop length",type:"int",defval:9,min:1,max:500,step:1}],compute:(r,e)=>{let t=I(e,"p",10),n=I(e,"x",1),i=I(e,"q",9),o=ae(Vr(r,t),l=>l*n),s=K(ct(Ge(r),t),o,(l,c)=>l-c),a=K(St(Ue(r),t),o,(l,c)=>l+c);return {plots:[{key:"stopShort",title:"Stop short",values:ct(s,i),color:W},{key:"stopLong",title:"Stop long",values:St(a,i),color:z}]}}},_k={type:"supertrend",title:"SuperTrend",shortTitle:"SuperTrend",overlay:true,inputs:[{key:"atrLength",title:"ATR length",type:"int",defval:10,min:1,max:500,step:1},{key:"mult",title:"Factor",type:"float",defval:3,min:.1,max:50,step:.1}],compute:(r,e)=>{let t=I(e,"atrLength",10),n=I(e,"mult",3),i=Vr(r,t),o=r.length,s=new Array(o).fill(Number.NaN),a=new Array(o).fill(1),l=Number.NaN,c=Number.NaN,d=1;for(let h=0;h<o;h++){let p=i[h];if(!Number.isFinite(p))continue;let m=r[h],f=(m.high+m.low)/2,g=f-n*p,b=f+n*p,y=h>0?r[h-1].close:m.close;l=Number.isFinite(l)&&y>l?Math.max(g,l):g,c=Number.isFinite(c)&&y<c?Math.min(b,c):b,d===1&&m.close<l?d=-1:d===-1&&m.close>c&&(d=1),a[h]=d,s[h]=d===1?l:c;}let u=a.map((h,p)=>Number.isFinite(s[p])?h===1?z:W:null);return {plots:[{key:"st",title:"SuperTrend",values:s,color:z,width:2,colors:u}]}}},Bk={type:"williams-alligator",title:"Williams Alligator",shortTitle:"Alligator",overlay:true,inputs:[{key:"jawLength",title:"Jaw length",type:"int",defval:13,min:1,max:500,step:1},{key:"teethLength",title:"Teeth length",type:"int",defval:8,min:1,max:500,step:1},{key:"lipsLength",title:"Lips length",type:"int",defval:5,min:1,max:500,step:1},{key:"jawOffset",title:"Jaw offset",type:"int",defval:8,min:0,max:100,step:1},{key:"teethOffset",title:"Teeth offset",type:"int",defval:5,min:0,max:100,step:1},{key:"lipsOffset",title:"Lips offset",type:"int",defval:3,min:0,max:100,step:1}],compute:(r,e)=>{let t=ee(r,"HL2"),n=ot(Le(t,I(e,"jawLength",13)),I(e,"jawOffset",8)),i=ot(Le(t,I(e,"teethLength",8)),I(e,"teethOffset",5)),o=ot(Le(t,I(e,"lipsLength",5)),I(e,"lipsOffset",3));return {plots:[{key:"jaw",title:"Jaw",values:n,color:_},{key:"teeth",title:"Teeth",values:i,color:W},{key:"lips",title:"Lips",values:o,color:z}]}}},Hk={type:"gator-oscillator",title:"Gator Oscillator",shortTitle:"Gator Oscillator",overlay:false,inputs:[],compute:r=>{let e=ee(r,"HL2"),t=ot(Le(e,13),8),n=ot(Le(e,8),5),i=ot(Le(e,5),3),o=ae(Te(t,n),Math.abs),s=ae(Te(n,i),l=>-Math.abs(l)),a=l=>l.map((c,d)=>{if(!Number.isFinite(c))return null;let u=d>0?l[d-1]:Number.NaN;return Number.isFinite(u)&&Math.abs(c)>Math.abs(u)?z:W});return {plots:[{key:"upper",title:"Upper",values:o,kind:"histogram",color:z,colors:a(o),base:0},{key:"lower",title:"Lower",values:s,kind:"histogram",color:W,colors:a(s),base:0}]}}},mx=[Ak,Rk,Dk,Ok,Nk,Fk,Vk,_k,Bk,Hk];function on(r,e,t){let n=[{key:"upper",price:e,color:J},{key:"lower",price:r,color:J}];return t!=null&&n.splice(1,0,{key:"middle",price:t,color:J,lineStyle:"dotted"}),n}var st=[{key:"zero",price:0,color:J}];function td(r){return r.map((e,t)=>{if(!Number.isFinite(e))return null;let n=t>0?r[t-1]:Number.NaN,i=Number.isFinite(n)?e>=n:true;return e>=0?i?z:`${z}80`:i?`${W}80`:W})}var zk={type:"rsi",title:"Relative Strength Index",shortTitle:"RSI",overlay:false,inputs:[D(14),be(),X()],compute:(r,e)=>({plots:[{key:"rsi",title:"RSI",values:ws(ee(r,F(e,"source","Close")),I(e,"length",14)),color:F(e,"color",_),width:2}],levels:on(30,70,50)})},$k={type:"stochastic",title:"Stochastic",shortTitle:"Stoch",overlay:false,inputs:[D(14,"kLength","%K length"),D(1,"kSmoothing","%K smoothing",500),D(3,"dLength","%D smoothing",500)],compute:(r,e)=>{let t=fe(Jc(De(r),Ge(r),Ue(r),I(e,"kLength",14)),I(e,"kSmoothing",1)),n=fe(t,I(e,"dLength",3));return {plots:[{key:"k",title:"%K",values:t,color:_,width:2},{key:"d",title:"%D",values:n,color:de}],levels:on(20,80)}}},Wk={type:"stochastic-rsi",title:"Stochastic RSI",shortTitle:"Stoch RSI",overlay:false,inputs:[D(14,"rsiLength","RSI length"),D(14,"stochLength","Stochastic length"),D(3,"kSmoothing","%K smoothing",500),D(3,"dLength","%D smoothing",500),be()],compute:(r,e)=>{let t=ws(ee(r,F(e,"source","Close")),I(e,"rsiLength",14)),n=fe(Jc(t,t,t,I(e,"stochLength",14)),I(e,"kSmoothing",3)),i=fe(n,I(e,"dLength",3));return {plots:[{key:"k",title:"%K",values:n,color:_,width:2},{key:"d",title:"%D",values:i,color:de}],levels:on(20,80)}}},Gk={type:"macd",title:"MACD",overlay:false,inputs:[D(12,"fastLength","Fast length"),D(26,"slowLength","Slow length"),D(9,"signalLength","Signal smoothing",500),be()],compute:(r,e)=>{let t=ee(r,F(e,"source","Close")),n=Te(Q(t,I(e,"fastLength",12)),Q(t,I(e,"slowLength",26))),i=Q(n,I(e,"signalLength",9)),o=Te(n,i);return {plots:[{key:"hist",title:"Histogram",values:o,kind:"histogram",color:z,colors:td(o),base:0},{key:"macd",title:"MACD",values:n,color:_,width:2},{key:"signal",title:"Signal",values:i,color:de}],levels:st}}},Uk={type:"ppo",title:"Percentage Price Oscillator",shortTitle:"PPO",overlay:false,inputs:[D(12,"fastLength","Fast length"),D(26,"slowLength","Slow length"),D(9,"signalLength","Signal smoothing",500),be()],compute:(r,e)=>{let t=ee(r,F(e,"source","Close")),n=Q(t,I(e,"fastLength",12)),i=Q(t,I(e,"slowLength",26)),o=K(n,i,(l,c)=>c===0?Number.NaN:(l-c)/c*100),s=Q(o,I(e,"signalLength",9)),a=Te(o,s);return {plots:[{key:"hist",title:"Histogram",values:a,kind:"histogram",color:z,colors:td(a),base:0},{key:"ppo",title:"PPO",values:o,color:_,width:2},{key:"signal",title:"Signal",values:s,color:de}],levels:st}}},Yk={type:"awesome-oscillator",title:"Awesome Oscillator",shortTitle:"AO",overlay:false,inputs:[],compute:r=>{let e=ee(r,"HL2"),t=Te(fe(e,5),fe(e,34)),n=t.map((i,o)=>{if(!Number.isFinite(i))return null;let s=o>0?t[o-1]:Number.NaN;return Number.isFinite(s)&&i<s?W:z});return {plots:[{key:"ao",title:"AO",values:t,kind:"histogram",color:z,colors:n,base:0}],levels:st}}},Kk={type:"commodity-channel-index",title:"Commodity Channel Index",shortTitle:"CCI",overlay:false,inputs:[D(20),be("HLC3"),X()],compute:(r,e)=>{let t=I(e,"length",20),n=ee(r,F(e,"source","HLC3")),i=fe(n,t),o=new Array(n.length).fill(Number.NaN);for(let a=t-1;a<n.length;a++){let l=i[a];if(!Number.isFinite(l))continue;let c=0;for(let d=a-t+1;d<=a;d++)c+=Math.abs(n[d]-l);o[a]=c/t;}return {plots:[{key:"cci",title:"CCI",values:n.map((a,l)=>{let c=i[l],d=o[l];return Number.isFinite(c)&&Number.isFinite(d)&&d!==0?(a-c)/(.015*d):Number.NaN}),color:F(e,"color",_),width:2}],levels:on(-100,100,0)}}},Xk={type:"williams-percent-r",title:"Williams %R",shortTitle:"%R",overlay:false,inputs:[D(14),X()],compute:(r,e)=>({plots:[{key:"wr",title:"%R",values:ae(Jc(De(r),Ge(r),Ue(r),I(e,"length",14)),n=>n-100),color:F(e,"color",_),width:2}],levels:on(-80,-20)})},jk={type:"chande-momentum-oscillator",title:"Chande Momentum Oscillator",shortTitle:"CMO",overlay:false,inputs:[D(9),be(),X()],compute:(r,e)=>{let t=I(e,"length",9),n=He(ee(r,F(e,"source","Close"))),i=we(ae(n,a=>Math.max(a,0)),t),o=we(ae(n,a=>Math.max(-a,0)),t);return {plots:[{key:"cmo",title:"CMO",values:K(i,o,(a,l)=>a+l===0?0:100*(a-l)/(a+l)),color:F(e,"color",_),width:2}],levels:on(-50,50,0)}}},qk={type:"connors-rsi",title:"Connors RSI",shortTitle:"CRSI",overlay:false,inputs:[D(3,"rsiLength","RSI length"),D(2,"streakLength","Streak RSI length"),D(100,"rankLength","Percent-rank length"),X()],compute:(r,e)=>{let t=De(r),n=new Array(t.length).fill(0);for(let l=1;l<t.length;l++){let c=t[l]-t[l-1];n[l]=c>0?Math.max(n[l-1],0)+1:c<0?Math.min(n[l-1],0)-1:0;}let i=ws(t,I(e,"rsiLength",3)),o=ws(n,I(e,"streakLength",2)),s=dx(Ft(t,1),I(e,"rankLength",100));return {plots:[{key:"crsi",title:"CRSI",values:t.map((l,c)=>{let d=i[c],u=o[c],h=s[c];return Number.isFinite(d)&&Number.isFinite(u)&&Number.isFinite(h)?(d+u+h)/3:Number.NaN}),color:F(e,"color",_),width:2}],levels:on(20,80,50)}}},Zk={type:"fisher-transform",title:"Fisher Transform",shortTitle:"Fisher",overlay:false,inputs:[D(9)],compute:(r,e)=>{let t=I(e,"length",9),n=ee(r,"HL2"),i=ct(n,t),o=St(n,t),s=r.length,a=new Array(s).fill(Number.NaN),l=0,c=0;for(let d=0;d<s;d++){let u=i[d],h=o[d];if(!Number.isFinite(u)||!Number.isFinite(h))continue;let p=u===h?0:(n[d]-h)/(u-h)-.5;l=Math.max(-0.999,Math.min(.999,.66*p+.67*l)),c=.5*Math.log((1+l)/(1-l))+.5*c,a[d]=c;}return {plots:[{key:"fisher",title:"Fisher",values:a,color:_,width:2},{key:"trigger",title:"Trigger",values:ot(a,1),color:de}],levels:st}}},Jk={type:"trix",title:"TRIX",overlay:false,inputs:[D(18),X()],compute:(r,e)=>{let t=I(e,"length",18),n=ae(De(r),Math.log),i=Q(Q(Q(n,t),t),t);return {plots:[{key:"trix",title:"TRIX",values:ae(He(i),s=>s*1e4),color:F(e,"color",_),width:2}],levels:st}}};function fx(r,e,t){let n=He(r),i=Q(Q(n,e),t),o=Q(Q(ae(n,Math.abs),e),t);return K(i,o,(s,a)=>a===0?0:100*s/a)}var Qk={type:"true-strength-index",title:"True Strength Index",shortTitle:"TSI",overlay:false,inputs:[D(25,"longLength","Long length"),D(13,"shortLength","Short length"),D(13,"signalLength","Signal length")],compute:(r,e)=>{let t=fx(De(r),I(e,"longLength",25),I(e,"shortLength",13));return {plots:[{key:"tsi",title:"TSI",values:t,color:_,width:2},{key:"signal",title:"Signal",values:Q(t,I(e,"signalLength",13)),color:de}],levels:st}}},eI={type:"smi-ergodic",title:"SMI Ergodic Oscillator",shortTitle:"SMIE",overlay:false,inputs:[D(5,"shortLength","Short length"),D(20,"longLength","Long length"),D(5,"signalLength","Signal length")],compute:(r,e)=>{let t=fx(De(r),I(e,"longLength",20),I(e,"shortLength",5)),n=Q(t,I(e,"signalLength",5)),i=Te(t,n);return {plots:[{key:"osc",title:"Oscillator",values:i,kind:"histogram",color:z,colors:td(i),base:0},{key:"smi",title:"SMI",values:t,color:_,width:2},{key:"signal",title:"Signal",values:n,color:de}],levels:st}}},tI={type:"schaff-trend-cycle",title:"Schaff Trend Cycle",shortTitle:"Schaff Trend Cycle",overlay:false,inputs:[D(10,"cycleLength","Cycle length"),D(23,"fastLength","Fast length"),D(50,"slowLength","Slow length")],compute:(r,e)=>{let t=I(e,"cycleLength",10),n=De(r),i=Te(Q(n,I(e,"fastLength",23)),Q(n,I(e,"slowLength",50))),o=a=>{let l=St(a,t),c=ct(a,t),d=new Array(a.length).fill(Number.NaN),u=Number.NaN,h=Number.NaN;for(let p=0;p<a.length;p++){let m=a[p],f=l[p],g=c[p];if(!Number.isFinite(m)||!Number.isFinite(f)||!Number.isFinite(g))continue;let b=g>f?(m-f)/(g-f)*100:Number.isFinite(u)?u:50;u=b,h=Number.isFinite(h)?h+.5*(b-h):b,d[p]=h;}return d};return {plots:[{key:"stc",title:"STC",values:o(o(i)),color:_,width:2}],levels:on(25,75)}}},nI={type:"know-sure-thing",title:"Know Sure Thing",shortTitle:"KST",overlay:false,inputs:[be(),D(9,"signalLength","Signal length")],compute:(r,e)=>{let t=ee(r,F(e,"source","Close")),n=[fe(Ft(t,10),10),fe(Ft(t,15),10),fe(Ft(t,20),10),fe(Ft(t,30),15)].reduce((i,o,s)=>K(i,o,(a,l)=>a+l*(s+1)),new Array(t.length).fill(0));return {plots:[{key:"kst",title:"KST",values:n,color:_,width:2},{key:"signal",title:"Signal",values:fe(n,I(e,"signalLength",9)),color:de}],levels:st}}},rI={type:"coppock-curve",title:"Coppock Curve",shortTitle:"Coppock",overlay:false,inputs:[D(10,"wmaLength","WMA length"),D(14,"longRoc","Long RoC length"),D(11,"shortRoc","Short RoC length"),be(),X()],compute:(r,e)=>{let t=ee(r,F(e,"source","Close"));return {plots:[{key:"coppock",title:"Coppock",values:Zc(K(Ft(t,I(e,"longRoc",14)),Ft(t,I(e,"shortRoc",11)),(i,o)=>i+o),I(e,"wmaLength",10)),color:F(e,"color",_),width:2}],levels:st}}},iI={type:"detrended-price-oscillator",title:"Detrended Price Oscillator",shortTitle:"DPO",overlay:false,inputs:[D(21),X()],compute:(r,e)=>{let t=I(e,"length",21),n=Math.floor(t/2)+1;return {plots:[{key:"dpo",title:"DPO",values:Te(De(r),ot(fe(De(r),t),n)),color:F(e,"color",_),width:2}],levels:st}}},oI={type:"rate-of-change",title:"Rate of Change",shortTitle:"ROC",overlay:false,inputs:[D(9),be(),X()],compute:(r,e)=>({plots:[{key:"roc",title:"RoC",values:Ft(ee(r,F(e,"source","Close")),I(e,"length",9)),color:F(e,"color",_),width:2}],levels:st})},sI={type:"ultimate-oscillator",title:"Ultimate Oscillator",shortTitle:"UO",overlay:false,inputs:[D(7,"fastLength","Fast length"),D(14,"middleLength","Middle length"),D(28,"slowLength","Slow length"),X()],compute:(r,e)=>{let t=r.length,n=new Array(t).fill(Number.NaN),i=new Array(t).fill(Number.NaN);for(let d=0;d<t;d++){let u=r[d],h=d>0?r[d-1].close:u.close,p=Math.min(u.low,h),m=Math.max(u.high,h);n[d]=u.close-p,i[d]=m-p;}let o=d=>K(we(n,d),we(i,d),(u,h)=>h===0?Number.NaN:u/h),s=o(I(e,"fastLength",7)),a=o(I(e,"middleLength",14)),l=o(I(e,"slowLength",28));return {plots:[{key:"uo",title:"UO",values:s.map((d,u)=>{let h=a[u],p=l[u];return Number.isFinite(d)&&Number.isFinite(h)&&Number.isFinite(p)?100*(4*d+2*h+p)/7:Number.NaN}),color:F(e,"color",_),width:2}],levels:on(30,70,50)}}},aI={type:"relative-vigor-index",title:"Relative Vigor Index",shortTitle:"RVGI",overlay:false,inputs:[D(10)],compute:(r,e)=>{let t=I(e,"length",10),n=ed(Te(De(r),ox(r))),i=ed(Te(Ge(r),Ue(r))),o=K(we(n,t),we(i,t),(s,a)=>a===0?0:s/a);return {plots:[{key:"rvgi",title:"RVGI",values:o,color:_,width:2},{key:"signal",title:"Signal",values:ed(o),color:de}],levels:st}}},lI={type:"relative-volatility-index",title:"Relative Volatility Index",shortTitle:"RVI",overlay:false,inputs:[D(10,"stdevLength","StdDev length"),D(14,"smoothLength","Smoothing length"),be(),X()],compute:(r,e)=>{let t=I(e,"smoothLength",14),n=ee(r,F(e,"source","Close")),i=rn(n,I(e,"stdevLength",10)),o=He(n),s=Le(K(i,o,(c,d)=>d>0?c:0),t),a=Le(K(i,o,(c,d)=>d<=0?c:0),t);return {plots:[{key:"rvi",title:"RVI",values:K(s,a,(c,d)=>c+d===0?50:100*c/(c+d)),color:F(e,"color",_),width:2}],levels:on(20,80,50)}}},cI={type:"balance-of-power",title:"Balance of Power",shortTitle:"BOP",overlay:false,inputs:[X()],compute:(r,e)=>({plots:[{key:"bop",title:"BOP",values:r.map(n=>n.high===n.low?0:(n.close-n.open)/(n.high-n.low)),color:F(e,"color",_),width:2}],levels:st})},dI={type:"elder-ray",title:"Elder Ray",overlay:false,inputs:[D(13)],compute:(r,e)=>{let t=Q(De(r),I(e,"length",13));return {plots:[{key:"bull",title:"Bull power",values:Te(Ge(r),t),kind:"histogram",color:z,base:0},{key:"bear",title:"Bear power",values:Te(Ue(r),t),kind:"histogram",color:W,base:0}],levels:st}}},uI={type:"ttm-squeeze",title:"TTM Squeeze",overlay:false,inputs:[D(20),{key:"bbMult",title:"Bollinger multiplier",type:"float",defval:2,min:.1,max:50,step:.1},{key:"kcMult",title:"Keltner multiplier",type:"float",defval:1.5,min:.1,max:50,step:.1}],compute:(r,e)=>{let t=I(e,"length",20),n=De(r),i=fe(n,t),o=ae(rn(n,t),h=>h*I(e,"bbMult",2)),s=ae(Le(jn(r),t),h=>h*I(e,"kcMult",1.5)),a=K(ct(Ge(r),t),St(Ue(r),t),(h,p)=>(h+p)/2),l=K(a,i,(h,p)=>(h+p)/2),c=Qc(Te(n,l),t),u=n.map((h,p)=>{let m=o[p],f=s[p];return Number.isFinite(m)&&Number.isFinite(f)?m<f:false}).map((h,p)=>Number.isFinite(c[p])?h?W:z:null);return {plots:[{key:"mom",title:"Momentum",values:c,kind:"histogram",color:z,colors:td(c),base:0},{key:"squeeze",title:"Squeeze",values:c.map(h=>Number.isFinite(h)?0:Number.NaN),kind:"cross",color:Je,colors:u}]}}},gx=[zk,$k,Wk,Gk,Uk,Yk,Kk,Xk,jk,qk,Zk,Jk,Qk,eI,tI,nI,rI,iI,oI,sI,aI,lI,cI,dI,uI];var hI={type:"aroon",title:"Aroon",overlay:false,inputs:[D(14)],compute:(r,e)=>{let t=I(e,"length",14),n=ae(ax(Ge(r),t+1),o=>100*(t-o)/t),i=ae(lx(Ue(r),t+1),o=>100*(t-o)/t);return {plots:[{key:"up",title:"Aroon up",values:n,color:z,width:2},{key:"down",title:"Aroon down",values:i,color:W,width:2}]}}},pI={type:"average-directional-index",title:"Average Directional Index",shortTitle:"ADX",overlay:false,inputs:[D(14,"diLength","DI length"),D(14,"adxLength","ADX smoothing")],compute:(r,e)=>{let t=I(e,"diLength",14),n=I(e,"adxLength",14),i=r.length,o=new Array(i).fill(Number.NaN),s=new Array(i).fill(Number.NaN);for(let u=1;u<i;u++){let h=r[u].high-r[u-1].high,p=r[u-1].low-r[u].low;o[u]=h>p&&h>0?h:0,s[u]=p>h&&p>0?p:0;}let a=Le(jn(r),t),l=K(Le(o,t),a,(u,h)=>h===0?0:100*u/h),c=K(Le(s,t),a,(u,h)=>h===0?0:100*u/h),d=K(l,c,(u,h)=>u+h===0?0:100*Math.abs(u-h)/(u+h));return {plots:[{key:"adx",title:"ADX",values:Le(d,n),color:_,width:2},{key:"plusDi",title:"+DI",values:l,color:z},{key:"minusDi",title:"-DI",values:c,color:W}],levels:[{key:"threshold",price:25,color:J,lineStyle:"dotted"}]}}},mI={type:"vortex-indicator",title:"Vortex Indicator",shortTitle:"VI",overlay:false,inputs:[D(14)],compute:(r,e)=>{let t=I(e,"length",14),n=r.length,i=new Array(n).fill(Number.NaN),o=new Array(n).fill(Number.NaN);for(let a=1;a<n;a++)i[a]=Math.abs(r[a].high-r[a-1].low),o[a]=Math.abs(r[a].low-r[a-1].high);let s=we(jn(r),t);return {plots:[{key:"viPlus",title:"VI+",values:K(we(i,t),s,(a,l)=>l===0?Number.NaN:a/l),color:z,width:2},{key:"viMinus",title:"VI-",values:K(we(o,t),s,(a,l)=>l===0?Number.NaN:a/l),color:W,width:2}],levels:[{key:"one",price:1,color:J,lineStyle:"dotted"}]}}},bx=[hI,pI,mI];var fI={type:"average-true-range",title:"Average True Range",shortTitle:"ATR",overlay:false,inputs:[D(14),X()],compute:(r,e)=>({plots:[{key:"atr",title:"ATR",values:Vr(r,I(e,"length",14)),color:F(e,"color",_),width:2}]})},gI={type:"historical-volatility",title:"Historical Volatility",shortTitle:"HV",overlay:false,inputs:[D(10),{key:"annual",title:"Periods per year",type:"int",defval:365,min:1,max:1e5,step:1,tooltip:"Annualization factor (365 for daily crypto bars, 252 for stock sessions)"},X()],compute:(r,e)=>{let t=ae(He(ae(De(r),Math.log)),i=>i);return {plots:[{key:"hv",title:"HV",values:ae(rn(t,I(e,"length",10)),i=>i*Math.sqrt(I(e,"annual",365))*100),color:F(e,"color",_),width:2}]}}},bI={type:"chaikin-volatility",title:"Chaikin Volatility",shortTitle:"CHV",overlay:false,inputs:[D(10,"emaLength","EMA length"),D(10,"rocLength","RoC length"),X()],compute:(r,e)=>{let t=Q(Te(Ge(r),Ue(r)),I(e,"emaLength",10));return {plots:[{key:"cv",title:"Chaikin Vol",values:Ft(t,I(e,"rocLength",10)),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},vI={type:"mass-index",title:"Mass Index",shortTitle:"MI",overlay:false,inputs:[D(25),X()],compute:(r,e)=>{let t=Te(Ge(r),Ue(r)),n=Q(t,9),i=K(n,Q(n,9),(o,s)=>s===0?Number.NaN:o/s);return {plots:[{key:"mi",title:"Mass Index",values:we(i,I(e,"length",25)),color:F(e,"color",_),width:2}],levels:[{key:"reversal",price:27,color:J,lineStyle:"dotted"}]}}},yI={type:"standard-deviation",title:"Standard Deviation",shortTitle:"StdDev",overlay:false,inputs:[D(20),be(),X()],compute:(r,e)=>({plots:[{key:"stdev",title:"StdDev",values:rn(ee(r,F(e,"source","Close")),I(e,"length",20)),color:F(e,"color",_),width:2}]})},wI={type:"ulcer-index",title:"Ulcer Index",overlay:false,inputs:[D(14),X()],compute:(r,e)=>{let t=I(e,"length",14),n=De(r),i=K(n,ct(n,t),(s,a)=>a===0?0:100*(s-a)/a);return {plots:[{key:"ui",title:"Ulcer",values:ae(fe(ae(i,s=>s*s),t),Math.sqrt),color:F(e,"color",_),width:2}]}}},xI={type:"choppiness-index",title:"Choppiness Index",shortTitle:"CHOP",overlay:false,inputs:[D(14),X()],compute:(r,e)=>{let t=I(e,"length",14),n=we(jn(r),t),i=K(ct(Ge(r),t),St(Ue(r),t),(s,a)=>s-a);return {plots:[{key:"chop",title:"CHOP",values:K(n,i,(s,a)=>a>0&&s>0?100*Math.log10(s/a)/Math.log10(t):Number.NaN),color:F(e,"color",_),width:2}],levels:[{key:"upper",price:61.8,color:J},{key:"lower",price:38.2,color:J}]}}},vx=[fI,gI,bI,vI,yI,wI,xI];function nd(r){return r.map(e=>e.volume==null||!Number.isFinite(e.volume)?Number.NaN:e.high===e.low?0:(2*e.close-e.high-e.low)/(e.high-e.low)*e.volume)}var SI={type:"on-balance-volume",title:"On Balance Volume",shortTitle:"OBV",overlay:false,inputs:[X()],compute:(r,e)=>{let t=xt(r),n=He(De(r)),i=K(t,n,(o,s)=>s>0?o:s<0?-o:0);return {plots:[{key:"obv",title:"OBV",values:xs(i),color:F(e,"color",_),width:2}]}}},CI={type:"accumulation-distribution",title:"Accumulation / Distribution",shortTitle:"A/D",overlay:false,inputs:[X()],compute:(r,e)=>({plots:[{key:"ad",title:"A/D",values:xs(nd(r)),color:F(e,"color",_),width:2}]})},TI={type:"chaikin-money-flow",title:"Chaikin Money Flow",shortTitle:"CMF",overlay:false,inputs:[D(20),X()],compute:(r,e)=>{let t=I(e,"length",20);return {plots:[{key:"cmf",title:"CMF",values:K(we(nd(r),t),we(xt(r),t),(i,o)=>o===0?0:i/o),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},EI={type:"chaikin-oscillator",title:"Chaikin Oscillator",shortTitle:"Chaikin Osc",overlay:false,inputs:[D(3,"fastLength","Fast length"),D(10,"slowLength","Slow length"),X()],compute:(r,e)=>{let t=xs(nd(r));return {plots:[{key:"co",title:"Chaikin Osc",values:Te(Q(t,I(e,"fastLength",3)),Q(t,I(e,"slowLength",10))),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},PI={type:"ease-of-movement",title:"Ease of Movement",shortTitle:"EOM",overlay:false,inputs:[D(14),{key:"divisor",title:"Divisor",type:"int",defval:1e4,min:1,max:1e9,step:1},X()],compute:(r,e)=>{let t=I(e,"divisor",1e4),n=ee(r,"HL2"),i=He(n),o=r.map((s,a)=>{let l=i[a];return s.volume==null||!Number.isFinite(s.volume)||s.volume===0||!Number.isFinite(l)?Number.NaN:t*l*(s.high-s.low)/s.volume});return {plots:[{key:"eom",title:"EOM",values:fe(o,I(e,"length",14)),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},LI={type:"force-index",title:"Force Index",shortTitle:"FI",overlay:false,inputs:[D(13),X()],compute:(r,e)=>{let t=K(He(De(r)),xt(r),(n,i)=>n*i);return {plots:[{key:"force",title:"Force",values:Q(t,I(e,"length",13)),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},MI={type:"klinger-oscillator",title:"Klinger Oscillator",shortTitle:"KVO",overlay:false,inputs:[D(34,"fastLength","Fast length"),D(55,"slowLength","Slow length"),D(13,"signalLength","Signal length")],compute:(r,e)=>{let t=ee(r,"HLC3"),n=He(t),i=K(xt(r),n,(s,a)=>a>=0?s:-s),o=Te(Q(i,I(e,"fastLength",34)),Q(i,I(e,"slowLength",55)));return {plots:[{key:"kvo",title:"KVO",values:o,color:_,width:2},{key:"signal",title:"Signal",values:Q(o,I(e,"signalLength",13)),color:de}],levels:[{key:"zero",price:0,color:J}]}}},kI={type:"money-flow-index",title:"Money Flow Index",shortTitle:"MFI",overlay:false,inputs:[D(14),X()],compute:(r,e)=>{let t=I(e,"length",14),n=ee(r,"HLC3"),i=K(n,xt(r),(c,d)=>c*d),o=He(n),s=we(K(i,o,(c,d)=>d>0?c:0),t),a=we(K(i,o,(c,d)=>d<0?c:0),t);return {plots:[{key:"mfi",title:"MFI",values:K(s,a,(c,d)=>d===0?100:100-100/(1+c/d)),color:F(e,"color",_),width:2}],levels:[{key:"upper",price:80,color:J},{key:"lower",price:20,color:J}]}}};function yx(r,e){let t=new Array(r.length).fill(Number.NaN),n=1e3,i=false;for(let o=1;o<r.length;o++){let s=r[o].volume,a=r[o-1].volume,l=r[o-1].close;if(s==null||a==null||!Number.isFinite(s)||!Number.isFinite(a)||l===0){i&&(t[o]=n);continue}i=true,e(s,a)&&(n+=(r[o].close-l)/l*n),t[o]=n;}return t}var II={type:"negative-volume-index",title:"Negative Volume Index",shortTitle:"Negative Volume Index",overlay:false,inputs:[D(255,"signalLength","Signal length"),X()],compute:(r,e)=>{let t=yx(r,(n,i)=>n<i);return {plots:[{key:"nvi",title:"NVI",values:t,color:F(e,"color",_),width:2},{key:"signal",title:"Signal",values:Q(t,I(e,"signalLength",255)),color:de}]}}},AI={type:"positive-volume-index",title:"Positive Volume Index",shortTitle:"Positive Volume Index",overlay:false,inputs:[D(255,"signalLength","Signal length"),X()],compute:(r,e)=>{let t=yx(r,(n,i)=>n>i);return {plots:[{key:"pvi",title:"PVI",values:t,color:F(e,"color",_),width:2},{key:"signal",title:"Signal",values:Q(t,I(e,"signalLength",255)),color:de}]}}},RI={type:"price-volume-trend",title:"Price Volume Trend",shortTitle:"PVT",overlay:false,inputs:[X()],compute:(r,e)=>{let t=De(r),n=r.map((i,o)=>{if(o===0||i.volume==null||!Number.isFinite(i.volume))return Number.NaN;let s=t[o-1];return s===0?0:(t[o]-s)/s*i.volume});return {plots:[{key:"pvt",title:"PVT",values:xs(n),color:F(e,"color",_),width:2}]}}},DI={type:"volume-oscillator",title:"Volume Oscillator",shortTitle:"Vol Osc",overlay:false,inputs:[D(5,"fastLength","Fast length"),D(10,"slowLength","Slow length"),X()],compute:(r,e)=>{let t=xt(r),n=Q(t,I(e,"fastLength",5)),i=Q(t,I(e,"slowLength",10));return {plots:[{key:"vo",title:"Volume Osc",values:K(n,i,(s,a)=>a===0?Number.NaN:100*(s-a)/a),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},OI={type:"pvo",title:"Percentage Volume Oscillator",shortTitle:"PVO",overlay:false,inputs:[D(12,"fastLength","Fast length"),D(26,"slowLength","Slow length"),D(9,"signalLength","Signal length")],compute:(r,e)=>{let t=xt(r),n=Q(t,I(e,"fastLength",12)),i=Q(t,I(e,"slowLength",26)),o=K(n,i,(l,c)=>c===0?Number.NaN:100*(l-c)/c),s=Q(o,I(e,"signalLength",9)),a=Te(o,s);return {plots:[{key:"hist",title:"Histogram",values:a,kind:"histogram",color:z,colors:a.map(l=>Number.isFinite(l)?l>=0?z:W:null),base:0},{key:"pvo",title:"PVO",values:o,color:_,width:2},{key:"signal",title:"Signal",values:s,color:de}],levels:[{key:"zero",price:0,color:J}]}}},NI={type:"volume-flow-indicator",title:"Volume Flow Indicator",shortTitle:"Volume Flow Indicator",overlay:false,inputs:[D(130),{key:"coef",title:"Cutoff coefficient",type:"float",defval:.2,min:.01,max:10,step:.01},{key:"volCoef",title:"Volume cap",type:"float",defval:2.5,min:.1,max:50,step:.1},D(3,"smoothLength","Smoothing length")],compute:(r,e)=>{let t=I(e,"length",130),n=I(e,"coef",.2),i=I(e,"volCoef",2.5),o=ae(ee(r,"HLC3"),Math.log),s=He(o),a=rn(s,30),l=xt(r),c=fe(l,t),d=He(ee(r,"HLC3")),u=r.map((f,g)=>{let b=Number.isFinite(a[g])?n*a[g]*f.close:Number.NaN,y=l[g],v=g>0?c[g-1]:Number.NaN,S=d[g];if(!Number.isFinite(b)||!Number.isFinite(y)||!Number.isFinite(v)||!Number.isFinite(S))return Number.NaN;let P=Math.min(y,v*i);return S>b?P:S<-b?-P:0}),h=r.map((f,g)=>{let b=g>0?c[g-1]:Number.NaN;return Number.isFinite(b)&&b!==0?b:Number.NaN}),p=we(u,t),m=K(p,h,(f,g)=>f/g);return {plots:[{key:"vfi",title:"VFI",values:fe(m,I(e,"smoothLength",3)),color:_,width:2}],levels:[{key:"zero",price:0,color:J}]}}},FI={type:"intraday-intensity",title:"Intraday Intensity",shortTitle:"Intraday Intensity",overlay:false,inputs:[D(21),X()],compute:(r,e)=>{let t=I(e,"length",21);return {plots:[{key:"ii",title:"II%",values:K(we(nd(r),t),we(xt(r),t),(i,o)=>o===0?0:100*i/o),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},wx=[SI,CI,TI,EI,PI,LI,MI,kI,II,AI,RI,DI,OI,NI,FI];var dp=864e5;function up(r,e){if(r==="Week")return Math.floor((Math.floor(e/dp)+3)/7);if(r==="Month"||r==="Quarter"||r==="Year"){let t=new Date(e);return r==="Year"?t.getUTCFullYear():r==="Quarter"?t.getUTCFullYear()*4+Math.floor(t.getUTCMonth()/3):t.getUTCFullYear()*12+t.getUTCMonth()}return Math.floor(e/dp)}var VI={type:"parabolic-sar",title:"Parabolic SAR",shortTitle:"SAR",overlay:true,inputs:[{key:"start",title:"Start",type:"float",defval:.02,min:.001,max:1,step:.001},{key:"increment",title:"Increment",type:"float",defval:.02,min:.001,max:1,step:.001},{key:"maximum",title:"Max value",type:"float",defval:.2,min:.01,max:1,step:.01}],compute:(r,e)=>{let t=I(e,"start",.02),n=I(e,"increment",.02),i=I(e,"maximum",.2),o=r.length,s=new Array(o).fill(Number.NaN),a=new Array(o).fill(null);if(o>=2){let l=r[1].close>=r[0].close,c=l?r[0].low:r[0].high,d=l?r[0].high:r[0].low,u=t;for(let h=1;h<o;h++){let p=r[h];c+=u*(d-c),l?c=Math.min(c,r[h-1].low,h>=2?r[h-2].low:r[h-1].low):c=Math.max(c,r[h-1].high,h>=2?r[h-2].high:r[h-1].high),(l?p.low<c:p.high>c)?(l=!l,c=d,d=l?p.high:p.low,u=t):l&&p.high>d?(d=p.high,u=Math.min(i,u+n)):!l&&p.low<d&&(d=p.low,u=Math.min(i,u+n)),s[h]=c,a[h]=l?z:W;}}return {plots:[{key:"sar",title:"PSAR",values:s,kind:"circles",color:_,colors:a}]}}},xx="Bands",rd="Style",cp=[{on:"band1",mult:"band1Mult",color:"band1Color",fill:"band1Fill",fillColor:"band1FillColor",defMult:1,defOn:true,defColor:z},{on:"band2",mult:"band2Mult",color:"band2Color",fill:"band2Fill",fillColor:"band2FillColor",defMult:2,defOn:false,defColor:de},{on:"band3",mult:"band3Mult",color:"band3Color",fill:"band3Fill",fillColor:"band3FillColor",defMult:3,defOn:false,defColor:Rs[4]}],_I={type:"vwap",title:"Volume Weighted Average Price",shortTitle:"VWAP",overlay:true,inputs:[{key:"anchor",title:"Period",type:"string",defval:"Day",options:["Day","Week","Month","Quarter","Year"],tooltip:"Where the accumulation resets (UTC periods)"},be("HLC3"),...cp.flatMap((r,e)=>[{key:r.on,title:`Band ${e+1} multiplier`,type:"bool",defval:r.defOn,inline:r.on,group:xx},{key:r.mult,title:"",type:"float",defval:r.defMult,min:.1,max:10,step:.1,inline:r.on,group:xx}]),{...X(Je,"VWAP color"),group:rd},...cp.flatMap((r,e)=>[{...X(r.defColor,`Band ${e+1} color`,r.color),inline:r.color,group:rd},{key:r.fill,title:"Fill",type:"bool",defval:true,inline:r.color,group:rd},{...X(Pn(r.defColor),"",r.fillColor),inline:r.color,group:rd}])],compute:(r,e)=>{let t=F(e,"anchor","Day"),n=ee(r,F(e,"source","HLC3")),i=r.length,o=new Array(i).fill(Number.NaN),s=cp.filter(p=>sp(e,p.on,p.defOn)).map(p=>({mult:Math.max(0,I(e,p.mult,p.defMult)),color:F(e,p.color,p.defColor),fill:sp(e,p.fill,true),fillColor:F(e,p.fillColor,Pn(p.defColor)),up:new Array(i).fill(Number.NaN),down:new Array(i).fill(Number.NaN)})),a=Number.NaN,l=0,c=0,d=0;for(let p=0;p<i;p++){let m=r[p],f=up(t,m.time);f!==a&&(a=f,l=0,c=0,d=0);let g=m.volume;if(g!=null&&Number.isFinite(g)&&g>0){let v=n[p];l+=v*g,c+=v*v*g,d+=g;}if(d<=0)continue;let b=l/d,y=Math.sqrt(Math.max(0,c/d-b*b));o[p]=b;for(let v of s)v.up[p]=b+v.mult*y,v.down[p]=b-v.mult*y;}let u=[{key:"vwap",title:"VWAP",values:o,color:F(e,"color",Je),width:2}],h=[];return s.forEach((p,m)=>{u.push({key:`up${m}`,title:`Upper ${p.mult}\u03C3`,values:p.up,color:p.color},{key:`down${m}`,title:`Lower ${p.mult}\u03C3`,values:p.down,color:p.color}),p.fill&&h.push({key:`band${m}`,from:`up${m}`,to:`down${m}`,color:p.fillColor});}),{plots:u,bands:h}}},BI={type:"pivot-points",title:"Pivot Points",shortTitle:"Pivots",overlay:true,inputs:[{key:"anchor",title:"Period",type:"string",defval:"Day",options:["Day","Week","Month"]}],compute:(r,e)=>{let t=F(e,"anchor","Day"),n=new Map;for(let l of r){let c=up(t,l.time),d=n.get(c);d?(d.high=Math.max(d.high,l.high),d.low=Math.min(d.low,l.low),d.close=l.close):n.set(c,{high:l.high,low:l.low,close:l.close});}let i=r.length,o=()=>new Array(i).fill(Number.NaN),s={p:o(),r1:o(),s1:o(),r2:o(),s2:o(),r3:o(),s3:o()};for(let l=0;l<i;l++){let c=n.get(up(t,r[l].time)-1);if(!c)continue;let d=(c.high+c.low+c.close)/3;s.p[l]=d,s.r1[l]=2*d-c.low,s.s1[l]=2*d-c.high,s.r2[l]=d+(c.high-c.low),s.s2[l]=d-(c.high-c.low),s.r3[l]=c.high+2*(d-c.low),s.s3[l]=c.low-2*(c.high-d);}let a=(l,c,d)=>({key:l,title:c,kind:"step",values:s[l],color:d});return {plots:[a("p","P",de),a("r1","R1",W),a("s1","S1",z),a("r2","R2",W),a("s2","S2",z),a("r3","R3",W),a("s3","S3",z)]}}},HI={type:"52-week-high-low",title:"52 Week High/Low",shortTitle:"52W H/L",overlay:true,inputs:[{key:"weeks",title:"Weeks",type:"int",defval:52,min:1,max:520,step:1}],compute:(r,e)=>{let t=I(e,"weeks",52)*7*dp,n=r.length,i=new Array(n).fill(Number.NaN),o=new Array(n).fill(Number.NaN),s=[],a=[],l=0;for(let c=0;c<n;c++){let d=r[c];for(;s.length>0&&r[s[s.length-1]].high<=d.high;)s.pop();for(s.push(c);a.length>0&&r[a[a.length-1]].low>=d.low;)a.pop();for(a.push(c);r[l].time<d.time-t;)l+=1;for(;s[0]<l;)s.shift();for(;a[0]<l;)a.shift();i[c]=r[s[0]].high,o[c]=r[a[0]].low;}return {plots:[{key:"high",title:"52W high",values:i,kind:"step",color:z},{key:"low",title:"52W low",values:o,kind:"step",color:W}]}}},zI={type:"zigzag",title:"ZigZag",overlay:true,inputs:[{key:"deviation",title:"Deviation %",type:"float",defval:5,min:.01,max:100,step:.1},{key:"depth",title:"Depth",type:"int",defval:10,min:1,max:500,step:1},X()],compute:(r,e)=>{let t=I(e,"deviation",5)/100,n=I(e,"depth",10),i=[];if(r.length>1){let o=r[1].close>=r[0].close,s=o?{i:0,price:r[0].high}:{i:0,price:r[0].low};for(let a=1;a<r.length;a++){let l=r[a];o?l.high>=s.price?s={i:a,price:l.high}:l.low<=s.price*(1-t)&&a-(i[i.length-1]?.i??-n)>=n&&(i.push(s),o=false,s={i:a,price:l.low}):l.low<=s.price?s={i:a,price:l.low}:l.high>=s.price*(1+t)&&a-(i[i.length-1]?.i??-n)>=n&&(i.push(s),o=true,s={i:a,price:l.high});}i.push(s);}return {plots:[],polylines:[{key:"zigzag",points:i.map(o=>({xloc:"bar_time",x:r[o.i].time,price:o.price})),curved:false,closed:false,lineColor:F(e,"color",_),lineWidth:2,lineStyle:"solid",arrowLeft:false,arrowRight:false}]}}},$I={type:"williams-fractal",title:"Williams Fractal",shortTitle:"Fractals",overlay:true,inputs:[{key:"periods",title:"Periods",type:"int",defval:2,min:1,max:50,step:1}],compute:(r,e)=>{let t=I(e,"periods",2),n=[],i=(o,s,a)=>{let l=s(r[o]);for(let c=o-t;c<=o+t;c++)if(c!==o&&!a(l,s(r[c])))return false;return true};for(let o=t;o<r.length-t;o++)i(o,s=>s.high,(s,a)=>s>=a)&&n.push({time:r[o].time,position:"aboveBar",shape:"triangleup",color:z}),i(o,s=>s.low,(s,a)=>s<=a)&&n.push({time:r[o].time,position:"belowBar",shape:"triangledown",color:W});return {plots:[],markers:n}}},Sx=[VI,_I,BI,HI,zI,$I];var WI=[...px,...mx,...gx,...bx,...vx,...wx,...Sx];function Cx(){for(let r of WI)Ln(rx(r));}var hp=class{constructor(e,t={},n={}){Jw(),qh(),ip(),Cx();let i=GI(e),o=jr(t.theme),s={currentPriceLine:t.currentPriceLine??true,logScale:t.logScale??false,nativeBackend:t.nativeBackend??"auto",...Tp(t.animations),glow:t.glow??0,upColor:t.upColor??z,downColor:t.downColor??W,priceStyle:t.priceStyle??"candles"},a=t.renderer??ys;if(typeof a!="function")throw new Error("[vela] options.renderer must be a renderer class, e.g. import { LwcRenderer } from 'vela/renderers/lwc'. The 'lwc'/'native' string options were removed.");let l=n.renderer??new a(s),c=n.engines??[],d=n.dataFeed??new mr,u={market:{symbol:t.symbol,timeframe:t.timeframe,bars:t.bars,session:t.session,visibleRange:t.visibleRange,data:t.data},live:t.live??false,theme:o,defaultLanguage:t.defaultLanguage??c[0]?.language??"pine",drawings:t.drawings,volume:t.volume??true};this.rendererControl=new so(l),t.settings&&this.rendererControl.setSettingsVisibility(t.settings),this.dataControl=new po(d),this.orchestrator=new Xa(i,l,d,c,u,this.dataControl);let h=Ed();Object.keys(h).length>0&&this.rendererControl.set(h),this.panesControl=new ja(this.orchestrator),this.drawingsControl=new mo(this.orchestrator.drawings);}registerEngine(e,t){return this.orchestrator.registerEngine(e,t),this}addIndicator(e,t){return this.orchestrator.addIndicator(e,t)}addNativeIndicator(e,t){return this.orchestrator.addNativeIndicator(e,t)}availableNativeIndicators(){return this.orchestrator.availableNativeIndicators()}presentNativeIndicators(){return this.orchestrator.presentNativeIndicators()}indicators(){return this.orchestrator.listIndicators()}runScript(e,t){let n=this.addIndicator(e,t),i=new Set,o=()=>{try{n.remove();}catch{}};return new Promise(s=>{let a=false,l=this.on("script:run",d=>{if(d.id===n.id){if(a){for(let u of i)u(d);return}a=true,c(),s({ok:true,run:d,error:null,onUpdate:u=>(i.add(u),()=>i.delete(u)),remove:()=>{l(),i.clear(),o();}});}}),c=n.on("error",({error:d})=>{a||(a=true,l(),c(),o(),s({ok:false,run:null,error:d,onUpdate:()=>()=>{},remove:()=>{}}));});})}runIndicator(e,t){let n=this.addIndicator(e,t);return new Promise(i=>{let o=n.on("ready",()=>{o(),s(),i({ok:true,handle:n,error:null,context:null});}),s=n.on("error",({error:a})=>{o(),s(),n.context().catch(()=>null).then(l=>{try{n.remove();}catch{}i({ok:false,handle:null,error:a,context:l});});});})}setMarket(e){return this.orchestrator.setMarket(e)}get market(){return this.orchestrator.marketSnapshot()}ready(){return this.orchestrator.ready()}historyComplete(){return this.orchestrator.historyComplete()}inspect(){return this.orchestrator.inspect()}get renderer(){return this.rendererControl}get panes(){return this.panesControl}get data(){return this.dataControl}get drawings(){return this.drawingsControl}on(e,t){return this.orchestrator.events.on(e,t)}getVisibleRange(){return this.orchestrator.getVisibleRange()}setVisibleRange(e){return this.orchestrator.setVisibleRange(e),this}panBy(e){return this.orchestrator.panBy(e),this}setVisibleRangePreset(e){return this.orchestrator.setVisibleRangePreset(e),this}resize(){this.orchestrator.resize();}setTheme(e){return this.orchestrator.setTheme(jr(e)),this}destroy(){this.orchestrator.destroy();}};function GI(r){if(typeof r!="string")return r;let e=document.querySelector(r);if(!e)throw new Error(`[vela] container not found for selector "${r}"`);return e}var Tx=["symbol","timeframes","style","layout","indicators","actions","undo-redo","alerts","panels","screenshot"];var _i=new Map,Ss=new Map,Cs=new Map;function UI(r){return Ss.set(r.id,r),()=>{Ss.get(r.id)===r&&Ss.delete(r.id);}}function YI(r){Ss.delete(r);}function KI(){return [...Ss.values()]}var Ex=100;function XI(r){return Cs.set(r.id,r),()=>{Cs.get(r.id)===r&&Cs.delete(r.id);}}function jI(r){Cs.delete(r);}function qI(){return [...Cs.values()].sort((r,e)=>(r.order??Ex)-(e.order??Ex))}var pp=["indicators","screenshot"],Px=new Set(pp),ZI=new Set(Tx);function JI(r){if(Px.has(r))return _i.get(r)}function QI(r){return ZI.has(r.id)&&!Px.has(r.id)?(console.warn(`[vela] widget action "${r.id}": this built-in topbar slot is a stateful control and cannot be overridden \u2014 ignored. Overridable slots: ${pp.join(", ")}.`),()=>{}):(_i.set(r.id,r),()=>{_i.get(r.id)===r&&_i.delete(r.id);})}function eA(r){_i.delete(r);}function tA(r,e){let t=[..._i.values()].filter(n=>n.target===r);return t.sort((n,i)=>(n.order??0)-(i.order??0)),e?t.filter(n=>!n.when||n.when(e)):t}var Ts=new Map;function nA(r){return Ts.set(r.id,r),()=>{Ts.get(r.id)===r&&Ts.delete(r.id);}}function rA(r){Ts.delete(r);}function iA(){return [...Ts.values()].sort((r,e)=>(r.order??0)-(e.order??0))}var Es=new Map;function oA(r){return Es.set(r.id,r),()=>{Es.get(r.id)===r&&Es.delete(r.id);}}function sA(r){Es.delete(r);}function aA(){return [...Es.values()].sort((r,e)=>(r.order??0)-(e.order??0))}var Ps=new Map;function lA(r){return Ps.set(r.key,r),()=>{Ps.get(r.key)===r&&Ps.delete(r.key);}}function cA(r){Ps.delete(r);}function dA(r){return [...Ps.values()].filter(e=>e.scope===r)}var id;function uA(r){return id=r,()=>{id===r&&(id=void 0);}}function hA(){return id}var Ls=new Map;function pA(r,e){return Ls.set(r,e),()=>{Ls.get(r)===e&&Ls.delete(r);}}function mA(r){Ls.delete(r);}function fA(r){return {...Object.fromEntries(Ls),...r}}var Lx=280,mp=200,Mx=640;function gA(r,e=mp,t=Mx){let n=Number.isFinite(e)&&e>0?e:mp,i=Number.isFinite(t)?Math.max(t,n):Number.POSITIVE_INFINITY;return Number.isFinite(r)?Math.round(Math.min(Math.max(r,n),i)):n}function Bi(r){let e=r.description?.split("/")[0]?.trim();return e?e.replace(/\s+Perpetual$/i,""):r.ticker.replace(/[-_/]?(USDT|USDC|USD1|USDS|BUSD|USD|EUR|PERP)$/i,"")||r.ticker}function Hi(r){let e=r.trim().toUpperCase();return e?`https://crypto-icons.ledger.com/${encodeURIComponent(e)}.png`:void 0}var kx="https://api.binance.com/api/v3",bA="https://api.binance.us/api/v3",fp="https://fapi.binance.com/fapi/v1",vA="wss://stream.binance.com:9443",yA="wss://stream.binance.us:9443",wA="wss://fstream.binance.com",xA=15e3,SA=2e3,Ix={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",360:"6h",480:"8h",720:"12h",D:"1d",W:"1w",M:"1M"},Ax={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},CA=[1,3,5,15,30,60,120,240,360,480,720],TA={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",360:"6h",480:"8h",720:"12h"},EA=["1","3","5","15","30","45","60","120","180","240","D","W","M"];function Rx(r){return Ax[r]??Ax[r.toLowerCase()]??r}function gp(r){let e=r.trim().toUpperCase();return e.endsWith(".P")?{apiSymbol:e.slice(0,-2),isFutures:true}:{apiSymbol:e,isFutures:false}}function Dx(r){return r.map(e=>({time:Number(e[0]),open:Number(e[1]),high:Number(e[2]),low:Number(e[3]),close:Number(e[4]),volume:Number(e[5])}))}function PA(r){return {time:Number(r.t),open:Number(r.o),high:Number(r.h),low:Number(r.l),close:Number(r.c),volume:Number(r.v)}}function LA(r){let e=new Map;for(let t of r)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function MA(r,e){let t=new Map;for(let n of r){let i=Math.floor(n.time/e)*e,o=t.get(i);o?(o.high=Math.max(o.high,n.high),o.low=Math.min(o.low,n.low),o.close=n.close,o.volume=(o.volume??0)+(n.volume??0)):t.set(i,{time:i,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,i)=>n.time-i.time)}function kA(r){return CA.filter(e=>e<r&&r%e===0).sort((e,t)=>t-e)[0]??null}var od=class{constructor(){this.spotBaseUrl=null;this.spotBaseProbe=null;this.symbolsPromise=null;}info(){return {name:"binance",displayName:"Binance",requiresApiKey:false,supportedTimeframes:EA,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let{apiSymbol:i,isFutures:o}=gp(e),s=o?fp:await this.spotBase(),a=Rx(t),l=Ix[a];if(l)return LA(Dx(await this.fetchKlines(s,i,l,n)));let c=/^\d+$/.test(a)?parseInt(a,10):null,d=c!=null?kA(c):null;if(c==null||d==null)return console.warn(`[vela] Binance: timeframe "${t}" is not supported and cannot be aggregated.`),[];let u=c/d,h={...n,limit:n.limit!=null?n.limit*u+u:void 0},p=Dx(await this.fetchKlines(s,i,TA[d],h)),m=MA(p,c*6e4);return n.limit!=null&&m.length>n.limit?m.slice(-n.limit):m}catch(i){return console.warn(`[vela] Binance: failed to fetch ${e} ${t} \u2014 ${i instanceof Error?i.message:String(i)}`),[]}}async getSymbolInfo(e){let{apiSymbol:t,isFutures:n}=gp(e),i=n?fp:await this.spotBase(),o=n?`${i}/exchangeInfo`:`${i}/exchangeInfo?symbol=${t}`,a=(await this.json(o).catch(()=>null))?.symbols??[],l=n?a.find(u=>u.symbol===t):a[0];if(!l)return;let c=l.filters?.find(u=>u.filterType==="PRICE_FILTER"),d=c?parseFloat(c.tickSize??"0.01"):.01;return {ticker:e,tickerid:`BINANCE:${e}`,prefix:"BINANCE",description:`${l.baseAsset} / ${l.quoteAsset}${n?" Perpetual":""}`,type:n?"futures":"crypto",basecurrency:l.baseAsset,currency:l.quoteAsset,mintick:d,pricescale:Math.round(1/d),timezone:"Etc/UTC",session:"24x7"}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=Promise.all([this.listSpot().catch(()=>[]),this.listFutures().catch(()=>[])]).then(([e,t])=>[...e,...t])),this.symbolsPromise}resolveSymbolIcon(e){return Hi(Bi(e))}subscribe(e,t,n){let{apiSymbol:i,isFutures:o}=gp(e),s=Ix[Rx(t)];return s&&typeof WebSocket<"u"?this.streamKlines(e,t,i,o,s,n):this.pollBars(e,t,n)}streamKlines(e,t,n,i,o,s){let a=false,l=null,c=null,d=null,u=null,h=`${n.toLowerCase()}@kline_${o}`,p=()=>{d&&(clearTimeout(d),d=null);},m=()=>{if(!(a||u)){p(),c&&(clearTimeout(c),c=null);try{l?.close();}catch{}l=null,console.warn(`[vela] Binance: ${e} ${t} stream delivered no data; falling back to polling.`),u=this.pollBars(e,t,s);}},f=async()=>{if(a)return;let g=i?wA:await this.spotWsBase();a||(l=new WebSocket(`${g}/ws/${h}`),d=setTimeout(m,xA),l.onmessage=b=>{if(!(a||u))try{let y=JSON.parse(typeof b.data=="string"?b.data:"");y.k&&(p(),s(PA(y.k)));}catch{}},l.onclose=()=>{!a&&!u&&(c=setTimeout(()=>{f();},SA));},l.onerror=()=>{try{l?.close();}catch{}});};return f(),()=>{a=true,p(),c&&clearTimeout(c),u?.();try{l?.close();}catch{}}}async spotWsBase(){return (await this.spotBase()).includes("binance.us")?yA:vA}pollBars(e,t,n){let i=false,o=null,s=async()=>{if(!i){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}i||(o=setTimeout(()=>{s();},3e3));}};return o=setTimeout(()=>{s();},3e3),()=>{i=true,o&&clearTimeout(o);}}async listSpot(){let e=await this.spotBase();return ((await this.json(`${e}/exchangeInfo`)).symbols??[]).filter(n=>n.status==="TRADING").map(n=>({ticker:n.symbol,description:`${n.baseAsset} / ${n.quoteAsset}`,type:"crypto"}))}async listFutures(){return ((await this.json(`${fp}/exchangeInfo`)).symbols??[]).filter(t=>t.contractType==="PERPETUAL"&&t.status==="TRADING").map(t=>({ticker:`${t.symbol}.P`,description:`${t.baseAsset} / ${t.quoteAsset} Perpetual`,type:"futures"}))}async fetchKlines(e,t,n,i){if(i.from!=null)return this.paginateForward(e,t,n,i.from,i.to??Date.now(),i.limit);let o=i.limit??500;return o>1e3?this.paginateBackward(e,t,n,o,i.to):this.klinesChunk(e,{symbol:t,interval:n,limit:o,endTime:i.to})}async paginateForward(e,t,n,i,o,s){let a=[],l=i;for(;l<o;){let c=await this.klinesChunk(e,{symbol:t,interval:n,limit:1e3,startTime:l,endTime:o});if(c.length===0||(a.push(...c),l=Number(c[c.length-1][6])+1,c.length<1e3)||s&&a.length>=s)break}return s?a.slice(0,s):a}async paginateBackward(e,t,n,i,o){let s=[],a=i,l=o,c=Math.ceil(i/1e3)+5;for(;a>0&&c-- >0;){let d=Math.min(a,1e3),u=await this.klinesChunk(e,{symbol:t,interval:n,limit:d,endTime:l});if(u.length===0||(s=u.concat(s),a-=u.length,l=Number(u[0][0])-1,u.length<d))break}return s}async klinesChunk(e,t){let n=new URL(`${e}/klines`);n.searchParams.set("symbol",t.symbol),n.searchParams.set("interval",t.interval),t.limit&&n.searchParams.set("limit",String(Math.min(t.limit,1e3))),t.startTime!=null&&n.searchParams.set("startTime",String(t.startTime)),t.endTime!=null&&n.searchParams.set("endTime",String(t.endTime));let i=await this.json(n.toString());return Array.isArray(i)?i.length>0&&!Array.isArray(i[0])?[]:i:[]}spotBase(){return this.spotBaseUrl?Promise.resolve(this.spotBaseUrl):(this.spotBaseProbe||(this.spotBaseProbe=(async()=>{try{for(let e of [kx,bA])try{if((await fetch(`${e}/ping`,{signal:AbortSignal.timeout(5e3)})).ok)return this.spotBaseUrl=e}catch{}return kx}finally{this.spotBaseProbe=null;}})()),this.spotBaseProbe)}async json(e){let t=await fetch(e);if(!t.ok)throw new Error(`Binance HTTP ${t.status} for ${e}`);return t.json()}};var IA="https://api.hyperliquid.xyz/info",AA="wss://api.hyperliquid.xyz/ws",RA=15e3,DA=2e3,Ox={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",480:"8h",720:"12h",D:"1d",W:"1w",M:"1M"},Nx={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},OA=[1,3,5,15,30,60,120,240,480,720],NA={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",480:"8h",720:"12h"},FA=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],Fx={D:864e5,W:6048e5,M:2592e6};function VA(r){if(Fx[r])return Fx[r];let e=parseInt(r,10);return Number.isFinite(e)&&e>0?e*6e4:36e5}function Vx(r){return Nx[r]??Nx[r.toLowerCase()]??r}function bp(r){let e=r.trim();return e.includes("/")?e:e.toUpperCase()}function vp(r){return {time:Number(r.t),open:Number(r.o),high:Number(r.h),low:Number(r.l),close:Number(r.c),volume:Number(r.v)}}function _A(r){let e=new Map;for(let t of r)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function BA(r,e){let t=new Map;for(let n of r){let i=Math.floor(n.time/e)*e,o=t.get(i);o?(o.high=Math.max(o.high,n.high),o.low=Math.min(o.low,n.low),o.close=n.close,o.volume=(o.volume??0)+(n.volume??0)):t.set(i,{time:i,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,i)=>n.time-i.time)}function HA(r){return OA.filter(e=>e<r&&r%e===0).sort((e,t)=>t-e)[0]??null}var sd=class{constructor(){this.metaPromise=null;this.spotMetaPromise=null;this.symbolsPromise=null;}info(){return {name:"hyperliquid",displayName:"Hyperliquid",requiresApiKey:false,supportedTimeframes:FA,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let i=bp(e),o=Vx(t),s=Ox[o];if(s)return _A((await this.fetchCandles(i,s,VA(o),n)).map(vp));let a=/^\d+$/.test(o)?parseInt(o,10):null,l=a!=null?HA(a):null;if(a==null||l==null)return console.warn(`[vela] Hyperliquid: timeframe "${t}" is not supported and cannot be aggregated.`),[];let c=a/l,d={...n,limit:n.limit!=null?n.limit*c+c:void 0},u=(await this.fetchCandles(i,NA[l],l*6e4,d)).map(vp),h=BA(u,a*6e4);return n.limit!=null&&h.length>n.limit?h.slice(-n.limit):h}catch(i){return console.warn(`[vela] Hyperliquid: failed to fetch ${e} ${t} \u2014 ${i instanceof Error?i.message:String(i)}`),[]}}async getSymbolInfo(e){let t=bp(e),i=(await this.fetchMeta().catch(()=>null))?.universe?.find(o=>o.name===t);if(i){let o=Bx(Math.max(0,6-(i.szDecimals??2)));return _x(e,t,"USD","futures",`${t} / USD Perpetual`,o)}if(t.includes("/")){let o=await this.fetchSpotMeta().catch(()=>null),s=o?.universe?.find(u=>u.name===t),a=s&&o?.tokens?o.tokens[s.tokens?.[0]??-1]:void 0,[l=t,c="USDC"]=t.split("/"),d=Bx(Math.max(0,8-(a?.szDecimals??2)));return _x(e,l,c,"crypto",`${l} / ${c}`,d)}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=Promise.all([this.listPerps().catch(()=>[]),this.listSpot().catch(()=>[])]).then(([e,t])=>[...e,...t])),this.symbolsPromise}resolveSymbolIcon(e){return Hi(Bi(e))}subscribe(e,t,n){let i=bp(e),o=Ox[Vx(t)];return o&&typeof WebSocket<"u"?this.streamCandles(e,t,i,o,n):this.pollBars(e,t,n)}async listPerps(){return ((await this.fetchMeta()).universe??[]).filter(t=>!t.isDelisted).map(t=>({ticker:t.name,description:`${t.name} / USD Perpetual`,type:"futures"}))}async listSpot(){let e=await this.fetchSpotMeta(),t=e.tokens??[],n=i=>i!=null?t[i]?.name??null:null;return (e.universe??[]).map(i=>{let o=n(i.tokens?.[0]),s=n(i.tokens?.[1]),a=o&&s?`${o} / ${s}`:i.name;return {ticker:i.name,description:a,type:"crypto"}})}async fetchCandles(e,t,n,i){let o=i.to??Date.now(),s=i.from!=null?i.from:o-((i.limit??500)+2)*n,a=await this.candleSnapshot(e,t,s,o);return i.from==null&&i.limit!=null&&a.length>i.limit?a.slice(-i.limit):a}async candleSnapshot(e,t,n,i){let o=await this.post({type:"candleSnapshot",req:{coin:e,interval:t,startTime:Math.floor(n),endTime:Math.floor(i)}});return Array.isArray(o)?o:[]}streamCandles(e,t,n,i,o){let s=false,a=null,l=null,c=null,d=null,u=null,h=()=>{d&&(clearTimeout(d),d=null);},p=()=>{l&&(clearInterval(l),l=null);},m=()=>{if(!(s||u)){h(),p(),c&&(clearTimeout(c),c=null);try{a?.close();}catch{}a=null,console.warn(`[vela] Hyperliquid: ${e} ${t} stream delivered no data; falling back to polling.`),u=this.pollBars(e,t,o);}},f=()=>{s||u||(a=new WebSocket(AA),d=setTimeout(m,RA),a.onopen=()=>{try{a?.send(JSON.stringify({method:"subscribe",subscription:{type:"candle",coin:n,interval:i}}));}catch{}l=setInterval(()=>{try{a?.send(JSON.stringify({method:"ping"}));}catch{}},3e4);},a.onmessage=g=>{if(!(s||u))try{let b=JSON.parse(typeof g.data=="string"?g.data:"");b.channel==="candle"&&b.data&&b.data.s===n&&(h(),o(vp(b.data)));}catch{}},a.onclose=()=>{p(),!s&&!u&&(c=setTimeout(f,DA));},a.onerror=()=>{try{a?.close();}catch{}});};return f(),()=>{s=true,h(),p(),c&&clearTimeout(c),u?.();try{a?.close();}catch{}}}pollBars(e,t,n){let i=false,o=null,s=async()=>{if(!i){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}i||(o=setTimeout(()=>{s();},3e3));}};return o=setTimeout(()=>{s();},3e3),()=>{i=true,o&&clearTimeout(o);}}fetchMeta(){return this.metaPromise??(this.metaPromise=this.post({type:"meta"}).then(e=>e))}fetchSpotMeta(){return this.spotMetaPromise??(this.spotMetaPromise=this.post({type:"spotMeta"}).then(e=>e))}async post(e){let t=await fetch(IA,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Hyperliquid HTTP ${t.status}`);return t.json()}};function _x(r,e,t,n,i,o){return {ticker:r,tickerid:`HYPERLIQUID:${r}`,prefix:"HYPERLIQUID",description:i,type:n,basecurrency:e,currency:t,mintick:o,pricescale:Math.round(1/o),timezone:"Etc/UTC",session:"24x7"}}function Bx(r){return Math.pow(10,-r)}var zA={now:()=>Date.now(),delay:r=>new Promise(e=>setTimeout(e,r))},ad=class{constructor(e,t,n=zA){this.maxConcurrent=e;this.minIntervalMs=t;this.clock=n;this.active=0;this.waiters=[];this.nextStartAt=0;this.pausedUntil=0;}async run(e){await this.acquire();try{return await this.waitForTurn(),await e()}finally{this.release();}}pauseFor(e){e>0&&(this.pausedUntil=Math.max(this.pausedUntil,this.clock.now()+e));}async waitForTurn(){for(;;){let e=this.clock.now(),t=Math.max(this.pausedUntil-e,this.nextStartAt-e);if(t<=0)break;await this.clock.delay(t);}this.nextStartAt=Math.max(this.clock.now(),this.nextStartAt)+this.minIntervalMs;}acquire(){return this.active<this.maxConcurrent?(this.active+=1,Promise.resolve()):new Promise(e=>{this.waiters.push(()=>{this.active+=1,e();});})}release(){this.active-=1;let e=this.waiters.shift();e&&e();}};var yp="https://api.exchange.coinbase.com",$A="wss://ws-feed.exchange.coinbase.com",WA={Accept:"application/json"},GA=15e3,UA=2e3,YA=5e3,ld=300,KA=4,XA=120,jA=4,qA=600,ZA=400;function JA(r,e){let t=Number(r.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t*1e3:e}var Hx={1:60,5:300,15:900,60:3600,360:21600,D:86400},zx={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},QA=[1,5,15,60,360,1440],e2={1:60,5:300,15:900,60:3600,360:21600,1440:86400},t2=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],wp=864e5;function $x(r){return zx[r]??zx[r.toLowerCase()]??r}function xp(r){return r.trim().toUpperCase()}function n2(r){return {time:Number(r[0])*1e3,open:Number(r[3]),high:Number(r[2]),low:Number(r[1]),close:Number(r[4]),volume:Number(r[5])}}function Sp(r){let e=new Map;for(let t of r)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function r2(r,e){return Wx(r,t=>Math.floor(t/e)*e)}function i2(r,e){return Wx(r,e==="W"?o2:s2)}function Wx(r,e){let t=new Map;for(let n of r){let i=e(n.time),o=t.get(i);o?(o.high=Math.max(o.high,n.high),o.low=Math.min(o.low,n.low),o.close=n.close,o.volume=(o.volume??0)+(n.volume??0)):t.set(i,{time:i,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,i)=>n.time-i.time)}function o2(r){let e=new Date(r),t=(e.getUTCDay()+6)%7;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()-t)}function s2(r){let e=new Date(r);return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)}function a2(r){return QA.filter(e=>e<r&&r%e===0).sort((e,t)=>t-e)[0]??null}function Cp(r,e){return e!=null&&r.length>e?r.slice(-e):r}var cd=class{constructor(){this.symbolsPromise=null;this.gate=new ad(KA,XA);}info(){return {name:"coinbase",displayName:"Coinbase",requiresApiKey:false,supportedTimeframes:t2,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let i=xp(e),o=$x(t),s=Hx[o];if(s)return Sp(await this.fetchCandles(i,s,n));if(o==="W"||o==="M"){let h=o==="W"?7*wp:31*wp,p=n.from!=null?n:{...n,limit:n.limit!=null?Math.ceil(n.limit*h/wp)+31:void 0},m=await this.fetchCandles(i,86400,p);return Cp(i2(m,o),n.limit)}let a=/^\d+$/.test(o)?parseInt(o,10):null,l=a!=null?a2(a):null;if(a==null||l==null)return console.warn(`[vela] Coinbase: timeframe "${t}" is not supported and cannot be aggregated.`),[];let c=a/l,d={...n,limit:n.limit!=null?n.limit*c+c:void 0},u=await this.fetchCandles(i,e2[l],d);return Cp(r2(u,a*6e4),n.limit)}catch(i){return console.warn(`[vela] Coinbase: failed to fetch ${e} ${t} \u2014 ${i instanceof Error?i.message:String(i)}`),[]}}async getSymbolInfo(e){let t=xp(e),n=await this.json(`${yp}/products/${t}`).catch(()=>null);if(!n||!n.id)return;let i=n.quote_increment!=null?parseFloat(n.quote_increment):.01,o=i>0?i:.01;return {ticker:e,tickerid:`COINBASE:${e}`,prefix:"COINBASE",description:`${n.base_currency} / ${n.quote_currency}`,type:"crypto",basecurrency:n.base_currency,currency:n.quote_currency,mintick:o,pricescale:Math.round(1/o),timezone:"Etc/UTC",session:"24x7"}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=this.fetchProducts().then(e=>e.filter(t=>t.status==="online"&&!t.trading_disabled).map(t=>({ticker:t.id,description:`${t.base_currency} / ${t.quote_currency}`,type:"crypto"}))).catch(()=>[])),this.symbolsPromise}resolveSymbolIcon(e){return Hi(Bi(e))}subscribe(e,t,n){let i=Hx[$x(t)];return i&&typeof WebSocket<"u"?this.streamTicker(e,t,i,n):this.pollBars(e,t,n)}async fetchProducts(){let e=await this.json(`${yp}/products`);return Array.isArray(e)?e:[]}async fetchCandles(e,t,n){return n.from!=null?this.paginateForward(e,t,n.from,n.to??Date.now(),n.limit):this.paginateBackward(e,t,n.limit??500,n.to??Date.now())}async paginateBackward(e,t,n,i){let o=t*1e3,s=[],a=n,l=i,c=Math.ceil(n/ld)+4;for(;a>0&&c-- >0;){let d=Math.min(a,ld),u=l-d*o,h=await this.candlesChunk(e,t,u,l);if(h.length===0||(s=h.concat(s),a-=h.length,l=h[0].time-1,h.length<d))break}return Cp(Sp(s),n)}async paginateForward(e,t,n,i,o){let s=t*1e3,a=[],l=n,c=Math.ceil((i-n)/(ld*s))+4;for(;l<i&&c-- >0;){let u=Math.min(l+ld*s,i),h=await this.candlesChunk(e,t,l,u);if(h.length>0&&a.push(...h),l=u,o!=null&&a.length>=o)break}let d=Sp(a);return o!=null?d.slice(0,o):d}async candlesChunk(e,t,n,i){let o=new URL(`${yp}/products/${e}/candles`);o.searchParams.set("granularity",String(t)),o.searchParams.set("start",String(Math.floor(n/1e3))),o.searchParams.set("end",String(Math.floor(i/1e3)));let s=await this.json(o.toString());return !Array.isArray(s)||s.length>0&&!Array.isArray(s[0])?[]:s.map(n2).sort((a,l)=>a.time-l.time)}streamTicker(e,t,n,i){let o=xp(e),s=n*1e3,a=T=>Math.floor(T/s)*s,l=false,c=null,d=null,u=null,h=null,p=null,m=null,f=()=>{u&&(clearTimeout(u),u=null);},g=()=>{h&&(clearInterval(h),h=null);},b=()=>{m&&i({...m});},y=async T=>{try{let E=await this.getBars(e,t,{limit:2});if(l||E.length===0)return;T&&E.length>=2&&i(E[E.length-2]);let x=E[E.length-1];m=m&&m.time===x.time?{...x,high:Math.max(x.high,m.high),low:Math.min(x.low,m.low),close:m.close}:{...x},b();}catch{}},v=(T,E)=>{let x=Number(T);if(!Number.isFinite(x))return;let L=a(E);!m||L>m.time?(m={time:L,open:x,high:x,low:x,close:x,volume:0},b(),y(false)):L===m.time&&(m={...m,close:x,high:Math.max(m.high,x),low:Math.min(m.low,x)},b());},S=()=>{if(!(l||p)){f(),g(),d&&(clearTimeout(d),d=null);try{c?.close();}catch{}c=null,console.warn(`[vela] Coinbase: ${e} ${t} stream delivered no data; falling back to polling.`),p=this.pollBars(e,t,i);}},P=()=>{l||p||(c=new WebSocket($A),u=setTimeout(S,GA),c.onopen=()=>{try{c?.send(JSON.stringify({type:"subscribe",product_ids:[o],channels:["ticker"]}));}catch{}y(false),h=setInterval(()=>{y(false);},YA);},c.onmessage=T=>{if(!(l||p))try{let E=JSON.parse(typeof T.data=="string"?T.data:"");E.type==="ticker"&&E.product_id===o&&E.price!=null&&(f(),v(E.price,E.time?Date.parse(E.time):Date.now()));}catch{}},c.onclose=()=>{g(),!l&&!p&&(d=setTimeout(P,UA));},c.onerror=()=>{try{c?.close();}catch{}});};return P(),()=>{l=true,f(),g(),d&&clearTimeout(d),p?.();try{c?.close();}catch{}}}pollBars(e,t,n){let i=false,o=null,s=async()=>{if(!i){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}i||(o=setTimeout(()=>{s();},3e3));}};return o=setTimeout(()=>{s();},3e3),()=>{i=true,o&&clearTimeout(o);}}async json(e){return (await this.request(e)).json()}async request(e){for(let t=0;;t+=1){let n=await this.gate.run(()=>fetch(e,{headers:WA}));if(n.status===429&&t<jA){let i=qA*2**t+Math.random()*ZA;this.gate.pauseFor(Math.max(JA(n,0),i));continue}if(!n.ok)throw new Error(`Coinbase HTTP ${n.status} for ${e}`);return n}}};
1007
+ `;function UM(r){let e=r.getElementById(_w);e||(e=r.createElement("style"),e.id=_w,r.head.appendChild(e)),e.textContent=GM;}function _h(r){return lt(r)?"#ffffff":"#000000"}function Bh(r,e){let t=lt(e);r.style.color=t?"#ffffff":"#000000",r.style.setProperty("--vela-attr-shadow",t?"rgba(0,0,0,0.45)":"rgba(255,255,255,0.55)");}function Bw(r,e,t){let n=r.createElement("div");return n.className="vela-attribution-custom",Object.assign(n.style,{position:"absolute",zIndex:"6",pointerEvents:"auto",display:"flex",alignItems:"center",lineHeight:"1"}),n.style.color=_h(t),n.innerHTML=e,n.dataset.velaScreenshot="1",n}function Hw(r,e){UM(r);let t=r.createElement("a");t.className="vela-attribution",t.href=WM,t.target="_blank",t.rel="noopener",t.title="Charting by Vela",t.setAttribute("aria-label","Charting by Vela"),Object.assign(t.style,{position:"absolute",zIndex:"6",pointerEvents:"auto",cursor:"pointer"}),Bh(t,e),t.dataset.velaScreenshot="1";let n=r.createElement("span");n.className="vela-attr-symbol",n.setAttribute("aria-hidden","true"),n.innerHTML=Fw;let i=r.createElement("span");return i.className="vela-attr-wordmark",i.innerHTML=Vw,t.append(n,i),t}function Uc(r){if(!r||r==="transparent")return false;let e=/rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*,\s*([\d.]+)\s*\)/.exec(r);return e?parseFloat(e[1])>.001:true}function zw(r,e,t){let n=r.borderTopLeftRadius,i=parseFloat(n)||0,o=n.endsWith("%")?i/100*Math.min(e,t):i;return Math.max(0,Math.min(o,Math.min(e,t)/2))}function Hh(r,e,t,n,i,o){r.beginPath(),o>0&&typeof r.roundRect=="function"?r.roundRect(e,t,n,i,o):r.rect(e,t,n,i);}function YM(r){try{let e=r.ownerDocument.createElement("canvas");e.width=1,e.height=1;let t=e.getContext("2d");return t?(t.drawImage(r,0,0,1,1),e.toDataURL(),!0):!1}catch{return false}}function Yc(r,e,t){let n=e.ownerDocument.defaultView;if(!n)return;r.save(),r.scale(t.dpr,t.dpr);let i=(c,d,u)=>{let h=c.textContent?.replace(/\s+/g," ").trim();if(!h)return;let p=c.ownerDocument.createRange();p.selectNodeContents(c);let m=p.getBoundingClientRect();m.width<=0||m.height<=0||(r.globalAlpha=u,r.fillStyle=d.color,r.font=`${d.fontStyle} ${d.fontWeight} ${d.fontSize} ${d.fontFamily}`,r.textBaseline="middle",r.textAlign="left",r.fillText(h,m.left-t.left,m.top-t.top+m.height/2));},o=(c,d,u)=>{if(!c.complete||c.naturalWidth<=0||!YM(c))return;let h=c.getBoundingClientRect();if(h.width<=0||h.height<=0)return;let p=h.left-t.left,m=h.top-t.top;r.save(),r.globalAlpha=u,Hh(r,p,m,h.width,h.height,zw(d,h.width,h.height)),r.clip(),r.drawImage(c,p,m,h.width,h.height),r.restore();},s=(c,d)=>{for(let u of c.children){if(u.hasAttribute("transform"))continue;let h=u.tagName.toLowerCase();if(h==="g"){s(u,d);continue}let p=b=>parseFloat(u.getAttribute(b)??"0")||0,m=null;if(h==="path"){let b=u.getAttribute("d");b&&(m=new Path2D(b));}else if(h==="circle")m=new Path2D,m.arc(p("cx"),p("cy"),p("r"),0,Math.PI*2);else if(h==="ellipse")m=new Path2D,m.ellipse(p("cx"),p("cy"),p("rx"),p("ry"),0,0,Math.PI*2);else if(h==="rect")m=new Path2D,m.rect(p("x"),p("y"),p("width"),p("height"));else if(h==="line")m=new Path2D,m.moveTo(p("x1"),p("y1")),m.lineTo(p("x2"),p("y2"));else if(h==="polyline"||h==="polygon"){let b=(u.getAttribute("points")??"").trim().split(/[\s,]+/).map(Number);if(b.length<4||b.some(Number.isNaN))continue;m=new Path2D,m.moveTo(b[0],b[1]);for(let y=2;y+1<b.length;y+=2)m.lineTo(b[y],b[y+1]);h==="polygon"&&m.closePath();}if(!m)continue;let f=n.getComputedStyle(u);f.fill&&f.fill!=="none"&&Uc(f.fill)&&(r.globalAlpha=d*(parseFloat(f.fillOpacity)||1),r.fillStyle=f.fill,r.fill(m));let g=parseFloat(f.strokeWidth)||0;f.stroke&&f.stroke!=="none"&&Uc(f.stroke)&&g>0&&(r.globalAlpha=d*(parseFloat(f.strokeOpacity)||1),r.strokeStyle=f.stroke,r.lineWidth=g,(f.strokeLinecap==="round"||f.strokeLinecap==="square"||f.strokeLinecap==="butt")&&(r.lineCap=f.strokeLinecap),(f.strokeLinejoin==="round"||f.strokeLinejoin==="bevel"||f.strokeLinejoin==="miter")&&(r.lineJoin=f.strokeLinejoin),r.stroke(m));}},a=(c,d)=>{let u=c.getBoundingClientRect();if(u.width<=0||u.height<=0)return;let h=n.getComputedStyle(c);if(h.display==="none"||h.visibility==="hidden")return;let p=d*(parseFloat(h.opacity)||1);if(p<=.001)return;let m=c.viewBox.baseVal,f=m&&m.width>0?m.width:u.width,g=m&&m.height>0?m.height:u.height;r.save(),r.translate(u.left-t.left,u.top-t.top),r.scale(u.width/f,u.height/g),m&&r.translate(-m.x,-m.y),s(c,p),r.restore();},l=(c,d)=>{let u=n.getComputedStyle(c);if(u.display==="none"||u.visibility==="hidden")return;let h=d*(parseFloat(u.opacity)||1);if(h<=.001)return;let p=c.getBoundingClientRect();if(p.width>0&&p.height>0){let m=p.left-t.left,f=p.top-t.top,g=zw(u,p.width,p.height);Uc(u.backgroundColor)&&(r.globalAlpha=h,r.fillStyle=u.backgroundColor,Hh(r,m,f,p.width,p.height,g),r.fill());let b=parseFloat(u.borderTopWidth)||0;b>0&&u.borderTopStyle!=="none"&&Uc(u.borderTopColor)&&(r.globalAlpha=h,r.strokeStyle=u.borderTopColor,r.lineWidth=b,Hh(r,m+b/2,f+b/2,p.width-b,p.height-b,Math.max(0,g-b/2)),r.stroke());}for(let m of c.childNodes)m.nodeType===3?i(m,u,h):m instanceof n.HTMLImageElement?o(m,n.getComputedStyle(m),h):m instanceof n.SVGSVGElement?a(m,h):m instanceof n.HTMLElement&&l(m,h);};e instanceof n.HTMLElement&&l(e,1),r.restore();}function $w(r,e,t,n,i){let o=Math.max(0,e),s=Math.min(r.length-1,t);if(o>s)return null;let a=1/0,l=-1/0;for(let v=o;v<=s;v+=1){let S=r[v];S.volume!=null&&S.volume>0&&(S.low<a&&(a=S.low),S.high>l&&(l=S.high));}if(!Number.isFinite(a))return null;let c=l>a?Math.max(1,Math.round(n)):1,d=l>a?(l-a)/c:1,u=Array.from({length:c},(v,S)=>({price:a+S*d,up:0,down:0}));for(let v=o;v<=s;v+=1){let S=r[v],P=S.volume;if(!(P!=null&&P>0))continue;let T=S.close>=S.open?"up":"down",E=S.high-S.low;if(E<=0){let w=zh(Math.floor((S.low-a)/d),c);u[w][T]+=P;continue}let x=zh(Math.floor((S.low-a)/d),c),L=zh(Math.floor((S.high-a)/d-1e-9),c);for(let w=x;w<=L;w+=1){let M=a+w*d,k=Math.min(S.high,M+d)-Math.max(S.low,M);k>0&&(u[w][T]+=P*k/E);}}let h=0,p=0,m=0;for(let v=0;v<c;v+=1){let S=u[v].up+u[v].down;h+=S,S>p&&(p=S,m=v);}if(p<=0)return null;let f=h*Math.min(1,Math.max(0,i)),g=m,b=m,y=p;for(;y<f&&(g>0||b<c-1);){let v=g>0?u[g-1].up+u[g-1].down:-1,S=b<c-1?u[b+1].up+u[b+1].down:-1;S>v?(b+=1,y+=S):(g-=1,y+=v);}return {rows:u,rowH:d,min:a,maxTotal:p,poc:m,vaFrom:g,vaTo:b}}function zh(r,e){return r<0?0:r>=e?e-1:r}function Ww(r,e,t,n){let{rows:i,rowH:o,maxTotal:s,poc:a,vaFrom:l,vaTo:c}=e,{rightX:d,maxW:u,yOf:h}=t;if(!(s<=0||u<=0)){for(let p=0;p<i.length;p+=1){let m=i[p],f=m.up+m.down;if(f<=0)continue;let g=h(m.price+o),b=Math.max(1,h(m.price)-g-1),y=f/s*u,v=m.up/f*y;r.globalAlpha=p>=l&&p<=c?.62:.28,v>0&&(r.fillStyle=n.upColor,r.fillRect(d-y,g,v,b)),y-v>0&&(r.fillStyle=n.downColor,r.fillRect(d-y+v,g,y-v,b));}if(n.showPoc){let p=i[a],m=h(p.price+o),f=Math.max(1,h(p.price)-m-1);r.globalAlpha=.9,r.strokeStyle=n.pocColor,r.lineWidth=1,r.strokeRect(d-u+.5,m+.5,u-1,f);}r.globalAlpha=1;}}var Kc=class{constructor(){this.canvas=null;this.ctx=null;this.memoKey="";this.memo=null;}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}destroy(){this.canvas=null,this.ctx=null,this.memoKey="",this.memo=null;}render(e){let t=this.ctx,n=this.canvas;if(!t||!n)return;let{bars:i,data:o,visible:s,coords:a,scale:l,bounds:c,theme:d}=e,u=a.dpr;if(t.setTransform(u,0,0,u,0,0),t.clearRect(0,0,n.width/u,n.height/u),!o||!s||i.length===0||c.height<=0)return;let h=a.visibleLogicalRange(),p=Math.max(0,Math.floor(h.from)),m=Math.min(i.length-1,Math.ceil(h.to));if(p>m)return;let f=i[m],g=`${p}:${m}:${i.length}:${f.high}:${f.low}:${f.close}:${f.volume??0}:${o.rows}:${o.valueAreaFrac}`;g!==this.memoKey&&(this.memoKey=g,this.memo=$w(i,p,m,o.rows,o.valueAreaFrac));let b=this.memo;b&&(t.save(),t.beginPath(),t.rect(0,c.top,a.width,c.height),t.clip(),Ww(t,b,{rightX:a.width,maxW:a.width*o.widthFrac,yOf:y=>a.priceToY(y,l,c)},{upColor:o.upColor,downColor:o.downColor,showPoc:o.showPoc,pocColor:d.textColor}),t.restore());}};var Be="price",ZM=8,JM="rgba(0,0,0,0)",Xc=64,QM=56,Gw=26,Vi=22,vs=26,$h=24,ek=5,tk="0 2px 8px rgba(0,0,0,0.4)",nk=12,jw=12,Uw=Xc+jw,Wh=Vi+14,rk=120,ik=2,Yw=6,ok=70,Fi=80,sk=110,ak=130,lk=.02,ck=.004,dk=.2,uk=4,ys=class{constructor(e){this.capabilities=Qv;this.surfaceBackground=Gt.background;this.surfaceTextColor=Gt.textColor;this.toolbarGutter=0;this.mountContainer=null;this.userDrawings=null;this.backdropRenderer=new Wc;this.volumeRenderer=new Gc;this.extLayers=[];this.layerOrderSig="";this.attributionEl=null;this.attributionEnabled=true;this.attributionHtml=null;this.vpvrRenderer=new Kc;this.resizeObserver=null;this.dprMedia=null;this.plotDeviceSize=null;this.coords=new pc;this.scene=new yc;this.backendMode="auto";this.glowAmount=0;this.chrome=new Pc;this.indicatorSlices=new zc;this.labelTooltip=null;this.crosshairLayer=new Mc;this.countdownTimer=null;this.symbolPicker=null;this.indicatorTitlesOn=true;this.indicatorValuesOn=true;this.legendActionsProvider=null;this.legendCalloutsProvider=null;this.legendOverviewAction=null;this.keyboard=null;this.keyboardEnabled=true;this.historyChordsEnabled=true;this.liveRegion=null;this.animZoom=true;this.animPan=true;this.animLiveBarMs=0;this.animLiveBarOnMs=90;this.candleUp=z;this.candleDown=W;this.introStyle="settle";this.introPlayed=false;this.introRaf=null;this.loadingEl=null;this.modelAlpha=1;this.targetBarSpacing=0;this.zoomAnchorLogical=0;this.zoomAnchorX=0;this.zoomAnchorMode="right";this.panVelocity=0;this.bars=[];this.didInitialFit=false;this.paintedData=false;this.skeletonClockMs=0;this.candleBodyAlpha=1;this.candleStructureAlpha=1;this.lastPointer=null;this.volumeActive=false;this.volumeHidden=false;this.vpvrActive=false;this.vpvrHidden=false;this.liveEaseTime=0;this.liveEaseHigh=0;this.liveEaseLow=0;this.liveEaseClose=0;this.axisDragEnabled=true;this.scaleDragHolder=null;this.scaleDragHeight=0;this.scaleDragStart=null;this.paneResizeEnabled=true;this.resizeAbove=null;this.resizeBelow=null;this.resizeSplitStart=null;this.hoverSeparatorY=null;this.maximizedPaneId=null;this.rightAxisW=Xc;this.paneControls=null;this.axisScaleButtons=null;this.paneActionCbs=new Set;this.hoverLogical=null;this.settingsDialog=null;this.hiddenSettings=[];this.dialogHost=null;this.settingsButton=null;this.settingsEnabled=false;this.scrollButton=null;this.pointerNearScrollBtn=false;this.scrollTargetRO=null;this.scrollBtnBottomPx=Wh;this.scrollBtnRightPx=Uw;this.layoutMode="desktop";this.viewportCbs=new Set;this.crosshairCbs=new Set;this.chartTypeSettingsCbs=new Set;this.configChangedCbs=new Set;this.themeSelectCbs=new Set;this.factoryConfig=null;this.hostSettingsSections=[];this.clickCbs=new Set;this.axisLongPressCbs=new Set;this.inputChangeCbs=new Set;this.removeIndicatorCbs=new Set;this.toggleVisibleCbs=new Set;this.moveIndicatorCbs=new Set;this.priceStyleCbs=new Set;this.name="native";this.features=["logScale","currentPriceLine","priceLabel","countdown","upColor","downColor","glow","animZoom","animPan","animLiveBar","intro","zoomAnchor","axisDrag","paneResize","candleZOrder","candleVisible","seriesOrder","highlights","sessionZones","gridlines","axisLabels","scaleMode","invertScale","paneScales","autoScale","timezone","keyboard","historyChords","priceStyle","priceBaseline","baselinePrice","settings","attribution","dialogHost","tradeMarkers","indicatorTitles","indicatorValues"];this.onScrollProximityMove=e=>{if(!this.scrollButton||!this.plot)return;let t=this.plot.getBoundingClientRect(),n=t.width-this.scrollBtnRightPx-vs/2,i=t.height-this.scrollBtnBottomPx-vs/2,o=Math.hypot(e.clientX-t.left-n,e.clientY-t.top-i)<=rk;o!==this.pointerNearScrollBtn&&(this.pointerNearScrollBtn=o,this.updateScrollToRealtimeButton());};this.onScrollProximityLeave=()=>{this.pointerNearScrollBtn&&(this.pointerNearScrollBtn=false,this.updateScrollToRealtimeButton());};this.onDprChange=()=>{this.watchDpr(),this.resize();};this.externalCross=null;this.snapMode="off";e&&(this.scene.showPriceLine=e.currentPriceLine,this.scene.logScale=e.logScale,this.backendMode=e.nativeBackend,this.animZoom=e.animZoom,this.animPan=e.animPan,this.setLiveBarEase(Ms(e.animLiveBar)),this.glowAmount=e.glow,this.candleUp=e.upColor,this.candleDown=e.downColor,this.scene.priceStyle=e.priceStyle,this.scene.basePainting=Zu(e.priceStyle),this.scene.candleOverride=cc(e.priceStyle,this.scene.style.chartTypes)),this.theme=this.deriveTheme(Gt);}applyFeature(e,t){switch(e){case "logScale":if(t&&typeof t=="object"){let n=t;this.setPaneLog(n.pane??Be,!!n.value);return}this.scene.logScale=!!t;break;case "currentPriceLine":this.scene.showPriceLine=!!t;break;case "priceLabel":this.scene.showPriceLabel=!!t;break;case "countdown":this.scene.showCountdown=!!t,this.syncCountdownTimer();break;case "upColor":this.candleUp=String(t),this.theme&&(this.theme=this.deriveTheme(this.theme));break;case "downColor":this.candleDown=String(t),this.theme&&(this.theme=this.deriveTheme(this.theme));break;case "glow":this.glowAmount=Number(t)||0,this.backend&&"glow"in this.backend&&(this.backend.glow=this.glowAmount);break;case "animZoom":this.animZoom=!!t;return;case "animPan":this.animPan=!!t;return;case "animLiveBar":this.setLiveBarEase(Ms(t));return;case "intro":{let n=t===false||t==="none"||t==="off"||t==null?"":String(t);this.introStyle=n,n&&this.playIntro(n);return}case "zoomAnchor":this.zoomAnchorMode=t==="right"?"right":"cursor",this.input&&(this.input.rightEdgeZoom=this.zoomAnchorMode==="right");return;case "axisDrag":this.axisDragEnabled=!!t,this.input&&(this.input.axisDrag=this.axisDragEnabled);return;case "paneResize":this.paneResizeEnabled=!!t,this.input&&(this.input.paneResize=this.paneResizeEnabled);return;case "candleZOrder":this.scene.candleZ=Number(t)||0;break;case "candleVisible":this.scene.candlesHidden=t===false;break;case "seriesOrder":this.applySeriesOrder(t);break;case "highlights":this.scene.highlights=fk(t);break;case "sessionZones":this.scene.sessionZones=gk(t);break;case "gridlines":this.scene.showGrid=!!t;break;case "axisLabels":this.scene.showAxisLabels=!!t;break;case "scaleMode":if(t&&typeof t=="object"){let n=t;this.setPaneScaleMode(n.pane??Be,Kw(n.mode));return}this.scene.scaleMode=Kw(t);break;case "invertScale":if(t&&typeof t=="object"){let n=t;this.setPaneInvert(n.pane??Be,!!n.value);return}this.scene.invertScale=!!t;break;case "autoScale":for(let n of this.scene.panes.values())n.manualScale=t?null:{...n.scale};break;case "timezone":this.scene.timezone=typeof t=="string"&&t?t:"UTC";break;case "priceStyle":this.setPriceStyle(bk(t)?t:"candles");break;case "priceBaseline":this.scene.baselineValue=t==null?null:Number(t);break;case "tradeMarkers":this.scene.tradeMarkers=Cy(this.scene.tradeMarkers,t);break;case "keyboard":this.setKeyboardEnabled(!!t);return;case "historyChords":this.historyChordsEnabled=!!t,this.userDrawings&&(this.userDrawings.historyChords=this.historyChordsEnabled);return;case "settings":this.setSettingsEnabled(!!t);return;case "indicatorTitles":this.indicatorTitlesOn=t!==false,this.inputsUI?.setTitlesVisible(this.indicatorTitlesOn);return;case "indicatorValues":this.indicatorValuesOn=t!==false,this.inputsUI?.setValuesVisible(this.indicatorValuesOn);return;case "attribution":this.attributionHtml=typeof t=="string"&&t.trim()?t:null,this.attributionEnabled=this.attributionHtml!==null||!!t,this.rebuildAttribution();return;case "dialogHost":this.dialogHost=t instanceof HTMLElement?t:null,this.settingsDialog?.close(),this.settingsDialog=null,this.inputsUI?.setDialogHost(this.dialogHost);return;default:return}this.scheduler?.invalidate(4);}readFeature(e){switch(e){case "logScale":return this.scene.logScale;case "currentPriceLine":return this.scene.showPriceLine;case "priceLabel":return this.scene.showPriceLabel;case "countdown":return this.scene.showCountdown;case "upColor":return this.candleUp;case "downColor":return this.candleDown;case "glow":return this.glowAmount;case "animZoom":return this.animZoom;case "animPan":return this.animPan;case "animLiveBar":return this.animLiveBarMs;case "intro":return this.introStyle;case "zoomAnchor":return this.zoomAnchorMode;case "axisDrag":return this.input?this.input.axisDrag:this.axisDragEnabled;case "paneResize":return this.input?this.input.paneResize:this.paneResizeEnabled;case "candleZOrder":return this.scene.candleZ;case "candleVisible":return !this.scene.candlesHidden;case "seriesOrder":return this.scene.indicatorZOrder();case "highlights":return this.scene.highlights;case "sessionZones":return this.scene.sessionZones;case "gridlines":return this.scene.showGrid;case "axisLabels":return this.scene.showAxisLabels;case "scaleMode":return this.scene.scaleMode;case "invertScale":return this.scene.invertScale;case "paneScales":return this.paneScaleInfos();case "autoScale":{let t=this.scene.orderedPanes().find(n=>n.kind==="price");return t?t.manualScale==null:true}case "timezone":return this.scene.timezone;case "priceStyle":return this.scene.priceStyle;case "priceBaseline":return this.scene.baselineValue;case "baselinePrice":{let t=this.scene.panes.get(Be);return t?this.scene.baselinePriceFor(t.scale):this.scene.baselineValue}case "tradeMarkers":return {...this.scene.tradeMarkers,colors:{...this.scene.tradeMarkers.colors}};case "keyboard":return this.keyboardEnabled;case "historyChords":return this.historyChordsEnabled;case "settings":return this.settingsEnabled;case "indicatorTitles":return this.indicatorTitlesOn;case "indicatorValues":return this.indicatorValuesOn;case "attribution":return this.attributionHtml??this.attributionEnabled;case "dialogHost":return this.dialogHost??void 0;default:return}}setNativeData(e,t){e==="volume"?(this.scene.volumeLayer=t??null,this.scheduler?.invalidate(3)):e==="vpvr"?(this.scene.vpvrLayer=t??null,this.scheduler?.invalidate(3)):e.endsWith("-pending")?(this.scene.nativePending.set(e.slice(0,-8),t??[]),this.scheduler?.invalidate(3)):(this.scene.nativeData.set(e,t),this.scheduler?.invalidate(3));}setIndicatorStatus(e,t){this.inputsUI.setStatus(e.id,t);}setLoading(e){if(!e||!this.wrapper){this.loadingEl?.remove(),this.loadingEl=null;return}if(this.loadingEl)return;let t=this.wrapper.ownerDocument,n=t.createElement("div");n.className="vela-loading",Object.assign(n.style,{position:"absolute",inset:"0",display:"flex",alignItems:"center",justifyContent:"center",gap:"7px",pointerEvents:"none"});for(let i=0;i<3;i+=1){let o=t.createElement("span");Object.assign(o.style,{width:"7px",height:"7px",borderRadius:"50%",background:this.chromeTheme().textColor,opacity:"0.15"}),o.animate([{opacity:.12},{opacity:.55}],{duration:800,iterations:1/0,direction:"alternate",easing:"ease-in-out",delay:-i*260}),n.appendChild(o);}this.wrapper.appendChild(n),this.loadingEl=n;}setPricePrecision(e){let t=typeof e=="number"&&e>0?e:void 0;t!==this.scene.priceMintick&&(this.scene.priceMintick=t,this.scheduler?.invalidate(4));}getConfig(){let e=this.scene.style,t=Object.fromEntries(Object.entries(e.chartTypes).map(([i,o])=>[i,{...o}])),n=this.theme;return {version:qu,chartTypes:t,layout:{background:n.background,textColor:n.textColor,fontFamily:n.fontFamily,fontSize:e.fontSize},grid:{vertLines:{visible:e.gridVert.visible,color:e.gridVert.color??n.gridColor},horzLines:{visible:e.gridHorz.visible,color:e.gridHorz.color??n.gridColor}},crosshair:{color:e.crosshair.color??n.textColor,width:e.crosshair.width,style:e.crosshair.style,opacity:e.crosshair.opacity,labelBackground:e.crosshair.labelBackground??n.textColor},priceScale:{mode:this.scene.scaleMode,log:this.scene.logScale,invert:this.scene.invertScale,borderColor:e.borderColor??n.borderColor,labelsVisible:this.scene.showAxisLabels,currentPriceLine:this.scene.showPriceLine,priceLabel:this.scene.showPriceLabel,countdown:this.scene.showCountdown,animateLastPrice:this.animLiveBarMs>0},panes:{separatorColor:e.separatorColor??n.borderColor},trades:{visible:this.scene.tradeMarkers.visible,labels:this.scene.tradeMarkers.labels,qty:this.scene.tradeMarkers.qty,longColor:this.scene.tradeMarkers.colors.long,shortColor:this.scene.tradeMarkers.colors.short,exitColor:this.scene.tradeMarkers.colors.exit},timeScale:{timezone:this.scene.timezone},candles:{upColor:this.candleUp,downColor:this.candleDown,bodyVisible:e.candle.bodyVisible,borderVisible:e.candle.borderVisible,borderUpColor:e.candle.borderUpColor??this.candleUp,borderDownColor:e.candle.borderDownColor??this.candleDown,wickVisible:e.candle.wickVisible,wickUpColor:e.candle.wickUpColor??this.candleUp,wickDownColor:e.candle.wickDownColor??this.candleDown},bars:{upColor:e.bars.upColor??this.candleUp,downColor:e.bars.downColor??this.candleDown},line:{color:e.line.color??this.candleUp,width:e.line.width},stacking:{candles:this.scene.candleZ,series:Object.fromEntries(this.scene.indicatorZOrder().map(({id:i,z:o})=>[i,o]))},area:(()=>{let i=e.area.lineColor??this.candleUp;return {lineColor:i,width:e.area.width,topColor:e.area.topColor??i,bottomColor:e.area.bottomColor??JM}})(),baseline:(()=>{let i=e.baseline.topLineColor??Si,o=e.baseline.bottomLineColor??Ci;return {topLineColor:i,bottomLineColor:o,topFillColor:e.baseline.topFillColor??q(i,xn),topFillColor2:e.baseline.topFillColor2??q(i,Sn),bottomFillColor:e.baseline.bottomFillColor??q(o,xn),bottomFillColor2:e.baseline.bottomFillColor2??q(o,Sn),width:e.baseline.width,baselineLevel:e.baseline.baselineLevel}})(),series:{style:this.scene.priceStyle,baseline:this.scene.baselineValue,spacing:this.coords.spacingScale},sessions:{premarketColor:e.sessions.premarketColor,postmarketColor:e.sessions.postmarketColor,extendedColor:e.sessions.extendedColor}}}applyConfig(e){let t=oy(this.getConfig(),e),n=this.scene.style;for(let[d,u]of Object.entries(t.chartTypes))if(JSON.stringify(n.chartTypes[d])!==JSON.stringify(u)){this.scene.nativeData.set(`${d}-settings`,{...u});for(let h of this.chartTypeSettingsCbs)h(d,{...u});}n.chartTypes=Object.fromEntries(Object.entries(t.chartTypes).map(([d,u])=>[d,{...u}]));let i=e&&typeof e=="object"?e.layout:void 0,o=i&&typeof i=="object"?i.textColor:void 0,s=typeof o=="string"&&o.trim().length>0,a=this.theme,l={textColor:t.layout.textColor,gridColor:a.gridColor,borderColor:a.borderColor};if(!s&&lt(t.layout.textColor)===lt(t.layout.background)){let d=lt(t.layout.background)?Gt:oo;l={textColor:d.textColor,gridColor:d.gridColor,borderColor:d.borderColor};}this.theme={...this.theme,background:t.layout.background,textColor:l.textColor,gridColor:l.gridColor,borderColor:l.borderColor,fontFamily:t.layout.fontFamily},n.fontSize=t.layout.fontSize;let c=(d,u,h)=>d===null&&u===h?null:u;n.gridVert={visible:t.grid.vertLines.visible,color:c(n.gridVert.color,t.grid.vertLines.color,a.gridColor)},n.gridHorz={visible:t.grid.horzLines.visible,color:c(n.gridHorz.color,t.grid.horzLines.color,a.gridColor)},n.crosshair={color:t.crosshair.color,width:t.crosshair.width,style:t.crosshair.style,opacity:t.crosshair.opacity,labelBackground:t.crosshair.labelBackground},this.scene.scaleMode=t.priceScale.mode,this.scene.logScale=t.priceScale.log,this.scene.invertScale=t.priceScale.invert,n.borderColor=c(n.borderColor,t.priceScale.borderColor,a.borderColor),this.scene.showAxisLabels=t.priceScale.labelsVisible,this.scene.showPriceLine=t.priceScale.currentPriceLine,this.scene.showPriceLabel=t.priceScale.priceLabel,this.scene.showCountdown=t.priceScale.countdown,this.syncCountdownTimer(),this.animLiveBarMs=t.priceScale.animateLastPrice?this.animLiveBarOnMs:0,n.separatorColor=c(n.separatorColor,t.panes.separatorColor,a.borderColor),this.scene.tradeMarkers={visible:t.trades.visible,labels:t.trades.labels,qty:t.trades.qty,colors:{long:t.trades.longColor,short:t.trades.shortColor,exit:t.trades.exitColor}},this.scene.timezone=t.timeScale.timezone,this.candleUp=t.candles.upColor,this.candleDown=t.candles.downColor,n.candle={bodyVisible:t.candles.bodyVisible,borderVisible:t.candles.borderVisible,borderUpColor:t.candles.borderUpColor,borderDownColor:t.candles.borderDownColor,wickVisible:t.candles.wickVisible,wickUpColor:t.candles.wickUpColor,wickDownColor:t.candles.wickDownColor},this.scene.candleZ=t.stacking.candles;for(let[d,u]of Object.entries(t.stacking.series))this.scene.setIndicatorZ(d,u);n.bars={upColor:t.bars.upColor,downColor:t.bars.downColor},n.line={color:t.line.color,width:t.line.width},n.area={lineColor:t.area.lineColor,width:t.area.width,topColor:t.area.topColor,bottomColor:t.area.bottomColor},n.baseline={topLineColor:t.baseline.topLineColor,bottomLineColor:t.baseline.bottomLineColor,topFillColor:t.baseline.topFillColor,topFillColor2:t.baseline.topFillColor2,bottomFillColor:t.baseline.bottomFillColor,bottomFillColor2:t.baseline.bottomFillColor2,width:t.baseline.width,baselineLevel:t.baseline.baselineLevel},n.sessions={premarketColor:t.sessions.premarketColor,postmarketColor:t.sessions.postmarketColor,extendedColor:t.sessions.extendedColor},this.setPriceStyle(t.series.style),this.scene.candleOverride=cc(this.scene.priceStyle,n.chartTypes),this.scene.baselineValue=t.series.baseline,this.coords.setPitchScale(t.series.spacing),this.coords.setViewport(this.clampViewport(this.coords.getViewport().barSpacing,this.coords.getViewport().rightOffset)),this.targetBarSpacing=this.coords.getViewport().barSpacing,this.theme=this.deriveTheme(this.theme),this.wrapper&&(Ae(this.wrapper,this.chromeTheme()),this.applyBackground()),this.inputsUI?.setTheme(this.theme),this.paneControls?.setTheme(this.theme),this.axisScaleButtons?.setTheme(this.theme),this.userDrawings?.setTheme(this.chromeTheme()),this.refreshScrollButtonTheme(),this.refreshAttributionColor(),this.scheduler?.invalidate(4);for(let d of this.configChangedCbs)d();}applySeriesOrder(e){if(!e||typeof e!="object")return;let t=e;typeof t.id=="string"&&(typeof t.z=="number"?this.scene.setIndicatorZ(t.id,t.z):t.to==="front"?this.scene.bringIndicatorToFront(t.id):t.to==="back"&&this.scene.sendIndicatorToBack(t.id));}setSettingsEnabled(e){this.settingsEnabled=e,e?(this.plot&&!this.settingsButton&&(this.settingsButton=this.makeSettingsButton(),this.plot.appendChild(this.settingsButton)),this.settingsButton&&(this.settingsButton.style.display="flex"),this.plot&&!this.settingsDialog&&(this.settingsDialog=new us(this.dialogHost??this.plot,this.theme))):(this.settingsButton?.style.setProperty("display","none"),this.settingsDialog?.close());}makeSettingsButton(){let e=document.createElement("button");return e.type="button",e.title="Chart settings",e.innerHTML=ye("gear",14),Object.assign(e.style,{position:"absolute",bottom:`${Vi+10}px`,right:`${Xc+10}px`,zIndex:"6",width:"26px",height:"26px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:"50%",border:`1px solid ${this.theme.borderColor}`,background:this.theme.background,color:this.theme.textColor,fontSize:"14px",lineHeight:"1",opacity:"0.75",pointerEvents:"auto",padding:"0"}),e.addEventListener("mouseenter",()=>e.style.opacity="1"),e.addEventListener("mouseleave",()=>e.style.opacity="0.75"),e.addEventListener("click",()=>this.toggleSettingsDialog()),e}openSettingsDialog(e){!this.settingsDialog&&this.plot&&(this.settingsDialog=new us(this.dialogHost??this.plot,this.theme),this.settingsDialog.setLayoutMode(this.layoutMode)),this.toggleSettingsDialog(e);}syncThemeControl(){this.settingsDialog?.setThemeControl(lt(this.surfaceBackground)?"dark":"light",e=>{for(let t of this.themeSelectCbs)t(e);});}toggleSettingsDialog(e){if(this.settingsDialog){if(e!==void 0&&this.settingsDialog.isOpen()){this.settingsDialog.showSection(e);return}this.settingsDialog.setTheme(this.theme),this.settingsDialog.setHostSections(this.hostSettingsSections),this.settingsDialog.setHiddenSettings(this.hiddenSettings),this.syncThemeControl(),this.settingsDialog.toggle(this.getConfig(),t=>this.applyConfig(t),t=>this.applyConfig(t),()=>{this.factoryConfig&&this.applyConfig(iy(this.factoryConfig)),this.settingsDialog?.close(),this.openSettingsDialog();},e);}}closeDialogs(){this.inputsUI?.closeOpenDialog(),this.settingsDialog?.close();}makeScrollToRealtimeButton(){let e=document.createElement("button");return e.type="button",e.title="Scroll to most recent bar (Alt+Shift+\u2192)",e.setAttribute("aria-label","Scroll to most recent bar"),e.innerHTML=this.scrollButtonIcon(),Object.assign(e.style,{position:"absolute",bottom:`${Wh}px`,right:`${Uw}px`,zIndex:"6",width:`${vs}px`,height:`${vs}px`,boxSizing:"border-box",display:"none",alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:`${ek}px`,border:`1px solid ${this.theme.borderColor}`,boxShadow:tk,background:this.scrollButtonSurface(),color:this.theme.textColor,lineHeight:"0",opacity:"0.85",pointerEvents:"auto",padding:"0"}),e.addEventListener("mouseenter",()=>e.style.opacity="1"),e.addEventListener("mouseleave",()=>e.style.opacity="0.85"),e.addEventListener("click",()=>this.scrollToRealtime()),e}scrollButtonIcon(){return ye("chevrons-right",nk)}scrollButtonSurface(){return q(this.theme.background,.5)}refreshScrollButtonTheme(){this.scrollButton&&(this.scrollButton.style.background=this.scrollButtonSurface(),this.scrollButton.style.color=this.theme.textColor,this.scrollButton.style.borderColor=this.theme.borderColor);}updateScrollToRealtimeButton(){let e=this.scrollButton;if(!e)return;let t=this.coords.barCount>0&&this.coords.getViewport().rightOffset<0;if(this.layoutMode==="mobile"){e.style.display=t?"flex":"none";return}e.style.display=t&&this.pointerNearScrollBtn?"flex":"none";}scrollToRealtime(){this.coords.barCount!==0&&this.glideRightOffset(Yw);}glideRightOffset(e){let t=this.coords.getViewport();if(!this.animPan){this.applyViewport({barSpacing:t.barSpacing,rightOffset:e});return}this.panVelocity=0,this.targetBarSpacing=t.barSpacing,this.scrollTargetRO=e,this.animator.start();}screenshotCanvas(){if(!this.dataCanvas)return null;this.computeScales(),this.paintData();let e=document.createElement("canvas");e.width=this.dataCanvas.width,e.height=this.dataCanvas.height;let t=e.getContext("2d");if(!t)return null;t.fillStyle=this.theme.background,t.fillRect(0,0,e.width,e.height);let n=this.plot?.getBoundingClientRect(),i=n&&n.width>0?{left:n.left,top:n.top,dpr:e.width/n.width}:null,o=[...this.mountContainer?.querySelectorAll("[data-vela-screenshot]")??[]];if(i)for(let s of o)s.getAttribute("data-vela-screenshot")==="under"&&Yc(t,s,i);for(let s of [...this.canvasPile(),this.chromeCanvas,this.drawingsCanvas])s&&s.width>0&&s.height>0&&t.drawImage(s,0,0);if(i){for(let s of this.plot?.querySelectorAll("[data-vela-pane]")??[])Yc(t,s,i);for(let s of o)s.getAttribute("data-vela-screenshot")!=="under"&&Yc(t,s,i);}return e}screenshot(){return this.screenshotCanvas()?.toDataURL("image/png")??null}playIntro(e){this.introRaf!=null&&cancelAnimationFrame(this.introRaf),this.introRaf=null;let t=this.bars,n=t.length;if(n===0)return;this.computeScales();for(let a of this.scene.panes.values())a.scale={...a.scaleTarget};this.modelAlpha=0;let i=650,o=performance.now(),s=a=>{let l=Math.min(1,(a-o)/i);this.scene.bars=l>=1?t:t.map((c,d)=>this.revealCandle(c,d,l,n,e)),this.paintData(),l<1?this.introRaf=requestAnimationFrame(s):(this.scene.bars=t,this.fadeInModels());};this.introRaf=requestAnimationFrame(s);}fadeInModels(){let t=performance.now(),n=i=>{this.modelAlpha=Math.min(1,(i-t)/350),this.paintData(),this.modelAlpha<1?this.introRaf=requestAnimationFrame(n):(this.modelAlpha=1,this.introRaf=null);};this.introRaf=requestAnimationFrame(n);}revealCandle(e,t,n,i,o){let a=Math.max(0,Math.min(1,(n-t/Math.max(1,i-1)*.55)/.44999999999999996)),l;if(o==="settle"){let u=a-1;l=1+(1.70158+1)*u*u*u+1.70158*u*u;}else {let d=1-a;l=1-d*d*d;}let c=e.open;return {...e,high:c+(e.high-c)*l,low:c+(e.low-c)*l,close:c+(e.close-c)*l}}deriveTheme(e){return {...e,upColor:this.candleUp,downColor:this.candleDown}}chromeTheme(){return {...this.theme,background:this.surfaceBackground,textColor:this.surfaceTextColor,borderColor:lt(this.surfaceBackground)?Gt.borderColor:oo.borderColor}}axisSurface(){return {background:this.theme.background,textColor:this.theme.textColor}}mount(e,t){this.mountContainer=e,this.publishGutters(),this.theme=this.deriveTheme(t),this.surfaceBackground=t.background,this.surfaceTextColor=t.textColor,this.wrapper=document.createElement("div"),Object.assign(this.wrapper.style,{position:"relative",width:"100%",height:"100%",overflow:"hidden",cursor:"crosshair",userSelect:"none",webkitUserSelect:"none"}),Ae(this.wrapper,this.chromeTheme()),this.backdropCanvas=document.createElement("canvas"),Object.assign(this.backdropCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.volumeCanvas=document.createElement("canvas"),Object.assign(this.volumeCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.dataCanvas=this.createGeometryBackend(),this.vpvrCanvas=document.createElement("canvas"),Object.assign(this.vpvrCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.chromeCanvas=document.createElement("canvas"),Object.assign(this.chromeCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.drawingsCanvas=document.createElement("canvas"),Object.assign(this.drawingsCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.cursorCanvas=document.createElement("canvas"),Object.assign(this.cursorCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.overlayRoot=document.createElement("div"),Object.assign(this.overlayRoot.style,{position:"absolute",inset:"0",pointerEvents:"none"}),this.plot=document.createElement("div"),Object.assign(this.plot.style,{position:"absolute",top:"0",right:"0",bottom:"0",left:"0"}),this.extLayers=Vh().map(o=>{let s=document.createElement("canvas");return Object.assign(s.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),{def:o,instance:o.create(),canvas:s}});let n=this.extLayers.filter(o=>o.def.placement==="below-data").map(o=>o.canvas),i=this.extLayers.filter(o=>o.def.placement!=="below-data").map(o=>o.canvas);this.plot.append(this.backdropCanvas,...n,this.dataCanvas,this.volumeCanvas,this.vpvrCanvas,...i,this.chromeCanvas,this.drawingsCanvas,this.cursorCanvas,this.overlayRoot),this.layerOrderSig="",this.wrapper.appendChild(this.plot),this.factoryConfig=this.getConfig(),this.attributionEl=this.buildAttributionEl(),this.attributionEnabled||(this.attributionEl.style.display="none"),this.positionAttribution(),this.wrapper.appendChild(this.attributionEl),e.appendChild(this.wrapper),this.applyBackground(),this.backdropRenderer.mount(this.backdropCanvas),this.volumeRenderer.mount(this.volumeCanvas),this.vpvrRenderer.mount(this.vpvrCanvas);for(let o of this.extLayers)o.instance.mount(o.canvas);this.chrome.mount(this.chromeCanvas),this.crosshairLayer.mount(this.cursorCanvas),this.coords.setViewport(ns()),this.scene.ensurePane(Be,"price",0,3),this.scheduler=new mc(o=>this.renderFrame(o)),this.animator=new fc(o=>this.animTick(o)),this.targetBarSpacing=this.coords.getViewport().barSpacing,this.input=new gc({getCoords:()=>this.coords,apply:o=>this.applyViewport(o),zoomTo:(o,s,a)=>this.zoomTo(o,s,a),fling:o=>this.fling(o),onPointerMove:(o,s)=>this.handlePointerMove(o,s),onClick:o=>{this.userDrawings?.deselect(),this.handleClick(o);},onAxisLongPress:(o,s,a)=>{for(let l of this.axisLongPressCbs)l({axis:o,x:s,y:a});},beginPriceScale:(o,s)=>this.beginPriceScale(o,s),priceScaleBy:o=>this.priceScaleBy(o),beginPricePan:o=>this.beginPricePan(o),pricePanBy:o=>this.pricePanBy(o),resetPriceScale:(o,s)=>this.resetPriceScale(o,s),dataDblClick:(o,s)=>this.dataDblClick(o,s),paneSeparatorAt:o=>this.paneSeparatorAt(o),beginPaneResize:o=>this.beginPaneResize(o),paneResizeBy:o=>this.paneResizeBy(o),resetPaneSize:o=>this.resetPaneSize(o),resetView:()=>this.resetView(),drawingsClaim:(o,s)=>this.userDrawings?.claim(o,s)??false,drawingsMeasureStart:(o,s,a)=>this.userDrawings?.beginMeasureAt(o,s,a)??false,drawingsMarqueeStart:(o,s)=>this.userDrawings?.beginMarqueeAt(o,s)??false,drawingsDeleteAt:(o,s)=>this.userDrawings?.deleteAt(o,s,true)??false,drawingsCancelPlacement:()=>this.userDrawings?.cancelPlacement()??false,drawingsSnapMode:()=>this.snapMode,drawingsPointerDown:(o,s,a,l,c)=>this.userDrawings?.pointerDown(o,s,a,l,c),drawingsPointerMove:(o,s,a,l,c)=>this.userDrawings?.pointerMove(o,s,a,l,c),drawingsPointerUp:(o,s,a)=>this.userDrawings?.pointerUp(o,s,a),drawingsCursor:(o,s)=>this.userDrawings?.cursorAt(o,s)??null,drawingsDblClick:(o,s)=>this.userDrawings?.dblClick(o,s)??false,drawingsClearTransient:()=>this.userDrawings?.clearTransient()}),this.input.rightEdgeZoom=this.zoomAnchorMode==="right",this.input.axisDrag=this.axisDragEnabled,this.input.paneResize=this.paneResizeEnabled,this.input.attach(this.dataCanvas),this.settingsEnabled&&this.setSettingsEnabled(true),this.syncCountdownTimer(),this.scrollButton=this.makeScrollToRealtimeButton(),this.plot.appendChild(this.scrollButton),this.plot.addEventListener("pointermove",this.onScrollProximityMove),this.plot.addEventListener("pointerleave",this.onScrollProximityLeave),this.labelTooltip=new Lc(this.plot,{theme:()=>this.chromeTheme(),lookup:(o,s)=>this.indicatorSlices.labelTooltipAt(o,s)}),this.userDrawings=new Bc(this.wrapper,this.plot,this.drawingsCanvas,{projector:()=>this.drawingProjector(),dpr:()=>this.coords.dpr,theme:()=>this.theme,requestScaleUpdate:()=>this.scheduler.invalidate(3),seriesBoundaries:o=>this.scene.seriesBoundaries(o),priceZ:o=>o===Be?this.scene.candleZ:null,requestDataPaint:()=>this.scheduler.invalidate(3),seriesLook:()=>{let o=this.scene.style,s=Ti(o.candle,this.scene.candleOverride,this.theme.upColor,this.theme.downColor),a=o.bars.upColor??this.theme.upColor,l=o.bars.downColor??this.theme.downColor,c=this.scene.priceStyle;return {style:c,upColor:c==="bars"?a:s.up,downColor:c==="bars"?l:s.down,lineColor:c==="area"?o.area.lineColor??this.theme.upColor:o.line.color??this.theme.upColor}},chartBarMs:()=>this.coords.barInterval,snap:(o,s,a,l)=>this.snapToCandle(o,s,a,l),setSnapMode:o=>this.setSnapMode(o),setToolbarGutter:o=>this.setToolbarGutter(o)}),this.userDrawings.historyChords=this.historyChordsEnabled,this.layoutMode==="mobile"&&(this.mountContainer?.setAttribute("data-vela-layout",this.layoutMode),this.userDrawings.setLayoutMode(this.layoutMode),this.scrollButton&&(this.scrollButton.style.width=`${$h}px`,this.scrollButton.style.height=`${$h}px`)),this.keyboard=new bc({panByBars:o=>this.panByBars(o),zoomByStep:o=>this.zoomByStep(o),stepCrosshair:o=>this.stepCrosshair(o),jumpToEdge:o=>this.focusBar(o==="first"?0:this.coords.barCount-1),resetView:()=>this.resetView(),scrollToRealtime:()=>this.scrollToRealtime(),clearCrosshair:()=>this.handlePointerMove(null,null),preempt:o=>this.userDrawings?.handleKey(o)??false}),this.setKeyboardEnabled(this.keyboardEnabled),this.inputsUI=new ic(this.plot,t,o=>this.paneBoundsFor(o)),this.inputsUI.setLayoutMode(this.layoutMode),this.inputsUI.setTitlesVisible(this.indicatorTitlesOn),this.inputsUI.setValuesVisible(this.indicatorValuesOn),this.inputsUI.setDialogHost(this.dialogHost),this.inputsUI.setSymbolPicker(this.symbolPicker),this.inputsUI.setLegendActions(this.legendActionsProvider),this.inputsUI.setLegendCallouts(this.legendCalloutsProvider),this.inputsUI.setLegendOverviewAction(this.legendOverviewAction),this.inputsUI.setOnChange(o=>{for(let s of this.inputChangeCbs)s({indicatorId:o.indicatorId,key:o.key,value:o.value,...o.kind?{kind:o.kind}:{}});}),this.inputsUI.setOnRemove(o=>{for(let s of this.removeIndicatorCbs)s(o);}),this.inputsUI.setOnToggleVisible((o,s)=>{for(let a of this.toggleVisibleCbs)a(o,s);}),this.inputsUI.setMoveApi({panes:()=>this.scene.orderedPanes().map((o,s)=>({id:o.id,kind:o.kind,label:o.kind==="price"?"Main chart":this.paneMasterTitle(o.id)??`Pane ${s}`,top:o.bounds.top,height:o.bounds.height})),move:(o,s)=>{for(let a of this.moveIndicatorCbs)a(o,s);}}),this.paneControls=new oc(this.plot,t,{panes:()=>this.paneControlViews(),rightAxis:()=>this.rightAxisW,onMove:(o,s)=>this.movePaneLocal(o,s),onToggleCollapse:o=>{let s=this.scene.panes.get(o);if(!s)return;let a=!s.collapsed;s.collapsed=a,this.afterPaneLayoutChange(),this.emitPaneAction({type:"collapse",paneId:o,collapsed:a});},onToggleMaximize:o=>{let s=this.maximizedPaneId!==o;this.maximizedPaneId=s?o:null,this.afterPaneLayoutChange(),this.emitPaneAction({type:"maximize",paneId:o,maximized:s});}}),this.paneControls.setSuspended(this.layoutMode==="mobile"),this.axisScaleButtons=new sc(this.plot,t,{panes:()=>this.axisScaleViews(),rightAxis:()=>this.rightAxisW,onToggleAuto:o=>this.togglePaneAuto(o),onToggleLog:o=>{let s=this.scene.panes.get(o);s&&this.setPaneLog(o,!Mi(this.scene,s));}}),this.resizeObserver=new ResizeObserver(o=>{for(let s of o){if(s.target!==this.plot)continue;let a=s.devicePixelContentBoxSize?.[0];a&&(this.plotDeviceSize={width:a.inlineSize,height:a.blockSize});}this.resize();}),this.resizeObserver.observe(this.wrapper);try{this.resizeObserver.observe(this.plot,{box:"device-pixel-content-box"});}catch{}this.watchDpr(),this.syncSize();}makeDataCanvas(){let e=document.createElement("canvas");return Object.assign(e.style,{position:"absolute",inset:"0",width:"100%",height:"100%"}),e}createGeometryBackend(){if((this.backendMode==="auto"||this.backendMode==="webgl2")&&ey()){let n=this.makeDataCanvas(),i=new hc;if(i.glow=this.glowAmount,i.onNeedsRedraw=()=>this.scheduler?.invalidate(4),i.onContextFailed=()=>this.swapToCanvas2dFallback(),i.mount(n),i.ok)return this.backend=i,n;i.destroy();}let e=this.makeDataCanvas(),t=new rs;return t.mount(e),this.backend=t,e}swapToCanvas2dFallback(){if(this.backend.kind==="canvas2d")return;let e=this.dataCanvas;this.input?.detach(),this.backend.destroy();let t=this.makeDataCanvas(),n=new rs;n.mount(t),this.backend=n,e.replaceWith(t),this.dataCanvas=t,this.input?.attach(t),this.syncSize();}watchDpr(){typeof window.matchMedia=="function"&&(this.dprMedia?.removeEventListener("change",this.onDprChange),this.dprMedia=window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.dprMedia.addEventListener("change",this.onDprChange,{once:true}));}setTheme(e){this.theme=this.deriveTheme(e),this.surfaceBackground=e.background,this.surfaceTextColor=e.textColor,this.wrapper&&Ae(this.wrapper,this.chromeTheme()),this.applyBackground(),this.inputsUI.setTheme(e),this.paneControls?.setTheme(this.theme),this.axisScaleButtons?.setTheme(this.theme),this.settingsDialog?.refreshConfig(this.getConfig()),this.syncThemeControl(),this.settingsDialog?.setTheme(this.theme),this.settingsButton&&(this.settingsButton.style.background=this.theme.background,this.settingsButton.style.color=this.theme.textColor,this.settingsButton.style.borderColor=this.theme.borderColor),this.refreshScrollButtonTheme(),this.userDrawings?.setTheme(this.chromeTheme()),this.refreshAttributionColor(),this.scheduler.invalidate(4);}resize(){this.syncSize();}syncCountdownTimer(){this.scene.showCountdown?this.countdownTimer==null&&(this.countdownTimer=setInterval(()=>{this.scene.showCountdown&&this.scene.bars.length>0&&this.scheduler?.invalidate(2);},1e3)):this.countdownTimer!=null&&(clearInterval(this.countdownTimer),this.countdownTimer=null);}destroy(){this.introRaf!=null&&cancelAnimationFrame(this.introRaf),this.loadingEl?.remove(),this.loadingEl=null,this.countdownTimer!=null&&(clearInterval(this.countdownTimer),this.countdownTimer=null),this.scheduler?.destroy(),this.animator?.stop(),this.input?.detach(),this.keyboard?.detach(),this.keyboard=null,this.liveRegion=null,this.inputsUI?.destroy(),this.paneControls?.destroy(),this.axisScaleButtons?.destroy(),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.dprMedia?.removeEventListener("change",this.onDprChange),this.dprMedia=null,this.userDrawings?.destroy(),this.userDrawings=null,this.settingsDialog?.destroy(),this.settingsDialog=null,this.settingsButton?.remove(),this.settingsButton=null,this.plot?.removeEventListener("pointermove",this.onScrollProximityMove),this.plot?.removeEventListener("pointerleave",this.onScrollProximityLeave),this.labelTooltip?.destroy(),this.labelTooltip=null,this.scrollButton?.remove(),this.scrollButton=null;for(let e of this.extLayers)e.instance.destroy?.();this.extLayers=[],this.backdropRenderer.destroy(),this.volumeRenderer.destroy(),this.vpvrRenderer.destroy(),this.backend.destroy(),this.chrome.destroy(),this.crosshairLayer.destroy(),this.attributionEl?.remove(),this.attributionEl=null,this.mountContainer?.style.removeProperty("--vela-toolbar-gutter"),this.mountContainer?.style.removeProperty("--vela-scale-gutter"),this.mountContainer?.style.removeProperty("--vela-bottom-gutter"),this.mountContainer?.style.removeProperty("--vela-price-pane-top"),this.mountContainer?.style.removeProperty("--vela-price-pane-bottom"),this.mountContainer=null,this.wrapper?.remove();}setBars(e,t){this.introRaf!=null&&(cancelAnimationFrame(this.introRaf),this.introRaf=null,this.modelAlpha=1),this.liveEaseTime=0;let n=this.bars,i=n[0]?.time;this.bars=vk(e),this.scene.bars=this.bars,this.coords.setBars(this.bars.map(s=>s.time));for(let s of this.scene.indicators.values())this.refreshAnchorOffset(s);if(t?.preserveView===true&&i!=null&&this.bars.length>0){let s=this.bars[0].time,a=0;if(s!==i){let l=this.bars.findIndex(c=>c.time===i);if(l>0)a=l;else {let c=n.findIndex(d=>d.time===s);c>0&&(a=-c);}}a!==0&&(this.zoomAnchorLogical+=a,this.hoverLogical!=null&&(this.hoverLogical+=a));}let o=t?.preserveView===true&&this.didInitialFit;if(this.coords.width>0&&!o&&(this.didInitialFit?this.reframeKeepZoom():this.fitContent(),this.didInitialFit=true),!this.introPlayed&&this.bars.length>0&&(this.introPlayed=true,this.introStyle)){this.playIntro(this.introStyle);return}this.scheduler.invalidate(4);}updateBar(e){let t=this.bars.length,n=this.bars[t-1];if(n&&e.time===n.time)this.bars[t-1]=e,this.animLiveBarMs<=0||this.liveEaseTime!==e.time?this.syncLiveEase(e):this.animator.start();else if(!n||e.time>n.time)this.bars.push(e),this.syncLiveEase(e),this.coords.barInterval>0?this.coords.appendBar(e.time):this.coords.setBars(this.bars.map(i=>i.time));else return;this.scene.bars=this.bars,this.scheduler.invalidate(4);}setLiveBarEase(e){this.animLiveBarMs=e,e>0&&(this.animLiveBarOnMs=e);}syncLiveEase(e){this.liveEaseTime=e.time,this.liveEaseHigh=e.high,this.liveEaseLow=e.low,this.liveEaseClose=e.close;}easeLiveBar(e){let t=this.bars[this.bars.length-1];if(!t||this.liveEaseTime!==t.time)return false;let n=Math.max(1e-9,Math.abs(t.close)*1e-6),i=this.animLiveBarMs,o=vt(this.liveEaseHigh,t.high,e,i),s=vt(this.liveEaseLow,t.low,e,i),a=vt(this.liveEaseClose,t.close,e,i),l=Math.abs(o-t.high)>n||Math.abs(s-t.low)>n||Math.abs(a-t.close)>n;return this.liveEaseHigh=l?o:t.high,this.liveEaseLow=l?s:t.low,this.liveEaseClose=l?a:t.close,l}ensurePane(e){this.scene.ensurePane(e.id,e.kind,e.order,e.heightWeight??(e.kind==="price"?3:1)),this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}removePane(e){e!==Be&&(this.scene.removePane(e),this.maximizedPaneId===e&&(this.maximizedPaneId=null),this.refreshAxisWidth(),this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}setIndicatorPane(e,t,n){let i=this.scene.indicators.get(e.id);i&&(i.paneId=t,i.ownScale=n?.ownScale===true,i.ownScale||this.scene.dropIndicatorScale(e.id),this.inputsUI.setPane(e.id,t),this.refreshAnchorOffset(i),this.refreshAxisWidth(),this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}orderPanes(e){this.scene.orderPanes(e),this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}setPaneCollapsed(e,t){let n=this.scene.panes.get(e);!n||n.collapsed===t||(n.collapsed=t,this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}setPaneMaximized(e){e!==null&&!this.scene.panes.has(e)&&(e=null),this.maximizedPaneId=e,this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}onPaneAction(e){return this.paneActionCbs.add(e),()=>this.paneActionCbs.delete(e)}emitPaneAction(e){for(let t of this.paneActionCbs)t(e);}onMoveIndicator(e){return this.moveIndicatorCbs.add(e),()=>this.moveIndicatorCbs.delete(e)}maxOwnScaleColumns(){let e=0;for(let t of this.scene.panes.values()){let n=this.scene.ownScaleIndicatorsForPane(t.id).length;n>e&&(e=n);}return e}refreshAxisWidth(){let e=Xc+QM*this.maxOwnScaleColumns();return e===this.rightAxisW?false:(this.rightAxisW=e,this.publishGutters(),this.coords.width>0&&this.syncSize(),true)}refreshAnchorOffset(e){let t=e.anchorTime;if(t==null||this.bars.length===0){this.scene.setAnchorOffset(e.id,0);return}let n=this.bars[0].time;if(t===n){this.scene.setAnchorOffset(e.id,0);return}if(t<n){let a=hk(e,n);if(a==null){console.warn(`[vela] indicator "${e.id}" starts before the first bar with no series to align on \u2014 rendering unanchored`),this.scene.setAnchorOffset(e.id,0);return}this.scene.setAnchorOffset(e.id,-a);return}let i=0,o=this.bars.length-1,s=this.bars.length;for(;i<=o;){let a=i+o>>1;this.bars[a].time>=t?(s=a,o=a-1):i=a+1;}if(s>=this.bars.length||this.bars[s].time!==t){console.warn(`[vela] indicator "${e.id}" anchorTime matches no chart bar \u2014 rendering unanchored`),this.scene.setAnchorOffset(e.id,0);return}this.scene.setAnchorOffset(e.id,s);}mountIndicator(e){return this.scene.indicators.set(e.id,e),this.refreshAnchorOffset(e),e.native&&this.extLayers.some(t=>t.def.id===e.native.type)?this.scene.assignIndicatorZTop(e.id):this.scene.assignIndicatorZ(e.id),this.inputsUI.upsert(e.id,e.shorttitle??e.title,e.inputs,e.inputValues,e.paneId,{native:!!e.native,...e.props?{props:e.props,propValues:e.propValues??{}}:{}}),e.native?.type==="volume"?(this.volumeActive=true,this.volumeHidden=false):e.native?.type==="vpvr"&&(this.vpvrActive=true,this.vpvrHidden=false),e.ownScale&&this.refreshAxisWidth(),this.paneControls?.refresh(),this.scheduler.invalidate(4),{id:e.id}}updateIndicator(e,t){let n=this.scene.indicators.get(e.id);if(n){if(t.kind==="value"&&t.anchorTime!==void 0){let i=t.anchorTime??void 0;i!==n.anchorTime&&(n.anchorTime=i,this.refreshAnchorOffset(n));}pk(n,t),this.scheduler.invalidate(3);}}removeIndicator(e){let t=this.scene.indicators.get(e.id)?.native?.type;t==="volume"?(this.volumeActive=false,this.volumeHidden=false,this.scene.volumeLayer=null):t==="vpvr"&&(this.vpvrActive=false,this.vpvrHidden=false,this.scene.vpvrLayer=null),this.scene.indicators.delete(e.id),this.scene.forgetIndicatorZ(e.id),this.scene.forgetAnchorOffset(e.id),this.scene.dropIndicatorScale(e.id),this.inputsUI.remove(e.id),this.refreshAxisWidth(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}setIndicatorInputs(e,t,n){this.inputsUI.setValues(e.id,t,n);}setSymbolPicker(e){this.symbolPicker=e,this.inputsUI?.setSymbolPicker(e);}setLegendActions(e){this.legendActionsProvider=e,this.inputsUI?.setLegendActions(e);}setLegendCallouts(e){this.legendCalloutsProvider=e,this.inputsUI?.setLegendCallouts(e);}setLegendOverviewAction(e){this.legendOverviewAction=e,this.inputsUI?.setLegendOverviewAction(e);}openIndicatorSettings(e){this.inputsUI?.openSettingsFor(e);}setIndicatorVisible(e,t){let n=this.scene.indicators.get(e.id)?.native?.type;if(n==="volume"||n==="vpvr"){n==="volume"?this.volumeHidden=!t:this.vpvrHidden=!t,this.inputsUI.setVisible(e.id,t),this.scheduler.invalidate(4);return}t||this.scene.indicators.delete(e.id),this.inputsUI.setVisible(e.id,t),this.scheduler.invalidate(4);}onInputChange(e){return this.inputChangeCbs.add(e),()=>this.inputChangeCbs.delete(e)}onToggleIndicatorVisible(e){return this.toggleVisibleCbs.add(e),()=>this.toggleVisibleCbs.delete(e)}onPriceStyleChange(e){return this.priceStyleCbs.add(e),()=>this.priceStyleCbs.delete(e)}setPriceStyle(e){if(e!==this.scene.priceStyle){this.scene.priceStyle=e,this.scene.basePainting=Zu(e),this.scene.candleOverride=cc(e,this.scene.style.chartTypes);for(let t of this.priceStyleCbs)t(e);}}onRemoveIndicator(e){return this.removeIndicatorCbs.add(e),()=>this.removeIndicatorCbs.delete(e)}setLayoutMode(e){if(e!==this.layoutMode){if(this.layoutMode=e,this.mountContainer?.setAttribute("data-vela-layout",e),this.userDrawings?.setLayoutMode(e),this.settingsDialog?.setLayoutMode(e),this.inputsUI?.setLayoutMode(e),this.paneControls?.setSuspended(e==="mobile"),this.scrollButton){let t=e==="mobile"?$h:vs;this.scrollButton.style.width=`${t}px`,this.scrollButton.style.height=`${t}px`;}this.updateScrollToRealtimeButton();}}setSettingsSections(e){this.hostSettingsSections=e,this.settingsDialog?.setHostSections(e);}setSettingsVisibility(e){this.hiddenSettings=[...e.hidden??[]],this.settingsDialog?.setHiddenSettings(this.hiddenSettings);}listSettingsIds(){return Uy(this.hostSettingsSections)}onChartTypeSettingsChange(e){return this.chartTypeSettingsCbs.add(e),()=>this.chartTypeSettingsCbs.delete(e)}onConfigChanged(e){return this.configChangedCbs.add(e),()=>this.configChangedCbs.delete(e)}onThemeSelect(e){return this.themeSelectCbs.add(e),()=>this.themeSelectCbs.delete(e)}onCrosshairMove(e){return this.crosshairCbs.add(e),()=>this.crosshairCbs.delete(e)}onClick(e){return this.clickCbs.add(e),()=>this.clickCbs.delete(e)}onAxisLongPress(e){return this.axisLongPressCbs.add(e),()=>this.axisLongPressCbs.delete(e)}onViewportChange(e){return this.viewportCbs.add(e),()=>this.viewportCbs.delete(e)}getVisibleRange(){let e=this.coords.barCount;if(e===0||this.coords.width===0)return null;let t=this.coords.visibleLogicalRange(),n=Math.max(0,Math.ceil(t.from)),i=Math.min(e-1,Math.floor(t.to));return i<n?null:{from:this.coords.logicalToTime(n),to:this.coords.logicalToTime(i)}}setVisibleRange(e){let t=this.coords.timeToLogical(e.from),n=this.coords.timeToLogical(e.to),i=Math.max(1e-6,n-t),o=tn(this.coords.width/(i*this.coords.spacingScale)),s=n-(this.coords.barCount-1);this.applyViewport({barSpacing:o,rightOffset:s});}panBy(e){if(this.coords.barCount===0||this.coords.width===0)return;let t=this.coords.getViewport(),n=this.coords.width/this.coords.pxPerBar(),i=this.scrollTargetRO??t.rightOffset;this.glideRightOffset(this.clampViewport(t.barSpacing,i+e*n).rightOffset);}applyViewport(e){this.animator.stop(),this.panVelocity=0,this.scrollTargetRO=null;let t=this.clampViewport(e.barSpacing,e.rightOffset);this.coords.setViewport(t),this.targetBarSpacing=t.barSpacing,this.scheduler.invalidate(4),this.emitViewportChange();}zoomTo(e,t,n){let i=this.clampViewport(e,this.coords.getViewport().rightOffset).barSpacing;if(this.zoomAnchorLogical=t,this.zoomAnchorX=n,this.panVelocity=0,this.scrollTargetRO=null,!this.animZoom){let o=this.clampViewport(i,this.anchoredRightOffset(i));this.coords.setViewport(o),this.targetBarSpacing=o.barSpacing,this.scheduler.invalidate(4),this.emitViewportChange();return}this.targetBarSpacing=i,this.animator.start();}fling(e){this.animPan&&(this.scrollTargetRO=null,this.panVelocity=e,this.animator.start());}anchoredRightOffset(e){let t=e*this.coords.spacingScale;return this.zoomAnchorLogical+(this.coords.width-this.zoomAnchorX)/t-(this.coords.barCount-1)}clampViewport(e,t){let n=this.coords.barCount,i=this.coords.width;if(n<=1||i<=0)return {barSpacing:tn(e),rightOffset:t};let o=Math.min(ik,n),s=this.coords.spacingScale,a=Math.min(1e3,i/(o*s)),l=Math.max(.5,Math.min(a,i/((n+Yw)*s))),c=Math.max(l,Math.min(a,e)),u=i/(c*s)-(o-1),h=o-n,p=Math.max(h,Math.min(u,t));return {barSpacing:c,rightOffset:p}}animTick(e){let t=this.coords.getViewport(),n=t.barSpacing,i=t.rightOffset,o=false,s=this.targetBarSpacing;Math.abs(n-s)>s*.001?(n=tn(vt(n,s,e,ok)),i=this.anchoredRightOffset(n),o=true):n!==s&&(n=s,i=this.anchoredRightOffset(n));let a=lk/Math.max(1e-6,n*this.coords.spacingScale);if(Math.abs(this.panVelocity)>a&&(i+=this.panVelocity*e,this.panVelocity*=Math.exp(-e/sk),Math.abs(this.panVelocity)<=a?this.panVelocity=0:o=true),this.scrollTargetRO!=null){let c=this.scrollTargetRO,d=vt(i,c,e,ak);Math.abs(d-c)<.001?(i=c,this.scrollTargetRO=null):(i=d,o=true);}let l=this.clampViewport(n,i);return l.barSpacing!==n&&(this.targetBarSpacing=l.barSpacing),this.scrollTargetRO!=null&&l.rightOffset!==i&&(this.scrollTargetRO=l.rightOffset),this.coords.setViewport(l),this.computeScales(),this.easeScales(e)&&(o=true),this.easeLiveBar(e)&&(o=true),this.skeletonClockMs+=e,this.paintData(),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx()),this.updateLegendValues(),this.emitViewportChange(),o}easeScales(e){let t=false;for(let n of this.scene.panes.values()){let i=n.scaleTarget,o=n.scale;if(i.log&&o.min>0&&i.min>0){let c=Math.log(i.min),d=Math.log(i.max),u=Math.max(1e-9,Math.abs(d-c)),h=vt(Math.log(o.min),c,e,Fi),p=vt(Math.log(o.max),d,e,Fi);Math.abs(h-c)<=u*.001&&Math.abs(p-d)<=u*.001?n.scale={min:i.min,max:i.max,log:true}:(t=true,n.scale={min:Math.exp(h),max:Math.exp(p),log:true});continue}let s=Math.max(1e-9,Math.abs(i.max-i.min)),a=vt(o.min,i.min,e,Fi),l=vt(o.max,i.max,e,Fi);Math.abs(a-i.min)<=s*.001&&Math.abs(l-i.max)<=s*.001?(a=i.min,l=i.max):t=true,n.scale={min:a,max:l,log:i.log};}for(let n of this.scene.indicatorScales.values()){let i=n.scaleTarget,o=n.scale,s=Math.max(1e-9,Math.abs(i.max-i.min)),a=vt(o.min,i.min,e,Fi),l=vt(o.max,i.max,e,Fi);Math.abs(a-i.min)<=s*.001&&Math.abs(l-i.max)<=s*.001?(a=i.min,l=i.max):t=true,n.scale={min:a,max:l};}return t}emitViewportChange(){this.updateScrollToRealtimeButton();let e=this.getVisibleRange();if(e)for(let t of this.viewportCbs)t(e);}handlePointerMove(e,t){if(e===null||t===null||this.coords.barCount===0){this.scene.crosshair=null,this.hoverSeparatorY=null,this.lastPointer=null,this.scheduler.invalidate(1),this.hoverLogical=null;let p={time:null,price:null,paneKind:null,values:new Map,ohlc:null};for(let m of this.crosshairCbs)m(p);return}let n=e>=0&&t>=0&&e<=this.coords.width&&t<=this.coords.height;this.scene.crosshair=n?{x:e,y:t}:null,this.lastPointer=n?{x:e,y:t}:null,this.hoverSeparatorY=e>=0&&t>=0&&t<=this.coords.height?this.separatorHoverY(t):null,this.scheduler.invalidate(1);let i=Math.round(this.coords.xToLogical(e)),o=i>=0&&i<this.coords.barCount,s=o?this.coords.logicalToTime(i):null,a=this.paneNodeAtY(t),l=n&&a?this.coords.yToPrice(t,a.scale,a.bounds):null,c=new Map;if(o)for(let p of this.scene.indicators.values()){let m=this.scene.offsetOf(p.id);for(let f of p.series)if(Ne(f)){let g=f.points[i-m]?.value;g!=null&&c.set(f.id,g);}}let d=o?this.bars[i]:void 0,u=d?{time:d.time,open:d.open,high:d.high,low:d.low,close:d.close,volume:d.volume}:null;this.hoverLogical=o?i:null;let h={time:s,price:l,paneKind:n&&a?a.kind:null,values:c,ohlc:u};for(let p of this.crosshairCbs)p(h);}handleClick(e){if(this.coords.barCount===0)return;let t=Math.round(this.coords.xToLogical(e)),n=t>=0&&t<this.coords.barCount;for(let i of this.clickCbs)i({time:n?this.coords.logicalToTime(t):null,price:null});}paneAtY(e){return this.paneNodeAtY(e)}paneNodeAtY(e){for(let t of this.scene.panes.values())if(e>=t.bounds.top&&e<=t.bounds.top+t.bounds.height)return t;return null}nearestPaneToY(e){let t=null,n=1/0;for(let i of this.scene.panes.values()){let o=e<i.bounds.top?i.bounds.top-e:e-(i.bounds.top+i.bounds.height);o<n&&(n=o,t=i);}return t}resolveScaleHolder(e,t){let n=this.paneNodeAtY(t);if(!n)return null;let i=this.coords.width,o=this.scene.ownScaleIndicatorsForPane(n.id);if(e>=i+64&&o.length>0){let s=Math.floor((e-i-64)/56),a=o[s];if(a)return {holder:this.scene.ensureIndicatorScale(a.id,n.scaleTarget),height:n.bounds.height}}return {holder:n,height:n.bounds.height}}beginPriceScale(e,t){let n=this.resolveScaleHolder(e,t);n&&(this.scaleDragHolder=n.holder,this.scaleDragHeight=n.height,this.scaleDragStart={...n.holder.scale},n.holder.manualScale={...n.holder.scale},this.axisScaleButtons?.reposition(),this.scheduler.invalidate(4));}priceScaleBy(e){let t=this.scaleDragHolder,n=this.scaleDragStart;!t||!n||this.setManualScale(t,Iw(n,Math.exp(e*ck)));}beginPricePan(e){let t=this.paneNodeAtY(e);return !t||!t.manualScale?false:(this.scaleDragHolder=t,this.scaleDragHeight=t.bounds.height,this.scaleDragStart={...t.scale},true)}pricePanBy(e){let t=this.scaleDragHolder,n=this.scaleDragStart;!t||!n||this.setManualScale(t,Aw(n,e,this.scaleDragHeight));}resetPriceScale(e,t){let n=this.resolveScaleHolder(e,t);n&&(n.holder.manualScale=null,this.axisScaleButtons?.reposition(),this.scheduler.invalidate(4));}dataDblClick(e,t){let n=this.paneNodeAtY(t)??this.nearestPaneToY(t);if(!n)return;let i=this.maximizedPaneId!==n.id;this.maximizedPaneId=i?n.id:null,this.afterPaneLayoutChange(),this.emitPaneAction({type:"maximize",paneId:n.id,maximized:i});}resetView(){this.fitContent(),this.scheduler.invalidate(4),this.emitViewportChange();}setManualScale(e,t){e.manualScale=t,e.scale={...t},e.scaleTarget={...t},e.initialized=true,this.scheduler.invalidate(4);}afterPaneLayoutChange(){this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}paneControlViews(){let e=this.scene.orderedPanes();return e.map((t,n)=>({id:t.id,kind:t.kind,collapsed:t.collapsed,maximized:this.maximizedPaneId===t.id,top:t.bounds.top,height:t.bounds.height,index:n,count:e.length}))}movePaneLocal(e,t){let n=this.scene.orderedPanes(),i=n.findIndex(l=>l.id===e);if(i<0)return;let o=t==="up"?i-1:i+1;if(o<1||o>=n.length)return;let s=n.map(l=>l.id),a=s[i];s[i]=s[o],s[o]=a,this.scene.orderPanes(s),this.afterPaneLayoutChange(),this.emitPaneAction({type:"move",paneId:e,dir:t});}paneSeparatorAt(e){return this.separatorPaneIndexAt(e)!==null}separatorHoverY(e){if(!this.paneResizeEnabled)return null;let t=this.separatorPaneIndexAt(e);return t===null?null:this.scene.orderedPanes()[t].bounds.top}separatorPaneIndexAt(e){let t=this.scene.orderedPanes();for(let n=1;n<t.length;n++)if(Math.abs(e-t[n].bounds.top)<=uk)return n;return null}beginPaneResize(e){let t=this.separatorPaneIndexAt(e);if(t===null)return;let n=this.scene.orderedPanes(),i=n[t-1],o=n[t];this.resizeAbove=i,this.resizeBelow=o,this.resizeSplitStart={combinedTop:i.bounds.top,combinedHeight:i.bounds.height+o.bounds.height,combinedWeight:i.heightWeight+o.heightWeight,startBoundaryY:o.bounds.top};}paneResizeBy(e){let t=this.resizeAbove,n=this.resizeBelow,i=this.resizeSplitStart;if(!t||!n||!i)return;let o=Rw(i,e);t.heightWeight=o.above,n.heightWeight=o.below,this.layoutPanes(),this.scheduler.invalidate(4);}resetPaneSize(e){let t=this.separatorPaneIndexAt(e);if(t===null)return;let n=this.scene.orderedPanes(),i=n[t-1],o=n[t],s=(i.heightWeight+o.heightWeight)/2;i.heightWeight=s,o.heightWeight=s,this.layoutPanes(),this.scheduler.invalidate(4);}setKeyboardEnabled(e){this.keyboardEnabled=e,!(!this.dataCanvas||!this.keyboard)&&(e?(this.dataCanvas.tabIndex=0,this.dataCanvas.setAttribute("role","application"),this.dataCanvas.setAttribute("aria-label","Interactive price chart. Use Left/Right arrows to move between bars, Shift+Arrow to pan, plus/minus to zoom, Home/End to jump, 0 to reset."),!this.liveRegion&&this.wrapper&&(this.liveRegion=document.createElement("div"),this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("role","status"),Object.assign(this.liveRegion.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:"0"}),this.wrapper.appendChild(this.liveRegion)),this.keyboard.attach(this.dataCanvas)):(this.keyboard.detach(),this.dataCanvas.removeAttribute("tabindex"),this.dataCanvas.removeAttribute("role"),this.dataCanvas.removeAttribute("aria-label")));}panByBars(e){let t=this.coords.getViewport();this.applyViewport({barSpacing:t.barSpacing,rightOffset:t.rightOffset+e});}zoomByStep(e){let t=this.coords.getViewport(),n=tn(t.barSpacing*Math.exp(e*dk));this.zoomTo(n,this.coords.rightEdgeLogical,this.coords.width);}stepCrosshair(e){let t=this.coords.barCount;if(t===0)return;let n=this.hoverLogical??Math.min(t-1,Math.round(this.coords.xToLogical(this.coords.width)));this.focusBar(n+e);}focusBar(e){let t=this.coords.barCount;if(t===0)return;let n=Math.max(0,Math.min(t-1,e)),i=this.coords.getViewport(),o=2,s=this.coords.xToLogical(0),a=this.coords.xToLogical(this.coords.width),l=i.rightOffset;n<s+o?l-=s+o-n:n>a-o&&(l+=n-(a-o)),l!==i.rightOffset&&this.applyViewport({barSpacing:i.barSpacing,rightOffset:l});let c=this.scene.orderedPanes().find(u=>u.kind==="price")??this.scene.orderedPanes()[0]??null,d=this.scene.crosshair?.y??(c?c.bounds.top+c.bounds.height/2:this.coords.height/2);this.handlePointerMove(this.coords.logicalToX(n),d),this.announceBar(n);}announceBar(e){if(!this.liveRegion)return;let t=this.bars[e],n=this.dataWindowPricePane(),i=this.dataWindowOHLC(t,n),o=[];t&&o.push(mk(t.time,this.scene.timezone)),i&&o.push(`Open ${i.o}, High ${i.h}, Low ${i.l}, Close ${i.c}`);for(let s of this.dataWindowGroups(e,n))for(let a of s.rows)o.push(`${a.label} ${a.value}`);this.liveRegion.textContent=o.join(". ");}getDataWindowReadout(){let e=this.bars.length;if(e===0)return {date:"",time:"",ohlc:null,groups:[]};let t=this.hoverLogical!=null?this.hoverLogical:e-1,n=this.bars[t],i=this.dataWindowPricePane(),o=n?qw(n.time,this.scene.timezone):{date:"",time:""};return {date:o.date,time:o.time,ohlc:this.dataWindowOHLC(n,i),groups:this.dataWindowGroups(t,i)}}dataWindowPricePane(){return this.scene.orderedPanes().find(e=>e.kind==="price")??null}dataWindowFmt(e,t){return t?Tc(t.scale,t.bounds.height,e,this.scene.priceMintick):String(e)}dataWindowOHLC(e,t){return e?{o:this.dataWindowFmt(e.open,t),h:this.dataWindowFmt(e.high,t),l:this.dataWindowFmt(e.low,t),c:this.dataWindowFmt(e.close,t),vol:e.volume!=null?Xw(e.volume):void 0,up:e.close>=e.open}:null}dataWindowGroups(e,t){let n=[];for(let i of this.scene.indicators.values()){let o=this.dataWindowRowsFor(i,e,t);o.length&&n.push({name:i.title,rows:o});}return n}dataWindowRowsFor(e,t,n){if(e.native?.type==="volume")return this.volumeReadoutRows(e,t);let i=(e.paneId?this.scene.panes.get(e.paneId):null)??n,o=this.scene.offsetOf(e.id),s=[];for(let a of e.series){let l,c;if(a.kind==="candle"||a.kind==="bar")l=a.bars[t-o]?.close,c=a.style?.up??this.theme.upColor;else if(Ne(a)){if(a.visible===false)continue;l=a.points[t-o]?.value,c=a.points[t-o]?.color??a.style.color;}else continue;l==null||!Number.isFinite(l)||s.push({label:a.title||e.title,value:this.dataWindowFmt(l,i),color:c});}return s}volumeReadoutRows(e,t){if(this.volumeHidden)return [];let n=this.bars[t],i=n?.volume;if(n==null||i==null||!Number.isFinite(i))return [];let o=this.scene.volumeLayer,s=n.close>=n.open?o?.upColor??this.theme.upColor:o?.downColor??this.theme.downColor;return [{label:e.title,value:Xw(i),color:s}]}updateLegendValues(){if(!this.inputsUI)return;let e=this.bars.length,t=new Map;if(e>0){let n=this.hoverLogical!=null?this.hoverLogical:e-1,i=this.dataWindowPricePane();for(let o of this.scene.indicators.values())t.set(o.id,this.dataWindowRowsFor(o,n,i).map(s=>({value:s.value,color:s.color})));}this.inputsUI.setPlotValues(t);}renderFrame(e){this.animator.active||(nh(e)?(this.computeScales(),this.paintData()):my(e)&&this.paintedData&&(this.chrome.prepare(this.scene,this.coords,this.theme),this.chrome.render(this.scene,this.coords,this.theme,this.axisSurface())),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx()),!nh(e)&&this.paintedData&&this.repaintCursorLayers(),this.updateLegendValues());}repaintCursorLayers(){let e=this.scene.panes.get(Be);if(!e)return;let t=typeof performance<"u"?performance.now():Date.now();for(let n of this.extLayers){if(!n.def.repaintOnCursor)continue;let i=this.layerPane(n.def.id)??e;i.collapsed||(n.instance.render(this.extLayerArgs(n.def.id,i.scale,i.bounds,t)),this.animZoom&&n.instance.animating?.()&&this.animator.start());}}clearLayerCanvas(e){e.width===0||e.height===0||e.getContext("2d")?.clearRect(0,0,e.width,e.height);}extLayerArgs(e,t,n,i){return {bars:this.scene.bars,data:this.scene.nativeData.get(e),settings:this.scene.nativeData.get(`${e}-settings`)??{},pending:this.scene.nativePending.get(e)??[],coords:this.coords,scale:t,bounds:n,theme:this.theme,priceStyle:this.scene.priceStyle,nowMs:i,cursor:this.lastPointer}}paintData(){this.syncLayerCanvasOrder(),this.stampScaleInvert(),this.backend.modelAlpha=this.modelAlpha,this.backend.candleBodyAlpha=this.candleBodyAlpha,this.backend.candleStructureAlpha=this.candleStructureAlpha;let e=1,t=1;this.backend.candleBodyScale=t;let n=this.scene.panes.get(Be);if(n){let a=this.nativeLayerPane("volume")??n;this.volumeRenderer.render({bars:this.scene.bars,data:this.scene.volumeLayer,visible:this.volumeActive&&!this.volumeHidden&&!a.collapsed,coords:this.coords,bounds:a.bounds,fillPane:a.kind!=="price"}),this.vpvrRenderer.render({bars:this.scene.bars,data:this.scene.vpvrLayer,visible:this.vpvrActive&&!this.vpvrHidden,coords:this.coords,scale:n.scale,bounds:n.bounds,theme:this.theme});let l=typeof performance<"u"?performance.now():Date.now(),c=null;for(let d of this.extLayers){let u=this.layerPane(d.def.id)??n;if(u.collapsed){this.clearLayerCanvas(d.canvas);continue}let h=this.extLayerArgs(d.def.id,u.scale,u.bounds,l);d.instance.render(h),u===n&&(c=Ow(c,d.instance.modulateBase?.(h)??null)),this.animZoom&&d.instance.animating?.()&&this.animator.start();}c&&(c.candleBodyScale!=null&&(this.backend.candleBodyScale=Gh(c.candleBodyScale)||.01),c.candleBodyAlpha!=null&&(this.backend.candleBodyAlpha=Gh(c.candleBodyAlpha)*this.candleBodyAlpha),c.gridAlpha!=null&&(e=Gh(c.gridAlpha)));}let i=this.bars.length-1,o=i>=0?this.bars[i]:void 0,s=!!o&&this.liveEaseTime===o.time&&(o.high!==this.liveEaseHigh||o.low!==this.liveEaseLow||o.close!==this.liveEaseClose);s&&o&&(this.bars[i]={...o,high:this.liveEaseHigh,low:this.liveEaseLow,close:this.liveEaseClose}),this.scene.drawingSlices=Cw(this.indicatorSlices.prepare(this.scene,this.coords,this.theme,this.dataCanvas),this.userDrawings?.prepareSlices(this.scene.orderedPanes().map(a=>a.id))??new Map),this.backdropRenderer.render(this.scene,this.coords,this.theme,e),this.backend.render(this.scene,this.coords,this.theme),this.chrome.render(this.scene,this.coords,this.theme,this.axisSurface()),this.userDrawings?.render(),s&&o&&(this.bars[i]=o),this.paintedData=true;}drawingProjector(){return Tw(this.coords,e=>{let t=this.scene.panes.get(e);return t?{scale:t.scale,bounds:t.bounds,collapsed:t.collapsed}:null},e=>this.paneNodeAtY(e)?.id??null,(e,t)=>this.barsInTimeRange(e,t),this.userDrawings?.seriesGateway?(e,t,n)=>this.userDrawings.seriesGateway.seriesInRange(e,t,n):void 0)}barsInTimeRange(e,t){let n=Math.min(e,t),i=Math.max(e,t),o=[];for(let s of this.bars)if(!(s.time<n)){if(s.time>i)break;o.push(s);}return o}get userDrawingsPort(){return this.userDrawings??void 0}focus(){this.dataCanvas?.focus({preventScroll:true});}setExternalCrosshair(e,t=null){let n=e==null?null:{time:e,price:t},i=this.externalCross;!n&&!i||n&&i&&i.time===n.time&&i.price===n.price||(this.externalCross=n,this.scheduler.invalidate(1));}externalCrossPx(){let e=this.externalCross;if(!e||this.coords.barCount===0)return null;let t=Math.floor(this.coords.timeToLogical(e.time));if(t<0||t>=this.coords.barCount)return null;let n=this.coords.logicalToX(t);if(!Number.isFinite(n)||n<0||n>this.coords.width)return null;let i=null;if(e.price!=null){let o=this.scene.orderedPanes().find(s=>s.kind==="price");o&&(i=this.coords.priceToY(e.price,o.scale,o.bounds),(!Number.isFinite(i)||i<o.bounds.top||i>o.bounds.top+o.bounds.height)&&(i=null));}return {x:n,y:i,time:this.coords.logicalToTime(t),price:i!=null?e.price:null}}setSnapMode(e){this.snapMode=e;}snapToCandle(e,t,n="strong",i){if(n==="off")return e;let o=this.bars.length;if(o===0)return e;let s=Math.max(0,Math.min(o-1,Math.round(this.coords.timeToLogical(e.time)))),a=this.bars[s];if(!a)return e;let l;if(t!==Be)l={time:a.time,price:e.price};else {let c=a.open;for(let d of [a.high,a.low,a.close])Math.abs(d-e.price)<Math.abs(c-e.price)&&(c=d);l={time:a.time,price:c};}if(n==="weak"&&i){let c=this.drawingProjector(),d=c.yOf(l.price,t);if(Math.hypot(c.xOf(l.time)-i.x,(d??i.y)-i.y)>ZM)return e}return l}computeScales(){let e=this.coords.barCount;if(e===0)return;let t=this.coords.visibleLogicalRange(),n=Math.max(0,Math.floor(t.from)),i=Math.min(e-1,Math.ceil(t.to));if(i<n)return;this.scene.percentBaseline=this.bars[n]?.close??0;let o=this.scene.orderedPanes(),s=o.find(l=>l.kind==="price")??null;this.chrome.prepare(this.scene,this.coords,this.theme);let a=this.animator.active;for(let l of o){if(l.manualScale){l.scaleTarget=l.manualScale,l.scale={...l.manualScale},l.initialized=true;continue}let d=this.scene.indicatorsForPane(l.id).filter(p=>p.ownScale!==true),u=this.chrome.paneDrawingsRange(d,this.scene,l===s,t);if(l===s){let p=Mw(this.scene.indicators.values(),n,i,m=>this.scene.offsetOf(m));p&&(u=u?{min:Math.min(u.min,p.min),max:Math.max(u.max,p.max)}:p);}let h=l.kind==="price"&&!this.scene.candlesHidden;if(l.scaleTarget=$c(d,this.bars,h,n,i,u,Mi(this.scene,l),p=>this.scene.offsetOf(p)),l.percentBaseline=l.kind==="price"?this.bars[n]?.close??0:this.firstVisibleValue(d,n),l.axisFormat=void 0,l.axisBands=void 0,this.volumeOwnsPane(l,d)){let p=this.maxVisibleVolume(n,i);p>0&&(l.scaleTarget={min:0,max:p/Oh},l.axisFormat="volume");}else if(this.layerNativesOwnPane(l,d)&&(l.scaleTarget=$c([],this.bars,true,n,i,u,Mi(this.scene,l),p=>this.scene.offsetOf(p)),l.percentBaseline=this.bars[n]?.close??0,d.every(p=>p.paneAxis!=null))){l.axisFormat="none";let p=d.find(m=>typeof m.paneAxis=="object");l.axisBands=p?p.paneAxis.bands:void 0;}if(l===s&&this.scene.tradeMarkers.visible&&l.bounds.height>0){let p=this.tradesScaleHints(t);if(p){let m=l.scaleTarget,f={...m,min:Math.min(m.min,p.min),max:Math.max(m.max,p.max)};l.scaleTarget=kw(f,l.bounds.height,p.abovePx,p.belowPx);}}(!a||!l.initialized)&&(l.scale={...l.scaleTarget},l.initialized=true);for(let p of this.scene.ownScaleIndicatorsForPane(l.id)){let m=this.scene.ensureIndicatorScale(p.id,l.scaleTarget);if(m.manualScale){m.scaleTarget=m.manualScale,m.scale={...m.manualScale},m.initialized=true;continue}let f=this.chrome.paneDrawingsRange([p],this.scene,false,t);m.scaleTarget=$c([p],this.bars,false,n,i,f,false,g=>this.scene.offsetOf(g)),(!a||!m.initialized)&&(m.scale={...m.scaleTarget},m.initialized=true);}}}tradesScaleHints(e){let t=null,n={timeToLogical:i=>this.coords.timeToLogical(i),barAt:i=>{let o=this.bars[Math.round(i)];return o?{high:o.high,low:o.low}:null}};for(let i of this.scene.indicators.values()){if(!i.trades?.length)continue;let o=Ly(i.trades,this.scene.tradeMarkers,n,e.from,e.to,this.scene.style.fontSize);o&&(t=t?{min:Math.min(t.min,o.min),max:Math.max(t.max,o.max),abovePx:Math.max(t.abovePx,o.abovePx),belowPx:Math.max(t.belowPx,o.belowPx)}:o);}return t}fitContent(){let e=this.coords.barCount,t=this.coords.width;if(e<=0||t<=0)return;this.animator?.stop(),this.panVelocity=0;for(let s of this.scene.panes.values())s.manualScale=null;for(let s of this.scene.indicatorScales.values())s.manualScale=null;let n=Math.min(e,200),i=6,o=this.clampViewport(t/((n+i)*this.coords.spacingScale),i);this.coords.setViewport(o),this.targetBarSpacing=o.barSpacing;}reframeKeepZoom(){this.animator?.stop(),this.panVelocity=0;for(let t of this.scene.panes.values())t.manualScale=null;for(let t of this.scene.indicatorScales.values())t.manualScale=null;let e={barSpacing:tn(this.coords.getViewport().barSpacing),rightOffset:ns().rightOffset};this.coords.setViewport(e),this.targetBarSpacing=e.barSpacing;}paneBoundsFor(e){let t=this.scene.panes.get(e);return {top:t?.bounds.top??0,height:t?.bounds.height??0,rightAxis:this.rightAxisW}}paneMasterTitle(e){let t=this.scene.orderedIndicatorsForPane(e);return (t.find(i=>i.ownScale!==true)??t[0])?.title||null}nativeLayerPane(e){for(let t of this.scene.indicators.values())if(t.native?.type===e)return this.scene.panes.get(t.paneId??Be)??null;return null}layerOwner(e){for(let t of this.scene.indicators.values())if(t.native?.type===e)return t;return null}layerPane(e){let t=this.layerOwner(e),n=t?t.paneId??Be:Be;return this.scene.panes.get(n)??null}orderedLayerCanvases(){let e=new Map(this.extLayers.map(i=>[i.def.id,i.canvas])),{below:t,above:n}=Nw(this.extLayers.map(i=>{let o=this.layerOwner(i.def.id);return {id:i.def.id,placement:i.def.placement==="below-data"?"below-data":"above-data",ownerZ:o?this.scene.zOf(o.id):null}}),this.scene.candleZ);return {below:t.map(i=>e.get(i)),above:n.map(i=>e.get(i))}}canvasPile(){let{below:e,above:t}=this.orderedLayerCanvases();return [this.backdropCanvas,...e,this.dataCanvas,this.volumeCanvas,this.vpvrCanvas,...t]}syncLayerCanvasOrder(){if(this.extLayers.length===0||!this.plot)return;let{below:e,above:t}=this.orderedLayerCanvases(),n=[...e.map(i=>this.extLayers.find(o=>o.canvas===i).def.id),"|",...t.map(i=>this.extLayers.find(o=>o.canvas===i).def.id)].join(",");if(n!==this.layerOrderSig){this.layerOrderSig=n;for(let i of e)this.plot.insertBefore(i,this.dataCanvas);for(let i of t)this.plot.insertBefore(i,this.chromeCanvas);}}volumeOwnsPane(e,t){return e.kind==="price"||!this.volumeActive||this.volumeHidden||!this.scene.volumeLayer||this.nativeLayerPane("volume")!==e?false:t.every(n=>n.native?.type==="volume")}layerNativesOwnPane(e,t){return e.kind==="price"||t.length===0?false:t.every(n=>n.series.length===0&&!!n.native&&this.extLayers.some(i=>i.def.id===n.native.type))}paneScaleInfos(){return this.scene.orderedPanes().map(e=>({id:e.id,kind:e.kind,top:e.bounds.top,height:e.bounds.height,mode:ah(this.scene,e),log:Mi(this.scene,e),invert:lh(this.scene,e)}))}axisScaleViews(){return this.scene.orderedPanes().map(e=>({id:e.id,top:e.bounds.top,height:e.bounds.height,collapsed:e.collapsed,auto:e.manualScale==null,log:Mi(this.scene,e)}))}togglePaneAuto(e){let t=this.scene.panes.get(e);t&&(t.manualScale=t.manualScale==null?{...t.scale}:null,this.scheduler?.invalidate(4));}setPaneScaleMode(e,t){if(e===Be)this.scene.scaleMode=t;else {let n=this.scene.panes.get(e);if(!n)return;n.scaleMode=t;}this.scheduler?.invalidate(4);}setPaneLog(e,t){let n=e===Be?this.scene.orderedPanes().find(i=>i.kind==="price"):this.scene.panes.get(e);if(e===Be)this.scene.logScale=t;else {if(!n)return;n.logScale=t;}n?.manualScale&&(n.manualScale.log=t),this.scheduler?.invalidate(4);}setPaneInvert(e,t){if(e===Be)this.scene.invertScale=t;else {let n=this.scene.panes.get(e);if(!n)return;n.invert=t;}this.scheduler?.invalidate(4);}stampScaleInvert(){for(let e of this.scene.panes.values()){let t=lh(this.scene,e);e.scale.invert=t,e.scaleTarget.invert=t,e.manualScale&&(e.manualScale.invert=t);for(let n of this.scene.ownScaleIndicatorsForPane(e.id)){let i=this.scene.indicatorScales.get(n.id);i&&(i.scale.invert=t,i.scaleTarget.invert=t,i.manualScale&&(i.manualScale.invert=t));}}}firstVisibleValue(e,t){for(let n of e){let i=this.scene.offsetOf(n.id);for(let o of n.series)if(o.overlay!==true){if(Ne(o)){let s=o.points[t-i]?.value;if(s!=null&&Number.isFinite(s))return s}else if(o.kind==="candle"||o.kind==="bar"){let s=o.bars[t-i];if(s&&Number.isFinite(s.close))return s.close}}}return 0}maxVisibleVolume(e,t){let n=0;for(let i=e;i<=t;i+=1){let o=this.bars[i]?.volume;o!=null&&o>n&&(n=o);}return n}layoutPanes(){let e=this.scene.orderedPanes(),t=this.coords.height;this.inputsUI?.setCollapsedPanes(this.collapsedMasterMap());let n=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null;if(n){let d=0;for(let u of e)u===n?u.bounds={top:0,height:t}:u.bounds={top:t,height:0},d+=u.bounds.height;this.inputsUI?.reposition(),this.paneControls?.reposition(),this.axisScaleButtons?.reposition(),this.repositionScrollButton(),this.positionAttribution(),this.publishPricePaneBounds();return}let i=e.filter(d=>d.collapsed),o=e.filter(d=>!d.collapsed),s=i.length*Gw,a=Math.max(0,t-s),l=o.reduce((d,u)=>d+(u.heightWeight||1),0)||1,c=0;for(let d of e){let u=d.collapsed?Gw:a*(d.heightWeight||1)/l;d.bounds={top:c,height:u},c+=u;}this.inputsUI?.reposition(),this.paneControls?.reposition(),this.axisScaleButtons?.reposition(),this.repositionScrollButton(),this.positionAttribution(),this.publishPricePaneBounds();}repositionScrollButton(){let e=this.coords.height;if(e<=0)return;let t=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null,n=t?[t]:this.scene.orderedPanes().filter(o=>!o.collapsed),i=n.length?Math.max(...n.map(o=>o.bounds.top+o.bounds.height)):e;this.scrollBtnBottomPx=Wh+Math.max(0,e-i),this.mountContainer?.style.setProperty("--vela-bottom-gutter",`${Vi+Math.max(0,e-i)}px`),this.scrollBtnRightPx=this.rightAxisW+jw,this.scrollButton&&(this.scrollButton.style.bottom=`${this.scrollBtnBottomPx}px`,this.scrollButton.style.right=`${this.scrollBtnRightPx}px`);}collapsedMasterMap(){let e=new Map;for(let t of this.scene.panes.values()){if(!t.collapsed)continue;let n=this.scene.orderedIndicatorsForPane(t.id),i=new Set(this.scene.ownScaleIndicatorsForPane(t.id).map(s=>s.id)),o=n.find(s=>!i.has(s.id))??n[0];e.set(t.id,o?.id??null);}return e}setToolbarGutter(e){e!==this.toolbarGutter&&(this.toolbarGutter=e,this.publishGutters(),this.positionAttribution(),this.syncSize());}publishGutters(){this.mountContainer?.style.setProperty("--vela-toolbar-gutter",`${this.toolbarGutter}px`),this.mountContainer?.style.setProperty("--vela-scale-gutter",`${this.rightAxisW}px`);}publishPricePaneBounds(){if(!this.mountContainer)return;let e=this.coords.height+Vi,t=this.scene.panes.get(Be),n=t?t.bounds.top:0,i=t?t.bounds.height:this.coords.height,o=Math.max(0,e-(n+i));this.mountContainer.style.setProperty("--vela-price-pane-top",`${n}px`),this.mountContainer.style.setProperty("--vela-price-pane-bottom",`${o}px`);}buildAttributionEl(){return this.attributionHtml!==null?Bw(document,this.attributionHtml,this.theme.background):Hw(document,this.theme.background)}rebuildAttribution(){this.attributionEl&&(this.attributionEl.remove(),this.attributionEl=this.buildAttributionEl(),this.attributionEnabled||(this.attributionEl.style.display="none"),this.positionAttribution(),this.wrapper.appendChild(this.attributionEl));}positionAttribution(){if(!this.attributionEl)return;let e=this.coords?.height??0,t=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null,n=t?[t]:this.scene.orderedPanes().filter(o=>!o.collapsed),i=e>0&&n.length?Math.max(...n.map(o=>o.bounds.top+o.bounds.height)):e;Object.assign(this.attributionEl.style,{left:`${(this.toolbarGutter||0)+12}px`,bottom:`${Vi+10+Math.max(0,e-i)}px`});}refreshAttributionColor(){this.attributionEl&&(this.attributionHtml!==null?this.attributionEl.style.color=_h(this.theme.background):Bh(this.attributionEl,this.theme.background));}syncSize(){let e=this.wrapper.clientWidth,t=this.wrapper.clientHeight;if(e<=0||t<=0)return;let n=window.devicePixelRatio||1;this.plot.style.left=`${this.toolbarGutter}px`;let i=this.plot.getBoundingClientRect(),o=Math.max(1,Math.round(i.width*n)),s=Math.max(1,Math.round(i.height*n)),a=this.plotDeviceSize;a&&Math.abs(a.width-i.width*n)<=1&&Math.abs(a.height-i.height*n)<=1&&(o=Math.max(1,a.width),s=Math.max(1,a.height));let l=o/n,c=s/n,d=u=>{u.width=o,u.height=s,u.style.width=`${l}px`,u.style.height=`${c}px`;};d(this.dataCanvas),d(this.backdropCanvas),d(this.volumeCanvas);for(let u of this.extLayers)d(u.canvas);d(this.vpvrCanvas),d(this.chromeCanvas),d(this.drawingsCanvas),d(this.cursorCanvas),this.coords.setSize(Math.max(1,l-this.rightAxisW),Math.max(1,c-Vi),n),this.scene.crosshair=null,this.layoutPanes(),this.userDrawings?.onResize(),!this.didInitialFit&&this.coords.barCount>0&&(this.fitContent(),this.didInitialFit=true),this.animator.active?(this.computeScales(),this.paintData(),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx())):this.scheduler.flushNow(4);}applyBackground(){this.wrapper.style.background=this.theme.background;}};function hk(r,e){for(let t of r.series){let n=t.kind==="candle"||t.kind==="bar"?t.bars:Ne(t)?t.points:null;if(!n||n.length===0)continue;let i=0,o=n.length;for(;i<o;){let s=i+o>>1;n[s].time<e?i=s+1:o=s;}return i}return null}function pk(r,e){if(e.kind==="value"){for(let t of e.series){let n=r.series.find(i=>i.id===t.seriesId);n&&(t.kind==="points"&&Ne(n)?n.points=t.points:t.kind==="bars"&&(n.kind==="candle"||n.kind==="bar")&&(n.bars=t.bars));}e.lines&&(r.lines=e.lines),e.boxes&&(r.boxes=e.boxes),e.labels&&(r.labels=e.labels),e.polylines&&(r.polylines=e.polylines),e.linefills&&(r.linefills=e.linefills),e.tables&&(r.tables=e.tables),e.trades&&(r.trades=e.trades);return}for(let t of e.removed){let n=r.series.findIndex(i=>i.id===t);n>=0&&r.series.splice(n,1);}for(let t of e.added)r.series.push(t);}function qw(r,e){let t=wc(r,e),n=i=>i<10?`0${i}`:String(i);return {date:`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())}`,time:`${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}}function mk(r,e){let{date:t,time:n}=qw(r,e);return `${t} ${n}`}function fk(r){if(!Array.isArray(r))return [];let e=[];for(let t of r){if(!t||typeof t!="object")continue;let n=t,i=Number(n.from),o=Number(n.to);!Number.isFinite(i)||!Number.isFinite(o)||o<=i||e.push({from:i,to:o,color:typeof n.color=="string"?n.color:"rgba(120,130,160,0.10)"});}return e.sort((t,n)=>t.from-n.from)}function gk(r){if(r==null||typeof r!="object")return null;let e=r,t=n=>{if(!Array.isArray(n))return [];let i=[];for(let o of n){if(!Array.isArray(o))continue;let s=Number(o[0]),a=Number(o[1]);Number.isFinite(s)&&Number.isFinite(a)&&a>s&&i.push([s,a]);}return i.sort((o,s)=>o[0]-s[0])};return {pre:t(e.pre),post:t(e.post),extended:t(e.extended)}}function Gh(r){return Math.max(0,Math.min(1,r))}function bk(r){return typeof r=="string"&&Ei().includes(r)}function Kw(r){return r==="percent"||r==="indexed"?r:"price"}function Xw(r){let e=Math.abs(r);return e>=1e9?`${(r/1e9).toFixed(2)}B`:e>=1e6?`${(r/1e6).toFixed(2)}M`:e>=1e3?`${(r/1e3).toFixed(2)}K`:r.toFixed(2)}function vk(r){let e=[...r].sort((n,i)=>n.time-i.time),t=[];for(let n of e){let i=t[t.length-1];i&&i.time===n.time?t[t.length-1]=n:t.push(n);}return t}function Uh(r,e){let t=(r.open+r.high+r.low+r.close)/4,n=e?(e.open+e.close)/2:(r.open+r.close)/2;return {time:r.time,open:n,high:Math.max(r.high,n,t),low:Math.min(r.low,n,t),close:t,...r.volume!=null?{volume:r.volume}:{}}}function Zw(r){let e=new Array(r.length),t;for(let n=0;n<r.length;n+=1)t=Uh(r[n],t),e[n]=t;return e}var yk={full:Zw,next:Uh};function Jw(){Cd({id:"heikinashi",label:"Heikin Ashi",barTransform:yk});}var Yh=z,Kh=W,Xh=20;function wk(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function Qw(r,e){return typeof r=="string"&&r!==""?r:e}function jc(r){return {upColor:Qw(r.upColor,Yh),downColor:Qw(r.downColor,Kh),heightFrac:Math.min(.5,Math.max(.05,wk(r.heightPct,Xh)/100))}}var jh=class{constructor(){this.ctx=null;this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData(jc(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx?.pushData(jc(e));}suspend(){}resume(){this.ctx?.pushData(jc(this.inputs));}stop(){}},ex={type:"volume",title:"Volume",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"upColor",title:"Up color",type:"color",defval:Yh},{key:"downColor",title:"Down color",type:"color",defval:Kh},{key:"heightPct",title:"Height %",type:"int",defval:Xh,min:5,max:50,step:1,tooltip:"Pane height the tallest visible bar occupies"}],defaultInputs:()=>({upColor:Yh,downColor:Kh,heightPct:Xh}),create:()=>new jh};function qh(){Ln(ex);}var Jh=24,Qh=30,ep=Ye,tp=W,np=70;function Zh(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function tx(r,e){return typeof r=="string"&&r!==""?r:e}function qc(r){return {rows:Math.round(Math.min(400,Math.max(2,Zh(r.rows,Jh)))),widthFrac:Math.min(.9,Math.max(.05,Zh(r.widthPct,Qh)/100)),upColor:tx(r.upColor,ep),downColor:tx(r.downColor,tp),showPoc:r.showPoc!==false,valueAreaFrac:Math.min(1,Math.max(0,Zh(r.valueAreaPct,np)/100))}}var rp=class{constructor(){this.ctx=null;this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData(qc(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx?.pushData(qc(e));}suspend(){}resume(){this.ctx?.pushData(qc(this.inputs));}stop(){}},nx={type:"vpvr",title:"Visible Range Volume Profile",shortTitle:"VRVP",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"rows",title:"Rows",type:"int",defval:Jh,min:2,max:400,step:1},{key:"widthPct",title:"Width %",type:"int",defval:Qh,min:5,max:90,step:1,tooltip:"Pane width the largest row occupies"},{key:"upColor",title:"Up color",type:"color",defval:ep},{key:"downColor",title:"Down color",type:"color",defval:tp},{key:"showPoc",title:"Point of control",type:"bool",defval:true},{key:"valueAreaPct",title:"Value area %",type:"int",defval:np,min:0,max:100,step:1}],defaultInputs:()=>({rows:Jh,widthPct:Qh,upColor:ep,downColor:tp,showPoc:true,valueAreaPct:np}),create:()=>new rp};function ip(){Ln(nx);}function Xn(r){let e=r.title.trim().toLowerCase().replace(/\s+/g,"-");return `${r.instanceId}:${r.kind}:${e}#${r.ordinal}`}function I(r,e,t){let n=r[e];return typeof n=="number"&&Number.isFinite(n)?n:t}function F(r,e,t){let n=r[e];return typeof n=="string"&&n!==""?n:t}function sp(r,e,t){let n=r[e];return typeof n=="boolean"?n:t}function xk(r,e,t){let n=new Array(r.length);for(let i=0;i<r.length;i++){let o=e[i],s={time:r[i].time,value:o!=null&&Number.isFinite(o)?o:null},a=t?.[i];a!=null&&(s.color=a),n[i]=s;}return n}var op=class{constructor(e){this.spec=e;this.ctx=null;this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,this.recompute();}onBars(){this.recompute();}onViewport(){}setInputs(e){this.inputs=e,this.ctx&&this.recompute();}suspend(){}resume(){this.recompute();}stop(){}recompute(){if(!this.ctx)return;let e=this.ctx.bars(),t=this.spec.compute(e,this.inputs),n=this.spec.type,i=[],o=new Map;t.plots.forEach((c,d)=>{let u=c.kind??"line",h=Xn({instanceId:n,kind:u,title:c.title,ordinal:d});o.set(c.key,h),i.push({id:h,title:c.title,paneId:"",kind:u,points:xk(e,c.values,c.colors),style:{color:c.color,width:c.width??1,lineStyle:c.lineStyle??"solid",...c.base!=null?{base:c.base}:{}},...c.overlay?{overlay:true}:{}});}),t.markers&&t.markers.length>0&&i.push({id:Xn({instanceId:n,kind:"markers",title:"markers",ordinal:0}),title:this.spec.shortTitle??this.spec.title,paneId:"",kind:"markers",markers:t.markers});let s=(t.bands??[]).flatMap((c,d)=>{let u=o.get(c.from),h=o.get(c.to);return !u||!h?[]:[{id:Xn({instanceId:n,kind:"fill",title:c.key,ordinal:d}),paneId:"",fromSeriesId:u,toSeriesId:h,color:c.color}]}),a=(t.levels??[]).map((c,d)=>({id:Xn({instanceId:n,kind:"hline",title:c.key,ordinal:d}),paneId:"",price:c.price,...c.color!=null?{color:c.color}:{},lineStyle:c.lineStyle??"dashed",width:1,...c.title!=null?{title:c.title}:{}})),l=(t.polylines??[]).map((c,d)=>{let{key:u,...h}=c;return {id:Xn({instanceId:n,kind:"polyline",title:u,ordinal:d}),paneId:"",...h}});this.ctx.emit({series:i,fills:s,priceLines:a,polylines:l}),this.ctx.setStatus("idle");}};function rx(r){return {type:r.type,title:r.title,...r.shortTitle!=null?{shortTitle:r.shortTitle}:{},paneHint:r.overlay?"price":"new",overlay:r.overlay,multiInstance:true,inputsSchema:()=>r.inputs,defaultInputs:()=>Object.fromEntries(r.inputs.map(e=>[e.key,e.defval])),create:()=>new op(r)}}var ix=["Close","Open","High","Low","HL2","HLC3","OHLC4","HLCC4"];function ee(r,e){let t=new Array(r.length);for(let n=0;n<r.length;n++){let i=r[n];switch(e){case "Open":t[n]=i.open;break;case "High":t[n]=i.high;break;case "Low":t[n]=i.low;break;case "HL2":t[n]=(i.high+i.low)/2;break;case "HLC3":t[n]=(i.high+i.low+i.close)/3;break;case "OHLC4":t[n]=(i.open+i.high+i.low+i.close)/4;break;case "HLCC4":t[n]=(i.high+i.low+i.close+i.close)/4;break;default:t[n]=i.close;}}return t}function xt(r){return r.map(e=>e.volume!=null&&Number.isFinite(e.volume)?e.volume:Number.NaN)}function Ge(r){return r.map(e=>e.high)}function Ue(r){return r.map(e=>e.low)}function De(r){return r.map(e=>e.close)}function ox(r){return r.map(e=>e.open)}function K(r,e,t){let n=new Array(r.length);for(let i=0;i<r.length;i++){let o=r[i],s=e[i];n[i]=Number.isFinite(o)&&Number.isFinite(s)?t(o,s):Number.NaN;}return n}function ae(r,e){let t=new Array(r.length);for(let n=0;n<r.length;n++){let i=r[n];t[n]=Number.isFinite(i)?e(i):Number.NaN;}return t}function Te(r,e){return K(r,e,(t,n)=>t-n)}function En(r,e,t){let n=new Array(r.length).fill(Number.NaN);if(e<=0)return n;let i=0;for(let o=0;o<r.length;o++)i=Number.isFinite(r[o])?i+1:0,i>=e&&(n[o]=t(r,o-e+1,o));return n}function we(r,e){return En(r,e,(t,n,i)=>{let o=0;for(let s=n;s<=i;s++)o+=t[s];return o})}function fe(r,e){return En(r,e,(t,n,i)=>{let o=0;for(let s=n;s<=i;s++)o+=t[s];return o/e})}function Zc(r,e){let t=e*(e+1)/2;return En(r,e,(n,i,o)=>{let s=0;for(let a=i;a<=o;a++)s+=n[a]*(a-i+1);return s/t})}function sx(r,e,t){let n=K(r,e,(i,o)=>i*o);return K(we(n,t),we(e,t),(i,o)=>o>0?i/o:Number.NaN)}function rn(r,e){return En(r,e,(t,n,i)=>{let o=0;for(let l=n;l<=i;l++)o+=t[l];let s=o/e,a=0;for(let l=n;l<=i;l++){let c=t[l]-s;a+=c*c;}return Math.sqrt(a/e)})}function ct(r,e){return En(r,e,(t,n,i)=>{let o=-1/0;for(let s=n;s<=i;s++)t[s]>o&&(o=t[s]);return o})}function St(r,e){return En(r,e,(t,n,i)=>{let o=1/0;for(let s=n;s<=i;s++)t[s]<o&&(o=t[s]);return o})}function ax(r,e){return En(r,e,(t,n,i)=>{let o=-1/0,s=i;for(let a=n;a<=i;a++)t[a]>=o&&(o=t[a],s=a);return i-s})}function lx(r,e){return En(r,e,(t,n,i)=>{let o=1/0,s=i;for(let a=n;a<=i;a++)t[a]<=o&&(o=t[a],s=a);return i-s})}function cx(r,e,t){let n=new Array(r.length).fill(Number.NaN),i=0,o=Number.NaN;for(let s=0;s<r.length;s++){let a=r[s];if(!Number.isFinite(a)){i=0,o=Number.NaN;continue}if(i+=1,Number.isFinite(o))o=t*a+(1-t)*o,n[s]=o;else if(i>=e){let l=0;for(let c=s-e+1;c<=s;c++)l+=r[c];o=l/e,n[s]=o;}}return n}function Q(r,e){return cx(r,e,2/(e+1))}function Le(r,e){return cx(r,e,1/e)}function He(r,e=1){let t=new Array(r.length).fill(Number.NaN);for(let n=e;n<r.length;n++){let i=r[n],o=r[n-e];Number.isFinite(i)&&Number.isFinite(o)&&(t[n]=i-o);}return t}function Ft(r,e){let t=new Array(r.length).fill(Number.NaN);for(let n=e;n<r.length;n++){let i=r[n],o=r[n-e];Number.isFinite(i)&&Number.isFinite(o)&&o!==0&&(t[n]=100*(i-o)/o);}return t}function ot(r,e){let t=new Array(r.length).fill(Number.NaN);for(let n=0;n<r.length;n++){let i=n-e;i>=0&&i<r.length&&(t[n]=r[i]);}return t}function jn(r){let e=new Array(r.length).fill(Number.NaN);for(let t=0;t<r.length;t++){let n=r[t];if(t===0){e[t]=n.high-n.low;continue}let i=r[t-1].close;e[t]=Math.max(n.high-n.low,Math.abs(n.high-i),Math.abs(n.low-i));}return e}function Vr(r,e){return Le(jn(r),e)}function ws(r,e){let t=He(r),n=ae(t,o=>Math.max(o,0)),i=ae(t,o=>Math.max(-o,0));return K(Le(n,e),Le(i,e),(o,s)=>s===0?100:100-100/(1+o/s))}function Jc(r,e,t,n){let i=ct(e,n),o=St(t,n),s=new Array(r.length).fill(Number.NaN);for(let a=0;a<r.length;a++){let l=r[a],c=i[a],d=o[a];!Number.isFinite(l)||!Number.isFinite(c)||!Number.isFinite(d)||(s[a]=c===d?50:100*(l-d)/(c-d));}return s}function Qc(r,e){let t=(e-1)*e/2,n=(e-1)*e*(2*e-1)/6,i=e*n-t*t;return En(r,e,(o,s,a)=>{let l=0,c=0;for(let h=s;h<=a;h++){let p=h-s;l+=o[h],c+=p*o[h];}let d=i===0?0:(e*c-t*l)/i;return (l-d*t)/e+d*(e-1)})}function ed(r){let e=new Array(r.length).fill(Number.NaN);for(let t=3;t<r.length;t++){let n=r[t-3],i=r[t-2],o=r[t-1],s=r[t];Number.isFinite(n)&&Number.isFinite(i)&&Number.isFinite(o)&&Number.isFinite(s)&&(e[t]=(n+2*i+2*o+s)/6);}return e}function dx(r,e){let t=new Array(r.length).fill(Number.NaN);for(let n=e;n<r.length;n++){let i=r[n];if(!Number.isFinite(i))continue;let o=0,s=0;for(let a=n-e;a<n;a++){let l=r[a];if(!Number.isFinite(l)){s=-1;break}s+=1,l<=i&&(o+=1);}s===e&&(t[n]=100*o/e);}return t}function xs(r){let e=new Array(r.length).fill(Number.NaN),t=0,n=false;for(let i=0;i<r.length;i++){let o=r[i];Number.isFinite(o)&&(t+=o,n=true),n&&(e[i]=t);}return e}function D(r,e="length",t="Length",n=5e3){return {key:e,title:t,type:"int",defval:r,min:1,max:n,step:1}}function be(r="Close"){return {key:"source",title:"Source",type:"string",defval:r,options:ix}}function X(r=_,e="Color",t="color"){return {key:t,title:e,type:"color",defval:r}}function Pn(r,e=.08){let t=/^#([0-9a-f]{6})$/i.exec(r.trim());if(!t)return r;let n=Math.round(e*255).toString(16).padStart(2,"0");return `#${t[1]}${n}`}var Sk=["SMA","EMA","WMA","RMA","VWMA"],ux={key:"offset",title:"Offset",type:"int",defval:0,min:-500,max:500,step:1};function hx(r,e,t,n){return {type:r,title:e,shortTitle:t,overlay:true,inputs:[D(20),be(),ux,X()],compute:(i,o)=>{let s=I(o,"length",20),a=n(ee(i,F(o,"source","Close")),s),l=Math.trunc(I(o,"offset",0));return l!==0&&(a=ot(a,l)),{plots:[{key:t.toLowerCase(),title:t,values:a,color:F(o,"color",_),width:2}]}}}}var Ck=hx("sma","Simple Moving Average","SMA",fe),Tk=hx("ema","Exponential Moving Average","EMA",Q),Ek={type:"moving-average",title:"Moving Average",shortTitle:"MA",overlay:true,inputs:[{key:"maType",title:"Type",type:"string",defval:"SMA",options:Sk},D(20),be(),ux,X()],compute:(r,e)=>{let t=I(e,"length",20),n=ee(r,F(e,"source","Close")),i=F(e,"maType","SMA"),o;switch(i){case "EMA":o=Q(n,t);break;case "WMA":o=Zc(n,t);break;case "RMA":o=Le(n,t);break;case "VWMA":o=sx(n,xt(r),t);break;default:o=fe(n,t);}let s=Math.trunc(I(e,"offset",0));return s!==0&&(o=ot(o,s)),{plots:[{key:"ma",title:i,values:o,color:F(e,"color",_),width:2}]}}},Pk={type:"rma",title:"Smoothed Moving Average",shortTitle:"RMA",overlay:true,inputs:[D(14),be(),X()],compute:(r,e)=>({plots:[{key:"rma",title:"RMA",values:Le(ee(r,F(e,"source","Close")),I(e,"length",14)),color:F(e,"color",_),width:2}]})},Lk={type:"zlema",title:"Zero-Lag Exponential Moving Average",shortTitle:"ZLEMA",overlay:true,inputs:[D(14),be(),X()],compute:(r,e)=>{let t=I(e,"length",14),n=ee(r,F(e,"source","Close")),i=Math.floor((t-1)/2),o=ot(n,i),s=K(n,o,(a,l)=>2*a-l);return {plots:[{key:"zlema",title:"ZLEMA",values:Q(s,t),color:F(e,"color",_),width:2}]}}},Mk={type:"vidya",title:"Variable Index Dynamic Average",shortTitle:"VIDYA",overlay:true,inputs:[D(14),{key:"cmoLength",title:"Momentum length",type:"int",defval:9,min:1,max:500,step:1},be(),X()],compute:(r,e)=>{let t=I(e,"length",14),n=I(e,"cmoLength",9),i=ee(r,F(e,"source","Close")),o=He(i),s=new Array(i.length).fill(Number.NaN),a=new Array(i.length).fill(Number.NaN);for(let u=n;u<i.length;u++){let h=0,p=0,m=true;for(let f=u-n+1;f<=u;f++){let g=o[f];if(!Number.isFinite(g)){m=false;break}g>0?h+=g:p-=g;}m&&(s[u]=h,a[u]=p);}let l=2/(t+1),c=new Array(i.length).fill(Number.NaN),d=Number.NaN;for(let u=0;u<i.length;u++){let h=i[u],p=s[u],m=a[u];if(!Number.isFinite(h)||!Number.isFinite(p)||!Number.isFinite(m))continue;let f=p+m,g=f===0?0:Math.abs((p-m)/f);d=Number.isFinite(d)?l*g*h+(1-l*g)*d:h,c[u]=d;}return {plots:[{key:"vidya",title:"VIDYA",values:c,color:F(e,"color",_),width:2}]}}},kk={type:"ma-envelope",title:"Moving Average Envelope",shortTitle:"MA Env",overlay:true,inputs:[{key:"maType",title:"Type",type:"string",defval:"SMA",options:["SMA","EMA"]},D(20),be(),{key:"percent",title:"Percent",type:"float",defval:2.5,min:.01,max:50,step:.1},X()],compute:(r,e)=>{let t=I(e,"length",20),n=ee(r,F(e,"source","Close")),i=F(e,"maType","SMA")==="EMA"?Q(n,t):fe(n,t),o=I(e,"percent",2.5)/100,s=F(e,"color",_);return {plots:[{key:"basis",title:"Basis",values:i,color:s,width:2},{key:"upper",title:"Upper",values:ae(i,a=>a*(1+o)),color:s},{key:"lower",title:"Lower",values:ae(i,a=>a*(1-o)),color:s}],bands:[{key:"envelope",from:"upper",to:"lower",color:Pn(s)}]}}},Ik={type:"linear-regression",title:"Linear Regression Curve",shortTitle:"LinReg",overlay:true,inputs:[D(14),be(),X()],compute:(r,e)=>({plots:[{key:"linreg",title:"LinReg",values:Qc(ee(r,F(e,"source","Close")),I(e,"length",14)),color:F(e,"color",_),width:2}]})},px=[Ck,Tk,Ek,Pk,Lk,Mk,kk,Ik];function ap(r,e){let t=I(e,"length",20),n=I(e,"mult",2),i=ee(r,F(e,"source","Close")),o=fe(i,t),s=ae(rn(i,t),a=>a*n);return {basis:o,upper:K(o,s,(a,l)=>a+l),lower:K(o,s,(a,l)=>a-l)}}var lp=[D(20),be(),{key:"mult",title:"StdDev",type:"float",defval:2,min:.1,max:50,step:.1}],Ak={type:"bollinger-bands",title:"Bollinger Bands",shortTitle:"BB",overlay:true,inputs:[...lp,X()],compute:(r,e)=>{let{basis:t,upper:n,lower:i}=ap(r,e),o=F(e,"color",_);return {plots:[{key:"basis",title:"Basis",values:t,color:de},{key:"upper",title:"Upper",values:n,color:o},{key:"lower",title:"Lower",values:i,color:o}],bands:[{key:"bb",from:"upper",to:"lower",color:Pn(o)}]}}},Rk={type:"percent-b",title:"Bollinger Bands %B",shortTitle:"%B",overlay:false,inputs:[...lp,X()],compute:(r,e)=>{let{upper:t,lower:n}=ap(r,e);return {plots:[{key:"pb",title:"%B",values:ee(r,F(e,"source","Close")).map((s,a)=>{let l=t[a],c=n[a];return Number.isFinite(l)&&Number.isFinite(c)&&l!==c?(s-c)/(l-c):Number.NaN}),color:F(e,"color",_),width:2}],levels:[{key:"upper",price:1,color:J},{key:"middle",price:.5,color:J,lineStyle:"dotted"},{key:"lower",price:0,color:J}]}}},Dk={type:"bandwidth",title:"Bollinger Bands Width",shortTitle:"BandWidth",overlay:false,inputs:[...lp,X()],compute:(r,e)=>{let{basis:t,upper:n,lower:i}=ap(r,e);return {plots:[{key:"bbw",title:"BBW",values:t.map((s,a)=>{let l=n[a],c=i[a];return Number.isFinite(s)&&s!==0&&Number.isFinite(l)&&Number.isFinite(c)?(l-c)/s*100:Number.NaN}),color:F(e,"color",_),width:2}]}}},Ok={type:"keltner-channels",title:"Keltner Channels",shortTitle:"KC",overlay:true,inputs:[D(20),{key:"mult",title:"Multiplier",type:"float",defval:2,min:.1,max:50,step:.1},{key:"atrLength",title:"ATR length",type:"int",defval:10,min:1,max:500,step:1},be(),X()],compute:(r,e)=>{let t=I(e,"length",20),n=I(e,"mult",2),i=Q(ee(r,F(e,"source","Close")),t),o=ae(Vr(r,I(e,"atrLength",10)),a=>a*n),s=F(e,"color",_);return {plots:[{key:"basis",title:"Basis",values:i,color:de},{key:"upper",title:"Upper",values:K(i,o,(a,l)=>a+l),color:s},{key:"lower",title:"Lower",values:K(i,o,(a,l)=>a-l),color:s}],bands:[{key:"kc",from:"upper",to:"lower",color:Pn(s)}]}}},Nk={type:"donchian-channels",title:"Donchian Channels",shortTitle:"DC",overlay:true,inputs:[D(20),X()],compute:(r,e)=>{let t=I(e,"length",20),n=ct(Ge(r),t),i=St(Ue(r),t),o=F(e,"color",_);return {plots:[{key:"basis",title:"Basis",values:K(n,i,(s,a)=>(s+a)/2),color:de},{key:"upper",title:"Upper",values:n,color:o},{key:"lower",title:"Lower",values:i,color:o}],bands:[{key:"dc",from:"upper",to:"lower",color:Pn(o)}]}}},Fk={type:"chandelier-exit",title:"Chandelier Exit",shortTitle:"CE",overlay:true,inputs:[D(22),{key:"mult",title:"ATR multiplier",type:"float",defval:3,min:.1,max:50,step:.1}],compute:(r,e)=>{let t=I(e,"length",22),n=ae(Vr(r,t),s=>s*I(e,"mult",3)),i=K(ct(Ge(r),t),n,(s,a)=>s-a),o=K(St(Ue(r),t),n,(s,a)=>s+a);return {plots:[{key:"long",title:"Long stop",values:i,color:z},{key:"short",title:"Short stop",values:o,color:W}]}}},Vk={type:"chande-kroll-stop",title:"Chande Kroll Stop",shortTitle:"CKS",overlay:true,inputs:[{key:"p",title:"ATR length",type:"int",defval:10,min:1,max:500,step:1},{key:"x",title:"ATR multiplier",type:"float",defval:1,min:.1,max:50,step:.1},{key:"q",title:"Stop length",type:"int",defval:9,min:1,max:500,step:1}],compute:(r,e)=>{let t=I(e,"p",10),n=I(e,"x",1),i=I(e,"q",9),o=ae(Vr(r,t),l=>l*n),s=K(ct(Ge(r),t),o,(l,c)=>l-c),a=K(St(Ue(r),t),o,(l,c)=>l+c);return {plots:[{key:"stopShort",title:"Stop short",values:ct(s,i),color:W},{key:"stopLong",title:"Stop long",values:St(a,i),color:z}]}}},_k={type:"supertrend",title:"SuperTrend",shortTitle:"SuperTrend",overlay:true,inputs:[{key:"atrLength",title:"ATR length",type:"int",defval:10,min:1,max:500,step:1},{key:"mult",title:"Factor",type:"float",defval:3,min:.1,max:50,step:.1}],compute:(r,e)=>{let t=I(e,"atrLength",10),n=I(e,"mult",3),i=Vr(r,t),o=r.length,s=new Array(o).fill(Number.NaN),a=new Array(o).fill(1),l=Number.NaN,c=Number.NaN,d=1;for(let h=0;h<o;h++){let p=i[h];if(!Number.isFinite(p))continue;let m=r[h],f=(m.high+m.low)/2,g=f-n*p,b=f+n*p,y=h>0?r[h-1].close:m.close;l=Number.isFinite(l)&&y>l?Math.max(g,l):g,c=Number.isFinite(c)&&y<c?Math.min(b,c):b,d===1&&m.close<l?d=-1:d===-1&&m.close>c&&(d=1),a[h]=d,s[h]=d===1?l:c;}let u=a.map((h,p)=>Number.isFinite(s[p])?h===1?z:W:null);return {plots:[{key:"st",title:"SuperTrend",values:s,color:z,width:2,colors:u}]}}},Bk={type:"williams-alligator",title:"Williams Alligator",shortTitle:"Alligator",overlay:true,inputs:[{key:"jawLength",title:"Jaw length",type:"int",defval:13,min:1,max:500,step:1},{key:"teethLength",title:"Teeth length",type:"int",defval:8,min:1,max:500,step:1},{key:"lipsLength",title:"Lips length",type:"int",defval:5,min:1,max:500,step:1},{key:"jawOffset",title:"Jaw offset",type:"int",defval:8,min:0,max:100,step:1},{key:"teethOffset",title:"Teeth offset",type:"int",defval:5,min:0,max:100,step:1},{key:"lipsOffset",title:"Lips offset",type:"int",defval:3,min:0,max:100,step:1}],compute:(r,e)=>{let t=ee(r,"HL2"),n=ot(Le(t,I(e,"jawLength",13)),I(e,"jawOffset",8)),i=ot(Le(t,I(e,"teethLength",8)),I(e,"teethOffset",5)),o=ot(Le(t,I(e,"lipsLength",5)),I(e,"lipsOffset",3));return {plots:[{key:"jaw",title:"Jaw",values:n,color:_},{key:"teeth",title:"Teeth",values:i,color:W},{key:"lips",title:"Lips",values:o,color:z}]}}},Hk={type:"gator-oscillator",title:"Gator Oscillator",shortTitle:"Gator Oscillator",overlay:false,inputs:[],compute:r=>{let e=ee(r,"HL2"),t=ot(Le(e,13),8),n=ot(Le(e,8),5),i=ot(Le(e,5),3),o=ae(Te(t,n),Math.abs),s=ae(Te(n,i),l=>-Math.abs(l)),a=l=>l.map((c,d)=>{if(!Number.isFinite(c))return null;let u=d>0?l[d-1]:Number.NaN;return Number.isFinite(u)&&Math.abs(c)>Math.abs(u)?z:W});return {plots:[{key:"upper",title:"Upper",values:o,kind:"histogram",color:z,colors:a(o),base:0},{key:"lower",title:"Lower",values:s,kind:"histogram",color:W,colors:a(s),base:0}]}}},mx=[Ak,Rk,Dk,Ok,Nk,Fk,Vk,_k,Bk,Hk];function on(r,e,t){let n=[{key:"upper",price:e,color:J},{key:"lower",price:r,color:J}];return t!=null&&n.splice(1,0,{key:"middle",price:t,color:J,lineStyle:"dotted"}),n}var st=[{key:"zero",price:0,color:J}];function td(r){return r.map((e,t)=>{if(!Number.isFinite(e))return null;let n=t>0?r[t-1]:Number.NaN,i=Number.isFinite(n)?e>=n:true;return e>=0?i?z:`${z}80`:i?`${W}80`:W})}var zk={type:"rsi",title:"Relative Strength Index",shortTitle:"RSI",overlay:false,inputs:[D(14),be(),X()],compute:(r,e)=>({plots:[{key:"rsi",title:"RSI",values:ws(ee(r,F(e,"source","Close")),I(e,"length",14)),color:F(e,"color",_),width:2}],levels:on(30,70,50)})},$k={type:"stochastic",title:"Stochastic",shortTitle:"Stoch",overlay:false,inputs:[D(14,"kLength","%K length"),D(1,"kSmoothing","%K smoothing",500),D(3,"dLength","%D smoothing",500)],compute:(r,e)=>{let t=fe(Jc(De(r),Ge(r),Ue(r),I(e,"kLength",14)),I(e,"kSmoothing",1)),n=fe(t,I(e,"dLength",3));return {plots:[{key:"k",title:"%K",values:t,color:_,width:2},{key:"d",title:"%D",values:n,color:de}],levels:on(20,80)}}},Wk={type:"stochastic-rsi",title:"Stochastic RSI",shortTitle:"Stoch RSI",overlay:false,inputs:[D(14,"rsiLength","RSI length"),D(14,"stochLength","Stochastic length"),D(3,"kSmoothing","%K smoothing",500),D(3,"dLength","%D smoothing",500),be()],compute:(r,e)=>{let t=ws(ee(r,F(e,"source","Close")),I(e,"rsiLength",14)),n=fe(Jc(t,t,t,I(e,"stochLength",14)),I(e,"kSmoothing",3)),i=fe(n,I(e,"dLength",3));return {plots:[{key:"k",title:"%K",values:n,color:_,width:2},{key:"d",title:"%D",values:i,color:de}],levels:on(20,80)}}},Gk={type:"macd",title:"MACD",overlay:false,inputs:[D(12,"fastLength","Fast length"),D(26,"slowLength","Slow length"),D(9,"signalLength","Signal smoothing",500),be()],compute:(r,e)=>{let t=ee(r,F(e,"source","Close")),n=Te(Q(t,I(e,"fastLength",12)),Q(t,I(e,"slowLength",26))),i=Q(n,I(e,"signalLength",9)),o=Te(n,i);return {plots:[{key:"hist",title:"Histogram",values:o,kind:"histogram",color:z,colors:td(o),base:0},{key:"macd",title:"MACD",values:n,color:_,width:2},{key:"signal",title:"Signal",values:i,color:de}],levels:st}}},Uk={type:"ppo",title:"Percentage Price Oscillator",shortTitle:"PPO",overlay:false,inputs:[D(12,"fastLength","Fast length"),D(26,"slowLength","Slow length"),D(9,"signalLength","Signal smoothing",500),be()],compute:(r,e)=>{let t=ee(r,F(e,"source","Close")),n=Q(t,I(e,"fastLength",12)),i=Q(t,I(e,"slowLength",26)),o=K(n,i,(l,c)=>c===0?Number.NaN:(l-c)/c*100),s=Q(o,I(e,"signalLength",9)),a=Te(o,s);return {plots:[{key:"hist",title:"Histogram",values:a,kind:"histogram",color:z,colors:td(a),base:0},{key:"ppo",title:"PPO",values:o,color:_,width:2},{key:"signal",title:"Signal",values:s,color:de}],levels:st}}},Yk={type:"awesome-oscillator",title:"Awesome Oscillator",shortTitle:"AO",overlay:false,inputs:[],compute:r=>{let e=ee(r,"HL2"),t=Te(fe(e,5),fe(e,34)),n=t.map((i,o)=>{if(!Number.isFinite(i))return null;let s=o>0?t[o-1]:Number.NaN;return Number.isFinite(s)&&i<s?W:z});return {plots:[{key:"ao",title:"AO",values:t,kind:"histogram",color:z,colors:n,base:0}],levels:st}}},Kk={type:"commodity-channel-index",title:"Commodity Channel Index",shortTitle:"CCI",overlay:false,inputs:[D(20),be("HLC3"),X()],compute:(r,e)=>{let t=I(e,"length",20),n=ee(r,F(e,"source","HLC3")),i=fe(n,t),o=new Array(n.length).fill(Number.NaN);for(let a=t-1;a<n.length;a++){let l=i[a];if(!Number.isFinite(l))continue;let c=0;for(let d=a-t+1;d<=a;d++)c+=Math.abs(n[d]-l);o[a]=c/t;}return {plots:[{key:"cci",title:"CCI",values:n.map((a,l)=>{let c=i[l],d=o[l];return Number.isFinite(c)&&Number.isFinite(d)&&d!==0?(a-c)/(.015*d):Number.NaN}),color:F(e,"color",_),width:2}],levels:on(-100,100,0)}}},Xk={type:"williams-percent-r",title:"Williams %R",shortTitle:"%R",overlay:false,inputs:[D(14),X()],compute:(r,e)=>({plots:[{key:"wr",title:"%R",values:ae(Jc(De(r),Ge(r),Ue(r),I(e,"length",14)),n=>n-100),color:F(e,"color",_),width:2}],levels:on(-80,-20)})},jk={type:"chande-momentum-oscillator",title:"Chande Momentum Oscillator",shortTitle:"CMO",overlay:false,inputs:[D(9),be(),X()],compute:(r,e)=>{let t=I(e,"length",9),n=He(ee(r,F(e,"source","Close"))),i=we(ae(n,a=>Math.max(a,0)),t),o=we(ae(n,a=>Math.max(-a,0)),t);return {plots:[{key:"cmo",title:"CMO",values:K(i,o,(a,l)=>a+l===0?0:100*(a-l)/(a+l)),color:F(e,"color",_),width:2}],levels:on(-50,50,0)}}},qk={type:"connors-rsi",title:"Connors RSI",shortTitle:"CRSI",overlay:false,inputs:[D(3,"rsiLength","RSI length"),D(2,"streakLength","Streak RSI length"),D(100,"rankLength","Percent-rank length"),X()],compute:(r,e)=>{let t=De(r),n=new Array(t.length).fill(0);for(let l=1;l<t.length;l++){let c=t[l]-t[l-1];n[l]=c>0?Math.max(n[l-1],0)+1:c<0?Math.min(n[l-1],0)-1:0;}let i=ws(t,I(e,"rsiLength",3)),o=ws(n,I(e,"streakLength",2)),s=dx(Ft(t,1),I(e,"rankLength",100));return {plots:[{key:"crsi",title:"CRSI",values:t.map((l,c)=>{let d=i[c],u=o[c],h=s[c];return Number.isFinite(d)&&Number.isFinite(u)&&Number.isFinite(h)?(d+u+h)/3:Number.NaN}),color:F(e,"color",_),width:2}],levels:on(20,80,50)}}},Zk={type:"fisher-transform",title:"Fisher Transform",shortTitle:"Fisher",overlay:false,inputs:[D(9)],compute:(r,e)=>{let t=I(e,"length",9),n=ee(r,"HL2"),i=ct(n,t),o=St(n,t),s=r.length,a=new Array(s).fill(Number.NaN),l=0,c=0;for(let d=0;d<s;d++){let u=i[d],h=o[d];if(!Number.isFinite(u)||!Number.isFinite(h))continue;let p=u===h?0:(n[d]-h)/(u-h)-.5;l=Math.max(-0.999,Math.min(.999,.66*p+.67*l)),c=.5*Math.log((1+l)/(1-l))+.5*c,a[d]=c;}return {plots:[{key:"fisher",title:"Fisher",values:a,color:_,width:2},{key:"trigger",title:"Trigger",values:ot(a,1),color:de}],levels:st}}},Jk={type:"trix",title:"TRIX",overlay:false,inputs:[D(18),X()],compute:(r,e)=>{let t=I(e,"length",18),n=ae(De(r),Math.log),i=Q(Q(Q(n,t),t),t);return {plots:[{key:"trix",title:"TRIX",values:ae(He(i),s=>s*1e4),color:F(e,"color",_),width:2}],levels:st}}};function fx(r,e,t){let n=He(r),i=Q(Q(n,e),t),o=Q(Q(ae(n,Math.abs),e),t);return K(i,o,(s,a)=>a===0?0:100*s/a)}var Qk={type:"true-strength-index",title:"True Strength Index",shortTitle:"TSI",overlay:false,inputs:[D(25,"longLength","Long length"),D(13,"shortLength","Short length"),D(13,"signalLength","Signal length")],compute:(r,e)=>{let t=fx(De(r),I(e,"longLength",25),I(e,"shortLength",13));return {plots:[{key:"tsi",title:"TSI",values:t,color:_,width:2},{key:"signal",title:"Signal",values:Q(t,I(e,"signalLength",13)),color:de}],levels:st}}},eI={type:"smi-ergodic",title:"SMI Ergodic Oscillator",shortTitle:"SMIE",overlay:false,inputs:[D(5,"shortLength","Short length"),D(20,"longLength","Long length"),D(5,"signalLength","Signal length")],compute:(r,e)=>{let t=fx(De(r),I(e,"longLength",20),I(e,"shortLength",5)),n=Q(t,I(e,"signalLength",5)),i=Te(t,n);return {plots:[{key:"osc",title:"Oscillator",values:i,kind:"histogram",color:z,colors:td(i),base:0},{key:"smi",title:"SMI",values:t,color:_,width:2},{key:"signal",title:"Signal",values:n,color:de}],levels:st}}},tI={type:"schaff-trend-cycle",title:"Schaff Trend Cycle",shortTitle:"Schaff Trend Cycle",overlay:false,inputs:[D(10,"cycleLength","Cycle length"),D(23,"fastLength","Fast length"),D(50,"slowLength","Slow length")],compute:(r,e)=>{let t=I(e,"cycleLength",10),n=De(r),i=Te(Q(n,I(e,"fastLength",23)),Q(n,I(e,"slowLength",50))),o=a=>{let l=St(a,t),c=ct(a,t),d=new Array(a.length).fill(Number.NaN),u=Number.NaN,h=Number.NaN;for(let p=0;p<a.length;p++){let m=a[p],f=l[p],g=c[p];if(!Number.isFinite(m)||!Number.isFinite(f)||!Number.isFinite(g))continue;let b=g>f?(m-f)/(g-f)*100:Number.isFinite(u)?u:50;u=b,h=Number.isFinite(h)?h+.5*(b-h):b,d[p]=h;}return d};return {plots:[{key:"stc",title:"STC",values:o(o(i)),color:_,width:2}],levels:on(25,75)}}},nI={type:"know-sure-thing",title:"Know Sure Thing",shortTitle:"KST",overlay:false,inputs:[be(),D(9,"signalLength","Signal length")],compute:(r,e)=>{let t=ee(r,F(e,"source","Close")),n=[fe(Ft(t,10),10),fe(Ft(t,15),10),fe(Ft(t,20),10),fe(Ft(t,30),15)].reduce((i,o,s)=>K(i,o,(a,l)=>a+l*(s+1)),new Array(t.length).fill(0));return {plots:[{key:"kst",title:"KST",values:n,color:_,width:2},{key:"signal",title:"Signal",values:fe(n,I(e,"signalLength",9)),color:de}],levels:st}}},rI={type:"coppock-curve",title:"Coppock Curve",shortTitle:"Coppock",overlay:false,inputs:[D(10,"wmaLength","WMA length"),D(14,"longRoc","Long RoC length"),D(11,"shortRoc","Short RoC length"),be(),X()],compute:(r,e)=>{let t=ee(r,F(e,"source","Close"));return {plots:[{key:"coppock",title:"Coppock",values:Zc(K(Ft(t,I(e,"longRoc",14)),Ft(t,I(e,"shortRoc",11)),(i,o)=>i+o),I(e,"wmaLength",10)),color:F(e,"color",_),width:2}],levels:st}}},iI={type:"detrended-price-oscillator",title:"Detrended Price Oscillator",shortTitle:"DPO",overlay:false,inputs:[D(21),X()],compute:(r,e)=>{let t=I(e,"length",21),n=Math.floor(t/2)+1;return {plots:[{key:"dpo",title:"DPO",values:Te(De(r),ot(fe(De(r),t),n)),color:F(e,"color",_),width:2}],levels:st}}},oI={type:"rate-of-change",title:"Rate of Change",shortTitle:"ROC",overlay:false,inputs:[D(9),be(),X()],compute:(r,e)=>({plots:[{key:"roc",title:"RoC",values:Ft(ee(r,F(e,"source","Close")),I(e,"length",9)),color:F(e,"color",_),width:2}],levels:st})},sI={type:"ultimate-oscillator",title:"Ultimate Oscillator",shortTitle:"UO",overlay:false,inputs:[D(7,"fastLength","Fast length"),D(14,"middleLength","Middle length"),D(28,"slowLength","Slow length"),X()],compute:(r,e)=>{let t=r.length,n=new Array(t).fill(Number.NaN),i=new Array(t).fill(Number.NaN);for(let d=0;d<t;d++){let u=r[d],h=d>0?r[d-1].close:u.close,p=Math.min(u.low,h),m=Math.max(u.high,h);n[d]=u.close-p,i[d]=m-p;}let o=d=>K(we(n,d),we(i,d),(u,h)=>h===0?Number.NaN:u/h),s=o(I(e,"fastLength",7)),a=o(I(e,"middleLength",14)),l=o(I(e,"slowLength",28));return {plots:[{key:"uo",title:"UO",values:s.map((d,u)=>{let h=a[u],p=l[u];return Number.isFinite(d)&&Number.isFinite(h)&&Number.isFinite(p)?100*(4*d+2*h+p)/7:Number.NaN}),color:F(e,"color",_),width:2}],levels:on(30,70,50)}}},aI={type:"relative-vigor-index",title:"Relative Vigor Index",shortTitle:"RVGI",overlay:false,inputs:[D(10)],compute:(r,e)=>{let t=I(e,"length",10),n=ed(Te(De(r),ox(r))),i=ed(Te(Ge(r),Ue(r))),o=K(we(n,t),we(i,t),(s,a)=>a===0?0:s/a);return {plots:[{key:"rvgi",title:"RVGI",values:o,color:_,width:2},{key:"signal",title:"Signal",values:ed(o),color:de}],levels:st}}},lI={type:"relative-volatility-index",title:"Relative Volatility Index",shortTitle:"RVI",overlay:false,inputs:[D(10,"stdevLength","StdDev length"),D(14,"smoothLength","Smoothing length"),be(),X()],compute:(r,e)=>{let t=I(e,"smoothLength",14),n=ee(r,F(e,"source","Close")),i=rn(n,I(e,"stdevLength",10)),o=He(n),s=Le(K(i,o,(c,d)=>d>0?c:0),t),a=Le(K(i,o,(c,d)=>d<=0?c:0),t);return {plots:[{key:"rvi",title:"RVI",values:K(s,a,(c,d)=>c+d===0?50:100*c/(c+d)),color:F(e,"color",_),width:2}],levels:on(20,80,50)}}},cI={type:"balance-of-power",title:"Balance of Power",shortTitle:"BOP",overlay:false,inputs:[X()],compute:(r,e)=>({plots:[{key:"bop",title:"BOP",values:r.map(n=>n.high===n.low?0:(n.close-n.open)/(n.high-n.low)),color:F(e,"color",_),width:2}],levels:st})},dI={type:"elder-ray",title:"Elder Ray",overlay:false,inputs:[D(13)],compute:(r,e)=>{let t=Q(De(r),I(e,"length",13));return {plots:[{key:"bull",title:"Bull power",values:Te(Ge(r),t),kind:"histogram",color:z,base:0},{key:"bear",title:"Bear power",values:Te(Ue(r),t),kind:"histogram",color:W,base:0}],levels:st}}},uI={type:"ttm-squeeze",title:"TTM Squeeze",overlay:false,inputs:[D(20),{key:"bbMult",title:"Bollinger multiplier",type:"float",defval:2,min:.1,max:50,step:.1},{key:"kcMult",title:"Keltner multiplier",type:"float",defval:1.5,min:.1,max:50,step:.1}],compute:(r,e)=>{let t=I(e,"length",20),n=De(r),i=fe(n,t),o=ae(rn(n,t),h=>h*I(e,"bbMult",2)),s=ae(Le(jn(r),t),h=>h*I(e,"kcMult",1.5)),a=K(ct(Ge(r),t),St(Ue(r),t),(h,p)=>(h+p)/2),l=K(a,i,(h,p)=>(h+p)/2),c=Qc(Te(n,l),t),u=n.map((h,p)=>{let m=o[p],f=s[p];return Number.isFinite(m)&&Number.isFinite(f)?m<f:false}).map((h,p)=>Number.isFinite(c[p])?h?W:z:null);return {plots:[{key:"mom",title:"Momentum",values:c,kind:"histogram",color:z,colors:td(c),base:0},{key:"squeeze",title:"Squeeze",values:c.map(h=>Number.isFinite(h)?0:Number.NaN),kind:"cross",color:Je,colors:u}]}}},gx=[zk,$k,Wk,Gk,Uk,Yk,Kk,Xk,jk,qk,Zk,Jk,Qk,eI,tI,nI,rI,iI,oI,sI,aI,lI,cI,dI,uI];var hI={type:"aroon",title:"Aroon",overlay:false,inputs:[D(14)],compute:(r,e)=>{let t=I(e,"length",14),n=ae(ax(Ge(r),t+1),o=>100*(t-o)/t),i=ae(lx(Ue(r),t+1),o=>100*(t-o)/t);return {plots:[{key:"up",title:"Aroon up",values:n,color:z,width:2},{key:"down",title:"Aroon down",values:i,color:W,width:2}]}}},pI={type:"average-directional-index",title:"Average Directional Index",shortTitle:"ADX",overlay:false,inputs:[D(14,"diLength","DI length"),D(14,"adxLength","ADX smoothing")],compute:(r,e)=>{let t=I(e,"diLength",14),n=I(e,"adxLength",14),i=r.length,o=new Array(i).fill(Number.NaN),s=new Array(i).fill(Number.NaN);for(let u=1;u<i;u++){let h=r[u].high-r[u-1].high,p=r[u-1].low-r[u].low;o[u]=h>p&&h>0?h:0,s[u]=p>h&&p>0?p:0;}let a=Le(jn(r),t),l=K(Le(o,t),a,(u,h)=>h===0?0:100*u/h),c=K(Le(s,t),a,(u,h)=>h===0?0:100*u/h),d=K(l,c,(u,h)=>u+h===0?0:100*Math.abs(u-h)/(u+h));return {plots:[{key:"adx",title:"ADX",values:Le(d,n),color:_,width:2},{key:"plusDi",title:"+DI",values:l,color:z},{key:"minusDi",title:"-DI",values:c,color:W}],levels:[{key:"threshold",price:25,color:J,lineStyle:"dotted"}]}}},mI={type:"vortex-indicator",title:"Vortex Indicator",shortTitle:"VI",overlay:false,inputs:[D(14)],compute:(r,e)=>{let t=I(e,"length",14),n=r.length,i=new Array(n).fill(Number.NaN),o=new Array(n).fill(Number.NaN);for(let a=1;a<n;a++)i[a]=Math.abs(r[a].high-r[a-1].low),o[a]=Math.abs(r[a].low-r[a-1].high);let s=we(jn(r),t);return {plots:[{key:"viPlus",title:"VI+",values:K(we(i,t),s,(a,l)=>l===0?Number.NaN:a/l),color:z,width:2},{key:"viMinus",title:"VI-",values:K(we(o,t),s,(a,l)=>l===0?Number.NaN:a/l),color:W,width:2}],levels:[{key:"one",price:1,color:J,lineStyle:"dotted"}]}}},bx=[hI,pI,mI];var fI={type:"average-true-range",title:"Average True Range",shortTitle:"ATR",overlay:false,inputs:[D(14),X()],compute:(r,e)=>({plots:[{key:"atr",title:"ATR",values:Vr(r,I(e,"length",14)),color:F(e,"color",_),width:2}]})},gI={type:"historical-volatility",title:"Historical Volatility",shortTitle:"HV",overlay:false,inputs:[D(10),{key:"annual",title:"Periods per year",type:"int",defval:365,min:1,max:1e5,step:1,tooltip:"Annualization factor (365 for daily crypto bars, 252 for stock sessions)"},X()],compute:(r,e)=>{let t=ae(He(ae(De(r),Math.log)),i=>i);return {plots:[{key:"hv",title:"HV",values:ae(rn(t,I(e,"length",10)),i=>i*Math.sqrt(I(e,"annual",365))*100),color:F(e,"color",_),width:2}]}}},bI={type:"chaikin-volatility",title:"Chaikin Volatility",shortTitle:"CHV",overlay:false,inputs:[D(10,"emaLength","EMA length"),D(10,"rocLength","RoC length"),X()],compute:(r,e)=>{let t=Q(Te(Ge(r),Ue(r)),I(e,"emaLength",10));return {plots:[{key:"cv",title:"Chaikin Vol",values:Ft(t,I(e,"rocLength",10)),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},vI={type:"mass-index",title:"Mass Index",shortTitle:"MI",overlay:false,inputs:[D(25),X()],compute:(r,e)=>{let t=Te(Ge(r),Ue(r)),n=Q(t,9),i=K(n,Q(n,9),(o,s)=>s===0?Number.NaN:o/s);return {plots:[{key:"mi",title:"Mass Index",values:we(i,I(e,"length",25)),color:F(e,"color",_),width:2}],levels:[{key:"reversal",price:27,color:J,lineStyle:"dotted"}]}}},yI={type:"standard-deviation",title:"Standard Deviation",shortTitle:"StdDev",overlay:false,inputs:[D(20),be(),X()],compute:(r,e)=>({plots:[{key:"stdev",title:"StdDev",values:rn(ee(r,F(e,"source","Close")),I(e,"length",20)),color:F(e,"color",_),width:2}]})},wI={type:"ulcer-index",title:"Ulcer Index",overlay:false,inputs:[D(14),X()],compute:(r,e)=>{let t=I(e,"length",14),n=De(r),i=K(n,ct(n,t),(s,a)=>a===0?0:100*(s-a)/a);return {plots:[{key:"ui",title:"Ulcer",values:ae(fe(ae(i,s=>s*s),t),Math.sqrt),color:F(e,"color",_),width:2}]}}},xI={type:"choppiness-index",title:"Choppiness Index",shortTitle:"CHOP",overlay:false,inputs:[D(14),X()],compute:(r,e)=>{let t=I(e,"length",14),n=we(jn(r),t),i=K(ct(Ge(r),t),St(Ue(r),t),(s,a)=>s-a);return {plots:[{key:"chop",title:"CHOP",values:K(n,i,(s,a)=>a>0&&s>0?100*Math.log10(s/a)/Math.log10(t):Number.NaN),color:F(e,"color",_),width:2}],levels:[{key:"upper",price:61.8,color:J},{key:"lower",price:38.2,color:J}]}}},vx=[fI,gI,bI,vI,yI,wI,xI];function nd(r){return r.map(e=>e.volume==null||!Number.isFinite(e.volume)?Number.NaN:e.high===e.low?0:(2*e.close-e.high-e.low)/(e.high-e.low)*e.volume)}var SI={type:"on-balance-volume",title:"On Balance Volume",shortTitle:"OBV",overlay:false,inputs:[X()],compute:(r,e)=>{let t=xt(r),n=He(De(r)),i=K(t,n,(o,s)=>s>0?o:s<0?-o:0);return {plots:[{key:"obv",title:"OBV",values:xs(i),color:F(e,"color",_),width:2}]}}},CI={type:"accumulation-distribution",title:"Accumulation / Distribution",shortTitle:"A/D",overlay:false,inputs:[X()],compute:(r,e)=>({plots:[{key:"ad",title:"A/D",values:xs(nd(r)),color:F(e,"color",_),width:2}]})},TI={type:"chaikin-money-flow",title:"Chaikin Money Flow",shortTitle:"CMF",overlay:false,inputs:[D(20),X()],compute:(r,e)=>{let t=I(e,"length",20);return {plots:[{key:"cmf",title:"CMF",values:K(we(nd(r),t),we(xt(r),t),(i,o)=>o===0?0:i/o),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},EI={type:"chaikin-oscillator",title:"Chaikin Oscillator",shortTitle:"Chaikin Osc",overlay:false,inputs:[D(3,"fastLength","Fast length"),D(10,"slowLength","Slow length"),X()],compute:(r,e)=>{let t=xs(nd(r));return {plots:[{key:"co",title:"Chaikin Osc",values:Te(Q(t,I(e,"fastLength",3)),Q(t,I(e,"slowLength",10))),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},PI={type:"ease-of-movement",title:"Ease of Movement",shortTitle:"EOM",overlay:false,inputs:[D(14),{key:"divisor",title:"Divisor",type:"int",defval:1e4,min:1,max:1e9,step:1},X()],compute:(r,e)=>{let t=I(e,"divisor",1e4),n=ee(r,"HL2"),i=He(n),o=r.map((s,a)=>{let l=i[a];return s.volume==null||!Number.isFinite(s.volume)||s.volume===0||!Number.isFinite(l)?Number.NaN:t*l*(s.high-s.low)/s.volume});return {plots:[{key:"eom",title:"EOM",values:fe(o,I(e,"length",14)),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},LI={type:"force-index",title:"Force Index",shortTitle:"FI",overlay:false,inputs:[D(13),X()],compute:(r,e)=>{let t=K(He(De(r)),xt(r),(n,i)=>n*i);return {plots:[{key:"force",title:"Force",values:Q(t,I(e,"length",13)),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},MI={type:"klinger-oscillator",title:"Klinger Oscillator",shortTitle:"KVO",overlay:false,inputs:[D(34,"fastLength","Fast length"),D(55,"slowLength","Slow length"),D(13,"signalLength","Signal length")],compute:(r,e)=>{let t=ee(r,"HLC3"),n=He(t),i=K(xt(r),n,(s,a)=>a>=0?s:-s),o=Te(Q(i,I(e,"fastLength",34)),Q(i,I(e,"slowLength",55)));return {plots:[{key:"kvo",title:"KVO",values:o,color:_,width:2},{key:"signal",title:"Signal",values:Q(o,I(e,"signalLength",13)),color:de}],levels:[{key:"zero",price:0,color:J}]}}},kI={type:"money-flow-index",title:"Money Flow Index",shortTitle:"MFI",overlay:false,inputs:[D(14),X()],compute:(r,e)=>{let t=I(e,"length",14),n=ee(r,"HLC3"),i=K(n,xt(r),(c,d)=>c*d),o=He(n),s=we(K(i,o,(c,d)=>d>0?c:0),t),a=we(K(i,o,(c,d)=>d<0?c:0),t);return {plots:[{key:"mfi",title:"MFI",values:K(s,a,(c,d)=>d===0?100:100-100/(1+c/d)),color:F(e,"color",_),width:2}],levels:[{key:"upper",price:80,color:J},{key:"lower",price:20,color:J}]}}};function yx(r,e){let t=new Array(r.length).fill(Number.NaN),n=1e3,i=false;for(let o=1;o<r.length;o++){let s=r[o].volume,a=r[o-1].volume,l=r[o-1].close;if(s==null||a==null||!Number.isFinite(s)||!Number.isFinite(a)||l===0){i&&(t[o]=n);continue}i=true,e(s,a)&&(n+=(r[o].close-l)/l*n),t[o]=n;}return t}var II={type:"negative-volume-index",title:"Negative Volume Index",shortTitle:"Negative Volume Index",overlay:false,inputs:[D(255,"signalLength","Signal length"),X()],compute:(r,e)=>{let t=yx(r,(n,i)=>n<i);return {plots:[{key:"nvi",title:"NVI",values:t,color:F(e,"color",_),width:2},{key:"signal",title:"Signal",values:Q(t,I(e,"signalLength",255)),color:de}]}}},AI={type:"positive-volume-index",title:"Positive Volume Index",shortTitle:"Positive Volume Index",overlay:false,inputs:[D(255,"signalLength","Signal length"),X()],compute:(r,e)=>{let t=yx(r,(n,i)=>n>i);return {plots:[{key:"pvi",title:"PVI",values:t,color:F(e,"color",_),width:2},{key:"signal",title:"Signal",values:Q(t,I(e,"signalLength",255)),color:de}]}}},RI={type:"price-volume-trend",title:"Price Volume Trend",shortTitle:"PVT",overlay:false,inputs:[X()],compute:(r,e)=>{let t=De(r),n=r.map((i,o)=>{if(o===0||i.volume==null||!Number.isFinite(i.volume))return Number.NaN;let s=t[o-1];return s===0?0:(t[o]-s)/s*i.volume});return {plots:[{key:"pvt",title:"PVT",values:xs(n),color:F(e,"color",_),width:2}]}}},DI={type:"volume-oscillator",title:"Volume Oscillator",shortTitle:"Vol Osc",overlay:false,inputs:[D(5,"fastLength","Fast length"),D(10,"slowLength","Slow length"),X()],compute:(r,e)=>{let t=xt(r),n=Q(t,I(e,"fastLength",5)),i=Q(t,I(e,"slowLength",10));return {plots:[{key:"vo",title:"Volume Osc",values:K(n,i,(s,a)=>a===0?Number.NaN:100*(s-a)/a),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},OI={type:"pvo",title:"Percentage Volume Oscillator",shortTitle:"PVO",overlay:false,inputs:[D(12,"fastLength","Fast length"),D(26,"slowLength","Slow length"),D(9,"signalLength","Signal length")],compute:(r,e)=>{let t=xt(r),n=Q(t,I(e,"fastLength",12)),i=Q(t,I(e,"slowLength",26)),o=K(n,i,(l,c)=>c===0?Number.NaN:100*(l-c)/c),s=Q(o,I(e,"signalLength",9)),a=Te(o,s);return {plots:[{key:"hist",title:"Histogram",values:a,kind:"histogram",color:z,colors:a.map(l=>Number.isFinite(l)?l>=0?z:W:null),base:0},{key:"pvo",title:"PVO",values:o,color:_,width:2},{key:"signal",title:"Signal",values:s,color:de}],levels:[{key:"zero",price:0,color:J}]}}},NI={type:"volume-flow-indicator",title:"Volume Flow Indicator",shortTitle:"Volume Flow Indicator",overlay:false,inputs:[D(130),{key:"coef",title:"Cutoff coefficient",type:"float",defval:.2,min:.01,max:10,step:.01},{key:"volCoef",title:"Volume cap",type:"float",defval:2.5,min:.1,max:50,step:.1},D(3,"smoothLength","Smoothing length")],compute:(r,e)=>{let t=I(e,"length",130),n=I(e,"coef",.2),i=I(e,"volCoef",2.5),o=ae(ee(r,"HLC3"),Math.log),s=He(o),a=rn(s,30),l=xt(r),c=fe(l,t),d=He(ee(r,"HLC3")),u=r.map((f,g)=>{let b=Number.isFinite(a[g])?n*a[g]*f.close:Number.NaN,y=l[g],v=g>0?c[g-1]:Number.NaN,S=d[g];if(!Number.isFinite(b)||!Number.isFinite(y)||!Number.isFinite(v)||!Number.isFinite(S))return Number.NaN;let P=Math.min(y,v*i);return S>b?P:S<-b?-P:0}),h=r.map((f,g)=>{let b=g>0?c[g-1]:Number.NaN;return Number.isFinite(b)&&b!==0?b:Number.NaN}),p=we(u,t),m=K(p,h,(f,g)=>f/g);return {plots:[{key:"vfi",title:"VFI",values:fe(m,I(e,"smoothLength",3)),color:_,width:2}],levels:[{key:"zero",price:0,color:J}]}}},FI={type:"intraday-intensity",title:"Intraday Intensity",shortTitle:"Intraday Intensity",overlay:false,inputs:[D(21),X()],compute:(r,e)=>{let t=I(e,"length",21);return {plots:[{key:"ii",title:"II%",values:K(we(nd(r),t),we(xt(r),t),(i,o)=>o===0?0:100*i/o),color:F(e,"color",_),width:2}],levels:[{key:"zero",price:0,color:J}]}}},wx=[SI,CI,TI,EI,PI,LI,MI,kI,II,AI,RI,DI,OI,NI,FI];var dp=864e5;function up(r,e){if(r==="Week")return Math.floor((Math.floor(e/dp)+3)/7);if(r==="Month"||r==="Quarter"||r==="Year"){let t=new Date(e);return r==="Year"?t.getUTCFullYear():r==="Quarter"?t.getUTCFullYear()*4+Math.floor(t.getUTCMonth()/3):t.getUTCFullYear()*12+t.getUTCMonth()}return Math.floor(e/dp)}var VI={type:"parabolic-sar",title:"Parabolic SAR",shortTitle:"SAR",overlay:true,inputs:[{key:"start",title:"Start",type:"float",defval:.02,min:.001,max:1,step:.001},{key:"increment",title:"Increment",type:"float",defval:.02,min:.001,max:1,step:.001},{key:"maximum",title:"Max value",type:"float",defval:.2,min:.01,max:1,step:.01}],compute:(r,e)=>{let t=I(e,"start",.02),n=I(e,"increment",.02),i=I(e,"maximum",.2),o=r.length,s=new Array(o).fill(Number.NaN),a=new Array(o).fill(null);if(o>=2){let l=r[1].close>=r[0].close,c=l?r[0].low:r[0].high,d=l?r[0].high:r[0].low,u=t;for(let h=1;h<o;h++){let p=r[h];c+=u*(d-c),l?c=Math.min(c,r[h-1].low,h>=2?r[h-2].low:r[h-1].low):c=Math.max(c,r[h-1].high,h>=2?r[h-2].high:r[h-1].high),(l?p.low<c:p.high>c)?(l=!l,c=d,d=l?p.high:p.low,u=t):l&&p.high>d?(d=p.high,u=Math.min(i,u+n)):!l&&p.low<d&&(d=p.low,u=Math.min(i,u+n)),s[h]=c,a[h]=l?z:W;}}return {plots:[{key:"sar",title:"PSAR",values:s,kind:"circles",color:_,colors:a}]}}},xx="Bands",rd="Style",cp=[{on:"band1",mult:"band1Mult",color:"band1Color",fill:"band1Fill",fillColor:"band1FillColor",defMult:1,defOn:true,defColor:z},{on:"band2",mult:"band2Mult",color:"band2Color",fill:"band2Fill",fillColor:"band2FillColor",defMult:2,defOn:false,defColor:de},{on:"band3",mult:"band3Mult",color:"band3Color",fill:"band3Fill",fillColor:"band3FillColor",defMult:3,defOn:false,defColor:Rs[4]}],_I={type:"vwap",title:"Volume Weighted Average Price",shortTitle:"VWAP",overlay:true,inputs:[{key:"anchor",title:"Period",type:"string",defval:"Day",options:["Day","Week","Month","Quarter","Year"],tooltip:"Where the accumulation resets (UTC periods)"},be("HLC3"),...cp.flatMap((r,e)=>[{key:r.on,title:`Band ${e+1} multiplier`,type:"bool",defval:r.defOn,inline:r.on,group:xx},{key:r.mult,title:"",type:"float",defval:r.defMult,min:.1,max:10,step:.1,inline:r.on,group:xx}]),{...X(Je,"VWAP color"),group:rd},...cp.flatMap((r,e)=>[{...X(r.defColor,`Band ${e+1} color`,r.color),inline:r.color,group:rd},{key:r.fill,title:"Fill",type:"bool",defval:true,inline:r.color,group:rd},{...X(Pn(r.defColor),"",r.fillColor),inline:r.color,group:rd}])],compute:(r,e)=>{let t=F(e,"anchor","Day"),n=ee(r,F(e,"source","HLC3")),i=r.length,o=new Array(i).fill(Number.NaN),s=cp.filter(p=>sp(e,p.on,p.defOn)).map(p=>({mult:Math.max(0,I(e,p.mult,p.defMult)),color:F(e,p.color,p.defColor),fill:sp(e,p.fill,true),fillColor:F(e,p.fillColor,Pn(p.defColor)),up:new Array(i).fill(Number.NaN),down:new Array(i).fill(Number.NaN)})),a=Number.NaN,l=0,c=0,d=0;for(let p=0;p<i;p++){let m=r[p],f=up(t,m.time);f!==a&&(a=f,l=0,c=0,d=0);let g=m.volume;if(g!=null&&Number.isFinite(g)&&g>0){let v=n[p];l+=v*g,c+=v*v*g,d+=g;}if(d<=0)continue;let b=l/d,y=Math.sqrt(Math.max(0,c/d-b*b));o[p]=b;for(let v of s)v.up[p]=b+v.mult*y,v.down[p]=b-v.mult*y;}let u=[{key:"vwap",title:"VWAP",values:o,color:F(e,"color",Je),width:2}],h=[];return s.forEach((p,m)=>{u.push({key:`up${m}`,title:`Upper ${p.mult}\u03C3`,values:p.up,color:p.color},{key:`down${m}`,title:`Lower ${p.mult}\u03C3`,values:p.down,color:p.color}),p.fill&&h.push({key:`band${m}`,from:`up${m}`,to:`down${m}`,color:p.fillColor});}),{plots:u,bands:h}}},BI={type:"pivot-points",title:"Pivot Points",shortTitle:"Pivots",overlay:true,inputs:[{key:"anchor",title:"Period",type:"string",defval:"Day",options:["Day","Week","Month"]}],compute:(r,e)=>{let t=F(e,"anchor","Day"),n=new Map;for(let l of r){let c=up(t,l.time),d=n.get(c);d?(d.high=Math.max(d.high,l.high),d.low=Math.min(d.low,l.low),d.close=l.close):n.set(c,{high:l.high,low:l.low,close:l.close});}let i=r.length,o=()=>new Array(i).fill(Number.NaN),s={p:o(),r1:o(),s1:o(),r2:o(),s2:o(),r3:o(),s3:o()};for(let l=0;l<i;l++){let c=n.get(up(t,r[l].time)-1);if(!c)continue;let d=(c.high+c.low+c.close)/3;s.p[l]=d,s.r1[l]=2*d-c.low,s.s1[l]=2*d-c.high,s.r2[l]=d+(c.high-c.low),s.s2[l]=d-(c.high-c.low),s.r3[l]=c.high+2*(d-c.low),s.s3[l]=c.low-2*(c.high-d);}let a=(l,c,d)=>({key:l,title:c,kind:"step",values:s[l],color:d});return {plots:[a("p","P",de),a("r1","R1",W),a("s1","S1",z),a("r2","R2",W),a("s2","S2",z),a("r3","R3",W),a("s3","S3",z)]}}},HI={type:"52-week-high-low",title:"52 Week High/Low",shortTitle:"52W H/L",overlay:true,inputs:[{key:"weeks",title:"Weeks",type:"int",defval:52,min:1,max:520,step:1}],compute:(r,e)=>{let t=I(e,"weeks",52)*7*dp,n=r.length,i=new Array(n).fill(Number.NaN),o=new Array(n).fill(Number.NaN),s=[],a=[],l=0;for(let c=0;c<n;c++){let d=r[c];for(;s.length>0&&r[s[s.length-1]].high<=d.high;)s.pop();for(s.push(c);a.length>0&&r[a[a.length-1]].low>=d.low;)a.pop();for(a.push(c);r[l].time<d.time-t;)l+=1;for(;s[0]<l;)s.shift();for(;a[0]<l;)a.shift();i[c]=r[s[0]].high,o[c]=r[a[0]].low;}return {plots:[{key:"high",title:"52W high",values:i,kind:"step",color:z},{key:"low",title:"52W low",values:o,kind:"step",color:W}]}}},zI={type:"zigzag",title:"ZigZag",overlay:true,inputs:[{key:"deviation",title:"Deviation %",type:"float",defval:5,min:.01,max:100,step:.1},{key:"depth",title:"Depth",type:"int",defval:10,min:1,max:500,step:1},X()],compute:(r,e)=>{let t=I(e,"deviation",5)/100,n=I(e,"depth",10),i=[];if(r.length>1){let o=r[1].close>=r[0].close,s=o?{i:0,price:r[0].high}:{i:0,price:r[0].low};for(let a=1;a<r.length;a++){let l=r[a];o?l.high>=s.price?s={i:a,price:l.high}:l.low<=s.price*(1-t)&&a-(i[i.length-1]?.i??-n)>=n&&(i.push(s),o=false,s={i:a,price:l.low}):l.low<=s.price?s={i:a,price:l.low}:l.high>=s.price*(1+t)&&a-(i[i.length-1]?.i??-n)>=n&&(i.push(s),o=true,s={i:a,price:l.high});}i.push(s);}return {plots:[],polylines:[{key:"zigzag",points:i.map(o=>({xloc:"bar_time",x:r[o.i].time,price:o.price})),curved:false,closed:false,lineColor:F(e,"color",_),lineWidth:2,lineStyle:"solid",arrowLeft:false,arrowRight:false}]}}},$I={type:"williams-fractal",title:"Williams Fractal",shortTitle:"Fractals",overlay:true,inputs:[{key:"periods",title:"Periods",type:"int",defval:2,min:1,max:50,step:1}],compute:(r,e)=>{let t=I(e,"periods",2),n=[],i=(o,s,a)=>{let l=s(r[o]);for(let c=o-t;c<=o+t;c++)if(c!==o&&!a(l,s(r[c])))return false;return true};for(let o=t;o<r.length-t;o++)i(o,s=>s.high,(s,a)=>s>=a)&&n.push({time:r[o].time,position:"aboveBar",shape:"triangleup",color:z}),i(o,s=>s.low,(s,a)=>s<=a)&&n.push({time:r[o].time,position:"belowBar",shape:"triangledown",color:W});return {plots:[],markers:n}}},Sx=[VI,_I,BI,HI,zI,$I];var WI=[...px,...mx,...gx,...bx,...vx,...wx,...Sx];function Cx(){for(let r of WI)Ln(rx(r));}var hp=class{constructor(e,t={},n={}){Jw(),qh(),ip(),Cx();let i=GI(e),o=jr(t.theme),s={currentPriceLine:t.currentPriceLine??true,logScale:t.logScale??false,nativeBackend:t.nativeBackend??"auto",...Tp(t.animations),glow:t.glow??0,upColor:t.upColor??z,downColor:t.downColor??W,priceStyle:t.priceStyle??"candles"},a=t.renderer??ys;if(typeof a!="function")throw new Error("[vela] options.renderer must be a renderer class, e.g. import { LwcRenderer } from 'vela/renderers/lwc'. The 'lwc'/'native' string options were removed.");let l=n.renderer??new a(s),c=n.engines??[],d=n.dataFeed??new mr,u={market:{symbol:t.symbol,timeframe:t.timeframe,bars:t.bars,session:t.session,visibleRange:t.visibleRange,data:t.data},live:t.live??false,theme:o,defaultLanguage:t.defaultLanguage??c[0]?.language??"pine",drawings:t.drawings,volume:t.volume??true};this.rendererControl=new so(l),t.settings&&this.rendererControl.setSettingsVisibility(t.settings),this.dataControl=new po(d),this.orchestrator=new Xa(i,l,d,c,u,this.dataControl);let h=Ed();Object.keys(h).length>0&&this.rendererControl.set(h),this.panesControl=new ja(this.orchestrator),this.drawingsControl=new mo(this.orchestrator.drawings);}registerEngine(e,t){return this.orchestrator.registerEngine(e,t),this}addIndicator(e,t){return this.orchestrator.addIndicator(e,t)}addNativeIndicator(e,t){return this.orchestrator.addNativeIndicator(e,t)}availableNativeIndicators(){return this.orchestrator.availableNativeIndicators()}presentNativeIndicators(){return this.orchestrator.presentNativeIndicators()}indicators(){return this.orchestrator.listIndicators()}runScript(e,t){let n=this.addIndicator(e,t),i=new Set,o=()=>{try{n.remove();}catch{}};return new Promise(s=>{let a=false,l=this.on("script:run",d=>{if(d.id===n.id){if(a){for(let u of i)u(d);return}a=true,c(),s({ok:true,run:d,error:null,onUpdate:u=>(i.add(u),()=>i.delete(u)),remove:()=>{l(),i.clear(),o();}});}}),c=n.on("error",({error:d})=>{a||(a=true,l(),c(),o(),s({ok:false,run:null,error:d,onUpdate:()=>()=>{},remove:()=>{}}));});})}runIndicator(e,t){let n=this.addIndicator(e,t);return new Promise(i=>{let o=n.on("ready",()=>{o(),s(),i({ok:true,handle:n,error:null,context:null});}),s=n.on("error",({error:a})=>{o(),s(),n.context().catch(()=>null).then(l=>{try{n.remove();}catch{}i({ok:false,handle:null,error:a,context:l});});});})}setMarket(e){return this.orchestrator.setMarket(e)}get market(){return this.orchestrator.marketSnapshot()}ready(){return this.orchestrator.ready()}historyComplete(){return this.orchestrator.historyComplete()}inspect(){return this.orchestrator.inspect()}get renderer(){return this.rendererControl}get panes(){return this.panesControl}get data(){return this.dataControl}get drawings(){return this.drawingsControl}on(e,t){return this.orchestrator.events.on(e,t)}getVisibleRange(){return this.orchestrator.getVisibleRange()}setVisibleRange(e){return this.orchestrator.setVisibleRange(e),this}panBy(e){return this.orchestrator.panBy(e),this}setVisibleRangePreset(e){return this.orchestrator.setVisibleRangePreset(e),this}resize(){this.orchestrator.resize();}setTheme(e){return this.orchestrator.setTheme(jr(e)),this}destroy(){this.orchestrator.destroy();}};function GI(r){if(typeof r!="string")return r;let e=document.querySelector(r);if(!e)throw new Error(`[vela] container not found for selector "${r}"`);return e}var Tx=["symbol","timeframes","style","layout","indicators","actions","undo-redo","alerts","panels","screenshot"];var _i=new Map,Ss=new Map,Cs=new Map;function UI(r){return Ss.set(r.id,r),()=>{Ss.get(r.id)===r&&Ss.delete(r.id);}}function YI(r){Ss.delete(r);}function KI(){return [...Ss.values()]}var Ex=100;function XI(r){return Cs.set(r.id,r),()=>{Cs.get(r.id)===r&&Cs.delete(r.id);}}function jI(r){Cs.delete(r);}function qI(){return [...Cs.values()].sort((r,e)=>(r.order??Ex)-(e.order??Ex))}var pp=["indicators","screenshot"],Px=new Set(pp),ZI=new Set(Tx);function JI(r){if(Px.has(r))return _i.get(r)}function QI(r){return ZI.has(r.id)&&!Px.has(r.id)?(console.warn(`[vela] widget action "${r.id}": this built-in topbar slot is a stateful control and cannot be overridden \u2014 ignored. Overridable slots: ${pp.join(", ")}.`),()=>{}):(_i.set(r.id,r),()=>{_i.get(r.id)===r&&_i.delete(r.id);})}function eA(r){_i.delete(r);}function tA(r,e){let t=[..._i.values()].filter(n=>n.target===r);return t.sort((n,i)=>(n.order??0)-(i.order??0)),e?t.filter(n=>!n.when||n.when(e)):t}var Ts=new Map;function nA(r){return Ts.set(r.id,r),()=>{Ts.get(r.id)===r&&Ts.delete(r.id);}}function rA(r){Ts.delete(r);}function iA(){return [...Ts.values()].sort((r,e)=>(r.order??0)-(e.order??0))}var Es=new Map;function oA(r){return Es.set(r.id,r),()=>{Es.get(r.id)===r&&Es.delete(r.id);}}function sA(r){Es.delete(r);}function aA(){return [...Es.values()].sort((r,e)=>(r.order??0)-(e.order??0))}var Ps=new Map;function lA(r){return Ps.set(r.key,r),()=>{Ps.get(r.key)===r&&Ps.delete(r.key);}}function cA(r){Ps.delete(r);}function dA(r){return [...Ps.values()].filter(e=>e.scope===r)}var id;function uA(r){return id=r,()=>{id===r&&(id=void 0);}}function hA(){return id}var Ls=new Map;function pA(r,e){return Ls.set(r,e),()=>{Ls.get(r)===e&&Ls.delete(r);}}function mA(r){Ls.delete(r);}function fA(r){return {...Object.fromEntries(Ls),...r}}var Lx=280,mp=200,Mx=640;function gA(r,e=mp,t=Mx){let n=Number.isFinite(e)&&e>0?e:mp,i=Number.isFinite(t)?Math.max(t,n):Number.POSITIVE_INFINITY;return Number.isFinite(r)?Math.round(Math.min(Math.max(r,n),i)):n}function Bi(r){let e=r.description?.split("/")[0]?.trim();return e?e.replace(/\s+Perpetual$/i,""):r.ticker.replace(/[-_/]?(USDT|USDC|USD1|USDS|BUSD|USD|EUR|PERP)$/i,"")||r.ticker}function Hi(r){let e=r.trim().toUpperCase();return e?`https://crypto-icons.ledger.com/${encodeURIComponent(e)}.png`:void 0}var kx="https://api.binance.com/api/v3",bA="https://api.binance.us/api/v3",fp="https://fapi.binance.com/fapi/v1",vA="wss://stream.binance.com:9443",yA="wss://stream.binance.us:9443",wA="wss://fstream.binance.com",xA=15e3,SA=2e3,Ix={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",360:"6h",480:"8h",720:"12h",D:"1d",W:"1w",M:"1M"},Ax={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},CA=[1,3,5,15,30,60,120,240,360,480,720],TA={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",360:"6h",480:"8h",720:"12h"},EA=["1","3","5","15","30","45","60","120","180","240","D","W","M"];function Rx(r){return Ax[r]??Ax[r.toLowerCase()]??r}function gp(r){let e=r.trim().toUpperCase();return e.endsWith(".P")?{apiSymbol:e.slice(0,-2),isFutures:true}:{apiSymbol:e,isFutures:false}}function Dx(r){return r.map(e=>({time:Number(e[0]),open:Number(e[1]),high:Number(e[2]),low:Number(e[3]),close:Number(e[4]),volume:Number(e[5])}))}function PA(r){return {time:Number(r.t),open:Number(r.o),high:Number(r.h),low:Number(r.l),close:Number(r.c),volume:Number(r.v)}}function LA(r){let e=new Map;for(let t of r)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function MA(r,e){let t=new Map;for(let n of r){let i=Math.floor(n.time/e)*e,o=t.get(i);o?(o.high=Math.max(o.high,n.high),o.low=Math.min(o.low,n.low),o.close=n.close,o.volume=(o.volume??0)+(n.volume??0)):t.set(i,{time:i,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,i)=>n.time-i.time)}function kA(r){return CA.filter(e=>e<r&&r%e===0).sort((e,t)=>t-e)[0]??null}var od=class{constructor(){this.spotBaseUrl=null;this.spotBaseProbe=null;this.symbolsPromise=null;}info(){return {name:"binance",displayName:"Binance",requiresApiKey:false,supportedTimeframes:EA,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let{apiSymbol:i,isFutures:o}=gp(e),s=o?fp:await this.spotBase(),a=Rx(t),l=Ix[a];if(l)return LA(Dx(await this.fetchKlines(s,i,l,n)));let c=/^\d+$/.test(a)?parseInt(a,10):null,d=c!=null?kA(c):null;if(c==null||d==null)return console.warn(`[vela] Binance: timeframe "${t}" is not supported and cannot be aggregated.`),[];let u=c/d,h={...n,limit:n.limit!=null?n.limit*u+u:void 0},p=Dx(await this.fetchKlines(s,i,TA[d],h)),m=MA(p,c*6e4);return n.limit!=null&&m.length>n.limit?m.slice(-n.limit):m}catch(i){return console.warn(`[vela] Binance: failed to fetch ${e} ${t} \u2014 ${i instanceof Error?i.message:String(i)}`),[]}}async getSymbolInfo(e){let{apiSymbol:t,isFutures:n}=gp(e),i=n?fp:await this.spotBase(),o=n?`${i}/exchangeInfo`:`${i}/exchangeInfo?symbol=${t}`,a=(await this.json(o).catch(()=>null))?.symbols??[],l=n?a.find(u=>u.symbol===t):a[0];if(!l)return;let c=l.filters?.find(u=>u.filterType==="PRICE_FILTER"),d=c?parseFloat(c.tickSize??"0.01"):.01;return {ticker:e,tickerid:`BINANCE:${e}`,prefix:"BINANCE",description:`${l.baseAsset} / ${l.quoteAsset}${n?" Perpetual":""}`,type:n?"futures":"crypto",basecurrency:l.baseAsset,currency:l.quoteAsset,mintick:d,pricescale:Math.round(1/d),timezone:"Etc/UTC",session:"24x7"}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=Promise.all([this.listSpot().catch(()=>[]),this.listFutures().catch(()=>[])]).then(([e,t])=>[...e,...t])),this.symbolsPromise}resolveSymbolIcon(e){return Hi(Bi(e))}subscribe(e,t,n){let{apiSymbol:i,isFutures:o}=gp(e),s=Ix[Rx(t)];return s&&typeof WebSocket<"u"?this.streamKlines(e,t,i,o,s,n):this.pollBars(e,t,n)}streamKlines(e,t,n,i,o,s){let a=false,l=null,c=null,d=null,u=null,h=`${n.toLowerCase()}@kline_${o}`,p=()=>{d&&(clearTimeout(d),d=null);},m=()=>{if(!(a||u)){p(),c&&(clearTimeout(c),c=null);try{l?.close();}catch{}l=null,console.warn(`[vela] Binance: ${e} ${t} stream delivered no data; falling back to polling.`),u=this.pollBars(e,t,s);}},f=async()=>{if(a)return;let g=i?wA:await this.spotWsBase();a||(l=new WebSocket(`${g}/ws/${h}`),d=setTimeout(m,xA),l.onmessage=b=>{if(!(a||u))try{let y=JSON.parse(typeof b.data=="string"?b.data:"");y.k&&(p(),s(PA(y.k)));}catch{}},l.onclose=()=>{!a&&!u&&(c=setTimeout(()=>{f();},SA));},l.onerror=()=>{try{l?.close();}catch{}});};return f(),()=>{a=true,p(),c&&clearTimeout(c),u?.();try{l?.close();}catch{}}}async spotWsBase(){return (await this.spotBase()).includes("binance.us")?yA:vA}pollBars(e,t,n){let i=false,o=null,s=async()=>{if(!i){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}i||(o=setTimeout(()=>{s();},3e3));}};return o=setTimeout(()=>{s();},3e3),()=>{i=true,o&&clearTimeout(o);}}async listSpot(){let e=await this.spotBase();return ((await this.json(`${e}/exchangeInfo`)).symbols??[]).filter(n=>n.status==="TRADING").map(n=>({ticker:n.symbol,description:`${n.baseAsset} / ${n.quoteAsset}`,type:"crypto"}))}async listFutures(){return ((await this.json(`${fp}/exchangeInfo`)).symbols??[]).filter(t=>t.contractType==="PERPETUAL"&&t.status==="TRADING").map(t=>({ticker:`${t.symbol}.P`,description:`${t.baseAsset} / ${t.quoteAsset} Perpetual`,type:"futures"}))}async fetchKlines(e,t,n,i){if(i.from!=null)return this.paginateForward(e,t,n,i.from,i.to??Date.now(),i.limit);let o=i.limit??500;return o>1e3?this.paginateBackward(e,t,n,o,i.to):this.klinesChunk(e,{symbol:t,interval:n,limit:o,endTime:i.to})}async paginateForward(e,t,n,i,o,s){let a=[],l=i;for(;l<o;){let c=await this.klinesChunk(e,{symbol:t,interval:n,limit:1e3,startTime:l,endTime:o});if(c.length===0||(a.push(...c),l=Number(c[c.length-1][6])+1,c.length<1e3)||s&&a.length>=s)break}return s?a.slice(0,s):a}async paginateBackward(e,t,n,i,o){let s=[],a=i,l=o,c=Math.ceil(i/1e3)+5;for(;a>0&&c-- >0;){let d=Math.min(a,1e3),u=await this.klinesChunk(e,{symbol:t,interval:n,limit:d,endTime:l});if(u.length===0||(s=u.concat(s),a-=u.length,l=Number(u[0][0])-1,u.length<d))break}return s}async klinesChunk(e,t){let n=new URL(`${e}/klines`);n.searchParams.set("symbol",t.symbol),n.searchParams.set("interval",t.interval),t.limit&&n.searchParams.set("limit",String(Math.min(t.limit,1e3))),t.startTime!=null&&n.searchParams.set("startTime",String(t.startTime)),t.endTime!=null&&n.searchParams.set("endTime",String(t.endTime));let i=await this.json(n.toString());return Array.isArray(i)?i.length>0&&!Array.isArray(i[0])?[]:i:[]}spotBase(){return this.spotBaseUrl?Promise.resolve(this.spotBaseUrl):(this.spotBaseProbe||(this.spotBaseProbe=(async()=>{try{for(let e of [kx,bA])try{if((await fetch(`${e}/ping`,{signal:AbortSignal.timeout(5e3)})).ok)return this.spotBaseUrl=e}catch{}return kx}finally{this.spotBaseProbe=null;}})()),this.spotBaseProbe)}async json(e){let t=await fetch(e);if(!t.ok)throw new Error(`Binance HTTP ${t.status} for ${e}`);return t.json()}};var IA="https://api.hyperliquid.xyz/info",AA="wss://api.hyperliquid.xyz/ws",RA=15e3,DA=2e3,Ox={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",480:"8h",720:"12h",D:"1d",W:"1w",M:"1M"},Nx={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},OA=[1,3,5,15,30,60,120,240,480,720],NA={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",480:"8h",720:"12h"},FA=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],Fx={D:864e5,W:6048e5,M:2592e6};function VA(r){if(Fx[r])return Fx[r];let e=parseInt(r,10);return Number.isFinite(e)&&e>0?e*6e4:36e5}function Vx(r){return Nx[r]??Nx[r.toLowerCase()]??r}function bp(r){let e=r.trim();return e.includes("/")?e:e.toUpperCase()}function vp(r){return {time:Number(r.t),open:Number(r.o),high:Number(r.h),low:Number(r.l),close:Number(r.c),volume:Number(r.v)}}function _A(r){let e=new Map;for(let t of r)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function BA(r,e){let t=new Map;for(let n of r){let i=Math.floor(n.time/e)*e,o=t.get(i);o?(o.high=Math.max(o.high,n.high),o.low=Math.min(o.low,n.low),o.close=n.close,o.volume=(o.volume??0)+(n.volume??0)):t.set(i,{time:i,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,i)=>n.time-i.time)}function HA(r){return OA.filter(e=>e<r&&r%e===0).sort((e,t)=>t-e)[0]??null}var sd=class{constructor(){this.metaPromise=null;this.spotMetaPromise=null;this.symbolsPromise=null;}info(){return {name:"hyperliquid",displayName:"Hyperliquid",requiresApiKey:false,supportedTimeframes:FA,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let i=bp(e),o=Vx(t),s=Ox[o];if(s)return _A((await this.fetchCandles(i,s,VA(o),n)).map(vp));let a=/^\d+$/.test(o)?parseInt(o,10):null,l=a!=null?HA(a):null;if(a==null||l==null)return console.warn(`[vela] Hyperliquid: timeframe "${t}" is not supported and cannot be aggregated.`),[];let c=a/l,d={...n,limit:n.limit!=null?n.limit*c+c:void 0},u=(await this.fetchCandles(i,NA[l],l*6e4,d)).map(vp),h=BA(u,a*6e4);return n.limit!=null&&h.length>n.limit?h.slice(-n.limit):h}catch(i){return console.warn(`[vela] Hyperliquid: failed to fetch ${e} ${t} \u2014 ${i instanceof Error?i.message:String(i)}`),[]}}async getSymbolInfo(e){let t=bp(e),i=(await this.fetchMeta().catch(()=>null))?.universe?.find(o=>o.name===t);if(i){let o=Bx(Math.max(0,6-(i.szDecimals??2)));return _x(e,t,"USD","futures",`${t} / USD Perpetual`,o)}if(t.includes("/")){let o=await this.fetchSpotMeta().catch(()=>null),s=o?.universe?.find(u=>u.name===t),a=s&&o?.tokens?o.tokens[s.tokens?.[0]??-1]:void 0,[l=t,c="USDC"]=t.split("/"),d=Bx(Math.max(0,8-(a?.szDecimals??2)));return _x(e,l,c,"crypto",`${l} / ${c}`,d)}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=Promise.all([this.listPerps().catch(()=>[]),this.listSpot().catch(()=>[])]).then(([e,t])=>[...e,...t])),this.symbolsPromise}resolveSymbolIcon(e){return Hi(Bi(e))}subscribe(e,t,n){let i=bp(e),o=Ox[Vx(t)];return o&&typeof WebSocket<"u"?this.streamCandles(e,t,i,o,n):this.pollBars(e,t,n)}async listPerps(){return ((await this.fetchMeta()).universe??[]).filter(t=>!t.isDelisted).map(t=>({ticker:t.name,description:`${t.name} / USD Perpetual`,type:"futures"}))}async listSpot(){let e=await this.fetchSpotMeta(),t=e.tokens??[],n=i=>i!=null?t[i]?.name??null:null;return (e.universe??[]).map(i=>{let o=n(i.tokens?.[0]),s=n(i.tokens?.[1]),a=o&&s?`${o} / ${s}`:i.name;return {ticker:i.name,description:a,type:"crypto"}})}async fetchCandles(e,t,n,i){let o=i.to??Date.now(),s=i.from!=null?i.from:o-((i.limit??500)+2)*n,a=await this.candleSnapshot(e,t,s,o);return i.from==null&&i.limit!=null&&a.length>i.limit?a.slice(-i.limit):a}async candleSnapshot(e,t,n,i){let o=await this.post({type:"candleSnapshot",req:{coin:e,interval:t,startTime:Math.floor(n),endTime:Math.floor(i)}});return Array.isArray(o)?o:[]}streamCandles(e,t,n,i,o){let s=false,a=null,l=null,c=null,d=null,u=null,h=()=>{d&&(clearTimeout(d),d=null);},p=()=>{l&&(clearInterval(l),l=null);},m=()=>{if(!(s||u)){h(),p(),c&&(clearTimeout(c),c=null);try{a?.close();}catch{}a=null,console.warn(`[vela] Hyperliquid: ${e} ${t} stream delivered no data; falling back to polling.`),u=this.pollBars(e,t,o);}},f=()=>{s||u||(a=new WebSocket(AA),d=setTimeout(m,RA),a.onopen=()=>{try{a?.send(JSON.stringify({method:"subscribe",subscription:{type:"candle",coin:n,interval:i}}));}catch{}l=setInterval(()=>{try{a?.send(JSON.stringify({method:"ping"}));}catch{}},3e4);},a.onmessage=g=>{if(!(s||u))try{let b=JSON.parse(typeof g.data=="string"?g.data:"");b.channel==="candle"&&b.data&&b.data.s===n&&(h(),o(vp(b.data)));}catch{}},a.onclose=()=>{p(),!s&&!u&&(c=setTimeout(f,DA));},a.onerror=()=>{try{a?.close();}catch{}});};return f(),()=>{s=true,h(),p(),c&&clearTimeout(c),u?.();try{a?.close();}catch{}}}pollBars(e,t,n){let i=false,o=null,s=async()=>{if(!i){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}i||(o=setTimeout(()=>{s();},3e3));}};return o=setTimeout(()=>{s();},3e3),()=>{i=true,o&&clearTimeout(o);}}fetchMeta(){return this.metaPromise??(this.metaPromise=this.post({type:"meta"}).then(e=>e))}fetchSpotMeta(){return this.spotMetaPromise??(this.spotMetaPromise=this.post({type:"spotMeta"}).then(e=>e))}async post(e){let t=await fetch(IA,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Hyperliquid HTTP ${t.status}`);return t.json()}};function _x(r,e,t,n,i,o){return {ticker:r,tickerid:`HYPERLIQUID:${r}`,prefix:"HYPERLIQUID",description:i,type:n,basecurrency:e,currency:t,mintick:o,pricescale:Math.round(1/o),timezone:"Etc/UTC",session:"24x7"}}function Bx(r){return Math.pow(10,-r)}var zA={now:()=>Date.now(),delay:r=>new Promise(e=>setTimeout(e,r))},ad=class{constructor(e,t,n=zA){this.maxConcurrent=e;this.minIntervalMs=t;this.clock=n;this.active=0;this.waiters=[];this.nextStartAt=0;this.pausedUntil=0;}async run(e){await this.acquire();try{return await this.waitForTurn(),await e()}finally{this.release();}}pauseFor(e){e>0&&(this.pausedUntil=Math.max(this.pausedUntil,this.clock.now()+e));}async waitForTurn(){for(;;){let e=this.clock.now(),t=Math.max(this.pausedUntil-e,this.nextStartAt-e);if(t<=0)break;await this.clock.delay(t);}this.nextStartAt=Math.max(this.clock.now(),this.nextStartAt)+this.minIntervalMs;}acquire(){return this.active<this.maxConcurrent?(this.active+=1,Promise.resolve()):new Promise(e=>{this.waiters.push(()=>{this.active+=1,e();});})}release(){this.active-=1;let e=this.waiters.shift();e&&e();}};var yp="https://api.exchange.coinbase.com",$A="wss://ws-feed.exchange.coinbase.com",WA={Accept:"application/json"},GA=15e3,UA=2e3,YA=5e3,ld=300,KA=4,XA=120,jA=4,qA=600,ZA=400;function JA(r,e){let t=Number(r.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t*1e3:e}var Hx={1:60,5:300,15:900,60:3600,360:21600,D:86400},zx={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},QA=[1,5,15,60,360,1440],e2={1:60,5:300,15:900,60:3600,360:21600,1440:86400},t2=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],wp=864e5;function $x(r){return zx[r]??zx[r.toLowerCase()]??r}function xp(r){return r.trim().toUpperCase()}function n2(r){return {time:Number(r[0])*1e3,open:Number(r[3]),high:Number(r[2]),low:Number(r[1]),close:Number(r[4]),volume:Number(r[5])}}function Sp(r){let e=new Map;for(let t of r)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function r2(r,e){return Wx(r,t=>Math.floor(t/e)*e)}function i2(r,e){return Wx(r,e==="W"?o2:s2)}function Wx(r,e){let t=new Map;for(let n of r){let i=e(n.time),o=t.get(i);o?(o.high=Math.max(o.high,n.high),o.low=Math.min(o.low,n.low),o.close=n.close,o.volume=(o.volume??0)+(n.volume??0)):t.set(i,{time:i,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,i)=>n.time-i.time)}function o2(r){let e=new Date(r),t=(e.getUTCDay()+6)%7;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()-t)}function s2(r){let e=new Date(r);return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)}function a2(r){return QA.filter(e=>e<r&&r%e===0).sort((e,t)=>t-e)[0]??null}function Cp(r,e){return e!=null&&r.length>e?r.slice(-e):r}var cd=class{constructor(){this.symbolsPromise=null;this.gate=new ad(KA,XA);}info(){return {name:"coinbase",displayName:"Coinbase",requiresApiKey:false,supportedTimeframes:t2,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let i=xp(e),o=$x(t),s=Hx[o];if(s)return Sp(await this.fetchCandles(i,s,n));if(o==="W"||o==="M"){let h=o==="W"?7*wp:31*wp,p=n.from!=null?n:{...n,limit:n.limit!=null?Math.ceil(n.limit*h/wp)+31:void 0},m=await this.fetchCandles(i,86400,p);return Cp(i2(m,o),n.limit)}let a=/^\d+$/.test(o)?parseInt(o,10):null,l=a!=null?a2(a):null;if(a==null||l==null)return console.warn(`[vela] Coinbase: timeframe "${t}" is not supported and cannot be aggregated.`),[];let c=a/l,d={...n,limit:n.limit!=null?n.limit*c+c:void 0},u=await this.fetchCandles(i,e2[l],d);return Cp(r2(u,a*6e4),n.limit)}catch(i){return console.warn(`[vela] Coinbase: failed to fetch ${e} ${t} \u2014 ${i instanceof Error?i.message:String(i)}`),[]}}async getSymbolInfo(e){let t=xp(e),n=await this.json(`${yp}/products/${t}`).catch(()=>null);if(!n||!n.id)return;let i=n.quote_increment!=null?parseFloat(n.quote_increment):.01,o=i>0?i:.01;return {ticker:e,tickerid:`COINBASE:${e}`,prefix:"COINBASE",description:`${n.base_currency} / ${n.quote_currency}`,type:"crypto",basecurrency:n.base_currency,currency:n.quote_currency,mintick:o,pricescale:Math.round(1/o),timezone:"Etc/UTC",session:"24x7"}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=this.fetchProducts().then(e=>e.filter(t=>t.status==="online"&&!t.trading_disabled).map(t=>({ticker:t.id,description:`${t.base_currency} / ${t.quote_currency}`,type:"crypto"}))).catch(()=>[])),this.symbolsPromise}resolveSymbolIcon(e){return Hi(Bi(e))}subscribe(e,t,n){let i=Hx[$x(t)];return i&&typeof WebSocket<"u"?this.streamTicker(e,t,i,n):this.pollBars(e,t,n)}async fetchProducts(){let e=await this.json(`${yp}/products`);return Array.isArray(e)?e:[]}async fetchCandles(e,t,n){return n.from!=null?this.paginateForward(e,t,n.from,n.to??Date.now(),n.limit):this.paginateBackward(e,t,n.limit??500,n.to??Date.now())}async paginateBackward(e,t,n,i){let o=t*1e3,s=[],a=n,l=i,c=Math.ceil(n/ld)+4;for(;a>0&&c-- >0;){let d=Math.min(a,ld),u=l-d*o,h=await this.candlesChunk(e,t,u,l);if(h.length===0||(s=h.concat(s),a-=h.length,l=h[0].time-1,h.length<d))break}return Cp(Sp(s),n)}async paginateForward(e,t,n,i,o){let s=t*1e3,a=[],l=n,c=Math.ceil((i-n)/(ld*s))+4;for(;l<i&&c-- >0;){let u=Math.min(l+ld*s,i),h=await this.candlesChunk(e,t,l,u);if(h.length>0&&a.push(...h),l=u,o!=null&&a.length>=o)break}let d=Sp(a);return o!=null?d.slice(0,o):d}async candlesChunk(e,t,n,i){let o=new URL(`${yp}/products/${e}/candles`);o.searchParams.set("granularity",String(t)),o.searchParams.set("start",String(Math.floor(n/1e3))),o.searchParams.set("end",String(Math.floor(i/1e3)));let s=await this.json(o.toString());return !Array.isArray(s)||s.length>0&&!Array.isArray(s[0])?[]:s.map(n2).sort((a,l)=>a.time-l.time)}streamTicker(e,t,n,i){let o=xp(e),s=n*1e3,a=T=>Math.floor(T/s)*s,l=false,c=null,d=null,u=null,h=null,p=null,m=null,f=()=>{u&&(clearTimeout(u),u=null);},g=()=>{h&&(clearInterval(h),h=null);},b=()=>{m&&i({...m});},y=async T=>{try{let E=await this.getBars(e,t,{limit:2});if(l||E.length===0)return;T&&E.length>=2&&i(E[E.length-2]);let x=E[E.length-1];m=m&&m.time===x.time?{...x,high:Math.max(x.high,m.high),low:Math.min(x.low,m.low),close:m.close}:{...x},b();}catch{}},v=(T,E)=>{let x=Number(T);if(!Number.isFinite(x))return;let L=a(E);!m||L>m.time?(m={time:L,open:x,high:x,low:x,close:x,volume:0},b(),y(false)):L===m.time&&(m={...m,close:x,high:Math.max(m.high,x),low:Math.min(m.low,x)},b());},S=()=>{if(!(l||p)){f(),g(),d&&(clearTimeout(d),d=null);try{c?.close();}catch{}c=null,console.warn(`[vela] Coinbase: ${e} ${t} stream delivered no data; falling back to polling.`),p=this.pollBars(e,t,i);}},P=()=>{l||p||(c=new WebSocket($A),u=setTimeout(S,GA),c.onopen=()=>{try{c?.send(JSON.stringify({type:"subscribe",product_ids:[o],channels:["ticker"]}));}catch{}y(false),h=setInterval(()=>{y(false);},YA);},c.onmessage=T=>{if(!(l||p))try{let E=JSON.parse(typeof T.data=="string"?T.data:"");E.type==="ticker"&&E.product_id===o&&E.price!=null&&(f(),v(E.price,E.time?Date.parse(E.time):Date.now()));}catch{}},c.onclose=()=>{g(),!l&&!p&&(d=setTimeout(P,UA));},c.onerror=()=>{try{c?.close();}catch{}});};return P(),()=>{l=true,f(),g(),d&&clearTimeout(d),p?.();try{c?.close();}catch{}}}pollBars(e,t,n){let i=false,o=null,s=async()=>{if(!i){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}i||(o=setTimeout(()=>{s();},3e3));}};return o=setTimeout(()=>{s();},3e3),()=>{i=true,o&&clearTimeout(o);}}async json(e){return (await this.request(e)).json()}async request(e){for(let t=0;;t+=1){let n=await this.gate.run(()=>fetch(e,{headers:WA}));if(n.status===429&&t<jA){let i=qA*2**t+Math.random()*ZA;this.gate.pauseFor(Math.max(JA(n,0),i));continue}if(!n.ok)throw new Error(`Coinbase HTTP ${n.status} for ${e}`);return n}}};
1008
1008
  exports.ACCENT=Ye;exports.ACCENT_BRIGHT=Br;exports.BEARISH=W;exports.BULLISH=z;exports.BarStore=qa;exports.BinanceProvider=od;exports.CATEGORICAL=Rs;exports.CHIP_PLATE=Op;exports.CROSSHAIR=Ap;exports.CachingDataFeed=uo;exports.CoinbaseProvider=cd;exports.DARK_THEME=Gt;exports.DEFAULT_PANEL_MAX_WIDTH=Mx;exports.DEFAULT_PANEL_MIN_WIDTH=mp;exports.DEFAULT_PANEL_WIDTH=Lx;exports.DataControl=po;exports.Drawing=G;exports.DrawingStore=Yr;exports.DrawingToolbar=bs;exports.DrawingsControl=mo;exports.HIGHLIGHT=kp;exports.HyperliquidProvider=sd;exports.INFO=Je;exports.INVALID=Os;exports.LIGHT_THEME=oo;exports.MARKER=Ip;exports.MultiProviderFeed=mr;exports.NEUTRAL=J;exports.NativeRenderer=ys;exports.OVERRIDABLE_TOPBAR_IDS=pp;exports.RendererControl=so;exports.SERIES_LINE=_;exports.SESSION_OFF=w2;exports.SESSION_POST=y2;exports.SESSION_PRE=v2;exports.SLATE=Dp;exports.SLATE_DEEP=Rp;exports.TRADE_EXIT=Vp;exports.TRADE_LONG=Np;exports.TRADE_SHORT=Fp;exports.TypedEventBus=qn;exports.VALID=Ds;exports.Vela=hp;exports.WARNING=de;exports.buildColorPicker=Yo;exports.buildToolbar=to;exports.categoricalColor=x2;exports.chartType=un;exports.chartTypes=Lt;exports.clampPanelWidth=gA;exports.combineColor=Yl;exports.createDrawing=Rn;exports.defaultToolbar=eo;exports.deserializeDrawing=pt;exports.drawingTypes=$a;exports.getDrawingType=Et;exports.getNativeIndicator=$i;exports.iconMarkup=Fs;exports.inputDeltas=Vb;exports.inputVisible=zo;exports.legendActions=iA;exports.legendCallouts=aA;exports.nativeIndicatorDescriptors=Is;exports.nativeIndicatorTypes=Pp;exports.normalizeSettingsRow=Kr;exports.registerChartType=Cd;exports.registerDefaultEngine=pA;exports.registerDrawingType=V;exports.registerIcon=N;exports.registerLegendAction=nA;exports.registerLegendCallout=oA;exports.registerNativeIndicator=Ln;exports.registerRendererDefaults=FC;exports.registerRendererLayer=zM;exports.registerSidePanel=XI;exports.registerStatePersistence=lA;exports.registerSymbolRanking=uA;exports.registerWidgetAction=QI;exports.registerWidgetAttachment=UI;exports.rendererDefaults=Ed;exports.rendererLayers=Vh;exports.resolveEngines=fA;exports.resolveTheme=jr;exports.settingsRowValueKeys=ro;exports.sharedBarStore=ao;exports.sidePanels=qI;exports.splitColor=$n;exports.stableSeriesId=Xn;exports.statePersistenceHandlers=dA;exports.symbolRanking=hA;exports.tickerModifierIds=Td;exports.timeframeToMs=Pt;exports.topbarActionOverride=JI;exports.unregisterChartType=LC;exports.unregisterDefaultEngine=mA;exports.unregisterLegendAction=rA;exports.unregisterLegendCallout=sA;exports.unregisterNativeIndicator=Ep;exports.unregisterRendererDefaults=VC;exports.unregisterRendererLayer=$M;exports.unregisterSidePanel=jI;exports.unregisterStatePersistence=cA;exports.unregisterWidgetAction=eA;exports.unregisterWidgetAttachment=YI;exports.widgetActions=tA;exports.widgetAttachments=KI;return exports;})({});