@kymoscope/sdk 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/kymoscope-embed.js +71 -71
  2. package/dist/kymoscope-sdk.js +65 -65
  3. package/dist/types/analysis/actions.d.ts +9 -0
  4. package/dist/types/analysis/aiCheck.d.ts +40 -0
  5. package/dist/types/analysis/badParts.d.ts +32 -0
  6. package/dist/types/analysis/changes.d.ts +8 -0
  7. package/dist/types/analysis/context.d.ts +7 -1
  8. package/dist/types/analysis/energy.d.ts +21 -0
  9. package/dist/types/analysis/gap.d.ts +6 -0
  10. package/dist/types/analysis/golden.d.ts +6 -0
  11. package/dist/types/analysis/index.d.ts +4 -0
  12. package/dist/types/analysis/known.d.ts +27 -0
  13. package/dist/types/analysis/oee.d.ts +5 -1
  14. package/dist/types/analysis/presets.d.ts +1 -1
  15. package/dist/types/analysis/ranges.d.ts +18 -0
  16. package/dist/types/analysis/reliability.d.ts +62 -1
  17. package/dist/types/analysis/report.d.ts +2 -2
  18. package/dist/types/analysis/review.d.ts +119 -0
  19. package/dist/types/analysis/runWear.d.ts +13 -0
  20. package/dist/types/analysis/shifts.d.ts +1 -0
  21. package/dist/types/analysis/stops.d.ts +10 -0
  22. package/dist/types/analysis/types.d.ts +31 -0
  23. package/dist/types/engine/createEngine.d.ts +22 -1
  24. package/dist/types/index.d.ts +6 -1
  25. package/dist/types/lib/live/clockProbe.d.ts +26 -0
  26. package/dist/types/lib/live/publisher.d.ts +5 -0
  27. package/dist/types/lib/live/types.d.ts +8 -0
  28. package/dist/types/lib/live/videoTrack.d.ts +46 -2
  29. package/dist/types/lib/measurePack.d.ts +13 -0
  30. package/dist/types/lib/recordings/videoSource.d.ts +12 -1
  31. package/dist/types/lib/segments/rules.d.ts +4 -0
  32. package/dist/types/lib/sync/detect.d.ts +28 -0
  33. package/dist/types/lib/sync/estimate.d.ts +143 -0
  34. package/dist/types/lib/sync/flash.d.ts +49 -0
  35. package/dist/types/lib/sync/frameFeatures.d.ts +16 -0
  36. package/package.json +1 -1
@@ -61,14 +61,14 @@ In case of a (multi dimensional) array or matrix, the prob order quantile of all
61
61
  : typeof r === 'boolean' ? (r ? 1 : 0) : NaN
62
62
  }
63
63
  }`;try{return Function(`env`,v)(a)}catch{return null}}function VT(e,t){let n=e.length,r=Array(n);for(let i=0;i<n;i++){if(e[i]===null){r[i]=null;continue}if(i===0){let n=KT(t[1],t[0]),a=KT(e[1],e[0]);r[i]=n===null||a===null||n===0?null:a/n}else if(i===n-1){let n=KT(t[i],t[i-1]),a=KT(e[i],e[i-1]);r[i]=n===null||a===null||n===0?null:a/n}else{let n=KT(t[i+1],t[i-1]),a=KT(e[i+1],e[i-1]);r[i]=n===null||a===null||n===0?null:a/n}}return r}function HT(e,t){let n=e.length,r=Array(n),i=0;r[0]=0;for(let a=1;a<n;a++){let n=e[a-1],o=e[a],s=t[a-1],c=t[a];if(n===null||o===null||s===null||c===null){r[a]=null;continue}i+=(n+o)/2*(c-s),r[a]=i}return r}function UT(e,t){let n=Math.floor(Math.max(1,Math.floor(t))/2),r=Array(e.length);for(let t=0;t<e.length;t++){let i=0,a=0,o=Math.max(0,t-n),s=Math.min(e.length-1,t+n);for(let t=o;t<=s;t++){let n=e[t];n!==null&&Number.isFinite(n)&&(i+=n,a++)}r[t]=a===0?null:i/a}return r}function WT(e,t){let n=Math.max(0,Math.floor(t)),r=Array(e.length);for(let t=0;t<e.length;t++)r[t]=t<n?null:e[t-n];return r}function GT(e,t){let n=Math.max(0,Math.floor(t)),r=Array(e.length);for(let t=0;t<e.length;t++)r[t]=t+n>=e.length?null:e[t+n];return r}function KT(e,t){return e===null||t===null||!Number.isFinite(e)||!Number.isFinite(t)?null:e-t}function qT(e,t){let n=e.length,r=new Float64Array(n);for(let i=0;i<n;i++){if(e[i]!==e[i]){r[i]=NaN;continue}let a=i===n-1?i:i+1,o=i===0?0:i-1,s=t[a]-t[o],c=e[a]-e[o];if(s!==s||c!==c||s===0){r[i]=NaN;continue}let l=c/s;if(l!==l)return null;r[i]=l}return r}function JT(e,t){let n=e.length,r=new Float64Array(n),i=0;for(let a=1;a<n;a++){let n=e[a-1],o=e[a],s=t[a-1],c=t[a];if(n!==n||o!==o||s!==s||c!==c){r[a]=NaN;continue}if(i+=(n+o)/2*(c-s),i!==i)return null;r[a]=i}return r}function YT(e,t){let n=Math.floor(Math.max(1,Math.floor(t))/2),r=new Float64Array(e.length);for(let t=0;t<e.length;t++){let i=0,a=0,o=Math.max(0,t-n),s=Math.min(e.length-1,t+n);for(let t=o;t<=s;t++){let n=e[t];n===n&&(i+=n,a++)}if(a===0){r[t]=NaN;continue}let c=i/a;if(c!==c)return null;r[t]=c}return r}function XT(e,t){let n=Math.max(0,Math.floor(t)),r=new Float64Array(e.length);for(let t=0;t<e.length;t++)r[t]=t<n?NaN:e[t-n];return r}function ZT(e,t){let n=Math.max(0,Math.floor(t)),r=new Float64Array(e.length);for(let t=0;t<e.length;t++)r[t]=t+n>=e.length?NaN:e[t+n];return r}function QT(e){let t=[];for(let n=1;n<e.length;n++){let r=e[n-1],i=e[n];if(r===null||i===null)continue;let a=i-r;Number.isFinite(a)&&a>0&&t.push(a)}if(t.length===0)return NaN;t.sort((e,t)=>e-t);let n=Math.floor(t.length/2);return 1/(t.length%2?t[n]:(t[n-1]+t[n])/2)}function $T(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0||e>=t/2)return null;let r=2*Math.PI*e/t,i=Math.cos(r),a=Math.sin(r)/(2*Math.SQRT1_2),o=1+a;return n===`low`?{b0:(1-i)/2/o,b1:(1-i)/o,b2:(1-i)/2/o,a1:-2*i/o,a2:(1-a)/o}:{b0:(1+i)/2/o,b1:-(1+i)/o,b2:(1+i)/2/o,a1:-2*i/o,a2:(1-a)/o}}function eE(e,t){let n=Array(e.length),r=0,i=0,a=0,o=0;for(let s=0;s<e.length;s++){let c=e[s];if(c===null||!Number.isFinite(c)){n[s]=null,r=0,i=0,a=0,o=0;continue}let l=t.b0*c+t.b1*r+t.b2*i-t.a1*a-t.a2*o;n[s]=l,i=r,r=c,o=a,a=l}return n}function tE(e,t,n){return!Number.isFinite(t)||t<=0?`${e}: cutoff frequency must be a positive number, got fc=${t}`:!Number.isFinite(n)||n<=0?`${e}: could not infer a valid sample rate from the time axis (got fs=${n}). Specify it explicitly as a third argument: ${e}(y, fc, fs)`:t>=n/2?`${e}: cutoff fc=${t} Hz must be below Nyquist fs/2=${(n/2).toFixed(3)} Hz. Inferred sample rate fs=${n.toFixed(3)} Hz from the current x-axis — pass an explicit fs as third arg: ${e}(y, fc, fs).`:`${e}: invalid filter parameters (fc=${t}, fs=${n})`}function nE(e,t,n){let r=$T(t,n,`low`);if(!r)throw Error(tE(`lowpass`,t,n));return eE(e,r)}function rE(e,t,n){let r=$T(t,n,`high`);if(!r)throw Error(tE(`highpass`,t,n));return eE(e,r)}function iE(e,t){let n=new Float64Array(e.length),r=0,i=0,a=0,o=0;for(let s=0;s<e.length;s++){let c=e[s];if(c!==c){n[s]=NaN,r=0,i=0,a=0,o=0;continue}let l=t.b0*c+t.b1*r+t.b2*i-t.a1*a-t.a2*o;if(l!==l)return null;n[s]=l,i=r,r=c,o=a,a=l}return n}function aE(e,t,n){let r=$T(t,n,`low`);if(!r)throw Error(tE(`lowpass`,t,n));return iE(e,r)}function oE(e,t,n){let r=$T(t,n,`high`);if(!r)throw Error(tE(`highpass`,t,n));return iE(e,r)}var sE=FT(),cE=new Map;function lE(e){let t=cE.get(e);if(t)return t;try{let t={ok:!0,node:MT(sE,e)};return cE.set(e,t),t}catch(t){let n={ok:!1,message:`parse error: ${t instanceof Error?t.message:`unknown error`}`};return cE.set(e,n),n}}var uE=[`derivative`,`integral`,`movavg`,`lag`,`lead`,`lowpass`,`highpass`],dE=new Set([`pi`,`e`,`true`,`false`,`null`]);function fE(e){return lE(e)}function pE(e){let t=e,n=new Set,r=new Set;t.traverse(e=>{if(e.type===`FunctionNode`){let t=e,n=t.fn?.name??t.name;typeof n==`string`&&r.add(n)}else if(e.type===`SymbolNode`){let t=e.name;typeof t==`string`&&!dE.has(t)&&n.add(t)}});for(let e of r)n.delete(e);return{identifiers:[...n],functions:[...r]}}var mE=FT();function hE(e,t,n,r){let{rows:i}=t,a=new Set(t.columnNames),o=Ue(i),{values:s,compiled:c,...l}=yE(e,e=>{if(!a.has(e))return;let t=o&&_e(o,e);if(t)return t;let n=new Float64Array(i.length);for(let t=0;t<i.length;t++){let r=i[t][e];n[t]=typeof r==`number`?r:NaN}return n},n,i.length,r),u=Array(s.length);for(let e=0;e<s.length;e++)u[e]=s[e]===s[e]?s[e]:null;return{...l,values:u}}var gE=!0,_E=new Map;function vE(e,t,n){if(!gE)return null;let r=_E.get(e);return r===void 0&&_E.set(e,r=BT(mE,t,n)),r}function yE(e,t,n,r,i,a){let o={channelId:e.id},s=new Float64Array;if(!e.enabled)return{...o,status:`disabled`,values:s};let c=lE(e.formula);if(!c.ok)return{...o,status:`parse-error`,values:s,message:c.message};let{identifiers:l,functions:u}=pE(c.node),d=new Set(i.filter(t=>t.id!==e.id).map(e=>e.name));for(let t of l)if(d.has(t))return{...o,status:`references-channel`,values:s,message:`Channel "${e.name}" references another channel "${t}". This is not allowed in V1.`};let f=l.map(t),p=l.filter((e,t)=>!f[t]);if(p.length>0)return{...o,status:`missing-inputs`,values:s,missingCols:p};if(u.some(e=>uE.includes(e))){let i=n?t(n):void 0;return OE(e,c.node,l,f,i,r,a)}let m=new Float64Array(r);try{let t=vE(`s${e.formula}`,c.node,l);if(t)return t(m,f,r),{...o,status:`ok`,values:m,compiled:!0};let n=c.node.compile(),i={};for(let e=0;e<r;e++){let t=!1;for(let n=0;n<l.length;n++){let r=f[n][e];if(r-r===0)i[l[n]]=r;else{t=!0;break}}m[e]=t?NaN:bE(n.evaluate(i))}return{...o,status:`ok`,values:m}}catch(e){return{...o,status:`runtime-error`,values:s,message:e instanceof Error?e.message:`runtime error`}}}function bE(e){return e==null?NaN:typeof e==`number`?Number.isFinite(e)?e:NaN:typeof e==`boolean`?+!!e:NaN}function xE(e){let t=new Float64Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]-e[n]===0?e[n]:NaN;return t}var SE=e=>Array.from(e,e=>e===e?e:null),CE={derivative:VT,integral:HT,movavg:UT,lag:WT,lead:GT,lowpass:nE,highpass:rE},wE={derivative:qT,integral:JT,movavg:YT,lag:XT,lead:ZT,lowpass:aE,highpass:oE};function TE(e,t){return Array.isArray(e)?e.map(e=>e===null?null:e+t):e.map(e=>e+t)}function EE(e,t,n,r,i){let a=0,o=0,s=Object.create(null),c=null,l=!1,u=e.transform(e=>{if(c||l||e.type!==`FunctionNode`)return e;let u=e,d=u.fn?.name??u.name;if(typeof d!=`string`||![`derivative`,`integral`,`movavg`,`lag`,`lead`,`lowpass`,`highpass`].includes(d))return e;let f=u.args??[];try{if(f.length===0)throw Error(`${d}(): missing first argument`);let c=f[0];if(c.type!==`SymbolNode`)throw Error(`${d}() expects a column name as its first argument`);let u=c.name,p=t[u];if(!p)throw Error(`${d}(): column "${u}" not available`);let m;if(d===`derivative`||d===`integral`){let e=f[1],a=e?.type===`SymbolNode`?t[e.name]??n:n;if(m=d===`derivative`?r.derivative(p,a):r.integral(p,a),d===`integral`&&m&&i){let e=o++,t=i.start(e);t&&(m=TE(m,t)),i.done(e,m)}}else if(d===`movavg`||d===`lag`||d===`lead`){let e=f[1];if(!e)throw Error(`${d}(y, n) requires a second argument`);let t=e.compile().evaluate({});if(!Number.isFinite(t))throw Error(`${d}(): n must be a finite number`);m=d===`movavg`?r.movavg(p,t):d===`lag`?r.lag(p,t):r.lead(p,t)}else{let e=f[1];if(!e)throw Error(`${d}(y, fc, fs?) requires a cutoff frequency`);let t=e.compile().evaluate({}),i=f[2],a=i?i.compile().evaluate({}):QT(n);m=d===`lowpass`?r.lowpass(p,t,a):r.highpass(p,t,a)}if(!m)return l=!0,e;let h=`__w${a++}`;return s[h]=m,new mE.SymbolNode(h)}catch(t){return c=t instanceof Error?t:Error(String(t)),e}});return c?{error:c.message}:l?null:{node:u,synthetic:s}}function DE(e,t){let n=new Set(pE(e).identifiers);return t.filter(e=>n.has(e))}function OE(e,t,n,r,i,a,o){let s={channelId:e.id},c=e=>({...s,status:`runtime-error`,values:new Float64Array,message:e}),l=Object.create(null);n.forEach((e,t)=>{l[e]=xE(r[t])});let u=i?xE(i):Float64Array.from({length:a},(e,t)=>t),d=new Float64Array(a);if(gE){let r=EE(t,l,u,wE,o);if(r&&`error`in r)return c(r.error);if(r){let t=Object.keys(r.synthetic),i=DE(r.node,n),o=vE(`w${e.formula}`,r.node,[...i,...t]);if(o)try{return o(d,[...i.map(e=>l[e]),...t.map(e=>r.synthetic[e])],a),{...s,status:`ok`,values:d,compiled:!0}}catch(e){return c(e instanceof Error?e.message:`runtime error`)}}}let f=Object.create(null);for(let e of n)f[e]=SE(l[e]);let p=EE(t,f,SE(u),CE,o);if(`error`in p)return c(p.error);let{synthetic:m}=p,h=p.node.compile(),g={};try{let e=[...DE(p.node,n).map(e=>[e,f[e]]),...Object.keys(m).map(e=>[e,m[e]])];rows:for(let t=0;t<a;t++){for(let[n,r]of e){let e=r[t];if(e===null||!Number.isFinite(e)){d[t]=NaN;continue rows}g[n]=e}d[t]=bE(h.evaluate(g))}return{...s,status:`ok`,values:d}}catch(e){return c(e instanceof Error?e.message:`runtime error`)}}function kE(e,t,n){let r={};for(let i of e)r[i.id]=hE(i,t,n,e);return r}var AE=new WeakMap;function jE(e,t,n,r,i){let a=AE.get(e);a||AE.set(e,a=new Map);let o=[i,...t.map(e=>e.id)].join(`
64
- `),s=a.get(o);s||(a.size>=4&&a.delete(a.keys().next().value),s={rows:e.map(e=>Object.create(e)),written:new Set},a.set(o,s));let c=new Set(n.map(e=>e.name)),l=[...s.written].filter(e=>!c.has(e));for(let t=0;t<e.length;t++){let e=s.rows[t];for(let t of l)delete e[t];for(let i of n)e[i.name]=r[i.id].values[t]}return s.written=c,s.rows.slice()}var ME=new WeakMap;function NE(e,t,n){let r=ME.get(e.rows);if(r&&r.channels===t&&r.xKey===n)return r.result;let i=kE(t,e,n),a=t.filter(e=>i[e.id]?.status===`ok`),o={rows:a.length===0?e.rows:jE(e.rows,t,a,i,n),ok:a};return ME.set(e.rows,{channels:t,xKey:n,result:o}),o}function PE(e,t,n){if(e.length===0)return[];let r=JSON.stringify(t);return e.filter(e=>e.name===n||r.includes(`"${e.name}"`))}function FE(e){let t=e.filter(e=>e.source===`personal`&&e.projectId===null),n={version:1,exportedAt:new Date().toISOString(),channels:t.map(e=>({name:e.name,units:e.units,formula:e.formula,enabled:e.enabled,...e.description===void 0?{}:{description:e.description}}))};return new Blob([JSON.stringify(n,null,2)],{type:`application/json`})}function IE(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)})}async function LE(e){let t=await IE(e),n;try{n=JSON.parse(t)}catch{return{channels:[],errors:[`Not a valid JSON file.`]}}if(!n||typeof n!=`object`||n.version!==1||!Array.isArray(n.channels))return{channels:[],errors:[`Unrecognized format. Is this a Kymoscope export (version 1)?`]};let r=[],i=[];return n.channels.forEach((e,t)=>{let n=e;if(typeof n.name!=`string`||typeof n.units!=`string`||typeof n.formula!=`string`){i.push(`Channel #${t+1} skipped: missing name/units/formula.`);return}r.push(br({name:n.name,units:n.units,formula:n.formula,enabled:typeof n.enabled==`boolean`?n.enabled:!0,description:typeof n.description==`string`?n.description:void 0,source:`personal`,sharedWithOrgId:null,ownerUserId:``}))}),{channels:r,errors:i}}var RE=3e3;function zE(e){return Math.max(RE,4*(e??0))}var BE=new WeakMap;function VE(e){let t=e.video,n=BE.get(t);if(n&&n.id===e.id&&n.name===e.name&&n.parentId===e.parentId&&n.lowOf===(e.lowOf??null))return n;let r={id:e.id,name:e.name,kind:`live`,parentId:e.parentId,lowOf:e.lowOf??null,info:()=>t.info(),range:()=>t.range(),seekPlan:e=>t.seekPlan(e),livePlan:()=>t.livePlan(),onUnit:e=>t.onUnit(e),acquire:()=>t.acquire()};return BE.set(t,r),r}var HE=class{ring=[];bytes=0;needKey=!0;width=0;height=0;codec=``;pending=null;subs=new Set;holders=0;demand=()=>{};maxBytes;now;constructor(e=128*1024*1024,t=Date.now){this.maxBytes=e,this.now=t}push(e){let t=this.pending;if(t&&t.seq!==e.seq&&(t.key&&(this.needKey=!0),t=this.pending=null),t||=this.pending={seq:e.seq,key:e.key,t:e.t,count:e.fragCount,parts:new Map},t.parts.has(e.fragIndex)||t.parts.set(e.fragIndex,e.payload),e.key&&e.fragIndex===0&&(this.width=e.width,this.height=e.height,this.codec=e.codec),t.parts.size<t.count||(this.pending=null,!t.key&&this.needKey))return null;let n=new Uint8Array([...Array(t.count).keys()].reduce((e,n)=>e+(t.parts.get(n)?.length??0),0)),r=0;for(let e=0;e<t.count;e++){let i=t.parts.get(e);i&&(n.set(i,r),r+=i.length)}t.key&&(this.needKey=!1);let i={t:t.t,seq:t.seq,key:t.key,data:n,arrivedAt:this.now()};return this.ring.push(i),this.bytes+=n.length,this.trim(),this.subs.forEach(e=>e(i)),i}trim(){for(;this.bytes>this.maxBytes;){let e=this.ring.findIndex((e,t)=>t>0&&e.key);if(e<0)return;for(let t of this.ring.splice(0,e))this.bytes-=t.data.length}}seekPlan(e){let t=0,n=this.ring.length;for(;t<n;){let r=t+n>>1;this.ring[r].t<=e?t=r+1:n=r}let r=t-1;for(;r>=0&&!this.ring[r].key;)r--;return r<0?[]:this.ring.slice(r,t)}livePlan(){for(let e=this.ring.length-1;e>=0;e--)if(this.ring[e].key)return this.ring.slice(e);return[]}onUnit(e){return this.subs.add(e),()=>{this.subs.delete(e)}}acquire(){this.holders++===0&&this.demand(!0);let e=!0;return()=>{e&&(e=!1,--this.holders===0&&this.demand(!1))}}onDemandChange(e){this.demand=e}info(){let e=this.ring.length,t=e?this.ring[e-1].t:null,n=[];for(let t=Math.max(1,e-9);t<e;t++)n.push(this.ring[t].arrivedAt-this.ring[t-1].arrivedAt);return n.sort((e,t)=>e-t),{width:this.width,height:this.height,codec:this.codec,latestT:t,lagMs:t===null?null:this.now()-t*1e3,units:e,bytes:this.bytes,arrivedAt:e?this.ring[e-1].arrivedAt:null,gapMs:n.length?n[n.length>>1]:null}}range(){return this.ring.length?[this.ring[0].t,this.ring[this.ring.length-1].t]:null}resync(){this.pending=null,this.needKey=!0}clear(){this.ring=[],this.bytes=0,this.pending=null,this.needKey=!0}},UE=class extends Error{code;detail;constructor(e,t){super(e),this.name=`KymoscopeError`,this.code=e,this.detail=t}};function WE(e){let t=new URL(e,location.href);if(t.origin===location.origin)return new Worker(t,{type:`module`});let n=URL.createObjectURL(new Blob([`import ${JSON.stringify(t.href)};`],{type:`text/javascript`}));try{return new Worker(n,{type:`module`})}finally{URL.revokeObjectURL(n)}}var GE=``+new URL(`assets/parseDataset.worker-PynRsPD8.js`,import.meta.url).href;function KE(){return WE(GE)}function qE(e,t=KE,n){return new Promise((r,i)=>{if(n?.aborted){i(new UE(`cancelled`));return}let a=t(),o=()=>{a.terminate(),i(new UE(`cancelled`))};n?.addEventListener(`abort`,o,{once:!0}),a.onmessage=e=>{if(n?.removeEventListener(`abort`,o),a.terminate(),e.data.ok){let{table:t,...n}=e.data.data;r({...n,rows:Pe(t)})}else i(Error(e.data.error))},a.onerror=e=>{n?.removeEventListener(`abort`,o),a.terminate(),i(e instanceof Error?e:Error(`Worker failed to parse the dataset.`))},a.postMessage(e)})}async function JE(e,t){if(typeof Worker<`u`)return qE(e,KE,t);let{table:n,...r}=je(`file`in e?await e.file.text():e.rawText,e.config);return{...r,rows:Pe(n)}}var YE=me(new WeakMap);function XE(e){let t=YE.get(e);if(t===void 0){t=!0;for(let n=0;n<e.length;n++)if(!(e[n]>=(n>0?e[n-1]:-1/0))){t=!1;break}YE.set(e,t)}return t}var ZE=class{#e;constructor(e){this.#e=e}async getSchema(){let{columnNames:e,units:t,rows:n}=this.#e;return e.map((e,r)=>({name:e,type:Le(n,e)?`number`:`string`,unit:t[r]??``}))}async getSeries(e){let{rows:t}=this.#e,n=Ue(t);if(n){let r=_e(n,e.viewport.xKey),i=_e(n,e.column),a=new Float64Array(t.length),o=new Float64Array(t.length),s=0;if(r&&i)for(let e=0;e<r.length;e++)r[e]===r[e]&&i[e]===i[e]&&(a[s]=r[e],o[s]=i[e],s++);return H(a.subarray(0,s),o.subarray(0,s),e.viewport.x0,e.viewport.x1,e.maxPoints)}let r=new Float64Array(t.length),i=new Float64Array(t.length),a=0;for(let n of t){let t=n[e.viewport.xKey],o=n[e.column];typeof t==`number`&&typeof o==`number`&&(r[a]=t,i[a]=o,a++)}return H(r.subarray(0,a),i.subarray(0,a),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.rows,i=new Set(this.#e.columnNames),a=i.has(t.xKey)?e.filter(e=>i.has(e)):[];if(a.length===0)return{x0:t.x0,bucket:0,rows:[],columns:a};let o=Ue(r),s=o&&_e(o,t.xKey),c=o?a.map(e=>_e(o,e)):[];if(s&&c.every(e=>e))return k(s,c,a,t.x0,t.x1,n);let l=new Float64Array(r.length),u=a.map(()=>new Float64Array(r.length));for(let e=0;e<r.length;e++){let n=r[e][t.xKey];l[e]=typeof n==`number`?n:NaN;for(let t=0;t<a.length;t++){let n=r[e][a[t]];u[t][e]=typeof n==`number`?n:NaN}}return k(l,u,a,t.x0,t.x1,n)}getColumnsSync(e,n,r){let i=Ue(this.#e.rows),a=i&&_e(i,n.xKey);if(!i||!a)return null;let o=e.filter(e=>_e(i,e));return o.length===0?null:t(a,o.map(e=>_e(i,e)),o,n.x0,n.x1,r)}async readColumns(e,t,n){let{rows:r,columnNames:i}=this.#e,a=Ue(r),o=Math.min(r.length,t+n),s={};for(let n of e){if(!i.includes(n))continue;let e=a&&_e(a,n);if(e){s[n]=e.slice(t,o);continue}let c=new Float64Array(Math.max(0,o-t));for(let e=t;e<o;e++){let i=r[e][n];c[e-t]=typeof i==`number`?i:NaN}s[n]=c}return s}async xBounds(e){return this.xBoundsSync(e)}xBoundsSync(e){let{rows:t}=this.#e,n=Ue(t),r=n&&_e(n,e),i=1/0,a=-1/0;if(r&&r.length>0&&XE(r))i=r[0],a=r[r.length-1];else if(r)for(let e=0;e<r.length;e++){let t=r[e];t<i&&(i=t),t>a&&(a=t)}else for(let n of t){let t=n[e];typeof t==`number`&&(t<i&&(i=t),t>a&&(a=t))}return i<=a?{x0:i,x1:a}:{x0:0,x1:0}}async dispose(){}};function QE(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function $E(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function eD(e){return this instanceof eD?(this.v=e,this):new eD(e)}function tD(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof eD?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function nD(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:eD(e[r](t)),done:!1}:i?i(t):t}:i}}function rD(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof $E==`function`?$E(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var iD=new TextDecoder(`utf-8`),aD=e=>iD.decode(e),oD=new TextEncoder,sD=e=>oD.encode(e),cD=e=>typeof e==`number`,lD=e=>typeof e==`boolean`,uD=e=>typeof e==`function`,dD=e=>e!=null&&Object(e)===e,fD=e=>dD(e)&&uD(e.then),pD=e=>dD(e)&&uD(e[Symbol.iterator]),mD=e=>dD(e)&&uD(e[Symbol.asyncIterator]),hD=e=>dD(e)&&dD(e.schema),gD=e=>dD(e)&&`done`in e&&`value`in e,_D=e=>dD(e)&&uD(e.stat)&&cD(e.fd),vD=e=>dD(e)&&xD(e.body),yD=e=>`_getDOMStream`in e&&`_getNodeStream`in e,bD=e=>dD(e)&&uD(e.abort)&&uD(e.getWriter)&&!yD(e),xD=e=>dD(e)&&uD(e.cancel)&&uD(e.getReader)&&!yD(e),SD=e=>dD(e)&&uD(e.end)&&uD(e.write)&&lD(e.writable)&&!yD(e),CD=e=>dD(e)&&uD(e.read)&&uD(e.pipe)&&lD(e.readable)&&!yD(e),wD=e=>dD(e)&&uD(e.clear)&&uD(e.bytes)&&uD(e.position)&&uD(e.setPosition)&&uD(e.capacity)&&uD(e.getBufferIdentifier)&&uD(e.createLong),TD=typeof SharedArrayBuffer<`u`?SharedArrayBuffer:ArrayBuffer;function ED(e){let t=e[0]?[e[0]]:[],n,r,i,a;for(let o,s,c=0,l=0,u=e.length;++c<u;){if(o=t[l],s=e[c],!o||!s||o.buffer!==s.buffer||s.byteOffset<o.byteOffset){s&&(t[++l]=s);continue}if({byteOffset:n,byteLength:i}=o,{byteOffset:r,byteLength:a}=s,n+i<r||r+a<n){s&&(t[++l]=s);continue}t[l]=new Uint8Array(o.buffer,n,r-n+a)}return t}function DD(e,t,n=0,r=t.byteLength){let i=e.byteLength,a=new Uint8Array(e.buffer,e.byteOffset,i),o=new Uint8Array(t.buffer,t.byteOffset,Math.min(r,i));return a.set(o,n),e}function OD(e,t){let n=ED(e),r=n.reduce((e,t)=>e+t.byteLength,0),i,a,o,s=0,c=-1,l=Math.min(t||1/0,r);for(let e=n.length;++c<e;){if(i=n[c],a=i.subarray(0,Math.min(i.length,l-s)),l<=s+a.length){a.length<i.length?n[c]=i.subarray(a.length):a.length===i.length&&c++,o?DD(o,a,s):o=a;break}DD(o||=new Uint8Array(l),a,s),s+=a.length}return[o||new Uint8Array,n.slice(c),r-(o?o.byteLength:0)]}function kD(e,t){let n=gD(t)?t.value:t;return n instanceof e?e===Uint8Array?new e(n.buffer,n.byteOffset,n.byteLength):n:n?(typeof n==`string`&&(n=sD(n)),n instanceof ArrayBuffer||n instanceof TD?new e(n):wD(n)?kD(e,n.bytes()):ArrayBuffer.isView(n)?n.byteLength<=0?new e(0):new e(n.buffer,n.byteOffset,n.byteLength/e.BYTES_PER_ELEMENT):e.from(n)):new e(0)}var AD=e=>kD(Int32Array,e),jD=e=>kD(BigInt64Array,e),MD=e=>kD(Uint8Array,e),ND=e=>(e.next(),e);function*PD(e,t){let n=function*(e){yield e};return yield*ND((function*(t){let n=null;do n=t.next(yield kD(e,n));while(!n.done)})((typeof t==`string`||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof TD?n(t):pD(t)?t:n(t))[Symbol.iterator]())),new e}var FD=e=>PD(Uint8Array,e);function ID(e,t){return tD(this,arguments,function*(){if(fD(t))return yield eD(yield eD(yield*nD(rD(ID(e,yield eD(t))))));let n=function(e){return tD(this,arguments,function*(){yield yield eD(yield eD(e))})};return yield eD(yield*nD(rD(ND((function(t){return tD(this,arguments,function*(){let n=null;do n=yield eD(t.next(yield yield eD(kD(e,n))));while(!n.done)})})((typeof t==`string`||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof TD?n(t):pD(t)?function(e){return tD(this,arguments,function*(){yield eD(yield*nD(rD(ND((function*(e){let t=null;do t=e.next(yield t?.value);while(!t.done)})(e[Symbol.iterator]())))))})}(t):mD(t)?t:n(t))[Symbol.asyncIterator]()))))),yield eD(new e)})}var LD=e=>ID(Uint8Array,e);function RD(e,t,n){if(e!==0){n=n.slice(0,t);for(let t=-1,r=n.length;++t<r;)n[t]+=e}return n.subarray(0,t)}function zD(e,t){let n=0,r=e.length;if(r!==t.length)return!1;if(r>0)do if(e[n]!==t[n])return!1;while(++n<r);return!0}var BD={fromIterable(e){return VD(HD(e))},fromAsyncIterable(e){return VD(UD(e))},fromDOMStream(e){return VD(WD(e))},fromNodeStream(e){return VD(qD(e))},toDOMStream(e,t){throw Error(`"toDOMStream" not available in this environment`)},toNodeStream(e,t){throw Error(`"toNodeStream" not available in this environment`)}},VD=e=>(e.next(),e);function*HD(e){let t,n=!1,r=[],i,a,o,s=0;function c(){return a===`peek`?OD(r,o)[0]:([i,r,s]=OD(r,o),i)}({cmd:a,size:o}=(yield null)||{cmd:`read`,size:0});let l=FD(e)[Symbol.iterator]();try{do if({done:t,value:i}=Number.isNaN(o-s)?l.next():l.next(o-s),!t&&i.byteLength>0&&(r.push(i),s+=i.byteLength),t||o<=s)do({cmd:a,size:o}=yield c());while(o<s);while(!t)}catch(e){(n=!0)&&typeof l.throw==`function`&&l.throw(e)}finally{n===!1&&typeof l.return==`function`&&l.return(null)}return null}function UD(e){return tD(this,arguments,function*(){let t,n=!1,r=[],i,a,o,s=0;function c(){return a===`peek`?OD(r,o)[0]:([i,r,s]=OD(r,o),i)}({cmd:a,size:o}=(yield yield eD(null))||{cmd:`read`,size:0});let l=LD(e)[Symbol.asyncIterator]();try{do if({done:t,value:i}=Number.isNaN(o-s)?yield eD(l.next()):yield eD(l.next(o-s)),!t&&i.byteLength>0&&(r.push(i),s+=i.byteLength),t||o<=s)do({cmd:a,size:o}=yield yield eD(c()));while(o<s);while(!t)}catch(e){(n=!0)&&typeof l.throw==`function`&&(yield eD(l.throw(e)))}finally{n===!1&&typeof l.return==`function`&&(yield eD(l.return(new Uint8Array)))}return yield eD(null)})}function WD(e){return tD(this,arguments,function*(){let t=!1,n=!1,r=[],i,a,o,s=0;function c(){return a===`peek`?OD(r,o)[0]:([i,r,s]=OD(r,o),i)}({cmd:a,size:o}=(yield yield eD(null))||{cmd:`read`,size:0});let l=new GD(e);try{do if({done:t,value:i}=Number.isNaN(o-s)?yield eD(l.read()):yield eD(l.read(o-s)),!t&&i.byteLength>0&&(r.push(MD(i)),s+=i.byteLength),t||o<=s)do({cmd:a,size:o}=yield yield eD(c()));while(o<s);while(!t)}catch(e){(n=!0)&&(yield eD(l.cancel(e)))}finally{n===!1?yield eD(l.cancel()):e.locked&&l.releaseLock()}return yield eD(null)})}var GD=class{constructor(e){this.source=e,this.reader=null,this.reader=this.source.getReader(),this.reader.closed.catch(()=>{})}get closed(){return this.reader?this.reader.closed.catch(()=>{}):Promise.resolve()}releaseLock(){this.reader&&this.reader.releaseLock(),this.reader=null}cancel(e){return QE(this,void 0,void 0,function*(){let{reader:t,source:n}=this;t&&(yield t.cancel(e).catch(()=>{})),n&&n.locked&&this.releaseLock()})}read(e){return QE(this,void 0,void 0,function*(){if(e===0)return{done:this.reader==null,value:new Uint8Array};let t=yield this.reader.read();return!t.done&&(t.value=MD(t)),t})}},KD=(e,t)=>{let n=e=>r([t,e]),r;return[t,n,new Promise(i=>(r=i)&&e.once(t,n))]};function qD(e){return tD(this,arguments,function*(){let t=[],n=`error`,r=!1,i=null,a,o,s=0,c=[],l;function u(){return a===`peek`?OD(c,o)[0]:([l,c,s]=OD(c,o),l)}if({cmd:a,size:o}=(yield yield eD(null))||{cmd:`read`,size:0},e.isTTY)return yield yield eD(new Uint8Array),yield eD(null);try{t[0]=KD(e,`end`),t[1]=KD(e,`error`);do{if(t[2]=KD(e,`readable`),[n,i]=yield eD(Promise.race(t.map(e=>e[2]))),n===`error`)break;if((r=n===`end`)||(Number.isFinite(o-s)?(l=MD(e.read(o-s)),l.byteLength<o-s&&(l=MD(e.read()))):l=MD(e.read()),l.byteLength>0&&(c.push(l),s+=l.byteLength)),r||o<=s)do({cmd:a,size:o}=yield yield eD(u()));while(o<s)}while(!r)}finally{yield eD(d(t,n===`error`?i:null))}return yield eD(null);function d(t,n){return l=c=null,new Promise((r,i)=>{for(let[n,r]of t)e.off(n,r);try{let t=e.destroy;t&&t.call(e,n),n=void 0}catch(e){n=e||n}finally{n==null?r():i(n)}})}})}var JD;(function(e){e[e.V1=0]=`V1`,e[e.V2=1]=`V2`,e[e.V3=2]=`V3`,e[e.V4=3]=`V4`,e[e.V5=4]=`V5`})(JD||={});var YD;(function(e){e[e.Sparse=0]=`Sparse`,e[e.Dense=1]=`Dense`})(YD||={});var XD;(function(e){e[e.HALF=0]=`HALF`,e[e.SINGLE=1]=`SINGLE`,e[e.DOUBLE=2]=`DOUBLE`})(XD||={});var ZD;(function(e){e[e.DAY=0]=`DAY`,e[e.MILLISECOND=1]=`MILLISECOND`})(ZD||={});var QD;(function(e){e[e.SECOND=0]=`SECOND`,e[e.MILLISECOND=1]=`MILLISECOND`,e[e.MICROSECOND=2]=`MICROSECOND`,e[e.NANOSECOND=3]=`NANOSECOND`})(QD||={});var $D;(function(e){e[e.YEAR_MONTH=0]=`YEAR_MONTH`,e[e.DAY_TIME=1]=`DAY_TIME`,e[e.MONTH_DAY_NANO=2]=`MONTH_DAY_NANO`})($D||={});var eO=new Int32Array(2),tO=new Float32Array(eO.buffer),nO=new Float64Array(eO.buffer),rO=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,iO;(function(e){e[e.UTF8_BYTES=1]=`UTF8_BYTES`,e[e.UTF16_STRING=2]=`UTF16_STRING`})(iO||={});var aO=class e{constructor(e){this.bytes_=e,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(t){return new e(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return BigInt.asIntN(64,BigInt(this.readUint32(e))+(BigInt(this.readUint32(e+4))<<BigInt(32)))}readUint64(e){return BigInt.asUintN(64,BigInt(this.readUint32(e))+(BigInt(this.readUint32(e+4))<<BigInt(32)))}readFloat32(e){return eO[0]=this.readInt32(e),tO[0]}readFloat64(e){return eO[+!rO]=this.readInt32(e),eO[+!!rO]=this.readInt32(e+4),nO[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,Number(BigInt.asIntN(32,t))),this.writeInt32(e+4,Number(BigInt.asIntN(32,t>>BigInt(32))))}writeUint64(e,t){this.writeUint32(e,Number(BigInt.asUintN(32,t))),this.writeUint32(e+4,Number(BigInt.asUintN(32,t>>BigInt(32))))}writeFloat32(e,t){tO[0]=t,this.writeInt32(e,eO[0])}writeFloat64(e,t){nO[0]=t,this.writeInt32(e,eO[+!rO]),this.writeInt32(e+4,eO[+!!rO])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw Error(`FlatBuffers: ByteBuffer is too short to contain an identifier.`);let e=``;for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let n=this.readInt32(e);e+=4;let r=this.bytes_.subarray(e,e+n);return t===iO.UTF8_BYTES?r:this.text_decoder_.decode(r)}__union_with_string(e,t){return typeof e==`string`?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw Error(`FlatBuffers: file identifier must be length 4`);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createScalarList(e,t){let n=[];for(let r=0;r<t;++r){let t=e(r);t!==null&&n.push(t)}return n}createObjList(e,t){let n=[];for(let r=0;r<t;++r){let t=e(r);t!==null&&n.push(t.unpack())}return n}},oO=class e{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null,this.text_encoder=new TextEncoder;let t;t=e||1024,this.bb=aO.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(t,n){t>this.minalign&&(this.minalign=t);let r=~(this.bb.capacity()-this.space+n)+1&t-1;for(;this.space<r+t+n;){let t=this.bb.capacity();this.bb=e.growByteBuffer(this.bb),this.space+=this.bb.capacity()-t}this.pad(r)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(--this.space,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,n){(this.force_defaults||t!==n)&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,n){t!=n&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw TypeError(`FlatBuffers: struct must be serialized inline.`)}notNested(){if(this.isNested)throw TypeError(`FlatBuffers: object serialization must not be nested.`)}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw Error(`FlatBuffers: cannot grow buffer beyond 2 gigabytes.`);let n=t<<1,r=aO.allocate(n);return r.setPosition(n-t),r.bytes().set(e.bytes(),n-t),r}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable??=[],this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw Error(`FlatBuffers: endObject called without startObject`);this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let n=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]==0?0:e-this.vtable[t]);this.addInt16(e-this.object_start);let r=(n+2)*2;this.addInt16(r);let i=0,a=this.space;outer_loop:for(t=0;t<this.vtables.length;t++){let e=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(e)){for(let t=2;t<r;t+=2)if(this.bb.readInt16(a+t)!=this.bb.readInt16(e+t))continue outer_loop;i=this.vtables[t];break}}return i?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,i-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,n){let r=n?4:0;if(t){let e=t;if(this.prep(this.minalign,8+r),e.length!=4)throw TypeError(`FlatBuffers: file identifier must be length 4`);for(let t=3;t>=0;t--)this.writeInt8(e.charCodeAt(t))}this.prep(this.minalign,4+r),this.addOffset(e),r&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let n=this.bb.capacity()-e,r=n-this.bb.readInt32(n);if(!(t<this.bb.readInt16(r)&&this.bb.readInt16(r+t)!=0))throw TypeError(`FlatBuffers: field `+t+` must be set`)}startVector(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(n,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||=new Map,this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(e==null)return 0;let t;return t=e instanceof Uint8Array?e:this.text_encoder.encode(e),this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length),this.bb.bytes().set(t,this.space),this.endVector()}createByteVector(e){return e==null?0:(this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length),this.bb.bytes().set(e,this.space),this.endVector())}createObjectOffset(e){return e===null?0:typeof e==`string`?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n];if(r!==null)t.push(this.createObjectOffset(r));else throw TypeError(`FlatBuffers: Argument for createObjectOffsetList cannot contain null.`)}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e.slice().reverse()),this.endVector()}},sO;(function(e){e[e.BUFFER=0]=`BUFFER`})(sO||={});var cO;(function(e){e[e.LZ4_FRAME=0]=`LZ4_FRAME`,e[e.ZSTD=1]=`ZSTD`})(cO||={});var lO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsBodyCompression(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsBodyCompression(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}codec(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt8(this.bb_pos+e):cO.LZ4_FRAME}method(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt8(this.bb_pos+e):sO.BUFFER}static startBodyCompression(e){e.startObject(2)}static addCodec(e,t){e.addFieldInt8(0,t,cO.LZ4_FRAME)}static addMethod(e,t){e.addFieldInt8(1,t,sO.BUFFER)}static endBodyCompression(e){return e.endObject()}static createBodyCompression(t,n,r){return e.startBodyCompression(t),e.addCodec(t,n),e.addMethod(t,r),e.endBodyCompression(t)}},uO=class{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}offset(){return this.bb.readInt64(this.bb_pos)}length(){return this.bb.readInt64(this.bb_pos+8)}static sizeOf(){return 16}static createBuffer(e,t,n){return e.prep(8,16),e.writeInt64(BigInt(n??0)),e.writeInt64(BigInt(t??0)),e.offset()}},dO=class{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}length(){return this.bb.readInt64(this.bb_pos)}nullCount(){return this.bb.readInt64(this.bb_pos+8)}static sizeOf(){return 16}static createFieldNode(e,t,n){return e.prep(8,16),e.writeInt64(BigInt(n??0)),e.writeInt64(BigInt(t??0)),e.offset()}},fO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsRecordBatch(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsRecordBatch(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}length(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt64(this.bb_pos+e):BigInt(`0`)}nodes(e,t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new dO).__init(this.bb.__vector(this.bb_pos+n)+e*16,this.bb):null}nodesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}buffers(e,t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new uO).__init(this.bb.__vector(this.bb_pos+n)+e*16,this.bb):null}buffersLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}compression(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new lO).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}static startRecordBatch(e){e.startObject(4)}static addLength(e,t){e.addFieldInt64(0,t,BigInt(`0`))}static addNodes(e,t){e.addFieldOffset(1,t,0)}static startNodesVector(e,t){e.startVector(16,t,8)}static addBuffers(e,t){e.addFieldOffset(2,t,0)}static startBuffersVector(e,t){e.startVector(16,t,8)}static addCompression(e,t){e.addFieldOffset(3,t,0)}static endRecordBatch(e){return e.endObject()}},pO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDictionaryBatch(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDictionaryBatch(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}id(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt64(this.bb_pos+e):BigInt(`0`)}data(e){let t=this.bb.__offset(this.bb_pos,6);return t?(e||new fO).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}isDelta(){let e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startDictionaryBatch(e){e.startObject(3)}static addId(e,t){e.addFieldInt64(0,t,BigInt(`0`))}static addData(e,t){e.addFieldOffset(1,t,0)}static addIsDelta(e,t){e.addFieldInt8(2,+t,0)}static endDictionaryBatch(e){return e.endObject()}},mO;(function(e){e[e.Little=0]=`Little`,e[e.Big=1]=`Big`})(mO||={});var hO;(function(e){e[e.DenseArray=0]=`DenseArray`})(hO||={});var gO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsInt(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInt(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}bitWidth(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):0}isSigned(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startInt(e){e.startObject(2)}static addBitWidth(e,t){e.addFieldInt32(0,t,0)}static addIsSigned(e,t){e.addFieldInt8(1,+t,0)}static endInt(e){return e.endObject()}static createInt(t,n,r){return e.startInt(t),e.addBitWidth(t,n),e.addIsSigned(t,r),e.endInt(t)}},_O=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDictionaryEncoding(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDictionaryEncoding(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}id(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt64(this.bb_pos+e):BigInt(`0`)}indexType(e){let t=this.bb.__offset(this.bb_pos,6);return t?(e||new gO).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}isOrdered(){let e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}dictionaryKind(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt16(this.bb_pos+e):hO.DenseArray}static startDictionaryEncoding(e){e.startObject(4)}static addId(e,t){e.addFieldInt64(0,t,BigInt(`0`))}static addIndexType(e,t){e.addFieldOffset(1,t,0)}static addIsOrdered(e,t){e.addFieldInt8(2,+t,0)}static addDictionaryKind(e,t){e.addFieldInt16(3,t,hO.DenseArray)}static endDictionaryEncoding(e){return e.endObject()}},vO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsKeyValue(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKeyValue(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}key(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}value(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}static startKeyValue(e){e.startObject(2)}static addKey(e,t){e.addFieldOffset(0,t,0)}static addValue(e,t){e.addFieldOffset(1,t,0)}static endKeyValue(e){return e.endObject()}static createKeyValue(t,n,r){return e.startKeyValue(t),e.addKey(t,n),e.addValue(t,r),e.endKeyValue(t)}},yO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsBinary(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsBinary(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startBinary(e){e.startObject(0)}static endBinary(e){return e.endObject()}static createBinary(t){return e.startBinary(t),e.endBinary(t)}},bO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsBool(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsBool(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startBool(e){e.startObject(0)}static endBool(e){return e.endObject()}static createBool(t){return e.startBool(t),e.endBool(t)}},xO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDate(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDate(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}unit(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):ZD.MILLISECOND}static startDate(e){e.startObject(1)}static addUnit(e,t){e.addFieldInt16(0,t,ZD.MILLISECOND)}static endDate(e){return e.endObject()}static createDate(t,n){return e.startDate(t),e.addUnit(t,n),e.endDate(t)}},SO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDecimal(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDecimal(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}precision(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):0}scale(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt32(this.bb_pos+e):0}bitWidth(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt32(this.bb_pos+e):128}static startDecimal(e){e.startObject(3)}static addPrecision(e,t){e.addFieldInt32(0,t,0)}static addScale(e,t){e.addFieldInt32(1,t,0)}static addBitWidth(e,t){e.addFieldInt32(2,t,128)}static endDecimal(e){return e.endObject()}static createDecimal(t,n,r,i){return e.startDecimal(t),e.addPrecision(t,n),e.addScale(t,r),e.addBitWidth(t,i),e.endDecimal(t)}},CO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDuration(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDuration(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}unit(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):QD.MILLISECOND}static startDuration(e){e.startObject(1)}static addUnit(e,t){e.addFieldInt16(0,t,QD.MILLISECOND)}static endDuration(e){return e.endObject()}static createDuration(t,n){return e.startDuration(t),e.addUnit(t,n),e.endDuration(t)}},wO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFixedSizeBinary(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFixedSizeBinary(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}byteWidth(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):0}static startFixedSizeBinary(e){e.startObject(1)}static addByteWidth(e,t){e.addFieldInt32(0,t,0)}static endFixedSizeBinary(e){return e.endObject()}static createFixedSizeBinary(t,n){return e.startFixedSizeBinary(t),e.addByteWidth(t,n),e.endFixedSizeBinary(t)}},TO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFixedSizeList(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFixedSizeList(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}listSize(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):0}static startFixedSizeList(e){e.startObject(1)}static addListSize(e,t){e.addFieldInt32(0,t,0)}static endFixedSizeList(e){return e.endObject()}static createFixedSizeList(t,n){return e.startFixedSizeList(t),e.addListSize(t,n),e.endFixedSizeList(t)}},EO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFloatingPoint(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFloatingPoint(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}precision(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):XD.HALF}static startFloatingPoint(e){e.startObject(1)}static addPrecision(e,t){e.addFieldInt16(0,t,XD.HALF)}static endFloatingPoint(e){return e.endObject()}static createFloatingPoint(t,n){return e.startFloatingPoint(t),e.addPrecision(t,n),e.endFloatingPoint(t)}},DO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsInterval(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInterval(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}unit(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):$D.YEAR_MONTH}static startInterval(e){e.startObject(1)}static addUnit(e,t){e.addFieldInt16(0,t,$D.YEAR_MONTH)}static endInterval(e){return e.endObject()}static createInterval(t,n){return e.startInterval(t),e.addUnit(t,n),e.endInterval(t)}},OO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsLargeBinary(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsLargeBinary(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startLargeBinary(e){e.startObject(0)}static endLargeBinary(e){return e.endObject()}static createLargeBinary(t){return e.startLargeBinary(t),e.endLargeBinary(t)}},kO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsLargeUtf8(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsLargeUtf8(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startLargeUtf8(e){e.startObject(0)}static endLargeUtf8(e){return e.endObject()}static createLargeUtf8(t){return e.startLargeUtf8(t),e.endLargeUtf8(t)}},AO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsList(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsList(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startList(e){e.startObject(0)}static endList(e){return e.endObject()}static createList(t){return e.startList(t),e.endList(t)}},jO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMap(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMap(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}keysSorted(){let e=this.bb.__offset(this.bb_pos,4);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startMap(e){e.startObject(1)}static addKeysSorted(e,t){e.addFieldInt8(0,+t,0)}static endMap(e){return e.endObject()}static createMap(t,n){return e.startMap(t),e.addKeysSorted(t,n),e.endMap(t)}},MO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsNull(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNull(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startNull(e){e.startObject(0)}static endNull(e){return e.endObject()}static createNull(t){return e.startNull(t),e.endNull(t)}},NO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsStruct_(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsStruct_(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startStruct_(e){e.startObject(0)}static endStruct_(e){return e.endObject()}static createStruct_(t){return e.startStruct_(t),e.endStruct_(t)}},PO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTime(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTime(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}unit(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):QD.MILLISECOND}bitWidth(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt32(this.bb_pos+e):32}static startTime(e){e.startObject(2)}static addUnit(e,t){e.addFieldInt16(0,t,QD.MILLISECOND)}static addBitWidth(e,t){e.addFieldInt32(1,t,32)}static endTime(e){return e.endObject()}static createTime(t,n,r){return e.startTime(t),e.addUnit(t,n),e.addBitWidth(t,r),e.endTime(t)}},FO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTimestamp(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTimestamp(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}unit(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):QD.SECOND}timezone(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}static startTimestamp(e){e.startObject(2)}static addUnit(e,t){e.addFieldInt16(0,t,QD.SECOND)}static addTimezone(e,t){e.addFieldOffset(1,t,0)}static endTimestamp(e){return e.endObject()}static createTimestamp(t,n,r){return e.startTimestamp(t),e.addUnit(t,n),e.addTimezone(t,r),e.endTimestamp(t)}},IO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsUnion(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsUnion(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}mode(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):YD.Sparse}typeIds(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt32(this.bb.__vector(this.bb_pos+t)+e*4):0}typeIdsLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}typeIdsArray(){let e=this.bb.__offset(this.bb_pos,6);return e?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}static startUnion(e){e.startObject(2)}static addMode(e,t){e.addFieldInt16(0,t,YD.Sparse)}static addTypeIds(e,t){e.addFieldOffset(1,t,0)}static createTypeIdsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addInt32(t[n]);return e.endVector()}static startTypeIdsVector(e,t){e.startVector(4,t,4)}static endUnion(e){return e.endObject()}static createUnion(t,n,r){return e.startUnion(t),e.addMode(t,n),e.addTypeIds(t,r),e.endUnion(t)}},LO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsUtf8(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsUtf8(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startUtf8(e){e.startObject(0)}static endUtf8(e){return e.endObject()}static createUtf8(t){return e.startUtf8(t),e.endUtf8(t)}},RO;(function(e){e[e.NONE=0]=`NONE`,e[e.Null=1]=`Null`,e[e.Int=2]=`Int`,e[e.FloatingPoint=3]=`FloatingPoint`,e[e.Binary=4]=`Binary`,e[e.Utf8=5]=`Utf8`,e[e.Bool=6]=`Bool`,e[e.Decimal=7]=`Decimal`,e[e.Date=8]=`Date`,e[e.Time=9]=`Time`,e[e.Timestamp=10]=`Timestamp`,e[e.Interval=11]=`Interval`,e[e.List=12]=`List`,e[e.Struct_=13]=`Struct_`,e[e.Union=14]=`Union`,e[e.FixedSizeBinary=15]=`FixedSizeBinary`,e[e.FixedSizeList=16]=`FixedSizeList`,e[e.Map=17]=`Map`,e[e.Duration=18]=`Duration`,e[e.LargeBinary=19]=`LargeBinary`,e[e.LargeUtf8=20]=`LargeUtf8`,e[e.LargeList=21]=`LargeList`,e[e.RunEndEncoded=22]=`RunEndEncoded`})(RO||={});var zO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsField(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsField(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}nullable(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}typeType(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readUint8(this.bb_pos+e):RO.NONE}type(e){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__union(e,this.bb_pos+t):null}dictionary(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new _O).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}children(t,n){let r=this.bb.__offset(this.bb_pos,14);return r?(n||new e).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+t*4),this.bb):null}childrenLength(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){let n=this.bb.__offset(this.bb_pos,16);return n?(t||new vO).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+e*4),this.bb):null}customMetadataLength(){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__vector_len(this.bb_pos+e):0}static startField(e){e.startObject(7)}static addName(e,t){e.addFieldOffset(0,t,0)}static addNullable(e,t){e.addFieldInt8(1,+t,0)}static addTypeType(e,t){e.addFieldInt8(2,t,RO.NONE)}static addType(e,t){e.addFieldOffset(3,t,0)}static addDictionary(e,t){e.addFieldOffset(4,t,0)}static addChildren(e,t){e.addFieldOffset(5,t,0)}static createChildrenVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startChildrenVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(6,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endField(e){return e.endObject()}},BO=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSchema(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSchema(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}endianness(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):mO.Little}fields(e,t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new zO).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+e*4),this.bb):null}fieldsLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new vO).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+e*4),this.bb):null}customMetadataLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}features(e){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+e*8):BigInt(0)}featuresLength(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSchema(e){e.startObject(4)}static addEndianness(e,t){e.addFieldInt16(0,t,mO.Little)}static addFields(e,t){e.addFieldOffset(1,t,0)}static createFieldsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startFieldsVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(2,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static addFeatures(e,t){e.addFieldOffset(3,t,0)}static createFeaturesVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startFeaturesVector(e,t){e.startVector(8,t,8)}static endSchema(e){return e.endObject()}static finishSchemaBuffer(e,t){e.finish(t)}static finishSizePrefixedSchemaBuffer(e,t){e.finish(t,void 0,!0)}static createSchema(t,n,r,i,a){return e.startSchema(t),e.addEndianness(t,n),e.addFields(t,r),e.addCustomMetadata(t,i),e.addFeatures(t,a),e.endSchema(t)}},VO;(function(e){e[e.NONE=0]=`NONE`,e[e.Schema=1]=`Schema`,e[e.DictionaryBatch=2]=`DictionaryBatch`,e[e.RecordBatch=3]=`RecordBatch`,e[e.Tensor=4]=`Tensor`,e[e.SparseTensor=5]=`SparseTensor`})(VO||={});var Z;(function(e){e[e.NONE=0]=`NONE`,e[e.Null=1]=`Null`,e[e.Int=2]=`Int`,e[e.Float=3]=`Float`,e[e.Binary=4]=`Binary`,e[e.Utf8=5]=`Utf8`,e[e.Bool=6]=`Bool`,e[e.Decimal=7]=`Decimal`,e[e.Date=8]=`Date`,e[e.Time=9]=`Time`,e[e.Timestamp=10]=`Timestamp`,e[e.Interval=11]=`Interval`,e[e.List=12]=`List`,e[e.Struct=13]=`Struct`,e[e.Union=14]=`Union`,e[e.FixedSizeBinary=15]=`FixedSizeBinary`,e[e.FixedSizeList=16]=`FixedSizeList`,e[e.Map=17]=`Map`,e[e.Duration=18]=`Duration`,e[e.LargeBinary=19]=`LargeBinary`,e[e.LargeUtf8=20]=`LargeUtf8`,e[e.Dictionary=-1]=`Dictionary`,e[e.Int8=-2]=`Int8`,e[e.Int16=-3]=`Int16`,e[e.Int32=-4]=`Int32`,e[e.Int64=-5]=`Int64`,e[e.Uint8=-6]=`Uint8`,e[e.Uint16=-7]=`Uint16`,e[e.Uint32=-8]=`Uint32`,e[e.Uint64=-9]=`Uint64`,e[e.Float16=-10]=`Float16`,e[e.Float32=-11]=`Float32`,e[e.Float64=-12]=`Float64`,e[e.DateDay=-13]=`DateDay`,e[e.DateMillisecond=-14]=`DateMillisecond`,e[e.TimestampSecond=-15]=`TimestampSecond`,e[e.TimestampMillisecond=-16]=`TimestampMillisecond`,e[e.TimestampMicrosecond=-17]=`TimestampMicrosecond`,e[e.TimestampNanosecond=-18]=`TimestampNanosecond`,e[e.TimeSecond=-19]=`TimeSecond`,e[e.TimeMillisecond=-20]=`TimeMillisecond`,e[e.TimeMicrosecond=-21]=`TimeMicrosecond`,e[e.TimeNanosecond=-22]=`TimeNanosecond`,e[e.DenseUnion=-23]=`DenseUnion`,e[e.SparseUnion=-24]=`SparseUnion`,e[e.IntervalDayTime=-25]=`IntervalDayTime`,e[e.IntervalYearMonth=-26]=`IntervalYearMonth`,e[e.DurationSecond=-27]=`DurationSecond`,e[e.DurationMillisecond=-28]=`DurationMillisecond`,e[e.DurationMicrosecond=-29]=`DurationMicrosecond`,e[e.DurationNanosecond=-30]=`DurationNanosecond`})(Z||={});var HO;(function(e){e[e.OFFSET=0]=`OFFSET`,e[e.DATA=1]=`DATA`,e[e.VALIDITY=2]=`VALIDITY`,e[e.TYPE=3]=`TYPE`})(HO||={});var UO=void 0;function WO(e){if(e===null)return`null`;if(e===UO)return`undefined`;switch(typeof e){case`number`:return`${e}`;case`bigint`:return`${e}`;case`string`:return`"${e}"`}return typeof e[Symbol.toPrimitive]==`function`?e[Symbol.toPrimitive](`string`):ArrayBuffer.isView(e)?e instanceof BigInt64Array||e instanceof BigUint64Array?`[${[...e].map(e=>WO(e))}]`:`[${e}]`:ArrayBuffer.isView(e)?`[${e}]`:JSON.stringify(e,(e,t)=>typeof t==`bigint`?`${t}`:t)}function GO(e){if(typeof e==`bigint`&&(e<-(2**53-1)||e>2**53-1))throw TypeError(`${e} is not safe to convert to a number.`);return Number(e)}function KO(e,t){return GO(e/t)+GO(e%t)/GO(t)}var qO=Symbol.for(`isArrowBigNum`);function JO(e,...t){return t.length===0?Object.setPrototypeOf(kD(this.TypedArray,e),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(e,...t),this.constructor.prototype)}JO.prototype[qO]=!0,JO.prototype.toJSON=function(){return`"${ek(this)}"`},JO.prototype.valueOf=function(e){return $O(this,e)},JO.prototype.toString=function(){return ek(this)},JO.prototype[Symbol.toPrimitive]=function(e=`default`){switch(e){case`number`:return $O(this);case`string`:return ek(this);case`default`:return tk(this)}return ek(this)};function YO(...e){return JO.apply(this,e)}function XO(...e){return JO.apply(this,e)}function ZO(...e){return JO.apply(this,e)}Object.setPrototypeOf(YO.prototype,Object.create(Int32Array.prototype)),Object.setPrototypeOf(XO.prototype,Object.create(Uint32Array.prototype)),Object.setPrototypeOf(ZO.prototype,Object.create(Uint32Array.prototype)),Object.assign(YO.prototype,JO.prototype,{constructor:YO,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array}),Object.assign(XO.prototype,JO.prototype,{constructor:XO,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array}),Object.assign(ZO.prototype,JO.prototype,{constructor:ZO,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});var QO=BigInt(4294967296)*BigInt(4294967296)-BigInt(1);function $O(e,t){let{buffer:n,byteOffset:r,byteLength:i,signed:a}=e,o=new BigUint64Array(n,r,i/8),s=a&&o.at(-1)&BigInt(1)<<BigInt(63),c=BigInt(0),l=0;if(s){for(let e of o)c|=(e^QO)*(BigInt(1)<<BigInt(64*l++));c*=BigInt(-1),c-=BigInt(1)}else for(let e of o)c|=e*(BigInt(1)<<BigInt(64*l++));if(typeof t==`number`){let e=BigInt(10**t),n=c/e,r=c%e;return GO(n)+GO(r)/GO(e)}return GO(c)}function ek(e){if(e.byteLength===8)return`${new e.BigIntArray(e.buffer,e.byteOffset,1)[0]}`;if(!e.signed)return nk(e);let t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2);if(new Int16Array([t.at(-1)])[0]>=0)return nk(e);t=t.slice();let n=1;for(let e=0;e<t.length;e++){let r=t[e],i=~r+n;t[e]=i,n&=+(r===0)}return`-${nk(t)}`}function tk(e){return e.byteLength===8?new e.BigIntArray(e.buffer,e.byteOffset,1)[0]:ek(e)}function nk(e){let t=``,n=new Uint32Array(2),r=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=new Uint32Array((r=new Uint16Array(r).reverse()).buffer),a=-1,o=r.length-1;do{for(n[0]=r[a=0];a<o;)r[a++]=n[1]=n[0]/10,n[0]=(n[0]-n[1]*10<<16)+r[a];r[a]=n[1]=n[0]/10,n[0]-=n[1]*10,t=`${n[0]}${t}`}while(i[0]||i[1]||i[2]||i[3]);return t??`0`}var rk=class e{static new(e,t){switch(t){case!0:return new YO(e);case!1:return new XO(e)}switch(e.constructor){case Int8Array:case Int16Array:case Int32Array:case BigInt64Array:return new YO(e)}return e.byteLength===16?new ZO(e):new XO(e)}static signed(e){return new YO(e)}static unsigned(e){return new XO(e)}static decimal(e){return new ZO(e)}constructor(t,n){return e.new(t,n)}},ik,ak,ok,sk,ck,lk,uk,dk,fk,pk,mk,hk,gk,_k,vk,yk,bk,xk,Sk,Ck,wk,Tk,Ek=class e{static isNull(e){return e?.typeId===Z.Null}static isInt(e){return e?.typeId===Z.Int}static isFloat(e){return e?.typeId===Z.Float}static isBinary(e){return e?.typeId===Z.Binary}static isLargeBinary(e){return e?.typeId===Z.LargeBinary}static isUtf8(e){return e?.typeId===Z.Utf8}static isLargeUtf8(e){return e?.typeId===Z.LargeUtf8}static isBool(e){return e?.typeId===Z.Bool}static isDecimal(e){return e?.typeId===Z.Decimal}static isDate(e){return e?.typeId===Z.Date}static isTime(e){return e?.typeId===Z.Time}static isTimestamp(e){return e?.typeId===Z.Timestamp}static isInterval(e){return e?.typeId===Z.Interval}static isDuration(e){return e?.typeId===Z.Duration}static isList(e){return e?.typeId===Z.List}static isStruct(e){return e?.typeId===Z.Struct}static isUnion(e){return e?.typeId===Z.Union}static isFixedSizeBinary(e){return e?.typeId===Z.FixedSizeBinary}static isFixedSizeList(e){return e?.typeId===Z.FixedSizeList}static isMap(e){return e?.typeId===Z.Map}static isDictionary(e){return e?.typeId===Z.Dictionary}static isDenseUnion(t){return e.isUnion(t)&&t.mode===YD.Dense}static isSparseUnion(t){return e.isUnion(t)&&t.mode===YD.Sparse}constructor(e){this.typeId=e}};ik=Symbol.toStringTag,Ek[ik]=(e=>(e.children=null,e.ArrayType=Array,e.OffsetArrayType=Int32Array,e[Symbol.toStringTag]=`DataType`))(Ek.prototype);var Dk=class extends Ek{constructor(){super(Z.Null)}toString(){return`Null`}};ak=Symbol.toStringTag,Dk[ak]=(e=>e[Symbol.toStringTag]=`Null`)(Dk.prototype);var Ok=class extends Ek{constructor(e,t){super(Z.Int),this.isSigned=e,this.bitWidth=t}get ArrayType(){switch(this.bitWidth){case 8:return this.isSigned?Int8Array:Uint8Array;case 16:return this.isSigned?Int16Array:Uint16Array;case 32:return this.isSigned?Int32Array:Uint32Array;case 64:return this.isSigned?BigInt64Array:BigUint64Array}throw Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`${this.isSigned?`I`:`Ui`}nt${this.bitWidth}`}};ok=Symbol.toStringTag,Ok[ok]=(e=>(e.isSigned=null,e.bitWidth=null,e[Symbol.toStringTag]=`Int`))(Ok.prototype);var kk=class extends Ok{constructor(){super(!0,8)}get ArrayType(){return Int8Array}},Ak=class extends Ok{constructor(){super(!0,16)}get ArrayType(){return Int16Array}},jk=class extends Ok{constructor(){super(!0,32)}get ArrayType(){return Int32Array}},Mk=class extends Ok{constructor(){super(!0,64)}get ArrayType(){return BigInt64Array}},Nk=class extends Ok{constructor(){super(!1,8)}get ArrayType(){return Uint8Array}},Pk=class extends Ok{constructor(){super(!1,16)}get ArrayType(){return Uint16Array}},Fk=class extends Ok{constructor(){super(!1,32)}get ArrayType(){return Uint32Array}},Ik=class extends Ok{constructor(){super(!1,64)}get ArrayType(){return BigUint64Array}};Object.defineProperty(kk.prototype,`ArrayType`,{value:Int8Array}),Object.defineProperty(Ak.prototype,`ArrayType`,{value:Int16Array}),Object.defineProperty(jk.prototype,`ArrayType`,{value:Int32Array}),Object.defineProperty(Mk.prototype,`ArrayType`,{value:BigInt64Array}),Object.defineProperty(Nk.prototype,`ArrayType`,{value:Uint8Array}),Object.defineProperty(Pk.prototype,`ArrayType`,{value:Uint16Array}),Object.defineProperty(Fk.prototype,`ArrayType`,{value:Uint32Array}),Object.defineProperty(Ik.prototype,`ArrayType`,{value:BigUint64Array});var Lk=class extends Ek{constructor(e){super(Z.Float),this.precision=e}get ArrayType(){switch(this.precision){case XD.HALF:return Uint16Array;case XD.SINGLE:return Float32Array;case XD.DOUBLE:return Float64Array}throw Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}};sk=Symbol.toStringTag,Lk[sk]=(e=>(e.precision=null,e[Symbol.toStringTag]=`Float`))(Lk.prototype);var Rk=class extends Lk{constructor(){super(XD.HALF)}},zk=class extends Lk{constructor(){super(XD.SINGLE)}},Bk=class extends Lk{constructor(){super(XD.DOUBLE)}};Object.defineProperty(Rk.prototype,`ArrayType`,{value:Uint16Array}),Object.defineProperty(zk.prototype,`ArrayType`,{value:Float32Array}),Object.defineProperty(Bk.prototype,`ArrayType`,{value:Float64Array});var Vk=class extends Ek{constructor(){super(Z.Binary)}toString(){return`Binary`}};ck=Symbol.toStringTag,Vk[ck]=(e=>(e.ArrayType=Uint8Array,e[Symbol.toStringTag]=`Binary`))(Vk.prototype);var Hk=class extends Ek{constructor(){super(Z.LargeBinary)}toString(){return`LargeBinary`}};lk=Symbol.toStringTag,Hk[lk]=(e=>(e.ArrayType=Uint8Array,e.OffsetArrayType=BigInt64Array,e[Symbol.toStringTag]=`LargeBinary`))(Hk.prototype);var Uk=class extends Ek{constructor(){super(Z.Utf8)}toString(){return`Utf8`}};uk=Symbol.toStringTag,Uk[uk]=(e=>(e.ArrayType=Uint8Array,e[Symbol.toStringTag]=`Utf8`))(Uk.prototype);var Wk=class extends Ek{constructor(){super(Z.LargeUtf8)}toString(){return`LargeUtf8`}};dk=Symbol.toStringTag,Wk[dk]=(e=>(e.ArrayType=Uint8Array,e.OffsetArrayType=BigInt64Array,e[Symbol.toStringTag]=`LargeUtf8`))(Wk.prototype);var Gk=class extends Ek{constructor(){super(Z.Bool)}toString(){return`Bool`}};fk=Symbol.toStringTag,Gk[fk]=(e=>(e.ArrayType=Uint8Array,e[Symbol.toStringTag]=`Bool`))(Gk.prototype);var Kk=class extends Ek{constructor(e,t,n=128){super(Z.Decimal),this.scale=e,this.precision=t,this.bitWidth=n}toString(){return`Decimal[${this.precision}e${this.scale>0?`+`:``}${this.scale}]`}};pk=Symbol.toStringTag,Kk[pk]=(e=>(e.scale=null,e.precision=null,e.ArrayType=Uint32Array,e[Symbol.toStringTag]=`Decimal`))(Kk.prototype);var qk=class extends Ek{constructor(e){super(Z.Date),this.unit=e}toString(){return`Date${(this.unit+1)*32}<${ZD[this.unit]}>`}get ArrayType(){return this.unit===ZD.DAY?Int32Array:BigInt64Array}};mk=Symbol.toStringTag,qk[mk]=(e=>(e.unit=null,e[Symbol.toStringTag]=`Date`))(qk.prototype);var Jk=class extends Ek{constructor(e,t){super(Z.Time),this.unit=e,this.bitWidth=t}toString(){return`Time${this.bitWidth}<${QD[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}};hk=Symbol.toStringTag,Jk[hk]=(e=>(e.unit=null,e.bitWidth=null,e[Symbol.toStringTag]=`Time`))(Jk.prototype);var Yk=class extends Ek{constructor(e,t){super(Z.Timestamp),this.unit=e,this.timezone=t}toString(){return`Timestamp<${QD[this.unit]}${this.timezone?`, ${this.timezone}`:``}>`}};gk=Symbol.toStringTag,Yk[gk]=(e=>(e.unit=null,e.timezone=null,e.ArrayType=BigInt64Array,e[Symbol.toStringTag]=`Timestamp`))(Yk.prototype);var Xk=class extends Yk{constructor(e){super(QD.MILLISECOND,e)}},Zk=class extends Ek{constructor(e){super(Z.Interval),this.unit=e}toString(){return`Interval<${$D[this.unit]}>`}};_k=Symbol.toStringTag,Zk[_k]=(e=>(e.unit=null,e.ArrayType=Int32Array,e[Symbol.toStringTag]=`Interval`))(Zk.prototype);var Qk=class extends Ek{constructor(e){super(Z.Duration),this.unit=e}toString(){return`Duration<${QD[this.unit]}>`}};vk=Symbol.toStringTag,Qk[vk]=(e=>(e.unit=null,e.ArrayType=BigInt64Array,e[Symbol.toStringTag]=`Duration`))(Qk.prototype);var $k=class extends Ek{constructor(e){super(Z.List),this.children=[e]}toString(){return`List<${this.valueType}>`}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}};yk=Symbol.toStringTag,$k[yk]=(e=>(e.children=null,e[Symbol.toStringTag]=`List`))($k.prototype);var eA=class extends Ek{constructor(e){super(Z.Struct),this.children=e}toString(){return`Struct<{${this.children.map(e=>`${e.name}:${e.type}`).join(`, `)}}>`}};bk=Symbol.toStringTag,eA[bk]=(e=>(e.children=null,e[Symbol.toStringTag]=`Struct`))(eA.prototype);var tA=class extends Ek{constructor(e,t,n){super(Z.Union),this.mode=e,this.children=n,this.typeIds=t=Int32Array.from(t),this.typeIdToChildIndex=t.reduce((e,t,n)=>(e[t]=n)&&e||e,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(e=>`${e.type}`).join(` | `)}>`}};xk=Symbol.toStringTag,tA[xk]=(e=>(e.mode=null,e.typeIds=null,e.children=null,e.typeIdToChildIndex=null,e.ArrayType=Int8Array,e[Symbol.toStringTag]=`Union`))(tA.prototype);var nA=class extends Ek{constructor(e){super(Z.FixedSizeBinary),this.byteWidth=e}toString(){return`FixedSizeBinary[${this.byteWidth}]`}};Sk=Symbol.toStringTag,nA[Sk]=(e=>(e.byteWidth=null,e.ArrayType=Uint8Array,e[Symbol.toStringTag]=`FixedSizeBinary`))(nA.prototype);var rA=class extends Ek{constructor(e,t){super(Z.FixedSizeList),this.listSize=e,this.children=[t]}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}toString(){return`FixedSizeList[${this.listSize}]<${this.valueType}>`}};Ck=Symbol.toStringTag,rA[Ck]=(e=>(e.children=null,e.listSize=null,e[Symbol.toStringTag]=`FixedSizeList`))(rA.prototype);var iA=class extends Ek{constructor(e,t=!1){if(super(Z.Map),this.children=[e],this.keysSorted=t,e&&(e.name=`entries`,e?.type?.children)){let t=(e?.type)?.children[0];t&&(t.name=`key`);let n=(e?.type)?.children[1];n&&(n.name=`value`)}}get keyType(){return this.children[0].type.children[0].type}get valueType(){return this.children[0].type.children[1].type}get childType(){return this.children[0].type}toString(){return`Map<{${this.children[0].type.children.map(e=>`${e.name}:${e.type}`).join(`, `)}}>`}};wk=Symbol.toStringTag,iA[wk]=(e=>(e.children=null,e.keysSorted=null,e[Symbol.toStringTag]=`Map_`))(iA.prototype);var aA=(e=>()=>++e)(-1),oA=class extends Ek{constructor(e,t,n,r){super(Z.Dictionary),this.indices=t,this.dictionary=e,this.isOrdered=r||!1,this.id=n==null?aA():GO(n)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}};Tk=Symbol.toStringTag,oA[Tk]=(e=>(e.id=null,e.indices=null,e.isOrdered=null,e.dictionary=null,e[Symbol.toStringTag]=`Dictionary`))(oA.prototype);function sA(e){let t=e;switch(e.typeId){case Z.Decimal:return e.bitWidth/32;case Z.Interval:return 1+t.unit;case Z.FixedSizeList:return t.listSize;case Z.FixedSizeBinary:return t.byteWidth;default:return 1}}var cA=class{visitMany(e,...t){return e.map((e,n)=>this.visit(e,...t.map(e=>e[n])))}visit(...e){return this.getVisitFn(e[0],!1).apply(this,e)}getVisitFn(e,t=!0){return lA(this,e,t)}getVisitFnByTypeId(e,t=!0){return uA(this,e,t)}visitNull(e,...t){return null}visitBool(e,...t){return null}visitInt(e,...t){return null}visitFloat(e,...t){return null}visitUtf8(e,...t){return null}visitLargeUtf8(e,...t){return null}visitBinary(e,...t){return null}visitLargeBinary(e,...t){return null}visitFixedSizeBinary(e,...t){return null}visitDate(e,...t){return null}visitTimestamp(e,...t){return null}visitTime(e,...t){return null}visitDecimal(e,...t){return null}visitList(e,...t){return null}visitStruct(e,...t){return null}visitUnion(e,...t){return null}visitDictionary(e,...t){return null}visitInterval(e,...t){return null}visitDuration(e,...t){return null}visitFixedSizeList(e,...t){return null}visitMap(e,...t){return null}};function lA(e,t,n=!0){return typeof t==`number`?uA(e,t,n):typeof t==`string`&&t in Z?uA(e,Z[t],n):t&&t instanceof Ek?uA(e,dA(t),n):t?.type&&t.type instanceof Ek?uA(e,dA(t.type),n):uA(e,Z.NONE,n)}function uA(e,t,n=!0){let r=null;switch(t){case Z.Null:r=e.visitNull;break;case Z.Bool:r=e.visitBool;break;case Z.Int:r=e.visitInt;break;case Z.Int8:r=e.visitInt8||e.visitInt;break;case Z.Int16:r=e.visitInt16||e.visitInt;break;case Z.Int32:r=e.visitInt32||e.visitInt;break;case Z.Int64:r=e.visitInt64||e.visitInt;break;case Z.Uint8:r=e.visitUint8||e.visitInt;break;case Z.Uint16:r=e.visitUint16||e.visitInt;break;case Z.Uint32:r=e.visitUint32||e.visitInt;break;case Z.Uint64:r=e.visitUint64||e.visitInt;break;case Z.Float:r=e.visitFloat;break;case Z.Float16:r=e.visitFloat16||e.visitFloat;break;case Z.Float32:r=e.visitFloat32||e.visitFloat;break;case Z.Float64:r=e.visitFloat64||e.visitFloat;break;case Z.Utf8:r=e.visitUtf8;break;case Z.LargeUtf8:r=e.visitLargeUtf8;break;case Z.Binary:r=e.visitBinary;break;case Z.LargeBinary:r=e.visitLargeBinary;break;case Z.FixedSizeBinary:r=e.visitFixedSizeBinary;break;case Z.Date:r=e.visitDate;break;case Z.DateDay:r=e.visitDateDay||e.visitDate;break;case Z.DateMillisecond:r=e.visitDateMillisecond||e.visitDate;break;case Z.Timestamp:r=e.visitTimestamp;break;case Z.TimestampSecond:r=e.visitTimestampSecond||e.visitTimestamp;break;case Z.TimestampMillisecond:r=e.visitTimestampMillisecond||e.visitTimestamp;break;case Z.TimestampMicrosecond:r=e.visitTimestampMicrosecond||e.visitTimestamp;break;case Z.TimestampNanosecond:r=e.visitTimestampNanosecond||e.visitTimestamp;break;case Z.Time:r=e.visitTime;break;case Z.TimeSecond:r=e.visitTimeSecond||e.visitTime;break;case Z.TimeMillisecond:r=e.visitTimeMillisecond||e.visitTime;break;case Z.TimeMicrosecond:r=e.visitTimeMicrosecond||e.visitTime;break;case Z.TimeNanosecond:r=e.visitTimeNanosecond||e.visitTime;break;case Z.Decimal:r=e.visitDecimal;break;case Z.List:r=e.visitList;break;case Z.Struct:r=e.visitStruct;break;case Z.Union:r=e.visitUnion;break;case Z.DenseUnion:r=e.visitDenseUnion||e.visitUnion;break;case Z.SparseUnion:r=e.visitSparseUnion||e.visitUnion;break;case Z.Dictionary:r=e.visitDictionary;break;case Z.Interval:r=e.visitInterval;break;case Z.IntervalDayTime:r=e.visitIntervalDayTime||e.visitInterval;break;case Z.IntervalYearMonth:r=e.visitIntervalYearMonth||e.visitInterval;break;case Z.Duration:r=e.visitDuration;break;case Z.DurationSecond:r=e.visitDurationSecond||e.visitDuration;break;case Z.DurationMillisecond:r=e.visitDurationMillisecond||e.visitDuration;break;case Z.DurationMicrosecond:r=e.visitDurationMicrosecond||e.visitDuration;break;case Z.DurationNanosecond:r=e.visitDurationNanosecond||e.visitDuration;break;case Z.FixedSizeList:r=e.visitFixedSizeList;break;case Z.Map:r=e.visitMap;break}if(typeof r==`function`)return r;if(!n)return()=>null;throw Error(`Unrecognized type '${Z[t]}'`)}function dA(e){switch(e.typeId){case Z.Null:return Z.Null;case Z.Int:{let{bitWidth:t,isSigned:n}=e;switch(t){case 8:return n?Z.Int8:Z.Uint8;case 16:return n?Z.Int16:Z.Uint16;case 32:return n?Z.Int32:Z.Uint32;case 64:return n?Z.Int64:Z.Uint64}return Z.Int}case Z.Float:switch(e.precision){case XD.HALF:return Z.Float16;case XD.SINGLE:return Z.Float32;case XD.DOUBLE:return Z.Float64}return Z.Float;case Z.Binary:return Z.Binary;case Z.LargeBinary:return Z.LargeBinary;case Z.Utf8:return Z.Utf8;case Z.LargeUtf8:return Z.LargeUtf8;case Z.Bool:return Z.Bool;case Z.Decimal:return Z.Decimal;case Z.Time:switch(e.unit){case QD.SECOND:return Z.TimeSecond;case QD.MILLISECOND:return Z.TimeMillisecond;case QD.MICROSECOND:return Z.TimeMicrosecond;case QD.NANOSECOND:return Z.TimeNanosecond}return Z.Time;case Z.Timestamp:switch(e.unit){case QD.SECOND:return Z.TimestampSecond;case QD.MILLISECOND:return Z.TimestampMillisecond;case QD.MICROSECOND:return Z.TimestampMicrosecond;case QD.NANOSECOND:return Z.TimestampNanosecond}return Z.Timestamp;case Z.Date:switch(e.unit){case ZD.DAY:return Z.DateDay;case ZD.MILLISECOND:return Z.DateMillisecond}return Z.Date;case Z.Interval:switch(e.unit){case $D.DAY_TIME:return Z.IntervalDayTime;case $D.YEAR_MONTH:return Z.IntervalYearMonth}return Z.Interval;case Z.Duration:switch(e.unit){case QD.SECOND:return Z.DurationSecond;case QD.MILLISECOND:return Z.DurationMillisecond;case QD.MICROSECOND:return Z.DurationMicrosecond;case QD.NANOSECOND:return Z.DurationNanosecond}return Z.Duration;case Z.Map:return Z.Map;case Z.List:return Z.List;case Z.Struct:return Z.Struct;case Z.Union:switch(e.mode){case YD.Dense:return Z.DenseUnion;case YD.Sparse:return Z.SparseUnion}return Z.Union;case Z.FixedSizeBinary:return Z.FixedSizeBinary;case Z.FixedSizeList:return Z.FixedSizeList;case Z.Dictionary:return Z.Dictionary}throw Error(`Unrecognized type '${Z[e.typeId]}'`)}cA.prototype.visitInt8=null,cA.prototype.visitInt16=null,cA.prototype.visitInt32=null,cA.prototype.visitInt64=null,cA.prototype.visitUint8=null,cA.prototype.visitUint16=null,cA.prototype.visitUint32=null,cA.prototype.visitUint64=null,cA.prototype.visitFloat16=null,cA.prototype.visitFloat32=null,cA.prototype.visitFloat64=null,cA.prototype.visitDateDay=null,cA.prototype.visitDateMillisecond=null,cA.prototype.visitTimestampSecond=null,cA.prototype.visitTimestampMillisecond=null,cA.prototype.visitTimestampMicrosecond=null,cA.prototype.visitTimestampNanosecond=null,cA.prototype.visitTimeSecond=null,cA.prototype.visitTimeMillisecond=null,cA.prototype.visitTimeMicrosecond=null,cA.prototype.visitTimeNanosecond=null,cA.prototype.visitDenseUnion=null,cA.prototype.visitSparseUnion=null,cA.prototype.visitIntervalDayTime=null,cA.prototype.visitIntervalYearMonth=null,cA.prototype.visitDuration=null,cA.prototype.visitDurationSecond=null,cA.prototype.visitDurationMillisecond=null,cA.prototype.visitDurationMicrosecond=null,cA.prototype.visitDurationNanosecond=null;var fA=new Float64Array(1),pA=new Uint32Array(fA.buffer);function mA(e){let t=(e&31744)>>10,n=(e&1023)/1024,r=(-1)**((e&32768)>>15);switch(t){case 31:return r*(n?NaN:1/0);case 0:return r*(n?6103515625e-14*n:0)}return r*2**(t-15)*(1+n)}function hA(e){if(e!==e)return 32256;fA[0]=e;let t=(pA[1]&2147483648)>>16&65535,n=pA[1]&2146435072,r=0;return n>=1089470464?pA[0]>0?n=31744:(n=(n&2080374784)>>16,r=(pA[1]&1048575)>>10):n<=1056964608?(r=1048576+(pA[1]&1048575),r=1048576+(r<<(n>>20)-998)>>21,n=0):(n=n-1056964608>>10,r=(pA[1]&1048575)+512>>10),t|n|r&65535}var gA=class extends cA{};function _A(e){return(t,n,r)=>{if(t.setValid(n,r!=null))return e(t,n,r)}}var vA=(e,t,n)=>{e[t]=Math.floor(n/864e5)},yA=(e,t,n,r)=>{if(n+1<t.length){let i=GO(t[n]),a=GO(t[n+1]);e.set(r.subarray(0,a-i),i)}},bA=({offset:e,values:t},n,r)=>{let i=e+n;r?t[i>>3]|=1<<i%8:t[i>>3]&=~(1<<i%8)},xA=({values:e},t,n)=>{e[t]=n},SA=({values:e},t,n)=>{e[t]=n},CA=({values:e},t,n)=>{e[t]=hA(n)},wA=(e,t,n)=>{switch(e.type.precision){case XD.HALF:return CA(e,t,n);case XD.SINGLE:case XD.DOUBLE:return SA(e,t,n)}},TA=({values:e},t,n)=>{vA(e,t,n.valueOf())},EA=({values:e},t,n)=>{e[t]=BigInt(n)},DA=({stride:e,values:t},n,r)=>{t.set(r.subarray(0,e),e*n)},OA=({values:e,valueOffsets:t},n,r)=>yA(e,t,n,r),kA=({values:e,valueOffsets:t},n,r)=>yA(e,t,n,sD(r)),AA=(e,t,n)=>{e.type.unit===ZD.DAY?TA(e,t,n):EA(e,t,n)},jA=({values:e},t,n)=>{e[t]=BigInt(n/1e3)},MA=({values:e},t,n)=>{e[t]=BigInt(n)},NA=({values:e},t,n)=>{e[t]=BigInt(n*1e3)},PA=({values:e},t,n)=>{e[t]=BigInt(n*1e6)},FA=(e,t,n)=>{switch(e.type.unit){case QD.SECOND:return jA(e,t,n);case QD.MILLISECOND:return MA(e,t,n);case QD.MICROSECOND:return NA(e,t,n);case QD.NANOSECOND:return PA(e,t,n)}},IA=({values:e},t,n)=>{e[t]=n},LA=({values:e},t,n)=>{e[t]=n},RA=({values:e},t,n)=>{e[t]=n},zA=({values:e},t,n)=>{e[t]=n},BA=(e,t,n)=>{switch(e.type.unit){case QD.SECOND:return IA(e,t,n);case QD.MILLISECOND:return LA(e,t,n);case QD.MICROSECOND:return RA(e,t,n);case QD.NANOSECOND:return zA(e,t,n)}},VA=({values:e,stride:t},n,r)=>{e.set(r.subarray(0,t),t*n)},HA=(e,t,n)=>{let r=e.children[0],i=e.valueOffsets,a=cj.getVisitFn(r);if(Array.isArray(n))for(let e=-1,o=i[t],s=i[t+1];o<s;)a(r,o++,n[++e]);else for(let e=-1,o=i[t],s=i[t+1];o<s;)a(r,o++,n.get(++e))},UA=(e,t,n)=>{let r=e.children[0],{valueOffsets:i}=e,a=cj.getVisitFn(r),{[t]:o,[t+1]:s}=i,c=n instanceof Map?n.entries():Object.entries(n);for(let e of c)if(a(r,o,e),++o>=s)break},WA=(e,t)=>(n,r,i,a)=>r&&n(r,e,t[a]),GA=(e,t)=>(n,r,i,a)=>r&&n(r,e,t.get(a)),KA=(e,t)=>(n,r,i,a)=>r&&n(r,e,t.get(i.name)),qA=(e,t)=>(n,r,i,a)=>r&&n(r,e,t[i.name]),JA=(e,t,n)=>{let r=e.type.children.map(e=>cj.getVisitFn(e.type)),i=n instanceof Map?KA(t,n):n instanceof aN?GA(t,n):Array.isArray(n)?WA(t,n):qA(t,n);e.type.children.forEach((t,n)=>i(r[n],e.children[n],t,n))},YA=(e,t,n)=>{e.type.mode===YD.Dense?XA(e,t,n):ZA(e,t,n)},XA=(e,t,n)=>{let r=e.type.typeIdToChildIndex[e.typeIds[t]],i=e.children[r];cj.visit(i,e.valueOffsets[t],n)},ZA=(e,t,n)=>{let r=e.type.typeIdToChildIndex[e.typeIds[t]],i=e.children[r];cj.visit(i,t,n)},QA=(e,t,n)=>{var r;(r=e.dictionary)==null||r.set(e.values[t],n)},$A=(e,t,n)=>{e.type.unit===$D.DAY_TIME?ej(e,t,n):tj(e,t,n)},ej=({values:e},t,n)=>{e.set(n.subarray(0,2),2*t)},tj=({values:e},t,n)=>{e[t]=n[0]*12+n[1]%12},nj=({values:e},t,n)=>{e[t]=n},rj=({values:e},t,n)=>{e[t]=n},ij=({values:e},t,n)=>{e[t]=n},aj=({values:e},t,n)=>{e[t]=n},oj=(e,t,n)=>{switch(e.type.unit){case QD.SECOND:return nj(e,t,n);case QD.MILLISECOND:return rj(e,t,n);case QD.MICROSECOND:return ij(e,t,n);case QD.NANOSECOND:return aj(e,t,n)}},sj=(e,t,n)=>{let{stride:r}=e,i=e.children[0],a=cj.getVisitFn(i);if(Array.isArray(n))for(let e=-1,o=t*r;++e<r;)a(i,o+e,n[e]);else for(let e=-1,o=t*r;++e<r;)a(i,o+e,n.get(e))};gA.prototype.visitBool=_A(bA),gA.prototype.visitInt=_A(xA),gA.prototype.visitInt8=_A(xA),gA.prototype.visitInt16=_A(xA),gA.prototype.visitInt32=_A(xA),gA.prototype.visitInt64=_A(xA),gA.prototype.visitUint8=_A(xA),gA.prototype.visitUint16=_A(xA),gA.prototype.visitUint32=_A(xA),gA.prototype.visitUint64=_A(xA),gA.prototype.visitFloat=_A(wA),gA.prototype.visitFloat16=_A(CA),gA.prototype.visitFloat32=_A(SA),gA.prototype.visitFloat64=_A(SA),gA.prototype.visitUtf8=_A(kA),gA.prototype.visitLargeUtf8=_A(kA),gA.prototype.visitBinary=_A(OA),gA.prototype.visitLargeBinary=_A(OA),gA.prototype.visitFixedSizeBinary=_A(DA),gA.prototype.visitDate=_A(AA),gA.prototype.visitDateDay=_A(TA),gA.prototype.visitDateMillisecond=_A(EA),gA.prototype.visitTimestamp=_A(FA),gA.prototype.visitTimestampSecond=_A(jA),gA.prototype.visitTimestampMillisecond=_A(MA),gA.prototype.visitTimestampMicrosecond=_A(NA),gA.prototype.visitTimestampNanosecond=_A(PA),gA.prototype.visitTime=_A(BA),gA.prototype.visitTimeSecond=_A(IA),gA.prototype.visitTimeMillisecond=_A(LA),gA.prototype.visitTimeMicrosecond=_A(RA),gA.prototype.visitTimeNanosecond=_A(zA),gA.prototype.visitDecimal=_A(VA),gA.prototype.visitList=_A(HA),gA.prototype.visitStruct=_A(JA),gA.prototype.visitUnion=_A(YA),gA.prototype.visitDenseUnion=_A(XA),gA.prototype.visitSparseUnion=_A(ZA),gA.prototype.visitDictionary=_A(QA),gA.prototype.visitInterval=_A($A),gA.prototype.visitIntervalDayTime=_A(ej),gA.prototype.visitIntervalYearMonth=_A(tj),gA.prototype.visitDuration=_A(oj),gA.prototype.visitDurationSecond=_A(nj),gA.prototype.visitDurationMillisecond=_A(rj),gA.prototype.visitDurationMicrosecond=_A(ij),gA.prototype.visitDurationNanosecond=_A(aj),gA.prototype.visitFixedSizeList=_A(sj),gA.prototype.visitMap=_A(UA);var cj=new gA,lj=Symbol.for(`parent`),uj=Symbol.for(`rowIndex`),dj=class{constructor(e,t){return this[lj]=e,this[uj]=t,new Proxy(this,new pj)}toArray(){return Object.values(this.toJSON())}toJSON(){let e=this[uj],t=this[lj],n=t.type.children,r={};for(let i=-1,a=n.length;++i<a;)r[n[i].name]=iM.visit(t.children[i],e);return r}toString(){return`{${[...this].map(([e,t])=>`${WO(e)}: ${WO(t)}`).join(`, `)}}`}[Symbol.for(`nodejs.util.inspect.custom`)](){return this.toString()}[Symbol.iterator](){return new fj(this[lj],this[uj])}},fj=class{constructor(e,t){this.childIndex=0,this.children=e.children,this.rowIndex=t,this.childFields=e.type.children,this.numChildren=this.childFields.length}[Symbol.iterator](){return this}next(){let e=this.childIndex;return e<this.numChildren?(this.childIndex=e+1,{done:!1,value:[this.childFields[e].name,iM.visit(this.children[e],this.rowIndex)]}):{done:!0,value:null}}};Object.defineProperties(dj.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:`Row`},[lj]:{writable:!0,enumerable:!1,configurable:!1,value:null},[uj]:{writable:!0,enumerable:!1,configurable:!1,value:-1}});var pj=class{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(e){return e[lj].type.children.map(e=>e.name)}has(e,t){return e[lj].type.children.findIndex(e=>e.name===t)!==-1}getOwnPropertyDescriptor(e,t){if(e[lj].type.children.findIndex(e=>e.name===t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];let n=e[lj].type.children.findIndex(e=>e.name===t);if(n!==-1){let r=iM.visit(e[lj].children[n],e[uj]);return Reflect.set(e,t,r),r}}set(e,t,n){let r=e[lj].type.children.findIndex(e=>e.name===t);return r===-1?Reflect.has(e,t)||typeof t==`symbol`?Reflect.set(e,t,n):!1:(cj.visit(e[lj].children[r],e[uj],n),Reflect.set(e,t,n))}},mj=class extends cA{};function hj(e){return(t,n)=>t.getValid(n)?e(t,n):null}var gj=(e,t)=>864e5*e[t],_j=(e,t)=>null,vj=(e,t,n)=>{if(n+1>=t.length)return null;let r=GO(t[n]),i=GO(t[n+1]);return e.subarray(r,i)},yj=({offset:e,values:t},n)=>{let r=e+n;return(t[r>>3]&1<<r%8)!=0},bj=({values:e},t)=>gj(e,t),xj=({values:e},t)=>GO(e[t]),Sj=({stride:e,values:t},n)=>t[e*n],Cj=({stride:e,values:t},n)=>mA(t[e*n]),wj=({values:e},t)=>e[t],Tj=({stride:e,values:t},n)=>t.subarray(e*n,e*(n+1)),Ej=({values:e,valueOffsets:t},n)=>vj(e,t,n),Dj=({values:e,valueOffsets:t},n)=>{let r=vj(e,t,n);return r===null?null:aD(r)},Oj=({values:e},t)=>e[t],kj=({type:e,values:t},n)=>e.precision===XD.HALF?mA(t[n]):t[n],Aj=(e,t)=>e.type.unit===ZD.DAY?bj(e,t):xj(e,t),jj=({values:e},t)=>1e3*GO(e[t]),Mj=({values:e},t)=>GO(e[t]),Nj=({values:e},t)=>KO(e[t],BigInt(1e3)),Pj=({values:e},t)=>KO(e[t],BigInt(1e6)),Fj=(e,t)=>{switch(e.type.unit){case QD.SECOND:return jj(e,t);case QD.MILLISECOND:return Mj(e,t);case QD.MICROSECOND:return Nj(e,t);case QD.NANOSECOND:return Pj(e,t)}},Ij=({values:e},t)=>e[t],Lj=({values:e},t)=>e[t],Rj=({values:e},t)=>e[t],zj=({values:e},t)=>e[t],Bj=(e,t)=>{switch(e.type.unit){case QD.SECOND:return Ij(e,t);case QD.MILLISECOND:return Lj(e,t);case QD.MICROSECOND:return Rj(e,t);case QD.NANOSECOND:return zj(e,t)}},Vj=({values:e,stride:t},n)=>rk.decimal(e.subarray(t*n,t*(n+1))),Hj=(e,t)=>{let{valueOffsets:n,stride:r,children:i}=e,{[t*r]:a,[t*r+1]:o}=n;return new aN([i[0].slice(a,o-a)])},Uj=(e,t)=>{let{valueOffsets:n,children:r}=e,{[t]:i,[t+1]:a}=n,o=r[0];return new lM(o.slice(i,a-i))},Wj=(e,t)=>new dj(e,t),Gj=(e,t)=>e.type.mode===YD.Dense?Kj(e,t):qj(e,t),Kj=(e,t)=>{let n=e.type.typeIdToChildIndex[e.typeIds[t]],r=e.children[n];return iM.visit(r,e.valueOffsets[t])},qj=(e,t)=>{let n=e.type.typeIdToChildIndex[e.typeIds[t]],r=e.children[n];return iM.visit(r,t)},Jj=(e,t)=>e.dictionary?.get(e.values[t]),Yj=(e,t)=>e.type.unit===$D.DAY_TIME?Xj(e,t):Zj(e,t),Xj=({values:e},t)=>e.subarray(2*t,2*(t+1)),Zj=({values:e},t)=>{let n=e[t],r=new Int32Array(2);return r[0]=Math.trunc(n/12),r[1]=Math.trunc(n%12),r},Qj=({values:e},t)=>e[t],$j=({values:e},t)=>e[t],eM=({values:e},t)=>e[t],tM=({values:e},t)=>e[t],nM=(e,t)=>{switch(e.type.unit){case QD.SECOND:return Qj(e,t);case QD.MILLISECOND:return $j(e,t);case QD.MICROSECOND:return eM(e,t);case QD.NANOSECOND:return tM(e,t)}},rM=(e,t)=>{let{stride:n,children:r}=e;return new aN([r[0].slice(t*n,n)])};mj.prototype.visitNull=hj(_j),mj.prototype.visitBool=hj(yj),mj.prototype.visitInt=hj(Oj),mj.prototype.visitInt8=hj(Sj),mj.prototype.visitInt16=hj(Sj),mj.prototype.visitInt32=hj(Sj),mj.prototype.visitInt64=hj(wj),mj.prototype.visitUint8=hj(Sj),mj.prototype.visitUint16=hj(Sj),mj.prototype.visitUint32=hj(Sj),mj.prototype.visitUint64=hj(wj),mj.prototype.visitFloat=hj(kj),mj.prototype.visitFloat16=hj(Cj),mj.prototype.visitFloat32=hj(Sj),mj.prototype.visitFloat64=hj(Sj),mj.prototype.visitUtf8=hj(Dj),mj.prototype.visitLargeUtf8=hj(Dj),mj.prototype.visitBinary=hj(Ej),mj.prototype.visitLargeBinary=hj(Ej),mj.prototype.visitFixedSizeBinary=hj(Tj),mj.prototype.visitDate=hj(Aj),mj.prototype.visitDateDay=hj(bj),mj.prototype.visitDateMillisecond=hj(xj),mj.prototype.visitTimestamp=hj(Fj),mj.prototype.visitTimestampSecond=hj(jj),mj.prototype.visitTimestampMillisecond=hj(Mj),mj.prototype.visitTimestampMicrosecond=hj(Nj),mj.prototype.visitTimestampNanosecond=hj(Pj),mj.prototype.visitTime=hj(Bj),mj.prototype.visitTimeSecond=hj(Ij),mj.prototype.visitTimeMillisecond=hj(Lj),mj.prototype.visitTimeMicrosecond=hj(Rj),mj.prototype.visitTimeNanosecond=hj(zj),mj.prototype.visitDecimal=hj(Vj),mj.prototype.visitList=hj(Hj),mj.prototype.visitStruct=hj(Wj),mj.prototype.visitUnion=hj(Gj),mj.prototype.visitDenseUnion=hj(Kj),mj.prototype.visitSparseUnion=hj(qj),mj.prototype.visitDictionary=hj(Jj),mj.prototype.visitInterval=hj(Yj),mj.prototype.visitIntervalDayTime=hj(Xj),mj.prototype.visitIntervalYearMonth=hj(Zj),mj.prototype.visitDuration=hj(nM),mj.prototype.visitDurationSecond=hj(Qj),mj.prototype.visitDurationMillisecond=hj($j),mj.prototype.visitDurationMicrosecond=hj(eM),mj.prototype.visitDurationNanosecond=hj(tM),mj.prototype.visitFixedSizeList=hj(rM),mj.prototype.visitMap=hj(Uj);var iM=new mj,aM=Symbol.for(`keys`),oM=Symbol.for(`vals`),sM=Symbol.for(`kKeysAsStrings`),cM=Symbol.for(`_kKeysAsStrings`),lM=class{constructor(e){return this[aM]=new aN([e.children[0]]).memoize(),this[oM]=e.children[1],new Proxy(this,new dM)}get[sM](){return this[cM]||(this[cM]=Array.from(this[aM].toArray(),String))}[Symbol.iterator](){return new uM(this[aM],this[oM])}get size(){return this[aM].length}toArray(){return Object.values(this.toJSON())}toJSON(){let e=this[aM],t=this[oM],n={};for(let r=-1,i=e.length;++r<i;)n[e.get(r)]=iM.visit(t,r);return n}toString(){return`{${[...this].map(([e,t])=>`${WO(e)}: ${WO(t)}`).join(`, `)}}`}[Symbol.for(`nodejs.util.inspect.custom`)](){return this.toString()}},uM=class{constructor(e,t){this.keys=e,this.vals=t,this.keyIndex=0,this.numKeys=e.length}[Symbol.iterator](){return this}next(){let e=this.keyIndex;return e===this.numKeys?{done:!0,value:null}:(this.keyIndex++,{done:!1,value:[this.keys.get(e),iM.visit(this.vals,e)]})}},dM=class{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(e){return e[sM]}has(e,t){return e[sM].includes(t)}getOwnPropertyDescriptor(e,t){if(e[sM].indexOf(t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];let n=e[sM].indexOf(t);if(n!==-1){let r=iM.visit(Reflect.get(e,oM),n);return Reflect.set(e,t,r),r}}set(e,t,n){let r=e[sM].indexOf(t);return r===-1?Reflect.has(e,t)?Reflect.set(e,t,n):!1:(cj.visit(Reflect.get(e,oM),r,n),Reflect.set(e,t,n))}};Object.defineProperties(lM.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:`Row`},[aM]:{writable:!0,enumerable:!1,configurable:!1,value:null},[oM]:{writable:!0,enumerable:!1,configurable:!1,value:null},[cM]:{writable:!0,enumerable:!1,configurable:!1,value:null}});var fM;function pM(e,t,n,r){let{length:i=0}=e,a=typeof t==`number`?t:0,o=typeof n==`number`?n:i;return a<0&&(a=(a%i+i)%i),o<0&&(o=(o%i+i)%i),o<a&&(fM=a,a=o,o=fM),o>i&&(o=i),r?r(e,a,o):[a,o]}var mM=(e,t)=>e<0?t+e:e,hM=e=>e!==e;function gM(e){if(typeof e!=`object`||!e)return hM(e)?hM:t=>t===e;if(e instanceof Date){let t=e.valueOf();return e=>e instanceof Date?e.valueOf()===t:!1}return ArrayBuffer.isView(e)?t=>t?zD(e,t):!1:e instanceof Map?vM(e):Array.isArray(e)?_M(e):e instanceof aN?yM(e):bM(e,!0)}function _M(e){let t=[];for(let n=-1,r=e.length;++n<r;)t[n]=gM(e[n]);return xM(t)}function vM(e){let t=-1,n=[];for(let r of e.values())n[++t]=gM(r);return xM(n)}function yM(e){let t=[];for(let n=-1,r=e.length;++n<r;)t[n]=gM(e.get(n));return xM(t)}function bM(e,t=!1){let n=Object.keys(e);if(!t&&n.length===0)return()=>!1;let r=[];for(let t=-1,i=n.length;++t<i;)r[t]=gM(e[n[t]]);return xM(r,n)}function xM(e,t){return n=>{if(!n||typeof n!=`object`)return!1;switch(n.constructor){case Array:return SM(e,n);case Map:return wM(e,n,n.keys());case lM:case dj:case Object:case void 0:return wM(e,n,t||Object.keys(n))}return n instanceof aN?CM(e,n):!1}}function SM(e,t){let n=e.length;if(t.length!==n)return!1;for(let r=-1;++r<n;)if(!e[r](t[r]))return!1;return!0}function CM(e,t){let n=e.length;if(t.length!==n)return!1;for(let r=-1;++r<n;)if(!e[r](t.get(r)))return!1;return!0}function wM(e,t,n){let r=n[Symbol.iterator](),i=t instanceof Map?t.keys():Object.keys(t)[Symbol.iterator](),a=t instanceof Map?t.values():Object.values(t)[Symbol.iterator](),o=0,s=e.length,c=a.next(),l=r.next(),u=i.next();for(;o<s&&!l.done&&!u.done&&!c.done&&!(l.value!==u.value||!e[o](c.value));++o,l=r.next(),u=i.next(),c=a.next());return o===s&&l.done&&u.done&&c.done?!0:(r.return&&r.return(),i.return&&i.return(),a.return&&a.return(),!1)}function TM(e,t,n,r){return(n&1<<r)!=0}function EM(e,t,n,r){return(n&1<<r)>>r}function DM(e,t,n){let r=n.byteLength+7&-8;if(e>0||n.byteLength<r){let i=new Uint8Array(r);return i.set(e%8==0?n.subarray(e>>3):OM(new kM(n,e,t,null,TM)).subarray(0,r)),i}return n}function OM(e){let t=[],n=0,r=0,i=0;for(let a of e)a&&(i|=1<<r),++r===8&&(t[n++]=i,i=r=0);(n===0||r>0)&&(t[n++]=i);let a=new Uint8Array(t.length+7&-8);return a.set(t),a}var kM=class{constructor(e,t,n,r,i){this.bytes=e,this.length=n,this.context=r,this.get=i,this.bit=t%8,this.byteIndex=t>>3,this.byte=e[this.byteIndex++],this.index=0}next(){return this.index<this.length?(this.bit===8&&(this.bit=0,this.byte=this.bytes[this.byteIndex++]),{value:this.get(this.context,this.index++,this.byte,this.bit++)}):{done:!0,value:null}}[Symbol.iterator](){return this}};function AM(e,t,n){if(n-t<=0)return 0;if(n-t<8){let r=0;for(let i of new kM(e,t,n-t,e,EM))r+=i;return r}let r=n>>3<<3,i=t+(t%8==0?0:8-t%8);return AM(e,t,i)+AM(e,r,n)+jM(e,i>>3,r-i>>3)}function jM(e,t,n){let r=0,i=Math.trunc(t),a=new DataView(e.buffer,e.byteOffset,e.byteLength),o=n===void 0?e.byteLength:i+n;for(;o-i>=4;)r+=MM(a.getUint32(i)),i+=4;for(;o-i>=2;)r+=MM(a.getUint16(i)),i+=2;for(;o-i>=1;)r+=MM(a.getUint8(i)),i+=1;return r}function MM(e){let t=Math.trunc(e);return t-=t>>>1&1431655765,t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}var NM=class e{get typeId(){return this.type.typeId}get ArrayType(){return this.type.ArrayType}get buffers(){return[this.valueOffsets,this.values,this.nullBitmap,this.typeIds]}get nullable(){if(this._nullCount!==0){let{type:e}=this;return Ek.isSparseUnion(e)||Ek.isDenseUnion(e)?this.children.some(e=>e.nullable):this.nullBitmap&&this.nullBitmap.byteLength>0}return!0}get byteLength(){let e=0,{valueOffsets:t,values:n,nullBitmap:r,typeIds:i}=this;return t&&(e+=t.byteLength),n&&(e+=n.byteLength),r&&(e+=r.byteLength),i&&(e+=i.byteLength),this.children.reduce((e,t)=>e+t.byteLength,e)}get nullCount(){if(Ek.isUnion(this.type))return this.children.reduce((e,t)=>e+t.nullCount,0);let e=this._nullCount,t;return e<=-1&&(t=this.nullBitmap)&&(this._nullCount=e=t.length===0?0:this.length-AM(t,this.offset,this.offset+this.length)),e}constructor(t,n,r,i,a,o=[],s){this.type=t,this.children=o,this.dictionary=s,this.offset=Math.floor(Math.max(n||0,0)),this.length=Math.floor(Math.max(r||0,0)),this._nullCount=Math.floor(Math.max(i||0,-1));let c;a instanceof e?(this.stride=a.stride,this.values=a.values,this.typeIds=a.typeIds,this.nullBitmap=a.nullBitmap,this.valueOffsets=a.valueOffsets):(this.stride=sA(t),a&&((c=a[0])&&(this.valueOffsets=c),(c=a[1])&&(this.values=c),(c=a[2])&&(this.nullBitmap=c),(c=a[3])&&(this.typeIds=c)))}getValid(e){let{type:t}=this;if(Ek.isUnion(t)){let n=t,r=this.children[n.typeIdToChildIndex[this.typeIds[e]]],i=n.mode===YD.Dense?this.valueOffsets[e]:e;return r.getValid(i)}if(this.nullable&&this.nullCount>0){let t=this.offset+e;return(this.nullBitmap[t>>3]&1<<t%8)!=0}return!0}setValid(e,t){let n,{type:r}=this;if(Ek.isUnion(r)){let i=r,a=this.children[i.typeIdToChildIndex[this.typeIds[e]]],o=i.mode===YD.Dense?this.valueOffsets[e]:e;n=a.getValid(o),a.setValid(o,t)}else{let{nullBitmap:r}=this,{offset:i,length:a}=this,o=i+e,s=1<<o%8,c=o>>3;(!r||r.byteLength<=c)&&(r=new Uint8Array((i+a+63&-64)>>3).fill(255),this.nullCount>0?(r.set(DM(i,a,this.nullBitmap),0),Object.assign(this,{nullBitmap:r})):Object.assign(this,{nullBitmap:r,_nullCount:0}));let l=r[c];n=(l&s)!==0,r[c]=t?l|s:l&~s}return n!==!!t&&(this._nullCount=this.nullCount+(t?-1:1)),t}clone(t=this.type,n=this.offset,r=this.length,i=this._nullCount,a=this,o=this.children){return new e(t,n,r,i,a,o,this.dictionary)}slice(e,t){let{stride:n,typeId:r,children:i}=this,a=(this._nullCount===0)-1,o=r===16?n:1,s=this._sliceBuffers(e,t,n,r);return this.clone(this.type,this.offset+e,t,a,s,i.length===0||this.valueOffsets?i:this._sliceChildren(i,o*e,o*t))}_changeLengthAndBackfillNullBitmap(e){if(this.typeId===Z.Null)return this.clone(this.type,0,e,0);let{length:t,nullCount:n}=this,r=new Uint8Array((e+63&-64)>>3).fill(255,0,t>>3);r[t>>3]=(1<<t-(t&-8))-1,n>0&&r.set(DM(this.offset,t,this.nullBitmap),0);let i=this.buffers;return i[HO.VALIDITY]=r,this.clone(this.type,0,e,n+(e-t),i)}_sliceBuffers(e,t,n,r){let i,{buffers:a}=this;return(i=a[HO.TYPE])&&(a[HO.TYPE]=i.subarray(e,e+t)),(i=a[HO.OFFSET])&&(a[HO.OFFSET]=i.subarray(e,e+t+1))||(i=a[HO.DATA])&&(a[HO.DATA]=r===6?i:i.subarray(n*e,n*(e+t))),a}_sliceChildren(e,t,n){return e.map(e=>e.slice(t,n))}};NM.prototype.children=Object.freeze([]);var PM=new class e extends cA{visit(e){return this.getVisitFn(e.type).call(this,e)}visitNull(e){let{type:t,offset:n=0,length:r=0}=e;return new NM(t,n,r,r)}visitBool(e){let{type:t,offset:n=0}=e,r=MD(e.nullBitmap),i=kD(t.ArrayType,e.data),{length:a=i.length>>3,nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,i,r])}visitInt(e){let{type:t,offset:n=0}=e,r=MD(e.nullBitmap),i=kD(t.ArrayType,e.data),{length:a=i.length,nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,i,r])}visitFloat(e){let{type:t,offset:n=0}=e,r=MD(e.nullBitmap),i=kD(t.ArrayType,e.data),{length:a=i.length,nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,i,r])}visitUtf8(e){let{type:t,offset:n=0}=e,r=MD(e.data),i=MD(e.nullBitmap),a=AD(e.valueOffsets),{length:o=a.length-1,nullCount:s=e.nullBitmap?-1:0}=e;return new NM(t,n,o,s,[a,r,i])}visitLargeUtf8(e){let{type:t,offset:n=0}=e,r=MD(e.data),i=MD(e.nullBitmap),a=jD(e.valueOffsets),{length:o=a.length-1,nullCount:s=e.nullBitmap?-1:0}=e;return new NM(t,n,o,s,[a,r,i])}visitBinary(e){let{type:t,offset:n=0}=e,r=MD(e.data),i=MD(e.nullBitmap),a=AD(e.valueOffsets),{length:o=a.length-1,nullCount:s=e.nullBitmap?-1:0}=e;return new NM(t,n,o,s,[a,r,i])}visitLargeBinary(e){let{type:t,offset:n=0}=e,r=MD(e.data),i=MD(e.nullBitmap),a=jD(e.valueOffsets),{length:o=a.length-1,nullCount:s=e.nullBitmap?-1:0}=e;return new NM(t,n,o,s,[a,r,i])}visitFixedSizeBinary(e){let{type:t,offset:n=0}=e,r=MD(e.nullBitmap),i=kD(t.ArrayType,e.data),{length:a=i.length/sA(t),nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,i,r])}visitDate(e){let{type:t,offset:n=0}=e,r=MD(e.nullBitmap),i=kD(t.ArrayType,e.data),{length:a=i.length/sA(t),nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,i,r])}visitTimestamp(e){let{type:t,offset:n=0}=e,r=MD(e.nullBitmap),i=kD(t.ArrayType,e.data),{length:a=i.length/sA(t),nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,i,r])}visitTime(e){let{type:t,offset:n=0}=e,r=MD(e.nullBitmap),i=kD(t.ArrayType,e.data),{length:a=i.length/sA(t),nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,i,r])}visitDecimal(e){let{type:t,offset:n=0}=e,r=MD(e.nullBitmap),i=kD(t.ArrayType,e.data),{length:a=i.length/sA(t),nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,i,r])}visitList(e){let{type:t,offset:n=0,child:r}=e,i=MD(e.nullBitmap),a=AD(e.valueOffsets),{length:o=a.length-1,nullCount:s=e.nullBitmap?-1:0}=e;return new NM(t,n,o,s,[a,void 0,i],[r])}visitStruct(e){let{type:t,offset:n=0,children:r=[]}=e,i=MD(e.nullBitmap),{length:a=r.reduce((e,{length:t})=>Math.max(e,t),0),nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,void 0,i],r)}visitUnion(e){let{type:t,offset:n=0,children:r=[]}=e,i=kD(t.ArrayType,e.typeIds),{length:a=i.length,nullCount:o=-1}=e;return Ek.isSparseUnion(t)?new NM(t,n,a,o,[void 0,void 0,void 0,i],r):new NM(t,n,a,o,[AD(e.valueOffsets),void 0,void 0,i],r)}visitDictionary(t){let{type:n,offset:r=0}=t,i=MD(t.nullBitmap),a=kD(n.indices.ArrayType,t.data),{dictionary:o=new aN([new e().visit({type:n.dictionary})])}=t,{length:s=a.length,nullCount:c=t.nullBitmap?-1:0}=t;return new NM(n,r,s,c,[void 0,a,i],[],o)}visitInterval(e){let{type:t,offset:n=0}=e,r=MD(e.nullBitmap),i=kD(t.ArrayType,e.data),{length:a=i.length/sA(t),nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,i,r])}visitDuration(e){let{type:t,offset:n=0}=e,r=MD(e.nullBitmap),i=kD(t.ArrayType,e.data),{length:a=i.length,nullCount:o=e.nullBitmap?-1:0}=e;return new NM(t,n,a,o,[void 0,i,r])}visitFixedSizeList(t){let{type:n,offset:r=0,child:i=new e().visit({type:n.valueType})}=t,a=MD(t.nullBitmap),{length:o=i.length/sA(n),nullCount:s=t.nullBitmap?-1:0}=t;return new NM(n,r,o,s,[void 0,void 0,a],[i])}visitMap(t){let{type:n,offset:r=0,child:i=new e().visit({type:n.childType})}=t,a=MD(t.nullBitmap),o=AD(t.valueOffsets),{length:s=o.length-1,nullCount:c=t.nullBitmap?-1:0}=t;return new NM(n,r,s,c,[o,void 0,a],[i])}};function FM(e){return PM.visit(e)}var IM=class{constructor(e=0,t){this.numChunks=e,this.getChunkIterator=t,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndex<this.numChunks;){let e=this.chunkIterator.next();if(!e.done)return e;++this.chunkIndex<this.numChunks&&(this.chunkIterator=this.getChunkIterator(this.chunkIndex))}return{done:!0,value:null}}[Symbol.iterator](){return this}};function LM(e){return e.some(e=>e.nullable)}function RM(e){return e.reduce((e,t)=>e+t.nullCount,0)}function zM(e){return e.reduce((e,t,n)=>(e[n+1]=e[n]+t.length,e),new Uint32Array(e.length+1))}function BM(e,t,n,r){let i=[];for(let a=-1,o=e.length;++a<o;){let o=e[a],s=t[a],{length:c}=o;if(s>=r)break;if(n>=s+c)continue;if(s>=n&&s+c<=r){i.push(o);continue}let l=Math.max(0,n-s),u=Math.min(r-s,c);i.push(o.slice(l,u-l))}return i.length===0&&i.push(e[0].slice(0,0)),i}function VM(e,t,n,r){let i=0,a=0,o=t.length-1;do{if(i>=o-1)return n<t[o]?r(e,i,n-t[i]):null;a=i+Math.trunc((o-i)*.5),n<t[a]?o=a:i=a}while(i<o)}function HM(e,t){return e.getValid(t)}function UM(e){function t(t,n,r){return e(t[n],r)}return function(e){let n=this.data;return VM(n,this._offsets,e,t)}}function WM(e){let t;function n(n,r,i){return e(n[r],i,t)}return function(e,r){let i=this.data;t=r;let a=VM(i,this._offsets,e,n);return t=void 0,a}}function GM(e){let t;function n(n,r,i){let a=i,o=0,s=0;for(let i=r-1,c=n.length;++i<c;){let r=n[i];if(~(o=e(r,t,a)))return s+o;a=0,s+=r.length}return-1}return function(e,r){t=e;let i=this.data,a=typeof r==`number`?VM(i,this._offsets,r,n):n(i,0,0);return t=void 0,a}}var KM=class extends cA{};function qM(e,t){return t===null&&e.length>0?0:-1}function JM(e,t){let{nullBitmap:n}=e;if(!n||e.nullCount<=0)return-1;let r=0;for(let i of new kM(n,e.offset+(t||0),e.length,n,TM)){if(!i)return r;++r}return-1}function YM(e,t,n){if(t===void 0)return-1;if(t===null)switch(e.typeId){case Z.Union:break;case Z.Dictionary:break;default:return JM(e,n)}let r=iM.getVisitFn(e),i=gM(t);for(let t=(n||0)-1,a=e.length;++t<a;)if(i(r(e,t)))return t;return-1}function XM(e,t,n){let r=iM.getVisitFn(e),i=gM(t);for(let t=(n||0)-1,a=e.length;++t<a;)if(i(r(e,t)))return t;return-1}KM.prototype.visitNull=qM,KM.prototype.visitBool=YM,KM.prototype.visitInt=YM,KM.prototype.visitInt8=YM,KM.prototype.visitInt16=YM,KM.prototype.visitInt32=YM,KM.prototype.visitInt64=YM,KM.prototype.visitUint8=YM,KM.prototype.visitUint16=YM,KM.prototype.visitUint32=YM,KM.prototype.visitUint64=YM,KM.prototype.visitFloat=YM,KM.prototype.visitFloat16=YM,KM.prototype.visitFloat32=YM,KM.prototype.visitFloat64=YM,KM.prototype.visitUtf8=YM,KM.prototype.visitLargeUtf8=YM,KM.prototype.visitBinary=YM,KM.prototype.visitLargeBinary=YM,KM.prototype.visitFixedSizeBinary=YM,KM.prototype.visitDate=YM,KM.prototype.visitDateDay=YM,KM.prototype.visitDateMillisecond=YM,KM.prototype.visitTimestamp=YM,KM.prototype.visitTimestampSecond=YM,KM.prototype.visitTimestampMillisecond=YM,KM.prototype.visitTimestampMicrosecond=YM,KM.prototype.visitTimestampNanosecond=YM,KM.prototype.visitTime=YM,KM.prototype.visitTimeSecond=YM,KM.prototype.visitTimeMillisecond=YM,KM.prototype.visitTimeMicrosecond=YM,KM.prototype.visitTimeNanosecond=YM,KM.prototype.visitDecimal=YM,KM.prototype.visitList=YM,KM.prototype.visitStruct=YM,KM.prototype.visitUnion=YM,KM.prototype.visitDenseUnion=XM,KM.prototype.visitSparseUnion=XM,KM.prototype.visitDictionary=YM,KM.prototype.visitInterval=YM,KM.prototype.visitIntervalDayTime=YM,KM.prototype.visitIntervalYearMonth=YM,KM.prototype.visitDuration=YM,KM.prototype.visitDurationSecond=YM,KM.prototype.visitDurationMillisecond=YM,KM.prototype.visitDurationMicrosecond=YM,KM.prototype.visitDurationNanosecond=YM,KM.prototype.visitFixedSizeList=YM,KM.prototype.visitMap=YM;var ZM=new KM,QM=class extends cA{};function $M(e){let{type:t}=e;if(e.nullCount===0&&e.stride===1&&(Ek.isInt(t)&&t.bitWidth!==64||Ek.isTime(t)&&t.bitWidth!==64||Ek.isFloat(t)&&t.precision!==XD.HALF))return new IM(e.data.length,t=>{let n=e.data[t];return n.values.subarray(0,n.length)[Symbol.iterator]()});let n=0;return new IM(e.data.length,t=>{let r=e.data[t].length,i=e.slice(n,n+r);return n+=r,new eN(i)})}var eN=class{constructor(e){this.vector=e,this.index=0}next(){return this.index<this.vector.length?{value:this.vector.get(this.index++)}:{done:!0,value:null}}[Symbol.iterator](){return this}};QM.prototype.visitNull=$M,QM.prototype.visitBool=$M,QM.prototype.visitInt=$M,QM.prototype.visitInt8=$M,QM.prototype.visitInt16=$M,QM.prototype.visitInt32=$M,QM.prototype.visitInt64=$M,QM.prototype.visitUint8=$M,QM.prototype.visitUint16=$M,QM.prototype.visitUint32=$M,QM.prototype.visitUint64=$M,QM.prototype.visitFloat=$M,QM.prototype.visitFloat16=$M,QM.prototype.visitFloat32=$M,QM.prototype.visitFloat64=$M,QM.prototype.visitUtf8=$M,QM.prototype.visitLargeUtf8=$M,QM.prototype.visitBinary=$M,QM.prototype.visitLargeBinary=$M,QM.prototype.visitFixedSizeBinary=$M,QM.prototype.visitDate=$M,QM.prototype.visitDateDay=$M,QM.prototype.visitDateMillisecond=$M,QM.prototype.visitTimestamp=$M,QM.prototype.visitTimestampSecond=$M,QM.prototype.visitTimestampMillisecond=$M,QM.prototype.visitTimestampMicrosecond=$M,QM.prototype.visitTimestampNanosecond=$M,QM.prototype.visitTime=$M,QM.prototype.visitTimeSecond=$M,QM.prototype.visitTimeMillisecond=$M,QM.prototype.visitTimeMicrosecond=$M,QM.prototype.visitTimeNanosecond=$M,QM.prototype.visitDecimal=$M,QM.prototype.visitList=$M,QM.prototype.visitStruct=$M,QM.prototype.visitUnion=$M,QM.prototype.visitDenseUnion=$M,QM.prototype.visitSparseUnion=$M,QM.prototype.visitDictionary=$M,QM.prototype.visitInterval=$M,QM.prototype.visitIntervalDayTime=$M,QM.prototype.visitIntervalYearMonth=$M,QM.prototype.visitDuration=$M,QM.prototype.visitDurationSecond=$M,QM.prototype.visitDurationMillisecond=$M,QM.prototype.visitDurationMicrosecond=$M,QM.prototype.visitDurationNanosecond=$M,QM.prototype.visitFixedSizeList=$M,QM.prototype.visitMap=$M;var tN=new QM,nN,rN={},iN={},aN=class e{constructor(t){let n=t[0]instanceof e?t.flatMap(e=>e.data):t;if(n.length===0||n.some(e=>!(e instanceof NM)))throw TypeError(`Vector constructor expects an Array of Data instances.`);let r=n[0]?.type;switch(n.length){case 0:this._offsets=[0];break;case 1:{let{get:e,set:t,indexOf:i}=rN[r.typeId],a=n[0];this.isValid=e=>HM(a,e),this.get=t=>e(a,t),this.set=(e,n)=>t(a,e,n),this.indexOf=e=>i(a,e),this._offsets=[0,a.length];break}default:Object.setPrototypeOf(this,iN[r.typeId]),this._offsets=zM(n);break}this.data=n,this.type=r,this.stride=sA(r),this.numChildren=r.children?.length??0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((e,t)=>e+t.byteLength,0)}get nullable(){return LM(this.data)}get nullCount(){return RM(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${Z[this.type.typeId]}Vector`}isValid(e){return!1}get(e){return null}at(e){return this.get(mM(e,this.length))}set(e,t){}indexOf(e,t){return-1}includes(e,t){return this.indexOf(e,t)>-1}[Symbol.iterator](){return tN.visit(this)}concat(...t){return new e(this.data.concat(t.flatMap(e=>e.data).flat(1/0)))}slice(t,n){return new e(pM(this,t,n,({data:e,_offsets:t},n,r)=>BM(e,t,n,r)))}toJSON(){return[...this]}toArray(){let{type:e,data:t,length:n,stride:r,ArrayType:i}=this;switch(e.typeId){case Z.Int:case Z.Float:case Z.Decimal:case Z.Time:case Z.Timestamp:switch(t.length){case 0:return new i;case 1:return t[0].values.subarray(0,n*r);default:return t.reduce((e,{values:t,length:n})=>(e.array.set(t.subarray(0,n*r),e.offset),e.offset+=n*r,e),{array:new i(n*r),offset:0}).array}}return[...this]}toString(){return`[${[...this].join(`,`)}]`}getChild(e){return this.getChildAt(this.type.children?.findIndex(t=>t.name===e))}getChildAt(t){return t>-1&&t<this.numChildren?new e(this.data.map(({children:e})=>e[t])):null}get isMemoized(){return Ek.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(Ek.isDictionary(this.type)){let t=new oN(this.data[0].dictionary);return new e(this.data.map(e=>{let n=e.clone();return n.dictionary=t,n}))}return new oN(this)}unmemoize(){if(Ek.isDictionary(this.type)&&this.isMemoized){let t=this.data[0].dictionary.unmemoize();return new e(this.data.map(e=>{let n=e.clone();return n.dictionary=t,n}))}return this}};nN=Symbol.toStringTag,aN[nN]=(e=>{e.type=Ek.prototype,e.data=[],e.length=0,e.stride=1,e.numChildren=0,e._offsets=new Uint32Array([0]),e[Symbol.isConcatSpreadable]=!0;let t=Object.keys(Z).map(e=>Z[e]).filter(e=>typeof e==`number`&&e!==Z.NONE);for(let n of t)rN[n]={get:iM.getVisitFnByTypeId(n),set:cj.getVisitFnByTypeId(n),indexOf:ZM.getVisitFnByTypeId(n)},iN[n]=Object.create(e,{isValid:{value:UM(HM)},get:{value:UM(iM.getVisitFnByTypeId(n))},set:{value:WM(cj.getVisitFnByTypeId(n))},indexOf:{value:GM(ZM.getVisitFnByTypeId(n))}});return`Vector`})(aN.prototype);var oN=class e extends aN{constructor(t){super(t.data);let n=this.get,r=this.set,i=this.slice,a=Array(this.length);Object.defineProperty(this,`get`,{value(e){let t=a[e];if(t!==void 0)return t;let r=n.call(this,e);return a[e]=r,r}}),Object.defineProperty(this,`set`,{value(e,t){r.call(this,e,t),a[e]=t}}),Object.defineProperty(this,`slice`,{value:(t,n)=>new e(i.call(this,t,n))}),Object.defineProperty(this,`isMemoized`,{value:!0}),Object.defineProperty(this,`unmemoize`,{value:()=>new aN(this.data)}),Object.defineProperty(this,`memoize`,{value:()=>this})}};function sN(e){if(e){if(e instanceof NM)return new aN([e]);if(e instanceof aN)return new aN(e.data);if(e.type instanceof Ek)return new aN([FM(e)]);if(Array.isArray(e))return new aN(e.flatMap(e=>cN(e)));if(ArrayBuffer.isView(e)){e instanceof DataView&&(e=new Uint8Array(e.buffer));let t={offset:0,length:e.length,nullCount:-1,data:e};if(e instanceof Int8Array)return new aN([FM(Object.assign(Object.assign({},t),{type:new kk}))]);if(e instanceof Int16Array)return new aN([FM(Object.assign(Object.assign({},t),{type:new Ak}))]);if(e instanceof Int32Array)return new aN([FM(Object.assign(Object.assign({},t),{type:new jk}))]);if(e instanceof BigInt64Array)return new aN([FM(Object.assign(Object.assign({},t),{type:new Mk}))]);if(e instanceof Uint8Array||e instanceof Uint8ClampedArray)return new aN([FM(Object.assign(Object.assign({},t),{type:new Nk}))]);if(e instanceof Uint16Array)return new aN([FM(Object.assign(Object.assign({},t),{type:new Pk}))]);if(e instanceof Uint32Array)return new aN([FM(Object.assign(Object.assign({},t),{type:new Fk}))]);if(e instanceof BigUint64Array)return new aN([FM(Object.assign(Object.assign({},t),{type:new Ik}))]);if(e instanceof Float32Array)return new aN([FM(Object.assign(Object.assign({},t),{type:new zk}))]);if(e instanceof Float64Array)return new aN([FM(Object.assign(Object.assign({},t),{type:new Bk}))]);throw Error(`Unrecognized input`)}}throw Error(`Unrecognized input`)}function cN(e){return e instanceof NM?[e]:e instanceof aN?e.data:sN(e).data}function lN(e){if(!e||e.length<=0)return function(e){return!0};let t=``,n=e.filter(e=>e===e);return n.length>0&&(t=`
64
+ `),s=a.get(o);s||(a.size>=4&&a.delete(a.keys().next().value),s={rows:e.map(e=>Object.create(e)),written:new Set},a.set(o,s));let c=new Set(n.map(e=>e.name)),l=[...s.written].filter(e=>!c.has(e));for(let t=0;t<e.length;t++){let e=s.rows[t];for(let t of l)delete e[t];for(let i of n)e[i.name]=r[i.id].values[t]}return s.written=c,s.rows.slice()}var ME=new WeakMap;function NE(e,t,n){let r=ME.get(e.rows);if(r&&r.channels===t&&r.xKey===n)return r.result;let i=kE(t,e,n),a=t.filter(e=>i[e.id]?.status===`ok`),o={rows:a.length===0?e.rows:jE(e.rows,t,a,i,n),ok:a};return ME.set(e.rows,{channels:t,xKey:n,result:o}),o}function PE(e,t,n){if(e.length===0)return[];let r=JSON.stringify(t);return e.filter(e=>e.name===n||r.includes(`"${e.name}"`))}function FE(e){let t=e.filter(e=>e.source===`personal`&&e.projectId===null),n={version:1,exportedAt:new Date().toISOString(),channels:t.map(e=>({name:e.name,units:e.units,formula:e.formula,enabled:e.enabled,...e.description===void 0?{}:{description:e.description}}))};return new Blob([JSON.stringify(n,null,2)],{type:`application/json`})}function IE(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)})}async function LE(e){let t=await IE(e),n;try{n=JSON.parse(t)}catch{return{channels:[],errors:[`Not a valid JSON file.`]}}if(!n||typeof n!=`object`||n.version!==1||!Array.isArray(n.channels))return{channels:[],errors:[`Unrecognized format. Is this a Kymoscope export (version 1)?`]};let r=[],i=[];return n.channels.forEach((e,t)=>{let n=e;if(typeof n.name!=`string`||typeof n.units!=`string`||typeof n.formula!=`string`){i.push(`Channel #${t+1} skipped: missing name/units/formula.`);return}r.push(br({name:n.name,units:n.units,formula:n.formula,enabled:typeof n.enabled==`boolean`?n.enabled:!0,description:typeof n.description==`string`?n.description:void 0,source:`personal`,sharedWithOrgId:null,ownerUserId:``}))}),{channels:r,errors:i}}var RE=3e3;function zE(e){return Math.max(RE,4*(e??0))}function BE(e,t){if(!e)return 0;let n=(e.offsetMs+e.driftPpm*1e-6*(t-e.tRef)*1e3)/1e3;return Number.isFinite(n)?n:0}function VE(e,t){return typeof e==`number`&&typeof t==`number`&&Number.isFinite(e)&&Number.isFinite(t)?(e-t)/1e3:0}function HE(e,t,n){let r=n+1;return n>=0&&r<e.length&&e[r].t-t<t-e[n].t?r:n}var UE=new WeakMap;function WE(e){let t=e.video,n=UE.get(t);if(n&&n.id===e.id&&n.name===e.name&&n.parentId===e.parentId&&n.lowOf===(e.lowOf??null))return n;let r={id:e.id,name:e.name,kind:`live`,parentId:e.parentId,lowOf:e.lowOf??null,sync:e.sync??null,clockOffsetMs:e.clockOffsetMs??null,info:()=>t.info(),range:()=>t.range(),seekPlan:e=>t.seekPlan(e),livePlan:()=>t.livePlan(),onUnit:e=>t.onUnit(e),acquire:()=>t.acquire(),unitsBetween:async(e,n)=>t.unitsBetween(e,n)};return UE.set(t,r),r}var GE=class{ring=[];bytes=0;needKey=!0;width=0;height=0;codec=``;pending=null;subs=new Set;holders=0;demand=()=>{};maxBytes;now;constructor(e=128*1024*1024,t=Date.now){this.maxBytes=e,this.now=t}push(e){let t=this.pending;if(t&&t.seq!==e.seq&&(t.key&&(this.needKey=!0),t=this.pending=null),t||=this.pending={seq:e.seq,key:e.key,t:e.t,count:e.fragCount,parts:new Map},t.parts.has(e.fragIndex)||t.parts.set(e.fragIndex,e.payload),e.key&&e.fragIndex===0&&(this.width=e.width,this.height=e.height,this.codec=e.codec),t.parts.size<t.count||(this.pending=null,!t.key&&this.needKey))return null;let n=new Uint8Array([...Array(t.count).keys()].reduce((e,n)=>e+(t.parts.get(n)?.length??0),0)),r=0;for(let e=0;e<t.count;e++){let i=t.parts.get(e);i&&(n.set(i,r),r+=i.length)}t.key&&(this.needKey=!1);let i={t:t.t,seq:t.seq,key:t.key,data:n,arrivedAt:this.now()};return this.ring.push(i),this.bytes+=n.length,this.trim(),this.subs.forEach(e=>e(i)),i}trim(){for(;this.bytes>this.maxBytes;){let e=this.ring.findIndex((e,t)=>t>0&&e.key);if(e<0)return;for(let t of this.ring.splice(0,e))this.bytes-=t.data.length}}seekPlan(e){let t=0,n=this.ring.length;for(;t<n;){let r=t+n>>1;this.ring[r].t<=e?t=r+1:n=r}let r=HE(this.ring,e,t-1),i=r;for(;i>=0&&!this.ring[i].key;)i--;return i<0?[]:this.ring.slice(i,r+1)}unitsBetween(e,t){let n=this.ring.findIndex(t=>t.t>e),r=(n<0?this.ring.length:n)-1;for(;r>0&&!this.ring[r].key;)r--;return this.ring.slice(Math.max(0,r)).filter(e=>e.t<=t)}livePlan(){for(let e=this.ring.length-1;e>=0;e--)if(this.ring[e].key)return this.ring.slice(e);return[]}onUnit(e){return this.subs.add(e),()=>{this.subs.delete(e)}}acquire(){this.holders++===0&&this.demand(!0);let e=!0;return()=>{e&&(e=!1,--this.holders===0&&this.demand(!1))}}onDemandChange(e){this.demand=e}info(){let e=this.ring.length,t=e?this.ring[e-1].t:null,n=[];for(let t=Math.max(1,e-9);t<e;t++)n.push(this.ring[t].arrivedAt-this.ring[t-1].arrivedAt);return n.sort((e,t)=>e-t),{width:this.width,height:this.height,codec:this.codec,latestT:t,lagMs:t===null?null:this.now()-t*1e3,units:e,bytes:this.bytes,arrivedAt:e?this.ring[e-1].arrivedAt:null,gapMs:n.length?n[n.length>>1]:null}}range(){return this.ring.length?[this.ring[0].t,this.ring[this.ring.length-1].t]:null}resync(){this.pending=null,this.needKey=!0}clear(){this.ring=[],this.bytes=0,this.pending=null,this.needKey=!0}},KE=[`min`,`max`,`mean`,`integral`,`first`,`last`,`delta`],qE=e=>`${e.channel}:${e.stat}`;function JE(e,t,n){switch(e){case`>`:return t>n;case`>=`:return t>=n;case`<`:return t<n;case`<=`:return t<=n;case`==`:return t===n;default:return t!==n}}var YE=()=>({prev:NaN,lo:0,hi:0});function XE(e,t){if(e.prev!==e.prev)return e.prev=e.lo=e.hi=t,!1;let n=t<e.prev&&e.prev-t>(e.hi-e.lo)/2;return n?e.lo=e.hi=t:(t<e.lo&&(e.lo=t),t>e.hi&&(e.hi=t)),e.prev=t,n}var ZE=new Map,QE=e=>{let t=ZE.get(e);return t||(t=new Intl.DateTimeFormat(`en-US`,{timeZone:e,hourCycle:`h23`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}),ZE.set(e,t)),t};function $E(e,t){let n={};for(let r of QE(t).formatToParts(new Date(Math.floor(e)*1e3)))n[r.type]=r.value;return(Date.UTC(+n.year,n.month-1,+n.day,+n.hour,+n.minute,+n.second)-Math.floor(e)*1e3)/1e3}function eD(e,t){let n=e+$E(e,t);return new Date(Math.floor(n)*1e3).toISOString().slice(0,10)}function tD(e,t,n){let[r,i,a]=e.split(`-`).map(Number),[o,s]=t.split(`:`).map(Number),c=Date.UTC(r,i-1,a,o,s)/1e3;return c-$E(c-$E(c,n),n)}var nD=(e,t)=>{let[n,r,i]=e.split(`-`).map(Number);return new Date(Date.UTC(n,r-1,i+t)).toISOString().slice(0,10)},rD=class{n=0;sum=0;min=1/0;max=-1/0;first=NaN;last=NaN;integral=0;lastT=NaN;add(e,t){t===t&&(this.n>0?this.integral+=(t+this.last)/2*(e-this.lastT):this.first=t,this.n++,this.sum+=t,t<this.min&&(this.min=t),t>this.max&&(this.max=t),this.last=t,this.lastT=e)}value(e){if(this.n===0)return null;switch(e){case`min`:return this.min;case`max`:return this.max;case`mean`:return this.sum/this.n;case`integral`:return this.integral;case`first`:return this.first;case`last`:return this.last;default:return this.last-this.first}}};function iD(e){let t=new Map,n=n=>{let r=t.get(n);return r||t.set(n,r=e.at.map(t=>tD(n,t,e.tz)).sort((e,t)=>e-t)),r},r=t=>{let r=eD(t,e.tz),i=-1/0;for(let e of n(r))e<=t&&(i=e);if(i>-1/0)return i;let a=n(nD(r,-1));return a[a.length-1]},i=t=>{let r=eD(t,e.tz);for(let e of n(r))if(e>t)return e;return n(nD(r,1))[0]},a=NaN,o=NaN,s={on:!1,edge:!1,at:NaN,event:!0,step(e){if(s.edge=s.on=!(e.t>=a&&e.t<o),!s.edge)return;let t=r(e.t);s.closeAt=o<=t?o:t,s.at=a=t,o=i(t)}};return s}function aD(e){switch(e.kind){case`compare`:{let t={on:!1,edge:!1,at:NaN,event:!1,step(n){let r=n.v(e.channel);r===r&&(t.on=JE(e.op,r,e.value)),t.at=n.t}};return t}case`elapsed`:{let t={on:!1,edge:!1,at:NaN,event:!1,step(n){let r=n.t-(e.from===`start`?n.start:n.ps);t.on=r===r&&(e.op===`>=`?r>=e.seconds:r<=e.seconds),t.at=n.t}};return t}case`change`:case`cross`:{let t=NaN,n={on:!1,edge:!1,at:NaN,event:!0,step(r){let i=r.v(e.channel);n.edge=!1,i===i&&(t===t&&(n.edge=e.kind===`change`?i!==t:e.dir===`rise`?t<e.value&&i>=e.value:t>e.value&&i<=e.value),t=i),n.on=n.edge,n.at=r.t}};return n}case`reset`:{let t=YE(),n={on:!1,edge:!1,at:NaN,event:!0,step(r){let i=r.v(e.channel);n.edge=i===i&&(t.prev===t.prev?XE(t,i):(XE(t,i),!0)),n.on=n.edge,n.at=r.t}};return n}case`clock`:return iD(e);case`parent-start`:{let e=!1,t={on:!1,edge:!1,at:NaN,event:!0,step(n){t.on=t.edge=!e,e=!0,t.at=n.ps}};return t}case`all`:case`any`:{let t=e.of.map(aD),n={on:!1,edge:!1,at:NaN,event:t.some(e=>e.event),step(r){for(let e of t)e.step(r);n.on=e.kind===`all`?t.every(e=>e.on):t.some(e=>e.on),n.edge=n.on&&t.some(e=>e.edge),n.at=r.t}};return n}default:return{on:!1,edge:!1,at:NaN,event:!0,step(){}}}}var oD=(e,t)=>e.kind===t||(e.kind===`all`||e.kind===`any`)&&e.of.some(e=>oD(e,t));function sD(e){let t=new Set,n=e=>{`channel`in e&&t.add(e.channel),(e.kind===`all`||e.kind===`any`)&&e.of.forEach(n)};return n(e.start),n(e.end),[...t]}var cD=class{rule;#e;#t;#n=NaN;#r=!1;#i=NaN;#a=NaN;#o=NaN;#s=NaN;#c;#l;constructor(e){this.rule=e,this.#c=oD(e.end,`parent-end`),this.#l=e.end.kind===`next-start`,this.#u()}#u(){this.#e=aD(this.rule.start),this.#t=aD(this.rule.end),this.#r=!1}#d(e,t,n){let r=this.rule.limits;if(!r)return[];let i=[],a=r.from===`start`?e:this.#n;return r.expectedWithin_s!=null&&t-a>r.expectedWithin_s&&i.push(`late`),r.max_s!=null&&t-e>r.max_s&&i.push(`too-long`),n&&r.min_s!=null&&t-e<r.min_s&&i.push(`too-short`),i}#f(e,t,n=!1){let r={tstart:this.#i,tend:e,flags:this.#d(this.#i,e,!0)};n&&(r.incomplete=!0),t.push(r),this.#i=this.#o=NaN}parentStart(e){this.#n=e,this.#i=this.#a=this.#o=NaN,this.#u()}parentEnd(e,t){this.#i===this.#i&&this.#f(e,t,!this.#c),this.#a=NaN,this.#n=NaN}step(e,t,n){this.#n!==this.#n&&(this.#n=e);let r={t:e,v:t,ps:this.#n,start:this.#i},i=this.#e,a=this.#t;i.step(r),a.step(r);let o=i.on&&(!this.#r||i.edge);this.#r=i.on;let s=i.event&&!(this.rule.start.kind===`all`||this.rule.start.kind===`any`)?i.at:e;if(this.#i===this.#i&&!this.#l&&e>this.#i){let t=this.rule.ignoreDips_s??0;a.on?t>0&&!a.event?(this.#o!==this.#o&&(this.#o=e),e-this.#o>=t&&this.#f(this.#o,n)):this.#f(e,n):this.#o=NaN}let c=e=>{this.#i===this.#i&&this.#f(this.#l&&i.closeAt!==void 0?i.closeAt:e,n),this.#i=e},l=this.#i!==this.#i||this.#l,u=this.rule.minHold_s??0;this.#a===this.#a?i.on?e-this.#a>=u&&(l&&c(this.#a),this.#a=NaN):this.#a=NaN:o&&l&&(u>0&&!i.event?this.#a=s:c(s)),this.#s=e}open(){return this.#i===this.#i?{tstart:this.#i,tend:null,flags:this.#d(this.#i,this.#s,!1)}:null}},lD=class{#e;constructor(e){let t=[],n=r=>{for(let i of e)i.parentId===r&&(t.push(i),n(i.id))};n(null),this.#e=t.map(e=>({...e,runner:new cD(e.rule),count:0,current:0,kids:[]})),this.#e.forEach((e,t)=>{e.parentId&&this.#e.find(t=>t.id===e.parentId).kids.push(t)})}#t(e,t,n,r){let i=this.#e[e];for(let e of t)n.push({...e,definitionId:i.id,index:i.current,...r?{parentIndex:r}:{}})}#n(e){let t=this.#e[e].parentId;return t?this.#e.find(e=>e.id===t).current:void 0}#r(e,t,n){for(let r of this.#e[e].kids){this.#r(r,t,n);let i=[];this.#e[r].runner.parentEnd(t,i),this.#t(r,i,n,this.#e[e].current)}}#i(e,t,n,r){let i=this.#e[e],a=i.runner.open()?.tstart,o=[];i.runner.step(t,n,o);let s=i.runner.open()?.tstart;if(o.length)for(let t of o)this.#r(e,t.tend,r),r.push({...t,definitionId:i.id,index:i.current,...this.#n(e)?{parentIndex:this.#n(e)}:{}});if(s!==void 0&&s!==a){i.current=++i.count;for(let e of i.kids)this.#e[e].current=this.#e[e].count=0,this.#e[e].runner.parentStart(s)}if(s!==void 0)for(let e of i.kids)this.#i(e,t,n,r)}feed(e,t){let n=new Map,r=e=>(n.has(e)||n.set(e,t(e)),n.get(e)),i=[],a=0,o=e=>{let t=r(e);return t?t[a]:NaN};for(;a<e.length;a++)for(let t=0;t<this.#e.length;t++)this.#e[t].parentId||this.#i(t,e[a],o,i);return i}open(){let e=[];return this.#e.forEach((t,n)=>{let r=t.runner.open(),i=this.#n(n);r&&(!t.parentId||this.#e.find(e=>e.id===t.parentId).runner.open())&&e.push({...r,definitionId:t.id,index:t.current,...i?{parentIndex:i}:{}})}),e}},uD=new Set([`>`,`>=`,`<`,`<=`,`==`,`!=`]),dD=e=>typeof e==`number`&&Number.isFinite(e),fD=e=>typeof e==`string`&&e.length>0;function pD(e,t){let n=e;if(!n||typeof n!=`object`)return!1;switch(n.kind){case`parent-start`:case`parent-end`:case`next-start`:case`manual`:return!0;case`all`:case`any`:return t<3&&Array.isArray(n.of)&&n.of.length>0&&n.of.every(e=>pD(e,t+1));case`compare`:return fD(n.channel)&&uD.has(n.op)&&dD(n.value);case`change`:case`reset`:return fD(n.channel);case`cross`:return fD(n.channel)&&(n.dir===`rise`||n.dir===`fall`)&&dD(n.value);case`elapsed`:return(n.from===`parent-start`||n.from===`start`)&&(n.op===`>=`||n.op===`<=`)&&dD(n.seconds);case`clock`:return Array.isArray(n.at)&&n.at.length>0&&n.at.every(e=>typeof e==`string`&&/^\d\d:\d\d$/.test(e))&&fD(n.tz);default:return!1}}function mD(e){if(!Array.isArray(e))return[];let t=e.filter(e=>{let t=e?.rule,n=t?.limits;return fD(e?.id)&&fD(e?.name)&&(e.parentId===null||fD(e.parentId))&&!!t&&pD(t.start,1)&&pD(t.end,1)&&(t.minHold_s===void 0||dD(t.minHold_s))&&(t.ignoreDips_s===void 0||dD(t.ignoreDips_s))&&(n===void 0||typeof n==`object`&&[`expectedWithin_s`,`min_s`,`max_s`].every(e=>n[e]===void 0||dD(n[e])))}),n=new Set(t.map(e=>e.id));return t.filter(e=>e.parentId===null||n.has(e.parentId)).map(e=>{let t=Array.isArray(e.kpis)?e.kpis.filter(e=>fD(e?.channel)&&KE.includes(e.stat)).slice(0,50):[],n=fD(e.show?.channel)&&KE.includes(e.show.stat)?{channel:e.show.channel,stat:e.show.stat,...dD(e.show.target)?{target:e.show.target}:e.show.better===`min`||e.show.better===`max`?{better:e.show.better}:{}}:void 0;return{id:e.id,name:e.name,parentId:e.parentId,rule:e.rule,...t.length?{kpis:t}:{},...n?{show:n}:{}}})}var hD=`Cycle time`,gD=65536;async function _D(e,t,n){let r=[...new Set([t,...n])],i=[];for(let n=0;;n+=gD){let a=await e.readColumns(r,n,gD),o=a[t]?.length??0;if(o>0&&i.push(a),o<gD)break}let a=e=>{if(!i.some(t=>t[e]))return;let n=new Float64Array(i.reduce((e,n)=>e+n[t].length,0)).fill(NaN),r=0;for(let a of i)a[e]&&n.set(a[e],r),r+=a[t].length;return n},o=new Map;for(let e of r){let n=e===t?void 0:a(e);n&&o.set(e,n)}return{t:a(t)??new Float64Array,cols:o}}function vD(e,t){let n=new lD(t);return[...n.feed(e.t,t=>e.cols.get(t)),...n.open()]}var yD=e=>[...new Set(e.flatMap(e=>[...sD(e.rule),...(e.kpis??[]).map(e=>e.channel)]))],bD=e=>`${e.channel} ${e.stat}`;function xD(e,t,n){let r=SD(e.t,t.tstart),i=t.tend===null?e.t.length:SD(e.t,t.tend),a={};for(let t of n){let n=e.cols.get(t.channel),o=new rD;if(n)for(let t=r;t<i;t++)o.add(e.t[t],n[t]);a[bD(t)]=o.value(t.stat)}return a}function SD(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 CD(e,t,n){let r=SD(e.t,n.tstart),i=n.tend===null?e.t.length:SD(e.t,n.tend),a=e.t.subarray(r,i),o={[hD]:a.map(e=>e-n.tstart),[t]:a};for(let[t,n]of e.cols)o[t]=n.subarray(r,i);return o}var wD=e=>e.replace(`-`,` `);function TD(e,t,n,r){let i=Object.fromEntries(n.map(e=>[e.id,e.name])),a=e=>n.find(t=>t.id===e)?.kpis??[],o=e=>r?xD(r,e,a(e.definitionId)):{},s=n.filter(e=>e.parentId===t).map(e=>e.id),c=e=>e.tend===null?null:e.tend-e.tstart,l=e.filter(e=>s.includes(e.definitionId)).sort((e,t)=>e.tstart-t.tstart);return{cycles:e.filter(e=>e.definitionId===t).sort((e,t)=>e.index-t.index).map(e=>{let t=l.filter(t=>t.parentIndex===e.index),n={Cycle:e.index,Start:e.tstart,End:e.tend,Duration:c(e)};for(let e of s){let r=t.filter(t=>t.definitionId===e);n[`${i[e]??e} duration`]=r.length&&r.every(e=>e.tend!==null)?r.reduce((e,t)=>e+t.tend-t.tstart,0):null}return Object.assign(n,o(e)),n.Flags=[...e.flags.map(wD),...t.flatMap(e=>e.flags.map(t=>`${i[e.definitionId]??e.definitionId} ${wD(t)}`))].join(`, `),n}),phases:l.map(e=>({Cycle:e.parentIndex,Phase:i[e.definitionId]??e.definitionId,Start:e.tstart,End:e.tend,Duration:c(e),...o(e),Flags:e.flags.map(wD).join(`, `)}))}}function ED(e){if(e.length===0)return``;let t=Object.keys(e[0]),n=e=>e===null?``:typeof e==`number`?String(e):/[",\n]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e;return[t.map(n).join(`,`),...e.map(e=>t.map(t=>n(e[t]??null)).join(`,`))].join(`
65
+ `)}var DD=.005,OD=8,kD=-1,AD=2,jD=.2,MD=4,ND=10,PD=e=>{let t=[...e].sort((e,t)=>e-t),n=t.length;return n?n%2?t[n>>1]:(t[n/2-1]+t[n/2])/2:NaN};function FD(e,t,n,r,i){let a=new Float32Array(i),o=0,s=e.length,c=NaN;for(let l=0;l<i;l++){let i=n+l*r;for(;o+1<s&&e[o+1]<=i;)o++;let u=e[o],d=o+1<s?e[o+1]:NaN,f=t[o];i>u&&d>u&&(f=t[o]+(t[o+1]-t[o])*(i-u)/(d-u)),i<u&&(f=t[0]),Number.isFinite(f)&&(c=f),a[l]=Number.isFinite(f)?f:Number.isFinite(c)?c:0}return a}function ID(e,t){let n=e.length,r=new Float64Array(n+1);for(let t=0;t<n;t++)r[t+1]=r[t]+e[t];let i=t>>1,a=new Float32Array(n);for(let t=0;t<n;t++){let o=Math.max(0,t-i),s=Math.min(n,t+i+1);a[t]=e[t]-(r[s]-r[o])/(s-o)}return a}function LD(e,t){if(t<=1)return e;let n=e.length,r=new Float64Array(n+1);for(let t=0;t<n;t++)r[t+1]=r[t]+e[t];let i=t>>1,a=new Float32Array(n);for(let e=0;e<n;e++){let t=Math.max(0,e-i),o=Math.min(n,e+i+1);a[e]=(r[o]-r[t])/(o-t)}return a}function RD(e,t){let n=Math.floor(e.length/t),r=new Float32Array(n);for(let i=0;i<n;i++){let n=0;for(let r=0;r<t;r++)n+=e[i*t+r];r[i]=n/t}return r}function zD(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];let n=t/e.length,r=0;for(let t=0;t<e.length;t++)r+=(e[t]-n)**2;let i=Math.sqrt(r/e.length),a=new Float32Array(e.length);if(i>1e-9)for(let t=0;t<e.length;t++)a[t]=(e[t]-n)/i;return a}function BD(e,t,n,r=new Float64Array(n)){let i=e.length,a=new Float64Array(t.length+1),o=new Float64Array(t.length+1);for(let e=0;e<t.length;e++)a[e+1]=a[e]+t[e],o[e+1]=o[e]+t[e]*t[e];for(let s=0;s<n;s++){let n=0;for(let r=0;r<i;r++)n+=e[r]*t[r+s];let c=(a[s+i]-a[s])/i,l=Math.sqrt(Math.max(0,(o[s+i]-o[s])/i-c*c));r[s]=l>1e-9?n/(i*l):0}return r}function VD(e,t,n){let r=0;for(let n=1;n<e.length;n++)t*e[n]>t*e[r]&&(r=n);let i=r,a=r;for(;i>0&&t*e[i-1]>t*e[r]/2;)i--;for(;a<e.length-1&&t*e[a+1]>t*e[r]/2;)a++;i=Math.min(i,r-n),a=Math.max(a,r+n);let o=0,s=0,c=0;for(let n=0;n<e.length;n++)(n<i||n>a)&&(o+=t*e[n],s+=e[n]*e[n],c++);let l=c?o/c:0,u=c?Math.sqrt(Math.max(1e-12,s/c-l*l)):1,d=0;if(r>0&&r<e.length-1){let n=t*e[r-1],i=t*e[r],a=t*e[r+1],o=n-2*i+a;o<0&&(d=Math.max(-.5,Math.min(.5,(n-a)/(2*o))))}return{k:r,frac:d,peak:t*e[r],z:(t*e[r]-l)/u}}function HD(e,t){let n=[],r=Math.max(1,Math.floor(e.length/2e3));for(let i=r;i<e.length;i+=r)(!t||Number.isFinite(t[i])&&Number.isFinite(t[i-1]))&&n.push(e[i]-e[i-1]);return PD(n)}function UD(e,t,n=20){let r=[];for(let i of e){if(i.t.length<50)continue;let e=1/HD(i.t,i.v);if(!(e>=ND))continue;let a=OD*DD,o=Math.floor((t[1]-t[0])/a);if(o<50)continue;let s=FD(i.t,i.v,t[0],a,o),c=(e,t,n)=>{let r=0,i=0;for(let a=t;a<n;a++)r+=e[a],i+=e[a]*e[a];let a=r/(n-t);return Math.sqrt(Math.max(0,i/(n-t)-a*a))},l=c(s,0,o);if(!(l>1e-9))continue;let u=Math.max(10,Math.min(o,Math.round(n/a))),d=0,f=0;for(let e=0;e+u<=o;e+=u)d+=c(s,e,e+u)/l,f++;let p=zD(s),m=0;for(let e=1;e<o;e++)m+=p[e]*p[e-1];m/=o-1,r.push({...i,rate:e,activity:(f?d/f:0)*Math.max(0,m)})}return r.sort((e,t)=>t.activity-e.activity)}function WD(e,t,n={}){let r=(n.maxLagMs??3e3)/1e3,i=t[0]-kD+AD/2,a=t[1]-r-AD/2-i,o=n.minSegments??5,s=n.maxSegments??10;if(!(a>0))return{segments:[],video:[]};let c=Math.max(Math.min(n.segmentS??20,a/(2*o)),Math.min(2.5,a)),l=Array.from({length:Math.floor(a/c+1e-6)},(e,t)=>[i+t*c,i+(t+1)*c]),u=l;if(l.length>s){let r=UD(e,t).slice(0,n.maxChannels??8),i=r.map(e=>Math.sqrt(GD(FD(e.t,e.v,t[0],.04,Math.floor((t[1]-t[0])/.04))))||1),a=l.map(([e,t])=>r.reduce((n,r,a)=>n+Math.sqrt(GD(FD(r.t,r.v,e,.04,Math.floor((t-e)/.04))))/i[a],0));u=[];for(let e=0;e<s;e++){let t=Math.floor(e*l.length/s),n=Math.floor((e+1)*l.length/s),r=t;for(let e=t;e<n;e++)a[e]>a[r]&&(r=e);u.push(l[r])}}return{segments:u,video:KD(u.map(([e,t])=>[e+kD-AD,t+r+AD]))}}function GD(e){let t=0,n=0;for(let r=0;r<e.length;r++)t+=e[r],n+=e[r]*e[r];return e.length?n/e.length-(t/e.length)**2:0}function KD(e){let t=[...e].sort((e,t)=>e[0]-t[0]),n=[];for(let e of t){let t=n[n.length-1];t&&e[0]<=t[1]+2?t[1]=Math.max(t[1],e[1]):n.push([e[0],e[1]])}return n}function qD(e,t,n){let r=[];for(let n=0;n<e.length;n++)for(let i=n+1;i<e.length;i++)e[i]!==e[n]&&r.push((t[i]-t[n])/(e[i]-e[n]));let i=r.length?PD(r):0,a=PD(t.map((t,r)=>t-i*(e[r]-n)));return{slope:i,at:a,mad:PD(t.map((t,r)=>t-a-i*(e[r]-n)).map(Math.abs))}}var JD=[[`value`,`level`],[`rate`,`diff`],[`abs`,`diff`]],YD=[[`value`,`diff`]];function XD(e){let t=new Map;for(let n of e){let e=/^(.+?)[\s_.-]?([0-9]|[xyzXYZ])$/.exec(n.name);if(!e||n.magnitude)continue;let r=JSON.stringify([e[1],n.unit??``]),i=t.get(r)??{stem:e[1],g:[]};i.g.push(n),t.set(r,i)}let n=new Set(e.map(e=>e.name)),r=[...e];for(let{stem:e,g:i}of t.values()){let t=i[0].t,a=t.length,o=`${e} |v|`;if(i.length<2||i.length>3||n.has(o)||!i.every(e=>e.t.length===a&&e.v.length===a&&e.t[0]===t[0]&&e.t[a-1]===t[a-1]))continue;let s=new Float64Array(a);for(let e=0;e<a;e++){let t=0;for(let n of i)t+=n.v[e]**2;s[e]=Math.sqrt(t)}r.push({name:o,t,v:s,unit:i[0].unit,magnitude:!0})}return r}function ZD(e,t,n){let r=e.t.length,i=e.cells;if(t===`level`){let t=new Float64Array(r);for(let a=0;a<r;a++)t[a]=e.levels[a*i+n];return{t:Float64Array.from(e.t),v:t}}let a=new Float64Array(r-1),o=new Float64Array(r-1);for(let t=1;t<r;t++){let r=e.t[t]-e.t[t-1],s=Math.max(.001,r),c=0;if(n===i){for(let n=0;n<i;n++)c+=e.diffs[t*i+n];c/=i}else c=e.diffs[t*i+n];a[t-1]=(e.t[t]+e.t[t-1])/2,o[t-1]=r>1?NaN:c/s}return{t:a,v:o}}function QD(e,t){if(t===`value`)return e;let n=e.t.length;if(t===`abs`){let t=new Float64Array(n),r=0,i=0,a=0,o=0;for(let s=0;s<n;s++){for(;i<n&&e.t[i]<=e.t[s]+AD/2;)Number.isFinite(e.v[i])&&(a+=e.v[i],o++),i++;for(;e.t[r]<e.t[s]-AD/2;)Number.isFinite(e.v[r])&&(a-=e.v[r],o--),r++;t[s]=o?Math.abs(e.v[s]-a/o):NaN}return{t:e.t,v:t}}let r=new Float64Array(n-1),i=new Float64Array(n-1);for(let t=1;t<n;t++){let n=e.t[t]-e.t[t-1];r[t-1]=(e.t[t]+e.t[t-1])/2,i[t-1]=n>0?Math.abs(e.v[t]-e.v[t-1])/n:NaN}return{t:r,v:i}}function $D(e,t,n={}){let r=e.t.length;if(r<20)return{ok:!1,reason:`too few video frames`};let i=HD(e.t),a=n.minLagMs===void 0?-i:n.minLagMs/1e3,o=(n.maxLagMs??3e3)/1e3,s=n.minSegments??5,c=n.minZ??5,l=Math.max(...t.map(e=>e.t[e.t.length-1]??-1/0)),u=Math.min(...t.map(e=>e.t[0]??1/0)),d=[Math.max(e.t[0],u),Math.min(e.t[r-1],l)];if(!(d[1]-d[0]>5))return{ok:!1,reason:`the video and the data overlap too little`};let f=UD(XD(t),d).filter(e=>e.activity>.05).slice(0,n.maxChannels??8);if(!f.length)return{ok:!1,reason:`no channel changes enough at ${ND} Hz or more`};let{segments:p}=WD(f,d,n);if(p.length<s)return{ok:!1,reason:`the recording is too short`};let m=Math.max(1,Math.round(i/DD)),h=Math.round(AD/DD),g=Math.round(kD/DD),_=Math.round(o/DD)-g+1,v=new Map,y=(e,t,n,r)=>{let i=v.get(e);if(!i){let a=t();i=p.map(([e,t])=>{let i=n?e:e+g*DD,o=Math.round((t-e)/DD)+(n?0:_-1),s=FD(a.t,a.v,i-AD,DD,o+2*h);return r&&(s=ID(s,h)),n&&(s=LD(s,m)),s.subarray(h,h+o)}),v.set(e,i)}return i},b=(t,n)=>y(`v:${t}:${n}`,()=>ZD(e,t,n),!1,!0),x=(e,t)=>y(`d:${e.name}:${t}`,()=>QD(e,t),!0,t===`value`),S=Math.floor(_/OD),C=[],w=new Map,T=(e,t)=>{let n=w.get(e);return n||w.set(e,n=t.map(e=>RD(e,OD))),n},E=new Float64Array(S),D=new Float64Array(S),O=n.pairs??JD;for(let t of f){let r=null;for(let[i,a]of t.magnitude&&!n.pairs?YD:O){let n=T(`d:${t.name}:${i}`,x(t,i)).map(zD),o=a===`level`?e.cells:e.cells+1;for(let e=0;e<o;e++){let o=T(`v:${a}:${e}`,b(a,e));E.fill(0);for(let e=0;e<p.length;e++){BD(n[e],o[e],S,D);for(let e=0;e<S;e++)E[e]+=D[e]/p.length}for(let n of a===`level`?[1,-1]:[1]){let o=VD(E,n,jD/(OD*DD));(!r||o.peak>r.peak)&&(r={chan:t,dk:i,vk:a,cell:e,peak:o.peak,sign:n})}}}for(let e of[...w.keys()])e.startsWith(`d:`)&&w.delete(e);r&&C.push(r)}C.sort((e,t)=>t.peak-e.peak);let k=[],A=new Float64Array(_),j=n.fineChannels??3;for(let e of C.filter((e,t)=>t<j||e.chan.magnitude)){let t=x(e.chan,e.dk).map(zD),n=b(e.vk,e.cell),r=[];for(let i=0;i<p.length;i++){BD(t[i],n[i],_,A);let a=VD(A,e.sign,jD/DD);a.k===0||a.k===_-1||a.z<MD||r.push({t:(p[i][0]+p[i][1])/2,offsetMs:((a.k+a.frac)*DD+kD)*1e3,z:a.z,peak:a.peak})}if(!r.length){k.push({pair:e,segs:r,offsetMs:NaN,driftPpm:0,tRef:NaN,spreadMs:NaN,z:0});continue}let a=e=>{let t=(e[0].t+e[e.length-1].t)/2,n=e.map(e=>e.t),r=e.map(e=>e.offsetMs),a=qD(n,r,t),o=n[n.length-1]-n[0];if(e.length<5||o<60||Math.abs(a.slope)*o<Math.max(3*a.mad,i*500)){let e=PD(r);a={slope:0,at:e,mad:PD(r.map(t=>Math.abs(t-e)))}}return{...a,tRef:t}},o=a(r),s=e=>Math.abs(e.offsetMs-o.at-o.slope*(e.t-o.tRef)),c=r.filter(e=>s(e)<=Math.max(i*1e3,5*o.mad));c.length&&c.length<r.length&&(o=a(c)),k.push({pair:e,segs:c,offsetMs:o.at,driftPpm:o.slope*1e3,tRef:o.tRef,spreadMs:o.mad,z:PD(c.map(e=>e.z))})}if(!k.length)return{ok:!1,reason:`nothing in the picture follows the data`};let M=i*1e3,N=e=>e.segs.length<s?`only ${e.segs.length} of ${p.length} segments found a peak`:e.z<c?`no clear match between the picture and the data`:e.spreadMs>M/2?`the segments disagree (±${Math.round(e.spreadMs)} ms)`:e.offsetMs<a*1e3||e.offsetMs>o*1e3?`the match is outside the plausible offsets`:null,P=k.map(t=>({channel:t.pair.chan.name,feature:`${t.pair.dk} ~ ${t.pair.vk} ${t.pair.cell===e.cells?`frame`:`cell ${t.pair.cell}`}${t.pair.sign<0?` (inverted)`:``}`,offsetMs:t.offsetMs,driftPpm:t.driftPpm,spreadMs:t.spreadMs,z:t.z,segments:t.segs.length,refused:N(t)})),F=k.filter(e=>!N(e)).sort((e,t)=>t.z-e.z),I=k.sort((e,t)=>t.z-e.z)[0],L=e=>({channel:e.pair.chan.name,offsetMs:e.offsetMs,spreadMs:e.spreadMs,z:e.z,segments:e.segs.length});if(!F.length)return{ok:!1,reason:N(I),best:L(I),tried:P};let R=F[0],z=F.filter(e=>e.z>=.75*R.z),B=z.filter(e=>Math.abs(e.offsetMs-R.offsetMs)<=Math.max(M,2*(e.spreadMs+R.spreadMs)));if(B.length<z.length)return{ok:!1,reason:`channels that match the picture disagree on the offset`,best:L(R),tried:P};let V=PD(B.map(e=>e.offsetMs+e.driftPpm*.001*(R.tRef-e.tRef))),ee=Math.max(0,Math.min(1,.5*Math.min(1,R.z/(2*c))+.5*(1-R.spreadMs/(M/2))));return{ok:!0,offsetMs:V,driftPpm:R.driftPpm,tRef:R.tRef,confidence:ee,spreadMs:R.spreadMs,channels:B.map(e=>e.pair.chan.name),segments:R.segs,z:R.z,framePeriodMs:M,tried:P}}var eO=e=>e>=.7?`high`:e>=.4?`medium`:`low`,tO=32,nO=18,rO=8,iO=6,aO=10,oO=16,sO=()=>new DOMException(`The operation was aborted.`,`AbortError`);async function cO(e,t,n={}){if(!e.unitsBetween)throw Error(`This camera has no recorded frames to analyse`);if(typeof VideoDecoder>`u`||typeof OffscreenCanvas>`u`)throw Error(`This browser can’t decode video here`);await e.ready?.();let r=e.info().codec;if(!r)throw Error(`No video found for this camera`);let i=new OffscreenCanvas(tO,nO).getContext(`2d`,{willReadFrequently:!0});if(!i)throw Error(`This browser can’t decode video here`);let a=[],o=[],s=[],c=null,l=new Float32Array(tO*nO),u=tO/rO,d=nO/iO,f=u*d,p=e=>{try{i.drawImage(e,0,0,tO,nO),a.push(e.timestamp/1e6)}finally{e.close()}let t=i.getImageData(0,0,tO,nO).data;for(let e=0;e<tO*nO;e++)l[e]=.299*t[4*e]+.587*t[4*e+1]+.114*t[4*e+2];for(let e=0;e<iO;e++)for(let t=0;t<rO;t++){let n=0,r=0;for(let i=e*d;i<(e+1)*d;i++)for(let e=t*u;e<(t+1)*u;e++){let t=i*tO+e;n+=l[t],c&&(r+=Math.abs(l[t]-c[t]))}o.push(n/f),s.push(r/f)}c=Float32Array.from(l)},m=null,h=new VideoDecoder({output:p,error:e=>{m=e instanceof Error?e:Error(String(e))}});h.configure({codec:r,hardwareAcceleration:`no-preference`});let g=()=>new Promise(e=>{let t=()=>{h.removeEventListener(`dequeue`,t),clearTimeout(n),e()},n=setTimeout(t,50);h.addEventListener(`dequeue`,t)}),_=t.reduce((e,[t,n])=>e+(n-t),0)||1,v=0;try{let r=-1/0;for(let[i,a]of t)for(let t=i;t<a;t+=aO){if(n.signal?.aborted)throw sO();let i=Math.min(a,t+aO),o=await e.unitsBetween(t,i),s=o.filter(e=>e.seq>r),c=o.some(e=>e.seq===r)?0:s.findIndex(e=>e.key),l=c<0?[]:s.slice(c);for(let e of l){if(m)throw m;if(n.signal?.aborted)throw sO();for(;h.decodeQueueSize>oO;)await g();h.decode(new EncodedVideoChunk({type:e.key?`key`:`delta`,timestamp:Math.round(e.t*1e6),data:e.data})),r=e.seq}v+=i-t,n.onProgress?.(Math.min(1,v/_))}if(await h.flush(),m)throw m}finally{h.state!==`closed`&&h.close()}let y=a.map((e,t)=>t).sort((e,t)=>a[e]-a[t]),b=rO*iO,x=new Float32Array(y.length*b),S=new Float32Array(y.length*b);return y.forEach((e,t)=>{x.set(o.slice(e*b,e*b+b),t*b),S.set(s.slice(e*b,e*b+b),t*b)}),{t:Float64Array.from(y,e=>a[e]),cells:b,levels:x,diffs:S}}async function lO(e,t={}){let n=performance.now(),r=(e,t=0)=>({...e,elapsedMs:performance.now()-n,frames:t}),i=e.video.range();if(!i)return r({ok:!1,reason:`this camera recorded no video`});let a=e.schema.filter(t=>t.type===`number`&&t.name!==e.timeKey).map(e=>e.name),o=await _D(e.data,e.timeKey,a);if(t.signal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);t.onProgress?.(.05);let s=o.t.map(t=>t+e.wallOrigin),c=[...o.cols].map(([t,n])=>{let r=[];for(let e=0;e<n.length;e++)Number.isFinite(n[e])&&Number.isFinite(s[e])&&r.push(e);let i=e.schema.find(e=>e.name===t)?.unit;return r.length===n.length?{name:t,t:s,v:n,unit:i}:{name:t,unit:i,t:Float64Array.from(r,e=>s[e]),v:Float64Array.from(r,e=>n[e])}}),l=[Math.max(i[0],s[0]??1/0),Math.min(i[1],s[s.length-1]??-1/0)];if(!(l[1]-l[0]>5))return r({ok:!1,reason:`the video and the data overlap too little`});let u=UD(XD(c),l).filter(e=>e.activity>.05).slice(0,t.estimate?.maxChannels??8);if(!u.length)return r({ok:!1,reason:`no channel changes enough at 10 Hz or more`});let{video:d}=WD(u,l,t.estimate);if(!d.length)return r({ok:!1,reason:`the recording is too short`});let f=await cO(e.video,d,{signal:t.signal,onProgress:e=>t.onProgress?.(.05+.9*e)}),p=$D(f,u,t.estimate);return t.onProgress?.(1),r(p,f.t.length)}var uO=15,dO=12,fO=20261119,pO=(()=>{let e=[],t=fO,n=0;for(;;){t=t*48271%2147483647;let r=340+t%861;if(n+r>=12*1e3)return e;n+=r,e.push(r)}})(),mO=(()=>{let e=[{at:0,level:1}],t=0;for(let n of pO)t+=n/1e3,e.push({at:t,level:e.length%2?0:1});return e[e.length-1].level===1&&e.push({at:12,level:0}),e})();function hO(e){let t=e-Math.floor(e/15)*15,n=0;for(let e of mO)if(e.at<=t)n=e.level;else break;return n}var gO=(e,t=2)=>Math.ceil((e+t)/15)*15,_O=e=>mO.map(t=>({t:e+t.at,level:t.level})),vO=-.1,yO=3,bO=.01,xO=5e-4,SO=.03,CO=.8;function wO(e,t){let n=e.t.length;if(t.length<4)return{ok:!1,reason:`too few flashes were shown`,frames:n};let r=t.map(e=>e.t),i=t.map(e=>e.level),a=[0];for(let e=1;e<r.length;e++)a.push(a[e-1]+i[e-1]*(r[e]-r[e-1]));let o=e=>{let t=0,n=r.length;for(;t<n;){let i=t+n>>1;r[i]<=e?t=i+1:n=i}return t-1},s=e=>{let t=o(e);return t<0?0:i[t]},c=e=>{let t=o(e);return t<0?0:a[t]+i[t]*(e-r[t])},l=(e,t,n)=>n<=0?s(e-t):(c(e-t)-c(e-t-n))/n,u=[];for(let t=0;t<n;t++)e.t[t]>=r[0]-.5&&e.t[t]<=r[r.length-1]+yO+.5&&u.push(t);if(u.length<30)return{ok:!1,reason:`the camera sent too few frames while the screen flashed`,frames:u.length};let d=u.slice(1).map((t,n)=>e.t[t]-e.t[u[n]]).sort((e,t)=>e-t),f=d[d.length>>1],p=e.cells,m=(t,n,r)=>{let i=0,a=0,o=0,s=0,c=0;for(let d of u){let u=l(e.t[d],n,r),f=e.levels[d*p+t];i+=u,a+=f,o+=u*u,s+=f*f,c+=u*f}let d=u.length,f=o-i*i/d,m=s-a*a/d;return f>1e-12&&m>1e-12?(c-i*a/d)/Math.sqrt(f*m):0},h={r:-1/0,cell:0,lag:0};for(let e=0;e<p;e++)for(let t=vO;t<=yO+1e-9;t+=bO){let n=m(e,t,0);n>h.r&&(h={r:n,cell:e,lag:t})}if(!(h.r>=CO*.9))return{ok:!1,reason:`the camera didn’t see the flashes: point it at the screen and try again`,frames:u.length};let g={r:-1/0,e:0,lags:[],rs:[]};for(let e of[0,1,2,3,4,5,6,7,8].map(e=>e*f/8)){let t=[],n=[],r=h.lag-e/2;for(let i=r-SO;i<=r+SO+1e-9;i+=xO)t.push(i),n.push(m(h.cell,i,e));let i=Math.max(...n);i>g.r+1e-9&&(g={r:i,e,lags:t,rs:n})}if(g.r<CO)return{ok:!1,reason:`the flashes were too faint or blurred: closer, or the screen brighter, and try again`,frames:u.length};let _=g.rs.indexOf(g.r),v=_,y=_;for(;v>0&&g.rs[v-1]>=g.r-1e-9;)v--;for(;y<g.rs.length-1&&g.rs[y+1]>=g.r-1e-9;)y++;let b=_,x=_;for(;b>0&&g.rs[b-1]>=g.r*.995;)b--;for(;x<g.rs.length-1&&g.rs[x+1]>=g.r*.995;)x++;return{ok:!0,offsetMs:((g.lags[v]+g.lags[y])/2+g.e/2)*1e3,spreadMs:Math.max(.5,(g.lags[x]-g.lags[b])*500),confidence:Math.max(0,Math.min(1,g.r)),cell:h.cell,frames:u.length,switches:t.length}}var TO=3e3;async function EO(e,t,n,r=5,i=TO){let a=e.replace(/\/+$/,``).replace(/^ws(s?):\/\//,`http$1://`)+`/v1/time`,o=null;for(let e=0;e<r;e++)try{let e=n(),r=await t(a,{cache:`no-store`,signal:AbortSignal.timeout(i)}),s=n(),c=Number((await r.json()).t),l=s-e;if(!Number.isFinite(c)||l<0)continue;(!o||l<o.rttMs)&&(o={offsetMs:(e+s)/2-c,rttMs:l})}catch{}return o}var DO=e=>e?{clock_offset_ms:Math.round(e.offsetMs*10)/10,clock_rtt_ms:Math.round(e.rttMs*10)/10}:{},OO=class extends Error{code;detail;constructor(e,t){super(e),this.name=`KymoscopeError`,this.code=e,this.detail=t}};function kO(e){let t=new URL(e,location.href);if(t.origin===location.origin)return new Worker(t,{type:`module`});let n=URL.createObjectURL(new Blob([`import ${JSON.stringify(t.href)};`],{type:`text/javascript`}));try{return new Worker(n,{type:`module`})}finally{URL.revokeObjectURL(n)}}var AO=``+new URL(`assets/parseDataset.worker-PynRsPD8.js`,import.meta.url).href;function jO(){return kO(AO)}function MO(e,t=jO,n){return new Promise((r,i)=>{if(n?.aborted){i(new OO(`cancelled`));return}let a=t(),o=()=>{a.terminate(),i(new OO(`cancelled`))};n?.addEventListener(`abort`,o,{once:!0}),a.onmessage=e=>{if(n?.removeEventListener(`abort`,o),a.terminate(),e.data.ok){let{table:t,...n}=e.data.data;r({...n,rows:Pe(t)})}else i(Error(e.data.error))},a.onerror=e=>{n?.removeEventListener(`abort`,o),a.terminate(),i(e instanceof Error?e:Error(`Worker failed to parse the dataset.`))},a.postMessage(e)})}async function NO(e,t){if(typeof Worker<`u`)return MO(e,jO,t);let{table:n,...r}=je(`file`in e?await e.file.text():e.rawText,e.config);return{...r,rows:Pe(n)}}var PO=me(new WeakMap);function FO(e){let t=PO.get(e);if(t===void 0){t=!0;for(let n=0;n<e.length;n++)if(!(e[n]>=(n>0?e[n-1]:-1/0))){t=!1;break}PO.set(e,t)}return t}var IO=class{#e;constructor(e){this.#e=e}async getSchema(){let{columnNames:e,units:t,rows:n}=this.#e;return e.map((e,r)=>({name:e,type:Le(n,e)?`number`:`string`,unit:t[r]??``}))}async getSeries(e){let{rows:t}=this.#e,n=Ue(t);if(n){let r=_e(n,e.viewport.xKey),i=_e(n,e.column),a=new Float64Array(t.length),o=new Float64Array(t.length),s=0;if(r&&i)for(let e=0;e<r.length;e++)r[e]===r[e]&&i[e]===i[e]&&(a[s]=r[e],o[s]=i[e],s++);return H(a.subarray(0,s),o.subarray(0,s),e.viewport.x0,e.viewport.x1,e.maxPoints)}let r=new Float64Array(t.length),i=new Float64Array(t.length),a=0;for(let n of t){let t=n[e.viewport.xKey],o=n[e.column];typeof t==`number`&&typeof o==`number`&&(r[a]=t,i[a]=o,a++)}return H(r.subarray(0,a),i.subarray(0,a),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.rows,i=new Set(this.#e.columnNames),a=i.has(t.xKey)?e.filter(e=>i.has(e)):[];if(a.length===0)return{x0:t.x0,bucket:0,rows:[],columns:a};let o=Ue(r),s=o&&_e(o,t.xKey),c=o?a.map(e=>_e(o,e)):[];if(s&&c.every(e=>e))return k(s,c,a,t.x0,t.x1,n);let l=new Float64Array(r.length),u=a.map(()=>new Float64Array(r.length));for(let e=0;e<r.length;e++){let n=r[e][t.xKey];l[e]=typeof n==`number`?n:NaN;for(let t=0;t<a.length;t++){let n=r[e][a[t]];u[t][e]=typeof n==`number`?n:NaN}}return k(l,u,a,t.x0,t.x1,n)}getColumnsSync(e,n,r){let i=Ue(this.#e.rows),a=i&&_e(i,n.xKey);if(!i||!a)return null;let o=e.filter(e=>_e(i,e));return o.length===0?null:t(a,o.map(e=>_e(i,e)),o,n.x0,n.x1,r)}async readColumns(e,t,n){let{rows:r,columnNames:i}=this.#e,a=Ue(r),o=Math.min(r.length,t+n),s={};for(let n of e){if(!i.includes(n))continue;let e=a&&_e(a,n);if(e){s[n]=e.slice(t,o);continue}let c=new Float64Array(Math.max(0,o-t));for(let e=t;e<o;e++){let i=r[e][n];c[e-t]=typeof i==`number`?i:NaN}s[n]=c}return s}async xBounds(e){return this.xBoundsSync(e)}xBoundsSync(e){let{rows:t}=this.#e,n=Ue(t),r=n&&_e(n,e),i=1/0,a=-1/0;if(r&&r.length>0&&FO(r))i=r[0],a=r[r.length-1];else if(r)for(let e=0;e<r.length;e++){let t=r[e];t<i&&(i=t),t>a&&(a=t)}else for(let n of t){let t=n[e];typeof t==`number`&&(t<i&&(i=t),t>a&&(a=t))}return i<=a?{x0:i,x1:a}:{x0:0,x1:0}}async dispose(){}};function LO(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function RO(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function zO(e){return this instanceof zO?(this.v=e,this):new zO(e)}function BO(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof zO?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function VO(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:zO(e[r](t)),done:!1}:i?i(t):t}:i}}function HO(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof RO==`function`?RO(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var UO=new TextDecoder(`utf-8`),WO=e=>UO.decode(e),GO=new TextEncoder,KO=e=>GO.encode(e),qO=e=>typeof e==`number`,JO=e=>typeof e==`boolean`,YO=e=>typeof e==`function`,XO=e=>e!=null&&Object(e)===e,ZO=e=>XO(e)&&YO(e.then),QO=e=>XO(e)&&YO(e[Symbol.iterator]),$O=e=>XO(e)&&YO(e[Symbol.asyncIterator]),ek=e=>XO(e)&&XO(e.schema),tk=e=>XO(e)&&`done`in e&&`value`in e,nk=e=>XO(e)&&YO(e.stat)&&qO(e.fd),rk=e=>XO(e)&&ok(e.body),ik=e=>`_getDOMStream`in e&&`_getNodeStream`in e,ak=e=>XO(e)&&YO(e.abort)&&YO(e.getWriter)&&!ik(e),ok=e=>XO(e)&&YO(e.cancel)&&YO(e.getReader)&&!ik(e),sk=e=>XO(e)&&YO(e.end)&&YO(e.write)&&JO(e.writable)&&!ik(e),ck=e=>XO(e)&&YO(e.read)&&YO(e.pipe)&&JO(e.readable)&&!ik(e),lk=e=>XO(e)&&YO(e.clear)&&YO(e.bytes)&&YO(e.position)&&YO(e.setPosition)&&YO(e.capacity)&&YO(e.getBufferIdentifier)&&YO(e.createLong),uk=typeof SharedArrayBuffer<`u`?SharedArrayBuffer:ArrayBuffer;function dk(e){let t=e[0]?[e[0]]:[],n,r,i,a;for(let o,s,c=0,l=0,u=e.length;++c<u;){if(o=t[l],s=e[c],!o||!s||o.buffer!==s.buffer||s.byteOffset<o.byteOffset){s&&(t[++l]=s);continue}if({byteOffset:n,byteLength:i}=o,{byteOffset:r,byteLength:a}=s,n+i<r||r+a<n){s&&(t[++l]=s);continue}t[l]=new Uint8Array(o.buffer,n,r-n+a)}return t}function fk(e,t,n=0,r=t.byteLength){let i=e.byteLength,a=new Uint8Array(e.buffer,e.byteOffset,i),o=new Uint8Array(t.buffer,t.byteOffset,Math.min(r,i));return a.set(o,n),e}function pk(e,t){let n=dk(e),r=n.reduce((e,t)=>e+t.byteLength,0),i,a,o,s=0,c=-1,l=Math.min(t||1/0,r);for(let e=n.length;++c<e;){if(i=n[c],a=i.subarray(0,Math.min(i.length,l-s)),l<=s+a.length){a.length<i.length?n[c]=i.subarray(a.length):a.length===i.length&&c++,o?fk(o,a,s):o=a;break}fk(o||=new Uint8Array(l),a,s),s+=a.length}return[o||new Uint8Array,n.slice(c),r-(o?o.byteLength:0)]}function mk(e,t){let n=tk(t)?t.value:t;return n instanceof e?e===Uint8Array?new e(n.buffer,n.byteOffset,n.byteLength):n:n?(typeof n==`string`&&(n=KO(n)),n instanceof ArrayBuffer||n instanceof uk?new e(n):lk(n)?mk(e,n.bytes()):ArrayBuffer.isView(n)?n.byteLength<=0?new e(0):new e(n.buffer,n.byteOffset,n.byteLength/e.BYTES_PER_ELEMENT):e.from(n)):new e(0)}var hk=e=>mk(Int32Array,e),gk=e=>mk(BigInt64Array,e),_k=e=>mk(Uint8Array,e),vk=e=>(e.next(),e);function*yk(e,t){let n=function*(e){yield e};return yield*vk((function*(t){let n=null;do n=t.next(yield mk(e,n));while(!n.done)})((typeof t==`string`||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof uk?n(t):QO(t)?t:n(t))[Symbol.iterator]())),new e}var bk=e=>yk(Uint8Array,e);function xk(e,t){return BO(this,arguments,function*(){if(ZO(t))return yield zO(yield zO(yield*VO(HO(xk(e,yield zO(t))))));let n=function(e){return BO(this,arguments,function*(){yield yield zO(yield zO(e))})};return yield zO(yield*VO(HO(vk((function(t){return BO(this,arguments,function*(){let n=null;do n=yield zO(t.next(yield yield zO(mk(e,n))));while(!n.done)})})((typeof t==`string`||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof uk?n(t):QO(t)?function(e){return BO(this,arguments,function*(){yield zO(yield*VO(HO(vk((function*(e){let t=null;do t=e.next(yield t?.value);while(!t.done)})(e[Symbol.iterator]())))))})}(t):$O(t)?t:n(t))[Symbol.asyncIterator]()))))),yield zO(new e)})}var Sk=e=>xk(Uint8Array,e);function Ck(e,t,n){if(e!==0){n=n.slice(0,t);for(let t=-1,r=n.length;++t<r;)n[t]+=e}return n.subarray(0,t)}function wk(e,t){let n=0,r=e.length;if(r!==t.length)return!1;if(r>0)do if(e[n]!==t[n])return!1;while(++n<r);return!0}var Tk={fromIterable(e){return Ek(Dk(e))},fromAsyncIterable(e){return Ek(Ok(e))},fromDOMStream(e){return Ek(kk(e))},fromNodeStream(e){return Ek(Mk(e))},toDOMStream(e,t){throw Error(`"toDOMStream" not available in this environment`)},toNodeStream(e,t){throw Error(`"toNodeStream" not available in this environment`)}},Ek=e=>(e.next(),e);function*Dk(e){let t,n=!1,r=[],i,a,o,s=0;function c(){return a===`peek`?pk(r,o)[0]:([i,r,s]=pk(r,o),i)}({cmd:a,size:o}=(yield null)||{cmd:`read`,size:0});let l=bk(e)[Symbol.iterator]();try{do if({done:t,value:i}=Number.isNaN(o-s)?l.next():l.next(o-s),!t&&i.byteLength>0&&(r.push(i),s+=i.byteLength),t||o<=s)do({cmd:a,size:o}=yield c());while(o<s);while(!t)}catch(e){(n=!0)&&typeof l.throw==`function`&&l.throw(e)}finally{n===!1&&typeof l.return==`function`&&l.return(null)}return null}function Ok(e){return BO(this,arguments,function*(){let t,n=!1,r=[],i,a,o,s=0;function c(){return a===`peek`?pk(r,o)[0]:([i,r,s]=pk(r,o),i)}({cmd:a,size:o}=(yield yield zO(null))||{cmd:`read`,size:0});let l=Sk(e)[Symbol.asyncIterator]();try{do if({done:t,value:i}=Number.isNaN(o-s)?yield zO(l.next()):yield zO(l.next(o-s)),!t&&i.byteLength>0&&(r.push(i),s+=i.byteLength),t||o<=s)do({cmd:a,size:o}=yield yield zO(c()));while(o<s);while(!t)}catch(e){(n=!0)&&typeof l.throw==`function`&&(yield zO(l.throw(e)))}finally{n===!1&&typeof l.return==`function`&&(yield zO(l.return(new Uint8Array)))}return yield zO(null)})}function kk(e){return BO(this,arguments,function*(){let t=!1,n=!1,r=[],i,a,o,s=0;function c(){return a===`peek`?pk(r,o)[0]:([i,r,s]=pk(r,o),i)}({cmd:a,size:o}=(yield yield zO(null))||{cmd:`read`,size:0});let l=new Ak(e);try{do if({done:t,value:i}=Number.isNaN(o-s)?yield zO(l.read()):yield zO(l.read(o-s)),!t&&i.byteLength>0&&(r.push(_k(i)),s+=i.byteLength),t||o<=s)do({cmd:a,size:o}=yield yield zO(c()));while(o<s);while(!t)}catch(e){(n=!0)&&(yield zO(l.cancel(e)))}finally{n===!1?yield zO(l.cancel()):e.locked&&l.releaseLock()}return yield zO(null)})}var Ak=class{constructor(e){this.source=e,this.reader=null,this.reader=this.source.getReader(),this.reader.closed.catch(()=>{})}get closed(){return this.reader?this.reader.closed.catch(()=>{}):Promise.resolve()}releaseLock(){this.reader&&this.reader.releaseLock(),this.reader=null}cancel(e){return LO(this,void 0,void 0,function*(){let{reader:t,source:n}=this;t&&(yield t.cancel(e).catch(()=>{})),n&&n.locked&&this.releaseLock()})}read(e){return LO(this,void 0,void 0,function*(){if(e===0)return{done:this.reader==null,value:new Uint8Array};let t=yield this.reader.read();return!t.done&&(t.value=_k(t)),t})}},jk=(e,t)=>{let n=e=>r([t,e]),r;return[t,n,new Promise(i=>(r=i)&&e.once(t,n))]};function Mk(e){return BO(this,arguments,function*(){let t=[],n=`error`,r=!1,i=null,a,o,s=0,c=[],l;function u(){return a===`peek`?pk(c,o)[0]:([l,c,s]=pk(c,o),l)}if({cmd:a,size:o}=(yield yield zO(null))||{cmd:`read`,size:0},e.isTTY)return yield yield zO(new Uint8Array),yield zO(null);try{t[0]=jk(e,`end`),t[1]=jk(e,`error`);do{if(t[2]=jk(e,`readable`),[n,i]=yield zO(Promise.race(t.map(e=>e[2]))),n===`error`)break;if((r=n===`end`)||(Number.isFinite(o-s)?(l=_k(e.read(o-s)),l.byteLength<o-s&&(l=_k(e.read()))):l=_k(e.read()),l.byteLength>0&&(c.push(l),s+=l.byteLength)),r||o<=s)do({cmd:a,size:o}=yield yield zO(u()));while(o<s)}while(!r)}finally{yield zO(d(t,n===`error`?i:null))}return yield zO(null);function d(t,n){return l=c=null,new Promise((r,i)=>{for(let[n,r]of t)e.off(n,r);try{let t=e.destroy;t&&t.call(e,n),n=void 0}catch(e){n=e||n}finally{n==null?r():i(n)}})}})}var Nk;(function(e){e[e.V1=0]=`V1`,e[e.V2=1]=`V2`,e[e.V3=2]=`V3`,e[e.V4=3]=`V4`,e[e.V5=4]=`V5`})(Nk||={});var Pk;(function(e){e[e.Sparse=0]=`Sparse`,e[e.Dense=1]=`Dense`})(Pk||={});var Fk;(function(e){e[e.HALF=0]=`HALF`,e[e.SINGLE=1]=`SINGLE`,e[e.DOUBLE=2]=`DOUBLE`})(Fk||={});var Ik;(function(e){e[e.DAY=0]=`DAY`,e[e.MILLISECOND=1]=`MILLISECOND`})(Ik||={});var Lk;(function(e){e[e.SECOND=0]=`SECOND`,e[e.MILLISECOND=1]=`MILLISECOND`,e[e.MICROSECOND=2]=`MICROSECOND`,e[e.NANOSECOND=3]=`NANOSECOND`})(Lk||={});var Rk;(function(e){e[e.YEAR_MONTH=0]=`YEAR_MONTH`,e[e.DAY_TIME=1]=`DAY_TIME`,e[e.MONTH_DAY_NANO=2]=`MONTH_DAY_NANO`})(Rk||={});var zk=new Int32Array(2),Bk=new Float32Array(zk.buffer),Vk=new Float64Array(zk.buffer),Hk=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,Uk;(function(e){e[e.UTF8_BYTES=1]=`UTF8_BYTES`,e[e.UTF16_STRING=2]=`UTF16_STRING`})(Uk||={});var Wk=class e{constructor(e){this.bytes_=e,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(t){return new e(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return BigInt.asIntN(64,BigInt(this.readUint32(e))+(BigInt(this.readUint32(e+4))<<BigInt(32)))}readUint64(e){return BigInt.asUintN(64,BigInt(this.readUint32(e))+(BigInt(this.readUint32(e+4))<<BigInt(32)))}readFloat32(e){return zk[0]=this.readInt32(e),Bk[0]}readFloat64(e){return zk[+!Hk]=this.readInt32(e),zk[+!!Hk]=this.readInt32(e+4),Vk[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,Number(BigInt.asIntN(32,t))),this.writeInt32(e+4,Number(BigInt.asIntN(32,t>>BigInt(32))))}writeUint64(e,t){this.writeUint32(e,Number(BigInt.asUintN(32,t))),this.writeUint32(e+4,Number(BigInt.asUintN(32,t>>BigInt(32))))}writeFloat32(e,t){Bk[0]=t,this.writeInt32(e,zk[0])}writeFloat64(e,t){Vk[0]=t,this.writeInt32(e,zk[+!Hk]),this.writeInt32(e+4,zk[+!!Hk])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw Error(`FlatBuffers: ByteBuffer is too short to contain an identifier.`);let e=``;for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let n=this.readInt32(e);e+=4;let r=this.bytes_.subarray(e,e+n);return t===Uk.UTF8_BYTES?r:this.text_decoder_.decode(r)}__union_with_string(e,t){return typeof e==`string`?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw Error(`FlatBuffers: file identifier must be length 4`);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createScalarList(e,t){let n=[];for(let r=0;r<t;++r){let t=e(r);t!==null&&n.push(t)}return n}createObjList(e,t){let n=[];for(let r=0;r<t;++r){let t=e(r);t!==null&&n.push(t.unpack())}return n}},Gk=class e{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null,this.text_encoder=new TextEncoder;let t;t=e||1024,this.bb=Wk.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(t,n){t>this.minalign&&(this.minalign=t);let r=~(this.bb.capacity()-this.space+n)+1&t-1;for(;this.space<r+t+n;){let t=this.bb.capacity();this.bb=e.growByteBuffer(this.bb),this.space+=this.bb.capacity()-t}this.pad(r)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(--this.space,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,n){(this.force_defaults||t!==n)&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,n){t!=n&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw TypeError(`FlatBuffers: struct must be serialized inline.`)}notNested(){if(this.isNested)throw TypeError(`FlatBuffers: object serialization must not be nested.`)}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw Error(`FlatBuffers: cannot grow buffer beyond 2 gigabytes.`);let n=t<<1,r=Wk.allocate(n);return r.setPosition(n-t),r.bytes().set(e.bytes(),n-t),r}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable??=[],this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw Error(`FlatBuffers: endObject called without startObject`);this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let n=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]==0?0:e-this.vtable[t]);this.addInt16(e-this.object_start);let r=(n+2)*2;this.addInt16(r);let i=0,a=this.space;outer_loop:for(t=0;t<this.vtables.length;t++){let e=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(e)){for(let t=2;t<r;t+=2)if(this.bb.readInt16(a+t)!=this.bb.readInt16(e+t))continue outer_loop;i=this.vtables[t];break}}return i?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,i-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,n){let r=n?4:0;if(t){let e=t;if(this.prep(this.minalign,8+r),e.length!=4)throw TypeError(`FlatBuffers: file identifier must be length 4`);for(let t=3;t>=0;t--)this.writeInt8(e.charCodeAt(t))}this.prep(this.minalign,4+r),this.addOffset(e),r&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let n=this.bb.capacity()-e,r=n-this.bb.readInt32(n);if(!(t<this.bb.readInt16(r)&&this.bb.readInt16(r+t)!=0))throw TypeError(`FlatBuffers: field `+t+` must be set`)}startVector(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(n,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||=new Map,this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(e==null)return 0;let t;return t=e instanceof Uint8Array?e:this.text_encoder.encode(e),this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length),this.bb.bytes().set(t,this.space),this.endVector()}createByteVector(e){return e==null?0:(this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length),this.bb.bytes().set(e,this.space),this.endVector())}createObjectOffset(e){return e===null?0:typeof e==`string`?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n];if(r!==null)t.push(this.createObjectOffset(r));else throw TypeError(`FlatBuffers: Argument for createObjectOffsetList cannot contain null.`)}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e.slice().reverse()),this.endVector()}},Kk;(function(e){e[e.BUFFER=0]=`BUFFER`})(Kk||={});var qk;(function(e){e[e.LZ4_FRAME=0]=`LZ4_FRAME`,e[e.ZSTD=1]=`ZSTD`})(qk||={});var Jk=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsBodyCompression(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsBodyCompression(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}codec(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt8(this.bb_pos+e):qk.LZ4_FRAME}method(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt8(this.bb_pos+e):Kk.BUFFER}static startBodyCompression(e){e.startObject(2)}static addCodec(e,t){e.addFieldInt8(0,t,qk.LZ4_FRAME)}static addMethod(e,t){e.addFieldInt8(1,t,Kk.BUFFER)}static endBodyCompression(e){return e.endObject()}static createBodyCompression(t,n,r){return e.startBodyCompression(t),e.addCodec(t,n),e.addMethod(t,r),e.endBodyCompression(t)}},Yk=class{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}offset(){return this.bb.readInt64(this.bb_pos)}length(){return this.bb.readInt64(this.bb_pos+8)}static sizeOf(){return 16}static createBuffer(e,t,n){return e.prep(8,16),e.writeInt64(BigInt(n??0)),e.writeInt64(BigInt(t??0)),e.offset()}},Xk=class{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}length(){return this.bb.readInt64(this.bb_pos)}nullCount(){return this.bb.readInt64(this.bb_pos+8)}static sizeOf(){return 16}static createFieldNode(e,t,n){return e.prep(8,16),e.writeInt64(BigInt(n??0)),e.writeInt64(BigInt(t??0)),e.offset()}},Zk=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsRecordBatch(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsRecordBatch(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}length(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt64(this.bb_pos+e):BigInt(`0`)}nodes(e,t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new Xk).__init(this.bb.__vector(this.bb_pos+n)+e*16,this.bb):null}nodesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}buffers(e,t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new Yk).__init(this.bb.__vector(this.bb_pos+n)+e*16,this.bb):null}buffersLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}compression(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Jk).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}static startRecordBatch(e){e.startObject(4)}static addLength(e,t){e.addFieldInt64(0,t,BigInt(`0`))}static addNodes(e,t){e.addFieldOffset(1,t,0)}static startNodesVector(e,t){e.startVector(16,t,8)}static addBuffers(e,t){e.addFieldOffset(2,t,0)}static startBuffersVector(e,t){e.startVector(16,t,8)}static addCompression(e,t){e.addFieldOffset(3,t,0)}static endRecordBatch(e){return e.endObject()}},Qk=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDictionaryBatch(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDictionaryBatch(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}id(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt64(this.bb_pos+e):BigInt(`0`)}data(e){let t=this.bb.__offset(this.bb_pos,6);return t?(e||new Zk).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}isDelta(){let e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startDictionaryBatch(e){e.startObject(3)}static addId(e,t){e.addFieldInt64(0,t,BigInt(`0`))}static addData(e,t){e.addFieldOffset(1,t,0)}static addIsDelta(e,t){e.addFieldInt8(2,+t,0)}static endDictionaryBatch(e){return e.endObject()}},$k;(function(e){e[e.Little=0]=`Little`,e[e.Big=1]=`Big`})($k||={});var eA;(function(e){e[e.DenseArray=0]=`DenseArray`})(eA||={});var tA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsInt(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInt(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}bitWidth(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):0}isSigned(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startInt(e){e.startObject(2)}static addBitWidth(e,t){e.addFieldInt32(0,t,0)}static addIsSigned(e,t){e.addFieldInt8(1,+t,0)}static endInt(e){return e.endObject()}static createInt(t,n,r){return e.startInt(t),e.addBitWidth(t,n),e.addIsSigned(t,r),e.endInt(t)}},nA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDictionaryEncoding(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDictionaryEncoding(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}id(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt64(this.bb_pos+e):BigInt(`0`)}indexType(e){let t=this.bb.__offset(this.bb_pos,6);return t?(e||new tA).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}isOrdered(){let e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}dictionaryKind(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt16(this.bb_pos+e):eA.DenseArray}static startDictionaryEncoding(e){e.startObject(4)}static addId(e,t){e.addFieldInt64(0,t,BigInt(`0`))}static addIndexType(e,t){e.addFieldOffset(1,t,0)}static addIsOrdered(e,t){e.addFieldInt8(2,+t,0)}static addDictionaryKind(e,t){e.addFieldInt16(3,t,eA.DenseArray)}static endDictionaryEncoding(e){return e.endObject()}},rA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsKeyValue(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKeyValue(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}key(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}value(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}static startKeyValue(e){e.startObject(2)}static addKey(e,t){e.addFieldOffset(0,t,0)}static addValue(e,t){e.addFieldOffset(1,t,0)}static endKeyValue(e){return e.endObject()}static createKeyValue(t,n,r){return e.startKeyValue(t),e.addKey(t,n),e.addValue(t,r),e.endKeyValue(t)}},iA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsBinary(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsBinary(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startBinary(e){e.startObject(0)}static endBinary(e){return e.endObject()}static createBinary(t){return e.startBinary(t),e.endBinary(t)}},aA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsBool(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsBool(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startBool(e){e.startObject(0)}static endBool(e){return e.endObject()}static createBool(t){return e.startBool(t),e.endBool(t)}},oA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDate(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDate(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}unit(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Ik.MILLISECOND}static startDate(e){e.startObject(1)}static addUnit(e,t){e.addFieldInt16(0,t,Ik.MILLISECOND)}static endDate(e){return e.endObject()}static createDate(t,n){return e.startDate(t),e.addUnit(t,n),e.endDate(t)}},sA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDecimal(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDecimal(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}precision(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):0}scale(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt32(this.bb_pos+e):0}bitWidth(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt32(this.bb_pos+e):128}static startDecimal(e){e.startObject(3)}static addPrecision(e,t){e.addFieldInt32(0,t,0)}static addScale(e,t){e.addFieldInt32(1,t,0)}static addBitWidth(e,t){e.addFieldInt32(2,t,128)}static endDecimal(e){return e.endObject()}static createDecimal(t,n,r,i){return e.startDecimal(t),e.addPrecision(t,n),e.addScale(t,r),e.addBitWidth(t,i),e.endDecimal(t)}},cA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDuration(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDuration(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}unit(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Lk.MILLISECOND}static startDuration(e){e.startObject(1)}static addUnit(e,t){e.addFieldInt16(0,t,Lk.MILLISECOND)}static endDuration(e){return e.endObject()}static createDuration(t,n){return e.startDuration(t),e.addUnit(t,n),e.endDuration(t)}},lA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFixedSizeBinary(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFixedSizeBinary(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}byteWidth(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):0}static startFixedSizeBinary(e){e.startObject(1)}static addByteWidth(e,t){e.addFieldInt32(0,t,0)}static endFixedSizeBinary(e){return e.endObject()}static createFixedSizeBinary(t,n){return e.startFixedSizeBinary(t),e.addByteWidth(t,n),e.endFixedSizeBinary(t)}},uA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFixedSizeList(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFixedSizeList(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}listSize(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):0}static startFixedSizeList(e){e.startObject(1)}static addListSize(e,t){e.addFieldInt32(0,t,0)}static endFixedSizeList(e){return e.endObject()}static createFixedSizeList(t,n){return e.startFixedSizeList(t),e.addListSize(t,n),e.endFixedSizeList(t)}},dA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFloatingPoint(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFloatingPoint(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}precision(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Fk.HALF}static startFloatingPoint(e){e.startObject(1)}static addPrecision(e,t){e.addFieldInt16(0,t,Fk.HALF)}static endFloatingPoint(e){return e.endObject()}static createFloatingPoint(t,n){return e.startFloatingPoint(t),e.addPrecision(t,n),e.endFloatingPoint(t)}},fA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsInterval(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInterval(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}unit(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Rk.YEAR_MONTH}static startInterval(e){e.startObject(1)}static addUnit(e,t){e.addFieldInt16(0,t,Rk.YEAR_MONTH)}static endInterval(e){return e.endObject()}static createInterval(t,n){return e.startInterval(t),e.addUnit(t,n),e.endInterval(t)}},pA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsLargeBinary(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsLargeBinary(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startLargeBinary(e){e.startObject(0)}static endLargeBinary(e){return e.endObject()}static createLargeBinary(t){return e.startLargeBinary(t),e.endLargeBinary(t)}},mA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsLargeUtf8(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsLargeUtf8(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startLargeUtf8(e){e.startObject(0)}static endLargeUtf8(e){return e.endObject()}static createLargeUtf8(t){return e.startLargeUtf8(t),e.endLargeUtf8(t)}},hA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsList(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsList(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startList(e){e.startObject(0)}static endList(e){return e.endObject()}static createList(t){return e.startList(t),e.endList(t)}},gA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMap(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMap(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}keysSorted(){let e=this.bb.__offset(this.bb_pos,4);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startMap(e){e.startObject(1)}static addKeysSorted(e,t){e.addFieldInt8(0,+t,0)}static endMap(e){return e.endObject()}static createMap(t,n){return e.startMap(t),e.addKeysSorted(t,n),e.endMap(t)}},_A=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsNull(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNull(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startNull(e){e.startObject(0)}static endNull(e){return e.endObject()}static createNull(t){return e.startNull(t),e.endNull(t)}},vA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsStruct_(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsStruct_(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startStruct_(e){e.startObject(0)}static endStruct_(e){return e.endObject()}static createStruct_(t){return e.startStruct_(t),e.endStruct_(t)}},yA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTime(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTime(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}unit(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Lk.MILLISECOND}bitWidth(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt32(this.bb_pos+e):32}static startTime(e){e.startObject(2)}static addUnit(e,t){e.addFieldInt16(0,t,Lk.MILLISECOND)}static addBitWidth(e,t){e.addFieldInt32(1,t,32)}static endTime(e){return e.endObject()}static createTime(t,n,r){return e.startTime(t),e.addUnit(t,n),e.addBitWidth(t,r),e.endTime(t)}},bA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTimestamp(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTimestamp(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}unit(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Lk.SECOND}timezone(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}static startTimestamp(e){e.startObject(2)}static addUnit(e,t){e.addFieldInt16(0,t,Lk.SECOND)}static addTimezone(e,t){e.addFieldOffset(1,t,0)}static endTimestamp(e){return e.endObject()}static createTimestamp(t,n,r){return e.startTimestamp(t),e.addUnit(t,n),e.addTimezone(t,r),e.endTimestamp(t)}},xA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsUnion(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsUnion(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}mode(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Pk.Sparse}typeIds(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt32(this.bb.__vector(this.bb_pos+t)+e*4):0}typeIdsLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}typeIdsArray(){let e=this.bb.__offset(this.bb_pos,6);return e?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}static startUnion(e){e.startObject(2)}static addMode(e,t){e.addFieldInt16(0,t,Pk.Sparse)}static addTypeIds(e,t){e.addFieldOffset(1,t,0)}static createTypeIdsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addInt32(t[n]);return e.endVector()}static startTypeIdsVector(e,t){e.startVector(4,t,4)}static endUnion(e){return e.endObject()}static createUnion(t,n,r){return e.startUnion(t),e.addMode(t,n),e.addTypeIds(t,r),e.endUnion(t)}},SA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsUtf8(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsUtf8(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static startUtf8(e){e.startObject(0)}static endUtf8(e){return e.endObject()}static createUtf8(t){return e.startUtf8(t),e.endUtf8(t)}},CA;(function(e){e[e.NONE=0]=`NONE`,e[e.Null=1]=`Null`,e[e.Int=2]=`Int`,e[e.FloatingPoint=3]=`FloatingPoint`,e[e.Binary=4]=`Binary`,e[e.Utf8=5]=`Utf8`,e[e.Bool=6]=`Bool`,e[e.Decimal=7]=`Decimal`,e[e.Date=8]=`Date`,e[e.Time=9]=`Time`,e[e.Timestamp=10]=`Timestamp`,e[e.Interval=11]=`Interval`,e[e.List=12]=`List`,e[e.Struct_=13]=`Struct_`,e[e.Union=14]=`Union`,e[e.FixedSizeBinary=15]=`FixedSizeBinary`,e[e.FixedSizeList=16]=`FixedSizeList`,e[e.Map=17]=`Map`,e[e.Duration=18]=`Duration`,e[e.LargeBinary=19]=`LargeBinary`,e[e.LargeUtf8=20]=`LargeUtf8`,e[e.LargeList=21]=`LargeList`,e[e.RunEndEncoded=22]=`RunEndEncoded`})(CA||={});var wA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsField(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsField(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}nullable(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}typeType(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readUint8(this.bb_pos+e):CA.NONE}type(e){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__union(e,this.bb_pos+t):null}dictionary(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new nA).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}children(t,n){let r=this.bb.__offset(this.bb_pos,14);return r?(n||new e).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+t*4),this.bb):null}childrenLength(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){let n=this.bb.__offset(this.bb_pos,16);return n?(t||new rA).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+e*4),this.bb):null}customMetadataLength(){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__vector_len(this.bb_pos+e):0}static startField(e){e.startObject(7)}static addName(e,t){e.addFieldOffset(0,t,0)}static addNullable(e,t){e.addFieldInt8(1,+t,0)}static addTypeType(e,t){e.addFieldInt8(2,t,CA.NONE)}static addType(e,t){e.addFieldOffset(3,t,0)}static addDictionary(e,t){e.addFieldOffset(4,t,0)}static addChildren(e,t){e.addFieldOffset(5,t,0)}static createChildrenVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startChildrenVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(6,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endField(e){return e.endObject()}},TA=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSchema(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSchema(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}endianness(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):$k.Little}fields(e,t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new wA).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+e*4),this.bb):null}fieldsLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new rA).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+e*4),this.bb):null}customMetadataLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}features(e){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+e*8):BigInt(0)}featuresLength(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSchema(e){e.startObject(4)}static addEndianness(e,t){e.addFieldInt16(0,t,$k.Little)}static addFields(e,t){e.addFieldOffset(1,t,0)}static createFieldsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startFieldsVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(2,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static addFeatures(e,t){e.addFieldOffset(3,t,0)}static createFeaturesVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startFeaturesVector(e,t){e.startVector(8,t,8)}static endSchema(e){return e.endObject()}static finishSchemaBuffer(e,t){e.finish(t)}static finishSizePrefixedSchemaBuffer(e,t){e.finish(t,void 0,!0)}static createSchema(t,n,r,i,a){return e.startSchema(t),e.addEndianness(t,n),e.addFields(t,r),e.addCustomMetadata(t,i),e.addFeatures(t,a),e.endSchema(t)}},EA;(function(e){e[e.NONE=0]=`NONE`,e[e.Schema=1]=`Schema`,e[e.DictionaryBatch=2]=`DictionaryBatch`,e[e.RecordBatch=3]=`RecordBatch`,e[e.Tensor=4]=`Tensor`,e[e.SparseTensor=5]=`SparseTensor`})(EA||={});var Z;(function(e){e[e.NONE=0]=`NONE`,e[e.Null=1]=`Null`,e[e.Int=2]=`Int`,e[e.Float=3]=`Float`,e[e.Binary=4]=`Binary`,e[e.Utf8=5]=`Utf8`,e[e.Bool=6]=`Bool`,e[e.Decimal=7]=`Decimal`,e[e.Date=8]=`Date`,e[e.Time=9]=`Time`,e[e.Timestamp=10]=`Timestamp`,e[e.Interval=11]=`Interval`,e[e.List=12]=`List`,e[e.Struct=13]=`Struct`,e[e.Union=14]=`Union`,e[e.FixedSizeBinary=15]=`FixedSizeBinary`,e[e.FixedSizeList=16]=`FixedSizeList`,e[e.Map=17]=`Map`,e[e.Duration=18]=`Duration`,e[e.LargeBinary=19]=`LargeBinary`,e[e.LargeUtf8=20]=`LargeUtf8`,e[e.Dictionary=-1]=`Dictionary`,e[e.Int8=-2]=`Int8`,e[e.Int16=-3]=`Int16`,e[e.Int32=-4]=`Int32`,e[e.Int64=-5]=`Int64`,e[e.Uint8=-6]=`Uint8`,e[e.Uint16=-7]=`Uint16`,e[e.Uint32=-8]=`Uint32`,e[e.Uint64=-9]=`Uint64`,e[e.Float16=-10]=`Float16`,e[e.Float32=-11]=`Float32`,e[e.Float64=-12]=`Float64`,e[e.DateDay=-13]=`DateDay`,e[e.DateMillisecond=-14]=`DateMillisecond`,e[e.TimestampSecond=-15]=`TimestampSecond`,e[e.TimestampMillisecond=-16]=`TimestampMillisecond`,e[e.TimestampMicrosecond=-17]=`TimestampMicrosecond`,e[e.TimestampNanosecond=-18]=`TimestampNanosecond`,e[e.TimeSecond=-19]=`TimeSecond`,e[e.TimeMillisecond=-20]=`TimeMillisecond`,e[e.TimeMicrosecond=-21]=`TimeMicrosecond`,e[e.TimeNanosecond=-22]=`TimeNanosecond`,e[e.DenseUnion=-23]=`DenseUnion`,e[e.SparseUnion=-24]=`SparseUnion`,e[e.IntervalDayTime=-25]=`IntervalDayTime`,e[e.IntervalYearMonth=-26]=`IntervalYearMonth`,e[e.DurationSecond=-27]=`DurationSecond`,e[e.DurationMillisecond=-28]=`DurationMillisecond`,e[e.DurationMicrosecond=-29]=`DurationMicrosecond`,e[e.DurationNanosecond=-30]=`DurationNanosecond`})(Z||={});var DA;(function(e){e[e.OFFSET=0]=`OFFSET`,e[e.DATA=1]=`DATA`,e[e.VALIDITY=2]=`VALIDITY`,e[e.TYPE=3]=`TYPE`})(DA||={});var OA=void 0;function kA(e){if(e===null)return`null`;if(e===OA)return`undefined`;switch(typeof e){case`number`:return`${e}`;case`bigint`:return`${e}`;case`string`:return`"${e}"`}return typeof e[Symbol.toPrimitive]==`function`?e[Symbol.toPrimitive](`string`):ArrayBuffer.isView(e)?e instanceof BigInt64Array||e instanceof BigUint64Array?`[${[...e].map(e=>kA(e))}]`:`[${e}]`:ArrayBuffer.isView(e)?`[${e}]`:JSON.stringify(e,(e,t)=>typeof t==`bigint`?`${t}`:t)}function AA(e){if(typeof e==`bigint`&&(e<-(2**53-1)||e>2**53-1))throw TypeError(`${e} is not safe to convert to a number.`);return Number(e)}function jA(e,t){return AA(e/t)+AA(e%t)/AA(t)}var MA=Symbol.for(`isArrowBigNum`);function NA(e,...t){return t.length===0?Object.setPrototypeOf(mk(this.TypedArray,e),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(e,...t),this.constructor.prototype)}NA.prototype[MA]=!0,NA.prototype.toJSON=function(){return`"${zA(this)}"`},NA.prototype.valueOf=function(e){return RA(this,e)},NA.prototype.toString=function(){return zA(this)},NA.prototype[Symbol.toPrimitive]=function(e=`default`){switch(e){case`number`:return RA(this);case`string`:return zA(this);case`default`:return BA(this)}return zA(this)};function PA(...e){return NA.apply(this,e)}function FA(...e){return NA.apply(this,e)}function IA(...e){return NA.apply(this,e)}Object.setPrototypeOf(PA.prototype,Object.create(Int32Array.prototype)),Object.setPrototypeOf(FA.prototype,Object.create(Uint32Array.prototype)),Object.setPrototypeOf(IA.prototype,Object.create(Uint32Array.prototype)),Object.assign(PA.prototype,NA.prototype,{constructor:PA,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array}),Object.assign(FA.prototype,NA.prototype,{constructor:FA,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array}),Object.assign(IA.prototype,NA.prototype,{constructor:IA,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});var LA=BigInt(4294967296)*BigInt(4294967296)-BigInt(1);function RA(e,t){let{buffer:n,byteOffset:r,byteLength:i,signed:a}=e,o=new BigUint64Array(n,r,i/8),s=a&&o.at(-1)&BigInt(1)<<BigInt(63),c=BigInt(0),l=0;if(s){for(let e of o)c|=(e^LA)*(BigInt(1)<<BigInt(64*l++));c*=BigInt(-1),c-=BigInt(1)}else for(let e of o)c|=e*(BigInt(1)<<BigInt(64*l++));if(typeof t==`number`){let e=BigInt(10**t),n=c/e,r=c%e;return AA(n)+AA(r)/AA(e)}return AA(c)}function zA(e){if(e.byteLength===8)return`${new e.BigIntArray(e.buffer,e.byteOffset,1)[0]}`;if(!e.signed)return VA(e);let t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2);if(new Int16Array([t.at(-1)])[0]>=0)return VA(e);t=t.slice();let n=1;for(let e=0;e<t.length;e++){let r=t[e],i=~r+n;t[e]=i,n&=+(r===0)}return`-${VA(t)}`}function BA(e){return e.byteLength===8?new e.BigIntArray(e.buffer,e.byteOffset,1)[0]:zA(e)}function VA(e){let t=``,n=new Uint32Array(2),r=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=new Uint32Array((r=new Uint16Array(r).reverse()).buffer),a=-1,o=r.length-1;do{for(n[0]=r[a=0];a<o;)r[a++]=n[1]=n[0]/10,n[0]=(n[0]-n[1]*10<<16)+r[a];r[a]=n[1]=n[0]/10,n[0]-=n[1]*10,t=`${n[0]}${t}`}while(i[0]||i[1]||i[2]||i[3]);return t??`0`}var HA=class e{static new(e,t){switch(t){case!0:return new PA(e);case!1:return new FA(e)}switch(e.constructor){case Int8Array:case Int16Array:case Int32Array:case BigInt64Array:return new PA(e)}return e.byteLength===16?new IA(e):new FA(e)}static signed(e){return new PA(e)}static unsigned(e){return new FA(e)}static decimal(e){return new IA(e)}constructor(t,n){return e.new(t,n)}},UA,WA,GA,KA,qA,JA,YA,XA,ZA,QA,$A,ej,tj,nj,rj,ij,aj,oj,sj,cj,lj,uj,dj=class e{static isNull(e){return e?.typeId===Z.Null}static isInt(e){return e?.typeId===Z.Int}static isFloat(e){return e?.typeId===Z.Float}static isBinary(e){return e?.typeId===Z.Binary}static isLargeBinary(e){return e?.typeId===Z.LargeBinary}static isUtf8(e){return e?.typeId===Z.Utf8}static isLargeUtf8(e){return e?.typeId===Z.LargeUtf8}static isBool(e){return e?.typeId===Z.Bool}static isDecimal(e){return e?.typeId===Z.Decimal}static isDate(e){return e?.typeId===Z.Date}static isTime(e){return e?.typeId===Z.Time}static isTimestamp(e){return e?.typeId===Z.Timestamp}static isInterval(e){return e?.typeId===Z.Interval}static isDuration(e){return e?.typeId===Z.Duration}static isList(e){return e?.typeId===Z.List}static isStruct(e){return e?.typeId===Z.Struct}static isUnion(e){return e?.typeId===Z.Union}static isFixedSizeBinary(e){return e?.typeId===Z.FixedSizeBinary}static isFixedSizeList(e){return e?.typeId===Z.FixedSizeList}static isMap(e){return e?.typeId===Z.Map}static isDictionary(e){return e?.typeId===Z.Dictionary}static isDenseUnion(t){return e.isUnion(t)&&t.mode===Pk.Dense}static isSparseUnion(t){return e.isUnion(t)&&t.mode===Pk.Sparse}constructor(e){this.typeId=e}};UA=Symbol.toStringTag,dj[UA]=(e=>(e.children=null,e.ArrayType=Array,e.OffsetArrayType=Int32Array,e[Symbol.toStringTag]=`DataType`))(dj.prototype);var fj=class extends dj{constructor(){super(Z.Null)}toString(){return`Null`}};WA=Symbol.toStringTag,fj[WA]=(e=>e[Symbol.toStringTag]=`Null`)(fj.prototype);var pj=class extends dj{constructor(e,t){super(Z.Int),this.isSigned=e,this.bitWidth=t}get ArrayType(){switch(this.bitWidth){case 8:return this.isSigned?Int8Array:Uint8Array;case 16:return this.isSigned?Int16Array:Uint16Array;case 32:return this.isSigned?Int32Array:Uint32Array;case 64:return this.isSigned?BigInt64Array:BigUint64Array}throw Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`${this.isSigned?`I`:`Ui`}nt${this.bitWidth}`}};GA=Symbol.toStringTag,pj[GA]=(e=>(e.isSigned=null,e.bitWidth=null,e[Symbol.toStringTag]=`Int`))(pj.prototype);var mj=class extends pj{constructor(){super(!0,8)}get ArrayType(){return Int8Array}},hj=class extends pj{constructor(){super(!0,16)}get ArrayType(){return Int16Array}},gj=class extends pj{constructor(){super(!0,32)}get ArrayType(){return Int32Array}},_j=class extends pj{constructor(){super(!0,64)}get ArrayType(){return BigInt64Array}},vj=class extends pj{constructor(){super(!1,8)}get ArrayType(){return Uint8Array}},yj=class extends pj{constructor(){super(!1,16)}get ArrayType(){return Uint16Array}},bj=class extends pj{constructor(){super(!1,32)}get ArrayType(){return Uint32Array}},xj=class extends pj{constructor(){super(!1,64)}get ArrayType(){return BigUint64Array}};Object.defineProperty(mj.prototype,`ArrayType`,{value:Int8Array}),Object.defineProperty(hj.prototype,`ArrayType`,{value:Int16Array}),Object.defineProperty(gj.prototype,`ArrayType`,{value:Int32Array}),Object.defineProperty(_j.prototype,`ArrayType`,{value:BigInt64Array}),Object.defineProperty(vj.prototype,`ArrayType`,{value:Uint8Array}),Object.defineProperty(yj.prototype,`ArrayType`,{value:Uint16Array}),Object.defineProperty(bj.prototype,`ArrayType`,{value:Uint32Array}),Object.defineProperty(xj.prototype,`ArrayType`,{value:BigUint64Array});var Sj=class extends dj{constructor(e){super(Z.Float),this.precision=e}get ArrayType(){switch(this.precision){case Fk.HALF:return Uint16Array;case Fk.SINGLE:return Float32Array;case Fk.DOUBLE:return Float64Array}throw Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}};KA=Symbol.toStringTag,Sj[KA]=(e=>(e.precision=null,e[Symbol.toStringTag]=`Float`))(Sj.prototype);var Cj=class extends Sj{constructor(){super(Fk.HALF)}},wj=class extends Sj{constructor(){super(Fk.SINGLE)}},Tj=class extends Sj{constructor(){super(Fk.DOUBLE)}};Object.defineProperty(Cj.prototype,`ArrayType`,{value:Uint16Array}),Object.defineProperty(wj.prototype,`ArrayType`,{value:Float32Array}),Object.defineProperty(Tj.prototype,`ArrayType`,{value:Float64Array});var Ej=class extends dj{constructor(){super(Z.Binary)}toString(){return`Binary`}};qA=Symbol.toStringTag,Ej[qA]=(e=>(e.ArrayType=Uint8Array,e[Symbol.toStringTag]=`Binary`))(Ej.prototype);var Dj=class extends dj{constructor(){super(Z.LargeBinary)}toString(){return`LargeBinary`}};JA=Symbol.toStringTag,Dj[JA]=(e=>(e.ArrayType=Uint8Array,e.OffsetArrayType=BigInt64Array,e[Symbol.toStringTag]=`LargeBinary`))(Dj.prototype);var Oj=class extends dj{constructor(){super(Z.Utf8)}toString(){return`Utf8`}};YA=Symbol.toStringTag,Oj[YA]=(e=>(e.ArrayType=Uint8Array,e[Symbol.toStringTag]=`Utf8`))(Oj.prototype);var kj=class extends dj{constructor(){super(Z.LargeUtf8)}toString(){return`LargeUtf8`}};XA=Symbol.toStringTag,kj[XA]=(e=>(e.ArrayType=Uint8Array,e.OffsetArrayType=BigInt64Array,e[Symbol.toStringTag]=`LargeUtf8`))(kj.prototype);var Aj=class extends dj{constructor(){super(Z.Bool)}toString(){return`Bool`}};ZA=Symbol.toStringTag,Aj[ZA]=(e=>(e.ArrayType=Uint8Array,e[Symbol.toStringTag]=`Bool`))(Aj.prototype);var jj=class extends dj{constructor(e,t,n=128){super(Z.Decimal),this.scale=e,this.precision=t,this.bitWidth=n}toString(){return`Decimal[${this.precision}e${this.scale>0?`+`:``}${this.scale}]`}};QA=Symbol.toStringTag,jj[QA]=(e=>(e.scale=null,e.precision=null,e.ArrayType=Uint32Array,e[Symbol.toStringTag]=`Decimal`))(jj.prototype);var Mj=class extends dj{constructor(e){super(Z.Date),this.unit=e}toString(){return`Date${(this.unit+1)*32}<${Ik[this.unit]}>`}get ArrayType(){return this.unit===Ik.DAY?Int32Array:BigInt64Array}};$A=Symbol.toStringTag,Mj[$A]=(e=>(e.unit=null,e[Symbol.toStringTag]=`Date`))(Mj.prototype);var Nj=class extends dj{constructor(e,t){super(Z.Time),this.unit=e,this.bitWidth=t}toString(){return`Time${this.bitWidth}<${Lk[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}};ej=Symbol.toStringTag,Nj[ej]=(e=>(e.unit=null,e.bitWidth=null,e[Symbol.toStringTag]=`Time`))(Nj.prototype);var Pj=class extends dj{constructor(e,t){super(Z.Timestamp),this.unit=e,this.timezone=t}toString(){return`Timestamp<${Lk[this.unit]}${this.timezone?`, ${this.timezone}`:``}>`}};tj=Symbol.toStringTag,Pj[tj]=(e=>(e.unit=null,e.timezone=null,e.ArrayType=BigInt64Array,e[Symbol.toStringTag]=`Timestamp`))(Pj.prototype);var Fj=class extends Pj{constructor(e){super(Lk.MILLISECOND,e)}},Ij=class extends dj{constructor(e){super(Z.Interval),this.unit=e}toString(){return`Interval<${Rk[this.unit]}>`}};nj=Symbol.toStringTag,Ij[nj]=(e=>(e.unit=null,e.ArrayType=Int32Array,e[Symbol.toStringTag]=`Interval`))(Ij.prototype);var Lj=class extends dj{constructor(e){super(Z.Duration),this.unit=e}toString(){return`Duration<${Lk[this.unit]}>`}};rj=Symbol.toStringTag,Lj[rj]=(e=>(e.unit=null,e.ArrayType=BigInt64Array,e[Symbol.toStringTag]=`Duration`))(Lj.prototype);var Rj=class extends dj{constructor(e){super(Z.List),this.children=[e]}toString(){return`List<${this.valueType}>`}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}};ij=Symbol.toStringTag,Rj[ij]=(e=>(e.children=null,e[Symbol.toStringTag]=`List`))(Rj.prototype);var zj=class extends dj{constructor(e){super(Z.Struct),this.children=e}toString(){return`Struct<{${this.children.map(e=>`${e.name}:${e.type}`).join(`, `)}}>`}};aj=Symbol.toStringTag,zj[aj]=(e=>(e.children=null,e[Symbol.toStringTag]=`Struct`))(zj.prototype);var Bj=class extends dj{constructor(e,t,n){super(Z.Union),this.mode=e,this.children=n,this.typeIds=t=Int32Array.from(t),this.typeIdToChildIndex=t.reduce((e,t,n)=>(e[t]=n)&&e||e,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(e=>`${e.type}`).join(` | `)}>`}};oj=Symbol.toStringTag,Bj[oj]=(e=>(e.mode=null,e.typeIds=null,e.children=null,e.typeIdToChildIndex=null,e.ArrayType=Int8Array,e[Symbol.toStringTag]=`Union`))(Bj.prototype);var Vj=class extends dj{constructor(e){super(Z.FixedSizeBinary),this.byteWidth=e}toString(){return`FixedSizeBinary[${this.byteWidth}]`}};sj=Symbol.toStringTag,Vj[sj]=(e=>(e.byteWidth=null,e.ArrayType=Uint8Array,e[Symbol.toStringTag]=`FixedSizeBinary`))(Vj.prototype);var Hj=class extends dj{constructor(e,t){super(Z.FixedSizeList),this.listSize=e,this.children=[t]}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}toString(){return`FixedSizeList[${this.listSize}]<${this.valueType}>`}};cj=Symbol.toStringTag,Hj[cj]=(e=>(e.children=null,e.listSize=null,e[Symbol.toStringTag]=`FixedSizeList`))(Hj.prototype);var Uj=class extends dj{constructor(e,t=!1){if(super(Z.Map),this.children=[e],this.keysSorted=t,e&&(e.name=`entries`,e?.type?.children)){let t=(e?.type)?.children[0];t&&(t.name=`key`);let n=(e?.type)?.children[1];n&&(n.name=`value`)}}get keyType(){return this.children[0].type.children[0].type}get valueType(){return this.children[0].type.children[1].type}get childType(){return this.children[0].type}toString(){return`Map<{${this.children[0].type.children.map(e=>`${e.name}:${e.type}`).join(`, `)}}>`}};lj=Symbol.toStringTag,Uj[lj]=(e=>(e.children=null,e.keysSorted=null,e[Symbol.toStringTag]=`Map_`))(Uj.prototype);var Wj=(e=>()=>++e)(-1),Gj=class extends dj{constructor(e,t,n,r){super(Z.Dictionary),this.indices=t,this.dictionary=e,this.isOrdered=r||!1,this.id=n==null?Wj():AA(n)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}};uj=Symbol.toStringTag,Gj[uj]=(e=>(e.id=null,e.indices=null,e.isOrdered=null,e.dictionary=null,e[Symbol.toStringTag]=`Dictionary`))(Gj.prototype);function Kj(e){let t=e;switch(e.typeId){case Z.Decimal:return e.bitWidth/32;case Z.Interval:return 1+t.unit;case Z.FixedSizeList:return t.listSize;case Z.FixedSizeBinary:return t.byteWidth;default:return 1}}var qj=class{visitMany(e,...t){return e.map((e,n)=>this.visit(e,...t.map(e=>e[n])))}visit(...e){return this.getVisitFn(e[0],!1).apply(this,e)}getVisitFn(e,t=!0){return Jj(this,e,t)}getVisitFnByTypeId(e,t=!0){return Yj(this,e,t)}visitNull(e,...t){return null}visitBool(e,...t){return null}visitInt(e,...t){return null}visitFloat(e,...t){return null}visitUtf8(e,...t){return null}visitLargeUtf8(e,...t){return null}visitBinary(e,...t){return null}visitLargeBinary(e,...t){return null}visitFixedSizeBinary(e,...t){return null}visitDate(e,...t){return null}visitTimestamp(e,...t){return null}visitTime(e,...t){return null}visitDecimal(e,...t){return null}visitList(e,...t){return null}visitStruct(e,...t){return null}visitUnion(e,...t){return null}visitDictionary(e,...t){return null}visitInterval(e,...t){return null}visitDuration(e,...t){return null}visitFixedSizeList(e,...t){return null}visitMap(e,...t){return null}};function Jj(e,t,n=!0){return typeof t==`number`?Yj(e,t,n):typeof t==`string`&&t in Z?Yj(e,Z[t],n):t&&t instanceof dj?Yj(e,Xj(t),n):t?.type&&t.type instanceof dj?Yj(e,Xj(t.type),n):Yj(e,Z.NONE,n)}function Yj(e,t,n=!0){let r=null;switch(t){case Z.Null:r=e.visitNull;break;case Z.Bool:r=e.visitBool;break;case Z.Int:r=e.visitInt;break;case Z.Int8:r=e.visitInt8||e.visitInt;break;case Z.Int16:r=e.visitInt16||e.visitInt;break;case Z.Int32:r=e.visitInt32||e.visitInt;break;case Z.Int64:r=e.visitInt64||e.visitInt;break;case Z.Uint8:r=e.visitUint8||e.visitInt;break;case Z.Uint16:r=e.visitUint16||e.visitInt;break;case Z.Uint32:r=e.visitUint32||e.visitInt;break;case Z.Uint64:r=e.visitUint64||e.visitInt;break;case Z.Float:r=e.visitFloat;break;case Z.Float16:r=e.visitFloat16||e.visitFloat;break;case Z.Float32:r=e.visitFloat32||e.visitFloat;break;case Z.Float64:r=e.visitFloat64||e.visitFloat;break;case Z.Utf8:r=e.visitUtf8;break;case Z.LargeUtf8:r=e.visitLargeUtf8;break;case Z.Binary:r=e.visitBinary;break;case Z.LargeBinary:r=e.visitLargeBinary;break;case Z.FixedSizeBinary:r=e.visitFixedSizeBinary;break;case Z.Date:r=e.visitDate;break;case Z.DateDay:r=e.visitDateDay||e.visitDate;break;case Z.DateMillisecond:r=e.visitDateMillisecond||e.visitDate;break;case Z.Timestamp:r=e.visitTimestamp;break;case Z.TimestampSecond:r=e.visitTimestampSecond||e.visitTimestamp;break;case Z.TimestampMillisecond:r=e.visitTimestampMillisecond||e.visitTimestamp;break;case Z.TimestampMicrosecond:r=e.visitTimestampMicrosecond||e.visitTimestamp;break;case Z.TimestampNanosecond:r=e.visitTimestampNanosecond||e.visitTimestamp;break;case Z.Time:r=e.visitTime;break;case Z.TimeSecond:r=e.visitTimeSecond||e.visitTime;break;case Z.TimeMillisecond:r=e.visitTimeMillisecond||e.visitTime;break;case Z.TimeMicrosecond:r=e.visitTimeMicrosecond||e.visitTime;break;case Z.TimeNanosecond:r=e.visitTimeNanosecond||e.visitTime;break;case Z.Decimal:r=e.visitDecimal;break;case Z.List:r=e.visitList;break;case Z.Struct:r=e.visitStruct;break;case Z.Union:r=e.visitUnion;break;case Z.DenseUnion:r=e.visitDenseUnion||e.visitUnion;break;case Z.SparseUnion:r=e.visitSparseUnion||e.visitUnion;break;case Z.Dictionary:r=e.visitDictionary;break;case Z.Interval:r=e.visitInterval;break;case Z.IntervalDayTime:r=e.visitIntervalDayTime||e.visitInterval;break;case Z.IntervalYearMonth:r=e.visitIntervalYearMonth||e.visitInterval;break;case Z.Duration:r=e.visitDuration;break;case Z.DurationSecond:r=e.visitDurationSecond||e.visitDuration;break;case Z.DurationMillisecond:r=e.visitDurationMillisecond||e.visitDuration;break;case Z.DurationMicrosecond:r=e.visitDurationMicrosecond||e.visitDuration;break;case Z.DurationNanosecond:r=e.visitDurationNanosecond||e.visitDuration;break;case Z.FixedSizeList:r=e.visitFixedSizeList;break;case Z.Map:r=e.visitMap;break}if(typeof r==`function`)return r;if(!n)return()=>null;throw Error(`Unrecognized type '${Z[t]}'`)}function Xj(e){switch(e.typeId){case Z.Null:return Z.Null;case Z.Int:{let{bitWidth:t,isSigned:n}=e;switch(t){case 8:return n?Z.Int8:Z.Uint8;case 16:return n?Z.Int16:Z.Uint16;case 32:return n?Z.Int32:Z.Uint32;case 64:return n?Z.Int64:Z.Uint64}return Z.Int}case Z.Float:switch(e.precision){case Fk.HALF:return Z.Float16;case Fk.SINGLE:return Z.Float32;case Fk.DOUBLE:return Z.Float64}return Z.Float;case Z.Binary:return Z.Binary;case Z.LargeBinary:return Z.LargeBinary;case Z.Utf8:return Z.Utf8;case Z.LargeUtf8:return Z.LargeUtf8;case Z.Bool:return Z.Bool;case Z.Decimal:return Z.Decimal;case Z.Time:switch(e.unit){case Lk.SECOND:return Z.TimeSecond;case Lk.MILLISECOND:return Z.TimeMillisecond;case Lk.MICROSECOND:return Z.TimeMicrosecond;case Lk.NANOSECOND:return Z.TimeNanosecond}return Z.Time;case Z.Timestamp:switch(e.unit){case Lk.SECOND:return Z.TimestampSecond;case Lk.MILLISECOND:return Z.TimestampMillisecond;case Lk.MICROSECOND:return Z.TimestampMicrosecond;case Lk.NANOSECOND:return Z.TimestampNanosecond}return Z.Timestamp;case Z.Date:switch(e.unit){case Ik.DAY:return Z.DateDay;case Ik.MILLISECOND:return Z.DateMillisecond}return Z.Date;case Z.Interval:switch(e.unit){case Rk.DAY_TIME:return Z.IntervalDayTime;case Rk.YEAR_MONTH:return Z.IntervalYearMonth}return Z.Interval;case Z.Duration:switch(e.unit){case Lk.SECOND:return Z.DurationSecond;case Lk.MILLISECOND:return Z.DurationMillisecond;case Lk.MICROSECOND:return Z.DurationMicrosecond;case Lk.NANOSECOND:return Z.DurationNanosecond}return Z.Duration;case Z.Map:return Z.Map;case Z.List:return Z.List;case Z.Struct:return Z.Struct;case Z.Union:switch(e.mode){case Pk.Dense:return Z.DenseUnion;case Pk.Sparse:return Z.SparseUnion}return Z.Union;case Z.FixedSizeBinary:return Z.FixedSizeBinary;case Z.FixedSizeList:return Z.FixedSizeList;case Z.Dictionary:return Z.Dictionary}throw Error(`Unrecognized type '${Z[e.typeId]}'`)}qj.prototype.visitInt8=null,qj.prototype.visitInt16=null,qj.prototype.visitInt32=null,qj.prototype.visitInt64=null,qj.prototype.visitUint8=null,qj.prototype.visitUint16=null,qj.prototype.visitUint32=null,qj.prototype.visitUint64=null,qj.prototype.visitFloat16=null,qj.prototype.visitFloat32=null,qj.prototype.visitFloat64=null,qj.prototype.visitDateDay=null,qj.prototype.visitDateMillisecond=null,qj.prototype.visitTimestampSecond=null,qj.prototype.visitTimestampMillisecond=null,qj.prototype.visitTimestampMicrosecond=null,qj.prototype.visitTimestampNanosecond=null,qj.prototype.visitTimeSecond=null,qj.prototype.visitTimeMillisecond=null,qj.prototype.visitTimeMicrosecond=null,qj.prototype.visitTimeNanosecond=null,qj.prototype.visitDenseUnion=null,qj.prototype.visitSparseUnion=null,qj.prototype.visitIntervalDayTime=null,qj.prototype.visitIntervalYearMonth=null,qj.prototype.visitDuration=null,qj.prototype.visitDurationSecond=null,qj.prototype.visitDurationMillisecond=null,qj.prototype.visitDurationMicrosecond=null,qj.prototype.visitDurationNanosecond=null;var Zj=new Float64Array(1),Qj=new Uint32Array(Zj.buffer);function $j(e){let t=(e&31744)>>10,n=(e&1023)/1024,r=(-1)**((e&32768)>>15);switch(t){case 31:return r*(n?NaN:1/0);case 0:return r*(n?6103515625e-14*n:0)}return r*2**(t-15)*(1+n)}function eM(e){if(e!==e)return 32256;Zj[0]=e;let t=(Qj[1]&2147483648)>>16&65535,n=Qj[1]&2146435072,r=0;return n>=1089470464?Qj[0]>0?n=31744:(n=(n&2080374784)>>16,r=(Qj[1]&1048575)>>10):n<=1056964608?(r=1048576+(Qj[1]&1048575),r=1048576+(r<<(n>>20)-998)>>21,n=0):(n=n-1056964608>>10,r=(Qj[1]&1048575)+512>>10),t|n|r&65535}var tM=class extends qj{};function nM(e){return(t,n,r)=>{if(t.setValid(n,r!=null))return e(t,n,r)}}var rM=(e,t,n)=>{e[t]=Math.floor(n/864e5)},iM=(e,t,n,r)=>{if(n+1<t.length){let i=AA(t[n]),a=AA(t[n+1]);e.set(r.subarray(0,a-i),i)}},aM=({offset:e,values:t},n,r)=>{let i=e+n;r?t[i>>3]|=1<<i%8:t[i>>3]&=~(1<<i%8)},oM=({values:e},t,n)=>{e[t]=n},sM=({values:e},t,n)=>{e[t]=n},cM=({values:e},t,n)=>{e[t]=eM(n)},lM=(e,t,n)=>{switch(e.type.precision){case Fk.HALF:return cM(e,t,n);case Fk.SINGLE:case Fk.DOUBLE:return sM(e,t,n)}},uM=({values:e},t,n)=>{rM(e,t,n.valueOf())},dM=({values:e},t,n)=>{e[t]=BigInt(n)},fM=({stride:e,values:t},n,r)=>{t.set(r.subarray(0,e),e*n)},pM=({values:e,valueOffsets:t},n,r)=>iM(e,t,n,r),mM=({values:e,valueOffsets:t},n,r)=>iM(e,t,n,KO(r)),hM=(e,t,n)=>{e.type.unit===Ik.DAY?uM(e,t,n):dM(e,t,n)},gM=({values:e},t,n)=>{e[t]=BigInt(n/1e3)},_M=({values:e},t,n)=>{e[t]=BigInt(n)},vM=({values:e},t,n)=>{e[t]=BigInt(n*1e3)},yM=({values:e},t,n)=>{e[t]=BigInt(n*1e6)},bM=(e,t,n)=>{switch(e.type.unit){case Lk.SECOND:return gM(e,t,n);case Lk.MILLISECOND:return _M(e,t,n);case Lk.MICROSECOND:return vM(e,t,n);case Lk.NANOSECOND:return yM(e,t,n)}},xM=({values:e},t,n)=>{e[t]=n},SM=({values:e},t,n)=>{e[t]=n},CM=({values:e},t,n)=>{e[t]=n},wM=({values:e},t,n)=>{e[t]=n},TM=(e,t,n)=>{switch(e.type.unit){case Lk.SECOND:return xM(e,t,n);case Lk.MILLISECOND:return SM(e,t,n);case Lk.MICROSECOND:return CM(e,t,n);case Lk.NANOSECOND:return wM(e,t,n)}},EM=({values:e,stride:t},n,r)=>{e.set(r.subarray(0,t),t*n)},DM=(e,t,n)=>{let r=e.children[0],i=e.valueOffsets,a=qM.getVisitFn(r);if(Array.isArray(n))for(let e=-1,o=i[t],s=i[t+1];o<s;)a(r,o++,n[++e]);else for(let e=-1,o=i[t],s=i[t+1];o<s;)a(r,o++,n.get(++e))},OM=(e,t,n)=>{let r=e.children[0],{valueOffsets:i}=e,a=qM.getVisitFn(r),{[t]:o,[t+1]:s}=i,c=n instanceof Map?n.entries():Object.entries(n);for(let e of c)if(a(r,o,e),++o>=s)break},kM=(e,t)=>(n,r,i,a)=>r&&n(r,e,t[a]),AM=(e,t)=>(n,r,i,a)=>r&&n(r,e,t.get(a)),jM=(e,t)=>(n,r,i,a)=>r&&n(r,e,t.get(i.name)),MM=(e,t)=>(n,r,i,a)=>r&&n(r,e,t[i.name]),NM=(e,t,n)=>{let r=e.type.children.map(e=>qM.getVisitFn(e.type)),i=n instanceof Map?jM(t,n):n instanceof WP?AM(t,n):Array.isArray(n)?kM(t,n):MM(t,n);e.type.children.forEach((t,n)=>i(r[n],e.children[n],t,n))},PM=(e,t,n)=>{e.type.mode===Pk.Dense?FM(e,t,n):IM(e,t,n)},FM=(e,t,n)=>{let r=e.type.typeIdToChildIndex[e.typeIds[t]],i=e.children[r];qM.visit(i,e.valueOffsets[t],n)},IM=(e,t,n)=>{let r=e.type.typeIdToChildIndex[e.typeIds[t]],i=e.children[r];qM.visit(i,t,n)},LM=(e,t,n)=>{var r;(r=e.dictionary)==null||r.set(e.values[t],n)},RM=(e,t,n)=>{e.type.unit===Rk.DAY_TIME?zM(e,t,n):BM(e,t,n)},zM=({values:e},t,n)=>{e.set(n.subarray(0,2),2*t)},BM=({values:e},t,n)=>{e[t]=n[0]*12+n[1]%12},VM=({values:e},t,n)=>{e[t]=n},HM=({values:e},t,n)=>{e[t]=n},UM=({values:e},t,n)=>{e[t]=n},WM=({values:e},t,n)=>{e[t]=n},GM=(e,t,n)=>{switch(e.type.unit){case Lk.SECOND:return VM(e,t,n);case Lk.MILLISECOND:return HM(e,t,n);case Lk.MICROSECOND:return UM(e,t,n);case Lk.NANOSECOND:return WM(e,t,n)}},KM=(e,t,n)=>{let{stride:r}=e,i=e.children[0],a=qM.getVisitFn(i);if(Array.isArray(n))for(let e=-1,o=t*r;++e<r;)a(i,o+e,n[e]);else for(let e=-1,o=t*r;++e<r;)a(i,o+e,n.get(e))};tM.prototype.visitBool=nM(aM),tM.prototype.visitInt=nM(oM),tM.prototype.visitInt8=nM(oM),tM.prototype.visitInt16=nM(oM),tM.prototype.visitInt32=nM(oM),tM.prototype.visitInt64=nM(oM),tM.prototype.visitUint8=nM(oM),tM.prototype.visitUint16=nM(oM),tM.prototype.visitUint32=nM(oM),tM.prototype.visitUint64=nM(oM),tM.prototype.visitFloat=nM(lM),tM.prototype.visitFloat16=nM(cM),tM.prototype.visitFloat32=nM(sM),tM.prototype.visitFloat64=nM(sM),tM.prototype.visitUtf8=nM(mM),tM.prototype.visitLargeUtf8=nM(mM),tM.prototype.visitBinary=nM(pM),tM.prototype.visitLargeBinary=nM(pM),tM.prototype.visitFixedSizeBinary=nM(fM),tM.prototype.visitDate=nM(hM),tM.prototype.visitDateDay=nM(uM),tM.prototype.visitDateMillisecond=nM(dM),tM.prototype.visitTimestamp=nM(bM),tM.prototype.visitTimestampSecond=nM(gM),tM.prototype.visitTimestampMillisecond=nM(_M),tM.prototype.visitTimestampMicrosecond=nM(vM),tM.prototype.visitTimestampNanosecond=nM(yM),tM.prototype.visitTime=nM(TM),tM.prototype.visitTimeSecond=nM(xM),tM.prototype.visitTimeMillisecond=nM(SM),tM.prototype.visitTimeMicrosecond=nM(CM),tM.prototype.visitTimeNanosecond=nM(wM),tM.prototype.visitDecimal=nM(EM),tM.prototype.visitList=nM(DM),tM.prototype.visitStruct=nM(NM),tM.prototype.visitUnion=nM(PM),tM.prototype.visitDenseUnion=nM(FM),tM.prototype.visitSparseUnion=nM(IM),tM.prototype.visitDictionary=nM(LM),tM.prototype.visitInterval=nM(RM),tM.prototype.visitIntervalDayTime=nM(zM),tM.prototype.visitIntervalYearMonth=nM(BM),tM.prototype.visitDuration=nM(GM),tM.prototype.visitDurationSecond=nM(VM),tM.prototype.visitDurationMillisecond=nM(HM),tM.prototype.visitDurationMicrosecond=nM(UM),tM.prototype.visitDurationNanosecond=nM(WM),tM.prototype.visitFixedSizeList=nM(KM),tM.prototype.visitMap=nM(OM);var qM=new tM,JM=Symbol.for(`parent`),YM=Symbol.for(`rowIndex`),XM=class{constructor(e,t){return this[JM]=e,this[YM]=t,new Proxy(this,new QM)}toArray(){return Object.values(this.toJSON())}toJSON(){let e=this[YM],t=this[JM],n=t.type.children,r={};for(let i=-1,a=n.length;++i<a;)r[n[i].name]=UN.visit(t.children[i],e);return r}toString(){return`{${[...this].map(([e,t])=>`${kA(e)}: ${kA(t)}`).join(`, `)}}`}[Symbol.for(`nodejs.util.inspect.custom`)](){return this.toString()}[Symbol.iterator](){return new ZM(this[JM],this[YM])}},ZM=class{constructor(e,t){this.childIndex=0,this.children=e.children,this.rowIndex=t,this.childFields=e.type.children,this.numChildren=this.childFields.length}[Symbol.iterator](){return this}next(){let e=this.childIndex;return e<this.numChildren?(this.childIndex=e+1,{done:!1,value:[this.childFields[e].name,UN.visit(this.children[e],this.rowIndex)]}):{done:!0,value:null}}};Object.defineProperties(XM.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:`Row`},[JM]:{writable:!0,enumerable:!1,configurable:!1,value:null},[YM]:{writable:!0,enumerable:!1,configurable:!1,value:-1}});var QM=class{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(e){return e[JM].type.children.map(e=>e.name)}has(e,t){return e[JM].type.children.findIndex(e=>e.name===t)!==-1}getOwnPropertyDescriptor(e,t){if(e[JM].type.children.findIndex(e=>e.name===t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];let n=e[JM].type.children.findIndex(e=>e.name===t);if(n!==-1){let r=UN.visit(e[JM].children[n],e[YM]);return Reflect.set(e,t,r),r}}set(e,t,n){let r=e[JM].type.children.findIndex(e=>e.name===t);return r===-1?Reflect.has(e,t)||typeof t==`symbol`?Reflect.set(e,t,n):!1:(qM.visit(e[JM].children[r],e[YM],n),Reflect.set(e,t,n))}},$M=class extends qj{};function eN(e){return(t,n)=>t.getValid(n)?e(t,n):null}var tN=(e,t)=>864e5*e[t],nN=(e,t)=>null,rN=(e,t,n)=>{if(n+1>=t.length)return null;let r=AA(t[n]),i=AA(t[n+1]);return e.subarray(r,i)},iN=({offset:e,values:t},n)=>{let r=e+n;return(t[r>>3]&1<<r%8)!=0},aN=({values:e},t)=>tN(e,t),oN=({values:e},t)=>AA(e[t]),sN=({stride:e,values:t},n)=>t[e*n],cN=({stride:e,values:t},n)=>$j(t[e*n]),lN=({values:e},t)=>e[t],uN=({stride:e,values:t},n)=>t.subarray(e*n,e*(n+1)),dN=({values:e,valueOffsets:t},n)=>rN(e,t,n),fN=({values:e,valueOffsets:t},n)=>{let r=rN(e,t,n);return r===null?null:WO(r)},pN=({values:e},t)=>e[t],mN=({type:e,values:t},n)=>e.precision===Fk.HALF?$j(t[n]):t[n],hN=(e,t)=>e.type.unit===Ik.DAY?aN(e,t):oN(e,t),gN=({values:e},t)=>1e3*AA(e[t]),_N=({values:e},t)=>AA(e[t]),vN=({values:e},t)=>jA(e[t],BigInt(1e3)),yN=({values:e},t)=>jA(e[t],BigInt(1e6)),bN=(e,t)=>{switch(e.type.unit){case Lk.SECOND:return gN(e,t);case Lk.MILLISECOND:return _N(e,t);case Lk.MICROSECOND:return vN(e,t);case Lk.NANOSECOND:return yN(e,t)}},xN=({values:e},t)=>e[t],SN=({values:e},t)=>e[t],CN=({values:e},t)=>e[t],wN=({values:e},t)=>e[t],TN=(e,t)=>{switch(e.type.unit){case Lk.SECOND:return xN(e,t);case Lk.MILLISECOND:return SN(e,t);case Lk.MICROSECOND:return CN(e,t);case Lk.NANOSECOND:return wN(e,t)}},EN=({values:e,stride:t},n)=>HA.decimal(e.subarray(t*n,t*(n+1))),DN=(e,t)=>{let{valueOffsets:n,stride:r,children:i}=e,{[t*r]:a,[t*r+1]:o}=n;return new WP([i[0].slice(a,o-a)])},ON=(e,t)=>{let{valueOffsets:n,children:r}=e,{[t]:i,[t+1]:a}=n,o=r[0];return new JN(o.slice(i,a-i))},kN=(e,t)=>new XM(e,t),AN=(e,t)=>e.type.mode===Pk.Dense?jN(e,t):MN(e,t),jN=(e,t)=>{let n=e.type.typeIdToChildIndex[e.typeIds[t]],r=e.children[n];return UN.visit(r,e.valueOffsets[t])},MN=(e,t)=>{let n=e.type.typeIdToChildIndex[e.typeIds[t]],r=e.children[n];return UN.visit(r,t)},NN=(e,t)=>e.dictionary?.get(e.values[t]),PN=(e,t)=>e.type.unit===Rk.DAY_TIME?FN(e,t):IN(e,t),FN=({values:e},t)=>e.subarray(2*t,2*(t+1)),IN=({values:e},t)=>{let n=e[t],r=new Int32Array(2);return r[0]=Math.trunc(n/12),r[1]=Math.trunc(n%12),r},LN=({values:e},t)=>e[t],RN=({values:e},t)=>e[t],zN=({values:e},t)=>e[t],BN=({values:e},t)=>e[t],VN=(e,t)=>{switch(e.type.unit){case Lk.SECOND:return LN(e,t);case Lk.MILLISECOND:return RN(e,t);case Lk.MICROSECOND:return zN(e,t);case Lk.NANOSECOND:return BN(e,t)}},HN=(e,t)=>{let{stride:n,children:r}=e;return new WP([r[0].slice(t*n,n)])};$M.prototype.visitNull=eN(nN),$M.prototype.visitBool=eN(iN),$M.prototype.visitInt=eN(pN),$M.prototype.visitInt8=eN(sN),$M.prototype.visitInt16=eN(sN),$M.prototype.visitInt32=eN(sN),$M.prototype.visitInt64=eN(lN),$M.prototype.visitUint8=eN(sN),$M.prototype.visitUint16=eN(sN),$M.prototype.visitUint32=eN(sN),$M.prototype.visitUint64=eN(lN),$M.prototype.visitFloat=eN(mN),$M.prototype.visitFloat16=eN(cN),$M.prototype.visitFloat32=eN(sN),$M.prototype.visitFloat64=eN(sN),$M.prototype.visitUtf8=eN(fN),$M.prototype.visitLargeUtf8=eN(fN),$M.prototype.visitBinary=eN(dN),$M.prototype.visitLargeBinary=eN(dN),$M.prototype.visitFixedSizeBinary=eN(uN),$M.prototype.visitDate=eN(hN),$M.prototype.visitDateDay=eN(aN),$M.prototype.visitDateMillisecond=eN(oN),$M.prototype.visitTimestamp=eN(bN),$M.prototype.visitTimestampSecond=eN(gN),$M.prototype.visitTimestampMillisecond=eN(_N),$M.prototype.visitTimestampMicrosecond=eN(vN),$M.prototype.visitTimestampNanosecond=eN(yN),$M.prototype.visitTime=eN(TN),$M.prototype.visitTimeSecond=eN(xN),$M.prototype.visitTimeMillisecond=eN(SN),$M.prototype.visitTimeMicrosecond=eN(CN),$M.prototype.visitTimeNanosecond=eN(wN),$M.prototype.visitDecimal=eN(EN),$M.prototype.visitList=eN(DN),$M.prototype.visitStruct=eN(kN),$M.prototype.visitUnion=eN(AN),$M.prototype.visitDenseUnion=eN(jN),$M.prototype.visitSparseUnion=eN(MN),$M.prototype.visitDictionary=eN(NN),$M.prototype.visitInterval=eN(PN),$M.prototype.visitIntervalDayTime=eN(FN),$M.prototype.visitIntervalYearMonth=eN(IN),$M.prototype.visitDuration=eN(VN),$M.prototype.visitDurationSecond=eN(LN),$M.prototype.visitDurationMillisecond=eN(RN),$M.prototype.visitDurationMicrosecond=eN(zN),$M.prototype.visitDurationNanosecond=eN(BN),$M.prototype.visitFixedSizeList=eN(HN),$M.prototype.visitMap=eN(ON);var UN=new $M,WN=Symbol.for(`keys`),GN=Symbol.for(`vals`),KN=Symbol.for(`kKeysAsStrings`),qN=Symbol.for(`_kKeysAsStrings`),JN=class{constructor(e){return this[WN]=new WP([e.children[0]]).memoize(),this[GN]=e.children[1],new Proxy(this,new XN)}get[KN](){return this[qN]||(this[qN]=Array.from(this[WN].toArray(),String))}[Symbol.iterator](){return new YN(this[WN],this[GN])}get size(){return this[WN].length}toArray(){return Object.values(this.toJSON())}toJSON(){let e=this[WN],t=this[GN],n={};for(let r=-1,i=e.length;++r<i;)n[e.get(r)]=UN.visit(t,r);return n}toString(){return`{${[...this].map(([e,t])=>`${kA(e)}: ${kA(t)}`).join(`, `)}}`}[Symbol.for(`nodejs.util.inspect.custom`)](){return this.toString()}},YN=class{constructor(e,t){this.keys=e,this.vals=t,this.keyIndex=0,this.numKeys=e.length}[Symbol.iterator](){return this}next(){let e=this.keyIndex;return e===this.numKeys?{done:!0,value:null}:(this.keyIndex++,{done:!1,value:[this.keys.get(e),UN.visit(this.vals,e)]})}},XN=class{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(e){return e[KN]}has(e,t){return e[KN].includes(t)}getOwnPropertyDescriptor(e,t){if(e[KN].indexOf(t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];let n=e[KN].indexOf(t);if(n!==-1){let r=UN.visit(Reflect.get(e,GN),n);return Reflect.set(e,t,r),r}}set(e,t,n){let r=e[KN].indexOf(t);return r===-1?Reflect.has(e,t)?Reflect.set(e,t,n):!1:(qM.visit(Reflect.get(e,GN),r,n),Reflect.set(e,t,n))}};Object.defineProperties(JN.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:`Row`},[WN]:{writable:!0,enumerable:!1,configurable:!1,value:null},[GN]:{writable:!0,enumerable:!1,configurable:!1,value:null},[qN]:{writable:!0,enumerable:!1,configurable:!1,value:null}});var ZN;function QN(e,t,n,r){let{length:i=0}=e,a=typeof t==`number`?t:0,o=typeof n==`number`?n:i;return a<0&&(a=(a%i+i)%i),o<0&&(o=(o%i+i)%i),o<a&&(ZN=a,a=o,o=ZN),o>i&&(o=i),r?r(e,a,o):[a,o]}var $N=(e,t)=>e<0?t+e:e,eP=e=>e!==e;function tP(e){if(typeof e!=`object`||!e)return eP(e)?eP:t=>t===e;if(e instanceof Date){let t=e.valueOf();return e=>e instanceof Date?e.valueOf()===t:!1}return ArrayBuffer.isView(e)?t=>t?wk(e,t):!1:e instanceof Map?rP(e):Array.isArray(e)?nP(e):e instanceof WP?iP(e):aP(e,!0)}function nP(e){let t=[];for(let n=-1,r=e.length;++n<r;)t[n]=tP(e[n]);return oP(t)}function rP(e){let t=-1,n=[];for(let r of e.values())n[++t]=tP(r);return oP(n)}function iP(e){let t=[];for(let n=-1,r=e.length;++n<r;)t[n]=tP(e.get(n));return oP(t)}function aP(e,t=!1){let n=Object.keys(e);if(!t&&n.length===0)return()=>!1;let r=[];for(let t=-1,i=n.length;++t<i;)r[t]=tP(e[n[t]]);return oP(r,n)}function oP(e,t){return n=>{if(!n||typeof n!=`object`)return!1;switch(n.constructor){case Array:return sP(e,n);case Map:return lP(e,n,n.keys());case JN:case XM:case Object:case void 0:return lP(e,n,t||Object.keys(n))}return n instanceof WP?cP(e,n):!1}}function sP(e,t){let n=e.length;if(t.length!==n)return!1;for(let r=-1;++r<n;)if(!e[r](t[r]))return!1;return!0}function cP(e,t){let n=e.length;if(t.length!==n)return!1;for(let r=-1;++r<n;)if(!e[r](t.get(r)))return!1;return!0}function lP(e,t,n){let r=n[Symbol.iterator](),i=t instanceof Map?t.keys():Object.keys(t)[Symbol.iterator](),a=t instanceof Map?t.values():Object.values(t)[Symbol.iterator](),o=0,s=e.length,c=a.next(),l=r.next(),u=i.next();for(;o<s&&!l.done&&!u.done&&!c.done&&!(l.value!==u.value||!e[o](c.value));++o,l=r.next(),u=i.next(),c=a.next());return o===s&&l.done&&u.done&&c.done?!0:(r.return&&r.return(),i.return&&i.return(),a.return&&a.return(),!1)}function uP(e,t,n,r){return(n&1<<r)!=0}function dP(e,t,n,r){return(n&1<<r)>>r}function fP(e,t,n){let r=n.byteLength+7&-8;if(e>0||n.byteLength<r){let i=new Uint8Array(r);return i.set(e%8==0?n.subarray(e>>3):pP(new mP(n,e,t,null,uP)).subarray(0,r)),i}return n}function pP(e){let t=[],n=0,r=0,i=0;for(let a of e)a&&(i|=1<<r),++r===8&&(t[n++]=i,i=r=0);(n===0||r>0)&&(t[n++]=i);let a=new Uint8Array(t.length+7&-8);return a.set(t),a}var mP=class{constructor(e,t,n,r,i){this.bytes=e,this.length=n,this.context=r,this.get=i,this.bit=t%8,this.byteIndex=t>>3,this.byte=e[this.byteIndex++],this.index=0}next(){return this.index<this.length?(this.bit===8&&(this.bit=0,this.byte=this.bytes[this.byteIndex++]),{value:this.get(this.context,this.index++,this.byte,this.bit++)}):{done:!0,value:null}}[Symbol.iterator](){return this}};function hP(e,t,n){if(n-t<=0)return 0;if(n-t<8){let r=0;for(let i of new mP(e,t,n-t,e,dP))r+=i;return r}let r=n>>3<<3,i=t+(t%8==0?0:8-t%8);return hP(e,t,i)+hP(e,r,n)+gP(e,i>>3,r-i>>3)}function gP(e,t,n){let r=0,i=Math.trunc(t),a=new DataView(e.buffer,e.byteOffset,e.byteLength),o=n===void 0?e.byteLength:i+n;for(;o-i>=4;)r+=_P(a.getUint32(i)),i+=4;for(;o-i>=2;)r+=_P(a.getUint16(i)),i+=2;for(;o-i>=1;)r+=_P(a.getUint8(i)),i+=1;return r}function _P(e){let t=Math.trunc(e);return t-=t>>>1&1431655765,t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}var vP=class e{get typeId(){return this.type.typeId}get ArrayType(){return this.type.ArrayType}get buffers(){return[this.valueOffsets,this.values,this.nullBitmap,this.typeIds]}get nullable(){if(this._nullCount!==0){let{type:e}=this;return dj.isSparseUnion(e)||dj.isDenseUnion(e)?this.children.some(e=>e.nullable):this.nullBitmap&&this.nullBitmap.byteLength>0}return!0}get byteLength(){let e=0,{valueOffsets:t,values:n,nullBitmap:r,typeIds:i}=this;return t&&(e+=t.byteLength),n&&(e+=n.byteLength),r&&(e+=r.byteLength),i&&(e+=i.byteLength),this.children.reduce((e,t)=>e+t.byteLength,e)}get nullCount(){if(dj.isUnion(this.type))return this.children.reduce((e,t)=>e+t.nullCount,0);let e=this._nullCount,t;return e<=-1&&(t=this.nullBitmap)&&(this._nullCount=e=t.length===0?0:this.length-hP(t,this.offset,this.offset+this.length)),e}constructor(t,n,r,i,a,o=[],s){this.type=t,this.children=o,this.dictionary=s,this.offset=Math.floor(Math.max(n||0,0)),this.length=Math.floor(Math.max(r||0,0)),this._nullCount=Math.floor(Math.max(i||0,-1));let c;a instanceof e?(this.stride=a.stride,this.values=a.values,this.typeIds=a.typeIds,this.nullBitmap=a.nullBitmap,this.valueOffsets=a.valueOffsets):(this.stride=Kj(t),a&&((c=a[0])&&(this.valueOffsets=c),(c=a[1])&&(this.values=c),(c=a[2])&&(this.nullBitmap=c),(c=a[3])&&(this.typeIds=c)))}getValid(e){let{type:t}=this;if(dj.isUnion(t)){let n=t,r=this.children[n.typeIdToChildIndex[this.typeIds[e]]],i=n.mode===Pk.Dense?this.valueOffsets[e]:e;return r.getValid(i)}if(this.nullable&&this.nullCount>0){let t=this.offset+e;return(this.nullBitmap[t>>3]&1<<t%8)!=0}return!0}setValid(e,t){let n,{type:r}=this;if(dj.isUnion(r)){let i=r,a=this.children[i.typeIdToChildIndex[this.typeIds[e]]],o=i.mode===Pk.Dense?this.valueOffsets[e]:e;n=a.getValid(o),a.setValid(o,t)}else{let{nullBitmap:r}=this,{offset:i,length:a}=this,o=i+e,s=1<<o%8,c=o>>3;(!r||r.byteLength<=c)&&(r=new Uint8Array((i+a+63&-64)>>3).fill(255),this.nullCount>0?(r.set(fP(i,a,this.nullBitmap),0),Object.assign(this,{nullBitmap:r})):Object.assign(this,{nullBitmap:r,_nullCount:0}));let l=r[c];n=(l&s)!==0,r[c]=t?l|s:l&~s}return n!==!!t&&(this._nullCount=this.nullCount+(t?-1:1)),t}clone(t=this.type,n=this.offset,r=this.length,i=this._nullCount,a=this,o=this.children){return new e(t,n,r,i,a,o,this.dictionary)}slice(e,t){let{stride:n,typeId:r,children:i}=this,a=(this._nullCount===0)-1,o=r===16?n:1,s=this._sliceBuffers(e,t,n,r);return this.clone(this.type,this.offset+e,t,a,s,i.length===0||this.valueOffsets?i:this._sliceChildren(i,o*e,o*t))}_changeLengthAndBackfillNullBitmap(e){if(this.typeId===Z.Null)return this.clone(this.type,0,e,0);let{length:t,nullCount:n}=this,r=new Uint8Array((e+63&-64)>>3).fill(255,0,t>>3);r[t>>3]=(1<<t-(t&-8))-1,n>0&&r.set(fP(this.offset,t,this.nullBitmap),0);let i=this.buffers;return i[DA.VALIDITY]=r,this.clone(this.type,0,e,n+(e-t),i)}_sliceBuffers(e,t,n,r){let i,{buffers:a}=this;return(i=a[DA.TYPE])&&(a[DA.TYPE]=i.subarray(e,e+t)),(i=a[DA.OFFSET])&&(a[DA.OFFSET]=i.subarray(e,e+t+1))||(i=a[DA.DATA])&&(a[DA.DATA]=r===6?i:i.subarray(n*e,n*(e+t))),a}_sliceChildren(e,t,n){return e.map(e=>e.slice(t,n))}};vP.prototype.children=Object.freeze([]);var yP=new class e extends qj{visit(e){return this.getVisitFn(e.type).call(this,e)}visitNull(e){let{type:t,offset:n=0,length:r=0}=e;return new vP(t,n,r,r)}visitBool(e){let{type:t,offset:n=0}=e,r=_k(e.nullBitmap),i=mk(t.ArrayType,e.data),{length:a=i.length>>3,nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,i,r])}visitInt(e){let{type:t,offset:n=0}=e,r=_k(e.nullBitmap),i=mk(t.ArrayType,e.data),{length:a=i.length,nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,i,r])}visitFloat(e){let{type:t,offset:n=0}=e,r=_k(e.nullBitmap),i=mk(t.ArrayType,e.data),{length:a=i.length,nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,i,r])}visitUtf8(e){let{type:t,offset:n=0}=e,r=_k(e.data),i=_k(e.nullBitmap),a=hk(e.valueOffsets),{length:o=a.length-1,nullCount:s=e.nullBitmap?-1:0}=e;return new vP(t,n,o,s,[a,r,i])}visitLargeUtf8(e){let{type:t,offset:n=0}=e,r=_k(e.data),i=_k(e.nullBitmap),a=gk(e.valueOffsets),{length:o=a.length-1,nullCount:s=e.nullBitmap?-1:0}=e;return new vP(t,n,o,s,[a,r,i])}visitBinary(e){let{type:t,offset:n=0}=e,r=_k(e.data),i=_k(e.nullBitmap),a=hk(e.valueOffsets),{length:o=a.length-1,nullCount:s=e.nullBitmap?-1:0}=e;return new vP(t,n,o,s,[a,r,i])}visitLargeBinary(e){let{type:t,offset:n=0}=e,r=_k(e.data),i=_k(e.nullBitmap),a=gk(e.valueOffsets),{length:o=a.length-1,nullCount:s=e.nullBitmap?-1:0}=e;return new vP(t,n,o,s,[a,r,i])}visitFixedSizeBinary(e){let{type:t,offset:n=0}=e,r=_k(e.nullBitmap),i=mk(t.ArrayType,e.data),{length:a=i.length/Kj(t),nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,i,r])}visitDate(e){let{type:t,offset:n=0}=e,r=_k(e.nullBitmap),i=mk(t.ArrayType,e.data),{length:a=i.length/Kj(t),nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,i,r])}visitTimestamp(e){let{type:t,offset:n=0}=e,r=_k(e.nullBitmap),i=mk(t.ArrayType,e.data),{length:a=i.length/Kj(t),nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,i,r])}visitTime(e){let{type:t,offset:n=0}=e,r=_k(e.nullBitmap),i=mk(t.ArrayType,e.data),{length:a=i.length/Kj(t),nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,i,r])}visitDecimal(e){let{type:t,offset:n=0}=e,r=_k(e.nullBitmap),i=mk(t.ArrayType,e.data),{length:a=i.length/Kj(t),nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,i,r])}visitList(e){let{type:t,offset:n=0,child:r}=e,i=_k(e.nullBitmap),a=hk(e.valueOffsets),{length:o=a.length-1,nullCount:s=e.nullBitmap?-1:0}=e;return new vP(t,n,o,s,[a,void 0,i],[r])}visitStruct(e){let{type:t,offset:n=0,children:r=[]}=e,i=_k(e.nullBitmap),{length:a=r.reduce((e,{length:t})=>Math.max(e,t),0),nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,void 0,i],r)}visitUnion(e){let{type:t,offset:n=0,children:r=[]}=e,i=mk(t.ArrayType,e.typeIds),{length:a=i.length,nullCount:o=-1}=e;return dj.isSparseUnion(t)?new vP(t,n,a,o,[void 0,void 0,void 0,i],r):new vP(t,n,a,o,[hk(e.valueOffsets),void 0,void 0,i],r)}visitDictionary(t){let{type:n,offset:r=0}=t,i=_k(t.nullBitmap),a=mk(n.indices.ArrayType,t.data),{dictionary:o=new WP([new e().visit({type:n.dictionary})])}=t,{length:s=a.length,nullCount:c=t.nullBitmap?-1:0}=t;return new vP(n,r,s,c,[void 0,a,i],[],o)}visitInterval(e){let{type:t,offset:n=0}=e,r=_k(e.nullBitmap),i=mk(t.ArrayType,e.data),{length:a=i.length/Kj(t),nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,i,r])}visitDuration(e){let{type:t,offset:n=0}=e,r=_k(e.nullBitmap),i=mk(t.ArrayType,e.data),{length:a=i.length,nullCount:o=e.nullBitmap?-1:0}=e;return new vP(t,n,a,o,[void 0,i,r])}visitFixedSizeList(t){let{type:n,offset:r=0,child:i=new e().visit({type:n.valueType})}=t,a=_k(t.nullBitmap),{length:o=i.length/Kj(n),nullCount:s=t.nullBitmap?-1:0}=t;return new vP(n,r,o,s,[void 0,void 0,a],[i])}visitMap(t){let{type:n,offset:r=0,child:i=new e().visit({type:n.childType})}=t,a=_k(t.nullBitmap),o=hk(t.valueOffsets),{length:s=o.length-1,nullCount:c=t.nullBitmap?-1:0}=t;return new vP(n,r,s,c,[o,void 0,a],[i])}};function bP(e){return yP.visit(e)}var xP=class{constructor(e=0,t){this.numChunks=e,this.getChunkIterator=t,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndex<this.numChunks;){let e=this.chunkIterator.next();if(!e.done)return e;++this.chunkIndex<this.numChunks&&(this.chunkIterator=this.getChunkIterator(this.chunkIndex))}return{done:!0,value:null}}[Symbol.iterator](){return this}};function SP(e){return e.some(e=>e.nullable)}function CP(e){return e.reduce((e,t)=>e+t.nullCount,0)}function wP(e){return e.reduce((e,t,n)=>(e[n+1]=e[n]+t.length,e),new Uint32Array(e.length+1))}function TP(e,t,n,r){let i=[];for(let a=-1,o=e.length;++a<o;){let o=e[a],s=t[a],{length:c}=o;if(s>=r)break;if(n>=s+c)continue;if(s>=n&&s+c<=r){i.push(o);continue}let l=Math.max(0,n-s),u=Math.min(r-s,c);i.push(o.slice(l,u-l))}return i.length===0&&i.push(e[0].slice(0,0)),i}function EP(e,t,n,r){let i=0,a=0,o=t.length-1;do{if(i>=o-1)return n<t[o]?r(e,i,n-t[i]):null;a=i+Math.trunc((o-i)*.5),n<t[a]?o=a:i=a}while(i<o)}function DP(e,t){return e.getValid(t)}function OP(e){function t(t,n,r){return e(t[n],r)}return function(e){let n=this.data;return EP(n,this._offsets,e,t)}}function kP(e){let t;function n(n,r,i){return e(n[r],i,t)}return function(e,r){let i=this.data;t=r;let a=EP(i,this._offsets,e,n);return t=void 0,a}}function AP(e){let t;function n(n,r,i){let a=i,o=0,s=0;for(let i=r-1,c=n.length;++i<c;){let r=n[i];if(~(o=e(r,t,a)))return s+o;a=0,s+=r.length}return-1}return function(e,r){t=e;let i=this.data,a=typeof r==`number`?EP(i,this._offsets,r,n):n(i,0,0);return t=void 0,a}}var jP=class extends qj{};function MP(e,t){return t===null&&e.length>0?0:-1}function NP(e,t){let{nullBitmap:n}=e;if(!n||e.nullCount<=0)return-1;let r=0;for(let i of new mP(n,e.offset+(t||0),e.length,n,uP)){if(!i)return r;++r}return-1}function PP(e,t,n){if(t===void 0)return-1;if(t===null)switch(e.typeId){case Z.Union:break;case Z.Dictionary:break;default:return NP(e,n)}let r=UN.getVisitFn(e),i=tP(t);for(let t=(n||0)-1,a=e.length;++t<a;)if(i(r(e,t)))return t;return-1}function FP(e,t,n){let r=UN.getVisitFn(e),i=tP(t);for(let t=(n||0)-1,a=e.length;++t<a;)if(i(r(e,t)))return t;return-1}jP.prototype.visitNull=MP,jP.prototype.visitBool=PP,jP.prototype.visitInt=PP,jP.prototype.visitInt8=PP,jP.prototype.visitInt16=PP,jP.prototype.visitInt32=PP,jP.prototype.visitInt64=PP,jP.prototype.visitUint8=PP,jP.prototype.visitUint16=PP,jP.prototype.visitUint32=PP,jP.prototype.visitUint64=PP,jP.prototype.visitFloat=PP,jP.prototype.visitFloat16=PP,jP.prototype.visitFloat32=PP,jP.prototype.visitFloat64=PP,jP.prototype.visitUtf8=PP,jP.prototype.visitLargeUtf8=PP,jP.prototype.visitBinary=PP,jP.prototype.visitLargeBinary=PP,jP.prototype.visitFixedSizeBinary=PP,jP.prototype.visitDate=PP,jP.prototype.visitDateDay=PP,jP.prototype.visitDateMillisecond=PP,jP.prototype.visitTimestamp=PP,jP.prototype.visitTimestampSecond=PP,jP.prototype.visitTimestampMillisecond=PP,jP.prototype.visitTimestampMicrosecond=PP,jP.prototype.visitTimestampNanosecond=PP,jP.prototype.visitTime=PP,jP.prototype.visitTimeSecond=PP,jP.prototype.visitTimeMillisecond=PP,jP.prototype.visitTimeMicrosecond=PP,jP.prototype.visitTimeNanosecond=PP,jP.prototype.visitDecimal=PP,jP.prototype.visitList=PP,jP.prototype.visitStruct=PP,jP.prototype.visitUnion=PP,jP.prototype.visitDenseUnion=FP,jP.prototype.visitSparseUnion=FP,jP.prototype.visitDictionary=PP,jP.prototype.visitInterval=PP,jP.prototype.visitIntervalDayTime=PP,jP.prototype.visitIntervalYearMonth=PP,jP.prototype.visitDuration=PP,jP.prototype.visitDurationSecond=PP,jP.prototype.visitDurationMillisecond=PP,jP.prototype.visitDurationMicrosecond=PP,jP.prototype.visitDurationNanosecond=PP,jP.prototype.visitFixedSizeList=PP,jP.prototype.visitMap=PP;var IP=new jP,LP=class extends qj{};function RP(e){let{type:t}=e;if(e.nullCount===0&&e.stride===1&&(dj.isInt(t)&&t.bitWidth!==64||dj.isTime(t)&&t.bitWidth!==64||dj.isFloat(t)&&t.precision!==Fk.HALF))return new xP(e.data.length,t=>{let n=e.data[t];return n.values.subarray(0,n.length)[Symbol.iterator]()});let n=0;return new xP(e.data.length,t=>{let r=e.data[t].length,i=e.slice(n,n+r);return n+=r,new zP(i)})}var zP=class{constructor(e){this.vector=e,this.index=0}next(){return this.index<this.vector.length?{value:this.vector.get(this.index++)}:{done:!0,value:null}}[Symbol.iterator](){return this}};LP.prototype.visitNull=RP,LP.prototype.visitBool=RP,LP.prototype.visitInt=RP,LP.prototype.visitInt8=RP,LP.prototype.visitInt16=RP,LP.prototype.visitInt32=RP,LP.prototype.visitInt64=RP,LP.prototype.visitUint8=RP,LP.prototype.visitUint16=RP,LP.prototype.visitUint32=RP,LP.prototype.visitUint64=RP,LP.prototype.visitFloat=RP,LP.prototype.visitFloat16=RP,LP.prototype.visitFloat32=RP,LP.prototype.visitFloat64=RP,LP.prototype.visitUtf8=RP,LP.prototype.visitLargeUtf8=RP,LP.prototype.visitBinary=RP,LP.prototype.visitLargeBinary=RP,LP.prototype.visitFixedSizeBinary=RP,LP.prototype.visitDate=RP,LP.prototype.visitDateDay=RP,LP.prototype.visitDateMillisecond=RP,LP.prototype.visitTimestamp=RP,LP.prototype.visitTimestampSecond=RP,LP.prototype.visitTimestampMillisecond=RP,LP.prototype.visitTimestampMicrosecond=RP,LP.prototype.visitTimestampNanosecond=RP,LP.prototype.visitTime=RP,LP.prototype.visitTimeSecond=RP,LP.prototype.visitTimeMillisecond=RP,LP.prototype.visitTimeMicrosecond=RP,LP.prototype.visitTimeNanosecond=RP,LP.prototype.visitDecimal=RP,LP.prototype.visitList=RP,LP.prototype.visitStruct=RP,LP.prototype.visitUnion=RP,LP.prototype.visitDenseUnion=RP,LP.prototype.visitSparseUnion=RP,LP.prototype.visitDictionary=RP,LP.prototype.visitInterval=RP,LP.prototype.visitIntervalDayTime=RP,LP.prototype.visitIntervalYearMonth=RP,LP.prototype.visitDuration=RP,LP.prototype.visitDurationSecond=RP,LP.prototype.visitDurationMillisecond=RP,LP.prototype.visitDurationMicrosecond=RP,LP.prototype.visitDurationNanosecond=RP,LP.prototype.visitFixedSizeList=RP,LP.prototype.visitMap=RP;var BP=new LP,VP,HP={},UP={},WP=class e{constructor(t){let n=t[0]instanceof e?t.flatMap(e=>e.data):t;if(n.length===0||n.some(e=>!(e instanceof vP)))throw TypeError(`Vector constructor expects an Array of Data instances.`);let r=n[0]?.type;switch(n.length){case 0:this._offsets=[0];break;case 1:{let{get:e,set:t,indexOf:i}=HP[r.typeId],a=n[0];this.isValid=e=>DP(a,e),this.get=t=>e(a,t),this.set=(e,n)=>t(a,e,n),this.indexOf=e=>i(a,e),this._offsets=[0,a.length];break}default:Object.setPrototypeOf(this,UP[r.typeId]),this._offsets=wP(n);break}this.data=n,this.type=r,this.stride=Kj(r),this.numChildren=r.children?.length??0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((e,t)=>e+t.byteLength,0)}get nullable(){return SP(this.data)}get nullCount(){return CP(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${Z[this.type.typeId]}Vector`}isValid(e){return!1}get(e){return null}at(e){return this.get($N(e,this.length))}set(e,t){}indexOf(e,t){return-1}includes(e,t){return this.indexOf(e,t)>-1}[Symbol.iterator](){return BP.visit(this)}concat(...t){return new e(this.data.concat(t.flatMap(e=>e.data).flat(1/0)))}slice(t,n){return new e(QN(this,t,n,({data:e,_offsets:t},n,r)=>TP(e,t,n,r)))}toJSON(){return[...this]}toArray(){let{type:e,data:t,length:n,stride:r,ArrayType:i}=this;switch(e.typeId){case Z.Int:case Z.Float:case Z.Decimal:case Z.Time:case Z.Timestamp:switch(t.length){case 0:return new i;case 1:return t[0].values.subarray(0,n*r);default:return t.reduce((e,{values:t,length:n})=>(e.array.set(t.subarray(0,n*r),e.offset),e.offset+=n*r,e),{array:new i(n*r),offset:0}).array}}return[...this]}toString(){return`[${[...this].join(`,`)}]`}getChild(e){return this.getChildAt(this.type.children?.findIndex(t=>t.name===e))}getChildAt(t){return t>-1&&t<this.numChildren?new e(this.data.map(({children:e})=>e[t])):null}get isMemoized(){return dj.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(dj.isDictionary(this.type)){let t=new GP(this.data[0].dictionary);return new e(this.data.map(e=>{let n=e.clone();return n.dictionary=t,n}))}return new GP(this)}unmemoize(){if(dj.isDictionary(this.type)&&this.isMemoized){let t=this.data[0].dictionary.unmemoize();return new e(this.data.map(e=>{let n=e.clone();return n.dictionary=t,n}))}return this}};VP=Symbol.toStringTag,WP[VP]=(e=>{e.type=dj.prototype,e.data=[],e.length=0,e.stride=1,e.numChildren=0,e._offsets=new Uint32Array([0]),e[Symbol.isConcatSpreadable]=!0;let t=Object.keys(Z).map(e=>Z[e]).filter(e=>typeof e==`number`&&e!==Z.NONE);for(let n of t)HP[n]={get:UN.getVisitFnByTypeId(n),set:qM.getVisitFnByTypeId(n),indexOf:IP.getVisitFnByTypeId(n)},UP[n]=Object.create(e,{isValid:{value:OP(DP)},get:{value:OP(UN.getVisitFnByTypeId(n))},set:{value:kP(qM.getVisitFnByTypeId(n))},indexOf:{value:AP(IP.getVisitFnByTypeId(n))}});return`Vector`})(WP.prototype);var GP=class e extends WP{constructor(t){super(t.data);let n=this.get,r=this.set,i=this.slice,a=Array(this.length);Object.defineProperty(this,`get`,{value(e){let t=a[e];if(t!==void 0)return t;let r=n.call(this,e);return a[e]=r,r}}),Object.defineProperty(this,`set`,{value(e,t){r.call(this,e,t),a[e]=t}}),Object.defineProperty(this,`slice`,{value:(t,n)=>new e(i.call(this,t,n))}),Object.defineProperty(this,`isMemoized`,{value:!0}),Object.defineProperty(this,`unmemoize`,{value:()=>new WP(this.data)}),Object.defineProperty(this,`memoize`,{value:()=>this})}};function KP(e){if(e){if(e instanceof vP)return new WP([e]);if(e instanceof WP)return new WP(e.data);if(e.type instanceof dj)return new WP([bP(e)]);if(Array.isArray(e))return new WP(e.flatMap(e=>qP(e)));if(ArrayBuffer.isView(e)){e instanceof DataView&&(e=new Uint8Array(e.buffer));let t={offset:0,length:e.length,nullCount:-1,data:e};if(e instanceof Int8Array)return new WP([bP(Object.assign(Object.assign({},t),{type:new mj}))]);if(e instanceof Int16Array)return new WP([bP(Object.assign(Object.assign({},t),{type:new hj}))]);if(e instanceof Int32Array)return new WP([bP(Object.assign(Object.assign({},t),{type:new gj}))]);if(e instanceof BigInt64Array)return new WP([bP(Object.assign(Object.assign({},t),{type:new _j}))]);if(e instanceof Uint8Array||e instanceof Uint8ClampedArray)return new WP([bP(Object.assign(Object.assign({},t),{type:new vj}))]);if(e instanceof Uint16Array)return new WP([bP(Object.assign(Object.assign({},t),{type:new yj}))]);if(e instanceof Uint32Array)return new WP([bP(Object.assign(Object.assign({},t),{type:new bj}))]);if(e instanceof BigUint64Array)return new WP([bP(Object.assign(Object.assign({},t),{type:new xj}))]);if(e instanceof Float32Array)return new WP([bP(Object.assign(Object.assign({},t),{type:new wj}))]);if(e instanceof Float64Array)return new WP([bP(Object.assign(Object.assign({},t),{type:new Tj}))]);throw Error(`Unrecognized input`)}}throw Error(`Unrecognized input`)}function qP(e){return e instanceof vP?[e]:e instanceof WP?e.data:KP(e).data}function JP(e){if(!e||e.length<=0)return function(e){return!0};let t=``,n=e.filter(e=>e===e);return n.length>0&&(t=`
65
66
  switch (x) {${n.map(e=>`
66
- case ${uN(e)}:`).join(``)}
67
+ case ${YP(e)}:`).join(``)}
67
68
  return false;
68
- }`),e.length!==n.length&&(t=`if (x !== x) return false;\n${t}`),Function(`x`,`${t}\nreturn true;`)}function uN(e){return typeof e==`bigint`?`${WO(e)}n`:WO(e)}function dN(e,t){let n=Math.ceil(e)*t-1;return(n-n%64+64||64)/t}function fN(e,t=0){return e.length>=t?e.subarray(0,t):DD(new e.constructor(t),e,0)}var pN=class{constructor(e,t=0,n=1){this.length=Math.ceil(t/n),this.buffer=new e(this.length),this.stride=n,this.BYTES_PER_ELEMENT=e.BYTES_PER_ELEMENT,this.ArrayType=e}get byteLength(){return Math.ceil(this.length*this.stride)*this.BYTES_PER_ELEMENT}get reservedLength(){return this.buffer.length/this.stride}get reservedByteLength(){return this.buffer.byteLength}set(e,t){return this}append(e){return this.set(this.length,e)}reserve(e){if(e>0){this.length+=e;let t=this.stride,n=this.length*t,r=this.buffer.length;n>=r&&this._resize(dN(r===0?n*1:n*2,this.BYTES_PER_ELEMENT))}return this}flush(e=this.length){e=dN(e*this.stride,this.BYTES_PER_ELEMENT);let t=fN(this.buffer,e);return this.clear(),t}clear(){return this.length=0,this.buffer=new this.ArrayType,this}_resize(e){return this.buffer=fN(this.buffer,e)}},mN=class extends pN{last(){return this.get(this.length-1)}get(e){return this.buffer[e]}set(e,t){return this.reserve(e-this.length+1),this.buffer[e*this.stride]=t,this}},hN=class extends mN{constructor(){super(Uint8Array,0,1/8),this.numValid=0}get numInvalid(){return this.length-this.numValid}get(e){return this.buffer[e>>3]>>e%8&1}set(e,t){let{buffer:n}=this.reserve(e-this.length+1),r=e>>3,i=e%8,a=n[r]>>i&1;return t?a===0&&(n[r]|=1<<i,++this.numValid):a===1&&(n[r]&=~(1<<i),--this.numValid),this}clear(){return this.numValid=0,super.clear()}},gN=class extends mN{constructor(e){super(e.OffsetArrayType,1,1)}append(e){return this.set(this.length-1,e)}set(e,t){let n=this.length-1,r=this.reserve(e-n+1).buffer;return n<e++&&n>=0&&r.fill(r[n],n,e),r[e]=r[e-1]+t,this}flush(e=this.length-1){return e>this.length&&this.set(e-1,this.BYTES_PER_ELEMENT>4?BigInt(0):0),super.flush(e+1)}},_N=class{static throughNode(e){throw Error(`"throughNode" not available in this environment`)}static throughDOM(e){throw Error(`"throughDOM" not available in this environment`)}constructor({type:e,nullValues:t}){this.length=0,this.finished=!1,this.type=e,this.children=[],this.nullValues=t,this.stride=sA(e),this._nulls=new hN,t&&t.length>0&&(this._isValid=lN(t))}toVector(){return new aN([this.flush()])}get ArrayType(){return this.type.ArrayType}get nullCount(){return this._nulls.numInvalid}get numChildren(){return this.children.length}get byteLength(){let e=0,{_offsets:t,_values:n,_nulls:r,_typeIds:i,children:a}=this;return t&&(e+=t.byteLength),n&&(e+=n.byteLength),r&&(e+=r.byteLength),i&&(e+=i.byteLength),a.reduce((e,t)=>e+t.byteLength,e)}get reservedLength(){return this._nulls.reservedLength}get reservedByteLength(){let e=0;return this._offsets&&(e+=this._offsets.reservedByteLength),this._values&&(e+=this._values.reservedByteLength),this._nulls&&(e+=this._nulls.reservedByteLength),this._typeIds&&(e+=this._typeIds.reservedByteLength),this.children.reduce((e,t)=>e+t.reservedByteLength,e)}get valueOffsets(){return this._offsets?this._offsets.buffer:null}get values(){return this._values?this._values.buffer:null}get nullBitmap(){return this._nulls?this._nulls.buffer:null}get typeIds(){return this._typeIds?this._typeIds.buffer:null}append(e){return this.set(this.length,e)}isValid(e){return this._isValid(e)}set(e,t){return this.setValid(e,this.isValid(t))&&this.setValue(e,t),this}setValue(e,t){this._setValue(this,e,t)}setValid(e,t){return this.length=this._nulls.set(e,+t).length,t}addChild(e,t=`${this.numChildren}`){throw Error(`Cannot append children to non-nested type "${this.type}"`)}getChildAt(e){return this.children[e]||null}flush(){let e,t,n,r,{type:i,length:a,nullCount:o,_typeIds:s,_offsets:c,_values:l,_nulls:u}=this;(t=s?.flush(a))?r=c?.flush(a):e=(r=c?.flush(a))?l?.flush(c.last()):l?.flush(a),o>0&&(n=u?.flush(a));let d=this.children.map(e=>e.flush());return this.clear(),FM({type:i,length:a,nullCount:o,children:d,child:d[0],data:e,typeIds:t,nullBitmap:n,valueOffsets:r})}finish(){this.finished=!0;for(let e of this.children)e.finish();return this}clear(){var e,t,n,r;this.length=0,(e=this._nulls)==null||e.clear(),(t=this._values)==null||t.clear(),(n=this._offsets)==null||n.clear(),(r=this._typeIds)==null||r.clear();for(let e of this.children)e.clear();return this}};_N.prototype.length=1,_N.prototype.stride=1,_N.prototype.children=null,_N.prototype.finished=!1,_N.prototype.nullValues=null,_N.prototype._isValid=()=>!0;var vN=class extends _N{constructor(e){super(e),this._values=new mN(this.ArrayType,0,this.stride)}setValue(e,t){let n=this._values;return n.reserve(e-n.length+1),super.setValue(e,t)}},yN=class extends _N{constructor(e){super(e),this._pendingLength=0,this._offsets=new gN(e.type)}setValue(e,t){let n=this._pending||=new Map,r=n.get(e);r&&(this._pendingLength-=r.length),this._pendingLength+=t instanceof lM?t[aM].length:t.length,n.set(e,t)}setValid(e,t){return super.setValid(e,t)?!0:((this._pending||=new Map).set(e,void 0),!1)}clear(){return this._pendingLength=0,this._pending=void 0,super.clear()}flush(){return this._flush(),super.flush()}finish(){return this._flush(),super.finish()}_flush(){let e=this._pending,t=this._pendingLength;return this._pendingLength=0,this._pending=void 0,e&&e.size>0&&this._flushPending(e,t),this}},bN=class{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}offset(){return this.bb.readInt64(this.bb_pos)}metaDataLength(){return this.bb.readInt32(this.bb_pos+8)}bodyLength(){return this.bb.readInt64(this.bb_pos+16)}static sizeOf(){return 24}static createBlock(e,t,n,r){return e.prep(8,24),e.writeInt64(BigInt(r??0)),e.pad(4),e.writeInt32(n),e.writeInt64(BigInt(t??0)),e.offset()}},xN=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFooter(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFooter(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}version(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):JD.V1}schema(e){let t=this.bb.__offset(this.bb_pos,6);return t?(e||new BO).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}dictionaries(e,t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new bN).__init(this.bb.__vector(this.bb_pos+n)+e*24,this.bb):null}dictionariesLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}recordBatches(e,t){let n=this.bb.__offset(this.bb_pos,10);return n?(t||new bN).__init(this.bb.__vector(this.bb_pos+n)+e*24,this.bb):null}recordBatchesLength(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){let n=this.bb.__offset(this.bb_pos,12);return n?(t||new vO).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+e*4),this.bb):null}customMetadataLength(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startFooter(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,JD.V1)}static addSchema(e,t){e.addFieldOffset(1,t,0)}static addDictionaries(e,t){e.addFieldOffset(2,t,0)}static startDictionariesVector(e,t){e.startVector(24,t,8)}static addRecordBatches(e,t){e.addFieldOffset(3,t,0)}static startRecordBatchesVector(e,t){e.startVector(24,t,8)}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endFooter(e){return e.endObject()}static finishFooterBuffer(e,t){e.finish(t)}static finishSizePrefixedFooterBuffer(e,t){e.finish(t,void 0,!0)}},SN=class e{constructor(e=[],t,n,r=JD.V5){this.fields=e||[],this.metadata=t||new Map,n||=TN(this.fields),this.dictionaries=n,this.metadataVersion=r}get[Symbol.toStringTag](){return`Schema`}get names(){return this.fields.map(e=>e.name)}toString(){return`Schema<{ ${this.fields.map((e,t)=>`${t}: ${e}`).join(`, `)} }>`}select(t){let n=new Set(t);return new e(this.fields.filter(e=>n.has(e.name)),this.metadata)}selectAt(t){return new e(t.map(e=>this.fields[e]).filter(Boolean),this.metadata)}assign(...t){let n=t[0]instanceof e?t[0]:Array.isArray(t[0])?new e(t[0]):new e(t),r=[...this.fields],i=wN(wN(new Map,this.metadata),n.metadata),a=n.fields.filter(e=>{let t=r.findIndex(t=>t.name===e.name);return~t?(r[t]=e.clone({metadata:wN(wN(new Map,r[t].metadata),e.metadata)}))&&!1:!0}),o=TN(a,new Map);return new e([...r,...a],i,new Map([...this.dictionaries,...o]))}};SN.prototype.fields=null,SN.prototype.metadata=null,SN.prototype.dictionaries=null;var CN=class e{static new(...t){let[n,r,i,a]=t;return t[0]&&typeof t[0]==`object`&&({name:n}=t[0],r===void 0&&(r=t[0].type),i===void 0&&(i=t[0].nullable),a===void 0&&(a=t[0].metadata)),new e(`${n}`,r,i,a)}constructor(e,t,n=!1,r){this.name=e,this.type=t,this.nullable=n,this.metadata=r||new Map}get typeId(){return this.type.typeId}get[Symbol.toStringTag](){return`Field`}toString(){return`${this.name}: ${this.type}`}clone(...t){let[n,r,i,a]=t;return!t[0]||typeof t[0]!=`object`?[n=this.name,r=this.type,i=this.nullable,a=this.metadata]=t:{name:n=this.name,type:r=this.type,nullable:i=this.nullable,metadata:a=this.metadata}=t[0],e.new(n,r,i,a)}};CN.prototype.type=null,CN.prototype.name=null,CN.prototype.nullable=null,CN.prototype.metadata=null;function wN(e,t){return new Map([...e||new Map,...t||new Map])}function TN(e,t=new Map){for(let n=-1,r=e.length;++n<r;){let r=e[n].type;if(Ek.isDictionary(r)){if(!t.has(r.id))t.set(r.id,r.dictionary);else if(t.get(r.id)!==r.dictionary)throw Error(`Cannot create Schema containing two different dictionaries with the same Id`)}r.children&&r.children.length>0&&TN(r.children,t)}return t}var EN=oO,DN=aO,ON=class{static decode(e){e=new DN(MD(e));let t=xN.getRootAsFooter(e);return new kN(SN.decode(t.schema(),new Map,t.version()),t)}static encode(e){let t=new EN,n=SN.encode(t,e.schema);xN.startRecordBatchesVector(t,e.numRecordBatches);for(let n of[...e.recordBatches()].slice().reverse())AN.encode(t,n);let r=t.endVector();xN.startDictionariesVector(t,e.numDictionaries);for(let n of[...e.dictionaryBatches()].slice().reverse())AN.encode(t,n);let i=t.endVector();return xN.startFooter(t),xN.addSchema(t,n),xN.addVersion(t,JD.V5),xN.addRecordBatches(t,r),xN.addDictionaries(t,i),xN.finishFooterBuffer(t,xN.endFooter(t)),t.asUint8Array()}get numRecordBatches(){return this._recordBatches.length}get numDictionaries(){return this._dictionaryBatches.length}constructor(e,t=JD.V5,n,r){this.schema=e,this.version=t,n&&(this._recordBatches=n),r&&(this._dictionaryBatches=r)}*recordBatches(){for(let e,t=-1,n=this.numRecordBatches;++t<n;)(e=this.getRecordBatch(t))&&(yield e)}*dictionaryBatches(){for(let e,t=-1,n=this.numDictionaries;++t<n;)(e=this.getDictionaryBatch(t))&&(yield e)}getRecordBatch(e){return e>=0&&e<this.numRecordBatches&&this._recordBatches[e]||null}getDictionaryBatch(e){return e>=0&&e<this.numDictionaries&&this._dictionaryBatches[e]||null}},kN=class extends ON{get numRecordBatches(){return this._footer.recordBatchesLength()}get numDictionaries(){return this._footer.dictionariesLength()}constructor(e,t){super(e,t.version()),this._footer=t}getRecordBatch(e){if(e>=0&&e<this.numRecordBatches){let t=this._footer.recordBatches(e);if(t)return AN.decode(t)}return null}getDictionaryBatch(e){if(e>=0&&e<this.numDictionaries){let t=this._footer.dictionaries(e);if(t)return AN.decode(t)}return null}},AN=class e{static decode(t){return new e(t.metaDataLength(),t.bodyLength(),t.offset())}static encode(e,t){let{metaDataLength:n}=t,r=BigInt(t.offset),i=BigInt(t.bodyLength);return bN.createBlock(e,r,n,i)}constructor(e,t,n){this.metaDataLength=e,this.offset=GO(n),this.bodyLength=GO(t)}},jN=Object.freeze({done:!0,value:void 0}),MN=class{constructor(e){this._json=e}get schema(){return this._json.schema}get batches(){return this._json.batches||[]}get dictionaries(){return this._json.dictionaries||[]}},NN=class{tee(){return this._getDOMStream().tee()}pipe(e,t){return this._getNodeStream().pipe(e,t)}pipeTo(e,t){return this._getDOMStream().pipeTo(e,t)}pipeThrough(e,t){return this._getDOMStream().pipeThrough(e,t)}_getDOMStream(){return this._DOMStream||=this.toDOMStream()}_getNodeStream(){return this._nodeStream||=this.toNodeStream()}},PN=class extends NN{constructor(){super(),this._values=[],this.resolvers=[],this._closedPromise=new Promise(e=>this._closedPromiseResolve=e)}get closed(){return this._closedPromise}cancel(e){return QE(this,void 0,void 0,function*(){yield this.return(e)})}write(e){this._ensureOpen()&&(this.resolvers.length<=0?this._values.push(e):this.resolvers.shift().resolve({done:!1,value:e}))}abort(e){this._closedPromiseResolve&&(this.resolvers.length<=0?this._error={error:e}:this.resolvers.shift().reject({done:!0,value:e}))}close(){if(this._closedPromiseResolve){let{resolvers:e}=this;for(;e.length>0;)e.shift().resolve(jN);this._closedPromiseResolve(),this._closedPromiseResolve=void 0}}[Symbol.asyncIterator](){return this}toDOMStream(e){return BD.toDOMStream(this._closedPromiseResolve||this._error?this:this._values,e)}toNodeStream(e){return BD.toNodeStream(this._closedPromiseResolve||this._error?this:this._values,e)}throw(e){return QE(this,void 0,void 0,function*(){return yield this.abort(e),jN})}return(e){return QE(this,void 0,void 0,function*(){return yield this.close(),jN})}read(e){return QE(this,void 0,void 0,function*(){return(yield this.next(e,`read`)).value})}peek(e){return QE(this,void 0,void 0,function*(){return(yield this.next(e,`peek`)).value})}next(...e){return this._values.length>0?Promise.resolve({done:!1,value:this._values.shift()}):this._error?Promise.reject({done:!0,value:this._error.error}):this._closedPromiseResolve?new Promise((e,t)=>{this.resolvers.push({resolve:e,reject:t})}):Promise.resolve(jN)}_ensureOpen(){if(this._closedPromiseResolve)return!0;throw Error(`AsyncQueue is closed`)}},FN=class extends PN{write(e){if((e=MD(e)).byteLength>0)return super.write(e)}toString(e=!1){return e?aD(this.toUint8Array(!0)):this.toUint8Array(!1).then(aD)}toUint8Array(e=!1){return e?OD(this._values)[0]:QE(this,void 0,void 0,function*(){var e,t,n,r;let i=[],a=0;try{for(var o=!0,s=rD(this),c;c=yield s.next(),e=c.done,!e;o=!0){r=c.value,o=!1;let e=r;i.push(e),a+=e.byteLength}}catch(e){t={error:e}}finally{try{!o&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(t)throw t.error}}return OD(i,a)[0]})}},IN=class{constructor(e){e&&(this.source=new RN(BD.fromIterable(e)))}[Symbol.iterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}},LN=class e{constructor(t){t instanceof e?this.source=t.source:t instanceof FN?this.source=new zN(BD.fromAsyncIterable(t)):CD(t)?this.source=new zN(BD.fromNodeStream(t)):xD(t)?this.source=new zN(BD.fromDOMStream(t)):vD(t)?this.source=new zN(BD.fromDOMStream(t.body)):pD(t)?this.source=new zN(BD.fromIterable(t)):(fD(t)||mD(t))&&(this.source=new zN(BD.fromAsyncIterable(t)))}[Symbol.asyncIterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}get closed(){return this.source.closed}cancel(e){return this.source.cancel(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}},RN=class{constructor(e){this.source=e}cancel(e){this.return(e)}peek(e){return this.next(e,`peek`).value}read(e){return this.next(e,`read`).value}next(e,t=`read`){return this.source.next({cmd:t,size:e})}throw(e){return Object.create(this.source.throw&&this.source.throw(e)||jN)}return(e){return Object.create(this.source.return&&this.source.return(e)||jN)}},zN=class{constructor(e){this.source=e,this._closedPromise=new Promise(e=>this._closedPromiseResolve=e)}cancel(e){return QE(this,void 0,void 0,function*(){yield this.return(e)})}get closed(){return this._closedPromise}read(e){return QE(this,void 0,void 0,function*(){return(yield this.next(e,`read`)).value})}peek(e){return QE(this,void 0,void 0,function*(){return(yield this.next(e,`peek`)).value})}next(e){return QE(this,arguments,void 0,function*(e,t=`read`){return yield this.source.next({cmd:t,size:e})})}throw(e){return QE(this,void 0,void 0,function*(){let t=this.source.throw&&(yield this.source.throw(e))||jN;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}return(e){return QE(this,void 0,void 0,function*(){let t=this.source.return&&(yield this.source.return(e))||jN;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}},BN=class extends IN{constructor(e,t){super(),this.position=0,this.buffer=MD(e),this.size=t===void 0?this.buffer.byteLength:t}readInt32(e){let{buffer:t,byteOffset:n}=this.readAt(e,4);return new DataView(t,n).getInt32(0,!0)}seek(e){return this.position=Math.min(e,this.size),e<this.size}read(e){let{buffer:t,size:n,position:r}=this;return t&&r<n?(typeof e!=`number`&&(e=1/0),this.position=Math.min(n,r+Math.min(n-r,e)),t.subarray(r,this.position)):null}readAt(e,t){let n=this.buffer,r=Math.min(this.size,e+t);return n?n.subarray(e,r):new Uint8Array(t)}close(){this.buffer&&=null}throw(e){return this.close(),{done:!0,value:e}}return(e){return this.close(),{done:!0,value:e}}},VN=class extends LN{constructor(e,t){super(),this.position=0,this._handle=e,typeof t==`number`?this.size=t:this._pending=QE(this,void 0,void 0,function*(){this.size=(yield e.stat()).size,delete this._pending})}readInt32(e){return QE(this,void 0,void 0,function*(){let{buffer:t,byteOffset:n}=yield this.readAt(e,4);return new DataView(t,n).getInt32(0,!0)})}seek(e){return QE(this,void 0,void 0,function*(){return this._pending&&(yield this._pending),this.position=Math.min(e,this.size),e<this.size})}read(e){return QE(this,void 0,void 0,function*(){this._pending&&(yield this._pending);let{_handle:t,size:n,position:r}=this;if(t&&r<n){typeof e!=`number`&&(e=1/0);let i=r,a=0,o=0,s=Math.min(n,i+Math.min(n-i,e)),c=new Uint8Array(Math.max(0,(this.position=s)-i));for(;(i+=o)<s&&(a+=o)<c.byteLength;)({bytesRead:o}=yield t.read(c,a,c.byteLength-a,i));return c}return null})}readAt(e,t){return QE(this,void 0,void 0,function*(){this._pending&&(yield this._pending);let{_handle:n,size:r}=this;if(n&&e+t<r){let i=Math.min(r,e+t),a=new Uint8Array(i-e);return(yield n.read(a,0,t,e)).buffer}return new Uint8Array(t)})}close(){return QE(this,void 0,void 0,function*(){let e=this._handle;this._handle=null,e&&(yield e.close())})}throw(e){return QE(this,void 0,void 0,function*(){return yield this.close(),{done:!0,value:e}})}return(e){return QE(this,void 0,void 0,function*(){return yield this.close(),{done:!0,value:e}})}},HN=65536;function UN(e){return e<0&&(e=4294967295+e+1),`0x${e.toString(16)}`}var WN=8,GN=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8],KN=class{constructor(e){this.buffer=e}high(){return this.buffer[1]}low(){return this.buffer[0]}_times(e){let t=new Uint32Array([this.buffer[1]>>>16,this.buffer[1]&65535,this.buffer[0]>>>16,this.buffer[0]&65535]),n=new Uint32Array([e.buffer[1]>>>16,e.buffer[1]&65535,e.buffer[0]>>>16,e.buffer[0]&65535]),r=t[3]*n[3];this.buffer[0]=r&65535;let i=r>>>16;return r=t[2]*n[3],i+=r,r=t[3]*n[2]>>>0,i+=r,this.buffer[0]+=i<<16,this.buffer[1]=i>>>0<r?HN:0,this.buffer[1]+=i>>>16,this.buffer[1]+=t[1]*n[3]+t[2]*n[2]+t[3]*n[1],this.buffer[1]+=t[0]*n[3]+t[1]*n[2]+t[2]*n[1]+t[3]*n[0]<<16,this}_plus(e){let t=this.buffer[0]+e.buffer[0]>>>0;this.buffer[1]+=e.buffer[1],t<this.buffer[0]>>>0&&++this.buffer[1],this.buffer[0]=t}lessThan(e){return this.buffer[1]<e.buffer[1]||this.buffer[1]===e.buffer[1]&&this.buffer[0]<e.buffer[0]}equals(e){return this.buffer[1]===e.buffer[1]&&this.buffer[0]==e.buffer[0]}greaterThan(e){return e.lessThan(this)}hex(){return`${UN(this.buffer[1])} ${UN(this.buffer[0])}`}},qN=class e extends KN{times(e){return this._times(e),this}plus(e){return this._plus(e),this}static from(t,n=new Uint32Array(2)){return e.fromString(typeof t==`string`?t:t.toString(),n)}static fromNumber(t,n=new Uint32Array(2)){return e.fromString(t.toString(),n)}static fromString(t,n=new Uint32Array(2)){let r=t.length,i=new e(n);for(let n=0;n<r;){let a=WN<r-n?WN:r-n,o=new e(new Uint32Array([Number.parseInt(t.slice(n,n+a),10),0])),s=new e(new Uint32Array([GN[a],0]));i.times(s),i.plus(o),n+=a}return i}static convertArray(t){let n=new Uint32Array(t.length*2);for(let r=-1,i=t.length;++r<i;)e.from(t[r],new Uint32Array(n.buffer,n.byteOffset+2*r*4,2));return n}static multiply(t,n){return new e(new Uint32Array(t.buffer)).times(n)}static add(t,n){return new e(new Uint32Array(t.buffer)).plus(n)}},JN=class e extends KN{negate(){return this.buffer[0]=~this.buffer[0]+1,this.buffer[1]=~this.buffer[1],this.buffer[0]==0&&++this.buffer[1],this}times(e){return this._times(e),this}plus(e){return this._plus(e),this}lessThan(e){let t=this.buffer[1]<<0,n=e.buffer[1]<<0;return t<n||t===n&&this.buffer[0]<e.buffer[0]}static from(t,n=new Uint32Array(2)){return e.fromString(typeof t==`string`?t:t.toString(),n)}static fromNumber(t,n=new Uint32Array(2)){return e.fromString(t.toString(),n)}static fromString(t,n=new Uint32Array(2)){let r=t.startsWith(`-`),i=t.length,a=new e(n);for(let n=+!!r;n<i;){let r=WN<i-n?WN:i-n,o=new e(new Uint32Array([Number.parseInt(t.slice(n,n+r),10),0])),s=new e(new Uint32Array([GN[r],0]));a.times(s),a.plus(o),n+=r}return r?a.negate():a}static convertArray(t){let n=new Uint32Array(t.length*2);for(let r=-1,i=t.length;++r<i;)e.from(t[r],new Uint32Array(n.buffer,n.byteOffset+2*r*4,2));return n}static multiply(t,n){return new e(new Uint32Array(t.buffer)).times(n)}static add(t,n){return new e(new Uint32Array(t.buffer)).plus(n)}},YN=class e{constructor(e){this.buffer=e}high(){return new JN(new Uint32Array(this.buffer.buffer,this.buffer.byteOffset+8,2))}low(){return new JN(new Uint32Array(this.buffer.buffer,this.buffer.byteOffset,2))}negate(){return this.buffer[0]=~this.buffer[0]+1,this.buffer[1]=~this.buffer[1],this.buffer[2]=~this.buffer[2],this.buffer[3]=~this.buffer[3],this.buffer[0]==0&&++this.buffer[1],this.buffer[1]==0&&++this.buffer[2],this.buffer[2]==0&&++this.buffer[3],this}times(e){let t=new qN(new Uint32Array([this.buffer[3],0])),n=new qN(new Uint32Array([this.buffer[2],0])),r=new qN(new Uint32Array([this.buffer[1],0])),i=new qN(new Uint32Array([this.buffer[0],0])),a=new qN(new Uint32Array([e.buffer[3],0])),o=new qN(new Uint32Array([e.buffer[2],0])),s=new qN(new Uint32Array([e.buffer[1],0])),c=new qN(new Uint32Array([e.buffer[0],0])),l=qN.multiply(i,c);this.buffer[0]=l.low();let u=new qN(new Uint32Array([l.high(),0]));return l=qN.multiply(r,c),u.plus(l),l=qN.multiply(i,s),u.plus(l),this.buffer[1]=u.low(),this.buffer[3]=+!!u.lessThan(l),this.buffer[2]=u.high(),new qN(new Uint32Array(this.buffer.buffer,this.buffer.byteOffset+8,2)).plus(qN.multiply(n,c)).plus(qN.multiply(r,s)).plus(qN.multiply(i,o)),this.buffer[3]+=qN.multiply(t,c).plus(qN.multiply(n,s)).plus(qN.multiply(r,o)).plus(qN.multiply(i,a)).low(),this}plus(e){let t=new Uint32Array(4);return t[3]=this.buffer[3]+e.buffer[3]>>>0,t[2]=this.buffer[2]+e.buffer[2]>>>0,t[1]=this.buffer[1]+e.buffer[1]>>>0,t[0]=this.buffer[0]+e.buffer[0]>>>0,t[0]<this.buffer[0]>>>0&&++t[1],t[1]<this.buffer[1]>>>0&&++t[2],t[2]<this.buffer[2]>>>0&&++t[3],this.buffer[3]=t[3],this.buffer[2]=t[2],this.buffer[1]=t[1],this.buffer[0]=t[0],this}hex(){return`${UN(this.buffer[3])} ${UN(this.buffer[2])} ${UN(this.buffer[1])} ${UN(this.buffer[0])}`}static multiply(t,n){return new e(new Uint32Array(t.buffer)).times(n)}static add(t,n){return new e(new Uint32Array(t.buffer)).plus(n)}static from(t,n=new Uint32Array(4)){return e.fromString(typeof t==`string`?t:t.toString(),n)}static fromNumber(t,n=new Uint32Array(4)){return e.fromString(t.toString(),n)}static fromString(t,n=new Uint32Array(4)){let r=t.startsWith(`-`),i=t.length,a=new e(n);for(let n=+!!r;n<i;){let r=WN<i-n?WN:i-n,o=new e(new Uint32Array([Number.parseInt(t.slice(n,n+r),10),0,0,0])),s=new e(new Uint32Array([GN[r],0,0,0]));a.times(s),a.plus(o),n+=r}return r?a.negate():a}static convertArray(t){let n=new Uint32Array(t.length*4);for(let r=-1,i=t.length;++r<i;)e.from(t[r],new Uint32Array(n.buffer,n.byteOffset+16*r,4));return n}},XN=class extends cA{constructor(e,t,n,r,i=JD.V5){super(),this.nodesIndex=-1,this.buffersIndex=-1,this.bytes=e,this.nodes=t,this.buffers=n,this.dictionaries=r,this.metadataVersion=i}visit(e){return super.visit(e instanceof CN?e.type:e)}visitNull(e,{length:t}=this.nextFieldNode()){return FM({type:e,length:t})}visitBool(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitInt(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitFloat(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitUtf8(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),data:this.readData(e)})}visitLargeUtf8(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),data:this.readData(e)})}visitBinary(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),data:this.readData(e)})}visitLargeBinary(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),data:this.readData(e)})}visitFixedSizeBinary(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitDate(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitTimestamp(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitTime(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitDecimal(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitList(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),child:this.visit(e.children[0])})}visitStruct(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),children:this.visitMany(e.children)})}visitUnion(e,{length:t,nullCount:n}=this.nextFieldNode()){return this.metadataVersion<JD.V5&&this.readNullBitmap(e,n),e.mode===YD.Sparse?this.visitSparseUnion(e,{length:t,nullCount:n}):this.visitDenseUnion(e,{length:t,nullCount:n})}visitDenseUnion(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,typeIds:this.readTypeIds(e),valueOffsets:this.readOffsets(e),children:this.visitMany(e.children)})}visitSparseUnion(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,typeIds:this.readTypeIds(e),children:this.visitMany(e.children)})}visitDictionary(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e.indices),dictionary:this.readDictionary(e)})}visitInterval(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitDuration(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitFixedSizeList(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),child:this.visit(e.children[0])})}visitMap(e,{length:t,nullCount:n}=this.nextFieldNode()){return FM({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),child:this.visit(e.children[0])})}nextFieldNode(){return this.nodes[++this.nodesIndex]}nextBufferRange(){return this.buffers[++this.buffersIndex]}readNullBitmap(e,t,n=this.nextBufferRange()){return t>0&&this.readData(e,n)||new Uint8Array}readOffsets(e,t){return this.readData(e,t)}readTypeIds(e,t){return this.readData(e,t)}readData(e,{length:t,offset:n}=this.nextBufferRange()){return this.bytes.subarray(n,n+t)}readDictionary(e){return this.dictionaries.get(e.id)}},ZN=class extends XN{constructor(e,t,n,r,i){super(new Uint8Array,t,n,r,i),this.sources=e}readNullBitmap(e,t,{offset:n}=this.nextBufferRange()){return t<=0?new Uint8Array:OM(this.sources[n])}readOffsets(e,{offset:t}=this.nextBufferRange()){return kD(Uint8Array,kD(e.OffsetArrayType,this.sources[t]))}readTypeIds(e,{offset:t}=this.nextBufferRange()){return kD(Uint8Array,kD(e.ArrayType,this.sources[t]))}readData(e,{offset:t}=this.nextBufferRange()){let{sources:n}=this;return Ek.isTimestamp(e)||(Ek.isInt(e)||Ek.isTime(e))&&e.bitWidth===64||Ek.isDuration(e)||Ek.isDate(e)&&e.unit===ZD.MILLISECOND?kD(Uint8Array,JN.convertArray(n[t])):Ek.isDecimal(e)?kD(Uint8Array,YN.convertArray(n[t])):Ek.isBinary(e)||Ek.isLargeBinary(e)||Ek.isFixedSizeBinary(e)?QN(n[t]):Ek.isBool(e)?OM(n[t]):Ek.isUtf8(e)||Ek.isLargeUtf8(e)?sD(n[t].join(``)):kD(Uint8Array,kD(e.ArrayType,n[t].map(e=>+e)))}};function QN(e){let t=e.join(``),n=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e>>1]=Number.parseInt(t.slice(e,e+2),16);return n}var $N=class extends yN{constructor(e){super(e),this._values=new pN(Uint8Array)}get byteLength(){let e=this._pendingLength+this.length*4;return this._offsets&&(e+=this._offsets.byteLength),this._values&&(e+=this._values.byteLength),this._nulls&&(e+=this._nulls.byteLength),e}setValue(e,t){return super.setValue(e,MD(t))}_flushPending(e,t){let n=this._offsets,r=this._values.reserve(t).buffer,i=0;for(let[t,a]of e)if(a===void 0)n.set(t,0);else{let e=a.length;r.set(a,i),n.set(t,e),i+=e}}},eP=class extends yN{constructor(e){super(e),this._values=new pN(Uint8Array)}get byteLength(){let e=this._pendingLength+this.length*4;return this._offsets&&(e+=this._offsets.byteLength),this._values&&(e+=this._values.byteLength),this._nulls&&(e+=this._nulls.byteLength),e}setValue(e,t){return super.setValue(e,MD(t))}_flushPending(e,t){let n=this._offsets,r=this._values.reserve(t).buffer,i=0;for(let[t,a]of e)if(a===void 0)n.set(t,BigInt(0));else{let e=a.length;r.set(a,i),n.set(t,BigInt(e)),i+=e}}},tP=class extends _N{constructor(e){super(e),this._values=new hN}setValue(e,t){this._values.set(e,+t)}},nP=class extends vN{};nP.prototype._setValue=AA;var rP=class extends nP{};rP.prototype._setValue=TA;var iP=class extends nP{};iP.prototype._setValue=EA;var aP=class extends vN{};aP.prototype._setValue=VA;var oP=class extends _N{constructor({type:e,nullValues:t,dictionaryHashFunction:n}){super({type:new oA(e.dictionary,e.indices,e.id,e.isOrdered)}),this._nulls=null,this._dictionaryOffset=0,this._keysToIndices=Object.create(null),this.indices=gF({type:this.type.indices,nullValues:t}),this.dictionary=gF({type:this.type.dictionary,nullValues:null}),typeof n==`function`&&(this.valueToKey=n)}get values(){return this.indices.values}get nullCount(){return this.indices.nullCount}get nullBitmap(){return this.indices.nullBitmap}get byteLength(){return this.indices.byteLength+this.dictionary.byteLength}get reservedLength(){return this.indices.reservedLength+this.dictionary.reservedLength}get reservedByteLength(){return this.indices.reservedByteLength+this.dictionary.reservedByteLength}isValid(e){return this.indices.isValid(e)}setValid(e,t){let n=this.indices;return t=n.setValid(e,t),this.length=n.length,t}setValue(e,t){let n=this._keysToIndices,r=this.valueToKey(t),i=n[r];return i===void 0&&(n[r]=i=this._dictionaryOffset+this.dictionary.append(t).length-1),this.indices.setValue(e,i)}flush(){let e=this.type,t=this._dictionary,n=this.dictionary.toVector(),r=this.indices.flush().clone(e);return r.dictionary=t?t.concat(n):n,this.finished||(this._dictionaryOffset+=n.length),this._dictionary=r.dictionary,this.clear(),r}finish(){return this.indices.finish(),this.dictionary.finish(),this._dictionaryOffset=0,this._keysToIndices=Object.create(null),super.finish()}clear(){return this.indices.clear(),this.dictionary.clear(),super.clear()}valueToKey(e){return typeof e==`string`?e:`${e}`}},sP=class extends vN{};sP.prototype._setValue=DA;var cP=class extends _N{setValue(e,t){let[n]=this.children,r=e*this.stride;for(let e=-1,i=t.length;++e<i;)n.set(r+e,t[e])}addChild(e,t=`0`){if(this.numChildren>0)throw Error(`FixedSizeListBuilder can only have one child.`);let n=this.children.push(e);return this.type=new rA(this.type.listSize,new CN(t,e.type,!0)),n}},lP=class extends vN{setValue(e,t){this._values.set(e,t)}},uP=class extends lP{setValue(e,t){super.setValue(e,hA(t))}},dP=class extends lP{},fP=class extends lP{},pP=class extends vN{};pP.prototype._setValue=$A;var mP=class extends pP{};mP.prototype._setValue=ej;var hP=class extends pP{};hP.prototype._setValue=tj;var gP=class extends vN{};gP.prototype._setValue=oj;var _P=class extends gP{};_P.prototype._setValue=nj;var vP=class extends gP{};vP.prototype._setValue=rj;var yP=class extends gP{};yP.prototype._setValue=ij;var bP=class extends gP{};bP.prototype._setValue=aj;var xP=class extends vN{setValue(e,t){this._values.set(e,t)}},SP=class extends xP{},CP=class extends xP{},wP=class extends xP{},TP=class extends xP{},EP=class extends xP{},DP=class extends xP{},OP=class extends xP{},kP=class extends xP{},AP=class extends yN{constructor(e){super(e),this._offsets=new gN(e.type)}addChild(e,t=`0`){if(this.numChildren>0)throw Error(`ListBuilder can only have one child.`);return this.children[this.numChildren]=e,this.type=new $k(new CN(t,e.type,!0)),this.numChildren-1}_flushPending(e){let t=this._offsets,[n]=this.children;for(let[r,i]of e)if(i===void 0)t.set(r,0);else{let e=i,a=e.length,o=t.set(r,a).buffer[r];for(let t=-1;++t<a;)n.set(o+t,e[t])}}},jP=class extends yN{set(e,t){return super.set(e,t)}setValue(e,t){let n=t instanceof Map?t:new Map(Object.entries(t)),r=this._pending||=new Map,i=r.get(e);i&&(this._pendingLength-=i.size),this._pendingLength+=n.size,r.set(e,n)}addChild(e,t=`${this.numChildren}`){if(this.numChildren>0)throw Error(`ListBuilder can only have one child.`);return this.children[this.numChildren]=e,this.type=new iA(new CN(t,e.type,!0),this.type.keysSorted),this.numChildren-1}_flushPending(e){let t=this._offsets,[n]=this.children;for(let[r,i]of e)if(i===void 0)t.set(r,0);else{let{[r]:e,[r+1]:a}=t.set(r,i.size).buffer;for(let t of i.entries())if(n.set(e,t),++e>=a)break}}},MP=class extends _N{setValue(e,t){}setValid(e,t){return this.length=Math.max(e+1,this.length),t}},NP=class extends _N{setValue(e,t){let{children:n,type:r}=this;switch(Array.isArray(t)||t.constructor){case!0:return r.children.forEach((r,i)=>n[i].set(e,t[i]));case Map:return r.children.forEach((r,i)=>n[i].set(e,t.get(r.name)));default:return r.children.forEach((r,i)=>n[i].set(e,t[r.name]))}}setValid(e,t){return super.setValid(e,t)||this.children.forEach(n=>n.setValid(e,t)),t}addChild(e,t=`${this.numChildren}`){let n=this.children.push(e);return this.type=new eA([...this.type.children,new CN(t,e.type,!0)]),n}},PP=class extends vN{};PP.prototype._setValue=FA;var FP=class extends PP{};FP.prototype._setValue=jA;var IP=class extends PP{};IP.prototype._setValue=MA;var LP=class extends PP{};LP.prototype._setValue=NA;var RP=class extends PP{};RP.prototype._setValue=PA;var zP=class extends vN{};zP.prototype._setValue=BA;var BP=class extends zP{};BP.prototype._setValue=IA;var VP=class extends zP{};VP.prototype._setValue=LA;var HP=class extends zP{};HP.prototype._setValue=RA;var UP=class extends zP{};UP.prototype._setValue=zA;var WP=class extends _N{constructor(e){super(e),this._typeIds=new mN(Int8Array,0,1),typeof e.valueToChildTypeId==`function`&&(this._valueToChildTypeId=e.valueToChildTypeId)}get typeIdToChildIndex(){return this.type.typeIdToChildIndex}append(e,t){return this.set(this.length,e,t)}set(e,t,n){return n===void 0&&(n=this._valueToChildTypeId(this,t,e)),this.setValue(e,t,n),this}setValue(e,t,n){this._typeIds.set(e,n);let r=this.type.typeIdToChildIndex[n];this.children[r]?.set(e,t)}addChild(e,t=`${this.children.length}`){let n=this.children.push(e),{type:{children:r,mode:i,typeIds:a}}=this,o=[...r,new CN(t,e.type)];return this.type=new tA(i,[...a,n],o),n}_valueToChildTypeId(e,t,n){throw Error("Cannot map UnionBuilder value to child typeId. Pass the `childTypeId` as the second argument to unionBuilder.append(), or supply a `valueToChildTypeId` function as part of the UnionBuilder constructor options.")}},GP=class extends WP{},KP=class extends WP{constructor(e){super(e),this._offsets=new mN(Int32Array)}setValue(e,t,n){let r=this._typeIds.set(e,n).buffer[e],i=this.getChildAt(this.type.typeIdToChildIndex[r]),a=this._offsets.set(e,i.length).buffer[e];i?.set(a,t)}},qP=class extends yN{constructor(e){super(e),this._values=new pN(Uint8Array)}get byteLength(){let e=this._pendingLength+this.length*4;return this._offsets&&(e+=this._offsets.byteLength),this._values&&(e+=this._values.byteLength),this._nulls&&(e+=this._nulls.byteLength),e}setValue(e,t){return super.setValue(e,sD(t))}_flushPending(e,t){}};qP.prototype._flushPending=$N.prototype._flushPending;var JP=class extends yN{constructor(e){super(e),this._values=new pN(Uint8Array)}get byteLength(){let e=this._pendingLength+this.length*4;return this._offsets&&(e+=this._offsets.byteLength),this._values&&(e+=this._values.byteLength),this._nulls&&(e+=this._nulls.byteLength),e}setValue(e,t){return super.setValue(e,sD(t))}_flushPending(e,t){}};JP.prototype._flushPending=eP.prototype._flushPending;var YP=new class extends cA{visitNull(){return MP}visitBool(){return tP}visitInt(){return xP}visitInt8(){return SP}visitInt16(){return CP}visitInt32(){return wP}visitInt64(){return TP}visitUint8(){return EP}visitUint16(){return DP}visitUint32(){return OP}visitUint64(){return kP}visitFloat(){return lP}visitFloat16(){return uP}visitFloat32(){return dP}visitFloat64(){return fP}visitUtf8(){return qP}visitLargeUtf8(){return JP}visitBinary(){return $N}visitLargeBinary(){return eP}visitFixedSizeBinary(){return sP}visitDate(){return nP}visitDateDay(){return rP}visitDateMillisecond(){return iP}visitTimestamp(){return PP}visitTimestampSecond(){return FP}visitTimestampMillisecond(){return IP}visitTimestampMicrosecond(){return LP}visitTimestampNanosecond(){return RP}visitTime(){return zP}visitTimeSecond(){return BP}visitTimeMillisecond(){return VP}visitTimeMicrosecond(){return HP}visitTimeNanosecond(){return UP}visitDecimal(){return aP}visitList(){return AP}visitStruct(){return NP}visitUnion(){return WP}visitDenseUnion(){return KP}visitSparseUnion(){return GP}visitDictionary(){return oP}visitInterval(){return pP}visitIntervalDayTime(){return mP}visitIntervalYearMonth(){return hP}visitDuration(){return gP}visitDurationSecond(){return _P}visitDurationMillisecond(){return vP}visitDurationMicrosecond(){return yP}visitDurationNanosecond(){return bP}visitFixedSizeList(){return cP}visitMap(){return jP}},XP=class extends cA{compareSchemas(e,t){return e===t||t instanceof e.constructor&&this.compareManyFields(e.fields,t.fields)}compareManyFields(e,t){return e===t||Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>this.compareFields(e,t[n]))}compareFields(e,t){return e===t||t instanceof e.constructor&&e.name===t.name&&e.nullable===t.nullable&&this.visit(e.type,t.type)}};function ZP(e,t){return t instanceof e.constructor}function QP(e,t){return e===t||ZP(e,t)}function $P(e,t){return e===t||ZP(e,t)&&e.bitWidth===t.bitWidth&&e.isSigned===t.isSigned}function eF(e,t){return e===t||ZP(e,t)&&e.precision===t.precision}function tF(e,t){return e===t||ZP(e,t)&&e.byteWidth===t.byteWidth}function nF(e,t){return e===t||ZP(e,t)&&e.unit===t.unit}function rF(e,t){return e===t||ZP(e,t)&&e.unit===t.unit&&e.timezone===t.timezone}function iF(e,t){return e===t||ZP(e,t)&&e.unit===t.unit&&e.bitWidth===t.bitWidth}function aF(e,t){return e===t||ZP(e,t)&&e.children.length===t.children.length&&pF.compareManyFields(e.children,t.children)}function oF(e,t){return e===t||ZP(e,t)&&e.children.length===t.children.length&&pF.compareManyFields(e.children,t.children)}function sF(e,t){return e===t||ZP(e,t)&&e.mode===t.mode&&e.typeIds.every((e,n)=>e===t.typeIds[n])&&pF.compareManyFields(e.children,t.children)}function cF(e,t){return e===t||ZP(e,t)&&e.id===t.id&&e.isOrdered===t.isOrdered&&pF.visit(e.indices,t.indices)&&pF.visit(e.dictionary,t.dictionary)}function lF(e,t){return e===t||ZP(e,t)&&e.unit===t.unit}function uF(e,t){return e===t||ZP(e,t)&&e.unit===t.unit}function dF(e,t){return e===t||ZP(e,t)&&e.listSize===t.listSize&&e.children.length===t.children.length&&pF.compareManyFields(e.children,t.children)}function fF(e,t){return e===t||ZP(e,t)&&e.keysSorted===t.keysSorted&&e.children.length===t.children.length&&pF.compareManyFields(e.children,t.children)}XP.prototype.visitNull=QP,XP.prototype.visitBool=QP,XP.prototype.visitInt=$P,XP.prototype.visitInt8=$P,XP.prototype.visitInt16=$P,XP.prototype.visitInt32=$P,XP.prototype.visitInt64=$P,XP.prototype.visitUint8=$P,XP.prototype.visitUint16=$P,XP.prototype.visitUint32=$P,XP.prototype.visitUint64=$P,XP.prototype.visitFloat=eF,XP.prototype.visitFloat16=eF,XP.prototype.visitFloat32=eF,XP.prototype.visitFloat64=eF,XP.prototype.visitUtf8=QP,XP.prototype.visitLargeUtf8=QP,XP.prototype.visitBinary=QP,XP.prototype.visitLargeBinary=QP,XP.prototype.visitFixedSizeBinary=tF,XP.prototype.visitDate=nF,XP.prototype.visitDateDay=nF,XP.prototype.visitDateMillisecond=nF,XP.prototype.visitTimestamp=rF,XP.prototype.visitTimestampSecond=rF,XP.prototype.visitTimestampMillisecond=rF,XP.prototype.visitTimestampMicrosecond=rF,XP.prototype.visitTimestampNanosecond=rF,XP.prototype.visitTime=iF,XP.prototype.visitTimeSecond=iF,XP.prototype.visitTimeMillisecond=iF,XP.prototype.visitTimeMicrosecond=iF,XP.prototype.visitTimeNanosecond=iF,XP.prototype.visitDecimal=QP,XP.prototype.visitList=aF,XP.prototype.visitStruct=oF,XP.prototype.visitUnion=sF,XP.prototype.visitDenseUnion=sF,XP.prototype.visitSparseUnion=sF,XP.prototype.visitDictionary=cF,XP.prototype.visitInterval=lF,XP.prototype.visitIntervalDayTime=lF,XP.prototype.visitIntervalYearMonth=lF,XP.prototype.visitDuration=uF,XP.prototype.visitDurationSecond=uF,XP.prototype.visitDurationMillisecond=uF,XP.prototype.visitDurationMicrosecond=uF,XP.prototype.visitDurationNanosecond=uF,XP.prototype.visitFixedSizeList=dF,XP.prototype.visitMap=fF;var pF=new XP;function mF(e,t){return pF.compareSchemas(e,t)}function hF(e,t){return pF.visit(e,t)}function gF(e){let t=e.type,n=new(YP.getVisitFn(t)())(e);if(t.children&&t.children.length>0){let r=e.children||[],i={nullValues:e.nullValues},a=Array.isArray(r)?((e,t)=>r[t]||i):(({name:e})=>r[e]||i);for(let[e,r]of t.children.entries()){let{type:t}=r,i=a(r,e);n.children.push(gF(Object.assign(Object.assign({},i),{type:t})))}}return n}function _F(e,t){if(e instanceof NM||e instanceof aN||e.type instanceof Ek||ArrayBuffer.isView(e))return sN(e);let n=[...yF({type:t??vF(e),nullValues:[null]})(e)],r=n.length===1?n[0]:n.reduce((e,t)=>e.concat(t));return Ek.isDictionary(r.type)?r.memoize():r}function vF(e){if(e.length===0)return new Dk;let t=0,n=0,r=0,i=0,a=0,o=0,s=0,c=0;for(let l of e){if(l==null){++t;continue}switch(typeof l){case`bigint`:++o;continue;case`boolean`:++s;continue;case`number`:++i;continue;case`string`:++a;continue;case`object`:Array.isArray(l)?++n:Object.prototype.toString.call(l)===`[object Date]`?++c:++r;continue}throw TypeError(`Unable to infer Vector type from input values, explicit type declaration expected.`)}if(i+t===e.length)return new Bk;if(a+t===e.length)return new oA(new Uk,new jk);if(o+t===e.length)return new Mk;if(s+t===e.length)return new Gk;if(c+t===e.length)return new Xk;if(n+t===e.length){let t=e,n=vF(t[t.findIndex(e=>e!=null)]);if(t.every(e=>e==null||hF(n,vF(e))))return new $k(new CN(``,n,!0))}else if(r+t===e.length){let t=new Map;for(let n of e)for(let e of Object.keys(n))!t.has(e)&&n[e]!=null&&t.set(e,new CN(e,vF([n[e]]),!0));return new eA([...t.values()])}throw TypeError(`Unable to infer Vector type from input values, explicit type declaration expected.`)}function yF(e){let{queueingStrategy:t=`count`}=e,{highWaterMark:n=t===`bytes`?2**14:1/0}=e,r=t===`bytes`?`byteLength`:`length`;return function*(t){let i=0,a=gF(e);for(let e of t)a.append(e)[r]>=n&&++i&&(yield a.toVector());(a.finish().length>0||i===0)&&(yield a.toVector())}}function bF(e,t){return xF(e,t.map(e=>e.data.concat()))}function xF(e,t){let n=[...e.fields],r=[],i={numBatches:t.reduce((e,t)=>Math.max(e,t.length),0)},a=0,o=0,s=-1,c=t.length,l,u=[];for(;i.numBatches-- >0;){for(o=1/0,s=-1;++s<c;)u[s]=l=t[s].shift(),o=Math.min(o,l?l.length:o);Number.isFinite(o)&&(u=SF(n,o,u,t,i),o>0&&(r[a++]=FM({type:new eA(n),length:o,nullCount:0,children:u.slice()})))}return[e=e.assign(n),r.map(t=>new EF(e,t))]}function SF(e,t,n,r,i){let a=(t+63&-64)>>3;for(let o=-1,s=r.length;++o<s;){let s=n[o],c=s?.length;if(c>=t)c===t?n[o]=s:(n[o]=s.slice(0,t),i.numBatches=Math.max(i.numBatches,r[o].unshift(s.slice(t,c-t))));else{let r=e[o];e[o]=r.clone({nullable:!0}),n[o]=s?._changeLengthAndBackfillNullBitmap(t)??FM({type:r.type,length:t,nullCount:t,nullBitmap:new Uint8Array(a)})}}return n}var CF,wF=class e{constructor(...t){if(t.length===0)return this.batches=[],this.schema=new SN([]),this._offsets=[0],this;let n,r;t[0]instanceof SN&&(n=t.shift()),t.at(-1)instanceof Uint32Array&&(r=t.pop());let i=t=>{if(t){if(t instanceof EF)return[t];if(t instanceof e)return t.batches;if(t instanceof NM){if(t.type instanceof eA)return[new EF(new SN(t.type.children),t)]}else if(Array.isArray(t))return t.flatMap(e=>i(e));else if(typeof t[Symbol.iterator]==`function`)return[...t].flatMap(e=>i(e));else if(typeof t==`object`){let e=Object.keys(t),r=e.map(e=>new aN([t[e]])),[,i]=bF(n??new SN(e.map((e,t)=>new CN(String(e),r[t].type,r[t].nullable))),r);return i.length===0?[new EF(t)]:i}}return[]},a=t.flatMap(e=>i(e));if(n=n??a[0]?.schema??new SN([]),!(n instanceof SN))throw TypeError(`Table constructor expects a [Schema, RecordBatch[]] pair.`);for(let e of a){if(!(e instanceof EF))throw TypeError(`Table constructor expects a [Schema, RecordBatch[]] pair.`);if(!mF(n,e.schema))throw TypeError(`Table and inner RecordBatch schemas must be equivalent.`)}this.schema=n,this.batches=a,this._offsets=r??zM(this.data)}get data(){return this.batches.map(({data:e})=>e)}get numCols(){return this.schema.fields.length}get numRows(){return this.data.reduce((e,t)=>e+t.length,0)}get nullCount(){return this._nullCount===-1&&(this._nullCount=RM(this.data)),this._nullCount}isValid(e){return!1}get(e){return null}at(e){return this.get(mM(e,this.numRows))}set(e,t){}indexOf(e,t){return-1}[Symbol.iterator](){return this.batches.length>0?tN.visit(new aN(this.data)):[][Symbol.iterator]()}toArray(){return[...this]}toString(){return`[\n ${this.toArray().join(`,
69
- `)}\n]`}concat(...t){let n=this.schema;return new e(n,this.data.concat(t.flatMap(({data:e})=>e)).map(e=>new EF(n,e)))}slice(t,n){let r=this.schema;return[t,n]=pM({length:this.numRows},t,n),new e(r,BM(this.data,this._offsets,t,n).map(e=>new EF(r,e)))}getChild(e){return this.getChildAt(this.schema.fields.findIndex(t=>t.name===e))}getChildAt(e){if(e>-1&&e<this.schema.fields.length){let t=this.data.map(t=>t.children[e]);if(t.length===0){let{type:n}=this.schema.fields[e],r=FM({type:n,length:0,nullCount:0});t.push(r._changeLengthAndBackfillNullBitmap(this.numRows))}return new aN(t)}return null}setChild(e,t){return this.setChildAt(this.schema.fields?.findIndex(t=>t.name===e),t)}setChildAt(t,n){let r=this.schema,i=[...this.batches];if(t>-1&&t<this.numCols){n||=new aN([FM({type:new Dk,length:this.numRows})]);let e=r.fields.slice(),a=e[t].clone({type:n.type}),o=this.schema.fields.map((e,t)=>this.getChildAt(t));[e[t],o[t]]=[a,n],[r,i]=bF(r,o)}return new e(r,i)}select(e){let t=this.schema.fields.reduce((e,t,n)=>e.set(t.name,n),new Map);return this.selectAt(e.map(e=>t.get(e)).filter(e=>e>-1))}selectAt(t){return new e(this.schema.selectAt(t),this.batches.map(e=>e.selectAt(t)))}assign(t){let n=this.schema.fields,[r,i]=t.schema.fields.reduce((e,t,r)=>{let[i,a]=e,o=n.findIndex(e=>e.name===t.name);return~o?a[o]=r:i.push(r),e},[[],[]]);return new e(...bF(this.schema.assign(t.schema),[...n.map((e,t)=>[t,i[t]]).map(([e,n])=>n===void 0?this.getChildAt(e):t.getChildAt(n)),...r.map(e=>t.getChildAt(e))].filter(Boolean)))}};CF=Symbol.toStringTag,wF[CF]=(e=>(e.schema=null,e.batches=[],e._offsets=new Uint32Array([0]),e._nullCount=-1,e[Symbol.isConcatSpreadable]=!0,e.isValid=UM(HM),e.get=UM(iM.getVisitFn(Z.Struct)),e.set=WM(cj.getVisitFn(Z.Struct)),e.indexOf=GM(ZM.getVisitFn(Z.Struct)),`Table`))(wF.prototype);var TF,EF=class e{constructor(...e){switch(e.length){case 2:if([this.schema]=e,!(this.schema instanceof SN)||([,this.data=FM({nullCount:0,type:new eA(this.schema.fields),children:this.schema.fields.map(e=>FM({type:e.type,nullCount:0}))})]=e,!(this.data instanceof NM)))throw TypeError(`RecordBatch constructor expects a [Schema, Data] pair.`);[this.schema,this.data]=DF(this.schema,this.data.children);break;case 1:{let[t]=e,{fields:n,children:r,length:i}=Object.keys(t).reduce((e,n,r)=>(e.children[r]=t[n],e.length=Math.max(e.length,t[n].length),e.fields[r]=CN.new({name:n,type:t[n].type,nullable:!0}),e),{length:0,fields:[],children:[]}),a=new SN(n),o=FM({type:new eA(n),length:i,children:r,nullCount:0});[this.schema,this.data]=DF(a,o.children,i);break}default:throw TypeError(`RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.`)}}get dictionaries(){return this._dictionaries||=OF(this.schema.fields,this.data.children)}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(e){return this.data.getValid(e)}get(e){return iM.visit(this.data,e)}at(e){return this.get(mM(e,this.numRows))}set(e,t){return cj.visit(this.data,e,t)}indexOf(e,t){return ZM.visit(this.data,e,t)}[Symbol.iterator](){return tN.visit(new aN([this.data]))}toArray(){return[...this]}concat(...e){return new wF(this.schema,[this,...e])}slice(t,n){let[r]=new aN([this.data]).slice(t,n).data;return new e(this.schema,r)}getChild(e){return this.getChildAt(this.schema.fields?.findIndex(t=>t.name===e))}getChildAt(e){return e>-1&&e<this.schema.fields.length?new aN([this.data.children[e]]):null}setChild(e,t){return this.setChildAt(this.schema.fields?.findIndex(t=>t.name===e),t)}setChildAt(t,n){let r=this.schema,i=this.data;if(t>-1&&t<this.numCols){n||=new aN([FM({type:new Dk,length:this.numRows})]);let e=r.fields.slice(),a=i.children.slice(),o=e[t].clone({type:n.type});[e[t],a[t]]=[o,n.data[0]],r=new SN(e,new Map(this.schema.metadata)),i=FM({type:new eA(e),children:a})}return new e(r,i)}select(t){let n=this.schema.select(t),r=new eA(n.fields),i=[];for(let e of t){let t=this.schema.fields.findIndex(t=>t.name===e);~t&&(i[t]=this.data.children[t])}return new e(n,FM({type:r,length:this.numRows,children:i}))}selectAt(t){let n=this.schema.selectAt(t),r=t.map(e=>this.data.children[e]).filter(Boolean);return new e(n,FM({type:new eA(n.fields),length:this.numRows,children:r}))}};TF=Symbol.toStringTag,EF[TF]=(e=>(e._nullCount=-1,e[Symbol.isConcatSpreadable]=!0,`RecordBatch`))(EF.prototype);function DF(e,t,n=t.reduce((e,t)=>Math.max(e,t.length),0)){let r=[...e.fields],i=[...t],a=(n+63&-64)>>3;for(let[o,s]of e.fields.entries()){let e=t[o];(!e||e.length!==n)&&(r[o]=s.clone({nullable:!0}),i[o]=e?._changeLengthAndBackfillNullBitmap(n)??FM({type:s.type,length:n,nullCount:n,nullBitmap:new Uint8Array(a)}))}return[e.assign(r),FM({type:new eA(r),length:n,children:i})]}function OF(e,t,n=new Map){if((e?.length??0)>0&&e?.length===t?.length)for(let r=-1,i=e.length;++r<i;){let{type:i}=e[r],a=t[r];for(let e of[a,...a?.dictionary?.data||[]])OF(i.children,e?.children,n);if(Ek.isDictionary(i)){let{id:e}=i;if(!n.has(e))a?.dictionary&&n.set(e,a.dictionary);else if(n.get(e)!==a.dictionary)throw Error(`Cannot create Schema containing two different dictionaries with the same Id`)}}return n}var kF=class extends EF{constructor(e){let t=e.fields.map(e=>FM({type:e.type})),n=FM({type:new eA(e.fields),nullCount:0,children:t});super(e,n)}},AF=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMessage(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMessage(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}version(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):JD.V1}headerType(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb_pos+e):VO.NONE}header(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__union(e,this.bb_pos+t):null}bodyLength(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt64(this.bb_pos+e):BigInt(`0`)}customMetadata(e,t){let n=this.bb.__offset(this.bb_pos,12);return n?(t||new vO).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+e*4),this.bb):null}customMetadataLength(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startMessage(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,JD.V1)}static addHeaderType(e,t){e.addFieldInt8(1,t,VO.NONE)}static addHeader(e,t){e.addFieldOffset(2,t,0)}static addBodyLength(e,t){e.addFieldInt64(3,t,BigInt(`0`))}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endMessage(e){return e.endObject()}static finishMessageBuffer(e,t){e.finish(t)}static finishSizePrefixedMessageBuffer(e,t){e.finish(t,void 0,!0)}static createMessage(t,n,r,i,a,o){return e.startMessage(t),e.addVersion(t,n),e.addHeaderType(t,r),e.addHeader(t,i),e.addBodyLength(t,a),e.addCustomMetadata(t,o),e.endMessage(t)}},jF=new class extends cA{visit(e,t){return e==null||t==null?void 0:super.visit(e,t)}visitNull(e,t){return MO.startNull(t),MO.endNull(t)}visitInt(e,t){return gO.startInt(t),gO.addBitWidth(t,e.bitWidth),gO.addIsSigned(t,e.isSigned),gO.endInt(t)}visitFloat(e,t){return EO.startFloatingPoint(t),EO.addPrecision(t,e.precision),EO.endFloatingPoint(t)}visitBinary(e,t){return yO.startBinary(t),yO.endBinary(t)}visitLargeBinary(e,t){return OO.startLargeBinary(t),OO.endLargeBinary(t)}visitBool(e,t){return bO.startBool(t),bO.endBool(t)}visitUtf8(e,t){return LO.startUtf8(t),LO.endUtf8(t)}visitLargeUtf8(e,t){return kO.startLargeUtf8(t),kO.endLargeUtf8(t)}visitDecimal(e,t){return SO.startDecimal(t),SO.addScale(t,e.scale),SO.addPrecision(t,e.precision),SO.addBitWidth(t,e.bitWidth),SO.endDecimal(t)}visitDate(e,t){return xO.startDate(t),xO.addUnit(t,e.unit),xO.endDate(t)}visitTime(e,t){return PO.startTime(t),PO.addUnit(t,e.unit),PO.addBitWidth(t,e.bitWidth),PO.endTime(t)}visitTimestamp(e,t){let n=e.timezone&&t.createString(e.timezone)||void 0;return FO.startTimestamp(t),FO.addUnit(t,e.unit),n!==void 0&&FO.addTimezone(t,n),FO.endTimestamp(t)}visitInterval(e,t){return DO.startInterval(t),DO.addUnit(t,e.unit),DO.endInterval(t)}visitDuration(e,t){return CO.startDuration(t),CO.addUnit(t,e.unit),CO.endDuration(t)}visitList(e,t){return AO.startList(t),AO.endList(t)}visitStruct(e,t){return NO.startStruct_(t),NO.endStruct_(t)}visitUnion(e,t){IO.startTypeIdsVector(t,e.typeIds.length);let n=IO.createTypeIdsVector(t,e.typeIds);return IO.startUnion(t),IO.addMode(t,e.mode),IO.addTypeIds(t,n),IO.endUnion(t)}visitDictionary(e,t){let n=this.visit(e.indices,t);return _O.startDictionaryEncoding(t),_O.addId(t,BigInt(e.id)),_O.addIsOrdered(t,e.isOrdered),n!==void 0&&_O.addIndexType(t,n),_O.endDictionaryEncoding(t)}visitFixedSizeBinary(e,t){return wO.startFixedSizeBinary(t),wO.addByteWidth(t,e.byteWidth),wO.endFixedSizeBinary(t)}visitFixedSizeList(e,t){return TO.startFixedSizeList(t),TO.addListSize(t,e.listSize),TO.endFixedSizeList(t)}visitMap(e,t){return jO.startMap(t),jO.addKeysSorted(t,e.keysSorted),jO.endMap(t)}};function MF(e,t=new Map){return new SN(FF(e,t),VF(e.metadata),t)}function NF(e){return new qF(e.count,LF(e.columns),RF(e.columns))}function PF(e){return new JF(NF(e.data),e.id,e.isDelta)}function FF(e,t){return(e.fields||[]).filter(Boolean).map(e=>CN.fromJSON(e,t))}function IF(e,t){return(e.children||[]).filter(Boolean).map(e=>CN.fromJSON(e,t))}function LF(e){return(e||[]).reduce((e,t)=>[...e,new XF(t.count,zF(t.VALIDITY)),...LF(t.children)],[])}function RF(e,t=[]){for(let n=-1,r=(e||[]).length;++n<r;){let r=e[n];r.VALIDITY&&t.push(new YF(t.length,r.VALIDITY.length)),r.TYPE_ID&&t.push(new YF(t.length,r.TYPE_ID.length)),r.OFFSET&&t.push(new YF(t.length,r.OFFSET.length)),r.DATA&&t.push(new YF(t.length,r.DATA.length)),t=RF(r.children,t)}return t}function zF(e){return(e||[]).reduce((e,t)=>e+ +(t===0),0)}function BF(e,t){let n,r,i,a,o,s;return!t||!(a=e.dictionary)?(o=UF(e,IF(e,t)),i=new CN(e.name,o,e.nullable,VF(e.metadata))):t.has(n=a.id)?(r=(r=a.indexType)?HF(r):new jk,s=new oA(t.get(n),r,n,a.isOrdered),i=new CN(e.name,s,e.nullable,VF(e.metadata))):(r=(r=a.indexType)?HF(r):new jk,t.set(n,o=UF(e,IF(e,t))),s=new oA(o,r,n,a.isOrdered),i=new CN(e.name,s,e.nullable,VF(e.metadata))),i||null}function VF(e=[]){return new Map(e.map(({key:e,value:t})=>[e,t]))}function HF(e){return new Ok(e.isSigned,e.bitWidth)}function UF(e,t){let n=e.type.name;switch(n){case`NONE`:return new Dk;case`null`:return new Dk;case`binary`:return new Vk;case`largebinary`:return new Hk;case`utf8`:return new Uk;case`largeutf8`:return new Wk;case`bool`:return new Gk;case`list`:return new $k((t||[])[0]);case`struct`:return new eA(t||[]);case`struct_`:return new eA(t||[])}switch(n){case`int`:{let t=e.type;return new Ok(t.isSigned,t.bitWidth)}case`floatingpoint`:{let t=e.type;return new Lk(XD[t.precision])}case`decimal`:{let t=e.type;return new Kk(t.scale,t.precision,t.bitWidth)}case`date`:{let t=e.type;return new qk(ZD[t.unit])}case`time`:{let t=e.type;return new Jk(QD[t.unit],t.bitWidth)}case`timestamp`:{let t=e.type;return new Yk(QD[t.unit],t.timezone)}case`interval`:{let t=e.type;return new Zk($D[t.unit])}case`duration`:{let t=e.type;return new Qk(QD[t.unit])}case`union`:{let n=e.type,[r,...i]=(n.mode+``).toLowerCase();return new tA(YD[r.toUpperCase()+i.join(``)],n.typeIds||[],t||[])}case`fixedsizebinary`:{let t=e.type;return new nA(t.byteWidth)}case`fixedsizelist`:{let n=e.type;return new rA(n.listSize,(t||[])[0])}case`map`:{let n=e.type;return new iA((t||[])[0],n.keysSorted)}}throw Error(`Unrecognized type: "${n}"`)}var WF=oO,GF=aO,KF=class e{static fromJSON(t,n){let r=new e(0,JD.V5,n);return r._createHeader=ZF(t,n),r}static decode(t){t=new GF(MD(t));let n=AF.getRootAsMessage(t),r=n.bodyLength(),i=n.version(),a=n.headerType(),o=new e(r,i,a);return o._createHeader=QF(n,a),o}static encode(e){let t=new WF,n=-1;return e.isSchema()?n=SN.encode(t,e.header()):e.isRecordBatch()?n=qF.encode(t,e.header()):e.isDictionaryBatch()&&(n=JF.encode(t,e.header())),AF.startMessage(t),AF.addVersion(t,JD.V5),AF.addHeader(t,n),AF.addHeaderType(t,e.headerType),AF.addBodyLength(t,BigInt(e.bodyLength)),AF.finishMessageBuffer(t,AF.endMessage(t)),t.asUint8Array()}static from(t,n=0){if(t instanceof SN)return new e(0,JD.V5,VO.Schema,t);if(t instanceof qF)return new e(n,JD.V5,VO.RecordBatch,t);if(t instanceof JF)return new e(n,JD.V5,VO.DictionaryBatch,t);throw Error(`Unrecognized Message header: ${t}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===VO.Schema}isRecordBatch(){return this.headerType===VO.RecordBatch}isDictionaryBatch(){return this.headerType===VO.DictionaryBatch}constructor(e,t,n,r){this._version=t,this._headerType=n,this.body=new Uint8Array,r&&(this._createHeader=()=>r),this._bodyLength=GO(e)}},qF=class{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(e,t,n){this._nodes=t,this._buffers=n,this._length=GO(e)}},JF=class{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(e,t,n=!1){this._data=e,this._isDelta=n,this._id=GO(t)}},YF=class{constructor(e,t){this.offset=GO(e),this.length=GO(t)}},XF=class{constructor(e,t){this.length=GO(e),this.nullCount=GO(t)}};function ZF(e,t){return(()=>{switch(t){case VO.Schema:return SN.fromJSON(e);case VO.RecordBatch:return qF.fromJSON(e);case VO.DictionaryBatch:return JF.fromJSON(e)}throw Error(`Unrecognized Message type: { name: ${VO[t]}, type: ${t} }`)})}function QF(e,t){return(()=>{switch(t){case VO.Schema:return SN.decode(e.header(new BO),new Map,e.version());case VO.RecordBatch:return qF.decode(e.header(new fO),e.version());case VO.DictionaryBatch:return JF.decode(e.header(new pO),e.version())}throw Error(`Unrecognized Message type: { name: ${VO[t]}, type: ${t} }`)})}CN.encode=pI,CN.decode=cI,CN.fromJSON=BF,SN.encode=fI,SN.decode=$F,SN.fromJSON=MF,qF.encode=mI,qF.decode=eI,qF.fromJSON=NF,JF.encode=hI,JF.decode=tI,JF.fromJSON=PF,XF.encode=gI,XF.decode=rI,YF.encode=_I,YF.decode=nI;function $F(e,t=new Map,n=JD.V5){return new SN(oI(e,t),lI(e),t,n)}function eI(e,t=JD.V5){if(e.compression()!==null)throw Error(`Record batch compression not implemented`);return new qF(e.length(),iI(e),aI(e,t))}function tI(e,t=JD.V5){return new JF(qF.decode(e.data(),t),e.id(),e.isDelta())}function nI(e){return new YF(e.offset(),e.length())}function rI(e){return new XF(e.length(),e.nullCount())}function iI(e){let t=[];for(let n,r=-1,i=-1,a=e.nodesLength();++r<a;)(n=e.nodes(r))&&(t[++i]=XF.decode(n));return t}function aI(e,t){let n=[];for(let r,i=-1,a=-1,o=e.buffersLength();++i<o;)(r=e.buffers(i))&&(t<JD.V4&&(r.bb_pos+=8*(i+1)),n[++a]=YF.decode(r));return n}function oI(e,t){let n=[];for(let r,i=-1,a=-1,o=e.fieldsLength();++i<o;)(r=e.fields(i))&&(n[++a]=CN.decode(r,t));return n}function sI(e,t){let n=[];for(let r,i=-1,a=-1,o=e.childrenLength();++i<o;)(r=e.children(i))&&(n[++a]=CN.decode(r,t));return n}function cI(e,t){let n,r,i,a,o,s;return!t||!(s=e.dictionary())?(i=dI(e,sI(e,t)),r=new CN(e.name(),i,e.nullable(),lI(e))):t.has(n=GO(s.id()))?(a=(a=s.indexType())?uI(a):new jk,o=new oA(t.get(n),a,n,s.isOrdered()),r=new CN(e.name(),o,e.nullable(),lI(e))):(a=(a=s.indexType())?uI(a):new jk,t.set(n,i=dI(e,sI(e,t))),o=new oA(i,a,n,s.isOrdered()),r=new CN(e.name(),o,e.nullable(),lI(e))),r||null}function lI(e){let t=new Map;if(e)for(let n,r,i=-1,a=Math.trunc(e.customMetadataLength());++i<a;)(n=e.customMetadata(i))&&(r=n.key())!=null&&t.set(r,n.value());return t}function uI(e){return new Ok(e.isSigned(),e.bitWidth())}function dI(e,t){let n=e.typeType();switch(n){case RO.NONE:return new Dk;case RO.Null:return new Dk;case RO.Binary:return new Vk;case RO.LargeBinary:return new Hk;case RO.Utf8:return new Uk;case RO.LargeUtf8:return new Wk;case RO.Bool:return new Gk;case RO.List:return new $k((t||[])[0]);case RO.Struct_:return new eA(t||[])}switch(n){case RO.Int:{let t=e.type(new gO);return new Ok(t.isSigned(),t.bitWidth())}case RO.FloatingPoint:return new Lk(e.type(new EO).precision());case RO.Decimal:{let t=e.type(new SO);return new Kk(t.scale(),t.precision(),t.bitWidth())}case RO.Date:return new qk(e.type(new xO).unit());case RO.Time:{let t=e.type(new PO);return new Jk(t.unit(),t.bitWidth())}case RO.Timestamp:{let t=e.type(new FO);return new Yk(t.unit(),t.timezone())}case RO.Interval:return new Zk(e.type(new DO).unit());case RO.Duration:return new Qk(e.type(new CO).unit());case RO.Union:{let n=e.type(new IO);return new tA(n.mode(),n.typeIdsArray()||[],t||[])}case RO.FixedSizeBinary:return new nA(e.type(new wO).byteWidth());case RO.FixedSizeList:return new rA(e.type(new TO).listSize(),(t||[])[0]);case RO.Map:{let n=e.type(new jO);return new iA((t||[])[0],n.keysSorted())}}throw Error(`Unrecognized type: "${RO[n]}" (${n})`)}function fI(e,t){let n=t.fields.map(t=>CN.encode(e,t));BO.startFieldsVector(e,n.length);let r=BO.createFieldsVector(e,n),i=t.metadata&&t.metadata.size>0?BO.createCustomMetadataVector(e,[...t.metadata].map(([t,n])=>{let r=e.createString(`${t}`),i=e.createString(`${n}`);return vO.startKeyValue(e),vO.addKey(e,r),vO.addValue(e,i),vO.endKeyValue(e)})):-1;return BO.startSchema(e),BO.addFields(e,r),BO.addEndianness(e,vI?mO.Little:mO.Big),i!==-1&&BO.addCustomMetadata(e,i),BO.endSchema(e)}function pI(e,t){let n=-1,r=-1,i=-1,a=t.type,o=t.typeId;Ek.isDictionary(a)?(o=a.dictionary.typeId,i=jF.visit(a,e),r=jF.visit(a.dictionary,e)):r=jF.visit(a,e);let s=(a.children||[]).map(t=>CN.encode(e,t)),c=zO.createChildrenVector(e,s),l=t.metadata&&t.metadata.size>0?zO.createCustomMetadataVector(e,[...t.metadata].map(([t,n])=>{let r=e.createString(`${t}`),i=e.createString(`${n}`);return vO.startKeyValue(e),vO.addKey(e,r),vO.addValue(e,i),vO.endKeyValue(e)})):-1;return t.name&&(n=e.createString(t.name)),zO.startField(e),zO.addType(e,r),zO.addTypeType(e,o),zO.addChildren(e,c),zO.addNullable(e,!!t.nullable),n!==-1&&zO.addName(e,n),i!==-1&&zO.addDictionary(e,i),l!==-1&&zO.addCustomMetadata(e,l),zO.endField(e)}function mI(e,t){let n=t.nodes||[],r=t.buffers||[];fO.startNodesVector(e,n.length);for(let t of n.slice().reverse())XF.encode(e,t);let i=e.endVector();fO.startBuffersVector(e,r.length);for(let t of r.slice().reverse())YF.encode(e,t);let a=e.endVector();return fO.startRecordBatch(e),fO.addLength(e,BigInt(t.length)),fO.addNodes(e,i),fO.addBuffers(e,a),fO.endRecordBatch(e)}function hI(e,t){let n=qF.encode(e,t.data);return pO.startDictionaryBatch(e),pO.addId(e,BigInt(t.id)),pO.addIsDelta(e,t.isDelta),pO.addData(e,n),pO.endDictionaryBatch(e)}function gI(e,t){return dO.createFieldNode(e,BigInt(t.length),BigInt(t.nullCount))}function _I(e,t){return uO.createBuffer(e,BigInt(t.offset),BigInt(t.length))}var vI=(()=>{let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]===256})(),yI=e=>`Expected ${VO[e]} Message in stream, but was null or length 0.`,bI=e=>`Header pointer of flatbuffer-encoded ${VO[e]} Message is null or length 0.`,xI=(e,t)=>`Expected to read ${e} metadata bytes, but only read ${t}.`,SI=(e,t)=>`Expected to read ${e} bytes for message body, but only read ${t}.`,CI=class{constructor(e){this.source=e instanceof IN?e:new IN(e)}[Symbol.iterator](){return this}next(){let e;return(e=this.readMetadataLength()).done||e.value===-1&&(e=this.readMetadataLength()).done||(e=this.readMetadata(e.value)).done?jN:e}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw Error(yI(e));return t.value}readMessageBody(e){if(e<=0)return new Uint8Array;let t=MD(this.source.read(e));if(t.byteLength<e)throw Error(SI(e,t.byteLength));return t.byteOffset%8==0&&t.byteOffset+t.byteLength<=t.buffer.byteLength?t:t.slice()}readSchema(e=!1){let t=VO.Schema,n=this.readMessage(t)?.header();if(e&&!n)throw Error(bI(t));return n}readMetadataLength(){let e=this.source.read(4),t=(e&&new aO(e))?.readInt32(0)||0;return{done:t===0,value:t}}readMetadata(e){let t=this.source.read(e);if(!t)return jN;if(t.byteLength<e)throw Error(xI(e,t.byteLength));return{done:!1,value:KF.decode(t)}}},wI=class{constructor(e,t){this.source=e instanceof LN?e:_D(e)?new VN(e,t):new LN(e)}[Symbol.asyncIterator](){return this}next(){return QE(this,void 0,void 0,function*(){let e;return(e=yield this.readMetadataLength()).done||e.value===-1&&(e=yield this.readMetadataLength()).done||(e=yield this.readMetadata(e.value)).done?jN:e})}throw(e){return QE(this,void 0,void 0,function*(){return yield this.source.throw(e)})}return(e){return QE(this,void 0,void 0,function*(){return yield this.source.return(e)})}readMessage(e){return QE(this,void 0,void 0,function*(){let t;if((t=yield this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw Error(yI(e));return t.value})}readMessageBody(e){return QE(this,void 0,void 0,function*(){if(e<=0)return new Uint8Array;let t=MD(yield this.source.read(e));if(t.byteLength<e)throw Error(SI(e,t.byteLength));return t.byteOffset%8==0&&t.byteOffset+t.byteLength<=t.buffer.byteLength?t:t.slice()})}readSchema(){return QE(this,arguments,void 0,function*(e=!1){let t=VO.Schema,n=(yield this.readMessage(t))?.header();if(e&&!n)throw Error(bI(t));return n})}readMetadataLength(){return QE(this,void 0,void 0,function*(){let e=yield this.source.read(4),t=(e&&new aO(e))?.readInt32(0)||0;return{done:t===0,value:t}})}readMetadata(e){return QE(this,void 0,void 0,function*(){let t=yield this.source.read(e);if(!t)return jN;if(t.byteLength<e)throw Error(xI(e,t.byteLength));return{done:!1,value:KF.decode(t)}})}},TI=class extends CI{constructor(e){super(new Uint8Array),this._schema=!1,this._body=[],this._batchIndex=0,this._dictionaryIndex=0,this._json=e instanceof MN?e:new MN(e)}next(){let{_json:e}=this;if(!this._schema)return this._schema=!0,{done:!1,value:KF.fromJSON(e.schema,VO.Schema)};if(this._dictionaryIndex<e.dictionaries.length){let t=e.dictionaries[this._dictionaryIndex++];return this._body=t.data.columns,{done:!1,value:KF.fromJSON(t,VO.DictionaryBatch)}}if(this._batchIndex<e.batches.length){let t=e.batches[this._batchIndex++];return this._body=t.columns,{done:!1,value:KF.fromJSON(t,VO.RecordBatch)}}return this._body=[],jN}readMessageBody(e){return t(this._body);function t(e){return(e||[]).reduce((e,n)=>[...e,...n.VALIDITY&&[n.VALIDITY]||[],...n.TYPE_ID&&[n.TYPE_ID]||[],...n.OFFSET&&[n.OFFSET]||[],...n.DATA&&[n.DATA]||[],...t(n.children)],[])}}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw Error(yI(e));return t.value}readSchema(){let e=VO.Schema,t=this.readMessage(e),n=t?.header();if(!t||!n)throw Error(bI(e));return n}},EI=`ARROW1`,DI=new Uint8Array(6);for(let e=0;e<6;e+=1)DI[e]=EI.codePointAt(e);function OI(e,t=0){for(let n=-1,r=DI.length;++n<r;)if(DI[n]!==e[t+n])return!1;return!0}var kI=DI.length,AI=kI+4,jI=kI*2+4,MI=class e extends NN{constructor(e){super(),this._impl=e}get closed(){return this._impl.closed}get schema(){return this._impl.schema}get autoDestroy(){return this._impl.autoDestroy}get dictionaries(){return this._impl.dictionaries}get numDictionaries(){return this._impl.numDictionaries}get numRecordBatches(){return this._impl.numRecordBatches}get footer(){return this._impl.isFile()?this._impl.footer:null}isSync(){return this._impl.isSync()}isAsync(){return this._impl.isAsync()}isFile(){return this._impl.isFile()}isStream(){return this._impl.isStream()}next(){return this._impl.next()}throw(e){return this._impl.throw(e)}return(e){return this._impl.return(e)}cancel(){return this._impl.cancel()}reset(e){return this._impl.reset(e),this._DOMStream=void 0,this._nodeStream=void 0,this}open(e){let t=this._impl.open(e);return fD(t)?t.then(()=>this):this}readRecordBatch(e){return this._impl.isFile()?this._impl.readRecordBatch(e):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return BD.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return BD.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(e){throw Error(`"throughNode" not available in this environment`)}static throughDOM(e,t){throw Error(`"throughDOM" not available in this environment`)}static from(t){return t instanceof e?t:hD(t)?KI(t):_D(t)?YI(t):fD(t)?QE(this,void 0,void 0,function*(){return yield e.from(yield t)}):vD(t)||xD(t)||CD(t)||mD(t)?JI(new LN(t)):qI(new IN(t))}static readAll(t){return t instanceof e?t.isSync()?WI(t):GI(t):hD(t)||ArrayBuffer.isView(t)||pD(t)||gD(t)?WI(t):GI(t)}},NI=class extends MI{constructor(e){super(e),this._impl=e}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return tD(this,arguments,function*(){yield eD(yield*nD(rD(this[Symbol.iterator]())))})}},PI=class extends MI{constructor(e){super(e),this._impl=e}readAll(){return QE(this,void 0,void 0,function*(){var e,t,n,r;let i=[];try{for(var a=!0,o=rD(this),s;s=yield o.next(),e=s.done,!e;a=!0){r=s.value,a=!1;let e=r;i.push(e)}}catch(e){t={error:e}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return i})}[Symbol.iterator](){throw Error(`AsyncRecordBatchStreamReader is not Iterable`)}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}},FI=class extends NI{constructor(e){super(e),this._impl=e}},II=class extends PI{constructor(e){super(e),this._impl=e}},LI=class{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(e=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=e}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(e){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=e,this.dictionaries=new Map,this}_loadRecordBatch(e,t){let n=this._loadVectors(e,t,this.schema.fields),r=FM({type:new eA(this.schema.fields),length:e.length,children:n});return new EF(this.schema,r)}_loadDictionaryBatch(e,t){let{id:n,isDelta:r}=e,{dictionaries:i,schema:a}=this,o=i.get(n),s=a.dictionaries.get(n),c=this._loadVectors(e.data,t,[s]);return(o&&r?o.concat(new aN(c)):new aN(c)).memoize()}_loadVectors(e,t,n){return new XN(t,e.nodes,e.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(n)}},RI=class extends LI{constructor(e,t){super(t),this._reader=hD(e)?new TI(this._handle=e):new CI(this._handle=e)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(e){return this.closed||(this.autoDestroy=UI(this,e),(this.schema||=this._reader.readSchema())||this.cancel()),this}throw(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(e):jN}return(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(e):jN}next(){if(this.closed)return jN;let e,{_reader:t}=this;for(;e=this._readNextMessageAndValidate();)if(e.isSchema())this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;let n=e.header(),r=t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(n,r)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;let n=e.header(),r=t.readMessageBody(e.bodyLength),i=this._loadDictionaryBatch(n,r);this.dictionaries.set(n.id,i)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new kF(this.schema)}):this.return()}_readNextMessageAndValidate(e){return this._reader.readMessage(e)}},zI=class extends LI{constructor(e,t){super(t),this._reader=new wI(this._handle=e)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return QE(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(e){return QE(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=UI(this,e),(this.schema||=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(e){return QE(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(e):jN})}return(e){return QE(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(e):jN})}next(){return QE(this,void 0,void 0,function*(){if(this.closed)return jN;let e,{_reader:t}=this;for(;e=yield this._readNextMessageAndValidate();)if(e.isSchema())yield this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;let n=e.header(),r=yield t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(n,r)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;let n=e.header(),r=yield t.readMessageBody(e.bodyLength),i=this._loadDictionaryBatch(n,r);this.dictionaries.set(n.id,i)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new kF(this.schema)}):yield this.return()})}_readNextMessageAndValidate(e){return QE(this,void 0,void 0,function*(){return yield this._reader.readMessage(e)})}},BI=class extends RI{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(e,t){super(e instanceof BN?e:new BN(e),t)}isSync(){return!0}isFile(){return!0}open(e){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(let e of this._footer.dictionaryBatches())e&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(e)}readRecordBatch(e){if(this.closed)return null;this._footer||this.open();let t=this._footer?.getRecordBatch(e);if(t&&this._handle.seek(t.offset)){let e=this._reader.readMessage(VO.RecordBatch);if(e?.isRecordBatch()){let t=e.header(),n=this._reader.readMessageBody(e.bodyLength);return this._loadRecordBatch(t,n)}}return null}_readDictionaryBatch(e){let t=this._footer?.getDictionaryBatch(e);if(t&&this._handle.seek(t.offset)){let e=this._reader.readMessage(VO.DictionaryBatch);if(e?.isDictionaryBatch()){let t=e.header(),n=this._reader.readMessageBody(e.bodyLength),r=this._loadDictionaryBatch(t,n);this.dictionaries.set(t.id,r)}}}_readFooter(){let{_handle:e}=this,t=e.size-AI,n=e.readInt32(t),r=e.readAt(t-n,n);return ON.decode(r)}_readNextMessageAndValidate(e){if(this._footer||this.open(),this._footer&&this._recordBatchIndex<this.numRecordBatches){let t=this._footer?.getRecordBatch(this._recordBatchIndex);if(t&&this._handle.seek(t.offset))return this._reader.readMessage(e)}return null}},VI=class extends zI{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(e,...t){let n=typeof t[0]==`number`?void 0:t.shift(),r=t[0]instanceof Map?t.shift():void 0;super(e instanceof VN?e:new VN(e,n),r)}isFile(){return!0}isAsync(){return!0}open(e){let t=Object.create(null,{open:{get:()=>super.open}});return QE(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(let e of this._footer.dictionaryBatches())e&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield t.open.call(this,e)})}readRecordBatch(e){return QE(this,void 0,void 0,function*(){if(this.closed)return null;this._footer||(yield this.open());let t=this._footer?.getRecordBatch(e);if(t&&(yield this._handle.seek(t.offset))){let e=yield this._reader.readMessage(VO.RecordBatch);if(e?.isRecordBatch()){let t=e.header(),n=yield this._reader.readMessageBody(e.bodyLength);return this._loadRecordBatch(t,n)}}return null})}_readDictionaryBatch(e){return QE(this,void 0,void 0,function*(){let t=this._footer?.getDictionaryBatch(e);if(t&&(yield this._handle.seek(t.offset))){let e=yield this._reader.readMessage(VO.DictionaryBatch);if(e?.isDictionaryBatch()){let t=e.header(),n=yield this._reader.readMessageBody(e.bodyLength),r=this._loadDictionaryBatch(t,n);this.dictionaries.set(t.id,r)}}})}_readFooter(){return QE(this,void 0,void 0,function*(){let{_handle:e}=this;e._pending&&(yield e._pending);let t=e.size-AI,n=yield e.readInt32(t),r=yield e.readAt(t-n,n);return ON.decode(r)})}_readNextMessageAndValidate(e){return QE(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex<this.numRecordBatches){let t=this._footer.getRecordBatch(this._recordBatchIndex);if(t&&(yield this._handle.seek(t.offset)))return yield this._reader.readMessage(e)}return null})}},HI=class extends RI{constructor(e,t){super(e,t)}_loadVectors(e,t,n){return new ZN(t,e.nodes,e.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(n)}};function UI(e,t){return t&&typeof t.autoDestroy==`boolean`?t.autoDestroy:e.autoDestroy}function*WI(e){let t=MI.from(e);try{if(!t.open({autoDestroy:!1}).closed)do yield t;while(!t.reset().open().closed)}finally{t.cancel()}}function GI(e){return tD(this,arguments,function*(){let t=yield eD(MI.from(e));try{if(!(yield eD(t.open({autoDestroy:!1}))).closed)do yield yield eD(t);while(!(yield eD(t.reset().open())).closed)}finally{yield eD(t.cancel())}})}function KI(e){return new NI(new HI(e))}function qI(e){let t=e.peek(kI+7&-8);return t&&t.byteLength>=4?OI(t)?new FI(new BI(e.read())):new NI(new RI(e)):new NI(new RI(function*(){}()))}function JI(e){return QE(this,void 0,void 0,function*(){let t=yield e.peek(kI+7&-8);return t&&t.byteLength>=4?OI(t)?new FI(new BI(yield e.read())):new PI(new zI(e)):new PI(new zI(function(){return tD(this,arguments,function*(){})}()))})}function YI(e){return QE(this,void 0,void 0,function*(){let{size:t}=yield e.stat(),n=new VN(e,t);return t>=jI&&OI(yield n.readAt(0,kI+7&-8))?new II(new VI(n)):new PI(new zI(n))})}var XI=class e extends cA{static assemble(...t){let n=e=>e.flatMap(e=>Array.isArray(e)?n(e):e instanceof EF?e.data.children:e.data),r=new e;return r.visitMany(n(t)),r}constructor(){super(),this._byteLength=0,this._nodes=[],this._buffers=[],this._bufferRegions=[]}visit(e){if(e instanceof aN)return this.visitMany(e.data),this;let{type:t}=e;if(!Ek.isDictionary(t)){let{length:n}=e;if(n>2147483647)throw RangeError(`Cannot write arrays larger than 2^31 - 1 in length`);if(Ek.isUnion(t))this.nodes.push(new XF(n,0));else{let{nullCount:r}=e;Ek.isNull(t)||ZI.call(this,r<=0?new Uint8Array:DM(e.offset,n,e.nullBitmap)),this.nodes.push(new XF(n,r))}}return super.visit(e)}visitNull(e){return this}visitDictionary(e){return this.visit(e.clone(e.type.indices))}get nodes(){return this._nodes}get buffers(){return this._buffers}get byteLength(){return this._byteLength}get bufferRegions(){return this._bufferRegions}};function ZI(e){let t=e.byteLength+7&-8;return this.buffers.push(e),this.bufferRegions.push(new YF(this._byteLength,t)),this._byteLength+=t,this}function QI(e){let{type:t,length:n,typeIds:r,valueOffsets:i}=e;if(ZI.call(this,r),t.mode===YD.Sparse)return rL.call(this,e);if(t.mode===YD.Dense){if(e.offset<=0)return ZI.call(this,i),rL.call(this,e);{let a=new Int32Array(n),o=Object.create(null),s=Object.create(null);for(let e,t,c=-1;++c<n;)(e=r[c])!==void 0&&((t=o[e])===void 0&&(t=o[e]=i[c]),a[c]=i[c]-t,s[e]=(s[e]??0)+1);ZI.call(this,a),this.visitMany(e.children.map((e,r)=>{let i=t.typeIds[r],a=o[i],c=s[i];return e.slice(a,Math.min(n,c))}))}}return this}function $I(e){let t;return e.nullCount>=e.length?ZI.call(this,new Uint8Array):(t=e.values)instanceof Uint8Array?ZI.call(this,DM(e.offset,e.length,t)):ZI.call(this,OM(e.values))}function eL(e){return ZI.call(this,e.values.subarray(0,e.length*e.stride))}function tL(e){let{length:t,values:n,valueOffsets:r}=e,i=GO(r[0]),a=GO(r[t]),o=Math.min(a-i,n.byteLength-i);return ZI.call(this,RD(-i,t+1,r)),ZI.call(this,n.subarray(i,i+o)),this}function nL(e){let{length:t,valueOffsets:n}=e;if(n){let{0:r,[t]:i}=n;return ZI.call(this,RD(-r,t+1,n)),this.visit(e.children[0].slice(r,i-r))}return this.visit(e.children[0])}function rL(e){return this.visitMany(e.type.children.map((t,n)=>e.children[n]).filter(Boolean))[0]}XI.prototype.visitBool=$I,XI.prototype.visitInt=eL,XI.prototype.visitFloat=eL,XI.prototype.visitUtf8=tL,XI.prototype.visitLargeUtf8=tL,XI.prototype.visitBinary=tL,XI.prototype.visitLargeBinary=tL,XI.prototype.visitFixedSizeBinary=eL,XI.prototype.visitDate=eL,XI.prototype.visitTimestamp=eL,XI.prototype.visitTime=eL,XI.prototype.visitDecimal=eL,XI.prototype.visitList=nL,XI.prototype.visitStruct=rL,XI.prototype.visitUnion=QI,XI.prototype.visitInterval=eL,XI.prototype.visitDuration=eL,XI.prototype.visitFixedSizeList=nL,XI.prototype.visitMap=nL;var iL=class extends NN{static throughNode(e){throw Error(`"throughNode" not available in this environment`)}static throughDOM(e,t){throw Error(`"throughDOM" not available in this environment`)}constructor(e){super(),this._position=0,this._started=!1,this._sink=new FN,this._schema=null,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,dD(e)||(e={autoDestroy:!0,writeLegacyIpcFormat:!1}),this._autoDestroy=typeof e.autoDestroy==`boolean`?e.autoDestroy:!0,this._writeLegacyIpcFormat=typeof e.writeLegacyIpcFormat==`boolean`?e.writeLegacyIpcFormat:!1}toString(e=!1){return this._sink.toString(e)}toUint8Array(e=!1){return this._sink.toUint8Array(e)}writeAll(e){return fD(e)?e.then(e=>this.writeAll(e)):mD(e)?cL(this,e):sL(this,e)}get closed(){return this._sink.closed}[Symbol.asyncIterator](){return this._sink[Symbol.asyncIterator]()}toDOMStream(e){return this._sink.toDOMStream(e)}toNodeStream(e){return this._sink.toNodeStream(e)}close(){return this.reset()._sink.close()}abort(e){return this.reset()._sink.abort(e)}finish(){return this._autoDestroy?this.close():this.reset(this._sink,this._schema),this}reset(e=this._sink,t=null){return e===this._sink||e instanceof FN?this._sink=e:(this._sink=new FN,e&&bD(e)?this.toDOMStream({type:`bytes`}).pipeTo(e):e&&SD(e)&&this.toNodeStream({objectMode:!1}).pipe(e)),this._started&&this._schema&&this._writeFooter(this._schema),this._started=!1,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,(!t||!mF(t,this._schema))&&(t==null?(this._position=0,this._schema=null):(this._started=!0,this._schema=t,this._writeSchema(t))),this}write(e){let t=null;if(!this._sink)throw Error(`RecordBatchWriter is closed`);if(e==null||e instanceof wF&&!(t=e.schema)||e instanceof EF&&!(t=e.schema))return this.finish()&&void 0;if(t&&!mF(t,this._schema)){if(this._started&&this._autoDestroy)return this.close();this.reset(this._sink,t)}e instanceof EF?e instanceof kF||this._writeRecordBatch(e):e instanceof wF?this.writeAll(e.batches):pD(e)&&this.writeAll(e)}_writeMessage(e,t=8){let n=t-1,r=KF.encode(e),i=r.byteLength,a=this._writeLegacyIpcFormat?4:8,o=i+a+n&~n,s=o-i-a;return e.headerType===VO.RecordBatch?this._recordBatchBlocks.push(new AN(o,e.bodyLength,this._position)):e.headerType===VO.DictionaryBatch&&this._dictionaryBlocks.push(new AN(o,e.bodyLength,this._position)),this._writeLegacyIpcFormat||this._write(Int32Array.of(-1)),this._write(Int32Array.of(o-a)),i>0&&this._write(r),this._writePadding(s)}_write(e){if(this._started){let t=MD(e);t&&t.byteLength>0&&(this._sink.write(t),this._position+=t.byteLength)}return this}_writeSchema(e){return this._writeMessage(KF.from(e))}_writeFooter(e){return this._writeLegacyIpcFormat?this._write(Int32Array.of(0)):this._write(Int32Array.of(-1,0))}_writeMagic(){return this._write(DI)}_writePadding(e){return e>0?this._write(new Uint8Array(e)):this}_writeRecordBatch(e){let{byteLength:t,nodes:n,bufferRegions:r,buffers:i}=XI.assemble(e),a=new qF(e.numRows,n,r),o=KF.from(a,t);return this._writeDictionaries(e)._writeMessage(o)._writeBodyBuffers(i)}_writeDictionaryBatch(e,t,n=!1){let{byteLength:r,nodes:i,bufferRegions:a,buffers:o}=XI.assemble(new aN([e])),s=new JF(new qF(e.length,i,a),t,n),c=KF.from(s,r);return this._writeMessage(c)._writeBodyBuffers(o)}_writeBodyBuffers(e){let t,n,r;for(let i=-1,a=e.length;++i<a;)(t=e[i])&&(n=t.byteLength)>0&&(this._write(t),(r=(n+7&-8)-n)>0&&this._writePadding(r));return this}_writeDictionaries(e){for(let[t,n]of e.dictionaries){let e=n?.data??[],r=this._seenDictionaries.get(t),i=this._dictionaryDeltaOffsets.get(t)??0;if(!r||r.data[0]!==e[0])for(let[n,r]of e.entries())this._writeDictionaryBatch(r,t,n>0);else if(i<e.length)for(let n of e.slice(i))this._writeDictionaryBatch(n,t,!0);this._seenDictionaries.set(t,n),this._dictionaryDeltaOffsets.set(t,e.length)}return this}},aL=class e extends iL{static writeAll(t,n){let r=new e(n);return fD(t)?t.then(e=>r.writeAll(e)):mD(t)?cL(r,t):sL(r,t)}},oL=class e extends iL{static writeAll(t){let n=new e;return fD(t)?t.then(e=>n.writeAll(e)):mD(t)?cL(n,t):sL(n,t)}constructor(){super(),this._autoDestroy=!0}_writeSchema(e){return this._writeMagic()._writePadding(2)}_writeDictionaryBatch(e,t,n=!1){if(!n&&this._seenDictionaries.has(t))throw Error(`The Arrow File format does not support replacement dictionaries. `);return super._writeDictionaryBatch(e,t,n)}_writeFooter(e){let t=ON.encode(new ON(e,JD.V5,this._recordBatchBlocks,this._dictionaryBlocks));return super._writeFooter(e)._write(t)._write(Int32Array.of(t.byteLength))._writeMagic()}};function sL(e,t){let n=t;t instanceof wF&&(n=t.batches,e.reset(void 0,t.schema));for(let t of n)e.write(t);return e.finish()}function cL(e,t){return QE(this,void 0,void 0,function*(){var n,r,i,a,o,s,c;try{for(n=!0,r=rD(t);i=yield r.next(),a=i.done,!a;n=!0){c=i.value,n=!1;let t=c;e.write(t)}}catch(e){o={error:e}}finally{try{!n&&!a&&(s=r.return)&&(yield s.call(r))}finally{if(o)throw o.error}}return e.finish()})}function lL(e,t=`stream`){return(t===`stream`?aL:oL).writeAll(e).toUint8Array(!0)}var uL=Object.create,dL=Object.defineProperty,fL=Object.getOwnPropertyDescriptor,pL=Object.getOwnPropertyNames,mL=Object.getPrototypeOf,hL=Object.prototype.hasOwnProperty,gL=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_L=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of pL(t))!hL.call(e,i)&&i!==n&&dL(e,i,{get:()=>t[i],enumerable:!(r=fL(t,i))||r.enumerable});return e},vL=(e,t,n)=>(n=e==null?{}:uL(mL(e)),_L(t||!e||!e.__esModule?dL(n,`default`,{value:e,enumerable:!0}):n,e)),yL=gL((e,t)=>{t.exports=Worker}),bL=(e=>(e[e.UNDEFINED=0]=`UNDEFINED`,e[e.AUTOMATIC=1]=`AUTOMATIC`,e[e.READ_ONLY=2]=`READ_ONLY`,e[e.READ_WRITE=3]=`READ_WRITE`,e))(bL||{}),xL=(e=>(e[e.IDENTIFIER=0]=`IDENTIFIER`,e[e.NUMERIC_CONSTANT=1]=`NUMERIC_CONSTANT`,e[e.STRING_CONSTANT=2]=`STRING_CONSTANT`,e[e.OPERATOR=3]=`OPERATOR`,e[e.KEYWORD=4]=`KEYWORD`,e[e.COMMENT=5]=`COMMENT`,e))(xL||{}),SL=(e=>(e[e.NONE=0]=`NONE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARNING=3]=`WARNING`,e[e.ERROR=4]=`ERROR`,e))(SL||{}),CL=(e=>(e[e.NONE=0]=`NONE`,e[e.CONNECT=1]=`CONNECT`,e[e.DISCONNECT=2]=`DISCONNECT`,e[e.OPEN=3]=`OPEN`,e[e.QUERY=4]=`QUERY`,e[e.INSTANTIATE=5]=`INSTANTIATE`,e))(CL||{}),wL=(e=>(e[e.NONE=0]=`NONE`,e[e.OK=1]=`OK`,e[e.ERROR=2]=`ERROR`,e[e.START=3]=`START`,e[e.RUN=4]=`RUN`,e[e.CAPTURE=5]=`CAPTURE`,e))(wL||{}),TL=(e=>(e[e.NONE=0]=`NONE`,e[e.WEB_WORKER=1]=`WEB_WORKER`,e[e.NODE_WORKER=2]=`NODE_WORKER`,e[e.BINDINGS=3]=`BINDINGS`,e[e.ASYNC_DUCKDB=4]=`ASYNC_DUCKDB`,e))(TL||{}),EL=class{constructor(e=2){this.level=e}log(e){e.level>=this.level&&console.log(e)}},DL=(e=>(e[e.SUCCESS=0]=`SUCCESS`,e[e.MAX_ARROW_ERROR=255]=`MAX_ARROW_ERROR`,e[e.DUCKDB_WASM_RETRY=256]=`DUCKDB_WASM_RETRY`,e))(DL||{}),OL=class{constructor(e,t){this._bindings=e,this._conn=t}get bindings(){return this._bindings}async close(){return this._bindings.disconnect(this._conn)}useUnsafe(e){return e(this._bindings,this._conn)}async query(e){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:e});let t=await this._bindings.runQuery(this._conn,e),n=MI.from(t);return console.assert(n.isSync(),`Reader is not sync`),console.assert(n.isFile(),`Reader is not file`),new wF(n)}async send(e,t=!1){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:e});let n=await this._bindings.startPendingQuery(this._conn,e,t);for(;n==null;){if(this._bindings.isDetached()){console.error(`cannot send a message since the worker is not set!`);return}n=await this._bindings.pollPendingQuery(this._conn)}let r=new kL(this._bindings,this._conn,n),i=await MI.from(r);return console.assert(i.isAsync()),console.assert(i.isStream()),i}async cancelSent(){return await this._bindings.cancelPendingQuery(this._conn)}async getTableNames(e){return await this._bindings.getTableNames(this._conn,e)}async prepare(e){let t=await this._bindings.createPrepared(this._conn,e);return new AL(this._bindings,this._conn,t)}async insertArrowTable(e,t){let n=lL(e,`stream`);await this.insertArrowFromIPCStream(n,t)}async insertArrowFromIPCStream(e,t){await this._bindings.insertArrowFromIPCStream(this._conn,e,t)}async insertCSVFromPath(e,t){await this._bindings.insertCSVFromPath(this._conn,e,t)}async insertJSONFromPath(e,t){await this._bindings.insertJSONFromPath(this._conn,e,t)}},kL=class{constructor(e,t,n){this.db=e,this.conn=t,this.header=n,this._first=!0,this._depleted=!1,this._inFlight=null}async next(){if(this._first)return this._first=!1,{done:!1,value:this.header};if(this._depleted)return{done:!0,value:null};let e=null;for(this._inFlight!=null&&(e=await this._inFlight,this._inFlight=null);e==null;)e=await this.db.fetchQueryResults(this.conn);return this._depleted=e.length==0,this._depleted||(this._inFlight=this.db.fetchQueryResults(this.conn)),{done:this._depleted,value:e}}[Symbol.asyncIterator](){return this}},AL=class{constructor(e,t,n){this.bindings=e,this.connectionId=t,this.statementId=n}async close(){await this.bindings.closePrepared(this.connectionId,this.statementId)}async query(...e){let t=await this.bindings.runPrepared(this.connectionId,this.statementId,e),n=MI.from(t);return console.assert(n.isSync()),console.assert(n.isFile()),new wF(n)}async send(...e){let t=await this.bindings.sendPrepared(this.connectionId,this.statementId,e),n=new kL(this.bindings,this.connectionId,t),r=await MI.from(n);return console.assert(r.isAsync()),console.assert(r.isStream()),r}},jL=(e=>(e.CANCEL_PENDING_QUERY=`CANCEL_PENDING_QUERY`,e.CLOSE_PREPARED=`CLOSE_PREPARED`,e.COLLECT_FILE_STATISTICS=`COLLECT_FILE_STATISTICS`,e.REGISTER_OPFS_FILE_NAME=`REGISTER_OPFS_FILE_NAME`,e.CONNECT=`CONNECT`,e.COPY_FILE_TO_BUFFER=`COPY_FILE_TO_BUFFER`,e.COPY_FILE_TO_PATH=`COPY_FILE_TO_PATH`,e.CREATE_PREPARED=`CREATE_PREPARED`,e.DISCONNECT=`DISCONNECT`,e.DROP_FILE=`DROP_FILE`,e.DROP_FILES=`DROP_FILES`,e.EXPORT_FILE_STATISTICS=`EXPORT_FILE_STATISTICS`,e.FETCH_QUERY_RESULTS=`FETCH_QUERY_RESULTS`,e.FLUSH_FILES=`FLUSH_FILES`,e.GET_FEATURE_FLAGS=`GET_FEATURE_FLAGS`,e.GET_TABLE_NAMES=`GET_TABLE_NAMES`,e.GET_VERSION=`GET_VERSION`,e.GLOB_FILE_INFOS=`GLOB_FILE_INFOS`,e.INSERT_ARROW_FROM_IPC_STREAM=`INSERT_ARROW_FROM_IPC_STREAM`,e.INSERT_CSV_FROM_PATH=`IMPORT_CSV_FROM_PATH`,e.INSERT_JSON_FROM_PATH=`IMPORT_JSON_FROM_PATH`,e.INSTANTIATE=`INSTANTIATE`,e.OPEN=`OPEN`,e.PING=`PING`,e.POLL_PENDING_QUERY=`POLL_PENDING_QUERY`,e.REGISTER_FILE_BUFFER=`REGISTER_FILE_BUFFER`,e.REGISTER_FILE_HANDLE=`REGISTER_FILE_HANDLE`,e.REGISTER_FILE_URL=`REGISTER_FILE_URL`,e.RESET=`RESET`,e.RUN_PREPARED=`RUN_PREPARED`,e.RUN_QUERY=`RUN_QUERY`,e.SEND_PREPARED=`SEND_PREPARED`,e.START_PENDING_QUERY=`START_PENDING_QUERY`,e.TOKENIZE=`TOKENIZE`,e))(jL||{}),ML=(e=>(e.CONNECTION_INFO=`CONNECTION_INFO`,e.ERROR=`ERROR`,e.FEATURE_FLAGS=`FEATURE_FLAGS`,e.FILE_BUFFER=`FILE_BUFFER`,e.FILE_INFOS=`FILE_INFOS`,e.FILE_SIZE=`FILE_SIZE`,e.FILE_STATISTICS=`FILE_STATISTICS`,e.INSTANTIATE_PROGRESS=`INSTANTIATE_PROGRESS`,e.LOG=`LOG`,e.PROGRESS_UPDATE=`PROGRESS_UPDATE`,e.OK=`OK`,e.PREPARED_STATEMENT_ID=`PREPARED_STATEMENT_ID`,e.QUERY_PLAN=`QUERY_PLAN`,e.QUERY_RESULT=`QUERY_RESULT`,e.QUERY_RESULT_CHUNK=`QUERY_RESULT_CHUNK`,e.QUERY_RESULT_HEADER=`QUERY_RESULT_HEADER`,e.QUERY_RESULT_HEADER_OR_NULL=`QUERY_RESULT_HEADER_OR_NULL`,e.REGISTERED_FILE=`REGISTERED_FILE`,e.SCRIPT_TOKENS=`SCRIPT_TOKENS`,e.SUCCESS=`SUCCESS`,e.TABLE_NAMES=`TABLE_NAMES`,e.VERSION_STRING=`VERSION_STRING`,e))(ML||{}),NL=class{constructor(e,t){this.promiseResolver=()=>{},this.promiseRejecter=()=>{},this.type=e,this.data=t,this.promise=new Promise((e,t)=>{this.promiseResolver=e,this.promiseRejecter=t})}};function PL(e){switch(e.typeId){case Z.Binary:return{sqlType:`binary`};case Z.Bool:return{sqlType:`bool`};case Z.Date:return{sqlType:`date`};case Z.DateDay:return{sqlType:`date32[d]`};case Z.DateMillisecond:return{sqlType:`date64[ms]`};case Z.Decimal:{let t=e;return{sqlType:`decimal`,precision:t.precision,scale:t.scale}}case Z.Float:return{sqlType:`float`};case Z.Float16:return{sqlType:`float16`};case Z.Float32:return{sqlType:`float32`};case Z.Float64:return{sqlType:`float64`};case Z.Int:return{sqlType:`int32`};case Z.Int16:return{sqlType:`int16`};case Z.Int32:return{sqlType:`int32`};case Z.Int64:return{sqlType:`int64`};case Z.Uint16:return{sqlType:`uint16`};case Z.Uint32:return{sqlType:`uint32`};case Z.Uint64:return{sqlType:`uint64`};case Z.Uint8:return{sqlType:`uint8`};case Z.IntervalDayTime:return{sqlType:`interval[dt]`};case Z.IntervalYearMonth:return{sqlType:`interval[m]`};case Z.List:return{sqlType:`list`,valueType:PL(e.valueType)};case Z.FixedSizeBinary:return{sqlType:`fixedsizebinary`,byteWidth:e.byteWidth};case Z.Null:return{sqlType:`null`};case Z.Utf8:return{sqlType:`utf8`};case Z.Struct:return{sqlType:`struct`,fields:e.children.map(e=>FL(e.name,e.type))};case Z.Map:{let t=e;return{sqlType:`map`,keyType:PL(t.keyType),valueType:PL(t.valueType)}}case Z.Time:return{sqlType:`time[s]`};case Z.TimeMicrosecond:return{sqlType:`time[us]`};case Z.TimeMillisecond:return{sqlType:`time[ms]`};case Z.TimeNanosecond:return{sqlType:`time[ns]`};case Z.TimeSecond:return{sqlType:`time[s]`};case Z.Timestamp:return{sqlType:`timestamp`,timezone:e.timezone||void 0};case Z.TimestampSecond:return{sqlType:`timestamp[s]`,timezone:e.timezone||void 0};case Z.TimestampMicrosecond:return{sqlType:`timestamp[us]`,timezone:e.timezone||void 0};case Z.TimestampNanosecond:return{sqlType:`timestamp[ns]`,timezone:e.timezone||void 0};case Z.TimestampMillisecond:return{sqlType:`timestamp[ms]`,timezone:e.timezone||void 0}}throw Error(`unsupported arrow type: ${e.toString()}`)}function FL(e,t){let n=PL(t);return n.name=e,n}var IL=/'(opfs:\/\/\S*?)'/g,LL=/(opfs:\/\/\S*?)/g;function RL(e){return e.search(LL)>-1}function zL(e){return[...e.matchAll(IL)].map(e=>e[1])}var BL=new TextEncoder,VL=class{constructor(e,t=null){this._onInstantiationProgress=[],this._onExecutionProgress=[],this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{},this._nextMessageId=0,this._pendingRequests=new Map,this._config={},this._logger=e,this._onMessageHandler=this.onMessage.bind(this),this._onErrorHandler=this.onError.bind(this),this._onCloseHandler=this.onClose.bind(this),t!=null&&this.attach(t)}get logger(){return this._logger}get config(){return this._config}attach(e){this._worker=e,this._worker.addEventListener(`message`,this._onMessageHandler),this._worker.addEventListener(`error`,this._onErrorHandler),this._worker.addEventListener(`close`,this._onCloseHandler),this._workerShutdownPromise=new Promise((e,t)=>{this._workerShutdownResolver=e})}detach(){this._worker&&(this._worker.removeEventListener(`message`,this._onMessageHandler),this._worker.removeEventListener(`error`,this._onErrorHandler),this._worker.removeEventListener(`close`,this._onCloseHandler),this._worker=null,this._workerShutdownResolver(null),this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async terminate(){this._worker&&(this._worker.terminate(),this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async postTask(e,t=[]){if(!this._worker){console.error(`cannot send a message since the worker is not set!:`+e.type+`,`+e.data);return}let n=this._nextMessageId++;return this._pendingRequests.set(n,e),this._worker.postMessage({messageId:n,type:e.type,data:e.data},t),await e.promise}onMessage(e){var t;let n=e.data;switch(n.type){case`PROGRESS_UPDATE`:for(let e of this._onExecutionProgress)e(n.data);return;case`LOG`:this._logger.log(n.data);return;case`INSTANTIATE_PROGRESS`:for(let e of this._onInstantiationProgress)e(n.data);return}let r=this._pendingRequests.get(n.requestId);if(!r){console.warn(`unassociated response: [${n.requestId}, ${n.type.toString()}]`);return}if(this._pendingRequests.delete(n.requestId),n.type==`ERROR`){let e=Error(n.data.message);e.name=n.data.name,(t=Object.getOwnPropertyDescriptor(e,`stack`))!=null&&t.writable&&(e.stack=n.data.stack),r.promiseRejecter(e);return}switch(r.type){case`CLOSE_PREPARED`:case`COLLECT_FILE_STATISTICS`:case`REGISTER_OPFS_FILE_NAME`:case`COPY_FILE_TO_PATH`:case`DISCONNECT`:case`DROP_FILE`:case`DROP_FILES`:case`FLUSH_FILES`:case`INSERT_ARROW_FROM_IPC_STREAM`:case`IMPORT_CSV_FROM_PATH`:case`IMPORT_JSON_FROM_PATH`:case`OPEN`:case`PING`:case`REGISTER_FILE_BUFFER`:case`REGISTER_FILE_HANDLE`:case`REGISTER_FILE_URL`:case`RESET`:if(n.type==`OK`){r.promiseResolver(n.data);return}break;case`INSTANTIATE`:if(this._onInstantiationProgress=[],n.type==`OK`){r.promiseResolver(n.data);return}break;case`GLOB_FILE_INFOS`:if(n.type==`FILE_INFOS`){r.promiseResolver(n.data);return}break;case`GET_VERSION`:if(n.type==`VERSION_STRING`){r.promiseResolver(n.data);return}break;case`GET_FEATURE_FLAGS`:if(n.type==`FEATURE_FLAGS`){r.promiseResolver(n.data);return}break;case`GET_TABLE_NAMES`:if(n.type==`TABLE_NAMES`){r.promiseResolver(n.data);return}break;case`TOKENIZE`:if(n.type==`SCRIPT_TOKENS`){r.promiseResolver(n.data);return}break;case`COPY_FILE_TO_BUFFER`:if(n.type==`FILE_BUFFER`){r.promiseResolver(n.data);return}break;case`EXPORT_FILE_STATISTICS`:if(n.type==`FILE_STATISTICS`){r.promiseResolver(n.data);return}break;case`CONNECT`:if(n.type==`CONNECTION_INFO`){r.promiseResolver(n.data);return}break;case`RUN_PREPARED`:case`RUN_QUERY`:if(n.type==`QUERY_RESULT`){r.promiseResolver(n.data);return}break;case`SEND_PREPARED`:if(n.type==`QUERY_RESULT_HEADER`){r.promiseResolver(n.data);return}break;case`START_PENDING_QUERY`:if(n.type==`QUERY_RESULT_HEADER_OR_NULL`){r.promiseResolver(n.data);return}break;case`POLL_PENDING_QUERY`:if(n.type==`QUERY_RESULT_HEADER_OR_NULL`){r.promiseResolver(n.data);return}break;case`CANCEL_PENDING_QUERY`:if(this._onInstantiationProgress=[],n.type==`SUCCESS`){r.promiseResolver(n.data);return}break;case`FETCH_QUERY_RESULTS`:if(n.type==`QUERY_RESULT_CHUNK`){r.promiseResolver(n.data);return}break;case`CREATE_PREPARED`:if(n.type==`PREPARED_STATEMENT_ID`){r.promiseResolver(n.data);return}break}r.promiseRejecter(Error(`unexpected response type: ${n.type.toString()}`))}onError(e){console.error(e),console.error(`error in duckdb worker: ${e.message}`),this._pendingRequests.clear()}onClose(){if(this._workerShutdownResolver(null),this._pendingRequests.size!=0){console.warn(`worker terminated with ${this._pendingRequests.size} pending requests`);return}this._pendingRequests.clear()}isDetached(){return!this._worker}async reset(){let e=new NL(`RESET`,null);return await this.postTask(e)}async ping(){let e=new NL(`PING`,null);await this.postTask(e)}async dropFile(e){let t=new NL(`DROP_FILE`,e);return await this.postTask(t)}async dropFiles(e){let t=new NL(`DROP_FILES`,e);return await this.postTask(t)}async flushFiles(){let e=new NL(`FLUSH_FILES`,null);return await this.postTask(e)}async instantiate(e,t=null,n=e=>{}){this._onInstantiationProgress.push(n);let r=new NL(`INSTANTIATE`,[e,t]);return await this.postTask(r)}async getVersion(){let e=new NL(`GET_VERSION`,null);return await this.postTask(e)}async getFeatureFlags(){let e=new NL(`GET_FEATURE_FLAGS`,null);return await this.postTask(e)}async open(e){this._config=e;let t=new NL(`OPEN`,e);await this.postTask(t)}async tokenize(e){let t=new NL(`TOKENIZE`,e);return await this.postTask(t)}async connectInternal(){let e=new NL(`CONNECT`,null);return await this.postTask(e)}async connect(){let e=await this.connectInternal();return new OL(this,e)}async disconnect(e){let t=new NL(`DISCONNECT`,e);await this.postTask(t)}async runQuery(e,t){if(this.shouldOPFSFileHandling()){let n=await this.registerOPFSFileFromSQL(t);try{return await this._runQueryAsync(e,t)}finally{n.length>0&&await this.dropFiles(n)}}else return await this._runQueryAsync(e,t)}async _runQueryAsync(e,t){let n=new NL(`RUN_QUERY`,[e,t]);return await this.postTask(n)}async startPendingQuery(e,t,n=!1){if(this.shouldOPFSFileHandling()){let r=await this.registerOPFSFileFromSQL(t);try{return await this._startPendingQueryAsync(e,t,n)}finally{r.length>0&&await this.dropFiles(r)}}else return await this._startPendingQueryAsync(e,t,n)}async _startPendingQueryAsync(e,t,n=!1){let r=new NL(`START_PENDING_QUERY`,[e,t,n]);return await this.postTask(r)}async pollPendingQuery(e){let t=new NL(`POLL_PENDING_QUERY`,e);return await this.postTask(t)}async cancelPendingQuery(e){let t=new NL(`CANCEL_PENDING_QUERY`,e);return await this.postTask(t)}async fetchQueryResults(e){let t=new NL(`FETCH_QUERY_RESULTS`,e);return await this.postTask(t)}async getTableNames(e,t){let n=new NL(`GET_TABLE_NAMES`,[e,t]);return await this.postTask(n)}async createPrepared(e,t){let n=new NL(`CREATE_PREPARED`,[e,t]);return await this.postTask(n)}async closePrepared(e,t){let n=new NL(`CLOSE_PREPARED`,[e,t]);await this.postTask(n)}async runPrepared(e,t,n){let r=new NL(`RUN_PREPARED`,[e,t,n]);return await this.postTask(r)}async sendPrepared(e,t,n){let r=new NL(`SEND_PREPARED`,[e,t,n]);return await this.postTask(r)}async globFiles(e){let t=new NL(`GLOB_FILE_INFOS`,e);return await this.postTask(t)}async registerFileText(e,t){let n=BL.encode(t);await this.registerFileBuffer(e,n)}async registerFileURL(e,t,n,r){t===void 0&&(t=e);let i=new NL(`REGISTER_FILE_URL`,[e,t,n,r]);await this.postTask(i)}async registerEmptyFileBuffer(e){}async registerFileBuffer(e,t){let n=new NL(`REGISTER_FILE_BUFFER`,[e,t]);await this.postTask(n,[t.buffer])}async registerFileHandle(e,t,n,r){let i=new NL(`REGISTER_FILE_HANDLE`,[e,t,n,r]);await this.postTask(i,[])}async registerOPFSFileName(e){let t=new NL(`REGISTER_OPFS_FILE_NAME`,[e]);await this.postTask(t,[])}async collectFileStatistics(e,t){let n=new NL(`COLLECT_FILE_STATISTICS`,[e,t]);await this.postTask(n,[])}async exportFileStatistics(e){let t=new NL(`EXPORT_FILE_STATISTICS`,e);return await this.postTask(t,[])}async copyFileToBuffer(e){let t=new NL(`COPY_FILE_TO_BUFFER`,e);return await this.postTask(t)}async copyFileToPath(e,t){let n=new NL(`COPY_FILE_TO_PATH`,[e,t]);await this.postTask(n)}async insertArrowFromIPCStream(e,t,n){if(t.length==0)return;let r=new NL(`INSERT_ARROW_FROM_IPC_STREAM`,[e,t,n]);await this.postTask(r,[t.buffer])}async insertCSVFromPath(e,t,n){if(n.columns!==void 0){let e=[];for(let t in n.columns){let r=n.columns[t];e.push(FL(t,r))}n.columnsFlat=e,delete n.columns}let r=new NL(`IMPORT_CSV_FROM_PATH`,[e,t,n]);await this.postTask(r)}async insertJSONFromPath(e,t,n){if(n.columns!==void 0){let e=[];for(let t in n.columns){let r=n.columns[t];e.push(FL(t,r))}n.columnsFlat=e,delete n.columns}let r=new NL(`IMPORT_JSON_FROM_PATH`,[e,t,n]);await this.postTask(r)}shouldOPFSFileHandling(){return RL(this.config.path??``)?this.config.opfs?.fileHandling==`auto`:!1}async registerOPFSFileFromSQL(e){let t=zL(e),n=[];for(let e of t)try{await this.registerOPFSFileName(e),n.push(e)}catch(t){throw console.error(t),Error(`File Not found:`+e)}return n}};function HL(){let e=new TextDecoder;return t=>(typeof SharedArrayBuffer<`u`&&t.buffer instanceof SharedArrayBuffer&&(t=new Uint8Array(t)),e.decode(t))}HL();var UL=(e=>(e[e.BUFFER=0]=`BUFFER`,e[e.NODE_FS=1]=`NODE_FS`,e[e.BROWSER_FILEREADER=2]=`BROWSER_FILEREADER`,e[e.BROWSER_FSACCESS=3]=`BROWSER_FSACCESS`,e[e.HTTP=4]=`HTTP`,e[e.S3=5]=`S3`,e))(UL||{}),WL={name:`@duckdb/duckdb-wasm`,version:`1.33.1-dev45.0`,description:`DuckDB powered by WebAssembly`,license:`MIT`,repository:{type:`git`,url:`https://github.com/duckdb/duckdb-wasm.git`},keywords:[`sql`,`duckdb`,`relational`,`database`,`data`,`query`,`wasm`,`analytics`,`olap`,`arrow`,`parquet`,`json`,`csv`],dependencies:{"apache-arrow":`^17.0.0`,qs:`^6.14.1`},devDependencies:{"@types/emscripten":`^1.39.10`,"@types/jasmine":`^5.1.13`,"@typescript-eslint/eslint-plugin":`^6.21.0`,"@typescript-eslint/parser":`^6.21.0`,esbuild:`^0.20.2`,eslint:`^8.57.0`,"eslint-plugin-jasmine":`^4.1.3`,"eslint-plugin-react":`^7.37.5`,"fast-glob":`^3.3.2`,jasmine:`^5.13.0`,"jasmine-core":`^5.1.2`,"jasmine-spec-reporter":`^7.0.0`,"js-sha256":`^0.11.1`,karma:`^6.4.2`,"karma-chrome-launcher":`^3.2.0`,"karma-coverage":`^2.2.1`,"karma-firefox-launcher":`^2.1.3`,"karma-jasmine":`^5.1.0`,"karma-jasmine-html-reporter":`^2.1.0`,"karma-sourcemap-loader":`^0.4.0`,"karma-spec-reporter":`^0.0.36`,"make-dir":`^4.0.0`,nyc:`^15.1.0`,prettier:`^3.2.5`,puppeteer:`^22.8.0`,rimraf:`^5.0.5`,s3rver:`^3.7.1`,typedoc:`^0.28.15`,typescript:`^5.3.3`,"wasm-feature-detect":`^1.6.1`,"web-worker":`^1.2.0`},scripts:{"build:debug":`node bundle.mjs debug && tsc --emitDeclarationOnly`,"build:release":`node bundle.mjs release && tsc --emitDeclarationOnly`,docs:`typedoc`,format:`prettier --write "**/*.+(js|ts)"`,report:`node ./coverage.mjs`,"test:node":`node --enable-source-maps ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs`,"test:node:debug":`node --inspect-brk --enable-source-maps ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs`,"test:node:coverage":`nyc -r json --report-dir ./coverage/node node ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs`,"test:firefox":`karma start ./karma/tests-firefox.cjs`,"test:chrome":`karma start ./karma/tests-chrome.cjs`,"test:chrome:eh":`karma start ./karma/tests-chrome-eh.cjs`,"test:chrome:coverage":`karma start ./karma/tests-chrome-coverage.cjs`,"test:browser":`karma start ./karma/tests-all.cjs`,"test:browser:debug":`karma start ./karma/tests-debug.cjs`,test:`npm run test:chrome && npm run test:node`,"test:coverage":`npm run test:chrome:coverage && npm run test:node:coverage && npm run report`,lint:`eslint src test`},files:[`dist`,`!dist/tests-*`,`!dist/duckdb-browser-mvp.worker.js.map`,`!dist/types/test`],main:`dist/duckdb-browser.cjs`,module:`dist/duckdb-browser.mjs`,types:`dist/duckdb-browser.d.ts`,jsdelivr:`dist/duckdb-browser.cjs`,unpkg:`dist/duckdb-browser.mjs`,sideEffects:!1,browser:{fs:!1,path:!1,perf_hooks:!1,os:!1,worker_threads:!1},exports:{"./dist/duckdb-mvp.wasm":`./dist/duckdb-mvp.wasm`,"./dist/duckdb-eh.wasm":`./dist/duckdb-eh.wasm`,"./dist/duckdb-coi.wasm":`./dist/duckdb-coi.wasm`,"./dist/duckdb-browser":`./dist/duckdb-browser.mjs`,"./dist/duckdb-browser.cjs":`./dist/duckdb-browser.cjs`,"./dist/duckdb-browser.mjs":`./dist/duckdb-browser.mjs`,"./dist/duckdb-browser-coi.pthread.worker.js":`./dist/duckdb-browser-coi.pthread.worker.js`,"./dist/duckdb-browser-coi.worker.js":`./dist/duckdb-browser-coi.worker.js`,"./dist/duckdb-browser-eh.worker.js":`./dist/duckdb-browser-eh.worker.js`,"./dist/duckdb-browser-mvp.worker.js":`./dist/duckdb-browser-mvp.worker.js`,"./dist/duckdb-node":`./dist/duckdb-node.cjs`,"./dist/duckdb-node.cjs":`./dist/duckdb-node.cjs`,"./dist/duckdb-node-blocking":`./dist/duckdb-node-blocking.cjs`,"./dist/duckdb-node-blocking.cjs":`./dist/duckdb-node-blocking.cjs`,"./dist/duckdb-node-eh.worker.cjs":`./dist/duckdb-node-eh.worker.cjs`,"./dist/duckdb-node-mvp.worker.cjs":`./dist/duckdb-node-mvp.worker.cjs`,"./blocking":{node:{types:`./dist/duckdb-node-blocking.d.ts`,require:`./dist/duckdb-node-blocking.cjs`,import:`./dist/duckdb-node-blocking.cjs`},types:`./dist/duckdb-node-blocking.d.ts`,import:`./dist/duckdb-node-blocking.mjs`,require:`./dist/duckdb-node-blocking.cjs`},".":{browser:{types:`./dist/duckdb-browser.d.ts`,import:`./dist/duckdb-browser.mjs`,require:`./dist/duckdb-browser.cjs`},node:{types:`./dist/duckdb-node.d.ts`,import:`./dist/duckdb-node.cjs`,require:`./dist/duckdb-node.cjs`},types:`./dist/duckdb-browser.d.ts`,import:`./dist/duckdb-browser.mjs`,require:`./dist/duckdb-browser.cjs`}}};WL.name,WL.version;var GL=WL.version.split(`.`);GL[0],GL[1],GL[2],vL(yL());var KL=``+new URL(`assets/duckdb-browser-eh.worker--3HUwN9R.js`,import.meta.url).href,qL=``+new URL(`assets/duckdb-eh-D-nnNw7L.wasm.gz`,import.meta.url).href;async function JL(e){if(!e.endsWith(`.gz`))return e;let t=await fetch(e);if(!t.ok)throw Error(`DuckDB-WASM did not load (${t.status})`);let n=new Uint8Array(await t.arrayBuffer());return n[0]===31&&n[1]===139&&(n=new Uint8Array(await new Response(new Blob([n]).stream().pipeThrough(new DecompressionStream(`gzip`))).arrayBuffer())),URL.createObjectURL(new Blob([n],{type:`application/wasm`}))}var YL=null;function XL(){return YL||(YL=(async()=>{let e=e=>new URL(e,location.href).href,t=URL.createObjectURL(new Blob([`importScripts(${JSON.stringify(e(KL))});`],{type:`text/javascript`})),n=new Worker(t),r=new VL(new EL(SL.WARNING),n),i=await JL(e(qL));await r.instantiate(i,null),URL.revokeObjectURL(t),i.startsWith(`blob:`)&&URL.revokeObjectURL(i);let a=await r.connect();return await a.query(`SET checkpoint_threshold = '1TB'`),await a.query(`SET autoinstall_known_extensions = false`),await a.query(`SET autoload_known_extensions = false`),await a.close(),r})(),YL)}function ZL(e){return`"`+e.replace(/"/g,`""`)+`"`}function QL(e){if(!(e.x1>e.x0))throw Error(`buildDecimationSql: x1 must be greater than x0`);if(e.maxPoints<1)throw Error(`buildDecimationSql: maxPoints must be >= 1`);if(!e.table||!e.xcol||!e.ycol)throw Error(`buildDecimationSql: table, xcol and ycol are required`);let t=(e.x1-e.x0)/e.maxPoints,n=ZL(e.xcol),r=ZL(e.ycol);return{sql:`SELECT least(floor((${n} - ?) / ?), ? - 1) AS b, min(${r}) AS lo, max(${r}) AS hi, arg_min(${r}, ${n}) AS first, arg_max(${r}, ${n}) AS last FROM ${ZL(e.table)} WHERE ${n} BETWEEN ? AND ? GROUP BY 1 ORDER BY 1`,params:[e.x0,t,e.maxPoints,e.x0,e.x1]}}function $L(e){if(!(e.x1>e.x0))throw Error(`buildMultiDecimationSql: x1 must be greater than x0`);if(e.maxPoints<1)throw Error(`buildMultiDecimationSql: maxPoints must be >= 1`);if(!e.table||!e.xcol||e.ycols.length===0)throw Error(`buildMultiDecimationSql: table, xcol and at least one ycol are required`);let t=(e.x1-e.x0)/e.maxPoints,n=ZL(e.xcol),r=ZL(e.table);return{sql:`SELECT least(floor((${n} - ?) / ?), ? - 1) AS b, ${e.ycols.map((e,t)=>`min(${ZL(e)}) AS y${t}lo, max(${ZL(e)}) AS y${t}hi`).join(`, `)} FROM ${r} WHERE ${n} BETWEEN ? AND ? GROUP BY 1 ORDER BY 1`,params:[e.x0,t,e.maxPoints,e.x0,e.x1]}}var eR=`__kym_bin`;function tR(e){if(!(e.binWidth>0))throw Error(`buildPyramidBuildL0Sql: binWidth must be > 0`);if(e.ycols.length===0)throw Error(`buildPyramidBuildL0Sql: at least one ycol is required`);let t=ZL(e.xcol),n=ZL(e.srcTable);return`CREATE OR REPLACE TABLE ${ZL(e.dstTable)} AS SELECT ${`CAST(floor((${t} - ${iR(e.x0base)}) / ${iR(e.binWidth)}) AS BIGINT)`} AS ${eR}, ${e.ycols.map(e=>`min(${ZL(e)}) AS ${ZL(e+`__lo`)}, max(${ZL(e)}) AS ${ZL(e+`__hi`)}`).join(`, `)} FROM ${n} WHERE ${t} IS NOT NULL GROUP BY 1`}function nR(e){let t=ZL(e.srcTable);return`CREATE OR REPLACE TABLE ${ZL(e.dstTable)} AS SELECT CAST(floor(${eR} / 2.0) AS BIGINT) AS ${eR}, ${e.ycols.map(e=>`min(${ZL(e+`__lo`)}) AS ${ZL(e+`__lo`)}, max(${ZL(e+`__hi`)}) AS ${ZL(e+`__hi`)}`).join(`, `)} FROM ${t} GROUP BY 1`}function rR(e){if(!(e.x1>e.x0))throw Error(`buildPyramidQuerySql: x1 must be greater than x0`);if(e.maxPoints<1)throw Error(`buildPyramidQuerySql: maxPoints must be >= 1`);if(e.ycols.length===0)throw Error(`buildPyramidQuerySql: at least one ycol is required`);let t=(e.x1-e.x0)/e.maxPoints,n=e.binWidth/t,r=(e.x0base-e.x0)/t+.5*n,i=Math.max(0,Math.floor((e.x0-e.x0base)/e.binWidth)),a=Math.floor((e.x1-e.x0base)/e.binWidth),o=ZL(e.levelTable);return{sql:`SELECT least(greatest(CAST(floor(? + ${eR} * ?) AS BIGINT), 0), ?) AS b, ${e.ycols.map((e,t)=>`min(${ZL(e+`__lo`)}) AS y${t}lo, max(${ZL(e+`__hi`)}) AS y${t}hi`).join(`, `)} FROM ${o} WHERE ${eR} BETWEEN ? AND ? GROUP BY 1 ORDER BY 1`,params:[r,n,e.maxPoints-1,i,a]}}function iR(e){if(!Number.isFinite(e))throw Error(`num: value must be finite`);return Number.isInteger(e)?String(e):e.toExponential(17)}function aR(e){let t=ZL(e.table);return e.range?{sql:`SELECT count(*) AS n FROM ${t} WHERE ${ZL(e.range.xcol)} BETWEEN ? AND ?`,params:[e.range.x0,e.range.x1]}:{sql:`SELECT count(*) AS n FROM ${t}`,params:[]}}function oR(e){if(!Number.isInteger(e.stride)||e.stride<1)throw Error(`buildSampleRowsSql: stride must be a positive integer`);let t=ZL(e.table),n=e.range?` WHERE ${ZL(e.range.xcol)} BETWEEN ? AND ?`:``,r=e.range?[e.range.x0,e.range.x1]:[];return e.stride===1?{sql:`SELECT * FROM ${t}${n}`,params:r}:{sql:`SELECT * EXCLUDE(__kym_rn) FROM (SELECT *, row_number() OVER () - 1 AS __kym_rn FROM ${t}${n}) WHERE __kym_rn % ${e.stride} = 0`,params:r}}function sR(e){return`'`+e.replace(/'/g,`''`)+`'`}function cR(e){let t=e.columnNames.map(sR).join(`, `),n=e.delim===` `?`'\\t'`:sR(e.delim),r=e.decimalComma?`decimal_separator=',', `:``;return`SELECT * FROM read_csv(${sR(e.handle)}, header=false, skip=${e.dataStartRow}, delim=${n}, `+r+`names=[${t}], auto_type_candidates=['DOUBLE', 'VARCHAR'])`}function lR(e,t,n){let r=e.length,i={x:new Float64Array(r),min:new Float64Array(r),max:new Float64Array(r),first:new Float64Array(r),last:new Float64Array(r)};for(let a=0;a<r;a++){let r=e[a],o=Number(r.b);i.x[a]=t+(o+.5)*n,i.min[a]=Number(r.lo),i.max[a]=Number(r.hi),i.first[a]=Number(r.first),i.last[a]=Number(r.last)}return i}var uR=class{#e;#t=new Map;constructor(e){this.#e=Math.max(1,e)}get(e){let t=this.#t.get(e);return t!==void 0&&(this.#t.delete(e),this.#t.set(e,t)),t}set(e,t){if(this.#t.has(e)&&this.#t.delete(e),this.#t.set(e,t),this.#t.size>this.#e){let e=this.#t.keys().next().value;this.#t.delete(e)}}get size(){return this.#t.size}},dR=0,fR=()=>`t_${++dR}`,pR=5e4,mR=65536,hR=512,gR=2;function _R(e){return e<1?1:2**Math.floor(Math.log2(e))}var vR=class e{#e;#t;#n;#r;#i=new uR(96);#a=new Map;#o=new Map;#s=[];#c=0;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n,this.#r=new Set(t.map(e=>e.name))}static async open(t,n){let r=await XL(),i=await r.connect(),a=await t.slice(0,256*1024).text(),o=U(a),s=Be(a),c=Xe(o,s.headerRow),l=s.unitsRow===null?``:o[s.unitsRow]??``,u=we(o[s.headerRow]??``),d=qe(o.slice(s.dataStartRow,s.dataStartRow+10),u);n?.({phase:`reading`,message:`Reading file…`});let f=new Uint8Array(await t.arrayBuffer());await r.dropFile(`input.csv`).catch(()=>{}),await r.registerFileBuffer(`input.csv`,f),n?.({phase:`parsing`,message:`Parsing CSV…`});let p=fR(),m=cR({handle:`input.csv`,columnNames:c,delim:u,dataStartRow:s.dataStartRow,decimalComma:d});await i.query(`CREATE OR REPLACE TABLE ${ZL(p)} AS ${m}`),await r.dropFile(`input.csv`).catch(()=>{});let h=l?l.split(u).map(e=>e.trim()):[],g=new Map;c.forEach((e,t)=>g.set(e,h[t]??``));let _=await e.attach(i,p,g);return n?.({phase:`done`,message:`Ready.`}),_}static async attach(t,n,r){return new e(t,(await t.query(`DESCRIBE ${ZL(n)}`)).toArray().map(e=>{let t=String(e.column_type??``),n=/INT|DECIMAL|DOUBLE|FLOAT|REAL|HUGEINT|BIGINT/i.test(t),i=String(e.column_name);return{name:i,type:n?`number`:`string`,unit:r.get(i)??``}}),n)}async getSchema(){return this.#t}async getSeries(e){if(!Number.isFinite(e.viewport.x0)||!Number.isFinite(e.viewport.x1)||e.viewport.x1<=e.viewport.x0){let e=new Float64Array;return{x:e,min:e,max:e,first:e,last:e}}let t=(e.viewport.x1-e.viewport.x0)/e.maxPoints,{sql:n,params:r}=QL({table:this.#n,xcol:e.viewport.xKey,ycol:e.column,x0:e.viewport.x0,x1:e.viewport.x1,maxPoints:e.maxPoints}),i=await this.#e.prepare(n);try{return lR((await i.query(...r)).toArray(),e.viewport.x0,t)}finally{await i.close()}}async getSeriesMulti(e,t,n){let r=(t.x1-t.x0)/n,i=this.#r.has(t.xKey)?e.filter(e=>this.#r.has(e)):[];if(i.length===0||!Number.isFinite(t.x0)||!Number.isFinite(t.x1)||t.x1<=t.x0)return{x0:t.x0,bucket:r,rows:[],columns:i};let a=`${t.xKey}|${i.join(`,`)}|${t.x0}|${t.x1}|${n}`,o=this.#i.get(a);if(o)return o;let s=this.#o.get(t.xKey);s===void 0&&this.#l(t.xKey);let{sql:c,params:l}=this.#u(s??null,i,t,n)??$L({table:this.#n,xcol:t.xKey,ycols:i,x0:t.x0,x1:t.x1,maxPoints:n}),u=await this.#e.prepare(c);try{let e=(await u.query(...l)).toArray(),n={x0:t.x0,bucket:r,rows:e,columns:i};return this.#i.set(a,n),n}finally{await u.close()}}#l(e){let t=this.#a.get(e);if(t)return t;let n=this.#d(e).then(t=>(this.#o.set(e,t),t)).catch(()=>(this.#o.set(e,null),null));return this.#a.set(e,n),n}#u(e,t,n,r){if(!e)return null;for(let n of t)if(!e.cols.has(n))return null;let i=(n.x1-n.x0)/r/gR,a=null;for(let t of e.levels)t.binWidth<=i&&(a=t);return a?rR({levelTable:a.table,ycols:t,x0base:e.x0base,binWidth:a.binWidth,x0:n.x0,x1:n.x1,maxPoints:r}):null}async#d(e){if(!this.#r.has(e))return null;let t=await(await XL()).connect();try{let n=aR({table:this.#n}),r=await t.query(n.sql),i=Number(r.getChild(`n`)?.get(0)??0);if(i<pR)return null;let a=await t.query(`SELECT min(${ZL(e)}) AS lo, max(${ZL(e)}) AS hi FROM ${ZL(this.#n)}`),o=Number(a.getChild(`lo`)?.get(0)),s=Number(a.getChild(`hi`)?.get(0));if(!Number.isFinite(o)||!Number.isFinite(s)||!(s>o))return null;let c=this.#t.filter(t=>t.type===`number`&&t.name!==e).map(e=>e.name);if(c.length===0)return null;let l=s-o,u=Math.min(mR,_R(i));if(u<hR*2)return null;let d=++this.#c,f=[],p=u,m=0,h=`${this.#n}_p${d}_0`;await t.query(tR({srcTable:this.#n,dstTable:h,xcol:e,ycols:c,x0base:o,binWidth:l/u})),this.#s.push(h),f.push({table:h,binWidth:l/u,nbins:p});let g=h;for(;p/2>=hR;){p/=2,m+=1;let e=`${this.#n}_p${d}_${m}`;await t.query(nR({srcTable:g,dstTable:e,ycols:c})),this.#s.push(e),f.push({table:e,binWidth:l/p,nbins:p}),g=e}return{x0base:o,cols:new Set(c),levels:f}}finally{await t.close()}}async sampleRows(e,t){let n=t&&this.#r.has(t.xcol)?t:void 0,r=aR({table:this.#n,range:n}),i=await this.#e.prepare(r.sql),a;try{let e=await i.query(...r.params);a=Number(e.getChild(`n`)?.get(0)??0)}finally{await i.close()}if(a===0)return[];let o=Math.max(1,Math.ceil(a/e)),{sql:s,params:c}=oR({table:this.#n,stride:o,range:n}),l=await this.#e.prepare(s),u=this.#t.map(e=>e.name),d=[];try{let e=await l.query(...c);for(let t=0;t<e.numRows;t++)d.push({});for(let t of u){let n=e.getChild(t);if(!n){for(let e of d)e[t]=null;continue}let r=n.toArray(),i=ArrayBuffer.isView(r),a=n.nullCount>0;for(let e=0;e<d.length;e++){let o=a&&!n.isValid(e)?null:i?r[e]:n.get(e);d[e][t]=typeof o==`bigint`?Number(o):o}}}finally{await l.close()}return d}async readColumns(e,t,n){let r=[...new Set(e)].filter(e=>this.#r.has(e));if(!r.length)return{};let i=r.map((e,t)=>`coalesce(TRY_CAST(${ZL(e)} AS DOUBLE), 'NaN'::DOUBLE) AS "c${t}"`).join(`, `),a=await this.#e.prepare(`SELECT ${i} FROM ${ZL(this.#n)} ORDER BY rowid LIMIT ? OFFSET ?`);try{let e=await a.query(n,t),i={};return r.forEach((t,n)=>{let r=e.getChild(`c${n}`)?.toArray();i[t]=r instanceof Float64Array?r:Float64Array.from(r??[],Number)}),i}finally{await a.close()}}async xBounds(e){if(!this.#r.has(e))return{x0:0,x1:0};let t=await this.#e.query(`SELECT min(${ZL(e)}) AS lo, max(${ZL(e)}) AS hi FROM ${ZL(this.#n)}`);return{x0:Number(t.getChild(`lo`)?.get(0)),x1:Number(t.getChild(`hi`)?.get(0))}}async dispose(){for(let e of this.#s)try{await this.#e.query(`DROP TABLE IF EXISTS ${ZL(e)}`)}catch{}try{await this.#e.query(`DROP TABLE IF EXISTS ${ZL(this.#n)}`)}catch{}await this.#e.close()}},yR=1e8,bR=256*1024;function xR(e,t,n=0,r=yR){return e>314572800||n+t>r?`duckdb`:`memory`}function SR(e,t){let n=U(t);t.length<e&&n.length>1&&(n=n.slice(0,-1));try{let t=Be(n.join(`
70
- `)),r=Xe(n,t.headerRow).length,i=n.slice(t.dataStartRow);if(i.length===0)return Math.ceil(e/8);let a=n.slice(0,t.dataStartRow).reduce((e,t)=>e+t.length+1,0),o=i.reduce((e,t)=>e+t.length+1,0)/i.length;return Math.ceil(Math.max(0,e-a)/o)*r}catch{return Math.ceil(e/8)}}var CR=12e3;async function wR(e,t,n){let r=Be(n),i=typeof Worker>`u`?et(n,r):await qE({rawText:n,config:r}),a=new ZE(i);return{id:e,name:t,kind:`memory`,source:a,schema:await a.getSchema(),data:i,rawText:n,parseConfig:r}}async function TR(e,t,n,r,i=e=>e.text(),a){let o=Be(r),s=typeof Worker>`u`?await JE({rawText:await i(n),config:o},a):await JE({file:n,config:o},a),c=new ZE(s);return{id:e,name:t,kind:`memory`,source:c,schema:await c.getSchema(),data:s,rawText:r,file:n,parseConfig:o}}async function ER(e,t,n){let r=await vR.open(t,n),i=await r.getSchema(),a=await r.sampleRows(CR),o={meta:``,columnNames:i.map(e=>e.name),units:i.map(e=>e.unit),rows:a},s=await t.slice(0,bR).text();return{id:e,name:t.name,kind:`duckdb`,source:r,schema:i,data:o,rawText:s,parseConfig:Be(s)}}async function DR(e,t,n,r,i=0,a){let o=await t.slice(0,bR).text();return xR(t.size,SR(t.size,o),i)===`memory`?TR(e,t.name,t,o,e=>n(e),a):ER(e,t,r)}function OR(e,t){return e instanceof File&&e.name===t.name&&e.size===t.size&&e.lastModified===t.lastModified}async function kR(e,t,n){let r=n.find(e=>e.kind===`memory`&&e.parseConfig&&OR(e.file,t)&&Ue(e.data.rows));if(!r)return null;let i=await t.slice(0,bR).text();if(!le(r.parseConfig,Be(i)))return null;let a={...r.data,rows:Pe(Ue(r.data.rows))};return{id:e,name:t.name,kind:`memory`,source:new ZE(a),schema:r.schema,data:a,rawText:r.rawText,file:t,parseConfig:r.parseConfig}}function AR(e){let t=new Set,n=0;for(let r of e){if(r.kind!==`memory`)continue;let e=Ue(r.data.rows)??r.data.rows;t.has(e)||(t.add(e),n+=r.data.rows.length*r.data.columnNames.length)}return n}var jR=4096,MR=[`.dat`,`.txt`,`.csv`,`.tsv`],NR=[L,h,z,i,dt,j,b],PR=e=>{let t=e.lastIndexOf(`.`);return t<=0?``:e.slice(t).toLowerCase()},FR=e=>{let t=e.lastIndexOf(`.`);return(t<=0?e:e.slice(0,t)).toLowerCase()};async function IR(e){let t=new Uint8Array(await e.slice(0,jR).arrayBuffer()),n=PR(e.name),r=NR.filter(e=>e.extensions.includes(n));for(let n of[...r,...NR.filter(e=>!r.includes(e))])if(n.sniff(t,e.name))return n;return null}async function LR(e){return new Uint8Array(await e.slice(0,jR).arrayBuffer()).includes(0)}async function RR(e){let t=await Promise.all(e.map(IR)),n=[],r=new Set;e.forEach((e,i)=>{let a=t[i];a&&(n.push({main:e,companions:[],format:a}),r.add(e))});for(let i of[...n])for(let n of i.format.companions??[]){let a=e.filter((e,r)=>!t[r]&&PR(e.name)===n.ext),o=a.find(e=>FR(e.name)===FR(i.main.name))??(n.anyName&&a.length===1?a[0]:void 0);o&&(i.companions.push(o),r.add(o))}let i=new Set(NR.flatMap(e=>(e.companions??[]).map(e=>e.ext))),a=[];for(let t of e){if(r.has(t))continue;let e=PR(t.name);e===`.dat`&&await LR(t)?a.push({file:t.name,error:Error(`This COMTRADE .dat needs its .cfg file — drop both together.`)}):MR.includes(e)?n.push({main:t,companions:[],format:null}):i.has(e)?a.push({file:t.name,error:Error(`${t.name} is read together with its main file (same name). Drop both files together.`)}):a.push({file:t.name,error:Error(`${t.name}: Kymoscope cannot read this file type.`)})}return n.sort((t,n)=>e.indexOf(t.main)-e.indexOf(n.main)),{items:n,errors:a}}var zR=[...new Set([...MR,...NR.flatMap(e=>[...e.extensions,...(e.companions??[]).map(e=>e.ext)])])];function BR(e){let t=0;for(let n=0;n<e.length;n++)e[n]!==e[n]&&t++;if(t===0)return sN(e);let n=new Uint8Array(e.length+7>>3);for(let t=0;t<e.length;t++)e[t]===e[t]&&(n[t>>3]|=1<<(t&7));return sN(FM({type:new Bk,data:e,nullBitmap:n,length:e.length,nullCount:t}))}var VR=122880,HR=class{#e;#t;#n;#r=!1;#i=[];#a=0;#o;rows=0;constructor(e,t,n,r=VR){this.#e=e,this.#t=t,this.#n=new SN(n.map(e=>new CN(e.name,e.text?new Uk:new Bk,!0))),this.#o=r}async append(e){let t=e.length;if(t===0)return;let n=this.#n.fields.map((n,r)=>{let i=e.columns[r];return(i instanceof Float64Array?BR(i.subarray(0,t)):_F(i.slice(0,t),new Uk)).data[0]});this.#i.push(new EF(this.#n,FM({type:new eA(this.#n.fields),length:t,nullCount:0,children:n}))),this.#a+=t,this.rows+=t,this.#a>=this.#o&&await this.flush()}async flush(){if(this.#a===0)return;let e=new wF(this.#n,this.#i);this.#i=[],this.#a=0,await this.#e.insertArrowTable(e,{name:this.#t,create:!this.#r}),this.#r=!0}},UR=`This file's groups do not interleave in time: reading them together would hold too much in memory. Choose fewer groups, or split them.`,WR=e=>e.length*(1+e.columns.length);function GR(e){let t=e[Symbol.asyncIterator]();return{pull:async()=>{let e=await t.next();return e.done?null:e.value}}}function KR(e,t){let n=Array.from({length:t.size},()=>[]),r=!1,i=0,a=async a=>{for(;;){if(n[a].length){let e=n[a].shift();return i-=WR(e),e}if(r)return null;let o=await e.next();if(o.done){r=!0;continue}let s=t.get(o.value.group);if(s!==void 0&&(n[s].push(o.value),(i+=WR(o.value))>128e6))throw Error(UR)}};return n.map((e,t)=>({pull:()=>a(t)}))}function qR(e,t){if(e.time)return e.time;let n=new Float64Array(e.length);if(t.time.kind===`rate`){let{rate:r,start:i}=t.time;for(let t=0;t<e.length;t++)n[t]=i+(e.start+t)/r}else for(let t=0;t<e.length;t++)n[t]=e.start+t;return n}var JR=new Int32Array,YR={t:new Float64Array,cols:[],from:0};function XR(e,t,n,r){let i=n,a=r;for(;i<a;){let n=i+a>>>1;e[n]<=t?i=n+1:a=n}return i}var ZR=class{group;channels;feed;pending=[];done=!1;last;scratch=[];#e=-1/0;constructor(e,t,n){this.group=e,this.channels=t,this.feed=n,this.last=t.map(e=>e.text?null:NaN)}rows(){let e=0;for(let t of this.pending)e+=t.t.length-t.from;return e}lastTime(){let e=this.pending[this.pending.length-1];return e&&e.t.length>e.from?e.t[e.t.length-1]:-1/0}async fill(){let e=await this.feed.pull();if(!e){this.done=!0;return}if(e.length===0)return;let t=QR(qR(e,this.group),this.#e);if(t.length&&(this.#e=t[t.length-1]),this.pending.push({t,cols:e.columns,from:0}),this.rows()*(1+this.channels.length)>128e6)throw Error(UR)}};function QR(e,t){let n=t,r=0;for(;r<e.length;r++){let t=e[r];if(!(t>=n&&t>-1/0&&t<1/0))break;n=t}if(r===e.length)return e;for(n===-1/0&&(n=0);r<e.length;r++){let t=e[r];t>=n&&t<1/0?n=t:e[r]=n}return e}function $R(e,t){let n=e.length,r=e.map(e=>e.t),i=Int32Array.from(e,e=>e.from),a=Int32Array.from(e,e=>XR(e.t,t,e.from,e.t.length));if(n===1)return r[0].subarray(i[0],a[0]);let o=0;for(let e=0;e<n;e++)o+=a[e]-i[e];let s=new Float64Array(o),c=0;for(;;){let e=1/0;for(let t=0;t<n;t++)i[t]<a[t]&&r[t][i[t]]<e&&(e=r[t][i[t]]);if(e===1/0)break;s[c++]=e;for(let t=0;t<n;t++){let n=r[t],o=a[t],s=i[t];for(;s<o&&n[s]===e;)s++;i[t]=s}}return s.subarray(0,c)}function ez(e,t,n,r,i,a){if(i-r>8)e.set(t.subarray(n+r,n+i),a);else for(let o=r;o<i;o++)e[a+o-r]=t[n+o]}function tz(e,t,n,r,i,a){let o=0;for(let s=0;s<n.length;s++){let c=n[s],l=c.length;if(l===0)continue;let u=i[s].from,d=i[s].cols[a];e.fill(t,o,c[0]);let f=r[s],p=0;for(let t=0;t<f.length;t++){let n=f[t];ez(e,d,u,p,n,c[p]);let r=c[n],i=c[n+1],a=d[u+n];if(i-r>16)e.fill(a,r,i);else for(let t=r;t<i;t++)e[t]=a;p=n+1}ez(e,d,u,p,l-1,c[p]),o=c[l-1],t=d[u+l-1]}e.fill(t,o,e.length)}function nz(e,t,n,r,i){let a=0;for(let o=0;o<n.length;o++){let s=n[o],c=s.length;if(c===0)continue;let l=r[o].from,u=r[o].cols[i];e.fill(t,a,s[0]);for(let t=0;t<c-1;t++)e.fill(u[l+t],s[t],s[t+1]);a=s[c-1],t=u[l+c-1]}e.fill(t,a,e.length)}function rz(e,t,n,r,i){let a=n.length,o=null,s=0;for(let c=0;c<i.length;c++){let l=e[t+c],u=r;if(n[r]<l){let e=r,t=1;for(;e+t<a&&n[e+t]<l;)e+=t,t*=2;let i=Math.min(e+t,a-1);for(;i-e>1;){let t=e+i>>>1;n[t]<l?e=t:i=t}r=i}i[c]=r,c>0&&r!==u+1&&((o??=new Int32Array(i.length-1))[s++]=c-1)}return o?o.subarray(0,s):JR}function iz(e,t,n,r,i){let a=t.length;if(r){let t=e.pending[0],n=t.from+a,r=t.cols.map(e=>e instanceof Float64Array?e.subarray(t.from,n):e.slice(t.from,n));if(a>0)for(let i=0;i<r.length;i++)e.last[i]=t.cols[i][n-1];return e.pending=n<t.t.length?[{...t,from:n}]:[],r}let o=e.pending,s=[],c=[];if(a>0){let e=t[a-1],n=0;for(let r of o){let i=r.t,a=XR(i,e,r.from,i.length),o=new Int32Array(a-r.from);if(c.push(rz(i,r.from,t,n,o)),o.length&&(n=o[o.length-1]),s.push(o),a<i.length)break}}let l=e.channels.map((r,l)=>{if(r.sparse&&n){let e=r.text?Array(a).fill(null):new Float64Array(a).fill(NaN);for(let n=0;n<s.length;n++){let r=s[n],{t:i,from:c}=o[n],u=o[n].cols[l];for(let n=0;n<r.length;n++){let o=r[n];o<a&&t[o]===i[c+n]&&(e[o]=u[c+n])}}return e}if(r.text){let t=Array(a);return nz(t,e.last[l],s,o,l),t}let u;return i?(e.scratch[l]?.length>=a||(e.scratch[l]=new Float64Array(a)),u=e.scratch[l].subarray(0,a)):u=new Float64Array(a),tz(u,e.last[l],s,c,o,l),u}),u=[];for(let t=0;t<o.length;t++){let n=o[t],r=t<s.length?s[t].length:0;if(r>0)for(let t=0;t<e.channels.length;t++)e.last[t]=n.cols[t][n.from+r-1];n.from+r<n.t.length&&u.push(r?{...n,from:n.from+r}:n)}return e.pending=u,l}async function az(e,t,n,r,i,a=!1){let o=e.map((e,r)=>new ZR(e,t[r],n[r])),s=-1;e.forEach((t,n)=>{!t.irregular&&(s<0||t.samples>e[s].samples)&&(s=n)});let c=e.map((e,t)=>t===s||!!e.irregular),l=o.filter((e,t)=>c[t]),u=l.length===1,d=0;for(;;){i?.throwIfAborted();for(let e of l)for(;!e.done&&e.rows()===0;)await e.fill();if(l.every(e=>e.rows()===0))break;let e=1/0;for(let t of l)t.done||(e=Math.min(e,t.lastTime()));for(let t=0;t<o.length;t++)if(!c[t])for(;!o[t].done&&o[t].lastTime()<=e;)await o[t].fill();let t=$R(l.map(e=>e.pending[0]??YR),e),n=[t];for(let e=0;e<o.length;e++)n.push(...iz(o[e],t,c[e],u&&c[e],a));d+=t.length,t.length&&await r({length:t.length,columns:n})}return d}var oz=class{#e;#t;#n;#r=0;constructor(e,t){let n=Math.max(1024,t);this.#e=e.map(e=>e.name),this.#t=e.map(()=>new Float64Array(n)),this.#n=e.map(()=>null)}append(e){let t=this.#r,n=t+e.length;if(n>this.#t[0].length){let e=Math.max(n,Math.ceil(this.#t[0].length*1.5));this.#t=this.#t.map(n=>{let r=new Float64Array(e);return r.set(n.subarray(0,t)),r})}e.columns.forEach((n,r)=>{let i=this.#t[r];if(n instanceof Float64Array){i.set(n.subarray(0,e.length),t);return}let a=this.#n[r];for(let o=0;o<e.length;o++){i[t+o]=NaN;let e=n[o];e!=null&&((a??=this.#n[r]=[])[t+o]=e)}}),this.#r=n}table(){let e=this.#r,t=this.#t.map(t=>t.length-e>t.length/100?t.slice(0,e):t.subarray(0,e));return{keys:this.#e,length:e,values:t,text:this.#n}}};async function sz(e,t,n){return D(await e.plan(t,n))}var cz=(e,t,n)=>Math.max(0,Math.min(e,Math.max(1<<20,n),Math.floor(1e8/t)));function lz(e,t){let n=t.flatMap(t=>t.channels.map(n=>({ch:e.groups[t.group].channels[n],group:e.groups[t.group].name}))),r=new Map;for(let{ch:e}of n)r.set(e.name.toLowerCase(),(r.get(e.name.toLowerCase())??0)+1);let i=De(n.map(({ch:e,group:n})=>t.length>1&&r.get(e.name.toLowerCase())>1?`${e.name} [${n}]`:e.name));return[{name:`Time`,unit:t.every(t=>e.groups[t.group].time.kind===`index`)?``:`s`,text:!1},...n.map(({ch:e},t)=>({name:i[t],unit:e.unit,text:!!e.text}))]}function uz(e,t){let n=t.map(t=>e.groups[t.group]);if(n.some(e=>e.samples<0))return-1;let r=0,i=0;for(let e of n)e.irregular?i+=e.samples:r=Math.max(r,e.samples);return r+i}function dz(e,t,n){let r=uz(e,t);return r<0?Math.ceil(n/4):r*(1+t.reduce((e,t)=>e+t.channels.length,0))}async function fz(e,t,n,r,i,a,o={}){let s=lz(n,i),c=i.map(e=>n.groups[e.group]),l=i.map(e=>e.channels.map(t=>n.groups[e.group].channels[t])),u=[...n.events];async function*d(e){for await(let t of e)t.events&&u.push(...t.events),yield t}let f={files:t,plan:n,io:r,selection:i,signal:o.signal},p=e.streamGroup&&i.length>1&&!n.interleaved?i.map(t=>GR(d(e.streamGroup({...f,selection:[t]},t.group)))):KR(d(e.stream(f)),new Map(i.map((e,t)=>[e.group,t]))),m=uz(n,i),h=a===`memory`?new oz(s,cz(m,s.length,r.size)):null,g=0,_=await az(c,l,p,async e=>{h?h.append(e):await o.chunk(e);let t=Date.now();o.progress&&t-g>100&&(g=t,o.progress(Math.min(.99,r.bytesRead/Math.max(1,r.size))))},o.signal,!!h);return o.progress?.(1),u.sort((e,t)=>e.time-t.time),{columns:s,rows:_,table:h?.table(),events:u}}var pz=``+new URL(`assets/importer.worker-BblHvxro.js`,import.meta.url).href,mz=``+new URL(`assets/h5wasmModule-BCQWU2Gw.js`,import.meta.url).href,hz=()=>new UE(`cancelled`);function gz(){let e=WE(pz);return e.postMessage({type:`init`,h5Url:new URL(mz,location.href).href}),e}var _z=null,vz=e=>{typeof requestIdleCallback==`function`?requestIdleCallback(e,{timeout:5e3}):setTimeout(e,1e3)};function yz(e,t=gz){t===gz&&typeof Worker>`u`||(_z&&_z.make!==t&&(_z.w.terminate(),_z=null),_z??={w:t(),h5:!1,make:t},e&&!_z.h5&&(_z.h5=!0,_z.w.postMessage({type:`warm`})))}function bz(e){if(_z?.make!==e)return{w:e(),rewarm:null};let{w:t,h5:n}=_z;return _z=null,{w:t,rewarm:n}}function xz(e,t,n,r,i){return!r&&typeof Worker>`u`?Sz(e,t,n,i):wz(e,t,n,r??gz)}function Sz(e,t,n,r=async e=>(await import(`./importers-CLmQyVrb.js`)).importerFor(e)){let i=new ke(t.main),a=null,o=null,s=e=>e.catch(e=>{throw n?.aborted?hz():f(e)});return{plan:()=>s((async()=>(a=await r(e),o=await sz(a,t,i)))()),read:(e,r,c={})=>(i.bytesRead=0,s(fz(a,t,o,i,e,r,{...c,signal:n}))),close(){}}}var Cz=3e4;function wz(e,t,n,r){let{w:i,rewarm:a}=bz(r),o=null,s=Promise.resolve(),c=Date.now(),l=-1,u=0,d=!1,f=e=>{let t=o;o=null,t?.reject(e)},p=e=>{d=!0,i.terminate(),f(e)},m=setInterval(()=>{o&&u===0&&Date.now()-c>Cz&&p(Error(S))},1e3),h=()=>p(hz());n?.addEventListener(`abort`,h,{once:!0}),i.onmessage=e=>{let t=e.data,n=o;n&&((t.type!==`alive`||t.work!==l)&&(c=Date.now()),t.type===`alive`?l=t.work:t.type===`plan`?(o=null,n.resolve(t.plan)):t.type===`progress`?n.on.progress?.(t.fraction):t.type===`chunk`?(u++,s=s.then(()=>n.on.chunk(t.chunk)).then(()=>{u--,c=Date.now(),i.postMessage({type:`ack`})},e=>{u--,p(e instanceof Error?e:Error(String(e)))})):t.type===`done`?s.then(()=>{o===n&&(o=null,n.resolve(t.result))}):f(Error(t.message)))},i.onerror=e=>f(e instanceof Error?e:Error(`The import worker failed.`));let g=(e,t={})=>new Promise((r,a)=>{if(n?.aborted){a(hz());return}if(d){a(Error(S));return}o={resolve:r,reject:a,on:t},c=Date.now(),i.postMessage(e)});return{plan:()=>g({type:`plan`,importer:e,files:t}),read:(e,t,n)=>g({type:`read`,selection:e,mode:t},n),close:()=>{clearInterval(m),n?.removeEventListener(`abort`,h),i.terminate(),a!==null&&vz(()=>yz(a,r))}}}var Tz=12e3,Ez=(e,t)=>t.map(t=>({group:t,channels:e.groups[t].channels.map((e,t)=>t)}));function Dz(e,t){let n=null;for(let r of t){let t=e.groups[r.group];!t.irregular&&(!n||t.samples>n.samples)&&(n={samples:t.samples,rate:t.rateHz})}return n?.rate??null}function Oz(e,t,n,r){return{format:e.format,importer:t,startTime:e.startTime,groups:e.groups.map(e=>({name:e.name,channels:e.channels.length,samples:e.samples,rateHz:e.rateHz})),selection:n,combined:n.length>1?{groups:n.length,rateHz:Dz(e,n)}:null,splitKey:r,channels:n.reduce((e,t)=>e+t.channels.length,0),notes:e.notes,meta:e.meta,events:[]}}async function kz(e,t,n,r,i,a){let o={meta:``,columnNames:n.columns.map(e=>e.name),units:n.columns.map(e=>e.unit),rows:Pe(n.table)},s=new ZE(o);return{id:e,name:t,kind:`memory`,source:s,schema:await s.getSchema(),data:o,file:r,companions:i,info:{...a,events:n.events}}}async function Az(e,t,n,r,i,a,o,s,c){let l=XL().then(e=>e.connect());l.catch(()=>void 0);let u=fR(),d=lz(r,i),f=new HR({insertArrowTable:async(e,t)=>(await l).insertArrowTable(e,t)},u,d);try{let r=await n.read(i,`stream`,{progress:c,chunk:e=>f.append(e)});if(await f.flush(),f.rows===0)throw Error(`${t}: the file has no samples.`);let p=await l,m=await vR.attach(p,u,new Map(d.map(e=>[e.name,e.unit]))),h=await m.getSchema(),g=await m.sampleRows(Tz);return{id:e,name:t,kind:`duckdb`,source:m,schema:h,data:{meta:``,columnNames:h.map(e=>e.name),units:h.map(e=>e.unit),rows:g},file:a,companions:o,info:{...s,events:r.events}}}catch(e){let t=await l.catch(()=>null);throw await t?.query(`DROP TABLE IF EXISTS ${ZL(u)}`).catch(()=>void 0),await t?.close().catch(()=>void 0),e}}async function jz(e,t){let{main:n,companions:r}=e,i=xz(e.format,{main:n,companions:r,keys:e.keys},t.signal,t.createWorker,t.find),a=[];try{t.priorInMemoryValues+n.size/8>1e8&&XL().catch(()=>void 0);let o=await i.plan(),s=t.selection??t.initial??Ez(o,o.defaultGroups??o.groups.map((e,t)=>t)),c=s.reduce((e,t)=>e+t.channels.length,0);if(!t.selection&&t.chooseChannels&&(t.pickChannels||o.pick||c>2e3)){let e=await t.chooseChannels({file:n.name,format:o.format,groups:o.groups.map(e=>({name:e.name,rateHz:e.rateHz,samples:e.samples,channels:e.channels.map(e=>({name:e.name,unit:e.unit}))})),selection:s,estimate:e=>dz(o,e,n.size),budget:yR,used:t.priorInMemoryValues,notes:o.notes});if(!e)throw new UE(`cancelled`);s=e.filter(e=>e.channels.length>0)}if(s.length===0)throw Error(`${n.name}: no channels to read.`);let l=!t.split&&(s.length===1||s.every(e=>o.groups[e.group].time.kind!==`index`))?[s]:s.map(e=>[e]),u=l.length>1?crypto.randomUUID():null,d=t.priorInMemoryValues;for(let s of l){let c=dz(o,s,n.size),f=l.length>1?`${n.name} · ${o.groups[s[0].group].name}`:n.name,p=Oz(o,e.format,s,u),m=crypto.randomUUID();if(xR(0,c,d)===`memory`){let e=await i.read(s,`memory`,{progress:t.onProgress});a.push(await kz(m,f,e,n,r,p)),d+=c}else a.push(await Az(m,f,i,o,s,n,r,p,t.onProgress))}return a}catch(e){for(let e of a)e.source.dispose().catch(()=>void 0);throw t.signal?.aborted?new UE(`cancelled`):e}finally{i.close()}}function Mz(e){return e.filter(e=>e.type===`number`).map(e=>e.name)}function Nz(e,t,n=5e5){let r=1/0,i=-1/0,a=Math.max(1,Math.ceil(e.length/n));for(let n=0;n<e.length;n+=a){let a=e[n][t];typeof a==`number`&&(a<r&&(r=a),a>i&&(i=a))}if(!Number.isFinite(r)||!Number.isFinite(i))return{min:0,max:1};if(r===i){let e=Math.abs(r)*.05||1;return{min:r-e,max:i+e}}let o=(i-r)*.04;return{min:r-o,max:i+o}}function Pz(e){switch(e.kind){case`multiband`:return e.series.length;case`parallelcoords`:return e.pcColumns.length;case`barchart`:return e.bcValueCols.length;case`radar`:return e.rdAxesCols.length;case`areachart`:return e.acYCols.length;case`cdfchart`:return e.cdValueCols.length;case`losscurve`:return e.lcLeftCols.length+e.lcRightCols.length;case`gauge`:return e.ggGauges.length;case`camera`:return 0;case`heatmap`:return e.hmColumns.length;case`xyzmesh`:return e.xyzColumns?.length??0;default:return 0}}function Fz(e,t=6){if(!Number.isFinite(e)||e<=0)return 1;let n=e/t,r=10**Math.floor(Math.log10(n)),i=n/r,a=1;return a=i<=1?1:i<=2?2:i<=5?5:10,a*r}function Iz(e){return Math.max(2,Math.min(6,Math.floor(e/64)))}function Lz(e,t,n,r){let i=Math.max(e,t)-Math.min(e,t),a=n!==void 0&&n>0&&Number.isFinite(n)?n:Fz(i,6);(a<=0||!Number.isFinite(a))&&(a=Fz(Math.max(i,1),6));let o=r!==void 0&&r>0&&Number.isFinite(r)?r:a/5;return(o<=0||!Number.isFinite(o))&&(o=a/5),{majorStep:a,minorStep:o}}function Rz(e,t,n){let r=Math.min(e,t),i=Math.max(e,t);if(n<=0||!Number.isFinite(n))return[];let a=[],o=Math.ceil(r/n-1e-12)*n,s=0;for(;o<=i+n*1e-9&&s++<1e4;)a.push(o),o+=n;return a}function zz(e,t,n,r){let i=Math.min(e,t),a=Math.max(e,t);if(n<=0||!Number.isFinite(n))return[];let o=e=>r.some(t=>Math.abs(e-t)<=(Math.abs(t)+1)*1e-9+1e-9),s=[],c=Math.ceil(i/n-1e-12)*n,l=0;for(;c<=a+n*1e-9&&l++<2e4;)o(c)||s.push(c),c+=n;return s}var Bz={[-12]:`p`,[-9]:`n`,[-6]:`µ`,[-3]:`m`,0:``,3:`k`,6:`M`,9:`G`,12:`T`};function Vz(e){if(!(e>0)||!Number.isFinite(e))return 0;let t=Math.max(0,-Math.floor(Math.log10(e)+1e-9));for(let n=t;n<=t+2;n++){let t=e*10**n;if(Math.abs(t-Math.round(t))<=1e-6*t)return n}return t+1}function Hz(e,t){if(!Number.isFinite(e))return`—`;if(!(t>0)||!Number.isFinite(t))return Uz(e);if(Math.abs(e)<t*1e-6)return`0`;let n=Math.floor(Math.log10(t)+1e-9);if(n>=3||n<-3){let r=3*Math.ceil((n-1)/3);if(r<-12||r>12)return e.toExponential(2);let i=e/10**r;if(r>0||Math.abs(i)<1e3)return i.toFixed(Vz(t/10**r))+Bz[r]}return e.toFixed(Vz(t))}function Uz(e){if(!Number.isFinite(e))return`—`;if(e===0)return`0`;let t=Math.abs(e);if(t<1e-12||t>=0x38d7ea4c68000)return e.toExponential(3);let n=0;(t<.001||t>=1e6)&&(n=3*Math.floor(Math.log10(t)/3));let r=e/10**n,i=Math.max(0,3-Math.floor(Math.log10(Math.abs(r))));return n!==0&&Math.abs(+r.toFixed(i))>=1e3&&(n+=3,r/=1e3,i=3),r.toFixed(i)+Bz[n]}var Wz=946684800,Gz=4102444800;function Kz(e,t,n){return/\(([^)]*)\)\s*$/.exec(e)?.[1].trim()===`s`&&n>t&&t>=Wz&&n<=Gz}var qz=new Map;function Jz(e){let t=qz.get(e);if(!t){let n={day:`numeric`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hourCycle:`h23`};try{t=new Intl.DateTimeFormat(`en-GB`,{...n,timeZone:e})}catch{t=Jz(void 0)}qz.set(e,t)}return t}var Yz=new Map,Xz=(e,t)=>{let n=Math.round(e*1e3),r=Math.floor(n/1e3),i=`${t??``}|${r}`,a=Yz.get(i);if(!a){let e={};for(let{type:n,value:i}of Jz(t).formatToParts(r*1e3))e[n]=i;let n=`${e.hour}:${e.minute}`;a={date:`${e.day} ${e.month}`,year:e.year,hm:n,hms:`${n}:${e.second}`},Yz.size>=1024&&Yz.clear(),Yz.set(i,a)}return{...a,ms:String(n-r*1e3).padStart(3,`0`)}},Zz,Qz=new Set;function $z(e){if(e!==void 0)try{new Intl.DateTimeFormat(void 0,{timeZone:e})}catch{e=void 0}if(e!==Zz){Zz=e;for(let e of Qz)e()}}var eB=()=>Zz;function tB(e){return Qz.add(e),()=>{Qz.delete(e)}}function nB(e,t,n,r=Zz){let i=Xz(e,r);return t>=86400?i.date:n>86400?`${i.date} ${i.hm}`:t>=60?i.hm:t>=1?i.hms:`${i.hms}.${i.ms}`}function rB(e,t=Zz){let n=Xz(e,t);return`${n.date} ${n.year} ${n.hms}.${n.ms}`}var iB=[`#fb923c`,`#60a5fa`,`#4ade80`,`#f87171`,`#facc15`,`#22d3ee`,`#f472b6`,`#2dd4bf`,`#94a3b8`,`#a3e635`];function aB(e,t,n,r=iB){let i=r.length>0?r:iB;return e[t]??i[n%i.length]}function oB(e){return[e===`light`?`#000000`:`#ffffff`,...iB.slice(0,9)]}function sB(e,t=`dark`){let n=(e??[]).filter(e=>typeof e==`string`&&/^#[0-9a-f]{3}([0-9a-f]{3})?$/i.test(e));return n.length>0?n:oB(t)}var cB=[`class`,`data-theme`,`data-color-scheme`];function lB(e){return e?.closest(`[data-color-scheme]`)??document.documentElement}function uB(e){return lB(e).getAttribute(`data-color-scheme`)===`light`?`light`:`dark`}function dB(e,t){let n=new MutationObserver(t),r=new Set([document.documentElement,lB(e)]);for(let e of r)n.observe(e,{attributes:!0,attributeFilter:cB});return()=>n.disconnect()}function fB(e,t){return!!t&&e.composedPath().includes(t)}var pB=[`min`,`max`,`mean`,`integral`,`first`,`last`,`delta`],mB=e=>`${e.channel}:${e.stat}`;function hB(e,t,n){switch(e){case`>`:return t>n;case`>=`:return t>=n;case`<`:return t<n;case`<=`:return t<=n;case`==`:return t===n;default:return t!==n}}var gB=()=>({prev:NaN,lo:0,hi:0});function _B(e,t){if(e.prev!==e.prev)return e.prev=e.lo=e.hi=t,!1;let n=t<e.prev&&e.prev-t>(e.hi-e.lo)/2;return n?e.lo=e.hi=t:(t<e.lo&&(e.lo=t),t>e.hi&&(e.hi=t)),e.prev=t,n}var vB=new Map,yB=e=>{let t=vB.get(e);return t||(t=new Intl.DateTimeFormat(`en-US`,{timeZone:e,hourCycle:`h23`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}),vB.set(e,t)),t};function bB(e,t){let n={};for(let r of yB(t).formatToParts(new Date(Math.floor(e)*1e3)))n[r.type]=r.value;return(Date.UTC(+n.year,n.month-1,+n.day,+n.hour,+n.minute,+n.second)-Math.floor(e)*1e3)/1e3}function xB(e,t){let n=e+bB(e,t);return new Date(Math.floor(n)*1e3).toISOString().slice(0,10)}function SB(e,t,n){let[r,i,a]=e.split(`-`).map(Number),[o,s]=t.split(`:`).map(Number),c=Date.UTC(r,i-1,a,o,s)/1e3;return c-bB(c-bB(c,n),n)}var CB=(e,t)=>{let[n,r,i]=e.split(`-`).map(Number);return new Date(Date.UTC(n,r-1,i+t)).toISOString().slice(0,10)},wB=class{n=0;sum=0;min=1/0;max=-1/0;first=NaN;last=NaN;integral=0;lastT=NaN;add(e,t){t===t&&(this.n>0?this.integral+=(t+this.last)/2*(e-this.lastT):this.first=t,this.n++,this.sum+=t,t<this.min&&(this.min=t),t>this.max&&(this.max=t),this.last=t,this.lastT=e)}value(e){if(this.n===0)return null;switch(e){case`min`:return this.min;case`max`:return this.max;case`mean`:return this.sum/this.n;case`integral`:return this.integral;case`first`:return this.first;case`last`:return this.last;default:return this.last-this.first}}},TB=[{value:`span`,label:`Span (max − min)`},{value:`mean`,label:`Mean`},{value:`max`,label:`Max`},{value:`min`,label:`Min`}];function EB(e,t){let n=[],r=gB(),i=-1;for(let a=0;a<e.length;a++){let o=e[a][t];if(typeof o!=`number`)continue;let s=_B(r,o);i<0?i=0:s&&(n.push({start:i,end:a}),i=a)}return i>=0&&n.push({start:i,end:e.length}),n}function DB(e,t){let n=[],r=e.length-1,i=Math.max(1,Math.floor(e.length/256)),a=t=>{let n=0,r=0,a=0;for(let o=0;o+1<e.length;o+=i){let i=e[o][t],s=e[o+1][t];typeof i!=`number`||typeof s!=`number`||(n++,s<i?r++:s===i&&a++)}return n<32||r<=.3*n&&a<=.9*n};for(let o of t){if(i>1&&!a(o))continue;let t=0,s=0,c=0,l=null,u=!1;for(let n of e){let e=n[o];if(typeof e==`number`){if(l!==null&&(c++,e>l?t++:e===l&&s++,c-t-s>.1*r||s>.5*r)){u=!0;break}l=e}}if(u||c===0||(t+s)/c<.9||t/c<.5)continue;let d=EB(e,o).length;d>1&&n.push({col:o,laps:d})}return n.sort((e,t)=>t.laps-e.laps).map(e=>e.col)}function OB(e,t){return DB(e,t)[0]??t[0]??``}function kB(e,t,n){if(n&&t.includes(n.channel)&&EB(e,n.channel).length>1)return{...n,metric:t.includes(n.metric)?n.metric:n.channel};let r=DB(e,t);if(r.length===0)return null;let i=r.find(e=>/time/i.test(e));return{channel:r[0],metric:i??r[0],stat:`span`}}function AB(e,t,n,r){let i=0,a=0,o=1/0,s=-1/0;for(let r=t.start;r<t.end;r++){let t=e[r][n];typeof t==`number`&&(i++,a+=t,t<o&&(o=t),t>s&&(s=t))}return i===0?null:r===`mean`?a/i:r===`max`?s:r===`min`?o:s-o}function jB(e){let t=e.filter(e=>e!==null);if(t.length===0)return null;let n=[...t].sort((e,t)=>e-t)[Math.floor(t.length/2)],r=t.filter(e=>e>=n*.8),i=Math.min(...r.length>1?r:t);return e.indexOf(i)}function MB(e,t){return t.trim()===`s`||/time/i.test(e)}function NB(e,t,n){if(e===null)return`—`;if(n&&e>=0){let t=Math.round(e*1e3),n=Math.floor(t/6e4);return`${n}:${((t-n*6e4)/1e3).toFixed(3).padStart(6,`0`)}`}let r=Math.abs(e),i=r!==0&&r<.01?Uz(e):e.toFixed(r>=1e3?0:r>=100?1:3);return t.trim()?`${i} ${t.trim()}`:i}function PB(e,t){return`${e}::lap${t}`}function FB(e){let t=new Map,n=n=>{let r=t.get(n);return r||t.set(n,r=e.at.map(t=>SB(n,t,e.tz)).sort((e,t)=>e-t)),r},r=t=>{let r=xB(t,e.tz),i=-1/0;for(let e of n(r))e<=t&&(i=e);if(i>-1/0)return i;let a=n(CB(r,-1));return a[a.length-1]},i=t=>{let r=xB(t,e.tz);for(let e of n(r))if(e>t)return e;return n(CB(r,1))[0]},a=NaN,o=NaN,s={on:!1,edge:!1,at:NaN,event:!0,step(e){if(s.edge=s.on=!(e.t>=a&&e.t<o),!s.edge)return;let t=r(e.t);s.closeAt=o<=t?o:t,s.at=a=t,o=i(t)}};return s}function IB(e){switch(e.kind){case`compare`:{let t={on:!1,edge:!1,at:NaN,event:!1,step(n){let r=n.v(e.channel);r===r&&(t.on=hB(e.op,r,e.value)),t.at=n.t}};return t}case`elapsed`:{let t={on:!1,edge:!1,at:NaN,event:!1,step(n){let r=n.t-(e.from===`start`?n.start:n.ps);t.on=r===r&&(e.op===`>=`?r>=e.seconds:r<=e.seconds),t.at=n.t}};return t}case`change`:case`cross`:{let t=NaN,n={on:!1,edge:!1,at:NaN,event:!0,step(r){let i=r.v(e.channel);n.edge=!1,i===i&&(t===t&&(n.edge=e.kind===`change`?i!==t:e.dir===`rise`?t<e.value&&i>=e.value:t>e.value&&i<=e.value),t=i),n.on=n.edge,n.at=r.t}};return n}case`reset`:{let t=gB(),n={on:!1,edge:!1,at:NaN,event:!0,step(r){let i=r.v(e.channel);n.edge=i===i&&(t.prev===t.prev?_B(t,i):(_B(t,i),!0)),n.on=n.edge,n.at=r.t}};return n}case`clock`:return FB(e);case`parent-start`:{let e=!1,t={on:!1,edge:!1,at:NaN,event:!0,step(n){t.on=t.edge=!e,e=!0,t.at=n.ps}};return t}case`all`:case`any`:{let t=e.of.map(IB),n={on:!1,edge:!1,at:NaN,event:t.some(e=>e.event),step(r){for(let e of t)e.step(r);n.on=e.kind===`all`?t.every(e=>e.on):t.some(e=>e.on),n.edge=n.on&&t.some(e=>e.edge),n.at=r.t}};return n}default:return{on:!1,edge:!1,at:NaN,event:!0,step(){}}}}var LB=(e,t)=>e.kind===t||(e.kind===`all`||e.kind===`any`)&&e.of.some(e=>LB(e,t));function RB(e){let t=new Set,n=e=>{`channel`in e&&t.add(e.channel),(e.kind===`all`||e.kind===`any`)&&e.of.forEach(n)};return n(e.start),n(e.end),[...t]}var zB=class{rule;#e;#t;#n=NaN;#r=!1;#i=NaN;#a=NaN;#o=NaN;#s=NaN;#c;#l;constructor(e){this.rule=e,this.#c=LB(e.end,`parent-end`),this.#l=e.end.kind===`next-start`,this.#u()}#u(){this.#e=IB(this.rule.start),this.#t=IB(this.rule.end),this.#r=!1}#d(e,t,n){let r=this.rule.limits;if(!r)return[];let i=[],a=r.from===`start`?e:this.#n;return r.expectedWithin_s!=null&&t-a>r.expectedWithin_s&&i.push(`late`),r.max_s!=null&&t-e>r.max_s&&i.push(`too-long`),n&&r.min_s!=null&&t-e<r.min_s&&i.push(`too-short`),i}#f(e,t,n=!1){let r={tstart:this.#i,tend:e,flags:this.#d(this.#i,e,!0)};n&&(r.incomplete=!0),t.push(r),this.#i=this.#o=NaN}parentStart(e){this.#n=e,this.#i=this.#a=this.#o=NaN,this.#u()}parentEnd(e,t){this.#i===this.#i&&this.#f(e,t,!this.#c),this.#a=NaN,this.#n=NaN}step(e,t,n){this.#n!==this.#n&&(this.#n=e);let r={t:e,v:t,ps:this.#n,start:this.#i},i=this.#e,a=this.#t;i.step(r),a.step(r);let o=i.on&&(!this.#r||i.edge);this.#r=i.on;let s=i.event&&!(this.rule.start.kind===`all`||this.rule.start.kind===`any`)?i.at:e;if(this.#i===this.#i&&!this.#l&&e>this.#i){let t=this.rule.ignoreDips_s??0;a.on?t>0&&!a.event?(this.#o!==this.#o&&(this.#o=e),e-this.#o>=t&&this.#f(this.#o,n)):this.#f(e,n):this.#o=NaN}let c=e=>{this.#i===this.#i&&this.#f(this.#l&&i.closeAt!==void 0?i.closeAt:e,n),this.#i=e},l=this.#i!==this.#i||this.#l,u=this.rule.minHold_s??0;this.#a===this.#a?i.on?e-this.#a>=u&&(l&&c(this.#a),this.#a=NaN):this.#a=NaN:o&&l&&(u>0&&!i.event?this.#a=s:c(s)),this.#s=e}open(){return this.#i===this.#i?{tstart:this.#i,tend:null,flags:this.#d(this.#i,this.#s,!1)}:null}},BB=class{#e;constructor(e){let t=[],n=r=>{for(let i of e)i.parentId===r&&(t.push(i),n(i.id))};n(null),this.#e=t.map(e=>({...e,runner:new zB(e.rule),count:0,current:0,kids:[]})),this.#e.forEach((e,t)=>{e.parentId&&this.#e.find(t=>t.id===e.parentId).kids.push(t)})}#t(e,t,n,r){let i=this.#e[e];for(let e of t)n.push({...e,definitionId:i.id,index:i.current,...r?{parentIndex:r}:{}})}#n(e){let t=this.#e[e].parentId;return t?this.#e.find(e=>e.id===t).current:void 0}#r(e,t,n){for(let r of this.#e[e].kids){this.#r(r,t,n);let i=[];this.#e[r].runner.parentEnd(t,i),this.#t(r,i,n,this.#e[e].current)}}#i(e,t,n,r){let i=this.#e[e],a=i.runner.open()?.tstart,o=[];i.runner.step(t,n,o);let s=i.runner.open()?.tstart;if(o.length)for(let t of o)this.#r(e,t.tend,r),r.push({...t,definitionId:i.id,index:i.current,...this.#n(e)?{parentIndex:this.#n(e)}:{}});if(s!==void 0&&s!==a){i.current=++i.count;for(let e of i.kids)this.#e[e].current=this.#e[e].count=0,this.#e[e].runner.parentStart(s)}if(s!==void 0)for(let e of i.kids)this.#i(e,t,n,r)}feed(e,t){let n=new Map,r=e=>(n.has(e)||n.set(e,t(e)),n.get(e)),i=[],a=0,o=e=>{let t=r(e);return t?t[a]:NaN};for(;a<e.length;a++)for(let t=0;t<this.#e.length;t++)this.#e[t].parentId||this.#i(t,e[a],o,i);return i}open(){let e=[];return this.#e.forEach((t,n)=>{let r=t.runner.open(),i=this.#n(n);r&&(!t.parentId||this.#e.find(e=>e.id===t.parentId).runner.open())&&e.push({...r,definitionId:t.id,index:t.current,...i?{parentIndex:i}:{}})}),e}},VB=new Set([`>`,`>=`,`<`,`<=`,`==`,`!=`]),HB=e=>typeof e==`number`&&Number.isFinite(e),UB=e=>typeof e==`string`&&e.length>0;function WB(e,t){let n=e;if(!n||typeof n!=`object`)return!1;switch(n.kind){case`parent-start`:case`parent-end`:case`next-start`:case`manual`:return!0;case`all`:case`any`:return t<3&&Array.isArray(n.of)&&n.of.length>0&&n.of.every(e=>WB(e,t+1));case`compare`:return UB(n.channel)&&VB.has(n.op)&&HB(n.value);case`change`:case`reset`:return UB(n.channel);case`cross`:return UB(n.channel)&&(n.dir===`rise`||n.dir===`fall`)&&HB(n.value);case`elapsed`:return(n.from===`parent-start`||n.from===`start`)&&(n.op===`>=`||n.op===`<=`)&&HB(n.seconds);case`clock`:return Array.isArray(n.at)&&n.at.length>0&&n.at.every(e=>typeof e==`string`&&/^\d\d:\d\d$/.test(e))&&UB(n.tz);default:return!1}}function GB(e){if(!Array.isArray(e))return[];let t=e.filter(e=>{let t=e?.rule,n=t?.limits;return UB(e?.id)&&UB(e?.name)&&(e.parentId===null||UB(e.parentId))&&!!t&&WB(t.start,1)&&WB(t.end,1)&&(t.minHold_s===void 0||HB(t.minHold_s))&&(t.ignoreDips_s===void 0||HB(t.ignoreDips_s))&&(n===void 0||typeof n==`object`&&[`expectedWithin_s`,`min_s`,`max_s`].every(e=>n[e]===void 0||HB(n[e])))}),n=new Set(t.map(e=>e.id));return t.filter(e=>e.parentId===null||n.has(e.parentId)).map(e=>{let t=Array.isArray(e.kpis)?e.kpis.filter(e=>UB(e?.channel)&&pB.includes(e.stat)).slice(0,50):[],n=UB(e.show?.channel)&&pB.includes(e.show.stat)?{channel:e.show.channel,stat:e.show.stat}:void 0;return{id:e.id,name:e.name,parentId:e.parentId,rule:e.rule,...t.length?{kpis:t}:{},...n?{show:n}:{}}})}var KB=`Cycle time`,qB=65536;async function JB(e,t,n){let r=[...new Set([t,...n])],i=[];for(let n=0;;n+=qB){let a=await e.readColumns(r,n,qB),o=a[t]?.length??0;if(o>0&&i.push(a),o<qB)break}let a=e=>{if(!i.some(t=>t[e]))return;let n=new Float64Array(i.reduce((e,n)=>e+n[t].length,0)).fill(NaN),r=0;for(let a of i)a[e]&&n.set(a[e],r),r+=a[t].length;return n},o=new Map;for(let e of r){let n=e===t?void 0:a(e);n&&o.set(e,n)}return{t:a(t)??new Float64Array,cols:o}}function YB(e,t){let n=new BB(t);return[...n.feed(e.t,t=>e.cols.get(t)),...n.open()]}var XB=e=>[...new Set(e.flatMap(e=>[...RB(e.rule),...(e.kpis??[]).map(e=>e.channel)]))],ZB=e=>`${e.channel} ${e.stat}`;function QB(e,t,n){let r=$B(e.t,t.tstart),i=t.tend===null?e.t.length:$B(e.t,t.tend),a={};for(let t of n){let n=e.cols.get(t.channel),o=new wB;if(n)for(let t=r;t<i;t++)o.add(e.t[t],n[t]);a[ZB(t)]=o.value(t.stat)}return a}function $B(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 eV(e,t,n){let r=$B(e.t,n.tstart),i=n.tend===null?e.t.length:$B(e.t,n.tend),a=e.t.subarray(r,i),o={[KB]:a.map(e=>e-n.tstart),[t]:a};for(let[t,n]of e.cols)o[t]=n.subarray(r,i);return o}var tV=e=>e.replace(`-`,` `);function nV(e,t,n,r){let i=Object.fromEntries(n.map(e=>[e.id,e.name])),a=e=>n.find(t=>t.id===e)?.kpis??[],o=e=>r?QB(r,e,a(e.definitionId)):{},s=n.filter(e=>e.parentId===t).map(e=>e.id),c=e=>e.tend===null?null:e.tend-e.tstart,l=e.filter(e=>s.includes(e.definitionId)).sort((e,t)=>e.tstart-t.tstart);return{cycles:e.filter(e=>e.definitionId===t).sort((e,t)=>e.index-t.index).map(e=>{let t=l.filter(t=>t.parentIndex===e.index),n={Cycle:e.index,Start:e.tstart,End:e.tend,Duration:c(e)};for(let e of s){let r=t.filter(t=>t.definitionId===e);n[`${i[e]??e} duration`]=r.length&&r.every(e=>e.tend!==null)?r.reduce((e,t)=>e+t.tend-t.tstart,0):null}return Object.assign(n,o(e)),n.Flags=[...e.flags.map(tV),...t.flatMap(e=>e.flags.map(t=>`${i[e.definitionId]??e.definitionId} ${tV(t)}`))].join(`, `),n}),phases:l.map(e=>({Cycle:e.parentIndex,Phase:i[e.definitionId]??e.definitionId,Start:e.tstart,End:e.tend,Duration:c(e),...o(e),Flags:e.flags.map(tV).join(`, `)}))}}function rV(e){if(e.length===0)return``;let t=Object.keys(e[0]),n=e=>e===null?``:typeof e==`number`?String(e):/[",\n]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e;return[t.map(n).join(`,`),...e.map(e=>t.map(t=>n(e[t]??null)).join(`,`))].join(`
71
- `)}var iV=(e,t,n)=>`kymoscope-workbook-export|3|${e}|${t??``}|${n??``}`,aV=e=>new TextEncoder().encode(e);async function oV(e,t){return{format:`kymoscope-workbook`,v:2,...await re(t,aV(JSON.stringify(e)),B)}}async function sV(e,t){let n=t.password?JSON.stringify(await oV(e,t.password)):JSON.stringify(e),r=await be(await Re(t.key),aV(n),iV(t.scope,t.scopeId,t.password?`password`:void 0));return{format:`kymoscope-workbook`,v:3,scope:t.scope,scope_id:t.scopeId,alg:`AES-256-GCM`,...r,...t.password?{inner:`password`}:{}}}function cV(e){return!!e&&typeof e==`object`&&e.format===`kymoscope-workbook`}function lV(e){return cV(e)?e.v===2?{v:2,scope:null,scopeId:null,password:!0}:e.v!==3||e.alg!==`AES-256-GCM`||typeof e.iv!=`string`||typeof e.ct!=`string`||![`user`,`org`,`any`].includes(e.scope)||e.scope===`any`!=(e.scope_id===null)||e.scope_id!==null&&typeof e.scope_id!=`string`||e.inner!==void 0&&e.inner!==`password`?null:{v:3,scope:e.scope,scopeId:e.scope_id,password:e.inner===`password`}:null}var uV=e=>{try{return JSON.parse(new TextDecoder().decode(e))}catch{throw new UE(`bad_file`)}};async function dV(e,t){let n=lV(e);if(!n)throw new UE(`bad_file`);let r=e;if(n.v===3){let i=e;if(!t.key)throw new UE(`scope_key_required`,{scope:n.scope,scopeId:n.scopeId});let a;try{a=await ae(await Re(t.key),i,iV(i.scope,i.scope_id,i.inner))}catch{throw new UE(`bad_file`)}if(r=uV(a),!n.password)return r;if(r?.v!==2||!cV(r))throw new UE(`bad_file`)}if(!t.password)throw new UE(`password_required`);let i;try{i=await Ve(t.password,r,B)}catch{throw new UE(`wrong_password`)}return uV(i)}var fV=new Set(Object.keys(tn));function pV(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{id:t,kind:n,rect:r}=e;return typeof t!=`string`||!fV.has(n)||!r||![r.x,r.y,r.w,r.h].every(e=>typeof e==`number`&&Number.isFinite(e))?[]:[{...e,rect:an(n,r,96)}]}):[]}var mV=e=>({name:e.name,xKey:e.xKey,panels:e.panels,panelChartSettings:e.panelChartSettings,panelChartBackgrounds:e.panelChartBackgrounds,...e.liveWindowSeconds===void 0?{}:{liveWindowSeconds:e.liveWindowSeconds}});function hV(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>{let n=t.beacon;return[e,n?.datasetId?{...t,beacon:{...n,datasetId:null}}:t]}))}function gV(e){return{version:2,worksheets:e.worksheets.map(e=>({...mV(e),panelChartSettings:hV(e.panelChartSettings)})),activeWorksheet:Math.max(0,e.worksheets.findIndex(t=>t.id===e.activeWorksheetId)),mathChannels:e.channels.map(e=>({name:e.name,formula:e.formula,units:e.units,enabled:e.enabled,...e.description?{description:e.description}:{}})),liveWindowSeconds:e.liveWindowSeconds,laps:e.laps?{channel:e.laps.channel,metric:e.laps.metric,stat:e.laps.stat}:null,...e.cycles?.length?{cycles:e.cycles}:{}}}function _V(e){return{version:1,kind:`worksheet`,exportedAt:new Date().toISOString(),worksheet:{name:e.name,xKey:e.xKey,panels:e.panels,panelChartSettings:e.panelChartSettings,panelChartBackgrounds:e.panelChartBackgrounds,...e.liveWindowSeconds===void 0?{}:{liveWindowSeconds:e.liveWindowSeconds}}}}function vV(e,t,n){let r={kind:e.kind,settings:t,background:n},i=e.title?.trim();return i&&(r.title=i),{version:1,kind:`chart`,exportedAt:new Date().toISOString(),chart:r}}function yV(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)})}async function bV(e){let t=await yV(e),n;try{n=JSON.parse(t)}catch{return{worksheets:[],errors:[`Not a valid JSON file.`]}}return EV(n)}var xV=new Set(TB.map(e=>e.value)),SV=/^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(?:rgba?|hsla?)\([0-9.,%\s/deg+-]+\)|[a-z]{3,24})$/i;function CV(e){return typeof e!=`string`||e.length>64||/[;{}<>\\]|\b(?:var|env|attr|url)\(/i.test(e)?!1:typeof CSS<`u`&&typeof CSS.supports==`function`?CSS.supports(`color`,e):SV.test(e.trim())}function wV(e){if(Array.isArray(e))return e.map(wV);if(!e||typeof e!=`object`)return e??{};let t={};for(let[n,r]of Object.entries(e))/colou?r$/i.test(n)&&typeof r==`string`&&!CV(r)||(t[n]=r&&typeof r==`object`?wV(r):r);return t}function TV(e){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e===null||CV(e)))}function EV(e){let t=e,n=t&&typeof t==`object`?t.version:void 0;if(!t||n!==1&&n!==2||!Array.isArray(t.worksheets))return{worksheets:[],errors:[`Unrecognized format. Is this a Kymoscope workbook file?`],activeIndex:0,mathChannels:[],liveWindowSeconds:void 0,laps:void 0,cycles:[]};let r=[],i=[];if(t.worksheets.forEach((e,t)=>{let n=e;if(typeof n?.name!=`string`||typeof n.xKey!=`string`){i.push(`Worksheet #${t+1} skipped: missing name or xKey.`);return}r.push({id:crypto.randomUUID(),name:n.name,xKey:n.xKey,panels:pV(n.panels),panelChartSettings:wV(n.panelChartSettings),panelChartBackgrounds:TV(n.panelChartBackgrounds),..._r(n.liveWindowSeconds)})}),n===1)return{worksheets:r,errors:i,activeIndex:0,mathChannels:[],liveWindowSeconds:void 0,laps:void 0,cycles:[]};let a=(Array.isArray(t.mathChannels)?t.mathChannels:[]).flatMap(e=>{let t=e;return typeof t?.name!=`string`||!t.name.trim()||typeof t.formula!=`string`?[]:[{name:t.name,formula:t.formula,units:typeof t.units==`string`?t.units:``,enabled:t.enabled!==!1,...typeof t.description==`string`&&t.description?{description:t.description}:{}}]}),o=t.liveWindowSeconds,s=t.laps,c=s&&typeof s.channel==`string`&&typeof s.metric==`string`&&xV.has(s.stat)?{channel:s.channel,metric:s.metric,stat:s.stat}:null,l=typeof t.activeWorksheet==`number`&&Number.isInteger(t.activeWorksheet)?t.activeWorksheet:0;return{worksheets:r,errors:i,mathChannels:a,laps:c,cycles:GB(t.cycles),activeIndex:Math.min(Math.max(0,l),Math.max(0,r.length-1)),liveWindowSeconds:o===null||typeof o==`number`&&o>0?o:void 0}}function DV(e){return e.some(e=>e.panels.length>0)}function OV(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.name!=`string`||typeof t.xKey!=`string`?null:{id:crypto.randomUUID(),name:t.name,xKey:t.xKey,panels:pV(t.panels),panelChartSettings:wV(t.panelChartSettings),panelChartBackgrounds:TV(t.panelChartBackgrounds),..._r(t.liveWindowSeconds)}}function kV(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.kind;if(typeof n!=`string`||!fV.has(n))return null;let r=hr({__chart:t.settings},``,1).__chart;if(!r||r.kind!==n)return null;let i={kind:n,settings:r,background:t.background===null||typeof t.background==`string`&&/^#[0-9a-fA-F]{6}$/.test(t.background)?t.background:null};return typeof t.title==`string`&&t.title.trim()&&(i.title=t.title),i}async function AV(e){let t=await yV(e),n;try{n=JSON.parse(t)}catch{return{type:`error`,errors:[`Not a valid JSON file.`]}}if(!n||typeof n!=`object`)return{type:`error`,errors:[`Unrecognized file.`]};if(n.format===`kymoscope-workbook`){let e=lV(n);return e?{type:`encrypted`,...e}:{type:`error`,errors:[`This file is from a newer version of Kymoscope.`]}}let r=n.kind;if(r===`worksheet`){let e=OV(n.worksheet);return e?{type:`worksheet`,worksheet:e}:{type:`error`,errors:[`Worksheet file is missing a name or X key.`]}}if(r===`chart`){let e=kV(n.chart);return e?{type:`chart`,chart:e}:{type:`error`,errors:[`Chart file is malformed or its settings do not match its type.`]}}let i=await bV(e);return i.worksheets.length===0&&i.errors.length>0?{type:`error`,errors:i.errors}:{type:`workspace`,worksheets:i.worksheets,errors:i.errors}}var jV=zR;function MV(e){let t=e.toLowerCase();return!t.startsWith(`.`)&&jV.some(e=>t.endsWith(e))}function NV(e,t=``){let n={name:t,path:``,dirs:[],files:[],allPaths:[]};for(let t of e){if(!MV(t.file.name))continue;let e=t.path.split(`/`).filter(Boolean),r=n;for(let t of e.slice(0,-1)){let e=r.path?`${r.path}/${t}`:t,n=r.dirs.find(e=>e.name===t);n||(n={name:t,path:e,dirs:[],files:[],allPaths:[]},r.dirs.push(n)),r=n}r.files.push(t)}let r=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`}).compare,i=e=>(e.dirs.sort((e,t)=>r(e.name,t.name)),e.files.sort((e,t)=>r(e.file.name,t.file.name)),e.allPaths=[...e.dirs.flatMap(i),...e.files.map(e=>e.path)],e.allPaths);return i(n),!n.files.length&&n.dirs.length===1?n.dirs[0]:n}function PV(e){return e.map(e=>({path:e.webkitRelativePath||e.name,file:e}))}async function FV(e){let t=[],n=async(e,r)=>{let i=r?`${r}/${e.name}`:e.name;if(e.isFile){let n=await new Promise((t,n)=>e.file(t,n));t.push({path:i,file:n});return}if(!e.isDirectory)return;let a=e.createReader();for(;;){let e=await new Promise((e,t)=>a.readEntries(e,t));if(!e.length)break;for(let t of e)await n(t,i)}};for(let t of e)await n(t,``);return t}function IV(){return typeof window.showDirectoryPicker==`function`}async function LV(){let e;try{e=await window.showDirectoryPicker({mode:`read`})}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return null;throw e}let t=[],n=async(e,r)=>{for await(let i of e.values()){let e=`${r}/${i.name}`;i.kind===`file`?t.push({path:e,file:await i.getFile()}):await n(i,e)}};return await n(e,e.name),t}var RV={1:`dohstRIUBeOkkAXOTXhhEkXanWzz-V4M518JBqTehRM`};function zV(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`)+`===`.slice((e.length+3)%4),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function BV(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n.startsWith(`*.`)?r.endsWith(n.slice(1))&&r.length>n.length-1:n===r}function VV(e){try{let t=JSON.parse(new TextDecoder().decode(zV(e)));return typeof t.sub!=`string`||typeof t.exp!=`number`||!Array.isArray(t.domains)||!t.domains.every(e=>typeof e==`string`)||t.kid!==void 0&&typeof t.kid!=`string`?null:t}catch{return null}}async function HV(e,t,n,r){if(!e)return{ok:!1,reason:`missing`};if(typeof e!=`string`)return{ok:!1,reason:`malformed`};let i=e.trim().split(`.`);if(i.length!==2||!i[0]||!i[1])return{ok:!1,reason:`malformed`};let a=VV(i[0]);if(!a)return{ok:!1,reason:`malformed`};let o=a.kid??`1`,s=typeof n==`string`?n:Object.hasOwn(n,o)?n[o]:void 0;if(!s)return{ok:!1,reason:`bad_signature`};let c;try{let e=await crypto.subtle.importKey(`raw`,zV(s),`Ed25519`,!1,[`verify`]);c=await crypto.subtle.verify(`Ed25519`,e,zV(i[1]),new TextEncoder().encode(i[0]))}catch{return{ok:!1,reason:`unsupported`}}return c?a.exp<r?{ok:!1,reason:`expired`}:a.domains.some(e=>BV(e,t))?{ok:!0,sub:a.sub,exp:a.exp}:{ok:!1,reason:`domain`}:{ok:!1,reason:`bad_signature`}}function UV(e,t){return HV(e,t,RV,Date.now()/1e3)}var Q={sans:`system-ui, sans-serif`,mono:`ui-monospace, monospace`};function WV(e){let t=e.getTransform().a||1;e.font=`13px ${Q.sans}`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`No data to plot`,e.canvas.width/t/2,e.canvas.height/t/2)}function GV(){let e=new Set;return{publish(t,n){for(let r of e)r(t,n)},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}function KV(){return kt(`span`,{className:`kymoscope-attribution`,role:`note`,style:{position:`absolute`,right:10,bottom:8,zIndex:50,pointerEvents:`none`,font:`500 11px/1.2 var(--font-sans, system-ui)`,letterSpacing:`0.02em`,padding:`4px 8px`,borderRadius:999,color:`var(--text-muted, #8a93a6)`,background:`color-mix(in oklch, var(--bg-elevated, #1b2130) 88%, transparent)`,border:`1px solid var(--border, #33405a)`},children:[`Powered by `,q(`strong`,{style:{color:`var(--accent, #f5a524)`,fontWeight:700},children:`Kymoscope`})]})}function qV(){let e=new Map;return{on(t,n){let r=e.get(t);return r||e.set(t,r=new Set),r.add(n),()=>{r.delete(n)}},emit(t,n){for(let r of e.get(t)??[])try{r(n)}catch(e){console.error(`[kymoscope] listener failed`,e)}},clear(){e.clear()}}}function JV(e,t=1){let n=e.trim().replace(/^#/,``);n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]);let r=n.length===8?parseInt(n.slice(6),16)/255:1;n.length===8&&(n=n.slice(0,6));let i=parseInt(n,16);return n.length!==6||Number.isNaN(i)||Number.isNaN(r)?[0,0,0,t]:[(i>>16&255)/255,(i>>8&255)/255,(i&255)/255,r*t]}function YV(e){return Math.max(0,(e>>1)-1)}var XV=2.5,ZV=`#version 300 es
69
+ }`),e.length!==n.length&&(t=`if (x !== x) return false;\n${t}`),Function(`x`,`${t}\nreturn true;`)}function YP(e){return typeof e==`bigint`?`${kA(e)}n`:kA(e)}function XP(e,t){let n=Math.ceil(e)*t-1;return(n-n%64+64||64)/t}function ZP(e,t=0){return e.length>=t?e.subarray(0,t):fk(new e.constructor(t),e,0)}var QP=class{constructor(e,t=0,n=1){this.length=Math.ceil(t/n),this.buffer=new e(this.length),this.stride=n,this.BYTES_PER_ELEMENT=e.BYTES_PER_ELEMENT,this.ArrayType=e}get byteLength(){return Math.ceil(this.length*this.stride)*this.BYTES_PER_ELEMENT}get reservedLength(){return this.buffer.length/this.stride}get reservedByteLength(){return this.buffer.byteLength}set(e,t){return this}append(e){return this.set(this.length,e)}reserve(e){if(e>0){this.length+=e;let t=this.stride,n=this.length*t,r=this.buffer.length;n>=r&&this._resize(XP(r===0?n*1:n*2,this.BYTES_PER_ELEMENT))}return this}flush(e=this.length){e=XP(e*this.stride,this.BYTES_PER_ELEMENT);let t=ZP(this.buffer,e);return this.clear(),t}clear(){return this.length=0,this.buffer=new this.ArrayType,this}_resize(e){return this.buffer=ZP(this.buffer,e)}},$P=class extends QP{last(){return this.get(this.length-1)}get(e){return this.buffer[e]}set(e,t){return this.reserve(e-this.length+1),this.buffer[e*this.stride]=t,this}},eF=class extends $P{constructor(){super(Uint8Array,0,1/8),this.numValid=0}get numInvalid(){return this.length-this.numValid}get(e){return this.buffer[e>>3]>>e%8&1}set(e,t){let{buffer:n}=this.reserve(e-this.length+1),r=e>>3,i=e%8,a=n[r]>>i&1;return t?a===0&&(n[r]|=1<<i,++this.numValid):a===1&&(n[r]&=~(1<<i),--this.numValid),this}clear(){return this.numValid=0,super.clear()}},tF=class extends $P{constructor(e){super(e.OffsetArrayType,1,1)}append(e){return this.set(this.length-1,e)}set(e,t){let n=this.length-1,r=this.reserve(e-n+1).buffer;return n<e++&&n>=0&&r.fill(r[n],n,e),r[e]=r[e-1]+t,this}flush(e=this.length-1){return e>this.length&&this.set(e-1,this.BYTES_PER_ELEMENT>4?BigInt(0):0),super.flush(e+1)}},nF=class{static throughNode(e){throw Error(`"throughNode" not available in this environment`)}static throughDOM(e){throw Error(`"throughDOM" not available in this environment`)}constructor({type:e,nullValues:t}){this.length=0,this.finished=!1,this.type=e,this.children=[],this.nullValues=t,this.stride=Kj(e),this._nulls=new eF,t&&t.length>0&&(this._isValid=JP(t))}toVector(){return new WP([this.flush()])}get ArrayType(){return this.type.ArrayType}get nullCount(){return this._nulls.numInvalid}get numChildren(){return this.children.length}get byteLength(){let e=0,{_offsets:t,_values:n,_nulls:r,_typeIds:i,children:a}=this;return t&&(e+=t.byteLength),n&&(e+=n.byteLength),r&&(e+=r.byteLength),i&&(e+=i.byteLength),a.reduce((e,t)=>e+t.byteLength,e)}get reservedLength(){return this._nulls.reservedLength}get reservedByteLength(){let e=0;return this._offsets&&(e+=this._offsets.reservedByteLength),this._values&&(e+=this._values.reservedByteLength),this._nulls&&(e+=this._nulls.reservedByteLength),this._typeIds&&(e+=this._typeIds.reservedByteLength),this.children.reduce((e,t)=>e+t.reservedByteLength,e)}get valueOffsets(){return this._offsets?this._offsets.buffer:null}get values(){return this._values?this._values.buffer:null}get nullBitmap(){return this._nulls?this._nulls.buffer:null}get typeIds(){return this._typeIds?this._typeIds.buffer:null}append(e){return this.set(this.length,e)}isValid(e){return this._isValid(e)}set(e,t){return this.setValid(e,this.isValid(t))&&this.setValue(e,t),this}setValue(e,t){this._setValue(this,e,t)}setValid(e,t){return this.length=this._nulls.set(e,+t).length,t}addChild(e,t=`${this.numChildren}`){throw Error(`Cannot append children to non-nested type "${this.type}"`)}getChildAt(e){return this.children[e]||null}flush(){let e,t,n,r,{type:i,length:a,nullCount:o,_typeIds:s,_offsets:c,_values:l,_nulls:u}=this;(t=s?.flush(a))?r=c?.flush(a):e=(r=c?.flush(a))?l?.flush(c.last()):l?.flush(a),o>0&&(n=u?.flush(a));let d=this.children.map(e=>e.flush());return this.clear(),bP({type:i,length:a,nullCount:o,children:d,child:d[0],data:e,typeIds:t,nullBitmap:n,valueOffsets:r})}finish(){this.finished=!0;for(let e of this.children)e.finish();return this}clear(){var e,t,n,r;this.length=0,(e=this._nulls)==null||e.clear(),(t=this._values)==null||t.clear(),(n=this._offsets)==null||n.clear(),(r=this._typeIds)==null||r.clear();for(let e of this.children)e.clear();return this}};nF.prototype.length=1,nF.prototype.stride=1,nF.prototype.children=null,nF.prototype.finished=!1,nF.prototype.nullValues=null,nF.prototype._isValid=()=>!0;var rF=class extends nF{constructor(e){super(e),this._values=new $P(this.ArrayType,0,this.stride)}setValue(e,t){let n=this._values;return n.reserve(e-n.length+1),super.setValue(e,t)}},iF=class extends nF{constructor(e){super(e),this._pendingLength=0,this._offsets=new tF(e.type)}setValue(e,t){let n=this._pending||=new Map,r=n.get(e);r&&(this._pendingLength-=r.length),this._pendingLength+=t instanceof JN?t[WN].length:t.length,n.set(e,t)}setValid(e,t){return super.setValid(e,t)?!0:((this._pending||=new Map).set(e,void 0),!1)}clear(){return this._pendingLength=0,this._pending=void 0,super.clear()}flush(){return this._flush(),super.flush()}finish(){return this._flush(),super.finish()}_flush(){let e=this._pending,t=this._pendingLength;return this._pendingLength=0,this._pending=void 0,e&&e.size>0&&this._flushPending(e,t),this}},aF=class{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}offset(){return this.bb.readInt64(this.bb_pos)}metaDataLength(){return this.bb.readInt32(this.bb_pos+8)}bodyLength(){return this.bb.readInt64(this.bb_pos+16)}static sizeOf(){return 24}static createBlock(e,t,n,r){return e.prep(8,24),e.writeInt64(BigInt(r??0)),e.pad(4),e.writeInt32(n),e.writeInt64(BigInt(t??0)),e.offset()}},oF=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFooter(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFooter(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}version(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Nk.V1}schema(e){let t=this.bb.__offset(this.bb_pos,6);return t?(e||new TA).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}dictionaries(e,t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new aF).__init(this.bb.__vector(this.bb_pos+n)+e*24,this.bb):null}dictionariesLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}recordBatches(e,t){let n=this.bb.__offset(this.bb_pos,10);return n?(t||new aF).__init(this.bb.__vector(this.bb_pos+n)+e*24,this.bb):null}recordBatchesLength(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){let n=this.bb.__offset(this.bb_pos,12);return n?(t||new rA).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+e*4),this.bb):null}customMetadataLength(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startFooter(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,Nk.V1)}static addSchema(e,t){e.addFieldOffset(1,t,0)}static addDictionaries(e,t){e.addFieldOffset(2,t,0)}static startDictionariesVector(e,t){e.startVector(24,t,8)}static addRecordBatches(e,t){e.addFieldOffset(3,t,0)}static startRecordBatchesVector(e,t){e.startVector(24,t,8)}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endFooter(e){return e.endObject()}static finishFooterBuffer(e,t){e.finish(t)}static finishSizePrefixedFooterBuffer(e,t){e.finish(t,void 0,!0)}},sF=class e{constructor(e=[],t,n,r=Nk.V5){this.fields=e||[],this.metadata=t||new Map,n||=uF(this.fields),this.dictionaries=n,this.metadataVersion=r}get[Symbol.toStringTag](){return`Schema`}get names(){return this.fields.map(e=>e.name)}toString(){return`Schema<{ ${this.fields.map((e,t)=>`${t}: ${e}`).join(`, `)} }>`}select(t){let n=new Set(t);return new e(this.fields.filter(e=>n.has(e.name)),this.metadata)}selectAt(t){return new e(t.map(e=>this.fields[e]).filter(Boolean),this.metadata)}assign(...t){let n=t[0]instanceof e?t[0]:Array.isArray(t[0])?new e(t[0]):new e(t),r=[...this.fields],i=lF(lF(new Map,this.metadata),n.metadata),a=n.fields.filter(e=>{let t=r.findIndex(t=>t.name===e.name);return~t?(r[t]=e.clone({metadata:lF(lF(new Map,r[t].metadata),e.metadata)}))&&!1:!0}),o=uF(a,new Map);return new e([...r,...a],i,new Map([...this.dictionaries,...o]))}};sF.prototype.fields=null,sF.prototype.metadata=null,sF.prototype.dictionaries=null;var cF=class e{static new(...t){let[n,r,i,a]=t;return t[0]&&typeof t[0]==`object`&&({name:n}=t[0],r===void 0&&(r=t[0].type),i===void 0&&(i=t[0].nullable),a===void 0&&(a=t[0].metadata)),new e(`${n}`,r,i,a)}constructor(e,t,n=!1,r){this.name=e,this.type=t,this.nullable=n,this.metadata=r||new Map}get typeId(){return this.type.typeId}get[Symbol.toStringTag](){return`Field`}toString(){return`${this.name}: ${this.type}`}clone(...t){let[n,r,i,a]=t;return!t[0]||typeof t[0]!=`object`?[n=this.name,r=this.type,i=this.nullable,a=this.metadata]=t:{name:n=this.name,type:r=this.type,nullable:i=this.nullable,metadata:a=this.metadata}=t[0],e.new(n,r,i,a)}};cF.prototype.type=null,cF.prototype.name=null,cF.prototype.nullable=null,cF.prototype.metadata=null;function lF(e,t){return new Map([...e||new Map,...t||new Map])}function uF(e,t=new Map){for(let n=-1,r=e.length;++n<r;){let r=e[n].type;if(dj.isDictionary(r)){if(!t.has(r.id))t.set(r.id,r.dictionary);else if(t.get(r.id)!==r.dictionary)throw Error(`Cannot create Schema containing two different dictionaries with the same Id`)}r.children&&r.children.length>0&&uF(r.children,t)}return t}var dF=Gk,fF=Wk,pF=class{static decode(e){e=new fF(_k(e));let t=oF.getRootAsFooter(e);return new mF(sF.decode(t.schema(),new Map,t.version()),t)}static encode(e){let t=new dF,n=sF.encode(t,e.schema);oF.startRecordBatchesVector(t,e.numRecordBatches);for(let n of[...e.recordBatches()].slice().reverse())hF.encode(t,n);let r=t.endVector();oF.startDictionariesVector(t,e.numDictionaries);for(let n of[...e.dictionaryBatches()].slice().reverse())hF.encode(t,n);let i=t.endVector();return oF.startFooter(t),oF.addSchema(t,n),oF.addVersion(t,Nk.V5),oF.addRecordBatches(t,r),oF.addDictionaries(t,i),oF.finishFooterBuffer(t,oF.endFooter(t)),t.asUint8Array()}get numRecordBatches(){return this._recordBatches.length}get numDictionaries(){return this._dictionaryBatches.length}constructor(e,t=Nk.V5,n,r){this.schema=e,this.version=t,n&&(this._recordBatches=n),r&&(this._dictionaryBatches=r)}*recordBatches(){for(let e,t=-1,n=this.numRecordBatches;++t<n;)(e=this.getRecordBatch(t))&&(yield e)}*dictionaryBatches(){for(let e,t=-1,n=this.numDictionaries;++t<n;)(e=this.getDictionaryBatch(t))&&(yield e)}getRecordBatch(e){return e>=0&&e<this.numRecordBatches&&this._recordBatches[e]||null}getDictionaryBatch(e){return e>=0&&e<this.numDictionaries&&this._dictionaryBatches[e]||null}},mF=class extends pF{get numRecordBatches(){return this._footer.recordBatchesLength()}get numDictionaries(){return this._footer.dictionariesLength()}constructor(e,t){super(e,t.version()),this._footer=t}getRecordBatch(e){if(e>=0&&e<this.numRecordBatches){let t=this._footer.recordBatches(e);if(t)return hF.decode(t)}return null}getDictionaryBatch(e){if(e>=0&&e<this.numDictionaries){let t=this._footer.dictionaries(e);if(t)return hF.decode(t)}return null}},hF=class e{static decode(t){return new e(t.metaDataLength(),t.bodyLength(),t.offset())}static encode(e,t){let{metaDataLength:n}=t,r=BigInt(t.offset),i=BigInt(t.bodyLength);return aF.createBlock(e,r,n,i)}constructor(e,t,n){this.metaDataLength=e,this.offset=AA(n),this.bodyLength=AA(t)}},gF=Object.freeze({done:!0,value:void 0}),_F=class{constructor(e){this._json=e}get schema(){return this._json.schema}get batches(){return this._json.batches||[]}get dictionaries(){return this._json.dictionaries||[]}},vF=class{tee(){return this._getDOMStream().tee()}pipe(e,t){return this._getNodeStream().pipe(e,t)}pipeTo(e,t){return this._getDOMStream().pipeTo(e,t)}pipeThrough(e,t){return this._getDOMStream().pipeThrough(e,t)}_getDOMStream(){return this._DOMStream||=this.toDOMStream()}_getNodeStream(){return this._nodeStream||=this.toNodeStream()}},yF=class extends vF{constructor(){super(),this._values=[],this.resolvers=[],this._closedPromise=new Promise(e=>this._closedPromiseResolve=e)}get closed(){return this._closedPromise}cancel(e){return LO(this,void 0,void 0,function*(){yield this.return(e)})}write(e){this._ensureOpen()&&(this.resolvers.length<=0?this._values.push(e):this.resolvers.shift().resolve({done:!1,value:e}))}abort(e){this._closedPromiseResolve&&(this.resolvers.length<=0?this._error={error:e}:this.resolvers.shift().reject({done:!0,value:e}))}close(){if(this._closedPromiseResolve){let{resolvers:e}=this;for(;e.length>0;)e.shift().resolve(gF);this._closedPromiseResolve(),this._closedPromiseResolve=void 0}}[Symbol.asyncIterator](){return this}toDOMStream(e){return Tk.toDOMStream(this._closedPromiseResolve||this._error?this:this._values,e)}toNodeStream(e){return Tk.toNodeStream(this._closedPromiseResolve||this._error?this:this._values,e)}throw(e){return LO(this,void 0,void 0,function*(){return yield this.abort(e),gF})}return(e){return LO(this,void 0,void 0,function*(){return yield this.close(),gF})}read(e){return LO(this,void 0,void 0,function*(){return(yield this.next(e,`read`)).value})}peek(e){return LO(this,void 0,void 0,function*(){return(yield this.next(e,`peek`)).value})}next(...e){return this._values.length>0?Promise.resolve({done:!1,value:this._values.shift()}):this._error?Promise.reject({done:!0,value:this._error.error}):this._closedPromiseResolve?new Promise((e,t)=>{this.resolvers.push({resolve:e,reject:t})}):Promise.resolve(gF)}_ensureOpen(){if(this._closedPromiseResolve)return!0;throw Error(`AsyncQueue is closed`)}},bF=class extends yF{write(e){if((e=_k(e)).byteLength>0)return super.write(e)}toString(e=!1){return e?WO(this.toUint8Array(!0)):this.toUint8Array(!1).then(WO)}toUint8Array(e=!1){return e?pk(this._values)[0]:LO(this,void 0,void 0,function*(){var e,t,n,r;let i=[],a=0;try{for(var o=!0,s=HO(this),c;c=yield s.next(),e=c.done,!e;o=!0){r=c.value,o=!1;let e=r;i.push(e),a+=e.byteLength}}catch(e){t={error:e}}finally{try{!o&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(t)throw t.error}}return pk(i,a)[0]})}},xF=class{constructor(e){e&&(this.source=new CF(Tk.fromIterable(e)))}[Symbol.iterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}},SF=class e{constructor(t){t instanceof e?this.source=t.source:t instanceof bF?this.source=new wF(Tk.fromAsyncIterable(t)):ck(t)?this.source=new wF(Tk.fromNodeStream(t)):ok(t)?this.source=new wF(Tk.fromDOMStream(t)):rk(t)?this.source=new wF(Tk.fromDOMStream(t.body)):QO(t)?this.source=new wF(Tk.fromIterable(t)):(ZO(t)||$O(t))&&(this.source=new wF(Tk.fromAsyncIterable(t)))}[Symbol.asyncIterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}get closed(){return this.source.closed}cancel(e){return this.source.cancel(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}},CF=class{constructor(e){this.source=e}cancel(e){this.return(e)}peek(e){return this.next(e,`peek`).value}read(e){return this.next(e,`read`).value}next(e,t=`read`){return this.source.next({cmd:t,size:e})}throw(e){return Object.create(this.source.throw&&this.source.throw(e)||gF)}return(e){return Object.create(this.source.return&&this.source.return(e)||gF)}},wF=class{constructor(e){this.source=e,this._closedPromise=new Promise(e=>this._closedPromiseResolve=e)}cancel(e){return LO(this,void 0,void 0,function*(){yield this.return(e)})}get closed(){return this._closedPromise}read(e){return LO(this,void 0,void 0,function*(){return(yield this.next(e,`read`)).value})}peek(e){return LO(this,void 0,void 0,function*(){return(yield this.next(e,`peek`)).value})}next(e){return LO(this,arguments,void 0,function*(e,t=`read`){return yield this.source.next({cmd:t,size:e})})}throw(e){return LO(this,void 0,void 0,function*(){let t=this.source.throw&&(yield this.source.throw(e))||gF;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}return(e){return LO(this,void 0,void 0,function*(){let t=this.source.return&&(yield this.source.return(e))||gF;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}},TF=class extends xF{constructor(e,t){super(),this.position=0,this.buffer=_k(e),this.size=t===void 0?this.buffer.byteLength:t}readInt32(e){let{buffer:t,byteOffset:n}=this.readAt(e,4);return new DataView(t,n).getInt32(0,!0)}seek(e){return this.position=Math.min(e,this.size),e<this.size}read(e){let{buffer:t,size:n,position:r}=this;return t&&r<n?(typeof e!=`number`&&(e=1/0),this.position=Math.min(n,r+Math.min(n-r,e)),t.subarray(r,this.position)):null}readAt(e,t){let n=this.buffer,r=Math.min(this.size,e+t);return n?n.subarray(e,r):new Uint8Array(t)}close(){this.buffer&&=null}throw(e){return this.close(),{done:!0,value:e}}return(e){return this.close(),{done:!0,value:e}}},EF=class extends SF{constructor(e,t){super(),this.position=0,this._handle=e,typeof t==`number`?this.size=t:this._pending=LO(this,void 0,void 0,function*(){this.size=(yield e.stat()).size,delete this._pending})}readInt32(e){return LO(this,void 0,void 0,function*(){let{buffer:t,byteOffset:n}=yield this.readAt(e,4);return new DataView(t,n).getInt32(0,!0)})}seek(e){return LO(this,void 0,void 0,function*(){return this._pending&&(yield this._pending),this.position=Math.min(e,this.size),e<this.size})}read(e){return LO(this,void 0,void 0,function*(){this._pending&&(yield this._pending);let{_handle:t,size:n,position:r}=this;if(t&&r<n){typeof e!=`number`&&(e=1/0);let i=r,a=0,o=0,s=Math.min(n,i+Math.min(n-i,e)),c=new Uint8Array(Math.max(0,(this.position=s)-i));for(;(i+=o)<s&&(a+=o)<c.byteLength;)({bytesRead:o}=yield t.read(c,a,c.byteLength-a,i));return c}return null})}readAt(e,t){return LO(this,void 0,void 0,function*(){this._pending&&(yield this._pending);let{_handle:n,size:r}=this;if(n&&e+t<r){let i=Math.min(r,e+t),a=new Uint8Array(i-e);return(yield n.read(a,0,t,e)).buffer}return new Uint8Array(t)})}close(){return LO(this,void 0,void 0,function*(){let e=this._handle;this._handle=null,e&&(yield e.close())})}throw(e){return LO(this,void 0,void 0,function*(){return yield this.close(),{done:!0,value:e}})}return(e){return LO(this,void 0,void 0,function*(){return yield this.close(),{done:!0,value:e}})}},DF=65536;function OF(e){return e<0&&(e=4294967295+e+1),`0x${e.toString(16)}`}var kF=8,AF=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8],jF=class{constructor(e){this.buffer=e}high(){return this.buffer[1]}low(){return this.buffer[0]}_times(e){let t=new Uint32Array([this.buffer[1]>>>16,this.buffer[1]&65535,this.buffer[0]>>>16,this.buffer[0]&65535]),n=new Uint32Array([e.buffer[1]>>>16,e.buffer[1]&65535,e.buffer[0]>>>16,e.buffer[0]&65535]),r=t[3]*n[3];this.buffer[0]=r&65535;let i=r>>>16;return r=t[2]*n[3],i+=r,r=t[3]*n[2]>>>0,i+=r,this.buffer[0]+=i<<16,this.buffer[1]=i>>>0<r?DF:0,this.buffer[1]+=i>>>16,this.buffer[1]+=t[1]*n[3]+t[2]*n[2]+t[3]*n[1],this.buffer[1]+=t[0]*n[3]+t[1]*n[2]+t[2]*n[1]+t[3]*n[0]<<16,this}_plus(e){let t=this.buffer[0]+e.buffer[0]>>>0;this.buffer[1]+=e.buffer[1],t<this.buffer[0]>>>0&&++this.buffer[1],this.buffer[0]=t}lessThan(e){return this.buffer[1]<e.buffer[1]||this.buffer[1]===e.buffer[1]&&this.buffer[0]<e.buffer[0]}equals(e){return this.buffer[1]===e.buffer[1]&&this.buffer[0]==e.buffer[0]}greaterThan(e){return e.lessThan(this)}hex(){return`${OF(this.buffer[1])} ${OF(this.buffer[0])}`}},MF=class e extends jF{times(e){return this._times(e),this}plus(e){return this._plus(e),this}static from(t,n=new Uint32Array(2)){return e.fromString(typeof t==`string`?t:t.toString(),n)}static fromNumber(t,n=new Uint32Array(2)){return e.fromString(t.toString(),n)}static fromString(t,n=new Uint32Array(2)){let r=t.length,i=new e(n);for(let n=0;n<r;){let a=kF<r-n?kF:r-n,o=new e(new Uint32Array([Number.parseInt(t.slice(n,n+a),10),0])),s=new e(new Uint32Array([AF[a],0]));i.times(s),i.plus(o),n+=a}return i}static convertArray(t){let n=new Uint32Array(t.length*2);for(let r=-1,i=t.length;++r<i;)e.from(t[r],new Uint32Array(n.buffer,n.byteOffset+2*r*4,2));return n}static multiply(t,n){return new e(new Uint32Array(t.buffer)).times(n)}static add(t,n){return new e(new Uint32Array(t.buffer)).plus(n)}},NF=class e extends jF{negate(){return this.buffer[0]=~this.buffer[0]+1,this.buffer[1]=~this.buffer[1],this.buffer[0]==0&&++this.buffer[1],this}times(e){return this._times(e),this}plus(e){return this._plus(e),this}lessThan(e){let t=this.buffer[1]<<0,n=e.buffer[1]<<0;return t<n||t===n&&this.buffer[0]<e.buffer[0]}static from(t,n=new Uint32Array(2)){return e.fromString(typeof t==`string`?t:t.toString(),n)}static fromNumber(t,n=new Uint32Array(2)){return e.fromString(t.toString(),n)}static fromString(t,n=new Uint32Array(2)){let r=t.startsWith(`-`),i=t.length,a=new e(n);for(let n=+!!r;n<i;){let r=kF<i-n?kF:i-n,o=new e(new Uint32Array([Number.parseInt(t.slice(n,n+r),10),0])),s=new e(new Uint32Array([AF[r],0]));a.times(s),a.plus(o),n+=r}return r?a.negate():a}static convertArray(t){let n=new Uint32Array(t.length*2);for(let r=-1,i=t.length;++r<i;)e.from(t[r],new Uint32Array(n.buffer,n.byteOffset+2*r*4,2));return n}static multiply(t,n){return new e(new Uint32Array(t.buffer)).times(n)}static add(t,n){return new e(new Uint32Array(t.buffer)).plus(n)}},PF=class e{constructor(e){this.buffer=e}high(){return new NF(new Uint32Array(this.buffer.buffer,this.buffer.byteOffset+8,2))}low(){return new NF(new Uint32Array(this.buffer.buffer,this.buffer.byteOffset,2))}negate(){return this.buffer[0]=~this.buffer[0]+1,this.buffer[1]=~this.buffer[1],this.buffer[2]=~this.buffer[2],this.buffer[3]=~this.buffer[3],this.buffer[0]==0&&++this.buffer[1],this.buffer[1]==0&&++this.buffer[2],this.buffer[2]==0&&++this.buffer[3],this}times(e){let t=new MF(new Uint32Array([this.buffer[3],0])),n=new MF(new Uint32Array([this.buffer[2],0])),r=new MF(new Uint32Array([this.buffer[1],0])),i=new MF(new Uint32Array([this.buffer[0],0])),a=new MF(new Uint32Array([e.buffer[3],0])),o=new MF(new Uint32Array([e.buffer[2],0])),s=new MF(new Uint32Array([e.buffer[1],0])),c=new MF(new Uint32Array([e.buffer[0],0])),l=MF.multiply(i,c);this.buffer[0]=l.low();let u=new MF(new Uint32Array([l.high(),0]));return l=MF.multiply(r,c),u.plus(l),l=MF.multiply(i,s),u.plus(l),this.buffer[1]=u.low(),this.buffer[3]=+!!u.lessThan(l),this.buffer[2]=u.high(),new MF(new Uint32Array(this.buffer.buffer,this.buffer.byteOffset+8,2)).plus(MF.multiply(n,c)).plus(MF.multiply(r,s)).plus(MF.multiply(i,o)),this.buffer[3]+=MF.multiply(t,c).plus(MF.multiply(n,s)).plus(MF.multiply(r,o)).plus(MF.multiply(i,a)).low(),this}plus(e){let t=new Uint32Array(4);return t[3]=this.buffer[3]+e.buffer[3]>>>0,t[2]=this.buffer[2]+e.buffer[2]>>>0,t[1]=this.buffer[1]+e.buffer[1]>>>0,t[0]=this.buffer[0]+e.buffer[0]>>>0,t[0]<this.buffer[0]>>>0&&++t[1],t[1]<this.buffer[1]>>>0&&++t[2],t[2]<this.buffer[2]>>>0&&++t[3],this.buffer[3]=t[3],this.buffer[2]=t[2],this.buffer[1]=t[1],this.buffer[0]=t[0],this}hex(){return`${OF(this.buffer[3])} ${OF(this.buffer[2])} ${OF(this.buffer[1])} ${OF(this.buffer[0])}`}static multiply(t,n){return new e(new Uint32Array(t.buffer)).times(n)}static add(t,n){return new e(new Uint32Array(t.buffer)).plus(n)}static from(t,n=new Uint32Array(4)){return e.fromString(typeof t==`string`?t:t.toString(),n)}static fromNumber(t,n=new Uint32Array(4)){return e.fromString(t.toString(),n)}static fromString(t,n=new Uint32Array(4)){let r=t.startsWith(`-`),i=t.length,a=new e(n);for(let n=+!!r;n<i;){let r=kF<i-n?kF:i-n,o=new e(new Uint32Array([Number.parseInt(t.slice(n,n+r),10),0,0,0])),s=new e(new Uint32Array([AF[r],0,0,0]));a.times(s),a.plus(o),n+=r}return r?a.negate():a}static convertArray(t){let n=new Uint32Array(t.length*4);for(let r=-1,i=t.length;++r<i;)e.from(t[r],new Uint32Array(n.buffer,n.byteOffset+16*r,4));return n}},FF=class extends qj{constructor(e,t,n,r,i=Nk.V5){super(),this.nodesIndex=-1,this.buffersIndex=-1,this.bytes=e,this.nodes=t,this.buffers=n,this.dictionaries=r,this.metadataVersion=i}visit(e){return super.visit(e instanceof cF?e.type:e)}visitNull(e,{length:t}=this.nextFieldNode()){return bP({type:e,length:t})}visitBool(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitInt(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitFloat(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitUtf8(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),data:this.readData(e)})}visitLargeUtf8(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),data:this.readData(e)})}visitBinary(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),data:this.readData(e)})}visitLargeBinary(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),data:this.readData(e)})}visitFixedSizeBinary(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitDate(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitTimestamp(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitTime(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitDecimal(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitList(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),child:this.visit(e.children[0])})}visitStruct(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),children:this.visitMany(e.children)})}visitUnion(e,{length:t,nullCount:n}=this.nextFieldNode()){return this.metadataVersion<Nk.V5&&this.readNullBitmap(e,n),e.mode===Pk.Sparse?this.visitSparseUnion(e,{length:t,nullCount:n}):this.visitDenseUnion(e,{length:t,nullCount:n})}visitDenseUnion(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,typeIds:this.readTypeIds(e),valueOffsets:this.readOffsets(e),children:this.visitMany(e.children)})}visitSparseUnion(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,typeIds:this.readTypeIds(e),children:this.visitMany(e.children)})}visitDictionary(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e.indices),dictionary:this.readDictionary(e)})}visitInterval(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitDuration(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),data:this.readData(e)})}visitFixedSizeList(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),child:this.visit(e.children[0])})}visitMap(e,{length:t,nullCount:n}=this.nextFieldNode()){return bP({type:e,length:t,nullCount:n,nullBitmap:this.readNullBitmap(e,n),valueOffsets:this.readOffsets(e),child:this.visit(e.children[0])})}nextFieldNode(){return this.nodes[++this.nodesIndex]}nextBufferRange(){return this.buffers[++this.buffersIndex]}readNullBitmap(e,t,n=this.nextBufferRange()){return t>0&&this.readData(e,n)||new Uint8Array}readOffsets(e,t){return this.readData(e,t)}readTypeIds(e,t){return this.readData(e,t)}readData(e,{length:t,offset:n}=this.nextBufferRange()){return this.bytes.subarray(n,n+t)}readDictionary(e){return this.dictionaries.get(e.id)}},IF=class extends FF{constructor(e,t,n,r,i){super(new Uint8Array,t,n,r,i),this.sources=e}readNullBitmap(e,t,{offset:n}=this.nextBufferRange()){return t<=0?new Uint8Array:pP(this.sources[n])}readOffsets(e,{offset:t}=this.nextBufferRange()){return mk(Uint8Array,mk(e.OffsetArrayType,this.sources[t]))}readTypeIds(e,{offset:t}=this.nextBufferRange()){return mk(Uint8Array,mk(e.ArrayType,this.sources[t]))}readData(e,{offset:t}=this.nextBufferRange()){let{sources:n}=this;return dj.isTimestamp(e)||(dj.isInt(e)||dj.isTime(e))&&e.bitWidth===64||dj.isDuration(e)||dj.isDate(e)&&e.unit===Ik.MILLISECOND?mk(Uint8Array,NF.convertArray(n[t])):dj.isDecimal(e)?mk(Uint8Array,PF.convertArray(n[t])):dj.isBinary(e)||dj.isLargeBinary(e)||dj.isFixedSizeBinary(e)?LF(n[t]):dj.isBool(e)?pP(n[t]):dj.isUtf8(e)||dj.isLargeUtf8(e)?KO(n[t].join(``)):mk(Uint8Array,mk(e.ArrayType,n[t].map(e=>+e)))}};function LF(e){let t=e.join(``),n=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e>>1]=Number.parseInt(t.slice(e,e+2),16);return n}var RF=class extends iF{constructor(e){super(e),this._values=new QP(Uint8Array)}get byteLength(){let e=this._pendingLength+this.length*4;return this._offsets&&(e+=this._offsets.byteLength),this._values&&(e+=this._values.byteLength),this._nulls&&(e+=this._nulls.byteLength),e}setValue(e,t){return super.setValue(e,_k(t))}_flushPending(e,t){let n=this._offsets,r=this._values.reserve(t).buffer,i=0;for(let[t,a]of e)if(a===void 0)n.set(t,0);else{let e=a.length;r.set(a,i),n.set(t,e),i+=e}}},zF=class extends iF{constructor(e){super(e),this._values=new QP(Uint8Array)}get byteLength(){let e=this._pendingLength+this.length*4;return this._offsets&&(e+=this._offsets.byteLength),this._values&&(e+=this._values.byteLength),this._nulls&&(e+=this._nulls.byteLength),e}setValue(e,t){return super.setValue(e,_k(t))}_flushPending(e,t){let n=this._offsets,r=this._values.reserve(t).buffer,i=0;for(let[t,a]of e)if(a===void 0)n.set(t,BigInt(0));else{let e=a.length;r.set(a,i),n.set(t,BigInt(e)),i+=e}}},BF=class extends nF{constructor(e){super(e),this._values=new eF}setValue(e,t){this._values.set(e,+t)}},VF=class extends rF{};VF.prototype._setValue=hM;var HF=class extends VF{};HF.prototype._setValue=uM;var UF=class extends VF{};UF.prototype._setValue=dM;var WF=class extends rF{};WF.prototype._setValue=EM;var GF=class extends nF{constructor({type:e,nullValues:t,dictionaryHashFunction:n}){super({type:new Gj(e.dictionary,e.indices,e.id,e.isOrdered)}),this._nulls=null,this._dictionaryOffset=0,this._keysToIndices=Object.create(null),this.indices=tL({type:this.type.indices,nullValues:t}),this.dictionary=tL({type:this.type.dictionary,nullValues:null}),typeof n==`function`&&(this.valueToKey=n)}get values(){return this.indices.values}get nullCount(){return this.indices.nullCount}get nullBitmap(){return this.indices.nullBitmap}get byteLength(){return this.indices.byteLength+this.dictionary.byteLength}get reservedLength(){return this.indices.reservedLength+this.dictionary.reservedLength}get reservedByteLength(){return this.indices.reservedByteLength+this.dictionary.reservedByteLength}isValid(e){return this.indices.isValid(e)}setValid(e,t){let n=this.indices;return t=n.setValid(e,t),this.length=n.length,t}setValue(e,t){let n=this._keysToIndices,r=this.valueToKey(t),i=n[r];return i===void 0&&(n[r]=i=this._dictionaryOffset+this.dictionary.append(t).length-1),this.indices.setValue(e,i)}flush(){let e=this.type,t=this._dictionary,n=this.dictionary.toVector(),r=this.indices.flush().clone(e);return r.dictionary=t?t.concat(n):n,this.finished||(this._dictionaryOffset+=n.length),this._dictionary=r.dictionary,this.clear(),r}finish(){return this.indices.finish(),this.dictionary.finish(),this._dictionaryOffset=0,this._keysToIndices=Object.create(null),super.finish()}clear(){return this.indices.clear(),this.dictionary.clear(),super.clear()}valueToKey(e){return typeof e==`string`?e:`${e}`}},KF=class extends rF{};KF.prototype._setValue=fM;var qF=class extends nF{setValue(e,t){let[n]=this.children,r=e*this.stride;for(let e=-1,i=t.length;++e<i;)n.set(r+e,t[e])}addChild(e,t=`0`){if(this.numChildren>0)throw Error(`FixedSizeListBuilder can only have one child.`);let n=this.children.push(e);return this.type=new Hj(this.type.listSize,new cF(t,e.type,!0)),n}},JF=class extends rF{setValue(e,t){this._values.set(e,t)}},YF=class extends JF{setValue(e,t){super.setValue(e,eM(t))}},XF=class extends JF{},ZF=class extends JF{},QF=class extends rF{};QF.prototype._setValue=RM;var $F=class extends QF{};$F.prototype._setValue=zM;var eI=class extends QF{};eI.prototype._setValue=BM;var tI=class extends rF{};tI.prototype._setValue=GM;var nI=class extends tI{};nI.prototype._setValue=VM;var rI=class extends tI{};rI.prototype._setValue=HM;var iI=class extends tI{};iI.prototype._setValue=UM;var aI=class extends tI{};aI.prototype._setValue=WM;var oI=class extends rF{setValue(e,t){this._values.set(e,t)}},sI=class extends oI{},cI=class extends oI{},lI=class extends oI{},uI=class extends oI{},dI=class extends oI{},fI=class extends oI{},pI=class extends oI{},mI=class extends oI{},hI=class extends iF{constructor(e){super(e),this._offsets=new tF(e.type)}addChild(e,t=`0`){if(this.numChildren>0)throw Error(`ListBuilder can only have one child.`);return this.children[this.numChildren]=e,this.type=new Rj(new cF(t,e.type,!0)),this.numChildren-1}_flushPending(e){let t=this._offsets,[n]=this.children;for(let[r,i]of e)if(i===void 0)t.set(r,0);else{let e=i,a=e.length,o=t.set(r,a).buffer[r];for(let t=-1;++t<a;)n.set(o+t,e[t])}}},gI=class extends iF{set(e,t){return super.set(e,t)}setValue(e,t){let n=t instanceof Map?t:new Map(Object.entries(t)),r=this._pending||=new Map,i=r.get(e);i&&(this._pendingLength-=i.size),this._pendingLength+=n.size,r.set(e,n)}addChild(e,t=`${this.numChildren}`){if(this.numChildren>0)throw Error(`ListBuilder can only have one child.`);return this.children[this.numChildren]=e,this.type=new Uj(new cF(t,e.type,!0),this.type.keysSorted),this.numChildren-1}_flushPending(e){let t=this._offsets,[n]=this.children;for(let[r,i]of e)if(i===void 0)t.set(r,0);else{let{[r]:e,[r+1]:a}=t.set(r,i.size).buffer;for(let t of i.entries())if(n.set(e,t),++e>=a)break}}},_I=class extends nF{setValue(e,t){}setValid(e,t){return this.length=Math.max(e+1,this.length),t}},vI=class extends nF{setValue(e,t){let{children:n,type:r}=this;switch(Array.isArray(t)||t.constructor){case!0:return r.children.forEach((r,i)=>n[i].set(e,t[i]));case Map:return r.children.forEach((r,i)=>n[i].set(e,t.get(r.name)));default:return r.children.forEach((r,i)=>n[i].set(e,t[r.name]))}}setValid(e,t){return super.setValid(e,t)||this.children.forEach(n=>n.setValid(e,t)),t}addChild(e,t=`${this.numChildren}`){let n=this.children.push(e);return this.type=new zj([...this.type.children,new cF(t,e.type,!0)]),n}},yI=class extends rF{};yI.prototype._setValue=bM;var bI=class extends yI{};bI.prototype._setValue=gM;var xI=class extends yI{};xI.prototype._setValue=_M;var SI=class extends yI{};SI.prototype._setValue=vM;var CI=class extends yI{};CI.prototype._setValue=yM;var wI=class extends rF{};wI.prototype._setValue=TM;var TI=class extends wI{};TI.prototype._setValue=xM;var EI=class extends wI{};EI.prototype._setValue=SM;var DI=class extends wI{};DI.prototype._setValue=CM;var OI=class extends wI{};OI.prototype._setValue=wM;var kI=class extends nF{constructor(e){super(e),this._typeIds=new $P(Int8Array,0,1),typeof e.valueToChildTypeId==`function`&&(this._valueToChildTypeId=e.valueToChildTypeId)}get typeIdToChildIndex(){return this.type.typeIdToChildIndex}append(e,t){return this.set(this.length,e,t)}set(e,t,n){return n===void 0&&(n=this._valueToChildTypeId(this,t,e)),this.setValue(e,t,n),this}setValue(e,t,n){this._typeIds.set(e,n);let r=this.type.typeIdToChildIndex[n];this.children[r]?.set(e,t)}addChild(e,t=`${this.children.length}`){let n=this.children.push(e),{type:{children:r,mode:i,typeIds:a}}=this,o=[...r,new cF(t,e.type)];return this.type=new Bj(i,[...a,n],o),n}_valueToChildTypeId(e,t,n){throw Error("Cannot map UnionBuilder value to child typeId. Pass the `childTypeId` as the second argument to unionBuilder.append(), or supply a `valueToChildTypeId` function as part of the UnionBuilder constructor options.")}},AI=class extends kI{},jI=class extends kI{constructor(e){super(e),this._offsets=new $P(Int32Array)}setValue(e,t,n){let r=this._typeIds.set(e,n).buffer[e],i=this.getChildAt(this.type.typeIdToChildIndex[r]),a=this._offsets.set(e,i.length).buffer[e];i?.set(a,t)}},MI=class extends iF{constructor(e){super(e),this._values=new QP(Uint8Array)}get byteLength(){let e=this._pendingLength+this.length*4;return this._offsets&&(e+=this._offsets.byteLength),this._values&&(e+=this._values.byteLength),this._nulls&&(e+=this._nulls.byteLength),e}setValue(e,t){return super.setValue(e,KO(t))}_flushPending(e,t){}};MI.prototype._flushPending=RF.prototype._flushPending;var NI=class extends iF{constructor(e){super(e),this._values=new QP(Uint8Array)}get byteLength(){let e=this._pendingLength+this.length*4;return this._offsets&&(e+=this._offsets.byteLength),this._values&&(e+=this._values.byteLength),this._nulls&&(e+=this._nulls.byteLength),e}setValue(e,t){return super.setValue(e,KO(t))}_flushPending(e,t){}};NI.prototype._flushPending=zF.prototype._flushPending;var PI=new class extends qj{visitNull(){return _I}visitBool(){return BF}visitInt(){return oI}visitInt8(){return sI}visitInt16(){return cI}visitInt32(){return lI}visitInt64(){return uI}visitUint8(){return dI}visitUint16(){return fI}visitUint32(){return pI}visitUint64(){return mI}visitFloat(){return JF}visitFloat16(){return YF}visitFloat32(){return XF}visitFloat64(){return ZF}visitUtf8(){return MI}visitLargeUtf8(){return NI}visitBinary(){return RF}visitLargeBinary(){return zF}visitFixedSizeBinary(){return KF}visitDate(){return VF}visitDateDay(){return HF}visitDateMillisecond(){return UF}visitTimestamp(){return yI}visitTimestampSecond(){return bI}visitTimestampMillisecond(){return xI}visitTimestampMicrosecond(){return SI}visitTimestampNanosecond(){return CI}visitTime(){return wI}visitTimeSecond(){return TI}visitTimeMillisecond(){return EI}visitTimeMicrosecond(){return DI}visitTimeNanosecond(){return OI}visitDecimal(){return WF}visitList(){return hI}visitStruct(){return vI}visitUnion(){return kI}visitDenseUnion(){return jI}visitSparseUnion(){return AI}visitDictionary(){return GF}visitInterval(){return QF}visitIntervalDayTime(){return $F}visitIntervalYearMonth(){return eI}visitDuration(){return tI}visitDurationSecond(){return nI}visitDurationMillisecond(){return rI}visitDurationMicrosecond(){return iI}visitDurationNanosecond(){return aI}visitFixedSizeList(){return qF}visitMap(){return gI}},FI=class extends qj{compareSchemas(e,t){return e===t||t instanceof e.constructor&&this.compareManyFields(e.fields,t.fields)}compareManyFields(e,t){return e===t||Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>this.compareFields(e,t[n]))}compareFields(e,t){return e===t||t instanceof e.constructor&&e.name===t.name&&e.nullable===t.nullable&&this.visit(e.type,t.type)}};function II(e,t){return t instanceof e.constructor}function LI(e,t){return e===t||II(e,t)}function RI(e,t){return e===t||II(e,t)&&e.bitWidth===t.bitWidth&&e.isSigned===t.isSigned}function zI(e,t){return e===t||II(e,t)&&e.precision===t.precision}function BI(e,t){return e===t||II(e,t)&&e.byteWidth===t.byteWidth}function VI(e,t){return e===t||II(e,t)&&e.unit===t.unit}function HI(e,t){return e===t||II(e,t)&&e.unit===t.unit&&e.timezone===t.timezone}function UI(e,t){return e===t||II(e,t)&&e.unit===t.unit&&e.bitWidth===t.bitWidth}function WI(e,t){return e===t||II(e,t)&&e.children.length===t.children.length&&QI.compareManyFields(e.children,t.children)}function GI(e,t){return e===t||II(e,t)&&e.children.length===t.children.length&&QI.compareManyFields(e.children,t.children)}function KI(e,t){return e===t||II(e,t)&&e.mode===t.mode&&e.typeIds.every((e,n)=>e===t.typeIds[n])&&QI.compareManyFields(e.children,t.children)}function qI(e,t){return e===t||II(e,t)&&e.id===t.id&&e.isOrdered===t.isOrdered&&QI.visit(e.indices,t.indices)&&QI.visit(e.dictionary,t.dictionary)}function JI(e,t){return e===t||II(e,t)&&e.unit===t.unit}function YI(e,t){return e===t||II(e,t)&&e.unit===t.unit}function XI(e,t){return e===t||II(e,t)&&e.listSize===t.listSize&&e.children.length===t.children.length&&QI.compareManyFields(e.children,t.children)}function ZI(e,t){return e===t||II(e,t)&&e.keysSorted===t.keysSorted&&e.children.length===t.children.length&&QI.compareManyFields(e.children,t.children)}FI.prototype.visitNull=LI,FI.prototype.visitBool=LI,FI.prototype.visitInt=RI,FI.prototype.visitInt8=RI,FI.prototype.visitInt16=RI,FI.prototype.visitInt32=RI,FI.prototype.visitInt64=RI,FI.prototype.visitUint8=RI,FI.prototype.visitUint16=RI,FI.prototype.visitUint32=RI,FI.prototype.visitUint64=RI,FI.prototype.visitFloat=zI,FI.prototype.visitFloat16=zI,FI.prototype.visitFloat32=zI,FI.prototype.visitFloat64=zI,FI.prototype.visitUtf8=LI,FI.prototype.visitLargeUtf8=LI,FI.prototype.visitBinary=LI,FI.prototype.visitLargeBinary=LI,FI.prototype.visitFixedSizeBinary=BI,FI.prototype.visitDate=VI,FI.prototype.visitDateDay=VI,FI.prototype.visitDateMillisecond=VI,FI.prototype.visitTimestamp=HI,FI.prototype.visitTimestampSecond=HI,FI.prototype.visitTimestampMillisecond=HI,FI.prototype.visitTimestampMicrosecond=HI,FI.prototype.visitTimestampNanosecond=HI,FI.prototype.visitTime=UI,FI.prototype.visitTimeSecond=UI,FI.prototype.visitTimeMillisecond=UI,FI.prototype.visitTimeMicrosecond=UI,FI.prototype.visitTimeNanosecond=UI,FI.prototype.visitDecimal=LI,FI.prototype.visitList=WI,FI.prototype.visitStruct=GI,FI.prototype.visitUnion=KI,FI.prototype.visitDenseUnion=KI,FI.prototype.visitSparseUnion=KI,FI.prototype.visitDictionary=qI,FI.prototype.visitInterval=JI,FI.prototype.visitIntervalDayTime=JI,FI.prototype.visitIntervalYearMonth=JI,FI.prototype.visitDuration=YI,FI.prototype.visitDurationSecond=YI,FI.prototype.visitDurationMillisecond=YI,FI.prototype.visitDurationMicrosecond=YI,FI.prototype.visitDurationNanosecond=YI,FI.prototype.visitFixedSizeList=XI,FI.prototype.visitMap=ZI;var QI=new FI;function $I(e,t){return QI.compareSchemas(e,t)}function eL(e,t){return QI.visit(e,t)}function tL(e){let t=e.type,n=new(PI.getVisitFn(t)())(e);if(t.children&&t.children.length>0){let r=e.children||[],i={nullValues:e.nullValues},a=Array.isArray(r)?((e,t)=>r[t]||i):(({name:e})=>r[e]||i);for(let[e,r]of t.children.entries()){let{type:t}=r,i=a(r,e);n.children.push(tL(Object.assign(Object.assign({},i),{type:t})))}}return n}function nL(e,t){if(e instanceof vP||e instanceof WP||e.type instanceof dj||ArrayBuffer.isView(e))return KP(e);let n=[...iL({type:t??rL(e),nullValues:[null]})(e)],r=n.length===1?n[0]:n.reduce((e,t)=>e.concat(t));return dj.isDictionary(r.type)?r.memoize():r}function rL(e){if(e.length===0)return new fj;let t=0,n=0,r=0,i=0,a=0,o=0,s=0,c=0;for(let l of e){if(l==null){++t;continue}switch(typeof l){case`bigint`:++o;continue;case`boolean`:++s;continue;case`number`:++i;continue;case`string`:++a;continue;case`object`:Array.isArray(l)?++n:Object.prototype.toString.call(l)===`[object Date]`?++c:++r;continue}throw TypeError(`Unable to infer Vector type from input values, explicit type declaration expected.`)}if(i+t===e.length)return new Tj;if(a+t===e.length)return new Gj(new Oj,new gj);if(o+t===e.length)return new _j;if(s+t===e.length)return new Aj;if(c+t===e.length)return new Fj;if(n+t===e.length){let t=e,n=rL(t[t.findIndex(e=>e!=null)]);if(t.every(e=>e==null||eL(n,rL(e))))return new Rj(new cF(``,n,!0))}else if(r+t===e.length){let t=new Map;for(let n of e)for(let e of Object.keys(n))!t.has(e)&&n[e]!=null&&t.set(e,new cF(e,rL([n[e]]),!0));return new zj([...t.values()])}throw TypeError(`Unable to infer Vector type from input values, explicit type declaration expected.`)}function iL(e){let{queueingStrategy:t=`count`}=e,{highWaterMark:n=t===`bytes`?2**14:1/0}=e,r=t===`bytes`?`byteLength`:`length`;return function*(t){let i=0,a=tL(e);for(let e of t)a.append(e)[r]>=n&&++i&&(yield a.toVector());(a.finish().length>0||i===0)&&(yield a.toVector())}}function aL(e,t){return oL(e,t.map(e=>e.data.concat()))}function oL(e,t){let n=[...e.fields],r=[],i={numBatches:t.reduce((e,t)=>Math.max(e,t.length),0)},a=0,o=0,s=-1,c=t.length,l,u=[];for(;i.numBatches-- >0;){for(o=1/0,s=-1;++s<c;)u[s]=l=t[s].shift(),o=Math.min(o,l?l.length:o);Number.isFinite(o)&&(u=sL(n,o,u,t,i),o>0&&(r[a++]=bP({type:new zj(n),length:o,nullCount:0,children:u.slice()})))}return[e=e.assign(n),r.map(t=>new dL(e,t))]}function sL(e,t,n,r,i){let a=(t+63&-64)>>3;for(let o=-1,s=r.length;++o<s;){let s=n[o],c=s?.length;if(c>=t)c===t?n[o]=s:(n[o]=s.slice(0,t),i.numBatches=Math.max(i.numBatches,r[o].unshift(s.slice(t,c-t))));else{let r=e[o];e[o]=r.clone({nullable:!0}),n[o]=s?._changeLengthAndBackfillNullBitmap(t)??bP({type:r.type,length:t,nullCount:t,nullBitmap:new Uint8Array(a)})}}return n}var cL,lL=class e{constructor(...t){if(t.length===0)return this.batches=[],this.schema=new sF([]),this._offsets=[0],this;let n,r;t[0]instanceof sF&&(n=t.shift()),t.at(-1)instanceof Uint32Array&&(r=t.pop());let i=t=>{if(t){if(t instanceof dL)return[t];if(t instanceof e)return t.batches;if(t instanceof vP){if(t.type instanceof zj)return[new dL(new sF(t.type.children),t)]}else if(Array.isArray(t))return t.flatMap(e=>i(e));else if(typeof t[Symbol.iterator]==`function`)return[...t].flatMap(e=>i(e));else if(typeof t==`object`){let e=Object.keys(t),r=e.map(e=>new WP([t[e]])),[,i]=aL(n??new sF(e.map((e,t)=>new cF(String(e),r[t].type,r[t].nullable))),r);return i.length===0?[new dL(t)]:i}}return[]},a=t.flatMap(e=>i(e));if(n=n??a[0]?.schema??new sF([]),!(n instanceof sF))throw TypeError(`Table constructor expects a [Schema, RecordBatch[]] pair.`);for(let e of a){if(!(e instanceof dL))throw TypeError(`Table constructor expects a [Schema, RecordBatch[]] pair.`);if(!$I(n,e.schema))throw TypeError(`Table and inner RecordBatch schemas must be equivalent.`)}this.schema=n,this.batches=a,this._offsets=r??wP(this.data)}get data(){return this.batches.map(({data:e})=>e)}get numCols(){return this.schema.fields.length}get numRows(){return this.data.reduce((e,t)=>e+t.length,0)}get nullCount(){return this._nullCount===-1&&(this._nullCount=CP(this.data)),this._nullCount}isValid(e){return!1}get(e){return null}at(e){return this.get($N(e,this.numRows))}set(e,t){}indexOf(e,t){return-1}[Symbol.iterator](){return this.batches.length>0?BP.visit(new WP(this.data)):[][Symbol.iterator]()}toArray(){return[...this]}toString(){return`[\n ${this.toArray().join(`,
70
+ `)}\n]`}concat(...t){let n=this.schema;return new e(n,this.data.concat(t.flatMap(({data:e})=>e)).map(e=>new dL(n,e)))}slice(t,n){let r=this.schema;return[t,n]=QN({length:this.numRows},t,n),new e(r,TP(this.data,this._offsets,t,n).map(e=>new dL(r,e)))}getChild(e){return this.getChildAt(this.schema.fields.findIndex(t=>t.name===e))}getChildAt(e){if(e>-1&&e<this.schema.fields.length){let t=this.data.map(t=>t.children[e]);if(t.length===0){let{type:n}=this.schema.fields[e],r=bP({type:n,length:0,nullCount:0});t.push(r._changeLengthAndBackfillNullBitmap(this.numRows))}return new WP(t)}return null}setChild(e,t){return this.setChildAt(this.schema.fields?.findIndex(t=>t.name===e),t)}setChildAt(t,n){let r=this.schema,i=[...this.batches];if(t>-1&&t<this.numCols){n||=new WP([bP({type:new fj,length:this.numRows})]);let e=r.fields.slice(),a=e[t].clone({type:n.type}),o=this.schema.fields.map((e,t)=>this.getChildAt(t));[e[t],o[t]]=[a,n],[r,i]=aL(r,o)}return new e(r,i)}select(e){let t=this.schema.fields.reduce((e,t,n)=>e.set(t.name,n),new Map);return this.selectAt(e.map(e=>t.get(e)).filter(e=>e>-1))}selectAt(t){return new e(this.schema.selectAt(t),this.batches.map(e=>e.selectAt(t)))}assign(t){let n=this.schema.fields,[r,i]=t.schema.fields.reduce((e,t,r)=>{let[i,a]=e,o=n.findIndex(e=>e.name===t.name);return~o?a[o]=r:i.push(r),e},[[],[]]);return new e(...aL(this.schema.assign(t.schema),[...n.map((e,t)=>[t,i[t]]).map(([e,n])=>n===void 0?this.getChildAt(e):t.getChildAt(n)),...r.map(e=>t.getChildAt(e))].filter(Boolean)))}};cL=Symbol.toStringTag,lL[cL]=(e=>(e.schema=null,e.batches=[],e._offsets=new Uint32Array([0]),e._nullCount=-1,e[Symbol.isConcatSpreadable]=!0,e.isValid=OP(DP),e.get=OP(UN.getVisitFn(Z.Struct)),e.set=kP(qM.getVisitFn(Z.Struct)),e.indexOf=AP(IP.getVisitFn(Z.Struct)),`Table`))(lL.prototype);var uL,dL=class e{constructor(...e){switch(e.length){case 2:if([this.schema]=e,!(this.schema instanceof sF)||([,this.data=bP({nullCount:0,type:new zj(this.schema.fields),children:this.schema.fields.map(e=>bP({type:e.type,nullCount:0}))})]=e,!(this.data instanceof vP)))throw TypeError(`RecordBatch constructor expects a [Schema, Data] pair.`);[this.schema,this.data]=fL(this.schema,this.data.children);break;case 1:{let[t]=e,{fields:n,children:r,length:i}=Object.keys(t).reduce((e,n,r)=>(e.children[r]=t[n],e.length=Math.max(e.length,t[n].length),e.fields[r]=cF.new({name:n,type:t[n].type,nullable:!0}),e),{length:0,fields:[],children:[]}),a=new sF(n),o=bP({type:new zj(n),length:i,children:r,nullCount:0});[this.schema,this.data]=fL(a,o.children,i);break}default:throw TypeError(`RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.`)}}get dictionaries(){return this._dictionaries||=pL(this.schema.fields,this.data.children)}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(e){return this.data.getValid(e)}get(e){return UN.visit(this.data,e)}at(e){return this.get($N(e,this.numRows))}set(e,t){return qM.visit(this.data,e,t)}indexOf(e,t){return IP.visit(this.data,e,t)}[Symbol.iterator](){return BP.visit(new WP([this.data]))}toArray(){return[...this]}concat(...e){return new lL(this.schema,[this,...e])}slice(t,n){let[r]=new WP([this.data]).slice(t,n).data;return new e(this.schema,r)}getChild(e){return this.getChildAt(this.schema.fields?.findIndex(t=>t.name===e))}getChildAt(e){return e>-1&&e<this.schema.fields.length?new WP([this.data.children[e]]):null}setChild(e,t){return this.setChildAt(this.schema.fields?.findIndex(t=>t.name===e),t)}setChildAt(t,n){let r=this.schema,i=this.data;if(t>-1&&t<this.numCols){n||=new WP([bP({type:new fj,length:this.numRows})]);let e=r.fields.slice(),a=i.children.slice(),o=e[t].clone({type:n.type});[e[t],a[t]]=[o,n.data[0]],r=new sF(e,new Map(this.schema.metadata)),i=bP({type:new zj(e),children:a})}return new e(r,i)}select(t){let n=this.schema.select(t),r=new zj(n.fields),i=[];for(let e of t){let t=this.schema.fields.findIndex(t=>t.name===e);~t&&(i[t]=this.data.children[t])}return new e(n,bP({type:r,length:this.numRows,children:i}))}selectAt(t){let n=this.schema.selectAt(t),r=t.map(e=>this.data.children[e]).filter(Boolean);return new e(n,bP({type:new zj(n.fields),length:this.numRows,children:r}))}};uL=Symbol.toStringTag,dL[uL]=(e=>(e._nullCount=-1,e[Symbol.isConcatSpreadable]=!0,`RecordBatch`))(dL.prototype);function fL(e,t,n=t.reduce((e,t)=>Math.max(e,t.length),0)){let r=[...e.fields],i=[...t],a=(n+63&-64)>>3;for(let[o,s]of e.fields.entries()){let e=t[o];(!e||e.length!==n)&&(r[o]=s.clone({nullable:!0}),i[o]=e?._changeLengthAndBackfillNullBitmap(n)??bP({type:s.type,length:n,nullCount:n,nullBitmap:new Uint8Array(a)}))}return[e.assign(r),bP({type:new zj(r),length:n,children:i})]}function pL(e,t,n=new Map){if((e?.length??0)>0&&e?.length===t?.length)for(let r=-1,i=e.length;++r<i;){let{type:i}=e[r],a=t[r];for(let e of[a,...a?.dictionary?.data||[]])pL(i.children,e?.children,n);if(dj.isDictionary(i)){let{id:e}=i;if(!n.has(e))a?.dictionary&&n.set(e,a.dictionary);else if(n.get(e)!==a.dictionary)throw Error(`Cannot create Schema containing two different dictionaries with the same Id`)}}return n}var mL=class extends dL{constructor(e){let t=e.fields.map(e=>bP({type:e.type})),n=bP({type:new zj(e.fields),nullCount:0,children:t});super(e,n)}},hL=class e{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMessage(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMessage(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}version(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Nk.V1}headerType(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb_pos+e):EA.NONE}header(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__union(e,this.bb_pos+t):null}bodyLength(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt64(this.bb_pos+e):BigInt(`0`)}customMetadata(e,t){let n=this.bb.__offset(this.bb_pos,12);return n?(t||new rA).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+e*4),this.bb):null}customMetadataLength(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startMessage(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,Nk.V1)}static addHeaderType(e,t){e.addFieldInt8(1,t,EA.NONE)}static addHeader(e,t){e.addFieldOffset(2,t,0)}static addBodyLength(e,t){e.addFieldInt64(3,t,BigInt(`0`))}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endMessage(e){return e.endObject()}static finishMessageBuffer(e,t){e.finish(t)}static finishSizePrefixedMessageBuffer(e,t){e.finish(t,void 0,!0)}static createMessage(t,n,r,i,a,o){return e.startMessage(t),e.addVersion(t,n),e.addHeaderType(t,r),e.addHeader(t,i),e.addBodyLength(t,a),e.addCustomMetadata(t,o),e.endMessage(t)}},gL=new class extends qj{visit(e,t){return e==null||t==null?void 0:super.visit(e,t)}visitNull(e,t){return _A.startNull(t),_A.endNull(t)}visitInt(e,t){return tA.startInt(t),tA.addBitWidth(t,e.bitWidth),tA.addIsSigned(t,e.isSigned),tA.endInt(t)}visitFloat(e,t){return dA.startFloatingPoint(t),dA.addPrecision(t,e.precision),dA.endFloatingPoint(t)}visitBinary(e,t){return iA.startBinary(t),iA.endBinary(t)}visitLargeBinary(e,t){return pA.startLargeBinary(t),pA.endLargeBinary(t)}visitBool(e,t){return aA.startBool(t),aA.endBool(t)}visitUtf8(e,t){return SA.startUtf8(t),SA.endUtf8(t)}visitLargeUtf8(e,t){return mA.startLargeUtf8(t),mA.endLargeUtf8(t)}visitDecimal(e,t){return sA.startDecimal(t),sA.addScale(t,e.scale),sA.addPrecision(t,e.precision),sA.addBitWidth(t,e.bitWidth),sA.endDecimal(t)}visitDate(e,t){return oA.startDate(t),oA.addUnit(t,e.unit),oA.endDate(t)}visitTime(e,t){return yA.startTime(t),yA.addUnit(t,e.unit),yA.addBitWidth(t,e.bitWidth),yA.endTime(t)}visitTimestamp(e,t){let n=e.timezone&&t.createString(e.timezone)||void 0;return bA.startTimestamp(t),bA.addUnit(t,e.unit),n!==void 0&&bA.addTimezone(t,n),bA.endTimestamp(t)}visitInterval(e,t){return fA.startInterval(t),fA.addUnit(t,e.unit),fA.endInterval(t)}visitDuration(e,t){return cA.startDuration(t),cA.addUnit(t,e.unit),cA.endDuration(t)}visitList(e,t){return hA.startList(t),hA.endList(t)}visitStruct(e,t){return vA.startStruct_(t),vA.endStruct_(t)}visitUnion(e,t){xA.startTypeIdsVector(t,e.typeIds.length);let n=xA.createTypeIdsVector(t,e.typeIds);return xA.startUnion(t),xA.addMode(t,e.mode),xA.addTypeIds(t,n),xA.endUnion(t)}visitDictionary(e,t){let n=this.visit(e.indices,t);return nA.startDictionaryEncoding(t),nA.addId(t,BigInt(e.id)),nA.addIsOrdered(t,e.isOrdered),n!==void 0&&nA.addIndexType(t,n),nA.endDictionaryEncoding(t)}visitFixedSizeBinary(e,t){return lA.startFixedSizeBinary(t),lA.addByteWidth(t,e.byteWidth),lA.endFixedSizeBinary(t)}visitFixedSizeList(e,t){return uA.startFixedSizeList(t),uA.addListSize(t,e.listSize),uA.endFixedSizeList(t)}visitMap(e,t){return gA.startMap(t),gA.addKeysSorted(t,e.keysSorted),gA.endMap(t)}};function _L(e,t=new Map){return new sF(bL(e,t),EL(e.metadata),t)}function vL(e){return new ML(e.count,SL(e.columns),CL(e.columns))}function yL(e){return new NL(vL(e.data),e.id,e.isDelta)}function bL(e,t){return(e.fields||[]).filter(Boolean).map(e=>cF.fromJSON(e,t))}function xL(e,t){return(e.children||[]).filter(Boolean).map(e=>cF.fromJSON(e,t))}function SL(e){return(e||[]).reduce((e,t)=>[...e,new FL(t.count,wL(t.VALIDITY)),...SL(t.children)],[])}function CL(e,t=[]){for(let n=-1,r=(e||[]).length;++n<r;){let r=e[n];r.VALIDITY&&t.push(new PL(t.length,r.VALIDITY.length)),r.TYPE_ID&&t.push(new PL(t.length,r.TYPE_ID.length)),r.OFFSET&&t.push(new PL(t.length,r.OFFSET.length)),r.DATA&&t.push(new PL(t.length,r.DATA.length)),t=CL(r.children,t)}return t}function wL(e){return(e||[]).reduce((e,t)=>e+ +(t===0),0)}function TL(e,t){let n,r,i,a,o,s;return!t||!(a=e.dictionary)?(o=OL(e,xL(e,t)),i=new cF(e.name,o,e.nullable,EL(e.metadata))):t.has(n=a.id)?(r=(r=a.indexType)?DL(r):new gj,s=new Gj(t.get(n),r,n,a.isOrdered),i=new cF(e.name,s,e.nullable,EL(e.metadata))):(r=(r=a.indexType)?DL(r):new gj,t.set(n,o=OL(e,xL(e,t))),s=new Gj(o,r,n,a.isOrdered),i=new cF(e.name,s,e.nullable,EL(e.metadata))),i||null}function EL(e=[]){return new Map(e.map(({key:e,value:t})=>[e,t]))}function DL(e){return new pj(e.isSigned,e.bitWidth)}function OL(e,t){let n=e.type.name;switch(n){case`NONE`:return new fj;case`null`:return new fj;case`binary`:return new Ej;case`largebinary`:return new Dj;case`utf8`:return new Oj;case`largeutf8`:return new kj;case`bool`:return new Aj;case`list`:return new Rj((t||[])[0]);case`struct`:return new zj(t||[]);case`struct_`:return new zj(t||[])}switch(n){case`int`:{let t=e.type;return new pj(t.isSigned,t.bitWidth)}case`floatingpoint`:{let t=e.type;return new Sj(Fk[t.precision])}case`decimal`:{let t=e.type;return new jj(t.scale,t.precision,t.bitWidth)}case`date`:{let t=e.type;return new Mj(Ik[t.unit])}case`time`:{let t=e.type;return new Nj(Lk[t.unit],t.bitWidth)}case`timestamp`:{let t=e.type;return new Pj(Lk[t.unit],t.timezone)}case`interval`:{let t=e.type;return new Ij(Rk[t.unit])}case`duration`:{let t=e.type;return new Lj(Lk[t.unit])}case`union`:{let n=e.type,[r,...i]=(n.mode+``).toLowerCase();return new Bj(Pk[r.toUpperCase()+i.join(``)],n.typeIds||[],t||[])}case`fixedsizebinary`:{let t=e.type;return new Vj(t.byteWidth)}case`fixedsizelist`:{let n=e.type;return new Hj(n.listSize,(t||[])[0])}case`map`:{let n=e.type;return new Uj((t||[])[0],n.keysSorted)}}throw Error(`Unrecognized type: "${n}"`)}var kL=Gk,AL=Wk,jL=class e{static fromJSON(t,n){let r=new e(0,Nk.V5,n);return r._createHeader=IL(t,n),r}static decode(t){t=new AL(_k(t));let n=hL.getRootAsMessage(t),r=n.bodyLength(),i=n.version(),a=n.headerType(),o=new e(r,i,a);return o._createHeader=LL(n,a),o}static encode(e){let t=new kL,n=-1;return e.isSchema()?n=sF.encode(t,e.header()):e.isRecordBatch()?n=ML.encode(t,e.header()):e.isDictionaryBatch()&&(n=NL.encode(t,e.header())),hL.startMessage(t),hL.addVersion(t,Nk.V5),hL.addHeader(t,n),hL.addHeaderType(t,e.headerType),hL.addBodyLength(t,BigInt(e.bodyLength)),hL.finishMessageBuffer(t,hL.endMessage(t)),t.asUint8Array()}static from(t,n=0){if(t instanceof sF)return new e(0,Nk.V5,EA.Schema,t);if(t instanceof ML)return new e(n,Nk.V5,EA.RecordBatch,t);if(t instanceof NL)return new e(n,Nk.V5,EA.DictionaryBatch,t);throw Error(`Unrecognized Message header: ${t}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===EA.Schema}isRecordBatch(){return this.headerType===EA.RecordBatch}isDictionaryBatch(){return this.headerType===EA.DictionaryBatch}constructor(e,t,n,r){this._version=t,this._headerType=n,this.body=new Uint8Array,r&&(this._createHeader=()=>r),this._bodyLength=AA(e)}},ML=class{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(e,t,n){this._nodes=t,this._buffers=n,this._length=AA(e)}},NL=class{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(e,t,n=!1){this._data=e,this._isDelta=n,this._id=AA(t)}},PL=class{constructor(e,t){this.offset=AA(e),this.length=AA(t)}},FL=class{constructor(e,t){this.length=AA(e),this.nullCount=AA(t)}};function IL(e,t){return(()=>{switch(t){case EA.Schema:return sF.fromJSON(e);case EA.RecordBatch:return ML.fromJSON(e);case EA.DictionaryBatch:return NL.fromJSON(e)}throw Error(`Unrecognized Message type: { name: ${EA[t]}, type: ${t} }`)})}function LL(e,t){return(()=>{switch(t){case EA.Schema:return sF.decode(e.header(new TA),new Map,e.version());case EA.RecordBatch:return ML.decode(e.header(new Zk),e.version());case EA.DictionaryBatch:return NL.decode(e.header(new Qk),e.version())}throw Error(`Unrecognized Message type: { name: ${EA[t]}, type: ${t} }`)})}cF.encode=QL,cF.decode=qL,cF.fromJSON=TL,sF.encode=ZL,sF.decode=RL,sF.fromJSON=_L,ML.encode=$L,ML.decode=zL,ML.fromJSON=vL,NL.encode=eR,NL.decode=BL,NL.fromJSON=yL,FL.encode=tR,FL.decode=HL,PL.encode=nR,PL.decode=VL;function RL(e,t=new Map,n=Nk.V5){return new sF(GL(e,t),JL(e),t,n)}function zL(e,t=Nk.V5){if(e.compression()!==null)throw Error(`Record batch compression not implemented`);return new ML(e.length(),UL(e),WL(e,t))}function BL(e,t=Nk.V5){return new NL(ML.decode(e.data(),t),e.id(),e.isDelta())}function VL(e){return new PL(e.offset(),e.length())}function HL(e){return new FL(e.length(),e.nullCount())}function UL(e){let t=[];for(let n,r=-1,i=-1,a=e.nodesLength();++r<a;)(n=e.nodes(r))&&(t[++i]=FL.decode(n));return t}function WL(e,t){let n=[];for(let r,i=-1,a=-1,o=e.buffersLength();++i<o;)(r=e.buffers(i))&&(t<Nk.V4&&(r.bb_pos+=8*(i+1)),n[++a]=PL.decode(r));return n}function GL(e,t){let n=[];for(let r,i=-1,a=-1,o=e.fieldsLength();++i<o;)(r=e.fields(i))&&(n[++a]=cF.decode(r,t));return n}function KL(e,t){let n=[];for(let r,i=-1,a=-1,o=e.childrenLength();++i<o;)(r=e.children(i))&&(n[++a]=cF.decode(r,t));return n}function qL(e,t){let n,r,i,a,o,s;return!t||!(s=e.dictionary())?(i=XL(e,KL(e,t)),r=new cF(e.name(),i,e.nullable(),JL(e))):t.has(n=AA(s.id()))?(a=(a=s.indexType())?YL(a):new gj,o=new Gj(t.get(n),a,n,s.isOrdered()),r=new cF(e.name(),o,e.nullable(),JL(e))):(a=(a=s.indexType())?YL(a):new gj,t.set(n,i=XL(e,KL(e,t))),o=new Gj(i,a,n,s.isOrdered()),r=new cF(e.name(),o,e.nullable(),JL(e))),r||null}function JL(e){let t=new Map;if(e)for(let n,r,i=-1,a=Math.trunc(e.customMetadataLength());++i<a;)(n=e.customMetadata(i))&&(r=n.key())!=null&&t.set(r,n.value());return t}function YL(e){return new pj(e.isSigned(),e.bitWidth())}function XL(e,t){let n=e.typeType();switch(n){case CA.NONE:return new fj;case CA.Null:return new fj;case CA.Binary:return new Ej;case CA.LargeBinary:return new Dj;case CA.Utf8:return new Oj;case CA.LargeUtf8:return new kj;case CA.Bool:return new Aj;case CA.List:return new Rj((t||[])[0]);case CA.Struct_:return new zj(t||[])}switch(n){case CA.Int:{let t=e.type(new tA);return new pj(t.isSigned(),t.bitWidth())}case CA.FloatingPoint:return new Sj(e.type(new dA).precision());case CA.Decimal:{let t=e.type(new sA);return new jj(t.scale(),t.precision(),t.bitWidth())}case CA.Date:return new Mj(e.type(new oA).unit());case CA.Time:{let t=e.type(new yA);return new Nj(t.unit(),t.bitWidth())}case CA.Timestamp:{let t=e.type(new bA);return new Pj(t.unit(),t.timezone())}case CA.Interval:return new Ij(e.type(new fA).unit());case CA.Duration:return new Lj(e.type(new cA).unit());case CA.Union:{let n=e.type(new xA);return new Bj(n.mode(),n.typeIdsArray()||[],t||[])}case CA.FixedSizeBinary:return new Vj(e.type(new lA).byteWidth());case CA.FixedSizeList:return new Hj(e.type(new uA).listSize(),(t||[])[0]);case CA.Map:{let n=e.type(new gA);return new Uj((t||[])[0],n.keysSorted())}}throw Error(`Unrecognized type: "${CA[n]}" (${n})`)}function ZL(e,t){let n=t.fields.map(t=>cF.encode(e,t));TA.startFieldsVector(e,n.length);let r=TA.createFieldsVector(e,n),i=t.metadata&&t.metadata.size>0?TA.createCustomMetadataVector(e,[...t.metadata].map(([t,n])=>{let r=e.createString(`${t}`),i=e.createString(`${n}`);return rA.startKeyValue(e),rA.addKey(e,r),rA.addValue(e,i),rA.endKeyValue(e)})):-1;return TA.startSchema(e),TA.addFields(e,r),TA.addEndianness(e,rR?$k.Little:$k.Big),i!==-1&&TA.addCustomMetadata(e,i),TA.endSchema(e)}function QL(e,t){let n=-1,r=-1,i=-1,a=t.type,o=t.typeId;dj.isDictionary(a)?(o=a.dictionary.typeId,i=gL.visit(a,e),r=gL.visit(a.dictionary,e)):r=gL.visit(a,e);let s=(a.children||[]).map(t=>cF.encode(e,t)),c=wA.createChildrenVector(e,s),l=t.metadata&&t.metadata.size>0?wA.createCustomMetadataVector(e,[...t.metadata].map(([t,n])=>{let r=e.createString(`${t}`),i=e.createString(`${n}`);return rA.startKeyValue(e),rA.addKey(e,r),rA.addValue(e,i),rA.endKeyValue(e)})):-1;return t.name&&(n=e.createString(t.name)),wA.startField(e),wA.addType(e,r),wA.addTypeType(e,o),wA.addChildren(e,c),wA.addNullable(e,!!t.nullable),n!==-1&&wA.addName(e,n),i!==-1&&wA.addDictionary(e,i),l!==-1&&wA.addCustomMetadata(e,l),wA.endField(e)}function $L(e,t){let n=t.nodes||[],r=t.buffers||[];Zk.startNodesVector(e,n.length);for(let t of n.slice().reverse())FL.encode(e,t);let i=e.endVector();Zk.startBuffersVector(e,r.length);for(let t of r.slice().reverse())PL.encode(e,t);let a=e.endVector();return Zk.startRecordBatch(e),Zk.addLength(e,BigInt(t.length)),Zk.addNodes(e,i),Zk.addBuffers(e,a),Zk.endRecordBatch(e)}function eR(e,t){let n=ML.encode(e,t.data);return Qk.startDictionaryBatch(e),Qk.addId(e,BigInt(t.id)),Qk.addIsDelta(e,t.isDelta),Qk.addData(e,n),Qk.endDictionaryBatch(e)}function tR(e,t){return Xk.createFieldNode(e,BigInt(t.length),BigInt(t.nullCount))}function nR(e,t){return Yk.createBuffer(e,BigInt(t.offset),BigInt(t.length))}var rR=(()=>{let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]===256})(),iR=e=>`Expected ${EA[e]} Message in stream, but was null or length 0.`,aR=e=>`Header pointer of flatbuffer-encoded ${EA[e]} Message is null or length 0.`,oR=(e,t)=>`Expected to read ${e} metadata bytes, but only read ${t}.`,sR=(e,t)=>`Expected to read ${e} bytes for message body, but only read ${t}.`,cR=class{constructor(e){this.source=e instanceof xF?e:new xF(e)}[Symbol.iterator](){return this}next(){let e;return(e=this.readMetadataLength()).done||e.value===-1&&(e=this.readMetadataLength()).done||(e=this.readMetadata(e.value)).done?gF:e}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw Error(iR(e));return t.value}readMessageBody(e){if(e<=0)return new Uint8Array;let t=_k(this.source.read(e));if(t.byteLength<e)throw Error(sR(e,t.byteLength));return t.byteOffset%8==0&&t.byteOffset+t.byteLength<=t.buffer.byteLength?t:t.slice()}readSchema(e=!1){let t=EA.Schema,n=this.readMessage(t)?.header();if(e&&!n)throw Error(aR(t));return n}readMetadataLength(){let e=this.source.read(4),t=(e&&new Wk(e))?.readInt32(0)||0;return{done:t===0,value:t}}readMetadata(e){let t=this.source.read(e);if(!t)return gF;if(t.byteLength<e)throw Error(oR(e,t.byteLength));return{done:!1,value:jL.decode(t)}}},lR=class{constructor(e,t){this.source=e instanceof SF?e:nk(e)?new EF(e,t):new SF(e)}[Symbol.asyncIterator](){return this}next(){return LO(this,void 0,void 0,function*(){let e;return(e=yield this.readMetadataLength()).done||e.value===-1&&(e=yield this.readMetadataLength()).done||(e=yield this.readMetadata(e.value)).done?gF:e})}throw(e){return LO(this,void 0,void 0,function*(){return yield this.source.throw(e)})}return(e){return LO(this,void 0,void 0,function*(){return yield this.source.return(e)})}readMessage(e){return LO(this,void 0,void 0,function*(){let t;if((t=yield this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw Error(iR(e));return t.value})}readMessageBody(e){return LO(this,void 0,void 0,function*(){if(e<=0)return new Uint8Array;let t=_k(yield this.source.read(e));if(t.byteLength<e)throw Error(sR(e,t.byteLength));return t.byteOffset%8==0&&t.byteOffset+t.byteLength<=t.buffer.byteLength?t:t.slice()})}readSchema(){return LO(this,arguments,void 0,function*(e=!1){let t=EA.Schema,n=(yield this.readMessage(t))?.header();if(e&&!n)throw Error(aR(t));return n})}readMetadataLength(){return LO(this,void 0,void 0,function*(){let e=yield this.source.read(4),t=(e&&new Wk(e))?.readInt32(0)||0;return{done:t===0,value:t}})}readMetadata(e){return LO(this,void 0,void 0,function*(){let t=yield this.source.read(e);if(!t)return gF;if(t.byteLength<e)throw Error(oR(e,t.byteLength));return{done:!1,value:jL.decode(t)}})}},uR=class extends cR{constructor(e){super(new Uint8Array),this._schema=!1,this._body=[],this._batchIndex=0,this._dictionaryIndex=0,this._json=e instanceof _F?e:new _F(e)}next(){let{_json:e}=this;if(!this._schema)return this._schema=!0,{done:!1,value:jL.fromJSON(e.schema,EA.Schema)};if(this._dictionaryIndex<e.dictionaries.length){let t=e.dictionaries[this._dictionaryIndex++];return this._body=t.data.columns,{done:!1,value:jL.fromJSON(t,EA.DictionaryBatch)}}if(this._batchIndex<e.batches.length){let t=e.batches[this._batchIndex++];return this._body=t.columns,{done:!1,value:jL.fromJSON(t,EA.RecordBatch)}}return this._body=[],gF}readMessageBody(e){return t(this._body);function t(e){return(e||[]).reduce((e,n)=>[...e,...n.VALIDITY&&[n.VALIDITY]||[],...n.TYPE_ID&&[n.TYPE_ID]||[],...n.OFFSET&&[n.OFFSET]||[],...n.DATA&&[n.DATA]||[],...t(n.children)],[])}}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw Error(iR(e));return t.value}readSchema(){let e=EA.Schema,t=this.readMessage(e),n=t?.header();if(!t||!n)throw Error(aR(e));return n}},dR=`ARROW1`,fR=new Uint8Array(6);for(let e=0;e<6;e+=1)fR[e]=dR.codePointAt(e);function pR(e,t=0){for(let n=-1,r=fR.length;++n<r;)if(fR[n]!==e[t+n])return!1;return!0}var mR=fR.length,hR=mR+4,gR=mR*2+4,_R=class e extends vF{constructor(e){super(),this._impl=e}get closed(){return this._impl.closed}get schema(){return this._impl.schema}get autoDestroy(){return this._impl.autoDestroy}get dictionaries(){return this._impl.dictionaries}get numDictionaries(){return this._impl.numDictionaries}get numRecordBatches(){return this._impl.numRecordBatches}get footer(){return this._impl.isFile()?this._impl.footer:null}isSync(){return this._impl.isSync()}isAsync(){return this._impl.isAsync()}isFile(){return this._impl.isFile()}isStream(){return this._impl.isStream()}next(){return this._impl.next()}throw(e){return this._impl.throw(e)}return(e){return this._impl.return(e)}cancel(){return this._impl.cancel()}reset(e){return this._impl.reset(e),this._DOMStream=void 0,this._nodeStream=void 0,this}open(e){let t=this._impl.open(e);return ZO(t)?t.then(()=>this):this}readRecordBatch(e){return this._impl.isFile()?this._impl.readRecordBatch(e):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return Tk.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return Tk.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(e){throw Error(`"throughNode" not available in this environment`)}static throughDOM(e,t){throw Error(`"throughDOM" not available in this environment`)}static from(t){return t instanceof e?t:ek(t)?jR(t):nk(t)?PR(t):ZO(t)?LO(this,void 0,void 0,function*(){return yield e.from(yield t)}):rk(t)||ok(t)||ck(t)||$O(t)?NR(new SF(t)):MR(new xF(t))}static readAll(t){return t instanceof e?t.isSync()?kR(t):AR(t):ek(t)||ArrayBuffer.isView(t)||QO(t)||tk(t)?kR(t):AR(t)}},vR=class extends _R{constructor(e){super(e),this._impl=e}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return BO(this,arguments,function*(){yield zO(yield*VO(HO(this[Symbol.iterator]())))})}},yR=class extends _R{constructor(e){super(e),this._impl=e}readAll(){return LO(this,void 0,void 0,function*(){var e,t,n,r;let i=[];try{for(var a=!0,o=HO(this),s;s=yield o.next(),e=s.done,!e;a=!0){r=s.value,a=!1;let e=r;i.push(e)}}catch(e){t={error:e}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return i})}[Symbol.iterator](){throw Error(`AsyncRecordBatchStreamReader is not Iterable`)}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}},bR=class extends vR{constructor(e){super(e),this._impl=e}},xR=class extends yR{constructor(e){super(e),this._impl=e}},SR=class{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(e=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=e}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(e){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=e,this.dictionaries=new Map,this}_loadRecordBatch(e,t){let n=this._loadVectors(e,t,this.schema.fields),r=bP({type:new zj(this.schema.fields),length:e.length,children:n});return new dL(this.schema,r)}_loadDictionaryBatch(e,t){let{id:n,isDelta:r}=e,{dictionaries:i,schema:a}=this,o=i.get(n),s=a.dictionaries.get(n),c=this._loadVectors(e.data,t,[s]);return(o&&r?o.concat(new WP(c)):new WP(c)).memoize()}_loadVectors(e,t,n){return new FF(t,e.nodes,e.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(n)}},CR=class extends SR{constructor(e,t){super(t),this._reader=ek(e)?new uR(this._handle=e):new cR(this._handle=e)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(e){return this.closed||(this.autoDestroy=OR(this,e),(this.schema||=this._reader.readSchema())||this.cancel()),this}throw(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(e):gF}return(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(e):gF}next(){if(this.closed)return gF;let e,{_reader:t}=this;for(;e=this._readNextMessageAndValidate();)if(e.isSchema())this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;let n=e.header(),r=t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(n,r)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;let n=e.header(),r=t.readMessageBody(e.bodyLength),i=this._loadDictionaryBatch(n,r);this.dictionaries.set(n.id,i)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new mL(this.schema)}):this.return()}_readNextMessageAndValidate(e){return this._reader.readMessage(e)}},wR=class extends SR{constructor(e,t){super(t),this._reader=new lR(this._handle=e)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return LO(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(e){return LO(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=OR(this,e),(this.schema||=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(e){return LO(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(e):gF})}return(e){return LO(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(e):gF})}next(){return LO(this,void 0,void 0,function*(){if(this.closed)return gF;let e,{_reader:t}=this;for(;e=yield this._readNextMessageAndValidate();)if(e.isSchema())yield this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;let n=e.header(),r=yield t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(n,r)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;let n=e.header(),r=yield t.readMessageBody(e.bodyLength),i=this._loadDictionaryBatch(n,r);this.dictionaries.set(n.id,i)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new mL(this.schema)}):yield this.return()})}_readNextMessageAndValidate(e){return LO(this,void 0,void 0,function*(){return yield this._reader.readMessage(e)})}},TR=class extends CR{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(e,t){super(e instanceof TF?e:new TF(e),t)}isSync(){return!0}isFile(){return!0}open(e){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(let e of this._footer.dictionaryBatches())e&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(e)}readRecordBatch(e){if(this.closed)return null;this._footer||this.open();let t=this._footer?.getRecordBatch(e);if(t&&this._handle.seek(t.offset)){let e=this._reader.readMessage(EA.RecordBatch);if(e?.isRecordBatch()){let t=e.header(),n=this._reader.readMessageBody(e.bodyLength);return this._loadRecordBatch(t,n)}}return null}_readDictionaryBatch(e){let t=this._footer?.getDictionaryBatch(e);if(t&&this._handle.seek(t.offset)){let e=this._reader.readMessage(EA.DictionaryBatch);if(e?.isDictionaryBatch()){let t=e.header(),n=this._reader.readMessageBody(e.bodyLength),r=this._loadDictionaryBatch(t,n);this.dictionaries.set(t.id,r)}}}_readFooter(){let{_handle:e}=this,t=e.size-hR,n=e.readInt32(t),r=e.readAt(t-n,n);return pF.decode(r)}_readNextMessageAndValidate(e){if(this._footer||this.open(),this._footer&&this._recordBatchIndex<this.numRecordBatches){let t=this._footer?.getRecordBatch(this._recordBatchIndex);if(t&&this._handle.seek(t.offset))return this._reader.readMessage(e)}return null}},ER=class extends wR{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(e,...t){let n=typeof t[0]==`number`?void 0:t.shift(),r=t[0]instanceof Map?t.shift():void 0;super(e instanceof EF?e:new EF(e,n),r)}isFile(){return!0}isAsync(){return!0}open(e){let t=Object.create(null,{open:{get:()=>super.open}});return LO(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(let e of this._footer.dictionaryBatches())e&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield t.open.call(this,e)})}readRecordBatch(e){return LO(this,void 0,void 0,function*(){if(this.closed)return null;this._footer||(yield this.open());let t=this._footer?.getRecordBatch(e);if(t&&(yield this._handle.seek(t.offset))){let e=yield this._reader.readMessage(EA.RecordBatch);if(e?.isRecordBatch()){let t=e.header(),n=yield this._reader.readMessageBody(e.bodyLength);return this._loadRecordBatch(t,n)}}return null})}_readDictionaryBatch(e){return LO(this,void 0,void 0,function*(){let t=this._footer?.getDictionaryBatch(e);if(t&&(yield this._handle.seek(t.offset))){let e=yield this._reader.readMessage(EA.DictionaryBatch);if(e?.isDictionaryBatch()){let t=e.header(),n=yield this._reader.readMessageBody(e.bodyLength),r=this._loadDictionaryBatch(t,n);this.dictionaries.set(t.id,r)}}})}_readFooter(){return LO(this,void 0,void 0,function*(){let{_handle:e}=this;e._pending&&(yield e._pending);let t=e.size-hR,n=yield e.readInt32(t),r=yield e.readAt(t-n,n);return pF.decode(r)})}_readNextMessageAndValidate(e){return LO(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex<this.numRecordBatches){let t=this._footer.getRecordBatch(this._recordBatchIndex);if(t&&(yield this._handle.seek(t.offset)))return yield this._reader.readMessage(e)}return null})}},DR=class extends CR{constructor(e,t){super(e,t)}_loadVectors(e,t,n){return new IF(t,e.nodes,e.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(n)}};function OR(e,t){return t&&typeof t.autoDestroy==`boolean`?t.autoDestroy:e.autoDestroy}function*kR(e){let t=_R.from(e);try{if(!t.open({autoDestroy:!1}).closed)do yield t;while(!t.reset().open().closed)}finally{t.cancel()}}function AR(e){return BO(this,arguments,function*(){let t=yield zO(_R.from(e));try{if(!(yield zO(t.open({autoDestroy:!1}))).closed)do yield yield zO(t);while(!(yield zO(t.reset().open())).closed)}finally{yield zO(t.cancel())}})}function jR(e){return new vR(new DR(e))}function MR(e){let t=e.peek(mR+7&-8);return t&&t.byteLength>=4?pR(t)?new bR(new TR(e.read())):new vR(new CR(e)):new vR(new CR(function*(){}()))}function NR(e){return LO(this,void 0,void 0,function*(){let t=yield e.peek(mR+7&-8);return t&&t.byteLength>=4?pR(t)?new bR(new TR(yield e.read())):new yR(new wR(e)):new yR(new wR(function(){return BO(this,arguments,function*(){})}()))})}function PR(e){return LO(this,void 0,void 0,function*(){let{size:t}=yield e.stat(),n=new EF(e,t);return t>=gR&&pR(yield n.readAt(0,mR+7&-8))?new xR(new ER(n)):new yR(new wR(n))})}var FR=class e extends qj{static assemble(...t){let n=e=>e.flatMap(e=>Array.isArray(e)?n(e):e instanceof dL?e.data.children:e.data),r=new e;return r.visitMany(n(t)),r}constructor(){super(),this._byteLength=0,this._nodes=[],this._buffers=[],this._bufferRegions=[]}visit(e){if(e instanceof WP)return this.visitMany(e.data),this;let{type:t}=e;if(!dj.isDictionary(t)){let{length:n}=e;if(n>2147483647)throw RangeError(`Cannot write arrays larger than 2^31 - 1 in length`);if(dj.isUnion(t))this.nodes.push(new FL(n,0));else{let{nullCount:r}=e;dj.isNull(t)||IR.call(this,r<=0?new Uint8Array:fP(e.offset,n,e.nullBitmap)),this.nodes.push(new FL(n,r))}}return super.visit(e)}visitNull(e){return this}visitDictionary(e){return this.visit(e.clone(e.type.indices))}get nodes(){return this._nodes}get buffers(){return this._buffers}get byteLength(){return this._byteLength}get bufferRegions(){return this._bufferRegions}};function IR(e){let t=e.byteLength+7&-8;return this.buffers.push(e),this.bufferRegions.push(new PL(this._byteLength,t)),this._byteLength+=t,this}function LR(e){let{type:t,length:n,typeIds:r,valueOffsets:i}=e;if(IR.call(this,r),t.mode===Pk.Sparse)return HR.call(this,e);if(t.mode===Pk.Dense){if(e.offset<=0)return IR.call(this,i),HR.call(this,e);{let a=new Int32Array(n),o=Object.create(null),s=Object.create(null);for(let e,t,c=-1;++c<n;)(e=r[c])!==void 0&&((t=o[e])===void 0&&(t=o[e]=i[c]),a[c]=i[c]-t,s[e]=(s[e]??0)+1);IR.call(this,a),this.visitMany(e.children.map((e,r)=>{let i=t.typeIds[r],a=o[i],c=s[i];return e.slice(a,Math.min(n,c))}))}}return this}function RR(e){let t;return e.nullCount>=e.length?IR.call(this,new Uint8Array):(t=e.values)instanceof Uint8Array?IR.call(this,fP(e.offset,e.length,t)):IR.call(this,pP(e.values))}function zR(e){return IR.call(this,e.values.subarray(0,e.length*e.stride))}function BR(e){let{length:t,values:n,valueOffsets:r}=e,i=AA(r[0]),a=AA(r[t]),o=Math.min(a-i,n.byteLength-i);return IR.call(this,Ck(-i,t+1,r)),IR.call(this,n.subarray(i,i+o)),this}function VR(e){let{length:t,valueOffsets:n}=e;if(n){let{0:r,[t]:i}=n;return IR.call(this,Ck(-r,t+1,n)),this.visit(e.children[0].slice(r,i-r))}return this.visit(e.children[0])}function HR(e){return this.visitMany(e.type.children.map((t,n)=>e.children[n]).filter(Boolean))[0]}FR.prototype.visitBool=RR,FR.prototype.visitInt=zR,FR.prototype.visitFloat=zR,FR.prototype.visitUtf8=BR,FR.prototype.visitLargeUtf8=BR,FR.prototype.visitBinary=BR,FR.prototype.visitLargeBinary=BR,FR.prototype.visitFixedSizeBinary=zR,FR.prototype.visitDate=zR,FR.prototype.visitTimestamp=zR,FR.prototype.visitTime=zR,FR.prototype.visitDecimal=zR,FR.prototype.visitList=VR,FR.prototype.visitStruct=HR,FR.prototype.visitUnion=LR,FR.prototype.visitInterval=zR,FR.prototype.visitDuration=zR,FR.prototype.visitFixedSizeList=VR,FR.prototype.visitMap=VR;var UR=class extends vF{static throughNode(e){throw Error(`"throughNode" not available in this environment`)}static throughDOM(e,t){throw Error(`"throughDOM" not available in this environment`)}constructor(e){super(),this._position=0,this._started=!1,this._sink=new bF,this._schema=null,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,XO(e)||(e={autoDestroy:!0,writeLegacyIpcFormat:!1}),this._autoDestroy=typeof e.autoDestroy==`boolean`?e.autoDestroy:!0,this._writeLegacyIpcFormat=typeof e.writeLegacyIpcFormat==`boolean`?e.writeLegacyIpcFormat:!1}toString(e=!1){return this._sink.toString(e)}toUint8Array(e=!1){return this._sink.toUint8Array(e)}writeAll(e){return ZO(e)?e.then(e=>this.writeAll(e)):$O(e)?qR(this,e):KR(this,e)}get closed(){return this._sink.closed}[Symbol.asyncIterator](){return this._sink[Symbol.asyncIterator]()}toDOMStream(e){return this._sink.toDOMStream(e)}toNodeStream(e){return this._sink.toNodeStream(e)}close(){return this.reset()._sink.close()}abort(e){return this.reset()._sink.abort(e)}finish(){return this._autoDestroy?this.close():this.reset(this._sink,this._schema),this}reset(e=this._sink,t=null){return e===this._sink||e instanceof bF?this._sink=e:(this._sink=new bF,e&&ak(e)?this.toDOMStream({type:`bytes`}).pipeTo(e):e&&sk(e)&&this.toNodeStream({objectMode:!1}).pipe(e)),this._started&&this._schema&&this._writeFooter(this._schema),this._started=!1,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,(!t||!$I(t,this._schema))&&(t==null?(this._position=0,this._schema=null):(this._started=!0,this._schema=t,this._writeSchema(t))),this}write(e){let t=null;if(!this._sink)throw Error(`RecordBatchWriter is closed`);if(e==null||e instanceof lL&&!(t=e.schema)||e instanceof dL&&!(t=e.schema))return this.finish()&&void 0;if(t&&!$I(t,this._schema)){if(this._started&&this._autoDestroy)return this.close();this.reset(this._sink,t)}e instanceof dL?e instanceof mL||this._writeRecordBatch(e):e instanceof lL?this.writeAll(e.batches):QO(e)&&this.writeAll(e)}_writeMessage(e,t=8){let n=t-1,r=jL.encode(e),i=r.byteLength,a=this._writeLegacyIpcFormat?4:8,o=i+a+n&~n,s=o-i-a;return e.headerType===EA.RecordBatch?this._recordBatchBlocks.push(new hF(o,e.bodyLength,this._position)):e.headerType===EA.DictionaryBatch&&this._dictionaryBlocks.push(new hF(o,e.bodyLength,this._position)),this._writeLegacyIpcFormat||this._write(Int32Array.of(-1)),this._write(Int32Array.of(o-a)),i>0&&this._write(r),this._writePadding(s)}_write(e){if(this._started){let t=_k(e);t&&t.byteLength>0&&(this._sink.write(t),this._position+=t.byteLength)}return this}_writeSchema(e){return this._writeMessage(jL.from(e))}_writeFooter(e){return this._writeLegacyIpcFormat?this._write(Int32Array.of(0)):this._write(Int32Array.of(-1,0))}_writeMagic(){return this._write(fR)}_writePadding(e){return e>0?this._write(new Uint8Array(e)):this}_writeRecordBatch(e){let{byteLength:t,nodes:n,bufferRegions:r,buffers:i}=FR.assemble(e),a=new ML(e.numRows,n,r),o=jL.from(a,t);return this._writeDictionaries(e)._writeMessage(o)._writeBodyBuffers(i)}_writeDictionaryBatch(e,t,n=!1){let{byteLength:r,nodes:i,bufferRegions:a,buffers:o}=FR.assemble(new WP([e])),s=new NL(new ML(e.length,i,a),t,n),c=jL.from(s,r);return this._writeMessage(c)._writeBodyBuffers(o)}_writeBodyBuffers(e){let t,n,r;for(let i=-1,a=e.length;++i<a;)(t=e[i])&&(n=t.byteLength)>0&&(this._write(t),(r=(n+7&-8)-n)>0&&this._writePadding(r));return this}_writeDictionaries(e){for(let[t,n]of e.dictionaries){let e=n?.data??[],r=this._seenDictionaries.get(t),i=this._dictionaryDeltaOffsets.get(t)??0;if(!r||r.data[0]!==e[0])for(let[n,r]of e.entries())this._writeDictionaryBatch(r,t,n>0);else if(i<e.length)for(let n of e.slice(i))this._writeDictionaryBatch(n,t,!0);this._seenDictionaries.set(t,n),this._dictionaryDeltaOffsets.set(t,e.length)}return this}},WR=class e extends UR{static writeAll(t,n){let r=new e(n);return ZO(t)?t.then(e=>r.writeAll(e)):$O(t)?qR(r,t):KR(r,t)}},GR=class e extends UR{static writeAll(t){let n=new e;return ZO(t)?t.then(e=>n.writeAll(e)):$O(t)?qR(n,t):KR(n,t)}constructor(){super(),this._autoDestroy=!0}_writeSchema(e){return this._writeMagic()._writePadding(2)}_writeDictionaryBatch(e,t,n=!1){if(!n&&this._seenDictionaries.has(t))throw Error(`The Arrow File format does not support replacement dictionaries. `);return super._writeDictionaryBatch(e,t,n)}_writeFooter(e){let t=pF.encode(new pF(e,Nk.V5,this._recordBatchBlocks,this._dictionaryBlocks));return super._writeFooter(e)._write(t)._write(Int32Array.of(t.byteLength))._writeMagic()}};function KR(e,t){let n=t;t instanceof lL&&(n=t.batches,e.reset(void 0,t.schema));for(let t of n)e.write(t);return e.finish()}function qR(e,t){return LO(this,void 0,void 0,function*(){var n,r,i,a,o,s,c;try{for(n=!0,r=HO(t);i=yield r.next(),a=i.done,!a;n=!0){c=i.value,n=!1;let t=c;e.write(t)}}catch(e){o={error:e}}finally{try{!n&&!a&&(s=r.return)&&(yield s.call(r))}finally{if(o)throw o.error}}return e.finish()})}function JR(e,t=`stream`){return(t===`stream`?WR:GR).writeAll(e).toUint8Array(!0)}var YR=Object.create,XR=Object.defineProperty,ZR=Object.getOwnPropertyDescriptor,QR=Object.getOwnPropertyNames,$R=Object.getPrototypeOf,ez=Object.prototype.hasOwnProperty,tz=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),nz=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of QR(t))!ez.call(e,i)&&i!==n&&XR(e,i,{get:()=>t[i],enumerable:!(r=ZR(t,i))||r.enumerable});return e},rz=(e,t,n)=>(n=e==null?{}:YR($R(e)),nz(t||!e||!e.__esModule?XR(n,`default`,{value:e,enumerable:!0}):n,e)),iz=tz((e,t)=>{t.exports=Worker}),az=(e=>(e[e.UNDEFINED=0]=`UNDEFINED`,e[e.AUTOMATIC=1]=`AUTOMATIC`,e[e.READ_ONLY=2]=`READ_ONLY`,e[e.READ_WRITE=3]=`READ_WRITE`,e))(az||{}),oz=(e=>(e[e.IDENTIFIER=0]=`IDENTIFIER`,e[e.NUMERIC_CONSTANT=1]=`NUMERIC_CONSTANT`,e[e.STRING_CONSTANT=2]=`STRING_CONSTANT`,e[e.OPERATOR=3]=`OPERATOR`,e[e.KEYWORD=4]=`KEYWORD`,e[e.COMMENT=5]=`COMMENT`,e))(oz||{}),sz=(e=>(e[e.NONE=0]=`NONE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARNING=3]=`WARNING`,e[e.ERROR=4]=`ERROR`,e))(sz||{}),cz=(e=>(e[e.NONE=0]=`NONE`,e[e.CONNECT=1]=`CONNECT`,e[e.DISCONNECT=2]=`DISCONNECT`,e[e.OPEN=3]=`OPEN`,e[e.QUERY=4]=`QUERY`,e[e.INSTANTIATE=5]=`INSTANTIATE`,e))(cz||{}),lz=(e=>(e[e.NONE=0]=`NONE`,e[e.OK=1]=`OK`,e[e.ERROR=2]=`ERROR`,e[e.START=3]=`START`,e[e.RUN=4]=`RUN`,e[e.CAPTURE=5]=`CAPTURE`,e))(lz||{}),uz=(e=>(e[e.NONE=0]=`NONE`,e[e.WEB_WORKER=1]=`WEB_WORKER`,e[e.NODE_WORKER=2]=`NODE_WORKER`,e[e.BINDINGS=3]=`BINDINGS`,e[e.ASYNC_DUCKDB=4]=`ASYNC_DUCKDB`,e))(uz||{}),dz=class{constructor(e=2){this.level=e}log(e){e.level>=this.level&&console.log(e)}},fz=(e=>(e[e.SUCCESS=0]=`SUCCESS`,e[e.MAX_ARROW_ERROR=255]=`MAX_ARROW_ERROR`,e[e.DUCKDB_WASM_RETRY=256]=`DUCKDB_WASM_RETRY`,e))(fz||{}),pz=class{constructor(e,t){this._bindings=e,this._conn=t}get bindings(){return this._bindings}async close(){return this._bindings.disconnect(this._conn)}useUnsafe(e){return e(this._bindings,this._conn)}async query(e){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:e});let t=await this._bindings.runQuery(this._conn,e),n=_R.from(t);return console.assert(n.isSync(),`Reader is not sync`),console.assert(n.isFile(),`Reader is not file`),new lL(n)}async send(e,t=!1){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:e});let n=await this._bindings.startPendingQuery(this._conn,e,t);for(;n==null;){if(this._bindings.isDetached()){console.error(`cannot send a message since the worker is not set!`);return}n=await this._bindings.pollPendingQuery(this._conn)}let r=new mz(this._bindings,this._conn,n),i=await _R.from(r);return console.assert(i.isAsync()),console.assert(i.isStream()),i}async cancelSent(){return await this._bindings.cancelPendingQuery(this._conn)}async getTableNames(e){return await this._bindings.getTableNames(this._conn,e)}async prepare(e){let t=await this._bindings.createPrepared(this._conn,e);return new hz(this._bindings,this._conn,t)}async insertArrowTable(e,t){let n=JR(e,`stream`);await this.insertArrowFromIPCStream(n,t)}async insertArrowFromIPCStream(e,t){await this._bindings.insertArrowFromIPCStream(this._conn,e,t)}async insertCSVFromPath(e,t){await this._bindings.insertCSVFromPath(this._conn,e,t)}async insertJSONFromPath(e,t){await this._bindings.insertJSONFromPath(this._conn,e,t)}},mz=class{constructor(e,t,n){this.db=e,this.conn=t,this.header=n,this._first=!0,this._depleted=!1,this._inFlight=null}async next(){if(this._first)return this._first=!1,{done:!1,value:this.header};if(this._depleted)return{done:!0,value:null};let e=null;for(this._inFlight!=null&&(e=await this._inFlight,this._inFlight=null);e==null;)e=await this.db.fetchQueryResults(this.conn);return this._depleted=e.length==0,this._depleted||(this._inFlight=this.db.fetchQueryResults(this.conn)),{done:this._depleted,value:e}}[Symbol.asyncIterator](){return this}},hz=class{constructor(e,t,n){this.bindings=e,this.connectionId=t,this.statementId=n}async close(){await this.bindings.closePrepared(this.connectionId,this.statementId)}async query(...e){let t=await this.bindings.runPrepared(this.connectionId,this.statementId,e),n=_R.from(t);return console.assert(n.isSync()),console.assert(n.isFile()),new lL(n)}async send(...e){let t=await this.bindings.sendPrepared(this.connectionId,this.statementId,e),n=new mz(this.bindings,this.connectionId,t),r=await _R.from(n);return console.assert(r.isAsync()),console.assert(r.isStream()),r}},gz=(e=>(e.CANCEL_PENDING_QUERY=`CANCEL_PENDING_QUERY`,e.CLOSE_PREPARED=`CLOSE_PREPARED`,e.COLLECT_FILE_STATISTICS=`COLLECT_FILE_STATISTICS`,e.REGISTER_OPFS_FILE_NAME=`REGISTER_OPFS_FILE_NAME`,e.CONNECT=`CONNECT`,e.COPY_FILE_TO_BUFFER=`COPY_FILE_TO_BUFFER`,e.COPY_FILE_TO_PATH=`COPY_FILE_TO_PATH`,e.CREATE_PREPARED=`CREATE_PREPARED`,e.DISCONNECT=`DISCONNECT`,e.DROP_FILE=`DROP_FILE`,e.DROP_FILES=`DROP_FILES`,e.EXPORT_FILE_STATISTICS=`EXPORT_FILE_STATISTICS`,e.FETCH_QUERY_RESULTS=`FETCH_QUERY_RESULTS`,e.FLUSH_FILES=`FLUSH_FILES`,e.GET_FEATURE_FLAGS=`GET_FEATURE_FLAGS`,e.GET_TABLE_NAMES=`GET_TABLE_NAMES`,e.GET_VERSION=`GET_VERSION`,e.GLOB_FILE_INFOS=`GLOB_FILE_INFOS`,e.INSERT_ARROW_FROM_IPC_STREAM=`INSERT_ARROW_FROM_IPC_STREAM`,e.INSERT_CSV_FROM_PATH=`IMPORT_CSV_FROM_PATH`,e.INSERT_JSON_FROM_PATH=`IMPORT_JSON_FROM_PATH`,e.INSTANTIATE=`INSTANTIATE`,e.OPEN=`OPEN`,e.PING=`PING`,e.POLL_PENDING_QUERY=`POLL_PENDING_QUERY`,e.REGISTER_FILE_BUFFER=`REGISTER_FILE_BUFFER`,e.REGISTER_FILE_HANDLE=`REGISTER_FILE_HANDLE`,e.REGISTER_FILE_URL=`REGISTER_FILE_URL`,e.RESET=`RESET`,e.RUN_PREPARED=`RUN_PREPARED`,e.RUN_QUERY=`RUN_QUERY`,e.SEND_PREPARED=`SEND_PREPARED`,e.START_PENDING_QUERY=`START_PENDING_QUERY`,e.TOKENIZE=`TOKENIZE`,e))(gz||{}),_z=(e=>(e.CONNECTION_INFO=`CONNECTION_INFO`,e.ERROR=`ERROR`,e.FEATURE_FLAGS=`FEATURE_FLAGS`,e.FILE_BUFFER=`FILE_BUFFER`,e.FILE_INFOS=`FILE_INFOS`,e.FILE_SIZE=`FILE_SIZE`,e.FILE_STATISTICS=`FILE_STATISTICS`,e.INSTANTIATE_PROGRESS=`INSTANTIATE_PROGRESS`,e.LOG=`LOG`,e.PROGRESS_UPDATE=`PROGRESS_UPDATE`,e.OK=`OK`,e.PREPARED_STATEMENT_ID=`PREPARED_STATEMENT_ID`,e.QUERY_PLAN=`QUERY_PLAN`,e.QUERY_RESULT=`QUERY_RESULT`,e.QUERY_RESULT_CHUNK=`QUERY_RESULT_CHUNK`,e.QUERY_RESULT_HEADER=`QUERY_RESULT_HEADER`,e.QUERY_RESULT_HEADER_OR_NULL=`QUERY_RESULT_HEADER_OR_NULL`,e.REGISTERED_FILE=`REGISTERED_FILE`,e.SCRIPT_TOKENS=`SCRIPT_TOKENS`,e.SUCCESS=`SUCCESS`,e.TABLE_NAMES=`TABLE_NAMES`,e.VERSION_STRING=`VERSION_STRING`,e))(_z||{}),vz=class{constructor(e,t){this.promiseResolver=()=>{},this.promiseRejecter=()=>{},this.type=e,this.data=t,this.promise=new Promise((e,t)=>{this.promiseResolver=e,this.promiseRejecter=t})}};function yz(e){switch(e.typeId){case Z.Binary:return{sqlType:`binary`};case Z.Bool:return{sqlType:`bool`};case Z.Date:return{sqlType:`date`};case Z.DateDay:return{sqlType:`date32[d]`};case Z.DateMillisecond:return{sqlType:`date64[ms]`};case Z.Decimal:{let t=e;return{sqlType:`decimal`,precision:t.precision,scale:t.scale}}case Z.Float:return{sqlType:`float`};case Z.Float16:return{sqlType:`float16`};case Z.Float32:return{sqlType:`float32`};case Z.Float64:return{sqlType:`float64`};case Z.Int:return{sqlType:`int32`};case Z.Int16:return{sqlType:`int16`};case Z.Int32:return{sqlType:`int32`};case Z.Int64:return{sqlType:`int64`};case Z.Uint16:return{sqlType:`uint16`};case Z.Uint32:return{sqlType:`uint32`};case Z.Uint64:return{sqlType:`uint64`};case Z.Uint8:return{sqlType:`uint8`};case Z.IntervalDayTime:return{sqlType:`interval[dt]`};case Z.IntervalYearMonth:return{sqlType:`interval[m]`};case Z.List:return{sqlType:`list`,valueType:yz(e.valueType)};case Z.FixedSizeBinary:return{sqlType:`fixedsizebinary`,byteWidth:e.byteWidth};case Z.Null:return{sqlType:`null`};case Z.Utf8:return{sqlType:`utf8`};case Z.Struct:return{sqlType:`struct`,fields:e.children.map(e=>bz(e.name,e.type))};case Z.Map:{let t=e;return{sqlType:`map`,keyType:yz(t.keyType),valueType:yz(t.valueType)}}case Z.Time:return{sqlType:`time[s]`};case Z.TimeMicrosecond:return{sqlType:`time[us]`};case Z.TimeMillisecond:return{sqlType:`time[ms]`};case Z.TimeNanosecond:return{sqlType:`time[ns]`};case Z.TimeSecond:return{sqlType:`time[s]`};case Z.Timestamp:return{sqlType:`timestamp`,timezone:e.timezone||void 0};case Z.TimestampSecond:return{sqlType:`timestamp[s]`,timezone:e.timezone||void 0};case Z.TimestampMicrosecond:return{sqlType:`timestamp[us]`,timezone:e.timezone||void 0};case Z.TimestampNanosecond:return{sqlType:`timestamp[ns]`,timezone:e.timezone||void 0};case Z.TimestampMillisecond:return{sqlType:`timestamp[ms]`,timezone:e.timezone||void 0}}throw Error(`unsupported arrow type: ${e.toString()}`)}function bz(e,t){let n=yz(t);return n.name=e,n}var xz=/'(opfs:\/\/\S*?)'/g,Sz=/(opfs:\/\/\S*?)/g;function Cz(e){return e.search(Sz)>-1}function wz(e){return[...e.matchAll(xz)].map(e=>e[1])}var Tz=new TextEncoder,Ez=class{constructor(e,t=null){this._onInstantiationProgress=[],this._onExecutionProgress=[],this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{},this._nextMessageId=0,this._pendingRequests=new Map,this._config={},this._logger=e,this._onMessageHandler=this.onMessage.bind(this),this._onErrorHandler=this.onError.bind(this),this._onCloseHandler=this.onClose.bind(this),t!=null&&this.attach(t)}get logger(){return this._logger}get config(){return this._config}attach(e){this._worker=e,this._worker.addEventListener(`message`,this._onMessageHandler),this._worker.addEventListener(`error`,this._onErrorHandler),this._worker.addEventListener(`close`,this._onCloseHandler),this._workerShutdownPromise=new Promise((e,t)=>{this._workerShutdownResolver=e})}detach(){this._worker&&(this._worker.removeEventListener(`message`,this._onMessageHandler),this._worker.removeEventListener(`error`,this._onErrorHandler),this._worker.removeEventListener(`close`,this._onCloseHandler),this._worker=null,this._workerShutdownResolver(null),this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async terminate(){this._worker&&(this._worker.terminate(),this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async postTask(e,t=[]){if(!this._worker){console.error(`cannot send a message since the worker is not set!:`+e.type+`,`+e.data);return}let n=this._nextMessageId++;return this._pendingRequests.set(n,e),this._worker.postMessage({messageId:n,type:e.type,data:e.data},t),await e.promise}onMessage(e){var t;let n=e.data;switch(n.type){case`PROGRESS_UPDATE`:for(let e of this._onExecutionProgress)e(n.data);return;case`LOG`:this._logger.log(n.data);return;case`INSTANTIATE_PROGRESS`:for(let e of this._onInstantiationProgress)e(n.data);return}let r=this._pendingRequests.get(n.requestId);if(!r){console.warn(`unassociated response: [${n.requestId}, ${n.type.toString()}]`);return}if(this._pendingRequests.delete(n.requestId),n.type==`ERROR`){let e=Error(n.data.message);e.name=n.data.name,(t=Object.getOwnPropertyDescriptor(e,`stack`))!=null&&t.writable&&(e.stack=n.data.stack),r.promiseRejecter(e);return}switch(r.type){case`CLOSE_PREPARED`:case`COLLECT_FILE_STATISTICS`:case`REGISTER_OPFS_FILE_NAME`:case`COPY_FILE_TO_PATH`:case`DISCONNECT`:case`DROP_FILE`:case`DROP_FILES`:case`FLUSH_FILES`:case`INSERT_ARROW_FROM_IPC_STREAM`:case`IMPORT_CSV_FROM_PATH`:case`IMPORT_JSON_FROM_PATH`:case`OPEN`:case`PING`:case`REGISTER_FILE_BUFFER`:case`REGISTER_FILE_HANDLE`:case`REGISTER_FILE_URL`:case`RESET`:if(n.type==`OK`){r.promiseResolver(n.data);return}break;case`INSTANTIATE`:if(this._onInstantiationProgress=[],n.type==`OK`){r.promiseResolver(n.data);return}break;case`GLOB_FILE_INFOS`:if(n.type==`FILE_INFOS`){r.promiseResolver(n.data);return}break;case`GET_VERSION`:if(n.type==`VERSION_STRING`){r.promiseResolver(n.data);return}break;case`GET_FEATURE_FLAGS`:if(n.type==`FEATURE_FLAGS`){r.promiseResolver(n.data);return}break;case`GET_TABLE_NAMES`:if(n.type==`TABLE_NAMES`){r.promiseResolver(n.data);return}break;case`TOKENIZE`:if(n.type==`SCRIPT_TOKENS`){r.promiseResolver(n.data);return}break;case`COPY_FILE_TO_BUFFER`:if(n.type==`FILE_BUFFER`){r.promiseResolver(n.data);return}break;case`EXPORT_FILE_STATISTICS`:if(n.type==`FILE_STATISTICS`){r.promiseResolver(n.data);return}break;case`CONNECT`:if(n.type==`CONNECTION_INFO`){r.promiseResolver(n.data);return}break;case`RUN_PREPARED`:case`RUN_QUERY`:if(n.type==`QUERY_RESULT`){r.promiseResolver(n.data);return}break;case`SEND_PREPARED`:if(n.type==`QUERY_RESULT_HEADER`){r.promiseResolver(n.data);return}break;case`START_PENDING_QUERY`:if(n.type==`QUERY_RESULT_HEADER_OR_NULL`){r.promiseResolver(n.data);return}break;case`POLL_PENDING_QUERY`:if(n.type==`QUERY_RESULT_HEADER_OR_NULL`){r.promiseResolver(n.data);return}break;case`CANCEL_PENDING_QUERY`:if(this._onInstantiationProgress=[],n.type==`SUCCESS`){r.promiseResolver(n.data);return}break;case`FETCH_QUERY_RESULTS`:if(n.type==`QUERY_RESULT_CHUNK`){r.promiseResolver(n.data);return}break;case`CREATE_PREPARED`:if(n.type==`PREPARED_STATEMENT_ID`){r.promiseResolver(n.data);return}break}r.promiseRejecter(Error(`unexpected response type: ${n.type.toString()}`))}onError(e){console.error(e),console.error(`error in duckdb worker: ${e.message}`),this._pendingRequests.clear()}onClose(){if(this._workerShutdownResolver(null),this._pendingRequests.size!=0){console.warn(`worker terminated with ${this._pendingRequests.size} pending requests`);return}this._pendingRequests.clear()}isDetached(){return!this._worker}async reset(){let e=new vz(`RESET`,null);return await this.postTask(e)}async ping(){let e=new vz(`PING`,null);await this.postTask(e)}async dropFile(e){let t=new vz(`DROP_FILE`,e);return await this.postTask(t)}async dropFiles(e){let t=new vz(`DROP_FILES`,e);return await this.postTask(t)}async flushFiles(){let e=new vz(`FLUSH_FILES`,null);return await this.postTask(e)}async instantiate(e,t=null,n=e=>{}){this._onInstantiationProgress.push(n);let r=new vz(`INSTANTIATE`,[e,t]);return await this.postTask(r)}async getVersion(){let e=new vz(`GET_VERSION`,null);return await this.postTask(e)}async getFeatureFlags(){let e=new vz(`GET_FEATURE_FLAGS`,null);return await this.postTask(e)}async open(e){this._config=e;let t=new vz(`OPEN`,e);await this.postTask(t)}async tokenize(e){let t=new vz(`TOKENIZE`,e);return await this.postTask(t)}async connectInternal(){let e=new vz(`CONNECT`,null);return await this.postTask(e)}async connect(){let e=await this.connectInternal();return new pz(this,e)}async disconnect(e){let t=new vz(`DISCONNECT`,e);await this.postTask(t)}async runQuery(e,t){if(this.shouldOPFSFileHandling()){let n=await this.registerOPFSFileFromSQL(t);try{return await this._runQueryAsync(e,t)}finally{n.length>0&&await this.dropFiles(n)}}else return await this._runQueryAsync(e,t)}async _runQueryAsync(e,t){let n=new vz(`RUN_QUERY`,[e,t]);return await this.postTask(n)}async startPendingQuery(e,t,n=!1){if(this.shouldOPFSFileHandling()){let r=await this.registerOPFSFileFromSQL(t);try{return await this._startPendingQueryAsync(e,t,n)}finally{r.length>0&&await this.dropFiles(r)}}else return await this._startPendingQueryAsync(e,t,n)}async _startPendingQueryAsync(e,t,n=!1){let r=new vz(`START_PENDING_QUERY`,[e,t,n]);return await this.postTask(r)}async pollPendingQuery(e){let t=new vz(`POLL_PENDING_QUERY`,e);return await this.postTask(t)}async cancelPendingQuery(e){let t=new vz(`CANCEL_PENDING_QUERY`,e);return await this.postTask(t)}async fetchQueryResults(e){let t=new vz(`FETCH_QUERY_RESULTS`,e);return await this.postTask(t)}async getTableNames(e,t){let n=new vz(`GET_TABLE_NAMES`,[e,t]);return await this.postTask(n)}async createPrepared(e,t){let n=new vz(`CREATE_PREPARED`,[e,t]);return await this.postTask(n)}async closePrepared(e,t){let n=new vz(`CLOSE_PREPARED`,[e,t]);await this.postTask(n)}async runPrepared(e,t,n){let r=new vz(`RUN_PREPARED`,[e,t,n]);return await this.postTask(r)}async sendPrepared(e,t,n){let r=new vz(`SEND_PREPARED`,[e,t,n]);return await this.postTask(r)}async globFiles(e){let t=new vz(`GLOB_FILE_INFOS`,e);return await this.postTask(t)}async registerFileText(e,t){let n=Tz.encode(t);await this.registerFileBuffer(e,n)}async registerFileURL(e,t,n,r){t===void 0&&(t=e);let i=new vz(`REGISTER_FILE_URL`,[e,t,n,r]);await this.postTask(i)}async registerEmptyFileBuffer(e){}async registerFileBuffer(e,t){let n=new vz(`REGISTER_FILE_BUFFER`,[e,t]);await this.postTask(n,[t.buffer])}async registerFileHandle(e,t,n,r){let i=new vz(`REGISTER_FILE_HANDLE`,[e,t,n,r]);await this.postTask(i,[])}async registerOPFSFileName(e){let t=new vz(`REGISTER_OPFS_FILE_NAME`,[e]);await this.postTask(t,[])}async collectFileStatistics(e,t){let n=new vz(`COLLECT_FILE_STATISTICS`,[e,t]);await this.postTask(n,[])}async exportFileStatistics(e){let t=new vz(`EXPORT_FILE_STATISTICS`,e);return await this.postTask(t,[])}async copyFileToBuffer(e){let t=new vz(`COPY_FILE_TO_BUFFER`,e);return await this.postTask(t)}async copyFileToPath(e,t){let n=new vz(`COPY_FILE_TO_PATH`,[e,t]);await this.postTask(n)}async insertArrowFromIPCStream(e,t,n){if(t.length==0)return;let r=new vz(`INSERT_ARROW_FROM_IPC_STREAM`,[e,t,n]);await this.postTask(r,[t.buffer])}async insertCSVFromPath(e,t,n){if(n.columns!==void 0){let e=[];for(let t in n.columns){let r=n.columns[t];e.push(bz(t,r))}n.columnsFlat=e,delete n.columns}let r=new vz(`IMPORT_CSV_FROM_PATH`,[e,t,n]);await this.postTask(r)}async insertJSONFromPath(e,t,n){if(n.columns!==void 0){let e=[];for(let t in n.columns){let r=n.columns[t];e.push(bz(t,r))}n.columnsFlat=e,delete n.columns}let r=new vz(`IMPORT_JSON_FROM_PATH`,[e,t,n]);await this.postTask(r)}shouldOPFSFileHandling(){return Cz(this.config.path??``)?this.config.opfs?.fileHandling==`auto`:!1}async registerOPFSFileFromSQL(e){let t=wz(e),n=[];for(let e of t)try{await this.registerOPFSFileName(e),n.push(e)}catch(t){throw console.error(t),Error(`File Not found:`+e)}return n}};function Dz(){let e=new TextDecoder;return t=>(typeof SharedArrayBuffer<`u`&&t.buffer instanceof SharedArrayBuffer&&(t=new Uint8Array(t)),e.decode(t))}Dz();var Oz=(e=>(e[e.BUFFER=0]=`BUFFER`,e[e.NODE_FS=1]=`NODE_FS`,e[e.BROWSER_FILEREADER=2]=`BROWSER_FILEREADER`,e[e.BROWSER_FSACCESS=3]=`BROWSER_FSACCESS`,e[e.HTTP=4]=`HTTP`,e[e.S3=5]=`S3`,e))(Oz||{}),kz={name:`@duckdb/duckdb-wasm`,version:`1.33.1-dev45.0`,description:`DuckDB powered by WebAssembly`,license:`MIT`,repository:{type:`git`,url:`https://github.com/duckdb/duckdb-wasm.git`},keywords:[`sql`,`duckdb`,`relational`,`database`,`data`,`query`,`wasm`,`analytics`,`olap`,`arrow`,`parquet`,`json`,`csv`],dependencies:{"apache-arrow":`^17.0.0`,qs:`^6.14.1`},devDependencies:{"@types/emscripten":`^1.39.10`,"@types/jasmine":`^5.1.13`,"@typescript-eslint/eslint-plugin":`^6.21.0`,"@typescript-eslint/parser":`^6.21.0`,esbuild:`^0.20.2`,eslint:`^8.57.0`,"eslint-plugin-jasmine":`^4.1.3`,"eslint-plugin-react":`^7.37.5`,"fast-glob":`^3.3.2`,jasmine:`^5.13.0`,"jasmine-core":`^5.1.2`,"jasmine-spec-reporter":`^7.0.0`,"js-sha256":`^0.11.1`,karma:`^6.4.2`,"karma-chrome-launcher":`^3.2.0`,"karma-coverage":`^2.2.1`,"karma-firefox-launcher":`^2.1.3`,"karma-jasmine":`^5.1.0`,"karma-jasmine-html-reporter":`^2.1.0`,"karma-sourcemap-loader":`^0.4.0`,"karma-spec-reporter":`^0.0.36`,"make-dir":`^4.0.0`,nyc:`^15.1.0`,prettier:`^3.2.5`,puppeteer:`^22.8.0`,rimraf:`^5.0.5`,s3rver:`^3.7.1`,typedoc:`^0.28.15`,typescript:`^5.3.3`,"wasm-feature-detect":`^1.6.1`,"web-worker":`^1.2.0`},scripts:{"build:debug":`node bundle.mjs debug && tsc --emitDeclarationOnly`,"build:release":`node bundle.mjs release && tsc --emitDeclarationOnly`,docs:`typedoc`,format:`prettier --write "**/*.+(js|ts)"`,report:`node ./coverage.mjs`,"test:node":`node --enable-source-maps ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs`,"test:node:debug":`node --inspect-brk --enable-source-maps ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs`,"test:node:coverage":`nyc -r json --report-dir ./coverage/node node ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs`,"test:firefox":`karma start ./karma/tests-firefox.cjs`,"test:chrome":`karma start ./karma/tests-chrome.cjs`,"test:chrome:eh":`karma start ./karma/tests-chrome-eh.cjs`,"test:chrome:coverage":`karma start ./karma/tests-chrome-coverage.cjs`,"test:browser":`karma start ./karma/tests-all.cjs`,"test:browser:debug":`karma start ./karma/tests-debug.cjs`,test:`npm run test:chrome && npm run test:node`,"test:coverage":`npm run test:chrome:coverage && npm run test:node:coverage && npm run report`,lint:`eslint src test`},files:[`dist`,`!dist/tests-*`,`!dist/duckdb-browser-mvp.worker.js.map`,`!dist/types/test`],main:`dist/duckdb-browser.cjs`,module:`dist/duckdb-browser.mjs`,types:`dist/duckdb-browser.d.ts`,jsdelivr:`dist/duckdb-browser.cjs`,unpkg:`dist/duckdb-browser.mjs`,sideEffects:!1,browser:{fs:!1,path:!1,perf_hooks:!1,os:!1,worker_threads:!1},exports:{"./dist/duckdb-mvp.wasm":`./dist/duckdb-mvp.wasm`,"./dist/duckdb-eh.wasm":`./dist/duckdb-eh.wasm`,"./dist/duckdb-coi.wasm":`./dist/duckdb-coi.wasm`,"./dist/duckdb-browser":`./dist/duckdb-browser.mjs`,"./dist/duckdb-browser.cjs":`./dist/duckdb-browser.cjs`,"./dist/duckdb-browser.mjs":`./dist/duckdb-browser.mjs`,"./dist/duckdb-browser-coi.pthread.worker.js":`./dist/duckdb-browser-coi.pthread.worker.js`,"./dist/duckdb-browser-coi.worker.js":`./dist/duckdb-browser-coi.worker.js`,"./dist/duckdb-browser-eh.worker.js":`./dist/duckdb-browser-eh.worker.js`,"./dist/duckdb-browser-mvp.worker.js":`./dist/duckdb-browser-mvp.worker.js`,"./dist/duckdb-node":`./dist/duckdb-node.cjs`,"./dist/duckdb-node.cjs":`./dist/duckdb-node.cjs`,"./dist/duckdb-node-blocking":`./dist/duckdb-node-blocking.cjs`,"./dist/duckdb-node-blocking.cjs":`./dist/duckdb-node-blocking.cjs`,"./dist/duckdb-node-eh.worker.cjs":`./dist/duckdb-node-eh.worker.cjs`,"./dist/duckdb-node-mvp.worker.cjs":`./dist/duckdb-node-mvp.worker.cjs`,"./blocking":{node:{types:`./dist/duckdb-node-blocking.d.ts`,require:`./dist/duckdb-node-blocking.cjs`,import:`./dist/duckdb-node-blocking.cjs`},types:`./dist/duckdb-node-blocking.d.ts`,import:`./dist/duckdb-node-blocking.mjs`,require:`./dist/duckdb-node-blocking.cjs`},".":{browser:{types:`./dist/duckdb-browser.d.ts`,import:`./dist/duckdb-browser.mjs`,require:`./dist/duckdb-browser.cjs`},node:{types:`./dist/duckdb-node.d.ts`,import:`./dist/duckdb-node.cjs`,require:`./dist/duckdb-node.cjs`},types:`./dist/duckdb-browser.d.ts`,import:`./dist/duckdb-browser.mjs`,require:`./dist/duckdb-browser.cjs`}}};kz.name,kz.version;var Az=kz.version.split(`.`);Az[0],Az[1],Az[2],rz(iz());var jz=``+new URL(`assets/duckdb-browser-eh.worker--3HUwN9R.js`,import.meta.url).href,Mz=``+new URL(`assets/duckdb-eh-D-nnNw7L.wasm.gz`,import.meta.url).href;async function Nz(e){if(!e.endsWith(`.gz`))return e;let t=await fetch(e);if(!t.ok)throw Error(`DuckDB-WASM did not load (${t.status})`);let n=new Uint8Array(await t.arrayBuffer());return n[0]===31&&n[1]===139&&(n=new Uint8Array(await new Response(new Blob([n]).stream().pipeThrough(new DecompressionStream(`gzip`))).arrayBuffer())),URL.createObjectURL(new Blob([n],{type:`application/wasm`}))}var Pz=null;function Fz(){return Pz||(Pz=(async()=>{let e=e=>new URL(e,location.href).href,t=URL.createObjectURL(new Blob([`importScripts(${JSON.stringify(e(jz))});`],{type:`text/javascript`})),n=new Worker(t),r=new Ez(new dz(sz.WARNING),n),i=await Nz(e(Mz));await r.instantiate(i,null),URL.revokeObjectURL(t),i.startsWith(`blob:`)&&URL.revokeObjectURL(i);let a=await r.connect();return await a.query(`SET checkpoint_threshold = '1TB'`),await a.query(`SET autoinstall_known_extensions = false`),await a.query(`SET autoload_known_extensions = false`),await a.close(),r})(),Pz)}function Iz(e){return`"`+e.replace(/"/g,`""`)+`"`}function Lz(e){if(!(e.x1>e.x0))throw Error(`buildDecimationSql: x1 must be greater than x0`);if(e.maxPoints<1)throw Error(`buildDecimationSql: maxPoints must be >= 1`);if(!e.table||!e.xcol||!e.ycol)throw Error(`buildDecimationSql: table, xcol and ycol are required`);let t=(e.x1-e.x0)/e.maxPoints,n=Iz(e.xcol),r=Iz(e.ycol);return{sql:`SELECT least(floor((${n} - ?) / ?), ? - 1) AS b, min(${r}) AS lo, max(${r}) AS hi, arg_min(${r}, ${n}) AS first, arg_max(${r}, ${n}) AS last FROM ${Iz(e.table)} WHERE ${n} BETWEEN ? AND ? GROUP BY 1 ORDER BY 1`,params:[e.x0,t,e.maxPoints,e.x0,e.x1]}}function Rz(e){if(!(e.x1>e.x0))throw Error(`buildMultiDecimationSql: x1 must be greater than x0`);if(e.maxPoints<1)throw Error(`buildMultiDecimationSql: maxPoints must be >= 1`);if(!e.table||!e.xcol||e.ycols.length===0)throw Error(`buildMultiDecimationSql: table, xcol and at least one ycol are required`);let t=(e.x1-e.x0)/e.maxPoints,n=Iz(e.xcol),r=Iz(e.table);return{sql:`SELECT least(floor((${n} - ?) / ?), ? - 1) AS b, ${e.ycols.map((e,t)=>`min(${Iz(e)}) AS y${t}lo, max(${Iz(e)}) AS y${t}hi`).join(`, `)} FROM ${r} WHERE ${n} BETWEEN ? AND ? GROUP BY 1 ORDER BY 1`,params:[e.x0,t,e.maxPoints,e.x0,e.x1]}}var zz=`__kym_bin`;function Bz(e){if(!(e.binWidth>0))throw Error(`buildPyramidBuildL0Sql: binWidth must be > 0`);if(e.ycols.length===0)throw Error(`buildPyramidBuildL0Sql: at least one ycol is required`);let t=Iz(e.xcol),n=Iz(e.srcTable);return`CREATE OR REPLACE TABLE ${Iz(e.dstTable)} AS SELECT ${`CAST(floor((${t} - ${Uz(e.x0base)}) / ${Uz(e.binWidth)}) AS BIGINT)`} AS ${zz}, ${e.ycols.map(e=>`min(${Iz(e)}) AS ${Iz(e+`__lo`)}, max(${Iz(e)}) AS ${Iz(e+`__hi`)}`).join(`, `)} FROM ${n} WHERE ${t} IS NOT NULL GROUP BY 1`}function Vz(e){let t=Iz(e.srcTable);return`CREATE OR REPLACE TABLE ${Iz(e.dstTable)} AS SELECT CAST(floor(${zz} / 2.0) AS BIGINT) AS ${zz}, ${e.ycols.map(e=>`min(${Iz(e+`__lo`)}) AS ${Iz(e+`__lo`)}, max(${Iz(e+`__hi`)}) AS ${Iz(e+`__hi`)}`).join(`, `)} FROM ${t} GROUP BY 1`}function Hz(e){if(!(e.x1>e.x0))throw Error(`buildPyramidQuerySql: x1 must be greater than x0`);if(e.maxPoints<1)throw Error(`buildPyramidQuerySql: maxPoints must be >= 1`);if(e.ycols.length===0)throw Error(`buildPyramidQuerySql: at least one ycol is required`);let t=(e.x1-e.x0)/e.maxPoints,n=e.binWidth/t,r=(e.x0base-e.x0)/t+.5*n,i=Math.max(0,Math.floor((e.x0-e.x0base)/e.binWidth)),a=Math.floor((e.x1-e.x0base)/e.binWidth),o=Iz(e.levelTable);return{sql:`SELECT least(greatest(CAST(floor(? + ${zz} * ?) AS BIGINT), 0), ?) AS b, ${e.ycols.map((e,t)=>`min(${Iz(e+`__lo`)}) AS y${t}lo, max(${Iz(e+`__hi`)}) AS y${t}hi`).join(`, `)} FROM ${o} WHERE ${zz} BETWEEN ? AND ? GROUP BY 1 ORDER BY 1`,params:[r,n,e.maxPoints-1,i,a]}}function Uz(e){if(!Number.isFinite(e))throw Error(`num: value must be finite`);return Number.isInteger(e)?String(e):e.toExponential(17)}function Wz(e){let t=Iz(e.table);return e.range?{sql:`SELECT count(*) AS n FROM ${t} WHERE ${Iz(e.range.xcol)} BETWEEN ? AND ?`,params:[e.range.x0,e.range.x1]}:{sql:`SELECT count(*) AS n FROM ${t}`,params:[]}}function Gz(e){if(!Number.isInteger(e.stride)||e.stride<1)throw Error(`buildSampleRowsSql: stride must be a positive integer`);let t=Iz(e.table),n=e.range?` WHERE ${Iz(e.range.xcol)} BETWEEN ? AND ?`:``,r=e.range?[e.range.x0,e.range.x1]:[];return e.stride===1?{sql:`SELECT * FROM ${t}${n}`,params:r}:{sql:`SELECT * EXCLUDE(__kym_rn) FROM (SELECT *, row_number() OVER () - 1 AS __kym_rn FROM ${t}${n}) WHERE __kym_rn % ${e.stride} = 0`,params:r}}function Kz(e){return`'`+e.replace(/'/g,`''`)+`'`}function qz(e){let t=e.columnNames.map(Kz).join(`, `),n=e.delim===` `?`'\\t'`:Kz(e.delim),r=e.decimalComma?`decimal_separator=',', `:``;return`SELECT * FROM read_csv(${Kz(e.handle)}, header=false, skip=${e.dataStartRow}, delim=${n}, `+r+`names=[${t}], auto_type_candidates=['DOUBLE', 'VARCHAR'])`}function Jz(e,t,n){let r=e.length,i={x:new Float64Array(r),min:new Float64Array(r),max:new Float64Array(r),first:new Float64Array(r),last:new Float64Array(r)};for(let a=0;a<r;a++){let r=e[a],o=Number(r.b);i.x[a]=t+(o+.5)*n,i.min[a]=Number(r.lo),i.max[a]=Number(r.hi),i.first[a]=Number(r.first),i.last[a]=Number(r.last)}return i}var Yz=class{#e;#t=new Map;constructor(e){this.#e=Math.max(1,e)}get(e){let t=this.#t.get(e);return t!==void 0&&(this.#t.delete(e),this.#t.set(e,t)),t}set(e,t){if(this.#t.has(e)&&this.#t.delete(e),this.#t.set(e,t),this.#t.size>this.#e){let e=this.#t.keys().next().value;this.#t.delete(e)}}get size(){return this.#t.size}},Xz=0,Zz=()=>`t_${++Xz}`,Qz=5e4,$z=65536,eB=512,tB=2;function nB(e){return e<1?1:2**Math.floor(Math.log2(e))}var rB=class e{#e;#t;#n;#r;#i=new Yz(96);#a=new Map;#o=new Map;#s=[];#c=0;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n,this.#r=new Set(t.map(e=>e.name))}static async open(t,n){let r=await Fz(),i=await r.connect(),a=await t.slice(0,256*1024).text(),o=U(a),s=Be(a),c=Xe(o,s.headerRow),l=s.unitsRow===null?``:o[s.unitsRow]??``,u=we(o[s.headerRow]??``),d=qe(o.slice(s.dataStartRow,s.dataStartRow+10),u);n?.({phase:`reading`,message:`Reading file…`});let f=new Uint8Array(await t.arrayBuffer());await r.dropFile(`input.csv`).catch(()=>{}),await r.registerFileBuffer(`input.csv`,f),n?.({phase:`parsing`,message:`Parsing CSV…`});let p=Zz(),m=qz({handle:`input.csv`,columnNames:c,delim:u,dataStartRow:s.dataStartRow,decimalComma:d});await i.query(`CREATE OR REPLACE TABLE ${Iz(p)} AS ${m}`),await r.dropFile(`input.csv`).catch(()=>{});let h=l?l.split(u).map(e=>e.trim()):[],g=new Map;c.forEach((e,t)=>g.set(e,h[t]??``));let _=await e.attach(i,p,g);return n?.({phase:`done`,message:`Ready.`}),_}static async attach(t,n,r){return new e(t,(await t.query(`DESCRIBE ${Iz(n)}`)).toArray().map(e=>{let t=String(e.column_type??``),n=/INT|DECIMAL|DOUBLE|FLOAT|REAL|HUGEINT|BIGINT/i.test(t),i=String(e.column_name);return{name:i,type:n?`number`:`string`,unit:r.get(i)??``}}),n)}async getSchema(){return this.#t}async getSeries(e){if(!Number.isFinite(e.viewport.x0)||!Number.isFinite(e.viewport.x1)||e.viewport.x1<=e.viewport.x0){let e=new Float64Array;return{x:e,min:e,max:e,first:e,last:e}}let t=(e.viewport.x1-e.viewport.x0)/e.maxPoints,{sql:n,params:r}=Lz({table:this.#n,xcol:e.viewport.xKey,ycol:e.column,x0:e.viewport.x0,x1:e.viewport.x1,maxPoints:e.maxPoints}),i=await this.#e.prepare(n);try{return Jz((await i.query(...r)).toArray(),e.viewport.x0,t)}finally{await i.close()}}async getSeriesMulti(e,t,n){let r=(t.x1-t.x0)/n,i=this.#r.has(t.xKey)?e.filter(e=>this.#r.has(e)):[];if(i.length===0||!Number.isFinite(t.x0)||!Number.isFinite(t.x1)||t.x1<=t.x0)return{x0:t.x0,bucket:r,rows:[],columns:i};let a=`${t.xKey}|${i.join(`,`)}|${t.x0}|${t.x1}|${n}`,o=this.#i.get(a);if(o)return o;let s=this.#o.get(t.xKey);s===void 0&&this.#l(t.xKey);let{sql:c,params:l}=this.#u(s??null,i,t,n)??Rz({table:this.#n,xcol:t.xKey,ycols:i,x0:t.x0,x1:t.x1,maxPoints:n}),u=await this.#e.prepare(c);try{let e=(await u.query(...l)).toArray(),n={x0:t.x0,bucket:r,rows:e,columns:i};return this.#i.set(a,n),n}finally{await u.close()}}#l(e){let t=this.#a.get(e);if(t)return t;let n=this.#d(e).then(t=>(this.#o.set(e,t),t)).catch(()=>(this.#o.set(e,null),null));return this.#a.set(e,n),n}#u(e,t,n,r){if(!e)return null;for(let n of t)if(!e.cols.has(n))return null;let i=(n.x1-n.x0)/r/tB,a=null;for(let t of e.levels)t.binWidth<=i&&(a=t);return a?Hz({levelTable:a.table,ycols:t,x0base:e.x0base,binWidth:a.binWidth,x0:n.x0,x1:n.x1,maxPoints:r}):null}async#d(e){if(!this.#r.has(e))return null;let t=await(await Fz()).connect();try{let n=Wz({table:this.#n}),r=await t.query(n.sql),i=Number(r.getChild(`n`)?.get(0)??0);if(i<Qz)return null;let a=await t.query(`SELECT min(${Iz(e)}) AS lo, max(${Iz(e)}) AS hi FROM ${Iz(this.#n)}`),o=Number(a.getChild(`lo`)?.get(0)),s=Number(a.getChild(`hi`)?.get(0));if(!Number.isFinite(o)||!Number.isFinite(s)||!(s>o))return null;let c=this.#t.filter(t=>t.type===`number`&&t.name!==e).map(e=>e.name);if(c.length===0)return null;let l=s-o,u=Math.min($z,nB(i));if(u<eB*2)return null;let d=++this.#c,f=[],p=u,m=0,h=`${this.#n}_p${d}_0`;await t.query(Bz({srcTable:this.#n,dstTable:h,xcol:e,ycols:c,x0base:o,binWidth:l/u})),this.#s.push(h),f.push({table:h,binWidth:l/u,nbins:p});let g=h;for(;p/2>=eB;){p/=2,m+=1;let e=`${this.#n}_p${d}_${m}`;await t.query(Vz({srcTable:g,dstTable:e,ycols:c})),this.#s.push(e),f.push({table:e,binWidth:l/p,nbins:p}),g=e}return{x0base:o,cols:new Set(c),levels:f}}finally{await t.close()}}async sampleRows(e,t){let n=t&&this.#r.has(t.xcol)?t:void 0,r=Wz({table:this.#n,range:n}),i=await this.#e.prepare(r.sql),a;try{let e=await i.query(...r.params);a=Number(e.getChild(`n`)?.get(0)??0)}finally{await i.close()}if(a===0)return[];let o=Math.max(1,Math.ceil(a/e)),{sql:s,params:c}=Gz({table:this.#n,stride:o,range:n}),l=await this.#e.prepare(s),u=this.#t.map(e=>e.name),d=[];try{let e=await l.query(...c);for(let t=0;t<e.numRows;t++)d.push({});for(let t of u){let n=e.getChild(t);if(!n){for(let e of d)e[t]=null;continue}let r=n.toArray(),i=ArrayBuffer.isView(r),a=n.nullCount>0;for(let e=0;e<d.length;e++){let o=a&&!n.isValid(e)?null:i?r[e]:n.get(e);d[e][t]=typeof o==`bigint`?Number(o):o}}}finally{await l.close()}return d}async readColumns(e,t,n){let r=[...new Set(e)].filter(e=>this.#r.has(e));if(!r.length)return{};let i=r.map((e,t)=>`coalesce(TRY_CAST(${Iz(e)} AS DOUBLE), 'NaN'::DOUBLE) AS "c${t}"`).join(`, `),a=await this.#e.prepare(`SELECT ${i} FROM ${Iz(this.#n)} ORDER BY rowid LIMIT ? OFFSET ?`);try{let e=await a.query(n,t),i={};return r.forEach((t,n)=>{let r=e.getChild(`c${n}`)?.toArray();i[t]=r instanceof Float64Array?r:Float64Array.from(r??[],Number)}),i}finally{await a.close()}}async xBounds(e){if(!this.#r.has(e))return{x0:0,x1:0};let t=await this.#e.query(`SELECT min(${Iz(e)}) AS lo, max(${Iz(e)}) AS hi FROM ${Iz(this.#n)}`);return{x0:Number(t.getChild(`lo`)?.get(0)),x1:Number(t.getChild(`hi`)?.get(0))}}async dispose(){for(let e of this.#s)try{await this.#e.query(`DROP TABLE IF EXISTS ${Iz(e)}`)}catch{}try{await this.#e.query(`DROP TABLE IF EXISTS ${Iz(this.#n)}`)}catch{}await this.#e.close()}},iB=1e8,aB=256*1024;function oB(e,t,n=0,r=iB){return e>314572800||n+t>r?`duckdb`:`memory`}function sB(e,t){let n=U(t);t.length<e&&n.length>1&&(n=n.slice(0,-1));try{let t=Be(n.join(`
71
+ `)),r=Xe(n,t.headerRow).length,i=n.slice(t.dataStartRow);if(i.length===0)return Math.ceil(e/8);let a=n.slice(0,t.dataStartRow).reduce((e,t)=>e+t.length+1,0),o=i.reduce((e,t)=>e+t.length+1,0)/i.length;return Math.ceil(Math.max(0,e-a)/o)*r}catch{return Math.ceil(e/8)}}var cB=12e3;async function lB(e,t,n){let r=Be(n),i=typeof Worker>`u`?et(n,r):await MO({rawText:n,config:r}),a=new IO(i);return{id:e,name:t,kind:`memory`,source:a,schema:await a.getSchema(),data:i,rawText:n,parseConfig:r}}async function uB(e,t,n,r,i=e=>e.text(),a){let o=Be(r),s=typeof Worker>`u`?await NO({rawText:await i(n),config:o},a):await NO({file:n,config:o},a),c=new IO(s);return{id:e,name:t,kind:`memory`,source:c,schema:await c.getSchema(),data:s,rawText:r,file:n,parseConfig:o}}async function dB(e,t,n){let r=await rB.open(t,n),i=await r.getSchema(),a=await r.sampleRows(cB),o={meta:``,columnNames:i.map(e=>e.name),units:i.map(e=>e.unit),rows:a},s=await t.slice(0,aB).text();return{id:e,name:t.name,kind:`duckdb`,source:r,schema:i,data:o,rawText:s,parseConfig:Be(s)}}async function fB(e,t,n,r,i=0,a){let o=await t.slice(0,aB).text();return oB(t.size,sB(t.size,o),i)===`memory`?uB(e,t.name,t,o,e=>n(e),a):dB(e,t,r)}function pB(e,t){return e instanceof File&&e.name===t.name&&e.size===t.size&&e.lastModified===t.lastModified}async function mB(e,t,n){let r=n.find(e=>e.kind===`memory`&&e.parseConfig&&pB(e.file,t)&&Ue(e.data.rows));if(!r)return null;let i=await t.slice(0,aB).text();if(!le(r.parseConfig,Be(i)))return null;let a={...r.data,rows:Pe(Ue(r.data.rows))};return{id:e,name:t.name,kind:`memory`,source:new IO(a),schema:r.schema,data:a,rawText:r.rawText,file:t,parseConfig:r.parseConfig}}function hB(e){let t=new Set,n=0;for(let r of e){if(r.kind!==`memory`)continue;let e=Ue(r.data.rows)??r.data.rows;t.has(e)||(t.add(e),n+=r.data.rows.length*r.data.columnNames.length)}return n}var gB=4096,_B=[`.dat`,`.txt`,`.csv`,`.tsv`],vB=[L,h,z,i,dt,j,b],yB=e=>{let t=e.lastIndexOf(`.`);return t<=0?``:e.slice(t).toLowerCase()},bB=e=>{let t=e.lastIndexOf(`.`);return(t<=0?e:e.slice(0,t)).toLowerCase()};async function xB(e){let t=new Uint8Array(await e.slice(0,gB).arrayBuffer()),n=yB(e.name),r=vB.filter(e=>e.extensions.includes(n));for(let n of[...r,...vB.filter(e=>!r.includes(e))])if(n.sniff(t,e.name))return n;return null}async function SB(e){return new Uint8Array(await e.slice(0,gB).arrayBuffer()).includes(0)}async function CB(e){let t=await Promise.all(e.map(xB)),n=[],r=new Set;e.forEach((e,i)=>{let a=t[i];a&&(n.push({main:e,companions:[],format:a}),r.add(e))});for(let i of[...n])for(let n of i.format.companions??[]){let a=e.filter((e,r)=>!t[r]&&yB(e.name)===n.ext),o=a.find(e=>bB(e.name)===bB(i.main.name))??(n.anyName&&a.length===1?a[0]:void 0);o&&(i.companions.push(o),r.add(o))}let i=new Set(vB.flatMap(e=>(e.companions??[]).map(e=>e.ext))),a=[];for(let t of e){if(r.has(t))continue;let e=yB(t.name);e===`.dat`&&await SB(t)?a.push({file:t.name,error:Error(`This COMTRADE .dat needs its .cfg file — drop both together.`)}):_B.includes(e)?n.push({main:t,companions:[],format:null}):i.has(e)?a.push({file:t.name,error:Error(`${t.name} is read together with its main file (same name). Drop both files together.`)}):a.push({file:t.name,error:Error(`${t.name}: Kymoscope cannot read this file type.`)})}return n.sort((t,n)=>e.indexOf(t.main)-e.indexOf(n.main)),{items:n,errors:a}}var wB=[...new Set([..._B,...vB.flatMap(e=>[...e.extensions,...(e.companions??[]).map(e=>e.ext)])])];function TB(e){let t=0;for(let n=0;n<e.length;n++)e[n]!==e[n]&&t++;if(t===0)return KP(e);let n=new Uint8Array(e.length+7>>3);for(let t=0;t<e.length;t++)e[t]===e[t]&&(n[t>>3]|=1<<(t&7));return KP(bP({type:new Tj,data:e,nullBitmap:n,length:e.length,nullCount:t}))}var EB=122880,DB=class{#e;#t;#n;#r=!1;#i=[];#a=0;#o;rows=0;constructor(e,t,n,r=EB){this.#e=e,this.#t=t,this.#n=new sF(n.map(e=>new cF(e.name,e.text?new Oj:new Tj,!0))),this.#o=r}async append(e){let t=e.length;if(t===0)return;let n=this.#n.fields.map((n,r)=>{let i=e.columns[r];return(i instanceof Float64Array?TB(i.subarray(0,t)):nL(i.slice(0,t),new Oj)).data[0]});this.#i.push(new dL(this.#n,bP({type:new zj(this.#n.fields),length:t,nullCount:0,children:n}))),this.#a+=t,this.rows+=t,this.#a>=this.#o&&await this.flush()}async flush(){if(this.#a===0)return;let e=new lL(this.#n,this.#i);this.#i=[],this.#a=0,await this.#e.insertArrowTable(e,{name:this.#t,create:!this.#r}),this.#r=!0}},OB=`This file's groups do not interleave in time: reading them together would hold too much in memory. Choose fewer groups, or split them.`,kB=e=>e.length*(1+e.columns.length);function AB(e){let t=e[Symbol.asyncIterator]();return{pull:async()=>{let e=await t.next();return e.done?null:e.value}}}function jB(e,t){let n=Array.from({length:t.size},()=>[]),r=!1,i=0,a=async a=>{for(;;){if(n[a].length){let e=n[a].shift();return i-=kB(e),e}if(r)return null;let o=await e.next();if(o.done){r=!0;continue}let s=t.get(o.value.group);if(s!==void 0&&(n[s].push(o.value),(i+=kB(o.value))>128e6))throw Error(OB)}};return n.map((e,t)=>({pull:()=>a(t)}))}function MB(e,t){if(e.time)return e.time;let n=new Float64Array(e.length);if(t.time.kind===`rate`){let{rate:r,start:i}=t.time;for(let t=0;t<e.length;t++)n[t]=i+(e.start+t)/r}else for(let t=0;t<e.length;t++)n[t]=e.start+t;return n}var NB=new Int32Array,PB={t:new Float64Array,cols:[],from:0};function FB(e,t,n,r){let i=n,a=r;for(;i<a;){let n=i+a>>>1;e[n]<=t?i=n+1:a=n}return i}var IB=class{group;channels;feed;pending=[];done=!1;last;scratch=[];#e=-1/0;constructor(e,t,n){this.group=e,this.channels=t,this.feed=n,this.last=t.map(e=>e.text?null:NaN)}rows(){let e=0;for(let t of this.pending)e+=t.t.length-t.from;return e}lastTime(){let e=this.pending[this.pending.length-1];return e&&e.t.length>e.from?e.t[e.t.length-1]:-1/0}async fill(){let e=await this.feed.pull();if(!e){this.done=!0;return}if(e.length===0)return;let t=LB(MB(e,this.group),this.#e);if(t.length&&(this.#e=t[t.length-1]),this.pending.push({t,cols:e.columns,from:0}),this.rows()*(1+this.channels.length)>128e6)throw Error(OB)}};function LB(e,t){let n=t,r=0;for(;r<e.length;r++){let t=e[r];if(!(t>=n&&t>-1/0&&t<1/0))break;n=t}if(r===e.length)return e;for(n===-1/0&&(n=0);r<e.length;r++){let t=e[r];t>=n&&t<1/0?n=t:e[r]=n}return e}function RB(e,t){let n=e.length,r=e.map(e=>e.t),i=Int32Array.from(e,e=>e.from),a=Int32Array.from(e,e=>FB(e.t,t,e.from,e.t.length));if(n===1)return r[0].subarray(i[0],a[0]);let o=0;for(let e=0;e<n;e++)o+=a[e]-i[e];let s=new Float64Array(o),c=0;for(;;){let e=1/0;for(let t=0;t<n;t++)i[t]<a[t]&&r[t][i[t]]<e&&(e=r[t][i[t]]);if(e===1/0)break;s[c++]=e;for(let t=0;t<n;t++){let n=r[t],o=a[t],s=i[t];for(;s<o&&n[s]===e;)s++;i[t]=s}}return s.subarray(0,c)}function zB(e,t,n,r,i,a){if(i-r>8)e.set(t.subarray(n+r,n+i),a);else for(let o=r;o<i;o++)e[a+o-r]=t[n+o]}function BB(e,t,n,r,i,a){let o=0;for(let s=0;s<n.length;s++){let c=n[s],l=c.length;if(l===0)continue;let u=i[s].from,d=i[s].cols[a];e.fill(t,o,c[0]);let f=r[s],p=0;for(let t=0;t<f.length;t++){let n=f[t];zB(e,d,u,p,n,c[p]);let r=c[n],i=c[n+1],a=d[u+n];if(i-r>16)e.fill(a,r,i);else for(let t=r;t<i;t++)e[t]=a;p=n+1}zB(e,d,u,p,l-1,c[p]),o=c[l-1],t=d[u+l-1]}e.fill(t,o,e.length)}function VB(e,t,n,r,i){let a=0;for(let o=0;o<n.length;o++){let s=n[o],c=s.length;if(c===0)continue;let l=r[o].from,u=r[o].cols[i];e.fill(t,a,s[0]);for(let t=0;t<c-1;t++)e.fill(u[l+t],s[t],s[t+1]);a=s[c-1],t=u[l+c-1]}e.fill(t,a,e.length)}function HB(e,t,n,r,i){let a=n.length,o=null,s=0;for(let c=0;c<i.length;c++){let l=e[t+c],u=r;if(n[r]<l){let e=r,t=1;for(;e+t<a&&n[e+t]<l;)e+=t,t*=2;let i=Math.min(e+t,a-1);for(;i-e>1;){let t=e+i>>>1;n[t]<l?e=t:i=t}r=i}i[c]=r,c>0&&r!==u+1&&((o??=new Int32Array(i.length-1))[s++]=c-1)}return o?o.subarray(0,s):NB}function UB(e,t,n,r,i){let a=t.length;if(r){let t=e.pending[0],n=t.from+a,r=t.cols.map(e=>e instanceof Float64Array?e.subarray(t.from,n):e.slice(t.from,n));if(a>0)for(let i=0;i<r.length;i++)e.last[i]=t.cols[i][n-1];return e.pending=n<t.t.length?[{...t,from:n}]:[],r}let o=e.pending,s=[],c=[];if(a>0){let e=t[a-1],n=0;for(let r of o){let i=r.t,a=FB(i,e,r.from,i.length),o=new Int32Array(a-r.from);if(c.push(HB(i,r.from,t,n,o)),o.length&&(n=o[o.length-1]),s.push(o),a<i.length)break}}let l=e.channels.map((r,l)=>{if(r.sparse&&n){let e=r.text?Array(a).fill(null):new Float64Array(a).fill(NaN);for(let n=0;n<s.length;n++){let r=s[n],{t:i,from:c}=o[n],u=o[n].cols[l];for(let n=0;n<r.length;n++){let o=r[n];o<a&&t[o]===i[c+n]&&(e[o]=u[c+n])}}return e}if(r.text){let t=Array(a);return VB(t,e.last[l],s,o,l),t}let u;return i?(e.scratch[l]?.length>=a||(e.scratch[l]=new Float64Array(a)),u=e.scratch[l].subarray(0,a)):u=new Float64Array(a),BB(u,e.last[l],s,c,o,l),u}),u=[];for(let t=0;t<o.length;t++){let n=o[t],r=t<s.length?s[t].length:0;if(r>0)for(let t=0;t<e.channels.length;t++)e.last[t]=n.cols[t][n.from+r-1];n.from+r<n.t.length&&u.push(r?{...n,from:n.from+r}:n)}return e.pending=u,l}async function WB(e,t,n,r,i,a=!1){let o=e.map((e,r)=>new IB(e,t[r],n[r])),s=-1;e.forEach((t,n)=>{!t.irregular&&(s<0||t.samples>e[s].samples)&&(s=n)});let c=e.map((e,t)=>t===s||!!e.irregular),l=o.filter((e,t)=>c[t]),u=l.length===1,d=0;for(;;){i?.throwIfAborted();for(let e of l)for(;!e.done&&e.rows()===0;)await e.fill();if(l.every(e=>e.rows()===0))break;let e=1/0;for(let t of l)t.done||(e=Math.min(e,t.lastTime()));for(let t=0;t<o.length;t++)if(!c[t])for(;!o[t].done&&o[t].lastTime()<=e;)await o[t].fill();let t=RB(l.map(e=>e.pending[0]??PB),e),n=[t];for(let e=0;e<o.length;e++)n.push(...UB(o[e],t,c[e],u&&c[e],a));d+=t.length,t.length&&await r({length:t.length,columns:n})}return d}var GB=class{#e;#t;#n;#r=0;constructor(e,t){let n=Math.max(1024,t);this.#e=e.map(e=>e.name),this.#t=e.map(()=>new Float64Array(n)),this.#n=e.map(()=>null)}append(e){let t=this.#r,n=t+e.length;if(n>this.#t[0].length){let e=Math.max(n,Math.ceil(this.#t[0].length*1.5));this.#t=this.#t.map(n=>{let r=new Float64Array(e);return r.set(n.subarray(0,t)),r})}e.columns.forEach((n,r)=>{let i=this.#t[r];if(n instanceof Float64Array){i.set(n.subarray(0,e.length),t);return}let a=this.#n[r];for(let o=0;o<e.length;o++){i[t+o]=NaN;let e=n[o];e!=null&&((a??=this.#n[r]=[])[t+o]=e)}}),this.#r=n}table(){let e=this.#r,t=this.#t.map(t=>t.length-e>t.length/100?t.slice(0,e):t.subarray(0,e));return{keys:this.#e,length:e,values:t,text:this.#n}}};async function KB(e,t,n){return D(await e.plan(t,n))}var qB=(e,t,n)=>Math.max(0,Math.min(e,Math.max(1<<20,n),Math.floor(1e8/t)));function JB(e,t){let n=t.flatMap(t=>t.channels.map(n=>({ch:e.groups[t.group].channels[n],group:e.groups[t.group].name}))),r=new Map;for(let{ch:e}of n)r.set(e.name.toLowerCase(),(r.get(e.name.toLowerCase())??0)+1);let i=De(n.map(({ch:e,group:n})=>t.length>1&&r.get(e.name.toLowerCase())>1?`${e.name} [${n}]`:e.name));return[{name:`Time`,unit:t.every(t=>e.groups[t.group].time.kind===`index`)?``:`s`,text:!1},...n.map(({ch:e},t)=>({name:i[t],unit:e.unit,text:!!e.text}))]}function YB(e,t){let n=t.map(t=>e.groups[t.group]);if(n.some(e=>e.samples<0))return-1;let r=0,i=0;for(let e of n)e.irregular?i+=e.samples:r=Math.max(r,e.samples);return r+i}function XB(e,t,n){let r=YB(e,t);return r<0?Math.ceil(n/4):r*(1+t.reduce((e,t)=>e+t.channels.length,0))}async function ZB(e,t,n,r,i,a,o={}){let s=JB(n,i),c=i.map(e=>n.groups[e.group]),l=i.map(e=>e.channels.map(t=>n.groups[e.group].channels[t])),u=[...n.events];async function*d(e){for await(let t of e)t.events&&u.push(...t.events),yield t}let f={files:t,plan:n,io:r,selection:i,signal:o.signal},p=e.streamGroup&&i.length>1&&!n.interleaved?i.map(t=>AB(d(e.streamGroup({...f,selection:[t]},t.group)))):jB(d(e.stream(f)),new Map(i.map((e,t)=>[e.group,t]))),m=YB(n,i),h=a===`memory`?new GB(s,qB(m,s.length,r.size)):null,g=0,_=await WB(c,l,p,async e=>{h?h.append(e):await o.chunk(e);let t=Date.now();o.progress&&t-g>100&&(g=t,o.progress(Math.min(.99,r.bytesRead/Math.max(1,r.size))))},o.signal,!!h);return o.progress?.(1),u.sort((e,t)=>e.time-t.time),{columns:s,rows:_,table:h?.table(),events:u}}var QB=``+new URL(`assets/importer.worker-BblHvxro.js`,import.meta.url).href,$B=``+new URL(`assets/h5wasmModule-BCQWU2Gw.js`,import.meta.url).href,eV=()=>new OO(`cancelled`);function tV(){let e=kO(QB);return e.postMessage({type:`init`,h5Url:new URL($B,location.href).href}),e}var nV=null,rV=e=>{typeof requestIdleCallback==`function`?requestIdleCallback(e,{timeout:5e3}):setTimeout(e,1e3)};function iV(e,t=tV){t===tV&&typeof Worker>`u`||(nV&&nV.make!==t&&(nV.w.terminate(),nV=null),nV??={w:t(),h5:!1,make:t},e&&!nV.h5&&(nV.h5=!0,nV.w.postMessage({type:`warm`})))}function aV(e){if(nV?.make!==e)return{w:e(),rewarm:null};let{w:t,h5:n}=nV;return nV=null,{w:t,rewarm:n}}function oV(e,t,n,r,i){return!r&&typeof Worker>`u`?sV(e,t,n,i):lV(e,t,n,r??tV)}function sV(e,t,n,r=async e=>(await import(`./importers-CLmQyVrb.js`)).importerFor(e)){let i=new ke(t.main),a=null,o=null,s=e=>e.catch(e=>{throw n?.aborted?eV():f(e)});return{plan:()=>s((async()=>(a=await r(e),o=await KB(a,t,i)))()),read:(e,r,c={})=>(i.bytesRead=0,s(ZB(a,t,o,i,e,r,{...c,signal:n}))),close(){}}}var cV=3e4;function lV(e,t,n,r){let{w:i,rewarm:a}=aV(r),o=null,s=Promise.resolve(),c=Date.now(),l=-1,u=0,d=!1,f=e=>{let t=o;o=null,t?.reject(e)},p=e=>{d=!0,i.terminate(),f(e)},m=setInterval(()=>{o&&u===0&&Date.now()-c>cV&&p(Error(S))},1e3),h=()=>p(eV());n?.addEventListener(`abort`,h,{once:!0}),i.onmessage=e=>{let t=e.data,n=o;n&&((t.type!==`alive`||t.work!==l)&&(c=Date.now()),t.type===`alive`?l=t.work:t.type===`plan`?(o=null,n.resolve(t.plan)):t.type===`progress`?n.on.progress?.(t.fraction):t.type===`chunk`?(u++,s=s.then(()=>n.on.chunk(t.chunk)).then(()=>{u--,c=Date.now(),i.postMessage({type:`ack`})},e=>{u--,p(e instanceof Error?e:Error(String(e)))})):t.type===`done`?s.then(()=>{o===n&&(o=null,n.resolve(t.result))}):f(Error(t.message)))},i.onerror=e=>f(e instanceof Error?e:Error(`The import worker failed.`));let g=(e,t={})=>new Promise((r,a)=>{if(n?.aborted){a(eV());return}if(d){a(Error(S));return}o={resolve:r,reject:a,on:t},c=Date.now(),i.postMessage(e)});return{plan:()=>g({type:`plan`,importer:e,files:t}),read:(e,t,n)=>g({type:`read`,selection:e,mode:t},n),close:()=>{clearInterval(m),n?.removeEventListener(`abort`,h),i.terminate(),a!==null&&rV(()=>iV(a,r))}}}var uV=12e3,dV=(e,t)=>t.map(t=>({group:t,channels:e.groups[t].channels.map((e,t)=>t)}));function fV(e,t){let n=null;for(let r of t){let t=e.groups[r.group];!t.irregular&&(!n||t.samples>n.samples)&&(n={samples:t.samples,rate:t.rateHz})}return n?.rate??null}function pV(e,t,n,r){return{format:e.format,importer:t,startTime:e.startTime,groups:e.groups.map(e=>({name:e.name,channels:e.channels.length,samples:e.samples,rateHz:e.rateHz})),selection:n,combined:n.length>1?{groups:n.length,rateHz:fV(e,n)}:null,splitKey:r,channels:n.reduce((e,t)=>e+t.channels.length,0),notes:e.notes,meta:e.meta,events:[]}}async function mV(e,t,n,r,i,a){let o={meta:``,columnNames:n.columns.map(e=>e.name),units:n.columns.map(e=>e.unit),rows:Pe(n.table)},s=new IO(o);return{id:e,name:t,kind:`memory`,source:s,schema:await s.getSchema(),data:o,file:r,companions:i,info:{...a,events:n.events}}}async function hV(e,t,n,r,i,a,o,s,c){let l=Fz().then(e=>e.connect());l.catch(()=>void 0);let u=Zz(),d=JB(r,i),f=new DB({insertArrowTable:async(e,t)=>(await l).insertArrowTable(e,t)},u,d);try{let r=await n.read(i,`stream`,{progress:c,chunk:e=>f.append(e)});if(await f.flush(),f.rows===0)throw Error(`${t}: the file has no samples.`);let p=await l,m=await rB.attach(p,u,new Map(d.map(e=>[e.name,e.unit]))),h=await m.getSchema(),g=await m.sampleRows(uV);return{id:e,name:t,kind:`duckdb`,source:m,schema:h,data:{meta:``,columnNames:h.map(e=>e.name),units:h.map(e=>e.unit),rows:g},file:a,companions:o,info:{...s,events:r.events}}}catch(e){let t=await l.catch(()=>null);throw await t?.query(`DROP TABLE IF EXISTS ${Iz(u)}`).catch(()=>void 0),await t?.close().catch(()=>void 0),e}}async function gV(e,t){let{main:n,companions:r}=e,i=oV(e.format,{main:n,companions:r,keys:e.keys},t.signal,t.createWorker,t.find),a=[];try{t.priorInMemoryValues+n.size/8>1e8&&Fz().catch(()=>void 0);let o=await i.plan(),s=t.selection??t.initial??dV(o,o.defaultGroups??o.groups.map((e,t)=>t)),c=s.reduce((e,t)=>e+t.channels.length,0);if(!t.selection&&t.chooseChannels&&(t.pickChannels||o.pick||c>2e3)){let e=await t.chooseChannels({file:n.name,format:o.format,groups:o.groups.map(e=>({name:e.name,rateHz:e.rateHz,samples:e.samples,channels:e.channels.map(e=>({name:e.name,unit:e.unit}))})),selection:s,estimate:e=>XB(o,e,n.size),budget:iB,used:t.priorInMemoryValues,notes:o.notes});if(!e)throw new OO(`cancelled`);s=e.filter(e=>e.channels.length>0)}if(s.length===0)throw Error(`${n.name}: no channels to read.`);let l=!t.split&&(s.length===1||s.every(e=>o.groups[e.group].time.kind!==`index`))?[s]:s.map(e=>[e]),u=l.length>1?crypto.randomUUID():null,d=t.priorInMemoryValues;for(let s of l){let c=XB(o,s,n.size),f=l.length>1?`${n.name} · ${o.groups[s[0].group].name}`:n.name,p=pV(o,e.format,s,u),m=crypto.randomUUID();if(oB(0,c,d)===`memory`){let e=await i.read(s,`memory`,{progress:t.onProgress});a.push(await mV(m,f,e,n,r,p)),d+=c}else a.push(await hV(m,f,i,o,s,n,r,p,t.onProgress))}return a}catch(e){for(let e of a)e.source.dispose().catch(()=>void 0);throw t.signal?.aborted?new OO(`cancelled`):e}finally{i.close()}}function _V(e){return e.filter(e=>e.type===`number`).map(e=>e.name)}function vV(e,t,n=5e5){let r=1/0,i=-1/0,a=Math.max(1,Math.ceil(e.length/n));for(let n=0;n<e.length;n+=a){let a=e[n][t];typeof a==`number`&&(a<r&&(r=a),a>i&&(i=a))}if(!Number.isFinite(r)||!Number.isFinite(i))return{min:0,max:1};if(r===i){let e=Math.abs(r)*.05||1;return{min:r-e,max:i+e}}let o=(i-r)*.04;return{min:r-o,max:i+o}}function yV(e){switch(e.kind){case`multiband`:return e.series.length;case`parallelcoords`:return e.pcColumns.length;case`barchart`:return e.bcValueCols.length;case`radar`:return e.rdAxesCols.length;case`areachart`:return e.acYCols.length;case`cdfchart`:return e.cdValueCols.length;case`losscurve`:return e.lcLeftCols.length+e.lcRightCols.length;case`gauge`:return e.ggGauges.length;case`camera`:return 0;case`heatmap`:return e.hmColumns.length;case`xyzmesh`:return e.xyzColumns?.length??0;default:return 0}}function bV(e,t=6){if(!Number.isFinite(e)||e<=0)return 1;let n=e/t,r=10**Math.floor(Math.log10(n)),i=n/r,a=1;return a=i<=1?1:i<=2?2:i<=5?5:10,a*r}function xV(e){return Math.max(2,Math.min(6,Math.floor(e/64)))}function SV(e,t,n,r){let i=Math.max(e,t)-Math.min(e,t),a=n!==void 0&&n>0&&Number.isFinite(n)?n:bV(i,6);(a<=0||!Number.isFinite(a))&&(a=bV(Math.max(i,1),6));let o=r!==void 0&&r>0&&Number.isFinite(r)?r:a/5;return(o<=0||!Number.isFinite(o))&&(o=a/5),{majorStep:a,minorStep:o}}function CV(e,t,n){let r=Math.min(e,t),i=Math.max(e,t);if(n<=0||!Number.isFinite(n))return[];let a=[],o=Math.ceil(r/n-1e-12)*n,s=0;for(;o<=i+n*1e-9&&s++<1e4;)a.push(o),o+=n;return a}function wV(e,t,n,r){let i=Math.min(e,t),a=Math.max(e,t);if(n<=0||!Number.isFinite(n))return[];let o=e=>r.some(t=>Math.abs(e-t)<=(Math.abs(t)+1)*1e-9+1e-9),s=[],c=Math.ceil(i/n-1e-12)*n,l=0;for(;c<=a+n*1e-9&&l++<2e4;)o(c)||s.push(c),c+=n;return s}var TV={[-12]:`p`,[-9]:`n`,[-6]:`µ`,[-3]:`m`,0:``,3:`k`,6:`M`,9:`G`,12:`T`};function EV(e){if(!(e>0)||!Number.isFinite(e))return 0;let t=Math.max(0,-Math.floor(Math.log10(e)+1e-9));for(let n=t;n<=t+2;n++){let t=e*10**n;if(Math.abs(t-Math.round(t))<=1e-6*t)return n}return t+1}function DV(e,t){if(!Number.isFinite(e))return`—`;if(!(t>0)||!Number.isFinite(t))return OV(e);if(Math.abs(e)<t*1e-6)return`0`;let n=Math.floor(Math.log10(t)+1e-9);if(n>=3||n<-3){let r=3*Math.ceil((n-1)/3);if(r<-12||r>12)return e.toExponential(2);let i=e/10**r;if(r>0||Math.abs(i)<1e3)return i.toFixed(EV(t/10**r))+TV[r]}return e.toFixed(EV(t))}function OV(e){if(!Number.isFinite(e))return`—`;if(e===0)return`0`;let t=Math.abs(e);if(t<1e-12||t>=0x38d7ea4c68000)return e.toExponential(3);let n=0;(t<.001||t>=1e6)&&(n=3*Math.floor(Math.log10(t)/3));let r=e/10**n,i=Math.max(0,3-Math.floor(Math.log10(Math.abs(r))));return n!==0&&Math.abs(+r.toFixed(i))>=1e3&&(n+=3,r/=1e3,i=3),r.toFixed(i)+TV[n]}var kV=946684800,AV=4102444800;function jV(e,t,n){return/\(([^)]*)\)\s*$/.exec(e)?.[1].trim()===`s`&&n>t&&t>=kV&&n<=AV}var MV=new Map;function NV(e){let t=MV.get(e);if(!t){let n={day:`numeric`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hourCycle:`h23`};try{t=new Intl.DateTimeFormat(`en-GB`,{...n,timeZone:e})}catch{t=NV(void 0)}MV.set(e,t)}return t}var PV=new Map,FV=(e,t)=>{let n=Math.round(e*1e3),r=Math.floor(n/1e3),i=`${t??``}|${r}`,a=PV.get(i);if(!a){let e={};for(let{type:n,value:i}of NV(t).formatToParts(r*1e3))e[n]=i;let n=`${e.hour}:${e.minute}`;a={date:`${e.day} ${e.month}`,year:e.year,hm:n,hms:`${n}:${e.second}`},PV.size>=1024&&PV.clear(),PV.set(i,a)}return{...a,ms:String(n-r*1e3).padStart(3,`0`)}},IV,LV=new Set;function RV(e){if(e!==void 0)try{new Intl.DateTimeFormat(void 0,{timeZone:e})}catch{e=void 0}if(e!==IV){IV=e;for(let e of LV)e()}}var zV=()=>IV;function BV(e){return LV.add(e),()=>{LV.delete(e)}}function VV(e,t,n,r=IV){let i=FV(e,r);return t>=86400?i.date:n>86400?`${i.date} ${i.hm}`:t>=60?i.hm:t>=1?i.hms:`${i.hms}.${i.ms}`}function HV(e,t=IV){let n=FV(e,t);return`${n.date} ${n.year} ${n.hms}.${n.ms}`}var UV=[`#fb923c`,`#60a5fa`,`#4ade80`,`#f87171`,`#facc15`,`#22d3ee`,`#f472b6`,`#2dd4bf`,`#94a3b8`,`#a3e635`];function WV(e,t,n,r=UV){let i=r.length>0?r:UV;return e[t]??i[n%i.length]}function GV(e){return[e===`light`?`#000000`:`#ffffff`,...UV.slice(0,9)]}function KV(e,t=`dark`){let n=(e??[]).filter(e=>typeof e==`string`&&/^#[0-9a-f]{3}([0-9a-f]{3})?$/i.test(e));return n.length>0?n:GV(t)}var qV=[`class`,`data-theme`,`data-color-scheme`];function JV(e){return e?.closest(`[data-color-scheme]`)??document.documentElement}function YV(e){return JV(e).getAttribute(`data-color-scheme`)===`light`?`light`:`dark`}function XV(e,t){let n=new MutationObserver(t),r=new Set([document.documentElement,JV(e)]);for(let e of r)n.observe(e,{attributes:!0,attributeFilter:qV});return()=>n.disconnect()}function ZV(e,t){return!!t&&e.composedPath().includes(t)}var QV=[{value:`span`,label:`Span (max − min)`},{value:`mean`,label:`Mean`},{value:`max`,label:`Max`},{value:`min`,label:`Min`}];function $V(e,t){let n=[],r=YE(),i=-1;for(let a=0;a<e.length;a++){let o=e[a][t];if(typeof o!=`number`)continue;let s=XE(r,o);i<0?i=0:s&&(n.push({start:i,end:a}),i=a)}return i>=0&&n.push({start:i,end:e.length}),n}function eH(e,t){let n=[],r=e.length-1,i=Math.max(1,Math.floor(e.length/256)),a=t=>{let n=0,r=0,a=0;for(let o=0;o+1<e.length;o+=i){let i=e[o][t],s=e[o+1][t];typeof i!=`number`||typeof s!=`number`||(n++,s<i?r++:s===i&&a++)}return n<32||r<=.3*n&&a<=.9*n};for(let o of t){if(i>1&&!a(o))continue;let t=0,s=0,c=0,l=null,u=!1;for(let n of e){let e=n[o];if(typeof e==`number`){if(l!==null&&(c++,e>l?t++:e===l&&s++,c-t-s>.1*r||s>.5*r)){u=!0;break}l=e}}if(u||c===0||(t+s)/c<.9||t/c<.5)continue;let d=$V(e,o).length;d>1&&n.push({col:o,laps:d})}return n.sort((e,t)=>t.laps-e.laps).map(e=>e.col)}function tH(e,t){return eH(e,t)[0]??t[0]??``}function nH(e,t,n){if(n&&t.includes(n.channel)&&$V(e,n.channel).length>1)return{...n,metric:t.includes(n.metric)?n.metric:n.channel};let r=eH(e,t);if(r.length===0)return null;let i=r.find(e=>/time/i.test(e));return{channel:r[0],metric:i??r[0],stat:`span`}}function rH(e,t,n,r){let i=0,a=0,o=1/0,s=-1/0;for(let r=t.start;r<t.end;r++){let t=e[r][n];typeof t==`number`&&(i++,a+=t,t<o&&(o=t),t>s&&(s=t))}return i===0?null:r===`mean`?a/i:r===`max`?s:r===`min`?o:s-o}function iH(e){let t=e.filter(e=>e!==null);if(t.length===0)return null;let n=[...t].sort((e,t)=>e-t)[Math.floor(t.length/2)],r=t.filter(e=>e>=n*.8),i=Math.min(...r.length>1?r:t);return e.indexOf(i)}function aH(e,t){return t.trim()===`s`||/time/i.test(e)}function oH(e,t,n){if(e===null)return`—`;if(n&&e>=0){let t=Math.round(e*1e3),n=Math.floor(t/6e4);return`${n}:${((t-n*6e4)/1e3).toFixed(3).padStart(6,`0`)}`}let r=Math.abs(e),i=r!==0&&r<.01?OV(e):e.toFixed(r>=1e3?0:r>=100?1:3);return t.trim()?`${i} ${t.trim()}`:i}function sH(e,t){return`${e}::lap${t}`}var cH=(e,t,n)=>`kymoscope-workbook-export|3|${e}|${t??``}|${n??``}`,lH=e=>new TextEncoder().encode(e);async function uH(e,t){return{format:`kymoscope-workbook`,v:2,...await re(t,lH(JSON.stringify(e)),B)}}async function dH(e,t){let n=t.password?JSON.stringify(await uH(e,t.password)):JSON.stringify(e),r=await be(await Re(t.key),lH(n),cH(t.scope,t.scopeId,t.password?`password`:void 0));return{format:`kymoscope-workbook`,v:3,scope:t.scope,scope_id:t.scopeId,alg:`AES-256-GCM`,...r,...t.password?{inner:`password`}:{}}}function fH(e){return!!e&&typeof e==`object`&&e.format===`kymoscope-workbook`}function pH(e){return fH(e)?e.v===2?{v:2,scope:null,scopeId:null,password:!0}:e.v!==3||e.alg!==`AES-256-GCM`||typeof e.iv!=`string`||typeof e.ct!=`string`||![`user`,`org`,`any`].includes(e.scope)||e.scope===`any`!=(e.scope_id===null)||e.scope_id!==null&&typeof e.scope_id!=`string`||e.inner!==void 0&&e.inner!==`password`?null:{v:3,scope:e.scope,scopeId:e.scope_id,password:e.inner===`password`}:null}var mH=e=>{try{return JSON.parse(new TextDecoder().decode(e))}catch{throw new OO(`bad_file`)}};async function hH(e,t){let n=pH(e);if(!n)throw new OO(`bad_file`);let r=e;if(n.v===3){let i=e;if(!t.key)throw new OO(`scope_key_required`,{scope:n.scope,scopeId:n.scopeId});let a;try{a=await ae(await Re(t.key),i,cH(i.scope,i.scope_id,i.inner))}catch{throw new OO(`bad_file`)}if(r=mH(a),!n.password)return r;if(r?.v!==2||!fH(r))throw new OO(`bad_file`)}if(!t.password)throw new OO(`password_required`);let i;try{i=await Ve(t.password,r,B)}catch{throw new OO(`wrong_password`)}return mH(i)}var gH=new Set(Object.keys(tn));function _H(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{id:t,kind:n,rect:r}=e;return typeof t!=`string`||!gH.has(n)||!r||![r.x,r.y,r.w,r.h].every(e=>typeof e==`number`&&Number.isFinite(e))?[]:[{...e,rect:an(n,r,96)}]}):[]}var vH=e=>({name:e.name,xKey:e.xKey,panels:e.panels,panelChartSettings:e.panelChartSettings,panelChartBackgrounds:e.panelChartBackgrounds,...e.liveWindowSeconds===void 0?{}:{liveWindowSeconds:e.liveWindowSeconds}});function yH(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>{let n=t.beacon;return[e,n?.datasetId?{...t,beacon:{...n,datasetId:null}}:t]}))}function bH(e){return{version:2,worksheets:e.worksheets.map(e=>({...vH(e),panelChartSettings:yH(e.panelChartSettings)})),activeWorksheet:Math.max(0,e.worksheets.findIndex(t=>t.id===e.activeWorksheetId)),mathChannels:e.channels.map(e=>({name:e.name,formula:e.formula,units:e.units,enabled:e.enabled,...e.description?{description:e.description}:{}})),liveWindowSeconds:e.liveWindowSeconds,laps:e.laps?{channel:e.laps.channel,metric:e.laps.metric,stat:e.laps.stat}:null,...e.cycles?.length?{cycles:e.cycles}:{}}}function xH(e){return{version:1,kind:`worksheet`,exportedAt:new Date().toISOString(),worksheet:{name:e.name,xKey:e.xKey,panels:e.panels,panelChartSettings:e.panelChartSettings,panelChartBackgrounds:e.panelChartBackgrounds,...e.liveWindowSeconds===void 0?{}:{liveWindowSeconds:e.liveWindowSeconds}}}}function SH(e,t,n){let r={kind:e.kind,settings:t,background:n},i=e.title?.trim();return i&&(r.title=i),{version:1,kind:`chart`,exportedAt:new Date().toISOString(),chart:r}}function CH(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)})}async function wH(e){let t=await CH(e),n;try{n=JSON.parse(t)}catch{return{worksheets:[],errors:[`Not a valid JSON file.`]}}return AH(n)}var TH=new Set(QV.map(e=>e.value)),EH=/^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(?:rgba?|hsla?)\([0-9.,%\s/deg+-]+\)|[a-z]{3,24})$/i;function DH(e){return typeof e!=`string`||e.length>64||/[;{}<>\\]|\b(?:var|env|attr|url)\(/i.test(e)?!1:typeof CSS<`u`&&typeof CSS.supports==`function`?CSS.supports(`color`,e):EH.test(e.trim())}function OH(e){if(Array.isArray(e))return e.map(OH);if(!e||typeof e!=`object`)return e??{};let t={};for(let[n,r]of Object.entries(e))/colou?r$/i.test(n)&&typeof r==`string`&&!DH(r)||(t[n]=r&&typeof r==`object`?OH(r):r);return t}function kH(e){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e===null||DH(e)))}function AH(e){let t=e,n=t&&typeof t==`object`?t.version:void 0;if(!t||n!==1&&n!==2||!Array.isArray(t.worksheets))return{worksheets:[],errors:[`Unrecognized format. Is this a Kymoscope workbook file?`],activeIndex:0,mathChannels:[],liveWindowSeconds:void 0,laps:void 0,cycles:[]};let r=[],i=[];if(t.worksheets.forEach((e,t)=>{let n=e;if(typeof n?.name!=`string`||typeof n.xKey!=`string`){i.push(`Worksheet #${t+1} skipped: missing name or xKey.`);return}r.push({id:crypto.randomUUID(),name:n.name,xKey:n.xKey,panels:_H(n.panels),panelChartSettings:OH(n.panelChartSettings),panelChartBackgrounds:kH(n.panelChartBackgrounds),..._r(n.liveWindowSeconds)})}),n===1)return{worksheets:r,errors:i,activeIndex:0,mathChannels:[],liveWindowSeconds:void 0,laps:void 0,cycles:[]};let a=(Array.isArray(t.mathChannels)?t.mathChannels:[]).flatMap(e=>{let t=e;return typeof t?.name!=`string`||!t.name.trim()||typeof t.formula!=`string`?[]:[{name:t.name,formula:t.formula,units:typeof t.units==`string`?t.units:``,enabled:t.enabled!==!1,...typeof t.description==`string`&&t.description?{description:t.description}:{}}]}),o=t.liveWindowSeconds,s=t.laps,c=s&&typeof s.channel==`string`&&typeof s.metric==`string`&&TH.has(s.stat)?{channel:s.channel,metric:s.metric,stat:s.stat}:null,l=typeof t.activeWorksheet==`number`&&Number.isInteger(t.activeWorksheet)?t.activeWorksheet:0;return{worksheets:r,errors:i,mathChannels:a,laps:c,cycles:mD(t.cycles),activeIndex:Math.min(Math.max(0,l),Math.max(0,r.length-1)),liveWindowSeconds:o===null||typeof o==`number`&&o>0?o:void 0}}function jH(e){return e.some(e=>e.panels.length>0)}function MH(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.name!=`string`||typeof t.xKey!=`string`?null:{id:crypto.randomUUID(),name:t.name,xKey:t.xKey,panels:_H(t.panels),panelChartSettings:OH(t.panelChartSettings),panelChartBackgrounds:kH(t.panelChartBackgrounds),..._r(t.liveWindowSeconds)}}function NH(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.kind;if(typeof n!=`string`||!gH.has(n))return null;let r=hr({__chart:t.settings},``,1).__chart;if(!r||r.kind!==n)return null;let i={kind:n,settings:r,background:t.background===null||typeof t.background==`string`&&/^#[0-9a-fA-F]{6}$/.test(t.background)?t.background:null};return typeof t.title==`string`&&t.title.trim()&&(i.title=t.title),i}async function PH(e){let t=await CH(e),n;try{n=JSON.parse(t)}catch{return{type:`error`,errors:[`Not a valid JSON file.`]}}if(!n||typeof n!=`object`)return{type:`error`,errors:[`Unrecognized file.`]};if(n.format===`kymoscope-workbook`){let e=pH(n);return e?{type:`encrypted`,...e}:{type:`error`,errors:[`This file is from a newer version of Kymoscope.`]}}let r=n.kind;if(r===`worksheet`){let e=MH(n.worksheet);return e?{type:`worksheet`,worksheet:e}:{type:`error`,errors:[`Worksheet file is missing a name or X key.`]}}if(r===`chart`){let e=NH(n.chart);return e?{type:`chart`,chart:e}:{type:`error`,errors:[`Chart file is malformed or its settings do not match its type.`]}}let i=await wH(e);return i.worksheets.length===0&&i.errors.length>0?{type:`error`,errors:i.errors}:{type:`workspace`,worksheets:i.worksheets,errors:i.errors}}var FH=wB;function IH(e){let t=e.toLowerCase();return!t.startsWith(`.`)&&FH.some(e=>t.endsWith(e))}function LH(e,t=``){let n={name:t,path:``,dirs:[],files:[],allPaths:[]};for(let t of e){if(!IH(t.file.name))continue;let e=t.path.split(`/`).filter(Boolean),r=n;for(let t of e.slice(0,-1)){let e=r.path?`${r.path}/${t}`:t,n=r.dirs.find(e=>e.name===t);n||(n={name:t,path:e,dirs:[],files:[],allPaths:[]},r.dirs.push(n)),r=n}r.files.push(t)}let r=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`}).compare,i=e=>(e.dirs.sort((e,t)=>r(e.name,t.name)),e.files.sort((e,t)=>r(e.file.name,t.file.name)),e.allPaths=[...e.dirs.flatMap(i),...e.files.map(e=>e.path)],e.allPaths);return i(n),!n.files.length&&n.dirs.length===1?n.dirs[0]:n}function RH(e){return e.map(e=>({path:e.webkitRelativePath||e.name,file:e}))}async function zH(e){let t=[],n=async(e,r)=>{let i=r?`${r}/${e.name}`:e.name;if(e.isFile){let n=await new Promise((t,n)=>e.file(t,n));t.push({path:i,file:n});return}if(!e.isDirectory)return;let a=e.createReader();for(;;){let e=await new Promise((e,t)=>a.readEntries(e,t));if(!e.length)break;for(let t of e)await n(t,i)}};for(let t of e)await n(t,``);return t}function BH(){return typeof window.showDirectoryPicker==`function`}async function VH(){let e;try{e=await window.showDirectoryPicker({mode:`read`})}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return null;throw e}let t=[],n=async(e,r)=>{for await(let i of e.values()){let e=`${r}/${i.name}`;i.kind===`file`?t.push({path:e,file:await i.getFile()}):await n(i,e)}};return await n(e,e.name),t}var HH={1:`dohstRIUBeOkkAXOTXhhEkXanWzz-V4M518JBqTehRM`};function UH(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`)+`===`.slice((e.length+3)%4),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}function WH(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n.startsWith(`*.`)?r.endsWith(n.slice(1))&&r.length>n.length-1:n===r}function GH(e){try{let t=JSON.parse(new TextDecoder().decode(UH(e)));return typeof t.sub!=`string`||typeof t.exp!=`number`||!Array.isArray(t.domains)||!t.domains.every(e=>typeof e==`string`)||t.kid!==void 0&&typeof t.kid!=`string`?null:t}catch{return null}}async function KH(e,t,n,r){if(!e)return{ok:!1,reason:`missing`};if(typeof e!=`string`)return{ok:!1,reason:`malformed`};let i=e.trim().split(`.`);if(i.length!==2||!i[0]||!i[1])return{ok:!1,reason:`malformed`};let a=GH(i[0]);if(!a)return{ok:!1,reason:`malformed`};let o=a.kid??`1`,s=typeof n==`string`?n:Object.hasOwn(n,o)?n[o]:void 0;if(!s)return{ok:!1,reason:`bad_signature`};let c;try{let e=await crypto.subtle.importKey(`raw`,UH(s),`Ed25519`,!1,[`verify`]);c=await crypto.subtle.verify(`Ed25519`,e,UH(i[1]),new TextEncoder().encode(i[0]))}catch{return{ok:!1,reason:`unsupported`}}return c?a.exp<r?{ok:!1,reason:`expired`}:a.domains.some(e=>WH(e,t))?{ok:!0,sub:a.sub,exp:a.exp}:{ok:!1,reason:`domain`}:{ok:!1,reason:`bad_signature`}}function qH(e,t){return KH(e,t,HH,Date.now()/1e3)}var Q={sans:`system-ui, sans-serif`,mono:`ui-monospace, monospace`};function JH(e){let t=e.getTransform().a||1;e.font=`13px ${Q.sans}`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`No data to plot`,e.canvas.width/t/2,e.canvas.height/t/2)}function YH(){let e=new Set;return{publish(t,n){for(let r of e)r(t,n)},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}function XH(){return kt(`span`,{className:`kymoscope-attribution`,role:`note`,style:{position:`absolute`,right:10,bottom:8,zIndex:50,pointerEvents:`none`,font:`500 11px/1.2 var(--font-sans, system-ui)`,letterSpacing:`0.02em`,padding:`4px 8px`,borderRadius:999,color:`var(--text-muted, #8a93a6)`,background:`color-mix(in oklch, var(--bg-elevated, #1b2130) 88%, transparent)`,border:`1px solid var(--border, #33405a)`},children:[`Powered by `,q(`strong`,{style:{color:`var(--accent, #f5a524)`,fontWeight:700},children:`Kymoscope`})]})}function ZH(){let e=new Map;return{on(t,n){let r=e.get(t);return r||e.set(t,r=new Set),r.add(n),()=>{r.delete(n)}},emit(t,n){for(let r of e.get(t)??[])try{r(n)}catch(e){console.error(`[kymoscope] listener failed`,e)}},clear(){e.clear()}}}function QH(e,t=1){let n=e.trim().replace(/^#/,``);n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]);let r=n.length===8?parseInt(n.slice(6),16)/255:1;n.length===8&&(n=n.slice(0,6));let i=parseInt(n,16);return n.length!==6||Number.isNaN(i)||Number.isNaN(r)?[0,0,0,t]:[(i>>16&255)/255,(i>>8&255)/255,(i&255)/255,r*t]}function $H(e){return Math.max(0,(e>>1)-1)}var eU=2.5,tU=`#version 300 es
72
72
  in vec2 a_corner; // static quad corner: (±1, ±1)
73
73
  in vec2 a_a; // per-instance: segment start (CSS px)
74
74
  in vec2 a_b; // per-instance: segment end (CSS px)
@@ -93,7 +93,7 @@ void main() {
93
93
  v_pos = pos;
94
94
  vec2 clip = pos / u_resolution * 2.0 - 1.0; // 0..1 → -1..1
95
95
  gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0); // flip y (px down → clip up)
96
- }`,QV=`#version 300 es
96
+ }`,nU=`#version 300 es
97
97
  precision highp float;
98
98
  uniform vec4 u_color;
99
99
  uniform float u_halfWidth; // visible half-thickness (CSS px)
@@ -124,7 +124,7 @@ void main() {
124
124
  // correct on premultiplied colour — straight alpha would darken the AA fringe.
125
125
  float a = u_color.a * cov;
126
126
  outColor = vec4(u_color.rgb * a, a);
127
- }`;function $V(e,t,n){let r=e.createShader(t);return r?(e.shaderSource(r,n),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(console.error(`glLines shader compile failed:`,e.getShaderInfoLog(r)),e.deleteShader(r),null)):null}function eH(e,t=1){let n=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0});if(!n)return null;let r=$V(n,n.VERTEX_SHADER,ZV),i=$V(n,n.FRAGMENT_SHADER,QV);if(!r||!i)return null;let a=n.createProgram();if(!a||(n.attachShader(a,r),n.attachShader(a,i),n.linkProgram(a),!n.getProgramParameter(a,n.LINK_STATUS)))return null;let o=n.getAttribLocation(a,`a_corner`),s=n.getAttribLocation(a,`a_a`),c=n.getAttribLocation(a,`a_b`),l=n.getUniformLocation(a,`u_resolution`),u=n.getUniformLocation(a,`u_color`),d=n.getUniformLocation(a,`u_ext`),f=n.getUniformLocation(a,`u_halfWidth`),p=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,p),n.bufferData(n.ARRAY_BUFFER,Float32Array.from([-1,-1,1,-1,-1,1,1,1]),n.STATIC_DRAW);let m=n.createBuffer(),h=n.createFramebuffer(),g=n.createRenderbuffer(),_=1,v=1,y=(`clientWidth`in e?e.clientWidth:0)||1,b=(`clientHeight`in e?e.clientHeight:0)||1,x=1;return{resize(t,r,i){y=Math.max(1,t),b=Math.max(1,r),x=i*2,e.width=Math.round(y*i),e.height=Math.round(b*i),_=e.width*2,v=e.height*2,h&&g&&(n.bindRenderbuffer(n.RENDERBUFFER,g),n.renderbufferStorage(n.RENDERBUFFER,n.RGBA8,_,v),n.bindFramebuffer(n.FRAMEBUFFER,h),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,g),n.bindFramebuffer(n.FRAMEBUFFER,null))},draw(r){n.bindFramebuffer(n.FRAMEBUFFER,h),n.viewport(0,0,h?_:e.width,h?v:e.height),n.disable(n.SCISSOR_TEST),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(a),n.uniform2f(l,y,b),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE_MINUS_SRC_ALPHA),n.bindBuffer(n.ARRAY_BUFFER,p),n.enableVertexAttribArray(o),n.vertexAttribPointer(o,2,n.FLOAT,!1,0,0),n.vertexAttribDivisor(o,0),n.bindBuffer(n.ARRAY_BUFFER,m),n.enableVertexAttribArray(s),n.vertexAttribPointer(s,2,n.FLOAT,!1,8,0),n.vertexAttribDivisor(s,1),n.enableVertexAttribArray(c),n.vertexAttribPointer(c,2,n.FLOAT,!1,8,8),n.vertexAttribDivisor(c,1);for(let e of r){let r=YV(e.points.length);if(r<1)continue;e.clip?(n.enable(n.SCISSOR_TEST),n.scissor(Math.round(e.clip.x*x),Math.round((b-e.clip.y-e.clip.h)*x),Math.round(e.clip.w*x),Math.round(e.clip.h*x))):n.disable(n.SCISSOR_TEST),n.bufferData(n.ARRAY_BUFFER,e.points,n.DYNAMIC_DRAW),n.uniform4fv(u,e.color);let i=e.width??t;n.uniform1f(d,i/2+XV),n.uniform1f(f,i/2),n.drawArraysInstanced(n.TRIANGLE_STRIP,0,4,r)}n.disable(n.SCISSOR_TEST),n.vertexAttribDivisor(s,0),n.vertexAttribDivisor(c,0),h&&(n.bindFramebuffer(n.READ_FRAMEBUFFER,h),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),n.blitFramebuffer(0,0,_,v,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.LINEAR),n.bindFramebuffer(n.FRAMEBUFFER,null))},dispose(){n.deleteBuffer(p),n.deleteBuffer(m),n.deleteFramebuffer(h),n.deleteRenderbuffer(g),n.deleteProgram(a),n.deleteShader(r),n.deleteShader(i),n.getExtension(`WEBGL_lose_context`)?.loseContext()}}}var tH=12,nH=0,rH=null,iH=new Set;function aH(){if(nH<tH)return!0;for(let e of[...iH]){if(nH<tH)break;e.hidden()&&e.evict()}return nH<tH}function oH(e){nH++,e&&iH.add(e);let t=!1;return()=>{t||(t=!0,nH--,e&&iH.delete(e))}}var sH=new Set;function cH(){if(rH&&!rH.gl.isContextLost())return rH;let e=document.createElement(`canvas`);e.width=1,e.height=1;let t=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0,preserveDrawingBuffer:!1});return rH=t?{canvas:e,gl:t}:null,e.addEventListener(`webglcontextlost`,e=>{e.preventDefault(),setTimeout(()=>{for(let e of[...sH])e()},0)}),rH}function lH(e,t=!1){if(t&&nH<tH){let t=oH();return{canvas:e,shared:!1,present(){},lost:()=>!1,release(){t();try{e.getContext(`webgl2`)?.getExtension(`WEBGL_lose_context`)?.loseContext()}catch{}}}}let n=cH();if(!n)return{canvas:e,shared:!1,present(){},lost:()=>!1,release(){}};let r=1,i=1,a={get width(){return r},set width(e){r=Math.max(1,Math.round(e)),n.canvas.width<r&&(n.canvas.width=r)},get height(){return i},set height(e){i=Math.max(1,Math.round(e)),n.canvas.height<i&&(n.canvas.height=i)},getContext(e){return e===`webgl2`?n.gl:null}},o=null;return{canvas:a,shared:!0,present(){e.width!==r&&(e.width=r),e.height!==i&&(e.height=i),o??=e.getContext(`2d`),o&&(o.globalCompositeOperation=`copy`,o.drawImage(n.canvas,0,n.canvas.height-i,r,i,0,0,r,i),o.globalCompositeOperation=`source-over`)},lost:()=>n.gl.isContextLost(),release(){}}}var uH=new WeakMap;function dH(e,t,n){let r=uH.get(e);return r||uH.set(e,r=new Map),r.has(t)||r.set(t,n()),r.get(t)}function fH(e,t){let n=lH(e),r=t(n.canvas);if(!r)return n.release(),null;let i=new Map,a=(e,t)=>{let n=t[0];return typeof n==`string`||typeof n==`number`&&(e===`setData`||e===`setStyles`)?`${e}:${n}`:e},o=(e,t)=>{let n=e=>{for(let t of[...i.keys()]){let n=t.indexOf(`:`);n>0&&!e(t.slice(n+1))&&i.delete(t)}};if(e===`remove`||e===`clearLayer`)n(e=>e!==String(t[0]));else if(e===`keep`&&Array.isArray(t[0])){let e=new Set(t[0].map(String));n(t=>e.has(t))}},s=()=>{try{r.dispose()}catch{}n.release(),n=lH(e);let a=t(n.canvas);if(!a)return!1;r=a;let o=[...i.values()];for(let e of o.filter(e=>e.name===`resize`).concat(o.filter(e=>e.name!==`resize`)))r[e.name](...e.args);return!0},c=()=>(n.lost()&&s(),r),l=()=>{n.lost()&&s()&&(r.render(),n.present())};return sH.add(l),new Proxy({},{get(e,t){if(t===`dispose`)return()=>{sH.delete(l),i.clear(),r.dispose(),n.release()};if(t===`render`)return()=>{c().render(),n.present()};let s=c()[t];return typeof s!=`function`||typeof t!=`string`?s:(...e)=>{if(o(t,e),t.startsWith(`set`)||t===`resize`){let n=a(t,e),r=i.get(n),o=t===`setData`&&typeof e[0]==`number`&&e[1]===null&&r?[e[0],r.args[1],r.args[2],...e.slice(3)]:e;i.delete(n),i.set(n,{name:t,args:o})}return s.apply(c(),e)}}})}var pH=1024,mH=`#version 300 es
127
+ }`;function rU(e,t,n){let r=e.createShader(t);return r?(e.shaderSource(r,n),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(console.error(`glLines shader compile failed:`,e.getShaderInfoLog(r)),e.deleteShader(r),null)):null}function iU(e,t=1){let n=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0});if(!n)return null;let r=rU(n,n.VERTEX_SHADER,tU),i=rU(n,n.FRAGMENT_SHADER,nU);if(!r||!i)return null;let a=n.createProgram();if(!a||(n.attachShader(a,r),n.attachShader(a,i),n.linkProgram(a),!n.getProgramParameter(a,n.LINK_STATUS)))return null;let o=n.getAttribLocation(a,`a_corner`),s=n.getAttribLocation(a,`a_a`),c=n.getAttribLocation(a,`a_b`),l=n.getUniformLocation(a,`u_resolution`),u=n.getUniformLocation(a,`u_color`),d=n.getUniformLocation(a,`u_ext`),f=n.getUniformLocation(a,`u_halfWidth`),p=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,p),n.bufferData(n.ARRAY_BUFFER,Float32Array.from([-1,-1,1,-1,-1,1,1,1]),n.STATIC_DRAW);let m=n.createBuffer(),h=n.createFramebuffer(),g=n.createRenderbuffer(),_=1,v=1,y=(`clientWidth`in e?e.clientWidth:0)||1,b=(`clientHeight`in e?e.clientHeight:0)||1,x=1;return{resize(t,r,i){y=Math.max(1,t),b=Math.max(1,r),x=i*2,e.width=Math.round(y*i),e.height=Math.round(b*i),_=e.width*2,v=e.height*2,h&&g&&(n.bindRenderbuffer(n.RENDERBUFFER,g),n.renderbufferStorage(n.RENDERBUFFER,n.RGBA8,_,v),n.bindFramebuffer(n.FRAMEBUFFER,h),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,g),n.bindFramebuffer(n.FRAMEBUFFER,null))},draw(r){n.bindFramebuffer(n.FRAMEBUFFER,h),n.viewport(0,0,h?_:e.width,h?v:e.height),n.disable(n.SCISSOR_TEST),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.useProgram(a),n.uniform2f(l,y,b),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE_MINUS_SRC_ALPHA),n.bindBuffer(n.ARRAY_BUFFER,p),n.enableVertexAttribArray(o),n.vertexAttribPointer(o,2,n.FLOAT,!1,0,0),n.vertexAttribDivisor(o,0),n.bindBuffer(n.ARRAY_BUFFER,m),n.enableVertexAttribArray(s),n.vertexAttribPointer(s,2,n.FLOAT,!1,8,0),n.vertexAttribDivisor(s,1),n.enableVertexAttribArray(c),n.vertexAttribPointer(c,2,n.FLOAT,!1,8,8),n.vertexAttribDivisor(c,1);for(let e of r){let r=$H(e.points.length);if(r<1)continue;e.clip?(n.enable(n.SCISSOR_TEST),n.scissor(Math.round(e.clip.x*x),Math.round((b-e.clip.y-e.clip.h)*x),Math.round(e.clip.w*x),Math.round(e.clip.h*x))):n.disable(n.SCISSOR_TEST),n.bufferData(n.ARRAY_BUFFER,e.points,n.DYNAMIC_DRAW),n.uniform4fv(u,e.color);let i=e.width??t;n.uniform1f(d,i/2+eU),n.uniform1f(f,i/2),n.drawArraysInstanced(n.TRIANGLE_STRIP,0,4,r)}n.disable(n.SCISSOR_TEST),n.vertexAttribDivisor(s,0),n.vertexAttribDivisor(c,0),h&&(n.bindFramebuffer(n.READ_FRAMEBUFFER,h),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),n.blitFramebuffer(0,0,_,v,0,0,e.width,e.height,n.COLOR_BUFFER_BIT,n.LINEAR),n.bindFramebuffer(n.FRAMEBUFFER,null))},dispose(){n.deleteBuffer(p),n.deleteBuffer(m),n.deleteFramebuffer(h),n.deleteRenderbuffer(g),n.deleteProgram(a),n.deleteShader(r),n.deleteShader(i),n.getExtension(`WEBGL_lose_context`)?.loseContext()}}}var aU=12,oU=0,sU=null,cU=new Set;function lU(){if(oU<aU)return!0;for(let e of[...cU]){if(oU<aU)break;e.hidden()&&e.evict()}return oU<aU}function uU(e){oU++,e&&cU.add(e);let t=!1;return()=>{t||(t=!0,oU--,e&&cU.delete(e))}}var dU=new Set;function fU(){if(sU&&!sU.gl.isContextLost())return sU;let e=document.createElement(`canvas`);e.width=1,e.height=1;let t=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0,preserveDrawingBuffer:!1});return sU=t?{canvas:e,gl:t}:null,e.addEventListener(`webglcontextlost`,e=>{e.preventDefault(),setTimeout(()=>{for(let e of[...dU])e()},0)}),sU}function pU(e,t=!1){if(t&&oU<aU){let t=uU();return{canvas:e,shared:!1,present(){},lost:()=>!1,release(){t();try{e.getContext(`webgl2`)?.getExtension(`WEBGL_lose_context`)?.loseContext()}catch{}}}}let n=fU();if(!n)return{canvas:e,shared:!1,present(){},lost:()=>!1,release(){}};let r=1,i=1,a={get width(){return r},set width(e){r=Math.max(1,Math.round(e)),n.canvas.width<r&&(n.canvas.width=r)},get height(){return i},set height(e){i=Math.max(1,Math.round(e)),n.canvas.height<i&&(n.canvas.height=i)},getContext(e){return e===`webgl2`?n.gl:null}},o=null;return{canvas:a,shared:!0,present(){e.width!==r&&(e.width=r),e.height!==i&&(e.height=i),o??=e.getContext(`2d`),o&&(o.globalCompositeOperation=`copy`,o.drawImage(n.canvas,0,n.canvas.height-i,r,i,0,0,r,i),o.globalCompositeOperation=`source-over`)},lost:()=>n.gl.isContextLost(),release(){}}}var mU=new WeakMap;function hU(e,t,n){let r=mU.get(e);return r||mU.set(e,r=new Map),r.has(t)||r.set(t,n()),r.get(t)}function gU(e,t){let n=pU(e),r=t(n.canvas);if(!r)return n.release(),null;let i=new Map,a=(e,t)=>{let n=t[0];return typeof n==`string`||typeof n==`number`&&(e===`setData`||e===`setStyles`)?`${e}:${n}`:e},o=(e,t)=>{let n=e=>{for(let t of[...i.keys()]){let n=t.indexOf(`:`);n>0&&!e(t.slice(n+1))&&i.delete(t)}};if(e===`remove`||e===`clearLayer`)n(e=>e!==String(t[0]));else if(e===`keep`&&Array.isArray(t[0])){let e=new Set(t[0].map(String));n(t=>e.has(t))}},s=()=>{try{r.dispose()}catch{}n.release(),n=pU(e);let a=t(n.canvas);if(!a)return!1;r=a;let o=[...i.values()];for(let e of o.filter(e=>e.name===`resize`).concat(o.filter(e=>e.name!==`resize`)))r[e.name](...e.args);return!0},c=()=>(n.lost()&&s(),r),l=()=>{n.lost()&&s()&&(r.render(),n.present())};return dU.add(l),new Proxy({},{get(e,t){if(t===`dispose`)return()=>{dU.delete(l),i.clear(),r.dispose(),n.release()};if(t===`render`)return()=>{c().render(),n.present()};let s=c()[t];return typeof s!=`function`||typeof t!=`string`?s:(...e)=>{if(o(t,e),t.startsWith(`set`)||t===`resize`){let n=a(t,e),r=i.get(n),o=t===`setData`&&typeof e[0]==`number`&&e[1]===null&&r?[e[0],r.args[1],r.args[2],...e.slice(3)]:e;i.delete(n),i.set(n,{name:t,args:o})}return s.apply(c(),e)}}})}var _U=1024,vU=`#version 300 es
128
128
  in vec2 a_corner; // static quad corner: (±1, ±1)
129
129
  in float a_ax; // per instance: segment start/end X (relative to the layer origin)
130
130
  in float a_bx;
@@ -148,7 +148,7 @@ flat out float v_halfWidth;
148
148
  flat out vec4 v_clip; // left, top, right, bottom (CSS px)
149
149
  out vec2 v_pos;
150
150
  vec4 style(int sid, int k) {
151
- return texelFetch(u_styles, ivec2((sid % ${pH}) * 3 + k, sid / ${pH}), 0);
151
+ return texelFetch(u_styles, ivec2((sid % ${_U}) * 3 + k, sid / ${_U}), 0);
152
152
  }
153
153
  void main() {
154
154
  int sid = int(a_sid + 0.5);
@@ -183,7 +183,7 @@ void main() {
183
183
  v_clip = vec4(u_left, top, min(u_left + u_plotW, u_cutPx), bottom);
184
184
  vec2 clip = pos / u_resolution * 2.0 - 1.0;
185
185
  gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);
186
- }`,hH=`#version 300 es
186
+ }`,yU=`#version 300 es
187
187
  precision highp float;
188
188
  flat in vec2 v_a;
189
189
  flat in vec2 v_b;
@@ -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 gH(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 _H(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=>gH(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 vH(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 yH(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 bH(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=$V(n,n.VERTEX_SHADER,mH),t=$V(n,n.FRAGMENT_SHADER,hH);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():dH(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=_H(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=vH(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/pH)),o=3*Math.min(Math.max(i,1),pH),s=new Float32Array(o*a*4);for(let n=0;n<i;n++){let i=r[n],a=(Math.floor(n/pH)*o+n%pH*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+XV,+(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)&&yH(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 xH=[],SH=12,CH=!1,wH=!1,TH=0,EH=3,DH=1;function OH(){return!CH&&typeof Worker<`u`&&typeof HTMLCanvasElement<`u`&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen==`function`}var kH=`kymoscope-gl-first-frame`;function AH(e,t=1,n,r,i){if(typeof e.transferControlToOffscreen!=`function`||typeof Worker>`u`)return null;let a,o=xH.pop();try{a=o??WE(``+new URL(`assets/offscreenLineWorker-C-_uNa_H.js`,import.meta.url).href)}catch{return CH=!0,null}let s;try{s=e.transferControlToOffscreen()}catch{return o?xH.push(o):a.terminate(),null}let c=()=>{},l=DH++,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`&&(wH=!0,performance.mark?.(kH),c()))},a.onerror=()=>{u=!0,(!wH||++TH>=EH)&&(CH=!0),n?.()};let d=oH(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&&!CH&&xH.length<SH;try{a.postMessage({type:`dispose`})}catch{e=!1}e?xH.push(a):a.terminate(),d()}},g=i?jH(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 jH(e,t=1){let n=fH(e,e=>bH(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 MH=new Set;function NH(e){MH.add(e)}function PH(e){MH.delete(e)}function FH(){let e=typeof window>`u`?[]:[window];for(let t of MH)t.closed||e.push(t);return e}var IH=1,LH=new Map;function RH(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 zH(e){let t=IH++,n=FH();if(n.length===1){let r=n[0],i=r.requestAnimationFrame(n=>{LH.delete(t),e(RH(r,n))});return LH.set(t,[{w:n[0],id:i}]),t}let r=[];for(let i of n)r.push({w:i,id:i.requestAnimationFrame(n=>{LH.has(t)&&(BH(t),e(RH(i,n)))})});return LH.set(t,r),t}function BH(e){if(e==null)return;let t=LH.get(e);if(t){LH.delete(e);for(let{w:e,id:n}of t)e.closed||e.cancelAnimationFrame(n)}}var VH=new WeakMap;function HH(e){e&&VH.set(e,(VH.get(e)??0)+1)}function UH(e){let t=VH.get(e)??0;for(let n of e.querySelectorAll(`*`))t+=VH.get(n)??0;return t}function WH(){return FH().every(e=>e.document.hidden)}var GH=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 KH(e){return!!e&&e.isConnected&&typeof e.checkVisibility==`function`&&!e.checkVisibility()}function qH(e,t){let n=0,r=null,i=()=>KH(t()),a=t=>{n=0,!i()&&(r=t,e())};return{schedule(){n||=zH(a)},now(){if(i())return;let o=t()?.ownerDocument?.timeline?.currentTime;if(typeof o!=`number`||o===r){n||=zH(a);return}n&&=(BH(n),0),r=o,e()},cancel(){n&&BH(n),n=0}}}var JH=.6,YH=16,XH={ts:-1,work:0,floor:1/0},ZH=1/0;function QH(e,t=-1/0){if(e!==XH.ts){if(e>XH.ts&&e<XH.ts+XH.work/JH)return!1;XH={ts:e,work:0,floor:ZH},ZH=1/0}return XH.work>=YH||t>XH.floor?(ZH=Math.min(ZH,t),!1):!0}function $H(e,t){e===XH.ts&&(XH.work+=t)}function eU(e,t=typeof window>`u`?null:e=>{zH(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 tU(e,t,n,r,i){return r+(e-t)/n*(i-r)}function nU(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 rU(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 iU(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 aU(e,t){return!(e>0)||!(t>0)?1:1-Math.exp(-e/t)}function oU(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 sU(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 cU(e,t){return e>0?Math.min(8e3,Math.max(400,Math.round(e*t*2))):2e3}var lU=.5;function uU(e,t,n,r=lU){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 dU(e=0){return{d:null,lastT:NaN,wall:0,base:NaN,wait:e,waitAge:0,gap:NaN}}var fU=new Map;function pU(e,t,n,r){let i=fU.get(e);if(i||fU.set(e,i={p:dU(),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=DU(i.p,t,a,r),i.d}function mU(){let e;for(let t of fU.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 hU(e){return Math.min(CU,e.wait*1.2+.05)}function gU(e){return Number.isFinite(e.gap)?Math.min(e.gap,hU(e)):0}function _U(e){let t=fU.get(e);return t?gU(t.p):0}function vU(e){let t=fU.get(e);return t?hU(t.p):0}function yU(e,t,n){let r=e(t);if(!(n>0))return r;let i=(r-e(t-bU))/bU;return Number.isFinite(i)&&i>=0?r+i*n:r}var bU=.25,xU=1,SU=250,CU=3,wU=90,TU=30,EU=.001;function DU(e,t,n,r){if(!Number.isFinite(t))return t;let i=n/1e3;e.wall+=i;let a=n>SU&&e.d!==null,o=e.lastT;if(t<e.lastT&&Object.assign(e,dU(),{wall:e.wall}),t<=e.lastT)e.base+=i*EU;else{let n=e.wall-t;e.base=Number.isNaN(e.base)?n:Math.min(e.base+i*EU,n);let r=t-o;r>0&&r<xU&&(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(CU,s),e.waitAge=0):s>e.wait*.8?e.waitAge=0:e.waitAge>wU&&(e.wait*=Math.exp(-i/TU)));let c=e.wall-e.base-hU(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 OU=(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),kU=(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),AU=(e,t)=>e.left+OU(e.x,t)*e.width,jU=(e,t)=>kU(e.x,(t-e.left)/(e.width||1)),MU=(e,t)=>e.top+(1-OU(e.y,t))*e.height,NU=e=>!e||Number.isFinite(e.v0)&&Number.isFinite(e.v1)&&e.v0!==e.v1&&(!e.log||e.v0>0&&e.v1>0),PU=(e,t)=>e===t||!!e&&!!t&&e.v0===t.v0&&e.v1===t.v1&&!!e.log==!!t.log;function FU(){let e=null,t=new Set;return{get:()=>e,set:n=>{if(n&&(n.width>0&&n.height>0?(!NU(n.x)||!NU(n.y))&&(n={...n,x:NU(n.x)?n.x:void 0,y:NU(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&&PU(n.x,e.x)&&PU(n.y,e.y))){e=n;for(let e of[...t])e()}},subscribe:e=>(t.add(e),()=>{t.delete(e)})}}var IU=gt(()=>{}),LU=()=>xt(IU),RU=`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`,zU=[5,4],BU=null;function VU(e,t,n,r){typeof Path2D>`u`||(BU??=new Path2D(RU),e.save(),e.setLineDash([]),e.translate(t,n),e.fillStyle=r,e.fill(BU),e.restore())}var HU=(()=>{try{return localStorage.getItem(`glLines`)!==`0`}catch{return!0}})(),UU=(()=>{try{return localStorage.getItem(`offscreenGl`)!==`0`}catch{return!0}})(),WU=70;function GU(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}var KU={top:14,right:160,bottom:40,left:110},qU={top:14,right:100,bottom:40,left:70},JU=640,YU={top:3,right:3,bottom:3,left:3},XU=260;function ZU(e){return e<XU?YU:e<JU?qU:KU}var QU=220,$U=.05,eW=2e3,tW=4,nW=1e3/120,rW=`11.25px ${Q.mono}`,iW=11*1.125,aW=24*1.125,oW=aW-iW+26,sW=.6,cW=13,lW=10,uW=5,dW=14,fW=4;function pW(e,t,n){return Math.min(n,Math.max(t,e))}function mW(e,t,n,r,i){let a=Math.min(r,i),o=Math.max(r,i);return t+(1-pW(o===a?.5:(e-a)/(o-a),0,1))*(n-t)}function hW(e,t,n,r){let i=e+t;return{bandTop:i-r/100*t,bandBottom:i-n/100*t}}function gW(e){return e.replace(/__(\d+|ref)$/,``)}function _W(e,t,n){let r=Math.floor((n-t-iW)/cW)+1;return Math.max(0,Math.min(e,r))}function vW(e){let t=0;for(let n of e)t+=n.length;return t}function yW(e,t){let n=e.cols.get(t);return n?new Float32Array(n):new Float32Array(e.length).fill(NaN)}function bW(e){let t=new Map;for(let n of e){let e=gW(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=gW(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 xW(e,t,n){let r=new Map,i=e.map((e,r)=>{let{bandTop:i}=hW(t,n,e.leader.bandFromPct,e.leader.bandToPct);return{g:e,i:r,bandTop:i,blockDY:e.members.length>1?iW+(e.members.length+1)*cW:oW}});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+iW,o=Math.max(i,a),s=o-iW;r.set(e.leader.id,s),a=o+n}return r}function SW(e,t){let n=e.cols.get(t);if(!n)return 0;let r=e.x;return n.length===e.length&&A.has(n)?CW(r,e.length):TW(r,e.length,e=>Number.isFinite(n[e]))}function CW(e,t){let n=wW.get(e);return n===void 0&&(n=TW(e,t,()=>!0),wW.set(e,n)),n}var wW=me(new WeakMap);function TW(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 EW(e,t){return e>0?Math.max(e*4,t*1e-9):Math.max(t*1e-6,1e-12)}var DW=1e30,OW=250;function kW({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=LU(),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(eW),le=K(y),ue=K(null),de=K(dU()),fe=K(0),pe=K(void 0),me=K(0),he=K(0),ge=K(16),_e=K(!0),ve=K(!1),[ye,be]=wt(0),xe=()=>KH(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=Tt(tB,eB),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=Ct(()=>{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 iU(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 rU(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,EW(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<OW);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=SW(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},HH(A.current))}let i=ZU(t),a=i===YU,{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),vW(C)<2||u<=0||d<=0){if(r.fillStyle=p,r.font=`13px ${Q.sans}`,WV(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=bW(z),V=xW(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}=hW(o,d,e.bandFromPct,e.bandToPct),r=Math.min(e.scaleMin,e.scaleMax),i=Math.max(e.scaleMin,e.scaleMax),{majorStep:a,minorStep:s}=Lz(e.scaleMin,e.scaleMax,e.yMajorStep??0,e.yMinorStep??0),c=a,l=Rz(r,i,c);l.length>120&&(l=Rz(r,i,c=Lz(e.scaleMin,e.scaleMax,0,0).majorStep));let u=zz(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=Hz(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)+fW+dW+(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=cU(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(GU(v?.style??`dashed`));for(let a of i){let i=mW(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-fW;r.strokeStyle=a,r.lineWidth=1;for(let i of o){let a=mW(i,t,n,e.scaleMin,e.scaleMax);r.beginPath(),r.moveTo(u-uW,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=mW(a,t,n,e.scaleMin,e.scaleMax);r.beginPath(),r.moveTo(u-lW,i),r.lineTo(u,i),r.stroke(),r.fillText(Hz(a,s),u-dW,i)}}}if((y?.style??`solid`)!==`none`&&(r.strokeStyle=y?.color??m,r.lineWidth=y?.width??1,r.setLineDash(GU(y?.style??`solid`)),r.strokeRect(l,o,u,d),r.setLineDash([])),(_?.style??`dashed`)!==`none`){r.strokeStyle=_?.color??m,r.lineWidth=_?.width??1,r.setLineDash(GU(_?.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=Kz(h,w,w+j);for(let e=0;e<=(a?-1:6);e++){let t=w+e/6*j;r.fillText(de?nB(t,j/6,j):Hz(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}=hW(o,d,t.bandFromPct,t.bandToPct),a=e=>mW(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=UU&&!I.current?F.current:null;if(UU&&!he&&!I.current&&D.current&&!L.current&&(he=OH()&&aH()?AH(D.current,1,Se,{hidden:xe,evict:Se},O.current??void 0):jH(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}=hW(o,d,e.bandFromPct,e.bandToPct);return{color:JV(e.color),bandTop:t,bandBottom:r,scaleMin:e.scaleMin,scaleMax:e.scaleMax,gapMedian:n.pts.hold?DW: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=>yW(p,e.column))})}i.length=r.length,he.setView(w,k,pe.current)}else{let e=N.current;HU&&!e&&!P.current&&D.current&&!L.current&&(e=eH(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}=hW(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=JV(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),mW(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=mW(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}=hW(o,d,e.bandFromPct,e.bandToPct),i=mW(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`?zU:GU(e.alarm.style)),r.beginPath(),r.moveTo(l,i),r.lineTo(l+u,i),r.stroke(),r.setLineDash([]),e.alarm.linked&&VU(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`${Uz(t)}${n?` ${n}`:``}`},ve=l+u+8;r.font=rW,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+iW),i){let i=_W(e.members.length,t,n);for(let n=0;n<i;n++)r.fillStyle=e.members[n].color,r.globalAlpha=sW,r.fillText(_e(e.members[n]),ve,t+iW+(n+1)*cW)}else r.fillStyle=e.leader.color,r.globalAlpha=sW,r.fillText(_e(e.leader),ve,t+aW);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}=ZU(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||vW(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=bW(_),C=xW(S,i,l),w=s+c+8;r.font=rW,r.textAlign=`left`;let T=tU(m,s,c,h,g),E=nU(p,T,v,y),D=e=>{let t=E.get(e.column);if(typeof t!=`number`)return`-`;let n=d[e.column]?.trim()??``;return`${Uz(t)}${n?` ${n}`:``}`};for(let e of S){let t=C.get(e.leader.id)??hW(i,l,e.leader.bandFromPct,e.leader.bandToPct).bandTop;if(e.members.length>1){let i=e.members.length*cW+4;r.fillStyle=b,r.fillRect(s+c+6,t+iW+2,a-8,i);let o=_W(e.members.length,t,n);for(let n=0;n<o;n++){let i=e.members[n];r.fillStyle=i.color,r.globalAlpha=sW,r.fillText(D(i),w,t+iW+(n+1)*cW)}}else{let n=e.leader;r.fillStyle=b,r.fillRect(s+c+6,t+iW+2,a-8,aW-iW+6),r.fillStyle=n.color,r.globalAlpha=sW,r.fillText(D(n),w,t+aW)}r.globalAlpha=1}let O=/^(.*?)\s*\(([^)]*)\)\s*$/.exec(f),A=O?O[1]:f,j=O?O[2].trim():``,M=Kz(f,h,g)?rB(T):``,N=M.lastIndexOf(` `),P=M?[`${A} ${M.slice(0,N)}`,M.slice(N+1)]:[`${A} ${Math.round(T)}${j}`];r.font=rW,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=zH(e=>{Ue.current=0,!xe()&&(Ke.current=e,Ge.current?.())}))}function St(){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,BH(Ue.current),Ue.current=0,yt(),bt()}function Et(){qe.current=bt,!We.current&&(We.current=zH(()=>{We.current=0,qe.current?.()}))}function Dt(e){U.current=zH(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&&!KH(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&&OH()&&aH())){Se();return}if(me.current&&e-me.current<nW-ge.current/2||!QH(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?pU(t.id,o,performance.now(),t.timeAfter):DU(de.current,o,a,t.timeAfter),n=t.id?vU(t.id):hU(de.current),r=yU(t.xAtTime,e,n);Number.isFinite(r)&&(s=r);let i=yU(t.xAtTime,e,n-(t.id?_U(t.id):gU(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]=sU(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=aU(n?Math.min(64,e-n):16,QU);ne.current=oU(ne.current,a,r?r[0]:null,i,t,$U),re.current=oU(re.current,o,r?r[1]:null,i,t,$U),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;(vW(Oe.current)===0||!p&&e-se.current>=tW)&&(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(),$H(e,performance.now()-r)}function Ot(){U.current||=(ae.current=0,zH(Dt))}function At(){U.current&&(BH(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?Ot():(At(),xt()),At),[!!y]),W(()=>dB(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(()=>{St()},[t,n,i,e,p,m,h,g,v,Ye]),W(()=>()=>{BH(Ue.current),BH(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 GH(()=>{Je.current=null,n(),xt()});r.observe(t);let i=eU(e=>et.current?.(e)),a=t=>{if(ke.current||Ve.current!==null)return;if(vW(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}=ZU(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(tU(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)},WU)},c=t=>{if(Pe.current!==`none`||t.buttons&2||Date.now()-Le.current<300||vW(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}=ZU(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=uU(De.current,p,t.deltaY<0,p*.001);return}if(Ee.current===`follow`&&ot()){let e=uU(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)},WU);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}=ZU(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}=ZU(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}=ZU(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(vW(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}=ZU(i.width),s=Math.max(1,i.width-a-o),c=Ae.current,l=Me.current,u=Math.abs(l-c);if(vW(r)<2||u<12){rt.current?.({clientX:t.clientX,clientY:t.clientY}),Et();return}let d=pW(Math.min(c,l),a,a+s),f=pW(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=pW(g,y,b),_=pW(_,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||vW(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}=ZU(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)}},[]),kt(`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 AW(){try{if(localStorage.getItem(`perfLog`)===`1`)return!0;if(localStorage.getItem(`perfLog`)===`0`)return!1}catch{}return!1}var jW=!1;function MW(){let e=AW();return e&&!jW&&(jW=!0,console.log(`[perf] logging enabled — zoom an out-of-core chart to see decimate()/sampleRows timings`)),e}MW();var NW=new Map;function PW(e,t){let n=(NW.get(e)??0)+1;NW.set(e,n),console.log(`[perf] ${e} #${n} ${t.toFixed(1)}ms`)}async function FW(e,t){if(!MW())return t();let n=performance.now();try{return await t()}finally{PW(e,performance.now()-n)}}var IW=20;async function LW(e,t,n,i){let{x0:a,bucket:o,rows:s,columns:c}=await FW(`decimate(${t.length}col)`,()=>e.getSeriesMulti(t,n,i));return r(s,c,a,o)}function RW(e,t,n,i,a=0,o=!1,s=0){let[c,l]=wt({points:C,fetchedViewport:null}),[u,d]=wt(!1),f=`${t.join(`,`)}|${n?`${n.xKey}:${n.x0}:${n.x1}`:`none`}|${i}|${a}`,p=Ct(()=>{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,i);return{points:r(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 r=!0;d(!0);let a=setTimeout(()=>{LW(e,t,n,i).then(t=>{r&&(l({points:t,fetchedViewport:n,source:e}),d(!1))}).catch(()=>{r&&d(!1)})},IW);return()=>{r=!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 zW=250,BW=2,VW=6e3,HW=2e6,UW=[];function WW(e,t,n,r,i,a){let o=!!e&&e.columnSet.has(n),s=Ct(()=>e&&o?t.filter(t=>e.columnSet.has(t)):UW,[e,o,t]),c=e&&o&&s.length>0?e.source:null,l=!!c&&!e?.live&&!!c.getSeriesMultiSync&&!!c.xBoundsSync,u=Ct(()=>l&&c?c.xBoundsSync(n):null,[l,c,n]),[d,f]=wt(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,zW):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:b,full:x}=RW(c,s,c&&h&&h.x1>h.x0?{xKey:n,x0:h.x0,x1:h.x1}:null,Math.min(VW,i*BW),_,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}=RW(c,s,c&&w!==null&&T!==null&&!E?{xKey:n,x0:w,x1:T}:null,i,_,l,a),k=Ct(()=>!O||D.length===0?v:g([y(v,e=>e<O.x0),D,y(v,e=>e>O.x1)]),[v,D,O]),A=!!c&&(h===null||b);return Ct(()=>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 GW=new WeakMap,KW=0;function qW(e){if(e.key!==void 0)return e.key;let t=GW.get(e.source);return t===void 0&&GW.set(e.source,t=KW++),`${t}${e.keySuffix}`}function JW(){let[e,t]=wt(()=>new Map);return[e,bt((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 YW=vt(function({id:e,layer:t,columns:n,xKey:r,view:i,mp:a,rawLimit:o,report:s}){let c=WW(t,n,r,i,a,o);return G(()=>{s(e,c)},[e,c,s]),G(()=>()=>s(e,null),[e,s]),null});function XW({layers:e,xKey:t,columns:n,maxPoints:r,...i}){let a=i.viewXRange??null,[o,s]=wt(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(HW/Math.max(1,e.length)),[f,p]=JW(),m=Ct(()=>e.map(qW),[e]),h=Ct(()=>m.map(e=>f.get(e)),[m,f]),g=Ct(()=>h.flatMap(e=>e&&e.points.length>0?[e.points]:[]),[h]),_=Ct(()=>{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 kt(Ot,{children:[e.map((e,r)=>q(YW,{id:m[r],layer:e,columns:n,xKey:t,view:a,mp:u,rawLimit:d,report:p},m[r])),g.length===0?kt(`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(kW,{points:g,fullXRange:_,...i,onPlotWidthCss:s})]})}function ZW(e){return!!e&&!Array.isArray(e)&&typeof e.length==`number`&&`x`in e&&`y`in e}function QW(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 $W(e,t,n){let r=n?.get(t);if(r)return r;let i=Ue(e);if(i)return _e(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 eG(e,t,n){let r=$W(e,t,n);if(!r||A.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 tG(e,t,n,r){if(!n){let n=eG(e,t,r);return n?[{label:t,values:n}]:[]}let i=$W(e,t,r);if(!i)return[];let a=i.length,o=r?.has(n)||e.length>0&&typeof e[0][n]==`number`?$W(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 nG(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 rG(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 iG(e,t){let n=new Float64Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n}function aG(e,t,n,r){let i=$W(e.rows,t,e.full),a=$W(e.rows,n,e.full);if(!i||!a)return null;let o=r.colorCol?$W(e.rows,r.colorCol,e.full):void 0;if(r.viewXRange){let t=$W(e.rows,r.xKey,e.full);if(t){let e=rG(t,r.viewXRange[0],r.viewXRange[1]);i=iG(i,e),a=iG(a,e),o&&=iG(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 oG(e,t,n,r){let i=[],a=[];e.forEach((e,o)=>{a.push(aB(r.colorOverrides,e.id,o,r.palette));let s=aG(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 sG=e=>ZW(e)?e:QW(e),cG=(e,t,n)=>t===t&&n===n&&(!e||t>=e.xmin&&t<=e.xmax&&n>=e.ymin&&n<=e.ymax);function lG(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(cG(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 uG(e,t,n){return lG(sG(e),t,n)}function dG(e,t){let n=sG(e),r=0,i=0;for(let e=0;e<n.length;e++)cG(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(!cG(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 fG(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 pG(e,t,n){let r=[];for(let n=e.length-1;n>=0;n--){let i=e[n];n===0?r.push(fG(i)):n===1?r.push(`${fG(i)}·${t}`):r.push(`${fG(i)}·${t}${n>1?`^${n}`:``}`)}return`${n} = ${r.join(` + `).replace(/\+ -/g,`− `)}`}var mG=[[0,45,80,160],[.25,40,145,175],[.5,60,180,110],[.75,220,175,55],[1,210,75,55]];function hG(e){let t=0;for(let n=1;n<mG.length;n++){if(e<=mG[n][0]){t=n-1;break}n===mG.length-1&&(t=n-1)}let n=t+1,r=(e-mG[t][0])/(mG[n][0]-mG[t][0]);return{r:Math.round(mG[t][1]+r*(mG[n][1]-mG[t][1])),g:Math.round(mG[t][2]+r*(mG[n][2]-mG[t][2])),b:Math.round(mG[t][3]+r*(mG[n][3]-mG[t][3]))}}function gG(e){let{r:t,g:n,b:r}=hG(e);return`rgb(${t},${n},${r})`}function _G(e,t){if(!Number.isFinite(e))return 0;let n=Math.floor(e*t);return n<0?0:n>=t?t-1:n}var vG=`#version 300 es
206
+ }`;function bU(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 xU(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=>bU(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 SU(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 CU(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 wU(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=rU(n,n.VERTEX_SHADER,vU),t=rU(n,n.FRAGMENT_SHADER,yU);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():hU(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=xU(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=SU(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/_U)),o=3*Math.min(Math.max(i,1),_U),s=new Float32Array(o*a*4);for(let n=0;n<i;n++){let i=r[n],a=(Math.floor(n/_U)*o+n%_U*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+eU,+(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)&&CU(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 TU=[],EU=12,DU=!1,OU=!1,kU=0,AU=3,jU=1;function MU(){return!DU&&typeof Worker<`u`&&typeof HTMLCanvasElement<`u`&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen==`function`}var NU=`kymoscope-gl-first-frame`;function PU(e,t=1,n,r,i){if(typeof e.transferControlToOffscreen!=`function`||typeof Worker>`u`)return null;let a,o=TU.pop();try{a=o??kO(``+new URL(`assets/offscreenLineWorker-C-_uNa_H.js`,import.meta.url).href)}catch{return DU=!0,null}let s;try{s=e.transferControlToOffscreen()}catch{return o?TU.push(o):a.terminate(),null}let c=()=>{},l=jU++,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`&&(OU=!0,performance.mark?.(NU),c()))},a.onerror=()=>{u=!0,(!OU||++kU>=AU)&&(DU=!0),n?.()};let d=uU(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&&!DU&&TU.length<EU;try{a.postMessage({type:`dispose`})}catch{e=!1}e?TU.push(a):a.terminate(),d()}},g=i?FU(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 FU(e,t=1){let n=gU(e,e=>wU(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 IU=new Set;function LU(e){IU.add(e)}function RU(e){IU.delete(e)}function zU(){let e=typeof window>`u`?[]:[window];for(let t of IU)t.closed||e.push(t);return e}var BU=1,VU=new Map;function HU(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 UU(e){let t=BU++,n=zU();if(n.length===1){let r=n[0],i=r.requestAnimationFrame(n=>{VU.delete(t),e(HU(r,n))});return VU.set(t,[{w:n[0],id:i}]),t}let r=[];for(let i of n)r.push({w:i,id:i.requestAnimationFrame(n=>{VU.has(t)&&(WU(t),e(HU(i,n)))})});return VU.set(t,r),t}function WU(e){if(e==null)return;let t=VU.get(e);if(t){VU.delete(e);for(let{w:e,id:n}of t)e.closed||e.cancelAnimationFrame(n)}}var GU=new WeakMap;function KU(e){e&&GU.set(e,(GU.get(e)??0)+1)}function qU(e){let t=GU.get(e)??0;for(let n of e.querySelectorAll(`*`))t+=GU.get(n)??0;return t}function JU(){return zU().every(e=>e.document.hidden)}var YU=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 XU(e){return!!e&&e.isConnected&&typeof e.checkVisibility==`function`&&!e.checkVisibility()}function ZU(e,t){let n=0,r=null,i=()=>XU(t()),a=t=>{n=0,!i()&&(r=t,e())};return{schedule(){n||=UU(a)},now(){if(i())return;let o=t()?.ownerDocument?.timeline?.currentTime;if(typeof o!=`number`||o===r){n||=UU(a);return}n&&=(WU(n),0),r=o,e()},cancel(){n&&WU(n),n=0}}}var QU=.6,$U=16,eW={ts:-1,work:0,floor:1/0},tW=1/0;function nW(e,t=-1/0){if(e!==eW.ts){if(e>eW.ts&&e<eW.ts+eW.work/QU)return!1;eW={ts:e,work:0,floor:tW},tW=1/0}return eW.work>=$U||t>eW.floor?(tW=Math.min(tW,t),!1):!0}function rW(e,t){e===eW.ts&&(eW.work+=t)}function iW(e,t=typeof window>`u`?null:e=>{UU(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 aW(e,t,n,r,i){return r+(e-t)/n*(i-r)}function oW(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 sW(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 cW(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 lW(e,t){return!(e>0)||!(t>0)?1:1-Math.exp(-e/t)}function uW(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 dW(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 fW(e,t){return e>0?Math.min(8e3,Math.max(400,Math.round(e*t*2))):2e3}var pW=.5;function mW(e,t,n,r=pW){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 hW(e=0){return{d:null,lastT:NaN,wall:0,base:NaN,wait:e,waitAge:0,gap:NaN}}var gW=new Map;function _W(e,t,n,r){let i=gW.get(e);if(i||gW.set(e,i={p:hW(),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=jW(i.p,t,a,r),i.d}function vW(){let e;for(let t of gW.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 yW(e){return Math.min(DW,e.wait*1.2+.05)}function bW(e){return Number.isFinite(e.gap)?Math.min(e.gap,yW(e)):0}function xW(e){let t=gW.get(e);return t?bW(t.p):0}function SW(e){let t=gW.get(e);return t?yW(t.p):0}function CW(e,t,n){let r=e(t);if(!(n>0))return r;let i=(r-e(t-wW))/wW;return Number.isFinite(i)&&i>=0?r+i*n:r}var wW=.25,TW=1,EW=250,DW=3,OW=90,kW=30,AW=.001;function jW(e,t,n,r){if(!Number.isFinite(t))return t;let i=n/1e3;e.wall+=i;let a=n>EW&&e.d!==null,o=e.lastT;if(t<e.lastT&&Object.assign(e,hW(),{wall:e.wall}),t<=e.lastT)e.base+=i*AW;else{let n=e.wall-t;e.base=Number.isNaN(e.base)?n:Math.min(e.base+i*AW,n);let r=t-o;r>0&&r<TW&&(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(DW,s),e.waitAge=0):s>e.wait*.8?e.waitAge=0:e.waitAge>OW&&(e.wait*=Math.exp(-i/kW)));let c=e.wall-e.base-yW(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 MW=(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),NW=(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),PW=(e,t)=>e.left+MW(e.x,t)*e.width,FW=(e,t)=>NW(e.x,(t-e.left)/(e.width||1)),IW=(e,t)=>e.top+(1-MW(e.y,t))*e.height,LW=e=>!e||Number.isFinite(e.v0)&&Number.isFinite(e.v1)&&e.v0!==e.v1&&(!e.log||e.v0>0&&e.v1>0),RW=(e,t)=>e===t||!!e&&!!t&&e.v0===t.v0&&e.v1===t.v1&&!!e.log==!!t.log;function zW(){let e=null,t=new Set;return{get:()=>e,set:n=>{if(n&&(n.width>0&&n.height>0?(!LW(n.x)||!LW(n.y))&&(n={...n,x:LW(n.x)?n.x:void 0,y:LW(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&&RW(n.x,e.x)&&RW(n.y,e.y))){e=n;for(let e of[...t])e()}},subscribe:e=>(t.add(e),()=>{t.delete(e)})}}var BW=gt(()=>{}),VW=()=>xt(BW),HW=`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`,UW=[5,4],WW=null;function GW(e,t,n,r){typeof Path2D>`u`||(WW??=new Path2D(HW),e.save(),e.setLineDash([]),e.translate(t,n),e.fillStyle=r,e.fill(WW),e.restore())}var KW=(()=>{try{return localStorage.getItem(`glLines`)!==`0`}catch{return!0}})(),qW=(()=>{try{return localStorage.getItem(`offscreenGl`)!==`0`}catch{return!0}})(),JW=70;function YW(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}var XW={top:14,right:160,bottom:40,left:110},ZW={top:14,right:100,bottom:40,left:70},QW=640,$W={top:3,right:3,bottom:3,left:3},eG=260;function tG(e){return e<eG?$W:e<QW?ZW:XW}var nG=220,rG=.05,iG=2e3,aG=4,oG=1e3/120,sG=`11.25px ${Q.mono}`,cG=11*1.125,lG=24*1.125,uG=lG-cG+26,dG=.6,fG=13,pG=10,mG=5,hG=14,gG=4;function _G(e,t,n){return Math.min(n,Math.max(t,e))}function vG(e,t,n,r,i){let a=Math.min(r,i),o=Math.max(r,i);return t+(1-_G(o===a?.5:(e-a)/(o-a),0,1))*(n-t)}function yG(e,t,n,r){let i=e+t;return{bandTop:i-r/100*t,bandBottom:i-n/100*t}}function bG(e){return e.replace(/__(\d+|ref)$/,``)}function xG(e,t,n){let r=Math.floor((n-t-cG)/fG)+1;return Math.max(0,Math.min(e,r))}function SG(e){let t=0;for(let n of e)t+=n.length;return t}function CG(e,t){let n=e.cols.get(t);return n?new Float32Array(n):new Float32Array(e.length).fill(NaN)}function wG(e){let t=new Map;for(let n of e){let e=bG(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=bG(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 TG(e,t,n){let r=new Map,i=e.map((e,r)=>{let{bandTop:i}=yG(t,n,e.leader.bandFromPct,e.leader.bandToPct);return{g:e,i:r,bandTop:i,blockDY:e.members.length>1?cG+(e.members.length+1)*fG:uG}});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+cG,o=Math.max(i,a),s=o-cG;r.set(e.leader.id,s),a=o+n}return r}function EG(e,t){let n=e.cols.get(t);if(!n)return 0;let r=e.x;return n.length===e.length&&A.has(n)?DG(r,e.length):kG(r,e.length,e=>Number.isFinite(n[e]))}function DG(e,t){let n=OG.get(e);return n===void 0&&(n=kG(e,t,()=>!0),OG.set(e,n)),n}var OG=me(new WeakMap);function kG(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 AG(e,t){return e>0?Math.max(e*4,t*1e-9):Math.max(t*1e-6,1e-12)}var jG=1e30,MG=250;function NG({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=VW(),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(iG),le=K(y),ue=K(null),de=K(hW()),fe=K(0),pe=K(void 0),me=K(0),he=K(0),ge=K(16),_e=K(!0),ve=K(!1),[ye,be]=wt(0),xe=()=>XU(A.current);function Se(){F.current?.dispose(),F.current=null,L.current=!1,I.current=!1,ee.current=[],be(e=>e+1)}W(()=>{ye&&Et()},[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(0);function Ve(e){let t=tG(e);return Be.current>0?{...t,left:t.left+Be.current}:t}let He=K(f),Ue=K(null),We=K({pts:null,x0:NaN,x1:NaN,ser:null}),Ge=K(0),Ke=K(0),qe=K(null),Je=K(null),Ye=K(null),Xe=K(null);G(()=>{He.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 Ze=Tt(BV,zV),Qe=K({xLabel:e,series:t,points:n,height:i,columnUnits:r,shiftMode:f,xAxisLine:p,yAxisLine:m,gridLine:h,lineWidth:g,showLatestValues:v,envelopes:_}),$e=K(null),et=K(null);G(()=>{Qe.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 tt=K(c),nt=K(w);nt.current=w,G(()=>{tt.current=c},[c]);let rt=K(l),it=K(u);G(()=>{rt.current=l,it.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,Et())})},[l,u]);let at=K(a);G(()=>{at.current=a},[a]);let ot=Ct(()=>{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]),st=K(ot);G(()=>{st.current=ot},[ot]);function ct(){return le.current!=null&&te.current===null&&H.current===null&&!ke.current&&Ue.current===null}function lt(){let{xmin:e,xmax:t}=st.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 ct()&&i!==null&&a!==null&&a>i&&Number.isFinite(i)&&Number.isFinite(a)?{xmin:i,xmax:a}:{xmin:e,xmax:t}}function ut(e,t){let n=le.current;if(!n?.latestValues)return cW(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 sW(e,i,a))r.set(t,n);return r}function dt(){return le.current?Oe.current:Qe.current.points}function ft(e,t,n){let r=new Map;for(let i of t)r.set(i,AG(_t(e,i),n));return r}function pt(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 mt(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<MG);return(!n||!i)&&(n={key:t.key,at:r,has:new Map,median:new Map},V.current.set(e,n)),n}function ht(e,t,n){let r=mt(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 gt(e,t){return pt(e).some((e,n)=>ht(n,e,t))}function _t(e,t){let n=pt(e);for(let e=0;e<n.length;e++){if(!ht(e,n[e],t))continue;let r=mt(e,n[e]),i=r.median.get(t);return i===void 0&&(i=EG(n[e].pts,t),r.median.set(t,i)),i}return 0}function vt(){if(Xe.current)return Xe.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 Xe.current=n,n}function yt(){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:Qe.current.height)}}function bt(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 xt(){let e=E.current;if(!e)return;let{w:t,h:n}=yt(),r=bt(e,t,n);if(!r)return;{let e=dt(),t=lt(),n=Qe.current.series,r=We.current;(r.pts!==e||r.x0!==t.xmin||r.x1!==t.xmax||r.ser!==n)&&(We.current={pts:e,x0:t.xmin,x1:t.xmax,ser:n},KU(A.current))}let i=tG(t),a=i===$W,{top:o,right:s,bottom:c}=i,l=i.left,u=t-l-s,d=n-o-c,{bg:f,muted:p,grid:m}=vt(),{xLabel:h,series:g,xAxisLine:_,yAxisLine:v,gridLine:y,lineWidth:b,columnUnits:x,showLatestValues:S}=Qe.current,C=dt();if(r.fillStyle=f,r.fillRect(0,0,t,n),SG(C)<2||u<=0||d<=0){if(r.fillStyle=p,r.font=`13px ${Q.sans}`,JH(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}=lt(),j=k-w,M=e=>l+(e-w)/j*u,z=g.filter(e=>e.bandToPct>e.bandFromPct&&e.scaleMin!==e.scaleMax&&gt(C,e.column)),B=wG(z),V=TG(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}=yG(o,d,e.bandFromPct,e.bandToPct),r=Math.min(e.scaleMin,e.scaleMax),i=Math.max(e.scaleMin,e.scaleMax),{majorStep:a,minorStep:s}=SV(e.scaleMin,e.scaleMax,e.yMajorStep??0,e.yMinorStep??0),c=a,l=CV(r,i,c);l.length>120&&(l=CV(r,i,c=SV(e.scaleMin,e.scaleMax,0,0).majorStep));let u=wV(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=DV(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)+gG+hG+(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)),Be.current=ae,T({left:l,top:o,width:u,height:d,x:{v0:w,v1:k}}),ce.current=fW(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(YW(v?.style??`dashed`));for(let a of i){let i=vG(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-gG;r.strokeStyle=a,r.lineWidth=1;for(let i of o){let a=vG(i,t,n,e.scaleMin,e.scaleMax);r.beginPath(),r.moveTo(u-mG,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=vG(a,t,n,e.scaleMin,e.scaleMax);r.beginPath(),r.moveTo(u-pG,i),r.lineTo(u,i),r.stroke(),r.fillText(DV(a,s),u-hG,i)}}}if((y?.style??`solid`)!==`none`&&(r.strokeStyle=y?.color??m,r.lineWidth=y?.width??1,r.setLineDash(YW(y?.style??`solid`)),r.strokeRect(l,o,u,d),r.setLineDash([])),(_?.style??`dashed`)!==`none`){r.strokeStyle=_?.color??m,r.lineWidth=_?.width??1,r.setLineDash(YW(_?.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=jV(h,w,w+j);for(let e=0;e<=(a?-1:6);e++){let t=w+e/6*j;r.fillText(de?VV(t,j/6,j):DV(t,j/6),l+e/6*u,ue)}r.textBaseline=`bottom`,a||r.fillText(h,l+u/2,n-5);let{shiftMode:fe}=Qe.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=Qe.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}=yG(o,d,t.bandFromPct,t.bandToPct),a=e=>vG(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=qW&&!I.current?F.current:null;if(qW&&!he&&!I.current&&D.current&&!L.current&&(he=MU()&&lU()?PU(D.current,1,Se,{hidden:xe,evict:Se},O.current??void 0):FU(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=pt(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=>ht(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}=yG(o,d,e.bandFromPct,e.bandToPct);return{color:QH(e.color),bandTop:t,bandBottom:r,scaleMin:e.scaleMin,scaleMax:e.scaleMax,gapMedian:n.pts.hold?jG:_t(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=>CG(p,e.column))})}i.length=r.length,he.setView(w,k,pe.current)}else{let e=N.current;KW&&!e&&!P.current&&D.current&&!L.current&&(e=iU(D.current),e?N.current=e:P.current=!0);let i=!!e;i&&e&&e.resize(t,n,window.devicePixelRatio||1);let a=[],s=ft(C,z.map(e=>e.column),j);for(let e of z){let{bandTop:t,bandBottom:n}=yG(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=QH(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),vG(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=vG(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}=yG(o,d,e.bandFromPct,e.bandToPct),i=vG(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`?UW:YW(e.alarm.style)),r.beginPath(),r.moveTo(l,i),r.lineTo(l+u,i),r.stroke(),r.setLineDash([]),e.alarm.linked&&GW(r,l+u-10-3,i-10-2,e.alarm.color),r.restore()}if(a)return;let ge=S?ut(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`${OV(t)}${n?` ${n}`:``}`},ve=l+u+8;r.font=sG,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+cG),i){let i=xG(e.members.length,t,n);for(let n=0;n<i;n++)r.fillStyle=e.members[n].color,r.globalAlpha=dG,r.fillText(_e(e.members[n]),ve,t+cG+(n+1)*fG)}else r.fillStyle=e.leader.color,r.globalAlpha=dG,r.fillText(_e(e.leader),ve,t+lG);r.globalAlpha=1}}function St(){let e=k.current;if(!e)return;let{w:t,h:n}=yt(),r=bt(e,t,n);if(!r)return;r.clearRect(0,0,t,n);let{top:i,right:a,bottom:o,left:s}=Ve(t),c=t-s-a,l=n-i-o,{series:u,columnUnits:d,xLabel:f}=Qe.current,p=dt();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||SG(p)<2||c<=0||l<=0)return;let{xmin:h,xmax:g}=lt(),_=u.filter(e=>e.bandToPct>e.bandFromPct&&e.scaleMin!==e.scaleMax&&gt(p,e.column)),v=[...new Set(_.map(e=>e.column))],y=ft(p,v,g-h),{bg:b,muted:x}=vt();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=wG(_),C=TG(S,i,l),w=s+c+8;r.font=sG,r.textAlign=`left`;let T=aW(m,s,c,h,g),E=oW(p,T,v,y),D=e=>{let t=E.get(e.column);if(typeof t!=`number`)return`-`;let n=d[e.column]?.trim()??``;return`${OV(t)}${n?` ${n}`:``}`};for(let e of S){let t=C.get(e.leader.id)??yG(i,l,e.leader.bandFromPct,e.leader.bandToPct).bandTop;if(e.members.length>1){let i=e.members.length*fG+4;r.fillStyle=b,r.fillRect(s+c+6,t+cG+2,a-8,i);let o=xG(e.members.length,t,n);for(let n=0;n<o;n++){let i=e.members[n];r.fillStyle=i.color,r.globalAlpha=dG,r.fillText(D(i),w,t+cG+(n+1)*fG)}}else{let n=e.leader;r.fillStyle=b,r.fillRect(s+c+6,t+cG+2,a-8,lG-cG+6),r.fillStyle=n.color,r.globalAlpha=dG,r.fillText(D(n),w,t+lG)}r.globalAlpha=1}let O=/^(.*?)\s*\(([^)]*)\)\s*$/.exec(f),A=O?O[1]:f,j=O?O[2].trim():``,M=jV(f,h,g)?HV(T):``,N=M.lastIndexOf(` `),P=M?[`${A} ${M.slice(0,N)}`,M.slice(N+1)]:[`${A} ${Math.round(T)}${j}`];r.font=sG,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 Et(){if(le.current){oe.current=!0;return}qe.current=()=>{xt(),St()},!Ge.current&&(Ge.current=UU(e=>{Ge.current=0,!xe()&&(Je.current=e,qe.current?.())}))}function Dt(){if(le.current){oe.current=!0;return}let e=A.current?.ownerDocument.timeline?.currentTime;if(typeof e!=`number`||e===Je.current){Et();return}Je.current=e,WU(Ge.current),Ge.current=0,xt(),St()}function Ot(){Ye.current=St,!Ke.current&&(Ke.current=UU(()=>{Ke.current=0,Ye.current?.()}))}function At(e){U.current=UU(At);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&&!XU(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&&MU()&&lU())){Se();return}if(me.current&&e-me.current<oG-ge.current/2||!nW(e,me.current||-1/0))return;me.current=e;let r=performance.now(),i=t.xBounds();i&&i[1]>i[0]&&(st.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?_W(t.id,o,performance.now(),t.timeAfter):jW(de.current,o,a,t.timeAfter),n=t.id?SW(t.id):yW(de.current),r=CW(t.xAtTime,e,n);Number.isFinite(r)&&(s=r);let i=CW(t.xAtTime,e,n-(t.id?xW(t.id):bW(de.current)));Number.isFinite(i)&&(c=i)}if(ct()){let n=s??t.latestX?.()??st.current.xmax,r=Ce.current,i=r!=null&&t.spanForSeconds?t.spanForSeconds(r):r??De.current,[a,o]=dW(st.current.xmin,st.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=lW(n?Math.min(64,e-n):16,nG);ne.current=uW(ne.current,a,r?r[0]:null,i,t,rG),re.current=uW(re.current,o,r?r[1]:null,i,t,rG),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=lt(),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;(SG(Oe.current)===0||!p&&e-se.current>=aG)&&(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,xt(),St(),rW(e,performance.now()-r)}function jt(){U.current||=(ae.current=0,UU(At))}function Mt(){U.current&&(WU(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?jt():(Mt(),Et()),Mt),[!!y]),W(()=>XV(A.current,()=>{Xe.current=null,Et()}),[]),W(()=>{Xe.current=null,Et()},[o]);let Nt=!!f;W(()=>{let e=k.current;e&&(e.style.cursor=Nt?`ew-resize`:``),Et()},[Nt,f?.label??``]);let Pt=s?.[0]??null,Ft=s?.[1]??null;return G(()=>{te.current===Pt&&H.current===Ft||(te.current=Pt,H.current=Ft,Et())},[Pt,Ft]),W(()=>{Dt()},[t,n,i,e,p,m,h,g,v,Ze]),W(()=>()=>{WU(Ge.current),WU(Ke.current),Ge.current=0,Ke.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 YU(()=>{Xe.current=null,n(),Et()});r.observe(t);let i=iW(e=>nt.current?.(e)),a=t=>{if(ke.current||Ue.current!==null)return;if(SG(dt())<2){z.current!==null&&(z.current=null,Ot(),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}=Ve(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,Ot(),i.set(null));return}z.current!==r&&(z.current=r,Ot());let{xmin:f,xmax:p}=lt();i.set(aW(r,o,u,f,p))},o=()=>{z.current!==null&&(z.current=null,Ot()),i.set(null)},s=e=>{$e.current&&clearTimeout($e.current),$e.current=setTimeout(()=>{$e.current=null,tt.current?.(e)},JW)},c=t=>{if(Pe.current!==`none`||t.buttons&2||Date.now()-Le.current<300||SG(dt())<2)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,{top:a,left:o,right:c,bottom:l}=Ve(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=st.current,p=f.xmax-f.xmin;if(!(p>0))return;if(Ee.current===`follow`&&ct()&&!we.current){De.current=mW(De.current,p,t.deltaY<0,p*.001);return}if(Ee.current===`follow`&&ct()){let e=mW(Ce.current,le.current?.bufferedSeconds?.()??p,t.deltaY<0);Ce.current=e,et.current&&clearTimeout(et.current),et.current=setTimeout(()=>{et.current=null,we.current?.(e)},JW);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),rt.current?.publish(it.current??``,null),Et();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),rt.current?.publish(it.current??``,null)):(te.current=C,H.current=w,s([C,w]),rt.current?.publish(it.current??``,[C,w])),Et()},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;$e.current&&=(clearTimeout($e.current),null),tt.current?.(e===null&&t===null?null:[e,t]),Ie.current=0,Et()}},u=t=>{if(t.button===0&&He.current){let n=e.getBoundingClientRect(),{left:r,top:i,right:a,bottom:o}=Ve(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){Ue.current=t.clientX,He.current.onDragStart();try{e.setPointerCapture(t.pointerId)}catch{}}return}if(t.button!==2)return;if(t.preventDefault(),t.buttons===0){at.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(Ue.current!==null){let n=t.clientX-Ue.current,r=e.getBoundingClientRect(),{left:i,right:a}=Ve(r.width),o=Math.max(1,r.width-i-a),{xmin:s,xmax:c}=lt(),l=c-s;l>0&&o>0&&He.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=dt(),{top:o,left:s,right:c,bottom:l}=Ve(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(SG(a)<2||!f)return;Pe.current=`rubber`,ke.current=!0,z.current=null}Pe.current===`rubber`&&(t.preventDefault(),Me.current=r,Ne.current=i,Ot())},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,Ot(),at.current?.({clientX:t.clientX,clientY:t.clientY});return}if(n!==`rubber`||!ke.current){ke.current=!1,Ot();return}ke.current=!1;let r=dt(),i=e.getBoundingClientRect(),{left:a,right:o}=Ve(i.width),s=Math.max(1,i.width-a-o),c=Ae.current,l=Me.current,u=Math.abs(l-c);if(SG(r)<2||u<12){at.current?.({clientX:t.clientX,clientY:t.clientY}),Ot();return}let d=_G(Math.min(c,l),a,a+s),f=_G(Math.max(c,l),a,a+s),{xmin:p,xmax:m}=lt(),h=m-p;if(!(h>0)){at.current?.({clientX:t.clientX,clientY:t.clientY}),Ot();return}let g=p+(d-a)/s*h,_=p+(f-a)/s*h;if(g>_){let e=g;g=_,_=e}let v=st.current,y=Math.min(v.xmin,v.xmax),b=Math.max(v.xmin,v.xmax);g=_G(g,y,b),_=_G(_,y,b);let x=_-g;if(x<=(b-y)*1e-12||x<=0){at.current?.({clientX:t.clientX,clientY:t.clientY}),Ot();return}at.current?.({clientX:t.clientX,clientY:t.clientY,zoomXRange:[g,_]}),Ot()},p=t=>{if(t.button===0&&Ue.current!==null){Ue.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{}at.current?.({clientX:t.clientX,clientY:t.clientY}),Ot()}},m=t=>{Ue.current!==null&&(Ue.current=null),Pe.current!==`none`&&(ke.current=!1,Pe.current=`none`);try{e.releasePointerCapture(t.pointerId)}catch{}Ot()},h=t=>{if(t.button!==0||SG(dt())<2)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,{top:a,left:o,right:s,bottom:c}=Ve(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,$e.current&&=(clearTimeout($e.current),null),tt.current?.(null),rt.current?.publish(it.current??``,null),Et(),Ot())},g=e=>{if(e.key!==`Escape`)return;let t=!1;Pe.current!==`none`&&(Pe.current=`none`,ke.current=!1,t=!0),Ue.current!==null&&(Ue.current=null,t=!0),t&&Ot()};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),$e.current&&clearTimeout($e.current),et.current&&clearTimeout(et.current)}},[]),kt(`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 PG(){try{if(localStorage.getItem(`perfLog`)===`1`)return!0;if(localStorage.getItem(`perfLog`)===`0`)return!1}catch{}return!1}var FG=!1;function IG(){let e=PG();return e&&!FG&&(FG=!0,console.log(`[perf] logging enabled — zoom an out-of-core chart to see decimate()/sampleRows timings`)),e}IG();var LG=new Map;function RG(e,t){let n=(LG.get(e)??0)+1;LG.set(e,n),console.log(`[perf] ${e} #${n} ${t.toFixed(1)}ms`)}async function zG(e,t){if(!IG())return t();let n=performance.now();try{return await t()}finally{RG(e,performance.now()-n)}}var BG=20;async function VG(e,t,n,i){let{x0:a,bucket:o,rows:s,columns:c}=await zG(`decimate(${t.length}col)`,()=>e.getSeriesMulti(t,n,i));return r(s,c,a,o)}function HG(e,t,n,i,a=0,o=!1,s=0){let[c,l]=wt({points:C,fetchedViewport:null}),[u,d]=wt(!1),f=`${t.join(`,`)}|${n?`${n.xKey}:${n.x0}:${n.x1}`:`none`}|${i}|${a}`,p=Ct(()=>{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,i);return{points:r(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 r=!0;d(!0);let a=setTimeout(()=>{VG(e,t,n,i).then(t=>{r&&(l({points:t,fetchedViewport:n,source:e}),d(!1))}).catch(()=>{r&&d(!1)})},BG);return()=>{r=!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 UG=250,WG=2,GG=6e3,KG=2e6,qG=[];function JG(e,t,n,r,i,a){let o=!!e&&e.columnSet.has(n),s=Ct(()=>e&&o?t.filter(t=>e.columnSet.has(t)):qG,[e,o,t]),c=e&&o&&s.length>0?e.source:null,l=!!c&&!e?.live&&!!c.getSeriesMultiSync&&!!c.xBoundsSync,u=Ct(()=>l&&c?c.xBoundsSync(n):null,[l,c,n]),[d,f]=wt(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,UG):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:b,full:x}=HG(c,s,c&&h&&h.x1>h.x0?{xKey:n,x0:h.x0,x1:h.x1}:null,Math.min(GG,i*WG),_,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}=HG(c,s,c&&w!==null&&T!==null&&!E?{xKey:n,x0:w,x1:T}:null,i,_,l,a),k=Ct(()=>!O||D.length===0?v:g([y(v,e=>e<O.x0),D,y(v,e=>e>O.x1)]),[v,D,O]),A=!!c&&(h===null||b);return Ct(()=>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 YG=new WeakMap,XG=0;function ZG(e){if(e.key!==void 0)return e.key;let t=YG.get(e.source);return t===void 0&&YG.set(e.source,t=XG++),`${t}${e.keySuffix}`}function QG(){let[e,t]=wt(()=>new Map);return[e,bt((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 $G=vt(function({id:e,layer:t,columns:n,xKey:r,view:i,mp:a,rawLimit:o,report:s}){let c=JG(t,n,r,i,a,o);return G(()=>{s(e,c)},[e,c,s]),G(()=>()=>s(e,null),[e,s]),null});function eK({layers:e,xKey:t,columns:n,maxPoints:r,...i}){let a=i.viewXRange??null,[o,s]=wt(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(KG/Math.max(1,e.length)),[f,p]=QG(),m=Ct(()=>e.map(ZG),[e]),h=Ct(()=>m.map(e=>f.get(e)),[m,f]),g=Ct(()=>h.flatMap(e=>e&&e.points.length>0?[e.points]:[]),[h]),_=Ct(()=>{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 kt(Ot,{children:[e.map((e,r)=>q($G,{id:m[r],layer:e,columns:n,xKey:t,view:a,mp:u,rawLimit:d,report:p},m[r])),g.length===0?kt(`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(NG,{points:g,fullXRange:_,...i,onPlotWidthCss:s})]})}function tK(e){return!!e&&!Array.isArray(e)&&typeof e.length==`number`&&`x`in e&&`y`in e}function nK(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 rK(e,t,n){let r=n?.get(t);if(r)return r;let i=Ue(e);if(i)return _e(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 iK(e,t,n){let r=rK(e,t,n);if(!r||A.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 aK(e,t,n,r){if(!n){let n=iK(e,t,r);return n?[{label:t,values:n}]:[]}let i=rK(e,t,r);if(!i)return[];let a=i.length,o=r?.has(n)||e.length>0&&typeof e[0][n]==`number`?rK(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 oK(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 sK(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 cK(e,t){let n=new Float64Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n}function lK(e,t,n,r){let i=rK(e.rows,t,e.full),a=rK(e.rows,n,e.full);if(!i||!a)return null;let o=r.colorCol?rK(e.rows,r.colorCol,e.full):void 0;if(r.viewXRange){let t=rK(e.rows,r.xKey,e.full);if(t){let e=sK(t,r.viewXRange[0],r.viewXRange[1]);i=cK(i,e),a=cK(a,e),o&&=cK(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 uK(e,t,n,r){let i=[],a=[];e.forEach((e,o)=>{a.push(WV(r.colorOverrides,e.id,o,r.palette));let s=lK(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 dK=e=>tK(e)?e:nK(e),fK=(e,t,n)=>t===t&&n===n&&(!e||t>=e.xmin&&t<=e.xmax&&n>=e.ymin&&n<=e.ymax);function pK(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(fK(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 mK(e,t,n){return pK(dK(e),t,n)}function hK(e,t){let n=dK(e),r=0,i=0;for(let e=0;e<n.length;e++)fK(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(!fK(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 gK(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 _K(e,t,n){let r=[];for(let n=e.length-1;n>=0;n--){let i=e[n];n===0?r.push(gK(i)):n===1?r.push(`${gK(i)}·${t}`):r.push(`${gK(i)}·${t}${n>1?`^${n}`:``}`)}return`${n} = ${r.join(` + `).replace(/\+ -/g,`− `)}`}var vK=[[0,45,80,160],[.25,40,145,175],[.5,60,180,110],[.75,220,175,55],[1,210,75,55]];function yK(e){let t=0;for(let n=1;n<vK.length;n++){if(e<=vK[n][0]){t=n-1;break}n===vK.length-1&&(t=n-1)}let n=t+1,r=(e-vK[t][0])/(vK[n][0]-vK[t][0]);return{r:Math.round(vK[t][1]+r*(vK[n][1]-vK[t][1])),g:Math.round(vK[t][2]+r*(vK[n][2]-vK[t][2])),b:Math.round(vK[t][3]+r*(vK[n][3]-vK[t][3]))}}function bK(e){let{r:t,g:n,b:r}=yK(e);return`rgb(${t},${n},${r})`}function xK(e,t){if(!Number.isFinite(e))return 0;let n=Math.floor(e*t);return n<0?0:n>=t?t-1:n}var SK=`#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
- }`,yG=`#version 300 es
232
+ }`,CK=`#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
- }`,bG=`#version 300 es
252
+ }`,wK=`#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
- }`,xG=`#version 300 es
271
+ }`,TK=`#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
- }`,SG=`#version 300 es
290
+ }`,EK=`#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
- }`,CG=`#version 300 es
325
+ }`,DK=`#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
- }`,wG=`
346
+ }`,OK=`
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 TG(e,t,n,r){let i=wG,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 EG=`#version 300 es
360
+ `;function kK(e,t,n,r){let i=OK,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 AK=`#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
- ${wG}
366
+ ${OK}
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
- }`,DG=`#version 300 es
371
+ }`,jK=`#version 300 es
372
372
  precision mediump float;
373
373
  out vec4 o;
374
- void main() { o = vec4(0.0); }`;function OG(e,t,n,r){let i=$V(e,e.VERTEX_SHADER,t),a=$V(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 kG(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 AG(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 jG(e){let t=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0});if(!t)return null;let n=dH(t,`glPoints|points`,()=>OG(t,vG,yG)),r=dH(t,`glPoints|lines`,()=>OG(t,SG,CG)),i=dH(t,`glPoints|points64`,()=>OG(t,TG(vG,[`a_x`],[`a_y`],!0),yG)),a=dH(t,`glPoints|sprites`,()=>OG(t,bG,xG)),o=dH(t,`glPoints|sprites64`,()=>OG(t,TG(bG,[`a_x`],[`a_y`],!0),xG)),s=dH(t,`glPoints|maxSprite`,()=>t.getParameter(t.ALIASED_POINT_SIZE_RANGE)[1]),c=dH(t,`glPoints|decode`,()=>OG(t,EG,DG,[`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,j=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,j),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,j),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=A.has(e)&&A.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=kG(n&&r?n:void 0,a),l=B&&(!n||r)?AG(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(A.has(e)&&A.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[j,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 MG={top:3,right:3,bottom:3,left:3};function NG(e,t,n){return t<200||n<120?{...MG,tiny:!0}:{...e,tiny:!1}}var PG={top:14,right:24,bottom:40,left:78},FG=70,IG=6,LG=8,RG=1.8;function zG(e,t,n){return Math.min(n,Math.max(t,e))}function BG(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 VG(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}function HG({points:e,xLabel:t,yLabel:n,color:r=`#38bdf8`,datasetColors:i,colorLabel:a,colorRange:o,height:s=400,pointRadius:c=RG,drawMode:l=`points`,lineWidth:u=1,backgroundToken:d=``,onPlotContextMenu:f,xAxisLine:p,yAxisLine:m,gridLine:h,fitSettings:g,xScale:_,yScale:v}){let y=LU(),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=Ct(()=>ZW(e)?e:QW(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:BG(e,`x`),y:BG(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=fH(V.current,jG),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(WG(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:uG(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=NG(PG,t,n),w=C.tiny?C.right:x?FG: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},HH(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}`,WV(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 Fz(de,6)})(),he=Rz(ce,le,me);if((p?.style??`dashed`)!==`none`){r.strokeStyle=p?.color??N,r.lineWidth=p?.width??1,r.setLineDash(VG(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-IG,t),r.lineTo(D,t),r.stroke(),r.fillText(Hz(e,me),D-LG,t)}let ge=(()=>{if(g?.majorStep){let e=parseFloat(g.majorStep);if(Number.isFinite(e)&&e>0)return e}return Fz(ue,Iz(O))})(),_e=Rz(oe,se,ge);if((f?.style??`dashed`)!==`none`){r.strokeStyle=f?.color??N,r.lineWidth=f?.width??1,r.setLineDash(VG(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+IG),r.stroke(),r.fillText(Hz(e,ge),t,T+k+IG+2)}(m?.style??`solid`)!==`none`&&(r.strokeStyle=m?.color??N,r.lineWidth=m?.width??1,r.setLineDash(VG(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}`},HH(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`&&KG(r,i,e,M.current.lineWidth),M.current.drawMode!==`lines`&&GG(r,i,e)}if(x&&!C.tiny){let e=D+O+10,n=k;for(let t=0;t<64;t++)r.fillStyle=gG(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(VG(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=pG(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`?zU:VG(e.style));let t=fe(e.value);U.beginPath(),U.moveTo(t,T),U.lineTo(t,T+k),U.stroke(),U.setLineDash([]),e.linked&&VU(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`?zU:VG(e.style));let t=pe(e.value);U.beginPath(),U.moveTo(D,t),U.lineTo(D+O,t),U.stroke(),U.setLineDash([]),e.linked&&VU(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}=NG(PG,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=`(${Uz(D.x)}, ${Uz(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(),UG(i,F,B,P,20,4),i.fill(),i.globalAlpha=1,i.strokeStyle=j,i.lineWidth=.5,i.beginPath(),UG(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??=qH(()=>{se.current(),ce.current()},()=>S.current);function ue(){le.current.schedule()}function de(){k.current||=zH(()=>{k.current=0,ce.current()})}W(()=>()=>{le.current?.cancel(),BH(k.current),k.current=0},[]);let fe=K(ue),pe=K(de);return G(()=>{fe.current=ue,pe.current=de}),W(()=>dB(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 GH(()=>{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}=NG(PG,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}=NG(PG,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}=NG(PG,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=zG(N,Math.max(f*1e-7,1e-12),f),F=zG(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)}},[]),kt(`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 UG(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 WG(e,t,n){if(e===`single`)return{kind:`single`,rgba:JV(t)};let r=new Uint8Array(256*4);for(let t=0;t<256;t++)if(e===`colormap`){let{r:e,g:n,b:i}=hG(t/255);r.set([e,n,i,255],t*4)}else{let e=JV(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 GG(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?_G(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?gG((t+.5)/24):n.col,e.fill(a[t]);e.globalAlpha=1}function KG(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 qG=11102230246251565e-32,JG=134217729,YG=(3+8*qG)*qG;function XG(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 ZG(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 QG=(3+16*qG)*qG,$G=(2+12*qG)*qG,eK=(9+64*qG)*qG*qG,tK=$(4),nK=$(8),rK=$(12),iK=$(16),aK=$(4);function oK(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=JG*T,p=f-(f-T),m=T-p,f=JG*O,h=f-(f-O),g=O-h,x=m*g-(b-p*h-m*h-p*g),S=D*E,f=JG*D,p=f-(f-D),m=D-p,f=JG*E,h=f-(f-E),g=E-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,tK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,tK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,tK[2]=v-(w-d)+(_-d),tK[3]=w;let k=ZG(4,tK),A=$G*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=eK*o+YG*Math.abs(k),k+=T*u+O*s-(D*l+E*c),k>=A||-k>=A))return k;b=s*O,f=JG*s,p=f-(f-s),m=s-p,f=JG*O,h=f-(f-O),g=O-h,x=m*g-(b-p*h-m*h-p*g),S=c*E,f=JG*c,p=f-(f-c),m=c-p,f=JG*E,h=f-(f-E),g=E-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,aK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,aK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,aK[2]=v-(w-d)+(_-d),aK[3]=w;let j=XG(4,tK,4,aK,nK);b=T*u,f=JG*T,p=f-(f-T),m=T-p,f=JG*u,h=f-(f-u),g=u-h,x=m*g-(b-p*h-m*h-p*g),S=D*l,f=JG*D,p=f-(f-D),m=D-p,f=JG*l,h=f-(f-l),g=l-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,aK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,aK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,aK[2]=v-(w-d)+(_-d),aK[3]=w;let M=XG(j,nK,4,aK,rK);return b=s*u,f=JG*s,p=f-(f-s),m=s-p,f=JG*u,h=f-(f-u),g=u-h,x=m*g-(b-p*h-m*h-p*g),S=c*l,f=JG*c,p=f-(f-c),m=c-p,f=JG*l,h=f-(f-l),g=l-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,aK[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,aK[1]=y-(_+d)+(d-S),w=v+_,d=w-v,aK[2]=v-(w-d)+(_-d),aK[3]=w,iK[XG(M,rK,4,aK,iK)-1]}function sK(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)>=QG*l?c:-oK(e,t,n,r,i,a,l)}(7+56*qG)*qG,(3+28*qG)*qG,(26+288*qG)*qG*qG,$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(8),$(8),$(8),$(4),$(8),$(8),$(16),$(12),$(192),$(192),(10+96*qG)*qG,(4+48*qG)*qG,(44+576*qG)*qG*qG,$(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*qG)*qG,(5+72*qG)*qG,(71+1408*qG)*qG*qG,$(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 cK=2**-52,lK=new Uint32Array(512),uK=class e{static from(t,n=vK,r=yK){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=fK(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=fK(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=mK(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];gK(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(sK(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=hK(h,g,_,v,b,x);this._cx=S.x,this._cy=S.y;for(let t=0;t<a;t++)this._dists[t]=fK(e[2*t],e[2*t+1],S.x,S.y);gK(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)<=cK&&Math.abs(u-s)<=cK||(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],sK(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],sK(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],sK(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(dK(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=lK[--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(pK(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<lK.length&&(lK[i++]=s)}else{if(i===0)break;e=lK[--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 dK(e,t){let n=e/(Math.abs(e)+Math.abs(t));return(t>0?3-n:1+n)/4}function fK(e,t,n,r){let i=e-n,a=t-r;return i*i+a*a}function pK(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 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),p=(l*u-s*d)*f,m=(o*d-c*u)*f;return p*p+m*m}function hK(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 gK(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;_K(e,i,a),t[e[n]]>t[e[r]]&&_K(e,n,r),t[e[a]]>t[e[r]]&&_K(e,a,r),t[e[n]]>t[e[a]]&&_K(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;_K(e,a,o)}e[n+1]=e[o],e[o]=s,r-a+1>=o-n?(gK(e,t,a,r),gK(e,t,n,o-1)):(gK(e,t,n,o-1),gK(e,t,a,r))}}function _K(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function vK(e){return e[0]}function yK(e){return e[1]}var bK=`
374
+ void main() { o = vec4(0.0); }`;function MK(e,t,n,r){let i=rU(e,e.VERTEX_SHADER,t),a=rU(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 NK(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 PK(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 FK(e){let t=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0});if(!t)return null;let n=hU(t,`glPoints|points`,()=>MK(t,SK,CK)),r=hU(t,`glPoints|lines`,()=>MK(t,EK,DK)),i=hU(t,`glPoints|points64`,()=>MK(t,kK(SK,[`a_x`],[`a_y`],!0),CK)),a=hU(t,`glPoints|sprites`,()=>MK(t,wK,TK)),o=hU(t,`glPoints|sprites64`,()=>MK(t,kK(wK,[`a_x`],[`a_y`],!0),TK)),s=hU(t,`glPoints|maxSprite`,()=>t.getParameter(t.ALIASED_POINT_SIZE_RANGE)[1]),c=hU(t,`glPoints|decode`,()=>MK(t,AK,jK,[`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,j=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,j),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,j),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=A.has(e)&&A.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=NK(n&&r?n:void 0,a),l=B&&(!n||r)?PK(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(A.has(e)&&A.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[j,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 IK={top:3,right:3,bottom:3,left:3};function LK(e,t,n){return t<200||n<120?{...IK,tiny:!0}:{...e,tiny:!1}}var RK={top:14,right:24,bottom:40,left:78},zK=70,BK=6,VK=8,HK=1.8;function UK(e,t,n){return Math.min(n,Math.max(t,e))}function WK(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 GK(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}function KK({points:e,xLabel:t,yLabel:n,color:r=`#38bdf8`,datasetColors:i,colorLabel:a,colorRange:o,height:s=400,pointRadius:c=HK,drawMode:l=`points`,lineWidth:u=1,backgroundToken:d=``,onPlotContextMenu:f,xAxisLine:p,yAxisLine:m,gridLine:h,fitSettings:g,xScale:_,yScale:v}){let y=VW(),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=Ct(()=>tK(e)?e:nK(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:WK(e,`x`),y:WK(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=gU(V.current,FK),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(JK(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:mK(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=LK(RK,t,n),w=C.tiny?C.right:x?zK: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},KU(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}`,JH(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 bV(de,6)})(),he=CV(ce,le,me);if((p?.style??`dashed`)!==`none`){r.strokeStyle=p?.color??N,r.lineWidth=p?.width??1,r.setLineDash(GK(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-BK,t),r.lineTo(D,t),r.stroke(),r.fillText(DV(e,me),D-VK,t)}let ge=(()=>{if(g?.majorStep){let e=parseFloat(g.majorStep);if(Number.isFinite(e)&&e>0)return e}return bV(ue,xV(O))})(),_e=CV(oe,se,ge);if((f?.style??`dashed`)!==`none`){r.strokeStyle=f?.color??N,r.lineWidth=f?.width??1,r.setLineDash(GK(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+BK),r.stroke(),r.fillText(DV(e,ge),t,T+k+BK+2)}(m?.style??`solid`)!==`none`&&(r.strokeStyle=m?.color??N,r.lineWidth=m?.width??1,r.setLineDash(GK(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}`},KU(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`&&XK(r,i,e,M.current.lineWidth),M.current.drawMode!==`lines`&&YK(r,i,e)}if(x&&!C.tiny){let e=D+O+10,n=k;for(let t=0;t<64;t++)r.fillStyle=bK(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(GK(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=_K(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`?UW:GK(e.style));let t=fe(e.value);U.beginPath(),U.moveTo(t,T),U.lineTo(t,T+k),U.stroke(),U.setLineDash([]),e.linked&&GW(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`?UW:GK(e.style));let t=pe(e.value);U.beginPath(),U.moveTo(D,t),U.lineTo(D+O,t),U.stroke(),U.setLineDash([]),e.linked&&GW(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}=LK(RK,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=`(${OV(D.x)}, ${OV(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(),qK(i,F,B,P,20,4),i.fill(),i.globalAlpha=1,i.strokeStyle=j,i.lineWidth=.5,i.beginPath(),qK(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??=ZU(()=>{se.current(),ce.current()},()=>S.current);function ue(){le.current.schedule()}function de(){k.current||=UU(()=>{k.current=0,ce.current()})}W(()=>()=>{le.current?.cancel(),WU(k.current),k.current=0},[]);let fe=K(ue),pe=K(de);return G(()=>{fe.current=ue,pe.current=de}),W(()=>XV(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 YU(()=>{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}=LK(RK,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}=LK(RK,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}=LK(RK,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=UK(N,Math.max(f*1e-7,1e-12),f),F=UK(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)}},[]),kt(`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 qK(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 JK(e,t,n){if(e===`single`)return{kind:`single`,rgba:QH(t)};let r=new Uint8Array(256*4);for(let t=0;t<256;t++)if(e===`colormap`){let{r:e,g:n,b:i}=yK(t/255);r.set([e,n,i,255],t*4)}else{let e=QH(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 YK(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?xK(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?bK((t+.5)/24):n.col,e.fill(a[t]);e.globalAlpha=1}function XK(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 ZK=11102230246251565e-32,QK=134217729,$K=(3+8*ZK)*ZK;function eq(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 tq(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 nq=(3+16*ZK)*ZK,rq=(2+12*ZK)*ZK,iq=(9+64*ZK)*ZK*ZK,aq=$(4),oq=$(8),sq=$(12),cq=$(16),lq=$(4);function uq(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=QK*T,p=f-(f-T),m=T-p,f=QK*O,h=f-(f-O),g=O-h,x=m*g-(b-p*h-m*h-p*g),S=D*E,f=QK*D,p=f-(f-D),m=D-p,f=QK*E,h=f-(f-E),g=E-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,aq[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,aq[1]=y-(_+d)+(d-S),w=v+_,d=w-v,aq[2]=v-(w-d)+(_-d),aq[3]=w;let k=tq(4,aq),A=rq*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=iq*o+$K*Math.abs(k),k+=T*u+O*s-(D*l+E*c),k>=A||-k>=A))return k;b=s*O,f=QK*s,p=f-(f-s),m=s-p,f=QK*O,h=f-(f-O),g=O-h,x=m*g-(b-p*h-m*h-p*g),S=c*E,f=QK*c,p=f-(f-c),m=c-p,f=QK*E,h=f-(f-E),g=E-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,lq[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,lq[1]=y-(_+d)+(d-S),w=v+_,d=w-v,lq[2]=v-(w-d)+(_-d),lq[3]=w;let j=eq(4,aq,4,lq,oq);b=T*u,f=QK*T,p=f-(f-T),m=T-p,f=QK*u,h=f-(f-u),g=u-h,x=m*g-(b-p*h-m*h-p*g),S=D*l,f=QK*D,p=f-(f-D),m=D-p,f=QK*l,h=f-(f-l),g=l-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,lq[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,lq[1]=y-(_+d)+(d-S),w=v+_,d=w-v,lq[2]=v-(w-d)+(_-d),lq[3]=w;let M=eq(j,oq,4,lq,sq);return b=s*u,f=QK*s,p=f-(f-s),m=s-p,f=QK*u,h=f-(f-u),g=u-h,x=m*g-(b-p*h-m*h-p*g),S=c*l,f=QK*c,p=f-(f-c),m=c-p,f=QK*l,h=f-(f-l),g=l-h,C=m*g-(S-p*h-m*h-p*g),_=x-C,d=x-_,lq[0]=x-(_+d)+(d-C),v=b+_,d=v-b,y=b-(v-d)+(_-d),_=y-S,d=y-_,lq[1]=y-(_+d)+(d-S),w=v+_,d=w-v,lq[2]=v-(w-d)+(_-d),lq[3]=w,cq[eq(M,sq,4,lq,cq)-1]}function dq(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)>=nq*l?c:-uq(e,t,n,r,i,a,l)}(7+56*ZK)*ZK,(3+28*ZK)*ZK,(26+288*ZK)*ZK*ZK,$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(4),$(8),$(8),$(8),$(4),$(8),$(8),$(16),$(12),$(192),$(192),(10+96*ZK)*ZK,(4+48*ZK)*ZK,(44+576*ZK)*ZK*ZK,$(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*ZK)*ZK,(5+72*ZK)*ZK,(71+1408*ZK)*ZK*ZK,$(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 fq=2**-52,pq=new Uint32Array(512),mq=class e{static from(t,n=Sq,r=Cq){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=gq(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=gq(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=vq(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];bq(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(dq(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=yq(h,g,_,v,b,x);this._cx=S.x,this._cy=S.y;for(let t=0;t<a;t++)this._dists[t]=gq(e[2*t],e[2*t+1],S.x,S.y);bq(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)<=fq&&Math.abs(u-s)<=fq||(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],dq(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],dq(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],dq(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(hq(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=pq[--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(_q(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<pq.length&&(pq[i++]=s)}else{if(i===0)break;e=pq[--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 hq(e,t){let n=e/(Math.abs(e)+Math.abs(t));return(t>0?3-n:1+n)/4}function gq(e,t,n,r){let i=e-n,a=t-r;return i*i+a*a}function _q(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 vq(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 yq(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 bq(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;xq(e,i,a),t[e[n]]>t[e[r]]&&xq(e,n,r),t[e[a]]>t[e[r]]&&xq(e,a,r),t[e[n]]>t[e[a]]&&xq(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;xq(e,a,o)}e[n+1]=e[o],e[o]=s,r-a+1>=o-n?(bq(e,t,a,r),bq(e,t,n,o-1)):(bq(e,t,n,o-1),bq(e,t,a,r))}}function xq(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function Sq(e){return e[0]}function Cq(e){return e[1]}var wq=`
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
- `,xK=`bool outside(vec3 n) { return any(greaterThan(abs(n), vec3(1.0001))); }`,SK=`#version 300 es
410
+ `,Tq=`bool outside(vec3 n) { return any(greaterThan(abs(n), vec3(1.0001))); }`,Eq=`#version 300 es
411
411
  in float a_x; in float a_y; in float a_z;
412
412
  uniform float u_size;
413
- ${bK}
414
- ${xK}
413
+ ${wq}
414
+ ${Tq}
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
- }`,CK=`#version 300 es
420
+ }`,Dq=`#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
- }`,wK=`#version 300 es
431
+ }`,Oq=`#version 300 es
432
432
  in float a_x; in float a_y; in float a_z;
433
- ${bK}
434
- void main() { gl_Position = place(vec3(a_x, a_y, a_z)); }`,TK=`#version 300 es
433
+ ${wq}
434
+ void main() { gl_Position = place(vec3(a_x, a_y, a_z)); }`,kq=`#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
- ${bK}
443
+ ${wq}
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
- }`,EK=`#version 300 es
462
+ }`,Aq=`#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
- ${xK}
467
+ ${Tq}
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
- }`,DK=`#version 300 es
473
+ }`,jq=`#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
- ${xK}
478
+ ${Tq}
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
- }`,OK=16e6,kK=128,AK=[`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 jK(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 MK(e){let t=e.getContext(`webgl2`,{antialias:!0,alpha:!0,premultipliedAlpha:!0,depth:!0});if(!t)return null;let n=(e,n,r,i)=>dH(t,`gl3d|${e}|${n}`,()=>{let a=$V(t,t.VERTEX_SHADER,e),o=$V(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([...AK,...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(SK,CK,r,[`u_size`,`u_rim`]),a=n(wK,EK,r,[`u_alpha`,`u_solid`]),o=n(TK,DK,[],[`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=[jK(e),jK(n),jK(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=jK(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/OK))),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)/kK)),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 NK=new Map;function PK(e,t){let n=NK.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;NK.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 FK(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}function IK(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 LK(e,t){return e.x*t.x+e.y*t.y+e.z*t.z}function RK(e){return Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z)}function zK(e){let t=RK(e);return t>1e-12?{x:e.x/t,y:e.y/t,z:e.z/t}:{x:0,y:0,z:1}}function BK(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 VK(e,t,n){let r=zK(FK(t,e)),i=zK(IK(r,n));return{right:i,up:IK(i,r),fwd:r,eye:e}}function HK(e,t,n,r,i){let a=FK(e,t.eye),o=LK(a,t.right),s=LK(a,t.up),c=LK(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 UK(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 WK=16,GK=.1,KK=Math.PI/4,qK=Math.PI/5,JK=3.2,YK=2e4,XK=(()=>{let e=new Uint8Array(256*4);for(let t=0;t<256;t++){let{r:n,g:r,b:i}=hG(t/255);e.set([n,r,i,255],t*4)}return e})();function ZK(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 QK=(e,t)=>!t||e>=t[0]&&e<=t[1];function $K(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&&QK(s,t)&&QK(c,n)&&QK(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 uK(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 eq=_t(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(KK),C=K(qK),w=K(JK),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=Ct(()=>{let n=ZK(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||!QK(t,s)||!QK(g,c)||!QK(_,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?UK(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=Ct(()=>k&&D?.cols?$K(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=fH(b.current,MK),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=NG({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:XK,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}`,WV(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=gG(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(Uz(O),i-4,e+4),s.fillText(Uz(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,WK,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=NG({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=Fz(C,8),k=Fz(w,8),j=Rz(a,o,O),M=Rz(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(Uz(n),y.left+3,c-2)):(s.textAlign=`left`,s.textBaseline=`top`,s.fillText(Uz(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(Hz(e,O),T(e),y.top+S+6);s.textAlign=`right`,s.textBaseline=`middle`;for(let e of M)s.fillText(Hz(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=VK(BK(g.center,i,e,t),g.center,{x:0,y:1,z:0}),o=Math.PI/3,c=h?3:WK,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=HK(e,a,o,m,_);return{sx:t.sx+c,sy:t.sy+c,depth:t.depth}};F=(e,t,n)=>{let r=b(UK(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=Fz(v.maxX-v.minX,6),D=Fz(v.maxY-v.minY,6),O=Fz(v.maxZ-v.minZ,6),k=Rz(v.minX,v.maxX,T),j=Rz(v.minY,v.maxY,D),M=Rz(v.minZ,v.maxZ,O),N=zz(v.minX,v.maxX,T/5,k),P=zz(v.minY,v.maxY,D/5,j),I=zz(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=UK(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=UK(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=UK(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=UK(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=GK*(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=GK*(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=GK*(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(UK(t,v.minY,v.minZ,v).x,!1);for(let t of k)e(UK(t,v.minY,v.minZ,v).x,!0);for(let e of P)t(UK(v.minX,e,v.minZ,v).z,!1);for(let e of j)t(UK(v.minX,e,v.minZ,v).z,!0);for(let e of I)n(UK(v.minX,v.minY,e,v).y,!1);for(let e of M)n(UK(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()}=${Uz(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=UK(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(Hz(e,T),n.sx,n.sy+12))}for(let e of j){let t=UK(v.minX,e,v.minZ,v).z,n=b({x:-1.22,y:-1,z:t});n.depth<.02||(s.textAlign=`right`,s.fillText(Hz(e,D),n.sx-4,n.sy))}for(let e of M){let t=UK(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(Hz(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(WK+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:XK,colorAxis:T,pointRadius:m,fill:te&&(V===`filled`||V===`both`),wire:te&&(V===`wireframe`||V===`both`),fillAlpha:ee,wireColor:PK(u,.5)}),_.render(),P.current!==g&&(P.current=g,HH(t));else if(g.cols){let e=g.cols,t=Math.max(1,Math.ceil(e.length/YK));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=gG(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??=qH(()=>L.current(),()=>x.current),W(()=>()=>R.current?.cancel(),[]);let z=()=>{S.current=KK,C.current=qK,w.current=JK,R.current.schedule()};return St(_,()=>({autoscale:z}),[]),W(()=>dB(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 GH(()=>{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=KK,C.current=qK,w.current=JK,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)}},[]),kt(`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`}})]})}),tq={top:14,right:24,bottom:40,left:64},nq=5;function rq(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}function iq(e){return Math.max(10,Math.min(200,Math.ceil(Math.sqrt(e))))}function aq(e,t,n){let r=(e-t)/n;return Math.exp(-.5*r*r)/(n*Math.sqrt(2*Math.PI))}function oq(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:iq(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 sq({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=LU(),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=Ct(()=>oq(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}=tq,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`,WV(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:Fz(P,5),R=Rz(0,S?P:N,L);r.strokeStyle=m,r.lineWidth=1,r.setLineDash(rq(`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=aq(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-nq,t),r.lineTo(s,t),r.stroke(),r.fillText(S?`10^${e.toFixed(0)}`:Hz(e,L),s-4,t)}let B=Fz(E-T,Iz(c)),V=Rz(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+nq),r.stroke(),r.fillText(Hz(e,B),t,i+d+nq+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??=qH(()=>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}=tq,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=`${Uz(m+e*g)} – ${Uz(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(){BH(m.current),m.current=zH(()=>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 GH(()=>{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}=tq,i=n.width-tq.left-tq.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)}},[]),kt(`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 cq=`
484
+ }`,Mq=16e6,Nq=128,Pq=[`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 Fq(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 Iq(e){let t=e.getContext(`webgl2`,{antialias:!0,alpha:!0,premultipliedAlpha:!0,depth:!0});if(!t)return null;let n=(e,n,r,i)=>hU(t,`gl3d|${e}|${n}`,()=>{let a=rU(t,t.VERTEX_SHADER,e),o=rU(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([...Pq,...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(Eq,Dq,r,[`u_size`,`u_rim`]),a=n(Oq,Aq,r,[`u_alpha`,`u_solid`]),o=n(kq,jq,[],[`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=[Fq(e),Fq(n),Fq(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=Fq(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/Mq))),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)/Nq)),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 Lq=new Map;function Rq(e,t){let n=Lq.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;Lq.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 zq(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}function Bq(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 Vq(e,t){return e.x*t.x+e.y*t.y+e.z*t.z}function Hq(e){return Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z)}function Uq(e){let t=Hq(e);return t>1e-12?{x:e.x/t,y:e.y/t,z:e.z/t}:{x:0,y:0,z:1}}function Wq(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 Gq(e,t,n){let r=Uq(zq(t,e)),i=Uq(Bq(r,n));return{right:i,up:Bq(i,r),fwd:r,eye:e}}function Kq(e,t,n,r,i){let a=zq(e,t.eye),o=Vq(a,t.right),s=Vq(a,t.up),c=Vq(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 qq(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 Jq=16,Yq=.1,Xq=Math.PI/4,Zq=Math.PI/5,Qq=3.2,$q=2e4,eJ=(()=>{let e=new Uint8Array(256*4);for(let t=0;t<256;t++){let{r:n,g:r,b:i}=yK(t/255);e.set([n,r,i,255],t*4)}return e})();function tJ(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 nJ=(e,t)=>!t||e>=t[0]&&e<=t[1];function rJ(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&&nJ(s,t)&&nJ(c,n)&&nJ(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 mq(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 iJ=_t(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(Xq),C=K(Zq),w=K(Qq),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=Ct(()=>{let n=tJ(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||!nJ(t,s)||!nJ(g,c)||!nJ(_,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?qq(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=Ct(()=>k&&D?.cols?rJ(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=gU(b.current,Iq),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=LK({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:eJ,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}`,JH(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=bK(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(OV(O),i-4,e+4),s.fillText(OV(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,Jq,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=LK({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=bV(C,8),k=bV(w,8),j=CV(a,o,O),M=CV(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(OV(n),y.left+3,c-2)):(s.textAlign=`left`,s.textBaseline=`top`,s.fillText(OV(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(DV(e,O),T(e),y.top+S+6);s.textAlign=`right`,s.textBaseline=`middle`;for(let e of M)s.fillText(DV(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=Gq(Wq(g.center,i,e,t),g.center,{x:0,y:1,z:0}),o=Math.PI/3,c=h?3:Jq,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=Kq(e,a,o,m,_);return{sx:t.sx+c,sy:t.sy+c,depth:t.depth}};F=(e,t,n)=>{let r=b(qq(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=bV(v.maxX-v.minX,6),D=bV(v.maxY-v.minY,6),O=bV(v.maxZ-v.minZ,6),k=CV(v.minX,v.maxX,T),j=CV(v.minY,v.maxY,D),M=CV(v.minZ,v.maxZ,O),N=wV(v.minX,v.maxX,T/5,k),P=wV(v.minY,v.maxY,D/5,j),I=wV(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=qq(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=qq(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=qq(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=qq(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=Yq*(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=Yq*(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=Yq*(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(qq(t,v.minY,v.minZ,v).x,!1);for(let t of k)e(qq(t,v.minY,v.minZ,v).x,!0);for(let e of P)t(qq(v.minX,e,v.minZ,v).z,!1);for(let e of j)t(qq(v.minX,e,v.minZ,v).z,!0);for(let e of I)n(qq(v.minX,v.minY,e,v).y,!1);for(let e of M)n(qq(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()}=${OV(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=qq(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(DV(e,T),n.sx,n.sy+12))}for(let e of j){let t=qq(v.minX,e,v.minZ,v).z,n=b({x:-1.22,y:-1,z:t});n.depth<.02||(s.textAlign=`right`,s.fillText(DV(e,D),n.sx-4,n.sy))}for(let e of M){let t=qq(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(DV(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(Jq+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:eJ,colorAxis:T,pointRadius:m,fill:te&&(V===`filled`||V===`both`),wire:te&&(V===`wireframe`||V===`both`),fillAlpha:ee,wireColor:Rq(u,.5)}),_.render(),P.current!==g&&(P.current=g,KU(t));else if(g.cols){let e=g.cols,t=Math.max(1,Math.ceil(e.length/$q));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=bK(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??=ZU(()=>L.current(),()=>x.current),W(()=>()=>R.current?.cancel(),[]);let z=()=>{S.current=Xq,C.current=Zq,w.current=Qq,R.current.schedule()};return St(_,()=>({autoscale:z}),[]),W(()=>XV(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 YU(()=>{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=Xq,C.current=Zq,w.current=Qq,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)}},[]),kt(`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`}})]})}),aJ={top:14,right:24,bottom:40,left:64},oJ=5;function sJ(e){return e===`dashed`?[5,4]:e===`dotted`?[1,4]:[]}function cJ(e){return Math.max(10,Math.min(200,Math.ceil(Math.sqrt(e))))}function lJ(e,t,n){let r=(e-t)/n;return Math.exp(-.5*r*r)/(n*Math.sqrt(2*Math.PI))}function uJ(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:cJ(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 dJ({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=VW(),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=Ct(()=>uJ(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}=aJ,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`,JH(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:bV(P,5),R=CV(0,S?P:N,L);r.strokeStyle=m,r.lineWidth=1,r.setLineDash(sJ(`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=lJ(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-oJ,t),r.lineTo(s,t),r.stroke(),r.fillText(S?`10^${e.toFixed(0)}`:DV(e,L),s-4,t)}let B=bV(E-T,xV(c)),V=CV(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+oJ),r.stroke(),r.fillText(DV(e,B),t,i+d+oJ+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??=ZU(()=>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}=aJ,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=`${OV(m+e*g)} – ${OV(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(){WU(m.current),m.current=UU(()=>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 YU(()=>{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}=aJ,i=n.width-aJ.left-aJ.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)}},[]),kt(`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 fJ=`
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
- `,lq=`
493
+ `,pJ=`
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
- `,uq=`#version 300 es
501
+ `,mJ=`#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
- ${cq}
507
+ ${fJ}
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
- }`,dq=`#version 300 es
514
+ }`,hJ=`#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
- ${cq}
517
+ ${fJ}
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
- }`,fq=`#version 300 es
527
+ }`,gJ=`#version 300 es
528
528
  precision highp float;
529
529
  uniform vec4 u_color;
530
- ${lq}
530
+ ${pJ}
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
- }`,pq=`#version 300 es
535
+ }`,_J=`#version 300 es
536
536
  precision highp float;
537
537
  flat in float v_k;
538
538
  uniform sampler2D u_palette;
539
- ${lq}
539
+ ${pJ}
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
- }`,mq=`#version 300 es
545
+ }`,vJ=`#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
- ${cq}
549
+ ${fJ}
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
- }`,hq=`#version 300 es
565
+ }`,yJ=`#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
- ${lq}
572
+ ${pJ}
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
- }`,gq=`#version 300 es
584
+ }`,bJ=`#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
- ${cq}
587
+ ${fJ}
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
- }`,_q=`#version 300 es
592
+ }`,xJ=`#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
- ${lq}
598
+ ${pJ}
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
- }`,vq=-3e38;function yq(e){for(let t=0;t<e.length;t++)if(e[t]-e[t]===0)return e[t];return 0}function bq(e){let t=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0});if(!t)return null;let n=(e,n,i,a)=>dH(t,`glPlot|${e}|${n}`,()=>r(e,n,i,a)),r=(e,n,r,i)=>{let a=$V(t,t.VERTEX_SHADER,e),o=$V(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(uq,fq,[`a_xa`,`a_xb`,`a_loa`,`a_lob`,`a_hia`,`a_hib`,`a_bstart`],[`u_color`]),a=n(dq,pq,[`a_x0`,`a_x1`,`a_y0`,`a_y1`,`a_k`],[`u_palette`]),o=n(mq,hq,[`a_ax`,`a_ay`,`a_bx`,`a_by`,`a_bstart`],[`u_color`,`u_half`,`u_ext`]),s=n(gq,_q,[],[`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=yq(t),o.oy=yq(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=yq(n),c.oy=yq(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=yq(t),o.oy=yq(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:vq}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 xq(e){let t=K({plot:null,failed:!1,size:``});return W(()=>()=>{t.current.plot?.dispose(),t.current.plot=null},[]),bt((n,r)=>{let i=t.current,a=e.current;if(!i.plot&&!i.failed&&a&&(i.plot=fH(a,bq),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 Sq(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 Cq=16;function wq(e,t,n,r){let i=Sq(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(Cq),m=new Int32Array(Cq);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(Cq-1,Math.floor(a/(2*Math.PI)*Cq));p[o]+=t[e],m[o]++}return{n:a,rMin:c,rMax:l,x:d,y:f,means:Array.from({length:Cq},(e,t)=>m[t]>0?p[t]/m[t]:0)}}function Tq({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=Ct(()=>wq(e,t,o,s),[e,t,o,s]),_=K(g);G(()=>{_.current=g},[g]);let v=K(null),y=xq(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`,WV(r);return}let w=g-m||1,T=(Math.min(t-64,n-32-24)-4)/2,E=t/2,D=32+T,O=Fz(w,4),k=Rz(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(Hz(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,PK(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/Cq;r.fillStyle=l,r.globalAlpha=.75;for(let i=0;i<Cq;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<Cq;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??=qH(()=>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 GH(()=>{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)},[]),kt(`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 Eq(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 Dq(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 Oq(e,t){let n=new Float64Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n}function kq(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 Aq(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 jq=new Float64Array,Mq=new Float64Array;function Nq(e,t,n){let r=t>>1;jq.length<r&&(jq=new Float64Array(r),Mq=new Float64Array(r));let i=jq.subarray(0,r),a=Mq.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}Aq(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 Pq=new Float64Array,Fq=0;function Iq(e){if(Fq===e)return Pq.subarray(0,e);Pq.length<e&&(Pq=new Float64Array(Math.max(e,Pq.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++){Pq[t]=.5*(1-i);let e=i*n-a*r;a=a*n+i*r,i=e}return Fq=e,Pq.subarray(0,e)}var Lq={top:14,right:24,bottom:40,left:64},Rq=5;function zq(e){let t=1;for(;t<e;)t<<=1;return t}function Bq(e,t,n,r){let i=e.length,a=Math.max(2,zq(i)),o=Nq(e,a,n===`hann`?Iq(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 Vq({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=LU(),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 _=Ct(()=>e.length>=4?Bq(e,t,a,i):null,[e,t,a,i]),v=Ct(()=>_&&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}=Lq,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`,WV(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`,WV(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=Fz(I-F,5),V=Rz(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:Fz(P-N,Iz(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})():Rz(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-Rq,z(e)),r.lineTo(s,z(e)),r.stroke(),r.fillText(Hz(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+Rq),r.stroke(),r.fillText(Hz(e,T?e:ee),R(e),i+l+Rq+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?Eq(k,O,Math.log10(N*M),Math.log10(P*M),re):Eq(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??=qH(()=>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 GH(()=>{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 Hq(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 Uq(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,Hq(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 Wq={top:14,right:24,bottom:48,left:64},Gq=5;function Kq(e,t){let n=e.length;if(n===0)return null;let[r,i,a,o,s]=Uq(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 qq({groups:e,color:t=`#fb923c`,whiskers:n=`1.5iqr`,height:r=400,backgroundToken:i=``,onPlotContextMenu:a}){let o=LU(),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=Ct(()=>e.filter(e=>e.values.length>0).map(e=>({label:e.label,box:Kq(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}=Wq,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`,WV(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=Fz(C-S,5),D=Rz(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-Gq,T(e)),r.lineTo(l,T(e)),r.stroke(),r.fillText(Hz(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+Gq+2,k-4,c-Gq-4),r.clip(),r.fillText(n,t,i+f+Gq+2),r.restore()}}let v=K(_);v.current=_;let y=K(null);y.current??=qH(()=>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 GH(()=>{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 Jq(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 Yq=e=>e.includes(`.`)&&!e.includes(`e`)?e.replace(/\.?0+$/,``):e;function Xq(e){return e>=1e3?`${Yq((e/1e3).toPrecision(3))}k`:Yq(e.toPrecision(3))}function Zq(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 Qq={top:14,right:24,bottom:40,left:68},$q=[[8,0,16],[48,0,96],[104,0,144],[160,0,128],[200,32,64],[230,100,16],[250,200,32],[255,255,220]],eJ=-80;function tJ(e){let t=$q.length-1,n=Math.min(t-1,Math.floor(e*t)),r=e*t-n,[i,a,o]=$q[n],[s,c,l]=$q[n+1];return[i+(s-i)*r,a+(c-a)*r,o+(l-o)*r]}var nJ=(()=>{let e=new Uint8Array(256*4);for(let t=0;t<256;t++){let[n,r,i]=tJ(t/255);e.set([n,r,i,255],t*4)}return e})();function rJ(e){let t=1;for(;t<e;)t<<=1;return t}var iJ=(e,t)=>Math.log(1+e/t*9)/Math.log(10),aJ=(e,t)=>t*(10**e-1)/9;function oJ({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=LU(),d=K(null),f=K(null),p=K(null),m=K(null),h=K(null),g=K(l);G(()=>{g.current=l},[l]);let _=rJ(Math.max(4,Math.min(n,4096))),v=Math.max(1,Math.round(_*(1-Math.max(0,Math.min(.95,r))))),y=Ct(()=>{if(!o)return null;let e=_>>1,n=t/2;return Int32Array.from({length:e},(t,r)=>Math.min(e-1,Math.floor(aJ((r+.5)/e,n)/n*e)))},[o,_,t]),b=K(null),x=Ct(()=>b.current=Zq(e,_,v,i===`hann`,a===`db`,y,b.current),[e,_,v,i,a,y]),S=Ct(()=>({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+eJ,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=fH(f.current,bq),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=NG(Qq,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`,WV(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=Jq(y,N).grid;j&&j.setGrid(`cells`,e.values,e.w,Math.min(e.h,j.maxTextureSize),[0,e.w,0,e.h],nJ,P,F),E.current.grid=y,E.current.shown=e,HH(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]=tJ(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?iJ(e,R):e/R));L.strokeStyle=v,L.lineWidth=.5,L.globalAlpha=.4;let B=Rz(0,R,Fz(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(Xq(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=Fz(V,6),te=Rz(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(Hz(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??=qH(()=>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 GH(()=>{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)},[]),kt(`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 sJ=300,cJ=256,lJ=-60,uJ=[];function dJ({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=Ct(()=>Zq(e,c,l,i===`hann`,u,null),[e,c,l,i,u]);return q(eq,{points:uJ,surface:Ct(()=>fJ(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 fJ(e,t,n,r,i){let{frames:a,bins:o,values:s}=e;if(a<2||o<2)return;let c=Math.min(a,sJ),l=Math.min(o,cJ),u=i?20*Math.log10(Math.max(e.max,1e-12))+lJ:-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 pJ(e,t,n){return Array.from({length:n},(r,i)=>e+(i+1)/(n+1)*(t-e))}function mJ(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 hJ(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 gJ(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 _J={top:14,right:32,bottom:80,left:80};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]}var yJ=[[33,102,172],[103,169,207],[209,229,240],[247,247,247],[253,219,199],[239,138,98],[178,24,43]],bJ=[[13,8,135],[84,2,163],[139,10,165],[185,50,137],[219,92,104],[244,136,73],[254,188,43],[240,249,33]],xJ=[[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 SJ(e,t){let n=e.length-1,r=Math.min(n-1,Math.floor(t*n));return vJ(e[r],e[r+1],t*n-r)}function CJ(e,t){return SJ(t===`plasma`?bJ:t===`viridis`?xJ:yJ,e)}function wJ(e){let t=new Uint8Array(256*4);for(let n=0;n<256;n++){let[r,i,a]=CJ(n/255,e);t.set([r,i,a,255],n*4)}return t}function TJ(e){return Math.abs(e)>=1e4||Math.abs(e)<.01&&e!==0?e.toExponential(1):String(parseFloat(e.toPrecision(3)))}function EJ(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 DJ(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=hJ(a),i=n[e.w]-n[0];u=Float64Array.from(n,e=>t+(e-n[0])/i*r)}if(l){let t=hJ(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 OJ(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 kJ(e,t,n,r,i,a){let o=Math.max(1,i),s=Math.max(1,a),c=Int32Array.from({length:o},(e,r)=>OJ(t.xB,n+r+.5)),l=new Float32Array(o*s);for(let n=0;n<s;n++){let i=OJ(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 AJ({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=Ct(()=>r??EJ(e??[],t??[],n??[]),[r,e,t,n]),C=Ct(()=>{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=fH(m.current,bq),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=NG(_J,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`,WV(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}`},HH(_.current));let{xCentres:F,yCentres:I,contours:L}=w.current,R=x?x.maxTextureSize:Math.max(1,Math.round(S*N)),z=Jq(m,R).grid,B=DJ(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?kJ(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],wJ(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]=CJ(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]=CJ(Math.max(0,Math.min(1,(n-g)/(v-g))),b);U.fillStyle=.299*r+.587*i+.114*a>128?`#000`:`#fff`,U.fillText(TJ(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?pJ(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=>mJ(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]=CJ(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(TJ(v),ce+12+2,le),r.fillText(TJ(g),ce+12+2,le+ue),r.fillText(TJ((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}=NG(_J,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]}: ${TJ(_)}`;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??=qH(()=>F.current(),()=>_.current);let L=()=>{b.current||=zH(()=>{b.current=0,P()})};return W(()=>{I.current.now()},[S,C,i,a,c,l,u]),W(()=>()=>{I.current?.cancel(),BH(b.current)},[]),W(()=>{v.current=null,I.current.schedule()},[d]),G(()=>{let e=_.current;if(!e)return;let t=new GH(()=>{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=OJ(i.xB,t.clientX-n.left),o=OJ(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)}},[]),kt(`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 jJ=2e3,MJ=1024;function NJ(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<=jJ){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(MJ),l=(i-r)/MJ||1;for(let t=0;t<a;t++)c[Math.max(0,Math.min(MJ-1,Math.floor((e[t]-r)/l)))]++;for(let e=0;e<n.length;e++){let i=0;for(let a=0;a<MJ;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 PJ={top:14,right:24,bottom:48,left:64},FJ=120;function IJ(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 LJ(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]=Uq(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:FJ},(e,t)=>r+t/(FJ-1)*(i-r));return{shapes:n.map((e,n)=>{let{q1:o,median:c,q3:l}=a[n],u=NJ(e.values,t>0?t:IJ(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 RJ({groups:e,color:t=`#818cf8`,showBox:n=!0,bandwidth:r=0,orientation:i=`vertical`,backgroundToken:a=``,onPlotContextMenu:o}){let s=LU(),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=Ct(()=>LJ(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}=PJ,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`,WV(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=Fz(E-T,5),A=Rz(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(Hz(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(Hz(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<FJ;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=FJ-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??=qH(()=>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 GH(()=>{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 zJ={top:48,right:16,bottom:72,left:80},BJ=[8,24,64],VJ=[56,189,248];function HJ(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 UJ(e){return`${(e*100).toFixed(1)}%`}function WJ(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 GJ({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=Ct(()=>WJ(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}=zJ,{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`,WV(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]=HJ(BJ,VJ,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?UJ(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: ${UJ(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}=zJ,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?UJ(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??=qH(()=>x.current(),()=>s.current);let C=()=>S.current.schedule(),w=()=>{BH(u.current),u.current=zH(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 GH(()=>{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}=zJ,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)}},[]),kt(`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 KJ={top:24,right:24,bottom:48,left:64};function qJ(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 JJ(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 YJ(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 XJ(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 ZJ({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=Ct(()=>qJ(e,t),[e,t]),f=Ct(()=>n===`pr`?{roc:null,pr:YJ(d)}:{roc:JJ(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}=KJ,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`,WV(r);return}let S=e=>c+e*l,C=e=>i+(1-e)*d,w=Rz(0,1,Fz(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(),XJ(r,t,n,a),r.strokeStyle=x,r.lineWidth=1,r.stroke(),r.beginPath(),XJ(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=Eq(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??=qH(()=>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 GH(()=>{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 QJ={top:20,right:64,bottom:48,left:64};function $J({xValues:e,series:t,xLabel:n=`Epoch`,backgroundToken:r=``,onPlotContextMenu:i}){let a=LU(),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 _=Ct(()=>{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:kq(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}=QJ,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`,WV(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=Fz(C.hi-C.lo,5),N=Rz(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=Fz(D-E,6),F=Rz(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?Eq(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(Hz(e,M),l-6,A(e));if(T){let e=Fz(w.hi-w.lo,5),t=Rz(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(Hz(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(Hz(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}=QJ,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}: ${Uz(e.values[D])}`,T+6,O),O+=14);w(0)}let x=K(y);x.current=y;let S=K(null);S.current??=qH(()=>x.current(),()=>c.current);let C=()=>S.current.schedule(),w=()=>{BH(d.current),d.current=zH(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 GH(()=>{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)}},[]),kt(`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 eY={top:40,right:24,bottom:40,left:72},tY=`#ef4444`,nY=`#f97316`,rY=`#22d3ee`;function iY(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 aY({points:e,sigmaLevel:t=3,color:n=`#22d3ee`,backgroundToken:r=``,onPlotContextMenu:i}){let a=LU(),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 _=Ct(()=>iY(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}=eY,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`,WV(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=Fz(D-E,5),j=Rz(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} ${Uz(e)}`,l+u-2,o-5))};M(w,nY,`UCL`,[5,3]),M(C,rY,`CL`,[]),M(T,nY,`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=Dq(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?tY: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(Hz(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}=eY,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}: `}${Uz(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?tY:_,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??=qH(()=>S.current(),()=>c.current);let w=()=>C.current.schedule(),T=()=>{BH(d.current),d.current=zH(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 GH(()=>{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)}},[]),kt(`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 oY={top:32,right:24,bottom:24,left:24},sY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`],cY=16;function lY(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 uY(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:cY},(e,t)=>lY((t+.5)/cY));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(cY-1,Math.floor(e*cY))):-1}for(let t=0;t<e.length;t++)s[t]<0&&(s[t]=0)}else if(!n&&e.colorIndex){c=sY;for(let t=0;t<e.length;t++)s[t]=Math.max(0,e.colorIndex[t])%sY.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 dY({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=Ct(()=>uY(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 _=xq(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}=oY,{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,PK(e.color,j),1,e.starts)),v.current=w,HH(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(Hz(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=sY[r%sY.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}=oY,{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??=qH(()=>w.current(),()=>u.current);let E=()=>T.current.schedule(),D=()=>{BH(p.current),p.current=zH(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 GH(()=>{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-oY.left-oY.right,a=r.length,o=t.clientX-n.left-oY.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)}},[]),kt(`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 fY(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 pY(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 mY={top:16,right:16,bottom:16,left:16},hY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function gY(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 _Y(e){let[t,n,r]=gY(e);return`rgb(${t},${n},${r})`}var vY=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++)e.set([...gY(t/255),255],t*4);return e})(),yY=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++){let[n,r,i]=PK(hY[t%hY.length],1);e.set([n*255,r*255,i*255,255],t*4)}return e});function bY(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 xY({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=Ct(()=>bY(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}=mY,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=fH(s.current,jG),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,HH(l.current));let f=`${c.mode}|${u}|${d}`;return n.style!==f&&(r.setStyle(c.mode===`single`?{kind:`single`,rgba:PK(u,1)}:{kind:c.mode,palette:c.mode===`colormap`?vY:yY()},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`,WV(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:mY.left,top:mY.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`?_Y(i):d.mode===`dataset`?hY[i%hY.length]:c,r.globalAlpha=.8,r.fill()}r.globalAlpha=1}if(l){let e=Math.min(120,Math.floor((n-mY.top-mY.bottom)*.4)),i=t-mY.right-12,o=mY.top+8;for(let t=0;t<e;t++)r.fillStyle=_Y(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=mY.left,i=n-mY.bottom-10;r.font=`9px ${Q.mono}`,r.textBaseline=`top`,E.forEach((n,o)=>{e>t-mY.right-60&&(e=mY.left,i-=14),r.fillStyle=hY[o%hY.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<mY.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??=qH(()=>w.current(),()=>l.current);let E=()=>T.current.schedule(),D=()=>{BH(f.current),f.current=zH(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 GH(()=>{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])-mY.left,g=e=>u(i.y[e])-mY.top,_=a+8,y=`${s}|${c}|${_}`;(!t||t.model!==o||t.key!==y)&&(t={model:o,key:y,g:fY(i.length,f,p,_,m,g)}),d.current=pY(t.g,n.clientX-r.left-mY.left,n.clientY-r.top-mY.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)}},[]),kt(`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 SY={top:8,right:8,bottom:8,left:8},CY=20,wY=[`#f97316`,`#fb923c`,`#fdba74`,`#fbbf24`,`#fcd34d`,`#4ade80`,`#34d399`,`#38bdf8`,`#818cf8`,`#a78bfa`];function TY(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 EY(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 DY(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 OY(e){return wY[e%wY.length]}function kY({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=Ct(()=>{let t=TY(e);return{roots:t,flat:EY(t),numRows:DY(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=SY.left+e.x0*t,o=(e.x1-e.x0)*t;return{x:a,y:i===`topdown`?SY.top+e.depth*CY:SY.top+n-(e.depth+1)*CY,w:o,h:CY-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`,WV(r);return}let{flat:l,numRows:u}=p.current,f=t-SY.left-SY.right,v=u*CY;for(let e of l){let t=_(e,f,v,u,c);if(!(t.w<1)&&(r.fillStyle=OY(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,CY-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+CY/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-SY.left-SY.right,l*CY,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+CY+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??=qH(()=>b.current(),()=>o.current);let S=()=>x.current.schedule(),C=()=>{BH(l.current),l.current=zH(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 GH(()=>{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-SY.left-SY.right,f=o*CY,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)}},[]),kt(`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 AY={top:24,right:24,bottom:52,left:56},jY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`],MY=.8;function NY(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 PY(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 FY({groups:e,columns:t,seriesNames:n,colors:r,mode:i=`grouped`,horizontal:a=!1,valueRange:o,backgroundToken:s=``,onPlotContextMenu:c}){let l=LU(),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=Ct(()=>{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=NY(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]??jY[n%jY.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=NG(AY,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=fH(d.current,bq),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`,WV(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(Hz(t,(g-h)/5),n,_+k+4)):(r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(Hz(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},HH(p.current));let I=Math.min(2,window.devicePixelRatio||1),L=Math.max(1,Math.round(M*I)),R=j.map(e=>{let t=JV(e);return[t[0],t[1],t[2],MY]}),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=PY(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=PY(s,d,L);r.globalAlpha=MY;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]+` `:``}${Uz(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??=qH(()=>j.current(),()=>p.current);let N=()=>{g.current||=zH(()=>{g.current=0,A()})};return W(()=>{M.current.now()},[y,n,r,i,a,o]),W(()=>()=>{M.current?.cancel(),BH(g.current)},[]),W(()=>{m.current=null,M.current.schedule()},[s]),G(()=>{let e=p.current;if(!e)return;let t=new GH(()=>{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)}},[]),kt(`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 IY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function LY(e,t){if(!t)return IY[e%IY.length];if(e===0)return t;let n=IY.filter(e=>e.toLowerCase()!==t.toLowerCase());return n[(e-1)%n.length]}var RY={top:36,right:36,bottom:36,left:36};function zY({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`,RY.left+8,RY.top+8);return}let h=c.length,g=t/2,_=n/2,v=Math.min(t-RY.left-RY.right,n-RY.top-RY.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=LY(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=RY.left,i=n-RY.bottom-10;r.font=`9px ${Q.mono}`,r.textBaseline=`top`;for(let n=0;n<l.length&&(r.fillStyle=LY(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-RY.right-30));n++);}}let g=K(h);g.current=h;let _=K(null);_.current??=qH(()=>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 GH(()=>{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)}},[]),kt(`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 BY={top:16,right:16,bottom:40,left:52},VY=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function HY(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=>kq(e)),xLo:c,xHi:l,yLo:u,yHi:d}}function UY({series:e,stacked:t=!1,yRange:n,backgroundToken:r=``,onPlotContextMenu:i}){let a=LU(),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=Ct(()=>{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=HY(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=Eq(a,o,n,r,i);return{x:Oq(a,c),hi:Oq(o,c),lo:s?Oq(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`,WV(i);return}let h=NG(BY,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(Hz(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(Hz(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},HH(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)=>JV(VY[t%VY.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=VY[e%VY.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=VY[n%VY.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=fH(s.current,bq),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}=NG(BY,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=${Uz(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??=qH(()=>O.current(),()=>l.current);let A=()=>{f.current||=zH(()=>{f.current=0,D()})};return W(()=>{k.current.now()},[e,h,n]),W(()=>()=>{k.current?.cancel(),BH(f.current)},[]),W(()=>{u.current=null,k.current.schedule()},[r]),G(()=>{let e=l.current;if(!e)return;let t=new GH(()=>{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)}},[]),kt(`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 WY={top:16,right:16,bottom:40,left:52},GY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function KY({series:e,complement:t=!1,logX:n=!1,backgroundToken:r=``,onPlotContextMenu:i}){let a=LU(),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=Ct(()=>{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`,WV(r);return}let{top:f,right:m,bottom:y,left:b}=WY,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(Hz(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=GY[e%GY.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=GY[n%GY.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}=WY,l=n-a-WY.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=Uz(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??=qH(()=>x.current(),()=>c.current);let C=()=>S.current.schedule(),w=()=>{BH(d.current),d.current=zH(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 GH(()=>{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)}},[]),kt(`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 qY={top:16,right:40,bottom:40,left:52},JY=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function YY(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 XY(e){let[t,n,r]=YY(e);return`rgb(${t},${n},${r})`}var ZY=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++)e.set([...YY(t/255),255],t*4);return e})(),QY=()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++){let[n,r,i]=PK(JY[t%JY.length],1);e.set([n*255,r*255,i*255,255],t*4)}return e};function $Y(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 eX({points:e,color:t=`#64748b`,colorByNumeric:n=!1,maxRadius:r=24,backgroundToken:i=``,onPlotContextMenu:a}){let o=LU(),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=Ct(()=>$Y(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}=qY,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=fH(c.current,jG),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,HH(u.current));let l=`${o.mode}|${s}`;return n.style!==l&&(r.setStyle(o.mode===`single`?{kind:`single`,rgba:PK(s,1)}:{kind:o.mode,palette:o.mode===`colormap`?ZY:QY()},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`,WV(r);return}let{xLo:p,xHi:m,yLo:h,yHi:C}=d.ext,{top:w,left:T}=qY,{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(Hz(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(Hz(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`?XY(n):d.mode===`dataset`?JY[n%JY.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-qY.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=JY[n%JY.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(`(${Uz(a.x[i])}, ${Uz(a.y[i])})`),m.push(`size=${Uz(a.size[i])}`);let _=a.colorIndex?.[i];_!==void 0&&_>=0&&a.colorLabels?m.push(a.colorLabels[_]):a.colorValue&&m.push(Uz(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<qY.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??=qH(()=>T.current(),()=>u.current);let D=()=>E.current.schedule(),O=()=>{BH(p.current),p.current=zH(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 GH(()=>{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])-qY.left,h=e=>p(i.y[e])-qY.top,_=a+6,v=`${s}|${c}|${_}`;(!t||t.model!==o||t.key!==v)&&(t={model:o,key:v,g:fY(i.length,l,u,_,m,h)}),f.current=pY(t.g,n.clientX-r.left-qY.left,n.clientY-r.top-qY.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)}},[]),kt(`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 tX={top:8,right:8,bottom:8,left:8},nX=[`#f97316`,`#38bdf8`,`#4ade80`,`#a78bfa`,`#fbbf24`,`#fb7185`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function rX(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 iX(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=iX(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 aX({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=Ct(()=>rX(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`,WV(i);return}let u=p.current,f=t-tX.left-tX.right,_=n-tX.top-tX.bottom,v=iX(u,tX.left,tX.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=nX[l%nX.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??=qH(()=>y.current(),()=>a.current);let x=()=>b.current.schedule(),S=()=>{BH(l.current),l.current=zH(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 GH(()=>{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)}},[]),kt(`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 oX={top:8,right:8,bottom:8,left:8},sX=14,cX=8,lX=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function uX(e,t,n,r){if(e.length===0||t.length===0)return{nodes:[],links:[]};let i=n-oX.left-oX.right,a=r-oX.top-oX.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=>oX.left+e/Math.max(1,c)*(i-sX),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)*cX,i=0;for(let e of n)i+=Math.max(8,(d.get(e)??0)/f*r*.8);let o=oX.top+(a-i-(n.length-1)*cX)/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:lX[e.indexOf(a)%lX.length]}),o+=s+cX}}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+sX,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 dX({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`,WV(r);return}let d=uX(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,sX,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+sX+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??=qH(()=>v.current(),()=>o.current);let b=()=>y.current.schedule(),x=()=>{BH(u.current),u.current=zH(_)};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 GH(()=>{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)}},[]),kt(`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 fX={top:24,right:24,bottom:52,left:52};function pX({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`,WV(r);return}let{top:h,right:g,bottom:_,left:v}=fX,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}=fX,f=t-u-fX.right,h=n-l-fX.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??=qH(()=>_.current(),()=>o.current);let y=()=>v.current.schedule(),b=()=>{BH(l.current),l.current=zH(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 GH(()=>{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-fX.left-fX.right,s=-1,l=20;for(let e=0;e<r.length;e++){let t=fX.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)}},[]),kt(`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 mX={top:24,right:24,bottom:48,left:52};function hX({points:e,color:t=`#a78bfa`,backgroundToken:n=``,onPlotContextMenu:r}){let i=LU(),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`,WV(r);return}let{xLo:_,xHi:v,yLo:y,yHi:b}=g(),{top:x,right:S,bottom:C,left:w}=mX,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(Hz(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(Hz(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}=mX,y=t-v-mX.right,b=n-_-mX.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=`(${Uz(s.theoretical)}, ${Uz(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??=qH(()=>y.current(),()=>s.current);let x=()=>b.current.schedule(),S=()=>{BH(u.current),u.current=zH(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 GH(()=>{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}=mX,p=i-d-mX.right,h=n.height-u-mX.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)}},[]),kt(`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 gX={top:8,right:16,bottom:40,left:120},_X=22,vX=3,yX=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function bX({tasks:e,backgroundToken:t=``,onPlotContextMenu:n}){let r=LU(),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`,WV(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}=gX,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*(_X+vX)+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(Hz(t,(g-h)/T),n,r+4)}for(let e=0;e<u.length;e++){let t=u[e],n=v+e*(_X+vX),r=yX[(w.get(t.group??t.label)??0)%yX.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,_X-vX),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+(_X-vX)/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}: ${Uz(s.start)} → ${Uz(s.end)} (${Uz(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-gX.left-gX.right,y=e=>gX.left+(e-h)/(g-h)*v,b=gX.top+i*(_X+vX),x=(y(s.start)+y(s.end))/2,S=Math.max(4,Math.min(t-f-8,x-f/2)),C=b-22<gX.top?b+_X+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??=qH(()=>_.current(),()=>o.current);let y=()=>v.current.schedule(),b=()=>{BH(l.current),l.current=zH(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 GH(()=>{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-gX.top)/(_X+vX));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)}},[]),kt(`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 xX=e=>[...e].filter(e=>Number.isFinite(e.at)).sort((e,t)=>e.at-t.at),SX=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]},CX=e=>`#${e.map(e=>Math.round(e).toString(16).padStart(2,`0`)).join(``)}`;function wX(e,t,n,r){let i=t?xX(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=SX(o.color),u=SX(s.color);return CX([l[0]+(u[0]-l[0])*c,l[1]+(u[1]-l[1])*c,l[2]+(u[2]-l[2])*c])}function TX(e,t,n,r,i,a=96){let o=i-r||1,s=t?xX(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:wX(`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:wX(`gradient`,s,n,r+(t+.5)/a*o)}))}function EX(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 DX(e,t,n){let r=t?xX(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 OX=.75*Math.PI,kX=1.5*Math.PI;function AX({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(dU()),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=DU(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`,WV(p);return}let{cols:y,rows:b}=jX(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`?VX(p,e,n,r,x,S,e.color,e.alarm??null,h):HX(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??=qH(()=>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 GH(()=>{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)?MX(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 jX(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 MX=(e,t)=>Hz(e,Fz(Math.abs(t),100)),NX=(e,t)=>Math.max(0,Math.min(1,(t-e.min)/(e.max-e.min||1))),PX=(e,t)=>{let n=e.fromZero?NX(e,0):0;return[Math.min(n,t),Math.max(n,t)]},FX=(e,t)=>!!t&&(t.linked?t.linked===`active`:Number.isFinite(e.value)&&e.value>=t.value),IX=e=>(e.colorMode===`gradient`||e.colorMode===`zones`)&&!!e.stops?.length,LX=(e,t)=>FX(e,t)?t.color:wX(e.colorMode,e.stops,e.color,e.value);function RX(e,t,n){for(let r of TX(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 zX(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 BX=Math.SQRT1_2;function VX(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=MX(t.min,u),f=MX(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,BX*h+g/2),r=h+t/2+BX*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+BX*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=>OX+e*kX;e.lineCap=`round`,e.lineWidth=_,e.strokeStyle=c.grid,e.beginPath(),e.arc(b,x,h,OX,OX+kX),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(NX(t,s.value)),OX+kX),e.stroke(),e.globalAlpha=1,e.lineCap=`round`);let[C,w]=PX(t,Number.isFinite(t.value)?NX(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(IX(t)){let n=kX/(2*Math.PI),r=RX(e.createConicGradient(OX,b,x),t,e=>e*n);r.addColorStop(1,wX(t.colorMode,t.stops,t.color,t.min)),e.strokeStyle=r,e.globalAlpha=.24,e.beginPath(),e.arc(b,x,h,OX,OX+kX),e.stroke(),e.globalAlpha=1,Number.isFinite(t.value)&&!FX(t,s)&&T()}if(Number.isFinite(t.value)&&(!IX(t)||FX(t,s))&&(e.strokeStyle=FX(t,s)?s.color:o,T()),t.fromZero&&t.min<0&&t.max>0){let n=S(NX(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(NX(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&&VU(e,b+Math.cos(n)*r-10/2,x+Math.sin(n)*r-10/2,s.color)}let E=Number.isFinite(t.value)?MX(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=FX(t,s)||IX(t)?LX(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(zX(e,t.unit,D),b,x+O*.32+Math.max(11,h*.19)));let A=x+BX*h+_/2+6,j=BX*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(zX(e,t.name,M),b,A+(v-N)/2)}function HX(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+NX(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(zX(e,t.name,f),u,h-p/2-m-4),e.textAlign=`right`,e.fillStyle=FX(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=FX(t,s)||IX(t)?LX(t,s):c.ink,e.font=`650 ${m}px ${Q.sans}`,e.fillText(Number.isFinite(t.value)?MX(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)?NX(t,t.value):0,y=e=>u+e*f,[b,x]=PX(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`};IX(t)&&(e.strokeStyle=RX(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)&&!FX(t,s)&&S()),Number.isFinite(t.value)&&(!IX(t)||FX(t,s))&&(e.strokeStyle=FX(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&&VU(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(MX(t.min,t.max-t.min),u,h+p/2+4),e.textAlign=`right`,e.fillText(MX(t.max,t.max-t.min),d,h+p/2+4)}var UX=`Video limit reached this month`,WX=720;function GX(e,t){return t?e<WX:e<640}function KX(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 qX(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 JX={get:()=>null,subscribe:()=>()=>{}};function YX(e){let[t,n]=wt(null);return G(()=>{let t=e.current;if(!t)return;let r=e=>n(t=>GX(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 XX(e){let t=nr(e.settings),[n,r]=wt(null),[i,a]=wt(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=>$n(t,e.live)))].sort();return q(QX,{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(ZX,{...d,id:t[0],onMenu:u});let f=n&&t.includes(n)?n:null,p=f?[f]:t,{cols:m,rows:h}=KX(p.length),g=()=>{a(f),r(null)};return kt(`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(ZX,{...d,id:e,multi:!0,wall:!f,onPick:f?void 0:()=>{a(null),r(e)}},e)),f?kt(`button`,{type:`button`,className:`kymo-camera__all`,onClick:g,autoFocus:!0,children:[kt(`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 ZX({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($X,{...e,...l,source:u,name:i?$n(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(QX,{onContextMenu:s,title:d.limitNotice,detail:$n(d,e.live)});if(!d?.video||d.status===`error`)return q(QX,{onContextMenu:s,title:`Camera offline`,detail:d?$n(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?VE({...f,video:f.video}):void 0;return q($X,{...e,...l,source:VE({...d,video:d.video}),low:p,name:i?$n(d,e.live):d.name,conn:d},d.id)}function QX({title:e,detail:t,onContextMenu:n}){return q(`div`,{className:`kymo-camera`,onContextMenu:n,children:kt(`div`,{className:`kymo-camera__empty`,children:[kt(`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 $X(e){let{settings:t,source:n}=e,r=e.cursor??JX,i=Tt(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=YX(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]=wt(null),x=y??m??n,[S,C]=wt(!1),[w,T]=wt(!0);W(()=>{if(!m||_.current?.source===m)return;let e=!_.current,t=null,n=!1,r=()=>t?_.current===t:e,i=t=oZ(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=eZ(e.rec||c!==null?null:x),D=tZ(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 kt(`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?kt(`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?``:rZ(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]}):kt(`div`,{className:`kymo-camera__empty kymo-camera__empty--cover`,role:`status`,children:[q(`p`,{className:`kymo-camera__empty-title`,children:`No signal`}),kt(`p`,{className:`kymo-camera__empty-detail`,children:[e.name,` · no video for `,nZ(E)]})]})]})}function eZ(e){let[t]=wt(()=>Date.now()),[n,r]=wt(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>zE(i)?Math.floor(a/1e3):null)};n();let i=setInterval(n,500);return()=>clearInterval(i)},[e,t]),n}function tZ(e){let[t,n]=wt(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 nZ(e){return e<60?`${e} s`:e<3600?`${Math.floor(e/60)} min`:`${Math.floor(e/3600)} h`}function rZ(e){let t=Math.abs(e).toFixed(1);return t===`0.0`?`0.0 s`:`${e<0?`−`:`+`}${t} s`}var iZ=60,aZ=.05;function oZ(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=dU(),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?iZ: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(DU(x,t,n,e=>{let t=b.find(t=>t.timestamp/1e6>e);return t?t.timestamp/1e6:NaN}),t-aZ);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=dU(),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=zH(F),N()};return P=zH(F),{source:e,show(){a=!0},buffered:()=>c,setTarget(e){e!==f&&(f=e,u&&j())},dispose(){s=!0,BH(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 sZ(e,t){let n=e.filter(e=>e.x.length>=2&&cZ(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 cZ(e){for(let t=1;t<e.length;t++)if(!(e[t]>=e[t-1]))return!1;return!0}function lZ(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 uZ(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 dZ(e,t,n,r,i){if(e.length===1){let a=e[0];return fZ(a.conn,t,n,a.keySuffix,a.offset,r,i)}let a=e.map(e=>fZ(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 fZ(e,t,n,r,i,a,o){let s=null;return{pull:(o,c,l,u)=>{let f=e.source.version();if(!s||s.ver!==f||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:f,x0:o,x1:c,mp:l,pts:{...a,x:u,cols:new Map([...a.cols].map(([e,t])=>[e+r,t]))}}}let p=d(s.pts,u);if(t!==`ElapsedTime`)return[...a,p];let m=Math.min(e.source.latestTimeSync(),u===void 0?1/0:u-i),h=ut(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 pZ(e,t){return e.filter(e=>Le(t,e))}var mZ=`__ref`,hZ=8e3;function gZ(e,t){return e.map(e=>({...e,id:`${e.id}${mZ}`,column:`${e.column}${mZ}`,color:t}))}var _Z=new WeakMap;function vZ(e,t,n){let r=e.data.rows,i=`${t}\n${n.join(`
608
- `)}`,a=_Z.get(r);a||(a=new Map,_Z.set(r,a));let o=a.get(i);if(o)return o;let s=yZ(m(r,t,n,hZ,mZ)),c={points:s,span:s.length>1?[s.x[0],s.x[s.length-1]]:null};return a.set(i,c),c}function yZ(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 bZ(e,t){return e?t?[Math.min(e[0],t[0]),Math.max(e[1],t[1])]:e:t}function xZ(e,t,n,r,i){e.source.trackCycles(t);let a=r.reference===`dataset`&&i?vZ(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+mZ,t]))}}else a&&(l=E(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,d(o.live,l)]},id:e.id,latestT:()=>e.source.latestTimeSync(),timeAfter:t=>e.source.timeAfterSync(t),xAtTime:n=>e.source.xAtTimeSync(t,n),xBounds:()=>bZ(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 SZ(e,t){return e.reference===`previous`?e.previousColor:e.reference===`dataset`&&t?e.datasetColor:null}function CZ(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 wZ=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?H(new Float64Array,new Float64Array,e.viewport.x0,e.viewport.x1,e.maxPoints):H(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}:k(r,i.map(e=>this.#e.get(e)),i,t.x0,t.x1,n)}getColumnsSync(e,n,r){let i=this.#e.get(n.xKey),a=i?e.filter(e=>this.#e.has(e)):[];return!i||a.length===0?null:t(i,a.map(e=>this.#e.get(e)),a,n.x0,n.x1,r)}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 TZ(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 EZ(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)=>TZ(i+(t+.5)*(c/n))),m=Array.from({length:r},(e,t)=>TZ(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 DZ(e,t){return t.some(t=>t.name===e)}function OZ(e,t){return DZ(e,t)?`ƒ ${e}`:e}var kZ=8e3,AZ=3e3,jZ=[];function MZ(e){return`live`in e?e.live.source.columns():`source`in e&&e.source instanceof wZ?e.source.columnMap:void 0}var NZ=4e3,PZ=new WeakMap;function FZ(e,t,n){let r=PZ.get(e);r||PZ.set(e,r=new Map);let i=JSON.stringify([n,...t]),a=r.get(i);return a||r.set(i,a=new ZE({meta:``,columnNames:[n,...t],units:[],rows:e})),a}var IZ=new WeakMap;function LZ(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 RZ(e,t){let n=1/0,r=-1/0;for(let{rows:i,offset:a}of e){let e=IZ.get(i);e||(e=new Map,IZ.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 zZ(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 BZ(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 VZ=new Map;function HZ(e){let t=VZ.get(e);return t||(t=Float64Array.from({length:e},(e,t)=>t),VZ.clear(),VZ.set(e,t)),t}function UZ(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:Ct(()=>d===`ElapsedTime`?e.liveConnections:e.liveConnections.map(e=>{let t=BZ(e.dataset.rows,d);return t===e.dataset.rows?e:{...e,dataset:{...e.dataset,rows:t}}}),[e.liveConnections,d])},[p,h]=wt({}),g=Ct(()=>l.some(e=>e.kind!==`multiband`),[l]),_=Ct(()=>f.connections.some(e=>r.includes(e.id)),[f.connections,r]),v=Ct(()=>{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=Ct(()=>lZ(i.map(e=>{let t=p[e.id];return t?{...e.data,rows:t}:e.data})),[i,p]),b=Ct(()=>{let e=f.connections.filter(e=>r.includes(e.id)).map(e=>e.dataset);return e.length===0?y:lZ(y?[y,...e]:e)},[y,f.connections,r]),x=Ct(()=>PE(a,u,d).map(e=>e.id).join(`
607
+ }`,SJ=-3e38;function CJ(e){for(let t=0;t<e.length;t++)if(e[t]-e[t]===0)return e[t];return 0}function wJ(e){let t=e.getContext(`webgl2`,{antialias:!1,alpha:!0,premultipliedAlpha:!0});if(!t)return null;let n=(e,n,i,a)=>hU(t,`glPlot|${e}|${n}`,()=>r(e,n,i,a)),r=(e,n,r,i)=>{let a=rU(t,t.VERTEX_SHADER,e),o=rU(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(mJ,gJ,[`a_xa`,`a_xb`,`a_loa`,`a_lob`,`a_hia`,`a_hib`,`a_bstart`],[`u_color`]),a=n(hJ,_J,[`a_x0`,`a_x1`,`a_y0`,`a_y1`,`a_k`],[`u_palette`]),o=n(vJ,yJ,[`a_ax`,`a_ay`,`a_bx`,`a_by`,`a_bstart`],[`u_color`,`u_half`,`u_ext`]),s=n(bJ,xJ,[],[`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=CJ(t),o.oy=CJ(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=CJ(n),c.oy=CJ(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=CJ(t),o.oy=CJ(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:SJ}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 TJ(e){let t=K({plot:null,failed:!1,size:``});return W(()=>()=>{t.current.plot?.dispose(),t.current.plot=null},[]),bt((n,r)=>{let i=t.current,a=e.current;if(!i.plot&&!i.failed&&a&&(i.plot=gU(a,wJ),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 EJ(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 DJ=16;function OJ(e,t,n,r){let i=EJ(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(DJ),m=new Int32Array(DJ);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(DJ-1,Math.floor(a/(2*Math.PI)*DJ));p[o]+=t[e],m[o]++}return{n:a,rMin:c,rMax:l,x:d,y:f,means:Array.from({length:DJ},(e,t)=>m[t]>0?p[t]/m[t]:0)}}function kJ({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=Ct(()=>OJ(e,t,o,s),[e,t,o,s]),_=K(g);G(()=>{_.current=g},[g]);let v=K(null),y=TJ(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`,JH(r);return}let w=g-m||1,T=(Math.min(t-64,n-32-24)-4)/2,E=t/2,D=32+T,O=bV(w,4),k=CV(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(DV(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,Rq(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/DJ;r.fillStyle=l,r.globalAlpha=.75;for(let i=0;i<DJ;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<DJ;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??=ZU(()=>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 YU(()=>{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)},[]),kt(`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 AJ(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 jJ(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 MJ(e,t){let n=new Float64Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n}function NJ(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 PJ(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 FJ=new Float64Array,IJ=new Float64Array;function LJ(e,t,n){let r=t>>1;FJ.length<r&&(FJ=new Float64Array(r),IJ=new Float64Array(r));let i=FJ.subarray(0,r),a=IJ.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}PJ(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 RJ=new Float64Array,zJ=0;function BJ(e){if(zJ===e)return RJ.subarray(0,e);RJ.length<e&&(RJ=new Float64Array(Math.max(e,RJ.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++){RJ[t]=.5*(1-i);let e=i*n-a*r;a=a*n+i*r,i=e}return zJ=e,RJ.subarray(0,e)}var VJ={top:14,right:24,bottom:40,left:64},HJ=5;function UJ(e){let t=1;for(;t<e;)t<<=1;return t}function WJ(e,t,n,r){let i=e.length,a=Math.max(2,UJ(i)),o=LJ(e,a,n===`hann`?BJ(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 GJ({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=VW(),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 _=Ct(()=>e.length>=4?WJ(e,t,a,i):null,[e,t,a,i]),v=Ct(()=>_&&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}=VJ,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`,JH(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`,JH(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=bV(I-F,5),V=CV(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:bV(P-N,xV(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})():CV(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-HJ,z(e)),r.lineTo(s,z(e)),r.stroke(),r.fillText(DV(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+HJ),r.stroke(),r.fillText(DV(e,T?e:ee),R(e),i+l+HJ+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?AJ(k,O,Math.log10(N*M),Math.log10(P*M),re):AJ(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??=ZU(()=>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 YU(()=>{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 KJ(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 qJ(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,KJ(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 JJ={top:14,right:24,bottom:48,left:64},YJ=5;function XJ(e,t){let n=e.length;if(n===0)return null;let[r,i,a,o,s]=qJ(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 ZJ({groups:e,color:t=`#fb923c`,whiskers:n=`1.5iqr`,height:r=400,backgroundToken:i=``,onPlotContextMenu:a}){let o=VW(),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=Ct(()=>e.filter(e=>e.values.length>0).map(e=>({label:e.label,box:XJ(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}=JJ,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`,JH(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=bV(C-S,5),D=CV(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-YJ,T(e)),r.lineTo(l,T(e)),r.stroke(),r.fillText(DV(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+YJ+2,k-4,c-YJ-4),r.clip(),r.fillText(n,t,i+f+YJ+2),r.restore()}}let v=K(_);v.current=_;let y=K(null);y.current??=ZU(()=>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 YU(()=>{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 QJ(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 $J=e=>e.includes(`.`)&&!e.includes(`e`)?e.replace(/\.?0+$/,``):e;function eY(e){return e>=1e3?`${$J((e/1e3).toPrecision(3))}k`:$J(e.toPrecision(3))}function tY(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 nY={top:14,right:24,bottom:40,left:68},rY=[[8,0,16],[48,0,96],[104,0,144],[160,0,128],[200,32,64],[230,100,16],[250,200,32],[255,255,220]],iY=-80;function aY(e){let t=rY.length-1,n=Math.min(t-1,Math.floor(e*t)),r=e*t-n,[i,a,o]=rY[n],[s,c,l]=rY[n+1];return[i+(s-i)*r,a+(c-a)*r,o+(l-o)*r]}var oY=(()=>{let e=new Uint8Array(256*4);for(let t=0;t<256;t++){let[n,r,i]=aY(t/255);e.set([n,r,i,255],t*4)}return e})();function sY(e){let t=1;for(;t<e;)t<<=1;return t}var cY=(e,t)=>Math.log(1+e/t*9)/Math.log(10),lY=(e,t)=>t*(10**e-1)/9;function uY({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=VW(),d=K(null),f=K(null),p=K(null),m=K(null),h=K(null),g=K(l);G(()=>{g.current=l},[l]);let _=sY(Math.max(4,Math.min(n,4096))),v=Math.max(1,Math.round(_*(1-Math.max(0,Math.min(.95,r))))),y=Ct(()=>{if(!o)return null;let e=_>>1,n=t/2;return Int32Array.from({length:e},(t,r)=>Math.min(e-1,Math.floor(lY((r+.5)/e,n)/n*e)))},[o,_,t]),b=K(null),x=Ct(()=>b.current=tY(e,_,v,i===`hann`,a===`db`,y,b.current),[e,_,v,i,a,y]),S=Ct(()=>({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+iY,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=gU(f.current,wJ),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=LK(nY,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`,JH(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=QJ(y,N).grid;j&&j.setGrid(`cells`,e.values,e.w,Math.min(e.h,j.maxTextureSize),[0,e.w,0,e.h],oY,P,F),E.current.grid=y,E.current.shown=e,KU(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]=aY(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?cY(e,R):e/R));L.strokeStyle=v,L.lineWidth=.5,L.globalAlpha=.4;let B=CV(0,R,bV(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(eY(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=bV(V,6),te=CV(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(DV(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??=ZU(()=>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 YU(()=>{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)},[]),kt(`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 dY=300,fY=256,pY=-60,mY=[];function hY({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=Ct(()=>tY(e,c,l,i===`hann`,u,null),[e,c,l,i,u]);return q(iJ,{points:mY,surface:Ct(()=>gY(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 gY(e,t,n,r,i){let{frames:a,bins:o,values:s}=e;if(a<2||o<2)return;let c=Math.min(a,dY),l=Math.min(o,fY),u=i?20*Math.log10(Math.max(e.max,1e-12))+pY:-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 _Y(e,t,n){return Array.from({length:n},(r,i)=>e+(i+1)/(n+1)*(t-e))}function vY(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 yY(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 bY(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 xY={top:14,right:32,bottom:80,left:80};function SY(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 CY=[[33,102,172],[103,169,207],[209,229,240],[247,247,247],[253,219,199],[239,138,98],[178,24,43]],wY=[[13,8,135],[84,2,163],[139,10,165],[185,50,137],[219,92,104],[244,136,73],[254,188,43],[240,249,33]],TY=[[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 EY(e,t){let n=e.length-1,r=Math.min(n-1,Math.floor(t*n));return SY(e[r],e[r+1],t*n-r)}function DY(e,t){return EY(t===`plasma`?wY:t===`viridis`?TY:CY,e)}function OY(e){let t=new Uint8Array(256*4);for(let n=0;n<256;n++){let[r,i,a]=DY(n/255,e);t.set([r,i,a,255],n*4)}return t}function kY(e){return Math.abs(e)>=1e4||Math.abs(e)<.01&&e!==0?e.toExponential(1):String(parseFloat(e.toPrecision(3)))}function AY(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 jY(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=yY(a),i=n[e.w]-n[0];u=Float64Array.from(n,e=>t+(e-n[0])/i*r)}if(l){let t=yY(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 MY(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 NY(e,t,n,r,i,a){let o=Math.max(1,i),s=Math.max(1,a),c=Int32Array.from({length:o},(e,r)=>MY(t.xB,n+r+.5)),l=new Float32Array(o*s);for(let n=0;n<s;n++){let i=MY(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 PY({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=Ct(()=>r??AY(e??[],t??[],n??[]),[r,e,t,n]),C=Ct(()=>{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=gU(m.current,wJ),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=LK(xY,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`,JH(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}`},KU(_.current));let{xCentres:F,yCentres:I,contours:L}=w.current,R=x?x.maxTextureSize:Math.max(1,Math.round(S*N)),z=QJ(m,R).grid,B=jY(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?NY(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],OY(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]=DY(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]=DY(Math.max(0,Math.min(1,(n-g)/(v-g))),b);U.fillStyle=.299*r+.587*i+.114*a>128?`#000`:`#fff`,U.fillText(kY(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?_Y(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=>vY(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]=DY(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(kY(v),ce+12+2,le),r.fillText(kY(g),ce+12+2,le+ue),r.fillText(kY((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}=LK(xY,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]}: ${kY(_)}`;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??=ZU(()=>F.current(),()=>_.current);let L=()=>{b.current||=UU(()=>{b.current=0,P()})};return W(()=>{I.current.now()},[S,C,i,a,c,l,u]),W(()=>()=>{I.current?.cancel(),WU(b.current)},[]),W(()=>{v.current=null,I.current.schedule()},[d]),G(()=>{let e=_.current;if(!e)return;let t=new YU(()=>{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=MY(i.xB,t.clientX-n.left),o=MY(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)}},[]),kt(`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 FY=2e3,IY=1024;function LY(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<=FY){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(IY),l=(i-r)/IY||1;for(let t=0;t<a;t++)c[Math.max(0,Math.min(IY-1,Math.floor((e[t]-r)/l)))]++;for(let e=0;e<n.length;e++){let i=0;for(let a=0;a<IY;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 RY={top:14,right:24,bottom:48,left:64},zY=120;function BY(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 VY(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]=qJ(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:zY},(e,t)=>r+t/(zY-1)*(i-r));return{shapes:n.map((e,n)=>{let{q1:o,median:c,q3:l}=a[n],u=LY(e.values,t>0?t:BY(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 HY({groups:e,color:t=`#818cf8`,showBox:n=!0,bandwidth:r=0,orientation:i=`vertical`,backgroundToken:a=``,onPlotContextMenu:o}){let s=VW(),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=Ct(()=>VY(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}=RY,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`,JH(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=bV(E-T,5),A=CV(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(DV(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(DV(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<zY;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=zY-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??=ZU(()=>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 YU(()=>{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 UY={top:48,right:16,bottom:72,left:80},WY=[8,24,64],GY=[56,189,248];function KY(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 qY(e){return`${(e*100).toFixed(1)}%`}function JY(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 YY({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=Ct(()=>JY(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}=UY,{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`,JH(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]=KY(WY,GY,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?qY(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: ${qY(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}=UY,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?qY(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??=ZU(()=>x.current(),()=>s.current);let C=()=>S.current.schedule(),w=()=>{WU(u.current),u.current=UU(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 YU(()=>{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}=UY,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)}},[]),kt(`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 XY={top:24,right:24,bottom:48,left:64};function ZY(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 QY(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 $Y(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 eX(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 tX({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=Ct(()=>ZY(e,t),[e,t]),f=Ct(()=>n===`pr`?{roc:null,pr:$Y(d)}:{roc:QY(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}=XY,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`,JH(r);return}let S=e=>c+e*l,C=e=>i+(1-e)*d,w=CV(0,1,bV(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(),eX(r,t,n,a),r.strokeStyle=x,r.lineWidth=1,r.stroke(),r.beginPath(),eX(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=AJ(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??=ZU(()=>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 YU(()=>{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 nX={top:20,right:64,bottom:48,left:64};function rX({xValues:e,series:t,xLabel:n=`Epoch`,backgroundToken:r=``,onPlotContextMenu:i}){let a=VW(),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 _=Ct(()=>{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:NJ(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}=nX,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`,JH(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=bV(C.hi-C.lo,5),N=CV(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=bV(D-E,6),F=CV(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?AJ(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(DV(e,M),l-6,A(e));if(T){let e=bV(w.hi-w.lo,5),t=CV(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(DV(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(DV(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}=nX,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}: ${OV(e.values[D])}`,T+6,O),O+=14);w(0)}let x=K(y);x.current=y;let S=K(null);S.current??=ZU(()=>x.current(),()=>c.current);let C=()=>S.current.schedule(),w=()=>{WU(d.current),d.current=UU(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 YU(()=>{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)}},[]),kt(`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 iX={top:40,right:24,bottom:40,left:72},aX=`#ef4444`,oX=`#f97316`,sX=`#22d3ee`;function cX(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 lX({points:e,sigmaLevel:t=3,color:n=`#22d3ee`,backgroundToken:r=``,onPlotContextMenu:i}){let a=VW(),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 _=Ct(()=>cX(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}=iX,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`,JH(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=bV(D-E,5),j=CV(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} ${OV(e)}`,l+u-2,o-5))};M(w,oX,`UCL`,[5,3]),M(C,sX,`CL`,[]),M(T,oX,`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=jJ(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?aX: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(DV(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}=iX,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}: `}${OV(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?aX:_,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??=ZU(()=>S.current(),()=>c.current);let w=()=>C.current.schedule(),T=()=>{WU(d.current),d.current=UU(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 YU(()=>{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)}},[]),kt(`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 uX={top:32,right:24,bottom:24,left:24},dX=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`],fX=16;function pX(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 mX(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:fX},(e,t)=>pX((t+.5)/fX));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(fX-1,Math.floor(e*fX))):-1}for(let t=0;t<e.length;t++)s[t]<0&&(s[t]=0)}else if(!n&&e.colorIndex){c=dX;for(let t=0;t<e.length;t++)s[t]=Math.max(0,e.colorIndex[t])%dX.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 hX({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=Ct(()=>mX(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 _=TJ(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}=uX,{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,Rq(e.color,j),1,e.starts)),v.current=w,KU(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(DV(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=dX[r%dX.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}=uX,{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??=ZU(()=>w.current(),()=>u.current);let E=()=>T.current.schedule(),D=()=>{WU(p.current),p.current=UU(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 YU(()=>{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-uX.left-uX.right,a=r.length,o=t.clientX-n.left-uX.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)}},[]),kt(`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 gX(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 _X(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 vX={top:16,right:16,bottom:16,left:16},yX=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function bX(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 xX(e){let[t,n,r]=bX(e);return`rgb(${t},${n},${r})`}var SX=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++)e.set([...bX(t/255),255],t*4);return e})(),CX=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++){let[n,r,i]=Rq(yX[t%yX.length],1);e.set([n*255,r*255,i*255,255],t*4)}return e});function wX(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 TX({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=Ct(()=>wX(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}=vX,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=gU(s.current,FK),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,KU(l.current));let f=`${c.mode}|${u}|${d}`;return n.style!==f&&(r.setStyle(c.mode===`single`?{kind:`single`,rgba:Rq(u,1)}:{kind:c.mode,palette:c.mode===`colormap`?SX:CX()},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`,JH(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:vX.left,top:vX.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`?xX(i):d.mode===`dataset`?yX[i%yX.length]:c,r.globalAlpha=.8,r.fill()}r.globalAlpha=1}if(l){let e=Math.min(120,Math.floor((n-vX.top-vX.bottom)*.4)),i=t-vX.right-12,o=vX.top+8;for(let t=0;t<e;t++)r.fillStyle=xX(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=vX.left,i=n-vX.bottom-10;r.font=`9px ${Q.mono}`,r.textBaseline=`top`,E.forEach((n,o)=>{e>t-vX.right-60&&(e=vX.left,i-=14),r.fillStyle=yX[o%yX.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<vX.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??=ZU(()=>w.current(),()=>l.current);let E=()=>T.current.schedule(),D=()=>{WU(f.current),f.current=UU(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 YU(()=>{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])-vX.left,g=e=>u(i.y[e])-vX.top,_=a+8,y=`${s}|${c}|${_}`;(!t||t.model!==o||t.key!==y)&&(t={model:o,key:y,g:gX(i.length,f,p,_,m,g)}),d.current=_X(t.g,n.clientX-r.left-vX.left,n.clientY-r.top-vX.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)}},[]),kt(`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 EX={top:8,right:8,bottom:8,left:8},DX=20,OX=[`#f97316`,`#fb923c`,`#fdba74`,`#fbbf24`,`#fcd34d`,`#4ade80`,`#34d399`,`#38bdf8`,`#818cf8`,`#a78bfa`];function kX(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 AX(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 jX(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 MX(e){return OX[e%OX.length]}function NX({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=Ct(()=>{let t=kX(e);return{roots:t,flat:AX(t),numRows:jX(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=EX.left+e.x0*t,o=(e.x1-e.x0)*t;return{x:a,y:i===`topdown`?EX.top+e.depth*DX:EX.top+n-(e.depth+1)*DX,w:o,h:DX-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`,JH(r);return}let{flat:l,numRows:u}=p.current,f=t-EX.left-EX.right,v=u*DX;for(let e of l){let t=_(e,f,v,u,c);if(!(t.w<1)&&(r.fillStyle=MX(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,DX-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+DX/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-EX.left-EX.right,l*DX,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+DX+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??=ZU(()=>b.current(),()=>o.current);let S=()=>x.current.schedule(),C=()=>{WU(l.current),l.current=UU(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 YU(()=>{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-EX.left-EX.right,f=o*DX,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)}},[]),kt(`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 PX={top:24,right:24,bottom:52,left:56},FX=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`],IX=.8;function LX(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 RX(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 zX({groups:e,columns:t,seriesNames:n,colors:r,mode:i=`grouped`,horizontal:a=!1,valueRange:o,backgroundToken:s=``,onPlotContextMenu:c}){let l=VW(),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=Ct(()=>{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=LX(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]??FX[n%FX.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=LK(PX,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=gU(d.current,wJ),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`,JH(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(DV(t,(g-h)/5),n,_+k+4)):(r.textAlign=`right`,r.textBaseline=`middle`,r.fillText(DV(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},KU(p.current));let I=Math.min(2,window.devicePixelRatio||1),L=Math.max(1,Math.round(M*I)),R=j.map(e=>{let t=QH(e);return[t[0],t[1],t[2],IX]}),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=RX(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=RX(s,d,L);r.globalAlpha=IX;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]+` `:``}${OV(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??=ZU(()=>j.current(),()=>p.current);let N=()=>{g.current||=UU(()=>{g.current=0,A()})};return W(()=>{M.current.now()},[y,n,r,i,a,o]),W(()=>()=>{M.current?.cancel(),WU(g.current)},[]),W(()=>{m.current=null,M.current.schedule()},[s]),G(()=>{let e=p.current;if(!e)return;let t=new YU(()=>{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)}},[]),kt(`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 BX=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function VX(e,t){if(!t)return BX[e%BX.length];if(e===0)return t;let n=BX.filter(e=>e.toLowerCase()!==t.toLowerCase());return n[(e-1)%n.length]}var HX={top:36,right:36,bottom:36,left:36};function UX({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`,HX.left+8,HX.top+8);return}let h=c.length,g=t/2,_=n/2,v=Math.min(t-HX.left-HX.right,n-HX.top-HX.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=VX(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=HX.left,i=n-HX.bottom-10;r.font=`9px ${Q.mono}`,r.textBaseline=`top`;for(let n=0;n<l.length&&(r.fillStyle=VX(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-HX.right-30));n++);}}let g=K(h);g.current=h;let _=K(null);_.current??=ZU(()=>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 YU(()=>{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)}},[]),kt(`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 WX={top:16,right:16,bottom:40,left:52},GX=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function KX(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=>NJ(e)),xLo:c,xHi:l,yLo:u,yHi:d}}function qX({series:e,stacked:t=!1,yRange:n,backgroundToken:r=``,onPlotContextMenu:i}){let a=VW(),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=Ct(()=>{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=KX(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=AJ(a,o,n,r,i);return{x:MJ(a,c),hi:MJ(o,c),lo:s?MJ(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`,JH(i);return}let h=LK(WX,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(DV(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(DV(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},KU(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)=>QH(GX[t%GX.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=GX[e%GX.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=GX[n%GX.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=gU(s.current,wJ),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}=LK(WX,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=${OV(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??=ZU(()=>O.current(),()=>l.current);let A=()=>{f.current||=UU(()=>{f.current=0,D()})};return W(()=>{k.current.now()},[e,h,n]),W(()=>()=>{k.current?.cancel(),WU(f.current)},[]),W(()=>{u.current=null,k.current.schedule()},[r]),G(()=>{let e=l.current;if(!e)return;let t=new YU(()=>{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)}},[]),kt(`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 JX={top:16,right:16,bottom:40,left:52},YX=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`];function XX({series:e,complement:t=!1,logX:n=!1,backgroundToken:r=``,onPlotContextMenu:i}){let a=VW(),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=Ct(()=>{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`,JH(r);return}let{top:f,right:m,bottom:y,left:b}=JX,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(DV(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=YX[e%YX.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=YX[n%YX.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}=JX,l=n-a-JX.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=OV(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??=ZU(()=>x.current(),()=>c.current);let C=()=>S.current.schedule(),w=()=>{WU(d.current),d.current=UU(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 YU(()=>{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)}},[]),kt(`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 ZX={top:16,right:40,bottom:40,left:52},QX=[`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function $X(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 eZ(e){let[t,n,r]=$X(e);return`rgb(${t},${n},${r})`}var tZ=(()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++)e.set([...$X(t/255),255],t*4);return e})(),nZ=()=>{let e=new Uint8Array(1024);for(let t=0;t<256;t++){let[n,r,i]=Rq(QX[t%QX.length],1);e.set([n*255,r*255,i*255,255],t*4)}return e};function rZ(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 iZ({points:e,color:t=`#64748b`,colorByNumeric:n=!1,maxRadius:r=24,backgroundToken:i=``,onPlotContextMenu:a}){let o=VW(),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=Ct(()=>rZ(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}=ZX,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=gU(c.current,FK),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,KU(u.current));let l=`${o.mode}|${s}`;return n.style!==l&&(r.setStyle(o.mode===`single`?{kind:`single`,rgba:Rq(s,1)}:{kind:o.mode,palette:o.mode===`colormap`?tZ:nZ()},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`,JH(r);return}let{xLo:p,xHi:m,yLo:h,yHi:C}=d.ext,{top:w,left:T}=ZX,{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(DV(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(DV(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`?eZ(n):d.mode===`dataset`?QX[n%QX.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-ZX.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=QX[n%QX.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(`(${OV(a.x[i])}, ${OV(a.y[i])})`),m.push(`size=${OV(a.size[i])}`);let _=a.colorIndex?.[i];_!==void 0&&_>=0&&a.colorLabels?m.push(a.colorLabels[_]):a.colorValue&&m.push(OV(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<ZX.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??=ZU(()=>T.current(),()=>u.current);let D=()=>E.current.schedule(),O=()=>{WU(p.current),p.current=UU(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 YU(()=>{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])-ZX.left,h=e=>p(i.y[e])-ZX.top,_=a+6,v=`${s}|${c}|${_}`;(!t||t.model!==o||t.key!==v)&&(t={model:o,key:v,g:gX(i.length,l,u,_,m,h)}),f.current=_X(t.g,n.clientX-r.left-ZX.left,n.clientY-r.top-ZX.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)}},[]),kt(`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 aZ={top:8,right:8,bottom:8,left:8},oZ=[`#f97316`,`#38bdf8`,`#4ade80`,`#a78bfa`,`#fbbf24`,`#fb7185`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function sZ(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 cZ(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=cZ(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 lZ({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=Ct(()=>sZ(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`,JH(i);return}let u=p.current,f=t-aZ.left-aZ.right,_=n-aZ.top-aZ.bottom,v=cZ(u,aZ.left,aZ.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=oZ[l%oZ.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??=ZU(()=>y.current(),()=>a.current);let x=()=>b.current.schedule(),S=()=>{WU(l.current),l.current=UU(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 YU(()=>{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)}},[]),kt(`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 uZ={top:8,right:8,bottom:8,left:8},dZ=14,fZ=8,pZ=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function mZ(e,t,n,r){if(e.length===0||t.length===0)return{nodes:[],links:[]};let i=n-uZ.left-uZ.right,a=r-uZ.top-uZ.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=>uZ.left+e/Math.max(1,c)*(i-dZ),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)*fZ,i=0;for(let e of n)i+=Math.max(8,(d.get(e)??0)/f*r*.8);let o=uZ.top+(a-i-(n.length-1)*fZ)/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:pZ[e.indexOf(a)%pZ.length]}),o+=s+fZ}}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+dZ,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 hZ({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`,JH(r);return}let d=mZ(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,dZ,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+dZ+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??=ZU(()=>v.current(),()=>o.current);let b=()=>y.current.schedule(),x=()=>{WU(u.current),u.current=UU(_)};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 YU(()=>{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)}},[]),kt(`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 gZ={top:24,right:24,bottom:52,left:52};function _Z({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`,JH(r);return}let{top:h,right:g,bottom:_,left:v}=gZ,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}=gZ,f=t-u-gZ.right,h=n-l-gZ.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??=ZU(()=>_.current(),()=>o.current);let y=()=>v.current.schedule(),b=()=>{WU(l.current),l.current=UU(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 YU(()=>{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-gZ.left-gZ.right,s=-1,l=20;for(let e=0;e<r.length;e++){let t=gZ.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)}},[]),kt(`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 vZ={top:24,right:24,bottom:48,left:52};function yZ({points:e,color:t=`#a78bfa`,backgroundToken:n=``,onPlotContextMenu:r}){let i=VW(),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`,JH(r);return}let{xLo:_,xHi:v,yLo:y,yHi:b}=g(),{top:x,right:S,bottom:C,left:w}=vZ,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(DV(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(DV(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}=vZ,y=t-v-vZ.right,b=n-_-vZ.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=`(${OV(s.theoretical)}, ${OV(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??=ZU(()=>y.current(),()=>s.current);let x=()=>b.current.schedule(),S=()=>{WU(u.current),u.current=UU(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 YU(()=>{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}=vZ,p=i-d-vZ.right,h=n.height-u-vZ.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)}},[]),kt(`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 bZ={top:8,right:16,bottom:40,left:120},xZ=22,SZ=3,CZ=[`#38bdf8`,`#4ade80`,`#fb7185`,`#fbbf24`,`#a78bfa`,`#f97316`,`#34d399`,`#e879f9`,`#facc15`,`#60a5fa`];function wZ({tasks:e,backgroundToken:t=``,onPlotContextMenu:n}){let r=VW(),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`,JH(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}=bZ,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*(xZ+SZ)+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(DV(t,(g-h)/T),n,r+4)}for(let e=0;e<u.length;e++){let t=u[e],n=v+e*(xZ+SZ),r=CZ[(w.get(t.group??t.label)??0)%CZ.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,xZ-SZ),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+(xZ-SZ)/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}: ${OV(s.start)} → ${OV(s.end)} (${OV(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-bZ.left-bZ.right,y=e=>bZ.left+(e-h)/(g-h)*v,b=bZ.top+i*(xZ+SZ),x=(y(s.start)+y(s.end))/2,S=Math.max(4,Math.min(t-f-8,x-f/2)),C=b-22<bZ.top?b+xZ+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??=ZU(()=>_.current(),()=>o.current);let y=()=>v.current.schedule(),b=()=>{WU(l.current),l.current=UU(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 YU(()=>{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-bZ.top)/(xZ+SZ));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)}},[]),kt(`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 TZ=e=>[...e].filter(e=>Number.isFinite(e.at)).sort((e,t)=>e.at-t.at),EZ=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]},DZ=e=>`#${e.map(e=>Math.round(e).toString(16).padStart(2,`0`)).join(``)}`;function OZ(e,t,n,r){let i=t?TZ(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=EZ(o.color),u=EZ(s.color);return DZ([l[0]+(u[0]-l[0])*c,l[1]+(u[1]-l[1])*c,l[2]+(u[2]-l[2])*c])}function kZ(e,t,n,r,i,a=96){let o=i-r||1,s=t?TZ(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:OZ(`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:OZ(`gradient`,s,n,r+(t+.5)/a*o)}))}function AZ(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 jZ(e,t,n){let r=t?TZ(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 MZ=.75*Math.PI,NZ=1.5*Math.PI;function PZ({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(hW()),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=jW(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`,JH(p);return}let{cols:y,rows:b}=FZ(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`?GZ(p,e,n,r,x,S,e.color,e.alarm??null,h):KZ(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??=ZU(()=>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 YU(()=>{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)?IZ(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 FZ(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 IZ=(e,t)=>DV(e,bV(Math.abs(t),100)),LZ=(e,t)=>Math.max(0,Math.min(1,(t-e.min)/(e.max-e.min||1))),RZ=(e,t)=>{let n=e.fromZero?LZ(e,0):0;return[Math.min(n,t),Math.max(n,t)]},zZ=(e,t)=>!!t&&(t.linked?t.linked===`active`:Number.isFinite(e.value)&&e.value>=t.value),BZ=e=>(e.colorMode===`gradient`||e.colorMode===`zones`)&&!!e.stops?.length,VZ=(e,t)=>zZ(e,t)?t.color:OZ(e.colorMode,e.stops,e.color,e.value);function HZ(e,t,n){for(let r of kZ(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 UZ(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 WZ=Math.SQRT1_2;function GZ(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=IZ(t.min,u),f=IZ(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,WZ*h+g/2),r=h+t/2+WZ*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+WZ*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=>MZ+e*NZ;e.lineCap=`round`,e.lineWidth=_,e.strokeStyle=c.grid,e.beginPath(),e.arc(b,x,h,MZ,MZ+NZ),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(LZ(t,s.value)),MZ+NZ),e.stroke(),e.globalAlpha=1,e.lineCap=`round`);let[C,w]=RZ(t,Number.isFinite(t.value)?LZ(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(BZ(t)){let n=NZ/(2*Math.PI),r=HZ(e.createConicGradient(MZ,b,x),t,e=>e*n);r.addColorStop(1,OZ(t.colorMode,t.stops,t.color,t.min)),e.strokeStyle=r,e.globalAlpha=.24,e.beginPath(),e.arc(b,x,h,MZ,MZ+NZ),e.stroke(),e.globalAlpha=1,Number.isFinite(t.value)&&!zZ(t,s)&&T()}if(Number.isFinite(t.value)&&(!BZ(t)||zZ(t,s))&&(e.strokeStyle=zZ(t,s)?s.color:o,T()),t.fromZero&&t.min<0&&t.max>0){let n=S(LZ(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(LZ(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&&GW(e,b+Math.cos(n)*r-10/2,x+Math.sin(n)*r-10/2,s.color)}let E=Number.isFinite(t.value)?IZ(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=zZ(t,s)||BZ(t)?VZ(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(UZ(e,t.unit,D),b,x+O*.32+Math.max(11,h*.19)));let A=x+WZ*h+_/2+6,j=WZ*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(UZ(e,t.name,M),b,A+(v-N)/2)}function KZ(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+LZ(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(UZ(e,t.name,f),u,h-p/2-m-4),e.textAlign=`right`,e.fillStyle=zZ(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=zZ(t,s)||BZ(t)?VZ(t,s):c.ink,e.font=`650 ${m}px ${Q.sans}`,e.fillText(Number.isFinite(t.value)?IZ(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)?LZ(t,t.value):0,y=e=>u+e*f,[b,x]=RZ(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`};BZ(t)&&(e.strokeStyle=HZ(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)&&!zZ(t,s)&&S()),Number.isFinite(t.value)&&(!BZ(t)||zZ(t,s))&&(e.strokeStyle=zZ(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&&GW(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(IZ(t.min,t.max-t.min),u,h+p/2+4),e.textAlign=`right`,e.fillText(IZ(t.max,t.max-t.min),d,h+p/2+4)}var qZ=`Video limit reached this month`,JZ=720;function YZ(e,t){return t?e<JZ:e<640}function XZ(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 ZZ(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 QZ={get:()=>null,subscribe:()=>()=>{}};function $Z(e){let[t,n]=wt(null);return G(()=>{let t=e.current;if(!t)return;let r=e=>n(t=>YZ(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 eQ(e){let t=nr(e.settings),[n,r]=wt(null),[i,a]=wt(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=>$n(t,e.live)))].sort();return q(nQ,{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(tQ,{...d,id:t[0],onMenu:u});let f=n&&t.includes(n)?n:null,p=f?[f]:t,{cols:m,rows:h}=XZ(p.length),g=()=>{a(f),r(null)};return kt(`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(tQ,{...d,id:e,multi:!0,wall:!f,onPick:f?void 0:()=>{a(null),r(e)}},e)),f?kt(`button`,{type:`button`,className:`kymo-camera__all`,onClick:g,autoFocus:!0,children:[kt(`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 tQ({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(rQ,{...e,...l,source:u,name:i?$n(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(nQ,{onContextMenu:s,title:d.limitNotice,detail:$n(d,e.live)});if(!d?.video||d.status===`error`)return q(nQ,{onContextMenu:s,title:`Camera offline`,detail:d?$n(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?WE({...f,video:f.video}):void 0;return q(rQ,{...e,...l,source:WE({...d,video:d.video}),low:p,name:i?$n(d,e.live):d.name,conn:d},d.id)}function nQ({title:e,detail:t,onContextMenu:n}){return q(`div`,{className:`kymo-camera`,onContextMenu:n,children:kt(`div`,{className:`kymo-camera__empty`,children:[kt(`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 rQ(e){let{settings:t,source:n}=e,r=e.cursor??QZ,i=Tt(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`,d=null;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`?d=r+s-a+t.offsetMs/1e3:e.xKey===`ElapsedTime`&&i===`exact`?d=s-a+t.offsetMs/1e3:(c=o,l=`Sync needs a time X axis`)}else s!==null&&(e.xIsTime?(d=o?.clock?.toWall(s,t.offsetMs)??null,d===null&&(l=`No data stream to sync with`)):l=`Sync needs a time X axis`);let f=e.rec?n.dataClockOffsetMs:o?.clockOffsetMs;d!==null&&(c=d+BE(n.sync,d)+VE(n.clockOffsetMs,f));let p=K(null),m=K(null),h=$Z(p),g=h===null?null:e.low&&(h||e.wall)?e.low:n,_=K(t.fit),v=K(c);G(()=>{_.current=t.fit,v.current=c});let y=K(null),b=K(null),[x,S]=wt(null),C=x??g??n,[w,T]=wt(!1),[E,D]=wt(!0);W(()=>{if(!g||y.current?.source===g)return;let e=!y.current,t=null,n=!1,r=()=>t?y.current===t:e,i=t=uQ(g,m.current,()=>_.current,v.current,{unsupported:()=>{r()&&T(!0)},buffered:e=>{r()&&D(e)},frame:()=>{if(y.current===t){n||(n=!0,S(g));return}y.current?.dispose(),y.current=i,b.current=null,i.show(),n=!0,S(g),D(i.buffered())}},e);if(e){y.current=i;return}return b.current=i,()=>{y.current!==i&&(i.dispose(),b.current===i&&(b.current=null))}},[g]),W(()=>()=>{y.current?.dispose(),y.current=null},[]),W(()=>{y.current?.setTarget(c),b.current?.setTarget(c)},[c]);let O=iQ(e.rec||c!==null?null:C),k=aQ(e.rec?n:null),A=!!C.lowOf,j=C.info().latestT,M=!e.rec&&c!==null&&j!==null?c-j:null,N=e.rec?`No video at this time`:`Not buffered`;return kt(`div`,{ref:p,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:m,className:`kymo-camera__video`,role:`img`,"aria-label":`Video from ${e.name}`}),w?q(`div`,{className:`kymo-camera__empty`,children:q(`p`,{className:`kymo-camera__empty-title`,children:`This browser can't decode this camera`})}):O===null?kt(`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:M===null?``:sQ(M)}),A?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&&!E?N:null)?q(`span`,{className:`kymo-camera__note`,children:l??N}):null,e.conn?.limitNotice?q(`span`,{className:`kymo-camera__note`,role:`status`,children:e.conn.limitNotice}):null,k?.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 (${k.broken} of ${k.broken+k.verified} checked ${k.broken+k.verified===1?`chunk`:`chunks`}). The video may have gaps there.`,children:`Some messages were missing or out of order`}):null]}):kt(`div`,{className:`kymo-camera__empty kymo-camera__empty--cover`,role:`status`,children:[q(`p`,{className:`kymo-camera__empty-title`,children:`No signal`}),kt(`p`,{className:`kymo-camera__empty-detail`,children:[e.name,` · no video for `,oQ(O)]})]})]})}function iQ(e){let[t]=wt(()=>Date.now()),[n,r]=wt(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>zE(i)?Math.floor(a/1e3):null)};n();let i=setInterval(n,500);return()=>clearInterval(i)},[e,t]),n}function aQ(e){let[t,n]=wt(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 oQ(e){return e<60?`${e} s`:e<3600?`${Math.floor(e/60)} min`:`${Math.floor(e/3600)} h`}function sQ(e){let t=Math.abs(e).toFixed(1);return t===`0.0`?`0.0 s`:`${e<0?`−`:`+`}${t} s`}var cQ=60,lQ=.05;function uQ(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=hW(),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?cQ: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(jW(x,t,n,e=>{let t=b.find(t=>t.timestamp/1e6>e);return t?t.timestamp/1e6:NaN}),t-lQ);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=hW(),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=UU(F),N()};return P=UU(F),{source:e,show(){a=!0},buffered:()=>c,setTarget(e){e!==f&&(f=e,u&&j())},dispose(){s=!0,WU(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 dQ(e,t){let n=e.filter(e=>e.x.length>=2&&fQ(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 fQ(e){for(let t=1;t<e.length;t++)if(!(e[t]>=e[t-1]))return!1;return!0}function pQ(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 mQ(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 hQ(e,t,n,r,i){if(e.length===1){let a=e[0];return gQ(a.conn,t,n,a.keySuffix,a.offset,r,i)}let a=e.map(e=>gQ(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 gQ(e,t,n,r,i,a,o){let s=null;return{pull:(o,c,l,u)=>{let f=e.source.version();if(!s||s.ver!==f||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:f,x0:o,x1:c,mp:l,pts:{...a,x:u,cols:new Map([...a.cols].map(([e,t])=>[e+r,t]))}}}let p=d(s.pts,u);if(t!==`ElapsedTime`)return[...a,p];let m=Math.min(e.source.latestTimeSync(),u===void 0?1/0:u-i),h=ut(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 _Q(e,t){return e.filter(e=>Le(t,e))}var vQ=`__ref`,yQ=8e3;function bQ(e,t){return e.map(e=>({...e,id:`${e.id}${vQ}`,column:`${e.column}${vQ}`,color:t}))}var xQ=new WeakMap;function SQ(e,t,n){let r=e.data.rows,i=`${t}\n${n.join(`
608
+ `)}`,a=xQ.get(r);a||(a=new Map,xQ.set(r,a));let o=a.get(i);if(o)return o;let s=CQ(m(r,t,n,yQ,vQ)),c={points:s,span:s.length>1?[s.x[0],s.x[s.length-1]]:null};return a.set(i,c),c}function CQ(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 wQ(e,t){return e?t?[Math.min(e[0],t[0]),Math.max(e[1],t[1])]:e:t}function TQ(e,t,n,r,i){e.source.trackCycles(t);let a=r.reference===`dataset`&&i?SQ(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+vQ,t]))}}else a&&(l=E(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,d(o.live,l)]},id:e.id,latestT:()=>e.source.latestTimeSync(),timeAfter:t=>e.source.timeAfterSync(t),xAtTime:n=>e.source.xAtTimeSync(t,n),xBounds:()=>wQ(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 EQ(e,t){return e.reference===`previous`?e.previousColor:e.reference===`dataset`&&t?e.datasetColor:null}function DQ(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 OQ=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?H(new Float64Array,new Float64Array,e.viewport.x0,e.viewport.x1,e.maxPoints):H(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}:k(r,i.map(e=>this.#e.get(e)),i,t.x0,t.x1,n)}getColumnsSync(e,n,r){let i=this.#e.get(n.xKey),a=i?e.filter(e=>this.#e.has(e)):[];return!i||a.length===0?null:t(i,a.map(e=>this.#e.get(e)),a,n.x0,n.x1,r)}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 kQ(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 AQ(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)=>kQ(i+(t+.5)*(c/n))),m=Array.from({length:r},(e,t)=>kQ(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 jQ(e,t){return t.some(t=>t.name===e)}function MQ(e,t){return jQ(e,t)?`ƒ ${e}`:e}var NQ=8e3,PQ=3e3,FQ=[];function IQ(e){return`live`in e?e.live.source.columns():`source`in e&&e.source instanceof OQ?e.source.columnMap:void 0}var LQ=4e3,RQ=new WeakMap;function zQ(e,t,n){let r=RQ.get(e);r||RQ.set(e,r=new Map);let i=JSON.stringify([n,...t]),a=r.get(i);return a||r.set(i,a=new IO({meta:``,columnNames:[n,...t],units:[],rows:e})),a}var BQ=new WeakMap;function VQ(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 HQ(e,t){let n=1/0,r=-1/0;for(let{rows:i,offset:a}of e){let e=BQ.get(i);e||(e=new Map,BQ.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 UQ(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 WQ(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 GQ=new Map;function KQ(e){let t=GQ.get(e);return t||(t=Float64Array.from({length:e},(e,t)=>t),GQ.clear(),GQ.set(e,t)),t}function qQ(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:Ct(()=>d===`ElapsedTime`?e.liveConnections:e.liveConnections.map(e=>{let t=WQ(e.dataset.rows,d);return t===e.dataset.rows?e:{...e,dataset:{...e.dataset,rows:t}}}),[e.liveConnections,d])},[p,h]=wt({}),g=Ct(()=>l.some(e=>e.kind!==`multiband`),[l]),_=Ct(()=>f.connections.some(e=>r.includes(e.id)),[f.connections,r]),v=Ct(()=>{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=Ct(()=>pQ(i.map(e=>{let t=p[e.id];return t?{...e.data,rows:t}:e.data})),[i,p]),b=Ct(()=>{let e=f.connections.filter(e=>r.includes(e.id)).map(e=>e.dataset);return e.length===0?y:pQ(y?[y,...e]:e)},[y,f.connections,r]),x=Ct(()=>PE(a,u,d).map(e=>e.id).join(`
609
609
  `),[a,u,d]),S=Ct(()=>{let e=new Set(x.split(`
610
- `));return a.filter(t=>e.has(t.id))},[a,x]),C=Ct(()=>{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=>NE(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=Ct(()=>{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=Ct(()=>T.length===1?MZ(T[0]):void 0,[T]),O=C?.partRows??jZ;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 FW(`sampleRows`,()=>n.sampleRows(AZ,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=Ct(()=>w?.columnNames.join(`
610
+ `));return a.filter(t=>e.has(t.id))},[a,x]),C=Ct(()=>{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=>NE(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=Ct(()=>{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=Ct(()=>T.length===1?IQ(T[0]):void 0,[T]),O=C?.partRows??FQ;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 zG(`sampleRows`,()=>n.sampleRows(PQ,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=Ct(()=>w?.columnNames.join(`
611
611
  `)??``,[w]),A=a.map(e=>e.name).join(`
612
- `),j=Ct(()=>{let e=i.filter(e=>e.kind!==`memory`).flatMap(e=>Mz(e.schema));return e.length?e:null},[i]),M=Ct(()=>i.some(e=>e.kind!==`memory`)||!_&&i.some(e=>e.data.rows.length>kZ),[i,_]),N=Ct(()=>uZ(f.connections.filter(e=>r.includes(e.id)),i.length,M,d,o),[M,i,f.connections,r,o,d]),P=Ct(()=>{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 RZ(e,d)},[_,i,M,O,o,d,f.connections,r,N]),F=C&&`okByPart`in C?C.okByPart:void 0,I=Ct(()=>{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:FZ(i,r,d),columnSet:new Set([d,...r]),key:`${e[n].key}|channels`})}),e},[M,T,E,o,F,O,d]),L=Ct(()=>{let e=C?.parts??(w?[w]:[]),t=new Set;for(let n of e)for(let e of pZ(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=Ct(()=>{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=Ct(()=>{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,kZ));else{let e=Math.max(1,Math.floor(kZ/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=Ct(()=>{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=>LZ(e,i),l;if(!E)l=a(r);else{let e=a(r);l=[];for(let t=0;t<T.length;t++){let n=aB(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=sZ(f.flatMap((t,n)=>{let r=t.cols.get(`${e.column}__${n}`);return r?[{x:t.x,y:r}]:[]}),NZ);return t?[{seriesId:e.id,color:e.color,...t}]:[]}):void 0,m=T.flatMap((e,t)=>`bands`in e&&e.bands?CZ(e,d,r,E?aB(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=Ct(()=>{let e={pts:{},colorMeta:{},datasetColors:{}};if(!w)return e;let t={},r={},i={},a=MZ,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}=oG(o,l,p,{xKey:d,viewXRange:n,colorOverrides:s,palette:c});t[e.id]=r,i[e.id]=a;continue}let m=aG(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=Ct(()=>{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=$W(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=$W(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?$W(r,s,i):void 0,p=c?$W(r,c,i):void 0,m=l?$W(r,l,i):void 0;if(!f||!p||!m){e[a.id]={points:t};continue}let h=n?$W(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=Ct(()=>{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&&eG(w.rows,n.histColumn,D)||new Float64Array}return e},[w,l,u,D]),ne=Ct(()=>{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?$W(w.rows,n.polarAngleCol,D):void 0,i=n?.kind===`polar`&&n.polarRadiusCol?$W(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&&eG(e,t,D)||new Float64Array,a=n?$W(e,n,D):void 0;return{signal:i,rate:a&&nG(a)||parseFloat(r)||1}},ie=Ct(()=>{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=Ct(()=>{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?tG(w.rows,n.boxValueCol,n.boxGroupCol||void 0,D):[]}return e},[w,l,u,D]),ae=Ct(()=>{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=Ct(()=>{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=$W(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=$W(r,d,D),s,c;if(n.hmSpacing===`values`){o&&gJ(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&&gJ(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]=EZ(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);gJ(e)&&(f=e),gJ(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=Ct(()=>{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?tG(w.rows,n.vlValueCol,n.vlGroupCol||void 0,D):[]}return e},[w,l,u,D]),ce=Ct(()=>{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=Ct(()=>{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?$W(w.rows,n.rocScoreCol,D):void 0,i=n?.kind===`roc`&&n.rocLabelCol?$W(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=Ct(()=>{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:$W(t,e,D)??new Float64Array,axis:r})),c=s[0]?.values.length??t.length,l=i&&$W(t,i,D)||Float64Array.from({length:c},(e,t)=>t);e[n.id]={xValues:l,series:s}}return e},[w,l,u,D]),de=Ct(()=>{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?$W(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=Ct(()=>{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=>$W(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=$W(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=Ct(()=>{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=$W(t,a,D),f=$W(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=$W(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=Ct(()=>{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=Ct(()=>{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=>$W(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=Ct(()=>{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=>$W(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=Ct(()=>{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=>$W(r,e,D)),a=i[0]?.length??r.length,o=(n.acXCol?$W(r,n.acXCol,D):void 0)??HZ(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=Ct(()=>{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:eG(w.rows,e,D)??new Float64Array}))}return e},[w,l,u,D]),ye=Ct(()=>{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=$W(t,i.bbXCol,D),o=$W(t,i.bbYCol,D),s=$W(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=$W(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=Ct(()=>{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=Ct(()=>{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=Ct(()=>{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?$W(w.rows,n.cbScoreCol,D):void 0,i=n?.kind===`calibration`&&n.cbLabelCol?$W(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=Ct(()=>{let e={};if(!w)return e;let t={length:0,theoretical:[],sample:[]},n=e=>{let t=eG(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=Ct(()=>{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=Ct(()=>w?zZ(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:Ct(()=>{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?$W(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]=WZ(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 WZ(e,t,n,r){t<=e&&(t=e+1);let i=Fz(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 GZ=`#fb7185`,KZ=2500;function qZ(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 JZ(e){let t=YZ(e);if(t.status!==`empty`||!e.data.dataset)return t;let n=new Set([...e.data.datasetWithChannels?.columnNames??[],...e.data.numericCols]);return qZ(e.settings).some(e=>!n.has(e))?{...t,status:`missing`}:t}function YZ(e){let{panel:t,data:r,settings:i}=e;if(t.kind===`camera`)return{status:`ready`,data:null,node:q(XX,{settings:i?.kind===`camera`?i:er(),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??[],f=i?.kind===`multiband`?i:null,p=[...new Set((f?.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:f?.xAxisLine,yAxisLine:f?.yAxisLine,gridLine:f?.gridLine,lineWidth:f?.lineWidth,onPlotContextMenu:o,shiftMode:e.shiftMode},g=f?.beacon;if(g?.enabled&&e.beaconLive&&p.length>0){let t=LZ((f?.series??[]).filter(t=>t.column!==e.xKey),f?.layout??`overlay`),n=g.reference===`dataset`&&g.datasetId?e.findDataset(g.datasetId):void 0,r=SZ(g,!!n),i=r?[...gZ(t,r),...t]:t;return s(q(kW,{...h,series:i,points:[],showLatestValues:!0,liveSource:xZ(e.beaconLive,e.xKey,p,g,n),envelopes:n?CZ(n,e.xKey,t,r??void 0):void 0,liveZoomMode:`free`}),{series:i,points:[]})}if(r.anyDuckDb)return u.length===0?c:s(q(XW,{...h,layers:r.duckDbLayers,xKey:e.xKey,columns:p,maxPoints:KZ}),{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?dZ(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:ut(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=d(v.pts,i);if(e.xKey!==`ElapsedTime`)return[s];let c=ut(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(kW,{...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:Dn(4),n=r.xyzPointsByPanel[l];if(!n||n.points.length<1&&!n.surface)return c;let u=!!n.surface;return s(q(eq,{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:xn(t.xyzXScale.scaleMin,t.xyzXScale.scaleMax),yRange:xn(t.xyzYScale.scaleMin,t.xyzYScale.scaleMax),zRange:xn(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:En(GZ),n=r.xyPointsByPanel.pts[l]??[];if(n.length===0)return c;let u=r.xyPointsByPanel.colorMeta[l];return s(q(HG,{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(sq,{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(Tq,{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(Vq,{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(qq,{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(dJ,{signal:e,sampleRate:t,windowSize:i.sgWindowSize,overlap:i.sgOverlap,winFunc:i.sgWinFunc,yMode:i.sgYMode,backgroundToken:a,onPlotContextMenu:o}),e):s(q(oJ,{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(AJ,{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(RJ,{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(GJ,{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(ZJ,{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($J,{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(aY,{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(dY,{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(xY,{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(kY,{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(FY,{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(zY,{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(UY,{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(KY,{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(eX,{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(aX,{nodes:e,backgroundToken:a,onPlotContextMenu:o}),e)}case`sankey`:{let e=r.sankeyDataByPanel[l]??{nodeNames:[],links:[]};return e.links.length===0?c:s(q(dX,{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(pX,{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(hX,{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(AX,{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(bX,{tasks:e,backgroundToken:a,onPlotContextMenu:o}),e)}}return c}var XZ=500,ZZ=1e3;function QZ(e){if(Array.isArray(e))return $Z(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,$Z(n)));return t<0?null:t}function $Z(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 eQ(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 tQ({stats:e,host:t}){let[n,r]=wt(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?UH(t.current):0,d=f=>{c>=0&&f-s>ZZ&&(c=f,s=f,a=0,o=0,l=e.renders,u=t.current?UH(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>=XZ){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?UH(i):0;r({fps:a*1e3/p,repaints:(m-u)*1e3/p,worstFrameMs:o,renderMs:e.lastRenderMs,rendersPerSec:(e.renders-l)*1e3/p,points:QZ(e.data),domNodes:i?i.getElementsByTagName(`*`).length:0,canvasMp:s/1e6,heapMb:d?d.usedJSHeapSize/1048576:null,live:(()=>{let e=mU();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:nQ,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`,eQ(n.points)]],[`DOM nodes`,eQ(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])=>kt(`div`,{style:rQ,children:[q(`dt`,{style:iQ,children:e}),q(`dd`,{style:n?{...aQ,color:n}:aQ,children:t})]},e))})}var nQ={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)`},rQ={display:`flex`,justifyContent:`space-between`,gap:12},iQ={color:`var(--text-muted, #8a93a6)`},aQ={margin:0,fontWeight:600,textAlign:`right`},oQ=[],sQ=3,cQ=`data-kymo-annotation-controls`;function lQ(e,t,n,r){return e.anchor===`x`&&!r?null:e.points.map(([i,a])=>[e.anchor===`x`?AU(r,i):i*t,a*n])}function uQ(e,t,n,r,i){return t.map(([t,a])=>[e.anchor===`x`&&i?jU(i,t):dQ(t/Math.max(1,n)),dQ(a/Math.max(1,r))])}var dQ=e=>Math.round(e*1e4)/1e4,fQ=vt(function({annotations:e,tool:t,plotFrame:n,onChange:r,onToolEnd:i,onSelect:a,marks:o=oQ,onMarkSelect:s}){let c=K(null),l=Tt(n.subscribe,n.get),u=l?.x?l:null,[d,f]=wt({w:0,h:0}),[p,m]=wt(null),[h,g]=wt(null),[_,v]=wt(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||xQ(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=>uQ(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)>sQ,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=lQ(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)<=sQ)return;let{size:c,frame:l}=y.current;a={...t,points:uQ(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(bQ(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=lQ(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=lQ(Yt(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`?yQ(F.px):null,R=e=>kt(Ot,{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(hQ,{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 kt(`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(mQ,{initial:e.text??``,onDone:M}):e.text,p===e.id&&e.kind===`text`&&!n?q(pQ,{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?kt(Ot,{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})=>kt(`g`,{"data-mark":e.ruleId,role:`img`,"aria-label":`${e.late?`Late · `:``}${e.ruleName}, ${e.severity}`,className:`kymo-mark kymo-mark--${e.severity}${e.late?` kymo-mark--late`:``}`,style:{color:Jt[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,kt(`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:gQ(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(pQ,{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 pQ({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 mQ({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 hQ({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 kt(Ot,{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=vQ(i,a,o,s,e.width);return kt(Ot,{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=_Q(t);return kt(Ot,{children:[r(e),q(`path`,{d:e,...n})]})}}return null}function gQ(e,t){if(e.kind===`arrow`)return t;let[[n,r],[i,a]]=t;return[[n,r],[i,r],[i,a],[n,a]]}function _Q(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 vQ(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 yQ(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 bQ(e,t){if(t)return{...e,text:t};let{text:n,...r}=e;return r}function xQ(e){let t=e;return!!t&&(t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))}function SQ(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=lQ(i,n,r,o);t&&(e.save(),i.anchor===`x`&&o&&(e.beginPath(),e.rect(o.left,0,o.width,r),e.clip()),CQ(e,i,t,a),e.restore())}e.restore()}function CQ(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(_Q(n)));else if(t.kind===`arrow`){let r=vQ(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 wQ={solid:void 0,dashed:`5 4`,dotted:`1 4`};function TQ(e,t,n){if(!e||!(n===`x`?e.x:e.y))return null;if(n===`x`){let n=AU(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=MU(e,t.value);return r>=e.top-.5&&r<=e.top+e.height+.5?[e.left,r,e.left+e.width,r]:null}var EQ=vt(function({frame:e,alarm:t,axis:n}){let r=TQ(Tt(e.subscribe,e.get),t,n);if(!r)return null;let i=t.linked?DQ(r,n):null;return kt(`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`?zU.join(` `):wQ[t.style]}),i?q(`path`,{"data-alert-glyph":``,d:RU,transform:`translate(${i[0]} ${i[1]})`,fill:t.color}):null]})});function DQ(e,t){return t===`y`?[e[2]-10-3,e[1]-10-2]:[e[0]+3,e[1]+2]}function OQ(e,t,n,r,i){let a=TQ(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`?zU:wQ[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=DQ(a,r);VU(e,t[0],t[1],n.color)}e.restore()}}function kQ(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,PQ(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 AQ=new WeakMap;function jQ(e,t){let n=AQ.get(e);n||AQ.set(e,n=new Map);let r=n.get(t);return r||n.set(t,r=n=>e.view.setLiveWindow(n,t)),r}var MQ=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=Dt(document.createElement(`div`)),this.root.render(q(BQ,{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}},NQ=new WeakMap;function PQ(e){let t=NQ.get(e);return t||(t=new MQ(e),NQ.set(e,t)),t}function FQ(e,t,n,r={}){e.charts.get(t);let i=PQ(e),a={key:crypto.randomUUID(),chartId:t,element:n,options:r,shiftDatasetId:null,emitter:qV(),xyz:null,annotationTool:null,selectedAnnotation:null,plotFrame:FU(),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 UE(`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 UE(`export_failed`,{reason:`canvas unavailable`}));for(let e of r)o.drawImage(e,0,0);let s=e.charts.get(t),c=XQ(s.settings,$1(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=$Q(s.annotations,d?ZQ(u.marks,u.selection,d.xKey):[],l),p=pr(c);return p&&n.clientWidth>0&&OQ(o,a.plotFrame.get(),p.alarm,p.axis,i.width/n.clientWidth),f.length&&n.clientWidth>0&&SQ(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 UE(`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 IQ(e){NQ.get(e)?.refresh()}function LQ(e){NQ.get(e)?.dispose(),NQ.delete(e)}function RQ(e){let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-color-scheme`,`class`,`data-theme`]}),()=>t.disconnect()}var zQ=()=>{let e=document.documentElement;return`${e.getAttribute(`data-color-scheme`)??``}|${e.getAttribute(`data-theme`)??``}|${e.className}`};function BQ({engine:e,registry:t}){Tt(t.subscribe,t.getVersion);let n=$1(e),r=Tt(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(Ot,{children:[...i.values()].map(t=>q(WQ,{engine:e,worksheet:t.worksheet,mounts:t.mounts},t.worksheet.id))})}var VQ=1e3,HQ=.25;function UQ(e,t,n,r){let[i,a]=wt(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=zH(u),o.current||n<l||WH()||!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/HQ-1),o.current=performance.now(),yt(()=>a(e=>e+1)))};return i=zH(u),()=>BH(i)},[n,e,t]),Ct(()=>n?e.map(e=>t.includes(e.id)?{...e,dataset:e.source.snapshot(VQ)}:e):e,[e,t,n,i])}function WQ({engine:e,worksheet:t,mounts:n}){let r=$1(e),i=Tt(r.store.subscribe,r.store.get),a=r.derived(),o=i.xRanges[t.id]??null,s=Ct(()=>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=UQ(s,i.selection,u,f),m=r.alertLines(),h=UZ({worksheet:JQ(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(GV()).current,_=Tt(RQ,zQ),v=t.id,y=jQ(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(Ot,{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=kQ(n,e,v),l=XQ(t.panelChartSettings[r.id],m);return Et(q(r$,{mount:n,annotations:t.panelChartSettings[r.id]?.annotations,marks:ZQ(i.marks,i.selection,t.xKey),onMarkSelect:c.onMarkSelect,alarm:pr(l),onAnnotations:c.onAnnotations,onAnnotationToolEnd:c.onAnnotationToolEnd,onAnnotationSelect:c.onAnnotationSelect,render:u=>JZ({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:qX(a.selectedDatasets,i.offsets),shiftMode:s?GQ(e,s.id,s.name):void 0,onContextMenu:c.onContextMenu,xyzRef:c.xyzRef}),licensed:b},n.key),n.element,n.key)})})}function GQ(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 KQ=[],qQ=new WeakMap;function JQ(e,t){if(!t.size)return e;let n=qQ.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]=XQ(a,t),i[n]!==a&&(r=!0);let a=r?{...e,panelChartSettings:i}:e;return qQ.set(e,{lines:t,out:a}),a}var YQ=new WeakMap;function XQ(e,t){if(!e||!t.size)return e;let n=YQ.get(e);if(n&&n.lines===t)return n.out;let r=dr(e,t);return YQ.set(e,{lines:t,out:r}),r}var ZQ=e$((e,t,n)=>{let r=e.filter(e=>e.timeColumn===n&&t.includes(e.targetId));return r.length?r:QQ}),QQ=[];function $Q(e,t,n){return!t.length||!n?.x?e:[...t.map(e=>Yt(e,n.x.v1)),...e]}function e$(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 t$(e,t){e.data=t}function n$(e,t){e.status!==t&&(e.status=t,e.emitter.emit(`status`,t))}function r$({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]=wt(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 GH(t);return n.observe(e),()=>n.disconnect()},[]);let{status:h,node:g,data:_}=t(d||400);m.data=_,W(()=>{t$(e,_)}),W(()=>{n$(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),kt(`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(IU.Provider,{value:e.plotFrame.set,children:g}),h===`ready`&&a?q(EQ,{frame:e.plotFrame,alarm:a.alarm,axis:a.axis}):null,h===`ready`&&(r?.length||e.annotationTool||i.length)?q(fQ,{annotations:r??KQ,tool:e.annotationTool,plotFrame:e.plotFrame,onChange:o,onToolEnd:s,onSelect:c,marks:i,onMarkSelect:l}):null,p?q(tQ,{stats:m,host:u}):null,n===!1?q(KV,{}):null]})}var i$=new WeakMap;function a$(e,t,n,r={}){let i=i$.get(e)??new Map;i$.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 UE(`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),NH(l);let h=n(m,r.mount),g=qV(),_=!1,v=()=>{_||(_=!0,i.delete(t),PH(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 o$(e){for(let t of[...i$.get(e)?.values()??[]])t.close()}function s$(e){let t=new Map;for(let[n,r]of i$.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 c$=12e3,l$=100;function u$(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 A.add(n),n;for(let e=0;e<n.length;e++){let t=n[e];t-t!==0&&(n[e]=NaN)}return n}function d$(e,t){let n=Object.keys(t.columns);if(n.length===0)throw new UE(`no_columns`);let r=t.columns[n[0]].length;if(n.some(e=>t.columns[e].length!==r))throw new UE(`column_length_mismatch`);let i=new Map(n.map(e=>[e,u$(t.columns[e],t.transfer)])),a=f$(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 UE(`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 f$(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,l$);t++)e.push(o.map(e=>{let r=n.get(e)[t];return r===r?String(r):``}).join(`,`));d=e.join(`
615
- `),f=Be(d)}let p={id:e,name:t,schema:l,rawText:d,parseConfig:f,fromColumns:!0};if(s>1e6){let e=new wZ(n,r);return{...p,kind:`columnar`,source:e,data:{meta:``,columnNames:o,units:c,rows:e.sampleRowsSync(c$)}}}let m={meta:``,columnNames:o,units:c,rows:Pe({keys:o,length:s,values:o.map(e=>n.get(e)),text:o.map(()=>null)},i)};return{...p,kind:`memory`,source:new ZE(m),data:m}}function p$(e,t,n){let r=e.fromColumns?m$(e):null;if(!r)throw new UE(`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)?(Qe(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{...h$(e,o,!0),columnSpares:s}}function m$(e){if(e.source instanceof wZ)return new Map(e.source.columnMap);let t=Ue(e.data.rows);return t?new Map(t.keys.map((e,n)=>[e,t.values[n]])):null}function h$(e,t,n=!1){let r=e.fromColumns?m$(e):null;if(!r)throw new UE(`invalid_argument`,{reason:`only datasets added with addColumns can be replaced`});let i=r;for(let e of Object.keys(t))i.set(e,u$(t[e],n));let a=i.values().next().value.length;for(let e of i.values())if(e.length!==a)throw new UE(`column_length_mismatch`);let o=Object.fromEntries(e.schema.map(e=>[e.name,e.unit])),s=f$(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 g$=new WeakMap;function _$(e){let t=e.fromColumns?m$(e):null;if(!t)return e.rawText??``;let n=e.data.rows,r=g$.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(`,`));g$.set(n,r=a.join(`
616
- `))}return r}function v$(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 y$(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 b$(){let e=y$(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?ZB(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=EB(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:PB(n.id,t),name:`${n.name} · Cycle ${t+1}`,data:r,source:new ZE(r)}}),values:a.map(e=>AB(n.data.rows,e,r,i)),unit:o,isTime:i===`span`&&MB(r,o)}}return t}),t=y$((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=y$((e,t)=>e.filter(e=>e.kind===`data`&&t.includes(e.id))),r=y$(e=>lZ(e.map(e=>e.data))),i=y$((e,t)=>t.length===0?e:lZ(e?[e,...t.map(e=>e.dataset)]:t.map(e=>e.dataset))),a=y$((e,t,n,r)=>{let i=new Set;if(e)for(let t of n.length>0?n:[e])for(let e of pZ(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=>Mz(e.schema));return[...new Set([...a,...o])]});return{lapsByDataset:e,selectedDatasets:t,selectedLive:n,staticDataset:r,mergedDataset:i,mergedParts:y$((e,t)=>[...e.map(e=>e.data),...t.map(e=>e.dataset)]),numericColumns:y$((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:y$((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:y$((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 x$=[{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`}],S$=new Map(x$.map(e=>[e.kind,e.label]));function C$(e){return S$.get(e)??e}var w$=`kymoscope-live.v1`,T$=`kymoscope-live.ack1`,E$=`kymoscope-live.ack2`,D$=1e3,O$=2e3,k$=3e4,A$=1e4,j$=30,M$=1e4,N$=300,P$=90,F$=e=>e.startsWith(`eyJ`);function I$(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 L$(e,t){return`${e.replace(/\/+$/,``)}/v1/streams/${t}/watch`}function R$(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=I$(r);if(a===null)return;let c=F$(r),d=c?Math.min(a,Date.now()/1e3+N$):a,f=Math.min(Math.max((d-(c?P$:j$))*1e3-Date.now(),M$),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(k$,O$*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(L$(e.url,t),[w$,T$,E$,`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}},D$);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>=A$)))}};return f(),()=>{if(s=!0,a&&=(clearTimeout(a),null),l(),i){let e=i;i=null,e.close(1e3)}}}var z$=960*1024,B$=24;function V$(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(B$+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=B$;return n&&(r[a++]=t.length,r.set(t,a),a+=t.length),r.set(e.payload,a),r}function H$(e){if(e.length<B$||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=B$,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 U$(e){let t=Math.max(1,Math.ceil(e.data.length/z$)),n=[];for(let r=0;r<t;r++)n.push(V$({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*z$,Math.min(e.data.length,(r+1)*z$))}));return n}function W$(e,t,n){let r=new Map,i=Promise.resolve(),o=n?ne(n,e=>t({type:`integrity`,integrity:e})):null;return Object.assign(n=>{let c=s(e,n).catch(()=>null);o?.arrive(n,new Uint8Array(n,0,1)[0]&127,c),i=i.then(async()=>{try{let e=await c;if(!e)return;if(e.kind===6){let n=H$(e.plaintext);n&&t({type:`video`,m:n})}else if(e.kind===5){let t=M(e.plaintext);r.set(t.id,t)}else if(e.kind===7){let n=a(e.plaintext,r);n&&t({type:`last`,values:n})}else if(e.kind===4){let n=await ot(e.plaintext,r);n&&t(n.historical?{type:`columns`,block:n.block,historical:!0}:{type:`columns`,block:n.block})}else if(e.kind===3)t({type:`columns`,block:it(e.plaintext)});else if(e.kind===2){let n=Oe(e.plaintext);t({type:`frames`,frames:Array.isArray(n?.frames)?n.frames:[]})}}catch{}})},{reset:()=>o?.reset()})}var G$=``+new URL(`assets/liveIngestWorker-UV5D515-.js`,import.meta.url).href;function K$(e,t,n,r,i){let a=()=>{let a=W$(n,r,t);return R$(e,t,a,e=>{e===`subscribed`&&a.reset(),i?.(e)})},o;try{if(typeof Worker>`u`)return a();o=WE(G$)}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 q$=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}},J$=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 Y$(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 H(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(){}},Y$=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)}},X$=4096,Z$=5e3,Q$=class{startedAt=Date.now();n=0;capacity=X$;time=new Float64Array(X$);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=x(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($$).join(`,`)}\n${t.map($$).join(`,`)}\n`],r=this.order.map(e=>this.cols.get(e));for(let e=0;e<this.n;e+=Z$){let t=Math.min(this.n,e+Z$),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 $$(e){let t=/^[=+\-@\t\r]/.test(e)?`'${e}`:e;return/[",\n\r]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var e1=512,t1=new WeakMap;function n1(e,t,n){let r=t1.get(e);r||t1.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 r1(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=fE(r.formula);if(!s.ok)continue;let{identifiers:c,functions:l}=pE(s.node);if(!c.every(e=>o.has(e)))continue;let u=l.some(e=>uE.includes(e)),d=Math.max(e.firstAbs,a-(u?e1:0)),f=new Map([n,...c].map(t=>[t,e.range(t,d,i)])),{carry:p,keep:m}=n1(e,`${r.id}|${r.formula}`,d),h=yE(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 i1(e,t){e.clearComputed(),t1.delete(e),r1(e,t,e.firstAbs)}var a1=8e3,o1=131072;function s1(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 c1=new Map;function l1(e,t){let n=`${t}|${Math.floor(e/900)}`,r=c1.get(n);r===void 0&&(r=bB(e,t),c1.size>1e4&&c1.clear(),c1.set(n,r));let i=(e+r)%86400;return i<0?i+86400:i}var u1=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`?l1(e,n.tz):n.kind===`elapsed`?e-this.#e:e<this.#e?NaN:n.kind===`event`?(this.#t!==this.#t&&t===t&&hB(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 d1(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&&hB(r.op,o,r.value)&&(a=e[t])}return{x:e.map(e=>e-a),t:e,cols:t}}let a=new u1(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 f1(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 p1(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 m1(e,t,n){let r=Math.max(2,Math.min(a1,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=f1(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 h1(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 g1=new WeakMap;function _1(e){let t=g1.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 g1.set(e,t),t}function v1(e,t,n){if(n===`minmax`)return{lo:e.min,hi:e.max};if(n===`sigma`){let n=_1(e);return{lo:e.mean.map((e,r)=>e-t*n[r]),hi:e.mean.map((e,r)=>e+t*n[r])}}let r=h1(n,e);return{lo:e.mean.map(e=>e-r),hi:e.mean.map(e=>e+r)}}function y1(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:_}=v1(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(h1(h,i),1e-9):0,C=_1(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=p1(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<p1(t.x,g,s)||a>p1(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 b1(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 ge(new Uint8Array(i.buffer))}function x1(e,t){let n=de(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 S1(e){if(!e.cycle)throw Error(`a live segment axis needs a cycle rule`);let t=new zB(e.cycle),r=new u1(e.axis),i=NaN,a=`channel`in e.axis?e.axis.channel:null,o=[...new Set([...RB(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 C1=1e7;function w1(e=globalThis.navigator?.deviceMemory){return Math.max(512,Math.round(((e??0)>0?e:16)*1024/8))}var T1=400,E1=4e3,D1=1e3,O1=3e3,k1=2,A1=5e3,j1=1e4;function M1(e,t,n=`data`){let r=new Ee(t.capacity??C1,void 0,void 0,(t.maxMemoryMB??w1())*1024*1024);return{meta:e,buffer:r,source:new J$(()=>r),unsub:()=>{},status:`connecting`,error:null,lastFrameAt:Date.now(),lastColCount:0,lastValued:0,recorder:null,dropped:0,recDropped:0,video:n===`camera`?new HE:null,clock:n===`camera`?null:new q$,lagTicks:0,lastRejoinAt:0,rejoin:()=>{},subscribed:!1,releaseTimer:void 0}}function N1(e,t,n,r){let i,a=-1/0,o=new Map;return async s=>{if(i===void 0&&(i=s,o.set(t,s)),s===i)return e;if(Date.now()-a<2e3)return null;a=Date.now();let c=await r().catch(()=>null);if(!c||o.has(c.salt)&&o.get(c.salt)!==s)return null;let l=c.key??(n===null?null:await _(n,c.salt));return!l||!await at(l,c.key_check).catch(()=>!1)?null:(o.set(c.salt,s),l)}}function P1(e,t,n=()=>({}),r){let i=new Map,a=e,o=[],s=[],c=``,l=()=>{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(T1),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)},u=(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&&f(e,r,t[t.length-1]?.t)},d=(e,t)=>{let n=e.buffer.endAbs;e.buffer.pushColumns(t),e.recorder?.addColumns(t),t.t.length>0&&f(e,n,t.t[t.t.length-1])},f=(e,t,n)=>{r1(e.buffer,s,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),p(e,t===0||e.buffer.columnNames.length!==e.lastColCount||e.buffer.valuedCount!==e.lastValued)},p=(e,t)=>{e.lastFrameAt=Date.now();let n=e.status===`stale`||e.status===`connecting`;n&&(e.status=`live`),(n||t)&&l()},m=e=>{let t=i.get(e);t&&(clearTimeout(t.releaseTimer),t.unsub(),i.delete(e),l())},h=setInterval(()=>{let e=Date.now(),t=!1;for(let n of i.values()){n.status===`live`&&e-n.lastFrameAt>E1&&(n.status=`stale`,t=!0);let i=n.video&&n.subscribed&&n.status===`live`?n.video.info().lagMs:null;n.lagTicks=i!==null&&i>O1?n.lagTicks+1:0,n.video&&n.lagTicks>=k1&&e-n.lastRejoinAt>=A1&&(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&&l()},D1);return{connections:()=>o,disconnect:m,startRecording(e){let t=i.get(e);!t||t.recorder||(t.recorder=new Q$,t.recDropped=0,l())},stopRecording(e){let t=i.get(e),n=t?.recorder;return!t||!n?null:(t.recorder=null,l(),{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:S1(t)}:void 0,t&&n.segAxis.tracker.feed(n.buffer,n.buffer.firstAbs,!t.replay),l())},setMathChannels(e){let t=JSON.stringify(e.map(e=>[e.id,e.name,e.units,e.formula,e.enabled]));if(t!==c){c=t,s=e;for(let t of i.values())t.video||(i1(t.buffer,e),t.segAxis&&(t.segAxis.tracker=S1(t.segAxis.cfg),t.segAxis.tracker.feed(t.buffer,t.buffer.firstAbs,!0)));i.size>0&&l()}},openLocal(e,t){let r=`local:${crypto.randomUUID()}`,a=M1({id:r,name:e,ownerName:`This page`,visibility:`private`,orgName:null,parentId:null,lowOf:null},{...n(),...t});return i.set(r,a),l(),{id:r,push:e=>{i.get(r)===a&&u(a,Array.isArray(e)?e:[e])},pushColumns:e=>{i.get(r)===a&&d(a,e)},close:()=>m(r)}},async connect(e,t,o){if(i.has(e.id))return;let s=a&&e.relay_url?{...a,url:e.relay_url,getToken:async e=>{let t=await a.getToken(e);return t&&!F$(t)?t:null}}:a;if(!s)throw new UE(`relay_unavailable`);let c;if(typeof t==`string`){let n=se(t).secret??t,r=await _(n,e.salt);if(!await at(r,e.key_check))throw new UE(`wrong_password`);c=o?.reload?N1(r,e.salt,n,o.reload):r}else if(c=`keyFor`in t?e=>t.keyFor(e):t,typeof c!=`function`){if(!await at(c,e.key_check))throw new UE(`wrong_password`);o?.reload&&(c=N1(c,e.salt,null,o.reload))}let f=M1({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(),...o},e.kind);i.set(e.id,f);let m=t=>{if(i.get(e.id)===f)if(t.type===`video`)f.video&&(f.video.push(t.m),p(f,!1));else if(t.type===`last`){let e=f.buffer;for(let n of t.values)e.setLastKnown(n.name,n.unit,n.t,n.v);(e.columnNames.length!==f.lastColCount||e.valuedCount!==f.lastValued)&&l()}else if(t.type===`gap`)f.dropped+=t.samples,f.recorder&&(f.recDropped+=t.samples),l();else if(t.type===`integrity`){let e=f.integrity;f.integrity=t.integrity,(!e||e.broken!==t.integrity.broken)&&l()}else t.type===`columns`?t.historical?r?.historical?.(e.id,t.block):d(f,t.block):u(f,t.frames)},h=t=>{!f.subscribed||i.get(e.id)!==f||(t===`subscribed`?(f.status=`live`,f.lastFrameAt=Date.now()):t===`error`&&(f.status=`error`,f.error=`connection_error`),l())};f.rejoin=()=>{f.unsub=f.video?R$(s,e.id,W$(c,m),h):K$(s,e.id,c,m,h)};let g=f.video;g?(f.status=`idle`,g.onDemandChange(t=>{i.get(e.id)===f&&(clearTimeout(f.releaseTimer),t?f.subscribed||(f.subscribed=!0,g.resync(),f.status=`connecting`,f.lastFrameAt=Date.now(),f.rejoin(),l()):f.releaseTimer=setTimeout(()=>{f.subscribed=!1,f.unsub(),f.unsub=()=>{},f.status=`idle`,f.error=null,f.lagTicks=0,l()},j1))})):(f.subscribed=!0,f.rejoin()),l()},dispose(){clearInterval(h);for(let e of i.values())clearTimeout(e.releaseTimer),e.unsub();i.clear(),o=[]}}}var F1=500,I1=1<<20;function L1(e){let t=[],r=new Map,i=new Map,a=[],o=``,s=(e,t)=>`${e}|${t}`,c=(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)},l=()=>[...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}}}),u=()=>{let t=l(),n=JSON.stringify(t);n!==o&&(o=n,e.setStates(t))};function d(n,r,i=!1){let o=t.find(e=>e.id===n.ruleId);if(n.kind===`raised`){a=[...a,{id:`${n.ruleId}|${n.target.id}|${n.t}${i?`|late`:``}`,ruleId:n.ruleId,ruleName:o?.name??``,severity:o?.severity??`info`,targetId:n.target.id,timeColumn:r,t0:n.t,t1:null,...i?{late:!0}:{}}];let e=a.filter(e=>e.targetId===n.target.id);e.length>F1&&(a=a.filter(t=>t!==e[0]))}else{let e=a.find(e=>e.ruleId===n.ruleId&&e.targetId===n.target.id&&e.t1===null&&!!e.late===i);e&&(a=a.map(t=>t===e?{...t,t1:n.t}:t))}e.setMarks(a),e.emit(i?{...n,late:!0}:n)}function f(){let a=new Set;for(let i of e.targets())for(let e of t){if(!c(e,i))continue;let t=s(e.id,i.id);a.add(t);let o=r.get(t),{channels:l,...u}=i;(!o||o.rule!==e)&&(o=ft(e,u),r.set(t,o));for(let e of o.bind(l))d(e,i.kind===`stream`?n:``)}for(let e of r.keys())a.has(e)||r.delete(e);for(let[e,t]of i)r.get(e)?.rule!==t.rule&&i.delete(e);u()}return{setRules(n){let r=[],i=n.filter(e=>{let t=pt(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}),f(),r},rules:()=>t,state:l,async evaluate(n,r){let i=e.targets().find(e=>e.id===n&&e.kind===`dataset`);if(!i)return[];let{channels:o,...s}=i,l=[],u=t.filter(e=>(!r.ruleIds||r.ruleIds.includes(e.id))&&c(e,s)),f=u.map(e=>{let t=ft(e,s);return t.bind(o),t}),p=[...new Set(u.flatMap(e=>Object.values(e.signals).map(e=>`formula`in e?e.formula:e.channel)))];for(let t=0;;t+=I1){let i=await e.readDataset(n,[r.timeColumn,...p],t,I1),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<I1)break}a=a.filter(e=>!(e.targetId===n&&(!r.ruleIds||r.ruleIds.includes(e.ruleId)))),e.setMarks(a);for(let e of l)d(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)d(e,n)}i&&u()},pushLate(t,a){let o=e.targets().find(e=>e.id===t&&e.kind===`stream`);if(!o)return;let{channels:s,...c}=o;for(let[e,o]of r){if(o.target.id!==t)continue;let r=i.get(e);(!r||r.rule!==o.rule)&&(r=ft(o.rule,c),r.bind(s),i.set(e,r));for(let e of r.push(a))d(e,n,!0)}},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)d(e,n)}i&&u()},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:f,clearMarks(t){a=t?a.filter(e=>e.targetId!==t):[],e.setMarks(a)}}}var R1=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}},z1={maxChartsPerWorksheet:null,maxChannelsPerChart:null,maxWorksheets:null,maxMathChannels:null,maxAlertRules:null,canImportExportWorkspaces:!0},B1=[];function V1(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 H1=[`#a78bfa`,`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#94a3b8`];function U1(e=`ET`){return{id:crypto.randomUUID(),name:`Worksheet`,panels:[],panelChartSettings:{},panelChartBackgrounds:{},xKey:e}}function W1(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(br({...e,name:a,source:`workbook`}))}return{channels:i,rename:r}}function G1(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 K1(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 q1(e,t,n){if(!e||!t)return fn();let{min:r,max:i}=Nz(e.rows,t);if(!Number.isFinite(r)||!Number.isFinite(i))return fn();let a=Fz(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 J1(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:Tn();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:En(H1[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:Dn(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 Y1(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 X1(){return typeof document>`u`?`dark`:uB(null)}function Z1(e={}){let t={...e},r=!1,i=U1(),a=v$({datasets:[],selection:[],worksheets:[i],activeWorksheetId:i.id,xRanges:{},offsets:{},colors:{},liveWindowSeconds:15,cycleRules:[],live:[],video:[],mathChannels:[],limits:{...z1,...t.limits},palette:sB(t.palette,X1()),importing:0,licensed:null,history:{canUndo:!1,canRedo:!1},marks:[],alerts:[],alertRules:[]}),o=qV(),s=()=>{let e=sB(t.palette,X1());a.set(t=>t.palette.join()===e.join()?t:{...t,palette:e})},c=typeof document>`u`?()=>{}:dB(null,s),l=b$(),u=()=>{if(r)throw new UE(`disposed`)},d=e=>{throw o.emit(`limit`,{reason:e}),new UE(`limit_reached`,{reason:e})},f=()=>a.get(),p=(e,t)=>{let n=f().limits.maxChannelsPerChart,r=Pz(t);n!==null&&r>n&&r>Pz(e)&&d(`channels-per-chart`)},m=y$((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??B1,layout:t.rect,window:t.window??null}),_=y$((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=y$((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:aB(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:aB(n,i.id,s(i.id,a),o),offset:r[i.id]??0,selected:t.includes(i.id),...e.cut?{cycle:V1(e.cut,a)}:{}})):null,selected:c?u===0?!1:u===l.length?!0:`partial`:t.includes(e.id)}})}),y=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:aB(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=y$(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 R1({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 UE(`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 UE(`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=P1(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(!ce.rules().length)return;t.columnNames.length!==ee.get(e)&&(ee.set(e,t.columnNames.length),ce.sync());let i=ce.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);ce.pushLive(e,{t:t.range(n,o,a),columns:s,scan:new Map})},historical:(e,t)=>{if(!ce.rules().length||!t.t.length)return;let n={};for(let r of ce.liveColumns(e)){let e=t.columns[r];e&&(n[r]=e instanceof Float64Array?e:Float64Array.from(e))}Object.keys(n).length&&ce.pushLate(e,{t:t.t instanceof Float64Array?t.t:Float64Array.from(t.t),columns:n,scan:new Map})},tick:(e,t,r)=>{if(!ce.rules().length)return;let i=t.range(n,t.endAbs-1,t.endAbs)[0];i===i&&ce.tickLive(e,i+(Date.now()-r)/1e3)}}),ee=new Map,te=y$((e,t)=>e.filter(e=>t.some(t=>PE([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=Mz(e.schema);t.length&&T(()=>a.set(e=>({...e,worksheets:e.worksheets.map(e=>J1(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 UE(`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 RR(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 jz({main:t,companions:i.companions,format:i.format.id},{priorInMemoryValues:AR(f().datasets),signal:s,onProgress:e=>o.emit(`import`,{file:t.name,phase:`progress`,fraction:e}),chooseChannels:n.chooseChannels,pickChannels:n.pickChannels}):[await kR(crypto.randomUUID(),t,f().datasets)??await DR(crypto.randomUUID(),t,K1,void 0,AR(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 UE(`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 UE&&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},ae=()=>setTimeout(()=>{r||IQ(rt)},0),oe=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&&ae()},se=async(e,t,n={})=>{let[r,...i]=await jz({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}}}},ce=L1({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({})}}),ue=y$((e,t)=>{let n=new Map;for(let r of e){let e=ht(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}),de=null;a.subscribe(()=>{let e=f();de&&de[0]===e.datasets&&de[1]===e.live||(de=[e.datasets,e.live],ce.rules().length&&ce.sync())});let fe={importFiles:ie,warmImport(e={}){u(),yz(!!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 UE(`not_found`,{datasetId:e});if(!t.info?.combined||!(t.file instanceof File))throw new UE(`invalid_argument`,{reason:`only a combined multi-rate import can be split`});let n=await jz({main:t.file,companions:t.companions??[],format:t.info.importer},{priorInMemoryValues:AR(f().datasets.filter(t=>t.id!==e)),selection:t.info.selection,split:!0});oe([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 UE(`not_found`,{datasetId:e});if(!n.info||!(n.file instanceof File))throw new UE(`invalid_argument`,{reason:`only binary imports have channels to choose`});try{let r=await jz({main:n.file,companions:n.companions??[],format:n.info.importer},{priorInMemoryValues:AR(f().datasets.filter(t=>t.id!==e)),initial:n.info.selection,chooseChannels:t,pickChannels:!0});oe([e]);for(let e of r)ne(e);return r.map(e=>e.id)}catch(e){if(e instanceof UE&&e.code===`cancelled`)return null;throw e}},async combine(e){u();let t=f().datasets.find(t=>t.id===e);if(!t)throw new UE(`not_found`,{datasetId:e});let n=t.info?.splitKey;if(!n||!(t.file instanceof File))throw new UE(`invalid_argument`,{reason:`only datasets split from one file can be combined`});let r=f().datasets.filter(e=>e.info?.splitKey===n),i=await jz({main:t.file,companions:t.companions??[],format:t.info.importer},{priorInMemoryValues:AR(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 UE(`invalid_argument`,{reason:`these groups have no common time base`})}return oe(r.map(e=>e.id)),ne(i[0]),i[0].id},async openRecording(e,t={}){u();let n=await se(e,AR(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 UE(`not_found`,{datasetId:e});let r=await se(t,AR(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),ae()},addColumns(e){u();let t=d$(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 UE(`not_found`,{datasetId:e});let i=h$(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 UE(`not_found`,{datasetId:e});let i=p$(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 wR(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 UE(`not_found`,{datasetId:e});let i=await JB(r.source,n,XB(t)),a=new Map(t.filter(e=>e.kpis?.length).map(e=>[e.id,e.kpis]));return YB(i,t).map(e=>a.has(e.definitionId)?{...e,kpis:QB(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 UE(`not_found`,{datasetId:e});let r=n.schema.filter(e=>e.type===`number`&&e.name!==t.timeKey).map(e=>e.name),i=await JB(n.source,t.timeKey,r),a={...Object.fromEntries(n.schema.map(e=>[e.name,e.unit])),[KB]:`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 UE(`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(fe.addColumns({name:`${n.name} · ${c}`,columns:eV(i,t.timeKey,r),units:a}))}if(t.tables!==!1){let e=nV(t.found,t.cycleId,t.defs,i);s.push(await fe.addText(rV(e.cycles),`${n.name} · ${o(t.cycleId)}s.csv`)),e.phases.length&&s.push(await fe.addText(rV(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 UE(`not_found`,{datasetId:e});let r;if(t){if(!t.defs.some(e=>e.id===t.cycleId))throw new UE(`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 JB(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=YB(a,t.defs).sort((e,t)=>e.tstart-t.tstart||!!e.parentIndex-+!!t.parentIndex).map(e=>c.has(e.definitionId)?{...e,kpis:QB(a,e,c.get(e.definitionId))}:e),u={...Object.fromEntries(n.schema.map(e=>[e.name,e.unit])),[KB]:`s`},d=e=>t.defs.find(t=>t.id===e)?.name??e,f=l.map(r=>d$(`${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:eV(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(),oe([e])},clear(){u(),oe(f().datasets.map(e=>e.id))},async configure(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new UE(`not_found`,{datasetId:e});if(t.parseConfig&&(n.kind!==`memory`||!n.parseConfig))throw new UE(`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 UE(`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?EB(n.data.rows,r.channel):[],l=r&&t.selectCycles===`best`?jB(c.map(e=>AB(n.data.rows,e,r.metric,r.stat))):null,u=l===null?c.map((t,n)=>PB(e,n)):[PB(e,l)];z(o?c.length>0?[...s,...u]:[...s,e]:s)}let r=t.parseConfig;if(!r)return;let i=(()=>{try{let e=Xe(U(n.rawText??``),r.headerRow);return n.data.columnNames.length===e.length&&n.data.columnNames.every((t,n)=>t===e[n])}catch{return!1}})();if(le(r,n.parseConfig)&&i)return;let o=n.fromColumns?_$(n):n.rawText??``,s=await JE(n.file?{file:n.file,config:r}:{rawText:o,config:r}),c=new ZE(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),ae(),n.cut&&await fe.cut(e,n.cut);let p=h().selectedDatasets,m=new Set(p.flatMap(e=>e.data.columnNames)),g=s.columnNames.filter(e=>Le(s.rows,e)),_=g.find(e=>e===`ET`)??g[0];T(()=>a.set(e=>({...e,worksheets:e.worksheets.map(e=>Y1(!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 UE(`not_found`,{datasetId:e});return{get rawText(){return t.kind===`memory`&&t.fromColumns?_$(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=Nz(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=pe(e);if(!i)return null;let a=Nz(i.rows,e);return Number.isFinite(a.min)&&Number.isFinite(a.max)?a:null}},pe=(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=NE(n.merged,n.channels,t);return{...n.merged,columnNames:[...n.merged.columnNames,...r.ok.map(e=>e.name)],rows:r.rows}},me=(e,t,n)=>h().selectedLive.length>0?{...n,scaleMin:``,scaleMax:``,majorStep:``,minorStep:``}:q1(pe(e,t),e,n),he={fromFileList:e=>PV(Array.from(e)),async fromDataTransfer(e){return FV(Array.from(e.items??[]).map(e=>e.webkitGetAsEntry?.()).filter(e=>!!e))},canPick:IV,pick:LV,tree:(e,t)=>NV(e,t),isImportable:MV},ge={add(e=`Worksheet`){u();let t=f(),n=t.limits.maxWorksheets;n!==null&&t.worksheets.length>=n&&d(`worksheets`);let r={...U1(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 UE(`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=>Y1({...e,xKey:t},e=>e!==t)),a.set(t=>({...t,xRanges:{...t.xRanges,[e]:null},offsets:{}}))}},_e={mount(e,t,n){return u(),FQ(rt,e,t,n)},openWindow(e,t){u(),F(e);let n=F(e).panel.window;return a$(rt,e,(t,n)=>FQ(rt,e,t,n),{...n,...t})},recordWindows(){u();let e=s$(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),IQ(rt)},kinds:()=>x$,label:C$,add(e,t={}){if(u(),!x$.some(t=>t.kind===e))throw new UE(`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={...ln(e,n.panels),...t.title?{title:t.title}:{}};t.layout&&(i.rect={...t.layout});let a=gr([i],{},H1[2],4)[i.id],o=a,s=h().numericColumns;if(s.length&&(o.kind===`multiband`||o.kind===`xyscatter`||o.kind===`xyzmesh`)&&(o=J1({...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??me(o.xyXCol,n.xKey,o.xyXScale),xyYScale:e.xyYScale??me(o.xyYCol,n.xKey,o.xyYScale)}}return p(a,o),L(n.id,e=>({...e,panels:t.layout?[...e.panels,i]:dn([...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:dn(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:me(e.xyXCol,n.xKey,r.xyXScale)}),typeof e.xyYCol==`string`&&e.xyYCol!==r.xyYCol&&!(`xyYScale`in e)&&(i={...i,xyYScale:me(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 UE(`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=Gt({...t,id:t.id||crypto.randomUUID()});if(!n)throw new UE(`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 UE(`not_found`,{annotationId:t});let i=Gt({...r,...n,id:r.id,kind:r.kind});if(!i)throw new UE(`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=Kt(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:dn(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 UE(`invalid_argument`,{reason:`not a multiband chart`});let i=f().limits.maxChannelsPerChart;i!==null&&Pz(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=yr(),l={id:c,column:s,color:H1[r.series.length%H1.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 _e.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 UE(`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 _e.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 fe.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)}},ve=new Map,ye={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){ye.setXRange(null,e)},setCursorX(e,t){u();let n=P(t).id;(ve.get(n)??null)!==e&&(ve.set(n,e),o.emit(`cursorchange`,{worksheetId:n,x:e}))},cursorX(e){return ve.get(P(e).id)??null},setLiveWindow(e,t){u();let n=P(t);n.liveWindowSeconds!==e&&L(n.id,t=>({...t,liveWindowSeconds:e}))}},be={save(e){u();let t=e.id??crypto.randomUUID(),[n]=GB([{...e,id:t,parentId:e.parentId??null}].concat(f().cycleRules.filter(e=>e.id!==t))).filter(e=>e.id===t);if(!n)throw new UE(`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))}))}},xe={create(e){u();let n=f(),r=n.limits.maxMathChannels;r!==null&&n.mathChannels.length>=r&&d(`math-channels`);let i=br(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 UE(`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 UE(`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 LE(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:()=>FE(f().mathChannels),preview(e,t){let n=h();return n.merged?hE(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}})}},Se=y$((e,t)=>[...e.flatMap(e=>e.kind===`camera`&&e.video?[VE({...e,video:e.video})]:[]),...t]),Ce=``;a.subscribe(()=>{let e=Se(f().live,f().video),t=e.map(e=>`${e.kind}:${e.id}:${e.recordingId??``}:${e.name}`).join(`|`);t!==Ce&&(Ce=t,o.emit(`videochange`,{sources:e}))});let we=(e,t,n)=>e.id===t&&(n===void 0||(e.recordingId??null)===n),Te={sources:()=>Se(f().live,f().video),register(e){u(),a.set(t=>({...t,video:[...t.video.filter(t=>!we(t,e.id,e.recordingId??null)),e]}))},unregister(e,t){u(),a.set(n=>n.video.some(n=>we(n,e,t))?{...n,video:n.video.filter(n=>!we(n,e,t))}:n)}},Ee={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))}},De=()=>{f().limits.canImportExportWorkspaces||d(`workspaces-io`)},Oe=async e=>{if(e instanceof Blob)try{return JSON.parse(await e.text())}catch{throw new UE(`bad_file`)}if(typeof e==`string`)try{return JSON.parse(e)}catch{throw new UE(`bad_file`)}return e},ke=async e=>e instanceof File?e:new File([JSON.stringify(await Oe(e))],`import.json`,{type:`application/json`}),Ae=e=>e.replace(/[^\w.-]+/g,`_`),je=e=>new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),Me=e=>{let t=hr(e.panelChartSettings,H1[2],4),n={};for(let r of e.panels)t[r.id]?.kind===r.kind&&(n[r.id]=t[r.id]);return{...e,panelChartSettings:gr(e.panels,n,H1[2],4)}},Ne=(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??{})}}),Pe=()=>new Set(f().worksheets.flatMap(e=>[e.id,...e.panels.map(e=>e.id)])),Fe=(e,t=0)=>{let n=f().limits.maxWorksheets,r=Ne((n===null?e:e.slice(0,Math.max(1,n))).map(Me),new Set),i=r[Math.min(t,r.length-1)];a.set(e=>({...e,worksheets:r,activeWorksheetId:i.id,xRanges:{}}))},Ie=(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&&Pz(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:dn([...t.panels,o]),panelChartSettings:{...t.panelChartSettings,[a]:e.settings},panelChartBackgrounds:e.background===null?t.panelChartBackgrounds:{...t.panelChartBackgrounds,[a]:e.background}})),a},Re=()=>{let e=f();return gV({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})},ze=e=>{if(e.worksheets.length===0)throw new UE(`bad_workspace`,{errors:e.errors});let{channels:t,rename:n}=W1(f().mathChannels,e.mathChannels);Fe(n.size?e.worksheets.map(e=>G1(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)||fe.configure(e.id,{beacon:r}).catch(e=>o.emit(`error`,{error:e,context:`io.openWorkbook`}));return{worksheets:e.worksheets.length,errors:e.errors}},Be=e=>{if(e===null)return;let t=h().numericColumns,n=t.length?e.worksheets.map(e=>J1(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()},Ve={undo(){u(),Be(S.undo())},redo(){u(),Be(S.redo())},clear(){u(),j()}},He={hasWork:()=>DV(f().worksheets),exportWorksheet(e){u(),De();let t=P(e),n=_V(t);return{json:n,blob:je(n),filename:`${Ae(t.name||`worksheet`)}.kymosh`}},exportChart(e){u(),De();let{ws:t,panel:n}=F(e),r=vV(n,t.panelChartSettings[e],t.panelChartBackgrounds[e]??null);return{json:r,blob:je(r),filename:`${Ae(n.title?.trim()||n.kind)}.json`}},parseFile:e=>AV(e),exportWorkspace(){u(),De();let e=Re();return{json:e,blob:je(e),filename:`kymoscope-workspace-${new Date().toISOString().slice(0,10)}.json`}},async exportWorkspaceEncrypted(e){u(),De();let t=typeof e==`string`?await oV(Re(),e):await sV(Re(),e);return{json:t,blob:je(t),filename:`kymoscope-workbook-${new Date().toISOString().slice(0,10)}.kymo`}},async importWorkspace(e,t={}){u(),De();let n=await Oe(e);return cV(n)&&(n=await dV(n,t)),M(()=>ze(EV(n)))},toWorkbook:Re,openWorkbook(e){return u(),M(()=>ze(EV(e)))},async importWorksheet(e){u(),De();let t=f();t.limits.maxWorksheets!==null&&t.worksheets.length>=t.limits.maxWorksheets&&d(`worksheets`);let n=await AV(await ke(e));if(n.type!==`worksheet`)throw new UE(`bad_file`,{found:n.type});let[r]=Ne([Me(n.worksheet)],Pe());return a.set(e=>({...e,worksheets:[...e.worksheets,r],activeWorksheetId:r.id})),r.id},async importChart(e,t){u(),De();let n=await AV(await ke(e));if(n.type!==`chart`)throw new UE(`bad_file`,{found:n.type});return Ie(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(Me):[U1()];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(()=>{oe(f().datasets.map(e=>e.id));let e=U1();a.set(t=>({...t,worksheets:[e],activeWorksheetId:e.id,xRanges:{},offsets:{},colors:{},mathChannels:t.mathChannels.filter(e=>e.source!==`workbook`)}))})}},Ue={merged(e){let t=h();if(!t.merged||t.channels.length===0)return t.merged;let n=NE(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}},We=typeof location<`u`?location.hostname:``,Ge=t.license,Ke=t.licenseKey,qe=!1,Je={},Ye=e=>{r||a.set(t=>({...t,licensed:e}))},Ze=(e,t,n)=>{clearTimeout(Je[e]);let r=Math.max(0,t-Date.now()),i=r>2**31-1;Je[e]=setTimeout(()=>{i?Ze(e,t,n):n()},i?2**31-1:r)},Qe=e=>Ze(`renew`,e,()=>void et()),$e=e=>Ze(`expiry`,e*1e3+1e3,()=>{UV(Ke,We).then(e=>{r||Ye(e.ok)})});async function et(){let e=36e5,t,n=null,i;try{t=await Promise.race([Ge.get(),new Promise((e,t)=>{i=setTimeout(()=>t(Error(`timeout`)),3e4)})]),n=await UV(t,We)}catch{}finally{clearTimeout(i)}if(r)return!1;if(n?.ok)return Ke=t,qe=!0,Ye(!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 UV(Ke,We);return r?!1:(Ye(a.ok),Qe(Date.now()+e),a.ok)}let tt=!Ge||t.licenseKey?UV(t.licenseKey,We).then(e=>(e.ok||console.warn(`[kymoscope] license ${e.reason}: showing attribution`),!qe&&!r&&(Ye(e.ok),e.ok&&Ge&&$e(e.exp)),e.ok)):null,nt=Ge?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:fe,folders:he,worksheets:ge,charts:_e,view:ye,mathChannels:xe,cycles:be,live:Ee,video:Te,io:He,history:Ve,data:Ue,alerts:{setRules:e=>{u();let t=ce.setRules(e);return a.set(e=>({...e,alertRules:ce.rules()})),t},rules:ce.rules,state:ce.state,evaluate:(e,t)=>(u(),ce.evaluate(e,t)),clearMarks:ce.clearMarks},marks:{list:()=>f().marks},dispose(){if(!r){r=!0,clearTimeout(Je.renew),clearTimeout(Je.expiry),c(),o$(rt),LQ(rt),V.dispose();for(let e of f().datasets)e.source.dispose().catch(()=>void 0);o.emit(`dispose`,void 0),o.clear()}}};return Q1.set(rt,{store:a,derived:h,live:V,alertLines:()=>ue(f().alertRules,f().alerts)}),rt}var Q1=new WeakMap;function $1(e){let t=Q1.get(e);if(!t)throw new UE(`invalid_argument`,{reason:`not a Kymoscope engine`});return t}var e0=2e3,t0=3;function n0(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 r0(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=n0(a);e?r.push(e):t||(i=a),a=[]}t&&a.push(t)}return{head:t,units:r,tail:i}}var i0=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}=ce(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 ie(i,a,e=>s(this.open,e.slice().buffer),n).catch(()=>`broken`)})}for(let e of a){let t=null;try{t=await s(this.open,e.bytes.slice().buffer)}catch{}if(t?.kind!==6)continue;let n=H$(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=r0(r),c=e=>e.reduce((e,t)=>e+t.v.payload.length,0);return{...o,bytes:o.units.reduce((e,t)=>e+t.data.length,0)+c(o.head)+c(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=n0([...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<e0?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<t0;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,t0+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=Ce([...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}},a0=[60,300,900,1800,3600,7200,14400,28800,43200,86400],o0={60:`1m`,300:`5m`,900:`15m`,1800:`30m`,3600:`1h`,7200:`2h`,14400:`4h`,28800:`8h`,43200:`12h`,86400:`24h`};function s0(e){if(typeof e==`number`)return a0.includes(e)?e:null;if(typeof e!=`string`)return null;let t=Object.entries(o0).find(([,t])=>t===e.trim().toLowerCase());return t?Number(t[0]):null}var c0=e=>o0[e]??`${e}s`;function l0(e){for(let t=a0.length-1;t>=0;t--)if(a0[t]*e<=157286400)return a0[t];return a0[0]}function u0(e,t,n){let r=t*1e3,i=n*1e3;return Math.floor((e+i)/r)*r+r-i}var d0=1e4,f0=1e3,p0=72e4,m0=3e5,h0=3e4,g0=1e4,_0=1e4,v0=64*1024,y0=50,b0=[`360p`,`480p`,`720p`,`1080p`],x0=e=>e+6+(e>=126?2:0)+(e>65535?6:0);function S0(e,t){return t*x0(e+30)}var C0=e=>typeof e==`number`&&Number.isFinite(e)&&e>0,w0=e=>Number.isInteger(e)&&e>=1;function T0(e,t){if(!e||e.mode!==`live`&&e.mode!==`record`)return null;if(t===`camera`)return b0.includes(e.quality)&&Number.isInteger(e.fps)&&e.fps>=1&&e.fps<=60?{mode:e.mode,quality:e.quality,fps:e.fps}:null;if(!C0(e.bytes_per_sec))return null;let n=e.bytes_per_sec,r={};if(e.mode===`record`){let t=e.splitEvery===void 0?l0(n):s0(e.splitEvery);if(t===null)return null;r={split_every:t}}return e.sources===void 0?C0(e.hz)&&w0(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=>C0(e?.hz)&&w0(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 E0=class extends Error{status;code;detail;constructor(e,t,n){super(`${n} (${t})`),this.status=e,this.code=t,this.detail=n}};async function D0(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 E0(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 E0(a.status,s?.error??`error`,s?.message??s?.error??o);return s}async function O0(e,t,n=fetch){let{auth:r}=se(t),{token:i}=await D0(n,e,`stream-token`,{"x-api-key":r}),a=await D0(n,e,`stream-publisher`,{Authorization:`Bearer ${i}`,"Content-Type":`application/json`},{action:`usage`});return{limits:a.limits??{},usage:a.usage}}var k0=e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0)),A0=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=v0;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}=se(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=T0(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`?I: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 e=await this.deps.store.load();this.salt=e?.salt??he();let t=await this.mint();this.token=t.token,this.relayUrl=t.relayUrl??null,this.maxBytesPerSec=t.maxBytesPerSec||0,this.maxMessageBytes=t.maxMessageBytes||v0,this.apiKeyId=t.apiKeyId??null;let n=t.project;this.e2ee=!!n?.e2ee;let r={};if(this.e2ee){this.projectId=n?.id??null;let t=e?.apiKeyId===this.apiKeyId;this.device=t&&e?.device||await O(),t&&e?.streamKey?{key:this.key,epoch:this.epoch,sealed:this.sealed}=e.streamKey:this.key=await Re(tt()),r.sender_device=await this.senderDevice()}else this.raw=k0(await ee(this.password,this.salt)),this.key=await Re(this.raw),this.gen=e?.keyGen??0;let i=await this.register(e?.streamId??null,r);if(this.sid=i.stream.id,this.ticket=i.ticket,this.admitted(i),this.e2ee?(this.senderDeviceId=i.sender_device_id??null,this.projectId=i.project?.id??this.projectId,await this.save(),await this.applyProject(i.project)):(await this.save(),await this.wrapFor(i.devices)),!this.relayUrl)throw Error(`stream-token returned no relayUrl`)}catch(e){throw e instanceof E0&&e.status>=400&&e.status<500&&this.refuse(e),e}this.stopped||(this.lastToken=this.deps.now(),this.connect(),this.heartbeatTimer=setInterval(()=>{this.housekeeping()},d0),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 w(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 xe(t,oe(),0),at:n});let r=this.chain;r.lane.add(e),!(n-r.at<f0)&&(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 D0(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 Je(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 lt(await rt(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>=p0){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 E0&&(e.status===401||e.status===403)&&this.refuse(e)}finally{this.busy=!1}}}async rekey(){let e=he(),t=k0(await ee(this.password,e)),n=await Re(t),r;try{r=await this.register(this.sid,{},e,n)}catch{return}this.salt=e,this.key=n,this.raw=t,this.gen=this.gen%255+1,await this.save(),await this.wrapFor(r.devices)}async wrapFor(e){let t=[];for(let n of e??[])try{t.push({device_id:n.id,wrapped:await T(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,y0)})}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 N(this.device.privateKey,t.wrapped,Me(this.projectId,n,this.senderDeviceId))}catch{if(this.deviceRetried)return;this.deviceRetried=!0,this.device=await O(),await this.reregister();return}let i=st(this.sid,this.projectId,n),a=this.key,o=n===this.epoch?this.sealed:null;if(o)try{await Te(r,o,i)}catch{o=null}if(!o){let e=tt();a=await Re(e),o=await Se(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`,[w$,`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{}},h0),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>=_0;if(this.disconnect(),this.stopped)return;let t=0;e?this.delay=1e3:(t=this.delay,this.delay=Math.min(this.delay*2,g0)),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<m0))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)}}},j0={"360p":{width:640,height:360},"480p":{width:854,height:480},"720p":{width:1280,height:720},"1080p":{width:1920,height:1080}},M0={width:640,height:360,fps:15,kbps:400},N0=[`avc1.640028`,`avc1.4d0028`,`avc1.42e028`],P0=[`avc1.64001f`,`avc1.4d001f`,`avc1.42e01f`],F0=2,I0=1e3,L0=1e3;async function*R0(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 z0(){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 B0=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?N0:P0){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>F0?(this.dropped++,!1):!0}encode(e){let t=this.now(),n=t-this.lastKey,r=this.resume||n>=this.keyframeMs||this.keyPending&&n>=I0;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=U$({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>=L0;)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()}},V0=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?j0[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??R0,this.scale=n.scale??z0(),this.high=new B0(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??M0}: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 UE(`camera_codec_unsupported`);if(this.lowOpt){let e=new B0(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<L0||!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()}},H0=new TextEncoder,U0={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`},W0=new Set([`authorization`,`content-type`,`content-length`,`user-agent`,`presigned-expires`,`expect`,`x-amzn-trace-id`,`range`,`connection`]),G0=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 K0(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`)}},K0=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]=Q0(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||!W0.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=Z0(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=>Z0(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 q0(await q0(await q0(await q0(`AWS4`+this.secretAccessKey,e),this.region),this.service),`aws4_request`),this.cache.set(t,n)),X0(await q0(n,await this.stringToSign()))}async stringToSign(){return[`AWS4-HMAC-SHA256`,this.datetime,this.credentialString,X0(await J0(await this.canonicalString()))].join(`
612
+ `),j=Ct(()=>{let e=i.filter(e=>e.kind!==`memory`).flatMap(e=>_V(e.schema));return e.length?e:null},[i]),M=Ct(()=>i.some(e=>e.kind!==`memory`)||!_&&i.some(e=>e.data.rows.length>NQ),[i,_]),N=Ct(()=>mQ(f.connections.filter(e=>r.includes(e.id)),i.length,M,d,o),[M,i,f.connections,r,o,d]),P=Ct(()=>{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 HQ(e,d)},[_,i,M,O,o,d,f.connections,r,N]),F=C&&`okByPart`in C?C.okByPart:void 0,I=Ct(()=>{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:zQ(i,r,d),columnSet:new Set([d,...r]),key:`${e[n].key}|channels`})}),e},[M,T,E,o,F,O,d]),L=Ct(()=>{let e=C?.parts??(w?[w]:[]),t=new Set;for(let n of e)for(let e of _Q(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=Ct(()=>{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=Ct(()=>{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,NQ));else{let e=Math.max(1,Math.floor(NQ/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=Ct(()=>{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=>VQ(e,i),l;if(!E)l=a(r);else{let e=a(r);l=[];for(let t=0;t<T.length;t++){let n=WV(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=dQ(f.flatMap((t,n)=>{let r=t.cols.get(`${e.column}__${n}`);return r?[{x:t.x,y:r}]:[]}),LQ);return t?[{seriesId:e.id,color:e.color,...t}]:[]}):void 0,m=T.flatMap((e,t)=>`bands`in e&&e.bands?DQ(e,d,r,E?WV(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=Ct(()=>{let e={pts:{},colorMeta:{},datasetColors:{}};if(!w)return e;let t={},r={},i={},a=IQ,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}=uK(o,l,p,{xKey:d,viewXRange:n,colorOverrides:s,palette:c});t[e.id]=r,i[e.id]=a;continue}let m=lK(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=Ct(()=>{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=rK(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=rK(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?rK(r,s,i):void 0,p=c?rK(r,c,i):void 0,m=l?rK(r,l,i):void 0;if(!f||!p||!m){e[a.id]={points:t};continue}let h=n?rK(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=Ct(()=>{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&&iK(w.rows,n.histColumn,D)||new Float64Array}return e},[w,l,u,D]),ne=Ct(()=>{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?rK(w.rows,n.polarAngleCol,D):void 0,i=n?.kind===`polar`&&n.polarRadiusCol?rK(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&&iK(e,t,D)||new Float64Array,a=n?rK(e,n,D):void 0;return{signal:i,rate:a&&oK(a)||parseFloat(r)||1}},ie=Ct(()=>{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=Ct(()=>{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?aK(w.rows,n.boxValueCol,n.boxGroupCol||void 0,D):[]}return e},[w,l,u,D]),ae=Ct(()=>{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=Ct(()=>{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=rK(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=rK(r,d,D),s,c;if(n.hmSpacing===`values`){o&&bY(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&&bY(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]=AQ(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);bY(e)&&(f=e),bY(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=Ct(()=>{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?aK(w.rows,n.vlValueCol,n.vlGroupCol||void 0,D):[]}return e},[w,l,u,D]),ce=Ct(()=>{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=Ct(()=>{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?rK(w.rows,n.rocScoreCol,D):void 0,i=n?.kind===`roc`&&n.rocLabelCol?rK(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=Ct(()=>{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:rK(t,e,D)??new Float64Array,axis:r})),c=s[0]?.values.length??t.length,l=i&&rK(t,i,D)||Float64Array.from({length:c},(e,t)=>t);e[n.id]={xValues:l,series:s}}return e},[w,l,u,D]),de=Ct(()=>{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?rK(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=Ct(()=>{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=>rK(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=rK(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=Ct(()=>{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=rK(t,a,D),f=rK(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=rK(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=Ct(()=>{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=Ct(()=>{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=>rK(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=Ct(()=>{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=>rK(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=Ct(()=>{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=>rK(r,e,D)),a=i[0]?.length??r.length,o=(n.acXCol?rK(r,n.acXCol,D):void 0)??KQ(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=Ct(()=>{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:iK(w.rows,e,D)??new Float64Array}))}return e},[w,l,u,D]),ye=Ct(()=>{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=rK(t,i.bbXCol,D),o=rK(t,i.bbYCol,D),s=rK(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=rK(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=Ct(()=>{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=Ct(()=>{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=Ct(()=>{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?rK(w.rows,n.cbScoreCol,D):void 0,i=n?.kind===`calibration`&&n.cbLabelCol?rK(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=Ct(()=>{let e={};if(!w)return e;let t={length:0,theoretical:[],sample:[]},n=e=>{let t=iK(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=Ct(()=>{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=Ct(()=>w?UQ(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:Ct(()=>{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?rK(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]=JQ(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 JQ(e,t,n,r){t<=e&&(t=e+1);let i=bV(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 YQ=`#fb7185`,XQ=2500;function ZQ(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 QQ(e){let t=$Q(e);if(t.status!==`empty`||!e.data.dataset)return t;let n=new Set([...e.data.datasetWithChannels?.columnNames??[],...e.data.numericCols]);return ZQ(e.settings).some(e=>!n.has(e))?{...t,status:`missing`}:t}function $Q(e){let{panel:t,data:r,settings:i}=e;if(t.kind===`camera`)return{status:`ready`,data:null,node:q(eQ,{settings:i?.kind===`camera`?i:er(),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??[],f=i?.kind===`multiband`?i:null,p=[...new Set((f?.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:f?.xAxisLine,yAxisLine:f?.yAxisLine,gridLine:f?.gridLine,lineWidth:f?.lineWidth,onPlotContextMenu:o,shiftMode:e.shiftMode},g=f?.beacon;if(g?.enabled&&e.beaconLive&&p.length>0){let t=VQ((f?.series??[]).filter(t=>t.column!==e.xKey),f?.layout??`overlay`),n=g.reference===`dataset`&&g.datasetId?e.findDataset(g.datasetId):void 0,r=EQ(g,!!n),i=r?[...bQ(t,r),...t]:t;return s(q(NG,{...h,series:i,points:[],showLatestValues:!0,liveSource:TQ(e.beaconLive,e.xKey,p,g,n),envelopes:n?DQ(n,e.xKey,t,r??void 0):void 0,liveZoomMode:`free`}),{series:i,points:[]})}if(r.anyDuckDb)return u.length===0?c:s(q(eK,{...h,layers:r.duckDbLayers,xKey:e.xKey,columns:p,maxPoints:XQ}),{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?hQ(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:ut(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=d(v.pts,i);if(e.xKey!==`ElapsedTime`)return[s];let c=ut(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(NG,{...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:Dn(4),n=r.xyzPointsByPanel[l];if(!n||n.points.length<1&&!n.surface)return c;let u=!!n.surface;return s(q(iJ,{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:xn(t.xyzXScale.scaleMin,t.xyzXScale.scaleMax),yRange:xn(t.xyzYScale.scaleMin,t.xyzYScale.scaleMax),zRange:xn(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:En(YQ),n=r.xyPointsByPanel.pts[l]??[];if(n.length===0)return c;let u=r.xyPointsByPanel.colorMeta[l];return s(q(KK,{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(dJ,{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(kJ,{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(GJ,{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(ZJ,{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(hY,{signal:e,sampleRate:t,windowSize:i.sgWindowSize,overlap:i.sgOverlap,winFunc:i.sgWinFunc,yMode:i.sgYMode,backgroundToken:a,onPlotContextMenu:o}),e):s(q(uY,{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(PY,{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(HY,{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(YY,{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(tX,{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(rX,{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(lX,{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(hX,{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(TX,{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(NX,{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(zX,{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(UX,{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(qX,{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(XX,{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(iZ,{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(lZ,{nodes:e,backgroundToken:a,onPlotContextMenu:o}),e)}case`sankey`:{let e=r.sankeyDataByPanel[l]??{nodeNames:[],links:[]};return e.links.length===0?c:s(q(hZ,{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(_Z,{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(yZ,{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(PZ,{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(wZ,{tasks:e,backgroundToken:a,onPlotContextMenu:o}),e)}}return c}var e$=500,t$=1e3;function n$(e){if(Array.isArray(e))return r$(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,r$(n)));return t<0?null:t}function r$(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 i$(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 a$({stats:e,host:t}){let[n,r]=wt(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?qU(t.current):0,d=f=>{c>=0&&f-s>t$&&(c=f,s=f,a=0,o=0,l=e.renders,u=t.current?qU(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>=e$){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?qU(i):0;r({fps:a*1e3/p,repaints:(m-u)*1e3/p,worstFrameMs:o,renderMs:e.lastRenderMs,rendersPerSec:(e.renders-l)*1e3/p,points:n$(e.data),domNodes:i?i.getElementsByTagName(`*`).length:0,canvasMp:s/1e6,heapMb:d?d.usedJSHeapSize/1048576:null,live:(()=>{let e=vW();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:o$,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`,i$(n.points)]],[`DOM nodes`,i$(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])=>kt(`div`,{style:s$,children:[q(`dt`,{style:c$,children:e}),q(`dd`,{style:n?{...l$,color:n}:l$,children:t})]},e))})}var o$={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)`},s$={display:`flex`,justifyContent:`space-between`,gap:12},c$={color:`var(--text-muted, #8a93a6)`},l$={margin:0,fontWeight:600,textAlign:`right`},u$=[],d$=3,f$=`data-kymo-annotation-controls`;function p$(e,t,n,r){return e.anchor===`x`&&!r?null:e.points.map(([i,a])=>[e.anchor===`x`?PW(r,i):i*t,a*n])}function m$(e,t,n,r,i){return t.map(([t,a])=>[e.anchor===`x`&&i?FW(i,t):h$(t/Math.max(1,n)),h$(a/Math.max(1,r))])}var h$=e=>Math.round(e*1e4)/1e4,g$=vt(function({annotations:e,tool:t,plotFrame:n,onChange:r,onToolEnd:i,onSelect:a,marks:o=u$,onMarkSelect:s}){let c=K(null),l=Tt(n.subscribe,n.get),u=l?.x?l:null,[d,f]=wt({w:0,h:0}),[p,m]=wt(null),[h,g]=wt(null),[_,v]=wt(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||T$(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=>m$(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)>d$,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=p$(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)<=d$)return;let{size:c,frame:l}=y.current;a={...t,points:m$(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(w$(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=p$(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=p$(Yt(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`?C$(F.px):null,R=e=>kt(Ot,{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(y$,{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 kt(`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(v$,{initial:e.text??``,onDone:M}):e.text,p===e.id&&e.kind===`text`&&!n?q(_$,{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?kt(Ot,{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})=>kt(`g`,{"data-mark":e.ruleId,role:`img`,"aria-label":`${e.late?`Late · `:``}${e.ruleName}, ${e.severity}`,className:`kymo-mark kymo-mark--${e.severity}${e.late?` kymo-mark--late`:``}`,style:{color:Jt[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,kt(`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:b$(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(_$,{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 _$({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 v$({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 y$({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 kt(Ot,{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=S$(i,a,o,s,e.width);return kt(Ot,{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=x$(t);return kt(Ot,{children:[r(e),q(`path`,{d:e,...n})]})}}return null}function b$(e,t){if(e.kind===`arrow`)return t;let[[n,r],[i,a]]=t;return[[n,r],[i,r],[i,a],[n,a]]}function x$(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 S$(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 C$(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 w$(e,t){if(t)return{...e,text:t};let{text:n,...r}=e;return r}function T$(e){let t=e;return!!t&&(t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))}function E$(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=p$(i,n,r,o);t&&(e.save(),i.anchor===`x`&&o&&(e.beginPath(),e.rect(o.left,0,o.width,r),e.clip()),D$(e,i,t,a),e.restore())}e.restore()}function D$(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(x$(n)));else if(t.kind===`arrow`){let r=S$(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 O$={solid:void 0,dashed:`5 4`,dotted:`1 4`};function k$(e,t,n){if(!e||!(n===`x`?e.x:e.y))return null;if(n===`x`){let n=PW(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=IW(e,t.value);return r>=e.top-.5&&r<=e.top+e.height+.5?[e.left,r,e.left+e.width,r]:null}var A$=vt(function({frame:e,alarm:t,axis:n}){let r=k$(Tt(e.subscribe,e.get),t,n);if(!r)return null;let i=t.linked?j$(r,n):null;return kt(`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`?UW.join(` `):O$[t.style]}),i?q(`path`,{"data-alert-glyph":``,d:HW,transform:`translate(${i[0]} ${i[1]})`,fill:t.color}):null]})});function j$(e,t){return t===`y`?[e[2]-10-3,e[1]-10-2]:[e[0]+3,e[1]+2]}function M$(e,t,n,r,i){let a=k$(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`?UW:O$[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=j$(a,r);GW(e,t[0],t[1],n.color)}e.restore()}}function N$(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,R$(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 P$=new WeakMap;function F$(e,t){let n=P$.get(e);n||P$.set(e,n=new Map);let r=n.get(t);return r||n.set(t,r=n=>e.view.setLiveWindow(n,t)),r}var I$=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=Dt(document.createElement(`div`)),this.root.render(q(W$,{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}},L$=new WeakMap;function R$(e){let t=L$.get(e);return t||(t=new I$(e),L$.set(e,t)),t}function z$(e,t,n,r={}){e.charts.get(t);let i=R$(e),a={key:crypto.randomUUID(),chartId:t,element:n,options:r,shiftDatasetId:null,emitter:ZH(),xyz:null,annotationTool:null,selectedAnnotation:null,plotFrame:zW(),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 OO(`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 OO(`export_failed`,{reason:`canvas unavailable`}));for(let e of r)o.drawImage(e,0,0);let s=e.charts.get(t),c=e1(s.settings,r2(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=r1(s.annotations,d?t1(u.marks,u.selection,d.xKey):[],l),p=pr(c);return p&&n.clientWidth>0&&M$(o,a.plotFrame.get(),p.alarm,p.axis,i.width/n.clientWidth),f.length&&n.clientWidth>0&&E$(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 OO(`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 B$(e){L$.get(e)?.refresh()}function V$(e){L$.get(e)?.dispose(),L$.delete(e)}function H$(e){let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-color-scheme`,`class`,`data-theme`]}),()=>t.disconnect()}var U$=()=>{let e=document.documentElement;return`${e.getAttribute(`data-color-scheme`)??``}|${e.getAttribute(`data-theme`)??``}|${e.className}`};function W$({engine:e,registry:t}){Tt(t.subscribe,t.getVersion);let n=r2(e),r=Tt(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(Ot,{children:[...i.values()].map(t=>q(J$,{engine:e,worksheet:t.worksheet,mounts:t.mounts},t.worksheet.id))})}var G$=1e3,K$=.25;function q$(e,t,n,r){let[i,a]=wt(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=UU(u),o.current||n<l||JU()||!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/K$-1),o.current=performance.now(),yt(()=>a(e=>e+1)))};return i=UU(u),()=>WU(i)},[n,e,t]),Ct(()=>n?e.map(e=>t.includes(e.id)?{...e,dataset:e.source.snapshot(G$)}:e):e,[e,t,n,i])}function J$({engine:e,worksheet:t,mounts:n}){let r=r2(e),i=Tt(r.store.subscribe,r.store.get),a=r.derived(),o=i.xRanges[t.id]??null,s=Ct(()=>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=q$(s,i.selection,u,f),m=r.alertLines(),h=qQ({worksheet:Q$(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(YH()).current,_=Tt(H$,U$),v=t.id,y=F$(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(Ot,{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=N$(n,e,v),l=e1(t.panelChartSettings[r.id],m);return Et(q(s1,{mount:n,annotations:t.panelChartSettings[r.id]?.annotations,marks:t1(i.marks,i.selection,t.xKey),onMarkSelect:c.onMarkSelect,alarm:pr(l),onAnnotations:c.onAnnotations,onAnnotationToolEnd:c.onAnnotationToolEnd,onAnnotationSelect:c.onAnnotationSelect,render:u=>QQ({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:ZZ(a.selectedDatasets,i.offsets),shiftMode:s?Y$(e,s.id,s.name):void 0,onContextMenu:c.onContextMenu,xyzRef:c.xyzRef}),licensed:b},n.key),n.element,n.key)})})}function Y$(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 X$=[],Z$=new WeakMap;function Q$(e,t){if(!t.size)return e;let n=Z$.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]=e1(a,t),i[n]!==a&&(r=!0);let a=r?{...e,panelChartSettings:i}:e;return Z$.set(e,{lines:t,out:a}),a}var $$=new WeakMap;function e1(e,t){if(!e||!t.size)return e;let n=$$.get(e);if(n&&n.lines===t)return n.out;let r=dr(e,t);return $$.set(e,{lines:t,out:r}),r}var t1=i1((e,t,n)=>{let r=e.filter(e=>e.timeColumn===n&&t.includes(e.targetId));return r.length?r:n1}),n1=[];function r1(e,t,n){return!t.length||!n?.x?e:[...t.map(e=>Yt(e,n.x.v1)),...e]}function i1(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 a1(e,t){e.data=t}function o1(e,t){e.status!==t&&(e.status=t,e.emitter.emit(`status`,t))}function s1({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]=wt(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 YU(t);return n.observe(e),()=>n.disconnect()},[]);let{status:h,node:g,data:_}=t(d||400);m.data=_,W(()=>{a1(e,_)}),W(()=>{o1(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),kt(`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(BW.Provider,{value:e.plotFrame.set,children:g}),h===`ready`&&a?q(A$,{frame:e.plotFrame,alarm:a.alarm,axis:a.axis}):null,h===`ready`&&(r?.length||e.annotationTool||i.length)?q(g$,{annotations:r??X$,tool:e.annotationTool,plotFrame:e.plotFrame,onChange:o,onToolEnd:s,onSelect:c,marks:i,onMarkSelect:l}):null,p?q(a$,{stats:m,host:u}):null,n===!1?q(XH,{}):null]})}var c1=new WeakMap;function l1(e,t,n,r={}){let i=c1.get(e)??new Map;c1.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 OO(`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),LU(l);let h=n(m,r.mount),g=ZH(),_=!1,v=()=>{_||(_=!0,i.delete(t),RU(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 u1(e){for(let t of[...c1.get(e)?.values()??[]])t.close()}function d1(e){let t=new Map;for(let[n,r]of c1.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 f1=12e3,p1=100;function m1(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 A.add(n),n;for(let e=0;e<n.length;e++){let t=n[e];t-t!==0&&(n[e]=NaN)}return n}function h1(e,t){let n=Object.keys(t.columns);if(n.length===0)throw new OO(`no_columns`);let r=t.columns[n[0]].length;if(n.some(e=>t.columns[e].length!==r))throw new OO(`column_length_mismatch`);let i=new Map(n.map(e=>[e,m1(t.columns[e],t.transfer)])),a=g1(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 OO(`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 g1(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,p1);t++)e.push(o.map(e=>{let r=n.get(e)[t];return r===r?String(r):``}).join(`,`));d=e.join(`
615
+ `),f=Be(d)}let p={id:e,name:t,schema:l,rawText:d,parseConfig:f,fromColumns:!0};if(s>1e6){let e=new OQ(n,r);return{...p,kind:`columnar`,source:e,data:{meta:``,columnNames:o,units:c,rows:e.sampleRowsSync(f1)}}}let m={meta:``,columnNames:o,units:c,rows:Pe({keys:o,length:s,values:o.map(e=>n.get(e)),text:o.map(()=>null)},i)};return{...p,kind:`memory`,source:new IO(m),data:m}}function _1(e,t,n){let r=e.fromColumns?v1(e):null;if(!r)throw new OO(`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)?(Qe(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{...y1(e,o,!0),columnSpares:s}}function v1(e){if(e.source instanceof OQ)return new Map(e.source.columnMap);let t=Ue(e.data.rows);return t?new Map(t.keys.map((e,n)=>[e,t.values[n]])):null}function y1(e,t,n=!1){let r=e.fromColumns?v1(e):null;if(!r)throw new OO(`invalid_argument`,{reason:`only datasets added with addColumns can be replaced`});let i=r;for(let e of Object.keys(t))i.set(e,m1(t[e],n));let a=i.values().next().value.length;for(let e of i.values())if(e.length!==a)throw new OO(`column_length_mismatch`);let o=Object.fromEntries(e.schema.map(e=>[e.name,e.unit])),s=g1(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 b1=new WeakMap;function x1(e){let t=e.fromColumns?v1(e):null;if(!t)return e.rawText??``;let n=e.data.rows,r=b1.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(`,`));b1.set(n,r=a.join(`
616
+ `))}return r}function S1(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 C1(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 w1(){let e=C1(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?bD(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=$V(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:sH(n.id,t),name:`${n.name} · Cycle ${t+1}`,data:r,source:new IO(r)}}),values:a.map(e=>rH(n.data.rows,e,r,i)),unit:o,isTime:i===`span`&&aH(r,o)}}return t}),t=C1((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=C1((e,t)=>e.filter(e=>e.kind===`data`&&t.includes(e.id))),r=C1(e=>pQ(e.map(e=>e.data))),i=C1((e,t)=>t.length===0?e:pQ(e?[e,...t.map(e=>e.dataset)]:t.map(e=>e.dataset))),a=C1((e,t,n,r)=>{let i=new Set;if(e)for(let t of n.length>0?n:[e])for(let e of _Q(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=>_V(e.schema));return[...new Set([...a,...o])]});return{lapsByDataset:e,selectedDatasets:t,selectedLive:n,staticDataset:r,mergedDataset:i,mergedParts:C1((e,t)=>[...e.map(e=>e.data),...t.map(e=>e.dataset)]),numericColumns:C1((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:C1((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:C1((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 T1=[{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`}],E1=new Map(T1.map(e=>[e.kind,e.label]));function D1(e){return E1.get(e)??e}var O1=`kymoscope-live.v1`,k1=`kymoscope-live.ack1`,A1=`kymoscope-live.ack2`,j1=1e3,M1=2e3,N1=3e4,P1=1e4,F1=30,I1=1e4,L1=300,R1=90,z1=e=>e.startsWith(`eyJ`);function B1(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 V1(e,t){return`${e.replace(/\/+$/,``)}/v1/streams/${t}/watch`}function H1(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=B1(r);if(a===null)return;let c=z1(r),d=c?Math.min(a,Date.now()/1e3+L1):a,f=Math.min(Math.max((d-(c?R1:F1))*1e3-Date.now(),I1),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(N1,M1*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(V1(e.url,t),[O1,k1,A1,`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}},j1);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>=P1)))}};return f(),()=>{if(s=!0,a&&=(clearTimeout(a),null),l(),i){let e=i;i=null,e.close(1e3)}}}var U1=960*1024,W1=24;function G1(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(W1+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=W1;return n&&(r[a++]=t.length,r.set(t,a),a+=t.length),r.set(e.payload,a),r}function K1(e){if(e.length<W1||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=W1,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 q1(e){let t=Math.max(1,Math.ceil(e.data.length/U1)),n=[];for(let r=0;r<t;r++)n.push(G1({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*U1,Math.min(e.data.length,(r+1)*U1))}));return n}function J1(e,t,n){let r=new Map,i=Promise.resolve(),o=n?ne(n,e=>t({type:`integrity`,integrity:e})):null;return Object.assign(n=>{let c=s(e,n).catch(()=>null);o?.arrive(n,new Uint8Array(n,0,1)[0]&127,c),i=i.then(async()=>{try{let e=await c;if(!e)return;if(e.kind===6){let n=K1(e.plaintext);n&&t({type:`video`,m:n})}else if(e.kind===5){let t=M(e.plaintext);r.set(t.id,t)}else if(e.kind===7){let n=a(e.plaintext,r);n&&t({type:`last`,values:n})}else if(e.kind===4){let n=await ot(e.plaintext,r);n&&t(n.historical?{type:`columns`,block:n.block,historical:!0}:{type:`columns`,block:n.block})}else if(e.kind===3)t({type:`columns`,block:it(e.plaintext)});else if(e.kind===2){let n=Oe(e.plaintext);t({type:`frames`,frames:Array.isArray(n?.frames)?n.frames:[]})}}catch{}})},{reset:()=>o?.reset()})}var Y1=``+new URL(`assets/liveIngestWorker-UV5D515-.js`,import.meta.url).href;function X1(e,t,n,r,i){let a=()=>{let a=J1(n,r,t);return H1(e,t,a,e=>{e===`subscribed`&&a.reset(),i?.(e)})},o;try{if(typeof Worker>`u`)return a();o=kO(Y1)}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 Z1=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}},Q1=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 $1(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 H(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(){}},$1=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)}},e0=4096,t0=5e3,n0=class{startedAt=Date.now();n=0;capacity=e0;time=new Float64Array(e0);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=x(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(r0).join(`,`)}\n${t.map(r0).join(`,`)}\n`],r=this.order.map(e=>this.cols.get(e));for(let e=0;e<this.n;e+=t0){let t=Math.min(this.n,e+t0),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 r0(e){let t=/^[=+\-@\t\r]/.test(e)?`'${e}`:e;return/[",\n\r]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var i0=512,a0=new WeakMap;function o0(e,t,n){let r=a0.get(e);r||a0.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 s0(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=fE(r.formula);if(!s.ok)continue;let{identifiers:c,functions:l}=pE(s.node);if(!c.every(e=>o.has(e)))continue;let u=l.some(e=>uE.includes(e)),d=Math.max(e.firstAbs,a-(u?i0:0)),f=new Map([n,...c].map(t=>[t,e.range(t,d,i)])),{carry:p,keep:m}=o0(e,`${r.id}|${r.formula}`,d),h=yE(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 c0(e,t){e.clearComputed(),a0.delete(e),s0(e,t,e.firstAbs)}var l0=8e3,u0=131072;function d0(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 f0=new Map;function p0(e,t){let n=`${t}|${Math.floor(e/900)}`,r=f0.get(n);r===void 0&&(r=$E(e,t),f0.size>1e4&&f0.clear(),f0.set(n,r));let i=(e+r)%86400;return i<0?i+86400:i}var m0=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`?p0(e,n.tz):n.kind===`elapsed`?e-this.#e:e<this.#e?NaN:n.kind===`event`?(this.#t!==this.#t&&t===t&&JE(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 h0(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&&JE(r.op,o,r.value)&&(a=e[t])}return{x:e.map(e=>e-a),t:e,cols:t}}let a=new m0(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 g0(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 _0(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 v0(e,t,n){let r=Math.max(2,Math.min(l0,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=g0(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 y0(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 b0=new WeakMap;function x0(e){let t=b0.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 b0.set(e,t),t}function S0(e,t,n){if(n===`minmax`)return{lo:e.min,hi:e.max};if(n===`sigma`){let n=x0(e);return{lo:e.mean.map((e,r)=>e-t*n[r]),hi:e.mean.map((e,r)=>e+t*n[r])}}let r=y0(n,e);return{lo:e.mean.map(e=>e-r),hi:e.mean.map(e=>e+r)}}function C0(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:_}=S0(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(y0(h,i),1e-9):0,C=x0(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=_0(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<_0(t.x,g,s)||a>_0(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 w0(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 ge(new Uint8Array(i.buffer))}function T0(e,t){let n=de(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 E0(e){if(!e.cycle)throw Error(`a live segment axis needs a cycle rule`);let t=new cD(e.cycle),r=new m0(e.axis),i=NaN,a=`channel`in e.axis?e.axis.channel:null,o=[...new Set([...sD(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 D0=1e7;function O0(e=globalThis.navigator?.deviceMemory){return Math.max(512,Math.round(((e??0)>0?e:16)*1024/8))}var k0=400,A0=4e3,j0=1e3,M0=3e3,N0=2,P0=5e3,F0=1e4;function I0(e,t,n=`data`){let r=new Ee(t.capacity??D0,void 0,void 0,(t.maxMemoryMB??O0())*1024*1024);return{meta:e,buffer:r,source:new Q1(()=>r),unsub:()=>{},status:`connecting`,error:null,lastFrameAt:Date.now(),lastColCount:0,lastValued:0,recorder:null,dropped:0,recDropped:0,video:n===`camera`?new GE:null,clock:n===`camera`?null:new Z1,lagTicks:0,lastRejoinAt:0,rejoin:()=>{},subscribed:!1,releaseTimer:void 0}}function L0(e,t,n,r){let i,a=-1/0,o=new Map;return async s=>{if(i===void 0&&(i=s,o.set(t,s)),s===i)return e;if(Date.now()-a<2e3)return null;a=Date.now();let c=await r().catch(()=>null);if(!c||o.has(c.salt)&&o.get(c.salt)!==s)return null;let l=c.key??(n===null?null:await _(n,c.salt));return!l||!await at(l,c.key_check).catch(()=>!1)?null:(o.set(c.salt,s),l)}}function R0(e,t,n=()=>({}),r){let i=new Map,a=e,o=[],s=[],c=``,l=()=>{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(k0),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)},u=(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&&f(e,r,t[t.length-1]?.t)},d=(e,t)=>{let n=e.buffer.endAbs;e.buffer.pushColumns(t),e.recorder?.addColumns(t),t.t.length>0&&f(e,n,t.t[t.t.length-1])},f=(e,t,n)=>{s0(e.buffer,s,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),p(e,t===0||e.buffer.columnNames.length!==e.lastColCount||e.buffer.valuedCount!==e.lastValued)},p=(e,t)=>{e.lastFrameAt=Date.now();let n=e.status===`stale`||e.status===`connecting`;n&&(e.status=`live`),(n||t)&&l()},m=e=>{let t=i.get(e);t&&(clearTimeout(t.releaseTimer),t.unsub(),i.delete(e),l())},h=setInterval(()=>{let e=Date.now(),t=!1;for(let n of i.values()){n.status===`live`&&e-n.lastFrameAt>A0&&(n.status=`stale`,t=!0);let i=n.video&&n.subscribed&&n.status===`live`?n.video.info().lagMs:null;n.lagTicks=i!==null&&i>M0?n.lagTicks+1:0,n.video&&n.lagTicks>=N0&&e-n.lastRejoinAt>=P0&&(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&&l()},j0);return{connections:()=>o,disconnect:m,startRecording(e){let t=i.get(e);!t||t.recorder||(t.recorder=new n0,t.recDropped=0,l())},stopRecording(e){let t=i.get(e),n=t?.recorder;return!t||!n?null:(t.recorder=null,l(),{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:E0(t)}:void 0,t&&n.segAxis.tracker.feed(n.buffer,n.buffer.firstAbs,!t.replay),l())},setMathChannels(e){let t=JSON.stringify(e.map(e=>[e.id,e.name,e.units,e.formula,e.enabled]));if(t!==c){c=t,s=e;for(let t of i.values())t.video||(c0(t.buffer,e),t.segAxis&&(t.segAxis.tracker=E0(t.segAxis.cfg),t.segAxis.tracker.feed(t.buffer,t.buffer.firstAbs,!0)));i.size>0&&l()}},openLocal(e,t){let r=`local:${crypto.randomUUID()}`,a=I0({id:r,name:e,ownerName:`This page`,visibility:`private`,orgName:null,parentId:null,lowOf:null},{...n(),...t});return i.set(r,a),l(),{id:r,push:e=>{i.get(r)===a&&u(a,Array.isArray(e)?e:[e])},pushColumns:e=>{i.get(r)===a&&d(a,e)},close:()=>m(r)}},async connect(e,t,o){if(i.has(e.id))return;let s=a&&e.relay_url?{...a,url:e.relay_url,getToken:async e=>{let t=await a.getToken(e);return t&&!z1(t)?t:null}}:a;if(!s)throw new OO(`relay_unavailable`);let c;if(typeof t==`string`){let n=se(t).secret??t,r=await _(n,e.salt);if(!await at(r,e.key_check))throw new OO(`wrong_password`);c=o?.reload?L0(r,e.salt,n,o.reload):r}else if(c=`keyFor`in t?e=>t.keyFor(e):t,typeof c!=`function`){if(!await at(c,e.key_check))throw new OO(`wrong_password`);o?.reload&&(c=L0(c,e.salt,null,o.reload))}let f=I0({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,sync:e.sync??null,clockOffsetMs:e.clock_offset_ms??null},{...n(),...o},e.kind);i.set(e.id,f);let m=t=>{if(i.get(e.id)===f)if(t.type===`video`)f.video&&(f.video.push(t.m),p(f,!1));else if(t.type===`last`){let e=f.buffer;for(let n of t.values)e.setLastKnown(n.name,n.unit,n.t,n.v);(e.columnNames.length!==f.lastColCount||e.valuedCount!==f.lastValued)&&l()}else if(t.type===`gap`)f.dropped+=t.samples,f.recorder&&(f.recDropped+=t.samples),l();else if(t.type===`integrity`){let e=f.integrity;f.integrity=t.integrity,(!e||e.broken!==t.integrity.broken)&&l()}else t.type===`columns`?t.historical?r?.historical?.(e.id,t.block):d(f,t.block):u(f,t.frames)},h=t=>{!f.subscribed||i.get(e.id)!==f||(t===`subscribed`?(f.status=`live`,f.lastFrameAt=Date.now()):t===`error`&&(f.status=`error`,f.error=`connection_error`),l())};f.rejoin=()=>{f.unsub=f.video?H1(s,e.id,J1(c,m),h):X1(s,e.id,c,m,h)};let g=f.video;g?(f.status=`idle`,g.onDemandChange(t=>{i.get(e.id)===f&&(clearTimeout(f.releaseTimer),t?f.subscribed||(f.subscribed=!0,g.resync(),f.status=`connecting`,f.lastFrameAt=Date.now(),f.rejoin(),l()):f.releaseTimer=setTimeout(()=>{f.subscribed=!1,f.unsub(),f.unsub=()=>{},f.status=`idle`,f.error=null,f.lagTicks=0,l()},F0))})):(f.subscribed=!0,f.rejoin()),l()},dispose(){clearInterval(h);for(let e of i.values())clearTimeout(e.releaseTimer),e.unsub();i.clear(),o=[]}}}var z0=500,B0=1<<20;function V0(e){let t=[],r=new Map,i=new Map,a=[],o=``,s=(e,t)=>`${e}|${t}`,c=(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)},l=()=>[...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}}}),u=()=>{let t=l(),n=JSON.stringify(t);n!==o&&(o=n,e.setStates(t))};function d(n,r,i=!1){let o=t.find(e=>e.id===n.ruleId);if(n.kind===`raised`){a=[...a,{id:`${n.ruleId}|${n.target.id}|${n.t}${i?`|late`:``}`,ruleId:n.ruleId,ruleName:o?.name??``,severity:o?.severity??`info`,targetId:n.target.id,timeColumn:r,t0:n.t,t1:null,...i?{late:!0}:{}}];let e=a.filter(e=>e.targetId===n.target.id);e.length>z0&&(a=a.filter(t=>t!==e[0]))}else{let e=a.find(e=>e.ruleId===n.ruleId&&e.targetId===n.target.id&&e.t1===null&&!!e.late===i);e&&(a=a.map(t=>t===e?{...t,t1:n.t}:t))}e.setMarks(a),e.emit(i?{...n,late:!0}:n)}function f(){let a=new Set;for(let i of e.targets())for(let e of t){if(!c(e,i))continue;let t=s(e.id,i.id);a.add(t);let o=r.get(t),{channels:l,...u}=i;(!o||o.rule!==e)&&(o=ft(e,u),r.set(t,o));for(let e of o.bind(l))d(e,i.kind===`stream`?n:``)}for(let e of r.keys())a.has(e)||r.delete(e);for(let[e,t]of i)r.get(e)?.rule!==t.rule&&i.delete(e);u()}return{setRules(n){let r=[],i=n.filter(e=>{let t=pt(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}),f(),r},rules:()=>t,state:l,async evaluate(n,r){let i=e.targets().find(e=>e.id===n&&e.kind===`dataset`);if(!i)return[];let{channels:o,...s}=i,l=[],u=t.filter(e=>(!r.ruleIds||r.ruleIds.includes(e.id))&&c(e,s)),f=u.map(e=>{let t=ft(e,s);return t.bind(o),t}),p=[...new Set(u.flatMap(e=>Object.values(e.signals).map(e=>`formula`in e?e.formula:e.channel)))];for(let t=0;;t+=B0){let i=await e.readDataset(n,[r.timeColumn,...p],t,B0),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<B0)break}a=a.filter(e=>!(e.targetId===n&&(!r.ruleIds||r.ruleIds.includes(e.ruleId)))),e.setMarks(a);for(let e of l)d(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)d(e,n)}i&&u()},pushLate(t,a){let o=e.targets().find(e=>e.id===t&&e.kind===`stream`);if(!o)return;let{channels:s,...c}=o;for(let[e,o]of r){if(o.target.id!==t)continue;let r=i.get(e);(!r||r.rule!==o.rule)&&(r=ft(o.rule,c),r.bind(s),i.set(e,r));for(let e of r.push(a))d(e,n,!0)}},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)d(e,n)}i&&u()},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:f,clearMarks(t){a=t?a.filter(e=>e.targetId!==t):[],e.setMarks(a)}}}var H0=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}},U0={maxChartsPerWorksheet:null,maxChannelsPerChart:null,maxWorksheets:null,maxMathChannels:null,maxAlertRules:null,canImportExportWorkspaces:!0},W0=[];function G0(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 K0=[`#a78bfa`,`#38bdf8`,`#fb7185`,`#4ade80`,`#fbbf24`,`#94a3b8`];function q0(e=`ET`){return{id:crypto.randomUUID(),name:`Worksheet`,panels:[],panelChartSettings:{},panelChartBackgrounds:{},xKey:e}}function J0(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(br({...e,name:a,source:`workbook`}))}return{channels:i,rename:r}}function Y0(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 X0(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 Z0(e,t,n){if(!e||!t)return fn();let{min:r,max:i}=vV(e.rows,t);if(!Number.isFinite(r)||!Number.isFinite(i))return fn();let a=bV(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 Q0(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:Tn();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:En(K0[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:Dn(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 $0(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 e2(){return typeof document>`u`?`dark`:YV(null)}function t2(e={}){let t={...e},r=!1,i=q0(),a=S1({datasets:[],selection:[],worksheets:[i],activeWorksheetId:i.id,xRanges:{},offsets:{},colors:{},liveWindowSeconds:15,cycleRules:[],live:[],video:[],mathChannels:[],limits:{...U0,...t.limits},palette:KV(t.palette,e2()),importing:0,licensed:null,history:{canUndo:!1,canRedo:!1},marks:[],alerts:[],alertRules:[]}),o=ZH(),s=()=>{let e=KV(t.palette,e2());a.set(t=>t.palette.join()===e.join()?t:{...t,palette:e})},c=typeof document>`u`?()=>{}:XV(null,s),l=w1(),u=()=>{if(r)throw new OO(`disposed`)},d=e=>{throw o.emit(`limit`,{reason:e}),new OO(`limit_reached`,{reason:e})},f=()=>a.get(),p=(e,t)=>{let n=f().limits.maxChannelsPerChart,r=yV(t);n!==null&&r>n&&r>yV(e)&&d(`channels-per-chart`)},m=C1((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??W0,layout:t.rect,window:t.window??null}),_=C1((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=C1((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:WV(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:WV(n,i.id,s(i.id,a),o),offset:r[i.id]??0,selected:t.includes(i.id),...e.cut?{cycle:G0(e.cut,a)}:{}})):null,selected:c?u===0?!1:u===l.length?!0:`partial`:t.includes(e.id)}})}),y=C1((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:WV(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=C1(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 H0({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 OO(`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 OO(`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=R0(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(!ce.rules().length)return;t.columnNames.length!==ee.get(e)&&(ee.set(e,t.columnNames.length),ce.sync());let i=ce.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);ce.pushLive(e,{t:t.range(n,o,a),columns:s,scan:new Map})},historical:(e,t)=>{if(!ce.rules().length||!t.t.length)return;let n={};for(let r of ce.liveColumns(e)){let e=t.columns[r];e&&(n[r]=e instanceof Float64Array?e:Float64Array.from(e))}Object.keys(n).length&&ce.pushLate(e,{t:t.t instanceof Float64Array?t.t:Float64Array.from(t.t),columns:n,scan:new Map})},tick:(e,t,r)=>{if(!ce.rules().length)return;let i=t.range(n,t.endAbs-1,t.endAbs)[0];i===i&&ce.tickLive(e,i+(Date.now()-r)/1e3)}}),ee=new Map,te=C1((e,t)=>e.filter(e=>t.some(t=>PE([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=_V(e.schema);t.length&&T(()=>a.set(e=>({...e,worksheets:e.worksheets.map(e=>Q0(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 OO(`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 CB(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 gV({main:t,companions:i.companions,format:i.format.id},{priorInMemoryValues:hB(f().datasets),signal:s,onProgress:e=>o.emit(`import`,{file:t.name,phase:`progress`,fraction:e}),chooseChannels:n.chooseChannels,pickChannels:n.pickChannels}):[await mB(crypto.randomUUID(),t,f().datasets)??await fB(crypto.randomUUID(),t,X0,void 0,hB(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 OO(`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 OO&&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},ae=()=>setTimeout(()=>{r||B$(rt)},0),oe=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&&ae()},se=async(e,t,n={})=>{let[r,...i]=await gV({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}}}},ce=V0({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({})}}),ue=C1((e,t)=>{let n=new Map;for(let r of e){let e=ht(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}),de=null;a.subscribe(()=>{let e=f();de&&de[0]===e.datasets&&de[1]===e.live||(de=[e.datasets,e.live],ce.rules().length&&ce.sync())});let fe={importFiles:ie,warmImport(e={}){u(),iV(!!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 OO(`not_found`,{datasetId:e});if(!t.info?.combined||!(t.file instanceof File))throw new OO(`invalid_argument`,{reason:`only a combined multi-rate import can be split`});let n=await gV({main:t.file,companions:t.companions??[],format:t.info.importer},{priorInMemoryValues:hB(f().datasets.filter(t=>t.id!==e)),selection:t.info.selection,split:!0});oe([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 OO(`not_found`,{datasetId:e});if(!n.info||!(n.file instanceof File))throw new OO(`invalid_argument`,{reason:`only binary imports have channels to choose`});try{let r=await gV({main:n.file,companions:n.companions??[],format:n.info.importer},{priorInMemoryValues:hB(f().datasets.filter(t=>t.id!==e)),initial:n.info.selection,chooseChannels:t,pickChannels:!0});oe([e]);for(let e of r)ne(e);return r.map(e=>e.id)}catch(e){if(e instanceof OO&&e.code===`cancelled`)return null;throw e}},async combine(e){u();let t=f().datasets.find(t=>t.id===e);if(!t)throw new OO(`not_found`,{datasetId:e});let n=t.info?.splitKey;if(!n||!(t.file instanceof File))throw new OO(`invalid_argument`,{reason:`only datasets split from one file can be combined`});let r=f().datasets.filter(e=>e.info?.splitKey===n),i=await gV({main:t.file,companions:t.companions??[],format:t.info.importer},{priorInMemoryValues:hB(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 OO(`invalid_argument`,{reason:`these groups have no common time base`})}return oe(r.map(e=>e.id)),ne(i[0]),i[0].id},async openRecording(e,t={}){u();let n=await se(e,hB(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 OO(`not_found`,{datasetId:e});let r=await se(t,hB(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),ae()},addColumns(e){u();let t=h1(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 OO(`not_found`,{datasetId:e});let i=y1(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 OO(`not_found`,{datasetId:e});let i=_1(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 lB(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 OO(`not_found`,{datasetId:e});let i=await _D(r.source,n,yD(t)),a=new Map(t.filter(e=>e.kpis?.length).map(e=>[e.id,e.kpis]));return vD(i,t).map(e=>a.has(e.definitionId)?{...e,kpis:xD(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 OO(`not_found`,{datasetId:e});let r=n.schema.filter(e=>e.type===`number`&&e.name!==t.timeKey).map(e=>e.name),i=await _D(n.source,t.timeKey,r),a={...Object.fromEntries(n.schema.map(e=>[e.name,e.unit])),[hD]:`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 OO(`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(fe.addColumns({name:`${n.name} · ${c}`,columns:CD(i,t.timeKey,r),units:a}))}if(t.tables!==!1){let e=TD(t.found,t.cycleId,t.defs,i);s.push(await fe.addText(ED(e.cycles),`${n.name} · ${o(t.cycleId)}s.csv`)),e.phases.length&&s.push(await fe.addText(ED(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 OO(`not_found`,{datasetId:e});let r;if(t){if(!t.defs.some(e=>e.id===t.cycleId))throw new OO(`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 _D(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=vD(a,t.defs).sort((e,t)=>e.tstart-t.tstart||!!e.parentIndex-+!!t.parentIndex).map(e=>c.has(e.definitionId)?{...e,kpis:xD(a,e,c.get(e.definitionId))}:e),u={...Object.fromEntries(n.schema.map(e=>[e.name,e.unit])),[hD]:`s`},d=e=>t.defs.find(t=>t.id===e)?.name??e,f=l.map(r=>h1(`${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:CD(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(),oe([e])},clear(){u(),oe(f().datasets.map(e=>e.id))},async configure(e,t){u();let n=f().datasets.find(t=>t.id===e);if(!n)throw new OO(`not_found`,{datasetId:e});if(t.parseConfig&&(n.kind!==`memory`||!n.parseConfig))throw new OO(`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 OO(`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?$V(n.data.rows,r.channel):[],l=r&&t.selectCycles===`best`?iH(c.map(e=>rH(n.data.rows,e,r.metric,r.stat))):null,u=l===null?c.map((t,n)=>sH(e,n)):[sH(e,l)];z(o?c.length>0?[...s,...u]:[...s,e]:s)}let r=t.parseConfig;if(!r)return;let i=(()=>{try{let e=Xe(U(n.rawText??``),r.headerRow);return n.data.columnNames.length===e.length&&n.data.columnNames.every((t,n)=>t===e[n])}catch{return!1}})();if(le(r,n.parseConfig)&&i)return;let o=n.fromColumns?x1(n):n.rawText??``,s=await NO(n.file?{file:n.file,config:r}:{rawText:o,config:r}),c=new IO(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),ae(),n.cut&&await fe.cut(e,n.cut);let p=h().selectedDatasets,m=new Set(p.flatMap(e=>e.data.columnNames)),g=s.columnNames.filter(e=>Le(s.rows,e)),_=g.find(e=>e===`ET`)??g[0];T(()=>a.set(e=>({...e,worksheets:e.worksheets.map(e=>$0(!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 OO(`not_found`,{datasetId:e});return{get rawText(){return t.kind===`memory`&&t.fromColumns?x1(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=vV(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=pe(e);if(!i)return null;let a=vV(i.rows,e);return Number.isFinite(a.min)&&Number.isFinite(a.max)?a:null}},pe=(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=NE(n.merged,n.channels,t);return{...n.merged,columnNames:[...n.merged.columnNames,...r.ok.map(e=>e.name)],rows:r.rows}},me=(e,t,n)=>h().selectedLive.length>0?{...n,scaleMin:``,scaleMax:``,majorStep:``,minorStep:``}:Z0(pe(e,t),e,n),he={fromFileList:e=>RH(Array.from(e)),async fromDataTransfer(e){return zH(Array.from(e.items??[]).map(e=>e.webkitGetAsEntry?.()).filter(e=>!!e))},canPick:BH,pick:VH,tree:(e,t)=>LH(e,t),isImportable:IH},ge={add(e=`Worksheet`){u();let t=f(),n=t.limits.maxWorksheets;n!==null&&t.worksheets.length>=n&&d(`worksheets`);let r={...q0(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 OO(`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=>$0({...e,xKey:t},e=>e!==t)),a.set(t=>({...t,xRanges:{...t.xRanges,[e]:null},offsets:{}}))}},_e={mount(e,t,n){return u(),z$(rt,e,t,n)},openWindow(e,t){u(),F(e);let n=F(e).panel.window;return l1(rt,e,(t,n)=>z$(rt,e,t,n),{...n,...t})},recordWindows(){u();let e=d1(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),B$(rt)},kinds:()=>T1,label:D1,add(e,t={}){if(u(),!T1.some(t=>t.kind===e))throw new OO(`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={...ln(e,n.panels),...t.title?{title:t.title}:{}};t.layout&&(i.rect={...t.layout});let a=gr([i],{},K0[2],4)[i.id],o=a,s=h().numericColumns;if(s.length&&(o.kind===`multiband`||o.kind===`xyscatter`||o.kind===`xyzmesh`)&&(o=Q0({...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??me(o.xyXCol,n.xKey,o.xyXScale),xyYScale:e.xyYScale??me(o.xyYCol,n.xKey,o.xyYScale)}}return p(a,o),L(n.id,e=>({...e,panels:t.layout?[...e.panels,i]:dn([...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:dn(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:me(e.xyXCol,n.xKey,r.xyXScale)}),typeof e.xyYCol==`string`&&e.xyYCol!==r.xyYCol&&!(`xyYScale`in e)&&(i={...i,xyYScale:me(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 OO(`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=Gt({...t,id:t.id||crypto.randomUUID()});if(!n)throw new OO(`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 OO(`not_found`,{annotationId:t});let i=Gt({...r,...n,id:r.id,kind:r.kind});if(!i)throw new OO(`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=Kt(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:dn(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 OO(`invalid_argument`,{reason:`not a multiband chart`});let i=f().limits.maxChannelsPerChart;i!==null&&yV(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=yr(),l={id:c,column:s,color:K0[r.series.length%K0.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 _e.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 OO(`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 _e.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 fe.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)}},ve=new Map,ye={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){ye.setXRange(null,e)},setCursorX(e,t){u();let n=P(t).id;(ve.get(n)??null)!==e&&(ve.set(n,e),o.emit(`cursorchange`,{worksheetId:n,x:e}))},cursorX(e){return ve.get(P(e).id)??null},setLiveWindow(e,t){u();let n=P(t);n.liveWindowSeconds!==e&&L(n.id,t=>({...t,liveWindowSeconds:e}))}},be={save(e){u();let t=e.id??crypto.randomUUID(),[n]=mD([{...e,id:t,parentId:e.parentId??null}].concat(f().cycleRules.filter(e=>e.id!==t))).filter(e=>e.id===t);if(!n)throw new OO(`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))}))}},xe={create(e){u();let n=f(),r=n.limits.maxMathChannels;r!==null&&n.mathChannels.length>=r&&d(`math-channels`);let i=br(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 OO(`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 OO(`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 LE(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:()=>FE(f().mathChannels),preview(e,t){let n=h();return n.merged?hE(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}})}},Se=C1((e,t)=>[...e.flatMap(e=>e.kind===`camera`&&e.video?[WE({...e,video:e.video})]:[]),...t]),Ce=``;a.subscribe(()=>{let e=Se(f().live,f().video),t=e.map(e=>`${e.kind}:${e.id}:${e.recordingId??``}:${e.name}:${e.sync?`${e.sync.offsetMs}/${e.sync.driftPpm}/${e.sync.method}`:``}`).join(`|`);t!==Ce&&(Ce=t,o.emit(`videochange`,{sources:e}))});let we=(e,t,n)=>e.id===t&&(n===void 0||(e.recordingId??null)===n),Te={sources:()=>Se(f().live,f().video),register(e){u(),a.set(t=>({...t,video:[...t.video.filter(t=>!we(t,e.id,e.recordingId??null)),e]}))},setSync(e,t,n){u();for(let r of Se(f().live,f().video))r.id===e&&(t===void 0||(r.recordingId??null)===t)&&(r.sync=n);a.set(e=>({...e,video:[...e.video]}))},async detectSync(e,t,n){u();let r=f().video.find(n=>n.kind===`recorded`&&n.id===e&&n.recordingId===t),i=f().datasets.find(e=>e.info?.meta?.recordingId===t);if(!r||!i)throw Error(`Open the recording this camera was recorded with`);let a=Number(i.info?.meta?.wallOrigin);if(!Number.isFinite(a)||!i.schema.some(e=>e.name===`Time`))throw Error(`This recording has no wall clock`);let o=await lO({video:r,data:i.source,schema:i.schema,timeKey:`Time`,wallOrigin:a},n);return o.ok?{...o,offsetMs:o.offsetMs-VE(r.clockOffsetMs,r.dataClockOffsetMs)*1e3}:o},relayClock(){u();let e=t.live?.relay?.url;return e?EO(e,fetch,Date.now):Promise.resolve(null)},async calibrateFlash(e,t,n={}){u();let r=Se(f().live,f().video).find(t=>t.kind===`live`&&t.id===e);if(!r?.unitsBetween)throw Error(`This camera isn’t live`);let i=r.clockOffsetMs??n.displayClockOffsetMs??0,a=t.map(e=>({t:e.t+i/1e3,level:e.level})),o=r.acquire?.();try{let e=a[a.length-1].t+3;for(let t=0;(r.range()?.[1]??0)<e&&t<15e3;t+=250){if(n.signal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);await new Promise(e=>setTimeout(e,250))}return wO(await cO(r,[[a[0].t-1,e]],{signal:n.signal,onProgress:n.onProgress}),a)}finally{o?.()}},unregister(e,t){u(),a.set(n=>n.video.some(n=>we(n,e,t))?{...n,video:n.video.filter(n=>!we(n,e,t))}:n)}},Ee={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))}},De=()=>{f().limits.canImportExportWorkspaces||d(`workspaces-io`)},Oe=async e=>{if(e instanceof Blob)try{return JSON.parse(await e.text())}catch{throw new OO(`bad_file`)}if(typeof e==`string`)try{return JSON.parse(e)}catch{throw new OO(`bad_file`)}return e},ke=async e=>e instanceof File?e:new File([JSON.stringify(await Oe(e))],`import.json`,{type:`application/json`}),Ae=e=>e.replace(/[^\w.-]+/g,`_`),je=e=>new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),Me=e=>{let t=hr(e.panelChartSettings,K0[2],4),n={};for(let r of e.panels)t[r.id]?.kind===r.kind&&(n[r.id]=t[r.id]);return{...e,panelChartSettings:gr(e.panels,n,K0[2],4)}},Ne=(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??{})}}),Pe=()=>new Set(f().worksheets.flatMap(e=>[e.id,...e.panels.map(e=>e.id)])),Fe=(e,t=0)=>{let n=f().limits.maxWorksheets,r=Ne((n===null?e:e.slice(0,Math.max(1,n))).map(Me),new Set),i=r[Math.min(t,r.length-1)];a.set(e=>({...e,worksheets:r,activeWorksheetId:i.id,xRanges:{}}))},Ie=(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&&yV(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:dn([...t.panels,o]),panelChartSettings:{...t.panelChartSettings,[a]:e.settings},panelChartBackgrounds:e.background===null?t.panelChartBackgrounds:{...t.panelChartBackgrounds,[a]:e.background}})),a},Re=()=>{let e=f();return bH({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})},ze=e=>{if(e.worksheets.length===0)throw new OO(`bad_workspace`,{errors:e.errors});let{channels:t,rename:n}=J0(f().mathChannels,e.mathChannels);Fe(n.size?e.worksheets.map(e=>Y0(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)||fe.configure(e.id,{beacon:r}).catch(e=>o.emit(`error`,{error:e,context:`io.openWorkbook`}));return{worksheets:e.worksheets.length,errors:e.errors}},Be=e=>{if(e===null)return;let t=h().numericColumns,n=t.length?e.worksheets.map(e=>Q0(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()},Ve={undo(){u(),Be(S.undo())},redo(){u(),Be(S.redo())},clear(){u(),j()}},He={hasWork:()=>jH(f().worksheets),exportWorksheet(e){u(),De();let t=P(e),n=xH(t);return{json:n,blob:je(n),filename:`${Ae(t.name||`worksheet`)}.kymosh`}},exportChart(e){u(),De();let{ws:t,panel:n}=F(e),r=SH(n,t.panelChartSettings[e],t.panelChartBackgrounds[e]??null);return{json:r,blob:je(r),filename:`${Ae(n.title?.trim()||n.kind)}.json`}},parseFile:e=>PH(e),exportWorkspace(){u(),De();let e=Re();return{json:e,blob:je(e),filename:`kymoscope-workspace-${new Date().toISOString().slice(0,10)}.json`}},async exportWorkspaceEncrypted(e){u(),De();let t=typeof e==`string`?await uH(Re(),e):await dH(Re(),e);return{json:t,blob:je(t),filename:`kymoscope-workbook-${new Date().toISOString().slice(0,10)}.kymo`}},async importWorkspace(e,t={}){u(),De();let n=await Oe(e);return fH(n)&&(n=await hH(n,t)),M(()=>ze(AH(n)))},toWorkbook:Re,openWorkbook(e){return u(),M(()=>ze(AH(e)))},async importWorksheet(e){u(),De();let t=f();t.limits.maxWorksheets!==null&&t.worksheets.length>=t.limits.maxWorksheets&&d(`worksheets`);let n=await PH(await ke(e));if(n.type!==`worksheet`)throw new OO(`bad_file`,{found:n.type});let[r]=Ne([Me(n.worksheet)],Pe());return a.set(e=>({...e,worksheets:[...e.worksheets,r],activeWorksheetId:r.id})),r.id},async importChart(e,t){u(),De();let n=await PH(await ke(e));if(n.type!==`chart`)throw new OO(`bad_file`,{found:n.type});return Ie(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(Me):[q0()];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(()=>{oe(f().datasets.map(e=>e.id));let e=q0();a.set(t=>({...t,worksheets:[e],activeWorksheetId:e.id,xRanges:{},offsets:{},colors:{},mathChannels:t.mathChannels.filter(e=>e.source!==`workbook`)}))})}},Ue={merged(e){let t=h();if(!t.merged||t.channels.length===0)return t.merged;let n=NE(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}},We=typeof location<`u`?location.hostname:``,Ge=t.license,Ke=t.licenseKey,qe=!1,Je={},Ye=e=>{r||a.set(t=>({...t,licensed:e}))},Ze=(e,t,n)=>{clearTimeout(Je[e]);let r=Math.max(0,t-Date.now()),i=r>2**31-1;Je[e]=setTimeout(()=>{i?Ze(e,t,n):n()},i?2**31-1:r)},Qe=e=>Ze(`renew`,e,()=>void et()),$e=e=>Ze(`expiry`,e*1e3+1e3,()=>{qH(Ke,We).then(e=>{r||Ye(e.ok)})});async function et(){let e=36e5,t,n=null,i;try{t=await Promise.race([Ge.get(),new Promise((e,t)=>{i=setTimeout(()=>t(Error(`timeout`)),3e4)})]),n=await qH(t,We)}catch{}finally{clearTimeout(i)}if(r)return!1;if(n?.ok)return Ke=t,qe=!0,Ye(!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 qH(Ke,We);return r?!1:(Ye(a.ok),Qe(Date.now()+e),a.ok)}let tt=!Ge||t.licenseKey?qH(t.licenseKey,We).then(e=>(e.ok||console.warn(`[kymoscope] license ${e.reason}: showing attribution`),!qe&&!r&&(Ye(e.ok),e.ok&&Ge&&$e(e.exp)),e.ok)):null,nt=Ge?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:fe,folders:he,worksheets:ge,charts:_e,view:ye,mathChannels:xe,cycles:be,live:Ee,video:Te,io:He,history:Ve,data:Ue,alerts:{setRules:e=>{u();let t=ce.setRules(e);return a.set(e=>({...e,alertRules:ce.rules()})),t},rules:ce.rules,state:ce.state,evaluate:(e,t)=>(u(),ce.evaluate(e,t)),clearMarks:ce.clearMarks},marks:{list:()=>f().marks},dispose(){if(!r){r=!0,clearTimeout(Je.renew),clearTimeout(Je.expiry),c(),u1(rt),V$(rt),V.dispose();for(let e of f().datasets)e.source.dispose().catch(()=>void 0);o.emit(`dispose`,void 0),o.clear()}}};return n2.set(rt,{store:a,derived:h,live:V,alertLines:()=>ue(f().alertRules,f().alerts)}),rt}var n2=new WeakMap;function r2(e){let t=n2.get(e);if(!t)throw new OO(`invalid_argument`,{reason:`not a Kymoscope engine`});return t}var i2=2e3,a2=3;function o2(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 s2(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=o2(a);e?r.push(e):t||(i=a),a=[]}t&&a.push(t)}return{head:t,units:r,tail:i}}var c2=class{kind=`recorded`;id;name;parentId;parentName;recordingId;sync;clockOffsetMs;dataClockOffsetMs;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.sync=e.sync??null,this.clockOffsetMs=e.clockOffsetMs??null,this.dataClockOffsetMs=e.dataClockOffsetMs??null,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}=ce(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 ie(i,a,e=>s(this.open,e.slice().buffer),n).catch(()=>`broken`)})}for(let e of a){let t=null;try{t=await s(this.open,e.bytes.slice().buffer)}catch{}if(t?.kind!==6)continue;let n=K1(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=s2(r),c=e=>e.reduce((e,t)=>e+t.v.payload.length,0);return{...o,bytes:o.units.reduce((e,t)=>e+t.data.length,0)+c(o.head)+c(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=o2([...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<i2?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--;t=HE(o,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<a2;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)}async unitsBetween(e,t){let n=this.chunks.length;if(!n)return[];let r=0;for(;r+1<n&&this.chunks[r+1].t0<=e*1e3;)r++;let i=r;for(;i+1<n&&this.chunks[i+1].t0-i2<=t*1e3;)i++;let a=(await Promise.all(Array.from({length:i-r+1},(e,t)=>this.units(r+t)))).flat(),o=()=>{let t=-1;for(let n=0;n<a.length&&a[n].t<=e;n++)a[n].key&&(t=n);return t},s=o();for(let e=0;s<0&&r>0&&e<a2;e++)a=[...await this.units(--r),...a],s=o();return s<0&&(s=a.findIndex(e=>e.key)),s<0?[]:a.slice(s).filter(e=>e.t<=t)}ready(){return this.waiting??=(async()=>{for(let e=0;e<Math.min(this.chunks.length,a2+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=Ce([...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}},l2=[60,300,900,1800,3600,7200,14400,28800,43200,86400],u2={60:`1m`,300:`5m`,900:`15m`,1800:`30m`,3600:`1h`,7200:`2h`,14400:`4h`,28800:`8h`,43200:`12h`,86400:`24h`};function d2(e){if(typeof e==`number`)return l2.includes(e)?e:null;if(typeof e!=`string`)return null;let t=Object.entries(u2).find(([,t])=>t===e.trim().toLowerCase());return t?Number(t[0]):null}var f2=e=>u2[e]??`${e}s`;function p2(e){for(let t=l2.length-1;t>=0;t--)if(l2[t]*e<=157286400)return l2[t];return l2[0]}function m2(e,t,n){let r=t*1e3,i=n*1e3;return Math.floor((e+i)/r)*r+r-i}var h2=1e4,g2=1e3,_2=72e4,v2=3e5,y2=3e4,b2=1e4,x2=1e4,S2=64*1024,C2=50,w2=[`360p`,`480p`,`720p`,`1080p`],T2=e=>e+6+(e>=126?2:0)+(e>65535?6:0);function E2(e,t){return t*T2(e+30)}var D2=e=>typeof e==`number`&&Number.isFinite(e)&&e>0,O2=e=>Number.isInteger(e)&&e>=1;function k2(e,t){if(!e||e.mode!==`live`&&e.mode!==`record`)return null;if(t===`camera`)return w2.includes(e.quality)&&Number.isInteger(e.fps)&&e.fps>=1&&e.fps<=60?{mode:e.mode,quality:e.quality,fps:e.fps}:null;if(!D2(e.bytes_per_sec))return null;let n=e.bytes_per_sec,r={};if(e.mode===`record`){let t=e.splitEvery===void 0?p2(n):d2(e.splitEvery);if(t===null)return null;r={split_every:t}}return e.sources===void 0?D2(e.hz)&&O2(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=>D2(e?.hz)&&O2(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 A2=class extends Error{status;code;detail;constructor(e,t,n){super(`${n} (${t})`),this.status=e,this.code=t,this.detail=n}};async function j2(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 A2(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 A2(a.status,s?.error??`error`,s?.message??s?.error??o);return s}async function M2(e,t,n=fetch){let{auth:r}=se(t),{token:i}=await j2(n,e,`stream-token`,{"x-api-key":r}),a=await j2(n,e,`stream-publisher`,{Authorization:`Bearer ${i}`,"Content-Type":`application/json`},{action:`usage`});return{limits:a.limits??{},usage:a.usage}}var N2=e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0)),P2=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=S2;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;clock=null;clockAt=-1/0;constructor(e,t){let{auth:n,secret:r}=se(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=k2(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`?I: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 e=await this.deps.store.load();this.salt=e?.salt??he();let t=await this.mint();this.token=t.token,this.relayUrl=t.relayUrl??null,this.maxBytesPerSec=t.maxBytesPerSec||0,this.maxMessageBytes=t.maxMessageBytes||S2,this.apiKeyId=t.apiKeyId??null,await this.probeClock();let n=t.project;this.e2ee=!!n?.e2ee;let r={};if(this.e2ee){this.projectId=n?.id??null;let t=e?.apiKeyId===this.apiKeyId;this.device=t&&e?.device||await O(),t&&e?.streamKey?{key:this.key,epoch:this.epoch,sealed:this.sealed}=e.streamKey:this.key=await Re(tt()),r.sender_device=await this.senderDevice()}else this.raw=N2(await ee(this.password,this.salt)),this.key=await Re(this.raw),this.gen=e?.keyGen??0;let i=await this.register(e?.streamId??null,r);if(this.sid=i.stream.id,this.ticket=i.ticket,this.admitted(i),this.e2ee?(this.senderDeviceId=i.sender_device_id??null,this.projectId=i.project?.id??this.projectId,await this.save(),await this.applyProject(i.project)):(await this.save(),await this.wrapFor(i.devices)),!this.relayUrl)throw Error(`stream-token returned no relayUrl`)}catch(e){throw e instanceof A2&&e.status>=400&&e.status<500&&this.refuse(e),e}this.stopped||(this.lastToken=this.deps.now(),this.connect(),this.heartbeatTimer=setInterval(()=>{this.housekeeping()},h2),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 w(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 xe(t,oe(),0),at:n});let r=this.chain;r.lane.add(e),!(n-r.at<g2)&&(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 j2(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 Je(r),visibility:this.opts.visibility??`private`,kind:this.opts.kind,profile:this.wire,...t,...DO(this.clock)};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)}async probeClock(){let e=this.deps.now();!this.relayUrl||e-this.clockAt<6e5||(this.clockAt=e,this.clock=await EO(this.relayUrl,this.deps.fetch,this.deps.now)??this.clock)}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 lt(await rt(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>=_2){this.lastToken=e;try{this.token=(await this.mint()).token}catch{return}}if(await this.probeClock(),this.e2ee){let e=await this.call({action:`heartbeat`,stream_id:this.sid,sender_device_id:this.senderDeviceId,epoch:this.haveKey?this.epoch:0,...DO(this.clock)});this.setTicket(e.ticket),this.notice(e),await this.applyProject(e.project)}else{let e=await this.call({action:`heartbeat`,stream_id:this.sid,...DO(this.clock)});this.setTicket(e.ticket),this.notice(e),await this.wrapFor(e.devices),e.rekey===!0&&await this.rekey()}}catch(e){e instanceof A2&&(e.status===401||e.status===403)&&this.refuse(e)}finally{this.busy=!1}}}async rekey(){let e=he(),t=N2(await ee(this.password,e)),n=await Re(t),r;try{r=await this.register(this.sid,{},e,n)}catch{return}this.salt=e,this.key=n,this.raw=t,this.gen=this.gen%255+1,await this.save(),await this.wrapFor(r.devices)}async wrapFor(e){let t=[];for(let n of e??[])try{t.push({device_id:n.id,wrapped:await T(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,C2)})}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 N(this.device.privateKey,t.wrapped,Me(this.projectId,n,this.senderDeviceId))}catch{if(this.deviceRetried)return;this.deviceRetried=!0,this.device=await O(),await this.reregister();return}let i=st(this.sid,this.projectId,n),a=this.key,o=n===this.epoch?this.sealed:null;if(o)try{await Te(r,o,i)}catch{o=null}if(!o){let e=tt();a=await Re(e),o=await Se(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`,[O1,`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{}},y2),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>=x2;if(this.disconnect(),this.stopped)return;let t=0;e?this.delay=1e3:(t=this.delay,this.delay=Math.min(this.delay*2,b2)),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<v2))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)}}},F2={"360p":{width:640,height:360},"480p":{width:854,height:480},"720p":{width:1280,height:720},"1080p":{width:1920,height:1080}},I2={width:640,height:360,fps:15,kbps:400},L2=[`avc1.640028`,`avc1.4d0028`,`avc1.42e028`],R2=[`avc1.64001f`,`avc1.4d001f`,`avc1.42e01f`],z2=2,B2=1e3,V2=1e3;async function*H2(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 U2(){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 W2=class{encoder=null;codec=``;error=null;unsubscribe=null;lastKey=-1/0;wallMinusPerf=0;anchoredAt=-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?L2:R2){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>z2?(this.dropped++,!1):!0}encode(e){let t=this.now(),n=t-this.lastKey,r=this.resume||n>=this.keyframeMs||this.keyPending&&n>=B2;r&&(this.lastKey=t,this.keyPending=this.resume=!1);let i=performance.now();i-this.anchoredAt>=1e3&&(this.anchoredAt=i,this.wallMinusPerf=Date.now()-i);let a=(this.wallMinusPerf+e.timestamp/1e3)/1e3;Math.abs(a-Date.now()/1e3)>60&&(a=Date.now()/1e3),this.times.set(e.timestamp,a),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=q1({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>=V2;)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()}},G2=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?F2[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??H2,this.scale=n.scale??U2(),this.high=new W2(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??I2}: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 OO(`camera_codec_unsupported`);if(this.lowOpt){let e=new W2(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<V2||!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()}},K2=new TextEncoder,q2={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`},J2=new Set([`authorization`,`content-type`,`content-length`,`user-agent`,`presigned-expires`,`expect`,`x-amzn-trace-id`,`range`,`connection`]),Y2=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 X2(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`)}},X2=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]=n4(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||!J2.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=t4(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=>t4(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 Z2(await Z2(await Z2(await Z2(`AWS4`+this.secretAccessKey,e),this.region),this.service),`aws4_request`),this.cache.set(t,n)),e4(await Z2(n,await this.stringToSign()))}async stringToSign(){return[`AWS4-HMAC-SHA256`,this.datetime,this.credentialString,e4(await Q2(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=X0(await J0(this.body||``))}return e}};async function q0(e,t){let n=await crypto.subtle.importKey(`raw`,typeof e==`string`?H0.encode(e):e,{name:`HMAC`,hash:{name:`SHA-256`}},!1,[`sign`]);return crypto.subtle.sign(`HMAC`,n,H0.encode(t))}async function J0(e){return crypto.subtle.digest(`SHA-256`,typeof e==`string`?H0.encode(e):e)}var Y0=[`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`a`,`b`,`c`,`d`,`e`,`f`];function X0(e){let t=new Uint8Array(e),n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=Y0[r>>>4&15],n+=Y0[r&15]}return n}function Z0(e){return e.replace(/[!'()*]/g,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase())}function Q0(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[U0[a]||a,o||``]}var $0=1e4,e2=2e3,t2=1e4,n2=6e4,r2=2e3,i2=6e4,a2=`rec`,o2=`meta.json`,s2=e=>Math.min(i2,Math.max(r2,e*2)),c2=e=>e>=1024?`${+(e/1024).toFixed(2)} GB`:`${e} MB`,l2=e=>e.replace(/(https?:\/\/[^\s?#'"]*)\?[^\s#'"]*/g,`$1`),u2=class extends Error{status;constructor(e,t){super(l2(e)),this.status=t}},d2=e=>e instanceof u2?void 0:e?.status,f2=e=>e?.code??String(d2(e)??`error`),p2=e=>`${String(e).padStart(8,`0`)}.krc`,m2=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},h2=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``);async function g2(e,t,n){let r=await(await e.getFileHandle(t,{create:!0})).createWritable();await r.write(n),await r.close()}async function _2(e,t){try{return JSON.parse(await(await(await e.getFileHandle(t)).getFile()).text())}catch{return null}}function v2(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 y2=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?u0(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?e2:$0)}root(){return this.rootDir??=(async()=>(this.opts.root?await this.opts.root():await navigator.storage.getDirectory()).getDirectoryHandle(a2,{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 v2(this.locks,`kymoscope-rec-${n}`);e&&this.held.set(n,e)}await g2(await(await this.root()).getDirectoryHandle(n,{create:!0}),o2,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 g2(await(await this.root()).getDirectoryHandle(n.id),o2,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=Ye(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 g2(await(await this.root()).getDirectoryHandle(t.id),p2(n),e),await this.enforceMax()})}async checkpoint(e,t,n){if(!this.opts.seal)return;let r;try{let i=h2((await crypto.subtle.digest(`SHA-256`,m2(e))).slice(0,8));r=ct({streamId:this.streamId,run:i,lane:1,seq:BigInt(t),count:n.length,hash:await ye(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 _2(i,o2))?.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 v2(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 _2(n,o2)?(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 _2(t,o2);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()+t2),null):(this.say(`refused:${t}`,`refused`,String(r.message??`Recording refused (${t})`),t),e===this.file?.id&&(this.refusedUntil=this.now()+n2),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 ${c0(this.splitEvery)}`:`cut with its data stream's`;this.status({type:`destination`,name:a,splitEvery:this.splitEvery,message:`Recording files: ${e} → ${a} (buffer ${c2(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 u2(`chunk upload failed: ${e?.message??e}`)}if(!r.ok)throw new u2(`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 g2(await(await i.getDirectoryHandle(e.stream_id,{create:!0})).getDirectoryHandle(t,{create:!0}),p2(n),r)}catch(e){throw new u2(`can't write to the folder: ${e?.message??e}`)}return}let o=(a.prefix??``).replace(/^\/+|\/+$/g,``),s=`${o?`${o}/`:``}${e.stream_id}/${t}/${p2(n)}`,c=`${a.endpoint.replace(/\/+$/,``)}/${a.bucket?`${a.bucket}/`:``}${s}`,l=new G0({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=h2(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(d2(e)===400)return this.dropChunk(n,r,`refused: ${f2(e)}`);if(d2(e)!==409||f2(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 _2(t,o2);return r?(await g2(t,o2,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=d2(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 (${f2(n)}): its chunks were dropped`,f2(n)),await this.forget(t);continue}throw n instanceof u2&&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=s2(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)}},b2=class{#e;constructor(e){this.#e=e}head(){let e=this.#e;return`${e.map(e=>$$(e.name)).join(`,`)}\n${e.map(e=>$$(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(){}},x2=new TextEncoder,S2=e=>e+7&-8,C2=104,w2=64,T2=104,E2=160,D2=4;function O2(e,t,n){let r=24+t.length*8+n.length,i=new Uint8Array(S2(r)),a=new DataView(i.buffer);return i.set(x2.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 k2=(e,t)=>O2(e,[],x2.encode(`${t}\0`)),A2=e=>BigInt(Math.round(e))*1000000n,j2=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+C2,r=e=>{let r=n;return t.push(e),n+=e.length,r},i=r(k2(`##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,A2(this.#t),!0);let o=r(O2(`##FH`,[0,i],a)),s=this.#e.map(e=>r(k2(`##TX`,e.name))),c=this.#e.map(e=>e.unit?r(k2(`##TX`,e.unit)):0),l=n,u=l+w2,d=this.#e.map((e,t)=>u+T2+t*E2),f=O2(`##DG`,[0,u,u+T2+e*E2,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=O2(`##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,D2),i.setUint32(4,n*8,!0),i.setUint32(8,64,!0),i.setUint8(20,255),O2(`##CN`,[n+1<e?d[n+1]:0,0,s[n],0,0,0,c[n],0],r)}),_=new Uint8Array(24);_.set(x2.encode(`##DT`),0),new DataView(_.buffer).setBigUint64(8,BigInt(24+this.#n*e*8),!0);let v=new Uint8Array(64);v.set(x2.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,A2(this.#t),!0);let b=[v,O2(`##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}},M2={csv:`text/csv`,mf4:`application/octet-stream`};async function N2(e,t,n,r={}){let i=xz(`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 b2(lz(e,a)):new j2(lz(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 P2(e,t,n={}){let r=[];return await N2(e,t,e=>{r.push(e)},n),new Blob(r,{type:M2[t]})}var F2=.01,I2=.05,L2=e=>Math.max(5,Math.ceil(e*I2)),R2=e=>Math.max(Math.abs(e.value)*2/100,2*e.spread);function z2(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=R2(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 B2=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>Number.isFinite(e)));function V2(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 H2=(e,t)=>U2(e,e=>Math.floor((e.t-t)/86400)),U2=(e,t)=>[...V2(e,t).values()].map(e=>({t:G2(e.map(e=>e.t)),v:G2(e.map(e=>e.v))})),W2=e=>typeof e==`number`&&Number.isFinite(e);function G2(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return e.length?t/e.length:NaN}function K2(e){if(e.length<2)return 0;let t=G2(e),n=0;for(let r=0;r<e.length;r++)n+=(e[r]-t)**2;return Math.sqrt(n/(e.length-1))}function q2(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 J2=e=>q2(e,.5);function Y2(e){let t=J2(e);return 1.4826*J2(Array.from(e,e=>Math.abs(e-t)))}function X2(e,t){return(e-J2(t))/Math.max(Y2(t),1e-12)}function Z2(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 Q2=e=>Math.min(1,2*(1-Z2(Math.abs(e))));function $2(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?Q2((c-n*r/2)/l):1,effect:c/(n*r)}}function e4(e){if(e<.5)return Math.log(Math.PI/Math.sin(Math.PI*e))-e4(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 t4(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 n4(e,t,n){if(e<=0)return 0;if(e>=1)return 1;let r=Math.exp(e4(t+n)-e4(t)-e4(n)+t*Math.log(e)+n*Math.log(1-e));return e<(t+1)/(t+n+2)?r*t4(e,t,n)/t:1-r*t4(1-e,n,t)/n}function r4(e,t){let n=.5*n4(t/(t+e*e),t/2,.5);return e>0?1-n:n}var i4=(e,t)=>n4(t/(t+e*e),t/2,.5);function a4(e,t){let n=-1e7,r=1e7;for(let i=0;i<120;i++){let i=(n+r)/2;r4(i,t)<e?n=i:r=i}return(n+r)/2}function o4(e,t,n,r){let i=e+n,a=t+r,o=(e,t)=>e4(e+1)-e4(t+1)-e4(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 s4(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:o4(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?Q2((i-a)/l):1}}function c4(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 l4(e,t){let n=G2(e),r=G2(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 u4(e,t){let n=e.length;if(n<3)return null;let r=G2(e),i=G2(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?i4(c/f,n-2):0,r2:s>0?1-u/s:0,n,s:d,mx:r,sxx:a}}function d4(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=G2(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=K2(t);return{beta:l,std:l.map((t,n)=>d>0?t*K2(e.map(e=>e[n]))/d:0),r2:s>0?1-u/s:0}}function f4(e,t){let n=d4(e,t);return n?{shares:n.std.map((n,r)=>n*l4(e.map(e=>e[r]),t)),r2:n.r2}:null}function p4(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 m4=2e3;function h4(e,t,{B:n=1e3,seed:r=1,alpha:i=.05}={}){let a=p4(r),o=[],s=Math.min(e,m4);for(let r=0;r<n;r++)o.push(t(Array.from({length:s},()=>Math.floor(a()*e))));let c=q2(o,i/2),l=q2(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 g4=[`management`,`quality`,`maintenance`,`production`],_4={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.`}},v4={"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`},y4=[...g4],b4={"00":y4,"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:y4,13:[`quality`,`production`],14:[`quality`]},x4=e=>`${e}. Supports your review; does not certify.`,S4=(e,t,n,r,i=[])=>({id:e,title:v4[e],verdict:t,roles:b4[e],findings:n,charts:r,notes:i,...n.length>3?{shown:3}:{}}),C4=e=>`${Math.round(e*100)}%`,w4=e=>`${Math.abs(e)>=10?Math.round(e):+e.toFixed(1)}%`;function T4(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 E4=e=>Number.isFinite(e)?Math.abs(e)>=1e3?Math.round(e).toLocaleString(`en-GB`):String(+e.toPrecision(Math.abs(e)<1?2:3)):`—`,D4=e=>Number.isFinite(e)?String(+e.toPrecision(4)):`—`,O4=(...e)=>A4(e=>Math.abs(e)<1?2:3,e),k4=(...e)=>A4(()=>4,e);function A4(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 j4=e=>`${e>0?`+`:e<0?`−`:``}${E4(Math.abs(e))}`;function M4(e){return e>=3600?`${E4(e/3600)} h`:e>=60?`${Math.round(e/60)} min`:`${Math.round(e)} s`}function N4(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 P4=e=>e===1?`once`:e===2?`twice`:`${e} times`,F4=(e,t,n=`${t}s`)=>`${e.toLocaleString(`en-GB`)} ${e===1?t:n}`,I4=e=>e.length<=1?e.join(``):`${e.slice(0,-1).join(`, `)} and ${e[e.length-1]}`,L4=e=>e.charAt(0).toUpperCase()+e.slice(1),R4=e=>e.charAt(0).toLowerCase()+e.slice(1);function z4(e){try{return new Intl.DateTimeFormat(`en-GB`,{timeZone:e}),!0}catch{return!1}}var B4=new Map,V4=(e,t)=>{let n=`${e}|${JSON.stringify(t)}`,r=B4.get(n);return r||B4.set(n,r=new Intl.DateTimeFormat(`en-GB`,{timeZone:z4(e)?e:`UTC`,...t})),r},H4=(e,t)=>V4(t,{day:`numeric`,month:`short`}).format(new Date(e*1e3)),U4=(e,t)=>V4(t,{day:`numeric`,month:`short`,hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}).format(new Date(e*1e3)),W4=(e,t)=>V4(t,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}).format(new Date(e*1e3)),G4=(e,t,n,r=`–`)=>`${U4(e,n)}${r}${H4(e,n)===H4(t,n)?W4(t,n):U4(t,n)}`,K4=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function q4(e,t){let n=V4(t,{weekday:`short`,hour:`2-digit`,hourCycle:`h23`}).formatToParts(new Date(e*1e3));return{day:K4.indexOf(n.find(e=>e.type===`weekday`).value),hour:Number(n.find(e=>e.type===`hour`).value)%24}}var J4=(e,t)=>`${K4[q4(e,t).day]} ${U4(e,t)}`,Y4={min:`minimum`,max:`maximum`,mean:`mean`,integral:`integral`,first:`at start`,last:`at end`,delta:`change`};function X4(e){if(e===`duration`)return`Cycle duration`;let t=e.lastIndexOf(`:`);return t<0?e:`${e.slice(0,t)} ${Y4[e.slice(t+1)]??e.slice(t+1)}`}var Z4=e=>e<.01?`p < 0.01`:`p = ${e.toFixed(2)}`;function Q4(e){let t=e.numbers.r,n=e.evidence===`correlation`&&Number.isFinite(t)?`r = ${t.toFixed(2)}`:e.p===null?``:Z4(e.p);return n?`${_4[e.evidence].label} · ${n}`:_4[e.evidence].label}var $4=3600,e3=(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 t3(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=e3(n,e.c.tstart-$4);return r<n.length&&n[r]<=(e.c.tend??e.c.tstart)},c=e=>({section:S4(`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(`${F4(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:s4(t,u.length,n,d.length)}}),p=c4(f.map(e=>e.t.p),F2),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:B2({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 (${C4(e.t.p1)}) against ${C4(e.t.p2)} of the rest.`}),g.push({text:`Act on “${e.r.name}” when it fires: it came before ${C4(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`),C4(e.t.p1),C4(e.t.p2)],finding:_.get(e.r.id),status:`watch`}))}]:[],y=m.slice(0,2).map(e=>`“${e.r.name}”`),b=m.length?`${I4(y)} came before off-golden batches more often than before the rest${m.length>2?`, and ${F4(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:S4(`07`,b,h,v),actions:g,next:x,numbers:{linked:m.length}}}var n3=(e,t)=>t===`duration`?e.c.tend===null?null:e.c.tend-e.c.tstart:e.c.kpis[t]??null,r3=e=>{let t=G2(e.map(e=>-e.gap));if(e.some(e=>e.g.value===0))return{text:E4(t),pct:null,abs:t};let n=G2(e.map(e=>-e.gap/Math.abs(e.g.value)*100));return{text:w4(n),pct:n,abs:t}},i3=e=>`${e<0?`−`:`+`}${w4(Math.abs(e))}`;function a3(e,t){let n=t.filter(e=>e.level===`better`),r=[],i=[],a=[],o=[];if(n.length<5)return{section:S4(`03`,n.length?`${F4(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=r3(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 V2(n,e=>e.c.streamId)){if(a.length<5)continue;let n=[...a].sort((e,t)=>e.gap-t.gap)[4],o=r3(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:B2({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 (${E4(n.c.value)}). ${F4(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}`:``}: ${F4(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=>n3(t,e)).filter(W2),r=c.map(t=>n3(t,e)).filter(W2);return t.length<5||r.length<5?[]:[{k:e,ma:J2(t),mb:J2(r),p:$2(t,r).p}]}),m=c4(p.map(e=>e.p),F2),h=p.filter((e,t)=>m[t]&&e.ma!==e.mb).map(e=>({...e,label:X4(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:B2({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}: ${E4(e.ma)} against ${E4(e.mb)} at golden level${Number.isFinite(e.pct)?` (${i3(e.pct)})`:``}.`});let g=h.filter(e=>Number.isFinite(e.pct)).map(e=>({label:e.label,pct:e.pct,text:`${E4(e.ma)} / ${E4(e.mb)}`}));g.length&&a.push({kind:`diverging`,rows:g,title:`03.1 · The ${F4(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:S4(`03`,`${F4(n.length,`batch`,`batches`)} beat the golden by ${u.text} on ${l}${_.length?` with ${I4(_)}`:``}.`,r,a),actions:i,next:o,numbers:{better:n.length}}}var o3=`Ppk is indicative: it assumes the values are normally distributed and the process stable, which this report does not test.`,s3=new Set([`mean`,`min`,`max`,`first`,`last`]),c3=e=>Number.isFinite(e)?e.toFixed(2):`–`;function l3(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||!s3.has(n.slice(i+1)))continue;let o=t.map(e=>e.c.kpis[n]).filter(W2),s=K2(o);if(o.length<30)continue;let c=G2(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:X4(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 ${I4(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]=k4(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)??C4(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:B2({cpk:e.cpk,n:e.n,mean:e.m,outside:e.out}),text:`${e.label}: Ppk ${c3(e.cpk)} over ${F4(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 ${c3(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,c3(e.cpk),s(e)??C4(e.out)],status:e.cpk<1?`crit`:e.cpk<r?`watch`:`ok`,...n?{finding:n}:{}}})}];return{section:{...S4(`04`,f.length?`${F4(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:x4(`Capability (AIAG SPC)`),fold:!0},actions:u,next:[],numbers:{low:f.length}}}var u3=[`generic`,`discrete`,`process`,`regulated`],d3={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`}}},f3=e=>d3[u3.find(t=>t===e)??`generic`],p3=e=>e===`quality`?`discrete`:e===`plants`?`process`:e===`pharma`?`regulated`:`generic`,m3=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),h3=e=>[...e].sort((e,t)=>t.length-e.length).map(m3).join(`|`),g3=new Map;function _3(e,t,n=[]){if(!e||!Object.keys(t.terms).length)return e;let r=g3.get(t.id);if(!r){let e=`(?<![\\w.])(${h3(Object.keys(t.terms))})(?!\\w)(?!\\.\\w)`;g3.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(`(${h3(s)})`)).map((e,t)=>t%2?e:o(e)).join(``):o(e)}function v3(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 y3=new Set([`id`,`section`,`kind`,`evidence`,`ref`,`refs`,`finding`,`day`,`status`,`unit`,`tone`,`roles`,`cites`,`owner`,`alert`,`batch`,`golden`]);function b3(e,t){return typeof e==`string`?t(e):Array.isArray(e)?e.map(e=>b3(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,y3.has(e)?n:b3(n,t)])):e}function x3(e,t,n=[]){if(t.id===`generic`)return e;let r=e=>_3(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})=>({...b3(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:b3(e.actions,r),missing:b3(e.missing,r)}}var S3=[`setting`,`measurement`,`quality`,`outside`,`energy`,`ignore`],C3={setting:`Adjustable setting`,measurement:`Measurement`,quality:`Quality result`,outside:`Outside influence`,energy:`Energy`,ignore:`Ignore`},w3=4e3,T3=(e=``)=>({role:null,unit:e,lo:null,hi:null,lsl:null,usl:null,target:null,calibration:null,suggested:!1}),E3=()=>({v:1,process:``,channels:{},lines:[],units:[],shifts:[],stops:[],costs:{currency:`EUR`,kwh:null,lineHour:null,scrap:null,rework:null,co2:null,licence:null}}),D3=e=>e&&!e.suggested?e.role:null,O3=e=>Object.keys(e?.channels??{}).filter(t=>D3(e.channels[t])===`energy`).sort()[0]??null,k3=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},A3=e=>Array.isArray(e)?e:[],j3=(e,t)=>typeof e==`string`?e.slice(0,t):``,M3=e=>typeof e==`number`&&Number.isFinite(e)?e:null,N3=e=>A3(e).filter(e=>typeof e==`string`).slice(0,500),P3=(e,t)=>e!==null&&t!==null&&e>=t?[null,null]:[e,t],F3=/^([01]\d|2[0-3]):[0-5]\d$/,I3=/^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d$/,L3=e=>e.suggested===!0?{suggested:!0}:{};function R3(e){let t=k3(e),n=j3(t.name,80),r=j3(t.from,16),i=j3(t.to,16);if(I3.test(r)&&I3.test(i)&&r<i)return[{name:n,from:r,to:i,...L3(t)}];if(!F3.test(r)||!F3.test(i))return[];let a=t.days===void 0?void 0:[...new Set(A3(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}:{},...L3(t)}]}function z3(e){let t=new Set,n=new Set;return A3(e).slice(0,50).map(e=>({name:j3(k3(e).name,80),streams:N3(k3(e).streams),...L3(k3(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 B3(e){let t=k3(e),n=k3(t.costs),r=E3(),i=Object.create(null);for(let[e,n]of Object.entries(k3(t.channels)).slice(0,2e3)){let t=k3(n),r=S3.find(e=>e===t.role)??null,[a,o]=P3(M3(t.lo),M3(t.hi)),[s,c]=P3(M3(t.lsl),M3(t.usl));i[e.slice(0,200)]={role:r,unit:j3(t.unit,40),lo:a,hi:o,lsl:s,usl:c,target:M3(t.target),calibration:M3(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:j3(t.process,w3),...t.processSuggested===!0&&j3(t.process,1)?{processSuggested:!0}:{},channels:i,lines:z3(t.lines),units:A3(t.units).slice(0,100).map(e=>({name:j3(k3(e).name,80),channels:N3(k3(e).channels),...L3(k3(e))})).filter(e=>e.name),shifts:A3(t.shifts).slice(0,12).map(e=>({name:j3(k3(e).name,40),start:j3(k3(e).start,5),end:j3(k3(e).end,5),...L3(k3(e))})).filter(e=>e.name&&F3.test(e.start)&&F3.test(e.end)),stops:A3(t.stops).slice(0,500).flatMap(R3),costs:{currency:/^[A-Z]{3}$/.test(String(n.currency))?String(n.currency):r.costs.currency,kwh:M3(n.kwh),lineHour:M3(n.lineHour),scrap:M3(n.scrap),rework:M3(n.rework),co2:M3(n.co2),licence:M3(n.licence)},...(M3(t.idealCycleS)??0)>0?{idealCycleS:t.idealCycleS}:{},...t.hideShifts===!0?{hideShifts:!0}:{},...u3.some(e=>e===t.preset)?{preset:t.preset}:{},...(M3(t.ppkMin)??0)>=1&&t.ppkMin<=3?{ppkMin:t.ppkMin}:{}}}var V3=(e,t)=>{let n=e+bB(e,t);return Math.floor((n%86400+86400)%86400/60)},H3=e=>e.slice(0,2)*60+ +e.slice(3,5);function U3(e,t,n){if(!t.length)return null;let r=V3(e,n);for(let e of t){let t=H3(e.start),n=H3(e.end);if(t<n?r>=t&&r<n:r>=t||r<n)return e.name}return null}var W3=e=>(new Date(`${e}T00:00:00Z`).getUTCDay()+6)%7;function G3(e,t,n,r){let i=[];for(let a of e.stops){if(a.from.length>5){i.push({t0:SB(a.from.slice(0,10),a.from.slice(11),t),t1:SB(a.to.slice(0,10),a.to.slice(11),t)});continue}for(let e=CB(xB(n,t),-1),o=xB(r,t);e<=o;e=CB(e,1)){if(a.days&&!a.days.includes(W3(e)))continue;let o=SB(e,a.from,t),s=SB(a.to>a.from?e:CB(e,1),a.to,t);s>n&&o<r&&i.push({t0:o,t1:s})}}return i}function K3(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:D3(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 q3(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 J3(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 Y3(e,t){let n=K3(e??E3()),r=Object.values(n.channels),i=r.some(e=>D3(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=>D3(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 X3(e){let t=K3(e??E3()),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=>D3(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 Z3(e,t){let n=Y3(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 Q3=.2,$3=20,e6=1e5,t6=2e4,n6=1e3,r6=class{values=[];#e;#t=0;#n=p4(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)}}},i6=11,a6=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 r6(t6);#T=0;#E=0;#D=new Float64Array(i6);#O=new Float64Array(i6);#k=new Float64Array(i6);#A=0;#j=0;#M=0;#N=[];#P=new r6(e6);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<n6?(this.#l.push(e),this.#l.length===n6&&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=J2(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.#_=Q3*this.#E}#L(e){let t=e-this.#h;this.#g>=20&&t>=300&&(this.#v+=t,this.#y++,this.#b.length<$3&&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===i6,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)%i6,this.#A<i6)return;let o=e=>(this.#j+e)%i6,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<$3&&this.#N.push(this.#D[o(5)]))}result(){this.#g&&this.#L(this.#s),this.#l.length<n6&&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?J2(n):0,spikes:this.#M,spikeAt:this.#N,min:this.#t,max:this.#n,lo:q2(t,.005),hi:q2(t,.995),median:J2(t),p01:q2(t,.01),p99:q2(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 o6(e){let t=e.slice(0,Math.max(3,Math.ceil(e.length/3)));if(!t.length)return null;let n=J2(t.map(e=>e.lo)),r=J2(t.map(e=>e.hi)),i=(r-n)/2;return r>n?{lo:n-i,hi:r+i,n:t.length}:null}var s6=3600,c6=86400;function l6(e,t){let n=e.filter(e=>W2(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=H2(n,r),a=i,o=`day`;if(i.length<7&&(a=U2(n,e=>e.rec),o=`recording`,a.length<6&&(a=U2(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=u4(a.map(e=>(e.t-r)/c6),a.map(e=>e.v)),c=J2(n.map(e=>e.edge).filter(W2));return s&&c>0&&s.b!==0?{t0:r,means:a,per:o,days:i.length,fit:s,edge:c,step:u6(a,s)}:null}function u6(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 d6(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*c6,h=s+c*((r-i)/c6),g=Math.abs(h)>=o;if(!g&&(m-r)/c6>365)return null;let _=(a4(1-F2/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)*c6).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)/c6)}}}function f6(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=Q3*J2(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 ${D4(n.value)}${d} from ${G4(n.t0,n.t1,o,` to `)}, ${M4(n.rec)} of it recorded${r>1?`; ${P4(r)} in all, ${M4(m)} recorded`:``}.`}}if(a){let e=a.per===`day`?`${j4(a.b*7)}${d} a week`:`${j4(a.b)}${d} a day`,t=`over ${F4(a.days,`day`)}${a.per===`day`?``:`, ${F4(a.n,a.per)}`}`;return{...l,status:`Drifting`,since:a.points[0]?.t??null,found:`${a.past?`Offset ${j4(a.vNow)}${d} against the golden, past the band edge (${E4(a.edge)}${d}); drifting ${e} ${t}.`:`Offset drifting ${e} against the golden ${t}; reaches the band edge (${E4(a.edge)}${d}) around ${H4(a.cross,o)}.`} Check calibration or the process.`}}let g=[];c&&g.push({since:c.t,text:`Offset against the golden moved by ${j4(c.d)}${d} on ${H4(c.t,o)} and stayed there: a change, not a drift.`});let _=J2(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=J2(t);t.length>=3&&n>0&&e.h.noise/n>=1.3&&X2(e.h.noise,t)>=3&&g.push({text:`Noise up ${C4(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:`${F4(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:`${M4(x)} of gaps in ${F4(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 ${E4(_)} Hz to ${E4(C.h.rateHz)} Hz on ${H4(C.r.t0,o)}.`,since:C.r.t0}),u.length>=3){let e=o6(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]=k4(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 ${F4(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 ${E4(_)} Hz.`,since:null}}function p6(e,t){let n=e.streams.length>1;return[...V2(t,e=>e.c.streamId)].flatMap(([t,r])=>{let i=m6(e,r);return i?[{...i,text:n?`${e.streams.find(e=>e.id===t)?.name??t}: ${R4(i.text)}`:i.text}]:[]}).sort((e,t)=>(e.p??1)-(t.p??1))[0]??null}function m6(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=J2(n.map(e=>e.v)),i=n[0].t,a=H2(n.map(e=>({t:e.t,v:e.v/r*100})),i),o=r>0&&a.length>=7?u4(a.map(e=>(e.t-i)/(7*c6)),a.map(e=>e.v)):null,s=o&&o.p<.01&&o.b>0&&!u6(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=Y2(u),p=f>0?Y2(d)/f:NaN,m=null;if(Number.isFinite(p)&&p>=1.15){let e=p4(1),t=Math.min(l,m4),n=Math.sqrt(t/l),r=n=>Y2(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 ${E4(s)}% a week since ${H4(i,e.tz)}`],...h===null?[]:[`the spread of ${e.value.label} is up ${C4(h)}`]];return{text:`${L4(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 h6=e=>new Set(e.recordings.flatMap(e=>Object.entries(e.health?.channels??{}).filter(([,e])=>e.clock).map(([e])=>e)));function g6(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 _6(e,t){let n=e.recordings.filter(e=>e.health).sort((e,t)=>e.t0-t.t0),r=new Map,i=K3(e.context??E3()),a=h6(e);for(let e of Object.keys(i.channels))[`setting`,`ignore`].includes(D3(i.channels[e])??``)&&a.add(e);for(let t of g6(e))a.add(t);let o=new Map([...V2(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=V2(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})=>l6(c.get(e)??[],t)),f=c4(d.flatMap(e=>e?[e.fit.p]:[]),F2),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 f6(a,t,r,n.filter(e=>e.streamId===t),e.units[r]??``,s&&m[i]&&!c?d6(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 v6(e,t){let n=_6(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=[...V2(n.filter(e=>e.status===`Drifting`),e=>e.sid).values()].filter(e=>e.length>1),d=new Set(u.flat()),f=[...V2(n.filter(e=>e.step),t=>`${t.sid}\u0000${H4(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}: ${R4(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:B2({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 ${H4(a.cross,e.tz)}`}.`,owner:`maintenance`,urgent:a.past||a.cross-e.period.to<30*c6,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)}: `:``}${I4(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 ${H4(n.cross,e.tz)}`}.`,owner:`maintenance`,urgent:n.past||n.cross-e.period.to<30*c6,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 ${I4(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?`–`:H4(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=H4(t[0].step.t,e.tz);return{cells:[`${c?`${l(t[0].sid)} · `:``}${F4(t.length,`channel`)}`,`Watch`,`Offsets against the golden moved on ${r} and stayed there (${t.map(e=>`${e.key} ${j4(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=p6(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:B2({growPerWeek:x.grow??NaN,spreadUp:x.spread??NaN})}),i.push({text:`Inspect the machine for wear: ${R4(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`)?`${F4(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:{...S4(`05`,n.length?`${T.length?L4(I4(T)):`All ${F4(n.length,`sensor`)} healthy`}${x?`, and signs of machine wear`:``}.`:`No sensor health was measured in this period.`,r,o),subtitle:x4(`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)}`:``} (${F4(e.length,`channel`)} drifting together)`}))],wear:x}}var y6=.0027,b6=240,x6=60,S6=new Set([`mean`,`min`,`max`,`first`,`last`]),C6=(e,t)=>e.length<=t?e:Array.from({length:t},(n,r)=>e[Math.round(r*(e.length-1)/(t-1))]);function w6(e,t){let n=e.context,r=new Set([...g6(e),...h6(e)]),i=e=>{let t=e.lastIndexOf(`:`),i=e.slice(0,t),a=D3(n?.channels[i]);return t>0&&S6.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 V2(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 W2(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=>`${X4(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<=b6?l.pts:C6(l.pts,b6-x6),p=new Set(f),m=l.pts.length<=b6?[]:C6(l.pts.filter(e=>e.out&&!p.has(e)),x6);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)}: ${F4(t.out,`batch`,`batches`)} of ${t.n.toLocaleString(`en-GB`)} (${w4(100*t.out/t.n)}) outside its control limits, ${E4(t.lcl)} to ${E4(t.ucl)}${c(t)}, the first on ${H4(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)}: ${F4(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 T6(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 E6(e,t){let n=K3(e.context??E3()),r=e.tz,{from:i,to:a}=e.period,o=Object.keys(n.channels).filter(e=>D3(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 V2(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*J2(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([...V2(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=T6(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=J2(i),c=J2(a),l=o?$2(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=c4(p.map(e=>e.enough?e.p:1),F2),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=U4(e.t,r),[a,o]=O4(e.a,e.b),[s,c]=O4(e.mb,e.ma);_.set(t,n),h.push({id:n,section:`08`,refs:[`08`],evidence:`statistical`,p:e.p,numbers:B2({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]=O4(e.a,e.b);return{t:e.t,row:{cells:[U4(e.t,r),e.ch,n,i,e.enough?`${j4(e.ma-e.mb)} (${Z4(e.p)})`:`Too few batches to tell`],..._.has(t)?{finding:_.get(t),...e.worse?{status:`watch`}:{}}:{}}}}),...s.map(e=>({t:e.t,row:{cells:[U4(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 ${U4(e.t,r)}; every batch in this report is judged against the current one.`);return{section:S4(`08`,h.length?`${F4(d.length,`setting change`)} in the period; ${h.length} ${h.length===1?`was`:`were`} followed by a different ${v}.`:d.length?`${F4(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 D6(e,t,n=_6(e,t)){let r=new Map([...V2(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=T6(i,n);for(;a<i.length&&i[a].c.tstart===n;)a++;return i.slice(T6(i,t),a)},a=V2(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,U4(e.t0,c),U4(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:`${F4(e.xs.length,`batch`,`batches`)} ${e.xs.length===1?`was`:`were`} made while ${e.s.ch} `+(e.stuck?`was stuck (from ${G4(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 ${G4(e.t0,e.t1,c,` to `)}. Check them before they ship.`)})),actions:s.map((e,t)=>({text:`Check the ${F4(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 O6={Wh:.001,kWh:1,MWh:1e3},k6=`Scope 2, location-based, factor entered by you`;function A6(e,t){let n=O6[(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 j6(e,t){let n=e.context,r=O3(n);if(!n||!r)return null;let i=t.filter(e=>W2(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=J2(c),u=c.reduce((e,t)=>e+t,0),d=A6(e,r),f=d!==null&&d>=u?d:u,p=[],m=[],h=(e.previous?.cycles??[]).map(e=>e.kwh).filter(e=>W2(e)&&e>=0),g=h.length>=5?J2(h):NaN,[_,v]=O4(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 (${j4(b)}%)`:``,S=[...a===null?[]:[T4(l*a,o)],...s===null?[]:[`${E4(l*s)} kg CO₂ (${k6})`]];p.push({id:`F09-1`,section:`09`,refs:[`09`],evidence:`measured`,p:null,numbers:B2({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 `)}`:``}; ${E4(f)} kWh in the period${f>u?`, ${E4(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?``:` (${T4(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:`${E4(e.kwh)} kWh${D(e.kwh)}`,tip:`${e.label}: ${C4(e.kwh/f)} of the period’s energy`}))}),C.length>=5&&w.length>=5){let e=J2(C),t=J2(w),n=$2(C,w);if(n.p<.01&&e>t&&t>0){T=!0;let r=(e-t)*C.length,[s,c]=O4(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:B2({off:e,rest:t,extra:r,p:n.p}),text:`Off-golden batches use ${w4((e-t)/t*100)} more energy than the rest: ${E4(r)} kWh${a===null?``:`, up to ${T4(r*a,o)}`}, in the period.`}),m.push({text:`Bring off-golden batches to golden level (see 02) to save up to ${E4(r)} kWh${a===null?``:` (${T4(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:{...S4(`09`,`${a===null?`${E4(f)} kWh`:`${T4(f*a,o)} of energy`} in the period${T?`; off-golden batches use more`:``}.`,p,E),subtitle:x4(`Energy review inputs (ISO 50001)`),fold:!0},actions:m,next:[],numbers:{kwh:l}}}var M6=1800,N6=2400,P6=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],F6=[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`],I6=e=>`${String(e%24).padStart(2,`0`)}:00`,L6=(e,t)=>e.c.z?.[t.ch]?.[t.piece];function R6(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 z6(e,t){let n=f4(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 B6(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=R6(u).map(e=>{let t=u.filter(t=>W2(L6(t,e)));return{f:e,mw:$2(d.map(t=>L6(t,e)).filter(W2),f.map(t=>L6(t,e)).filter(W2)),r:l4(t.map(t=>L6(t,e)),t.map(e=>e.gap))}}),t=c4(e.map(e=>e.mw.p),F2),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=>W2(L6(e,t.f)))),c=o.map(e=>n.map(t=>L6(e,t.f))),l=o.map(e=>e.gap),m=n.length?z6(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=h4(o.length,e=>z6(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 (${F4(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:C4(m.shares[e]),tip:`${n[e].f.label} goes with ${C4(m.shares[e])} of the difference in how far batches are from the golden`})),{label:`Not explained by the recorded channels`,value:g,text:C4(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 ${C4(p.share)} of the difference in how far batches are from the golden${h.length>1?`; the ${h.length} differences together go with ${C4(m.r2)}`:``}.`,evidence:`correlation`,p:u.mw.p,numbers:B2({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 ${C4(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(`${C4(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 V2(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=s4(l(h),h.length,l(g),g.length);if(e.p<.01&&e.p1>e.p2){let n=s({text:`Off-golden share is ${C4(e.p1)} in the first ${N6/60} minutes after a stop of more than ${M6/60} minutes, against ${C4(e.p2)} the rest of the time.`,evidence:`statistical`,p:e.p,numbers:B2({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 ${M6/60} minutes: the first ${N6/60} minutes after a stop run ${C4(e.p1)} off-golden against ${C4(e.p2)}.`,owner:`production`,urgent:!1,rank:(e.p1-e.p2)*(h.length/t.length),refs:[n]})}}let _=(e,n,r=t)=>{let i=V2(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:s4(l(t),t.length,a-l(t),r.length-t.length)})),s=c4(o.map(e=>e.t.p),F2),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 ${C4(v.t.p1)} off-golden against ${C4(v.t.p2)} on the other streams.`,evidence:`statistical`,p:v.t.p,numbers:B2({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 ${C4(y.t.p1)} off-golden against ${C4(y.t.p2)} in the rest of the period.`,evidence:`statistical`,p:y.t.p,numbers:B2({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=H2(t.map(e=>({t:e.c.tstart,v:e.gap})),n),i=r.length>=7?u4(r.map(e=>(e.t-n)/86400),r.map(e=>e.v)):null;if(i&&i.p<.01&&i.b!==0){let a=N4(e),o=a?` ${a}`:``,c=r[r.length-1].t;s({text:`The gap to the golden ${i.b>0?`grows`:`shrinks`} by ${E4(Math.abs(i.b)*7)}${o} a week since ${H4(n,e.tz)}.`,evidence:`statistical`,p:i.p,numbers:B2({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=q4(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,U3(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 ${I6(+C.k)} and ${I6(+C.k+1)}`,other:`at other hours`,look:`Find what changes around ${I6(+C.k)} (a shift change, a start-up, a material change)`}]:[],...w?[{w,when:`on ${F6[+w.k]}s`,other:`on other days`,look:`Find what is different on ${F6[+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 ${C4(e.t.p1)} off-golden against ${C4(e.t.p2)} ${i}.`,evidence:`statistical`,p:e.t.p,numbers:B2({share:e.t.p1,others:e.t.p2,p:e.t.p})},o);r.push({text:`${a}: batches then run ${C4(e.t.p1)} off-golden against ${C4(e.t.p2)}.`,owner:`production`,urgent:!1,rank:o,refs:[c]})}if(O.length){let e=P6.map(()=>Array(24).fill(0)),n=P6.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:P6,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?`${C4(k)} of batches miss the golden. ${p.label} goes with most of the difference between them and the golden.`:`${C4(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:{...S4(`02`,A,n,a),fold:!0},actions:r,next:i,numbers:{off:c.length,share:k}}}function V6(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=V2(t.filter(e=>r.has(e.c.streamId)),e=>r.get(e.c.streamId)),a=e=>({section:S4(`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:s4(n,t.length,s-n,o.length-t.length)}}),l=c4(c.map(e=>e.t.p),F2),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:B2({share:e.t.p1,others:e.t.p2,p:e.t.p,batches:e.xs.length}),text:`${e.name} runs ${C4(e.t.p1)} off-golden against ${C4(e.t.p2)} on the other lines.`}),u(e)&&p.push({text:`Find what ${e.name} does differently from the other lines: it runs ${C4(e.t.p1)} off-golden against ${C4(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`),C4(1-e.t.p1),C4(e.better/e.xs.length)],...t?{finding:t,status:u(e)?`crit`:`ok`}:{}}})}],g=d.filter(u),_=e=>I4(e.slice(0,2).map(e=>e.name))+(e.length>2?` and ${F4(e.length-2,`more line`)}`:``);return{section:S4(`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 H6(e,t){let n=K3(e.context??E3()).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?T4(o(e.s),i):M4(e.s),detail:a?`${M4(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:T4(u,i),detail:`${E4(t.energyKwh)} kWh more than batches at golden level`});let d=n.scrap,f=d===null?``:`${T4(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?F4(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?T4(o(m)+h,i):m?M4(m):T4(h,i),detail:`${e} outside their limits or flagged bad: ${[m?`${M4(m)} of line time`:``,h?`${T4(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 ${T4(p.money,i)}`,detail:`${F4(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=F4(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 ${T4(o(t.review.s),i)}`:e,detail:`${a?`${e}, `:``}${M4(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 ${T4(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 ${F4(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 ${T4(y,i)}`:v?M4(v):_[0].amount:`Nothing lost`,totalNote:b?a?`to recover in this period${v?`: ${M4(v)} of line time`:``}`:`of line time to recover in this period`:`against the golden in this period`,...S?{hint:S}:{}}}var U6=86400;function W6(e,t,n){if(!t.length&&!n)return null;let r=K3(e.context??E3()),i=e.tz,a=e.period.to,o=r.stops.length?G3(r,i,a,a+90*U6).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`:J4(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 ${C4(n.spread)}`:`cycle time ${j4(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?`–`:H4(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 ${F4(c.length,`maintenance job`)}${l.now?`: the first now`:u?`: the first by ${H4(u.by,i)}`:``}.`}],actions:[],notes:[],next:o?[]:[`Add planned stops in Process context to place maintenance in them.`]}}var G6=()=>({findings:[],charts:[],notes:[],actions:[],next:[]});function K6(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 q6=7200,J6=e=>e.reduce((e,t)=>e+t.t1-t.t0,0),Y6=(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 X6(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 Z6(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 Q6(e,t,n,r){let i=Y6([{t0:n,t1:r}],[{t0:e.period.from,t1:e.period.to}]);return i.length?(t.shifts.length&&(i=Y6(i,X6(G3({...t,stops:t.shifts.map(e=>({name:e.name,from:e.start,to:e.end}))},e.tz,n,r)))),t.stops.length?Z6(i,G3(t,e.tz,n,r)):i):i}function $6(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*J2(n):0)}function e8(e){return t8(e).stops}function t8(e){let t=K3(e.context??E3()),n=[],r=0,i=V2(e.cycles,e=>e.recordingId),a=V2(e.covered??[],e=>e.streamId);for(let[o,s]of V2([...e.recordings].sort((e,t)=>e.t0-t.t0),e=>e.streamId)){let c=$6(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?J6(Q6(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=Q6(e,t,r.t0,r.t1),o=J6(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 n8(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?{...G6(),next:r}:null;let i=K3(e.context??E3()),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+J6(Q6(e,i,n.t0,n.t1)),0)+J6(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=J6(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=[...V2(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=[...V2(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 ${M4(e.stopped)}.`:`${a(e.sid)} stopped ${P4(e.n)} for ${M4(e.stopped)} in total; it ran ${M4(e.mtbf)} between stops on average and took ${M4(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?[...V2(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: ${F4(m.n,`stop`)} cost ${M4(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),M4(e.stopped),M4(e.mtbf),M4(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 r8=new Set([`mean`,`min`,`max`,`first`,`last`]),i8=()=>({plan:0,stop:0,ideal:0,n:0,good:0,badIdeal:0}),a8=e=>Math.max(0,e.plan-e.stop),o8=e=>{let t=a8(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 s8(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 V2(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?J2(t):NaN)}let t=n.map(e=>e.c).sort((e,t)=>e.tstart-t.tstart),i=$6(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)+q2(a,I2))}return r}function c8(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&&r8.has(e.slice(i+1))&&(n.usl!==null&&r>n.usl||n.lsl!==null&&r<n.lsl)}))}}var l8=x4(`OEE as ISO 22400-2`),u8={stops:`Stops`,slow:`Slow batches and short waits`,bad:`Bad parts`,off:`Off-golden batches`};function d8(e,t,n=[]){let r=e.context;if(!r?.shifts.length)return null;let i=e.tz,a=e.recordings,o=a.length?G3(r,i,Math.min(...a.map(e=>e.t0)),Math.max(...a.map(e=>e.t1))):[],s=s8(e,t),c=i8(),l=new Map,u=new Map,d=(e,t)=>e.get(t)??e.set(t,i8()).get(t),f=(e,t)=>{let n=U3(e,r.shifts,i);if(n!==null)for(let r of[c,d(l,n),d(u,xB(e,i))])t(r)},p=e=>({section:S4(`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}=c8(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=o8(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?`${E4(+e.toFixed(1))} s`:M4(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 ${T4(e/3600*S,x)})`,D=[{label:u8.stops,s:c.plan-a8(c),owner:`maintenance`,act:e=>`Find what stops the line (see 05.4): ${e} of planned time stopped.`},{label:u8.slow,s:Math.max(0,a8(c)-c.ideal),owner:`production`,act:e=>`Bring the pace to the ideal cycle: slow batches and short waits cost ${e}.`},g?{label:u8.bad,s:c.badIdeal,owner:`quality`,act:e=>`Bring the bad parts inside their limits (see 04): they cost ${e}.`}:{label:u8.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:B2({oee:b.oee,availability:b.A,performance:b.P,quality:b.Q,plannedH:c.plan/3600}),text:`OEE ${C4(b.oee)}: availability ${C4(b.A)}, performance ${C4(b.P)}, quality ${C4(b.Q)}, over ${M4(c.plan)} of planned time.${T?` ${T}`:``}`}),k.s>0){let e=N({evidence:`measured`,p:null,numbers:B2({hours:k.s/3600,share:k.s/O,cost:S===null?NaN:k.s/3600*S}),text:`${k.label} lose the most: ${M4(k.s)}${E(k.s)}, ${C4(k.s/O)} of the ${M4(O)} lost.`});j.push({text:k.act(`${M4(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=o8(t);return{cells:[e.name,C4(n.A),t.n?C4(n.P):`–`,t.n?C4(n.Q):`–`,C4(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:`${M4(e.s)}${E(e.s)}`,tip:`${e.label}: ${C4(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:SB(e,`00:00`,i),v:o8(t).oee})).sort((e,t)=>e.t-t.t),I=F.length>=7?u4(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:B2({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 ${H4(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:{...S4(`06`,L,A,M),subtitle:l8,fold:!0},actions:j,next:R,numbers:{oee:b.oee,stopsS:c.plan-a8(c),slowS:Math.max(0,a8(c)-c.ideal),offS:c.badIdeal}}}function f8(e,t,n,r=[]){let i=K3(e.context??E3()).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=U3(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||s4(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 (${C4(u.share)} against ${C4(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:S4(`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?C4(e.share):`–`,M4(e.stopped),String(e.alerts)],...g&&e===u?{status:`watch`,finding:`F11-1`}:{}}))}]),actions:[],next:[],numbers:g?{share:u.share,others:m}:{}}}function p8(e,t,n=[],r,i=e8(e)){let a=e.previous,o=a?{...e,period:a.period,recordings:a.recordings,cycles:a.cycles,previous:null}:null,s=o?z2(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=s4(c(t),t.length,c(s),s.length),u=e=>e.map(e=>e.c.value),d=J2(u(t)),f=J2(u(s)),p=$2(u(t),u(s)),[m,h]=c4([l.p,p.p],F2),g=e.value.label,[_,v]=O4(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:B2({share:l.p1,before:l.p2,p:l.p}),text:`${C4(l.p1)} of batches at golden level or better, ${e?`up`:`down`} from ${C4(l.p2)} the period before.`}),w.push({better:e,text:`${C4(l.p1)} of batches at golden level, ${e?`up`:`down`} from ${C4(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:B2({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=`${H4(a.period.from,E)} – ${H4(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=_6(e,t))=>n.filter(e=>e.status===`Replace`||e.status===`Drifting`).length,M=A(i),N=A(e8(o));return{section:S4(`01`,k,x,[{kind:`tiles`,tiles:[{label:`At golden level or better`,value:C4(l.p1),note:`${C4(l.p2)} before`},{label:`${g} median`,value:_,note:`${v} before`},{label:`Stopped`,value:M4(M),note:`${M4(N)} before`},{label:`Sensors to replace or drifting`,value:String(j(e,t,r)),note:`${j(o,s)} before`}]}]),actions:T,next:[],numbers:B2({share:l.p1,before:l.p2,median:d,medianBefore:f,stoppedS:M,stoppedBeforeS:N})}}function m8(e,t,n,r){let{tz:i}=e,a=xB(e.period.from,i),o=xB(e.period.to-1,i),s=[];for(let e=a;e<=o&&s.length<=400;e=CB(e,1))s.push(e);if(s.length<2||s.length>400||!t.length)return null;let c=e=>s.indexOf(xB(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=>[SB(e,`00:00`,i),SB(CB(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=`${K4[(n.getUTCDay()+6)%7]} ${n.getUTCDate()} ${n.toLocaleString(`en-GB`,{month:`short`,timeZone:`UTC`})}`,i=[l[t]?`${F4(l[t],`batch`,`batches`)}, ${C4(u[t]/l[t])} off the golden`:`no batches`,...d[t]>=60?[`stopped ${M4(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 h8={management:`Management`,quality:`Quality`,maintenance:`Maintenance`,production:`Production`},g8=e=>e.findings.length||e.id===`01`?e:{...e,charts:[],notes:[]},_8=(e,t)=>{let n=t.filter(e=>!!e);return{...e,section:K6(g8(e.section),n),actions:[...e.actions,...n.flatMap(e=>e.actions)],next:[...e.next,...n.flatMap(e=>e.next)]}},v8=e=>({cells:[e.id,e.text,h8[e.owner]],...e.urgent?{status:`crit`}:{}});function y8(e){let t=g6(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 b8(e){let t=z4(e.tz)?e:{...e,tz:`UTC`},n=y8(t.context?{...t,context:K3(t.context)}:t),r=z2(n),i=B6(n,r),a=a3(n,r),o=v6(n,r),{stops:s,offGaps:c}=t8(n),l=n8(n,s,c),u=_8(o.out,[l,W6(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=g8(i.section),m=g8(a.section),h=g8(f.section),g=l3(n,r),_=D6(n,r,o.sensors),v=g===null?w6(n,r):null,y=_?`${F4(_.findings.reduce((e,t)=>e+t.numbers.batches,0),`batch`,`batches`)} to check before they ship: made while a sensor was failing.`:v?`${F4(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)?_8(g,[_]):[g,_8({section:{...S4(`04`,y,[],[]),fold:!0,subtitle:x4(_?`Containment: batches made while a sensor was failing`:`Control chart (Shewhart individuals, 3σ)`)},actions:[],next:[],numbers:{}},[_,v])],x=E6(n,r),S=[p8(n,r,x&&!(`needs`in x)?x.section.findings:[],o.sensors,s),b,d8(n,r,s),t3(n,r),x,j6(n,r),V6(n,r),n.context?.hideShifts?null:f8(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=>g8(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=S4(`12`,D.length?`Start with ${I4(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(v8),...D.length>5?{shown:5,more:F4(D.length-5,`more action`)}:{}}]:[]),A=[...new Set([...i.next,...a.next,...f.next,...C.flatMap(e=>e.next)])],j=S4(`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=c8(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=H6(n,{time:R&&`slowS`in R?[{label:u8.stops,s:R.stopsS,owner:h8.maintenance,ref:`06`},{label:u8.slow,s:R.slowS,owner:h8.production,ref:`06`},n.value.key===`duration`?{label:u8.bad,s:R.offS,owner:h8.quality,ref:`06`,bad:!0}:{label:u8.off,s:R.offS,owner:h8.quality,ref:`06`}]:[{label:`Stops`,s:s.reduce((e,t)=>e+t.t1-t.t0,0),owner:h8.maintenance,ref:`05`},{label:`Batches slower than the golden`,s:I,owner:h8.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=m8(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=S4(`00`,r.length?`${C4(M/r.length)} of batches at golden level or better${N?`, and ${F4(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(v8),ref:`12`}]:[],...V?[V]:[],{kind:`tiles`,tiles:[{label:`Batches`,value:r.length.toLocaleString(`en-GB`),note:F4(n.recordings.length,`file`)},{label:`At golden level or better`,value:r.length?C4(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=S4(`14`,`How the findings were made and how sure each one is.`,[],[],[`Cycles found with “${n.rule.name}” v${n.rule.version} in ${F4(n.recordings.length,`recording`)} of ${F4(n.streams.length,`stream`)}, ${C4(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 ${F4(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 ${q6/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 ${s6/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}. ${o3}`]:[],...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*y6*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 ${$4/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=h6(n),ce=Object.keys(n.units).filter(e=>!se.has(e)).length;return{v:1,cover:{title:`Report ${H4(n.period.from,n.tz)} – ${H4(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:`${F4(n.streams.length,`stream`)} · ${F4(n.recordings.length,`file`)}${ce||!ie?` · ${F4(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([...Y3(n.context??null,n.alertRules?.length??0),...w].map(e=>[`${e.section} ${e.needs}`,e])).values()].map(e=>({section:e.section,title:v4[e.section],needs:e.needs})).sort((e,t)=>e.section.localeCompare(t.section))}}function x8(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 S8(e,t){return t===`full`?e.sections:e.sections.filter(e=>e.roles.includes(t))}var C8={verdict:30,sentence:35,action:30},w8={verdict:250,sentence:300,action:250},T8=/\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,E8=/\b(\d{1,2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?/gi,D8=e=>e.normalize(`NFKC`).replace(/−/g,`-`),O8=e=>T8.test(D8(e))||/(?![0-9])\p{Nd}/u.test(D8(e)),k8=e=>{let t=D8(e),n=[];return t=t.replace(E8,(e,t,r)=>(n.push(`${+t} ${r.toLowerCase()}`),` `)),[...n,...(t.match(/[-+]?(?:\d[\d,]*)?\.?\d+%?/gu)??[]).map(e=>e.replace(/,/g,``))]},A8=e=>!!e&&typeof e==`object`&&!Array.isArray(e),j8=e=>Array.isArray(e)?e.filter(A8):[];function M8(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(!A8(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||O8(o))return null;let c=new Set([...r,...a?s.map(e=>n.get(e)):[]].flatMap(k8));return k8(o).every(e=>c.has(e))?{text:o,cites:s}:null},i=e=>({words:C8[e],chars:w8[e]}),a=A8(t)?t:{},o=new Map(j8(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(j8(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 N8=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 P8(e,t){let n=t?K3(t):null;return{process:n?.process??``,channels:Object.entries(n?.channels??{}).flatMap(([e,t])=>{let n=D3(t);return n&&n!==`ignore`?[{name:e,role:C3[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:Q4(e),refs:e.refs}))})),actions:e.actions.map(e=>({id:e.id,text:e.text,owner:e.owner,refs:e.refs}))}}function F8(e,t,n){let r=M8({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),N8(n)]}:e);return{...e,cover:{...e.cover,ai:n},sections:u,actions:a}}var I8=.5,L8=5400,R8=/^[kM]?Wh?$/,z8=86400/300,B8=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],V8=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`)}`},H8=(e,t)=>Math.round(e/t)*t;function U8(e){if(!e.length)return null;let t=J2(e.map(e=>e.p01??e.lo)),n=J2(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 W8(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 G8(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=bB(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 K8(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=>B8[e]).join(`, `)}`,from:`00:00`,to:`00:00`,days:i}}function q8(e){let t={shifts:[],stops:[]};if(e.size<3)return t;let n=Array.from({length:z8},(t,n)=>[...e.values()].filter(e=>e.has(n)).length/e.size),r=n.map(e=>e>=I8),i=[],a=r.indexOf(!0);if(a<0)return t;for(let e=0;e<z8;e++){let t=(a+e)%z8;if(r[t])continue;let n=i[i.length-1];n&&(n.a+n.n)%z8===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>L8);for(let e of i.filter(e=>e.n*300<600))for(let t=0;t<e.n;t++)r[(e.a+t)%z8]=!0;let c=i.filter(e=>e.n*300>=600).flatMap(e=>Array.from({length:e.n},(t,r)=>n[(e.a+r)%z8])),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)%z8*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=H8(t.a,900),n=H8(t.b,900);n>e&&m.push({name:`Break`,from:V8(e),to:V8(n)})}let i=n.map(e=>H8(r(e),1800)),a=f?i:[H8(e.a,1800),...i,H8(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:H8(e.a+r*t/n,1800),b:H8(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:V8(e.a),end:V8(e.b)})),stops:m}}function J8(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 Y8(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 X8(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 Z8(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=U8(r.filter(e=>e.moves!==!1));e&&(n[t]=e)}let r=G8(W8(e.recordings),e.tz),i=q8(r),a=K8(r);return{units:t,ranges:n,energy:Object.keys(t).filter(e=>R8.test(t[e].trim())).sort(),settings:X8(e.health,e.recordings.reduce((e,t)=>e+t.batches.length,0)),shifts:i.shifts,stops:[...i.stops,...a?[a]:[]],lines:J8(e.streams),machines:Y8(Object.keys(t))}}function Q8(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]=T3(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 $8(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 e5=Lt({AI_NOTE:()=>N8,AI_SENTENCES:()=>2,AI_WORDS:()=>C8,ALPHA:()=>F2,CHANNEL_ROLES:()=>S3,CHANNEL_ROLE_TEXT:()=>C3,EVIDENCE_TEXT:()=>_4,GOLDEN_SHARE:()=>I2,HealthAcc:()=>a6,MIN_GROUP:()=>5,OFF_GOLDEN_PCT:()=>2,PRESETS:()=>d3,PRESET_IDS:()=>u3,PROCESS_MAX:()=>w3,REPORT_ROLES:()=>g4,SECTION_ROLES:()=>b4,SECTION_TITLES:()=>v4,aiInput:()=>P8,applyAi:()=>F8,applyInferred:()=>Q8,applyPreset:()=>x3,assumedSections:()=>$8,buildReport:()=>b8,classify:()=>z2,completeness:()=>Z3,confirmAll:()=>J3,confirmed:()=>K3,contextGaps:()=>Y3,dateText:()=>H4,dateTimeText:()=>U4,emptyChannel:()=>T3,emptyContext:()=>E3,energyChannel:()=>O3,evidenceLabel:()=>Q4,exact:()=>D4,goldenRank:()=>L2,inferContext:()=>Z8,listedFindings:()=>x8,moneyGaps:()=>X3,namesOf:()=>v3,num:()=>E4,pText:()=>Z4,parseContext:()=>B3,pct1:()=>w4,presetForIndustry:()=>p3,presetOf:()=>f3,roleOf:()=>D3,shiftOf:()=>U3,spanText:()=>G4,stopSpans:()=>G3,suggestedCount:()=>q3,term:()=>_3,usualRange:()=>o6,viewSections:()=>S8});export{cQ as ANNOTATION_CONTROLS_ATTR,Bt as ANNOTATION_KINDS,u1 as AxisState,TB as BEACON_STATS,y2 as BrowserRecorder,j0 as CAMERA_QUALITIES,He as CHAIN_LIVE,Ne as CHAIN_RECORDING,S3 as CHANNEL_ROLES,C3 as CHANNEL_ROLE_TEXT,fr as CHART_ALARM_FIELDS,x$ as CHART_KINDS,KB as CYCLE_TIME,V0 as CameraSender,xe as ChainLane,zB as CycleRunner,BB as CycleSet,Xt as DASHBOARD_GRID_COLS,Qt as DASHBOARD_GRID_GAP_PX,Zt as DASHBOARD_GRID_ROWS,iB as DATASET_PALETTE,Vt as DEFAULT_ANNOTATION_WIDTH,pn as DEFAULT_AXIS_LINE,hn as DEFAULT_BEACON,mn as DEFAULT_GRID_LINE,wn as DEFAULT_TRACE_WIDTH,Cn as DEFAULT_XYZ_POINT_RADIUS,Sn as DEFAULT_XY_POINT_RADIUS,_4 as EVIDENCE_TEXT,M2 as EXPORT_TYPES,PT as FUNCTION_REFERENCE,a6 as HealthAcc,jV as IMPORTABLE_EXT,P as KIND_CHAIN,l as KIND_VIDEO,pB as KPI_STATS,ze as KRC_HEADER_BYTES,wB as KpiAcc,UE as KymoscopeError,mt as LEAF_KEYS,n as LIVE_TIME_COLUMN,M0 as LOW_PRESET,A0 as LivePublisher,o1 as MAX_BAND_CELLS,a1 as MAX_GRID,tr as MAX_PANEL_CAMERAS,nn as MIN_PANEL_H,tn as MIN_PANEL_W,I as OPEN_STREAM_PASSWORD,d3 as PRESETS,u3 as PRESET_IDS,w3 as PROCESS_MAX,g4 as REPORT_ROLES,i0 as RecordedVideoSource,E0 as RegistryError,v4 as SECTION_TITLES,qt as SEVERITY_HEX,a0 as SPLIT_STEPS,z1 as UNLIMITED,UX as VIDEO_LIMIT_NOTICE,z$ as VIDEO_MAX_FRAGMENT,uE as WINDOW_FN_NAMES,B as WORKBOOK_EXPORT_AAD,P8 as aiInput,p as alertEventAad,v as alertRuleAad,d1 as alignSegment,e5 as analysis,F8 as applyAi,Q8 as applyInferred,x3 as applyPreset,dn as arrangeAutoLayout,s1 as axisColumn,v1 as bandEdges,jB as bestCycleIndex,Ge as bindKeyAad,c2 as bufferLabel,pG as buildEquation,FE as buildMathChannelsBlob,m1 as buildReference,b8 as buildReport,NV as buildTree,$n as cameraLabel,ne as chainVerifier,pr as chartAlarm,Pz as chartChannelCount,C$ as chartLabel,vr as clampPct,an as clampRectForKind,lr as coerceAlarmLine,Gt as coerceAnnotation,wX as colorAt,aB as colorForDataset,uB as colorSchemeOf,DX as colorsCss,Le as columnIsNumeric,hB as compareOp,y1 as compareToReference,Z3 as completeness,uG as computePolyFit,dG as computeR2,J3 as confirmAll,K3 as confirmed,Z1 as createEngine,ft as createRuleEvaluator,eV as cutCycle,RB as cycleRuleChannels,nV as cycleTables,DB as cyclicChannels,x1 as decodeBand,nt as decodeChain,H$ as decodeVideo,OZ as decorateColumnLabel,Wn as defaultAreaChartPanelSettings,Hn as defaultBarChartPanelSettings,jn as defaultBoxPlotPanelSettings,Kn as defaultBubbleChartPanelSettings,Xn as defaultCalibrationPanelSettings,er as defaultCameraPanelSettings,Gn as defaultCdfChartPanelSettings,Fn as defaultConfusionPanelSettings,Rn as defaultControlChartPanelSettings,oB as defaultDatasetPalette,Bn as defaultEmbeddingPanelSettings,Vn as defaultFlameGraphPanelSettings,Qn as defaultGanttPanelSettings,Yn as defaultGaugePanelSettings,Nn as defaultHeatmapPanelSettings,On as defaultHistogramPanelSettings,Ln as defaultLossCurvePanelSettings,Tn as defaultMultibandPanelSettings,zn as defaultParallelCoordsPanelSettings,kn as defaultPolarPanelSettings,Zn as defaultQQPlotPanelSettings,Un as defaultRadarPanelSettings,In as defaultRocPanelSettings,Jn as defaultSankeyPanelSettings,Mn as defaultSpectrogramPanelSettings,An as defaultSpectrumPanelSettings,l0 as defaultSplit,qn as defaultTreemapPanelSettings,Pn as defaultViolinPanelSettings,fn as defaultXyAxisScaleSettings,En as defaultXyPanelSettings,Dn as defaultXyzPanelSettings,XB as definitionChannels,_ as deriveKey,ee as deriveRawKeyBase64,V as deviceFingerprint,on as dragLayout,T3 as emptyChannel,E3 as emptyContext,b1 as encodeBand,ct as encodeChain,V$ as encodeVideo,sV as encryptWorkbookFile,O3 as energyChannel,gr as ensurePanelSettingsForPanels,hE as evalChannel,fB as eventWithin,Q4 as evidenceLabel,P2 as exportRecording,N2 as exportRecordingTo,pE as extractFreeIdentifiers,O0 as fetchUsage,YB as findCycles,nB as formatClockTick,rB as formatClockValue,NB as formatLapValue,c0 as formatSplit,U$ as fragmentVideo,te as generateApiToken,O as generateDeviceKeyPair,e as generateRecoveryKeyPair,he as generateSalt,eB as getClockTimeZone,U as getRawNonEmptyLines,p1 as gridAt,OB as guessBeaconChannel,$e as hashToken,Re as importStreamKey,Z8 as inferContext,Be as inferParseConfig,Kz as isClockAxis,MV as isImportable,DZ as isMathChannelName,ZB as kpiColumn,mB as kpiKey,QB as kpisOf,x8 as listedFindings,S0 as liveBytesPerSec,S1 as liveSegmentTracker,xB as localDay,l1 as localSeconds,Je as makeKeyCheck,Yt as markToAnnotation,X3 as moneyGaps,v3 as namesOf,yn as newGaugeItem,br as newMathChannel,ln as newPanel,gB as newResetState,oe as newRun,yr as newSeriesId,Fz as niceMajorStep,dB as observeColorScheme,wR as openDatasetFromText,s as openMessage,xz as openSession,Te as openUnderProjectKey,ae as openWithKey,Ve as openWithPassword,nr as panelCameras,Xe as parseColumnNames,le as parseConfigsEqual,B3 as parseContext,GB as parseCycleDefinitions,et as parseDatasetWithConfig,fE as parseFormula,ce as parseKrc,Ae as parseKrcHeader,LE as parseMathChannelsFile,xn as parseOptionalAxisRange,hr as parsePanelChartSettingsMap,Ze as parseRecoveryCode,s0 as parseSplit,_1 as pooledSd,p3 as presetForIndustry,f3 as presetOf,EX as presetStops,ue as projectConfigKeyAad,Me as projectWrapAad,tt as randomKey,JB as readSource,Ie as recordingKeyAad,Ke as recordingKeySealAad,pe as recoveryAttestationAad,ve as recoveryCode,We as recoveryKeyAad,Fe as recoveryPrivateKey,CZ as referenceBands,f1 as resample,_B as resetStep,dr as resolveLinkedAlarms,D3 as roleOf,rV as rowsCsv,w as sealMessage,Se as sealUnderProjectKey,be as sealWithKey,re as sealWithPassword,rt as senderBindKey,lt as senderBinding,$z as setClockTimeZone,CB as shiftDay,se as splitApiKey,EB as splitLaps,st as streamKeyAad,fe as subsampleIndices,tB as subscribeClockTimeZone,kB as suggestBeacon,q3 as suggestedCount,_3 as term,ht as thresholdOf,bB as tzOffsetS,N as unwrapForDevice,o as unwrapStreamKey,pt as validateRule,at as verifyKeyCheck,UV as verifyLicense,F as verifySenderBinding,S8 as viewSections,u as workbookBodyAad,iV as workbookExportAad,lV as workbookFileInfo,c as workbookKeyAad,T as wrapForDevice,SB 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=e4(await Q2(this.body||``))}return e}};async function Z2(e,t){let n=await crypto.subtle.importKey(`raw`,typeof e==`string`?K2.encode(e):e,{name:`HMAC`,hash:{name:`SHA-256`}},!1,[`sign`]);return crypto.subtle.sign(`HMAC`,n,K2.encode(t))}async function Q2(e){return crypto.subtle.digest(`SHA-256`,typeof e==`string`?K2.encode(e):e)}var $2=[`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`a`,`b`,`c`,`d`,`e`,`f`];function e4(e){let t=new Uint8Array(e),n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=$2[r>>>4&15],n+=$2[r&15]}return n}function t4(e){return e.replace(/[!'()*]/g,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase())}function n4(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[q2[a]||a,o||``]}var r4=1e4,i4=2e3,a4=1e4,o4=6e4,s4=2e3,c4=6e4,l4=`rec`,u4=`meta.json`,d4=e=>Math.min(c4,Math.max(s4,e*2)),f4=e=>e>=1024?`${+(e/1024).toFixed(2)} GB`:`${e} MB`,p4=e=>e.replace(/(https?:\/\/[^\s?#'"]*)\?[^\s#'"]*/g,`$1`),m4=class extends Error{status;constructor(e,t){super(p4(e)),this.status=t}},h4=e=>e instanceof m4?void 0:e?.status,g4=e=>e?.code??String(h4(e)??`error`),_4=e=>`${String(e).padStart(8,`0`)}.krc`,v4=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},y4=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``);async function b4(e,t,n){let r=await(await e.getFileHandle(t,{create:!0})).createWritable();await r.write(n),await r.close()}async function x4(e,t){try{return JSON.parse(await(await(await e.getFileHandle(t)).getFile()).text())}catch{return null}}function S4(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 C4=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?m2(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?i4:r4)}root(){return this.rootDir??=(async()=>(this.opts.root?await this.opts.root():await navigator.storage.getDirectory()).getDirectoryHandle(l4,{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 S4(this.locks,`kymoscope-rec-${n}`);e&&this.held.set(n,e)}await b4(await(await this.root()).getDirectoryHandle(n,{create:!0}),u4,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 b4(await(await this.root()).getDirectoryHandle(n.id),u4,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=Ye(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 b4(await(await this.root()).getDirectoryHandle(t.id),_4(n),e),await this.enforceMax()})}async checkpoint(e,t,n){if(!this.opts.seal)return;let r;try{let i=y4((await crypto.subtle.digest(`SHA-256`,v4(e))).slice(0,8));r=ct({streamId:this.streamId,run:i,lane:1,seq:BigInt(t),count:n.length,hash:await ye(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 x4(i,u4))?.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 S4(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 x4(n,u4)?(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 x4(t,u4);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()+a4),null):(this.say(`refused:${t}`,`refused`,String(r.message??`Recording refused (${t})`),t),e===this.file?.id&&(this.refusedUntil=this.now()+o4),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 ${f2(this.splitEvery)}`:`cut with its data stream's`;this.status({type:`destination`,name:a,splitEvery:this.splitEvery,message:`Recording files: ${e} → ${a} (buffer ${f4(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 m4(`chunk upload failed: ${e?.message??e}`)}if(!r.ok)throw new m4(`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 b4(await(await i.getDirectoryHandle(e.stream_id,{create:!0})).getDirectoryHandle(t,{create:!0}),_4(n),r)}catch(e){throw new m4(`can't write to the folder: ${e?.message??e}`)}return}let o=(a.prefix??``).replace(/^\/+|\/+$/g,``),s=`${o?`${o}/`:``}${e.stream_id}/${t}/${_4(n)}`,c=`${a.endpoint.replace(/\/+$/,``)}/${a.bucket?`${a.bucket}/`:``}${s}`,l=new Y2({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=y4(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(h4(e)===400)return this.dropChunk(n,r,`refused: ${g4(e)}`);if(h4(e)!==409||g4(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 x4(t,u4);return r?(await b4(t,u4,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=h4(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 (${g4(n)}): its chunks were dropped`,g4(n)),await this.forget(t);continue}throw n instanceof m4&&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=d4(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)}},w4=class{#e;constructor(e){this.#e=e}head(){let e=this.#e;return`${e.map(e=>r0(e.name)).join(`,`)}\n${e.map(e=>r0(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(){}},T4=new TextEncoder,E4=e=>e+7&-8,D4=104,O4=64,k4=104,A4=160,j4=4;function M4(e,t,n){let r=24+t.length*8+n.length,i=new Uint8Array(E4(r)),a=new DataView(i.buffer);return i.set(T4.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 N4=(e,t)=>M4(e,[],T4.encode(`${t}\0`)),P4=e=>BigInt(Math.round(e))*1000000n,F4=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+D4,r=e=>{let r=n;return t.push(e),n+=e.length,r},i=r(N4(`##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,P4(this.#t),!0);let o=r(M4(`##FH`,[0,i],a)),s=this.#e.map(e=>r(N4(`##TX`,e.name))),c=this.#e.map(e=>e.unit?r(N4(`##TX`,e.unit)):0),l=n,u=l+O4,d=this.#e.map((e,t)=>u+k4+t*A4),f=M4(`##DG`,[0,u,u+k4+e*A4,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=M4(`##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,j4),i.setUint32(4,n*8,!0),i.setUint32(8,64,!0),i.setUint8(20,255),M4(`##CN`,[n+1<e?d[n+1]:0,0,s[n],0,0,0,c[n],0],r)}),_=new Uint8Array(24);_.set(T4.encode(`##DT`),0),new DataView(_.buffer).setBigUint64(8,BigInt(24+this.#n*e*8),!0);let v=new Uint8Array(64);v.set(T4.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,P4(this.#t),!0);let b=[v,M4(`##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}},I4={csv:`text/csv`,mf4:`application/octet-stream`};async function L4(e,t,n,r={}){let i=oV(`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 w4(JB(e,a)):new F4(JB(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 R4(e,t,n={}){let r=[];return await L4(e,t,e=>{r.push(e)},n),new Blob(r,{type:I4[t]})}var z4={management:`Management`,quality:`Quality`,maintenance:`Maintenance`,production:`Production`},B4=e=>({cells:[e.id,e.text,z4[e.owner]],...e.urgent?{status:`crit`}:{}}),V4=[`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.`}},U4={"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`},W4=[...V4],G4={"00":W4,"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:W4,13:[`quality`,`production`],14:[`quality`]},K4=e=>`${e}. Supports your review; does not certify.`,q4=(e,t,n,r,i=[])=>({id:e,title:U4[e],verdict:t,roles:G4[e],findings:n,charts:r,notes:i,...n.length>3?{shown:3}:{}}),J4=e=>`${Math.round(e*100)}%`,Y4=e=>`${Math.abs(e)>=10?Math.round(e):+e.toFixed(1)}%`;function X4(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 Z4=e=>Number.isFinite(e)?Math.abs(e)>=1e3?Math.round(e).toLocaleString(`en-GB`):String(+e.toPrecision(Math.abs(e)<1?2:3)):`—`,Q4=e=>Number.isFinite(e)?String(+e.toPrecision(4)):`—`,$4=(...e)=>t3(e=>Math.abs(e)<1?2:3,e),e3=(...e)=>t3(()=>4,e);function t3(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 n3=e=>`${e>0?`+`:e<0?`−`:``}${Z4(Math.abs(e))}`;function r3(e){return e>=3600?`${Z4(e/3600)} h`:e>=60?`${Math.round(e/60)} min`:`${Math.round(e)} s`}function i3(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 a3=e=>e===1?`once`:e===2?`twice`:`${e} times`,o3=(e,t,n=`${t}s`)=>`${e.toLocaleString(`en-GB`)} ${e===1?t:n}`,s3=e=>e.length<=1?e.join(``):`${e.slice(0,-1).join(`, `)} and ${e[e.length-1]}`,c3=e=>e.charAt(0).toUpperCase()+e.slice(1),l3=e=>e.charAt(0).toLowerCase()+e.slice(1);function u3(e){try{return new Intl.DateTimeFormat(`en-GB`,{timeZone:e}),!0}catch{return!1}}var d3=new Map,f3=(e,t)=>{let n=`${e}|${JSON.stringify(t)}`,r=d3.get(n);return r||d3.set(n,r=new Intl.DateTimeFormat(`en-GB`,{timeZone:u3(e)?e:`UTC`,...t})),r},p3=(e,t)=>f3(t,{day:`numeric`,month:`short`}).format(new Date(e*1e3)),m3=(e,t)=>f3(t,{day:`numeric`,month:`short`,hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}).format(new Date(e*1e3)),h3=(e,t)=>f3(t,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}).format(new Date(e*1e3)),g3=(e,t,n,r=`–`)=>`${m3(e,n)}${r}${p3(e,n)===p3(t,n)?h3(t,n):m3(t,n)}`,_3=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function v3(e,t){let n=f3(t,{weekday:`short`,hour:`2-digit`,hourCycle:`h23`}).formatToParts(new Date(e*1e3));return{day:_3.indexOf(n.find(e=>e.type===`weekday`).value),hour:Number(n.find(e=>e.type===`hour`).value)%24}}var y3=(e,t)=>`${_3[v3(e,t).day]} ${m3(e,t)}`,b3={min:`minimum`,max:`maximum`,mean:`mean`,integral:`integral`,first:`at start`,last:`at end`,delta:`change`};function x3(e){if(e===`duration`)return`Cycle duration`;let t=e.lastIndexOf(`:`);return t<0?e:`${e.slice(0,t)} ${b3[e.slice(t+1)]??e.slice(t+1)}`}var S3=e=>e<.01?`p < 0.01`:`p = ${e.toFixed(2)}`;function C3(e){let t=e.numbers.r,n=e.evidence===`correlation`&&Number.isFinite(t)?`r = ${t.toFixed(2)}`:e.p===null?``:S3(e.p);return n?`${H4[e.evidence].label} · ${n}`:H4[e.evidence].label}var w3=[`design`,`season`,`planned`,`handled`],T3={design:`Not a problem: it is so by design`,season:`Not a problem: the season or the weather`,planned:`Not a problem: it was planned`,handled:`Known: it is being handled`},E3=/\b\d{1,2}\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\b/gi,D3=(e,t)=>`${e}|${t.replace(E3,`#`).replace(/[-+−]?\d[\d,.:]*%?/g,`#`).replace(/\s+/g,` `).trim().toLowerCase()}`,O3=(e,t)=>Object.entries(t).some(([t,n])=>Number.isFinite(e[t])&&Math.abs(n)>0&&Math.abs(e[t])>2*Math.abs(n));function k3(e,t){if(!t.length)return e;let n=new Map(t.map(e=>[e.sig,e])),r=[],i=new Set,a=e=>t=>{let a=e===`00`||!t.sig?void 0:n.get(t.sig);return!a||O3(t.numbers,a.numbers)?!0:(i.add(t.id),r.push({id:t.id,section:e,text:t.text,reason:a.reason,note:a.note,at:a.at}),!1)},o=e.sections.map(e=>({...e,findings:e.findings.filter(a(e.id))}));if(!i.size)return e;let s=e.actions.filter(e=>!e.refs.length||e.refs.some(e=>!i.has(e))).map((e,t)=>({...e,id:`A${t+1}`})),c=`${o3(i.size,`finding`)} marked as known in the Process context ${i.size===1?`was`:`were`} set aside, with the actions that rested only on ${i.size===1?`it`:`them`}: listed under Known.`,l=o.map(e=>({...e,charts:e.charts.map(t=>t.kind===`table`&&t.columns[0]===`#`?{...t,rows:(e.id===`00`?s.slice(0,t.rows.length):s).map(B4),...e.id===`12`&&s.length>5?{shown:5,more:o3(s.length-5,`more action`)}:{}}:t),...e.id===`14`?{notes:[...e.notes,c]}:{}}));return{...e,sections:l,actions:s,known:r}}function A3(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 j3=(e,t)=>M3(e,e=>Math.floor((e.t-t)/86400)),M3=(e,t)=>[...A3(e,t).values()].map(e=>({t:P3(e.map(e=>e.t)),v:P3(e.map(e=>e.v))})),N3=e=>typeof e==`number`&&Number.isFinite(e);function P3(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return e.length?t/e.length:NaN}function F3(e){if(e.length<2)return 0;let t=P3(e),n=0;for(let r=0;r<e.length;r++)n+=(e[r]-t)**2;return Math.sqrt(n/(e.length-1))}function I3(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 L3=e=>I3(e,.5);function R3(e){let t=L3(e);return 1.4826*L3(Array.from(e,e=>Math.abs(e-t)))}function z3(e,t){return(e-L3(t))/Math.max(R3(t),1e-12)}function B3(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 V3=e=>Math.min(1,2*(1-B3(Math.abs(e))));function H3(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?V3((c-n*r/2)/l):1,effect:c/(n*r)}}function U3(e){if(e<.5)return Math.log(Math.PI/Math.sin(Math.PI*e))-U3(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 W3(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 G3(e,t,n){if(e<=0)return 0;if(e>=1)return 1;let r=Math.exp(U3(t+n)-U3(t)-U3(n)+t*Math.log(e)+n*Math.log(1-e));return e<(t+1)/(t+n+2)?r*W3(e,t,n)/t:1-r*W3(1-e,n,t)/n}function K3(e,t){let n=.5*G3(t/(t+e*e),t/2,.5);return e>0?1-n:n}var q3=(e,t)=>G3(t/(t+e*e),t/2,.5);function J3(e,t){let n=-1e7,r=1e7;for(let i=0;i<120;i++){let i=(n+r)/2;K3(i,t)<e?n=i:r=i}return(n+r)/2}function Y3(e,t,n,r){let i=e+n,a=t+r,o=(e,t)=>U3(e+1)-U3(t+1)-U3(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 X3(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:Y3(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?V3((i-a)/l):1}}function Z3(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 Q3(e,t){let n=P3(e),r=P3(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 $3(e,t){let n=e.length;if(n<3)return null;let r=P3(e),i=P3(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?q3(c/f,n-2):0,r2:s>0?1-u/s:0,n,s:d,mx:r,sxx:a}}function e6(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=P3(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=F3(t);return{beta:l,std:l.map((t,n)=>d>0?t*F3(e.map(e=>e[n]))/d:0),r2:s>0?1-u/s:0}}function t6(e,t){let n=e6(e,t);return n?{shares:n.std.map((n,r)=>n*Q3(e.map(e=>e[r]),t)),r2:n.r2}:null}function n6(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 r6=2e3;function i6(e,t,{B:n=1e3,seed:r=1,alpha:i=.05}={}){let a=n6(r),o=[],s=Math.min(e,r6);for(let r=0;r<n;r++)o.push(t(Array.from({length:s},()=>Math.floor(a()*e))));let c=I3(o,i/2),l=I3(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 a6=.01,o6=.05,s6=e=>Math.max(5,Math.ceil(e*o6)),c6=e=>Math.max(Math.abs(e.value)*2/100,2*e.spread);function l6(e){let t=e.value.key,n=t.indexOf(`~`),r=new Map;if(n<0)return r;let i=t.slice(0,n),a=new Map;for(let t of e.cycles){let e=t.kpis[i];e!=null&&Number.isFinite(e)&&a.set(t.streamId,[...a.get(t.streamId)??[],{t:t.tstart,v:e}])}for(let[e,t]of a)t.sort((e,t)=>e.t-t.t),t.length>2&&r.set(e,1.4826*L3(t.slice(1).map((e,n)=>Math.abs(e.v-t[n].v)))/Math.SQRT2);return r}function u6(e){let t=new Map(e.goldens.map(e=>[e.streamId,e])),n=l6(e),r=[];for(let i of e.cycles){let a=t.get(i.streamId);if(!a||i.value===null||!Number.isFinite(i.value)||i.tend===null||i.flag===`excluded`)continue;let o=e.value.better===`min`?i.value-a.value:a.value-i.value,s=Math.max(c6(a),2*(n.get(i.streamId)??0));r.push({c:i,g:a,gap:o,level:o>s?`off`:o<-s?`better`:`golden`})}return r.sort((e,t)=>e.c.tstart-t.c.tstart)}var d6=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>Number.isFinite(e))),f6=3600,p6=(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 m6(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=p6(n,e.c.tstart-f6);return r<n.length&&n[r]<=(e.c.tend??e.c.tstart)},c=e=>({section:q4(`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(`${o3(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:X3(t,u.length,n,d.length)}}),p=Z3(f.map(e=>e.t.p),a6),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:d6({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 (${J4(e.t.p1)}) against ${J4(e.t.p2)} of the rest.`}),g.push({text:`Act on “${e.r.name}” when it fires: it came before ${J4(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`),J4(e.t.p1),J4(e.t.p2)],finding:_.get(e.r.id),status:`watch`}))}]:[],y=m.slice(0,2).map(e=>`“${e.r.name}”`),b=m.length?`${s3(y)} came before off-golden batches more often than before the rest${m.length>2?`, and ${o3(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:q4(`07`,b,h,v),actions:g,next:x,numbers:{linked:m.length}}}var h6=(e,t)=>t===`duration`?e.c.tend===null?null:e.c.tend-e.c.tstart:e.c.kpis[t]??null,g6=e=>{let t=P3(e.map(e=>-e.gap));if(e.some(e=>e.g.value===0))return{text:Z4(t),pct:null,abs:t};let n=P3(e.map(e=>-e.gap/Math.abs(e.g.value)*100));return{text:Y4(n),pct:n,abs:t}},_6=e=>`${e<0?`−`:`+`}${Y4(Math.abs(e))}`;function v6(e,t){let n=t.filter(e=>e.level===`better`),r=[],i=[],a=[],o=[];if(n.length<5)return{section:q4(`03`,n.length?`${o3(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=g6(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 A3(n,e=>e.c.streamId)){if(a.length<5)continue;let n=[...a].sort((e,t)=>e.gap-t.gap)[4],o=g6(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:d6({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 (${Z4(n.c.value)}). ${o3(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}`:``}: ${o3(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=>h6(t,e)).filter(N3),r=c.map(t=>h6(t,e)).filter(N3);return t.length<5||r.length<5?[]:[{k:e,ma:L3(t),mb:L3(r),p:H3(t,r).p}]}),m=Z3(p.map(e=>e.p),a6),h=p.filter((e,t)=>m[t]&&e.ma!==e.mb).map(e=>({...e,label:x3(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:d6({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}: ${Z4(e.ma)} against ${Z4(e.mb)} at golden level${Number.isFinite(e.pct)?` (${_6(e.pct)})`:``}.`});let g=h.filter(e=>Number.isFinite(e.pct)).map(e=>({label:e.label,pct:e.pct,text:`${Z4(e.ma)} / ${Z4(e.mb)}`}));g.length&&a.push({kind:`diverging`,rows:g,title:`03.1 · The ${o3(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:q4(`03`,`${o3(n.length,`batch`,`batches`)} beat the golden by ${u.text} on ${l}${_.length?` with ${s3(_)}`:``}.`,r,a),actions:i,next:o,numbers:{better:n.length}}}var y6=`Ppk is indicative: it assumes the values are normally distributed and the process stable, which this report does not test.`,b6=new Set([`mean`,`min`,`max`,`first`,`last`]),x6=e=>Number.isFinite(e)?e.toFixed(2):`–`;function S6(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||!b6.has(n.slice(i+1)))continue;let o=t.map(e=>e.c.kpis[n]).filter(N3),s=F3(o);if(o.length<30)continue;let c=P3(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:x3(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 ${s3(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]=e3(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)??J4(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:d6({cpk:e.cpk,n:e.n,mean:e.m,outside:e.out}),text:`${e.label}: Ppk ${x6(e.cpk)} over ${o3(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 ${x6(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,x6(e.cpk),s(e)??J4(e.out)],status:e.cpk<1?`crit`:e.cpk<r?`watch`:`ok`,...n?{finding:n}:{}}})}];return{section:{...q4(`04`,f.length?`${o3(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:K4(`Capability (AIAG SPC)`),fold:!0},actions:u,next:[],numbers:{low:f.length}}}var C6=[`generic`,`discrete`,`process`,`regulated`,`motorsport`,`lab`],w6={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`}},motorsport:{id:`motorsport`,label:`Motorsport (laps, runs and sessions)`,first:[`04`,`05`,`02`,`08`,`03`],collapsed:[`06`,`09`,`10`,`11`,`13`],roles:{"04":[`production`,`quality`],"05":[`maintenance`,`production`]},terms:{"slow batches":`slow laps`,batches:`laps`,batch:`lap`,"bad parts":`bad laps`,"line time":`track time`,"before they ship":`before their data is used`,"production at risk":`running at risk`,"the line":`the car`,"other lines":`other cars`,"lines run alike":`cars run alike`,"inspect the machine for wear":`inspect the car for wear`,"machine wear":`wear`}},lab:{id:`lab`,label:`Test lab (test cycles, cells, rigs)`,first:[`04`,`02`,`05`,`08`,`09`],collapsed:[`06`,`10`,`11`,`13`],roles:{"04":[`quality`,`production`],"05":[`maintenance`,`quality`]},terms:{"slow batches":`slow cycles`,batches:`cycles`,batch:`cycle`,"bad parts":`bad cycles`,"line time":`test time`,"before they ship":`before their results are used`,"production at risk":`testing at risk`,"the line":`the rig`,"other lines":`other rigs`,"lines run alike":`rigs run alike`,"inspect the machine for wear":`inspect for wear`,"machine wear":`wear`}}},T6=e=>w6[C6.find(t=>t===e)??`generic`],E6=e=>e===`quality`?`discrete`:e===`plants`?`process`:e===`pharma`?`regulated`:e===`motorsport`?`motorsport`:e===`test`||e===`battery`?`lab`:`generic`,D6=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),O6=e=>[...e].sort((e,t)=>t.length-e.length).map(D6).join(`|`),k6=new Map;function A6(e,t,n=[]){if(!e||!Object.keys(t.terms).length)return e;let r=k6.get(t.id);if(!r){let e=`(?<![\\w.])(${O6(Object.keys(t.terms))})(?!\\w)(?!\\.\\w)`;k6.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(`(${O6(s)})`)).map((e,t)=>t%2?e:o(e)).join(``):o(e)}function j6(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 M6=new Set([`id`,`section`,`kind`,`evidence`,`ref`,`refs`,`finding`,`day`,`status`,`unit`,`tone`,`roles`,`cites`,`owner`,`alert`,`batch`,`golden`,`sig`,`reason`]);function N6(e,t){return typeof e==`string`?t(e):Array.isArray(e)?e.map(e=>N6(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,M6.has(e)?n:N6(n,t)])):e}function P6(e,t,n=[]){if(t.id===`generic`)return e;let r=e=>A6(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})=>({...N6(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:N6(e.actions,r),missing:N6(e.missing,r),...e.known?{known:N6(e.known,r)}:{}}}var F6=[`setting`,`measurement`,`quality`,`outside`,`energy`,`category`,`ignore`],I6={setting:`Adjustable setting`,measurement:`Measurement`,quality:`Quality result`,outside:`Outside influence`,energy:`Energy or consumption`,category:`Category (a driver, a recipe, a cell)`,ignore:`Ignore`},L6=4e3,R6=(e=``)=>({role:null,unit:e,lo:null,hi:null,lsl:null,usl:null,target:null,calibration:null,suggested:!1}),z6=()=>({v:1,process:``,channels:{},lines:[],units:[],shifts:[],stops:[],costs:{currency:`EUR`,kwh:null,lineHour:null,scrap:null,rework:null,co2:null,licence:null}}),B6=e=>e&&!e.suggested?e.role:null,V6=e=>Object.keys(e?.channels??{}).filter(t=>B6(e.channels[t])===`energy`).sort()[0]??null,H6=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},U6=e=>Array.isArray(e)?e:[],W6=(e,t)=>typeof e==`string`?e.slice(0,t):``,G6=e=>typeof e==`number`&&Number.isFinite(e)?e:null,K6=e=>U6(e).filter(e=>typeof e==`string`).slice(0,500),q6=(e,t)=>e!==null&&t!==null&&e>=t?[null,null]:[e,t],J6=/^([01]\d|2[0-3]):[0-5]\d$/,Y6=/^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d$/,X6=e=>e.suggested===!0?{suggested:!0}:{};function Z6(e){let t=H6(e),n=W6(t.name,80),r=W6(t.from,16),i=W6(t.to,16);if(Y6.test(r)&&Y6.test(i)&&r<i)return[{name:n,from:r,to:i,...X6(t)}];if(!J6.test(r)||!J6.test(i))return[];let a=t.days===void 0?void 0:[...new Set(U6(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}:{},...X6(t)}]}function Q6(e){let t=new Set,n=new Set;return U6(e).slice(0,50).map(e=>({name:W6(H6(e).name,80),streams:K6(H6(e).streams),...X6(H6(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 $6(e){let t=H6(e),n=H6(t.costs),r=z6(),i=Object.create(null);for(let[e,n]of Object.entries(H6(t.channels)).slice(0,2e3)){let t=H6(n),r=F6.find(e=>e===t.role)??null,[a,o]=q6(G6(t.lo),G6(t.hi)),[s,c]=q6(G6(t.lsl),G6(t.usl));i[e.slice(0,200)]={role:r,unit:W6(t.unit,40),lo:a,hi:o,lsl:s,usl:c,target:G6(t.target),calibration:G6(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:W6(t.process,L6),...t.processSuggested===!0&&W6(t.process,1)?{processSuggested:!0}:{},channels:i,lines:Q6(t.lines),units:U6(t.units).slice(0,100).map(e=>({name:W6(H6(e).name,80),channels:K6(H6(e).channels),...X6(H6(e))})).filter(e=>e.name),shifts:U6(t.shifts).slice(0,12).map(e=>({name:W6(H6(e).name,40),start:W6(H6(e).start,5),end:W6(H6(e).end,5),...X6(H6(e))})).filter(e=>e.name&&J6.test(e.start)&&J6.test(e.end)),stops:U6(t.stops).slice(0,500).flatMap(Z6),costs:{currency:/^[A-Z]{3}$/.test(String(n.currency))?String(n.currency):r.costs.currency,kwh:G6(n.kwh),lineHour:G6(n.lineHour),scrap:G6(n.scrap),rework:G6(n.rework),co2:G6(n.co2),licence:G6(n.licence)},...(G6(t.idealCycleS)??0)>0?{idealCycleS:t.idealCycleS}:{},...t.hideShifts===!0?{hideShifts:!0}:{},...C6.some(e=>e===t.preset)?{preset:t.preset}:{},...(G6(t.ppkMin)??0)>=1&&t.ppkMin<=3?{ppkMin:t.ppkMin}:{},...U6(t.known).length?{known:U6(t.known).slice(0,200).flatMap(e=>{let t=H6(e),n=w3.find(e=>e===t.reason),r=W6(t.sig,600),i=Object.fromEntries(Object.entries(H6(t.numbers)).filter(([,e])=>typeof e==`number`&&Number.isFinite(e)).slice(0,40));return n&&r&&Number.isFinite(t.at)?[{sig:r,section:W6(t.section,4),text:W6(t.text,1e3),reason:n,note:W6(t.note,300),numbers:i,at:t.at}]:[]})}:{}}}var e8=(e,t)=>{let n=e+$E(e,t);return Math.floor((n%86400+86400)%86400/60)},t8=e=>e.slice(0,2)*60+ +e.slice(3,5);function n8(e){let t=new Map;return n=>{let r=Math.floor(n/900),i=t.get(r);return i===void 0&&(i=eD(r*900,e),t.set(r,i)),i}}function r8(e,t,n){if(!t.length)return null;let r=e8(e,n);for(let e of t){let t=t8(e.start),n=t8(e.end);if(t<n?r>=t&&r<n:r>=t||r<n)return e.name}return null}var i8=e=>(new Date(`${e}T00:00:00Z`).getUTCDay()+6)%7;function a8(e,t,n,r){let i=[];for(let a of e.stops){if(a.from.length>5){i.push({t0:tD(a.from.slice(0,10),a.from.slice(11),t),t1:tD(a.to.slice(0,10),a.to.slice(11),t)});continue}for(let e=nD(eD(n,t),-1),o=eD(r,t);e<=o;e=nD(e,1)){if(a.days&&!a.days.includes(i8(e)))continue;let o=tD(e,a.from,t),s=tD(a.to>a.from?e:nD(e,1),a.to,t);s>n&&o<r&&i.push({t0:o,t1:s})}}return i}function o8(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:B6(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 s8(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 c8(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 l8(e,t){let n=o8(e??z6()),r=Object.values(n.channels),i=r.some(e=>B6(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=>B6(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 u8(e){let t=o8(e??z6()),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=>B6(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 d8(e,t){let n=l8(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 f8=.2,p8=20,m8=1e5,h8=2e4,g8=1e3,_8=class{values=[];#e;#t=0;#n=n6(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)}}},v8=11,y8=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 _8(h8);#T=0;#E=0;#D=new Float64Array(v8);#O=new Float64Array(v8);#k=new Float64Array(v8);#A=0;#j=0;#M=0;#N=[];#P=new _8(m8);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<g8?(this.#l.push(e),this.#l.length===g8&&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=L3(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.#_=f8*this.#E}#L(e){let t=e-this.#h;this.#g>=20&&t>=300&&(this.#v+=t,this.#y++,this.#b.length<p8&&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===v8,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)%v8,this.#A<v8)return;let o=e=>(this.#j+e)%v8,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<p8&&this.#N.push(this.#D[o(5)]))}result(){this.#g&&this.#L(this.#s),this.#l.length<g8&&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?L3(n):0,spikes:this.#M,spikeAt:this.#N,min:this.#t,max:this.#n,lo:I3(t,.005),hi:I3(t,.995),median:L3(t),p01:I3(t,.01),p99:I3(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 b8(e){let t=e.slice(0,Math.max(3,Math.ceil(e.length/3)));if(!t.length)return null;let n=L3(t.map(e=>e.lo)),r=L3(t.map(e=>e.hi)),i=(r-n)/2;return r>n?{lo:n-i,hi:r+i,n:t.length}:null}var x8=3600,S8=86400;function C8(e,t){let n=e.filter(e=>N3(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=j3(n,r),a=i,o=`day`;if(i.length<7&&(a=M3(n,e=>e.rec),o=`recording`,a.length<6&&(a=M3(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=$3(a.map(e=>(e.t-r)/S8),a.map(e=>e.v)),c=L3(n.map(e=>e.edge).filter(N3));return s&&c>0&&s.b!==0?{t0:r,means:a,per:o,days:i.length,fit:s,edge:c,step:w8(a,s)}:null}function w8(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 T8(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*S8,h=s+c*((r-i)/S8),g=Math.abs(h)>=o;if(!g&&(m-r)/S8>365)return null;let _=(J3(1-a6/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)*S8).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)/S8)}}}var E8=.02,D8=.01;function O8(e,t,n={s:0,total:0}){let r=e.filter(e=>e.tend!==null&&e.range?.[t]).sort((e,t)=>e.tstart-t.tstart),i=r.map(e=>e.range[t][1]-e.range[t][0]),a=L3(i);if(!(a>0))return[];let o=E8*a,s=i.map(e=>e<=o);if(s.filter(Boolean).length>.25*r.length)return[];let c=[],l=null,u=s.filter(Boolean).length,d=e=>r.length*((u-e.n)/Math.max(1,r.length-e.n))**e.n<D8,f=e=>e.n<3&&!(n.total>0&&Math.max(0,n.s-(e.t1-e.t0))/n.total<.05),p=()=>{l&&l.t1-l.t0>=600&&d(l)&&!f(l)&&c.push(l)};for(let[e,n]of r.entries()){let r=n.range[t][0];if(s[e]&&l&&Math.abs(r-l.value)<=o){l.t1=n.tend,l.n++;continue}p(),l=s[e]?{t0:n.tstart,t1:n.tend,value:r,n:1}:null}return p(),c}function k8(e){let t=e.filter(e=>e.status===`Replace`&&e.stuck.length).sort((e,t)=>e.key.localeCompare(t.key)),n=new Set,r=e=>e.stuck.reduce((e,t)=>e+t.t1-t.t0,0),i=(e,t)=>e.stuck.reduce((e,n)=>e+t.stuck.reduce((e,t)=>e+Math.max(0,Math.min(n.t1,t.t1)-Math.max(n.t0,t.t0)),0),0);for(let[e,a]of t.entries()){if(n.has(a))continue;let o=t.slice(e+1).filter(e=>!n.has(e)&&e.sid===a.sid&&i(a,e)>=.5*Math.min(r(a),r(e)));if(o.length){for(let e of o)n.add(e);a.with=o.map(e=>e.key),a.found=`${a.found.replace(/\.$/,``)}, and ${s3(a.with)} held with it: one fault (a probe and what is computed from it, or one cable).`}}return e.filter(e=>!n.has(e))}function A8(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=s.filter(e=>e.range?.[n]).length>=20;if(f){let e=O8(s,n,{s:u.reduce((e,t)=>e+t.h.flatS,0),total:u.reduce((e,t)=>e+(t.r.t1-t.r.t0),0)});if(e.length){let t=e.reduce((e,t)=>t.t1-t.t0>e.t1-e.t0?t:e),n=e.reduce((e,t)=>e+t.n,0);return{...l,status:`Replace`,since:e[0].t0,stuck:e.map(({t0:e,t1:t})=>({t0:e,t1:t})),found:`Stuck at ${Q4(t.value)}${d} from ${g3(t.t0,t.t1,o,` to `)} while ${o3(t.n,`batch`,`batches`)} ran${e.length>1?`; ${a3(e.length)} in all, ${o3(n,`batch`,`batches`)}`:``}.`}}}let p=s.map(e=>e.tstart).sort((e,t)=>e-t),m=e=>{let t=0,n=p.length;for(;t<n;){let r=t+n>>1;p[r]<e.t0?t=r+1:n=r}return t<p.length&&p[t]<=e.t1},h=f?[]:u.flatMap(e=>e.h.flats).filter(e=>!p.length||m(e)).sort((e,t)=>e.t0-t.t0),g=p.length?h.reduce((e,t)=>e+t.t1-t.t0,0):u.reduce((e,t)=>e+t.h.flatS,0),_=p.length?h.length:u.reduce((e,t)=>e+t.h.flatRuns,0);if(u.some(e=>e.h.moves)&&u.some(e=>e.h.noise>0)&&g>=600&&h.length){let e=f8*L3(u.map(e=>e.h.noise).filter(e=>e>0)),t=[];for(let n of h){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.length;return{...l,status:`Replace`,since:h[0].t0,stuck:t.map(({t0:e,t1:t})=>({t0:e,t1:t})),found:`Stuck at ${Q4(n.value)}${d} from ${g3(n.t0,n.t1,o,` to `)}, ${r3(n.rec)} of it recorded${r>1?`; ${a3(r)} in all, ${r3(g)} recorded`:``}.`}}if(a){let e=a.per===`day`?`${n3(a.b*7)}${d} a week`:`${n3(a.b)}${d} a day`,t=`over ${o3(a.days,`day`)}${a.per===`day`?``:`, ${o3(a.n,a.per)}`}`;return{...l,status:`Drifting`,since:a.points[0]?.t??null,found:`${a.past?`Offset ${n3(a.vNow)}${d} against the golden, past the band edge (${Z4(a.edge)}${d}); drifting ${e} ${t}.`:`Offset drifting ${e} against the golden ${t}; reaches the band edge (${Z4(a.edge)}${d}) around ${p3(a.cross,o)}.`} Check calibration or the process.`}}let v=[];c&&v.push({since:c.t,text:`Offset against the golden moved by ${n3(c.d)}${d} on ${p3(c.t,o)} and stayed there: a change, not a drift.`});let y=L3(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=L3(t);t.length>=3&&n>0&&e.h.noise/n>=1.3&&z3(e.h.noise,t)>=3&&v.push({text:`Noise up ${J4(e.h.noise/n-1)}. Check the cable and its shielding.`,since:e.r.t0})}let b=u.reduce((e,t)=>e+t.h.n,0),x=u.reduce((e,t)=>e+t.h.spikes,0),S=s.length>0&&x*5>=s.length&&x<=3*s.length;b&&x/b>=1e-4&&!S&&v.push({text:`${o3(x,`spike`)}.`,since:Math.min(...u.flatMap(e=>e.h.spikeAt))});let C=u.reduce((e,t)=>e+(t.r.t1-t.r.t0),0),w=u.reduce((e,t)=>e+t.h.gapS,0),T=u.reduce((e,t)=>e+t.h.gaps,0);C>0&&w/C>=.01&&v.push({text:`${r3(w)} of gaps in ${o3(T,`place`)}.`,since:u.find(e=>e.h.gaps).r.t0});let E=u.find(e=>e.h.rateHz>0&&e.h.rateHz<.9*y);if(E&&v.push({text:`Rate dropped from ${Z4(y)} Hz to ${Z4(E.h.rateHz)} Hz on ${p3(E.r.t0,o)}.`,since:E.r.t0}),u.length>=3){let e=b8(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=>e.min<t-r&&!(e.min===0&&t>0),a=e?u.find(e=>i(e.h)||e.h.max>n+r):void 0;if(a){let[i,o,s]=e3(a.h.max>n+r?a.h.max:a.h.min,t,n);v.push({since:a.r.t0,text:`Read ${i}${d}, outside the usual ${o} to ${s}${d} learned from the first ${o3(e.n,`recording`)}.`})}}return v.length?{...l,status:`Watch`,found:v.map(e=>e.text).join(` `),since:Math.min(...v.map(e=>e.since)),...c&&v.length===1?{step:c}:{}}:{...l,status:`Healthy`,found:`No gaps or spikes worth a look, rate steady at ${Z4(y)} Hz.`,since:null}}function j8(e,t){let n=e.streams.length>1;return[...A3(t,e=>e.c.streamId)].flatMap(([t,r])=>{let i=M8(e,r);return i?[{...i,sid:t,text:n?`${e.streams.find(e=>e.id===t)?.name??t}: ${l3(i.text)}`:i.text}]:[]}).sort((e,t)=>(e.p??1)-(t.p??1))[0]??null}function M8(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=L3(n.map(e=>e.v)),i=n[0].t,a=j3(n.map(e=>({t:e.t,v:e.v/r*100})),i),o=r>0&&a.length>=7?$3(a.map(e=>(e.t-i)/(7*S8)),a.map(e=>e.v)):null,s=o&&o.p<.01&&o.b>0&&!w8(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=R3(u),p=f>0?R3(d)/f:NaN,m=null;if(Number.isFinite(p)&&p>=1.15){let e=n6(1),t=Math.min(l,r6),n=Math.sqrt(t/l),r=n=>R3(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=``;if(s!==null){let e=$3(a.map(e=>(e.t-i)/S8),a.map(e=>e.v/100*r)),n=[...new Set(t.flatMap(e=>Object.keys(e.c.phases??{})))].map(e=>{let n=j3(t.filter(t=>N3(t.c.phases?.[e])).map(t=>({t:t.c.tstart,v:t.c.phases[e]})),i),r=n.length>=7?$3(n.map(e=>(e.t-i)/S8),n.map(e=>e.v)):null;return{ph:e,b:r&&r.p<.01?r.b:0}}).sort((e,t)=>t.b-e.b)[0];e&&n&&n.b>0&&n.b>=.5*e.b&&(g=`, most of it in the phase “${n.ph}” (${r3(n.b*7)} longer a week)`)}let _=[...s===null?[]:[`cycle time grows ${Z4(s)}% a week since ${p3(i,e.tz)}${g}`],...h===null?[]:[`the spread of ${e.value.label} is up ${J4(h)}`]];return{text:`${c3(_.join(` and `))}.${_.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}}function N8(e,t,n,r,i){let a=r.flatMap(e=>e.health.channels[n]?[{r:e,h:e.health.channels[n]}]:[]),o=a.length>=3?b8(a.map(e=>e.h)):null;if(!o)return null;let s=1e-9*Math.max(1,Math.abs(o.lo),Math.abs(o.hi)),c=a.find(e=>e.h.min<o.lo-s||e.h.max>o.hi+s);if(!c)return null;let l=i?` ${i}`:``,[u,d,f]=e3(c.h.max>o.hi+s?c.h.max:c.h.min,o.lo,o.hi);return{ch:e,sid:t,key:n,drift:null,stuck:[],status:`Watch`,since:c.r.t0,outside:!0,found:`Outside influence: read ${u}${l}, outside its usual ${d} to ${f}${l}. Batches made meanwhile may differ for that reason, not the machine's.`}}function P8(e,t,n){if(!n.size)return e;let r=A3(t,e=>e.c.streamId);return e.map(e=>{if(e.status!==`Drifting`||!e.drift)return e;let t=r.get(e.sid)??[],i=t[0]?.c.tstart??0;for(let r of n){let n=t.filter(t=>N3(t.c.d?.[e.key])&&N3(t.c.d?.[r])),a=A3(n,e=>Math.floor((e.c.tstart-i)/S8)),o=[...a.size>=7?a:A3(n,e=>e.c.recordingId)].map(([,t])=>({t:L3(t.map(e=>e.c.tstart)),v:L3(t.map(t=>t.c.d[e.key])),o:L3(t.map(e=>e.c.d[r]))}));if(o.length<6)continue;let s=$3(o.map(e=>e.o),o.map(e=>e.v));if(!s||!(s.p<.01))continue;let c=$3(o.map(e=>(e.t-i)/S8),o.map(e=>e.v-(s.a+s.b*e.o))),l=Q3(o.map(e=>e.v),o.map(e=>e.o));if(Math.abs(l)>=.8||c&&!(c.p<.01))return{...e,status:`Watch`,drift:null,found:`Follows ${r}, an outside influence (r = ${Z4(l)} ${a.size>=7?`day by day`:`recording by recording`}): the weather or the surroundings at work, not a sensor to calibrate.`}}return e})}function F8(e,t,n=new Map){if(!(t.streams.length>1))return e;let r=new Map;for(let t of e)(r.get(t.key)??r.set(t.key,new Set).get(t.key)).add(t.sid);let i=[],a=new Set,o=e=>t.units[e]?` ${t.units[e]}`:``,s=(e,t)=>e.length>=2&&e.length>=.6*(r.get(t)?.size??0);for(let[t,n]of A3(e.filter(e=>e.status===`Drifting`&&e.drift),e=>`${e.key}\u0000${Math.sign(e.drift.b)}`)){let e=t.split(`\0`)[0];if(!s(n,e))continue;let r=L3(n.map(e=>e.drift.b)),c=n.filter(e=>Math.abs(e.drift.b)>=2*Math.abs(r)),l=n.filter(e=>!c.includes(e)),u=L3(l.map(e=>e.drift.b));for(let t of c)t.found=`Drifts ${Z4(t.drift.b/u)}× as fast as on the other ${o3(l.length,`stream`)} (${n3(t.drift.b*7)}${o(e)} a week against ${n3(u*7)}${o(e)}). ${t.found}`;if(!(l.length<2)){for(let e of l)a.add(e);i.push({ch:`${e} on ${o3(l.length,`stream`)}`,sid:``,key:e,drift:null,stuck:[],status:`Watch`,since:Math.min(...l.map(e=>e.since??1/0)),common:!0,found:`Drifts alike on ${o3(l.length,`stream`)} (${n3(u*7)}${o(e)} a week against the golden): a cause common to them (the season, the material, normal aging), not ${o3(l.length,`sensor`)} to calibrate.`})}}let c=e=>t.streams.find(t=>t.id===e)?.name??e,l=new Map;for(let t of e.filter(e=>e.status===`Drifting`&&e.drift&&!a.has(e)&&!e.found.startsWith(`Drifts `))){let e=n.get(t.key)??[];if(e.length<3)continue;let r=L3(e);Math.sign(r)===Math.sign(t.drift.b)&&(Math.abs(t.drift.b)<2*Math.abs(r)?(l.get(t.key)??l.set(t.key,[]).get(t.key)).push(t):t.found=`Drifts ${Z4(t.drift.b/r)}× as fast as the streams' usual (${n3(t.drift.b*7)}${o(t.key)} a week against ${n3(r*7)}${o(t.key)}). ${t.found}`)}for(let[e,t]of l){let r=L3(n.get(e));for(let e of t)a.add(e);i.push({ch:`${e} on ${s3(t.map(e=>c(e.sid)))}`,sid:``,key:e,drift:null,stuck:[],status:`Watch`,since:Math.min(...t.map(e=>e.since??1/0)),common:!0,found:`Drifts like on the other streams (${n3(r*7)}${o(e)} a week on all ${n.get(e).length}): a cause common to them (the season, the material, normal aging), not a sensor to calibrate.`})}let u=e=>e===null?``:p3(e,t.tz);for(let[t,n]of A3(e.filter(e=>e.status===`Watch`&&!a.has(e)&&/outside (its|the) usual/.test(e.found)),e=>`${e.key}\u0000${u(e.since)}`)){let e=t.split(`\0`)[0];if(s(n,e)){for(let e of n)a.add(e);i.push({...n[0],ch:`${e} on ${o3(n.length,`stream`)}`,sid:``,common:!0,found:`${n[0].outside?`Outside influence: l`:`L`}eft its usual range on ${o3(n.length,`stream`)} on ${u(n[0].since)} (${n.map(e=>/read ([^,]*?)(,| outside)/i.exec(e.found)?.[1]??``).filter(Boolean).slice(0,1).join(``)}): one cause common to them, not ${o3(n.length,`sensor`)}.`})}}return[...e.filter(e=>!a.has(e)),...i]}var I8=e=>new Set(e.recordings.flatMap(e=>Object.entries(e.health?.channels??{}).filter(([,e])=>e.clock).map(([e])=>e)));function L8(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 R8(e,t){let n=e.recordings.filter(e=>e.health).sort((e,t)=>e.t0-t.t0),r=new Map,i=o8(e.context??z6()),a=I8(e);for(let e of Object.keys(i.channels))[`setting`,`ignore`,`category`].includes(B6(i.channels[e])??``)&&a.add(e);let o=new Set(Object.keys(i.channels).filter(e=>B6(i.channels[e])===`outside`)),s=new Set(Object.keys(i.channels).filter(e=>B6(i.channels[e])===`quality`||i.channels[e].lsl!==null||i.channels[e].usl!==null));for(let t of L8(e))a.add(t);let c=A3(e.cycles,e=>e.streamId);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 l=e.streams.length>1,u=A3(t,e=>e.c.streamId),d=(t,n)=>l?`${e.streams.find(e=>e.id===t)?.name??t} · ${n}`:n,f={Replace:0,Drifting:1,Watch:2,Healthy:3},p=[...r.values()].map(({sid:e,key:t})=>C8(u.get(e)??[],t)),m=Z3(p.flatMap(e=>e?[e.fit.p]:[]),a6),h=0,g=p.map(e=>!!e&&m[h++]),_=new Map;for(let[e,{key:t}]of[...r.values()].entries())p[e]&&(_.get(t)??_.set(t,[]).get(t)).push(p[e].fit.b);return F8(P8(k8([...r.values()].map(({sid:t,key:r},i)=>{let a=d(t,r),l=p[i];if(o.has(r))return N8(a,t,r,n.filter(e=>e.streamId===t),e.units[r]??``);if(s.has(r))return A8(a,t,r,n.filter(e=>e.streamId===t),e.units[r]??``,null,e.tz,c.get(t),null);let u=l&&g[i]?l.step:null;return A8(a,t,r,n.filter(e=>e.streamId===t),e.units[r]??``,l&&g[i]&&!u?T8(a,r,l,e.period.to):null,e.tz,c.get(t),u)}).filter(e=>!!e)),t,o),e,_).sort((e,t)=>f[e.status]-f[t.status]||(e.drift&&t.drift?e.drift.cross-t.drift.cross:0)||e.ch.localeCompare(t.ch))}function z8(e,t,n){let r=[];for(let[i,a]of A3(t.filter(e=>e.c.d&&e.c.range),e=>e.c.streamId)){if(a.length<20)continue;let t=Object.keys(a[0].c.d).filter(t=>!n.has(t)&&e.units[t]&&a[0].c.range[t]),o=e=>L3(a.map(t=>t.c.range[e]?.[1]).filter(N3)),s=e.recordings.filter(e=>e.streamId===i&&e.health),c=e=>L3(s.map(t=>t.health.channels[e]?.median).filter(N3)),l=e=>L3(a.map(t=>t.c.range[e]?t.c.range[e][1]-t.c.range[e][0]:NaN).filter(N3));for(let[n,s]of t.entries())for(let u of t.slice(n+1)){if(e.units[s]!==e.units[u])continue;let t=o(s),n=o(u),d=l(s),f=l(u);if(!(Math.abs(t-n)<=.02*Math.max(Math.abs(t),Math.abs(n)))||!(d>0&&f>0&&Math.min(d,f)/Math.max(d,f)>=.8))continue;let p=c(s),m=c(u);if(!(Math.abs(p-m)<=.02*Math.max(Math.abs(p),Math.abs(m),d)))continue;let h=a.filter(e=>N3(e.c.d[s])&&N3(e.c.d[u])).map(e=>({t:e.c.tstart,v:e.c.d[s]-e.c.d[u]}));if(h.length<20)continue;let g=h[0].t,_=j3(h,g);if(_.length<7)continue;let v=$3(_.map(e=>(e.t-g)/S8),_.map(e=>e.v));if(!v||v.b===0)continue;let y=(_[_.length-1].t-_[0].t)/S8,b=v.b*y;Math.abs(b)<4*v.s||r.push({sid:i,a:s,b:u,t0:_[0].t,diff:b,perWeek:v.b*7,p:v.p})}}let i=Z3(r.map(e=>e.p),a6);return r.filter((e,t)=>i[t])}function B8(e,t){let n=R8(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=[...A3(n.filter(e=>e.status===`Drifting`),e=>e.sid).values()].filter(e=>e.length>1),d=new Set(u.flat()),f=[...A3(n.filter(e=>e.step),t=>`${t.sid}\u0000${p3(t.step.t,e.tz)}`).values()].filter(e=>e.length>1),p=new Set(f.flat()),m=o8(e.context??z6()),h=z8(e,t,new Set([...I8(e),...L8(e),...Object.keys(m.channels).filter(e=>[`setting`,`ignore`,`category`,`outside`,`quality`].includes(B6(m.channels[e])??``))])),g=new Map(h.map(e=>[e.sid,e]));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}: ${l3(t.found)}`,owner:`maintenance`,urgent:!0,rank:1,refs:[n]});else if(t.status===`Drifting`&&!d.has(t)){let a=t.drift,o=g.get(t.sid),s=!!o&&o.a!==t.key&&o.b!==t.key;r.push({id:n,section:`05`,refs:[`05`],evidence:`statistical`,p:a.p,text:`${t.ch}: ${s?t.found.replace(/ Check calibration or the process\.$/,` Likely with ${o.a} and ${o.b} reading apart on this stream (below).`):t.found}`,numbers:d6({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})}),s||i.push({text:`${t.ch} offset drifting: check calibration or the process ${a.past?`now`:`before ${p3(a.cross,e.tz)}`}.`,owner:`maintenance`,urgent:a.past||a.cross-e.period.to<7*S8,rank:.5,refs:[n]})}}let _=e=>e.map(e=>e.drift).sort((e,t)=>t.past-+e.past||e.cross-t.cross)[0],v=t=>{let n=t.drift,r=e.units[t.key]?` ${e.units[t.key]}`:``;return`${t.key} ${n.per===`day`?`${n3(n.b*7)}${r} a week`:`${n3(n.b)}${r} a day`}`},y=e=>`${c?`${l(e[0].sid)}: `:``}${s3(e.map(e=>e.key))} drift together against the golden (${e.map(v).join(`, `)}): one change of the process (wear, a setting), not ${e.length} sensors to calibrate.`,b=new Map;for(let t of u){let n=_(t),a=`F05-${r.length+1}`;b.set(t,a);for(let e of t)s.set(e,a);r.push({id:a,section:`05`,refs:[`05`],evidence:`statistical`,p:Math.max(...t.map(e=>e.drift.p)),text:y(t),numbers:d6({channels:t.length,cross:n.cross,past:+n.past})}),i.push({text:`${c?`${l(t[0].sid)}: `:``}${s3(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 ${p3(n.cross,e.tz)}`}.`,owner:`maintenance`,urgent:n.past||n.cross-e.period.to<7*S8,rank:.5,refs:[a]})}let x=[...n.filter(e=>e.status===`Drifting`&&!d.has(e)).map(e=>e.ch),...u.map(e=>`the process${c?` on ${l(e[0].sid)}`:``}`)];x.length&&a.push(`Run the report again after checking ${s3(x)} to confirm the ${x.length===1?`offset is`:`offsets are`} gone.`);let S=t=>({cells:[t.ch,t.status,t.found,t.since===null?`–`:p3(t.since,e.tz)],status:t.status===`Replace`?`crit`:`watch`,...s.has(t)?{finding:s.get(t)}:{}}),C=t=>{let n=t=>e.units[t.key]?` ${e.units[t.key]}`:``,r=p3(t[0].step.t,e.tz);return{cells:[`${c?`${l(t[0].sid)} · `:``}${o3(t.length,`channel`)}`,`Watch`,`Offsets against the golden moved on ${r} and stayed there (${t.map(e=>`${e.key} ${n3(e.step.d)}${n(e)}`).join(`, `)}): one change of the process, not ${t.length} sensors.`,r],status:`watch`}},w=n.filter(e=>e.status!==`Healthy`),T=n.length-w.length;w.length&&o.push({kind:`table`,columns:[`Sensor`,`Status`,`What was found`,`Since`],rows:[...w.filter(e=>!p.has(e)&&!d.has(e)).map(S),...u.map(t=>({cells:[`${c?`${l(t[0].sid)} · `:``}${o3(t.length,`channel`)}`,`Drifting together`,y(t),p3(Math.min(...t.map(e=>e.since??1/0)),e.tz)],status:`watch`,finding:b.get(t)})),...f.map(C)],title:`05.1 · Sensors that need a look${T?`; the other ${T} ${T===1?`is`:`are`} healthy`:``}`});let E=n.flatMap(e=>e.drift?[e.drift]:[]).sort((e,t)=>e.cross-t.cross)[0];E&&o.push({kind:`trend`,title:`05.2 · Drift forecast, ${E.ch}: its offset against the golden per ${E.per}, forecast to the band edge`,unit:e.units[E.key]??``,points:E.points,line:E.line,limit:Math.sign(E.b)*E.edge,crossing:E.past?null:{t:E.cross,lo:E.lo,hi:E.hi}});for(let t of h){let n=`F05-${r.length+1}`,a=e.units[t.a]?` ${e.units[t.a]}`:``,[o]=e3(Math.abs(t.diff)),s=t.diff>0?t.a:t.b,u=t.diff>0?t.b:t.a;r.push({id:n,section:`05`,refs:[`05`],evidence:`statistical`,p:t.p,numbers:d6({diff:t.diff,perWeek:t.perWeek,p:t.p}),text:`${c?`${l(t.sid)}: `:``}${t.a} and ${t.b} read alike, but ${s} now reads ${o}${a} high against ${u}, drifting ${n3(Math.abs(t.perWeek))}${a} a week since ${p3(t.t0,e.tz)}: one of the two is off.`}),i.push({text:`${c?`${l(t.sid)}: `:``}Calibrate ${t.a} and ${t.b} against each other: ${s} reads ${o}${a} high against ${u}, drifting since ${p3(t.t0,e.tz)}.`,owner:`maintenance`,urgent:!0,rank:1,refs:[n]})}let D=j8(e,t);if(D){let e=`F05-${r.length+1}`,t=n.filter(e=>e.status===`Drifting`&&(!c||e.sid===D.sid)).map(e=>e.key);t.length&&(D.text=`${D.text.replace(/\.( (Together they are )?[Cc]onsistent with wear\.)$/,``)}, as ${s3(t.slice(0,3))} ${t.length===1?`drifts`:`drift`} (see 05.1).${D.text.match(/\.( (Together they are )?[Cc]onsistent with wear\.)$/)?.[1]??``}`),r.push({id:e,section:`05`,refs:[`05`],evidence:`statistical`,p:D.p,text:D.text,numbers:d6({growPerWeek:D.grow??NaN,spreadUp:D.spread??NaN})}),i.push({text:`Inspect the machine for wear: ${c?D.text:l3(D.text)}`,owner:`maintenance`,urgent:!1,rank:.3,refs:[e]})}let O=e=>n.filter(t=>t.status===e).length,k=O(`Watch`)-p.size+f.length,A=u.length===1&&u[0].length===O(`Drifting`),j=[O(`Replace`)?`${o3(O(`Replace`),`sensor`)} to replace`:``,O(`Drifting`)?`${O(`Drifting`)} drifting${A?` together${c?` on ${l(u[0][0].sid)}`:``}`:``}`:``,k?`${k} to watch`:``].filter(Boolean);return{out:{section:{...q4(`05`,n.length?`${j.length?c3(s3(j)):`All ${o3(n.length,`sensor`)} healthy`}${D?`, and signs of machine wear`:``}.`:`No sensor health was measured in this period.`,r,o),subtitle:K4(`Reliability data (ISO 14224 style)`),fold:!0},actions:i,next:a,numbers:{replace:O(`Replace`),drifting:O(`Drifting`),watch:k}},sensors:n,drifts:[...n.filter(e=>e.status===`Drifting`&&!d.has(e)).map(e=>e.drift),...u.map(e=>({..._(e),work:`Check the process${c?` on ${l(e[0].sid)}`:``} (${o3(e.length,`channel`)} drifting together)`}))],wear:D}}var V8=.0027,H8=240,U8=60,W8=new Set([`mean`,`min`,`max`,`first`,`last`]),G8=(e,t)=>e.length<=t?e:Array.from({length:t},(n,r)=>e[Math.round(r*(e.length-1)/(t-1))]);function K8(e,t){let n=e.context,r=new Set([...L8(e),...I8(e)]),i=e=>{let t=e.lastIndexOf(`:`),i=e.slice(0,t),a=B6(n?.channels[i]);return t>0&&W8.has(e.slice(t+1))&&!r.has(i)&&a!==`setting`&&a!==`ignore`&&a!==`energy`&&a!==`category`},a=e.streams.length>1,o=[];for(let[e,n]of A3(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 N3(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=>`${x3(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<=H8?l.pts:G8(l.pts,H8-U8),p=new Set(f),m=l.pts.length<=H8?[]:G8(l.pts.filter(e=>e.out&&!p.has(e)),U8);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)}: ${o3(t.out,`batch`,`batches`)} of ${t.n.toLocaleString(`en-GB`)} (${Y4(100*t.out/t.n)}) outside its control limits, ${Z4(t.lcl)} to ${Z4(t.ucl)}${c(t)}, the first on ${p3(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)}: ${o3(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 q8(e,t){let n=1.2533*Math.sqrt(R3(t)**2/t.length+R3(e)**2/e.length),r=L3(t)-L3(e);return{d:r,lo:r-1.96*n,hi:r+1.96*n}}function J8(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 Y8(e,t){let n=o8(e.context??z6()),r=e.tz,{from:i,to:a}=e.period,o=Object.keys(n.channels).filter(e=>B6(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 A3(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*L3(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([...A3(t,e=>e.c.streamId)].map(([e,t])=>[e,t.slice().sort((e,t)=>e.c.tstart-t.c.tstart)])),p=new Set(Object.keys(n.channels).filter(e=>n.channels[e].lsl!==null||n.channels[e].usl!==null)),m=e.value.key.replace(/~.*$/,``),h=[...new Set(t.flatMap(e=>Object.keys(e.c.kpis)))].filter(e=>e!==m&&p.has(e.slice(0,e.lastIndexOf(`:`)))),g=new Set([...o,...p]),_=[...new Set(t.flatMap(e=>Object.keys(e.c.kpis)))].filter(e=>{if(g.has(e.slice(0,e.lastIndexOf(`:`))))return!1;let n=new Set(t.map(t=>t.c.kpis[e]).filter(N3));return n.size>=2&&n.size<=6&&[...n].every(Number.isInteger)}),v=new Map,y=(e,t,n)=>{let i=`${e}\u0000${n.join(`|`)}`;if(!v.has(i)){let e=e=>n.map(t=>e.c.kpis[t]).join(`|`),a=new Map([...A3(t,e)].map(([e,t])=>[e,L3(t.map(e=>e.c.value))])),o=n8(r),s=t.map(e=>o(e.c.tstart)),c=new Map;s.forEach((e,t)=>{let n=c.get(e);n?n[1]=t+1:c.set(e,[t,t+1])}),v.set(i,{adj:t.map(t=>t.c.value-(n.length?a.get(e(t)):0)),day:s,span:c})}return v.get(i)},b=d.map(t=>{let n=f.get(t.sid)??[],i=J8(n,t.t),a=_.filter(e=>!e.startsWith(`${t.ch.split(` · `).pop()}:`)),{adj:o,span:s}=y(t.sid,n,a),[c,l]=s.get(eD(t.t,r))??[i,i],u=e=>{let t=e.map(e=>o[e]),n=L3(t),r=1.4826*R3(t);return t.filter(e=>!(r>0)||Math.abs(e-n)<=3*r)},d=(e,t)=>Array.from({length:Math.max(0,t-e)},(t,n)=>e+n),p=u(d(Math.min(c,i),i)),m=u(d(i,Math.max(l,i))),g=p.length>=5&&m.length>=5,v=g?p:u(d(Math.max(0,i-20),i)),b=g?m:u(d(i,Math.min(n.length,i+20))),x=v.length>=5&&b.length>=5,S=L3(v),C=L3(b),w=x?H3(b,v):{p:1,effect:.5},T=x?q8(v,b):null,E=h.flatMap(e=>{let t=n.slice(Math.max(0,i-20),i).map(t=>t.c.kpis[e]).filter(N3),r=n.slice(i,i+20).map(t=>t.c.kpis[e]).filter(N3);if(t.length<5||r.length<5)return[];let a=H3(r,t);return a.p<.01/Math.max(1,h.length)?[{key:e,mb:L3(t),ma:L3(r),p:a.p}]:[]});return{...t,enough:x,mb:S,ma:C,shift:T,useDay:g,strata:a.map(e=>e.slice(0,e.lastIndexOf(`:`))),p:w.p,worse:e.value.better===`min`?w.effect>.5:w.effect<.5,quality:E}}),x=Z3(b.map(e=>e.enough?e.p:1),a6),S=[],C=[],w=new Map,T=e.value.label,E=i3(e)?` ${i3(e)}`:``;b.forEach((e,t)=>{let n=e.enough&&x[t];if(!n&&!e.quality.length)return;let i=`F08-${S.length+1}`,a=m3(e.t,r),[o,s]=$4(e.a,e.b);w.set(t,i);let c=e.quality.map(e=>{let[t,n]=$4(e.mb,e.ma);return`${x3(e.key)} went from ${t} to ${n}`}),l=e.shift,[u,d,f]=n?$4(Math.abs(l.d),Math.abs(l.lo),Math.abs(l.hi)):[``,``,``],p=`${e.useDay?`the same day’s batches`:`the 20 batches each side`}${e.strata.length?`, within each ${s3(e.strata)}`:``}`,m=l&&l.d!==0&&Math.sign(l.lo)===Math.sign(l.hi)?`${T} was ${u}${E} ${l.d<0?`lower`:`higher`} afterwards (${e.worse?`worse`:`better`}; 95% interval ${l.d<0?f:d} to ${l.d<0?d:f}${E}, on ${p})`:`${T} moved ${e.worse?`worse`:`better`} afterwards (on ${p})`,h=[...n?[m]:[],...c.map((e,t)=>t===0&&!n?`${e} afterwards`:e)];S.push({id:i,section:`08`,refs:[`08`],evidence:`statistical`,p:n?e.p:e.quality[0].p,numbers:d6({from:e.a,to:e.b,before:e.mb,after:e.ma,p:e.p,effect:e.shift?.d??NaN,lo:e.shift?.lo??NaN,hi:e.shift?.hi??NaN}),text:`${e.ch} was changed from ${o} to ${s} on ${a}; ${h.join(`; `)}.`}),n&&e.worse&&C.push({text:`Review the ${e.ch} change of ${a}: ${T} has been worse since.`,owner:`production`,urgent:!1,rank:Math.min(1,Math.abs(e.ma-e.mb)/(Math.abs(e.mb)||1)),refs:[i]})});let D=[...b.map((e,t)=>{let[n,i]=$4(e.a,e.b);return{t:e.t,row:{cells:[m3(e.t,r),e.ch,n,i,e.enough?`${n3(e.ma-e.mb)} (${S3(e.p)})`:`Too few batches to tell`],...w.has(t)?{finding:w.get(t),...e.worse?{status:`watch`}:{}}:{}}}}),...s.map(e=>({t:e.t,row:{cells:[m3(e.t,r),c?`${l(e.streamId)} · Golden`:`Golden`,`–`,e.label,`–`]}}))].sort((e,t)=>e.t-t.t).map(e=>e.row),O=[...new Set(s.map(e=>`The golden changed on ${m3(e.t,r)}; every batch in this report is judged against the current one.`))];return{section:q4(`08`,S.length?`${o3(d.length,`setting change`)} in the period; ${S.length} ${S.length===1?`was`:`were`} followed by a different ${T} or quality.`:d.length?`${o3(d.length,`setting change`)} in the period, none followed by a clear difference in ${T}.`:O[0],S,[{kind:`table`,title:`08.1 · Changes of settings`,columns:[`When`,`Setting`,`From`,`To`,`Effect on ${T}`],rows:D}],O),actions:C,next:[],numbers:{changes:d.length,goldens:s.length}}}function X8(e,t,n=R8(e,t)){let r=new Map([...A3(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=J8(i,n);for(;a<i.length&&i[a].c.tstart===n;)a++;return i.slice(J8(i,t),a)},a=A3(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,m3(e.t0,c),m3(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:`${o3(e.xs.length,`batch`,`batches`)} ${e.xs.length===1?`was`:`were`} made while ${e.s.ch} `+(e.stuck?`was stuck (from ${g3(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 ${g3(e.t0,e.t1,c,` to `)}. Check them before they ship.`)})),actions:s.map((e,t)=>({text:`Check the ${o3(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 Z8={W:{base:`kWh`,perS:.001/3600},kW:{base:`kWh`,perS:1/3600},MW:{base:`kWh`,perS:1e3/3600},Wh:{base:`kWh`,meter:.001},kWh:{base:`kWh`,meter:1},MWh:{base:`kWh`,meter:1e3},L:{base:`L`,meter:1},"L/s":{base:`L`,perS:1},"L/min":{base:`L`,perS:1/60},"L/h":{base:`L`,perS:1/3600},"m³":{base:`m³`,meter:1},m3:{base:`m³`,meter:1},"m³/h":{base:`m³`,perS:1/3600},"m3/h":{base:`m³`,perS:1/3600},kg:{base:`kg`,meter:1},t:{base:`kg`,meter:1e3},"kg/s":{base:`kg`,perS:1},"kg/min":{base:`kg`,perS:1/60},"kg/h":{base:`kg`,perS:1/3600},"t/h":{base:`kg`,perS:1e3/3600}},Q8=e=>Z8[(e??``).trim()]??null,$8=`kW, W, MW, kWh, Wh, MWh (energy), L, L/h, m³, m³/h, kg, kg/h or t (fuel, water, gas, steam)`,e5=`Scope 2, location-based, factor entered by you`;function t5(e,t){let n=Q8(e.context?.channels[t]?.unit)?.meter,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 n5(e,t){let n=e.context,r=V6(n);if(!n||!r)return null;let i=t.filter(e=>N3(e.c.kwh)&&e.c.kwh>=0);if(i.length<5)return{section:`09`,needs:`09 · ${r} has ${i.length?`a measure in only ${i.length} of`:`no measure in`} this period’s batches: check it is recorded and its unit in Process context is one of ${$8}.`};let a=Q8(n.channels[r]?.unit)?.base??`kWh`,o=a===`kWh`,s=o?n.costs.kwh:null,c=n.costs.currency,l=o?n.costs.co2:null,u=o?`energy`:r,d=` ${a}`,f=o?``:` of ${r}`,p=i.map(e=>e.c.kwh),m=L3(p),h=p.reduce((e,t)=>e+t,0),g=t5(e,r),_=g!==null&&g>=h?g:h,v=[],y=[],b=(e.previous?.cycles??[]).map(e=>e.kwh).filter(e=>N3(e)&&e>=0),x=b.length>=5?L3(b):NaN,[S,C]=$4(m,x),w=(m-x)/x*100,T=Math.abs(w)>=10?Math.round(w):+w.toFixed(1),E=Number.isFinite(x)?S===C||!T?`, as the period before`:`, against ${C} the period before (${n3(T)}%)`:``,D=[...s===null?[]:[X4(m*s,c)],...l===null?[]:[`${Z4(m*l)} kg CO₂ (${e5})`]];v.push({id:`F09-1`,section:`09`,refs:[`09`],evidence:`measured`,p:null,numbers:d6({kwh:m,before:x,cost:s===null?NaN:m*s,co2:l===null?NaN:m*l,total:_,inBatches:h}),text:`A batch uses ${S}${d}${f} (median)${E}${D.length?`: ${D.join(` and `)}`:``}; ${Z4(_)}${d} in the period${_>h?`, ${Z4(h)} of them while a batch ran`:``}.`});let O=i.filter(e=>e.level===`off`).map(e=>e.c.kwh),k=i.filter(e=>e.level!==`off`).map(e=>e.c.kwh),A=!1,j=[],M=e=>s===null?``:` (${X4(e*s,c)})`;if(_>h&&j.push({kind:`bars`,title:`09.1 · Where the period’s ${u} goes${s===null?``:`, and what it costs`}`,max:Math.max(h,_-h),rows:[{label:`While a batch runs`,kwh:h},{label:`Between batches, in stops and breaks`,kwh:_-h}].sort((e,t)=>t.kwh-e.kwh).map(e=>({label:e.label,value:e.kwh,text:`${Z4(e.kwh)}${d}${M(e.kwh)}`,tip:`${e.label}: ${J4(e.kwh/_)} of the period’s ${u}`}))}),O.length>=5&&k.length>=5){let e=L3(O),t=L3(k),n=H3(O,k);if(n.p<.01&&e>t&&t>0){A=!0;let a=(e-t)*O.length,[l,p]=$4(e,t);j.push({kind:`bars`,title:`09.2 · ${o?`Energy`:r} per batch: off-golden batches against the rest (median)`,max:e,rows:[{label:`Off-golden batches`,value:e,text:`${l}${d}`,tip:`Off-golden batches: ${l}${d} a batch (median of ${O.length.toLocaleString(`en-GB`)})`},{label:`At golden level or better`,value:t,text:`${p}${d}`,muted:!0,tip:`At golden level or better: ${p}${d} a batch (median of ${k.length.toLocaleString(`en-GB`)})`}]}),v.push({id:`F09-2`,section:`09`,refs:[`09`],evidence:`statistical`,p:n.p,numbers:d6({off:e,rest:t,extra:a,p:n.p}),text:`Off-golden batches use ${Y4((e-t)/t*100)} more ${u} than the rest: ${Z4(a)}${d}${s===null?``:`, up to ${X4(a*s,c)}`}, in the period.`}),y.push({text:`Bring off-golden batches to golden level (see 02) to save up to ${Z4(a)}${d}${f}${s===null?``:` (${X4(a*s,c)})`} in a period like this one.`,owner:`production`,urgent:!1,rank:(e-t)/t*(O.length/i.length),refs:[`F09-2`]})}}return{section:{...q4(`09`,`${s===null?`${Z4(_)}${d}${f}`:`${X4(_*s,c)} of energy`} in the period${A?`; off-golden batches use more`:``}.`,v,j),...o?{subtitle:K4(`Energy review inputs (ISO 50001)`)}:{title:`Consumption`},fold:!0},actions:y,next:[],numbers:{kwh:m,energy:+!!o}}}var r5=1800,i5=2400,a5=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],o5=[`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`,`Sunday`],s5=e=>`${String(e%24).padStart(2,`0`)}:00`,c5=(e,t)=>e.c.z?.[t.ch]?.[t.piece];function l5(e,t){let n=e.value.key.replace(/~.*$/,``).replace(/:[^:]*$/,``),r=t=>{let n=e.context?.channels[t];return n&&!n.suggested?n.role:null};return[...new Set(t.slice(0,5e3).flatMap(e=>Object.keys(e.c.kpis).filter(e=>e.endsWith(`:last`)).map(e=>e.slice(0,-5))))].filter(e=>{if(e===n)return!1;let i=r(e);if(i===`category`)return t.some(t=>N3(t.c.kpis[`${e}:last`]));if(i!==null)return!1;let a=new Set,o=0,s=0;for(let n of t){let t=n.c.kpis[`${e}:first`],r=n.c.kpis[`${e}:last`];if(N3(r)&&(!Number.isInteger(r)||(a.add(r),o++,(t==null||t===r)&&s++,a.size>12)))return!1}return o>=10&&a.size>=2&&s>=.95*o}).sort()}function u5(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 d5(e,t){let n=t6(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 f5(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 t=e.value.key.replace(/~.*$/,``),n=t===`duration`?null:t.slice(0,t.lastIndexOf(`:`)),o=u5(u).filter(e=>e.ch!==n).map(e=>{let t=u.filter(t=>N3(c5(t,e)));return{f:e,mw:H3(d.map(t=>c5(t,e)).filter(N3),f.map(t=>c5(t,e)).filter(N3)),r:Q3(t.map(t=>c5(t,e)),t.map(e=>e.gap))}}),c=Z3(o.map(e=>e.mw.p),a6),l=o.filter((e,t)=>c[t]&&e.mw.effect>.5&&e.r>0).sort((e,t)=>t.r-e.r).slice(0,8),m=u.filter(e=>l.every(t=>N3(c5(e,t.f)))),h=m.map(e=>l.map(t=>c5(e,t.f))),g=m.map(e=>e.gap),_=l.length?d5(h,g):null;if(_){let e=_.shares.map((e,t)=>t).sort((e,t)=>_.shares[t]-_.shares[e]),t=e[0],n=l[t],o=i6(m.length,e=>d5(e.map(e=>h[e]),e.map(e=>g[e]))?.shares[t]??NaN),c=e.filter(e=>_.shares[e]>=.01),u=Math.max(0,1-_.r2);p={label:n.f.label,share:_.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 (${o3(m.length,`batch`,`batches`)} measured, ${d.length.toLocaleString(`en-GB`)} off-golden)`,max:Math.max(u,...c.map(e=>_.shares[e]))*1.1,rows:[...c.map(e=>({label:l[e].f.label,value:_.shares[e],text:J4(_.shares[e]),tip:`${l[e].f.label} goes with ${J4(_.shares[e])} of the difference in how far batches are from the golden`})),{label:`Not explained by the recorded channels`,value:u,text:J4(u),muted:!0,tip:`Goes with none of the channels recorded: something else changes between batches.`}]});let f=d.reduce((e,t)=>t.gap>e.gap?t:e,d[0]),v=s({focus:{ch:n.f.ch,piece:n.f.piece},...f?{batch:{streamId:f.c.streamId,cycleId:f.c.id}}:{},text:`${n.f.label} goes with ${J4(p.share)} of the difference in how far batches are from the golden${c.length>1?`; the ${c.length} differences together go with ${J4(_.r2)}`:``}.`,evidence:`correlation`,p:n.mw.p,numbers:d6({share:p.share,lo:o.lo,hi:o.hi,r2:_.r2,r:n.r,p:n.mw.p})},p.share);for(let e of c.slice(0,3)){let t=l[e].f;r.push({text:`Test bringing ${t.ch}${t.piece===`Cycle`?``:` in ${t.piece}`} back to the golden: it goes with ${J4(_.shares[e])} of the difference in how far batches are from the golden.`,owner:`production`,urgent:!1,rank:_.shares[e],refs:[v]})}u>=.2&&i.push(`${J4(u)} 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 A3(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=X3(l(h),h.length,l(g),g.length);if(e.p<.01&&e.p1>e.p2){let n=s({text:`Off-golden share is ${J4(e.p1)} in the first ${i5/60} minutes after a stop of more than ${r5/60} minutes, against ${J4(e.p2)} the rest of the time.`,evidence:`statistical`,p:e.p,numbers:d6({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 ${r5/60} minutes: the first ${i5/60} minutes after a stop run ${J4(e.p1)} off-golden against ${J4(e.p2)}.`,owner:`production`,urgent:!1,rank:(e.p1-e.p2)*(h.length/t.length),refs:[n]})}}let _=(e,n,r=t)=>{let i=A3(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:X3(l(t),t.length,a-l(t),r.length-t.length)})),s=Z3(o.map(e=>e.t.p),a6),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 ${J4(v.t.p1)} off-golden against ${J4(v.t.p2)} on the other streams.`,evidence:`statistical`,p:v.t.p,numbers:d6({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 ${J4(y.t.p1)} off-golden against ${J4(y.t.p2)} in the rest of the period.`,evidence:`statistical`,p:y.t.p,numbers:d6({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=j3(t.map(e=>({t:e.c.tstart,v:e.gap})),n),i=r.length>=7?$3(r.map(e=>(e.t-n)/86400),r.map(e=>e.v)):null;if(i&&i.p<.01&&i.b!==0){let a=i3(e),o=a?` ${a}`:``,c=r[r.length-1].t;s({text:`The gap to the golden ${i.b>0?`grows`:`shrinks`} by ${Z4(Math.abs(i.b)*7)}${o} a week since ${p3(n,e.tz)}.`,evidence:`statistical`,p:i.p,numbers:d6({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=v3(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,r8(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=[...l5(e,t).flatMap(e=>{let n=_(t=>String(t.c.kpis[`${e}:last`]),5,t.filter(t=>N3(t.c.kpis[`${e}:last`])));return n?[{w:n,when:`with ${e} ${n.k}`,other:`with the other ${e} values`,look:`Find what goes with ${e} ${n.k}`}]:[]}),...C?[{w:C,when:`started between ${s5(+C.k)} and ${s5(+C.k+1)}`,other:`at other hours`,look:`Find what changes around ${s5(+C.k)} (a shift change, a start-up, a material change)`}]:[],...w?[{w,when:`on ${o5[+w.k]}s`,other:`on other days`,look:`Find what is different on ${o5[+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 ${J4(e.t.p1)} off-golden against ${J4(e.t.p2)} ${i}.`,evidence:`statistical`,p:e.t.p,numbers:d6({share:e.t.p1,others:e.t.p2,p:e.t.p})},o);r.push({text:`${a}: batches then run ${J4(e.t.p1)} off-golden against ${J4(e.t.p2)}.`,owner:`production`,urgent:!1,rank:o,refs:[c]})}if(O.length){let e=a5.map(()=>Array(24).fill(0)),n=a5.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:a5,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?`${J4(k)} of batches miss the golden. ${p.label} goes with most of the difference between them and the golden.`:`${J4(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:{...q4(`02`,A,n,a),fold:!0},actions:r,next:i,numbers:{off:c.length,share:k}}}function p5(e,t){let n=o8(e.context??z6()).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?X4(o(e.s),i):r3(e.s),detail:a?`${r3(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:X4(u,i),detail:`${Z4(t.energyKwh)} kWh more than batches at golden level`});let d=n.scrap,f=d===null?``:`${X4(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?o3(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?X4(o(m)+h,i):m?r3(m):X4(h,i),detail:`${e} outside their limits or flagged bad: ${[m?`${r3(m)} of line time`:``,h?`${X4(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 ${X4(p.money,i)}`,detail:`${o3(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=o3(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 ${X4(o(t.review.s),i)}`:e,detail:`${a?`${e}, `:``}${r3(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 ${X4(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 ${o3(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 ${X4(y,i)}`:v?r3(v):_[0].amount:`Nothing lost`,totalNote:b?a?`to recover in this period${v?`: ${r3(v)} of line time`:``}`:`of line time to recover in this period`:`against the golden in this period`,...S?{hint:S}:{}}}var m5=()=>({findings:[],charts:[],notes:[],actions:[],next:[]});function h5(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 g5=7200,_5=7200,v5=e=>e.reduce((e,t)=>e+t.t1-t.t0,0),y5=(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 b5(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 x5(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 S5(e,t,n,r){let i=y5([{t0:n,t1:r}],[{t0:e.period.from,t1:e.period.to}]);return i.length?(t.shifts.length&&(i=y5(i,b5(a8({...t,stops:t.shifts.map(e=>({name:e.name,from:e.start,to:e.end}))},e.tz,n,r)))),t.stops.length?x5(i,a8(t,e.tz,n,r)):i):i}function C5(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*L3(n):0)}function w5(e){return T5(e).stops}function T5(e){let t=o8(e.context??z6()),n=[],r=0,i=A3(e.cycles,e=>e.recordingId),a=A3(e.covered??[],e=>e.streamId);for(let[o,s]of A3([...e.recordings].sort((e,t)=>e.t0-t.t0),e=>e.streamId)){let c=C5(s.flatMap(e=>i.get(e.id)??[])),l=[],u=[...s,...a.get(o)??[]].sort((e,t)=>e.t0-t.t0),d=[],f=-1/0;for(let e of u)!e.continues&&e.t0-f>=300&&f>-1/0&&d.push({t0:f,t1:e.t0}),f=Math.max(f,e.t1);let p=d.map(e=>e.t1-e.t0).filter(e=>e<=g5),m=p.length>=5?5*L3(p):0;for(let n of d){let i=n.t1-n.t0;i<=m||(!t.shifts.length&&(eD(n.t0,e.tz)!==eD(n.t1,e.tz)||i>28800||!m&&i>7200)?v5(S5(e,t,n.t0,n.t1))>=300&&r++:l.push({streamId:o,t0:n.t0,t1:n.t1,kind:`no_data`,unit:null}))}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=S5(e,t,r.t0,r.t1),o=v5(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 E5(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?{...m5(),next:r}:null;let i=o8(e.context??z6()),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+v5(S5(e,i,n.t0,n.t1)),0)+v5(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=v5(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=[...A3(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=[...A3(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 ${r3(e.stopped)}.`:`${a(e.sid)} stopped ${a3(e.n)} for ${r3(e.stopped)} in total; it ran ${r3(e.mtbf)} between stops on average and took ${r3(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?[...A3(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];m.share>=.2&&p.push({text:`Find why ${m.label} stops: ${o3(m.n,`stop`)} cost ${r3(m.stopped)} this period.`,owner:`maintenance`,urgent:!1,rank:m.share,refs:[...new Set(m.xs.map(e=>u.get(e.streamId)))]});let h=[];for(let e of t.slice().sort((e,t)=>e.streamId.localeCompare(t.streamId)||e.t0-t.t0)){let t=h[h.length-1];e.part&&t&&t.streamId===e.streamId?(t.t1=e.t1,t.stopped+=e.t1-e.t0,t.pieces.push(e)):h.push({...e,stopped:e.t1-e.t0,pieces:[e]})}let g=new Map([...A3(e.cycles,e=>e.streamId)].map(([e,t])=>[e,t.map(e=>e.tstart)])),_=(e,t)=>{let n=0,r=0;for(let i of t){let t=new Set;for(let n of g.get(e)??[])n>=i.t0&&n<i.t1&&t.add(Math.floor((n-i.t0)/300));n+=Math.ceil((i.t1-i.t0)/300),r+=t.size}return n?r/n:0},v=e.streams.length>1?h.filter(t=>t.kind===`no_data`&&e.streams.every(e=>e.id===t.streamId||_(e.id,t.pieces)>=.8)).sort((e,t)=>t.stopped-e.stopped).slice(0,3):[];for(let t of v){let n=e.streams.filter(e=>e.id!==t.streamId).map(e=>e.name);c.push({id:`F05-S${c.length+1}`,section:`05`,refs:[`05`],evidence:`measured`,p:null,numbers:{seconds:t.stopped},text:`${a(t.streamId)}: nothing recorded from ${g3(t.t0,t.t1,e.tz,` to `)} (${r3(t.stopped)}) while ${s3(n)} made batches all along: a stop, or its recording was off. If it ran, check what records it.`})}let y=h.filter(e=>e.stopped>=_5).sort((e,t)=>t.stopped-e.stopped).slice(0,10);return{findings:c,notes:[],actions:p,charts:[...y.length?[{kind:`table`,title:`05.6 · Longest stops`,columns:[`When`,`Stream`,`Stopped`,`What the data shows`],rows:y.map(t=>({cells:[g3(t.t0,t.t1,e.tz,` to `),a(t.streamId),r3(t.stopped),t.kind===`no_data`?`Stopped, nothing recorded`:`Stopped, recorded with no batch made${t.unit?`; ${t.unit} went flat first`:``}`]})),...y.length>5?{shown:5,more:o3(y.length-5,`more stop`)}:{}}]:[],{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),r3(e.stopped),r3(e.mtbf),r3(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 D5=new Set([`mean`,`min`,`max`,`first`,`last`]),O5=()=>({plan:0,stop:0,ideal:0,n:0,good:0,badIdeal:0}),k5=e=>Math.max(0,e.plan-e.stop),A5=e=>{let t=k5(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 j5(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 A3(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?L3(t):NaN)}let t=n.map(e=>e.c).sort((e,t)=>e.tstart-t.tstart),i=C5(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)+I3(a,o6))}return r}function M5(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&&D5.has(e.slice(i+1))&&(n.usl!==null&&r>n.usl||n.lsl!==null&&r<n.lsl)}))}}function N5(e){if(e.value.key===`duration`)return!1;let t=e.value.key.replace(/~.*$/,``),n=e.context?.channels?.[t.slice(0,t.lastIndexOf(`:`))];return!n||n.lsl===null&&n.usl===null}var P5=K4(`OEE as ISO 22400-2`),F5={stops:`Stops`,slow:`Slow batches and short waits`,bad:`Bad parts`,off:`Off-golden batches`};function I5(e,t,n=[]){let r=e.context;if(!r?.shifts.length)return null;let i=e.tz,a=e.recordings,o=a.length?a8(r,i,Math.min(...a.map(e=>e.t0)),Math.max(...a.map(e=>e.t1))):[],s=j5(e,t),c=O5(),l=new Map,u=new Map,d=(e,t)=>e.get(t)??e.set(t,O5()).get(t),f=n8(i),p=(e,t)=>{let n=r8(e,r.shifts,i);if(n!==null)for(let r of[c,d(l,n),d(u,f(e))])t(r)},m=e=>({section:q4(`06`,e,[],[]),actions:[],next:[],numbers:{}});if(![...s.values()].some(Number.isFinite))return m(`No stream has a cycle time to compare, so OEE could not be measured.`);let h=new Set(e.recordings.filter(e=>e.failed).map(e=>e.id)),g=new Set(t.filter(e=>!h.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));p(n,e=>{e.plan+=i,g.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);p(n,t=>{t.stop+=r-n,e.kind===`no_data`&&(t.plan+=r-n)})}let _=!N5(e),{limits:v,outside:y}=M5(r),b=!1;for(let e of t){let t=s.get(e.c.streamId)??NaN;if(!Number.isFinite(t)||h.has(e.c.recordingId))continue;let n=e.c.flag===`bad`||y(e.c.kpis)||!_&&e.level===`off`;b||=n||e.c.flag===`good`,p(e.c.tstart,e=>{e.ideal+=t,e.n++,n?e.badIdeal+=t:e.good++})}if(!c.plan)return m(`No recorded time falls in the shifts, so OEE could not be measured.`);let x=A5(c),S=r.costs.currency,C=r.costs.lineHour,w=[...new Set(t.map(e=>s.get(e.c.streamId)??NaN).filter(Number.isFinite))].sort((e,t)=>e-t),T=e=>e<60?`${Z4(+e.toFixed(1))} s`:r3(e),E=w.length?r.idealCycleS?`Ideal cycle ${T(w[0])}, set in Process context.`:`Ideal cycle ${T(w[0])}${w.length>1&&T(w[0])!==T(w[w.length-1])?` to ${T(w[w.length-1])}`:``}, inferred from the data.`:``,D=e=>C===null?``:` (up to ${X4(e/3600*C,S)})`,O=[{label:F5.stops,s:c.plan-k5(c),owner:`maintenance`,act:e=>`Find what stops the line (see 05.4): ${e} of planned time stopped.`},{label:F5.slow,s:Math.max(0,k5(c)-c.ideal),owner:`production`,act:e=>`Bring the pace to the ideal cycle: slow batches and short waits cost ${e}.`},_?{label:F5.bad,s:c.badIdeal,owner:`quality`,act:e=>`Bring the bad parts inside their limits (see 04): they cost ${e}.`}:{label:F5.off,s:c.badIdeal,owner:`quality`,act:e=>`Bring off-golden batches to golden level (see 02): they cost ${e}.`}];O.sort((e,t)=>t.s-e.s);let k=O.reduce((e,t)=>e+t.s,0),A=O[0],j=[],M=[],N=[],P=e=>{let t=`F06-${j.length+1}`;return j.push({id:t,section:`06`,refs:[`06`],...e}),t};if(P({evidence:`measured`,p:null,numbers:d6({oee:x.oee,availability:x.A,performance:x.P,quality:x.Q,plannedH:c.plan/3600}),text:`OEE ${J4(x.oee)}: availability ${J4(x.A)}, performance ${J4(x.P)}, quality ${J4(x.Q)}, over ${r3(c.plan)} of planned time.${E?` ${E}`:``}`}),A.s>0){let e=P({evidence:`measured`,p:null,numbers:d6({hours:A.s/3600,share:A.s/k,cost:C===null?NaN:A.s/3600*C}),text:`${A.label} lose the most: ${r3(A.s)}${D(A.s)}, ${J4(A.s/k)} of the ${r3(k)} lost.`});M.push({text:A.act(`${r3(A.s)}${D(A.s)}`),owner:A.owner,urgent:!1,rank:A.s/c.plan,refs:[e]})}let F=r.shifts.filter(e=>l.has(e.name)).map(e=>{let t=l.get(e.name),n=A5(t);return{cells:[e.name,J4(n.A),t.n?J4(n.P):`–`,t.n?J4(n.Q):`–`,J4(n.oee)]}});k>0&&N.push({kind:`bars`,title:`06.1 · Where planned time is lost${C===null?``:`, and what it costs`}`,max:A.s/3600,rows:O.filter(e=>e.s>=60).map(e=>({label:e.label,value:e.s/3600,text:`${r3(e.s)}${D(e.s)}`,tip:`${e.label}: ${J4(e.s/k)} of the time lost`}))}),F.length>1&&!r.hideShifts&&N.push({kind:`table`,title:`06.2 · OEE by shift`,columns:[`Shift`,`Availability`,`Performance`,`Quality`,`OEE`],rows:F});let I=[...u].filter(([,e])=>e.plan>0).map(([e,t])=>({t:tD(e,`00:00`,i),v:A5(t).oee})).sort((e,t)=>e.t-t.t),L=I.length>=7?$3(I.map(e=>(e.t-I[0].t)/86400),I.map(e=>e.v)):null;if(L&&L.p<.01&&Math.abs(L.b*700)>=1){P({evidence:`statistical`,p:L.p,numbers:d6({perWeek:L.b*7,days:L.n,p:L.p}),text:`OEE ${L.b<0?`falls`:`rises`} by ${Math.round(Math.abs(L.b*700))} points a week since ${p3(I[0].t,i)}.`});let e=I[0].t,t=I[I.length-1].t;N.push({kind:`trend`,title:`06.3 · OEE per day, with its trend`,unit:`%`,points:I.map(e=>({t:e.t,v:e.v*100})),line:{t0:e,v0:L.a*100,t1:t,v1:(L.a+L.b*(t-e)/86400)*100},limit:null,crossing:null})}let R=A.s>0?`${A.label} lose the most time.`:`No planned time is lost.`,z=_&&c.n&&!b&&!v.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:{...q4(`06`,R,j,N),subtitle:P5,fold:!0},actions:M,next:z,numbers:{oee:x.oee,stopsS:c.plan-k5(c),slowS:Math.max(0,k5(c)-c.ideal),offS:c.badIdeal}}}function L5(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=A3(t.filter(e=>r.has(e.c.streamId)),e=>r.get(e.c.streamId)),a=e=>({section:q4(`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:X3(n,t.length,s-n,o.length-t.length)}}),l=Z3(c.map(e=>e.t.p),a6),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),f=M5(e.context),p=e=>e.c.flag===`bad`||f.outside(e.c.kpis),m=f.limits.length?o.filter(p).length:0,h=m?[...i].map(([e,t])=>{let n=t.filter(p).length;return{name:e,xs:t,t:X3(n,t.length,m-n,o.length-t.length)}}):[],g=Z3(h.map(e=>e.t.p),a6),_=h.filter((e,t)=>g[t]&&e.t.p1>e.t.p2&&e.xs.length>=5).sort((e,t)=>t.t.p1-t.t.p2-(e.t.p1-e.t.p2)).slice(0,i.size===2?1:void 0);if(!d.length&&!_.length)return a(`The lines run alike: none misses the golden more often than the others.`);let v=[],y=[],b=new Map;for(let e of _){let t=`F10-${v.length+1}`;v.push({id:t,section:`10`,refs:[`10`,`04`],evidence:`statistical`,p:e.t.p,numbers:d6({share:e.t.p1,others:e.t.p2,p:e.t.p,batches:e.xs.length}),text:`${e.name} makes ${J4(e.t.p1)} of its batches outside their limits against ${J4(e.t.p2)} on the other lines.`}),y.push({text:`Find why ${e.name} makes more batches outside their limits: ${J4(e.t.p1)} against ${J4(e.t.p2)} on the other lines (see 04).`,owner:`quality`,urgent:!1,rank:(e.t.p1-e.t.p2)*10,refs:[t]})}for(let e of d){let t=`F10-${v.length+1}`;b.set(e.name,t),v.push({id:t,section:`10`,refs:[`10`],evidence:`statistical`,p:e.t.p,numbers:d6({share:e.t.p1,others:e.t.p2,p:e.t.p,batches:e.xs.length}),text:`${e.name} runs ${J4(e.t.p1)} off-golden against ${J4(e.t.p2)} on the other lines.`}),u(e)&&y.push({text:`Find what ${e.name} does differently from the other lines: it runs ${J4(e.t.p1)} off-golden against ${J4(e.t.p2)}.`,owner:`production`,urgent:!1,rank:(e.t.p1-e.t.p2)*(e.xs.length/o.length),refs:[t]})}let x=[{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=b.get(e.name);return{cells:[e.name,e.xs.length.toLocaleString(`en-GB`),J4(1-e.t.p1),J4(e.better/e.xs.length)],...t?{finding:t,status:u(e)?`crit`:`ok`}:{}}})}];if(!d.length)return{section:q4(`10`,v[0].text,v,x),actions:y,next:[],numbers:{lines:i.size}};let S=d.filter(u),C=e=>s3(e.slice(0,2).map(e=>e.name))+(e.length>2?` and ${o3(e.length-2,`more line`)}`:``);return{section:q4(`10`,S.length?`${C(S)} ${S.length>1?`miss`:`misses`} the golden more often than the other lines.`:`${C(d)} ${d.length>1?`miss`:`misses`} the golden less often than the other lines.`,v,x),actions:y,next:[],numbers:{lines:i.size}}}var R5=86400;function z5(e,t,n){if(!t.length&&!n)return null;let r=o8(e.context??z6()),i=e.tz,a=e.period.to,o=r.stops.length?a8(r,i,a,a+90*R5).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`:y3(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 ${J4(n.spread)}`:`cycle time ${n3(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?`–`:p3(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 ${o3(c.length,`maintenance job`)}${l.now?`: the first now`:u?`: the first by ${p3(u.by,i)}`:``}.`}],actions:[],notes:[],next:o?[]:[`Add planned stops in Process context to place maintenance in them.`]}}function B5(e,t,n){if(e<=0)return 0;if(n<=0)return-1/0;if(n>=1)return 0;let r=Math.log(n),i=Math.log1p(-n),a=[];for(let n=e;n<=t;n++)a.push(U3(t+1)-U3(n+1)-U3(t-n+1)+n*r+(t-n)*i);let o=Math.max(...a);return o+Math.log(a.reduce((e,t)=>e+Math.exp(t-o),0))}function V5(e,t,n,r=3){if(e.length<1||t.length<10)return[];let i=new Set([...e,...t].flatMap(e=>[...Object.keys(e.c.d??{}),...Object.keys(e.c.range??{})])),a=[],o=(e,t,n)=>n===`mean`?e.c.d?.[t]:e.c.range?.[t]?.[n===`min`?0:1];for(let s of i){if(n.has(s))continue;let i=null;for(let n of[`mean`,`min`,`max`]){let a=t.map(e=>o(e,s,n)).filter(N3),c=e.map(e=>o(e,s,n)).filter(N3);if(a.length<10||!c.length)continue;let l=1.4826*R3(a);if(!(l>0))continue;let u=L3(c)-L3(a),d=u/l;Math.abs(d)>=r&&(!i||Math.abs(d)>Math.abs(i.z))&&(i={ch:s,stat:n,diff:u,z:d})}i&&a.push(i)}return a.sort((e,t)=>Math.abs(t.z)-Math.abs(e.z))}function H5(e,t){let n=t[e.ch]?` ${t[e.ch]}`:``,[r]=$4(Math.abs(e.diff));return`${e.stat===`mean`?e.ch:`${e.ch}'s ${e.stat===`max`?`highest`:`lowest`}`} ${r}${n} ${e.diff>0?`higher`:`lower`}`}function U5(e,t){let n=e.length,r=[],i=new Uint8Array(n);for(let a=0;a<3;a++){let a=e.filter((e,t)=>e&&!i[t]).length,o=n-r.reduce((e,t)=>e+t.b-t.a+1,0),s=a/Math.max(1,o),c=e=>t?.[e]??s,l=0,u=-1,d=-1,f=0,p=0;for(let t=0;t<n;t++){if(i[t]){f=0,p=t+1;continue}f+=+!!e[t]-Math.min(.5,Math.max(3*c(t),.02)),f<=0?(f=0,p=t+1):f>l&&(l=f,u=p,d=t)}if(u<0)break;let m=e.slice(u,d+1).filter(Boolean).length,h=d-u+1,g=t?e.slice(u,d+1).reduce((e,t,n)=>e+c(u+n),0)/h:(a-m)/Math.max(1,o-h);if(m<5||B5(m,h,Math.max(g,1/n))>Math.log(1e-6))break;r.push({a:u,b:d,k:m});for(let e=u;e<=d;e++)i[e]=1}return r}function W5(e,t,n=[],r=new Map){let i=o8(e.context??z6()),a=M5(i);if(!a.limits.length)return null;let o=new Map(i.lines.flatMap(e=>e.streams.map(t=>[t,e.name]))),s=(e,t)=>!i.lines.length||o.get(e)!==void 0&&o.get(e)===o.get(t)||i.lines.every(e=>e.streams.length<=1),c=e.tz,l=e.streams.length>1,u=e.units,d=t=>e.streams.find(e=>e.id===t)?.name??t,f=e=>l?`${d(e)}: `:``,p=a.limits.map(([e])=>e),m=new Set([...p,...Object.keys(i.channels).filter(e=>[`ignore`,`outside`,`category`].includes(B6(i.channels[e])??``))]),h=e=>e.c.flag===`bad`||a.outside(e.c.kpis),g=e=>{let t=new Map;for(let n of e)for(let[e,r]of a.limits)for(let[i,a]of Object.entries(n.c.kpis))i.slice(0,i.lastIndexOf(`:`))!==e||!N3(a)||(r.usl!==null&&a>r.usl||r.lsl!==null&&a<r.lsl)&&t.set(e,(t.get(e)??0)+1);let n=[...t].sort((e,t)=>t[1]-e[1])[0]?.[0]??p[0],r=i.channels[n],[o,s]=$4(r.lsl??NaN,r.usl??NaN);return`outside ${n}'s limits (${r.lsl!==null&&r.usl!==null?`${o} to ${s}`:r.lsl===null?`${s} or less`:`${o} or more`})`},_=[],v=[],y=[],b=()=>`F04-B${_.length+1}`,x=0;for(let[e,i]of A3(t,e=>e.c.streamId)){let a=i.slice().sort((e,t)=>e.c.tstart-t.c.tstart),o=a.map(h),l=o.filter(Boolean).length;if(!l)continue;x+=l;let p=a.filter((e,t)=>!o[t]),S=t=>n.find(n=>n.sid===e&&t>=n.t0&&t<=n.t1);if(l<=10){let n=a.filter((e,t)=>o[t]),r=n.map(n=>{let r=t.filter(t=>t.c.streamId!==e&&s(e,t.c.streamId)&&Math.abs(t.c.tstart-n.c.tstart)<=43200&&!h(t)),i=S(n.c.tstart),a=i?null:V5([n],r.length>=10?r:p,m,4)[0],o=i?`made while ${i.ch} was stuck: its reading can't be trusted`:a?H5(a,u):`nothing recorded stood out`;return y.push([m3(n.c.tstart,c),d(e),o]),{x:n,why:o,s:i}}),i=r.filter(e=>!e.s),x=b();_.push({id:x,section:`04`,refs:[`04`],evidence:`measured`,p:null,numbers:{batches:l},text:`${f(e)}${o3(l,`batch`,`batches`)} ${g(n)}: ${r.map(e=>`${m3(e.x.c.tstart,c)} (${e.why})`).join(`; `)}.`}),i.length&&v.push({text:`${f(e)}Hold the ${o3(i.length,`batch`,`batches`)} ${g(i.map(e=>e.x))} for review, and check what went with ${i.length===1?`it`:`them`} (see 04).`,owner:`quality`,urgent:!0,rank:2,refs:[x]});continue}let C=e=>Math.floor((e.c.tstart-a[0].c.tstart)/86400),w=[...A3(a.map((e,t)=>({x:e,bad:o[t]})),e=>C(e.x))].map(([e,t])=>({d:e,share:t.filter(e=>e.bad).length/t.length,n:t.length})).filter(e=>e.n>=10).sort((e,t)=>e.d-t.d),T=null;if(w.length>=7){let e=$3(w.map(e=>e.d),w.map(e=>e.share)),t=Math.max(1,Math.floor(w.length/3)),n=e=>e.reduce((e,t)=>e+t.share*t.n,0)/e.reduce((e,t)=>e+t.n,0),r=n(w.slice(0,t)),i=n(w.slice(-t));e&&e.p<.01&&e.b>0&&i>=2*Math.max(r,.001)&&(T={a:e.a,b:e.b,p:e.p,s0:r,s1:i})}let E=U5(o,T?a.map(e=>Math.min(1,Math.max(0,T.a+T.b*C(e)))):void 0),D=new Uint8Array(a.length);for(let e of E)for(let t=e.a;t<=e.b;t++)D[t]=1;let O=a.filter((e,t)=>!o[t]&&!D[t]),k=(n,r)=>{let i=t.filter(t=>t.c.streamId!==e&&s(e,t.c.streamId)&&t.c.tstart>=n&&t.c.tstart<=r&&!h(t));return i.length>=10?{xs:i,against:`on the other streams at the same time`}:{xs:O,against:`in good batches`}};for(let t of E){let n=a.slice(t.a,t.b+1),r=n.filter(h),i=n.length,o=g(r),s=(l-t.k)/Math.max(1,a.length-i),d=t.b===a.length-1,p=n[0].c.tstart,y=n[n.length-1].c.tend??n[n.length-1].c.tstart,x=k(p,y),C=S(p)?[]:V5(r,x.xs,m).slice(0,2),w=b(),T=g3(p,y,c,` to `);_.push({id:w,section:`04`,refs:[`04`],evidence:`statistical`,p:null,numbers:d6({batches:t.k,of:i,share:t.k/i,others:s}),text:`${f(e)}${t.k.toLocaleString(`en-GB`)} of ${o3(i,`batch`,`batches`)} ${o} from ${T}${d?`, still at the end of the period`:``} (${J4(t.k/i)} against ${J4(s)} otherwise)${C.length?`; meanwhile ${s3(C.map(e=>H5(e,u)))} than ${x.against}`:``}.`}),v.push({text:`${f(e)}Find what changed ${d?`since`:`from`} ${T.split(` to `)[0]}, when ${o3(t.k,`batch`,`batches`)} went ${o}${C.length?` with ${H5(C[0],u)}`:``}.`,owner:`production`,urgent:d||t.k>=.2*l,rank:1+t.k/l,refs:[w]})}if(T){let t=g(a.filter((e,t)=>!D[t]).filter(h)),n=(r.get(e)??[]).filter(e=>!m.has(e)).slice(0,2),i=b();_.push({id:i,section:`04`,refs:[`04`,...n.length?[`05`]:[]],evidence:`statistical`,p:T.p,numbers:d6({from:T.s0,to:T.s1,perDay:T.b,p:T.p}),text:`${f(e)}batches ${t} grow from ${J4(T.s0)} to ${J4(T.s1)} over the period, a steady rise consistent with wear of a tool or a part${n.length?`, as ${s3(n)} ${n.length===1?`drifts`:`drift`} (see 05)`:``}.`}),v.push({text:`${f(e)}Inspect for wear before more batches go ${t}: their share grew from ${J4(T.s0)} to ${J4(T.s1)}${n.length?`, as ${s3(n)} ${n.length===1?`drifts`:`drift`}`:``}.`,owner:`maintenance`,urgent:!0,rank:1.5,refs:[i]})}}return _.length?{findings:_,actions:v,charts:y.length?[{kind:`table`,title:`04.3 · Batches outside their limits, and what went with them`,columns:[`When`,`Stream`,`What went with it`],rows:y.map(e=>({cells:e,status:`crit`}))}]:[],bad:x}:null}function G5(e,t,n=new Set){let r=o8(e.context??z6()),i=e.tz,a=L8(e),o=Object.entries(r.channels).filter(([e,t])=>(t.lo!==null||t.hi!==null)&&!a.has(e));if(!o.length)return null;let s=e.streams.length>1,c=t=>e.streams.find(e=>e.id===t)?.name??t,l=e.value.key===`duration`,u=e.value.label,d=[],f=[];for(let[r,a]of A3(t,e=>e.c.streamId)){let t=a.slice().sort((e,t)=>e.c.tstart-t.c.tstart);for(let[a,p]of o){let o=t.map(e=>{let t=e.c.range?.[a];return t?p.hi!==null&&t[1]>p.hi?1:p.lo!==null&&t[0]<p.lo?-1:0:0}),m=new Map([1,-1].map(e=>[e,o.filter(t=>t===e).length])),h=e=>m.get(e)/t.length,g=(e,n)=>t.length*Math.max(0,(h(n)*t.length-e)/Math.max(1,t.length-e))**e,_=new Map,v=0;for(;v<t.length;){let e=o[v];if(!e){v++;continue}let n=v;for(;n+1<t.length&&o[n+1]===e;)n++;let r=t.slice(v,n+1),s=r[0].c.tstart,c=r[r.length-1].c.tend??r[r.length-1].c.tstart;if(v=n+1,r.length<5||c-s<600||h(e)>.1||g(r.length,e)>=.01)continue;let l=e>0?Math.max(...r.map(e=>e.c.range[a][1])):Math.min(...r.map(e=>e.c.range[a][0])),u=p.lo!==null&&p.hi!==null?p.hi-p.lo:Math.abs((e>0?p.hi:p.lo)??0);if(Math.abs(l-(e>0?p.hi:p.lo))<.05*u)continue;let d=new Set(r.map(e=>eD(e.c.tstart,i))),f=e=>e.map(e=>e.c.value).filter(e=>e!==null),m=new Set(r),y=f(t.filter(e=>!m.has(e)&&d.has(eD(e.c.tstart,i)))),b=f(r),x=y.length>=5&&b.length>=5,S=x?L3(b)-L3(y):NaN,C=x?H3(b,y).p:1;(_.get(e)??_.set(e,[]).get(e)).push({run:r,t0:s,t1:c,peak:l,diff:S,p:C,days:d.size})}for(let[o,m]of _){let h=m.reduce((e,t)=>t.t1-t.t0>e.t1-e.t0?t:e),g=t=>t.p<.01&&(e.value.better===`min`?t.diff>0:t.diff<0),_=e.units[a]?` ${e.units[a]}`:``,[v,y,b,x]=$4(p.lo??NaN,p.hi??NaN,h.peak,Math.abs(h.diff)),S=p.lo!==null&&p.hi!==null?`${v} to ${y}${_}`:p.lo===null?`${y}${_} or less`:`${v}${_} or more`,C=h.days===1?`that day`:`those days`,w=!(h.p<.01)||!Number.isFinite(h.diff)?``:l?`; they were ${x} s ${h.diff>0?`slower`:`faster`} than the other batches of ${C}`:`; their ${u} was ${x} ${g(h)?`worse`:`better`} than in the other batches of ${C}`,T=m.length>1?` It happened ${a3(m.length)} in all, ${r3(m.reduce((e,t)=>e+t.t1-t.t0,0))}.`:``,E=n.has(`${r}\u0000${a}`),D=`F05-R${d.length+1}`,O=s?`${c(r)}: `:``,k=o>0?`above`:`below`;d.push({id:D,section:`05`,refs:[`05`],evidence:h.p<.01?`statistical`:`measured`,p:h.p<.01?h.p:null,numbers:d6({batches:h.run.length,peak:h.peak,diff:h.diff,episodes:m.length}),text:`${O}${a} ${k} its expected range (${S}) in ${o3(h.run.length,`batch`,`batches`)} in a row from ${g3(h.t0,h.t1,i,` to `)}, ${o>0?`up`:`down`} to ${b}${_}${w}.${T}${E?` ${a} drifts on this stream (see 05.1): it crossed its range as it did.`:``}`}),f.push({text:`${O}Find why ${a} went ${k} its expected range from ${g3(h.t0,h.t1,i,` to `)} (${o>0?`up`:`down`} to ${b}${_})${m.length>1?`, ${a3(m.length)} in all`:``}.`,owner:`maintenance`,urgent:!E&&m.some(e=>e.t1-e.t0>=3600||g(e)),rank:1+h.run.length/t.length,refs:[D]})}}}return d.length?{findings:d,actions:f,charts:[],notes:[],next:[]}:null}function K5(e){let t=[];for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++)t.push((e[r]-e[n])/(r-n));return L3(t)}function q5(e,t){let n=t=>e.value.better===`min`?t>0:t<0,r=e.streams.length>1,i=t=>e.streams.find(e=>e.id===t)?.name??t,a=e.value.key===`duration`?` s`:``,o=e.value.label,s=[...A3(t,e=>e.c.streamId)].map(([e,t])=>{let r=[...A3(t,e=>e.c.recordingId).values()].map(e=>e.slice().sort((e,t)=>e.c.tstart-t.c.tstart).slice(1,-1)).filter(e=>e.length>=4).sort((e,t)=>e[0].c.tstart-t[0].c.tstart).map(e=>e.map(e=>e.c.value).slice(0,60)),i=0,a=r.map(e=>{let t={i,v:e[0]};return i+=e.length+2,t}),o=a.length>=3?L3(a.flatMap((e,t)=>a.slice(t+1).map(t=>(t.v-e.v)/(t.i-e.i)))):NaN,s=r.map(K5),c=L3(r.map(e=>e.length+2)),l=L3(r.map(e=>{let t=K5(e);return 1.4826*R3(e.map((e,n)=>e-t*n))})),u=s.filter(n).length,d=s.filter(e=>e!==0).length,f=d?1-B3((u-.5-d/2)/Math.sqrt(d/4)):1;return{sid:e,runs:r.length,b:L3(s),len:c,scatter:l,k:u,n:d,p:f,startSlope:o}}).filter(e=>e.runs>=5),c=[],l=[];for(let e of s){if(!(e.p<.01)||!n(e.b)||!(Math.abs(e.b)*e.len>=.5*e.scatter)||!(Math.abs(e.startSlope)<.5*Math.abs(e.b)))continue;let t=s.filter(t=>t!==e),u=`F05-W${c.length+1}`,d=r?`${i(e.sid)}: `:``,f=t.length?`, against ${Z4(Math.abs(L3(t.map(e=>e.b))))}${a} on the other ${o3(t.length,`stream`)}`:``;c.push({id:u,section:`05`,refs:[`05`],evidence:`statistical`,p:e.p,numbers:d6({perBatch:e.b,run:e.len,runs:e.runs,p:e.p}),text:`${d}${o} gets ${Z4(Math.abs(e.b))}${a} worse a batch along a run (${Z4(Math.abs(e.b)*e.len)}${a} over a usual run of ${e.len}) in ${e.k} of ${o3(e.n,`run`)}${f}: wear within a run (tyres, a tool, a filter) that each new run starts again.`}),l.push({text:`${d}Find what wears along a run: ${o} gets ${Z4(Math.abs(e.b))}${a} worse a batch, ${Z4(Math.abs(e.b)*e.len)}${a} by the end of a usual run.`,owner:`production`,urgent:!1,rank:.6,refs:[u]})}return c.length?{findings:c,actions:l,charts:[],notes:[],next:[]}:null}function J5(e,t,n,r=[]){let i=o8(e.context??z6()).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=r8(e,i,a);return t===null?void 0:o.get(t)},c=t.map(e=>r8(e.c.tstart,i,a));t.forEach((e,t)=>{let n=c[t],r=n===null?void 0:o.get(n);r&&(r.n++,e.level!==`off`&&r.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 l=[...o].map(([e,t])=>({name:e,...t,share:t.n?t.good/t.n:NaN})),u=l.filter(e=>e.n>=5),d=u.reduce((e,t)=>!e||t.share<e.share?t:e,null),f=d&&u.filter(e=>e!==d),p=f?.reduce((e,t)=>e+t.n,0)??0,m=f?.reduce((e,t)=>e+t.good,0)??0,h=p?m/p:NaN,g=!!d&&r.some(e=>e.text.includes(`on the ${d.name} shift`)),_=!!d&&h-d.share>=.05&&(g||X3(d.good,d.n,m,p).p<.01),v=[];if(_){let e=`The ${d.name} shift has the lowest share of batches at golden level (${J4(d.share)} against ${J4(h)}).`,t=[`11`,...g?[`02`]:[]];v.push({id:`F11-1`,section:`11`,refs:t,evidence:`measured`,p:null,text:e,numbers:{share:d.share,others:h,batches:d.n}})}let y=new Map(i.map(e=>{let[t,n]=e.start.split(`:`).map(Number),[r,i]=e.end.split(`:`).map(Number);return[e.name,{off:t*3600+n*60,len:((r*60+i-(t*60+n)+1440)%1440||1440)/60}]})),b=n8(a),x=new Map(i.map(e=>[e.name,new Set]));t.forEach((e,t)=>{let n=c[t];n!==null&&x.get(n).add(b(e.c.tstart-y.get(n).off))});let S=new Map(i.map(e=>[e.name,y.get(e.name).len*x.get(e.name).size])),C=e=>e.stopped/Math.max(1,S.get(e.name)??0),w=u.reduce((e,t)=>!e||C(t)>C(e)?t:e,null),T=w?u.filter(e=>e!==w):[],E=T.length?T.reduce((e,t)=>e+t.stopped,0)/Math.max(1,T.reduce((e,t)=>e+(S.get(t.name)??0),0)):NaN;if(w&&T.length&&C(w)>=1.25*E&&w.stopped-E*(S.get(w.name)??0)>=3600){let e=`The ${w.name} shift stops most: ${r3(w.stopped)} stopped, ${J4(C(w)/E-1)} more per hour worked than the other shifts.`;v.push({id:`F11-${v.length+1}`,section:`11`,refs:[`11`],evidence:`measured`,p:null,text:e,numbers:{stopped:w.stopped,rate:C(w),others:E}})}let D=l.filter(e=>e.n);return{section:q4(`11`,v.length?v[0].text:u.length>=2?`The shifts perform alike.`:D.length===1?`Only the ${D[0].name} shift made batches in this period.`:`Too few batches in the shifts to compare them.`,v,[{kind:`table`,title:`11.1 · Shifts`,columns:[`Shift`,`Batches`,`At golden level or better`,`Stopped`,`Alerts`],rows:l.map(e=>({cells:[e.name,e.n.toLocaleString(`en-GB`),e.n?J4(e.share):`–`,r3(e.stopped),String(e.alerts)],..._&&e===d?{status:`watch`,finding:`F11-1`}:{}}))}]),actions:[],next:[],numbers:_?{share:d.share,others:h}:{}}}function Y5(e,t,n=[],r,i=w5(e)){let a=e.previous,o=a?{...e,period:a.period,recordings:a.recordings,cycles:a.cycles,previous:null}:null,s=o?u6(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=X3(c(t),t.length,c(s),s.length),u=e=>e.map(e=>e.c.value),d=L3(u(t)),f=L3(u(s)),p=H3(u(t),u(s)),[m,h]=Z3([l.p,p.p],a6),g=e.value.label,[_,v]=$4(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:d6({share:l.p1,before:l.p2,p:l.p}),text:`${J4(l.p1)} of batches at golden level or better, ${e?`up`:`down`} from ${J4(l.p2)} the period before.`}),w.push({better:e,text:`${J4(l.p1)} of batches at golden level, ${e?`up`:`down`} from ${J4(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:d6({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=`${p3(a.period.from,E)} – ${p3(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=R8(e,t))=>n.filter(e=>e.status===`Replace`||e.status===`Drifting`).length,M=A(i),N=A(w5(o));return{section:q4(`01`,k,x,[{kind:`tiles`,tiles:[{label:`At golden level or better`,value:J4(l.p1),note:`${J4(l.p2)} before`},{label:`${g} median`,value:_,note:`${v} before`},{label:`Stopped`,value:r3(M),note:`${r3(N)} before`},{label:`Sensors to replace or drifting`,value:String(j(e,t,r)),note:`${j(o,s)} before`}]}]),actions:T,next:[],numbers:d6({share:l.p1,before:l.p2,median:d,medianBefore:f,stoppedS:M,stoppedBeforeS:N})}}function X5(e,t,n,r){let{tz:i}=e,a=eD(e.period.from,i),o=eD(e.period.to-1,i),s=[];for(let e=a;e<=o&&s.length<=400;e=nD(e,1))s.push(e);if(s.length<2||s.length>400||!t.length)return null;let c=e=>s.indexOf(eD(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=>[tD(e,`00:00`,i),tD(nD(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=`${_3[(n.getUTCDay()+6)%7]} ${n.getUTCDate()} ${n.toLocaleString(`en-GB`,{month:`short`,timeZone:`UTC`})}`,i=[l[t]?`${o3(l[t],`batch`,`batches`)}, ${J4(u[t]/l[t])} off the golden`:`no batches`,...d[t]>=60?[`stopped ${r3(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 Z5=e=>e.findings.length||e.id===`01`?e:{...e,charts:[],notes:[]},Q5=(e,t)=>{let n=t.filter(e=>!!e);return{...e,section:h5(Z5(e.section),n),actions:[...e.actions,...n.flatMap(e=>e.actions)],next:[...e.next,...n.flatMap(e=>e.next)]}};function $5(e){let t=L8(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 e7(e){let t=u3(e.tz)?e:{...e,tz:`UTC`},n=$5(t.context?{...t,context:o8(t.context)}:t),r=u6(n),i=f5(n,r),a=v6(n,r),o=B8(n,r),{stops:s,offGaps:c}=T5(n),l=E5(n,s,c),u=Q5(o.out,[l,z5(n,o.drifts,o.wear),G5(n,r,new Set(o.sensors.filter(e=>e.status===`Drifting`).map(e=>`${e.sid}\u0000${e.key}`))),q5(n,r)]),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=Z5(i.section),m=Z5(a.section),h=Z5(f.section),g=S6(n,r),_=X8(n,r,o.sensors),v=g===null?K8(n,r):null,y=new Map;for(let e of o.sensors)e.status===`Drifting`&&y.set(e.sid,[...y.get(e.sid)??[],e.key]);let b=W5(n,r,o.sensors.flatMap(e=>e.stuck.map(t=>({...t,sid:e.sid,ch:e.key}))),y),x=b?{findings:b.findings,charts:b.charts,notes:[],actions:b.actions,next:[]}:null,S=_?`${o3(_.findings.reduce((e,t)=>e+t.numbers.batches,0),`batch`,`batches`)} to check before they ship: made while a sensor was failing.`:v?`${o3(v.findings.length,`feature`)} left ${v.findings.length===1?`its`:`their`} control limits; no specification limits say which batches are bad.`:``,C=!_&&!v&&!x?g:g&&!(`needs`in g)?Q5(g,[x,_]):[g,Q5({section:{...q4(`04`,S,[],[]),fold:!0,subtitle:K4(_?`Containment: batches made while a sensor was failing`:`Control chart (Shewhart individuals, 3σ)`)},actions:[],next:[],numbers:{}},[x,_,v])],w=b?[C].flat().map(e=>!e||`needs`in e?e:{...e,section:{...e.section,verdict:b.findings[0].text,findings:[...b.findings,...e.section.findings.filter(e=>!b.findings.includes(e))]},actions:e.actions.map(e=>b.actions.includes(e)?e:{...e,urgent:e.urgent&&!e.text.startsWith(`Bring `)})}):C,T=Y8(n,r),E=[Y5(n,r,T&&!(`needs`in T)?T.section.findings:[],o.sensors,s),w,I5(n,r,s),m6(n,r),T,n5(n,r),L5(n,r),n.context?.hideShifts?null:J5(n,r,s,i.section.findings)].flat(),D=E.filter(e=>!!e&&!(`needs`in e)),O=E.filter(e=>!!e&&`needs`in e),k=D.map(e=>Z5(e.section)),A=new Set(k.map(e=>e.id)),j=[...i.actions,...a.actions,...f.actions,...D.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})),M=j.slice(0,3),N=q4(`12`,j.length?`Start with ${s3(M.map(e=>e.id))}: ${M.some(e=>e.urgent)?`urgent items`:`the largest effect`} first.`:`Nothing to act on in this period.`,[],j.length?[{kind:`table`,title:`12.1 · Actions, most urgent first`,columns:[`#`,`Action`,`Owner`],rows:j.map(B4),...j.length>5?{shown:5,more:o3(j.length-5,`more action`)}:{}}]:[]),P=[...new Set([...i.next,...a.next,...f.next,...D.flatMap(e=>e.next)])],F=q4(`13`,P[0]??`Nothing left unexplained that more data would answer.`,[],[],P.slice(1)),I=r.filter(e=>e.level!==`off`).length,L=j.filter(e=>e.urgent).length,R=e=>{let t=new Set(e.findings.map(e=>e.id)),n=j.findIndex(e=>e.refs.some(e=>t.has(e)));return n<0?1/0:n},z=[p,h,m,...k].filter(e=>e.findings.length).map(e=>({s:e,i:R(e)})).sort((e,t)=>e.i-t.i||0).map(e=>e.s),B=n.value.key===`duration`?r.reduce((e,t)=>e+Math.max(0,t.gap),0):0,V=M5(n.context),ee=D.find(e=>e.section.id===`06`)?.numbers,te=D.find(e=>e.section.id===`09`),H=te?.numbers.energy?te.section.findings.find(e=>e.id===`F09-2`)?.numbers.extra:void 0,ne=p5(n,{time:ee&&`slowS`in ee?[{label:F5.stops,s:ee.stopsS,owner:z4.maintenance,ref:`06`},{label:F5.slow,s:ee.slowS,owner:z4.production,ref:`06`},N5(n)?{label:F5.off,s:ee.offS,owner:z4.quality,ref:`06`}:{label:F5.bad,s:ee.offS,owner:z4.quality,ref:`06`,bad:!0}]:[{label:`Stops`,s:s.reduce((e,t)=>e+t.t1-t.t0,0),owner:z4.maintenance,ref:`05`},{label:`Batches slower than the golden`,s:B,owner:z4.production,ref:`02`}],energyKwh:H??null,review:_&&A.has(`04`)?{batches:_.findings.reduce((e,t)=>e+t.numbers.batches,0),s:_.findings.reduce((e,t)=>e+t.numbers.seconds,0)}:null,scrap:V.limits.length||r.some(e=>e.c.flag===`bad`||e.c.flag===`good`)?{batches:r.filter(e=>e.c.flag===`bad`||V.outside(e.c.kpis)).length,assumed:!1}:n.value.key===`duration`?null:{batches:r.length-I,assumed:!0}}),re=X5(n,r,s,o.sensors.flatMap(e=>e.stuck)),ie=o.sensors.filter(e=>e.status===`Drifting`),U=new Set(ie.map(e=>e.sid)),ae=q4(`00`,r.length?`${V.limits.length?`${J4(1-r.filter(e=>e.c.flag===`bad`||V.outside(e.c.kpis)).length/r.length)} of batches within their limits, `:``}${J4(I/r.length)} ${V.limits.length?`at golden level or better`:`of batches at golden level or better`}${L?`, and ${o3(L,`urgent item`)}`:``}.`:`No batches could be compared with a golden in this period.`,z.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})),[...ne?[ne]:[],...M.length?[{kind:`table`,title:`00.2 · What to do first`,columns:[`#`,`Action`,`Owner`],rows:M.map(B4),ref:`12`}]:[],...re?[re]:[],{kind:`tiles`,tiles:[{label:`Batches`,value:r.length.toLocaleString(`en-GB`),note:o3(n.recordings.length,`file`)},{label:`At golden level or better`,value:r.length?J4(I/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)}]:[],...ie.length?[{value:String(ie.length),label:`${ie.length===1?`Channel`:`Channels`} drifting${U.size>1?` on ${U.size} streams`:n.streams.length>1?`${ie.length>1?`, all`:``} on ${n.streams.find(e=>e.id===ie[0].sid)?.name??`one stream`}`:``}`}]:[]]}]),oe=n.recordings.filter(e=>!e.failed&&!e.unread),se=n.recordings.filter(e=>e.failed),ce=n.recordings.filter(e=>e.unread).length,le=e=>n.streams.find(t=>t.id===e)?.name??`A stream`,ue=q4(`14`,`How the findings were made and how sure each one is.`,[],[],[`Cycles found with “${n.rule.name}” v${n.rule.version} in ${o3(n.recordings.length,`recording`)} of ${o3(n.streams.length,`stream`)}, ${J4(n.recordings.length?oe.length/n.recordings.length:0)} read${ce?`; ${ce} not read, counted through ${ce===1?`its`:`their`} stored cycles and measures`:``}${se.length?` (could not be read: ${se.map(e=>`${e.name}, ${e.failed}`).join(`; `)})`:``}.`,...n.goldens.map(e=>`${le(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 ${o3(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 ${g5/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 ${x8/3600} h between them, a stop or a file boundary, are one; a flat run alone is no fault), noise (median absolute deviation of sample-to-sample changes), spikes (Hampel filter, 6 robust σ), rate drops; on a stream with batches a sensor is stuck when, in batches made one after another over 10 minutes or more, it held one value while it moves in its usual batch (what it does between batches or in one phase of a batch never counts), and sensors of one stream stuck over the same time are one fault; 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}. ${y6}`]:[],...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*V8*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.`]:[],..._&&A.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.`]:[],...A.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${N5(n)?`, and at golden level or better`:``}. The daily trend is a straight line over 7 days or more, kept at p < 0.01.`]:[],...A.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 ${f6/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.`]:[],...A.has(`08`)?[`Changes (08): consecutive flat runs of a setting at values more than 3 noise σ apart; the effect by Mann–Whitney on the same day’s batches either side (else the 20 batches each side), each against its group’s median when a few-valued KPI groups them (a driver, an operator), Benjamini–Hochberg at q = 0.01 across the changes; its size is the difference of the medians with a 95% interval (a median’s standard error taken as 1.2533 × MAD / √n), which a factor nobody recorded can still be part of.`]:[],...A.has(`09`)?[`Energy and consumption (09): per batch, a rate (W, kW, MW; L/h, m³/h, kg/h) integrated over the batch, or a meter (Wh, kWh, MWh; L, m³, kg, t) 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.`]:[],...A.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.`]:[],...A.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.`]:[],...A.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.`]),de=n.goldens,fe=I8(n),pe=Object.keys(n.units).filter(e=>!fe.has(e)).length;return k3({v:1,cover:{title:`Report ${p3(n.period.from,n.tz)} – ${p3(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:de.length===1?`${de[0].label}${de[0].proposed?` (proposed: no golden set)`:de[0].auto?` (set automatically: none was set)`:``}`:de.length?`${de.length} goldens, one per stream`:`None`,data:`${o3(n.streams.length,`stream`)} · ${o3(n.recordings.length,`file`)}${pe||!ce?` · ${o3(pe,`channel`)}`:``}`,madeBy:n.madeBy,madeAt:n.madeAt,tz:n.tz,context:n.contextVersion?`Process context v${n.contextVersion}`:`None set`},actions:j,sections:[ae,p,m,...k,h,N,F,ue].sort((e,t)=>e.id.localeCompare(t.id)).map(e=>({...e,findings:e.findings.map(t=>({...t,sig:D3(e.id,t.text)}))})),missing:[...new Map([...l8(n.context??null,n.alertRules?.length??0),...O].map(e=>[`${e.section} ${e.needs}`,e])).values()].map(e=>({section:e.section,title:U4[e.section],needs:e.needs})).sort((e,t)=>e.section.localeCompare(t.section))},n.context?.known??[])}function t7(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 n7(e,t){return t===`full`?e.sections:e.sections.filter(e=>e.roles.includes(t))}var r7={verdict:30,sentence:35,action:30},i7={verdict:250,sentence:300,action:250},a7=/\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,o7=/\b(\d{1,2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?/gi,s7=e=>e.normalize(`NFKC`).replace(/−/g,`-`),c7=e=>a7.test(s7(e))||/(?![0-9])\p{Nd}/u.test(s7(e)),l7=e=>{let t=s7(e),n=[];return t=t.replace(o7,(e,t,r)=>(n.push(`${+t} ${r.toLowerCase()}`),` `)),[...n,...(t.match(/[-+]?(?:\d[\d,]*)?\.?\d+%?/gu)??[]).map(e=>e.replace(/,/g,``))]},u7=e=>!!e&&typeof e==`object`&&!Array.isArray(e),d7=e=>Array.isArray(e)?e.filter(u7):[];function f7(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(!u7(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||c7(o))return null;let c=new Set([...r,...a?s.map(e=>n.get(e)):[]].flatMap(l7));return l7(o).every(e=>c.has(e))?{text:o,cites:s}:null},i=e=>({words:r7[e],chars:i7[e]}),a=u7(t)?t:{},o=new Map(d7(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(d7(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}}function p7(e,t){let n=new Map(e.findings.map(e=>[e.id,e])),r=new Map(e.results.map(e=>[e.id,e.text])),i=new Map(e.actions.map(e=>[e.id,e])),a=e=>n.get(e)?.text??r.get(e),o=(e,t)=>!!e&&e.length<=i7[t]&&e.split(/\s+/).length<=r7[t]&&!c7(e),s=(e,t)=>{let n=new Set(t.flatMap(l7));return l7(e).every(e=>n.has(e))},c=u7(t)?t:{},l=[],u=new Set;for(let t of d7(c.triage)){let i=typeof t.finding==`string`?n.get(t.finding):void 0,a=t.verdict===`merge`&&typeof t.into==`string`&&t.into!==t.finding?n.get(t.into):void 0,c=typeof t.reason==`string`?t.reason.trim():``;!i||i.fixed||u.has(i.id)||!(t.verdict===`set_aside`||a)||!o(c,`sentence`)||s(c,[...e.findings.map(e=>e.text),...r.values()])&&(u.add(i.id),l.push({finding:i.id,verdict:a?`merge`:`set_aside`,into:a?.id??null,reason:c}))}let d=e=>typeof e==`string`&&!u.has(e)&&a(e)!==void 0,f=[],p=new Set;for(let e of d7(c.actions)){if(f.length>=5)break;let t=typeof e.action==`string`?i.get(e.action):void 0,r=!t&&typeof e.finding==`string`&&d(e.finding)&&n.has(e.finding)?e.finding:null,c=t?.id??r;if(!c||p.has(c))continue;let l=Array.isArray(e.cites)?[...new Set(e.cites.filter(d))]:[],u=typeof e.text==`string`?e.text.trim():``,m=o(u,`action`)&&s(u,[t?.text??``,...r?[a(r)]:[],...l.map(e=>a(e))]);!t&&!m||(p.add(c),f.push({action:t?.id??null,finding:r,text:m?u:``,cites:m?l:[]}))}return{triage:l,actions:f,summary:d7(c.summary).flatMap(e=>{let t=typeof e.text==`string`?e.text.trim():``,n=Array.isArray(e.cites)?[...new Set(e.cites)]:[];return o(t,`sentence`)&&n.length&&n.every(d)&&s(t,n.map(e=>a(e)))?[{text:t,cites:n}]:[]}).slice(0,3)}}var m7=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 h7(e,t){let n=t?o8(t):null;return{process:n?.process??``,channels:Object.entries(n?.channels??{}).flatMap(([e,t])=>{let n=B6(t);return n&&n!==`ignore`?[{name:e,role:I6[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:C3(e),refs:e.refs}))})),actions:e.actions.map(e=>({id:e.id,text:e.text,owner:e.owner,refs:e.refs}))}}function g7(e,t,n){let r=f7({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),m7(n)]}:e);return{...e,cover:{...e.cover,ai:n},sections:u,actions:a}}function _7(e,t){let n=t.context?o8(t.context):null,r=u6(t),i=M5(n),a=v7(t),o=[];for(let[e,n]of A3(r,e=>`${e.c.streamId}\u0000${eD(e.c.tstart,t.tz)}`)){let[t,r]=e.split(`\0`),s=n.map(e=>e.c.value).filter(N3);o.push([a.get(t)??t,r,n.length,n.filter(e=>e.c.flag===`bad`||i.outside(e.c.kpis)).length,Math.round(100*n.filter(e=>e.level===`off`).length/n.length),s.length?+L3(s).toPrecision(4):null])}return o.sort((e,t)=>e[0].localeCompare(t[0])||e[1].localeCompare(t[1])),{process:n?.process??``,value:{label:t.value.label,better:t.value.key.includes(`~`)?`closer to the target`:t.value.better===`min`?`lower`:`higher`},channels:Object.entries(n?.channels??{}).flatMap(([e,t])=>{let n=B6(t);return n===`ignore`?[]:[{name:e,role:n?I6[n]:``,unit:t.unit}]}).slice(0,200),streams:t.streams.map(e=>e.name),kpis:y7(t),days:o.slice(0,400),findings:e.sections.filter(e=>e.id!==`14`).flatMap(e=>e.findings.map(t=>({id:t.id,section:e.id,text:t.text,evidence:C3(t),fixed:e.id===`00`||t.id.startsWith(`F04-C`)}))),losses:e.sections.flatMap(e=>e.charts.flatMap(e=>e.kind===`losses`?e.rows.map(e=>({label:e.label,amount:e.amount,detail:e.detail})):[])),known:(n?.known??[]).slice(0,50).map(e=>({text:e.text,reason:T3[e.reason],note:e.note})),actions:e.actions.map(e=>({id:e.id,text:e.text,owner:z4[e.owner],urgent:e.urgent,refs:e.refs}))}}var v7=e=>new Map(e.streams.map(e=>[e.id,e.name]));function y7(e){let t=new Set;for(let n of e.cycles.slice(0,2e3))for(let e of Object.keys(n.kpis))t.add(e);return[`value`,`duration`,`bad`,...[...t].sort()].slice(0,300)}function b7(e,t){let n=Array.isArray(e?.checks)?e.checks:[],r=new Set(t.streams),i=new Set(t.kpis),a=e=>typeof e==`string`?e:``,o=e=>/^\d{4}-\d{2}-\d{2}( \d{2}:\d{2})?$/.test(a(e))?a(e):``,s=[];for(let e of n){let t=e??{},n=a(t.stream),c=a(t.kpi);if(t.tool===`compare`&&i.has(c)&&[`stream`,`shift`,`weekday`,`hour`].includes(a(t.by))&&(!n||r.has(n)))s.push({tool:`compare`,kpi:c,by:t.by,stream:n||null});else if(t.tool===`before_after`&&i.has(c)&&r.has(n)&&o(t.at))s.push({tool:`before_after`,kpi:c,stream:n,at:o(t.at)});else if(t.tool===`pair`&&i.has(a(t.a))&&i.has(a(t.b))&&r.has(n))s.push({tool:`pair`,a:a(t.a),b:a(t.b),stream:n});else if(t.tool===`daily`&&i.has(c)&&r.has(n))s.push({tool:`daily`,kpi:c,stream:n});else if(t.tool===`episode`&&r.has(n)&&o(t.from)&&o(t.to)){let e=(Array.isArray(t.kpis)?t.kpis:[]).map(a).filter(e=>i.has(e)).slice(0,6);e.length&&s.push({tool:`episode`,stream:n,from:o(t.from),to:o(t.to),kpis:e})}if(s.length>=12)break}return s}function x7(e,t){let n=u6(e),r=e.context?o8(e.context):null,i=M5(r),a=new Map(e.streams.map(e=>[e.name,e.id])),o=(e,t)=>t===`value`?e.c.value:t===`duration`?e.c.tend===null?null:e.c.tend-e.c.tstart:t===`bad`?Number(e.c.flag===`bad`||i.outside(e.c.kpis)):e.c.kpis[t]??null,s=(e,t)=>e.map(e=>o(e,t)).filter(N3),c=t=>tD(t.slice(0,10),t.length>10?t.slice(11):`00:00`,e.tz),l=e=>Math.abs(e)>=1e5?Z4(e):String(+e.toPrecision(5)),u=e=>e.length?l(L3(e)):`–`,d=(e,t)=>e.length?t===`bad`?`${+(100*e.reduce((e,t)=>e+t,0)/e.length).toPrecision(3)}% bad`:u(e):`–`,f=e=>e<.001?`p < 0.001`:`p ${e.toFixed(3)}`;return t.map((t,i)=>{let u=`R${i+1}`,p=e=>n.filter(t=>!e||t.c.streamId===a.get(e)),m;if(t.tool===`compare`){let n=n=>t.by===`stream`?e.streams.find(e=>e.id===n.c.streamId)?.name??`?`:t.by===`shift`?r8(n.c.tstart,r?.shifts??[],e.tz)??`no shift`:t.by===`weekday`?_3[v3(n.c.tstart,e.tz).day]:`${v3(n.c.tstart,e.tz).hour}h`,i=p(t.stream),a=[...A3(i,n)].filter(([,e])=>s(e,t.kpi).length>=5).slice(0,24).map(([e,r])=>({g:e,n:s(r,t.kpi).length,m:d(s(r,t.kpi),t.kpi),...H3(s(r,t.kpi),s(i.filter(t=>n(t)!==e),t.kpi))})),o=a.reduce((e,t)=>!e||t.p<e.p?t:e,null);m=`${t.kpi} by ${t.by}${t.stream?` on ${t.stream}`:``}: ${a.map(e=>`${e.g} median ${e.m} (${o3(e.n,`batch`,`batches`)})`).join(`; `)}.`+(o&&a.length>1?` Most different: ${o.g} against the rest, ${f(Math.min(1,o.p*a.length))}.`:``)}else if(t.tool===`before_after`){let e=c(t.at),n=p(t.stream),r=s(n.filter(t=>t.c.tstart<e),t.kpi),i=s(n.filter(t=>t.c.tstart>=e),t.kpi);m=r.length>=5&&i.length>=5?`${t.kpi} on ${t.stream} before ${t.at}: median ${d(r,t.kpi)} (${o3(r.length,`batch`,`batches`)}); after: ${d(i,t.kpi)} (${o3(i.length,`batch`,`batches`)}), ${f(H3(r,i).p)}.`:`${t.kpi} on ${t.stream} around ${t.at}: too few batches on one side to compare.`}else if(t.tool===`pair`){let n=[...A3(p(t.stream).filter(e=>N3(o(e,t.a))&&N3(o(e,t.b))),t=>eD(t.c.tstart,e.tz))].map(([e,n])=>({d:e,v:L3(n.map(e=>o(e,t.a)-o(e,t.b)))})).sort((e,t)=>e.d.localeCompare(t.d)),r=n.length>=5?$3(n.map((e,t)=>t),n.map(e=>e.v)):null;m=n.length?`${t.a} − ${t.b} on ${t.stream}, daily median: ${l(n[0].v)} on ${n[0].d}, ${l(n[n.length-1].v)} on ${n[n.length-1].d}`+(r?`; trend ${l(r.b*7)} a week, ${f(r.p)}.`:`.`):`${t.a} and ${t.b} on ${t.stream}: no batch has both.`}else if(t.tool===`daily`){let n=[...A3(p(t.stream).filter(e=>N3(o(e,t.kpi))),t=>eD(t.c.tstart,e.tz))].sort(([e],[t])=>e.localeCompare(t)),r=Math.max(1,Math.ceil(n.length/60)),i=[];for(let e=0;e<n.length;e+=r){let a=n.slice(e,e+r);i.push(`${a[0][0].slice(5)} ${d(a.flatMap(([,e])=>s(e,t.kpi)),t.kpi)}`)}m=`${t.kpi} on ${t.stream}, median by ${r===1?`day`:`${r} days`}: ${i.join(`, `)||`no batch`}.`}else{let n=c(t.from),r=t.to.length>10?c(t.to):c(t.to)+86400,i=p(t.stream),a=i.filter(e=>e.c.tstart>=n&&e.c.tstart<r),o=new Set(a.map(t=>eD(t.c.tstart,e.tz))),l=i.filter(t=>!(t.c.tstart>=n&&t.c.tstart<r)&&o.has(eD(t.c.tstart,e.tz)));m=`${t.stream} from ${t.from} to ${t.to}: ${o3(a.length,`batch`,`batches`)} against ${o3(l.length,`batch`,`batches`)} the rest of those days. `+t.kpis.map(e=>{let t=s(a,e),n=s(l,e);return`${e}: ${d(t,e)} against ${d(n,e)}${t.length>=5&&n.length>=5?`, ${f(H3(t,n).p)}`:``}`}).join(`; `)+`.`}return{id:u,check:t,text:m}})}var S7=e=>e===`05`?`maintenance`:e===`04`?`quality`:`production`;function C7(e,t,n,r){let i=new Map(e.actions.map(e=>[e.id,e])),a=new Map(e.sections.flatMap(e=>e.findings.map(t=>[t.id,e.id]))),o=[],s=new Set;for(let e of t.actions.slice(0,5)){let t=e.action?i.get(e.action):void 0;t&&!s.has(t.id)?(s.add(t.id),o.push({...t,text:e.text||t.text,refs:[...new Set([...t.refs,...e.cites.filter(e=>a.has(e))])]})):!t&&e.finding&&a.has(e.finding)&&e.text&&o.push({text:e.text,owner:S7(a.get(e.finding)),urgent:!1,refs:[e.finding]})}let c=[...o,...e.actions.filter(e=>!s.has(e.id))].map((e,t)=>({...e,id:`A${t+1}`})),l=new Map(t.triage.map(e=>[e.finding,e])),u=[],d=e.sections.map(e=>{let n=e.findings.filter(t=>{let n=l.get(t.id);return n&&u.push({id:t.id,section:e.id,text:t.text,reason:n.reason,into:n.into}),!n}),r=e.charts.map(t=>t.kind===`table`&&t.columns[0]===`#`?{...t,rows:(e.id===`00`?c.slice(0,t.rows.length):c).map(B4),...e.id===`12`&&c.length>5?{shown:5,more:o3(c.length-5,`more action`)}:{}}:t),i=c.slice(0,3).map(e=>e.id);return{...e,findings:n,charts:r,...e.id===`12`&&c.length?{verdict:`Start with ${s3(i)}: ranked by Kymoscope’s AI review.`}:{},...e.id===`00`&&t.summary.length?{ai:t.summary}:{}}}),f=`Reviewed by Kymoscope’s AI (${r}) before it was worded: ${n.length?`${o3(n.length,`check`)} computed from the batches, `:``}${u.length?`${o3(u.length,`finding`)} left out with ${u.length===1?`its`:`their`} reason`:`every finding kept`}, the actions ranked. The numbers are Kymoscope’s.`,p=d.map(e=>e.id===`14`?{...e,notes:[...e.notes,f]}:e);return{...e,sections:p,actions:c,review:{model:r,checks:n,setAside:u}}}var w7=.5,T7=5400,E7=/^[kM]?Wh?$/,D7=86400/300,O7=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],k7=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`)}`},A7=(e,t)=>Math.round(e/t)*t;function j7(e){if(!e.length)return null;let t=L3(e.map(e=>e.p01??e.lo)),n=L3(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 M7(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 N7(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=$E(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 P7(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=>O7[e]).join(`, `)}`,from:`00:00`,to:`00:00`,days:i}}function F7(e){let t={shifts:[],stops:[]};if(e.size<3)return t;let n=Array.from({length:D7},(t,n)=>[...e.values()].filter(e=>e.has(n)).length/e.size),r=n.map(e=>e>=w7),i=[],a=r.indexOf(!0);if(a<0)return t;for(let e=0;e<D7;e++){let t=(a+e)%D7;if(r[t])continue;let n=i[i.length-1];n&&(n.a+n.n)%D7===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>T7);for(let e of i.filter(e=>e.n*300<600))for(let t=0;t<e.n;t++)r[(e.a+t)%D7]=!0;let c=i.filter(e=>e.n*300>=600).flatMap(e=>Array.from({length:e.n},(t,r)=>n[(e.a+r)%D7])),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)%D7*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=A7(t.a,900),n=A7(t.b,900);n>e&&m.push({name:`Break`,from:k7(e),to:k7(n)})}let i=n.map(e=>A7(r(e),1800)),a=f?i:[A7(e.a,1800),...i,A7(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:A7(e.a+r*t/n,1800),b:A7(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:k7(e.a),end:k7(e.b)})),stops:m}}function I7(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 L7(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 R7(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 z7(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=j7(r.filter(e=>e.moves!==!1));e&&(n[t]=e)}let r=N7(M7(e.recordings),e.tz),i=F7(r),a=P7(r);return{units:t,ranges:n,energy:Object.keys(t).filter(e=>E7.test(t[e].trim())).sort(),settings:R7(e.health,e.recordings.reduce((e,t)=>e+t.batches.length,0)),shifts:i.shifts,stops:[...i.stops,...a?[a]:[]],lines:I7(e.streams),machines:L7(Object.keys(t))}}function B7(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]=R6(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 V7(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 H7=Lt({AI_NOTE:()=>m7,AI_SENTENCES:()=>2,AI_WORDS:()=>r7,ALPHA:()=>a6,CHANNEL_ROLES:()=>F6,CHANNEL_ROLE_TEXT:()=>I6,CONSUMPTION_UNITS:()=>Z8,CONSUMPTION_UNIT_LIST:()=>$8,EVIDENCE_TEXT:()=>H4,GOLDEN_SHARE:()=>o6,HealthAcc:()=>y8,KNOWN_GROWTH:()=>2,KNOWN_MAX:()=>200,KNOWN_REASONS:()=>w3,KNOWN_REASON_TEXT:()=>T3,MIN_GROUP:()=>5,OFF_GOLDEN_PCT:()=>2,PRESETS:()=>w6,PRESET_IDS:()=>C6,PROCESS_MAX:()=>L6,REPORT_ROLES:()=>V4,REVIEW_CHECKS:()=>12,SECTION_ROLES:()=>G4,SECTION_TITLES:()=>U4,aiInput:()=>h7,applyAi:()=>g7,applyInferred:()=>B7,applyKnown:()=>k3,applyPreset:()=>P6,applyReview:()=>C7,assumedSections:()=>V7,buildReport:()=>e7,checkReview:()=>p7,classify:()=>u6,completeness:()=>d8,confirmAll:()=>c8,confirmed:()=>o8,consumptionUnit:()=>Q8,contextGaps:()=>l8,dateText:()=>p3,dateTimeText:()=>m3,emptyChannel:()=>R6,emptyContext:()=>z6,energyChannel:()=>V6,evidenceLabel:()=>C3,exact:()=>Q4,findingSignature:()=>D3,goldenRank:()=>s6,grew:()=>O3,inferContext:()=>z7,listedFindings:()=>t7,moneyGaps:()=>u8,namesOf:()=>j6,num:()=>Z4,pText:()=>S3,parseChecks:()=>b7,parseContext:()=>$6,pct1:()=>Y4,presetForIndustry:()=>E6,presetOf:()=>T6,reviewPack:()=>_7,roleOf:()=>B6,runChecks:()=>x7,shiftOf:()=>r8,spanText:()=>g3,stopSpans:()=>a8,suggestedCount:()=>s8,term:()=>A6,usualRange:()=>b8,viewSections:()=>n7});export{f$ as ANNOTATION_CONTROLS_ATTR,Bt as ANNOTATION_KINDS,m0 as AxisState,QV as BEACON_STATS,C4 as BrowserRecorder,F2 as CAMERA_QUALITIES,He as CHAIN_LIVE,Ne as CHAIN_RECORDING,F6 as CHANNEL_ROLES,I6 as CHANNEL_ROLE_TEXT,fr as CHART_ALARM_FIELDS,T1 as CHART_KINDS,hD as CYCLE_TIME,G2 as CameraSender,xe as ChainLane,cD as CycleRunner,lD as CycleSet,Xt as DASHBOARD_GRID_COLS,Qt as DASHBOARD_GRID_GAP_PX,Zt as DASHBOARD_GRID_ROWS,UV as DATASET_PALETTE,Vt as DEFAULT_ANNOTATION_WIDTH,pn as DEFAULT_AXIS_LINE,hn as DEFAULT_BEACON,mn as DEFAULT_GRID_LINE,wn as DEFAULT_TRACE_WIDTH,Cn as DEFAULT_XYZ_POINT_RADIUS,Sn as DEFAULT_XY_POINT_RADIUS,H4 as EVIDENCE_TEXT,I4 as EXPORT_TYPES,dO as FLASH_ACTIVE_S,uO as FLASH_CYCLE_S,PT as FUNCTION_REFERENCE,y8 as HealthAcc,FH as IMPORTABLE_EXT,P as KIND_CHAIN,l as KIND_VIDEO,KE as KPI_STATS,ze as KRC_HEADER_BYTES,rD as KpiAcc,OO as KymoscopeError,mt as LEAF_KEYS,n as LIVE_TIME_COLUMN,I2 as LOW_PRESET,P2 as LivePublisher,u0 as MAX_BAND_CELLS,l0 as MAX_GRID,tr as MAX_PANEL_CAMERAS,nn as MIN_PANEL_H,tn as MIN_PANEL_W,I as OPEN_STREAM_PASSWORD,w6 as PRESETS,C6 as PRESET_IDS,L6 as PROCESS_MAX,V4 as REPORT_ROLES,c2 as RecordedVideoSource,A2 as RegistryError,U4 as SECTION_TITLES,qt as SEVERITY_HEX,l2 as SPLIT_STEPS,U0 as UNLIMITED,qZ as VIDEO_LIMIT_NOTICE,U1 as VIDEO_MAX_FRAGMENT,uE as WINDOW_FN_NAMES,B as WORKBOOK_EXPORT_AAD,h7 as aiInput,p as alertEventAad,v as alertRuleAad,h0 as alignSegment,H7 as analysis,g7 as applyAi,B7 as applyInferred,P6 as applyPreset,dn as arrangeAutoLayout,d0 as axisColumn,S0 as bandEdges,iH as bestCycleIndex,Ge as bindKeyAad,f4 as bufferLabel,_K as buildEquation,FE as buildMathChannelsBlob,v0 as buildReference,e7 as buildReport,LH as buildTree,$n as cameraLabel,ne as chainVerifier,pr as chartAlarm,yV as chartChannelCount,D1 as chartLabel,vr as clampPct,an as clampRectForKind,VE as clockShiftS,lr as coerceAlarmLine,Gt as coerceAnnotation,OZ as colorAt,WV as colorForDataset,YV as colorSchemeOf,jZ as colorsCss,Le as columnIsNumeric,JE as compareOp,C0 as compareToReference,d8 as completeness,mK as computePolyFit,hK as computeR2,eO as confidenceLabel,c8 as confirmAll,o8 as confirmed,t2 as createEngine,ft as createRuleEvaluator,CD as cutCycle,sD as cycleRuleChannels,TD as cycleTables,eH as cyclicChannels,T0 as decodeBand,nt as decodeChain,K1 as decodeVideo,MQ as decorateColumnLabel,Wn as defaultAreaChartPanelSettings,Hn as defaultBarChartPanelSettings,jn as defaultBoxPlotPanelSettings,Kn as defaultBubbleChartPanelSettings,Xn as defaultCalibrationPanelSettings,er as defaultCameraPanelSettings,Gn as defaultCdfChartPanelSettings,Fn as defaultConfusionPanelSettings,Rn as defaultControlChartPanelSettings,GV as defaultDatasetPalette,Bn as defaultEmbeddingPanelSettings,Vn as defaultFlameGraphPanelSettings,Qn as defaultGanttPanelSettings,Yn as defaultGaugePanelSettings,Nn as defaultHeatmapPanelSettings,On as defaultHistogramPanelSettings,Ln as defaultLossCurvePanelSettings,Tn as defaultMultibandPanelSettings,zn as defaultParallelCoordsPanelSettings,kn as defaultPolarPanelSettings,Zn as defaultQQPlotPanelSettings,Un as defaultRadarPanelSettings,In as defaultRocPanelSettings,Jn as defaultSankeyPanelSettings,Mn as defaultSpectrogramPanelSettings,An as defaultSpectrumPanelSettings,p2 as defaultSplit,qn as defaultTreemapPanelSettings,Pn as defaultViolinPanelSettings,fn as defaultXyAxisScaleSettings,En as defaultXyPanelSettings,Dn as defaultXyzPanelSettings,yD as definitionChannels,_ as deriveKey,ee as deriveRawKeyBase64,V as deviceFingerprint,on as dragLayout,R6 as emptyChannel,z6 as emptyContext,w0 as encodeBand,ct as encodeChain,G1 as encodeVideo,dH as encryptWorkbookFile,V6 as energyChannel,gr as ensurePanelSettingsForPanels,wO as estimateFlash,$D as estimateSync,hE as evalChannel,ZV as eventWithin,C3 as evidenceLabel,R4 as exportRecording,L4 as exportRecordingTo,pE as extractFreeIdentifiers,M2 as fetchUsage,vD as findCycles,_O as flashCycle,hO as flashLevel,VV as formatClockTick,HV as formatClockValue,oH as formatLapValue,f2 as formatSplit,q1 as fragmentVideo,te as generateApiToken,O as generateDeviceKeyPair,e as generateRecoveryKeyPair,he as generateSalt,zV as getClockTimeZone,U as getRawNonEmptyLines,_0 as gridAt,tH as guessBeaconChannel,$e as hashToken,Re as importStreamKey,z7 as inferContext,Be as inferParseConfig,jV as isClockAxis,IH as isImportable,jQ as isMathChannelName,bD as kpiColumn,qE as kpiKey,xD as kpisOf,t7 as listedFindings,E2 as liveBytesPerSec,E0 as liveSegmentTracker,eD as localDay,p0 as localSeconds,Je as makeKeyCheck,Yt as markToAnnotation,u8 as moneyGaps,j6 as namesOf,yn as newGaugeItem,br as newMathChannel,ln as newPanel,YE as newResetState,oe as newRun,yr as newSeriesId,gO as nextFlashCycle,bV as niceMajorStep,XV as observeColorScheme,lB as openDatasetFromText,s as openMessage,oV as openSession,Te as openUnderProjectKey,ae as openWithKey,Ve as openWithPassword,nr as panelCameras,Xe as parseColumnNames,le as parseConfigsEqual,$6 as parseContext,mD as parseCycleDefinitions,et as parseDatasetWithConfig,fE as parseFormula,ce as parseKrc,Ae as parseKrcHeader,LE as parseMathChannelsFile,xn as parseOptionalAxisRange,hr as parsePanelChartSettingsMap,Ze as parseRecoveryCode,d2 as parseSplit,x0 as pooledSd,E6 as presetForIndustry,T6 as presetOf,AZ as presetStops,EO as probeClock,ue as projectConfigKeyAad,Me as projectWrapAad,tt as randomKey,_D as readSource,Ie as recordingKeyAad,Ke as recordingKeySealAad,pe as recoveryAttestationAad,ve as recoveryCode,We as recoveryKeyAad,Fe as recoveryPrivateKey,DQ as referenceBands,g0 as resample,XE as resetStep,dr as resolveLinkedAlarms,B6 as roleOf,ED as rowsCsv,w as sealMessage,Se as sealUnderProjectKey,be as sealWithKey,re as sealWithPassword,rt as senderBindKey,lt as senderBinding,RV as setClockTimeZone,nD as shiftDay,se as splitApiKey,$V as splitLaps,st as streamKeyAad,fe as subsampleIndices,BV as subscribeClockTimeZone,nH as suggestBeacon,s8 as suggestedCount,BE as syncShiftS,A6 as term,ht as thresholdOf,$E as tzOffsetS,N as unwrapForDevice,o as unwrapStreamKey,pt as validateRule,at as verifyKeyCheck,qH as verifyLicense,F as verifySenderBinding,n7 as viewSections,u as workbookBodyAad,cH as workbookExportAad,pH as workbookFileInfo,c as workbookKeyAad,T as wrapForDevice,tD as zonedInstant};