@kymoscope/sdk 0.14.1 → 0.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/kymoscope-embed.js +51 -51
- package/dist/kymoscope-sdk.js +54 -54
- package/dist/types/lib/render/frames.d.ts +2 -1
- package/package.json +1 -1
package/dist/kymoscope-sdk.js
CHANGED
|
@@ -203,8 +203,8 @@ void main() {
|
|
|
203
203
|
if (cov <= 0.0) discard;
|
|
204
204
|
float alpha = v_color.a * cov;
|
|
205
205
|
outColor = vec4(v_color.rgb * alpha, alpha);
|
|
206
|
-
}`;function hH(e,t,n,r){let i=e.length,a=0;for(let t=0;t<i;t++)Number.isFinite(r[t])&&Number.isFinite(e[t])&&a++;if(a===i)return null;let o=new Float32Array(a),s=new Float32Array(a),c=new Uint8Array(a),l=0,u=!1;for(let a=0;a<i;a++)n[a]&&(u=!0),Number.isFinite(r[a])&&Number.isFinite(e[a])&&(o[l]=t[a],s[l]=r[a],u&&=(c[l]=255,!1),l++);return{x:o,y:s,starts:c}}function gH(e,t,n){let r=e.length,i=0;for(let t=0;t<r;t++)if(Number.isFinite(e[t])){i=e[t];break}let a=new Float32Array(r);for(let t=0;t<r;t++)a[t]=e[t]-i;let o=new Uint8Array(r);if(t)for(let e=0;e<r;e++)t[e]&&(o[e]=255);let s=n.map(t=>hH(e,a,o,t)??{x:a,y:t,starts:o}),c=s.map(e=>e.y.length),l=c.reduce((e,t)=>e+t,0),u=new Float32Array(l),d=new Float32Array(l),f=new Uint8Array(l),p=new Float32Array(l),m=0;return s.forEach((e,t)=>{u.set(e.x,m),d.set(e.y,m),f.set(e.starts,m),e.y.length>0&&(f[m]=255),p.fill(t,m,m+e.y.length),m+=e.y.length}),{origin:i,x:u,y:d,starts:f,sid:p,counts:c}}function _H(e,t,n,r,i,a){let o=(i-r)/a,s=(t,n)=>{let r=0,i=e.length;for(;r<i;){let a=r+i>>>1;(n?e[a]<=t:e[a]<t)?r=a+1:i=a}return r},c=s(r,!1),l=s(i,!0),u=t.length*(2*a+2),d=new Float32Array(u),f=new Float32Array(u),p=new Uint8Array(u),m=new Float32Array(u),h=0,g=(e,t,r)=>{d[h]=e-n,f[h]=t,m[h]=r,h++};return t.forEach((t,n)=>{let i=h;for(let r=c-1;r>=Math.max(0,c-64);r--)if(t[r]===t[r]){g(e[r],t[r],n);break}let s=c;for(let i=0;i<a&&s<l;i++){let c=i===a-1?1/0:r+(i+1)*o,u=1/0,d=-1/0,f=-1,p=-1;for(;s<l&&e[s]<c;s++){let e=t[s];e<u&&(u=e,f=s),e>d&&(d=e,p=s)}f<0||(f===p?g(e[f],u,n):f<p?(g(e[f],u,n),g(e[p],d,n)):(g(e[p],d,n),g(e[f],u,n)))}for(let r=l;r<Math.min(e.length,l+64);r++)if(t[r]===t[r]){g(e[r],t[r],n);break}h>i&&(p[i]=255)}),{x:d.subarray(0,h),y:f.subarray(0,h),starts:p.subarray(0,h),sid:m.subarray(0,h),bucket:o}}function vH(e){for(let t=1;t<e.length;t++)if(!(e[t]>=e[t-1]))return!1;return e.length===0||e[0]===e[0]}function yH(e,t=1){let n=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0}),r=typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas;if(!n)return null;let i=()=>{let e=QV(n,n.VERTEX_SHADER,pH),t=QV(n,n.FRAGMENT_SHADER,mH);if(!e||!t)return null;let r=n.createProgram();return r?(n.attachShader(r,e),n.attachShader(r,t),n.linkProgram(r),n.getProgramParameter(r,n.LINK_STATUS)?{prog:r,vs:e,fs:t}:(console.error(`glSeries program link failed:`,n.getProgramInfoLog(r)),null)):null},a=r?i():uH(n,`glSeries`,i);if(!a)return null;let{prog:o,vs:s,fs:c}=a,l=e=>n.getAttribLocation(o,e),u=l(`a_corner`),d=l(`a_ax`),f=l(`a_bx`),p=l(`a_ay`),m=l(`a_by`),h=l(`a_bstart`),g=l(`a_sid`),_=[d,f,p,m,h,g],v=e=>n.getUniformLocation(o,e),y={res:v(`u_resolution`),styles:v(`u_styles`),left:v(`u_left`),plotW:v(`u_plotW`),xoff:v(`u_xoff`),xscale:v(`u_xscale`),xR:v(`u_xR`),minGap:v(`u_minGap`),cutPx:v(`u_cutPx`)},b=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,b),n.bufferData(n.ARRAY_BUFFER,Float32Array.from([-1,-1,1,-1,-1,1,1,1]),n.STATIC_DRAW);let x=n.createFramebuffer(),S=n.createRenderbuffer(),C=1,w=1,T=(`clientWidth`in e?e.clientWidth:0)||1,E=(`clientHeight`in e?e.clientHeight:0)||1,D=[],O=0,k=1,A=1/0,j=e=>{let t=n.createBuffer();return n.bindBuffer(n.ARRAY_BUFFER,t),n.bufferData(n.ARRAY_BUFFER,e,n.STATIC_DRAW),t},M=e=>{if(e)for(let t of[e.x,e.y,e.starts,e.sid])n.deleteBuffer(t)},N=e=>{e&&(M(e.full),M(e.res),n.deleteTexture(e.styles))},P=e=>({x:j(e.x),y:j(e.y),starts:j(e.starts),sid:j(e.sid),total:e.x.length}),F=e=>{let t=e.full;if(t&&t.version===e.version)return t;if(t&&e.valuesOnly&&t.whole&&e.counts.every(t=>t===e.xs.length)){let r=e.xs.length,i=e.columns.length===1?e.columns[0]:new Float32Array(r*e.columns.length);return e.columns.length>1&&e.columns.forEach((e,t)=>i.set(e,t*r)),n.bindBuffer(n.ARRAY_BUFFER,t.y),n.bufferSubData(n.ARRAY_BUFFER,0,i),t.version=e.version,t}M(t);let r=gH(e.xs,e.breaks,e.columns);return e.full={...P(r),version:e.version,whole:r.counts.every(t=>t===e.xs.length)},e.full},I=t=>{let n=Math.max(1,Math.round(t.plotW*(e.width/T)));if(t.resamplable&&k>O){let e=t.xs,r=0,i=e.length;for(;r<i;){let t=r+i>>>1;e[t]<O?r=t+1:i=t}let a=r;for(i=e.length;r<i;){let t=r+i>>>1;e[t]<=k?r=t+1:i=t}if(r-a>n*4){let r=`${t.version}|${O}|${k}|${n}`;if(t.res?.key!==r){M(t.res);let i=_H(e,t.columns,t.origin,O,k,n);t.res={...P(i),key:r,bucket:i.bucket}}return{d:t.res,minGap:t.res.bucket*2.5}}}return{d:F(t),minGap:0}},L=(e,r)=>{let i=e.counts.length,a=Math.max(1,Math.ceil(i/fH)),o=3*Math.min(Math.max(i,1),fH),s=new Float32Array(o*a*4);for(let n=0;n<i;n++){let i=r[n],a=(Math.floor(n/fH)*o+n%fH*3)*4;if(!i)continue;let c=i.width??t;s.set([Math.min(i.scaleMin,i.scaleMax),Math.max(i.scaleMin,i.scaleMax),i.bandTop,i.bandBottom],a),s.set(i.color,a+4),s.set([i.gapMedian,c/2,c/2+YV,+(e.counts[n]>=2)],a+8)}n.bindTexture(n.TEXTURE_2D,e.styles),n.texImage2D(n.TEXTURE_2D,0,n.RGBA32F,o,a,0,n.RGBA,n.FLOAT,s),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST)};return{resize(t,r,i){T=Math.max(1,t),E=Math.max(1,r),e.width=Math.round(T*i),e.height=Math.round(E*i),C=e.width*2,w=e.height*2,x&&S&&(n.bindRenderbuffer(n.RENDERBUFFER,S),n.renderbufferStorage(n.RENDERBUFFER,n.RGBA8,C,w),n.bindFramebuffer(n.FRAMEBUFFER,x),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,S),n.bindFramebuffer(n.FRAMEBUFFER,null))},setData(e,t,r,i){let a=D[e],o=!t&&!!a&&i.length===a.columns.length;if(!t){if(!a)return;t=a.xs,r=a.breaks}let s=0;for(let e=0;e<t.length;e++)if(Number.isFinite(t[e])){s=t[e];break}let c=i.map(e=>{let t=0;for(let n=0;n<e.length;n++)e[n]===e[n]&&t++;return t});if(a&&(o||a.xs===t)){a.columns=i,a.counts=c,a.valuesOnly=o,a.version++,o||(M(a.full),a.full=null);return}let l={xs:t,breaks:r,columns:i,origin:s,counts:c,resamplable:!r?.some(e=>e)&&vH(t),version:0,valuesOnly:!1,full:null,res:null,styles:n.createTexture(),left:a?.left??0,plotW:a?.plotW??0};L(l,[]),D[e]=l,N(a)},setStyles(e,t,n,r){let i=D[e];i&&(L(i,t),i.left=n,i.plotW=r)},clearLayer(e){N(D[e]),D[e]=null},setView(e,t,n=1/0){O=e,k=t,A=n},render(){n.bindFramebuffer(n.FRAMEBUFFER,x),n.viewport(0,0,x?C:e.width,x?w:e.height),n.disable(n.SCISSOR_TEST),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(o),n.uniform2f(y.res,T,E),n.uniform1i(y.styles,0),n.activeTexture(n.TEXTURE0),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE_MINUS_SRC_ALPHA),n.bindBuffer(n.ARRAY_BUFFER,b),n.enableVertexAttribArray(u),n.vertexAttribPointer(u,2,n.FLOAT,!1,0,0),n.vertexAttribDivisor(u,0);for(let e of _)n.enableVertexAttribArray(e),n.vertexAttribDivisor(e,1);let t=k-O||1;for(let e of D){if(!e)continue;n.uniform1f(y.left,e.left),n.uniform1f(y.plotW,e.plotW),n.uniform1f(y.xoff,O-e.origin),n.uniform1f(y.xscale,e.plotW/t),n.uniform1f(y.xR,t),n.uniform1f(y.cutPx,Number.isFinite(A)?e.left+(A-O)*(e.plotW/t):1e9);let{d:r,minGap:i}=I(e);r.total<2||(n.uniform1f(y.minGap,i),n.bindTexture(n.TEXTURE_2D,e.styles),n.bindBuffer(n.ARRAY_BUFFER,r.x),n.vertexAttribPointer(d,1,n.FLOAT,!1,4,0),n.vertexAttribPointer(f,1,n.FLOAT,!1,4,4),n.bindBuffer(n.ARRAY_BUFFER,r.y),n.vertexAttribPointer(p,1,n.FLOAT,!1,4,0),n.vertexAttribPointer(m,1,n.FLOAT,!1,4,4),n.bindBuffer(n.ARRAY_BUFFER,r.starts),n.vertexAttribPointer(h,1,n.UNSIGNED_BYTE,!0,1,1),n.bindBuffer(n.ARRAY_BUFFER,r.sid),n.vertexAttribPointer(g,1,n.FLOAT,!1,4,0),n.drawArraysInstanced(n.TRIANGLE_STRIP,0,4,r.total-1))}for(let e of _)n.vertexAttribDivisor(e,0);x&&(n.bindFramebuffer(n.READ_FRAMEBUFFER,x),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),n.blitFramebuffer(0,0,C,w,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.LINEAR),n.bindFramebuffer(n.FRAMEBUFFER,null))},dispose(){for(let e of D)N(e);D.length=0,n.deleteBuffer(b),n.deleteFramebuffer(x),n.deleteRenderbuffer(S),r&&(n.deleteProgram(o),n.deleteShader(s),n.deleteShader(c)),r&&n.getExtension(`WEBGL_lose_context`)?.loseContext()}}}``+new URL(`assets/offscreenLineWorker-C-_uNa_H.js`,import.meta.url).href;var bH=[],xH=12,SH=!1,CH=!1,wH=0,TH=3,EH=1;function DH(){return!SH&&typeof Worker<`u`&&typeof HTMLCanvasElement<`u`&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen==`function`}var OH=`kymoscope-gl-first-frame`;function kH(e,t=1,n,r,i){if(typeof e.transferControlToOffscreen!=`function`||typeof Worker>`u`)return null;let a,o=bH.pop();try{a=o??UE(``+new URL(`assets/offscreenLineWorker-C-_uNa_H.js`,import.meta.url).href)}catch{return SH=!0,null}let s;try{s=e.transferControlToOffscreen()}catch{return o?bH.push(o):a.terminate(),null}let c=()=>{},l=EH++,u=!1;a.postMessage({type:`init`,canvas:s,lineWidth:t,gen:l},[s]),a.onmessage=e=>{e.data?.gen===l&&(e.data.type===`lost`?n?.():e.data.type===`first`&&(CH=!0,performance.mark?.(OH),c()))},a.onerror=()=>{u=!0,(!CH||++wH>=TH)&&(SH=!0),n?.()};let d=aH(r),f=-1,p=-1,m=-1,h={own:!0,resize(e,t,n){e===f&&t===p&&n===m||(f=e,p=t,m=n,a.postMessage({type:`resize`,w:e,h:t,dpr:n}))},setData(e,t){let n=[];t.xs&&n.push(t.xs.buffer),t.breaks&&n.push(t.breaks.buffer);for(let e of t.columns)n.push(e.buffer);a.postMessage({type:`data`,layer:e,...t},n)},setStyle(e,t){a.postMessage({type:`style`,layer:e,...t})},clear(e){a.postMessage({type:`clear`,layer:e})},setView(e,t,n){a.postMessage({type:`view`,xmin:e,xmax:t,cut:n})},dispose(){a.onmessage=null,a.onerror=null;let e=!u&&!SH&&bH.length<xH;try{a.postMessage({type:`dispose`})}catch{e=!1}e?bH.push(a):a.terminate(),d()}},g=i?AH(i,t):null;if(!g||!i)return h;let _=()=>{g&&(g.dispose(),g=null,i.getContext(`2d`)?.clearRect(0,0,i.width,i.height))};return c=()=>{(typeof requestAnimationFrame==`function`?requestAnimationFrame:setTimeout)(_)},{own:!0,resize(e,t,n){g?.resize(e,t,n),h.resize(e,t,n)},setData(e,t){g?.setData(e,{...t,xs:t.xs?t.xs.slice():null,breaks:t.breaks?.slice(),columns:t.columns.map(e=>e.slice())}),h.setData(e,t)},setStyle(e,t){g?.setStyle(e,t),h.setStyle(e,t)},clear(e){g?.clear(e),h.clear(e)},setView(e,t,n){g?.setView(e,t,n),h.setView(e,t,n)},dispose(){_(),h.dispose()}}}function AH(e,t=1){let n=dH(e,e=>yH(e,t));if(!n)return null;let r=0,i=1,a,o=``,s=(e,t)=>{n.setStyles(e,t.styles,t.left,t.plotW),r=t.xmin,i=t.xmax,a=t.cut,n.setView(r,i,a),n.render()};return{resize(e,t,r){let i=`${e}|${t}|${r}`;i!==o&&(o=i,n.resize(e,t,r),n.render())},setData(e,t){n.setData(e,t.xs,t.breaks,t.columns),s(e,t)},setStyle(e,t){s(e,t)},clear(e){n.clearLayer(e),n.render()},setView(e,t,o){e===r&&t===i&&o===a||(r=e,i=t,a=o,n.setView(e,t,o),n.render())},dispose(){n.dispose()}}}var jH=new Set;function MH(e){jH.add(e)}function NH(e){jH.delete(e)}function PH(){let e=typeof window>`u`?[]:[window];for(let t of jH)t.closed||e.push(t);return e}var FH=1,IH=new Map;function LH(e){let t=FH++,n=PH();if(n.length===1){let r=n[0].requestAnimationFrame(n=>{IH.delete(t),e(n)});return IH.set(t,[{w:n[0],id:r}]),t}let r=[],i=n=>{IH.has(t)&&(RH(t),e(n))};for(let e of n)r.push({w:e,id:e.requestAnimationFrame(i)});return IH.set(t,r),t}function RH(e){if(e==null)return;let t=IH.get(e);if(t){IH.delete(e);for(let{w:e,id:n}of t)e.closed||e.cancelAnimationFrame(n)}}var zH=new WeakMap;function BH(e){e&&zH.set(e,(zH.get(e)??0)+1)}function VH(e){let t=zH.get(e)??0;for(let n of e.querySelectorAll(`*`))t+=zH.get(n)??0;return t}function HH(){return PH().every(e=>e.document.hidden)}var UH=class{#e;#t=new Map;constructor(e){this.#e=e}observe(e,t){let n=e.ownerDocument.defaultView??window,r=this.#t.get(n);r||(r=new(n.ResizeObserver??ResizeObserver)(e=>this.#e(e,this)),this.#t.set(n,r)),r.observe(e,t)}unobserve(e){for(let t of this.#t.values())t.unobserve(e)}disconnect(){for(let e of this.#t.values())e.disconnect();this.#t.clear()}};function WH(e){return!!e&&e.isConnected&&typeof e.checkVisibility==`function`&&!e.checkVisibility()}function GH(e,t){let n=0,r=null,i=()=>WH(t()),a=t=>{n=0,!i()&&(r=t,e())};return{schedule(){n||=LH(a)},now(){if(i())return;let o=t()?.ownerDocument?.timeline?.currentTime;if(typeof o!=`number`||o===r){n||=LH(a);return}n&&=(RH(n),0),r=o,e()},cancel(){n&&RH(n),n=0}}}var KH=.6,qH=16,JH={ts:-1,work:0,floor:1/0},YH=1/0;function XH(e,t=-1/0){if(e!==JH.ts){if(e>JH.ts&&e<JH.ts+JH.work/KH)return!1;JH={ts:e,work:0,floor:YH},YH=1/0}return JH.work>=qH||t>JH.floor?(YH=Math.min(YH,t),!1):!0}function ZH(e,t){e===JH.ts&&(JH.work+=t)}function QH(e,t=typeof window>`u`?null:e=>{LH(e)}){let n=!1,r=null;return{set(i){if(r=i,!t){e(i);return}n||(n=!0,t(()=>{n=!1,e(r)}))}}}function $H(e,t,n,r,i){return r+(e-t)/n*(i-r)}function eU(e,t,n,r){let i=new Map,a=n.length;if(a===0)return i;let o=new Float64Array(a),s=new Float64Array(a).fill(1/0);for(let r of e){let e=r.x;for(let i=0;i<a;i++){let a=r.cols.get(n[i]);if(!a)continue;let c=s[i],l=o[i];for(let n=0;n<r.length;n++){let r=e[n],i=r<t?t-r:r-t;if(i>=c)continue;let o=a[n];Number.isFinite(o)&&(c=i,l=o)}s[i]=c,o[i]=l}}for(let e=0;e<a;e++)s[e]!==1/0&&(r&&s[e]>(r.get(n[e])??1/0)||i.set(n[e],o[e]));return i}function tU(e,t,n,r=64){let i=new Map;if(t.length===0||!Number.isFinite(n))return i;let a=new Map;for(let o of e){if(o.length===0)continue;let e=0,s=o.length-1;for(;e<s;){let t=e+s>>1;o.x[t]<n?e=t+1:s=t}for(let s of t){let t=o.cols.get(s);if(t)for(let c=0;c<=r;c++){let r=e-c,l=e+c,u=r>=0&&Number.isFinite(t[r])?r:l<o.length&&Number.isFinite(t[l])?l:-1;if(u<0)continue;let d=Math.abs(o.x[u]-n);d<(a.get(s)??1/0)&&(a.set(s,d),i.set(s,t[u]));break}}}return i}function nU(e,t){let n=new Map;if(t.length===0)return n;for(let r=e.length-1;r>=0&&n.size<t.length;r--){let i=e[r];for(let e of t){if(n.has(e))continue;let t=i.cols.get(e);if(t){for(let r=i.length-1;r>=0;r--)if(Number.isFinite(t[r])){n.set(e,t[r]);break}}}}return n}function rU(e,t){return!(e>0)||!(t>0)?1:1-Math.exp(-e/t)}function iU(e,t,n,r,i,a){let o=e;return n!==null&&Math.abs(t-n)<i*a&&(o+=t-n),o+(t-o)*r}function aU(e,t,n,r=t){if(!(t>e)||n==null||!(n>0))return[e,t];let i=Number.isFinite(r)?Math.max(e,r):t;return i-n<e?[e,Math.min(t,e+n)]:[i-n,i]}function oU(e,t){return e>0?Math.min(8e3,Math.max(400,Math.round(e*t*2))):2e3}var sU=.5;function cU(e,t,n,r=sU){if(!(t>0))return e;let i=e!=null&&e>0?Math.min(e,t):t,a=n?i*.88:i/.88;return a>=t*.999?null:Math.max(r,a)}function lU(e=0){return{d:null,lastT:NaN,wall:0,base:NaN,wait:e,waitAge:0,gap:NaN}}var uU=new Map;function dU(e,t,n,r){let i=uU.get(e);if(i||uU.set(e,i={p:lU(),at:NaN,d:NaN}),n-i.at<2&&Number.isFinite(i.d))return i.d;let a=Number.isNaN(i.at)?16:n-i.at;return i.at=n,i.d=TU(i.p,t,a,r),i.d}function fU(){let e;for(let t of uU.values())(!e||t.at>e.at)&&(e=t);return e&&Number.isFinite(e.d)?{newest:e.p.lastT,lag:e.p.lastT-e.d,wait:e.p.wait,waitAge:e.p.waitAge}:null}function pU(e){return Math.min(xU,e.wait*1.2+.05)}function mU(e){return Number.isFinite(e.gap)?Math.min(e.gap,pU(e)):0}function hU(e){let t=uU.get(e);return t?mU(t.p):0}function gU(e){let t=uU.get(e);return t?pU(t.p):0}function _U(e,t,n){let r=e(t);if(!(n>0))return r;let i=(r-e(t-vU))/vU;return Number.isFinite(i)&&i>=0?r+i*n:r}var vU=.25,yU=1,bU=250,xU=3,SU=90,CU=30,wU=.001;function TU(e,t,n,r){if(!Number.isFinite(t))return t;let i=n/1e3;e.wall+=i;let a=n>bU&&e.d!==null,o=e.lastT;if(t<e.lastT&&Object.assign(e,lU(),{wall:e.wall}),t<=e.lastT)e.base+=i*wU;else{let n=e.wall-t;e.base=Number.isNaN(e.base)?n:Math.min(e.base+i*wU,n);let r=t-o;r>0&&r<yU&&(e.gap=Number.isNaN(e.gap)?r:e.gap+(r-e.gap)*.1)}e.lastT=t;let s=e.wall-t-e.base;if(r){let n=t>o?r(o):NaN;s=t>o?e.wall-e.base-(Number.isFinite(n)?n:o):0}a||(e.waitAge+=i),a||(s>e.wait?(e.wait=Math.min(xU,s),e.waitAge=0):s>e.wait*.8?e.waitAge=0:e.waitAge>SU&&(e.wait*=Math.exp(-i/CU)));let c=e.wall-e.base-pU(e);if(e.d===null)e.d=e.wait>0?Math.min(t,c):t;else if(a||e.d<c-2)e.d=Math.min(t,c);else{let t=Math.min(n,64);e.d+=t/1e3,e.d+=(c-e.d)*Math.min(1,t/500)}return e.d>t&&(e.d=t),e.d}var EU=(e,t)=>e.log?(Math.log10(Math.max(t,Number.MIN_VALUE))-Math.log10(e.v0))/(Math.log10(e.v1)-Math.log10(e.v0)||1):(t-e.v0)/(e.v1-e.v0||1),DU=(e,t)=>e.log?10**(Math.log10(e.v0)+t*(Math.log10(e.v1)-Math.log10(e.v0))):e.v0+t*(e.v1-e.v0),OU=(e,t)=>e.left+EU(e.x,t)*e.width,kU=(e,t)=>DU(e.x,(t-e.left)/(e.width||1)),AU=(e,t)=>e.top+(1-EU(e.y,t))*e.height,jU=e=>!e||Number.isFinite(e.v0)&&Number.isFinite(e.v1)&&e.v0!==e.v1&&(!e.log||e.v0>0&&e.v1>0),MU=(e,t)=>e===t||!!e&&!!t&&e.v0===t.v0&&e.v1===t.v1&&!!e.log==!!t.log;function NU(){let e=null,t=new Set;return{get:()=>e,set:n=>{if(n&&(n.width>0&&n.height>0?(!jU(n.x)||!jU(n.y))&&(n={...n,x:jU(n.x)?n.x:void 0,y:jU(n.y)?n.y:void 0}):n=null),!(n===e||n&&e&&n.left===e.left&&n.top===e.top&&n.width===e.width&&n.height===e.height&&MU(n.x,e.x)&&MU(n.y,e.y))){e=n;for(let e of[...t])e()}},subscribe:e=>(t.add(e),()=>{t.delete(e)})}}var PU=ht(()=>{}),FU=()=>bt(PU),IU=`M5 .8a3.1 3.1 0 0 0-3.1 3.1v2.3L.8 7.6h8.4L8.1 6.2V3.9A3.1 3.1 0 0 0 5 .8zM3.9 8.4a1.1 1.1 0 0 0 2.2 0z`,LU=[5,4],RU=null;function zU(e,t,n,r){typeof Path2D>`u`||(RU??=new Path2D(IU),e.save(),e.setLineDash([]),e.translate(t,n),e.fillStyle=r,e.fill(RU),e.restore())}var BU=(()=>{try{return localStorage.getItem(`glLines`)!==`0`}catch{return!0}})(),VU=(()=>{try{return localStorage.getItem(`offscreenGl`)!==`0`}catch{return!0}})(),HU=70;function UU(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}var WU={top:14,right:160,bottom:40,left:110},GU={top:14,right:100,bottom:40,left:70},KU=640,qU={top:3,right:3,bottom:3,left:3},JU=260;function YU(e){return e<JU?qU:e<KU?GU:WU}var XU=220,ZU=.05,QU=2e3,$U=4,eW=1e3/120,tW=`11.25px ${Q.mono}`,nW=11*1.125,rW=24*1.125,iW=rW-nW+26,aW=.6,oW=13,sW=10,cW=5,lW=14,uW=4;function dW(e,t,n){return Math.min(n,Math.max(t,e))}function fW(e,t,n,r,i){let a=Math.min(r,i),o=Math.max(r,i);return t+(1-dW(o===a?.5:(e-a)/(o-a),0,1))*(n-t)}function pW(e,t,n,r){let i=e+t;return{bandTop:i-r/100*t,bandBottom:i-n/100*t}}function mW(e){return e.replace(/__(\d+|ref)$/,``)}function hW(e,t,n){let r=Math.floor((n-t-nW)/oW)+1;return Math.max(0,Math.min(e,r))}function gW(e){let t=0;for(let n of e)t+=n.length;return t}function _W(e,t){let n=e.cols.get(t);return n?new Float32Array(n):new Float32Array(e.length).fill(NaN)}function vW(e){let t=new Map;for(let n of e){let e=mW(n.column),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=new Set,r=[];for(let i of e){let e=mW(i.column);if(n.has(e))continue;n.add(e);let a=t.get(e);r.push({base:e,leader:a[0],members:a})}return r}function yW(e,t,n){let r=new Map,i=e.map((e,r)=>{let{bandTop:i}=pW(t,n,e.leader.bandFromPct,e.leader.bandToPct);return{g:e,i:r,bandTop:i,blockDY:e.members.length>1?nW+(e.members.length+1)*oW:iW}});i.sort((e,t)=>e.bandTop-t.bandTop||e.i-t.i);let a=-1/0;for(let{g:e,bandTop:t,blockDY:n}of i){let i=t+nW,o=Math.max(i,a),s=o-nW;r.set(e.leader.id,s),a=o+n}return r}function bW(e,t){let n=e.cols.get(t);if(!n)return 0;let r=e.x;return n.length===e.length&&j.has(n)?xW(r,e.length):CW(r,e.length,e=>Number.isFinite(n[e]))}function xW(e,t){let n=SW.get(e);return n===void 0&&(n=CW(e,t,()=>!0),SW.set(e,n)),n}var SW=t(new WeakMap);function CW(e,t,n){let r=null,i=0,a=0;for(let o=0;o<t;o++)n(o)&&(r!==null&&e[o]!==r&&(i+=Math.abs(e[o]-r),a++),r=e[o]);return a===0?0:i/a}function wW(e,t){return e>0?Math.max(e*4,t*1e-9):Math.max(t*1e-6,1e-12)}var TW=1e30,EW=250;function DW({xLabel:e,series:t,points:n,columnUnits:r={},height:i=440,onPlotContextMenu:a,backgroundToken:o=``,viewXRange:s=null,onViewXRangeChange:c,liveZoom:l,liveZoomId:u,fullXRange:d=null,shiftMode:f,xAxisLine:p,yAxisLine:m,gridLine:h,lineWidth:g=1,envelopes:_,showLatestValues:v=!1,liveSource:y,liveWindowSeconds:b=null,onLiveWindowChange:x,liveZoomMode:S,onPlotWidthCss:C,onCursorX:w}){let T=FU(),E=K(null),D=K(null),O=K(null),k=K(null),A=K(null),j=K(C);j.current=C;let M=K(-1),N=K(null),P=K(!1),F=K(null),I=K(!1),L=K(!1),R=K(null),z=K(null),B=K({pts:null,layers:[]}),V=K(new Map),ee=K([]),te=K(null),H=K(null),ne=K(null),re=K(null),ie=K(null),U=K(0),ae=K(0),oe=K(!1),se=K(0),ce=K(QU),le=K(y),ue=K(null),de=K(lU()),fe=K(0),pe=K(void 0),me=K(0),he=K(0),ge=K(16),_e=K(!0),ve=K(!1),[ye,be]=Ct(0),xe=()=>WH(A.current);function Se(){F.current?.dispose(),F.current=null,L.current=!1,I.current=!1,ee.current=[],be(e=>e+1)}W(()=>{ye&&xt()},[ye]),G(()=>{le.current=y,ue.current=null,B.current={pts:null,layers:[]},V.current.clear()},[y]);let Ce=K(b);G(()=>{Ce.current=b},[b]);let we=K(x);we.current=x;let Te=S??(x?`follow`:`free`),Ee=K(Te);Ee.current=Te;let De=K(null);G(()=>{De.current=null},[Te,e]);let Oe=K([]),ke=K(!1),Ae=K(0),je=K(0),Me=K(0),Ne=K(0),Pe=K(`none`),Fe=K(0),Ie=K(0),Le=K(0),Re=K(null),ze=K(null),Be=K(f),Ve=K(null),He=K({pts:null,x0:NaN,x1:NaN,ser:null}),Ue=K(0),We=K(0),Ge=K(null),Ke=K(null),qe=K(null),Je=K(null);G(()=>{Be.current=f},[f]),W(()=>(R.current&&=(clearTimeout(R.current),null),()=>{N.current?.dispose(),N.current=null;let e=F.current;e&&(R.current=setTimeout(()=>{e.dispose(),F.current===e&&(F.current=null),R.current=null},0))}),[]);let Ye=wt(eB,$z),Xe=K({xLabel:e,series:t,points:n,height:i,columnUnits:r,shiftMode:f,xAxisLine:p,yAxisLine:m,gridLine:h,lineWidth:g,showLatestValues:v,envelopes:_}),Ze=K(null),Qe=K(null);G(()=>{Xe.current={xLabel:e,series:t,points:n,height:i,columnUnits:r,shiftMode:f,xAxisLine:p,yAxisLine:m,gridLine:h,lineWidth:g,showLatestValues:v,envelopes:_}},[e,t,n,i,r,f,p,m,h,g,v,_]);let $e=K(c),et=K(w);et.current=w,G(()=>{$e.current=c},[c]);let tt=K(l),nt=K(u);G(()=>{tt.current=l,nt.current=u},[l,u]),W(()=>{if(!(!l||!u))return l.subscribe((e,t)=>{e!==u&&(te.current=t?.[0]??null,H.current=t?.[1]??null,xt())})},[l,u]);let rt=K(a);G(()=>{rt.current=a},[a]);let it=St(()=>{if(d&&d[1]>d[0])return{xmin:d[0],xmax:d[1]};let e=1/0,t=-1/0;for(let r of n)for(let n=0;n<r.length;n++){let i=r.x[n];i<e&&(e=i),i>t&&(t=i)}return(!Number.isFinite(e)||e===t)&&(--e,t+=1),{xmin:e,xmax:t}},[n,d]),at=K(it);G(()=>{at.current=it},[it]);function ot(){return le.current!=null&&te.current===null&&H.current===null&&!ke.current&&Ve.current===null}function st(){let{xmin:e,xmax:t}=at.current,n=te.current,r=H.current;if(n!==null&&r!==null&&r>n&&Number.isFinite(n)&&Number.isFinite(r))return{xmin:n,xmax:r};let i=ne.current,a=re.current;return ot()&&i!==null&&a!==null&&a>i&&Number.isFinite(i)&&Number.isFinite(a)?{xmin:i,xmax:a}:{xmin:e,xmax:t}}function ct(e,t){let n=le.current;if(!n?.latestValues)return nU(e,t);let r=n.latestValues(t),i=t.filter(e=>!r.has(e)),a=n.latestX?.();if(i.length>0&&a!=null)for(let[t,n]of tU(e,i,a))r.set(t,n);return r}function lt(){return le.current?Oe.current:Xe.current.points}function ut(e,t,n){let r=new Map;for(let i of t)r.set(i,wW(ht(e,i),n));return r}function dt(e){if(B.current.pts===e)return B.current.layers;let t=B.current.layers,n=le.current?.version?.(),r=e.map((e,r)=>({pts:e,key:t[r]?.pts===e?t[r].key:n??e}));return B.current={pts:e,layers:r},r}function ft(e,t){let n=V.current.get(e),r=performance.now(),i=n&&(n.key===t.key||typeof t.key==`number`&&typeof n.key==`number`&&r-n.at<EW);return(!n||!i)&&(n={key:t.key,at:r,has:new Map,median:new Map},V.current.set(e,n)),n}function pt(e,t,n){let r=ft(e,t),i=r.has.get(n);if(i===void 0){let e=t.pts.cols.get(n);i=!!e&&e.some(Number.isFinite),r.has.set(n,i)}return i}function mt(e,t){return dt(e).some((e,n)=>pt(n,e,t))}function ht(e,t){let n=dt(e);for(let e=0;e<n.length;e++){if(!pt(e,n[e],t))continue;let r=ft(e,n[e]),i=r.median.get(t);return i===void 0&&(i=bW(n[e].pts,t),r.median.set(t,i)),i}return 0}function gt(){if(Je.current)return Je.current;let e=A.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return Je.current=n,n}function _t(){let e=A.current,t=Math.max(1,e?.clientWidth||200),n=e?.clientHeight??0;return{w:t,h:Math.max(1,n>0?n:Xe.current.height)}}function vt(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function yt(){let e=E.current;if(!e)return;let{w:t,h:n}=_t(),r=vt(e,t,n);if(!r)return;{let e=lt(),t=st(),n=Xe.current.series,r=He.current;(r.pts!==e||r.x0!==t.xmin||r.x1!==t.xmax||r.ser!==n)&&(He.current={pts:e,x0:t.xmin,x1:t.xmax,ser:n},BH(A.current))}let i=YU(t),a=i===qU,{top:o,right:s,bottom:c}=i,l=i.left,u=t-l-s,d=n-o-c,{bg:f,muted:p,grid:m}=gt(),{xLabel:h,series:g,xAxisLine:_,yAxisLine:v,gridLine:y,lineWidth:b,columnUnits:x,showLatestValues:S}=Xe.current,C=lt();if(r.fillStyle=f,r.fillRect(0,0,t,n),gW(C)<2||u<=0||d<=0){if(r.fillStyle=p,r.font=`13px ${Q.sans}`,UV(r),N.current&&(N.current.resize(t,n,window.devicePixelRatio||1),N.current.draw([])),F.current){F.current.resize(t,n,window.devicePixelRatio||1);for(let e=0;e<ee.current.length;e++)F.current.clear(e);ee.current=[]}return}let{xmin:w,xmax:k}=st(),j=k-w,M=e=>l+(e-w)/j*u;T({left:l,top:o,width:u,height:d,x:{v0:w,v1:k}});let z=g.filter(e=>e.bandToPct>e.bandFromPct&&e.scaleMin!==e.scaleMax&&mt(C,e.column)),B=vW(z),V=yW(B,o,d),te=new Map;for(let e of B){let t=V.get(e.leader.id);t!==void 0&&e.members.forEach(e=>te.set(e.id,t))}let H=new Set,ne=new Set;for(let e of B)e.members.length>1&&e.members.forEach(e=>H.add(e.id)),ne.add(e.leader.id);let re=`11px ${Q.mono}`,ie=z.map(e=>{let{bandTop:t,bandBottom:n}=pW(o,d,e.bandFromPct,e.bandToPct),r=Math.min(e.scaleMin,e.scaleMax),i=Math.max(e.scaleMin,e.scaleMax),{majorStep:a,minorStep:s}=Iz(e.scaleMin,e.scaleMax,e.yMajorStep??0,e.yMinorStep??0),c=a,l=Lz(r,i,c);l.length>120&&(l=Lz(r,i,c=Iz(e.scaleMin,e.scaleMax,0,0).majorStep));let u=Rz(r,i,s,l);return u.length>400&&(u=[]),{s:e,bandTop:t,bandBottom:n,majors:l,minors:u,step:c}}),U=new Map,ae=0;{r.save(),r.font=re;let e=ie.filter(e=>ne.has(e.s.id));e.sort((e,t)=>{let n=Math.abs(e.s.bandToPct-e.s.bandFromPct),r=Math.abs(t.s.bandToPct-t.s.bandFromPct);return n===r?ie.indexOf(e)-ie.indexOf(t):r-n});let n=new Map,a=[];for(let t of e){let r=0;for(;r<e.length;r++){let e=a[r];if(!e||e.length===0||!e.some(e=>t.bandTop<e.bandBottom&&t.bandBottom>e.bandTop))break}n.set(t.s.id,r),a[r]||(a[r]=[]),a[r].push(t)}let o=new Map,c=new Map;for(let t of e){let e=0;for(let n of t.majors){let i=Vz(n,t.step),a=c.get(i);a===void 0&&c.set(i,a=r.measureText(i).width),a>e&&(e=a)}o.set(t.s.id,e)}let u=[],d=[],f=0;for(let e=0;e<a.length;e++){u[e]=f;let t=0;for(let n of a[e]??[]){let e=o.get(n.s.id)??0;e>t&&(t=e)}d[e]=t,f+=t+22}for(let e of ie){let t=n.get(e.s.id)??0;U.set(e.s.id,u[t]??0)}let p=i.left;for(let e=0;e<a.length;e++){let t=a[e];if(!t||t.length===0)continue;let n=(u[e]??0)+uW+lW+(d[e]??0)+6;n>p&&(p=n)}let m=Math.max(i.left,t-s-Math.max(120,t*.4)),h=Math.min(Math.ceil(p),m);h>l&&(ae=h-l),r.restore()}ae>0&&(l+=ae,u=Math.max(1,t-l-s)),ce.current=oU(u,window.devicePixelRatio||1);let oe=(e,t)=>1-(1-e)**t,se=new Map,le=new Map;for(let e of ie){let t=`${e.bandTop}|${e.bandBottom}|${e.s.scaleMin}|${e.s.scaleMax}|${e.majors.join(`,`)}`,n=se.get(t);n?n.k++:se.set(t,{c:e,k:1});let r=H.has(e.s.id)?p:e.s.color,i=`${e.bandTop}|${e.bandBottom}|${r}`,a=le.get(i);a?a.k++:le.set(i,{c:e,color:r,k:1})}if((v?.style??`dashed`)!==`none`)for(let{c:{s:e,bandTop:t,bandBottom:n,majors:i},k:a}of se.values()){r.save(),r.strokeStyle=v?.color??m,r.globalAlpha=oe(.1,a),r.lineWidth=v?.width??1,r.lineCap=`round`,r.setLineDash(UU(v?.style??`dashed`));for(let a of i){let i=fW(a,t,n,e.scaleMin,e.scaleMax);r.beginPath(),r.moveTo(l,i),r.lineTo(l+u,i),r.stroke()}r.restore()}for(let{c:{bandTop:e,bandBottom:t},color:n,k:i}of le.values())r.strokeStyle=n,r.lineWidth=1,r.setLineDash([]),r.globalAlpha=oe(.45,i),r.beginPath(),r.moveTo(l,e),r.lineTo(l,t),r.stroke(),r.globalAlpha=1;for(let{s:e,bandTop:t,bandBottom:n,majors:i,minors:o,step:s}of a?[]:ie){let a=H.has(e.id)?p:e.color;if(ne.has(e.id)){let c=U.get(e.id)??0,u=l-c-uW;r.strokeStyle=a,r.lineWidth=1;for(let i of o){let a=fW(i,t,n,e.scaleMin,e.scaleMax);r.beginPath(),r.moveTo(u-cW,a),r.lineTo(u,a),r.stroke()}r.font=re,r.textAlign=`right`,r.textBaseline=`middle`,r.strokeStyle=a,r.fillStyle=a;for(let a of i){let i=fW(a,t,n,e.scaleMin,e.scaleMax);r.beginPath(),r.moveTo(u-sW,i),r.lineTo(u,i),r.stroke(),r.fillText(Vz(a,s),u-lW,i)}}}if((y?.style??`solid`)!==`none`&&(r.strokeStyle=y?.color??m,r.lineWidth=y?.width??1,r.setLineDash(UU(y?.style??`solid`)),r.strokeRect(l,o,u,d),r.setLineDash([])),(_?.style??`dashed`)!==`none`){r.strokeStyle=_?.color??m,r.lineWidth=_?.width??1,r.setLineDash(UU(_?.style??`dashed`));for(let e=1;e<6;e++){let t=l+e/6*u;r.beginPath(),r.moveTo(t,o),r.lineTo(t,o+d),r.stroke()}r.setLineDash([])}let ue=o+d+10;r.fillStyle=p,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`;let de=Gz(h,w,w+j);for(let e=0;e<=(a?-1:6);e++){let t=w+e/6*j;r.fillText(de?tB(t,j/6,j):Vz(t,j/6),l+e/6*u,ue)}r.textBaseline=`bottom`,a||r.fillText(h,l+u/2,n-5);let{shiftMode:fe}=Xe.current;fe&&(r.globalAlpha=.8,r.font=`10px ${Q.sans}`,r.fillStyle=p,r.textAlign=`center`,r.textBaseline=`top`,r.fillText(`⇄ shifting: ${fe.label}`,l+u/2,o+3),r.globalAlpha=1);let me=Xe.current.envelopes;if(me?.length){r.save(),r.beginPath(),r.rect(l,o,u,d),r.clip();for(let e of me){let t=z.find(t=>t.id===e.seriesId||t.id.startsWith(`${e.seriesId}__`));if(!t)continue;let{bandTop:n,bandBottom:i}=pW(o,d,t.bandFromPct,t.bandToPct),a=e=>fW(e,n,i,t.scaleMin,t.scaleMax);r.fillStyle=e.color,r.globalAlpha=.2;let s=0;for(;s<e.x.length;){for(;s<e.x.length&&e.lo[s]!==e.lo[s];)s++;let t=s;for(;s<e.x.length&&e.lo[s]===e.lo[s];)s++;if(!(s-t<2)){r.beginPath(),r.moveTo(M(e.x[t]),a(e.hi[t]));for(let n=t+1;n<s;n++)r.lineTo(M(e.x[n]),a(e.hi[n]));for(let n=s-1;n>=t;n--)r.lineTo(M(e.x[n]),a(e.lo[n]));r.closePath(),r.fill()}}}r.restore()}R.current&&=(clearTimeout(R.current),null);let he=VU&&!I.current?F.current:null;if(VU&&!he&&!I.current&&D.current&&!L.current&&(he=DH()&&iH()?kH(D.current,1,Se,{hidden:xe,evict:Se},O.current??void 0):AH(D.current),he?(F.current=he,L.current=!0):I.current=!0),he){he.resize(t,n,window.devicePixelRatio||1);let e=`${l.toFixed(2)}|${u.toFixed(2)}|${o}|${d}|${b}|`+z.map(e=>`${e.id}:${e.column}:${e.bandFromPct}:${e.bandToPct}:${e.scaleMin}:${e.scaleMax}:${e.color}`).join(`,`),r=dt(C),i=ee.current;for(let t=0;t<Math.max(r.length,i.length);t++){let n=r[t];if(!n){i[t]&&he.clear(t),i[t]=null;continue}let a=z.filter(e=>pt(t,n,e.column)),s=a.map(e=>e.column).join(`
|
|
207
|
-
`),c=i[t];if(c&&c.pts===n.pts&&c.sig===e&&c.cols===s)continue;i[t]={pts:n.pts,sig:e,cols:s};let f={styles:a.map(e=>{let{bandTop:t,bandBottom:r}=pW(o,d,e.bandFromPct,e.bandToPct);return{color:qV(e.color),bandTop:t,bandBottom:r,scaleMin:e.scaleMin,scaleMax:e.scaleMax,gapMedian:n.pts.hold?TW:ht(C,e.column),width:b}}),left:l,plotW:u,xmin:w,xmax:k,cut:pe.current};if(c&&c.pts===n.pts&&c.cols===s){he.setStyle(t,f);continue}let p=n.pts,m=!!c&&c.pts.x===p.x&&c.pts.brk===p.brk&&c.cols===s;he.setData(t,{...f,xs:m?null:p.x.slice(),breaks:m?void 0:p.brk?.slice(),columns:a.map(e=>_W(p,e.column))})}i.length=r.length,he.setView(w,k,pe.current)}else{let e=N.current;BU&&!e&&!P.current&&D.current&&!L.current&&(e=$V(D.current),e?N.current=e:P.current=!0);let i=!!e;i&&e&&e.resize(t,n,window.devicePixelRatio||1);let a=[],s=ut(C,z.map(e=>e.column),j);for(let e of z){let{bandTop:t,bandBottom:n}=pW(o,d,e.bandFromPct,e.bandToPct),c=s.get(e.column);if(i){let r={x:l,y:t,w:u,h:n-t},i=qV(e.color),o=[],s=null,d=()=>{o.length>=4&&a.push({points:Float32Array.from(o),color:i,clip:r,width:b}),o=[]};for(let r of C){let i=r.cols.get(e.column);if(i){s=null;for(let a=0;a<r.length;a++){r.brk?.[a]&&d();let l=i[a];if(!Number.isFinite(l))continue;let u=r.x[a];s!==null&&!r.hold&&Math.abs(u-s)>c&&d(),o.push(M(u),fW(l,t,n,e.scaleMin,e.scaleMax)),s=u}d()}}d();continue}r.strokeStyle=e.color,r.lineWidth=b,r.lineJoin=`round`,r.lineCap=`round`,r.save(),r.beginPath(),r.rect(l,t,u,n-t),r.clip(),r.beginPath();let f=!1,p=null,m=!1;for(let i of C){let a=i.cols.get(e.column);if(a){m=!0;for(let o=0;o<i.length;o++){i.brk?.[o]&&(m=!0);let s=a[o];if(!Number.isFinite(s))continue;let l=i.x[o],u=M(l),d=fW(s,t,n,e.scaleMin,e.scaleMax);f?m||p!==null&&!i.hold&&Math.abs(l-p)>c?(r.stroke(),r.beginPath(),r.moveTo(u,d),p=l,m=!1):(r.lineTo(u,d),p=l):(r.moveTo(u,d),f=!0,p=l,m=!1)}}}f&&r.stroke(),r.restore()}i&&e&&e.draw(a)}for(let e of z){if(!e.alarm)continue;let{bandTop:t,bandBottom:n}=pW(o,d,e.bandFromPct,e.bandToPct),i=fW(e.alarm.value,t,n,e.scaleMin,e.scaleMax);r.save(),r.beginPath(),r.rect(l,t,u,n-t),r.clip(),r.strokeStyle=e.alarm.color,r.lineWidth=e.alarm.width,r.setLineDash(e.alarm.linked===`active`?LU:UU(e.alarm.style)),r.beginPath(),r.moveTo(l,i),r.lineTo(l+u,i),r.stroke(),r.setLineDash([]),e.alarm.linked&&zU(r,l+u-10-3,i-10-2,e.alarm.color),r.restore()}if(a)return;let ge=S?ct(C,z.map(e=>e.column)):null,_e=e=>{let t=ge?.get(e.column);if(typeof t!=`number`)return`-`;let n=x[e.column]?.trim()??``;return`${Hz(t)}${n?` ${n}`:``}`},ve=l+u+8;r.font=tW,r.textAlign=`left`;for(let e of B){let t=V.get(e.leader.id);if(t===void 0)continue;let i=e.members.length>1;if(r.fillStyle=i?p:e.leader.color,r.globalAlpha=1,r.fillText(e.base,ve,t+nW),i){let i=hW(e.members.length,t,n);for(let n=0;n<i;n++)r.fillStyle=e.members[n].color,r.globalAlpha=aW,r.fillText(_e(e.members[n]),ve,t+nW+(n+1)*oW)}else r.fillStyle=e.leader.color,r.globalAlpha=aW,r.fillText(_e(e.leader),ve,t+rW);r.globalAlpha=1}}function bt(){let e=k.current;if(!e)return;let{w:t,h:n}=_t(),r=vt(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let{top:i,right:a,bottom:o,left:s}=YU(t),c=t-s-a,l=n-i-o,{series:u,columnUnits:d,xLabel:f}=Xe.current,p=lt();if(ke.current&&c>0&&l>0){let e=Ae.current,t=je.current,n=Me.current,i=Ne.current,a=Math.min(e,n),o=Math.min(t,i),s=Math.abs(n-e),c=Math.abs(i-t);r.fillStyle=`rgba(59, 130, 246, 0.12)`,r.fillRect(a,o,s,c),r.strokeStyle=`rgba(59, 130, 246, 0.85)`,r.setLineDash([4,3]),r.lineWidth=1,r.strokeRect(a,o,s,c),r.setLineDash([])}let m=z.current;if(m===null||gW(p)<2||c<=0||l<=0)return;let{xmin:h,xmax:g}=st(),_=u.filter(e=>e.bandToPct>e.bandFromPct&&e.scaleMin!==e.scaleMax&&mt(p,e.column)),v=[...new Set(_.map(e=>e.column))],y=ut(p,v,g-h),{bg:b,muted:x}=gt();r.strokeStyle=x,r.globalAlpha=.5,r.lineWidth=1,r.beginPath(),r.moveTo(m,i),r.lineTo(m,i+l),r.stroke(),r.globalAlpha=1;let S=vW(_),C=yW(S,i,l),w=s+c+8;r.font=tW,r.textAlign=`left`;let T=$H(m,s,c,h,g),E=eU(p,T,v,y),D=e=>{let t=E.get(e.column);if(typeof t!=`number`)return`-`;let n=d[e.column]?.trim()??``;return`${Hz(t)}${n?` ${n}`:``}`};for(let e of S){let t=C.get(e.leader.id)??pW(i,l,e.leader.bandFromPct,e.leader.bandToPct).bandTop;if(e.members.length>1){let i=e.members.length*oW+4;r.fillStyle=b,r.fillRect(s+c+6,t+nW+2,a-8,i);let o=hW(e.members.length,t,n);for(let n=0;n<o;n++){let i=e.members[n];r.fillStyle=i.color,r.globalAlpha=aW,r.fillText(D(i),w,t+nW+(n+1)*oW)}}else{let n=e.leader;r.fillStyle=b,r.fillRect(s+c+6,t+nW+2,a-8,rW-nW+6),r.fillStyle=n.color,r.globalAlpha=aW,r.fillText(D(n),w,t+rW)}r.globalAlpha=1}let O=/^(.*?)\s*\(([^)]*)\)\s*$/.exec(f),A=O?O[1]:f,j=O?O[2].trim():``,M=Gz(f,h,g)?nB(T):``,N=M.lastIndexOf(` `),P=M?[`${A} ${M.slice(0,N)}`,M.slice(N+1)]:[`${A} ${Math.round(T)}${j}`];r.font=tW,r.textAlign=`left`,r.textBaseline=`alphabetic`,P.forEach((e,t)=>{let n=r.measureText(e).width,a=i+l-(P.length-1-t)*15;r.fillStyle=b,r.fillRect(w-2,a-11,n+6,15),r.fillStyle=x,r.globalAlpha=1,r.fillText(e,w,a)})}function xt(){if(le.current){oe.current=!0;return}Ge.current=()=>{yt(),bt()},!Ue.current&&(Ue.current=LH(e=>{Ue.current=0,!xe()&&(Ke.current=e,Ge.current?.())}))}function Tt(){if(le.current){oe.current=!0;return}let e=A.current?.ownerDocument.timeline?.currentTime;if(typeof e!=`number`||e===Ke.current){xt();return}Ke.current=e,RH(Ue.current),Ue.current=0,yt(),bt()}function Et(){qe.current=bt,!We.current&&(We.current=LH(()=>{We.current=0,qe.current?.()}))}function Dt(e){U.current=LH(Dt);let t=le.current;if(!t)return;ge.current+=(Math.min(50,he.current?e-he.current:16)-ge.current)*.1,he.current=e;let n=A.current;if(!(_e.current&&!WH(n))){if(!ve.current){ve.current=!0;let e=F.current;e&&(ee.current.forEach((t,n)=>{t&&e.clear(n)}),ee.current=[],e.resize(1,1,1))}return}if(ve.current&&(ve.current=!1,F.current&&!F.current.own&&DH()&&iH())){Se();return}if(me.current&&e-me.current<eW-ge.current/2||!XH(e,me.current||-1/0))return;me.current=e;let r=performance.now(),i=t.xBounds();i&&i[1]>i[0]&&(at.current={xmin:i[0],xmax:i[1]});let a=fe.current?e-fe.current:16;fe.current=e,a>250&&(ne.current=null,re.current=null);let o=t.latestT?.(),s,c;if(o!==void 0&&t.xAtTime&&Number.isFinite(o)){let e=t.id?dU(t.id,o,performance.now(),t.timeAfter):TU(de.current,o,a,t.timeAfter),n=t.id?gU(t.id):pU(de.current),r=_U(t.xAtTime,e,n);Number.isFinite(r)&&(s=r);let i=_U(t.xAtTime,e,n-(t.id?hU(t.id):mU(de.current)));Number.isFinite(i)&&(c=i)}if(ot()){let n=s??t.latestX?.()??at.current.xmax,r=Ce.current,i=r!=null&&t.spanForSeconds?t.spanForSeconds(r):r??De.current,[a,o]=aU(at.current.xmin,at.current.xmax,i,n??void 0);if(!t.spanForSeconds&&s!==void 0&&s>a&&(o=s),Number.isFinite(a)&&Number.isFinite(o)&&o>a){let t=o-a,n=re.current!==null&&o<re.current-t;if(ne.current===null||re.current===null||n)ne.current=a,re.current=o,ae.current=e;else{let n=ae.current;ae.current=e;let r=ie.current,i=rU(n?Math.min(64,e-n):16,XU);ne.current=iU(ne.current,a,r?r[0]:null,i,t,ZU),re.current=iU(re.current,o,r?r[1]:null,i,t,ZU),Math.abs(a-ne.current)<t*1e-6&&(ne.current=a),Math.abs(o-re.current)<t*1e-6&&(re.current=o)}ie.current=[a,o]}}else ne.current=null,re.current=null,ae.current=0;let l=st(),u=t.version?.(),d=ce.current,f=ue.current,p=f!==null&&u!==void 0&&f.ver===u&&f.x0===l.xmin&&f.x1===l.xmax&&f.mp===d&&f.cut===c;(gW(Oe.current)===0||!p&&e-se.current>=$U)&&(se.current=e,pe.current=t.cutOnGpu&&F.current?c:void 0,Oe.current=t.pull(l.xmin,l.xmax,d,c,pe.current!==void 0),ue.current=u===void 0?null:{ver:u,x0:l.xmin,x1:l.xmax,mp:d,cut:c}),oe.current=!1,yt(),bt(),ZH(e,performance.now()-r)}function kt(){U.current||=(ae.current=0,LH(Dt))}function At(){U.current&&(RH(U.current),U.current=0,fe.current=0,ne.current=null,re.current=null,Oe.current=[],pe.current=void 0)}W(()=>{let e=A.current,t=e?.ownerDocument.defaultView?.IntersectionObserver;if(!e||!t)return;let n=new t(e=>{let t=e[e.length-1];(t.isIntersecting||t.boundingClientRect.width>0)&&(_e.current=t.isIntersecting)});return n.observe(e),()=>{n.disconnect(),_e.current=!0}},[]),W(()=>(y?kt():(At(),xt()),At),[!!y]),W(()=>uB(A.current,()=>{Je.current=null,xt()}),[]),W(()=>{Je.current=null,xt()},[o]);let jt=!!f;W(()=>{let e=k.current;e&&(e.style.cursor=jt?`ew-resize`:``),xt()},[jt,f?.label??``]);let Mt=s?.[0]??null,Nt=s?.[1]??null;return G(()=>{te.current===Mt&&H.current===Nt||(te.current=Mt,H.current=Nt,xt())},[Mt,Nt]),W(()=>{Tt()},[t,n,i,e,p,m,h,g,v,Ye]),W(()=>()=>{RH(Ue.current),RH(We.current),Ue.current=0,We.current=0},[]),W(()=>{let e=k.current,t=A.current;if(!e||!t)return;let n=()=>{let e=Math.round(t.clientWidth);e>0&&e!==M.current&&(M.current=e,j.current?.(e))};n();let r=new UH(()=>{Je.current=null,n(),xt()});r.observe(t);let i=QH(e=>et.current?.(e)),a=t=>{if(ke.current||Ve.current!==null)return;if(gW(lt())<2){z.current!==null&&(z.current=null,Et(),i.set(null));return}let n=e.getBoundingClientRect(),r=t.clientX-n.left,a=t.clientY-n.top,{left:o,top:s,right:c,bottom:l}=YU(n.width),u=Math.max(1,n.width-o-c),d=n.height-s-l;if(r<o||r>o+u||a<s||a>s+d){z.current!==null&&(z.current=null,Et(),i.set(null));return}z.current!==r&&(z.current=r,Et());let{xmin:f,xmax:p}=st();i.set($H(r,o,u,f,p))},o=()=>{z.current!==null&&(z.current=null,Et()),i.set(null)},s=e=>{Ze.current&&clearTimeout(Ze.current),Ze.current=setTimeout(()=>{Ze.current=null,$e.current?.(e)},HU)},c=t=>{if(Pe.current!==`none`||t.buttons&2||Date.now()-Le.current<300||gW(lt())<2)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,{top:a,left:o,right:c,bottom:l}=YU(n.width),u=Math.max(1,n.width-o-c),d=Math.max(1,n.height-a-l);if(r<o||r>o+u||i<a||i>a+d)return;t.preventDefault();let f=at.current,p=f.xmax-f.xmin;if(!(p>0))return;if(Ee.current===`follow`&&ot()&&!we.current){De.current=cU(De.current,p,t.deltaY<0,p*.001);return}if(Ee.current===`follow`&&ot()){let e=cU(Ce.current,le.current?.bufferedSeconds?.()??p,t.deltaY<0);Ce.current=e,Qe.current&&clearTimeout(Qe.current),Qe.current=setTimeout(()=>{Qe.current=null,we.current?.(e)},HU);return}let m=te.current??f.xmin,h=(H.current??f.xmax)-m;if(!(h>0))return;let g=Date.now();g-Ie.current>300&&(Re.current=te.current,ze.current=H.current),Ie.current=g;let _=m+(r-o)/u*h,v=t.deltaY<0,y=.88,b=v?h*y:h/y,x=Math.max(p*1e-7,1e-12);if(v)b=Math.max(b,x);else{if(b>=p*.999){te.current=null,H.current=null,s(null),tt.current?.publish(nt.current??``,null),xt();return}b=Math.min(b,p)}let S=(_-m)/h,C=_-S*b,w=_+(1-S)*b;C<f.xmin&&(w+=f.xmin-C,C=f.xmin),w>f.xmax&&(C-=w-f.xmax,w=f.xmax),w-C<b-1e-12&&(C=Math.max(f.xmin,_-b/2),w=C+b,w>f.xmax&&(w=f.xmax,C=w-b)),w-C>=p*.999?(te.current=null,H.current=null,s(null),tt.current?.publish(nt.current??``,null)):(te.current=C,H.current=w,s([C,w]),tt.current?.publish(nt.current??``,[C,w])),xt()},l=e=>{if(e.preventDefault(),Le.current=Date.now(),Date.now()-Ie.current<300){te.current=Re.current,H.current=ze.current;let e=Re.current,t=ze.current;Ze.current&&=(clearTimeout(Ze.current),null),$e.current?.(e===null&&t===null?null:[e,t]),Ie.current=0,xt()}},u=t=>{if(t.button===0&&Be.current){let n=e.getBoundingClientRect(),{left:r,top:i,right:a,bottom:o}=YU(n.width),s=Math.max(1,n.width-r-a),c=n.height-i-o,l=t.clientX-n.left,u=t.clientY-n.top;if(l>=r&&l<=r+s&&u>=i&&u<=i+c){Ve.current=t.clientX,Be.current.onDragStart();try{e.setPointerCapture(t.pointerId)}catch{}}return}if(t.button!==2)return;if(t.preventDefault(),t.buttons===0){rt.current?.({clientX:t.clientX,clientY:t.clientY});return}if(Pe.current!==`none`){ke.current=!1,Pe.current=`none`;try{e.releasePointerCapture(t.pointerId)}catch{}}let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top;Fe.current=Date.now(),Pe.current=`menuOnly`,ke.current=!1,Ae.current=r,je.current=i,Me.current=r,Ne.current=i;try{e.setPointerCapture(t.pointerId)}catch{}},d=t=>{if(Ve.current!==null){let n=t.clientX-Ve.current,r=e.getBoundingClientRect(),{left:i,right:a}=YU(r.width),o=Math.max(1,r.width-i-a),{xmin:s,xmax:c}=st(),l=c-s;l>0&&o>0&&Be.current?.onDragOffset(n/o*l);return}if(Pe.current===`none`)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top;if(Pe.current===`menuOnly`){if(Date.now()-Fe.current<150)return;let e=r-Ae.current,t=i-je.current;if(Math.sqrt(e*e+t*t)<12)return;let a=lt(),{top:o,left:s,right:c,bottom:l}=YU(n.width),u=n.width-s-c,d=n.height-o-l,f=u>0&&d>0&&Ae.current>=s&&Ae.current<=s+u&&je.current>=o&&je.current<=o+d;if(gW(a)<2||!f)return;Pe.current=`rubber`,ke.current=!0,z.current=null}Pe.current===`rubber`&&(t.preventDefault(),Me.current=r,Ne.current=i,Et())},f=t=>{if(t.button!==2)return;t.preventDefault();let n=Pe.current;Pe.current=`none`;try{e.releasePointerCapture(t.pointerId)}catch{}if(n===`menuOnly`){ke.current=!1,Et(),rt.current?.({clientX:t.clientX,clientY:t.clientY});return}if(n!==`rubber`||!ke.current){ke.current=!1,Et();return}ke.current=!1;let r=lt(),i=e.getBoundingClientRect(),{left:a,right:o}=YU(i.width),s=Math.max(1,i.width-a-o),c=Ae.current,l=Me.current,u=Math.abs(l-c);if(gW(r)<2||u<12){rt.current?.({clientX:t.clientX,clientY:t.clientY}),Et();return}let d=dW(Math.min(c,l),a,a+s),f=dW(Math.max(c,l),a,a+s),{xmin:p,xmax:m}=st(),h=m-p;if(!(h>0)){rt.current?.({clientX:t.clientX,clientY:t.clientY}),Et();return}let g=p+(d-a)/s*h,_=p+(f-a)/s*h;if(g>_){let e=g;g=_,_=e}let v=at.current,y=Math.min(v.xmin,v.xmax),b=Math.max(v.xmin,v.xmax);g=dW(g,y,b),_=dW(_,y,b);let x=_-g;if(x<=(b-y)*1e-12||x<=0){rt.current?.({clientX:t.clientX,clientY:t.clientY}),Et();return}rt.current?.({clientX:t.clientX,clientY:t.clientY,zoomXRange:[g,_]}),Et()},p=t=>{if(t.button===0&&Ve.current!==null){Ve.current=null;try{e.releasePointerCapture(t.pointerId)}catch{}return}if(t.button===2){f(t);return}if(t.buttons===0&&Pe.current!==`none`){Pe.current=`none`,ke.current=!1;try{e.releasePointerCapture(t.pointerId)}catch{}rt.current?.({clientX:t.clientX,clientY:t.clientY}),Et()}},m=t=>{Ve.current!==null&&(Ve.current=null),Pe.current!==`none`&&(ke.current=!1,Pe.current=`none`);try{e.releasePointerCapture(t.pointerId)}catch{}Et()},h=t=>{if(t.button!==0||gW(lt())<2)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,{top:a,left:o,right:s,bottom:c}=YU(n.width),l=Math.max(1,n.width-o-s),u=Math.max(1,n.height-a-c);r<o||r>o+l||i<a||i>a+u||te.current===null&&H.current===null||(te.current=null,H.current=null,Ze.current&&=(clearTimeout(Ze.current),null),$e.current?.(null),tt.current?.publish(nt.current??``,null),xt(),Et())},g=e=>{if(e.key!==`Escape`)return;let t=!1;Pe.current!==`none`&&(Pe.current=`none`,ke.current=!1,t=!0),Ve.current!==null&&(Ve.current=null,t=!0),t&&Et()};e.addEventListener(`mousemove`,a),e.addEventListener(`mouseleave`,o),e.addEventListener(`wheel`,c,{passive:!1}),e.addEventListener(`contextmenu`,l),e.addEventListener(`pointerdown`,u),e.addEventListener(`pointermove`,d),e.addEventListener(`pointerup`,p),e.addEventListener(`pointercancel`,m),e.addEventListener(`dblclick`,h);let _=e.ownerDocument.defaultView??window;return _.addEventListener(`keydown`,g),()=>{r.disconnect(),e.removeEventListener(`mousemove`,a),e.removeEventListener(`mouseleave`,o),e.removeEventListener(`wheel`,c),e.removeEventListener(`contextmenu`,l),e.removeEventListener(`pointerdown`,u),e.removeEventListener(`pointermove`,d),e.removeEventListener(`pointerup`,p),e.removeEventListener(`pointercancel`,m),e.removeEventListener(`dblclick`,h),_.removeEventListener(`keydown`,g),Ze.current&&clearTimeout(Ze.current),Qe.current&&clearTimeout(Qe.current)}},[]),Ot(`div`,{ref:A,className:`chart-canvas-wrap`,children:[q(`canvas`,{ref:E,className:`chart-canvas`,role:`img`,"aria-label":`Chart of ${e}`}),q(`canvas`,{ref:O,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:D,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}},ye),q(`canvas`,{ref:k,className:`chart-canvas chart-overlay`})]})}function OW(){try{if(localStorage.getItem(`perfLog`)===`1`)return!0;if(localStorage.getItem(`perfLog`)===`0`)return!1}catch{}return!1}var kW=!1;function AW(){let e=OW();return e&&!kW&&(kW=!0,console.log(`[perf] logging enabled — zoom an out-of-core chart to see decimate()/sampleRows timings`)),e}AW();var jW=new Map;function MW(e,t){let n=(jW.get(e)??0)+1;jW.set(e,n),console.log(`[perf] ${e} #${n} ${t.toFixed(1)}ms`)}async function NW(e,t){if(!AW())return t();let n=performance.now();try{return await t()}finally{MW(e,performance.now()-n)}}var PW=20;async function FW(e,t,n,r){let{x0:a,bucket:o,rows:s,columns:c}=await NW(`decimate(${t.length}col)`,()=>e.getSeriesMulti(t,n,r));return i(s,c,a,o)}function IW(e,t,n,r,a=0,o=!1,s=0){let[c,l]=Ct({points:C,fetchedViewport:null}),[u,d]=Ct(!1),f=`${t.join(`,`)}|${n?`${n.xKey}:${n.x0}:${n.x1}`:`none`}|${r}|${a}`,p=St(()=>{if(!o||!e?.getSeriesMultiSync||!n||t.length===0)return null;let a=s>0?e.getColumnsSync?.(t,n,s):null;if(a)return{points:a,loading:!1,fetchedViewport:n,full:!0};let c=e.getSeriesMultiSync(t,n,r);return{points:i(c.rows,c.columns,c.x0,c.bucket),loading:!1,fetchedViewport:n}},[o,e,f,s]);return W(()=>{if(o)return;if(!e||!n||t.length===0){l({points:C,fetchedViewport:null});return}let i=!0;d(!0);let a=setTimeout(()=>{FW(e,t,n,r).then(t=>{i&&(l({points:t,fetchedViewport:n,source:e}),d(!1))}).catch(()=>{i&&d(!1)})},PW);return()=>{i=!1,clearTimeout(a)}},[e,f,o]),p||(c.source!==void 0&&c.source!==e?{points:C,loading:u,fetchedViewport:null}:{points:c.points,loading:u,fetchedViewport:c.fetchedViewport})}var LW=250,RW=2,zW=6e3,BW=2e6,VW=[];function HW(e,t,n,r,i,a){let o=!!e&&e.columnSet.has(n),s=St(()=>e&&o?t.filter(t=>e.columnSet.has(t)):VW,[e,o,t]),c=e&&o&&s.length>0?e.source:null,l=!!c&&!e?.live&&!!c.getSeriesMultiSync&&!!c.xBoundsSync,u=St(()=>l&&c?c.xBoundsSync(n):null,[l,c,n]),[d,f]=Ct(null),p=!!e?.live;W(()=>{if(!c||l)return;let e=!0,t=()=>c.xBounds(n).then(t=>{let r=c.version?.()??0;e&&f(e=>e&&e.source===c&&e.xKey===n&&e.ver===r?e:{source:c,xKey:n,b:t,ver:r})}).catch(()=>{});t();let r=p?setInterval(t,LW):void 0;return()=>{e=!1,clearInterval(r)}},[c,n,p,l]);let m=d&&d.source===c&&d.xKey===n?d:null,h=u??m?.b??null,_=m?.ver??0,{points:v,loading:y,full:x}=IW(c,s,c&&h&&h.x1>h.x0?{xKey:n,x0:h.x0,x1:h.x1}:null,Math.min(zW,i*RW),_,l,a),S=e?.xOffset??0,w=r&&r[1]>r[0]?r[0]-S:null,T=r&&r[1]>r[0]?r[1]-S:null,E=x||!!h&&w!==null&&T!==null&&w<=h.x0&&T>=h.x1,{points:D,fetchedViewport:O}=IW(c,s,c&&w!==null&&T!==null&&!E?{xKey:n,x0:w,x1:T}:null,i,_,l,a),k=St(()=>!O||D.length===0?v:g([b(v,e=>e<O.x0),D,b(v,e=>e>O.x1)]),[v,D,O]),A=!!c&&(h===null||y);return St(()=>e?{points:R(k,e.keySuffix,e.xOffset),bounds:h?{x0:h.x0+e.xOffset,x1:h.x1+e.xOffset}:null,loading:A}:{points:C,bounds:null,loading:!1},[e,k,h,A])}var UW=new WeakMap,WW=0;function GW(e){if(e.key!==void 0)return e.key;let t=UW.get(e.source);return t===void 0&&UW.set(e.source,t=WW++),`${t}${e.keySuffix}`}function KW(){let[e,t]=Ct(()=>new Map);return[e,yt((e,n)=>t(t=>{if(n?t.get(e)===n:!t.has(e))return t;let r=new Map(t);return n?r.set(e,n):r.delete(e),r}),[])]}var qW=_t(function({id:e,layer:t,columns:n,xKey:r,view:i,mp:a,rawLimit:o,report:s}){let c=HW(t,n,r,i,a,o);return G(()=>{s(e,c)},[e,c,s]),G(()=>()=>s(e,null),[e,s]),null});function JW({layers:e,xKey:t,columns:n,maxPoints:r,...i}){let a=i.viewXRange??null,[o,s]=Ct(null),c=typeof window<`u`?Math.min(3,Math.max(1,window.devicePixelRatio||1)):1,l=o==null?r:Math.min(r,Math.round(o*c/50)*50),u=Math.max(1e3,Math.round(l/Math.sqrt(Math.max(1,e.length)))),d=Math.floor(BW/Math.max(1,e.length)),[f,p]=KW(),m=St(()=>e.map(GW),[e]),h=St(()=>m.map(e=>f.get(e)),[m,f]),g=St(()=>h.flatMap(e=>e&&e.points.length>0?[e.points]:[]),[h]),_=St(()=>{let e=1/0,t=-1/0;for(let n of h){let r=n?.bounds;r&&(e=Math.min(e,r.x0),t=Math.max(t,r.x1))}return Number.isFinite(e)&&t>e?[e,t]:null},[h]),v=h.some(e=>!e||e.loading);return Ot(Dt,{children:[e.map((e,r)=>q(qW,{id:m[r],layer:e,columns:n,xKey:t,view:a,mp:u,rawLimit:d,report:p},m[r])),g.length===0?Ot(`div`,{className:`chart-placeholder chart-placeholder--no-data`,onContextMenu:e=>{e.preventDefault(),i.onPlotContextMenu?.({clientX:e.clientX,clientY:e.clientY})},children:[q(`span`,{className:`content-empty-icon`,"aria-hidden":!0}),q(`h2`,{children:v?`Loading…`:`No data to plot`}),v?null:q(`p`,{children:`None of the selected datasets has this X column together with a plotted channel.`})]}):q(DW,{points:g,fullXRange:_,...i,onPlotWidthCss:s})]})}function YW(e){return!!e&&!Array.isArray(e)&&typeof e.length==`number`&&`x`in e&&`y`in e}function XW(e){let t=e.length,n=new Float64Array(t),r=new Float64Array(t),i=t>0&&e[0].c!==void 0?new Float32Array(t):void 0,a=e.some(e=>e.d!==void 0)?new Uint8Array(t):void 0;for(let o=0;o<t;o++){let t=e[o];n[o]=t.x,r[o]=t.y,i&&(i[o]=t.c??0),a&&(a[o]=t.d??0)}return{length:t,x:n,y:r,c:i,d:a}}function ZW(e,t,n){let r=n?.get(t);if(r)return r;let i=ve(e);if(i)return pe(i,t);if(e.length===0||!(t in e[0]))return;let a=new Float64Array(e.length);for(let n=0;n<e.length;n++){let r=e[n][t];a[n]=typeof r==`number`?r:NaN}return a}function QW(e,t,n){let r=ZW(e,t,n);if(!r||j.has(r))return r;let i=0;for(let e=0;e<r.length;e++)r[e]-r[e]===0&&i++;if(i===r.length)return r;let a=new Float64Array(i);for(let e=0,t=0;e<r.length;e++)r[e]-r[e]===0&&(a[t++]=r[e]);return a}function $W(e,t,n,r){if(!n){let n=QW(e,t,r);return n?[{label:t,values:n}]:[]}let i=ZW(e,t,r);if(!i)return[];let a=i.length,o=r?.has(n)||e.length>0&&typeof e[0][n]==`number`?ZW(e,n,r):void 0,s=t=>{if(o){let e=o[t];return e===e?String(e):`unknown`}return String(e[t]?.[n]??`unknown`)},c=new Map,l=[],u=new Int32Array(a),d=[];for(let e=0;e<a;e++){if(i[e]-i[e]!==0){u[e]=-1;continue}let t=s(e),n=c.get(t);n===void 0&&(c.set(t,n=l.length),l.push(t),d.push(0)),u[e]=n,d[n]++}let f=l.map((e,t)=>({label:e,values:new Float64Array(d[t])})),p=new Int32Array(l.length);for(let e=0;e<a;e++){let t=u[e];t>=0&&(f[t].values[p[t]++]=i[e])}return f}function eG(e){let t=NaN,n=NaN,r=0;for(let i=0;i<e.length;i++){let a=e[i];a-a===0&&(r===0&&(t=a),n=a,r++)}let i=n-t;return r>1&&i>0?(r-1)/i:null}function tG(e,t,n){let r=0;for(let i=0;i<e.length;i++)e[i]>=t&&e[i]<=n&&r++;let i=new Uint32Array(r),a=0;for(let r=0;r<e.length;r++)e[r]>=t&&e[r]<=n&&(i[a++]=r);return i}function nG(e,t){let n=new Float64Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n}function rG(e,t,n,r){let i=ZW(e.rows,t,e.full),a=ZW(e.rows,n,e.full);if(!i||!a)return null;let o=r.colorCol?ZW(e.rows,r.colorCol,e.full):void 0;if(r.viewXRange){let t=ZW(e.rows,r.xKey,e.full);if(t){let e=tG(t,r.viewXRange[0],r.viewXRange[1]);i=nG(i,e),a=nG(a,e),o&&=nG(o,e)}}let s=Math.min(i.length,a.length);if(!o)return{cols:{length:s,x:i,y:a}};let c=1/0,l=-1/0;for(let e=0;e<s;e++){let t=o[e];t<c&&(c=t),t>l&&(l=t)}if(!(l>c))return{cols:{length:s,x:i,y:a}};let u=new Float32Array(s),d=l-c;for(let e=0;e<s;e++){let t=o[e];u[e]=t===t?(t-c)/d:0}return{cols:{length:s,x:i,y:a,c:u},color:{label:r.colorCol,min:c,max:l}}}function iG(e,t,n,r){let i=[],a=[];e.forEach((e,o)=>{a.push(iB(r.colorOverrides,e.id,o,r.palette));let s=rG(e,t,n,{xKey:r.xKey,viewXRange:r.viewXRange});i.push(s?.cols??{length:0,x:[],y:[]})});let o=i.reduce((e,t)=>e+t.length,0),s=new Float64Array(o),c=new Float64Array(o),l=new Uint8Array(o),u=0;return i.forEach((e,t)=>{for(let t=0;t<e.length;t++)s[u+t]=e.x[t],c[u+t]=e.y[t];l.fill(Math.min(t,255),u,u+e.length),u+=e.length}),{cols:{length:o,x:s,y:c,d:l},colors:a}}var aG=e=>YW(e)?e:XW(e),oG=(e,t,n)=>t===t&&n===n&&(!e||t>=e.xmin&&t<=e.xmax&&n>=e.ymin&&n<=e.ymax);function sG(e,t,n){let r=t+1,i=Array.from({length:r},()=>Array(r).fill(0)),a=Array(r).fill(0),o=new Float64Array(2*r-1),s=0;for(let t=0;t<e.length;t++){let c=e.x[t],l=e.y[t];if(oG(n,c,l)){s++,o[0]=1;for(let e=1;e<o.length;e++)o[e]=o[e-1]*c;for(let e=0;e<r;e++){for(let t=0;t<r;t++)i[e][t]+=o[e+t];a[e]+=o[e]*l}}}if(s<r)return null;let c=i.map((e,t)=>[...e,a[t]]);for(let e=0;e<r;e++){let t=e;for(let n=e+1;n<r;n++)Math.abs(c[n][e])>Math.abs(c[t][e])&&(t=n);if([c[e],c[t]]=[c[t],c[e]],Math.abs(c[e][e])<1e-10)return null;let n=c[e][e];for(let t=e;t<=r;t++)c[e][t]/=n;for(let t=0;t<r;t++){if(t===e)continue;let n=c[t][e];for(let i=e;i<=r;i++)c[t][i]-=n*c[e][i]}}return c.map(e=>e[r])}function cG(e,t,n){return sG(aG(e),t,n)}function lG(e,t){let n=aG(e),r=0,i=0;for(let e=0;e<n.length;e++)oG(void 0,n.x[e],n.y[e])&&(r++,i+=n.y[e]);if(r===0)return 0;let a=i/r,o=0,s=0;for(let e=0;e<n.length;e++){let r=n.x[e],i=n.y[e];if(!oG(void 0,r,i))continue;let c=0;for(let e=t.length-1;e>=0;e--)c=c*r+t[e];o+=(i-a)**2,s+=(i-c)**2}return o<1e-15?1:Math.max(0,1-s/o)}function uG(e,t=4){if(!Number.isFinite(e))return`?`;let n=Math.abs(e);return n===0?`0`:n>=1e5||n>0&&n<.001?e.toExponential(2):e.toPrecision(t).replace(/\.?0+$/,``)}function dG(e,t,n){let r=[];for(let n=e.length-1;n>=0;n--){let i=e[n];n===0?r.push(uG(i)):n===1?r.push(`${uG(i)}·${t}`):r.push(`${uG(i)}·${t}${n>1?`^${n}`:``}`)}return`${n} = ${r.join(` + `).replace(/\+ -/g,`− `)}`}var fG=[[0,45,80,160],[.25,40,145,175],[.5,60,180,110],[.75,220,175,55],[1,210,75,55]];function pG(e){let t=0;for(let n=1;n<fG.length;n++){if(e<=fG[n][0]){t=n-1;break}n===fG.length-1&&(t=n-1)}let n=t+1,r=(e-fG[t][0])/(fG[n][0]-fG[t][0]);return{r:Math.round(fG[t][1]+r*(fG[n][1]-fG[t][1])),g:Math.round(fG[t][2]+r*(fG[n][2]-fG[t][2])),b:Math.round(fG[t][3]+r*(fG[n][3]-fG[t][3]))}}function mG(e){let{r:t,g:n,b:r}=pG(e);return`rgb(${t},${n},${r})`}function hG(e,t){if(!Number.isFinite(e))return 0;let n=Math.floor(e*t);return n<0?0:n>=t?t-1:n}var gG=`#version 300 es
|
|
206
|
+
}`;function hH(e,t,n,r){let i=e.length,a=0;for(let t=0;t<i;t++)Number.isFinite(r[t])&&Number.isFinite(e[t])&&a++;if(a===i)return null;let o=new Float32Array(a),s=new Float32Array(a),c=new Uint8Array(a),l=0,u=!1;for(let a=0;a<i;a++)n[a]&&(u=!0),Number.isFinite(r[a])&&Number.isFinite(e[a])&&(o[l]=t[a],s[l]=r[a],u&&=(c[l]=255,!1),l++);return{x:o,y:s,starts:c}}function gH(e,t,n){let r=e.length,i=0;for(let t=0;t<r;t++)if(Number.isFinite(e[t])){i=e[t];break}let a=new Float32Array(r);for(let t=0;t<r;t++)a[t]=e[t]-i;let o=new Uint8Array(r);if(t)for(let e=0;e<r;e++)t[e]&&(o[e]=255);let s=n.map(t=>hH(e,a,o,t)??{x:a,y:t,starts:o}),c=s.map(e=>e.y.length),l=c.reduce((e,t)=>e+t,0),u=new Float32Array(l),d=new Float32Array(l),f=new Uint8Array(l),p=new Float32Array(l),m=0;return s.forEach((e,t)=>{u.set(e.x,m),d.set(e.y,m),f.set(e.starts,m),e.y.length>0&&(f[m]=255),p.fill(t,m,m+e.y.length),m+=e.y.length}),{origin:i,x:u,y:d,starts:f,sid:p,counts:c}}function _H(e,t,n,r,i,a){let o=(i-r)/a,s=(t,n)=>{let r=0,i=e.length;for(;r<i;){let a=r+i>>>1;(n?e[a]<=t:e[a]<t)?r=a+1:i=a}return r},c=s(r,!1),l=s(i,!0),u=t.length*(2*a+2),d=new Float32Array(u),f=new Float32Array(u),p=new Uint8Array(u),m=new Float32Array(u),h=0,g=(e,t,r)=>{d[h]=e-n,f[h]=t,m[h]=r,h++};return t.forEach((t,n)=>{let i=h;for(let r=c-1;r>=Math.max(0,c-64);r--)if(t[r]===t[r]){g(e[r],t[r],n);break}let s=c;for(let i=0;i<a&&s<l;i++){let c=i===a-1?1/0:r+(i+1)*o,u=1/0,d=-1/0,f=-1,p=-1;for(;s<l&&e[s]<c;s++){let e=t[s];e<u&&(u=e,f=s),e>d&&(d=e,p=s)}f<0||(f===p?g(e[f],u,n):f<p?(g(e[f],u,n),g(e[p],d,n)):(g(e[p],d,n),g(e[f],u,n)))}for(let r=l;r<Math.min(e.length,l+64);r++)if(t[r]===t[r]){g(e[r],t[r],n);break}h>i&&(p[i]=255)}),{x:d.subarray(0,h),y:f.subarray(0,h),starts:p.subarray(0,h),sid:m.subarray(0,h),bucket:o}}function vH(e){for(let t=1;t<e.length;t++)if(!(e[t]>=e[t-1]))return!1;return e.length===0||e[0]===e[0]}function yH(e,t=1){let n=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0}),r=typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas;if(!n)return null;let i=()=>{let e=QV(n,n.VERTEX_SHADER,pH),t=QV(n,n.FRAGMENT_SHADER,mH);if(!e||!t)return null;let r=n.createProgram();return r?(n.attachShader(r,e),n.attachShader(r,t),n.linkProgram(r),n.getProgramParameter(r,n.LINK_STATUS)?{prog:r,vs:e,fs:t}:(console.error(`glSeries program link failed:`,n.getProgramInfoLog(r)),null)):null},a=r?i():uH(n,`glSeries`,i);if(!a)return null;let{prog:o,vs:s,fs:c}=a,l=e=>n.getAttribLocation(o,e),u=l(`a_corner`),d=l(`a_ax`),f=l(`a_bx`),p=l(`a_ay`),m=l(`a_by`),h=l(`a_bstart`),g=l(`a_sid`),_=[d,f,p,m,h,g],v=e=>n.getUniformLocation(o,e),y={res:v(`u_resolution`),styles:v(`u_styles`),left:v(`u_left`),plotW:v(`u_plotW`),xoff:v(`u_xoff`),xscale:v(`u_xscale`),xR:v(`u_xR`),minGap:v(`u_minGap`),cutPx:v(`u_cutPx`)},b=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,b),n.bufferData(n.ARRAY_BUFFER,Float32Array.from([-1,-1,1,-1,-1,1,1,1]),n.STATIC_DRAW);let x=n.createFramebuffer(),S=n.createRenderbuffer(),C=1,w=1,T=(`clientWidth`in e?e.clientWidth:0)||1,E=(`clientHeight`in e?e.clientHeight:0)||1,D=[],O=0,k=1,A=1/0,j=e=>{let t=n.createBuffer();return n.bindBuffer(n.ARRAY_BUFFER,t),n.bufferData(n.ARRAY_BUFFER,e,n.STATIC_DRAW),t},M=e=>{if(e)for(let t of[e.x,e.y,e.starts,e.sid])n.deleteBuffer(t)},N=e=>{e&&(M(e.full),M(e.res),n.deleteTexture(e.styles))},P=e=>({x:j(e.x),y:j(e.y),starts:j(e.starts),sid:j(e.sid),total:e.x.length}),F=e=>{let t=e.full;if(t&&t.version===e.version)return t;if(t&&e.valuesOnly&&t.whole&&e.counts.every(t=>t===e.xs.length)){let r=e.xs.length,i=e.columns.length===1?e.columns[0]:new Float32Array(r*e.columns.length);return e.columns.length>1&&e.columns.forEach((e,t)=>i.set(e,t*r)),n.bindBuffer(n.ARRAY_BUFFER,t.y),n.bufferSubData(n.ARRAY_BUFFER,0,i),t.version=e.version,t}M(t);let r=gH(e.xs,e.breaks,e.columns);return e.full={...P(r),version:e.version,whole:r.counts.every(t=>t===e.xs.length)},e.full},I=t=>{let n=Math.max(1,Math.round(t.plotW*(e.width/T)));if(t.resamplable&&k>O){let e=t.xs,r=0,i=e.length;for(;r<i;){let t=r+i>>>1;e[t]<O?r=t+1:i=t}let a=r;for(i=e.length;r<i;){let t=r+i>>>1;e[t]<=k?r=t+1:i=t}if(r-a>n*4){let r=`${t.version}|${O}|${k}|${n}`;if(t.res?.key!==r){M(t.res);let i=_H(e,t.columns,t.origin,O,k,n);t.res={...P(i),key:r,bucket:i.bucket}}return{d:t.res,minGap:t.res.bucket*2.5}}}return{d:F(t),minGap:0}},L=(e,r)=>{let i=e.counts.length,a=Math.max(1,Math.ceil(i/fH)),o=3*Math.min(Math.max(i,1),fH),s=new Float32Array(o*a*4);for(let n=0;n<i;n++){let i=r[n],a=(Math.floor(n/fH)*o+n%fH*3)*4;if(!i)continue;let c=i.width??t;s.set([Math.min(i.scaleMin,i.scaleMax),Math.max(i.scaleMin,i.scaleMax),i.bandTop,i.bandBottom],a),s.set(i.color,a+4),s.set([i.gapMedian,c/2,c/2+YV,+(e.counts[n]>=2)],a+8)}n.bindTexture(n.TEXTURE_2D,e.styles),n.texImage2D(n.TEXTURE_2D,0,n.RGBA32F,o,a,0,n.RGBA,n.FLOAT,s),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST)};return{resize(t,r,i){T=Math.max(1,t),E=Math.max(1,r),e.width=Math.round(T*i),e.height=Math.round(E*i),C=e.width*2,w=e.height*2,x&&S&&(n.bindRenderbuffer(n.RENDERBUFFER,S),n.renderbufferStorage(n.RENDERBUFFER,n.RGBA8,C,w),n.bindFramebuffer(n.FRAMEBUFFER,x),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,S),n.bindFramebuffer(n.FRAMEBUFFER,null))},setData(e,t,r,i){let a=D[e],o=!t&&!!a&&i.length===a.columns.length;if(!t){if(!a)return;t=a.xs,r=a.breaks}let s=0;for(let e=0;e<t.length;e++)if(Number.isFinite(t[e])){s=t[e];break}let c=i.map(e=>{let t=0;for(let n=0;n<e.length;n++)e[n]===e[n]&&t++;return t});if(a&&(o||a.xs===t)){a.columns=i,a.counts=c,a.valuesOnly=o,a.version++,o||(M(a.full),a.full=null);return}let l={xs:t,breaks:r,columns:i,origin:s,counts:c,resamplable:!r?.some(e=>e)&&vH(t),version:0,valuesOnly:!1,full:null,res:null,styles:n.createTexture(),left:a?.left??0,plotW:a?.plotW??0};L(l,[]),D[e]=l,N(a)},setStyles(e,t,n,r){let i=D[e];i&&(L(i,t),i.left=n,i.plotW=r)},clearLayer(e){N(D[e]),D[e]=null},setView(e,t,n=1/0){O=e,k=t,A=n},render(){n.bindFramebuffer(n.FRAMEBUFFER,x),n.viewport(0,0,x?C:e.width,x?w:e.height),n.disable(n.SCISSOR_TEST),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(o),n.uniform2f(y.res,T,E),n.uniform1i(y.styles,0),n.activeTexture(n.TEXTURE0),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE_MINUS_SRC_ALPHA),n.bindBuffer(n.ARRAY_BUFFER,b),n.enableVertexAttribArray(u),n.vertexAttribPointer(u,2,n.FLOAT,!1,0,0),n.vertexAttribDivisor(u,0);for(let e of _)n.enableVertexAttribArray(e),n.vertexAttribDivisor(e,1);let t=k-O||1;for(let e of D){if(!e)continue;n.uniform1f(y.left,e.left),n.uniform1f(y.plotW,e.plotW),n.uniform1f(y.xoff,O-e.origin),n.uniform1f(y.xscale,e.plotW/t),n.uniform1f(y.xR,t),n.uniform1f(y.cutPx,Number.isFinite(A)?e.left+(A-O)*(e.plotW/t):1e9);let{d:r,minGap:i}=I(e);r.total<2||(n.uniform1f(y.minGap,i),n.bindTexture(n.TEXTURE_2D,e.styles),n.bindBuffer(n.ARRAY_BUFFER,r.x),n.vertexAttribPointer(d,1,n.FLOAT,!1,4,0),n.vertexAttribPointer(f,1,n.FLOAT,!1,4,4),n.bindBuffer(n.ARRAY_BUFFER,r.y),n.vertexAttribPointer(p,1,n.FLOAT,!1,4,0),n.vertexAttribPointer(m,1,n.FLOAT,!1,4,4),n.bindBuffer(n.ARRAY_BUFFER,r.starts),n.vertexAttribPointer(h,1,n.UNSIGNED_BYTE,!0,1,1),n.bindBuffer(n.ARRAY_BUFFER,r.sid),n.vertexAttribPointer(g,1,n.FLOAT,!1,4,0),n.drawArraysInstanced(n.TRIANGLE_STRIP,0,4,r.total-1))}for(let e of _)n.vertexAttribDivisor(e,0);x&&(n.bindFramebuffer(n.READ_FRAMEBUFFER,x),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),n.blitFramebuffer(0,0,C,w,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.LINEAR),n.bindFramebuffer(n.FRAMEBUFFER,null))},dispose(){for(let e of D)N(e);D.length=0,n.deleteBuffer(b),n.deleteFramebuffer(x),n.deleteRenderbuffer(S),r&&(n.deleteProgram(o),n.deleteShader(s),n.deleteShader(c)),r&&n.getExtension(`WEBGL_lose_context`)?.loseContext()}}}``+new URL(`assets/offscreenLineWorker-C-_uNa_H.js`,import.meta.url).href;var bH=[],xH=12,SH=!1,CH=!1,wH=0,TH=3,EH=1;function DH(){return!SH&&typeof Worker<`u`&&typeof HTMLCanvasElement<`u`&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen==`function`}var OH=`kymoscope-gl-first-frame`;function kH(e,t=1,n,r,i){if(typeof e.transferControlToOffscreen!=`function`||typeof Worker>`u`)return null;let a,o=bH.pop();try{a=o??UE(``+new URL(`assets/offscreenLineWorker-C-_uNa_H.js`,import.meta.url).href)}catch{return SH=!0,null}let s;try{s=e.transferControlToOffscreen()}catch{return o?bH.push(o):a.terminate(),null}let c=()=>{},l=EH++,u=!1;a.postMessage({type:`init`,canvas:s,lineWidth:t,gen:l},[s]),a.onmessage=e=>{e.data?.gen===l&&(e.data.type===`lost`?n?.():e.data.type===`first`&&(CH=!0,performance.mark?.(OH),c()))},a.onerror=()=>{u=!0,(!CH||++wH>=TH)&&(SH=!0),n?.()};let d=aH(r),f=-1,p=-1,m=-1,h={own:!0,resize(e,t,n){e===f&&t===p&&n===m||(f=e,p=t,m=n,a.postMessage({type:`resize`,w:e,h:t,dpr:n}))},setData(e,t){let n=[];t.xs&&n.push(t.xs.buffer),t.breaks&&n.push(t.breaks.buffer);for(let e of t.columns)n.push(e.buffer);a.postMessage({type:`data`,layer:e,...t},n)},setStyle(e,t){a.postMessage({type:`style`,layer:e,...t})},clear(e){a.postMessage({type:`clear`,layer:e})},setView(e,t,n){a.postMessage({type:`view`,xmin:e,xmax:t,cut:n})},dispose(){a.onmessage=null,a.onerror=null;let e=!u&&!SH&&bH.length<xH;try{a.postMessage({type:`dispose`})}catch{e=!1}e?bH.push(a):a.terminate(),d()}},g=i?AH(i,t):null;if(!g||!i)return h;let _=()=>{g&&(g.dispose(),g=null,i.getContext(`2d`)?.clearRect(0,0,i.width,i.height))};return c=()=>{(typeof requestAnimationFrame==`function`?requestAnimationFrame:setTimeout)(_)},{own:!0,resize(e,t,n){g?.resize(e,t,n),h.resize(e,t,n)},setData(e,t){g?.setData(e,{...t,xs:t.xs?t.xs.slice():null,breaks:t.breaks?.slice(),columns:t.columns.map(e=>e.slice())}),h.setData(e,t)},setStyle(e,t){g?.setStyle(e,t),h.setStyle(e,t)},clear(e){g?.clear(e),h.clear(e)},setView(e,t,n){g?.setView(e,t,n),h.setView(e,t,n)},dispose(){_(),h.dispose()}}}function AH(e,t=1){let n=dH(e,e=>yH(e,t));if(!n)return null;let r=0,i=1,a,o=``,s=(e,t)=>{n.setStyles(e,t.styles,t.left,t.plotW),r=t.xmin,i=t.xmax,a=t.cut,n.setView(r,i,a),n.render()};return{resize(e,t,r){let i=`${e}|${t}|${r}`;i!==o&&(o=i,n.resize(e,t,r),n.render())},setData(e,t){n.setData(e,t.xs,t.breaks,t.columns),s(e,t)},setStyle(e,t){s(e,t)},clear(e){n.clearLayer(e),n.render()},setView(e,t,o){e===r&&t===i&&o===a||(r=e,i=t,a=o,n.setView(e,t,o),n.render())},dispose(){n.dispose()}}}var jH=new Set;function MH(e){jH.add(e)}function NH(e){jH.delete(e)}function PH(){let e=typeof window>`u`?[]:[window];for(let t of jH)t.closed||e.push(t);return e}var FH=1,IH=new Map;function LH(e,t){let n=typeof window>`u`?void 0:window.performance?.timeOrigin,r=e.performance?.timeOrigin;return n!==void 0&&r!==void 0&&e!==window?t+(r-n):t}function RH(e){let t=FH++,n=PH();if(n.length===1){let r=n[0],i=r.requestAnimationFrame(n=>{IH.delete(t),e(LH(r,n))});return IH.set(t,[{w:n[0],id:i}]),t}let r=[];for(let i of n)r.push({w:i,id:i.requestAnimationFrame(n=>{IH.has(t)&&(zH(t),e(LH(i,n)))})});return IH.set(t,r),t}function zH(e){if(e==null)return;let t=IH.get(e);if(t){IH.delete(e);for(let{w:e,id:n}of t)e.closed||e.cancelAnimationFrame(n)}}var BH=new WeakMap;function VH(e){e&&BH.set(e,(BH.get(e)??0)+1)}function HH(e){let t=BH.get(e)??0;for(let n of e.querySelectorAll(`*`))t+=BH.get(n)??0;return t}function UH(){return PH().every(e=>e.document.hidden)}var WH=class{#e;#t=new Map;constructor(e){this.#e=e}observe(e,t){let n=e.ownerDocument.defaultView??window,r=this.#t.get(n);r||(r=new(n.ResizeObserver??ResizeObserver)(e=>this.#e(e,this)),this.#t.set(n,r)),r.observe(e,t)}unobserve(e){for(let t of this.#t.values())t.unobserve(e)}disconnect(){for(let e of this.#t.values())e.disconnect();this.#t.clear()}};function GH(e){return!!e&&e.isConnected&&typeof e.checkVisibility==`function`&&!e.checkVisibility()}function KH(e,t){let n=0,r=null,i=()=>GH(t()),a=t=>{n=0,!i()&&(r=t,e())};return{schedule(){n||=RH(a)},now(){if(i())return;let o=t()?.ownerDocument?.timeline?.currentTime;if(typeof o!=`number`||o===r){n||=RH(a);return}n&&=(zH(n),0),r=o,e()},cancel(){n&&zH(n),n=0}}}var qH=.6,JH=16,YH={ts:-1,work:0,floor:1/0},XH=1/0;function ZH(e,t=-1/0){if(e!==YH.ts){if(e>YH.ts&&e<YH.ts+YH.work/qH)return!1;YH={ts:e,work:0,floor:XH},XH=1/0}return YH.work>=JH||t>YH.floor?(XH=Math.min(XH,t),!1):!0}function QH(e,t){e===YH.ts&&(YH.work+=t)}function $H(e,t=typeof window>`u`?null:e=>{RH(e)}){let n=!1,r=null;return{set(i){if(r=i,!t){e(i);return}n||(n=!0,t(()=>{n=!1,e(r)}))}}}function eU(e,t,n,r,i){return r+(e-t)/n*(i-r)}function tU(e,t,n,r){let i=new Map,a=n.length;if(a===0)return i;let o=new Float64Array(a),s=new Float64Array(a).fill(1/0);for(let r of e){let e=r.x;for(let i=0;i<a;i++){let a=r.cols.get(n[i]);if(!a)continue;let c=s[i],l=o[i];for(let n=0;n<r.length;n++){let r=e[n],i=r<t?t-r:r-t;if(i>=c)continue;let o=a[n];Number.isFinite(o)&&(c=i,l=o)}s[i]=c,o[i]=l}}for(let e=0;e<a;e++)s[e]!==1/0&&(r&&s[e]>(r.get(n[e])??1/0)||i.set(n[e],o[e]));return i}function nU(e,t,n,r=64){let i=new Map;if(t.length===0||!Number.isFinite(n))return i;let a=new Map;for(let o of e){if(o.length===0)continue;let e=0,s=o.length-1;for(;e<s;){let t=e+s>>1;o.x[t]<n?e=t+1:s=t}for(let s of t){let t=o.cols.get(s);if(t)for(let c=0;c<=r;c++){let r=e-c,l=e+c,u=r>=0&&Number.isFinite(t[r])?r:l<o.length&&Number.isFinite(t[l])?l:-1;if(u<0)continue;let d=Math.abs(o.x[u]-n);d<(a.get(s)??1/0)&&(a.set(s,d),i.set(s,t[u]));break}}}return i}function rU(e,t){let n=new Map;if(t.length===0)return n;for(let r=e.length-1;r>=0&&n.size<t.length;r--){let i=e[r];for(let e of t){if(n.has(e))continue;let t=i.cols.get(e);if(t){for(let r=i.length-1;r>=0;r--)if(Number.isFinite(t[r])){n.set(e,t[r]);break}}}}return n}function iU(e,t){return!(e>0)||!(t>0)?1:1-Math.exp(-e/t)}function aU(e,t,n,r,i,a){let o=e;return n!==null&&Math.abs(t-n)<i*a&&(o+=t-n),o+(t-o)*r}function oU(e,t,n,r=t){if(!(t>e)||n==null||!(n>0))return[e,t];let i=Number.isFinite(r)?Math.max(e,r):t;return i-n<e?[e,Math.min(t,e+n)]:[i-n,i]}function sU(e,t){return e>0?Math.min(8e3,Math.max(400,Math.round(e*t*2))):2e3}var cU=.5;function lU(e,t,n,r=cU){if(!(t>0))return e;let i=e!=null&&e>0?Math.min(e,t):t,a=n?i*.88:i/.88;return a>=t*.999?null:Math.max(r,a)}function uU(e=0){return{d:null,lastT:NaN,wall:0,base:NaN,wait:e,waitAge:0,gap:NaN}}var dU=new Map;function fU(e,t,n,r){let i=dU.get(e);if(i||dU.set(e,i={p:uU(),at:NaN,d:NaN}),n-i.at<2&&Number.isFinite(i.d))return i.d;let a=Number.isNaN(i.at)?16:n-i.at;return i.at=n,i.d=EU(i.p,t,a,r),i.d}function pU(){let e;for(let t of dU.values())(!e||t.at>e.at)&&(e=t);return e&&Number.isFinite(e.d)?{newest:e.p.lastT,lag:e.p.lastT-e.d,wait:e.p.wait,waitAge:e.p.waitAge}:null}function mU(e){return Math.min(SU,e.wait*1.2+.05)}function hU(e){return Number.isFinite(e.gap)?Math.min(e.gap,mU(e)):0}function gU(e){let t=dU.get(e);return t?hU(t.p):0}function _U(e){let t=dU.get(e);return t?mU(t.p):0}function vU(e,t,n){let r=e(t);if(!(n>0))return r;let i=(r-e(t-yU))/yU;return Number.isFinite(i)&&i>=0?r+i*n:r}var yU=.25,bU=1,xU=250,SU=3,CU=90,wU=30,TU=.001;function EU(e,t,n,r){if(!Number.isFinite(t))return t;let i=n/1e3;e.wall+=i;let a=n>xU&&e.d!==null,o=e.lastT;if(t<e.lastT&&Object.assign(e,uU(),{wall:e.wall}),t<=e.lastT)e.base+=i*TU;else{let n=e.wall-t;e.base=Number.isNaN(e.base)?n:Math.min(e.base+i*TU,n);let r=t-o;r>0&&r<bU&&(e.gap=Number.isNaN(e.gap)?r:e.gap+(r-e.gap)*.1)}e.lastT=t;let s=e.wall-t-e.base;if(r){let n=t>o?r(o):NaN;s=t>o?e.wall-e.base-(Number.isFinite(n)?n:o):0}a||(e.waitAge+=i),a||(s>e.wait?(e.wait=Math.min(SU,s),e.waitAge=0):s>e.wait*.8?e.waitAge=0:e.waitAge>CU&&(e.wait*=Math.exp(-i/wU)));let c=e.wall-e.base-mU(e);if(e.d===null)e.d=e.wait>0?Math.min(t,c):t;else if(a||e.d<c-2)e.d=Math.min(t,c);else{let t=Math.min(n,64);e.d+=t/1e3,e.d+=(c-e.d)*Math.min(1,t/500)}return e.d>t&&(e.d=t),e.d}var DU=(e,t)=>e.log?(Math.log10(Math.max(t,Number.MIN_VALUE))-Math.log10(e.v0))/(Math.log10(e.v1)-Math.log10(e.v0)||1):(t-e.v0)/(e.v1-e.v0||1),OU=(e,t)=>e.log?10**(Math.log10(e.v0)+t*(Math.log10(e.v1)-Math.log10(e.v0))):e.v0+t*(e.v1-e.v0),kU=(e,t)=>e.left+DU(e.x,t)*e.width,AU=(e,t)=>OU(e.x,(t-e.left)/(e.width||1)),jU=(e,t)=>e.top+(1-DU(e.y,t))*e.height,MU=e=>!e||Number.isFinite(e.v0)&&Number.isFinite(e.v1)&&e.v0!==e.v1&&(!e.log||e.v0>0&&e.v1>0),NU=(e,t)=>e===t||!!e&&!!t&&e.v0===t.v0&&e.v1===t.v1&&!!e.log==!!t.log;function PU(){let e=null,t=new Set;return{get:()=>e,set:n=>{if(n&&(n.width>0&&n.height>0?(!MU(n.x)||!MU(n.y))&&(n={...n,x:MU(n.x)?n.x:void 0,y:MU(n.y)?n.y:void 0}):n=null),!(n===e||n&&e&&n.left===e.left&&n.top===e.top&&n.width===e.width&&n.height===e.height&&NU(n.x,e.x)&&NU(n.y,e.y))){e=n;for(let e of[...t])e()}},subscribe:e=>(t.add(e),()=>{t.delete(e)})}}var FU=ht(()=>{}),IU=()=>bt(FU),LU=`M5 .8a3.1 3.1 0 0 0-3.1 3.1v2.3L.8 7.6h8.4L8.1 6.2V3.9A3.1 3.1 0 0 0 5 .8zM3.9 8.4a1.1 1.1 0 0 0 2.2 0z`,RU=[5,4],zU=null;function BU(e,t,n,r){typeof Path2D>`u`||(zU??=new Path2D(LU),e.save(),e.setLineDash([]),e.translate(t,n),e.fillStyle=r,e.fill(zU),e.restore())}var VU=(()=>{try{return localStorage.getItem(`glLines`)!==`0`}catch{return!0}})(),HU=(()=>{try{return localStorage.getItem(`offscreenGl`)!==`0`}catch{return!0}})(),UU=70;function WU(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}var GU={top:14,right:160,bottom:40,left:110},KU={top:14,right:100,bottom:40,left:70},qU=640,JU={top:3,right:3,bottom:3,left:3},YU=260;function XU(e){return e<YU?JU:e<qU?KU:GU}var ZU=220,QU=.05,$U=2e3,eW=4,tW=1e3/120,nW=`11.25px ${Q.mono}`,rW=11*1.125,iW=24*1.125,aW=iW-rW+26,oW=.6,sW=13,cW=10,lW=5,uW=14,dW=4;function fW(e,t,n){return Math.min(n,Math.max(t,e))}function pW(e,t,n,r,i){let a=Math.min(r,i),o=Math.max(r,i);return t+(1-fW(o===a?.5:(e-a)/(o-a),0,1))*(n-t)}function mW(e,t,n,r){let i=e+t;return{bandTop:i-r/100*t,bandBottom:i-n/100*t}}function hW(e){return e.replace(/__(\d+|ref)$/,``)}function gW(e,t,n){let r=Math.floor((n-t-rW)/sW)+1;return Math.max(0,Math.min(e,r))}function _W(e){let t=0;for(let n of e)t+=n.length;return t}function vW(e,t){let n=e.cols.get(t);return n?new Float32Array(n):new Float32Array(e.length).fill(NaN)}function yW(e){let t=new Map;for(let n of e){let e=hW(n.column),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=new Set,r=[];for(let i of e){let e=hW(i.column);if(n.has(e))continue;n.add(e);let a=t.get(e);r.push({base:e,leader:a[0],members:a})}return r}function bW(e,t,n){let r=new Map,i=e.map((e,r)=>{let{bandTop:i}=mW(t,n,e.leader.bandFromPct,e.leader.bandToPct);return{g:e,i:r,bandTop:i,blockDY:e.members.length>1?rW+(e.members.length+1)*sW:aW}});i.sort((e,t)=>e.bandTop-t.bandTop||e.i-t.i);let a=-1/0;for(let{g:e,bandTop:t,blockDY:n}of i){let i=t+rW,o=Math.max(i,a),s=o-rW;r.set(e.leader.id,s),a=o+n}return r}function xW(e,t){let n=e.cols.get(t);if(!n)return 0;let r=e.x;return n.length===e.length&&j.has(n)?SW(r,e.length):wW(r,e.length,e=>Number.isFinite(n[e]))}function SW(e,t){let n=CW.get(e);return n===void 0&&(n=wW(e,t,()=>!0),CW.set(e,n)),n}var CW=t(new WeakMap);function wW(e,t,n){let r=null,i=0,a=0;for(let o=0;o<t;o++)n(o)&&(r!==null&&e[o]!==r&&(i+=Math.abs(e[o]-r),a++),r=e[o]);return a===0?0:i/a}function TW(e,t){return e>0?Math.max(e*4,t*1e-9):Math.max(t*1e-6,1e-12)}var EW=1e30,DW=250;function OW({xLabel:e,series:t,points:n,columnUnits:r={},height:i=440,onPlotContextMenu:a,backgroundToken:o=``,viewXRange:s=null,onViewXRangeChange:c,liveZoom:l,liveZoomId:u,fullXRange:d=null,shiftMode:f,xAxisLine:p,yAxisLine:m,gridLine:h,lineWidth:g=1,envelopes:_,showLatestValues:v=!1,liveSource:y,liveWindowSeconds:b=null,onLiveWindowChange:x,liveZoomMode:S,onPlotWidthCss:C,onCursorX:w}){let T=IU(),E=K(null),D=K(null),O=K(null),k=K(null),A=K(null),j=K(C);j.current=C;let M=K(-1),N=K(null),P=K(!1),F=K(null),I=K(!1),L=K(!1),R=K(null),z=K(null),B=K({pts:null,layers:[]}),V=K(new Map),ee=K([]),te=K(null),H=K(null),ne=K(null),re=K(null),ie=K(null),U=K(0),ae=K(0),oe=K(!1),se=K(0),ce=K($U),le=K(y),ue=K(null),de=K(uU()),fe=K(0),pe=K(void 0),me=K(0),he=K(0),ge=K(16),_e=K(!0),ve=K(!1),[ye,be]=Ct(0),xe=()=>GH(A.current);function Se(){F.current?.dispose(),F.current=null,L.current=!1,I.current=!1,ee.current=[],be(e=>e+1)}W(()=>{ye&&xt()},[ye]),G(()=>{le.current=y,ue.current=null,B.current={pts:null,layers:[]},V.current.clear()},[y]);let Ce=K(b);G(()=>{Ce.current=b},[b]);let we=K(x);we.current=x;let Te=S??(x?`follow`:`free`),Ee=K(Te);Ee.current=Te;let De=K(null);G(()=>{De.current=null},[Te,e]);let Oe=K([]),ke=K(!1),Ae=K(0),je=K(0),Me=K(0),Ne=K(0),Pe=K(`none`),Fe=K(0),Ie=K(0),Le=K(0),Re=K(null),ze=K(null),Be=K(f),Ve=K(null),He=K({pts:null,x0:NaN,x1:NaN,ser:null}),Ue=K(0),We=K(0),Ge=K(null),Ke=K(null),qe=K(null),Je=K(null);G(()=>{Be.current=f},[f]),W(()=>(R.current&&=(clearTimeout(R.current),null),()=>{N.current?.dispose(),N.current=null;let e=F.current;e&&(R.current=setTimeout(()=>{e.dispose(),F.current===e&&(F.current=null),R.current=null},0))}),[]);let Ye=wt(eB,$z),Xe=K({xLabel:e,series:t,points:n,height:i,columnUnits:r,shiftMode:f,xAxisLine:p,yAxisLine:m,gridLine:h,lineWidth:g,showLatestValues:v,envelopes:_}),Ze=K(null),Qe=K(null);G(()=>{Xe.current={xLabel:e,series:t,points:n,height:i,columnUnits:r,shiftMode:f,xAxisLine:p,yAxisLine:m,gridLine:h,lineWidth:g,showLatestValues:v,envelopes:_}},[e,t,n,i,r,f,p,m,h,g,v,_]);let $e=K(c),et=K(w);et.current=w,G(()=>{$e.current=c},[c]);let tt=K(l),nt=K(u);G(()=>{tt.current=l,nt.current=u},[l,u]),W(()=>{if(!(!l||!u))return l.subscribe((e,t)=>{e!==u&&(te.current=t?.[0]??null,H.current=t?.[1]??null,xt())})},[l,u]);let rt=K(a);G(()=>{rt.current=a},[a]);let it=St(()=>{if(d&&d[1]>d[0])return{xmin:d[0],xmax:d[1]};let e=1/0,t=-1/0;for(let r of n)for(let n=0;n<r.length;n++){let i=r.x[n];i<e&&(e=i),i>t&&(t=i)}return(!Number.isFinite(e)||e===t)&&(--e,t+=1),{xmin:e,xmax:t}},[n,d]),at=K(it);G(()=>{at.current=it},[it]);function ot(){return le.current!=null&&te.current===null&&H.current===null&&!ke.current&&Ve.current===null}function st(){let{xmin:e,xmax:t}=at.current,n=te.current,r=H.current;if(n!==null&&r!==null&&r>n&&Number.isFinite(n)&&Number.isFinite(r))return{xmin:n,xmax:r};let i=ne.current,a=re.current;return ot()&&i!==null&&a!==null&&a>i&&Number.isFinite(i)&&Number.isFinite(a)?{xmin:i,xmax:a}:{xmin:e,xmax:t}}function ct(e,t){let n=le.current;if(!n?.latestValues)return rU(e,t);let r=n.latestValues(t),i=t.filter(e=>!r.has(e)),a=n.latestX?.();if(i.length>0&&a!=null)for(let[t,n]of nU(e,i,a))r.set(t,n);return r}function lt(){return le.current?Oe.current:Xe.current.points}function ut(e,t,n){let r=new Map;for(let i of t)r.set(i,TW(ht(e,i),n));return r}function dt(e){if(B.current.pts===e)return B.current.layers;let t=B.current.layers,n=le.current?.version?.(),r=e.map((e,r)=>({pts:e,key:t[r]?.pts===e?t[r].key:n??e}));return B.current={pts:e,layers:r},r}function ft(e,t){let n=V.current.get(e),r=performance.now(),i=n&&(n.key===t.key||typeof t.key==`number`&&typeof n.key==`number`&&r-n.at<DW);return(!n||!i)&&(n={key:t.key,at:r,has:new Map,median:new Map},V.current.set(e,n)),n}function pt(e,t,n){let r=ft(e,t),i=r.has.get(n);if(i===void 0){let e=t.pts.cols.get(n);i=!!e&&e.some(Number.isFinite),r.has.set(n,i)}return i}function mt(e,t){return dt(e).some((e,n)=>pt(n,e,t))}function ht(e,t){let n=dt(e);for(let e=0;e<n.length;e++){if(!pt(e,n[e],t))continue;let r=ft(e,n[e]),i=r.median.get(t);return i===void 0&&(i=xW(n[e].pts,t),r.median.set(t,i)),i}return 0}function gt(){if(Je.current)return Je.current;let e=A.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return Je.current=n,n}function _t(){let e=A.current,t=Math.max(1,e?.clientWidth||200),n=e?.clientHeight??0;return{w:t,h:Math.max(1,n>0?n:Xe.current.height)}}function vt(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function yt(){let e=E.current;if(!e)return;let{w:t,h:n}=_t(),r=vt(e,t,n);if(!r)return;{let e=lt(),t=st(),n=Xe.current.series,r=He.current;(r.pts!==e||r.x0!==t.xmin||r.x1!==t.xmax||r.ser!==n)&&(He.current={pts:e,x0:t.xmin,x1:t.xmax,ser:n},VH(A.current))}let i=XU(t),a=i===JU,{top:o,right:s,bottom:c}=i,l=i.left,u=t-l-s,d=n-o-c,{bg:f,muted:p,grid:m}=gt(),{xLabel:h,series:g,xAxisLine:_,yAxisLine:v,gridLine:y,lineWidth:b,columnUnits:x,showLatestValues:S}=Xe.current,C=lt();if(r.fillStyle=f,r.fillRect(0,0,t,n),_W(C)<2||u<=0||d<=0){if(r.fillStyle=p,r.font=`13px ${Q.sans}`,UV(r),N.current&&(N.current.resize(t,n,window.devicePixelRatio||1),N.current.draw([])),F.current){F.current.resize(t,n,window.devicePixelRatio||1);for(let e=0;e<ee.current.length;e++)F.current.clear(e);ee.current=[]}return}let{xmin:w,xmax:k}=st(),j=k-w,M=e=>l+(e-w)/j*u;T({left:l,top:o,width:u,height:d,x:{v0:w,v1:k}});let z=g.filter(e=>e.bandToPct>e.bandFromPct&&e.scaleMin!==e.scaleMax&&mt(C,e.column)),B=yW(z),V=bW(B,o,d),te=new Map;for(let e of B){let t=V.get(e.leader.id);t!==void 0&&e.members.forEach(e=>te.set(e.id,t))}let H=new Set,ne=new Set;for(let e of B)e.members.length>1&&e.members.forEach(e=>H.add(e.id)),ne.add(e.leader.id);let re=`11px ${Q.mono}`,ie=z.map(e=>{let{bandTop:t,bandBottom:n}=mW(o,d,e.bandFromPct,e.bandToPct),r=Math.min(e.scaleMin,e.scaleMax),i=Math.max(e.scaleMin,e.scaleMax),{majorStep:a,minorStep:s}=Iz(e.scaleMin,e.scaleMax,e.yMajorStep??0,e.yMinorStep??0),c=a,l=Lz(r,i,c);l.length>120&&(l=Lz(r,i,c=Iz(e.scaleMin,e.scaleMax,0,0).majorStep));let u=Rz(r,i,s,l);return u.length>400&&(u=[]),{s:e,bandTop:t,bandBottom:n,majors:l,minors:u,step:c}}),U=new Map,ae=0;{r.save(),r.font=re;let e=ie.filter(e=>ne.has(e.s.id));e.sort((e,t)=>{let n=Math.abs(e.s.bandToPct-e.s.bandFromPct),r=Math.abs(t.s.bandToPct-t.s.bandFromPct);return n===r?ie.indexOf(e)-ie.indexOf(t):r-n});let n=new Map,a=[];for(let t of e){let r=0;for(;r<e.length;r++){let e=a[r];if(!e||e.length===0||!e.some(e=>t.bandTop<e.bandBottom&&t.bandBottom>e.bandTop))break}n.set(t.s.id,r),a[r]||(a[r]=[]),a[r].push(t)}let o=new Map,c=new Map;for(let t of e){let e=0;for(let n of t.majors){let i=Vz(n,t.step),a=c.get(i);a===void 0&&c.set(i,a=r.measureText(i).width),a>e&&(e=a)}o.set(t.s.id,e)}let u=[],d=[],f=0;for(let e=0;e<a.length;e++){u[e]=f;let t=0;for(let n of a[e]??[]){let e=o.get(n.s.id)??0;e>t&&(t=e)}d[e]=t,f+=t+22}for(let e of ie){let t=n.get(e.s.id)??0;U.set(e.s.id,u[t]??0)}let p=i.left;for(let e=0;e<a.length;e++){let t=a[e];if(!t||t.length===0)continue;let n=(u[e]??0)+dW+uW+(d[e]??0)+6;n>p&&(p=n)}let m=Math.max(i.left,t-s-Math.max(120,t*.4)),h=Math.min(Math.ceil(p),m);h>l&&(ae=h-l),r.restore()}ae>0&&(l+=ae,u=Math.max(1,t-l-s)),ce.current=sU(u,window.devicePixelRatio||1);let oe=(e,t)=>1-(1-e)**t,se=new Map,le=new Map;for(let e of ie){let t=`${e.bandTop}|${e.bandBottom}|${e.s.scaleMin}|${e.s.scaleMax}|${e.majors.join(`,`)}`,n=se.get(t);n?n.k++:se.set(t,{c:e,k:1});let r=H.has(e.s.id)?p:e.s.color,i=`${e.bandTop}|${e.bandBottom}|${r}`,a=le.get(i);a?a.k++:le.set(i,{c:e,color:r,k:1})}if((v?.style??`dashed`)!==`none`)for(let{c:{s:e,bandTop:t,bandBottom:n,majors:i},k:a}of se.values()){r.save(),r.strokeStyle=v?.color??m,r.globalAlpha=oe(.1,a),r.lineWidth=v?.width??1,r.lineCap=`round`,r.setLineDash(WU(v?.style??`dashed`));for(let a of i){let i=pW(a,t,n,e.scaleMin,e.scaleMax);r.beginPath(),r.moveTo(l,i),r.lineTo(l+u,i),r.stroke()}r.restore()}for(let{c:{bandTop:e,bandBottom:t},color:n,k:i}of le.values())r.strokeStyle=n,r.lineWidth=1,r.setLineDash([]),r.globalAlpha=oe(.45,i),r.beginPath(),r.moveTo(l,e),r.lineTo(l,t),r.stroke(),r.globalAlpha=1;for(let{s:e,bandTop:t,bandBottom:n,majors:i,minors:o,step:s}of a?[]:ie){let a=H.has(e.id)?p:e.color;if(ne.has(e.id)){let c=U.get(e.id)??0,u=l-c-dW;r.strokeStyle=a,r.lineWidth=1;for(let i of o){let a=pW(i,t,n,e.scaleMin,e.scaleMax);r.beginPath(),r.moveTo(u-lW,a),r.lineTo(u,a),r.stroke()}r.font=re,r.textAlign=`right`,r.textBaseline=`middle`,r.strokeStyle=a,r.fillStyle=a;for(let a of i){let i=pW(a,t,n,e.scaleMin,e.scaleMax);r.beginPath(),r.moveTo(u-cW,i),r.lineTo(u,i),r.stroke(),r.fillText(Vz(a,s),u-uW,i)}}}if((y?.style??`solid`)!==`none`&&(r.strokeStyle=y?.color??m,r.lineWidth=y?.width??1,r.setLineDash(WU(y?.style??`solid`)),r.strokeRect(l,o,u,d),r.setLineDash([])),(_?.style??`dashed`)!==`none`){r.strokeStyle=_?.color??m,r.lineWidth=_?.width??1,r.setLineDash(WU(_?.style??`dashed`));for(let e=1;e<6;e++){let t=l+e/6*u;r.beginPath(),r.moveTo(t,o),r.lineTo(t,o+d),r.stroke()}r.setLineDash([])}let ue=o+d+10;r.fillStyle=p,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`;let de=Gz(h,w,w+j);for(let e=0;e<=(a?-1:6);e++){let t=w+e/6*j;r.fillText(de?tB(t,j/6,j):Vz(t,j/6),l+e/6*u,ue)}r.textBaseline=`bottom`,a||r.fillText(h,l+u/2,n-5);let{shiftMode:fe}=Xe.current;fe&&(r.globalAlpha=.8,r.font=`10px ${Q.sans}`,r.fillStyle=p,r.textAlign=`center`,r.textBaseline=`top`,r.fillText(`⇄ shifting: ${fe.label}`,l+u/2,o+3),r.globalAlpha=1);let me=Xe.current.envelopes;if(me?.length){r.save(),r.beginPath(),r.rect(l,o,u,d),r.clip();for(let e of me){let t=z.find(t=>t.id===e.seriesId||t.id.startsWith(`${e.seriesId}__`));if(!t)continue;let{bandTop:n,bandBottom:i}=mW(o,d,t.bandFromPct,t.bandToPct),a=e=>pW(e,n,i,t.scaleMin,t.scaleMax);r.fillStyle=e.color,r.globalAlpha=.2;let s=0;for(;s<e.x.length;){for(;s<e.x.length&&e.lo[s]!==e.lo[s];)s++;let t=s;for(;s<e.x.length&&e.lo[s]===e.lo[s];)s++;if(!(s-t<2)){r.beginPath(),r.moveTo(M(e.x[t]),a(e.hi[t]));for(let n=t+1;n<s;n++)r.lineTo(M(e.x[n]),a(e.hi[n]));for(let n=s-1;n>=t;n--)r.lineTo(M(e.x[n]),a(e.lo[n]));r.closePath(),r.fill()}}}r.restore()}R.current&&=(clearTimeout(R.current),null);let he=HU&&!I.current?F.current:null;if(HU&&!he&&!I.current&&D.current&&!L.current&&(he=DH()&&iH()?kH(D.current,1,Se,{hidden:xe,evict:Se},O.current??void 0):AH(D.current),he?(F.current=he,L.current=!0):I.current=!0),he){he.resize(t,n,window.devicePixelRatio||1);let e=`${l.toFixed(2)}|${u.toFixed(2)}|${o}|${d}|${b}|`+z.map(e=>`${e.id}:${e.column}:${e.bandFromPct}:${e.bandToPct}:${e.scaleMin}:${e.scaleMax}:${e.color}`).join(`,`),r=dt(C),i=ee.current;for(let t=0;t<Math.max(r.length,i.length);t++){let n=r[t];if(!n){i[t]&&he.clear(t),i[t]=null;continue}let a=z.filter(e=>pt(t,n,e.column)),s=a.map(e=>e.column).join(`
|
|
207
|
+
`),c=i[t];if(c&&c.pts===n.pts&&c.sig===e&&c.cols===s)continue;i[t]={pts:n.pts,sig:e,cols:s};let f={styles:a.map(e=>{let{bandTop:t,bandBottom:r}=mW(o,d,e.bandFromPct,e.bandToPct);return{color:qV(e.color),bandTop:t,bandBottom:r,scaleMin:e.scaleMin,scaleMax:e.scaleMax,gapMedian:n.pts.hold?EW:ht(C,e.column),width:b}}),left:l,plotW:u,xmin:w,xmax:k,cut:pe.current};if(c&&c.pts===n.pts&&c.cols===s){he.setStyle(t,f);continue}let p=n.pts,m=!!c&&c.pts.x===p.x&&c.pts.brk===p.brk&&c.cols===s;he.setData(t,{...f,xs:m?null:p.x.slice(),breaks:m?void 0:p.brk?.slice(),columns:a.map(e=>vW(p,e.column))})}i.length=r.length,he.setView(w,k,pe.current)}else{let e=N.current;VU&&!e&&!P.current&&D.current&&!L.current&&(e=$V(D.current),e?N.current=e:P.current=!0);let i=!!e;i&&e&&e.resize(t,n,window.devicePixelRatio||1);let a=[],s=ut(C,z.map(e=>e.column),j);for(let e of z){let{bandTop:t,bandBottom:n}=mW(o,d,e.bandFromPct,e.bandToPct),c=s.get(e.column);if(i){let r={x:l,y:t,w:u,h:n-t},i=qV(e.color),o=[],s=null,d=()=>{o.length>=4&&a.push({points:Float32Array.from(o),color:i,clip:r,width:b}),o=[]};for(let r of C){let i=r.cols.get(e.column);if(i){s=null;for(let a=0;a<r.length;a++){r.brk?.[a]&&d();let l=i[a];if(!Number.isFinite(l))continue;let u=r.x[a];s!==null&&!r.hold&&Math.abs(u-s)>c&&d(),o.push(M(u),pW(l,t,n,e.scaleMin,e.scaleMax)),s=u}d()}}d();continue}r.strokeStyle=e.color,r.lineWidth=b,r.lineJoin=`round`,r.lineCap=`round`,r.save(),r.beginPath(),r.rect(l,t,u,n-t),r.clip(),r.beginPath();let f=!1,p=null,m=!1;for(let i of C){let a=i.cols.get(e.column);if(a){m=!0;for(let o=0;o<i.length;o++){i.brk?.[o]&&(m=!0);let s=a[o];if(!Number.isFinite(s))continue;let l=i.x[o],u=M(l),d=pW(s,t,n,e.scaleMin,e.scaleMax);f?m||p!==null&&!i.hold&&Math.abs(l-p)>c?(r.stroke(),r.beginPath(),r.moveTo(u,d),p=l,m=!1):(r.lineTo(u,d),p=l):(r.moveTo(u,d),f=!0,p=l,m=!1)}}}f&&r.stroke(),r.restore()}i&&e&&e.draw(a)}for(let e of z){if(!e.alarm)continue;let{bandTop:t,bandBottom:n}=mW(o,d,e.bandFromPct,e.bandToPct),i=pW(e.alarm.value,t,n,e.scaleMin,e.scaleMax);r.save(),r.beginPath(),r.rect(l,t,u,n-t),r.clip(),r.strokeStyle=e.alarm.color,r.lineWidth=e.alarm.width,r.setLineDash(e.alarm.linked===`active`?RU:WU(e.alarm.style)),r.beginPath(),r.moveTo(l,i),r.lineTo(l+u,i),r.stroke(),r.setLineDash([]),e.alarm.linked&&BU(r,l+u-10-3,i-10-2,e.alarm.color),r.restore()}if(a)return;let ge=S?ct(C,z.map(e=>e.column)):null,_e=e=>{let t=ge?.get(e.column);if(typeof t!=`number`)return`-`;let n=x[e.column]?.trim()??``;return`${Hz(t)}${n?` ${n}`:``}`},ve=l+u+8;r.font=nW,r.textAlign=`left`;for(let e of B){let t=V.get(e.leader.id);if(t===void 0)continue;let i=e.members.length>1;if(r.fillStyle=i?p:e.leader.color,r.globalAlpha=1,r.fillText(e.base,ve,t+rW),i){let i=gW(e.members.length,t,n);for(let n=0;n<i;n++)r.fillStyle=e.members[n].color,r.globalAlpha=oW,r.fillText(_e(e.members[n]),ve,t+rW+(n+1)*sW)}else r.fillStyle=e.leader.color,r.globalAlpha=oW,r.fillText(_e(e.leader),ve,t+iW);r.globalAlpha=1}}function bt(){let e=k.current;if(!e)return;let{w:t,h:n}=_t(),r=vt(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let{top:i,right:a,bottom:o,left:s}=XU(t),c=t-s-a,l=n-i-o,{series:u,columnUnits:d,xLabel:f}=Xe.current,p=lt();if(ke.current&&c>0&&l>0){let e=Ae.current,t=je.current,n=Me.current,i=Ne.current,a=Math.min(e,n),o=Math.min(t,i),s=Math.abs(n-e),c=Math.abs(i-t);r.fillStyle=`rgba(59, 130, 246, 0.12)`,r.fillRect(a,o,s,c),r.strokeStyle=`rgba(59, 130, 246, 0.85)`,r.setLineDash([4,3]),r.lineWidth=1,r.strokeRect(a,o,s,c),r.setLineDash([])}let m=z.current;if(m===null||_W(p)<2||c<=0||l<=0)return;let{xmin:h,xmax:g}=st(),_=u.filter(e=>e.bandToPct>e.bandFromPct&&e.scaleMin!==e.scaleMax&&mt(p,e.column)),v=[...new Set(_.map(e=>e.column))],y=ut(p,v,g-h),{bg:b,muted:x}=gt();r.strokeStyle=x,r.globalAlpha=.5,r.lineWidth=1,r.beginPath(),r.moveTo(m,i),r.lineTo(m,i+l),r.stroke(),r.globalAlpha=1;let S=yW(_),C=bW(S,i,l),w=s+c+8;r.font=nW,r.textAlign=`left`;let T=eU(m,s,c,h,g),E=tU(p,T,v,y),D=e=>{let t=E.get(e.column);if(typeof t!=`number`)return`-`;let n=d[e.column]?.trim()??``;return`${Hz(t)}${n?` ${n}`:``}`};for(let e of S){let t=C.get(e.leader.id)??mW(i,l,e.leader.bandFromPct,e.leader.bandToPct).bandTop;if(e.members.length>1){let i=e.members.length*sW+4;r.fillStyle=b,r.fillRect(s+c+6,t+rW+2,a-8,i);let o=gW(e.members.length,t,n);for(let n=0;n<o;n++){let i=e.members[n];r.fillStyle=i.color,r.globalAlpha=oW,r.fillText(D(i),w,t+rW+(n+1)*sW)}}else{let n=e.leader;r.fillStyle=b,r.fillRect(s+c+6,t+rW+2,a-8,iW-rW+6),r.fillStyle=n.color,r.globalAlpha=oW,r.fillText(D(n),w,t+iW)}r.globalAlpha=1}let O=/^(.*?)\s*\(([^)]*)\)\s*$/.exec(f),A=O?O[1]:f,j=O?O[2].trim():``,M=Gz(f,h,g)?nB(T):``,N=M.lastIndexOf(` `),P=M?[`${A} ${M.slice(0,N)}`,M.slice(N+1)]:[`${A} ${Math.round(T)}${j}`];r.font=nW,r.textAlign=`left`,r.textBaseline=`alphabetic`,P.forEach((e,t)=>{let n=r.measureText(e).width,a=i+l-(P.length-1-t)*15;r.fillStyle=b,r.fillRect(w-2,a-11,n+6,15),r.fillStyle=x,r.globalAlpha=1,r.fillText(e,w,a)})}function xt(){if(le.current){oe.current=!0;return}Ge.current=()=>{yt(),bt()},!Ue.current&&(Ue.current=RH(e=>{Ue.current=0,!xe()&&(Ke.current=e,Ge.current?.())}))}function Tt(){if(le.current){oe.current=!0;return}let e=A.current?.ownerDocument.timeline?.currentTime;if(typeof e!=`number`||e===Ke.current){xt();return}Ke.current=e,zH(Ue.current),Ue.current=0,yt(),bt()}function Et(){qe.current=bt,!We.current&&(We.current=RH(()=>{We.current=0,qe.current?.()}))}function Dt(e){U.current=RH(Dt);let t=le.current;if(!t)return;ge.current+=(Math.min(50,he.current?e-he.current:16)-ge.current)*.1,he.current=e;let n=A.current;if(!(_e.current&&!GH(n))){if(!ve.current){ve.current=!0;let e=F.current;e&&(ee.current.forEach((t,n)=>{t&&e.clear(n)}),ee.current=[],e.resize(1,1,1))}return}if(ve.current&&(ve.current=!1,F.current&&!F.current.own&&DH()&&iH())){Se();return}if(me.current&&e-me.current<tW-ge.current/2||!ZH(e,me.current||-1/0))return;me.current=e;let r=performance.now(),i=t.xBounds();i&&i[1]>i[0]&&(at.current={xmin:i[0],xmax:i[1]});let a=fe.current?e-fe.current:16;fe.current=e,a>250&&(ne.current=null,re.current=null);let o=t.latestT?.(),s,c;if(o!==void 0&&t.xAtTime&&Number.isFinite(o)){let e=t.id?fU(t.id,o,performance.now(),t.timeAfter):EU(de.current,o,a,t.timeAfter),n=t.id?_U(t.id):mU(de.current),r=vU(t.xAtTime,e,n);Number.isFinite(r)&&(s=r);let i=vU(t.xAtTime,e,n-(t.id?gU(t.id):hU(de.current)));Number.isFinite(i)&&(c=i)}if(ot()){let n=s??t.latestX?.()??at.current.xmax,r=Ce.current,i=r!=null&&t.spanForSeconds?t.spanForSeconds(r):r??De.current,[a,o]=oU(at.current.xmin,at.current.xmax,i,n??void 0);if(!t.spanForSeconds&&s!==void 0&&s>a&&(o=s),Number.isFinite(a)&&Number.isFinite(o)&&o>a){let t=o-a,n=re.current!==null&&o<re.current-t;if(ne.current===null||re.current===null||n)ne.current=a,re.current=o,ae.current=e;else{let n=ae.current;ae.current=e;let r=ie.current,i=iU(n?Math.min(64,e-n):16,ZU);ne.current=aU(ne.current,a,r?r[0]:null,i,t,QU),re.current=aU(re.current,o,r?r[1]:null,i,t,QU),Math.abs(a-ne.current)<t*1e-6&&(ne.current=a),Math.abs(o-re.current)<t*1e-6&&(re.current=o)}ie.current=[a,o]}}else ne.current=null,re.current=null,ae.current=0;let l=st(),u=t.version?.(),d=ce.current,f=ue.current,p=f!==null&&u!==void 0&&f.ver===u&&f.x0===l.xmin&&f.x1===l.xmax&&f.mp===d&&f.cut===c;(_W(Oe.current)===0||!p&&e-se.current>=eW)&&(se.current=e,pe.current=t.cutOnGpu&&F.current?c:void 0,Oe.current=t.pull(l.xmin,l.xmax,d,c,pe.current!==void 0),ue.current=u===void 0?null:{ver:u,x0:l.xmin,x1:l.xmax,mp:d,cut:c}),oe.current=!1,yt(),bt(),QH(e,performance.now()-r)}function kt(){U.current||=(ae.current=0,RH(Dt))}function At(){U.current&&(zH(U.current),U.current=0,fe.current=0,ne.current=null,re.current=null,Oe.current=[],pe.current=void 0)}W(()=>{let e=A.current,t=e?.ownerDocument.defaultView?.IntersectionObserver;if(!e||!t)return;let n=new t(e=>{let t=e[e.length-1];(t.isIntersecting||t.boundingClientRect.width>0)&&(_e.current=t.isIntersecting)});return n.observe(e),()=>{n.disconnect(),_e.current=!0}},[]),W(()=>(y?kt():(At(),xt()),At),[!!y]),W(()=>uB(A.current,()=>{Je.current=null,xt()}),[]),W(()=>{Je.current=null,xt()},[o]);let jt=!!f;W(()=>{let e=k.current;e&&(e.style.cursor=jt?`ew-resize`:``),xt()},[jt,f?.label??``]);let Mt=s?.[0]??null,Nt=s?.[1]??null;return G(()=>{te.current===Mt&&H.current===Nt||(te.current=Mt,H.current=Nt,xt())},[Mt,Nt]),W(()=>{Tt()},[t,n,i,e,p,m,h,g,v,Ye]),W(()=>()=>{zH(Ue.current),zH(We.current),Ue.current=0,We.current=0},[]),W(()=>{let e=k.current,t=A.current;if(!e||!t)return;let n=()=>{let e=Math.round(t.clientWidth);e>0&&e!==M.current&&(M.current=e,j.current?.(e))};n();let r=new WH(()=>{Je.current=null,n(),xt()});r.observe(t);let i=$H(e=>et.current?.(e)),a=t=>{if(ke.current||Ve.current!==null)return;if(_W(lt())<2){z.current!==null&&(z.current=null,Et(),i.set(null));return}let n=e.getBoundingClientRect(),r=t.clientX-n.left,a=t.clientY-n.top,{left:o,top:s,right:c,bottom:l}=XU(n.width),u=Math.max(1,n.width-o-c),d=n.height-s-l;if(r<o||r>o+u||a<s||a>s+d){z.current!==null&&(z.current=null,Et(),i.set(null));return}z.current!==r&&(z.current=r,Et());let{xmin:f,xmax:p}=st();i.set(eU(r,o,u,f,p))},o=()=>{z.current!==null&&(z.current=null,Et()),i.set(null)},s=e=>{Ze.current&&clearTimeout(Ze.current),Ze.current=setTimeout(()=>{Ze.current=null,$e.current?.(e)},UU)},c=t=>{if(Pe.current!==`none`||t.buttons&2||Date.now()-Le.current<300||_W(lt())<2)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,{top:a,left:o,right:c,bottom:l}=XU(n.width),u=Math.max(1,n.width-o-c),d=Math.max(1,n.height-a-l);if(r<o||r>o+u||i<a||i>a+d)return;t.preventDefault();let f=at.current,p=f.xmax-f.xmin;if(!(p>0))return;if(Ee.current===`follow`&&ot()&&!we.current){De.current=lU(De.current,p,t.deltaY<0,p*.001);return}if(Ee.current===`follow`&&ot()){let e=lU(Ce.current,le.current?.bufferedSeconds?.()??p,t.deltaY<0);Ce.current=e,Qe.current&&clearTimeout(Qe.current),Qe.current=setTimeout(()=>{Qe.current=null,we.current?.(e)},UU);return}let m=te.current??f.xmin,h=(H.current??f.xmax)-m;if(!(h>0))return;let g=Date.now();g-Ie.current>300&&(Re.current=te.current,ze.current=H.current),Ie.current=g;let _=m+(r-o)/u*h,v=t.deltaY<0,y=.88,b=v?h*y:h/y,x=Math.max(p*1e-7,1e-12);if(v)b=Math.max(b,x);else{if(b>=p*.999){te.current=null,H.current=null,s(null),tt.current?.publish(nt.current??``,null),xt();return}b=Math.min(b,p)}let S=(_-m)/h,C=_-S*b,w=_+(1-S)*b;C<f.xmin&&(w+=f.xmin-C,C=f.xmin),w>f.xmax&&(C-=w-f.xmax,w=f.xmax),w-C<b-1e-12&&(C=Math.max(f.xmin,_-b/2),w=C+b,w>f.xmax&&(w=f.xmax,C=w-b)),w-C>=p*.999?(te.current=null,H.current=null,s(null),tt.current?.publish(nt.current??``,null)):(te.current=C,H.current=w,s([C,w]),tt.current?.publish(nt.current??``,[C,w])),xt()},l=e=>{if(e.preventDefault(),Le.current=Date.now(),Date.now()-Ie.current<300){te.current=Re.current,H.current=ze.current;let e=Re.current,t=ze.current;Ze.current&&=(clearTimeout(Ze.current),null),$e.current?.(e===null&&t===null?null:[e,t]),Ie.current=0,xt()}},u=t=>{if(t.button===0&&Be.current){let n=e.getBoundingClientRect(),{left:r,top:i,right:a,bottom:o}=XU(n.width),s=Math.max(1,n.width-r-a),c=n.height-i-o,l=t.clientX-n.left,u=t.clientY-n.top;if(l>=r&&l<=r+s&&u>=i&&u<=i+c){Ve.current=t.clientX,Be.current.onDragStart();try{e.setPointerCapture(t.pointerId)}catch{}}return}if(t.button!==2)return;if(t.preventDefault(),t.buttons===0){rt.current?.({clientX:t.clientX,clientY:t.clientY});return}if(Pe.current!==`none`){ke.current=!1,Pe.current=`none`;try{e.releasePointerCapture(t.pointerId)}catch{}}let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top;Fe.current=Date.now(),Pe.current=`menuOnly`,ke.current=!1,Ae.current=r,je.current=i,Me.current=r,Ne.current=i;try{e.setPointerCapture(t.pointerId)}catch{}},d=t=>{if(Ve.current!==null){let n=t.clientX-Ve.current,r=e.getBoundingClientRect(),{left:i,right:a}=XU(r.width),o=Math.max(1,r.width-i-a),{xmin:s,xmax:c}=st(),l=c-s;l>0&&o>0&&Be.current?.onDragOffset(n/o*l);return}if(Pe.current===`none`)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top;if(Pe.current===`menuOnly`){if(Date.now()-Fe.current<150)return;let e=r-Ae.current,t=i-je.current;if(Math.sqrt(e*e+t*t)<12)return;let a=lt(),{top:o,left:s,right:c,bottom:l}=XU(n.width),u=n.width-s-c,d=n.height-o-l,f=u>0&&d>0&&Ae.current>=s&&Ae.current<=s+u&&je.current>=o&&je.current<=o+d;if(_W(a)<2||!f)return;Pe.current=`rubber`,ke.current=!0,z.current=null}Pe.current===`rubber`&&(t.preventDefault(),Me.current=r,Ne.current=i,Et())},f=t=>{if(t.button!==2)return;t.preventDefault();let n=Pe.current;Pe.current=`none`;try{e.releasePointerCapture(t.pointerId)}catch{}if(n===`menuOnly`){ke.current=!1,Et(),rt.current?.({clientX:t.clientX,clientY:t.clientY});return}if(n!==`rubber`||!ke.current){ke.current=!1,Et();return}ke.current=!1;let r=lt(),i=e.getBoundingClientRect(),{left:a,right:o}=XU(i.width),s=Math.max(1,i.width-a-o),c=Ae.current,l=Me.current,u=Math.abs(l-c);if(_W(r)<2||u<12){rt.current?.({clientX:t.clientX,clientY:t.clientY}),Et();return}let d=fW(Math.min(c,l),a,a+s),f=fW(Math.max(c,l),a,a+s),{xmin:p,xmax:m}=st(),h=m-p;if(!(h>0)){rt.current?.({clientX:t.clientX,clientY:t.clientY}),Et();return}let g=p+(d-a)/s*h,_=p+(f-a)/s*h;if(g>_){let e=g;g=_,_=e}let v=at.current,y=Math.min(v.xmin,v.xmax),b=Math.max(v.xmin,v.xmax);g=fW(g,y,b),_=fW(_,y,b);let x=_-g;if(x<=(b-y)*1e-12||x<=0){rt.current?.({clientX:t.clientX,clientY:t.clientY}),Et();return}rt.current?.({clientX:t.clientX,clientY:t.clientY,zoomXRange:[g,_]}),Et()},p=t=>{if(t.button===0&&Ve.current!==null){Ve.current=null;try{e.releasePointerCapture(t.pointerId)}catch{}return}if(t.button===2){f(t);return}if(t.buttons===0&&Pe.current!==`none`){Pe.current=`none`,ke.current=!1;try{e.releasePointerCapture(t.pointerId)}catch{}rt.current?.({clientX:t.clientX,clientY:t.clientY}),Et()}},m=t=>{Ve.current!==null&&(Ve.current=null),Pe.current!==`none`&&(ke.current=!1,Pe.current=`none`);try{e.releasePointerCapture(t.pointerId)}catch{}Et()},h=t=>{if(t.button!==0||_W(lt())<2)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,{top:a,left:o,right:s,bottom:c}=XU(n.width),l=Math.max(1,n.width-o-s),u=Math.max(1,n.height-a-c);r<o||r>o+l||i<a||i>a+u||te.current===null&&H.current===null||(te.current=null,H.current=null,Ze.current&&=(clearTimeout(Ze.current),null),$e.current?.(null),tt.current?.publish(nt.current??``,null),xt(),Et())},g=e=>{if(e.key!==`Escape`)return;let t=!1;Pe.current!==`none`&&(Pe.current=`none`,ke.current=!1,t=!0),Ve.current!==null&&(Ve.current=null,t=!0),t&&Et()};e.addEventListener(`mousemove`,a),e.addEventListener(`mouseleave`,o),e.addEventListener(`wheel`,c,{passive:!1}),e.addEventListener(`contextmenu`,l),e.addEventListener(`pointerdown`,u),e.addEventListener(`pointermove`,d),e.addEventListener(`pointerup`,p),e.addEventListener(`pointercancel`,m),e.addEventListener(`dblclick`,h);let _=e.ownerDocument.defaultView??window;return _.addEventListener(`keydown`,g),()=>{r.disconnect(),e.removeEventListener(`mousemove`,a),e.removeEventListener(`mouseleave`,o),e.removeEventListener(`wheel`,c),e.removeEventListener(`contextmenu`,l),e.removeEventListener(`pointerdown`,u),e.removeEventListener(`pointermove`,d),e.removeEventListener(`pointerup`,p),e.removeEventListener(`pointercancel`,m),e.removeEventListener(`dblclick`,h),_.removeEventListener(`keydown`,g),Ze.current&&clearTimeout(Ze.current),Qe.current&&clearTimeout(Qe.current)}},[]),Ot(`div`,{ref:A,className:`chart-canvas-wrap`,children:[q(`canvas`,{ref:E,className:`chart-canvas`,role:`img`,"aria-label":`Chart of ${e}`}),q(`canvas`,{ref:O,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:D,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}},ye),q(`canvas`,{ref:k,className:`chart-canvas chart-overlay`})]})}function kW(){try{if(localStorage.getItem(`perfLog`)===`1`)return!0;if(localStorage.getItem(`perfLog`)===`0`)return!1}catch{}return!1}var AW=!1;function jW(){let e=kW();return e&&!AW&&(AW=!0,console.log(`[perf] logging enabled — zoom an out-of-core chart to see decimate()/sampleRows timings`)),e}jW();var MW=new Map;function NW(e,t){let n=(MW.get(e)??0)+1;MW.set(e,n),console.log(`[perf] ${e} #${n} ${t.toFixed(1)}ms`)}async function PW(e,t){if(!jW())return t();let n=performance.now();try{return await t()}finally{NW(e,performance.now()-n)}}var FW=20;async function IW(e,t,n,r){let{x0:a,bucket:o,rows:s,columns:c}=await PW(`decimate(${t.length}col)`,()=>e.getSeriesMulti(t,n,r));return i(s,c,a,o)}function LW(e,t,n,r,a=0,o=!1,s=0){let[c,l]=Ct({points:C,fetchedViewport:null}),[u,d]=Ct(!1),f=`${t.join(`,`)}|${n?`${n.xKey}:${n.x0}:${n.x1}`:`none`}|${r}|${a}`,p=St(()=>{if(!o||!e?.getSeriesMultiSync||!n||t.length===0)return null;let a=s>0?e.getColumnsSync?.(t,n,s):null;if(a)return{points:a,loading:!1,fetchedViewport:n,full:!0};let c=e.getSeriesMultiSync(t,n,r);return{points:i(c.rows,c.columns,c.x0,c.bucket),loading:!1,fetchedViewport:n}},[o,e,f,s]);return W(()=>{if(o)return;if(!e||!n||t.length===0){l({points:C,fetchedViewport:null});return}let i=!0;d(!0);let a=setTimeout(()=>{IW(e,t,n,r).then(t=>{i&&(l({points:t,fetchedViewport:n,source:e}),d(!1))}).catch(()=>{i&&d(!1)})},FW);return()=>{i=!1,clearTimeout(a)}},[e,f,o]),p||(c.source!==void 0&&c.source!==e?{points:C,loading:u,fetchedViewport:null}:{points:c.points,loading:u,fetchedViewport:c.fetchedViewport})}var RW=250,zW=2,BW=6e3,VW=2e6,HW=[];function UW(e,t,n,r,i,a){let o=!!e&&e.columnSet.has(n),s=St(()=>e&&o?t.filter(t=>e.columnSet.has(t)):HW,[e,o,t]),c=e&&o&&s.length>0?e.source:null,l=!!c&&!e?.live&&!!c.getSeriesMultiSync&&!!c.xBoundsSync,u=St(()=>l&&c?c.xBoundsSync(n):null,[l,c,n]),[d,f]=Ct(null),p=!!e?.live;W(()=>{if(!c||l)return;let e=!0,t=()=>c.xBounds(n).then(t=>{let r=c.version?.()??0;e&&f(e=>e&&e.source===c&&e.xKey===n&&e.ver===r?e:{source:c,xKey:n,b:t,ver:r})}).catch(()=>{});t();let r=p?setInterval(t,RW):void 0;return()=>{e=!1,clearInterval(r)}},[c,n,p,l]);let m=d&&d.source===c&&d.xKey===n?d:null,h=u??m?.b??null,_=m?.ver??0,{points:v,loading:y,full:x}=LW(c,s,c&&h&&h.x1>h.x0?{xKey:n,x0:h.x0,x1:h.x1}:null,Math.min(BW,i*zW),_,l,a),S=e?.xOffset??0,w=r&&r[1]>r[0]?r[0]-S:null,T=r&&r[1]>r[0]?r[1]-S:null,E=x||!!h&&w!==null&&T!==null&&w<=h.x0&&T>=h.x1,{points:D,fetchedViewport:O}=LW(c,s,c&&w!==null&&T!==null&&!E?{xKey:n,x0:w,x1:T}:null,i,_,l,a),k=St(()=>!O||D.length===0?v:g([b(v,e=>e<O.x0),D,b(v,e=>e>O.x1)]),[v,D,O]),A=!!c&&(h===null||y);return St(()=>e?{points:R(k,e.keySuffix,e.xOffset),bounds:h?{x0:h.x0+e.xOffset,x1:h.x1+e.xOffset}:null,loading:A}:{points:C,bounds:null,loading:!1},[e,k,h,A])}var WW=new WeakMap,GW=0;function KW(e){if(e.key!==void 0)return e.key;let t=WW.get(e.source);return t===void 0&&WW.set(e.source,t=GW++),`${t}${e.keySuffix}`}function qW(){let[e,t]=Ct(()=>new Map);return[e,yt((e,n)=>t(t=>{if(n?t.get(e)===n:!t.has(e))return t;let r=new Map(t);return n?r.set(e,n):r.delete(e),r}),[])]}var JW=_t(function({id:e,layer:t,columns:n,xKey:r,view:i,mp:a,rawLimit:o,report:s}){let c=UW(t,n,r,i,a,o);return G(()=>{s(e,c)},[e,c,s]),G(()=>()=>s(e,null),[e,s]),null});function YW({layers:e,xKey:t,columns:n,maxPoints:r,...i}){let a=i.viewXRange??null,[o,s]=Ct(null),c=typeof window<`u`?Math.min(3,Math.max(1,window.devicePixelRatio||1)):1,l=o==null?r:Math.min(r,Math.round(o*c/50)*50),u=Math.max(1e3,Math.round(l/Math.sqrt(Math.max(1,e.length)))),d=Math.floor(VW/Math.max(1,e.length)),[f,p]=qW(),m=St(()=>e.map(KW),[e]),h=St(()=>m.map(e=>f.get(e)),[m,f]),g=St(()=>h.flatMap(e=>e&&e.points.length>0?[e.points]:[]),[h]),_=St(()=>{let e=1/0,t=-1/0;for(let n of h){let r=n?.bounds;r&&(e=Math.min(e,r.x0),t=Math.max(t,r.x1))}return Number.isFinite(e)&&t>e?[e,t]:null},[h]),v=h.some(e=>!e||e.loading);return Ot(Dt,{children:[e.map((e,r)=>q(JW,{id:m[r],layer:e,columns:n,xKey:t,view:a,mp:u,rawLimit:d,report:p},m[r])),g.length===0?Ot(`div`,{className:`chart-placeholder chart-placeholder--no-data`,onContextMenu:e=>{e.preventDefault(),i.onPlotContextMenu?.({clientX:e.clientX,clientY:e.clientY})},children:[q(`span`,{className:`content-empty-icon`,"aria-hidden":!0}),q(`h2`,{children:v?`Loading…`:`No data to plot`}),v?null:q(`p`,{children:`None of the selected datasets has this X column together with a plotted channel.`})]}):q(OW,{points:g,fullXRange:_,...i,onPlotWidthCss:s})]})}function XW(e){return!!e&&!Array.isArray(e)&&typeof e.length==`number`&&`x`in e&&`y`in e}function ZW(e){let t=e.length,n=new Float64Array(t),r=new Float64Array(t),i=t>0&&e[0].c!==void 0?new Float32Array(t):void 0,a=e.some(e=>e.d!==void 0)?new Uint8Array(t):void 0;for(let o=0;o<t;o++){let t=e[o];n[o]=t.x,r[o]=t.y,i&&(i[o]=t.c??0),a&&(a[o]=t.d??0)}return{length:t,x:n,y:r,c:i,d:a}}function QW(e,t,n){let r=n?.get(t);if(r)return r;let i=ve(e);if(i)return pe(i,t);if(e.length===0||!(t in e[0]))return;let a=new Float64Array(e.length);for(let n=0;n<e.length;n++){let r=e[n][t];a[n]=typeof r==`number`?r:NaN}return a}function $W(e,t,n){let r=QW(e,t,n);if(!r||j.has(r))return r;let i=0;for(let e=0;e<r.length;e++)r[e]-r[e]===0&&i++;if(i===r.length)return r;let a=new Float64Array(i);for(let e=0,t=0;e<r.length;e++)r[e]-r[e]===0&&(a[t++]=r[e]);return a}function eG(e,t,n,r){if(!n){let n=$W(e,t,r);return n?[{label:t,values:n}]:[]}let i=QW(e,t,r);if(!i)return[];let a=i.length,o=r?.has(n)||e.length>0&&typeof e[0][n]==`number`?QW(e,n,r):void 0,s=t=>{if(o){let e=o[t];return e===e?String(e):`unknown`}return String(e[t]?.[n]??`unknown`)},c=new Map,l=[],u=new Int32Array(a),d=[];for(let e=0;e<a;e++){if(i[e]-i[e]!==0){u[e]=-1;continue}let t=s(e),n=c.get(t);n===void 0&&(c.set(t,n=l.length),l.push(t),d.push(0)),u[e]=n,d[n]++}let f=l.map((e,t)=>({label:e,values:new Float64Array(d[t])})),p=new Int32Array(l.length);for(let e=0;e<a;e++){let t=u[e];t>=0&&(f[t].values[p[t]++]=i[e])}return f}function tG(e){let t=NaN,n=NaN,r=0;for(let i=0;i<e.length;i++){let a=e[i];a-a===0&&(r===0&&(t=a),n=a,r++)}let i=n-t;return r>1&&i>0?(r-1)/i:null}function nG(e,t,n){let r=0;for(let i=0;i<e.length;i++)e[i]>=t&&e[i]<=n&&r++;let i=new Uint32Array(r),a=0;for(let r=0;r<e.length;r++)e[r]>=t&&e[r]<=n&&(i[a++]=r);return i}function rG(e,t){let n=new Float64Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n}function iG(e,t,n,r){let i=QW(e.rows,t,e.full),a=QW(e.rows,n,e.full);if(!i||!a)return null;let o=r.colorCol?QW(e.rows,r.colorCol,e.full):void 0;if(r.viewXRange){let t=QW(e.rows,r.xKey,e.full);if(t){let e=nG(t,r.viewXRange[0],r.viewXRange[1]);i=rG(i,e),a=rG(a,e),o&&=rG(o,e)}}let s=Math.min(i.length,a.length);if(!o)return{cols:{length:s,x:i,y:a}};let c=1/0,l=-1/0;for(let e=0;e<s;e++){let t=o[e];t<c&&(c=t),t>l&&(l=t)}if(!(l>c))return{cols:{length:s,x:i,y:a}};let u=new Float32Array(s),d=l-c;for(let e=0;e<s;e++){let t=o[e];u[e]=t===t?(t-c)/d:0}return{cols:{length:s,x:i,y:a,c:u},color:{label:r.colorCol,min:c,max:l}}}function aG(e,t,n,r){let i=[],a=[];e.forEach((e,o)=>{a.push(iB(r.colorOverrides,e.id,o,r.palette));let s=iG(e,t,n,{xKey:r.xKey,viewXRange:r.viewXRange});i.push(s?.cols??{length:0,x:[],y:[]})});let o=i.reduce((e,t)=>e+t.length,0),s=new Float64Array(o),c=new Float64Array(o),l=new Uint8Array(o),u=0;return i.forEach((e,t)=>{for(let t=0;t<e.length;t++)s[u+t]=e.x[t],c[u+t]=e.y[t];l.fill(Math.min(t,255),u,u+e.length),u+=e.length}),{cols:{length:o,x:s,y:c,d:l},colors:a}}var oG=e=>XW(e)?e:ZW(e),sG=(e,t,n)=>t===t&&n===n&&(!e||t>=e.xmin&&t<=e.xmax&&n>=e.ymin&&n<=e.ymax);function cG(e,t,n){let r=t+1,i=Array.from({length:r},()=>Array(r).fill(0)),a=Array(r).fill(0),o=new Float64Array(2*r-1),s=0;for(let t=0;t<e.length;t++){let c=e.x[t],l=e.y[t];if(sG(n,c,l)){s++,o[0]=1;for(let e=1;e<o.length;e++)o[e]=o[e-1]*c;for(let e=0;e<r;e++){for(let t=0;t<r;t++)i[e][t]+=o[e+t];a[e]+=o[e]*l}}}if(s<r)return null;let c=i.map((e,t)=>[...e,a[t]]);for(let e=0;e<r;e++){let t=e;for(let n=e+1;n<r;n++)Math.abs(c[n][e])>Math.abs(c[t][e])&&(t=n);if([c[e],c[t]]=[c[t],c[e]],Math.abs(c[e][e])<1e-10)return null;let n=c[e][e];for(let t=e;t<=r;t++)c[e][t]/=n;for(let t=0;t<r;t++){if(t===e)continue;let n=c[t][e];for(let i=e;i<=r;i++)c[t][i]-=n*c[e][i]}}return c.map(e=>e[r])}function lG(e,t,n){return cG(oG(e),t,n)}function uG(e,t){let n=oG(e),r=0,i=0;for(let e=0;e<n.length;e++)sG(void 0,n.x[e],n.y[e])&&(r++,i+=n.y[e]);if(r===0)return 0;let a=i/r,o=0,s=0;for(let e=0;e<n.length;e++){let r=n.x[e],i=n.y[e];if(!sG(void 0,r,i))continue;let c=0;for(let e=t.length-1;e>=0;e--)c=c*r+t[e];o+=(i-a)**2,s+=(i-c)**2}return o<1e-15?1:Math.max(0,1-s/o)}function dG(e,t=4){if(!Number.isFinite(e))return`?`;let n=Math.abs(e);return n===0?`0`:n>=1e5||n>0&&n<.001?e.toExponential(2):e.toPrecision(t).replace(/\.?0+$/,``)}function fG(e,t,n){let r=[];for(let n=e.length-1;n>=0;n--){let i=e[n];n===0?r.push(dG(i)):n===1?r.push(`${dG(i)}·${t}`):r.push(`${dG(i)}·${t}${n>1?`^${n}`:``}`)}return`${n} = ${r.join(` + `).replace(/\+ -/g,`− `)}`}var pG=[[0,45,80,160],[.25,40,145,175],[.5,60,180,110],[.75,220,175,55],[1,210,75,55]];function mG(e){let t=0;for(let n=1;n<pG.length;n++){if(e<=pG[n][0]){t=n-1;break}n===pG.length-1&&(t=n-1)}let n=t+1,r=(e-pG[t][0])/(pG[n][0]-pG[t][0]);return{r:Math.round(pG[t][1]+r*(pG[n][1]-pG[t][1])),g:Math.round(pG[t][2]+r*(pG[n][2]-pG[t][2])),b:Math.round(pG[t][3]+r*(pG[n][3]-pG[t][3]))}}function hG(e){let{r:t,g:n,b:r}=mG(e);return`rgb(${t},${n},${r})`}function gG(e,t){if(!Number.isFinite(e))return 0;let n=Math.floor(e*t);return n<0?0:n>=t?t-1:n}var _G=`#version 300 es
|
|
208
208
|
in vec2 a_corner;
|
|
209
209
|
in float a_x;
|
|
210
210
|
in float a_y;
|
|
@@ -229,7 +229,7 @@ void main() {
|
|
|
229
229
|
v_tex = (clamp(floor(a_k * u_kScale + 0.5), 0.0, 255.0) + 0.5) / 256.0;
|
|
230
230
|
vec2 clip = pos / u_resolution * 2.0 - 1.0;
|
|
231
231
|
gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);
|
|
232
|
-
}`,
|
|
232
|
+
}`,vG=`#version 300 es
|
|
233
233
|
precision highp float;
|
|
234
234
|
in vec2 v_local;
|
|
235
235
|
in float v_tex;
|
|
@@ -249,7 +249,7 @@ void main() {
|
|
|
249
249
|
vec4 c = texture(u_palette, vec2(v_tex, 0.5));
|
|
250
250
|
float a = c.a * u_alpha * cov;
|
|
251
251
|
outColor = vec4(c.rgb * a, a);
|
|
252
|
-
}`,
|
|
252
|
+
}`,yG=`#version 300 es
|
|
253
253
|
in float a_x;
|
|
254
254
|
in float a_y;
|
|
255
255
|
in float a_k;
|
|
@@ -268,7 +268,7 @@ void main() {
|
|
|
268
268
|
v_tex = (clamp(floor(a_k * u_kScale + 0.5), 0.0, 255.0) + 0.5) / 256.0;
|
|
269
269
|
vec2 clip = p / u_resolution * 2.0 - 1.0;
|
|
270
270
|
gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);
|
|
271
|
-
}`,
|
|
271
|
+
}`,bG=`#version 300 es
|
|
272
272
|
precision highp float;
|
|
273
273
|
in float v_tex;
|
|
274
274
|
uniform sampler2D u_palette;
|
|
@@ -287,7 +287,7 @@ void main() {
|
|
|
287
287
|
vec4 c = texture(u_palette, vec2(v_tex, 0.5));
|
|
288
288
|
float a = c.a * u_alpha * cov;
|
|
289
289
|
outColor = vec4(c.rgb * a, a);
|
|
290
|
-
}`,
|
|
290
|
+
}`,xG=`#version 300 es
|
|
291
291
|
in vec2 a_corner;
|
|
292
292
|
in float a_ax;
|
|
293
293
|
in float a_ay;
|
|
@@ -322,7 +322,7 @@ void main() {
|
|
|
322
322
|
v_tex = (clamp(floor(a_k * u_kScale + 0.5), 0.0, 255.0) + 0.5) / 256.0;
|
|
323
323
|
vec2 clip = pos / u_resolution * 2.0 - 1.0;
|
|
324
324
|
gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);
|
|
325
|
-
}`,
|
|
325
|
+
}`,SG=`#version 300 es
|
|
326
326
|
precision highp float;
|
|
327
327
|
flat in vec2 v_a;
|
|
328
328
|
flat in vec2 v_b;
|
|
@@ -343,7 +343,7 @@ void main() {
|
|
|
343
343
|
vec4 c = texture(u_palette, vec2(v_tex, 0.5));
|
|
344
344
|
float a = c.a * cov;
|
|
345
345
|
outColor = vec4(c.rgb * a, a);
|
|
346
|
-
}`,
|
|
346
|
+
}`,CG=`
|
|
347
347
|
uniform vec2 u_ox;
|
|
348
348
|
uniform vec2 u_oy;
|
|
349
349
|
float dbl(uvec2 b, vec2 o) {
|
|
@@ -357,21 +357,21 @@ float dbl(uvec2 b, vec2 o) {
|
|
|
357
357
|
float l = float(b.x & 0x1FFFFFFFu) * exp2(float(int(e) - 1075));
|
|
358
358
|
return (h - o.x) + ((sgn != 0u ? -l : l) - o.y);
|
|
359
359
|
}
|
|
360
|
-
`;function
|
|
361
|
-
`)}${c}`)}var
|
|
360
|
+
`;function wG(e,t,n,r){let i=CG,a=e,o=[];for(let[e,r]of[[t,`u_ox`],[n,`u_oy`]])for(let t of e)a=a.replace(`in float ${t};`,`in uvec2 ${t}_bits;`),o.push(` float ${t} = dbl(${t}_bits, ${r});`);let s=[...t,...n].map(e=>`${e} != ${e}`).join(` || `),c=r?`\n if (${s}) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; }`:``;return a.replace(`void main() {`,`${i}void main() {\n${o.join(`
|
|
361
|
+
`)}${c}`)}var TG=`#version 300 es
|
|
362
362
|
in uvec2 a_x_bits;
|
|
363
363
|
in uvec2 a_y_bits;
|
|
364
364
|
out float v_x;
|
|
365
365
|
out float v_y;
|
|
366
|
-
${
|
|
366
|
+
${CG}
|
|
367
367
|
void main() {
|
|
368
368
|
v_x = dbl(a_x_bits, u_ox);
|
|
369
369
|
v_y = dbl(a_y_bits, u_oy);
|
|
370
370
|
gl_Position = vec4(0.0);
|
|
371
|
-
}`,
|
|
371
|
+
}`,EG=`#version 300 es
|
|
372
372
|
precision mediump float;
|
|
373
373
|
out vec4 o;
|
|
374
|
-
void main() { o = vec4(0.0); }`;function EG(e,t,n,r){let i=QV(e,e.VERTEX_SHADER,t),a=QV(e,e.FRAGMENT_SHADER,n);if(!i||!a)return null;let o=e.createProgram();return e.attachShader(o,i),e.attachShader(o,a),r&&e.transformFeedbackVaryings(o,r,e.SEPARATE_ATTRIBS),e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)?{prog:o,shaders:[i,a]}:(console.error(`glPoints program link failed:`,e.getProgramInfoLog(o)),null)}function DG(e,t){if(!e)return[{v:0,a:0,b:t}];let n=[];for(let r=0;r<t;r++)r===0||e[r]!==e[r-1]?n.push({v:e[r],a:r,b:r+1}):n[n.length-1].b=r+1;return n}function OG(e,t,n,r,i,a){let o=[],s=0;for(let c of a){let a=n.filter(e=>e.v===c.v);if(a.length>1)return null;let l=-1;if(a.length===1){for(let n=a[0].a;n<a[0].b;n++)if(e[n]===r[c.a]&&t[n]===i[c.a]){l=n;break}}if(l<0){o.push({src:0,len:0});continue}let u=Math.min(a[0].b-l,c.b-c.a);for(let n=0;n<u;n++)if(e[l+n]!==r[c.a+n]||t[l+n]!==i[c.a+n])return null;o.push({src:l,len:u}),s+=u}return s>0?o:null}function kG(e){let t=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0});if(!t)return null;let n=uH(t,`glPoints|points`,()=>EG(t,gG,_G)),r=uH(t,`glPoints|lines`,()=>EG(t,bG,xG)),i=uH(t,`glPoints|points64`,()=>EG(t,CG(gG,[`a_x`],[`a_y`],!0),_G)),a=uH(t,`glPoints|sprites`,()=>EG(t,vG,yG)),o=uH(t,`glPoints|sprites64`,()=>EG(t,CG(vG,[`a_x`],[`a_y`],!0),yG)),s=uH(t,`glPoints|maxSprite`,()=>t.getParameter(t.ALIASED_POINT_SIZE_RANGE)[1]),c=uH(t,`glPoints|decode`,()=>EG(t,wG,TG,[`v_x`,`v_y`])),l=t.createVertexArray();if(!n||!r)return null;let u=(e,n)=>Object.fromEntries(n.map(n=>[n,t.getAttribLocation(e,n)])),d=(e,n)=>Object.fromEntries(n.map(n=>[n,t.getUniformLocation(e,n)])),f=u(n.prog,[`a_corner`,`a_x`,`a_y`,`a_k`,`a_r`]),p=d(n.prog,[`u_resolution`,`u_plot`,`u_view`,`u_radius`,`u_kScale`,`u_palette`,`u_alpha`,`u_clip`,`u_dpr`,`u_height`]),m=u(r.prog,[`a_corner`,`a_ax`,`a_ay`,`a_bx`,`a_by`,`a_bstart`,`a_k`]),h=d(r.prog,[`u_resolution`,`u_plot`,`u_view`,`u_ext`,`u_kScale`,`u_palette`,`u_half`,`u_clip`]),g=i&&u(i.prog,[`a_corner`,`a_x_bits`,`a_y_bits`,`a_k`,`a_r`]),_=i&&d(i.prog,[`u_resolution`,`u_plot`,`u_view`,`u_radius`,`u_kScale`,`u_palette`,`u_alpha`,`u_clip`,`u_dpr`,`u_height`,`u_ox`,`u_oy`]),v=[`u_resolution`,`u_plot`,`u_view`,`u_radius`,`u_kScale`,`u_palette`,`u_alpha`,`u_clip`,`u_dpr`,`u_height`],y=a&&u(a.prog,[`a_x`,`a_y`,`a_k`]),b=a&&d(a.prog,v),x=o&&u(o.prog,[`a_x_bits`,`a_y_bits`,`a_k`]),S=o&&d(o.prog,[...v,`u_ox`,`u_oy`]),C=c&&u(c.prog,[`a_x_bits`,`a_y_bits`]),w=c&&d(c.prog,[`u_ox`,`u_oy`]),T=t.createTransformFeedback(),E=t.createVertexArray(),D=t.createBuffer(),O=t.createBuffer(),k=!1,A=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,A),t.bufferData(t.ARRAY_BUFFER,Float32Array.from([-1,-1,1,-1,-1,1,1,1]),t.STATIC_DRAW);let M=t.createBuffer(),N=t.createBuffer(),P=t.createBuffer(),F=t.createBuffer(),I=t.createBuffer(),L=t.createBuffer(),R=t.createBuffer(),z=t.createBuffer(),B=null,V=t.createTexture(),ee=0,te=!1,H=!1,ne=!1,re=0,ie=0,U=1,ae=1,oe=1,se=1.8,ce=.8,le=255,ue=!0,de=!1,fe=1,pe={xmin:0,xmax:1,ymin:0,ymax:1},me={left:0,top:0,width:1,height:1},he=new Float32Array,ge=new Float32Array,_e=new Float32Array,ve=new Uint8Array,ye=new Float32Array,be=new Map,xe=(e,n,r)=>{t.bindBuffer(t.ARRAY_BUFFER,e);let i=r*n.BYTES_PER_ELEMENT;i<=(be.get(e)??0)?t.bufferSubData(t.ARRAY_BUFFER,0,n,0,r):(t.bufferData(t.ARRAY_BUFFER,n.subarray(0,r),t.DYNAMIC_DRAW),be.set(e,i))},Se=(e,n,r,i,a,o)=>{let s=r.BYTES_PER_ELEMENT;if(t.bindBuffer(t.ARRAY_BUFFER,n),(be.get(n)??0)<o*s){let e=Math.ceil(o*1.25)*s;t.bufferData(t.ARRAY_BUFFER,e,t.DYNAMIC_DRAW),be.set(n,e)}t.bindBuffer(t.COPY_READ_BUFFER,e),t.bindBuffer(t.COPY_WRITE_BUFFER,n),i.forEach((e,n)=>{a[n].len&&t.copyBufferSubData(t.COPY_READ_BUFFER,t.COPY_WRITE_BUFFER,a[n].src*s,e.a*s,a[n].len*s)}),t.bindBuffer(t.COPY_READ_BUFFER,null),t.bindBuffer(t.COPY_WRITE_BUFFER,null),i.forEach((e,n)=>{let i=e.a+a[n].len;e.b>i&&t.bufferSubData(t.ARRAY_BUFFER,i*s,r,i,e.b-i)})},Ce=(e,n,r=0,i=t.FLOAT)=>{t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(e);let a=i===t.FLOAT?4:1;t.vertexAttribPointer(e,1,i,i!==t.FLOAT,a,r*a),t.vertexAttribDivisor(e,1)},we=(e,n,r=0)=>{t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(e),t.vertexAttribIPointer(e,2,t.UNSIGNED_INT,8,r*8),t.vertexAttribDivisor(e,1)},Te=e=>{t.bindBuffer(t.ARRAY_BUFFER,A),t.enableVertexAttribArray(e),t.vertexAttribPointer(e,2,t.FLOAT,!1,0,0),t.vertexAttribDivisor(e,0)};return{resize(t,n,r){U=Math.max(1,t),ae=Math.max(1,n),oe=r,e.width=Math.round(U*oe),e.height=Math.round(ae*oe)},setData(e,t,n,r=!1,i){let a=Math.min(e.length,t.length);he.length<a&&(he=new Float32Array(a),ge=new Float32Array(a)),te=!!n,H=!!i,n&&_e.length<a&&(_e=new Float32Array(a)),i&&ye.length<a&&(ye=new Float32Array(a)),de&&ve.length<a&&(ve=new Uint8Array(a)),re=0,ie=0;for(let n=0;n<a;n++)if(e[n]-e[n]===0&&t[n]-t[n]===0){re=e[n],ie=t[n];break}let o=j.has(e)&&j.has(t);if(ne=!!g&&!!c&&e instanceof Float64Array&&t instanceof Float64Array&&(o||!de),k=!1,ne){let o=e,s=t;if(n)for(let e=0;e<a;e++)_e[e]=n[e];let c=DG(n&&r?n:void 0,a),l=B&&(!n||r)?OG(B.x,B.y,B.runs,o,s,c):null;if(l?(Se(M,L,o,c,l,a),[M,L]=[L,M],Se(N,R,s,c,l,a),[N,R]=[R,N],n&&(Se(P,z,_e,c,l,a),[P,z]=[z,P])):(xe(M,o,a),xe(N,s,a),n&&xe(P,_e,a)),(!B||B.x.length<a)&&(B={x:new Float64Array(Math.ceil(a*1.25)),y:new Float64Array(Math.ceil(a*1.25)),runs:c,n:a}),B.x.set(o.subarray(0,a)),B.y.set(s.subarray(0,a)),B.runs=c,B.n=a,i){for(let e=0;e<a;e++)ye[e]=i[e];xe(I,ye,a)}if(de){if(ve.fill(0,0,a),a&&(ve[0]=255),n&&r)for(let e=1;e<a;e++)n[e]!==n[e-1]&&(ve[e]=255);xe(F,ve,a)}ee=a;return}B=null;let s=0;if(j.has(e)&&j.has(t)){for(let t=0;t<a;t++)he[t]=e[t]-re;for(let e=0;e<a;e++)ge[e]=t[e]-ie;if(n)for(let e=0;e<a;e++)_e[e]=n[e];if(i)for(let e=0;e<a;e++)ye[e]=i[e];if(de&&(ve.fill(0,0,a),a&&(ve[0]=255),n&&r))for(let e=1;e<a;e++)n[e]!==n[e-1]&&(ve[e]=255);s=a}else{let o=!0;for(let c=0;c<a;c++){let a=e[c],l=t[c];if(a-a!==0||l-l!==0){o=!0;continue}he[s]=a-re,ge[s]=l-ie,n&&(_e[s]=n[c]),i&&(ye[s]=i[c]),de&&(ve[s]=o||r&&n&&s>0&&n[c]!==_e[s-1]?255:0),o=!1,s++}}ee=s,xe(M,he,s),xe(N,ge,s),n&&xe(P,_e,s),i&&xe(I,ye,s),de&&xe(F,ve,s)},setStyle(e,n,r){se=n,ce=r;let i=new Uint8Array(256*4);if(e.kind===`single`){let t=e.rgba.map(e=>Math.round(e*255));for(let e=0;e<256;e++)i.set(t,e*4);le=0}else i.set(e.palette.subarray(0,256*4)),le=e.kind===`colormap`?255:1;t.bindTexture(t.TEXTURE_2D,V),t.texImage2D(t.TEXTURE_2D,0,t.RGBA8,256,1,0,t.RGBA,t.UNSIGNED_BYTE,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)},setDraw(e,t,n){ue=e,de=t,fe=n},setView(e,t,n,r,i){pe={xmin:e,xmax:t,ymin:n,ymax:r},me=i},render(){if(t.bindFramebuffer(t.FRAMEBUFFER,null),t.viewport(0,0,e.width,e.height),t.disable(t.SCISSOR_TEST),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),ee===0)return;t.bindVertexArray(l),t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,V);let u=te?le:0,d=[pe.xmin-re,pe.xmax-re,pe.ymin-ie,pe.ymax-ie],v=[me.left,me.top,me.left+me.width,me.top+me.height],A=e=>{let t=Math.fround(e);return[t,e-t]},j=ne,L=M,R=N;if(ne&&de&&ee>1){if(!k){for(let e of[D,O])t.bindBuffer(t.ARRAY_BUFFER,e),(be.get(e)??0)<ee*4&&(t.bufferData(t.ARRAY_BUFFER,ee*4,t.DYNAMIC_COPY),be.set(e,ee*4));t.bindBuffer(t.ARRAY_BUFFER,null),t.bindVertexArray(E),t.useProgram(c.prog),t.uniform2f(w.u_ox,...A(re)),t.uniform2f(w.u_oy,...A(ie)),we(C.a_x_bits,M),we(C.a_y_bits,N),t.vertexAttribDivisor(C.a_x_bits,0),t.vertexAttribDivisor(C.a_y_bits,0),t.enable(t.RASTERIZER_DISCARD),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,T),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,0,D),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,1,O),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,0,ee),t.endTransformFeedback(),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,0,null),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,1,null),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null),t.disable(t.RASTERIZER_DISCARD),t.bindVertexArray(l),k=!0}j=!1,L=D,R=O}if(de&&ee>1){let e=h,n=m;t.useProgram(r.prog),t.uniform2f(e.u_resolution,U,ae),t.uniform4f(e.u_plot,me.left,me.top,me.width,me.height),t.uniform4f(e.u_view,...d),t.uniform1f(e.u_half,fe/2),t.uniform1f(e.u_ext,fe/2+1),t.uniform1f(e.u_kScale,u),t.uniform4f(e.u_clip,...v),t.uniform1i(e.u_palette,0),Te(n.a_corner),Ce(n.a_ax,L,0),Ce(n.a_bx,L,1),Ce(n.a_ay,R,0),Ce(n.a_by,R,1),Ce(n.a_bstart,F,1,t.UNSIGNED_BYTE),te?Ce(n.a_k,P,0):(t.disableVertexAttribArray(n.a_k),t.vertexAttrib1f(n.a_k,0)),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,ee-1);for(let e of Object.values(n))t.vertexAttribDivisor(e,0)}if(ue&&!H&&2*(se+.5)*oe<=s&&(j?o:a)){let n=j?S:b,r=j?x:y;t.useProgram((j?o:a).prog),j&&(t.uniform2f(n.u_ox,...A(re)),t.uniform2f(n.u_oy,...A(ie))),t.uniform2f(n.u_resolution,U,ae),t.uniform4f(n.u_plot,me.left,me.top,me.width,me.height),t.uniform4f(n.u_view,...d),t.uniform1f(n.u_radius,se),t.uniform1f(n.u_kScale,u),t.uniform1f(n.u_alpha,ce),t.uniform4f(n.u_clip,...v),t.uniform1f(n.u_dpr,oe),t.uniform1f(n.u_height,e.height),t.uniform1i(n.u_palette,0),j?(we(r.a_x_bits,M),we(r.a_y_bits,N)):(Ce(r.a_x,L),Ce(r.a_y,R)),te?Ce(r.a_k,P):(t.disableVertexAttribArray(r.a_k),t.vertexAttrib1f(r.a_k,0));for(let e of Object.values(r))t.vertexAttribDivisor(e,0);t.drawArrays(t.POINTS,0,ee)}else if(ue){let r=j?_:p,a=j?g:f;t.useProgram(j?i.prog:n.prog),j&&(t.uniform2f(r.u_ox,...A(re)),t.uniform2f(r.u_oy,...A(ie))),t.uniform2f(r.u_resolution,U,ae),t.uniform4f(r.u_plot,me.left,me.top,me.width,me.height),t.uniform4f(r.u_view,...d),t.uniform1f(r.u_radius,se),t.uniform1f(r.u_kScale,u),t.uniform1f(r.u_alpha,ce),t.uniform4f(r.u_clip,...v),t.uniform1f(r.u_dpr,oe),t.uniform1f(r.u_height,e.height),t.uniform1i(r.u_palette,0),Te(a.a_corner),j?(we(a.a_x_bits,M),we(a.a_y_bits,N)):(Ce(a.a_x,L),Ce(a.a_y,R)),te?Ce(a.a_k,P):(t.disableVertexAttribArray(a.a_k),t.vertexAttrib1f(a.a_k,0)),H?Ce(a.a_r,I):(t.disableVertexAttribArray(a.a_r),t.vertexAttrib1f(a.a_r,0)),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,ee);for(let e of Object.values(a))t.vertexAttribDivisor(e,0)}t.bindVertexArray(null)},dispose(){for(let e of[A,M,N,P,F,I,D,O,L,R,z])t.deleteBuffer(e);t.deleteTransformFeedback(T),t.deleteVertexArray(E),t.deleteTexture(V),t.deleteVertexArray(l)}}}var AG={top:3,right:3,bottom:3,left:3};function jG(e,t,n){return t<200||n<120?{...AG,tiny:!0}:{...e,tiny:!1}}var MG={top:14,right:24,bottom:40,left:78},NG=70,PG=6,FG=8,IG=1.8;function LG(e,t,n){return Math.min(n,Math.max(t,e))}function RG(e,t){let n=e[t],r=1/0,i=-1/0;for(let t=0;t<e.length;t++){let e=n[t];e<r&&(r=e),e>i&&(i=e)}(!Number.isFinite(r)||r===i)&&(--r,i+=1);let a=(i-r)*.04;return{min:r-a,max:i+a}}function zG(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}function BG({points:e,xLabel:t,yLabel:n,color:r=`#38bdf8`,datasetColors:i,colorLabel:a,colorRange:o,height:s=400,pointRadius:c=IG,drawMode:l=`points`,lineWidth:u=1,backgroundToken:d=``,onPlotContextMenu:f,xAxisLine:p,yAxisLine:m,gridLine:h,fitSettings:g,xScale:_,yScale:v}){let y=FU(),b=K(null),x=K(null),S=K(null),C=K(f);G(()=>{C.current=f},[f]);let w=K(null),T=K(null),E=K(null),D=K(null),O=K(null),k=K(0),A=K(null),j=St(()=>YW(e)?e:XW(e),[e]),M=K({cols:j,xLabel:t,yLabel:n,color:r,datasetColors:i,colorLabel:a,colorRange:o,height:s,pointRadius:c,drawMode:l,lineWidth:u,xAxisLine:p,yAxisLine:m,gridLine:h,fitSettings:g,xScale:_,yScale:v});G(()=>{M.current={cols:j,xLabel:t,yLabel:n,color:r,datasetColors:i,colorLabel:a,colorRange:o,height:s,pointRadius:c,drawMode:l,lineWidth:u,xAxisLine:p,yAxisLine:m,gridLine:h,fitSettings:g,xScale:_,yScale:v}},[j,t,n,r,i,a,o,s,c,l,u,p,m,h,g,_,v]);let N=K({cols:null,value:{x:{min:0,max:1},y:{min:0,max:1}}});function P(){let e=M.current.cols,t=N.current;return t.cols!==e&&(t.value={x:RG(e,`x`),y:RG(e,`y`)},t.cols=e),t.value}W(()=>{T.current=null,E.current=null,D.current=null,O.current=null},[t,n]);function F(){let e=P(),t=T.current,n=E.current,r=D.current,i=O.current;return{xmin:t!==null&&n!==null&&n>t?t:e.x.min,xmax:t!==null&&n!==null&&n>t?n:e.x.max,ymin:r!==null&&i!==null&&i>r?r:e.y.min,ymax:r!==null&&i!==null&&i>r?i:e.y.max}}function I(){if(T.current!==null||D.current!==null)return F();let{xScale:e,yScale:t}=M.current,n=e=>{if(!e)return null;let t=parseFloat(e.scaleMin),n=parseFloat(e.scaleMax);return Number.isFinite(t)&&Number.isFinite(n)&&t<n?{min:t,max:n}:null},r=n(e)??P().x,i=n(t)??P().y;return{xmin:r.min,xmax:r.max,ymin:i.min,ymax:i.max}}function L(){if(A.current)return A.current;let e=S.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`,accent:`#f97316`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`,accent:t.getPropertyValue(`--accent`).trim()||`#f97316`};return A.current=n,n}function R(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function z(){let e=S.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||M.current.height)}}let B=K(null),V=K(null),ee=K({r:null,failed:!1,data:null,mode:``,style:``,size:``});function te(e,t){let n=ee.current;!n.r&&!n.failed&&V.current&&(n.r=dH(V.current,kG),n.failed=!n.r);let r=n.r;if(!r||!V.current)return null;let{cols:i,color:a,datasetColors:o,pointRadius:s,drawMode:c,lineWidth:l}=M.current,u=Math.min(2,window.devicePixelRatio||1),d=`${e}x${t}@${u}`;n.size!==d&&(r.resize(e,t,u),V.current.style.width=`${e}px`,V.current.style.height=`${t}px`,n.size=d);let f=o&&o.length>0&&i.d?`dataset`:i.c?`colormap`:`single`,p=c!==`points`;r.setDraw(c!==`lines`,p,l),(n.data!==i||n.mode!==`${f}|${p}`)&&(r.setData(i.x,i.y,f===`dataset`?i.d:f===`colormap`?i.c:void 0,f===`dataset`),n.data=i,n.mode=`${f}|${p}`);let m=`${f}|${a}|${f===`dataset`?o.join(`,`):``}|${s}`;return n.style!==m&&(r.setStyle(HG(f,a,o),Math.max(.25,s),.8),n.style=m),r}W(()=>()=>{ee.current.r?.dispose(),ee.current.r=null},[]);let H=K({cols:null,key:``,coeffs:null});function ne(e,t,n){let r=`${t}|${n.xmin}|${n.xmax}|${n.ymin}|${n.ymax}`,i=H.current;return(i.cols!==e||i.key!==r)&&(H.current={cols:e,key:r,coeffs:cG(e,t,n)}),H.current.coeffs}let re=K({pts:null,view:``}),ie=K(``);function U(){let e=b.current;if(!e)return;let{w:t,h:n}=z(),r=R(e,t,n);if(!r)return;let{cols:i,xLabel:a,yLabel:o,color:s,datasetColors:c,colorLabel:l,colorRange:u,pointRadius:d,xAxisLine:f,yAxisLine:p,gridLine:m,fitSettings:h,xScale:g,yScale:_}=M.current,v=!!c&&c.length>0&&!!i.d,x=!v&&i.length>0&&!!i.c,C=jG(MG,t,n),w=C.tiny?C.right:x?NG:C.right,{top:T,bottom:E,left:D}=C,O=t-D-w,k=n-T-E,{bg:A,muted:j,grid:N,accent:P}=L(),F=Math.max(.25,d),V=te(t,n),ee=i.length>=1&&O>0&&k>0?I():null,H=[t,n,e.width,ee&&`${ee.xmin}|${ee.xmax}|${ee.ymin}|${ee.ymax}`,a,o,x,v,l,u?.join(),JSON.stringify([f,p,m,g,_]),A,j,N,P].join(`§`);if(V&&ee&&!h&&ie.current===H){let e=re.current;e.pts!==i&&(re.current={pts:i,view:e.view},BH(S.current)),V.setView(ee.xmin,ee.xmax,ee.ymin,ee.ymax,{left:D,top:T,width:O,height:k}),V.render();return}ie.current=H,r.fillStyle=A,r.fillRect(0,0,t,n);let U=B.current?R(B.current,t,n):null;U?.clearRect(0,0,t,n);let ae=V;if(i.length<1||O<=0||k<=0){ae?.render(),r.fillStyle=j,r.font=`13px ${Q.sans}`,UV(r);return}let{xmin:oe,xmax:se,ymin:ce,ymax:le}=I(),ue=se-oe,de=le-ce,fe=e=>D+(e-oe)/ue*O;y({left:D,top:T,width:O,height:k,x:{v0:oe,v1:se}});let pe=e=>T+(le-e)/de*k,me=(()=>{if(_?.majorStep){let e=parseFloat(_.majorStep);if(Number.isFinite(e)&&e>0)return e}return Pz(de,6)})(),he=Lz(ce,le,me);if((p?.style??`dashed`)!==`none`){r.strokeStyle=p?.color??N,r.lineWidth=p?.width??1,r.setLineDash(zG(p?.style??`dashed`));for(let e of he){let t=pe(e);r.beginPath(),r.moveTo(D,t),r.lineTo(D+O,t),r.stroke()}r.setLineDash([])}r.strokeStyle=j,r.lineWidth=1,r.fillStyle=j,r.font=`11px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of C.tiny?[]:he){let t=pe(e);r.beginPath(),r.moveTo(D-PG,t),r.lineTo(D,t),r.stroke(),r.fillText(Vz(e,me),D-FG,t)}let ge=(()=>{if(g?.majorStep){let e=parseFloat(g.majorStep);if(Number.isFinite(e)&&e>0)return e}return Pz(ue,Fz(O))})(),_e=Lz(oe,se,ge);if((f?.style??`dashed`)!==`none`){r.strokeStyle=f?.color??N,r.lineWidth=f?.width??1,r.setLineDash(zG(f?.style??`dashed`));for(let e of _e){let t=fe(e);r.beginPath(),r.moveTo(t,T),r.lineTo(t,T+k),r.stroke()}r.setLineDash([])}r.strokeStyle=j,r.lineWidth=1,r.fillStyle=j,r.textAlign=`center`,r.textBaseline=`top`;for(let e of C.tiny?[]:_e){let t=fe(e);r.beginPath(),r.moveTo(t,T+k),r.lineTo(t,T+k+PG),r.stroke(),r.fillText(Vz(e,ge),t,T+k+PG+2)}(m?.style??`solid`)!==`none`&&(r.strokeStyle=m?.color??N,r.lineWidth=m?.width??1,r.setLineDash(zG(m?.style??`solid`)),r.strokeRect(D,T,O,k),r.setLineDash([])),r.fillStyle=j,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,C.tiny||(r.fillText(a,D+O/2,n-4),r.save(),r.translate(14,T+k/2),r.rotate(-Math.PI/2),r.fillText(o,0,0),r.restore());let ve=re.current;if((ve.pts!==i||ve.view!==`${oe}|${se}|${ce}|${le}`)&&(re.current={pts:i,view:`${oe}|${se}|${ce}|${le}`},BH(S.current)),ae)ae.setView(oe,se,ce,le,{left:D,top:T,width:O,height:k}),ae.render();else{let e={xToPx:fe,yToPx:pe,left:D,top:T,plotW:O,plotH:k,dotR:F,col:s,dsColors:v?c:null,hasColormap:x};M.current.drawMode!==`points`&&WG(r,i,e,M.current.lineWidth),M.current.drawMode!==`lines`&&UG(r,i,e)}if(x&&!C.tiny){let e=D+O+10,n=k;for(let t=0;t<64;t++)r.fillStyle=mG(1-t/64),r.fillRect(e,T+t/64*n,10,n/64+1);r.strokeStyle=j,r.lineWidth=.5,r.strokeRect(e,T,10,n),r.fillStyle=j,r.font=`10px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`top`;let i=u?String(u[1].toPrecision(3)):`1`,a=u?String(u[0].toPrecision(3)):`0`;r.fillText(i,e+10+3,T),r.textBaseline=`bottom`,r.fillText(a,e+10+3,T+n),l&&(r.save(),r.textBaseline=`middle`,r.translate(t-6,T+n/2),r.rotate(Math.PI/2),r.fillText(l,0,0),r.restore())}if(h&&U){let e=ne(i,h.degree,{xmin:oe,xmax:se,ymin:ce,ymax:le});if(e){U.save(),U.beginPath(),U.rect(D,T,O,k),U.clip(),U.strokeStyle=h.color,U.lineWidth=h.width,U.setLineDash(zG(h.lineStyle)),U.beginPath();for(let t=0;t<=300;t++){let n=oe+t/300*ue,r=e.reduce((e,t,r)=>e+t*n**+r,0),i=fe(n),a=pe(r);t===0?U.moveTo(i,a):U.lineTo(i,a)}U.stroke(),U.setLineDash([]);let t=dG(e,`x`,`y`);U.fillStyle=P,U.font=`10px ${Q.mono}`,U.textAlign=`right`,U.textBaseline=`top`,U.fillText(t,D+O-8,T+8),U.restore()}}if((g?.alarm||_?.alarm)&&U){if(U.save(),U.beginPath(),U.rect(D,T,O,k),U.clip(),g?.alarm){let e=g.alarm;U.strokeStyle=e.color,U.lineWidth=e.width,U.setLineDash(e.linked===`active`?LU:zG(e.style));let t=fe(e.value);U.beginPath(),U.moveTo(t,T),U.lineTo(t,T+k),U.stroke(),U.setLineDash([]),e.linked&&zU(U,t+3,T+2,e.color)}if(_?.alarm){let e=_.alarm;U.strokeStyle=e.color,U.lineWidth=e.width,U.setLineDash(e.linked===`active`?LU:zG(e.style));let t=pe(e.value);U.beginPath(),U.moveTo(D,t),U.lineTo(D+O,t),U.stroke(),U.setLineDash([]),e.linked&&zU(U,D+O-10-3,t-10-2,e.color)}U.restore()}}let ae=K(``);function oe(){let e=x.current;if(!e)return;let{w:t,h:n}=z(),r=`${t}x${n}`;if(w.current===null&&ae.current===r)return;let i=R(e,t,n);if(!i)return;i.clearRect(0,0,t,n),ae.current=w.current===null?r:``;let a=w.current,{cols:o,color:s,datasetColors:c,pointRadius:l}=M.current;if(a===null||a>=o.length||o.length<1)return;let u=Math.max(4,l*2),d=o.d?.[a],f=c&&c.length>0&&d!==void 0?c[d]??s:s,{top:p,right:m,bottom:h,left:g}=jG(MG,t,n),_=t-g-m,v=n-p-h;if(_<=0||v<=0)return;let{xmin:y,xmax:b,ymin:S,ymax:C}=I(),T=b-y,E=C-S,D={x:o.x[a],y:o.y[a]},O=g+(D.x-y)/T*_,k=p+(C-D.y)/E*v,{bg:A,muted:j}=L();i.strokeStyle=j,i.globalAlpha=.4,i.lineWidth=1,i.setLineDash([3,3]),i.beginPath(),i.moveTo(O,p),i.lineTo(O,p+v),i.stroke(),i.beginPath(),i.moveTo(g,k),i.lineTo(g+_,k),i.stroke(),i.setLineDash([]),i.globalAlpha=1,i.fillStyle=f,i.beginPath(),i.arc(O,k,u,0,Math.PI*2),i.fill(),i.strokeStyle=A,i.lineWidth=1.5,i.beginPath(),i.arc(O,k,u,0,Math.PI*2),i.stroke();let N=`(${Hz(D.x)}, ${Hz(D.y)})`;i.font=`11px ${Q.mono}`;let P=i.measureText(N).width+12,F=O+10,B=k-24;F+P>g+_&&(F=O-P-10),B<p&&(B=k+10),i.fillStyle=A,i.globalAlpha=.85,i.beginPath(),VG(i,F,B,P,20,4),i.fill(),i.globalAlpha=1,i.strokeStyle=j,i.lineWidth=.5,i.beginPath(),VG(i,F,B,P,20,4),i.stroke(),i.fillStyle=j,i.textAlign=`left`,i.textBaseline=`middle`,i.fillText(N,F+6,B+20/2)}let se=K(U),ce=K(oe);G(()=>{se.current=U,ce.current=oe});let le=K(null);le.current??=GH(()=>{se.current(),ce.current()},()=>S.current);function ue(){le.current.schedule()}function de(){k.current||=LH(()=>{k.current=0,ce.current()})}W(()=>()=>{le.current?.cancel(),RH(k.current),k.current=0},[]);let fe=K(ue),pe=K(de);return G(()=>{fe.current=ue,pe.current=de}),W(()=>uB(S.current,()=>{A.current=null,fe.current()}),[]),W(()=>{A.current=null,fe.current()},[d]),W(()=>{le.current.now()},[e,t,n,r,i,s,c,l,u,p,m,h,g,_,v]),W(()=>{let e=x.current,t=S.current;if(!e||!t)return;let n=new UH(()=>{A.current=null,fe.current()});n.observe(t);let r=null;function i(e,t){let n=M.current.cols;if(n.length===0)return null;let{w:i,h:a}=z(),{top:o,right:s,bottom:c,left:l}=jG(MG,i,a),u=i-l-s,d=a-o-c,{xmin:f,xmax:p,ymin:m,ymax:h}=I(),g=p-f,_=h-m,v=Math.max(12,M.current.pointRadius*10),y=`${i}|${a}|${f}|${p}|${m}|${h}|${v}`;if(!r||r.cols!==n||r.key!==y){let e=Math.max(1,Math.ceil(u/v)),t=Math.max(1,Math.ceil(d/v)),i=t=>{let r=(n.x[t]-f)/g*u,i=(h-n.y[t])/_*d;return r>=0&&r<u&&i>=0&&i<d?Math.floor(i/v)*e+Math.floor(r/v):-1},a=new Uint32Array(e*t+1);for(let e=0;e<n.length;e++){let t=i(e);t>=0&&a[t+1]++}for(let n=0;n<e*t;n++)a[n+1]+=a[n];let o=a.slice(0,e*t),s=new Uint32Array(a[e*t]);for(let e=0;e<n.length;e++){let t=i(e);t>=0&&(s[o[t]++]=e)}r={cols:n,key:y,cell:v,nx:e,start:a,ix:s}}let b=r,x=Math.floor((e-l)/b.cell),S=Math.floor((t-o)/b.cell),C=(b.start.length-1)/b.nx,w=-1,T=v*v;for(let r=S-1;r<=S+1;r++)if(!(r<0||r>=C))for(let i=x-1;i<=x+1;i++){if(i<0||i>=b.nx)continue;let a=r*b.nx+i;for(let r=b.start[a];r<b.start[a+1];r++){let i=b.ix[r],a=l+(n.x[i]-f)/g*u,s=o+(h-n.y[i])/_*d,c=(a-e)**2+(s-t)**2;c<T&&(T=c,w=i)}}return w<0?null:w}let a=t=>{if(M.current.cols.length<1){w.current!==null&&(w.current=null,pe.current());return}let n=e.getBoundingClientRect(),r=t.clientX-n.left,a=t.clientY-n.top,{left:o,top:s,right:c,bottom:l}=jG(MG,n.width,n.height),u=Math.max(1,n.width-o-c),d=n.height-s-l;if(r<o||r>o+u||a<s||a>s+d){w.current!==null&&(w.current=null,pe.current());return}let f=i(r,a);w.current!==f&&(w.current=f,pe.current())},o=()=>{w.current!==null&&(w.current=null,pe.current())},s=t=>{if(M.current.cols.length<1)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,{top:a,left:o,right:s,bottom:c}=jG(MG,n.width,n.height),l=Math.max(1,n.width-o-s),u=Math.max(1,n.height-a-c);if(r<o||r>o+l||i<a||i>a+u)return;t.preventDefault();let d=P(),f=d.x.max-d.x.min,p=d.y.max-d.y.min,m=I(),h=m.xmin,g=m.xmax,_=m.ymin,v=m.ymax,y=g-h,b=v-_,x=(r-o)/l,S=(i-a)/u,C=h+x*y,w=v-S*b,k=t.deltaY<0,A=.88,j=k?A:1/A,N=y*j,F=b*j;if(!k&&N>=f*.999&&F>=p*.999){T.current=null,E.current=null,D.current=null,O.current=null,fe.current();return}N=LG(N,Math.max(f*1e-7,1e-12),f),F=LG(F,Math.max(p*1e-7,1e-12),p);let L=C-x*N,R=C+(1-x)*N;L<d.x.min&&(R+=d.x.min-L,L=d.x.min),R>d.x.max&&(L-=R-d.x.max,R=d.x.max);let z=w-(1-S)*F,B=w+S*F;z<d.y.min&&(B+=d.y.min-z,z=d.y.min),B>d.y.max&&(z-=B-d.y.max,B=d.y.max),T.current=L,E.current=R,D.current=z,O.current=B,fe.current()},c=e=>{e.button===0&&(T.current===null&&D.current===null||(T.current=null,E.current=null,D.current=null,O.current=null,fe.current(),pe.current()))},l=e=>{e.preventDefault(),C.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`mousemove`,a),e.addEventListener(`mouseleave`,o),e.addEventListener(`wheel`,s,{passive:!1}),e.addEventListener(`contextmenu`,l),e.addEventListener(`dblclick`,c),()=>{n.disconnect(),e.removeEventListener(`mousemove`,a),e.removeEventListener(`mouseleave`,o),e.removeEventListener(`wheel`,s),e.removeEventListener(`contextmenu`,l),e.removeEventListener(`dblclick`,c)}},[]),Ot(`div`,{ref:S,className:`chart-canvas-wrap`,children:[q(`canvas`,{ref:b,className:`chart-canvas`,role:`img`,"aria-label":`Scatter ${t} vs ${n}`}),q(`canvas`,{ref:V,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:B,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:x,className:`chart-canvas chart-overlay`})]})}function VG(e,t,n,r,i,a){e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.arcTo(t+r,n,t+r,n+a,a),e.lineTo(t+r,n+i-a),e.arcTo(t+r,n+i,t+r-a,n+i,a),e.lineTo(t+a,n+i),e.arcTo(t,n+i,t,n+i-a,a),e.lineTo(t,n+a),e.arcTo(t,n,t+a,n,a)}function HG(e,t,n){if(e===`single`)return{kind:`single`,rgba:qV(t)};let r=new Uint8Array(256*4);for(let t=0;t<256;t++)if(e===`colormap`){let{r:e,g:n,b:i}=pG(t/255);r.set([e,n,i,255],t*4)}else{let e=qV(n[Math.min(t,n.length-1)]);r.set([e[0]*255,e[1]*255,e[2]*255,e[3]*255],t*4)}return{kind:e===`colormap`?`colormap`:`dataset`,palette:r}}function UG(e,t,n){let r=Math.PI*2,i=n.dsColors?n.dsColors.length:n.hasColormap?24:1,a=Array.from({length:i},()=>new Path2D);for(let e=0;e<t.length;e++){let o=n.xToPx(t.x[e]),s=n.yToPx(t.y[e]);if(!(o>=n.left&&o<=n.left+n.plotW&&s>=n.top&&s<=n.top+n.plotH))continue;let c=n.dsColors?Math.min(t.d?.[e]??0,i-1):n.hasColormap?hG(t.c?.[e]??0,24):0;a[c].moveTo(o+n.dotR,s),a[c].arc(o,s,n.dotR,0,r)}e.globalAlpha=.8;for(let t=0;t<i;t++)e.fillStyle=n.dsColors?n.dsColors[t]:n.hasColormap?mG((t+.5)/24):n.col,e.fill(a[t]);e.globalAlpha=1}function WG(e,t,n,r){e.save(),e.beginPath(),e.rect(n.left,n.top,n.plotW,n.plotH),e.clip(),e.lineWidth=r;let i=n.dsColors?n.dsColors.length:1;for(let r=0;r<i;r++){e.beginPath();let i=!1;for(let a=0;a<t.length;a++){if(n.dsColors&&(t.d?.[a]??0)!==r){i=!1;continue}let o=t.x[a],s=t.y[a];if(o-o!==0||s-s!==0){i=!1;continue}i?e.lineTo(n.xToPx(o),n.yToPx(s)):(e.moveTo(n.xToPx(o),n.yToPx(s)),i=!0)}e.strokeStyle=n.dsColors?n.dsColors[r]:n.col,e.stroke()}e.restore()}var GG=11102230246251565e-32,KG=134217729,qG=(3+8*GG)*GG;function JG(e,t,n,r,i){let a,o,s,c,l=t[0],u=r[0],d=0,f=0;u>l==u>-l?(a=l,l=t[++d]):(a=u,u=r[++f]);let p=0;if(d<e&&f<n)for(u>l==u>-l?(o=l+a,s=a-(o-l),l=t[++d]):(o=u+a,s=a-(o-u),u=r[++f]),a=o,s!==0&&(i[p++]=s);d<e&&f<n;)u>l==u>-l?(o=a+l,c=o-a,s=a-(o-c)+(l-c),l=t[++d]):(o=a+u,c=o-a,s=a-(o-c)+(u-c),u=r[++f]),a=o,s!==0&&(i[p++]=s);for(;d<e;)o=a+l,c=o-a,s=a-(o-c)+(l-c),l=t[++d],a=o,s!==0&&(i[p++]=s);for(;f<n;)o=a+u,c=o-a,s=a-(o-c)+(u-c),u=r[++f],a=o,s!==0&&(i[p++]=s);return(a!==0||p===0)&&(i[p++]=a),p}function YG(e,t){let n=t[0];for(let r=1;r<e;r++)n+=t[r];return n}function $(e){return new Float64Array(e)}var XG=(3+16*GG)*GG,ZG=(2+12*GG)*GG,QG=(9+64*GG)*GG*GG,$G=$(4),eK=$(8),tK=$(12),nK=$(16),rK=$(4);function iK(e,t,n,r,i,a,o){let s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T=e-i,E=n-i,D=t-a,O=r-a;b=T*O,f=KG*T,p=f-(f-T),m=T-p,f=KG*O,h=f-(f-O),g=O-h,x=m*g-(b-p*h-m*h-p*g),S=D*E,f=KG*D,p=f-(f-D),m=D-p,f=KG*E,h=f-(f-E),g=E-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,$G[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,$G[1]=y-(_+d)+(d-S),w=v+_,d=w-v,$G[2]=v-(w-d)+(_-d),$G[3]=w;let k=YG(4,$G),A=ZG*o;if(k>=A||-k>=A||(d=e-T,s=e-(T+d)+(d-i),d=n-E,l=n-(E+d)+(d-i),d=t-D,c=t-(D+d)+(d-a),d=r-O,u=r-(O+d)+(d-a),s===0&&c===0&&l===0&&u===0)||(A=QG*o+qG*Math.abs(k),k+=T*u+O*s-(D*l+E*c),k>=A||-k>=A))return k;b=s*O,f=KG*s,p=f-(f-s),m=s-p,f=KG*O,h=f-(f-O),g=O-h,x=m*g-(b-p*h-m*h-p*g),S=c*E,f=KG*c,p=f-(f-c),m=c-p,f=KG*E,h=f-(f-E),g=E-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,rK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,rK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,rK[2]=v-(w-d)+(_-d),rK[3]=w;let j=JG(4,$G,4,rK,eK);b=T*u,f=KG*T,p=f-(f-T),m=T-p,f=KG*u,h=f-(f-u),g=u-h,x=m*g-(b-p*h-m*h-p*g),S=D*l,f=KG*D,p=f-(f-D),m=D-p,f=KG*l,h=f-(f-l),g=l-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,rK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,rK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,rK[2]=v-(w-d)+(_-d),rK[3]=w;let M=JG(j,eK,4,rK,tK);return b=s*u,f=KG*s,p=f-(f-s),m=s-p,f=KG*u,h=f-(f-u),g=u-h,x=m*g-(b-p*h-m*h-p*g),S=c*l,f=KG*c,p=f-(f-c),m=c-p,f=KG*l,h=f-(f-l),g=l-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,rK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,rK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,rK[2]=v-(w-d)+(_-d),rK[3]=w,nK[JG(M,tK,4,rK,nK)-1]}function aK(e,t,n,r,i,a){let o=(t-a)*(n-i),s=(e-i)*(r-a),c=o-s,l=Math.abs(o+s);return Math.abs(c)>=XG*l?c:-iK(e,t,n,r,i,a,l)}(7+56*GG)*GG,(3+28*GG)*GG,(26+288*GG)*GG*GG,$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(8),$(8),$(8),$(4),$(8),$(8),$(16),$(12),$(192),$(192),(10+96*GG)*GG,(4+48*GG)*GG,(44+576*GG)*GG*GG,$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(8),$(8),$(8),$(8),$(8),$(8),$(8),$(8),$(8),$(4),$(4),$(4),$(8),$(16),$(16),$(16),$(32),$(32),$(48),$(64),$(1152),$(1152),(16+224*GG)*GG,(5+72*GG)*GG,(71+1408*GG)*GG*GG,$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(24),$(24),$(24),$(24),$(24),$(24),$(24),$(24),$(24),$(24),$(1152),$(1152),$(1152),$(1152),$(1152),$(2304),$(2304),$(3456),$(5760),$(8),$(8),$(8),$(16),$(24),$(48),$(48),$(96),$(192),$(384),$(384),$(384),$(768),$(96),$(96),$(96),$(1152);var oK=2**-52,sK=new Uint32Array(512),cK=class e{static from(t,n=gK,r=_K){let i=t.length,a=new Float64Array(i*2);for(let e=0;e<i;e++){let i=t[e];a[2*e]=n(i),a[2*e+1]=r(i)}return new e(a)}constructor(e){let t=e.length>>1;if(t>0&&typeof e[0]!=`number`)throw Error(`Expected coords to contain numbers.`);this.coords=e;let n=Math.max(2*t-5,0);this._triangles=new Uint32Array(n*3),this._halfedges=new Int32Array(n*3),this._hashSize=Math.ceil(Math.sqrt(t)),this._hullPrev=new Uint32Array(t),this._hullNext=new Uint32Array(t),this._hullTri=new Uint32Array(t),this._hullHash=new Int32Array(this._hashSize),this._ids=new Uint32Array(t),this._dists=new Float64Array(t),this.trianglesLen=0,this._cx=0,this._cy=0,this._hullStart=0,this.hull=this._triangles,this.triangles=this._triangles,this.halfedges=this._halfedges,this.update()}update(){let{coords:e,_hullPrev:t,_hullNext:n,_hullTri:r,_hullHash:i}=this,a=e.length>>1,o=1/0,s=1/0,c=-1/0,l=-1/0;for(let t=0;t<a;t++){let n=e[2*t],r=e[2*t+1];n<o&&(o=n),r<s&&(s=r),n>c&&(c=n),r>l&&(l=r),this._ids[t]=t}let u=(o+c)/2,d=(s+l)/2,f=0,p=0,m=0;for(let t=0,n=1/0;t<a;t++){let r=uK(u,d,e[2*t],e[2*t+1]);r<n&&(f=t,n=r)}let h=e[2*f],g=e[2*f+1];for(let t=0,n=1/0;t<a;t++){if(t===f)continue;let r=uK(h,g,e[2*t],e[2*t+1]);r<n&&r>0&&(p=t,n=r)}let _=e[2*p],v=e[2*p+1],y=1/0;for(let t=0;t<a;t++){if(t===f||t===p)continue;let n=fK(h,g,_,v,e[2*t],e[2*t+1]);n<y&&(m=t,y=n)}let b=e[2*m],x=e[2*m+1];if(y===1/0){for(let t=0;t<a;t++)this._dists[t]=e[2*t]-e[0]||e[2*t+1]-e[1];mK(this._ids,this._dists,0,a-1);let t=new Uint32Array(a),n=0;for(let e=0,r=-1/0;e<a;e++){let i=this._ids[e],a=this._dists[i];a>r&&(t[n++]=i,r=a)}this.hull=t.subarray(0,n),this.triangles=new Uint32Array,this.halfedges=new Int32Array;return}if(aK(h,g,_,v,b,x)<0){let e=p,t=_,n=v;p=m,_=b,v=x,m=e,b=t,x=n}let S=pK(h,g,_,v,b,x);this._cx=S.x,this._cy=S.y;for(let t=0;t<a;t++)this._dists[t]=uK(e[2*t],e[2*t+1],S.x,S.y);mK(this._ids,this._dists,0,a-1),this._hullStart=f;let C=3;n[f]=t[m]=p,n[p]=t[f]=m,n[m]=t[p]=f,r[f]=0,r[p]=1,r[m]=2,i.fill(-1),i[this._hashKey(h,g)]=f,i[this._hashKey(_,v)]=p,i[this._hashKey(b,x)]=m,this.trianglesLen=0,this._addTriangle(f,p,m,-1,-1,-1);for(let a=0,o=0,s=0;a<this._ids.length;a++){let c=this._ids[a],l=e[2*c],u=e[2*c+1];if(a>0&&Math.abs(l-o)<=oK&&Math.abs(u-s)<=oK||(o=l,s=u,c===f||c===p||c===m))continue;let d=0;for(let e=0,t=this._hashKey(l,u);e<this._hashSize&&(d=i[(t+e)%this._hashSize],!(d!==-1&&d!==n[d]));e++);d=t[d];let h=d,g;for(;g=n[h],aK(l,u,e[2*h],e[2*h+1],e[2*g],e[2*g+1])>=0;)if(h=g,h===d){h=-1;break}if(h===-1)continue;let _=this._addTriangle(h,c,n[h],-1,-1,r[h]);r[c]=this._legalize(_+2),r[h]=_,C++;let v=n[h];for(;g=n[v],aK(l,u,e[2*v],e[2*v+1],e[2*g],e[2*g+1])<0;)_=this._addTriangle(v,c,g,r[c],-1,r[v]),r[c]=this._legalize(_+2),n[v]=v,C--,v=g;if(h===d)for(;g=t[h],aK(l,u,e[2*g],e[2*g+1],e[2*h],e[2*h+1])<0;)_=this._addTriangle(g,c,h,-1,r[h],r[g]),this._legalize(_+2),r[g]=_,n[h]=h,C--,h=g;this._hullStart=t[c]=h,n[h]=t[v]=c,n[c]=v,i[this._hashKey(l,u)]=c,i[this._hashKey(e[2*h],e[2*h+1])]=h}this.hull=new Uint32Array(C);for(let e=0,t=this._hullStart;e<C;e++)this.hull[e]=t,t=n[t];this.triangles=this._triangles.subarray(0,this.trianglesLen),this.halfedges=this._halfedges.subarray(0,this.trianglesLen)}_hashKey(e,t){return Math.floor(lK(e-this._cx,t-this._cy)*this._hashSize)%this._hashSize}_legalize(e){let{_triangles:t,_halfedges:n,coords:r}=this,i=0,a=0;for(;;){let o=n[e],s=e-e%3;if(a=s+(e+2)%3,o===-1){if(i===0)break;e=sK[--i];continue}let c=o-o%3,l=s+(e+1)%3,u=c+(o+2)%3,d=t[a],f=t[e],p=t[l],m=t[u];if(dK(r[2*d],r[2*d+1],r[2*f],r[2*f+1],r[2*p],r[2*p+1],r[2*m],r[2*m+1])){t[e]=m,t[o]=d;let r=n[u];if(r===-1){let t=this._hullStart;do{if(this._hullTri[t]===u){this._hullTri[t]=e;break}t=this._hullPrev[t]}while(t!==this._hullStart)}this._link(e,r),this._link(o,n[a]),this._link(a,u);let s=c+(o+1)%3;i<sK.length&&(sK[i++]=s)}else{if(i===0)break;e=sK[--i]}}return a}_link(e,t){this._halfedges[e]=t,t!==-1&&(this._halfedges[t]=e)}_addTriangle(e,t,n,r,i,a){let o=this.trianglesLen;return this._triangles[o]=e,this._triangles[o+1]=t,this._triangles[o+2]=n,this._link(o,r),this._link(o+1,i),this._link(o+2,a),this.trianglesLen+=3,o}};function lK(e,t){let n=e/(Math.abs(e)+Math.abs(t));return(t>0?3-n:1+n)/4}function uK(e,t,n,r){let i=e-n,a=t-r;return i*i+a*a}function dK(e,t,n,r,i,a,o,s){let c=e-o,l=t-s,u=n-o,d=r-s,f=i-o,p=a-s,m=c*c+l*l,h=u*u+d*d,g=f*f+p*p;return c*(d*g-h*p)-l*(u*g-h*f)+m*(u*p-d*f)<0}function fK(e,t,n,r,i,a){let o=n-e,s=r-t,c=i-e,l=a-t,u=o*o+s*s,d=c*c+l*l,f=.5/(o*l-s*c),p=(l*u-s*d)*f,m=(o*d-c*u)*f;return p*p+m*m}function pK(e,t,n,r,i,a){let o=n-e,s=r-t,c=i-e,l=a-t,u=o*o+s*s,d=c*c+l*l,f=.5/(o*l-s*c);return{x:e+(l*u-s*d)*f,y:t+(o*d-c*u)*f}}function mK(e,t,n,r){if(r-n<=20)for(let i=n+1;i<=r;i++){let r=e[i],a=t[r],o=i-1;for(;o>=n&&t[e[o]]>a;)e[o+1]=e[o--];e[o+1]=r}else{let i=n+r>>1,a=n+1,o=r;hK(e,i,a),t[e[n]]>t[e[r]]&&hK(e,n,r),t[e[a]]>t[e[r]]&&hK(e,a,r),t[e[n]]>t[e[a]]&&hK(e,n,a);let s=e[a],c=t[s];for(;;){do a++;while(t[e[a]]<c);do o--;while(t[e[o]]>c);if(o<a)break;hK(e,a,o)}e[n+1]=e[o],e[o]=s,r-a+1>=o-n?(mK(e,t,a,r),mK(e,t,n,o-1)):(mK(e,t,n,o-1),mK(e,t,a,r))}}function hK(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function gK(e){return e[0]}function _K(e){return e[1]}var vK=`
|
|
374
|
+
void main() { o = vec4(0.0); }`;function DG(e,t,n,r){let i=QV(e,e.VERTEX_SHADER,t),a=QV(e,e.FRAGMENT_SHADER,n);if(!i||!a)return null;let o=e.createProgram();return e.attachShader(o,i),e.attachShader(o,a),r&&e.transformFeedbackVaryings(o,r,e.SEPARATE_ATTRIBS),e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)?{prog:o,shaders:[i,a]}:(console.error(`glPoints program link failed:`,e.getProgramInfoLog(o)),null)}function OG(e,t){if(!e)return[{v:0,a:0,b:t}];let n=[];for(let r=0;r<t;r++)r===0||e[r]!==e[r-1]?n.push({v:e[r],a:r,b:r+1}):n[n.length-1].b=r+1;return n}function kG(e,t,n,r,i,a){let o=[],s=0;for(let c of a){let a=n.filter(e=>e.v===c.v);if(a.length>1)return null;let l=-1;if(a.length===1){for(let n=a[0].a;n<a[0].b;n++)if(e[n]===r[c.a]&&t[n]===i[c.a]){l=n;break}}if(l<0){o.push({src:0,len:0});continue}let u=Math.min(a[0].b-l,c.b-c.a);for(let n=0;n<u;n++)if(e[l+n]!==r[c.a+n]||t[l+n]!==i[c.a+n])return null;o.push({src:l,len:u}),s+=u}return s>0?o:null}function AG(e){let t=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0});if(!t)return null;let n=uH(t,`glPoints|points`,()=>DG(t,_G,vG)),r=uH(t,`glPoints|lines`,()=>DG(t,xG,SG)),i=uH(t,`glPoints|points64`,()=>DG(t,wG(_G,[`a_x`],[`a_y`],!0),vG)),a=uH(t,`glPoints|sprites`,()=>DG(t,yG,bG)),o=uH(t,`glPoints|sprites64`,()=>DG(t,wG(yG,[`a_x`],[`a_y`],!0),bG)),s=uH(t,`glPoints|maxSprite`,()=>t.getParameter(t.ALIASED_POINT_SIZE_RANGE)[1]),c=uH(t,`glPoints|decode`,()=>DG(t,TG,EG,[`v_x`,`v_y`])),l=t.createVertexArray();if(!n||!r)return null;let u=(e,n)=>Object.fromEntries(n.map(n=>[n,t.getAttribLocation(e,n)])),d=(e,n)=>Object.fromEntries(n.map(n=>[n,t.getUniformLocation(e,n)])),f=u(n.prog,[`a_corner`,`a_x`,`a_y`,`a_k`,`a_r`]),p=d(n.prog,[`u_resolution`,`u_plot`,`u_view`,`u_radius`,`u_kScale`,`u_palette`,`u_alpha`,`u_clip`,`u_dpr`,`u_height`]),m=u(r.prog,[`a_corner`,`a_ax`,`a_ay`,`a_bx`,`a_by`,`a_bstart`,`a_k`]),h=d(r.prog,[`u_resolution`,`u_plot`,`u_view`,`u_ext`,`u_kScale`,`u_palette`,`u_half`,`u_clip`]),g=i&&u(i.prog,[`a_corner`,`a_x_bits`,`a_y_bits`,`a_k`,`a_r`]),_=i&&d(i.prog,[`u_resolution`,`u_plot`,`u_view`,`u_radius`,`u_kScale`,`u_palette`,`u_alpha`,`u_clip`,`u_dpr`,`u_height`,`u_ox`,`u_oy`]),v=[`u_resolution`,`u_plot`,`u_view`,`u_radius`,`u_kScale`,`u_palette`,`u_alpha`,`u_clip`,`u_dpr`,`u_height`],y=a&&u(a.prog,[`a_x`,`a_y`,`a_k`]),b=a&&d(a.prog,v),x=o&&u(o.prog,[`a_x_bits`,`a_y_bits`,`a_k`]),S=o&&d(o.prog,[...v,`u_ox`,`u_oy`]),C=c&&u(c.prog,[`a_x_bits`,`a_y_bits`]),w=c&&d(c.prog,[`u_ox`,`u_oy`]),T=t.createTransformFeedback(),E=t.createVertexArray(),D=t.createBuffer(),O=t.createBuffer(),k=!1,A=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,A),t.bufferData(t.ARRAY_BUFFER,Float32Array.from([-1,-1,1,-1,-1,1,1,1]),t.STATIC_DRAW);let M=t.createBuffer(),N=t.createBuffer(),P=t.createBuffer(),F=t.createBuffer(),I=t.createBuffer(),L=t.createBuffer(),R=t.createBuffer(),z=t.createBuffer(),B=null,V=t.createTexture(),ee=0,te=!1,H=!1,ne=!1,re=0,ie=0,U=1,ae=1,oe=1,se=1.8,ce=.8,le=255,ue=!0,de=!1,fe=1,pe={xmin:0,xmax:1,ymin:0,ymax:1},me={left:0,top:0,width:1,height:1},he=new Float32Array,ge=new Float32Array,_e=new Float32Array,ve=new Uint8Array,ye=new Float32Array,be=new Map,xe=(e,n,r)=>{t.bindBuffer(t.ARRAY_BUFFER,e);let i=r*n.BYTES_PER_ELEMENT;i<=(be.get(e)??0)?t.bufferSubData(t.ARRAY_BUFFER,0,n,0,r):(t.bufferData(t.ARRAY_BUFFER,n.subarray(0,r),t.DYNAMIC_DRAW),be.set(e,i))},Se=(e,n,r,i,a,o)=>{let s=r.BYTES_PER_ELEMENT;if(t.bindBuffer(t.ARRAY_BUFFER,n),(be.get(n)??0)<o*s){let e=Math.ceil(o*1.25)*s;t.bufferData(t.ARRAY_BUFFER,e,t.DYNAMIC_DRAW),be.set(n,e)}t.bindBuffer(t.COPY_READ_BUFFER,e),t.bindBuffer(t.COPY_WRITE_BUFFER,n),i.forEach((e,n)=>{a[n].len&&t.copyBufferSubData(t.COPY_READ_BUFFER,t.COPY_WRITE_BUFFER,a[n].src*s,e.a*s,a[n].len*s)}),t.bindBuffer(t.COPY_READ_BUFFER,null),t.bindBuffer(t.COPY_WRITE_BUFFER,null),i.forEach((e,n)=>{let i=e.a+a[n].len;e.b>i&&t.bufferSubData(t.ARRAY_BUFFER,i*s,r,i,e.b-i)})},Ce=(e,n,r=0,i=t.FLOAT)=>{t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(e);let a=i===t.FLOAT?4:1;t.vertexAttribPointer(e,1,i,i!==t.FLOAT,a,r*a),t.vertexAttribDivisor(e,1)},we=(e,n,r=0)=>{t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(e),t.vertexAttribIPointer(e,2,t.UNSIGNED_INT,8,r*8),t.vertexAttribDivisor(e,1)},Te=e=>{t.bindBuffer(t.ARRAY_BUFFER,A),t.enableVertexAttribArray(e),t.vertexAttribPointer(e,2,t.FLOAT,!1,0,0),t.vertexAttribDivisor(e,0)};return{resize(t,n,r){U=Math.max(1,t),ae=Math.max(1,n),oe=r,e.width=Math.round(U*oe),e.height=Math.round(ae*oe)},setData(e,t,n,r=!1,i){let a=Math.min(e.length,t.length);he.length<a&&(he=new Float32Array(a),ge=new Float32Array(a)),te=!!n,H=!!i,n&&_e.length<a&&(_e=new Float32Array(a)),i&&ye.length<a&&(ye=new Float32Array(a)),de&&ve.length<a&&(ve=new Uint8Array(a)),re=0,ie=0;for(let n=0;n<a;n++)if(e[n]-e[n]===0&&t[n]-t[n]===0){re=e[n],ie=t[n];break}let o=j.has(e)&&j.has(t);if(ne=!!g&&!!c&&e instanceof Float64Array&&t instanceof Float64Array&&(o||!de),k=!1,ne){let o=e,s=t;if(n)for(let e=0;e<a;e++)_e[e]=n[e];let c=OG(n&&r?n:void 0,a),l=B&&(!n||r)?kG(B.x,B.y,B.runs,o,s,c):null;if(l?(Se(M,L,o,c,l,a),[M,L]=[L,M],Se(N,R,s,c,l,a),[N,R]=[R,N],n&&(Se(P,z,_e,c,l,a),[P,z]=[z,P])):(xe(M,o,a),xe(N,s,a),n&&xe(P,_e,a)),(!B||B.x.length<a)&&(B={x:new Float64Array(Math.ceil(a*1.25)),y:new Float64Array(Math.ceil(a*1.25)),runs:c,n:a}),B.x.set(o.subarray(0,a)),B.y.set(s.subarray(0,a)),B.runs=c,B.n=a,i){for(let e=0;e<a;e++)ye[e]=i[e];xe(I,ye,a)}if(de){if(ve.fill(0,0,a),a&&(ve[0]=255),n&&r)for(let e=1;e<a;e++)n[e]!==n[e-1]&&(ve[e]=255);xe(F,ve,a)}ee=a;return}B=null;let s=0;if(j.has(e)&&j.has(t)){for(let t=0;t<a;t++)he[t]=e[t]-re;for(let e=0;e<a;e++)ge[e]=t[e]-ie;if(n)for(let e=0;e<a;e++)_e[e]=n[e];if(i)for(let e=0;e<a;e++)ye[e]=i[e];if(de&&(ve.fill(0,0,a),a&&(ve[0]=255),n&&r))for(let e=1;e<a;e++)n[e]!==n[e-1]&&(ve[e]=255);s=a}else{let o=!0;for(let c=0;c<a;c++){let a=e[c],l=t[c];if(a-a!==0||l-l!==0){o=!0;continue}he[s]=a-re,ge[s]=l-ie,n&&(_e[s]=n[c]),i&&(ye[s]=i[c]),de&&(ve[s]=o||r&&n&&s>0&&n[c]!==_e[s-1]?255:0),o=!1,s++}}ee=s,xe(M,he,s),xe(N,ge,s),n&&xe(P,_e,s),i&&xe(I,ye,s),de&&xe(F,ve,s)},setStyle(e,n,r){se=n,ce=r;let i=new Uint8Array(256*4);if(e.kind===`single`){let t=e.rgba.map(e=>Math.round(e*255));for(let e=0;e<256;e++)i.set(t,e*4);le=0}else i.set(e.palette.subarray(0,256*4)),le=e.kind===`colormap`?255:1;t.bindTexture(t.TEXTURE_2D,V),t.texImage2D(t.TEXTURE_2D,0,t.RGBA8,256,1,0,t.RGBA,t.UNSIGNED_BYTE,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)},setDraw(e,t,n){ue=e,de=t,fe=n},setView(e,t,n,r,i){pe={xmin:e,xmax:t,ymin:n,ymax:r},me=i},render(){if(t.bindFramebuffer(t.FRAMEBUFFER,null),t.viewport(0,0,e.width,e.height),t.disable(t.SCISSOR_TEST),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),ee===0)return;t.bindVertexArray(l),t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,V);let u=te?le:0,d=[pe.xmin-re,pe.xmax-re,pe.ymin-ie,pe.ymax-ie],v=[me.left,me.top,me.left+me.width,me.top+me.height],A=e=>{let t=Math.fround(e);return[t,e-t]},j=ne,L=M,R=N;if(ne&&de&&ee>1){if(!k){for(let e of[D,O])t.bindBuffer(t.ARRAY_BUFFER,e),(be.get(e)??0)<ee*4&&(t.bufferData(t.ARRAY_BUFFER,ee*4,t.DYNAMIC_COPY),be.set(e,ee*4));t.bindBuffer(t.ARRAY_BUFFER,null),t.bindVertexArray(E),t.useProgram(c.prog),t.uniform2f(w.u_ox,...A(re)),t.uniform2f(w.u_oy,...A(ie)),we(C.a_x_bits,M),we(C.a_y_bits,N),t.vertexAttribDivisor(C.a_x_bits,0),t.vertexAttribDivisor(C.a_y_bits,0),t.enable(t.RASTERIZER_DISCARD),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,T),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,0,D),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,1,O),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,0,ee),t.endTransformFeedback(),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,0,null),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,1,null),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null),t.disable(t.RASTERIZER_DISCARD),t.bindVertexArray(l),k=!0}j=!1,L=D,R=O}if(de&&ee>1){let e=h,n=m;t.useProgram(r.prog),t.uniform2f(e.u_resolution,U,ae),t.uniform4f(e.u_plot,me.left,me.top,me.width,me.height),t.uniform4f(e.u_view,...d),t.uniform1f(e.u_half,fe/2),t.uniform1f(e.u_ext,fe/2+1),t.uniform1f(e.u_kScale,u),t.uniform4f(e.u_clip,...v),t.uniform1i(e.u_palette,0),Te(n.a_corner),Ce(n.a_ax,L,0),Ce(n.a_bx,L,1),Ce(n.a_ay,R,0),Ce(n.a_by,R,1),Ce(n.a_bstart,F,1,t.UNSIGNED_BYTE),te?Ce(n.a_k,P,0):(t.disableVertexAttribArray(n.a_k),t.vertexAttrib1f(n.a_k,0)),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,ee-1);for(let e of Object.values(n))t.vertexAttribDivisor(e,0)}if(ue&&!H&&2*(se+.5)*oe<=s&&(j?o:a)){let n=j?S:b,r=j?x:y;t.useProgram((j?o:a).prog),j&&(t.uniform2f(n.u_ox,...A(re)),t.uniform2f(n.u_oy,...A(ie))),t.uniform2f(n.u_resolution,U,ae),t.uniform4f(n.u_plot,me.left,me.top,me.width,me.height),t.uniform4f(n.u_view,...d),t.uniform1f(n.u_radius,se),t.uniform1f(n.u_kScale,u),t.uniform1f(n.u_alpha,ce),t.uniform4f(n.u_clip,...v),t.uniform1f(n.u_dpr,oe),t.uniform1f(n.u_height,e.height),t.uniform1i(n.u_palette,0),j?(we(r.a_x_bits,M),we(r.a_y_bits,N)):(Ce(r.a_x,L),Ce(r.a_y,R)),te?Ce(r.a_k,P):(t.disableVertexAttribArray(r.a_k),t.vertexAttrib1f(r.a_k,0));for(let e of Object.values(r))t.vertexAttribDivisor(e,0);t.drawArrays(t.POINTS,0,ee)}else if(ue){let r=j?_:p,a=j?g:f;t.useProgram(j?i.prog:n.prog),j&&(t.uniform2f(r.u_ox,...A(re)),t.uniform2f(r.u_oy,...A(ie))),t.uniform2f(r.u_resolution,U,ae),t.uniform4f(r.u_plot,me.left,me.top,me.width,me.height),t.uniform4f(r.u_view,...d),t.uniform1f(r.u_radius,se),t.uniform1f(r.u_kScale,u),t.uniform1f(r.u_alpha,ce),t.uniform4f(r.u_clip,...v),t.uniform1f(r.u_dpr,oe),t.uniform1f(r.u_height,e.height),t.uniform1i(r.u_palette,0),Te(a.a_corner),j?(we(a.a_x_bits,M),we(a.a_y_bits,N)):(Ce(a.a_x,L),Ce(a.a_y,R)),te?Ce(a.a_k,P):(t.disableVertexAttribArray(a.a_k),t.vertexAttrib1f(a.a_k,0)),H?Ce(a.a_r,I):(t.disableVertexAttribArray(a.a_r),t.vertexAttrib1f(a.a_r,0)),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,ee);for(let e of Object.values(a))t.vertexAttribDivisor(e,0)}t.bindVertexArray(null)},dispose(){for(let e of[A,M,N,P,F,I,D,O,L,R,z])t.deleteBuffer(e);t.deleteTransformFeedback(T),t.deleteVertexArray(E),t.deleteTexture(V),t.deleteVertexArray(l)}}}var jG={top:3,right:3,bottom:3,left:3};function MG(e,t,n){return t<200||n<120?{...jG,tiny:!0}:{...e,tiny:!1}}var NG={top:14,right:24,bottom:40,left:78},PG=70,FG=6,IG=8,LG=1.8;function RG(e,t,n){return Math.min(n,Math.max(t,e))}function zG(e,t){let n=e[t],r=1/0,i=-1/0;for(let t=0;t<e.length;t++){let e=n[t];e<r&&(r=e),e>i&&(i=e)}(!Number.isFinite(r)||r===i)&&(--r,i+=1);let a=(i-r)*.04;return{min:r-a,max:i+a}}function BG(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}function VG({points:e,xLabel:t,yLabel:n,color:r=`#38bdf8`,datasetColors:i,colorLabel:a,colorRange:o,height:s=400,pointRadius:c=LG,drawMode:l=`points`,lineWidth:u=1,backgroundToken:d=``,onPlotContextMenu:f,xAxisLine:p,yAxisLine:m,gridLine:h,fitSettings:g,xScale:_,yScale:v}){let y=IU(),b=K(null),x=K(null),S=K(null),C=K(f);G(()=>{C.current=f},[f]);let w=K(null),T=K(null),E=K(null),D=K(null),O=K(null),k=K(0),A=K(null),j=St(()=>XW(e)?e:ZW(e),[e]),M=K({cols:j,xLabel:t,yLabel:n,color:r,datasetColors:i,colorLabel:a,colorRange:o,height:s,pointRadius:c,drawMode:l,lineWidth:u,xAxisLine:p,yAxisLine:m,gridLine:h,fitSettings:g,xScale:_,yScale:v});G(()=>{M.current={cols:j,xLabel:t,yLabel:n,color:r,datasetColors:i,colorLabel:a,colorRange:o,height:s,pointRadius:c,drawMode:l,lineWidth:u,xAxisLine:p,yAxisLine:m,gridLine:h,fitSettings:g,xScale:_,yScale:v}},[j,t,n,r,i,a,o,s,c,l,u,p,m,h,g,_,v]);let N=K({cols:null,value:{x:{min:0,max:1},y:{min:0,max:1}}});function P(){let e=M.current.cols,t=N.current;return t.cols!==e&&(t.value={x:zG(e,`x`),y:zG(e,`y`)},t.cols=e),t.value}W(()=>{T.current=null,E.current=null,D.current=null,O.current=null},[t,n]);function F(){let e=P(),t=T.current,n=E.current,r=D.current,i=O.current;return{xmin:t!==null&&n!==null&&n>t?t:e.x.min,xmax:t!==null&&n!==null&&n>t?n:e.x.max,ymin:r!==null&&i!==null&&i>r?r:e.y.min,ymax:r!==null&&i!==null&&i>r?i:e.y.max}}function I(){if(T.current!==null||D.current!==null)return F();let{xScale:e,yScale:t}=M.current,n=e=>{if(!e)return null;let t=parseFloat(e.scaleMin),n=parseFloat(e.scaleMax);return Number.isFinite(t)&&Number.isFinite(n)&&t<n?{min:t,max:n}:null},r=n(e)??P().x,i=n(t)??P().y;return{xmin:r.min,xmax:r.max,ymin:i.min,ymax:i.max}}function L(){if(A.current)return A.current;let e=S.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`,accent:`#f97316`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`,accent:t.getPropertyValue(`--accent`).trim()||`#f97316`};return A.current=n,n}function R(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function z(){let e=S.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||M.current.height)}}let B=K(null),V=K(null),ee=K({r:null,failed:!1,data:null,mode:``,style:``,size:``});function te(e,t){let n=ee.current;!n.r&&!n.failed&&V.current&&(n.r=dH(V.current,AG),n.failed=!n.r);let r=n.r;if(!r||!V.current)return null;let{cols:i,color:a,datasetColors:o,pointRadius:s,drawMode:c,lineWidth:l}=M.current,u=Math.min(2,window.devicePixelRatio||1),d=`${e}x${t}@${u}`;n.size!==d&&(r.resize(e,t,u),V.current.style.width=`${e}px`,V.current.style.height=`${t}px`,n.size=d);let f=o&&o.length>0&&i.d?`dataset`:i.c?`colormap`:`single`,p=c!==`points`;r.setDraw(c!==`lines`,p,l),(n.data!==i||n.mode!==`${f}|${p}`)&&(r.setData(i.x,i.y,f===`dataset`?i.d:f===`colormap`?i.c:void 0,f===`dataset`),n.data=i,n.mode=`${f}|${p}`);let m=`${f}|${a}|${f===`dataset`?o.join(`,`):``}|${s}`;return n.style!==m&&(r.setStyle(UG(f,a,o),Math.max(.25,s),.8),n.style=m),r}W(()=>()=>{ee.current.r?.dispose(),ee.current.r=null},[]);let H=K({cols:null,key:``,coeffs:null});function ne(e,t,n){let r=`${t}|${n.xmin}|${n.xmax}|${n.ymin}|${n.ymax}`,i=H.current;return(i.cols!==e||i.key!==r)&&(H.current={cols:e,key:r,coeffs:lG(e,t,n)}),H.current.coeffs}let re=K({pts:null,view:``}),ie=K(``);function U(){let e=b.current;if(!e)return;let{w:t,h:n}=z(),r=R(e,t,n);if(!r)return;let{cols:i,xLabel:a,yLabel:o,color:s,datasetColors:c,colorLabel:l,colorRange:u,pointRadius:d,xAxisLine:f,yAxisLine:p,gridLine:m,fitSettings:h,xScale:g,yScale:_}=M.current,v=!!c&&c.length>0&&!!i.d,x=!v&&i.length>0&&!!i.c,C=MG(NG,t,n),w=C.tiny?C.right:x?PG:C.right,{top:T,bottom:E,left:D}=C,O=t-D-w,k=n-T-E,{bg:A,muted:j,grid:N,accent:P}=L(),F=Math.max(.25,d),V=te(t,n),ee=i.length>=1&&O>0&&k>0?I():null,H=[t,n,e.width,ee&&`${ee.xmin}|${ee.xmax}|${ee.ymin}|${ee.ymax}`,a,o,x,v,l,u?.join(),JSON.stringify([f,p,m,g,_]),A,j,N,P].join(`§`);if(V&&ee&&!h&&ie.current===H){let e=re.current;e.pts!==i&&(re.current={pts:i,view:e.view},VH(S.current)),V.setView(ee.xmin,ee.xmax,ee.ymin,ee.ymax,{left:D,top:T,width:O,height:k}),V.render();return}ie.current=H,r.fillStyle=A,r.fillRect(0,0,t,n);let U=B.current?R(B.current,t,n):null;U?.clearRect(0,0,t,n);let ae=V;if(i.length<1||O<=0||k<=0){ae?.render(),r.fillStyle=j,r.font=`13px ${Q.sans}`,UV(r);return}let{xmin:oe,xmax:se,ymin:ce,ymax:le}=I(),ue=se-oe,de=le-ce,fe=e=>D+(e-oe)/ue*O;y({left:D,top:T,width:O,height:k,x:{v0:oe,v1:se}});let pe=e=>T+(le-e)/de*k,me=(()=>{if(_?.majorStep){let e=parseFloat(_.majorStep);if(Number.isFinite(e)&&e>0)return e}return Pz(de,6)})(),he=Lz(ce,le,me);if((p?.style??`dashed`)!==`none`){r.strokeStyle=p?.color??N,r.lineWidth=p?.width??1,r.setLineDash(BG(p?.style??`dashed`));for(let e of he){let t=pe(e);r.beginPath(),r.moveTo(D,t),r.lineTo(D+O,t),r.stroke()}r.setLineDash([])}r.strokeStyle=j,r.lineWidth=1,r.fillStyle=j,r.font=`11px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of C.tiny?[]:he){let t=pe(e);r.beginPath(),r.moveTo(D-FG,t),r.lineTo(D,t),r.stroke(),r.fillText(Vz(e,me),D-IG,t)}let ge=(()=>{if(g?.majorStep){let e=parseFloat(g.majorStep);if(Number.isFinite(e)&&e>0)return e}return Pz(ue,Fz(O))})(),_e=Lz(oe,se,ge);if((f?.style??`dashed`)!==`none`){r.strokeStyle=f?.color??N,r.lineWidth=f?.width??1,r.setLineDash(BG(f?.style??`dashed`));for(let e of _e){let t=fe(e);r.beginPath(),r.moveTo(t,T),r.lineTo(t,T+k),r.stroke()}r.setLineDash([])}r.strokeStyle=j,r.lineWidth=1,r.fillStyle=j,r.textAlign=`center`,r.textBaseline=`top`;for(let e of C.tiny?[]:_e){let t=fe(e);r.beginPath(),r.moveTo(t,T+k),r.lineTo(t,T+k+FG),r.stroke(),r.fillText(Vz(e,ge),t,T+k+FG+2)}(m?.style??`solid`)!==`none`&&(r.strokeStyle=m?.color??N,r.lineWidth=m?.width??1,r.setLineDash(BG(m?.style??`solid`)),r.strokeRect(D,T,O,k),r.setLineDash([])),r.fillStyle=j,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,C.tiny||(r.fillText(a,D+O/2,n-4),r.save(),r.translate(14,T+k/2),r.rotate(-Math.PI/2),r.fillText(o,0,0),r.restore());let ve=re.current;if((ve.pts!==i||ve.view!==`${oe}|${se}|${ce}|${le}`)&&(re.current={pts:i,view:`${oe}|${se}|${ce}|${le}`},VH(S.current)),ae)ae.setView(oe,se,ce,le,{left:D,top:T,width:O,height:k}),ae.render();else{let e={xToPx:fe,yToPx:pe,left:D,top:T,plotW:O,plotH:k,dotR:F,col:s,dsColors:v?c:null,hasColormap:x};M.current.drawMode!==`points`&&GG(r,i,e,M.current.lineWidth),M.current.drawMode!==`lines`&&WG(r,i,e)}if(x&&!C.tiny){let e=D+O+10,n=k;for(let t=0;t<64;t++)r.fillStyle=hG(1-t/64),r.fillRect(e,T+t/64*n,10,n/64+1);r.strokeStyle=j,r.lineWidth=.5,r.strokeRect(e,T,10,n),r.fillStyle=j,r.font=`10px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`top`;let i=u?String(u[1].toPrecision(3)):`1`,a=u?String(u[0].toPrecision(3)):`0`;r.fillText(i,e+10+3,T),r.textBaseline=`bottom`,r.fillText(a,e+10+3,T+n),l&&(r.save(),r.textBaseline=`middle`,r.translate(t-6,T+n/2),r.rotate(Math.PI/2),r.fillText(l,0,0),r.restore())}if(h&&U){let e=ne(i,h.degree,{xmin:oe,xmax:se,ymin:ce,ymax:le});if(e){U.save(),U.beginPath(),U.rect(D,T,O,k),U.clip(),U.strokeStyle=h.color,U.lineWidth=h.width,U.setLineDash(BG(h.lineStyle)),U.beginPath();for(let t=0;t<=300;t++){let n=oe+t/300*ue,r=e.reduce((e,t,r)=>e+t*n**+r,0),i=fe(n),a=pe(r);t===0?U.moveTo(i,a):U.lineTo(i,a)}U.stroke(),U.setLineDash([]);let t=fG(e,`x`,`y`);U.fillStyle=P,U.font=`10px ${Q.mono}`,U.textAlign=`right`,U.textBaseline=`top`,U.fillText(t,D+O-8,T+8),U.restore()}}if((g?.alarm||_?.alarm)&&U){if(U.save(),U.beginPath(),U.rect(D,T,O,k),U.clip(),g?.alarm){let e=g.alarm;U.strokeStyle=e.color,U.lineWidth=e.width,U.setLineDash(e.linked===`active`?RU:BG(e.style));let t=fe(e.value);U.beginPath(),U.moveTo(t,T),U.lineTo(t,T+k),U.stroke(),U.setLineDash([]),e.linked&&BU(U,t+3,T+2,e.color)}if(_?.alarm){let e=_.alarm;U.strokeStyle=e.color,U.lineWidth=e.width,U.setLineDash(e.linked===`active`?RU:BG(e.style));let t=pe(e.value);U.beginPath(),U.moveTo(D,t),U.lineTo(D+O,t),U.stroke(),U.setLineDash([]),e.linked&&BU(U,D+O-10-3,t-10-2,e.color)}U.restore()}}let ae=K(``);function oe(){let e=x.current;if(!e)return;let{w:t,h:n}=z(),r=`${t}x${n}`;if(w.current===null&&ae.current===r)return;let i=R(e,t,n);if(!i)return;i.clearRect(0,0,t,n),ae.current=w.current===null?r:``;let a=w.current,{cols:o,color:s,datasetColors:c,pointRadius:l}=M.current;if(a===null||a>=o.length||o.length<1)return;let u=Math.max(4,l*2),d=o.d?.[a],f=c&&c.length>0&&d!==void 0?c[d]??s:s,{top:p,right:m,bottom:h,left:g}=MG(NG,t,n),_=t-g-m,v=n-p-h;if(_<=0||v<=0)return;let{xmin:y,xmax:b,ymin:S,ymax:C}=I(),T=b-y,E=C-S,D={x:o.x[a],y:o.y[a]},O=g+(D.x-y)/T*_,k=p+(C-D.y)/E*v,{bg:A,muted:j}=L();i.strokeStyle=j,i.globalAlpha=.4,i.lineWidth=1,i.setLineDash([3,3]),i.beginPath(),i.moveTo(O,p),i.lineTo(O,p+v),i.stroke(),i.beginPath(),i.moveTo(g,k),i.lineTo(g+_,k),i.stroke(),i.setLineDash([]),i.globalAlpha=1,i.fillStyle=f,i.beginPath(),i.arc(O,k,u,0,Math.PI*2),i.fill(),i.strokeStyle=A,i.lineWidth=1.5,i.beginPath(),i.arc(O,k,u,0,Math.PI*2),i.stroke();let N=`(${Hz(D.x)}, ${Hz(D.y)})`;i.font=`11px ${Q.mono}`;let P=i.measureText(N).width+12,F=O+10,B=k-24;F+P>g+_&&(F=O-P-10),B<p&&(B=k+10),i.fillStyle=A,i.globalAlpha=.85,i.beginPath(),HG(i,F,B,P,20,4),i.fill(),i.globalAlpha=1,i.strokeStyle=j,i.lineWidth=.5,i.beginPath(),HG(i,F,B,P,20,4),i.stroke(),i.fillStyle=j,i.textAlign=`left`,i.textBaseline=`middle`,i.fillText(N,F+6,B+20/2)}let se=K(U),ce=K(oe);G(()=>{se.current=U,ce.current=oe});let le=K(null);le.current??=KH(()=>{se.current(),ce.current()},()=>S.current);function ue(){le.current.schedule()}function de(){k.current||=RH(()=>{k.current=0,ce.current()})}W(()=>()=>{le.current?.cancel(),zH(k.current),k.current=0},[]);let fe=K(ue),pe=K(de);return G(()=>{fe.current=ue,pe.current=de}),W(()=>uB(S.current,()=>{A.current=null,fe.current()}),[]),W(()=>{A.current=null,fe.current()},[d]),W(()=>{le.current.now()},[e,t,n,r,i,s,c,l,u,p,m,h,g,_,v]),W(()=>{let e=x.current,t=S.current;if(!e||!t)return;let n=new WH(()=>{A.current=null,fe.current()});n.observe(t);let r=null;function i(e,t){let n=M.current.cols;if(n.length===0)return null;let{w:i,h:a}=z(),{top:o,right:s,bottom:c,left:l}=MG(NG,i,a),u=i-l-s,d=a-o-c,{xmin:f,xmax:p,ymin:m,ymax:h}=I(),g=p-f,_=h-m,v=Math.max(12,M.current.pointRadius*10),y=`${i}|${a}|${f}|${p}|${m}|${h}|${v}`;if(!r||r.cols!==n||r.key!==y){let e=Math.max(1,Math.ceil(u/v)),t=Math.max(1,Math.ceil(d/v)),i=t=>{let r=(n.x[t]-f)/g*u,i=(h-n.y[t])/_*d;return r>=0&&r<u&&i>=0&&i<d?Math.floor(i/v)*e+Math.floor(r/v):-1},a=new Uint32Array(e*t+1);for(let e=0;e<n.length;e++){let t=i(e);t>=0&&a[t+1]++}for(let n=0;n<e*t;n++)a[n+1]+=a[n];let o=a.slice(0,e*t),s=new Uint32Array(a[e*t]);for(let e=0;e<n.length;e++){let t=i(e);t>=0&&(s[o[t]++]=e)}r={cols:n,key:y,cell:v,nx:e,start:a,ix:s}}let b=r,x=Math.floor((e-l)/b.cell),S=Math.floor((t-o)/b.cell),C=(b.start.length-1)/b.nx,w=-1,T=v*v;for(let r=S-1;r<=S+1;r++)if(!(r<0||r>=C))for(let i=x-1;i<=x+1;i++){if(i<0||i>=b.nx)continue;let a=r*b.nx+i;for(let r=b.start[a];r<b.start[a+1];r++){let i=b.ix[r],a=l+(n.x[i]-f)/g*u,s=o+(h-n.y[i])/_*d,c=(a-e)**2+(s-t)**2;c<T&&(T=c,w=i)}}return w<0?null:w}let a=t=>{if(M.current.cols.length<1){w.current!==null&&(w.current=null,pe.current());return}let n=e.getBoundingClientRect(),r=t.clientX-n.left,a=t.clientY-n.top,{left:o,top:s,right:c,bottom:l}=MG(NG,n.width,n.height),u=Math.max(1,n.width-o-c),d=n.height-s-l;if(r<o||r>o+u||a<s||a>s+d){w.current!==null&&(w.current=null,pe.current());return}let f=i(r,a);w.current!==f&&(w.current=f,pe.current())},o=()=>{w.current!==null&&(w.current=null,pe.current())},s=t=>{if(M.current.cols.length<1)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,{top:a,left:o,right:s,bottom:c}=MG(NG,n.width,n.height),l=Math.max(1,n.width-o-s),u=Math.max(1,n.height-a-c);if(r<o||r>o+l||i<a||i>a+u)return;t.preventDefault();let d=P(),f=d.x.max-d.x.min,p=d.y.max-d.y.min,m=I(),h=m.xmin,g=m.xmax,_=m.ymin,v=m.ymax,y=g-h,b=v-_,x=(r-o)/l,S=(i-a)/u,C=h+x*y,w=v-S*b,k=t.deltaY<0,A=.88,j=k?A:1/A,N=y*j,F=b*j;if(!k&&N>=f*.999&&F>=p*.999){T.current=null,E.current=null,D.current=null,O.current=null,fe.current();return}N=RG(N,Math.max(f*1e-7,1e-12),f),F=RG(F,Math.max(p*1e-7,1e-12),p);let L=C-x*N,R=C+(1-x)*N;L<d.x.min&&(R+=d.x.min-L,L=d.x.min),R>d.x.max&&(L-=R-d.x.max,R=d.x.max);let z=w-(1-S)*F,B=w+S*F;z<d.y.min&&(B+=d.y.min-z,z=d.y.min),B>d.y.max&&(z-=B-d.y.max,B=d.y.max),T.current=L,E.current=R,D.current=z,O.current=B,fe.current()},c=e=>{e.button===0&&(T.current===null&&D.current===null||(T.current=null,E.current=null,D.current=null,O.current=null,fe.current(),pe.current()))},l=e=>{e.preventDefault(),C.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`mousemove`,a),e.addEventListener(`mouseleave`,o),e.addEventListener(`wheel`,s,{passive:!1}),e.addEventListener(`contextmenu`,l),e.addEventListener(`dblclick`,c),()=>{n.disconnect(),e.removeEventListener(`mousemove`,a),e.removeEventListener(`mouseleave`,o),e.removeEventListener(`wheel`,s),e.removeEventListener(`contextmenu`,l),e.removeEventListener(`dblclick`,c)}},[]),Ot(`div`,{ref:S,className:`chart-canvas-wrap`,children:[q(`canvas`,{ref:b,className:`chart-canvas`,role:`img`,"aria-label":`Scatter ${t} vs ${n}`}),q(`canvas`,{ref:V,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:B,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:x,className:`chart-canvas chart-overlay`})]})}function HG(e,t,n,r,i,a){e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.arcTo(t+r,n,t+r,n+a,a),e.lineTo(t+r,n+i-a),e.arcTo(t+r,n+i,t+r-a,n+i,a),e.lineTo(t+a,n+i),e.arcTo(t,n+i,t,n+i-a,a),e.lineTo(t,n+a),e.arcTo(t,n,t+a,n,a)}function UG(e,t,n){if(e===`single`)return{kind:`single`,rgba:qV(t)};let r=new Uint8Array(256*4);for(let t=0;t<256;t++)if(e===`colormap`){let{r:e,g:n,b:i}=mG(t/255);r.set([e,n,i,255],t*4)}else{let e=qV(n[Math.min(t,n.length-1)]);r.set([e[0]*255,e[1]*255,e[2]*255,e[3]*255],t*4)}return{kind:e===`colormap`?`colormap`:`dataset`,palette:r}}function WG(e,t,n){let r=Math.PI*2,i=n.dsColors?n.dsColors.length:n.hasColormap?24:1,a=Array.from({length:i},()=>new Path2D);for(let e=0;e<t.length;e++){let o=n.xToPx(t.x[e]),s=n.yToPx(t.y[e]);if(!(o>=n.left&&o<=n.left+n.plotW&&s>=n.top&&s<=n.top+n.plotH))continue;let c=n.dsColors?Math.min(t.d?.[e]??0,i-1):n.hasColormap?gG(t.c?.[e]??0,24):0;a[c].moveTo(o+n.dotR,s),a[c].arc(o,s,n.dotR,0,r)}e.globalAlpha=.8;for(let t=0;t<i;t++)e.fillStyle=n.dsColors?n.dsColors[t]:n.hasColormap?hG((t+.5)/24):n.col,e.fill(a[t]);e.globalAlpha=1}function GG(e,t,n,r){e.save(),e.beginPath(),e.rect(n.left,n.top,n.plotW,n.plotH),e.clip(),e.lineWidth=r;let i=n.dsColors?n.dsColors.length:1;for(let r=0;r<i;r++){e.beginPath();let i=!1;for(let a=0;a<t.length;a++){if(n.dsColors&&(t.d?.[a]??0)!==r){i=!1;continue}let o=t.x[a],s=t.y[a];if(o-o!==0||s-s!==0){i=!1;continue}i?e.lineTo(n.xToPx(o),n.yToPx(s)):(e.moveTo(n.xToPx(o),n.yToPx(s)),i=!0)}e.strokeStyle=n.dsColors?n.dsColors[r]:n.col,e.stroke()}e.restore()}var KG=11102230246251565e-32,qG=134217729,JG=(3+8*KG)*KG;function YG(e,t,n,r,i){let a,o,s,c,l=t[0],u=r[0],d=0,f=0;u>l==u>-l?(a=l,l=t[++d]):(a=u,u=r[++f]);let p=0;if(d<e&&f<n)for(u>l==u>-l?(o=l+a,s=a-(o-l),l=t[++d]):(o=u+a,s=a-(o-u),u=r[++f]),a=o,s!==0&&(i[p++]=s);d<e&&f<n;)u>l==u>-l?(o=a+l,c=o-a,s=a-(o-c)+(l-c),l=t[++d]):(o=a+u,c=o-a,s=a-(o-c)+(u-c),u=r[++f]),a=o,s!==0&&(i[p++]=s);for(;d<e;)o=a+l,c=o-a,s=a-(o-c)+(l-c),l=t[++d],a=o,s!==0&&(i[p++]=s);for(;f<n;)o=a+u,c=o-a,s=a-(o-c)+(u-c),u=r[++f],a=o,s!==0&&(i[p++]=s);return(a!==0||p===0)&&(i[p++]=a),p}function XG(e,t){let n=t[0];for(let r=1;r<e;r++)n+=t[r];return n}function $(e){return new Float64Array(e)}var ZG=(3+16*KG)*KG,QG=(2+12*KG)*KG,$G=(9+64*KG)*KG*KG,eK=$(4),tK=$(8),nK=$(12),rK=$(16),iK=$(4);function aK(e,t,n,r,i,a,o){let s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T=e-i,E=n-i,D=t-a,O=r-a;b=T*O,f=qG*T,p=f-(f-T),m=T-p,f=qG*O,h=f-(f-O),g=O-h,x=m*g-(b-p*h-m*h-p*g),S=D*E,f=qG*D,p=f-(f-D),m=D-p,f=qG*E,h=f-(f-E),g=E-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,eK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,eK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,eK[2]=v-(w-d)+(_-d),eK[3]=w;let k=XG(4,eK),A=QG*o;if(k>=A||-k>=A||(d=e-T,s=e-(T+d)+(d-i),d=n-E,l=n-(E+d)+(d-i),d=t-D,c=t-(D+d)+(d-a),d=r-O,u=r-(O+d)+(d-a),s===0&&c===0&&l===0&&u===0)||(A=$G*o+JG*Math.abs(k),k+=T*u+O*s-(D*l+E*c),k>=A||-k>=A))return k;b=s*O,f=qG*s,p=f-(f-s),m=s-p,f=qG*O,h=f-(f-O),g=O-h,x=m*g-(b-p*h-m*h-p*g),S=c*E,f=qG*c,p=f-(f-c),m=c-p,f=qG*E,h=f-(f-E),g=E-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,iK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,iK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,iK[2]=v-(w-d)+(_-d),iK[3]=w;let j=YG(4,eK,4,iK,tK);b=T*u,f=qG*T,p=f-(f-T),m=T-p,f=qG*u,h=f-(f-u),g=u-h,x=m*g-(b-p*h-m*h-p*g),S=D*l,f=qG*D,p=f-(f-D),m=D-p,f=qG*l,h=f-(f-l),g=l-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,iK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,iK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,iK[2]=v-(w-d)+(_-d),iK[3]=w;let M=YG(j,tK,4,iK,nK);return b=s*u,f=qG*s,p=f-(f-s),m=s-p,f=qG*u,h=f-(f-u),g=u-h,x=m*g-(b-p*h-m*h-p*g),S=c*l,f=qG*c,p=f-(f-c),m=c-p,f=qG*l,h=f-(f-l),g=l-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,iK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,iK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,iK[2]=v-(w-d)+(_-d),iK[3]=w,rK[YG(M,nK,4,iK,rK)-1]}function oK(e,t,n,r,i,a){let o=(t-a)*(n-i),s=(e-i)*(r-a),c=o-s,l=Math.abs(o+s);return Math.abs(c)>=ZG*l?c:-aK(e,t,n,r,i,a,l)}(7+56*KG)*KG,(3+28*KG)*KG,(26+288*KG)*KG*KG,$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(8),$(8),$(8),$(4),$(8),$(8),$(16),$(12),$(192),$(192),(10+96*KG)*KG,(4+48*KG)*KG,(44+576*KG)*KG*KG,$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(8),$(8),$(8),$(8),$(8),$(8),$(8),$(8),$(8),$(4),$(4),$(4),$(8),$(16),$(16),$(16),$(32),$(32),$(48),$(64),$(1152),$(1152),(16+224*KG)*KG,(5+72*KG)*KG,(71+1408*KG)*KG*KG,$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(24),$(24),$(24),$(24),$(24),$(24),$(24),$(24),$(24),$(24),$(1152),$(1152),$(1152),$(1152),$(1152),$(2304),$(2304),$(3456),$(5760),$(8),$(8),$(8),$(16),$(24),$(48),$(48),$(96),$(192),$(384),$(384),$(384),$(768),$(96),$(96),$(96),$(1152);var sK=2**-52,cK=new Uint32Array(512),lK=class e{static from(t,n=_K,r=vK){let i=t.length,a=new Float64Array(i*2);for(let e=0;e<i;e++){let i=t[e];a[2*e]=n(i),a[2*e+1]=r(i)}return new e(a)}constructor(e){let t=e.length>>1;if(t>0&&typeof e[0]!=`number`)throw Error(`Expected coords to contain numbers.`);this.coords=e;let n=Math.max(2*t-5,0);this._triangles=new Uint32Array(n*3),this._halfedges=new Int32Array(n*3),this._hashSize=Math.ceil(Math.sqrt(t)),this._hullPrev=new Uint32Array(t),this._hullNext=new Uint32Array(t),this._hullTri=new Uint32Array(t),this._hullHash=new Int32Array(this._hashSize),this._ids=new Uint32Array(t),this._dists=new Float64Array(t),this.trianglesLen=0,this._cx=0,this._cy=0,this._hullStart=0,this.hull=this._triangles,this.triangles=this._triangles,this.halfedges=this._halfedges,this.update()}update(){let{coords:e,_hullPrev:t,_hullNext:n,_hullTri:r,_hullHash:i}=this,a=e.length>>1,o=1/0,s=1/0,c=-1/0,l=-1/0;for(let t=0;t<a;t++){let n=e[2*t],r=e[2*t+1];n<o&&(o=n),r<s&&(s=r),n>c&&(c=n),r>l&&(l=r),this._ids[t]=t}let u=(o+c)/2,d=(s+l)/2,f=0,p=0,m=0;for(let t=0,n=1/0;t<a;t++){let r=dK(u,d,e[2*t],e[2*t+1]);r<n&&(f=t,n=r)}let h=e[2*f],g=e[2*f+1];for(let t=0,n=1/0;t<a;t++){if(t===f)continue;let r=dK(h,g,e[2*t],e[2*t+1]);r<n&&r>0&&(p=t,n=r)}let _=e[2*p],v=e[2*p+1],y=1/0;for(let t=0;t<a;t++){if(t===f||t===p)continue;let n=pK(h,g,_,v,e[2*t],e[2*t+1]);n<y&&(m=t,y=n)}let b=e[2*m],x=e[2*m+1];if(y===1/0){for(let t=0;t<a;t++)this._dists[t]=e[2*t]-e[0]||e[2*t+1]-e[1];hK(this._ids,this._dists,0,a-1);let t=new Uint32Array(a),n=0;for(let e=0,r=-1/0;e<a;e++){let i=this._ids[e],a=this._dists[i];a>r&&(t[n++]=i,r=a)}this.hull=t.subarray(0,n),this.triangles=new Uint32Array,this.halfedges=new Int32Array;return}if(oK(h,g,_,v,b,x)<0){let e=p,t=_,n=v;p=m,_=b,v=x,m=e,b=t,x=n}let S=mK(h,g,_,v,b,x);this._cx=S.x,this._cy=S.y;for(let t=0;t<a;t++)this._dists[t]=dK(e[2*t],e[2*t+1],S.x,S.y);hK(this._ids,this._dists,0,a-1),this._hullStart=f;let C=3;n[f]=t[m]=p,n[p]=t[f]=m,n[m]=t[p]=f,r[f]=0,r[p]=1,r[m]=2,i.fill(-1),i[this._hashKey(h,g)]=f,i[this._hashKey(_,v)]=p,i[this._hashKey(b,x)]=m,this.trianglesLen=0,this._addTriangle(f,p,m,-1,-1,-1);for(let a=0,o=0,s=0;a<this._ids.length;a++){let c=this._ids[a],l=e[2*c],u=e[2*c+1];if(a>0&&Math.abs(l-o)<=sK&&Math.abs(u-s)<=sK||(o=l,s=u,c===f||c===p||c===m))continue;let d=0;for(let e=0,t=this._hashKey(l,u);e<this._hashSize&&(d=i[(t+e)%this._hashSize],!(d!==-1&&d!==n[d]));e++);d=t[d];let h=d,g;for(;g=n[h],oK(l,u,e[2*h],e[2*h+1],e[2*g],e[2*g+1])>=0;)if(h=g,h===d){h=-1;break}if(h===-1)continue;let _=this._addTriangle(h,c,n[h],-1,-1,r[h]);r[c]=this._legalize(_+2),r[h]=_,C++;let v=n[h];for(;g=n[v],oK(l,u,e[2*v],e[2*v+1],e[2*g],e[2*g+1])<0;)_=this._addTriangle(v,c,g,r[c],-1,r[v]),r[c]=this._legalize(_+2),n[v]=v,C--,v=g;if(h===d)for(;g=t[h],oK(l,u,e[2*g],e[2*g+1],e[2*h],e[2*h+1])<0;)_=this._addTriangle(g,c,h,-1,r[h],r[g]),this._legalize(_+2),r[g]=_,n[h]=h,C--,h=g;this._hullStart=t[c]=h,n[h]=t[v]=c,n[c]=v,i[this._hashKey(l,u)]=c,i[this._hashKey(e[2*h],e[2*h+1])]=h}this.hull=new Uint32Array(C);for(let e=0,t=this._hullStart;e<C;e++)this.hull[e]=t,t=n[t];this.triangles=this._triangles.subarray(0,this.trianglesLen),this.halfedges=this._halfedges.subarray(0,this.trianglesLen)}_hashKey(e,t){return Math.floor(uK(e-this._cx,t-this._cy)*this._hashSize)%this._hashSize}_legalize(e){let{_triangles:t,_halfedges:n,coords:r}=this,i=0,a=0;for(;;){let o=n[e],s=e-e%3;if(a=s+(e+2)%3,o===-1){if(i===0)break;e=cK[--i];continue}let c=o-o%3,l=s+(e+1)%3,u=c+(o+2)%3,d=t[a],f=t[e],p=t[l],m=t[u];if(fK(r[2*d],r[2*d+1],r[2*f],r[2*f+1],r[2*p],r[2*p+1],r[2*m],r[2*m+1])){t[e]=m,t[o]=d;let r=n[u];if(r===-1){let t=this._hullStart;do{if(this._hullTri[t]===u){this._hullTri[t]=e;break}t=this._hullPrev[t]}while(t!==this._hullStart)}this._link(e,r),this._link(o,n[a]),this._link(a,u);let s=c+(o+1)%3;i<cK.length&&(cK[i++]=s)}else{if(i===0)break;e=cK[--i]}}return a}_link(e,t){this._halfedges[e]=t,t!==-1&&(this._halfedges[t]=e)}_addTriangle(e,t,n,r,i,a){let o=this.trianglesLen;return this._triangles[o]=e,this._triangles[o+1]=t,this._triangles[o+2]=n,this._link(o,r),this._link(o+1,i),this._link(o+2,a),this.trianglesLen+=3,o}};function uK(e,t){let n=e/(Math.abs(e)+Math.abs(t));return(t>0?3-n:1+n)/4}function dK(e,t,n,r){let i=e-n,a=t-r;return i*i+a*a}function fK(e,t,n,r,i,a,o,s){let c=e-o,l=t-s,u=n-o,d=r-s,f=i-o,p=a-s,m=c*c+l*l,h=u*u+d*d,g=f*f+p*p;return c*(d*g-h*p)-l*(u*g-h*f)+m*(u*p-d*f)<0}function pK(e,t,n,r,i,a){let o=n-e,s=r-t,c=i-e,l=a-t,u=o*o+s*s,d=c*c+l*l,f=.5/(o*l-s*c),p=(l*u-s*d)*f,m=(o*d-c*u)*f;return p*p+m*m}function mK(e,t,n,r,i,a){let o=n-e,s=r-t,c=i-e,l=a-t,u=o*o+s*s,d=c*c+l*l,f=.5/(o*l-s*c);return{x:e+(l*u-s*d)*f,y:t+(o*d-c*u)*f}}function hK(e,t,n,r){if(r-n<=20)for(let i=n+1;i<=r;i++){let r=e[i],a=t[r],o=i-1;for(;o>=n&&t[e[o]]>a;)e[o+1]=e[o--];e[o+1]=r}else{let i=n+r>>1,a=n+1,o=r;gK(e,i,a),t[e[n]]>t[e[r]]&&gK(e,n,r),t[e[a]]>t[e[r]]&&gK(e,a,r),t[e[n]]>t[e[a]]&&gK(e,n,a);let s=e[a],c=t[s];for(;;){do a++;while(t[e[a]]<c);do o--;while(t[e[o]]>c);if(o<a)break;gK(e,a,o)}e[n+1]=e[o],e[o]=s,r-a+1>=o-n?(hK(e,t,a,r),hK(e,t,n,o-1)):(hK(e,t,n,o-1),hK(e,t,a,r))}}function gK(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function _K(e){return e[0]}function vK(e){return e[1]}var yK=`
|
|
375
375
|
uniform vec3 u_lo; // the box minimum, relative to the data origin
|
|
376
376
|
uniform vec3 u_span; // the box size (0: a flat axis)
|
|
377
377
|
uniform int u_flat; // 0: 3D camera, 1: a 2D view
|
|
@@ -407,17 +407,17 @@ vec4 place(vec3 d) {
|
|
|
407
407
|
float z = clamp(cz / 16.0, 0.0, 1.0) * 2.0 - 1.0;
|
|
408
408
|
return vec4(c.x * cz, -c.y * cz, z * cz, cz);
|
|
409
409
|
}
|
|
410
|
-
`,
|
|
410
|
+
`,bK=`bool outside(vec3 n) { return any(greaterThan(abs(n), vec3(1.0001))); }`,xK=`#version 300 es
|
|
411
411
|
in float a_x; in float a_y; in float a_z;
|
|
412
412
|
uniform float u_size;
|
|
413
|
-
${vK}
|
|
414
413
|
${yK}
|
|
414
|
+
${bK}
|
|
415
415
|
void main() {
|
|
416
416
|
vec3 d = vec3(a_x, a_y, a_z);
|
|
417
417
|
gl_Position = place(d);
|
|
418
418
|
gl_PointSize = u_size;
|
|
419
419
|
if (a_x != a_x || a_y != a_y || a_z != a_z || outside(v_n)) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
|
|
420
|
-
}`,
|
|
420
|
+
}`,SK=`#version 300 es
|
|
421
421
|
precision highp float;
|
|
422
422
|
in vec3 v_n; in vec4 v_color;
|
|
423
423
|
uniform float u_size; // device px
|
|
@@ -428,10 +428,10 @@ void main() {
|
|
|
428
428
|
if (u_size >= 3.0 && r > u_size * 0.5) discard;
|
|
429
429
|
vec4 c = r > u_size * 0.5 - u_rim ? vec4(0.0588, 0.0627, 0.0784, 0.85) : v_color;
|
|
430
430
|
o = vec4(c.rgb * c.a, c.a);
|
|
431
|
-
}`,
|
|
431
|
+
}`,CK=`#version 300 es
|
|
432
432
|
in float a_x; in float a_y; in float a_z;
|
|
433
|
-
${
|
|
434
|
-
void main() { gl_Position = place(vec3(a_x, a_y, a_z)); }`,
|
|
433
|
+
${yK}
|
|
434
|
+
void main() { gl_Position = place(vec3(a_x, a_y, a_z)); }`,wK=`#version 300 es
|
|
435
435
|
precision highp int;
|
|
436
436
|
uniform highp sampler2D u_z;
|
|
437
437
|
uniform ivec2 u_n; // grid size
|
|
@@ -440,7 +440,7 @@ uniform int u_wstep; // grid cells between wire lines
|
|
|
440
440
|
uniform int u_wire;
|
|
441
441
|
uniform vec4 u_ext; // x0, x1, y0, y1 (relative to the origin)
|
|
442
442
|
out float v_hole;
|
|
443
|
-
${
|
|
443
|
+
${yK}
|
|
444
444
|
void main() {
|
|
445
445
|
int cx = (u_n.x - 2) / u_step + 1, cy = (u_n.y - 2) / u_step + 1;
|
|
446
446
|
int id = gl_VertexID, gx, gy;
|
|
@@ -459,29 +459,29 @@ void main() {
|
|
|
459
459
|
v_hole = z != z ? 1.0 : 0.0;
|
|
460
460
|
float fx = u_n.x > 1 ? float(gx) / float(u_n.x - 1) : 0.0, fy = u_n.y > 1 ? float(gy) / float(u_n.y - 1) : 0.0;
|
|
461
461
|
gl_Position = place(vec3(mix(u_ext.x, u_ext.y, fx), mix(u_ext.z, u_ext.w, fy), z == z ? z : 0.0));
|
|
462
|
-
}`,
|
|
462
|
+
}`,TK=`#version 300 es
|
|
463
463
|
precision highp float;
|
|
464
464
|
in vec3 v_n; in vec4 v_color;
|
|
465
465
|
uniform float u_alpha;
|
|
466
466
|
uniform vec4 u_solid; // a colour of its own (wire) when its alpha is set
|
|
467
|
-
${
|
|
467
|
+
${bK}
|
|
468
468
|
out vec4 o;
|
|
469
469
|
void main() {
|
|
470
470
|
if (outside(v_n)) discard;
|
|
471
471
|
vec4 c = u_solid.a > 0.0 ? u_solid : vec4(v_color.rgb, u_alpha);
|
|
472
472
|
o = vec4(c.rgb * c.a, c.a);
|
|
473
|
-
}`,
|
|
473
|
+
}`,EK=`#version 300 es
|
|
474
474
|
precision highp float;
|
|
475
475
|
in vec3 v_n; in vec4 v_color; in float v_hole;
|
|
476
476
|
uniform float u_alpha;
|
|
477
477
|
uniform vec4 u_solid;
|
|
478
|
-
${
|
|
478
|
+
${bK}
|
|
479
479
|
out vec4 o;
|
|
480
480
|
void main() {
|
|
481
481
|
if (v_hole > 0.0 || outside(v_n)) discard;
|
|
482
482
|
vec4 c = u_solid.a > 0.0 ? u_solid : vec4(v_color.rgb, u_alpha);
|
|
483
483
|
o = vec4(c.rgb * c.a, c.a);
|
|
484
|
-
}`,EK=16e6,DK=128,OK=[`u_lo`,`u_span`,`u_flat`,`u_eye`,`u_right`,`u_up`,`u_fwd`,`u_f`,`u_h`,`u_v`,`u_c`,`u_plot`,`u_resolution`,`u_palette`];function kK(e){for(let t=0;t<e.length;t++)if(e[t]===e[t]&&Math.abs(e[t])!==1/0)return e[t];return 0}function AK(e){let t=e.getContext(`webgl2`,{antialias:!0,alpha:!0,premultipliedAlpha:!0,depth:!0});if(!t)return null;let n=(e,n,r,i)=>uH(t,`gl3d|${e}|${n}`,()=>{let a=QV(t,t.VERTEX_SHADER,e),o=QV(t,t.FRAGMENT_SHADER,n);if(!a||!o)return null;let s=t.createProgram();return t.attachShader(s,a),t.attachShader(s,o),t.linkProgram(s),t.getProgramParameter(s,t.LINK_STATUS)?{prog:s,a:Object.fromEntries(r.map(e=>[e,t.getAttribLocation(s,e)])),u:Object.fromEntries([...OK,...i].map(e=>[e,t.getUniformLocation(s,e)]))}:(console.error(`gl3d program link failed:`,t.getProgramInfoLog(s)),null)}),r=[`a_x`,`a_y`,`a_z`],i=n(bK,xK,r,[`u_size`,`u_rim`]),a=n(SK,wK,r,[`u_alpha`,`u_solid`]),o=n(CK,TK,[],[`u_alpha`,`u_solid`,`u_z`,`u_n`,`u_step`,`u_wstep`,`u_wire`,`u_ext`]);if(!i||!a||!o)return null;let s=t.getParameter(t.MAX_TEXTURE_SIZE),c=t.createVertexArray(),l={x:t.createBuffer(),y:t.createBuffer(),z:t.createBuffer()},u=t.createBuffer(),d=t.createBuffer(),f=new Map,p=t.createTexture(),m=t.createTexture(),h=1,g=1,_=1,v={minX:0,maxX:1,minY:0,maxY:1,minZ:0,maxZ:1},y={kind:`2d`,h:0,v:1},b={left:0,top:0,width:1,height:1},x=null,S=0,C=[0,0,0],w=0,T=0,E=null,D={w:0,h:0},O=new Float32Array,k=(e,n,r)=>{t.bindBuffer(e,n),r.byteLength<=(f.get(n)??0)?t.bufferSubData(e,0,r):(t.bufferData(e,r,t.DYNAMIC_DRAW),f.set(n,r.byteLength))},A=(e,t)=>{let n=e.length;O.length<n&&(O=new Float32Array(n));for(let r=0;r<n;r++)O[r]=e[r]-t;return O.subarray(0,n)},j=(e,n)=>{let r=e.u,i=v;t.uniform3f(r.u_lo,i.minX-n[0],i.minY-n[1],i.minZ-n[2]);let a=(e,t)=>t-e>1e-12*Math.max(1,Math.abs(e))?t-e:0;t.uniform3f(r.u_span,a(i.minX,i.maxX),a(i.minY,i.maxY),a(i.minZ,i.maxZ));let o=e=>[+(e===0),+(e===1),+(e===2)];y.kind===`3d`?(t.uniform1i(r.u_flat,0),t.uniform3f(r.u_eye,...y.eye),t.uniform3f(r.u_right,...y.right),t.uniform3f(r.u_up,...y.up),t.uniform3f(r.u_fwd,...y.fwd),t.uniform1f(r.u_f,y.f)):(t.uniform1i(r.u_flat,1),t.uniform3f(r.u_h,...o(y.h)),t.uniform3f(r.u_v,...o(y.v))),t.uniform3f(r.u_c,...o(x.colorAxis)),t.uniform4f(r.u_plot,b.left,b.top,b.width,b.height),t.uniform2f(r.u_resolution,h,g),t.uniform1i(r.u_palette,0)},M=e=>{for(let n of[`x`,`y`,`z`]){let r=e.a[`a_${n}`];t.bindBuffer(t.ARRAY_BUFFER,l[n]),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,1,t.FLOAT,!1,0,0)}};return{maxTextureSize:s,resize(t,n,r){h=Math.max(1,t),g=Math.max(1,n),_=r,e.width=Math.max(1,Math.round(h*_)),e.height=Math.max(1,Math.round(g*_))},setBounds(e){v=e},setView(e,t){y=e,b=t},setPoints(e,n,r){if(!e||!n||!r){S=0;return}S=Math.min(e.length,n.length,r.length),C=[kK(e),kK(n),kK(r)],k(t.ARRAY_BUFFER,l.x,A(e,C[0]).subarray(0,S)),k(t.ARRAY_BUFFER,l.y,A(n,C[1]).subarray(0,S)),k(t.ARRAY_BUFFER,l.z,A(r,C[2]).subarray(0,S))},setTriangles(e){if(!e||e.length<3){w=T=0;return}w=e.length-e.length%3,k(t.ELEMENT_ARRAY_BUFFER,u,e.subarray(0,w));let n=new Uint32Array(w*2);for(let t=0;t<w;t+=3){let r=e[t],i=e[t+1],a=e[t+2],o=t*2;n[o]=r,n[o+1]=i,n[o+2]=i,n[o+3]=a,n[o+4]=a,n[o+5]=r}T=n.length,k(t.ELEMENT_ARRAY_BUFFER,d,n)},setSurface(e,n=0,r=0,i=[0,1],a=[0,1]){if(!e||n<2||r<2||n>s||r>s){E=null;return}let o=kK(e),c=A(e,o).subarray(0,n*r);t.bindTexture(t.TEXTURE_2D,m),t.pixelStorei(t.UNPACK_ALIGNMENT,4),D.w===n&&D.h===r?t.texSubImage2D(t.TEXTURE_2D,0,0,0,n,r,t.RED,t.FLOAT,c):(t.texImage2D(t.TEXTURE_2D,0,t.R32F,n,r,0,t.RED,t.FLOAT,c),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),D={w:n,h:r}),E={w:n,h:r,origin:o,ext:[i[0],i[1],a[0],a[1]]}},setStyle(e){x?.palette!==e.palette&&(t.bindTexture(t.TEXTURE_2D,p),t.texImage2D(t.TEXTURE_2D,0,t.RGBA8,256,1,0,t.RGBA,t.UNSIGNED_BYTE,e.palette),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)),x=e},render(){t.viewport(0,0,e.width,e.height),t.clearColor(0,0,0,0),t.clearDepth(1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT);let n=x;if(!n)return;t.bindVertexArray(c),t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,p),t.enable(t.POLYGON_OFFSET_FILL),t.polygonOffset(1,1);let r=n.wireColor;if(E){let e=o;t.useProgram(e.prog);let[i,a,s,c]=E.ext;j(e,[i,s,E.origin]),t.uniform4f(e.u.u_ext,0,a-i,0,c-s),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,m),t.uniform1i(e.u.u_z,1),t.uniform2i(e.u.u_n,E.w,E.h);let l=(E.w-1)*(E.h-1),u=Math.max(1,Math.ceil(Math.sqrt(l/EK))),d=Math.floor((E.w-2)/u)+1,f=Math.floor((E.h-2)/u)+1;if(t.uniform1i(e.u.u_step,u),t.uniform1f(e.u.u_alpha,n.fillAlpha),n.fill&&(t.uniform1i(e.u.u_wire,0),t.uniform4f(e.u.u_solid,0,0,0,0),t.drawArrays(t.TRIANGLES,0,d*f*6)),n.wire){let n=u*Math.max(1,Math.ceil(Math.max(d,f)/DK)),i=Math.floor((E.h-1)/n)+1,a=Math.floor((E.w-1)/n)+1;t.uniform1i(e.u.u_wire,1),t.uniform1i(e.u.u_wstep,n),t.uniform4f(e.u.u_solid,...r),t.drawArrays(t.LINES,0,(i*d+a*f)*2)}t.activeTexture(t.TEXTURE0)}if(S>0){if(w>0&&(n.fill||n.wire)){let e=a;t.useProgram(e.prog),j(e,C),M(e),t.uniform1f(e.u.u_alpha,n.fillAlpha),n.fill&&(t.uniform4f(e.u.u_solid,0,0,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,u),t.drawElements(t.TRIANGLES,w,t.UNSIGNED_INT,0)),n.wire&&(t.uniform4f(e.u.u_solid,...r),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,d),t.drawElements(t.LINES,T,t.UNSIGNED_INT,0))}let e=i;t.useProgram(e.prog),j(e,C),M(e);let o=Math.max(1,2*n.pointRadius*_);t.uniform1f(e.u.u_size,o),t.uniform1f(e.u.u_rim,o>=3?Math.max(.9,n.pointRadius*.3)*_:0),t.drawArrays(t.POINTS,0,S)}t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.DEPTH_TEST),t.bindVertexArray(null)},dispose(){for(let e of[l.x,l.y,l.z,u,d])t.deleteBuffer(e);t.deleteTexture(p),t.deleteTexture(m),t.deleteVertexArray(c)}}}var jK=new Map;function MK(e,t){let n=jK.get(e);if(!n){let r=typeof OffscreenCanvas>`u`?null:new OffscreenCanvas(1,1).getContext(`2d`,{willReadFrequently:!0});if(!r)return[0,0,0,t];r.fillStyle=e,r.fillRect(0,0,1,1);let i=r.getImageData(0,0,1,1).data;jK.set(e,n=[i[0]/255,i[1]/255,i[2]/255,i[3]/255])}return[n[0],n[1],n[2],n[3]*t]}function NK(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}function PK(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}function FK(e,t){return e.x*t.x+e.y*t.y+e.z*t.z}function IK(e){return Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z)}function LK(e){let t=IK(e);return t>1e-12?{x:e.x/t,y:e.y/t,z:e.z/t}:{x:0,y:0,z:1}}function RK(e,t,n,r){let i=Math.cos(n),a=Math.sin(n),o=Math.cos(r),s=Math.sin(r);return{x:e.x+t*o*a,y:e.y+t*s,z:e.z+t*o*i}}function zK(e,t,n){let r=LK(NK(t,e)),i=LK(PK(r,n));return{right:i,up:PK(i,r),fwd:r,eye:e}}function BK(e,t,n,r,i){let a=NK(e,t.eye),o=FK(a,t.right),s=FK(a,t.up),c=FK(a,t.fwd);if(c<.01)return{sx:-9999,sy:-9999,depth:c};let l=1/Math.tan(n/2);return{sx:r/2+o/c*l*(i/2),sy:i/2-s/c*l*(i/2),depth:c}}function VK(e,t,n,r){let i=(e,t,n)=>{let r=n-t;return r<1e-12?0:(e-t)/r*2-1};return{x:i(e,r.minX,r.maxX),y:i(n,r.minZ,r.maxZ),z:i(t,r.minY,r.maxY)}}var HK=16,UK=.1,WK=Math.PI/4,GK=Math.PI/5,KK=3.2,qK=2e4,JK=(()=>{let e=new Uint8Array(256*4);for(let t=0;t<256;t++){let{r:n,g:r,b:i}=pG(t/255);e.set([n,r,i,255],t*4)}return e})();function YK(e){if(!Array.isArray(e))return e;let t=e.length,n=new Float64Array(t),r=new Float64Array(t),i=new Float64Array(t);for(let a=0;a<t;a++)n[a]=e[a].x,r[a]=e[a].y,i[a]=e[a].z;return{length:t,x:n,y:r,z:i}}var XK=(e,t)=>!t||e>=t[0]&&e<=t[1];function ZK(e,t,n,r){let i=new Uint32Array(e.length),a=0;for(let o=0;o<e.length;o++){let s=e.x[o],c=e.y[o],l=e.z[o];s-s===0&&c-c===0&&l-l===0&&XK(s,t)&&XK(c,n)&&XK(l,r)&&(i[a++]=o)}if(a<3)return null;let o=new Float64Array(a*2);for(let t=0;t<a;t++)o[2*t]=e.x[i[t]],o[2*t+1]=e.y[i[t]];try{let e=new cK(o).triangles;for(let t=0;t<e.length;t++)e[t]=i[e[t]];return e.length>=3?e:null}catch{return null}}var QK=gt(function({points:e,surface:t,xLabel:n,yLabel:r,zLabel:i,height:a=500,backgroundToken:o=``,xRange:s,yRange:c,zRange:l,viewMode:u,pointRadius:d=4,alarms:f,showMesh:p=!1,meshStyle:m=`filled`,meshOpacity:h=.85,onPlotContextMenu:g},_){let v=K(g);G(()=>{v.current=g},[g]);let y=K(null),b=K(null),x=K(null),S=K(WK),C=K(GK),w=K(KK),T=K(null),E=K({xLabel:n,yLabel:r,zLabel:i,height:a,viewMode:u,pointRadius:d,alarms:f??[],showMesh:p,meshStyle:m,meshOpacity:h});G(()=>{E.current={xLabel:n,yLabel:r,zLabel:i,height:a,viewMode:u,pointRadius:d,alarms:f??[],showMesh:p,meshStyle:m,meshOpacity:h}},[n,r,i,a,u,d,f,p,m,h]);let D=St(()=>{let n=YK(e),r=1/0,i=-1/0,a=1/0,o=-1/0,u=1/0,d=-1/0,f=0,p=0,m=0,h=0;for(let e=0;e<n.length;e++){let t=n.x[e],g=n.y[e],_=n.z[e];t-t!==0||g-g!==0||_-_!==0||!XK(t,s)||!XK(g,c)||!XK(_,l)||(t<r&&(r=t),t>i&&(i=t),g<a&&(a=g),g>o&&(o=g),_<u&&(u=_),_>d&&(d=_),f+=t,p+=g,m+=_,h++)}let g=null;if(t&&t.w>=2&&t.h>=2){let e=t.values,n=!1;for(let r=0;r<t.w*t.h;r++){let t=e[r];t-t===0&&(n=!0,t<u&&(u=t),t>d&&(d=t))}n&&(g=t,r=Math.min(r,t.x[0],t.x[1]),i=Math.max(i,t.x[0],t.x[1]),a=Math.min(a,t.y[0],t.y[1]),o=Math.max(o,t.y[0],t.y[1]))}if(h===0&&!g)return null;s&&(r=s[0],i=s[1]),c&&(a=c[0],o=c[1]),l&&(u=l[0],d=l[1]);let _={minX:r,maxX:i,minY:a,maxY:o,minZ:u,maxZ:d},v=h>0?VK(f/h,p/h,m/h,_):{x:0,y:0,z:0};return{cols:h>0?n:null,surface:g,bounds:_,center:v}},[e,t,s,c,l]),O=u??`3d`,k=p&&(O===`3d`||O===`xy`),A=St(()=>k&&D?.cols?ZK(D.cols,s,c,l):null,[k,D,s,c,l]),j=K({model:D,triangles:A});G(()=>{j.current={model:D,triangles:A}},[D,A]);let M=K({r:null,failed:!1,cols:null,surface:null,tris:null,size:``});function N(e,t,n){let r=M.current;!r.r&&!r.failed&&b.current&&(r.r=dH(b.current,AK),r.failed=!r.r);let i=r.r;if(!i||!b.current)return null;let a=`${e}x${t}@${n}`;r.size!==a&&(i.resize(e,t,n),b.current.style.width=`${e}px`,b.current.style.height=`${t}px`,r.size=a);let{model:o,triangles:s}=j.current,c=o?.cols??null;r.cols!==c&&(i.setPoints(c?.x??null,c?.y,c?.z),r.cols=c);let l=o?.surface??null;return r.surface!==l&&(i.setSurface(l?.values??null,l?.w,l?.h,l?.x,l?.y),r.surface=l),r.tris!==s&&(i.setTriangles(s),r.tris=s),i}W(()=>()=>{M.current.r?.dispose(),M.current.r=null},[]);let P=K(null);function F(){let e=y.current,t=x.current;if(!e||!t)return;let n=Math.max(1,t.clientWidth),r=Math.max(1,t.clientHeight),i=Math.min(2,window.devicePixelRatio||1),a=Math.floor(n*i),o=Math.floor(r*i);(e.width!==a||e.height!==o)&&(e.width=a,e.height=o);let s=e.getContext(`2d`);if(!s)return;s.setTransform(i,0,0,i,0,0);let{bg:c,muted:l,grid:u}=I(),{xLabel:d,yLabel:f,zLabel:p}=E.current,m=Math.max(.25,E.current.pointRadius??4),h=jG({top:0,right:0,bottom:0,left:0},n,r).tiny;s.fillStyle=c,s.fillRect(0,0,n,r);let g=j.current.model,_=N(n,r,i);if(!g){if(_?.setStyle({palette:JK,colorAxis:2,pointRadius:m,fill:!1,wire:!1,fillAlpha:1,wireColor:[0,0,0,0]}),_?.setPoints(null),M.current.cols=null,_?.render(),h)return;s.fillStyle=l,s.font=`13px ${Q.sans}`,UV(s);return}let v=g.bounds,b=E.current.viewMode??`3d`,T=b===`xz`?1:b===`yz`?0:2,D=[v.minX,v.minY,v.minZ][T],O=[v.maxX,v.maxY,v.maxZ][T],k=(e,t,n)=>{let r=T===0?e:T===1?t:n,i=O-D;return i>1e-12?(r-D)/i:.5},A,F,L,R=(e,t,r)=>{let i=n-28,a=t/32;for(let t=0;t<32;t++)s.fillStyle=mG(1-t/32),s.fillRect(i,e+t*a,14,a+1);s.strokeStyle=u,s.lineWidth=1,s.strokeRect(i,e,14,t),s.fillStyle=l,s.font=`9px ${Q.mono}`,s.textAlign=`right`,s.fillText(Hz(O),i-4,e+4),s.fillText(Hz(D),i-4,e+t),s.fillText(r,i-4,e-6)},z=e=>{s.fillStyle=l,s.font=`10px ${Q.sans}`,s.textAlign=`left`,s.globalAlpha=.7,s.fillText(e,HK,r-6),s.globalAlpha=1};if(b!==`3d`){let e,t,i,a,o,c,m,g,_;b===`xy`?(e=d,t=f,i=p,a=v.minX,o=v.maxX,c=v.minY,m=v.maxY,g=0,_=1):b===`xz`?(e=d,t=p,i=f,a=v.minX,o=v.maxX,c=v.minZ,m=v.maxZ,g=0,_=2):(e=f,t=p,i=d,a=v.minY,o=v.maxY,c=v.minZ,m=v.maxZ,g=1,_=2);let y=jG({left:72,right:48,top:24,bottom:52},n,r),x=Math.max(1,n-y.left-y.right),S=Math.max(1,r-y.top-y.bottom),C=o-a||1,w=m-c||1,T=e=>y.left+(e-a)/C*x,D=e=>y.top+S-(e-c)/w*S;A={left:y.left,top:y.top,width:x,height:S},L={kind:`2d`,h:g,v:_},F=(e,t,n)=>{let r=[e,t,n];return[T(r[g]),D(r[_])]};let O=Pz(C,8),k=Pz(w,8),j=Lz(a,o,O),M=Lz(c,m,k);s.strokeStyle=u,s.lineWidth=.5,s.globalAlpha=.3;for(let e of j){let t=T(e);s.beginPath(),s.moveTo(t,y.top),s.lineTo(t,y.top+S),s.stroke()}for(let e of M){let t=D(e);s.beginPath(),s.moveTo(y.left,t),s.lineTo(y.left+x,t),s.stroke()}s.globalAlpha=1,s.strokeStyle=u,s.lineWidth=1,s.strokeRect(y.left,y.top,x,S),s.save(),s.beginPath(),s.rect(y.left,y.top,x,S),s.clip();for(let e of E.current.alarms){let{axis:t,value:n,color:r,style:i,width:a}=e,o=null,c=null;b===`xy`?t===`x`?o=T(n):t===`y`&&(c=D(n)):b===`xz`?t===`x`?o=T(n):t===`z`&&(c=D(n)):t===`y`?o=T(n):t===`z`&&(c=D(n)),!(o===null&&c===null)&&(i===`dashed`?s.setLineDash([7,4]):i===`dotted`?s.setLineDash([2,4]):s.setLineDash([]),s.strokeStyle=r,s.lineWidth=a,s.globalAlpha=.9,s.beginPath(),o===null?c!==null&&(s.moveTo(y.left,c),s.lineTo(y.left+x,c)):(s.moveTo(o,y.top),s.lineTo(o,y.top+S)),s.stroke(),s.setLineDash([]),s.globalAlpha=1,s.fillStyle=r,s.font=`bold 10px ${Q.mono}`,s.globalAlpha=.95,o===null?c!==null&&(s.textAlign=`left`,s.textBaseline=`bottom`,s.fillText(Hz(n),y.left+3,c-2)):(s.textAlign=`left`,s.textBaseline=`top`,s.fillText(Hz(n),o+3,y.top+2)),s.globalAlpha=1,s.textBaseline=`alphabetic`)}if(s.restore(),!h){s.fillStyle=l,s.font=`10px ${Q.mono}`,s.textAlign=`center`,s.textBaseline=`top`;for(let e of j)s.fillText(Vz(e,O),T(e),y.top+S+6);s.textAlign=`right`,s.textBaseline=`middle`;for(let e of M)s.fillText(Vz(e,k),y.left-8,D(e));s.textBaseline=`alphabetic`,s.font=`bold 11px ${Q.mono}`,s.textAlign=`center`,s.fillStyle=`#fb7185`,s.fillText(e,y.left+x/2,r-8),s.save(),s.translate(14,y.top+S/2),s.rotate(-Math.PI/2),s.fillStyle=`#38bdf8`,s.textAlign=`center`,s.fillText(t,0,0),s.restore(),R(y.top+8,Math.min(S-20,180),i),z(`2D projection: ${b.toUpperCase()} plane · Color = ${i}`)}}else{let e=S.current,t=C.current,i=w.current,a=zK(RK(g.center,i,e,t),g.center,{x:0,y:1,z:0}),o=Math.PI/3,c=h?3:HK,m=Math.max(1,n-c*2),_=Math.max(1,r-c*2-(h?0:24));A={left:c,top:c,width:m,height:_};let y=e=>[e.x,e.y,e.z];L={kind:`3d`,eye:y(a.eye),right:y(a.right),up:y(a.up),fwd:y(a.fwd),f:1/Math.tan(o/2)};let b=e=>{let t=BK(e,a,o,m,_);return{sx:t.sx+c,sy:t.sy+c,depth:t.depth}};F=(e,t,n)=>{let r=b(VK(e,t,n,v));return r.depth<.02?null:[r.sx,r.sy]};let x=(e,t,n)=>{let r=b(e),i=b(t);r.depth<.02||i.depth<.02||(s.strokeStyle=n.color,s.lineWidth=n.width,s.globalAlpha=n.alpha??1,s.beginPath(),s.moveTo(r.sx,r.sy),s.lineTo(i.sx,i.sy),s.stroke(),s.globalAlpha=1)},T=Pz(v.maxX-v.minX,6),D=Pz(v.maxY-v.minY,6),O=Pz(v.maxZ-v.minZ,6),k=Lz(v.minX,v.maxX,T),j=Lz(v.minY,v.maxY,D),M=Lz(v.minZ,v.maxZ,O),N=Rz(v.minX,v.maxX,T/5,k),P=Rz(v.minY,v.maxY,D/5,j),I=Rz(v.minZ,v.maxZ,O/5,M);for(let[e,t]of[[{x:-1,y:-1,z:-1},{x:1,y:-1,z:-1}],[{x:1,y:-1,z:-1},{x:1,y:-1,z:1}],[{x:1,y:-1,z:1},{x:-1,y:-1,z:1}],[{x:-1,y:-1,z:1},{x:-1,y:-1,z:-1}],[{x:-1,y:1,z:-1},{x:1,y:1,z:-1}],[{x:1,y:1,z:-1},{x:1,y:1,z:1}],[{x:1,y:1,z:1},{x:-1,y:1,z:1}],[{x:-1,y:1,z:1},{x:-1,y:1,z:-1}],[{x:-1,y:-1,z:-1},{x:-1,y:1,z:-1}],[{x:1,y:-1,z:-1},{x:1,y:1,z:-1}],[{x:1,y:-1,z:1},{x:1,y:1,z:1}],[{x:-1,y:-1,z:1},{x:-1,y:1,z:1}]])x(e,t,{color:u,width:1,alpha:.65});if(!h){for(let e of k){let t=VK(e,v.minY,v.minZ,v).x;x({x:t,y:-1,z:-1},{x:t,y:-1,z:1},{color:u,width:.75,alpha:.45})}for(let e of j){let t=VK(v.minX,e,v.minZ,v).z;x({x:-1,y:-1,z:t},{x:1,y:-1,z:t},{color:u,width:.75,alpha:.45})}for(let e of P){let t=VK(v.minX,e,v.minZ,v).z;x({x:-1,y:-1,z:t},{x:1,y:-1,z:t},{color:u,width:.5,alpha:.22})}for(let e of N){let t=VK(e,v.minY,v.minZ,v).x;x({x:t,y:-1,z:-1},{x:t,y:-1,z:1},{color:u,width:.5,alpha:.22})}let e=(e,t)=>{let n=UK*(t?1:.55);x({x:e,y:-1,z:-1},{x:e,y:-1+n,z:-1},{color:`#fb7185`,width:t?1.25:.75,alpha:.95})},t=(e,t)=>{let n=UK*(t?1:.55);x({x:-1,y:-1,z:e},{x:-1+n,y:-1,z:e},{color:`#38bdf8`,width:t?1.25:.75,alpha:.95})},n=(e,t)=>{let n=UK*(t?1:.55);x({x:-1,y:e,z:-1},{x:-1+n,y:e,z:-1},{color:`#4ade80`,width:t?1.25:.75,alpha:.95})};for(let t of N)e(VK(t,v.minY,v.minZ,v).x,!1);for(let t of k)e(VK(t,v.minY,v.minZ,v).x,!0);for(let e of P)t(VK(v.minX,e,v.minZ,v).z,!1);for(let e of j)t(VK(v.minX,e,v.minZ,v).z,!0);for(let e of I)n(VK(v.minX,v.minY,e,v).y,!1);for(let e of M)n(VK(v.minX,v.minY,e,v).y,!0)}let B=(e,t,n)=>{let r=n-t;return r<1e-12?0:(e-t)/r*2-1};for(let e of E.current.alarms){let{axis:t,value:n,color:r,style:i,width:a}=e,o;if(t===`z`){let e=B(n,v.minZ,v.maxZ);o=[{x:-1,y:e,z:-1},{x:1,y:e,z:-1},{x:1,y:e,z:1},{x:-1,y:e,z:1}]}else if(t===`x`){let e=B(n,v.minX,v.maxX);o=[{x:e,y:-1,z:-1},{x:e,y:1,z:-1},{x:e,y:1,z:1},{x:e,y:-1,z:1}]}else{let e=B(n,v.minY,v.maxY);o=[{x:-1,y:-1,z:e},{x:1,y:-1,z:e},{x:1,y:1,z:e},{x:-1,y:1,z:e}]}let c=o.map(e=>b(e));if(c.every(e=>e.depth>=.02)){s.beginPath(),s.moveTo(c[0].sx,c[0].sy);for(let e=1;e<c.length;e++)s.lineTo(c[e].sx,c[e].sy);s.closePath(),s.fillStyle=r,s.globalAlpha=.18,s.fill(),i===`dashed`?s.setLineDash([7,4]):i===`dotted`?s.setLineDash([2,4]):s.setLineDash([]),s.strokeStyle=r,s.lineWidth=a,s.globalAlpha=.9,s.beginPath(),s.moveTo(c[0].sx,c[0].sy);for(let e=1;e<c.length;e++)s.lineTo(c[e].sx,c[e].sy);s.closePath(),s.stroke(),s.setLineDash([]),s.globalAlpha=1;let e=c.reduce((e,t)=>t.sy>e.sy?t:e);s.fillStyle=r,s.font=`bold 10px ${Q.mono}`,s.textAlign=`center`,s.globalAlpha=.95,s.fillText(`${t.toUpperCase()}=${Hz(n)}`,e.sx,e.sy-6),s.globalAlpha=1}}if(!h){s.font=`10px ${Q.mono}`,s.textBaseline=`middle`;for(let e of k){let t=VK(e,v.minY,v.minZ,v).x,n=b({x:t,y:-1.2,z:-1.2});n.depth<.02||(s.fillStyle=l,s.textAlign=`center`,s.fillText(Vz(e,T),n.sx,n.sy+12))}for(let e of j){let t=VK(v.minX,e,v.minZ,v).z,n=b({x:-1.22,y:-1,z:t});n.depth<.02||(s.textAlign=`right`,s.fillText(Vz(e,D),n.sx-4,n.sy))}for(let e of M){let t=VK(v.minX,v.minY,e,v).y,n=b({x:-1.22,y:t,z:-1.2});n.depth<.02||(s.textAlign=`right`,s.fillText(Vz(e,O),n.sx-4,n.sy))}s.textBaseline=`alphabetic`,s.font=`bold 11px ${Q.mono}`;let e=b({x:1.15,y:-1,z:-1.15});e.depth>=.02&&(s.fillStyle=`#fb7185`,s.textAlign=`center`,s.fillText(d,e.sx,e.sy+16)),e=b({x:-1.18,y:-1,z:1.15}),e.depth>=.02&&(s.fillStyle=`#38bdf8`,s.textAlign=`center`,s.fillText(f,e.sx-10,e.sy)),e=b({x:-1.18,y:1.15,z:-1.18}),e.depth>=.02&&(s.fillStyle=`#4ade80`,s.textAlign=`center`,s.fillText(p,e.sx-10,e.sy)),R(HK+8,Math.min(r-80,180),p),z(`Drag: rotate | Wheel: zoom | Dbl‑click: reset · ${g.surface?`Surface`:E.current.showMesh?`Mesh: ${E.current.meshStyle}`:`Scatter`} · color = Z`)}}let{showMesh:B,meshStyle:V,meshOpacity:ee}=E.current,te=!!g.surface||B;if(_)_.setBounds(v),_.setView(L,A),_.setStyle({palette:JK,colorAxis:T,pointRadius:m,fill:te&&(V===`filled`||V===`both`),wire:te&&(V===`wireframe`||V===`both`),fillAlpha:ee,wireColor:MK(u,.5)}),_.render(),P.current!==g&&(P.current=g,BH(t));else if(g.cols){let e=g.cols,t=Math.max(1,Math.ceil(e.length/qK));for(let n=0;n<e.length;n+=t){let t=e.x[n],r=e.y[n],i=e.z[n];if(!(t>=v.minX&&t<=v.maxX&&r>=v.minY&&r<=v.maxY&&i>=v.minZ&&i<=v.maxZ))continue;let a=F(t,r,i);a&&(s.fillStyle=mG(k(t,r,i)),s.beginPath(),s.arc(a[0],a[1],m,0,Math.PI*2),s.fill())}}}function I(){if(T.current)return T.current;let e=x.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return T.current=n,n}let L=K(F);G(()=>{L.current=F});let R=K(null);R.current??=GH(()=>L.current(),()=>x.current),W(()=>()=>R.current?.cancel(),[]);let z=()=>{S.current=WK,C.current=GK,w.current=KK,R.current.schedule()};return xt(_,()=>({autoscale:z}),[]),W(()=>uB(x.current,()=>{T.current=null,R.current.schedule()}),[]),W(()=>{T.current=null,R.current.schedule()},[o]),W(()=>{R.current.now()},[D,A,n,r,i,a,u,d,f,p,m,h]),W(()=>{let e=y.current,t=x.current;if(!e||!t)return;let n=()=>R.current.schedule(),r=new UH(()=>{T.current=null,n()});r.observe(t);let i=!1,a=0,o=0,s=t=>{t.button===0&&(i=!0,a=t.clientX,o=t.clientY,e.setPointerCapture(t.pointerId))},c=e=>{if(!i)return;let t=e.clientX-a,r=e.clientY-o;a=e.clientX,o=e.clientY,S.current-=t*.008,C.current+=r*.008,C.current=Math.max(-Math.PI/2+.05,Math.min(Math.PI/2-.05,C.current)),n()},l=()=>{i=!1},u=e=>{e.preventDefault();let t=e.deltaY>0?1.08:.92;w.current=Math.max(1.2,Math.min(12,w.current*t)),n()},d=()=>{S.current=WK,C.current=GK,w.current=KK,n()},f=e=>{e.preventDefault(),v.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`pointerdown`,s),e.addEventListener(`pointermove`,c),e.addEventListener(`pointerup`,l),e.addEventListener(`pointercancel`,l),e.addEventListener(`wheel`,u,{passive:!1}),e.addEventListener(`contextmenu`,f),e.addEventListener(`dblclick`,d),()=>{r.disconnect(),e.removeEventListener(`pointerdown`,s),e.removeEventListener(`pointermove`,c),e.removeEventListener(`pointerup`,l),e.removeEventListener(`pointercancel`,l),e.removeEventListener(`wheel`,u),e.removeEventListener(`contextmenu`,f),e.removeEventListener(`dblclick`,d)}},[]),Ot(`div`,{ref:x,className:`chart-canvas-wrap`,children:[q(`canvas`,{ref:y,className:`chart-canvas`,role:`img`,"aria-label":`3D scatter: ${n} vs ${r} vs ${i}`,style:{display:`block`,width:`100%`,height:`100%`,cursor:`grab`}}),q(`canvas`,{ref:b,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}})]})}),$K={top:14,right:24,bottom:40,left:64},eq=5;function tq(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}function nq(e){return Math.max(10,Math.min(200,Math.ceil(Math.sqrt(e))))}function rq(e,t,n){let r=(e-t)/n;return Math.exp(-.5*r*r)/(n*Math.sqrt(2*Math.PI))}function iq(e,t){let n=e.length;if(n===0)return null;let r=1/0,i=-1/0,a=0;for(let t=0;t<n;t++){let n=e[t];n<r&&(r=n),n>i&&(i=n),a+=n}r===i&&(--r,i+=1);let o=t>0?t:nq(n),s=(i-r)/o,c=Array(o).fill(0),l=a/n,u=0;for(let t=0;t<n;t++){let n=e[t];c[Math.min(o-1,Math.floor((n-r)/s))]++,u+=(n-l)**2}return{lo:r,hi:i,nBins:o,width:s,counts:c,mean:l,sd:Math.sqrt(u/n),total:n}}function aq({values:e,label:t,bins:n=0,color:r=`#38bdf8`,showNormal:i=!1,logY:a=!1,height:o=400,backgroundToken:s=``,onPlotContextMenu:c}){let l=FU(),u=K(null),d=K(null),f=K(null),p=K(null),m=K(0),h=K(null),g=K(c);G(()=>{g.current=c},[c]);let _=K({values:e,label:t,bins:n,color:r,showNormal:i,logY:a,height:o});G(()=>{_.current={values:e,label:t,bins:n,color:r,showNormal:i,logY:a,height:o}},[e,t,n,r,i,a,o]);function v(){if(h.current)return h.current;let e=f.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return h.current=n,n}function y(){let e=f.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||_.current.height)}}function b(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}let x=St(()=>iq(e,n),[e,n]),S=K(x);G(()=>{S.current=x},[x]);let C=()=>S.current;function w(){let e=u.current;if(!e)return;let{w:t,h:n}=y(),r=b(e,t,n);if(!r)return;let{top:i,right:a,bottom:o,left:s}=$K,c=t-s-a,d=n-i-o,{bg:f,muted:p,grid:m}=v(),{label:h,color:g,showNormal:x,logY:S}=_.current;r.fillStyle=f,r.fillRect(0,0,t,n);let w=C();if(!w||c<=0||d<=0){r.fillStyle=p,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{lo:T,hi:E,nBins:D,width:O,counts:k,mean:A,sd:j,total:M}=w,N=Math.max(...k),P=S?Math.log10(N+1)+.1:N*1.08,F=e=>s+(e-T)/(E-T)*c;l({left:s,top:i,width:c,height:d,x:{v0:T,v1:E}});let I=e=>i+(P-(S?e>0?Math.log10(e):0:e))/(P-0)*d,L=S?1:Pz(P,5),R=Lz(0,S?P:N,L);r.strokeStyle=m,r.lineWidth=1,r.setLineDash(tq(`dashed`));for(let e of R){let t=I(e);r.beginPath(),r.moveTo(s,t),r.lineTo(s+c,t),r.stroke()}r.setLineDash([]);let z=Math.max(.5,c/D*.04);for(let e=0;e<D;e++){let t=F(T+e*O)+z/2,n=F(T+(e+1)*O)-z/2,i=I(0),a=I(k[e]);r.fillStyle=g,r.globalAlpha=.75,r.fillRect(t,a,n-t,i-a),r.globalAlpha=1}if(x&&j>0){r.beginPath();for(let e=0;e<=200;e++){let t=T+e/200*(E-T),n=rq(t,A,j)*M*O,i=F(t),a=I(n);e===0?r.moveTo(i,a):r.lineTo(i,a)}r.strokeStyle=`#f97316`,r.lineWidth=1,r.stroke()}r.strokeStyle=p,r.lineWidth=1,r.fillStyle=p,r.font=`11px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of R){let t=I(e);r.beginPath(),r.moveTo(s-eq,t),r.lineTo(s,t),r.stroke(),r.fillText(S?`10^${e.toFixed(0)}`:Vz(e,L),s-4,t)}let B=Pz(E-T,Fz(c)),V=Lz(T,E,B);r.fillStyle=p,r.textAlign=`center`,r.textBaseline=`top`;for(let e of V){let t=F(e);r.beginPath(),r.moveTo(t,i+d),r.lineTo(t,i+d+eq),r.stroke(),r.fillText(Vz(e,B),t,i+d+eq+2)}r.strokeStyle=m,r.lineWidth=1,r.strokeRect(s,i,c,d),r.fillStyle=p,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(h,s+c/2,n-4),r.save(),r.translate(14,i+d/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(S?`log₁₀(count)`:`count`,0,0),r.restore()}let T=K(w);T.current=w;let E=K(null);E.current??=GH(()=>T.current(),()=>f.current);let D=()=>E.current.schedule();function O(e){let t=d.current;if(!t)return;let{w:n,h:r}=y(),i=b(t,n,r);if(!i||(i.clearRect(0,0,n,r),e===null))return;let{top:a,right:o,bottom:s,left:c}=$K,l=n-c-o,u=r-a-s,{muted:f}=v(),p=C();if(!p)return;let{lo:m,hi:h,width:g,counts:_}=p,x=e=>c+(e-m)/(h-m)*l,S=x(m+e*g),w=x(m+(e+1)*g);i.fillStyle=`rgba(255,255,255,0.12)`,i.fillRect(S,a,w-S,u);let T=(S+w)/2,E=_[e],D=(E/p.total*100).toFixed(1),O=`${Hz(m+e*g)} – ${Hz(m+(e+1)*g)}`,k=`n = ${E} (${D}%)`;i.font=`11px ${Q.mono}`;let A=i.measureText(k).width,j=i.measureText(O).width,M=Math.max(A,j),N=Math.min(T+8,c+l-M-8);i.fillStyle=f,i.textAlign=`left`,i.textBaseline=`top`,i.fillText(O,N,a+8),i.fillText(k,N,a+22)}function k(){RH(m.current),m.current=LH(()=>O(p.current))}return W(()=>{E.current.now()}),W(()=>()=>E.current?.cancel(),[]),W(()=>{h.current=null,D()},[s]),G(()=>{let e=f.current;if(!e)return;let t=new UH(()=>{h.current=null,D(),k()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=d.current;if(!e)return;function t(t){let n=e.getBoundingClientRect(),{left:r}=$K,i=n.width-$K.left-$K.right,a=C();if(!a||i<=0){p.current=null,k();return}let o=t.clientX-n.left-r,s=Math.floor(o/i*a.nBins);p.current=s>=0&&s<a.nBins?s:null,k()}function n(){p.current=null,k()}function r(e){e.preventDefault(),g.current?.({clientX:e.clientX,clientY:e.clientY})}return e.addEventListener(`mousemove`,t),e.addEventListener(`mouseleave`,n),e.addEventListener(`contextmenu`,r),()=>{e.removeEventListener(`mousemove`,t),e.removeEventListener(`mouseleave`,n),e.removeEventListener(`contextmenu`,r)}},[]),Ot(`div`,{ref:f,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:u,className:`chart-canvas`,role:`img`,"aria-label":`Histogram of ${t}`}),q(`canvas`,{ref:d,className:`chart-canvas chart-overlay`})]})}var oq=`
|
|
484
|
+
}`,DK=16e6,OK=128,kK=[`u_lo`,`u_span`,`u_flat`,`u_eye`,`u_right`,`u_up`,`u_fwd`,`u_f`,`u_h`,`u_v`,`u_c`,`u_plot`,`u_resolution`,`u_palette`];function AK(e){for(let t=0;t<e.length;t++)if(e[t]===e[t]&&Math.abs(e[t])!==1/0)return e[t];return 0}function jK(e){let t=e.getContext(`webgl2`,{antialias:!0,alpha:!0,premultipliedAlpha:!0,depth:!0});if(!t)return null;let n=(e,n,r,i)=>uH(t,`gl3d|${e}|${n}`,()=>{let a=QV(t,t.VERTEX_SHADER,e),o=QV(t,t.FRAGMENT_SHADER,n);if(!a||!o)return null;let s=t.createProgram();return t.attachShader(s,a),t.attachShader(s,o),t.linkProgram(s),t.getProgramParameter(s,t.LINK_STATUS)?{prog:s,a:Object.fromEntries(r.map(e=>[e,t.getAttribLocation(s,e)])),u:Object.fromEntries([...kK,...i].map(e=>[e,t.getUniformLocation(s,e)]))}:(console.error(`gl3d program link failed:`,t.getProgramInfoLog(s)),null)}),r=[`a_x`,`a_y`,`a_z`],i=n(xK,SK,r,[`u_size`,`u_rim`]),a=n(CK,TK,r,[`u_alpha`,`u_solid`]),o=n(wK,EK,[],[`u_alpha`,`u_solid`,`u_z`,`u_n`,`u_step`,`u_wstep`,`u_wire`,`u_ext`]);if(!i||!a||!o)return null;let s=t.getParameter(t.MAX_TEXTURE_SIZE),c=t.createVertexArray(),l={x:t.createBuffer(),y:t.createBuffer(),z:t.createBuffer()},u=t.createBuffer(),d=t.createBuffer(),f=new Map,p=t.createTexture(),m=t.createTexture(),h=1,g=1,_=1,v={minX:0,maxX:1,minY:0,maxY:1,minZ:0,maxZ:1},y={kind:`2d`,h:0,v:1},b={left:0,top:0,width:1,height:1},x=null,S=0,C=[0,0,0],w=0,T=0,E=null,D={w:0,h:0},O=new Float32Array,k=(e,n,r)=>{t.bindBuffer(e,n),r.byteLength<=(f.get(n)??0)?t.bufferSubData(e,0,r):(t.bufferData(e,r,t.DYNAMIC_DRAW),f.set(n,r.byteLength))},A=(e,t)=>{let n=e.length;O.length<n&&(O=new Float32Array(n));for(let r=0;r<n;r++)O[r]=e[r]-t;return O.subarray(0,n)},j=(e,n)=>{let r=e.u,i=v;t.uniform3f(r.u_lo,i.minX-n[0],i.minY-n[1],i.minZ-n[2]);let a=(e,t)=>t-e>1e-12*Math.max(1,Math.abs(e))?t-e:0;t.uniform3f(r.u_span,a(i.minX,i.maxX),a(i.minY,i.maxY),a(i.minZ,i.maxZ));let o=e=>[+(e===0),+(e===1),+(e===2)];y.kind===`3d`?(t.uniform1i(r.u_flat,0),t.uniform3f(r.u_eye,...y.eye),t.uniform3f(r.u_right,...y.right),t.uniform3f(r.u_up,...y.up),t.uniform3f(r.u_fwd,...y.fwd),t.uniform1f(r.u_f,y.f)):(t.uniform1i(r.u_flat,1),t.uniform3f(r.u_h,...o(y.h)),t.uniform3f(r.u_v,...o(y.v))),t.uniform3f(r.u_c,...o(x.colorAxis)),t.uniform4f(r.u_plot,b.left,b.top,b.width,b.height),t.uniform2f(r.u_resolution,h,g),t.uniform1i(r.u_palette,0)},M=e=>{for(let n of[`x`,`y`,`z`]){let r=e.a[`a_${n}`];t.bindBuffer(t.ARRAY_BUFFER,l[n]),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,1,t.FLOAT,!1,0,0)}};return{maxTextureSize:s,resize(t,n,r){h=Math.max(1,t),g=Math.max(1,n),_=r,e.width=Math.max(1,Math.round(h*_)),e.height=Math.max(1,Math.round(g*_))},setBounds(e){v=e},setView(e,t){y=e,b=t},setPoints(e,n,r){if(!e||!n||!r){S=0;return}S=Math.min(e.length,n.length,r.length),C=[AK(e),AK(n),AK(r)],k(t.ARRAY_BUFFER,l.x,A(e,C[0]).subarray(0,S)),k(t.ARRAY_BUFFER,l.y,A(n,C[1]).subarray(0,S)),k(t.ARRAY_BUFFER,l.z,A(r,C[2]).subarray(0,S))},setTriangles(e){if(!e||e.length<3){w=T=0;return}w=e.length-e.length%3,k(t.ELEMENT_ARRAY_BUFFER,u,e.subarray(0,w));let n=new Uint32Array(w*2);for(let t=0;t<w;t+=3){let r=e[t],i=e[t+1],a=e[t+2],o=t*2;n[o]=r,n[o+1]=i,n[o+2]=i,n[o+3]=a,n[o+4]=a,n[o+5]=r}T=n.length,k(t.ELEMENT_ARRAY_BUFFER,d,n)},setSurface(e,n=0,r=0,i=[0,1],a=[0,1]){if(!e||n<2||r<2||n>s||r>s){E=null;return}let o=AK(e),c=A(e,o).subarray(0,n*r);t.bindTexture(t.TEXTURE_2D,m),t.pixelStorei(t.UNPACK_ALIGNMENT,4),D.w===n&&D.h===r?t.texSubImage2D(t.TEXTURE_2D,0,0,0,n,r,t.RED,t.FLOAT,c):(t.texImage2D(t.TEXTURE_2D,0,t.R32F,n,r,0,t.RED,t.FLOAT,c),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),D={w:n,h:r}),E={w:n,h:r,origin:o,ext:[i[0],i[1],a[0],a[1]]}},setStyle(e){x?.palette!==e.palette&&(t.bindTexture(t.TEXTURE_2D,p),t.texImage2D(t.TEXTURE_2D,0,t.RGBA8,256,1,0,t.RGBA,t.UNSIGNED_BYTE,e.palette),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)),x=e},render(){t.viewport(0,0,e.width,e.height),t.clearColor(0,0,0,0),t.clearDepth(1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT);let n=x;if(!n)return;t.bindVertexArray(c),t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,p),t.enable(t.POLYGON_OFFSET_FILL),t.polygonOffset(1,1);let r=n.wireColor;if(E){let e=o;t.useProgram(e.prog);let[i,a,s,c]=E.ext;j(e,[i,s,E.origin]),t.uniform4f(e.u.u_ext,0,a-i,0,c-s),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,m),t.uniform1i(e.u.u_z,1),t.uniform2i(e.u.u_n,E.w,E.h);let l=(E.w-1)*(E.h-1),u=Math.max(1,Math.ceil(Math.sqrt(l/DK))),d=Math.floor((E.w-2)/u)+1,f=Math.floor((E.h-2)/u)+1;if(t.uniform1i(e.u.u_step,u),t.uniform1f(e.u.u_alpha,n.fillAlpha),n.fill&&(t.uniform1i(e.u.u_wire,0),t.uniform4f(e.u.u_solid,0,0,0,0),t.drawArrays(t.TRIANGLES,0,d*f*6)),n.wire){let n=u*Math.max(1,Math.ceil(Math.max(d,f)/OK)),i=Math.floor((E.h-1)/n)+1,a=Math.floor((E.w-1)/n)+1;t.uniform1i(e.u.u_wire,1),t.uniform1i(e.u.u_wstep,n),t.uniform4f(e.u.u_solid,...r),t.drawArrays(t.LINES,0,(i*d+a*f)*2)}t.activeTexture(t.TEXTURE0)}if(S>0){if(w>0&&(n.fill||n.wire)){let e=a;t.useProgram(e.prog),j(e,C),M(e),t.uniform1f(e.u.u_alpha,n.fillAlpha),n.fill&&(t.uniform4f(e.u.u_solid,0,0,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,u),t.drawElements(t.TRIANGLES,w,t.UNSIGNED_INT,0)),n.wire&&(t.uniform4f(e.u.u_solid,...r),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,d),t.drawElements(t.LINES,T,t.UNSIGNED_INT,0))}let e=i;t.useProgram(e.prog),j(e,C),M(e);let o=Math.max(1,2*n.pointRadius*_);t.uniform1f(e.u.u_size,o),t.uniform1f(e.u.u_rim,o>=3?Math.max(.9,n.pointRadius*.3)*_:0),t.drawArrays(t.POINTS,0,S)}t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.DEPTH_TEST),t.bindVertexArray(null)},dispose(){for(let e of[l.x,l.y,l.z,u,d])t.deleteBuffer(e);t.deleteTexture(p),t.deleteTexture(m),t.deleteVertexArray(c)}}}var MK=new Map;function NK(e,t){let n=MK.get(e);if(!n){let r=typeof OffscreenCanvas>`u`?null:new OffscreenCanvas(1,1).getContext(`2d`,{willReadFrequently:!0});if(!r)return[0,0,0,t];r.fillStyle=e,r.fillRect(0,0,1,1);let i=r.getImageData(0,0,1,1).data;MK.set(e,n=[i[0]/255,i[1]/255,i[2]/255,i[3]/255])}return[n[0],n[1],n[2],n[3]*t]}function PK(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}function FK(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}function IK(e,t){return e.x*t.x+e.y*t.y+e.z*t.z}function LK(e){return Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z)}function RK(e){let t=LK(e);return t>1e-12?{x:e.x/t,y:e.y/t,z:e.z/t}:{x:0,y:0,z:1}}function zK(e,t,n,r){let i=Math.cos(n),a=Math.sin(n),o=Math.cos(r),s=Math.sin(r);return{x:e.x+t*o*a,y:e.y+t*s,z:e.z+t*o*i}}function BK(e,t,n){let r=RK(PK(t,e)),i=RK(FK(r,n));return{right:i,up:FK(i,r),fwd:r,eye:e}}function VK(e,t,n,r,i){let a=PK(e,t.eye),o=IK(a,t.right),s=IK(a,t.up),c=IK(a,t.fwd);if(c<.01)return{sx:-9999,sy:-9999,depth:c};let l=1/Math.tan(n/2);return{sx:r/2+o/c*l*(i/2),sy:i/2-s/c*l*(i/2),depth:c}}function HK(e,t,n,r){let i=(e,t,n)=>{let r=n-t;return r<1e-12?0:(e-t)/r*2-1};return{x:i(e,r.minX,r.maxX),y:i(n,r.minZ,r.maxZ),z:i(t,r.minY,r.maxY)}}var UK=16,WK=.1,GK=Math.PI/4,KK=Math.PI/5,qK=3.2,JK=2e4,YK=(()=>{let e=new Uint8Array(256*4);for(let t=0;t<256;t++){let{r:n,g:r,b:i}=mG(t/255);e.set([n,r,i,255],t*4)}return e})();function XK(e){if(!Array.isArray(e))return e;let t=e.length,n=new Float64Array(t),r=new Float64Array(t),i=new Float64Array(t);for(let a=0;a<t;a++)n[a]=e[a].x,r[a]=e[a].y,i[a]=e[a].z;return{length:t,x:n,y:r,z:i}}var ZK=(e,t)=>!t||e>=t[0]&&e<=t[1];function QK(e,t,n,r){let i=new Uint32Array(e.length),a=0;for(let o=0;o<e.length;o++){let s=e.x[o],c=e.y[o],l=e.z[o];s-s===0&&c-c===0&&l-l===0&&ZK(s,t)&&ZK(c,n)&&ZK(l,r)&&(i[a++]=o)}if(a<3)return null;let o=new Float64Array(a*2);for(let t=0;t<a;t++)o[2*t]=e.x[i[t]],o[2*t+1]=e.y[i[t]];try{let e=new lK(o).triangles;for(let t=0;t<e.length;t++)e[t]=i[e[t]];return e.length>=3?e:null}catch{return null}}var $K=gt(function({points:e,surface:t,xLabel:n,yLabel:r,zLabel:i,height:a=500,backgroundToken:o=``,xRange:s,yRange:c,zRange:l,viewMode:u,pointRadius:d=4,alarms:f,showMesh:p=!1,meshStyle:m=`filled`,meshOpacity:h=.85,onPlotContextMenu:g},_){let v=K(g);G(()=>{v.current=g},[g]);let y=K(null),b=K(null),x=K(null),S=K(GK),C=K(KK),w=K(qK),T=K(null),E=K({xLabel:n,yLabel:r,zLabel:i,height:a,viewMode:u,pointRadius:d,alarms:f??[],showMesh:p,meshStyle:m,meshOpacity:h});G(()=>{E.current={xLabel:n,yLabel:r,zLabel:i,height:a,viewMode:u,pointRadius:d,alarms:f??[],showMesh:p,meshStyle:m,meshOpacity:h}},[n,r,i,a,u,d,f,p,m,h]);let D=St(()=>{let n=XK(e),r=1/0,i=-1/0,a=1/0,o=-1/0,u=1/0,d=-1/0,f=0,p=0,m=0,h=0;for(let e=0;e<n.length;e++){let t=n.x[e],g=n.y[e],_=n.z[e];t-t!==0||g-g!==0||_-_!==0||!ZK(t,s)||!ZK(g,c)||!ZK(_,l)||(t<r&&(r=t),t>i&&(i=t),g<a&&(a=g),g>o&&(o=g),_<u&&(u=_),_>d&&(d=_),f+=t,p+=g,m+=_,h++)}let g=null;if(t&&t.w>=2&&t.h>=2){let e=t.values,n=!1;for(let r=0;r<t.w*t.h;r++){let t=e[r];t-t===0&&(n=!0,t<u&&(u=t),t>d&&(d=t))}n&&(g=t,r=Math.min(r,t.x[0],t.x[1]),i=Math.max(i,t.x[0],t.x[1]),a=Math.min(a,t.y[0],t.y[1]),o=Math.max(o,t.y[0],t.y[1]))}if(h===0&&!g)return null;s&&(r=s[0],i=s[1]),c&&(a=c[0],o=c[1]),l&&(u=l[0],d=l[1]);let _={minX:r,maxX:i,minY:a,maxY:o,minZ:u,maxZ:d},v=h>0?HK(f/h,p/h,m/h,_):{x:0,y:0,z:0};return{cols:h>0?n:null,surface:g,bounds:_,center:v}},[e,t,s,c,l]),O=u??`3d`,k=p&&(O===`3d`||O===`xy`),A=St(()=>k&&D?.cols?QK(D.cols,s,c,l):null,[k,D,s,c,l]),j=K({model:D,triangles:A});G(()=>{j.current={model:D,triangles:A}},[D,A]);let M=K({r:null,failed:!1,cols:null,surface:null,tris:null,size:``});function N(e,t,n){let r=M.current;!r.r&&!r.failed&&b.current&&(r.r=dH(b.current,jK),r.failed=!r.r);let i=r.r;if(!i||!b.current)return null;let a=`${e}x${t}@${n}`;r.size!==a&&(i.resize(e,t,n),b.current.style.width=`${e}px`,b.current.style.height=`${t}px`,r.size=a);let{model:o,triangles:s}=j.current,c=o?.cols??null;r.cols!==c&&(i.setPoints(c?.x??null,c?.y,c?.z),r.cols=c);let l=o?.surface??null;return r.surface!==l&&(i.setSurface(l?.values??null,l?.w,l?.h,l?.x,l?.y),r.surface=l),r.tris!==s&&(i.setTriangles(s),r.tris=s),i}W(()=>()=>{M.current.r?.dispose(),M.current.r=null},[]);let P=K(null);function F(){let e=y.current,t=x.current;if(!e||!t)return;let n=Math.max(1,t.clientWidth),r=Math.max(1,t.clientHeight),i=Math.min(2,window.devicePixelRatio||1),a=Math.floor(n*i),o=Math.floor(r*i);(e.width!==a||e.height!==o)&&(e.width=a,e.height=o);let s=e.getContext(`2d`);if(!s)return;s.setTransform(i,0,0,i,0,0);let{bg:c,muted:l,grid:u}=I(),{xLabel:d,yLabel:f,zLabel:p}=E.current,m=Math.max(.25,E.current.pointRadius??4),h=MG({top:0,right:0,bottom:0,left:0},n,r).tiny;s.fillStyle=c,s.fillRect(0,0,n,r);let g=j.current.model,_=N(n,r,i);if(!g){if(_?.setStyle({palette:YK,colorAxis:2,pointRadius:m,fill:!1,wire:!1,fillAlpha:1,wireColor:[0,0,0,0]}),_?.setPoints(null),M.current.cols=null,_?.render(),h)return;s.fillStyle=l,s.font=`13px ${Q.sans}`,UV(s);return}let v=g.bounds,b=E.current.viewMode??`3d`,T=b===`xz`?1:b===`yz`?0:2,D=[v.minX,v.minY,v.minZ][T],O=[v.maxX,v.maxY,v.maxZ][T],k=(e,t,n)=>{let r=T===0?e:T===1?t:n,i=O-D;return i>1e-12?(r-D)/i:.5},A,F,L,R=(e,t,r)=>{let i=n-28,a=t/32;for(let t=0;t<32;t++)s.fillStyle=hG(1-t/32),s.fillRect(i,e+t*a,14,a+1);s.strokeStyle=u,s.lineWidth=1,s.strokeRect(i,e,14,t),s.fillStyle=l,s.font=`9px ${Q.mono}`,s.textAlign=`right`,s.fillText(Hz(O),i-4,e+4),s.fillText(Hz(D),i-4,e+t),s.fillText(r,i-4,e-6)},z=e=>{s.fillStyle=l,s.font=`10px ${Q.sans}`,s.textAlign=`left`,s.globalAlpha=.7,s.fillText(e,UK,r-6),s.globalAlpha=1};if(b!==`3d`){let e,t,i,a,o,c,m,g,_;b===`xy`?(e=d,t=f,i=p,a=v.minX,o=v.maxX,c=v.minY,m=v.maxY,g=0,_=1):b===`xz`?(e=d,t=p,i=f,a=v.minX,o=v.maxX,c=v.minZ,m=v.maxZ,g=0,_=2):(e=f,t=p,i=d,a=v.minY,o=v.maxY,c=v.minZ,m=v.maxZ,g=1,_=2);let y=MG({left:72,right:48,top:24,bottom:52},n,r),x=Math.max(1,n-y.left-y.right),S=Math.max(1,r-y.top-y.bottom),C=o-a||1,w=m-c||1,T=e=>y.left+(e-a)/C*x,D=e=>y.top+S-(e-c)/w*S;A={left:y.left,top:y.top,width:x,height:S},L={kind:`2d`,h:g,v:_},F=(e,t,n)=>{let r=[e,t,n];return[T(r[g]),D(r[_])]};let O=Pz(C,8),k=Pz(w,8),j=Lz(a,o,O),M=Lz(c,m,k);s.strokeStyle=u,s.lineWidth=.5,s.globalAlpha=.3;for(let e of j){let t=T(e);s.beginPath(),s.moveTo(t,y.top),s.lineTo(t,y.top+S),s.stroke()}for(let e of M){let t=D(e);s.beginPath(),s.moveTo(y.left,t),s.lineTo(y.left+x,t),s.stroke()}s.globalAlpha=1,s.strokeStyle=u,s.lineWidth=1,s.strokeRect(y.left,y.top,x,S),s.save(),s.beginPath(),s.rect(y.left,y.top,x,S),s.clip();for(let e of E.current.alarms){let{axis:t,value:n,color:r,style:i,width:a}=e,o=null,c=null;b===`xy`?t===`x`?o=T(n):t===`y`&&(c=D(n)):b===`xz`?t===`x`?o=T(n):t===`z`&&(c=D(n)):t===`y`?o=T(n):t===`z`&&(c=D(n)),!(o===null&&c===null)&&(i===`dashed`?s.setLineDash([7,4]):i===`dotted`?s.setLineDash([2,4]):s.setLineDash([]),s.strokeStyle=r,s.lineWidth=a,s.globalAlpha=.9,s.beginPath(),o===null?c!==null&&(s.moveTo(y.left,c),s.lineTo(y.left+x,c)):(s.moveTo(o,y.top),s.lineTo(o,y.top+S)),s.stroke(),s.setLineDash([]),s.globalAlpha=1,s.fillStyle=r,s.font=`bold 10px ${Q.mono}`,s.globalAlpha=.95,o===null?c!==null&&(s.textAlign=`left`,s.textBaseline=`bottom`,s.fillText(Hz(n),y.left+3,c-2)):(s.textAlign=`left`,s.textBaseline=`top`,s.fillText(Hz(n),o+3,y.top+2)),s.globalAlpha=1,s.textBaseline=`alphabetic`)}if(s.restore(),!h){s.fillStyle=l,s.font=`10px ${Q.mono}`,s.textAlign=`center`,s.textBaseline=`top`;for(let e of j)s.fillText(Vz(e,O),T(e),y.top+S+6);s.textAlign=`right`,s.textBaseline=`middle`;for(let e of M)s.fillText(Vz(e,k),y.left-8,D(e));s.textBaseline=`alphabetic`,s.font=`bold 11px ${Q.mono}`,s.textAlign=`center`,s.fillStyle=`#fb7185`,s.fillText(e,y.left+x/2,r-8),s.save(),s.translate(14,y.top+S/2),s.rotate(-Math.PI/2),s.fillStyle=`#38bdf8`,s.textAlign=`center`,s.fillText(t,0,0),s.restore(),R(y.top+8,Math.min(S-20,180),i),z(`2D projection: ${b.toUpperCase()} plane · Color = ${i}`)}}else{let e=S.current,t=C.current,i=w.current,a=BK(zK(g.center,i,e,t),g.center,{x:0,y:1,z:0}),o=Math.PI/3,c=h?3:UK,m=Math.max(1,n-c*2),_=Math.max(1,r-c*2-(h?0:24));A={left:c,top:c,width:m,height:_};let y=e=>[e.x,e.y,e.z];L={kind:`3d`,eye:y(a.eye),right:y(a.right),up:y(a.up),fwd:y(a.fwd),f:1/Math.tan(o/2)};let b=e=>{let t=VK(e,a,o,m,_);return{sx:t.sx+c,sy:t.sy+c,depth:t.depth}};F=(e,t,n)=>{let r=b(HK(e,t,n,v));return r.depth<.02?null:[r.sx,r.sy]};let x=(e,t,n)=>{let r=b(e),i=b(t);r.depth<.02||i.depth<.02||(s.strokeStyle=n.color,s.lineWidth=n.width,s.globalAlpha=n.alpha??1,s.beginPath(),s.moveTo(r.sx,r.sy),s.lineTo(i.sx,i.sy),s.stroke(),s.globalAlpha=1)},T=Pz(v.maxX-v.minX,6),D=Pz(v.maxY-v.minY,6),O=Pz(v.maxZ-v.minZ,6),k=Lz(v.minX,v.maxX,T),j=Lz(v.minY,v.maxY,D),M=Lz(v.minZ,v.maxZ,O),N=Rz(v.minX,v.maxX,T/5,k),P=Rz(v.minY,v.maxY,D/5,j),I=Rz(v.minZ,v.maxZ,O/5,M);for(let[e,t]of[[{x:-1,y:-1,z:-1},{x:1,y:-1,z:-1}],[{x:1,y:-1,z:-1},{x:1,y:-1,z:1}],[{x:1,y:-1,z:1},{x:-1,y:-1,z:1}],[{x:-1,y:-1,z:1},{x:-1,y:-1,z:-1}],[{x:-1,y:1,z:-1},{x:1,y:1,z:-1}],[{x:1,y:1,z:-1},{x:1,y:1,z:1}],[{x:1,y:1,z:1},{x:-1,y:1,z:1}],[{x:-1,y:1,z:1},{x:-1,y:1,z:-1}],[{x:-1,y:-1,z:-1},{x:-1,y:1,z:-1}],[{x:1,y:-1,z:-1},{x:1,y:1,z:-1}],[{x:1,y:-1,z:1},{x:1,y:1,z:1}],[{x:-1,y:-1,z:1},{x:-1,y:1,z:1}]])x(e,t,{color:u,width:1,alpha:.65});if(!h){for(let e of k){let t=HK(e,v.minY,v.minZ,v).x;x({x:t,y:-1,z:-1},{x:t,y:-1,z:1},{color:u,width:.75,alpha:.45})}for(let e of j){let t=HK(v.minX,e,v.minZ,v).z;x({x:-1,y:-1,z:t},{x:1,y:-1,z:t},{color:u,width:.75,alpha:.45})}for(let e of P){let t=HK(v.minX,e,v.minZ,v).z;x({x:-1,y:-1,z:t},{x:1,y:-1,z:t},{color:u,width:.5,alpha:.22})}for(let e of N){let t=HK(e,v.minY,v.minZ,v).x;x({x:t,y:-1,z:-1},{x:t,y:-1,z:1},{color:u,width:.5,alpha:.22})}let e=(e,t)=>{let n=WK*(t?1:.55);x({x:e,y:-1,z:-1},{x:e,y:-1+n,z:-1},{color:`#fb7185`,width:t?1.25:.75,alpha:.95})},t=(e,t)=>{let n=WK*(t?1:.55);x({x:-1,y:-1,z:e},{x:-1+n,y:-1,z:e},{color:`#38bdf8`,width:t?1.25:.75,alpha:.95})},n=(e,t)=>{let n=WK*(t?1:.55);x({x:-1,y:e,z:-1},{x:-1+n,y:e,z:-1},{color:`#4ade80`,width:t?1.25:.75,alpha:.95})};for(let t of N)e(HK(t,v.minY,v.minZ,v).x,!1);for(let t of k)e(HK(t,v.minY,v.minZ,v).x,!0);for(let e of P)t(HK(v.minX,e,v.minZ,v).z,!1);for(let e of j)t(HK(v.minX,e,v.minZ,v).z,!0);for(let e of I)n(HK(v.minX,v.minY,e,v).y,!1);for(let e of M)n(HK(v.minX,v.minY,e,v).y,!0)}let B=(e,t,n)=>{let r=n-t;return r<1e-12?0:(e-t)/r*2-1};for(let e of E.current.alarms){let{axis:t,value:n,color:r,style:i,width:a}=e,o;if(t===`z`){let e=B(n,v.minZ,v.maxZ);o=[{x:-1,y:e,z:-1},{x:1,y:e,z:-1},{x:1,y:e,z:1},{x:-1,y:e,z:1}]}else if(t===`x`){let e=B(n,v.minX,v.maxX);o=[{x:e,y:-1,z:-1},{x:e,y:1,z:-1},{x:e,y:1,z:1},{x:e,y:-1,z:1}]}else{let e=B(n,v.minY,v.maxY);o=[{x:-1,y:-1,z:e},{x:1,y:-1,z:e},{x:1,y:1,z:e},{x:-1,y:1,z:e}]}let c=o.map(e=>b(e));if(c.every(e=>e.depth>=.02)){s.beginPath(),s.moveTo(c[0].sx,c[0].sy);for(let e=1;e<c.length;e++)s.lineTo(c[e].sx,c[e].sy);s.closePath(),s.fillStyle=r,s.globalAlpha=.18,s.fill(),i===`dashed`?s.setLineDash([7,4]):i===`dotted`?s.setLineDash([2,4]):s.setLineDash([]),s.strokeStyle=r,s.lineWidth=a,s.globalAlpha=.9,s.beginPath(),s.moveTo(c[0].sx,c[0].sy);for(let e=1;e<c.length;e++)s.lineTo(c[e].sx,c[e].sy);s.closePath(),s.stroke(),s.setLineDash([]),s.globalAlpha=1;let e=c.reduce((e,t)=>t.sy>e.sy?t:e);s.fillStyle=r,s.font=`bold 10px ${Q.mono}`,s.textAlign=`center`,s.globalAlpha=.95,s.fillText(`${t.toUpperCase()}=${Hz(n)}`,e.sx,e.sy-6),s.globalAlpha=1}}if(!h){s.font=`10px ${Q.mono}`,s.textBaseline=`middle`;for(let e of k){let t=HK(e,v.minY,v.minZ,v).x,n=b({x:t,y:-1.2,z:-1.2});n.depth<.02||(s.fillStyle=l,s.textAlign=`center`,s.fillText(Vz(e,T),n.sx,n.sy+12))}for(let e of j){let t=HK(v.minX,e,v.minZ,v).z,n=b({x:-1.22,y:-1,z:t});n.depth<.02||(s.textAlign=`right`,s.fillText(Vz(e,D),n.sx-4,n.sy))}for(let e of M){let t=HK(v.minX,v.minY,e,v).y,n=b({x:-1.22,y:t,z:-1.2});n.depth<.02||(s.textAlign=`right`,s.fillText(Vz(e,O),n.sx-4,n.sy))}s.textBaseline=`alphabetic`,s.font=`bold 11px ${Q.mono}`;let e=b({x:1.15,y:-1,z:-1.15});e.depth>=.02&&(s.fillStyle=`#fb7185`,s.textAlign=`center`,s.fillText(d,e.sx,e.sy+16)),e=b({x:-1.18,y:-1,z:1.15}),e.depth>=.02&&(s.fillStyle=`#38bdf8`,s.textAlign=`center`,s.fillText(f,e.sx-10,e.sy)),e=b({x:-1.18,y:1.15,z:-1.18}),e.depth>=.02&&(s.fillStyle=`#4ade80`,s.textAlign=`center`,s.fillText(p,e.sx-10,e.sy)),R(UK+8,Math.min(r-80,180),p),z(`Drag: rotate | Wheel: zoom | Dbl‑click: reset · ${g.surface?`Surface`:E.current.showMesh?`Mesh: ${E.current.meshStyle}`:`Scatter`} · color = Z`)}}let{showMesh:B,meshStyle:V,meshOpacity:ee}=E.current,te=!!g.surface||B;if(_)_.setBounds(v),_.setView(L,A),_.setStyle({palette:YK,colorAxis:T,pointRadius:m,fill:te&&(V===`filled`||V===`both`),wire:te&&(V===`wireframe`||V===`both`),fillAlpha:ee,wireColor:NK(u,.5)}),_.render(),P.current!==g&&(P.current=g,VH(t));else if(g.cols){let e=g.cols,t=Math.max(1,Math.ceil(e.length/JK));for(let n=0;n<e.length;n+=t){let t=e.x[n],r=e.y[n],i=e.z[n];if(!(t>=v.minX&&t<=v.maxX&&r>=v.minY&&r<=v.maxY&&i>=v.minZ&&i<=v.maxZ))continue;let a=F(t,r,i);a&&(s.fillStyle=hG(k(t,r,i)),s.beginPath(),s.arc(a[0],a[1],m,0,Math.PI*2),s.fill())}}}function I(){if(T.current)return T.current;let e=x.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return T.current=n,n}let L=K(F);G(()=>{L.current=F});let R=K(null);R.current??=KH(()=>L.current(),()=>x.current),W(()=>()=>R.current?.cancel(),[]);let z=()=>{S.current=GK,C.current=KK,w.current=qK,R.current.schedule()};return xt(_,()=>({autoscale:z}),[]),W(()=>uB(x.current,()=>{T.current=null,R.current.schedule()}),[]),W(()=>{T.current=null,R.current.schedule()},[o]),W(()=>{R.current.now()},[D,A,n,r,i,a,u,d,f,p,m,h]),W(()=>{let e=y.current,t=x.current;if(!e||!t)return;let n=()=>R.current.schedule(),r=new WH(()=>{T.current=null,n()});r.observe(t);let i=!1,a=0,o=0,s=t=>{t.button===0&&(i=!0,a=t.clientX,o=t.clientY,e.setPointerCapture(t.pointerId))},c=e=>{if(!i)return;let t=e.clientX-a,r=e.clientY-o;a=e.clientX,o=e.clientY,S.current-=t*.008,C.current+=r*.008,C.current=Math.max(-Math.PI/2+.05,Math.min(Math.PI/2-.05,C.current)),n()},l=()=>{i=!1},u=e=>{e.preventDefault();let t=e.deltaY>0?1.08:.92;w.current=Math.max(1.2,Math.min(12,w.current*t)),n()},d=()=>{S.current=GK,C.current=KK,w.current=qK,n()},f=e=>{e.preventDefault(),v.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`pointerdown`,s),e.addEventListener(`pointermove`,c),e.addEventListener(`pointerup`,l),e.addEventListener(`pointercancel`,l),e.addEventListener(`wheel`,u,{passive:!1}),e.addEventListener(`contextmenu`,f),e.addEventListener(`dblclick`,d),()=>{r.disconnect(),e.removeEventListener(`pointerdown`,s),e.removeEventListener(`pointermove`,c),e.removeEventListener(`pointerup`,l),e.removeEventListener(`pointercancel`,l),e.removeEventListener(`wheel`,u),e.removeEventListener(`contextmenu`,f),e.removeEventListener(`dblclick`,d)}},[]),Ot(`div`,{ref:x,className:`chart-canvas-wrap`,children:[q(`canvas`,{ref:y,className:`chart-canvas`,role:`img`,"aria-label":`3D scatter: ${n} vs ${r} vs ${i}`,style:{display:`block`,width:`100%`,height:`100%`,cursor:`grab`}}),q(`canvas`,{ref:b,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}})]})}),eq={top:14,right:24,bottom:40,left:64},tq=5;function nq(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}function rq(e){return Math.max(10,Math.min(200,Math.ceil(Math.sqrt(e))))}function iq(e,t,n){let r=(e-t)/n;return Math.exp(-.5*r*r)/(n*Math.sqrt(2*Math.PI))}function aq(e,t){let n=e.length;if(n===0)return null;let r=1/0,i=-1/0,a=0;for(let t=0;t<n;t++){let n=e[t];n<r&&(r=n),n>i&&(i=n),a+=n}r===i&&(--r,i+=1);let o=t>0?t:rq(n),s=(i-r)/o,c=Array(o).fill(0),l=a/n,u=0;for(let t=0;t<n;t++){let n=e[t];c[Math.min(o-1,Math.floor((n-r)/s))]++,u+=(n-l)**2}return{lo:r,hi:i,nBins:o,width:s,counts:c,mean:l,sd:Math.sqrt(u/n),total:n}}function oq({values:e,label:t,bins:n=0,color:r=`#38bdf8`,showNormal:i=!1,logY:a=!1,height:o=400,backgroundToken:s=``,onPlotContextMenu:c}){let l=IU(),u=K(null),d=K(null),f=K(null),p=K(null),m=K(0),h=K(null),g=K(c);G(()=>{g.current=c},[c]);let _=K({values:e,label:t,bins:n,color:r,showNormal:i,logY:a,height:o});G(()=>{_.current={values:e,label:t,bins:n,color:r,showNormal:i,logY:a,height:o}},[e,t,n,r,i,a,o]);function v(){if(h.current)return h.current;let e=f.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return h.current=n,n}function y(){let e=f.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||_.current.height)}}function b(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}let x=St(()=>aq(e,n),[e,n]),S=K(x);G(()=>{S.current=x},[x]);let C=()=>S.current;function w(){let e=u.current;if(!e)return;let{w:t,h:n}=y(),r=b(e,t,n);if(!r)return;let{top:i,right:a,bottom:o,left:s}=eq,c=t-s-a,d=n-i-o,{bg:f,muted:p,grid:m}=v(),{label:h,color:g,showNormal:x,logY:S}=_.current;r.fillStyle=f,r.fillRect(0,0,t,n);let w=C();if(!w||c<=0||d<=0){r.fillStyle=p,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{lo:T,hi:E,nBins:D,width:O,counts:k,mean:A,sd:j,total:M}=w,N=Math.max(...k),P=S?Math.log10(N+1)+.1:N*1.08,F=e=>s+(e-T)/(E-T)*c;l({left:s,top:i,width:c,height:d,x:{v0:T,v1:E}});let I=e=>i+(P-(S?e>0?Math.log10(e):0:e))/(P-0)*d,L=S?1:Pz(P,5),R=Lz(0,S?P:N,L);r.strokeStyle=m,r.lineWidth=1,r.setLineDash(nq(`dashed`));for(let e of R){let t=I(e);r.beginPath(),r.moveTo(s,t),r.lineTo(s+c,t),r.stroke()}r.setLineDash([]);let z=Math.max(.5,c/D*.04);for(let e=0;e<D;e++){let t=F(T+e*O)+z/2,n=F(T+(e+1)*O)-z/2,i=I(0),a=I(k[e]);r.fillStyle=g,r.globalAlpha=.75,r.fillRect(t,a,n-t,i-a),r.globalAlpha=1}if(x&&j>0){r.beginPath();for(let e=0;e<=200;e++){let t=T+e/200*(E-T),n=iq(t,A,j)*M*O,i=F(t),a=I(n);e===0?r.moveTo(i,a):r.lineTo(i,a)}r.strokeStyle=`#f97316`,r.lineWidth=1,r.stroke()}r.strokeStyle=p,r.lineWidth=1,r.fillStyle=p,r.font=`11px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of R){let t=I(e);r.beginPath(),r.moveTo(s-tq,t),r.lineTo(s,t),r.stroke(),r.fillText(S?`10^${e.toFixed(0)}`:Vz(e,L),s-4,t)}let B=Pz(E-T,Fz(c)),V=Lz(T,E,B);r.fillStyle=p,r.textAlign=`center`,r.textBaseline=`top`;for(let e of V){let t=F(e);r.beginPath(),r.moveTo(t,i+d),r.lineTo(t,i+d+tq),r.stroke(),r.fillText(Vz(e,B),t,i+d+tq+2)}r.strokeStyle=m,r.lineWidth=1,r.strokeRect(s,i,c,d),r.fillStyle=p,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(h,s+c/2,n-4),r.save(),r.translate(14,i+d/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(S?`log₁₀(count)`:`count`,0,0),r.restore()}let T=K(w);T.current=w;let E=K(null);E.current??=KH(()=>T.current(),()=>f.current);let D=()=>E.current.schedule();function O(e){let t=d.current;if(!t)return;let{w:n,h:r}=y(),i=b(t,n,r);if(!i||(i.clearRect(0,0,n,r),e===null))return;let{top:a,right:o,bottom:s,left:c}=eq,l=n-c-o,u=r-a-s,{muted:f}=v(),p=C();if(!p)return;let{lo:m,hi:h,width:g,counts:_}=p,x=e=>c+(e-m)/(h-m)*l,S=x(m+e*g),w=x(m+(e+1)*g);i.fillStyle=`rgba(255,255,255,0.12)`,i.fillRect(S,a,w-S,u);let T=(S+w)/2,E=_[e],D=(E/p.total*100).toFixed(1),O=`${Hz(m+e*g)} – ${Hz(m+(e+1)*g)}`,k=`n = ${E} (${D}%)`;i.font=`11px ${Q.mono}`;let A=i.measureText(k).width,j=i.measureText(O).width,M=Math.max(A,j),N=Math.min(T+8,c+l-M-8);i.fillStyle=f,i.textAlign=`left`,i.textBaseline=`top`,i.fillText(O,N,a+8),i.fillText(k,N,a+22)}function k(){zH(m.current),m.current=RH(()=>O(p.current))}return W(()=>{E.current.now()}),W(()=>()=>E.current?.cancel(),[]),W(()=>{h.current=null,D()},[s]),G(()=>{let e=f.current;if(!e)return;let t=new WH(()=>{h.current=null,D(),k()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=d.current;if(!e)return;function t(t){let n=e.getBoundingClientRect(),{left:r}=eq,i=n.width-eq.left-eq.right,a=C();if(!a||i<=0){p.current=null,k();return}let o=t.clientX-n.left-r,s=Math.floor(o/i*a.nBins);p.current=s>=0&&s<a.nBins?s:null,k()}function n(){p.current=null,k()}function r(e){e.preventDefault(),g.current?.({clientX:e.clientX,clientY:e.clientY})}return e.addEventListener(`mousemove`,t),e.addEventListener(`mouseleave`,n),e.addEventListener(`contextmenu`,r),()=>{e.removeEventListener(`mousemove`,t),e.removeEventListener(`mouseleave`,n),e.removeEventListener(`contextmenu`,r)}},[]),Ot(`div`,{ref:f,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:u,className:`chart-canvas`,role:`img`,"aria-label":`Histogram of ${t}`}),q(`canvas`,{ref:d,className:`chart-canvas chart-overlay`})]})}var sq=`
|
|
485
485
|
uniform vec2 u_resolution;
|
|
486
486
|
uniform vec4 u_plot; // left, top, width, height (CSS px)
|
|
487
487
|
uniform vec4 u_view; // xmin, xmax, ymin, ymax (relative to the layer origin)
|
|
@@ -490,7 +490,7 @@ vec2 project(float x, float y) {
|
|
|
490
490
|
u_plot.y + (u_view.w - y) / (u_view.w - u_view.z) * u_plot.w);
|
|
491
491
|
}
|
|
492
492
|
vec4 toClip(vec2 p) { vec2 c = p / u_resolution * 2.0 - 1.0; return vec4(c.x, -c.y, 0.0, 1.0); }
|
|
493
|
-
`,
|
|
493
|
+
`,cq=`
|
|
494
494
|
uniform vec4 u_clip; // left, top, right, bottom (CSS px)
|
|
495
495
|
uniform float u_dpr;
|
|
496
496
|
uniform float u_height; // canvas height (device px)
|
|
@@ -498,23 +498,23 @@ bool outside() {
|
|
|
498
498
|
vec2 f = vec2(gl_FragCoord.x, u_height - gl_FragCoord.y) / u_dpr;
|
|
499
499
|
return f.x < u_clip.x || f.x > u_clip.z || f.y < u_clip.y || f.y > u_clip.w;
|
|
500
500
|
}
|
|
501
|
-
`,
|
|
501
|
+
`,lq=`#version 300 es
|
|
502
502
|
in vec2 a_corner; // (0|1 along x, 0 = lo | 1 = hi)
|
|
503
503
|
in float a_xa; in float a_xb;
|
|
504
504
|
in float a_loa; in float a_lob;
|
|
505
505
|
in float a_hia; in float a_hib;
|
|
506
506
|
in float a_bstart;
|
|
507
|
-
${
|
|
507
|
+
${sq}
|
|
508
508
|
void main() {
|
|
509
509
|
if (a_bstart > 0.5) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; }
|
|
510
510
|
float x = a_corner.x < 0.5 ? a_xa : a_xb;
|
|
511
511
|
float lo = a_corner.x < 0.5 ? a_loa : a_lob;
|
|
512
512
|
float hi = a_corner.x < 0.5 ? a_hia : a_hib;
|
|
513
513
|
gl_Position = toClip(project(x, a_corner.y < 0.5 ? lo : hi));
|
|
514
|
-
}`,
|
|
514
|
+
}`,uq=`#version 300 es
|
|
515
515
|
in vec2 a_corner; // (0|1, 0|1)
|
|
516
516
|
in float a_x0; in float a_x1; in float a_y0; in float a_y1; in float a_k;
|
|
517
|
-
${
|
|
517
|
+
${sq}
|
|
518
518
|
flat out float v_k;
|
|
519
519
|
void main() {
|
|
520
520
|
vec2 p0 = project(a_x0, a_y0), p1 = project(a_x1, a_y1);
|
|
@@ -524,29 +524,29 @@ void main() {
|
|
|
524
524
|
vec2 half_ = max((hi - lo) * 0.5, vec2(0.5));
|
|
525
525
|
v_k = a_k;
|
|
526
526
|
gl_Position = toClip(c + (a_corner * 2.0 - 1.0) * half_);
|
|
527
|
-
}`,
|
|
527
|
+
}`,dq=`#version 300 es
|
|
528
528
|
precision highp float;
|
|
529
529
|
uniform vec4 u_color;
|
|
530
|
-
${
|
|
530
|
+
${cq}
|
|
531
531
|
out vec4 outColor;
|
|
532
532
|
void main() {
|
|
533
533
|
if (outside()) discard;
|
|
534
534
|
outColor = vec4(u_color.rgb * u_color.a, u_color.a);
|
|
535
|
-
}`,
|
|
535
|
+
}`,fq=`#version 300 es
|
|
536
536
|
precision highp float;
|
|
537
537
|
flat in float v_k;
|
|
538
538
|
uniform sampler2D u_palette;
|
|
539
|
-
${
|
|
539
|
+
${cq}
|
|
540
540
|
out vec4 outColor;
|
|
541
541
|
void main() {
|
|
542
542
|
if (outside()) discard;
|
|
543
543
|
vec4 c = texture(u_palette, vec2((v_k + 0.5) / 256.0, 0.5));
|
|
544
544
|
outColor = vec4(c.rgb * c.a, c.a);
|
|
545
|
-
}`,
|
|
545
|
+
}`,pq=`#version 300 es
|
|
546
546
|
in vec2 a_corner;
|
|
547
547
|
in float a_ax; in float a_ay; in float a_bx; in float a_by;
|
|
548
548
|
in float a_bstart;
|
|
549
|
-
${
|
|
549
|
+
${sq}
|
|
550
550
|
uniform float u_ext;
|
|
551
551
|
flat out vec2 v_a;
|
|
552
552
|
flat out vec2 v_b;
|
|
@@ -562,14 +562,14 @@ void main() {
|
|
|
562
562
|
vec2 pos = base + dir * (a_corner.x * u_ext) + n * (a_corner.y * u_ext);
|
|
563
563
|
v_a = a; v_b = b; v_pos = pos;
|
|
564
564
|
gl_Position = toClip(pos);
|
|
565
|
-
}`,
|
|
565
|
+
}`,mq=`#version 300 es
|
|
566
566
|
precision highp float;
|
|
567
567
|
flat in vec2 v_a;
|
|
568
568
|
flat in vec2 v_b;
|
|
569
569
|
in vec2 v_pos;
|
|
570
570
|
uniform vec4 u_color;
|
|
571
571
|
uniform float u_half;
|
|
572
|
-
${
|
|
572
|
+
${cq}
|
|
573
573
|
out vec4 outColor;
|
|
574
574
|
void main() {
|
|
575
575
|
if (outside()) discard;
|
|
@@ -581,21 +581,21 @@ void main() {
|
|
|
581
581
|
if (cov <= 0.0) discard;
|
|
582
582
|
float a = u_color.a * cov;
|
|
583
583
|
outColor = vec4(u_color.rgb * a, a);
|
|
584
|
-
}`,
|
|
584
|
+
}`,hq=`#version 300 es
|
|
585
585
|
in vec2 a_corner; // (0|1, 0|1)
|
|
586
586
|
uniform vec4 u_extent; // x0, x1, y0, y1 (relative to the layer origin)
|
|
587
|
-
${
|
|
587
|
+
${sq}
|
|
588
588
|
out vec2 v_uv;
|
|
589
589
|
void main() {
|
|
590
590
|
v_uv = a_corner;
|
|
591
591
|
gl_Position = toClip(project(mix(u_extent.x, u_extent.y, a_corner.x), mix(u_extent.z, u_extent.w, a_corner.y)));
|
|
592
|
-
}`,
|
|
592
|
+
}`,gq=`#version 300 es
|
|
593
593
|
precision highp float;
|
|
594
594
|
in vec2 v_uv;
|
|
595
595
|
uniform highp sampler2D u_values;
|
|
596
596
|
uniform sampler2D u_palette;
|
|
597
597
|
uniform vec2 u_range; // vmin, vmax
|
|
598
|
-
${
|
|
598
|
+
${cq}
|
|
599
599
|
out vec4 outColor;
|
|
600
600
|
void main() {
|
|
601
601
|
if (outside()) discard;
|
|
@@ -604,19 +604,19 @@ void main() {
|
|
|
604
604
|
float t = u_range.y > u_range.x ? clamp((v - u_range.x) / (u_range.y - u_range.x), 0.0, 1.0) : 0.5;
|
|
605
605
|
vec4 c = texture(u_palette, vec2((floor(t * 255.0) + 0.5) / 256.0, 0.5));
|
|
606
606
|
outColor = vec4(c.rgb * c.a, c.a);
|
|
607
|
-
}`,gq=-3e38;function _q(e){for(let t=0;t<e.length;t++)if(e[t]-e[t]===0)return e[t];return 0}function vq(e){let t=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0});if(!t)return null;let n=(e,n,i,a)=>uH(t,`glPlot|${e}|${n}`,()=>r(e,n,i,a)),r=(e,n,r,i)=>{let a=QV(t,t.VERTEX_SHADER,e),o=QV(t,t.FRAGMENT_SHADER,n);if(!a||!o)return null;let s=t.createProgram();if(t.attachShader(s,a),t.attachShader(s,o),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))return console.error(`glPlot program link failed:`,t.getProgramInfoLog(s)),null;let c=[`u_resolution`,`u_plot`,`u_view`,`u_clip`,`u_dpr`,`u_height`];return{prog:s,shaders:[a,o],a:Object.fromEntries([`a_corner`,...r].map(e=>[e,t.getAttribLocation(s,e)])),u:Object.fromEntries([...c,...i].map(e=>[e,t.getUniformLocation(s,e)]))}},i=n(cq,uq,[`a_xa`,`a_xb`,`a_loa`,`a_lob`,`a_hia`,`a_hib`,`a_bstart`],[`u_color`]),a=n(lq,dq,[`a_x0`,`a_x1`,`a_y0`,`a_y1`,`a_k`],[`u_palette`]),o=n(fq,pq,[`a_ax`,`a_ay`,`a_bx`,`a_by`,`a_bstart`],[`u_color`,`u_half`,`u_ext`]),s=n(mq,hq,[],[`u_extent`,`u_values`,`u_palette`,`u_range`]);if(!i||!a||!o||!s)return null;let c=t.getParameter(t.MAX_TEXTURE_SIZE),l=t.createVertexArray(),u=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,u),t.bufferData(t.ARRAY_BUFFER,Float32Array.from([0,0,1,0,0,1,1,1]),t.STATIC_DRAW);let d=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,d),t.bufferData(t.ARRAY_BUFFER,Float32Array.from([-1,-1,1,-1,-1,1,1,1]),t.STATIC_DRAW);let f=new Map,p=1,m=1,h=1,g={xmin:0,xmax:1,ymin:0,ymax:1},_={left:0,top:0,width:1,height:1},v=new WeakMap,y=new Float32Array,b=e=>{for(let n of Object.values(e.buffers))t.deleteBuffer(n);e.palette&&t.deleteTexture(e.palette),e.values&&t.deleteTexture(e.values)},x=new Float32Array,S=(e,n)=>{t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA8,256,1,0,t.RGBA,t.UNSIGNED_BYTE,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)},C=(e,t)=>{let n=f.get(e);if(n&&n.kind===t)return n;n&&b(n);let r={kind:t,n:0,ox:0,oy:0,buffers:{},color:[0,0,0,1],width:1};return f.set(e,r),r},w=(e,n,r)=>{let i=e.buffers[n]??=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,i),r.byteLength<=(v.get(i)??0)?t.bufferSubData(t.ARRAY_BUFFER,0,r):(t.bufferData(t.ARRAY_BUFFER,r,t.DYNAMIC_DRAW),v.set(i,r.byteLength))},T=(e,t,n,r)=>{let i=n.length;y.length<i&&(y=new Float32Array(i));for(let e=0;e<i;e++)y[e]=n[e]-r;w(e,t,y.subarray(0,i))},E=(e,t,n)=>{let r=new Uint8Array(e);t&&r.set(t.subarray(0,e)),e&&(r[0]=255);for(let t=0;t<e;t++)n(t)||(r[t]=255,t+1<e&&(r[t+1]=255));return r},D=(e,n,r=0,i=t.FLOAT)=>{if(e<0)return;t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(e);let a=i===t.FLOAT?4:1;t.vertexAttribPointer(e,1,i,i!==t.FLOAT,a,r*a),t.vertexAttribDivisor(e,1)},O=(n,r,i)=>{t.useProgram(n.prog),t.uniform2f(n.u.u_resolution,p,m),t.uniform4f(n.u.u_plot,_.left,_.top,_.width,_.height),t.uniform4f(n.u.u_view,g.xmin-r.ox,g.xmax-r.ox,g.ymin-r.oy,g.ymax-r.oy),t.uniform4f(n.u.u_clip,_.left,_.top,_.left+_.width,_.top+_.height),t.uniform1f(n.u.u_dpr,h),t.uniform1f(n.u.u_height,e.height),t.bindBuffer(t.ARRAY_BUFFER,i),t.enableVertexAttribArray(n.a.a_corner),t.vertexAttribPointer(n.a.a_corner,2,t.FLOAT,!1,0,0),t.vertexAttribDivisor(n.a.a_corner,0)},k=e=>{for(let n of Object.values(e.a))n>=0&&t.vertexAttribDivisor(n,0)};return{resize(t,n,r){p=Math.max(1,t),m=Math.max(1,n),h=r,e.width=Math.round(p*h),e.height=Math.round(m*h)},setView(e,t,n,r,i){g={xmin:e,xmax:t,ymin:n,ymax:r},_=i},setBands(e,t,n,r,i,a){let o=C(e,`bands`),s=Math.min(t.length,n.length,r.length);o.ox=_q(t),o.oy=_q(r),T(o,`x`,t,o.ox),T(o,`lo`,n,o.oy),T(o,`hi`,r,o.oy),w(o,`start`,E(s,a,e=>t[e]-t[e]===0&&n[e]-n[e]===0&&r[e]-r[e]===0)),o.n=Math.max(0,s-1),o.color=i},setRects(e,n,r,i,a,o,s){let c=C(e,`rects`),l=Math.min(n.length,r.length,i.length,a.length);c.ox=_q(n),c.oy=_q(i),T(c,`x0`,n,c.ox),T(c,`x1`,r,c.ox),T(c,`y0`,i,c.oy),T(c,`y1`,a,c.oy),s?T(c,`k`,s,0):delete c.buffers.k;let u=new Uint8Array(256*4);for(let e=0;e<256;e++){let t=o[Math.min(e,o.length-1)]??[0,0,0,1];u.set([t[0]*255,t[1]*255,t[2]*255,t[3]*255],e*4)}c.palette??=t.createTexture(),t.bindTexture(t.TEXTURE_2D,c.palette),t.texImage2D(t.TEXTURE_2D,0,t.RGBA8,256,1,0,t.RGBA,t.UNSIGNED_BYTE,u),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),c.n=l},setLine(e,t,n,r,i,a){let o=C(e,`line`),s=Math.min(t.length,n.length);o.ox=_q(t),o.oy=_q(n),T(o,`x`,t,o.ox),T(o,`y`,n,o.oy),w(o,`start`,E(s,a,e=>t[e]-t[e]===0&&n[e]-n[e]===0)),o.n=Math.max(0,s-1),o.color=r,o.width=i},maxTextureSize:c,setGrid(e,n,r,i,a,o,s,c){let l=C(e,`grid`),u=r*i,d=0;for(let e=0;e<u;e++)d+=n[e]*0;let f=n.subarray(0,u);if(d!==0){x.length<u&&(x=new Float32Array(u));for(let e=0;e<u;e++){let t=n[e];x[e]=t===t?t:gq}f=x.subarray(0,u)}let p=!l.values;l.values??=t.createTexture(),t.bindTexture(t.TEXTURE_2D,l.values),t.pixelStorei(t.UNPACK_ALIGNMENT,4),!p&&l.grid&&l.grid.w===r&&l.grid.h===i?t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,i,t.RED,t.FLOAT,f):(t.texImage2D(t.TEXTURE_2D,0,t.R32F,r,i,0,t.RED,t.FLOAT,f),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)),l.palette??=t.createTexture(),S(l.palette,o);let[m,h,g,_]=a;l.ox=m,l.oy=g,l.grid={w:r,h:i,x0:m,x1:h,y0:g,y1:_,vmin:s,vmax:c},l.n=1},setGridRange(e,t,n){let r=f.get(e);r?.grid&&(r.grid.vmin=t,r.grid.vmax=n)},remove(e){let t=f.get(e);t&&(b(t),f.delete(e))},keep(e){let t=new Set(e);for(let e of[...f.keys()])t.has(e)||this.remove(e)},render(){t.bindFramebuffer(t.FRAMEBUFFER,null),t.viewport(0,0,e.width,e.height),t.disable(t.SCISSOR_TEST),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.bindVertexArray(l),t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA);for(let e of f.values()){if(e.n<=0)continue;let n=e.buffers;if(e.kind===`bands`)O(i,e,u),t.uniform4f(i.u.u_color,...e.color),D(i.a.a_xa,n.x,0),D(i.a.a_xb,n.x,1),D(i.a.a_loa,n.lo,0),D(i.a.a_lob,n.lo,1),D(i.a.a_hia,n.hi,0),D(i.a.a_hib,n.hi,1),D(i.a.a_bstart,n.start,1,t.UNSIGNED_BYTE),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,e.n),k(i);else if(e.kind===`grid`){let n=e.grid;O(s,e,u),t.uniform4f(s.u.u_extent,0,n.x1-n.x0,0,n.y1-n.y0),t.uniform2f(s.u.u_range,n.vmin,n.vmax),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e.values),t.uniform1i(s.u.u_values,0),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,e.palette),t.uniform1i(s.u.u_palette,1),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.activeTexture(t.TEXTURE0)}else e.kind===`rects`?(O(a,e,u),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e.palette),t.uniform1i(a.u.u_palette,0),D(a.a.a_x0,n.x0),D(a.a.a_x1,n.x1),D(a.a.a_y0,n.y0),D(a.a.a_y1,n.y1),n.k?D(a.a.a_k,n.k):(t.disableVertexAttribArray(a.a.a_k),t.vertexAttrib1f(a.a.a_k,0)),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,e.n),k(a)):(O(o,e,d),t.uniform4f(o.u.u_color,...e.color),t.uniform1f(o.u.u_half,e.width/2),t.uniform1f(o.u.u_ext,e.width/2+1.5),D(o.a.a_ax,n.x,0),D(o.a.a_bx,n.x,1),D(o.a.a_ay,n.y,0),D(o.a.a_by,n.y,1),D(o.a.a_bstart,n.start,1,t.UNSIGNED_BYTE),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,e.n),k(o))}t.bindVertexArray(null)},dispose(){for(let e of f.values())b(e);f.clear(),t.deleteBuffer(u),t.deleteBuffer(d),t.deleteVertexArray(l)}}}function yq(e){let t=K({plot:null,failed:!1,size:``});return W(()=>()=>{t.current.plot?.dispose(),t.current.plot=null},[]),yt((n,r)=>{let i=t.current,a=e.current;if(!i.plot&&!i.failed&&a&&(i.plot=dH(a,vq),i.failed=!i.plot),!i.plot||!a)return null;let o=Math.min(2,window.devicePixelRatio||1),s=`${n}x${r}@${o}`;return i.size!==s&&(i.plot.resize(n,r,o),a.style.width=`${n}px`,a.style.height=`${r}px`,i.size=s),i.plot},[e])}function bq(e){let t=!1;for(let n=0;n<e.length;n++)if(Math.abs(e[n])>Math.PI*2){t=!0;break}let n=new Float64Array(e.length);for(let r=0;r<e.length;r++)n[r]=t?e[r]*Math.PI/180:e[r];return n}var xq=16;function Sq(e,t,n,r){let i=bq(e),a=Math.min(i.length,t.length),o=1/0,s=-1/0;for(let e=0;e<a;e++){let n=t[e];n<o&&(o=n),n>s&&(s=n)}let c=n??Math.min(0,o),l=r??s,u=l-c||1,d=new Float64Array(a),f=new Float64Array(a),p=new Float64Array(xq),m=new Int32Array(xq);for(let e=0;e<a;e++){let n=Math.max(0,(t[e]-c)/u),r=i[e];n>1.0001?d[e]=f[e]=NaN:(d[e]=Math.sin(r)*n,f[e]=Math.cos(r)*n);let a=r%(2*Math.PI);a<0&&(a+=2*Math.PI);let o=Math.min(xq-1,Math.floor(a/(2*Math.PI)*xq));p[o]+=t[e],m[o]++}return{n:a,rMin:c,rMax:l,x:d,y:f,means:Array.from({length:xq},(e,t)=>m[t]>0?p[t]/m[t]:0)}}function Cq({angles:e,radii:t,angleLabel:n,radiusLabel:r,color:i=`#a78bfa`,mode:a=`waveform`,radiusMin:o,radiusMax:s,height:c=400,backgroundToken:l=``,onPlotContextMenu:u}){let d=K(null),f=K(null),p=K(null),m=K(u);G(()=>{m.current=u},[u]);let h=K({angles:e,radii:t,angleLabel:n,radiusLabel:r,color:i,mode:a,radiusMin:o,radiusMax:s,height:c});G(()=>{h.current={angles:e,radii:t,angleLabel:n,radiusLabel:r,color:i,mode:a,radiusMin:o,radiusMax:s,height:c}},[e,t,n,r,i,a,o,s,c]);let g=St(()=>Sq(e,t,o,s),[e,t,o,s]),_=K(g);G(()=>{_.current=g},[g]);let v=K(null),y=yq(v),b=K({geo:null,color:``});function x(){if(p.current)return p.current;let e=f.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return p.current=n,n}function S(){let e=f.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||h.current.height)}}function C(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function w(){let e=d.current;if(!e)return;let{w:t,h:n}=S(),r=C(e,t,n);if(!r)return;let{bg:i,muted:a,grid:o}=x(),{angleLabel:s,radiusLabel:c,color:l,mode:u}=h.current,f=_.current,{n:p,rMin:m,rMax:g}=f;r.fillStyle=i,r.fillRect(0,0,t,n);let v=y(t,n);if(p===0){v?.keep([]),v?.render(),r.fillStyle=a,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let w=g-m||1,T=(Math.min(t-64,n-32-24)-4)/2,E=t/2,D=32+T,O=Pz(w,4),k=Lz(m,g,O);r.strokeStyle=o,r.lineWidth=1,r.setLineDash([3,3]);for(let e of k){let t=(e-m)/w*T;t<0||(r.beginPath(),r.arc(E,D,t,0,Math.PI*2),r.stroke())}r.setLineDash([]),r.strokeStyle=o,r.lineWidth=1;for(let e=0;e<360;e+=30){let t=e*Math.PI/180;r.beginPath(),r.moveTo(E,D),r.lineTo(E+Math.cos(-t+Math.PI/2)*T,D+Math.sin(-t+Math.PI/2)*T),r.stroke()}r.fillStyle=a,r.font=`10px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`middle`;for(let e=0;e<360;e+=30){let t=e*Math.PI/180,n=E+Math.sin(t)*(T+14),i=D-Math.cos(t)*(T+14);r.fillText(`${e}°`,n,i)}r.textAlign=`left`,r.textBaseline=`middle`;for(let e of k){let t=(e-m)/w*T;t<4||r.fillText(Vz(e,O),E+4,D-t)}if(r.strokeStyle=a,r.lineWidth=1,r.setLineDash([]),r.beginPath(),r.arc(E,D,T,0,Math.PI*2),r.stroke(),r.save(),r.beginPath(),r.arc(E,D,T,0,Math.PI*2),r.clip(),u===`waveform`)if(v)(b.current.geo!==f||b.current.color!==l)&&(v.setLine(`wave`,f.x,f.y,MK(l,.9),1),b.current={geo:f,color:l}),v.keep([`wave`]),v.setView(-1,1,-1,1,{left:E-T,top:D-T,width:T*2,height:T*2}),v.render();else{r.strokeStyle=l,r.lineWidth=1,r.globalAlpha=.9,r.beginPath();let e=!1;for(let t=0;t<p;t++){let n=E+f.x[t]*T,i=D-f.y[t]*T;if(n!==n){e=!1;continue}e?r.lineTo(n,i):(r.moveTo(n,i),e=!0)}r.stroke(),r.globalAlpha=1}else{v?.keep([]),v?.render();let e=f.means,t=Math.max(...e,1e-10),n=2*Math.PI/xq;r.fillStyle=l,r.globalAlpha=.75;for(let i=0;i<xq;i++){let a=e[i]/t*T,o=i*n-Math.PI/2-n/2;r.beginPath(),r.moveTo(E,D),r.arc(E,D,a,o,o+n),r.closePath(),r.fill()}r.globalAlpha=1,r.strokeStyle=l,r.lineWidth=.5,r.globalAlpha=.4;for(let i=0;i<xq;i++){let a=e[i]/t*T,o=i*n-Math.PI/2-n/2;r.beginPath(),r.moveTo(E,D),r.arc(E,D,a,o,o+n),r.closePath(),r.stroke()}r.globalAlpha=1}r.restore(),r.fillStyle=a,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(`${s} / ${c}`,E,n-4)}let T=K(w);T.current=w;let E=K(null);E.current??=GH(()=>T.current(),()=>f.current);let D=()=>E.current.schedule();return W(()=>{E.current.now()}),W(()=>()=>E.current?.cancel(),[]),W(()=>{p.current=null,D()},[l]),G(()=>{let e=f.current;if(!e)return;let t=new UH(()=>{p.current=null,D()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=d.current;if(!e)return;let t=e=>{e.preventDefault(),m.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),Ot(`div`,{ref:f,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:d,className:`chart-canvas`,role:`img`,"aria-label":`Polar chart: ${n} vs ${r}`}),q(`canvas`,{ref:v,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}})]})}function wq(e,t,n,r,i){let a=Math.min(e.length,t.length),o=(t,n)=>{let r=0,i=a;for(;r<i;){let a=r+i>>>1;(n?e[a]<=t:e[a]<t)?r=a+1:i=a}return r},s=o(n,!1),c=o(r,!0),l=Math.max(0,s-1),u=Math.min(a,c+1);if(u-l<=2*i){let e=new Uint32Array(u-l);for(let t=0;t<e.length;t++)e[t]=l+t;return e}let d=new Uint32Array(2*i+2),f=0;s>0&&(d[f++]=s-1);let p=(r-n)/i,m=s;for(let r=0;r<i&&m<c;r++){let a=r===i-1?1/0:n+(r+1)*p,o=1/0,s=-1/0,l=-1,u=-1;for(;m<c&&e[m]<a;m++){let e=t[m];e<o&&(o=e,l=m),e>s&&(s=e,u=m)}l<0||(l===u?d[f++]=l:l<u?(d[f++]=l,d[f++]=u):(d[f++]=u,d[f++]=l))}return c<a&&(d[f++]=c),d.subarray(0,f)}function Tq(e,t){let n=e.length;if(n<=2*t)return Uint32Array.from({length:n},(e,t)=>t);let r=new Uint32Array(2*t),i=0;for(let a=0;a<t;a++){let o=Math.floor(a*n/t),s=Math.floor((a+1)*n/t),c=1/0,l=-1/0,u=-1,d=-1;for(let t=o;t<s;t++){let n=e[t];n<c&&(c=n,u=t),n>l&&(l=n,d=t)}u<0||(u===d?r[i++]=u:u<d?(r[i++]=u,r[i++]=d):(r[i++]=d,r[i++]=u))}return r.subarray(0,i)}function Eq(e,t){let n=new Float64Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n}function Dq(e){for(let t=1;t<e.length;t++)if(!(e[t]>=e[t-1]))return!1;return e.length===0||e[0]===e[0]}function Oq(e,t){let n=e.length;for(let r=1,i=0;r<n;r++){let a=n>>1;for(;i&a;a>>=1)i^=a;if(i^=a,r<i){let n=e[r];e[r]=e[i],e[i]=n,n=t[r],t[r]=t[i],t[i]=n}}for(let r=2;r<=n;r<<=1){let i=r>>1,a=-2*Math.PI/r,o=Math.cos(a),s=Math.sin(a);for(let a=0;a<n;a+=r){let n=1,r=0;for(let c=0;c<i;c++){let l=a+c,u=l+i,d=e[u]*n-t[u]*r,f=e[u]*r+t[u]*n;e[u]=e[l]-d,t[u]=t[l]-f,e[l]+=d,t[l]+=f;let p=n*o-r*s;r=n*s+r*o,n=p}}}}var kq=new Float64Array,Aq=new Float64Array;function jq(e,t,n){let r=t>>1;kq.length<r&&(kq=new Float64Array(r),Aq=new Float64Array(r));let i=kq.subarray(0,r),a=Aq.subarray(0,r),o=e.length;for(let t=0;t<r;t++){let r=2*t,s=r+1;i[t]=r<o?e[r]*(n?n[r]:1):0,a[t]=s<o?e[s]*(n?n[s]:1):0}Oq(i,a);let s=new Float64Array(r),c=-2*Math.PI/t,l=Math.cos(c),u=Math.sin(c),d=1,f=0;for(let e=0;e<r;e++){let t=e===0?0:r-e,n=i[e],o=a[e],c=i[t],p=-a[t],m=(n+c)/2,h=(o+p)/2,g=(o-p)/2,_=-(n-c)/2,v=m+d*g-f*_,y=h+d*_+f*g;s[e]=Math.sqrt(v*v+y*y);let b=d*l-f*u;f=d*u+f*l,d=b}return s}var Mq=new Float64Array,Nq=0;function Pq(e){if(Nq===e)return Mq.subarray(0,e);Mq.length<e&&(Mq=new Float64Array(Math.max(e,Mq.length*2)));let t=2*Math.PI/Math.max(1,e-1),n=Math.cos(t),r=Math.sin(t),i=1,a=0;for(let t=0;t<e;t++){Mq[t]=.5*(1-i);let e=i*n-a*r;a=a*n+i*r,i=e}return Nq=e,Mq.subarray(0,e)}var Fq={top:14,right:24,bottom:40,left:64},Iq=5;function Lq(e){let t=1;for(;t<e;)t<<=1;return t}function Rq(e,t,n,r){let i=e.length,a=Math.max(2,Lq(i)),o=jq(e,a,n===`hann`?Pq(i):void 0),s=a/2,c=new Float64Array(s),l=2/a;for(let e=0;e<s;e++){c[e]=e*t/a;let n=o[e]*l;o[e]=r===`db`?20*Math.log10(Math.max(n,1e-12)):n}return{freqs:c,amps:o}}function zq({signal:e,sampleRate:t=1,label:n,xMode:r=`hz`,yMode:i=`amplitude`,window:a=`hann`,color:o=`#34d399`,logX:s=!1,height:c=400,backgroundToken:l=``,onPlotContextMenu:u}){let d=FU(),f=K(null),p=K(null),m=K(null),h=K(u);G(()=>{h.current=u},[u]);let g=K({signal:e,sampleRate:t,label:n,xMode:r,yMode:i,window:a,color:o,logX:s,height:c});G(()=>{g.current={signal:e,sampleRate:t,label:n,xMode:r,yMode:i,window:a,color:o,logX:s,height:c}},[e,t,n,r,i,a,o,s,c]);let _=St(()=>e.length>=4?Rq(e,t,a,i):null,[e,t,a,i]),v=St(()=>_&&s?_.freqs.map(e=>Math.log10(e)):null,[_,s]),y=K(_&&{..._,logFreqs:v});G(()=>{y.current=_&&{..._,logFreqs:v}},[_,v]);function b(){if(m.current)return m.current;let e=p.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return m.current=n,n}function x(){let e=p.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||g.current.height)}}function S(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function C(){let e=f.current;if(!e)return;let{w:t,h:n}=x(),r=S(e,t,n);if(!r)return;let{top:i,right:a,bottom:o,left:s}=Fq,c=t-s-a,l=n-i-o,{bg:u,muted:p,grid:m}=b(),{sampleRate:h,label:_,xMode:v,yMode:C,color:w,logX:T}=g.current,E=y.current;if(r.fillStyle=u,r.fillRect(0,0,t,n),!E||c<=0||l<=0){r.fillStyle=p,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{freqs:D,amps:O,logFreqs:k}=E,A=D.length,j=v===`hz`?`${_} (Hz)`:`${_} (order)`,M=v===`order`&&h>0?h:1,N=D[1]/M,P=D[A-1]/M,F=1/0,I=-1/0;for(let e=1;e<A;e++)O[e]<F&&(F=O[e]),O[e]>I&&(I=O[e]);if(!Number.isFinite(F)||!Number.isFinite(I)){r.fillStyle=p,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let L=(I-F)*.05||.1;F-=L,I+=L;let R=T?e=>{if(e<=0||N<=0)return s;let t=Math.log10(N),n=Math.log10(P);return s+(Math.log10(e)-t)/(n-t)*c}:e=>s+(e-N)/(P-N)*c;T&&N<=0&&(N=D[1]>0?D[1]/M:.001),d({left:s,top:i,width:c,height:l,x:{v0:N,v1:P,log:T},y:{v0:F,v1:I}});let z=e=>i+(I-e)/(I-F)*l,B=Pz(I-F,5),V=Lz(F,I,B);r.strokeStyle=m,r.lineWidth=1,r.setLineDash([3,3]);for(let e of V)r.beginPath(),r.moveTo(s,z(e)),r.lineTo(s+c,z(e)),r.stroke();r.setLineDash([]);let ee=T?1:Pz(P-N,Fz(c)),te=T?(()=>{let e=[],t=Math.ceil(Math.log10(Math.max(N,1e-12))),n=Math.floor(Math.log10(P));for(let r=t;r<=n;r++)for(let t of[1,2,5]){let n=t*10**r;n>=N&&n<=P&&e.push(n)}return e})():Lz(N,P,ee);r.strokeStyle=m,r.lineWidth=1,r.setLineDash([3,3]);for(let e of te)r.beginPath(),r.moveTo(R(e),i),r.lineTo(R(e),i+l),r.stroke();r.setLineDash([]),r.strokeStyle=p,r.lineWidth=1,r.fillStyle=p,r.font=`11px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of V)r.beginPath(),r.moveTo(s-Iq,z(e)),r.lineTo(s,z(e)),r.stroke(),r.fillText(Vz(e,B),s-4,z(e));r.textAlign=`center`,r.textBaseline=`top`;for(let e of te)r.beginPath(),r.moveTo(R(e),i+l),r.lineTo(R(e),i+l+Iq),r.stroke(),r.fillText(Vz(e,T?e:ee),R(e),i+l+Iq+2);r.strokeStyle=m,r.lineWidth=1,r.strokeRect(s,i,c,l),r.save(),r.beginPath(),r.rect(s,i,c,l),r.clip(),r.strokeStyle=w,r.lineWidth=1,r.beginPath();let H=!1,ne=Math.min(2,window.devicePixelRatio||1),re=Math.max(1,Math.round(c*ne)),ie=A>re*4?T&&k?wq(k,O,Math.log10(N*M),Math.log10(P*M),re):wq(D,O,N*M,P*M,re):null;for(let e=+!ie;e<(ie?ie.length:A);e++){let t=ie?ie[e]:e;if(t<1)continue;let n=D[t]/M;if(n<N||n>P)continue;let i=R(n),a=z(O[t]);H?r.lineTo(i,a):(r.moveTo(i,a),H=!0)}r.stroke(),r.restore(),r.fillStyle=p,r.font=`11px ${Q.mono}`,r.save(),r.translate(14,i+l/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(C===`db`?`dB`:`Amplitude`,0,0),r.restore(),r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(j,s+c/2,n-4)}let w=K(C);w.current=C;let T=K(null);T.current??=GH(()=>w.current(),()=>p.current);let E=()=>T.current.schedule();return W(()=>{T.current.now()}),W(()=>()=>T.current?.cancel(),[]),W(()=>{m.current=null,E()},[l]),G(()=>{let e=p.current;if(!e)return;let t=new UH(()=>{m.current=null,E()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=f.current;if(!e)return;let t=e=>{e.preventDefault(),h.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),q(`div`,{ref:p,style:{position:`relative`,width:`100%`,height:`100%`},children:q(`canvas`,{ref:f,className:`chart-canvas`,role:`img`,"aria-label":`Spectrum of ${n}`})})}function Bq(e,t,n=0,r=e.length-1){for(;r>n;){let i=n+r>>>1,a=e[n],o=e[i],s=e[r];if(a>o){let e=a;a=o,o=e}o>s&&(o=s),a>o&&(o=a);let c=o,l=n,u=r;for(;l<=u;){for(;e[l]<c;)l++;for(;e[u]>c;)u--;if(l<=u){let t=e[l];e[l]=e[u],e[u]=t,l++,u--}}if(t<=u)r=u;else if(t>=l)n=l;else break}return e[t]}function Vq(e,t){let n=e.length;if(n===0)return t.map(()=>0);let r=[...new Set(t.flatMap(e=>{let t=e/100*(n-1);return[Math.floor(t),Math.ceil(t)]}))].sort((e,t)=>e-t),i=new Map,a=0;for(let t of r)i.set(t,Bq(e,t,a)),a=t;return t.map(e=>{let t=e/100*(n-1),r=Math.floor(t);return i.get(r)+(i.get(Math.ceil(t))-i.get(r))*(t-r)})}var Hq={top:14,right:24,bottom:48,left:64},Uq=5;function Wq(e,t){let n=e.length;if(n===0)return null;let[r,i,a,o,s]=Vq(Float64Array.from(e),[0,25,50,75,100]),c=0;for(let t=0;t<n;t++)c+=e[t];let l=c/n;if(t!==`1.5iqr`)return{q1:i,median:a,q3:o,mean:l,whiskerLo:r,whiskerHi:s,outliers:new Float64Array};let u=o-i,d=i-1.5*u,f=o+1.5*u,p=1/0,m=-1/0,h=0;for(let t=0;t<n;t++){let n=e[t];if(n<d||n>f){h++;continue}n<p&&(p=n),n>m&&(m=n)}let g=new Float64Array(h);for(let t=0,r=0;t<n;t++){let n=e[t];(n<d||n>f)&&(g[r++]=n)}return g.sort(),{q1:i,median:a,q3:o,mean:l,whiskerLo:p<=m?p:i,whiskerHi:p<=m?m:o,outliers:g}}function Gq({groups:e,color:t=`#fb923c`,whiskers:n=`1.5iqr`,height:r=400,backgroundToken:i=``,onPlotContextMenu:a}){let o=FU(),s=K(null),c=K(null),l=K(null),u=K(a);G(()=>{u.current=a},[a]);let d=K({groups:e,color:t,whiskers:n,height:r});G(()=>{d.current={groups:e,color:t,whiskers:n,height:r}},[e,t,n,r]);let f=St(()=>e.filter(e=>e.values.length>0).map(e=>({label:e.label,box:Wq(e.values,n)})),[e,n]),p=K(f);G(()=>{p.current=f},[f]);function m(){if(l.current)return l.current;let e=c.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return l.current=n,n}function h(){let e=c.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||d.current.height)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function _(){let e=s.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;let{top:i,right:a,bottom:c,left:l}=Hq,u=t-l-a,f=n-i-c,{bg:_,muted:v,grid:y}=m(),{color:b}=d.current;r.fillStyle=_,r.fillRect(0,0,t,n);let x=p.current;if(x.length===0||u<=0||f<=0){r.fillStyle=v,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let S=1/0,C=-1/0;for(let e of x){e.box.whiskerLo<S&&(S=e.box.whiskerLo),e.box.whiskerHi>C&&(C=e.box.whiskerHi);for(let t of e.box.outliers)t<S&&(S=t),t>C&&(C=t)}let w=(C-S)*.08||1;S-=w,C+=w;let T=e=>i+(C-e)/(C-S)*f;o({left:l,top:i,width:u,height:f,y:{v0:S,v1:C}});let E=Pz(C-S,5),D=Lz(S,C,E);r.strokeStyle=y,r.lineWidth=1,r.setLineDash([3,3]);for(let e of D)r.beginPath(),r.moveTo(l,T(e)),r.lineTo(l+u,T(e)),r.stroke();r.setLineDash([]),r.strokeStyle=v,r.lineWidth=1,r.fillStyle=v,r.font=`11px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of D)r.beginPath(),r.moveTo(l-Uq,T(e)),r.lineTo(l,T(e)),r.stroke(),r.fillText(Vz(e,E),l-4,T(e));r.strokeStyle=y,r.lineWidth=1,r.strokeRect(l,i,u,f),r.save(),r.beginPath(),r.rect(l,i,u,f),r.clip();let O=x.length,k=u/O,A=Math.min(k*.55,60);for(let e=0;e<O;e++){let{box:t}=x[e],n=l+k*e+k/2;r.strokeStyle=b,r.lineWidth=1.5,r.beginPath(),r.moveTo(n,T(t.whiskerLo)),r.lineTo(n,T(t.whiskerHi)),r.stroke();let i=A*.35;r.beginPath(),r.moveTo(n-i,T(t.whiskerLo)),r.lineTo(n+i,T(t.whiskerLo)),r.moveTo(n-i,T(t.whiskerHi)),r.lineTo(n+i,T(t.whiskerHi)),r.stroke();let a=n-A/2,o=T(t.q3),s=Math.max(1,T(t.q1)-o);r.fillStyle=b,r.globalAlpha=.25,r.fillRect(a,o,A,s),r.globalAlpha=1,r.strokeStyle=b,r.lineWidth=1.5,r.strokeRect(a,o,A,s),r.strokeStyle=b,r.lineWidth=2.5,r.beginPath(),r.moveTo(a,T(t.median)),r.lineTo(a+A,T(t.median)),r.stroke();let c=T(t.mean);r.fillStyle=b,r.beginPath(),r.moveTo(n,c-5),r.lineTo(n+5,c),r.lineTo(n,c+5),r.lineTo(n-5,c),r.closePath(),r.fill(),r.fillStyle=b,r.globalAlpha=.6;let u=NaN;for(let e of t.outliers){let t=T(e);Math.abs(t-u)<.5||(u=t,r.beginPath(),r.arc(n,t,2.5,0,Math.PI*2),r.fill())}r.globalAlpha=1}r.restore(),r.fillStyle=v,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`;for(let e=0;e<O;e++){let t=l+k*e+k/2,n=x[e].label;r.save(),r.rect(l+k*e+2,i+f+Uq+2,k-4,c-Uq-4),r.clip(),r.fillText(n,t,i+f+Uq+2),r.restore()}}let v=K(_);v.current=_;let y=K(null);y.current??=GH(()=>v.current(),()=>c.current);let b=()=>y.current.schedule();return W(()=>{y.current.now()}),W(()=>()=>y.current?.cancel(),[]),W(()=>{l.current=null,b()},[i]),G(()=>{let e=c.current;if(!e)return;let t=new UH(()=>{l.current=null,b()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=s.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),q(`div`,{ref:c,style:{position:`relative`,width:`100%`,height:`100%`},children:q(`canvas`,{ref:s,className:`chart-canvas`,role:`img`,"aria-label":`Box plot`})})}function Kq(e,t){if(e.w<=t)return{grid:e,per:1};let n=e.w/t,r=new Float32Array(t*e.h);for(let i=0;i<e.h;i++){let a=i*e.w;for(let o=0;o<t;o++){let s=Math.floor(o*n),c=Math.min(e.w,Math.floor((o+1)*n)),l=0,u=0;for(let t=s;t<c;t++){let n=e.values[a+t];n===n&&(l+=n,u++)}r[i*t+o]=u?l/u:NaN}}let i=e.xLabels;return{grid:{w:t,h:e.h,values:r,xLabels:e=>typeof i==`function`?i(Math.floor(e*n)):i[Math.floor(e*n)],yLabels:e.yLabels},per:n}}var qq=e=>e.includes(`.`)&&!e.includes(`e`)?e.replace(/\.?0+$/,``):e;function Jq(e){return e>=1e3?`${qq((e/1e3).toPrecision(3))}k`:qq(e.toPrecision(3))}function Yq(e,t,n,r,i,a,o){let s=t>>1,c=e.length,l=c>=t?Math.floor((c-t)/n)+1:0,u=`${t}|${n}|${r}|${i}|${a?a.join(`,`):``}`,d=-1,f=0;if(o&&o.key===u&&o.frames>0&&c>0){let r=o.sig;for(let i=0;i*n<r.length&&f===0;i++){let a=i*n;if(r[a]!==e[0])continue;let s=Math.min(r.length-a,c),u=!0;for(let t=0;t<s;t++)if(r[a+t]!==e[t]){u=!1;break}if(!u)continue;let p=s>=t?Math.floor((s-t)/n)+1:0;d=i,f=Math.max(0,Math.min(p,o.frames-i,l))}}let p=new Float32Array(l*s),m=new Float32Array(l);if(f>0){for(let e=0;e<s;e++)p.set(o.values.subarray(e*o.frames+d,e*o.frames+d+f),e*l);m.set(o.frameMax.subarray(d,d+f))}let h=new Float64Array(t);for(let e=0;e<t;e++)h[e]=r?.5*(1-Math.cos(2*Math.PI*e/(t-1))):1;let g=Math.log2(t),_=new Uint32Array(t);for(let e=0;e<t;e++){let t=0,n=e;for(let e=0;e<g;e++)t=t<<1|n&1,n>>=1;_[e]=t}let v=new Float64Array(t),y=new Float64Array(t),b=new Float64Array(s);for(let r=f;r<l;r++){let o=r*n;for(let n=0;n<t;n++){let t=_[n];v[n]=e[o+t]*h[t],y[n]=0}for(let e=2;e<=t;e<<=1){let n=e>>1,r=-2*Math.PI/e,i=Math.cos(r),a=Math.sin(r);for(let r=0;r<t;r+=e){let e=1,t=0;for(let o=0;o<n;o++){let s=r+o,c=s+n,l=v[c]*e-y[c]*t,u=v[c]*t+y[c]*e;v[c]=v[s]-l,y[c]=y[s]-u,v[s]+=l,y[s]+=u;let d=e*i-t*a;t=e*a+t*i,e=d}}}let c=0;for(let e=0;e<s;e++){let n=Math.sqrt(v[e]*v[e]+y[e]*y[e])/t;b[e]=n,n>c&&(c=n)}m[r]=c;for(let e=0;e<s;e++){let t=b[a?a[e]:e];p[e*l+r]=i?20*Math.log10(Math.max(t,1e-12)):t}}let x=1e-10;for(let e=0;e<l;e++)m[e]>x&&(x=m[e]);return{values:p,frames:l,bins:s,max:x,computed:l-f,sig:Float64Array.from(e),frameMax:m,key:u}}var Xq={top:14,right:24,bottom:40,left:68},Zq=[[8,0,16],[48,0,96],[104,0,144],[160,0,128],[200,32,64],[230,100,16],[250,200,32],[255,255,220]],Qq=-80;function $q(e){let t=Zq.length-1,n=Math.min(t-1,Math.floor(e*t)),r=e*t-n,[i,a,o]=Zq[n],[s,c,l]=Zq[n+1];return[i+(s-i)*r,a+(c-a)*r,o+(l-o)*r]}var eJ=(()=>{let e=new Uint8Array(256*4);for(let t=0;t<256;t++){let[n,r,i]=$q(t/255);e.set([n,r,i,255],t*4)}return e})();function tJ(e){let t=1;for(;t<e;)t<<=1;return t}var nJ=(e,t)=>Math.log(1+e/t*9)/Math.log(10),rJ=(e,t)=>t*(10**e-1)/9;function iJ({signal:e,sampleRate:t=1e3,windowSize:n=512,overlap:r=.5,winFunc:i=`hann`,yMode:a=`db`,logFreq:o=!1,label:s=``,backgroundToken:c=``,onPlotContextMenu:l}){let u=FU(),d=K(null),f=K(null),p=K(null),m=K(null),h=K(null),g=K(l);G(()=>{g.current=l},[l]);let _=tJ(Math.max(4,Math.min(n,4096))),v=Math.max(1,Math.round(_*(1-Math.max(0,Math.min(.95,r))))),y=St(()=>{if(!o)return null;let e=_>>1,n=t/2;return Int32Array.from({length:e},(t,r)=>Math.min(e-1,Math.floor(rJ((r+.5)/e,n)/n*e)))},[o,_,t]),b=K(null),x=St(()=>b.current=Yq(e,_,v,i===`hann`,a===`db`,y,b.current),[e,_,v,i,a,y]),S=St(()=>({w:x.frames,h:x.bins,values:x.values,xLabels:[],yLabels:[]}),[x]),C=a===`db`?20*Math.log10(x.max):x.max,w=a===`db`?[C+Qq,C]:[0,C],T=K({grid:S,range:w,sampleRate:t,winSz:_,step:v,yMode:a,logFreq:o,label:s});G(()=>{T.current={grid:S,range:w,sampleRate:t,winSz:_,step:v,yMode:a,logFreq:o,label:s}},[S,w[0],w[1],t,_,v,a,o,s]);let E=K({plot:null,failed:!1,size:``,grid:null,shown:null});W(()=>()=>{E.current.plot?.dispose(),E.current.plot=null},[]);function D(){if(h.current)return h.current;let e=m.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return h.current=n,n}function O(){let e=m.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function k(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function A(e,t){let n=E.current;if(!n.plot&&!n.failed&&f.current&&(n.plot=dH(f.current,vq),n.failed=!n.plot),!n.plot||!f.current)return null;let r=Math.min(2,window.devicePixelRatio||1),i=`${e}x${t}@${r}`;return n.size!==i&&(n.plot.resize(e,t,r),f.current.style.width=`${e}px`,f.current.style.height=`${t}px`,n.size=i),n.plot}function j(){let e=d.current;if(!e)return;let{w:t,h:n}=O(),r=k(e,t,n);if(!r)return;let i=p.current?k(p.current,t,n):null;i?.clearRect(0,0,t,n);let a=jG(Xq,t,n),{top:o,right:s,bottom:c,left:l}=a,f=t-l-s,h=n-o-c,{bg:g,muted:_,grid:v}=D(),{grid:y,sampleRate:b,winSz:x,step:S,logFreq:C,label:w}=T.current;r.fillStyle=g,r.fillRect(0,0,t,n);let j=A(t,n);if(y.w===0||f<=0||h<=0){if(j?.keep([]),j?.render(),a.tiny)return;r.fillStyle=_,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let M=Math.min(2,window.devicePixelRatio||1),N=j?j.maxTextureSize:Math.max(1,Math.round(f*M)),[P,F]=T.current.range;if(E.current.grid!==y||!E.current.shown||!j&&E.current.shown.w>N){let e=Kq(y,N).grid;j&&j.setGrid(`cells`,e.values,e.w,Math.min(e.h,j.maxTextureSize),[0,e.w,0,e.h],eJ,P,F),E.current.grid=y,E.current.shown=e,BH(m.current)}let I=E.current.shown;if(j)j.keep([`cells`]),j.setGridRange(`cells`,P,F),j.setView(0,I.w,0,I.h,{left:l,top:o,width:f,height:h}),j.render();else{let e=document.createElement(`canvas`);e.width=I.w,e.height=I.h;let t=e.getContext(`2d`),n=t.createImageData(I.w,I.h);for(let e=0;e<I.h;e++)for(let t=0;t<I.w;t++){let[r,i,a]=$q(Math.max(0,Math.min(1,(I.values[e*I.w+t]-P)/(F-P)))),o=(t+(I.h-1-e)*I.w)*4;n.data[o]=r,n.data[o+1]=i,n.data[o+2]=a,n.data[o+3]=255}t.putImageData(n,0,0),r.drawImage(e,l,o,f,h)}if(a.tiny)return;let L=i??r,R=b/2,z=e=>o+h*(1-(C?nJ(e,R):e/R));L.strokeStyle=v,L.lineWidth=.5,L.globalAlpha=.4;let B=Lz(0,R,Pz(R,5));L.setLineDash([3,4]);for(let e of B){let t=z(e);L.beginPath(),L.moveTo(l,t),L.lineTo(l+f,t),L.stroke()}L.setLineDash([]),L.globalAlpha=1,L.strokeStyle=v,L.strokeRect(l,o,f,h),r.fillStyle=_,r.font=`10px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`,r.strokeStyle=_,r.lineWidth=1;for(let e of B){let t=z(e);r.beginPath(),r.moveTo(l-4,t),r.lineTo(l,t),r.stroke(),r.fillText(Jq(e),l-6,t)}let V=(y.w*S+x)/b;u({left:l,top:o,width:f,height:h,x:{v0:0,v1:V}});let ee=Pz(V,6),te=Lz(0,V,ee);r.textAlign=`center`,r.textBaseline=`top`;for(let e of te){let t=l+e/V*f;r.beginPath(),r.moveTo(t,o+h),r.lineTo(t,o+h+4),r.stroke(),r.fillText(Vz(e,ee),t,o+h+6)}r.fillStyle=_,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(w||`Time (s)`,l+f/2,n-4),r.save(),r.translate(12,o+h/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.fillText(`Frequency (Hz)`,0,0),r.restore()}let M=K(j);G(()=>{M.current=j});let N=K(null);return N.current??=GH(()=>M.current(),()=>m.current),W(()=>{N.current.now()},[S,w[0],w[1],t,_,v,a,o,s]),W(()=>()=>N.current?.cancel(),[]),W(()=>{h.current=null,N.current.schedule()},[c]),G(()=>{let e=m.current;if(!e)return;let t=new UH(()=>{h.current=null,N.current.schedule()});return t.observe(e),()=>t.disconnect()},[]),G(()=>{let e=p.current;if(!e)return;let t=e=>{e.preventDefault(),g.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),Ot(`div`,{ref:m,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:d,className:`chart-canvas`,role:`img`,"aria-label":`Spectrogram`}),q(`canvas`,{ref:f,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:p,className:`chart-canvas chart-overlay`})]})}var aJ=300,oJ=256,sJ=-60,cJ=[];function lJ({signal:e,sampleRate:t,windowSize:n,overlap:r,winFunc:i,yMode:a,backgroundToken:o,onPlotContextMenu:s}){let c=2**Math.ceil(Math.log2(Math.max(4,Math.min(n,4096)))),l=Math.max(1,Math.round(c*(1-Math.max(0,Math.min(.95,r))))),u=a===`db`,d=St(()=>Yq(e,c,l,i===`hann`,u,null),[e,c,l,i,u]);return q(QK,{points:cJ,surface:St(()=>uJ(d,t,c,l,u),[d,t,c,l,u]),xLabel:`Time (s)`,yLabel:`Frequency (Hz)`,zLabel:u?`Level (dB)`:`Amplitude`,viewMode:`3d`,showMesh:!0,meshStyle:`filled`,meshOpacity:1,backgroundToken:o,onPlotContextMenu:s})}function uJ(e,t,n,r,i){let{frames:a,bins:o,values:s}=e;if(a<2||o<2)return;let c=Math.min(a,aJ),l=Math.min(o,oJ),u=i?20*Math.log10(Math.max(e.max,1e-12))+sJ:-1/0,d=new Float32Array(c*l);for(let e=0;e<l;e++){let t=Math.floor(e*o/l),n=Math.max(t+1,Math.floor((e+1)*o/l));for(let r=0;r<c;r++){let i=Math.floor(r*a/c),o=Math.max(i+1,Math.floor((r+1)*a/c)),l=-1/0;for(let e=t;e<n;e++)for(let t=i;t<o;t++){let n=s[e*a+t];n>l&&(l=n)}d[e*c+r]=Math.max(u,l)}}let f=e=>(e*r+n/2)/t;return{w:c,h:l,values:d,x:[f(0),f(a-1)],y:[0,(o-1)*t/n]}}function dJ(e,t,n){return Array.from({length:n},(r,i)=>e+(i+1)/(n+1)*(t-e))}function fJ(e,t,n,r){let i=[],a=(n,r)=>e[r*t+n],o=(e,t)=>(r-e)/(t-e);for(let e=0;e+1<n;e++)for(let n=0;n+1<t;n++){let t=a(n,e),s=a(n+1,e),c=a(n+1,e+1),l=a(n,e+1);if(t!==t||s!==s||c!==c||l!==l)continue;let u=(t>=r?8:0)|(s>=r?4:0)|(c>=r?2:0)|l>=r;if(u===0||u===15)continue;let d=()=>[n+o(t,s),e],f=()=>[n+1,e+o(s,c)],p=()=>[n+o(l,c),e+1],m=()=>[n,e+o(t,l)],h=(e,t)=>i.push([e[0],e[1],t[0],t[1]]);switch(u){case 1:case 14:h(m(),p());break;case 2:case 13:h(p(),f());break;case 3:case 12:h(m(),f());break;case 4:case 11:h(d(),f());break;case 6:case 9:h(d(),p());break;case 7:case 8:h(m(),d());break;case 5:case 10:{let e=(t+s+c+l)/4>=r;u===5===e?(h(m(),d()),h(p(),f())):(h(d(),f()),h(m(),p()));break}}}return i}function pJ(e){let t=e.length,n=new Float64Array(t+1);if(t===1)return n[0]=e[0]-.5,n[1]=e[0]+.5,n;for(let r=1;r<t;r++)n[r]=(e[r-1]+e[r])/2;return n[0]=e[0]-(n[1]-e[0]),n[t]=e[t-1]+(e[t-1]-n[t-1]),n}function mJ(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t])||t>0&&!(e[t]>e[t-1]))return!1;return!0}var hJ={top:14,right:32,bottom:80,left:80};function gJ(e,t,n){return[e[0]+(t[0]-e[0])*n,e[1]+(t[1]-e[1])*n,e[2]+(t[2]-e[2])*n]}var _J=[[33,102,172],[103,169,207],[209,229,240],[247,247,247],[253,219,199],[239,138,98],[178,24,43]],vJ=[[13,8,135],[84,2,163],[139,10,165],[185,50,137],[219,92,104],[244,136,73],[254,188,43],[240,249,33]],yJ=[[68,1,84],[72,40,120],[62,83,160],[49,120,178],[38,153,185],[31,184,187],[53,213,158],[117,231,101],[198,239,82],[253,231,37]];function bJ(e,t){let n=e.length-1,r=Math.min(n-1,Math.floor(t*n));return gJ(e[r],e[r+1],t*n-r)}function xJ(e,t){return bJ(t===`plasma`?vJ:t===`viridis`?yJ:_J,e)}function SJ(e){let t=new Uint8Array(256*4);for(let n=0;n<256;n++){let[r,i,a]=xJ(n/255,e);t.set([r,i,a,255],n*4)}return t}function CJ(e){return Math.abs(e)>=1e4||Math.abs(e)<.01&&e!==0?e.toExponential(1):String(parseFloat(e.toPrecision(3)))}function wJ(e,t,n){let r=new Map(t.map((e,t)=>[e,t])),i=new Map(n.map((e,t)=>[e,t])),a=new Float32Array(t.length*n.length);for(let n of e){let e=r.get(n.x),o=i.get(n.y);e!==void 0&&o!==void 0&&(a[o*t.length+e]=n.value)}return{w:t.length,h:n.length,values:a,xLabels:t,yLabels:n}}function TJ(e,t,n,r,i,a,o){let s=(e,t,n)=>Float64Array.from({length:e+1},(r,i)=>t+i/e*n),c=!!a&&a.length===e.w,l=!!o&&o.length===e.h,u=s(e.w,t,r),d=s(e.h,n,i);if(c){let n=pJ(a),i=n[e.w]-n[0];u=Float64Array.from(n,e=>t+(e-n[0])/i*r)}if(l){let t=pJ(Float64Array.from(o).reverse()),r=e.h,a=t[r]-t[0];d=Float64Array.from({length:r+1},(e,o)=>n+(t[r]-t[r-o])/a*i)}return{xB:u,yB:d,byValue:c||l}}function EJ(e,t){if(t<e[0]||t>=e[e.length-1])return-1;let n=0,r=e.length-1;for(;r-n>1;){let i=n+r>>1;e[i]<=t?n=i:r=i}return n}function DJ(e,t,n,r,i,a){let o=Math.max(1,i),s=Math.max(1,a),c=Int32Array.from({length:o},(e,r)=>EJ(t.xB,n+r+.5)),l=new Float32Array(o*s);for(let n=0;n<s;n++){let i=EJ(t.yB,r+n+.5),a=i*e.w;for(let t=0;t<o;t++)l[n*o+t]=i<0||c[t]<0?NaN:e.values[a+c[t]]}return{w:o,h:s,values:l,xLabels:e.xLabels,yLabels:e.yLabels}}function OJ({cells:e,xLabels:t,yLabels:n,grid:r,showValues:i=!0,colorScheme:a=`diverging`,vMin:o,vMax:s,xCentres:c,yCentres:l,contours:u=0,backgroundToken:d=``,onPlotContextMenu:f}){let p=K(null),m=K(null),h=K(null),g=K(null),_=K(null),v=K(null),y=K(null),b=K(0),x=K(f);G(()=>{x.current=f},[f]);let S=St(()=>r??wJ(e??[],t??[],n??[]),[r,e,t,n]),C=St(()=>{let e=o??1/0,t=s??-1/0;if(o===void 0||s===void 0){let n=1/0,r=-1/0;for(let e=0;e<S.w*S.h;e++){let t=S.values[e];t<n&&(n=t),t>r&&(r=t)}o===void 0&&(e=n),s===void 0&&(t=r)}return t>e||(e=Number.isFinite(e)?e-1:0,t=e+2),{lo:e,hi:t}},[S,o,s]),w=K({data:S,range:C,showValues:i,colorScheme:a,xCentres:c,yCentres:l,contours:u});G(()=>{w.current={data:S,range:C,showValues:i,colorScheme:a,xCentres:c,yCentres:l,contours:u}},[S,C,i,a,c,l,u]);let T=K({plot:null,failed:!1,size:``,data:null,key:``,shown:null,geo:null}),E=K({key:``,grid:null,segs:[]});W(()=>()=>{T.current.plot?.dispose(),T.current.plot=null},[]);let D=K({data:null,range:``});function O(){if(v.current)return v.current;let e=_.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return v.current=n,n}function k(){let e=_.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function A(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function j(e,t){let n=T.current;if(!n.plot&&!n.failed&&m.current&&(n.plot=dH(m.current,vq),n.failed=!n.plot),!n.plot||!m.current)return null;let r=Math.min(2,window.devicePixelRatio||1),i=`${e}x${t}@${r}`;return n.size!==i&&(n.plot.resize(e,t,r),m.current.style.width=`${e}px`,m.current.style.height=`${t}px`,n.size=i),n.plot}let M=(e,t)=>typeof e==`function`?e(t):e[t];function N(){let e=p.current;if(!e)return;let{w:t,h:n}=k(),r=A(e,t,n);if(!r)return;let i=h.current?A(h.current,t,n):null;i?.clearRect(0,0,t,n);let a=jG(hJ,t,n),{top:o,right:s,bottom:c,left:l}=a,{bg:u,muted:d,grid:f}=O(),{data:m,range:{lo:g,hi:v},showValues:y,colorScheme:b}=w.current;r.fillStyle=u,r.fillRect(0,0,t,n);let x=j(t,n);if(m.w===0||m.h===0){x?.keep([]),x?.render(),r.fillStyle=d,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let S=t-l-s,C=n-o-c,N=Math.min(2,window.devicePixelRatio||1),P=D.current;(P.data!==m||P.range!==`${g}|${v}`)&&(D.current={data:m,range:`${g}|${v}`},BH(_.current));let{xCentres:F,yCentres:I,contours:L}=w.current,R=x?x.maxTextureSize:Math.max(1,Math.round(S*N)),z=Kq(m,R).grid,B=TJ(z,l,o,S,C,z===m?F:void 0,z===m?I:void 0),V=B.byValue,ee=`${R}|${b}|${V?`${S}x${C}`:``}`,te=T.current.shown;if(T.current.data!==m||T.current.key!==ee||!te){te=z;let e=V?DJ(te,B,l,o,Math.round(S),Math.round(C)):te;x&&x.setGrid(`cells`,e.values,e.w,Math.min(e.h,x.maxTextureSize),[0,e.w,0,e.h],SJ(b),g,v),T.current.data=m,T.current.key=ee,T.current.shown=te}T.current.geo=B;let H=V?Math.round(S):te.w,ne=V?Math.round(C):te.h,re=e=>B.xB[e+1]-B.xB[e],ie=e=>B.yB[e+1]-B.yB[e];if(x)x.keep([`cells`]),x.setGridRange(`cells`,g,v),x.setView(0,H,ne,0,{left:l,top:o,width:S,height:C}),x.render();else for(let e=0;e<te.h;e++)for(let t=0;t<te.w;t++){let n=te.values[e*te.w+t];if(Number.isNaN(n))continue;let[i,a,o]=xJ(Math.max(0,Math.min(1,(n-g)/(v-g))),b);r.fillStyle=`rgb(${i|0},${a|0},${o|0})`,r.fillRect(B.xB[t],B.yB[e],re(t)+.5,ie(e)+.5)}let U=i??r;if(y){for(let e=0;e<te.h;e++)if(!(ie(e)<=16)){U.font=`${Math.min(12,Math.max(8,ie(e)*.4))}px ${Q.mono}`,U.textAlign=`center`,U.textBaseline=`middle`;for(let t=0;t<te.w;t++){let n=te.values[e*te.w+t];if(Number.isNaN(n)||re(t)<=28)continue;let[r,i,a]=xJ(Math.max(0,Math.min(1,(n-g)/(v-g))),b);U.fillStyle=.299*r+.587*i+.114*a>128?`#000`:`#fff`,U.fillText(CJ(n),(B.xB[t]+B.xB[t+1])/2,(B.yB[e]+B.yB[e+1])/2)}}}if(S/te.w>=4&&C/te.h>=4){U.strokeStyle=u,U.lineWidth=.5;for(let e=0;e<=te.w;e++)U.beginPath(),U.moveTo(B.xB[e],o),U.lineTo(B.xB[e],o+C),U.stroke();for(let e=0;e<=te.h;e++)U.beginPath(),U.moveTo(l,B.yB[e]),U.lineTo(l+S,B.yB[e]),U.stroke()}let ae=L>0?dJ(g,v,L):[];if(ae.length&&te.w>=2&&te.h>=2&&te.w*te.h<=4e6){let e=`${g}|${v}|${L}`;if(E.current.grid!==te||E.current.key!==e){let t=te;E.current={key:e,grid:t,segs:ae.map(e=>fJ(t.values,t.w,t.h,e))}}let t=(e,t)=>{let n=Math.min(t.length-3,Math.max(0,Math.floor(e))),r=(t[n]+t[n+1])/2;return r+((t[n+1]+t[n+2])/2-r)*(e-n)};U.save(),U.beginPath(),U.rect(l,o,S,C),U.clip(),U.lineCap=`round`,U.lineJoin=`round`;for(let[e,n]of[[2.6,`rgba(0,0,0,0.38)`],[1.1,`rgba(255,255,255,0.92)`]]){U.lineWidth=e,U.strokeStyle=n,U.beginPath();for(let e of E.current.segs)for(let[n,r,i,a]of e)U.moveTo(t(n,B.xB),t(r,B.yB)),U.lineTo(t(i,B.xB),t(a,B.yB));U.stroke()}U.restore()}r.fillStyle=d,r.font=`10px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`;let oe=-1/0;for(let e=0;e<(a.tiny?0:te.w);e++){let t=(B.xB[e]+B.xB[e+1])/2;t-oe<18||(oe=t,r.save(),r.translate(t,o+C+4),r.rotate(-Math.PI/4),r.fillText(M(te.xLabels,e),0,0),r.restore())}r.textAlign=`right`,r.textBaseline=`middle`;let se=-1/0;for(let e=0;e<(a.tiny?0:te.h);e++){let t=(B.yB[e]+B.yB[e+1])/2;t-se<12||(se=t,r.fillText(te.yLabels[e]??``,l-4,t))}if(a.tiny)return;let ce=t-s+4,le=o,ue=C;for(let e=0;e<ue;e++){let[t,n,i]=xJ(1-e/ue,b);r.fillStyle=`rgb(${t|0},${n|0},${i|0})`,r.fillRect(ce,le+e,12,1)}r.strokeStyle=f,r.lineWidth=.5,r.strokeRect(ce,le,12,ue),r.fillStyle=d,r.font=`9px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`middle`,r.fillText(CJ(v),ce+12+2,le),r.fillText(CJ(g),ce+12+2,le+ue),r.fillText(CJ((g+v)/2),ce+12+2,le+ue/2),r.strokeStyle=`rgba(255,255,255,0.92)`,r.lineWidth=1;for(let e of ae){let t=le+ue*(1-(e-g)/(v-g));r.beginPath(),r.moveTo(ce-2,t),r.lineTo(ce+12+2,t),r.stroke()}}function P(){let e=g.current;if(!e)return;let{w:t,h:n}=k(),r=A(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=y.current,a=T.current.shown,o=T.current.geo;if(!i||!a||!o)return;let{top:s,right:c,bottom:l}=jG(hJ,t,n),{xi:u,yi:d}=i;if(u>=a.w||d>=a.h)return;let f=o.xB[u],p=o.xB[u+1],m=o.yB[d],h=o.yB[d+1];r.strokeStyle=`rgba(255,255,255,0.7)`,r.lineWidth=1.5,r.strokeRect(f+.5,m+.5,Math.max(1,p-f-1),Math.max(1,h-m-1));let _=a.values[d*a.w+u];if(!Number.isNaN(_)){let e=`${M(a.xLabels,u)} × ${a.yLabels[d]}: ${CJ(_)}`;r.font=`11px ${Q.mono}`;let n=r.measureText(e).width,i=Math.min(p+.1*(p-f),t-c-n-6),o=Math.max(s+4,m-.3*(h-m));r.fillStyle=`rgba(0,0,0,0.7)`,r.fillRect(i-3,o-3,n+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(e,i,o)}}let F=K(N);F.current=N;let I=K(null);I.current??=GH(()=>F.current(),()=>_.current);let L=()=>{b.current||=LH(()=>{b.current=0,P()})};return W(()=>{I.current.now()},[S,C,i,a,c,l,u]),W(()=>()=>{I.current?.cancel(),RH(b.current)},[]),W(()=>{v.current=null,I.current.schedule()},[d]),G(()=>{let e=_.current;if(!e)return;let t=new UH(()=>{v.current=null,I.current.schedule(),L()});return t.observe(e),()=>t.disconnect()},[]),G(()=>{let e=g.current;if(!e)return;let t=e=>{e.preventDefault(),x.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{shown:r,geo:i}=T.current;if(!r||!i)return;let a=EJ(i.xB,t.clientX-n.left),o=EJ(i.yB,t.clientY-n.top);y.current=a>=0&&a<r.w&&o>=0&&o<r.h?{xi:a,yi:o}:null,L()},r=()=>{y.current=null,L()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:_,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:p,className:`chart-canvas`,role:`img`,"aria-label":`Heatmap`}),q(`canvas`,{ref:m,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:h,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:g,className:`chart-canvas chart-overlay`})]})}var kJ=2e3,AJ=1024;function jJ(e,t,n,r,i){let a=e.length,o=1/(a*t*Math.sqrt(2*Math.PI)),s=new Float64Array(n.length);if(a<=kJ){for(let r=0;r<n.length;r++){let i=0;for(let o=0;o<a;o++){let a=(n[r]-e[o])/t;i+=Math.exp(-.5*a*a)}s[r]=i*o}return s}let c=new Float64Array(AJ),l=(i-r)/AJ||1;for(let t=0;t<a;t++)c[Math.max(0,Math.min(AJ-1,Math.floor((e[t]-r)/l)))]++;for(let e=0;e<n.length;e++){let i=0;for(let a=0;a<AJ;a++){if(c[a]===0)continue;let o=(n[e]-(r+(a+.5)*l))/t;i+=c[a]*Math.exp(-.5*o*o)}s[e]=i*o}return s}var MJ={top:14,right:24,bottom:48,left:64},NJ=120;function PJ(e,t,n){let r=e.length;if(r<2)return 1;let i=0;for(let t=0;t<r;t++)i+=e[t];let a=i/r,o=0;for(let t=0;t<r;t++)o+=(e[t]-a)**2;let s=Math.sqrt(o/(r-1));return .9*Math.min(s,(n-t)/1.34)*r**-.2}function FJ(e,t){let n=e.filter(e=>e.values.length>=2),r=1/0,i=-1/0,a=n.map(e=>{let[t,n,a,o,s]=Vq(Float64Array.from(e.values),[0,25,50,75,100]);return t<r&&(r=t),s>i&&(i=s),{q1:n,median:a,q3:o}}),o=(i-r)*.1||1;r-=o,i+=o;let s=Float64Array.from({length:NJ},(e,t)=>r+t/(NJ-1)*(i-r));return{shapes:n.map((e,n)=>{let{q1:o,median:c,q3:l}=a[n],u=jJ(e.values,t>0?t:PJ(e.values,o,l),s,r,i),d=1e-10;for(let e of u)e>d&&(d=e);return{label:e.label,density:u,maxDensity:d,q1:o,median:c,q3:l}}),pts:s,yMin:r,yMax:i}}function IJ({groups:e,color:t=`#818cf8`,showBox:n=!0,bandwidth:r=0,orientation:i=`vertical`,backgroundToken:a=``,onPlotContextMenu:o}){let s=FU(),c=K(null),l=K(null),u=K(null),d=K(o);G(()=>{d.current=o},[o]);let f=K({groups:e,color:t,showBox:n,bandwidth:r,orientation:i});G(()=>{f.current={groups:e,color:t,showBox:n,bandwidth:r,orientation:i}},[e,t,n,r,i]);let p=St(()=>FJ(e,r),[e,r]),m=K(p);G(()=>{m.current=p},[p]);function h(){if(u.current)return u.current;let e=l.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return u.current=n,n}function g(){let e=l.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function _(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function v(){let e=c.current;if(!e)return;let{w:t,h:n}=g(),r=_(e,t,n);if(!r)return;let{top:i,right:a,bottom:o,left:l}=MJ,u=t-l-a,d=n-i-o,{bg:p,muted:v,grid:y}=h(),{color:b,showBox:x,orientation:S}=f.current;r.fillStyle=p,r.fillRect(0,0,t,n);let{shapes:C,pts:w,yMin:T,yMax:E}=m.current;if(C.length===0||u<=0||d<=0){r.fillStyle=v,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let D=S===`vertical`,O=D?e=>i+d*(1-(e-T)/(E-T)):e=>l+u*((e-T)/(E-T));s({left:l,top:i,width:u,height:d,...D?{y:{v0:T,v1:E}}:{x:{v0:T,v1:E}}});let k=Pz(E-T,5),A=Lz(T,E,k);r.strokeStyle=y,r.lineWidth=1,r.setLineDash([3,3]);for(let e of A)D?(r.beginPath(),r.moveTo(l,O(e)),r.lineTo(l+u,O(e)),r.stroke()):(r.beginPath(),r.moveTo(O(e),i),r.lineTo(O(e),i+d),r.stroke());if(r.setLineDash([]),r.fillStyle=v,r.font=`11px ${Q.mono}`,r.strokeStyle=v,r.lineWidth=1,D){r.textAlign=`right`,r.textBaseline=`middle`;for(let e of A)r.beginPath(),r.moveTo(l-4,O(e)),r.lineTo(l,O(e)),r.stroke(),r.fillText(Vz(e,k),l-6,O(e))}else{r.textAlign=`center`,r.textBaseline=`top`;for(let e of A)r.beginPath(),r.moveTo(O(e),i+d),r.lineTo(O(e),i+d+4),r.stroke(),r.fillText(Vz(e,k),O(e),i+d+6)}r.strokeStyle=y,r.strokeRect(l,i,u,d),r.save(),r.beginPath(),r.rect(l,i,u,d),r.clip();let j=C.length,M=D?u/j:d/j;for(let e=0;e<j;e++){let{density:t,maxDensity:n,q1:a,median:o,q3:s}=C[e],c=D?l+M*e+M/2:i+M*e+M/2,u=M*.45;r.beginPath();for(let e=0;e<NJ;e++){let i=t[e]/n*u,a=O(w[e]);D?e===0?r.moveTo(c-i,a):r.lineTo(c-i,a):e===0?r.moveTo(a,c-i):r.lineTo(a,c-i)}for(let e=NJ-1;e>=0;e--){let i=t[e]/n*u,a=O(w[e]);D?r.lineTo(c+i,a):r.lineTo(a,c+i)}if(r.closePath(),r.fillStyle=b,r.globalAlpha=.35,r.fill(),r.strokeStyle=b,r.lineWidth=1,r.globalAlpha=.9,r.stroke(),r.globalAlpha=1,x){let e=u*.22;D?(r.fillStyle=b,r.globalAlpha=.7,r.fillRect(c-e,O(s),e*2,O(a)-O(s)),r.globalAlpha=1,r.strokeStyle=b,r.lineWidth=2,r.beginPath(),r.moveTo(c-e,O(o)),r.lineTo(c+e,O(o)),r.stroke()):(r.fillStyle=b,r.globalAlpha=.7,r.fillRect(O(a),c-e,O(s)-O(a),e*2),r.globalAlpha=1,r.strokeStyle=b,r.lineWidth=2,r.beginPath(),r.moveTo(O(o),c-e),r.lineTo(O(o),c+e),r.stroke())}}if(r.restore(),r.fillStyle=v,r.font=`11px ${Q.mono}`,D){r.textAlign=`center`,r.textBaseline=`top`;for(let e=0;e<j;e++)r.fillText(C[e].label,l+M*e+M/2,i+d+6)}else{r.textAlign=`right`,r.textBaseline=`middle`;for(let e=0;e<j;e++)r.fillText(C[e].label,l-6,i+M*e+M/2)}}let y=K(v);y.current=v;let b=K(null);b.current??=GH(()=>y.current(),()=>l.current);let x=()=>b.current.schedule();return W(()=>{b.current.now()}),W(()=>()=>b.current?.cancel(),[]),W(()=>{u.current=null,x()},[a]),G(()=>{let e=l.current;if(!e)return;let t=new UH(()=>{u.current=null,x()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=c.current;if(!e)return;let t=e=>{e.preventDefault(),d.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),q(`div`,{ref:l,style:{position:`relative`,width:`100%`,height:`100%`},children:q(`canvas`,{ref:c,className:`chart-canvas`,role:`img`,"aria-label":`Violin plot`})})}var LJ={top:48,right:16,bottom:72,left:80},RJ=[8,24,64],zJ=[56,189,248];function BJ(e,t,n){return[e[0]+(t[0]-e[0])*n,e[1]+(t[1]-e[1])*n,e[2]+(t[2]-e[2])*n]}function VJ(e){return`${(e*100).toFixed(1)}%`}function HJ(e,t,n){if(e.length===0)return null;let r=Math.min(e.length,t.length),i=Array(r),a=Array(r),o=new Set,s=0;for(let n=0;n<r;n++)i[n]=String(e[n]),a[n]=String(t[n]),o.add(i[n]),o.add(a[n]),i[n]===a[n]&&s++;let c=[...o].sort(),l=c.length,u=new Map(c.map((e,t)=>[e,t])),d=Array.from({length:l},()=>Array(l).fill(0));for(let e=0;e<r;e++)d[u.get(i[e])][u.get(a[e])]++;let f=d.map(e=>e.reduce((e,t)=>e+t,0));return{classes:c,matrix:n?d.map((e,t)=>e.map(e=>f[t]>0?e/f[t]:0)):d,raw:d,accuracy:s/e.length}}function UJ({actual:e,predicted:t,normalize:n=!1,backgroundToken:r=``,onPlotContextMenu:i}){let a=K(null),o=K(null),s=K(null),c=K(null),l=K(null),u=K(0),d=K(i);G(()=>{d.current=i},[i]);let f=K({actual:e,predicted:t,normalize:n});G(()=>{f.current={actual:e,predicted:t,normalize:n}},[e,t,n]);function p(){if(c.current)return c.current;let e=s.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return c.current=n,n}function m(){let e=s.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function h(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}let g=St(()=>HJ(e,t,n),[e,t,n]),_=K(g);G(()=>{_.current=g},[g]);let v=()=>_.current;function y(){let e=a.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;let{top:i,right:o,bottom:s,left:c}=LJ,{bg:l,muted:u,grid:d}=p();r.fillStyle=l,r.fillRect(0,0,t,n);let g=v();if(!g){r.fillStyle=u,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{classes:_,matrix:y,accuracy:b}=g,x=_.length,S=t-c-o,C=n-i-s,w=S/x,T=C/x,E=0;for(let e of y)for(let t of e)t>E&&(E=t);for(let e=0;e<x;e++)for(let t=0;t<x;t++){let n=y[e][t],[a,o,s]=BJ(RJ,zJ,E>0?n/E:0);if(r.fillStyle=`rgb(${a|0},${o|0},${s|0})`,r.fillRect(c+t*w,i+e*T,w,T),w>24&&T>14){r.fillStyle=.299*a+.587*o+.114*s>100?`#000`:`#fff`,r.font=`${Math.min(12,Math.max(8,T*.38))}px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`middle`;let l=f.current.normalize;r.fillText(l?VJ(n):String(n|0),c+(t+.5)*w,i+(e+.5)*T)}}r.strokeStyle=l,r.lineWidth=.5;for(let e=0;e<=x;e++)r.beginPath(),r.moveTo(c+e*w,i),r.lineTo(c+e*w,i+C),r.stroke(),r.beginPath(),r.moveTo(c,i+e*T),r.lineTo(c+S,i+e*T),r.stroke();r.strokeStyle=d,r.strokeRect(c,i,S,C),r.fillStyle=u,r.font=`10px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`;for(let e=0;e<x;e++)r.fillText(_[e],c-4,i+(e+.5)*T);r.textAlign=`center`,r.textBaseline=`top`;for(let e=0;e<x;e++)r.save(),r.translate(c+(e+.5)*w,i+C+4),r.rotate(-Math.PI/4),r.fillText(_[e],0,0),r.restore();r.fillStyle=u,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(`Predicted`,c+S/2,n-4),r.save(),r.translate(12,i+C/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.fillText(`Actual`,0,0),r.restore(),r.fillStyle=u,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(`Accuracy: ${VJ(b)}`,c+S/2,i/2)}function b(){let e=o.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=l.current;if(!i)return;let{top:a,right:s,bottom:c,left:u}=LJ,d=v();if(!d)return;let{classes:p,matrix:g}=d,_=p.length,y=t-u-s,b=n-a-c,x=y/_,S=b/_;r.strokeStyle=`rgba(255,255,255,0.8)`,r.lineWidth=2,r.strokeRect(u+i.c*x+1,a+i.r*S+1,x-2,S-2);let C=g[i.r][i.c],w=f.current.normalize,T=`${p[i.r]} → ${p[i.c]}: ${w?VJ(C):C|0}`;r.font=`11px ${Q.mono}`;let E=r.measureText(T).width,D=Math.min(u+(i.c+1.1)*x,t-E-6),O=Math.max(6,a+(i.r-.3)*S);r.fillStyle=`rgba(0,0,0,0.75)`,r.fillRect(D-3,O-3,E+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(T,D,O)}let x=K(y);x.current=y;let S=K(null);S.current??=GH(()=>x.current(),()=>s.current);let C=()=>S.current.schedule(),w=()=>{RH(u.current),u.current=LH(b)};return W(()=>{S.current.now()}),W(()=>()=>S.current?.cancel(),[]),W(()=>{c.current=null,C()},[r]),G(()=>{let e=s.current;if(!e)return;let t=new UH(()=>{c.current=null,C(),w()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=o.current;if(!e)return;let t=e=>{e.preventDefault(),d.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{top:r,right:i,bottom:a,left:o}=LJ,s=v();if(!s)return;let c=s.classes.length,u=n.width-o-i,d=n.height-r-a,f=Math.floor((t.clientX-n.left-o)/(u/c)),p=Math.floor((t.clientY-n.top-r)/(d/c));l.current=p>=0&&p<c&&f>=0&&f<c?{r:p,c:f}:null,w()},r=()=>{l.current=null,w()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:s,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:a,className:`chart-canvas`,role:`img`,"aria-label":`Confusion matrix`}),q(`canvas`,{ref:o,className:`chart-canvas chart-overlay`})]})}var WJ={top:24,right:24,bottom:48,left:64};function GJ(e,t){let n=0,r=0,i=Math.min(e.length,t.length);for(let a=0;a<i;a++)e[a]-e[a]!==0||t[a]-t[a]!==0||(t[a]===1?n++:r++);let a=new Float64Array(n),o=new Float64Array(r);for(let n=0,r=0,s=0;n<i;n++)e[n]-e[n]!==0||t[n]-t[n]!==0||(t[n]===1?a[r++]=e[n]:o[s++]=e[n]);a.sort(),o.sort();let s=new Uint8Array(n+r);for(let e=0,t=n-1,i=r-1;e<s.length;e++)i<0||t>=0&&a[t]>=o[i]?(s[e]=1,t--):(s[e]=0,i--);return s}function KJ(e){let t=0;for(let n of e)t+=n;let n=e.length-t;if(t===0||n===0)return null;let r=new Float64Array(e.length+2),i=new Float64Array(e.length+2),a=0,o=0,s=0;for(let c=0;c<e.length;c++)e[c]===1?a++:o++,r[c+1]=o/n,i[c+1]=a/t,s+=(r[c+1]-r[c])*(i[c+1]+i[c])/2;return r[e.length+1]=1,i[e.length+1]=1,{fpr:r,tpr:i,auc:s}}function qJ(e){let t=0;for(let n of e)t+=n;if(t===0)return null;let n=new Float64Array(e.length),r=new Float64Array(e.length),i=0,a=0,o=0;for(let s=0;s<e.length;s++)e[s]===1?i++:a++,n[s]=i/t,r[s]=i/(i+a),s>0&&(o+=(n[s]-n[s-1])*r[s]);return{recall:n,precision:r,ap:o}}function JJ(e,t,n,r){let i=n(0),a=r(0);e.moveTo(i,a);for(let o=1;o<t;o++){let s=n(o),c=r(o);o<t-1&&Math.abs(s-i)<.5&&Math.abs(c-a)<.5||(e.lineTo(s,c),i=s,a=c)}}function YJ({scores:e,labels:t,mode:n=`roc`,color:r=`#f472b6`,backgroundToken:i=``,onPlotContextMenu:a}){let o=K(null),s=K(null),c=K(null),l=K(a);G(()=>{l.current=a},[a]);let u=K({scores:e,labels:t,mode:n,color:r});G(()=>{u.current={scores:e,labels:t,mode:n,color:r}},[e,t,n,r]);let d=St(()=>GJ(e,t),[e,t]),f=St(()=>n===`pr`?{roc:null,pr:qJ(d)}:{roc:KJ(d),pr:null},[d,n]),p=K(f);G(()=>{p.current=f},[f]);function m(){if(c.current)return c.current;let e=s.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return c.current=n,n}function h(){let e=s.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function _(){let e=o.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;let{top:i,right:a,bottom:s,left:c}=WJ,l=t-c-a,d=n-i-s,{bg:f,muted:_,grid:v}=m(),{scores:y,mode:b,color:x}=u.current;if(r.fillStyle=f,r.fillRect(0,0,t,n),y.length===0){r.fillStyle=_,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let S=e=>c+e*l,C=e=>i+(1-e)*d,w=Lz(0,1,Pz(1,5));r.strokeStyle=v,r.lineWidth=1,r.setLineDash([3,3]);for(let e of w)r.beginPath(),r.moveTo(S(e),i),r.lineTo(S(e),i+d),r.stroke(),r.beginPath(),r.moveTo(c,C(e)),r.lineTo(c+l,C(e)),r.stroke();if(r.setLineDash([]),b===`roc`&&(r.strokeStyle=_,r.lineWidth=1,r.setLineDash([4,4]),r.beginPath(),r.moveTo(S(0),C(0)),r.lineTo(S(1),C(1)),r.stroke(),r.setLineDash([])),b===`roc`){let e=p.current.roc;if(e){let t=e.fpr.length,n=t=>S(e.fpr[t]),a=t=>C(e.tpr[t]);r.beginPath(),JJ(r,t,n,a),r.strokeStyle=x,r.lineWidth=1,r.stroke(),r.beginPath(),JJ(r,t,n,a),r.lineTo(S(1),C(0)),r.lineTo(S(0),C(0)),r.closePath(),r.fillStyle=x,r.globalAlpha=.15,r.fill(),r.globalAlpha=1,r.fillStyle=x,r.font=`bold 13px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`AUC = ${e.auc.toFixed(3)}`,c+8,i+8)}}else{let e=p.current.pr;if(e){let t=wq(e.recall,e.precision,0,1,Math.max(1,Math.round(l*Math.min(2,window.devicePixelRatio||1))));r.beginPath();for(let n=0;n<t.length;n++){let i=S(e.recall[t[n]]),a=C(e.precision[t[n]]);n===0?r.moveTo(i,a):r.lineTo(i,a)}r.strokeStyle=x,r.lineWidth=1,r.stroke(),r.fillStyle=x,r.font=`bold 13px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`AP = ${e.ap.toFixed(3)}`,c+8,i+8)}}r.fillStyle=_,r.font=`11px ${Q.mono}`,r.strokeStyle=_,r.lineWidth=1,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of w)r.beginPath(),r.moveTo(c-4,C(e)),r.lineTo(c,C(e)),r.stroke(),r.fillText(e.toFixed(1),c-6,C(e));r.textAlign=`center`,r.textBaseline=`top`;for(let e of w)r.beginPath(),r.moveTo(S(e),i+d),r.lineTo(S(e),i+d+4),r.stroke(),r.fillText(e.toFixed(1),S(e),i+d+6);r.strokeStyle=v,r.strokeRect(c,i,l,d),r.fillStyle=_,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(b===`roc`?`False Positive Rate`:`Recall`,c+l/2,n-4),r.save(),r.translate(12,i+d/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.fillText(b===`roc`?`True Positive Rate`:`Precision`,0,0),r.restore()}let v=K(_);v.current=_;let y=K(null);y.current??=GH(()=>v.current(),()=>s.current);let b=()=>y.current.schedule();return W(()=>{y.current.now()}),W(()=>()=>y.current?.cancel(),[]),W(()=>{c.current=null,b()},[i]),G(()=>{let e=s.current;if(!e)return;let t=new UH(()=>{c.current=null,b()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=o.current;if(!e)return;let t=e=>{e.preventDefault(),l.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),q(`div`,{ref:s,style:{position:`relative`,width:`100%`,height:`100%`},children:q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`ROC / PR curve`})})}var XJ={top:20,right:64,bottom:48,left:64};function ZJ({xValues:e,series:t,xLabel:n=`Epoch`,backgroundToken:r=``,onPlotContextMenu:i}){let a=FU(),o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(0),f=K(i);G(()=>{f.current=i},[i]);let p=K({xValues:e,series:t,xLabel:n});G(()=>{p.current={xValues:e,series:t,xLabel:n}},[e,t,n]);function m(){if(l.current)return l.current;let e=c.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return l.current=n,n}function h(){let e=c.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}let _=St(()=>{let n=e=>{let t=1/0,n=-1/0;for(let r of e)for(let e=0;e<r.values.length;e++){let i=r.values[e];i<t&&(t=i),i>n&&(n=i)}if(!Number.isFinite(t))return{lo:0,hi:1};let r=(n-t)*.06||.1;return{lo:t-r,hi:n+r}},r=t.filter(e=>e.axis===`left`),i=t.filter(e=>e.axis===`right`),a=1/0,o=-1/0;for(let t=0;t<e.length;t++){let n=e[t];n<a&&(a=n),n>o&&(o=n)}return{leftExt:n(r.length?r:t),rightExt:n(i.length?i:t),hasRight:i.length>0,xMin:a,xMax:o,ascending:Dq(e)}},[e,t]),v=K(_);G(()=>{v.current=_},[_]);function y(){let e=o.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;let{top:i,right:s,bottom:c,left:l}=XJ,u=t-l-s,d=n-i-c,{bg:f,muted:_,grid:y}=m(),{xValues:b,series:x,xLabel:S}=p.current;if(r.fillStyle=f,r.fillRect(0,0,t,n),b.length===0||x.length===0){r.fillStyle=_,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{leftExt:C,rightExt:w,hasRight:T,xMin:E,xMax:D,ascending:O}=v.current,k=e=>l+(e-E)/(D-E||1)*u;a({left:l,top:i,width:u,height:d,x:{v0:E,v1:D},y:{v0:C.lo,v1:C.hi}});let A=e=>i+(1-(e-C.lo)/(C.hi-C.lo))*d,j=e=>i+(1-(e-w.lo)/(w.hi-w.lo))*d,M=Pz(C.hi-C.lo,5),N=Lz(C.lo,C.hi,M);r.strokeStyle=y,r.lineWidth=1,r.setLineDash([3,3]);for(let e of N)r.beginPath(),r.moveTo(l,A(e)),r.lineTo(l+u,A(e)),r.stroke();let P=Pz(D-E,6),F=Lz(E,D,P);for(let e of F)r.beginPath(),r.moveTo(k(e),i),r.lineTo(k(e),i+d),r.stroke();r.setLineDash([]);let I=Math.min(2,window.devicePixelRatio||1),L=Math.max(1,Math.round(u*I));for(let e of x){let t=e.axis===`right`&&T?j:A,n=Math.min(b.length,e.values.length),i=O&&n>4*L?wq(b,e.values,E,D,L):null;r.beginPath();let a=!1;for(let o=0;o<(i?i.length:n);o++){let n=i?i[o]:o,s=b[n],c=e.values[n];if(s-s!==0||c-c!==0){a=!1;continue}let l=k(s),u=t(c);a?r.lineTo(l,u):(r.moveTo(l,u),a=!0)}r.strokeStyle=e.color,r.lineWidth=1,r.stroke()}r.fillStyle=_,r.font=`11px ${Q.mono}`,r.strokeStyle=_,r.lineWidth=1,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of N)r.beginPath(),r.moveTo(l-4,A(e)),r.lineTo(l,A(e)),r.stroke(),r.fillText(Vz(e,M),l-6,A(e));if(T){let e=Pz(w.hi-w.lo,5),t=Lz(w.lo,w.hi,e);r.textAlign=`left`;for(let n of t)r.beginPath(),r.moveTo(l+u,j(n)),r.lineTo(l+u+4,j(n)),r.stroke(),r.fillText(Vz(n,e),l+u+6,j(n))}r.textAlign=`center`,r.textBaseline=`top`;for(let e of F)r.beginPath(),r.moveTo(k(e),i+d),r.lineTo(k(e),i+d+4),r.stroke(),r.fillText(Vz(e,P),k(e),i+d+6);r.strokeStyle=y,r.strokeRect(l,i,u,d),r.fillStyle=_,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(S,l+u/2,n-4);let R=l+8,z=i+6;r.font=`10px ${Q.mono}`,r.textBaseline=`middle`;for(let e of x)r.fillStyle=e.color,r.fillRect(R,z-4,16,3),r.fillStyle=_,r.textAlign=`left`,r.fillText(e.label,R+20,z),R+=r.measureText(e.label).width+36,R>l+u-60&&(R=l+8,z+=14)}function b(){let e=s.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=u.current;if(i===null)return;let{top:a,right:o,bottom:c,left:l}=XJ,d=t-l-o,f=n-a-c,{muted:_}=m(),{xValues:y,series:b}=p.current;if(y.length===0)return;let{xMin:x,xMax:S,ascending:C}=v.current,w=e=>l+(e-x)/(S-x||1)*d,T=Math.max(l,Math.min(l+d,i));r.strokeStyle=_,r.lineWidth=1,r.setLineDash([3,3]),r.beginPath(),r.moveTo(T,a),r.lineTo(T,a+f),r.stroke(),r.setLineDash([]);let E=(T-l)/d,D=Math.round(E*(y.length-1));if(C){let e=x+E*(S-x),t=0,n=y.length;for(;t<n;){let r=t+n>>>1;y[r]<e?t=r+1:n=r}D=t>0&&(t>=y.length||e-y[t-1]<y[t]-e)?t-1:t}if(D<0||D>=y.length)return;let O=a+8;r.font=`10px ${Q.mono}`,r.textBaseline=`top`;for(let e of b)D<e.values.length&&Number.isFinite(e.values[D])&&(r.fillStyle=e.color,r.textAlign=`left`,r.fillText(`${e.label}: ${Hz(e.values[D])}`,T+6,O),O+=14);w(0)}let x=K(y);x.current=y;let S=K(null);S.current??=GH(()=>x.current(),()=>c.current);let C=()=>S.current.schedule(),w=()=>{RH(d.current),d.current=LH(b)};return W(()=>{S.current.now()}),W(()=>()=>S.current?.cancel(),[]),W(()=>{l.current=null,C()},[r]),G(()=>{let e=c.current;if(!e)return;let t=new UH(()=>{l.current=null,C(),w()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=s.current;if(!e)return;let t=e=>{e.preventDefault(),f.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect();u.current=t.clientX-n.left,w()},r=()=>{u.current=null,w()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:c,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Loss curves`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`})]})}var QJ={top:40,right:24,bottom:40,left:72},$J=`#ef4444`,eY=`#f97316`,tY=`#22d3ee`;function nY(e,t){let n=e.length,r=e.value;if(n===0)return null;let i=0;for(let e=0;e<n;e++)i+=r[e];let a=i/n,o=0;for(let e=0;e<n;e++)o+=(r[e]-a)**2;let s=Math.sqrt(o/n),c=a+t*s,l=a-t*s,u=l,d=c,f=0;for(let e=0;e<n;e++){let t=r[e];t<u&&(u=t),t>d&&(d=t),(t>c||t<l)&&f++}let p=(d-u)*.08||.5,m=new Uint32Array(f);for(let e=0,t=0;e<n;e++)(r[e]>c||r[e]<l)&&(m[t++]=e);return{mean:a,sd:s,ucl:c,lcl:l,yMin:u-p,yMax:d+p,ooc:m}}function rY({points:e,sigmaLevel:t=3,color:n=`#22d3ee`,backgroundToken:r=``,onPlotContextMenu:i}){let a=FU(),o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(0),f=K(i);G(()=>{f.current=i},[i]);let p=K({points:e,sigmaLevel:t,color:n});G(()=>{p.current={points:e,sigmaLevel:t,color:n}},[e,t,n]);function m(){if(l.current)return l.current;let e=c.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return l.current=n,n}function h(){let e=c.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}let _=St(()=>nY(e,t),[e,t]),v=K(_);G(()=>{v.current=_},[_]);let y=()=>v.current;function b(){let e=o.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;let{top:i,right:s,bottom:c,left:l}=QJ,u=t-l-s,d=n-i-c,{bg:f,muted:_,grid:v}=m(),{points:b,color:x}=p.current;if(r.fillStyle=f,r.fillRect(0,0,t,n),b.length===0){r.fillStyle=_,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let S=y(),{mean:C,ucl:w,lcl:T,yMin:E,yMax:D}=S,O=e=>l+e/(b.length-1||1)*u;a({left:l,top:i,width:u,height:d,x:{v0:0,v1:b.length-1||1}});let k=e=>i+(1-(e-E)/(D-E))*d,A=Pz(D-E,5),j=Lz(E,D,A);r.strokeStyle=v,r.lineWidth=1,r.setLineDash([3,3]);for(let e of j)r.beginPath(),r.moveTo(l,k(e)),r.lineTo(l+u,k(e)),r.stroke();r.setLineDash([]);let M=(e,t,n,a=[])=>{let o=k(e);o<i||o>i+d||(r.strokeStyle=t,r.lineWidth=1.2,r.setLineDash(a),r.beginPath(),r.moveTo(l,o),r.lineTo(l+u,o),r.stroke(),r.setLineDash([]),r.fillStyle=t,r.font=`9px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(`${n} ${Hz(e)}`,l+u-2,o-5))};M(w,eY,`UCL`,[5,3]),M(C,tY,`CL`,[]),M(T,eY,`LCL`,[5,3]);let N=Math.min(2,window.devicePixelRatio||1),P=Math.max(1,Math.round(u*N)),F=b.length,I=b.value,L=Tq(I,P);r.beginPath();for(let e=0;e<L.length;e++){let t=L[e],n=O(t),i=k(I[t]);e===0?r.moveTo(n,i):r.lineTo(n,i)}r.strokeStyle=x,r.lineWidth=1,r.stroke();let R=(e,t)=>{r.beginPath(),r.arc(O(e),k(I[e]),t?4:3,0,Math.PI*2),r.fillStyle=t?$J:x,r.fill()};if(F<=u/4)for(let e=0;e<F;e++)R(e,I[e]>w||I[e]<T);else{let e=NaN,t=NaN;for(let n of S.ooc){let r=Math.round(O(n)),i=Math.round(k(I[n]));r===e&&i===t||(e=r,t=i,R(n,!0))}}r.fillStyle=_,r.font=`11px ${Q.mono}`,r.strokeStyle=_,r.lineWidth=1,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of j)r.beginPath(),r.moveTo(l-4,k(e)),r.lineTo(l,k(e)),r.stroke(),r.fillText(Vz(e,A),l-6,k(e));r.strokeStyle=v,r.strokeRect(l,i,u,d)}function x(){let e=s.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=u.current;if(i===null)return;let{top:a,right:o,bottom:c,left:l}=QJ,d=t-l-o,f=n-a-c,{muted:_}=m(),{points:v}=p.current;if(v.length===0)return;let{ucl:b,lcl:x,yMin:S,yMax:C}=y(),w=e=>l+e/(v.length-1||1)*d,T=e=>a+(1-(e-S)/(C-S))*f,E=Math.round((i-l)/d*(v.length-1));if(E<0||E>=v.length)return;let D=v.value[E],O=w(E),k=T(D);r.strokeStyle=_,r.lineWidth=1,r.setLineDash([3,3]),r.beginPath(),r.moveTo(O,a),r.lineTo(O,a+f),r.stroke(),r.setLineDash([]);let A=v.subgroup?.(E),j=`${A?`${A}: `:`#${E+1}: `}${Hz(D)}`;r.font=`11px ${Q.mono}`;let M=r.measureText(j).width,N=O+8+M>l+d?O-M-10:O+8;r.fillStyle=`rgba(0,0,0,0.75)`,r.fillRect(N-3,k-12,M+6,18),r.fillStyle=D>b||D<x?$J:_,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(j,N,k-11)}let S=K(b);S.current=b;let C=K(null);C.current??=GH(()=>S.current(),()=>c.current);let w=()=>C.current.schedule(),T=()=>{RH(d.current),d.current=LH(x)};return W(()=>{C.current.now()}),W(()=>()=>C.current?.cancel(),[]),W(()=>{l.current=null,w()},[r]),G(()=>{let e=c.current;if(!e)return;let t=new UH(()=>{l.current=null,w(),T()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=s.current;if(!e)return;let t=e=>{e.preventDefault(),f.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect();u.current=t.clientX-n.left,T()},r=()=>{u.current=null,T()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:c,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Control chart`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`})]})}var iY={top:32,right:24,bottom:24,left:24},aY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`],oY=16;function sY(e){return`rgb(${Math.round(255*Math.min(1,Math.max(0,3.5*e-.5)))},${Math.round(255*Math.min(1,Math.max(0,e<.5?2*e:2-2*e)))},${Math.round(255*Math.min(1,Math.max(0,1.5-3.5*e)))})`}function cY(e,t,n,r){let i=Math.min(t,e.columns.length),a=e.columns.slice(0,i).map(t=>{let n=1/0,r=-1/0;for(let i=0;i<e.length;i++){let e=t[i];e<n&&(n=e),e>r&&(r=e)}if(!Number.isFinite(n))return{lo:0,hi:1};let i=(r-n)*.05||.5;return{lo:n-i,hi:r+i}}),o={lo:0,hi:1},s=new Int32Array(e.length),c=[r];if(n&&e.colorValue){let t=e.colorValue,n=1/0,r=-1/0;for(let i=0;i<e.length;i++)t[i]<n&&(n=t[i]),t[i]>r&&(r=t[i]);Number.isFinite(n)&&(o={lo:n,hi:r}),c=Array.from({length:oY},(e,t)=>sY((t+.5)/oY));for(let n=0;n<e.length;n++){let e=(t[n]-o.lo)/(o.hi-o.lo||1);s[n]=t[n]===t[n]?Math.max(0,Math.min(oY-1,Math.floor(e*oY))):-1}for(let t=0;t<e.length;t++)s[t]<0&&(s[t]=0)}else if(!n&&e.colorIndex){c=aY;for(let t=0;t<e.length;t++)s[t]=Math.max(0,e.colorIndex[t])%aY.length}let l=new Int32Array(c.length);for(let t=0;t<e.length;t++)l[s[t]]++;let u=c.map((e,t)=>({color:e,x:new Float64Array(l[t]*i),y:new Float64Array(l[t]*i),starts:new Uint8Array(l[t]*i)})),d=new Int32Array(c.length);for(let t=0;t<e.length;t++){let n=u[s[t]],r=d[s[t]]++*i;n.starts[r]=1;for(let o=0;o<i;o++,r++){let i=a[o];n.x[r]=o,n.y[r]=(e.columns[o][t]-i.lo)/(i.hi-i.lo)}}return{k:i,extents:a,colorExt:o,groups:u.filter(e=>e.x.length>0)}}function lY({rows:e,axes:t,color:n=`#64748b`,colorByNumeric:r=!1,backgroundToken:i=``,onPlotContextMenu:a}){let o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(null),f=K(null),p=K(0),m=K(a);G(()=>{m.current=a},[a]);let h=St(()=>cY(e,t.length,r,n),[e,t.length,r,n]),g=K({rows:e,axes:t,colorByNumeric:r,model:h});G(()=>{g.current={rows:e,axes:t,colorByNumeric:r,model:h}},[e,t,r,h]);let _=yq(s),v=K(null);function y(){if(d.current)return d.current;let e=u.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return d.current=n,n}function b(){let e=u.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function x(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function S(){let e=o.current;if(!e)return;let{w:t,h:n}=b(),r=x(e,t,n);if(!r)return;let i=c.current?x(c.current,t,n):null;i?.clearRect(0,0,t,n);let a=i??r,{top:s,right:l,bottom:d,left:f}=iY,{bg:p,muted:m}=y(),{rows:h,axes:S,colorByNumeric:C,model:w}=g.current;r.fillStyle=p,r.fillRect(0,0,t,n);let T=_(t,n);if(S.length<2||h.length===0||w.k<2){T?.keep([]),T?.render(),r.fillStyle=m,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`Select ≥ 2 axes`,f+8,s+8);return}let E=t-f-l,D=n-s-d,O=w.k,k=Array.from({length:O},(e,t)=>f+t/(O-1)*E),A=(e,t)=>{let n=w.extents[t];return s+(1-(e-n.lo)/(n.hi-n.lo))*D},j=Math.max(.05,Math.min(.7,60/h.length));if(T)v.current!==w&&(w.groups.forEach((e,t)=>T.setLine(`c${t}`,e.x,e.y,MK(e.color,j),1,e.starts)),v.current=w,BH(u.current)),T.keep(w.groups.map((e,t)=>`c${t}`)),T.setView(0,O-1,0,1,{left:f,top:s,width:E,height:D}),T.render();else{r.globalAlpha=j;for(let e of w.groups){r.beginPath();let t=!1;for(let n=0;n<e.x.length;n++){let i=e.y[n];if(e.starts[n]&&(t=!1),i!==i){t=!1;continue}let a=f+e.x[n]/(O-1)*E,o=s+(1-i)*D;t?r.lineTo(a,o):(r.moveTo(a,o),t=!0)}r.strokeStyle=e.color,r.lineWidth=1,r.stroke()}r.globalAlpha=1}a.strokeStyle=m,a.lineWidth=1.5;for(let e=0;e<O;e++)a.beginPath(),a.moveTo(k[e],s),a.lineTo(k[e],s+D),a.stroke();a.fillStyle=m,a.font=`9px ${Q.mono}`;for(let e=0;e<O;e++){let t=w.extents[e];for(let n of[0,.25,.5,.75,1]){let r=t.lo+n*(t.hi-t.lo),i=A(r,e);a.beginPath(),a.moveTo(k[e]-3,i),a.lineTo(k[e]+3,i),a.stroke(),a.textAlign=e===O-1?`left`:`right`,a.textBaseline=`middle`,a.fillText(Vz(r,(t.hi-t.lo)/4),k[e]+(e===O-1?5:-5),i)}a.font=`10px ${Q.mono}`,a.textAlign=`center`,a.textBaseline=`bottom`,a.fillText(S[e],k[e],s-4)}let M=h.colorLabels??[];if(!C&&M.length>0&&M.length<=10){let e=f,t=s+D+8;a.font=`9px ${Q.mono}`,a.textBaseline=`top`,M.forEach((n,r)=>{a.fillStyle=aY[r%aY.length],a.fillRect(e,t,10,8),a.fillStyle=m,a.textAlign=`left`,a.fillText(n,e+13,t),e+=a.measureText(n).width+26,e>f+E-40&&(e=f,t+=12)})}}function C(){let e=l.current;if(!e)return;let{w:t,h:n}=b(),r=x(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=f.current;if(i===null)return;let{top:a,right:o,bottom:s,left:c}=iY,{axes:u}=g.current;if(u.length<2)return;let d=t-c-o,p=c+i/(u.length-1)*d;r.strokeStyle=`rgba(255,255,255,0.6)`,r.lineWidth=2,r.beginPath(),r.moveTo(p,a-4),r.lineTo(p,a+(n-a-s)+4),r.stroke()}let w=K(S);w.current=S;let T=K(null);T.current??=GH(()=>w.current(),()=>u.current);let E=()=>T.current.schedule(),D=()=>{RH(p.current),p.current=LH(C)};return W(()=>{T.current.now()}),W(()=>()=>T.current?.cancel(),[]),W(()=>{d.current=null,E()},[i]),G(()=>{let e=u.current;if(!e)return;let t=new UH(()=>{d.current=null,E(),D()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=l.current;if(!e)return;let t=e=>{e.preventDefault(),m.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{axes:r}=g.current;if(r.length<2)return;let i=n.width-iY.left-iY.right,a=r.length,o=t.clientX-n.left-iY.left,s=Math.round(o/i*(a-1));f.current=Math.abs(o-s/(a-1)*i)<20&&s>=0&&s<a?s:null,D()},r=()=>{f.current=null,D()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:u,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Parallel coordinates`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:c,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:l,className:`chart-canvas chart-overlay`})]})}function uY(e,t,n,r,i,a){let o=Math.max(1,Math.ceil(t/r)),s=Math.max(1,Math.ceil(n/r)),c=e=>{let s=i(e),c=a(e);return s>=0&&s<t&&c>=0&&c<n?Math.floor(c/r)*o+Math.floor(s/r):-1},l=new Uint32Array(o*s+1);for(let t=0;t<e;t++){let e=c(t);e>=0&&l[e+1]++}for(let e=0;e<o*s;e++)l[e+1]+=l[e];let u=l.slice(0,o*s),d=new Uint32Array(l[o*s]);for(let t=0;t<e;t++){let e=c(t);e>=0&&(d[u[e]++]=t)}return{cell:r,nx:o,ny:s,start:l,ix:d}}function dY(e,t,n,r,i,a,o){let s=Math.floor(t/e.cell),c=Math.floor(n/e.cell),l=-1,u=r*r;for(let r=c-1;r<=c+1;r++)if(!(r<0||r>=e.ny))for(let c=s-1;c<=s+1;c++){if(c<0||c>=e.nx)continue;let s=r*e.nx+c;for(let r=e.start[s];r<e.start[s+1];r++){let s=e.ix[r],c=(i(s)-t)**2+(a(s)-n)**2;c<u&&(!o||c<o(s)**2)&&(u=c,l=s)}}return l<0?null:l}var fY={top:16,right:16,bottom:16,left:16},pY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function mY(e){return[Math.round(255*Math.min(1,Math.max(0,3.5*e-.5))),Math.round(255*Math.min(1,Math.max(0,e<.5?2*e:2-2*e))),Math.round(255*Math.min(1,Math.max(0,1.5-3.5*e)))]}function hY(e){let[t,n,r]=mY(e);return`rgb(${t},${n},${r})`}var gY=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++)e.set([...mY(t/255),255],t*4);return e})(),_Y=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++){let[n,r,i]=MK(pY[t%pY.length],1);e.set([n*255,r*255,i*255,255],t*4)}return e});function vY(e,t){let n=1/0,r=-1/0,i=1/0,a=-1/0;for(let t=0;t<e.length;t++){let o=e.x[t],s=e.y[t];o<n&&(n=o),o>r&&(r=o),s<i&&(i=s),s>a&&(a=s)}let o=!Number.isFinite(n)||!Number.isFinite(i)?{xLo:-1,xHi:1,yLo:-1,yHi:1}:(()=>{let e=(r-n)*.05||.5,t=(a-i)*.05||.5;return{xLo:n-e,xHi:r+e,yLo:i-t,yHi:a+t}})(),s={lo:0,hi:1},c=null,l=`single`;if(t&&e.colorValue){let t=e.colorValue,n=1/0,r=-1/0;for(let i=0;i<e.length;i++){let e=t[i];e<n&&(n=e),e>r&&(r=e)}Number.isFinite(n)&&(s={lo:n,hi:r}),c=new Float32Array(e.length);let i=s.hi-s.lo;for(let n=0;n<e.length;n++)c[n]=t[n]===t[n]?Math.max(0,Math.min(1,i>0?(t[n]-s.lo)/i:.5)):0;l=`colormap`}else !t&&e.colorIndex&&(c=Float32Array.from(e.colorIndex,e=>e>=0?e%256:0),l=`dataset`);return{ext:o,colorExt:s,key:c,mode:l}}function yY({points:e,color:t=`#64748b`,colorByNumeric:n=!1,pointSize:r=4,backgroundToken:i=``,onPlotContextMenu:a}){let o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(null),f=K(0),p=K(a);G(()=>{p.current=a},[a]);let m=St(()=>vY(e,n),[e,n]),h=K({points:e,color:t,colorByNumeric:n,pointSize:r,model:m});G(()=>{h.current={points:e,color:t,colorByNumeric:n,pointSize:r,model:m}},[e,t,n,r,m]);let g=K({r:null,failed:!1,size:``,model:null,style:``});W(()=>()=>{g.current.r?.dispose(),g.current.r=null},[]);function _(){if(u.current)return u.current;let e=l.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return u.current=n,n}function v(){let e=l.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function y(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function b(e,t){let{top:n,right:r,bottom:i,left:a}=fY,o=e-a-r,s=t-n-i,c=h.current.model.ext;return{xToPx:e=>a+(e-c.xLo)/(c.xHi-c.xLo)*o,yToPx:e=>n+(1-(e-c.yLo)/(c.yHi-c.yLo))*s,plotW:o,plotH:s,ext:c}}function x(e,t){let n=g.current;!n.r&&!n.failed&&s.current&&(n.r=dH(s.current,kG),n.failed=!n.r);let r=n.r;if(!r||!s.current)return null;let i=Math.min(2,window.devicePixelRatio||1),a=`${e}x${t}@${i}`;n.size!==a&&(r.resize(e,t,i),s.current.style.width=`${e}px`,s.current.style.height=`${t}px`,n.size=a);let{points:o,model:c,color:u,pointSize:d}=h.current;n.model!==c&&(r.setData(o.x,o.y,c.key??void 0),n.model=c,BH(l.current));let f=`${c.mode}|${u}|${d}`;return n.style!==f&&(r.setStyle(c.mode===`single`?{kind:`single`,rgba:MK(u,1)}:{kind:c.mode,palette:c.mode===`colormap`?gY:_Y()},d,.8),r.setDraw(!0,!1,0),n.style=f),r}function S(){let e=o.current;if(!e)return;let{w:t,h:n}=v(),r=y(e,t,n);if(!r)return;let{bg:i,muted:a}=_(),{points:s,color:c,colorByNumeric:l,pointSize:u,model:d}=h.current;r.fillStyle=i,r.fillRect(0,0,t,n);let f=x(t,n);if(s.length===0){f?.setData([],[]),g.current.model=null,f?.render(),r.fillStyle=a,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let p=d.colorExt,{xToPx:m,yToPx:S,plotW:C,plotH:w,ext:T}=b(t,n);if(f)f.setView(T.xLo,T.xHi,T.yLo,T.yHi,{left:fY.left,top:fY.top,width:C,height:w}),f.render();else{for(let e=0;e<s.length;e++){let t=s.x[e],n=s.y[e];if(t!==t||n!==n)continue;let i=d.key?.[e]??0;r.beginPath(),r.arc(m(t),S(n),u,0,Math.PI*2),r.fillStyle=d.mode===`colormap`?hY(i):d.mode===`dataset`?pY[i%pY.length]:c,r.globalAlpha=.8,r.fill()}r.globalAlpha=1}if(l){let e=Math.min(120,Math.floor((n-fY.top-fY.bottom)*.4)),i=t-fY.right-12,o=fY.top+8;for(let t=0;t<e;t++)r.fillStyle=hY(1-t/(e-1)),r.fillRect(i,o+t,8,1);r.fillStyle=a,r.font=`9px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`middle`;let s=e=>Math.abs(e)>=1e4||Math.abs(e)<.001&&e!==0?e.toExponential(1):String(parseFloat(e.toPrecision(3)));r.fillText(s(p.hi),i+10,o),r.fillText(s(p.lo),i+10,o+e)}let E=s.colorLabels??[];if(!l&&E.length>0&&E.length<=10){let e=fY.left,i=n-fY.bottom-10;r.font=`9px ${Q.mono}`,r.textBaseline=`top`,E.forEach((n,o)=>{e>t-fY.right-60&&(e=fY.left,i-=14),r.fillStyle=pY[o%pY.length],r.beginPath(),r.arc(e+4,i+4,4,0,Math.PI*2),r.fill(),r.fillStyle=a,r.textAlign=`left`,r.fillText(n,e+10,i),e+=r.measureText(n).width+20})}}function C(){let e=c.current;if(!e)return;let{w:t,h:n}=v(),r=y(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=d.current;if(i===null)return;let{points:a,pointSize:o}=h.current;if(i<0||i>=a.length)return;let{xToPx:s,yToPx:l}=b(t,n),u=a.x[i],f=a.y[i],p=s(u),m=l(f);r.beginPath(),r.arc(p,m,o+3,0,Math.PI*2),r.strokeStyle=`rgba(255,255,255,0.9)`,r.lineWidth=2,r.stroke();let g=[],_=a.label?.(i);_&&g.push(_);let x=a.colorIndex?.[i];x!==void 0&&x>=0&&a.colorLabels?g.push(a.colorLabels[x]):a.colorValue&&g.push(a.colorValue[i].toFixed(3)),g.push(`(${u.toFixed(3)}, ${f.toFixed(3)})`);let S=g.join(` · `);r.font=`11px ${Q.mono}`;let C=r.measureText(S).width,w=Math.max(4,Math.min(t-C-8,p+10)),T=m-20<fY.top?m+10:m-20;r.fillStyle=`rgba(0,0,0,0.75)`,r.fillRect(w-3,T-3,C+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(S,w,T)}let w=K(S);w.current=S;let T=K(null);T.current??=GH(()=>w.current(),()=>l.current);let E=()=>T.current.schedule(),D=()=>{RH(f.current),f.current=LH(C)};return W(()=>{T.current.now()}),W(()=>()=>T.current?.cancel(),[]),W(()=>{u.current=null,E()},[i]),G(()=>{let e=l.current;if(!e)return;let t=new UH(()=>{u.current=null,E(),D()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=c.current;if(!e)return;let t=null,n=e=>{e.preventDefault(),p.current?.({clientX:e.clientX,clientY:e.clientY})},r=n=>{let r=e.getBoundingClientRect(),{points:i,pointSize:a,model:o}=h.current,{w:s,h:c}=v(),{xToPx:l,yToPx:u,plotW:f,plotH:p}=b(s,c),m=e=>l(i.x[e])-fY.left,g=e=>u(i.y[e])-fY.top,_=a+8,y=`${s}|${c}|${_}`;(!t||t.model!==o||t.key!==y)&&(t={model:o,key:y,g:uY(i.length,f,p,_,m,g)}),d.current=dY(t.g,n.clientX-r.left-fY.left,n.clientY-r.top-fY.top,_,m,g),D()},i=()=>{d.current=null,D()};return e.addEventListener(`contextmenu`,n),e.addEventListener(`mousemove`,r),e.addEventListener(`mouseleave`,i),()=>{e.removeEventListener(`contextmenu`,n),e.removeEventListener(`mousemove`,r),e.removeEventListener(`mouseleave`,i)}},[]),Ot(`div`,{ref:l,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Embedding / scatter`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:c,className:`chart-canvas chart-overlay`})]})}var bY={top:8,right:8,bottom:8,left:8},xY=20,SY=[`#f97316`,`#fb923c`,`#fdba74`,`#fbbf24`,`#fcd34d`,`#4ade80`,`#34d399`,`#38bdf8`,`#818cf8`,`#a78bfa`];function CY(e){let t=new Map;for(let n of e){let e=n.parent??``;t.has(e)||t.set(e,[]),t.get(e).push(n)}function n(r,i){let a=(t.get(r)??[]).map(e=>n(e.name,i+1)),o=e.find(e=>e.name===r),s=a.reduce((e,t)=>e+t.value,0);return{name:r,value:o?Math.max(o.value,s):s,children:a,depth:i,x0:0,x1:1}}let r=new Set(e.map(e=>e.name)),i=e.filter(e=>!e.parent||!r.has(e.parent)).map(e=>n(e.name,0)),a=i.reduce((e,t)=>e+t.value,0)||1;function o(e,t,n){e.x0=t,e.x1=n;let r=n-t,i=t;for(let t of e.children){let n=t.value/e.value*r;o(t,i,i+n),i+=n}}let s=0;for(let e of i){let t=e.value/a;o(e,s,s+t),s+=t}return i}function wY(e){let t=[];function n(e){t.push(e);for(let t of e.children)n(t)}for(let t of e)n(t);return t}function TY(e){let t=0;function n(e){e.depth>t&&(t=e.depth);for(let t of e.children)n(t)}for(let t of e)n(t);return t}function EY(e){return SY[e%SY.length]}function DY({nodes:e,direction:t=`bottomup`,backgroundToken:n=``,onPlotContextMenu:r}){let i=K(null),a=K(null),o=K(null),s=K(null),c=K(null),l=K(0),u=K(r);G(()=>{u.current=r},[r]);let d=K({nodes:e,direction:t});G(()=>{d.current={nodes:e,direction:t}},[e,t]);let f=St(()=>{let t=CY(e);return{roots:t,flat:wY(t),numRows:TY(t)+1}},[e]),p=K(f);G(()=>{p.current=f},[f]);function m(){if(s.current)return s.current;let e=o.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return s.current=n,n}function h(){let e=o.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function _(e,t,n,r,i){let a=bY.left+e.x0*t,o=(e.x1-e.x0)*t;return{x:a,y:i===`topdown`?bY.top+e.depth*xY:bY.top+n-(e.depth+1)*xY,w:o,h:xY-1}}function v(){let e=i.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;let{bg:a,muted:o}=m(),{nodes:s,direction:c}=d.current;if(r.fillStyle=a,r.fillRect(0,0,t,n),s.length===0){r.fillStyle=o,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{flat:l,numRows:u}=p.current,f=t-bY.left-bY.right,v=u*xY;for(let e of l){let t=_(e,f,v,u,c);if(!(t.w<1)&&(r.fillStyle=EY(e.depth),r.fillRect(t.x,t.y,t.w,t.h),t.w>24)){r.fillStyle=`rgba(0,0,0,0.75)`,r.font=`${Math.min(11,xY-4)}px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`middle`;let n=e.name,i=Math.floor((t.w-4)/7),a=n.length>i?n.slice(0,i-1)+`…`:n;r.fillText(a,t.x+3,t.y+xY/2)}}}function y(){let e=a.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=c.current;if(!i)return;let{direction:o}=d.current,{roots:s,numRows:l}=p.current;if(s.length===0)return;let u=_(i,t-bY.left-bY.right,l*xY,l,o);r.strokeStyle=`rgba(255,255,255,0.9)`,r.lineWidth=2,r.strokeRect(u.x+1,u.y+1,u.w-2,u.h-2);let f=`${i.name} (${i.value.toLocaleString()})`;r.font=`11px ${Q.mono}`;let m=r.measureText(f).width,v=Math.max(4,Math.min(t-m-8,u.x+u.w/2-m/2)),y=u.y<30?u.y+xY+4:u.y-20;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(v-3,y-3,m+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(f,v,y)}let b=K(v);b.current=v;let x=K(null);x.current??=GH(()=>b.current(),()=>o.current);let S=()=>x.current.schedule(),C=()=>{RH(l.current),l.current=LH(y)};return W(()=>{x.current.now()}),W(()=>()=>x.current?.cancel(),[]),W(()=>{s.current=null,S()},[n]),G(()=>{let e=o.current;if(!e)return;let t=new UH(()=>{s.current=null,S(),C()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=a.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{direction:r}=d.current,{roots:i,flat:a,numRows:o}=p.current;if(i.length===0){c.current=null,C();return}let s=t.clientX-n.left,l=t.clientY-n.top,u=n.width-bY.left-bY.right,f=o*xY,m=null;for(let e of a){let t=_(e,u,f,o,r);if(s>=t.x&&s<=t.x+t.w&&l>=t.y&&l<=t.y+t.h){m=e;break}}c.current=m,C()},r=()=>{c.current=null,C()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:o,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:i,className:`chart-canvas`,role:`img`,"aria-label":`Flame graph`}),q(`canvas`,{ref:a,className:`chart-canvas chart-overlay`})]})}var OY={top:24,right:24,bottom:52,left:56},kY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`],AY=.8;function jY(e,t,n,r){let i,a,o;if(t)a=t.length,i=t.values,o=e=>String(e+1);else{let t=e??[];a=t.length,i=Array.from({length:n},(e,n)=>Float64Array.from(t,e=>e.values[n]??0)),o=e=>t[e].label}let s=0,c=0;if(r===`stacked`)for(let e=0;e<a;e++){let t=0,n=0;for(let r of i){let i=r[e];i>0?t+=i:i<0&&(n+=i)}t>c&&(c=t),n<s&&(s=n)}else for(let e of i)for(let t=0;t<a;t++){let n=e[t];n>c&&(c=n),n<s&&(s=n)}return c===s&&(c=s+1),{n:a,values:i,label:o,lo:s,hi:c}}function MY(e,t,n){let r=e.values.length,i=[],a=[],o=[],s=[],c=[],l=(e,t,n,r,l)=>{i.push(e),a.push(t),o.push(n),s.push(r),c.push(l)};if(e.n<=n)for(let n=0;n<e.n;n++)if(t===`grouped`){let t=.8/r;for(let i=0;i<r;i++){let r=e.values[i][n];r===r&&l(n-.4+i*t,n-.4+(i+1)*t-t*.05,0,r,i)}}else{let t=0,i=0;for(let a=0;a<r;a++){let r=e.values[a][n];r!==r||r===0||(r>0?(l(n-.4,n+.4,t,t+r,a),t+=r):(l(n-.4,n+.4,i,i+r,a),i+=r))}}else{let i=e.n/n,a=new Float64Array(r),o=new Float64Array(r);for(let s=0;s<n;s++){let n=Math.floor(s*i),c=Math.min(e.n,Math.floor((s+1)*i));if(!(c<=n)){a.fill(0),o.fill(0);for(let i=n;i<c;i++){let n=0,s=0;for(let c=0;c<r;c++){let r=e.values[c][i];r===r&&(t===`stacked`?r>0?(n+=r,n>o[c]&&(o[c]=n)):(s+=r,s<a[c]&&(a[c]=s)):(r>o[c]&&(o[c]=r),r<a[c]&&(a[c]=r)))}}for(let e=t===`stacked`?r-1:0;t===`stacked`?e>=0:e<r;t===`stacked`?e--:e++)(o[e]!==0||a[e]!==0)&&l(n-.5,c-.5,a[e],o[e],e)}}}return{x0:Float64Array.from(i),x1:Float64Array.from(a),y0:Float64Array.from(o),y1:Float64Array.from(s),k:Float64Array.from(c)}}function NY({groups:e,columns:t,seriesNames:n,colors:r,mode:i=`grouped`,horizontal:a=!1,valueRange:o,backgroundToken:s=``,onPlotContextMenu:c}){let l=FU(),u=K(null),d=K(null),f=K(null),p=K(null),m=K(null),h=K(null),g=K(0),_=K(c);G(()=>{_.current=c},[c]);let v=K(null),y=St(()=>{let r=[e,i,n.length,t?.length,...t?.values??[]],a=v.current;if(a&&a.key.length===r.length&&a.key.every((e,t)=>e===r[t]))return a.value;let o=jY(e,t,n.length,i);return v.current={key:r,value:o},o},[e,t,n.length,i]),b=K({bars:y,seriesNames:n,colors:r,mode:i,horizontal:a,valueRange:o});G(()=>{b.current={bars:y,seriesNames:n,colors:r,mode:i,horizontal:a,valueRange:o}},[y,n,r,i,a,o]);let x=K({plot:null,failed:!1,key:``,data:null,size:``});W(()=>()=>{x.current.plot?.dispose(),x.current.plot=null},[]);let S=K({bars:null,view:``});function C(){if(m.current)return m.current;let e=p.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return m.current=n,n}function w(){let e=p.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function T(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function E(e){let t=b.current.colors??[];return Array.from({length:e},(e,n)=>t[n]??kY[n%kY.length])}function D(e,t){let{bars:n,valueRange:r}=b.current,i=n.lo,a=n.hi;r?.min!==void 0&&Number.isFinite(r.min)&&(i=r.min),r?.max!==void 0&&Number.isFinite(r.max)&&(a=r.max);let o=jG(OY,e,t),{top:s,right:c,bottom:l,left:u}=o;return{lo:i,hi:a,top:s,left:u,plotW:e-u-c,plotH:t-s-l,tiny:o.tiny}}function O(e,t){let n=x.current;if(!n.plot&&!n.failed&&d.current&&(n.plot=dH(d.current,vq),n.failed=!n.plot),!n.plot||!d.current)return null;let r=Math.min(2,window.devicePixelRatio||1),i=`${e}x${t}@${r}`;return n.size!==i&&(n.plot.resize(e,t,r),d.current.style.width=`${e}px`,d.current.style.height=`${t}px`,n.size=i),n.plot}function k(){let e=u.current;if(!e)return;let{w:t,h:n}=w(),r=T(e,t,n);if(!r)return;let{bg:i,muted:a,grid:o}=C(),{bars:s,seriesNames:c,mode:d,horizontal:f}=b.current;r.fillStyle=i,r.fillRect(0,0,t,n);let m=O(t,n);if(s.n===0||c.length===0){m?.keep([]),m?.render(),r.fillStyle=a,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{lo:h,hi:g,top:_,left:v,plotW:y,plotH:k,tiny:A}=D(t,n),j=E(c.length),M=f?k:y,N=e=>f?v+(e-h)/(g-h)*y:_+k-(e-h)/(g-h)*k,P=e=>(f?_:v)+(e+.5)/s.n*M;l({left:v,top:_,width:y,height:k,...f?{x:{v0:h,v1:g}}:{y:{v0:h,v1:g}}}),r.strokeStyle=o,r.lineWidth=1;for(let e=0;e<=5;e++){let t=h+e/5*(g-h),n=N(t);r.beginPath(),f?(r.moveTo(n,_),r.lineTo(n,_+k)):(r.moveTo(v,n),r.lineTo(v+y,n)),r.stroke(),r.fillStyle=a,r.font=`9px ${Q.mono}`,!A&&(f?(r.textAlign=`center`,r.textBaseline=`top`,r.fillText(Vz(t,(g-h)/5),n,_+k+4)):(r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(Vz(t,(g-h)/5),v-4,n)))}let F=`${h}|${g}|${f}`;(S.current.bars!==s||S.current.view!==F)&&(S.current={bars:s,view:F},BH(p.current));let I=Math.min(2,window.devicePixelRatio||1),L=Math.max(1,Math.round(M*I)),R=j.map(e=>{let t=qV(e);return[t[0],t[1],t[2],AY]}),z={left:v,top:_,width:y,height:k};if(m){let e=`${d}|${f}|${L}|${j.join(`,`)}`;if(x.current.key!==e||x.current.data!==s){let t=MY(s,d,L);f?m.setRects(`bars`,t.y0,t.y1,t.x0,t.x1,R,t.k):m.setRects(`bars`,t.x0,t.x1,t.y0,t.y1,R,t.k),m.keep([`bars`]),x.current.key=e,x.current.data=s}f?m.setView(h,g,s.n-.5,-.5,z):m.setView(-.5,s.n-.5,h,g,z),m.render()}else{let e=MY(s,d,L);r.globalAlpha=AY;for(let t=0;t<e.x0.length;t++){r.fillStyle=j[e.k[t]];let n=P(e.x0[t]-.5),i=P(e.x1[t]-.5),a=N(e.y0[t]),o=N(e.y1[t]);f?r.fillRect(Math.min(a,o),n,Math.max(1,Math.abs(o-a)),Math.max(1,i-n)):r.fillRect(n,Math.min(a,o),Math.max(1,i-n),Math.max(1,Math.abs(o-a)))}r.globalAlpha=1}if(h<0&&g>0){let e=N(0);r.strokeStyle=a,r.lineWidth=1.5,r.beginPath(),f?(r.moveTo(e,_),r.lineTo(e,_+k)):(r.moveTo(v,e),r.lineTo(v+y,e)),r.stroke()}r.fillStyle=a,r.font=`9px ${Q.mono}`;let B=Math.max(1,Math.ceil(s.n/Math.max(1,Math.floor(M/(f?14:48)))));for(let e=0;e<(A?0:s.n);e+=B){let t=P(e),n=s.label(e),i=n.length>14?n.slice(0,13)+`…`:n;f?(r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(i,v-4,t)):(r.textAlign=`center`,r.textBaseline=`top`,r.fillText(i,t,_+k+4))}if(c.length>1&&!A){let e=f?_-14:_+k+32,t=v;r.font=`9px ${Q.mono}`,r.textBaseline=`top`;for(let n=0;n<c.length&&(r.fillStyle=j[n],r.fillRect(t,e,10,8),r.fillStyle=a,r.textAlign=`left`,r.fillText(c[n],t+13,e),t+=r.measureText(c[n]).width+26,!(t>v+y-30));n++);}}function A(){let e=f.current;if(!e)return;let{w:t,h:n}=w(),r=T(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=h.current,{bars:a,seriesNames:o,horizontal:s}=b.current;if(i===null||i>=a.n)return;let{top:c,left:l,plotW:u,plotH:d}=D(t,n),p=s?d:u,m=(s?c:l)+(i+.5)/a.n*p,g=Math.max(1,p/a.n);r.fillStyle=`rgba(255,255,255,0.08)`,s?r.fillRect(l,m-g/2,u,g):r.fillRect(m-g/2,c,g,d);let _=a.values.map((e,t)=>`${o.length>1?o[t]+` `:``}${Hz(e[i])}`).join(` `),v=`${a.label(i)}: ${_}`;r.font=`11px ${Q.mono}`;let y=r.measureText(v).width,x=s?l+u/2:m,S=s?m:c+d/2,C=Math.max(4,Math.min(t-y-8,x-y/2)),E=S-28<c?S+10:S-24;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(C-3,E-3,y+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(v,C,E)}let j=K(k);j.current=k;let M=K(null);M.current??=GH(()=>j.current(),()=>p.current);let N=()=>{g.current||=LH(()=>{g.current=0,A()})};return W(()=>{M.current.now()},[y,n,r,i,a,o]),W(()=>()=>{M.current?.cancel(),RH(g.current)},[]),W(()=>{m.current=null,M.current.schedule()},[s]),G(()=>{let e=p.current;if(!e)return;let t=new UH(()=>{m.current=null,M.current.schedule(),N()});return t.observe(e),()=>t.disconnect()},[]),G(()=>{let e=f.current;if(!e)return;let t=e=>{e.preventDefault(),_.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{bars:r,horizontal:i}=b.current,{w:a,h:o}=w(),{top:s,left:c,plotW:l,plotH:u}=D(a,o),d=i?t.clientY-n.top-s:t.clientX-n.left-c,f=i?u:l,p=d>=0&&d<f&&r.n>0?Math.min(r.n-1,Math.floor(d/f*r.n)):null;p!==h.current&&(h.current=p,N())},r=()=>{h.current=null,N()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:p,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:u,className:`chart-canvas`,role:`img`,"aria-label":`Bar chart`}),q(`canvas`,{ref:d,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:f,className:`chart-canvas chart-overlay`})]})}var PY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function FY(e,t){if(!t)return PY[e%PY.length];if(e===0)return t;let n=PY.filter(e=>e.toLowerCase()!==t.toLowerCase());return n[(e-1)%n.length]}var IY={top:36,right:36,bottom:36,left:36};function LY({axes:e,series:t,fill:n=!0,color:r,backgroundToken:i=``,onPlotContextMenu:a}){let o=K(null),s=K(null),c=K(null),l=K(null),u=K(a);G(()=>{u.current=a},[a]);let d=K({axes:e,series:t,fill:n,color:r});G(()=>{d.current={axes:e,series:t,fill:n,color:r}},[e,t,n,r]);function f(){if(l.current)return l.current;let e=c.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return l.current=n,n}function p(){let e=c.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function m(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function h(){let e=o.current;if(!e)return;let{w:t,h:n}=p(),r=m(e,t,n);if(!r)return;let{bg:i,muted:a,grid:s}=f(),{axes:c,series:l,fill:u}=d.current;if(r.fillStyle=i,r.fillRect(0,0,t,n),c.length<3||l.length===0){r.fillStyle=a,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`Select ≥ 3 axes`,IY.left+8,IY.top+8);return}let h=c.length,g=t/2,_=n/2,v=Math.min(t-IY.left-IY.right,n-IY.top-IY.bottom)/2,y=c.map((e,t)=>{let n=0;for(let e of l){let r=e.values[t]??0;r>n&&(n=r)}return n||1});function b(e){return Math.PI*2*e/h-Math.PI/2}function x(e,t){let n=b(e);return{x:g+Math.cos(n)*v*t,y:_+Math.sin(n)*v*t}}for(let e=1;e<=4;e++){let t=e/4;r.beginPath();for(let e=0;e<h;e++){let n=x(e,t);e===0?r.moveTo(n.x,n.y):r.lineTo(n.x,n.y)}r.closePath(),r.strokeStyle=s,r.lineWidth=1,r.stroke()}r.strokeStyle=a,r.lineWidth=1;for(let e=0;e<h;e++){let t=x(e,1);r.beginPath(),r.moveTo(g,_),r.lineTo(t.x,t.y),r.stroke(),r.fillStyle=a,r.font=`10px ${Q.mono}`;let n=b(e),i=x(e,1+10/v);r.textAlign=Math.abs(Math.cos(n))<.1?`center`:Math.cos(n)<0?`right`:`left`,r.textBaseline=Math.abs(Math.sin(n))<.1?`middle`:Math.sin(n)<0?`bottom`:`top`;let o=c[e].length>12?c[e].slice(0,11)+`…`:c[e];r.fillText(o,i.x,i.y)}for(let e=0;e<l.length;e++){let t=l[e],n=FY(e,d.current.color);r.beginPath();for(let e=0;e<h;e++){let n=Math.max(0,Math.min(1,(t.values[e]??0)/y[e])),i=x(e,n);e===0?r.moveTo(i.x,i.y):r.lineTo(i.x,i.y)}r.closePath(),u&&(r.fillStyle=n,r.globalAlpha=.15,r.fill()),r.globalAlpha=1,r.strokeStyle=n,r.lineWidth=1,r.stroke();for(let e=0;e<h;e++){let i=Math.max(0,Math.min(1,(t.values[e]??0)/y[e])),a=x(e,i);r.beginPath(),r.arc(a.x,a.y,3,0,Math.PI*2),r.fillStyle=n,r.globalAlpha=.9,r.fill()}r.globalAlpha=1}if(l.length>1){let e=IY.left,i=n-IY.bottom-10;r.font=`9px ${Q.mono}`,r.textBaseline=`top`;for(let n=0;n<l.length&&(r.fillStyle=FY(n,d.current.color),r.fillRect(e,i,10,8),r.fillStyle=a,r.textAlign=`left`,r.fillText(l[n].name,e+13,i),e+=r.measureText(l[n].name).width+26,!(e>t-IY.right-30));n++);}}let g=K(h);g.current=h;let _=K(null);_.current??=GH(()=>g.current(),()=>c.current);let v=()=>_.current.schedule();return W(()=>{_.current.now()}),W(()=>()=>_.current?.cancel(),[]),W(()=>{l.current=null,v()},[i]),G(()=>{let e=c.current;if(!e)return;let t=new UH(()=>{l.current=null,v()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=s.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>{e.removeEventListener(`contextmenu`,t)}},[]),Ot(`div`,{ref:c,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Radar chart`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`})]})}var RY={top:16,right:16,bottom:40,left:52},zY=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function BY(e,t){let n=e.length>0&&e.every(t=>t.x===e[0].x||t.x.length===e[0].x.length),r=t&&n,i=e.map(e=>e.x),a=[],o=[],s=null;for(let t of e){if(!r){a.push(t.y),o.push(null);continue}let e=t.x.length,n=new Float64Array(e);for(let r=0;r<e;r++){let e=t.y[r];n[r]=(s?s[r]:0)+(e>0?e:0)}a.push(n),o.push(s??null),s=n}let c=1/0,l=-1/0,u=0,d=0;for(let e of i)for(let t=0;t<e.length;t++){let n=e[t];n<c&&(c=n),n>l&&(l=n)}for(let e of a)for(let t=0;t<e.length;t++){let n=e[t];n<u&&(u=n),n>d&&(d=n)}return Number.isFinite(c)||(c=0,l=1),{x:i,lo:o,hi:a,ascending:i.map(e=>Dq(e)),xLo:c,xHi:l,yLo:u,yHi:d}}function VY({series:e,stacked:t=!1,yRange:n,backgroundToken:r=``,onPlotContextMenu:i}){let a=FU(),o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(null),f=K(0),p=K(i);G(()=>{p.current=i},[i]);let m=K(null),h=St(()=>{let n=m.current;if(n&&n.stacked===t&&n.series.length===e.length&&n.series.every((t,n)=>t.x===e[n].x&&t.y===e[n].y&&t.name===e[n].name))return n.value;let r=BY(e,t);return m.current={series:e,stacked:t,value:r},r},[e,t]),g=K({series:e,prepared:h,yRange:n});G(()=>{g.current={series:e,prepared:h,yRange:n}},[e,h,n]);let _=K({plot:null,failed:!1,key:``,size:``});W(()=>()=>{_.current.plot?.dispose(),_.current.plot=null},[]);let v=K({prepared:null,view:``});function y(){if(u.current)return u.current;let e=l.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return u.current=n,n}function b(){let e=l.current;return{w:Math.max(1,e?.clientWidth||600),h:Math.max(1,e?.clientHeight||300)}}function x(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function S(e,t){let n=(e.xHi-e.xLo)*.01||.5,r=e.yLo,i=e.yHi;return i===r&&(i=r+1),i+=(i-r)*.05,t?.min!==void 0&&Number.isFinite(t.min)&&(r=t.min),t?.max!==void 0&&Number.isFinite(t.max)&&(i=t.max),{xLo:e.xLo-n,xHi:e.xHi+n,yLo:r,yHi:i}}function C(e,t,n,r,i){let a=e.x[t],o=e.hi[t],s=e.lo[t];if(!e.ascending[t]||a.length<=2*i)return{x:a,hi:o,lo:s??new Float64Array(a.length)};let c=wq(a,o,n,r,i);return{x:Eq(a,c),hi:Eq(o,c),lo:s?Eq(s,c):new Float64Array(c.length)}}function w(){let e=o.current;if(!e)return;let{w:n,h:r}=b(),i=x(e,n,r);if(!i)return;let{bg:s,muted:c,grid:u}=y(),{series:d,prepared:f,yRange:p}=g.current;i.fillStyle=s,i.fillRect(0,0,n,r);let m=_.current.plot;if(d.length===0){m?.keep([]),m?.render(),i.fillStyle=c,i.font=`13px ${Q.sans}`,i.textAlign=`left`,i.textBaseline=`top`,UV(i);return}let h=jG(RY,n,r),{top:w,right:D,bottom:O,left:k}=h,A=n-k-D,j=r-w-O,{xLo:M,xHi:N,yLo:P,yHi:F}=S(f,p),I=e=>k+(e-M)/(N-M)*A,L=e=>w+j-(e-P)/(F-P)*j;a({left:k,top:w,width:A,height:j,x:{v0:M,v1:N},y:{v0:P,v1:F}}),i.strokeStyle=u,i.lineWidth=1;for(let e=0;e<=5;e++){let t=P+e/5*(F-P),n=L(t);i.beginPath(),i.moveTo(k,n),i.lineTo(k+A,n),i.stroke(),i.fillStyle=c,i.font=`9px ${Q.mono}`,i.textAlign=`right`,i.textBaseline=`middle`,h.tiny||i.fillText(Vz(t,(F-P)/5),k-4,n)}let R=Math.min(8,f.x[0]?.length??5);for(let e=0;e<=R;e++){let t=M+e/R*(N-M),n=I(t);i.beginPath(),i.moveTo(n,w),i.lineTo(n,w+j),i.stroke(),i.fillStyle=c,i.font=`9px ${Q.mono}`,i.textAlign=`center`,i.textBaseline=`top`,h.tiny||i.fillText(Vz(t,(N-M)/R),n,w+j+4)}let z=`${M}|${N}|${P}|${F}`;(v.current.prepared!==f||v.current.view!==z)&&(v.current={prepared:f,view:z},BH(l.current));let B=E(n,r),V=Math.min(2,window.devicePixelRatio||1),ee=Math.max(1,Math.round(A*V)),te=d.map((e,t)=>qV(zY[t%zY.length]));if(B){let e=`${M}|${N}|${ee}`;if(_.current.key!==e||T.current!==f){let n=[];for(let e=0;e<d.length;e++){let r=C(f,e,M,N,ee),i=te[e],a=[i[0],i[1],i[2],f.lo[e]||t?.7:.25];B.setBands(`b${e}`,r.x,r.lo,r.hi,a),B.setLine(`l${e}`,r.x,r.hi,i,1),n.push(`b${e}`,`l${e}`)}B.keep(n),_.current.key=e,T.current=f}B.setView(M,N,P,F,{left:k,top:w,width:A,height:j}),B.render()}else for(let e=0;e<d.length;e++){let n=C(f,e,M,N,ee),r=zY[e%zY.length];i.save(),i.beginPath(),i.rect(k,w,A,j),i.clip(),i.beginPath();for(let e=0;e<n.x.length;e++){let t=I(n.x[e]);e===0?i.moveTo(t,L(n.lo[e])):i.lineTo(t,L(n.lo[e]))}for(let e=n.x.length-1;e>=0;e--)i.lineTo(I(n.x[e]),L(n.hi[e]));i.closePath(),i.fillStyle=r,i.globalAlpha=f.lo[e]||t?.7:.25,i.fill(),i.beginPath();for(let e=0;e<n.x.length;e++){let t=I(n.x[e]),r=L(n.hi[e]);e===0?i.moveTo(t,r):i.lineTo(t,r)}i.globalAlpha=1,i.strokeStyle=r,i.lineWidth=1,i.stroke(),i.restore()}if(d.length>1&&!h.tiny){let e=k,t=w+j+24;i.font=`9px ${Q.mono}`,i.textBaseline=`top`;for(let n=0;n<d.length&&(i.fillStyle=zY[n%zY.length],i.fillRect(e,t,10,8),i.fillStyle=c,i.textAlign=`left`,i.fillText(d[n].name,e+13,t),e+=i.measureText(d[n].name).width+26,!(e>k+A-30));n++);}}let T=K(null);function E(e,t){let n=_.current;if(!n.plot&&!n.failed&&s.current&&(n.plot=dH(s.current,vq),n.failed=!n.plot),!n.plot||!s.current)return null;let r=Math.min(2,window.devicePixelRatio||1),i=`${e}x${t}@${r}`;return n.size!==i&&(n.plot.resize(e,t,r),s.current.style.width=`${e}px`,s.current.style.height=`${t}px`,n.size=i),n.plot}function D(){let e=c.current;if(!e)return;let{w:t,h:n}=b(),r=x(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=d.current;if(i===null)return;let{prepared:a,yRange:o}=g.current,{top:s,right:l,left:u,bottom:f}=jG(RY,t,n),p=n-s-f;r.strokeStyle=`rgba(255,255,255,0.4)`,r.lineWidth=1,r.setLineDash([4,4]),r.beginPath(),r.moveTo(i,s),r.lineTo(i,s+p),r.stroke(),r.setLineDash([]);let{xLo:m,xHi:h}=S(a,o),_=t-u-l,v=`x=${Hz(m+(i-u)/_*(h-m))}`;r.font=`11px ${Q.mono}`;let y=r.measureText(v).width,C=Math.max(4,Math.min(t-y-8,i-y/2));r.fillStyle=`rgba(0,0,0,0.7)`,r.fillRect(C-3,s-3,y+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(v,C,s)}let O=K(w);O.current=w;let k=K(null);k.current??=GH(()=>O.current(),()=>l.current);let A=()=>{f.current||=LH(()=>{f.current=0,D()})};return W(()=>{k.current.now()},[e,h,n]),W(()=>()=>{k.current?.cancel(),RH(f.current)},[]),W(()=>{u.current=null,k.current.schedule()},[r]),G(()=>{let e=l.current;if(!e)return;let t=new UH(()=>{u.current=null,k.current.schedule(),A()});return t.observe(e),()=>t.disconnect()},[]),G(()=>{let e=c.current;if(!e)return;let t=e=>{e.preventDefault(),p.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect();d.current=t.clientX-n.left,A()},r=()=>{d.current=null,A()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:l,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Area chart`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:c,className:`chart-canvas chart-overlay`})]})}var HY={top:16,right:16,bottom:40,left:52},UY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function WY({series:e,complement:t=!1,logX:n=!1,backgroundToken:r=``,onPlotContextMenu:i}){let a=FU(),o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(0),f=K(i);G(()=>{f.current=i},[i]);let p=K({series:e,complement:t,logX:n});G(()=>{p.current={series:e,complement:t,logX:n}},[e,t,n]);let m=St(()=>{let t=e.map(e=>Float64Array.from(e.values).sort()),n=1/0,r=-1/0;for(let e of t)e.length&&(n=Math.min(n,e[0]),r=Math.max(r,e[e.length-1]));return{all:t,xLo:n,xHi:r}},[e]),h=K(m);G(()=>{h.current=m},[m]);function g(){if(l.current)return l.current;let e=c.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return l.current=n,n}function _(){let e=c.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function v(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function y(){let e=o.current;if(!e)return;let{w:t,h:n}=_(),r=v(e,t,n);if(!r)return;let{bg:i,muted:s,grid:c}=g(),{series:l,complement:u,logX:d}=p.current;if(r.fillStyle=i,r.fillRect(0,0,t,n),l.length===0){r.fillStyle=s,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{top:f,right:m,bottom:y,left:b}=HY,x=t-b-m,S=n-f-y,{xLo:C,xHi:w}=h.current;Number.isFinite(C)||(C=0,w=1);let T=e=>Math.log10(Math.max(1e-10,e)),E=d?T(C):C,D=d?T(w):w,O=e=>b+((d?T(e):e)-E)/(D-E||1)*x,k=e=>f+S-e*S;a({left:b,top:f,width:x,height:S,x:{v0:C,v1:w,log:d}});for(let e=0;e<=5;e++){let t=e/5,n=k(t);r.strokeStyle=c,r.lineWidth=1,r.beginPath(),r.moveTo(b,n),r.lineTo(b+x,n),r.stroke(),r.fillStyle=s,r.font=`9px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(String(t.toFixed(2)),b-4,n)}for(let e=0;e<=6;e++){let t=C+e/6*(w-C),n=O(t);r.strokeStyle=c,r.lineWidth=1,r.beginPath(),r.moveTo(n,f),r.lineTo(n,f+S),r.stroke(),r.fillStyle=s,r.font=`9px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`,r.fillText(Vz(t,(w-C)/6),n,f+S+4)}for(let e=0;e<l.length;e++){let t=h.current.all[e],n=t?.length??0;if(n===0)continue;let i=e=>k(u?1-(e+1)/n:(e+1)/n),a=O(t[0]),o=k(+!!u);r.beginPath(),r.moveTo(a,o);for(let e=0;e<n;e++){if(e+1<n&&t[e+1]===t[e])continue;let s=O(t[e]),c=i(e);if(Math.abs(s-a)<.5){o=c;continue}r.lineTo(a,o),r.lineTo(s,o),a=s,o=c}r.lineTo(a,o),r.strokeStyle=UY[e%UY.length],r.lineWidth=1,r.stroke()}if(l.length>1){let e=b,t=f+S+24;r.font=`9px ${Q.mono}`,r.textBaseline=`top`;for(let n=0;n<l.length&&(r.fillStyle=UY[n%UY.length],r.fillRect(e,t,16,2),r.fillStyle=s,r.textAlign=`left`,r.fillText(l[n].name,e+20,t-3),e+=r.measureText(l[n].name).width+30,!(e>b+x-30));n++);}r.save(),r.translate(12,f+S/2),r.rotate(-Math.PI/2),r.fillStyle=s,r.font=`9px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(u?`CCDF`:`CDF`,0,0),r.restore()}function b(){let e=s.current;if(!e)return;let{w:t,h:n}=_(),r=v(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=u.current;if(i===null)return;let{top:a,left:o,right:c}=HY,l=n-a-HY.bottom,d=t-o-c;r.strokeStyle=`rgba(255,255,255,0.4)`,r.lineWidth=1,r.setLineDash([4,4]),r.beginPath(),r.moveTo(i,a),r.lineTo(i,a+l),r.stroke(),r.setLineDash([]);let{xLo:f,xHi:p}=h.current;if(!Number.isFinite(f))return;let m=Hz(f+(i-o)/d*(p-f));r.font=`11px ${Q.mono}`;let g=r.measureText(m).width,y=Math.max(4,Math.min(t-g-8,i-g/2));r.fillStyle=`rgba(0,0,0,0.7)`,r.fillRect(y-3,a+l+2,g+6,16),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(m,y,a+l+4)}let x=K(y);x.current=y;let S=K(null);S.current??=GH(()=>x.current(),()=>c.current);let C=()=>S.current.schedule(),w=()=>{RH(d.current),d.current=LH(b)};return W(()=>{S.current.now()}),W(()=>()=>S.current?.cancel(),[]),W(()=>{l.current=null,C()},[r]),G(()=>{let e=c.current;if(!e)return;let t=new UH(()=>{l.current=null,C(),w()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=s.current;if(!e)return;let t=e=>{e.preventDefault(),f.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect();u.current=t.clientX-n.left,w()},r=()=>{u.current=null,w()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:c,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`CDF chart`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`})]})}var GY={top:16,right:40,bottom:40,left:52},KY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function qY(e){return[Math.round(255*Math.min(1,Math.max(0,3.5*e-.5))),Math.round(255*Math.min(1,Math.max(0,e<.5?2*e:2-2*e))),Math.round(255*Math.min(1,Math.max(0,1.5-3.5*e)))]}function JY(e){let[t,n,r]=qY(e);return`rgb(${t},${n},${r})`}var YY=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++)e.set([...qY(t/255),255],t*4);return e})(),XY=()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++){let[n,r,i]=MK(KY[t%KY.length],1);e.set([n*255,r*255,i*255,255],t*4)}return e};function ZY(e,t,n){let r=e.length,i=1/0,a=-1/0,o=1/0,s=-1/0,c=1/0,l=-1/0;for(let t=0;t<r;t++){let n=e.x[t],r=e.y[t],u=e.size[t];n<i&&(i=n),n>a&&(a=n),r<o&&(o=r),r>s&&(s=r),u<c&&(c=u),u>l&&(l=u)}let u=Number.isFinite(i)?(()=>{let e=(a-i)*.1||1,t=(s-o)*.1||1;return{xLo:i-e,xHi:a+e,yLo:o-t,yHi:s+t,sLo:c,sHi:l}})():{xLo:-1,xHi:1,yLo:-1,yHi:1,sLo:1,sHi:1},d=u.sHi-u.sLo||1,f=new Float32Array(r);for(let t=0;t<r;t++)f[t]=3+(e.size[t]-u.sLo)/d*(n-3);let p=0,m=1,h=null,g=`single`;if(t&&e.colorValue){let t=e.colorValue,n=1/0,i=-1/0;for(let e=0;e<r;e++)t[e]<n&&(n=t[e]),t[e]>i&&(i=t[e]);Number.isFinite(n)&&(p=n,m=i),h=new Float32Array(r);for(let e=0;e<r;e++)h[e]=t[e]===t[e]?Math.max(0,Math.min(1,(t[e]-p)/(m-p||1))):0;g=`colormap`}else !t&&e.colorIndex&&(h=Float32Array.from(e.colorIndex,e=>e>=0?e%256:0),g=`dataset`);let _=Uint32Array.from({length:r},(e,t)=>t).sort((e,t)=>(f[t]||0)-(f[e]||0)),v=e=>{let t=new Float64Array(r);for(let n=0;n<r;n++)t[n]=e[_[n]];return t};return{ext:u,radius:f,key:h,mode:g,colorLo:p,colorHi:m,drawn:{x:v(e.x),y:v(e.y),r:v(f),k:h?v(h):void 0}}}function QY({points:e,color:t=`#64748b`,colorByNumeric:n=!1,maxRadius:r=24,backgroundToken:i=``,onPlotContextMenu:a}){let o=FU(),s=K(null),c=K(null),l=K(null),u=K(null),d=K(null),f=K(null),p=K(0),m=K(a);G(()=>{m.current=a},[a]);let h=St(()=>ZY(e,n,r),[e,n,r]),g=K({points:e,color:t,colorByNumeric:n,maxRadius:r,model:h});G(()=>{g.current={points:e,color:t,colorByNumeric:n,maxRadius:r,model:h}},[e,t,n,r,h]);let _=K({r:null,failed:!1,size:``,model:null,style:``});W(()=>()=>{_.current.r?.dispose(),_.current.r=null},[]);function v(){if(d.current)return d.current;let e=u.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return d.current=n,n}function y(){let e=u.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function b(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function x(e,t){let{xLo:n,xHi:r,yLo:i,yHi:a}=g.current.model.ext,{top:s,right:c,bottom:l,left:u}=GY,d=e-u-c,f=t-s-l;return o({left:u,top:s,width:d,height:f,x:{v0:n,v1:r},y:{v0:i,v1:a}}),{plotW:d,plotH:f,xToPx:e=>u+(e-n)/(r-n)*d,yToPx:e=>s+(1-(e-i)/(a-i))*f}}function S(e,t){let n=_.current;!n.r&&!n.failed&&c.current&&(n.r=dH(c.current,kG),n.failed=!n.r);let r=n.r;if(!r||!c.current)return null;let i=Math.min(2,window.devicePixelRatio||1),a=`${e}x${t}@${i}`;n.size!==a&&(r.resize(e,t,i),c.current.style.width=`${e}px`,c.current.style.height=`${t}px`,n.size=a);let{model:o,color:s}=g.current;n.model!==o&&(r.setData(o.drawn.x,o.drawn.y,o.drawn.k,!1,o.drawn.r),n.model=o,BH(u.current));let l=`${o.mode}|${s}`;return n.style!==l&&(r.setStyle(o.mode===`single`?{kind:`single`,rgba:MK(s,1)}:{kind:o.mode,palette:o.mode===`colormap`?YY:XY()},3,.65),r.setDraw(!0,!1,0),n.style=l),r}function C(){let e=s.current;if(!e)return;let{w:t,h:n}=y(),r=b(e,t,n);if(!r)return;let{bg:i,muted:a,grid:o}=v(),{points:c,color:l,colorByNumeric:u,model:d}=g.current;r.fillStyle=i,r.fillRect(0,0,t,n);let f=S(t,n);if(c.length===0){f?.setData([],[]),_.current.model=null,f?.render(),r.fillStyle=a,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{xLo:p,xHi:m,yLo:h,yHi:C}=d.ext,{top:w,left:T}=GY,{plotW:E,plotH:D,xToPx:O,yToPx:k}=x(t,n);r.strokeStyle=o,r.lineWidth=1;for(let e=0;e<=5;e++){let t=p+e/5*(m-p),n=O(t);r.beginPath(),r.moveTo(n,w),r.lineTo(n,w+D),r.stroke(),r.fillStyle=a,r.font=`9px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`,r.fillText(Vz(t,(m-p)/5),n,w+D+4);let i=h+e/5*(C-h),o=k(i);r.beginPath(),r.moveTo(T,o),r.lineTo(T+E,o),r.stroke(),r.fillStyle=a,r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(Vz(i,(C-h)/5),T-4,o)}if(f)f.setView(p,m,h,C,{left:T,top:w,width:E,height:D}),f.render();else{let e=d.drawn;r.globalAlpha=.65;for(let t=0;t<e.x.length;t++){if(e.x[t]!==e.x[t]||e.y[t]!==e.y[t])continue;let n=e.k?.[t]??0;r.fillStyle=d.mode===`colormap`?JY(n):d.mode===`dataset`?KY[n%KY.length]:l,r.beginPath(),r.arc(O(e.x[t]),k(e.y[t]),e.r[t],0,Math.PI*2),r.fill()}r.globalAlpha=1}let A=c.colorLabels??[];if(!u&&A.length>0&&A.length<=10){let e=T,t=n-GY.bottom-10;r.font=`9px ${Q.mono}`,r.textBaseline=`top`;for(let n=0;n<A.length;n++){let i=A[n];if(r.fillStyle=KY[n%KY.length],r.beginPath(),r.arc(e+4,t+4,4,0,Math.PI*2),r.fill(),r.fillStyle=a,r.textAlign=`left`,r.fillText(i,e+10,t),e+=r.measureText(i).width+20,e>T+E-60)break}}}function w(){let e=l.current;if(!e)return;let{w:t,h:n}=y(),r=b(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=f.current;if(i===null)return;let{points:a,model:o}=g.current;if(i<0||i>=a.length)return;let{xToPx:s,yToPx:c}=x(t,n),u=o.radius[i],d=s(a.x[i]),p=c(a.y[i]);r.beginPath(),r.arc(d,p,u+2,0,Math.PI*2),r.strokeStyle=`rgba(255,255,255,0.9)`,r.lineWidth=2,r.stroke();let m=[],h=a.label?.(i);h&&m.push(h),m.push(`(${Hz(a.x[i])}, ${Hz(a.y[i])})`),m.push(`size=${Hz(a.size[i])}`);let _=a.colorIndex?.[i];_!==void 0&&_>=0&&a.colorLabels?m.push(a.colorLabels[_]):a.colorValue&&m.push(Hz(a.colorValue[i]));let v=m.join(` · `);r.font=`11px ${Q.mono}`;let S=r.measureText(v).width,C=Math.max(4,Math.min(t-S-8,d+u+4)),w=p-20<GY.top?p+u+4:p-20;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(C-3,w-3,S+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(v,C,w)}let T=K(C);T.current=C;let E=K(null);E.current??=GH(()=>T.current(),()=>u.current);let D=()=>E.current.schedule(),O=()=>{RH(p.current),p.current=LH(w)};return W(()=>{E.current.now()}),W(()=>()=>E.current?.cancel(),[]),W(()=>{d.current=null,D()},[i]),G(()=>{let e=u.current;if(!e)return;let t=new UH(()=>{d.current=null,D(),O()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=l.current;if(!e)return;let t=null,n=e=>{e.preventDefault(),m.current?.({clientX:e.clientX,clientY:e.clientY})},r=n=>{let r=e.getBoundingClientRect(),{points:i,maxRadius:a,model:o}=g.current,{w:s,h:c}=y(),{plotW:l,plotH:u,xToPx:d,yToPx:p}=x(s,c),m=e=>d(i.x[e])-GY.left,h=e=>p(i.y[e])-GY.top,_=a+6,v=`${s}|${c}|${_}`;(!t||t.model!==o||t.key!==v)&&(t={model:o,key:v,g:uY(i.length,l,u,_,m,h)}),f.current=dY(t.g,n.clientX-r.left-GY.left,n.clientY-r.top-GY.top,_,m,h,e=>o.radius[e]+6),O()},i=()=>{f.current=null,O()};return e.addEventListener(`contextmenu`,n),e.addEventListener(`mousemove`,r),e.addEventListener(`mouseleave`,i),()=>{e.removeEventListener(`contextmenu`,n),e.removeEventListener(`mousemove`,r),e.removeEventListener(`mouseleave`,i)}},[]),Ot(`div`,{ref:u,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:s,className:`chart-canvas`,role:`img`,"aria-label":`Bubble chart`}),q(`canvas`,{ref:c,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:l,className:`chart-canvas chart-overlay`})]})}var $Y={top:8,right:8,bottom:8,left:8},eX=[`#f97316`,`#38bdf8`,`#4ade80`,`#a78bfa`,`#fbbf24`,`#fb7185`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function tX(e){let t=new Map;for(let n of e){let e=n.parent??``;t.has(e)||t.set(e,[]),t.get(e).push(n)}function n(r,i){let a=(t.get(r)??[]).map(e=>n(e.name,i+1)),o=e.find(e=>e.name===r),s=a.reduce((e,t)=>e+t.value,0);return{name:r,value:o?Math.max(o.value,s):s,children:a,depth:i}}let r=new Set(e.map(e=>e.name));return e.filter(e=>!e.parent||!r.has(e.parent)).map(e=>n(e.name,0))}function nX(e,t,n,r,i,a){if(e.length===0||r<=0||i<=0||e.reduce((e,t)=>e+t.value,0)===0)return[];let o=[],s=[...e].sort((e,t)=>t.value-e.value),c=t,l=n,u=r,d=i;for(;s.length>0;){let e=u*d,t=s.reduce((e,t)=>e+t.value,0),n=e/t,r=[],i=1/0;for(let e=1;e<=s.length;e++){let a=s.slice(0,e),o=a.reduce((e,t)=>e+t.value,0)/t*(u<=d?u:d),c=0;for(let e of a){let t=e.value*n/o,r=Math.max(t/o,o/t);r>c&&(c=r)}if(c<i)i=c,r=a;else break}let f=r.reduce((e,t)=>e+t.value,0),p=u<=d,m=f/t*(p?u:d),h=0;for(let e of r){let t=e.value/f,n=p?u:t*u,r=p?t*d:d,i=p?c:c+h,s=p?l+h:l,g=p?m:n,_=p?r:m;if(o.push({node:e,x:i,y:s,w:g,h:_,depth:a}),e.children.length>0&&g>4&&_>4){let t=nX(e.children,i+1,s+1,g-2,_-2,a+1);for(let e of t)o.push(e)}h+=p?r:n}s=s.slice(r.length),p?(c+=m,u-=m):(l+=m,d-=m)}return o}function rX({nodes:e,backgroundToken:t=``,onPlotContextMenu:n}){let r=K(null),i=K(null),a=K(null),o=K(null),s=K([]),c=K(null),l=K(0),u=K(n);G(()=>{u.current=n},[n]);let d=K({nodes:e});G(()=>{d.current={nodes:e}},[e]);let f=St(()=>tX(e),[e]),p=K(f);G(()=>{p.current=f},[f]);function m(){if(o.current)return o.current;let e=a.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return o.current=n,n}function h(){let e=a.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function _(){let e=r.current;if(!e)return;let{w:t,h:n}=h(),i=g(e,t,n);if(!i)return;let{bg:a,muted:o}=m(),{nodes:l}=d.current;if(i.fillStyle=a,i.fillRect(0,0,t,n),l.length===0){i.fillStyle=o,i.font=`13px ${Q.sans}`,i.textAlign=`left`,i.textBaseline=`top`,UV(i);return}let u=p.current,f=t-$Y.left-$Y.right,_=n-$Y.top-$Y.bottom,v=nX(u,$Y.left,$Y.top,f,_,0);s.current=v;for(let e=0;e<v.length;e++){let{node:t,x:n,y:r,w:o,h:s,depth:l}=v[e];if(o<2||s<2)continue;let u=eX[l%eX.length],d=c.current===e;if(i.fillStyle=u,i.globalAlpha=d?.95:.75,i.fillRect(n,r,o,s),i.globalAlpha=1,i.strokeStyle=a,i.lineWidth=1,i.strokeRect(n,r,o,s),o>20&&s>14){i.fillStyle=`rgba(0,0,0,0.75)`,i.font=`${Math.min(11,s-4)}px ${Q.mono}`,i.textAlign=`left`,i.textBaseline=`top`;let e=Math.floor((o-4)/6),a=t.name.length>e?t.name.slice(0,e-1)+`…`:t.name;i.fillText(a,n+3,r+3)}}i.globalAlpha=1}function v(){let e=i.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let a=c.current;if(a===null)return;let o=s.current;if(a<0||a>=o.length)return;let{node:l,x:u,y:d,w:f,h:p}=o[a];r.strokeStyle=`rgba(255,255,255,0.9)`,r.lineWidth=2,r.strokeRect(u+1,d+1,f-2,p-2);let m=`${l.name}: ${l.value.toLocaleString()}`;r.font=`11px ${Q.mono}`;let _=r.measureText(m).width,v=Math.max(4,Math.min(t-_-8,u+f/2-_/2)),y=d<30?d+p+4:d-20;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(v-3,y-3,_+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(m,v,y)}let y=K(_);y.current=_;let b=K(null);b.current??=GH(()=>y.current(),()=>a.current);let x=()=>b.current.schedule(),S=()=>{RH(l.current),l.current=LH(v)};return W(()=>{b.current.now()}),W(()=>()=>b.current?.cancel(),[]),W(()=>{o.current=null,x()},[t]),G(()=>{let e=a.current;if(!e)return;let t=new UH(()=>{o.current=null,x(),S()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=i.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,a=s.current,o=null;for(let e=0;e<a.length;e++){let t=a[e];r>=t.x&&r<=t.x+t.w&&i>=t.y&&i<=t.y+t.h&&(o=e)}c.current=o,S()},r=()=>{c.current=null,S()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:a,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:r,className:`chart-canvas`,role:`img`,"aria-label":`Treemap`}),q(`canvas`,{ref:i,className:`chart-canvas chart-overlay`})]})}var iX={top:8,right:8,bottom:8,left:8},aX=14,oX=8,sX=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function cX(e,t,n,r){if(e.length===0||t.length===0)return{nodes:[],links:[]};let i=n-iX.left-iX.right,a=r-iX.top-iX.bottom,o=new Map;for(let t of e)o.set(t,0);let s=!0;for(;s;){s=!1;for(let e of t){let t=o.get(e.source)??0;(o.get(e.target)??0)<=t&&(o.set(e.target,t+1),s=!0)}}let c=Math.max(0,...Array.from(o.values())),l=e=>iX.left+e/Math.max(1,c)*(i-aX),u=new Map;for(let[e,t]of o)u.has(t)||u.set(t,[]),u.get(t).push(e);let d=new Map;for(let t of e)d.set(t,0);for(let e of t)d.set(e.source,(d.get(e.source)??0)+e.value),d.set(e.target,(d.get(e.target)??0)+e.value);let f=Math.max(1,...Array.from(d.values())),p=new Map;for(let[t,n]of u){let r=a-(n.length-1)*oX,i=0;for(let e of n)i+=Math.max(8,(d.get(e)??0)/f*r*.8);let o=iX.top+(a-i-(n.length-1)*oX)/2;for(let i=0;i<n.length;i++){let a=n[i],s=Math.max(8,(d.get(a)??0)/f*r*.8);p.set(a,{name:a,x:l(t),y:o,h:s,color:sX[e.indexOf(a)%sX.length]}),o+=s+oX}}let m=new Map,h=new Map;for(let[e,t]of p)m.set(e,t.y),h.set(e,t.y);let g=[];for(let e of t){let t=p.get(e.source),n=p.get(e.target);if(!t||!n)continue;let r=Math.max(1,e.value/f*t.h),i=m.get(e.source)??t.y,a=h.get(e.target)??n.y;m.set(e.source,i+r),h.set(e.target,a+r),g.push({sx:t.x+aX,sy:i+r/2,tx:n.x,ty:a+r/2,h:r,color:t.color,label:`${e.source} → ${e.target}: ${e.value.toLocaleString()}`})}return{nodes:Array.from(p.values()),links:g}}function lX({nodeNames:e,links:t,backgroundToken:n=``,onPlotContextMenu:r}){let i=K(null),a=K(null),o=K(null),s=K(null),c=K({nodes:[],links:[]}),l=K(null),u=K(0),d=K(r);G(()=>{d.current=r},[r]);let f=K({nodeNames:e,links:t});G(()=>{f.current={nodeNames:e,links:t}},[e,t]);function p(){if(s.current)return s.current;let e=o.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return s.current=n,n}function m(){let e=o.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function h(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function g(){let e=i.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;let{bg:a,muted:o}=p(),{nodeNames:s,links:u}=f.current;if(r.fillStyle=a,r.fillRect(0,0,t,n),s.length===0||u.length===0){r.fillStyle=o,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let d=cX(s,u,t,n);c.current=d;for(let e=0;e<d.links.length;e++){let t=d.links[e],n=l.current===e,i=(t.tx-t.sx)/2;r.beginPath(),r.moveTo(t.sx,t.sy-t.h/2),r.bezierCurveTo(t.sx+i,t.sy-t.h/2,t.tx-i,t.ty-t.h/2,t.tx,t.ty-t.h/2),r.lineTo(t.tx,t.ty+t.h/2),r.bezierCurveTo(t.tx-i,t.ty+t.h/2,t.sx+i,t.sy+t.h/2,t.sx,t.sy+t.h/2),r.closePath(),r.fillStyle=t.color,r.globalAlpha=n?.55:.3,r.fill()}r.globalAlpha=1;for(let e of d.nodes)r.fillStyle=e.color,r.globalAlpha=.9,r.fillRect(e.x,e.y,aX,e.h),r.globalAlpha=1,r.fillStyle=o,r.font=`9px ${Q.mono}`,r.textBaseline=`middle`,e.x>t/2?(r.textAlign=`right`,r.fillText(e.name,e.x-3,e.y+e.h/2)):(r.textAlign=`left`,r.fillText(e.name,e.x+aX+3,e.y+e.h/2));r.globalAlpha=1}function _(){let e=a.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=l.current;if(i===null)return;let o=c.current;if(i<0||i>=o.links.length)return;let s=o.links[i],u=s.label;r.font=`11px ${Q.mono}`;let d=r.measureText(u).width,f=Math.max(4,Math.min(t-d-8,(s.sx+s.tx)/2-d/2)),p=Math.max(4,(s.sy+s.ty)/2-10);r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(f-3,p-3,d+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(u,f,p)}let v=K(g);v.current=g;let y=K(null);y.current??=GH(()=>v.current(),()=>o.current);let b=()=>y.current.schedule(),x=()=>{RH(u.current),u.current=LH(_)};return W(()=>{y.current.now()}),W(()=>()=>y.current?.cancel(),[]),W(()=>{s.current=null,b()},[n]),G(()=>{let e=o.current;if(!e)return;let t=new UH(()=>{s.current=null,b(),x()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=a.current;if(!e)return;let t=e=>{e.preventDefault(),d.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,a=c.current,o=null;for(let e=0;e<a.links.length;e++){let t=a.links[e];if(r>=t.sx&&r<=t.tx&&Math.abs(i-(t.sy+t.ty)/2)<t.h/2+6){o=e;break}}l.current=o,x()},r=()=>{l.current=null,x()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:o,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:i,className:`chart-canvas`,role:`img`,"aria-label":`Sankey diagram`}),q(`canvas`,{ref:a,className:`chart-canvas chart-overlay`})]})}var uX={top:24,right:24,bottom:52,left:52};function dX({bins:e,color:t=`#38bdf8`,backgroundToken:n=``,onPlotContextMenu:r}){let i=K(null),a=K(null),o=K(null),s=K(null),c=K(null),l=K(0),u=K(r);G(()=>{u.current=r},[r]);let d=K({bins:e,color:t});G(()=>{d.current={bins:e,color:t}},[e,t]);function f(){if(s.current)return s.current;let e=o.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return s.current=n,n}function p(){let e=o.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function m(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function h(){let e=i.current;if(!e)return;let{w:t,h:n}=p(),r=m(e,t,n);if(!r)return;let{bg:a,muted:o,grid:s}=f(),{bins:l,color:u}=d.current;if(r.fillStyle=a,r.fillRect(0,0,t,n),l.length===0){r.fillStyle=o,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{top:h,right:g,bottom:_,left:v}=uX,y=t-v-g,b=n-h-_,x=e=>v+e*y,S=e=>h+(1-e)*b;for(let e=0;e<=5;e++){let t=e/5;r.strokeStyle=s,r.lineWidth=1,r.beginPath(),r.moveTo(v,S(t)),r.lineTo(v+y,S(t)),r.stroke(),r.beginPath(),r.moveTo(x(t),h),r.lineTo(x(t),h+b),r.stroke(),r.fillStyle=o,r.font=`9px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(t.toFixed(2),v-4,S(t)),r.textAlign=`center`,r.textBaseline=`top`,r.fillText(t.toFixed(2),x(t),h+b+4)}r.strokeStyle=o,r.lineWidth=1.5,r.setLineDash([6,4]),r.beginPath(),r.moveTo(x(0),S(0)),r.lineTo(x(1),S(1)),r.stroke(),r.setLineDash([]);let C=Math.max(1,...l.map(e=>e.count)),w=b*.15;for(let e of l){let t=Math.max(1,y/l.length*.7),n=x(e.center)-t/2,i=e.count/C*w;r.fillStyle=u,r.globalAlpha=.3,r.fillRect(n,h+b-i,t,i)}r.globalAlpha=1,r.beginPath();for(let e=0;e<l.length;e++){let t=x(l[e].center),n=S(l[e].actual);e===0?r.moveTo(t,n):r.lineTo(t,n)}r.strokeStyle=u,r.lineWidth=1,r.stroke();for(let e=0;e<l.length;e++){let t=c.current===e;r.beginPath(),r.arc(x(l[e].center),S(l[e].actual),t?6:4,0,Math.PI*2),r.fillStyle=u,r.globalAlpha=t?1:.85,r.fill()}r.globalAlpha=1,r.fillStyle=o,r.font=`10px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(`Predicted probability`,v+y/2,n-4),r.save(),r.translate(12,h+b/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(`Actual rate`,0,0),r.restore()}function g(){let e=a.current;if(!e)return;let{w:t,h:n}=p(),r=m(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=c.current;if(i===null)return;let{bins:o}=d.current;if(i<0||i>=o.length)return;let s=o[i],{top:l,left:u}=uX,f=t-u-uX.right,h=n-l-uX.bottom,g=u+s.center*f,_=l+(1-s.actual)*h,v=`pred=${s.center.toFixed(2)} actual=${s.actual.toFixed(3)} n=${s.count}`;r.font=`11px ${Q.mono}`;let y=r.measureText(v).width,b=Math.max(4,Math.min(t-y-8,g-y/2)),x=_-28<l?_+12:_-24;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(b-3,x-3,y+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(v,b,x)}let _=K(h);_.current=h;let v=K(null);v.current??=GH(()=>_.current(),()=>o.current);let y=()=>v.current.schedule(),b=()=>{RH(l.current),l.current=LH(g)};return W(()=>{v.current.now()}),W(()=>()=>v.current?.cancel(),[]),W(()=>{s.current=null,y()},[n]),G(()=>{let e=o.current;if(!e)return;let t=new UH(()=>{s.current=null,y(),b()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=a.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{bins:r}=d.current,{w:i}=p(),a=t.clientX-n.left,o=i-uX.left-uX.right,s=-1,l=20;for(let e=0;e<r.length;e++){let t=uX.left+r[e].center*o,n=Math.abs(a-t);n<l&&(l=n,s=e)}c.current=s>=0?s:null,b()},r=()=>{c.current=null,b()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:o,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:i,className:`chart-canvas`,role:`img`,"aria-label":`Calibration curve`}),q(`canvas`,{ref:a,className:`chart-canvas chart-overlay`})]})}var fX={top:24,right:24,bottom:48,left:52};function pX({points:e,color:t=`#a78bfa`,backgroundToken:n=``,onPlotContextMenu:r}){let i=FU(),a=K(null),o=K(null),s=K(null),c=K(null),l=K(null),u=K(0),d=K(r);G(()=>{d.current=r},[r]);let f=K({points:e,color:t});G(()=>{f.current={points:e,color:t}},[e,t]);function p(){if(c.current)return c.current;let e=s.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return c.current=n,n}function m(){let e=s.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function h(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function g(){let{points:e}=f.current,t=1/0,n=-1/0,r=1/0,i=-1/0;if(e.length>0&&(t=e.theoretical[0],n=e.theoretical[e.length-1],r=e.sample[0],i=e.sample[e.length-1]),!Number.isFinite(t))return{xLo:-3,xHi:3,yLo:-3,yHi:3};let a=(n-t)*.05||.5,o=(i-r)*.05||.5;return{xLo:t-a,xHi:n+a,yLo:r-o,yHi:i+o}}function _(){let e=a.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;let{bg:o,muted:s,grid:c}=p(),{points:u,color:d}=f.current;if(r.fillStyle=o,r.fillRect(0,0,t,n),u.length===0){r.fillStyle=s,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{xLo:_,xHi:v,yLo:y,yHi:b}=g(),{top:x,right:S,bottom:C,left:w}=fX,T=t-w-S,E=n-x-C,D=e=>w+(e-_)/(v-_)*T,O=e=>x+(1-(e-y)/(b-y))*E;i({left:w,top:x,width:T,height:E,x:{v0:_,v1:v}}),r.strokeStyle=c,r.lineWidth=1;for(let e=0;e<=5;e++){let t=_+e/5*(v-_),n=D(t);r.beginPath(),r.moveTo(n,x),r.lineTo(n,x+E),r.stroke(),r.fillStyle=s,r.font=`9px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`,r.fillText(Vz(t,(v-_)/5),n,x+E+4);let i=y+e/5*(b-y),a=O(i);r.beginPath(),r.moveTo(w,a),r.lineTo(w+T,a),r.stroke(),r.fillStyle=s,r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(Vz(i,(b-y)/5),w-4,a)}let k=Math.max(_,y),A=Math.min(v,b);k<A&&(r.strokeStyle=s,r.lineWidth=1.5,r.setLineDash([6,4]),r.beginPath(),r.moveTo(D(k),O(k)),r.lineTo(D(A),O(A)),r.stroke(),r.setLineDash([])),r.fillStyle=d,r.globalAlpha=.75;let j=NaN,M=NaN;for(let e=0;e<u.length;e++){let t=Math.round(D(u.theoretical[e])),n=Math.round(O(u.sample[e]));t===j&&n===M||(j=t,M=n,r.beginPath(),r.arc(t,n,3,0,Math.PI*2),r.fill())}let N=l.current;N!==null&&N<u.length&&(r.globalAlpha=1,r.beginPath(),r.arc(D(u.theoretical[N]),O(u.sample[N]),5,0,Math.PI*2),r.fill()),r.globalAlpha=1,r.fillStyle=s,r.font=`10px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(`Theoretical quantiles`,w+T/2,n-4),r.save(),r.translate(12,x+E/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(`Sample quantiles`,0,0),r.restore()}function v(){let e=o.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=l.current;if(i===null)return;let{points:a}=f.current;if(i<0||i>=a.length)return;let s={theoretical:a.theoretical[i],sample:a.sample[i]},{xLo:c,xHi:u,yLo:d,yHi:p}=g(),{top:_,left:v}=fX,y=t-v-fX.right,b=n-_-fX.bottom,x=v+(s.theoretical-c)/(u-c)*y,S=_+(1-(s.sample-d)/(p-d))*b;r.beginPath(),r.arc(x,S,6,0,Math.PI*2),r.strokeStyle=`rgba(255,255,255,0.9)`,r.lineWidth=2,r.stroke();let C=`(${Hz(s.theoretical)}, ${Hz(s.sample)})`;r.font=`11px ${Q.mono}`;let w=r.measureText(C).width,T=Math.max(4,Math.min(t-w-8,x+10)),E=S-20<_?S+10:S-20;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(T-3,E-3,w+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(C,T,E)}let y=K(_);y.current=_;let b=K(null);b.current??=GH(()=>y.current(),()=>s.current);let x=()=>b.current.schedule(),S=()=>{RH(u.current),u.current=LH(v)};return W(()=>{b.current.now()}),W(()=>()=>b.current?.cancel(),[]),W(()=>{c.current=null,x()},[n]),G(()=>{let e=s.current;if(!e)return;let t=new UH(()=>{c.current=null,x(),S()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=o.current;if(!e)return;let t=e=>{e.preventDefault(),d.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{points:r}=f.current,{w:i}=m(),{xLo:a,xHi:o,yLo:s,yHi:c}=g(),{top:u,left:d}=fX,p=i-d-fX.right,h=n.height-u-fX.bottom,_=t.clientX-n.left,v=t.clientY-n.top,y=e=>a+(e-d)/p*(o-a),b=e=>{let t=0,n=r.length;for(;t<n;){let i=t+n>>>1;r.theoretical[i]<e?t=i+1:n=i}return t},x=b(y(_-10)),C=Math.min(r.length,b(y(_+10))+1),w=-1,T=10**2;for(let e=x;e<C;e++){let t=d+(r.theoretical[e]-a)/(o-a)*p,n=u+(1-(r.sample[e]-s)/(c-s))*h,i=(_-t)**2+(v-n)**2;i<T&&(T=i,w=e)}l.current=w>=0?w:null,S()},r=()=>{l.current=null,S()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:s,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:a,className:`chart-canvas`,role:`img`,"aria-label":`Q-Q plot`}),q(`canvas`,{ref:o,className:`chart-canvas chart-overlay`})]})}var mX={top:8,right:16,bottom:40,left:120},hX=22,gX=3,_X=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function vX({tasks:e,backgroundToken:t=``,onPlotContextMenu:n}){let r=FU(),i=K(null),a=K(null),o=K(null),s=K(null),c=K(null),l=K(0),u=K(n);G(()=>{u.current=n},[n]);let d=K({tasks:e});G(()=>{d.current={tasks:e}},[e]);function f(){if(s.current)return s.current;let e=o.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return s.current=n,n}function p(){let e=o.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function m(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function h(){let e=i.current;if(!e)return;let{w:t,h:n}=p(),a=m(e,t,n);if(!a)return;let{bg:o,muted:s,grid:l}=f(),{tasks:u}=d.current;if(a.fillStyle=o,a.fillRect(0,0,t,n),u.length===0){a.fillStyle=s,a.font=`13px ${Q.sans}`,a.textAlign=`left`,a.textBaseline=`top`,UV(a);return}let h=1/0,g=-1/0;for(let e of u)e.start<h&&(h=e.start),e.end>g&&(g=e.end);Number.isFinite(h)||(h=0,g=1);let _=(g-h)*.02||1;h-=_,g+=_;let{top:v,right:y,bottom:b,left:x}=mX,S=t-x-y,C=e=>x+(e-h)/(g-h)*S;r({left:x,top:v,width:S,height:n-v-b,x:{v0:h,v1:g}});let w=new Map;for(let e of u){let t=e.group??e.label;w.has(t)||w.set(t,w.size)}let T=Math.min(8,Math.floor(S/60));a.strokeStyle=l,a.lineWidth=1;for(let e=0;e<=T;e++){let t=h+e/T*(g-h),n=C(t),r=u.length*(hX+gX)+v;a.beginPath(),a.moveTo(n,v),a.lineTo(n,r),a.stroke(),a.fillStyle=s,a.font=`9px ${Q.mono}`,a.textAlign=`center`,a.textBaseline=`top`,a.fillText(Vz(t,(g-h)/T),n,r+4)}for(let e=0;e<u.length;e++){let t=u[e],n=v+e*(hX+gX),r=_X[(w.get(t.group??t.label)??0)%_X.length],i=c.current===e,o=C(t.start),l=C(t.end),d=Math.max(2,l-o);a.fillStyle=r,a.globalAlpha=i?.95:.75,a.fillRect(o,n,d,hX-gX),a.globalAlpha=1,a.fillStyle=s,a.font=`9px ${Q.mono}`,a.textAlign=`right`,a.textBaseline=`middle`;let f=t.label.length>16?t.label.slice(0,15)+`…`:t.label;a.fillText(f,x-4,n+(hX-gX)/2)}a.globalAlpha=1}function g(){let e=a.current;if(!e)return;let{w:t,h:n}=p(),r=m(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=c.current;if(i===null)return;let{tasks:o}=d.current;if(i<0||i>=o.length)return;let s=o[i],l=s.end-s.start,u=`${s.label}: ${Hz(s.start)} → ${Hz(s.end)} (${Hz(l)})`;r.font=`11px ${Q.mono}`;let f=r.measureText(u).width,h=1/0,g=-1/0;for(let e of o)e.start<h&&(h=e.start),e.end>g&&(g=e.end);let _=(g-h)*.02||1;h-=_,g+=_;let v=t-mX.left-mX.right,y=e=>mX.left+(e-h)/(g-h)*v,b=mX.top+i*(hX+gX),x=(y(s.start)+y(s.end))/2,S=Math.max(4,Math.min(t-f-8,x-f/2)),C=b-22<mX.top?b+hX+4:b-20;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(S-3,C-3,f+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(u,S,C)}let _=K(h);_.current=h;let v=K(null);v.current??=GH(()=>_.current(),()=>o.current);let y=()=>v.current.schedule(),b=()=>{RH(l.current),l.current=LH(g)};return W(()=>{v.current.now()}),W(()=>()=>v.current?.cancel(),[]),W(()=>{s.current=null,y()},[t]),G(()=>{let e=o.current;if(!e)return;let t=new UH(()=>{s.current=null,y(),b()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=a.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{tasks:r}=d.current,i=t.clientY-n.top,a=Math.floor((i-mX.top)/(hX+gX));c.current=a>=0&&a<r.length?a:null,b()},r=()=>{c.current=null,b()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:o,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:i,className:`chart-canvas`,role:`img`,"aria-label":`Gantt chart`}),q(`canvas`,{ref:a,className:`chart-canvas chart-overlay`})]})}var yX=e=>[...e].filter(e=>Number.isFinite(e.at)).sort((e,t)=>e.at-t.at),bX=e=>{let t=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i.exec(e);return t?[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]:[128,128,128]},xX=e=>`#${e.map(e=>Math.round(e).toString(16).padStart(2,`0`)).join(``)}`;function SX(e,t,n,r){let i=t?yX(t):[];if(!e||e===`solid`||i.length===0||!Number.isFinite(r))return n;if(e===`zones`){let e=i[0].color;for(let t of i)r>=t.at&&(e=t.color);return e}if(r<=i[0].at)return i[0].color;if(r>=i[i.length-1].at)return i[i.length-1].color;let a=0;for(;i[a+1].at<r;)a++;let o=i[a],s=i[a+1],c=(r-o.at)/(s.at-o.at||1),l=bX(o.color),u=bX(s.color);return xX([l[0]+(u[0]-l[0])*c,l[1]+(u[1]-l[1])*c,l[2]+(u[2]-l[2])*c])}function CX(e,t,n,r,i,a=96){let o=i-r||1,s=t?yX(t):[];if(!e||e===`solid`||s.length===0)return[{f0:0,f1:1,color:n}];if(e===`zones`){let e=[0,...s.slice(1).map(e=>(e.at-r)/o).filter(e=>e>0&&e<1),1];return e.slice(0,-1).map((t,i)=>({f0:t,f1:e[i+1],color:SX(`zones`,s,n,r+(t+e[i+1])/2*o)}))}return Array.from({length:a},(e,t)=>({f0:t/a,f1:(t+1)/a,color:SX(`gradient`,s,n,r+(t+.5)/a*o)}))}function wX(e,t,n){let r=e=>+(t+e*(n-t)).toPrecision(6),i=`#22c55e`,a=`#ef4444`;if(e===`traffic`)return{mode:`zones`,stops:[{at:r(0),color:i},{at:r(.7),color:`#f5a524`},{at:r(.9),color:a}]};let o=[{at:r(0),color:i},{at:r(.5),color:`#eab308`},{at:r(1),color:a}];return{mode:`gradient`,stops:e===`green-red`?o:o.map((e,t)=>({...e,color:o[o.length-1-t].color}))}}function TX(e,t,n){let r=t?yX(t):[];if(!e||e===`solid`||r.length===0)return n;let i=r[0].at,a=r[r.length-1].at,o=e=>`${((e-i)/(a-i||1)*100).toFixed(1)}%`;if(e===`gradient`)return`linear-gradient(90deg, ${r.map(e=>`${e.color} ${o(e.at)}`).join(`, `)})`;let s=100/r.length;return`linear-gradient(90deg, ${r.map((e,t)=>`${e.color} ${(t*s).toFixed(1)}% ${((t+1)*s).toFixed(1)}%`).join(`, `)})`}var EX=.75*Math.PI,DX=1.5*Math.PI;function OX({gauges:e,live:t,backgroundToken:n=``,onPlotContextMenu:r}){let i=K(null),a=K(null),o=K(null),s=K(r);G(()=>{s.current=r},[r]);let c=K({gauges:e,live:t});G(()=>{c.current={gauges:e,live:t}},[e,t]);let l=K(lU()),u=K(0);function d(){if(o.current)return o.current;let e=a.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`,ink:`#e4e4e7`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`,ink:t.getPropertyValue(`--chart-fg`).trim()||`#e4e4e7`};return o.current=n,n}function f(){let e=i.current,t=a.current;if(!e||!t)return;let n=Math.max(1,t.clientWidth),r=Math.max(1,t.clientHeight),o=Math.min(2,window.devicePixelRatio||1),s=Math.floor(n*o),f=Math.floor(r*o);(e.width!==s||e.height!==f)&&(e.width=s,e.height=f),e.style.width=`${n}px`,e.style.height=`${r}px`;let p=e.getContext(`2d`);if(!p)return;p.setTransform(o,0,0,o,0,0);let h=d(),{gauges:g,live:_}=c.current,v=g;if(_){let e=performance.now(),t=TU(l.current,_.latestT(),e-u.current,_.timeAfter);u.current=e,v=g.map(e=>{if((e.stat??`last`)!==`last`)return e;let n=_.valueAt(e.name,t);return Number.isFinite(n)?{...e,value:n}:e}),m.current.schedule()}if(p.fillStyle=h.bg,p.fillRect(0,0,n,r),v.length===0){p.fillStyle=h.muted,p.font=`13px ${Q.sans}`,p.textAlign=`left`,p.textBaseline=`top`,UV(p);return}let{cols:y,rows:b}=kX(v.length,n,r,v.some(e=>e.style===`arc`)?1.15:3.2),x=n/y,S=r/b;v.forEach((e,t)=>{let n=t%y*x,r=Math.floor(t/y)*S;e.style===`arc`?zX(p,e,n,r,x,S,e.color,e.alarm??null,h):BX(p,e,n,r,x,S,e.color,e.alarm??null,h)})}let p=K(f);p.current=f;let m=K(null);return m.current??=GH(()=>p.current(),()=>a.current),W(()=>{m.current.now()}),W(()=>()=>m.current?.cancel(),[]),W(()=>{o.current=null,m.current.schedule()},[n]),G(()=>{let e=a.current;if(!e)return;let t=new UH(()=>{o.current=null,m.current.schedule()});return t.observe(e),()=>t.disconnect()},[]),q(`div`,{ref:a,style:{position:`relative`,width:`100%`,height:`100%`},children:q(`canvas`,{ref:i,className:`chart-canvas`,role:`img`,"aria-label":`Gauges: ${e.map(e=>`${e.name} ${Number.isFinite(e.value)?AX(e.value,e.max-e.min):`no value`}${e.unit?` ${e.unit}`:``}`).join(`, `)}`,onContextMenu:e=>{e.preventDefault(),s.current?.({clientX:e.clientX,clientY:e.clientY})}})})}function kX(e,t,n,r){let i={cols:1,rows:e,size:-1};for(let a=1;a<=e;a++){let o=Math.ceil(e/a),s=t/a,c=n/o,l=Math.min(s,c*r);l>i.size&&(i={cols:a,rows:o,size:l})}return{cols:i.cols,rows:i.rows}}var AX=(e,t)=>Vz(e,Pz(Math.abs(t),100)),jX=(e,t)=>Math.max(0,Math.min(1,(t-e.min)/(e.max-e.min||1))),MX=(e,t)=>{let n=e.fromZero?jX(e,0):0;return[Math.min(n,t),Math.max(n,t)]},NX=(e,t)=>!!t&&(t.linked?t.linked===`active`:Number.isFinite(e.value)&&e.value>=t.value),PX=e=>(e.colorMode===`gradient`||e.colorMode===`zones`)&&!!e.stops?.length,FX=(e,t)=>NX(e,t)?t.color:SX(e.colorMode,e.stops,e.color,e.value);function IX(e,t,n){for(let r of CX(t.colorMode,t.stops,t.color,t.min,t.max))e.addColorStop(n(r.f0),r.color),e.addColorStop(n(r.f1),r.color);return e}function LX(e,t,n){if(e.measureText(t).width<=n)return t;let r=t;for(;r.length>1&&e.measureText(`${r}…`).width>n;)r=r.slice(0,-1);return n>0?`${r}…`:``}var RX=Math.SQRT1_2;function zX(e,t,n,r,i,a,o,s,c){let l=Math.max(6,Math.min(i,a)*.06),u=t.max-t.min,d=AX(t.min,u),f=AX(t.max,u),p=e=>Math.max(9,Math.min(22,e*.1)),m=e=>Math.max(4,e*.13),h=Math.max(8,Math.min((i-2*l)/2,(a-2*l)/1.9)),g=0;for(let t=0;t<2;t++){e.font=`${p(h)}px ${Q.mono}`,g=Math.max(e.measureText(d).width,e.measureText(f).width);let t=m(h),n=Math.max(h+t/2,RX*h+g/2),r=h+t/2+RX*h+t/2+6+p(h)*1.2;h=Math.max(8,Math.min(h*(i-2*l)/(2*n),h*(a-2*l)/r))}let _=m(h),v=p(h),y=h+_/2+RX*h+_/2+6+v*1.2,b=n+i/2,x=r+l+h+_/2+Math.max(0,(a-2*l-y)/2),S=e=>EX+e*DX;e.lineCap=`round`,e.lineWidth=_,e.strokeStyle=c.grid,e.beginPath(),e.arc(b,x,h,EX,EX+DX),e.stroke(),s&&s.value<t.max&&(e.globalAlpha=.3,e.strokeStyle=s.color,e.lineCap=`butt`,e.beginPath(),e.arc(b,x,h,S(jX(t,s.value)),EX+DX),e.stroke(),e.globalAlpha=1,e.lineCap=`round`);let[C,w]=MX(t,Number.isFinite(t.value)?jX(t,t.value):0),T=()=>{e.lineCap=t.fromZero?`butt`:`round`,e.beginPath(),e.arc(b,x,h,S(C),Math.max(S(C)+1e-4,S(w))),e.stroke(),e.lineCap=`round`};if(PX(t)){let n=DX/(2*Math.PI),r=IX(e.createConicGradient(EX,b,x),t,e=>e*n);r.addColorStop(1,SX(t.colorMode,t.stops,t.color,t.min)),e.strokeStyle=r,e.globalAlpha=.24,e.beginPath(),e.arc(b,x,h,EX,EX+DX),e.stroke(),e.globalAlpha=1,Number.isFinite(t.value)&&!NX(t,s)&&T()}if(Number.isFinite(t.value)&&(!PX(t)||NX(t,s))&&(e.strokeStyle=NX(t,s)?s.color:o,T()),t.fromZero&&t.min<0&&t.max>0){let n=S(jX(t,0));e.strokeStyle=c.muted,e.lineWidth=1.5,e.lineCap=`butt`,e.beginPath(),e.moveTo(b+Math.cos(n)*(h-_*.75),x+Math.sin(n)*(h-_*.75)),e.lineTo(b+Math.cos(n)*(h+_*.75),x+Math.sin(n)*(h+_*.75)),e.stroke(),e.lineWidth=_,e.lineCap=`round`}if(s&&s.value>=t.min&&s.value<=t.max){let n=S(jX(t,s.value));e.strokeStyle=s.color,e.lineWidth=Math.max(1.5,s.width),e.lineCap=`butt`,e.beginPath(),e.moveTo(b+Math.cos(n)*(h-_*.9),x+Math.sin(n)*(h-_*.9)),e.lineTo(b+Math.cos(n)*(h+_*.9),x+Math.sin(n)*(h+_*.9)),e.stroke();let r=h+_*.9+10*.7;s.linked&&zU(e,b+Math.cos(n)*r-10/2,x+Math.sin(n)*r-10/2,s.color)}let E=Number.isFinite(t.value)?AX(t.value,u):`—`,D=2*(h-_)*.82,O=Math.max(11,h*.42);e.font=`650 ${O}px ${Q.sans}`;let k=e.measureText(E).width;k>D&&(O=Math.max(9,O*D/k),e.font=`650 ${O}px ${Q.sans}`),e.textAlign=`center`,e.textBaseline=`alphabetic`,e.fillStyle=NX(t,s)||PX(t)?FX(t,s):c.ink,e.fillText(E,b,x+O*.32),e.fillStyle=c.muted,t.unit&&(e.font=`600 ${Math.max(9,h*.13)}px ${Q.sans}`,e.fillText(LX(e,t.unit,D),b,x+O*.32+Math.max(11,h*.19)));let A=x+RX*h+_/2+6,j=RX*h;e.textBaseline=`top`,e.font=`${v}px ${Q.mono}`,e.fillText(d,b-j,A),e.fillText(f,b+j,A);let M=2*j-g-16,N=Math.max(10,Math.min(26,h*.13));e.font=`600 ${N}px ${Q.sans}`;let P=e.measureText(t.name).width;P>M&&N>9&&(N=Math.max(9,N*M/P),e.font=`600 ${N}px ${Q.sans}`),e.fillText(LX(e,t.name,M),b,A+(v-N)/2)}function BX(e,t,n,r,i,a,o,s,c){let l=Math.max(14,i*.06),u=n+l,d=n+i-l,f=d-u,p=Math.max(6,Math.min(16,a*.14)),m=Math.max(12,Math.min(34,a*.28)),h=r+a/2+m*.35,g=e=>u+jX(t,e)*f;e.textBaseline=`alphabetic`,e.fillStyle=c.muted,e.font=`600 ${Math.max(10,m*.42)}px ${Q.sans}`,e.textAlign=`left`,e.fillText(LX(e,t.name,f),u,h-p/2-m-4),e.textAlign=`right`,e.fillStyle=NX(t,s)?s.color:c.ink,e.font=`650 ${m}px ${Q.sans}`;let _=t.unit?(e.font=`600 ${Math.max(9,m*.4)}px ${Q.sans}`,e.measureText(` ${t.unit}`).width):0;t.unit&&(e.fillStyle=c.muted,e.fillText(` ${t.unit}`,d,h-p/2-8)),e.fillStyle=NX(t,s)||PX(t)?FX(t,s):c.ink,e.font=`650 ${m}px ${Q.sans}`,e.fillText(Number.isFinite(t.value)?AX(t.value,t.max-t.min):`—`,d-_,h-p/2-8),e.lineCap=`round`,e.lineWidth=p,e.strokeStyle=c.grid,e.beginPath(),e.moveTo(u,h),e.lineTo(d,h),e.stroke(),s&&s.value<t.max&&(e.globalAlpha=.3,e.strokeStyle=s.color,e.lineCap=`butt`,e.beginPath(),e.moveTo(g(s.value),h),e.lineTo(d,h),e.stroke(),e.globalAlpha=1,e.lineCap=`round`);let v=Number.isFinite(t.value)?jX(t,t.value):0,y=e=>u+e*f,[b,x]=MX(t,v),S=()=>{e.lineCap=t.fromZero?`butt`:`round`,e.beginPath(),e.moveTo(y(b),h),e.lineTo(Math.max(y(b)+.5,y(x)),h),e.stroke(),e.lineCap=`round`};PX(t)&&(e.strokeStyle=IX(e.createLinearGradient(u,0,d,0),t,e=>e),e.globalAlpha=.24,e.beginPath(),e.moveTo(u,h),e.lineTo(d,h),e.stroke(),e.globalAlpha=1,Number.isFinite(t.value)&&!NX(t,s)&&S()),Number.isFinite(t.value)&&(!PX(t)||NX(t,s))&&(e.strokeStyle=NX(t,s)?s.color:o,S()),t.fromZero&&t.min<0&&t.max>0&&(e.strokeStyle=c.muted,e.lineWidth=1.5,e.lineCap=`butt`,e.beginPath(),e.moveTo(g(0),h-p*.75),e.lineTo(g(0),h+p*.75),e.stroke(),e.lineWidth=p,e.lineCap=`round`),s&&s.value>=t.min&&s.value<=t.max&&(e.strokeStyle=s.color,e.lineWidth=Math.max(1.5,s.width),e.lineCap=`butt`,e.beginPath(),e.moveTo(g(s.value),h-p),e.lineTo(g(s.value),h+p),e.stroke(),s.linked&&zU(e,g(s.value)-10/2,h-p-10-2,s.color)),e.fillStyle=c.muted,e.font=`${Math.max(9,m*.34)}px ${Q.mono}`,e.textBaseline=`top`,e.textAlign=`left`,e.fillText(AX(t.min,t.max-t.min),u,h+p/2+4),e.textAlign=`right`,e.fillText(AX(t.max,t.max-t.min),d,h+p/2+4)}var VX=`Video limit reached this month`,HX=720;function UX(e,t){return t?e<HX:e<640}function WX(e){return e<=1?{cols:1,rows:1}:e===2?{cols:2,rows:1}:e<=4?{cols:2,rows:2}:{cols:3,rows:3}}function GX(e,t){return e.flatMap(e=>{let n=e.info?.meta;if(!n?.recordingId)return[];let r=n.wallOrigin?Number(n.wallOrigin):NaN,i=n.wallQuality;return[{recordingId:n.recordingId,wallOrigin:Number.isFinite(r)?r:null,wallQuality:i===`exact`||i===`approx`?i:null,xOffset:t[e.id]??0}]})}var KX={get:()=>null,subscribe:()=>()=>{}};function qX(e){let[t,n]=Ct(null);return G(()=>{let t=e.current;if(!t)return;let r=e=>n(t=>UX(e,t??!1));if(r(t.clientWidth),typeof ResizeObserver>`u`)return;let i=new ResizeObserver(e=>{for(let t of e)r(t.contentRect.width)});return i.observe(t),()=>i.disconnect()},[e]),t}function JX(e){let t=tr(e.settings),[n,r]=Ct(null),[i,a]=Ct(null),o=K(null);W(()=>{i&&o.current?.querySelector(`[data-camera="${CSS.escape(i)}"]`)?.focus()},[i]);let s=e.recordings??[],c=e=>s.findIndex(t=>t.recordingId===e.recordingId),l=(e.video??[]).filter(e=>e.kind===`recorded`&&c(e)>=0).sort((e,t)=>c(e)-c(t)),u=e.onContextMenu?t=>{t.preventDefault(),e.onContextMenu({clientX:t.clientX,clientY:t.clientY})}:void 0;if(!t.length){let t=[...new Set([...e.live.filter(e=>e.kind===`camera`&&!e.lowOf),...l].map(t=>Qn(t,e.live)))].sort();return q(XX,{onContextMenu:u,title:`Choose a camera in this panel's settings`,detail:t.length?t.join(`, `):void 0})}let d={panel:e,recorded:l,recIndex:c};if(t.length===1)return q(YX,{...d,id:t[0],onMenu:u});let f=n&&t.includes(n)?n:null,p=f?[f]:t,{cols:m,rows:h}=WX(p.length),g=()=>{a(f),r(null)};return Ot(`div`,{ref:o,className:`kymo-camera-wall`,style:{gridTemplateColumns:`repeat(${m}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${h}, minmax(0, 1fr))`},onContextMenu:u,onKeyDown:e=>{e.key===`Escape`&&f&&(e.stopPropagation(),g())},children:[p.map(e=>q(YX,{...d,id:e,multi:!0,wall:!f,onPick:f?void 0:()=>{a(null),r(e)}},e)),f?Ot(`button`,{type:`button`,className:`kymo-camera__all`,onClick:g,autoFocus:!0,children:[Ot(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[q(`rect`,{x:`2`,y:`2`,width:`5`,height:`5`,rx:`1`}),q(`rect`,{x:`9`,y:`2`,width:`5`,height:`5`,rx:`1`}),q(`rect`,{x:`2`,y:`9`,width:`5`,height:`5`,rx:`1`}),q(`rect`,{x:`9`,y:`9`,width:`5`,height:`5`,rx:`1`})]}),`All cameras`]}):null]})}function YX({panel:e,recorded:t,recIndex:n,id:r,multi:i,wall:a,onPick:o,onMenu:s}){let c=e.recordings??[],l={onMenu:s,wall:a,onPick:o},u=t.find(e=>e.id===r);if(u)return q(ZX,{...e,...l,source:u,name:i?Qn(u,e.live):u.name,rec:c[n(u)]},`rec:${u.recordingId}:${u.id}`);let d=e.live.find(e=>e.id===r&&e.kind===`camera`);if(d?.limitNotice&&(d.limitNotice===`Video limit reached this month`||!d.video))return q(XX,{onContextMenu:s,title:d.limitNotice,detail:Qn(d,e.live)});if(!d?.video||d.status===`error`)return q(XX,{onContextMenu:s,title:`Camera offline`,detail:d?Qn(d,e.live):void 0});let f=e.live.find(e=>e.kind===`camera`&&e.lowOf===d.id&&e.video&&e.status!==`error`),p=f?.video?BE({...f,video:f.video}):void 0;return q(ZX,{...e,...l,source:BE({...d,video:d.video}),low:p,name:i?Qn(d,e.live):d.name,conn:d},d.id)}function XX({title:e,detail:t,onContextMenu:n}){return q(`div`,{className:`kymo-camera`,onContextMenu:n,children:Ot(`div`,{className:`kymo-camera__empty`,children:[Ot(`svg`,{className:`kymo-camera__empty-icon`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[q(`rect`,{x:`2.5`,y:`6`,width:`13`,height:`12`,rx:`2.5`}),q(`path`,{d:`M15.5 10.5 21.5 7v10l-6-3.5`})]}),q(`p`,{className:`kymo-camera__empty-title`,children:e}),t?q(`p`,{className:`kymo-camera__empty-detail`,children:t}):null]})})}function ZX(e){let{settings:t,source:n}=e,r=e.cursor??KX,i=wt(r.subscribe,r.get),a=e=>e.kind===`data`,o=e.rec?void 0:t.syncStreamId?e.live.find(e=>e.id===t.syncStreamId&&a(e)):e.live.find(t=>t.id===e.conn.parentId&&a(t))??e.live.find(t=>a(t)&&e.selection.includes(t.id))??e.live.find(a),s=i??e.viewXRange?.[1]??null,c=null,l=null,u=o?.clock?.quality()??`none`;if(e.rec){let{wallOrigin:r,wallQuality:i,xOffset:a}=e.rec;u=i??`none`;let o=n.range()?.[0]??null;s===null?c=o:r===null?(c=o,l=`This recording has no wall clock`):e.xKey===`Time`?c=r+s-a+t.offsetMs/1e3:e.xKey===`ElapsedTime`&&i===`exact`?c=s-a+t.offsetMs/1e3:(c=o,l=`Sync needs a time X axis`)}else s!==null&&(e.xIsTime?(c=o?.clock?.toWall(s,t.offsetMs)??null,c===null&&(l=`No data stream to sync with`)):l=`Sync needs a time X axis`);let d=K(null),f=K(null),p=qX(d),m=p===null?null:e.low&&(p||e.wall)?e.low:n,h=K(t.fit),g=K(c);G(()=>{h.current=t.fit,g.current=c});let _=K(null),v=K(null),[y,b]=Ct(null),x=y??m??n,[S,C]=Ct(!1),[w,T]=Ct(!0);W(()=>{if(!m||_.current?.source===m)return;let e=!_.current,t=null,n=!1,r=()=>t?_.current===t:e,i=t=iZ(m,f.current,()=>h.current,g.current,{unsupported:()=>{r()&&C(!0)},buffered:e=>{r()&&T(e)},frame:()=>{if(_.current===t){n||(n=!0,b(m));return}_.current?.dispose(),_.current=i,v.current=null,i.show(),n=!0,b(m),T(i.buffered())}},e);if(e){_.current=i;return}return v.current=i,()=>{_.current!==i&&(i.dispose(),v.current===i&&(v.current=null))}},[m]),W(()=>()=>{_.current?.dispose(),_.current=null},[]),W(()=>{_.current?.setTarget(c),v.current?.setTarget(c)},[c]);let E=QX(e.rec||c!==null?null:x),D=$X(e.rec?n:null),O=!!x.lowOf,k=x.info().latestT,A=!e.rec&&c!==null&&k!==null?c-k:null,j=e.rec?`No video at this time`:`Not buffered`;return Ot(`div`,{ref:d,className:`kymo-camera${e.onPick?` is-tile`:``}`,onContextMenu:e.onMenu,...e.onPick?{role:`button`,tabIndex:0,"data-camera":n.id,"aria-label":`Show ${e.name} alone`,onClick:e.onPick,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e.onPick())}}:{},children:[q(`canvas`,{ref:f,className:`kymo-camera__video`,role:`img`,"aria-label":`Video from ${e.name}`}),S?q(`div`,{className:`kymo-camera__empty`,children:q(`p`,{className:`kymo-camera__empty-title`,children:`This browser can't decode this camera`})}):E===null?Ot(`div`,{className:`kymo-camera__overlay`,children:[q(`span`,{className:`kymo-camera__name`,children:e.name}),e.rec?q(`span`,{className:`kymo-camera__rec`,children:`Recording`}):c===null?q(`span`,{className:`kymo-camera__live`,children:`LIVE`}):q(`span`,{className:`kymo-camera__ago`,children:A===null?``:tZ(A)}),O?q(`span`,{className:`kymo-camera__badge`,title:`Low-quality copy (small panel)`,children:`LQ`}):null,c!==null&&u!==`none`?q(`span`,{className:`kymo-camera__badge${u===`exact`?` is-exact`:``}`,children:u===`exact`?`Exact`:`Approx.`}):null,l??(c!==null&&!w?j:null)?q(`span`,{className:`kymo-camera__note`,children:l??j}):null,e.conn?.limitNotice?q(`span`,{className:`kymo-camera__note`,role:`status`,children:e.conn.limitNotice}):null,D?.broken?q(`span`,{className:`kymo-camera__note`,role:`status`,title:`Some of this recording was missing, out of order or changed where it is stored (${D.broken} of ${D.broken+D.verified} checked ${D.broken+D.verified===1?`chunk`:`chunks`}). The video may have gaps there.`,children:`Some messages were missing or out of order`}):null]}):Ot(`div`,{className:`kymo-camera__empty kymo-camera__empty--cover`,role:`status`,children:[q(`p`,{className:`kymo-camera__empty-title`,children:`No signal`}),Ot(`p`,{className:`kymo-camera__empty-detail`,children:[e.name,` · no video for `,eZ(E)]})]})]})}function QX(e){let[t]=Ct(()=>Date.now()),[n,r]=Ct(null);return W(()=>{if(!e){r(null);return}let n=()=>{let{arrivedAt:n,gapMs:i}=e.info(),a=Date.now()-Math.max(n??0,t);r(a>RE(i)?Math.floor(a/1e3):null)};n();let i=setInterval(n,500);return()=>clearInterval(i)},[e,t]),n}function $X(e){let[t,n]=Ct(null);return W(()=>{if(!e?.integrity){n(null);return}let t=()=>{let t=e.integrity();n(e=>e?.verified===t?.verified&&e?.broken===t?.broken?e:t&&{verified:t.verified,broken:t.broken})};t();let r=setInterval(t,1e3);return()=>clearInterval(r)},[e]),t}function eZ(e){return e<60?`${e} s`:e<3600?`${Math.floor(e/60)} min`:`${Math.floor(e/3600)} h`}function tZ(e){let t=Math.abs(e).toFixed(1);return t===`0.0`?`0.0 s`:`${e<0?`−`:`+`}${t} s`}var nZ=60,rZ=.05;function iZ(e,t,n,r,i,a=!0){let o=e.acquire?.(),s=!1,c=!0,l=e=>{c=e,i.buffered(e)},u=null,d=null,f=r,p=`live`,m=!0,h=!1,g=!1,_=null,v=null,y=null,b=[],x=lU(),S=NaN,C=[],w=()=>{for(let e of b)e.close();b=[]},T=e=>{if(s){e.close();return}if(p===`seek`){_?.close(),_=e;return}for(b.push(e);b.length>(a?nZ:1);)b.shift().close();i.frame?.()},E=e=>{if(!b.length)return;let t=b[b.length-1].timestamp/1e6,n=Number.isNaN(S)?16:e-S,r=Math.max(TU(x,t,n,e=>{let t=b.find(t=>t.timestamp/1e6>e);return t?t.timestamp/1e6:NaN}),t-rZ);x.d=r;let i=-1;for(;i+1<b.length&&b[i+1].timestamp/1e6<=r+1e-6;)i++;if(!(i<0)){for(let e=0;e<i;e++)b[e].close();v?.close(),v=b[i],b=b.slice(i+1)}},D=()=>{!d||d.state===`closed`?d=new VideoDecoder({output:T,error:()=>{}}):d.reset(),d.configure(u),m=!0},O=e=>{d?.state===`closed`&&e.key&&D(),!(d?.state!==`configured`||m&&!e.key)&&(m=!1,d.decode(new EncodedVideoChunk({type:e.key?`key`:`delta`,timestamp:Math.round(e.t*1e6),data:e.data})))},k=()=>{p=`live`,l(!0),w(),x=lU(),D();for(let t of e.livePlan?.()??[])O(t)},A=async()=>{if(!h){h=!0;try{for(;!s&&p===`seek`&&g;){g=!1;let t=[];try{t=await e.seekPlan(f)}catch{}if(!(s||p!==`seek`||g)&&(l(t.length>0),t.length)){D();for(let e of t)O(e);try{await d.flush()}catch{}p===`seek`&&_&&(v?.close(),v=_,_=null,i.frame?.())}}}finally{h=!1,_?.close(),_=null}}},j=()=>{f===null?p!==`live`&&k():(p=`seek`,w(),g=!0,A())};e.onUnit&&C.push(e.onUnit(e=>{u&&p===`live`&&O(e)})),(async()=>{if(typeof VideoDecoder>`u`){i.unsupported();return}if(e.info().codec||(e.ready?await e.ready():e.onUnit&&await new Promise(t=>{let n=e.onUnit(()=>{e.info().codec&&(n(),t())});C.push(n)})),s)return;if(!e.info().codec){l(!1);return}let t={codec:e.info().codec,optimizeForLatency:!0,hardwareAcceleration:`no-preference`},n=!1;try{n=(await VideoDecoder.isConfigSupported(t)).supported===!0}catch{}if(!s){if(!n){i.unsupported();return}u=t,f===null?k():j()}})();let M=n(),N=()=>{if(!a)return;let e=window.devicePixelRatio||1,r=Math.max(1,Math.round(t.clientWidth*e)),i=Math.max(1,Math.round(t.clientHeight*e)),o=!1,s=performance.now();if(p===`live`&&E(s),S=s,(t.width!==r||t.height!==i)&&(t.width=r,t.height=i,o=!0),v&&(y?.close(),y=v,v=null,o=!0),n()!==M&&(M=n(),o=!0),!o||!y)return;let c=t.getContext(`2d`);if(!c)return;let l=y.displayWidth,u=y.displayHeight,d=M===`cover`?Math.max(r/l,i/u):Math.min(r/l,i/u),f=l*d,m=u*d;c.clearRect(0,0,r,i),c.drawImage(y,(r-f)/2,(i-m)/2,f,m)},P=0,F=()=>{P=LH(F),N()};return P=LH(F),{source:e,show(){a=!0},buffered:()=>c,setTarget(e){e!==f&&(f=e,u&&j())},dispose(){s=!0,RH(P),C.forEach(e=>e()),d&&d.state!==`closed`&&d.close();for(let e of[_,v,y])e?.close();_=v=y=null,w(),o?.()}}}function aZ(e,t){let n=e.filter(e=>e.x.length>=2&&oZ(e.x));if(n.length<2)return null;let r=1/0,i=-1/0;for(let e of n)e.x[0]<r&&(r=e.x[0]),e.x[e.x.length-1]>i&&(i=e.x[e.x.length-1]);if(!(i>r))return null;let a=Math.max(2,t),o=Float64Array.from({length:a},(e,t)=>r+t/(a-1)*(i-r)),s=new Float64Array(a).fill(1/0),c=new Float64Array(a).fill(-1/0),l=new Uint16Array(a);for(let e of n){let t=0;for(let n=0;n<a;n++){let r=o[n];if(r<e.x[0]||r>e.x[e.x.length-1])continue;for(;t<e.x.length-2&&e.x[t+1]<r;)t++;let i=e.x[t],a=e.x[t+1],u=e.y[t],d=e.y[t+1],f=a===i?u:u+(d-u)*(r-i)/(a-i);f-f===0&&(f<s[n]&&(s[n]=f),f>c[n]&&(c[n]=f),l[n]++)}}for(let e=0;e<a;e++)l[e]<2&&(s[e]=NaN,c[e]=NaN);return{x:o,lo:s,hi:c}}function oZ(e){for(let t=1;t<e.length;t++)if(!(e[t]>=e[t-1]))return!1;return!0}function sZ(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=new Set,n={};for(let r of e)for(let e=0;e<r.columnNames.length;e++){let i=r.columnNames[e];t.add(i),r.units[e]?.trim()&&(n[i]=r.units[e])}let r=[...t];return{meta:``,columnNames:r,units:r.map(e=>n[e]??``),rows:e.flatMap(e=>e.rows)}}function cZ(e,t,n,r,i){return n||e.length===0||(t>0?e.length!==1:e.length<2||r!==`ElapsedTime`)?null:e.map((e,n)=>({conn:e,keySuffix:`__${t+n}`,offset:i[e.id]??0}))}function lZ(e,t,n,r,i){if(e.length===1){let a=e[0];return uZ(a.conn,t,n,a.keySuffix,a.offset,r,i)}let a=e.map(e=>uZ(e.conn,t,n,e.keySuffix,e.offset,[],null)),o=()=>a.reduce((e,t)=>t.latestT()>e.latestT()?t:e);return{pull:(e,t,n,i)=>[...r,...a.flatMap(r=>r.pull(e,t,n,i))],xBounds:()=>{let e=i;for(let t of a){let n=t.xBounds();n&&(e=e?[Math.min(e[0],n[0]),Math.max(e[1],n[1])]:n)}return e},latestX:()=>o().latestX(),version:()=>a.reduce((e,t)=>e+t.version(),0),latestT:()=>o().latestT(),timeAfter:e=>o().timeAfter(e),xAtTime:e=>o().xAtTime(e),latestValues:e=>new Map(a.flatMap(t=>[...t.latestValues(e)]))}}function uZ(e,t,n,r,i,a,o){let s=null;return{pull:(o,c,l,u)=>{let d=e.source.version();if(!s||s.ver!==d||s.x0!==o||s.x1!==c||s.mp!==l){let a=e.source.getPointsSync(n,{xKey:t,x0:o-i,x1:c-i},l),u=i===0?a.x:a.x.map(e=>e+i);s={ver:d,x0:o,x1:c,mp:l,pts:{...a,x:u,cols:new Map([...a.cols].map(([e,t])=>[e+r,t]))}}}let p=f(s.pts,u);if(t!==`ElapsedTime`)return[...a,p];let m=Math.min(e.source.latestTimeSync(),u===void 0?1/0:u-i),h=lt(n,t=>e.source.lastKnownSync(t),o-i,c-i,m);if(!h)return[...a,p];let g=i===0?h.x:h.x.map(e=>e+i);return[...a,p,{...h,x:g,cols:new Map([...h.cols].map(([e,t])=>[e+r,t]))}]},xBounds:()=>{let n=e.source.xBoundsSync(t);return n.x1>n.x0?o?[Math.min(o[0],n.x0+i),Math.max(o[1],n.x1+i)]:[n.x0+i,n.x1+i]:o},latestX:()=>{let n=e.source.latestSync(t);return Number.isFinite(n)?n+i:null},version:()=>e.source.version(),id:e.id,latestT:()=>e.source.latestTimeSync(),timeAfter:t=>e.source.timeAfterSync(t),xAtTime:n=>e.source.xAtTimeSync(t,n)+i,latestValues:t=>{let n=new Map,i=t.filter(e=>e.endsWith(r)),a=e.source.latestValuesSync(i.map(e=>e.slice(0,-r.length)));for(let e of i){let t=a.get(e.slice(0,-r.length));t!==void 0&&n.set(e,t)}return n}}}function dZ(e,t){return e.filter(e=>Ze(t,e))}var fZ=`__ref`,pZ=8e3;function mZ(e,t){return e.map(e=>({...e,id:`${e.id}${fZ}`,column:`${e.column}${fZ}`,color:t}))}var hZ=new WeakMap;function gZ(e,t,n){let r=e.data.rows,i=`${t}\n${n.join(`
|
|
608
|
-
`)}`,a=
|
|
607
|
+
}`,_q=-3e38;function vq(e){for(let t=0;t<e.length;t++)if(e[t]-e[t]===0)return e[t];return 0}function yq(e){let t=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0});if(!t)return null;let n=(e,n,i,a)=>uH(t,`glPlot|${e}|${n}`,()=>r(e,n,i,a)),r=(e,n,r,i)=>{let a=QV(t,t.VERTEX_SHADER,e),o=QV(t,t.FRAGMENT_SHADER,n);if(!a||!o)return null;let s=t.createProgram();if(t.attachShader(s,a),t.attachShader(s,o),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))return console.error(`glPlot program link failed:`,t.getProgramInfoLog(s)),null;let c=[`u_resolution`,`u_plot`,`u_view`,`u_clip`,`u_dpr`,`u_height`];return{prog:s,shaders:[a,o],a:Object.fromEntries([`a_corner`,...r].map(e=>[e,t.getAttribLocation(s,e)])),u:Object.fromEntries([...c,...i].map(e=>[e,t.getUniformLocation(s,e)]))}},i=n(lq,dq,[`a_xa`,`a_xb`,`a_loa`,`a_lob`,`a_hia`,`a_hib`,`a_bstart`],[`u_color`]),a=n(uq,fq,[`a_x0`,`a_x1`,`a_y0`,`a_y1`,`a_k`],[`u_palette`]),o=n(pq,mq,[`a_ax`,`a_ay`,`a_bx`,`a_by`,`a_bstart`],[`u_color`,`u_half`,`u_ext`]),s=n(hq,gq,[],[`u_extent`,`u_values`,`u_palette`,`u_range`]);if(!i||!a||!o||!s)return null;let c=t.getParameter(t.MAX_TEXTURE_SIZE),l=t.createVertexArray(),u=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,u),t.bufferData(t.ARRAY_BUFFER,Float32Array.from([0,0,1,0,0,1,1,1]),t.STATIC_DRAW);let d=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,d),t.bufferData(t.ARRAY_BUFFER,Float32Array.from([-1,-1,1,-1,-1,1,1,1]),t.STATIC_DRAW);let f=new Map,p=1,m=1,h=1,g={xmin:0,xmax:1,ymin:0,ymax:1},_={left:0,top:0,width:1,height:1},v=new WeakMap,y=new Float32Array,b=e=>{for(let n of Object.values(e.buffers))t.deleteBuffer(n);e.palette&&t.deleteTexture(e.palette),e.values&&t.deleteTexture(e.values)},x=new Float32Array,S=(e,n)=>{t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA8,256,1,0,t.RGBA,t.UNSIGNED_BYTE,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)},C=(e,t)=>{let n=f.get(e);if(n&&n.kind===t)return n;n&&b(n);let r={kind:t,n:0,ox:0,oy:0,buffers:{},color:[0,0,0,1],width:1};return f.set(e,r),r},w=(e,n,r)=>{let i=e.buffers[n]??=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,i),r.byteLength<=(v.get(i)??0)?t.bufferSubData(t.ARRAY_BUFFER,0,r):(t.bufferData(t.ARRAY_BUFFER,r,t.DYNAMIC_DRAW),v.set(i,r.byteLength))},T=(e,t,n,r)=>{let i=n.length;y.length<i&&(y=new Float32Array(i));for(let e=0;e<i;e++)y[e]=n[e]-r;w(e,t,y.subarray(0,i))},E=(e,t,n)=>{let r=new Uint8Array(e);t&&r.set(t.subarray(0,e)),e&&(r[0]=255);for(let t=0;t<e;t++)n(t)||(r[t]=255,t+1<e&&(r[t+1]=255));return r},D=(e,n,r=0,i=t.FLOAT)=>{if(e<0)return;t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(e);let a=i===t.FLOAT?4:1;t.vertexAttribPointer(e,1,i,i!==t.FLOAT,a,r*a),t.vertexAttribDivisor(e,1)},O=(n,r,i)=>{t.useProgram(n.prog),t.uniform2f(n.u.u_resolution,p,m),t.uniform4f(n.u.u_plot,_.left,_.top,_.width,_.height),t.uniform4f(n.u.u_view,g.xmin-r.ox,g.xmax-r.ox,g.ymin-r.oy,g.ymax-r.oy),t.uniform4f(n.u.u_clip,_.left,_.top,_.left+_.width,_.top+_.height),t.uniform1f(n.u.u_dpr,h),t.uniform1f(n.u.u_height,e.height),t.bindBuffer(t.ARRAY_BUFFER,i),t.enableVertexAttribArray(n.a.a_corner),t.vertexAttribPointer(n.a.a_corner,2,t.FLOAT,!1,0,0),t.vertexAttribDivisor(n.a.a_corner,0)},k=e=>{for(let n of Object.values(e.a))n>=0&&t.vertexAttribDivisor(n,0)};return{resize(t,n,r){p=Math.max(1,t),m=Math.max(1,n),h=r,e.width=Math.round(p*h),e.height=Math.round(m*h)},setView(e,t,n,r,i){g={xmin:e,xmax:t,ymin:n,ymax:r},_=i},setBands(e,t,n,r,i,a){let o=C(e,`bands`),s=Math.min(t.length,n.length,r.length);o.ox=vq(t),o.oy=vq(r),T(o,`x`,t,o.ox),T(o,`lo`,n,o.oy),T(o,`hi`,r,o.oy),w(o,`start`,E(s,a,e=>t[e]-t[e]===0&&n[e]-n[e]===0&&r[e]-r[e]===0)),o.n=Math.max(0,s-1),o.color=i},setRects(e,n,r,i,a,o,s){let c=C(e,`rects`),l=Math.min(n.length,r.length,i.length,a.length);c.ox=vq(n),c.oy=vq(i),T(c,`x0`,n,c.ox),T(c,`x1`,r,c.ox),T(c,`y0`,i,c.oy),T(c,`y1`,a,c.oy),s?T(c,`k`,s,0):delete c.buffers.k;let u=new Uint8Array(256*4);for(let e=0;e<256;e++){let t=o[Math.min(e,o.length-1)]??[0,0,0,1];u.set([t[0]*255,t[1]*255,t[2]*255,t[3]*255],e*4)}c.palette??=t.createTexture(),t.bindTexture(t.TEXTURE_2D,c.palette),t.texImage2D(t.TEXTURE_2D,0,t.RGBA8,256,1,0,t.RGBA,t.UNSIGNED_BYTE,u),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),c.n=l},setLine(e,t,n,r,i,a){let o=C(e,`line`),s=Math.min(t.length,n.length);o.ox=vq(t),o.oy=vq(n),T(o,`x`,t,o.ox),T(o,`y`,n,o.oy),w(o,`start`,E(s,a,e=>t[e]-t[e]===0&&n[e]-n[e]===0)),o.n=Math.max(0,s-1),o.color=r,o.width=i},maxTextureSize:c,setGrid(e,n,r,i,a,o,s,c){let l=C(e,`grid`),u=r*i,d=0;for(let e=0;e<u;e++)d+=n[e]*0;let f=n.subarray(0,u);if(d!==0){x.length<u&&(x=new Float32Array(u));for(let e=0;e<u;e++){let t=n[e];x[e]=t===t?t:_q}f=x.subarray(0,u)}let p=!l.values;l.values??=t.createTexture(),t.bindTexture(t.TEXTURE_2D,l.values),t.pixelStorei(t.UNPACK_ALIGNMENT,4),!p&&l.grid&&l.grid.w===r&&l.grid.h===i?t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,i,t.RED,t.FLOAT,f):(t.texImage2D(t.TEXTURE_2D,0,t.R32F,r,i,0,t.RED,t.FLOAT,f),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)),l.palette??=t.createTexture(),S(l.palette,o);let[m,h,g,_]=a;l.ox=m,l.oy=g,l.grid={w:r,h:i,x0:m,x1:h,y0:g,y1:_,vmin:s,vmax:c},l.n=1},setGridRange(e,t,n){let r=f.get(e);r?.grid&&(r.grid.vmin=t,r.grid.vmax=n)},remove(e){let t=f.get(e);t&&(b(t),f.delete(e))},keep(e){let t=new Set(e);for(let e of[...f.keys()])t.has(e)||this.remove(e)},render(){t.bindFramebuffer(t.FRAMEBUFFER,null),t.viewport(0,0,e.width,e.height),t.disable(t.SCISSOR_TEST),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.bindVertexArray(l),t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA);for(let e of f.values()){if(e.n<=0)continue;let n=e.buffers;if(e.kind===`bands`)O(i,e,u),t.uniform4f(i.u.u_color,...e.color),D(i.a.a_xa,n.x,0),D(i.a.a_xb,n.x,1),D(i.a.a_loa,n.lo,0),D(i.a.a_lob,n.lo,1),D(i.a.a_hia,n.hi,0),D(i.a.a_hib,n.hi,1),D(i.a.a_bstart,n.start,1,t.UNSIGNED_BYTE),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,e.n),k(i);else if(e.kind===`grid`){let n=e.grid;O(s,e,u),t.uniform4f(s.u.u_extent,0,n.x1-n.x0,0,n.y1-n.y0),t.uniform2f(s.u.u_range,n.vmin,n.vmax),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e.values),t.uniform1i(s.u.u_values,0),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,e.palette),t.uniform1i(s.u.u_palette,1),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.activeTexture(t.TEXTURE0)}else e.kind===`rects`?(O(a,e,u),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e.palette),t.uniform1i(a.u.u_palette,0),D(a.a.a_x0,n.x0),D(a.a.a_x1,n.x1),D(a.a.a_y0,n.y0),D(a.a.a_y1,n.y1),n.k?D(a.a.a_k,n.k):(t.disableVertexAttribArray(a.a.a_k),t.vertexAttrib1f(a.a.a_k,0)),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,e.n),k(a)):(O(o,e,d),t.uniform4f(o.u.u_color,...e.color),t.uniform1f(o.u.u_half,e.width/2),t.uniform1f(o.u.u_ext,e.width/2+1.5),D(o.a.a_ax,n.x,0),D(o.a.a_bx,n.x,1),D(o.a.a_ay,n.y,0),D(o.a.a_by,n.y,1),D(o.a.a_bstart,n.start,1,t.UNSIGNED_BYTE),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,e.n),k(o))}t.bindVertexArray(null)},dispose(){for(let e of f.values())b(e);f.clear(),t.deleteBuffer(u),t.deleteBuffer(d),t.deleteVertexArray(l)}}}function bq(e){let t=K({plot:null,failed:!1,size:``});return W(()=>()=>{t.current.plot?.dispose(),t.current.plot=null},[]),yt((n,r)=>{let i=t.current,a=e.current;if(!i.plot&&!i.failed&&a&&(i.plot=dH(a,yq),i.failed=!i.plot),!i.plot||!a)return null;let o=Math.min(2,window.devicePixelRatio||1),s=`${n}x${r}@${o}`;return i.size!==s&&(i.plot.resize(n,r,o),a.style.width=`${n}px`,a.style.height=`${r}px`,i.size=s),i.plot},[e])}function xq(e){let t=!1;for(let n=0;n<e.length;n++)if(Math.abs(e[n])>Math.PI*2){t=!0;break}let n=new Float64Array(e.length);for(let r=0;r<e.length;r++)n[r]=t?e[r]*Math.PI/180:e[r];return n}var Sq=16;function Cq(e,t,n,r){let i=xq(e),a=Math.min(i.length,t.length),o=1/0,s=-1/0;for(let e=0;e<a;e++){let n=t[e];n<o&&(o=n),n>s&&(s=n)}let c=n??Math.min(0,o),l=r??s,u=l-c||1,d=new Float64Array(a),f=new Float64Array(a),p=new Float64Array(Sq),m=new Int32Array(Sq);for(let e=0;e<a;e++){let n=Math.max(0,(t[e]-c)/u),r=i[e];n>1.0001?d[e]=f[e]=NaN:(d[e]=Math.sin(r)*n,f[e]=Math.cos(r)*n);let a=r%(2*Math.PI);a<0&&(a+=2*Math.PI);let o=Math.min(Sq-1,Math.floor(a/(2*Math.PI)*Sq));p[o]+=t[e],m[o]++}return{n:a,rMin:c,rMax:l,x:d,y:f,means:Array.from({length:Sq},(e,t)=>m[t]>0?p[t]/m[t]:0)}}function wq({angles:e,radii:t,angleLabel:n,radiusLabel:r,color:i=`#a78bfa`,mode:a=`waveform`,radiusMin:o,radiusMax:s,height:c=400,backgroundToken:l=``,onPlotContextMenu:u}){let d=K(null),f=K(null),p=K(null),m=K(u);G(()=>{m.current=u},[u]);let h=K({angles:e,radii:t,angleLabel:n,radiusLabel:r,color:i,mode:a,radiusMin:o,radiusMax:s,height:c});G(()=>{h.current={angles:e,radii:t,angleLabel:n,radiusLabel:r,color:i,mode:a,radiusMin:o,radiusMax:s,height:c}},[e,t,n,r,i,a,o,s,c]);let g=St(()=>Cq(e,t,o,s),[e,t,o,s]),_=K(g);G(()=>{_.current=g},[g]);let v=K(null),y=bq(v),b=K({geo:null,color:``});function x(){if(p.current)return p.current;let e=f.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return p.current=n,n}function S(){let e=f.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||h.current.height)}}function C(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function w(){let e=d.current;if(!e)return;let{w:t,h:n}=S(),r=C(e,t,n);if(!r)return;let{bg:i,muted:a,grid:o}=x(),{angleLabel:s,radiusLabel:c,color:l,mode:u}=h.current,f=_.current,{n:p,rMin:m,rMax:g}=f;r.fillStyle=i,r.fillRect(0,0,t,n);let v=y(t,n);if(p===0){v?.keep([]),v?.render(),r.fillStyle=a,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let w=g-m||1,T=(Math.min(t-64,n-32-24)-4)/2,E=t/2,D=32+T,O=Pz(w,4),k=Lz(m,g,O);r.strokeStyle=o,r.lineWidth=1,r.setLineDash([3,3]);for(let e of k){let t=(e-m)/w*T;t<0||(r.beginPath(),r.arc(E,D,t,0,Math.PI*2),r.stroke())}r.setLineDash([]),r.strokeStyle=o,r.lineWidth=1;for(let e=0;e<360;e+=30){let t=e*Math.PI/180;r.beginPath(),r.moveTo(E,D),r.lineTo(E+Math.cos(-t+Math.PI/2)*T,D+Math.sin(-t+Math.PI/2)*T),r.stroke()}r.fillStyle=a,r.font=`10px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`middle`;for(let e=0;e<360;e+=30){let t=e*Math.PI/180,n=E+Math.sin(t)*(T+14),i=D-Math.cos(t)*(T+14);r.fillText(`${e}°`,n,i)}r.textAlign=`left`,r.textBaseline=`middle`;for(let e of k){let t=(e-m)/w*T;t<4||r.fillText(Vz(e,O),E+4,D-t)}if(r.strokeStyle=a,r.lineWidth=1,r.setLineDash([]),r.beginPath(),r.arc(E,D,T,0,Math.PI*2),r.stroke(),r.save(),r.beginPath(),r.arc(E,D,T,0,Math.PI*2),r.clip(),u===`waveform`)if(v)(b.current.geo!==f||b.current.color!==l)&&(v.setLine(`wave`,f.x,f.y,NK(l,.9),1),b.current={geo:f,color:l}),v.keep([`wave`]),v.setView(-1,1,-1,1,{left:E-T,top:D-T,width:T*2,height:T*2}),v.render();else{r.strokeStyle=l,r.lineWidth=1,r.globalAlpha=.9,r.beginPath();let e=!1;for(let t=0;t<p;t++){let n=E+f.x[t]*T,i=D-f.y[t]*T;if(n!==n){e=!1;continue}e?r.lineTo(n,i):(r.moveTo(n,i),e=!0)}r.stroke(),r.globalAlpha=1}else{v?.keep([]),v?.render();let e=f.means,t=Math.max(...e,1e-10),n=2*Math.PI/Sq;r.fillStyle=l,r.globalAlpha=.75;for(let i=0;i<Sq;i++){let a=e[i]/t*T,o=i*n-Math.PI/2-n/2;r.beginPath(),r.moveTo(E,D),r.arc(E,D,a,o,o+n),r.closePath(),r.fill()}r.globalAlpha=1,r.strokeStyle=l,r.lineWidth=.5,r.globalAlpha=.4;for(let i=0;i<Sq;i++){let a=e[i]/t*T,o=i*n-Math.PI/2-n/2;r.beginPath(),r.moveTo(E,D),r.arc(E,D,a,o,o+n),r.closePath(),r.stroke()}r.globalAlpha=1}r.restore(),r.fillStyle=a,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(`${s} / ${c}`,E,n-4)}let T=K(w);T.current=w;let E=K(null);E.current??=KH(()=>T.current(),()=>f.current);let D=()=>E.current.schedule();return W(()=>{E.current.now()}),W(()=>()=>E.current?.cancel(),[]),W(()=>{p.current=null,D()},[l]),G(()=>{let e=f.current;if(!e)return;let t=new WH(()=>{p.current=null,D()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=d.current;if(!e)return;let t=e=>{e.preventDefault(),m.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),Ot(`div`,{ref:f,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:d,className:`chart-canvas`,role:`img`,"aria-label":`Polar chart: ${n} vs ${r}`}),q(`canvas`,{ref:v,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}})]})}function Tq(e,t,n,r,i){let a=Math.min(e.length,t.length),o=(t,n)=>{let r=0,i=a;for(;r<i;){let a=r+i>>>1;(n?e[a]<=t:e[a]<t)?r=a+1:i=a}return r},s=o(n,!1),c=o(r,!0),l=Math.max(0,s-1),u=Math.min(a,c+1);if(u-l<=2*i){let e=new Uint32Array(u-l);for(let t=0;t<e.length;t++)e[t]=l+t;return e}let d=new Uint32Array(2*i+2),f=0;s>0&&(d[f++]=s-1);let p=(r-n)/i,m=s;for(let r=0;r<i&&m<c;r++){let a=r===i-1?1/0:n+(r+1)*p,o=1/0,s=-1/0,l=-1,u=-1;for(;m<c&&e[m]<a;m++){let e=t[m];e<o&&(o=e,l=m),e>s&&(s=e,u=m)}l<0||(l===u?d[f++]=l:l<u?(d[f++]=l,d[f++]=u):(d[f++]=u,d[f++]=l))}return c<a&&(d[f++]=c),d.subarray(0,f)}function Eq(e,t){let n=e.length;if(n<=2*t)return Uint32Array.from({length:n},(e,t)=>t);let r=new Uint32Array(2*t),i=0;for(let a=0;a<t;a++){let o=Math.floor(a*n/t),s=Math.floor((a+1)*n/t),c=1/0,l=-1/0,u=-1,d=-1;for(let t=o;t<s;t++){let n=e[t];n<c&&(c=n,u=t),n>l&&(l=n,d=t)}u<0||(u===d?r[i++]=u:u<d?(r[i++]=u,r[i++]=d):(r[i++]=d,r[i++]=u))}return r.subarray(0,i)}function Dq(e,t){let n=new Float64Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n}function Oq(e){for(let t=1;t<e.length;t++)if(!(e[t]>=e[t-1]))return!1;return e.length===0||e[0]===e[0]}function kq(e,t){let n=e.length;for(let r=1,i=0;r<n;r++){let a=n>>1;for(;i&a;a>>=1)i^=a;if(i^=a,r<i){let n=e[r];e[r]=e[i],e[i]=n,n=t[r],t[r]=t[i],t[i]=n}}for(let r=2;r<=n;r<<=1){let i=r>>1,a=-2*Math.PI/r,o=Math.cos(a),s=Math.sin(a);for(let a=0;a<n;a+=r){let n=1,r=0;for(let c=0;c<i;c++){let l=a+c,u=l+i,d=e[u]*n-t[u]*r,f=e[u]*r+t[u]*n;e[u]=e[l]-d,t[u]=t[l]-f,e[l]+=d,t[l]+=f;let p=n*o-r*s;r=n*s+r*o,n=p}}}}var Aq=new Float64Array,jq=new Float64Array;function Mq(e,t,n){let r=t>>1;Aq.length<r&&(Aq=new Float64Array(r),jq=new Float64Array(r));let i=Aq.subarray(0,r),a=jq.subarray(0,r),o=e.length;for(let t=0;t<r;t++){let r=2*t,s=r+1;i[t]=r<o?e[r]*(n?n[r]:1):0,a[t]=s<o?e[s]*(n?n[s]:1):0}kq(i,a);let s=new Float64Array(r),c=-2*Math.PI/t,l=Math.cos(c),u=Math.sin(c),d=1,f=0;for(let e=0;e<r;e++){let t=e===0?0:r-e,n=i[e],o=a[e],c=i[t],p=-a[t],m=(n+c)/2,h=(o+p)/2,g=(o-p)/2,_=-(n-c)/2,v=m+d*g-f*_,y=h+d*_+f*g;s[e]=Math.sqrt(v*v+y*y);let b=d*l-f*u;f=d*u+f*l,d=b}return s}var Nq=new Float64Array,Pq=0;function Fq(e){if(Pq===e)return Nq.subarray(0,e);Nq.length<e&&(Nq=new Float64Array(Math.max(e,Nq.length*2)));let t=2*Math.PI/Math.max(1,e-1),n=Math.cos(t),r=Math.sin(t),i=1,a=0;for(let t=0;t<e;t++){Nq[t]=.5*(1-i);let e=i*n-a*r;a=a*n+i*r,i=e}return Pq=e,Nq.subarray(0,e)}var Iq={top:14,right:24,bottom:40,left:64},Lq=5;function Rq(e){let t=1;for(;t<e;)t<<=1;return t}function zq(e,t,n,r){let i=e.length,a=Math.max(2,Rq(i)),o=Mq(e,a,n===`hann`?Fq(i):void 0),s=a/2,c=new Float64Array(s),l=2/a;for(let e=0;e<s;e++){c[e]=e*t/a;let n=o[e]*l;o[e]=r===`db`?20*Math.log10(Math.max(n,1e-12)):n}return{freqs:c,amps:o}}function Bq({signal:e,sampleRate:t=1,label:n,xMode:r=`hz`,yMode:i=`amplitude`,window:a=`hann`,color:o=`#34d399`,logX:s=!1,height:c=400,backgroundToken:l=``,onPlotContextMenu:u}){let d=IU(),f=K(null),p=K(null),m=K(null),h=K(u);G(()=>{h.current=u},[u]);let g=K({signal:e,sampleRate:t,label:n,xMode:r,yMode:i,window:a,color:o,logX:s,height:c});G(()=>{g.current={signal:e,sampleRate:t,label:n,xMode:r,yMode:i,window:a,color:o,logX:s,height:c}},[e,t,n,r,i,a,o,s,c]);let _=St(()=>e.length>=4?zq(e,t,a,i):null,[e,t,a,i]),v=St(()=>_&&s?_.freqs.map(e=>Math.log10(e)):null,[_,s]),y=K(_&&{..._,logFreqs:v});G(()=>{y.current=_&&{..._,logFreqs:v}},[_,v]);function b(){if(m.current)return m.current;let e=p.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return m.current=n,n}function x(){let e=p.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||g.current.height)}}function S(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function C(){let e=f.current;if(!e)return;let{w:t,h:n}=x(),r=S(e,t,n);if(!r)return;let{top:i,right:a,bottom:o,left:s}=Iq,c=t-s-a,l=n-i-o,{bg:u,muted:p,grid:m}=b(),{sampleRate:h,label:_,xMode:v,yMode:C,color:w,logX:T}=g.current,E=y.current;if(r.fillStyle=u,r.fillRect(0,0,t,n),!E||c<=0||l<=0){r.fillStyle=p,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{freqs:D,amps:O,logFreqs:k}=E,A=D.length,j=v===`hz`?`${_} (Hz)`:`${_} (order)`,M=v===`order`&&h>0?h:1,N=D[1]/M,P=D[A-1]/M,F=1/0,I=-1/0;for(let e=1;e<A;e++)O[e]<F&&(F=O[e]),O[e]>I&&(I=O[e]);if(!Number.isFinite(F)||!Number.isFinite(I)){r.fillStyle=p,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let L=(I-F)*.05||.1;F-=L,I+=L;let R=T?e=>{if(e<=0||N<=0)return s;let t=Math.log10(N),n=Math.log10(P);return s+(Math.log10(e)-t)/(n-t)*c}:e=>s+(e-N)/(P-N)*c;T&&N<=0&&(N=D[1]>0?D[1]/M:.001),d({left:s,top:i,width:c,height:l,x:{v0:N,v1:P,log:T},y:{v0:F,v1:I}});let z=e=>i+(I-e)/(I-F)*l,B=Pz(I-F,5),V=Lz(F,I,B);r.strokeStyle=m,r.lineWidth=1,r.setLineDash([3,3]);for(let e of V)r.beginPath(),r.moveTo(s,z(e)),r.lineTo(s+c,z(e)),r.stroke();r.setLineDash([]);let ee=T?1:Pz(P-N,Fz(c)),te=T?(()=>{let e=[],t=Math.ceil(Math.log10(Math.max(N,1e-12))),n=Math.floor(Math.log10(P));for(let r=t;r<=n;r++)for(let t of[1,2,5]){let n=t*10**r;n>=N&&n<=P&&e.push(n)}return e})():Lz(N,P,ee);r.strokeStyle=m,r.lineWidth=1,r.setLineDash([3,3]);for(let e of te)r.beginPath(),r.moveTo(R(e),i),r.lineTo(R(e),i+l),r.stroke();r.setLineDash([]),r.strokeStyle=p,r.lineWidth=1,r.fillStyle=p,r.font=`11px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of V)r.beginPath(),r.moveTo(s-Lq,z(e)),r.lineTo(s,z(e)),r.stroke(),r.fillText(Vz(e,B),s-4,z(e));r.textAlign=`center`,r.textBaseline=`top`;for(let e of te)r.beginPath(),r.moveTo(R(e),i+l),r.lineTo(R(e),i+l+Lq),r.stroke(),r.fillText(Vz(e,T?e:ee),R(e),i+l+Lq+2);r.strokeStyle=m,r.lineWidth=1,r.strokeRect(s,i,c,l),r.save(),r.beginPath(),r.rect(s,i,c,l),r.clip(),r.strokeStyle=w,r.lineWidth=1,r.beginPath();let H=!1,ne=Math.min(2,window.devicePixelRatio||1),re=Math.max(1,Math.round(c*ne)),ie=A>re*4?T&&k?Tq(k,O,Math.log10(N*M),Math.log10(P*M),re):Tq(D,O,N*M,P*M,re):null;for(let e=+!ie;e<(ie?ie.length:A);e++){let t=ie?ie[e]:e;if(t<1)continue;let n=D[t]/M;if(n<N||n>P)continue;let i=R(n),a=z(O[t]);H?r.lineTo(i,a):(r.moveTo(i,a),H=!0)}r.stroke(),r.restore(),r.fillStyle=p,r.font=`11px ${Q.mono}`,r.save(),r.translate(14,i+l/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(C===`db`?`dB`:`Amplitude`,0,0),r.restore(),r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(j,s+c/2,n-4)}let w=K(C);w.current=C;let T=K(null);T.current??=KH(()=>w.current(),()=>p.current);let E=()=>T.current.schedule();return W(()=>{T.current.now()}),W(()=>()=>T.current?.cancel(),[]),W(()=>{m.current=null,E()},[l]),G(()=>{let e=p.current;if(!e)return;let t=new WH(()=>{m.current=null,E()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=f.current;if(!e)return;let t=e=>{e.preventDefault(),h.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),q(`div`,{ref:p,style:{position:`relative`,width:`100%`,height:`100%`},children:q(`canvas`,{ref:f,className:`chart-canvas`,role:`img`,"aria-label":`Spectrum of ${n}`})})}function Vq(e,t,n=0,r=e.length-1){for(;r>n;){let i=n+r>>>1,a=e[n],o=e[i],s=e[r];if(a>o){let e=a;a=o,o=e}o>s&&(o=s),a>o&&(o=a);let c=o,l=n,u=r;for(;l<=u;){for(;e[l]<c;)l++;for(;e[u]>c;)u--;if(l<=u){let t=e[l];e[l]=e[u],e[u]=t,l++,u--}}if(t<=u)r=u;else if(t>=l)n=l;else break}return e[t]}function Hq(e,t){let n=e.length;if(n===0)return t.map(()=>0);let r=[...new Set(t.flatMap(e=>{let t=e/100*(n-1);return[Math.floor(t),Math.ceil(t)]}))].sort((e,t)=>e-t),i=new Map,a=0;for(let t of r)i.set(t,Vq(e,t,a)),a=t;return t.map(e=>{let t=e/100*(n-1),r=Math.floor(t);return i.get(r)+(i.get(Math.ceil(t))-i.get(r))*(t-r)})}var Uq={top:14,right:24,bottom:48,left:64},Wq=5;function Gq(e,t){let n=e.length;if(n===0)return null;let[r,i,a,o,s]=Hq(Float64Array.from(e),[0,25,50,75,100]),c=0;for(let t=0;t<n;t++)c+=e[t];let l=c/n;if(t!==`1.5iqr`)return{q1:i,median:a,q3:o,mean:l,whiskerLo:r,whiskerHi:s,outliers:new Float64Array};let u=o-i,d=i-1.5*u,f=o+1.5*u,p=1/0,m=-1/0,h=0;for(let t=0;t<n;t++){let n=e[t];if(n<d||n>f){h++;continue}n<p&&(p=n),n>m&&(m=n)}let g=new Float64Array(h);for(let t=0,r=0;t<n;t++){let n=e[t];(n<d||n>f)&&(g[r++]=n)}return g.sort(),{q1:i,median:a,q3:o,mean:l,whiskerLo:p<=m?p:i,whiskerHi:p<=m?m:o,outliers:g}}function Kq({groups:e,color:t=`#fb923c`,whiskers:n=`1.5iqr`,height:r=400,backgroundToken:i=``,onPlotContextMenu:a}){let o=IU(),s=K(null),c=K(null),l=K(null),u=K(a);G(()=>{u.current=a},[a]);let d=K({groups:e,color:t,whiskers:n,height:r});G(()=>{d.current={groups:e,color:t,whiskers:n,height:r}},[e,t,n,r]);let f=St(()=>e.filter(e=>e.values.length>0).map(e=>({label:e.label,box:Gq(e.values,n)})),[e,n]),p=K(f);G(()=>{p.current=f},[f]);function m(){if(l.current)return l.current;let e=c.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return l.current=n,n}function h(){let e=c.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||d.current.height)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function _(){let e=s.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;let{top:i,right:a,bottom:c,left:l}=Uq,u=t-l-a,f=n-i-c,{bg:_,muted:v,grid:y}=m(),{color:b}=d.current;r.fillStyle=_,r.fillRect(0,0,t,n);let x=p.current;if(x.length===0||u<=0||f<=0){r.fillStyle=v,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let S=1/0,C=-1/0;for(let e of x){e.box.whiskerLo<S&&(S=e.box.whiskerLo),e.box.whiskerHi>C&&(C=e.box.whiskerHi);for(let t of e.box.outliers)t<S&&(S=t),t>C&&(C=t)}let w=(C-S)*.08||1;S-=w,C+=w;let T=e=>i+(C-e)/(C-S)*f;o({left:l,top:i,width:u,height:f,y:{v0:S,v1:C}});let E=Pz(C-S,5),D=Lz(S,C,E);r.strokeStyle=y,r.lineWidth=1,r.setLineDash([3,3]);for(let e of D)r.beginPath(),r.moveTo(l,T(e)),r.lineTo(l+u,T(e)),r.stroke();r.setLineDash([]),r.strokeStyle=v,r.lineWidth=1,r.fillStyle=v,r.font=`11px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of D)r.beginPath(),r.moveTo(l-Wq,T(e)),r.lineTo(l,T(e)),r.stroke(),r.fillText(Vz(e,E),l-4,T(e));r.strokeStyle=y,r.lineWidth=1,r.strokeRect(l,i,u,f),r.save(),r.beginPath(),r.rect(l,i,u,f),r.clip();let O=x.length,k=u/O,A=Math.min(k*.55,60);for(let e=0;e<O;e++){let{box:t}=x[e],n=l+k*e+k/2;r.strokeStyle=b,r.lineWidth=1.5,r.beginPath(),r.moveTo(n,T(t.whiskerLo)),r.lineTo(n,T(t.whiskerHi)),r.stroke();let i=A*.35;r.beginPath(),r.moveTo(n-i,T(t.whiskerLo)),r.lineTo(n+i,T(t.whiskerLo)),r.moveTo(n-i,T(t.whiskerHi)),r.lineTo(n+i,T(t.whiskerHi)),r.stroke();let a=n-A/2,o=T(t.q3),s=Math.max(1,T(t.q1)-o);r.fillStyle=b,r.globalAlpha=.25,r.fillRect(a,o,A,s),r.globalAlpha=1,r.strokeStyle=b,r.lineWidth=1.5,r.strokeRect(a,o,A,s),r.strokeStyle=b,r.lineWidth=2.5,r.beginPath(),r.moveTo(a,T(t.median)),r.lineTo(a+A,T(t.median)),r.stroke();let c=T(t.mean);r.fillStyle=b,r.beginPath(),r.moveTo(n,c-5),r.lineTo(n+5,c),r.lineTo(n,c+5),r.lineTo(n-5,c),r.closePath(),r.fill(),r.fillStyle=b,r.globalAlpha=.6;let u=NaN;for(let e of t.outliers){let t=T(e);Math.abs(t-u)<.5||(u=t,r.beginPath(),r.arc(n,t,2.5,0,Math.PI*2),r.fill())}r.globalAlpha=1}r.restore(),r.fillStyle=v,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`;for(let e=0;e<O;e++){let t=l+k*e+k/2,n=x[e].label;r.save(),r.rect(l+k*e+2,i+f+Wq+2,k-4,c-Wq-4),r.clip(),r.fillText(n,t,i+f+Wq+2),r.restore()}}let v=K(_);v.current=_;let y=K(null);y.current??=KH(()=>v.current(),()=>c.current);let b=()=>y.current.schedule();return W(()=>{y.current.now()}),W(()=>()=>y.current?.cancel(),[]),W(()=>{l.current=null,b()},[i]),G(()=>{let e=c.current;if(!e)return;let t=new WH(()=>{l.current=null,b()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=s.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),q(`div`,{ref:c,style:{position:`relative`,width:`100%`,height:`100%`},children:q(`canvas`,{ref:s,className:`chart-canvas`,role:`img`,"aria-label":`Box plot`})})}function qq(e,t){if(e.w<=t)return{grid:e,per:1};let n=e.w/t,r=new Float32Array(t*e.h);for(let i=0;i<e.h;i++){let a=i*e.w;for(let o=0;o<t;o++){let s=Math.floor(o*n),c=Math.min(e.w,Math.floor((o+1)*n)),l=0,u=0;for(let t=s;t<c;t++){let n=e.values[a+t];n===n&&(l+=n,u++)}r[i*t+o]=u?l/u:NaN}}let i=e.xLabels;return{grid:{w:t,h:e.h,values:r,xLabels:e=>typeof i==`function`?i(Math.floor(e*n)):i[Math.floor(e*n)],yLabels:e.yLabels},per:n}}var Jq=e=>e.includes(`.`)&&!e.includes(`e`)?e.replace(/\.?0+$/,``):e;function Yq(e){return e>=1e3?`${Jq((e/1e3).toPrecision(3))}k`:Jq(e.toPrecision(3))}function Xq(e,t,n,r,i,a,o){let s=t>>1,c=e.length,l=c>=t?Math.floor((c-t)/n)+1:0,u=`${t}|${n}|${r}|${i}|${a?a.join(`,`):``}`,d=-1,f=0;if(o&&o.key===u&&o.frames>0&&c>0){let r=o.sig;for(let i=0;i*n<r.length&&f===0;i++){let a=i*n;if(r[a]!==e[0])continue;let s=Math.min(r.length-a,c),u=!0;for(let t=0;t<s;t++)if(r[a+t]!==e[t]){u=!1;break}if(!u)continue;let p=s>=t?Math.floor((s-t)/n)+1:0;d=i,f=Math.max(0,Math.min(p,o.frames-i,l))}}let p=new Float32Array(l*s),m=new Float32Array(l);if(f>0){for(let e=0;e<s;e++)p.set(o.values.subarray(e*o.frames+d,e*o.frames+d+f),e*l);m.set(o.frameMax.subarray(d,d+f))}let h=new Float64Array(t);for(let e=0;e<t;e++)h[e]=r?.5*(1-Math.cos(2*Math.PI*e/(t-1))):1;let g=Math.log2(t),_=new Uint32Array(t);for(let e=0;e<t;e++){let t=0,n=e;for(let e=0;e<g;e++)t=t<<1|n&1,n>>=1;_[e]=t}let v=new Float64Array(t),y=new Float64Array(t),b=new Float64Array(s);for(let r=f;r<l;r++){let o=r*n;for(let n=0;n<t;n++){let t=_[n];v[n]=e[o+t]*h[t],y[n]=0}for(let e=2;e<=t;e<<=1){let n=e>>1,r=-2*Math.PI/e,i=Math.cos(r),a=Math.sin(r);for(let r=0;r<t;r+=e){let e=1,t=0;for(let o=0;o<n;o++){let s=r+o,c=s+n,l=v[c]*e-y[c]*t,u=v[c]*t+y[c]*e;v[c]=v[s]-l,y[c]=y[s]-u,v[s]+=l,y[s]+=u;let d=e*i-t*a;t=e*a+t*i,e=d}}}let c=0;for(let e=0;e<s;e++){let n=Math.sqrt(v[e]*v[e]+y[e]*y[e])/t;b[e]=n,n>c&&(c=n)}m[r]=c;for(let e=0;e<s;e++){let t=b[a?a[e]:e];p[e*l+r]=i?20*Math.log10(Math.max(t,1e-12)):t}}let x=1e-10;for(let e=0;e<l;e++)m[e]>x&&(x=m[e]);return{values:p,frames:l,bins:s,max:x,computed:l-f,sig:Float64Array.from(e),frameMax:m,key:u}}var Zq={top:14,right:24,bottom:40,left:68},Qq=[[8,0,16],[48,0,96],[104,0,144],[160,0,128],[200,32,64],[230,100,16],[250,200,32],[255,255,220]],$q=-80;function eJ(e){let t=Qq.length-1,n=Math.min(t-1,Math.floor(e*t)),r=e*t-n,[i,a,o]=Qq[n],[s,c,l]=Qq[n+1];return[i+(s-i)*r,a+(c-a)*r,o+(l-o)*r]}var tJ=(()=>{let e=new Uint8Array(256*4);for(let t=0;t<256;t++){let[n,r,i]=eJ(t/255);e.set([n,r,i,255],t*4)}return e})();function nJ(e){let t=1;for(;t<e;)t<<=1;return t}var rJ=(e,t)=>Math.log(1+e/t*9)/Math.log(10),iJ=(e,t)=>t*(10**e-1)/9;function aJ({signal:e,sampleRate:t=1e3,windowSize:n=512,overlap:r=.5,winFunc:i=`hann`,yMode:a=`db`,logFreq:o=!1,label:s=``,backgroundToken:c=``,onPlotContextMenu:l}){let u=IU(),d=K(null),f=K(null),p=K(null),m=K(null),h=K(null),g=K(l);G(()=>{g.current=l},[l]);let _=nJ(Math.max(4,Math.min(n,4096))),v=Math.max(1,Math.round(_*(1-Math.max(0,Math.min(.95,r))))),y=St(()=>{if(!o)return null;let e=_>>1,n=t/2;return Int32Array.from({length:e},(t,r)=>Math.min(e-1,Math.floor(iJ((r+.5)/e,n)/n*e)))},[o,_,t]),b=K(null),x=St(()=>b.current=Xq(e,_,v,i===`hann`,a===`db`,y,b.current),[e,_,v,i,a,y]),S=St(()=>({w:x.frames,h:x.bins,values:x.values,xLabels:[],yLabels:[]}),[x]),C=a===`db`?20*Math.log10(x.max):x.max,w=a===`db`?[C+$q,C]:[0,C],T=K({grid:S,range:w,sampleRate:t,winSz:_,step:v,yMode:a,logFreq:o,label:s});G(()=>{T.current={grid:S,range:w,sampleRate:t,winSz:_,step:v,yMode:a,logFreq:o,label:s}},[S,w[0],w[1],t,_,v,a,o,s]);let E=K({plot:null,failed:!1,size:``,grid:null,shown:null});W(()=>()=>{E.current.plot?.dispose(),E.current.plot=null},[]);function D(){if(h.current)return h.current;let e=m.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return h.current=n,n}function O(){let e=m.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function k(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function A(e,t){let n=E.current;if(!n.plot&&!n.failed&&f.current&&(n.plot=dH(f.current,yq),n.failed=!n.plot),!n.plot||!f.current)return null;let r=Math.min(2,window.devicePixelRatio||1),i=`${e}x${t}@${r}`;return n.size!==i&&(n.plot.resize(e,t,r),f.current.style.width=`${e}px`,f.current.style.height=`${t}px`,n.size=i),n.plot}function j(){let e=d.current;if(!e)return;let{w:t,h:n}=O(),r=k(e,t,n);if(!r)return;let i=p.current?k(p.current,t,n):null;i?.clearRect(0,0,t,n);let a=MG(Zq,t,n),{top:o,right:s,bottom:c,left:l}=a,f=t-l-s,h=n-o-c,{bg:g,muted:_,grid:v}=D(),{grid:y,sampleRate:b,winSz:x,step:S,logFreq:C,label:w}=T.current;r.fillStyle=g,r.fillRect(0,0,t,n);let j=A(t,n);if(y.w===0||f<=0||h<=0){if(j?.keep([]),j?.render(),a.tiny)return;r.fillStyle=_,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let M=Math.min(2,window.devicePixelRatio||1),N=j?j.maxTextureSize:Math.max(1,Math.round(f*M)),[P,F]=T.current.range;if(E.current.grid!==y||!E.current.shown||!j&&E.current.shown.w>N){let e=qq(y,N).grid;j&&j.setGrid(`cells`,e.values,e.w,Math.min(e.h,j.maxTextureSize),[0,e.w,0,e.h],tJ,P,F),E.current.grid=y,E.current.shown=e,VH(m.current)}let I=E.current.shown;if(j)j.keep([`cells`]),j.setGridRange(`cells`,P,F),j.setView(0,I.w,0,I.h,{left:l,top:o,width:f,height:h}),j.render();else{let e=document.createElement(`canvas`);e.width=I.w,e.height=I.h;let t=e.getContext(`2d`),n=t.createImageData(I.w,I.h);for(let e=0;e<I.h;e++)for(let t=0;t<I.w;t++){let[r,i,a]=eJ(Math.max(0,Math.min(1,(I.values[e*I.w+t]-P)/(F-P)))),o=(t+(I.h-1-e)*I.w)*4;n.data[o]=r,n.data[o+1]=i,n.data[o+2]=a,n.data[o+3]=255}t.putImageData(n,0,0),r.drawImage(e,l,o,f,h)}if(a.tiny)return;let L=i??r,R=b/2,z=e=>o+h*(1-(C?rJ(e,R):e/R));L.strokeStyle=v,L.lineWidth=.5,L.globalAlpha=.4;let B=Lz(0,R,Pz(R,5));L.setLineDash([3,4]);for(let e of B){let t=z(e);L.beginPath(),L.moveTo(l,t),L.lineTo(l+f,t),L.stroke()}L.setLineDash([]),L.globalAlpha=1,L.strokeStyle=v,L.strokeRect(l,o,f,h),r.fillStyle=_,r.font=`10px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`,r.strokeStyle=_,r.lineWidth=1;for(let e of B){let t=z(e);r.beginPath(),r.moveTo(l-4,t),r.lineTo(l,t),r.stroke(),r.fillText(Yq(e),l-6,t)}let V=(y.w*S+x)/b;u({left:l,top:o,width:f,height:h,x:{v0:0,v1:V}});let ee=Pz(V,6),te=Lz(0,V,ee);r.textAlign=`center`,r.textBaseline=`top`;for(let e of te){let t=l+e/V*f;r.beginPath(),r.moveTo(t,o+h),r.lineTo(t,o+h+4),r.stroke(),r.fillText(Vz(e,ee),t,o+h+6)}r.fillStyle=_,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(w||`Time (s)`,l+f/2,n-4),r.save(),r.translate(12,o+h/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.fillText(`Frequency (Hz)`,0,0),r.restore()}let M=K(j);G(()=>{M.current=j});let N=K(null);return N.current??=KH(()=>M.current(),()=>m.current),W(()=>{N.current.now()},[S,w[0],w[1],t,_,v,a,o,s]),W(()=>()=>N.current?.cancel(),[]),W(()=>{h.current=null,N.current.schedule()},[c]),G(()=>{let e=m.current;if(!e)return;let t=new WH(()=>{h.current=null,N.current.schedule()});return t.observe(e),()=>t.disconnect()},[]),G(()=>{let e=p.current;if(!e)return;let t=e=>{e.preventDefault(),g.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),Ot(`div`,{ref:m,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:d,className:`chart-canvas`,role:`img`,"aria-label":`Spectrogram`}),q(`canvas`,{ref:f,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:p,className:`chart-canvas chart-overlay`})]})}var oJ=300,sJ=256,cJ=-60,lJ=[];function uJ({signal:e,sampleRate:t,windowSize:n,overlap:r,winFunc:i,yMode:a,backgroundToken:o,onPlotContextMenu:s}){let c=2**Math.ceil(Math.log2(Math.max(4,Math.min(n,4096)))),l=Math.max(1,Math.round(c*(1-Math.max(0,Math.min(.95,r))))),u=a===`db`,d=St(()=>Xq(e,c,l,i===`hann`,u,null),[e,c,l,i,u]);return q($K,{points:lJ,surface:St(()=>dJ(d,t,c,l,u),[d,t,c,l,u]),xLabel:`Time (s)`,yLabel:`Frequency (Hz)`,zLabel:u?`Level (dB)`:`Amplitude`,viewMode:`3d`,showMesh:!0,meshStyle:`filled`,meshOpacity:1,backgroundToken:o,onPlotContextMenu:s})}function dJ(e,t,n,r,i){let{frames:a,bins:o,values:s}=e;if(a<2||o<2)return;let c=Math.min(a,oJ),l=Math.min(o,sJ),u=i?20*Math.log10(Math.max(e.max,1e-12))+cJ:-1/0,d=new Float32Array(c*l);for(let e=0;e<l;e++){let t=Math.floor(e*o/l),n=Math.max(t+1,Math.floor((e+1)*o/l));for(let r=0;r<c;r++){let i=Math.floor(r*a/c),o=Math.max(i+1,Math.floor((r+1)*a/c)),l=-1/0;for(let e=t;e<n;e++)for(let t=i;t<o;t++){let n=s[e*a+t];n>l&&(l=n)}d[e*c+r]=Math.max(u,l)}}let f=e=>(e*r+n/2)/t;return{w:c,h:l,values:d,x:[f(0),f(a-1)],y:[0,(o-1)*t/n]}}function fJ(e,t,n){return Array.from({length:n},(r,i)=>e+(i+1)/(n+1)*(t-e))}function pJ(e,t,n,r){let i=[],a=(n,r)=>e[r*t+n],o=(e,t)=>(r-e)/(t-e);for(let e=0;e+1<n;e++)for(let n=0;n+1<t;n++){let t=a(n,e),s=a(n+1,e),c=a(n+1,e+1),l=a(n,e+1);if(t!==t||s!==s||c!==c||l!==l)continue;let u=(t>=r?8:0)|(s>=r?4:0)|(c>=r?2:0)|l>=r;if(u===0||u===15)continue;let d=()=>[n+o(t,s),e],f=()=>[n+1,e+o(s,c)],p=()=>[n+o(l,c),e+1],m=()=>[n,e+o(t,l)],h=(e,t)=>i.push([e[0],e[1],t[0],t[1]]);switch(u){case 1:case 14:h(m(),p());break;case 2:case 13:h(p(),f());break;case 3:case 12:h(m(),f());break;case 4:case 11:h(d(),f());break;case 6:case 9:h(d(),p());break;case 7:case 8:h(m(),d());break;case 5:case 10:{let e=(t+s+c+l)/4>=r;u===5===e?(h(m(),d()),h(p(),f())):(h(d(),f()),h(m(),p()));break}}}return i}function mJ(e){let t=e.length,n=new Float64Array(t+1);if(t===1)return n[0]=e[0]-.5,n[1]=e[0]+.5,n;for(let r=1;r<t;r++)n[r]=(e[r-1]+e[r])/2;return n[0]=e[0]-(n[1]-e[0]),n[t]=e[t-1]+(e[t-1]-n[t-1]),n}function hJ(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t])||t>0&&!(e[t]>e[t-1]))return!1;return!0}var gJ={top:14,right:32,bottom:80,left:80};function _J(e,t,n){return[e[0]+(t[0]-e[0])*n,e[1]+(t[1]-e[1])*n,e[2]+(t[2]-e[2])*n]}var vJ=[[33,102,172],[103,169,207],[209,229,240],[247,247,247],[253,219,199],[239,138,98],[178,24,43]],yJ=[[13,8,135],[84,2,163],[139,10,165],[185,50,137],[219,92,104],[244,136,73],[254,188,43],[240,249,33]],bJ=[[68,1,84],[72,40,120],[62,83,160],[49,120,178],[38,153,185],[31,184,187],[53,213,158],[117,231,101],[198,239,82],[253,231,37]];function xJ(e,t){let n=e.length-1,r=Math.min(n-1,Math.floor(t*n));return _J(e[r],e[r+1],t*n-r)}function SJ(e,t){return xJ(t===`plasma`?yJ:t===`viridis`?bJ:vJ,e)}function CJ(e){let t=new Uint8Array(256*4);for(let n=0;n<256;n++){let[r,i,a]=SJ(n/255,e);t.set([r,i,a,255],n*4)}return t}function wJ(e){return Math.abs(e)>=1e4||Math.abs(e)<.01&&e!==0?e.toExponential(1):String(parseFloat(e.toPrecision(3)))}function TJ(e,t,n){let r=new Map(t.map((e,t)=>[e,t])),i=new Map(n.map((e,t)=>[e,t])),a=new Float32Array(t.length*n.length);for(let n of e){let e=r.get(n.x),o=i.get(n.y);e!==void 0&&o!==void 0&&(a[o*t.length+e]=n.value)}return{w:t.length,h:n.length,values:a,xLabels:t,yLabels:n}}function EJ(e,t,n,r,i,a,o){let s=(e,t,n)=>Float64Array.from({length:e+1},(r,i)=>t+i/e*n),c=!!a&&a.length===e.w,l=!!o&&o.length===e.h,u=s(e.w,t,r),d=s(e.h,n,i);if(c){let n=mJ(a),i=n[e.w]-n[0];u=Float64Array.from(n,e=>t+(e-n[0])/i*r)}if(l){let t=mJ(Float64Array.from(o).reverse()),r=e.h,a=t[r]-t[0];d=Float64Array.from({length:r+1},(e,o)=>n+(t[r]-t[r-o])/a*i)}return{xB:u,yB:d,byValue:c||l}}function DJ(e,t){if(t<e[0]||t>=e[e.length-1])return-1;let n=0,r=e.length-1;for(;r-n>1;){let i=n+r>>1;e[i]<=t?n=i:r=i}return n}function OJ(e,t,n,r,i,a){let o=Math.max(1,i),s=Math.max(1,a),c=Int32Array.from({length:o},(e,r)=>DJ(t.xB,n+r+.5)),l=new Float32Array(o*s);for(let n=0;n<s;n++){let i=DJ(t.yB,r+n+.5),a=i*e.w;for(let t=0;t<o;t++)l[n*o+t]=i<0||c[t]<0?NaN:e.values[a+c[t]]}return{w:o,h:s,values:l,xLabels:e.xLabels,yLabels:e.yLabels}}function kJ({cells:e,xLabels:t,yLabels:n,grid:r,showValues:i=!0,colorScheme:a=`diverging`,vMin:o,vMax:s,xCentres:c,yCentres:l,contours:u=0,backgroundToken:d=``,onPlotContextMenu:f}){let p=K(null),m=K(null),h=K(null),g=K(null),_=K(null),v=K(null),y=K(null),b=K(0),x=K(f);G(()=>{x.current=f},[f]);let S=St(()=>r??TJ(e??[],t??[],n??[]),[r,e,t,n]),C=St(()=>{let e=o??1/0,t=s??-1/0;if(o===void 0||s===void 0){let n=1/0,r=-1/0;for(let e=0;e<S.w*S.h;e++){let t=S.values[e];t<n&&(n=t),t>r&&(r=t)}o===void 0&&(e=n),s===void 0&&(t=r)}return t>e||(e=Number.isFinite(e)?e-1:0,t=e+2),{lo:e,hi:t}},[S,o,s]),w=K({data:S,range:C,showValues:i,colorScheme:a,xCentres:c,yCentres:l,contours:u});G(()=>{w.current={data:S,range:C,showValues:i,colorScheme:a,xCentres:c,yCentres:l,contours:u}},[S,C,i,a,c,l,u]);let T=K({plot:null,failed:!1,size:``,data:null,key:``,shown:null,geo:null}),E=K({key:``,grid:null,segs:[]});W(()=>()=>{T.current.plot?.dispose(),T.current.plot=null},[]);let D=K({data:null,range:``});function O(){if(v.current)return v.current;let e=_.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return v.current=n,n}function k(){let e=_.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function A(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function j(e,t){let n=T.current;if(!n.plot&&!n.failed&&m.current&&(n.plot=dH(m.current,yq),n.failed=!n.plot),!n.plot||!m.current)return null;let r=Math.min(2,window.devicePixelRatio||1),i=`${e}x${t}@${r}`;return n.size!==i&&(n.plot.resize(e,t,r),m.current.style.width=`${e}px`,m.current.style.height=`${t}px`,n.size=i),n.plot}let M=(e,t)=>typeof e==`function`?e(t):e[t];function N(){let e=p.current;if(!e)return;let{w:t,h:n}=k(),r=A(e,t,n);if(!r)return;let i=h.current?A(h.current,t,n):null;i?.clearRect(0,0,t,n);let a=MG(gJ,t,n),{top:o,right:s,bottom:c,left:l}=a,{bg:u,muted:d,grid:f}=O(),{data:m,range:{lo:g,hi:v},showValues:y,colorScheme:b}=w.current;r.fillStyle=u,r.fillRect(0,0,t,n);let x=j(t,n);if(m.w===0||m.h===0){x?.keep([]),x?.render(),r.fillStyle=d,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let S=t-l-s,C=n-o-c,N=Math.min(2,window.devicePixelRatio||1),P=D.current;(P.data!==m||P.range!==`${g}|${v}`)&&(D.current={data:m,range:`${g}|${v}`},VH(_.current));let{xCentres:F,yCentres:I,contours:L}=w.current,R=x?x.maxTextureSize:Math.max(1,Math.round(S*N)),z=qq(m,R).grid,B=EJ(z,l,o,S,C,z===m?F:void 0,z===m?I:void 0),V=B.byValue,ee=`${R}|${b}|${V?`${S}x${C}`:``}`,te=T.current.shown;if(T.current.data!==m||T.current.key!==ee||!te){te=z;let e=V?OJ(te,B,l,o,Math.round(S),Math.round(C)):te;x&&x.setGrid(`cells`,e.values,e.w,Math.min(e.h,x.maxTextureSize),[0,e.w,0,e.h],CJ(b),g,v),T.current.data=m,T.current.key=ee,T.current.shown=te}T.current.geo=B;let H=V?Math.round(S):te.w,ne=V?Math.round(C):te.h,re=e=>B.xB[e+1]-B.xB[e],ie=e=>B.yB[e+1]-B.yB[e];if(x)x.keep([`cells`]),x.setGridRange(`cells`,g,v),x.setView(0,H,ne,0,{left:l,top:o,width:S,height:C}),x.render();else for(let e=0;e<te.h;e++)for(let t=0;t<te.w;t++){let n=te.values[e*te.w+t];if(Number.isNaN(n))continue;let[i,a,o]=SJ(Math.max(0,Math.min(1,(n-g)/(v-g))),b);r.fillStyle=`rgb(${i|0},${a|0},${o|0})`,r.fillRect(B.xB[t],B.yB[e],re(t)+.5,ie(e)+.5)}let U=i??r;if(y){for(let e=0;e<te.h;e++)if(!(ie(e)<=16)){U.font=`${Math.min(12,Math.max(8,ie(e)*.4))}px ${Q.mono}`,U.textAlign=`center`,U.textBaseline=`middle`;for(let t=0;t<te.w;t++){let n=te.values[e*te.w+t];if(Number.isNaN(n)||re(t)<=28)continue;let[r,i,a]=SJ(Math.max(0,Math.min(1,(n-g)/(v-g))),b);U.fillStyle=.299*r+.587*i+.114*a>128?`#000`:`#fff`,U.fillText(wJ(n),(B.xB[t]+B.xB[t+1])/2,(B.yB[e]+B.yB[e+1])/2)}}}if(S/te.w>=4&&C/te.h>=4){U.strokeStyle=u,U.lineWidth=.5;for(let e=0;e<=te.w;e++)U.beginPath(),U.moveTo(B.xB[e],o),U.lineTo(B.xB[e],o+C),U.stroke();for(let e=0;e<=te.h;e++)U.beginPath(),U.moveTo(l,B.yB[e]),U.lineTo(l+S,B.yB[e]),U.stroke()}let ae=L>0?fJ(g,v,L):[];if(ae.length&&te.w>=2&&te.h>=2&&te.w*te.h<=4e6){let e=`${g}|${v}|${L}`;if(E.current.grid!==te||E.current.key!==e){let t=te;E.current={key:e,grid:t,segs:ae.map(e=>pJ(t.values,t.w,t.h,e))}}let t=(e,t)=>{let n=Math.min(t.length-3,Math.max(0,Math.floor(e))),r=(t[n]+t[n+1])/2;return r+((t[n+1]+t[n+2])/2-r)*(e-n)};U.save(),U.beginPath(),U.rect(l,o,S,C),U.clip(),U.lineCap=`round`,U.lineJoin=`round`;for(let[e,n]of[[2.6,`rgba(0,0,0,0.38)`],[1.1,`rgba(255,255,255,0.92)`]]){U.lineWidth=e,U.strokeStyle=n,U.beginPath();for(let e of E.current.segs)for(let[n,r,i,a]of e)U.moveTo(t(n,B.xB),t(r,B.yB)),U.lineTo(t(i,B.xB),t(a,B.yB));U.stroke()}U.restore()}r.fillStyle=d,r.font=`10px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`;let oe=-1/0;for(let e=0;e<(a.tiny?0:te.w);e++){let t=(B.xB[e]+B.xB[e+1])/2;t-oe<18||(oe=t,r.save(),r.translate(t,o+C+4),r.rotate(-Math.PI/4),r.fillText(M(te.xLabels,e),0,0),r.restore())}r.textAlign=`right`,r.textBaseline=`middle`;let se=-1/0;for(let e=0;e<(a.tiny?0:te.h);e++){let t=(B.yB[e]+B.yB[e+1])/2;t-se<12||(se=t,r.fillText(te.yLabels[e]??``,l-4,t))}if(a.tiny)return;let ce=t-s+4,le=o,ue=C;for(let e=0;e<ue;e++){let[t,n,i]=SJ(1-e/ue,b);r.fillStyle=`rgb(${t|0},${n|0},${i|0})`,r.fillRect(ce,le+e,12,1)}r.strokeStyle=f,r.lineWidth=.5,r.strokeRect(ce,le,12,ue),r.fillStyle=d,r.font=`9px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`middle`,r.fillText(wJ(v),ce+12+2,le),r.fillText(wJ(g),ce+12+2,le+ue),r.fillText(wJ((g+v)/2),ce+12+2,le+ue/2),r.strokeStyle=`rgba(255,255,255,0.92)`,r.lineWidth=1;for(let e of ae){let t=le+ue*(1-(e-g)/(v-g));r.beginPath(),r.moveTo(ce-2,t),r.lineTo(ce+12+2,t),r.stroke()}}function P(){let e=g.current;if(!e)return;let{w:t,h:n}=k(),r=A(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=y.current,a=T.current.shown,o=T.current.geo;if(!i||!a||!o)return;let{top:s,right:c,bottom:l}=MG(gJ,t,n),{xi:u,yi:d}=i;if(u>=a.w||d>=a.h)return;let f=o.xB[u],p=o.xB[u+1],m=o.yB[d],h=o.yB[d+1];r.strokeStyle=`rgba(255,255,255,0.7)`,r.lineWidth=1.5,r.strokeRect(f+.5,m+.5,Math.max(1,p-f-1),Math.max(1,h-m-1));let _=a.values[d*a.w+u];if(!Number.isNaN(_)){let e=`${M(a.xLabels,u)} × ${a.yLabels[d]}: ${wJ(_)}`;r.font=`11px ${Q.mono}`;let n=r.measureText(e).width,i=Math.min(p+.1*(p-f),t-c-n-6),o=Math.max(s+4,m-.3*(h-m));r.fillStyle=`rgba(0,0,0,0.7)`,r.fillRect(i-3,o-3,n+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(e,i,o)}}let F=K(N);F.current=N;let I=K(null);I.current??=KH(()=>F.current(),()=>_.current);let L=()=>{b.current||=RH(()=>{b.current=0,P()})};return W(()=>{I.current.now()},[S,C,i,a,c,l,u]),W(()=>()=>{I.current?.cancel(),zH(b.current)},[]),W(()=>{v.current=null,I.current.schedule()},[d]),G(()=>{let e=_.current;if(!e)return;let t=new WH(()=>{v.current=null,I.current.schedule(),L()});return t.observe(e),()=>t.disconnect()},[]),G(()=>{let e=g.current;if(!e)return;let t=e=>{e.preventDefault(),x.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{shown:r,geo:i}=T.current;if(!r||!i)return;let a=DJ(i.xB,t.clientX-n.left),o=DJ(i.yB,t.clientY-n.top);y.current=a>=0&&a<r.w&&o>=0&&o<r.h?{xi:a,yi:o}:null,L()},r=()=>{y.current=null,L()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:_,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:p,className:`chart-canvas`,role:`img`,"aria-label":`Heatmap`}),q(`canvas`,{ref:m,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:h,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:g,className:`chart-canvas chart-overlay`})]})}var AJ=2e3,jJ=1024;function MJ(e,t,n,r,i){let a=e.length,o=1/(a*t*Math.sqrt(2*Math.PI)),s=new Float64Array(n.length);if(a<=AJ){for(let r=0;r<n.length;r++){let i=0;for(let o=0;o<a;o++){let a=(n[r]-e[o])/t;i+=Math.exp(-.5*a*a)}s[r]=i*o}return s}let c=new Float64Array(jJ),l=(i-r)/jJ||1;for(let t=0;t<a;t++)c[Math.max(0,Math.min(jJ-1,Math.floor((e[t]-r)/l)))]++;for(let e=0;e<n.length;e++){let i=0;for(let a=0;a<jJ;a++){if(c[a]===0)continue;let o=(n[e]-(r+(a+.5)*l))/t;i+=c[a]*Math.exp(-.5*o*o)}s[e]=i*o}return s}var NJ={top:14,right:24,bottom:48,left:64},PJ=120;function FJ(e,t,n){let r=e.length;if(r<2)return 1;let i=0;for(let t=0;t<r;t++)i+=e[t];let a=i/r,o=0;for(let t=0;t<r;t++)o+=(e[t]-a)**2;let s=Math.sqrt(o/(r-1));return .9*Math.min(s,(n-t)/1.34)*r**-.2}function IJ(e,t){let n=e.filter(e=>e.values.length>=2),r=1/0,i=-1/0,a=n.map(e=>{let[t,n,a,o,s]=Hq(Float64Array.from(e.values),[0,25,50,75,100]);return t<r&&(r=t),s>i&&(i=s),{q1:n,median:a,q3:o}}),o=(i-r)*.1||1;r-=o,i+=o;let s=Float64Array.from({length:PJ},(e,t)=>r+t/(PJ-1)*(i-r));return{shapes:n.map((e,n)=>{let{q1:o,median:c,q3:l}=a[n],u=MJ(e.values,t>0?t:FJ(e.values,o,l),s,r,i),d=1e-10;for(let e of u)e>d&&(d=e);return{label:e.label,density:u,maxDensity:d,q1:o,median:c,q3:l}}),pts:s,yMin:r,yMax:i}}function LJ({groups:e,color:t=`#818cf8`,showBox:n=!0,bandwidth:r=0,orientation:i=`vertical`,backgroundToken:a=``,onPlotContextMenu:o}){let s=IU(),c=K(null),l=K(null),u=K(null),d=K(o);G(()=>{d.current=o},[o]);let f=K({groups:e,color:t,showBox:n,bandwidth:r,orientation:i});G(()=>{f.current={groups:e,color:t,showBox:n,bandwidth:r,orientation:i}},[e,t,n,r,i]);let p=St(()=>IJ(e,r),[e,r]),m=K(p);G(()=>{m.current=p},[p]);function h(){if(u.current)return u.current;let e=l.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return u.current=n,n}function g(){let e=l.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function _(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function v(){let e=c.current;if(!e)return;let{w:t,h:n}=g(),r=_(e,t,n);if(!r)return;let{top:i,right:a,bottom:o,left:l}=NJ,u=t-l-a,d=n-i-o,{bg:p,muted:v,grid:y}=h(),{color:b,showBox:x,orientation:S}=f.current;r.fillStyle=p,r.fillRect(0,0,t,n);let{shapes:C,pts:w,yMin:T,yMax:E}=m.current;if(C.length===0||u<=0||d<=0){r.fillStyle=v,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let D=S===`vertical`,O=D?e=>i+d*(1-(e-T)/(E-T)):e=>l+u*((e-T)/(E-T));s({left:l,top:i,width:u,height:d,...D?{y:{v0:T,v1:E}}:{x:{v0:T,v1:E}}});let k=Pz(E-T,5),A=Lz(T,E,k);r.strokeStyle=y,r.lineWidth=1,r.setLineDash([3,3]);for(let e of A)D?(r.beginPath(),r.moveTo(l,O(e)),r.lineTo(l+u,O(e)),r.stroke()):(r.beginPath(),r.moveTo(O(e),i),r.lineTo(O(e),i+d),r.stroke());if(r.setLineDash([]),r.fillStyle=v,r.font=`11px ${Q.mono}`,r.strokeStyle=v,r.lineWidth=1,D){r.textAlign=`right`,r.textBaseline=`middle`;for(let e of A)r.beginPath(),r.moveTo(l-4,O(e)),r.lineTo(l,O(e)),r.stroke(),r.fillText(Vz(e,k),l-6,O(e))}else{r.textAlign=`center`,r.textBaseline=`top`;for(let e of A)r.beginPath(),r.moveTo(O(e),i+d),r.lineTo(O(e),i+d+4),r.stroke(),r.fillText(Vz(e,k),O(e),i+d+6)}r.strokeStyle=y,r.strokeRect(l,i,u,d),r.save(),r.beginPath(),r.rect(l,i,u,d),r.clip();let j=C.length,M=D?u/j:d/j;for(let e=0;e<j;e++){let{density:t,maxDensity:n,q1:a,median:o,q3:s}=C[e],c=D?l+M*e+M/2:i+M*e+M/2,u=M*.45;r.beginPath();for(let e=0;e<PJ;e++){let i=t[e]/n*u,a=O(w[e]);D?e===0?r.moveTo(c-i,a):r.lineTo(c-i,a):e===0?r.moveTo(a,c-i):r.lineTo(a,c-i)}for(let e=PJ-1;e>=0;e--){let i=t[e]/n*u,a=O(w[e]);D?r.lineTo(c+i,a):r.lineTo(a,c+i)}if(r.closePath(),r.fillStyle=b,r.globalAlpha=.35,r.fill(),r.strokeStyle=b,r.lineWidth=1,r.globalAlpha=.9,r.stroke(),r.globalAlpha=1,x){let e=u*.22;D?(r.fillStyle=b,r.globalAlpha=.7,r.fillRect(c-e,O(s),e*2,O(a)-O(s)),r.globalAlpha=1,r.strokeStyle=b,r.lineWidth=2,r.beginPath(),r.moveTo(c-e,O(o)),r.lineTo(c+e,O(o)),r.stroke()):(r.fillStyle=b,r.globalAlpha=.7,r.fillRect(O(a),c-e,O(s)-O(a),e*2),r.globalAlpha=1,r.strokeStyle=b,r.lineWidth=2,r.beginPath(),r.moveTo(O(o),c-e),r.lineTo(O(o),c+e),r.stroke())}}if(r.restore(),r.fillStyle=v,r.font=`11px ${Q.mono}`,D){r.textAlign=`center`,r.textBaseline=`top`;for(let e=0;e<j;e++)r.fillText(C[e].label,l+M*e+M/2,i+d+6)}else{r.textAlign=`right`,r.textBaseline=`middle`;for(let e=0;e<j;e++)r.fillText(C[e].label,l-6,i+M*e+M/2)}}let y=K(v);y.current=v;let b=K(null);b.current??=KH(()=>y.current(),()=>l.current);let x=()=>b.current.schedule();return W(()=>{b.current.now()}),W(()=>()=>b.current?.cancel(),[]),W(()=>{u.current=null,x()},[a]),G(()=>{let e=l.current;if(!e)return;let t=new WH(()=>{u.current=null,x()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=c.current;if(!e)return;let t=e=>{e.preventDefault(),d.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),q(`div`,{ref:l,style:{position:`relative`,width:`100%`,height:`100%`},children:q(`canvas`,{ref:c,className:`chart-canvas`,role:`img`,"aria-label":`Violin plot`})})}var RJ={top:48,right:16,bottom:72,left:80},zJ=[8,24,64],BJ=[56,189,248];function VJ(e,t,n){return[e[0]+(t[0]-e[0])*n,e[1]+(t[1]-e[1])*n,e[2]+(t[2]-e[2])*n]}function HJ(e){return`${(e*100).toFixed(1)}%`}function UJ(e,t,n){if(e.length===0)return null;let r=Math.min(e.length,t.length),i=Array(r),a=Array(r),o=new Set,s=0;for(let n=0;n<r;n++)i[n]=String(e[n]),a[n]=String(t[n]),o.add(i[n]),o.add(a[n]),i[n]===a[n]&&s++;let c=[...o].sort(),l=c.length,u=new Map(c.map((e,t)=>[e,t])),d=Array.from({length:l},()=>Array(l).fill(0));for(let e=0;e<r;e++)d[u.get(i[e])][u.get(a[e])]++;let f=d.map(e=>e.reduce((e,t)=>e+t,0));return{classes:c,matrix:n?d.map((e,t)=>e.map(e=>f[t]>0?e/f[t]:0)):d,raw:d,accuracy:s/e.length}}function WJ({actual:e,predicted:t,normalize:n=!1,backgroundToken:r=``,onPlotContextMenu:i}){let a=K(null),o=K(null),s=K(null),c=K(null),l=K(null),u=K(0),d=K(i);G(()=>{d.current=i},[i]);let f=K({actual:e,predicted:t,normalize:n});G(()=>{f.current={actual:e,predicted:t,normalize:n}},[e,t,n]);function p(){if(c.current)return c.current;let e=s.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return c.current=n,n}function m(){let e=s.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function h(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}let g=St(()=>UJ(e,t,n),[e,t,n]),_=K(g);G(()=>{_.current=g},[g]);let v=()=>_.current;function y(){let e=a.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;let{top:i,right:o,bottom:s,left:c}=RJ,{bg:l,muted:u,grid:d}=p();r.fillStyle=l,r.fillRect(0,0,t,n);let g=v();if(!g){r.fillStyle=u,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{classes:_,matrix:y,accuracy:b}=g,x=_.length,S=t-c-o,C=n-i-s,w=S/x,T=C/x,E=0;for(let e of y)for(let t of e)t>E&&(E=t);for(let e=0;e<x;e++)for(let t=0;t<x;t++){let n=y[e][t],[a,o,s]=VJ(zJ,BJ,E>0?n/E:0);if(r.fillStyle=`rgb(${a|0},${o|0},${s|0})`,r.fillRect(c+t*w,i+e*T,w,T),w>24&&T>14){r.fillStyle=.299*a+.587*o+.114*s>100?`#000`:`#fff`,r.font=`${Math.min(12,Math.max(8,T*.38))}px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`middle`;let l=f.current.normalize;r.fillText(l?HJ(n):String(n|0),c+(t+.5)*w,i+(e+.5)*T)}}r.strokeStyle=l,r.lineWidth=.5;for(let e=0;e<=x;e++)r.beginPath(),r.moveTo(c+e*w,i),r.lineTo(c+e*w,i+C),r.stroke(),r.beginPath(),r.moveTo(c,i+e*T),r.lineTo(c+S,i+e*T),r.stroke();r.strokeStyle=d,r.strokeRect(c,i,S,C),r.fillStyle=u,r.font=`10px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`;for(let e=0;e<x;e++)r.fillText(_[e],c-4,i+(e+.5)*T);r.textAlign=`center`,r.textBaseline=`top`;for(let e=0;e<x;e++)r.save(),r.translate(c+(e+.5)*w,i+C+4),r.rotate(-Math.PI/4),r.fillText(_[e],0,0),r.restore();r.fillStyle=u,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(`Predicted`,c+S/2,n-4),r.save(),r.translate(12,i+C/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.fillText(`Actual`,0,0),r.restore(),r.fillStyle=u,r.font=`11px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(`Accuracy: ${HJ(b)}`,c+S/2,i/2)}function b(){let e=o.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=l.current;if(!i)return;let{top:a,right:s,bottom:c,left:u}=RJ,d=v();if(!d)return;let{classes:p,matrix:g}=d,_=p.length,y=t-u-s,b=n-a-c,x=y/_,S=b/_;r.strokeStyle=`rgba(255,255,255,0.8)`,r.lineWidth=2,r.strokeRect(u+i.c*x+1,a+i.r*S+1,x-2,S-2);let C=g[i.r][i.c],w=f.current.normalize,T=`${p[i.r]} → ${p[i.c]}: ${w?HJ(C):C|0}`;r.font=`11px ${Q.mono}`;let E=r.measureText(T).width,D=Math.min(u+(i.c+1.1)*x,t-E-6),O=Math.max(6,a+(i.r-.3)*S);r.fillStyle=`rgba(0,0,0,0.75)`,r.fillRect(D-3,O-3,E+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(T,D,O)}let x=K(y);x.current=y;let S=K(null);S.current??=KH(()=>x.current(),()=>s.current);let C=()=>S.current.schedule(),w=()=>{zH(u.current),u.current=RH(b)};return W(()=>{S.current.now()}),W(()=>()=>S.current?.cancel(),[]),W(()=>{c.current=null,C()},[r]),G(()=>{let e=s.current;if(!e)return;let t=new WH(()=>{c.current=null,C(),w()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=o.current;if(!e)return;let t=e=>{e.preventDefault(),d.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{top:r,right:i,bottom:a,left:o}=RJ,s=v();if(!s)return;let c=s.classes.length,u=n.width-o-i,d=n.height-r-a,f=Math.floor((t.clientX-n.left-o)/(u/c)),p=Math.floor((t.clientY-n.top-r)/(d/c));l.current=p>=0&&p<c&&f>=0&&f<c?{r:p,c:f}:null,w()},r=()=>{l.current=null,w()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:s,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:a,className:`chart-canvas`,role:`img`,"aria-label":`Confusion matrix`}),q(`canvas`,{ref:o,className:`chart-canvas chart-overlay`})]})}var GJ={top:24,right:24,bottom:48,left:64};function KJ(e,t){let n=0,r=0,i=Math.min(e.length,t.length);for(let a=0;a<i;a++)e[a]-e[a]!==0||t[a]-t[a]!==0||(t[a]===1?n++:r++);let a=new Float64Array(n),o=new Float64Array(r);for(let n=0,r=0,s=0;n<i;n++)e[n]-e[n]!==0||t[n]-t[n]!==0||(t[n]===1?a[r++]=e[n]:o[s++]=e[n]);a.sort(),o.sort();let s=new Uint8Array(n+r);for(let e=0,t=n-1,i=r-1;e<s.length;e++)i<0||t>=0&&a[t]>=o[i]?(s[e]=1,t--):(s[e]=0,i--);return s}function qJ(e){let t=0;for(let n of e)t+=n;let n=e.length-t;if(t===0||n===0)return null;let r=new Float64Array(e.length+2),i=new Float64Array(e.length+2),a=0,o=0,s=0;for(let c=0;c<e.length;c++)e[c]===1?a++:o++,r[c+1]=o/n,i[c+1]=a/t,s+=(r[c+1]-r[c])*(i[c+1]+i[c])/2;return r[e.length+1]=1,i[e.length+1]=1,{fpr:r,tpr:i,auc:s}}function JJ(e){let t=0;for(let n of e)t+=n;if(t===0)return null;let n=new Float64Array(e.length),r=new Float64Array(e.length),i=0,a=0,o=0;for(let s=0;s<e.length;s++)e[s]===1?i++:a++,n[s]=i/t,r[s]=i/(i+a),s>0&&(o+=(n[s]-n[s-1])*r[s]);return{recall:n,precision:r,ap:o}}function YJ(e,t,n,r){let i=n(0),a=r(0);e.moveTo(i,a);for(let o=1;o<t;o++){let s=n(o),c=r(o);o<t-1&&Math.abs(s-i)<.5&&Math.abs(c-a)<.5||(e.lineTo(s,c),i=s,a=c)}}function XJ({scores:e,labels:t,mode:n=`roc`,color:r=`#f472b6`,backgroundToken:i=``,onPlotContextMenu:a}){let o=K(null),s=K(null),c=K(null),l=K(a);G(()=>{l.current=a},[a]);let u=K({scores:e,labels:t,mode:n,color:r});G(()=>{u.current={scores:e,labels:t,mode:n,color:r}},[e,t,n,r]);let d=St(()=>KJ(e,t),[e,t]),f=St(()=>n===`pr`?{roc:null,pr:JJ(d)}:{roc:qJ(d),pr:null},[d,n]),p=K(f);G(()=>{p.current=f},[f]);function m(){if(c.current)return c.current;let e=s.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return c.current=n,n}function h(){let e=s.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function _(){let e=o.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;let{top:i,right:a,bottom:s,left:c}=GJ,l=t-c-a,d=n-i-s,{bg:f,muted:_,grid:v}=m(),{scores:y,mode:b,color:x}=u.current;if(r.fillStyle=f,r.fillRect(0,0,t,n),y.length===0){r.fillStyle=_,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let S=e=>c+e*l,C=e=>i+(1-e)*d,w=Lz(0,1,Pz(1,5));r.strokeStyle=v,r.lineWidth=1,r.setLineDash([3,3]);for(let e of w)r.beginPath(),r.moveTo(S(e),i),r.lineTo(S(e),i+d),r.stroke(),r.beginPath(),r.moveTo(c,C(e)),r.lineTo(c+l,C(e)),r.stroke();if(r.setLineDash([]),b===`roc`&&(r.strokeStyle=_,r.lineWidth=1,r.setLineDash([4,4]),r.beginPath(),r.moveTo(S(0),C(0)),r.lineTo(S(1),C(1)),r.stroke(),r.setLineDash([])),b===`roc`){let e=p.current.roc;if(e){let t=e.fpr.length,n=t=>S(e.fpr[t]),a=t=>C(e.tpr[t]);r.beginPath(),YJ(r,t,n,a),r.strokeStyle=x,r.lineWidth=1,r.stroke(),r.beginPath(),YJ(r,t,n,a),r.lineTo(S(1),C(0)),r.lineTo(S(0),C(0)),r.closePath(),r.fillStyle=x,r.globalAlpha=.15,r.fill(),r.globalAlpha=1,r.fillStyle=x,r.font=`bold 13px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`AUC = ${e.auc.toFixed(3)}`,c+8,i+8)}}else{let e=p.current.pr;if(e){let t=Tq(e.recall,e.precision,0,1,Math.max(1,Math.round(l*Math.min(2,window.devicePixelRatio||1))));r.beginPath();for(let n=0;n<t.length;n++){let i=S(e.recall[t[n]]),a=C(e.precision[t[n]]);n===0?r.moveTo(i,a):r.lineTo(i,a)}r.strokeStyle=x,r.lineWidth=1,r.stroke(),r.fillStyle=x,r.font=`bold 13px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`AP = ${e.ap.toFixed(3)}`,c+8,i+8)}}r.fillStyle=_,r.font=`11px ${Q.mono}`,r.strokeStyle=_,r.lineWidth=1,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of w)r.beginPath(),r.moveTo(c-4,C(e)),r.lineTo(c,C(e)),r.stroke(),r.fillText(e.toFixed(1),c-6,C(e));r.textAlign=`center`,r.textBaseline=`top`;for(let e of w)r.beginPath(),r.moveTo(S(e),i+d),r.lineTo(S(e),i+d+4),r.stroke(),r.fillText(e.toFixed(1),S(e),i+d+6);r.strokeStyle=v,r.strokeRect(c,i,l,d),r.fillStyle=_,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(b===`roc`?`False Positive Rate`:`Recall`,c+l/2,n-4),r.save(),r.translate(12,i+d/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.fillText(b===`roc`?`True Positive Rate`:`Precision`,0,0),r.restore()}let v=K(_);v.current=_;let y=K(null);y.current??=KH(()=>v.current(),()=>s.current);let b=()=>y.current.schedule();return W(()=>{y.current.now()}),W(()=>()=>y.current?.cancel(),[]),W(()=>{c.current=null,b()},[i]),G(()=>{let e=s.current;if(!e)return;let t=new WH(()=>{c.current=null,b()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=o.current;if(!e)return;let t=e=>{e.preventDefault(),l.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>e.removeEventListener(`contextmenu`,t)},[]),q(`div`,{ref:s,style:{position:`relative`,width:`100%`,height:`100%`},children:q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`ROC / PR curve`})})}var ZJ={top:20,right:64,bottom:48,left:64};function QJ({xValues:e,series:t,xLabel:n=`Epoch`,backgroundToken:r=``,onPlotContextMenu:i}){let a=IU(),o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(0),f=K(i);G(()=>{f.current=i},[i]);let p=K({xValues:e,series:t,xLabel:n});G(()=>{p.current={xValues:e,series:t,xLabel:n}},[e,t,n]);function m(){if(l.current)return l.current;let e=c.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return l.current=n,n}function h(){let e=c.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}let _=St(()=>{let n=e=>{let t=1/0,n=-1/0;for(let r of e)for(let e=0;e<r.values.length;e++){let i=r.values[e];i<t&&(t=i),i>n&&(n=i)}if(!Number.isFinite(t))return{lo:0,hi:1};let r=(n-t)*.06||.1;return{lo:t-r,hi:n+r}},r=t.filter(e=>e.axis===`left`),i=t.filter(e=>e.axis===`right`),a=1/0,o=-1/0;for(let t=0;t<e.length;t++){let n=e[t];n<a&&(a=n),n>o&&(o=n)}return{leftExt:n(r.length?r:t),rightExt:n(i.length?i:t),hasRight:i.length>0,xMin:a,xMax:o,ascending:Oq(e)}},[e,t]),v=K(_);G(()=>{v.current=_},[_]);function y(){let e=o.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;let{top:i,right:s,bottom:c,left:l}=ZJ,u=t-l-s,d=n-i-c,{bg:f,muted:_,grid:y}=m(),{xValues:b,series:x,xLabel:S}=p.current;if(r.fillStyle=f,r.fillRect(0,0,t,n),b.length===0||x.length===0){r.fillStyle=_,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{leftExt:C,rightExt:w,hasRight:T,xMin:E,xMax:D,ascending:O}=v.current,k=e=>l+(e-E)/(D-E||1)*u;a({left:l,top:i,width:u,height:d,x:{v0:E,v1:D},y:{v0:C.lo,v1:C.hi}});let A=e=>i+(1-(e-C.lo)/(C.hi-C.lo))*d,j=e=>i+(1-(e-w.lo)/(w.hi-w.lo))*d,M=Pz(C.hi-C.lo,5),N=Lz(C.lo,C.hi,M);r.strokeStyle=y,r.lineWidth=1,r.setLineDash([3,3]);for(let e of N)r.beginPath(),r.moveTo(l,A(e)),r.lineTo(l+u,A(e)),r.stroke();let P=Pz(D-E,6),F=Lz(E,D,P);for(let e of F)r.beginPath(),r.moveTo(k(e),i),r.lineTo(k(e),i+d),r.stroke();r.setLineDash([]);let I=Math.min(2,window.devicePixelRatio||1),L=Math.max(1,Math.round(u*I));for(let e of x){let t=e.axis===`right`&&T?j:A,n=Math.min(b.length,e.values.length),i=O&&n>4*L?Tq(b,e.values,E,D,L):null;r.beginPath();let a=!1;for(let o=0;o<(i?i.length:n);o++){let n=i?i[o]:o,s=b[n],c=e.values[n];if(s-s!==0||c-c!==0){a=!1;continue}let l=k(s),u=t(c);a?r.lineTo(l,u):(r.moveTo(l,u),a=!0)}r.strokeStyle=e.color,r.lineWidth=1,r.stroke()}r.fillStyle=_,r.font=`11px ${Q.mono}`,r.strokeStyle=_,r.lineWidth=1,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of N)r.beginPath(),r.moveTo(l-4,A(e)),r.lineTo(l,A(e)),r.stroke(),r.fillText(Vz(e,M),l-6,A(e));if(T){let e=Pz(w.hi-w.lo,5),t=Lz(w.lo,w.hi,e);r.textAlign=`left`;for(let n of t)r.beginPath(),r.moveTo(l+u,j(n)),r.lineTo(l+u+4,j(n)),r.stroke(),r.fillText(Vz(n,e),l+u+6,j(n))}r.textAlign=`center`,r.textBaseline=`top`;for(let e of F)r.beginPath(),r.moveTo(k(e),i+d),r.lineTo(k(e),i+d+4),r.stroke(),r.fillText(Vz(e,P),k(e),i+d+6);r.strokeStyle=y,r.strokeRect(l,i,u,d),r.fillStyle=_,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(S,l+u/2,n-4);let R=l+8,z=i+6;r.font=`10px ${Q.mono}`,r.textBaseline=`middle`;for(let e of x)r.fillStyle=e.color,r.fillRect(R,z-4,16,3),r.fillStyle=_,r.textAlign=`left`,r.fillText(e.label,R+20,z),R+=r.measureText(e.label).width+36,R>l+u-60&&(R=l+8,z+=14)}function b(){let e=s.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=u.current;if(i===null)return;let{top:a,right:o,bottom:c,left:l}=ZJ,d=t-l-o,f=n-a-c,{muted:_}=m(),{xValues:y,series:b}=p.current;if(y.length===0)return;let{xMin:x,xMax:S,ascending:C}=v.current,w=e=>l+(e-x)/(S-x||1)*d,T=Math.max(l,Math.min(l+d,i));r.strokeStyle=_,r.lineWidth=1,r.setLineDash([3,3]),r.beginPath(),r.moveTo(T,a),r.lineTo(T,a+f),r.stroke(),r.setLineDash([]);let E=(T-l)/d,D=Math.round(E*(y.length-1));if(C){let e=x+E*(S-x),t=0,n=y.length;for(;t<n;){let r=t+n>>>1;y[r]<e?t=r+1:n=r}D=t>0&&(t>=y.length||e-y[t-1]<y[t]-e)?t-1:t}if(D<0||D>=y.length)return;let O=a+8;r.font=`10px ${Q.mono}`,r.textBaseline=`top`;for(let e of b)D<e.values.length&&Number.isFinite(e.values[D])&&(r.fillStyle=e.color,r.textAlign=`left`,r.fillText(`${e.label}: ${Hz(e.values[D])}`,T+6,O),O+=14);w(0)}let x=K(y);x.current=y;let S=K(null);S.current??=KH(()=>x.current(),()=>c.current);let C=()=>S.current.schedule(),w=()=>{zH(d.current),d.current=RH(b)};return W(()=>{S.current.now()}),W(()=>()=>S.current?.cancel(),[]),W(()=>{l.current=null,C()},[r]),G(()=>{let e=c.current;if(!e)return;let t=new WH(()=>{l.current=null,C(),w()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=s.current;if(!e)return;let t=e=>{e.preventDefault(),f.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect();u.current=t.clientX-n.left,w()},r=()=>{u.current=null,w()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:c,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Loss curves`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`})]})}var $J={top:40,right:24,bottom:40,left:72},eY=`#ef4444`,tY=`#f97316`,nY=`#22d3ee`;function rY(e,t){let n=e.length,r=e.value;if(n===0)return null;let i=0;for(let e=0;e<n;e++)i+=r[e];let a=i/n,o=0;for(let e=0;e<n;e++)o+=(r[e]-a)**2;let s=Math.sqrt(o/n),c=a+t*s,l=a-t*s,u=l,d=c,f=0;for(let e=0;e<n;e++){let t=r[e];t<u&&(u=t),t>d&&(d=t),(t>c||t<l)&&f++}let p=(d-u)*.08||.5,m=new Uint32Array(f);for(let e=0,t=0;e<n;e++)(r[e]>c||r[e]<l)&&(m[t++]=e);return{mean:a,sd:s,ucl:c,lcl:l,yMin:u-p,yMax:d+p,ooc:m}}function iY({points:e,sigmaLevel:t=3,color:n=`#22d3ee`,backgroundToken:r=``,onPlotContextMenu:i}){let a=IU(),o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(0),f=K(i);G(()=>{f.current=i},[i]);let p=K({points:e,sigmaLevel:t,color:n});G(()=>{p.current={points:e,sigmaLevel:t,color:n}},[e,t,n]);function m(){if(l.current)return l.current;let e=c.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return l.current=n,n}function h(){let e=c.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}let _=St(()=>rY(e,t),[e,t]),v=K(_);G(()=>{v.current=_},[_]);let y=()=>v.current;function b(){let e=o.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;let{top:i,right:s,bottom:c,left:l}=$J,u=t-l-s,d=n-i-c,{bg:f,muted:_,grid:v}=m(),{points:b,color:x}=p.current;if(r.fillStyle=f,r.fillRect(0,0,t,n),b.length===0){r.fillStyle=_,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let S=y(),{mean:C,ucl:w,lcl:T,yMin:E,yMax:D}=S,O=e=>l+e/(b.length-1||1)*u;a({left:l,top:i,width:u,height:d,x:{v0:0,v1:b.length-1||1}});let k=e=>i+(1-(e-E)/(D-E))*d,A=Pz(D-E,5),j=Lz(E,D,A);r.strokeStyle=v,r.lineWidth=1,r.setLineDash([3,3]);for(let e of j)r.beginPath(),r.moveTo(l,k(e)),r.lineTo(l+u,k(e)),r.stroke();r.setLineDash([]);let M=(e,t,n,a=[])=>{let o=k(e);o<i||o>i+d||(r.strokeStyle=t,r.lineWidth=1.2,r.setLineDash(a),r.beginPath(),r.moveTo(l,o),r.lineTo(l+u,o),r.stroke(),r.setLineDash([]),r.fillStyle=t,r.font=`9px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(`${n} ${Hz(e)}`,l+u-2,o-5))};M(w,tY,`UCL`,[5,3]),M(C,nY,`CL`,[]),M(T,tY,`LCL`,[5,3]);let N=Math.min(2,window.devicePixelRatio||1),P=Math.max(1,Math.round(u*N)),F=b.length,I=b.value,L=Eq(I,P);r.beginPath();for(let e=0;e<L.length;e++){let t=L[e],n=O(t),i=k(I[t]);e===0?r.moveTo(n,i):r.lineTo(n,i)}r.strokeStyle=x,r.lineWidth=1,r.stroke();let R=(e,t)=>{r.beginPath(),r.arc(O(e),k(I[e]),t?4:3,0,Math.PI*2),r.fillStyle=t?eY:x,r.fill()};if(F<=u/4)for(let e=0;e<F;e++)R(e,I[e]>w||I[e]<T);else{let e=NaN,t=NaN;for(let n of S.ooc){let r=Math.round(O(n)),i=Math.round(k(I[n]));r===e&&i===t||(e=r,t=i,R(n,!0))}}r.fillStyle=_,r.font=`11px ${Q.mono}`,r.strokeStyle=_,r.lineWidth=1,r.textAlign=`right`,r.textBaseline=`middle`;for(let e of j)r.beginPath(),r.moveTo(l-4,k(e)),r.lineTo(l,k(e)),r.stroke(),r.fillText(Vz(e,A),l-6,k(e));r.strokeStyle=v,r.strokeRect(l,i,u,d)}function x(){let e=s.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=u.current;if(i===null)return;let{top:a,right:o,bottom:c,left:l}=$J,d=t-l-o,f=n-a-c,{muted:_}=m(),{points:v}=p.current;if(v.length===0)return;let{ucl:b,lcl:x,yMin:S,yMax:C}=y(),w=e=>l+e/(v.length-1||1)*d,T=e=>a+(1-(e-S)/(C-S))*f,E=Math.round((i-l)/d*(v.length-1));if(E<0||E>=v.length)return;let D=v.value[E],O=w(E),k=T(D);r.strokeStyle=_,r.lineWidth=1,r.setLineDash([3,3]),r.beginPath(),r.moveTo(O,a),r.lineTo(O,a+f),r.stroke(),r.setLineDash([]);let A=v.subgroup?.(E),j=`${A?`${A}: `:`#${E+1}: `}${Hz(D)}`;r.font=`11px ${Q.mono}`;let M=r.measureText(j).width,N=O+8+M>l+d?O-M-10:O+8;r.fillStyle=`rgba(0,0,0,0.75)`,r.fillRect(N-3,k-12,M+6,18),r.fillStyle=D>b||D<x?eY:_,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(j,N,k-11)}let S=K(b);S.current=b;let C=K(null);C.current??=KH(()=>S.current(),()=>c.current);let w=()=>C.current.schedule(),T=()=>{zH(d.current),d.current=RH(x)};return W(()=>{C.current.now()}),W(()=>()=>C.current?.cancel(),[]),W(()=>{l.current=null,w()},[r]),G(()=>{let e=c.current;if(!e)return;let t=new WH(()=>{l.current=null,w(),T()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=s.current;if(!e)return;let t=e=>{e.preventDefault(),f.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect();u.current=t.clientX-n.left,T()},r=()=>{u.current=null,T()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:c,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Control chart`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`})]})}var aY={top:32,right:24,bottom:24,left:24},oY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`],sY=16;function cY(e){return`rgb(${Math.round(255*Math.min(1,Math.max(0,3.5*e-.5)))},${Math.round(255*Math.min(1,Math.max(0,e<.5?2*e:2-2*e)))},${Math.round(255*Math.min(1,Math.max(0,1.5-3.5*e)))})`}function lY(e,t,n,r){let i=Math.min(t,e.columns.length),a=e.columns.slice(0,i).map(t=>{let n=1/0,r=-1/0;for(let i=0;i<e.length;i++){let e=t[i];e<n&&(n=e),e>r&&(r=e)}if(!Number.isFinite(n))return{lo:0,hi:1};let i=(r-n)*.05||.5;return{lo:n-i,hi:r+i}}),o={lo:0,hi:1},s=new Int32Array(e.length),c=[r];if(n&&e.colorValue){let t=e.colorValue,n=1/0,r=-1/0;for(let i=0;i<e.length;i++)t[i]<n&&(n=t[i]),t[i]>r&&(r=t[i]);Number.isFinite(n)&&(o={lo:n,hi:r}),c=Array.from({length:sY},(e,t)=>cY((t+.5)/sY));for(let n=0;n<e.length;n++){let e=(t[n]-o.lo)/(o.hi-o.lo||1);s[n]=t[n]===t[n]?Math.max(0,Math.min(sY-1,Math.floor(e*sY))):-1}for(let t=0;t<e.length;t++)s[t]<0&&(s[t]=0)}else if(!n&&e.colorIndex){c=oY;for(let t=0;t<e.length;t++)s[t]=Math.max(0,e.colorIndex[t])%oY.length}let l=new Int32Array(c.length);for(let t=0;t<e.length;t++)l[s[t]]++;let u=c.map((e,t)=>({color:e,x:new Float64Array(l[t]*i),y:new Float64Array(l[t]*i),starts:new Uint8Array(l[t]*i)})),d=new Int32Array(c.length);for(let t=0;t<e.length;t++){let n=u[s[t]],r=d[s[t]]++*i;n.starts[r]=1;for(let o=0;o<i;o++,r++){let i=a[o];n.x[r]=o,n.y[r]=(e.columns[o][t]-i.lo)/(i.hi-i.lo)}}return{k:i,extents:a,colorExt:o,groups:u.filter(e=>e.x.length>0)}}function uY({rows:e,axes:t,color:n=`#64748b`,colorByNumeric:r=!1,backgroundToken:i=``,onPlotContextMenu:a}){let o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(null),f=K(null),p=K(0),m=K(a);G(()=>{m.current=a},[a]);let h=St(()=>lY(e,t.length,r,n),[e,t.length,r,n]),g=K({rows:e,axes:t,colorByNumeric:r,model:h});G(()=>{g.current={rows:e,axes:t,colorByNumeric:r,model:h}},[e,t,r,h]);let _=bq(s),v=K(null);function y(){if(d.current)return d.current;let e=u.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return d.current=n,n}function b(){let e=u.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function x(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function S(){let e=o.current;if(!e)return;let{w:t,h:n}=b(),r=x(e,t,n);if(!r)return;let i=c.current?x(c.current,t,n):null;i?.clearRect(0,0,t,n);let a=i??r,{top:s,right:l,bottom:d,left:f}=aY,{bg:p,muted:m}=y(),{rows:h,axes:S,colorByNumeric:C,model:w}=g.current;r.fillStyle=p,r.fillRect(0,0,t,n);let T=_(t,n);if(S.length<2||h.length===0||w.k<2){T?.keep([]),T?.render(),r.fillStyle=m,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`Select ≥ 2 axes`,f+8,s+8);return}let E=t-f-l,D=n-s-d,O=w.k,k=Array.from({length:O},(e,t)=>f+t/(O-1)*E),A=(e,t)=>{let n=w.extents[t];return s+(1-(e-n.lo)/(n.hi-n.lo))*D},j=Math.max(.05,Math.min(.7,60/h.length));if(T)v.current!==w&&(w.groups.forEach((e,t)=>T.setLine(`c${t}`,e.x,e.y,NK(e.color,j),1,e.starts)),v.current=w,VH(u.current)),T.keep(w.groups.map((e,t)=>`c${t}`)),T.setView(0,O-1,0,1,{left:f,top:s,width:E,height:D}),T.render();else{r.globalAlpha=j;for(let e of w.groups){r.beginPath();let t=!1;for(let n=0;n<e.x.length;n++){let i=e.y[n];if(e.starts[n]&&(t=!1),i!==i){t=!1;continue}let a=f+e.x[n]/(O-1)*E,o=s+(1-i)*D;t?r.lineTo(a,o):(r.moveTo(a,o),t=!0)}r.strokeStyle=e.color,r.lineWidth=1,r.stroke()}r.globalAlpha=1}a.strokeStyle=m,a.lineWidth=1.5;for(let e=0;e<O;e++)a.beginPath(),a.moveTo(k[e],s),a.lineTo(k[e],s+D),a.stroke();a.fillStyle=m,a.font=`9px ${Q.mono}`;for(let e=0;e<O;e++){let t=w.extents[e];for(let n of[0,.25,.5,.75,1]){let r=t.lo+n*(t.hi-t.lo),i=A(r,e);a.beginPath(),a.moveTo(k[e]-3,i),a.lineTo(k[e]+3,i),a.stroke(),a.textAlign=e===O-1?`left`:`right`,a.textBaseline=`middle`,a.fillText(Vz(r,(t.hi-t.lo)/4),k[e]+(e===O-1?5:-5),i)}a.font=`10px ${Q.mono}`,a.textAlign=`center`,a.textBaseline=`bottom`,a.fillText(S[e],k[e],s-4)}let M=h.colorLabels??[];if(!C&&M.length>0&&M.length<=10){let e=f,t=s+D+8;a.font=`9px ${Q.mono}`,a.textBaseline=`top`,M.forEach((n,r)=>{a.fillStyle=oY[r%oY.length],a.fillRect(e,t,10,8),a.fillStyle=m,a.textAlign=`left`,a.fillText(n,e+13,t),e+=a.measureText(n).width+26,e>f+E-40&&(e=f,t+=12)})}}function C(){let e=l.current;if(!e)return;let{w:t,h:n}=b(),r=x(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=f.current;if(i===null)return;let{top:a,right:o,bottom:s,left:c}=aY,{axes:u}=g.current;if(u.length<2)return;let d=t-c-o,p=c+i/(u.length-1)*d;r.strokeStyle=`rgba(255,255,255,0.6)`,r.lineWidth=2,r.beginPath(),r.moveTo(p,a-4),r.lineTo(p,a+(n-a-s)+4),r.stroke()}let w=K(S);w.current=S;let T=K(null);T.current??=KH(()=>w.current(),()=>u.current);let E=()=>T.current.schedule(),D=()=>{zH(p.current),p.current=RH(C)};return W(()=>{T.current.now()}),W(()=>()=>T.current?.cancel(),[]),W(()=>{d.current=null,E()},[i]),G(()=>{let e=u.current;if(!e)return;let t=new WH(()=>{d.current=null,E(),D()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=l.current;if(!e)return;let t=e=>{e.preventDefault(),m.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{axes:r}=g.current;if(r.length<2)return;let i=n.width-aY.left-aY.right,a=r.length,o=t.clientX-n.left-aY.left,s=Math.round(o/i*(a-1));f.current=Math.abs(o-s/(a-1)*i)<20&&s>=0&&s<a?s:null,D()},r=()=>{f.current=null,D()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:u,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Parallel coordinates`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:c,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:l,className:`chart-canvas chart-overlay`})]})}function dY(e,t,n,r,i,a){let o=Math.max(1,Math.ceil(t/r)),s=Math.max(1,Math.ceil(n/r)),c=e=>{let s=i(e),c=a(e);return s>=0&&s<t&&c>=0&&c<n?Math.floor(c/r)*o+Math.floor(s/r):-1},l=new Uint32Array(o*s+1);for(let t=0;t<e;t++){let e=c(t);e>=0&&l[e+1]++}for(let e=0;e<o*s;e++)l[e+1]+=l[e];let u=l.slice(0,o*s),d=new Uint32Array(l[o*s]);for(let t=0;t<e;t++){let e=c(t);e>=0&&(d[u[e]++]=t)}return{cell:r,nx:o,ny:s,start:l,ix:d}}function fY(e,t,n,r,i,a,o){let s=Math.floor(t/e.cell),c=Math.floor(n/e.cell),l=-1,u=r*r;for(let r=c-1;r<=c+1;r++)if(!(r<0||r>=e.ny))for(let c=s-1;c<=s+1;c++){if(c<0||c>=e.nx)continue;let s=r*e.nx+c;for(let r=e.start[s];r<e.start[s+1];r++){let s=e.ix[r],c=(i(s)-t)**2+(a(s)-n)**2;c<u&&(!o||c<o(s)**2)&&(u=c,l=s)}}return l<0?null:l}var pY={top:16,right:16,bottom:16,left:16},mY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function hY(e){return[Math.round(255*Math.min(1,Math.max(0,3.5*e-.5))),Math.round(255*Math.min(1,Math.max(0,e<.5?2*e:2-2*e))),Math.round(255*Math.min(1,Math.max(0,1.5-3.5*e)))]}function gY(e){let[t,n,r]=hY(e);return`rgb(${t},${n},${r})`}var _Y=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++)e.set([...hY(t/255),255],t*4);return e})(),vY=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++){let[n,r,i]=NK(mY[t%mY.length],1);e.set([n*255,r*255,i*255,255],t*4)}return e});function yY(e,t){let n=1/0,r=-1/0,i=1/0,a=-1/0;for(let t=0;t<e.length;t++){let o=e.x[t],s=e.y[t];o<n&&(n=o),o>r&&(r=o),s<i&&(i=s),s>a&&(a=s)}let o=!Number.isFinite(n)||!Number.isFinite(i)?{xLo:-1,xHi:1,yLo:-1,yHi:1}:(()=>{let e=(r-n)*.05||.5,t=(a-i)*.05||.5;return{xLo:n-e,xHi:r+e,yLo:i-t,yHi:a+t}})(),s={lo:0,hi:1},c=null,l=`single`;if(t&&e.colorValue){let t=e.colorValue,n=1/0,r=-1/0;for(let i=0;i<e.length;i++){let e=t[i];e<n&&(n=e),e>r&&(r=e)}Number.isFinite(n)&&(s={lo:n,hi:r}),c=new Float32Array(e.length);let i=s.hi-s.lo;for(let n=0;n<e.length;n++)c[n]=t[n]===t[n]?Math.max(0,Math.min(1,i>0?(t[n]-s.lo)/i:.5)):0;l=`colormap`}else !t&&e.colorIndex&&(c=Float32Array.from(e.colorIndex,e=>e>=0?e%256:0),l=`dataset`);return{ext:o,colorExt:s,key:c,mode:l}}function bY({points:e,color:t=`#64748b`,colorByNumeric:n=!1,pointSize:r=4,backgroundToken:i=``,onPlotContextMenu:a}){let o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(null),f=K(0),p=K(a);G(()=>{p.current=a},[a]);let m=St(()=>yY(e,n),[e,n]),h=K({points:e,color:t,colorByNumeric:n,pointSize:r,model:m});G(()=>{h.current={points:e,color:t,colorByNumeric:n,pointSize:r,model:m}},[e,t,n,r,m]);let g=K({r:null,failed:!1,size:``,model:null,style:``});W(()=>()=>{g.current.r?.dispose(),g.current.r=null},[]);function _(){if(u.current)return u.current;let e=l.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return u.current=n,n}function v(){let e=l.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function y(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function b(e,t){let{top:n,right:r,bottom:i,left:a}=pY,o=e-a-r,s=t-n-i,c=h.current.model.ext;return{xToPx:e=>a+(e-c.xLo)/(c.xHi-c.xLo)*o,yToPx:e=>n+(1-(e-c.yLo)/(c.yHi-c.yLo))*s,plotW:o,plotH:s,ext:c}}function x(e,t){let n=g.current;!n.r&&!n.failed&&s.current&&(n.r=dH(s.current,AG),n.failed=!n.r);let r=n.r;if(!r||!s.current)return null;let i=Math.min(2,window.devicePixelRatio||1),a=`${e}x${t}@${i}`;n.size!==a&&(r.resize(e,t,i),s.current.style.width=`${e}px`,s.current.style.height=`${t}px`,n.size=a);let{points:o,model:c,color:u,pointSize:d}=h.current;n.model!==c&&(r.setData(o.x,o.y,c.key??void 0),n.model=c,VH(l.current));let f=`${c.mode}|${u}|${d}`;return n.style!==f&&(r.setStyle(c.mode===`single`?{kind:`single`,rgba:NK(u,1)}:{kind:c.mode,palette:c.mode===`colormap`?_Y:vY()},d,.8),r.setDraw(!0,!1,0),n.style=f),r}function S(){let e=o.current;if(!e)return;let{w:t,h:n}=v(),r=y(e,t,n);if(!r)return;let{bg:i,muted:a}=_(),{points:s,color:c,colorByNumeric:l,pointSize:u,model:d}=h.current;r.fillStyle=i,r.fillRect(0,0,t,n);let f=x(t,n);if(s.length===0){f?.setData([],[]),g.current.model=null,f?.render(),r.fillStyle=a,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let p=d.colorExt,{xToPx:m,yToPx:S,plotW:C,plotH:w,ext:T}=b(t,n);if(f)f.setView(T.xLo,T.xHi,T.yLo,T.yHi,{left:pY.left,top:pY.top,width:C,height:w}),f.render();else{for(let e=0;e<s.length;e++){let t=s.x[e],n=s.y[e];if(t!==t||n!==n)continue;let i=d.key?.[e]??0;r.beginPath(),r.arc(m(t),S(n),u,0,Math.PI*2),r.fillStyle=d.mode===`colormap`?gY(i):d.mode===`dataset`?mY[i%mY.length]:c,r.globalAlpha=.8,r.fill()}r.globalAlpha=1}if(l){let e=Math.min(120,Math.floor((n-pY.top-pY.bottom)*.4)),i=t-pY.right-12,o=pY.top+8;for(let t=0;t<e;t++)r.fillStyle=gY(1-t/(e-1)),r.fillRect(i,o+t,8,1);r.fillStyle=a,r.font=`9px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`middle`;let s=e=>Math.abs(e)>=1e4||Math.abs(e)<.001&&e!==0?e.toExponential(1):String(parseFloat(e.toPrecision(3)));r.fillText(s(p.hi),i+10,o),r.fillText(s(p.lo),i+10,o+e)}let E=s.colorLabels??[];if(!l&&E.length>0&&E.length<=10){let e=pY.left,i=n-pY.bottom-10;r.font=`9px ${Q.mono}`,r.textBaseline=`top`,E.forEach((n,o)=>{e>t-pY.right-60&&(e=pY.left,i-=14),r.fillStyle=mY[o%mY.length],r.beginPath(),r.arc(e+4,i+4,4,0,Math.PI*2),r.fill(),r.fillStyle=a,r.textAlign=`left`,r.fillText(n,e+10,i),e+=r.measureText(n).width+20})}}function C(){let e=c.current;if(!e)return;let{w:t,h:n}=v(),r=y(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=d.current;if(i===null)return;let{points:a,pointSize:o}=h.current;if(i<0||i>=a.length)return;let{xToPx:s,yToPx:l}=b(t,n),u=a.x[i],f=a.y[i],p=s(u),m=l(f);r.beginPath(),r.arc(p,m,o+3,0,Math.PI*2),r.strokeStyle=`rgba(255,255,255,0.9)`,r.lineWidth=2,r.stroke();let g=[],_=a.label?.(i);_&&g.push(_);let x=a.colorIndex?.[i];x!==void 0&&x>=0&&a.colorLabels?g.push(a.colorLabels[x]):a.colorValue&&g.push(a.colorValue[i].toFixed(3)),g.push(`(${u.toFixed(3)}, ${f.toFixed(3)})`);let S=g.join(` · `);r.font=`11px ${Q.mono}`;let C=r.measureText(S).width,w=Math.max(4,Math.min(t-C-8,p+10)),T=m-20<pY.top?m+10:m-20;r.fillStyle=`rgba(0,0,0,0.75)`,r.fillRect(w-3,T-3,C+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(S,w,T)}let w=K(S);w.current=S;let T=K(null);T.current??=KH(()=>w.current(),()=>l.current);let E=()=>T.current.schedule(),D=()=>{zH(f.current),f.current=RH(C)};return W(()=>{T.current.now()}),W(()=>()=>T.current?.cancel(),[]),W(()=>{u.current=null,E()},[i]),G(()=>{let e=l.current;if(!e)return;let t=new WH(()=>{u.current=null,E(),D()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=c.current;if(!e)return;let t=null,n=e=>{e.preventDefault(),p.current?.({clientX:e.clientX,clientY:e.clientY})},r=n=>{let r=e.getBoundingClientRect(),{points:i,pointSize:a,model:o}=h.current,{w:s,h:c}=v(),{xToPx:l,yToPx:u,plotW:f,plotH:p}=b(s,c),m=e=>l(i.x[e])-pY.left,g=e=>u(i.y[e])-pY.top,_=a+8,y=`${s}|${c}|${_}`;(!t||t.model!==o||t.key!==y)&&(t={model:o,key:y,g:dY(i.length,f,p,_,m,g)}),d.current=fY(t.g,n.clientX-r.left-pY.left,n.clientY-r.top-pY.top,_,m,g),D()},i=()=>{d.current=null,D()};return e.addEventListener(`contextmenu`,n),e.addEventListener(`mousemove`,r),e.addEventListener(`mouseleave`,i),()=>{e.removeEventListener(`contextmenu`,n),e.removeEventListener(`mousemove`,r),e.removeEventListener(`mouseleave`,i)}},[]),Ot(`div`,{ref:l,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Embedding / scatter`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:c,className:`chart-canvas chart-overlay`})]})}var xY={top:8,right:8,bottom:8,left:8},SY=20,CY=[`#f97316`,`#fb923c`,`#fdba74`,`#fbbf24`,`#fcd34d`,`#4ade80`,`#34d399`,`#38bdf8`,`#818cf8`,`#a78bfa`];function wY(e){let t=new Map;for(let n of e){let e=n.parent??``;t.has(e)||t.set(e,[]),t.get(e).push(n)}function n(r,i){let a=(t.get(r)??[]).map(e=>n(e.name,i+1)),o=e.find(e=>e.name===r),s=a.reduce((e,t)=>e+t.value,0);return{name:r,value:o?Math.max(o.value,s):s,children:a,depth:i,x0:0,x1:1}}let r=new Set(e.map(e=>e.name)),i=e.filter(e=>!e.parent||!r.has(e.parent)).map(e=>n(e.name,0)),a=i.reduce((e,t)=>e+t.value,0)||1;function o(e,t,n){e.x0=t,e.x1=n;let r=n-t,i=t;for(let t of e.children){let n=t.value/e.value*r;o(t,i,i+n),i+=n}}let s=0;for(let e of i){let t=e.value/a;o(e,s,s+t),s+=t}return i}function TY(e){let t=[];function n(e){t.push(e);for(let t of e.children)n(t)}for(let t of e)n(t);return t}function EY(e){let t=0;function n(e){e.depth>t&&(t=e.depth);for(let t of e.children)n(t)}for(let t of e)n(t);return t}function DY(e){return CY[e%CY.length]}function OY({nodes:e,direction:t=`bottomup`,backgroundToken:n=``,onPlotContextMenu:r}){let i=K(null),a=K(null),o=K(null),s=K(null),c=K(null),l=K(0),u=K(r);G(()=>{u.current=r},[r]);let d=K({nodes:e,direction:t});G(()=>{d.current={nodes:e,direction:t}},[e,t]);let f=St(()=>{let t=wY(e);return{roots:t,flat:TY(t),numRows:EY(t)+1}},[e]),p=K(f);G(()=>{p.current=f},[f]);function m(){if(s.current)return s.current;let e=o.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return s.current=n,n}function h(){let e=o.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||400)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function _(e,t,n,r,i){let a=xY.left+e.x0*t,o=(e.x1-e.x0)*t;return{x:a,y:i===`topdown`?xY.top+e.depth*SY:xY.top+n-(e.depth+1)*SY,w:o,h:SY-1}}function v(){let e=i.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;let{bg:a,muted:o}=m(),{nodes:s,direction:c}=d.current;if(r.fillStyle=a,r.fillRect(0,0,t,n),s.length===0){r.fillStyle=o,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{flat:l,numRows:u}=p.current,f=t-xY.left-xY.right,v=u*SY;for(let e of l){let t=_(e,f,v,u,c);if(!(t.w<1)&&(r.fillStyle=DY(e.depth),r.fillRect(t.x,t.y,t.w,t.h),t.w>24)){r.fillStyle=`rgba(0,0,0,0.75)`,r.font=`${Math.min(11,SY-4)}px ${Q.mono}`,r.textAlign=`left`,r.textBaseline=`middle`;let n=e.name,i=Math.floor((t.w-4)/7),a=n.length>i?n.slice(0,i-1)+`…`:n;r.fillText(a,t.x+3,t.y+SY/2)}}}function y(){let e=a.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=c.current;if(!i)return;let{direction:o}=d.current,{roots:s,numRows:l}=p.current;if(s.length===0)return;let u=_(i,t-xY.left-xY.right,l*SY,l,o);r.strokeStyle=`rgba(255,255,255,0.9)`,r.lineWidth=2,r.strokeRect(u.x+1,u.y+1,u.w-2,u.h-2);let f=`${i.name} (${i.value.toLocaleString()})`;r.font=`11px ${Q.mono}`;let m=r.measureText(f).width,v=Math.max(4,Math.min(t-m-8,u.x+u.w/2-m/2)),y=u.y<30?u.y+SY+4:u.y-20;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(v-3,y-3,m+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(f,v,y)}let b=K(v);b.current=v;let x=K(null);x.current??=KH(()=>b.current(),()=>o.current);let S=()=>x.current.schedule(),C=()=>{zH(l.current),l.current=RH(y)};return W(()=>{x.current.now()}),W(()=>()=>x.current?.cancel(),[]),W(()=>{s.current=null,S()},[n]),G(()=>{let e=o.current;if(!e)return;let t=new WH(()=>{s.current=null,S(),C()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=a.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{direction:r}=d.current,{roots:i,flat:a,numRows:o}=p.current;if(i.length===0){c.current=null,C();return}let s=t.clientX-n.left,l=t.clientY-n.top,u=n.width-xY.left-xY.right,f=o*SY,m=null;for(let e of a){let t=_(e,u,f,o,r);if(s>=t.x&&s<=t.x+t.w&&l>=t.y&&l<=t.y+t.h){m=e;break}}c.current=m,C()},r=()=>{c.current=null,C()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:o,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:i,className:`chart-canvas`,role:`img`,"aria-label":`Flame graph`}),q(`canvas`,{ref:a,className:`chart-canvas chart-overlay`})]})}var kY={top:24,right:24,bottom:52,left:56},AY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`],jY=.8;function MY(e,t,n,r){let i,a,o;if(t)a=t.length,i=t.values,o=e=>String(e+1);else{let t=e??[];a=t.length,i=Array.from({length:n},(e,n)=>Float64Array.from(t,e=>e.values[n]??0)),o=e=>t[e].label}let s=0,c=0;if(r===`stacked`)for(let e=0;e<a;e++){let t=0,n=0;for(let r of i){let i=r[e];i>0?t+=i:i<0&&(n+=i)}t>c&&(c=t),n<s&&(s=n)}else for(let e of i)for(let t=0;t<a;t++){let n=e[t];n>c&&(c=n),n<s&&(s=n)}return c===s&&(c=s+1),{n:a,values:i,label:o,lo:s,hi:c}}function NY(e,t,n){let r=e.values.length,i=[],a=[],o=[],s=[],c=[],l=(e,t,n,r,l)=>{i.push(e),a.push(t),o.push(n),s.push(r),c.push(l)};if(e.n<=n)for(let n=0;n<e.n;n++)if(t===`grouped`){let t=.8/r;for(let i=0;i<r;i++){let r=e.values[i][n];r===r&&l(n-.4+i*t,n-.4+(i+1)*t-t*.05,0,r,i)}}else{let t=0,i=0;for(let a=0;a<r;a++){let r=e.values[a][n];r!==r||r===0||(r>0?(l(n-.4,n+.4,t,t+r,a),t+=r):(l(n-.4,n+.4,i,i+r,a),i+=r))}}else{let i=e.n/n,a=new Float64Array(r),o=new Float64Array(r);for(let s=0;s<n;s++){let n=Math.floor(s*i),c=Math.min(e.n,Math.floor((s+1)*i));if(!(c<=n)){a.fill(0),o.fill(0);for(let i=n;i<c;i++){let n=0,s=0;for(let c=0;c<r;c++){let r=e.values[c][i];r===r&&(t===`stacked`?r>0?(n+=r,n>o[c]&&(o[c]=n)):(s+=r,s<a[c]&&(a[c]=s)):(r>o[c]&&(o[c]=r),r<a[c]&&(a[c]=r)))}}for(let e=t===`stacked`?r-1:0;t===`stacked`?e>=0:e<r;t===`stacked`?e--:e++)(o[e]!==0||a[e]!==0)&&l(n-.5,c-.5,a[e],o[e],e)}}}return{x0:Float64Array.from(i),x1:Float64Array.from(a),y0:Float64Array.from(o),y1:Float64Array.from(s),k:Float64Array.from(c)}}function PY({groups:e,columns:t,seriesNames:n,colors:r,mode:i=`grouped`,horizontal:a=!1,valueRange:o,backgroundToken:s=``,onPlotContextMenu:c}){let l=IU(),u=K(null),d=K(null),f=K(null),p=K(null),m=K(null),h=K(null),g=K(0),_=K(c);G(()=>{_.current=c},[c]);let v=K(null),y=St(()=>{let r=[e,i,n.length,t?.length,...t?.values??[]],a=v.current;if(a&&a.key.length===r.length&&a.key.every((e,t)=>e===r[t]))return a.value;let o=MY(e,t,n.length,i);return v.current={key:r,value:o},o},[e,t,n.length,i]),b=K({bars:y,seriesNames:n,colors:r,mode:i,horizontal:a,valueRange:o});G(()=>{b.current={bars:y,seriesNames:n,colors:r,mode:i,horizontal:a,valueRange:o}},[y,n,r,i,a,o]);let x=K({plot:null,failed:!1,key:``,data:null,size:``});W(()=>()=>{x.current.plot?.dispose(),x.current.plot=null},[]);let S=K({bars:null,view:``});function C(){if(m.current)return m.current;let e=p.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return m.current=n,n}function w(){let e=p.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function T(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function E(e){let t=b.current.colors??[];return Array.from({length:e},(e,n)=>t[n]??AY[n%AY.length])}function D(e,t){let{bars:n,valueRange:r}=b.current,i=n.lo,a=n.hi;r?.min!==void 0&&Number.isFinite(r.min)&&(i=r.min),r?.max!==void 0&&Number.isFinite(r.max)&&(a=r.max);let o=MG(kY,e,t),{top:s,right:c,bottom:l,left:u}=o;return{lo:i,hi:a,top:s,left:u,plotW:e-u-c,plotH:t-s-l,tiny:o.tiny}}function O(e,t){let n=x.current;if(!n.plot&&!n.failed&&d.current&&(n.plot=dH(d.current,yq),n.failed=!n.plot),!n.plot||!d.current)return null;let r=Math.min(2,window.devicePixelRatio||1),i=`${e}x${t}@${r}`;return n.size!==i&&(n.plot.resize(e,t,r),d.current.style.width=`${e}px`,d.current.style.height=`${t}px`,n.size=i),n.plot}function k(){let e=u.current;if(!e)return;let{w:t,h:n}=w(),r=T(e,t,n);if(!r)return;let{bg:i,muted:a,grid:o}=C(),{bars:s,seriesNames:c,mode:d,horizontal:f}=b.current;r.fillStyle=i,r.fillRect(0,0,t,n);let m=O(t,n);if(s.n===0||c.length===0){m?.keep([]),m?.render(),r.fillStyle=a,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{lo:h,hi:g,top:_,left:v,plotW:y,plotH:k,tiny:A}=D(t,n),j=E(c.length),M=f?k:y,N=e=>f?v+(e-h)/(g-h)*y:_+k-(e-h)/(g-h)*k,P=e=>(f?_:v)+(e+.5)/s.n*M;l({left:v,top:_,width:y,height:k,...f?{x:{v0:h,v1:g}}:{y:{v0:h,v1:g}}}),r.strokeStyle=o,r.lineWidth=1;for(let e=0;e<=5;e++){let t=h+e/5*(g-h),n=N(t);r.beginPath(),f?(r.moveTo(n,_),r.lineTo(n,_+k)):(r.moveTo(v,n),r.lineTo(v+y,n)),r.stroke(),r.fillStyle=a,r.font=`9px ${Q.mono}`,!A&&(f?(r.textAlign=`center`,r.textBaseline=`top`,r.fillText(Vz(t,(g-h)/5),n,_+k+4)):(r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(Vz(t,(g-h)/5),v-4,n)))}let F=`${h}|${g}|${f}`;(S.current.bars!==s||S.current.view!==F)&&(S.current={bars:s,view:F},VH(p.current));let I=Math.min(2,window.devicePixelRatio||1),L=Math.max(1,Math.round(M*I)),R=j.map(e=>{let t=qV(e);return[t[0],t[1],t[2],jY]}),z={left:v,top:_,width:y,height:k};if(m){let e=`${d}|${f}|${L}|${j.join(`,`)}`;if(x.current.key!==e||x.current.data!==s){let t=NY(s,d,L);f?m.setRects(`bars`,t.y0,t.y1,t.x0,t.x1,R,t.k):m.setRects(`bars`,t.x0,t.x1,t.y0,t.y1,R,t.k),m.keep([`bars`]),x.current.key=e,x.current.data=s}f?m.setView(h,g,s.n-.5,-.5,z):m.setView(-.5,s.n-.5,h,g,z),m.render()}else{let e=NY(s,d,L);r.globalAlpha=jY;for(let t=0;t<e.x0.length;t++){r.fillStyle=j[e.k[t]];let n=P(e.x0[t]-.5),i=P(e.x1[t]-.5),a=N(e.y0[t]),o=N(e.y1[t]);f?r.fillRect(Math.min(a,o),n,Math.max(1,Math.abs(o-a)),Math.max(1,i-n)):r.fillRect(n,Math.min(a,o),Math.max(1,i-n),Math.max(1,Math.abs(o-a)))}r.globalAlpha=1}if(h<0&&g>0){let e=N(0);r.strokeStyle=a,r.lineWidth=1.5,r.beginPath(),f?(r.moveTo(e,_),r.lineTo(e,_+k)):(r.moveTo(v,e),r.lineTo(v+y,e)),r.stroke()}r.fillStyle=a,r.font=`9px ${Q.mono}`;let B=Math.max(1,Math.ceil(s.n/Math.max(1,Math.floor(M/(f?14:48)))));for(let e=0;e<(A?0:s.n);e+=B){let t=P(e),n=s.label(e),i=n.length>14?n.slice(0,13)+`…`:n;f?(r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(i,v-4,t)):(r.textAlign=`center`,r.textBaseline=`top`,r.fillText(i,t,_+k+4))}if(c.length>1&&!A){let e=f?_-14:_+k+32,t=v;r.font=`9px ${Q.mono}`,r.textBaseline=`top`;for(let n=0;n<c.length&&(r.fillStyle=j[n],r.fillRect(t,e,10,8),r.fillStyle=a,r.textAlign=`left`,r.fillText(c[n],t+13,e),t+=r.measureText(c[n]).width+26,!(t>v+y-30));n++);}}function A(){let e=f.current;if(!e)return;let{w:t,h:n}=w(),r=T(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=h.current,{bars:a,seriesNames:o,horizontal:s}=b.current;if(i===null||i>=a.n)return;let{top:c,left:l,plotW:u,plotH:d}=D(t,n),p=s?d:u,m=(s?c:l)+(i+.5)/a.n*p,g=Math.max(1,p/a.n);r.fillStyle=`rgba(255,255,255,0.08)`,s?r.fillRect(l,m-g/2,u,g):r.fillRect(m-g/2,c,g,d);let _=a.values.map((e,t)=>`${o.length>1?o[t]+` `:``}${Hz(e[i])}`).join(` `),v=`${a.label(i)}: ${_}`;r.font=`11px ${Q.mono}`;let y=r.measureText(v).width,x=s?l+u/2:m,S=s?m:c+d/2,C=Math.max(4,Math.min(t-y-8,x-y/2)),E=S-28<c?S+10:S-24;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(C-3,E-3,y+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(v,C,E)}let j=K(k);j.current=k;let M=K(null);M.current??=KH(()=>j.current(),()=>p.current);let N=()=>{g.current||=RH(()=>{g.current=0,A()})};return W(()=>{M.current.now()},[y,n,r,i,a,o]),W(()=>()=>{M.current?.cancel(),zH(g.current)},[]),W(()=>{m.current=null,M.current.schedule()},[s]),G(()=>{let e=p.current;if(!e)return;let t=new WH(()=>{m.current=null,M.current.schedule(),N()});return t.observe(e),()=>t.disconnect()},[]),G(()=>{let e=f.current;if(!e)return;let t=e=>{e.preventDefault(),_.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{bars:r,horizontal:i}=b.current,{w:a,h:o}=w(),{top:s,left:c,plotW:l,plotH:u}=D(a,o),d=i?t.clientY-n.top-s:t.clientX-n.left-c,f=i?u:l,p=d>=0&&d<f&&r.n>0?Math.min(r.n-1,Math.floor(d/f*r.n)):null;p!==h.current&&(h.current=p,N())},r=()=>{h.current=null,N()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:p,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:u,className:`chart-canvas`,role:`img`,"aria-label":`Bar chart`}),q(`canvas`,{ref:d,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:f,className:`chart-canvas chart-overlay`})]})}var FY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function IY(e,t){if(!t)return FY[e%FY.length];if(e===0)return t;let n=FY.filter(e=>e.toLowerCase()!==t.toLowerCase());return n[(e-1)%n.length]}var LY={top:36,right:36,bottom:36,left:36};function RY({axes:e,series:t,fill:n=!0,color:r,backgroundToken:i=``,onPlotContextMenu:a}){let o=K(null),s=K(null),c=K(null),l=K(null),u=K(a);G(()=>{u.current=a},[a]);let d=K({axes:e,series:t,fill:n,color:r});G(()=>{d.current={axes:e,series:t,fill:n,color:r}},[e,t,n,r]);function f(){if(l.current)return l.current;let e=c.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return l.current=n,n}function p(){let e=c.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function m(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function h(){let e=o.current;if(!e)return;let{w:t,h:n}=p(),r=m(e,t,n);if(!r)return;let{bg:i,muted:a,grid:s}=f(),{axes:c,series:l,fill:u}=d.current;if(r.fillStyle=i,r.fillRect(0,0,t,n),c.length<3||l.length===0){r.fillStyle=a,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`Select ≥ 3 axes`,LY.left+8,LY.top+8);return}let h=c.length,g=t/2,_=n/2,v=Math.min(t-LY.left-LY.right,n-LY.top-LY.bottom)/2,y=c.map((e,t)=>{let n=0;for(let e of l){let r=e.values[t]??0;r>n&&(n=r)}return n||1});function b(e){return Math.PI*2*e/h-Math.PI/2}function x(e,t){let n=b(e);return{x:g+Math.cos(n)*v*t,y:_+Math.sin(n)*v*t}}for(let e=1;e<=4;e++){let t=e/4;r.beginPath();for(let e=0;e<h;e++){let n=x(e,t);e===0?r.moveTo(n.x,n.y):r.lineTo(n.x,n.y)}r.closePath(),r.strokeStyle=s,r.lineWidth=1,r.stroke()}r.strokeStyle=a,r.lineWidth=1;for(let e=0;e<h;e++){let t=x(e,1);r.beginPath(),r.moveTo(g,_),r.lineTo(t.x,t.y),r.stroke(),r.fillStyle=a,r.font=`10px ${Q.mono}`;let n=b(e),i=x(e,1+10/v);r.textAlign=Math.abs(Math.cos(n))<.1?`center`:Math.cos(n)<0?`right`:`left`,r.textBaseline=Math.abs(Math.sin(n))<.1?`middle`:Math.sin(n)<0?`bottom`:`top`;let o=c[e].length>12?c[e].slice(0,11)+`…`:c[e];r.fillText(o,i.x,i.y)}for(let e=0;e<l.length;e++){let t=l[e],n=IY(e,d.current.color);r.beginPath();for(let e=0;e<h;e++){let n=Math.max(0,Math.min(1,(t.values[e]??0)/y[e])),i=x(e,n);e===0?r.moveTo(i.x,i.y):r.lineTo(i.x,i.y)}r.closePath(),u&&(r.fillStyle=n,r.globalAlpha=.15,r.fill()),r.globalAlpha=1,r.strokeStyle=n,r.lineWidth=1,r.stroke();for(let e=0;e<h;e++){let i=Math.max(0,Math.min(1,(t.values[e]??0)/y[e])),a=x(e,i);r.beginPath(),r.arc(a.x,a.y,3,0,Math.PI*2),r.fillStyle=n,r.globalAlpha=.9,r.fill()}r.globalAlpha=1}if(l.length>1){let e=LY.left,i=n-LY.bottom-10;r.font=`9px ${Q.mono}`,r.textBaseline=`top`;for(let n=0;n<l.length&&(r.fillStyle=IY(n,d.current.color),r.fillRect(e,i,10,8),r.fillStyle=a,r.textAlign=`left`,r.fillText(l[n].name,e+13,i),e+=r.measureText(l[n].name).width+26,!(e>t-LY.right-30));n++);}}let g=K(h);g.current=h;let _=K(null);_.current??=KH(()=>g.current(),()=>c.current);let v=()=>_.current.schedule();return W(()=>{_.current.now()}),W(()=>()=>_.current?.cancel(),[]),W(()=>{l.current=null,v()},[i]),G(()=>{let e=c.current;if(!e)return;let t=new WH(()=>{l.current=null,v()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=s.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})};return e.addEventListener(`contextmenu`,t),()=>{e.removeEventListener(`contextmenu`,t)}},[]),Ot(`div`,{ref:c,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Radar chart`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`})]})}var zY={top:16,right:16,bottom:40,left:52},BY=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function VY(e,t){let n=e.length>0&&e.every(t=>t.x===e[0].x||t.x.length===e[0].x.length),r=t&&n,i=e.map(e=>e.x),a=[],o=[],s=null;for(let t of e){if(!r){a.push(t.y),o.push(null);continue}let e=t.x.length,n=new Float64Array(e);for(let r=0;r<e;r++){let e=t.y[r];n[r]=(s?s[r]:0)+(e>0?e:0)}a.push(n),o.push(s??null),s=n}let c=1/0,l=-1/0,u=0,d=0;for(let e of i)for(let t=0;t<e.length;t++){let n=e[t];n<c&&(c=n),n>l&&(l=n)}for(let e of a)for(let t=0;t<e.length;t++){let n=e[t];n<u&&(u=n),n>d&&(d=n)}return Number.isFinite(c)||(c=0,l=1),{x:i,lo:o,hi:a,ascending:i.map(e=>Oq(e)),xLo:c,xHi:l,yLo:u,yHi:d}}function HY({series:e,stacked:t=!1,yRange:n,backgroundToken:r=``,onPlotContextMenu:i}){let a=IU(),o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(null),f=K(0),p=K(i);G(()=>{p.current=i},[i]);let m=K(null),h=St(()=>{let n=m.current;if(n&&n.stacked===t&&n.series.length===e.length&&n.series.every((t,n)=>t.x===e[n].x&&t.y===e[n].y&&t.name===e[n].name))return n.value;let r=VY(e,t);return m.current={series:e,stacked:t,value:r},r},[e,t]),g=K({series:e,prepared:h,yRange:n});G(()=>{g.current={series:e,prepared:h,yRange:n}},[e,h,n]);let _=K({plot:null,failed:!1,key:``,size:``});W(()=>()=>{_.current.plot?.dispose(),_.current.plot=null},[]);let v=K({prepared:null,view:``});function y(){if(u.current)return u.current;let e=l.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return u.current=n,n}function b(){let e=l.current;return{w:Math.max(1,e?.clientWidth||600),h:Math.max(1,e?.clientHeight||300)}}function x(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function S(e,t){let n=(e.xHi-e.xLo)*.01||.5,r=e.yLo,i=e.yHi;return i===r&&(i=r+1),i+=(i-r)*.05,t?.min!==void 0&&Number.isFinite(t.min)&&(r=t.min),t?.max!==void 0&&Number.isFinite(t.max)&&(i=t.max),{xLo:e.xLo-n,xHi:e.xHi+n,yLo:r,yHi:i}}function C(e,t,n,r,i){let a=e.x[t],o=e.hi[t],s=e.lo[t];if(!e.ascending[t]||a.length<=2*i)return{x:a,hi:o,lo:s??new Float64Array(a.length)};let c=Tq(a,o,n,r,i);return{x:Dq(a,c),hi:Dq(o,c),lo:s?Dq(s,c):new Float64Array(c.length)}}function w(){let e=o.current;if(!e)return;let{w:n,h:r}=b(),i=x(e,n,r);if(!i)return;let{bg:s,muted:c,grid:u}=y(),{series:d,prepared:f,yRange:p}=g.current;i.fillStyle=s,i.fillRect(0,0,n,r);let m=_.current.plot;if(d.length===0){m?.keep([]),m?.render(),i.fillStyle=c,i.font=`13px ${Q.sans}`,i.textAlign=`left`,i.textBaseline=`top`,UV(i);return}let h=MG(zY,n,r),{top:w,right:D,bottom:O,left:k}=h,A=n-k-D,j=r-w-O,{xLo:M,xHi:N,yLo:P,yHi:F}=S(f,p),I=e=>k+(e-M)/(N-M)*A,L=e=>w+j-(e-P)/(F-P)*j;a({left:k,top:w,width:A,height:j,x:{v0:M,v1:N},y:{v0:P,v1:F}}),i.strokeStyle=u,i.lineWidth=1;for(let e=0;e<=5;e++){let t=P+e/5*(F-P),n=L(t);i.beginPath(),i.moveTo(k,n),i.lineTo(k+A,n),i.stroke(),i.fillStyle=c,i.font=`9px ${Q.mono}`,i.textAlign=`right`,i.textBaseline=`middle`,h.tiny||i.fillText(Vz(t,(F-P)/5),k-4,n)}let R=Math.min(8,f.x[0]?.length??5);for(let e=0;e<=R;e++){let t=M+e/R*(N-M),n=I(t);i.beginPath(),i.moveTo(n,w),i.lineTo(n,w+j),i.stroke(),i.fillStyle=c,i.font=`9px ${Q.mono}`,i.textAlign=`center`,i.textBaseline=`top`,h.tiny||i.fillText(Vz(t,(N-M)/R),n,w+j+4)}let z=`${M}|${N}|${P}|${F}`;(v.current.prepared!==f||v.current.view!==z)&&(v.current={prepared:f,view:z},VH(l.current));let B=E(n,r),V=Math.min(2,window.devicePixelRatio||1),ee=Math.max(1,Math.round(A*V)),te=d.map((e,t)=>qV(BY[t%BY.length]));if(B){let e=`${M}|${N}|${ee}`;if(_.current.key!==e||T.current!==f){let n=[];for(let e=0;e<d.length;e++){let r=C(f,e,M,N,ee),i=te[e],a=[i[0],i[1],i[2],f.lo[e]||t?.7:.25];B.setBands(`b${e}`,r.x,r.lo,r.hi,a),B.setLine(`l${e}`,r.x,r.hi,i,1),n.push(`b${e}`,`l${e}`)}B.keep(n),_.current.key=e,T.current=f}B.setView(M,N,P,F,{left:k,top:w,width:A,height:j}),B.render()}else for(let e=0;e<d.length;e++){let n=C(f,e,M,N,ee),r=BY[e%BY.length];i.save(),i.beginPath(),i.rect(k,w,A,j),i.clip(),i.beginPath();for(let e=0;e<n.x.length;e++){let t=I(n.x[e]);e===0?i.moveTo(t,L(n.lo[e])):i.lineTo(t,L(n.lo[e]))}for(let e=n.x.length-1;e>=0;e--)i.lineTo(I(n.x[e]),L(n.hi[e]));i.closePath(),i.fillStyle=r,i.globalAlpha=f.lo[e]||t?.7:.25,i.fill(),i.beginPath();for(let e=0;e<n.x.length;e++){let t=I(n.x[e]),r=L(n.hi[e]);e===0?i.moveTo(t,r):i.lineTo(t,r)}i.globalAlpha=1,i.strokeStyle=r,i.lineWidth=1,i.stroke(),i.restore()}if(d.length>1&&!h.tiny){let e=k,t=w+j+24;i.font=`9px ${Q.mono}`,i.textBaseline=`top`;for(let n=0;n<d.length&&(i.fillStyle=BY[n%BY.length],i.fillRect(e,t,10,8),i.fillStyle=c,i.textAlign=`left`,i.fillText(d[n].name,e+13,t),e+=i.measureText(d[n].name).width+26,!(e>k+A-30));n++);}}let T=K(null);function E(e,t){let n=_.current;if(!n.plot&&!n.failed&&s.current&&(n.plot=dH(s.current,yq),n.failed=!n.plot),!n.plot||!s.current)return null;let r=Math.min(2,window.devicePixelRatio||1),i=`${e}x${t}@${r}`;return n.size!==i&&(n.plot.resize(e,t,r),s.current.style.width=`${e}px`,s.current.style.height=`${t}px`,n.size=i),n.plot}function D(){let e=c.current;if(!e)return;let{w:t,h:n}=b(),r=x(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=d.current;if(i===null)return;let{prepared:a,yRange:o}=g.current,{top:s,right:l,left:u,bottom:f}=MG(zY,t,n),p=n-s-f;r.strokeStyle=`rgba(255,255,255,0.4)`,r.lineWidth=1,r.setLineDash([4,4]),r.beginPath(),r.moveTo(i,s),r.lineTo(i,s+p),r.stroke(),r.setLineDash([]);let{xLo:m,xHi:h}=S(a,o),_=t-u-l,v=`x=${Hz(m+(i-u)/_*(h-m))}`;r.font=`11px ${Q.mono}`;let y=r.measureText(v).width,C=Math.max(4,Math.min(t-y-8,i-y/2));r.fillStyle=`rgba(0,0,0,0.7)`,r.fillRect(C-3,s-3,y+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(v,C,s)}let O=K(w);O.current=w;let k=K(null);k.current??=KH(()=>O.current(),()=>l.current);let A=()=>{f.current||=RH(()=>{f.current=0,D()})};return W(()=>{k.current.now()},[e,h,n]),W(()=>()=>{k.current?.cancel(),zH(f.current)},[]),W(()=>{u.current=null,k.current.schedule()},[r]),G(()=>{let e=l.current;if(!e)return;let t=new WH(()=>{u.current=null,k.current.schedule(),A()});return t.observe(e),()=>t.disconnect()},[]),G(()=>{let e=c.current;if(!e)return;let t=e=>{e.preventDefault(),p.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect();d.current=t.clientX-n.left,A()},r=()=>{d.current=null,A()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:l,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`Area chart`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:c,className:`chart-canvas chart-overlay`})]})}var UY={top:16,right:16,bottom:40,left:52},WY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function GY({series:e,complement:t=!1,logX:n=!1,backgroundToken:r=``,onPlotContextMenu:i}){let a=IU(),o=K(null),s=K(null),c=K(null),l=K(null),u=K(null),d=K(0),f=K(i);G(()=>{f.current=i},[i]);let p=K({series:e,complement:t,logX:n});G(()=>{p.current={series:e,complement:t,logX:n}},[e,t,n]);let m=St(()=>{let t=e.map(e=>Float64Array.from(e.values).sort()),n=1/0,r=-1/0;for(let e of t)e.length&&(n=Math.min(n,e[0]),r=Math.max(r,e[e.length-1]));return{all:t,xLo:n,xHi:r}},[e]),h=K(m);G(()=>{h.current=m},[m]);function g(){if(l.current)return l.current;let e=c.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return l.current=n,n}function _(){let e=c.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function v(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function y(){let e=o.current;if(!e)return;let{w:t,h:n}=_(),r=v(e,t,n);if(!r)return;let{bg:i,muted:s,grid:c}=g(),{series:l,complement:u,logX:d}=p.current;if(r.fillStyle=i,r.fillRect(0,0,t,n),l.length===0){r.fillStyle=s,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{top:f,right:m,bottom:y,left:b}=UY,x=t-b-m,S=n-f-y,{xLo:C,xHi:w}=h.current;Number.isFinite(C)||(C=0,w=1);let T=e=>Math.log10(Math.max(1e-10,e)),E=d?T(C):C,D=d?T(w):w,O=e=>b+((d?T(e):e)-E)/(D-E||1)*x,k=e=>f+S-e*S;a({left:b,top:f,width:x,height:S,x:{v0:C,v1:w,log:d}});for(let e=0;e<=5;e++){let t=e/5,n=k(t);r.strokeStyle=c,r.lineWidth=1,r.beginPath(),r.moveTo(b,n),r.lineTo(b+x,n),r.stroke(),r.fillStyle=s,r.font=`9px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(String(t.toFixed(2)),b-4,n)}for(let e=0;e<=6;e++){let t=C+e/6*(w-C),n=O(t);r.strokeStyle=c,r.lineWidth=1,r.beginPath(),r.moveTo(n,f),r.lineTo(n,f+S),r.stroke(),r.fillStyle=s,r.font=`9px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`,r.fillText(Vz(t,(w-C)/6),n,f+S+4)}for(let e=0;e<l.length;e++){let t=h.current.all[e],n=t?.length??0;if(n===0)continue;let i=e=>k(u?1-(e+1)/n:(e+1)/n),a=O(t[0]),o=k(+!!u);r.beginPath(),r.moveTo(a,o);for(let e=0;e<n;e++){if(e+1<n&&t[e+1]===t[e])continue;let s=O(t[e]),c=i(e);if(Math.abs(s-a)<.5){o=c;continue}r.lineTo(a,o),r.lineTo(s,o),a=s,o=c}r.lineTo(a,o),r.strokeStyle=WY[e%WY.length],r.lineWidth=1,r.stroke()}if(l.length>1){let e=b,t=f+S+24;r.font=`9px ${Q.mono}`,r.textBaseline=`top`;for(let n=0;n<l.length&&(r.fillStyle=WY[n%WY.length],r.fillRect(e,t,16,2),r.fillStyle=s,r.textAlign=`left`,r.fillText(l[n].name,e+20,t-3),e+=r.measureText(l[n].name).width+30,!(e>b+x-30));n++);}r.save(),r.translate(12,f+S/2),r.rotate(-Math.PI/2),r.fillStyle=s,r.font=`9px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(u?`CCDF`:`CDF`,0,0),r.restore()}function b(){let e=s.current;if(!e)return;let{w:t,h:n}=_(),r=v(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=u.current;if(i===null)return;let{top:a,left:o,right:c}=UY,l=n-a-UY.bottom,d=t-o-c;r.strokeStyle=`rgba(255,255,255,0.4)`,r.lineWidth=1,r.setLineDash([4,4]),r.beginPath(),r.moveTo(i,a),r.lineTo(i,a+l),r.stroke(),r.setLineDash([]);let{xLo:f,xHi:p}=h.current;if(!Number.isFinite(f))return;let m=Hz(f+(i-o)/d*(p-f));r.font=`11px ${Q.mono}`;let g=r.measureText(m).width,y=Math.max(4,Math.min(t-g-8,i-g/2));r.fillStyle=`rgba(0,0,0,0.7)`,r.fillRect(y-3,a+l+2,g+6,16),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(m,y,a+l+4)}let x=K(y);x.current=y;let S=K(null);S.current??=KH(()=>x.current(),()=>c.current);let C=()=>S.current.schedule(),w=()=>{zH(d.current),d.current=RH(b)};return W(()=>{S.current.now()}),W(()=>()=>S.current?.cancel(),[]),W(()=>{l.current=null,C()},[r]),G(()=>{let e=c.current;if(!e)return;let t=new WH(()=>{l.current=null,C(),w()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=s.current;if(!e)return;let t=e=>{e.preventDefault(),f.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect();u.current=t.clientX-n.left,w()},r=()=>{u.current=null,w()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:c,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:o,className:`chart-canvas`,role:`img`,"aria-label":`CDF chart`}),q(`canvas`,{ref:s,className:`chart-canvas chart-overlay`})]})}var KY={top:16,right:40,bottom:40,left:52},qY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function JY(e){return[Math.round(255*Math.min(1,Math.max(0,3.5*e-.5))),Math.round(255*Math.min(1,Math.max(0,e<.5?2*e:2-2*e))),Math.round(255*Math.min(1,Math.max(0,1.5-3.5*e)))]}function YY(e){let[t,n,r]=JY(e);return`rgb(${t},${n},${r})`}var XY=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++)e.set([...JY(t/255),255],t*4);return e})(),ZY=()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++){let[n,r,i]=NK(qY[t%qY.length],1);e.set([n*255,r*255,i*255,255],t*4)}return e};function QY(e,t,n){let r=e.length,i=1/0,a=-1/0,o=1/0,s=-1/0,c=1/0,l=-1/0;for(let t=0;t<r;t++){let n=e.x[t],r=e.y[t],u=e.size[t];n<i&&(i=n),n>a&&(a=n),r<o&&(o=r),r>s&&(s=r),u<c&&(c=u),u>l&&(l=u)}let u=Number.isFinite(i)?(()=>{let e=(a-i)*.1||1,t=(s-o)*.1||1;return{xLo:i-e,xHi:a+e,yLo:o-t,yHi:s+t,sLo:c,sHi:l}})():{xLo:-1,xHi:1,yLo:-1,yHi:1,sLo:1,sHi:1},d=u.sHi-u.sLo||1,f=new Float32Array(r);for(let t=0;t<r;t++)f[t]=3+(e.size[t]-u.sLo)/d*(n-3);let p=0,m=1,h=null,g=`single`;if(t&&e.colorValue){let t=e.colorValue,n=1/0,i=-1/0;for(let e=0;e<r;e++)t[e]<n&&(n=t[e]),t[e]>i&&(i=t[e]);Number.isFinite(n)&&(p=n,m=i),h=new Float32Array(r);for(let e=0;e<r;e++)h[e]=t[e]===t[e]?Math.max(0,Math.min(1,(t[e]-p)/(m-p||1))):0;g=`colormap`}else !t&&e.colorIndex&&(h=Float32Array.from(e.colorIndex,e=>e>=0?e%256:0),g=`dataset`);let _=Uint32Array.from({length:r},(e,t)=>t).sort((e,t)=>(f[t]||0)-(f[e]||0)),v=e=>{let t=new Float64Array(r);for(let n=0;n<r;n++)t[n]=e[_[n]];return t};return{ext:u,radius:f,key:h,mode:g,colorLo:p,colorHi:m,drawn:{x:v(e.x),y:v(e.y),r:v(f),k:h?v(h):void 0}}}function $Y({points:e,color:t=`#64748b`,colorByNumeric:n=!1,maxRadius:r=24,backgroundToken:i=``,onPlotContextMenu:a}){let o=IU(),s=K(null),c=K(null),l=K(null),u=K(null),d=K(null),f=K(null),p=K(0),m=K(a);G(()=>{m.current=a},[a]);let h=St(()=>QY(e,n,r),[e,n,r]),g=K({points:e,color:t,colorByNumeric:n,maxRadius:r,model:h});G(()=>{g.current={points:e,color:t,colorByNumeric:n,maxRadius:r,model:h}},[e,t,n,r,h]);let _=K({r:null,failed:!1,size:``,model:null,style:``});W(()=>()=>{_.current.r?.dispose(),_.current.r=null},[]);function v(){if(d.current)return d.current;let e=u.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return d.current=n,n}function y(){let e=u.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function b(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function x(e,t){let{xLo:n,xHi:r,yLo:i,yHi:a}=g.current.model.ext,{top:s,right:c,bottom:l,left:u}=KY,d=e-u-c,f=t-s-l;return o({left:u,top:s,width:d,height:f,x:{v0:n,v1:r},y:{v0:i,v1:a}}),{plotW:d,plotH:f,xToPx:e=>u+(e-n)/(r-n)*d,yToPx:e=>s+(1-(e-i)/(a-i))*f}}function S(e,t){let n=_.current;!n.r&&!n.failed&&c.current&&(n.r=dH(c.current,AG),n.failed=!n.r);let r=n.r;if(!r||!c.current)return null;let i=Math.min(2,window.devicePixelRatio||1),a=`${e}x${t}@${i}`;n.size!==a&&(r.resize(e,t,i),c.current.style.width=`${e}px`,c.current.style.height=`${t}px`,n.size=a);let{model:o,color:s}=g.current;n.model!==o&&(r.setData(o.drawn.x,o.drawn.y,o.drawn.k,!1,o.drawn.r),n.model=o,VH(u.current));let l=`${o.mode}|${s}`;return n.style!==l&&(r.setStyle(o.mode===`single`?{kind:`single`,rgba:NK(s,1)}:{kind:o.mode,palette:o.mode===`colormap`?XY:ZY()},3,.65),r.setDraw(!0,!1,0),n.style=l),r}function C(){let e=s.current;if(!e)return;let{w:t,h:n}=y(),r=b(e,t,n);if(!r)return;let{bg:i,muted:a,grid:o}=v(),{points:c,color:l,colorByNumeric:u,model:d}=g.current;r.fillStyle=i,r.fillRect(0,0,t,n);let f=S(t,n);if(c.length===0){f?.setData([],[]),_.current.model=null,f?.render(),r.fillStyle=a,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{xLo:p,xHi:m,yLo:h,yHi:C}=d.ext,{top:w,left:T}=KY,{plotW:E,plotH:D,xToPx:O,yToPx:k}=x(t,n);r.strokeStyle=o,r.lineWidth=1;for(let e=0;e<=5;e++){let t=p+e/5*(m-p),n=O(t);r.beginPath(),r.moveTo(n,w),r.lineTo(n,w+D),r.stroke(),r.fillStyle=a,r.font=`9px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`,r.fillText(Vz(t,(m-p)/5),n,w+D+4);let i=h+e/5*(C-h),o=k(i);r.beginPath(),r.moveTo(T,o),r.lineTo(T+E,o),r.stroke(),r.fillStyle=a,r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(Vz(i,(C-h)/5),T-4,o)}if(f)f.setView(p,m,h,C,{left:T,top:w,width:E,height:D}),f.render();else{let e=d.drawn;r.globalAlpha=.65;for(let t=0;t<e.x.length;t++){if(e.x[t]!==e.x[t]||e.y[t]!==e.y[t])continue;let n=e.k?.[t]??0;r.fillStyle=d.mode===`colormap`?YY(n):d.mode===`dataset`?qY[n%qY.length]:l,r.beginPath(),r.arc(O(e.x[t]),k(e.y[t]),e.r[t],0,Math.PI*2),r.fill()}r.globalAlpha=1}let A=c.colorLabels??[];if(!u&&A.length>0&&A.length<=10){let e=T,t=n-KY.bottom-10;r.font=`9px ${Q.mono}`,r.textBaseline=`top`;for(let n=0;n<A.length;n++){let i=A[n];if(r.fillStyle=qY[n%qY.length],r.beginPath(),r.arc(e+4,t+4,4,0,Math.PI*2),r.fill(),r.fillStyle=a,r.textAlign=`left`,r.fillText(i,e+10,t),e+=r.measureText(i).width+20,e>T+E-60)break}}}function w(){let e=l.current;if(!e)return;let{w:t,h:n}=y(),r=b(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=f.current;if(i===null)return;let{points:a,model:o}=g.current;if(i<0||i>=a.length)return;let{xToPx:s,yToPx:c}=x(t,n),u=o.radius[i],d=s(a.x[i]),p=c(a.y[i]);r.beginPath(),r.arc(d,p,u+2,0,Math.PI*2),r.strokeStyle=`rgba(255,255,255,0.9)`,r.lineWidth=2,r.stroke();let m=[],h=a.label?.(i);h&&m.push(h),m.push(`(${Hz(a.x[i])}, ${Hz(a.y[i])})`),m.push(`size=${Hz(a.size[i])}`);let _=a.colorIndex?.[i];_!==void 0&&_>=0&&a.colorLabels?m.push(a.colorLabels[_]):a.colorValue&&m.push(Hz(a.colorValue[i]));let v=m.join(` · `);r.font=`11px ${Q.mono}`;let S=r.measureText(v).width,C=Math.max(4,Math.min(t-S-8,d+u+4)),w=p-20<KY.top?p+u+4:p-20;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(C-3,w-3,S+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(v,C,w)}let T=K(C);T.current=C;let E=K(null);E.current??=KH(()=>T.current(),()=>u.current);let D=()=>E.current.schedule(),O=()=>{zH(p.current),p.current=RH(w)};return W(()=>{E.current.now()}),W(()=>()=>E.current?.cancel(),[]),W(()=>{d.current=null,D()},[i]),G(()=>{let e=u.current;if(!e)return;let t=new WH(()=>{d.current=null,D(),O()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=l.current;if(!e)return;let t=null,n=e=>{e.preventDefault(),m.current?.({clientX:e.clientX,clientY:e.clientY})},r=n=>{let r=e.getBoundingClientRect(),{points:i,maxRadius:a,model:o}=g.current,{w:s,h:c}=y(),{plotW:l,plotH:u,xToPx:d,yToPx:p}=x(s,c),m=e=>d(i.x[e])-KY.left,h=e=>p(i.y[e])-KY.top,_=a+6,v=`${s}|${c}|${_}`;(!t||t.model!==o||t.key!==v)&&(t={model:o,key:v,g:dY(i.length,l,u,_,m,h)}),f.current=fY(t.g,n.clientX-r.left-KY.left,n.clientY-r.top-KY.top,_,m,h,e=>o.radius[e]+6),O()},i=()=>{f.current=null,O()};return e.addEventListener(`contextmenu`,n),e.addEventListener(`mousemove`,r),e.addEventListener(`mouseleave`,i),()=>{e.removeEventListener(`contextmenu`,n),e.removeEventListener(`mousemove`,r),e.removeEventListener(`mouseleave`,i)}},[]),Ot(`div`,{ref:u,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:s,className:`chart-canvas`,role:`img`,"aria-label":`Bubble chart`}),q(`canvas`,{ref:c,className:`chart-canvas chart-overlay`,style:{pointerEvents:`none`}}),q(`canvas`,{ref:l,className:`chart-canvas chart-overlay`})]})}var eX={top:8,right:8,bottom:8,left:8},tX=[`#f97316`,`#38bdf8`,`#4ade80`,`#a78bfa`,`#fbbf24`,`#fb7185`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function nX(e){let t=new Map;for(let n of e){let e=n.parent??``;t.has(e)||t.set(e,[]),t.get(e).push(n)}function n(r,i){let a=(t.get(r)??[]).map(e=>n(e.name,i+1)),o=e.find(e=>e.name===r),s=a.reduce((e,t)=>e+t.value,0);return{name:r,value:o?Math.max(o.value,s):s,children:a,depth:i}}let r=new Set(e.map(e=>e.name));return e.filter(e=>!e.parent||!r.has(e.parent)).map(e=>n(e.name,0))}function rX(e,t,n,r,i,a){if(e.length===0||r<=0||i<=0||e.reduce((e,t)=>e+t.value,0)===0)return[];let o=[],s=[...e].sort((e,t)=>t.value-e.value),c=t,l=n,u=r,d=i;for(;s.length>0;){let e=u*d,t=s.reduce((e,t)=>e+t.value,0),n=e/t,r=[],i=1/0;for(let e=1;e<=s.length;e++){let a=s.slice(0,e),o=a.reduce((e,t)=>e+t.value,0)/t*(u<=d?u:d),c=0;for(let e of a){let t=e.value*n/o,r=Math.max(t/o,o/t);r>c&&(c=r)}if(c<i)i=c,r=a;else break}let f=r.reduce((e,t)=>e+t.value,0),p=u<=d,m=f/t*(p?u:d),h=0;for(let e of r){let t=e.value/f,n=p?u:t*u,r=p?t*d:d,i=p?c:c+h,s=p?l+h:l,g=p?m:n,_=p?r:m;if(o.push({node:e,x:i,y:s,w:g,h:_,depth:a}),e.children.length>0&&g>4&&_>4){let t=rX(e.children,i+1,s+1,g-2,_-2,a+1);for(let e of t)o.push(e)}h+=p?r:n}s=s.slice(r.length),p?(c+=m,u-=m):(l+=m,d-=m)}return o}function iX({nodes:e,backgroundToken:t=``,onPlotContextMenu:n}){let r=K(null),i=K(null),a=K(null),o=K(null),s=K([]),c=K(null),l=K(0),u=K(n);G(()=>{u.current=n},[n]);let d=K({nodes:e});G(()=>{d.current={nodes:e}},[e]);let f=St(()=>nX(e),[e]),p=K(f);G(()=>{p.current=f},[f]);function m(){if(o.current)return o.current;let e=a.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return o.current=n,n}function h(){let e=a.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function g(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function _(){let e=r.current;if(!e)return;let{w:t,h:n}=h(),i=g(e,t,n);if(!i)return;let{bg:a,muted:o}=m(),{nodes:l}=d.current;if(i.fillStyle=a,i.fillRect(0,0,t,n),l.length===0){i.fillStyle=o,i.font=`13px ${Q.sans}`,i.textAlign=`left`,i.textBaseline=`top`,UV(i);return}let u=p.current,f=t-eX.left-eX.right,_=n-eX.top-eX.bottom,v=rX(u,eX.left,eX.top,f,_,0);s.current=v;for(let e=0;e<v.length;e++){let{node:t,x:n,y:r,w:o,h:s,depth:l}=v[e];if(o<2||s<2)continue;let u=tX[l%tX.length],d=c.current===e;if(i.fillStyle=u,i.globalAlpha=d?.95:.75,i.fillRect(n,r,o,s),i.globalAlpha=1,i.strokeStyle=a,i.lineWidth=1,i.strokeRect(n,r,o,s),o>20&&s>14){i.fillStyle=`rgba(0,0,0,0.75)`,i.font=`${Math.min(11,s-4)}px ${Q.mono}`,i.textAlign=`left`,i.textBaseline=`top`;let e=Math.floor((o-4)/6),a=t.name.length>e?t.name.slice(0,e-1)+`…`:t.name;i.fillText(a,n+3,r+3)}}i.globalAlpha=1}function v(){let e=i.current;if(!e)return;let{w:t,h:n}=h(),r=g(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let a=c.current;if(a===null)return;let o=s.current;if(a<0||a>=o.length)return;let{node:l,x:u,y:d,w:f,h:p}=o[a];r.strokeStyle=`rgba(255,255,255,0.9)`,r.lineWidth=2,r.strokeRect(u+1,d+1,f-2,p-2);let m=`${l.name}: ${l.value.toLocaleString()}`;r.font=`11px ${Q.mono}`;let _=r.measureText(m).width,v=Math.max(4,Math.min(t-_-8,u+f/2-_/2)),y=d<30?d+p+4:d-20;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(v-3,y-3,_+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(m,v,y)}let y=K(_);y.current=_;let b=K(null);b.current??=KH(()=>y.current(),()=>a.current);let x=()=>b.current.schedule(),S=()=>{zH(l.current),l.current=RH(v)};return W(()=>{b.current.now()}),W(()=>()=>b.current?.cancel(),[]),W(()=>{o.current=null,x()},[t]),G(()=>{let e=a.current;if(!e)return;let t=new WH(()=>{o.current=null,x(),S()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=i.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,a=s.current,o=null;for(let e=0;e<a.length;e++){let t=a[e];r>=t.x&&r<=t.x+t.w&&i>=t.y&&i<=t.y+t.h&&(o=e)}c.current=o,S()},r=()=>{c.current=null,S()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:a,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:r,className:`chart-canvas`,role:`img`,"aria-label":`Treemap`}),q(`canvas`,{ref:i,className:`chart-canvas chart-overlay`})]})}var aX={top:8,right:8,bottom:8,left:8},oX=14,sX=8,cX=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function lX(e,t,n,r){if(e.length===0||t.length===0)return{nodes:[],links:[]};let i=n-aX.left-aX.right,a=r-aX.top-aX.bottom,o=new Map;for(let t of e)o.set(t,0);let s=!0;for(;s;){s=!1;for(let e of t){let t=o.get(e.source)??0;(o.get(e.target)??0)<=t&&(o.set(e.target,t+1),s=!0)}}let c=Math.max(0,...Array.from(o.values())),l=e=>aX.left+e/Math.max(1,c)*(i-oX),u=new Map;for(let[e,t]of o)u.has(t)||u.set(t,[]),u.get(t).push(e);let d=new Map;for(let t of e)d.set(t,0);for(let e of t)d.set(e.source,(d.get(e.source)??0)+e.value),d.set(e.target,(d.get(e.target)??0)+e.value);let f=Math.max(1,...Array.from(d.values())),p=new Map;for(let[t,n]of u){let r=a-(n.length-1)*sX,i=0;for(let e of n)i+=Math.max(8,(d.get(e)??0)/f*r*.8);let o=aX.top+(a-i-(n.length-1)*sX)/2;for(let i=0;i<n.length;i++){let a=n[i],s=Math.max(8,(d.get(a)??0)/f*r*.8);p.set(a,{name:a,x:l(t),y:o,h:s,color:cX[e.indexOf(a)%cX.length]}),o+=s+sX}}let m=new Map,h=new Map;for(let[e,t]of p)m.set(e,t.y),h.set(e,t.y);let g=[];for(let e of t){let t=p.get(e.source),n=p.get(e.target);if(!t||!n)continue;let r=Math.max(1,e.value/f*t.h),i=m.get(e.source)??t.y,a=h.get(e.target)??n.y;m.set(e.source,i+r),h.set(e.target,a+r),g.push({sx:t.x+oX,sy:i+r/2,tx:n.x,ty:a+r/2,h:r,color:t.color,label:`${e.source} → ${e.target}: ${e.value.toLocaleString()}`})}return{nodes:Array.from(p.values()),links:g}}function uX({nodeNames:e,links:t,backgroundToken:n=``,onPlotContextMenu:r}){let i=K(null),a=K(null),o=K(null),s=K(null),c=K({nodes:[],links:[]}),l=K(null),u=K(0),d=K(r);G(()=>{d.current=r},[r]);let f=K({nodeNames:e,links:t});G(()=>{f.current={nodeNames:e,links:t}},[e,t]);function p(){if(s.current)return s.current;let e=o.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return s.current=n,n}function m(){let e=o.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function h(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function g(){let e=i.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;let{bg:a,muted:o}=p(),{nodeNames:s,links:u}=f.current;if(r.fillStyle=a,r.fillRect(0,0,t,n),s.length===0||u.length===0){r.fillStyle=o,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let d=lX(s,u,t,n);c.current=d;for(let e=0;e<d.links.length;e++){let t=d.links[e],n=l.current===e,i=(t.tx-t.sx)/2;r.beginPath(),r.moveTo(t.sx,t.sy-t.h/2),r.bezierCurveTo(t.sx+i,t.sy-t.h/2,t.tx-i,t.ty-t.h/2,t.tx,t.ty-t.h/2),r.lineTo(t.tx,t.ty+t.h/2),r.bezierCurveTo(t.tx-i,t.ty+t.h/2,t.sx+i,t.sy+t.h/2,t.sx,t.sy+t.h/2),r.closePath(),r.fillStyle=t.color,r.globalAlpha=n?.55:.3,r.fill()}r.globalAlpha=1;for(let e of d.nodes)r.fillStyle=e.color,r.globalAlpha=.9,r.fillRect(e.x,e.y,oX,e.h),r.globalAlpha=1,r.fillStyle=o,r.font=`9px ${Q.mono}`,r.textBaseline=`middle`,e.x>t/2?(r.textAlign=`right`,r.fillText(e.name,e.x-3,e.y+e.h/2)):(r.textAlign=`left`,r.fillText(e.name,e.x+oX+3,e.y+e.h/2));r.globalAlpha=1}function _(){let e=a.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=l.current;if(i===null)return;let o=c.current;if(i<0||i>=o.links.length)return;let s=o.links[i],u=s.label;r.font=`11px ${Q.mono}`;let d=r.measureText(u).width,f=Math.max(4,Math.min(t-d-8,(s.sx+s.tx)/2-d/2)),p=Math.max(4,(s.sy+s.ty)/2-10);r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(f-3,p-3,d+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(u,f,p)}let v=K(g);v.current=g;let y=K(null);y.current??=KH(()=>v.current(),()=>o.current);let b=()=>y.current.schedule(),x=()=>{zH(u.current),u.current=RH(_)};return W(()=>{y.current.now()}),W(()=>()=>y.current?.cancel(),[]),W(()=>{s.current=null,b()},[n]),G(()=>{let e=o.current;if(!e)return;let t=new WH(()=>{s.current=null,b(),x()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=a.current;if(!e)return;let t=e=>{e.preventDefault(),d.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,a=c.current,o=null;for(let e=0;e<a.links.length;e++){let t=a.links[e];if(r>=t.sx&&r<=t.tx&&Math.abs(i-(t.sy+t.ty)/2)<t.h/2+6){o=e;break}}l.current=o,x()},r=()=>{l.current=null,x()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:o,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:i,className:`chart-canvas`,role:`img`,"aria-label":`Sankey diagram`}),q(`canvas`,{ref:a,className:`chart-canvas chart-overlay`})]})}var dX={top:24,right:24,bottom:52,left:52};function fX({bins:e,color:t=`#38bdf8`,backgroundToken:n=``,onPlotContextMenu:r}){let i=K(null),a=K(null),o=K(null),s=K(null),c=K(null),l=K(0),u=K(r);G(()=>{u.current=r},[r]);let d=K({bins:e,color:t});G(()=>{d.current={bins:e,color:t}},[e,t]);function f(){if(s.current)return s.current;let e=o.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return s.current=n,n}function p(){let e=o.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function m(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function h(){let e=i.current;if(!e)return;let{w:t,h:n}=p(),r=m(e,t,n);if(!r)return;let{bg:a,muted:o,grid:s}=f(),{bins:l,color:u}=d.current;if(r.fillStyle=a,r.fillRect(0,0,t,n),l.length===0){r.fillStyle=o,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{top:h,right:g,bottom:_,left:v}=dX,y=t-v-g,b=n-h-_,x=e=>v+e*y,S=e=>h+(1-e)*b;for(let e=0;e<=5;e++){let t=e/5;r.strokeStyle=s,r.lineWidth=1,r.beginPath(),r.moveTo(v,S(t)),r.lineTo(v+y,S(t)),r.stroke(),r.beginPath(),r.moveTo(x(t),h),r.lineTo(x(t),h+b),r.stroke(),r.fillStyle=o,r.font=`9px ${Q.mono}`,r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(t.toFixed(2),v-4,S(t)),r.textAlign=`center`,r.textBaseline=`top`,r.fillText(t.toFixed(2),x(t),h+b+4)}r.strokeStyle=o,r.lineWidth=1.5,r.setLineDash([6,4]),r.beginPath(),r.moveTo(x(0),S(0)),r.lineTo(x(1),S(1)),r.stroke(),r.setLineDash([]);let C=Math.max(1,...l.map(e=>e.count)),w=b*.15;for(let e of l){let t=Math.max(1,y/l.length*.7),n=x(e.center)-t/2,i=e.count/C*w;r.fillStyle=u,r.globalAlpha=.3,r.fillRect(n,h+b-i,t,i)}r.globalAlpha=1,r.beginPath();for(let e=0;e<l.length;e++){let t=x(l[e].center),n=S(l[e].actual);e===0?r.moveTo(t,n):r.lineTo(t,n)}r.strokeStyle=u,r.lineWidth=1,r.stroke();for(let e=0;e<l.length;e++){let t=c.current===e;r.beginPath(),r.arc(x(l[e].center),S(l[e].actual),t?6:4,0,Math.PI*2),r.fillStyle=u,r.globalAlpha=t?1:.85,r.fill()}r.globalAlpha=1,r.fillStyle=o,r.font=`10px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(`Predicted probability`,v+y/2,n-4),r.save(),r.translate(12,h+b/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(`Actual rate`,0,0),r.restore()}function g(){let e=a.current;if(!e)return;let{w:t,h:n}=p(),r=m(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=c.current;if(i===null)return;let{bins:o}=d.current;if(i<0||i>=o.length)return;let s=o[i],{top:l,left:u}=dX,f=t-u-dX.right,h=n-l-dX.bottom,g=u+s.center*f,_=l+(1-s.actual)*h,v=`pred=${s.center.toFixed(2)} actual=${s.actual.toFixed(3)} n=${s.count}`;r.font=`11px ${Q.mono}`;let y=r.measureText(v).width,b=Math.max(4,Math.min(t-y-8,g-y/2)),x=_-28<l?_+12:_-24;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(b-3,x-3,y+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(v,b,x)}let _=K(h);_.current=h;let v=K(null);v.current??=KH(()=>_.current(),()=>o.current);let y=()=>v.current.schedule(),b=()=>{zH(l.current),l.current=RH(g)};return W(()=>{v.current.now()}),W(()=>()=>v.current?.cancel(),[]),W(()=>{s.current=null,y()},[n]),G(()=>{let e=o.current;if(!e)return;let t=new WH(()=>{s.current=null,y(),b()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=a.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{bins:r}=d.current,{w:i}=p(),a=t.clientX-n.left,o=i-dX.left-dX.right,s=-1,l=20;for(let e=0;e<r.length;e++){let t=dX.left+r[e].center*o,n=Math.abs(a-t);n<l&&(l=n,s=e)}c.current=s>=0?s:null,b()},r=()=>{c.current=null,b()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:o,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:i,className:`chart-canvas`,role:`img`,"aria-label":`Calibration curve`}),q(`canvas`,{ref:a,className:`chart-canvas chart-overlay`})]})}var pX={top:24,right:24,bottom:48,left:52};function mX({points:e,color:t=`#a78bfa`,backgroundToken:n=``,onPlotContextMenu:r}){let i=IU(),a=K(null),o=K(null),s=K(null),c=K(null),l=K(null),u=K(0),d=K(r);G(()=>{d.current=r},[r]);let f=K({points:e,color:t});G(()=>{f.current={points:e,color:t}},[e,t]);function p(){if(c.current)return c.current;let e=s.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return c.current=n,n}function m(){let e=s.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function h(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function g(){let{points:e}=f.current,t=1/0,n=-1/0,r=1/0,i=-1/0;if(e.length>0&&(t=e.theoretical[0],n=e.theoretical[e.length-1],r=e.sample[0],i=e.sample[e.length-1]),!Number.isFinite(t))return{xLo:-3,xHi:3,yLo:-3,yHi:3};let a=(n-t)*.05||.5,o=(i-r)*.05||.5;return{xLo:t-a,xHi:n+a,yLo:r-o,yHi:i+o}}function _(){let e=a.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;let{bg:o,muted:s,grid:c}=p(),{points:u,color:d}=f.current;if(r.fillStyle=o,r.fillRect(0,0,t,n),u.length===0){r.fillStyle=s,r.font=`13px ${Q.sans}`,r.textAlign=`left`,r.textBaseline=`top`,UV(r);return}let{xLo:_,xHi:v,yLo:y,yHi:b}=g(),{top:x,right:S,bottom:C,left:w}=pX,T=t-w-S,E=n-x-C,D=e=>w+(e-_)/(v-_)*T,O=e=>x+(1-(e-y)/(b-y))*E;i({left:w,top:x,width:T,height:E,x:{v0:_,v1:v}}),r.strokeStyle=c,r.lineWidth=1;for(let e=0;e<=5;e++){let t=_+e/5*(v-_),n=D(t);r.beginPath(),r.moveTo(n,x),r.lineTo(n,x+E),r.stroke(),r.fillStyle=s,r.font=`9px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`top`,r.fillText(Vz(t,(v-_)/5),n,x+E+4);let i=y+e/5*(b-y),a=O(i);r.beginPath(),r.moveTo(w,a),r.lineTo(w+T,a),r.stroke(),r.fillStyle=s,r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(Vz(i,(b-y)/5),w-4,a)}let k=Math.max(_,y),A=Math.min(v,b);k<A&&(r.strokeStyle=s,r.lineWidth=1.5,r.setLineDash([6,4]),r.beginPath(),r.moveTo(D(k),O(k)),r.lineTo(D(A),O(A)),r.stroke(),r.setLineDash([])),r.fillStyle=d,r.globalAlpha=.75;let j=NaN,M=NaN;for(let e=0;e<u.length;e++){let t=Math.round(D(u.theoretical[e])),n=Math.round(O(u.sample[e]));t===j&&n===M||(j=t,M=n,r.beginPath(),r.arc(t,n,3,0,Math.PI*2),r.fill())}let N=l.current;N!==null&&N<u.length&&(r.globalAlpha=1,r.beginPath(),r.arc(D(u.theoretical[N]),O(u.sample[N]),5,0,Math.PI*2),r.fill()),r.globalAlpha=1,r.fillStyle=s,r.font=`10px ${Q.mono}`,r.textAlign=`center`,r.textBaseline=`bottom`,r.fillText(`Theoretical quantiles`,w+T/2,n-4),r.save(),r.translate(12,x+E/2),r.rotate(-Math.PI/2),r.textAlign=`center`,r.textBaseline=`middle`,r.fillText(`Sample quantiles`,0,0),r.restore()}function v(){let e=o.current;if(!e)return;let{w:t,h:n}=m(),r=h(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=l.current;if(i===null)return;let{points:a}=f.current;if(i<0||i>=a.length)return;let s={theoretical:a.theoretical[i],sample:a.sample[i]},{xLo:c,xHi:u,yLo:d,yHi:p}=g(),{top:_,left:v}=pX,y=t-v-pX.right,b=n-_-pX.bottom,x=v+(s.theoretical-c)/(u-c)*y,S=_+(1-(s.sample-d)/(p-d))*b;r.beginPath(),r.arc(x,S,6,0,Math.PI*2),r.strokeStyle=`rgba(255,255,255,0.9)`,r.lineWidth=2,r.stroke();let C=`(${Hz(s.theoretical)}, ${Hz(s.sample)})`;r.font=`11px ${Q.mono}`;let w=r.measureText(C).width,T=Math.max(4,Math.min(t-w-8,x+10)),E=S-20<_?S+10:S-20;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(T-3,E-3,w+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(C,T,E)}let y=K(_);y.current=_;let b=K(null);b.current??=KH(()=>y.current(),()=>s.current);let x=()=>b.current.schedule(),S=()=>{zH(u.current),u.current=RH(v)};return W(()=>{b.current.now()}),W(()=>()=>b.current?.cancel(),[]),W(()=>{c.current=null,x()},[n]),G(()=>{let e=s.current;if(!e)return;let t=new WH(()=>{c.current=null,x(),S()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=o.current;if(!e)return;let t=e=>{e.preventDefault(),d.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{points:r}=f.current,{w:i}=m(),{xLo:a,xHi:o,yLo:s,yHi:c}=g(),{top:u,left:d}=pX,p=i-d-pX.right,h=n.height-u-pX.bottom,_=t.clientX-n.left,v=t.clientY-n.top,y=e=>a+(e-d)/p*(o-a),b=e=>{let t=0,n=r.length;for(;t<n;){let i=t+n>>>1;r.theoretical[i]<e?t=i+1:n=i}return t},x=b(y(_-10)),C=Math.min(r.length,b(y(_+10))+1),w=-1,T=10**2;for(let e=x;e<C;e++){let t=d+(r.theoretical[e]-a)/(o-a)*p,n=u+(1-(r.sample[e]-s)/(c-s))*h,i=(_-t)**2+(v-n)**2;i<T&&(T=i,w=e)}l.current=w>=0?w:null,S()},r=()=>{l.current=null,S()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:s,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:a,className:`chart-canvas`,role:`img`,"aria-label":`Q-Q plot`}),q(`canvas`,{ref:o,className:`chart-canvas chart-overlay`})]})}var hX={top:8,right:16,bottom:40,left:120},gX=22,_X=3,vX=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function yX({tasks:e,backgroundToken:t=``,onPlotContextMenu:n}){let r=IU(),i=K(null),a=K(null),o=K(null),s=K(null),c=K(null),l=K(0),u=K(n);G(()=>{u.current=n},[n]);let d=K({tasks:e});G(()=>{d.current={tasks:e}},[e]);function f(){if(s.current)return s.current;let e=o.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`};return s.current=n,n}function p(){let e=o.current;return{w:Math.max(1,e?.clientWidth||200),h:Math.max(1,e?.clientHeight||300)}}function m(e,t,n){let r=Math.min(2,window.devicePixelRatio||1),i=Math.floor(t*r),a=Math.floor(n*r);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),e.style.width=`${t}px`,e.style.height=`${n}px`;let o=e.getContext(`2d`);return o&&o.setTransform(r,0,0,r,0,0),o}function h(){let e=i.current;if(!e)return;let{w:t,h:n}=p(),a=m(e,t,n);if(!a)return;let{bg:o,muted:s,grid:l}=f(),{tasks:u}=d.current;if(a.fillStyle=o,a.fillRect(0,0,t,n),u.length===0){a.fillStyle=s,a.font=`13px ${Q.sans}`,a.textAlign=`left`,a.textBaseline=`top`,UV(a);return}let h=1/0,g=-1/0;for(let e of u)e.start<h&&(h=e.start),e.end>g&&(g=e.end);Number.isFinite(h)||(h=0,g=1);let _=(g-h)*.02||1;h-=_,g+=_;let{top:v,right:y,bottom:b,left:x}=hX,S=t-x-y,C=e=>x+(e-h)/(g-h)*S;r({left:x,top:v,width:S,height:n-v-b,x:{v0:h,v1:g}});let w=new Map;for(let e of u){let t=e.group??e.label;w.has(t)||w.set(t,w.size)}let T=Math.min(8,Math.floor(S/60));a.strokeStyle=l,a.lineWidth=1;for(let e=0;e<=T;e++){let t=h+e/T*(g-h),n=C(t),r=u.length*(gX+_X)+v;a.beginPath(),a.moveTo(n,v),a.lineTo(n,r),a.stroke(),a.fillStyle=s,a.font=`9px ${Q.mono}`,a.textAlign=`center`,a.textBaseline=`top`,a.fillText(Vz(t,(g-h)/T),n,r+4)}for(let e=0;e<u.length;e++){let t=u[e],n=v+e*(gX+_X),r=vX[(w.get(t.group??t.label)??0)%vX.length],i=c.current===e,o=C(t.start),l=C(t.end),d=Math.max(2,l-o);a.fillStyle=r,a.globalAlpha=i?.95:.75,a.fillRect(o,n,d,gX-_X),a.globalAlpha=1,a.fillStyle=s,a.font=`9px ${Q.mono}`,a.textAlign=`right`,a.textBaseline=`middle`;let f=t.label.length>16?t.label.slice(0,15)+`…`:t.label;a.fillText(f,x-4,n+(gX-_X)/2)}a.globalAlpha=1}function g(){let e=a.current;if(!e)return;let{w:t,h:n}=p(),r=m(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let i=c.current;if(i===null)return;let{tasks:o}=d.current;if(i<0||i>=o.length)return;let s=o[i],l=s.end-s.start,u=`${s.label}: ${Hz(s.start)} → ${Hz(s.end)} (${Hz(l)})`;r.font=`11px ${Q.mono}`;let f=r.measureText(u).width,h=1/0,g=-1/0;for(let e of o)e.start<h&&(h=e.start),e.end>g&&(g=e.end);let _=(g-h)*.02||1;h-=_,g+=_;let v=t-hX.left-hX.right,y=e=>hX.left+(e-h)/(g-h)*v,b=hX.top+i*(gX+_X),x=(y(s.start)+y(s.end))/2,S=Math.max(4,Math.min(t-f-8,x-f/2)),C=b-22<hX.top?b+gX+4:b-20;r.fillStyle=`rgba(0,0,0,0.8)`,r.fillRect(S-3,C-3,f+6,18),r.fillStyle=`#fff`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(u,S,C)}let _=K(h);_.current=h;let v=K(null);v.current??=KH(()=>_.current(),()=>o.current);let y=()=>v.current.schedule(),b=()=>{zH(l.current),l.current=RH(g)};return W(()=>{v.current.now()}),W(()=>()=>v.current?.cancel(),[]),W(()=>{s.current=null,y()},[t]),G(()=>{let e=o.current;if(!e)return;let t=new WH(()=>{s.current=null,y(),b()});return t.observe(e),()=>t.disconnect()}),G(()=>{let e=a.current;if(!e)return;let t=e=>{e.preventDefault(),u.current?.({clientX:e.clientX,clientY:e.clientY})},n=t=>{let n=e.getBoundingClientRect(),{tasks:r}=d.current,i=t.clientY-n.top,a=Math.floor((i-hX.top)/(gX+_X));c.current=a>=0&&a<r.length?a:null,b()},r=()=>{c.current=null,b()};return e.addEventListener(`contextmenu`,t),e.addEventListener(`mousemove`,n),e.addEventListener(`mouseleave`,r),()=>{e.removeEventListener(`contextmenu`,t),e.removeEventListener(`mousemove`,n),e.removeEventListener(`mouseleave`,r)}},[]),Ot(`div`,{ref:o,style:{position:`relative`,width:`100%`,height:`100%`},children:[q(`canvas`,{ref:i,className:`chart-canvas`,role:`img`,"aria-label":`Gantt chart`}),q(`canvas`,{ref:a,className:`chart-canvas chart-overlay`})]})}var bX=e=>[...e].filter(e=>Number.isFinite(e.at)).sort((e,t)=>e.at-t.at),xX=e=>{let t=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i.exec(e);return t?[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]:[128,128,128]},SX=e=>`#${e.map(e=>Math.round(e).toString(16).padStart(2,`0`)).join(``)}`;function CX(e,t,n,r){let i=t?bX(t):[];if(!e||e===`solid`||i.length===0||!Number.isFinite(r))return n;if(e===`zones`){let e=i[0].color;for(let t of i)r>=t.at&&(e=t.color);return e}if(r<=i[0].at)return i[0].color;if(r>=i[i.length-1].at)return i[i.length-1].color;let a=0;for(;i[a+1].at<r;)a++;let o=i[a],s=i[a+1],c=(r-o.at)/(s.at-o.at||1),l=xX(o.color),u=xX(s.color);return SX([l[0]+(u[0]-l[0])*c,l[1]+(u[1]-l[1])*c,l[2]+(u[2]-l[2])*c])}function wX(e,t,n,r,i,a=96){let o=i-r||1,s=t?bX(t):[];if(!e||e===`solid`||s.length===0)return[{f0:0,f1:1,color:n}];if(e===`zones`){let e=[0,...s.slice(1).map(e=>(e.at-r)/o).filter(e=>e>0&&e<1),1];return e.slice(0,-1).map((t,i)=>({f0:t,f1:e[i+1],color:CX(`zones`,s,n,r+(t+e[i+1])/2*o)}))}return Array.from({length:a},(e,t)=>({f0:t/a,f1:(t+1)/a,color:CX(`gradient`,s,n,r+(t+.5)/a*o)}))}function TX(e,t,n){let r=e=>+(t+e*(n-t)).toPrecision(6),i=`#22c55e`,a=`#ef4444`;if(e===`traffic`)return{mode:`zones`,stops:[{at:r(0),color:i},{at:r(.7),color:`#f5a524`},{at:r(.9),color:a}]};let o=[{at:r(0),color:i},{at:r(.5),color:`#eab308`},{at:r(1),color:a}];return{mode:`gradient`,stops:e===`green-red`?o:o.map((e,t)=>({...e,color:o[o.length-1-t].color}))}}function EX(e,t,n){let r=t?bX(t):[];if(!e||e===`solid`||r.length===0)return n;let i=r[0].at,a=r[r.length-1].at,o=e=>`${((e-i)/(a-i||1)*100).toFixed(1)}%`;if(e===`gradient`)return`linear-gradient(90deg, ${r.map(e=>`${e.color} ${o(e.at)}`).join(`, `)})`;let s=100/r.length;return`linear-gradient(90deg, ${r.map((e,t)=>`${e.color} ${(t*s).toFixed(1)}% ${((t+1)*s).toFixed(1)}%`).join(`, `)})`}var DX=.75*Math.PI,OX=1.5*Math.PI;function kX({gauges:e,live:t,backgroundToken:n=``,onPlotContextMenu:r}){let i=K(null),a=K(null),o=K(null),s=K(r);G(()=>{s.current=r},[r]);let c=K({gauges:e,live:t});G(()=>{c.current={gauges:e,live:t}},[e,t]);let l=K(uU()),u=K(0);function d(){if(o.current)return o.current;let e=a.current;if(!e)return{bg:`#0f1014`,muted:`#71717a`,grid:`#27272a`,ink:`#e4e4e7`};let t=getComputedStyle(e),n={bg:t.getPropertyValue(`--chart-bg`).trim()||`#0f1014`,muted:t.getPropertyValue(`--chart-muted`).trim()||`#71717a`,grid:t.getPropertyValue(`--chart-grid`).trim()||`#27272a`,ink:t.getPropertyValue(`--chart-fg`).trim()||`#e4e4e7`};return o.current=n,n}function f(){let e=i.current,t=a.current;if(!e||!t)return;let n=Math.max(1,t.clientWidth),r=Math.max(1,t.clientHeight),o=Math.min(2,window.devicePixelRatio||1),s=Math.floor(n*o),f=Math.floor(r*o);(e.width!==s||e.height!==f)&&(e.width=s,e.height=f),e.style.width=`${n}px`,e.style.height=`${r}px`;let p=e.getContext(`2d`);if(!p)return;p.setTransform(o,0,0,o,0,0);let h=d(),{gauges:g,live:_}=c.current,v=g;if(_){let e=performance.now(),t=EU(l.current,_.latestT(),e-u.current,_.timeAfter);u.current=e,v=g.map(e=>{if((e.stat??`last`)!==`last`)return e;let n=_.valueAt(e.name,t);return Number.isFinite(n)?{...e,value:n}:e}),m.current.schedule()}if(p.fillStyle=h.bg,p.fillRect(0,0,n,r),v.length===0){p.fillStyle=h.muted,p.font=`13px ${Q.sans}`,p.textAlign=`left`,p.textBaseline=`top`,UV(p);return}let{cols:y,rows:b}=AX(v.length,n,r,v.some(e=>e.style===`arc`)?1.15:3.2),x=n/y,S=r/b;v.forEach((e,t)=>{let n=t%y*x,r=Math.floor(t/y)*S;e.style===`arc`?BX(p,e,n,r,x,S,e.color,e.alarm??null,h):VX(p,e,n,r,x,S,e.color,e.alarm??null,h)})}let p=K(f);p.current=f;let m=K(null);return m.current??=KH(()=>p.current(),()=>a.current),W(()=>{m.current.now()}),W(()=>()=>m.current?.cancel(),[]),W(()=>{o.current=null,m.current.schedule()},[n]),G(()=>{let e=a.current;if(!e)return;let t=new WH(()=>{o.current=null,m.current.schedule()});return t.observe(e),()=>t.disconnect()},[]),q(`div`,{ref:a,style:{position:`relative`,width:`100%`,height:`100%`},children:q(`canvas`,{ref:i,className:`chart-canvas`,role:`img`,"aria-label":`Gauges: ${e.map(e=>`${e.name} ${Number.isFinite(e.value)?jX(e.value,e.max-e.min):`no value`}${e.unit?` ${e.unit}`:``}`).join(`, `)}`,onContextMenu:e=>{e.preventDefault(),s.current?.({clientX:e.clientX,clientY:e.clientY})}})})}function AX(e,t,n,r){let i={cols:1,rows:e,size:-1};for(let a=1;a<=e;a++){let o=Math.ceil(e/a),s=t/a,c=n/o,l=Math.min(s,c*r);l>i.size&&(i={cols:a,rows:o,size:l})}return{cols:i.cols,rows:i.rows}}var jX=(e,t)=>Vz(e,Pz(Math.abs(t),100)),MX=(e,t)=>Math.max(0,Math.min(1,(t-e.min)/(e.max-e.min||1))),NX=(e,t)=>{let n=e.fromZero?MX(e,0):0;return[Math.min(n,t),Math.max(n,t)]},PX=(e,t)=>!!t&&(t.linked?t.linked===`active`:Number.isFinite(e.value)&&e.value>=t.value),FX=e=>(e.colorMode===`gradient`||e.colorMode===`zones`)&&!!e.stops?.length,IX=(e,t)=>PX(e,t)?t.color:CX(e.colorMode,e.stops,e.color,e.value);function LX(e,t,n){for(let r of wX(t.colorMode,t.stops,t.color,t.min,t.max))e.addColorStop(n(r.f0),r.color),e.addColorStop(n(r.f1),r.color);return e}function RX(e,t,n){if(e.measureText(t).width<=n)return t;let r=t;for(;r.length>1&&e.measureText(`${r}…`).width>n;)r=r.slice(0,-1);return n>0?`${r}…`:``}var zX=Math.SQRT1_2;function BX(e,t,n,r,i,a,o,s,c){let l=Math.max(6,Math.min(i,a)*.06),u=t.max-t.min,d=jX(t.min,u),f=jX(t.max,u),p=e=>Math.max(9,Math.min(22,e*.1)),m=e=>Math.max(4,e*.13),h=Math.max(8,Math.min((i-2*l)/2,(a-2*l)/1.9)),g=0;for(let t=0;t<2;t++){e.font=`${p(h)}px ${Q.mono}`,g=Math.max(e.measureText(d).width,e.measureText(f).width);let t=m(h),n=Math.max(h+t/2,zX*h+g/2),r=h+t/2+zX*h+t/2+6+p(h)*1.2;h=Math.max(8,Math.min(h*(i-2*l)/(2*n),h*(a-2*l)/r))}let _=m(h),v=p(h),y=h+_/2+zX*h+_/2+6+v*1.2,b=n+i/2,x=r+l+h+_/2+Math.max(0,(a-2*l-y)/2),S=e=>DX+e*OX;e.lineCap=`round`,e.lineWidth=_,e.strokeStyle=c.grid,e.beginPath(),e.arc(b,x,h,DX,DX+OX),e.stroke(),s&&s.value<t.max&&(e.globalAlpha=.3,e.strokeStyle=s.color,e.lineCap=`butt`,e.beginPath(),e.arc(b,x,h,S(MX(t,s.value)),DX+OX),e.stroke(),e.globalAlpha=1,e.lineCap=`round`);let[C,w]=NX(t,Number.isFinite(t.value)?MX(t,t.value):0),T=()=>{e.lineCap=t.fromZero?`butt`:`round`,e.beginPath(),e.arc(b,x,h,S(C),Math.max(S(C)+1e-4,S(w))),e.stroke(),e.lineCap=`round`};if(FX(t)){let n=OX/(2*Math.PI),r=LX(e.createConicGradient(DX,b,x),t,e=>e*n);r.addColorStop(1,CX(t.colorMode,t.stops,t.color,t.min)),e.strokeStyle=r,e.globalAlpha=.24,e.beginPath(),e.arc(b,x,h,DX,DX+OX),e.stroke(),e.globalAlpha=1,Number.isFinite(t.value)&&!PX(t,s)&&T()}if(Number.isFinite(t.value)&&(!FX(t)||PX(t,s))&&(e.strokeStyle=PX(t,s)?s.color:o,T()),t.fromZero&&t.min<0&&t.max>0){let n=S(MX(t,0));e.strokeStyle=c.muted,e.lineWidth=1.5,e.lineCap=`butt`,e.beginPath(),e.moveTo(b+Math.cos(n)*(h-_*.75),x+Math.sin(n)*(h-_*.75)),e.lineTo(b+Math.cos(n)*(h+_*.75),x+Math.sin(n)*(h+_*.75)),e.stroke(),e.lineWidth=_,e.lineCap=`round`}if(s&&s.value>=t.min&&s.value<=t.max){let n=S(MX(t,s.value));e.strokeStyle=s.color,e.lineWidth=Math.max(1.5,s.width),e.lineCap=`butt`,e.beginPath(),e.moveTo(b+Math.cos(n)*(h-_*.9),x+Math.sin(n)*(h-_*.9)),e.lineTo(b+Math.cos(n)*(h+_*.9),x+Math.sin(n)*(h+_*.9)),e.stroke();let r=h+_*.9+10*.7;s.linked&&BU(e,b+Math.cos(n)*r-10/2,x+Math.sin(n)*r-10/2,s.color)}let E=Number.isFinite(t.value)?jX(t.value,u):`—`,D=2*(h-_)*.82,O=Math.max(11,h*.42);e.font=`650 ${O}px ${Q.sans}`;let k=e.measureText(E).width;k>D&&(O=Math.max(9,O*D/k),e.font=`650 ${O}px ${Q.sans}`),e.textAlign=`center`,e.textBaseline=`alphabetic`,e.fillStyle=PX(t,s)||FX(t)?IX(t,s):c.ink,e.fillText(E,b,x+O*.32),e.fillStyle=c.muted,t.unit&&(e.font=`600 ${Math.max(9,h*.13)}px ${Q.sans}`,e.fillText(RX(e,t.unit,D),b,x+O*.32+Math.max(11,h*.19)));let A=x+zX*h+_/2+6,j=zX*h;e.textBaseline=`top`,e.font=`${v}px ${Q.mono}`,e.fillText(d,b-j,A),e.fillText(f,b+j,A);let M=2*j-g-16,N=Math.max(10,Math.min(26,h*.13));e.font=`600 ${N}px ${Q.sans}`;let P=e.measureText(t.name).width;P>M&&N>9&&(N=Math.max(9,N*M/P),e.font=`600 ${N}px ${Q.sans}`),e.fillText(RX(e,t.name,M),b,A+(v-N)/2)}function VX(e,t,n,r,i,a,o,s,c){let l=Math.max(14,i*.06),u=n+l,d=n+i-l,f=d-u,p=Math.max(6,Math.min(16,a*.14)),m=Math.max(12,Math.min(34,a*.28)),h=r+a/2+m*.35,g=e=>u+MX(t,e)*f;e.textBaseline=`alphabetic`,e.fillStyle=c.muted,e.font=`600 ${Math.max(10,m*.42)}px ${Q.sans}`,e.textAlign=`left`,e.fillText(RX(e,t.name,f),u,h-p/2-m-4),e.textAlign=`right`,e.fillStyle=PX(t,s)?s.color:c.ink,e.font=`650 ${m}px ${Q.sans}`;let _=t.unit?(e.font=`600 ${Math.max(9,m*.4)}px ${Q.sans}`,e.measureText(` ${t.unit}`).width):0;t.unit&&(e.fillStyle=c.muted,e.fillText(` ${t.unit}`,d,h-p/2-8)),e.fillStyle=PX(t,s)||FX(t)?IX(t,s):c.ink,e.font=`650 ${m}px ${Q.sans}`,e.fillText(Number.isFinite(t.value)?jX(t.value,t.max-t.min):`—`,d-_,h-p/2-8),e.lineCap=`round`,e.lineWidth=p,e.strokeStyle=c.grid,e.beginPath(),e.moveTo(u,h),e.lineTo(d,h),e.stroke(),s&&s.value<t.max&&(e.globalAlpha=.3,e.strokeStyle=s.color,e.lineCap=`butt`,e.beginPath(),e.moveTo(g(s.value),h),e.lineTo(d,h),e.stroke(),e.globalAlpha=1,e.lineCap=`round`);let v=Number.isFinite(t.value)?MX(t,t.value):0,y=e=>u+e*f,[b,x]=NX(t,v),S=()=>{e.lineCap=t.fromZero?`butt`:`round`,e.beginPath(),e.moveTo(y(b),h),e.lineTo(Math.max(y(b)+.5,y(x)),h),e.stroke(),e.lineCap=`round`};FX(t)&&(e.strokeStyle=LX(e.createLinearGradient(u,0,d,0),t,e=>e),e.globalAlpha=.24,e.beginPath(),e.moveTo(u,h),e.lineTo(d,h),e.stroke(),e.globalAlpha=1,Number.isFinite(t.value)&&!PX(t,s)&&S()),Number.isFinite(t.value)&&(!FX(t)||PX(t,s))&&(e.strokeStyle=PX(t,s)?s.color:o,S()),t.fromZero&&t.min<0&&t.max>0&&(e.strokeStyle=c.muted,e.lineWidth=1.5,e.lineCap=`butt`,e.beginPath(),e.moveTo(g(0),h-p*.75),e.lineTo(g(0),h+p*.75),e.stroke(),e.lineWidth=p,e.lineCap=`round`),s&&s.value>=t.min&&s.value<=t.max&&(e.strokeStyle=s.color,e.lineWidth=Math.max(1.5,s.width),e.lineCap=`butt`,e.beginPath(),e.moveTo(g(s.value),h-p),e.lineTo(g(s.value),h+p),e.stroke(),s.linked&&BU(e,g(s.value)-10/2,h-p-10-2,s.color)),e.fillStyle=c.muted,e.font=`${Math.max(9,m*.34)}px ${Q.mono}`,e.textBaseline=`top`,e.textAlign=`left`,e.fillText(jX(t.min,t.max-t.min),u,h+p/2+4),e.textAlign=`right`,e.fillText(jX(t.max,t.max-t.min),d,h+p/2+4)}var HX=`Video limit reached this month`,UX=720;function WX(e,t){return t?e<UX:e<640}function GX(e){return e<=1?{cols:1,rows:1}:e===2?{cols:2,rows:1}:e<=4?{cols:2,rows:2}:{cols:3,rows:3}}function KX(e,t){return e.flatMap(e=>{let n=e.info?.meta;if(!n?.recordingId)return[];let r=n.wallOrigin?Number(n.wallOrigin):NaN,i=n.wallQuality;return[{recordingId:n.recordingId,wallOrigin:Number.isFinite(r)?r:null,wallQuality:i===`exact`||i===`approx`?i:null,xOffset:t[e.id]??0}]})}var qX={get:()=>null,subscribe:()=>()=>{}};function JX(e){let[t,n]=Ct(null);return G(()=>{let t=e.current;if(!t)return;let r=e=>n(t=>WX(e,t??!1));if(r(t.clientWidth),typeof ResizeObserver>`u`)return;let i=new ResizeObserver(e=>{for(let t of e)r(t.contentRect.width)});return i.observe(t),()=>i.disconnect()},[e]),t}function YX(e){let t=tr(e.settings),[n,r]=Ct(null),[i,a]=Ct(null),o=K(null);W(()=>{i&&o.current?.querySelector(`[data-camera="${CSS.escape(i)}"]`)?.focus()},[i]);let s=e.recordings??[],c=e=>s.findIndex(t=>t.recordingId===e.recordingId),l=(e.video??[]).filter(e=>e.kind===`recorded`&&c(e)>=0).sort((e,t)=>c(e)-c(t)),u=e.onContextMenu?t=>{t.preventDefault(),e.onContextMenu({clientX:t.clientX,clientY:t.clientY})}:void 0;if(!t.length){let t=[...new Set([...e.live.filter(e=>e.kind===`camera`&&!e.lowOf),...l].map(t=>Qn(t,e.live)))].sort();return q(ZX,{onContextMenu:u,title:`Choose a camera in this panel's settings`,detail:t.length?t.join(`, `):void 0})}let d={panel:e,recorded:l,recIndex:c};if(t.length===1)return q(XX,{...d,id:t[0],onMenu:u});let f=n&&t.includes(n)?n:null,p=f?[f]:t,{cols:m,rows:h}=GX(p.length),g=()=>{a(f),r(null)};return Ot(`div`,{ref:o,className:`kymo-camera-wall`,style:{gridTemplateColumns:`repeat(${m}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${h}, minmax(0, 1fr))`},onContextMenu:u,onKeyDown:e=>{e.key===`Escape`&&f&&(e.stopPropagation(),g())},children:[p.map(e=>q(XX,{...d,id:e,multi:!0,wall:!f,onPick:f?void 0:()=>{a(null),r(e)}},e)),f?Ot(`button`,{type:`button`,className:`kymo-camera__all`,onClick:g,autoFocus:!0,children:[Ot(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[q(`rect`,{x:`2`,y:`2`,width:`5`,height:`5`,rx:`1`}),q(`rect`,{x:`9`,y:`2`,width:`5`,height:`5`,rx:`1`}),q(`rect`,{x:`2`,y:`9`,width:`5`,height:`5`,rx:`1`}),q(`rect`,{x:`9`,y:`9`,width:`5`,height:`5`,rx:`1`})]}),`All cameras`]}):null]})}function XX({panel:e,recorded:t,recIndex:n,id:r,multi:i,wall:a,onPick:o,onMenu:s}){let c=e.recordings??[],l={onMenu:s,wall:a,onPick:o},u=t.find(e=>e.id===r);if(u)return q(QX,{...e,...l,source:u,name:i?Qn(u,e.live):u.name,rec:c[n(u)]},`rec:${u.recordingId}:${u.id}`);let d=e.live.find(e=>e.id===r&&e.kind===`camera`);if(d?.limitNotice&&(d.limitNotice===`Video limit reached this month`||!d.video))return q(ZX,{onContextMenu:s,title:d.limitNotice,detail:Qn(d,e.live)});if(!d?.video||d.status===`error`)return q(ZX,{onContextMenu:s,title:`Camera offline`,detail:d?Qn(d,e.live):void 0});let f=e.live.find(e=>e.kind===`camera`&&e.lowOf===d.id&&e.video&&e.status!==`error`),p=f?.video?BE({...f,video:f.video}):void 0;return q(QX,{...e,...l,source:BE({...d,video:d.video}),low:p,name:i?Qn(d,e.live):d.name,conn:d},d.id)}function ZX({title:e,detail:t,onContextMenu:n}){return q(`div`,{className:`kymo-camera`,onContextMenu:n,children:Ot(`div`,{className:`kymo-camera__empty`,children:[Ot(`svg`,{className:`kymo-camera__empty-icon`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[q(`rect`,{x:`2.5`,y:`6`,width:`13`,height:`12`,rx:`2.5`}),q(`path`,{d:`M15.5 10.5 21.5 7v10l-6-3.5`})]}),q(`p`,{className:`kymo-camera__empty-title`,children:e}),t?q(`p`,{className:`kymo-camera__empty-detail`,children:t}):null]})})}function QX(e){let{settings:t,source:n}=e,r=e.cursor??qX,i=wt(r.subscribe,r.get),a=e=>e.kind===`data`,o=e.rec?void 0:t.syncStreamId?e.live.find(e=>e.id===t.syncStreamId&&a(e)):e.live.find(t=>t.id===e.conn.parentId&&a(t))??e.live.find(t=>a(t)&&e.selection.includes(t.id))??e.live.find(a),s=i??e.viewXRange?.[1]??null,c=null,l=null,u=o?.clock?.quality()??`none`;if(e.rec){let{wallOrigin:r,wallQuality:i,xOffset:a}=e.rec;u=i??`none`;let o=n.range()?.[0]??null;s===null?c=o:r===null?(c=o,l=`This recording has no wall clock`):e.xKey===`Time`?c=r+s-a+t.offsetMs/1e3:e.xKey===`ElapsedTime`&&i===`exact`?c=s-a+t.offsetMs/1e3:(c=o,l=`Sync needs a time X axis`)}else s!==null&&(e.xIsTime?(c=o?.clock?.toWall(s,t.offsetMs)??null,c===null&&(l=`No data stream to sync with`)):l=`Sync needs a time X axis`);let d=K(null),f=K(null),p=JX(d),m=p===null?null:e.low&&(p||e.wall)?e.low:n,h=K(t.fit),g=K(c);G(()=>{h.current=t.fit,g.current=c});let _=K(null),v=K(null),[y,b]=Ct(null),x=y??m??n,[S,C]=Ct(!1),[w,T]=Ct(!0);W(()=>{if(!m||_.current?.source===m)return;let e=!_.current,t=null,n=!1,r=()=>t?_.current===t:e,i=t=aZ(m,f.current,()=>h.current,g.current,{unsupported:()=>{r()&&C(!0)},buffered:e=>{r()&&T(e)},frame:()=>{if(_.current===t){n||(n=!0,b(m));return}_.current?.dispose(),_.current=i,v.current=null,i.show(),n=!0,b(m),T(i.buffered())}},e);if(e){_.current=i;return}return v.current=i,()=>{_.current!==i&&(i.dispose(),v.current===i&&(v.current=null))}},[m]),W(()=>()=>{_.current?.dispose(),_.current=null},[]),W(()=>{_.current?.setTarget(c),v.current?.setTarget(c)},[c]);let E=$X(e.rec||c!==null?null:x),D=eZ(e.rec?n:null),O=!!x.lowOf,k=x.info().latestT,A=!e.rec&&c!==null&&k!==null?c-k:null,j=e.rec?`No video at this time`:`Not buffered`;return Ot(`div`,{ref:d,className:`kymo-camera${e.onPick?` is-tile`:``}`,onContextMenu:e.onMenu,...e.onPick?{role:`button`,tabIndex:0,"data-camera":n.id,"aria-label":`Show ${e.name} alone`,onClick:e.onPick,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e.onPick())}}:{},children:[q(`canvas`,{ref:f,className:`kymo-camera__video`,role:`img`,"aria-label":`Video from ${e.name}`}),S?q(`div`,{className:`kymo-camera__empty`,children:q(`p`,{className:`kymo-camera__empty-title`,children:`This browser can't decode this camera`})}):E===null?Ot(`div`,{className:`kymo-camera__overlay`,children:[q(`span`,{className:`kymo-camera__name`,children:e.name}),e.rec?q(`span`,{className:`kymo-camera__rec`,children:`Recording`}):c===null?q(`span`,{className:`kymo-camera__live`,children:`LIVE`}):q(`span`,{className:`kymo-camera__ago`,children:A===null?``:nZ(A)}),O?q(`span`,{className:`kymo-camera__badge`,title:`Low-quality copy (small panel)`,children:`LQ`}):null,c!==null&&u!==`none`?q(`span`,{className:`kymo-camera__badge${u===`exact`?` is-exact`:``}`,children:u===`exact`?`Exact`:`Approx.`}):null,l??(c!==null&&!w?j:null)?q(`span`,{className:`kymo-camera__note`,children:l??j}):null,e.conn?.limitNotice?q(`span`,{className:`kymo-camera__note`,role:`status`,children:e.conn.limitNotice}):null,D?.broken?q(`span`,{className:`kymo-camera__note`,role:`status`,title:`Some of this recording was missing, out of order or changed where it is stored (${D.broken} of ${D.broken+D.verified} checked ${D.broken+D.verified===1?`chunk`:`chunks`}). The video may have gaps there.`,children:`Some messages were missing or out of order`}):null]}):Ot(`div`,{className:`kymo-camera__empty kymo-camera__empty--cover`,role:`status`,children:[q(`p`,{className:`kymo-camera__empty-title`,children:`No signal`}),Ot(`p`,{className:`kymo-camera__empty-detail`,children:[e.name,` · no video for `,tZ(E)]})]})]})}function $X(e){let[t]=Ct(()=>Date.now()),[n,r]=Ct(null);return W(()=>{if(!e){r(null);return}let n=()=>{let{arrivedAt:n,gapMs:i}=e.info(),a=Date.now()-Math.max(n??0,t);r(a>RE(i)?Math.floor(a/1e3):null)};n();let i=setInterval(n,500);return()=>clearInterval(i)},[e,t]),n}function eZ(e){let[t,n]=Ct(null);return W(()=>{if(!e?.integrity){n(null);return}let t=()=>{let t=e.integrity();n(e=>e?.verified===t?.verified&&e?.broken===t?.broken?e:t&&{verified:t.verified,broken:t.broken})};t();let r=setInterval(t,1e3);return()=>clearInterval(r)},[e]),t}function tZ(e){return e<60?`${e} s`:e<3600?`${Math.floor(e/60)} min`:`${Math.floor(e/3600)} h`}function nZ(e){let t=Math.abs(e).toFixed(1);return t===`0.0`?`0.0 s`:`${e<0?`−`:`+`}${t} s`}var rZ=60,iZ=.05;function aZ(e,t,n,r,i,a=!0){let o=e.acquire?.(),s=!1,c=!0,l=e=>{c=e,i.buffered(e)},u=null,d=null,f=r,p=`live`,m=!0,h=!1,g=!1,_=null,v=null,y=null,b=[],x=uU(),S=NaN,C=[],w=()=>{for(let e of b)e.close();b=[]},T=e=>{if(s){e.close();return}if(p===`seek`){_?.close(),_=e;return}for(b.push(e);b.length>(a?rZ:1);)b.shift().close();i.frame?.()},E=e=>{if(!b.length)return;let t=b[b.length-1].timestamp/1e6,n=Number.isNaN(S)?16:e-S,r=Math.max(EU(x,t,n,e=>{let t=b.find(t=>t.timestamp/1e6>e);return t?t.timestamp/1e6:NaN}),t-iZ);x.d=r;let i=-1;for(;i+1<b.length&&b[i+1].timestamp/1e6<=r+1e-6;)i++;if(!(i<0)){for(let e=0;e<i;e++)b[e].close();v?.close(),v=b[i],b=b.slice(i+1)}},D=()=>{!d||d.state===`closed`?d=new VideoDecoder({output:T,error:()=>{}}):d.reset(),d.configure(u),m=!0},O=e=>{d?.state===`closed`&&e.key&&D(),!(d?.state!==`configured`||m&&!e.key)&&(m=!1,d.decode(new EncodedVideoChunk({type:e.key?`key`:`delta`,timestamp:Math.round(e.t*1e6),data:e.data})))},k=()=>{p=`live`,l(!0),w(),x=uU(),D();for(let t of e.livePlan?.()??[])O(t)},A=async()=>{if(!h){h=!0;try{for(;!s&&p===`seek`&&g;){g=!1;let t=[];try{t=await e.seekPlan(f)}catch{}if(!(s||p!==`seek`||g)&&(l(t.length>0),t.length)){D();for(let e of t)O(e);try{await d.flush()}catch{}p===`seek`&&_&&(v?.close(),v=_,_=null,i.frame?.())}}}finally{h=!1,_?.close(),_=null}}},j=()=>{f===null?p!==`live`&&k():(p=`seek`,w(),g=!0,A())};e.onUnit&&C.push(e.onUnit(e=>{u&&p===`live`&&O(e)})),(async()=>{if(typeof VideoDecoder>`u`){i.unsupported();return}if(e.info().codec||(e.ready?await e.ready():e.onUnit&&await new Promise(t=>{let n=e.onUnit(()=>{e.info().codec&&(n(),t())});C.push(n)})),s)return;if(!e.info().codec){l(!1);return}let t={codec:e.info().codec,optimizeForLatency:!0,hardwareAcceleration:`no-preference`},n=!1;try{n=(await VideoDecoder.isConfigSupported(t)).supported===!0}catch{}if(!s){if(!n){i.unsupported();return}u=t,f===null?k():j()}})();let M=n(),N=()=>{if(!a)return;let e=window.devicePixelRatio||1,r=Math.max(1,Math.round(t.clientWidth*e)),i=Math.max(1,Math.round(t.clientHeight*e)),o=!1,s=performance.now();if(p===`live`&&E(s),S=s,(t.width!==r||t.height!==i)&&(t.width=r,t.height=i,o=!0),v&&(y?.close(),y=v,v=null,o=!0),n()!==M&&(M=n(),o=!0),!o||!y)return;let c=t.getContext(`2d`);if(!c)return;let l=y.displayWidth,u=y.displayHeight,d=M===`cover`?Math.max(r/l,i/u):Math.min(r/l,i/u),f=l*d,m=u*d;c.clearRect(0,0,r,i),c.drawImage(y,(r-f)/2,(i-m)/2,f,m)},P=0,F=()=>{P=RH(F),N()};return P=RH(F),{source:e,show(){a=!0},buffered:()=>c,setTarget(e){e!==f&&(f=e,u&&j())},dispose(){s=!0,zH(P),C.forEach(e=>e()),d&&d.state!==`closed`&&d.close();for(let e of[_,v,y])e?.close();_=v=y=null,w(),o?.()}}}function oZ(e,t){let n=e.filter(e=>e.x.length>=2&&sZ(e.x));if(n.length<2)return null;let r=1/0,i=-1/0;for(let e of n)e.x[0]<r&&(r=e.x[0]),e.x[e.x.length-1]>i&&(i=e.x[e.x.length-1]);if(!(i>r))return null;let a=Math.max(2,t),o=Float64Array.from({length:a},(e,t)=>r+t/(a-1)*(i-r)),s=new Float64Array(a).fill(1/0),c=new Float64Array(a).fill(-1/0),l=new Uint16Array(a);for(let e of n){let t=0;for(let n=0;n<a;n++){let r=o[n];if(r<e.x[0]||r>e.x[e.x.length-1])continue;for(;t<e.x.length-2&&e.x[t+1]<r;)t++;let i=e.x[t],a=e.x[t+1],u=e.y[t],d=e.y[t+1],f=a===i?u:u+(d-u)*(r-i)/(a-i);f-f===0&&(f<s[n]&&(s[n]=f),f>c[n]&&(c[n]=f),l[n]++)}}for(let e=0;e<a;e++)l[e]<2&&(s[e]=NaN,c[e]=NaN);return{x:o,lo:s,hi:c}}function sZ(e){for(let t=1;t<e.length;t++)if(!(e[t]>=e[t-1]))return!1;return!0}function cZ(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=new Set,n={};for(let r of e)for(let e=0;e<r.columnNames.length;e++){let i=r.columnNames[e];t.add(i),r.units[e]?.trim()&&(n[i]=r.units[e])}let r=[...t];return{meta:``,columnNames:r,units:r.map(e=>n[e]??``),rows:e.flatMap(e=>e.rows)}}function lZ(e,t,n,r,i){return n||e.length===0||(t>0?e.length!==1:e.length<2||r!==`ElapsedTime`)?null:e.map((e,n)=>({conn:e,keySuffix:`__${t+n}`,offset:i[e.id]??0}))}function uZ(e,t,n,r,i){if(e.length===1){let a=e[0];return dZ(a.conn,t,n,a.keySuffix,a.offset,r,i)}let a=e.map(e=>dZ(e.conn,t,n,e.keySuffix,e.offset,[],null)),o=()=>a.reduce((e,t)=>t.latestT()>e.latestT()?t:e);return{pull:(e,t,n,i)=>[...r,...a.flatMap(r=>r.pull(e,t,n,i))],xBounds:()=>{let e=i;for(let t of a){let n=t.xBounds();n&&(e=e?[Math.min(e[0],n[0]),Math.max(e[1],n[1])]:n)}return e},latestX:()=>o().latestX(),version:()=>a.reduce((e,t)=>e+t.version(),0),latestT:()=>o().latestT(),timeAfter:e=>o().timeAfter(e),xAtTime:e=>o().xAtTime(e),latestValues:e=>new Map(a.flatMap(t=>[...t.latestValues(e)]))}}function dZ(e,t,n,r,i,a,o){let s=null;return{pull:(o,c,l,u)=>{let d=e.source.version();if(!s||s.ver!==d||s.x0!==o||s.x1!==c||s.mp!==l){let a=e.source.getPointsSync(n,{xKey:t,x0:o-i,x1:c-i},l),u=i===0?a.x:a.x.map(e=>e+i);s={ver:d,x0:o,x1:c,mp:l,pts:{...a,x:u,cols:new Map([...a.cols].map(([e,t])=>[e+r,t]))}}}let p=f(s.pts,u);if(t!==`ElapsedTime`)return[...a,p];let m=Math.min(e.source.latestTimeSync(),u===void 0?1/0:u-i),h=lt(n,t=>e.source.lastKnownSync(t),o-i,c-i,m);if(!h)return[...a,p];let g=i===0?h.x:h.x.map(e=>e+i);return[...a,p,{...h,x:g,cols:new Map([...h.cols].map(([e,t])=>[e+r,t]))}]},xBounds:()=>{let n=e.source.xBoundsSync(t);return n.x1>n.x0?o?[Math.min(o[0],n.x0+i),Math.max(o[1],n.x1+i)]:[n.x0+i,n.x1+i]:o},latestX:()=>{let n=e.source.latestSync(t);return Number.isFinite(n)?n+i:null},version:()=>e.source.version(),id:e.id,latestT:()=>e.source.latestTimeSync(),timeAfter:t=>e.source.timeAfterSync(t),xAtTime:n=>e.source.xAtTimeSync(t,n)+i,latestValues:t=>{let n=new Map,i=t.filter(e=>e.endsWith(r)),a=e.source.latestValuesSync(i.map(e=>e.slice(0,-r.length)));for(let e of i){let t=a.get(e.slice(0,-r.length));t!==void 0&&n.set(e,t)}return n}}}function fZ(e,t){return e.filter(e=>Ze(t,e))}var pZ=`__ref`,mZ=8e3;function hZ(e,t){return e.map(e=>({...e,id:`${e.id}${pZ}`,column:`${e.column}${pZ}`,color:t}))}var gZ=new WeakMap;function _Z(e,t,n){let r=e.data.rows,i=`${t}\n${n.join(`
|
|
608
|
+
`)}`,a=gZ.get(r);a||(a=new Map,gZ.set(r,a));let o=a.get(i);if(o)return o;let s=vZ(m(r,t,n,mZ,pZ)),c={points:s,span:s.length>1?[s.x[0],s.x[s.length-1]]:null};return a.set(i,c),c}function vZ(e){let t=!0;for(let n=1;n<e.length&&t;n++)t=e.x[n-1]<=e.x[n];if(t)return e;let n=Array.from({length:e.length},(e,t)=>t).sort((t,n)=>e.x[t]-e.x[n]),r=new Map;for(let[t,i]of e.cols)r.set(t,Float64Array.from(n,e=>i[e]));return{length:e.length,x:Float64Array.from(n,t=>e.x[t]),cols:r}}function yZ(e,t){return e?t?[Math.min(e[0],t[0]),Math.max(e[1],t[1])]:e:t}function bZ(e,t,n,r,i){e.source.trackCycles(t);let a=r.reference===`dataset`&&i?_Z(i,t,n):null,o=null;return{pull:(i,s,c,l)=>{let u=e.source.version();if(!o||o.ver!==u||o.x0!==i||o.x1!==s||o.mp!==c){let l=C;if(r.reference===`previous`){let r=e.source.cyclePointsSync(t,`previous`,n,{x0:i,x1:s},c);l={...r,cols:new Map([...r.cols].map(([e,t])=>[e+pZ,t]))}}else a&&(l=D(a.points,i,s));o={ver:u,x0:i,x1:s,mp:c,live:e.source.cyclePointsSync(t,`current`,n,{x0:i,x1:s},c),ref:l}}return[o.ref,f(o.live,l)]},id:e.id,latestT:()=>e.source.latestTimeSync(),timeAfter:t=>e.source.timeAfterSync(t),xAtTime:n=>e.source.xAtTimeSync(t,n),xBounds:()=>yZ(e.source.cycleSpanSync(t),a?.span??null),latestX:()=>{let n=e.source.latestSync(t);return Number.isFinite(n)?n:null},version:()=>e.source.version(),latestValues:t=>e.source.latestValuesSync(t)}}function xZ(e,t){return e.reference===`previous`?e.previousColor:e.reference===`dataset`&&t?e.datasetColor:null}function SZ(e,t,n,r,i=0){let a=e.bands;if(!a)return[];let o=n.filter(e=>a[e.column]);if(o.length===0||e.data.rows.length!==a[o[0].column].lo.length)return[];let s=Float64Array.from(e.data.rows,e=>{let n=e[t];return typeof n==`number`?n+i:NaN});return o.map(e=>({seriesId:e.id,color:r??e.color,x:s,lo:a[e.column].lo,hi:a[e.column].hi}))}var CZ=class{#e;#t;#n;#r=new Map;constructor(e,t={}){this.#e=e,this.#t=[...e.keys()].map(e=>({name:e,type:`number`,unit:t[e]??``})),this.#n=e.size?e.values().next().value.length:0}get length(){return this.#n}get columnMap(){return this.#e}async getSchema(){return this.#t}async getSeries(e){let t=this.#e.get(e.viewport.xKey),n=this.#e.get(e.column);return!t||!n?ee(new Float64Array,new Float64Array,e.viewport.x0,e.viewport.x1,e.maxPoints):ee(t,n,e.viewport.x0,e.viewport.x1,e.maxPoints)}async getSeriesMulti(e,t,n){return this.getSeriesMultiSync(e,t,n)}getSeriesMultiSync(e,t,n){let r=this.#e.get(t.xKey),i=r?e.filter(e=>this.#e.has(e)):[];return!r||i.length===0?{x0:t.x0,bucket:0,rows:[],columns:i}:ne(r,i.map(e=>this.#e.get(e)),i,t.x0,t.x1,n)}getColumnsSync(e,t,n){let r=this.#e.get(t.xKey),i=r?e.filter(e=>this.#e.has(e)):[];return!r||i.length===0?null:A(r,i.map(e=>this.#e.get(e)),i,t.x0,t.x1,n)}async readColumns(e,t,n){let r={};for(let i of e){let e=this.#e.get(i);e&&(r[i]=e.slice(t,t+n))}return r}async xBounds(e){return this.xBoundsSync(e)}xBoundsSync(e){let t=this.#r.get(e);if(!t){let n=this.#e.get(e),r=1/0,i=-1/0;if(n)for(let e=0;e<n.length;e++){let t=n[e];t<r&&(r=t),t>i&&(i=t)}t=r<=i?{x0:r,x1:i}:{x0:0,x1:0},this.#r.set(e,t)}return t}sampleRowsSync(e,t){let n=t?this.#e.get(t.xcol):void 0,r=null;if(t&&n){r=[];for(let e=0;e<n.length;e++)n[e]>=t.x0&&n[e]<=t.x1&&r.push(e)}let i=r?r.length:this.#n,a=Math.max(1,Math.ceil(i/e)),o=[...this.#e.keys()],s=o.map(e=>this.#e.get(e)),c=[];for(let e=0;e<i;e+=a){let t=r?r[e]:e,n={};for(let e=0;e<o.length;e++){let r=s[e][t];n[o[e]]=Number.isNaN(r)?null:r}c.push(n)}return c}async sampleRows(e,t){return this.sampleRowsSync(e,t)}async dispose(){}};function wZ(e){if(!Number.isFinite(e))return`—`;let t=Math.abs(e);return t>=1e4||t<.01&&e!==0?e.toExponential(1):String(parseFloat(e.toPrecision(4)))}function TZ(e,t){let n=Math.max(1,Math.min(50,Math.floor(t.xBins))),r=Math.max(1,Math.min(50,Math.floor(t.yBins))),i=t.xMin,a=t.xMax,o=t.yMin,s=t.yMax;if(i===void 0||a===void 0||o===void 0||s===void 0){let n=1/0,r=-1/0,c=1/0,l=-1/0;for(let i of e){let e=i[t.xCol],a=i[t.yCol];typeof e==`number`&&Number.isFinite(e)&&(e<n&&(n=e),e>r&&(r=e)),typeof a==`number`&&Number.isFinite(a)&&(a<c&&(c=a),a>l&&(l=a))}i===void 0&&(i=n),a===void 0&&(a=r),o===void 0&&(o=c),s===void 0&&(s=l)}let c=a-i,l=s-o;if(!(c>0)||!(l>0))return{cells:[],xLabels:[],yLabels:[]};let u=new Float64Array(n*r),d=new Float64Array(n*r),f=t.valueCol===``;for(let p of e){let e=p[t.xCol],m=p[t.yCol];if(typeof e!=`number`||!Number.isFinite(e)||typeof m!=`number`||!Number.isFinite(m)||e<i||e>a||m<o||m>s)continue;let h=Math.floor((e-i)/c*n);h>=n&&(h=n-1),h<0&&(h=0);let g=Math.floor((m-o)/l*r);g>=r&&(g=r-1),g<0&&(g=0);let _=g*n+h;if(f)d[_]+=1;else{let e=p[t.valueCol];if(typeof e!=`number`||!Number.isFinite(e))continue;u[_]+=e,d[_]+=1}}let p=Array.from({length:n},(e,t)=>wZ(i+(t+.5)*(c/n))),m=Array.from({length:r},(e,t)=>wZ(o+(r-1-t+.5)*(l/r))),h=[];for(let e=0;e<r;e++){let t=r-1-e;for(let r=0;r<n;r++){let i=e*n+r,a=d[i],o=f?a:a>0?u[i]/a:NaN;h.push({x:p[r],y:m[t],value:o})}}return{cells:h,xLabels:p,yLabels:m}}function EZ(e,t){return t.some(t=>t.name===e)}function DZ(e,t){return EZ(e,t)?`ƒ ${e}`:e}var OZ=8e3,kZ=3e3,AZ=[];function jZ(e){return`live`in e?e.live.source.columns():`source`in e&&e.source instanceof CZ?e.source.columnMap:void 0}var MZ=4e3,NZ=new WeakMap;function PZ(e,t,n){let r=NZ.get(e);r||NZ.set(e,r=new Map);let i=JSON.stringify([n,...t]),a=r.get(i);return a||r.set(i,a=new XE({meta:``,columnNames:[n,...t],units:[],rows:e})),a}var FZ=new WeakMap;function IZ(e,t){if(t!==`parallel`||e.length===0)return e;let n=e.length,r=100/n;return e.map((e,t)=>({...e,bandFromPct:Math.round((n-1-t)*r),bandToPct:Math.round((n-t)*r)}))}function LZ(e,t){let n=1/0,r=-1/0;for(let{rows:i,offset:a}of e){let e=FZ.get(i);e||(e=new Map,FZ.set(i,e));let o=e.get(t);if(o===void 0){let n=1/0,r=-1/0;for(let e of i){let i=e[t];typeof i!=`number`||!Number.isFinite(i)||(i<n&&(n=i),i>r&&(r=i))}o=Number.isFinite(n)?[n,r]:null,e.set(t,o)}o&&(n=Math.min(n,o[0]+a),r=Math.max(r,o[1]+a))}return Number.isFinite(n)&&r>n?[n,r]:null}function RZ(e,t){let n={};for(let t=0;t<e.columnNames.length;t++){let r=e.units[t]?.trim();r&&(n[e.columnNames[t]]=r)}let r=Object.entries(n);for(let e=0;e<t;e++)for(let[t,i]of r)n[`${t}__${e}`]=i;return n}function zZ(e,t){let n=1/0,r=-1/0;for(let i of e){let e=i[t];typeof e!=`number`||!Number.isFinite(e)||(e<n&&(n=e),e>r&&(r=e))}if(!(r>n))return e;let i=(r-n)/2,a=0,o=NaN;for(let n=0;n<e.length;n++){let r=e[n][t];typeof r!=`number`||!Number.isFinite(r)||(r<o-i&&(a=n),o=r)}return a===0?e:e.slice(a)}var BZ=new Map;function VZ(e){let t=BZ.get(e);return t||(t=Float64Array.from({length:e},(e,t)=>t),BZ.clear(),BZ.set(e,t)),t}function HZ(e){let{worksheet:t,viewXRange:n,selectedIds:r,selectedDatasets:i,mathChannels:a,datasetOffsets:o,datasetColors:s,datasetPalette:c}=e,l=t.panels,u=t.panelChartSettings,d=t.xKey,f={connections:St(()=>d===`ElapsedTime`?e.liveConnections:e.liveConnections.map(e=>{let t=zZ(e.dataset.rows,d);return t===e.dataset.rows?e:{...e,dataset:{...e.dataset,rows:t}}}),[e.liveConnections,d])},[p,h]=Ct({}),g=St(()=>l.some(e=>e.kind!==`multiband`),[l]),_=St(()=>f.connections.some(e=>r.includes(e.id)),[f.connections,r]),v=St(()=>{let e=f.connections.filter(e=>r.includes(e.id));return e.length===1&&i.length===0?e[0]:null},[f.connections,r,i]),y=St(()=>cZ(i.map(e=>{let t=p[e.id];return t?{...e.data,rows:t}:e.data})),[i,p]),b=St(()=>{let e=f.connections.filter(e=>r.includes(e.id)).map(e=>e.dataset);return e.length===0?y:cZ(y?[y,...e]:e)},[y,f.connections,r]),x=St(()=>NE(a,u,d).map(e=>e.id).join(`
|
|
609
609
|
`),[a,u,d]),S=St(()=>{let e=new Set(x.split(`
|
|
610
|
-
`));return a.filter(t=>e.has(t.id))},[a,x]),C=St(()=>{if(!b)return null;let e=[...i.map(e=>{let t=p[e.id];return t?{...e.data,rows:t}:e.data}),...f.connections.filter(e=>r.includes(e.id)).map(e=>e.dataset)];if(S.length===0)return{dataset:b,partRows:e.map(e=>e.rows),parts:e};let t=e.map(e=>ME(e,S,d)),n=new Set(t.flatMap(e=>e.ok.map(e=>e.id))),a=S.filter(e=>n.has(e.id)),o=t.map(e=>e.rows),s=t.map(e=>e.ok.map(e=>e.name));if(a.length===0)return{dataset:b,partRows:o,parts:e};let c=a.filter(e=>!b.columnNames.includes(e.name));return{dataset:{meta:b.meta,columnNames:[...b.columnNames,...c.map(e=>e.name)],units:[...b.units,...c.map(e=>e.units)],rows:o.length===1?o[0]:[].concat(...o)},partRows:o,parts:e,okByPart:s}},[b,i,p,f.connections,r,S,d]),w=C?.dataset??null,T=St(()=>{let e=f.connections.filter(e=>r.includes(e.id));return e.length===0?i:[...i,...e.map(e=>({id:e.id,name:e.name,data:e.dataset,live:e}))]},[i,f.connections,r]),E=T.length>1,D=St(()=>T.length===1?
|
|
610
|
+
`));return a.filter(t=>e.has(t.id))},[a,x]),C=St(()=>{if(!b)return null;let e=[...i.map(e=>{let t=p[e.id];return t?{...e.data,rows:t}:e.data}),...f.connections.filter(e=>r.includes(e.id)).map(e=>e.dataset)];if(S.length===0)return{dataset:b,partRows:e.map(e=>e.rows),parts:e};let t=e.map(e=>ME(e,S,d)),n=new Set(t.flatMap(e=>e.ok.map(e=>e.id))),a=S.filter(e=>n.has(e.id)),o=t.map(e=>e.rows),s=t.map(e=>e.ok.map(e=>e.name));if(a.length===0)return{dataset:b,partRows:o,parts:e};let c=a.filter(e=>!b.columnNames.includes(e.name));return{dataset:{meta:b.meta,columnNames:[...b.columnNames,...c.map(e=>e.name)],units:[...b.units,...c.map(e=>e.units)],rows:o.length===1?o[0]:[].concat(...o)},partRows:o,parts:e,okByPart:s}},[b,i,p,f.connections,r,S,d]),w=C?.dataset??null,T=St(()=>{let e=f.connections.filter(e=>r.includes(e.id));return e.length===0?i:[...i,...e.map(e=>({id:e.id,name:e.name,data:e.dataset,live:e}))]},[i,f.connections,r]),E=T.length>1,D=St(()=>T.length===1?jZ(T[0]):void 0,[T]),O=C?.partRows??AZ;W(()=>{let e=i.filter(e=>e.kind!==`memory`);if(e.length===0)return;if(!n||!g){h(e=>Object.keys(e).length?{}:e);return}let t=!1,r=setTimeout(()=>{(async()=>{let r=await Promise.all(e.map(async e=>{let t={xcol:d,x0:n[0],x1:n[1]};try{let n=e.source,r=await PW(`sampleRows`,()=>n.sampleRows(kZ,t));return[e.id,r]}catch{return null}}));if(t)return;let i={};for(let e of r)e&&(i[e[0]]=e[1]);h(i)})()},150);return()=>{t=!0,clearTimeout(r)}},[i,n,d,g]);let k=St(()=>w?.columnNames.join(`
|
|
611
611
|
`)??``,[w]),A=a.map(e=>e.name).join(`
|
|
612
|
-
`),j=St(()=>{let e=i.filter(e=>e.kind!==`memory`).flatMap(e=>jz(e.schema));return e.length?e:null},[i]),M=St(()=>i.some(e=>e.kind!==`memory`)||!_&&i.some(e=>e.data.rows.length>
|
|
613
|
-
`).filter(e=>!i.has(e));return a.length?[...r,...a]:r},[k,A,j]),R=St(()=>{let e=[];for(let t of l){if(t.kind!==`multiband`)continue;let n=u[t.id],r=n&&n.kind===`multiband`?n.series:[];e.push([t.id,[...new Set(r.map(e=>e.column).filter(e=>e!==d))]])}return JSON.stringify(e)},[l,u,d]),z=St(()=>{let e={};if(!w||M)return e;for(let[t,n]of JSON.parse(R)){let r=[];if(n.length>0)if(!E)r.push(m(w.rows,d,n,DZ));else{let e=Math.max(1,Math.floor(DZ/T.length));for(let t=0;t<T.length;t++){let i=T[t];if(N&&`live`in i&&i.live)continue;let a=O[t]??i.data.rows;r.push(m(a,d,n,e,`__${t}`,o[i.id]??0))}}e[t]=r}return e},[w,R,d,E,T,o,O,N,M]),B=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`multiband`)continue;let n=u[t.id],r=(n&&n.kind===`multiband`?n.series:[]).filter(e=>e.column!==d),i=n&&n.kind===`multiband`?n.layout:`overlay`,a=e=>FZ(e,i),l;if(!E)l=a(r);else{let e=a(r);l=[];for(let t=0;t<T.length;t++){let n=iB(s,T[t].id,t,c);for(let r of e)l.push({...r,id:`${r.id}__${t}`,column:`${r.column}__${t}`,color:n})}}let f=z[t.id]??[],p=E&&n?.kind===`multiband`&&n.envelope?r.flatMap(e=>{let t=aZ(f.flatMap((t,n)=>{let r=t.cols.get(`${e.column}__${n}`);return r?[{x:t.x,y:r}]:[]}),jZ);return t?[{seriesId:e.id,color:e.color,...t}]:[]}):void 0,m=T.flatMap((e,t)=>`bands`in e&&e.bands?xZ(e,d,r,E?iB(s,e.id,t,c):void 0,o[e.id]??0):[]),h=[...p??[],...m];e[t.id]={effectiveSeries:l,points:f,envelopes:h.length?h:void 0}}return e},[w,l,u,d,E,T,s,c,o,z]),V=St(()=>{let e={pts:{},colorMeta:{},datasetColors:{}};if(!w)return e;let t={},r={},i={},a=AZ,o=T.map((e,t)=>({id:e.id,rows:O[t]??p[e.id]??e.data.rows,full:a(e)})),f={id:`single`,rows:w.rows,full:T.length===1?a(T[0]):void 0};for(let e of l){if(e.kind!==`xyscatter`)continue;let a=u[e.id];if(!a||a.kind!==`xyscatter`)continue;let{xyXCol:l,xyYCol:p}=a;if(!l||!p){t[e.id]={length:0,x:[],y:[]};continue}if(E){let{cols:r,colors:a}=iG(o,l,p,{xKey:d,viewXRange:n,colorOverrides:s,palette:c});t[e.id]=r,i[e.id]=a;continue}let m=rG(f,l,p,{xKey:d,viewXRange:n,colorCol:a.xyColorCol||void 0});t[e.id]=m?.cols??{length:0,x:[],y:[]},m?.color&&(r[e.id]=m.color)}return{pts:t,colorMeta:r,datasetColors:i}},[w,l,u,n,d,E,T,p,s,c,O]),ee=K(new Map),te=St(()=>{let e={};if(!w)return e;let t={length:0,x:[],y:[],z:[]},{rows:r}=w,i=D;for(let a of l){if(a.kind!==`xyzmesh`)continue;let o=u[a.id];if(!o||o.kind!==`xyzmesh`)continue;if(o.xyzMode===`matrix`){let n=(o.xyzColumns??[]).flatMap(e=>{let t=ZW(r,e,i);return t?[t]:[]}),s=n[0]?.length??0,c=n.length;if(s<2||c<2){e[a.id]={points:t};continue}let l=ee.current.get(a.id);l?.length!==s*c&&ee.current.set(a.id,l=new Float32Array(s*c)),n.forEach((e,t)=>l.set(e.length===s?e:e.subarray(0,s),t*s));let u=ZW(r,d,i),f=u&&!(o.xyzColumns??[]).includes(d)&&u.length>=s&&Number.isFinite(u[0])&&Number.isFinite(u[s-1])?[u[0],u[s-1]]:[0,s-1];e[a.id]={points:t,surface:{w:s,h:c,values:l,x:f,y:[0,c-1]}};continue}let{xyzXCol:s,xyzYCol:c,xyzZCol:l}=o,f=s?ZW(r,s,i):void 0,p=c?ZW(r,c,i):void 0,m=l?ZW(r,l,i):void 0;if(!f||!p||!m){e[a.id]={points:t};continue}let h=n?ZW(r,d,i):void 0;if(!n||!h){e[a.id]={points:{length:Math.min(f.length,p.length,m.length),x:f,y:p,z:m}};continue}let[g,_]=n,v=0;for(let e=0;e<h.length;e++)h[e]>=g&&h[e]<=_&&v++;let y=new Float64Array(v),b=new Float64Array(v),x=new Float64Array(v);for(let e=0,t=0;e<h.length;e++)h[e]>=g&&h[e]<=_&&(y[t]=f[e],b[t]=p[e],x[t]=m[e],t++);e[a.id]={points:{length:v,x:y,y:b,z:x}}}return e},[w,l,u,n,d,D]),H=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`histogram`)continue;let n=u[t.id];e[t.id]=n?.kind===`histogram`&&n.histColumn&&QW(w.rows,n.histColumn,D)||new Float64Array}return e},[w,l,u,D]),ne=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`polar`)continue;let n=u[t.id],r=n?.kind===`polar`&&n.polarAngleCol?ZW(w.rows,n.polarAngleCol,D):void 0,i=n?.kind===`polar`&&n.polarRadiusCol?ZW(w.rows,n.polarRadiusCol,D):void 0;e[t.id]=r&&i?{angles:r,radii:i}:{angles:[],radii:[]}}return e},[w,l,u,D]),re=(e,t,n,r)=>{let i=t&&QW(e,t,D)||new Float64Array,a=n?ZW(e,n,D):void 0;return{signal:i,rate:a&&eG(a)||parseFloat(r)||1}},ie=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`spectrum`)continue;let n=u[t.id];n?.kind===`spectrum`&&(e[t.id]=re(w.rows,n.specSignalCol,n.specTimeCol,n.specSampleRate))}return e},[w,l,u,D]),U=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`boxplot`)continue;let n=u[t.id];e[t.id]=n?.kind===`boxplot`&&n.boxValueCol?$W(w.rows,n.boxValueCol,n.boxGroupCol||void 0,D):[]}return e},[w,l,u,D]),ae=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`spectrogram`)continue;let n=u[t.id];n?.kind===`spectrogram`&&(e[t.id]=re(w.rows,n.sgSignalCol,n.sgTimeCol,n.sgSampleRate))}return e},[w,l,u,D]),oe=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`heatmap`)continue;let n=u[t.id];if(!n||n.kind!==`heatmap`){e[t.id]={cells:[],xLabels:[],yLabels:[]};continue}if(n.hmMode===`matrix`){let r=w.rows,i=n.hmColumns.flatMap(e=>{let t=ZW(r,e,D);return t?[{name:e,v:t}]:[]}),a=i.reduce((e,t)=>Math.min(e,t.v.length),i.length?1/0:0),o=ZW(r,d,D),s,c;if(n.hmSpacing===`values`){o&&mJ(o.subarray(0,a))&&(s=Float64Array.from(o.subarray(0,a)));let e=i.map(e=>({c:e,v:parseFloat(e.name)})).sort((e,t)=>t.v-e.v);e.length&&mJ(e.map(e=>e.v).reverse())&&(i=e.map(e=>e.c),c=Float64Array.from(e,e=>e.v))}let l=i.length,u=new Float32Array(a*l);i.forEach((e,t)=>u.set(e.v.subarray(0,a),t*a));let f=e=>String(o?+o[e].toPrecision(6):e+1);e[t.id]={cells:[],xLabels:[],yLabels:i.map(e=>e.name),grid:{w:a,h:l,values:u,xLabels:f,yLabels:i.map(e=>e.name)},xCentres:s,yCentres:c}}else if(n.hmMode===`correlation`){let r=n.hmColumns.filter(e=>L.includes(e));if(r.length<2){e[t.id]={cells:[],xLabels:r,yLabels:r};continue}let i=r.map(e=>{let t=[];for(let n of w.rows){let r=n[e];typeof r==`number`&&Number.isFinite(r)&&t.push(r)}return t}),a=i.map(e=>e.reduce((e,t)=>e+t,0)/(e.length||1)),o=[];for(let e=0;e<r.length;e++)for(let t=0;t<r.length;t++){let n=i[e],s=i[t],c=a[e],l=a[t],u=Math.min(n.length,s.length),d=0,f=0,p=0;for(let e=0;e<u;e++){let t=n[e]-c,r=s[e]-l;d+=t*r,f+=t*t,p+=r*r}let m=f>0&&p>0?d/Math.sqrt(f*p):+(e===t);o.push({x:r[t],y:r[e],value:m})}e[t.id]={cells:o,xLabels:r,yLabels:r}}else if(n.hmMode===`binned`||n.hmMode===`count`){let{hmXCol:r,hmYCol:i}=n,a=n.hmMode===`count`?``:n.hmValueCol;if(!r||!i||n.hmMode===`binned`&&!a){e[t.id]={cells:[],xLabels:[],yLabels:[]};continue}let o=e=>{let t=parseFloat(e);return Number.isFinite(t)?t:void 0};e[t.id]=wZ(w.rows,{xCol:r,yCol:i,valueCol:a,xBins:n.hmXBins,yBins:n.hmYBins,xMin:o(n.hmXMin),xMax:o(n.hmXMax),yMin:o(n.hmYMin),yMax:o(n.hmYMax)})}else{let{hmXCol:r,hmYCol:i,hmValueCol:a}=n;if(!r||!i||!a){e[t.id]={cells:[],xLabels:[],yLabels:[]};continue}let o=new Map,s=new Set,c=new Set;for(let e of w.rows){let t=String(e[r]??``),n=String(e[i]??``),l=e[a];if(typeof l!=`number`||!Number.isFinite(l))continue;s.add(t),c.add(n);let u=`${t}\0${n}`,d=o.get(u)??{sum:0,count:0};o.set(u,{sum:d.sum+l,count:d.count+1})}let l=e=>{let t=[...e];return t.every(e=>e.trim()!==``&&Number.isFinite(Number(e)))?t.sort((e,t)=>Number(e)-Number(t)):t.sort()},u=l(s),d=l(c),f,p;if(n.hmSpacing===`values`){let e=Float64Array.from(u,Number),t=Float64Array.from(d,Number);mJ(e)&&(f=e),mJ(t)&&(d=[...d].reverse(),p=t.reverse())}let m=[];for(let e of d)for(let t of u){let n=o.get(`${t}\0${e}`);m.push({x:t,y:e,value:n?n.sum/n.count:0})}e[t.id]={cells:m,xLabels:u,yLabels:d,xCentres:f,yCentres:p}}}return e},[w,l,u,L,d,D]),se=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`violin`)continue;let n=u[t.id];e[t.id]=n?.kind===`violin`&&n.vlValueCol?$W(w.rows,n.vlValueCol,n.vlGroupCol||void 0,D):[]}return e},[w,l,u,D]),ce=St(()=>{let e={};if(!w)return e;let{rows:t}=w;for(let n of l){if(n.kind!==`confusion`)continue;let r=u[n.id];if(!r||r.kind!==`confusion`||!r.cfActualCol||!r.cfPredictedCol){e[n.id]={actual:[],predicted:[]};continue}let{cfActualCol:i,cfPredictedCol:a}=r,o=D?.get(i),s=D?.get(a);if(o&&s){e[n.id]={actual:o,predicted:s};continue}let c=[],l=[];for(let e of t){let t=e[i],n=e[a];t!==void 0&&n!==void 0&&(c.push(t),l.push(n))}e[n.id]={actual:c,predicted:l}}return e},[w,l,u,D]),le=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`roc`)continue;let n=u[t.id],r=n?.kind===`roc`&&n.rocScoreCol?ZW(w.rows,n.rocScoreCol,D):void 0,i=n?.kind===`roc`&&n.rocLabelCol?ZW(w.rows,n.rocLabelCol,D):void 0;e[t.id]=r&&i?{scores:r,labels:i}:{scores:[],labels:[]}}return e},[w,l,u,D]),ue=St(()=>{let e={};if(!w)return e;let{rows:t}=w;for(let n of l){if(n.kind!==`losscurve`)continue;let r=u[n.id];if(!r||r.kind!==`losscurve`){e[n.id]={xValues:[],series:[]};continue}let{lcXCol:i,lcLeftCols:a,lcRightCols:o}=r,s=[...a.map(e=>({...e,axis:`left`})),...o.map(e=>({...e,axis:`right`}))].map(({column:e,color:n,axis:r})=>({label:e,color:n,values:ZW(t,e,D)??new Float64Array,axis:r})),c=s[0]?.values.length??t.length,l=i&&ZW(t,i,D)||Float64Array.from({length:c},(e,t)=>t);e[n.id]={xValues:l,series:s}}return e},[w,l,u,D]),de=St(()=>{let e={};if(!w)return e;let{rows:t}=w;for(let n of l){if(n.kind!==`controlchart`)continue;let r=u[n.id],i=r?.kind===`controlchart`&&r.ccValueCol?ZW(t,r.ccValueCol,D):void 0;if(!r||r.kind!==`controlchart`||!i){e[n.id]={length:0,value:[]};continue}let a=0;for(let e=0;e<i.length;e++)i[e]-i[e]===0&&a++;let o=a===i.length?null:new Uint32Array(a),s=o?new Float64Array(a):i;if(o)for(let e=0,t=0;e<i.length;e++)i[e]-i[e]===0&&(o[t]=e,s[t++]=i[e]);let c=r.ccSubgroupCol,l=c?D?.get(c):void 0,d=e=>o?o[e]:e;e[n.id]={length:a,value:s,subgroup:c?e=>String(l?l[d(e)]:t[d(e)]?.[c]??``):void 0}}return e},[w,l,u,D]),fe=St(()=>{let e={};if(!w)return e;let{rows:t}=w;for(let n of l){if(n.kind!==`parallelcoords`)continue;let r=u[n.id];if(!r||r.kind!==`parallelcoords`||r.pcColumns.length<2){e[n.id]={length:0,columns:[]};continue}let i=r.pcColumns.map(e=>ZW(t,e,D)??new Float64Array),a=Math.min(...i.map(e=>e.length)),o={length:a,columns:i},s=r.pcColorByCol;if(s)if(L.includes(s))o.colorValue=ZW(t,s,D);else{let e=new Map,n=new Int32Array(a);for(let r=0;r<a;r++){let i=String(t[r]?.[s]??``),a=e.get(i);a===void 0&&e.set(i,a=e.size),n[r]=a}o.colorIndex=n,o.colorLabels=[...e.keys()]}e[n.id]=o}return e},[w,l,u,L,D]),pe=St(()=>{let e={};if(!w)return e;let{rows:t}=w,n={length:0,x:[],y:[]};for(let r of l){if(r.kind!==`embedding`)continue;let i=u[r.id];if(!i||i.kind!==`embedding`||!i.emXCol||!i.emYCol){e[r.id]=n;continue}let{emXCol:a,emYCol:o,emColorCol:s,emColorMode:c,emLabelCol:l}=i,d=ZW(t,a,D),f=ZW(t,o,D);if(!d||!f){e[r.id]=n;continue}let p=Math.min(d.length,f.length),m={length:p,x:d,y:f};if(s)if(c===`numeric`&&L.includes(s))m.colorValue=ZW(t,s,D);else{let e=D?.get(s),n=new Map,r=new Int32Array(p);for(let i=0;i<p;i++){let a=String(e?e[i]:t[i]?.[s]??``),o=n.get(a);o===void 0&&n.set(a,o=n.size),r[i]=o}m.colorIndex=r,m.colorLabels=[...n.keys()]}if(l){let e=D?.get(l);m.label=e?t=>String(e[t]):e=>String(t[e]?.[l]??``)}e[r.id]=m}return e},[w,l,u,L,D]),me=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`flamegraph`)continue;let n=u[t.id];if(!n||n.kind!==`flamegraph`||!n.fgNameCol||!n.fgValueCol){e[t.id]=[];continue}let r=[];for(let e of w.rows){let t=String(e[n.fgNameCol]??``),i=n.fgParentCol?String(e[n.fgParentCol]??``):``,a=e[n.fgValueCol];!t||typeof a!=`number`||!Number.isFinite(a)||r.push({name:t,parent:i,value:a})}e[t.id]=r}return e},[w,l,u]),he=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`barchart`)continue;let n=u[t.id];if(!n||n.kind!==`barchart`||n.bcValueCols.length===0){e[t.id]={groups:[],seriesNames:[]};continue}let r=n.bcValueCols;if(n.bcCategoryCol){let i=new Map;for(let e of w.rows){let t=String(e[n.bcCategoryCol]??`(blank)`);i.has(t)||i.set(t,r.map(()=>0));let a=new Map,o=i.get(t);for(let t=0;t<r.length;t++){let n=e[r[t]];typeof n==`number`&&Number.isFinite(n)&&(o[t]+=n),a.set(r[t],(a.get(r[t])??0)+1)}}e[t.id]={groups:Array.from(i.entries()).map(([e,t])=>({label:e,values:t})),seriesNames:r}}else{let n=w.rows,i=r.map(e=>ZW(n,e,D)),a=i.reduce((e,t)=>t?Math.min(e,t.length):e,1/0),o=Number.isFinite(a)?a:n.length,s=i.map(e=>e??new Float64Array(o).fill(NaN));e[t.id]={groups:[],columns:{length:o,values:s},seriesNames:r}}}return e},[w,l,u,D]),ge=St(()=>{let e={};if(!w)return e;let{rows:t}=w;for(let n of l){if(n.kind!==`radar`)continue;let r=u[n.id];if(!r||r.kind!==`radar`||r.rdAxesCols.length<3){e[n.id]={axes:[],series:[]};continue}let i=r.rdAxesCols,a=i.map(e=>ZW(t,e,D));if(r.rdGroupCol){let o=r.rdGroupCol,s=D?.get(o),c=s?s.length:t.length,l=new Map;for(let e=0;e<c;e++){let n=s?s[e]===s[e]?String(s[e]):`(blank)`:String(t[e][o]??`(blank)`),r=l.get(n);r||l.set(n,r=i.map(()=>0));for(let t=0;t<i.length;t++){let n=a[t]?.[e]??NaN;n-n===0&&(r[t]+=n)}}e[n.id]={axes:i,series:Array.from(l.entries()).map(([e,t])=>({name:e,values:t}))}}else{let t=a.map(e=>{let t=0,n=0;if(e)for(let r=0;r<e.length;r++)e[r]-e[r]===0&&(t+=e[r],n++);return t/(n||1)});e[n.id]={axes:i,series:[{name:`Series 1`,values:t}]}}}return e},[w,l,u,D]),_e=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`areachart`)continue;let n=u[t.id];if(!n||n.kind!==`areachart`||n.acYCols.length===0){e[t.id]=[];continue}let r=w.rows,i=n.acYCols.map(e=>ZW(r,e,D)),a=i[0]?.length??r.length,o=(n.acXCol?ZW(r,n.acXCol,D):void 0)??BZ(a);e[t.id]=n.acYCols.flatMap((e,t)=>{let n=i[t];return n?[{name:e,x:o,y:n}]:[]})}return e},[w,l,u,D]),ve=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`cdfchart`)continue;let n=u[t.id];if(!n||n.kind!==`cdfchart`){e[t.id]=[];continue}e[t.id]=n.cdValueCols.map(e=>({name:e,values:QW(w.rows,e,D)??new Float64Array}))}return e},[w,l,u,D]),ye=St(()=>{let e={};if(!w)return e;let{rows:t}=w,n={length:0,x:[],y:[],size:[]};for(let r of l){if(r.kind!==`bubblechart`)continue;let i=u[r.id];if(!i||i.kind!==`bubblechart`||!i.bbXCol||!i.bbYCol||!i.bbSizeCol){e[r.id]=n;continue}let a=ZW(t,i.bbXCol,D),o=ZW(t,i.bbYCol,D),s=ZW(t,i.bbSizeCol,D);if(!a||!o||!s){e[r.id]=n;continue}let c=Math.min(a.length,o.length,s.length),l=new Float64Array(c);for(let e=0;e<c;e++)l[e]=s[e]===s[e]?Math.max(0,s[e]):NaN;let d=new Float64Array(c);for(let e=0;e<c;e++)d[e]=l[e]===l[e]?a[e]:NaN;let f={length:c,x:d,y:o,size:l};if(i.bbColorCol){if(i.bbColorMode===`numeric`)f.colorValue=ZW(t,i.bbColorCol,D);else if(i.bbColorMode===`categorical`){let e=D?.get(i.bbColorCol),n=new Map,r=new Int32Array(c);for(let a=0;a<c;a++){let o=String(e?e[a]:t[a]?.[i.bbColorCol]??``),s=n.get(o);s===void 0&&n.set(o,s=n.size),r[a]=s}f.colorIndex=r,f.colorLabels=[...n.keys()]}}e[r.id]=f}return e},[w,l,u,D]),be=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`treemap`)continue;let n=u[t.id];if(!n||n.kind!==`treemap`||!n.tmNameCol||!n.tmValueCol){e[t.id]=[];continue}let r=[];for(let e of w.rows){let t=String(e[n.tmNameCol]??``),i=n.tmParentCol?String(e[n.tmParentCol]??``):``,a=e[n.tmValueCol];!t||typeof a!=`number`||!Number.isFinite(a)||r.push({name:t,parent:i,value:a})}e[t.id]=r}return e},[w,l,u]),xe=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`sankey`)continue;let n=u[t.id];if(!n||n.kind!==`sankey`||!n.skSourceCol||!n.skTargetCol||!n.skValueCol){e[t.id]={nodeNames:[],links:[]};continue}let r=new Set,i=[];for(let e of w.rows){let t=String(e[n.skSourceCol]??``),a=String(e[n.skTargetCol]??``),o=e[n.skValueCol];!t||!a||typeof o!=`number`||!Number.isFinite(o)||(r.add(t),r.add(a),i.push({source:t,target:a,value:o}))}e[t.id]={nodeNames:Array.from(r),links:i}}return e},[w,l,u]),Se=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`calibration`)continue;let n=u[t.id],r=n?.kind===`calibration`&&n.cbScoreCol?ZW(w.rows,n.cbScoreCol,D):void 0,i=n?.kind===`calibration`&&n.cbLabelCol?ZW(w.rows,n.cbLabelCol,D):void 0;if(!n||n.kind!==`calibration`||!r||!i){e[t.id]=[];continue}let a=Math.max(2,n.cbBins),o=new Float64Array(a),s=new Float64Array(a);for(let e=0;e<Math.min(r.length,i.length);e++){let t=r[e],n=i[e];if(t-t!==0||n-n!==0)continue;let c=Math.max(0,Math.min(a-1,Math.floor(t*a)));o[c]+=n,s[c]++}e[t.id]=Array.from({length:a},(e,t)=>({center:(t+.5)/a,actual:s[t]>0?o[t]/s[t]:0,count:s[t]})).filter(e=>e.count>0)}return e},[w,l,u,D]),Ce=St(()=>{let e={};if(!w)return e;let t={length:0,theoretical:[],sample:[]},n=e=>{let t=QW(w.rows,e,D);return t?Float64Array.from(t).sort():new Float64Array};for(let r of l){if(r.kind!==`qqplot`)continue;let i=u[r.id];if(!i||i.kind!==`qqplot`||!i.qqValueCol){e[r.id]=t;continue}let a=n(i.qqValueCol),o=a.length;if(o===0){e[r.id]=t;continue}if(i.qqMode===`column`&&i.qqRefCol){let t=n(i.qqRefCol),s=Math.min(o,t.length);e[r.id]={length:s,theoretical:t.subarray(0,s),sample:a.subarray(0,s)}}else{let t=e=>{let t=[2.515517,.802853,.010328],n=[1.432788,.189269,.001308],r=Math.sqrt(-2*Math.log(Math.min(e,1-e))),i=r-(t[0]+t[1]*r+t[2]*r*r)/(1+n[0]*r+n[1]*r*r+n[2]*r*r*r);return e<.5?-i:i},n=new Float64Array(o);for(let e=0;e<o;e++)n[e]=t((e+.5)/o);e[r.id]={length:o,theoretical:n,sample:a}}}return e},[w,l,u,D]),we=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`gantt`)continue;let n=u[t.id];if(!n||n.kind!==`gantt`||!n.gtLabelCol||!n.gtStartCol||!n.gtEndCol){e[t.id]=[];continue}let r=[];for(let e of w.rows){let t=String(e[n.gtLabelCol]??``),i=e[n.gtStartCol],a=e[n.gtEndCol];if(!t||typeof i!=`number`||typeof a!=`number`||!Number.isFinite(i)||!Number.isFinite(a))continue;let o={label:t,start:i,end:a};n.gtGroupCol&&e[n.gtGroupCol]!==void 0&&(o.group=String(e[n.gtGroupCol])),r.push(o)}e[t.id]=r}return e},[w,l,u]),Te=w&&w.columnNames.indexOf(d)>=0?w.units[w.columnNames.indexOf(d)]??``:``,Ee=St(()=>w?LZ(w,E?T.length:0):{},[w,E,T]);return{dataset:b,datasetWithChannels:w,multiDatasetMode:E,numericCols:L,anyDuckDb:M,duckDbLayers:I,liveConn:v,liveOverlays:N,hasLiveSelected:_,staticXRange:P,xUnit:Te,columnUnits:Ee,multibandDataByPanel:B,xyPointsByPanel:V,xyzPointsByPanel:te,histogramDataByPanel:H,polarDataByPanel:ne,spectrumDataByPanel:ie,boxplotDataByPanel:U,spectrogramDataByPanel:ae,heatmapDataByPanel:oe,violinDataByPanel:se,confusionDataByPanel:ce,rocDataByPanel:le,lossCurveDataByPanel:ue,controlChartDataByPanel:de,parallelCoordsDataByPanel:fe,embeddingDataByPanel:pe,flameGraphDataByPanel:me,barChartDataByPanel:he,radarDataByPanel:ge,areaChartDataByPanel:_e,cdfChartDataByPanel:ve,bubbleChartDataByPanel:ye,treemapDataByPanel:be,sankeyDataByPanel:xe,calibrationDataByPanel:Se,qqPlotDataByPanel:Ce,ganttDataByPanel:we,gaugeDataByPanel:St(()=>{let e={};if(!w)return e;let t=e=>e.trim()!==``&&Number.isFinite(Number(e))?Number(e):void 0;for(let n of l){if(n.kind!==`gauge`)continue;let r=u[n.id];if(r?.kind!==`gauge`){e[n.id]=[];continue}e[n.id]=r.ggGauges.flatMap(e=>{let n=e.column,r=n?ZW(w.rows,n,D):void 0;if(!r)return[];let i=1/0,a=-1/0,o=0,s=0,c=NaN;for(let e=0;e<r.length;e++){let t=r[e];t-t===0&&(t<i&&(i=t),t>a&&(a=t),o+=t,s++,c=t)}let l=s===0?NaN:e.value===`mean`?o/s:e.value===`min`?i:e.value===`max`?a:c,[u,d]=HZ(s?i:0,s?a:1,t(e.min),t(e.max));return[{name:n,unit:Ee[n]??``,value:l,min:u,max:d,alarm:e.alarm??null,color:e.color,style:e.style,fromZero:e.fill===`zero`,colorMode:e.colorMode,stops:e.stops,stat:e.value}]})}return e},[w,l,u,D,Ee])}}function HZ(e,t,n,r){t<=e&&(t=e+1);let i=Pz(t-e,5),a=n??Math.floor(e/i)*i,o=r??Math.ceil(t/i)*i;return o>a?[a,o]:[a,a+1]}var UZ=`#fb7185`,WZ=2500;function GZ(e){let t=[],n=(e,r)=>{if(typeof e==`string`){e&&(r===`column`||/(Col|Cols|Column|Columns)$/.test(r))&&t.push(e);return}if(Array.isArray(e)){for(let t of e)n(t,r);return}if(e&&typeof e==`object`)for(let[t,r]of Object.entries(e))t!==`addColumn`&&n(r,t)};return n(e,``),[...new Set(t)]}function KZ(e){let t=qZ(e);if(t.status!==`empty`||!e.data.dataset)return t;let n=new Set([...e.data.datasetWithChannels?.columnNames??[],...e.data.numericCols]);return GZ(e.settings).some(e=>!n.has(e))?{...t,status:`missing`}:t}function qZ(e){let{panel:t,data:r,settings:i}=e;if(t.kind===`camera`)return{status:`ready`,data:null,node:q(JX,{settings:i?.kind===`camera`?i:$n(),live:e.live??[],selection:e.selection??[],viewXRange:e.viewXRange,xIsTime:e.xKey===n,xKey:e.xKey,video:e.video,recordings:e.recordings,cursor:e.cursor,onContextMenu:t=>e.onContextMenu(t)})};if(!r.dataset)return{status:`no-data`,node:null,data:null};let a=`${e.background??`theme`}|${e.styleToken}`,o=t=>e.onContextMenu(t),s=(e,t)=>({status:`ready`,node:e,data:t}),c={status:`empty`,node:null,data:null},l=t.id;switch(t.kind){case`multiband`:{let t=r.multibandDataByPanel[l],n=t?.points??[],u=t?.effectiveSeries??[],d=i?.kind===`multiband`?i:null,p=[...new Set((d?.series??[]).map(e=>e.column).filter(t=>t!==e.xKey))],m=e.xKey===`ElapsedTime`&&!r.numericCols.includes(`Time`)?`Time`:e.xKey,h={xLabel:r.xUnit?`${m} (${r.xUnit})`:m,series:u,columnUnits:r.columnUnits,height:e.height,backgroundToken:a,viewXRange:e.viewXRange,onViewXRangeChange:e.onViewXRangeChange,onCursorX:e.onCursorX,liveZoom:e.liveZoom,liveZoomId:l,xAxisLine:d?.xAxisLine,yAxisLine:d?.yAxisLine,gridLine:d?.gridLine,lineWidth:d?.lineWidth,onPlotContextMenu:o,shiftMode:e.shiftMode},g=d?.beacon;if(g?.enabled&&e.beaconLive&&p.length>0){let t=FZ((d?.series??[]).filter(t=>t.column!==e.xKey),d?.layout??`overlay`),n=g.reference===`dataset`&&g.datasetId?e.findDataset(g.datasetId):void 0,r=bZ(g,!!n),i=r?[...mZ(t,r),...t]:t;return s(q(DW,{...h,series:i,points:[],showLatestValues:!0,liveSource:yZ(e.beaconLive,e.xKey,p,g,n),envelopes:n?xZ(n,e.xKey,t,r??void 0):void 0,liveZoomMode:`free`}),{series:i,points:[]})}if(r.anyDuckDb)return u.length===0?c:s(q(JW,{...h,layers:r.duckDbLayers,xKey:e.xKey,columns:p,maxPoints:WZ}),{series:u,columns:p});if(!n.some(e=>e.length>0)&&!r.liveOverlays||u.length===0||!p.some(e=>r.numericCols.includes(e)))return c;let _=r.liveConn,v=null,y=r.liveOverlays,b=!_&&y&&p.length>0?lZ(y,e.xKey,p,n,r.staticXRange):void 0,x=!!b&&n.length>0,S=b??(_&&p.length>0?{pull:(t,n,r,i,a)=>{let o=_.source.version();if(a){let i=2**Math.ceil(Math.log2((n-t)/8)),a=Math.floor(t/i)*i,s=Math.ceil(n/i)*i,c=Math.round(r*(s-a)/(n-t));return(!v||v.ver!==o||v.x0!==a||v.x1!==s||Math.abs(v.mp-c)>c*.25)&&(v={ver:o,x0:a,x1:s,mp:c,pts:_.source.getPointsSync(p,{xKey:e.xKey,x0:a,x1:s},c),held:lt(p,e=>_.source.lastKnownSync(e),a,s,_.source.latestTimeSync())}),v.held?[v.pts,v.held]:[v.pts]}(!v||v.ver!==o||v.x0!==t||v.x1!==n||v.mp!==r)&&(v={ver:o,x0:t,x1:n,mp:r,pts:_.source.getPointsSync(p,{xKey:e.xKey,x0:t,x1:n},r)});let s=f(v.pts,i);if(e.xKey!==`ElapsedTime`)return[s];let c=lt(p,e=>_.source.lastKnownSync(e),t,n,Math.min(_.source.latestTimeSync(),i??1/0));return c?[s,c]:[s]},cutOnGpu:e.xKey===`ElapsedTime`,id:_.id,latestT:()=>_.source.latestTimeSync(),timeAfter:e=>_.source.timeAfterSync(e),xAtTime:t=>_.source.xAtTimeSync(e.xKey,t),xBounds:()=>{let t=_.source.xBoundsSync(e.xKey);return t.x1>t.x0?[t.x0,t.x1]:null},latestX:()=>{let t=_.source.latestSync(e.xKey);return Number.isFinite(t)?t:null},version:()=>_.source.version(),latestValues:e=>_.source.latestValuesSync(e),...e.xKey===`ElapsedTime`?{}:{spanForSeconds:t=>_.source.xTravelSync(e.xKey,t),bufferedSeconds:()=>{let e=_.source.xBoundsSync(`ElapsedTime`);return e.x1-e.x0}}}:void 0);return s(q(DW,{...h,points:n,envelopes:t?.envelopes,showLatestValues:r.hasLiveSelected,fullXRange:r.staticXRange,liveSource:S,liveWindowSeconds:x?null:e.liveWindowSeconds,onLiveWindowChange:x?void 0:e.onLiveWindowChange,liveZoomMode:x?`free`:`follow`}),{series:u,points:n})}case`xyzmesh`:{let t=i?.kind===`xyzmesh`?i:En(4),n=r.xyzPointsByPanel[l];if(!n||n.points.length<1&&!n.surface)return c;let u=!!n.surface;return s(q(QK,{ref:e.xyzRef,points:n.points,surface:n.surface,xLabel:u?(t.xyzColumns??[]).includes(e.xKey)?`Row`:e.xKey:t.xyzXCol,yLabel:u?`Column`:t.xyzYCol,zLabel:u?`Value`:t.xyzZCol,height:e.height,backgroundToken:a,xRange:bn(t.xyzXScale.scaleMin,t.xyzXScale.scaleMax),yRange:bn(t.xyzYScale.scaleMin,t.xyzYScale.scaleMax),zRange:bn(t.xyzZScale.scaleMin,t.xyzZScale.scaleMax),viewMode:t.xyzViewMode,pointRadius:t.xyzPointRadius,showMesh:t.showMesh,meshStyle:t.meshStyle,meshOpacity:t.meshOpacity,alarms:[...t.xyzXScale.alarm?[{axis:`x`,...t.xyzXScale.alarm}]:[],...t.xyzYScale.alarm?[{axis:`y`,...t.xyzYScale.alarm}]:[],...t.xyzZScale.alarm?[{axis:`z`,...t.xyzZScale.alarm}]:[]],onPlotContextMenu:o}),n.surface??n.points)}case`xyscatter`:{let t=i?.kind===`xyscatter`?i:Tn(UZ),n=r.xyPointsByPanel.pts[l]??[];if(n.length===0)return c;let u=r.xyPointsByPanel.colorMeta[l];return s(q(BG,{points:n,xLabel:t.xyXCol,yLabel:t.xyYCol,color:t.xyColor,datasetColors:r.xyPointsByPanel.datasetColors[l],colorLabel:u?.label,colorRange:u?[u.min,u.max]:void 0,pointRadius:t.xyPointRadius,drawMode:t.xyDrawMode,lineWidth:t.xyLineWidth,height:e.height,backgroundToken:a,xAxisLine:t.xyXAxisLine,yAxisLine:t.xyYAxisLine,gridLine:t.xyGridLine,fitSettings:t.xyFit,xScale:t.xyXScale,yScale:t.xyYScale,onPlotContextMenu:o}),n)}case`histogram`:{if(i?.kind!==`histogram`)return c;let t=r.histogramDataByPanel[l]??[];return t.length===0?c:s(q(aq,{values:t,label:i.histColumn,bins:i.histBins,color:i.histColor,showNormal:i.histNormal,logY:i.histLogY,height:e.height,backgroundToken:a,onPlotContextMenu:o}),t)}case`polar`:{if(i?.kind!==`polar`)return c;let t=r.polarDataByPanel[l]??{angles:[],radii:[]};if(t.angles.length===0)return c;let n=parseFloat(i.polarRadiusMin),u=parseFloat(i.polarRadiusMax);return s(q(Cq,{angles:t.angles,radii:t.radii,angleLabel:i.polarAngleCol,radiusLabel:i.polarRadiusCol,color:i.polarColor,mode:i.polarMode,radiusMin:Number.isFinite(n)?n:void 0,radiusMax:Number.isFinite(u)?u:void 0,height:e.height,backgroundToken:a,onPlotContextMenu:o}),t)}case`spectrum`:{if(i?.kind!==`spectrum`)return c;let{signal:t,rate:n}=r.spectrumDataByPanel[l]??{signal:[],rate:1};return t.length<4?c:s(q(zq,{signal:t,sampleRate:n,label:i.specSignalCol,xMode:i.specXMode,yMode:i.specYMode,window:i.specWindow,color:i.specColor,logX:i.specLogX,height:e.height,backgroundToken:a,onPlotContextMenu:o}),t)}case`boxplot`:{if(i?.kind!==`boxplot`)return c;let t=r.boxplotDataByPanel[l]??[];return t.length===0?c:s(q(Gq,{groups:t,color:i.boxColor,whiskers:i.boxWhiskers,height:e.height,backgroundToken:a,onPlotContextMenu:o}),t)}case`spectrogram`:{if(i?.kind!==`spectrogram`)return c;let{signal:e,rate:t}=r.spectrogramDataByPanel[l]??{signal:[],rate:1};return e.length<i.sgWindowSize?c:i.sgView===`waterfall`?s(q(lJ,{signal:e,sampleRate:t,windowSize:i.sgWindowSize,overlap:i.sgOverlap,winFunc:i.sgWinFunc,yMode:i.sgYMode,backgroundToken:a,onPlotContextMenu:o}),e):s(q(iJ,{signal:e,sampleRate:t,windowSize:i.sgWindowSize,overlap:i.sgOverlap,winFunc:i.sgWinFunc,yMode:i.sgYMode,logFreq:i.sgLogFreq,backgroundToken:a,onPlotContextMenu:o}),e)}case`heatmap`:{if(i?.kind!==`heatmap`)return c;let e=r.heatmapDataByPanel[l]??{cells:[],xLabels:[],yLabels:[]};if(e.cells.length===0&&!(e.grid&&e.grid.w*e.grid.h>0))return c;let t=e=>e!==void 0&&e.trim()!==``&&Number.isFinite(Number(e))?Number(e):void 0;return s(q(OJ,{cells:e.cells,xLabels:e.xLabels,yLabels:e.yLabels,grid:e.grid,showValues:i.hmShowValues,colorScheme:i.hmColorScheme,xCentres:e.xCentres,yCentres:e.yCentres,contours:i.hmContours??0,vMin:t(i.hmRange?.scaleMin),vMax:t(i.hmRange?.scaleMax),backgroundToken:a,onPlotContextMenu:o}),e)}case`violin`:{if(i?.kind!==`violin`)return c;let e=r.violinDataByPanel[l]??[];return e.some(e=>e.values.length>0)?s(q(IJ,{groups:e,color:i.vlColor,showBox:i.vlShowBox,bandwidth:parseFloat(i.vlBandwidth)||void 0,orientation:i.vlOrientation,backgroundToken:a,onPlotContextMenu:o}),e):c}case`confusion`:{if(i?.kind!==`confusion`)return c;let e=r.confusionDataByPanel[l]??{actual:[],predicted:[]};return e.actual.length===0?c:s(q(UJ,{actual:e.actual,predicted:e.predicted,normalize:i.cfNormalize,backgroundToken:a,onPlotContextMenu:o}),e)}case`roc`:{if(i?.kind!==`roc`)return c;let e=r.rocDataByPanel[l]??{scores:[],labels:[]};return e.scores.length===0?c:s(q(YJ,{scores:e.scores,labels:e.labels,mode:i.rocMode,color:i.rocColor,backgroundToken:a,onPlotContextMenu:o}),e)}case`losscurve`:{if(i?.kind!==`losscurve`)return c;let e=r.lossCurveDataByPanel[l]??{xValues:[],series:[]};return e.series.length===0?c:s(q(ZJ,{xValues:e.xValues,series:e.series,xLabel:i.lcXCol||`Step`,backgroundToken:a,onPlotContextMenu:o}),e)}case`controlchart`:{if(i?.kind!==`controlchart`)return c;let e=r.controlChartDataByPanel[l];return!e||e.length<2?c:s(q(rY,{points:e,sigmaLevel:i.ccSigmaLevel,color:i.ccColor,backgroundToken:a,onPlotContextMenu:o}),e)}case`parallelcoords`:{if(i?.kind!==`parallelcoords`)return c;let e=r.parallelCoordsDataByPanel[l];if(!e||e.length===0||i.pcColumns.length<2)return c;let t=i.pcColorByCol?r.numericCols.includes(i.pcColorByCol):!1;return s(q(lY,{rows:e,axes:i.pcColumns,color:i.pcColor,colorByNumeric:t,backgroundToken:a,onPlotContextMenu:o}),e)}case`embedding`:{if(i?.kind!==`embedding`)return c;let e=r.embeddingDataByPanel[l];return!e||e.length===0?c:s(q(yY,{points:e,color:i.emColor,colorByNumeric:i.emColorMode===`numeric`&&!!i.emColorCol,pointSize:i.emPointSize,backgroundToken:a,onPlotContextMenu:o}),e)}case`flamegraph`:{if(i?.kind!==`flamegraph`)return c;let e=r.flameGraphDataByPanel[l]??[];return e.length===0?c:s(q(DY,{nodes:e,direction:i.fgDirection,backgroundToken:a,onPlotContextMenu:o}),e)}case`barchart`:{if(i?.kind!==`barchart`)return c;let e=r.barChartDataByPanel[l]??{groups:[],seriesNames:[]};if(e.groups.length===0&&!e.columns?.length)return c;let t=e=>e!==void 0&&e.trim()!==``&&Number.isFinite(Number(e))?Number(e):void 0,n=i.bcValueScale?{min:t(i.bcValueScale.scaleMin),max:t(i.bcValueScale.scaleMax)}:void 0;return s(q(NY,{groups:e.columns?void 0:e.groups,columns:e.columns,seriesNames:e.seriesNames,mode:i.bcMode,horizontal:i.bcHorizontal,valueRange:n,backgroundToken:a,onPlotContextMenu:o}),e)}case`radar`:{if(i?.kind!==`radar`)return c;let e=r.radarDataByPanel[l]??{axes:[],series:[]};return e.axes.length<3?c:s(q(LY,{axes:e.axes,series:e.series,fill:i.rdFill,color:i.rdColor,backgroundToken:a,onPlotContextMenu:o}),e)}case`areachart`:{if(i?.kind!==`areachart`)return c;let e=r.areaChartDataByPanel[l]??[];if(e.length===0)return c;let t=e=>e!==void 0&&e.trim()!==``&&Number.isFinite(Number(e))?Number(e):void 0,n=i.acYScale?{min:t(i.acYScale.scaleMin),max:t(i.acYScale.scaleMax)}:void 0;return s(q(VY,{series:e,stacked:i.acStacked,yRange:n,backgroundToken:a,onPlotContextMenu:o}),e)}case`cdfchart`:{if(i?.kind!==`cdfchart`)return c;let e=r.cdfChartDataByPanel[l]??[];return e.length===0?c:s(q(WY,{series:e,complement:i.cdComplement,logX:i.cdLogX,backgroundToken:a,onPlotContextMenu:o}),e)}case`bubblechart`:{if(i?.kind!==`bubblechart`)return c;let e=r.bubbleChartDataByPanel[l];return!e||e.length===0?c:s(q(QY,{points:e,color:i.bbColor,colorByNumeric:i.bbColorMode===`numeric`,maxRadius:i.bbMaxRadius,backgroundToken:a,onPlotContextMenu:o}),e)}case`treemap`:{let e=r.treemapDataByPanel[l]??[];return e.length===0?c:s(q(rX,{nodes:e,backgroundToken:a,onPlotContextMenu:o}),e)}case`sankey`:{let e=r.sankeyDataByPanel[l]??{nodeNames:[],links:[]};return e.links.length===0?c:s(q(lX,{nodeNames:e.nodeNames,links:e.links,backgroundToken:a,onPlotContextMenu:o}),e)}case`calibration`:{if(i?.kind!==`calibration`)return c;let e=r.calibrationDataByPanel[l]??[];return e.length===0?c:s(q(dX,{bins:e,color:i.cbColor,backgroundToken:a,onPlotContextMenu:o}),e)}case`qqplot`:{if(i?.kind!==`qqplot`)return c;let e=r.qqPlotDataByPanel[l];return!e||e.length===0?c:s(q(pX,{points:e,color:i.qqColor,backgroundToken:a,onPlotContextMenu:o}),e)}case`gauge`:{if(i?.kind!==`gauge`)return c;let e=r.gaugeDataByPanel[l]??[];if(e.length===0)return c;let t=r.liveConn??(r.liveOverlays?.length===1?r.liveOverlays[0].conn:void 0);return s(q(OX,{gauges:e,live:t?{latestT:()=>t.source.latestTimeSync(),timeAfter:e=>t.source.timeAfterSync(e),valueAt:(e,n)=>t.source.xAtTimeSync(e,n,!0)}:void 0,backgroundToken:a,onPlotContextMenu:o}),e)}case`gantt`:{let e=r.ganttDataByPanel[l]??[];return e.length===0?c:s(q(vX,{tasks:e,backgroundToken:a,onPlotContextMenu:o}),e)}}return c}var JZ=500,YZ=1e3;function XZ(e){if(Array.isArray(e))return ZZ(e);if(!e||typeof e!=`object`)return null;let t=-1;for(let n of Object.values(e))Array.isArray(n)&&(t=Math.max(t,ZZ(n)));return t<0?null:t}function ZZ(e){let t=e=>!!e&&typeof e==`object`&&e.x instanceof Float64Array;return e.length>0&&t(e[0])?e.reduce((e,n)=>e+(t(n)?n.length:0),0):e.length}function QZ(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${Math.round(e/1e3)}k`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function $Z({stats:e,host:t}){let[n,r]=Ct(null);if(W(()=>{let n=t.current?.ownerDocument.defaultView??window,i=0,a=0,o=0,s=-1,c=-1,l=e.renders,u=t.current?VH(t.current):0,d=f=>{c>=0&&f-s>YZ&&(c=f,s=f,a=0,o=0,l=e.renders,u=t.current?VH(t.current):0),c<0?(c=f,s=f):f!==s&&(o=Math.max(o,f-s),s=f,a++);let p=f-c;if(p>=JZ){let i=t.current,s=0;if(i)for(let e of i.getElementsByTagName(`canvas`))s+=e.width*e.height;let d=n.performance.memory,m=i?VH(i):0;r({fps:a*1e3/p,repaints:(m-u)*1e3/p,worstFrameMs:o,renderMs:e.lastRenderMs,rendersPerSec:(e.renders-l)*1e3/p,points:XZ(e.data),domNodes:i?i.getElementsByTagName(`*`).length:0,canvasMp:s/1e6,heapMb:d?d.usedJSHeapSize/1048576:null,live:(()=>{let e=fU();return e?{age:Date.now()/1e3-e.newest,lag:e.lag,wait:e.wait,waitAge:e.waitAge}:null})()}),a=0,o=0,c=f,l=e.renders,u=m}i=n.requestAnimationFrame(d)};return i=n.requestAnimationFrame(d),()=>n.cancelAnimationFrame(i)},[e,t]),!n)return null;let i=n.fps<20?`var(--danger, #e5484d)`:n.fps<45?`var(--accent, #f5a524)`:void 0;return q(`dl`,{className:`kymo-perf-hud`,style:eQ,children:[[`FPS`,n.fps.toFixed(0),i],[`Repaints/s`,n.repaints.toFixed(0)],[`Slowest frame`,`${n.worstFrameMs.toFixed(1)} ms`],[`Render`,`${n.renderMs.toFixed(1)} ms`],[`Renders/s`,n.rendersPerSec.toFixed(1)],...n.points===null?[]:[[`Points`,QZ(n.points)]],[`DOM nodes`,QZ(n.domNodes)],[`Canvas`,`${n.canvasMp.toFixed(2)} MP`],...n.heapMb===null?[]:[[`JS heap`,`${n.heapMb.toFixed(0)} MB`]],...n.live?[[`Data age`,`${n.live.age.toFixed(2)} s`],[`Live lag`,`${n.live.lag.toFixed(2)} s`],[`Late by`,`${n.live.wait.toFixed(2)} s · ${n.live.waitAge.toFixed(0)} s ago`]]:[]].map(([e,t,n])=>Ot(`div`,{style:tQ,children:[q(`dt`,{style:nQ,children:e}),q(`dd`,{style:n?{...rQ,color:n}:rQ,children:t})]},e))})}var eQ={position:`absolute`,top:8,right:8,zIndex:60,flex:`none`,pointerEvents:`none`,userSelect:`none`,margin:0,padding:`6px 9px`,minWidth:148,display:`grid`,gap:1,font:`500 10.5px/1.35 var(--font-sans, system-ui)`,fontVariantNumeric:`tabular-nums`,fontFeatureSettings:`"tnum" 1`,color:`var(--text-strong, #f3f5fa)`,background:`color-mix(in oklch, var(--bg-elevated, #1b2130) 86%, transparent)`,border:`1px solid var(--border, #33405a)`,borderRadius:6,boxShadow:`0 4px 14px color-mix(in oklch, black 28%, transparent)`},tQ={display:`flex`,justifyContent:`space-between`,gap:12},nQ={color:`var(--text-muted, #8a93a6)`},rQ={margin:0,fontWeight:600,textAlign:`right`},iQ=[],aQ=3,oQ=`data-kymo-annotation-controls`;function sQ(e,t,n,r){return e.anchor===`x`&&!r?null:e.points.map(([i,a])=>[e.anchor===`x`?OU(r,i):i*t,a*n])}function cQ(e,t,n,r,i){return t.map(([t,a])=>[e.anchor===`x`&&i?kU(i,t):lQ(t/Math.max(1,n)),lQ(a/Math.max(1,r))])}var lQ=e=>Math.round(e*1e4)/1e4,uQ=_t(function({annotations:e,tool:t,plotFrame:n,onChange:r,onToolEnd:i,onSelect:a,marks:o=iQ,onMarkSelect:s}){let c=K(null),l=wt(n.subscribe,n.get),u=l?.x?l:null,[d,f]=Ct({w:0,h:0}),[p,m]=Ct(null),[h,g]=Ct(null),[_,v]=Ct(null),y=K({annotations:e,onChange:r,onToolEnd:i,onSelect:a,tool:t,selected:p,editing:h,frame:u,size:d});y.current={annotations:e,onChange:r,onToolEnd:i,onSelect:a,tool:t,selected:p,editing:h,frame:u,size:d};let b=e=>{y.current.selected!==e&&(y.current.selected=e,m(e),y.current.onSelect(e))};G(()=>{let e=c.current;if(!e)return;let t=e.ownerDocument.defaultView??window,n=()=>f({w:e.clientWidth,h:e.clientHeight});n();let r=new t.ResizeObserver(n);return r.observe(e),()=>r.disconnect()},[]),W(()=>{t&&b(null)}),W(()=>{p&&!e.some(e=>e.id===p)&&b(null)}),W(()=>()=>{y.current.selected&&y.current.onSelect(null)},[]),W(()=>{let e=c.current?.ownerDocument;if(!e)return;let t=e=>{let{selected:t,editing:n,tool:r,annotations:i,onChange:a,onToolEnd:o}=y.current;if(!(n||yQ(e.target))){if(e.key===`Escape`&&r){o();return}t&&(e.key===`Delete`||e.key===`Backspace`?(e.preventDefault(),a(i.filter(e=>e.id!==t)),b(null)):e.key===`Escape`&&b(null))}},n=e=>{let t=y.current.selected,n=e.target;t&&!n?.closest?.(`[data-ann-id="${CSS.escape(t)}"], [data-kymo-annotation-controls]`)&&b(null)};return e.addEventListener(`keydown`,t),e.addEventListener(`pointerdown`,n,!0),()=>{e.removeEventListener(`keydown`,t),e.removeEventListener(`pointerdown`,n,!0)}},[]);let{w:x,h:S}=d,C=e=>{let t=c.current.getBoundingClientRect();return[e.clientX-t.left,e.clientY-t.top]},w=(e,t)=>{let n=c.current.ownerDocument,r=t=>e(C(t),t),i=()=>{n.removeEventListener(`pointermove`,r),n.removeEventListener(`pointerup`,i),n.removeEventListener(`pointercancel`,i),t()};n.addEventListener(`pointermove`,r),n.addEventListener(`pointerup`,i),n.addEventListener(`pointercancel`,i)},T=e=>r([...y.current.annotations,e]),E=e=>r(y.current.annotations.map(t=>t.id===e.id?e:t)),D=e=>{if(!t||e.button!==0||h)return;e.preventDefault(),e.stopPropagation();let n=C(e),r={id:crypto.randomUUID(),kind:t.kind,color:t.color,width:t.width,...u?{anchor:`x`}:{}},i=e=>cQ(r,e,x,S,u);if(t.kind===`text`){v({...r,points:i([n]),text:``}),g(r.id);return}let a=t.kind===`brush`?[n]:[n,n],o={...r,points:i(a)};v(o);let s=!1;w((t,n)=>{if(s||=Math.hypot(n.clientX-e.clientX,n.clientY-e.clientY)>aQ,r.kind===`brush`){let e=a[a.length-1];if(Math.hypot(t[0]-e[0],t[1]-e[1])<2)return;a=[...a,t]}else a=[a[0],t];o={...o,points:i(a)},v(o)},()=>{v(null),s&&o.points.length>=2&&T(o)})},O=(e,t,n)=>{let r=sQ(t,x,S,u);if(!r)return;let i=C(e),a=null;w((o,s)=>{if(!a&&Math.hypot(s.clientX-e.clientX,s.clientY-e.clientY)<=aQ)return;let{size:c,frame:l}=y.current;a={...t,points:cQ(t,n(r,[o[0]-i[0],o[1]-i[1]],o),c.w,c.h,l)},v(a)},()=>{v(null),a&&E(a)})},k=(e,n)=>{t||e.button!==0||h===n.id||(e.preventDefault(),e.stopPropagation(),b(n.id),O(e,n,(e,[t,n])=>e.map(([e,r])=>[e+t,r+n])))},A=(e,t,n)=>{e.button===0&&(e.preventDefault(),e.stopPropagation(),O(e,t,(e,r,i)=>{let a=e.map(e=>[...e]);return t.kind===`arrow`?a[n]=i:(a[+(n===1||n===2)][0]=i[0],a[+(n===2||n===3)][1]=i[1]),a}))},j=e=>{t||e.kind!==`text`&&e.kind!==`box`||(b(e.id),g(e.id))},M=e=>{let t=h;g(null);let n=_&&_.id===t?_:null;if(v(null),e===null||!t)return;let i=e.replace(/\s+$/,``),a=y.current.annotations;if(n){i&&T({...n,text:i});return}let o=a.find(e=>e.id===t);o&&(!i&&o.kind===`text`?r(a.filter(e=>e.id!==t)):E(vQ(o,i)))},N=e=>{r(y.current.annotations.filter(t=>t.id!==e)),b(null)},P=(_?e.some(e=>e.id===_.id)?e.map(e=>e.id===_.id?_:e):[...e,_]:e).flatMap(e=>{let t=sQ(e,x,S,u);return t?[{a:e,px:t}]:[]}),F=p?P.find(e=>e.a.id===p):void 0,I=u?o.map(e=>{let t=sQ(Jt(e,u.x.v1),x,S,u);return{m:e,x0:Math.min(t[0][0],t[1][0]),x1:Math.max(t[0][0],t[1][0])}}):[],L=F&&F.a.kind!==`text`?_Q(F.px):null,R=e=>Ot(Dt,{children:[q(`svg`,{className:`kymo-ann-svg`,width:x,height:S,viewBox:`0 0 ${x} ${S}`,"aria-hidden":`true`,children:e.map(({a:e,px:t})=>e.kind===`text`?null:q(`g`,{"data-ann-id":e.id,className:`kymo-ann kymo-ann--${e.kind}`,onPointerDown:t=>k(t,e),onDoubleClick:()=>j(e),children:q(pQ,{a:e,px:t})},e.id))}),e.map(({a:e,px:t})=>{if(e.kind!==`text`&&e.kind!==`box`)return null;let n=h===e.id;if(!n&&!e.text)return null;let r=e.kind===`text`?{left:t[0][0],top:t[0][1]}:{left:Math.min(t[0][0],t[1][0]),top:Math.min(t[0][1],t[1][1]),transform:`translateY(calc(-100% - 3px))`};return Ot(`div`,{"data-ann-id":e.id,className:`kymo-ann-text kymo-ann-text--${e.kind}${p===e.id&&e.kind===`text`?` is-selected`:``}`,style:{...r,color:e.color,fontSize:e.kind===`text`?e.width:12},onPointerDown:t=>k(t,e),onDoubleClick:()=>j(e),children:[n?q(fQ,{initial:e.text??``,onDone:M}):e.text,p===e.id&&e.kind===`text`&&!n?q(dQ,{onDelete:()=>N(e.id),style:{right:-11,top:-11}}):null]},`t-${e.id}`)})]});return q(`div`,{ref:c,className:`kymo-annotations${t?` is-drawing is-tool-${t.kind}`:``}`,onPointerDown:D,onContextMenu:t?e=>e.preventDefault():void 0,children:x>0&&S>0?Ot(Dt,{children:[u&&I.length?q(`div`,{className:`kymo-ann-clip`,style:{clipPath:`inset(0 ${Math.max(0,x-u.left-u.width)}px 0 ${Math.max(0,u.left)}px)`},children:q(`svg`,{className:`kymo-ann-svg kymo-marks`,width:x,height:S,viewBox:`0 0 ${x} ${S}`,children:I.map(({m:e,x0:t,x1:n})=>Ot(`g`,{"data-mark":e.ruleId,role:`img`,"aria-label":`${e.ruleName}, ${e.severity}`,className:`kymo-mark kymo-mark--${e.severity}`,style:{color:qt[e.severity]},children:[q(`rect`,{x:t,y:u.top,width:Math.max(1,n-t),height:u.height,fill:`currentColor`,fillOpacity:.12}),q(`rect`,{x:t,y:u.top,width:Math.max(1,n-t),height:2,fill:`currentColor`}),q(`rect`,{className:`kymo-mark-hit`,x:t,y:u.top,width:Math.max(6,n-t),height:8,onPointerDown:t=>{t.stopPropagation(),s?.(e.ruleId)}})]},e.id))})}):null,R(P.filter(e=>e.a.anchor!==`x`)),u?q(`div`,{className:`kymo-ann-clip`,style:{clipPath:`inset(0 ${Math.max(0,x-u.left-u.width)}px 0 ${Math.max(0,u.left)}px)`},children:R(P.filter(e=>e.a.anchor===`x`))}):null,Ot(`svg`,{className:`kymo-ann-svg`,width:x,height:S,viewBox:`0 0 ${x} ${S}`,"aria-hidden":`true`,children:[L?q(`rect`,{className:`kymo-ann-selection`,x:L.x-6,y:L.y-6,width:L.w+12,height:L.h+12,rx:4}):null,F&&!h&&(F.a.kind===`box`||F.a.kind===`arrow`)?q(`g`,{"data-ann-id":F.a.id,children:mQ(F.a,F.px).map(([e,t],n)=>q(`rect`,{className:`kymo-ann-handle kymo-ann-handle--${F.a.kind===`arrow`?`end`:n%2?`nesw`:`nwse`}`,x:e-4.5,y:t-4.5,width:9,height:9,rx:2,onPointerDown:e=>A(e,F.a,n)},n))}):null]}),L&&!h?q(dQ,{onDelete:()=>N(F.a.id),id:F.a.id,style:{left:Math.min(x-12,L.x+L.w+6)-10,top:Math.max(10,L.y-6)-10}}):null]}):null})});function dQ({onDelete:e,style:t,id:n}){return q(`button`,{type:`button`,className:`kymo-ann-delete`,style:t,"data-ann-id":n,"aria-label":`Delete annotation`,title:`Delete (Del)`,onPointerDown:e=>e.stopPropagation(),onClick:e,children:q(`svg`,{viewBox:`0 0 10 10`,width:`8`,height:`8`,"aria-hidden":`true`,children:q(`path`,{d:`M2 2l6 6M8 2l-6 6`})})})}function fQ({initial:e,onDone:t}){let n=K(null),r=K(!1),i=e=>{r.current||(r.current=!0,t(e))};return G(()=>{let t=n.current;if(!t)return;t.textContent=e,t.focus();let r=t.ownerDocument.createRange();r.selectNodeContents(t);let i=t.ownerDocument.defaultView?.getSelection();i?.removeAllRanges(),i?.addRange(r)},[]),q(`div`,{ref:n,className:`kymo-ann-editor`,contentEditable:`plaintext-only`,suppressContentEditableWarning:!0,role:`textbox`,"aria-label":`Annotation text`,"aria-multiline":`true`,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),e.key===`Enter`&&!e.shiftKey?(e.preventDefault(),i(n.current?.innerText??``)):e.key===`Escape`&&(e.preventDefault(),i(null))},onBlur:()=>i(n.current?.innerText??``)})}function pQ({a:e,px:t}){let n={stroke:e.color,strokeWidth:e.width,fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`},r=t=>q(`path`,{className:`kymo-ann-hit`,d:t,strokeWidth:Math.max(12,e.width+10)});switch(e.kind){case`box`:{let[[i,a],[o,s]]=t,c=`M${i} ${a}H${o}V${s}H${i}Z`;return Ot(Dt,{children:[r(c),q(`path`,{d:c,...n}),q(`path`,{d:c,fill:e.color,fillOpacity:.06,stroke:`none`,pointerEvents:`none`})]})}case`arrow`:{let[[i,a],[o,s]]=t,c=gQ(i,a,o,s,e.width);return Ot(Dt,{children:[r(`M${i} ${a}L${o} ${s}`),q(`path`,{d:`M${i} ${a}L${c.base[0]} ${c.base[1]}`,...n}),q(`path`,{d:c.d,fill:e.color,stroke:e.color,strokeWidth:1,strokeLinejoin:`round`})]})}case`brush`:{let e=hQ(t);return Ot(Dt,{children:[r(e),q(`path`,{d:e,...n})]})}}return null}function mQ(e,t){if(e.kind===`arrow`)return t;let[[n,r],[i,a]]=t;return[[n,r],[i,r],[i,a],[n,a]]}function hQ(e){if(e.length===0)return``;if(e.length<3)return`M${e[0][0]} ${e[0][1]}`+e.slice(1).map(([e,t])=>`L${e} ${t}`).join(``);let t=`M${e[0][0]} ${e[0][1]}`;for(let n=1;n<e.length-1;n++){let[r,i]=e[n],[a,o]=e[n+1];t+=`Q${r} ${i} ${(r+a)/2} ${(i+o)/2}`}let[n,r]=e[e.length-1];return t+`L${n} ${r}`}function gQ(e,t,n,r,i){let a=Math.max(9,i*4),o=Math.atan2(r-t,n-e),s=.42,c=[n-a*Math.cos(o-s),r-a*Math.sin(o-s)],l=[n-a*Math.cos(o+s),r-a*Math.sin(o+s)],u=[n-a*.8*Math.cos(o),r-a*.8*Math.sin(o)];return{d:`M${n} ${r}L${c[0]} ${c[1]}L${l[0]} ${l[1]}Z`,base:u,l:c,r:l}}function _Q(e){let t=e.map(e=>e[0]),n=e.map(e=>e[1]),r=Math.min(...t),i=Math.min(...n);return{x:r,y:i,w:Math.max(...t)-r,h:Math.max(...n)-i}}function vQ(e,t){if(t)return{...e,text:t};let{text:n,...r}=e;return r}function yQ(e){let t=e;return!!t&&(t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))}function bQ(e,t,n,r,i,a,o){e.save(),e.scale(i,i),e.lineCap=`round`,e.lineJoin=`round`;for(let i of t){let t=sQ(i,n,r,o);t&&(e.save(),i.anchor===`x`&&o&&(e.beginPath(),e.rect(o.left,0,o.width,r),e.clip()),xQ(e,i,t,a),e.restore())}e.restore()}function xQ(e,t,n,r){if(e.strokeStyle=t.color,e.fillStyle=t.color,e.lineWidth=t.width,t.kind===`box`)e.strokeRect(n[0][0],n[0][1],n[1][0]-n[0][0],n[1][1]-n[0][1]);else if(t.kind===`brush`)e.stroke(new Path2D(hQ(n)));else if(t.kind===`arrow`){let r=gQ(n[0][0],n[0][1],n[1][0],n[1][1],t.width);e.beginPath(),e.moveTo(n[0][0],n[0][1]),e.lineTo(r.base[0],r.base[1]),e.stroke(),e.beginPath(),e.moveTo(n[1][0],n[1][1]),e.lineTo(r.l[0],r.l[1]),e.lineTo(r.r[0],r.r[1]),e.closePath(),e.fill()}if(!t.text)return;let i=t.kind===`text`?t.width:12;e.font=`600 ${i}px ${r}`,e.textBaseline=`top`;let a=t.text.split(`
|
|
614
|
-
`),o=i*1.25,s=n[0][0],c=n[0][1];t.kind===`box`&&(s=Math.min(n[0][0],n[1][0]),c=Math.min(n[0][1],n[1][1])-a.length*o-7),a.forEach((t,n)=>e.fillText(t,s+6,c+2+n*o))}var SQ={solid:void 0,dashed:`5 4`,dotted:`1 4`};function CQ(e,t,n){if(!e||!(n===`x`?e.x:e.y))return null;if(n===`x`){let n=OU(e,t.value);return n>=e.left-.5&&n<=e.left+e.width+.5?[n,e.top,n,e.top+e.height]:null}let r=AU(e,t.value);return r>=e.top-.5&&r<=e.top+e.height+.5?[e.left,r,e.left+e.width,r]:null}var wQ=_t(function({frame:e,alarm:t,axis:n}){let r=CQ(wt(e.subscribe,e.get),t,n);if(!r)return null;let i=t.linked?TQ(r,n):null;return Ot(`svg`,{className:`kymo-alarm`,"aria-hidden":`true`,children:[q(`line`,{x1:r[0],y1:r[1],x2:r[2],y2:r[3],stroke:t.color,strokeWidth:t.width,strokeDasharray:t.linked===`active`?LU.join(` `):SQ[t.style]}),i?q(`path`,{"data-alert-glyph":``,d:IU,transform:`translate(${i[0]} ${i[1]})`,fill:t.color}):null]})});function TQ(e,t){return t===`y`?[e[2]-10-3,e[1]-10-2]:[e[0]+3,e[1]+2]}function EQ(e,t,n,r,i){let a=CQ(t,n,r);if(a){if(e.save(),e.scale(i,i),e.strokeStyle=n.color,e.lineWidth=n.width,e.setLineDash(n.linked===`active`?LU:SQ[n.style]?.split(` `).map(Number)??[]),e.beginPath(),e.moveTo(a[0],a[1]),e.lineTo(a[2],a[3]),e.stroke(),n.linked){let t=TQ(a,r);zU(e,t[0],t[1],n.color)}e.restore()}}function DQ(e,t,n){return e.handlers?.wsId===n?e.handlers:e.handlers={wsId:n,onViewXRangeChange:r=>{t.view.setXRange(r,n),e.emitter.emit(`viewchange`,r)},onCursorX:e=>{try{t.view.setCursorX(e,n)}catch{}},cursor:{get:()=>{try{return t.view.cursorX(n)}catch{return null}},subscribe:e=>t.on(`cursorchange`,t=>{t.worksheetId===n&&e(t.x)})},onContextMenu:t=>e.emitter.emit(`contextmenu`,t),xyzRef:t=>{e.xyz=t},onAnnotations:n=>t.charts.setAnnotations(e.chartId,n),onAnnotationToolEnd:()=>{e.annotationTool=null,MQ(t).bump(),e.emitter.emit(`annotationtool`,null)},onAnnotationSelect:t=>{e.selectedAnnotation=t,e.emitter.emit(`annotationselect`,t)},onMarkSelect:t=>e.emitter.emit(`markselect`,t)}}var OQ=new WeakMap;function kQ(e,t){let n=OQ.get(e);n||OQ.set(e,n=new Map);let r=n.get(t);return r||n.set(t,r=n=>e.view.setLiveWindow(n,t)),r}var AQ=class{mounts=new Map;version=0;listeners=new Set;root=null;engine;constructor(e){this.engine=e}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getVersion=()=>this.version;bump(){this.version++;for(let e of[...this.listeners])e()}add(e){this.mounts.set(e.key,e),this.root||(this.root=Et(document.createElement(`div`)),this.root.render(q(RQ,{engine:this.engine,registry:this}))),this.bump()}remove(e){this.mounts.delete(e)&&this.bump()}refresh(){this.bump()}dispose(){this.mounts.clear(),this.root?.unmount(),this.root=null}},jQ=new WeakMap;function MQ(e){let t=jQ.get(e);return t||(t=new AQ(e),jQ.set(e,t)),t}function NQ(e,t,n,r={}){e.charts.get(t);let i=MQ(e),a={key:crypto.randomUUID(),chartId:t,element:n,options:r,shiftDatasetId:null,emitter:KV(),xyz:null,annotationTool:null,selectedAnnotation:null,plotFrame:NU(),status:null,data:null};i.add(a);let o=!1;return{chartId:t,status:()=>a.status,data:()=>a.data,on:(e,t)=>a.emitter.on(e,t),exportPng(){let r=Array.from(n.querySelectorAll(`canvas`));if(r.length===0)return Promise.reject(new HE(`export_failed`,{reason:`nothing to export`}));let i=document.createElement(`canvas`);i.width=r[0].width,i.height=r[0].height;let o=i.getContext(`2d`);if(!o)return Promise.reject(new HE(`export_failed`,{reason:`canvas unavailable`}));for(let e of r)o.drawImage(e,0,0);let s=e.charts.get(t),c=JQ(s.settings,Z1(e).alertLines()),l=a.plotFrame.get()?.x?a.plotFrame.get():null,u=e.getState(),d=u.worksheets.find(e=>e.charts.some(e=>e.id===t)),f=ZQ(s.annotations,d?YQ(u.marks,u.selection,d.xKey):[],l),p=fr(c);return p&&n.clientWidth>0&&EQ(o,a.plotFrame.get(),p.alarm,p.axis,i.width/n.clientWidth),f.length&&n.clientWidth>0&&bQ(o,f,n.clientWidth,n.clientHeight,i.width/n.clientWidth,Q.sans,l),new Promise((e,t)=>i.toBlob(n=>n?e(n):t(new HE(`export_failed`,{reason:`encode failed`})),`image/png`))},autoscale(){a.xyz?.autoscale()},setShiftMode(e){a.shiftDatasetId!==e&&(a.shiftDatasetId=e,i.bump())},setAnnotationTool(e){a.annotationTool=e?{...e}:null,i.bump()},annotationTool:()=>a.annotationTool,selectedAnnotation:()=>a.selectedAnnotation,setOptions(e){a.options={...e},i.bump()},destroy(){o||(o=!0,a.emitter.clear(),i.remove(a.key))}}}function PQ(e){jQ.get(e)?.refresh()}function FQ(e){jQ.get(e)?.dispose(),jQ.delete(e)}function IQ(e){let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-color-scheme`,`class`,`data-theme`]}),()=>t.disconnect()}var LQ=()=>{let e=document.documentElement;return`${e.getAttribute(`data-color-scheme`)??``}|${e.getAttribute(`data-theme`)??``}|${e.className}`};function RQ({engine:e,registry:t}){wt(t.subscribe,t.getVersion);let n=Z1(e),r=wt(n.store.subscribe,n.store.get),i=new Map;for(let e of t.mounts.values()){let t=r.worksheets.find(t=>t.panels.some(t=>t.id===e.chartId));if(!t)continue;let n=i.get(t.id)??{worksheet:t,mounts:[]};n.mounts.push(e),i.set(t.id,n)}return q(Dt,{children:[...i.values()].map(t=>q(HQ,{engine:e,worksheet:t.worksheet,mounts:t.mounts},t.worksheet.id))})}var zQ=1e3,BQ=.25;function VQ(e,t,n,r){let[i,a]=Ct(0),o=K(0),s=K(0);return W(()=>{o.current&&=(s.current=performance.now()-o.current,0)}),W(()=>{if(!n)return;let i=0,c=-1,l=0,u=n=>{if(i=LH(u),o.current||n<l||HH()||!r())return;let d=0;for(let n of e)t.includes(n.id)&&(d+=n.source.version());d!==c&&(c=d,l=n+s.current*(1/BQ-1),o.current=performance.now(),vt(()=>a(e=>e+1)))};return i=LH(u),()=>RH(i)},[n,e,t]),St(()=>n?e.map(e=>t.includes(e.id)?{...e,dataset:e.source.snapshot(zQ)}:e):e,[e,t,n,i])}function HQ({engine:e,worksheet:t,mounts:n}){let r=Z1(e),i=wt(r.store.subscribe,r.store.get),a=r.derived(),o=i.xRanges[t.id]??null,s=St(()=>i.live.filter(e=>e.kind===`data`),[i.live]),c=a.selectedLive.length,l=e=>{let n=t.panelChartSettings[e];return n?.kind===`multiband`&&n.beacon?.enabled===!0},u=c>0&&t.panels.some(e=>e.kind!==`multiband`&&e.kind!==`camera`||c>1&&!l(e.id)),d=K(n);d.current=n;let f=K(()=>d.current.some(e=>e.element.isConnected&&(typeof e.element.checkVisibility!=`function`||e.element.checkVisibility()))).current,p=VQ(s,i.selection,u,f),m=r.alertLines(),h=VZ({worksheet:KQ(t,m),viewXRange:o,selectedIds:i.selection,selectedDatasets:a.selectedDatasets,liveConnections:p,mathChannels:a.channels,datasetOffsets:i.offsets,datasetColors:i.colors,datasetPalette:i.palette}),g=K(WV()).current,_=wt(IQ,LQ),v=t.id,y=kQ(e,v),b=i.licensed,x=a.selectedLive[0]??null,S=e=>i.datasets.find(t=>t.id===e)??Object.values(a.laps).flatMap(e=>e.laps).find(t=>t.id===e);return q(Dt,{children:n.map(n=>{let r=t.panels.find(e=>e.id===n.chartId);if(!r)return null;let s=n.shiftDatasetId?a.selectedDatasets.find(e=>e.id===n.shiftDatasetId):void 0,c=DQ(n,e,v),l=JQ(t.panelChartSettings[r.id],m);return Tt(q(t$,{mount:n,annotations:t.panelChartSettings[r.id]?.annotations,marks:YQ(i.marks,i.selection,t.xKey),onMarkSelect:c.onMarkSelect,alarm:fr(l),onAnnotations:c.onAnnotations,onAnnotationToolEnd:c.onAnnotationToolEnd,onAnnotationSelect:c.onAnnotationSelect,render:u=>KZ({panel:r,settings:l,background:n.options.style?.background??t.panelChartBackgrounds[r.id]??null,styleToken:JSON.stringify([_,n.options.theme,n.options.style,Q]),data:h,xKey:t.xKey,height:u,viewXRange:o,onViewXRangeChange:c.onViewXRangeChange,onCursorX:c.onCursorX,liveZoom:g,liveWindowSeconds:t.liveWindowSeconds===void 0?i.liveWindowSeconds:t.liveWindowSeconds,onLiveWindowChange:y,beaconLive:x,findDataset:S,live:i.live,selection:i.selection,cursor:c.cursor,video:e.video.sources(),recordings:GX(a.selectedDatasets,i.offsets),shiftMode:s?UQ(e,s.id,s.name):void 0,onContextMenu:c.onContextMenu,xyzRef:c.xyzRef}),licensed:b},n.key),n.element,n.key)})})}function UQ(e,t,n){let r=0;return{label:n,onDragStart:()=>{r=e.getState().datasets.find(e=>e.id===t)?.offset??0},onDragOffset:n=>e.datasets.setOffset(t,r+n)}}var WQ=[],GQ=new WeakMap;function KQ(e,t){if(!t.size)return e;let n=GQ.get(e);if(n&&n.lines===t)return n.out;let r=!1,i={};for(let[n,a]of Object.entries(e.panelChartSettings))i[n]=JQ(a,t),i[n]!==a&&(r=!0);let a=r?{...e,panelChartSettings:i}:e;return GQ.set(e,{lines:t,out:a}),a}var qQ=new WeakMap;function JQ(e,t){if(!e||!t.size)return e;let n=qQ.get(e);if(n&&n.lines===t)return n.out;let r=ur(e,t);return qQ.set(e,{lines:t,out:r}),r}var YQ=QQ((e,t,n)=>{let r=e.filter(e=>e.timeColumn===n&&t.includes(e.targetId));return r.length?r:XQ}),XQ=[];function ZQ(e,t,n){return!t.length||!n?.x?e:[...t.map(e=>Jt(e,n.x.v1)),...e]}function QQ(e){let t=null,n;return(r,i,a)=>t&&t[0]===r&&t[1]===i&&t[2]===a?n:(t=[r,i,a],n=e(r,i,a),n)}function $Q(e,t){e.data=t}function e$(e,t){e.status!==t&&(e.status=t,e.emitter.emit(`status`,t))}function t$({mount:e,render:t,licensed:n,annotations:r,marks:i,alarm:a,onAnnotations:o,onAnnotationToolEnd:s,onAnnotationSelect:c,onMarkSelect:l}){let u=K(null),[d,f]=Ct(0),p=!!e.options.debug,m=K({renderStart:0,lastRenderMs:0,renders:0,data:null}).current;p&&(m.renderStart=performance.now()),G(()=>{p&&(m.lastRenderMs=performance.now()-m.renderStart,m.renders++)}),G(()=>{let e=u.current;if(!e)return;let t=()=>f(Math.max(120,Math.floor(e.clientHeight)));t();let n=new UH(t);return n.observe(e),()=>n.disconnect()},[]);let{status:h,node:g,data:_}=t(d||400);m.data=_,W(()=>{$Q(e,_)}),W(()=>{e$(e,h)});let{theme:v,style:y,className:b}=e.options,x={};return y?.background&&(x[`--chart-bg`]=y.background),y?.muted&&(x[`--chart-muted`]=y.muted),y?.grid&&(x[`--chart-grid`]=y.grid),y?.accent&&(x[`--accent`]=y.accent),Ot(`div`,{ref:u,onContextMenu:h===`ready`?void 0:t=>{t.preventDefault(),e.emitter.emit(`contextmenu`,{clientX:t.clientX,clientY:t.clientY})},className:b?`kymo-chart ${b}`:`kymo-chart`,"data-color-scheme":v,"data-status":h,style:x,children:[q(PU.Provider,{value:e.plotFrame.set,children:g}),h===`ready`&&a?q(wQ,{frame:e.plotFrame,alarm:a.alarm,axis:a.axis}):null,h===`ready`&&(r?.length||e.annotationTool||i.length)?q(uQ,{annotations:r??WQ,tool:e.annotationTool,plotFrame:e.plotFrame,onChange:o,onToolEnd:s,onSelect:c,marks:i,onMarkSelect:l}):null,p?q($Z,{stats:m,host:u}):null,n===!1?q(GV,{}):null]})}var n$=new WeakMap;function r$(e,t,n,r={}){let i=n$.get(e)??new Map;n$.set(e,i);let a=i.get(t);if(a&&!a.window.closed)return a.window.focus(),a;let o=e.charts.get(t),s=r.title??(o.title||e.charts.label(o.kind));for(let e of i.values())e.window.closed||e.window.focus();let c=40*(i.size+1),l=window.open(``,`kymoscope-chart-${t}`,`popup,width=${r.width??960},height=${r.height??600},left=${r.left??window.screenX+c},top=${r.top??window.screenY+c}`);if(!l)throw new HE(`popup_blocked`,{chartId:t});let u=l.document;u.head.replaceChildren(),u.body.replaceChildren(),u.title=s;for(let e of document.querySelectorAll(`style, link[rel="stylesheet"]`)){let t=e.cloneNode(!0);t instanceof HTMLLinkElement&&(t.href=e.href),u.head.appendChild(t)}let d=()=>{for(let e of[...u.documentElement.attributes])u.documentElement.removeAttribute(e.name);for(let e of document.documentElement.attributes)u.documentElement.setAttribute(e.name,e.value);u.body.className=document.body.className};d();let f=new MutationObserver(d);f.observe(document.documentElement,{attributes:!0}),f.observe(document.body,{attributes:!0,attributeFilter:[`class`]}),Object.assign(u.body.style,{margin:`0`,position:`fixed`,inset:`0`,display:`flex`,flexDirection:`column`,background:getComputedStyle(document.body).backgroundColor});let p=u.createElement(`div`);p.className=`kymo-window-controls`;let m=u.createElement(`div`);m.className=`kymo-window-plot`,Object.assign(m.style,{flex:`1`,minHeight:`0`,position:`relative`}),u.body.append(p,m),MH(l);let h=n(m,r.mount),g=KV(),_=!1,v=()=>{_||(_=!0,i.delete(t),NH(l),f.disconnect(),b(),window.removeEventListener(`pagehide`,y),h.destroy(),g.emit(`close`,void 0),g.clear())},y=()=>x.close(),b=e.subscribe(()=>{try{e.charts.get(t)}catch{x.close()}});l.addEventListener(`pagehide`,v),window.addEventListener(`pagehide`,y);let x={chartId:t,window:l,controls:p,view:h,close(){v(),l.closed||l.close()},on:(e,t)=>g.on(e,t)};return i.set(t,x),x}function i$(e){for(let t of[...n$.get(e)?.values()??[]])t.close()}function a$(e){let t=new Map;for(let[n,r]of n$.get(e)??[]){let e=r.window;e.closed||t.set(n,{left:e.screenX,top:e.screenY,width:e.innerWidth,height:e.innerHeight})}return t}var o$=12e3,s$=100;function c$(e,t=!1){let n,r=0;if(t&&e instanceof Float64Array){n=e;let t=0,i=0,a=0,o=n.length&-4;for(let e=0;e<o;e+=4)r+=n[e]*0,t+=n[e+1]*0,i+=n[e+2]*0,a+=n[e+3]*0;for(let e=o;e<n.length;e++)r+=n[e]*0;r+=t+i+a}else{n=new Float64Array(e.length);for(let t=0;t<n.length;t++){let i=+e[t];n[t]=i,r+=i*0}}if(r===0)return j.add(n),n;for(let e=0;e<n.length;e++){let t=n[e];t-t!==0&&(n[e]=NaN)}return n}function l$(e,t){let n=Object.keys(t.columns);if(n.length===0)throw new HE(`no_columns`);let r=t.columns[n[0]].length;if(n.some(e=>t.columns[e].length!==r))throw new HE(`column_length_mismatch`);let i=new Map(n.map(e=>[e,c$(t.columns[e],t.transfer)])),a=u$(e,t.name,i,t.units??{});if(t.bands){for(let e of Object.values(t.bands))if(e.lo.length!==r||e.hi.length!==r)throw new HE(`column_length_mismatch`);a.bands=Object.fromEntries(Object.entries(t.bands).map(([e,t])=>[e,{lo:Float64Array.from(t.lo),hi:Float64Array.from(t.hi)}]))}return a}function u$(e,t,n,r,i,a){let o=[...n.keys()],s=n.get(o[0]).length,c=o.map(e=>r[e]??``),l=o.map((e,t)=>({name:e,type:`number`,unit:c[t]})),u=!!a&&a.schema.length===o.length&&a.schema.every((e,t)=>e.name===o[t]),d,f;if(u)d=a.rawText??``,f=a.parseConfig;else{let e=[o.join(`,`)];for(let t=0;t<Math.min(s,s$);t++)e.push(o.map(e=>{let r=n.get(e)[t];return r===r?String(r):``}).join(`,`));d=e.join(`
|
|
615
|
-
`),f=ae(d)}let p={id:e,name:t,schema:l,rawText:d,parseConfig:f,fromColumns:!0};if(s>1e6){let e=new
|
|
616
|
-
`))}return r}function g$(e){let t=e,n=new Set;return{get:()=>t,set(e){let r=e(t);if(r!==t){t=r;for(let e of[...n])try{e()}catch(e){console.error(`[kymoscope] subscriber failed`,e)}}},subscribe(e){return n.add(e),()=>{n.delete(e)}}}}function _$(e){let t=null,n;return(...r)=>t&&t.length===r.length&&t.every((e,t)=>e===r[t])?n:(t=r,n=e(...r),n)}function v$(){let e=_$(e=>{let t={};for(let n of e){if(n.cut){let e=n.cut.defs.find(e=>e.id===n.cut.cycleId)?.show,r=e&&e.channel!==n.cut.timeKey?XB(e):null;t[n.id]=r?{laps:n.cut.parts,values:n.cut.found.map(e=>e.kpis?.[r]??null),unit:n.schema.find(t=>t.name===e.channel)?.unit??``,isTime:!1}:{laps:n.cut.parts,values:n.cut.found.map(e=>e.tend===null?null:e.tend-e.tstart),unit:`s`,isTime:!0};continue}if(!n.beacon||n.kind!==`memory`)continue;let{channel:e,metric:r,stat:i}=n.beacon,a=TB(n.data.rows,e);if(a.length===0)continue;let o=n.data.units[n.data.columnNames.indexOf(r)]??``;t[n.id]={laps:a.map((e,t)=>{let r={...n.data,rows:n.data.rows.slice(e.start,e.end)};return{...n,id:NB(n.id,t),name:`${n.name} · Cycle ${t+1}`,data:r,source:new XE(r)}}),values:a.map(e=>kB(n.data.rows,e,r,i)),unit:o,isTime:i===`span`&&jB(r,o)}}return t}),t=_$((e,t,n)=>e.flatMap(e=>t[e.id]?t[e.id].laps.filter(e=>n.includes(e.id)):n.includes(e.id)?[e]:[])),n=_$((e,t)=>e.filter(e=>e.kind===`data`&&t.includes(e.id))),r=_$(e=>sZ(e.map(e=>e.data))),i=_$((e,t)=>t.length===0?e:sZ(e?[e,...t.map(e=>e.dataset)]:t.map(e=>e.dataset))),a=_$((e,t,n,r)=>{let i=new Set;if(e)for(let t of n.length>0?n:[e])for(let e of dZ(t.columnNames,t.rows))i.add(e);for(let e of r)for(let t of e.dataset.columnNames)(t===`ElapsedTime`||e.source.hasValues(t))&&i.add(t);let a=e?e.columnNames.filter(e=>i.has(e)):[],o=t.filter(e=>e.kind!==`memory`).flatMap(e=>jz(e.schema));return[...new Set([...a,...o])]});return{lapsByDataset:e,selectedDatasets:t,selectedLive:n,staticDataset:r,mergedDataset:i,mergedParts:_$((e,t)=>[...e.map(e=>e.data),...t.map(e=>e.dataset)]),numericColumns:_$((e,t,n,r=[],i=[])=>{let o=a(e,t,r,i),s=new Set(o);return[...o,...n.map(e=>e.name).filter(e=>!s.has(e))]}),allColumns:_$((e,t,n)=>[...new Set([...e?.columnNames??[],...t.filter(e=>e.kind!==`memory`).flatMap(e=>e.schema.map(e=>e.name)),...n.map(e=>e.name)])]),columnUnits:_$((e,t)=>{let n={};e&&e.columnNames.forEach((t,r)=>{let i=e.units[r]?.trim();i&&(n[t]=i)});for(let e of t)e.units&&(n[e.name]=e.units);return n})}}var y$=[{kind:`multiband`,label:`Multi-band`},{kind:`xyscatter`,label:`X-Y scatter`},{kind:`xyzmesh`,label:`X-Y-Z mesh`},{kind:`histogram`,label:`Histogram`},{kind:`polar`,label:`Polar`},{kind:`spectrum`,label:`Spectrum`},{kind:`boxplot`,label:`Box Plot`},{kind:`spectrogram`,label:`Spectrogram`},{kind:`heatmap`,label:`Heatmap`},{kind:`violin`,label:`Violin`},{kind:`confusion`,label:`Confusion Matrix`},{kind:`roc`,label:`ROC Curve`},{kind:`losscurve`,label:`Loss Curves`},{kind:`controlchart`,label:`Control Chart`},{kind:`parallelcoords`,label:`Parallel Coords`},{kind:`embedding`,label:`Embedding`},{kind:`flamegraph`,label:`Flame Graph`},{kind:`barchart`,label:`Bar Chart`},{kind:`radar`,label:`Radar`},{kind:`areachart`,label:`Area Chart`},{kind:`cdfchart`,label:`CDF / ECDF`},{kind:`bubblechart`,label:`Bubble Chart`},{kind:`treemap`,label:`Treemap`},{kind:`sankey`,label:`Sankey`},{kind:`calibration`,label:`Calibration Curve`},{kind:`gauge`,label:`Gauges`},{kind:`camera`,label:`Camera`},{kind:`qqplot`,label:`Q-Q Plot`},{kind:`gantt`,label:`Gantt Chart`}],b$=new Map(y$.map(e=>[e.kind,e.label]));function x$(e){return b$.get(e)??e}var S$=`kymoscope-live.v1`,C$=`kymoscope-live.ack1`,w$=`kymoscope-live.ack2`,T$=1e3,E$=2e3,D$=3e4,O$=1e4,k$=30,A$=1e4,j$=300,M$=90,N$=e=>e.startsWith(`eyJ`);function P$(e){try{let t=e.split(`.`)[1]??``,n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)+`===`.slice((t.length+3)%4)),r=JSON.parse(n).exp;return typeof r==`number`?r:null}catch{return null}}function F$(e,t){return`${e.replace(/\/+$/,``)}/v1/streams/${t}/watch`}function I$(e,t,n,r){let i=null,a=null,o=null,s=!1,c=0,l=()=>{o&&=(clearTimeout(o),null)},u=(n,r)=>{l();let a=P$(r);if(a===null)return;let c=N$(r),d=c?Math.min(a,Date.now()/1e3+j$):a,f=Math.min(Math.max((d-(c?M$:k$))*1e3-Date.now(),A$),2**31-1);o=setTimeout(async()=>{o=null;let r=null;try{r=await e.getToken(t)}catch{r=null}if(!(s||i!==n||!r)){try{n.send(JSON.stringify({type:`auth`,token:r}))}catch{return}u(n,r)}},f)},d=(e=!1)=>{if(s||a)return;let t=e?0:Math.min(D$,E$*2**c++)*(.75+Math.random()/2);a=setTimeout(()=>{a=null,f()},t)},f=async()=>{if(s)return;let a=null;try{a=await e.getToken(t)}catch{a=null}if(s)return;if(!a){r?.(`error`),d();return}let o=new WebSocket(F$(e.url,t),[S$,C$,w$,`bearer.${a}`]);o.binaryType=`arraybuffer`,i=o;let f=a,p=Date.now(),m=0,h=setInterval(()=>{if(!(m===0||o.readyState!==1)){try{o.send(JSON.stringify({type:`ack`,b:m}))}catch{return}m=0}},T$);o.onopen=()=>{r?.(`subscribed`),u(o,f)},o.onmessage=e=>{if(c=0,typeof e.data!=`string`){m+=e.data.byteLength,n(e.data);return}if(e.data.startsWith(`{"type":"probe"`))try{let t=JSON.parse(e.data).id;typeof t==`string`&&t.length<=64&&o.send(JSON.stringify({type:`ack`,id:t}))}catch{}},o.onclose=()=>{clearInterval(h),i===o&&(i=null,l(),!s&&(r?.(`error`),d(Date.now()-p>=O$)))}};return f(),()=>{if(s=!0,a&&=(clearTimeout(a),null),l(),i){let e=i;i=null,e.close(1e3)}}}var L$=960*1024,R$=24;function z$(e){let t=e.key&&e.fragIndex===0?new TextEncoder().encode(e.codec):new Uint8Array;if(t.length>255)throw Error(`codec string too long`);let n=e.key&&e.fragIndex===0?1+t.length:0,r=new Uint8Array(R$+n+e.payload.length),i=new DataView(r.buffer);i.setUint8(0,1),i.setUint8(1,!!e.key|(e.last?2:0)),i.setUint8(2,1),i.setUint8(3,0),i.setFloat64(4,e.t,!0),i.setUint32(12,e.seq>>>0,!0),i.setUint16(16,e.fragIndex,!0),i.setUint16(18,e.fragCount,!0),i.setUint16(20,e.width,!0),i.setUint16(22,e.height,!0);let a=R$;return n&&(r[a++]=t.length,r.set(t,a),a+=t.length),r.set(e.payload,a),r}function B$(e){if(e.length<R$||e[0]!==1||e[2]!==1)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=(e[1]&1)!=0,r=t.getUint16(16,!0),i=t.getUint16(18,!0);if(i===0||r>=i)return null;let a=R$,o=``;if(n&&r===0){if(e.length<a+1||e.length<a+1+e[a])return null;o=new TextDecoder().decode(e.subarray(a+1,a+1+e[a])),a+=1+e[a]}return{key:n,last:(e[1]&2)!=0,t:t.getFloat64(4,!0),seq:t.getUint32(12,!0),fragIndex:r,fragCount:i,width:t.getUint16(20,!0),height:t.getUint16(22,!0),codec:o,payload:e.subarray(a)}}function V$(e){let t=Math.max(1,Math.ceil(e.data.length/L$)),n=[];for(let r=0;r<t;r++)n.push(z$({key:e.key,last:r===t-1,t:e.t,seq:e.seq,fragIndex:r,fragCount:t,width:e.width,height:e.height,codec:e.codec,payload:e.data.subarray(r*L$,Math.min(e.data.length,(r+1)*L$))}));return n}function H$(e,t,n){let r=new Map,i=Promise.resolve(),a=n?re(n,e=>t({type:`integrity`,integrity:e})):null;return Object.assign(n=>{let s=c(e,n).catch(()=>null);a?.arrive(n,new Uint8Array(n,0,1)[0]&127,s),i=i.then(async()=>{try{let e=await s;if(!e)return;if(e.kind===6){let n=B$(e.plaintext);n&&t({type:`video`,m:n})}else if(e.kind===5){let t=N(e.plaintext);r.set(t.id,t)}else if(e.kind===7){let n=o(e.plaintext,r);n&&t({type:`last`,values:n})}else if(e.kind===4){let n=await at(e.plaintext,r);n&&!n.historical&&t({type:`columns`,block:n.block})}else if(e.kind===3)t({type:`columns`,block:rt(e.plaintext)});else if(e.kind===2){let n=ke(e.plaintext);t({type:`frames`,frames:Array.isArray(n?.frames)?n.frames:[]})}}catch{}})},{reset:()=>a?.reset()})}var U$=``+new URL(`assets/liveIngestWorker-w4p7hYsW.js`,import.meta.url).href;function W$(e,t,n,r,i){let a=()=>{let a=H$(n,r,t);return I$(e,t,a,e=>{e===`subscribed`&&a.reset(),i?.(e)})},o;try{if(typeof Worker>`u`)return a();o=UE(U$)}catch{return a()}let s=!1,c=()=>{try{o.postMessage({type:`stop`})}catch{o.terminate()}};return o.onmessage=a=>{let s=a.data;if(s.type===`decoded`){if(r(s.d),s.bytes)try{o.postMessage({type:`ack`,bytes:s.bytes})}catch{}}else if(s.type===`status`)i?.(s.status);else if(s.type===`ask`){let r=s.what===`token`?e.getToken(t):typeof n==`function`?n(s.arg):n;Promise.resolve(r).catch(()=>null).then(e=>{try{o.postMessage({type:`reply`,id:s.id,value:e})}catch{}})}},o.onerror=()=>{o.terminate(),!s&&(c=a())},o.postMessage({type:`start`,url:e.url,streamId:t,key:typeof n==`function`?null:n}),()=>{s=!0,c()}}var G$=class{samples=[];exact=!1;windowS;constructor(e=30){this.windowS=e}observe(e,t){if(e>1e9){this.samples=[],this.exact=!0;return}this.exact=!1;let n=t-e,r=this.samples[this.samples.length-1];for(r&&Math.abs(n-r.off)>1&&(this.samples=[]),this.samples.push({at:t,off:n});this.samples.length&&this.samples[0].at<t-this.windowS;)this.samples.shift()}quality(){return this.exact?`exact`:this.samples.length?`approx`:`none`}toWall(e,t=0){if(this.exact)return e+t/1e3;if(!this.samples.length)return null;let n=1/0;for(let e of this.samples)n=Math.min(n,e.off);return e+n+t/1e3}toStream(e,t=0){let n=this.toWall(0,t);return n===null?null:e-n}},K$=class{#e;constructor(e){this.#e=typeof e==`function`?e:()=>e}size(){return this.#e().size}get columnNames(){return this.#e().columnNames}version(){return this.#e().version}columns(){let e=this.#e();return new q$(new Set(e.columnNames),t=>e.mirrorColumn(t))}hasValues(e){return this.#e().hasValues(e)}snapshot(e){return this.#e().toDataset(e)}async getSchema(){let e=this.#e();return e.columnNames.map(t=>({name:t,type:`number`,unit:e.unitOf(t)}))}async getSeries(e){let t=this.#e();return ee(t.columnValues(e.viewport.xKey),t.columnValues(e.column),e.viewport.x0,e.viewport.x1,e.maxPoints)}async getSeriesMulti(e,t,n){return this.getSeriesMultiSync(e,t,n)}getSeriesMultiSync(e,t,n){return this.#e().decimateColumns(t.xKey,e,t.x0,t.x1,n)}getPointsSync(e,t,n){return this.#e().decimatePoints(t.xKey,e,t.x0,t.x1,n)}async xBounds(e){return this.xBoundsSync(e)}xBoundsSync(e){return this.#e().columnBounds(e)}xTravelSync(e,t){return this.#e().xTravel(e,t)}timeAfterSync(e){return this.#e().timeAfter(e)}latestTimeSync(){return this.#e().latestTime()}xAtTimeSync(e,t,n=!1){return this.#e().xAtTime(e,t,n)}latestSync(e){return this.#e().lastValue(e)}latestValuesSync(e){let t=this.#e(),n=new Map;for(let r of e){let e=t.lastValue(r),i=t.lastKnown(r);Number.isFinite(e)?n.set(r,e):i&&n.set(r,i.v)}return n}valueBoundsSync(e){let t=this.#e().valueBounds(e),n=this.#e().lastKnown(e);if(!t&&!n)return null;let r=Math.min(t?.x0??1/0,n?.v??1/0),i=Math.max(t?.x1??-1/0,n?.v??-1/0);if(r!==i)return{min:r,max:i};let a=Math.max(.5,Math.abs(r)*.05);return{min:r-a,max:i+a}}lastKnownSync(e){return this.#e().lastKnown(e)}trackCycles(e){this.#e().trackCycles(e)}cycleSpanSync(e){return this.#e().cycleSpan(e)}decimateCycleSync(e,t,n,r,i){return this.#e().decimateCycle(e,t,n,r.x0,r.x1,i)}cyclePointsSync(e,t,n,r,i){return this.#e().decimateCyclePoints(e,t,n,r.x0,r.x1,i)}async readColumns(e,t,n){let r=this.#e(),i=new Set(r.columnNames),a={};for(let o of e)i.has(o)&&(a[o]=r.columnValues(o).slice(t,t+n));return a}async dispose(){}},q$=class extends Map{#e;#t;constructor(e,t){super(),this.#e=e,this.#t=t}get(e){if(!super.has(e)&&this.#e.has(e)){let t=this.#t(e);t&&super.set(e,t)}return super.get(e)}has(e){return this.#e.has(e)}},J$=4096,Y$=5e3,X$=class{startedAt=Date.now();n=0;capacity=J$;time=new Float64Array(J$);cols=new Map;order=[];units=new Map;timeColumn;timeUnit;constructor(e=n,t=`s`){this.timeColumn=e,this.timeUnit=t}get rows(){return this.n}add(e){this.n===this.capacity&&this.grow();let t=this.n;this.time[t]=e.t;for(let n of e.signals){let e=this.cols.get(n.name);e||(e=new Float64Array(this.capacity).fill(NaN),this.cols.set(n.name,e),this.order.push(n.name)),n.unit&&!this.units.get(n.name)&&this.units.set(n.name,n.unit),e[t]=typeof n.value==`number`?n.value:NaN}this.n++}addColumns(e){let t=S(e,this.timeColumn),n=e.t.length;for(;this.n+n>this.capacity;)this.grow();let r=this.n,i=(e,t)=>{if(t instanceof Float64Array||t instanceof Float32Array)e.set(t,r);else for(let i=0;i<n;i++)e[r+i]=+t[i]};i(this.time,e.t);for(let n of t){let t=this.cols.get(n);t||(t=new Float64Array(this.capacity).fill(NaN),this.cols.set(n,t),this.order.push(n));let r=e.units?.[n];r&&!this.units.get(n)&&this.units.set(n,r),i(t,e.columns[n])}this.n+=n}grow(){let e=this.capacity*2,t=new Float64Array(e);t.set(this.time),this.time=t;for(let[t,n]of this.cols){let r=new Float64Array(e).fill(NaN);r.set(n),this.cols.set(t,r)}this.capacity=e}toCsvParts(){let e=[this.timeColumn,...this.order],t=[this.timeUnit,...this.order.map(e=>this.units.get(e)??``)],n=[`${e.map(Z$).join(`,`)}\n${t.map(Z$).join(`,`)}\n`],r=this.order.map(e=>this.cols.get(e));for(let e=0;e<this.n;e+=Y$){let t=Math.min(this.n,e+Y$),i=``;for(let n=e;n<t;n++){i+=String(this.time[n]);for(let e of r){let t=e[n];i+=Number.isNaN(t)?`,`:`,${t}`}i+=`
|
|
617
|
-
`}n.push(i)}return n}};function Z$(e){let t=/^[=+\-@\t\r]/.test(e)?`'${e}`:e;return/[",\n\r]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var Q$=512,$$=new WeakMap;function e1(e,t,n){let r=$$.get(e);r||$$.set(e,r=new Map);let i=r.get(t),a={start:n,values:[]};return{carry:{start:e=>{let t=i?.values[e];if(!i||!t)return 0;for(let e=Math.min(n-i.start,t.length-1);e>=0;e--){let n=t[e];if(n!==null&&Number.isFinite(n))return n}return 0},done:(e,t)=>{a.values[e]=t}},keep:()=>{r.set(t,a)}}}function t1(e,t,r){let i=e.endAbs,a=Math.max(r,e.firstAbs);if(a>=i||t.length===0)return;let o=new Set(e.columnNames);for(let r of t){if(!r.enabled)continue;let s=dE(r.formula);if(!s.ok)continue;let{identifiers:c,functions:l}=fE(s.node);if(!c.every(e=>o.has(e)))continue;let u=l.some(e=>lE.includes(e)),d=Math.max(e.firstAbs,a-(u?Q$:0)),f=new Map([n,...c].map(t=>[t,e.range(t,d,i)])),{carry:p,keep:m}=e1(e,`${r.id}|${r.formula}`,d),h=vE(r,e=>f.get(e),n,i-d,t,p);h.status===`ok`&&(e.writeComputed(r.name,r.units,a,h.values.subarray(a-d)),m())}}function n1(e,t){e.clearComputed(),$$.delete(e),t1(e,t,e.firstAbs)}var r1=8e3,i1=131072;function a1(e,t={}){switch(e.kind){case`elapsed`:return{name:`Elapsed`,unit:`s`};case`event`:return{name:`Since ${e.channel} ${e.op} ${e.value}`,unit:`s`};case`clock`:return{name:`Time of day`,unit:`s`};default:{let n=t[e.channel]??``;return e.integral?{name:`∫${e.channel}`,unit:n?`${n}·s`:`s`}:{name:`${e.channel} since start`,unit:n}}}}var o1=new Map;function s1(e,t){let n=`${t}|${Math.floor(e/900)}`,r=o1.get(n);r===void 0&&(r=yB(e,t),o1.size>1e4&&o1.clear(),o1.set(n,r));let i=(e+r)%86400;return i<0?i+86400:i}var c1=class{axis;#e=NaN;#t=NaN;#n=NaN;#r=0;#i=NaN;#a=NaN;constructor(e){this.axis=e}begin(e){this.#e=e,this.#t=NaN,this.#n=NaN,this.#r=0,this.#i=NaN,this.#a=NaN}x(e,t){let n=this.axis;return n.kind===`clock`?s1(e,n.tz):n.kind===`elapsed`?e-this.#e:e<this.#e?NaN:n.kind===`event`?(this.#t!==this.#t&&t===t&&mB(n.op,t,n.value)&&(this.#t=e),e-this.#t):n.integral?(t===t&&(this.#i===this.#i&&(this.#r+=(t+this.#i)/2*(e-this.#a)),this.#i=t,this.#a=e),this.#i===this.#i?this.#r:NaN):(t===t&&(this.#n!==this.#n&&(this.#n=t),this.#i=t),this.#i===this.#i?this.#i-this.#n:NaN)}};function l1(e,t,n,r){let i=`channel`in r?t.get(r.channel):void 0;if(r.kind===`event`){let a=NaN;for(let t=0;t<e.length&&a!==a;t++){let o=i?i[t]:NaN;e[t]>=n&&o===o&&mB(r.op,o,r.value)&&(a=e[t])}return{x:e.map(e=>e-a),t:e,cols:t}}let a=new c1(r);a.begin(n);let o=new Float64Array(e.length);for(let t=0;t<e.length;t++)o[t]=a.x(e[t],i?i[t]:NaN);return{x:o,t:e,cols:t}}function u1(e,t,n){let r=[];for(let n=0;n<e.length;n++)e[n]===e[n]&&t[n]===t[n]&&r.push(n);let i=!0;for(let t=1;t<r.length&&i;t++)i=e[r[t-1]]<=e[r[t]];i||r.sort((t,n)=>e[t]-e[n]);let a=r.length,o=new Float64Array(n.length).fill(NaN);if(a<2)return o;let s=Float64Array.from(r,t=>e[t]),c=Float64Array.from(r,e=>t[e]),l=Float64Array.from({length:a-1},(e,t)=>s[t+1]-s[t]).sort(),u=l[l.length>>1],d=u>0?4*u:1/0,f=0;for(let e=0;e<n.length;e++){let t=n[e];if(!(t>=s[0]&&t<=s[a-1]))continue;for(;f<a-2&&s[f+1]<t;)f++;let r=s[f],i=s[f+1];i-r>d||(o[e]=i===r?c[f]:c[f]+(c[f+1]-c[f])*(t-r)/(i-r))}return o}function d1(e,t,n){let r=e.length;if(r===0||!(n>=e[0]&&n<=e[r-1]))return NaN;if(r===1)return t[0];let i=(n-e[0])/(e[r-1]-e[0])*(r-1),a=Math.min(r-2,Math.floor(i));return t[a]+(t[a+1]-t[a])*(i-a)}function f1(e,t,n){let r=Math.max(2,Math.min(r1,Math.floor(n)));if(r*t.length>131072)throw Error(`too_many_cells`);let i=1/0,a=-1/0;for(let t of e)for(let e of t.x)e===e&&(e<i&&(i=e),e>a&&(a=e));if(!(a>i))throw Error(`empty`);let o=Float64Array.from({length:r},(e,t)=>i+t*(a-i)/(r-1)),s=new Map;for(let n of t){let t=new Uint16Array(r),i=new Float64Array(r),a=new Float64Array(r),c=new Float32Array(r).fill(1/0),l=new Float32Array(r).fill(-1/0);for(let s of e){let e=s.cols.get(n);if(!e)continue;let u=u1(s.x,e,o);for(let e=0;e<r;e++){let n=u[e];if(n!==n)continue;let r=++t[e],o=n-i[e];i[e]+=o/r,a[e]+=o*(n-i[e]),n<c[e]&&(c[e]=n),n>l[e]&&(l[e]=n)}}let u={mean:new Float32Array(r),sd:new Float32Array(r),min:c,max:l,n:t};for(let e=0;e<r;e++){if(t[e]===0){u.mean[e]=u.sd[e]=u.min[e]=u.max[e]=NaN;continue}u.mean[e]=i[e],u.sd[e]=t[e]>1?Math.sqrt(a[e]/(t[e]-1)):0}s.set(n,u)}return{x:o,channels:s}}function p1(e,t){if(e.unit===`abs`)return e.tolerance;let n=1/0,r=-1/0;for(let e of t.mean)e===e&&(e<n&&(n=e),e>r&&(r=e));return r>=n?Math.max(r-n,Math.abs(r),Math.abs(n))*e.tolerance/100:0}var m1=new WeakMap;function h1(e){let t=m1.get(e);if(t)return t;let n=e.sd.length,r=Math.max(2,Math.round(n/100));t=new Float32Array(n).fill(NaN);for(let i=0;i<n;i++){if(e.n[i]<2)continue;let a=0,o=0;for(let t=Math.max(0,i-r);t<=Math.min(n-1,i+r);t++)e.n[t]>=2&&e.sd[t]===e.sd[t]&&(a+=e.sd[t]**2,o++);t[i]=o?Math.sqrt(a/o):NaN}return m1.set(e,t),t}function g1(e,t,n){if(n===`minmax`)return{lo:e.min,hi:e.max};if(n===`sigma`){let n=h1(e);return{lo:e.mean.map((e,r)=>e-t*n[r]),hi:e.mean.map((e,r)=>e+t*n[r])}}let r=p1(n,e);return{lo:e.mean.map(e=>e-r),hi:e.mean.map(e=>e+r)}}function _1(e,t,n,r=`sigma`,i=0){let a=typeof r==`function`?r:()=>({band:r,k:n}),o=[...t.channels.keys()],s=new Map,c=new Map,l=[],u=new Uint8Array(e.t.length),d=o.map(()=>new Uint8Array(e.t.length)),f=t.x.length;o.forEach((n,r)=>{let i=t.channels.get(n),o=e.cols.get(n);if(!o)return;let{band:p,k:m}=a(n),h=typeof p==`object`?p:null,{lo:g,hi:_}=g1(i,m,p),v=0,y=0,b=0;for(let e of i.mean)if(e===e){v++;let t=e-y;y+=t/v,b+=t*(e-y)}let x=v>1?Math.max(Math.sqrt(b/(v-1)),1e-9):1e-9,S=h?Math.max(p1(h,i),1e-9):0,C=h1(i),w=new Float64Array(e.t.length).fill(NaN),T=new Float64Array(e.t.length).fill(NaN),E=0,D=0;for(let n=0;n<e.t.length;n++){let a=o[n],s=e.x[n];if(a!==a||s!==s)continue;let c=d1(t.x,i.mean,s);if(c!==c)continue;w[n]=a-c;let l=Math.round((s-t.x[0])/(t.x[f-1]-t.x[0])*(f-1));T[n]=Math.abs(a-c)/(h?S:i.n[l]>=2&&C[l]===C[l]?Math.max(C[l],1e-9):x),E+=T[n],D++,(h||i.n[l]>=2)&&(a<d1(t.x,g,s)||a>d1(t.x,_,s))&&(u[n]=1,d[r][n]=1)}s.set(n,w),c.set(n,T),l.push({channel:n,z:D?E/D:0})}),l.sort((e,t)=>t.z-e.z);let p=[];for(let t=0;t<u.length;t++){if(!u[t])continue;let n=t;for(;n<u.length&&u[n];)n++;let r=p[p.length-1];r&&e.t[t]-e.t[Math.min(r[1],u.length-1)]<i?r[1]=n:p.push([t,n]),t=n}let m=[];for(let[t,n]of p){let r=e.t[t],a=e.t[Math.min(n,u.length-1)];a-r>=i&&m.push({t0:r,t1:a,channels:o.filter((e,r)=>d[r].subarray(t,n).includes(1))})}return{delta:s,score:l,deviations:m,z:c}}function v1(e,t){let n=e.x.length,r=t.length,i=new DataView(new ArrayBuffer(12+8*n+r*n*18));[75,82,66,49].forEach((e,t)=>i.setUint8(t,e)),i.setUint32(4,n,!0),i.setUint32(8,r,!0);let a=12;for(let t=0;t<n;t++,a+=8)i.setFloat64(a,e.x[t],!0);for(let r of t){let t=e.channels.get(r);if(!t)throw Error(`The reference has no channel ${r}`);for(let e of[t.mean,t.sd,t.min,t.max])for(let t=0;t<n;t++,a+=4)i.setFloat32(a,e[t],!0);for(let e=0;e<n;e++,a+=2)i.setUint16(a,t.n[e],!0)}return _e(new Uint8Array(i.buffer))}function y1(e,t){let n=fe(e),r=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.length<12||String.fromCharCode(n[0],n[1],n[2],n[3])!==`KRB1`)throw Error(`Not a reference band`);let i=r.getUint32(4,!0),a=r.getUint32(8,!0);if(a!==t.length||n.length!==12+8*i+a*i*18)throw Error(`This reference band does not match its channels`);let o=12,s=new Float64Array(i);for(let e=0;e<i;e++,o+=8)s[e]=r.getFloat64(o,!0);let c=new Map;for(let e of t){let t=()=>{let e=new Float32Array(i);for(let t=0;t<i;t++,o+=4)e[t]=r.getFloat32(o,!0);return e},n=t(),a=t(),s=t(),l=t(),u=new Uint16Array(i);for(let e=0;e<i;e++,o+=2)u[e]=r.getUint16(o,!0);c.set(e,{mean:n,sd:a,min:s,max:l,n:u})}return{x:s,channels:c}}function b1(e){if(!e.cycle)throw Error(`a live segment axis needs a cycle rule`);let t=new RB(e.cycle),r=new c1(e.axis),i=NaN,a=`channel`in e.axis?e.axis.channel:null,o=[...new Set([...LB(e.cycle),...a?[a]:[]])];return{feed(s,c,l=!1){let u=Math.max(c,s.firstAbs),d=s.endAbs;if(u>=d)return;let f=t=>{l||e.onEvent?.(t)},p=s.range(n,u,d),m=new Map(o.map(e=>[e,s.range(e,u,d)])),h=new Float64Array(p.length).fill(NaN),g=a?m.get(a):null,_=[];for(let e=0;e<p.length;e++){t.step(p[e],t=>{let n=m.get(t);return n?n[e]:NaN},_);let n=t.open()?.tstart??null;n!==null&&(n!==i&&(i=n,r.begin(n),f({type:`open`,tstart:n})),h[e]=r.x(p[e],g?g[e]:NaN))}for(let e of _)f({type:`close`,segment:{tstart:e.tstart,tend:e.tend,kpis:{duration:(e.tend??e.tstart)-e.tstart},...e.flags.length?{flags:e.flags}:{}}});s.writeComputed(e.column,e.unit,u,h)}}}var x1=1e7;function S1(e=globalThis.navigator?.deviceMemory){return Math.max(512,Math.round(((e??0)>0?e:16)*1024/8))}var C1=400,w1=4e3,T1=1e3,E1=3e3,D1=2,O1=5e3,k1=1e4;function A1(e,t,n=`data`){let r=new De(t.capacity??x1,void 0,void 0,(t.maxMemoryMB??S1())*1024*1024);return{meta:e,buffer:r,source:new K$(()=>r),unsub:()=>{},status:`connecting`,error:null,lastFrameAt:Date.now(),lastColCount:0,lastValued:0,recorder:null,dropped:0,recDropped:0,video:n===`camera`?new VE:null,clock:n===`camera`?null:new G$,lagTicks:0,lastRejoinAt:0,rejoin:()=>{},subscribed:!1,releaseTimer:void 0}}function j1(e,t,n,r){let i,a=-1/0,o=new Map;return async c=>{if(i===void 0&&(i=c,o.set(t,c)),c===i)return e;if(Date.now()-a<2e3)return null;a=Date.now();let l=await r().catch(()=>null);if(!l||o.has(l.salt)&&o.get(l.salt)!==c)return null;let u=l.key??(n===null?null:await We(n,l.salt));return!u||!await s(u,l.key_check).catch(()=>!1)?null:(o.set(l.salt,c),u)}}function M1(e,t,n=()=>({}),r){let i=new Map,a=e,o=[],c=[],l=``,u=()=>{let e=[];for(let t of i.values())t.lastColCount=t.buffer.columnNames.length,t.lastValued=t.buffer.valuedCount,e.push({...t.meta,kind:t.video?`camera`:`data`,video:t.video,clock:t.clock,dataset:t.buffer.toDataset(C1),source:t.source,rowCount:t.buffer.size,status:t.status,error:t.error,recordingSince:t.recorder?.startedAt??null,droppedSamples:t.dropped,...t.integrity?{integrity:t.integrity}:{}});o=e,t(o)},d=(e,t)=>{let n=!1,r=e.buffer.endAbs;for(let r of t)r&&typeof r.t==`number`&&Array.isArray(r.signals)&&(e.buffer.push(r),e.recorder?.add(r),n=!0);n&&p(e,r,t[t.length-1]?.t)},f=(e,t)=>{let n=e.buffer.endAbs;e.buffer.pushColumns(t),e.recorder?.addColumns(t),t.t.length>0&&p(e,n,t.t[t.t.length-1])},p=(e,t,n)=>{t1(e.buffer,c,t),e.segAxis?.tracker.feed(e.buffer,t),r?.rows(e.meta.id,e.buffer,t),typeof n==`number`&&e.clock?.observe(n,Date.now()/1e3),m(e,t===0||e.buffer.columnNames.length!==e.lastColCount||e.buffer.valuedCount!==e.lastValued)},m=(e,t)=>{e.lastFrameAt=Date.now();let n=e.status===`stale`||e.status===`connecting`;n&&(e.status=`live`),(n||t)&&u()},h=e=>{let t=i.get(e);t&&(clearTimeout(t.releaseTimer),t.unsub(),i.delete(e),u())},g=setInterval(()=>{let e=Date.now(),t=!1;for(let n of i.values()){n.status===`live`&&e-n.lastFrameAt>w1&&(n.status=`stale`,t=!0);let i=n.video&&n.subscribed&&n.status===`live`?n.video.info().lagMs:null;n.lagTicks=i!==null&&i>E1?n.lagTicks+1:0,n.video&&n.lagTicks>=D1&&e-n.lastRejoinAt>=O1&&(n.lagTicks=0,n.lastRejoinAt=e,n.video.resync(),n.unsub(),n.rejoin()),n.buffer.size&&r?.tick(n.meta.id,n.buffer,n.lastFrameAt)}t&&u()},T1);return{connections:()=>o,disconnect:h,startRecording(e){let t=i.get(e);!t||t.recorder||(t.recorder=new X$,t.recDropped=0,u())},stopRecording(e){let t=i.get(e),n=t?.recorder;return!t||!n?null:(t.recorder=null,u(),{csv:n.toCsvParts(),rows:n.rows,name:t.meta.name,startedAt:n.startedAt,droppedSamples:t.recDropped})},setRelay(e){a=e},setSegmentAxis(e,t){let n=i.get(e);n&&(n.segAxis=t?{cfg:t,tracker:b1(t)}:void 0,t&&n.segAxis.tracker.feed(n.buffer,n.buffer.firstAbs,!t.replay),u())},setMathChannels(e){let t=JSON.stringify(e.map(e=>[e.id,e.name,e.units,e.formula,e.enabled]));if(t!==l){l=t,c=e;for(let t of i.values())t.video||(n1(t.buffer,e),t.segAxis&&(t.segAxis.tracker=b1(t.segAxis.cfg),t.segAxis.tracker.feed(t.buffer,t.buffer.firstAbs,!0)));i.size>0&&u()}},openLocal(e,t){let r=`local:${crypto.randomUUID()}`,a=A1({id:r,name:e,ownerName:`This page`,visibility:`private`,orgName:null,parentId:null,lowOf:null},{...n(),...t});return i.set(r,a),u(),{id:r,push:e=>{i.get(r)===a&&d(a,Array.isArray(e)?e:[e])},pushColumns:e=>{i.get(r)===a&&f(a,e)},close:()=>h(r)}},async connect(e,t,r){if(i.has(e.id))return;let o=a&&e.relay_url?{...a,url:e.relay_url,getToken:async e=>{let t=await a.getToken(e);return t&&!N$(t)?t:null}}:a;if(!o)throw new HE(`relay_unavailable`);let c;if(typeof t==`string`){let n=ct(t).secret??t,i=await We(n,e.salt);if(!await s(i,e.key_check))throw new HE(`wrong_password`);c=r?.reload?j1(i,e.salt,n,r.reload):i}else if(c=`keyFor`in t?e=>t.keyFor(e):t,typeof c!=`function`){if(!await s(c,e.key_check))throw new HE(`wrong_password`);r?.reload&&(c=j1(c,e.salt,null,r.reload))}let l=A1({id:e.id,name:e.name,ownerName:e.owner_name??``,visibility:e.visibility??`private`,orgName:e.org_name??null,projectName:e.project_name??null,parentId:e.parent_stream_id??null,lowOf:e.low_of_stream_id??null,limitNotice:e.limit_notice??null},{...n(),...r},e.kind);i.set(e.id,l);let p=t=>{if(i.get(e.id)===l)if(t.type===`video`)l.video&&(l.video.push(t.m),m(l,!1));else if(t.type===`last`){let e=l.buffer;for(let n of t.values)e.setLastKnown(n.name,n.unit,n.t,n.v);(e.columnNames.length!==l.lastColCount||e.valuedCount!==l.lastValued)&&u()}else if(t.type===`gap`)l.dropped+=t.samples,l.recorder&&(l.recDropped+=t.samples),u();else if(t.type===`integrity`){let e=l.integrity;l.integrity=t.integrity,(!e||e.broken!==t.integrity.broken)&&u()}else t.type===`columns`?f(l,t.block):d(l,t.frames)},h=t=>{!l.subscribed||i.get(e.id)!==l||(t===`subscribed`?(l.status=`live`,l.lastFrameAt=Date.now()):t===`error`&&(l.status=`error`,l.error=`connection_error`),u())};l.rejoin=()=>{l.unsub=l.video?I$(o,e.id,H$(c,p),h):W$(o,e.id,c,p,h)};let g=l.video;g?(l.status=`idle`,g.onDemandChange(t=>{i.get(e.id)===l&&(clearTimeout(l.releaseTimer),t?l.subscribed||(l.subscribed=!0,g.resync(),l.status=`connecting`,l.lastFrameAt=Date.now(),l.rejoin(),u()):l.releaseTimer=setTimeout(()=>{l.subscribed=!1,l.unsub(),l.unsub=()=>{},l.status=`idle`,l.error=null,l.lagTicks=0,u()},k1))})):(l.subscribed=!0,l.rejoin()),u()},dispose(){clearInterval(g);for(let e of i.values())clearTimeout(e.releaseTimer),e.unsub();i.clear(),o=[]}}}var N1=500,P1=1<<20;function F1(e){let t=[],r=new Map,i=[],a=``,o=(e,t)=>`${e}|${t}`,s=(e,t)=>{let n=t.kind===`stream`?e.targets?.streams:t.kind===`history`?e.targets?.histories:e.targets?.datasets;return!n||n.includes(t.kind===`dataset`?t.name??t.id:t.id)},c=()=>[...r.values()].map(e=>{let{state:t,missing:n,since:r}=e.state();return{ruleId:e.rule.id,target:e.target,state:t,...n?{missing:n}:{},...r===void 0?{}:{since:r}}}),l=()=>{let t=c(),n=JSON.stringify(t);n!==a&&(a=n,e.setStates(t))};function u(n,r){let a=t.find(e=>e.id===n.ruleId);if(n.kind===`raised`){i=[...i,{id:`${n.ruleId}|${n.target.id}|${n.t}`,ruleId:n.ruleId,ruleName:a?.name??``,severity:a?.severity??`info`,targetId:n.target.id,timeColumn:r,t0:n.t,t1:null}];let e=i.filter(e=>e.targetId===n.target.id);e.length>N1&&(i=i.filter(t=>t!==e[0]))}else{let e=i.find(e=>e.ruleId===n.ruleId&&e.targetId===n.target.id&&e.t1===null);e&&(i=i.map(t=>t===e?{...t,t1:n.t}:t))}e.setMarks(i),e.emit(n)}function d(){let i=new Set;for(let a of e.targets())for(let e of t){if(!s(e,a))continue;let t=o(e.id,a.id);i.add(t);let c=r.get(t),{channels:l,...d}=a;(!c||c.rule!==e)&&(c=dt(e,d),r.set(t,c));for(let e of c.bind(l))u(e,a.kind===`stream`?n:``)}for(let e of r.keys())i.has(e)||r.delete(e);l()}return{setRules(n){let r=[],i=n.filter(e=>{let t=ft(e);return r.push(...t.map(t=>({ruleId:String(e?.id??``),...t}))),!t.length}),a=e.maxRules();a!==null&&i.length>a&&e.limit();let o=new Map(t.map(e=>[e.id,e]));return t=(a===null?i:i.slice(0,a)).map(e=>{let t=o.get(e.id);return t&&t.version===e.version?t:e}),d(),r},rules:()=>t,state:c,async evaluate(n,r){let a=e.targets().find(e=>e.id===n&&e.kind===`dataset`);if(!a)return[];let{channels:o,...c}=a,l=[],d=t.filter(e=>(!r.ruleIds||r.ruleIds.includes(e.id))&&s(e,c)),f=d.map(e=>{let t=dt(e,c);return t.bind(o),t}),p=[...new Set(d.flatMap(e=>Object.values(e.signals).map(e=>`formula`in e?e.formula:e.channel)))];for(let t=0;;t+=P1){let i=await e.readDataset(n,[r.timeColumn,...p],t,P1),a=i[r.timeColumn];if(!a||!a.length)break;for(let e of f)l.push(...e.push({t:a,columns:i}));if(a.length<P1)break}i=i.filter(e=>!(e.targetId===n&&(!r.ruleIds||r.ruleIds.includes(e.ruleId)))),e.setMarks(i);for(let e of l)u(e,r.timeColumn);return l},pushLive(e,t){let i=!1;for(let a of r.values()){if(a.target.id!==e)continue;let r=a.push(t);r.length&&(i=!0);for(let e of r)u(e,n)}i&&l()},tickLive(e,t){let i=!1;for(let a of r.values()){if(a.target.id!==e)continue;let r=a.tick(t);r.length&&(i=!0);for(let e of r)u(e,n)}i&&l()},liveColumns(e){let t=new Set;for(let n of r.values())if(n.target.id===e)for(let e of Object.values(n.rule.signals))t.add(`formula`in e?e.formula:e.channel);return[...t]},sync:d,clearMarks(t){i=t?i.filter(e=>e.targetId!==t):[],e.setMarks(i)}}}var I1=class{past=[];future=[];current=null;lastAt=-1/0;o;equals;constructor(e){this.o=e,this.equals=e.equals??Object.is}get canUndo(){return this.past.length>0}get canRedo(){return this.future.length>0}observe(e){if(this.current===null)return this.current=e,!1;if(this.equals(e,this.current))return!1;let t=this.o.now();return t-this.lastAt<this.o.mergeMs&&this.past.length>0||(this.past.push(this.current),this.past.length>this.o.limit&&this.past.shift()),this.current=e,this.future=[],this.lastAt=t,!0}rebase(e){this.current=e}undo(){if(this.past.length===0)return null;let e=this.past.pop();return this.future.push(this.current),this.current=e,this.lastAt=-1/0,e}redo(){if(this.future.length===0)return null;let e=this.future.pop();return this.past.push(this.current),this.current=e,this.lastAt=-1/0,e}clear(e){this.past=[],this.future=[],this.current=e,this.lastAt=-1/0}},L1={maxChartsPerWorksheet:null,maxChannelsPerChart:null,maxWorksheets:null,maxMathChannels:null,maxAlertRules:null,canImportExportWorkspaces:!0},R1=[];function z1(e,t){let n=e.found[t];return{definitionId:n.definitionId,rule:e.defs.find(e=>e.id===n.definitionId)?.name??n.definitionId,index:n.index,parentIndex:n.parentIndex??null,tstart:n.tstart,tend:n.tend,flags:n.flags,kpis:n.kpis??{},incomplete:!!n.incomplete}}var B1=[`#a78bfa`,`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#94a3b8`];function V1(e=`ET`){return{id:crypto.randomUUID(),name:`Worksheet`,panels:[],panelChartSettings:{},panelChartBackgrounds:{},xKey:e}}function H1(e,t){let n=e.filter(e=>e.source!==`workbook`),r=new Map,i=[];for(let e of t){let t=n.find(t=>t.name===e.name);if(t&&t.formula===e.formula&&t.units===e.units)continue;let a=t?`${e.name} (workbook)`:e.name;t&&r.set(e.name,a),i.push(yr({...e,name:a,source:`workbook`}))}return{channels:i,rename:r}}function U1(e,t){let n=JSON.stringify({xKey:e.xKey,panelChartSettings:e.panelChartSettings});for(let[e,r]of t)n=n.split(JSON.stringify(e)).join(JSON.stringify(r));return{...e,...JSON.parse(n)}}function W1(e){return typeof e.text==`function`?e.text():new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result??``)),r.onerror=()=>n(r.error),r.readAsText(e)})}function G1(e,t,n){if(!e||!t)return dn();let{min:r,max:i}=Mz(e.rows,t);if(!Number.isFinite(r)||!Number.isFinite(i))return dn();let a=Pz(i-r||1,6),o=a>=1?Math.round(a):a,s=o>=1?1:o/10,c=Math.max(0,Math.ceil(-Math.log10(s))),l=e=>String(Number(e.toFixed(c)));return{...n,scaleMin:l(Math.floor(r/s)*s),scaleMax:l(Math.ceil(i/s)*s),majorStep:l(o),minorStep:``}}function K1(e,t){let r=t.includes(e.xKey)?e.xKey:t.includes(`ET`)?`ET`:t.includes(`ElapsedTime`)?n:t[0],i={...e.panelChartSettings};for(let n of e.panels){let e=i[n.id];if(n.kind===`multiband`){let r=e&&e.kind===`multiband`?e:wn();i[n.id]={...r,kind:`multiband`,addColumn:r.addColumn&&t.includes(r.addColumn)?r.addColumn:t[0]}}else if(n.kind===`xyscatter`){let r=e&&e.kind===`xyscatter`?e:Tn(B1[2]),a=r.xyXCol||t[0],o=r.xyYCol||(t.length>1&&t[1]!==a?t[1]:t[0]);i[n.id]={...r,kind:`xyscatter`,xyXCol:a,xyYCol:o}}else if(n.kind===`xyzmesh`){let r=e&&e.kind===`xyzmesh`?e:En(4),a=r.xyzXCol||t[0],o=r.xyzYCol||(t.length>1?t[1]:t[0]),s=r.xyzZCol||(t.length>2?t[2]:t[0]);i[n.id]={...r,kind:`xyzmesh`,xyzXCol:a,xyzYCol:o,xyzZCol:s}}}return{...e,xKey:r,panelChartSettings:i}}function q1(e,t){let n=!1,r={...e.panelChartSettings};for(let[i,a]of Object.entries(e.panelChartSettings)){if(a.kind!==`multiband`)continue;let e=a.series.filter(e=>t(e.column));e.length!==a.series.length&&(r[i]={...a,series:e},n=!0)}return n?{...e,panelChartSettings:r}:e}function J1(){return typeof document>`u`?`dark`:lB(null)}function Y1(e={}){let t={...e},r=!1,i=V1(),a=g$({datasets:[],selection:[],worksheets:[i],activeWorksheetId:i.id,xRanges:{},offsets:{},colors:{},liveWindowSeconds:15,cycleRules:[],live:[],video:[],mathChannels:[],limits:{...L1,...t.limits},palette:oB(t.palette,J1()),importing:0,licensed:null,history:{canUndo:!1,canRedo:!1},marks:[],alerts:[],alertRules:[]}),o=KV(),s=()=>{let e=oB(t.palette,J1());a.set(t=>t.palette.join()===e.join()?t:{...t,palette:e})},c=typeof document>`u`?()=>{}:uB(null,s),l=v$(),u=()=>{if(r)throw new HE(`disposed`)},d=e=>{throw o.emit(`limit`,{reason:e}),new HE(`limit_reached`,{reason:e})},f=()=>a.get(),p=(e,t)=>{let n=f().limits.maxChannelsPerChart,r=Nz(t);n!==null&&r>n&&r>Nz(e)&&d(`channels-per-chart`)},m=_$((e,t)=>t===null?e:e.slice(0,t)),h=()=>{let e=f(),t=l.lapsByDataset(e.datasets),n=l.selectedDatasets(e.datasets,t,e.selection),r=l.selectedLive(e.live,e.selection),i=l.staticDataset(n),a=l.mergedDataset(i,r),o=m(e.mathChannels,e.limits.maxMathChannels);return{laps:t,selectedDatasets:n,selectedLive:r,staticDataset:i,merged:a,channels:o,numericColumns:l.numericColumns(a,n,o,l.mergedParts(n,r),r),allColumns:l.allColumns(a,n,o),columnUnits:l.columnUnits(a,o)}},g=(e,t)=>({id:t.id,kind:t.kind,title:t.title??null,settings:e.panelChartSettings[t.id],background:e.panelChartBackgrounds[t.id]??null,annotations:e.panelChartSettings[t.id]?.annotations??R1,layout:t.rect,window:t.window??null}),_=_$((e,t,n)=>e.map(e=>({id:e.id,name:e.name,xKey:e.xKey,xRange:t[e.id]??null,liveWindowSeconds:e.liveWindowSeconds===void 0?n:e.liveWindowSeconds,charts:e.panels.map(t=>g(e,t))}))),v=_$((e,t,n,r,i,a,o)=>{let s=(e,t)=>{let n=a.findIndex(t=>t.id===e);return n>=0?n:t};return e.map((e,a)=>{let c=i[e.id],l=c?.laps.map(e=>e.id)??[],u=l.filter(e=>t.includes(e)).length;return{id:e.id,name:e.name,kind:e.kind,columns:e.schema.map(e=>({name:e.name,unit:e.unit??``,numeric:e.type===`number`})),rowCount:e.data.rows.length,color:iB(n,e.id,s(e.id,a),o),customColor:e.id in n,offset:r[e.id]??0,parseConfig:e.parseConfig??null,fileInfo:e.info??null,beacon:e.beacon??null,cut:e.cut?{cycleId:e.cut.cycleId,timeKey:e.cut.timeKey,defs:e.cut.defs}:null,laps:c?c.laps.map((i,a)=>({id:i.id,name:i.name,value:c.values[a],unit:c.unit,isTime:c.isTime,color:iB(n,i.id,s(i.id,a),o),offset:r[i.id]??0,selected:t.includes(i.id),...e.cut?{cycle:z1(e.cut,a)}:{}})):null,selected:c?u===0?!1:u===l.length?!0:`partial`:t.includes(e.id)}})}),y=_$((e,t,n,r,i)=>{let a=e.filter(e=>t.includes(e.id)).map(e=>e.id);return e.map((e,o)=>({id:e.id,name:e.name,ownerName:e.ownerName,visibility:e.visibility,orgName:e.orgName,kind:e.kind,parentId:e.parentId,lowOf:e.lowOf,status:e.status,error:e.error,rowCount:e.rowCount,selected:t.includes(e.id),color:iB(n,e.id,a.includes(e.id)?r+a.indexOf(e.id):o,i),customColor:e.id in n,recordingSince:e.recordingSince,limitNotice:e.limitNotice??null,...e.integrity?{integrity:e.integrity}:{},channels:e.dataset.columnNames}))}),b=_$(e=>{let t=h();return{datasets:v(e.datasets,e.selection,e.colors,e.offsets,t.laps,t.selectedDatasets,e.palette),selection:e.selection,worksheets:_(e.worksheets,e.xRanges,e.liveWindowSeconds),activeWorksheetId:e.activeWorksheetId,mathChannels:t.channels,live:y(e.live,e.selection,e.colors,t.selectedDatasets.length,e.palette),liveWindowSeconds:(()=>{let t=e.worksheets.find(t=>t.id===e.activeWorksheetId);return t?.liveWindowSeconds===void 0?e.liveWindowSeconds:t.liveWindowSeconds})(),cycleRules:e.cycleRules,limits:e.limits,palette:e.palette,importing:e.importing,licensed:e.licensed,hasData:t.merged!==null,multiDataset:t.selectedDatasets.length+t.selectedLive.length>1,numericColumns:t.numericColumns,allColumns:t.allColumns,columnUnits:t.columnUnits,history:e.history,marks:e.marks,alerts:e.alerts}}),x=(e,t)=>e===t||e.length===t.length&&e.every((e,n)=>e===t[n]||JSON.stringify(e)===JSON.stringify(t[n])),S=new I1({limit:100,mergeMs:500,now:()=>Date.now(),equals:(e,t)=>e.liveWindowSeconds===t.liveWindowSeconds&&x(e.worksheets,t.worksheets)&&x(e.channels,t.channels)}),C=!0,w=0,T=e=>{w++;try{e()}finally{w--}},E=e=>[e.worksheets,e.mathChannels,e.liveWindowSeconds],D=[],O=()=>{let e=f();return{worksheets:e.worksheets,channels:e.mathChannels.filter(e=>e.source===`workbook`),liveWindowSeconds:e.liveWindowSeconds,activeWorksheetId:e.activeWorksheetId}},k=()=>a.set(e=>e.history.canUndo===S.canUndo&&e.history.canRedo===S.canRedo?e:{...e,history:{canUndo:S.canUndo,canRedo:S.canRedo}}),A=()=>{if(C)return;let e=E(f());e.every((e,t)=>e===D[t])||(D=e,w?S.rebase(O()):S.observe(O()),k())},j=()=>{D=E(f()),S.clear(O()),k()},M=e=>{C=!0;let t;try{t=e()}finally{C=!1}return j(),t},N=()=>b(f());a.subscribe(()=>{A(),o.emit(`change`,N())});let P=e=>{let t=f(),n=t.worksheets.find(n=>n.id===(e??t.activeWorksheetId));if(!n)throw new HE(`not_found`,{worksheetId:e});return n},F=e=>{for(let t of f().worksheets){let n=t.panels.find(t=>t.id===e);if(n)return{ws:t,panel:n}}throw new HE(`not_found`,{chartId:e})},I=(e,t)=>{let n=e=>e&&t?e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height:!e&&!t,r=f().worksheets.find(t=>t.panels.some(t=>t.id===e&&!n(t.window)));r&&T(()=>L(r.id,n=>({...n,panels:n.panels.map(n=>{if(n.id!==e)return n;if(t)return{...n,window:{...t}};let{window:r,...i}=n;return i})})))},L=(e,t)=>a.set(n=>{let r=!1,i=n.worksheets.map(n=>{if(n.id!==e)return n;let i=t(n);return i!==n&&(r=!0),i});return r?{...n,worksheets:i}:n}),R=(e,t)=>{let{ws:n}=F(e);L(n.id,n=>({...n,panelChartSettings:{...n.panelChartSettings,[e]:t(n.panelChartSettings[e])}}))},z=e=>a.set(t=>e.length===t.selection.length&&e.every((e,n)=>e===t.selection[n])?t:{...t,selection:e,xRanges:{}}),B=new Set,V=M1(t.live?.relay,e=>{let t=e.map(e=>e.id),r=e.filter(e=>e.kind===`data`&&!B.has(e.id)).map(e=>e.id),i=[...B].filter(e=>!t.includes(e));if(B=new Set(t),a.set(t=>({...t,live:e})),i.length&&z(f().selection.filter(e=>!i.includes(e))),r.length){let e=f().selection,t=r.filter(t=>!e.includes(t));t.length&&z([...e,...t])}let o=h();if(o.selectedLive.length&&o.merged){let e=o.merged.columnNames;if(e.includes(`ElapsedTime`))for(let t of f().worksheets)e.includes(t.xKey)||T(()=>L(t.id,e=>({...e,xKey:n})))}},()=>({capacity:t.live?.capacity,maxMemoryMB:t.live?.maxMemoryMB}),{rows:(e,t,r)=>{if(!se.rules().length)return;t.columnNames.length!==ee.get(e)&&(ee.set(e,t.columnNames.length),se.sync());let i=se.liveColumns(e);if(!i.length)return;let a=t.endAbs,o=Math.max(r,t.firstAbs);if(a<=o)return;let s={};for(let e of i)s[e]=t.range(e,o,a);se.pushLive(e,{t:t.range(n,o,a),columns:s,scan:new Map})},tick:(e,t,r)=>{if(!se.rules().length)return;let i=t.range(n,t.endAbs-1,t.endAbs)[0];i===i&&se.tickLive(e,i+(Date.now()-r)/1e3)}}),ee=new Map,te=_$((e,t)=>e.filter(e=>t.some(t=>NE([e],t.panelChartSettings,t.xKey).length>0))),H=()=>V.setMathChannels(te(m(f().mathChannels,f().limits.maxMathChannels),f().worksheets));H(),a.subscribe(H);let ne=e=>{a.set(t=>({...t,datasets:[...t.datasets,e]})),z([...f().selection,e.id]);let t=jz(e.schema);t.length&&T(()=>a.set(e=>({...e,worksheets:e.worksheets.map(e=>K1(e,t))})))},re=Promise.resolve(),ie=async(e,n={})=>{u();let i=e.map(e=>e instanceof File?e:e.file);if(i.length===0)return{ids:[],errors:[]};if(await t.beforeImport?.()===!1)throw new HE(`import_vetoed`);let{signal:s}=n;a.set(e=>({...e,importing:e.importing+i.length}));let c=re.then(async()=>{let e={ids:[],errors:[]},t=i.length,c=e=>{t-=e,a.set(t=>({...t,importing:Math.max(0,t.importing-e)}))};try{let{items:t,errors:a}=await LR(i);c(i.length-t.length);for(let{file:t,error:n}of a)e.errors.push({file:t,error:n}),o.emit(`import`,{file:t,phase:`error`,error:n}),o.emit(`error`,{error:n,context:`import`});for(let i of t){if(r)break;if(s?.aborted){e.cancelled=!0;break}let t=i.main;await new Promise(e=>setTimeout(e,0)),o.emit(`import`,{file:t.name,phase:`start`});try{let a=i.format?await Az({main:t,companions:i.companions,format:i.format.id},{priorInMemoryValues:kR(f().datasets),signal:s,onProgress:e=>o.emit(`import`,{file:t.name,phase:`progress`,fraction:e}),chooseChannels:n.chooseChannels,pickChannels:n.pickChannels}):[await OR(crypto.randomUUID(),t,f().datasets)??await ER(crypto.randomUUID(),t,W1,void 0,kR(f().datasets),s)];if(r){for(let e of a)e.source.dispose();break}if(s?.aborted){for(let e of a)e.source.dispose();throw new HE(`cancelled`)}for(let t of a)ne(t),e.ids.push(t.id);o.emit(`import`,{file:t.name,phase:`done`,datasetId:a[0].id,datasetIds:a.map(e=>e.id)})}catch(n){let r=n instanceof Error?n:Error(String(n));o.emit(`import`,{file:t.name,phase:`error`,error:r}),r instanceof HE&&r.code===`cancelled`?e.cancelled=!0:(e.errors.push({file:t.name,error:r}),o.emit(`error`,{error:r,context:`import`}))}finally{c(1)}if(e.cancelled)break}}finally{t>0&&c(t)}return e});return re=c.catch(()=>void 0),c},U=()=>setTimeout(()=>{r||PQ(rt)},0),ae=e=>{let t=t=>e.some(e=>t===e||t.startsWith(`${e}::`)),n=f().datasets.filter(t=>e.includes(t.id));for(let e of n)e.source.dispose().catch(()=>void 0);a.set(n=>{let r={...n.offsets},i={...n.colors};for(let e of Object.keys(r))t(e)&&delete r[e];for(let e of Object.keys(i))t(e)&&delete i[e];return{...n,datasets:n.datasets.filter(t=>!e.includes(t.id)),offsets:r,colors:i}}),z(f().selection.filter(e=>!t(e))),n.length>0&&U()},oe=async(e,t,n={})=>{let[r,...i]=await Az({main:new File(e.chunks,`${e.name}.krc`),companions:[],format:`krc`,keys:e.keys},{priorInMemoryValues:t,...n});for(let e of i)e.source.dispose();return{...r,file:void 0,name:e.name,info:r.info&&{...r.info,startTime:e.startTime??r.info.startTime,meta:{...r.info.meta,recordingId:e.recordingId}}}},se=F1({targets:()=>[...f().datasets.map(e=>({kind:`dataset`,id:e.id,name:e.name,channels:e.schema.map(e=>e.name)})),...f().live.filter(e=>e.kind===`data`).map(e=>({kind:`stream`,id:e.id,name:e.name,channels:e.source.columnNames}))],maxRules:()=>f().limits.maxAlertRules,emit:e=>o.emit(`alert`,e),limit:()=>o.emit(`limit`,{reason:`alert-rules`}),setMarks:e=>a.set(t=>({...t,marks:e})),setStates:e=>a.set(t=>({...t,alerts:e})),readDataset:(e,t,n,r)=>{let i=f().datasets.find(t=>t.id===e);return i?i.source.readColumns(t,n,r):Promise.resolve({})}}),ce=_$((e,t)=>{let n=new Map;for(let r of e){let e=mt(r);e!==null&&n.set(r.id,{value:e,active:t.some(e=>e.ruleId===r.id&&(e.state===`active`||e.state===`clearing`))})}return n}),le=null;a.subscribe(()=>{let e=f();le&&le[0]===e.datasets&&le[1]===e.live||(le=[e.datasets,e.live],se.rules().length&&se.sync())});let ue={importFiles:ie,warmImport(e={}){u(),vz(!!e.formats?.some(e=>e===`hdf5`||e===`mat`))},async splitByRate(e){u();let t=f().datasets.find(t=>t.id===e);if(!t)throw new HE(`not_found`,{datasetId:e});if(!t.info?.combined||!(t.file instanceof File))throw new HE(`invalid_argument`,{reason:`only a combined multi-rate import can be split`});let n=await Az({main:t.file,companions:t.companions??[],format:t.info.importer},{priorInMemoryValues:kR(f().datasets.filter(t=>t.id!==e)),selection:t.info.selection,split:!0});ae([e]);for(let e of n)ne(e);return n.map(e=>e.id)},async chooseChannels(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{datasetId:e});if(!n.info||!(n.file instanceof File))throw new HE(`invalid_argument`,{reason:`only binary imports have channels to choose`});try{let r=await Az({main:n.file,companions:n.companions??[],format:n.info.importer},{priorInMemoryValues:kR(f().datasets.filter(t=>t.id!==e)),initial:n.info.selection,chooseChannels:t,pickChannels:!0});ae([e]);for(let e of r)ne(e);return r.map(e=>e.id)}catch(e){if(e instanceof HE&&e.code===`cancelled`)return null;throw e}},async combine(e){u();let t=f().datasets.find(t=>t.id===e);if(!t)throw new HE(`not_found`,{datasetId:e});let n=t.info?.splitKey;if(!n||!(t.file instanceof File))throw new HE(`invalid_argument`,{reason:`only datasets split from one file can be combined`});let r=f().datasets.filter(e=>e.info?.splitKey===n),i=await Az({main:t.file,companions:t.companions??[],format:t.info.importer},{priorInMemoryValues:kR(f().datasets.filter(e=>!r.includes(e))),selection:r.flatMap(e=>e.info.selection)});if(i.length!==1){for(let e of i)e.source.dispose();throw new HE(`invalid_argument`,{reason:`these groups have no common time base`})}return ae(r.map(e=>e.id)),ne(i[0]),i[0].id},async openRecording(e,t={}){u();let n=await oe(e,kR(f().datasets),t);return ne(n),n.id},async reopenRecording(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{datasetId:e});let r=await oe(t,kR(f().datasets.filter(t=>t.id!==e)));a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?{...r,id:e,beacon:n.beacon}:t)})),n.source.dispose().catch(()=>void 0),U()},addColumns(e){u();let t=l$(crypto.randomUUID(),e);return ne(t),t.id},replaceColumns(e,t,n={}){u();let r=f().datasets.find(t=>t.id===e);if(!r)throw new HE(`not_found`,{datasetId:e});let i=p$(r,t,n.transfer);a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?i:t)}))},writeColumns(e,t,n){u();let r=f().datasets.find(t=>t.id===e);if(!r)throw new HE(`not_found`,{datasetId:e});let i=d$(r,t,n);a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?i:t)}))},async addText(e,t=`dataset.csv`){u();let n=await CR(crypto.randomUUID(),t,e);return ne(n),n.id},async findCycles(e,t,n){u();let r=f().datasets.find(t=>t.id===e);if(!r)throw new HE(`not_found`,{datasetId:e});let i=await qB(r.source,n,YB(t)),a=new Map(t.filter(e=>e.kpis?.length).map(e=>[e.id,e.kpis]));return JB(i,t).map(e=>a.has(e.definitionId)?{...e,kpis:ZB(i,e,a.get(e.definitionId))}:e)},async addCycles(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{datasetId:e});let r=n.schema.filter(e=>e.type===`number`&&e.name!==t.timeKey).map(e=>e.name),i=await qB(n.source,t.timeKey,r),a={...Object.fromEntries(n.schema.map(e=>[e.name,e.unit])),[GB]:`s`},o=e=>t.defs.find(t=>t.id===e)?.name??e,s=[];for(let e of t.pick){let r=t.found.find(t=>t.definitionId===e.definitionId&&t.index===e.index&&t.parentIndex===e.parentIndex);if(!r)throw new HE(`not_found`,{reason:`no ${o(e.definitionId)} ${e.index} in the cycles found`});let c=r.parentIndex?`${o(t.cycleId)} ${r.parentIndex} · ${o(r.definitionId)}`:`${o(r.definitionId)} ${r.index}`;s.push(ue.addColumns({name:`${n.name} · ${c}`,columns:$B(i,t.timeKey,r),units:a}))}if(t.tables!==!1){let e=tV(t.found,t.cycleId,t.defs,i);s.push(await ue.addText(nV(e.cycles),`${n.name} · ${o(t.cycleId)}s.csv`)),e.phases.length&&s.push(await ue.addText(nV(e.phases),`${n.name} · Phases.csv`))}return s},async cut(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{datasetId:e});let r;if(t){if(!t.defs.some(e=>e.id===t.cycleId))throw new HE(`invalid_argument`,{reason:`cycleId is not one of defs`});let i=n.schema.filter(e=>e.type===`number`&&e.name!==t.timeKey).map(e=>e.name),a=await qB(n.source,t.timeKey,i),o=t.defs.find(e=>e.id===t.cycleId)?.show,s=e=>[...e.kpis??[],...o&&o.channel!==t.timeKey?[o]:[]],c=new Map(t.defs.filter(e=>s(e).length).map(e=>[e.id,s(e)])),l=JB(a,t.defs).sort((e,t)=>e.tstart-t.tstart||!!e.parentIndex-+!!t.parentIndex).map(e=>c.has(e.definitionId)?{...e,kpis:ZB(a,e,c.get(e.definitionId))}:e),u={...Object.fromEntries(n.schema.map(e=>[e.name,e.unit])),[GB]:`s`},d=e=>t.defs.find(t=>t.id===e)?.name??e,f=l.map(r=>l$(`${e}::${r.definitionId}:${r.parentIndex??0}:${r.index}`,{name:r.parentIndex?`${n.name} · ${d(t.cycleId)} ${r.parentIndex} · ${d(r.definitionId)}`:`${n.name} · ${d(r.definitionId)} ${r.index}`,columns:$B(a,t.timeKey,r),units:u})),p=a.t.length?a.t[a.t.length-1]:NaN,m=l.map(e=>e.tend===null&&p===p?{...e,tend:p,incomplete:!0}:e);r={defs:t.defs,cycleId:t.cycleId,timeKey:t.timeKey,found:m,parts:f}}else if(!n.cut)return 0;if(!f().datasets.some(t=>t.id===e))return 0;a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?{...t,cut:r}:t)}));let i=f().selection,o=i.some(t=>t===e||t.startsWith(`${e}::`)),s=i.filter(t=>t!==e&&!t.startsWith(`${e}::`)),c=r?r.parts.filter((e,t)=>!r.found[t].parentIndex).map(e=>e.id):[];return z(o?c.length>0?[...s,...c]:[...s,e]:s),c.length},remove(e){u(),ae([e])},clear(){u(),ae(f().datasets.map(e=>e.id))},async configure(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{datasetId:e});if(t.parseConfig&&(n.kind!==`memory`||!n.parseConfig))throw new HE(`invalid_argument`,{reason:n.parseConfig?`out-of-core datasets cannot be re-parsed`:`binary files have no text parse settings`});if(t.beacon!==void 0&&t.beacon!==null&&n.kind!==`memory`)throw new HE(`invalid_argument`,{reason:`laps need an in-memory dataset`});if(t.beacon!==void 0&&JSON.stringify(t.beacon)!==JSON.stringify(n.beacon??null)){let r=t.beacon??void 0;a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?{...t,beacon:r}:t)}));let i=f().selection,o=i.some(t=>t===e||t.startsWith(`${e}::`)),s=i.filter(t=>t!==e&&!t.startsWith(`${e}::`)),c=r?TB(n.data.rows,r.channel):[],l=r&&t.selectCycles===`best`?AB(c.map(e=>kB(n.data.rows,e,r.metric,r.stat))):null,u=l===null?c.map((t,n)=>NB(e,n)):[NB(e,l)];z(o?c.length>0?[...s,...u]:[...s,e]:s)}let r=t.parseConfig;if(!r)return;let i=(()=>{try{let e=ze(Te(n.rawText??``),r.headerRow);return n.data.columnNames.length===e.length&&n.data.columnNames.every((t,n)=>t===e[n])}catch{return!1}})();if(Ye(r,n.parseConfig)&&i)return;let o=n.fromColumns?h$(n):n.rawText??``,s=await qE(n.file?{file:n.file,config:r}:{rawText:o,config:r}),c=new XE(s),l=await c.getSchema(),d=n.fromColumns?{rawText:o,fromColumns:!1}:{};a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?{...t,...d,data:s,source:c,schema:l,parseConfig:r}:t)})),n.source.dispose().catch(()=>void 0),U(),n.cut&&await ue.cut(e,n.cut);let p=h().selectedDatasets,m=new Set(p.flatMap(e=>e.data.columnNames)),g=s.columnNames.filter(e=>Ze(s.rows,e)),_=g.find(e=>e===`ET`)??g[0];T(()=>a.set(e=>({...e,worksheets:e.worksheets.map(e=>q1(!m.has(e.xKey)&&_?{...e,xKey:_}:e,e=>m.has(e)))})))},setColor(e,t){u(),a.set(n=>{let r={...n.colors};return t===null?delete r[e]:r[e]=t,{...n,colors:r}})},setOffset(e,t){u(),a.set(n=>({...n,offsets:{...n.offsets,[e]:t}}))},resetOffsets(){u(),a.set(e=>Object.keys(e.offsets).length?{...e,offsets:{}}:e)},select(e){u(),z([...e])},toggle(e){u();let t=f().selection,n=h().laps[e];if(n){let e=n.laps.map(e=>e.id);z(e.every(e=>t.includes(e))?t.filter(t=>!e.includes(t)):[...t,...e.filter(e=>!t.includes(e))]);return}z(t.includes(e)?t.filter(t=>t!==e):[...t,e])},selectAll(){u();let e=h().laps,t=f().live.filter(e=>f().selection.includes(e.id)).map(e=>e.id);z([...f().datasets.flatMap(t=>e[t.id]?e[t.id].laps.map(e=>e.id):[t.id]),...t])},deselectAll(){u(),z([])},raw(e){let t=f().datasets.find(t=>t.id===e);if(!t)throw new HE(`not_found`,{datasetId:e});return{get rawText(){return t.kind===`memory`&&t.fromColumns?h$(t):t.rawText??``},data:t.data,parseConfig:t.parseConfig??null,kind:t.kind,beacon:t.beacon??null}},async columnBounds(e){u();let t=h(),n=t.selectedDatasets.find(t=>t.schema.some(t=>t.name===e));if(n&&n.kind===`memory`){let t=Mz(n.data.rows,e);if(Number.isFinite(t.min)&&Number.isFinite(t.max))return t}else if(n){let t=await n.source.xBounds(e).catch(()=>null);if(t&&Number.isFinite(t.x0)&&Number.isFinite(t.x1)&&t.x1>=t.x0)return{min:t.x0,max:t.x1}}let r=t.selectedLive.find(t=>t.dataset.columnNames.includes(e));if(r){let t=r.source.valueBoundsSync(e);if(t)return t}let i=de(e);if(!i)return null;let a=Mz(i.rows,e);return Number.isFinite(a.min)&&Number.isFinite(a.max)?a:null}},de=(e,t=P().xKey)=>{let n=h();if(!n.merged)return null;if(!n.channels.find(t=>t.name===e))return n.merged;let r=ME(n.merged,n.channels,t);return{...n.merged,columnNames:[...n.merged.columnNames,...r.ok.map(e=>e.name)],rows:r.rows}},fe=(e,t,n)=>h().selectedLive.length>0?{...n,scaleMin:``,scaleMax:``,majorStep:``,minorStep:``}:G1(de(e,t),e,n),pe={fromFileList:e=>NV(Array.from(e)),async fromDataTransfer(e){return PV(Array.from(e.items??[]).map(e=>e.webkitGetAsEntry?.()).filter(e=>!!e))},canPick:FV,pick:IV,tree:(e,t)=>MV(e,t),isImportable:jV},me={add(e=`Worksheet`){u();let t=f(),n=t.limits.maxWorksheets;n!==null&&t.worksheets.length>=n&&d(`worksheets`);let r={...V1(P().xKey||`ET`),name:e};return a.set(e=>({...e,worksheets:[...e.worksheets,r],activeWorksheetId:r.id})),r.id},rename(e,t){u(),P(e),L(e,e=>e.name===t?e:{...e,name:t})},remove(e){u();let t=f();if(P(e),t.worksheets.length<=1)throw new HE(`invalid_argument`,{reason:`the last worksheet cannot be removed`});let n=t.worksheets.findIndex(t=>t.id===e),r=t.worksheets.filter(t=>t.id!==e);a.set(t=>({...t,worksheets:r,activeWorksheetId:t.activeWorksheetId===e?r[Math.max(0,n-1)].id:t.activeWorksheetId}))},reorder(e,t){u(),a.set(n=>{if(e===t||e<0||t<0||e>=n.worksheets.length||t>=n.worksheets.length)return n;let r=[...n.worksheets],[i]=r.splice(e,1);return r.splice(t,0,i),{...n,worksheets:r}})},activate(e){u(),P(e),a.set(t=>t.activeWorksheetId===e?t:{...t,activeWorksheetId:e,xRanges:{...t.xRanges,[e]:null}})},setXKey(e,t){u(),P(e),L(e,e=>q1({...e,xKey:t},e=>e!==t)),a.set(t=>({...t,xRanges:{...t.xRanges,[e]:null},offsets:{}}))}},he={mount(e,t,n){return u(),NQ(rt,e,t,n)},openWindow(e,t){u(),F(e);let n=F(e).panel.window;return r$(rt,e,(t,n)=>NQ(rt,e,t,n),{...n,...t})},recordWindows(){u();let e=a$(rt);for(let t of f().worksheets)for(let n of t.panels)I(n.id,e.get(n.id)??null)},setFonts(e){e.sans&&(Q.sans=e.sans),e.mono&&(Q.mono=e.mono),PQ(rt)},kinds:()=>y$,label:x$,add(e,t={}){if(u(),!y$.some(t=>t.kind===e))throw new HE(`invalid_argument`,{kind:e});let n=P(t.worksheetId),r=f().limits.maxChartsPerWorksheet;r!==null&&n.panels.length>=r&&d(`charts-per-worksheet`);let i={...cn(e,n.panels),...t.title?{title:t.title}:{}};t.layout&&(i.rect={...t.layout});let a=hr([i],{},B1[2],4)[i.id],o=a,s=h().numericColumns;if(s.length&&(o.kind===`multiband`||o.kind===`xyscatter`||o.kind===`xyzmesh`)&&(o=K1({...n,panels:[i],panelChartSettings:{[i.id]:o}},s).panelChartSettings[i.id],o.kind===`multiband`&&(o={...o,addColumn:s.find(e=>e!==n.xKey)??s[0]})),t.settings&&(o={...o,...t.settings,kind:o.kind}),s.length&&o.kind===`xyscatter`){let e=t.settings??{};o={...o,xyXScale:e.xyXScale??fe(o.xyXCol,n.xKey,o.xyXScale),xyYScale:e.xyYScale??fe(o.xyYCol,n.xKey,o.xyYScale)}}return p(a,o),L(n.id,e=>({...e,panels:t.layout?[...e.panels,i]:un([...e.panels,i]),panelChartSettings:{...e.panelChartSettings,[i.id]:o}})),i.id},remove(e){u();let{ws:t}=F(e);L(t.id,t=>{let n={...t.panelChartSettings},r={...t.panelChartBackgrounds};return delete n[e],delete r[e],{...t,panels:un(t.panels.filter(t=>t.id!==e)),panelChartSettings:n,panelChartBackgrounds:r}})},rename(e,t){u();let{ws:n}=F(e),r=t?.trim()||void 0;L(n.id,t=>({...t,panels:t.panels.map(t=>{if(t.id!==e)return t;let{title:n,...i}=t;return r?{...i,title:r}:i})}))},update(e,t){u();let{ws:n}=F(e),r=n.panelChartSettings[e],i={...r,...t,kind:r.kind};if(r.kind===`xyscatter`&&i.kind===`xyscatter`){let e=t;typeof e.xyXCol==`string`&&e.xyXCol!==r.xyXCol&&!(`xyXScale`in e)&&(i={...i,xyXScale:fe(e.xyXCol,n.xKey,r.xyXScale)}),typeof e.xyYCol==`string`&&e.xyYCol!==r.xyYCol&&!(`xyYScale`in e)&&(i={...i,xyYScale:fe(e.xyYCol,n.xKey,r.xyYScale)})}p(r,i),R(e,()=>i)},replaceSettings(e,t){u();let{ws:n,panel:r}=F(e);if(t.kind!==r.kind)throw new HE(`invalid_argument`,{reason:`settings kind mismatch`});p(n.panelChartSettings[e],t),R(e,()=>t)},setBackground(e,t){u();let{ws:n}=F(e);L(n.id,n=>({...n,panelChartBackgrounds:{...n.panelChartBackgrounds,[e]:t}}))},addAnnotation(e,t){u(),F(e);let n=Wt({...t,id:t.id||crypto.randomUUID()});if(!n)throw new HE(`invalid_argument`,{reason:`not a valid annotation`});return R(e,e=>({...e,annotations:[...(e.annotations??[]).filter(e=>e.id!==n.id),n]})),n.id},updateAnnotation(e,t,n){u();let r=(F(e).ws.panelChartSettings[e]?.annotations??[]).find(e=>e.id===t);if(!r)throw new HE(`not_found`,{annotationId:t});let i=Wt({...r,...n,id:r.id,kind:r.kind});if(!i)throw new HE(`invalid_argument`,{reason:`not a valid annotation`});R(e,e=>({...e,annotations:(e.annotations??[]).map(e=>e.id===i.id?i:e)}))},removeAnnotation(e,t){u(),F(e),R(e,e=>({...e,annotations:(e.annotations??[]).filter(e=>e.id!==t)}))},setAnnotations(e,t){u(),F(e);let n=Gt(t)??[];R(e,e=>({...e,annotations:n}))},setLayout(e,t){u();let{ws:n}=F(e);L(n.id,n=>({...n,panels:n.panels.map(n=>n.id===e?{...n,rect:{...t}}:n)}))},setLayouts(e,t){u(),L(e,e=>({...e,panels:e.panels.map(e=>t[e.id]?{...e,rect:{...t[e.id]}}:e)}))},autoLayout(e){u(),L(P(e).id,e=>({...e,panels:un(e.panels)}))},get(e){let{ws:t,panel:n}=F(e);return g(t,n)},list(e){let t=P(e);return t.panels.map(e=>g(t,e))},async addSeries(e,t){u();let{ws:n}=F(e),r=n.panelChartSettings[e];if(!r||r.kind!==`multiband`)throw new HE(`invalid_argument`,{reason:`not a multiband chart`});let i=f().limits.maxChannelsPerChart;i!==null&&Nz(r)>=i&&d(`channels-per-chart`);let a=h().numericColumns,o=new Set(r.series.map(e=>e.column)),s=t??a.find(e=>e!==n.xKey&&!o.has(e))??a.find(e=>e!==n.xKey)??``;if(!s)return null;let c=vr(),l={id:c,column:s,color:B1[r.series.length%B1.length],bandFromPct:0,bandToPct:100,scaleMin:0,scaleMax:1,yMajorStep:0,yMinorStep:0};return R(e,e=>e.kind===`multiband`?{...e,series:[...e.series,l]}:e),await he.autoScaleSeries(e,c),c},async updateSeries(e,t,n){u();let{ws:r}=F(e),i=r.panelChartSettings[e],a=i&&i.kind===`multiband`?i.series.find(e=>e.id===t):void 0;if(!a)throw new HE(`not_found`,{seriesId:t});R(e,e=>e.kind===`multiband`?{...e,series:e.series.map(e=>e.id===t?{...e,...n,id:e.id}:e)}:e),n.column&&n.column!==a.column&&n.scaleMin===void 0&&n.scaleMax===void 0&&await he.autoScaleSeries(e,t)},removeSeries(e,t){u(),R(e,e=>e.kind===`multiband`?{...e,series:e.series.filter(e=>e.id!==t)}:e)},reorderSeries(e,t){u(),R(e,e=>{if(e.kind!==`multiband`)return e;let n=new Map(e.series.map(e=>[e.id,e])),r=t.map(e=>n.get(e)).filter(e=>!!e),i=e.series.filter(e=>!t.includes(e.id));return{...e,series:[...r,...i]}})},async autoScaleSeries(e,t){u();let{ws:n}=F(e),i=n.panelChartSettings[e],a=i&&i.kind===`multiband`?i.series.find(e=>e.id===t):void 0;if(!a)return;let o=await ue.columnBounds(a.column);!o||r||R(e,e=>e.kind===`multiband`?{...e,series:e.series.map(e=>e.id===t?{...e,scaleMin:o.min,scaleMax:o.max}:e)}:e)}},ge=new Map,_e={setXRange(e,t){u();let n=P(t).id;a.set(t=>{let r=t.xRanges[n]??null;return r===e||r&&e&&r[0]===e[0]&&r[1]===e[1]?t:{...t,xRanges:{...t.xRanges,[n]:e}}})},resetZoom(e){_e.setXRange(null,e)},setCursorX(e,t){u();let n=P(t).id;(ge.get(n)??null)!==e&&(ge.set(n,e),o.emit(`cursorchange`,{worksheetId:n,x:e}))},cursorX(e){return ge.get(P(e).id)??null},setLiveWindow(e,t){u();let n=P(t);n.liveWindowSeconds!==e&&L(n.id,t=>({...t,liveWindowSeconds:e}))}},ve={save(e){u();let t=e.id??crypto.randomUUID(),[n]=WB([{...e,id:t,parentId:e.parentId??null}].concat(f().cycleRules.filter(e=>e.id!==t))).filter(e=>e.id===t);if(!n)throw new HE(`invalid_argument`,{reason:`not a valid cycle rule (or its parent is missing)`});return a.set(e=>({...e,cycleRules:e.cycleRules.some(e=>e.id===t)?e.cycleRules.map(e=>e.id===t?n:e):[...e.cycleRules,n]})),t},remove(e){u();let t=new Set([e]);for(let e=!0;e;){e=!1;for(let n of f().cycleRules)n.parentId&&t.has(n.parentId)&&!t.has(n.id)&&(t.add(n.id),e=!0)}a.set(e=>({...e,cycleRules:e.cycleRules.filter(e=>!t.has(e.id))}))}},ye={create(e){u();let n=f(),r=n.limits.maxMathChannels;r!==null&&n.mathChannels.length>=r&&d(`math-channels`);let i=yr(e);return a.set(e=>({...e,mathChannels:[...e.mathChannels,i]})),Promise.resolve(t.mathChannels?.create(i)).catch(e=>o.emit(`error`,{error:e,context:`mathChannels.create`})),i},update(e,n){u();let r=f().mathChannels.find(t=>t.id===e);if(!r)throw new HE(`not_found`,{channelId:e});a.set(t=>({...t,mathChannels:t.mathChannels.map(t=>t.id===e?{...t,...n,updatedAt:Date.now()}:t)})),r.source!==`workbook`&&Promise.resolve(t.mathChannels?.update(e,n)).catch(e=>o.emit(`error`,{error:e,context:`mathChannels.update`}))},remove(e){u();let n=f().mathChannels.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{channelId:e});a.set(t=>({...t,mathChannels:t.mathChannels.filter(t=>t.id!==e)})),n.source!==`workbook`&&Promise.resolve(t.mathChannels?.remove(e)).catch(e=>o.emit(`error`,{error:e,context:`mathChannels.remove`}))},async importFile(e){u();let{channels:n,errors:r}=await IE(e),i=f(),o=i.limits.maxMathChannels===null?n.length:Math.max(0,i.limits.maxMathChannels-i.mathChannels.length);n.length>0&&o===0&&d(`math-channels`);let s=n.slice(0,o);return a.set(e=>({...e,mathChannels:[...e.mathChannels,...s]})),await t.mathChannels?.importMany(s),{channels:s,errors:r}},async importMany(e){u();let n=f(),r=n.limits.maxMathChannels===null?e.length:Math.max(0,n.limits.maxMathChannels-n.mathChannels.length);e.length>0&&r===0&&d(`math-channels`);let i=e.slice(0,r);return a.set(e=>({...e,mathChannels:[...e.mathChannels,...i]})),await t.mathChannels?.importMany(i),i},exportBlob:()=>PE(f().mathChannels),preview(e,t){let n=h();return n.merged?mE(e,n.merged,P(t).xKey,n.channels.filter(t=>t.id!==e.id)):null},sync(e){u(),a.set(t=>{let n=t.mathChannels.filter(e=>e.source===`workbook`),r=n.length?[...e,...n]:e;return t.mathChannels===r?t:{...t,mathChannels:r}})}},be=_$((e,t)=>[...e.flatMap(e=>e.kind===`camera`&&e.video?[BE({...e,video:e.video})]:[]),...t]),xe=``;a.subscribe(()=>{let e=be(f().live,f().video),t=e.map(e=>`${e.kind}:${e.id}:${e.recordingId??``}:${e.name}`).join(`|`);t!==xe&&(xe=t,o.emit(`videochange`,{sources:e}))});let Se=(e,t,n)=>e.id===t&&(n===void 0||(e.recordingId??null)===n),Ce={sources:()=>be(f().live,f().video),register(e){u(),a.set(t=>({...t,video:[...t.video.filter(t=>!Se(t,e.id,e.recordingId??null)),e]}))},unregister(e,t){u(),a.set(n=>n.video.some(n=>Se(n,e,t))?{...n,video:n.video.filter(n=>!Se(n,e,t))}:n)}},we={openLocal(e,t){return u(),V.openLocal(e,t)},async connect(e,t,n){u(),await V.connect(e,t,n)},startRecording(e){u(),V.startRecording(e)},stopRecording(e){return u(),V.stopRecording(e)},setSegmentAxis(e,t){u(),V.setSegmentAxis(e,t)},rowCount(e){return V.connections().find(t=>t.id===e)?.source.size()??0},disconnect(e){u(),V.disconnect(e),z(f().selection.filter(t=>t!==e))}},Ee=()=>{f().limits.canImportExportWorkspaces||d(`workspaces-io`)},De=async e=>{if(e instanceof Blob)try{return JSON.parse(await e.text())}catch{throw new HE(`bad_file`)}if(typeof e==`string`)try{return JSON.parse(e)}catch{throw new HE(`bad_file`)}return e},Oe=async e=>e instanceof File?e:new File([JSON.stringify(await De(e))],`import.json`,{type:`application/json`}),ke=e=>e.replace(/[^\w.-]+/g,`_`),Ae=e=>new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),je=e=>{let t=mr(e.panelChartSettings,B1[2],4),n={};for(let r of e.panels)t[r.id]?.kind===r.kind&&(n[r.id]=t[r.id]);return{...e,panelChartSettings:hr(e.panels,n,B1[2],4)}},Me=(e,t)=>e.map(e=>{let n=e=>{let n=t.has(e)?crypto.randomUUID():e;return t.add(n),n},r=new Map(e.panels.map(e=>[e.id,n(e.id)])),i=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[r.get(e)??e,t]));return{...e,id:n(e.id),panels:e.panels.map(e=>({...e,id:r.get(e.id)})),panelChartSettings:i(e.panelChartSettings),panelChartBackgrounds:i(e.panelChartBackgrounds??{})}}),Ne=()=>new Set(f().worksheets.flatMap(e=>[e.id,...e.panels.map(e=>e.id)])),Pe=(e,t=0)=>{let n=f().limits.maxWorksheets,r=Me((n===null?e:e.slice(0,Math.max(1,n))).map(je),new Set),i=r[Math.min(t,r.length-1)];a.set(e=>({...e,worksheets:r,activeWorksheetId:i.id,xRanges:{}}))},Fe=(e,t)=>{let n=P(t),r=f().limits.maxChartsPerWorksheet;r!==null&&n.panels.length>=r&&d(`charts-per-worksheet`);let i=f().limits.maxChannelsPerChart;i!==null&&Nz(e.settings)>i&&d(`channels-per-chart`);let a=crypto.randomUUID(),o={id:a,kind:e.kind,rect:{x:0,y:0,w:6,h:24},...e.title?{title:e.title}:{}};return L(n.id,t=>({...t,panels:un([...t.panels,o]),panelChartSettings:{...t.panelChartSettings,[a]:e.settings},panelChartBackgrounds:e.background===null?t.panelChartBackgrounds:{...t.panelChartBackgrounds,[a]:e.background}})),a},Ie=()=>{let e=f();return hV({worksheets:e.worksheets,activeWorksheetId:e.activeWorksheetId,channels:te(m(e.mathChannels,e.limits.maxMathChannels),e.worksheets),liveWindowSeconds:e.liveWindowSeconds,laps:e.datasets.find(e=>e.beacon)?.beacon??null,cycles:e.cycleRules})},Le=e=>{if(e.worksheets.length===0)throw new HE(`bad_workspace`,{errors:e.errors});let{channels:t,rename:n}=H1(f().mathChannels,e.mathChannels);Pe(n.size?e.worksheets.map(e=>U1(e,n)):e.worksheets,e.activeIndex),a.set(n=>({...n,mathChannels:[...n.mathChannels.filter(e=>e.source!==`workbook`),...t],liveWindowSeconds:e.liveWindowSeconds===void 0?n.liveWindowSeconds:e.liveWindowSeconds,cycleRules:e.cycles}));let r=e.laps;if(r)for(let e of f().datasets)e.kind!==`memory`||e.beacon||!e.data.columnNames.includes(r.channel)||ue.configure(e.id,{beacon:r}).catch(e=>o.emit(`error`,{error:e,context:`io.openWorkbook`}));return{worksheets:e.worksheets.length,errors:e.errors}},Re=e=>{if(e===null)return;let t=h().numericColumns,n=t.length?e.worksheets.map(e=>K1(e,t)):e.worksheets;C=!0;try{a.set(t=>{let r=t=>e.worksheets.some(e=>e.id===t);return{...t,worksheets:n,activeWorksheetId:r(t.activeWorksheetId)?t.activeWorksheetId:r(e.activeWorksheetId)?e.activeWorksheetId:e.worksheets[0].id,xRanges:Object.fromEntries(Object.entries(t.xRanges).filter(([e])=>r(e))),mathChannels:[...t.mathChannels.filter(e=>e.source!==`workbook`),...e.channels],liveWindowSeconds:e.liveWindowSeconds}})}finally{C=!1}D=E(f()),S.rebase(O()),k()},Be={undo(){u(),Re(S.undo())},redo(){u(),Re(S.redo())},clear(){u(),j()}},Ve={hasWork:()=>EV(f().worksheets),exportWorksheet(e){u(),Ee();let t=P(e),n=gV(t);return{json:n,blob:Ae(n),filename:`${ke(t.name||`worksheet`)}.kymosh`}},exportChart(e){u(),Ee();let{ws:t,panel:n}=F(e),r=_V(n,t.panelChartSettings[e],t.panelChartBackgrounds[e]??null);return{json:r,blob:Ae(r),filename:`${ke(n.title?.trim()||n.kind)}.json`}},parseFile:e=>kV(e),exportWorkspace(){u(),Ee();let e=Ie();return{json:e,blob:Ae(e),filename:`kymoscope-workspace-${new Date().toISOString().slice(0,10)}.json`}},async exportWorkspaceEncrypted(e){u(),Ee();let t=typeof e==`string`?await aV(Ie(),e):await oV(Ie(),e);return{json:t,blob:Ae(t),filename:`kymoscope-workbook-${new Date().toISOString().slice(0,10)}.kymo`}},async importWorkspace(e,t={}){u(),Ee();let n=await De(e);return sV(n)&&(n=await uV(n,t)),M(()=>Le(TV(n)))},toWorkbook:Ie,openWorkbook(e){return u(),M(()=>Le(TV(e)))},async importWorksheet(e){u(),Ee();let t=f();t.limits.maxWorksheets!==null&&t.worksheets.length>=t.limits.maxWorksheets&&d(`worksheets`);let n=await kV(await Oe(e));if(n.type!==`worksheet`)throw new HE(`bad_file`,{found:n.type});let[r]=Me([je(n.worksheet)],Ne());return a.set(e=>({...e,worksheets:[...e.worksheets,r],activeWorksheetId:r.id})),r.id},async importChart(e,t){u(),Ee();let n=await kV(await Oe(e));if(n.type!==`chart`)throw new HE(`bad_file`,{found:n.type});return Fe(n.chart,t)},snapshot(){let e=f();return{datasets:e.datasets,worksheets:e.worksheets,activeWorksheetId:e.activeWorksheetId,selection:e.selection}},restore(e){u();let t=new Set(e.datasets);for(let e of f().datasets)t.has(e)||e.source.dispose().catch(()=>void 0);let n=e.worksheets.length?e.worksheets.map(je):[V1()];M(()=>a.set(t=>({...t,datasets:e.datasets,worksheets:n,activeWorksheetId:n.some(t=>t.id===e.activeWorksheetId)?e.activeWorksheetId:n[0].id,selection:e.selection,xRanges:{},offsets:{},colors:{}})))},reset(){u(),M(()=>{ae(f().datasets.map(e=>e.id));let e=V1();a.set(t=>({...t,worksheets:[e],activeWorksheetId:e.id,xRanges:{},offsets:{},colors:{},mathChannels:t.mathChannels.filter(e=>e.source!==`workbook`)}))})}},He={merged(e){let t=h();if(!t.merged||t.channels.length===0)return t.merged;let n=ME(t.merged,t.channels,P(e).xKey);return{...t.merged,columnNames:[...t.merged.columnNames,...n.ok.map(e=>e.name)],units:[...t.merged.units,...n.ok.map(e=>e.units)],rows:n.rows}},plotted(){return h().merged}},Ue=typeof location<`u`?location.hostname:``,We=t.license,Ge=t.licenseKey,Ke=!1,qe={},Je=e=>{r||a.set(t=>({...t,licensed:e}))},Xe=(e,t,n)=>{clearTimeout(qe[e]);let r=Math.max(0,t-Date.now()),i=r>2**31-1;qe[e]=setTimeout(()=>{i?Xe(e,t,n):n()},i?2**31-1:r)},Qe=e=>Xe(`renew`,e,()=>void et()),$e=e=>Xe(`expiry`,e*1e3+1e3,()=>{HV(Ge,Ue).then(e=>{r||Je(e.ok)})});async function et(){let e=36e5,t,n=null,i;try{t=await Promise.race([We.get(),new Promise((e,t)=>{i=setTimeout(()=>t(Error(`timeout`)),3e4)})]),n=await HV(t,Ue)}catch{}finally{clearTimeout(i)}if(r)return!1;if(n?.ok)return Ge=t,Ke=!0,Je(!0),$e(n.exp),Qe(Math.max(n.exp*1e3-168*e,Date.now()+e)),!0;console.warn(`[kymoscope] license renewal failed (${n?n.reason:`license.get failed or timed out`}): keeping the current key`);let a=await HV(Ge,Ue);return r?!1:(Je(a.ok),Qe(Date.now()+e),a.ok)}let tt=!We||t.licenseKey?HV(t.licenseKey,Ue).then(e=>(e.ok||console.warn(`[kymoscope] license ${e.reason}: showing attribution`),!Ke&&!r&&(Je(e.ok),e.ok&&We&&$e(e.exp)),e.ok)):null,nt=We?et():tt;C=!1,j();let rt={getState:N,subscribe(e){return a.subscribe(e)},on:o.on,licensed:nt,isLicensed:()=>f().licensed,setOptions(e){if(u(),t={...t,...e},e.live&&V.setRelay(e.live.relay),e.palette&&s(),e.limits){let t={...f().limits,...e.limits};a.set(e=>{let n=t.maxWorksheets===null?e.worksheets:e.worksheets.slice(0,Math.max(1,t.maxWorksheets)),r=n.some(t=>t.id===e.activeWorksheetId)?e.activeWorksheetId:n[0].id;return{...e,limits:t,activeWorksheetId:r}})}},datasets:ue,folders:pe,worksheets:me,charts:he,view:_e,mathChannels:ye,cycles:ve,live:we,video:Ce,io:Ve,history:Be,data:He,alerts:{setRules:e=>{u();let t=se.setRules(e);return a.set(e=>({...e,alertRules:se.rules()})),t},rules:se.rules,state:se.state,evaluate:(e,t)=>(u(),se.evaluate(e,t)),clearMarks:se.clearMarks},marks:{list:()=>f().marks},dispose(){if(!r){r=!0,clearTimeout(qe.renew),clearTimeout(qe.expiry),c(),i$(rt),FQ(rt),V.dispose();for(let e of f().datasets)e.source.dispose().catch(()=>void 0);o.emit(`dispose`,void 0),o.clear()}}};return X1.set(rt,{store:a,derived:h,live:V,alertLines:()=>ce(f().alertRules,f().alerts)}),rt}var X1=new WeakMap;function Z1(e){let t=X1.get(e);if(!t)throw new HE(`invalid_argument`,{reason:`not a Kymoscope engine`});return t}var Q1=2e3,$1=3;function e0(e){let t=e[0].v.fragCount,n=new Map;for(let r of e)r.v.fragCount===t&&!n.has(r.v.fragIndex)&&n.set(r.v.fragIndex,r);let r=[];for(let e=0;e<t;e++){let t=n.get(e);if(!t)return null;r.push(t.v.payload)}let i=n.get(0),a=r[0];if(t>1){a=new Uint8Array(r.reduce((e,t)=>e+t.length,0));for(let e=0,n=0;e<t;e++)a.set(r[e],n),n+=r[e].length}return{t:i.v.t,seq:i.v.seq,key:i.v.key,data:a,arrivedAt:i.at}}function t0(e){let t=[],n=0;for(;n<e.length&&e[n].v.fragIndex>0&&e[n].v.seq===e[0].v.seq;)t.push(e[n++]);let r=[],i=[],a=[];for(;n<=e.length;n++){let t=e[n];if(a.length&&(!t||t.v.seq!==a[0].v.seq)){let e=e0(a);e?r.push(e):t||(i=a),a=[]}t&&a.push(t)}return{head:t,units:r,tail:i}}var n0=class{kind=`recorded`;id;name;parentId;parentName;recordingId;chunks;fetch;open;maxBytes;cache=new Map;sizes=new Map;bytes=0;width=0;height=0;codec=``;waiting=null;checks=new Map;constructor(e){this.id=e.id,this.name=e.name,this.parentId=e.parentId,this.parentName=e.parentName??null,this.recordingId=e.recordingId,this.chunks=[...e.chunks].sort((e,t)=>e.seq-t.seq),this.fetch=e.fetchChunk,this.open=e.open,this.maxBytes=e.maxBytes??256*1024*1024}async parse(e){let t=this.chunks[e].seq,n=new Uint8Array(await this.fetch(t)),r=[],{header:i,messages:a}=le(n);if(!this.checks.has(e)){let n=i.seq===t?e===0?0:this.chunks[e-1].seq+1:-1;this.checks.set(e,{rid:i.recordingId,check:await U(i,a,e=>c(this.open,e.slice().buffer),n).catch(()=>`broken`)})}for(let e of a){let t=null;try{t=await c(this.open,e.bytes.slice().buffer)}catch{}if(t?.kind!==6)continue;let n=B$(t.plaintext);n&&(n.key&&n.fragIndex===0&&!this.codec&&(this.codec=n.codec,this.width=n.width,this.height=n.height),r.push({v:n,at:e.at}))}let o=t0(r),s=e=>e.reduce((e,t)=>e+t.v.payload.length,0);return{...o,bytes:o.units.reduce((e,t)=>e+t.data.length,0)+s(o.head)+s(o.tail)}}parsed(e){let t=this.cache.get(e);if(t)return this.cache.delete(e),this.cache.set(e,t),t;let n=this.parse(e);return this.cache.set(e,n),n.then(t=>{this.cache.get(e)===n&&(this.sizes.set(e,[t.bytes,t.units.length]),this.bytes+=t.bytes,this.evict(e))},()=>{this.cache.get(e)===n&&this.cache.delete(e)}),n}evict(e){for(let t of this.cache.keys()){if(this.bytes<=this.maxBytes)return;let n=this.sizes.get(t);t===e||!n||(this.bytes-=n[0],this.sizes.delete(t),this.cache.delete(t))}}async units(e){let t;try{t=await this.parsed(e)}catch{return[]}if(t.full)return t.full;if(!t.tail.length||e+1>=this.chunks.length)return t.full=t.units;let n=await this.parsed(e+1).catch(()=>null);if(!n)return t.units;let r=null;try{r=e0([...t.tail,...n.head.filter(e=>e.v.seq===t.tail[0].v.seq)])}catch{}return t.full=r?[...t.units,r]:t.units}async seekPlan(e){let t=this.chunks.length;if(!t)return[];let n=e*1e3,r=0;for(;r+1<t&&this.chunks[r+1].t0<=n;)r++;let i=r,a=r+1<t&&this.chunks[r+1].t0-n<Q1?r+1:r,o=(await Promise.all(Array.from({length:a-i+1},(e,t)=>this.units(i+t)))).flat(),s=()=>{let t=o.length-1;for(;t>=0&&o[t].t>e;)t--;let n=t;for(;n>=0&&!o[n].key;)n--;return[n,t]},[c,l]=s();for(let e=0;c<0&&i>0&&e<$1;e++)o=[...await this.units(--i),...o],[c,l]=s();return a+1<t&&this.units(a+1),c<0?[]:o.slice(c,l+1)}ready(){return this.waiting??=(async()=>{for(let e=0;e<Math.min(this.chunks.length,$1+1)&&!this.codec;e++)await this.units(e);this.codec||(this.waiting=null)})()}info(){let e=0;for(let[,t]of this.sizes.values())e+=t;return{width:this.width,height:this.height,codec:this.codec,latestT:this.range()?.[1]??null,lagMs:null,units:e,bytes:this.bytes}}integrity(){let e=new Map;for(let t of this.checks.values())e.set(t.rid,(e.get(t.rid)??0)+1);let t=[...e].sort((e,t)=>t[1]-e[1])[0]?.[0],n=we([...this.checks.values()].map(e=>e.rid===t?e:{rid:t,check:`broken`}));return n.verified||n.broken?n:null}range(){let e=this.chunks.length;return e?[this.chunks[0].t0/1e3,this.chunks[e-1].t1/1e3]:null}},r0=[60,300,900,1800,3600,7200,14400,28800,43200,86400],i0={60:`1m`,300:`5m`,900:`15m`,1800:`30m`,3600:`1h`,7200:`2h`,14400:`4h`,28800:`8h`,43200:`12h`,86400:`24h`};function a0(e){if(typeof e==`number`)return r0.includes(e)?e:null;if(typeof e!=`string`)return null;let t=Object.entries(i0).find(([,t])=>t===e.trim().toLowerCase());return t?Number(t[0]):null}var o0=e=>i0[e]??`${e}s`;function s0(e){for(let t=r0.length-1;t>=0;t--)if(r0[t]*e<=157286400)return r0[t];return r0[0]}function c0(e,t,n){let r=t*1e3,i=n*1e3;return Math.floor((e+i)/r)*r+r-i}var l0=1e4,u0=1e3,d0=72e4,f0=3e5,p0=3e4,m0=1e4,h0=1e4,g0=64*1024,_0=50,v0=[`360p`,`480p`,`720p`,`1080p`],y0=e=>e+6+(e>=126?2:0)+(e>65535?6:0);function b0(e,t){return t*y0(e+30)}var x0=e=>typeof e==`number`&&Number.isFinite(e)&&e>0,S0=e=>Number.isInteger(e)&&e>=1;function C0(e,t){if(!e||e.mode!==`live`&&e.mode!==`record`)return null;if(t===`camera`)return v0.includes(e.quality)&&Number.isInteger(e.fps)&&e.fps>=1&&e.fps<=60?{mode:e.mode,quality:e.quality,fps:e.fps}:null;if(!x0(e.bytes_per_sec))return null;let n=e.bytes_per_sec,r={};if(e.mode===`record`){let t=e.splitEvery===void 0?s0(n):a0(e.splitEvery);if(t===null)return null;r={split_every:t}}return e.sources===void 0?x0(e.hz)&&S0(e.channels)?{mode:e.mode,hz:e.hz,channels:e.channels,bytes_per_sec:n,...r}:null:Array.isArray(e.sources)&&e.sources.length>0&&e.sources.every(e=>x0(e?.hz)&&S0(e?.channels))?{mode:e.mode,sources:e.sources.map(({hz:e,channels:t})=>Object.freeze({hz:e,channels:t})),bytes_per_sec:n,...r}:null}var w0=class extends Error{status;code;detail;constructor(e,t,n){super(`${n} (${t})`),this.status=e,this.code=t,this.detail=n}};async function T0(e,t,n,r,i){let a;try{a=await e(`${t.replace(/\/+$/,``)}/functions/v1/${n}`,{method:`POST`,headers:r,body:i===void 0?void 0:JSON.stringify(i)})}catch(e){throw new w0(0,`network`,e?.message??String(e))}let o=await a.text(),s=null;try{s=JSON.parse(o)}catch{}if(a.status!==200)throw new w0(a.status,s?.error??`error`,s?.message??s?.error??o);return s}async function E0(e,t,n=fetch){let{auth:r}=ct(t),{token:i}=await T0(n,e,`stream-token`,{"x-api-key":r}),a=await T0(n,e,`stream-publisher`,{Authorization:`Bearer ${i}`,"Content-Type":`application/json`},{action:`usage`});return{limits:a.limits??{},usage:a.usage}}var D0=e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0)),O0=class{opts;deps;auth;secret;password;token=``;ticket=``;relayUrl=null;apiKeyId=null;projectId=null;e2ee=!1;sid=null;chain=null;held=null;salt=``;key=null;raw=null;gen=0;epoch=0;haveKey=!1;sealed=null;device=null;senderDeviceId=null;deviceRetried=!1;maxBytesPerSec=0;maxMessageBytes=g0;ws=null;open=!1;everOpen=!1;connectedAt=0;authAt=0;delay=1e3;lastToken=0;viewerCount=0;busy=!1;stopped=!1;refusal=null;heartbeatTimer=null;pingTimer=null;retryTimer=null;statusFns=new Set;viewerFns=new Set;lastStatus=``;wire;usage=null;bitrate=null;noticeCode=null;constructor(e,t){let{auth:n,secret:r}=ct(e.apiKey);if(!r)throw Error(`This API key has no encryption secret (created before keys carried one). Create a new API key in Kymoscope.`);if(e.kind===`camera`&&!e.parentStreamId)throw Error(`A camera is added to one of your live streams: choose its stream (parentStreamId).`);if(!!e.layer!=!!e.lowOf)throw Error(`A low layer needs both layer: 'low' and lowOf (its high camera's stream id).`);if(e.layer&&e.kind!==`camera`)throw Error(`Only a camera has a low layer.`);let i=C0(e.profile,e.kind);if(!i)throw Error(`profile is required: mode plus hz/channels (or sources) and bytes_per_sec, or quality/fps for a camera`);if(this.wire=Object.freeze(e.kind===`data`?{...i,sender:`browser`}:i),e.visibility===`open`&&e.password)throw Error(`An open stream has no password: anyone may watch it. Remove the password, or use visibility 'private'.`);if(e.password&&e.visibility!==`open`&&e.password.length<12&&!e.allowShortPassword)throw Error(`The stream password has ${e.password.length} characters: anyone signed in can see a general stream and try to guess a short password. Use 12 or more, or set allowShortPassword: true to accept that risk.`);this.opts=e,this.deps=t,this.auth=n,this.secret=r,this.password=e.visibility===`open`?L:e.password||r}get streamId(){return this.sid}get viewers(){return this.viewerCount}get limits(){return{maxBytesPerSec:this.maxBytesPerSec,maxMessageBytes:this.maxMessageBytes}}get usageMessage(){return this.usage}get bitrateKbps(){return this.bitrate}get profile(){return this.wire}onStatus(e){return this.statusFns.add(e),()=>{this.statusFns.delete(e)}}onViewers(e){return this.viewerFns.add(e),()=>{this.viewerFns.delete(e)}}async start(){this.emit();try{let t=await this.deps.store.load();this.salt=t?.salt??e();let n=await this.mint();this.token=n.token,this.relayUrl=n.relayUrl??null,this.maxBytesPerSec=n.maxBytesPerSec||0,this.maxMessageBytes=n.maxMessageBytes||g0,this.apiKeyId=n.apiKeyId??null;let r=n.project;this.e2ee=!!r?.e2ee;let i={};if(this.e2ee){this.projectId=r?.id??null;let e=t?.apiKeyId===this.apiKeyId;this.device=e&&t?.device||await H(),e&&t?.streamKey?{key:this.key,epoch:this.epoch,sealed:this.sealed}=t.streamKey:this.key=await Qe(Me()),i.sender_device=await this.senderDevice()}else this.raw=D0(await v(this.password,this.salt)),this.key=await Qe(this.raw),this.gen=t?.keyGen??0;let a=await this.register(t?.streamId??null,i);if(this.sid=a.stream.id,this.ticket=a.ticket,this.admitted(a),this.e2ee?(this.senderDeviceId=a.sender_device_id??null,this.projectId=a.project?.id??this.projectId,await this.save(),await this.applyProject(a.project)):(await this.save(),await this.wrapFor(a.devices)),!this.relayUrl)throw Error(`stream-token returned no relayUrl`)}catch(e){throw e instanceof w0&&e.status>=400&&e.status<500&&this.refuse(e),e}this.stopped||(this.lastToken=this.deps.now(),this.connect(),this.heartbeatTimer=setInterval(()=>{this.housekeeping()},l0),this.emit())}async send(e,t){if(this.stopped||!this.open)return!1;let n=await this.seal(e,t);return!!n&&this.sendSealed(n)}async seal(e,t){let n=this.key,r=this.e2ee?this.epoch&255:this.gen||void 0;return!n||this.e2ee&&!this.haveKey?null:new Uint8Array(await T(n,e,t,r))}sendSealed(e){let t=this.ws;if(!this.open||!t)return!1;if(this.held)return this.held.push(e),!0;try{t.send(e)}catch{return!1}return this.chained(e),!0}chained(e){let t=this.sid;if(!t)return;let n=this.deps.now();this.chain?.sid!==t&&(this.chain={sid:t,lane:new Se(t,se(),0),at:n});let r=this.chain;r.lane.add(e),!(n-r.at<u0)&&(r.at=n,this.held=[],r.lane.checkpoint().then(e=>this.seal(8,e)).catch(()=>null).then(e=>{let t=this.ws,n=this.held??[];if(this.held=null,!(!t||!this.open))try{e&&t.send(e);for(let e of n)t.send(e),this.chained(e)}catch{}}))}recordingUpload(e){return this.post(`recording-upload`,{Authorization:`Bearer ${this.token}`,"Content-Type":`application/json`},e)}stop(){!this.stopped&&this.sid&&this.call({action:`offline`,stream_id:this.sid}).catch(()=>{}),this.stopped=!0,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.retryTimer&&clearTimeout(this.retryTimer),this.heartbeatTimer=this.retryTimer=null;let e=this.ws;if(this.disconnect(),e){e.onopen=e.onmessage=e.onclose=null;try{e.close(1e3)}catch{}}}post(e,t,n){return T0(this.deps.fetch,this.opts.supabaseUrl,e,t,n)}mint(){return this.post(`stream-token`,{"x-api-key":this.auth})}call(e){return this.post(`stream-publisher`,{Authorization:`Bearer ${this.token}`,"Content-Type":`application/json`},e)}async register(e,t,n=this.salt,r=this.key){let i={action:`register`,name:this.opts.name,salt:n,key_check:await Le(r),visibility:this.opts.visibility??`private`,kind:this.opts.kind,profile:this.wire,...t};return this.opts.kind===`camera`&&(i.parent_stream_id=this.opts.parentStreamId),this.opts.layer&&(i.layer=this.opts.layer,i.low_of=this.opts.lowOf),e&&(i.stream_id=e),this.call(i)}admitted(e){this.usage=typeof e.usage?.message==`string`?e.usage.message:null,this.bitrate=typeof e.bitrate_kbps==`number`?e.bitrate_kbps:null}notice(e){let t=e?.notice,n=typeof t?.code==`string`?t.code:null;if(n&&n!==this.noticeCode)try{this.opts.onNotice?.({code:n,message:String(t.message??n)})}catch{}this.noticeCode=n}async senderDevice(){let e=this.device.publicKey;return{public_key:e,binding:await nt(await ie(this.secret),this.apiKeyId??``,e)}}async housekeeping(){if(!(this.busy||this.stopped)){this.busy=!0;try{let e=this.deps.now();if(e-this.lastToken>=d0){this.lastToken=e;try{this.token=(await this.mint()).token}catch{return}}if(this.e2ee){let e=await this.call({action:`heartbeat`,stream_id:this.sid,sender_device_id:this.senderDeviceId,epoch:this.haveKey?this.epoch:0});this.setTicket(e.ticket),this.notice(e),await this.applyProject(e.project)}else{let e=await this.call({action:`heartbeat`,stream_id:this.sid});this.setTicket(e.ticket),this.notice(e),await this.wrapFor(e.devices),e.rekey===!0&&await this.rekey()}}catch(e){e instanceof w0&&(e.status===401||e.status===403)&&this.refuse(e)}finally{this.busy=!1}}}async rekey(){let t=e(),n=D0(await v(this.password,t)),r=await Qe(n),i;try{i=await this.register(this.sid,{},t,r)}catch{return}this.salt=t,this.key=r,this.raw=n,this.gen=this.gen%255+1,await this.save(),await this.wrapFor(i.devices)}async wrapFor(e){let t=[];for(let n of e??[])try{t.push({device_id:n.id,wrapped:await l(n.public_key,this.raw,`${this.sid}|${n.id}`)})}catch{}if(t.length)try{await this.call({action:`wrap_keys`,stream_id:this.sid,keys:t.slice(0,_0)})}catch{}}async applyProject(e){if(!this.e2ee||!e)return;let t=e.key;if(!t){this.emit();return}let n=Number(t.epoch);if(this.haveKey&&n<=this.epoch)return;let r;try{r=await ot(this.device.privateKey,t.wrapped,de(this.projectId,n,this.senderDeviceId))}catch{if(this.deviceRetried)return;this.deviceRetried=!0,this.device=await H(),await this.reregister();return}let i=ce(this.sid,this.projectId,n),a=this.key,o=n===this.epoch?this.sealed:null;if(o)try{await qe(r,o,i)}catch{o=null}if(!o){let e=Me();a=await Qe(e),o=await Pe(r,e,i),e.fill(0)}try{await this.call({action:`wrap_keys`,stream_id:this.sid,sender_device_id:this.senderDeviceId,project_wrap:{epoch:n,iv:o.iv,ct:o.ct}})}catch{return}this.stopped||(this.key=a,this.sealed=o,this.epoch=n,this.haveKey=!0,await this.save(),this.emit())}async reregister(){let e;try{e=await this.register(this.sid,{sender_device:await this.senderDevice()})}catch{return}this.ticket=e.ticket,this.admitted(e),this.senderDeviceId=e.sender_device_id??null;let t=e.stream.id;if(t!==this.sid){this.sid=t;let e=this.ws;if(e){this.disconnect(),e.onopen=e.onmessage=e.onclose=null;try{e.close(1e3)}catch{}this.connect()}}await this.save(),await this.applyProject(e.project),this.deviceRetried=!1}async save(){try{await this.deps.store.save({apiKeyId:this.apiKeyId,streamId:this.sid,salt:this.salt,device:this.e2ee?this.device:null,streamKey:this.e2ee&&this.haveKey?{epoch:this.epoch,key:this.key,sealed:this.sealed}:null,...this.gen?{keyGen:this.gen}:{}})}catch{}}connect(){if(this.retryTimer=null,this.stopped)return;let e=this.relayUrl.replace(/\/+$/,``).replace(/^http(s?):\/\//,`ws$1://`),t;try{t=new this.deps.WebSocket(`${e}/v1/streams/${this.sid}/publish`,[S$,`bearer.${this.ticket}`])}catch{this.dropped();return}t.binaryType=`arraybuffer`,this.ws=t,t.onopen=()=>{t===this.ws&&(this.open=this.everOpen=!0,this.connectedAt=this.authAt=this.deps.now(),this.pingTimer=setInterval(()=>{try{t.send(`ping`)}catch{}},p0),this.emit())},t.onmessage=e=>{if(!(t!==this.ws||typeof e.data!=`string`||!e.data.startsWith(`{`)))try{let t=JSON.parse(e.data);t?.type===`viewers`&&this.setViewers(Number(t.count)||0)}catch{}},t.onclose=()=>{t===this.ws&&this.dropped()}}disconnect(){this.ws=null,this.open=!1,this.pingTimer&&clearInterval(this.pingTimer),this.pingTimer=null,this.setViewers(0)}dropped(){let e=this.open&&this.deps.now()-this.connectedAt>=h0;if(this.disconnect(),this.stopped)return;let t=0;e?this.delay=1e3:(t=this.delay,this.delay=Math.min(this.delay*2,m0)),this.retryTimer=setTimeout(()=>this.connect(),t),this.emit()}setTicket(e){this.ticket=e;let t=this.deps.now();if(!(!this.open||!this.ws||t-this.authAt<f0))try{this.ws.send(JSON.stringify({type:`auth`,token:e})),this.authAt=t}catch{}}setViewers(e){if(e!==this.viewerCount){this.viewerCount=e;for(let t of this.viewerFns)t(e);this.emit()}}refuse(e){this.refusal={code:e.code,message:e.detail},this.emit(),this.stop()}status(){return this.refusal?{phase:`refused`,...this.refusal}:this.sid?this.e2ee&&!this.haveKey?{phase:`waiting_approval`}:this.open?{phase:`live`,viewers:this.viewerCount}:this.everOpen?{phase:`reconnecting`}:{phase:`registering`}:{phase:`registering`}}emit(){let e=this.status(),t=JSON.stringify(e);if(t!==this.lastStatus){this.lastStatus=t;for(let t of this.statusFns)t(e)}}},k0={"360p":{width:640,height:360},"480p":{width:854,height:480},"720p":{width:1280,height:720},"1080p":{width:1920,height:1080}},A0={width:640,height:360,fps:15,kbps:400},j0=[`avc1.640028`,`avc1.4d0028`,`avc1.42e028`],M0=[`avc1.64001f`,`avc1.4d001f`,`avc1.42e01f`],N0=2,P0=1e3,F0=1e3;async function*I0(e){if(typeof MediaStreamTrackProcessor<`u`){let t=new MediaStreamTrackProcessor({track:e}).readable.getReader();try{for(;;){let{value:e,done:n}=await t.read();if(n)return;yield e}}finally{t.cancel().catch(()=>{})}}let t=document.createElement(`video`);t.muted=!0,t.playsInline=!0,t.srcObject=new MediaStream([e]),await t.play();try{for(;e.readyState===`live`;)await new Promise(e=>t.requestVideoFrameCallback(()=>e())),yield new VideoFrame(t,{timestamp:Math.round(performance.now()*1e3)})}finally{t.pause(),t.srcObject=null}}function L0(){let e=null;return(t,n,r)=>(e??=new OffscreenCanvas(n,r).getContext(`2d`),e.drawImage(t,0,0,n,r),new VideoFrame(e.canvas,{timestamp:t.timestamp}))}var R0=class{encoder=null;codec=``;error=null;unsubscribe=null;lastKey=-1/0;keyPending=!1;resume=!0;lastViewers=0;encoding=!1;dropped=0;seq=0;times=new Map;window=[];sending=Promise.resolve();publisher;preset;keyframeMs;Encoder;now;recorder;constructor(e,t,n,r,i,a=null){if(a&&!(e.seal&&e.sendSealed))throw Error(`A recording camera needs a LivePublisher (seal, sendSealed).`);this.recorder=a,this.publisher=e,this.preset=t,this.keyframeMs=n,this.Encoder=r,this.now=i}async configure(e){let{width:t,height:n,fps:r}=this.preset,i=e*1e3,a=null;for(let e of n>720?j0:M0){let o={codec:e,width:t,height:n,bitrate:i,framerate:r,avc:{format:`annexb`},latencyMode:`realtime`,bitrateMode:`constant`};if((await this.Encoder.isConfigSupported(o)).supported===!0){a=o;break}}return a?(this.codec=a.codec,this.encoder=new this.Encoder({output:e=>this.onChunk(e),error:e=>{this.error=e.message||String(e),this.closeEncoder()}}),this.encoder.configure(a),this.lastViewers=this.publisher.viewers,this.unsubscribe=this.publisher.onViewers(e=>{e>this.lastViewers&&(this.keyPending=!0),this.lastViewers=e}),!0):!1}ready(){let e=this.encoder;return this.encoding=!!e&&!this.error&&(this.publisher.viewers>0||!!this.recorder?.wants()),!e||!this.encoding?(this.resume=!0,!1):e.encodeQueueSize>N0?(this.dropped++,!1):!0}encode(e){let t=this.now(),n=t-this.lastKey,r=this.resume||n>=this.keyframeMs||this.keyPending&&n>=P0;r&&(this.lastKey=t,this.keyPending=this.resume=!1);let i=(performance.timeOrigin+e.timestamp/1e3)/1e3;Math.abs(i-Date.now()/1e3)>60&&(i=Date.now()/1e3),this.times.set(e.timestamp,i),this.encoder.encode(e,{keyFrame:r})}onChunk(e){let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=this.times.get(e.timestamp)??Date.now()/1e3;this.times.delete(e.timestamp);let{width:r,height:i}=this.preset,a=e.type===`key`,o=V$({key:a,t:n,seq:this.seq++,width:r,height:i,codec:this.codec,data:t}),s=this.recorder,c=this.publisher;o.forEach((e,t)=>{this.sending=this.sending.then(async()=>{if(!s)return c.send(6,e);let r=await c.seal(6,e);return r?(s.add(r,n*1e3,a&&t===0),c.viewers>0&&c.sendSealed(r)):!1}).catch(()=>!1)}),this.window.push({at:this.now(),bytes:t.length})}get queue(){return this.encoder?.state===`configured`?this.encoder.encodeQueueSize:0}stats(){let e=this.now();for(;this.window.length&&e-this.window[0].at>=F0;)this.window.shift();let t=this.window.reduce((e,t)=>e+t.bytes,0);return{fps:this.window.length,kbps:t*8/1e3,viewers:this.publisher.viewers,encoding:this.encoding}}stop(){this.encoding=!1,this.closeEncoder(),this.unsubscribe?.(),this.unsubscribe=null}closeEncoder(){this.encoder&&this.encoder.state!==`closed`&&this.encoder.close()}},z0=class{high;lowOpt;low=null;lowAt=-1/0;keyframeMs;Encoder;now;frames;scale;stopped=!1;statsFns=new Set;lastStats=-1/0;constructor(e,t={},n={}){let{quality:r,fps:i}=e.profile,a=r?k0[r]:void 0;if(!a||!i)throw Error(`A CameraSender needs a camera publisher (profile quality and fps).`);this.keyframeMs=(t.keyframeS??2)*1e3,this.Encoder=n.VideoEncoder??VideoEncoder,this.now=n.now??Date.now,this.frames=n.frames??I0,this.scale=n.scale??L0(),this.high=new R0(e,{...a,fps:i},this.keyframeMs,this.Encoder,this.now,t.recorder??null),this.lowOpt=t.low?{publisher:t.low.publisher,preset:t.low.preset??A0}:null}async start(e){let t=this.high.publisher.bitrateKbps;if(t==null)throw Error(`The camera has no bitrate: start its LivePublisher first (register answers it).`);if(!await this.high.configure(t))throw new HE(`camera_codec_unsupported`);if(this.lowOpt){let e=new R0(this.lowOpt.publisher,this.lowOpt.preset,this.keyframeMs,this.Encoder,this.now);await e.configure(this.lowOpt.publisher.bitrateKbps??this.lowOpt.preset.kbps)&&(this.low=e)}this.loop(e)}async loop(e){for await(let t of this.frames(e)){if(this.stopped){t.close();break}try{this.onFrame(t)}finally{t.close()}this.emitStats()}}onFrame(e){this.high.ready()&&this.high.encode(e);let t=this.low;if(!t)return;let n=this.now();if(n-this.lowAt<750/t.preset.fps||!t.ready())return;this.lowAt=n;let r=this.scale(e,t.preset.width,t.preset.height);try{t.encode(r)}finally{r.close()}}stats(){return{...this.high.stats(),dropped:this.high.dropped,queue:this.high.queue,error:this.high.error,low:this.low?this.low.stats():null}}onStats(e){return this.statsFns.add(e),()=>{this.statsFns.delete(e)}}emitStats(){let e=this.now();if(e-this.lastStats<F0||!this.statsFns.size)return;this.lastStats=e;let t=this.stats();for(let e of this.statsFns)e(t)}stop(){this.stopped=!0,this.high.stop(),this.low?.stop()}},B0=new TextEncoder,V0={appstream2:`appstream`,cloudhsmv2:`cloudhsm`,email:`ses`,marketplace:`aws-marketplace`,mobile:`AWSMobileHubService`,pinpoint:`mobiletargeting`,queue:`sqs`,"git-codecommit":`codecommit`,"mturk-requester-sandbox":`mturk-requester`,"personalize-runtime":`personalize`},H0=new Set([`authorization`,`content-type`,`content-length`,`user-agent`,`presigned-expires`,`expect`,`x-amzn-trace-id`,`range`,`connection`]),U0=class{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:n,service:r,region:i,cache:a,retries:o,initRetryMs:s}){if(e==null)throw TypeError(`accessKeyId is a required option`);if(t==null)throw TypeError(`secretAccessKey is a required option`);this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=n,this.service=r,this.region=i,this.cache=a||new Map,this.retries=o??10,this.initRetryMs=s||50}async sign(e,t){if(e instanceof Request){let{method:n,url:r,headers:i,body:a}=e;t=Object.assign({method:n,url:r,headers:i},t),t.body==null&&i.has(`Content-Type`)&&(t.body=a!=null&&i.has(`X-Amz-Content-Sha256`)?a:await e.clone().arrayBuffer()),e=r}let n=new W0(Object.assign({url:e.toString()},t,this,t&&t.aws)),r=Object.assign({},t,await n.sign());delete r.aws;try{return new Request(r.url.toString(),r)}catch(e){if(e instanceof TypeError)return new Request(r.url.toString(),Object.assign({duplex:`half`},r));throw e}}async fetch(e,t){for(let n=0;n<=this.retries;n++){let r=fetch(await this.sign(e,t));if(n===this.retries)return r;let i=await r;if(i.status<500&&i.status!==429)return i;await new Promise(e=>setTimeout(e,Math.random()*this.initRetryMs*2**n))}throw Error(`An unknown error occurred, ensure retries is not negative`)}},W0=class{constructor({method:e,url:t,headers:n,body:r,accessKeyId:i,secretAccessKey:a,sessionToken:o,service:s,region:c,cache:l,datetime:u,signQuery:d,appendSessionToken:f,allHeaders:p,singleEncode:m}){if(t==null)throw TypeError(`url is a required option`);if(i==null)throw TypeError(`accessKeyId is a required option`);if(a==null)throw TypeError(`secretAccessKey is a required option`);this.method=e||(r?`POST`:`GET`),this.url=new URL(t),this.headers=new Headers(n||{}),this.body=r,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=o;let h,g;(!s||!c)&&([h,g]=X0(this.url,this.headers)),this.service=s||h||``,this.region=c||g||`us-east-1`,this.cache=l||new Map,this.datetime=u||new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),this.signQuery=d,this.appendSessionToken=f||this.service===`iotdevicegateway`,this.headers.delete(`Host`),this.service===`s3`&&!this.signQuery&&!this.headers.has(`X-Amz-Content-Sha256`)&&this.headers.set(`X-Amz-Content-Sha256`,`UNSIGNED-PAYLOAD`);let _=this.signQuery?this.url.searchParams:this.headers;if(_.set(`X-Amz-Date`,this.datetime),this.sessionToken&&!this.appendSessionToken&&_.set(`X-Amz-Security-Token`,this.sessionToken),this.signableHeaders=[`host`,...this.headers.keys()].filter(e=>p||!H0.has(e)).sort(),this.signedHeaders=this.signableHeaders.join(`;`),this.canonicalHeaders=this.signableHeaders.map(e=>e+`:`+(e===`host`?this.url.host:(this.headers.get(e)||``).replace(/\s+/g,` `))).join(`
|
|
618
|
-
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,`aws4_request`].join(`/`),this.signQuery&&(this.service===`s3`&&!_.has(`X-Amz-Expires`)&&_.set(`X-Amz-Expires`,`86400`),_.set(`X-Amz-Algorithm`,`AWS4-HMAC-SHA256`),_.set(`X-Amz-Credential`,this.accessKeyId+`/`+this.credentialString),_.set(`X-Amz-SignedHeaders`,this.signedHeaders)),this.service===`s3`)try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g,` `))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,`/`);m||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,`/`)),this.encodedPath=
|
|
612
|
+
`),j=St(()=>{let e=i.filter(e=>e.kind!==`memory`).flatMap(e=>jz(e.schema));return e.length?e:null},[i]),M=St(()=>i.some(e=>e.kind!==`memory`)||!_&&i.some(e=>e.data.rows.length>OZ),[i,_]),N=St(()=>lZ(f.connections.filter(e=>r.includes(e.id)),i.length,M,d,o),[M,i,f.connections,r,o,d]),P=St(()=>{if(!_||i.length===0||M)return null;let e=i.map((e,t)=>{let n=e.data.rows;return{rows:n.length>0&&typeof n[0][d]==`number`?n:O[t]??n,offset:o[e.id]??0}});if(!N)for(let t of f.connections)r.includes(t.id)&&e.push({rows:t.dataset.rows,offset:o[t.id]??0});return LZ(e,d)},[_,i,M,O,o,d,f.connections,r,N]),F=C&&`okByPart`in C?C.okByPart:void 0,I=St(()=>{if(!M)return[];let e=T.map((e,t)=>({live:`live`in e&&!!e.live,source:`live`in e&&e.live?e.live.source:e.source,columnSet:new Set(`live`in e&&e.live?e.data.columnNames:e.schema.map(e=>e.name)),keySuffix:E?`__${t}`:``,xOffset:o[e.id]??0,key:`${e.id}|${E?t:``}`}));return T.forEach((t,n)=>{let r=F?.[n],i=O[n];`live`in t&&t.live||!r?.length||!i||e.push({...e[n],live:!1,source:PZ(i,r,d),columnSet:new Set([d,...r]),key:`${e[n].key}|channels`})}),e},[M,T,E,o,F,O,d]),L=St(()=>{let e=C?.parts??(w?[w]:[]),t=new Set;for(let n of e)for(let e of fZ(n.columnNames,n.rows))t.add(e);let n=w?w.columnNames.filter(e=>t.has(e)):[],r=[...new Set(j?[...n,...j]:n)];if(A===``)return r;let i=new Set(r),a=A.split(`
|
|
613
|
+
`).filter(e=>!i.has(e));return a.length?[...r,...a]:r},[k,A,j]),R=St(()=>{let e=[];for(let t of l){if(t.kind!==`multiband`)continue;let n=u[t.id],r=n&&n.kind===`multiband`?n.series:[];e.push([t.id,[...new Set(r.map(e=>e.column).filter(e=>e!==d))]])}return JSON.stringify(e)},[l,u,d]),z=St(()=>{let e={};if(!w||M)return e;for(let[t,n]of JSON.parse(R)){let r=[];if(n.length>0)if(!E)r.push(m(w.rows,d,n,OZ));else{let e=Math.max(1,Math.floor(OZ/T.length));for(let t=0;t<T.length;t++){let i=T[t];if(N&&`live`in i&&i.live)continue;let a=O[t]??i.data.rows;r.push(m(a,d,n,e,`__${t}`,o[i.id]??0))}}e[t]=r}return e},[w,R,d,E,T,o,O,N,M]),B=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`multiband`)continue;let n=u[t.id],r=(n&&n.kind===`multiband`?n.series:[]).filter(e=>e.column!==d),i=n&&n.kind===`multiband`?n.layout:`overlay`,a=e=>IZ(e,i),l;if(!E)l=a(r);else{let e=a(r);l=[];for(let t=0;t<T.length;t++){let n=iB(s,T[t].id,t,c);for(let r of e)l.push({...r,id:`${r.id}__${t}`,column:`${r.column}__${t}`,color:n})}}let f=z[t.id]??[],p=E&&n?.kind===`multiband`&&n.envelope?r.flatMap(e=>{let t=oZ(f.flatMap((t,n)=>{let r=t.cols.get(`${e.column}__${n}`);return r?[{x:t.x,y:r}]:[]}),MZ);return t?[{seriesId:e.id,color:e.color,...t}]:[]}):void 0,m=T.flatMap((e,t)=>`bands`in e&&e.bands?SZ(e,d,r,E?iB(s,e.id,t,c):void 0,o[e.id]??0):[]),h=[...p??[],...m];e[t.id]={effectiveSeries:l,points:f,envelopes:h.length?h:void 0}}return e},[w,l,u,d,E,T,s,c,o,z]),V=St(()=>{let e={pts:{},colorMeta:{},datasetColors:{}};if(!w)return e;let t={},r={},i={},a=jZ,o=T.map((e,t)=>({id:e.id,rows:O[t]??p[e.id]??e.data.rows,full:a(e)})),f={id:`single`,rows:w.rows,full:T.length===1?a(T[0]):void 0};for(let e of l){if(e.kind!==`xyscatter`)continue;let a=u[e.id];if(!a||a.kind!==`xyscatter`)continue;let{xyXCol:l,xyYCol:p}=a;if(!l||!p){t[e.id]={length:0,x:[],y:[]};continue}if(E){let{cols:r,colors:a}=aG(o,l,p,{xKey:d,viewXRange:n,colorOverrides:s,palette:c});t[e.id]=r,i[e.id]=a;continue}let m=iG(f,l,p,{xKey:d,viewXRange:n,colorCol:a.xyColorCol||void 0});t[e.id]=m?.cols??{length:0,x:[],y:[]},m?.color&&(r[e.id]=m.color)}return{pts:t,colorMeta:r,datasetColors:i}},[w,l,u,n,d,E,T,p,s,c,O]),ee=K(new Map),te=St(()=>{let e={};if(!w)return e;let t={length:0,x:[],y:[],z:[]},{rows:r}=w,i=D;for(let a of l){if(a.kind!==`xyzmesh`)continue;let o=u[a.id];if(!o||o.kind!==`xyzmesh`)continue;if(o.xyzMode===`matrix`){let n=(o.xyzColumns??[]).flatMap(e=>{let t=QW(r,e,i);return t?[t]:[]}),s=n[0]?.length??0,c=n.length;if(s<2||c<2){e[a.id]={points:t};continue}let l=ee.current.get(a.id);l?.length!==s*c&&ee.current.set(a.id,l=new Float32Array(s*c)),n.forEach((e,t)=>l.set(e.length===s?e:e.subarray(0,s),t*s));let u=QW(r,d,i),f=u&&!(o.xyzColumns??[]).includes(d)&&u.length>=s&&Number.isFinite(u[0])&&Number.isFinite(u[s-1])?[u[0],u[s-1]]:[0,s-1];e[a.id]={points:t,surface:{w:s,h:c,values:l,x:f,y:[0,c-1]}};continue}let{xyzXCol:s,xyzYCol:c,xyzZCol:l}=o,f=s?QW(r,s,i):void 0,p=c?QW(r,c,i):void 0,m=l?QW(r,l,i):void 0;if(!f||!p||!m){e[a.id]={points:t};continue}let h=n?QW(r,d,i):void 0;if(!n||!h){e[a.id]={points:{length:Math.min(f.length,p.length,m.length),x:f,y:p,z:m}};continue}let[g,_]=n,v=0;for(let e=0;e<h.length;e++)h[e]>=g&&h[e]<=_&&v++;let y=new Float64Array(v),b=new Float64Array(v),x=new Float64Array(v);for(let e=0,t=0;e<h.length;e++)h[e]>=g&&h[e]<=_&&(y[t]=f[e],b[t]=p[e],x[t]=m[e],t++);e[a.id]={points:{length:v,x:y,y:b,z:x}}}return e},[w,l,u,n,d,D]),H=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`histogram`)continue;let n=u[t.id];e[t.id]=n?.kind===`histogram`&&n.histColumn&&$W(w.rows,n.histColumn,D)||new Float64Array}return e},[w,l,u,D]),ne=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`polar`)continue;let n=u[t.id],r=n?.kind===`polar`&&n.polarAngleCol?QW(w.rows,n.polarAngleCol,D):void 0,i=n?.kind===`polar`&&n.polarRadiusCol?QW(w.rows,n.polarRadiusCol,D):void 0;e[t.id]=r&&i?{angles:r,radii:i}:{angles:[],radii:[]}}return e},[w,l,u,D]),re=(e,t,n,r)=>{let i=t&&$W(e,t,D)||new Float64Array,a=n?QW(e,n,D):void 0;return{signal:i,rate:a&&tG(a)||parseFloat(r)||1}},ie=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`spectrum`)continue;let n=u[t.id];n?.kind===`spectrum`&&(e[t.id]=re(w.rows,n.specSignalCol,n.specTimeCol,n.specSampleRate))}return e},[w,l,u,D]),U=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`boxplot`)continue;let n=u[t.id];e[t.id]=n?.kind===`boxplot`&&n.boxValueCol?eG(w.rows,n.boxValueCol,n.boxGroupCol||void 0,D):[]}return e},[w,l,u,D]),ae=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`spectrogram`)continue;let n=u[t.id];n?.kind===`spectrogram`&&(e[t.id]=re(w.rows,n.sgSignalCol,n.sgTimeCol,n.sgSampleRate))}return e},[w,l,u,D]),oe=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`heatmap`)continue;let n=u[t.id];if(!n||n.kind!==`heatmap`){e[t.id]={cells:[],xLabels:[],yLabels:[]};continue}if(n.hmMode===`matrix`){let r=w.rows,i=n.hmColumns.flatMap(e=>{let t=QW(r,e,D);return t?[{name:e,v:t}]:[]}),a=i.reduce((e,t)=>Math.min(e,t.v.length),i.length?1/0:0),o=QW(r,d,D),s,c;if(n.hmSpacing===`values`){o&&hJ(o.subarray(0,a))&&(s=Float64Array.from(o.subarray(0,a)));let e=i.map(e=>({c:e,v:parseFloat(e.name)})).sort((e,t)=>t.v-e.v);e.length&&hJ(e.map(e=>e.v).reverse())&&(i=e.map(e=>e.c),c=Float64Array.from(e,e=>e.v))}let l=i.length,u=new Float32Array(a*l);i.forEach((e,t)=>u.set(e.v.subarray(0,a),t*a));let f=e=>String(o?+o[e].toPrecision(6):e+1);e[t.id]={cells:[],xLabels:[],yLabels:i.map(e=>e.name),grid:{w:a,h:l,values:u,xLabels:f,yLabels:i.map(e=>e.name)},xCentres:s,yCentres:c}}else if(n.hmMode===`correlation`){let r=n.hmColumns.filter(e=>L.includes(e));if(r.length<2){e[t.id]={cells:[],xLabels:r,yLabels:r};continue}let i=r.map(e=>{let t=[];for(let n of w.rows){let r=n[e];typeof r==`number`&&Number.isFinite(r)&&t.push(r)}return t}),a=i.map(e=>e.reduce((e,t)=>e+t,0)/(e.length||1)),o=[];for(let e=0;e<r.length;e++)for(let t=0;t<r.length;t++){let n=i[e],s=i[t],c=a[e],l=a[t],u=Math.min(n.length,s.length),d=0,f=0,p=0;for(let e=0;e<u;e++){let t=n[e]-c,r=s[e]-l;d+=t*r,f+=t*t,p+=r*r}let m=f>0&&p>0?d/Math.sqrt(f*p):+(e===t);o.push({x:r[t],y:r[e],value:m})}e[t.id]={cells:o,xLabels:r,yLabels:r}}else if(n.hmMode===`binned`||n.hmMode===`count`){let{hmXCol:r,hmYCol:i}=n,a=n.hmMode===`count`?``:n.hmValueCol;if(!r||!i||n.hmMode===`binned`&&!a){e[t.id]={cells:[],xLabels:[],yLabels:[]};continue}let o=e=>{let t=parseFloat(e);return Number.isFinite(t)?t:void 0};e[t.id]=TZ(w.rows,{xCol:r,yCol:i,valueCol:a,xBins:n.hmXBins,yBins:n.hmYBins,xMin:o(n.hmXMin),xMax:o(n.hmXMax),yMin:o(n.hmYMin),yMax:o(n.hmYMax)})}else{let{hmXCol:r,hmYCol:i,hmValueCol:a}=n;if(!r||!i||!a){e[t.id]={cells:[],xLabels:[],yLabels:[]};continue}let o=new Map,s=new Set,c=new Set;for(let e of w.rows){let t=String(e[r]??``),n=String(e[i]??``),l=e[a];if(typeof l!=`number`||!Number.isFinite(l))continue;s.add(t),c.add(n);let u=`${t}\0${n}`,d=o.get(u)??{sum:0,count:0};o.set(u,{sum:d.sum+l,count:d.count+1})}let l=e=>{let t=[...e];return t.every(e=>e.trim()!==``&&Number.isFinite(Number(e)))?t.sort((e,t)=>Number(e)-Number(t)):t.sort()},u=l(s),d=l(c),f,p;if(n.hmSpacing===`values`){let e=Float64Array.from(u,Number),t=Float64Array.from(d,Number);hJ(e)&&(f=e),hJ(t)&&(d=[...d].reverse(),p=t.reverse())}let m=[];for(let e of d)for(let t of u){let n=o.get(`${t}\0${e}`);m.push({x:t,y:e,value:n?n.sum/n.count:0})}e[t.id]={cells:m,xLabels:u,yLabels:d,xCentres:f,yCentres:p}}}return e},[w,l,u,L,d,D]),se=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`violin`)continue;let n=u[t.id];e[t.id]=n?.kind===`violin`&&n.vlValueCol?eG(w.rows,n.vlValueCol,n.vlGroupCol||void 0,D):[]}return e},[w,l,u,D]),ce=St(()=>{let e={};if(!w)return e;let{rows:t}=w;for(let n of l){if(n.kind!==`confusion`)continue;let r=u[n.id];if(!r||r.kind!==`confusion`||!r.cfActualCol||!r.cfPredictedCol){e[n.id]={actual:[],predicted:[]};continue}let{cfActualCol:i,cfPredictedCol:a}=r,o=D?.get(i),s=D?.get(a);if(o&&s){e[n.id]={actual:o,predicted:s};continue}let c=[],l=[];for(let e of t){let t=e[i],n=e[a];t!==void 0&&n!==void 0&&(c.push(t),l.push(n))}e[n.id]={actual:c,predicted:l}}return e},[w,l,u,D]),le=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`roc`)continue;let n=u[t.id],r=n?.kind===`roc`&&n.rocScoreCol?QW(w.rows,n.rocScoreCol,D):void 0,i=n?.kind===`roc`&&n.rocLabelCol?QW(w.rows,n.rocLabelCol,D):void 0;e[t.id]=r&&i?{scores:r,labels:i}:{scores:[],labels:[]}}return e},[w,l,u,D]),ue=St(()=>{let e={};if(!w)return e;let{rows:t}=w;for(let n of l){if(n.kind!==`losscurve`)continue;let r=u[n.id];if(!r||r.kind!==`losscurve`){e[n.id]={xValues:[],series:[]};continue}let{lcXCol:i,lcLeftCols:a,lcRightCols:o}=r,s=[...a.map(e=>({...e,axis:`left`})),...o.map(e=>({...e,axis:`right`}))].map(({column:e,color:n,axis:r})=>({label:e,color:n,values:QW(t,e,D)??new Float64Array,axis:r})),c=s[0]?.values.length??t.length,l=i&&QW(t,i,D)||Float64Array.from({length:c},(e,t)=>t);e[n.id]={xValues:l,series:s}}return e},[w,l,u,D]),de=St(()=>{let e={};if(!w)return e;let{rows:t}=w;for(let n of l){if(n.kind!==`controlchart`)continue;let r=u[n.id],i=r?.kind===`controlchart`&&r.ccValueCol?QW(t,r.ccValueCol,D):void 0;if(!r||r.kind!==`controlchart`||!i){e[n.id]={length:0,value:[]};continue}let a=0;for(let e=0;e<i.length;e++)i[e]-i[e]===0&&a++;let o=a===i.length?null:new Uint32Array(a),s=o?new Float64Array(a):i;if(o)for(let e=0,t=0;e<i.length;e++)i[e]-i[e]===0&&(o[t]=e,s[t++]=i[e]);let c=r.ccSubgroupCol,l=c?D?.get(c):void 0,d=e=>o?o[e]:e;e[n.id]={length:a,value:s,subgroup:c?e=>String(l?l[d(e)]:t[d(e)]?.[c]??``):void 0}}return e},[w,l,u,D]),fe=St(()=>{let e={};if(!w)return e;let{rows:t}=w;for(let n of l){if(n.kind!==`parallelcoords`)continue;let r=u[n.id];if(!r||r.kind!==`parallelcoords`||r.pcColumns.length<2){e[n.id]={length:0,columns:[]};continue}let i=r.pcColumns.map(e=>QW(t,e,D)??new Float64Array),a=Math.min(...i.map(e=>e.length)),o={length:a,columns:i},s=r.pcColorByCol;if(s)if(L.includes(s))o.colorValue=QW(t,s,D);else{let e=new Map,n=new Int32Array(a);for(let r=0;r<a;r++){let i=String(t[r]?.[s]??``),a=e.get(i);a===void 0&&e.set(i,a=e.size),n[r]=a}o.colorIndex=n,o.colorLabels=[...e.keys()]}e[n.id]=o}return e},[w,l,u,L,D]),pe=St(()=>{let e={};if(!w)return e;let{rows:t}=w,n={length:0,x:[],y:[]};for(let r of l){if(r.kind!==`embedding`)continue;let i=u[r.id];if(!i||i.kind!==`embedding`||!i.emXCol||!i.emYCol){e[r.id]=n;continue}let{emXCol:a,emYCol:o,emColorCol:s,emColorMode:c,emLabelCol:l}=i,d=QW(t,a,D),f=QW(t,o,D);if(!d||!f){e[r.id]=n;continue}let p=Math.min(d.length,f.length),m={length:p,x:d,y:f};if(s)if(c===`numeric`&&L.includes(s))m.colorValue=QW(t,s,D);else{let e=D?.get(s),n=new Map,r=new Int32Array(p);for(let i=0;i<p;i++){let a=String(e?e[i]:t[i]?.[s]??``),o=n.get(a);o===void 0&&n.set(a,o=n.size),r[i]=o}m.colorIndex=r,m.colorLabels=[...n.keys()]}if(l){let e=D?.get(l);m.label=e?t=>String(e[t]):e=>String(t[e]?.[l]??``)}e[r.id]=m}return e},[w,l,u,L,D]),me=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`flamegraph`)continue;let n=u[t.id];if(!n||n.kind!==`flamegraph`||!n.fgNameCol||!n.fgValueCol){e[t.id]=[];continue}let r=[];for(let e of w.rows){let t=String(e[n.fgNameCol]??``),i=n.fgParentCol?String(e[n.fgParentCol]??``):``,a=e[n.fgValueCol];!t||typeof a!=`number`||!Number.isFinite(a)||r.push({name:t,parent:i,value:a})}e[t.id]=r}return e},[w,l,u]),he=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`barchart`)continue;let n=u[t.id];if(!n||n.kind!==`barchart`||n.bcValueCols.length===0){e[t.id]={groups:[],seriesNames:[]};continue}let r=n.bcValueCols;if(n.bcCategoryCol){let i=new Map;for(let e of w.rows){let t=String(e[n.bcCategoryCol]??`(blank)`);i.has(t)||i.set(t,r.map(()=>0));let a=new Map,o=i.get(t);for(let t=0;t<r.length;t++){let n=e[r[t]];typeof n==`number`&&Number.isFinite(n)&&(o[t]+=n),a.set(r[t],(a.get(r[t])??0)+1)}}e[t.id]={groups:Array.from(i.entries()).map(([e,t])=>({label:e,values:t})),seriesNames:r}}else{let n=w.rows,i=r.map(e=>QW(n,e,D)),a=i.reduce((e,t)=>t?Math.min(e,t.length):e,1/0),o=Number.isFinite(a)?a:n.length,s=i.map(e=>e??new Float64Array(o).fill(NaN));e[t.id]={groups:[],columns:{length:o,values:s},seriesNames:r}}}return e},[w,l,u,D]),ge=St(()=>{let e={};if(!w)return e;let{rows:t}=w;for(let n of l){if(n.kind!==`radar`)continue;let r=u[n.id];if(!r||r.kind!==`radar`||r.rdAxesCols.length<3){e[n.id]={axes:[],series:[]};continue}let i=r.rdAxesCols,a=i.map(e=>QW(t,e,D));if(r.rdGroupCol){let o=r.rdGroupCol,s=D?.get(o),c=s?s.length:t.length,l=new Map;for(let e=0;e<c;e++){let n=s?s[e]===s[e]?String(s[e]):`(blank)`:String(t[e][o]??`(blank)`),r=l.get(n);r||l.set(n,r=i.map(()=>0));for(let t=0;t<i.length;t++){let n=a[t]?.[e]??NaN;n-n===0&&(r[t]+=n)}}e[n.id]={axes:i,series:Array.from(l.entries()).map(([e,t])=>({name:e,values:t}))}}else{let t=a.map(e=>{let t=0,n=0;if(e)for(let r=0;r<e.length;r++)e[r]-e[r]===0&&(t+=e[r],n++);return t/(n||1)});e[n.id]={axes:i,series:[{name:`Series 1`,values:t}]}}}return e},[w,l,u,D]),_e=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`areachart`)continue;let n=u[t.id];if(!n||n.kind!==`areachart`||n.acYCols.length===0){e[t.id]=[];continue}let r=w.rows,i=n.acYCols.map(e=>QW(r,e,D)),a=i[0]?.length??r.length,o=(n.acXCol?QW(r,n.acXCol,D):void 0)??VZ(a);e[t.id]=n.acYCols.flatMap((e,t)=>{let n=i[t];return n?[{name:e,x:o,y:n}]:[]})}return e},[w,l,u,D]),ve=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`cdfchart`)continue;let n=u[t.id];if(!n||n.kind!==`cdfchart`){e[t.id]=[];continue}e[t.id]=n.cdValueCols.map(e=>({name:e,values:$W(w.rows,e,D)??new Float64Array}))}return e},[w,l,u,D]),ye=St(()=>{let e={};if(!w)return e;let{rows:t}=w,n={length:0,x:[],y:[],size:[]};for(let r of l){if(r.kind!==`bubblechart`)continue;let i=u[r.id];if(!i||i.kind!==`bubblechart`||!i.bbXCol||!i.bbYCol||!i.bbSizeCol){e[r.id]=n;continue}let a=QW(t,i.bbXCol,D),o=QW(t,i.bbYCol,D),s=QW(t,i.bbSizeCol,D);if(!a||!o||!s){e[r.id]=n;continue}let c=Math.min(a.length,o.length,s.length),l=new Float64Array(c);for(let e=0;e<c;e++)l[e]=s[e]===s[e]?Math.max(0,s[e]):NaN;let d=new Float64Array(c);for(let e=0;e<c;e++)d[e]=l[e]===l[e]?a[e]:NaN;let f={length:c,x:d,y:o,size:l};if(i.bbColorCol){if(i.bbColorMode===`numeric`)f.colorValue=QW(t,i.bbColorCol,D);else if(i.bbColorMode===`categorical`){let e=D?.get(i.bbColorCol),n=new Map,r=new Int32Array(c);for(let a=0;a<c;a++){let o=String(e?e[a]:t[a]?.[i.bbColorCol]??``),s=n.get(o);s===void 0&&n.set(o,s=n.size),r[a]=s}f.colorIndex=r,f.colorLabels=[...n.keys()]}}e[r.id]=f}return e},[w,l,u,D]),be=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`treemap`)continue;let n=u[t.id];if(!n||n.kind!==`treemap`||!n.tmNameCol||!n.tmValueCol){e[t.id]=[];continue}let r=[];for(let e of w.rows){let t=String(e[n.tmNameCol]??``),i=n.tmParentCol?String(e[n.tmParentCol]??``):``,a=e[n.tmValueCol];!t||typeof a!=`number`||!Number.isFinite(a)||r.push({name:t,parent:i,value:a})}e[t.id]=r}return e},[w,l,u]),xe=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`sankey`)continue;let n=u[t.id];if(!n||n.kind!==`sankey`||!n.skSourceCol||!n.skTargetCol||!n.skValueCol){e[t.id]={nodeNames:[],links:[]};continue}let r=new Set,i=[];for(let e of w.rows){let t=String(e[n.skSourceCol]??``),a=String(e[n.skTargetCol]??``),o=e[n.skValueCol];!t||!a||typeof o!=`number`||!Number.isFinite(o)||(r.add(t),r.add(a),i.push({source:t,target:a,value:o}))}e[t.id]={nodeNames:Array.from(r),links:i}}return e},[w,l,u]),Se=St(()=>{let e={};if(!w)return e;for(let t of l){if(t.kind!==`calibration`)continue;let n=u[t.id],r=n?.kind===`calibration`&&n.cbScoreCol?QW(w.rows,n.cbScoreCol,D):void 0,i=n?.kind===`calibration`&&n.cbLabelCol?QW(w.rows,n.cbLabelCol,D):void 0;if(!n||n.kind!==`calibration`||!r||!i){e[t.id]=[];continue}let a=Math.max(2,n.cbBins),o=new Float64Array(a),s=new Float64Array(a);for(let e=0;e<Math.min(r.length,i.length);e++){let t=r[e],n=i[e];if(t-t!==0||n-n!==0)continue;let c=Math.max(0,Math.min(a-1,Math.floor(t*a)));o[c]+=n,s[c]++}e[t.id]=Array.from({length:a},(e,t)=>({center:(t+.5)/a,actual:s[t]>0?o[t]/s[t]:0,count:s[t]})).filter(e=>e.count>0)}return e},[w,l,u,D]),Ce=St(()=>{let e={};if(!w)return e;let t={length:0,theoretical:[],sample:[]},n=e=>{let t=$W(w.rows,e,D);return t?Float64Array.from(t).sort():new Float64Array};for(let r of l){if(r.kind!==`qqplot`)continue;let i=u[r.id];if(!i||i.kind!==`qqplot`||!i.qqValueCol){e[r.id]=t;continue}let a=n(i.qqValueCol),o=a.length;if(o===0){e[r.id]=t;continue}if(i.qqMode===`column`&&i.qqRefCol){let t=n(i.qqRefCol),s=Math.min(o,t.length);e[r.id]={length:s,theoretical:t.subarray(0,s),sample:a.subarray(0,s)}}else{let t=e=>{let t=[2.515517,.802853,.010328],n=[1.432788,.189269,.001308],r=Math.sqrt(-2*Math.log(Math.min(e,1-e))),i=r-(t[0]+t[1]*r+t[2]*r*r)/(1+n[0]*r+n[1]*r*r+n[2]*r*r*r);return e<.5?-i:i},n=new Float64Array(o);for(let e=0;e<o;e++)n[e]=t((e+.5)/o);e[r.id]={length:o,theoretical:n,sample:a}}}return e},[w,l,u,D]),we=St(()=>{if(!w)return{};let e={};for(let t of l){if(t.kind!==`gantt`)continue;let n=u[t.id];if(!n||n.kind!==`gantt`||!n.gtLabelCol||!n.gtStartCol||!n.gtEndCol){e[t.id]=[];continue}let r=[];for(let e of w.rows){let t=String(e[n.gtLabelCol]??``),i=e[n.gtStartCol],a=e[n.gtEndCol];if(!t||typeof i!=`number`||typeof a!=`number`||!Number.isFinite(i)||!Number.isFinite(a))continue;let o={label:t,start:i,end:a};n.gtGroupCol&&e[n.gtGroupCol]!==void 0&&(o.group=String(e[n.gtGroupCol])),r.push(o)}e[t.id]=r}return e},[w,l,u]),Te=w&&w.columnNames.indexOf(d)>=0?w.units[w.columnNames.indexOf(d)]??``:``,Ee=St(()=>w?RZ(w,E?T.length:0):{},[w,E,T]);return{dataset:b,datasetWithChannels:w,multiDatasetMode:E,numericCols:L,anyDuckDb:M,duckDbLayers:I,liveConn:v,liveOverlays:N,hasLiveSelected:_,staticXRange:P,xUnit:Te,columnUnits:Ee,multibandDataByPanel:B,xyPointsByPanel:V,xyzPointsByPanel:te,histogramDataByPanel:H,polarDataByPanel:ne,spectrumDataByPanel:ie,boxplotDataByPanel:U,spectrogramDataByPanel:ae,heatmapDataByPanel:oe,violinDataByPanel:se,confusionDataByPanel:ce,rocDataByPanel:le,lossCurveDataByPanel:ue,controlChartDataByPanel:de,parallelCoordsDataByPanel:fe,embeddingDataByPanel:pe,flameGraphDataByPanel:me,barChartDataByPanel:he,radarDataByPanel:ge,areaChartDataByPanel:_e,cdfChartDataByPanel:ve,bubbleChartDataByPanel:ye,treemapDataByPanel:be,sankeyDataByPanel:xe,calibrationDataByPanel:Se,qqPlotDataByPanel:Ce,ganttDataByPanel:we,gaugeDataByPanel:St(()=>{let e={};if(!w)return e;let t=e=>e.trim()!==``&&Number.isFinite(Number(e))?Number(e):void 0;for(let n of l){if(n.kind!==`gauge`)continue;let r=u[n.id];if(r?.kind!==`gauge`){e[n.id]=[];continue}e[n.id]=r.ggGauges.flatMap(e=>{let n=e.column,r=n?QW(w.rows,n,D):void 0;if(!r)return[];let i=1/0,a=-1/0,o=0,s=0,c=NaN;for(let e=0;e<r.length;e++){let t=r[e];t-t===0&&(t<i&&(i=t),t>a&&(a=t),o+=t,s++,c=t)}let l=s===0?NaN:e.value===`mean`?o/s:e.value===`min`?i:e.value===`max`?a:c,[u,d]=UZ(s?i:0,s?a:1,t(e.min),t(e.max));return[{name:n,unit:Ee[n]??``,value:l,min:u,max:d,alarm:e.alarm??null,color:e.color,style:e.style,fromZero:e.fill===`zero`,colorMode:e.colorMode,stops:e.stops,stat:e.value}]})}return e},[w,l,u,D,Ee])}}function UZ(e,t,n,r){t<=e&&(t=e+1);let i=Pz(t-e,5),a=n??Math.floor(e/i)*i,o=r??Math.ceil(t/i)*i;return o>a?[a,o]:[a,a+1]}var WZ=`#fb7185`,GZ=2500;function KZ(e){let t=[],n=(e,r)=>{if(typeof e==`string`){e&&(r===`column`||/(Col|Cols|Column|Columns)$/.test(r))&&t.push(e);return}if(Array.isArray(e)){for(let t of e)n(t,r);return}if(e&&typeof e==`object`)for(let[t,r]of Object.entries(e))t!==`addColumn`&&n(r,t)};return n(e,``),[...new Set(t)]}function qZ(e){let t=JZ(e);if(t.status!==`empty`||!e.data.dataset)return t;let n=new Set([...e.data.datasetWithChannels?.columnNames??[],...e.data.numericCols]);return KZ(e.settings).some(e=>!n.has(e))?{...t,status:`missing`}:t}function JZ(e){let{panel:t,data:r,settings:i}=e;if(t.kind===`camera`)return{status:`ready`,data:null,node:q(YX,{settings:i?.kind===`camera`?i:$n(),live:e.live??[],selection:e.selection??[],viewXRange:e.viewXRange,xIsTime:e.xKey===n,xKey:e.xKey,video:e.video,recordings:e.recordings,cursor:e.cursor,onContextMenu:t=>e.onContextMenu(t)})};if(!r.dataset)return{status:`no-data`,node:null,data:null};let a=`${e.background??`theme`}|${e.styleToken}`,o=t=>e.onContextMenu(t),s=(e,t)=>({status:`ready`,node:e,data:t}),c={status:`empty`,node:null,data:null},l=t.id;switch(t.kind){case`multiband`:{let t=r.multibandDataByPanel[l],n=t?.points??[],u=t?.effectiveSeries??[],d=i?.kind===`multiband`?i:null,p=[...new Set((d?.series??[]).map(e=>e.column).filter(t=>t!==e.xKey))],m=e.xKey===`ElapsedTime`&&!r.numericCols.includes(`Time`)?`Time`:e.xKey,h={xLabel:r.xUnit?`${m} (${r.xUnit})`:m,series:u,columnUnits:r.columnUnits,height:e.height,backgroundToken:a,viewXRange:e.viewXRange,onViewXRangeChange:e.onViewXRangeChange,onCursorX:e.onCursorX,liveZoom:e.liveZoom,liveZoomId:l,xAxisLine:d?.xAxisLine,yAxisLine:d?.yAxisLine,gridLine:d?.gridLine,lineWidth:d?.lineWidth,onPlotContextMenu:o,shiftMode:e.shiftMode},g=d?.beacon;if(g?.enabled&&e.beaconLive&&p.length>0){let t=IZ((d?.series??[]).filter(t=>t.column!==e.xKey),d?.layout??`overlay`),n=g.reference===`dataset`&&g.datasetId?e.findDataset(g.datasetId):void 0,r=xZ(g,!!n),i=r?[...hZ(t,r),...t]:t;return s(q(OW,{...h,series:i,points:[],showLatestValues:!0,liveSource:bZ(e.beaconLive,e.xKey,p,g,n),envelopes:n?SZ(n,e.xKey,t,r??void 0):void 0,liveZoomMode:`free`}),{series:i,points:[]})}if(r.anyDuckDb)return u.length===0?c:s(q(YW,{...h,layers:r.duckDbLayers,xKey:e.xKey,columns:p,maxPoints:GZ}),{series:u,columns:p});if(!n.some(e=>e.length>0)&&!r.liveOverlays||u.length===0||!p.some(e=>r.numericCols.includes(e)))return c;let _=r.liveConn,v=null,y=r.liveOverlays,b=!_&&y&&p.length>0?uZ(y,e.xKey,p,n,r.staticXRange):void 0,x=!!b&&n.length>0,S=b??(_&&p.length>0?{pull:(t,n,r,i,a)=>{let o=_.source.version();if(a){let i=2**Math.ceil(Math.log2((n-t)/8)),a=Math.floor(t/i)*i,s=Math.ceil(n/i)*i,c=Math.round(r*(s-a)/(n-t));return(!v||v.ver!==o||v.x0!==a||v.x1!==s||Math.abs(v.mp-c)>c*.25)&&(v={ver:o,x0:a,x1:s,mp:c,pts:_.source.getPointsSync(p,{xKey:e.xKey,x0:a,x1:s},c),held:lt(p,e=>_.source.lastKnownSync(e),a,s,_.source.latestTimeSync())}),v.held?[v.pts,v.held]:[v.pts]}(!v||v.ver!==o||v.x0!==t||v.x1!==n||v.mp!==r)&&(v={ver:o,x0:t,x1:n,mp:r,pts:_.source.getPointsSync(p,{xKey:e.xKey,x0:t,x1:n},r)});let s=f(v.pts,i);if(e.xKey!==`ElapsedTime`)return[s];let c=lt(p,e=>_.source.lastKnownSync(e),t,n,Math.min(_.source.latestTimeSync(),i??1/0));return c?[s,c]:[s]},cutOnGpu:e.xKey===`ElapsedTime`,id:_.id,latestT:()=>_.source.latestTimeSync(),timeAfter:e=>_.source.timeAfterSync(e),xAtTime:t=>_.source.xAtTimeSync(e.xKey,t),xBounds:()=>{let t=_.source.xBoundsSync(e.xKey);return t.x1>t.x0?[t.x0,t.x1]:null},latestX:()=>{let t=_.source.latestSync(e.xKey);return Number.isFinite(t)?t:null},version:()=>_.source.version(),latestValues:e=>_.source.latestValuesSync(e),...e.xKey===`ElapsedTime`?{}:{spanForSeconds:t=>_.source.xTravelSync(e.xKey,t),bufferedSeconds:()=>{let e=_.source.xBoundsSync(`ElapsedTime`);return e.x1-e.x0}}}:void 0);return s(q(OW,{...h,points:n,envelopes:t?.envelopes,showLatestValues:r.hasLiveSelected,fullXRange:r.staticXRange,liveSource:S,liveWindowSeconds:x?null:e.liveWindowSeconds,onLiveWindowChange:x?void 0:e.onLiveWindowChange,liveZoomMode:x?`free`:`follow`}),{series:u,points:n})}case`xyzmesh`:{let t=i?.kind===`xyzmesh`?i:En(4),n=r.xyzPointsByPanel[l];if(!n||n.points.length<1&&!n.surface)return c;let u=!!n.surface;return s(q($K,{ref:e.xyzRef,points:n.points,surface:n.surface,xLabel:u?(t.xyzColumns??[]).includes(e.xKey)?`Row`:e.xKey:t.xyzXCol,yLabel:u?`Column`:t.xyzYCol,zLabel:u?`Value`:t.xyzZCol,height:e.height,backgroundToken:a,xRange:bn(t.xyzXScale.scaleMin,t.xyzXScale.scaleMax),yRange:bn(t.xyzYScale.scaleMin,t.xyzYScale.scaleMax),zRange:bn(t.xyzZScale.scaleMin,t.xyzZScale.scaleMax),viewMode:t.xyzViewMode,pointRadius:t.xyzPointRadius,showMesh:t.showMesh,meshStyle:t.meshStyle,meshOpacity:t.meshOpacity,alarms:[...t.xyzXScale.alarm?[{axis:`x`,...t.xyzXScale.alarm}]:[],...t.xyzYScale.alarm?[{axis:`y`,...t.xyzYScale.alarm}]:[],...t.xyzZScale.alarm?[{axis:`z`,...t.xyzZScale.alarm}]:[]],onPlotContextMenu:o}),n.surface??n.points)}case`xyscatter`:{let t=i?.kind===`xyscatter`?i:Tn(WZ),n=r.xyPointsByPanel.pts[l]??[];if(n.length===0)return c;let u=r.xyPointsByPanel.colorMeta[l];return s(q(VG,{points:n,xLabel:t.xyXCol,yLabel:t.xyYCol,color:t.xyColor,datasetColors:r.xyPointsByPanel.datasetColors[l],colorLabel:u?.label,colorRange:u?[u.min,u.max]:void 0,pointRadius:t.xyPointRadius,drawMode:t.xyDrawMode,lineWidth:t.xyLineWidth,height:e.height,backgroundToken:a,xAxisLine:t.xyXAxisLine,yAxisLine:t.xyYAxisLine,gridLine:t.xyGridLine,fitSettings:t.xyFit,xScale:t.xyXScale,yScale:t.xyYScale,onPlotContextMenu:o}),n)}case`histogram`:{if(i?.kind!==`histogram`)return c;let t=r.histogramDataByPanel[l]??[];return t.length===0?c:s(q(oq,{values:t,label:i.histColumn,bins:i.histBins,color:i.histColor,showNormal:i.histNormal,logY:i.histLogY,height:e.height,backgroundToken:a,onPlotContextMenu:o}),t)}case`polar`:{if(i?.kind!==`polar`)return c;let t=r.polarDataByPanel[l]??{angles:[],radii:[]};if(t.angles.length===0)return c;let n=parseFloat(i.polarRadiusMin),u=parseFloat(i.polarRadiusMax);return s(q(wq,{angles:t.angles,radii:t.radii,angleLabel:i.polarAngleCol,radiusLabel:i.polarRadiusCol,color:i.polarColor,mode:i.polarMode,radiusMin:Number.isFinite(n)?n:void 0,radiusMax:Number.isFinite(u)?u:void 0,height:e.height,backgroundToken:a,onPlotContextMenu:o}),t)}case`spectrum`:{if(i?.kind!==`spectrum`)return c;let{signal:t,rate:n}=r.spectrumDataByPanel[l]??{signal:[],rate:1};return t.length<4?c:s(q(Bq,{signal:t,sampleRate:n,label:i.specSignalCol,xMode:i.specXMode,yMode:i.specYMode,window:i.specWindow,color:i.specColor,logX:i.specLogX,height:e.height,backgroundToken:a,onPlotContextMenu:o}),t)}case`boxplot`:{if(i?.kind!==`boxplot`)return c;let t=r.boxplotDataByPanel[l]??[];return t.length===0?c:s(q(Kq,{groups:t,color:i.boxColor,whiskers:i.boxWhiskers,height:e.height,backgroundToken:a,onPlotContextMenu:o}),t)}case`spectrogram`:{if(i?.kind!==`spectrogram`)return c;let{signal:e,rate:t}=r.spectrogramDataByPanel[l]??{signal:[],rate:1};return e.length<i.sgWindowSize?c:i.sgView===`waterfall`?s(q(uJ,{signal:e,sampleRate:t,windowSize:i.sgWindowSize,overlap:i.sgOverlap,winFunc:i.sgWinFunc,yMode:i.sgYMode,backgroundToken:a,onPlotContextMenu:o}),e):s(q(aJ,{signal:e,sampleRate:t,windowSize:i.sgWindowSize,overlap:i.sgOverlap,winFunc:i.sgWinFunc,yMode:i.sgYMode,logFreq:i.sgLogFreq,backgroundToken:a,onPlotContextMenu:o}),e)}case`heatmap`:{if(i?.kind!==`heatmap`)return c;let e=r.heatmapDataByPanel[l]??{cells:[],xLabels:[],yLabels:[]};if(e.cells.length===0&&!(e.grid&&e.grid.w*e.grid.h>0))return c;let t=e=>e!==void 0&&e.trim()!==``&&Number.isFinite(Number(e))?Number(e):void 0;return s(q(kJ,{cells:e.cells,xLabels:e.xLabels,yLabels:e.yLabels,grid:e.grid,showValues:i.hmShowValues,colorScheme:i.hmColorScheme,xCentres:e.xCentres,yCentres:e.yCentres,contours:i.hmContours??0,vMin:t(i.hmRange?.scaleMin),vMax:t(i.hmRange?.scaleMax),backgroundToken:a,onPlotContextMenu:o}),e)}case`violin`:{if(i?.kind!==`violin`)return c;let e=r.violinDataByPanel[l]??[];return e.some(e=>e.values.length>0)?s(q(LJ,{groups:e,color:i.vlColor,showBox:i.vlShowBox,bandwidth:parseFloat(i.vlBandwidth)||void 0,orientation:i.vlOrientation,backgroundToken:a,onPlotContextMenu:o}),e):c}case`confusion`:{if(i?.kind!==`confusion`)return c;let e=r.confusionDataByPanel[l]??{actual:[],predicted:[]};return e.actual.length===0?c:s(q(WJ,{actual:e.actual,predicted:e.predicted,normalize:i.cfNormalize,backgroundToken:a,onPlotContextMenu:o}),e)}case`roc`:{if(i?.kind!==`roc`)return c;let e=r.rocDataByPanel[l]??{scores:[],labels:[]};return e.scores.length===0?c:s(q(XJ,{scores:e.scores,labels:e.labels,mode:i.rocMode,color:i.rocColor,backgroundToken:a,onPlotContextMenu:o}),e)}case`losscurve`:{if(i?.kind!==`losscurve`)return c;let e=r.lossCurveDataByPanel[l]??{xValues:[],series:[]};return e.series.length===0?c:s(q(QJ,{xValues:e.xValues,series:e.series,xLabel:i.lcXCol||`Step`,backgroundToken:a,onPlotContextMenu:o}),e)}case`controlchart`:{if(i?.kind!==`controlchart`)return c;let e=r.controlChartDataByPanel[l];return!e||e.length<2?c:s(q(iY,{points:e,sigmaLevel:i.ccSigmaLevel,color:i.ccColor,backgroundToken:a,onPlotContextMenu:o}),e)}case`parallelcoords`:{if(i?.kind!==`parallelcoords`)return c;let e=r.parallelCoordsDataByPanel[l];if(!e||e.length===0||i.pcColumns.length<2)return c;let t=i.pcColorByCol?r.numericCols.includes(i.pcColorByCol):!1;return s(q(uY,{rows:e,axes:i.pcColumns,color:i.pcColor,colorByNumeric:t,backgroundToken:a,onPlotContextMenu:o}),e)}case`embedding`:{if(i?.kind!==`embedding`)return c;let e=r.embeddingDataByPanel[l];return!e||e.length===0?c:s(q(bY,{points:e,color:i.emColor,colorByNumeric:i.emColorMode===`numeric`&&!!i.emColorCol,pointSize:i.emPointSize,backgroundToken:a,onPlotContextMenu:o}),e)}case`flamegraph`:{if(i?.kind!==`flamegraph`)return c;let e=r.flameGraphDataByPanel[l]??[];return e.length===0?c:s(q(OY,{nodes:e,direction:i.fgDirection,backgroundToken:a,onPlotContextMenu:o}),e)}case`barchart`:{if(i?.kind!==`barchart`)return c;let e=r.barChartDataByPanel[l]??{groups:[],seriesNames:[]};if(e.groups.length===0&&!e.columns?.length)return c;let t=e=>e!==void 0&&e.trim()!==``&&Number.isFinite(Number(e))?Number(e):void 0,n=i.bcValueScale?{min:t(i.bcValueScale.scaleMin),max:t(i.bcValueScale.scaleMax)}:void 0;return s(q(PY,{groups:e.columns?void 0:e.groups,columns:e.columns,seriesNames:e.seriesNames,mode:i.bcMode,horizontal:i.bcHorizontal,valueRange:n,backgroundToken:a,onPlotContextMenu:o}),e)}case`radar`:{if(i?.kind!==`radar`)return c;let e=r.radarDataByPanel[l]??{axes:[],series:[]};return e.axes.length<3?c:s(q(RY,{axes:e.axes,series:e.series,fill:i.rdFill,color:i.rdColor,backgroundToken:a,onPlotContextMenu:o}),e)}case`areachart`:{if(i?.kind!==`areachart`)return c;let e=r.areaChartDataByPanel[l]??[];if(e.length===0)return c;let t=e=>e!==void 0&&e.trim()!==``&&Number.isFinite(Number(e))?Number(e):void 0,n=i.acYScale?{min:t(i.acYScale.scaleMin),max:t(i.acYScale.scaleMax)}:void 0;return s(q(HY,{series:e,stacked:i.acStacked,yRange:n,backgroundToken:a,onPlotContextMenu:o}),e)}case`cdfchart`:{if(i?.kind!==`cdfchart`)return c;let e=r.cdfChartDataByPanel[l]??[];return e.length===0?c:s(q(GY,{series:e,complement:i.cdComplement,logX:i.cdLogX,backgroundToken:a,onPlotContextMenu:o}),e)}case`bubblechart`:{if(i?.kind!==`bubblechart`)return c;let e=r.bubbleChartDataByPanel[l];return!e||e.length===0?c:s(q($Y,{points:e,color:i.bbColor,colorByNumeric:i.bbColorMode===`numeric`,maxRadius:i.bbMaxRadius,backgroundToken:a,onPlotContextMenu:o}),e)}case`treemap`:{let e=r.treemapDataByPanel[l]??[];return e.length===0?c:s(q(iX,{nodes:e,backgroundToken:a,onPlotContextMenu:o}),e)}case`sankey`:{let e=r.sankeyDataByPanel[l]??{nodeNames:[],links:[]};return e.links.length===0?c:s(q(uX,{nodeNames:e.nodeNames,links:e.links,backgroundToken:a,onPlotContextMenu:o}),e)}case`calibration`:{if(i?.kind!==`calibration`)return c;let e=r.calibrationDataByPanel[l]??[];return e.length===0?c:s(q(fX,{bins:e,color:i.cbColor,backgroundToken:a,onPlotContextMenu:o}),e)}case`qqplot`:{if(i?.kind!==`qqplot`)return c;let e=r.qqPlotDataByPanel[l];return!e||e.length===0?c:s(q(mX,{points:e,color:i.qqColor,backgroundToken:a,onPlotContextMenu:o}),e)}case`gauge`:{if(i?.kind!==`gauge`)return c;let e=r.gaugeDataByPanel[l]??[];if(e.length===0)return c;let t=r.liveConn??(r.liveOverlays?.length===1?r.liveOverlays[0].conn:void 0);return s(q(kX,{gauges:e,live:t?{latestT:()=>t.source.latestTimeSync(),timeAfter:e=>t.source.timeAfterSync(e),valueAt:(e,n)=>t.source.xAtTimeSync(e,n,!0)}:void 0,backgroundToken:a,onPlotContextMenu:o}),e)}case`gantt`:{let e=r.ganttDataByPanel[l]??[];return e.length===0?c:s(q(yX,{tasks:e,backgroundToken:a,onPlotContextMenu:o}),e)}}return c}var YZ=500,XZ=1e3;function ZZ(e){if(Array.isArray(e))return QZ(e);if(!e||typeof e!=`object`)return null;let t=-1;for(let n of Object.values(e))Array.isArray(n)&&(t=Math.max(t,QZ(n)));return t<0?null:t}function QZ(e){let t=e=>!!e&&typeof e==`object`&&e.x instanceof Float64Array;return e.length>0&&t(e[0])?e.reduce((e,n)=>e+(t(n)?n.length:0),0):e.length}function $Z(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${Math.round(e/1e3)}k`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function eQ({stats:e,host:t}){let[n,r]=Ct(null);if(W(()=>{let n=t.current?.ownerDocument.defaultView??window,i=0,a=0,o=0,s=-1,c=-1,l=e.renders,u=t.current?HH(t.current):0,d=f=>{c>=0&&f-s>XZ&&(c=f,s=f,a=0,o=0,l=e.renders,u=t.current?HH(t.current):0),c<0?(c=f,s=f):f!==s&&(o=Math.max(o,f-s),s=f,a++);let p=f-c;if(p>=YZ){let i=t.current,s=0;if(i)for(let e of i.getElementsByTagName(`canvas`))s+=e.width*e.height;let d=n.performance.memory,m=i?HH(i):0;r({fps:a*1e3/p,repaints:(m-u)*1e3/p,worstFrameMs:o,renderMs:e.lastRenderMs,rendersPerSec:(e.renders-l)*1e3/p,points:ZZ(e.data),domNodes:i?i.getElementsByTagName(`*`).length:0,canvasMp:s/1e6,heapMb:d?d.usedJSHeapSize/1048576:null,live:(()=>{let e=pU();return e?{age:Date.now()/1e3-e.newest,lag:e.lag,wait:e.wait,waitAge:e.waitAge}:null})()}),a=0,o=0,c=f,l=e.renders,u=m}i=n.requestAnimationFrame(d)};return i=n.requestAnimationFrame(d),()=>n.cancelAnimationFrame(i)},[e,t]),!n)return null;let i=n.fps<20?`var(--danger, #e5484d)`:n.fps<45?`var(--accent, #f5a524)`:void 0;return q(`dl`,{className:`kymo-perf-hud`,style:tQ,children:[[`FPS`,n.fps.toFixed(0),i],[`Repaints/s`,n.repaints.toFixed(0)],[`Slowest frame`,`${n.worstFrameMs.toFixed(1)} ms`],[`Render`,`${n.renderMs.toFixed(1)} ms`],[`Renders/s`,n.rendersPerSec.toFixed(1)],...n.points===null?[]:[[`Points`,$Z(n.points)]],[`DOM nodes`,$Z(n.domNodes)],[`Canvas`,`${n.canvasMp.toFixed(2)} MP`],...n.heapMb===null?[]:[[`JS heap`,`${n.heapMb.toFixed(0)} MB`]],...n.live?[[`Data age`,`${n.live.age.toFixed(2)} s`],[`Live lag`,`${n.live.lag.toFixed(2)} s`],[`Late by`,`${n.live.wait.toFixed(2)} s · ${n.live.waitAge.toFixed(0)} s ago`]]:[]].map(([e,t,n])=>Ot(`div`,{style:nQ,children:[q(`dt`,{style:rQ,children:e}),q(`dd`,{style:n?{...iQ,color:n}:iQ,children:t})]},e))})}var tQ={position:`absolute`,top:8,right:8,zIndex:60,flex:`none`,pointerEvents:`none`,userSelect:`none`,margin:0,padding:`6px 9px`,minWidth:148,display:`grid`,gap:1,font:`500 10.5px/1.35 var(--font-sans, system-ui)`,fontVariantNumeric:`tabular-nums`,fontFeatureSettings:`"tnum" 1`,color:`var(--text-strong, #f3f5fa)`,background:`color-mix(in oklch, var(--bg-elevated, #1b2130) 86%, transparent)`,border:`1px solid var(--border, #33405a)`,borderRadius:6,boxShadow:`0 4px 14px color-mix(in oklch, black 28%, transparent)`},nQ={display:`flex`,justifyContent:`space-between`,gap:12},rQ={color:`var(--text-muted, #8a93a6)`},iQ={margin:0,fontWeight:600,textAlign:`right`},aQ=[],oQ=3,sQ=`data-kymo-annotation-controls`;function cQ(e,t,n,r){return e.anchor===`x`&&!r?null:e.points.map(([i,a])=>[e.anchor===`x`?kU(r,i):i*t,a*n])}function lQ(e,t,n,r,i){return t.map(([t,a])=>[e.anchor===`x`&&i?AU(i,t):uQ(t/Math.max(1,n)),uQ(a/Math.max(1,r))])}var uQ=e=>Math.round(e*1e4)/1e4,dQ=_t(function({annotations:e,tool:t,plotFrame:n,onChange:r,onToolEnd:i,onSelect:a,marks:o=aQ,onMarkSelect:s}){let c=K(null),l=wt(n.subscribe,n.get),u=l?.x?l:null,[d,f]=Ct({w:0,h:0}),[p,m]=Ct(null),[h,g]=Ct(null),[_,v]=Ct(null),y=K({annotations:e,onChange:r,onToolEnd:i,onSelect:a,tool:t,selected:p,editing:h,frame:u,size:d});y.current={annotations:e,onChange:r,onToolEnd:i,onSelect:a,tool:t,selected:p,editing:h,frame:u,size:d};let b=e=>{y.current.selected!==e&&(y.current.selected=e,m(e),y.current.onSelect(e))};G(()=>{let e=c.current;if(!e)return;let t=e.ownerDocument.defaultView??window,n=()=>f({w:e.clientWidth,h:e.clientHeight});n();let r=new t.ResizeObserver(n);return r.observe(e),()=>r.disconnect()},[]),W(()=>{t&&b(null)}),W(()=>{p&&!e.some(e=>e.id===p)&&b(null)}),W(()=>()=>{y.current.selected&&y.current.onSelect(null)},[]),W(()=>{let e=c.current?.ownerDocument;if(!e)return;let t=e=>{let{selected:t,editing:n,tool:r,annotations:i,onChange:a,onToolEnd:o}=y.current;if(!(n||bQ(e.target))){if(e.key===`Escape`&&r){o();return}t&&(e.key===`Delete`||e.key===`Backspace`?(e.preventDefault(),a(i.filter(e=>e.id!==t)),b(null)):e.key===`Escape`&&b(null))}},n=e=>{let t=y.current.selected,n=e.target;t&&!n?.closest?.(`[data-ann-id="${CSS.escape(t)}"], [data-kymo-annotation-controls]`)&&b(null)};return e.addEventListener(`keydown`,t),e.addEventListener(`pointerdown`,n,!0),()=>{e.removeEventListener(`keydown`,t),e.removeEventListener(`pointerdown`,n,!0)}},[]);let{w:x,h:S}=d,C=e=>{let t=c.current.getBoundingClientRect();return[e.clientX-t.left,e.clientY-t.top]},w=(e,t)=>{let n=c.current.ownerDocument,r=t=>e(C(t),t),i=()=>{n.removeEventListener(`pointermove`,r),n.removeEventListener(`pointerup`,i),n.removeEventListener(`pointercancel`,i),t()};n.addEventListener(`pointermove`,r),n.addEventListener(`pointerup`,i),n.addEventListener(`pointercancel`,i)},T=e=>r([...y.current.annotations,e]),E=e=>r(y.current.annotations.map(t=>t.id===e.id?e:t)),D=e=>{if(!t||e.button!==0||h)return;e.preventDefault(),e.stopPropagation();let n=C(e),r={id:crypto.randomUUID(),kind:t.kind,color:t.color,width:t.width,...u?{anchor:`x`}:{}},i=e=>lQ(r,e,x,S,u);if(t.kind===`text`){v({...r,points:i([n]),text:``}),g(r.id);return}let a=t.kind===`brush`?[n]:[n,n],o={...r,points:i(a)};v(o);let s=!1;w((t,n)=>{if(s||=Math.hypot(n.clientX-e.clientX,n.clientY-e.clientY)>oQ,r.kind===`brush`){let e=a[a.length-1];if(Math.hypot(t[0]-e[0],t[1]-e[1])<2)return;a=[...a,t]}else a=[a[0],t];o={...o,points:i(a)},v(o)},()=>{v(null),s&&o.points.length>=2&&T(o)})},O=(e,t,n)=>{let r=cQ(t,x,S,u);if(!r)return;let i=C(e),a=null;w((o,s)=>{if(!a&&Math.hypot(s.clientX-e.clientX,s.clientY-e.clientY)<=oQ)return;let{size:c,frame:l}=y.current;a={...t,points:lQ(t,n(r,[o[0]-i[0],o[1]-i[1]],o),c.w,c.h,l)},v(a)},()=>{v(null),a&&E(a)})},k=(e,n)=>{t||e.button!==0||h===n.id||(e.preventDefault(),e.stopPropagation(),b(n.id),O(e,n,(e,[t,n])=>e.map(([e,r])=>[e+t,r+n])))},A=(e,t,n)=>{e.button===0&&(e.preventDefault(),e.stopPropagation(),O(e,t,(e,r,i)=>{let a=e.map(e=>[...e]);return t.kind===`arrow`?a[n]=i:(a[+(n===1||n===2)][0]=i[0],a[+(n===2||n===3)][1]=i[1]),a}))},j=e=>{t||e.kind!==`text`&&e.kind!==`box`||(b(e.id),g(e.id))},M=e=>{let t=h;g(null);let n=_&&_.id===t?_:null;if(v(null),e===null||!t)return;let i=e.replace(/\s+$/,``),a=y.current.annotations;if(n){i&&T({...n,text:i});return}let o=a.find(e=>e.id===t);o&&(!i&&o.kind===`text`?r(a.filter(e=>e.id!==t)):E(yQ(o,i)))},N=e=>{r(y.current.annotations.filter(t=>t.id!==e)),b(null)},P=(_?e.some(e=>e.id===_.id)?e.map(e=>e.id===_.id?_:e):[...e,_]:e).flatMap(e=>{let t=cQ(e,x,S,u);return t?[{a:e,px:t}]:[]}),F=p?P.find(e=>e.a.id===p):void 0,I=u?o.map(e=>{let t=cQ(Jt(e,u.x.v1),x,S,u);return{m:e,x0:Math.min(t[0][0],t[1][0]),x1:Math.max(t[0][0],t[1][0])}}):[],L=F&&F.a.kind!==`text`?vQ(F.px):null,R=e=>Ot(Dt,{children:[q(`svg`,{className:`kymo-ann-svg`,width:x,height:S,viewBox:`0 0 ${x} ${S}`,"aria-hidden":`true`,children:e.map(({a:e,px:t})=>e.kind===`text`?null:q(`g`,{"data-ann-id":e.id,className:`kymo-ann kymo-ann--${e.kind}`,onPointerDown:t=>k(t,e),onDoubleClick:()=>j(e),children:q(mQ,{a:e,px:t})},e.id))}),e.map(({a:e,px:t})=>{if(e.kind!==`text`&&e.kind!==`box`)return null;let n=h===e.id;if(!n&&!e.text)return null;let r=e.kind===`text`?{left:t[0][0],top:t[0][1]}:{left:Math.min(t[0][0],t[1][0]),top:Math.min(t[0][1],t[1][1]),transform:`translateY(calc(-100% - 3px))`};return Ot(`div`,{"data-ann-id":e.id,className:`kymo-ann-text kymo-ann-text--${e.kind}${p===e.id&&e.kind===`text`?` is-selected`:``}`,style:{...r,color:e.color,fontSize:e.kind===`text`?e.width:12},onPointerDown:t=>k(t,e),onDoubleClick:()=>j(e),children:[n?q(pQ,{initial:e.text??``,onDone:M}):e.text,p===e.id&&e.kind===`text`&&!n?q(fQ,{onDelete:()=>N(e.id),style:{right:-11,top:-11}}):null]},`t-${e.id}`)})]});return q(`div`,{ref:c,className:`kymo-annotations${t?` is-drawing is-tool-${t.kind}`:``}`,onPointerDown:D,onContextMenu:t?e=>e.preventDefault():void 0,children:x>0&&S>0?Ot(Dt,{children:[u&&I.length?q(`div`,{className:`kymo-ann-clip`,style:{clipPath:`inset(0 ${Math.max(0,x-u.left-u.width)}px 0 ${Math.max(0,u.left)}px)`},children:q(`svg`,{className:`kymo-ann-svg kymo-marks`,width:x,height:S,viewBox:`0 0 ${x} ${S}`,children:I.map(({m:e,x0:t,x1:n})=>Ot(`g`,{"data-mark":e.ruleId,role:`img`,"aria-label":`${e.ruleName}, ${e.severity}`,className:`kymo-mark kymo-mark--${e.severity}`,style:{color:qt[e.severity]},children:[q(`rect`,{x:t,y:u.top,width:Math.max(1,n-t),height:u.height,fill:`currentColor`,fillOpacity:.12}),q(`rect`,{x:t,y:u.top,width:Math.max(1,n-t),height:2,fill:`currentColor`}),q(`rect`,{className:`kymo-mark-hit`,x:t,y:u.top,width:Math.max(6,n-t),height:8,onPointerDown:t=>{t.stopPropagation(),s?.(e.ruleId)}})]},e.id))})}):null,R(P.filter(e=>e.a.anchor!==`x`)),u?q(`div`,{className:`kymo-ann-clip`,style:{clipPath:`inset(0 ${Math.max(0,x-u.left-u.width)}px 0 ${Math.max(0,u.left)}px)`},children:R(P.filter(e=>e.a.anchor===`x`))}):null,Ot(`svg`,{className:`kymo-ann-svg`,width:x,height:S,viewBox:`0 0 ${x} ${S}`,"aria-hidden":`true`,children:[L?q(`rect`,{className:`kymo-ann-selection`,x:L.x-6,y:L.y-6,width:L.w+12,height:L.h+12,rx:4}):null,F&&!h&&(F.a.kind===`box`||F.a.kind===`arrow`)?q(`g`,{"data-ann-id":F.a.id,children:hQ(F.a,F.px).map(([e,t],n)=>q(`rect`,{className:`kymo-ann-handle kymo-ann-handle--${F.a.kind===`arrow`?`end`:n%2?`nesw`:`nwse`}`,x:e-4.5,y:t-4.5,width:9,height:9,rx:2,onPointerDown:e=>A(e,F.a,n)},n))}):null]}),L&&!h?q(fQ,{onDelete:()=>N(F.a.id),id:F.a.id,style:{left:Math.min(x-12,L.x+L.w+6)-10,top:Math.max(10,L.y-6)-10}}):null]}):null})});function fQ({onDelete:e,style:t,id:n}){return q(`button`,{type:`button`,className:`kymo-ann-delete`,style:t,"data-ann-id":n,"aria-label":`Delete annotation`,title:`Delete (Del)`,onPointerDown:e=>e.stopPropagation(),onClick:e,children:q(`svg`,{viewBox:`0 0 10 10`,width:`8`,height:`8`,"aria-hidden":`true`,children:q(`path`,{d:`M2 2l6 6M8 2l-6 6`})})})}function pQ({initial:e,onDone:t}){let n=K(null),r=K(!1),i=e=>{r.current||(r.current=!0,t(e))};return G(()=>{let t=n.current;if(!t)return;t.textContent=e,t.focus();let r=t.ownerDocument.createRange();r.selectNodeContents(t);let i=t.ownerDocument.defaultView?.getSelection();i?.removeAllRanges(),i?.addRange(r)},[]),q(`div`,{ref:n,className:`kymo-ann-editor`,contentEditable:`plaintext-only`,suppressContentEditableWarning:!0,role:`textbox`,"aria-label":`Annotation text`,"aria-multiline":`true`,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),e.key===`Enter`&&!e.shiftKey?(e.preventDefault(),i(n.current?.innerText??``)):e.key===`Escape`&&(e.preventDefault(),i(null))},onBlur:()=>i(n.current?.innerText??``)})}function mQ({a:e,px:t}){let n={stroke:e.color,strokeWidth:e.width,fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`},r=t=>q(`path`,{className:`kymo-ann-hit`,d:t,strokeWidth:Math.max(12,e.width+10)});switch(e.kind){case`box`:{let[[i,a],[o,s]]=t,c=`M${i} ${a}H${o}V${s}H${i}Z`;return Ot(Dt,{children:[r(c),q(`path`,{d:c,...n}),q(`path`,{d:c,fill:e.color,fillOpacity:.06,stroke:`none`,pointerEvents:`none`})]})}case`arrow`:{let[[i,a],[o,s]]=t,c=_Q(i,a,o,s,e.width);return Ot(Dt,{children:[r(`M${i} ${a}L${o} ${s}`),q(`path`,{d:`M${i} ${a}L${c.base[0]} ${c.base[1]}`,...n}),q(`path`,{d:c.d,fill:e.color,stroke:e.color,strokeWidth:1,strokeLinejoin:`round`})]})}case`brush`:{let e=gQ(t);return Ot(Dt,{children:[r(e),q(`path`,{d:e,...n})]})}}return null}function hQ(e,t){if(e.kind===`arrow`)return t;let[[n,r],[i,a]]=t;return[[n,r],[i,r],[i,a],[n,a]]}function gQ(e){if(e.length===0)return``;if(e.length<3)return`M${e[0][0]} ${e[0][1]}`+e.slice(1).map(([e,t])=>`L${e} ${t}`).join(``);let t=`M${e[0][0]} ${e[0][1]}`;for(let n=1;n<e.length-1;n++){let[r,i]=e[n],[a,o]=e[n+1];t+=`Q${r} ${i} ${(r+a)/2} ${(i+o)/2}`}let[n,r]=e[e.length-1];return t+`L${n} ${r}`}function _Q(e,t,n,r,i){let a=Math.max(9,i*4),o=Math.atan2(r-t,n-e),s=.42,c=[n-a*Math.cos(o-s),r-a*Math.sin(o-s)],l=[n-a*Math.cos(o+s),r-a*Math.sin(o+s)],u=[n-a*.8*Math.cos(o),r-a*.8*Math.sin(o)];return{d:`M${n} ${r}L${c[0]} ${c[1]}L${l[0]} ${l[1]}Z`,base:u,l:c,r:l}}function vQ(e){let t=e.map(e=>e[0]),n=e.map(e=>e[1]),r=Math.min(...t),i=Math.min(...n);return{x:r,y:i,w:Math.max(...t)-r,h:Math.max(...n)-i}}function yQ(e,t){if(t)return{...e,text:t};let{text:n,...r}=e;return r}function bQ(e){let t=e;return!!t&&(t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))}function xQ(e,t,n,r,i,a,o){e.save(),e.scale(i,i),e.lineCap=`round`,e.lineJoin=`round`;for(let i of t){let t=cQ(i,n,r,o);t&&(e.save(),i.anchor===`x`&&o&&(e.beginPath(),e.rect(o.left,0,o.width,r),e.clip()),SQ(e,i,t,a),e.restore())}e.restore()}function SQ(e,t,n,r){if(e.strokeStyle=t.color,e.fillStyle=t.color,e.lineWidth=t.width,t.kind===`box`)e.strokeRect(n[0][0],n[0][1],n[1][0]-n[0][0],n[1][1]-n[0][1]);else if(t.kind===`brush`)e.stroke(new Path2D(gQ(n)));else if(t.kind===`arrow`){let r=_Q(n[0][0],n[0][1],n[1][0],n[1][1],t.width);e.beginPath(),e.moveTo(n[0][0],n[0][1]),e.lineTo(r.base[0],r.base[1]),e.stroke(),e.beginPath(),e.moveTo(n[1][0],n[1][1]),e.lineTo(r.l[0],r.l[1]),e.lineTo(r.r[0],r.r[1]),e.closePath(),e.fill()}if(!t.text)return;let i=t.kind===`text`?t.width:12;e.font=`600 ${i}px ${r}`,e.textBaseline=`top`;let a=t.text.split(`
|
|
614
|
+
`),o=i*1.25,s=n[0][0],c=n[0][1];t.kind===`box`&&(s=Math.min(n[0][0],n[1][0]),c=Math.min(n[0][1],n[1][1])-a.length*o-7),a.forEach((t,n)=>e.fillText(t,s+6,c+2+n*o))}var CQ={solid:void 0,dashed:`5 4`,dotted:`1 4`};function wQ(e,t,n){if(!e||!(n===`x`?e.x:e.y))return null;if(n===`x`){let n=kU(e,t.value);return n>=e.left-.5&&n<=e.left+e.width+.5?[n,e.top,n,e.top+e.height]:null}let r=jU(e,t.value);return r>=e.top-.5&&r<=e.top+e.height+.5?[e.left,r,e.left+e.width,r]:null}var TQ=_t(function({frame:e,alarm:t,axis:n}){let r=wQ(wt(e.subscribe,e.get),t,n);if(!r)return null;let i=t.linked?EQ(r,n):null;return Ot(`svg`,{className:`kymo-alarm`,"aria-hidden":`true`,children:[q(`line`,{x1:r[0],y1:r[1],x2:r[2],y2:r[3],stroke:t.color,strokeWidth:t.width,strokeDasharray:t.linked===`active`?RU.join(` `):CQ[t.style]}),i?q(`path`,{"data-alert-glyph":``,d:LU,transform:`translate(${i[0]} ${i[1]})`,fill:t.color}):null]})});function EQ(e,t){return t===`y`?[e[2]-10-3,e[1]-10-2]:[e[0]+3,e[1]+2]}function DQ(e,t,n,r,i){let a=wQ(t,n,r);if(a){if(e.save(),e.scale(i,i),e.strokeStyle=n.color,e.lineWidth=n.width,e.setLineDash(n.linked===`active`?RU:CQ[n.style]?.split(` `).map(Number)??[]),e.beginPath(),e.moveTo(a[0],a[1]),e.lineTo(a[2],a[3]),e.stroke(),n.linked){let t=EQ(a,r);BU(e,t[0],t[1],n.color)}e.restore()}}function OQ(e,t,n){return e.handlers?.wsId===n?e.handlers:e.handlers={wsId:n,onViewXRangeChange:r=>{t.view.setXRange(r,n),e.emitter.emit(`viewchange`,r)},onCursorX:e=>{try{t.view.setCursorX(e,n)}catch{}},cursor:{get:()=>{try{return t.view.cursorX(n)}catch{return null}},subscribe:e=>t.on(`cursorchange`,t=>{t.worksheetId===n&&e(t.x)})},onContextMenu:t=>e.emitter.emit(`contextmenu`,t),xyzRef:t=>{e.xyz=t},onAnnotations:n=>t.charts.setAnnotations(e.chartId,n),onAnnotationToolEnd:()=>{e.annotationTool=null,NQ(t).bump(),e.emitter.emit(`annotationtool`,null)},onAnnotationSelect:t=>{e.selectedAnnotation=t,e.emitter.emit(`annotationselect`,t)},onMarkSelect:t=>e.emitter.emit(`markselect`,t)}}var kQ=new WeakMap;function AQ(e,t){let n=kQ.get(e);n||kQ.set(e,n=new Map);let r=n.get(t);return r||n.set(t,r=n=>e.view.setLiveWindow(n,t)),r}var jQ=class{mounts=new Map;version=0;listeners=new Set;root=null;engine;constructor(e){this.engine=e}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getVersion=()=>this.version;bump(){this.version++;for(let e of[...this.listeners])e()}add(e){this.mounts.set(e.key,e),this.root||(this.root=Et(document.createElement(`div`)),this.root.render(q(zQ,{engine:this.engine,registry:this}))),this.bump()}remove(e){this.mounts.delete(e)&&this.bump()}refresh(){this.bump()}dispose(){this.mounts.clear(),this.root?.unmount(),this.root=null}},MQ=new WeakMap;function NQ(e){let t=MQ.get(e);return t||(t=new jQ(e),MQ.set(e,t)),t}function PQ(e,t,n,r={}){e.charts.get(t);let i=NQ(e),a={key:crypto.randomUUID(),chartId:t,element:n,options:r,shiftDatasetId:null,emitter:KV(),xyz:null,annotationTool:null,selectedAnnotation:null,plotFrame:PU(),status:null,data:null};i.add(a);let o=!1;return{chartId:t,status:()=>a.status,data:()=>a.data,on:(e,t)=>a.emitter.on(e,t),exportPng(){let r=Array.from(n.querySelectorAll(`canvas`));if(r.length===0)return Promise.reject(new HE(`export_failed`,{reason:`nothing to export`}));let i=document.createElement(`canvas`);i.width=r[0].width,i.height=r[0].height;let o=i.getContext(`2d`);if(!o)return Promise.reject(new HE(`export_failed`,{reason:`canvas unavailable`}));for(let e of r)o.drawImage(e,0,0);let s=e.charts.get(t),c=YQ(s.settings,Q1(e).alertLines()),l=a.plotFrame.get()?.x?a.plotFrame.get():null,u=e.getState(),d=u.worksheets.find(e=>e.charts.some(e=>e.id===t)),f=QQ(s.annotations,d?XQ(u.marks,u.selection,d.xKey):[],l),p=fr(c);return p&&n.clientWidth>0&&DQ(o,a.plotFrame.get(),p.alarm,p.axis,i.width/n.clientWidth),f.length&&n.clientWidth>0&&xQ(o,f,n.clientWidth,n.clientHeight,i.width/n.clientWidth,Q.sans,l),new Promise((e,t)=>i.toBlob(n=>n?e(n):t(new HE(`export_failed`,{reason:`encode failed`})),`image/png`))},autoscale(){a.xyz?.autoscale()},setShiftMode(e){a.shiftDatasetId!==e&&(a.shiftDatasetId=e,i.bump())},setAnnotationTool(e){a.annotationTool=e?{...e}:null,i.bump()},annotationTool:()=>a.annotationTool,selectedAnnotation:()=>a.selectedAnnotation,setOptions(e){a.options={...e},i.bump()},destroy(){o||(o=!0,a.emitter.clear(),i.remove(a.key))}}}function FQ(e){MQ.get(e)?.refresh()}function IQ(e){MQ.get(e)?.dispose(),MQ.delete(e)}function LQ(e){let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-color-scheme`,`class`,`data-theme`]}),()=>t.disconnect()}var RQ=()=>{let e=document.documentElement;return`${e.getAttribute(`data-color-scheme`)??``}|${e.getAttribute(`data-theme`)??``}|${e.className}`};function zQ({engine:e,registry:t}){wt(t.subscribe,t.getVersion);let n=Q1(e),r=wt(n.store.subscribe,n.store.get),i=new Map;for(let e of t.mounts.values()){let t=r.worksheets.find(t=>t.panels.some(t=>t.id===e.chartId));if(!t)continue;let n=i.get(t.id)??{worksheet:t,mounts:[]};n.mounts.push(e),i.set(t.id,n)}return q(Dt,{children:[...i.values()].map(t=>q(UQ,{engine:e,worksheet:t.worksheet,mounts:t.mounts},t.worksheet.id))})}var BQ=1e3,VQ=.25;function HQ(e,t,n,r){let[i,a]=Ct(0),o=K(0),s=K(0);return W(()=>{o.current&&=(s.current=performance.now()-o.current,0)}),W(()=>{if(!n)return;let i=0,c=-1,l=0,u=n=>{if(i=RH(u),o.current||n<l||UH()||!r())return;let d=0;for(let n of e)t.includes(n.id)&&(d+=n.source.version());d!==c&&(c=d,l=n+s.current*(1/VQ-1),o.current=performance.now(),vt(()=>a(e=>e+1)))};return i=RH(u),()=>zH(i)},[n,e,t]),St(()=>n?e.map(e=>t.includes(e.id)?{...e,dataset:e.source.snapshot(BQ)}:e):e,[e,t,n,i])}function UQ({engine:e,worksheet:t,mounts:n}){let r=Q1(e),i=wt(r.store.subscribe,r.store.get),a=r.derived(),o=i.xRanges[t.id]??null,s=St(()=>i.live.filter(e=>e.kind===`data`),[i.live]),c=a.selectedLive.length,l=e=>{let n=t.panelChartSettings[e];return n?.kind===`multiband`&&n.beacon?.enabled===!0},u=c>0&&t.panels.some(e=>e.kind!==`multiband`&&e.kind!==`camera`||c>1&&!l(e.id)),d=K(n);d.current=n;let f=K(()=>d.current.some(e=>e.element.isConnected&&(typeof e.element.checkVisibility!=`function`||e.element.checkVisibility()))).current,p=HQ(s,i.selection,u,f),m=r.alertLines(),h=HZ({worksheet:qQ(t,m),viewXRange:o,selectedIds:i.selection,selectedDatasets:a.selectedDatasets,liveConnections:p,mathChannels:a.channels,datasetOffsets:i.offsets,datasetColors:i.colors,datasetPalette:i.palette}),g=K(WV()).current,_=wt(LQ,RQ),v=t.id,y=AQ(e,v),b=i.licensed,x=a.selectedLive[0]??null,S=e=>i.datasets.find(t=>t.id===e)??Object.values(a.laps).flatMap(e=>e.laps).find(t=>t.id===e);return q(Dt,{children:n.map(n=>{let r=t.panels.find(e=>e.id===n.chartId);if(!r)return null;let s=n.shiftDatasetId?a.selectedDatasets.find(e=>e.id===n.shiftDatasetId):void 0,c=OQ(n,e,v),l=YQ(t.panelChartSettings[r.id],m);return Tt(q(n$,{mount:n,annotations:t.panelChartSettings[r.id]?.annotations,marks:XQ(i.marks,i.selection,t.xKey),onMarkSelect:c.onMarkSelect,alarm:fr(l),onAnnotations:c.onAnnotations,onAnnotationToolEnd:c.onAnnotationToolEnd,onAnnotationSelect:c.onAnnotationSelect,render:u=>qZ({panel:r,settings:l,background:n.options.style?.background??t.panelChartBackgrounds[r.id]??null,styleToken:JSON.stringify([_,n.options.theme,n.options.style,Q]),data:h,xKey:t.xKey,height:u,viewXRange:o,onViewXRangeChange:c.onViewXRangeChange,onCursorX:c.onCursorX,liveZoom:g,liveWindowSeconds:t.liveWindowSeconds===void 0?i.liveWindowSeconds:t.liveWindowSeconds,onLiveWindowChange:y,beaconLive:x,findDataset:S,live:i.live,selection:i.selection,cursor:c.cursor,video:e.video.sources(),recordings:KX(a.selectedDatasets,i.offsets),shiftMode:s?WQ(e,s.id,s.name):void 0,onContextMenu:c.onContextMenu,xyzRef:c.xyzRef}),licensed:b},n.key),n.element,n.key)})})}function WQ(e,t,n){let r=0;return{label:n,onDragStart:()=>{r=e.getState().datasets.find(e=>e.id===t)?.offset??0},onDragOffset:n=>e.datasets.setOffset(t,r+n)}}var GQ=[],KQ=new WeakMap;function qQ(e,t){if(!t.size)return e;let n=KQ.get(e);if(n&&n.lines===t)return n.out;let r=!1,i={};for(let[n,a]of Object.entries(e.panelChartSettings))i[n]=YQ(a,t),i[n]!==a&&(r=!0);let a=r?{...e,panelChartSettings:i}:e;return KQ.set(e,{lines:t,out:a}),a}var JQ=new WeakMap;function YQ(e,t){if(!e||!t.size)return e;let n=JQ.get(e);if(n&&n.lines===t)return n.out;let r=ur(e,t);return JQ.set(e,{lines:t,out:r}),r}var XQ=$Q((e,t,n)=>{let r=e.filter(e=>e.timeColumn===n&&t.includes(e.targetId));return r.length?r:ZQ}),ZQ=[];function QQ(e,t,n){return!t.length||!n?.x?e:[...t.map(e=>Jt(e,n.x.v1)),...e]}function $Q(e){let t=null,n;return(r,i,a)=>t&&t[0]===r&&t[1]===i&&t[2]===a?n:(t=[r,i,a],n=e(r,i,a),n)}function e$(e,t){e.data=t}function t$(e,t){e.status!==t&&(e.status=t,e.emitter.emit(`status`,t))}function n$({mount:e,render:t,licensed:n,annotations:r,marks:i,alarm:a,onAnnotations:o,onAnnotationToolEnd:s,onAnnotationSelect:c,onMarkSelect:l}){let u=K(null),[d,f]=Ct(0),p=!!e.options.debug,m=K({renderStart:0,lastRenderMs:0,renders:0,data:null}).current;p&&(m.renderStart=performance.now()),G(()=>{p&&(m.lastRenderMs=performance.now()-m.renderStart,m.renders++)}),G(()=>{let e=u.current;if(!e)return;let t=()=>f(Math.max(120,Math.floor(e.clientHeight)));t();let n=new WH(t);return n.observe(e),()=>n.disconnect()},[]);let{status:h,node:g,data:_}=t(d||400);m.data=_,W(()=>{e$(e,_)}),W(()=>{t$(e,h)});let{theme:v,style:y,className:b}=e.options,x={};return y?.background&&(x[`--chart-bg`]=y.background),y?.muted&&(x[`--chart-muted`]=y.muted),y?.grid&&(x[`--chart-grid`]=y.grid),y?.accent&&(x[`--accent`]=y.accent),Ot(`div`,{ref:u,onContextMenu:h===`ready`?void 0:t=>{t.preventDefault(),e.emitter.emit(`contextmenu`,{clientX:t.clientX,clientY:t.clientY})},className:b?`kymo-chart ${b}`:`kymo-chart`,"data-color-scheme":v,"data-status":h,style:x,children:[q(FU.Provider,{value:e.plotFrame.set,children:g}),h===`ready`&&a?q(TQ,{frame:e.plotFrame,alarm:a.alarm,axis:a.axis}):null,h===`ready`&&(r?.length||e.annotationTool||i.length)?q(dQ,{annotations:r??GQ,tool:e.annotationTool,plotFrame:e.plotFrame,onChange:o,onToolEnd:s,onSelect:c,marks:i,onMarkSelect:l}):null,p?q(eQ,{stats:m,host:u}):null,n===!1?q(GV,{}):null]})}var r$=new WeakMap;function i$(e,t,n,r={}){let i=r$.get(e)??new Map;r$.set(e,i);let a=i.get(t);if(a&&!a.window.closed)return a.window.focus(),a;let o=e.charts.get(t),s=r.title??(o.title||e.charts.label(o.kind));for(let e of i.values())e.window.closed||e.window.focus();let c=40*(i.size+1),l=window.open(``,`kymoscope-chart-${t}`,`popup,width=${r.width??960},height=${r.height??600},left=${r.left??window.screenX+c},top=${r.top??window.screenY+c}`);if(!l)throw new HE(`popup_blocked`,{chartId:t});let u=l.document;u.head.replaceChildren(),u.body.replaceChildren(),u.title=s;for(let e of document.querySelectorAll(`style, link[rel="stylesheet"]`)){let t=e.cloneNode(!0);t instanceof HTMLLinkElement&&(t.href=e.href),u.head.appendChild(t)}let d=()=>{for(let e of[...u.documentElement.attributes])u.documentElement.removeAttribute(e.name);for(let e of document.documentElement.attributes)u.documentElement.setAttribute(e.name,e.value);u.body.className=document.body.className};d();let f=new MutationObserver(d);f.observe(document.documentElement,{attributes:!0}),f.observe(document.body,{attributes:!0,attributeFilter:[`class`]}),Object.assign(u.body.style,{margin:`0`,position:`fixed`,inset:`0`,display:`flex`,flexDirection:`column`,background:getComputedStyle(document.body).backgroundColor});let p=u.createElement(`div`);p.className=`kymo-window-controls`;let m=u.createElement(`div`);m.className=`kymo-window-plot`,Object.assign(m.style,{flex:`1`,minHeight:`0`,position:`relative`}),u.body.append(p,m),MH(l);let h=n(m,r.mount),g=KV(),_=!1,v=()=>{_||(_=!0,i.delete(t),NH(l),f.disconnect(),b(),window.removeEventListener(`pagehide`,y),h.destroy(),g.emit(`close`,void 0),g.clear())},y=()=>x.close(),b=e.subscribe(()=>{try{e.charts.get(t)}catch{x.close()}});l.addEventListener(`pagehide`,v),window.addEventListener(`pagehide`,y);let x={chartId:t,window:l,controls:p,view:h,close(){v(),l.closed||l.close()},on:(e,t)=>g.on(e,t)};return i.set(t,x),x}function a$(e){for(let t of[...r$.get(e)?.values()??[]])t.close()}function o$(e){let t=new Map;for(let[n,r]of r$.get(e)??[]){let e=r.window;e.closed||t.set(n,{left:e.screenX,top:e.screenY,width:e.innerWidth,height:e.innerHeight})}return t}var s$=12e3,c$=100;function l$(e,t=!1){let n,r=0;if(t&&e instanceof Float64Array){n=e;let t=0,i=0,a=0,o=n.length&-4;for(let e=0;e<o;e+=4)r+=n[e]*0,t+=n[e+1]*0,i+=n[e+2]*0,a+=n[e+3]*0;for(let e=o;e<n.length;e++)r+=n[e]*0;r+=t+i+a}else{n=new Float64Array(e.length);for(let t=0;t<n.length;t++){let i=+e[t];n[t]=i,r+=i*0}}if(r===0)return j.add(n),n;for(let e=0;e<n.length;e++){let t=n[e];t-t!==0&&(n[e]=NaN)}return n}function u$(e,t){let n=Object.keys(t.columns);if(n.length===0)throw new HE(`no_columns`);let r=t.columns[n[0]].length;if(n.some(e=>t.columns[e].length!==r))throw new HE(`column_length_mismatch`);let i=new Map(n.map(e=>[e,l$(t.columns[e],t.transfer)])),a=d$(e,t.name,i,t.units??{});if(t.bands){for(let e of Object.values(t.bands))if(e.lo.length!==r||e.hi.length!==r)throw new HE(`column_length_mismatch`);a.bands=Object.fromEntries(Object.entries(t.bands).map(([e,t])=>[e,{lo:Float64Array.from(t.lo),hi:Float64Array.from(t.hi)}]))}return a}function d$(e,t,n,r,i,a){let o=[...n.keys()],s=n.get(o[0]).length,c=o.map(e=>r[e]??``),l=o.map((e,t)=>({name:e,type:`number`,unit:c[t]})),u=!!a&&a.schema.length===o.length&&a.schema.every((e,t)=>e.name===o[t]),d,f;if(u)d=a.rawText??``,f=a.parseConfig;else{let e=[o.join(`,`)];for(let t=0;t<Math.min(s,c$);t++)e.push(o.map(e=>{let r=n.get(e)[t];return r===r?String(r):``}).join(`,`));d=e.join(`
|
|
615
|
+
`),f=ae(d)}let p={id:e,name:t,schema:l,rawText:d,parseConfig:f,fromColumns:!0};if(s>1e6){let e=new CZ(n,r);return{...p,kind:`columnar`,source:e,data:{meta:``,columnNames:o,units:c,rows:e.sampleRowsSync(s$)}}}let m={meta:``,columnNames:o,units:c,rows:He({keys:o,length:s,values:o.map(e=>n.get(e)),text:o.map(()=>null)},i)};return{...p,kind:`memory`,source:new XE(m),data:m}}function f$(e,t,n){let r=e.fromColumns?p$(e):null;if(!r)throw new HE(`invalid_argument`,{reason:`only datasets added with addColumns can be written`});let i=r.values().next().value.length,a=e.columnSpares??new Map,o={};for(let e of t){let t=a.get(e);t&&t.length===i&&t!==r.get(e)?(he(t),o[e]=t):o[e]=new Float64Array(i)}n(o,Object.fromEntries(t.map(e=>[e,r.get(e)])));let s=new Map(a);for(let e of t){let t=r.get(e);t?s.set(e,t):s.delete(e)}return{...m$(e,o,!0),columnSpares:s}}function p$(e){if(e.source instanceof CZ)return new Map(e.source.columnMap);let t=ve(e.data.rows);return t?new Map(t.keys.map((e,n)=>[e,t.values[n]])):null}function m$(e,t,n=!1){let r=e.fromColumns?p$(e):null;if(!r)throw new HE(`invalid_argument`,{reason:`only datasets added with addColumns can be replaced`});let i=r;for(let e of Object.keys(t))i.set(e,l$(t[e],n));let a=i.values().next().value.length;for(let e of i.values())if(e.length!==a)throw new HE(`column_length_mismatch`);let o=Object.fromEntries(e.schema.map(e=>[e.name,e.unit])),s=d$(e.id,e.name,i,o,e.kind===`memory`?e.data.rows:void 0,e),c=s.schema.length===e.schema.length&&s.schema.every((t,n)=>t.name===e.schema[n].name);return{...s,schema:c?e.schema:s.schema,beacon:e.beacon,bands:e.bands}}var h$=new WeakMap;function g$(e){let t=e.fromColumns?p$(e):null;if(!t)return e.rawText??``;let n=e.data.rows,r=h$.get(n);if(r===void 0){let e=[...t.keys()],i=e.map(e=>t.get(e)),a=[e.join(`,`)],o=i[0].length;for(let e=0;e<o;e++)a.push(i.map(t=>t[e]===t[e]?String(t[e]):``).join(`,`));h$.set(n,r=a.join(`
|
|
616
|
+
`))}return r}function _$(e){let t=e,n=new Set;return{get:()=>t,set(e){let r=e(t);if(r!==t){t=r;for(let e of[...n])try{e()}catch(e){console.error(`[kymoscope] subscriber failed`,e)}}},subscribe(e){return n.add(e),()=>{n.delete(e)}}}}function v$(e){let t=null,n;return(...r)=>t&&t.length===r.length&&t.every((e,t)=>e===r[t])?n:(t=r,n=e(...r),n)}function y$(){let e=v$(e=>{let t={};for(let n of e){if(n.cut){let e=n.cut.defs.find(e=>e.id===n.cut.cycleId)?.show,r=e&&e.channel!==n.cut.timeKey?XB(e):null;t[n.id]=r?{laps:n.cut.parts,values:n.cut.found.map(e=>e.kpis?.[r]??null),unit:n.schema.find(t=>t.name===e.channel)?.unit??``,isTime:!1}:{laps:n.cut.parts,values:n.cut.found.map(e=>e.tend===null?null:e.tend-e.tstart),unit:`s`,isTime:!0};continue}if(!n.beacon||n.kind!==`memory`)continue;let{channel:e,metric:r,stat:i}=n.beacon,a=TB(n.data.rows,e);if(a.length===0)continue;let o=n.data.units[n.data.columnNames.indexOf(r)]??``;t[n.id]={laps:a.map((e,t)=>{let r={...n.data,rows:n.data.rows.slice(e.start,e.end)};return{...n,id:NB(n.id,t),name:`${n.name} · Cycle ${t+1}`,data:r,source:new XE(r)}}),values:a.map(e=>kB(n.data.rows,e,r,i)),unit:o,isTime:i===`span`&&jB(r,o)}}return t}),t=v$((e,t,n)=>e.flatMap(e=>t[e.id]?t[e.id].laps.filter(e=>n.includes(e.id)):n.includes(e.id)?[e]:[])),n=v$((e,t)=>e.filter(e=>e.kind===`data`&&t.includes(e.id))),r=v$(e=>cZ(e.map(e=>e.data))),i=v$((e,t)=>t.length===0?e:cZ(e?[e,...t.map(e=>e.dataset)]:t.map(e=>e.dataset))),a=v$((e,t,n,r)=>{let i=new Set;if(e)for(let t of n.length>0?n:[e])for(let e of fZ(t.columnNames,t.rows))i.add(e);for(let e of r)for(let t of e.dataset.columnNames)(t===`ElapsedTime`||e.source.hasValues(t))&&i.add(t);let a=e?e.columnNames.filter(e=>i.has(e)):[],o=t.filter(e=>e.kind!==`memory`).flatMap(e=>jz(e.schema));return[...new Set([...a,...o])]});return{lapsByDataset:e,selectedDatasets:t,selectedLive:n,staticDataset:r,mergedDataset:i,mergedParts:v$((e,t)=>[...e.map(e=>e.data),...t.map(e=>e.dataset)]),numericColumns:v$((e,t,n,r=[],i=[])=>{let o=a(e,t,r,i),s=new Set(o);return[...o,...n.map(e=>e.name).filter(e=>!s.has(e))]}),allColumns:v$((e,t,n)=>[...new Set([...e?.columnNames??[],...t.filter(e=>e.kind!==`memory`).flatMap(e=>e.schema.map(e=>e.name)),...n.map(e=>e.name)])]),columnUnits:v$((e,t)=>{let n={};e&&e.columnNames.forEach((t,r)=>{let i=e.units[r]?.trim();i&&(n[t]=i)});for(let e of t)e.units&&(n[e.name]=e.units);return n})}}var b$=[{kind:`multiband`,label:`Multi-band`},{kind:`xyscatter`,label:`X-Y scatter`},{kind:`xyzmesh`,label:`X-Y-Z mesh`},{kind:`histogram`,label:`Histogram`},{kind:`polar`,label:`Polar`},{kind:`spectrum`,label:`Spectrum`},{kind:`boxplot`,label:`Box Plot`},{kind:`spectrogram`,label:`Spectrogram`},{kind:`heatmap`,label:`Heatmap`},{kind:`violin`,label:`Violin`},{kind:`confusion`,label:`Confusion Matrix`},{kind:`roc`,label:`ROC Curve`},{kind:`losscurve`,label:`Loss Curves`},{kind:`controlchart`,label:`Control Chart`},{kind:`parallelcoords`,label:`Parallel Coords`},{kind:`embedding`,label:`Embedding`},{kind:`flamegraph`,label:`Flame Graph`},{kind:`barchart`,label:`Bar Chart`},{kind:`radar`,label:`Radar`},{kind:`areachart`,label:`Area Chart`},{kind:`cdfchart`,label:`CDF / ECDF`},{kind:`bubblechart`,label:`Bubble Chart`},{kind:`treemap`,label:`Treemap`},{kind:`sankey`,label:`Sankey`},{kind:`calibration`,label:`Calibration Curve`},{kind:`gauge`,label:`Gauges`},{kind:`camera`,label:`Camera`},{kind:`qqplot`,label:`Q-Q Plot`},{kind:`gantt`,label:`Gantt Chart`}],x$=new Map(b$.map(e=>[e.kind,e.label]));function S$(e){return x$.get(e)??e}var C$=`kymoscope-live.v1`,w$=`kymoscope-live.ack1`,T$=`kymoscope-live.ack2`,E$=1e3,D$=2e3,O$=3e4,k$=1e4,A$=30,j$=1e4,M$=300,N$=90,P$=e=>e.startsWith(`eyJ`);function F$(e){try{let t=e.split(`.`)[1]??``,n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)+`===`.slice((t.length+3)%4)),r=JSON.parse(n).exp;return typeof r==`number`?r:null}catch{return null}}function I$(e,t){return`${e.replace(/\/+$/,``)}/v1/streams/${t}/watch`}function L$(e,t,n,r){let i=null,a=null,o=null,s=!1,c=0,l=()=>{o&&=(clearTimeout(o),null)},u=(n,r)=>{l();let a=F$(r);if(a===null)return;let c=P$(r),d=c?Math.min(a,Date.now()/1e3+M$):a,f=Math.min(Math.max((d-(c?N$:A$))*1e3-Date.now(),j$),2**31-1);o=setTimeout(async()=>{o=null;let r=null;try{r=await e.getToken(t)}catch{r=null}if(!(s||i!==n||!r)){try{n.send(JSON.stringify({type:`auth`,token:r}))}catch{return}u(n,r)}},f)},d=(e=!1)=>{if(s||a)return;let t=e?0:Math.min(O$,D$*2**c++)*(.75+Math.random()/2);a=setTimeout(()=>{a=null,f()},t)},f=async()=>{if(s)return;let a=null;try{a=await e.getToken(t)}catch{a=null}if(s)return;if(!a){r?.(`error`),d();return}let o=new WebSocket(I$(e.url,t),[C$,w$,T$,`bearer.${a}`]);o.binaryType=`arraybuffer`,i=o;let f=a,p=Date.now(),m=0,h=setInterval(()=>{if(!(m===0||o.readyState!==1)){try{o.send(JSON.stringify({type:`ack`,b:m}))}catch{return}m=0}},E$);o.onopen=()=>{r?.(`subscribed`),u(o,f)},o.onmessage=e=>{if(c=0,typeof e.data!=`string`){m+=e.data.byteLength,n(e.data);return}if(e.data.startsWith(`{"type":"probe"`))try{let t=JSON.parse(e.data).id;typeof t==`string`&&t.length<=64&&o.send(JSON.stringify({type:`ack`,id:t}))}catch{}},o.onclose=()=>{clearInterval(h),i===o&&(i=null,l(),!s&&(r?.(`error`),d(Date.now()-p>=k$)))}};return f(),()=>{if(s=!0,a&&=(clearTimeout(a),null),l(),i){let e=i;i=null,e.close(1e3)}}}var R$=960*1024,z$=24;function B$(e){let t=e.key&&e.fragIndex===0?new TextEncoder().encode(e.codec):new Uint8Array;if(t.length>255)throw Error(`codec string too long`);let n=e.key&&e.fragIndex===0?1+t.length:0,r=new Uint8Array(z$+n+e.payload.length),i=new DataView(r.buffer);i.setUint8(0,1),i.setUint8(1,!!e.key|(e.last?2:0)),i.setUint8(2,1),i.setUint8(3,0),i.setFloat64(4,e.t,!0),i.setUint32(12,e.seq>>>0,!0),i.setUint16(16,e.fragIndex,!0),i.setUint16(18,e.fragCount,!0),i.setUint16(20,e.width,!0),i.setUint16(22,e.height,!0);let a=z$;return n&&(r[a++]=t.length,r.set(t,a),a+=t.length),r.set(e.payload,a),r}function V$(e){if(e.length<z$||e[0]!==1||e[2]!==1)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=(e[1]&1)!=0,r=t.getUint16(16,!0),i=t.getUint16(18,!0);if(i===0||r>=i)return null;let a=z$,o=``;if(n&&r===0){if(e.length<a+1||e.length<a+1+e[a])return null;o=new TextDecoder().decode(e.subarray(a+1,a+1+e[a])),a+=1+e[a]}return{key:n,last:(e[1]&2)!=0,t:t.getFloat64(4,!0),seq:t.getUint32(12,!0),fragIndex:r,fragCount:i,width:t.getUint16(20,!0),height:t.getUint16(22,!0),codec:o,payload:e.subarray(a)}}function H$(e){let t=Math.max(1,Math.ceil(e.data.length/R$)),n=[];for(let r=0;r<t;r++)n.push(B$({key:e.key,last:r===t-1,t:e.t,seq:e.seq,fragIndex:r,fragCount:t,width:e.width,height:e.height,codec:e.codec,payload:e.data.subarray(r*R$,Math.min(e.data.length,(r+1)*R$))}));return n}function U$(e,t,n){let r=new Map,i=Promise.resolve(),a=n?re(n,e=>t({type:`integrity`,integrity:e})):null;return Object.assign(n=>{let s=c(e,n).catch(()=>null);a?.arrive(n,new Uint8Array(n,0,1)[0]&127,s),i=i.then(async()=>{try{let e=await s;if(!e)return;if(e.kind===6){let n=V$(e.plaintext);n&&t({type:`video`,m:n})}else if(e.kind===5){let t=N(e.plaintext);r.set(t.id,t)}else if(e.kind===7){let n=o(e.plaintext,r);n&&t({type:`last`,values:n})}else if(e.kind===4){let n=await at(e.plaintext,r);n&&!n.historical&&t({type:`columns`,block:n.block})}else if(e.kind===3)t({type:`columns`,block:rt(e.plaintext)});else if(e.kind===2){let n=ke(e.plaintext);t({type:`frames`,frames:Array.isArray(n?.frames)?n.frames:[]})}}catch{}})},{reset:()=>a?.reset()})}var W$=``+new URL(`assets/liveIngestWorker-w4p7hYsW.js`,import.meta.url).href;function G$(e,t,n,r,i){let a=()=>{let a=U$(n,r,t);return L$(e,t,a,e=>{e===`subscribed`&&a.reset(),i?.(e)})},o;try{if(typeof Worker>`u`)return a();o=UE(W$)}catch{return a()}let s=!1,c=()=>{try{o.postMessage({type:`stop`})}catch{o.terminate()}};return o.onmessage=a=>{let s=a.data;if(s.type===`decoded`){if(r(s.d),s.bytes)try{o.postMessage({type:`ack`,bytes:s.bytes})}catch{}}else if(s.type===`status`)i?.(s.status);else if(s.type===`ask`){let r=s.what===`token`?e.getToken(t):typeof n==`function`?n(s.arg):n;Promise.resolve(r).catch(()=>null).then(e=>{try{o.postMessage({type:`reply`,id:s.id,value:e})}catch{}})}},o.onerror=()=>{o.terminate(),!s&&(c=a())},o.postMessage({type:`start`,url:e.url,streamId:t,key:typeof n==`function`?null:n}),()=>{s=!0,c()}}var K$=class{samples=[];exact=!1;windowS;constructor(e=30){this.windowS=e}observe(e,t){if(e>1e9){this.samples=[],this.exact=!0;return}this.exact=!1;let n=t-e,r=this.samples[this.samples.length-1];for(r&&Math.abs(n-r.off)>1&&(this.samples=[]),this.samples.push({at:t,off:n});this.samples.length&&this.samples[0].at<t-this.windowS;)this.samples.shift()}quality(){return this.exact?`exact`:this.samples.length?`approx`:`none`}toWall(e,t=0){if(this.exact)return e+t/1e3;if(!this.samples.length)return null;let n=1/0;for(let e of this.samples)n=Math.min(n,e.off);return e+n+t/1e3}toStream(e,t=0){let n=this.toWall(0,t);return n===null?null:e-n}},q$=class{#e;constructor(e){this.#e=typeof e==`function`?e:()=>e}size(){return this.#e().size}get columnNames(){return this.#e().columnNames}version(){return this.#e().version}columns(){let e=this.#e();return new J$(new Set(e.columnNames),t=>e.mirrorColumn(t))}hasValues(e){return this.#e().hasValues(e)}snapshot(e){return this.#e().toDataset(e)}async getSchema(){let e=this.#e();return e.columnNames.map(t=>({name:t,type:`number`,unit:e.unitOf(t)}))}async getSeries(e){let t=this.#e();return ee(t.columnValues(e.viewport.xKey),t.columnValues(e.column),e.viewport.x0,e.viewport.x1,e.maxPoints)}async getSeriesMulti(e,t,n){return this.getSeriesMultiSync(e,t,n)}getSeriesMultiSync(e,t,n){return this.#e().decimateColumns(t.xKey,e,t.x0,t.x1,n)}getPointsSync(e,t,n){return this.#e().decimatePoints(t.xKey,e,t.x0,t.x1,n)}async xBounds(e){return this.xBoundsSync(e)}xBoundsSync(e){return this.#e().columnBounds(e)}xTravelSync(e,t){return this.#e().xTravel(e,t)}timeAfterSync(e){return this.#e().timeAfter(e)}latestTimeSync(){return this.#e().latestTime()}xAtTimeSync(e,t,n=!1){return this.#e().xAtTime(e,t,n)}latestSync(e){return this.#e().lastValue(e)}latestValuesSync(e){let t=this.#e(),n=new Map;for(let r of e){let e=t.lastValue(r),i=t.lastKnown(r);Number.isFinite(e)?n.set(r,e):i&&n.set(r,i.v)}return n}valueBoundsSync(e){let t=this.#e().valueBounds(e),n=this.#e().lastKnown(e);if(!t&&!n)return null;let r=Math.min(t?.x0??1/0,n?.v??1/0),i=Math.max(t?.x1??-1/0,n?.v??-1/0);if(r!==i)return{min:r,max:i};let a=Math.max(.5,Math.abs(r)*.05);return{min:r-a,max:i+a}}lastKnownSync(e){return this.#e().lastKnown(e)}trackCycles(e){this.#e().trackCycles(e)}cycleSpanSync(e){return this.#e().cycleSpan(e)}decimateCycleSync(e,t,n,r,i){return this.#e().decimateCycle(e,t,n,r.x0,r.x1,i)}cyclePointsSync(e,t,n,r,i){return this.#e().decimateCyclePoints(e,t,n,r.x0,r.x1,i)}async readColumns(e,t,n){let r=this.#e(),i=new Set(r.columnNames),a={};for(let o of e)i.has(o)&&(a[o]=r.columnValues(o).slice(t,t+n));return a}async dispose(){}},J$=class extends Map{#e;#t;constructor(e,t){super(),this.#e=e,this.#t=t}get(e){if(!super.has(e)&&this.#e.has(e)){let t=this.#t(e);t&&super.set(e,t)}return super.get(e)}has(e){return this.#e.has(e)}},Y$=4096,X$=5e3,Z$=class{startedAt=Date.now();n=0;capacity=Y$;time=new Float64Array(Y$);cols=new Map;order=[];units=new Map;timeColumn;timeUnit;constructor(e=n,t=`s`){this.timeColumn=e,this.timeUnit=t}get rows(){return this.n}add(e){this.n===this.capacity&&this.grow();let t=this.n;this.time[t]=e.t;for(let n of e.signals){let e=this.cols.get(n.name);e||(e=new Float64Array(this.capacity).fill(NaN),this.cols.set(n.name,e),this.order.push(n.name)),n.unit&&!this.units.get(n.name)&&this.units.set(n.name,n.unit),e[t]=typeof n.value==`number`?n.value:NaN}this.n++}addColumns(e){let t=S(e,this.timeColumn),n=e.t.length;for(;this.n+n>this.capacity;)this.grow();let r=this.n,i=(e,t)=>{if(t instanceof Float64Array||t instanceof Float32Array)e.set(t,r);else for(let i=0;i<n;i++)e[r+i]=+t[i]};i(this.time,e.t);for(let n of t){let t=this.cols.get(n);t||(t=new Float64Array(this.capacity).fill(NaN),this.cols.set(n,t),this.order.push(n));let r=e.units?.[n];r&&!this.units.get(n)&&this.units.set(n,r),i(t,e.columns[n])}this.n+=n}grow(){let e=this.capacity*2,t=new Float64Array(e);t.set(this.time),this.time=t;for(let[t,n]of this.cols){let r=new Float64Array(e).fill(NaN);r.set(n),this.cols.set(t,r)}this.capacity=e}toCsvParts(){let e=[this.timeColumn,...this.order],t=[this.timeUnit,...this.order.map(e=>this.units.get(e)??``)],n=[`${e.map(Q$).join(`,`)}\n${t.map(Q$).join(`,`)}\n`],r=this.order.map(e=>this.cols.get(e));for(let e=0;e<this.n;e+=X$){let t=Math.min(this.n,e+X$),i=``;for(let n=e;n<t;n++){i+=String(this.time[n]);for(let e of r){let t=e[n];i+=Number.isNaN(t)?`,`:`,${t}`}i+=`
|
|
617
|
+
`}n.push(i)}return n}};function Q$(e){let t=/^[=+\-@\t\r]/.test(e)?`'${e}`:e;return/[",\n\r]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var $$=512,e1=new WeakMap;function t1(e,t,n){let r=e1.get(e);r||e1.set(e,r=new Map);let i=r.get(t),a={start:n,values:[]};return{carry:{start:e=>{let t=i?.values[e];if(!i||!t)return 0;for(let e=Math.min(n-i.start,t.length-1);e>=0;e--){let n=t[e];if(n!==null&&Number.isFinite(n))return n}return 0},done:(e,t)=>{a.values[e]=t}},keep:()=>{r.set(t,a)}}}function n1(e,t,r){let i=e.endAbs,a=Math.max(r,e.firstAbs);if(a>=i||t.length===0)return;let o=new Set(e.columnNames);for(let r of t){if(!r.enabled)continue;let s=dE(r.formula);if(!s.ok)continue;let{identifiers:c,functions:l}=fE(s.node);if(!c.every(e=>o.has(e)))continue;let u=l.some(e=>lE.includes(e)),d=Math.max(e.firstAbs,a-(u?$$:0)),f=new Map([n,...c].map(t=>[t,e.range(t,d,i)])),{carry:p,keep:m}=t1(e,`${r.id}|${r.formula}`,d),h=vE(r,e=>f.get(e),n,i-d,t,p);h.status===`ok`&&(e.writeComputed(r.name,r.units,a,h.values.subarray(a-d)),m())}}function r1(e,t){e.clearComputed(),e1.delete(e),n1(e,t,e.firstAbs)}var i1=8e3,a1=131072;function o1(e,t={}){switch(e.kind){case`elapsed`:return{name:`Elapsed`,unit:`s`};case`event`:return{name:`Since ${e.channel} ${e.op} ${e.value}`,unit:`s`};case`clock`:return{name:`Time of day`,unit:`s`};default:{let n=t[e.channel]??``;return e.integral?{name:`∫${e.channel}`,unit:n?`${n}·s`:`s`}:{name:`${e.channel} since start`,unit:n}}}}var s1=new Map;function c1(e,t){let n=`${t}|${Math.floor(e/900)}`,r=s1.get(n);r===void 0&&(r=yB(e,t),s1.size>1e4&&s1.clear(),s1.set(n,r));let i=(e+r)%86400;return i<0?i+86400:i}var l1=class{axis;#e=NaN;#t=NaN;#n=NaN;#r=0;#i=NaN;#a=NaN;constructor(e){this.axis=e}begin(e){this.#e=e,this.#t=NaN,this.#n=NaN,this.#r=0,this.#i=NaN,this.#a=NaN}x(e,t){let n=this.axis;return n.kind===`clock`?c1(e,n.tz):n.kind===`elapsed`?e-this.#e:e<this.#e?NaN:n.kind===`event`?(this.#t!==this.#t&&t===t&&mB(n.op,t,n.value)&&(this.#t=e),e-this.#t):n.integral?(t===t&&(this.#i===this.#i&&(this.#r+=(t+this.#i)/2*(e-this.#a)),this.#i=t,this.#a=e),this.#i===this.#i?this.#r:NaN):(t===t&&(this.#n!==this.#n&&(this.#n=t),this.#i=t),this.#i===this.#i?this.#i-this.#n:NaN)}};function u1(e,t,n,r){let i=`channel`in r?t.get(r.channel):void 0;if(r.kind===`event`){let a=NaN;for(let t=0;t<e.length&&a!==a;t++){let o=i?i[t]:NaN;e[t]>=n&&o===o&&mB(r.op,o,r.value)&&(a=e[t])}return{x:e.map(e=>e-a),t:e,cols:t}}let a=new l1(r);a.begin(n);let o=new Float64Array(e.length);for(let t=0;t<e.length;t++)o[t]=a.x(e[t],i?i[t]:NaN);return{x:o,t:e,cols:t}}function d1(e,t,n){let r=[];for(let n=0;n<e.length;n++)e[n]===e[n]&&t[n]===t[n]&&r.push(n);let i=!0;for(let t=1;t<r.length&&i;t++)i=e[r[t-1]]<=e[r[t]];i||r.sort((t,n)=>e[t]-e[n]);let a=r.length,o=new Float64Array(n.length).fill(NaN);if(a<2)return o;let s=Float64Array.from(r,t=>e[t]),c=Float64Array.from(r,e=>t[e]),l=Float64Array.from({length:a-1},(e,t)=>s[t+1]-s[t]).sort(),u=l[l.length>>1],d=u>0?4*u:1/0,f=0;for(let e=0;e<n.length;e++){let t=n[e];if(!(t>=s[0]&&t<=s[a-1]))continue;for(;f<a-2&&s[f+1]<t;)f++;let r=s[f],i=s[f+1];i-r>d||(o[e]=i===r?c[f]:c[f]+(c[f+1]-c[f])*(t-r)/(i-r))}return o}function f1(e,t,n){let r=e.length;if(r===0||!(n>=e[0]&&n<=e[r-1]))return NaN;if(r===1)return t[0];let i=(n-e[0])/(e[r-1]-e[0])*(r-1),a=Math.min(r-2,Math.floor(i));return t[a]+(t[a+1]-t[a])*(i-a)}function p1(e,t,n){let r=Math.max(2,Math.min(i1,Math.floor(n)));if(r*t.length>131072)throw Error(`too_many_cells`);let i=1/0,a=-1/0;for(let t of e)for(let e of t.x)e===e&&(e<i&&(i=e),e>a&&(a=e));if(!(a>i))throw Error(`empty`);let o=Float64Array.from({length:r},(e,t)=>i+t*(a-i)/(r-1)),s=new Map;for(let n of t){let t=new Uint16Array(r),i=new Float64Array(r),a=new Float64Array(r),c=new Float32Array(r).fill(1/0),l=new Float32Array(r).fill(-1/0);for(let s of e){let e=s.cols.get(n);if(!e)continue;let u=d1(s.x,e,o);for(let e=0;e<r;e++){let n=u[e];if(n!==n)continue;let r=++t[e],o=n-i[e];i[e]+=o/r,a[e]+=o*(n-i[e]),n<c[e]&&(c[e]=n),n>l[e]&&(l[e]=n)}}let u={mean:new Float32Array(r),sd:new Float32Array(r),min:c,max:l,n:t};for(let e=0;e<r;e++){if(t[e]===0){u.mean[e]=u.sd[e]=u.min[e]=u.max[e]=NaN;continue}u.mean[e]=i[e],u.sd[e]=t[e]>1?Math.sqrt(a[e]/(t[e]-1)):0}s.set(n,u)}return{x:o,channels:s}}function m1(e,t){if(e.unit===`abs`)return e.tolerance;let n=1/0,r=-1/0;for(let e of t.mean)e===e&&(e<n&&(n=e),e>r&&(r=e));return r>=n?Math.max(r-n,Math.abs(r),Math.abs(n))*e.tolerance/100:0}var h1=new WeakMap;function g1(e){let t=h1.get(e);if(t)return t;let n=e.sd.length,r=Math.max(2,Math.round(n/100));t=new Float32Array(n).fill(NaN);for(let i=0;i<n;i++){if(e.n[i]<2)continue;let a=0,o=0;for(let t=Math.max(0,i-r);t<=Math.min(n-1,i+r);t++)e.n[t]>=2&&e.sd[t]===e.sd[t]&&(a+=e.sd[t]**2,o++);t[i]=o?Math.sqrt(a/o):NaN}return h1.set(e,t),t}function _1(e,t,n){if(n===`minmax`)return{lo:e.min,hi:e.max};if(n===`sigma`){let n=g1(e);return{lo:e.mean.map((e,r)=>e-t*n[r]),hi:e.mean.map((e,r)=>e+t*n[r])}}let r=m1(n,e);return{lo:e.mean.map(e=>e-r),hi:e.mean.map(e=>e+r)}}function v1(e,t,n,r=`sigma`,i=0){let a=typeof r==`function`?r:()=>({band:r,k:n}),o=[...t.channels.keys()],s=new Map,c=new Map,l=[],u=new Uint8Array(e.t.length),d=o.map(()=>new Uint8Array(e.t.length)),f=t.x.length;o.forEach((n,r)=>{let i=t.channels.get(n),o=e.cols.get(n);if(!o)return;let{band:p,k:m}=a(n),h=typeof p==`object`?p:null,{lo:g,hi:_}=_1(i,m,p),v=0,y=0,b=0;for(let e of i.mean)if(e===e){v++;let t=e-y;y+=t/v,b+=t*(e-y)}let x=v>1?Math.max(Math.sqrt(b/(v-1)),1e-9):1e-9,S=h?Math.max(m1(h,i),1e-9):0,C=g1(i),w=new Float64Array(e.t.length).fill(NaN),T=new Float64Array(e.t.length).fill(NaN),E=0,D=0;for(let n=0;n<e.t.length;n++){let a=o[n],s=e.x[n];if(a!==a||s!==s)continue;let c=f1(t.x,i.mean,s);if(c!==c)continue;w[n]=a-c;let l=Math.round((s-t.x[0])/(t.x[f-1]-t.x[0])*(f-1));T[n]=Math.abs(a-c)/(h?S:i.n[l]>=2&&C[l]===C[l]?Math.max(C[l],1e-9):x),E+=T[n],D++,(h||i.n[l]>=2)&&(a<f1(t.x,g,s)||a>f1(t.x,_,s))&&(u[n]=1,d[r][n]=1)}s.set(n,w),c.set(n,T),l.push({channel:n,z:D?E/D:0})}),l.sort((e,t)=>t.z-e.z);let p=[];for(let t=0;t<u.length;t++){if(!u[t])continue;let n=t;for(;n<u.length&&u[n];)n++;let r=p[p.length-1];r&&e.t[t]-e.t[Math.min(r[1],u.length-1)]<i?r[1]=n:p.push([t,n]),t=n}let m=[];for(let[t,n]of p){let r=e.t[t],a=e.t[Math.min(n,u.length-1)];a-r>=i&&m.push({t0:r,t1:a,channels:o.filter((e,r)=>d[r].subarray(t,n).includes(1))})}return{delta:s,score:l,deviations:m,z:c}}function y1(e,t){let n=e.x.length,r=t.length,i=new DataView(new ArrayBuffer(12+8*n+r*n*18));[75,82,66,49].forEach((e,t)=>i.setUint8(t,e)),i.setUint32(4,n,!0),i.setUint32(8,r,!0);let a=12;for(let t=0;t<n;t++,a+=8)i.setFloat64(a,e.x[t],!0);for(let r of t){let t=e.channels.get(r);if(!t)throw Error(`The reference has no channel ${r}`);for(let e of[t.mean,t.sd,t.min,t.max])for(let t=0;t<n;t++,a+=4)i.setFloat32(a,e[t],!0);for(let e=0;e<n;e++,a+=2)i.setUint16(a,t.n[e],!0)}return _e(new Uint8Array(i.buffer))}function b1(e,t){let n=fe(e),r=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.length<12||String.fromCharCode(n[0],n[1],n[2],n[3])!==`KRB1`)throw Error(`Not a reference band`);let i=r.getUint32(4,!0),a=r.getUint32(8,!0);if(a!==t.length||n.length!==12+8*i+a*i*18)throw Error(`This reference band does not match its channels`);let o=12,s=new Float64Array(i);for(let e=0;e<i;e++,o+=8)s[e]=r.getFloat64(o,!0);let c=new Map;for(let e of t){let t=()=>{let e=new Float32Array(i);for(let t=0;t<i;t++,o+=4)e[t]=r.getFloat32(o,!0);return e},n=t(),a=t(),s=t(),l=t(),u=new Uint16Array(i);for(let e=0;e<i;e++,o+=2)u[e]=r.getUint16(o,!0);c.set(e,{mean:n,sd:a,min:s,max:l,n:u})}return{x:s,channels:c}}function x1(e){if(!e.cycle)throw Error(`a live segment axis needs a cycle rule`);let t=new RB(e.cycle),r=new l1(e.axis),i=NaN,a=`channel`in e.axis?e.axis.channel:null,o=[...new Set([...LB(e.cycle),...a?[a]:[]])];return{feed(s,c,l=!1){let u=Math.max(c,s.firstAbs),d=s.endAbs;if(u>=d)return;let f=t=>{l||e.onEvent?.(t)},p=s.range(n,u,d),m=new Map(o.map(e=>[e,s.range(e,u,d)])),h=new Float64Array(p.length).fill(NaN),g=a?m.get(a):null,_=[];for(let e=0;e<p.length;e++){t.step(p[e],t=>{let n=m.get(t);return n?n[e]:NaN},_);let n=t.open()?.tstart??null;n!==null&&(n!==i&&(i=n,r.begin(n),f({type:`open`,tstart:n})),h[e]=r.x(p[e],g?g[e]:NaN))}for(let e of _)f({type:`close`,segment:{tstart:e.tstart,tend:e.tend,kpis:{duration:(e.tend??e.tstart)-e.tstart},...e.flags.length?{flags:e.flags}:{}}});s.writeComputed(e.column,e.unit,u,h)}}}var S1=1e7;function C1(e=globalThis.navigator?.deviceMemory){return Math.max(512,Math.round(((e??0)>0?e:16)*1024/8))}var w1=400,T1=4e3,E1=1e3,D1=3e3,O1=2,k1=5e3,A1=1e4;function j1(e,t,n=`data`){let r=new De(t.capacity??S1,void 0,void 0,(t.maxMemoryMB??C1())*1024*1024);return{meta:e,buffer:r,source:new q$(()=>r),unsub:()=>{},status:`connecting`,error:null,lastFrameAt:Date.now(),lastColCount:0,lastValued:0,recorder:null,dropped:0,recDropped:0,video:n===`camera`?new VE:null,clock:n===`camera`?null:new K$,lagTicks:0,lastRejoinAt:0,rejoin:()=>{},subscribed:!1,releaseTimer:void 0}}function M1(e,t,n,r){let i,a=-1/0,o=new Map;return async c=>{if(i===void 0&&(i=c,o.set(t,c)),c===i)return e;if(Date.now()-a<2e3)return null;a=Date.now();let l=await r().catch(()=>null);if(!l||o.has(l.salt)&&o.get(l.salt)!==c)return null;let u=l.key??(n===null?null:await We(n,l.salt));return!u||!await s(u,l.key_check).catch(()=>!1)?null:(o.set(l.salt,c),u)}}function N1(e,t,n=()=>({}),r){let i=new Map,a=e,o=[],c=[],l=``,u=()=>{let e=[];for(let t of i.values())t.lastColCount=t.buffer.columnNames.length,t.lastValued=t.buffer.valuedCount,e.push({...t.meta,kind:t.video?`camera`:`data`,video:t.video,clock:t.clock,dataset:t.buffer.toDataset(w1),source:t.source,rowCount:t.buffer.size,status:t.status,error:t.error,recordingSince:t.recorder?.startedAt??null,droppedSamples:t.dropped,...t.integrity?{integrity:t.integrity}:{}});o=e,t(o)},d=(e,t)=>{let n=!1,r=e.buffer.endAbs;for(let r of t)r&&typeof r.t==`number`&&Array.isArray(r.signals)&&(e.buffer.push(r),e.recorder?.add(r),n=!0);n&&p(e,r,t[t.length-1]?.t)},f=(e,t)=>{let n=e.buffer.endAbs;e.buffer.pushColumns(t),e.recorder?.addColumns(t),t.t.length>0&&p(e,n,t.t[t.t.length-1])},p=(e,t,n)=>{n1(e.buffer,c,t),e.segAxis?.tracker.feed(e.buffer,t),r?.rows(e.meta.id,e.buffer,t),typeof n==`number`&&e.clock?.observe(n,Date.now()/1e3),m(e,t===0||e.buffer.columnNames.length!==e.lastColCount||e.buffer.valuedCount!==e.lastValued)},m=(e,t)=>{e.lastFrameAt=Date.now();let n=e.status===`stale`||e.status===`connecting`;n&&(e.status=`live`),(n||t)&&u()},h=e=>{let t=i.get(e);t&&(clearTimeout(t.releaseTimer),t.unsub(),i.delete(e),u())},g=setInterval(()=>{let e=Date.now(),t=!1;for(let n of i.values()){n.status===`live`&&e-n.lastFrameAt>T1&&(n.status=`stale`,t=!0);let i=n.video&&n.subscribed&&n.status===`live`?n.video.info().lagMs:null;n.lagTicks=i!==null&&i>D1?n.lagTicks+1:0,n.video&&n.lagTicks>=O1&&e-n.lastRejoinAt>=k1&&(n.lagTicks=0,n.lastRejoinAt=e,n.video.resync(),n.unsub(),n.rejoin()),n.buffer.size&&r?.tick(n.meta.id,n.buffer,n.lastFrameAt)}t&&u()},E1);return{connections:()=>o,disconnect:h,startRecording(e){let t=i.get(e);!t||t.recorder||(t.recorder=new Z$,t.recDropped=0,u())},stopRecording(e){let t=i.get(e),n=t?.recorder;return!t||!n?null:(t.recorder=null,u(),{csv:n.toCsvParts(),rows:n.rows,name:t.meta.name,startedAt:n.startedAt,droppedSamples:t.recDropped})},setRelay(e){a=e},setSegmentAxis(e,t){let n=i.get(e);n&&(n.segAxis=t?{cfg:t,tracker:x1(t)}:void 0,t&&n.segAxis.tracker.feed(n.buffer,n.buffer.firstAbs,!t.replay),u())},setMathChannels(e){let t=JSON.stringify(e.map(e=>[e.id,e.name,e.units,e.formula,e.enabled]));if(t!==l){l=t,c=e;for(let t of i.values())t.video||(r1(t.buffer,e),t.segAxis&&(t.segAxis.tracker=x1(t.segAxis.cfg),t.segAxis.tracker.feed(t.buffer,t.buffer.firstAbs,!0)));i.size>0&&u()}},openLocal(e,t){let r=`local:${crypto.randomUUID()}`,a=j1({id:r,name:e,ownerName:`This page`,visibility:`private`,orgName:null,parentId:null,lowOf:null},{...n(),...t});return i.set(r,a),u(),{id:r,push:e=>{i.get(r)===a&&d(a,Array.isArray(e)?e:[e])},pushColumns:e=>{i.get(r)===a&&f(a,e)},close:()=>h(r)}},async connect(e,t,r){if(i.has(e.id))return;let o=a&&e.relay_url?{...a,url:e.relay_url,getToken:async e=>{let t=await a.getToken(e);return t&&!P$(t)?t:null}}:a;if(!o)throw new HE(`relay_unavailable`);let c;if(typeof t==`string`){let n=ct(t).secret??t,i=await We(n,e.salt);if(!await s(i,e.key_check))throw new HE(`wrong_password`);c=r?.reload?M1(i,e.salt,n,r.reload):i}else if(c=`keyFor`in t?e=>t.keyFor(e):t,typeof c!=`function`){if(!await s(c,e.key_check))throw new HE(`wrong_password`);r?.reload&&(c=M1(c,e.salt,null,r.reload))}let l=j1({id:e.id,name:e.name,ownerName:e.owner_name??``,visibility:e.visibility??`private`,orgName:e.org_name??null,projectName:e.project_name??null,parentId:e.parent_stream_id??null,lowOf:e.low_of_stream_id??null,limitNotice:e.limit_notice??null},{...n(),...r},e.kind);i.set(e.id,l);let p=t=>{if(i.get(e.id)===l)if(t.type===`video`)l.video&&(l.video.push(t.m),m(l,!1));else if(t.type===`last`){let e=l.buffer;for(let n of t.values)e.setLastKnown(n.name,n.unit,n.t,n.v);(e.columnNames.length!==l.lastColCount||e.valuedCount!==l.lastValued)&&u()}else if(t.type===`gap`)l.dropped+=t.samples,l.recorder&&(l.recDropped+=t.samples),u();else if(t.type===`integrity`){let e=l.integrity;l.integrity=t.integrity,(!e||e.broken!==t.integrity.broken)&&u()}else t.type===`columns`?f(l,t.block):d(l,t.frames)},h=t=>{!l.subscribed||i.get(e.id)!==l||(t===`subscribed`?(l.status=`live`,l.lastFrameAt=Date.now()):t===`error`&&(l.status=`error`,l.error=`connection_error`),u())};l.rejoin=()=>{l.unsub=l.video?L$(o,e.id,U$(c,p),h):G$(o,e.id,c,p,h)};let g=l.video;g?(l.status=`idle`,g.onDemandChange(t=>{i.get(e.id)===l&&(clearTimeout(l.releaseTimer),t?l.subscribed||(l.subscribed=!0,g.resync(),l.status=`connecting`,l.lastFrameAt=Date.now(),l.rejoin(),u()):l.releaseTimer=setTimeout(()=>{l.subscribed=!1,l.unsub(),l.unsub=()=>{},l.status=`idle`,l.error=null,l.lagTicks=0,u()},A1))})):(l.subscribed=!0,l.rejoin()),u()},dispose(){clearInterval(g);for(let e of i.values())clearTimeout(e.releaseTimer),e.unsub();i.clear(),o=[]}}}var P1=500,F1=1<<20;function I1(e){let t=[],r=new Map,i=[],a=``,o=(e,t)=>`${e}|${t}`,s=(e,t)=>{let n=t.kind===`stream`?e.targets?.streams:t.kind===`history`?e.targets?.histories:e.targets?.datasets;return!n||n.includes(t.kind===`dataset`?t.name??t.id:t.id)},c=()=>[...r.values()].map(e=>{let{state:t,missing:n,since:r}=e.state();return{ruleId:e.rule.id,target:e.target,state:t,...n?{missing:n}:{},...r===void 0?{}:{since:r}}}),l=()=>{let t=c(),n=JSON.stringify(t);n!==a&&(a=n,e.setStates(t))};function u(n,r){let a=t.find(e=>e.id===n.ruleId);if(n.kind===`raised`){i=[...i,{id:`${n.ruleId}|${n.target.id}|${n.t}`,ruleId:n.ruleId,ruleName:a?.name??``,severity:a?.severity??`info`,targetId:n.target.id,timeColumn:r,t0:n.t,t1:null}];let e=i.filter(e=>e.targetId===n.target.id);e.length>P1&&(i=i.filter(t=>t!==e[0]))}else{let e=i.find(e=>e.ruleId===n.ruleId&&e.targetId===n.target.id&&e.t1===null);e&&(i=i.map(t=>t===e?{...t,t1:n.t}:t))}e.setMarks(i),e.emit(n)}function d(){let i=new Set;for(let a of e.targets())for(let e of t){if(!s(e,a))continue;let t=o(e.id,a.id);i.add(t);let c=r.get(t),{channels:l,...d}=a;(!c||c.rule!==e)&&(c=dt(e,d),r.set(t,c));for(let e of c.bind(l))u(e,a.kind===`stream`?n:``)}for(let e of r.keys())i.has(e)||r.delete(e);l()}return{setRules(n){let r=[],i=n.filter(e=>{let t=ft(e);return r.push(...t.map(t=>({ruleId:String(e?.id??``),...t}))),!t.length}),a=e.maxRules();a!==null&&i.length>a&&e.limit();let o=new Map(t.map(e=>[e.id,e]));return t=(a===null?i:i.slice(0,a)).map(e=>{let t=o.get(e.id);return t&&t.version===e.version?t:e}),d(),r},rules:()=>t,state:c,async evaluate(n,r){let a=e.targets().find(e=>e.id===n&&e.kind===`dataset`);if(!a)return[];let{channels:o,...c}=a,l=[],d=t.filter(e=>(!r.ruleIds||r.ruleIds.includes(e.id))&&s(e,c)),f=d.map(e=>{let t=dt(e,c);return t.bind(o),t}),p=[...new Set(d.flatMap(e=>Object.values(e.signals).map(e=>`formula`in e?e.formula:e.channel)))];for(let t=0;;t+=F1){let i=await e.readDataset(n,[r.timeColumn,...p],t,F1),a=i[r.timeColumn];if(!a||!a.length)break;for(let e of f)l.push(...e.push({t:a,columns:i}));if(a.length<F1)break}i=i.filter(e=>!(e.targetId===n&&(!r.ruleIds||r.ruleIds.includes(e.ruleId)))),e.setMarks(i);for(let e of l)u(e,r.timeColumn);return l},pushLive(e,t){let i=!1;for(let a of r.values()){if(a.target.id!==e)continue;let r=a.push(t);r.length&&(i=!0);for(let e of r)u(e,n)}i&&l()},tickLive(e,t){let i=!1;for(let a of r.values()){if(a.target.id!==e)continue;let r=a.tick(t);r.length&&(i=!0);for(let e of r)u(e,n)}i&&l()},liveColumns(e){let t=new Set;for(let n of r.values())if(n.target.id===e)for(let e of Object.values(n.rule.signals))t.add(`formula`in e?e.formula:e.channel);return[...t]},sync:d,clearMarks(t){i=t?i.filter(e=>e.targetId!==t):[],e.setMarks(i)}}}var L1=class{past=[];future=[];current=null;lastAt=-1/0;o;equals;constructor(e){this.o=e,this.equals=e.equals??Object.is}get canUndo(){return this.past.length>0}get canRedo(){return this.future.length>0}observe(e){if(this.current===null)return this.current=e,!1;if(this.equals(e,this.current))return!1;let t=this.o.now();return t-this.lastAt<this.o.mergeMs&&this.past.length>0||(this.past.push(this.current),this.past.length>this.o.limit&&this.past.shift()),this.current=e,this.future=[],this.lastAt=t,!0}rebase(e){this.current=e}undo(){if(this.past.length===0)return null;let e=this.past.pop();return this.future.push(this.current),this.current=e,this.lastAt=-1/0,e}redo(){if(this.future.length===0)return null;let e=this.future.pop();return this.past.push(this.current),this.current=e,this.lastAt=-1/0,e}clear(e){this.past=[],this.future=[],this.current=e,this.lastAt=-1/0}},R1={maxChartsPerWorksheet:null,maxChannelsPerChart:null,maxWorksheets:null,maxMathChannels:null,maxAlertRules:null,canImportExportWorkspaces:!0},z1=[];function B1(e,t){let n=e.found[t];return{definitionId:n.definitionId,rule:e.defs.find(e=>e.id===n.definitionId)?.name??n.definitionId,index:n.index,parentIndex:n.parentIndex??null,tstart:n.tstart,tend:n.tend,flags:n.flags,kpis:n.kpis??{},incomplete:!!n.incomplete}}var V1=[`#a78bfa`,`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#94a3b8`];function H1(e=`ET`){return{id:crypto.randomUUID(),name:`Worksheet`,panels:[],panelChartSettings:{},panelChartBackgrounds:{},xKey:e}}function U1(e,t){let n=e.filter(e=>e.source!==`workbook`),r=new Map,i=[];for(let e of t){let t=n.find(t=>t.name===e.name);if(t&&t.formula===e.formula&&t.units===e.units)continue;let a=t?`${e.name} (workbook)`:e.name;t&&r.set(e.name,a),i.push(yr({...e,name:a,source:`workbook`}))}return{channels:i,rename:r}}function W1(e,t){let n=JSON.stringify({xKey:e.xKey,panelChartSettings:e.panelChartSettings});for(let[e,r]of t)n=n.split(JSON.stringify(e)).join(JSON.stringify(r));return{...e,...JSON.parse(n)}}function G1(e){return typeof e.text==`function`?e.text():new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result??``)),r.onerror=()=>n(r.error),r.readAsText(e)})}function K1(e,t,n){if(!e||!t)return dn();let{min:r,max:i}=Mz(e.rows,t);if(!Number.isFinite(r)||!Number.isFinite(i))return dn();let a=Pz(i-r||1,6),o=a>=1?Math.round(a):a,s=o>=1?1:o/10,c=Math.max(0,Math.ceil(-Math.log10(s))),l=e=>String(Number(e.toFixed(c)));return{...n,scaleMin:l(Math.floor(r/s)*s),scaleMax:l(Math.ceil(i/s)*s),majorStep:l(o),minorStep:``}}function q1(e,t){let r=t.includes(e.xKey)?e.xKey:t.includes(`ET`)?`ET`:t.includes(`ElapsedTime`)?n:t[0],i={...e.panelChartSettings};for(let n of e.panels){let e=i[n.id];if(n.kind===`multiband`){let r=e&&e.kind===`multiband`?e:wn();i[n.id]={...r,kind:`multiband`,addColumn:r.addColumn&&t.includes(r.addColumn)?r.addColumn:t[0]}}else if(n.kind===`xyscatter`){let r=e&&e.kind===`xyscatter`?e:Tn(V1[2]),a=r.xyXCol||t[0],o=r.xyYCol||(t.length>1&&t[1]!==a?t[1]:t[0]);i[n.id]={...r,kind:`xyscatter`,xyXCol:a,xyYCol:o}}else if(n.kind===`xyzmesh`){let r=e&&e.kind===`xyzmesh`?e:En(4),a=r.xyzXCol||t[0],o=r.xyzYCol||(t.length>1?t[1]:t[0]),s=r.xyzZCol||(t.length>2?t[2]:t[0]);i[n.id]={...r,kind:`xyzmesh`,xyzXCol:a,xyzYCol:o,xyzZCol:s}}}return{...e,xKey:r,panelChartSettings:i}}function J1(e,t){let n=!1,r={...e.panelChartSettings};for(let[i,a]of Object.entries(e.panelChartSettings)){if(a.kind!==`multiband`)continue;let e=a.series.filter(e=>t(e.column));e.length!==a.series.length&&(r[i]={...a,series:e},n=!0)}return n?{...e,panelChartSettings:r}:e}function Y1(){return typeof document>`u`?`dark`:lB(null)}function X1(e={}){let t={...e},r=!1,i=H1(),a=_$({datasets:[],selection:[],worksheets:[i],activeWorksheetId:i.id,xRanges:{},offsets:{},colors:{},liveWindowSeconds:15,cycleRules:[],live:[],video:[],mathChannels:[],limits:{...R1,...t.limits},palette:oB(t.palette,Y1()),importing:0,licensed:null,history:{canUndo:!1,canRedo:!1},marks:[],alerts:[],alertRules:[]}),o=KV(),s=()=>{let e=oB(t.palette,Y1());a.set(t=>t.palette.join()===e.join()?t:{...t,palette:e})},c=typeof document>`u`?()=>{}:uB(null,s),l=y$(),u=()=>{if(r)throw new HE(`disposed`)},d=e=>{throw o.emit(`limit`,{reason:e}),new HE(`limit_reached`,{reason:e})},f=()=>a.get(),p=(e,t)=>{let n=f().limits.maxChannelsPerChart,r=Nz(t);n!==null&&r>n&&r>Nz(e)&&d(`channels-per-chart`)},m=v$((e,t)=>t===null?e:e.slice(0,t)),h=()=>{let e=f(),t=l.lapsByDataset(e.datasets),n=l.selectedDatasets(e.datasets,t,e.selection),r=l.selectedLive(e.live,e.selection),i=l.staticDataset(n),a=l.mergedDataset(i,r),o=m(e.mathChannels,e.limits.maxMathChannels);return{laps:t,selectedDatasets:n,selectedLive:r,staticDataset:i,merged:a,channels:o,numericColumns:l.numericColumns(a,n,o,l.mergedParts(n,r),r),allColumns:l.allColumns(a,n,o),columnUnits:l.columnUnits(a,o)}},g=(e,t)=>({id:t.id,kind:t.kind,title:t.title??null,settings:e.panelChartSettings[t.id],background:e.panelChartBackgrounds[t.id]??null,annotations:e.panelChartSettings[t.id]?.annotations??z1,layout:t.rect,window:t.window??null}),_=v$((e,t,n)=>e.map(e=>({id:e.id,name:e.name,xKey:e.xKey,xRange:t[e.id]??null,liveWindowSeconds:e.liveWindowSeconds===void 0?n:e.liveWindowSeconds,charts:e.panels.map(t=>g(e,t))}))),v=v$((e,t,n,r,i,a,o)=>{let s=(e,t)=>{let n=a.findIndex(t=>t.id===e);return n>=0?n:t};return e.map((e,a)=>{let c=i[e.id],l=c?.laps.map(e=>e.id)??[],u=l.filter(e=>t.includes(e)).length;return{id:e.id,name:e.name,kind:e.kind,columns:e.schema.map(e=>({name:e.name,unit:e.unit??``,numeric:e.type===`number`})),rowCount:e.data.rows.length,color:iB(n,e.id,s(e.id,a),o),customColor:e.id in n,offset:r[e.id]??0,parseConfig:e.parseConfig??null,fileInfo:e.info??null,beacon:e.beacon??null,cut:e.cut?{cycleId:e.cut.cycleId,timeKey:e.cut.timeKey,defs:e.cut.defs}:null,laps:c?c.laps.map((i,a)=>({id:i.id,name:i.name,value:c.values[a],unit:c.unit,isTime:c.isTime,color:iB(n,i.id,s(i.id,a),o),offset:r[i.id]??0,selected:t.includes(i.id),...e.cut?{cycle:B1(e.cut,a)}:{}})):null,selected:c?u===0?!1:u===l.length?!0:`partial`:t.includes(e.id)}})}),y=v$((e,t,n,r,i)=>{let a=e.filter(e=>t.includes(e.id)).map(e=>e.id);return e.map((e,o)=>({id:e.id,name:e.name,ownerName:e.ownerName,visibility:e.visibility,orgName:e.orgName,kind:e.kind,parentId:e.parentId,lowOf:e.lowOf,status:e.status,error:e.error,rowCount:e.rowCount,selected:t.includes(e.id),color:iB(n,e.id,a.includes(e.id)?r+a.indexOf(e.id):o,i),customColor:e.id in n,recordingSince:e.recordingSince,limitNotice:e.limitNotice??null,...e.integrity?{integrity:e.integrity}:{},channels:e.dataset.columnNames}))}),b=v$(e=>{let t=h();return{datasets:v(e.datasets,e.selection,e.colors,e.offsets,t.laps,t.selectedDatasets,e.palette),selection:e.selection,worksheets:_(e.worksheets,e.xRanges,e.liveWindowSeconds),activeWorksheetId:e.activeWorksheetId,mathChannels:t.channels,live:y(e.live,e.selection,e.colors,t.selectedDatasets.length,e.palette),liveWindowSeconds:(()=>{let t=e.worksheets.find(t=>t.id===e.activeWorksheetId);return t?.liveWindowSeconds===void 0?e.liveWindowSeconds:t.liveWindowSeconds})(),cycleRules:e.cycleRules,limits:e.limits,palette:e.palette,importing:e.importing,licensed:e.licensed,hasData:t.merged!==null,multiDataset:t.selectedDatasets.length+t.selectedLive.length>1,numericColumns:t.numericColumns,allColumns:t.allColumns,columnUnits:t.columnUnits,history:e.history,marks:e.marks,alerts:e.alerts}}),x=(e,t)=>e===t||e.length===t.length&&e.every((e,n)=>e===t[n]||JSON.stringify(e)===JSON.stringify(t[n])),S=new L1({limit:100,mergeMs:500,now:()=>Date.now(),equals:(e,t)=>e.liveWindowSeconds===t.liveWindowSeconds&&x(e.worksheets,t.worksheets)&&x(e.channels,t.channels)}),C=!0,w=0,T=e=>{w++;try{e()}finally{w--}},E=e=>[e.worksheets,e.mathChannels,e.liveWindowSeconds],D=[],O=()=>{let e=f();return{worksheets:e.worksheets,channels:e.mathChannels.filter(e=>e.source===`workbook`),liveWindowSeconds:e.liveWindowSeconds,activeWorksheetId:e.activeWorksheetId}},k=()=>a.set(e=>e.history.canUndo===S.canUndo&&e.history.canRedo===S.canRedo?e:{...e,history:{canUndo:S.canUndo,canRedo:S.canRedo}}),A=()=>{if(C)return;let e=E(f());e.every((e,t)=>e===D[t])||(D=e,w?S.rebase(O()):S.observe(O()),k())},j=()=>{D=E(f()),S.clear(O()),k()},M=e=>{C=!0;let t;try{t=e()}finally{C=!1}return j(),t},N=()=>b(f());a.subscribe(()=>{A(),o.emit(`change`,N())});let P=e=>{let t=f(),n=t.worksheets.find(n=>n.id===(e??t.activeWorksheetId));if(!n)throw new HE(`not_found`,{worksheetId:e});return n},F=e=>{for(let t of f().worksheets){let n=t.panels.find(t=>t.id===e);if(n)return{ws:t,panel:n}}throw new HE(`not_found`,{chartId:e})},I=(e,t)=>{let n=e=>e&&t?e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height:!e&&!t,r=f().worksheets.find(t=>t.panels.some(t=>t.id===e&&!n(t.window)));r&&T(()=>L(r.id,n=>({...n,panels:n.panels.map(n=>{if(n.id!==e)return n;if(t)return{...n,window:{...t}};let{window:r,...i}=n;return i})})))},L=(e,t)=>a.set(n=>{let r=!1,i=n.worksheets.map(n=>{if(n.id!==e)return n;let i=t(n);return i!==n&&(r=!0),i});return r?{...n,worksheets:i}:n}),R=(e,t)=>{let{ws:n}=F(e);L(n.id,n=>({...n,panelChartSettings:{...n.panelChartSettings,[e]:t(n.panelChartSettings[e])}}))},z=e=>a.set(t=>e.length===t.selection.length&&e.every((e,n)=>e===t.selection[n])?t:{...t,selection:e,xRanges:{}}),B=new Set,V=N1(t.live?.relay,e=>{let t=e.map(e=>e.id),r=e.filter(e=>e.kind===`data`&&!B.has(e.id)).map(e=>e.id),i=[...B].filter(e=>!t.includes(e));if(B=new Set(t),a.set(t=>({...t,live:e})),i.length&&z(f().selection.filter(e=>!i.includes(e))),r.length){let e=f().selection,t=r.filter(t=>!e.includes(t));t.length&&z([...e,...t])}let o=h();if(o.selectedLive.length&&o.merged){let e=o.merged.columnNames;if(e.includes(`ElapsedTime`))for(let t of f().worksheets)e.includes(t.xKey)||T(()=>L(t.id,e=>({...e,xKey:n})))}},()=>({capacity:t.live?.capacity,maxMemoryMB:t.live?.maxMemoryMB}),{rows:(e,t,r)=>{if(!se.rules().length)return;t.columnNames.length!==ee.get(e)&&(ee.set(e,t.columnNames.length),se.sync());let i=se.liveColumns(e);if(!i.length)return;let a=t.endAbs,o=Math.max(r,t.firstAbs);if(a<=o)return;let s={};for(let e of i)s[e]=t.range(e,o,a);se.pushLive(e,{t:t.range(n,o,a),columns:s,scan:new Map})},tick:(e,t,r)=>{if(!se.rules().length)return;let i=t.range(n,t.endAbs-1,t.endAbs)[0];i===i&&se.tickLive(e,i+(Date.now()-r)/1e3)}}),ee=new Map,te=v$((e,t)=>e.filter(e=>t.some(t=>NE([e],t.panelChartSettings,t.xKey).length>0))),H=()=>V.setMathChannels(te(m(f().mathChannels,f().limits.maxMathChannels),f().worksheets));H(),a.subscribe(H);let ne=e=>{a.set(t=>({...t,datasets:[...t.datasets,e]})),z([...f().selection,e.id]);let t=jz(e.schema);t.length&&T(()=>a.set(e=>({...e,worksheets:e.worksheets.map(e=>q1(e,t))})))},re=Promise.resolve(),ie=async(e,n={})=>{u();let i=e.map(e=>e instanceof File?e:e.file);if(i.length===0)return{ids:[],errors:[]};if(await t.beforeImport?.()===!1)throw new HE(`import_vetoed`);let{signal:s}=n;a.set(e=>({...e,importing:e.importing+i.length}));let c=re.then(async()=>{let e={ids:[],errors:[]},t=i.length,c=e=>{t-=e,a.set(t=>({...t,importing:Math.max(0,t.importing-e)}))};try{let{items:t,errors:a}=await LR(i);c(i.length-t.length);for(let{file:t,error:n}of a)e.errors.push({file:t,error:n}),o.emit(`import`,{file:t,phase:`error`,error:n}),o.emit(`error`,{error:n,context:`import`});for(let i of t){if(r)break;if(s?.aborted){e.cancelled=!0;break}let t=i.main;await new Promise(e=>setTimeout(e,0)),o.emit(`import`,{file:t.name,phase:`start`});try{let a=i.format?await Az({main:t,companions:i.companions,format:i.format.id},{priorInMemoryValues:kR(f().datasets),signal:s,onProgress:e=>o.emit(`import`,{file:t.name,phase:`progress`,fraction:e}),chooseChannels:n.chooseChannels,pickChannels:n.pickChannels}):[await OR(crypto.randomUUID(),t,f().datasets)??await ER(crypto.randomUUID(),t,G1,void 0,kR(f().datasets),s)];if(r){for(let e of a)e.source.dispose();break}if(s?.aborted){for(let e of a)e.source.dispose();throw new HE(`cancelled`)}for(let t of a)ne(t),e.ids.push(t.id);o.emit(`import`,{file:t.name,phase:`done`,datasetId:a[0].id,datasetIds:a.map(e=>e.id)})}catch(n){let r=n instanceof Error?n:Error(String(n));o.emit(`import`,{file:t.name,phase:`error`,error:r}),r instanceof HE&&r.code===`cancelled`?e.cancelled=!0:(e.errors.push({file:t.name,error:r}),o.emit(`error`,{error:r,context:`import`}))}finally{c(1)}if(e.cancelled)break}}finally{t>0&&c(t)}return e});return re=c.catch(()=>void 0),c},U=()=>setTimeout(()=>{r||FQ(rt)},0),ae=e=>{let t=t=>e.some(e=>t===e||t.startsWith(`${e}::`)),n=f().datasets.filter(t=>e.includes(t.id));for(let e of n)e.source.dispose().catch(()=>void 0);a.set(n=>{let r={...n.offsets},i={...n.colors};for(let e of Object.keys(r))t(e)&&delete r[e];for(let e of Object.keys(i))t(e)&&delete i[e];return{...n,datasets:n.datasets.filter(t=>!e.includes(t.id)),offsets:r,colors:i}}),z(f().selection.filter(e=>!t(e))),n.length>0&&U()},oe=async(e,t,n={})=>{let[r,...i]=await Az({main:new File(e.chunks,`${e.name}.krc`),companions:[],format:`krc`,keys:e.keys},{priorInMemoryValues:t,...n});for(let e of i)e.source.dispose();return{...r,file:void 0,name:e.name,info:r.info&&{...r.info,startTime:e.startTime??r.info.startTime,meta:{...r.info.meta,recordingId:e.recordingId}}}},se=I1({targets:()=>[...f().datasets.map(e=>({kind:`dataset`,id:e.id,name:e.name,channels:e.schema.map(e=>e.name)})),...f().live.filter(e=>e.kind===`data`).map(e=>({kind:`stream`,id:e.id,name:e.name,channels:e.source.columnNames}))],maxRules:()=>f().limits.maxAlertRules,emit:e=>o.emit(`alert`,e),limit:()=>o.emit(`limit`,{reason:`alert-rules`}),setMarks:e=>a.set(t=>({...t,marks:e})),setStates:e=>a.set(t=>({...t,alerts:e})),readDataset:(e,t,n,r)=>{let i=f().datasets.find(t=>t.id===e);return i?i.source.readColumns(t,n,r):Promise.resolve({})}}),ce=v$((e,t)=>{let n=new Map;for(let r of e){let e=mt(r);e!==null&&n.set(r.id,{value:e,active:t.some(e=>e.ruleId===r.id&&(e.state===`active`||e.state===`clearing`))})}return n}),le=null;a.subscribe(()=>{let e=f();le&&le[0]===e.datasets&&le[1]===e.live||(le=[e.datasets,e.live],se.rules().length&&se.sync())});let ue={importFiles:ie,warmImport(e={}){u(),vz(!!e.formats?.some(e=>e===`hdf5`||e===`mat`))},async splitByRate(e){u();let t=f().datasets.find(t=>t.id===e);if(!t)throw new HE(`not_found`,{datasetId:e});if(!t.info?.combined||!(t.file instanceof File))throw new HE(`invalid_argument`,{reason:`only a combined multi-rate import can be split`});let n=await Az({main:t.file,companions:t.companions??[],format:t.info.importer},{priorInMemoryValues:kR(f().datasets.filter(t=>t.id!==e)),selection:t.info.selection,split:!0});ae([e]);for(let e of n)ne(e);return n.map(e=>e.id)},async chooseChannels(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{datasetId:e});if(!n.info||!(n.file instanceof File))throw new HE(`invalid_argument`,{reason:`only binary imports have channels to choose`});try{let r=await Az({main:n.file,companions:n.companions??[],format:n.info.importer},{priorInMemoryValues:kR(f().datasets.filter(t=>t.id!==e)),initial:n.info.selection,chooseChannels:t,pickChannels:!0});ae([e]);for(let e of r)ne(e);return r.map(e=>e.id)}catch(e){if(e instanceof HE&&e.code===`cancelled`)return null;throw e}},async combine(e){u();let t=f().datasets.find(t=>t.id===e);if(!t)throw new HE(`not_found`,{datasetId:e});let n=t.info?.splitKey;if(!n||!(t.file instanceof File))throw new HE(`invalid_argument`,{reason:`only datasets split from one file can be combined`});let r=f().datasets.filter(e=>e.info?.splitKey===n),i=await Az({main:t.file,companions:t.companions??[],format:t.info.importer},{priorInMemoryValues:kR(f().datasets.filter(e=>!r.includes(e))),selection:r.flatMap(e=>e.info.selection)});if(i.length!==1){for(let e of i)e.source.dispose();throw new HE(`invalid_argument`,{reason:`these groups have no common time base`})}return ae(r.map(e=>e.id)),ne(i[0]),i[0].id},async openRecording(e,t={}){u();let n=await oe(e,kR(f().datasets),t);return ne(n),n.id},async reopenRecording(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{datasetId:e});let r=await oe(t,kR(f().datasets.filter(t=>t.id!==e)));a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?{...r,id:e,beacon:n.beacon}:t)})),n.source.dispose().catch(()=>void 0),U()},addColumns(e){u();let t=u$(crypto.randomUUID(),e);return ne(t),t.id},replaceColumns(e,t,n={}){u();let r=f().datasets.find(t=>t.id===e);if(!r)throw new HE(`not_found`,{datasetId:e});let i=m$(r,t,n.transfer);a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?i:t)}))},writeColumns(e,t,n){u();let r=f().datasets.find(t=>t.id===e);if(!r)throw new HE(`not_found`,{datasetId:e});let i=f$(r,t,n);a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?i:t)}))},async addText(e,t=`dataset.csv`){u();let n=await CR(crypto.randomUUID(),t,e);return ne(n),n.id},async findCycles(e,t,n){u();let r=f().datasets.find(t=>t.id===e);if(!r)throw new HE(`not_found`,{datasetId:e});let i=await qB(r.source,n,YB(t)),a=new Map(t.filter(e=>e.kpis?.length).map(e=>[e.id,e.kpis]));return JB(i,t).map(e=>a.has(e.definitionId)?{...e,kpis:ZB(i,e,a.get(e.definitionId))}:e)},async addCycles(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{datasetId:e});let r=n.schema.filter(e=>e.type===`number`&&e.name!==t.timeKey).map(e=>e.name),i=await qB(n.source,t.timeKey,r),a={...Object.fromEntries(n.schema.map(e=>[e.name,e.unit])),[GB]:`s`},o=e=>t.defs.find(t=>t.id===e)?.name??e,s=[];for(let e of t.pick){let r=t.found.find(t=>t.definitionId===e.definitionId&&t.index===e.index&&t.parentIndex===e.parentIndex);if(!r)throw new HE(`not_found`,{reason:`no ${o(e.definitionId)} ${e.index} in the cycles found`});let c=r.parentIndex?`${o(t.cycleId)} ${r.parentIndex} · ${o(r.definitionId)}`:`${o(r.definitionId)} ${r.index}`;s.push(ue.addColumns({name:`${n.name} · ${c}`,columns:$B(i,t.timeKey,r),units:a}))}if(t.tables!==!1){let e=tV(t.found,t.cycleId,t.defs,i);s.push(await ue.addText(nV(e.cycles),`${n.name} · ${o(t.cycleId)}s.csv`)),e.phases.length&&s.push(await ue.addText(nV(e.phases),`${n.name} · Phases.csv`))}return s},async cut(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{datasetId:e});let r;if(t){if(!t.defs.some(e=>e.id===t.cycleId))throw new HE(`invalid_argument`,{reason:`cycleId is not one of defs`});let i=n.schema.filter(e=>e.type===`number`&&e.name!==t.timeKey).map(e=>e.name),a=await qB(n.source,t.timeKey,i),o=t.defs.find(e=>e.id===t.cycleId)?.show,s=e=>[...e.kpis??[],...o&&o.channel!==t.timeKey?[o]:[]],c=new Map(t.defs.filter(e=>s(e).length).map(e=>[e.id,s(e)])),l=JB(a,t.defs).sort((e,t)=>e.tstart-t.tstart||!!e.parentIndex-+!!t.parentIndex).map(e=>c.has(e.definitionId)?{...e,kpis:ZB(a,e,c.get(e.definitionId))}:e),u={...Object.fromEntries(n.schema.map(e=>[e.name,e.unit])),[GB]:`s`},d=e=>t.defs.find(t=>t.id===e)?.name??e,f=l.map(r=>u$(`${e}::${r.definitionId}:${r.parentIndex??0}:${r.index}`,{name:r.parentIndex?`${n.name} · ${d(t.cycleId)} ${r.parentIndex} · ${d(r.definitionId)}`:`${n.name} · ${d(r.definitionId)} ${r.index}`,columns:$B(a,t.timeKey,r),units:u})),p=a.t.length?a.t[a.t.length-1]:NaN,m=l.map(e=>e.tend===null&&p===p?{...e,tend:p,incomplete:!0}:e);r={defs:t.defs,cycleId:t.cycleId,timeKey:t.timeKey,found:m,parts:f}}else if(!n.cut)return 0;if(!f().datasets.some(t=>t.id===e))return 0;a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?{...t,cut:r}:t)}));let i=f().selection,o=i.some(t=>t===e||t.startsWith(`${e}::`)),s=i.filter(t=>t!==e&&!t.startsWith(`${e}::`)),c=r?r.parts.filter((e,t)=>!r.found[t].parentIndex).map(e=>e.id):[];return z(o?c.length>0?[...s,...c]:[...s,e]:s),c.length},remove(e){u(),ae([e])},clear(){u(),ae(f().datasets.map(e=>e.id))},async configure(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{datasetId:e});if(t.parseConfig&&(n.kind!==`memory`||!n.parseConfig))throw new HE(`invalid_argument`,{reason:n.parseConfig?`out-of-core datasets cannot be re-parsed`:`binary files have no text parse settings`});if(t.beacon!==void 0&&t.beacon!==null&&n.kind!==`memory`)throw new HE(`invalid_argument`,{reason:`laps need an in-memory dataset`});if(t.beacon!==void 0&&JSON.stringify(t.beacon)!==JSON.stringify(n.beacon??null)){let r=t.beacon??void 0;a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?{...t,beacon:r}:t)}));let i=f().selection,o=i.some(t=>t===e||t.startsWith(`${e}::`)),s=i.filter(t=>t!==e&&!t.startsWith(`${e}::`)),c=r?TB(n.data.rows,r.channel):[],l=r&&t.selectCycles===`best`?AB(c.map(e=>kB(n.data.rows,e,r.metric,r.stat))):null,u=l===null?c.map((t,n)=>NB(e,n)):[NB(e,l)];z(o?c.length>0?[...s,...u]:[...s,e]:s)}let r=t.parseConfig;if(!r)return;let i=(()=>{try{let e=ze(Te(n.rawText??``),r.headerRow);return n.data.columnNames.length===e.length&&n.data.columnNames.every((t,n)=>t===e[n])}catch{return!1}})();if(Ye(r,n.parseConfig)&&i)return;let o=n.fromColumns?g$(n):n.rawText??``,s=await qE(n.file?{file:n.file,config:r}:{rawText:o,config:r}),c=new XE(s),l=await c.getSchema(),d=n.fromColumns?{rawText:o,fromColumns:!1}:{};a.set(t=>({...t,datasets:t.datasets.map(t=>t.id===e?{...t,...d,data:s,source:c,schema:l,parseConfig:r}:t)})),n.source.dispose().catch(()=>void 0),U(),n.cut&&await ue.cut(e,n.cut);let p=h().selectedDatasets,m=new Set(p.flatMap(e=>e.data.columnNames)),g=s.columnNames.filter(e=>Ze(s.rows,e)),_=g.find(e=>e===`ET`)??g[0];T(()=>a.set(e=>({...e,worksheets:e.worksheets.map(e=>J1(!m.has(e.xKey)&&_?{...e,xKey:_}:e,e=>m.has(e)))})))},setColor(e,t){u(),a.set(n=>{let r={...n.colors};return t===null?delete r[e]:r[e]=t,{...n,colors:r}})},setOffset(e,t){u(),a.set(n=>({...n,offsets:{...n.offsets,[e]:t}}))},resetOffsets(){u(),a.set(e=>Object.keys(e.offsets).length?{...e,offsets:{}}:e)},select(e){u(),z([...e])},toggle(e){u();let t=f().selection,n=h().laps[e];if(n){let e=n.laps.map(e=>e.id);z(e.every(e=>t.includes(e))?t.filter(t=>!e.includes(t)):[...t,...e.filter(e=>!t.includes(e))]);return}z(t.includes(e)?t.filter(t=>t!==e):[...t,e])},selectAll(){u();let e=h().laps,t=f().live.filter(e=>f().selection.includes(e.id)).map(e=>e.id);z([...f().datasets.flatMap(t=>e[t.id]?e[t.id].laps.map(e=>e.id):[t.id]),...t])},deselectAll(){u(),z([])},raw(e){let t=f().datasets.find(t=>t.id===e);if(!t)throw new HE(`not_found`,{datasetId:e});return{get rawText(){return t.kind===`memory`&&t.fromColumns?g$(t):t.rawText??``},data:t.data,parseConfig:t.parseConfig??null,kind:t.kind,beacon:t.beacon??null}},async columnBounds(e){u();let t=h(),n=t.selectedDatasets.find(t=>t.schema.some(t=>t.name===e));if(n&&n.kind===`memory`){let t=Mz(n.data.rows,e);if(Number.isFinite(t.min)&&Number.isFinite(t.max))return t}else if(n){let t=await n.source.xBounds(e).catch(()=>null);if(t&&Number.isFinite(t.x0)&&Number.isFinite(t.x1)&&t.x1>=t.x0)return{min:t.x0,max:t.x1}}let r=t.selectedLive.find(t=>t.dataset.columnNames.includes(e));if(r){let t=r.source.valueBoundsSync(e);if(t)return t}let i=de(e);if(!i)return null;let a=Mz(i.rows,e);return Number.isFinite(a.min)&&Number.isFinite(a.max)?a:null}},de=(e,t=P().xKey)=>{let n=h();if(!n.merged)return null;if(!n.channels.find(t=>t.name===e))return n.merged;let r=ME(n.merged,n.channels,t);return{...n.merged,columnNames:[...n.merged.columnNames,...r.ok.map(e=>e.name)],rows:r.rows}},fe=(e,t,n)=>h().selectedLive.length>0?{...n,scaleMin:``,scaleMax:``,majorStep:``,minorStep:``}:K1(de(e,t),e,n),pe={fromFileList:e=>NV(Array.from(e)),async fromDataTransfer(e){return PV(Array.from(e.items??[]).map(e=>e.webkitGetAsEntry?.()).filter(e=>!!e))},canPick:FV,pick:IV,tree:(e,t)=>MV(e,t),isImportable:jV},me={add(e=`Worksheet`){u();let t=f(),n=t.limits.maxWorksheets;n!==null&&t.worksheets.length>=n&&d(`worksheets`);let r={...H1(P().xKey||`ET`),name:e};return a.set(e=>({...e,worksheets:[...e.worksheets,r],activeWorksheetId:r.id})),r.id},rename(e,t){u(),P(e),L(e,e=>e.name===t?e:{...e,name:t})},remove(e){u();let t=f();if(P(e),t.worksheets.length<=1)throw new HE(`invalid_argument`,{reason:`the last worksheet cannot be removed`});let n=t.worksheets.findIndex(t=>t.id===e),r=t.worksheets.filter(t=>t.id!==e);a.set(t=>({...t,worksheets:r,activeWorksheetId:t.activeWorksheetId===e?r[Math.max(0,n-1)].id:t.activeWorksheetId}))},reorder(e,t){u(),a.set(n=>{if(e===t||e<0||t<0||e>=n.worksheets.length||t>=n.worksheets.length)return n;let r=[...n.worksheets],[i]=r.splice(e,1);return r.splice(t,0,i),{...n,worksheets:r}})},activate(e){u(),P(e),a.set(t=>t.activeWorksheetId===e?t:{...t,activeWorksheetId:e,xRanges:{...t.xRanges,[e]:null}})},setXKey(e,t){u(),P(e),L(e,e=>J1({...e,xKey:t},e=>e!==t)),a.set(t=>({...t,xRanges:{...t.xRanges,[e]:null},offsets:{}}))}},he={mount(e,t,n){return u(),PQ(rt,e,t,n)},openWindow(e,t){u(),F(e);let n=F(e).panel.window;return i$(rt,e,(t,n)=>PQ(rt,e,t,n),{...n,...t})},recordWindows(){u();let e=o$(rt);for(let t of f().worksheets)for(let n of t.panels)I(n.id,e.get(n.id)??null)},setFonts(e){e.sans&&(Q.sans=e.sans),e.mono&&(Q.mono=e.mono),FQ(rt)},kinds:()=>b$,label:S$,add(e,t={}){if(u(),!b$.some(t=>t.kind===e))throw new HE(`invalid_argument`,{kind:e});let n=P(t.worksheetId),r=f().limits.maxChartsPerWorksheet;r!==null&&n.panels.length>=r&&d(`charts-per-worksheet`);let i={...cn(e,n.panels),...t.title?{title:t.title}:{}};t.layout&&(i.rect={...t.layout});let a=hr([i],{},V1[2],4)[i.id],o=a,s=h().numericColumns;if(s.length&&(o.kind===`multiband`||o.kind===`xyscatter`||o.kind===`xyzmesh`)&&(o=q1({...n,panels:[i],panelChartSettings:{[i.id]:o}},s).panelChartSettings[i.id],o.kind===`multiband`&&(o={...o,addColumn:s.find(e=>e!==n.xKey)??s[0]})),t.settings&&(o={...o,...t.settings,kind:o.kind}),s.length&&o.kind===`xyscatter`){let e=t.settings??{};o={...o,xyXScale:e.xyXScale??fe(o.xyXCol,n.xKey,o.xyXScale),xyYScale:e.xyYScale??fe(o.xyYCol,n.xKey,o.xyYScale)}}return p(a,o),L(n.id,e=>({...e,panels:t.layout?[...e.panels,i]:un([...e.panels,i]),panelChartSettings:{...e.panelChartSettings,[i.id]:o}})),i.id},remove(e){u();let{ws:t}=F(e);L(t.id,t=>{let n={...t.panelChartSettings},r={...t.panelChartBackgrounds};return delete n[e],delete r[e],{...t,panels:un(t.panels.filter(t=>t.id!==e)),panelChartSettings:n,panelChartBackgrounds:r}})},rename(e,t){u();let{ws:n}=F(e),r=t?.trim()||void 0;L(n.id,t=>({...t,panels:t.panels.map(t=>{if(t.id!==e)return t;let{title:n,...i}=t;return r?{...i,title:r}:i})}))},update(e,t){u();let{ws:n}=F(e),r=n.panelChartSettings[e],i={...r,...t,kind:r.kind};if(r.kind===`xyscatter`&&i.kind===`xyscatter`){let e=t;typeof e.xyXCol==`string`&&e.xyXCol!==r.xyXCol&&!(`xyXScale`in e)&&(i={...i,xyXScale:fe(e.xyXCol,n.xKey,r.xyXScale)}),typeof e.xyYCol==`string`&&e.xyYCol!==r.xyYCol&&!(`xyYScale`in e)&&(i={...i,xyYScale:fe(e.xyYCol,n.xKey,r.xyYScale)})}p(r,i),R(e,()=>i)},replaceSettings(e,t){u();let{ws:n,panel:r}=F(e);if(t.kind!==r.kind)throw new HE(`invalid_argument`,{reason:`settings kind mismatch`});p(n.panelChartSettings[e],t),R(e,()=>t)},setBackground(e,t){u();let{ws:n}=F(e);L(n.id,n=>({...n,panelChartBackgrounds:{...n.panelChartBackgrounds,[e]:t}}))},addAnnotation(e,t){u(),F(e);let n=Wt({...t,id:t.id||crypto.randomUUID()});if(!n)throw new HE(`invalid_argument`,{reason:`not a valid annotation`});return R(e,e=>({...e,annotations:[...(e.annotations??[]).filter(e=>e.id!==n.id),n]})),n.id},updateAnnotation(e,t,n){u();let r=(F(e).ws.panelChartSettings[e]?.annotations??[]).find(e=>e.id===t);if(!r)throw new HE(`not_found`,{annotationId:t});let i=Wt({...r,...n,id:r.id,kind:r.kind});if(!i)throw new HE(`invalid_argument`,{reason:`not a valid annotation`});R(e,e=>({...e,annotations:(e.annotations??[]).map(e=>e.id===i.id?i:e)}))},removeAnnotation(e,t){u(),F(e),R(e,e=>({...e,annotations:(e.annotations??[]).filter(e=>e.id!==t)}))},setAnnotations(e,t){u(),F(e);let n=Gt(t)??[];R(e,e=>({...e,annotations:n}))},setLayout(e,t){u();let{ws:n}=F(e);L(n.id,n=>({...n,panels:n.panels.map(n=>n.id===e?{...n,rect:{...t}}:n)}))},setLayouts(e,t){u(),L(e,e=>({...e,panels:e.panels.map(e=>t[e.id]?{...e,rect:{...t[e.id]}}:e)}))},autoLayout(e){u(),L(P(e).id,e=>({...e,panels:un(e.panels)}))},get(e){let{ws:t,panel:n}=F(e);return g(t,n)},list(e){let t=P(e);return t.panels.map(e=>g(t,e))},async addSeries(e,t){u();let{ws:n}=F(e),r=n.panelChartSettings[e];if(!r||r.kind!==`multiband`)throw new HE(`invalid_argument`,{reason:`not a multiband chart`});let i=f().limits.maxChannelsPerChart;i!==null&&Nz(r)>=i&&d(`channels-per-chart`);let a=h().numericColumns,o=new Set(r.series.map(e=>e.column)),s=t??a.find(e=>e!==n.xKey&&!o.has(e))??a.find(e=>e!==n.xKey)??``;if(!s)return null;let c=vr(),l={id:c,column:s,color:V1[r.series.length%V1.length],bandFromPct:0,bandToPct:100,scaleMin:0,scaleMax:1,yMajorStep:0,yMinorStep:0};return R(e,e=>e.kind===`multiband`?{...e,series:[...e.series,l]}:e),await he.autoScaleSeries(e,c),c},async updateSeries(e,t,n){u();let{ws:r}=F(e),i=r.panelChartSettings[e],a=i&&i.kind===`multiband`?i.series.find(e=>e.id===t):void 0;if(!a)throw new HE(`not_found`,{seriesId:t});R(e,e=>e.kind===`multiband`?{...e,series:e.series.map(e=>e.id===t?{...e,...n,id:e.id}:e)}:e),n.column&&n.column!==a.column&&n.scaleMin===void 0&&n.scaleMax===void 0&&await he.autoScaleSeries(e,t)},removeSeries(e,t){u(),R(e,e=>e.kind===`multiband`?{...e,series:e.series.filter(e=>e.id!==t)}:e)},reorderSeries(e,t){u(),R(e,e=>{if(e.kind!==`multiband`)return e;let n=new Map(e.series.map(e=>[e.id,e])),r=t.map(e=>n.get(e)).filter(e=>!!e),i=e.series.filter(e=>!t.includes(e.id));return{...e,series:[...r,...i]}})},async autoScaleSeries(e,t){u();let{ws:n}=F(e),i=n.panelChartSettings[e],a=i&&i.kind===`multiband`?i.series.find(e=>e.id===t):void 0;if(!a)return;let o=await ue.columnBounds(a.column);!o||r||R(e,e=>e.kind===`multiband`?{...e,series:e.series.map(e=>e.id===t?{...e,scaleMin:o.min,scaleMax:o.max}:e)}:e)}},ge=new Map,_e={setXRange(e,t){u();let n=P(t).id;a.set(t=>{let r=t.xRanges[n]??null;return r===e||r&&e&&r[0]===e[0]&&r[1]===e[1]?t:{...t,xRanges:{...t.xRanges,[n]:e}}})},resetZoom(e){_e.setXRange(null,e)},setCursorX(e,t){u();let n=P(t).id;(ge.get(n)??null)!==e&&(ge.set(n,e),o.emit(`cursorchange`,{worksheetId:n,x:e}))},cursorX(e){return ge.get(P(e).id)??null},setLiveWindow(e,t){u();let n=P(t);n.liveWindowSeconds!==e&&L(n.id,t=>({...t,liveWindowSeconds:e}))}},ve={save(e){u();let t=e.id??crypto.randomUUID(),[n]=WB([{...e,id:t,parentId:e.parentId??null}].concat(f().cycleRules.filter(e=>e.id!==t))).filter(e=>e.id===t);if(!n)throw new HE(`invalid_argument`,{reason:`not a valid cycle rule (or its parent is missing)`});return a.set(e=>({...e,cycleRules:e.cycleRules.some(e=>e.id===t)?e.cycleRules.map(e=>e.id===t?n:e):[...e.cycleRules,n]})),t},remove(e){u();let t=new Set([e]);for(let e=!0;e;){e=!1;for(let n of f().cycleRules)n.parentId&&t.has(n.parentId)&&!t.has(n.id)&&(t.add(n.id),e=!0)}a.set(e=>({...e,cycleRules:e.cycleRules.filter(e=>!t.has(e.id))}))}},ye={create(e){u();let n=f(),r=n.limits.maxMathChannels;r!==null&&n.mathChannels.length>=r&&d(`math-channels`);let i=yr(e);return a.set(e=>({...e,mathChannels:[...e.mathChannels,i]})),Promise.resolve(t.mathChannels?.create(i)).catch(e=>o.emit(`error`,{error:e,context:`mathChannels.create`})),i},update(e,n){u();let r=f().mathChannels.find(t=>t.id===e);if(!r)throw new HE(`not_found`,{channelId:e});a.set(t=>({...t,mathChannels:t.mathChannels.map(t=>t.id===e?{...t,...n,updatedAt:Date.now()}:t)})),r.source!==`workbook`&&Promise.resolve(t.mathChannels?.update(e,n)).catch(e=>o.emit(`error`,{error:e,context:`mathChannels.update`}))},remove(e){u();let n=f().mathChannels.find(t=>t.id===e);if(!n)throw new HE(`not_found`,{channelId:e});a.set(t=>({...t,mathChannels:t.mathChannels.filter(t=>t.id!==e)})),n.source!==`workbook`&&Promise.resolve(t.mathChannels?.remove(e)).catch(e=>o.emit(`error`,{error:e,context:`mathChannels.remove`}))},async importFile(e){u();let{channels:n,errors:r}=await IE(e),i=f(),o=i.limits.maxMathChannels===null?n.length:Math.max(0,i.limits.maxMathChannels-i.mathChannels.length);n.length>0&&o===0&&d(`math-channels`);let s=n.slice(0,o);return a.set(e=>({...e,mathChannels:[...e.mathChannels,...s]})),await t.mathChannels?.importMany(s),{channels:s,errors:r}},async importMany(e){u();let n=f(),r=n.limits.maxMathChannels===null?e.length:Math.max(0,n.limits.maxMathChannels-n.mathChannels.length);e.length>0&&r===0&&d(`math-channels`);let i=e.slice(0,r);return a.set(e=>({...e,mathChannels:[...e.mathChannels,...i]})),await t.mathChannels?.importMany(i),i},exportBlob:()=>PE(f().mathChannels),preview(e,t){let n=h();return n.merged?mE(e,n.merged,P(t).xKey,n.channels.filter(t=>t.id!==e.id)):null},sync(e){u(),a.set(t=>{let n=t.mathChannels.filter(e=>e.source===`workbook`),r=n.length?[...e,...n]:e;return t.mathChannels===r?t:{...t,mathChannels:r}})}},be=v$((e,t)=>[...e.flatMap(e=>e.kind===`camera`&&e.video?[BE({...e,video:e.video})]:[]),...t]),xe=``;a.subscribe(()=>{let e=be(f().live,f().video),t=e.map(e=>`${e.kind}:${e.id}:${e.recordingId??``}:${e.name}`).join(`|`);t!==xe&&(xe=t,o.emit(`videochange`,{sources:e}))});let Se=(e,t,n)=>e.id===t&&(n===void 0||(e.recordingId??null)===n),Ce={sources:()=>be(f().live,f().video),register(e){u(),a.set(t=>({...t,video:[...t.video.filter(t=>!Se(t,e.id,e.recordingId??null)),e]}))},unregister(e,t){u(),a.set(n=>n.video.some(n=>Se(n,e,t))?{...n,video:n.video.filter(n=>!Se(n,e,t))}:n)}},we={openLocal(e,t){return u(),V.openLocal(e,t)},async connect(e,t,n){u(),await V.connect(e,t,n)},startRecording(e){u(),V.startRecording(e)},stopRecording(e){return u(),V.stopRecording(e)},setSegmentAxis(e,t){u(),V.setSegmentAxis(e,t)},rowCount(e){return V.connections().find(t=>t.id===e)?.source.size()??0},disconnect(e){u(),V.disconnect(e),z(f().selection.filter(t=>t!==e))}},Ee=()=>{f().limits.canImportExportWorkspaces||d(`workspaces-io`)},De=async e=>{if(e instanceof Blob)try{return JSON.parse(await e.text())}catch{throw new HE(`bad_file`)}if(typeof e==`string`)try{return JSON.parse(e)}catch{throw new HE(`bad_file`)}return e},Oe=async e=>e instanceof File?e:new File([JSON.stringify(await De(e))],`import.json`,{type:`application/json`}),ke=e=>e.replace(/[^\w.-]+/g,`_`),Ae=e=>new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),je=e=>{let t=mr(e.panelChartSettings,V1[2],4),n={};for(let r of e.panels)t[r.id]?.kind===r.kind&&(n[r.id]=t[r.id]);return{...e,panelChartSettings:hr(e.panels,n,V1[2],4)}},Me=(e,t)=>e.map(e=>{let n=e=>{let n=t.has(e)?crypto.randomUUID():e;return t.add(n),n},r=new Map(e.panels.map(e=>[e.id,n(e.id)])),i=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[r.get(e)??e,t]));return{...e,id:n(e.id),panels:e.panels.map(e=>({...e,id:r.get(e.id)})),panelChartSettings:i(e.panelChartSettings),panelChartBackgrounds:i(e.panelChartBackgrounds??{})}}),Ne=()=>new Set(f().worksheets.flatMap(e=>[e.id,...e.panels.map(e=>e.id)])),Pe=(e,t=0)=>{let n=f().limits.maxWorksheets,r=Me((n===null?e:e.slice(0,Math.max(1,n))).map(je),new Set),i=r[Math.min(t,r.length-1)];a.set(e=>({...e,worksheets:r,activeWorksheetId:i.id,xRanges:{}}))},Fe=(e,t)=>{let n=P(t),r=f().limits.maxChartsPerWorksheet;r!==null&&n.panels.length>=r&&d(`charts-per-worksheet`);let i=f().limits.maxChannelsPerChart;i!==null&&Nz(e.settings)>i&&d(`channels-per-chart`);let a=crypto.randomUUID(),o={id:a,kind:e.kind,rect:{x:0,y:0,w:6,h:24},...e.title?{title:e.title}:{}};return L(n.id,t=>({...t,panels:un([...t.panels,o]),panelChartSettings:{...t.panelChartSettings,[a]:e.settings},panelChartBackgrounds:e.background===null?t.panelChartBackgrounds:{...t.panelChartBackgrounds,[a]:e.background}})),a},Ie=()=>{let e=f();return hV({worksheets:e.worksheets,activeWorksheetId:e.activeWorksheetId,channels:te(m(e.mathChannels,e.limits.maxMathChannels),e.worksheets),liveWindowSeconds:e.liveWindowSeconds,laps:e.datasets.find(e=>e.beacon)?.beacon??null,cycles:e.cycleRules})},Le=e=>{if(e.worksheets.length===0)throw new HE(`bad_workspace`,{errors:e.errors});let{channels:t,rename:n}=U1(f().mathChannels,e.mathChannels);Pe(n.size?e.worksheets.map(e=>W1(e,n)):e.worksheets,e.activeIndex),a.set(n=>({...n,mathChannels:[...n.mathChannels.filter(e=>e.source!==`workbook`),...t],liveWindowSeconds:e.liveWindowSeconds===void 0?n.liveWindowSeconds:e.liveWindowSeconds,cycleRules:e.cycles}));let r=e.laps;if(r)for(let e of f().datasets)e.kind!==`memory`||e.beacon||!e.data.columnNames.includes(r.channel)||ue.configure(e.id,{beacon:r}).catch(e=>o.emit(`error`,{error:e,context:`io.openWorkbook`}));return{worksheets:e.worksheets.length,errors:e.errors}},Re=e=>{if(e===null)return;let t=h().numericColumns,n=t.length?e.worksheets.map(e=>q1(e,t)):e.worksheets;C=!0;try{a.set(t=>{let r=t=>e.worksheets.some(e=>e.id===t);return{...t,worksheets:n,activeWorksheetId:r(t.activeWorksheetId)?t.activeWorksheetId:r(e.activeWorksheetId)?e.activeWorksheetId:e.worksheets[0].id,xRanges:Object.fromEntries(Object.entries(t.xRanges).filter(([e])=>r(e))),mathChannels:[...t.mathChannels.filter(e=>e.source!==`workbook`),...e.channels],liveWindowSeconds:e.liveWindowSeconds}})}finally{C=!1}D=E(f()),S.rebase(O()),k()},Be={undo(){u(),Re(S.undo())},redo(){u(),Re(S.redo())},clear(){u(),j()}},Ve={hasWork:()=>EV(f().worksheets),exportWorksheet(e){u(),Ee();let t=P(e),n=gV(t);return{json:n,blob:Ae(n),filename:`${ke(t.name||`worksheet`)}.kymosh`}},exportChart(e){u(),Ee();let{ws:t,panel:n}=F(e),r=_V(n,t.panelChartSettings[e],t.panelChartBackgrounds[e]??null);return{json:r,blob:Ae(r),filename:`${ke(n.title?.trim()||n.kind)}.json`}},parseFile:e=>kV(e),exportWorkspace(){u(),Ee();let e=Ie();return{json:e,blob:Ae(e),filename:`kymoscope-workspace-${new Date().toISOString().slice(0,10)}.json`}},async exportWorkspaceEncrypted(e){u(),Ee();let t=typeof e==`string`?await aV(Ie(),e):await oV(Ie(),e);return{json:t,blob:Ae(t),filename:`kymoscope-workbook-${new Date().toISOString().slice(0,10)}.kymo`}},async importWorkspace(e,t={}){u(),Ee();let n=await De(e);return sV(n)&&(n=await uV(n,t)),M(()=>Le(TV(n)))},toWorkbook:Ie,openWorkbook(e){return u(),M(()=>Le(TV(e)))},async importWorksheet(e){u(),Ee();let t=f();t.limits.maxWorksheets!==null&&t.worksheets.length>=t.limits.maxWorksheets&&d(`worksheets`);let n=await kV(await Oe(e));if(n.type!==`worksheet`)throw new HE(`bad_file`,{found:n.type});let[r]=Me([je(n.worksheet)],Ne());return a.set(e=>({...e,worksheets:[...e.worksheets,r],activeWorksheetId:r.id})),r.id},async importChart(e,t){u(),Ee();let n=await kV(await Oe(e));if(n.type!==`chart`)throw new HE(`bad_file`,{found:n.type});return Fe(n.chart,t)},snapshot(){let e=f();return{datasets:e.datasets,worksheets:e.worksheets,activeWorksheetId:e.activeWorksheetId,selection:e.selection}},restore(e){u();let t=new Set(e.datasets);for(let e of f().datasets)t.has(e)||e.source.dispose().catch(()=>void 0);let n=e.worksheets.length?e.worksheets.map(je):[H1()];M(()=>a.set(t=>({...t,datasets:e.datasets,worksheets:n,activeWorksheetId:n.some(t=>t.id===e.activeWorksheetId)?e.activeWorksheetId:n[0].id,selection:e.selection,xRanges:{},offsets:{},colors:{}})))},reset(){u(),M(()=>{ae(f().datasets.map(e=>e.id));let e=H1();a.set(t=>({...t,worksheets:[e],activeWorksheetId:e.id,xRanges:{},offsets:{},colors:{},mathChannels:t.mathChannels.filter(e=>e.source!==`workbook`)}))})}},He={merged(e){let t=h();if(!t.merged||t.channels.length===0)return t.merged;let n=ME(t.merged,t.channels,P(e).xKey);return{...t.merged,columnNames:[...t.merged.columnNames,...n.ok.map(e=>e.name)],units:[...t.merged.units,...n.ok.map(e=>e.units)],rows:n.rows}},plotted(){return h().merged}},Ue=typeof location<`u`?location.hostname:``,We=t.license,Ge=t.licenseKey,Ke=!1,qe={},Je=e=>{r||a.set(t=>({...t,licensed:e}))},Xe=(e,t,n)=>{clearTimeout(qe[e]);let r=Math.max(0,t-Date.now()),i=r>2**31-1;qe[e]=setTimeout(()=>{i?Xe(e,t,n):n()},i?2**31-1:r)},Qe=e=>Xe(`renew`,e,()=>void et()),$e=e=>Xe(`expiry`,e*1e3+1e3,()=>{HV(Ge,Ue).then(e=>{r||Je(e.ok)})});async function et(){let e=36e5,t,n=null,i;try{t=await Promise.race([We.get(),new Promise((e,t)=>{i=setTimeout(()=>t(Error(`timeout`)),3e4)})]),n=await HV(t,Ue)}catch{}finally{clearTimeout(i)}if(r)return!1;if(n?.ok)return Ge=t,Ke=!0,Je(!0),$e(n.exp),Qe(Math.max(n.exp*1e3-168*e,Date.now()+e)),!0;console.warn(`[kymoscope] license renewal failed (${n?n.reason:`license.get failed or timed out`}): keeping the current key`);let a=await HV(Ge,Ue);return r?!1:(Je(a.ok),Qe(Date.now()+e),a.ok)}let tt=!We||t.licenseKey?HV(t.licenseKey,Ue).then(e=>(e.ok||console.warn(`[kymoscope] license ${e.reason}: showing attribution`),!Ke&&!r&&(Je(e.ok),e.ok&&We&&$e(e.exp)),e.ok)):null,nt=We?et():tt;C=!1,j();let rt={getState:N,subscribe(e){return a.subscribe(e)},on:o.on,licensed:nt,isLicensed:()=>f().licensed,setOptions(e){if(u(),t={...t,...e},e.live&&V.setRelay(e.live.relay),e.palette&&s(),e.limits){let t={...f().limits,...e.limits};a.set(e=>{let n=t.maxWorksheets===null?e.worksheets:e.worksheets.slice(0,Math.max(1,t.maxWorksheets)),r=n.some(t=>t.id===e.activeWorksheetId)?e.activeWorksheetId:n[0].id;return{...e,limits:t,activeWorksheetId:r}})}},datasets:ue,folders:pe,worksheets:me,charts:he,view:_e,mathChannels:ye,cycles:ve,live:we,video:Ce,io:Ve,history:Be,data:He,alerts:{setRules:e=>{u();let t=se.setRules(e);return a.set(e=>({...e,alertRules:se.rules()})),t},rules:se.rules,state:se.state,evaluate:(e,t)=>(u(),se.evaluate(e,t)),clearMarks:se.clearMarks},marks:{list:()=>f().marks},dispose(){if(!r){r=!0,clearTimeout(qe.renew),clearTimeout(qe.expiry),c(),a$(rt),IQ(rt),V.dispose();for(let e of f().datasets)e.source.dispose().catch(()=>void 0);o.emit(`dispose`,void 0),o.clear()}}};return Z1.set(rt,{store:a,derived:h,live:V,alertLines:()=>ce(f().alertRules,f().alerts)}),rt}var Z1=new WeakMap;function Q1(e){let t=Z1.get(e);if(!t)throw new HE(`invalid_argument`,{reason:`not a Kymoscope engine`});return t}var $1=2e3,e0=3;function t0(e){let t=e[0].v.fragCount,n=new Map;for(let r of e)r.v.fragCount===t&&!n.has(r.v.fragIndex)&&n.set(r.v.fragIndex,r);let r=[];for(let e=0;e<t;e++){let t=n.get(e);if(!t)return null;r.push(t.v.payload)}let i=n.get(0),a=r[0];if(t>1){a=new Uint8Array(r.reduce((e,t)=>e+t.length,0));for(let e=0,n=0;e<t;e++)a.set(r[e],n),n+=r[e].length}return{t:i.v.t,seq:i.v.seq,key:i.v.key,data:a,arrivedAt:i.at}}function n0(e){let t=[],n=0;for(;n<e.length&&e[n].v.fragIndex>0&&e[n].v.seq===e[0].v.seq;)t.push(e[n++]);let r=[],i=[],a=[];for(;n<=e.length;n++){let t=e[n];if(a.length&&(!t||t.v.seq!==a[0].v.seq)){let e=t0(a);e?r.push(e):t||(i=a),a=[]}t&&a.push(t)}return{head:t,units:r,tail:i}}var r0=class{kind=`recorded`;id;name;parentId;parentName;recordingId;chunks;fetch;open;maxBytes;cache=new Map;sizes=new Map;bytes=0;width=0;height=0;codec=``;waiting=null;checks=new Map;constructor(e){this.id=e.id,this.name=e.name,this.parentId=e.parentId,this.parentName=e.parentName??null,this.recordingId=e.recordingId,this.chunks=[...e.chunks].sort((e,t)=>e.seq-t.seq),this.fetch=e.fetchChunk,this.open=e.open,this.maxBytes=e.maxBytes??256*1024*1024}async parse(e){let t=this.chunks[e].seq,n=new Uint8Array(await this.fetch(t)),r=[],{header:i,messages:a}=le(n);if(!this.checks.has(e)){let n=i.seq===t?e===0?0:this.chunks[e-1].seq+1:-1;this.checks.set(e,{rid:i.recordingId,check:await U(i,a,e=>c(this.open,e.slice().buffer),n).catch(()=>`broken`)})}for(let e of a){let t=null;try{t=await c(this.open,e.bytes.slice().buffer)}catch{}if(t?.kind!==6)continue;let n=V$(t.plaintext);n&&(n.key&&n.fragIndex===0&&!this.codec&&(this.codec=n.codec,this.width=n.width,this.height=n.height),r.push({v:n,at:e.at}))}let o=n0(r),s=e=>e.reduce((e,t)=>e+t.v.payload.length,0);return{...o,bytes:o.units.reduce((e,t)=>e+t.data.length,0)+s(o.head)+s(o.tail)}}parsed(e){let t=this.cache.get(e);if(t)return this.cache.delete(e),this.cache.set(e,t),t;let n=this.parse(e);return this.cache.set(e,n),n.then(t=>{this.cache.get(e)===n&&(this.sizes.set(e,[t.bytes,t.units.length]),this.bytes+=t.bytes,this.evict(e))},()=>{this.cache.get(e)===n&&this.cache.delete(e)}),n}evict(e){for(let t of this.cache.keys()){if(this.bytes<=this.maxBytes)return;let n=this.sizes.get(t);t===e||!n||(this.bytes-=n[0],this.sizes.delete(t),this.cache.delete(t))}}async units(e){let t;try{t=await this.parsed(e)}catch{return[]}if(t.full)return t.full;if(!t.tail.length||e+1>=this.chunks.length)return t.full=t.units;let n=await this.parsed(e+1).catch(()=>null);if(!n)return t.units;let r=null;try{r=t0([...t.tail,...n.head.filter(e=>e.v.seq===t.tail[0].v.seq)])}catch{}return t.full=r?[...t.units,r]:t.units}async seekPlan(e){let t=this.chunks.length;if(!t)return[];let n=e*1e3,r=0;for(;r+1<t&&this.chunks[r+1].t0<=n;)r++;let i=r,a=r+1<t&&this.chunks[r+1].t0-n<$1?r+1:r,o=(await Promise.all(Array.from({length:a-i+1},(e,t)=>this.units(i+t)))).flat(),s=()=>{let t=o.length-1;for(;t>=0&&o[t].t>e;)t--;let n=t;for(;n>=0&&!o[n].key;)n--;return[n,t]},[c,l]=s();for(let e=0;c<0&&i>0&&e<e0;e++)o=[...await this.units(--i),...o],[c,l]=s();return a+1<t&&this.units(a+1),c<0?[]:o.slice(c,l+1)}ready(){return this.waiting??=(async()=>{for(let e=0;e<Math.min(this.chunks.length,e0+1)&&!this.codec;e++)await this.units(e);this.codec||(this.waiting=null)})()}info(){let e=0;for(let[,t]of this.sizes.values())e+=t;return{width:this.width,height:this.height,codec:this.codec,latestT:this.range()?.[1]??null,lagMs:null,units:e,bytes:this.bytes}}integrity(){let e=new Map;for(let t of this.checks.values())e.set(t.rid,(e.get(t.rid)??0)+1);let t=[...e].sort((e,t)=>t[1]-e[1])[0]?.[0],n=we([...this.checks.values()].map(e=>e.rid===t?e:{rid:t,check:`broken`}));return n.verified||n.broken?n:null}range(){let e=this.chunks.length;return e?[this.chunks[0].t0/1e3,this.chunks[e-1].t1/1e3]:null}},i0=[60,300,900,1800,3600,7200,14400,28800,43200,86400],a0={60:`1m`,300:`5m`,900:`15m`,1800:`30m`,3600:`1h`,7200:`2h`,14400:`4h`,28800:`8h`,43200:`12h`,86400:`24h`};function o0(e){if(typeof e==`number`)return i0.includes(e)?e:null;if(typeof e!=`string`)return null;let t=Object.entries(a0).find(([,t])=>t===e.trim().toLowerCase());return t?Number(t[0]):null}var s0=e=>a0[e]??`${e}s`;function c0(e){for(let t=i0.length-1;t>=0;t--)if(i0[t]*e<=157286400)return i0[t];return i0[0]}function l0(e,t,n){let r=t*1e3,i=n*1e3;return Math.floor((e+i)/r)*r+r-i}var u0=1e4,d0=1e3,f0=72e4,p0=3e5,m0=3e4,h0=1e4,g0=1e4,_0=64*1024,v0=50,y0=[`360p`,`480p`,`720p`,`1080p`],b0=e=>e+6+(e>=126?2:0)+(e>65535?6:0);function x0(e,t){return t*b0(e+30)}var S0=e=>typeof e==`number`&&Number.isFinite(e)&&e>0,C0=e=>Number.isInteger(e)&&e>=1;function w0(e,t){if(!e||e.mode!==`live`&&e.mode!==`record`)return null;if(t===`camera`)return y0.includes(e.quality)&&Number.isInteger(e.fps)&&e.fps>=1&&e.fps<=60?{mode:e.mode,quality:e.quality,fps:e.fps}:null;if(!S0(e.bytes_per_sec))return null;let n=e.bytes_per_sec,r={};if(e.mode===`record`){let t=e.splitEvery===void 0?c0(n):o0(e.splitEvery);if(t===null)return null;r={split_every:t}}return e.sources===void 0?S0(e.hz)&&C0(e.channels)?{mode:e.mode,hz:e.hz,channels:e.channels,bytes_per_sec:n,...r}:null:Array.isArray(e.sources)&&e.sources.length>0&&e.sources.every(e=>S0(e?.hz)&&C0(e?.channels))?{mode:e.mode,sources:e.sources.map(({hz:e,channels:t})=>Object.freeze({hz:e,channels:t})),bytes_per_sec:n,...r}:null}var T0=class extends Error{status;code;detail;constructor(e,t,n){super(`${n} (${t})`),this.status=e,this.code=t,this.detail=n}};async function E0(e,t,n,r,i){let a;try{a=await e(`${t.replace(/\/+$/,``)}/functions/v1/${n}`,{method:`POST`,headers:r,body:i===void 0?void 0:JSON.stringify(i)})}catch(e){throw new T0(0,`network`,e?.message??String(e))}let o=await a.text(),s=null;try{s=JSON.parse(o)}catch{}if(a.status!==200)throw new T0(a.status,s?.error??`error`,s?.message??s?.error??o);return s}async function D0(e,t,n=fetch){let{auth:r}=ct(t),{token:i}=await E0(n,e,`stream-token`,{"x-api-key":r}),a=await E0(n,e,`stream-publisher`,{Authorization:`Bearer ${i}`,"Content-Type":`application/json`},{action:`usage`});return{limits:a.limits??{},usage:a.usage}}var O0=e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0)),k0=class{opts;deps;auth;secret;password;token=``;ticket=``;relayUrl=null;apiKeyId=null;projectId=null;e2ee=!1;sid=null;chain=null;held=null;salt=``;key=null;raw=null;gen=0;epoch=0;haveKey=!1;sealed=null;device=null;senderDeviceId=null;deviceRetried=!1;maxBytesPerSec=0;maxMessageBytes=_0;ws=null;open=!1;everOpen=!1;connectedAt=0;authAt=0;delay=1e3;lastToken=0;viewerCount=0;busy=!1;stopped=!1;refusal=null;heartbeatTimer=null;pingTimer=null;retryTimer=null;statusFns=new Set;viewerFns=new Set;lastStatus=``;wire;usage=null;bitrate=null;noticeCode=null;constructor(e,t){let{auth:n,secret:r}=ct(e.apiKey);if(!r)throw Error(`This API key has no encryption secret (created before keys carried one). Create a new API key in Kymoscope.`);if(e.kind===`camera`&&!e.parentStreamId)throw Error(`A camera is added to one of your live streams: choose its stream (parentStreamId).`);if(!!e.layer!=!!e.lowOf)throw Error(`A low layer needs both layer: 'low' and lowOf (its high camera's stream id).`);if(e.layer&&e.kind!==`camera`)throw Error(`Only a camera has a low layer.`);let i=w0(e.profile,e.kind);if(!i)throw Error(`profile is required: mode plus hz/channels (or sources) and bytes_per_sec, or quality/fps for a camera`);if(this.wire=Object.freeze(e.kind===`data`?{...i,sender:`browser`}:i),e.visibility===`open`&&e.password)throw Error(`An open stream has no password: anyone may watch it. Remove the password, or use visibility 'private'.`);if(e.password&&e.visibility!==`open`&&e.password.length<12&&!e.allowShortPassword)throw Error(`The stream password has ${e.password.length} characters: anyone signed in can see a general stream and try to guess a short password. Use 12 or more, or set allowShortPassword: true to accept that risk.`);this.opts=e,this.deps=t,this.auth=n,this.secret=r,this.password=e.visibility===`open`?L:e.password||r}get streamId(){return this.sid}get viewers(){return this.viewerCount}get limits(){return{maxBytesPerSec:this.maxBytesPerSec,maxMessageBytes:this.maxMessageBytes}}get usageMessage(){return this.usage}get bitrateKbps(){return this.bitrate}get profile(){return this.wire}onStatus(e){return this.statusFns.add(e),()=>{this.statusFns.delete(e)}}onViewers(e){return this.viewerFns.add(e),()=>{this.viewerFns.delete(e)}}async start(){this.emit();try{let t=await this.deps.store.load();this.salt=t?.salt??e();let n=await this.mint();this.token=n.token,this.relayUrl=n.relayUrl??null,this.maxBytesPerSec=n.maxBytesPerSec||0,this.maxMessageBytes=n.maxMessageBytes||_0,this.apiKeyId=n.apiKeyId??null;let r=n.project;this.e2ee=!!r?.e2ee;let i={};if(this.e2ee){this.projectId=r?.id??null;let e=t?.apiKeyId===this.apiKeyId;this.device=e&&t?.device||await H(),e&&t?.streamKey?{key:this.key,epoch:this.epoch,sealed:this.sealed}=t.streamKey:this.key=await Qe(Me()),i.sender_device=await this.senderDevice()}else this.raw=O0(await v(this.password,this.salt)),this.key=await Qe(this.raw),this.gen=t?.keyGen??0;let a=await this.register(t?.streamId??null,i);if(this.sid=a.stream.id,this.ticket=a.ticket,this.admitted(a),this.e2ee?(this.senderDeviceId=a.sender_device_id??null,this.projectId=a.project?.id??this.projectId,await this.save(),await this.applyProject(a.project)):(await this.save(),await this.wrapFor(a.devices)),!this.relayUrl)throw Error(`stream-token returned no relayUrl`)}catch(e){throw e instanceof T0&&e.status>=400&&e.status<500&&this.refuse(e),e}this.stopped||(this.lastToken=this.deps.now(),this.connect(),this.heartbeatTimer=setInterval(()=>{this.housekeeping()},u0),this.emit())}async send(e,t){if(this.stopped||!this.open)return!1;let n=await this.seal(e,t);return!!n&&this.sendSealed(n)}async seal(e,t){let n=this.key,r=this.e2ee?this.epoch&255:this.gen||void 0;return!n||this.e2ee&&!this.haveKey?null:new Uint8Array(await T(n,e,t,r))}sendSealed(e){let t=this.ws;if(!this.open||!t)return!1;if(this.held)return this.held.push(e),!0;try{t.send(e)}catch{return!1}return this.chained(e),!0}chained(e){let t=this.sid;if(!t)return;let n=this.deps.now();this.chain?.sid!==t&&(this.chain={sid:t,lane:new Se(t,se(),0),at:n});let r=this.chain;r.lane.add(e),!(n-r.at<d0)&&(r.at=n,this.held=[],r.lane.checkpoint().then(e=>this.seal(8,e)).catch(()=>null).then(e=>{let t=this.ws,n=this.held??[];if(this.held=null,!(!t||!this.open))try{e&&t.send(e);for(let e of n)t.send(e),this.chained(e)}catch{}}))}recordingUpload(e){return this.post(`recording-upload`,{Authorization:`Bearer ${this.token}`,"Content-Type":`application/json`},e)}stop(){!this.stopped&&this.sid&&this.call({action:`offline`,stream_id:this.sid}).catch(()=>{}),this.stopped=!0,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.retryTimer&&clearTimeout(this.retryTimer),this.heartbeatTimer=this.retryTimer=null;let e=this.ws;if(this.disconnect(),e){e.onopen=e.onmessage=e.onclose=null;try{e.close(1e3)}catch{}}}post(e,t,n){return E0(this.deps.fetch,this.opts.supabaseUrl,e,t,n)}mint(){return this.post(`stream-token`,{"x-api-key":this.auth})}call(e){return this.post(`stream-publisher`,{Authorization:`Bearer ${this.token}`,"Content-Type":`application/json`},e)}async register(e,t,n=this.salt,r=this.key){let i={action:`register`,name:this.opts.name,salt:n,key_check:await Le(r),visibility:this.opts.visibility??`private`,kind:this.opts.kind,profile:this.wire,...t};return this.opts.kind===`camera`&&(i.parent_stream_id=this.opts.parentStreamId),this.opts.layer&&(i.layer=this.opts.layer,i.low_of=this.opts.lowOf),e&&(i.stream_id=e),this.call(i)}admitted(e){this.usage=typeof e.usage?.message==`string`?e.usage.message:null,this.bitrate=typeof e.bitrate_kbps==`number`?e.bitrate_kbps:null}notice(e){let t=e?.notice,n=typeof t?.code==`string`?t.code:null;if(n&&n!==this.noticeCode)try{this.opts.onNotice?.({code:n,message:String(t.message??n)})}catch{}this.noticeCode=n}async senderDevice(){let e=this.device.publicKey;return{public_key:e,binding:await nt(await ie(this.secret),this.apiKeyId??``,e)}}async housekeeping(){if(!(this.busy||this.stopped)){this.busy=!0;try{let e=this.deps.now();if(e-this.lastToken>=f0){this.lastToken=e;try{this.token=(await this.mint()).token}catch{return}}if(this.e2ee){let e=await this.call({action:`heartbeat`,stream_id:this.sid,sender_device_id:this.senderDeviceId,epoch:this.haveKey?this.epoch:0});this.setTicket(e.ticket),this.notice(e),await this.applyProject(e.project)}else{let e=await this.call({action:`heartbeat`,stream_id:this.sid});this.setTicket(e.ticket),this.notice(e),await this.wrapFor(e.devices),e.rekey===!0&&await this.rekey()}}catch(e){e instanceof T0&&(e.status===401||e.status===403)&&this.refuse(e)}finally{this.busy=!1}}}async rekey(){let t=e(),n=O0(await v(this.password,t)),r=await Qe(n),i;try{i=await this.register(this.sid,{},t,r)}catch{return}this.salt=t,this.key=r,this.raw=n,this.gen=this.gen%255+1,await this.save(),await this.wrapFor(i.devices)}async wrapFor(e){let t=[];for(let n of e??[])try{t.push({device_id:n.id,wrapped:await l(n.public_key,this.raw,`${this.sid}|${n.id}`)})}catch{}if(t.length)try{await this.call({action:`wrap_keys`,stream_id:this.sid,keys:t.slice(0,v0)})}catch{}}async applyProject(e){if(!this.e2ee||!e)return;let t=e.key;if(!t){this.emit();return}let n=Number(t.epoch);if(this.haveKey&&n<=this.epoch)return;let r;try{r=await ot(this.device.privateKey,t.wrapped,de(this.projectId,n,this.senderDeviceId))}catch{if(this.deviceRetried)return;this.deviceRetried=!0,this.device=await H(),await this.reregister();return}let i=ce(this.sid,this.projectId,n),a=this.key,o=n===this.epoch?this.sealed:null;if(o)try{await qe(r,o,i)}catch{o=null}if(!o){let e=Me();a=await Qe(e),o=await Pe(r,e,i),e.fill(0)}try{await this.call({action:`wrap_keys`,stream_id:this.sid,sender_device_id:this.senderDeviceId,project_wrap:{epoch:n,iv:o.iv,ct:o.ct}})}catch{return}this.stopped||(this.key=a,this.sealed=o,this.epoch=n,this.haveKey=!0,await this.save(),this.emit())}async reregister(){let e;try{e=await this.register(this.sid,{sender_device:await this.senderDevice()})}catch{return}this.ticket=e.ticket,this.admitted(e),this.senderDeviceId=e.sender_device_id??null;let t=e.stream.id;if(t!==this.sid){this.sid=t;let e=this.ws;if(e){this.disconnect(),e.onopen=e.onmessage=e.onclose=null;try{e.close(1e3)}catch{}this.connect()}}await this.save(),await this.applyProject(e.project),this.deviceRetried=!1}async save(){try{await this.deps.store.save({apiKeyId:this.apiKeyId,streamId:this.sid,salt:this.salt,device:this.e2ee?this.device:null,streamKey:this.e2ee&&this.haveKey?{epoch:this.epoch,key:this.key,sealed:this.sealed}:null,...this.gen?{keyGen:this.gen}:{}})}catch{}}connect(){if(this.retryTimer=null,this.stopped)return;let e=this.relayUrl.replace(/\/+$/,``).replace(/^http(s?):\/\//,`ws$1://`),t;try{t=new this.deps.WebSocket(`${e}/v1/streams/${this.sid}/publish`,[C$,`bearer.${this.ticket}`])}catch{this.dropped();return}t.binaryType=`arraybuffer`,this.ws=t,t.onopen=()=>{t===this.ws&&(this.open=this.everOpen=!0,this.connectedAt=this.authAt=this.deps.now(),this.pingTimer=setInterval(()=>{try{t.send(`ping`)}catch{}},m0),this.emit())},t.onmessage=e=>{if(!(t!==this.ws||typeof e.data!=`string`||!e.data.startsWith(`{`)))try{let t=JSON.parse(e.data);t?.type===`viewers`&&this.setViewers(Number(t.count)||0)}catch{}},t.onclose=()=>{t===this.ws&&this.dropped()}}disconnect(){this.ws=null,this.open=!1,this.pingTimer&&clearInterval(this.pingTimer),this.pingTimer=null,this.setViewers(0)}dropped(){let e=this.open&&this.deps.now()-this.connectedAt>=g0;if(this.disconnect(),this.stopped)return;let t=0;e?this.delay=1e3:(t=this.delay,this.delay=Math.min(this.delay*2,h0)),this.retryTimer=setTimeout(()=>this.connect(),t),this.emit()}setTicket(e){this.ticket=e;let t=this.deps.now();if(!(!this.open||!this.ws||t-this.authAt<p0))try{this.ws.send(JSON.stringify({type:`auth`,token:e})),this.authAt=t}catch{}}setViewers(e){if(e!==this.viewerCount){this.viewerCount=e;for(let t of this.viewerFns)t(e);this.emit()}}refuse(e){this.refusal={code:e.code,message:e.detail},this.emit(),this.stop()}status(){return this.refusal?{phase:`refused`,...this.refusal}:this.sid?this.e2ee&&!this.haveKey?{phase:`waiting_approval`}:this.open?{phase:`live`,viewers:this.viewerCount}:this.everOpen?{phase:`reconnecting`}:{phase:`registering`}:{phase:`registering`}}emit(){let e=this.status(),t=JSON.stringify(e);if(t!==this.lastStatus){this.lastStatus=t;for(let t of this.statusFns)t(e)}}},A0={"360p":{width:640,height:360},"480p":{width:854,height:480},"720p":{width:1280,height:720},"1080p":{width:1920,height:1080}},j0={width:640,height:360,fps:15,kbps:400},M0=[`avc1.640028`,`avc1.4d0028`,`avc1.42e028`],N0=[`avc1.64001f`,`avc1.4d001f`,`avc1.42e01f`],P0=2,F0=1e3,I0=1e3;async function*L0(e){if(typeof MediaStreamTrackProcessor<`u`){let t=new MediaStreamTrackProcessor({track:e}).readable.getReader();try{for(;;){let{value:e,done:n}=await t.read();if(n)return;yield e}}finally{t.cancel().catch(()=>{})}}let t=document.createElement(`video`);t.muted=!0,t.playsInline=!0,t.srcObject=new MediaStream([e]),await t.play();try{for(;e.readyState===`live`;)await new Promise(e=>t.requestVideoFrameCallback(()=>e())),yield new VideoFrame(t,{timestamp:Math.round(performance.now()*1e3)})}finally{t.pause(),t.srcObject=null}}function R0(){let e=null;return(t,n,r)=>(e??=new OffscreenCanvas(n,r).getContext(`2d`),e.drawImage(t,0,0,n,r),new VideoFrame(e.canvas,{timestamp:t.timestamp}))}var z0=class{encoder=null;codec=``;error=null;unsubscribe=null;lastKey=-1/0;keyPending=!1;resume=!0;lastViewers=0;encoding=!1;dropped=0;seq=0;times=new Map;window=[];sending=Promise.resolve();publisher;preset;keyframeMs;Encoder;now;recorder;constructor(e,t,n,r,i,a=null){if(a&&!(e.seal&&e.sendSealed))throw Error(`A recording camera needs a LivePublisher (seal, sendSealed).`);this.recorder=a,this.publisher=e,this.preset=t,this.keyframeMs=n,this.Encoder=r,this.now=i}async configure(e){let{width:t,height:n,fps:r}=this.preset,i=e*1e3,a=null;for(let e of n>720?M0:N0){let o={codec:e,width:t,height:n,bitrate:i,framerate:r,avc:{format:`annexb`},latencyMode:`realtime`,bitrateMode:`constant`};if((await this.Encoder.isConfigSupported(o)).supported===!0){a=o;break}}return a?(this.codec=a.codec,this.encoder=new this.Encoder({output:e=>this.onChunk(e),error:e=>{this.error=e.message||String(e),this.closeEncoder()}}),this.encoder.configure(a),this.lastViewers=this.publisher.viewers,this.unsubscribe=this.publisher.onViewers(e=>{e>this.lastViewers&&(this.keyPending=!0),this.lastViewers=e}),!0):!1}ready(){let e=this.encoder;return this.encoding=!!e&&!this.error&&(this.publisher.viewers>0||!!this.recorder?.wants()),!e||!this.encoding?(this.resume=!0,!1):e.encodeQueueSize>P0?(this.dropped++,!1):!0}encode(e){let t=this.now(),n=t-this.lastKey,r=this.resume||n>=this.keyframeMs||this.keyPending&&n>=F0;r&&(this.lastKey=t,this.keyPending=this.resume=!1);let i=(performance.timeOrigin+e.timestamp/1e3)/1e3;Math.abs(i-Date.now()/1e3)>60&&(i=Date.now()/1e3),this.times.set(e.timestamp,i),this.encoder.encode(e,{keyFrame:r})}onChunk(e){let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=this.times.get(e.timestamp)??Date.now()/1e3;this.times.delete(e.timestamp);let{width:r,height:i}=this.preset,a=e.type===`key`,o=H$({key:a,t:n,seq:this.seq++,width:r,height:i,codec:this.codec,data:t}),s=this.recorder,c=this.publisher;o.forEach((e,t)=>{this.sending=this.sending.then(async()=>{if(!s)return c.send(6,e);let r=await c.seal(6,e);return r?(s.add(r,n*1e3,a&&t===0),c.viewers>0&&c.sendSealed(r)):!1}).catch(()=>!1)}),this.window.push({at:this.now(),bytes:t.length})}get queue(){return this.encoder?.state===`configured`?this.encoder.encodeQueueSize:0}stats(){let e=this.now();for(;this.window.length&&e-this.window[0].at>=I0;)this.window.shift();let t=this.window.reduce((e,t)=>e+t.bytes,0);return{fps:this.window.length,kbps:t*8/1e3,viewers:this.publisher.viewers,encoding:this.encoding}}stop(){this.encoding=!1,this.closeEncoder(),this.unsubscribe?.(),this.unsubscribe=null}closeEncoder(){this.encoder&&this.encoder.state!==`closed`&&this.encoder.close()}},B0=class{high;lowOpt;low=null;lowAt=-1/0;keyframeMs;Encoder;now;frames;scale;stopped=!1;statsFns=new Set;lastStats=-1/0;constructor(e,t={},n={}){let{quality:r,fps:i}=e.profile,a=r?A0[r]:void 0;if(!a||!i)throw Error(`A CameraSender needs a camera publisher (profile quality and fps).`);this.keyframeMs=(t.keyframeS??2)*1e3,this.Encoder=n.VideoEncoder??VideoEncoder,this.now=n.now??Date.now,this.frames=n.frames??L0,this.scale=n.scale??R0(),this.high=new z0(e,{...a,fps:i},this.keyframeMs,this.Encoder,this.now,t.recorder??null),this.lowOpt=t.low?{publisher:t.low.publisher,preset:t.low.preset??j0}:null}async start(e){let t=this.high.publisher.bitrateKbps;if(t==null)throw Error(`The camera has no bitrate: start its LivePublisher first (register answers it).`);if(!await this.high.configure(t))throw new HE(`camera_codec_unsupported`);if(this.lowOpt){let e=new z0(this.lowOpt.publisher,this.lowOpt.preset,this.keyframeMs,this.Encoder,this.now);await e.configure(this.lowOpt.publisher.bitrateKbps??this.lowOpt.preset.kbps)&&(this.low=e)}this.loop(e)}async loop(e){for await(let t of this.frames(e)){if(this.stopped){t.close();break}try{this.onFrame(t)}finally{t.close()}this.emitStats()}}onFrame(e){this.high.ready()&&this.high.encode(e);let t=this.low;if(!t)return;let n=this.now();if(n-this.lowAt<750/t.preset.fps||!t.ready())return;this.lowAt=n;let r=this.scale(e,t.preset.width,t.preset.height);try{t.encode(r)}finally{r.close()}}stats(){return{...this.high.stats(),dropped:this.high.dropped,queue:this.high.queue,error:this.high.error,low:this.low?this.low.stats():null}}onStats(e){return this.statsFns.add(e),()=>{this.statsFns.delete(e)}}emitStats(){let e=this.now();if(e-this.lastStats<I0||!this.statsFns.size)return;this.lastStats=e;let t=this.stats();for(let e of this.statsFns)e(t)}stop(){this.stopped=!0,this.high.stop(),this.low?.stop()}},V0=new TextEncoder,H0={appstream2:`appstream`,cloudhsmv2:`cloudhsm`,email:`ses`,marketplace:`aws-marketplace`,mobile:`AWSMobileHubService`,pinpoint:`mobiletargeting`,queue:`sqs`,"git-codecommit":`codecommit`,"mturk-requester-sandbox":`mturk-requester`,"personalize-runtime":`personalize`},U0=new Set([`authorization`,`content-type`,`content-length`,`user-agent`,`presigned-expires`,`expect`,`x-amzn-trace-id`,`range`,`connection`]),W0=class{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:n,service:r,region:i,cache:a,retries:o,initRetryMs:s}){if(e==null)throw TypeError(`accessKeyId is a required option`);if(t==null)throw TypeError(`secretAccessKey is a required option`);this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=n,this.service=r,this.region=i,this.cache=a||new Map,this.retries=o??10,this.initRetryMs=s||50}async sign(e,t){if(e instanceof Request){let{method:n,url:r,headers:i,body:a}=e;t=Object.assign({method:n,url:r,headers:i},t),t.body==null&&i.has(`Content-Type`)&&(t.body=a!=null&&i.has(`X-Amz-Content-Sha256`)?a:await e.clone().arrayBuffer()),e=r}let n=new G0(Object.assign({url:e.toString()},t,this,t&&t.aws)),r=Object.assign({},t,await n.sign());delete r.aws;try{return new Request(r.url.toString(),r)}catch(e){if(e instanceof TypeError)return new Request(r.url.toString(),Object.assign({duplex:`half`},r));throw e}}async fetch(e,t){for(let n=0;n<=this.retries;n++){let r=fetch(await this.sign(e,t));if(n===this.retries)return r;let i=await r;if(i.status<500&&i.status!==429)return i;await new Promise(e=>setTimeout(e,Math.random()*this.initRetryMs*2**n))}throw Error(`An unknown error occurred, ensure retries is not negative`)}},G0=class{constructor({method:e,url:t,headers:n,body:r,accessKeyId:i,secretAccessKey:a,sessionToken:o,service:s,region:c,cache:l,datetime:u,signQuery:d,appendSessionToken:f,allHeaders:p,singleEncode:m}){if(t==null)throw TypeError(`url is a required option`);if(i==null)throw TypeError(`accessKeyId is a required option`);if(a==null)throw TypeError(`secretAccessKey is a required option`);this.method=e||(r?`POST`:`GET`),this.url=new URL(t),this.headers=new Headers(n||{}),this.body=r,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=o;let h,g;(!s||!c)&&([h,g]=Z0(this.url,this.headers)),this.service=s||h||``,this.region=c||g||`us-east-1`,this.cache=l||new Map,this.datetime=u||new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),this.signQuery=d,this.appendSessionToken=f||this.service===`iotdevicegateway`,this.headers.delete(`Host`),this.service===`s3`&&!this.signQuery&&!this.headers.has(`X-Amz-Content-Sha256`)&&this.headers.set(`X-Amz-Content-Sha256`,`UNSIGNED-PAYLOAD`);let _=this.signQuery?this.url.searchParams:this.headers;if(_.set(`X-Amz-Date`,this.datetime),this.sessionToken&&!this.appendSessionToken&&_.set(`X-Amz-Security-Token`,this.sessionToken),this.signableHeaders=[`host`,...this.headers.keys()].filter(e=>p||!U0.has(e)).sort(),this.signedHeaders=this.signableHeaders.join(`;`),this.canonicalHeaders=this.signableHeaders.map(e=>e+`:`+(e===`host`?this.url.host:(this.headers.get(e)||``).replace(/\s+/g,` `))).join(`
|
|
618
|
+
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,`aws4_request`].join(`/`),this.signQuery&&(this.service===`s3`&&!_.has(`X-Amz-Expires`)&&_.set(`X-Amz-Expires`,`86400`),_.set(`X-Amz-Algorithm`,`AWS4-HMAC-SHA256`),_.set(`X-Amz-Credential`,this.accessKeyId+`/`+this.credentialString),_.set(`X-Amz-SignedHeaders`,this.signedHeaders)),this.service===`s3`)try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g,` `))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,`/`);m||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,`/`)),this.encodedPath=X0(this.encodedPath);let v=new Set;this.encodedSearch=[...this.url.searchParams].filter(([e])=>{if(!e)return!1;if(this.service===`s3`){if(v.has(e))return!1;v.add(e)}return!0}).map(e=>e.map(e=>X0(encodeURIComponent(e)))).sort(([e,t],[n,r])=>e<n?-1:e>n?1:t<r?-1:+(t>r)).map(e=>e.join(`=`)).join(`&`)}async sign(){return this.signQuery?(this.url.searchParams.set(`X-Amz-Signature`,await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set(`X-Amz-Security-Token`,this.sessionToken)):this.headers.set(`Authorization`,await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return[`AWS4-HMAC-SHA256 Credential=`+this.accessKeyId+`/`+this.credentialString,`SignedHeaders=`+this.signedHeaders,`Signature=`+await this.signature()].join(`, `)}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),n=this.cache.get(t);return n||(n=await K0(await K0(await K0(await K0(`AWS4`+this.secretAccessKey,e),this.region),this.service),`aws4_request`),this.cache.set(t,n)),Y0(await K0(n,await this.stringToSign()))}async stringToSign(){return[`AWS4-HMAC-SHA256`,this.datetime,this.credentialString,Y0(await q0(await this.canonicalString()))].join(`
|
|
619
619
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
620
620
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
621
|
-
`)}async hexBodyHash(){let e=this.headers.get(`X-Amz-Content-Sha256`)||(this.service===`s3`&&this.signQuery?`UNSIGNED-PAYLOAD`:null);if(e==null){if(this.body&&typeof this.body!=`string`&&!(`byteLength`in this.body))throw Error(`body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header`);e=J0(await K0(this.body||``))}return e}};async function G0(e,t){let n=await crypto.subtle.importKey(`raw`,typeof e==`string`?B0.encode(e):e,{name:`HMAC`,hash:{name:`SHA-256`}},!1,[`sign`]);return crypto.subtle.sign(`HMAC`,n,B0.encode(t))}async function K0(e){return crypto.subtle.digest(`SHA-256`,typeof e==`string`?B0.encode(e):e)}var q0=[`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`a`,`b`,`c`,`d`,`e`,`f`];function J0(e){let t=new Uint8Array(e),n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=q0[r>>>4&15],n+=q0[r&15]}return n}function Y0(e){return e.replace(/[!'()*]/g,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase())}function X0(e,t){let{hostname:n,pathname:r}=e;if(n.endsWith(`.on.aws`)){let e=n.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return e==null?[``,``]:[`lambda`,e[1]||``]}if(n.endsWith(`.r2.cloudflarestorage.com`))return[`s3`,`auto`];if(n.endsWith(`.backblazeb2.com`)){let e=n.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return e==null?[``,``]:[`s3`,e[1]||``]}let i=n.replace(`dualstack.`,``).match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),a=i&&i[1]||``,o=i&&i[2];if(o===`us-gov`)o=`us-gov-west-1`;else if(o===`s3`||o===`s3-accelerate`)o=`us-east-1`,a=`s3`;else if(a===`iot`)a=n.startsWith(`iot.`)?`execute-api`:n.startsWith(`data.jobs.iot.`)?`iot-jobs-data`:r===`/mqtt`?`iotdevicegateway`:`iotdata`;else if(a===`autoscaling`){let e=(t.get(`X-Amz-Target`)||``).split(`.`)[0];e===`AnyScaleFrontendService`?a=`application-autoscaling`:e===`AnyScaleScalingPlannerFrontendService`&&(a=`autoscaling-plans`)}else o==null&&a.startsWith(`s3-`)?(o=a.slice(3).replace(/^fips-|^external-1/,``),a=`s3`):a.endsWith(`-fips`)?a=a.slice(0,-5):o&&/-\d$/.test(a)&&!/-\d$/.test(o)&&([a,o]=[o,a]);return[V0[a]||a,o||``]}var Z0=1e4,Q0=2e3,$0=1e4,e2=6e4,t2=2e3,n2=6e4,r2=`rec`,i2=`meta.json`,a2=e=>Math.min(n2,Math.max(t2,e*2)),o2=e=>e>=1024?`${+(e/1024).toFixed(2)} GB`:`${e} MB`,s2=e=>e.replace(/(https?:\/\/[^\s?#'"]*)\?[^\s#'"]*/g,`$1`),c2=class extends Error{status;constructor(e,t){super(s2(e)),this.status=t}},l2=e=>e instanceof c2?void 0:e?.status,u2=e=>e?.code??String(l2(e)??`error`),d2=e=>`${String(e).padStart(8,`0`)}.krc`,f2=e=>{let t=Uint8Array.from(e.replace(/-/g,``).match(/../g)??[],e=>parseInt(e,16));if(t.length!==16)throw Error(`bad_recording_id`);return t},p2=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``);async function m2(e,t,n){let r=await(await e.getFileHandle(t,{create:!0})).createWritable();await r.write(n),await r.close()}async function h2(e,t){try{return JSON.parse(await(await(await e.getFileHandle(t)).getFile()).text())}catch{return null}}function g2(e,t){return new Promise(n=>{e.request(t,{ifAvailable:!0},e=>{if(!e){n(null);return}return new Promise(e=>n(e))}).catch(()=>n(null))})}var _2=class{streamId;parentStreamId;bufferMaxMB;dropped=0;usedBytes=0;storage;opts;now;fetch;locks;rootDir=null;parent=void 0;polledAt=-1/0;polling=!1;cutAt=1/0;noneSince=null;file=null;chunk=null;continues=!1;prev=null;lost=new Set;io=Promise.resolve();writing=new Set;held=new Map;opened=new Map;blocked=new Set;wait=new Map;said=new Set;fullSaid=!1;refusedUntil=0;closing=!1;stopped=!1;wake=null;loop=null;constructor(e){this.opts=e,this.streamId=e.streamId,this.parentStreamId=e.parentStreamId,this.bufferMaxMB=e.bufferMaxMB??2048,this.storage=e.storage??null,this.now=e.now??Date.now,this.fetch=e.fetch??((...e)=>fetch(...e)),this.locks=e.locks===void 0?typeof navigator<`u`&&navigator.locks||null:e.locks,e.autostart!==!1&&(this.loop=this.run())}wants(){return!!this.file||!!this.parent}splitEvery=null;get currentId(){return this.file?.id??null}setStorage(e){this.storage=e,this.blocked.clear();for(let e of[...this.said])e.startsWith(`storage:`)&&this.said.delete(e);this.wake?.()}add(e,t,n){if(this.closing)return;this.pollDue()&&this.pollParent();let r=this.parent??null,i=this.file;if(i&&r===null&&this.noneSince!==null&&this.now()-this.noneSince>=3e4?this.endFile(!1,`stopped`):i&&r!==null&&n&&i.meta.parent!==r&&this.endFile(!0,`stopped`),!this.file){if(!r||!n||this.now()<this.refusedUntil)return;this.openFile(t,r)}let a=this.chunk;a&&(a.bytes+12+e.length>4194304||Math.abs(t-a.records[0].at)>=6e4)&&(this.flush(),a=null),a??=this.chunk={records:[],bytes:56,opened:this.now()},a.records.push({at:t,bytes:e}),a.bytes+=12+e.length}tick(){this.chunk&&this.now()-this.chunk.opened>=6e4&&this.flush()}stop(){this.file&&this.endFile(!1,`stopped`),this.continues=!1}async pollParent(){if(!this.polling){this.polling=!0,this.polledAt=this.now();try{let e=await this.opts.call({action:`current`,stream_id:this.parentStreamId}),t=typeof e.recording_id==`string`?e.recording_id:null,n=typeof e.split_every==`number`&&e.split_every>0?e.split_every:null,r=this.now();this.noneSince=t===null?this.noneSince??r:null,t!==null&&(t!==this.parent||n!==this.splitEvery)&&(this.splitEvery=n,this.cutAt=n?c0(r,n,-new Date(r).getTimezoneOffset()*60):1/0),this.parent=t}catch{}finally{this.polling=!1}}}pollDue(){let e=this.now();if(e>=this.cutAt&&this.polledAt<this.cutAt)return!0;let t=e>=this.cutAt&&e<this.cutAt+6e4||!!this.file&&this.parent===null;return e-this.polledAt>=(t?Q0:Z0)}root(){return this.rootDir??=(async()=>(this.opts.root?await this.opts.root():await navigator.storage.getDirectory()).getDirectoryHandle(r2,{create:!0}))().catch(e=>{throw this.rootDir=null,e})}queue(e){this.io=this.io.then(e).catch(e=>{e?.name!==`NotFoundError`&&this.say(`disk`,`disk_error`,`Can't write the recording buffer: ${e?.message??e}`)})}openFile(e,t){let n=crypto.randomUUID(),r={stream_id:this.streamId,kind:`camera`,parent:t,continues:this.continues,prev:this.continues?this.prev:null,t0:e,closed:!1};this.file={id:n,seq:0,meta:r},this.writing.add(n),this.queue(async()=>{if(this.locks){let e=await g2(this.locks,`kymoscope-rec-${n}`);e&&this.held.set(n,e)}await m2(await(await this.root()).getDirectoryHandle(n,{create:!0}),i2,JSON.stringify(r))})}endFile(e,t){let n=this.file;this.flush(),this.file=this.chunk=null,this.continues=e,this.prev=n.id,n.meta={...n.meta,closed:!0,reason:t};let r=JSON.stringify(n.meta);this.queue(async()=>{try{await m2(await(await this.root()).getDirectoryHandle(n.id),i2,r)}finally{this.writing.delete(n.id)}})}flush(){let e=this.chunk,t=this.file;if(this.chunk=null,!e?.records.length||!t)return;let n=t.seq++,r=e.records;this.queue(async()=>{await this.checkpoint(t.id,n,r);let e=Je(t.id,n,r),i=new DataView(e.buffer);i.setFloat64(40,Math.min(...r.map(e=>e.at)),!0),i.setFloat64(48,Math.max(...r.map(e=>e.at)),!0),await m2(await(await this.root()).getDirectoryHandle(t.id),d2(n),e),await this.enforceMax()})}async checkpoint(e,t,n){if(!this.opts.seal)return;let r;try{let i=p2((await crypto.subtle.digest(`SHA-256`,f2(e))).slice(0,8));r=st({streamId:this.streamId,run:i,lane:1,seq:BigInt(t),count:n.length,hash:await be(n.map(e=>crypto.subtle.digest(`SHA-256`,e.bytes)))})}catch{return}let i=await this.opts.seal(8,r).catch(()=>null);i&&n.push({at:n[n.length-1].at,bytes:i})}async enforceMax(){let e=await this.root(),t=0,n=[];for await(let[r,i]of e.entries()){if(i.kind!==`directory`)continue;let e=(await h2(i,i2))?.t0??0;try{for await(let[a,o]of i.entries()){if(o.kind!==`file`)continue;let s=(await o.getFile()).size;t+=s,a.endsWith(`.krc`)&&n.push({t0:e,seq:parseInt(a,10),dir:i,id:r,name:a,size:s})}}catch{}}n.sort((e,t)=>e.t0-t.t0||e.seq-t.seq);let r=this.bufferMaxMB*1024*1024,i=0,a=new Map;for(let e of n){if(t<=r)break;try{await e.dir.removeEntry(e.name)}catch{continue}t-=e.size,i++,a.set(e.id,e.dir)}for(let[e,t]of a){if(e===this.file?.id)continue;let n=!1;try{for await(let[e]of t.entries())n||=e.endsWith(`.krc`)}catch{}n||this.lost.add(e)}this.usedBytes=t,i&&(this.dropped+=i,this.fullSaid||(this.fullSaid=!0,this.status({type:`buffer_full`,message:`Recording buffer full: dropped the oldest ${i} chunks`})))}status(e){try{this.opts.onStatus?.(e)}catch{}}say(e,t,n,r){this.said.has(e)||(this.said.add(e),this.status({type:t,message:n,...r?{reason:r}:{}}))}async claim(e,t){if(this.held.has(t)||this.writing.has(t))return!0;if(this.locks){let e=await g2(this.locks,`kymoscope-rec-${t}`);if(!e)return!1;this.held.set(t,e)}let n=await e.getDirectoryHandle(t).catch(()=>null);return!n||!await h2(n,i2)?(this.release(t),await e.removeEntry(t,{recursive:!0}).catch(()=>{}),!1):(this.locks||this.held.set(t,()=>{}),!0)}release(e){this.held.get(e)?.(),this.held.delete(e)}async files(){let e=await this.root(),t=[];for await(let[n,r]of e.entries())r.kind===`directory`&&t.push(n);let n=[];for(let r of t){if(!await this.claim(e,r))continue;let t=await e.getDirectoryHandle(r).catch(()=>null),i=t&&await h2(t,i2);t&&i?.stream_id&&n.push({id:r,meta:i,dir:t})}return n.sort((e,t)=>e.meta.t0-t.meta.t0||(e.id<t.id?-1:1))}async forget(e,t=!0){this.opened.delete(e),t&&this.lost.add(e),this.file?.id===e&&(this.file=this.chunk=null,this.writing.delete(e),this.continues=!1),this.release(e),await(await this.root()).removeEntry(e,{recursive:!0}).catch(()=>{})}async open(e,t){let n={action:`open`,recording_id:t.id??e,stream_id:t.stream_id,kind:t.kind,continues:!!t.continues&&!this.lost.has(t.prev??``),t0:t.t0,parent_recording_id:t.parent};this.opts.retentionDays!==void 0&&(n.retention_days=this.opts.retentionDays);let r=await this.opts.call(n);if(r.record===!1){let t=String(r.reason??`refused`);return t===`parent_not_found`?(this.wait.set(e,this.now()+$0),null):(this.say(`refused:${t}`,`refused`,String(r.message??`Recording refused (${t})`),t),e===this.file?.id&&(this.refusedUntil=this.now()+e2),await this.forget(e),null)}let i=r.destination??`kymoscope`;if(i!==`kymoscope`&&!this.storage?.[i.kind]){this.blocked.add(e);let t=`storage:${i.id}`;return this.said.has(t)||(this.said.add(t),this.status({type:`storage_needed`,destination:i,message:i.kind===`folder`?`This project records to ${i.name}: choose its folder to store the camera's files`:`This project records to ${i.name}: this sender needs its S3 keys (storage)`})),null}let a=i===`kymoscope`?`Kymoscope`:i.name;if(!this.said.has(`destination:${a}`)){this.said.add(`destination:${a}`);let e=this.splitEvery?`every ${o0(this.splitEvery)}`:`cut with its data stream's`;this.status({type:`destination`,name:a,splitEvery:this.splitEvery,message:`Recording files: ${e} → ${a} (buffer ${o2(this.bufferMaxMB)})`})}return this.opened.set(e,i),i}async put(e,t,n){let r;try{r=await this.fetch(e,t?{method:`PUT`,body:t,headers:n}:void 0)}catch(e){throw new c2(`chunk upload failed: ${e?.message??e}`)}if(!r.ok)throw new c2(`chunk upload failed: HTTP ${r.status}`,r.status)}async writeOwn(e,t,n,r){let{folder:i,s3:a}=this.storage??{};if(i){try{await m2(await(await i.getDirectoryHandle(e.stream_id,{create:!0})).getDirectoryHandle(t,{create:!0}),d2(n),r)}catch(e){throw new c2(`can't write to the folder: ${e?.message??e}`)}return}let o=(a.prefix??``).replace(/^\/+|\/+$/g,``),s=`${o?`${o}/`:``}${e.stream_id}/${t}/${d2(n)}`,c=`${a.endpoint.replace(/\/+$/,``)}/${a.bucket?`${a.bucket}/`:``}${s}`,l=new U0({accessKeyId:a.accessKeyId,secretAccessKey:a.secretAccessKey,service:`s3`,region:a.region||`us-east-1`});await this.put(await l.sign(c,{method:`PUT`,body:r}))}dropChunk(e,t,n){return this.say(`chunk:${n}`,`chunk_dropped`,`A recording chunk was dropped (${n})`),e.removeEntry(t).catch(()=>{})}async uploadChunk(e,t,n,r){let i=t.id??e,a;try{a=new Uint8Array(await(await(await n.getFileHandle(r)).getFile()).arrayBuffer())}catch{return}let o;try{o=Ae(a)}catch{o=null}if(!o||o.bytes!==a.length)return this.dropChunk(n,r,`unreadable on disk`);let s=parseInt(r,10),c=p2(await crypto.subtle.digest(`SHA-256`,a));try{let e=await this.opts.call({action:`chunk`,recording_id:i,seq:s,bytes:a.length,sha256:c});e.own?await this.writeOwn(t,i,s,a):await this.put(String(e.url),a,{Authorization:`Bearer ${e.ticket}`}),await this.opts.call({action:`confirm`,recording_id:i,seq:s,bytes:a.length,messages:o.count,t0:o.t0,t1:o.t1,sha256:c})}catch(e){if(l2(e)===400)return this.dropChunk(n,r,`refused: ${u2(e)}`);if(l2(e)!==409||u2(e)!==`chunk_exists`)throw e}await n.removeEntry(r).catch(()=>{}),this.usedBytes=Math.max(0,this.usedBytes-a.length),this.fullSaid=!1,this.said.delete(`put`)}async reopen(e,t){let n=!1;for await(let[e]of t.entries())n||=e.endsWith(`.krc`);if(!n&&this.file?.id!==e)return!1;this.file?.id===e&&this.endFile(!1,`stopped`),await this.io;let r=await h2(t,i2);return r?(await m2(t,i2,JSON.stringify({...r,id:crypto.randomUUID(),continues:!1,prev:null})),this.opened.delete(e),!0):!1}async uploadPending(){let e=!0;for(let{id:t,meta:n,dir:r}of await this.files()){if(this.blocked.has(t))continue;if(this.now()<(this.wait.get(t)??0)){e=!1;continue}let i=n.closed||!this.writing.has(t);try{if(!(this.opened.get(t)??await this.open(t,n))){!this.blocked.has(t)&&(this.held.has(t)||this.writing.has(t))&&(e=!1);continue}let a=[];for await(let[e,t]of r.entries())t.kind===`file`&&e.endsWith(`.krc`)&&a.push(e);for(let e of a.sort())await this.uploadChunk(t,n,r,e);i?(await this.opts.call({action:`close`,recording_id:n.id??t,reason:n.reason??`stopped`}),await this.forget(t,!1)):e=!1}catch(n){let i=l2(n);if(i===404&&this.opened.has(t)&&await this.reopen(t,r)){e=!1;continue}if(i===403||i===404||i===410||i===400){this.say(`gone:${t}`,`refused`,`A recording file was refused (${u2(n)}): its chunks were dropped`,u2(n)),await this.forget(t);continue}throw n instanceof c2&&n.status!==401&&this.say(`put`,`storage_error`,`Can't store recording chunks (${n.message}); retrying`),n}}return e}async run(){let e=0;for(;!this.stopped;){let t=!1;try{this.tick(),this.pollDue()&&await this.pollParent(),t=await this.uploadPending(),e=0}catch{e=a2(e)}if(this.closing&&(t||e))break;await new Promise(t=>{this.wake=t,setTimeout(t,e||1e3)}),this.wake=null}}async close(e=3e3){this.stop(),this.closing=!0,this.wake?.(),this.loop?await Promise.race([this.loop,new Promise(t=>setTimeout(t,e))]):await this.io,this.stopped=!0,this.wake?.();for(let e of[...this.held.keys()])this.release(e)}},v2=class{#e;constructor(e){this.#e=e}head(){let e=this.#e;return`${e.map(e=>Z$(e.name)).join(`,`)}\n${e.map(e=>Z$(e.unit)).join(`,`)}\n`}append(e){let t=e.columns,n=``;for(let r=0;r<e.length;r++){for(let e=0;e<t.length;e++){let i=t[e][r];n+=(e?`,`:``)+(Number.isNaN(i)?``:String(i))}n+=`
|
|
622
|
-
`}return n}end(){}},y2=new TextEncoder,b2=e=>e+7&-8,x2=104,S2=64,C2=104,w2=160,T2=4;function E2(e,t,n){let r=24+t.length*8+n.length,i=new Uint8Array(b2(r)),a=new DataView(i.buffer);return i.set(y2.encode(e),0),a.setBigUint64(8,BigInt(r),!0),a.setBigUint64(16,BigInt(t.length),!0),t.forEach((e,t)=>a.setBigUint64(24+t*8,BigInt(e),!0)),i.set(n,24+t.length*8),i}var D2=(e,t)=>E2(e,[],y2.encode(`${t}\0`)),O2=e=>BigInt(Math.round(e))*1000000n,k2=class{#e;#t;#n;#r=0;constructor(e,t,n){this.#e=e,this.#t=t?Date.parse(t):Date.now(),this.#n=n}append(e){let t=e.columns,n=t.length,r=new Float64Array(e.length*n);for(let i=0;i<e.length;i++)for(let e=0;e<n;e++)r[i*n+e]=t[e][i];return this.#r+=e.length,new Uint8Array(r.buffer)}end(){if(this.#r!==this.#n)throw Error(`The recording changed while it was exported (${this.#r} of ${this.#n} rows).`)}head(){let e=this.#e.length,t=[],n=64+x2,r=e=>{let r=n;return t.push(e),n+=e.length,r},i=r(D2(`##MD`,`<FHcomment><TX>Kymoscope cloud recording</TX><tool_id>Kymoscope</tool_id><tool_vendor>Kymoscope</tool_vendor><tool_version>1</tool_version></FHcomment>`)),a=new Uint8Array(16);new DataView(a.buffer).setBigUint64(0,O2(this.#t),!0);let o=r(E2(`##FH`,[0,i],a)),s=this.#e.map(e=>r(D2(`##TX`,e.name))),c=this.#e.map(e=>e.unit?r(D2(`##TX`,e.unit)):0),l=n,u=l+S2,d=this.#e.map((e,t)=>u+C2+t*w2),f=E2(`##DG`,[0,u,u+C2+e*w2,0],new Uint8Array(8)),p=new Uint8Array(32),m=new DataView(p.buffer);m.setBigUint64(8,BigInt(this.#n),!0),m.setUint32(24,e*8,!0);let h=E2(`##CG`,[0,d[0],0,0,0,0],p),g=this.#e.map((t,n)=>{let r=new Uint8Array(72),i=new DataView(r.buffer);return i.setUint8(0,n===0?2:0),i.setUint8(1,+(n===0)),i.setUint8(2,T2),i.setUint32(4,n*8,!0),i.setUint32(8,64,!0),i.setUint8(20,255),E2(`##CN`,[n+1<e?d[n+1]:0,0,s[n],0,0,0,c[n],0],r)}),_=new Uint8Array(24);_.set(y2.encode(`##DT`),0),new DataView(_.buffer).setBigUint64(8,BigInt(24+this.#n*e*8),!0);let v=new Uint8Array(64);v.set(y2.encode(`MDF 4.10 Kymoscop`),0),new DataView(v.buffer).setUint16(28,410,!0);let y=new Uint8Array(32);new DataView(y.buffer).setBigUint64(0,O2(this.#t),!0);let b=[v,E2(`##HD`,[l,o,0,0,0,0],y),...t,f,h,...g,_],x=new Uint8Array(b.reduce((e,t)=>e+t.length,0));return b.reduce((e,t)=>(x.set(t,e),e+t.length),0),x}},A2={csv:`text/csv`,mf4:`application/octet-stream`};async function j2(e,t,n,r={}){let i=bz(`krc`,{main:new File(e.chunks,`${e.name}.krc`),companions:[],keys:e.keys},r.signal,r.createWorker);try{let e=await i.plan(),a=[{group:0,channels:e.groups[0].channels.map((e,t)=>t)}],o=t===`csv`?new v2(cz(e,a)):new k2(cz(e,a),e.startTime,e.groups[0].samples);await n(o.head()),await i.read(a,`stream`,{chunk:async e=>{await n(o.append(e))},progress:r.onProgress}),o.end()}finally{i.close()}}async function M2(e,t,n={}){let r=[];return await j2(e,t,e=>{r.push(e)},n),new Blob(r,{type:A2[t]})}var N2=.01,P2=.05,F2=e=>Math.max(5,Math.ceil(e*P2)),I2=e=>Math.max(Math.abs(e.value)*2/100,2*e.spread);function L2(e){let t=new Map(e.goldens.map(e=>[e.streamId,e])),n=[];for(let r of e.cycles){let i=t.get(r.streamId);if(!i||r.value===null||!Number.isFinite(r.value)||r.tend===null||r.flag===`excluded`)continue;let a=e.value.better===`min`?r.value-i.value:i.value-r.value,o=I2(i);n.push({c:r,g:i,gap:a,level:a>o?`off`:a<-o?`better`:`golden`})}return n.sort((e,t)=>e.c.tstart-t.c.tstart)}var R2=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>Number.isFinite(e)));function z2(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}var B2=(e,t)=>V2(e,e=>Math.floor((e.t-t)/86400)),V2=(e,t)=>[...z2(e,t).values()].map(e=>({t:U2(e.map(e=>e.t)),v:U2(e.map(e=>e.v))})),H2=e=>typeof e==`number`&&Number.isFinite(e);function U2(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return e.length?t/e.length:NaN}function W2(e){if(e.length<2)return 0;let t=U2(e),n=0;for(let r=0;r<e.length;r++)n+=(e[r]-t)**2;return Math.sqrt(n/(e.length-1))}function G2(e,t){let n=Array.from(e).filter(Number.isFinite).sort((e,t)=>e-t);if(!n.length)return NaN;let r=(n.length-1)*t,i=Math.floor(r);return i+1<n.length?n[i]+(r-i)*(n[i+1]-n[i]):n[i]}var K2=e=>G2(e,.5);function q2(e){let t=K2(e);return 1.4826*K2(Array.from(e,e=>Math.abs(e-t)))}function J2(e,t){return(e-K2(t))/Math.max(q2(t),1e-12)}function Y2(e){let t=Math.abs(e)/Math.SQRT2,n=1/(1+.3275911*t),r=1-((((1.061405429*n-1.453152027)*n+1.421413741)*n-.284496736)*n+.254829592)*n*Math.exp(-t*t);return e>=0?(1+r)/2:(1-r)/2}var X2=e=>Math.min(1,2*(1-Y2(Math.abs(e))));function Z2(e,t){let n=e.length,r=t.length;if(n<2||r<2)return{u:NaN,p:1,effect:.5};let i=[...e.map(e=>({v:e,g:0})),...t.map(e=>({v:e,g:1}))].sort((e,t)=>e.v-t.v),a=i.length,o=0,s=0;for(let e=0;e<a;){let t=e;for(;t<a&&i[t].v===i[e].v;)t++;let n=(e+1+t)/2;for(let r=e;r<t;r++)i[r].g===0&&(o+=n);s+=(t-e)**3-(t-e),e=t}let c=o-n*(n+1)/2,l=Math.sqrt(n*r/12*(a+1-s/(a*(a-1))));return{u:c,p:l>0?X2((c-n*r/2)/l):1,effect:c/(n*r)}}function Q2(e){if(e<.5)return Math.log(Math.PI/Math.sin(Math.PI*e))-Q2(1-e);let t=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7];--e;let n=t[0],r=e+7.5;for(let r=1;r<9;r++)n+=t[r]/(e+r);return .5*Math.log(2*Math.PI)+(e+.5)*Math.log(r)-r+Math.log(n)}function $2(e,t,n){let r=1e-300,i=e=>Math.abs(e)<r?r:e,a=1,o=1/i(1-(t+n)*e/(t+1)),s=o;for(let r=1;r<=300;r++){let c=2*r,l=r*(n-r)*e/((t-1+c)*(t+c));o=1/i(1+l*o),a=i(1+l/a),s*=o*a,l=-(t+r)*(t+n+r)*e/((t+c)*(t+1+c)),o=1/i(1+l*o),a=i(1+l/a);let u=o*a;if(s*=u,Math.abs(u-1)<1e-14)break}return s}function e4(e,t,n){if(e<=0)return 0;if(e>=1)return 1;let r=Math.exp(Q2(t+n)-Q2(t)-Q2(n)+t*Math.log(e)+n*Math.log(1-e));return e<(t+1)/(t+n+2)?r*$2(e,t,n)/t:1-r*$2(1-e,n,t)/n}function t4(e,t){let n=.5*e4(t/(t+e*e),t/2,.5);return e>0?1-n:n}var n4=(e,t)=>e4(t/(t+e*e),t/2,.5);function r4(e,t){let n=-1e7,r=1e7;for(let i=0;i<120;i++){let i=(n+r)/2;t4(i,t)<e?n=i:r=i}return(n+r)/2}function i4(e,t,n,r){let i=e+n,a=t+r,o=(e,t)=>Q2(e+1)-Q2(t+1)-Q2(e-t+1),s=e=>o(t,e)+o(r,i-e)-o(a,i),c=s(e),l=0;for(let e=Math.max(0,i-r);e<=Math.min(i,t);e++){let t=s(e);t<=c+1e-7&&(l+=Math.exp(t))}return Math.min(1,l)}function a4(e,t,n,r){let i=t?e/t:NaN,a=r?n/r:NaN;if(!t||!r)return{p1:i,p2:a,p:1};let o=t+r,s=e+n;if(Math.min(t,r)*Math.min(s,o-s)/o<5)return{p1:i,p2:a,p:i4(e,t,n,r)};let c=s/o,l=Math.sqrt(c*(1-c)*(1/t+1/r));return{p1:i,p2:a,p:l>0?X2((i-a)/l):1}}function o4(e,t){let n=e.map((e,t)=>t).sort((t,n)=>e[t]-e[n]),r=e.length,i=0;n.forEach((n,a)=>{e[n]<=(a+1)/r*t&&(i=a+1)});let a=e.map(()=>!1);for(let e=0;e<i;e++)a[n[e]]=!0;return a}function s4(e,t){let n=U2(e),r=U2(t),i=0,a=0,o=0;for(let s=0;s<e.length;s++)i+=(e[s]-n)*(t[s]-r),a+=(e[s]-n)**2,o+=(t[s]-r)**2;return a>0&&o>0?i/Math.sqrt(a*o):0}function c4(e,t){let n=e.length;if(n<3)return null;let r=U2(e),i=U2(t),a=0,o=0,s=0;for(let c=0;c<n;c++)a+=(e[c]-r)**2,o+=(e[c]-r)*(t[c]-i),s+=(t[c]-i)**2;if(!(a>0))return null;let c=o/a,l=i-c*r,u=Math.max(0,s-c*o),d=Math.sqrt(u/(n-2)),f=d/Math.sqrt(a);return{a:l,b:c,se:f,p:f>0?n4(c/f,n-2):0,r2:s>0?1-u/s:0,n,s:d,mx:r,sxx:a}}function l4(e,t){let n=t.length,r=e[0]?.length??0;if(n<=r+1)return null;let i=Array.from({length:r},(t,r)=>{let i=0;for(let t=0;t<n;t++)i+=e[t][r];return i/n}),a=U2(t),o=Array.from({length:r},()=>new Float64Array(r+1)),s=0;for(let c=0;c<n;c++){let n=t[c]-a;s+=n*n;for(let t=0;t<r;t++){let a=e[c][t]-i[t];for(let n=0;n<r;n++)o[t][n]+=a*(e[c][n]-i[n]);o[t][r]+=a*n}}let c=Math.max(...o.map((e,t)=>e[t]));for(let e=0;e<r;e++){let t=e;for(let n=e+1;n<r;n++)Math.abs(o[n][e])>Math.abs(o[t][e])&&(t=n);if(!(Math.abs(o[t][e])>1e-12*c))return null;[o[e],o[t]]=[o[t],o[e]];for(let t=0;t<r;t++){if(t===e)continue;let n=o[t][e]/o[e][e];for(let i=e;i<=r;i++)o[t][i]-=n*o[e][i]}}let l=o.map((e,t)=>e[r]/e[t]),u=0;for(let o=0;o<n;o++){let n=a;for(let t=0;t<r;t++)n+=l[t]*(e[o][t]-i[t]);u+=(t[o]-n)**2}let d=W2(t);return{beta:l,std:l.map((t,n)=>d>0?t*W2(e.map(e=>e[n]))/d:0),r2:s>0?1-u/s:0}}function u4(e,t){let n=l4(e,t);return n?{shares:n.std.map((n,r)=>n*s4(e.map(e=>e[r]),t)),r2:n.r2}:null}function d4(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}var f4=2e3;function p4(e,t,{B:n=1e3,seed:r=1,alpha:i=.05}={}){let a=d4(r),o=[],s=Math.min(e,f4);for(let r=0;r<n;r++)o.push(t(Array.from({length:s},()=>Math.floor(a()*e))));let c=G2(o,i/2),l=G2(o,1-i/2);if(s<e){let n=t(Array.from({length:e},(e,t)=>t)),r=Math.sqrt(s/e);c=n+(c-n)*r,l=n+(l-n)*r}return{lo:c,hi:l}}var m4=[`management`,`quality`,`maintenance`,`production`],h4={measured:{label:`Measured`,meaning:`Read directly from the data. No model involved.`},trial:{label:`Confirmed by trial`,meaning:`A deliberate change with a before/after comparison.`},statistical:{label:`Statistical`,meaning:`A difference between groups of batches, with its p-value: the chance of a difference this large if there were none.`},correlation:{label:`Correlation`,meaning:`Two signals move together. A lead to test, not a proven cause.`},engineer:{label:`Confirmed by engineer`,meaning:`An engineer checked the finding and signed it in the report.`}},g4={"00":`Executive summary`,"01":`Since the last period`,"02":`Why batches miss the golden`,"03":`Better than the golden`,"04":`Quality: capability and containment`,"05":`Reliability and maintenance`,"06":`OEE and where time is lost`,"07":`Alerts that come before bad batches`,"08":`Changes detected`,"09":`Energy, cost and CO₂`,10:`Compared with the other lines`,11:`Shifts compared`,12:`Recommended actions`,13:`Next analyses to run`,14:`Method, evidence and approval`},_4=[...m4],v4={"00":_4,"01":[`management`],"02":[`quality`,`production`],"03":[`quality`,`production`],"04":[`quality`],"05":[`maintenance`],"06":[`management`,`maintenance`,`production`],"07":[`quality`,`production`],"08":[`quality`,`maintenance`],"09":[`management`],10:[`management`],11:[`quality`,`production`],12:_4,13:[`quality`,`production`],14:[`quality`]},y4=e=>`${e}. Supports your review; does not certify.`,b4=(e,t,n,r,i=[])=>({id:e,title:g4[e],verdict:t,roles:v4[e],findings:n,charts:r,notes:i,...n.length>3?{shown:3}:{}}),x4=e=>`${Math.round(e*100)}%`,S4=e=>`${Math.abs(e)>=10?Math.round(e):+e.toFixed(1)}%`;function C4(e,t){let n=Math.abs(e)<100?2:0;return new Intl.NumberFormat(`en-GB`,{style:`currency`,currency:t,minimumFractionDigits:n,maximumFractionDigits:n}).format(e)}var w4=e=>Number.isFinite(e)?Math.abs(e)>=1e3?Math.round(e).toLocaleString(`en-GB`):String(+e.toPrecision(Math.abs(e)<1?2:3)):`—`,T4=e=>Number.isFinite(e)?String(+e.toPrecision(4)):`—`,E4=(...e)=>O4(e=>Math.abs(e)<1?2:3,e),D4=(...e)=>O4(()=>4,e);function O4(e,t){let n=n=>t.map(t=>Number.isFinite(t)?String(+t.toPrecision(Math.min(17,e(t)+n))):`—`);for(let e=0;e<14;e++){let r=n(e);if(t.every((e,n)=>t.every((t,i)=>Object.is(e,t)||r[n]!==r[i])))return r}return n(14)}var k4=e=>`${e>0?`+`:e<0?`−`:``}${w4(Math.abs(e))}`;function A4(e){return e>=3600?`${w4(e/3600)} h`:e>=60?`${Math.round(e/60)} min`:`${Math.round(e)} s`}function j4(e){let t=e.value.key,n=t.lastIndexOf(`:`);return t===`duration`?`s`:e.units[t]??(n>0&&/^(mean|min|max|first|last|median|std|range)$/.test(t.slice(n+1))?e.units[t.slice(0,n)]??``:``)}var M4=e=>e===1?`once`:e===2?`twice`:`${e} times`,N4=(e,t,n=`${t}s`)=>`${e.toLocaleString(`en-GB`)} ${e===1?t:n}`,P4=e=>e.length<=1?e.join(``):`${e.slice(0,-1).join(`, `)} and ${e[e.length-1]}`,F4=e=>e.charAt(0).toUpperCase()+e.slice(1),I4=e=>e.charAt(0).toLowerCase()+e.slice(1);function L4(e){try{return new Intl.DateTimeFormat(`en-GB`,{timeZone:e}),!0}catch{return!1}}var R4=new Map,z4=(e,t)=>{let n=`${e}|${JSON.stringify(t)}`,r=R4.get(n);return r||R4.set(n,r=new Intl.DateTimeFormat(`en-GB`,{timeZone:L4(e)?e:`UTC`,...t})),r},B4=(e,t)=>z4(t,{day:`numeric`,month:`short`}).format(new Date(e*1e3)),V4=(e,t)=>z4(t,{day:`numeric`,month:`short`,hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}).format(new Date(e*1e3)),H4=(e,t)=>z4(t,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}).format(new Date(e*1e3)),U4=(e,t,n,r=`–`)=>`${V4(e,n)}${r}${B4(e,n)===B4(t,n)?H4(t,n):V4(t,n)}`,W4=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function G4(e,t){let n=z4(t,{weekday:`short`,hour:`2-digit`,hourCycle:`h23`}).formatToParts(new Date(e*1e3));return{day:W4.indexOf(n.find(e=>e.type===`weekday`).value),hour:Number(n.find(e=>e.type===`hour`).value)%24}}var K4=(e,t)=>`${W4[G4(e,t).day]} ${V4(e,t)}`,q4={min:`minimum`,max:`maximum`,mean:`mean`,integral:`integral`,first:`at start`,last:`at end`,delta:`change`};function J4(e){if(e===`duration`)return`Cycle duration`;let t=e.lastIndexOf(`:`);return t<0?e:`${e.slice(0,t)} ${q4[e.slice(t+1)]??e.slice(t+1)}`}var Y4=e=>e<.01?`p < 0.01`:`p = ${e.toFixed(2)}`;function X4(e){let t=e.numbers.r,n=e.evidence===`correlation`&&Number.isFinite(t)?`r = ${t.toFixed(2)}`:e.p===null?``:Y4(e.p);return n?`${h4[e.evidence].label} · ${n}`:h4[e.evidence].label}var Z4=3600,Q4=(e,t)=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i]<t?n=i+1:r=i}return n};function $4(e,t){let n=e.alertRules??[];if(!n.length)return null;let r=e.alerts??[],i=new Map,a=new Map,o=new Set;for(let e of r){let t=`${e.rule}|${e.streamId}`;if(o.has(`${t}|${e.t}`))continue;o.add(`${t}|${e.t}`);let n=i.get(t);n||i.set(t,n=[]),n.push(e.t),a.set(e.rule,(a.get(e.rule)??0)+1)}for(let e of i.values())e.sort((e,t)=>e-t);let s=(e,t)=>{let n=i.get(`${t}|${e.c.streamId}`);if(!n)return!1;let r=Q4(n,e.c.tstart-Z4);return r<n.length&&n[r]<=(e.c.tend??e.c.tstart)},c=e=>({section:b4(`07`,e,[],[]),actions:[],next:[],numbers:{}}),l=n.filter(e=>a.has(e.id));if(!l.length)return c(`No alert fired in this period.`);let u=t.filter(e=>e.level===`off`),d=t.filter(e=>e.level!==`off`);if(!u.length)return c(`No batch missed the golden, so no alert can be linked to one.`);if(u.length<5||d.length<5)return c(`${N4(u.length,`off-golden batch`,`off-golden batches`)} in this period: 5 are needed to link alerts to them.`);let f=l.map(e=>{let t=u.filter(t=>s(t,e.id)).length,n=d.filter(t=>s(t,e.id)).length;return{r:e,k1:t,t:a4(t,u.length,n,d.length)}}),p=o4(f.map(e=>e.t.p),N2),m=f.filter((e,t)=>p[t]&&e.t.p1>e.t.p2).sort((e,t)=>t.t.p1-t.t.p2-(e.t.p1-e.t.p2)),h=[],g=[],_=new Map;for(let e of m){let n=`F07-${h.length+1}`;_.set(e.r.id,n),h.push({id:n,section:`07`,refs:[`07`],evidence:`statistical`,p:e.t.p,numbers:R2({before:e.t.p1,rest:e.t.p2,p:e.t.p,fired:a.get(e.r.id)}),text:`“${e.r.name}” came before ${e.k1} of ${u.length} off-golden batches (${x4(e.t.p1)}) against ${x4(e.t.p2)} of the rest.`}),g.push({text:`Act on “${e.r.name}” when it fires: it came before ${x4(e.t.p1)} of off-golden batches.`,owner:`production`,urgent:!1,rank:(e.t.p1-e.t.p2)*(u.length/t.length),refs:[n]})}let v=m.length?[{kind:`table`,title:`07.1 · Alerts linked to off-golden batches: the share of batches each came before (in the hour before, or during)`,columns:[`Alert`,`Fired`,`Off-golden batches`,`The rest`],rows:m.map(e=>({cells:[e.r.name,a.get(e.r.id).toLocaleString(`en-GB`),x4(e.t.p1),x4(e.t.p2)],finding:_.get(e.r.id),status:`watch`}))}]:[],y=m.slice(0,2).map(e=>`“${e.r.name}”`),b=m.length?`${P4(y)} came before off-golden batches more often than before the rest${m.length>2?`, and ${N4(m.length-2,`more alert`)}`:``}.`:`No alert came before off-golden batches more often than before the rest.`,x=m.length?[]:[`Make an alert rule on the channel that goes with the gap (see 02) to warn before off-golden batches.`];return{section:b4(`07`,b,h,v),actions:g,next:x,numbers:{linked:m.length}}}var e3=(e,t)=>t===`duration`?e.c.tend===null?null:e.c.tend-e.c.tstart:e.c.kpis[t]??null,t3=e=>{let t=U2(e.map(e=>-e.gap));if(e.some(e=>e.g.value===0))return{text:w4(t),pct:null,abs:t};let n=U2(e.map(e=>-e.gap/Math.abs(e.g.value)*100));return{text:S4(n),pct:n,abs:t}},n3=e=>`${e<0?`−`:`+`}${S4(Math.abs(e))}`;function r3(e,t){let n=t.filter(e=>e.level===`better`),r=[],i=[],a=[],o=[];if(n.length<5)return{section:b4(`03`,n.length?`${N4(n.length,`batch`,`batches`)} beat the golden; 5 are needed to call it repeatable.`:`No batch beat the golden in this period.`,r,a),actions:i,next:o,numbers:{better:n.length}};let s=t.filter(e=>e.level===`golden`),c=s.length>=5?s:t.filter(e=>e.level!==`better`),l=e.value.label,u=t3(n),d=e=>{let t=`F03-${r.length+1}`;return r.push({id:t,section:`03`,refs:[`03`],...e}),t},f=e.streams.length>1;for(let[r,a]of z2(n,e=>e.c.streamId)){if(a.length<5)continue;let n=[...a].sort((e,t)=>e.gap-t.gap)[4],o=t3(a),s=e.streams.find(e=>e.id===r)?.name??`a stream`,c=d({evidence:`measured`,p:null,golden:{streamId:r,cycleId:n.c.id},numbers:R2({repeats:a.length,value:n.c.value,pct:o.pct??NaN,by:o.abs}),text:`Proposed new golden${f?` for ${s}`:``}: the batch of ${n.c.label}, the best ${l} that 5 batches reach (${w4(n.c.value)}). ${N4(a.length,`batch`,`batches`)} beat the golden by ${o.text} on ${l}, so this machine can reach it. Make it the golden to measure the next report against it.`});i.push({text:`Make the batch of ${n.c.label} the golden${f?` of ${s}`:``}: ${N4(a.length,`batch`,`batches`)} beat the current one by ${o.text}.`,owner:`quality`,urgent:!1,rank:a.length/t.length,refs:[c]})}r.length&&o.push(`Measure the next report against the new golden once it is set in Cycles.`);let p=[`duration`,...new Set(t.flatMap(e=>Object.keys(e.c.kpis)))].filter((t,n,r)=>t!==e.value.key&&r.indexOf(t)===n).flatMap(e=>{let t=n.map(t=>e3(t,e)).filter(H2),r=c.map(t=>e3(t,e)).filter(H2);return t.length<5||r.length<5?[]:[{k:e,ma:K2(t),mb:K2(r),p:Z2(t,r).p}]}),m=o4(p.map(e=>e.p),N2),h=p.filter((e,t)=>m[t]&&e.ma!==e.mb).map(e=>({...e,label:J4(e.k),pct:e.mb===0?NaN:(e.ma-e.mb)/Math.abs(e.mb)*100})).sort((e,t)=>(Math.abs(t.pct)||1/0)-(Math.abs(e.pct)||1/0)).slice(0,5);for(let e of h)d({evidence:`correlation`,p:e.p,numbers:R2({better:e.ma,golden:e.mb,pct:e.pct,p:e.p}),text:`Batches that beat the golden go with ${e.ma<e.mb?`a lower`:`a higher`} ${e.label}: ${w4(e.ma)} against ${w4(e.mb)} at golden level${Number.isFinite(e.pct)?` (${n3(e.pct)})`:``}.`});let g=h.filter(e=>Number.isFinite(e.pct)).map(e=>({label:e.label,pct:e.pct,text:`${w4(e.ma)} / ${w4(e.mb)}`}));g.length&&a.push({kind:`diverging`,rows:g,title:`03.1 · The ${N4(n.length,`better batch`,`better batches`)} against those at golden level, % difference. Values: better / at golden level.`});let _=h.slice(0,3).map(e=>`${e.ma<e.mb?`a lower`:`a higher`} ${e.label}`);return{section:b4(`03`,`${N4(n.length,`batch`,`batches`)} beat the golden by ${u.text} on ${l}${_.length?` with ${P4(_)}`:``}.`,r,a),actions:i,next:o,numbers:{better:n.length}}}var i3=`Ppk is indicative: it assumes the values are normally distributed and the process stable, which this report does not test.`,a3=new Set([`mean`,`min`,`max`,`first`,`last`]),o3=e=>Number.isFinite(e)?e.toFixed(2):`–`;function s3(e,t){let n=Object.entries(e.context?.channels??{}).filter(([,e])=>e.lsl!==null||e.usl!==null);if(!n.length)return null;let r=e.context?.ppkMin??1.33,i=[...new Set(t.flatMap(e=>Object.keys(e.c.kpis)))],a=[];for(let[e,r]of n)for(let n of i){let i=n.lastIndexOf(`:`);if(n.slice(0,i)!==e||!a3.has(n.slice(i+1)))continue;let o=t.map(e=>e.c.kpis[n]).filter(H2),s=W2(o);if(o.length<30)continue;let c=U2(o),l=o.filter(e=>r.usl!==null&&e>r.usl||r.lsl!==null&&e<r.lsl).length/o.length,u=s>0?Math.min(r.usl===null?1/0:(r.usl-c)/(3*s),r.lsl===null?1/0:(c-r.lsl)/(3*s)):l>0?-1/0:1/0;a.push({key:n,label:J4(n),lsl:r.lsl,usl:r.usl,n:o.length,m:c,cpk:u,out:l})}if(!a.length)return{section:`04`,needs:`04.1 · Add the mean, minimum or maximum of ${P4(n.map(([e])=>e))} to the cycle rule’s KPIs (30 batches or more) to see capability.`};a.sort((e,t)=>e.cpk-t.cpk);let o=e=>{let[t,n,r]=D4(e.lsl??NaN,e.usl??NaN,e.m);return{m:r,limits:`${e.lsl===null?`–`:t} to ${e.usl===null?`–`:n}`}},s=e=>e.out>0&&e.out<.005?`${Math.round(e.out*e.n)} of ${e.n}`:null,c=e=>`${s(e)??x4(e.out)} ${s(e)?`batches`:`of batches`} outside`,l=[],u=[],d=new Map,f=a.filter(e=>e.cpk<r);for(let e of f){let t=`F04-${l.length+1}`,n=o(e);d.set(e.key,t),l.push({id:t,section:`04`,refs:[`04`],evidence:`measured`,p:null,numbers:R2({cpk:e.cpk,n:e.n,mean:e.m,outside:e.out}),text:`${e.label}: Ppk ${o3(e.cpk)} over ${N4(e.n,`batch`,`batches`)} (mean ${n.m}, limits ${n.limits}); ${c(e)}.`}),e.cpk<1&&u.push({text:`Bring ${e.label} inside its limits: Ppk ${o3(e.cpk)}, ${c(e)}.`,owner:`quality`,urgent:e.out>0,rank:e.out+(1-Math.max(e.cpk,-10))/10,refs:[t]})}let p=[{kind:`table`,title:`04.1 · Capability per feature (indicative Ppk, capable from ${r})`,columns:[`Feature`,`Limits`,`Mean`,`Ppk (indicative)`,`Outside`],rows:a.map(e=>{let t=o(e),n=d.get(e.key);return{cells:[e.label,t.limits,t.m,o3(e.cpk),s(e)??x4(e.out)],status:e.cpk<1?`crit`:e.cpk<r?`watch`:`ok`,...n?{finding:n}:{}}})}];return{section:{...b4(`04`,f.length?`${N4(f.length,`feature`)} below Ppk ${r}${f.length>1?`; ${f[0].label} the lowest`:``}.`:`Every feature with limits is capable (Ppk ${r} or more).`,l,p),subtitle:y4(`Capability (AIAG SPC)`),fold:!0},actions:u,next:[],numbers:{low:f.length}}}var c3=[`generic`,`discrete`,`process`,`regulated`],l3={generic:{id:`generic`,label:`Generic`,first:[],collapsed:[],roles:{},terms:{}},discrete:{id:`discrete`,label:`Discrete manufacturing (stamping, machining, assembly)`,first:[`06`,`05`,`04`,`02`],collapsed:[`03`,`13`],roles:{"06":[`management`,`maintenance`,`production`,`quality`],"04":[`quality`,`production`]},terms:{"slow batches":`slow cycles`,batches:`parts`,batch:`part`}},process:{id:`process`,label:`Process (chemical, food, batch plants)`,first:[`02`,`04`,`09`,`03`],collapsed:[`10`,`13`],roles:{"09":[`management`,`production`],"04":[`quality`,`production`]},terms:{"bad parts":`bad batches`}},regulated:{id:`regulated`,label:`Regulated (pharma, food: quality and batch review first)`,regulated:!0,first:[`04`,`02`,`05`,`07`,`08`],collapsed:[`10`,`13`],roles:{"04":[`quality`,`production`],"05":[`maintenance`,`quality`],"06":[`management`,`maintenance`,`production`,`quality`],"09":[`management`,`production`]},terms:{"bad parts":`bad batches`}}},u3=e=>l3[c3.find(t=>t===e)??`generic`],d3=e=>e===`quality`?`discrete`:e===`plants`?`process`:e===`pharma`?`regulated`:`generic`,f3=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),p3=e=>[...e].sort((e,t)=>t.length-e.length).map(f3).join(`|`),m3=new Map;function h3(e,t,n=[]){if(!e||!Object.keys(t.terms).length)return e;let r=m3.get(t.id);if(!r){let e=`(?<![\\w.])(${p3(Object.keys(t.terms))})(?!\\w)(?!\\.\\w)`;m3.set(t.id,r={all:new RegExp(e,`gi`),has:new RegExp(e,`i`)})}let{all:i,has:a}=r,o=e=>e.replace(i,e=>{let n=t.terms[e.toLowerCase()];return e[0]===e[0].toLowerCase()?n:n[0].toUpperCase()+n.slice(1)}),s=n.filter(e=>e&&a.test(e));return s.length?e.split(RegExp(`(${p3(s)})`)).map((e,t)=>t%2?e:o(e)).join(``):o(e)}function g3(e){let t=e.context;return[...new Set([e.project,e.rule.name,e.value.label,...e.streams.map(e=>e.name),...Object.keys(e.units),...e.recordings.map(e=>e.name),...e.goldens.map(e=>e.label),...(e.alertRules??[]).map(e=>e.name),...(e.goldenChanges??[]).map(e=>e.label),...t?[...Object.keys(t.channels),...t.shifts.map(e=>e.name),...t.stops.map(e=>e.name),...t.lines.map(e=>e.name),...t.units.map(e=>e.name)]:[]])]}var _3=new Set([`id`,`section`,`kind`,`evidence`,`ref`,`refs`,`finding`,`day`,`status`,`unit`,`tone`,`roles`,`cites`,`owner`,`alert`,`batch`,`golden`]);function v3(e,t){return typeof e==`string`?t(e):Array.isArray(e)?e.map(e=>v3(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,_3.has(e)?n:v3(n,t)])):e}function y3(e,t,n=[]){if(t.id===`generic`)return e;let r=e=>h3(e,t,n),i=e=>e===`00`?-1:t.first.includes(e)?t.first.indexOf(e):t.first.length,a=e.sections.map((e,t)=>({s:e,i:t})).sort((e,t)=>i(e.s.id)-i(t.s.id)||e.i-t.i).map(({s:e})=>({...v3(e,r),roles:t.roles[e.id]??e.roles,...t.collapsed.includes(e.id)&&(e.findings.length||e.charts.length)?{collapsed:!0}:{}}));return{...e,preset:t.id,sections:a,actions:v3(e.actions,r),missing:v3(e.missing,r)}}var b3=[`setting`,`measurement`,`quality`,`outside`,`energy`,`ignore`],x3={setting:`Adjustable setting`,measurement:`Measurement`,quality:`Quality result`,outside:`Outside influence`,energy:`Energy`,ignore:`Ignore`},S3=4e3,C3=(e=``)=>({role:null,unit:e,lo:null,hi:null,lsl:null,usl:null,target:null,calibration:null,suggested:!1}),w3=()=>({v:1,process:``,channels:{},lines:[],units:[],shifts:[],stops:[],costs:{currency:`EUR`,kwh:null,lineHour:null,scrap:null,rework:null,co2:null,licence:null}}),T3=e=>e&&!e.suggested?e.role:null,E3=e=>Object.keys(e?.channels??{}).filter(t=>T3(e.channels[t])===`energy`).sort()[0]??null,D3=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},O3=e=>Array.isArray(e)?e:[],k3=(e,t)=>typeof e==`string`?e.slice(0,t):``,A3=e=>typeof e==`number`&&Number.isFinite(e)?e:null,j3=e=>O3(e).filter(e=>typeof e==`string`).slice(0,500),M3=(e,t)=>e!==null&&t!==null&&e>=t?[null,null]:[e,t],N3=/^([01]\d|2[0-3]):[0-5]\d$/,P3=/^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d$/,F3=e=>e.suggested===!0?{suggested:!0}:{};function I3(e){let t=D3(e),n=k3(t.name,80),r=k3(t.from,16),i=k3(t.to,16);if(P3.test(r)&&P3.test(i)&&r<i)return[{name:n,from:r,to:i,...F3(t)}];if(!N3.test(r)||!N3.test(i))return[];let a=t.days===void 0?void 0:[...new Set(O3(t.days).filter(e=>Number.isInteger(e)&&e>=0&&e<=6))].sort();return a&&!a.length?[]:[{name:n,from:r,to:i,...a?{days:a}:{},...F3(t)}]}function L3(e){let t=new Set,n=new Set;return O3(e).slice(0,50).map(e=>({name:k3(D3(e).name,80),streams:j3(D3(e).streams),...F3(D3(e))})).filter(e=>e.name&&!t.has(e.name)&&t.add(e.name)).map(e=>({...e,streams:e.streams.filter(e=>!n.has(e)&&n.add(e))}))}function R3(e){let t=D3(e),n=D3(t.costs),r=w3(),i=Object.create(null);for(let[e,n]of Object.entries(D3(t.channels)).slice(0,2e3)){let t=D3(n),r=b3.find(e=>e===t.role)??null,[a,o]=M3(A3(t.lo),A3(t.hi)),[s,c]=M3(A3(t.lsl),A3(t.usl));i[e.slice(0,200)]={role:r,unit:k3(t.unit,40),lo:a,hi:o,lsl:s,usl:c,target:A3(t.target),calibration:A3(t.calibration),suggested:t.suggested===!0&&r!==null,...t.unitSuggested===!0?{unitSuggested:!0}:{},...t.rangeSuggested===!0&&a!==null&&o!==null?{rangeSuggested:!0}:{}}}return{v:1,process:k3(t.process,S3),...t.processSuggested===!0&&k3(t.process,1)?{processSuggested:!0}:{},channels:i,lines:L3(t.lines),units:O3(t.units).slice(0,100).map(e=>({name:k3(D3(e).name,80),channels:j3(D3(e).channels),...F3(D3(e))})).filter(e=>e.name),shifts:O3(t.shifts).slice(0,12).map(e=>({name:k3(D3(e).name,40),start:k3(D3(e).start,5),end:k3(D3(e).end,5),...F3(D3(e))})).filter(e=>e.name&&N3.test(e.start)&&N3.test(e.end)),stops:O3(t.stops).slice(0,500).flatMap(I3),costs:{currency:/^[A-Z]{3}$/.test(String(n.currency))?String(n.currency):r.costs.currency,kwh:A3(n.kwh),lineHour:A3(n.lineHour),scrap:A3(n.scrap),rework:A3(n.rework),co2:A3(n.co2),licence:A3(n.licence)},...(A3(t.idealCycleS)??0)>0?{idealCycleS:t.idealCycleS}:{},...t.hideShifts===!0?{hideShifts:!0}:{},...c3.some(e=>e===t.preset)?{preset:t.preset}:{},...(A3(t.ppkMin)??0)>=1&&t.ppkMin<=3?{ppkMin:t.ppkMin}:{}}}var z3=(e,t)=>{let n=e+yB(e,t);return Math.floor((n%86400+86400)%86400/60)},B3=e=>e.slice(0,2)*60+ +e.slice(3,5);function V3(e,t,n){if(!t.length)return null;let r=z3(e,n);for(let e of t){let t=B3(e.start),n=B3(e.end);if(t<n?r>=t&&r<n:r>=t||r<n)return e.name}return null}var H3=e=>(new Date(`${e}T00:00:00Z`).getUTCDay()+6)%7;function U3(e,t,n,r){let i=[];for(let a of e.stops){if(a.from.length>5){i.push({t0:xB(a.from.slice(0,10),a.from.slice(11),t),t1:xB(a.to.slice(0,10),a.to.slice(11),t)});continue}for(let e=SB(bB(n,t),-1),o=bB(r,t);e<=o;e=SB(e,1)){if(a.days&&!a.days.includes(H3(e)))continue;let o=xB(e,a.from,t),s=xB(a.to>a.from?e:SB(e,1),a.to,t);s>n&&o<r&&i.push({t0:o,t1:s})}}return i}function W3(e){let t=e=>e.filter(e=>!e.suggested),n=Object.create(null);for(let[t,r]of Object.entries(e.channels)){let{unitSuggested:e,rangeSuggested:i,...a}=r;n[t]={...a,role:T3(r),suggested:!1,unit:e?``:r.unit,lo:i?null:r.lo,hi:i?null:r.hi}}let{processSuggested:r,...i}=e;return{...i,process:r?``:e.process,channels:n,shifts:t(e.shifts),stops:t(e.stops),lines:t(e.lines),units:t(e.units)}}function G3(e){let t=e=>Number(!!e);return t(e.processSuggested)+Object.values(e.channels).reduce((e,n)=>e+t(n.suggested)+t(n.unitSuggested)+t(n.rangeSuggested),0)+[...e.shifts,...e.stops,...e.lines,...e.units].filter(e=>e.suggested).length}function K3(e){let t=e=>e.map(e=>{let t={...e};return delete t.suggested,t}),n=Object.create(null);for(let[t,r]of Object.entries(e.channels)){let e={...r,suggested:!1};delete e.unitSuggested,delete e.rangeSuggested,n[t]=e}let r={...e,channels:n,shifts:t(e.shifts),stops:t(e.stops),lines:t(e.lines),units:t(e.units)};return delete r.processSuggested,r}function q3(e,t){let n=W3(e??w3()),r=Object.values(n.channels),i=r.some(e=>T3(e)===`energy`),a=n.costs.kwh!==null,o=[];return!n.shifts.length&&!n.hideShifts&&o.push({section:`02`,add:null,needs:`02.4 · Add shifts in Process context to split the batches that miss the golden by shift.`}),r.some(e=>e.lsl!==null||e.usl!==null)||o.push({section:`04`,add:`add specification limits`,needs:`Add specification limits (LSL, USL) to the channels in Process context to see capability (Ppk).`}),n.shifts.length?n.costs.lineHour===null&&o.push({section:`06`,add:null,needs:`06.1 · Add the cost of an hour of line time in Process context to see what the lost time costs.`}):o.push({section:`06`,add:`add shifts`,needs:`Add shifts and the cost of an hour of line time in Process context to see OEE and where time is lost.`}),t||o.push({section:`07`,add:`make alert rules`,needs:`Make alert rules in this project to see which alerts come before off-golden batches.`}),r.some(e=>T3(e)===`setting`)||o.push({section:`08`,add:`mark the adjustable settings`,needs:`Mark which channels are adjustable settings in Process context to see their changes.`}),i?(a||o.push({section:`09`,add:null,needs:`09 · Add the price per kWh in Process context to see what the energy costs.`}),n.costs.co2===null&&o.push({section:`09`,add:null,needs:`09 · Add the grid CO₂ factor (kg per kWh) in Process context to see CO₂ per batch.`})):o.push({section:`09`,add:`mark the energy channel`,needs:`Mark the energy channel in Process context to see energy per batch; the price per kWh adds its cost and the grid CO₂ factor its CO₂.`}),n.lines.filter(e=>e.streams.length).length<2&&o.push({section:`10`,add:`name two or more lines`,needs:`Say which streams are comparable lines in Process context (two or more) to compare lines.`}),!n.shifts.length&&!n.hideShifts&&o.push({section:`11`,add:`add shifts`,needs:`Add the shifts in Process context to compare them.`}),o}function J3(e){let t=W3(e??w3()),n=Object.values(t.channels),r=[];return t.costs.lineHour===null&&r.push({add:`the cost of an hour of line time`,shows:`losses in money`}),t.costs.kwh===null&&n.some(e=>T3(e)===`energy`)&&r.push({add:`the price per kWh`,shows:`what the energy costs`}),t.costs.scrap===null&&n.some(e=>e.lsl!==null||e.usl!==null)&&r.push({add:`the cost of a scrapped batch`,shows:`what the batches off specification cost`}),r}function Y3(e,t){let n=q3(e,t).filter(e=>e.add!==null),r=new Map;for(let e of n)r.set(e.add,[...r.get(e.add)??[],e.section]);return{ready:15-n.length,total:15,adds:[...r].map(([e,t])=>({add:e,sections:t}))}}var X3=.2,Z3=20,Q3=1e5,$3=2e4,e6=1e3,t6=class{values=[];#e;#t=0;#n=d4(1);constructor(e){this.#e=e}push(e){let t=this.#t++;if(t<this.#e)this.values.push(e);else{let n=Math.floor(this.#n()*(t+1));n<this.#e&&(this.values[n]=e)}}},n6=11,r6=class{#e=0;#t=1/0;#n=-1/0;#r=!1;#i=!0;#a=NaN;#o=NaN;#s=NaN;#c=NaN;#l=[];#u=NaN;#d=NaN;#f=0;#p=0;#m=NaN;#h=NaN;#g=0;#_=0;#v=0;#y=0;#b=[];#x=new Float64Array(64);#S=0;#C=new Float64Array(63);#w=new t6($3);#T=0;#E=0;#D=new Float64Array(n6);#O=new Float64Array(n6);#k=new Float64Array(n6);#A=0;#j=0;#M=0;#N=[];#P=new t6(Q3);push(e,t){for(let n=0;n<e.length;n++){let r=t[n],i=e[n];if(!(r!==r||i!==i)){if(this.#e++,r<this.#t&&(this.#t=r),r>this.#n&&(this.#n=r),this.#P.push(r),this.#s===this.#s){let e=i-this.#s,t=!1;this.#l.length<e6?(this.#l.push(e),this.#l.length===e6&&this.#F()):e>this.#d&&(t=!0,this.#f+=e-this.#u,this.#p++),r!==this.#c&&(this.#r=!0),r<this.#c&&(this.#i=!1),Math.abs(r-this.#m)<=this.#_&&!t?this.#g++:(this.#L(this.#s),this.#I(i,r))}else this.#o=i,this.#a=r,this.#I(i,r);this.#R(r),this.#z(i,r),this.#s=i,this.#c=r}}}#F(){this.#u=K2(this.#l.filter(e=>e>0)),this.#d=this.#u>0?4*this.#u:1/0;for(let e of this.#l)e>this.#d&&(this.#f+=e-this.#u,this.#p++)}#I(e,t){this.#m=t,this.#h=e,this.#g=1,this.#_=X3*this.#E}#L(e){let t=e-this.#h;this.#g>=20&&t>=300&&(this.#v+=t,this.#y++,this.#b.length<Z3&&this.#b.push({t0:this.#h,t1:e,value:this.#m}))}#R(e){let t=this.#x,n=this.#C;if(t[this.#S++]=e,this.#S<64)return;for(let e=1;e<64;e++)n[e-1]=t[e]-t[e-1];n.sort();let r=n[31];for(let e=0;e<n.length;e++)n[e]=Math.abs(n[e]-r);n.sort(),this.#T=1.4826*n[31]/Math.SQRT2,this.#w.push(this.#T),this.#T>0&&(this.#E=this.#E?.9*this.#E+.1*this.#T:this.#T),t[0]=e,this.#S=1}#z(e,t){let n=this.#k,r=this.#A===n6,i=this.#A;if(r){let e=this.#O[this.#j],t=0;for(;n[t]!==e;)t++;for(;t<i-1;t++)n[t]=n[t+1];i--}let a=i;for(;a>0&&n[a-1]>t;)n[a]=n[a-1],a--;if(n[a]=t,this.#A=i+1,this.#D[this.#j]=e,this.#O[this.#j]=t,this.#j=(this.#j+1)%n6,this.#A<n6)return;let o=e=>(this.#j+e)%n6,s=n[5],c=this.#O[o(5)],l=Math.abs(c-s),u=Math.max(this.#T,1e-9*Math.max(1,Math.abs(s)));if(l<=6*u)return;let d=Array.from(n,e=>Math.abs(e-s)).sort((e,t)=>e-t);l<=6*Math.max(1.4826*d[5],u)||Math.abs(this.#O[o(4)]-s)>l/2||Math.abs(this.#O[o(6)]-s)>l/2||(this.#M++,this.#N.length<Z3&&this.#N.push(this.#D[o(5)]))}result(){this.#g&&this.#L(this.#s),this.#l.length<e6&&this.#l.length>=2&&this.#F();let e=this.#s-this.#o-this.#f,t=this.#P.values,n=this.#w.values.filter(e=>e>0),r=this.#s-this.#o;return{n:this.#e,rateHz:this.#e>1&&e>0?(this.#e-1)/e:0,gapS:this.#f,gaps:this.#p,flatS:this.#v,flatRuns:this.#y,flats:this.#b,noise:n.length?K2(n):0,spikes:this.#M,spikeAt:this.#N,min:this.#t,max:this.#n,lo:G2(t,.005),hi:G2(t,.995),median:K2(t),p01:G2(t,.01),p99:G2(t,.99),moves:this.#r,clock:this.#i&&r>0&&Math.abs(this.#c-this.#a-r)<=.01*r,counter:this.#i&&this.#r}}};function i6(e){let t=e.slice(0,Math.max(3,Math.ceil(e.length/3)));if(!t.length)return null;let n=K2(t.map(e=>e.lo)),r=K2(t.map(e=>e.hi)),i=(r-n)/2;return r>n?{lo:n-i,hi:r+i,n:t.length}:null}var a6=3600,o6=86400;function s6(e,t){let n=e.filter(e=>H2(e.c.d?.[t])).map(e=>({t:e.c.tstart,v:e.c.d[t],edge:e.g.edges[t],rec:e.c.recordingId}));if(n.length<20)return null;let r=n[0].t,i=B2(n,r),a=i,o=`day`;if(i.length<7&&(a=V2(n,e=>e.rec),o=`recording`,a.length<6&&(a=V2(n,e=>Math.floor((e.t-r)/3600)),o=`hour`)),a.length<6)return null;a.sort((e,t)=>e.t-t.t);let s=c4(a.map(e=>(e.t-r)/o6),a.map(e=>e.v)),c=K2(n.map(e=>e.edge).filter(H2));return s&&c>0&&s.b!==0?{t0:r,means:a,per:o,days:i.length,fit:s,edge:c,step:c6(a,s)}:null}function c6(e,t){let n=e.length,r=t.s*t.s*(t.n-2);if(n<4)return null;let i=e.reduce((e,t)=>e+t.v,0),a=e.reduce((e,t)=>e+t.v*t.v,0),o=1/0,s=0,c=0;for(let t=1;t<n;t++){c+=e[t-1].v;let r=a-c*c/t-(i-c)**2/(n-t);r<o&&(o=r,s=t)}if(!(o<.5*r))return null;let l=e.slice(0,s),u=e.slice(s);return{t:e[s].t,d:u.reduce((e,t)=>e+t.v,0)/u.length-l.reduce((e,t)=>e+t.v,0)/l.length}}function l6(e,t,n,r){let{t0:i,fit:a,edge:o}=n,{a:s,b:c,s:l,n:u,mx:d,sxx:f}=a,p=Math.sign(c)*o,m=i+(p-s)/c*o6,h=s+c*((r-i)/o6),g=Math.abs(h)>=o;if(!g&&(m-r)/o6>365)return null;let _=(r4(1-N2/2,u-2)*l)**2,v=s+c*d-p,y=c*c-_/f,b=(c*v)**2-y*(v*v-_/u),x=y>0&&b>=0?[(-c*v-Math.sqrt(b))/y,(-c*v+Math.sqrt(b))/y].map(e=>i+(d+e)*o6).sort((e,t)=>e-t):null,S=g?r:m;return{ch:e,key:t,b:c,p:a.p,days:n.days,n:u,per:n.per,edge:o,cross:m,lo:x?x[0]:m,hi:x?x[1]:null,past:g,vNow:h,points:n.means,line:{t0:i,v0:s,t1:S,v1:s+c*((S-i)/o6)}}}function u6(e,t,n,r,i,a,o,s=[],c=null){let l={ch:e,sid:t,key:n,drift:a,stuck:[]},u=r.flatMap(e=>e.health.channels[n]?[{r:e,h:e.health.channels[n]}]:[]);if(!u.length&&!a)return null;let d=i?` ${i}`:``,f=e=>{let t=0,n=s.length;for(;t<n;){let r=t+n>>1;s[r]<e.t0?t=r+1:n=r}return t<s.length&&s[t]<=e.t1},p=u.flatMap(e=>e.h.flats).filter(e=>!s.length||f(e)).sort((e,t)=>e.t0-t.t0),m=s.length?p.reduce((e,t)=>e+t.t1-t.t0,0):u.reduce((e,t)=>e+t.h.flatS,0),h=s.length?p.length:u.reduce((e,t)=>e+t.h.flatRuns,0);if(u.some(e=>e.h.moves)&&u.some(e=>e.h.noise>0)&&m>=600&&p.length){let e=X3*K2(u.map(e=>e.h.noise).filter(e=>e>0)),t=[];for(let n of p){let r=t[t.length-1];r&&n.t0-r.t1<=3600&&Math.abs(n.value-r.value)<=e?(r.t1=Math.max(r.t1,n.t1),r.rec+=n.t1-n.t0):t.push({...n,rec:n.t1-n.t0})}let n=t.reduce((e,t)=>t.t1-t.t0>e.t1-e.t0?t:e),r=t.length+h-p.length;return{...l,status:`Replace`,since:p[0].t0,stuck:t.map(({t0:e,t1:t})=>({t0:e,t1:t})),found:`Stuck at ${T4(n.value)}${d} from ${U4(n.t0,n.t1,o,` to `)}, ${A4(n.rec)} of it recorded${r>1?`; ${M4(r)} in all, ${A4(m)} recorded`:``}.`}}if(a){let e=a.per===`day`?`${k4(a.b*7)}${d} a week`:`${k4(a.b)}${d} a day`,t=`over ${N4(a.days,`day`)}${a.per===`day`?``:`, ${N4(a.n,a.per)}`}`;return{...l,status:`Drifting`,since:a.points[0]?.t??null,found:`${a.past?`Offset ${k4(a.vNow)}${d} against the golden, past the band edge (${w4(a.edge)}${d}); drifting ${e} ${t}.`:`Offset drifting ${e} against the golden ${t}; reaches the band edge (${w4(a.edge)}${d}) around ${B4(a.cross,o)}.`} Check calibration or the process.`}}let g=[];c&&g.push({since:c.t,text:`Offset against the golden moved by ${k4(c.d)}${d} on ${B4(c.t,o)} and stayed there: a change, not a drift.`});let _=K2(u.map(e=>e.h.rateHz).filter(e=>e>0));if(u.length>=4){let e=u[u.length-1],t=u.slice(0,-1).map(e=>e.h.noise).filter(e=>e>0),n=K2(t);t.length>=3&&n>0&&e.h.noise/n>=1.3&&J2(e.h.noise,t)>=3&&g.push({text:`Noise up ${x4(e.h.noise/n-1)}. Check the cable and its shielding.`,since:e.r.t0})}let v=u.reduce((e,t)=>e+t.h.n,0),y=u.reduce((e,t)=>e+t.h.spikes,0);v&&y/v>=1e-4&&g.push({text:`${N4(y,`spike`)}.`,since:Math.min(...u.flatMap(e=>e.h.spikeAt))});let b=u.reduce((e,t)=>e+(t.r.t1-t.r.t0),0),x=u.reduce((e,t)=>e+t.h.gapS,0),S=u.reduce((e,t)=>e+t.h.gaps,0);b>0&&x/b>=.01&&g.push({text:`${A4(x)} of gaps in ${N4(S,`place`)}.`,since:u.find(e=>e.h.gaps).r.t0});let C=u.find(e=>e.h.rateHz>0&&e.h.rateHz<.9*_);if(C&&g.push({text:`Rate dropped from ${w4(_)} Hz to ${w4(C.h.rateHz)} Hz on ${B4(C.r.t0,o)}.`,since:C.r.t0}),u.length>=3){let e=i6(u.map(e=>e.h)),t=e?.lo??0,n=e?.hi??0,r=1e-9*Math.max(1,Math.abs(t),Math.abs(n)),i=e?u.find(e=>e.h.min<t-r||e.h.max>n+r):void 0;if(i){let[a,o,s]=D4(i.h.max>n+r?i.h.max:i.h.min,t,n);g.push({since:i.r.t0,text:`Read ${a}${d}, outside the usual ${o} to ${s}${d} learned from the first ${N4(e.n,`recording`)}.`})}}return g.length?{...l,status:`Watch`,found:g.map(e=>e.text).join(` `),since:Math.min(...g.map(e=>e.since)),...c&&g.length===1?{step:c}:{}}:{...l,status:`Healthy`,found:`No gaps or spikes worth a look, rate steady at ${w4(_)} Hz.`,since:null}}function d6(e,t){let n=e.streams.length>1;return[...z2(t,e=>e.c.streamId)].flatMap(([t,r])=>{let i=f6(e,r);return i?[{...i,text:n?`${e.streams.find(e=>e.id===t)?.name??t}: ${I4(i.text)}`:i.text}]:[]}).sort((e,t)=>(e.p??1)-(t.p??1))[0]??null}function f6(e,t){let n=t.filter(e=>e.c.tend!==null).map(e=>({t:e.c.tstart,v:e.c.tend-e.c.tstart}));if(n.length<30)return null;let r=K2(n.map(e=>e.v)),i=n[0].t,a=B2(n.map(e=>({t:e.t,v:e.v/r*100})),i),o=r>0&&a.length>=7?c4(a.map(e=>(e.t-i)/(7*o6)),a.map(e=>e.v)):null,s=o&&o.p<.01&&o.b>0&&!c6(a,o)?o.b:null,c=t.map(e=>e.c.value),l=Math.floor(c.length/3),u=c.slice(0,l),d=c.slice(c.length-l),f=q2(u),p=f>0?q2(d)/f:NaN,m=null;if(Number.isFinite(p)&&p>=1.15){let e=d4(1),t=Math.min(l,f4),n=Math.sqrt(t/l),r=n=>q2(Array.from({length:t},()=>n[Math.floor(e()*n.length)])),i=0,a=0;for(let e=0;e<1e3;e++){let e=r(u),t=r(d);e>0&&(a++,p+(t/e-p)*n<=1&&i++)}m=a?(i+1)/(a+1):1}let h=m!==null&&m<.01?p-1:null;if(s===null&&h===null)return null;let g=[...s===null?[]:[`cycle time grows ${w4(s)}% a week since ${B4(i,e.tz)}`],...h===null?[]:[`the spread of ${e.value.label} is up ${x4(h)}`]];return{text:`${F4(g.join(` and `))}.${g.length===2?` Together they are consistent with wear.`:` Consistent with wear.`}`,p:Math.min(s===null?1:o.p,h===null?1:m),grow:s,spread:h}}var p6=e=>new Set(e.recordings.flatMap(e=>Object.entries(e.health?.channels??{}).filter(([,e])=>e.clock).map(([e])=>e)));function m6(e){let t=new Map;for(let n of e.recordings)for(let[e,r]of Object.entries(n.health?.channels??{}))r.moves&&t.set(e,(t.get(e)??!0)&&r.counter===!0);return new Set([...t].filter(([,e])=>e).map(([e])=>e))}function h6(e,t){let n=e.recordings.filter(e=>e.health).sort((e,t)=>e.t0-t.t0),r=new Map,i=W3(e.context??w3()),a=p6(e);for(let e of Object.keys(i.channels))[`setting`,`ignore`].includes(T3(i.channels[e])??``)&&a.add(e);for(let t of m6(e))a.add(t);let o=new Map([...z2(e.cycles,e=>e.streamId)].map(([e,t])=>[e,t.map(e=>e.tstart).sort((e,t)=>e-t)]));for(let e of n)for(let t of Object.keys(e.health.channels))a.has(t)||r.set(`${e.streamId}\u0000${t}`,{sid:e.streamId,key:t});for(let e of t)for(let t of Object.keys(e.c.d??{}))a.has(t)||r.set(`${e.c.streamId}\u0000${t}`,{sid:e.c.streamId,key:t});let s=e.streams.length>1,c=z2(t,e=>e.c.streamId),l=(t,n)=>s?`${e.streams.find(e=>e.id===t)?.name??t} · ${n}`:n,u={Replace:0,Drifting:1,Watch:2,Healthy:3},d=[...r.values()].map(({sid:e,key:t})=>s6(c.get(e)??[],t)),f=o4(d.flatMap(e=>e?[e.fit.p]:[]),N2),p=0,m=d.map(e=>!!e&&f[p++]);return[...r.values()].map(({sid:t,key:r},i)=>{let a=l(t,r),s=d[i],c=s&&m[i]?s.step:null;return u6(a,t,r,n.filter(e=>e.streamId===t),e.units[r]??``,s&&m[i]&&!c?l6(a,r,s,e.period.to):null,e.tz,o.get(t),c)}).filter(e=>!!e).sort((e,t)=>u[e.status]-u[t.status]||(e.drift&&t.drift?e.drift.cross-t.drift.cross:0)||e.ch.localeCompare(t.ch))}function g6(e,t){let n=h6(e,t),r=[],i=[],a=[],o=[],s=new Map,c=e.streams.length>1,l=t=>e.streams.find(e=>e.id===t)?.name??t,u=[...z2(n.filter(e=>e.status===`Drifting`),e=>e.sid).values()].filter(e=>e.length>1),d=new Set(u.flat()),f=[...z2(n.filter(e=>e.step),t=>`${t.sid}\u0000${B4(t.step.t,e.tz)}`).values()].filter(e=>e.length>1),p=new Set(f.flat());for(let t of n){let n=`F05-${r.length+1}`;if((t.status===`Replace`||t.status===`Drifting`)&&s.set(t,n),t.status===`Replace`)r.push({id:n,section:`05`,refs:[`05`],evidence:`measured`,p:null,numbers:{},text:`${t.ch}: ${t.found}`}),i.push({text:`Replace or repair ${t.ch}: ${I4(t.found)}`,owner:`maintenance`,urgent:!0,rank:1,refs:[n]});else if(t.status===`Drifting`){let a=t.drift;r.push({id:n,section:`05`,refs:[`05`],evidence:`statistical`,p:a.p,text:`${t.ch}: ${t.found}`,numbers:R2({perWeek:a.b*7,edge:a.edge,cross:a.cross,lo:a.lo,hi:a.hi??NaN,days:a.days,points:a.n,p:a.p})}),d.has(t)||i.push({text:`${t.ch} offset drifting: check calibration or the process ${a.past?`now`:`before ${B4(a.cross,e.tz)}`}.`,owner:`maintenance`,urgent:a.past||a.cross-e.period.to<30*o6,rank:.5,refs:[n]})}}let m=e=>e.map(e=>e.drift).sort((e,t)=>t.past-+e.past||e.cross-t.cross)[0];for(let t of u){let n=m(t);i.push({text:`${c?`${l(t[0].sid)}: `:``}${P4(t.map(e=>e.key))} drift together against the golden, which points to the process (wear, a setting) rather than to ${t.length} sensors. Check it ${n.past?`now`:`before ${B4(n.cross,e.tz)}`}.`,owner:`maintenance`,urgent:n.past||n.cross-e.period.to<30*o6,rank:.5,refs:t.map(e=>s.get(e))})}let h=n.filter(e=>e.status===`Drifting`).map(e=>e.ch);h.length&&a.push(`Run the report again after checking ${P4(h)} to confirm the ${h.length===1?`offset is`:`offsets are`} gone.`);let g=t=>({cells:[t.ch,t.status,t.found,t.since===null?`–`:B4(t.since,e.tz)],status:t.status===`Replace`?`crit`:`watch`,...s.has(t)?{finding:s.get(t)}:{}}),_=t=>{let n=t=>e.units[t.key]?` ${e.units[t.key]}`:``,r=B4(t[0].step.t,e.tz);return{cells:[`${c?`${l(t[0].sid)} · `:``}${N4(t.length,`channel`)}`,`Watch`,`Offsets against the golden moved on ${r} and stayed there (${t.map(e=>`${e.key} ${k4(e.step.d)}${n(e)}`).join(`, `)}): one change of the process, not ${t.length} sensors.`,r],status:`watch`}},v=n.filter(e=>e.status!==`Healthy`),y=n.length-v.length;v.length&&o.push({kind:`table`,columns:[`Sensor`,`Status`,`What was found`,`Since`],rows:[...v.filter(e=>!p.has(e)).map(g),...f.map(_)],title:`05.1 · Sensors that need a look${y?`; the other ${y} ${y===1?`is`:`are`} healthy`:``}`});let b=n.flatMap(e=>e.drift?[e.drift]:[]).sort((e,t)=>e.cross-t.cross)[0];b&&o.push({kind:`trend`,title:`05.2 · Drift forecast, ${b.ch}: its offset against the golden per ${b.per}, forecast to the band edge`,unit:e.units[b.key]??``,points:b.points,line:b.line,limit:Math.sign(b.b)*b.edge,crossing:b.past?null:{t:b.cross,lo:b.lo,hi:b.hi}});let x=d6(e,t);if(x){let e=`F05-${r.length+1}`;r.push({id:e,section:`05`,refs:[`05`],evidence:`statistical`,p:x.p,text:x.text,numbers:R2({growPerWeek:x.grow??NaN,spreadUp:x.spread??NaN})}),i.push({text:`Inspect the machine for wear: ${I4(x.text)}`,owner:`maintenance`,urgent:!1,rank:.3,refs:[e]})}let S=e=>n.filter(t=>t.status===e).length,C=S(`Watch`)-p.size+f.length,w=u.length===1&&u[0].length===S(`Drifting`),T=[S(`Replace`)?`${N4(S(`Replace`),`sensor`)} to replace`:``,S(`Drifting`)?`${S(`Drifting`)} drifting${w?` together${c?` on ${l(u[0][0].sid)}`:``}`:``}`:``,C?`${C} to watch`:``].filter(Boolean);return{out:{section:{...b4(`05`,n.length?`${T.length?F4(P4(T)):`All ${N4(n.length,`sensor`)} healthy`}${x?`, and signs of machine wear`:``}.`:`No sensor health was measured in this period.`,r,o),subtitle:y4(`Reliability data (ISO 14224 style)`),fold:!0},actions:i,next:a,numbers:{replace:S(`Replace`),drifting:S(`Drifting`),watch:C}},sensors:n,drifts:[...n.filter(e=>e.status===`Drifting`&&!d.has(e)).map(e=>e.drift),...u.map(e=>({...m(e),work:`Check the process${c?` on ${l(e[0].sid)}`:``} (${N4(e.length,`channel`)} drifting together)`}))],wear:x}}var _6=.0027,v6=240,y6=60,b6=new Set([`mean`,`min`,`max`,`first`,`last`]),x6=(e,t)=>e.length<=t?e:Array.from({length:t},(n,r)=>e[Math.round(r*(e.length-1)/(t-1))]);function S6(e,t){let n=e.context,r=new Set([...m6(e),...p6(e)]),i=e=>{let t=e.lastIndexOf(`:`),i=e.slice(0,t),a=T3(n?.channels[i]);return t>0&&b6.has(e.slice(t+1))&&!r.has(i)&&a!==`setting`&&a!==`ignore`&&a!==`energy`},a=e.streams.length>1,o=[];for(let[e,n]of z2(t,e=>e.c.streamId)){let t=n.map(e=>e.c).sort((e,t)=>e.tstart-t.tstart);for(let n of[...new Set(t.flatMap(e=>Object.keys(e.kpis)))].filter(i)){let r=t.flatMap(e=>{let t=e.kpis[n];return H2(t)?[{t:e.tstart,v:t}]:[]});if(r.length<30)continue;let i=r.reduce((e,t)=>e+t.v,0)/r.length,a=r.slice(1).reduce((e,t,n)=>e+Math.abs(t.v-r[n].v),0)/(r.length-1)/1.128;if(!(a>0))continue;let s=i+3*a,c=i-3*a,l=r.map(e=>({...e,out:e.v>s||e.v<c})),u=l.filter(e=>e.out).length;u>=1&&u>2*.0027*r.length&&o.push({key:n,sid:e,n:r.length,out:u,mean:i,ucl:s,lcl:c,pts:l})}}if(!o.length)return null;o.sort((e,t)=>t.out/t.n-e.out/e.n||t.out-e.out);let s=t=>`${J4(t.key)}${a?` on ${e.streams.find(e=>e.id===t.sid)?.name??`one stream`}`:``}`,c=t=>{let n=e.units[t.key.slice(0,t.key.lastIndexOf(`:`))];return n?` ${n}`:``},l=o[0],u=o.slice(0,3),d=e=>`F04-S${e+1}`,f=l.pts.length<=v6?l.pts:x6(l.pts,v6-y6),p=new Set(f),m=l.pts.length<=v6?[]:x6(l.pts.filter(e=>e.out&&!p.has(e)),y6);return{charts:[{kind:`control`,title:`04.3 · Control chart, ${s(l)}: each batch against the limits of its own variation (mean ± 3σ)`,unit:c(l).trim(),mean:l.mean,ucl:l.ucl,lcl:l.lcl,n:l.n,outside:l.out,points:[...f,...m].sort((e,t)=>e.t-t.t).map(e=>({t:e.t,v:e.v,...e.out?{out:!0}:{}}))}],findings:u.map((t,n)=>({id:d(n),section:`04`,refs:[`04`],evidence:`measured`,p:null,numbers:{outside:t.out,n:t.n,mean:t.mean,ucl:t.ucl,lcl:t.lcl},text:`${s(t)}: ${N4(t.out,`batch`,`batches`)} of ${t.n.toLocaleString(`en-GB`)} (${S4(100*t.out/t.n)}) outside its control limits, ${w4(t.lcl)} to ${w4(t.ucl)}${c(t)}, the first on ${B4(t.pts.find(e=>e.out).t,e.tz)}. The process moved; with no specification limits, nothing says these batches are bad.`})),actions:[{text:`Find what moved ${s(l)}: ${N4(l.out,`batch`,`batches`)} outside its control limits. Add its specification limits in Process context to know which batches are bad.`,owner:`quality`,urgent:!1,rank:Math.min(1,l.out/l.n),refs:[d(0)]}],notes:[],next:[]}}function C6(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].c.tstart<t?n=i+1:r=i}return n}function w6(e,t){let n=W3(e.context??w3()),r=e.tz,{from:i,to:a}=e.period,o=Object.keys(n.channels).filter(e=>T3(n.channels[e])===`setting`),s=(e.goldenChanges??[]).filter(e=>e.t>=i&&e.t<a);if(!o.length&&!s.length)return{section:`08`,needs:`Mark which channels are adjustable settings in Process context to see their changes.`};let c=e.streams.length>1,l=t=>e.streams.find(e=>e.id===t)?.name??t,u=(e,t)=>c?`${l(e)} · ${t}`:t,d=[];for(let[t,n]of z2(e.recordings.filter(e=>e.health).sort((e,t)=>e.t0-t.t0),e=>e.streamId))for(let e of o){let r=n.flatMap(t=>t.health.channels[e]?[t.health.channels[e]]:[]),o=r.flatMap(e=>e.flats).sort((e,t)=>e.t0-t.t0),s=Math.max(3*K2(r.map(e=>e.noise)),1e-9);o.forEach((n,r)=>{let c=o[r-1];c&&Math.abs(n.value-c.value)>s&&n.t0>=i&&n.t0<a&&d.push({sid:t,ch:u(t,e),t:n.t0,a:c.value,b:n.value})})}if(!d.length&&!s.length)return null;let f=new Map([...z2(t,e=>e.c.streamId)].map(([e,t])=>[e,t.slice().sort((e,t)=>e.c.tstart-t.c.tstart)])),p=d.map(t=>{let n=f.get(t.sid)??[],r=C6(n,t.t),i=n.slice(Math.max(0,r-20),r).map(e=>e.c.value),a=n.slice(r,r+20).map(e=>e.c.value),o=i.length>=5&&a.length>=5,s=K2(i),c=K2(a),l=o?Z2(a,i):{p:1,effect:.5};return{...t,enough:o,mb:s,ma:c,p:l.p,worse:e.value.better===`min`?l.effect>.5:l.effect<.5}}),m=o4(p.map(e=>e.enough?e.p:1),N2),h=[],g=[],_=new Map,v=e.value.label;p.forEach((e,t)=>{if(!e.enough||!m[t])return;let n=`F08-${h.length+1}`,i=V4(e.t,r),[a,o]=E4(e.a,e.b),[s,c]=E4(e.mb,e.ma);_.set(t,n),h.push({id:n,section:`08`,refs:[`08`],evidence:`statistical`,p:e.p,numbers:R2({from:e.a,to:e.b,before:e.mb,after:e.ma,p:e.p}),text:`${e.ch} was changed from ${a} to ${o} on ${i}; ${s===c?`${v} moved ${e.worse?`worse`:`better`} afterwards (median ${s} both times)`:`${v} went from ${s} to ${c} afterwards (${e.worse?`worse`:`better`})`}.`}),e.worse&&g.push({text:`Review the ${e.ch} change of ${i}: ${v} has been worse since.`,owner:`production`,urgent:!1,rank:Math.min(1,Math.abs(e.ma-e.mb)/(Math.abs(e.mb)||1)),refs:[n]})});let y=[...p.map((e,t)=>{let[n,i]=E4(e.a,e.b);return{t:e.t,row:{cells:[V4(e.t,r),e.ch,n,i,e.enough?`${k4(e.ma-e.mb)} (${Y4(e.p)})`:`Too few batches to tell`],..._.has(t)?{finding:_.get(t),...e.worse?{status:`watch`}:{}}:{}}}}),...s.map(e=>({t:e.t,row:{cells:[V4(e.t,r),c?`${l(e.streamId)} · Golden`:`Golden`,`–`,e.label,`–`]}}))].sort((e,t)=>e.t-t.t).map(e=>e.row),b=s.map(e=>`The golden changed on ${V4(e.t,r)}; every batch in this report is judged against the current one.`);return{section:b4(`08`,h.length?`${N4(d.length,`setting change`)} in the period; ${h.length} ${h.length===1?`was`:`were`} followed by a different ${v}.`:d.length?`${N4(d.length,`setting change`)} in the period, none followed by a clear difference in ${v}.`:b[0],h,[{kind:`table`,title:`08.1 · Changes of settings`,columns:[`When`,`Setting`,`From`,`To`,`Effect on ${v}`],rows:y}],b),actions:g,next:[],numbers:{changes:d.length,goldens:s.length}}}function T6(e,t,n=h6(e,t)){let r=new Map([...z2(t,e=>e.c.streamId)].map(([e,t])=>[e,t.slice().sort((e,t)=>e.c.tstart-t.c.tstart)])),i=(e,t,n)=>{let i=r.get(e)??[],a=C6(i,n);for(;a<i.length&&i[a].c.tstart===n;)a++;return i.slice(C6(i,t),a)},a=z2(n.filter(e=>e.status===`Drifting`),e=>e.sid),o=e=>e.status===`Drifting`&&(a.get(e.sid)?.length??0)>1,s=n.filter(t=>e.goldens.some(e=>e.streamId===t.sid&&t.key in e.edges)&&!o(t)).flatMap(t=>(t.status===`Replace`?t.stuck.map(e=>({...e,stuck:!0})):t.drift?.past?[{t0:Math.max(t.drift.cross,e.period.from),t1:e.period.to,stuck:!1}]:[]).map(e=>({s:t,...e,xs:i(t.sid,e.t0,e.t1)}))).filter(e=>e.xs.length).sort((e,t)=>t.xs.length-e.xs.length||e.t0-t.t0).slice(0,10);if(!s.length)return null;let c=e.tz,l=e=>`F04-C${e+1}`;return{charts:[{kind:`table`,title:`04.2 · Batches made while a sensor was failing`,columns:[`Sensor`,`From`,`To`,`Batches`,`Of them off-golden`],rows:s.map((e,t)=>({cells:[e.s.ch,V4(e.t0,c),V4(e.xs[e.xs.length-1].c.tstart,c),String(e.xs.length),String(e.xs.filter(e=>e.level===`off`).length)],status:e.stuck?`crit`:`watch`,finding:l(t)}))}],findings:s.map((e,t)=>({id:l(t),section:`04`,refs:[`04`,`05`],evidence:`measured`,p:null,numbers:{batches:e.xs.length,off:e.xs.filter(e=>e.level===`off`).length,seconds:e.xs.reduce((e,t)=>e+Math.max(0,(t.c.tend??t.c.tstart)-t.c.tstart),0)},text:`${N4(e.xs.length,`batch`,`batches`)} ${e.xs.length===1?`was`:`were`} made while ${e.s.ch} `+(e.stuck?`was stuck (from ${U4(e.t0,e.t1,c,` to `)}): their ${e.s.ch} readings can't be trusted. Check them before they ship.`:`read beyond its band (the sensor or the process), from ${U4(e.t0,e.t1,c,` to `)}. Check them before they ship.`)})),actions:s.map((e,t)=>({text:`Check the ${N4(e.xs.length,`batch`,`batches`)} made while ${e.s.ch} ${e.stuck?`was stuck`:`read beyond its band`} before they ship.`,owner:`quality`,urgent:e.stuck,rank:1,refs:[l(t)]})),notes:[],next:[]}}var E6={Wh:.001,kWh:1,MWh:1e3},D6=`Scope 2, location-based, factor entered by you`;function O6(e,t){let n=E6[(e.context?.channels[t]?.unit??``).trim()],r=n?e.recordings.flatMap(e=>{let n=e.health?.channels[t];return n?.counter?[n]:[]}):[];return r.length?r.reduce((e,t)=>e+(t.max-t.min)*n,0):null}function k6(e,t){let n=e.context,r=E3(n);if(!n||!r)return null;let i=t.filter(e=>H2(e.c.kwh)&&e.c.kwh>=0);if(i.length<5)return{section:`09`,needs:`09 · ${r} has ${i.length?`energy in only ${i.length} of`:`no energy in`} this period’s batches: check it is recorded and its unit in Process context is kW, W, MW, kWh, Wh or MWh.`};let a=n.costs.kwh,o=n.costs.currency,s=n.costs.co2,c=i.map(e=>e.c.kwh),l=K2(c),u=c.reduce((e,t)=>e+t,0),d=O6(e,r),f=d!==null&&d>=u?d:u,p=[],m=[],h=(e.previous?.cycles??[]).map(e=>e.kwh).filter(e=>H2(e)&&e>=0),g=h.length>=5?K2(h):NaN,[_,v]=E4(l,g),y=(l-g)/g*100,b=Math.abs(y)>=10?Math.round(y):+y.toFixed(1),x=Number.isFinite(g)?_===v||!b?`, as the period before`:`, against ${v} the period before (${k4(b)}%)`:``,S=[...a===null?[]:[C4(l*a,o)],...s===null?[]:[`${w4(l*s)} kg CO₂ (${D6})`]];p.push({id:`F09-1`,section:`09`,refs:[`09`],evidence:`measured`,p:null,numbers:R2({kwh:l,before:g,cost:a===null?NaN:l*a,co2:s===null?NaN:l*s,total:f,inBatches:u}),text:`A batch uses ${_} kWh (median)${x}${S.length?`: ${S.join(` and `)}`:``}; ${w4(f)} kWh in the period${f>u?`, ${w4(u)} of them while a batch ran`:``}.`});let C=i.filter(e=>e.level===`off`).map(e=>e.c.kwh),w=i.filter(e=>e.level!==`off`).map(e=>e.c.kwh),T=!1,E=[],D=e=>a===null?``:` (${C4(e*a,o)})`;if(f>u&&E.push({kind:`bars`,title:`09.1 · Where the period’s energy goes${a===null?``:`, and what it costs`}`,max:Math.max(u,f-u),rows:[{label:`While a batch runs`,kwh:u},{label:`Between batches, in stops and breaks`,kwh:f-u}].sort((e,t)=>t.kwh-e.kwh).map(e=>({label:e.label,value:e.kwh,text:`${w4(e.kwh)} kWh${D(e.kwh)}`,tip:`${e.label}: ${x4(e.kwh/f)} of the period’s energy`}))}),C.length>=5&&w.length>=5){let e=K2(C),t=K2(w),n=Z2(C,w);if(n.p<.01&&e>t&&t>0){T=!0;let r=(e-t)*C.length,[s,c]=E4(e,t);E.push({kind:`bars`,title:`09.2 · Energy per batch: off-golden batches against the rest (median)`,max:e,rows:[{label:`Off-golden batches`,value:e,text:`${s} kWh`,tip:`Off-golden batches: ${s} kWh a batch (median of ${C.length.toLocaleString(`en-GB`)})`},{label:`At golden level or better`,value:t,text:`${c} kWh`,muted:!0,tip:`At golden level or better: ${c} kWh a batch (median of ${w.length.toLocaleString(`en-GB`)})`}]}),p.push({id:`F09-2`,section:`09`,refs:[`09`],evidence:`statistical`,p:n.p,numbers:R2({off:e,rest:t,extra:r,p:n.p}),text:`Off-golden batches use ${S4((e-t)/t*100)} more energy than the rest: ${w4(r)} kWh${a===null?``:`, up to ${C4(r*a,o)}`}, in the period.`}),m.push({text:`Bring off-golden batches to golden level (see 02) to save up to ${w4(r)} kWh${a===null?``:` (${C4(r*a,o)})`} in a period like this one.`,owner:`production`,urgent:!1,rank:(e-t)/t*(C.length/i.length),refs:[`F09-2`]})}}return{section:{...b4(`09`,`${a===null?`${w4(f)} kWh`:`${C4(f*a,o)} of energy`} in the period${T?`; off-golden batches use more`:``}.`,p,E),subtitle:y4(`Energy review inputs (ISO 50001)`),fold:!0},actions:m,next:[],numbers:{kwh:l}}}var A6=1800,j6=2400,M6=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],N6=[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`],P6=e=>`${String(e%24).padStart(2,`0`)}:00`,F6=(e,t)=>e.c.z?.[t.ch]?.[t.piece];function I6(e){let t=new Map;for(let n of e)for(let[e,r]of Object.entries(n.c.z))for(let n of Object.keys(r)){let r=`${e}\u0000${n}`;t.set(r,(t.get(r)??0)+1)}let n=[...t].filter(([,t])=>t>=.8*e.length).map(([e])=>e.split(`\0`)).sort(),r=new Set(n.filter(([,e])=>e!==`Cycle`).map(([e])=>e));return n.filter(([e,t])=>t!==`Cycle`||!r.has(e)).map(([e,t])=>({ch:e,piece:t,label:t===`Cycle`?e:`${e} · ${t}`}))}function L6(e,t){let n=u4(e,t);if(!n)return null;let r=n.shares.map(e=>Math.max(0,e)),i=r.reduce((e,t)=>e+t,0);return{shares:r.map(e=>i>0?e/i*n.r2:0),r2:n.r2}}function R6(e,t){let n=[],r=[],i=[],a=[],o=new Map,s=(e,t)=>{let r=`F02-${n.length+1}`;return n.push({id:r,section:`02`,refs:[`02`],...e}),o.set(r,t),r},c=t.filter(e=>e.level===`off`),l=e=>e.filter(e=>e.level===`off`).length,u=t.filter(e=>e.c.z),d=u.filter(e=>e.level===`off`),f=u.filter(e=>e.level!==`off`),p=null;if(d.length>=5&&f.length>=5){let e=I6(u).map(e=>{let t=u.filter(t=>H2(F6(t,e)));return{f:e,mw:Z2(d.map(t=>F6(t,e)).filter(H2),f.map(t=>F6(t,e)).filter(H2)),r:s4(t.map(t=>F6(t,e)),t.map(e=>e.gap))}}),t=o4(e.map(e=>e.mw.p),N2),n=e.filter((e,n)=>t[n]&&e.mw.effect>.5&&e.r>0).sort((e,t)=>t.r-e.r).slice(0,8),o=u.filter(e=>n.every(t=>H2(F6(e,t.f)))),c=o.map(e=>n.map(t=>F6(e,t.f))),l=o.map(e=>e.gap),m=n.length?L6(c,l):null;if(m){let e=m.shares.map((e,t)=>t).sort((e,t)=>m.shares[t]-m.shares[e]),t=e[0],u=n[t],f=p4(o.length,e=>L6(e.map(e=>c[e]),e.map(e=>l[e]))?.shares[t]??NaN),h=e.filter(e=>m.shares[e]>=.01),g=Math.max(0,1-m.r2);p={label:u.f.label,share:m.shares[t]},a.push({kind:`bars`,title:`02.1 · What goes with batches missing the golden: how much of the difference between batches each one explains (${N4(o.length,`batch`,`batches`)} measured, ${d.length.toLocaleString(`en-GB`)} off-golden)`,max:Math.max(g,...h.map(e=>m.shares[e]))*1.1,rows:[...h.map(e=>({label:n[e].f.label,value:m.shares[e],text:x4(m.shares[e]),tip:`${n[e].f.label} goes with ${x4(m.shares[e])} of the difference in how far batches are from the golden`})),{label:`Not explained by the recorded channels`,value:g,text:x4(g),muted:!0,tip:`Goes with none of the channels recorded: something else changes between batches.`}]});let _=d.reduce((e,t)=>t.gap>e.gap?t:e,d[0]),v=s({focus:{ch:u.f.ch,piece:u.f.piece},..._?{batch:{streamId:_.c.streamId,cycleId:_.c.id}}:{},text:`${u.f.label} goes with ${x4(p.share)} of the difference in how far batches are from the golden${h.length>1?`; the ${h.length} differences together go with ${x4(m.r2)}`:``}.`,evidence:`correlation`,p:u.mw.p,numbers:R2({share:p.share,lo:f.lo,hi:f.hi,r2:m.r2,r:u.r,p:u.mw.p})},p.share);for(let e of h.slice(0,3)){let t=n[e].f;r.push({text:`Test bringing ${t.ch}${t.piece===`Cycle`?``:` in ${t.piece}`} back to the golden: it goes with ${x4(m.shares[e])} of the difference in how far batches are from the golden.`,owner:`production`,urgent:!1,rank:m.shares[e],refs:[v]})}g>=.2&&i.push(`${x4(g)} of the difference in how far batches are from the golden goes with none of the recorded channels. Record what else changes between batches (material lot, ambient temperature, settings) as channels.`)}else i.push(`No recorded channel goes with the batches that miss the golden. Record what else changes between batches (material lot, ambient temperature, settings) as channels.`)}let m=new Set;for(let e of z2(t,e=>e.c.streamId).values()){let t=-1/0;e.forEach((n,r)=>{let i=e[r-1];i&&n.c.tstart-(i.c.tend??i.c.tstart)>1800&&(t=n.c.tstart),n.c.tstart-t<2400&&m.add(n.c.id)})}let h=t.filter(e=>m.has(e.c.id)),g=t.filter(e=>!m.has(e.c.id));if(h.length>=5&&g.length>=5){let e=a4(l(h),h.length,l(g),g.length);if(e.p<.01&&e.p1>e.p2){let n=s({text:`Off-golden share is ${x4(e.p1)} in the first ${j6/60} minutes after a stop of more than ${A6/60} minutes, against ${x4(e.p2)} the rest of the time.`,evidence:`statistical`,p:e.p,numbers:R2({warm:e.p1,rest:e.p2,p:e.p,batches:h.length})},(e.p1-e.p2)*(h.length/t.length));r.push({text:`Warm the line up after stops longer than ${A6/60} minutes: the first ${j6/60} minutes after a stop run ${x4(e.p1)} off-golden against ${x4(e.p2)}.`,owner:`production`,urgent:!1,rank:(e.p1-e.p2)*(h.length/t.length),refs:[n]})}}let _=(e,n,r=t)=>{let i=z2(r,e),a=l(r);if(i.size<2)return null;let o=[...i].filter(([,e])=>e.length>=n&&r.length-e.length>=5).map(([e,t])=>({k:e,n:t.length,t:a4(l(t),t.length,a-l(t),r.length-t.length)})),s=o4(o.map(e=>e.t.p),N2),c=null;return o.forEach((e,t)=>{s[t]&&e.t.p1-e.t.p2>=.05&&(!c||e.t.p1-e.t.p2>c.t.p1-c.t.p2)&&(c=e)}),c},v=_(e=>e.c.streamId,5);v&&s({text:`${e.streams.find(e=>e.id===v.k)?.name??`One stream`} runs ${x4(v.t.p1)} off-golden against ${x4(v.t.p2)} on the other streams.`,evidence:`statistical`,p:v.t.p,numbers:R2({share:v.t.p1,others:v.t.p2,p:v.t.p})},(v.t.p1-v.t.p2)*(v.n/t.length));let y=_(e=>e.c.recordingId,10);y&&s({text:`Recording ${e.recordings.find(e=>e.id===y.k)?.name??`one file`} runs ${x4(y.t.p1)} off-golden against ${x4(y.t.p2)} in the rest of the period.`,evidence:`statistical`,p:y.t.p,numbers:R2({share:y.t.p1,others:y.t.p2,p:y.t.p})},(y.t.p1-y.t.p2)*(y.n/t.length));let b=null;if(t.length>=5){let n=t[0].c.tstart,r=B2(t.map(e=>({t:e.c.tstart,v:e.gap})),n),i=r.length>=7?c4(r.map(e=>(e.t-n)/86400),r.map(e=>e.v)):null;if(i&&i.p<.01&&i.b!==0){let a=j4(e),o=a?` ${a}`:``,c=r[r.length-1].t;s({text:`The gap to the golden ${i.b>0?`grows`:`shrinks`} by ${w4(Math.abs(i.b)*7)}${o} a week since ${B4(n,e.tz)}.`,evidence:`statistical`,p:i.p,numbers:R2({perWeek:i.b*7,days:i.n,p:i.p})},Math.min(1,Math.abs(i.b*(c-n)/86400)/(t.reduce((e,t)=>e+Math.abs(t.gap),0)/t.length||1))),b={kind:`trend`,title:`02.3 · Gap to the golden per day, with its trend`,unit:o.trim(),points:r,line:{t0:n,v0:i.a,t1:c,v1:i.a+i.b*(c-n)/86400},limit:null,crossing:null}}}let x=new Map,S=new Map(t.map(t=>{let n=Math.floor(t.c.tstart/900),r=x.get(n);return r||x.set(n,r=G4(n*900,e.tz)),[t.c.id,r]})),C=_(e=>String(S.get(e.c.id).hour),5),w=_(e=>String(S.get(e.c.id).day),5),T=e.context?.hideShifts?[]:e.context?.shifts??[],E=new Map(T.length?t.map(t=>[t.c.id,V3(t.c.tstart,T,e.tz)]):[]),D=T.length?_(e=>E.get(e.c.id),5,t.filter(e=>E.get(e.c.id)!==null)):null,O=[...C?[{w:C,when:`started between ${P6(+C.k)} and ${P6(+C.k+1)}`,other:`at other hours`,look:`Find what changes around ${P6(+C.k)} (a shift change, a start-up, a material change)`}]:[],...w?[{w,when:`on ${N6[+w.k]}s`,other:`on other days`,look:`Find what is different on ${N6[+w.k]}s (crew, material, maintenance)`}]:[],...D?[{w:D,when:`on the ${D.k} shift`,other:`on the other shifts`,look:`Find what the ${D.k} shift does differently (crew, set-up, material)`}]:[]];for(let{w:e,when:n,other:i,look:a}of O){let o=(e.t.p1-e.t.p2)*(e.n/t.length),c=s({text:`Batches ${n} run ${x4(e.t.p1)} off-golden against ${x4(e.t.p2)} ${i}.`,evidence:`statistical`,p:e.t.p,numbers:R2({share:e.t.p1,others:e.t.p2,p:e.t.p})},o);r.push({text:`${a}: batches then run ${x4(e.t.p1)} off-golden against ${x4(e.t.p2)}.`,owner:`production`,urgent:!1,rank:o,refs:[c]})}if(O.length){let e=M6.map(()=>Array(24).fill(0)),n=M6.map(()=>Array(24).fill(0));for(let r of t){let{day:t,hour:i}=S.get(r.c.id);e[t][i]++,r.level===`off`&&n[t][i]++}a.push({kind:`heat`,title:`02.2 · Off-golden share by hour and weekday. Stronger colour is worse; hours with fewer than 5 batches are left empty.`,rows:M6,cols:Array.from({length:24},(e,t)=>String(t).padStart(2,`0`)),cells:e.map((e,t)=>e.map((e,r)=>e>=5?n[t][r]/e:null)),legend:`off-golden`})}b&&a.push(b);let k=t.length?c.length/t.length:0,A=t.length?c.length?p?`${x4(k)} of batches miss the golden. ${p.label} goes with most of the difference between them and the golden.`:`${x4(k)} of batches miss the golden; no recorded channel goes with the gap yet.`:`Every batch is at golden level or better.`:`No batches with a value to compare against a golden in this period.`;return n.sort((e,t)=>o.get(t.id)-o.get(e.id)),{section:{...b4(`02`,A,n,a),fold:!0},actions:r,next:i,numbers:{off:c.length,share:k}}}function z6(e,t){let n=(e.context?.lines??[]).filter(e=>e.streams.length);if(n.length<2)return null;let r=new Map(n.flatMap(e=>e.streams.map(t=>[t,e.name]))),i=z2(t.filter(e=>r.has(e.c.streamId)),e=>r.get(e.c.streamId)),a=e=>({section:b4(`10`,e,[],[]),actions:[],next:[],numbers:{}});if(i.size<2)return a(`${i.size?`Only one line has`:`No line has`} batches in this report: tick the files of the other lines to compare them.`);let o=[...i.values()].flat(),s=o.filter(e=>e.level===`off`).length,c=[...i].map(([e,t])=>{let n=t.filter(e=>e.level===`off`).length;return{name:e,xs:t,better:t.filter(e=>e.level===`better`).length,t:a4(n,t.length,s-n,o.length-t.length)}}),l=o4(c.map(e=>e.t.p),N2),u=e=>e.t.p1>e.t.p2,d=c.filter((e,t)=>l[t]&&e.t.p1!==e.t.p2&&e.xs.length>=5&&o.length-e.xs.length>=5).sort((e,t)=>Number(u(t))-Number(u(e))||Math.abs(t.t.p1-t.t.p2)-Math.abs(e.t.p1-e.t.p2)).slice(0,i.size===2?1:void 0);if(!d.length)return a(`The lines run alike: none misses the golden more often than the others.`);let f=[],p=[],m=new Map;for(let e of d){let t=`F10-${f.length+1}`;m.set(e.name,t),f.push({id:t,section:`10`,refs:[`10`],evidence:`statistical`,p:e.t.p,numbers:R2({share:e.t.p1,others:e.t.p2,p:e.t.p,batches:e.xs.length}),text:`${e.name} runs ${x4(e.t.p1)} off-golden against ${x4(e.t.p2)} on the other lines.`}),u(e)&&p.push({text:`Find what ${e.name} does differently from the other lines: it runs ${x4(e.t.p1)} off-golden against ${x4(e.t.p2)}.`,owner:`production`,urgent:!1,rank:(e.t.p1-e.t.p2)*(e.xs.length/o.length),refs:[t]})}let h=[{kind:`table`,title:`10.1 · The lines side by side`,columns:[`Line`,`Batches`,`At golden level or better`,`Better than the golden`],rows:c.map(e=>{let t=m.get(e.name);return{cells:[e.name,e.xs.length.toLocaleString(`en-GB`),x4(1-e.t.p1),x4(e.better/e.xs.length)],...t?{finding:t,status:u(e)?`crit`:`ok`}:{}}})}],g=d.filter(u),_=e=>P4(e.slice(0,2).map(e=>e.name))+(e.length>2?` and ${N4(e.length-2,`more line`)}`:``);return{section:b4(`10`,g.length?`${_(g)} ${g.length>1?`miss`:`misses`} the golden more often than the other lines.`:`${_(d)} ${d.length>1?`miss`:`misses`} the golden less often than the other lines.`,f,h),actions:p,next:[],numbers:{lines:i.size}}}function B6(e,t){let n=W3(e.context??w3()).costs,r=n.lineHour,i=n.currency,a=r!==null,o=e=>a?e/3600*r:e/3600,s=e=>e.s>=60&&(!a||o(e.s)>=1),c=new Map,l=t.time.filter(e=>!e.bad&&s(e)).map(e=>{let t={label:e.label,value:o(e.s),owner:e.owner,ref:e.ref,amount:a?C4(o(e.s),i):A4(e.s),detail:a?`${A4(e.s)} of line time`:`of line time`};return c.set(t,e.s),t}),u=t.energyKwh!==null&&t.energyKwh>0&&n.kwh!==null?t.energyKwh*n.kwh:0;u>=1&&l.push({label:`Extra energy of off-golden batches`,value:a?u:null,owner:`Production`,ref:`09`,amount:C4(u,i),detail:`${w4(t.energyKwh)} kWh more than batches at golden level`});let d=n.scrap,f=d===null?``:`${C4(d,i)} a scrapped batch`,p=t.scrap&&d!==null&&t.scrap.batches*d>=1?{...t.scrap,money:t.scrap.batches*d}:null,m=t.time.filter(e=>e.bad&&s(e)).reduce((e,t)=>e+t.s,0),h=p&&!p.assumed?p.money:0;if(m||h){let e=t.scrap&&!t.scrap.assumed?N4(t.scrap.batches,`batch`,`batches`):`Batches`,n={label:`Bad parts`,value:a?o(m)+h:m?o(m):null,owner:`Quality`,ref:`04`,amount:a?C4(o(m)+h,i):m?A4(m):C4(h,i),detail:`${e} outside their limits or flagged bad: ${[m?`${A4(m)} of line time`:``,h?`${C4(h,i)} scrapped material`:``].filter(Boolean).join(` + `)}`};l.push(n),c.set(n,m)}let g=l.reduce((e,t)=>e+(t.value??0),0),_=l.filter(e=>!a||e.value>=.005*g).sort((e,t)=>(t.value??-1)-(e.value??-1)),v=_.reduce((e,t)=>e+(c.get(t)??0),0);if(p?.assumed&&_.push({label:`Off-golden batches, if scrapped`,value:null,owner:`Quality`,ref:`02`,assumed:!0,amount:`up to ${C4(p.money,i)}`,detail:`${N4(p.batches,`off-golden batch`,`off-golden batches`)} at ${f}; no specification limits say which are scrap`}),t.review&&t.review.batches>0){let e=N4(t.review.batches,`batch`,`batches`);_.push(d===null?{label:`Batches to check before they ship`,value:o(t.review.s),owner:`Quality`,ref:`04`,atRisk:!0,amount:a?`up to ${C4(o(t.review.s),i)}`:e,detail:`${a?`${e}, `:``}${A4(t.review.s)} of production at risk: made while a sensor was failing`}:{label:`Batches to check before they ship`,value:a?t.review.batches*d:null,owner:`Quality`,ref:`04`,atRisk:!0,amount:`up to ${C4(t.review.batches*d,i)}`,detail:`${e} at ${f}, at risk: made while a sensor was failing`})}if(!_.length)return null;let y=_.reduce((e,t)=>e+(t.atRisk||t.assumed?0:t.value??0),0),b=_.some(e=>!e.atRisk&&!e.assumed),x=d===null&&t.scrap&&!t.scrap.assumed?t.scrap.batches:0,S=a?x?`Add the cost of a scrapped batch to see what the ${N4(x,`batch`,`batches`)} off specification cost`:null:`Add the cost of an hour of line time to see this in money`;return{kind:`losses`,unit:a?`money`:`hours`,title:`00.1 · Where the ${a?`money`:`time`} goes`,rows:_,total:b?a?`Up to ${C4(y,i)}`:v?A4(v):_[0].amount:`Nothing lost`,totalNote:b?a?`to recover in this period${v?`: ${A4(v)} of line time`:``}`:`of line time to recover in this period`:`against the golden in this period`,...S?{hint:S}:{}}}var V6=86400;function H6(e,t,n){if(!t.length&&!n)return null;let r=W3(e.context??w3()),i=e.tz,a=e.period.to,o=r.stops.length?U3(r,i,a,a+90*V6).map(e=>e.t0).filter(e=>e>a).sort((e,t)=>e-t):null,s=e=>{if(!o)return`No planned stop set`;let t=e===null?o[0]:o.filter(t=>t<e).pop();return t===void 0?`None before it`:K4(t,i)},c=[...t.map(e=>{let t=e.past||e.lo<=a;return{work:e.work??`Recalibrate ${e.ch}`,by:t?null:e.lo,now:t}}),...n?[{work:`Inspect the machine for wear (${n.grow===null?`spread of ${e.value.label} up ${x4(n.spread)}`:`cycle time ${k4(n.grow)}% a week`})`,by:null,now:!1}]:[]].sort((e,t)=>t.now-+e.now||(e.by??1/0)-(t.by??1/0)),l=c[0],u=c.find(e=>e.by!==null);return{charts:[{kind:`table`,title:`05.5 · Maintenance to plan`,columns:[`Work`,`By`,`Next planned stop before it`],rows:c.map(e=>({cells:[e.work,e.now?`Now`:e.by===null?`–`:B4(e.by,i),s(e.by)],...e.now?{status:`crit`}:{}}))}],findings:[{id:`F05-M1`,section:`05`,refs:[`05`],evidence:`measured`,p:null,numbers:{jobs:c.length,...u&&!l.now?{first:u.by}:{}},text:`Plan ${N4(c.length,`maintenance job`)}${l.now?`: the first now`:u?`: the first by ${B4(u.by,i)}`:``}.`}],actions:[],notes:[],next:o?[]:[`Add planned stops in Process context to place maintenance in them.`]}}var U6=()=>({findings:[],charts:[],notes:[],actions:[],next:[]});function W6(e,t){let n=[...e.charts,...t.flatMap(e=>e.charts)],r=[...e.findings,...t.flatMap(e=>e.findings)],i=e=>`title`in e?e.title:``;return{...e,findings:r,notes:[...e.notes,...t.flatMap(e=>e.notes)],...r.length>3?{shown:e.shown??3}:{},charts:n.map((e,t)=>({c:e,i:t})).sort((e,t)=>i(e.c).localeCompare(i(t.c))||e.i-t.i).map(e=>e.c)}}var G6=7200,K6=e=>e.reduce((e,t)=>e+t.t1-t.t0,0),q6=(e,t)=>e.flatMap(e=>t.map(t=>({t0:Math.max(e.t0,t.t0),t1:Math.min(e.t1,t.t1)}))).filter(e=>e.t1>e.t0);function J6(e){let t=[];for(let n of[...e].sort((e,t)=>e.t0-t.t0)){let e=t[t.length-1];e&&n.t0<=e.t1?e.t1=Math.max(e.t1,n.t1):t.push({t0:n.t0,t1:n.t1})}return t}function Y6(e,t){for(let n of t)e=e.flatMap(e=>[{t0:e.t0,t1:Math.min(e.t1,n.t0)},{t0:Math.max(e.t0,n.t1),t1:e.t1}]).filter(e=>e.t1>e.t0);return e}function X6(e,t,n,r){let i=q6([{t0:n,t1:r}],[{t0:e.period.from,t1:e.period.to}]);return i.length?(t.shifts.length&&(i=q6(i,J6(U3({...t,stops:t.shifts.map(e=>({name:e.name,from:e.start,to:e.end}))},e.tz,n,r)))),t.stops.length?Y6(i,U3(t,e.tz,n,r)):i):i}function Z6(e){let t=[...e].sort((e,t)=>e.tstart-t.tstart),n=t.slice(1).map((e,n)=>e.tstart-(t[n].tend??t[n].tstart)).filter(e=>e>=0);return Math.max(300,n.length?5*K2(n):0)}function Q6(e){return $6(e).stops}function $6(e){let t=W3(e.context??w3()),n=[],r=0,i=z2(e.cycles,e=>e.recordingId),a=z2(e.covered??[],e=>e.streamId);for(let[o,s]of z2([...e.recordings].sort((e,t)=>e.t0-t.t0),e=>e.streamId)){let c=Z6(s.flatMap(e=>i.get(e.id)??[])),l=[],u=-1/0;for(let n of[...s,...a.get(o)??[]].sort((e,t)=>e.t0-t.t0))!n.continues&&n.t0-u>=300&&u>-1/0&&(!t.shifts.length&&n.t0-u>7200?K6(X6(e,t,u,n.t0))>=300&&r++:l.push({streamId:o,t0:u,t1:n.t0,kind:`no_data`,unit:null})),u=Math.max(u,n.t1);if(s.some(e=>i.has(e.id))){let e=s.filter(e=>i.has(e.id)||!(e.unread||e.failed)),t=e.flatMap(e=>i.get(e.id)??[]).sort((e,t)=>e.tstart-t.tstart),n=0,r=-1/0,a=[];for(let t of[...e].sort((e,t)=>e.t0-t.t0)){let e=a[a.length-1];e&&t.t0-e.t1<300?e.t1=Math.max(e.t1,t.t1):a.push({t0:t.t0,t1:t.t1})}for(let e of a){let i=Math.max(e.t0,Math.min(r,e.t1));for(;n<t.length&&t[n].tstart<e.t1;n++){let e=t[n];e.tstart-i>c&&l.push({streamId:o,t0:i,t1:e.tstart,kind:`no_batches`,unit:null}),i=Math.max(i,e.tend??e.tstart),r=Math.max(r,e.tend??e.tstart)}e.t1-i>c&&l.push({streamId:o,t0:i,t1:e.t1,kind:`no_batches`,unit:null})}}for(let r of l){let i=t.units.find(e=>e.channels.some(e=>s.some(t=>t.health?.channels[e]?.flats.some(e=>Math.abs(e.t0-r.t0)<=60))))?.name??null,a=X6(e,t,r.t0,r.t1),o=K6(a);o>=300&&(r.kind!==`no_batches`||o>c)&&a.forEach((e,t)=>n.push({...r,...e,unit:i,...t?{part:t}:{}}))}}return{stops:n.sort((e,t)=>e.t0-t.t0||e.streamId.localeCompare(t.streamId)),offGaps:r}}function e8(e,t,n=0){let r=n?[`Add the shifts in Process context to count longer gaps as stops.`]:[];if(!t.length)return r.length?{...U6(),next:r}:null;let i=W3(e.context??w3()),a=t=>e.streams.find(e=>e.id===t)?.name??`A stream`,o=n=>e.recordings.filter(e=>e.streamId===n).reduce((t,n)=>t+K6(X6(e,i,n.t0,n.t1)),0)+K6(t.filter(e=>e.streamId===n&&e.kind===`no_data`)),s=e=>{let t=[...new Set(e.map(e=>e.streamId))].reduce((e,t)=>e+o(t),0),n=K6(e),r=Math.max(1,e.filter(e=>!e.part).length);return{n:r,stopped:n,mtbf:(t-n)/r,mttr:n/r,share:t>0?n/t:0}},c=[],l=[...z2(t,e=>e.streamId)].map(([e,t])=>({sid:e,xs:t,...s(t)})).sort((e,t)=>t.stopped-e.stopped);for(let e of l){let t=[...z2(e.xs.filter(e=>e.unit),e=>e.unit)].sort((e,t)=>t[1].length-e[1].length);c.push({id:`F05-S${c.length+1}`,section:`05`,refs:[`05`],evidence:t.length?`correlation`:`measured`,p:null,numbers:{stops:e.n,stoppedS:e.stopped,mtbfS:e.mtbf,mttrS:e.mttr},text:(e.n===1?`${a(e.sid)} stopped once, for ${A4(e.stopped)}.`:`${a(e.sid)} stopped ${M4(e.n)} for ${A4(e.stopped)} in total; it ran ${A4(e.mtbf)} between stops on average and took ${A4(e.mttr)} to restart.`)+(t.length?` ${t[0][1].length} of the stops began when a ${t[0][0]} channel went flat.`:``)})}let u=new Map(l.map((e,t)=>[e.sid,c[t].id])),d=t.some(e=>e.unit),f=d?[...z2(t,e=>e.unit??`No unit found`)].map(([e,t])=>({label:e,xs:t,...s(t)})).sort((e,t)=>t.stopped-e.stopped):l.map(e=>({...e,label:a(e.sid)})),p=[],m=f[0];return m.share>=.2&&p.push({text:`Find why ${m.label} stops: ${N4(m.n,`stop`)} cost ${A4(m.stopped)} this period.`,owner:`maintenance`,urgent:!1,rank:m.share,refs:[...new Set(m.xs.map(e=>u.get(e.streamId)))]}),{findings:c,notes:[],actions:p,charts:[{kind:`table`,title:`05.4 · Stops by ${d?`machine unit`:`stream`}`,columns:[d?`Unit`:`Stream`,`Stops`,`Stopped`,`MTBF`,`MTTR`],rows:f.map(e=>({cells:[e.label,String(e.n),A4(e.stopped),A4(e.mtbf),A4(e.mttr)],...e.share>=.2?{status:`crit`}:{},...d?{}:{finding:u.get(e.xs[0].streamId)}}))}],next:[...!i.units.length&&t.length>=3?[`Add the machine units in Process context to see which unit each stop starts in.`]:[],...r]}}var t8=new Set([`mean`,`min`,`max`,`first`,`last`]),n8=()=>({plan:0,stop:0,ideal:0,n:0,good:0,badIdeal:0}),r8=e=>Math.max(0,e.plan-e.stop),i8=e=>{let t=r8(e),n=e.plan>0?t/e.plan:0,r=t>0?Math.min(1,e.ideal/t):0,i=e.n?e.good/e.n:0;return{A:n,P:r,Q:i,oee:n*r*i}};function a8(e,t){let n=e.context?.idealCycleS;if(n)return new Map(e.streams.map(e=>[e.id,n]));let r=new Map(e.value.key===`duration`?e.goldens.map(e=>[e.streamId,e.value]):[]);for(let[e,n]of z2(t,e=>e.c.streamId)){if(!r.has(e)){let t=n.filter(e=>e.level!==`off`).map(e=>e.c.tend-e.c.tstart);r.set(e,t.length?K2(t):NaN)}let t=n.map(e=>e.c).sort((e,t)=>e.tstart-t.tstart),i=Z6(t),a=t.slice(1).map((e,n)=>e.tstart-t[n].tend).filter(e=>e>=0&&e<=i);a.length&&r.set(e,r.get(e)+G2(a,P2))}return r}function o8(e){let t=Object.entries(e?.channels??{}).filter(([,e])=>e.lsl!==null||e.usl!==null);return{limits:t,outside:e=>t.some(([t,n])=>Object.entries(e).some(([e,r])=>{let i=e.lastIndexOf(`:`);return r!==null&&e.slice(0,i)===t&&t8.has(e.slice(i+1))&&(n.usl!==null&&r>n.usl||n.lsl!==null&&r<n.lsl)}))}}var s8=y4(`OEE as ISO 22400-2`),c8={stops:`Stops`,slow:`Slow batches and short waits`,bad:`Bad parts`,off:`Off-golden batches`};function l8(e,t,n=[]){let r=e.context;if(!r?.shifts.length)return null;let i=e.tz,a=e.recordings,o=a.length?U3(r,i,Math.min(...a.map(e=>e.t0)),Math.max(...a.map(e=>e.t1))):[],s=a8(e,t),c=n8(),l=new Map,u=new Map,d=(e,t)=>e.get(t)??e.set(t,n8()).get(t),f=(e,t)=>{let n=V3(e,r.shifts,i);if(n!==null)for(let r of[c,d(l,n),d(u,bB(e,i))])t(r)},p=e=>({section:b4(`06`,e,[],[]),actions:[],next:[],numbers:{}});if(![...s.values()].some(Number.isFinite))return p(`No stream has a cycle time to compare, so OEE could not be measured.`);let m=new Set(e.recordings.filter(e=>e.failed).map(e=>e.id)),h=new Set(t.filter(e=>!m.has(e.c.recordingId)).map(e=>e.c.streamId));for(let t of e.recordings)if(!(t.failed||!Number.isFinite(s.get(t.streamId))))for(let e=Math.floor(t.t0/900)*900;e<t.t1;e+=900){let n=Math.max(e,t.t0),r=Math.min(e+900,t.t1),i=Math.max(0,r-n-o.reduce((e,t)=>e+Math.max(0,Math.min(r,t.t1)-Math.max(n,t.t0)),0));f(n,e=>{e.plan+=i,h.has(t.streamId)||(e.stop+=i)})}for(let e of n)if(Number.isFinite(s.get(e.streamId)))for(let t=Math.floor(e.t0/900)*900;t<e.t1;t+=900){let n=Math.max(t,e.t0),r=Math.min(t+900,e.t1);f(n,t=>{t.stop+=r-n,e.kind===`no_data`&&(t.plan+=r-n)})}let g=e.value.key===`duration`,{limits:_,outside:v}=o8(r),y=!1;for(let e of t){let t=s.get(e.c.streamId)??NaN;if(!Number.isFinite(t)||m.has(e.c.recordingId))continue;let n=e.c.flag===`bad`||v(e.c.kpis)||!g&&e.level===`off`;y||=n||e.c.flag===`good`,f(e.c.tstart,e=>{e.ideal+=t,e.n++,n?e.badIdeal+=t:e.good++})}if(!c.plan)return p(`No recorded time falls in the shifts, so OEE could not be measured.`);let b=i8(c),x=r.costs.currency,S=r.costs.lineHour,C=[...new Set(t.map(e=>s.get(e.c.streamId)??NaN).filter(Number.isFinite))].sort((e,t)=>e-t),w=e=>e<60?`${w4(+e.toFixed(1))} s`:A4(e),T=C.length?r.idealCycleS?`Ideal cycle ${w(C[0])}, set in Process context.`:`Ideal cycle ${w(C[0])}${C.length>1&&w(C[0])!==w(C[C.length-1])?` to ${w(C[C.length-1])}`:``}, inferred from the data.`:``,E=e=>S===null?``:` (up to ${C4(e/3600*S,x)})`,D=[{label:c8.stops,s:c.plan-r8(c),owner:`maintenance`,act:e=>`Find what stops the line (see 05.4): ${e} of planned time stopped.`},{label:c8.slow,s:Math.max(0,r8(c)-c.ideal),owner:`production`,act:e=>`Bring the pace to the ideal cycle: slow batches and short waits cost ${e}.`},g?{label:c8.bad,s:c.badIdeal,owner:`quality`,act:e=>`Bring the bad parts inside their limits (see 04): they cost ${e}.`}:{label:c8.off,s:c.badIdeal,owner:`quality`,act:e=>`Bring off-golden batches to golden level (see 02): they cost ${e}.`}];D.sort((e,t)=>t.s-e.s);let O=D.reduce((e,t)=>e+t.s,0),k=D[0],A=[],j=[],M=[],N=e=>{let t=`F06-${A.length+1}`;return A.push({id:t,section:`06`,refs:[`06`],...e}),t};if(N({evidence:`measured`,p:null,numbers:R2({oee:b.oee,availability:b.A,performance:b.P,quality:b.Q,plannedH:c.plan/3600}),text:`OEE ${x4(b.oee)}: availability ${x4(b.A)}, performance ${x4(b.P)}, quality ${x4(b.Q)}, over ${A4(c.plan)} of planned time.${T?` ${T}`:``}`}),k.s>0){let e=N({evidence:`measured`,p:null,numbers:R2({hours:k.s/3600,share:k.s/O,cost:S===null?NaN:k.s/3600*S}),text:`${k.label} lose the most: ${A4(k.s)}${E(k.s)}, ${x4(k.s/O)} of the ${A4(O)} lost.`});j.push({text:k.act(`${A4(k.s)}${E(k.s)}`),owner:k.owner,urgent:!1,rank:k.s/c.plan,refs:[e]})}let P=r.shifts.filter(e=>l.has(e.name)).map(e=>{let t=l.get(e.name),n=i8(t);return{cells:[e.name,x4(n.A),t.n?x4(n.P):`–`,t.n?x4(n.Q):`–`,x4(n.oee)]}});O>0&&M.push({kind:`bars`,title:`06.1 · Where planned time is lost${S===null?``:`, and what it costs`}`,max:k.s/3600,rows:D.filter(e=>e.s>=60).map(e=>({label:e.label,value:e.s/3600,text:`${A4(e.s)}${E(e.s)}`,tip:`${e.label}: ${x4(e.s/O)} of the time lost`}))}),P.length>1&&!r.hideShifts&&M.push({kind:`table`,title:`06.2 · OEE by shift`,columns:[`Shift`,`Availability`,`Performance`,`Quality`,`OEE`],rows:P});let F=[...u].filter(([,e])=>e.plan>0).map(([e,t])=>({t:xB(e,`00:00`,i),v:i8(t).oee})).sort((e,t)=>e.t-t.t),I=F.length>=7?c4(F.map(e=>(e.t-F[0].t)/86400),F.map(e=>e.v)):null;if(I&&I.p<.01&&Math.abs(I.b*700)>=1){N({evidence:`statistical`,p:I.p,numbers:R2({perWeek:I.b*7,days:I.n,p:I.p}),text:`OEE ${I.b<0?`falls`:`rises`} by ${Math.round(Math.abs(I.b*700))} points a week since ${B4(F[0].t,i)}.`});let e=F[0].t,t=F[F.length-1].t;M.push({kind:`trend`,title:`06.3 · OEE per day, with its trend`,unit:`%`,points:F.map(e=>({t:e.t,v:e.v*100})),line:{t0:e,v0:I.a*100,t1:t,v1:(I.a+I.b*(t-e)/86400)*100},limit:null,crossing:null})}let L=k.s>0?`${k.label} lose the most time.`:`No planned time is lost.`,R=g&&c.n&&!y&&!_.length?[`Add specification limits to the quality channels in Process context: OEE counts every batch as good until something says which are bad.`]:[];return{section:{...b4(`06`,L,A,M),subtitle:s8,fold:!0},actions:j,next:R,numbers:{oee:b.oee,stopsS:c.plan-r8(c),slowS:Math.max(0,r8(c)-c.ideal),offS:c.badIdeal}}}function u8(e,t,n,r=[]){let i=W3(e.context??w3()).shifts,a=e.tz;if(!i.length)return{section:`11`,needs:`Add the shifts in Process context to compare them.`};let o=new Map(i.map(e=>[e.name,{n:0,good:0,stopped:0,alerts:0}])),s=e=>{let t=V3(e,i,a);return t===null?void 0:o.get(t)};for(let e of t){let t=s(e.c.tstart);t&&(t.n++,e.level!==`off`&&t.good++)}for(let t of e.alerts??[]){let e=s(t.t);e&&e.alerts++}for(let e of n)for(let t=Math.floor(e.t0/900)*900;t<e.t1;t+=900){let n=Math.max(t,e.t0),r=Math.min(t+900,e.t1),i=s(n);i&&(i.stopped+=r-n)}let c=[...o].map(([e,t])=>({name:e,...t,share:t.n?t.good/t.n:NaN})),l=c.filter(e=>e.n>=5),u=l.reduce((e,t)=>!e||t.share<e.share?t:e,null),d=u&&l.filter(e=>e!==u),f=d?.reduce((e,t)=>e+t.n,0)??0,p=d?.reduce((e,t)=>e+t.good,0)??0,m=f?p/f:NaN,h=!!u&&r.some(e=>e.text.includes(`on the ${u.name} shift`)),g=!!u&&m-u.share>=.05&&(h||a4(u.good,u.n,p,f).p<.01),_=[];if(g){let e=`The ${u.name} shift has the lowest share of batches at golden level (${x4(u.share)} against ${x4(m)}).`,t=[`11`,...h?[`02`]:[]];_.push({id:`F11-1`,section:`11`,refs:t,evidence:`measured`,p:null,text:e,numbers:{share:u.share,others:m,batches:u.n}})}let v=c.filter(e=>e.n);return{section:b4(`11`,g?_[0].text:l.length>=2?`The shifts perform alike.`:v.length===1?`Only the ${v[0].name} shift made batches in this period.`:`Too few batches in the shifts to compare them.`,_,[{kind:`table`,title:`11.1 · Shifts`,columns:[`Shift`,`Batches`,`At golden level or better`,`Stopped`,`Alerts`],rows:c.map(e=>({cells:[e.name,e.n.toLocaleString(`en-GB`),e.n?x4(e.share):`–`,A4(e.stopped),String(e.alerts)],...g&&e===u?{status:`watch`,finding:`F11-1`}:{}}))}]),actions:[],next:[],numbers:g?{share:u.share,others:m}:{}}}function d8(e,t,n=[],r,i=Q6(e)){let a=e.previous,o=a?{...e,period:a.period,recordings:a.recordings,cycles:a.cycles,previous:null}:null,s=o?L2(o):[];if(!o||s.length<5)return{section:`01`,needs:`The period before this one has too few stored batches to compare with. It fills in once the cycles of that period are found.`};if(t.length<5)return{section:`01`,needs:`This period has too few batches to compare with the one before.`};let c=e=>e.filter(e=>e.level!==`off`).length,l=a4(c(t),t.length,c(s),s.length),u=e=>e.map(e=>e.c.value),d=K2(u(t)),f=K2(u(s)),p=Z2(u(t),u(s)),[m,h]=o4([l.p,p.p],N2),g=e.value.label,[_,v]=E4(d,f),y=e.value.better===`min`?p.effect<.5:p.effect>.5,b=_===v?y?`better`:`worse`:null,x=[],S=[],C=[],w=[];if(m){let e=l.p1>l.p2;x.push({id:`F01-1`,section:`01`,refs:[`01`],evidence:`statistical`,p:l.p,numbers:R2({share:l.p1,before:l.p2,p:l.p}),text:`${x4(l.p1)} of batches at golden level or better, ${e?`up`:`down`} from ${x4(l.p2)} the period before.`}),w.push({better:e,text:`${x4(l.p1)} of batches at golden level, ${e?`up`:`down`} from ${x4(l.p2)}.`}),e||(S.push(`the share at golden level`),C.push(`F01-1`))}h&&(x.push({id:`F01-2`,section:`01`,refs:[`01`],evidence:`statistical`,p:p.p,numbers:R2({median:d,before:f,p:p.p}),text:b?`${g} moved ${b} since the period before (median ${_} both times).`:`The median ${g} is ${_}, ${y?`better`:`worse`} than ${v} the period before.`}),w.push({better:y,text:b?`${g} moved ${b} (median ${_} both times).`:`the median ${g} is ${_}, against ${v}.`}),y||(S.push(g),C.push(`F01-2`)));let T=[],E=e.tz,D=`${B4(a.period.from,E)} – ${B4(a.period.to-1,E)}`;S.length&&T.push({text:`Find what changed since the period before (${D}): ${S.join(` and `)} ${S.length>1?`are`:`is`} worse.`,owner:`management`,urgent:!1,rank:Math.max(0,l.p2-l.p1),refs:[...C,...n.map(e=>e.id)]});let O=w.find(e=>!e.better)??w[0],k=O?`${O.better?`Better`:`Worse`} than the period before: ${O.text}`:`About the same as the period before.`,A=e=>e.reduce((e,t)=>e+t.t1-t.t0,0),j=(e,t,n=h6(e,t))=>n.filter(e=>e.status===`Replace`||e.status===`Drifting`).length,M=A(i),N=A(Q6(o));return{section:b4(`01`,k,x,[{kind:`tiles`,tiles:[{label:`At golden level or better`,value:x4(l.p1),note:`${x4(l.p2)} before`},{label:`${g} median`,value:_,note:`${v} before`},{label:`Stopped`,value:A4(M),note:`${A4(N)} before`},{label:`Sensors to replace or drifting`,value:String(j(e,t,r)),note:`${j(o,s)} before`}]}]),actions:T,next:[],numbers:R2({share:l.p1,before:l.p2,median:d,medianBefore:f,stoppedS:M,stoppedBeforeS:N})}}function f8(e,t,n,r){let{tz:i}=e,a=bB(e.period.from,i),o=bB(e.period.to-1,i),s=[];for(let e=a;e<=o&&s.length<=400;e=SB(e,1))s.push(e);if(s.length<2||s.length>400||!t.length)return null;let c=e=>s.indexOf(bB(e,i)),l=s.map(()=>0),u=s.map(()=>0),d=s.map(()=>0),f=s.map(()=>!1);for(let e of t){let t=c(e.c.tstart);t>=0&&(l[t]++,e.level===`off`&&u[t]++)}let p=s.map(e=>[xB(e,`00:00`,i),xB(SB(e,1),`00:00`,i)]);for(let e of n)p.forEach(([t,n],r)=>{d[r]+=Math.max(0,Math.min(n,e.t1)-Math.max(t,e.t0))});let m=r??e.recordings.flatMap(e=>Object.values(e.health?.channels??{}).filter(e=>!e.clock).flatMap(e=>e.flats));for(let e of m)p.forEach(([t,n],r)=>{e.t1>t&&e.t0<n&&(f[r]=!0)});return s.every((e,t)=>!u[t]&&d[t]<60&&!f[t])?null:{kind:`strip`,title:`00.3 · The period day by day: the share of batches off the golden, with stops and failing sensors marked`,legend:`off the golden`,days:s.map((e,t)=>{let n=new Date(`${e}T00:00:00Z`),r=`${W4[(n.getUTCDay()+6)%7]} ${n.getUTCDate()} ${n.toLocaleString(`en-GB`,{month:`short`,timeZone:`UTC`})}`,i=[l[t]?`${N4(l[t],`batch`,`batches`)}, ${x4(u[t]/l[t])} off the golden`:`no batches`,...d[t]>=60?[`stopped ${A4(d[t])}`]:[],...f[t]?[`a sensor stuck`]:[]];return{day:e,label:r,n:l[t],off:l[t]?u[t]/l[t]:null,stopS:d[t],sensor:f[t],text:`${r}: ${i.join(`, `)}`}})}}var p8={management:`Management`,quality:`Quality`,maintenance:`Maintenance`,production:`Production`},m8=e=>e.findings.length||e.id===`01`?e:{...e,charts:[],notes:[]},h8=(e,t)=>{let n=t.filter(e=>!!e);return{...e,section:W6(m8(e.section),n),actions:[...e.actions,...n.flatMap(e=>e.actions)],next:[...e.next,...n.flatMap(e=>e.next)]}},g8=e=>({cells:[e.id,e.text,p8[e.owner]],...e.urgent?{status:`crit`}:{}});function _8(e){let t=m6(e);if(!t.size)return e;let n=e=>e&&Object.fromEntries(Object.entries(e).filter(([e])=>!t.has(e)));return{...e,cycles:e.cycles.map(e=>({...e,z:n(e.z),d:n(e.d)})),goldens:e.goldens.map(e=>({...e,edges:n(e.edges)}))}}function v8(e){let t=L4(e.tz)?e:{...e,tz:`UTC`},n=_8(t.context?{...t,context:W3(t.context)}:t),r=L2(n),i=R6(n,r),a=r3(n,r),o=g6(n,r),{stops:s,offGaps:c}=$6(n),l=e8(n,s,c),u=h8(o.out,[l,H6(n,o.drifts,o.wear)]),d=o.out.numbers.replace+o.out.numbers.drifting+o.out.numbers.watch,f=!o.out.section.findings.length&&l?.findings.length?{...u,section:{...u.section,verdict:`${l.findings[0].text}${d?` ${o.out.section.verdict}`:``}`}}:u,p=m8(i.section),m=m8(a.section),h=m8(f.section),g=s3(n,r),_=T6(n,r,o.sensors),v=g===null?S6(n,r):null,y=_?`${N4(_.findings.reduce((e,t)=>e+t.numbers.batches,0),`batch`,`batches`)} to check before they ship: made while a sensor was failing.`:v?`${N4(v.findings.length,`feature`)} left ${v.findings.length===1?`its`:`their`} control limits; no specification limits say which batches are bad.`:``,b=!_&&!v?g:g&&!(`needs`in g)?h8(g,[_]):[g,h8({section:{...b4(`04`,y,[],[]),fold:!0,subtitle:y4(_?`Containment: batches made while a sensor was failing`:`Control chart (Shewhart individuals, 3σ)`)},actions:[],next:[],numbers:{}},[_,v])],x=w6(n,r),S=[d8(n,r,x&&!(`needs`in x)?x.section.findings:[],o.sensors,s),b,l8(n,r,s),$4(n,r),x,k6(n,r),z6(n,r),n.context?.hideShifts?null:u8(n,r,s,i.section.findings)].flat(),C=S.filter(e=>!!e&&!(`needs`in e)),w=S.filter(e=>!!e&&`needs`in e),T=C.map(e=>m8(e.section)),E=new Set(T.map(e=>e.id)),D=[...i.actions,...a.actions,...f.actions,...C.flatMap(e=>e.actions)].sort((e,t)=>Number(t.urgent)-Number(e.urgent)||t.rank-e.rank).map((e,t)=>({id:`A${t+1}`,text:e.text,owner:e.owner,urgent:e.urgent,refs:e.refs})),O=D.slice(0,3),k=b4(`12`,D.length?`Start with ${P4(O.map(e=>e.id))}: ${O.some(e=>e.urgent)?`urgent items`:`the largest effect`} first.`:`Nothing to act on in this period.`,[],D.length?[{kind:`table`,title:`12.1 · Actions, most urgent first`,columns:[`#`,`Action`,`Owner`],rows:D.map(g8),...D.length>5?{shown:5,more:N4(D.length-5,`more action`)}:{}}]:[]),A=[...new Set([...i.next,...a.next,...f.next,...C.flatMap(e=>e.next)])],j=b4(`13`,A[0]??`Nothing left unexplained that more data would answer.`,[],[],A.slice(1)),M=r.filter(e=>e.level!==`off`).length,N=D.filter(e=>e.urgent).length,P=e=>{let t=new Set(e.findings.map(e=>e.id)),n=D.findIndex(e=>e.refs.some(e=>t.has(e)));return n<0?1/0:n},F=[p,h,m,...T].filter(e=>e.findings.length).map(e=>({s:e,i:P(e)})).sort((e,t)=>e.i-t.i||0).map(e=>e.s),I=n.value.key===`duration`?r.reduce((e,t)=>e+Math.max(0,t.gap),0):0,L=o8(n.context),R=C.find(e=>e.section.id===`06`)?.numbers,z=C.find(e=>e.section.id===`09`)?.section.findings.find(e=>e.id===`F09-2`)?.numbers.extra,B=B6(n,{time:R&&`slowS`in R?[{label:c8.stops,s:R.stopsS,owner:p8.maintenance,ref:`06`},{label:c8.slow,s:R.slowS,owner:p8.production,ref:`06`},n.value.key===`duration`?{label:c8.bad,s:R.offS,owner:p8.quality,ref:`06`,bad:!0}:{label:c8.off,s:R.offS,owner:p8.quality,ref:`06`}]:[{label:`Stops`,s:s.reduce((e,t)=>e+t.t1-t.t0,0),owner:p8.maintenance,ref:`05`},{label:`Batches slower than the golden`,s:I,owner:p8.production,ref:`02`}],energyKwh:z??null,review:_&&E.has(`04`)?{batches:_.findings.reduce((e,t)=>e+t.numbers.batches,0),s:_.findings.reduce((e,t)=>e+t.numbers.seconds,0)}:null,scrap:L.limits.length||r.some(e=>e.c.flag===`bad`||e.c.flag===`good`)?{batches:r.filter(e=>e.c.flag===`bad`||L.outside(e.c.kpis)).length,assumed:!1}:n.value.key===`duration`?null:{batches:r.length-M,assumed:!0}}),V=f8(n,r,s,o.sensors.flatMap(e=>e.stuck)),ee=o.sensors.filter(e=>e.status===`Drifting`),te=new Set(ee.map(e=>e.sid)),H=b4(`00`,r.length?`${x4(M/r.length)} of batches at golden level or better${N?`, and ${N4(N,`urgent item`)}`:``}.`:`No batches could be compared with a golden in this period.`,F.map((e,t)=>({id:`F00-${t+1}`,section:`00`,text:e.verdict,evidence:e.findings[0].evidence,p:e.findings[0].p,refs:[e.id],numbers:e.findings[0].numbers})),[...B?[B]:[],...O.length?[{kind:`table`,title:`00.2 · What to do first`,columns:[`#`,`Action`,`Owner`],rows:O.map(g8),ref:`12`}]:[],...V?[V]:[],{kind:`tiles`,tiles:[{label:`Batches`,value:r.length.toLocaleString(`en-GB`),note:N4(n.recordings.length,`file`)},{label:`At golden level or better`,value:r.length?x4(M/r.length):`–`},...a.numbers.better?[{label:`Better than the golden`,value:a.numbers.better.toLocaleString(`en-GB`)}]:[],...f.numbers.replace?[{label:f.numbers.replace===1?`Sensor to replace`:`Sensors to replace`,value:String(f.numbers.replace)}]:[],...ee.length?[{value:String(ee.length),label:`${ee.length===1?`Channel`:`Channels`} drifting${te.size>1?` on ${te.size} streams`:n.streams.length>1?`${ee.length>1?`, all`:``} on ${n.streams.find(e=>e.id===ee[0].sid)?.name??`one stream`}`:``}`}]:[]]}]),ne=n.recordings.filter(e=>!e.failed&&!e.unread),re=n.recordings.filter(e=>e.failed),ie=n.recordings.filter(e=>e.unread).length,U=e=>n.streams.find(t=>t.id===e)?.name??`A stream`,ae=b4(`14`,`How the findings were made and how sure each one is.`,[],[],[`Cycles found with “${n.rule.name}” v${n.rule.version} in ${N4(n.recordings.length,`recording`)} of ${N4(n.streams.length,`stream`)}, ${x4(n.recordings.length?ne.length/n.recordings.length:0)} read${ie?`; ${ie} not read, counted through ${ie===1?`its`:`their`} stored cycles and measures`:``}${re.length?` (could not be read: ${re.map(e=>`${e.name}, ${e.failed}`).join(`; `)})`:``}.`,...n.goldens.map(e=>`${U(e.streamId)}: compared with ${e.label}${e.proposed?`, proposed because no golden is set`:e.auto?`, set by this report because none was set (the best ${n.value.label} that 1 batch in 20 reaches, and at least 5); change it with Make it the golden or in Batches`:``}, on ${N4(Object.keys(e.edges).length,`channel`)}.`),`A batch is at golden level when its ${n.value.label} is within 2% of the golden’s (or twice the spread of the golden’s own batches), and better than the golden beyond that on the good side.`,`Shares of the batch-to-batch variation in the gap: a least-squares fit, over all measured batches, of each batch’s gap on its deviation from the golden by channel and phase, split with Pratt’s measure; only deviations that differ between off-golden batches and the rest enter (Mann–Whitney, Benjamini–Hochberg at q = 0.01 across channel × phase). Shares and what better batches do differently are correlations: leads to test, not proven causes.`,`Patterns: two-proportion tests (Fisher’s exact test with small counts), Benjamini–Hochberg at q = 0.01 across streams and across files; a group is named only when it runs at least 5 points more off-golden than the rest. What better batches do differently: Mann–Whitney per measure, Benjamini–Hochberg at q = 0.01 across measures. The proposed golden of a stream: the best value at least 5 of its batches reach. Intervals: bootstrap over batches (1,000 resamples; over 2,000 batches, resamples of 2,000 scaled to the period). p-values are shown as they are, never as a confidence.`,...s.length||c?[`Stops (05.4): no data for ${300/60} minutes or more, or no batch for ${300/60} minutes or more and at least 5× the usual wait between two batches; planned stops and time outside the shifts left out${n.context?.shifts.length?``:`; without shifts, no data for more than ${G6/3600} h is time off, not a stop`}; a stop is given a machine unit when one of its channels went flat within 60 s of the stop’s start.`]:[],`Sensor health per recording: gaps (steps over 4× the usual), flat runs (${300/60} minutes or more of one repeated value; runs at the same value with up to ${a6/3600} h between them, a stop or a file boundary, are one; a sensor is stuck only where batches were made meanwhile, not while the line stood still), noise (median absolute deviation of sample-to-sample changes), spikes (Hampel filter, 6 robust σ), rate drops, and values outside the range learned from the first third of the period’s recordings. Drift: a straight-line trend of each channel’s offset from the golden, forecast to the golden’s band edge; an offset that stepped once and stayed is a change, not a drift. Counters (an energy meter, a part count) are not compared with the golden.`,...t===e?[]:[`Times in UTC: the time zone “${e.tz}” is not known.`],`Drifts and wear are fitted on daily means (batches of one day are not independent), with Student’s t. Over fewer than 7 days a drift is fitted on means per recording (per hour with fewer than 6 recordings), at least 6 of them, and says so: those means are not independent either, so a short drift is a lead to confirm over more days. Drifts are kept at Benjamini–Hochberg q = 0.01 across sensors; the day a drift reaches the band edge has a 99 % interval by inverse prediction (Fieller).`,...g&&!(`needs`in g)?[`Capability (04.1): Ppk = min(USL − mean, mean − LSL) / 3σ of each cycle KPI (mean, minimum, maximum, at start, at end) whose channel has specification limits in Process context, over at least 30 batches; capable from ${n.context?.ppkMin??1.33}. ${i3}`]:[],...v?[`Control chart (04.3): per stream, each level KPI of the batches in time order; centre line = the mean, σ = the average moving range / 1.128, limits = mean ± 3σ, from 30 batches; a KPI is named when more than ${(2*_6*100).toFixed(2)}% of its batches are outside (twice what a stable process leaves by chance). It says the process moved, not that a batch is bad.`]:[],...h.charts.some(e=>`title`in e&&e.title.startsWith(`05.5`))?[`Maintenance (05.5): each recalibration by the lower end of its crossing’s 99 % interval, placed in the latest planned stop before it.`]:[],..._&&E.has(`04`)?[`Batches made while a sensor was failing (04.2): the flat runs (05.1) and the drift past the band edge (05.2) of the sensors a golden compares; a batch counts when it starts inside one.`]:[],...E.has(`06`)?[`OEE (06), with the ratios of ISO 22400-2: planned time is the recorded time inside the shifts less planned stops, plus the stops with no data (05.4); availability = the time not stopped (planned time less 05.4’s stops) / planned time; performance = the ideal cycle × batches / the time not stopped, the ideal cycle being ${n.context?.idealCycleS?`the one set in Process context`:`inferred from the data: the golden’s cycle time plus the shortest wait between two batches that 1 wait in 20 reaches`}; quality = good batches / batches: not flagged bad and inside the specification limits${n.value.key===`duration`?``:`, and at golden level or better`}. The daily trend is a straight line over 7 days or more, kept at p < 0.01.`]:[],...E.has(`07`)?[`Alerts (07): the project’s alert rules run over the period’s recordings; an alert comes before a batch when raised in the ${Z4/3600} h before it starts or while it runs; two-proportion tests (Fisher’s exact test with small counts), Benjamini–Hochberg at q = 0.01 across rules.`]:[],...E.has(`08`)?[`Changes (08): consecutive flat runs of a setting at values more than 3 noise σ apart; the effect by Mann–Whitney on the 20 batches each side, Benjamini–Hochberg at q = 0.01 across the changes.`]:[],...E.has(`09`)?[`Energy (09): per batch, a power channel (W, kW, MW) integrated over the batch, or an energy meter (Wh, kWh, MWh) by its change; the period’s energy is what a meter counted over the recordings (the batches’ energy with a power channel); off-golden batches against the rest by Mann–Whitney. CO₂ is the energy times the grid factor entered in Process context: Scope 2, location-based.`]:[],...E.has(`10`)?[`Lines (10): each line’s batches against its own streams’ goldens; each line against the other lines by two-proportion tests, Benjamini–Hochberg at q = 0.01 across lines.`]:[],...E.has(`11`)?[`Shifts (11): measured counts per shift (batches, the share at golden level or better, stopped time in 15-minute blocks, alerts); the weakest shift is named when its share differs from the other shifts’ by a two-proportion test at p < 0.01, or when 02.4 named it.`]:[],...E.has(`01`)?[`Since the last period (01): the previous period’s stored batches judged against the current goldens; the share at golden level by a two-proportion test and the value by Mann–Whitney, Benjamini–Hochberg at q = 0.01 across the two.`]:[],`Findings computed by Kymoscope, worded from fixed templates; no AI was used.`]),oe=n.goldens,se=p6(n),ce=Object.keys(n.units).filter(e=>!se.has(e)).length;return{v:1,cover:{title:`Report ${B4(n.period.from,n.tz)} – ${B4(n.period.to-1,n.tz)}`,project:n.project,period:n.period,cycle:`${n.rule.name} v${n.rule.version}`,value:`${n.value.label}, ${n.value.better===`min`?`lower`:`higher`} is better`,golden:oe.length===1?`${oe[0].label}${oe[0].proposed?` (proposed: no golden set)`:oe[0].auto?` (set automatically: none was set)`:``}`:oe.length?`${oe.length} goldens, one per stream`:`None`,data:`${N4(n.streams.length,`stream`)} · ${N4(n.recordings.length,`file`)}${ce||!ie?` · ${N4(ce,`channel`)}`:``}`,madeBy:n.madeBy,madeAt:n.madeAt,tz:n.tz,context:n.contextVersion?`Process context v${n.contextVersion}`:`None set`},actions:D,sections:[H,p,m,...T,h,k,j,ae].sort((e,t)=>e.id.localeCompare(t.id)),missing:[...new Map([...q3(n.context??null,n.alertRules?.length??0),...w].map(e=>[`${e.section} ${e.needs}`,e])).values()].map(e=>({section:e.section,title:g4[e.section],needs:e.needs})).sort((e,t)=>e.section.localeCompare(t.section))}}function y8(e){let t=new Set((e.fold?e.charts.slice(0,1):e.charts).flatMap(e=>e.kind===`table`?e.rows.flatMap(e=>e.finding?[e.finding]:[]):[])),n=e.shown??e.findings.length,r=e=>!t.has(e.id);if(e.fold){let t=e.findings.filter(r);return{full:t.slice(0,n),rest:t.slice(n)}}return{full:e.findings.slice(0,n).filter(r),rest:e.findings.slice(n).filter(r)}}function b8(e,t){return t===`full`?e.sections:e.sections.filter(e=>e.roles.includes(t))}var x8={verdict:30,sentence:35,action:30},S8={verdict:250,sentence:300,action:250},C8=/\b(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|hundred|thousand|million|dozen|half|twice|double|triple)\b/i,w8=/\b(\d{1,2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?/gi,T8=e=>e.normalize(`NFKC`).replace(/−/g,`-`),E8=e=>C8.test(T8(e))||/(?![0-9])\p{Nd}/u.test(T8(e)),D8=e=>{let t=T8(e),n=[];return t=t.replace(w8,(e,t,r)=>(n.push(`${+t} ${r.toLowerCase()}`),` `)),[...n,...(t.match(/[-+]?(?:\d[\d,]*)?\.?\d+%?/gu)??[]).map(e=>e.replace(/,/g,``))]},O8=e=>!!e&&typeof e==`object`&&!Array.isArray(e),k8=e=>Array.isArray(e)?e.filter(O8):[];function A8(e,t){let n=new Map(e.sections.flatMap(e=>e.findings.map(e=>[e.id,e.text]))),r=(e,t,r,i,a=!0)=>{if(!O8(e))return null;let o=typeof e.text==`string`?e.text.trim():``,s=Array.isArray(e.cites)?[...new Set(e.cites)]:[];if(!o||!s.length||!s.every(e=>typeof e==`string`&&n.has(e)&&i.has(e))||o.length>t.chars||o.split(/\s+/).length>t.words||E8(o))return null;let c=new Set([...r,...a?s.map(e=>n.get(e)):[]].flatMap(D8));return D8(o).every(e=>c.has(e))?{text:o,cites:s}:null},i=e=>({words:x8[e],chars:S8[e]}),a=O8(t)?t:{},o=new Map(k8(a.actions).map(e=>[e.id,e])),s=e.actions.flatMap(e=>{let t=r(o.get(e.id),i(`action`),[e.text],new Set(e.refs));return t?[{id:e.id,text:t.text,cites:t.cites}]:[]}),c=new Map(k8(a.sections).map(e=>[e.id,e])),l=new Map(e.sections.map(e=>[e.id,e.findings.map(e=>e.id)])),u=t=>new Set(t.id===`12`?e.actions.flatMap(e=>e.refs):[...l.get(t.id),...t.id===`00`?t.findings.flatMap(e=>e.refs.flatMap(e=>l.get(e)??[])):[]]);return{sections:e.sections.flatMap(e=>{let t=e.id===`14`?void 0:c.get(e.id);if(!t)return[];let n=u(e),a=r(t.verdict,i(`verdict`),[e.verdict],n,!1),o=(Array.isArray(t.sentences)?t.sentences:[]).map(e=>r(e,i(`sentence`),[],n)).filter(e=>!!e).slice(0,2);return a||o.length?[{id:e.id,verdict:a,sentences:o}]:[]}),actions:s}}var j8=e=>`Findings computed by Kymoscope. Text written by Kymoscope’s AI (${e}) from the findings and the Process context only, never from the data; every sentence names the findings it rests on.`;function M8(e,t){let n=t?W3(t):null;return{process:n?.process??``,channels:Object.entries(n?.channels??{}).flatMap(([e,t])=>{let n=T3(t);return n&&n!==`ignore`?[{name:e,role:x3[n],unit:t.unit}]:[]}).slice(0,200),sections:e.sections.filter(e=>e.id!==`14`).map(e=>({id:e.id,title:e.title,verdict:e.verdict,findings:e.findings.map(e=>({id:e.id,text:e.text,evidence:X4(e),refs:e.refs}))})),actions:e.actions.map(e=>({id:e.id,text:e.text,owner:e.owner,refs:e.refs}))}}function N8(e,t,n){let r=A8({sections:e.sections.map(e=>({id:e.id,verdict:e.verdict,findings:e.findings})),actions:e.actions},t),i=new Map(r.actions.map(e=>[e.id,e.text])),a=e.actions.map(e=>i.has(e.id)?{...e,text:i.get(e.id)}:e),o=new Map(a.map(e=>[e.id,e.text])),s=new Map(r.sections.map(e=>[e.id,e])),c=e.sections.map(e=>{let t=e.charts.map(e=>e.kind===`table`&&e.columns[0]===`#`?{...e,rows:e.rows.map(e=>o.has(e.cells[0])?{...e,cells:[e.cells[0],o.get(e.cells[0]),...e.cells.slice(2)]}:e)}:e),n=s.get(e.id);if(!n)return{...e,charts:t};let r=new Set(e.charts.flatMap(e=>e.kind===`table`?e.rows.flatMap(e=>e.finding?[e.finding]:[]):[])),i=e.findings.length===1&&r.has(e.findings[0].id)?[]:n.sentences;return{...e,charts:t,...n.verdict?{verdict:n.verdict.text}:{},...i.length?{ai:i}:{}}}),l=new Map(c.map(e=>[e.id,e.verdict])),u=c.map(e=>e.id===`00`?{...e,findings:e.findings.map(e=>({...e,text:l.get(e.refs[0])??e.text}))}:e.id===`14`?{...e,notes:[...e.notes.slice(0,-1),j8(n)]}:e);return{...e,cover:{...e.cover,ai:n},sections:u,actions:a}}var P8=.5,F8=5400,I8=/^[kM]?Wh?$/,L8=86400/300,R8=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],z8=e=>{let t=Math.round((e%86400+86400)%86400/60)%1440;return`${String(Math.floor(t/60)).padStart(2,`0`)}:${String(t%60).padStart(2,`0`)}`},B8=(e,t)=>Math.round(e/t)*t;function V8(e){if(!e.length)return null;let t=K2(e.map(e=>e.p01??e.lo)),n=K2(e.map(e=>e.p99??e.hi));if(!(n>t))return null;let r=Math.floor(Math.log10(n-t)),i=10**(r-1),a=Math.max(0,1-r);return{lo:+(Math.floor(t/i)*i).toFixed(a),hi:+(Math.ceil(n/i)*i).toFixed(a)}}function H8(e){let t=new Set(e.filter(e=>e.batches.length).map(e=>e.streamId)),n=e.flatMap(e=>t.has(e.streamId)?e.batches:[[e.t0,e.t1]]).filter(([e,t])=>t>e).sort((e,t)=>e[0]-t[0]),r=[];for(let[e,t]of n){let n=r[r.length-1];n&&e-n[1]<600?n[1]=Math.max(n[1],t):r.push([e,t])}return r}function U8(e,t){let n=new Map,r=e=>{let r=Math.floor(e/3600),i=n.get(r);return i===void 0&&n.set(r,i=yB(e,t)),e+i},i=new Map;for(let[t,n]of e)for(let e=Math.ceil((t-300/2)/300)*300+300/2;e<n;e+=300){let t=r(e),n=Math.floor(t/86400),a=Math.floor((t-n*86400)/300),o=i.get(n);o||i.set(n,o=new Set),o.add(a)}return i}function W8(e){let t=[...e.keys()].sort((e,t)=>e-t);if(t.length<3||t[t.length-1]-t[0]<13)return null;let n=Array(7).fill(0),r=Array(7).fill(0);for(let i=t[0];i<=t[t.length-1];i++){let t=(i+3)%7;n[t]++,e.has(i)&&r[t]++}let i=[0,1,2,3,4,5,6].filter(e=>n[e]>=2&&r[e]===0),a=[0,1,2,3,4,5,6].filter(e=>!i.includes(e));return!i.length||!a.length||a.some(e=>r[e]/n[e]<.6)?null:{name:i.join()===`5,6`?`Weekend`:`No work on ${i.map(e=>R8[e]).join(`, `)}`,from:`00:00`,to:`00:00`,days:i}}function G8(e){let t={shifts:[],stops:[]};if(e.size<3)return t;let n=Array.from({length:L8},(t,n)=>[...e.values()].filter(e=>e.has(n)).length/e.size),r=n.map(e=>e>=P8),i=[],a=r.indexOf(!0);if(a<0)return t;for(let e=0;e<L8;e++){let t=(a+e)%L8;if(r[t])continue;let n=i[i.length-1];n&&(n.a+n.n)%L8===t?n.n++:i.push({a:t,n:1})}let o=i.filter(e=>e.n*300>=600&&e.n*300<=5400),s=i.filter(e=>e.n*300>F8);for(let e of i.filter(e=>e.n*300<600))for(let t=0;t<e.n;t++)r[(e.a+t)%L8]=!0;let c=i.filter(e=>e.n*300>=600).flatMap(e=>Array.from({length:e.n},(t,r)=>n[(e.a+r)%L8])),l=n.filter((e,t)=>r[t]),u=e=>e.reduce((e,t)=>e+t,0)/e.length;if(!c.length||u(l)<.7||u(c)>.25)return t;let d=[];if(!s.length)d.push({a:0,b:86400,pauses:[]});else for(let e=0;e<s.length;e++){let t=(s[e].a+s[e].n)%L8*300,n=s[(e+1)%s.length].a*300;d.push({a:t,b:n>t?n:n+86400,pauses:[]})}let f=!s.length;for(let e of o){let t=e.a*300,n=t+e.n*300,r=d.find(e=>f||t>=e.a&&n<=e.b||t+86400>=e.a&&n+86400<=e.b);r&&r.pauses.push(f||t>=r.a?{a:t,b:n}:{a:t+86400,b:n+86400})}let p=[],m=[];for(let e of d){e.pauses.sort((e,t)=>e.a-t.a);let n=[...e.pauses],r=e=>(e.a+e.b)/2;for(;;){if(f&&n.length<2){n.length=0;break}let t=-1,i=1/0;if(n.forEach((a,o)=>{let s=o>0?r(n[o-1]):f?r(n[n.length-1])-86400:e.a,c=o<n.length-1?r(n[o+1]):f?r(n[0])+86400:e.b,l=Math.min(r(a)-s,c-r(a));l<i&&(i=l,t=o)}),t<0||i>=21600)break;n.splice(t,1)}for(let t of e.pauses.filter(e=>!n.includes(e))){let e=B8(t.a,900),n=B8(t.b,900);n>e&&m.push({name:`Break`,from:z8(e),to:z8(n)})}let i=n.map(e=>B8(r(e),1800)),a=f?i:[B8(e.a,1800),...i,B8(e.b,1800)],o=f?i.map((e,t)=>({a:e,b:t<i.length-1?i[t+1]:i[0]+86400})):a.slice(0,-1).map((e,t)=>({a:e,b:a[t+1]}));if(f&&!o.length)return t;for(let e of o){let t=e.b-e.a,n=Math.round(t/(8*3600));if(n>=2&&Math.abs(t-n*8*3600)<=3600)for(let r=0;r<n;r++)p.push({a:B8(e.a+r*t/n,1800),b:B8(e.a+(r+1)*t/n,1800)});else t>=3600&&p.push(e)}}let h=e=>(e%86400+86400)%86400;return{shifts:p.sort((e,t)=>h(e.a)-h(t.a)).map((e,t)=>({name:`Shift ${t+1}`,start:z8(e.a),end:z8(e.b)})),stops:m}}function K8(e){let t=new Map;for(let n of e){if(!n.rule||!n.channels.length)continue;let e=`${n.rule}|${n.channels.map(e=>e.name).sort().join(`\0`)}`;t.set(e,[...t.get(e)??[],n])}return([...t.values()].filter(e=>e.length>=2).sort((e,t)=>t.length-e.length)[0]??[]).map(e=>({name:e.name,streams:[e.id]})).sort((e,t)=>e.name.localeCompare(t.name))}function q8(e){let t=new Map;for(let n of e){let e=n.includes(`.`)?n.indexOf(`.`):n.indexOf(`_`);e>0&&t.set(n.slice(0,e),[...t.get(n.slice(0,e))??[],n])}return[...t].filter(([,t])=>t.length>=2&&t.length<e.length).map(([e,t])=>({name:e,channels:t.sort()})).sort((e,t)=>e.name.localeCompare(t.name))}function J8(e,t){return Object.keys(e).filter(n=>{let r=e[n].filter(e=>!e.clock&&e.noise!==void 0&&e.flatS!==void 0&&e.n&&e.rateHz),i=r.reduce((e,t)=>e+t.n/t.rateHz,0),a=r.reduce((e,t)=>e+(t.flatRuns??0),0);return r.length>0&&r.every(e=>e.noise===0)&&i>0&&r.reduce((e,t)=>e+t.flatS,0)>=.9*i&&!(t>=10&&a>=.5*t)}).sort()}function Y8(e){let t={};for(let n of e.streams)for(let e of n.channels)t[e.name]||(t[e.name]=e.unit);let n={};for(let[t,r]of Object.entries(e.health)){if(r.some(e=>e.clock))continue;let e=V8(r.filter(e=>e.moves!==!1));e&&(n[t]=e)}let r=U8(H8(e.recordings),e.tz),i=G8(r),a=W8(r);return{units:t,ranges:n,energy:Object.keys(t).filter(e=>I8.test(t[e].trim())).sort(),settings:J8(e.health,e.recordings.reduce((e,t)=>e+t.batches.length,0)),shifts:i.shifts,stops:[...i.stops,...a?[a]:[]],lines:K8(e.streams),machines:q8(Object.keys(t))}}function X8(e,t){let n=Object.create(null);for(let[t,r]of Object.entries(e.channels))n[t]=r;for(let e of[...Object.keys(t.units),...Object.keys(t.ranges),...t.settings])n[e]||(n[e]=C3(t.units[e]??``));for(let[e,r]of Object.entries(n)){let i=r;!i.unit&&t.units[e]&&(i={...i,unit:t.units[e],unitSuggested:!0});let a=t.ranges[e];a&&i.lo===null&&i.hi===null&&(i={...i,lo:a.lo,hi:a.hi,rangeSuggested:!0}),t.energy.includes(e)&&i.role===null?i={...i,role:`energy`,suggested:!0}:t.settings.includes(e)&&i.role===null&&(i={...i,role:`setting`,suggested:!0}),n[e]=i}let r=e=>e.map(e=>({...e,suggested:!0})),i=new Set(Object.keys(n));return{...e,channels:n,shifts:e.shifts.length?e.shifts:r(t.shifts),stops:e.stops.length?e.stops:r(t.stops),lines:e.lines.length?e.lines:r(t.lines),units:e.units.length?e.units:r(t.machines.map(e=>({...e,channels:e.channels.filter(e=>i.has(e))})).filter(e=>e.channels.length))}}function Z8(e){let t=new Map,n=(e,n)=>{for(let r of n)t.set(r,[...t.get(r)??[],e])},r=e=>e.filter(e=>e.suggested).length,i=(e,t)=>`${e} ${t}${e===1?``:`s`}`;r(e.shifts)&&n(i(r(e.shifts),`shift`),[`02`,`05`,`06`,`11`]),r(e.stops)&&n(i(r(e.stops),`planned stop`),[`05`,`06`]),r(e.lines)&&n(i(r(e.lines),`line`),[`10`]),r(e.units)&&n(i(r(e.units),`machine unit`),[`05`]);let a=Object.keys(e.channels).filter(t=>e.channels[t].role===`energy`&&e.channels[t].suggested);a.length&&n(`the energy channel ${a.sort()[0]}`,[`09`]);let o=Object.keys(e.channels).filter(t=>e.channels[t].role===`setting`&&e.channels[t].suggested);return o.length&&n(i(o.length,`adjustable setting`),[`08`]),t}var Q8=It({AI_NOTE:()=>j8,AI_SENTENCES:()=>2,AI_WORDS:()=>x8,ALPHA:()=>N2,CHANNEL_ROLES:()=>b3,CHANNEL_ROLE_TEXT:()=>x3,EVIDENCE_TEXT:()=>h4,GOLDEN_SHARE:()=>P2,HealthAcc:()=>r6,MIN_GROUP:()=>5,OFF_GOLDEN_PCT:()=>2,PRESETS:()=>l3,PRESET_IDS:()=>c3,PROCESS_MAX:()=>S3,REPORT_ROLES:()=>m4,SECTION_ROLES:()=>v4,SECTION_TITLES:()=>g4,aiInput:()=>M8,applyAi:()=>N8,applyInferred:()=>X8,applyPreset:()=>y3,assumedSections:()=>Z8,buildReport:()=>v8,classify:()=>L2,completeness:()=>Y3,confirmAll:()=>K3,confirmed:()=>W3,contextGaps:()=>q3,dateText:()=>B4,dateTimeText:()=>V4,emptyChannel:()=>C3,emptyContext:()=>w3,energyChannel:()=>E3,evidenceLabel:()=>X4,exact:()=>T4,goldenRank:()=>F2,inferContext:()=>Y8,listedFindings:()=>y8,moneyGaps:()=>J3,namesOf:()=>g3,num:()=>w4,pText:()=>Y4,parseContext:()=>R3,pct1:()=>S4,presetForIndustry:()=>d3,presetOf:()=>u3,roleOf:()=>T3,shiftOf:()=>V3,spanText:()=>U4,stopSpans:()=>U3,suggestedCount:()=>G3,term:()=>h3,usualRange:()=>i6,viewSections:()=>b8});export{oQ as ANNOTATION_CONTROLS_ATTR,zt as ANNOTATION_KINDS,c1 as AxisState,wB as BEACON_STATS,_2 as BrowserRecorder,k0 as CAMERA_QUALITIES,Ve as CHAIN_LIVE,Ne as CHAIN_RECORDING,b3 as CHANNEL_ROLES,x3 as CHANNEL_ROLE_TEXT,dr as CHART_ALARM_FIELDS,y$ as CHART_KINDS,GB as CYCLE_TIME,z0 as CameraSender,Se as ChainLane,RB as CycleRunner,zB as CycleSet,Yt as DASHBOARD_GRID_COLS,Zt as DASHBOARD_GRID_GAP_PX,Xt as DASHBOARD_GRID_ROWS,rB as DATASET_PALETTE,Bt as DEFAULT_ANNOTATION_WIDTH,fn as DEFAULT_AXIS_LINE,mn as DEFAULT_BEACON,pn as DEFAULT_GRID_LINE,Cn as DEFAULT_TRACE_WIDTH,Sn as DEFAULT_XYZ_POINT_RADIUS,xn as DEFAULT_XY_POINT_RADIUS,h4 as EVIDENCE_TEXT,A2 as EXPORT_TYPES,NT as FUNCTION_REFERENCE,r6 as HealthAcc,AV as IMPORTABLE_EXT,F as KIND_CHAIN,u as KIND_VIDEO,fB as KPI_STATS,Re as KRC_HEADER_BYTES,CB as KpiAcc,HE as KymoscopeError,pt as LEAF_KEYS,n as LIVE_TIME_COLUMN,A0 as LOW_PRESET,O0 as LivePublisher,i1 as MAX_BAND_CELLS,r1 as MAX_GRID,er as MAX_PANEL_CAMERAS,tn as MIN_PANEL_H,en as MIN_PANEL_W,L as OPEN_STREAM_PASSWORD,l3 as PRESETS,c3 as PRESET_IDS,S3 as PROCESS_MAX,m4 as REPORT_ROLES,n0 as RecordedVideoSource,w0 as RegistryError,g4 as SECTION_TITLES,Kt as SEVERITY_HEX,r0 as SPLIT_STEPS,L1 as UNLIMITED,VX as VIDEO_LIMIT_NOTICE,L$ as VIDEO_MAX_FRAGMENT,lE as WINDOW_FN_NAMES,B as WORKBOOK_EXPORT_AAD,M8 as aiInput,p as alertRuleAad,l1 as alignSegment,Q8 as analysis,N8 as applyAi,X8 as applyInferred,y3 as applyPreset,un as arrangeAutoLayout,a1 as axisColumn,g1 as bandEdges,AB as bestCycleIndex,y as bindKeyAad,o2 as bufferLabel,dG as buildEquation,PE as buildMathChannelsBlob,f1 as buildReference,v8 as buildReport,MV as buildTree,Qn as cameraLabel,re as chainVerifier,fr as chartAlarm,Nz as chartChannelCount,x$ as chartLabel,_r as clampPct,rn as clampRectForKind,cr as coerceAlarmLine,Wt as coerceAnnotation,SX as colorAt,iB as colorForDataset,lB as colorSchemeOf,TX as colorsCss,Ze as columnIsNumeric,mB as compareOp,_1 as compareToReference,Y3 as completeness,cG as computePolyFit,lG as computeR2,K3 as confirmAll,W3 as confirmed,Y1 as createEngine,dt as createRuleEvaluator,$B as cutCycle,LB as cycleRuleChannels,tV as cycleTables,EB as cyclicChannels,y1 as decodeBand,tt as decodeChain,B$ as decodeVideo,EZ as decorateColumnLabel,Un as defaultAreaChartPanelSettings,Vn as defaultBarChartPanelSettings,An as defaultBoxPlotPanelSettings,Gn as defaultBubbleChartPanelSettings,Yn as defaultCalibrationPanelSettings,$n as defaultCameraPanelSettings,Wn as defaultCdfChartPanelSettings,Pn as defaultConfusionPanelSettings,Ln as defaultControlChartPanelSettings,aB as defaultDatasetPalette,zn as defaultEmbeddingPanelSettings,Bn as defaultFlameGraphPanelSettings,Zn as defaultGanttPanelSettings,Jn as defaultGaugePanelSettings,Mn as defaultHeatmapPanelSettings,Dn as defaultHistogramPanelSettings,In as defaultLossCurvePanelSettings,wn as defaultMultibandPanelSettings,Rn as defaultParallelCoordsPanelSettings,On as defaultPolarPanelSettings,Xn as defaultQQPlotPanelSettings,Hn as defaultRadarPanelSettings,Fn as defaultRocPanelSettings,qn as defaultSankeyPanelSettings,jn as defaultSpectrogramPanelSettings,kn as defaultSpectrumPanelSettings,s0 as defaultSplit,Kn as defaultTreemapPanelSettings,Nn as defaultViolinPanelSettings,dn as defaultXyAxisScaleSettings,Tn as defaultXyPanelSettings,En as defaultXyzPanelSettings,YB as definitionChannels,We as deriveKey,v as deriveRawKeyBase64,te as deviceFingerprint,an as dragLayout,C3 as emptyChannel,w3 as emptyContext,v1 as encodeBand,st as encodeChain,z$ as encodeVideo,oV as encryptWorkbookFile,E3 as energyChannel,hr as ensurePanelSettingsForPanels,mE as evalChannel,dB as eventWithin,X4 as evidenceLabel,M2 as exportRecording,j2 as exportRecordingTo,fE as extractFreeIdentifiers,E0 as fetchUsage,JB as findCycles,tB as formatClockTick,nB as formatClockValue,MB as formatLapValue,o0 as formatSplit,V$ as fragmentVideo,V as generateApiToken,H as generateDeviceKeyPair,k as generateRecoveryKeyPair,e as generateSalt,$z as getClockTimeZone,Te as getRawNonEmptyLines,d1 as gridAt,DB as guessBeaconChannel,ge as hashToken,Qe as importStreamKey,Y8 as inferContext,ae as inferParseConfig,Gz as isClockAxis,jV as isImportable,TZ as isMathChannelName,XB as kpiColumn,pB as kpiKey,ZB as kpisOf,y8 as listedFindings,b0 as liveBytesPerSec,b1 as liveSegmentTracker,bB as localDay,s1 as localSeconds,Le as makeKeyCheck,Jt as markToAnnotation,J3 as moneyGaps,g3 as namesOf,vn as newGaugeItem,yr as newMathChannel,cn as newPanel,hB as newResetState,se as newRun,vr as newSeriesId,Pz as niceMajorStep,uB as observeColorScheme,CR as openDatasetFromText,c as openMessage,bz as openSession,qe as openUnderProjectKey,Ee as openWithKey,oe as openWithPassword,tr as panelCameras,ze as parseColumnNames,Ye as parseConfigsEqual,R3 as parseContext,WB as parseCycleDefinitions,je as parseDatasetWithConfig,dE as parseFormula,le as parseKrc,Ae as parseKrcHeader,IE as parseMathChannelsFile,bn as parseOptionalAxisRange,mr as parsePanelChartSettingsMap,Be as parseRecoveryCode,a0 as parseSplit,h1 as pooledSd,d3 as presetForIndustry,u3 as presetOf,wX as presetStops,Xe as projectConfigKeyAad,de as projectWrapAad,Me as randomKey,qB as readSource,Fe as recordingKeyAad,Ge as recordingKeySealAad,et as recoveryAttestationAad,me as recoveryCode,ye as recoveryKeyAad,Ue as recoveryPrivateKey,xZ as referenceBands,u1 as resample,gB as resetStep,ur as resolveLinkedAlarms,T3 as roleOf,nV as rowsCsv,T as sealMessage,Pe as sealUnderProjectKey,Ce as sealWithKey,xe as sealWithPassword,ie as senderBindKey,nt as senderBinding,Qz as setClockTimeZone,SB as shiftDay,ct as splitApiKey,TB as splitLaps,ce as streamKeyAad,$e as subsampleIndices,eB as subscribeClockTimeZone,OB as suggestBeacon,G3 as suggestedCount,h3 as term,mt as thresholdOf,yB as tzOffsetS,ot as unwrapForDevice,P as unwrapStreamKey,ft as validateRule,s as verifyKeyCheck,HV as verifyLicense,it as verifySenderBinding,b8 as viewSections,I as workbookBodyAad,rV as workbookExportAad,cV as workbookFileInfo,d as workbookKeyAad,l as wrapForDevice,xB as zonedInstant};
|
|
621
|
+
`)}async hexBodyHash(){let e=this.headers.get(`X-Amz-Content-Sha256`)||(this.service===`s3`&&this.signQuery?`UNSIGNED-PAYLOAD`:null);if(e==null){if(this.body&&typeof this.body!=`string`&&!(`byteLength`in this.body))throw Error(`body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header`);e=Y0(await q0(this.body||``))}return e}};async function K0(e,t){let n=await crypto.subtle.importKey(`raw`,typeof e==`string`?V0.encode(e):e,{name:`HMAC`,hash:{name:`SHA-256`}},!1,[`sign`]);return crypto.subtle.sign(`HMAC`,n,V0.encode(t))}async function q0(e){return crypto.subtle.digest(`SHA-256`,typeof e==`string`?V0.encode(e):e)}var J0=[`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`a`,`b`,`c`,`d`,`e`,`f`];function Y0(e){let t=new Uint8Array(e),n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=J0[r>>>4&15],n+=J0[r&15]}return n}function X0(e){return e.replace(/[!'()*]/g,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase())}function Z0(e,t){let{hostname:n,pathname:r}=e;if(n.endsWith(`.on.aws`)){let e=n.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return e==null?[``,``]:[`lambda`,e[1]||``]}if(n.endsWith(`.r2.cloudflarestorage.com`))return[`s3`,`auto`];if(n.endsWith(`.backblazeb2.com`)){let e=n.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return e==null?[``,``]:[`s3`,e[1]||``]}let i=n.replace(`dualstack.`,``).match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),a=i&&i[1]||``,o=i&&i[2];if(o===`us-gov`)o=`us-gov-west-1`;else if(o===`s3`||o===`s3-accelerate`)o=`us-east-1`,a=`s3`;else if(a===`iot`)a=n.startsWith(`iot.`)?`execute-api`:n.startsWith(`data.jobs.iot.`)?`iot-jobs-data`:r===`/mqtt`?`iotdevicegateway`:`iotdata`;else if(a===`autoscaling`){let e=(t.get(`X-Amz-Target`)||``).split(`.`)[0];e===`AnyScaleFrontendService`?a=`application-autoscaling`:e===`AnyScaleScalingPlannerFrontendService`&&(a=`autoscaling-plans`)}else o==null&&a.startsWith(`s3-`)?(o=a.slice(3).replace(/^fips-|^external-1/,``),a=`s3`):a.endsWith(`-fips`)?a=a.slice(0,-5):o&&/-\d$/.test(a)&&!/-\d$/.test(o)&&([a,o]=[o,a]);return[H0[a]||a,o||``]}var Q0=1e4,$0=2e3,e2=1e4,t2=6e4,n2=2e3,r2=6e4,i2=`rec`,a2=`meta.json`,o2=e=>Math.min(r2,Math.max(n2,e*2)),s2=e=>e>=1024?`${+(e/1024).toFixed(2)} GB`:`${e} MB`,c2=e=>e.replace(/(https?:\/\/[^\s?#'"]*)\?[^\s#'"]*/g,`$1`),l2=class extends Error{status;constructor(e,t){super(c2(e)),this.status=t}},u2=e=>e instanceof l2?void 0:e?.status,d2=e=>e?.code??String(u2(e)??`error`),f2=e=>`${String(e).padStart(8,`0`)}.krc`,p2=e=>{let t=Uint8Array.from(e.replace(/-/g,``).match(/../g)??[],e=>parseInt(e,16));if(t.length!==16)throw Error(`bad_recording_id`);return t},m2=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``);async function h2(e,t,n){let r=await(await e.getFileHandle(t,{create:!0})).createWritable();await r.write(n),await r.close()}async function g2(e,t){try{return JSON.parse(await(await(await e.getFileHandle(t)).getFile()).text())}catch{return null}}function _2(e,t){return new Promise(n=>{e.request(t,{ifAvailable:!0},e=>{if(!e){n(null);return}return new Promise(e=>n(e))}).catch(()=>n(null))})}var v2=class{streamId;parentStreamId;bufferMaxMB;dropped=0;usedBytes=0;storage;opts;now;fetch;locks;rootDir=null;parent=void 0;polledAt=-1/0;polling=!1;cutAt=1/0;noneSince=null;file=null;chunk=null;continues=!1;prev=null;lost=new Set;io=Promise.resolve();writing=new Set;held=new Map;opened=new Map;blocked=new Set;wait=new Map;said=new Set;fullSaid=!1;refusedUntil=0;closing=!1;stopped=!1;wake=null;loop=null;constructor(e){this.opts=e,this.streamId=e.streamId,this.parentStreamId=e.parentStreamId,this.bufferMaxMB=e.bufferMaxMB??2048,this.storage=e.storage??null,this.now=e.now??Date.now,this.fetch=e.fetch??((...e)=>fetch(...e)),this.locks=e.locks===void 0?typeof navigator<`u`&&navigator.locks||null:e.locks,e.autostart!==!1&&(this.loop=this.run())}wants(){return!!this.file||!!this.parent}splitEvery=null;get currentId(){return this.file?.id??null}setStorage(e){this.storage=e,this.blocked.clear();for(let e of[...this.said])e.startsWith(`storage:`)&&this.said.delete(e);this.wake?.()}add(e,t,n){if(this.closing)return;this.pollDue()&&this.pollParent();let r=this.parent??null,i=this.file;if(i&&r===null&&this.noneSince!==null&&this.now()-this.noneSince>=3e4?this.endFile(!1,`stopped`):i&&r!==null&&n&&i.meta.parent!==r&&this.endFile(!0,`stopped`),!this.file){if(!r||!n||this.now()<this.refusedUntil)return;this.openFile(t,r)}let a=this.chunk;a&&(a.bytes+12+e.length>4194304||Math.abs(t-a.records[0].at)>=6e4)&&(this.flush(),a=null),a??=this.chunk={records:[],bytes:56,opened:this.now()},a.records.push({at:t,bytes:e}),a.bytes+=12+e.length}tick(){this.chunk&&this.now()-this.chunk.opened>=6e4&&this.flush()}stop(){this.file&&this.endFile(!1,`stopped`),this.continues=!1}async pollParent(){if(!this.polling){this.polling=!0,this.polledAt=this.now();try{let e=await this.opts.call({action:`current`,stream_id:this.parentStreamId}),t=typeof e.recording_id==`string`?e.recording_id:null,n=typeof e.split_every==`number`&&e.split_every>0?e.split_every:null,r=this.now();this.noneSince=t===null?this.noneSince??r:null,t!==null&&(t!==this.parent||n!==this.splitEvery)&&(this.splitEvery=n,this.cutAt=n?l0(r,n,-new Date(r).getTimezoneOffset()*60):1/0),this.parent=t}catch{}finally{this.polling=!1}}}pollDue(){let e=this.now();if(e>=this.cutAt&&this.polledAt<this.cutAt)return!0;let t=e>=this.cutAt&&e<this.cutAt+6e4||!!this.file&&this.parent===null;return e-this.polledAt>=(t?$0:Q0)}root(){return this.rootDir??=(async()=>(this.opts.root?await this.opts.root():await navigator.storage.getDirectory()).getDirectoryHandle(i2,{create:!0}))().catch(e=>{throw this.rootDir=null,e})}queue(e){this.io=this.io.then(e).catch(e=>{e?.name!==`NotFoundError`&&this.say(`disk`,`disk_error`,`Can't write the recording buffer: ${e?.message??e}`)})}openFile(e,t){let n=crypto.randomUUID(),r={stream_id:this.streamId,kind:`camera`,parent:t,continues:this.continues,prev:this.continues?this.prev:null,t0:e,closed:!1};this.file={id:n,seq:0,meta:r},this.writing.add(n),this.queue(async()=>{if(this.locks){let e=await _2(this.locks,`kymoscope-rec-${n}`);e&&this.held.set(n,e)}await h2(await(await this.root()).getDirectoryHandle(n,{create:!0}),a2,JSON.stringify(r))})}endFile(e,t){let n=this.file;this.flush(),this.file=this.chunk=null,this.continues=e,this.prev=n.id,n.meta={...n.meta,closed:!0,reason:t};let r=JSON.stringify(n.meta);this.queue(async()=>{try{await h2(await(await this.root()).getDirectoryHandle(n.id),a2,r)}finally{this.writing.delete(n.id)}})}flush(){let e=this.chunk,t=this.file;if(this.chunk=null,!e?.records.length||!t)return;let n=t.seq++,r=e.records;this.queue(async()=>{await this.checkpoint(t.id,n,r);let e=Je(t.id,n,r),i=new DataView(e.buffer);i.setFloat64(40,Math.min(...r.map(e=>e.at)),!0),i.setFloat64(48,Math.max(...r.map(e=>e.at)),!0),await h2(await(await this.root()).getDirectoryHandle(t.id),f2(n),e),await this.enforceMax()})}async checkpoint(e,t,n){if(!this.opts.seal)return;let r;try{let i=m2((await crypto.subtle.digest(`SHA-256`,p2(e))).slice(0,8));r=st({streamId:this.streamId,run:i,lane:1,seq:BigInt(t),count:n.length,hash:await be(n.map(e=>crypto.subtle.digest(`SHA-256`,e.bytes)))})}catch{return}let i=await this.opts.seal(8,r).catch(()=>null);i&&n.push({at:n[n.length-1].at,bytes:i})}async enforceMax(){let e=await this.root(),t=0,n=[];for await(let[r,i]of e.entries()){if(i.kind!==`directory`)continue;let e=(await g2(i,a2))?.t0??0;try{for await(let[a,o]of i.entries()){if(o.kind!==`file`)continue;let s=(await o.getFile()).size;t+=s,a.endsWith(`.krc`)&&n.push({t0:e,seq:parseInt(a,10),dir:i,id:r,name:a,size:s})}}catch{}}n.sort((e,t)=>e.t0-t.t0||e.seq-t.seq);let r=this.bufferMaxMB*1024*1024,i=0,a=new Map;for(let e of n){if(t<=r)break;try{await e.dir.removeEntry(e.name)}catch{continue}t-=e.size,i++,a.set(e.id,e.dir)}for(let[e,t]of a){if(e===this.file?.id)continue;let n=!1;try{for await(let[e]of t.entries())n||=e.endsWith(`.krc`)}catch{}n||this.lost.add(e)}this.usedBytes=t,i&&(this.dropped+=i,this.fullSaid||(this.fullSaid=!0,this.status({type:`buffer_full`,message:`Recording buffer full: dropped the oldest ${i} chunks`})))}status(e){try{this.opts.onStatus?.(e)}catch{}}say(e,t,n,r){this.said.has(e)||(this.said.add(e),this.status({type:t,message:n,...r?{reason:r}:{}}))}async claim(e,t){if(this.held.has(t)||this.writing.has(t))return!0;if(this.locks){let e=await _2(this.locks,`kymoscope-rec-${t}`);if(!e)return!1;this.held.set(t,e)}let n=await e.getDirectoryHandle(t).catch(()=>null);return!n||!await g2(n,a2)?(this.release(t),await e.removeEntry(t,{recursive:!0}).catch(()=>{}),!1):(this.locks||this.held.set(t,()=>{}),!0)}release(e){this.held.get(e)?.(),this.held.delete(e)}async files(){let e=await this.root(),t=[];for await(let[n,r]of e.entries())r.kind===`directory`&&t.push(n);let n=[];for(let r of t){if(!await this.claim(e,r))continue;let t=await e.getDirectoryHandle(r).catch(()=>null),i=t&&await g2(t,a2);t&&i?.stream_id&&n.push({id:r,meta:i,dir:t})}return n.sort((e,t)=>e.meta.t0-t.meta.t0||(e.id<t.id?-1:1))}async forget(e,t=!0){this.opened.delete(e),t&&this.lost.add(e),this.file?.id===e&&(this.file=this.chunk=null,this.writing.delete(e),this.continues=!1),this.release(e),await(await this.root()).removeEntry(e,{recursive:!0}).catch(()=>{})}async open(e,t){let n={action:`open`,recording_id:t.id??e,stream_id:t.stream_id,kind:t.kind,continues:!!t.continues&&!this.lost.has(t.prev??``),t0:t.t0,parent_recording_id:t.parent};this.opts.retentionDays!==void 0&&(n.retention_days=this.opts.retentionDays);let r=await this.opts.call(n);if(r.record===!1){let t=String(r.reason??`refused`);return t===`parent_not_found`?(this.wait.set(e,this.now()+e2),null):(this.say(`refused:${t}`,`refused`,String(r.message??`Recording refused (${t})`),t),e===this.file?.id&&(this.refusedUntil=this.now()+t2),await this.forget(e),null)}let i=r.destination??`kymoscope`;if(i!==`kymoscope`&&!this.storage?.[i.kind]){this.blocked.add(e);let t=`storage:${i.id}`;return this.said.has(t)||(this.said.add(t),this.status({type:`storage_needed`,destination:i,message:i.kind===`folder`?`This project records to ${i.name}: choose its folder to store the camera's files`:`This project records to ${i.name}: this sender needs its S3 keys (storage)`})),null}let a=i===`kymoscope`?`Kymoscope`:i.name;if(!this.said.has(`destination:${a}`)){this.said.add(`destination:${a}`);let e=this.splitEvery?`every ${s0(this.splitEvery)}`:`cut with its data stream's`;this.status({type:`destination`,name:a,splitEvery:this.splitEvery,message:`Recording files: ${e} → ${a} (buffer ${s2(this.bufferMaxMB)})`})}return this.opened.set(e,i),i}async put(e,t,n){let r;try{r=await this.fetch(e,t?{method:`PUT`,body:t,headers:n}:void 0)}catch(e){throw new l2(`chunk upload failed: ${e?.message??e}`)}if(!r.ok)throw new l2(`chunk upload failed: HTTP ${r.status}`,r.status)}async writeOwn(e,t,n,r){let{folder:i,s3:a}=this.storage??{};if(i){try{await h2(await(await i.getDirectoryHandle(e.stream_id,{create:!0})).getDirectoryHandle(t,{create:!0}),f2(n),r)}catch(e){throw new l2(`can't write to the folder: ${e?.message??e}`)}return}let o=(a.prefix??``).replace(/^\/+|\/+$/g,``),s=`${o?`${o}/`:``}${e.stream_id}/${t}/${f2(n)}`,c=`${a.endpoint.replace(/\/+$/,``)}/${a.bucket?`${a.bucket}/`:``}${s}`,l=new W0({accessKeyId:a.accessKeyId,secretAccessKey:a.secretAccessKey,service:`s3`,region:a.region||`us-east-1`});await this.put(await l.sign(c,{method:`PUT`,body:r}))}dropChunk(e,t,n){return this.say(`chunk:${n}`,`chunk_dropped`,`A recording chunk was dropped (${n})`),e.removeEntry(t).catch(()=>{})}async uploadChunk(e,t,n,r){let i=t.id??e,a;try{a=new Uint8Array(await(await(await n.getFileHandle(r)).getFile()).arrayBuffer())}catch{return}let o;try{o=Ae(a)}catch{o=null}if(!o||o.bytes!==a.length)return this.dropChunk(n,r,`unreadable on disk`);let s=parseInt(r,10),c=m2(await crypto.subtle.digest(`SHA-256`,a));try{let e=await this.opts.call({action:`chunk`,recording_id:i,seq:s,bytes:a.length,sha256:c});e.own?await this.writeOwn(t,i,s,a):await this.put(String(e.url),a,{Authorization:`Bearer ${e.ticket}`}),await this.opts.call({action:`confirm`,recording_id:i,seq:s,bytes:a.length,messages:o.count,t0:o.t0,t1:o.t1,sha256:c})}catch(e){if(u2(e)===400)return this.dropChunk(n,r,`refused: ${d2(e)}`);if(u2(e)!==409||d2(e)!==`chunk_exists`)throw e}await n.removeEntry(r).catch(()=>{}),this.usedBytes=Math.max(0,this.usedBytes-a.length),this.fullSaid=!1,this.said.delete(`put`)}async reopen(e,t){let n=!1;for await(let[e]of t.entries())n||=e.endsWith(`.krc`);if(!n&&this.file?.id!==e)return!1;this.file?.id===e&&this.endFile(!1,`stopped`),await this.io;let r=await g2(t,a2);return r?(await h2(t,a2,JSON.stringify({...r,id:crypto.randomUUID(),continues:!1,prev:null})),this.opened.delete(e),!0):!1}async uploadPending(){let e=!0;for(let{id:t,meta:n,dir:r}of await this.files()){if(this.blocked.has(t))continue;if(this.now()<(this.wait.get(t)??0)){e=!1;continue}let i=n.closed||!this.writing.has(t);try{if(!(this.opened.get(t)??await this.open(t,n))){!this.blocked.has(t)&&(this.held.has(t)||this.writing.has(t))&&(e=!1);continue}let a=[];for await(let[e,t]of r.entries())t.kind===`file`&&e.endsWith(`.krc`)&&a.push(e);for(let e of a.sort())await this.uploadChunk(t,n,r,e);i?(await this.opts.call({action:`close`,recording_id:n.id??t,reason:n.reason??`stopped`}),await this.forget(t,!1)):e=!1}catch(n){let i=u2(n);if(i===404&&this.opened.has(t)&&await this.reopen(t,r)){e=!1;continue}if(i===403||i===404||i===410||i===400){this.say(`gone:${t}`,`refused`,`A recording file was refused (${d2(n)}): its chunks were dropped`,d2(n)),await this.forget(t);continue}throw n instanceof l2&&n.status!==401&&this.say(`put`,`storage_error`,`Can't store recording chunks (${n.message}); retrying`),n}}return e}async run(){let e=0;for(;!this.stopped;){let t=!1;try{this.tick(),this.pollDue()&&await this.pollParent(),t=await this.uploadPending(),e=0}catch{e=o2(e)}if(this.closing&&(t||e))break;await new Promise(t=>{this.wake=t,setTimeout(t,e||1e3)}),this.wake=null}}async close(e=3e3){this.stop(),this.closing=!0,this.wake?.(),this.loop?await Promise.race([this.loop,new Promise(t=>setTimeout(t,e))]):await this.io,this.stopped=!0,this.wake?.();for(let e of[...this.held.keys()])this.release(e)}},y2=class{#e;constructor(e){this.#e=e}head(){let e=this.#e;return`${e.map(e=>Q$(e.name)).join(`,`)}\n${e.map(e=>Q$(e.unit)).join(`,`)}\n`}append(e){let t=e.columns,n=``;for(let r=0;r<e.length;r++){for(let e=0;e<t.length;e++){let i=t[e][r];n+=(e?`,`:``)+(Number.isNaN(i)?``:String(i))}n+=`
|
|
622
|
+
`}return n}end(){}},b2=new TextEncoder,x2=e=>e+7&-8,S2=104,C2=64,w2=104,T2=160,E2=4;function D2(e,t,n){let r=24+t.length*8+n.length,i=new Uint8Array(x2(r)),a=new DataView(i.buffer);return i.set(b2.encode(e),0),a.setBigUint64(8,BigInt(r),!0),a.setBigUint64(16,BigInt(t.length),!0),t.forEach((e,t)=>a.setBigUint64(24+t*8,BigInt(e),!0)),i.set(n,24+t.length*8),i}var O2=(e,t)=>D2(e,[],b2.encode(`${t}\0`)),k2=e=>BigInt(Math.round(e))*1000000n,A2=class{#e;#t;#n;#r=0;constructor(e,t,n){this.#e=e,this.#t=t?Date.parse(t):Date.now(),this.#n=n}append(e){let t=e.columns,n=t.length,r=new Float64Array(e.length*n);for(let i=0;i<e.length;i++)for(let e=0;e<n;e++)r[i*n+e]=t[e][i];return this.#r+=e.length,new Uint8Array(r.buffer)}end(){if(this.#r!==this.#n)throw Error(`The recording changed while it was exported (${this.#r} of ${this.#n} rows).`)}head(){let e=this.#e.length,t=[],n=64+S2,r=e=>{let r=n;return t.push(e),n+=e.length,r},i=r(O2(`##MD`,`<FHcomment><TX>Kymoscope cloud recording</TX><tool_id>Kymoscope</tool_id><tool_vendor>Kymoscope</tool_vendor><tool_version>1</tool_version></FHcomment>`)),a=new Uint8Array(16);new DataView(a.buffer).setBigUint64(0,k2(this.#t),!0);let o=r(D2(`##FH`,[0,i],a)),s=this.#e.map(e=>r(O2(`##TX`,e.name))),c=this.#e.map(e=>e.unit?r(O2(`##TX`,e.unit)):0),l=n,u=l+C2,d=this.#e.map((e,t)=>u+w2+t*T2),f=D2(`##DG`,[0,u,u+w2+e*T2,0],new Uint8Array(8)),p=new Uint8Array(32),m=new DataView(p.buffer);m.setBigUint64(8,BigInt(this.#n),!0),m.setUint32(24,e*8,!0);let h=D2(`##CG`,[0,d[0],0,0,0,0],p),g=this.#e.map((t,n)=>{let r=new Uint8Array(72),i=new DataView(r.buffer);return i.setUint8(0,n===0?2:0),i.setUint8(1,+(n===0)),i.setUint8(2,E2),i.setUint32(4,n*8,!0),i.setUint32(8,64,!0),i.setUint8(20,255),D2(`##CN`,[n+1<e?d[n+1]:0,0,s[n],0,0,0,c[n],0],r)}),_=new Uint8Array(24);_.set(b2.encode(`##DT`),0),new DataView(_.buffer).setBigUint64(8,BigInt(24+this.#n*e*8),!0);let v=new Uint8Array(64);v.set(b2.encode(`MDF 4.10 Kymoscop`),0),new DataView(v.buffer).setUint16(28,410,!0);let y=new Uint8Array(32);new DataView(y.buffer).setBigUint64(0,k2(this.#t),!0);let b=[v,D2(`##HD`,[l,o,0,0,0,0],y),...t,f,h,...g,_],x=new Uint8Array(b.reduce((e,t)=>e+t.length,0));return b.reduce((e,t)=>(x.set(t,e),e+t.length),0),x}},j2={csv:`text/csv`,mf4:`application/octet-stream`};async function M2(e,t,n,r={}){let i=bz(`krc`,{main:new File(e.chunks,`${e.name}.krc`),companions:[],keys:e.keys},r.signal,r.createWorker);try{let e=await i.plan(),a=[{group:0,channels:e.groups[0].channels.map((e,t)=>t)}],o=t===`csv`?new y2(cz(e,a)):new A2(cz(e,a),e.startTime,e.groups[0].samples);await n(o.head()),await i.read(a,`stream`,{chunk:async e=>{await n(o.append(e))},progress:r.onProgress}),o.end()}finally{i.close()}}async function N2(e,t,n={}){let r=[];return await M2(e,t,e=>{r.push(e)},n),new Blob(r,{type:j2[t]})}var P2=.01,F2=.05,I2=e=>Math.max(5,Math.ceil(e*F2)),L2=e=>Math.max(Math.abs(e.value)*2/100,2*e.spread);function R2(e){let t=new Map(e.goldens.map(e=>[e.streamId,e])),n=[];for(let r of e.cycles){let i=t.get(r.streamId);if(!i||r.value===null||!Number.isFinite(r.value)||r.tend===null||r.flag===`excluded`)continue;let a=e.value.better===`min`?r.value-i.value:i.value-r.value,o=L2(i);n.push({c:r,g:i,gap:a,level:a>o?`off`:a<-o?`better`:`golden`})}return n.sort((e,t)=>e.c.tstart-t.c.tstart)}var z2=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>Number.isFinite(e)));function B2(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}var V2=(e,t)=>H2(e,e=>Math.floor((e.t-t)/86400)),H2=(e,t)=>[...B2(e,t).values()].map(e=>({t:W2(e.map(e=>e.t)),v:W2(e.map(e=>e.v))})),U2=e=>typeof e==`number`&&Number.isFinite(e);function W2(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return e.length?t/e.length:NaN}function G2(e){if(e.length<2)return 0;let t=W2(e),n=0;for(let r=0;r<e.length;r++)n+=(e[r]-t)**2;return Math.sqrt(n/(e.length-1))}function K2(e,t){let n=Array.from(e).filter(Number.isFinite).sort((e,t)=>e-t);if(!n.length)return NaN;let r=(n.length-1)*t,i=Math.floor(r);return i+1<n.length?n[i]+(r-i)*(n[i+1]-n[i]):n[i]}var q2=e=>K2(e,.5);function J2(e){let t=q2(e);return 1.4826*q2(Array.from(e,e=>Math.abs(e-t)))}function Y2(e,t){return(e-q2(t))/Math.max(J2(t),1e-12)}function X2(e){let t=Math.abs(e)/Math.SQRT2,n=1/(1+.3275911*t),r=1-((((1.061405429*n-1.453152027)*n+1.421413741)*n-.284496736)*n+.254829592)*n*Math.exp(-t*t);return e>=0?(1+r)/2:(1-r)/2}var Z2=e=>Math.min(1,2*(1-X2(Math.abs(e))));function Q2(e,t){let n=e.length,r=t.length;if(n<2||r<2)return{u:NaN,p:1,effect:.5};let i=[...e.map(e=>({v:e,g:0})),...t.map(e=>({v:e,g:1}))].sort((e,t)=>e.v-t.v),a=i.length,o=0,s=0;for(let e=0;e<a;){let t=e;for(;t<a&&i[t].v===i[e].v;)t++;let n=(e+1+t)/2;for(let r=e;r<t;r++)i[r].g===0&&(o+=n);s+=(t-e)**3-(t-e),e=t}let c=o-n*(n+1)/2,l=Math.sqrt(n*r/12*(a+1-s/(a*(a-1))));return{u:c,p:l>0?Z2((c-n*r/2)/l):1,effect:c/(n*r)}}function $2(e){if(e<.5)return Math.log(Math.PI/Math.sin(Math.PI*e))-$2(1-e);let t=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7];--e;let n=t[0],r=e+7.5;for(let r=1;r<9;r++)n+=t[r]/(e+r);return .5*Math.log(2*Math.PI)+(e+.5)*Math.log(r)-r+Math.log(n)}function e4(e,t,n){let r=1e-300,i=e=>Math.abs(e)<r?r:e,a=1,o=1/i(1-(t+n)*e/(t+1)),s=o;for(let r=1;r<=300;r++){let c=2*r,l=r*(n-r)*e/((t-1+c)*(t+c));o=1/i(1+l*o),a=i(1+l/a),s*=o*a,l=-(t+r)*(t+n+r)*e/((t+c)*(t+1+c)),o=1/i(1+l*o),a=i(1+l/a);let u=o*a;if(s*=u,Math.abs(u-1)<1e-14)break}return s}function t4(e,t,n){if(e<=0)return 0;if(e>=1)return 1;let r=Math.exp($2(t+n)-$2(t)-$2(n)+t*Math.log(e)+n*Math.log(1-e));return e<(t+1)/(t+n+2)?r*e4(e,t,n)/t:1-r*e4(1-e,n,t)/n}function n4(e,t){let n=.5*t4(t/(t+e*e),t/2,.5);return e>0?1-n:n}var r4=(e,t)=>t4(t/(t+e*e),t/2,.5);function i4(e,t){let n=-1e7,r=1e7;for(let i=0;i<120;i++){let i=(n+r)/2;n4(i,t)<e?n=i:r=i}return(n+r)/2}function a4(e,t,n,r){let i=e+n,a=t+r,o=(e,t)=>$2(e+1)-$2(t+1)-$2(e-t+1),s=e=>o(t,e)+o(r,i-e)-o(a,i),c=s(e),l=0;for(let e=Math.max(0,i-r);e<=Math.min(i,t);e++){let t=s(e);t<=c+1e-7&&(l+=Math.exp(t))}return Math.min(1,l)}function o4(e,t,n,r){let i=t?e/t:NaN,a=r?n/r:NaN;if(!t||!r)return{p1:i,p2:a,p:1};let o=t+r,s=e+n;if(Math.min(t,r)*Math.min(s,o-s)/o<5)return{p1:i,p2:a,p:a4(e,t,n,r)};let c=s/o,l=Math.sqrt(c*(1-c)*(1/t+1/r));return{p1:i,p2:a,p:l>0?Z2((i-a)/l):1}}function s4(e,t){let n=e.map((e,t)=>t).sort((t,n)=>e[t]-e[n]),r=e.length,i=0;n.forEach((n,a)=>{e[n]<=(a+1)/r*t&&(i=a+1)});let a=e.map(()=>!1);for(let e=0;e<i;e++)a[n[e]]=!0;return a}function c4(e,t){let n=W2(e),r=W2(t),i=0,a=0,o=0;for(let s=0;s<e.length;s++)i+=(e[s]-n)*(t[s]-r),a+=(e[s]-n)**2,o+=(t[s]-r)**2;return a>0&&o>0?i/Math.sqrt(a*o):0}function l4(e,t){let n=e.length;if(n<3)return null;let r=W2(e),i=W2(t),a=0,o=0,s=0;for(let c=0;c<n;c++)a+=(e[c]-r)**2,o+=(e[c]-r)*(t[c]-i),s+=(t[c]-i)**2;if(!(a>0))return null;let c=o/a,l=i-c*r,u=Math.max(0,s-c*o),d=Math.sqrt(u/(n-2)),f=d/Math.sqrt(a);return{a:l,b:c,se:f,p:f>0?r4(c/f,n-2):0,r2:s>0?1-u/s:0,n,s:d,mx:r,sxx:a}}function u4(e,t){let n=t.length,r=e[0]?.length??0;if(n<=r+1)return null;let i=Array.from({length:r},(t,r)=>{let i=0;for(let t=0;t<n;t++)i+=e[t][r];return i/n}),a=W2(t),o=Array.from({length:r},()=>new Float64Array(r+1)),s=0;for(let c=0;c<n;c++){let n=t[c]-a;s+=n*n;for(let t=0;t<r;t++){let a=e[c][t]-i[t];for(let n=0;n<r;n++)o[t][n]+=a*(e[c][n]-i[n]);o[t][r]+=a*n}}let c=Math.max(...o.map((e,t)=>e[t]));for(let e=0;e<r;e++){let t=e;for(let n=e+1;n<r;n++)Math.abs(o[n][e])>Math.abs(o[t][e])&&(t=n);if(!(Math.abs(o[t][e])>1e-12*c))return null;[o[e],o[t]]=[o[t],o[e]];for(let t=0;t<r;t++){if(t===e)continue;let n=o[t][e]/o[e][e];for(let i=e;i<=r;i++)o[t][i]-=n*o[e][i]}}let l=o.map((e,t)=>e[r]/e[t]),u=0;for(let o=0;o<n;o++){let n=a;for(let t=0;t<r;t++)n+=l[t]*(e[o][t]-i[t]);u+=(t[o]-n)**2}let d=G2(t);return{beta:l,std:l.map((t,n)=>d>0?t*G2(e.map(e=>e[n]))/d:0),r2:s>0?1-u/s:0}}function d4(e,t){let n=u4(e,t);return n?{shares:n.std.map((n,r)=>n*c4(e.map(e=>e[r]),t)),r2:n.r2}:null}function f4(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}var p4=2e3;function m4(e,t,{B:n=1e3,seed:r=1,alpha:i=.05}={}){let a=f4(r),o=[],s=Math.min(e,p4);for(let r=0;r<n;r++)o.push(t(Array.from({length:s},()=>Math.floor(a()*e))));let c=K2(o,i/2),l=K2(o,1-i/2);if(s<e){let n=t(Array.from({length:e},(e,t)=>t)),r=Math.sqrt(s/e);c=n+(c-n)*r,l=n+(l-n)*r}return{lo:c,hi:l}}var h4=[`management`,`quality`,`maintenance`,`production`],g4={measured:{label:`Measured`,meaning:`Read directly from the data. No model involved.`},trial:{label:`Confirmed by trial`,meaning:`A deliberate change with a before/after comparison.`},statistical:{label:`Statistical`,meaning:`A difference between groups of batches, with its p-value: the chance of a difference this large if there were none.`},correlation:{label:`Correlation`,meaning:`Two signals move together. A lead to test, not a proven cause.`},engineer:{label:`Confirmed by engineer`,meaning:`An engineer checked the finding and signed it in the report.`}},_4={"00":`Executive summary`,"01":`Since the last period`,"02":`Why batches miss the golden`,"03":`Better than the golden`,"04":`Quality: capability and containment`,"05":`Reliability and maintenance`,"06":`OEE and where time is lost`,"07":`Alerts that come before bad batches`,"08":`Changes detected`,"09":`Energy, cost and CO₂`,10:`Compared with the other lines`,11:`Shifts compared`,12:`Recommended actions`,13:`Next analyses to run`,14:`Method, evidence and approval`},v4=[...h4],y4={"00":v4,"01":[`management`],"02":[`quality`,`production`],"03":[`quality`,`production`],"04":[`quality`],"05":[`maintenance`],"06":[`management`,`maintenance`,`production`],"07":[`quality`,`production`],"08":[`quality`,`maintenance`],"09":[`management`],10:[`management`],11:[`quality`,`production`],12:v4,13:[`quality`,`production`],14:[`quality`]},b4=e=>`${e}. Supports your review; does not certify.`,x4=(e,t,n,r,i=[])=>({id:e,title:_4[e],verdict:t,roles:y4[e],findings:n,charts:r,notes:i,...n.length>3?{shown:3}:{}}),S4=e=>`${Math.round(e*100)}%`,C4=e=>`${Math.abs(e)>=10?Math.round(e):+e.toFixed(1)}%`;function w4(e,t){let n=Math.abs(e)<100?2:0;return new Intl.NumberFormat(`en-GB`,{style:`currency`,currency:t,minimumFractionDigits:n,maximumFractionDigits:n}).format(e)}var T4=e=>Number.isFinite(e)?Math.abs(e)>=1e3?Math.round(e).toLocaleString(`en-GB`):String(+e.toPrecision(Math.abs(e)<1?2:3)):`—`,E4=e=>Number.isFinite(e)?String(+e.toPrecision(4)):`—`,D4=(...e)=>k4(e=>Math.abs(e)<1?2:3,e),O4=(...e)=>k4(()=>4,e);function k4(e,t){let n=n=>t.map(t=>Number.isFinite(t)?String(+t.toPrecision(Math.min(17,e(t)+n))):`—`);for(let e=0;e<14;e++){let r=n(e);if(t.every((e,n)=>t.every((t,i)=>Object.is(e,t)||r[n]!==r[i])))return r}return n(14)}var A4=e=>`${e>0?`+`:e<0?`−`:``}${T4(Math.abs(e))}`;function j4(e){return e>=3600?`${T4(e/3600)} h`:e>=60?`${Math.round(e/60)} min`:`${Math.round(e)} s`}function M4(e){let t=e.value.key,n=t.lastIndexOf(`:`);return t===`duration`?`s`:e.units[t]??(n>0&&/^(mean|min|max|first|last|median|std|range)$/.test(t.slice(n+1))?e.units[t.slice(0,n)]??``:``)}var N4=e=>e===1?`once`:e===2?`twice`:`${e} times`,P4=(e,t,n=`${t}s`)=>`${e.toLocaleString(`en-GB`)} ${e===1?t:n}`,F4=e=>e.length<=1?e.join(``):`${e.slice(0,-1).join(`, `)} and ${e[e.length-1]}`,I4=e=>e.charAt(0).toUpperCase()+e.slice(1),L4=e=>e.charAt(0).toLowerCase()+e.slice(1);function R4(e){try{return new Intl.DateTimeFormat(`en-GB`,{timeZone:e}),!0}catch{return!1}}var z4=new Map,B4=(e,t)=>{let n=`${e}|${JSON.stringify(t)}`,r=z4.get(n);return r||z4.set(n,r=new Intl.DateTimeFormat(`en-GB`,{timeZone:R4(e)?e:`UTC`,...t})),r},V4=(e,t)=>B4(t,{day:`numeric`,month:`short`}).format(new Date(e*1e3)),H4=(e,t)=>B4(t,{day:`numeric`,month:`short`,hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}).format(new Date(e*1e3)),U4=(e,t)=>B4(t,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}).format(new Date(e*1e3)),W4=(e,t,n,r=`–`)=>`${H4(e,n)}${r}${V4(e,n)===V4(t,n)?U4(t,n):H4(t,n)}`,G4=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function K4(e,t){let n=B4(t,{weekday:`short`,hour:`2-digit`,hourCycle:`h23`}).formatToParts(new Date(e*1e3));return{day:G4.indexOf(n.find(e=>e.type===`weekday`).value),hour:Number(n.find(e=>e.type===`hour`).value)%24}}var q4=(e,t)=>`${G4[K4(e,t).day]} ${H4(e,t)}`,J4={min:`minimum`,max:`maximum`,mean:`mean`,integral:`integral`,first:`at start`,last:`at end`,delta:`change`};function Y4(e){if(e===`duration`)return`Cycle duration`;let t=e.lastIndexOf(`:`);return t<0?e:`${e.slice(0,t)} ${J4[e.slice(t+1)]??e.slice(t+1)}`}var X4=e=>e<.01?`p < 0.01`:`p = ${e.toFixed(2)}`;function Z4(e){let t=e.numbers.r,n=e.evidence===`correlation`&&Number.isFinite(t)?`r = ${t.toFixed(2)}`:e.p===null?``:X4(e.p);return n?`${g4[e.evidence].label} · ${n}`:g4[e.evidence].label}var Q4=3600,$4=(e,t)=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i]<t?n=i+1:r=i}return n};function e3(e,t){let n=e.alertRules??[];if(!n.length)return null;let r=e.alerts??[],i=new Map,a=new Map,o=new Set;for(let e of r){let t=`${e.rule}|${e.streamId}`;if(o.has(`${t}|${e.t}`))continue;o.add(`${t}|${e.t}`);let n=i.get(t);n||i.set(t,n=[]),n.push(e.t),a.set(e.rule,(a.get(e.rule)??0)+1)}for(let e of i.values())e.sort((e,t)=>e-t);let s=(e,t)=>{let n=i.get(`${t}|${e.c.streamId}`);if(!n)return!1;let r=$4(n,e.c.tstart-Q4);return r<n.length&&n[r]<=(e.c.tend??e.c.tstart)},c=e=>({section:x4(`07`,e,[],[]),actions:[],next:[],numbers:{}}),l=n.filter(e=>a.has(e.id));if(!l.length)return c(`No alert fired in this period.`);let u=t.filter(e=>e.level===`off`),d=t.filter(e=>e.level!==`off`);if(!u.length)return c(`No batch missed the golden, so no alert can be linked to one.`);if(u.length<5||d.length<5)return c(`${P4(u.length,`off-golden batch`,`off-golden batches`)} in this period: 5 are needed to link alerts to them.`);let f=l.map(e=>{let t=u.filter(t=>s(t,e.id)).length,n=d.filter(t=>s(t,e.id)).length;return{r:e,k1:t,t:o4(t,u.length,n,d.length)}}),p=s4(f.map(e=>e.t.p),P2),m=f.filter((e,t)=>p[t]&&e.t.p1>e.t.p2).sort((e,t)=>t.t.p1-t.t.p2-(e.t.p1-e.t.p2)),h=[],g=[],_=new Map;for(let e of m){let n=`F07-${h.length+1}`;_.set(e.r.id,n),h.push({id:n,section:`07`,refs:[`07`],evidence:`statistical`,p:e.t.p,numbers:z2({before:e.t.p1,rest:e.t.p2,p:e.t.p,fired:a.get(e.r.id)}),text:`“${e.r.name}” came before ${e.k1} of ${u.length} off-golden batches (${S4(e.t.p1)}) against ${S4(e.t.p2)} of the rest.`}),g.push({text:`Act on “${e.r.name}” when it fires: it came before ${S4(e.t.p1)} of off-golden batches.`,owner:`production`,urgent:!1,rank:(e.t.p1-e.t.p2)*(u.length/t.length),refs:[n]})}let v=m.length?[{kind:`table`,title:`07.1 · Alerts linked to off-golden batches: the share of batches each came before (in the hour before, or during)`,columns:[`Alert`,`Fired`,`Off-golden batches`,`The rest`],rows:m.map(e=>({cells:[e.r.name,a.get(e.r.id).toLocaleString(`en-GB`),S4(e.t.p1),S4(e.t.p2)],finding:_.get(e.r.id),status:`watch`}))}]:[],y=m.slice(0,2).map(e=>`“${e.r.name}”`),b=m.length?`${F4(y)} came before off-golden batches more often than before the rest${m.length>2?`, and ${P4(m.length-2,`more alert`)}`:``}.`:`No alert came before off-golden batches more often than before the rest.`,x=m.length?[]:[`Make an alert rule on the channel that goes with the gap (see 02) to warn before off-golden batches.`];return{section:x4(`07`,b,h,v),actions:g,next:x,numbers:{linked:m.length}}}var t3=(e,t)=>t===`duration`?e.c.tend===null?null:e.c.tend-e.c.tstart:e.c.kpis[t]??null,n3=e=>{let t=W2(e.map(e=>-e.gap));if(e.some(e=>e.g.value===0))return{text:T4(t),pct:null,abs:t};let n=W2(e.map(e=>-e.gap/Math.abs(e.g.value)*100));return{text:C4(n),pct:n,abs:t}},r3=e=>`${e<0?`−`:`+`}${C4(Math.abs(e))}`;function i3(e,t){let n=t.filter(e=>e.level===`better`),r=[],i=[],a=[],o=[];if(n.length<5)return{section:x4(`03`,n.length?`${P4(n.length,`batch`,`batches`)} beat the golden; 5 are needed to call it repeatable.`:`No batch beat the golden in this period.`,r,a),actions:i,next:o,numbers:{better:n.length}};let s=t.filter(e=>e.level===`golden`),c=s.length>=5?s:t.filter(e=>e.level!==`better`),l=e.value.label,u=n3(n),d=e=>{let t=`F03-${r.length+1}`;return r.push({id:t,section:`03`,refs:[`03`],...e}),t},f=e.streams.length>1;for(let[r,a]of B2(n,e=>e.c.streamId)){if(a.length<5)continue;let n=[...a].sort((e,t)=>e.gap-t.gap)[4],o=n3(a),s=e.streams.find(e=>e.id===r)?.name??`a stream`,c=d({evidence:`measured`,p:null,golden:{streamId:r,cycleId:n.c.id},numbers:z2({repeats:a.length,value:n.c.value,pct:o.pct??NaN,by:o.abs}),text:`Proposed new golden${f?` for ${s}`:``}: the batch of ${n.c.label}, the best ${l} that 5 batches reach (${T4(n.c.value)}). ${P4(a.length,`batch`,`batches`)} beat the golden by ${o.text} on ${l}, so this machine can reach it. Make it the golden to measure the next report against it.`});i.push({text:`Make the batch of ${n.c.label} the golden${f?` of ${s}`:``}: ${P4(a.length,`batch`,`batches`)} beat the current one by ${o.text}.`,owner:`quality`,urgent:!1,rank:a.length/t.length,refs:[c]})}r.length&&o.push(`Measure the next report against the new golden once it is set in Cycles.`);let p=[`duration`,...new Set(t.flatMap(e=>Object.keys(e.c.kpis)))].filter((t,n,r)=>t!==e.value.key&&r.indexOf(t)===n).flatMap(e=>{let t=n.map(t=>t3(t,e)).filter(U2),r=c.map(t=>t3(t,e)).filter(U2);return t.length<5||r.length<5?[]:[{k:e,ma:q2(t),mb:q2(r),p:Q2(t,r).p}]}),m=s4(p.map(e=>e.p),P2),h=p.filter((e,t)=>m[t]&&e.ma!==e.mb).map(e=>({...e,label:Y4(e.k),pct:e.mb===0?NaN:(e.ma-e.mb)/Math.abs(e.mb)*100})).sort((e,t)=>(Math.abs(t.pct)||1/0)-(Math.abs(e.pct)||1/0)).slice(0,5);for(let e of h)d({evidence:`correlation`,p:e.p,numbers:z2({better:e.ma,golden:e.mb,pct:e.pct,p:e.p}),text:`Batches that beat the golden go with ${e.ma<e.mb?`a lower`:`a higher`} ${e.label}: ${T4(e.ma)} against ${T4(e.mb)} at golden level${Number.isFinite(e.pct)?` (${r3(e.pct)})`:``}.`});let g=h.filter(e=>Number.isFinite(e.pct)).map(e=>({label:e.label,pct:e.pct,text:`${T4(e.ma)} / ${T4(e.mb)}`}));g.length&&a.push({kind:`diverging`,rows:g,title:`03.1 · The ${P4(n.length,`better batch`,`better batches`)} against those at golden level, % difference. Values: better / at golden level.`});let _=h.slice(0,3).map(e=>`${e.ma<e.mb?`a lower`:`a higher`} ${e.label}`);return{section:x4(`03`,`${P4(n.length,`batch`,`batches`)} beat the golden by ${u.text} on ${l}${_.length?` with ${F4(_)}`:``}.`,r,a),actions:i,next:o,numbers:{better:n.length}}}var a3=`Ppk is indicative: it assumes the values are normally distributed and the process stable, which this report does not test.`,o3=new Set([`mean`,`min`,`max`,`first`,`last`]),s3=e=>Number.isFinite(e)?e.toFixed(2):`–`;function c3(e,t){let n=Object.entries(e.context?.channels??{}).filter(([,e])=>e.lsl!==null||e.usl!==null);if(!n.length)return null;let r=e.context?.ppkMin??1.33,i=[...new Set(t.flatMap(e=>Object.keys(e.c.kpis)))],a=[];for(let[e,r]of n)for(let n of i){let i=n.lastIndexOf(`:`);if(n.slice(0,i)!==e||!o3.has(n.slice(i+1)))continue;let o=t.map(e=>e.c.kpis[n]).filter(U2),s=G2(o);if(o.length<30)continue;let c=W2(o),l=o.filter(e=>r.usl!==null&&e>r.usl||r.lsl!==null&&e<r.lsl).length/o.length,u=s>0?Math.min(r.usl===null?1/0:(r.usl-c)/(3*s),r.lsl===null?1/0:(c-r.lsl)/(3*s)):l>0?-1/0:1/0;a.push({key:n,label:Y4(n),lsl:r.lsl,usl:r.usl,n:o.length,m:c,cpk:u,out:l})}if(!a.length)return{section:`04`,needs:`04.1 · Add the mean, minimum or maximum of ${F4(n.map(([e])=>e))} to the cycle rule’s KPIs (30 batches or more) to see capability.`};a.sort((e,t)=>e.cpk-t.cpk);let o=e=>{let[t,n,r]=O4(e.lsl??NaN,e.usl??NaN,e.m);return{m:r,limits:`${e.lsl===null?`–`:t} to ${e.usl===null?`–`:n}`}},s=e=>e.out>0&&e.out<.005?`${Math.round(e.out*e.n)} of ${e.n}`:null,c=e=>`${s(e)??S4(e.out)} ${s(e)?`batches`:`of batches`} outside`,l=[],u=[],d=new Map,f=a.filter(e=>e.cpk<r);for(let e of f){let t=`F04-${l.length+1}`,n=o(e);d.set(e.key,t),l.push({id:t,section:`04`,refs:[`04`],evidence:`measured`,p:null,numbers:z2({cpk:e.cpk,n:e.n,mean:e.m,outside:e.out}),text:`${e.label}: Ppk ${s3(e.cpk)} over ${P4(e.n,`batch`,`batches`)} (mean ${n.m}, limits ${n.limits}); ${c(e)}.`}),e.cpk<1&&u.push({text:`Bring ${e.label} inside its limits: Ppk ${s3(e.cpk)}, ${c(e)}.`,owner:`quality`,urgent:e.out>0,rank:e.out+(1-Math.max(e.cpk,-10))/10,refs:[t]})}let p=[{kind:`table`,title:`04.1 · Capability per feature (indicative Ppk, capable from ${r})`,columns:[`Feature`,`Limits`,`Mean`,`Ppk (indicative)`,`Outside`],rows:a.map(e=>{let t=o(e),n=d.get(e.key);return{cells:[e.label,t.limits,t.m,s3(e.cpk),s(e)??S4(e.out)],status:e.cpk<1?`crit`:e.cpk<r?`watch`:`ok`,...n?{finding:n}:{}}})}];return{section:{...x4(`04`,f.length?`${P4(f.length,`feature`)} below Ppk ${r}${f.length>1?`; ${f[0].label} the lowest`:``}.`:`Every feature with limits is capable (Ppk ${r} or more).`,l,p),subtitle:b4(`Capability (AIAG SPC)`),fold:!0},actions:u,next:[],numbers:{low:f.length}}}var l3=[`generic`,`discrete`,`process`,`regulated`],u3={generic:{id:`generic`,label:`Generic`,first:[],collapsed:[],roles:{},terms:{}},discrete:{id:`discrete`,label:`Discrete manufacturing (stamping, machining, assembly)`,first:[`06`,`05`,`04`,`02`],collapsed:[`03`,`13`],roles:{"06":[`management`,`maintenance`,`production`,`quality`],"04":[`quality`,`production`]},terms:{"slow batches":`slow cycles`,batches:`parts`,batch:`part`}},process:{id:`process`,label:`Process (chemical, food, batch plants)`,first:[`02`,`04`,`09`,`03`],collapsed:[`10`,`13`],roles:{"09":[`management`,`production`],"04":[`quality`,`production`]},terms:{"bad parts":`bad batches`}},regulated:{id:`regulated`,label:`Regulated (pharma, food: quality and batch review first)`,regulated:!0,first:[`04`,`02`,`05`,`07`,`08`],collapsed:[`10`,`13`],roles:{"04":[`quality`,`production`],"05":[`maintenance`,`quality`],"06":[`management`,`maintenance`,`production`,`quality`],"09":[`management`,`production`]},terms:{"bad parts":`bad batches`}}},d3=e=>u3[l3.find(t=>t===e)??`generic`],f3=e=>e===`quality`?`discrete`:e===`plants`?`process`:e===`pharma`?`regulated`:`generic`,p3=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),m3=e=>[...e].sort((e,t)=>t.length-e.length).map(p3).join(`|`),h3=new Map;function g3(e,t,n=[]){if(!e||!Object.keys(t.terms).length)return e;let r=h3.get(t.id);if(!r){let e=`(?<![\\w.])(${m3(Object.keys(t.terms))})(?!\\w)(?!\\.\\w)`;h3.set(t.id,r={all:new RegExp(e,`gi`),has:new RegExp(e,`i`)})}let{all:i,has:a}=r,o=e=>e.replace(i,e=>{let n=t.terms[e.toLowerCase()];return e[0]===e[0].toLowerCase()?n:n[0].toUpperCase()+n.slice(1)}),s=n.filter(e=>e&&a.test(e));return s.length?e.split(RegExp(`(${m3(s)})`)).map((e,t)=>t%2?e:o(e)).join(``):o(e)}function _3(e){let t=e.context;return[...new Set([e.project,e.rule.name,e.value.label,...e.streams.map(e=>e.name),...Object.keys(e.units),...e.recordings.map(e=>e.name),...e.goldens.map(e=>e.label),...(e.alertRules??[]).map(e=>e.name),...(e.goldenChanges??[]).map(e=>e.label),...t?[...Object.keys(t.channels),...t.shifts.map(e=>e.name),...t.stops.map(e=>e.name),...t.lines.map(e=>e.name),...t.units.map(e=>e.name)]:[]])]}var v3=new Set([`id`,`section`,`kind`,`evidence`,`ref`,`refs`,`finding`,`day`,`status`,`unit`,`tone`,`roles`,`cites`,`owner`,`alert`,`batch`,`golden`]);function y3(e,t){return typeof e==`string`?t(e):Array.isArray(e)?e.map(e=>y3(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,v3.has(e)?n:y3(n,t)])):e}function b3(e,t,n=[]){if(t.id===`generic`)return e;let r=e=>g3(e,t,n),i=e=>e===`00`?-1:t.first.includes(e)?t.first.indexOf(e):t.first.length,a=e.sections.map((e,t)=>({s:e,i:t})).sort((e,t)=>i(e.s.id)-i(t.s.id)||e.i-t.i).map(({s:e})=>({...y3(e,r),roles:t.roles[e.id]??e.roles,...t.collapsed.includes(e.id)&&(e.findings.length||e.charts.length)?{collapsed:!0}:{}}));return{...e,preset:t.id,sections:a,actions:y3(e.actions,r),missing:y3(e.missing,r)}}var x3=[`setting`,`measurement`,`quality`,`outside`,`energy`,`ignore`],S3={setting:`Adjustable setting`,measurement:`Measurement`,quality:`Quality result`,outside:`Outside influence`,energy:`Energy`,ignore:`Ignore`},C3=4e3,w3=(e=``)=>({role:null,unit:e,lo:null,hi:null,lsl:null,usl:null,target:null,calibration:null,suggested:!1}),T3=()=>({v:1,process:``,channels:{},lines:[],units:[],shifts:[],stops:[],costs:{currency:`EUR`,kwh:null,lineHour:null,scrap:null,rework:null,co2:null,licence:null}}),E3=e=>e&&!e.suggested?e.role:null,D3=e=>Object.keys(e?.channels??{}).filter(t=>E3(e.channels[t])===`energy`).sort()[0]??null,O3=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},k3=e=>Array.isArray(e)?e:[],A3=(e,t)=>typeof e==`string`?e.slice(0,t):``,j3=e=>typeof e==`number`&&Number.isFinite(e)?e:null,M3=e=>k3(e).filter(e=>typeof e==`string`).slice(0,500),N3=(e,t)=>e!==null&&t!==null&&e>=t?[null,null]:[e,t],P3=/^([01]\d|2[0-3]):[0-5]\d$/,F3=/^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d$/,I3=e=>e.suggested===!0?{suggested:!0}:{};function L3(e){let t=O3(e),n=A3(t.name,80),r=A3(t.from,16),i=A3(t.to,16);if(F3.test(r)&&F3.test(i)&&r<i)return[{name:n,from:r,to:i,...I3(t)}];if(!P3.test(r)||!P3.test(i))return[];let a=t.days===void 0?void 0:[...new Set(k3(t.days).filter(e=>Number.isInteger(e)&&e>=0&&e<=6))].sort();return a&&!a.length?[]:[{name:n,from:r,to:i,...a?{days:a}:{},...I3(t)}]}function R3(e){let t=new Set,n=new Set;return k3(e).slice(0,50).map(e=>({name:A3(O3(e).name,80),streams:M3(O3(e).streams),...I3(O3(e))})).filter(e=>e.name&&!t.has(e.name)&&t.add(e.name)).map(e=>({...e,streams:e.streams.filter(e=>!n.has(e)&&n.add(e))}))}function z3(e){let t=O3(e),n=O3(t.costs),r=T3(),i=Object.create(null);for(let[e,n]of Object.entries(O3(t.channels)).slice(0,2e3)){let t=O3(n),r=x3.find(e=>e===t.role)??null,[a,o]=N3(j3(t.lo),j3(t.hi)),[s,c]=N3(j3(t.lsl),j3(t.usl));i[e.slice(0,200)]={role:r,unit:A3(t.unit,40),lo:a,hi:o,lsl:s,usl:c,target:j3(t.target),calibration:j3(t.calibration),suggested:t.suggested===!0&&r!==null,...t.unitSuggested===!0?{unitSuggested:!0}:{},...t.rangeSuggested===!0&&a!==null&&o!==null?{rangeSuggested:!0}:{}}}return{v:1,process:A3(t.process,C3),...t.processSuggested===!0&&A3(t.process,1)?{processSuggested:!0}:{},channels:i,lines:R3(t.lines),units:k3(t.units).slice(0,100).map(e=>({name:A3(O3(e).name,80),channels:M3(O3(e).channels),...I3(O3(e))})).filter(e=>e.name),shifts:k3(t.shifts).slice(0,12).map(e=>({name:A3(O3(e).name,40),start:A3(O3(e).start,5),end:A3(O3(e).end,5),...I3(O3(e))})).filter(e=>e.name&&P3.test(e.start)&&P3.test(e.end)),stops:k3(t.stops).slice(0,500).flatMap(L3),costs:{currency:/^[A-Z]{3}$/.test(String(n.currency))?String(n.currency):r.costs.currency,kwh:j3(n.kwh),lineHour:j3(n.lineHour),scrap:j3(n.scrap),rework:j3(n.rework),co2:j3(n.co2),licence:j3(n.licence)},...(j3(t.idealCycleS)??0)>0?{idealCycleS:t.idealCycleS}:{},...t.hideShifts===!0?{hideShifts:!0}:{},...l3.some(e=>e===t.preset)?{preset:t.preset}:{},...(j3(t.ppkMin)??0)>=1&&t.ppkMin<=3?{ppkMin:t.ppkMin}:{}}}var B3=(e,t)=>{let n=e+yB(e,t);return Math.floor((n%86400+86400)%86400/60)},V3=e=>e.slice(0,2)*60+ +e.slice(3,5);function H3(e,t,n){if(!t.length)return null;let r=B3(e,n);for(let e of t){let t=V3(e.start),n=V3(e.end);if(t<n?r>=t&&r<n:r>=t||r<n)return e.name}return null}var U3=e=>(new Date(`${e}T00:00:00Z`).getUTCDay()+6)%7;function W3(e,t,n,r){let i=[];for(let a of e.stops){if(a.from.length>5){i.push({t0:xB(a.from.slice(0,10),a.from.slice(11),t),t1:xB(a.to.slice(0,10),a.to.slice(11),t)});continue}for(let e=SB(bB(n,t),-1),o=bB(r,t);e<=o;e=SB(e,1)){if(a.days&&!a.days.includes(U3(e)))continue;let o=xB(e,a.from,t),s=xB(a.to>a.from?e:SB(e,1),a.to,t);s>n&&o<r&&i.push({t0:o,t1:s})}}return i}function G3(e){let t=e=>e.filter(e=>!e.suggested),n=Object.create(null);for(let[t,r]of Object.entries(e.channels)){let{unitSuggested:e,rangeSuggested:i,...a}=r;n[t]={...a,role:E3(r),suggested:!1,unit:e?``:r.unit,lo:i?null:r.lo,hi:i?null:r.hi}}let{processSuggested:r,...i}=e;return{...i,process:r?``:e.process,channels:n,shifts:t(e.shifts),stops:t(e.stops),lines:t(e.lines),units:t(e.units)}}function K3(e){let t=e=>Number(!!e);return t(e.processSuggested)+Object.values(e.channels).reduce((e,n)=>e+t(n.suggested)+t(n.unitSuggested)+t(n.rangeSuggested),0)+[...e.shifts,...e.stops,...e.lines,...e.units].filter(e=>e.suggested).length}function q3(e){let t=e=>e.map(e=>{let t={...e};return delete t.suggested,t}),n=Object.create(null);for(let[t,r]of Object.entries(e.channels)){let e={...r,suggested:!1};delete e.unitSuggested,delete e.rangeSuggested,n[t]=e}let r={...e,channels:n,shifts:t(e.shifts),stops:t(e.stops),lines:t(e.lines),units:t(e.units)};return delete r.processSuggested,r}function J3(e,t){let n=G3(e??T3()),r=Object.values(n.channels),i=r.some(e=>E3(e)===`energy`),a=n.costs.kwh!==null,o=[];return!n.shifts.length&&!n.hideShifts&&o.push({section:`02`,add:null,needs:`02.4 · Add shifts in Process context to split the batches that miss the golden by shift.`}),r.some(e=>e.lsl!==null||e.usl!==null)||o.push({section:`04`,add:`add specification limits`,needs:`Add specification limits (LSL, USL) to the channels in Process context to see capability (Ppk).`}),n.shifts.length?n.costs.lineHour===null&&o.push({section:`06`,add:null,needs:`06.1 · Add the cost of an hour of line time in Process context to see what the lost time costs.`}):o.push({section:`06`,add:`add shifts`,needs:`Add shifts and the cost of an hour of line time in Process context to see OEE and where time is lost.`}),t||o.push({section:`07`,add:`make alert rules`,needs:`Make alert rules in this project to see which alerts come before off-golden batches.`}),r.some(e=>E3(e)===`setting`)||o.push({section:`08`,add:`mark the adjustable settings`,needs:`Mark which channels are adjustable settings in Process context to see their changes.`}),i?(a||o.push({section:`09`,add:null,needs:`09 · Add the price per kWh in Process context to see what the energy costs.`}),n.costs.co2===null&&o.push({section:`09`,add:null,needs:`09 · Add the grid CO₂ factor (kg per kWh) in Process context to see CO₂ per batch.`})):o.push({section:`09`,add:`mark the energy channel`,needs:`Mark the energy channel in Process context to see energy per batch; the price per kWh adds its cost and the grid CO₂ factor its CO₂.`}),n.lines.filter(e=>e.streams.length).length<2&&o.push({section:`10`,add:`name two or more lines`,needs:`Say which streams are comparable lines in Process context (two or more) to compare lines.`}),!n.shifts.length&&!n.hideShifts&&o.push({section:`11`,add:`add shifts`,needs:`Add the shifts in Process context to compare them.`}),o}function Y3(e){let t=G3(e??T3()),n=Object.values(t.channels),r=[];return t.costs.lineHour===null&&r.push({add:`the cost of an hour of line time`,shows:`losses in money`}),t.costs.kwh===null&&n.some(e=>E3(e)===`energy`)&&r.push({add:`the price per kWh`,shows:`what the energy costs`}),t.costs.scrap===null&&n.some(e=>e.lsl!==null||e.usl!==null)&&r.push({add:`the cost of a scrapped batch`,shows:`what the batches off specification cost`}),r}function X3(e,t){let n=J3(e,t).filter(e=>e.add!==null),r=new Map;for(let e of n)r.set(e.add,[...r.get(e.add)??[],e.section]);return{ready:15-n.length,total:15,adds:[...r].map(([e,t])=>({add:e,sections:t}))}}var Z3=.2,Q3=20,$3=1e5,e6=2e4,t6=1e3,n6=class{values=[];#e;#t=0;#n=f4(1);constructor(e){this.#e=e}push(e){let t=this.#t++;if(t<this.#e)this.values.push(e);else{let n=Math.floor(this.#n()*(t+1));n<this.#e&&(this.values[n]=e)}}},r6=11,i6=class{#e=0;#t=1/0;#n=-1/0;#r=!1;#i=!0;#a=NaN;#o=NaN;#s=NaN;#c=NaN;#l=[];#u=NaN;#d=NaN;#f=0;#p=0;#m=NaN;#h=NaN;#g=0;#_=0;#v=0;#y=0;#b=[];#x=new Float64Array(64);#S=0;#C=new Float64Array(63);#w=new n6(e6);#T=0;#E=0;#D=new Float64Array(r6);#O=new Float64Array(r6);#k=new Float64Array(r6);#A=0;#j=0;#M=0;#N=[];#P=new n6($3);push(e,t){for(let n=0;n<e.length;n++){let r=t[n],i=e[n];if(!(r!==r||i!==i)){if(this.#e++,r<this.#t&&(this.#t=r),r>this.#n&&(this.#n=r),this.#P.push(r),this.#s===this.#s){let e=i-this.#s,t=!1;this.#l.length<t6?(this.#l.push(e),this.#l.length===t6&&this.#F()):e>this.#d&&(t=!0,this.#f+=e-this.#u,this.#p++),r!==this.#c&&(this.#r=!0),r<this.#c&&(this.#i=!1),Math.abs(r-this.#m)<=this.#_&&!t?this.#g++:(this.#L(this.#s),this.#I(i,r))}else this.#o=i,this.#a=r,this.#I(i,r);this.#R(r),this.#z(i,r),this.#s=i,this.#c=r}}}#F(){this.#u=q2(this.#l.filter(e=>e>0)),this.#d=this.#u>0?4*this.#u:1/0;for(let e of this.#l)e>this.#d&&(this.#f+=e-this.#u,this.#p++)}#I(e,t){this.#m=t,this.#h=e,this.#g=1,this.#_=Z3*this.#E}#L(e){let t=e-this.#h;this.#g>=20&&t>=300&&(this.#v+=t,this.#y++,this.#b.length<Q3&&this.#b.push({t0:this.#h,t1:e,value:this.#m}))}#R(e){let t=this.#x,n=this.#C;if(t[this.#S++]=e,this.#S<64)return;for(let e=1;e<64;e++)n[e-1]=t[e]-t[e-1];n.sort();let r=n[31];for(let e=0;e<n.length;e++)n[e]=Math.abs(n[e]-r);n.sort(),this.#T=1.4826*n[31]/Math.SQRT2,this.#w.push(this.#T),this.#T>0&&(this.#E=this.#E?.9*this.#E+.1*this.#T:this.#T),t[0]=e,this.#S=1}#z(e,t){let n=this.#k,r=this.#A===r6,i=this.#A;if(r){let e=this.#O[this.#j],t=0;for(;n[t]!==e;)t++;for(;t<i-1;t++)n[t]=n[t+1];i--}let a=i;for(;a>0&&n[a-1]>t;)n[a]=n[a-1],a--;if(n[a]=t,this.#A=i+1,this.#D[this.#j]=e,this.#O[this.#j]=t,this.#j=(this.#j+1)%r6,this.#A<r6)return;let o=e=>(this.#j+e)%r6,s=n[5],c=this.#O[o(5)],l=Math.abs(c-s),u=Math.max(this.#T,1e-9*Math.max(1,Math.abs(s)));if(l<=6*u)return;let d=Array.from(n,e=>Math.abs(e-s)).sort((e,t)=>e-t);l<=6*Math.max(1.4826*d[5],u)||Math.abs(this.#O[o(4)]-s)>l/2||Math.abs(this.#O[o(6)]-s)>l/2||(this.#M++,this.#N.length<Q3&&this.#N.push(this.#D[o(5)]))}result(){this.#g&&this.#L(this.#s),this.#l.length<t6&&this.#l.length>=2&&this.#F();let e=this.#s-this.#o-this.#f,t=this.#P.values,n=this.#w.values.filter(e=>e>0),r=this.#s-this.#o;return{n:this.#e,rateHz:this.#e>1&&e>0?(this.#e-1)/e:0,gapS:this.#f,gaps:this.#p,flatS:this.#v,flatRuns:this.#y,flats:this.#b,noise:n.length?q2(n):0,spikes:this.#M,spikeAt:this.#N,min:this.#t,max:this.#n,lo:K2(t,.005),hi:K2(t,.995),median:q2(t),p01:K2(t,.01),p99:K2(t,.99),moves:this.#r,clock:this.#i&&r>0&&Math.abs(this.#c-this.#a-r)<=.01*r,counter:this.#i&&this.#r}}};function a6(e){let t=e.slice(0,Math.max(3,Math.ceil(e.length/3)));if(!t.length)return null;let n=q2(t.map(e=>e.lo)),r=q2(t.map(e=>e.hi)),i=(r-n)/2;return r>n?{lo:n-i,hi:r+i,n:t.length}:null}var o6=3600,s6=86400;function c6(e,t){let n=e.filter(e=>U2(e.c.d?.[t])).map(e=>({t:e.c.tstart,v:e.c.d[t],edge:e.g.edges[t],rec:e.c.recordingId}));if(n.length<20)return null;let r=n[0].t,i=V2(n,r),a=i,o=`day`;if(i.length<7&&(a=H2(n,e=>e.rec),o=`recording`,a.length<6&&(a=H2(n,e=>Math.floor((e.t-r)/3600)),o=`hour`)),a.length<6)return null;a.sort((e,t)=>e.t-t.t);let s=l4(a.map(e=>(e.t-r)/s6),a.map(e=>e.v)),c=q2(n.map(e=>e.edge).filter(U2));return s&&c>0&&s.b!==0?{t0:r,means:a,per:o,days:i.length,fit:s,edge:c,step:l6(a,s)}:null}function l6(e,t){let n=e.length,r=t.s*t.s*(t.n-2);if(n<4)return null;let i=e.reduce((e,t)=>e+t.v,0),a=e.reduce((e,t)=>e+t.v*t.v,0),o=1/0,s=0,c=0;for(let t=1;t<n;t++){c+=e[t-1].v;let r=a-c*c/t-(i-c)**2/(n-t);r<o&&(o=r,s=t)}if(!(o<.5*r))return null;let l=e.slice(0,s),u=e.slice(s);return{t:e[s].t,d:u.reduce((e,t)=>e+t.v,0)/u.length-l.reduce((e,t)=>e+t.v,0)/l.length}}function u6(e,t,n,r){let{t0:i,fit:a,edge:o}=n,{a:s,b:c,s:l,n:u,mx:d,sxx:f}=a,p=Math.sign(c)*o,m=i+(p-s)/c*s6,h=s+c*((r-i)/s6),g=Math.abs(h)>=o;if(!g&&(m-r)/s6>365)return null;let _=(i4(1-P2/2,u-2)*l)**2,v=s+c*d-p,y=c*c-_/f,b=(c*v)**2-y*(v*v-_/u),x=y>0&&b>=0?[(-c*v-Math.sqrt(b))/y,(-c*v+Math.sqrt(b))/y].map(e=>i+(d+e)*s6).sort((e,t)=>e-t):null,S=g?r:m;return{ch:e,key:t,b:c,p:a.p,days:n.days,n:u,per:n.per,edge:o,cross:m,lo:x?x[0]:m,hi:x?x[1]:null,past:g,vNow:h,points:n.means,line:{t0:i,v0:s,t1:S,v1:s+c*((S-i)/s6)}}}function d6(e,t,n,r,i,a,o,s=[],c=null){let l={ch:e,sid:t,key:n,drift:a,stuck:[]},u=r.flatMap(e=>e.health.channels[n]?[{r:e,h:e.health.channels[n]}]:[]);if(!u.length&&!a)return null;let d=i?` ${i}`:``,f=e=>{let t=0,n=s.length;for(;t<n;){let r=t+n>>1;s[r]<e.t0?t=r+1:n=r}return t<s.length&&s[t]<=e.t1},p=u.flatMap(e=>e.h.flats).filter(e=>!s.length||f(e)).sort((e,t)=>e.t0-t.t0),m=s.length?p.reduce((e,t)=>e+t.t1-t.t0,0):u.reduce((e,t)=>e+t.h.flatS,0),h=s.length?p.length:u.reduce((e,t)=>e+t.h.flatRuns,0);if(u.some(e=>e.h.moves)&&u.some(e=>e.h.noise>0)&&m>=600&&p.length){let e=Z3*q2(u.map(e=>e.h.noise).filter(e=>e>0)),t=[];for(let n of p){let r=t[t.length-1];r&&n.t0-r.t1<=3600&&Math.abs(n.value-r.value)<=e?(r.t1=Math.max(r.t1,n.t1),r.rec+=n.t1-n.t0):t.push({...n,rec:n.t1-n.t0})}let n=t.reduce((e,t)=>t.t1-t.t0>e.t1-e.t0?t:e),r=t.length+h-p.length;return{...l,status:`Replace`,since:p[0].t0,stuck:t.map(({t0:e,t1:t})=>({t0:e,t1:t})),found:`Stuck at ${E4(n.value)}${d} from ${W4(n.t0,n.t1,o,` to `)}, ${j4(n.rec)} of it recorded${r>1?`; ${N4(r)} in all, ${j4(m)} recorded`:``}.`}}if(a){let e=a.per===`day`?`${A4(a.b*7)}${d} a week`:`${A4(a.b)}${d} a day`,t=`over ${P4(a.days,`day`)}${a.per===`day`?``:`, ${P4(a.n,a.per)}`}`;return{...l,status:`Drifting`,since:a.points[0]?.t??null,found:`${a.past?`Offset ${A4(a.vNow)}${d} against the golden, past the band edge (${T4(a.edge)}${d}); drifting ${e} ${t}.`:`Offset drifting ${e} against the golden ${t}; reaches the band edge (${T4(a.edge)}${d}) around ${V4(a.cross,o)}.`} Check calibration or the process.`}}let g=[];c&&g.push({since:c.t,text:`Offset against the golden moved by ${A4(c.d)}${d} on ${V4(c.t,o)} and stayed there: a change, not a drift.`});let _=q2(u.map(e=>e.h.rateHz).filter(e=>e>0));if(u.length>=4){let e=u[u.length-1],t=u.slice(0,-1).map(e=>e.h.noise).filter(e=>e>0),n=q2(t);t.length>=3&&n>0&&e.h.noise/n>=1.3&&Y2(e.h.noise,t)>=3&&g.push({text:`Noise up ${S4(e.h.noise/n-1)}. Check the cable and its shielding.`,since:e.r.t0})}let v=u.reduce((e,t)=>e+t.h.n,0),y=u.reduce((e,t)=>e+t.h.spikes,0);v&&y/v>=1e-4&&g.push({text:`${P4(y,`spike`)}.`,since:Math.min(...u.flatMap(e=>e.h.spikeAt))});let b=u.reduce((e,t)=>e+(t.r.t1-t.r.t0),0),x=u.reduce((e,t)=>e+t.h.gapS,0),S=u.reduce((e,t)=>e+t.h.gaps,0);b>0&&x/b>=.01&&g.push({text:`${j4(x)} of gaps in ${P4(S,`place`)}.`,since:u.find(e=>e.h.gaps).r.t0});let C=u.find(e=>e.h.rateHz>0&&e.h.rateHz<.9*_);if(C&&g.push({text:`Rate dropped from ${T4(_)} Hz to ${T4(C.h.rateHz)} Hz on ${V4(C.r.t0,o)}.`,since:C.r.t0}),u.length>=3){let e=a6(u.map(e=>e.h)),t=e?.lo??0,n=e?.hi??0,r=1e-9*Math.max(1,Math.abs(t),Math.abs(n)),i=e?u.find(e=>e.h.min<t-r||e.h.max>n+r):void 0;if(i){let[a,o,s]=O4(i.h.max>n+r?i.h.max:i.h.min,t,n);g.push({since:i.r.t0,text:`Read ${a}${d}, outside the usual ${o} to ${s}${d} learned from the first ${P4(e.n,`recording`)}.`})}}return g.length?{...l,status:`Watch`,found:g.map(e=>e.text).join(` `),since:Math.min(...g.map(e=>e.since)),...c&&g.length===1?{step:c}:{}}:{...l,status:`Healthy`,found:`No gaps or spikes worth a look, rate steady at ${T4(_)} Hz.`,since:null}}function f6(e,t){let n=e.streams.length>1;return[...B2(t,e=>e.c.streamId)].flatMap(([t,r])=>{let i=p6(e,r);return i?[{...i,text:n?`${e.streams.find(e=>e.id===t)?.name??t}: ${L4(i.text)}`:i.text}]:[]}).sort((e,t)=>(e.p??1)-(t.p??1))[0]??null}function p6(e,t){let n=t.filter(e=>e.c.tend!==null).map(e=>({t:e.c.tstart,v:e.c.tend-e.c.tstart}));if(n.length<30)return null;let r=q2(n.map(e=>e.v)),i=n[0].t,a=V2(n.map(e=>({t:e.t,v:e.v/r*100})),i),o=r>0&&a.length>=7?l4(a.map(e=>(e.t-i)/(7*s6)),a.map(e=>e.v)):null,s=o&&o.p<.01&&o.b>0&&!l6(a,o)?o.b:null,c=t.map(e=>e.c.value),l=Math.floor(c.length/3),u=c.slice(0,l),d=c.slice(c.length-l),f=J2(u),p=f>0?J2(d)/f:NaN,m=null;if(Number.isFinite(p)&&p>=1.15){let e=f4(1),t=Math.min(l,p4),n=Math.sqrt(t/l),r=n=>J2(Array.from({length:t},()=>n[Math.floor(e()*n.length)])),i=0,a=0;for(let e=0;e<1e3;e++){let e=r(u),t=r(d);e>0&&(a++,p+(t/e-p)*n<=1&&i++)}m=a?(i+1)/(a+1):1}let h=m!==null&&m<.01?p-1:null;if(s===null&&h===null)return null;let g=[...s===null?[]:[`cycle time grows ${T4(s)}% a week since ${V4(i,e.tz)}`],...h===null?[]:[`the spread of ${e.value.label} is up ${S4(h)}`]];return{text:`${I4(g.join(` and `))}.${g.length===2?` Together they are consistent with wear.`:` Consistent with wear.`}`,p:Math.min(s===null?1:o.p,h===null?1:m),grow:s,spread:h}}var m6=e=>new Set(e.recordings.flatMap(e=>Object.entries(e.health?.channels??{}).filter(([,e])=>e.clock).map(([e])=>e)));function h6(e){let t=new Map;for(let n of e.recordings)for(let[e,r]of Object.entries(n.health?.channels??{}))r.moves&&t.set(e,(t.get(e)??!0)&&r.counter===!0);return new Set([...t].filter(([,e])=>e).map(([e])=>e))}function g6(e,t){let n=e.recordings.filter(e=>e.health).sort((e,t)=>e.t0-t.t0),r=new Map,i=G3(e.context??T3()),a=m6(e);for(let e of Object.keys(i.channels))[`setting`,`ignore`].includes(E3(i.channels[e])??``)&&a.add(e);for(let t of h6(e))a.add(t);let o=new Map([...B2(e.cycles,e=>e.streamId)].map(([e,t])=>[e,t.map(e=>e.tstart).sort((e,t)=>e-t)]));for(let e of n)for(let t of Object.keys(e.health.channels))a.has(t)||r.set(`${e.streamId}\u0000${t}`,{sid:e.streamId,key:t});for(let e of t)for(let t of Object.keys(e.c.d??{}))a.has(t)||r.set(`${e.c.streamId}\u0000${t}`,{sid:e.c.streamId,key:t});let s=e.streams.length>1,c=B2(t,e=>e.c.streamId),l=(t,n)=>s?`${e.streams.find(e=>e.id===t)?.name??t} · ${n}`:n,u={Replace:0,Drifting:1,Watch:2,Healthy:3},d=[...r.values()].map(({sid:e,key:t})=>c6(c.get(e)??[],t)),f=s4(d.flatMap(e=>e?[e.fit.p]:[]),P2),p=0,m=d.map(e=>!!e&&f[p++]);return[...r.values()].map(({sid:t,key:r},i)=>{let a=l(t,r),s=d[i],c=s&&m[i]?s.step:null;return d6(a,t,r,n.filter(e=>e.streamId===t),e.units[r]??``,s&&m[i]&&!c?u6(a,r,s,e.period.to):null,e.tz,o.get(t),c)}).filter(e=>!!e).sort((e,t)=>u[e.status]-u[t.status]||(e.drift&&t.drift?e.drift.cross-t.drift.cross:0)||e.ch.localeCompare(t.ch))}function _6(e,t){let n=g6(e,t),r=[],i=[],a=[],o=[],s=new Map,c=e.streams.length>1,l=t=>e.streams.find(e=>e.id===t)?.name??t,u=[...B2(n.filter(e=>e.status===`Drifting`),e=>e.sid).values()].filter(e=>e.length>1),d=new Set(u.flat()),f=[...B2(n.filter(e=>e.step),t=>`${t.sid}\u0000${V4(t.step.t,e.tz)}`).values()].filter(e=>e.length>1),p=new Set(f.flat());for(let t of n){let n=`F05-${r.length+1}`;if((t.status===`Replace`||t.status===`Drifting`)&&s.set(t,n),t.status===`Replace`)r.push({id:n,section:`05`,refs:[`05`],evidence:`measured`,p:null,numbers:{},text:`${t.ch}: ${t.found}`}),i.push({text:`Replace or repair ${t.ch}: ${L4(t.found)}`,owner:`maintenance`,urgent:!0,rank:1,refs:[n]});else if(t.status===`Drifting`){let a=t.drift;r.push({id:n,section:`05`,refs:[`05`],evidence:`statistical`,p:a.p,text:`${t.ch}: ${t.found}`,numbers:z2({perWeek:a.b*7,edge:a.edge,cross:a.cross,lo:a.lo,hi:a.hi??NaN,days:a.days,points:a.n,p:a.p})}),d.has(t)||i.push({text:`${t.ch} offset drifting: check calibration or the process ${a.past?`now`:`before ${V4(a.cross,e.tz)}`}.`,owner:`maintenance`,urgent:a.past||a.cross-e.period.to<30*s6,rank:.5,refs:[n]})}}let m=e=>e.map(e=>e.drift).sort((e,t)=>t.past-+e.past||e.cross-t.cross)[0];for(let t of u){let n=m(t);i.push({text:`${c?`${l(t[0].sid)}: `:``}${F4(t.map(e=>e.key))} drift together against the golden, which points to the process (wear, a setting) rather than to ${t.length} sensors. Check it ${n.past?`now`:`before ${V4(n.cross,e.tz)}`}.`,owner:`maintenance`,urgent:n.past||n.cross-e.period.to<30*s6,rank:.5,refs:t.map(e=>s.get(e))})}let h=n.filter(e=>e.status===`Drifting`).map(e=>e.ch);h.length&&a.push(`Run the report again after checking ${F4(h)} to confirm the ${h.length===1?`offset is`:`offsets are`} gone.`);let g=t=>({cells:[t.ch,t.status,t.found,t.since===null?`–`:V4(t.since,e.tz)],status:t.status===`Replace`?`crit`:`watch`,...s.has(t)?{finding:s.get(t)}:{}}),_=t=>{let n=t=>e.units[t.key]?` ${e.units[t.key]}`:``,r=V4(t[0].step.t,e.tz);return{cells:[`${c?`${l(t[0].sid)} · `:``}${P4(t.length,`channel`)}`,`Watch`,`Offsets against the golden moved on ${r} and stayed there (${t.map(e=>`${e.key} ${A4(e.step.d)}${n(e)}`).join(`, `)}): one change of the process, not ${t.length} sensors.`,r],status:`watch`}},v=n.filter(e=>e.status!==`Healthy`),y=n.length-v.length;v.length&&o.push({kind:`table`,columns:[`Sensor`,`Status`,`What was found`,`Since`],rows:[...v.filter(e=>!p.has(e)).map(g),...f.map(_)],title:`05.1 · Sensors that need a look${y?`; the other ${y} ${y===1?`is`:`are`} healthy`:``}`});let b=n.flatMap(e=>e.drift?[e.drift]:[]).sort((e,t)=>e.cross-t.cross)[0];b&&o.push({kind:`trend`,title:`05.2 · Drift forecast, ${b.ch}: its offset against the golden per ${b.per}, forecast to the band edge`,unit:e.units[b.key]??``,points:b.points,line:b.line,limit:Math.sign(b.b)*b.edge,crossing:b.past?null:{t:b.cross,lo:b.lo,hi:b.hi}});let x=f6(e,t);if(x){let e=`F05-${r.length+1}`;r.push({id:e,section:`05`,refs:[`05`],evidence:`statistical`,p:x.p,text:x.text,numbers:z2({growPerWeek:x.grow??NaN,spreadUp:x.spread??NaN})}),i.push({text:`Inspect the machine for wear: ${L4(x.text)}`,owner:`maintenance`,urgent:!1,rank:.3,refs:[e]})}let S=e=>n.filter(t=>t.status===e).length,C=S(`Watch`)-p.size+f.length,w=u.length===1&&u[0].length===S(`Drifting`),T=[S(`Replace`)?`${P4(S(`Replace`),`sensor`)} to replace`:``,S(`Drifting`)?`${S(`Drifting`)} drifting${w?` together${c?` on ${l(u[0][0].sid)}`:``}`:``}`:``,C?`${C} to watch`:``].filter(Boolean);return{out:{section:{...x4(`05`,n.length?`${T.length?I4(F4(T)):`All ${P4(n.length,`sensor`)} healthy`}${x?`, and signs of machine wear`:``}.`:`No sensor health was measured in this period.`,r,o),subtitle:b4(`Reliability data (ISO 14224 style)`),fold:!0},actions:i,next:a,numbers:{replace:S(`Replace`),drifting:S(`Drifting`),watch:C}},sensors:n,drifts:[...n.filter(e=>e.status===`Drifting`&&!d.has(e)).map(e=>e.drift),...u.map(e=>({...m(e),work:`Check the process${c?` on ${l(e[0].sid)}`:``} (${P4(e.length,`channel`)} drifting together)`}))],wear:x}}var v6=.0027,y6=240,b6=60,x6=new Set([`mean`,`min`,`max`,`first`,`last`]),S6=(e,t)=>e.length<=t?e:Array.from({length:t},(n,r)=>e[Math.round(r*(e.length-1)/(t-1))]);function C6(e,t){let n=e.context,r=new Set([...h6(e),...m6(e)]),i=e=>{let t=e.lastIndexOf(`:`),i=e.slice(0,t),a=E3(n?.channels[i]);return t>0&&x6.has(e.slice(t+1))&&!r.has(i)&&a!==`setting`&&a!==`ignore`&&a!==`energy`},a=e.streams.length>1,o=[];for(let[e,n]of B2(t,e=>e.c.streamId)){let t=n.map(e=>e.c).sort((e,t)=>e.tstart-t.tstart);for(let n of[...new Set(t.flatMap(e=>Object.keys(e.kpis)))].filter(i)){let r=t.flatMap(e=>{let t=e.kpis[n];return U2(t)?[{t:e.tstart,v:t}]:[]});if(r.length<30)continue;let i=r.reduce((e,t)=>e+t.v,0)/r.length,a=r.slice(1).reduce((e,t,n)=>e+Math.abs(t.v-r[n].v),0)/(r.length-1)/1.128;if(!(a>0))continue;let s=i+3*a,c=i-3*a,l=r.map(e=>({...e,out:e.v>s||e.v<c})),u=l.filter(e=>e.out).length;u>=1&&u>2*.0027*r.length&&o.push({key:n,sid:e,n:r.length,out:u,mean:i,ucl:s,lcl:c,pts:l})}}if(!o.length)return null;o.sort((e,t)=>t.out/t.n-e.out/e.n||t.out-e.out);let s=t=>`${Y4(t.key)}${a?` on ${e.streams.find(e=>e.id===t.sid)?.name??`one stream`}`:``}`,c=t=>{let n=e.units[t.key.slice(0,t.key.lastIndexOf(`:`))];return n?` ${n}`:``},l=o[0],u=o.slice(0,3),d=e=>`F04-S${e+1}`,f=l.pts.length<=y6?l.pts:S6(l.pts,y6-b6),p=new Set(f),m=l.pts.length<=y6?[]:S6(l.pts.filter(e=>e.out&&!p.has(e)),b6);return{charts:[{kind:`control`,title:`04.3 · Control chart, ${s(l)}: each batch against the limits of its own variation (mean ± 3σ)`,unit:c(l).trim(),mean:l.mean,ucl:l.ucl,lcl:l.lcl,n:l.n,outside:l.out,points:[...f,...m].sort((e,t)=>e.t-t.t).map(e=>({t:e.t,v:e.v,...e.out?{out:!0}:{}}))}],findings:u.map((t,n)=>({id:d(n),section:`04`,refs:[`04`],evidence:`measured`,p:null,numbers:{outside:t.out,n:t.n,mean:t.mean,ucl:t.ucl,lcl:t.lcl},text:`${s(t)}: ${P4(t.out,`batch`,`batches`)} of ${t.n.toLocaleString(`en-GB`)} (${C4(100*t.out/t.n)}) outside its control limits, ${T4(t.lcl)} to ${T4(t.ucl)}${c(t)}, the first on ${V4(t.pts.find(e=>e.out).t,e.tz)}. The process moved; with no specification limits, nothing says these batches are bad.`})),actions:[{text:`Find what moved ${s(l)}: ${P4(l.out,`batch`,`batches`)} outside its control limits. Add its specification limits in Process context to know which batches are bad.`,owner:`quality`,urgent:!1,rank:Math.min(1,l.out/l.n),refs:[d(0)]}],notes:[],next:[]}}function w6(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].c.tstart<t?n=i+1:r=i}return n}function T6(e,t){let n=G3(e.context??T3()),r=e.tz,{from:i,to:a}=e.period,o=Object.keys(n.channels).filter(e=>E3(n.channels[e])===`setting`),s=(e.goldenChanges??[]).filter(e=>e.t>=i&&e.t<a);if(!o.length&&!s.length)return{section:`08`,needs:`Mark which channels are adjustable settings in Process context to see their changes.`};let c=e.streams.length>1,l=t=>e.streams.find(e=>e.id===t)?.name??t,u=(e,t)=>c?`${l(e)} · ${t}`:t,d=[];for(let[t,n]of B2(e.recordings.filter(e=>e.health).sort((e,t)=>e.t0-t.t0),e=>e.streamId))for(let e of o){let r=n.flatMap(t=>t.health.channels[e]?[t.health.channels[e]]:[]),o=r.flatMap(e=>e.flats).sort((e,t)=>e.t0-t.t0),s=Math.max(3*q2(r.map(e=>e.noise)),1e-9);o.forEach((n,r)=>{let c=o[r-1];c&&Math.abs(n.value-c.value)>s&&n.t0>=i&&n.t0<a&&d.push({sid:t,ch:u(t,e),t:n.t0,a:c.value,b:n.value})})}if(!d.length&&!s.length)return null;let f=new Map([...B2(t,e=>e.c.streamId)].map(([e,t])=>[e,t.slice().sort((e,t)=>e.c.tstart-t.c.tstart)])),p=d.map(t=>{let n=f.get(t.sid)??[],r=w6(n,t.t),i=n.slice(Math.max(0,r-20),r).map(e=>e.c.value),a=n.slice(r,r+20).map(e=>e.c.value),o=i.length>=5&&a.length>=5,s=q2(i),c=q2(a),l=o?Q2(a,i):{p:1,effect:.5};return{...t,enough:o,mb:s,ma:c,p:l.p,worse:e.value.better===`min`?l.effect>.5:l.effect<.5}}),m=s4(p.map(e=>e.enough?e.p:1),P2),h=[],g=[],_=new Map,v=e.value.label;p.forEach((e,t)=>{if(!e.enough||!m[t])return;let n=`F08-${h.length+1}`,i=H4(e.t,r),[a,o]=D4(e.a,e.b),[s,c]=D4(e.mb,e.ma);_.set(t,n),h.push({id:n,section:`08`,refs:[`08`],evidence:`statistical`,p:e.p,numbers:z2({from:e.a,to:e.b,before:e.mb,after:e.ma,p:e.p}),text:`${e.ch} was changed from ${a} to ${o} on ${i}; ${s===c?`${v} moved ${e.worse?`worse`:`better`} afterwards (median ${s} both times)`:`${v} went from ${s} to ${c} afterwards (${e.worse?`worse`:`better`})`}.`}),e.worse&&g.push({text:`Review the ${e.ch} change of ${i}: ${v} has been worse since.`,owner:`production`,urgent:!1,rank:Math.min(1,Math.abs(e.ma-e.mb)/(Math.abs(e.mb)||1)),refs:[n]})});let y=[...p.map((e,t)=>{let[n,i]=D4(e.a,e.b);return{t:e.t,row:{cells:[H4(e.t,r),e.ch,n,i,e.enough?`${A4(e.ma-e.mb)} (${X4(e.p)})`:`Too few batches to tell`],..._.has(t)?{finding:_.get(t),...e.worse?{status:`watch`}:{}}:{}}}}),...s.map(e=>({t:e.t,row:{cells:[H4(e.t,r),c?`${l(e.streamId)} · Golden`:`Golden`,`–`,e.label,`–`]}}))].sort((e,t)=>e.t-t.t).map(e=>e.row),b=s.map(e=>`The golden changed on ${H4(e.t,r)}; every batch in this report is judged against the current one.`);return{section:x4(`08`,h.length?`${P4(d.length,`setting change`)} in the period; ${h.length} ${h.length===1?`was`:`were`} followed by a different ${v}.`:d.length?`${P4(d.length,`setting change`)} in the period, none followed by a clear difference in ${v}.`:b[0],h,[{kind:`table`,title:`08.1 · Changes of settings`,columns:[`When`,`Setting`,`From`,`To`,`Effect on ${v}`],rows:y}],b),actions:g,next:[],numbers:{changes:d.length,goldens:s.length}}}function E6(e,t,n=g6(e,t)){let r=new Map([...B2(t,e=>e.c.streamId)].map(([e,t])=>[e,t.slice().sort((e,t)=>e.c.tstart-t.c.tstart)])),i=(e,t,n)=>{let i=r.get(e)??[],a=w6(i,n);for(;a<i.length&&i[a].c.tstart===n;)a++;return i.slice(w6(i,t),a)},a=B2(n.filter(e=>e.status===`Drifting`),e=>e.sid),o=e=>e.status===`Drifting`&&(a.get(e.sid)?.length??0)>1,s=n.filter(t=>e.goldens.some(e=>e.streamId===t.sid&&t.key in e.edges)&&!o(t)).flatMap(t=>(t.status===`Replace`?t.stuck.map(e=>({...e,stuck:!0})):t.drift?.past?[{t0:Math.max(t.drift.cross,e.period.from),t1:e.period.to,stuck:!1}]:[]).map(e=>({s:t,...e,xs:i(t.sid,e.t0,e.t1)}))).filter(e=>e.xs.length).sort((e,t)=>t.xs.length-e.xs.length||e.t0-t.t0).slice(0,10);if(!s.length)return null;let c=e.tz,l=e=>`F04-C${e+1}`;return{charts:[{kind:`table`,title:`04.2 · Batches made while a sensor was failing`,columns:[`Sensor`,`From`,`To`,`Batches`,`Of them off-golden`],rows:s.map((e,t)=>({cells:[e.s.ch,H4(e.t0,c),H4(e.xs[e.xs.length-1].c.tstart,c),String(e.xs.length),String(e.xs.filter(e=>e.level===`off`).length)],status:e.stuck?`crit`:`watch`,finding:l(t)}))}],findings:s.map((e,t)=>({id:l(t),section:`04`,refs:[`04`,`05`],evidence:`measured`,p:null,numbers:{batches:e.xs.length,off:e.xs.filter(e=>e.level===`off`).length,seconds:e.xs.reduce((e,t)=>e+Math.max(0,(t.c.tend??t.c.tstart)-t.c.tstart),0)},text:`${P4(e.xs.length,`batch`,`batches`)} ${e.xs.length===1?`was`:`were`} made while ${e.s.ch} `+(e.stuck?`was stuck (from ${W4(e.t0,e.t1,c,` to `)}): their ${e.s.ch} readings can't be trusted. Check them before they ship.`:`read beyond its band (the sensor or the process), from ${W4(e.t0,e.t1,c,` to `)}. Check them before they ship.`)})),actions:s.map((e,t)=>({text:`Check the ${P4(e.xs.length,`batch`,`batches`)} made while ${e.s.ch} ${e.stuck?`was stuck`:`read beyond its band`} before they ship.`,owner:`quality`,urgent:e.stuck,rank:1,refs:[l(t)]})),notes:[],next:[]}}var D6={Wh:.001,kWh:1,MWh:1e3},O6=`Scope 2, location-based, factor entered by you`;function k6(e,t){let n=D6[(e.context?.channels[t]?.unit??``).trim()],r=n?e.recordings.flatMap(e=>{let n=e.health?.channels[t];return n?.counter?[n]:[]}):[];return r.length?r.reduce((e,t)=>e+(t.max-t.min)*n,0):null}function A6(e,t){let n=e.context,r=D3(n);if(!n||!r)return null;let i=t.filter(e=>U2(e.c.kwh)&&e.c.kwh>=0);if(i.length<5)return{section:`09`,needs:`09 · ${r} has ${i.length?`energy in only ${i.length} of`:`no energy in`} this period’s batches: check it is recorded and its unit in Process context is kW, W, MW, kWh, Wh or MWh.`};let a=n.costs.kwh,o=n.costs.currency,s=n.costs.co2,c=i.map(e=>e.c.kwh),l=q2(c),u=c.reduce((e,t)=>e+t,0),d=k6(e,r),f=d!==null&&d>=u?d:u,p=[],m=[],h=(e.previous?.cycles??[]).map(e=>e.kwh).filter(e=>U2(e)&&e>=0),g=h.length>=5?q2(h):NaN,[_,v]=D4(l,g),y=(l-g)/g*100,b=Math.abs(y)>=10?Math.round(y):+y.toFixed(1),x=Number.isFinite(g)?_===v||!b?`, as the period before`:`, against ${v} the period before (${A4(b)}%)`:``,S=[...a===null?[]:[w4(l*a,o)],...s===null?[]:[`${T4(l*s)} kg CO₂ (${O6})`]];p.push({id:`F09-1`,section:`09`,refs:[`09`],evidence:`measured`,p:null,numbers:z2({kwh:l,before:g,cost:a===null?NaN:l*a,co2:s===null?NaN:l*s,total:f,inBatches:u}),text:`A batch uses ${_} kWh (median)${x}${S.length?`: ${S.join(` and `)}`:``}; ${T4(f)} kWh in the period${f>u?`, ${T4(u)} of them while a batch ran`:``}.`});let C=i.filter(e=>e.level===`off`).map(e=>e.c.kwh),w=i.filter(e=>e.level!==`off`).map(e=>e.c.kwh),T=!1,E=[],D=e=>a===null?``:` (${w4(e*a,o)})`;if(f>u&&E.push({kind:`bars`,title:`09.1 · Where the period’s energy goes${a===null?``:`, and what it costs`}`,max:Math.max(u,f-u),rows:[{label:`While a batch runs`,kwh:u},{label:`Between batches, in stops and breaks`,kwh:f-u}].sort((e,t)=>t.kwh-e.kwh).map(e=>({label:e.label,value:e.kwh,text:`${T4(e.kwh)} kWh${D(e.kwh)}`,tip:`${e.label}: ${S4(e.kwh/f)} of the period’s energy`}))}),C.length>=5&&w.length>=5){let e=q2(C),t=q2(w),n=Q2(C,w);if(n.p<.01&&e>t&&t>0){T=!0;let r=(e-t)*C.length,[s,c]=D4(e,t);E.push({kind:`bars`,title:`09.2 · Energy per batch: off-golden batches against the rest (median)`,max:e,rows:[{label:`Off-golden batches`,value:e,text:`${s} kWh`,tip:`Off-golden batches: ${s} kWh a batch (median of ${C.length.toLocaleString(`en-GB`)})`},{label:`At golden level or better`,value:t,text:`${c} kWh`,muted:!0,tip:`At golden level or better: ${c} kWh a batch (median of ${w.length.toLocaleString(`en-GB`)})`}]}),p.push({id:`F09-2`,section:`09`,refs:[`09`],evidence:`statistical`,p:n.p,numbers:z2({off:e,rest:t,extra:r,p:n.p}),text:`Off-golden batches use ${C4((e-t)/t*100)} more energy than the rest: ${T4(r)} kWh${a===null?``:`, up to ${w4(r*a,o)}`}, in the period.`}),m.push({text:`Bring off-golden batches to golden level (see 02) to save up to ${T4(r)} kWh${a===null?``:` (${w4(r*a,o)})`} in a period like this one.`,owner:`production`,urgent:!1,rank:(e-t)/t*(C.length/i.length),refs:[`F09-2`]})}}return{section:{...x4(`09`,`${a===null?`${T4(f)} kWh`:`${w4(f*a,o)} of energy`} in the period${T?`; off-golden batches use more`:``}.`,p,E),subtitle:b4(`Energy review inputs (ISO 50001)`),fold:!0},actions:m,next:[],numbers:{kwh:l}}}var j6=1800,M6=2400,N6=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],P6=[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`],F6=e=>`${String(e%24).padStart(2,`0`)}:00`,I6=(e,t)=>e.c.z?.[t.ch]?.[t.piece];function L6(e){let t=new Map;for(let n of e)for(let[e,r]of Object.entries(n.c.z))for(let n of Object.keys(r)){let r=`${e}\u0000${n}`;t.set(r,(t.get(r)??0)+1)}let n=[...t].filter(([,t])=>t>=.8*e.length).map(([e])=>e.split(`\0`)).sort(),r=new Set(n.filter(([,e])=>e!==`Cycle`).map(([e])=>e));return n.filter(([e,t])=>t!==`Cycle`||!r.has(e)).map(([e,t])=>({ch:e,piece:t,label:t===`Cycle`?e:`${e} · ${t}`}))}function R6(e,t){let n=d4(e,t);if(!n)return null;let r=n.shares.map(e=>Math.max(0,e)),i=r.reduce((e,t)=>e+t,0);return{shares:r.map(e=>i>0?e/i*n.r2:0),r2:n.r2}}function z6(e,t){let n=[],r=[],i=[],a=[],o=new Map,s=(e,t)=>{let r=`F02-${n.length+1}`;return n.push({id:r,section:`02`,refs:[`02`],...e}),o.set(r,t),r},c=t.filter(e=>e.level===`off`),l=e=>e.filter(e=>e.level===`off`).length,u=t.filter(e=>e.c.z),d=u.filter(e=>e.level===`off`),f=u.filter(e=>e.level!==`off`),p=null;if(d.length>=5&&f.length>=5){let e=L6(u).map(e=>{let t=u.filter(t=>U2(I6(t,e)));return{f:e,mw:Q2(d.map(t=>I6(t,e)).filter(U2),f.map(t=>I6(t,e)).filter(U2)),r:c4(t.map(t=>I6(t,e)),t.map(e=>e.gap))}}),t=s4(e.map(e=>e.mw.p),P2),n=e.filter((e,n)=>t[n]&&e.mw.effect>.5&&e.r>0).sort((e,t)=>t.r-e.r).slice(0,8),o=u.filter(e=>n.every(t=>U2(I6(e,t.f)))),c=o.map(e=>n.map(t=>I6(e,t.f))),l=o.map(e=>e.gap),m=n.length?R6(c,l):null;if(m){let e=m.shares.map((e,t)=>t).sort((e,t)=>m.shares[t]-m.shares[e]),t=e[0],u=n[t],f=m4(o.length,e=>R6(e.map(e=>c[e]),e.map(e=>l[e]))?.shares[t]??NaN),h=e.filter(e=>m.shares[e]>=.01),g=Math.max(0,1-m.r2);p={label:u.f.label,share:m.shares[t]},a.push({kind:`bars`,title:`02.1 · What goes with batches missing the golden: how much of the difference between batches each one explains (${P4(o.length,`batch`,`batches`)} measured, ${d.length.toLocaleString(`en-GB`)} off-golden)`,max:Math.max(g,...h.map(e=>m.shares[e]))*1.1,rows:[...h.map(e=>({label:n[e].f.label,value:m.shares[e],text:S4(m.shares[e]),tip:`${n[e].f.label} goes with ${S4(m.shares[e])} of the difference in how far batches are from the golden`})),{label:`Not explained by the recorded channels`,value:g,text:S4(g),muted:!0,tip:`Goes with none of the channels recorded: something else changes between batches.`}]});let _=d.reduce((e,t)=>t.gap>e.gap?t:e,d[0]),v=s({focus:{ch:u.f.ch,piece:u.f.piece},..._?{batch:{streamId:_.c.streamId,cycleId:_.c.id}}:{},text:`${u.f.label} goes with ${S4(p.share)} of the difference in how far batches are from the golden${h.length>1?`; the ${h.length} differences together go with ${S4(m.r2)}`:``}.`,evidence:`correlation`,p:u.mw.p,numbers:z2({share:p.share,lo:f.lo,hi:f.hi,r2:m.r2,r:u.r,p:u.mw.p})},p.share);for(let e of h.slice(0,3)){let t=n[e].f;r.push({text:`Test bringing ${t.ch}${t.piece===`Cycle`?``:` in ${t.piece}`} back to the golden: it goes with ${S4(m.shares[e])} of the difference in how far batches are from the golden.`,owner:`production`,urgent:!1,rank:m.shares[e],refs:[v]})}g>=.2&&i.push(`${S4(g)} of the difference in how far batches are from the golden goes with none of the recorded channels. Record what else changes between batches (material lot, ambient temperature, settings) as channels.`)}else i.push(`No recorded channel goes with the batches that miss the golden. Record what else changes between batches (material lot, ambient temperature, settings) as channels.`)}let m=new Set;for(let e of B2(t,e=>e.c.streamId).values()){let t=-1/0;e.forEach((n,r)=>{let i=e[r-1];i&&n.c.tstart-(i.c.tend??i.c.tstart)>1800&&(t=n.c.tstart),n.c.tstart-t<2400&&m.add(n.c.id)})}let h=t.filter(e=>m.has(e.c.id)),g=t.filter(e=>!m.has(e.c.id));if(h.length>=5&&g.length>=5){let e=o4(l(h),h.length,l(g),g.length);if(e.p<.01&&e.p1>e.p2){let n=s({text:`Off-golden share is ${S4(e.p1)} in the first ${M6/60} minutes after a stop of more than ${j6/60} minutes, against ${S4(e.p2)} the rest of the time.`,evidence:`statistical`,p:e.p,numbers:z2({warm:e.p1,rest:e.p2,p:e.p,batches:h.length})},(e.p1-e.p2)*(h.length/t.length));r.push({text:`Warm the line up after stops longer than ${j6/60} minutes: the first ${M6/60} minutes after a stop run ${S4(e.p1)} off-golden against ${S4(e.p2)}.`,owner:`production`,urgent:!1,rank:(e.p1-e.p2)*(h.length/t.length),refs:[n]})}}let _=(e,n,r=t)=>{let i=B2(r,e),a=l(r);if(i.size<2)return null;let o=[...i].filter(([,e])=>e.length>=n&&r.length-e.length>=5).map(([e,t])=>({k:e,n:t.length,t:o4(l(t),t.length,a-l(t),r.length-t.length)})),s=s4(o.map(e=>e.t.p),P2),c=null;return o.forEach((e,t)=>{s[t]&&e.t.p1-e.t.p2>=.05&&(!c||e.t.p1-e.t.p2>c.t.p1-c.t.p2)&&(c=e)}),c},v=_(e=>e.c.streamId,5);v&&s({text:`${e.streams.find(e=>e.id===v.k)?.name??`One stream`} runs ${S4(v.t.p1)} off-golden against ${S4(v.t.p2)} on the other streams.`,evidence:`statistical`,p:v.t.p,numbers:z2({share:v.t.p1,others:v.t.p2,p:v.t.p})},(v.t.p1-v.t.p2)*(v.n/t.length));let y=_(e=>e.c.recordingId,10);y&&s({text:`Recording ${e.recordings.find(e=>e.id===y.k)?.name??`one file`} runs ${S4(y.t.p1)} off-golden against ${S4(y.t.p2)} in the rest of the period.`,evidence:`statistical`,p:y.t.p,numbers:z2({share:y.t.p1,others:y.t.p2,p:y.t.p})},(y.t.p1-y.t.p2)*(y.n/t.length));let b=null;if(t.length>=5){let n=t[0].c.tstart,r=V2(t.map(e=>({t:e.c.tstart,v:e.gap})),n),i=r.length>=7?l4(r.map(e=>(e.t-n)/86400),r.map(e=>e.v)):null;if(i&&i.p<.01&&i.b!==0){let a=M4(e),o=a?` ${a}`:``,c=r[r.length-1].t;s({text:`The gap to the golden ${i.b>0?`grows`:`shrinks`} by ${T4(Math.abs(i.b)*7)}${o} a week since ${V4(n,e.tz)}.`,evidence:`statistical`,p:i.p,numbers:z2({perWeek:i.b*7,days:i.n,p:i.p})},Math.min(1,Math.abs(i.b*(c-n)/86400)/(t.reduce((e,t)=>e+Math.abs(t.gap),0)/t.length||1))),b={kind:`trend`,title:`02.3 · Gap to the golden per day, with its trend`,unit:o.trim(),points:r,line:{t0:n,v0:i.a,t1:c,v1:i.a+i.b*(c-n)/86400},limit:null,crossing:null}}}let x=new Map,S=new Map(t.map(t=>{let n=Math.floor(t.c.tstart/900),r=x.get(n);return r||x.set(n,r=K4(n*900,e.tz)),[t.c.id,r]})),C=_(e=>String(S.get(e.c.id).hour),5),w=_(e=>String(S.get(e.c.id).day),5),T=e.context?.hideShifts?[]:e.context?.shifts??[],E=new Map(T.length?t.map(t=>[t.c.id,H3(t.c.tstart,T,e.tz)]):[]),D=T.length?_(e=>E.get(e.c.id),5,t.filter(e=>E.get(e.c.id)!==null)):null,O=[...C?[{w:C,when:`started between ${F6(+C.k)} and ${F6(+C.k+1)}`,other:`at other hours`,look:`Find what changes around ${F6(+C.k)} (a shift change, a start-up, a material change)`}]:[],...w?[{w,when:`on ${P6[+w.k]}s`,other:`on other days`,look:`Find what is different on ${P6[+w.k]}s (crew, material, maintenance)`}]:[],...D?[{w:D,when:`on the ${D.k} shift`,other:`on the other shifts`,look:`Find what the ${D.k} shift does differently (crew, set-up, material)`}]:[]];for(let{w:e,when:n,other:i,look:a}of O){let o=(e.t.p1-e.t.p2)*(e.n/t.length),c=s({text:`Batches ${n} run ${S4(e.t.p1)} off-golden against ${S4(e.t.p2)} ${i}.`,evidence:`statistical`,p:e.t.p,numbers:z2({share:e.t.p1,others:e.t.p2,p:e.t.p})},o);r.push({text:`${a}: batches then run ${S4(e.t.p1)} off-golden against ${S4(e.t.p2)}.`,owner:`production`,urgent:!1,rank:o,refs:[c]})}if(O.length){let e=N6.map(()=>Array(24).fill(0)),n=N6.map(()=>Array(24).fill(0));for(let r of t){let{day:t,hour:i}=S.get(r.c.id);e[t][i]++,r.level===`off`&&n[t][i]++}a.push({kind:`heat`,title:`02.2 · Off-golden share by hour and weekday. Stronger colour is worse; hours with fewer than 5 batches are left empty.`,rows:N6,cols:Array.from({length:24},(e,t)=>String(t).padStart(2,`0`)),cells:e.map((e,t)=>e.map((e,r)=>e>=5?n[t][r]/e:null)),legend:`off-golden`})}b&&a.push(b);let k=t.length?c.length/t.length:0,A=t.length?c.length?p?`${S4(k)} of batches miss the golden. ${p.label} goes with most of the difference between them and the golden.`:`${S4(k)} of batches miss the golden; no recorded channel goes with the gap yet.`:`Every batch is at golden level or better.`:`No batches with a value to compare against a golden in this period.`;return n.sort((e,t)=>o.get(t.id)-o.get(e.id)),{section:{...x4(`02`,A,n,a),fold:!0},actions:r,next:i,numbers:{off:c.length,share:k}}}function B6(e,t){let n=(e.context?.lines??[]).filter(e=>e.streams.length);if(n.length<2)return null;let r=new Map(n.flatMap(e=>e.streams.map(t=>[t,e.name]))),i=B2(t.filter(e=>r.has(e.c.streamId)),e=>r.get(e.c.streamId)),a=e=>({section:x4(`10`,e,[],[]),actions:[],next:[],numbers:{}});if(i.size<2)return a(`${i.size?`Only one line has`:`No line has`} batches in this report: tick the files of the other lines to compare them.`);let o=[...i.values()].flat(),s=o.filter(e=>e.level===`off`).length,c=[...i].map(([e,t])=>{let n=t.filter(e=>e.level===`off`).length;return{name:e,xs:t,better:t.filter(e=>e.level===`better`).length,t:o4(n,t.length,s-n,o.length-t.length)}}),l=s4(c.map(e=>e.t.p),P2),u=e=>e.t.p1>e.t.p2,d=c.filter((e,t)=>l[t]&&e.t.p1!==e.t.p2&&e.xs.length>=5&&o.length-e.xs.length>=5).sort((e,t)=>Number(u(t))-Number(u(e))||Math.abs(t.t.p1-t.t.p2)-Math.abs(e.t.p1-e.t.p2)).slice(0,i.size===2?1:void 0);if(!d.length)return a(`The lines run alike: none misses the golden more often than the others.`);let f=[],p=[],m=new Map;for(let e of d){let t=`F10-${f.length+1}`;m.set(e.name,t),f.push({id:t,section:`10`,refs:[`10`],evidence:`statistical`,p:e.t.p,numbers:z2({share:e.t.p1,others:e.t.p2,p:e.t.p,batches:e.xs.length}),text:`${e.name} runs ${S4(e.t.p1)} off-golden against ${S4(e.t.p2)} on the other lines.`}),u(e)&&p.push({text:`Find what ${e.name} does differently from the other lines: it runs ${S4(e.t.p1)} off-golden against ${S4(e.t.p2)}.`,owner:`production`,urgent:!1,rank:(e.t.p1-e.t.p2)*(e.xs.length/o.length),refs:[t]})}let h=[{kind:`table`,title:`10.1 · The lines side by side`,columns:[`Line`,`Batches`,`At golden level or better`,`Better than the golden`],rows:c.map(e=>{let t=m.get(e.name);return{cells:[e.name,e.xs.length.toLocaleString(`en-GB`),S4(1-e.t.p1),S4(e.better/e.xs.length)],...t?{finding:t,status:u(e)?`crit`:`ok`}:{}}})}],g=d.filter(u),_=e=>F4(e.slice(0,2).map(e=>e.name))+(e.length>2?` and ${P4(e.length-2,`more line`)}`:``);return{section:x4(`10`,g.length?`${_(g)} ${g.length>1?`miss`:`misses`} the golden more often than the other lines.`:`${_(d)} ${d.length>1?`miss`:`misses`} the golden less often than the other lines.`,f,h),actions:p,next:[],numbers:{lines:i.size}}}function V6(e,t){let n=G3(e.context??T3()).costs,r=n.lineHour,i=n.currency,a=r!==null,o=e=>a?e/3600*r:e/3600,s=e=>e.s>=60&&(!a||o(e.s)>=1),c=new Map,l=t.time.filter(e=>!e.bad&&s(e)).map(e=>{let t={label:e.label,value:o(e.s),owner:e.owner,ref:e.ref,amount:a?w4(o(e.s),i):j4(e.s),detail:a?`${j4(e.s)} of line time`:`of line time`};return c.set(t,e.s),t}),u=t.energyKwh!==null&&t.energyKwh>0&&n.kwh!==null?t.energyKwh*n.kwh:0;u>=1&&l.push({label:`Extra energy of off-golden batches`,value:a?u:null,owner:`Production`,ref:`09`,amount:w4(u,i),detail:`${T4(t.energyKwh)} kWh more than batches at golden level`});let d=n.scrap,f=d===null?``:`${w4(d,i)} a scrapped batch`,p=t.scrap&&d!==null&&t.scrap.batches*d>=1?{...t.scrap,money:t.scrap.batches*d}:null,m=t.time.filter(e=>e.bad&&s(e)).reduce((e,t)=>e+t.s,0),h=p&&!p.assumed?p.money:0;if(m||h){let e=t.scrap&&!t.scrap.assumed?P4(t.scrap.batches,`batch`,`batches`):`Batches`,n={label:`Bad parts`,value:a?o(m)+h:m?o(m):null,owner:`Quality`,ref:`04`,amount:a?w4(o(m)+h,i):m?j4(m):w4(h,i),detail:`${e} outside their limits or flagged bad: ${[m?`${j4(m)} of line time`:``,h?`${w4(h,i)} scrapped material`:``].filter(Boolean).join(` + `)}`};l.push(n),c.set(n,m)}let g=l.reduce((e,t)=>e+(t.value??0),0),_=l.filter(e=>!a||e.value>=.005*g).sort((e,t)=>(t.value??-1)-(e.value??-1)),v=_.reduce((e,t)=>e+(c.get(t)??0),0);if(p?.assumed&&_.push({label:`Off-golden batches, if scrapped`,value:null,owner:`Quality`,ref:`02`,assumed:!0,amount:`up to ${w4(p.money,i)}`,detail:`${P4(p.batches,`off-golden batch`,`off-golden batches`)} at ${f}; no specification limits say which are scrap`}),t.review&&t.review.batches>0){let e=P4(t.review.batches,`batch`,`batches`);_.push(d===null?{label:`Batches to check before they ship`,value:o(t.review.s),owner:`Quality`,ref:`04`,atRisk:!0,amount:a?`up to ${w4(o(t.review.s),i)}`:e,detail:`${a?`${e}, `:``}${j4(t.review.s)} of production at risk: made while a sensor was failing`}:{label:`Batches to check before they ship`,value:a?t.review.batches*d:null,owner:`Quality`,ref:`04`,atRisk:!0,amount:`up to ${w4(t.review.batches*d,i)}`,detail:`${e} at ${f}, at risk: made while a sensor was failing`})}if(!_.length)return null;let y=_.reduce((e,t)=>e+(t.atRisk||t.assumed?0:t.value??0),0),b=_.some(e=>!e.atRisk&&!e.assumed),x=d===null&&t.scrap&&!t.scrap.assumed?t.scrap.batches:0,S=a?x?`Add the cost of a scrapped batch to see what the ${P4(x,`batch`,`batches`)} off specification cost`:null:`Add the cost of an hour of line time to see this in money`;return{kind:`losses`,unit:a?`money`:`hours`,title:`00.1 · Where the ${a?`money`:`time`} goes`,rows:_,total:b?a?`Up to ${w4(y,i)}`:v?j4(v):_[0].amount:`Nothing lost`,totalNote:b?a?`to recover in this period${v?`: ${j4(v)} of line time`:``}`:`of line time to recover in this period`:`against the golden in this period`,...S?{hint:S}:{}}}var H6=86400;function U6(e,t,n){if(!t.length&&!n)return null;let r=G3(e.context??T3()),i=e.tz,a=e.period.to,o=r.stops.length?W3(r,i,a,a+90*H6).map(e=>e.t0).filter(e=>e>a).sort((e,t)=>e-t):null,s=e=>{if(!o)return`No planned stop set`;let t=e===null?o[0]:o.filter(t=>t<e).pop();return t===void 0?`None before it`:q4(t,i)},c=[...t.map(e=>{let t=e.past||e.lo<=a;return{work:e.work??`Recalibrate ${e.ch}`,by:t?null:e.lo,now:t}}),...n?[{work:`Inspect the machine for wear (${n.grow===null?`spread of ${e.value.label} up ${S4(n.spread)}`:`cycle time ${A4(n.grow)}% a week`})`,by:null,now:!1}]:[]].sort((e,t)=>t.now-+e.now||(e.by??1/0)-(t.by??1/0)),l=c[0],u=c.find(e=>e.by!==null);return{charts:[{kind:`table`,title:`05.5 · Maintenance to plan`,columns:[`Work`,`By`,`Next planned stop before it`],rows:c.map(e=>({cells:[e.work,e.now?`Now`:e.by===null?`–`:V4(e.by,i),s(e.by)],...e.now?{status:`crit`}:{}}))}],findings:[{id:`F05-M1`,section:`05`,refs:[`05`],evidence:`measured`,p:null,numbers:{jobs:c.length,...u&&!l.now?{first:u.by}:{}},text:`Plan ${P4(c.length,`maintenance job`)}${l.now?`: the first now`:u?`: the first by ${V4(u.by,i)}`:``}.`}],actions:[],notes:[],next:o?[]:[`Add planned stops in Process context to place maintenance in them.`]}}var W6=()=>({findings:[],charts:[],notes:[],actions:[],next:[]});function G6(e,t){let n=[...e.charts,...t.flatMap(e=>e.charts)],r=[...e.findings,...t.flatMap(e=>e.findings)],i=e=>`title`in e?e.title:``;return{...e,findings:r,notes:[...e.notes,...t.flatMap(e=>e.notes)],...r.length>3?{shown:e.shown??3}:{},charts:n.map((e,t)=>({c:e,i:t})).sort((e,t)=>i(e.c).localeCompare(i(t.c))||e.i-t.i).map(e=>e.c)}}var K6=7200,q6=e=>e.reduce((e,t)=>e+t.t1-t.t0,0),J6=(e,t)=>e.flatMap(e=>t.map(t=>({t0:Math.max(e.t0,t.t0),t1:Math.min(e.t1,t.t1)}))).filter(e=>e.t1>e.t0);function Y6(e){let t=[];for(let n of[...e].sort((e,t)=>e.t0-t.t0)){let e=t[t.length-1];e&&n.t0<=e.t1?e.t1=Math.max(e.t1,n.t1):t.push({t0:n.t0,t1:n.t1})}return t}function X6(e,t){for(let n of t)e=e.flatMap(e=>[{t0:e.t0,t1:Math.min(e.t1,n.t0)},{t0:Math.max(e.t0,n.t1),t1:e.t1}]).filter(e=>e.t1>e.t0);return e}function Z6(e,t,n,r){let i=J6([{t0:n,t1:r}],[{t0:e.period.from,t1:e.period.to}]);return i.length?(t.shifts.length&&(i=J6(i,Y6(W3({...t,stops:t.shifts.map(e=>({name:e.name,from:e.start,to:e.end}))},e.tz,n,r)))),t.stops.length?X6(i,W3(t,e.tz,n,r)):i):i}function Q6(e){let t=[...e].sort((e,t)=>e.tstart-t.tstart),n=t.slice(1).map((e,n)=>e.tstart-(t[n].tend??t[n].tstart)).filter(e=>e>=0);return Math.max(300,n.length?5*q2(n):0)}function $6(e){return e8(e).stops}function e8(e){let t=G3(e.context??T3()),n=[],r=0,i=B2(e.cycles,e=>e.recordingId),a=B2(e.covered??[],e=>e.streamId);for(let[o,s]of B2([...e.recordings].sort((e,t)=>e.t0-t.t0),e=>e.streamId)){let c=Q6(s.flatMap(e=>i.get(e.id)??[])),l=[],u=-1/0;for(let n of[...s,...a.get(o)??[]].sort((e,t)=>e.t0-t.t0))!n.continues&&n.t0-u>=300&&u>-1/0&&(!t.shifts.length&&n.t0-u>7200?q6(Z6(e,t,u,n.t0))>=300&&r++:l.push({streamId:o,t0:u,t1:n.t0,kind:`no_data`,unit:null})),u=Math.max(u,n.t1);if(s.some(e=>i.has(e.id))){let e=s.filter(e=>i.has(e.id)||!(e.unread||e.failed)),t=e.flatMap(e=>i.get(e.id)??[]).sort((e,t)=>e.tstart-t.tstart),n=0,r=-1/0,a=[];for(let t of[...e].sort((e,t)=>e.t0-t.t0)){let e=a[a.length-1];e&&t.t0-e.t1<300?e.t1=Math.max(e.t1,t.t1):a.push({t0:t.t0,t1:t.t1})}for(let e of a){let i=Math.max(e.t0,Math.min(r,e.t1));for(;n<t.length&&t[n].tstart<e.t1;n++){let e=t[n];e.tstart-i>c&&l.push({streamId:o,t0:i,t1:e.tstart,kind:`no_batches`,unit:null}),i=Math.max(i,e.tend??e.tstart),r=Math.max(r,e.tend??e.tstart)}e.t1-i>c&&l.push({streamId:o,t0:i,t1:e.t1,kind:`no_batches`,unit:null})}}for(let r of l){let i=t.units.find(e=>e.channels.some(e=>s.some(t=>t.health?.channels[e]?.flats.some(e=>Math.abs(e.t0-r.t0)<=60))))?.name??null,a=Z6(e,t,r.t0,r.t1),o=q6(a);o>=300&&(r.kind!==`no_batches`||o>c)&&a.forEach((e,t)=>n.push({...r,...e,unit:i,...t?{part:t}:{}}))}}return{stops:n.sort((e,t)=>e.t0-t.t0||e.streamId.localeCompare(t.streamId)),offGaps:r}}function t8(e,t,n=0){let r=n?[`Add the shifts in Process context to count longer gaps as stops.`]:[];if(!t.length)return r.length?{...W6(),next:r}:null;let i=G3(e.context??T3()),a=t=>e.streams.find(e=>e.id===t)?.name??`A stream`,o=n=>e.recordings.filter(e=>e.streamId===n).reduce((t,n)=>t+q6(Z6(e,i,n.t0,n.t1)),0)+q6(t.filter(e=>e.streamId===n&&e.kind===`no_data`)),s=e=>{let t=[...new Set(e.map(e=>e.streamId))].reduce((e,t)=>e+o(t),0),n=q6(e),r=Math.max(1,e.filter(e=>!e.part).length);return{n:r,stopped:n,mtbf:(t-n)/r,mttr:n/r,share:t>0?n/t:0}},c=[],l=[...B2(t,e=>e.streamId)].map(([e,t])=>({sid:e,xs:t,...s(t)})).sort((e,t)=>t.stopped-e.stopped);for(let e of l){let t=[...B2(e.xs.filter(e=>e.unit),e=>e.unit)].sort((e,t)=>t[1].length-e[1].length);c.push({id:`F05-S${c.length+1}`,section:`05`,refs:[`05`],evidence:t.length?`correlation`:`measured`,p:null,numbers:{stops:e.n,stoppedS:e.stopped,mtbfS:e.mtbf,mttrS:e.mttr},text:(e.n===1?`${a(e.sid)} stopped once, for ${j4(e.stopped)}.`:`${a(e.sid)} stopped ${N4(e.n)} for ${j4(e.stopped)} in total; it ran ${j4(e.mtbf)} between stops on average and took ${j4(e.mttr)} to restart.`)+(t.length?` ${t[0][1].length} of the stops began when a ${t[0][0]} channel went flat.`:``)})}let u=new Map(l.map((e,t)=>[e.sid,c[t].id])),d=t.some(e=>e.unit),f=d?[...B2(t,e=>e.unit??`No unit found`)].map(([e,t])=>({label:e,xs:t,...s(t)})).sort((e,t)=>t.stopped-e.stopped):l.map(e=>({...e,label:a(e.sid)})),p=[],m=f[0];return m.share>=.2&&p.push({text:`Find why ${m.label} stops: ${P4(m.n,`stop`)} cost ${j4(m.stopped)} this period.`,owner:`maintenance`,urgent:!1,rank:m.share,refs:[...new Set(m.xs.map(e=>u.get(e.streamId)))]}),{findings:c,notes:[],actions:p,charts:[{kind:`table`,title:`05.4 · Stops by ${d?`machine unit`:`stream`}`,columns:[d?`Unit`:`Stream`,`Stops`,`Stopped`,`MTBF`,`MTTR`],rows:f.map(e=>({cells:[e.label,String(e.n),j4(e.stopped),j4(e.mtbf),j4(e.mttr)],...e.share>=.2?{status:`crit`}:{},...d?{}:{finding:u.get(e.xs[0].streamId)}}))}],next:[...!i.units.length&&t.length>=3?[`Add the machine units in Process context to see which unit each stop starts in.`]:[],...r]}}var n8=new Set([`mean`,`min`,`max`,`first`,`last`]),r8=()=>({plan:0,stop:0,ideal:0,n:0,good:0,badIdeal:0}),i8=e=>Math.max(0,e.plan-e.stop),a8=e=>{let t=i8(e),n=e.plan>0?t/e.plan:0,r=t>0?Math.min(1,e.ideal/t):0,i=e.n?e.good/e.n:0;return{A:n,P:r,Q:i,oee:n*r*i}};function o8(e,t){let n=e.context?.idealCycleS;if(n)return new Map(e.streams.map(e=>[e.id,n]));let r=new Map(e.value.key===`duration`?e.goldens.map(e=>[e.streamId,e.value]):[]);for(let[e,n]of B2(t,e=>e.c.streamId)){if(!r.has(e)){let t=n.filter(e=>e.level!==`off`).map(e=>e.c.tend-e.c.tstart);r.set(e,t.length?q2(t):NaN)}let t=n.map(e=>e.c).sort((e,t)=>e.tstart-t.tstart),i=Q6(t),a=t.slice(1).map((e,n)=>e.tstart-t[n].tend).filter(e=>e>=0&&e<=i);a.length&&r.set(e,r.get(e)+K2(a,F2))}return r}function s8(e){let t=Object.entries(e?.channels??{}).filter(([,e])=>e.lsl!==null||e.usl!==null);return{limits:t,outside:e=>t.some(([t,n])=>Object.entries(e).some(([e,r])=>{let i=e.lastIndexOf(`:`);return r!==null&&e.slice(0,i)===t&&n8.has(e.slice(i+1))&&(n.usl!==null&&r>n.usl||n.lsl!==null&&r<n.lsl)}))}}var c8=b4(`OEE as ISO 22400-2`),l8={stops:`Stops`,slow:`Slow batches and short waits`,bad:`Bad parts`,off:`Off-golden batches`};function u8(e,t,n=[]){let r=e.context;if(!r?.shifts.length)return null;let i=e.tz,a=e.recordings,o=a.length?W3(r,i,Math.min(...a.map(e=>e.t0)),Math.max(...a.map(e=>e.t1))):[],s=o8(e,t),c=r8(),l=new Map,u=new Map,d=(e,t)=>e.get(t)??e.set(t,r8()).get(t),f=(e,t)=>{let n=H3(e,r.shifts,i);if(n!==null)for(let r of[c,d(l,n),d(u,bB(e,i))])t(r)},p=e=>({section:x4(`06`,e,[],[]),actions:[],next:[],numbers:{}});if(![...s.values()].some(Number.isFinite))return p(`No stream has a cycle time to compare, so OEE could not be measured.`);let m=new Set(e.recordings.filter(e=>e.failed).map(e=>e.id)),h=new Set(t.filter(e=>!m.has(e.c.recordingId)).map(e=>e.c.streamId));for(let t of e.recordings)if(!(t.failed||!Number.isFinite(s.get(t.streamId))))for(let e=Math.floor(t.t0/900)*900;e<t.t1;e+=900){let n=Math.max(e,t.t0),r=Math.min(e+900,t.t1),i=Math.max(0,r-n-o.reduce((e,t)=>e+Math.max(0,Math.min(r,t.t1)-Math.max(n,t.t0)),0));f(n,e=>{e.plan+=i,h.has(t.streamId)||(e.stop+=i)})}for(let e of n)if(Number.isFinite(s.get(e.streamId)))for(let t=Math.floor(e.t0/900)*900;t<e.t1;t+=900){let n=Math.max(t,e.t0),r=Math.min(t+900,e.t1);f(n,t=>{t.stop+=r-n,e.kind===`no_data`&&(t.plan+=r-n)})}let g=e.value.key===`duration`,{limits:_,outside:v}=s8(r),y=!1;for(let e of t){let t=s.get(e.c.streamId)??NaN;if(!Number.isFinite(t)||m.has(e.c.recordingId))continue;let n=e.c.flag===`bad`||v(e.c.kpis)||!g&&e.level===`off`;y||=n||e.c.flag===`good`,f(e.c.tstart,e=>{e.ideal+=t,e.n++,n?e.badIdeal+=t:e.good++})}if(!c.plan)return p(`No recorded time falls in the shifts, so OEE could not be measured.`);let b=a8(c),x=r.costs.currency,S=r.costs.lineHour,C=[...new Set(t.map(e=>s.get(e.c.streamId)??NaN).filter(Number.isFinite))].sort((e,t)=>e-t),w=e=>e<60?`${T4(+e.toFixed(1))} s`:j4(e),T=C.length?r.idealCycleS?`Ideal cycle ${w(C[0])}, set in Process context.`:`Ideal cycle ${w(C[0])}${C.length>1&&w(C[0])!==w(C[C.length-1])?` to ${w(C[C.length-1])}`:``}, inferred from the data.`:``,E=e=>S===null?``:` (up to ${w4(e/3600*S,x)})`,D=[{label:l8.stops,s:c.plan-i8(c),owner:`maintenance`,act:e=>`Find what stops the line (see 05.4): ${e} of planned time stopped.`},{label:l8.slow,s:Math.max(0,i8(c)-c.ideal),owner:`production`,act:e=>`Bring the pace to the ideal cycle: slow batches and short waits cost ${e}.`},g?{label:l8.bad,s:c.badIdeal,owner:`quality`,act:e=>`Bring the bad parts inside their limits (see 04): they cost ${e}.`}:{label:l8.off,s:c.badIdeal,owner:`quality`,act:e=>`Bring off-golden batches to golden level (see 02): they cost ${e}.`}];D.sort((e,t)=>t.s-e.s);let O=D.reduce((e,t)=>e+t.s,0),k=D[0],A=[],j=[],M=[],N=e=>{let t=`F06-${A.length+1}`;return A.push({id:t,section:`06`,refs:[`06`],...e}),t};if(N({evidence:`measured`,p:null,numbers:z2({oee:b.oee,availability:b.A,performance:b.P,quality:b.Q,plannedH:c.plan/3600}),text:`OEE ${S4(b.oee)}: availability ${S4(b.A)}, performance ${S4(b.P)}, quality ${S4(b.Q)}, over ${j4(c.plan)} of planned time.${T?` ${T}`:``}`}),k.s>0){let e=N({evidence:`measured`,p:null,numbers:z2({hours:k.s/3600,share:k.s/O,cost:S===null?NaN:k.s/3600*S}),text:`${k.label} lose the most: ${j4(k.s)}${E(k.s)}, ${S4(k.s/O)} of the ${j4(O)} lost.`});j.push({text:k.act(`${j4(k.s)}${E(k.s)}`),owner:k.owner,urgent:!1,rank:k.s/c.plan,refs:[e]})}let P=r.shifts.filter(e=>l.has(e.name)).map(e=>{let t=l.get(e.name),n=a8(t);return{cells:[e.name,S4(n.A),t.n?S4(n.P):`–`,t.n?S4(n.Q):`–`,S4(n.oee)]}});O>0&&M.push({kind:`bars`,title:`06.1 · Where planned time is lost${S===null?``:`, and what it costs`}`,max:k.s/3600,rows:D.filter(e=>e.s>=60).map(e=>({label:e.label,value:e.s/3600,text:`${j4(e.s)}${E(e.s)}`,tip:`${e.label}: ${S4(e.s/O)} of the time lost`}))}),P.length>1&&!r.hideShifts&&M.push({kind:`table`,title:`06.2 · OEE by shift`,columns:[`Shift`,`Availability`,`Performance`,`Quality`,`OEE`],rows:P});let F=[...u].filter(([,e])=>e.plan>0).map(([e,t])=>({t:xB(e,`00:00`,i),v:a8(t).oee})).sort((e,t)=>e.t-t.t),I=F.length>=7?l4(F.map(e=>(e.t-F[0].t)/86400),F.map(e=>e.v)):null;if(I&&I.p<.01&&Math.abs(I.b*700)>=1){N({evidence:`statistical`,p:I.p,numbers:z2({perWeek:I.b*7,days:I.n,p:I.p}),text:`OEE ${I.b<0?`falls`:`rises`} by ${Math.round(Math.abs(I.b*700))} points a week since ${V4(F[0].t,i)}.`});let e=F[0].t,t=F[F.length-1].t;M.push({kind:`trend`,title:`06.3 · OEE per day, with its trend`,unit:`%`,points:F.map(e=>({t:e.t,v:e.v*100})),line:{t0:e,v0:I.a*100,t1:t,v1:(I.a+I.b*(t-e)/86400)*100},limit:null,crossing:null})}let L=k.s>0?`${k.label} lose the most time.`:`No planned time is lost.`,R=g&&c.n&&!y&&!_.length?[`Add specification limits to the quality channels in Process context: OEE counts every batch as good until something says which are bad.`]:[];return{section:{...x4(`06`,L,A,M),subtitle:c8,fold:!0},actions:j,next:R,numbers:{oee:b.oee,stopsS:c.plan-i8(c),slowS:Math.max(0,i8(c)-c.ideal),offS:c.badIdeal}}}function d8(e,t,n,r=[]){let i=G3(e.context??T3()).shifts,a=e.tz;if(!i.length)return{section:`11`,needs:`Add the shifts in Process context to compare them.`};let o=new Map(i.map(e=>[e.name,{n:0,good:0,stopped:0,alerts:0}])),s=e=>{let t=H3(e,i,a);return t===null?void 0:o.get(t)};for(let e of t){let t=s(e.c.tstart);t&&(t.n++,e.level!==`off`&&t.good++)}for(let t of e.alerts??[]){let e=s(t.t);e&&e.alerts++}for(let e of n)for(let t=Math.floor(e.t0/900)*900;t<e.t1;t+=900){let n=Math.max(t,e.t0),r=Math.min(t+900,e.t1),i=s(n);i&&(i.stopped+=r-n)}let c=[...o].map(([e,t])=>({name:e,...t,share:t.n?t.good/t.n:NaN})),l=c.filter(e=>e.n>=5),u=l.reduce((e,t)=>!e||t.share<e.share?t:e,null),d=u&&l.filter(e=>e!==u),f=d?.reduce((e,t)=>e+t.n,0)??0,p=d?.reduce((e,t)=>e+t.good,0)??0,m=f?p/f:NaN,h=!!u&&r.some(e=>e.text.includes(`on the ${u.name} shift`)),g=!!u&&m-u.share>=.05&&(h||o4(u.good,u.n,p,f).p<.01),_=[];if(g){let e=`The ${u.name} shift has the lowest share of batches at golden level (${S4(u.share)} against ${S4(m)}).`,t=[`11`,...h?[`02`]:[]];_.push({id:`F11-1`,section:`11`,refs:t,evidence:`measured`,p:null,text:e,numbers:{share:u.share,others:m,batches:u.n}})}let v=c.filter(e=>e.n);return{section:x4(`11`,g?_[0].text:l.length>=2?`The shifts perform alike.`:v.length===1?`Only the ${v[0].name} shift made batches in this period.`:`Too few batches in the shifts to compare them.`,_,[{kind:`table`,title:`11.1 · Shifts`,columns:[`Shift`,`Batches`,`At golden level or better`,`Stopped`,`Alerts`],rows:c.map(e=>({cells:[e.name,e.n.toLocaleString(`en-GB`),e.n?S4(e.share):`–`,j4(e.stopped),String(e.alerts)],...g&&e===u?{status:`watch`,finding:`F11-1`}:{}}))}]),actions:[],next:[],numbers:g?{share:u.share,others:m}:{}}}function f8(e,t,n=[],r,i=$6(e)){let a=e.previous,o=a?{...e,period:a.period,recordings:a.recordings,cycles:a.cycles,previous:null}:null,s=o?R2(o):[];if(!o||s.length<5)return{section:`01`,needs:`The period before this one has too few stored batches to compare with. It fills in once the cycles of that period are found.`};if(t.length<5)return{section:`01`,needs:`This period has too few batches to compare with the one before.`};let c=e=>e.filter(e=>e.level!==`off`).length,l=o4(c(t),t.length,c(s),s.length),u=e=>e.map(e=>e.c.value),d=q2(u(t)),f=q2(u(s)),p=Q2(u(t),u(s)),[m,h]=s4([l.p,p.p],P2),g=e.value.label,[_,v]=D4(d,f),y=e.value.better===`min`?p.effect<.5:p.effect>.5,b=_===v?y?`better`:`worse`:null,x=[],S=[],C=[],w=[];if(m){let e=l.p1>l.p2;x.push({id:`F01-1`,section:`01`,refs:[`01`],evidence:`statistical`,p:l.p,numbers:z2({share:l.p1,before:l.p2,p:l.p}),text:`${S4(l.p1)} of batches at golden level or better, ${e?`up`:`down`} from ${S4(l.p2)} the period before.`}),w.push({better:e,text:`${S4(l.p1)} of batches at golden level, ${e?`up`:`down`} from ${S4(l.p2)}.`}),e||(S.push(`the share at golden level`),C.push(`F01-1`))}h&&(x.push({id:`F01-2`,section:`01`,refs:[`01`],evidence:`statistical`,p:p.p,numbers:z2({median:d,before:f,p:p.p}),text:b?`${g} moved ${b} since the period before (median ${_} both times).`:`The median ${g} is ${_}, ${y?`better`:`worse`} than ${v} the period before.`}),w.push({better:y,text:b?`${g} moved ${b} (median ${_} both times).`:`the median ${g} is ${_}, against ${v}.`}),y||(S.push(g),C.push(`F01-2`)));let T=[],E=e.tz,D=`${V4(a.period.from,E)} – ${V4(a.period.to-1,E)}`;S.length&&T.push({text:`Find what changed since the period before (${D}): ${S.join(` and `)} ${S.length>1?`are`:`is`} worse.`,owner:`management`,urgent:!1,rank:Math.max(0,l.p2-l.p1),refs:[...C,...n.map(e=>e.id)]});let O=w.find(e=>!e.better)??w[0],k=O?`${O.better?`Better`:`Worse`} than the period before: ${O.text}`:`About the same as the period before.`,A=e=>e.reduce((e,t)=>e+t.t1-t.t0,0),j=(e,t,n=g6(e,t))=>n.filter(e=>e.status===`Replace`||e.status===`Drifting`).length,M=A(i),N=A($6(o));return{section:x4(`01`,k,x,[{kind:`tiles`,tiles:[{label:`At golden level or better`,value:S4(l.p1),note:`${S4(l.p2)} before`},{label:`${g} median`,value:_,note:`${v} before`},{label:`Stopped`,value:j4(M),note:`${j4(N)} before`},{label:`Sensors to replace or drifting`,value:String(j(e,t,r)),note:`${j(o,s)} before`}]}]),actions:T,next:[],numbers:z2({share:l.p1,before:l.p2,median:d,medianBefore:f,stoppedS:M,stoppedBeforeS:N})}}function p8(e,t,n,r){let{tz:i}=e,a=bB(e.period.from,i),o=bB(e.period.to-1,i),s=[];for(let e=a;e<=o&&s.length<=400;e=SB(e,1))s.push(e);if(s.length<2||s.length>400||!t.length)return null;let c=e=>s.indexOf(bB(e,i)),l=s.map(()=>0),u=s.map(()=>0),d=s.map(()=>0),f=s.map(()=>!1);for(let e of t){let t=c(e.c.tstart);t>=0&&(l[t]++,e.level===`off`&&u[t]++)}let p=s.map(e=>[xB(e,`00:00`,i),xB(SB(e,1),`00:00`,i)]);for(let e of n)p.forEach(([t,n],r)=>{d[r]+=Math.max(0,Math.min(n,e.t1)-Math.max(t,e.t0))});let m=r??e.recordings.flatMap(e=>Object.values(e.health?.channels??{}).filter(e=>!e.clock).flatMap(e=>e.flats));for(let e of m)p.forEach(([t,n],r)=>{e.t1>t&&e.t0<n&&(f[r]=!0)});return s.every((e,t)=>!u[t]&&d[t]<60&&!f[t])?null:{kind:`strip`,title:`00.3 · The period day by day: the share of batches off the golden, with stops and failing sensors marked`,legend:`off the golden`,days:s.map((e,t)=>{let n=new Date(`${e}T00:00:00Z`),r=`${G4[(n.getUTCDay()+6)%7]} ${n.getUTCDate()} ${n.toLocaleString(`en-GB`,{month:`short`,timeZone:`UTC`})}`,i=[l[t]?`${P4(l[t],`batch`,`batches`)}, ${S4(u[t]/l[t])} off the golden`:`no batches`,...d[t]>=60?[`stopped ${j4(d[t])}`]:[],...f[t]?[`a sensor stuck`]:[]];return{day:e,label:r,n:l[t],off:l[t]?u[t]/l[t]:null,stopS:d[t],sensor:f[t],text:`${r}: ${i.join(`, `)}`}})}}var m8={management:`Management`,quality:`Quality`,maintenance:`Maintenance`,production:`Production`},h8=e=>e.findings.length||e.id===`01`?e:{...e,charts:[],notes:[]},g8=(e,t)=>{let n=t.filter(e=>!!e);return{...e,section:G6(h8(e.section),n),actions:[...e.actions,...n.flatMap(e=>e.actions)],next:[...e.next,...n.flatMap(e=>e.next)]}},_8=e=>({cells:[e.id,e.text,m8[e.owner]],...e.urgent?{status:`crit`}:{}});function v8(e){let t=h6(e);if(!t.size)return e;let n=e=>e&&Object.fromEntries(Object.entries(e).filter(([e])=>!t.has(e)));return{...e,cycles:e.cycles.map(e=>({...e,z:n(e.z),d:n(e.d)})),goldens:e.goldens.map(e=>({...e,edges:n(e.edges)}))}}function y8(e){let t=R4(e.tz)?e:{...e,tz:`UTC`},n=v8(t.context?{...t,context:G3(t.context)}:t),r=R2(n),i=z6(n,r),a=i3(n,r),o=_6(n,r),{stops:s,offGaps:c}=e8(n),l=t8(n,s,c),u=g8(o.out,[l,U6(n,o.drifts,o.wear)]),d=o.out.numbers.replace+o.out.numbers.drifting+o.out.numbers.watch,f=!o.out.section.findings.length&&l?.findings.length?{...u,section:{...u.section,verdict:`${l.findings[0].text}${d?` ${o.out.section.verdict}`:``}`}}:u,p=h8(i.section),m=h8(a.section),h=h8(f.section),g=c3(n,r),_=E6(n,r,o.sensors),v=g===null?C6(n,r):null,y=_?`${P4(_.findings.reduce((e,t)=>e+t.numbers.batches,0),`batch`,`batches`)} to check before they ship: made while a sensor was failing.`:v?`${P4(v.findings.length,`feature`)} left ${v.findings.length===1?`its`:`their`} control limits; no specification limits say which batches are bad.`:``,b=!_&&!v?g:g&&!(`needs`in g)?g8(g,[_]):[g,g8({section:{...x4(`04`,y,[],[]),fold:!0,subtitle:b4(_?`Containment: batches made while a sensor was failing`:`Control chart (Shewhart individuals, 3σ)`)},actions:[],next:[],numbers:{}},[_,v])],x=T6(n,r),S=[f8(n,r,x&&!(`needs`in x)?x.section.findings:[],o.sensors,s),b,u8(n,r,s),e3(n,r),x,A6(n,r),B6(n,r),n.context?.hideShifts?null:d8(n,r,s,i.section.findings)].flat(),C=S.filter(e=>!!e&&!(`needs`in e)),w=S.filter(e=>!!e&&`needs`in e),T=C.map(e=>h8(e.section)),E=new Set(T.map(e=>e.id)),D=[...i.actions,...a.actions,...f.actions,...C.flatMap(e=>e.actions)].sort((e,t)=>Number(t.urgent)-Number(e.urgent)||t.rank-e.rank).map((e,t)=>({id:`A${t+1}`,text:e.text,owner:e.owner,urgent:e.urgent,refs:e.refs})),O=D.slice(0,3),k=x4(`12`,D.length?`Start with ${F4(O.map(e=>e.id))}: ${O.some(e=>e.urgent)?`urgent items`:`the largest effect`} first.`:`Nothing to act on in this period.`,[],D.length?[{kind:`table`,title:`12.1 · Actions, most urgent first`,columns:[`#`,`Action`,`Owner`],rows:D.map(_8),...D.length>5?{shown:5,more:P4(D.length-5,`more action`)}:{}}]:[]),A=[...new Set([...i.next,...a.next,...f.next,...C.flatMap(e=>e.next)])],j=x4(`13`,A[0]??`Nothing left unexplained that more data would answer.`,[],[],A.slice(1)),M=r.filter(e=>e.level!==`off`).length,N=D.filter(e=>e.urgent).length,P=e=>{let t=new Set(e.findings.map(e=>e.id)),n=D.findIndex(e=>e.refs.some(e=>t.has(e)));return n<0?1/0:n},F=[p,h,m,...T].filter(e=>e.findings.length).map(e=>({s:e,i:P(e)})).sort((e,t)=>e.i-t.i||0).map(e=>e.s),I=n.value.key===`duration`?r.reduce((e,t)=>e+Math.max(0,t.gap),0):0,L=s8(n.context),R=C.find(e=>e.section.id===`06`)?.numbers,z=C.find(e=>e.section.id===`09`)?.section.findings.find(e=>e.id===`F09-2`)?.numbers.extra,B=V6(n,{time:R&&`slowS`in R?[{label:l8.stops,s:R.stopsS,owner:m8.maintenance,ref:`06`},{label:l8.slow,s:R.slowS,owner:m8.production,ref:`06`},n.value.key===`duration`?{label:l8.bad,s:R.offS,owner:m8.quality,ref:`06`,bad:!0}:{label:l8.off,s:R.offS,owner:m8.quality,ref:`06`}]:[{label:`Stops`,s:s.reduce((e,t)=>e+t.t1-t.t0,0),owner:m8.maintenance,ref:`05`},{label:`Batches slower than the golden`,s:I,owner:m8.production,ref:`02`}],energyKwh:z??null,review:_&&E.has(`04`)?{batches:_.findings.reduce((e,t)=>e+t.numbers.batches,0),s:_.findings.reduce((e,t)=>e+t.numbers.seconds,0)}:null,scrap:L.limits.length||r.some(e=>e.c.flag===`bad`||e.c.flag===`good`)?{batches:r.filter(e=>e.c.flag===`bad`||L.outside(e.c.kpis)).length,assumed:!1}:n.value.key===`duration`?null:{batches:r.length-M,assumed:!0}}),V=p8(n,r,s,o.sensors.flatMap(e=>e.stuck)),ee=o.sensors.filter(e=>e.status===`Drifting`),te=new Set(ee.map(e=>e.sid)),H=x4(`00`,r.length?`${S4(M/r.length)} of batches at golden level or better${N?`, and ${P4(N,`urgent item`)}`:``}.`:`No batches could be compared with a golden in this period.`,F.map((e,t)=>({id:`F00-${t+1}`,section:`00`,text:e.verdict,evidence:e.findings[0].evidence,p:e.findings[0].p,refs:[e.id],numbers:e.findings[0].numbers})),[...B?[B]:[],...O.length?[{kind:`table`,title:`00.2 · What to do first`,columns:[`#`,`Action`,`Owner`],rows:O.map(_8),ref:`12`}]:[],...V?[V]:[],{kind:`tiles`,tiles:[{label:`Batches`,value:r.length.toLocaleString(`en-GB`),note:P4(n.recordings.length,`file`)},{label:`At golden level or better`,value:r.length?S4(M/r.length):`–`},...a.numbers.better?[{label:`Better than the golden`,value:a.numbers.better.toLocaleString(`en-GB`)}]:[],...f.numbers.replace?[{label:f.numbers.replace===1?`Sensor to replace`:`Sensors to replace`,value:String(f.numbers.replace)}]:[],...ee.length?[{value:String(ee.length),label:`${ee.length===1?`Channel`:`Channels`} drifting${te.size>1?` on ${te.size} streams`:n.streams.length>1?`${ee.length>1?`, all`:``} on ${n.streams.find(e=>e.id===ee[0].sid)?.name??`one stream`}`:``}`}]:[]]}]),ne=n.recordings.filter(e=>!e.failed&&!e.unread),re=n.recordings.filter(e=>e.failed),ie=n.recordings.filter(e=>e.unread).length,U=e=>n.streams.find(t=>t.id===e)?.name??`A stream`,ae=x4(`14`,`How the findings were made and how sure each one is.`,[],[],[`Cycles found with “${n.rule.name}” v${n.rule.version} in ${P4(n.recordings.length,`recording`)} of ${P4(n.streams.length,`stream`)}, ${S4(n.recordings.length?ne.length/n.recordings.length:0)} read${ie?`; ${ie} not read, counted through ${ie===1?`its`:`their`} stored cycles and measures`:``}${re.length?` (could not be read: ${re.map(e=>`${e.name}, ${e.failed}`).join(`; `)})`:``}.`,...n.goldens.map(e=>`${U(e.streamId)}: compared with ${e.label}${e.proposed?`, proposed because no golden is set`:e.auto?`, set by this report because none was set (the best ${n.value.label} that 1 batch in 20 reaches, and at least 5); change it with Make it the golden or in Batches`:``}, on ${P4(Object.keys(e.edges).length,`channel`)}.`),`A batch is at golden level when its ${n.value.label} is within 2% of the golden’s (or twice the spread of the golden’s own batches), and better than the golden beyond that on the good side.`,`Shares of the batch-to-batch variation in the gap: a least-squares fit, over all measured batches, of each batch’s gap on its deviation from the golden by channel and phase, split with Pratt’s measure; only deviations that differ between off-golden batches and the rest enter (Mann–Whitney, Benjamini–Hochberg at q = 0.01 across channel × phase). Shares and what better batches do differently are correlations: leads to test, not proven causes.`,`Patterns: two-proportion tests (Fisher’s exact test with small counts), Benjamini–Hochberg at q = 0.01 across streams and across files; a group is named only when it runs at least 5 points more off-golden than the rest. What better batches do differently: Mann–Whitney per measure, Benjamini–Hochberg at q = 0.01 across measures. The proposed golden of a stream: the best value at least 5 of its batches reach. Intervals: bootstrap over batches (1,000 resamples; over 2,000 batches, resamples of 2,000 scaled to the period). p-values are shown as they are, never as a confidence.`,...s.length||c?[`Stops (05.4): no data for ${300/60} minutes or more, or no batch for ${300/60} minutes or more and at least 5× the usual wait between two batches; planned stops and time outside the shifts left out${n.context?.shifts.length?``:`; without shifts, no data for more than ${K6/3600} h is time off, not a stop`}; a stop is given a machine unit when one of its channels went flat within 60 s of the stop’s start.`]:[],`Sensor health per recording: gaps (steps over 4× the usual), flat runs (${300/60} minutes or more of one repeated value; runs at the same value with up to ${o6/3600} h between them, a stop or a file boundary, are one; a sensor is stuck only where batches were made meanwhile, not while the line stood still), noise (median absolute deviation of sample-to-sample changes), spikes (Hampel filter, 6 robust σ), rate drops, and values outside the range learned from the first third of the period’s recordings. Drift: a straight-line trend of each channel’s offset from the golden, forecast to the golden’s band edge; an offset that stepped once and stayed is a change, not a drift. Counters (an energy meter, a part count) are not compared with the golden.`,...t===e?[]:[`Times in UTC: the time zone “${e.tz}” is not known.`],`Drifts and wear are fitted on daily means (batches of one day are not independent), with Student’s t. Over fewer than 7 days a drift is fitted on means per recording (per hour with fewer than 6 recordings), at least 6 of them, and says so: those means are not independent either, so a short drift is a lead to confirm over more days. Drifts are kept at Benjamini–Hochberg q = 0.01 across sensors; the day a drift reaches the band edge has a 99 % interval by inverse prediction (Fieller).`,...g&&!(`needs`in g)?[`Capability (04.1): Ppk = min(USL − mean, mean − LSL) / 3σ of each cycle KPI (mean, minimum, maximum, at start, at end) whose channel has specification limits in Process context, over at least 30 batches; capable from ${n.context?.ppkMin??1.33}. ${a3}`]:[],...v?[`Control chart (04.3): per stream, each level KPI of the batches in time order; centre line = the mean, σ = the average moving range / 1.128, limits = mean ± 3σ, from 30 batches; a KPI is named when more than ${(2*v6*100).toFixed(2)}% of its batches are outside (twice what a stable process leaves by chance). It says the process moved, not that a batch is bad.`]:[],...h.charts.some(e=>`title`in e&&e.title.startsWith(`05.5`))?[`Maintenance (05.5): each recalibration by the lower end of its crossing’s 99 % interval, placed in the latest planned stop before it.`]:[],..._&&E.has(`04`)?[`Batches made while a sensor was failing (04.2): the flat runs (05.1) and the drift past the band edge (05.2) of the sensors a golden compares; a batch counts when it starts inside one.`]:[],...E.has(`06`)?[`OEE (06), with the ratios of ISO 22400-2: planned time is the recorded time inside the shifts less planned stops, plus the stops with no data (05.4); availability = the time not stopped (planned time less 05.4’s stops) / planned time; performance = the ideal cycle × batches / the time not stopped, the ideal cycle being ${n.context?.idealCycleS?`the one set in Process context`:`inferred from the data: the golden’s cycle time plus the shortest wait between two batches that 1 wait in 20 reaches`}; quality = good batches / batches: not flagged bad and inside the specification limits${n.value.key===`duration`?``:`, and at golden level or better`}. The daily trend is a straight line over 7 days or more, kept at p < 0.01.`]:[],...E.has(`07`)?[`Alerts (07): the project’s alert rules run over the period’s recordings; an alert comes before a batch when raised in the ${Q4/3600} h before it starts or while it runs; two-proportion tests (Fisher’s exact test with small counts), Benjamini–Hochberg at q = 0.01 across rules.`]:[],...E.has(`08`)?[`Changes (08): consecutive flat runs of a setting at values more than 3 noise σ apart; the effect by Mann–Whitney on the 20 batches each side, Benjamini–Hochberg at q = 0.01 across the changes.`]:[],...E.has(`09`)?[`Energy (09): per batch, a power channel (W, kW, MW) integrated over the batch, or an energy meter (Wh, kWh, MWh) by its change; the period’s energy is what a meter counted over the recordings (the batches’ energy with a power channel); off-golden batches against the rest by Mann–Whitney. CO₂ is the energy times the grid factor entered in Process context: Scope 2, location-based.`]:[],...E.has(`10`)?[`Lines (10): each line’s batches against its own streams’ goldens; each line against the other lines by two-proportion tests, Benjamini–Hochberg at q = 0.01 across lines.`]:[],...E.has(`11`)?[`Shifts (11): measured counts per shift (batches, the share at golden level or better, stopped time in 15-minute blocks, alerts); the weakest shift is named when its share differs from the other shifts’ by a two-proportion test at p < 0.01, or when 02.4 named it.`]:[],...E.has(`01`)?[`Since the last period (01): the previous period’s stored batches judged against the current goldens; the share at golden level by a two-proportion test and the value by Mann–Whitney, Benjamini–Hochberg at q = 0.01 across the two.`]:[],`Findings computed by Kymoscope, worded from fixed templates; no AI was used.`]),oe=n.goldens,se=m6(n),ce=Object.keys(n.units).filter(e=>!se.has(e)).length;return{v:1,cover:{title:`Report ${V4(n.period.from,n.tz)} – ${V4(n.period.to-1,n.tz)}`,project:n.project,period:n.period,cycle:`${n.rule.name} v${n.rule.version}`,value:`${n.value.label}, ${n.value.better===`min`?`lower`:`higher`} is better`,golden:oe.length===1?`${oe[0].label}${oe[0].proposed?` (proposed: no golden set)`:oe[0].auto?` (set automatically: none was set)`:``}`:oe.length?`${oe.length} goldens, one per stream`:`None`,data:`${P4(n.streams.length,`stream`)} · ${P4(n.recordings.length,`file`)}${ce||!ie?` · ${P4(ce,`channel`)}`:``}`,madeBy:n.madeBy,madeAt:n.madeAt,tz:n.tz,context:n.contextVersion?`Process context v${n.contextVersion}`:`None set`},actions:D,sections:[H,p,m,...T,h,k,j,ae].sort((e,t)=>e.id.localeCompare(t.id)),missing:[...new Map([...J3(n.context??null,n.alertRules?.length??0),...w].map(e=>[`${e.section} ${e.needs}`,e])).values()].map(e=>({section:e.section,title:_4[e.section],needs:e.needs})).sort((e,t)=>e.section.localeCompare(t.section))}}function b8(e){let t=new Set((e.fold?e.charts.slice(0,1):e.charts).flatMap(e=>e.kind===`table`?e.rows.flatMap(e=>e.finding?[e.finding]:[]):[])),n=e.shown??e.findings.length,r=e=>!t.has(e.id);if(e.fold){let t=e.findings.filter(r);return{full:t.slice(0,n),rest:t.slice(n)}}return{full:e.findings.slice(0,n).filter(r),rest:e.findings.slice(n).filter(r)}}function x8(e,t){return t===`full`?e.sections:e.sections.filter(e=>e.roles.includes(t))}var S8={verdict:30,sentence:35,action:30},C8={verdict:250,sentence:300,action:250},w8=/\b(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|hundred|thousand|million|dozen|half|twice|double|triple)\b/i,T8=/\b(\d{1,2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?/gi,E8=e=>e.normalize(`NFKC`).replace(/−/g,`-`),D8=e=>w8.test(E8(e))||/(?![0-9])\p{Nd}/u.test(E8(e)),O8=e=>{let t=E8(e),n=[];return t=t.replace(T8,(e,t,r)=>(n.push(`${+t} ${r.toLowerCase()}`),` `)),[...n,...(t.match(/[-+]?(?:\d[\d,]*)?\.?\d+%?/gu)??[]).map(e=>e.replace(/,/g,``))]},k8=e=>!!e&&typeof e==`object`&&!Array.isArray(e),A8=e=>Array.isArray(e)?e.filter(k8):[];function j8(e,t){let n=new Map(e.sections.flatMap(e=>e.findings.map(e=>[e.id,e.text]))),r=(e,t,r,i,a=!0)=>{if(!k8(e))return null;let o=typeof e.text==`string`?e.text.trim():``,s=Array.isArray(e.cites)?[...new Set(e.cites)]:[];if(!o||!s.length||!s.every(e=>typeof e==`string`&&n.has(e)&&i.has(e))||o.length>t.chars||o.split(/\s+/).length>t.words||D8(o))return null;let c=new Set([...r,...a?s.map(e=>n.get(e)):[]].flatMap(O8));return O8(o).every(e=>c.has(e))?{text:o,cites:s}:null},i=e=>({words:S8[e],chars:C8[e]}),a=k8(t)?t:{},o=new Map(A8(a.actions).map(e=>[e.id,e])),s=e.actions.flatMap(e=>{let t=r(o.get(e.id),i(`action`),[e.text],new Set(e.refs));return t?[{id:e.id,text:t.text,cites:t.cites}]:[]}),c=new Map(A8(a.sections).map(e=>[e.id,e])),l=new Map(e.sections.map(e=>[e.id,e.findings.map(e=>e.id)])),u=t=>new Set(t.id===`12`?e.actions.flatMap(e=>e.refs):[...l.get(t.id),...t.id===`00`?t.findings.flatMap(e=>e.refs.flatMap(e=>l.get(e)??[])):[]]);return{sections:e.sections.flatMap(e=>{let t=e.id===`14`?void 0:c.get(e.id);if(!t)return[];let n=u(e),a=r(t.verdict,i(`verdict`),[e.verdict],n,!1),o=(Array.isArray(t.sentences)?t.sentences:[]).map(e=>r(e,i(`sentence`),[],n)).filter(e=>!!e).slice(0,2);return a||o.length?[{id:e.id,verdict:a,sentences:o}]:[]}),actions:s}}var M8=e=>`Findings computed by Kymoscope. Text written by Kymoscope’s AI (${e}) from the findings and the Process context only, never from the data; every sentence names the findings it rests on.`;function N8(e,t){let n=t?G3(t):null;return{process:n?.process??``,channels:Object.entries(n?.channels??{}).flatMap(([e,t])=>{let n=E3(t);return n&&n!==`ignore`?[{name:e,role:S3[n],unit:t.unit}]:[]}).slice(0,200),sections:e.sections.filter(e=>e.id!==`14`).map(e=>({id:e.id,title:e.title,verdict:e.verdict,findings:e.findings.map(e=>({id:e.id,text:e.text,evidence:Z4(e),refs:e.refs}))})),actions:e.actions.map(e=>({id:e.id,text:e.text,owner:e.owner,refs:e.refs}))}}function P8(e,t,n){let r=j8({sections:e.sections.map(e=>({id:e.id,verdict:e.verdict,findings:e.findings})),actions:e.actions},t),i=new Map(r.actions.map(e=>[e.id,e.text])),a=e.actions.map(e=>i.has(e.id)?{...e,text:i.get(e.id)}:e),o=new Map(a.map(e=>[e.id,e.text])),s=new Map(r.sections.map(e=>[e.id,e])),c=e.sections.map(e=>{let t=e.charts.map(e=>e.kind===`table`&&e.columns[0]===`#`?{...e,rows:e.rows.map(e=>o.has(e.cells[0])?{...e,cells:[e.cells[0],o.get(e.cells[0]),...e.cells.slice(2)]}:e)}:e),n=s.get(e.id);if(!n)return{...e,charts:t};let r=new Set(e.charts.flatMap(e=>e.kind===`table`?e.rows.flatMap(e=>e.finding?[e.finding]:[]):[])),i=e.findings.length===1&&r.has(e.findings[0].id)?[]:n.sentences;return{...e,charts:t,...n.verdict?{verdict:n.verdict.text}:{},...i.length?{ai:i}:{}}}),l=new Map(c.map(e=>[e.id,e.verdict])),u=c.map(e=>e.id===`00`?{...e,findings:e.findings.map(e=>({...e,text:l.get(e.refs[0])??e.text}))}:e.id===`14`?{...e,notes:[...e.notes.slice(0,-1),M8(n)]}:e);return{...e,cover:{...e.cover,ai:n},sections:u,actions:a}}var F8=.5,I8=5400,L8=/^[kM]?Wh?$/,R8=86400/300,z8=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],B8=e=>{let t=Math.round((e%86400+86400)%86400/60)%1440;return`${String(Math.floor(t/60)).padStart(2,`0`)}:${String(t%60).padStart(2,`0`)}`},V8=(e,t)=>Math.round(e/t)*t;function H8(e){if(!e.length)return null;let t=q2(e.map(e=>e.p01??e.lo)),n=q2(e.map(e=>e.p99??e.hi));if(!(n>t))return null;let r=Math.floor(Math.log10(n-t)),i=10**(r-1),a=Math.max(0,1-r);return{lo:+(Math.floor(t/i)*i).toFixed(a),hi:+(Math.ceil(n/i)*i).toFixed(a)}}function U8(e){let t=new Set(e.filter(e=>e.batches.length).map(e=>e.streamId)),n=e.flatMap(e=>t.has(e.streamId)?e.batches:[[e.t0,e.t1]]).filter(([e,t])=>t>e).sort((e,t)=>e[0]-t[0]),r=[];for(let[e,t]of n){let n=r[r.length-1];n&&e-n[1]<600?n[1]=Math.max(n[1],t):r.push([e,t])}return r}function W8(e,t){let n=new Map,r=e=>{let r=Math.floor(e/3600),i=n.get(r);return i===void 0&&n.set(r,i=yB(e,t)),e+i},i=new Map;for(let[t,n]of e)for(let e=Math.ceil((t-300/2)/300)*300+300/2;e<n;e+=300){let t=r(e),n=Math.floor(t/86400),a=Math.floor((t-n*86400)/300),o=i.get(n);o||i.set(n,o=new Set),o.add(a)}return i}function G8(e){let t=[...e.keys()].sort((e,t)=>e-t);if(t.length<3||t[t.length-1]-t[0]<13)return null;let n=Array(7).fill(0),r=Array(7).fill(0);for(let i=t[0];i<=t[t.length-1];i++){let t=(i+3)%7;n[t]++,e.has(i)&&r[t]++}let i=[0,1,2,3,4,5,6].filter(e=>n[e]>=2&&r[e]===0),a=[0,1,2,3,4,5,6].filter(e=>!i.includes(e));return!i.length||!a.length||a.some(e=>r[e]/n[e]<.6)?null:{name:i.join()===`5,6`?`Weekend`:`No work on ${i.map(e=>z8[e]).join(`, `)}`,from:`00:00`,to:`00:00`,days:i}}function K8(e){let t={shifts:[],stops:[]};if(e.size<3)return t;let n=Array.from({length:R8},(t,n)=>[...e.values()].filter(e=>e.has(n)).length/e.size),r=n.map(e=>e>=F8),i=[],a=r.indexOf(!0);if(a<0)return t;for(let e=0;e<R8;e++){let t=(a+e)%R8;if(r[t])continue;let n=i[i.length-1];n&&(n.a+n.n)%R8===t?n.n++:i.push({a:t,n:1})}let o=i.filter(e=>e.n*300>=600&&e.n*300<=5400),s=i.filter(e=>e.n*300>I8);for(let e of i.filter(e=>e.n*300<600))for(let t=0;t<e.n;t++)r[(e.a+t)%R8]=!0;let c=i.filter(e=>e.n*300>=600).flatMap(e=>Array.from({length:e.n},(t,r)=>n[(e.a+r)%R8])),l=n.filter((e,t)=>r[t]),u=e=>e.reduce((e,t)=>e+t,0)/e.length;if(!c.length||u(l)<.7||u(c)>.25)return t;let d=[];if(!s.length)d.push({a:0,b:86400,pauses:[]});else for(let e=0;e<s.length;e++){let t=(s[e].a+s[e].n)%R8*300,n=s[(e+1)%s.length].a*300;d.push({a:t,b:n>t?n:n+86400,pauses:[]})}let f=!s.length;for(let e of o){let t=e.a*300,n=t+e.n*300,r=d.find(e=>f||t>=e.a&&n<=e.b||t+86400>=e.a&&n+86400<=e.b);r&&r.pauses.push(f||t>=r.a?{a:t,b:n}:{a:t+86400,b:n+86400})}let p=[],m=[];for(let e of d){e.pauses.sort((e,t)=>e.a-t.a);let n=[...e.pauses],r=e=>(e.a+e.b)/2;for(;;){if(f&&n.length<2){n.length=0;break}let t=-1,i=1/0;if(n.forEach((a,o)=>{let s=o>0?r(n[o-1]):f?r(n[n.length-1])-86400:e.a,c=o<n.length-1?r(n[o+1]):f?r(n[0])+86400:e.b,l=Math.min(r(a)-s,c-r(a));l<i&&(i=l,t=o)}),t<0||i>=21600)break;n.splice(t,1)}for(let t of e.pauses.filter(e=>!n.includes(e))){let e=V8(t.a,900),n=V8(t.b,900);n>e&&m.push({name:`Break`,from:B8(e),to:B8(n)})}let i=n.map(e=>V8(r(e),1800)),a=f?i:[V8(e.a,1800),...i,V8(e.b,1800)],o=f?i.map((e,t)=>({a:e,b:t<i.length-1?i[t+1]:i[0]+86400})):a.slice(0,-1).map((e,t)=>({a:e,b:a[t+1]}));if(f&&!o.length)return t;for(let e of o){let t=e.b-e.a,n=Math.round(t/(8*3600));if(n>=2&&Math.abs(t-n*8*3600)<=3600)for(let r=0;r<n;r++)p.push({a:V8(e.a+r*t/n,1800),b:V8(e.a+(r+1)*t/n,1800)});else t>=3600&&p.push(e)}}let h=e=>(e%86400+86400)%86400;return{shifts:p.sort((e,t)=>h(e.a)-h(t.a)).map((e,t)=>({name:`Shift ${t+1}`,start:B8(e.a),end:B8(e.b)})),stops:m}}function q8(e){let t=new Map;for(let n of e){if(!n.rule||!n.channels.length)continue;let e=`${n.rule}|${n.channels.map(e=>e.name).sort().join(`\0`)}`;t.set(e,[...t.get(e)??[],n])}return([...t.values()].filter(e=>e.length>=2).sort((e,t)=>t.length-e.length)[0]??[]).map(e=>({name:e.name,streams:[e.id]})).sort((e,t)=>e.name.localeCompare(t.name))}function J8(e){let t=new Map;for(let n of e){let e=n.includes(`.`)?n.indexOf(`.`):n.indexOf(`_`);e>0&&t.set(n.slice(0,e),[...t.get(n.slice(0,e))??[],n])}return[...t].filter(([,t])=>t.length>=2&&t.length<e.length).map(([e,t])=>({name:e,channels:t.sort()})).sort((e,t)=>e.name.localeCompare(t.name))}function Y8(e,t){return Object.keys(e).filter(n=>{let r=e[n].filter(e=>!e.clock&&e.noise!==void 0&&e.flatS!==void 0&&e.n&&e.rateHz),i=r.reduce((e,t)=>e+t.n/t.rateHz,0),a=r.reduce((e,t)=>e+(t.flatRuns??0),0);return r.length>0&&r.every(e=>e.noise===0)&&i>0&&r.reduce((e,t)=>e+t.flatS,0)>=.9*i&&!(t>=10&&a>=.5*t)}).sort()}function X8(e){let t={};for(let n of e.streams)for(let e of n.channels)t[e.name]||(t[e.name]=e.unit);let n={};for(let[t,r]of Object.entries(e.health)){if(r.some(e=>e.clock))continue;let e=H8(r.filter(e=>e.moves!==!1));e&&(n[t]=e)}let r=W8(U8(e.recordings),e.tz),i=K8(r),a=G8(r);return{units:t,ranges:n,energy:Object.keys(t).filter(e=>L8.test(t[e].trim())).sort(),settings:Y8(e.health,e.recordings.reduce((e,t)=>e+t.batches.length,0)),shifts:i.shifts,stops:[...i.stops,...a?[a]:[]],lines:q8(e.streams),machines:J8(Object.keys(t))}}function Z8(e,t){let n=Object.create(null);for(let[t,r]of Object.entries(e.channels))n[t]=r;for(let e of[...Object.keys(t.units),...Object.keys(t.ranges),...t.settings])n[e]||(n[e]=w3(t.units[e]??``));for(let[e,r]of Object.entries(n)){let i=r;!i.unit&&t.units[e]&&(i={...i,unit:t.units[e],unitSuggested:!0});let a=t.ranges[e];a&&i.lo===null&&i.hi===null&&(i={...i,lo:a.lo,hi:a.hi,rangeSuggested:!0}),t.energy.includes(e)&&i.role===null?i={...i,role:`energy`,suggested:!0}:t.settings.includes(e)&&i.role===null&&(i={...i,role:`setting`,suggested:!0}),n[e]=i}let r=e=>e.map(e=>({...e,suggested:!0})),i=new Set(Object.keys(n));return{...e,channels:n,shifts:e.shifts.length?e.shifts:r(t.shifts),stops:e.stops.length?e.stops:r(t.stops),lines:e.lines.length?e.lines:r(t.lines),units:e.units.length?e.units:r(t.machines.map(e=>({...e,channels:e.channels.filter(e=>i.has(e))})).filter(e=>e.channels.length))}}function Q8(e){let t=new Map,n=(e,n)=>{for(let r of n)t.set(r,[...t.get(r)??[],e])},r=e=>e.filter(e=>e.suggested).length,i=(e,t)=>`${e} ${t}${e===1?``:`s`}`;r(e.shifts)&&n(i(r(e.shifts),`shift`),[`02`,`05`,`06`,`11`]),r(e.stops)&&n(i(r(e.stops),`planned stop`),[`05`,`06`]),r(e.lines)&&n(i(r(e.lines),`line`),[`10`]),r(e.units)&&n(i(r(e.units),`machine unit`),[`05`]);let a=Object.keys(e.channels).filter(t=>e.channels[t].role===`energy`&&e.channels[t].suggested);a.length&&n(`the energy channel ${a.sort()[0]}`,[`09`]);let o=Object.keys(e.channels).filter(t=>e.channels[t].role===`setting`&&e.channels[t].suggested);return o.length&&n(i(o.length,`adjustable setting`),[`08`]),t}var $8=It({AI_NOTE:()=>M8,AI_SENTENCES:()=>2,AI_WORDS:()=>S8,ALPHA:()=>P2,CHANNEL_ROLES:()=>x3,CHANNEL_ROLE_TEXT:()=>S3,EVIDENCE_TEXT:()=>g4,GOLDEN_SHARE:()=>F2,HealthAcc:()=>i6,MIN_GROUP:()=>5,OFF_GOLDEN_PCT:()=>2,PRESETS:()=>u3,PRESET_IDS:()=>l3,PROCESS_MAX:()=>C3,REPORT_ROLES:()=>h4,SECTION_ROLES:()=>y4,SECTION_TITLES:()=>_4,aiInput:()=>N8,applyAi:()=>P8,applyInferred:()=>Z8,applyPreset:()=>b3,assumedSections:()=>Q8,buildReport:()=>y8,classify:()=>R2,completeness:()=>X3,confirmAll:()=>q3,confirmed:()=>G3,contextGaps:()=>J3,dateText:()=>V4,dateTimeText:()=>H4,emptyChannel:()=>w3,emptyContext:()=>T3,energyChannel:()=>D3,evidenceLabel:()=>Z4,exact:()=>E4,goldenRank:()=>I2,inferContext:()=>X8,listedFindings:()=>b8,moneyGaps:()=>Y3,namesOf:()=>_3,num:()=>T4,pText:()=>X4,parseContext:()=>z3,pct1:()=>C4,presetForIndustry:()=>f3,presetOf:()=>d3,roleOf:()=>E3,shiftOf:()=>H3,spanText:()=>W4,stopSpans:()=>W3,suggestedCount:()=>K3,term:()=>g3,usualRange:()=>a6,viewSections:()=>x8});export{sQ as ANNOTATION_CONTROLS_ATTR,zt as ANNOTATION_KINDS,l1 as AxisState,wB as BEACON_STATS,v2 as BrowserRecorder,A0 as CAMERA_QUALITIES,Ve as CHAIN_LIVE,Ne as CHAIN_RECORDING,x3 as CHANNEL_ROLES,S3 as CHANNEL_ROLE_TEXT,dr as CHART_ALARM_FIELDS,b$ as CHART_KINDS,GB as CYCLE_TIME,B0 as CameraSender,Se as ChainLane,RB as CycleRunner,zB as CycleSet,Yt as DASHBOARD_GRID_COLS,Zt as DASHBOARD_GRID_GAP_PX,Xt as DASHBOARD_GRID_ROWS,rB as DATASET_PALETTE,Bt as DEFAULT_ANNOTATION_WIDTH,fn as DEFAULT_AXIS_LINE,mn as DEFAULT_BEACON,pn as DEFAULT_GRID_LINE,Cn as DEFAULT_TRACE_WIDTH,Sn as DEFAULT_XYZ_POINT_RADIUS,xn as DEFAULT_XY_POINT_RADIUS,g4 as EVIDENCE_TEXT,j2 as EXPORT_TYPES,NT as FUNCTION_REFERENCE,i6 as HealthAcc,AV as IMPORTABLE_EXT,F as KIND_CHAIN,u as KIND_VIDEO,fB as KPI_STATS,Re as KRC_HEADER_BYTES,CB as KpiAcc,HE as KymoscopeError,pt as LEAF_KEYS,n as LIVE_TIME_COLUMN,j0 as LOW_PRESET,k0 as LivePublisher,a1 as MAX_BAND_CELLS,i1 as MAX_GRID,er as MAX_PANEL_CAMERAS,tn as MIN_PANEL_H,en as MIN_PANEL_W,L as OPEN_STREAM_PASSWORD,u3 as PRESETS,l3 as PRESET_IDS,C3 as PROCESS_MAX,h4 as REPORT_ROLES,r0 as RecordedVideoSource,T0 as RegistryError,_4 as SECTION_TITLES,Kt as SEVERITY_HEX,i0 as SPLIT_STEPS,R1 as UNLIMITED,HX as VIDEO_LIMIT_NOTICE,R$ as VIDEO_MAX_FRAGMENT,lE as WINDOW_FN_NAMES,B as WORKBOOK_EXPORT_AAD,N8 as aiInput,p as alertRuleAad,u1 as alignSegment,$8 as analysis,P8 as applyAi,Z8 as applyInferred,b3 as applyPreset,un as arrangeAutoLayout,o1 as axisColumn,_1 as bandEdges,AB as bestCycleIndex,y as bindKeyAad,s2 as bufferLabel,fG as buildEquation,PE as buildMathChannelsBlob,p1 as buildReference,y8 as buildReport,MV as buildTree,Qn as cameraLabel,re as chainVerifier,fr as chartAlarm,Nz as chartChannelCount,S$ as chartLabel,_r as clampPct,rn as clampRectForKind,cr as coerceAlarmLine,Wt as coerceAnnotation,CX as colorAt,iB as colorForDataset,lB as colorSchemeOf,EX as colorsCss,Ze as columnIsNumeric,mB as compareOp,v1 as compareToReference,X3 as completeness,lG as computePolyFit,uG as computeR2,q3 as confirmAll,G3 as confirmed,X1 as createEngine,dt as createRuleEvaluator,$B as cutCycle,LB as cycleRuleChannels,tV as cycleTables,EB as cyclicChannels,b1 as decodeBand,tt as decodeChain,V$ as decodeVideo,DZ as decorateColumnLabel,Un as defaultAreaChartPanelSettings,Vn as defaultBarChartPanelSettings,An as defaultBoxPlotPanelSettings,Gn as defaultBubbleChartPanelSettings,Yn as defaultCalibrationPanelSettings,$n as defaultCameraPanelSettings,Wn as defaultCdfChartPanelSettings,Pn as defaultConfusionPanelSettings,Ln as defaultControlChartPanelSettings,aB as defaultDatasetPalette,zn as defaultEmbeddingPanelSettings,Bn as defaultFlameGraphPanelSettings,Zn as defaultGanttPanelSettings,Jn as defaultGaugePanelSettings,Mn as defaultHeatmapPanelSettings,Dn as defaultHistogramPanelSettings,In as defaultLossCurvePanelSettings,wn as defaultMultibandPanelSettings,Rn as defaultParallelCoordsPanelSettings,On as defaultPolarPanelSettings,Xn as defaultQQPlotPanelSettings,Hn as defaultRadarPanelSettings,Fn as defaultRocPanelSettings,qn as defaultSankeyPanelSettings,jn as defaultSpectrogramPanelSettings,kn as defaultSpectrumPanelSettings,c0 as defaultSplit,Kn as defaultTreemapPanelSettings,Nn as defaultViolinPanelSettings,dn as defaultXyAxisScaleSettings,Tn as defaultXyPanelSettings,En as defaultXyzPanelSettings,YB as definitionChannels,We as deriveKey,v as deriveRawKeyBase64,te as deviceFingerprint,an as dragLayout,w3 as emptyChannel,T3 as emptyContext,y1 as encodeBand,st as encodeChain,B$ as encodeVideo,oV as encryptWorkbookFile,D3 as energyChannel,hr as ensurePanelSettingsForPanels,mE as evalChannel,dB as eventWithin,Z4 as evidenceLabel,N2 as exportRecording,M2 as exportRecordingTo,fE as extractFreeIdentifiers,D0 as fetchUsage,JB as findCycles,tB as formatClockTick,nB as formatClockValue,MB as formatLapValue,s0 as formatSplit,H$ as fragmentVideo,V as generateApiToken,H as generateDeviceKeyPair,k as generateRecoveryKeyPair,e as generateSalt,$z as getClockTimeZone,Te as getRawNonEmptyLines,f1 as gridAt,DB as guessBeaconChannel,ge as hashToken,Qe as importStreamKey,X8 as inferContext,ae as inferParseConfig,Gz as isClockAxis,jV as isImportable,EZ as isMathChannelName,XB as kpiColumn,pB as kpiKey,ZB as kpisOf,b8 as listedFindings,x0 as liveBytesPerSec,x1 as liveSegmentTracker,bB as localDay,c1 as localSeconds,Le as makeKeyCheck,Jt as markToAnnotation,Y3 as moneyGaps,_3 as namesOf,vn as newGaugeItem,yr as newMathChannel,cn as newPanel,hB as newResetState,se as newRun,vr as newSeriesId,Pz as niceMajorStep,uB as observeColorScheme,CR as openDatasetFromText,c as openMessage,bz as openSession,qe as openUnderProjectKey,Ee as openWithKey,oe as openWithPassword,tr as panelCameras,ze as parseColumnNames,Ye as parseConfigsEqual,z3 as parseContext,WB as parseCycleDefinitions,je as parseDatasetWithConfig,dE as parseFormula,le as parseKrc,Ae as parseKrcHeader,IE as parseMathChannelsFile,bn as parseOptionalAxisRange,mr as parsePanelChartSettingsMap,Be as parseRecoveryCode,o0 as parseSplit,g1 as pooledSd,f3 as presetForIndustry,d3 as presetOf,TX as presetStops,Xe as projectConfigKeyAad,de as projectWrapAad,Me as randomKey,qB as readSource,Fe as recordingKeyAad,Ge as recordingKeySealAad,et as recoveryAttestationAad,me as recoveryCode,ye as recoveryKeyAad,Ue as recoveryPrivateKey,SZ as referenceBands,d1 as resample,gB as resetStep,ur as resolveLinkedAlarms,E3 as roleOf,nV as rowsCsv,T as sealMessage,Pe as sealUnderProjectKey,Ce as sealWithKey,xe as sealWithPassword,ie as senderBindKey,nt as senderBinding,Qz as setClockTimeZone,SB as shiftDay,ct as splitApiKey,TB as splitLaps,ce as streamKeyAad,$e as subsampleIndices,eB as subscribeClockTimeZone,OB as suggestBeacon,K3 as suggestedCount,g3 as term,mt as thresholdOf,yB as tzOffsetS,ot as unwrapForDevice,P as unwrapStreamKey,ft as validateRule,s as verifyKeyCheck,HV as verifyLicense,it as verifySenderBinding,x8 as viewSections,I as workbookBodyAad,rV as workbookExportAad,cV as workbookFileInfo,d as workbookKeyAad,l as wrapForDevice,xB as zonedInstant};
|