@kymoscope/sdk 0.19.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/importer.worker-B4rzpZKn.js +1006 -0
- package/dist/importer-D_Rxf-9b.js +12 -0
- package/dist/importers-D4cCElZQ.js +1004 -0
- package/dist/kymoscope-embed.js +1094 -94
- package/dist/kymoscope-sdk.js +70 -70
- package/dist/types/engine/createEngine.d.ts +2 -0
- package/dist/types/lib/importers/delimited/format.d.ts +3 -0
- package/dist/types/lib/importers/delimited/importer.d.ts +5 -0
- package/dist/types/lib/importers/delimited/parse.d.ts +11 -0
- package/dist/types/lib/importers/mcap/decode.d.ts +26 -0
- package/dist/types/lib/importers/mcap/format.d.ts +2 -0
- package/dist/types/lib/importers/mcap/importer.d.ts +2 -0
- package/dist/types/lib/importers/mcap/lz4.d.ts +5 -0
- package/dist/types/lib/importers/mcap/protobuf.d.ts +2 -0
- package/dist/types/lib/importers/mseed/format.d.ts +7 -0
- package/dist/types/lib/importers/mseed/importer.d.ts +2 -0
- package/dist/types/lib/importers/mseed/steim.d.ts +6 -0
- package/dist/types/lib/importers/openImport.d.ts +1 -0
- package/dist/types/lib/importers/parquet/format.d.ts +2 -0
- package/dist/types/lib/importers/parquet/importer.d.ts +5 -0
- package/dist/types/lib/importers/pqdif/format.d.ts +2 -0
- package/dist/types/lib/importers/pqdif/importer.d.ts +2 -0
- package/dist/types/lib/importers/pqdif/records.d.ts +50 -0
- package/dist/types/lib/importers/pqdif/tags.d.ts +98 -0
- package/dist/types/lib/importers/table/importer.d.ts +10 -0
- package/dist/types/lib/importers/table/long.d.ts +37 -0
- package/dist/types/lib/importers/table/table.d.ts +44 -0
- package/dist/types/lib/importers/types.d.ts +2 -0
- package/dist/types/lib/importers/ulog/format.d.ts +3 -0
- package/dist/types/lib/importers/ulog/importer.d.ts +2 -0
- package/dist/types/lib/importers/xlsx/format.d.ts +2 -0
- package/dist/types/lib/importers/xlsx/importer.d.ts +23 -0
- package/dist/types/lib/importers/xlsx/xml.d.ts +24 -0
- package/dist/types/lib/importers/xlsx/zip.d.ts +12 -0
- package/dist/types/lib/yAxisTicks.d.ts +6 -0
- package/package.json +7 -1
- package/dist/assets/importer.worker-BTbPiEHd.js +0 -6
- package/dist/importer-O00bqqEU.js +0 -11
- package/dist/importers-C90FOCV-.js +0 -5
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
const e=1<<20,t=16<<20;var n=class{size;bytesRead=0;#e;#t=new Map;constructor(e){this.#e=e,this.size=e.size}async read(t,n){let r=Math.min(this.size,t+n);if(r<=t)return new Uint8Array;if(r-t>e)return this.slice(t,r-t);let i=Math.floor(t/e),a=Math.floor((r-1)/e),o=await this.#n(i);if(i===a)return o.subarray(t-i*e,r-i*e);let s=new Uint8Array(r-t),c=o.subarray(t-i*e);return s.set(c),s.set((await this.#n(a)).subarray(0,r-a*e),c.length),s}async slice(e,t){let n=Math.min(this.size,e+t);if(n<=e)return new Uint8Array;let r=new Uint8Array(await this.#e.slice(e,n).arrayBuffer());return this.bytesRead+=r.length,r}async*windows(e,n,r=t){let i=Math.min(this.size,e+n);for(let t=e;t<i;t+=r)yield{offset:t,bytes:await this.slice(t,Math.min(r,i-t))}}async#n(t){let n=this.#t.get(t);if(n)return this.#t.delete(t),this.#t.set(t,n),n;let r=await this.slice(t*e,e);return this.#t.size>=64&&this.#t.delete(this.#t.keys().next().value),this.#t.set(t,r),r}};const r=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);function i(e,t,n=!0){let r=e.getUint32(n?t:t+4,n);return e.getUint32(n?t+4:t,n)*4294967296+r}function a(e,t,n=!0){let r=e.getUint32(n?t:t+4,n);return e.getInt32(n?t+4:t,n)*4294967296+r}const o=new TextDecoder(`utf-8`),s=new TextDecoder(`latin1`);function c(e,t=!1){let n=e.indexOf(0);return(t?s:o).decode(n<0?e:e.subarray(0,n))}const l=e=>s.decode(e),u=e=>o.decode(e);function d(e,t,n=0){if(e.length<n+t.length)return!1;for(let r=0;r<t.length;r++)if(e[n+r]!==t.charCodeAt(r))return!1;return!0}function f(e,t){return e.selection.find(e=>e.group===t)?.channels??[]}const p={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,exp:Math.exp,ln:Math.log,log:Math.log,log10:Math.log10,sqrt:Math.sqrt,abs:Math.abs,pow:Math.pow,min:Math.min,max:Math.max};function m(e){if(e.length>4096)return null;let t=e.match(/\d+\.?\d*(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|\*\*|[-+*/^(),]|\S/g)??[],n=0,r=()=>t[n],i=()=>{throw Error(`formula`)},a=e=>{t[n++]!==e&&i()},o=()=>{let e=s();for(;r()===`+`||r()===`-`;){let r=t[n++],i=e,a=s();e=r===`+`?e=>i(e)+a(e):e=>i(e)-a(e)}return e},s=()=>{let e=c();for(;r()===`*`||r()===`/`;){let r=t[n++],i=e,a=c();e=r===`*`?e=>i(e)*a(e):e=>i(e)/a(e)}return e},c=()=>{if(r()===`-`){n++;let e=c();return t=>-e(t)}return r()===`+`?(n++,c()):l()},l=()=>{let e=u();if(r()===`^`||r()===`**`){n++;let t=c();return n=>e(n)**t(n)}return e},u=()=>{let e=t[n++];if(e===void 0&&i(),e===`(`){let e=o();return a(`)`),e}if(/^[\d.]/.test(e)){let t=Number(e);return Number.isFinite(t)||i(),()=>t}if(e===`X`||e===`x`||e===`X1`)return e=>e;if(Object.hasOwn(p,e)){let t=p[e];a(`(`);let i=[o()];for(;r()===`,`;)n++,i.push(o());return a(`)`),i.length===1?e=>t(i[0](e)):e=>t(...i.map(t=>t(e)))}return i()};try{let e=o();return n===t.length?e:null}catch{return null}}const h={k:`id`};function g(e,t){let{keys:n,vals:r}=e,i=n.length;if(i===0)return t;if(t<=n[0])return r[0];if(t>=n[i-1])return r[i-1];let a=0,o=i-1;for(;o-a>1;){let e=a+o>>1;n[e]<=t?a=e:o=e}return e.interp?r[a]+(r[o]-r[a])*(t-n[a])/(n[o]-n[a]):t-n[a]<=n[o]-t?r[a]:r[o]}function _(e,t){let n=t.length;switch(e.k){case`lin`:{let{a:r,b:i}=e;if(r===1&&i===0)return;for(let e=0;e<n;e++)t[e]=r*t[e]+i;return}case`rat`:{let[r,i,a,o,s,c]=e.p;for(let e=0;e<n;e++){let n=t[e];t[e]=(r*n*n+i*n+a)/(o*n*n+s*n+c)}return}case`poly`:{let[r,i,a,o,s,c]=e.p;for(let e=0;e<n;e++){let n=t[e]-s-c;t[e]=(i-o*n)/(a*n-r)}return}case`alg`:{let r=e.f;for(let e=0;e<n;e++)t[e]=r(t[e]);return}case`tab`:for(let r=0;r<n;r++)t[r]=g(e,t[r]);return;case`rtv`:for(let r=0;r<n;r++){let n=t[r],i=e.def;for(let t=0;t<e.lo.length;t++)if(n>=e.lo[t]&&n<=e.hi[t]){i=e.vals[t];break}t[r]=i}return;default:return}}function v(e,t){let n=Float64Array.of(t);return _(e,n),n[0]}const y=(e,t)=>e===null||typeof e==`string`?e:String(v(e,t));function b(e,t){let n=Array(t.length),r=e.ranges.every(e=>e.lo===e.hi)?new Map(e.ranges.map(e=>[e.lo,e.to])):null;for(let i=0;i<t.length;i++){let a=t[i];if(a!==a){n[i]=null;continue}let o=e.def;if(r){let e=r.get(a);e!==void 0&&(o=e)}else for(let t of e.ranges)if(a>=t.lo&&(e.int||t.lo===t.hi?a<=t.hi:a<t.hi)){o=t.to;break}n[i]=y(o,a)}return n}function x(e,t){let n=(e,t)=>({type:e,bigEndian:t,encoding:`latin1`});switch(e){case 0:return n(`uint`,!t);case 1:return n(`int`,!t);case 2:case 3:return n(`float`,!t);case 7:return n(`string`,!1);case 8:return n(`bytes`,!1);case 9:return n(`uint`,!0);case 10:return n(`int`,!0);case 11:case 12:return n(`float`,!0);case 13:return n(`uint`,!1);case 14:return n(`int`,!1);case 15:case 16:return n(`float`,!1);default:return null}}async function S(e,t,n){let i=r(t).getUint16(24,!0)===0,a=async t=>{let n=r(await e.read(t,4)).getUint16(2,i),a=await e.read(t,n);return{id:l(a.subarray(0,2)),v:r(a),b:a,size:n}},o=(e,t)=>e.getUint32(t,i),s=(e,t)=>e.getUint16(t,i),u=(e,t)=>e.getFloat64(t,i),d=async e=>e?c((await a(e)).b.subarray(4),!0):``,f=[],p=new Set,g=e=>{if(p.has(e))throw Error(`This MDF file is damaged (its blocks link in a loop).`);p.add(e)},_=async(e,t)=>{if(!e)return{conv:h,unit:``};let{v:n,b:r}=await a(e),i=c(r.subarray(22,42),!0),l=s(n,42),f=s(n,44),p=e=>u(n,46+8*e);switch(l){case 0:return{conv:{k:`lin`,a:p(1),b:p(0)},unit:i};case 1:case 2:{let e=new Float64Array(f),t=new Float64Array(f);for(let n=0;n<f;n++)e[n]=p(2*n),t[n]=p(2*n+1);return{conv:{k:`tab`,keys:e,vals:t,interp:l===1},unit:i}}case 6:return{conv:{k:`poly`,p:[0,1,2,3,4,5].map(p)},unit:i};case 9:return{conv:{k:`rat`,p:[0,1,2,3,4,5].map(p)},unit:i};case 10:{let e=c(r.subarray(46,302),!0),t=m(e);return{conv:t?{k:`alg`,f:t}:{k:`unsupported`,what:`the formula "${e}"`},unit:i}}case 11:return{conv:{k:`text`,ranges:Array.from({length:f},(e,t)=>{let i=46+40*t,a=u(n,i);return{lo:a,hi:a,to:c(r.subarray(i+8,i+40),!0)}}),def:null,int:t},unit:i};case 12:{let e=await Promise.all(Array.from({length:f},async(e,t)=>{let r=46+20*t;return{lo:u(n,r),hi:u(n,r+8),to:await d(o(n,r+16))}}));return{conv:{k:`text`,ranges:e.slice(1),def:e[0]?.to??null,int:t},unit:i}}case 65535:return{conv:h,unit:i};default:return{conv:{k:`unsupported`,what:`MDF3 conversion type ${l}`},unit:i}}},v=await a(64),y=null;if(v.size>=172&&(o(v.v,164)||o(v.v,168))){let e=o(v.v,168)*4294967296+o(v.v,164);y=new Date(e/1e6).toISOString()}else{let e=l(v.b.subarray(18,28)),t=l(v.b.subarray(28,36));/^\d\d:\d\d:\d{4}$/.test(e)&&(y=`${e.slice(6)}-${e.slice(3,5)}-${e.slice(0,2)}T${t}`)}let b=[],S=0;for(let e=o(v.v,4),t=0;e;t++){g(e);let n=await a(e),r=s(n.v,22),l=[];for(let e=o(n.v,8);e;){g(e);let n=await a(e),u=[],p=null;for(let e=o(n.v,8);e;){g(e);let t=await a(e),n=c(t.b.subarray(26,58),!0),r=(t.size>=222?await d(o(t.v,218)):``)||n,l=x(s(t.v,190),i),m=s(t.v,186)+(t.size>=228?8*s(t.v,226):0);if(!l)f.push(`${r}: MDF3 data type ${s(t.v,190)} is not supported; skipped.`);else{let{conv:e,unit:n}=await _(o(t.v,8),l.type!==`float`),i={name:r,unit:n,kind:s(t.v,24)===1?`master`:`value`,...l,conv:e,sd:null,sdRecordId:null,byteOffset:m>>3,bitOffset:m&7,bitCount:s(t.v,188),invalBit:null,allInvalid:!1};i.kind===`master`&&!p?p=i:i.kind===`value`&&u.push(i)}e=o(t.v,4)}S++,l.push({name:await d(o(n.v,12))||`Group ${S}`,dg:t,recordId:s(n.v,16),recordIdSize:+(r>0),idTrailer:+(r===2),dataBytes:s(n.v,20),invalBytes:0,cycles:o(n.v,22),vlsdCg:!1,sorted:!0,master:p,channels:u,stream:[],busType:0,busEvent:!1}),e=o(n.v,4)}let u=l.reduce((e,t)=>e+t.cycles*(t.recordIdSize+t.dataBytes+t.idTrailer),0),p=[{offset:o(n.v,16),length:u,zip:null}];for(let e of l)e.stream=p,e.sorted=l.length===1,b.push(e);e=o(n.v,4)}return{version:`MDF ${n}`,startTime:y,groups:b,notes:f,meta:{}}}const C=e=>e*1032+1024,w=1e3,T=(e,t)=>e.length>t?`${e.slice(0,t-1)}…`:e;function ee(e){let t=e.notes;for(let n of e.groups){n.name=T(String(n.name),256);for(let e of n.channels)e.name=T(String(e.name),256),e.unit=T(String(e.unit??``),64);Number.isInteger(n.samples)&&n.samples>=-1||(n.samples=-1),n.rateHz===null||Number.isFinite(n.rateHz)&&n.rateHz>0||(n.rateHz=null),n.time.kind===`rate`&&!(Number.isFinite(n.time.rate)&&n.time.rate>0&&Number.isFinite(n.time.start))&&(t.push(`${n.name}: its sample rate in the file is not usable; samples are numbered instead.`),n.time={kind:`index`},n.rateHz=null)}t.length>100&&t.splice(100,t.length-100,`${t.length-100} more notes.`),e.notes=t.map(e=>T(String(e),w));let n={};for(let[t,r]of Object.entries(e.meta).slice(0,200))n[T(t,256)]=T(String(r),w);return e.meta=n,e.events=e.events.filter(e=>Number.isFinite(e.time)).map(e=>({time:e.time,text:T(String(e.text),w)})),e}function E(e){return e instanceof Error&&(e.constructor===Error||e.name===`KymoscopeError`||e.name===`AbortError`)?e:Error(`This file couldn't be read (it may be damaged).`)}function D(e,t){if(e.seen.has(t))throw Error(`This MF4 is damaged (its blocks link in a loop).`);e.seen.add(t)}async function O(e,t){let n=await e.read(t,24);if(n.length<24)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let a=r(n),o=l(n.subarray(0,4)),s=i(a,8),c=i(a,16);if(!o.startsWith(`##`)||s<24+8*c||s>1<<26)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let u=await e.read(t,s);if(u.length<s)throw Error(`This MF4 is damaged (the block at byte ${t} runs past the end of the file).`);let d=r(u),f=[];for(let e=0;e<c;e++)f.push(i(d,24+8*e));let p=u.subarray(24+8*c);return{id:o,links:f,data:r(p),bytes:p}}const te={lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`};function ne(e){let t=e.indexOf(`<TX>`),n=t<0?-1:e.indexOf(`</TX>`,t+4);return(n>=0?e.slice(t+4,n):e.replace(/<[^<>]*>/g,``)).replace(/&(lt|gt|amp|quot|apos);/g,(e,t)=>te[t]).trim()}function k(e,t){if(!t)return Promise.resolve(``);let n=e.texts.get(t);return n||(n=O(e.io,t).then(e=>{let t=c(e.bytes);return e.id===`##MD`?ne(t):t}),e.texts.set(t,n)),n}async function A(e,t,n=0){if(!t)return[];let a=e.io,o=await a.read(t,24),s=l(o.subarray(0,4)),c=o.length<24?0:i(r(o),8);switch(s){case`##DT`:case`##SD`:case`##RD`:return[{offset:t+24,length:c-24,zip:null}];case`##DZ`:{let e=r(await a.read(t+24,24));if(e.byteLength<24)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let n=e.getUint8(2);if(n===2||n===3)throw Error(`This MF4 uses zstd compression, which isn't supported yet.`);if(n===4||n===5)throw Error(`This MF4 uses LZ4 compression, which isn't supported yet.`);if(n>5)throw Error(`This MF4 is damaged (unknown compression type ${n}).`);let o=e.getUint32(4,!0),s=i(e,8),c=i(e,16);if(s>C(c)||n===1&&o===0)throw Error(`This MF4 is damaged (bad compressed block at byte ${t}).`);if(n===1&&s>268435456)throw Error(`This MF4 has a compressed block over 256 MB, which Kymoscope cannot read.`);return[{offset:t+48,length:c,zip:{type:n,param:o,orgLength:s}}]}case`##DL`:{if(n>1)throw Error(`This MF4 is damaged (unexpected ${s} block in its data).`);let r=[];for(let n=t;n;){D(e,n);let t=await O(a,n);for(let n of t.links.slice(1))r.push(...await A(e,n,2));n=t.links[0]}return r}case`##HL`:if(n>0)throw Error(`This MF4 is damaged (unexpected ${s} block in its data).`);return D(e,t),A(e,(await O(a,t)).links[0],1);case`##DV`:case`##DI`:throw Error(`This MF4 uses column-oriented storage (MDF 4.2 DV/DI blocks), which Kymoscope cannot read yet.`);default:throw Error(`This MF4 is damaged (unexpected ${s} block in its data).`)}}async function re(e,t,n){return t?l(await e.io.read(t,4))===`##CC`?j(e,t,n+1):k(e,t):null}async function j(e,t,n=0){if(!t||n>4||e.busy.has(t))return h;let r=e.convs.get(t);if(r)return r;e.busy.add(t);try{let r=await ie(e,t,n);return e.convs.set(t,r),r}finally{e.busy.delete(t)}}async function ie(e,t,n){let r=await O(e.io,t),i=r.data,a=i.getUint8(0),o=i.getUint16(4,!0),s=i.getUint16(6,!0),c=new Float64Array(s);for(let e=0;e<s;e++)c[e]=i.getFloat64(24+8*e,!0);let l=r.links.slice(4,4+o),u=()=>Promise.all(l.map(t=>re(e,t,n)));switch(a){case 0:return h;case 1:return{k:`lin`,b:c[0],a:c[1]};case 2:return{k:`rat`,p:[...c]};case 3:{let t=await k(e,l[0]),n=m(t);return n?{k:`alg`,f:n}:{k:`unsupported`,what:`the formula "${t}"`}}case 4:case 5:{let e=s>>1,t=new Float64Array(e),n=new Float64Array(e);for(let r=0;r<e;r++)t[r]=c[2*r],n[r]=c[2*r+1];return{k:`tab`,keys:t,vals:n,interp:a===4}}case 6:{let e=Math.max(0,Math.floor((s-1)/3)),t=new Float64Array(e),n=new Float64Array(e),r=new Float64Array(e);for(let i=0;i<e;i++)t[i]=c[3*i],n[i]=c[3*i+1],r[i]=c[3*i+2];return{k:`rtv`,lo:t,hi:n,vals:r,def:c[s-1]}}case 7:{let e=await u();return{k:`text`,ranges:[...c].map((t,n)=>({lo:t,hi:t,to:e[n]??null})),def:e[s]??null,int:!0}}case 8:{let e=await u(),t=s>>1;return{k:`text`,ranges:Array.from({length:t},(t,n)=>({lo:c[2*n],hi:c[2*n+1],to:e[n]??null})),def:e[t]??null,int:!0}}default:return{k:`unsupported`,what:`conversion type ${a}`}}}const ae={0:{type:`uint`,bigEndian:!1,encoding:`latin1`},1:{type:`uint`,bigEndian:!0,encoding:`latin1`},2:{type:`int`,bigEndian:!1,encoding:`latin1`},3:{type:`int`,bigEndian:!0,encoding:`latin1`},4:{type:`float`,bigEndian:!1,encoding:`latin1`},5:{type:`float`,bigEndian:!0,encoding:`latin1`},6:{type:`string`,bigEndian:!1,encoding:`latin1`},7:{type:`string`,bigEndian:!1,encoding:`utf-8`},8:{type:`string`,bigEndian:!1,encoding:`utf-16le`},9:{type:`string`,bigEndian:!0,encoding:`utf-16be`},10:{type:`bytes`,bigEndian:!1,encoding:`latin1`}};async function oe(e,t){let{io:n,notes:r}=e,a=t.data,o=a.getUint8(0),s=a.getUint8(1),c=a.getUint8(2),u=await k(e,t.links[2]),d=ae[c];if(!d)return r.push(`${u}: data type ${c} is not supported; the channel was skipped.`),null;let f;if(o===2||o===3)if(s===1)f=o===2?`master`:`vmaster`;else{if(r.push(`The master channel ${u} is not time (sync type ${s}): samples are numbered instead.`),o===3)return null;f=`value`}else if(o===1)f=`vlsd`;else if(o===0||o===4)f=`value`;else return r.push(`${u}: channel type ${o} is not supported; skipped.`),null;let p=await j(e,t.links[4]),m=p.k===`text`?{...p,int:d.type!==`float`}:p,h=await k(e,t.links[6]);!h&&t.links[4]&&(h=await k(e,(await O(n,t.links[4])).links[1]));let g=null,_=null;f===`vlsd`&&t.links[5]&&(l(await n.read(t.links[5],4))===`##CG`?_=i((await O(n,t.links[5])).data,0):g=await A(e,t.links[5]));let v=a.getUint32(12,!0);return{name:u,unit:h,kind:f,...d,conv:m,sd:g,sdRecordId:_,byteOffset:a.getUint32(4,!0),bitOffset:a.getUint8(3),bitCount:a.getUint32(8,!0),invalBit:v&2?a.getUint32(16,!0):null,allInvalid:(v&1)!=0}}async function M(e,t,n,r=0){let{io:i,notes:a}=e;for(let o=t;o;){D(e,o);let t=await O(i,o),s=t.links[1];s&&r<4&&(l(await i.read(s,4))===`##CN`?await M(e,s,n,r+1):a.push(`${await k(e,t.links[2])}: array channels (CA) are not supported yet; skipped.`));let c=await oe(e,t);c&&n.push(c),o=t.links[0]}}async function se(e,t,n,r){let a=t.data,o=a.getUint16(16,!0),s=0;t.links[3]&&(s=(await O(e.io,t.links[3])).data.getUint8(1));let c={name:await k(e,t.links[2]),dg:n,recordId:i(a,0),recordIdSize:r,idTrailer:0,dataBytes:a.getUint32(24,!0),invalBytes:a.getUint32(28,!0),cycles:i(a,8),vlsdCg:(o&1)!=0,sorted:!0,master:null,channels:[],stream:[],busType:s,busEvent:(o&2)!=0};if(c.vlsdCg)return c;let l=[];await M(e,t.links[1],l);for(let e of l)e.kind===`master`||e.kind===`vmaster`?c.master||=e:c.channels.push(e);return c}async function N(e,t){let n=await O(e,64);if(n.id!==`##HD`)throw Error(`This MF4 is damaged (no header block).`);let r=i(n.data,0),a=(n.data.getUint8(12)&1)!=0,o=new Date(r/1e6).toISOString(),s=r>0?a?o.slice(0,-1):o:null,c={io:e,notes:[],seen:new Set,texts:new Map,convs:new Map,busy:new Set},l=[],u=0;for(let t=n.links[0],r=0;t;r++){D(c,t);let n=await O(e,t),i=n.data.getUint8(0),a=[];for(let t=n.links[1];t;){D(c,t);let n=await O(e,t),o=await se(c,n,r,i);o.vlsdCg||(u++,o.name||=`Group ${u}`),a.push(o),t=n.links[0]}let o=await A(c,n.links[2]),s=a.length===1;for(let e of a)e.stream=o,e.sorted=s,l.push(e);t=n.links[0]}return{version:`MF4 ${t}`,startTime:s,groups:l,notes:c.notes,meta:{}}}function ce(e){let t=e&32768?-1:1,n=e>>10&31,r=e&1023;return n===0?t*2**-14*(r/1024):n===31?r?NaN:t*(1/0):t*2**(n-15)*(1+r/1024)}function P(e,t,n,i,a,o,s=0){let c=r(t),l=!e.bigEndian,u=a+e.byteOffset,d=e.bitCount;if(e.bitOffset===0)if(e.type===`float`){if(d===64){for(let e=0;e<n;e++,u+=i)o[s+e]=c.getFloat64(u,l);return}if(d===32){for(let e=0;e<n;e++,u+=i)o[s+e]=c.getFloat32(u,l);return}if(d===16){for(let e=0;e<n;e++,u+=i)o[s+e]=ce(c.getUint16(u,l));return}}else if(e.type===`int`){if(d===8){for(let e=0;e<n;e++,u+=i)o[s+e]=c.getInt8(u);return}if(d===16){for(let e=0;e<n;e++,u+=i)o[s+e]=c.getInt16(u,l);return}if(d===32){for(let e=0;e<n;e++,u+=i)o[s+e]=c.getInt32(u,l);return}if(d===64){for(let e=0;e<n;e++,u+=i)o[s+e]=c.getInt32(u+(l?4:0),l)*4294967296+c.getUint32(u+(l?0:4),l);return}}else{if(d===8){for(let e=0;e<n;e++,u+=i)o[s+e]=t[u];return}if(d===16){for(let e=0;e<n;e++,u+=i)o[s+e]=c.getUint16(u,l);return}if(d===32){for(let e=0;e<n;e++,u+=i)o[s+e]=c.getUint32(u,l);return}if(d===64){for(let e=0;e<n;e++,u+=i)o[s+e]=c.getUint32(u+(l?4:0),l)*4294967296+c.getUint32(u+(l?0:4),l);return}}let f=e.bitOffset+d+7>>3,p=2**e.bitOffset,m=2**d,h=m/2,g=e.type===`int`;for(let e=0;e<n;e++,u+=i){let n=0;if(l)for(let e=f-1;e>=0;e--)n=n*256+t[u+e];else for(let e=0;e<f;e++)n=n*256+t[u+e];n=Math.floor(n/p)%m,o[s+e]=g&&n>=h?n-m:n}}const le=new Map,ue=e=>{let t=le.get(e);return t||le.set(e,t=new TextDecoder(e)),t};function de(e){let t=e.indexOf(`\0`);return t<0?e:e.slice(0,t)}function fe(e,t,n,r,i){let a=ue(e.encoding),o=e.bitCount>>3,s=Array(n);for(let c=0,l=i+e.byteOffset;c<n;c++,l+=r)s[c]=de(a.decode(t.subarray(l,l+o)));return s}function pe(e,t,n,r,i,a){let o=a instanceof Float64Array?NaN:null;if(e.allInvalid){for(let e=0;e<n;e++)a[e]=o;return}if(e.invalBit===null)return;let s=1<<(e.invalBit&7);for(let c=0,l=i+(e.invalBit>>3);c<n;c++,l+=r)t[l]&s&&(a[c]=o)}const me={id:`mdf`,label:`ASAM MDF (MF4, MDF 3)`,extensions:[`.mf4`,`.mdf`,`.mf3`,`.dat`],companions:[{ext:`.dbc`,anyName:!0}],sniff:e=>d(e,`MDF `)||d(e,`UnFinMF `)},F=e=>e.recordIdSize+e.dataBytes+e.invalBytes+e.idTrailer,he=(e,t)=>e.reduce((e,n)=>e+(n.zip?n.zip.orgLength:Math.max(0,Math.min(n.length,t-n.offset))),0),ge=e=>e.byteOffset+Math.ceil((e.bitOffset+e.bitCount)/8);function _e(e,t){return e.kind===`vmaster`?!0:(e.kind===`vlsd`||e.type===`uint`||e.type===`int`||e.type===`float`?!(e.bitCount>=1&&e.bitCount<=64):!(e.bitCount>=8))?!1:ge(e)<=t.dataBytes}function ve(e,t){let n=e.notes;for(let r of e.groups){if(![0,1,2,4,8].includes(r.recordIdSize))throw Error(`This MDF file is damaged (bad record id size).`);if(r.vlsdCg)continue;let e=F(r);if(e>67108864||e===0){r.cycles>0&&n.push(`${r.name||`A group`}: its records are ${e===0?`empty`:`too large`} (damaged); skipped.`),r.cycles=0;continue}r.cycles=Math.min(r.cycles,Math.floor(he(r.stream,t)/e));let i=r.channels.filter(e=>!_e(e,r));for(let e of i)n.push(`${e.name}: its bits lie outside its record (damaged); skipped.`);i.length&&(r.channels=r.channels.filter(e=>!i.includes(e))),r.master&&!_e(r.master,r)&&(n.push(`${r.master.name}: the time channel lies outside its record (damaged): samples are numbered instead.`),r.master=null);for(let e of r.master?[...r.channels,r.master]:r.channels)e.invalBit!==null&&e.invalBit>=8*r.invalBytes&&(e.invalBit=null)}}function ye(e,t){let n=0;for(let r of e.master?[...t,e.master]:t){if(r.invalBit!==null)return 1/0;r.kind!==`vmaster`&&(n=Math.max(n,r.byteOffset+(r.bitOffset+r.bitCount+7>>3)))}return e.recordIdSize+n}var I=Uint8Array,L=Uint16Array,be=Int32Array,xe=new I([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Se=new I([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ce=new I([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),we=function(e,t){for(var n=new L(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new be(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Te=we(xe,2),Ee=Te.b,De=Te.r;Ee[28]=258,De[258]=28;var Oe=we(Se,0),ke=Oe.b;Oe.r;for(var Ae=new L(32768),R=0;R<32768;++R){var z=(R&43690)>>1|(R&21845)<<1;z=(z&52428)>>2|(z&13107)<<2,z=(z&61680)>>4|(z&3855)<<4,Ae[R]=((z&65280)>>8|(z&255)<<8)>>1}for(var B=(function(e,t,n){for(var r=e.length,i=0,a=new L(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new L(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new L(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Ae[d]>>c]=l}else for(s=new L(r),i=0;i<r;++i)e[i]&&(s[i]=Ae[o[e[i]-1]++]>>15-e[i]);return s}),V=new I(288),R=0;R<144;++R)V[R]=8;for(var R=144;R<256;++R)V[R]=9;for(var R=256;R<280;++R)V[R]=7;for(var R=280;R<288;++R)V[R]=8;for(var je=new I(32),R=0;R<32;++R)je[R]=5;var Me=B(V,9,1),Ne=B(je,5,1),Pe=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},H=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},Fe=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Ie=function(e){return(e+7)/8|0},Le=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new I(e.subarray(t,n))},Re=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],U=function(e,t,n){var r=Error(t||Re[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,U),!n)throw r;return r},ze=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new I(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new I(i*3));var l=function(e){var t=n.length;if(e>t){var r=new I(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=H(e,d,1);var v=H(e,d+1,3);if(d+=3,!v){var y=Ie(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&U(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}else if(v==1)p=Me,m=Ne,h=9,g=5;else if(v==2){var S=H(e,d,31)+257,C=H(e,d+10,15)+4,w=S+H(e,d+5,31)+1;d+=14;for(var T=new I(w),ee=new I(19),E=0;E<C;++E)ee[Ce[E]]=H(e,d+E*3,7);d+=C*3;for(var D=Pe(ee),O=(1<<D)-1,te=B(ee,D,1),E=0;E<w;){var ne=te[H(e,d,O)];d+=ne&15;var y=ne>>4;if(y<16)T[E++]=y;else{var k=0,A=0;for(y==16?(A=3+H(e,d,3),d+=2,k=T[E-1]):y==17?(A=3+H(e,d,7),d+=3):y==18&&(A=11+H(e,d,127),d+=7);A--;)T[E++]=k}}var re=T.subarray(0,S),j=T.subarray(S);h=Pe(re),g=Pe(j),p=B(re,h,1),m=B(j,g,1)}else U(1);if(d>_){c&&U(0);break}}s&&l(f+131072);for(var ie=(1<<h)-1,ae=(1<<g)-1,oe=d;;oe=d){var k=p[Fe(e,d)&ie],M=k>>4;if(d+=k&15,d>_){c&&U(0);break}if(k||U(2),M<256)n[f++]=M;else if(M==256){oe=d,p=null;break}else{var se=M-254;if(M>264){var E=M-257,N=xe[E];se=H(e,d,(1<<N)-1)+Ee[E],d+=N}var ce=m[Fe(e,d)&ae],P=ce>>4;ce||U(3),d+=ce&15;var j=ke[P];if(P>3){var N=Se[P];j+=Fe(e,d)&(1<<N)-1,d+=N}if(d>_){c&&U(0);break}s&&l(f+131072);var le=f+se;if(f<j){var ue=a-j,de=Math.min(j,le);for(ue+f<0&&U(3);f<de;++f)n[f]=r[ue+f]}for(;f<le;++f)n[f]=n[f-j]}}t.l=p,t.p=oe,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?Le(n,0,f):n.subarray(0,f)},Be=new I(0),Ve=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&U(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&U(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2},He=function(){function e(e,t){typeof e==`function`&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new I(32768),this.p=new I(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||U(5),this.d&&U(4),!this.p.length)this.p=e;else if(e.length){var t=new I(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=ze(this.p,this.s,this.o);this.ondata(Le(n,t,this.s.b),this.d),this.o=Le(n,this.s.b-32768),this.s.b=this.o.length,this.p=Le(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),Ue=function(){function e(e,t){He.call(this,e,t),this.v=e&&e.dictionary?2:1}return e.prototype.push=function(e,t){if(He.prototype.e.call(this,e),this.v){if(this.p.length<6&&!t)return;this.p=this.p.subarray(Ve(this.p,this.v-1)),this.v=0}t&&(this.p.length<4&&U(6,`invalid zlib data`),this.p=this.p.subarray(0,-4)),He.prototype.c.call(this,t)},e}(),We=typeof TextDecoder<`u`&&new TextDecoder;try{We.decode(Be,{stream:!0})}catch{}const Ge=65536;async function*Ke(e){for(let t=0;t<e.length;t+=Ge)yield e.subarray(t,t+Ge)}async function*qe(e){if(typeof DecompressionStream!=`function`){let t=[],n=new Ue(e=>{t.push(e)});for await(let r of e)for(n.push(r,!1);t.length;)yield t.shift();for(n.push(new Uint8Array,!0);t.length;)yield t.shift();return}let t=new DecompressionStream(`deflate`),n=t.writable.getWriter();(async()=>{for await(let t of e)await n.write(t);await n.close()})().catch(e=>n.abort(e).catch(()=>{}));let r=t.readable.getReader();try{for(;;){let{done:e,value:t}=await r.read().catch(e=>{throw e instanceof TypeError?Error(`This file's compressed data is damaged.`):e});if(e)return;yield t}}finally{r.cancel().catch(()=>{})}}async function W(e,t=-1,n=1/0){let r=[],i=Math.min(t,n),a=t>=0?new Uint8Array(i):null,o=0;for await(let s of qe(Ke(e))){if(a){if(o+s.length>t&&n>t)throw Error(`Compressed data is longer than its header says.`);a.set(o+s.length>i?s.subarray(0,i-o):s,o)}else r.push(s);if(o+=s.length,o>=n)break}if(a)return o>=i?a:a.subarray(0,o);let s=r.length===1?r[0]:new Uint8Array(o);return r.length>1&&r.reduce((e,t)=>(s.set(t,e),e+t.length),0),o>n?s.subarray(0,n):s}const Je=new Uint8Array(Uint32Array.of(1).buffer)[0]===1;function Ye(e,t,n,r=t){let i=Math.floor(n/t),a=new Uint8Array(r<t?i*r:n),o=r%4==0&&Je?new Uint32Array(a.buffer,0,i*r>>2):null,s=r>>2;for(let t=0;t<i;t+=512){let n=Math.min(i,t+512);if(o)for(let a=0;a<r;a+=4){let r=a*i,c=r+i,l=c+i,u=l+i;for(let i=t,d=t*s+(a>>2);i<n;i++,d+=s)o[d]=e[r+i]|e[c+i]<<8|e[l+i]<<16|e[u+i]<<24}else for(let o=0;o<r;o++){let s=o*i;for(let i=t,c=t*r+o;i<n;i++,c+=r)a[c]=e[s+i]}}let c=i*t;return r===t&&a.set(e.subarray(c,n),c),a}function Xe(e,t,n){if(!(n<t)||e.length===0)return t;let r=Math.min(t,n+3&-4);return r===t?t:e.every(e=>e.zip?.type===1&&e.zip.param===t&&e.zip.orgLength%t===0)?r:t}async function Ze(e,t,n=1/0,r=1/0){let i=await e.slice(t.offset,t.length),{type:a,param:o,orgLength:s}=t.zip;if(a===0)return W(i,s,r);let c=Math.min(n,o);return Ye(await W(i,s,c<o?s/o*c:1/0),o,s,c)}async function*Qe(e,t,n,r=1/0){let i=e=>!!e?.zip&&!(e.zip.type===0&&(e.length>16777216||e.zip.orgLength>268435456)),a=null;for(let o=0;o<t.length;o++){let s=t[o];if(n?.throwIfAborted(),!s.zip)for await(let t of e.windows(s.offset,s.length))yield t.bytes;else if(i(s)){let n=a??Ze(e,s,r);a=i(t[o+1])?Ze(e,t[o+1],r):null,a?.catch(()=>{}),yield await n}else{let t=s.zip.orgLength;for await(let n of qe((async function*(){for await(let t of e.windows(s.offset,s.length))yield t.bytes})()))if(yield n.length>t?n.subarray(0,t):n,(t-=n.length)<=0)break}}}async function*$e(e,t,n,r){if(r<=0||t<=0)return;let i=Math.min(n,r),a=null,o=0,s=0;for await(let n of e){let e=0;for(;e<n.length&&s<r;){if(o===0){let a=Math.min(i,r-s,Math.floor((n.length-e)/t));if(a>0){yield{buf:n.subarray(e,e+a*t),n:a},s+=a,e+=a*t;continue}}a??=new Uint8Array(t*i);let c=Math.min(a.length,(r-s)*t),l=Math.min(n.length-e,c-o);if(a.set(n.subarray(e,e+l),o),o+=l,e+=l,o===c){let e=o/t;yield{buf:a,n:e},s+=e,o=0}}if(s>=r)return}a&&o>=t&&(yield{buf:a,n:Math.floor(o/t)})}async function et(e,t,n,r){let i=n*r,a=0;for(let n of t){let t=n.zip?n.zip.orgLength:n.length;if(i<a)return null;if(i+r<=a+t)return n.zip?null:e.read(n.offset+i-a,r);a+=t}return null}const tt=(e,t)=>(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0;var nt=class{#e;#t;#n;#r;#i=new Uint8Array;#a=0;#o;#s=0;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n,this.#r=Qe(e,t,n),this.#o=t.reduce((e,t)=>e+(t.zip?t.zip.orgLength:t.length),0)}peek(e){let t=e-this.#a;if(t<0||t+4>this.#i.length)return null;let n=tt(this.#i,t);return t+4+n>this.#i.length?null:this.#i.subarray(t+4,t+4+n)}async get(e){for(;;){let t=this.peek(e);if(t)return t;let n=e-this.#a;if(e+4>this.#o||n>=0&&n+4<=this.#i.length&&e+4+tt(this.#i,n)>this.#o)throw Error(`This MF4 is damaged (string data ends early).`);e<this.#a&&(this.#r=Qe(this.#e,this.#t,this.#n),this.#i=new Uint8Array,this.#a=0);let r=await this.#r.next();if(r.done)throw Error(`This MF4 is damaged (string data ends early).`);if((this.#s+=r.value.length)>4*this.#o+16777216)throw Error(`This MF4 is damaged (its string offsets jump back and forth).`);let i=Math.max(0,Math.min(e-this.#a,this.#i.length)),a=this.#i.subarray(i),o=new Uint8Array(a.length+r.value.length);o.set(a),o.set(r.value,a.length),this.#a+=i,this.#i=o}}};const rt=e=>Math.max(1,Math.min(65536,Math.floor((8<<20)/Math.max(1,e))));var it=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t){this.#e=e,this.#t=t}want(e){this.#r.has(e)||this.#r.set(e,new Map)}wanted(e){return this.#r.has(e)}put(e,t,n){this.#r.get(e).set(t,n)}async bytes(e,t){let n=Array(t.length);if(e.sdRecordId!==null){let r=this.#r.get(e.sdRecordId);for(let e=0;e<t.length;e++)n[e]=r?.get(t[e])??null,r?.delete(t[e]);return n}if(!e.sd)return n.fill(null);let r=this.#n.get(e);r||this.#n.set(e,r=new nt(this.#e,e.sd,this.#t));for(let e=0;e<t.length;e++)n[e]=r.peek(t[e])??await r.get(t[e]);return n}async strings(e,t){let n=ue(e.encoding);return(await this.bytes(e,t)).map(e=>e?de(n.decode(e)):null)}};function at(e,t,n,r,i=F(e),a=new Float64Array(n)){let o=e.master;if(!o)return null;if(o.kind===`vmaster`)for(let e=0;e<n;e++)a[e]=r+e;else P(o,t,n,i,e.recordIdSize,a);return _(o.conv,a),a}function ot(e,t,n){return n===1?e[t]:n===2?e[t]|e[t+1]<<8:n===4?(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0:((e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0)+4294967296*((e[t+4]|e[t+5]<<8|e[t+6]<<16|e[t+7]<<24)>>>0)}function st(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async function*ct(e,t,n,r,i,a=1/0){let o=t.groups[n[0]];if(o.sorted){let t=Xe(o.stream,F(o),a),r=0;for await(let{buf:a,n:s}of $e(Qe(e,o.stream,i,t),t,rt(t),o.cycles))yield{g:n[0],buf:a,n:s,start:r,size:t},r+=s;return}let s=t.groups.map((e,t)=>({g:e,k:t})).filter(({g:e})=>e.dg===o.dg),c=o.recordIdSize,l=new Map;for(let e of n){let n=t.groups[e],r=F(n);l.set(n.recordId,{k:e,size:r,buf:new Uint8Array(r*Math.min(rt(r),Math.max(1,n.cycles))),fill:0,start:0})}let u=new Map(s.map(({g:e})=>[e.recordId,e.vlsdCg?-1:F(e)])),d=new Map,f=new Uint8Array;for await(let t of Qe(e,o.stream,i)){let e=f.length?st(f,t):t,n=0;for(;!(n+c>e.length);){let t=ot(e,n,c),i=u.get(t);if(i===void 0)throw Error(`This MF4 is damaged (unknown record id ${t}).`);if(i<0){if(n+c+4>e.length)break;let i=(e[n+c]|e[n+c+1]<<8|e[n+c+2]<<16|e[n+c+3]<<24)>>>0;if(i>67108864)throw Error(`This MF4 is damaged (a string record of ${i} bytes).`);let a=n+c+4+i;if(a>e.length)break;let o=d.get(t)??0;r.wanted(t)&&r.put(t,o,e.slice(n+c+4,a)),d.set(t,o+4+i),n=a;continue}if(n+i>e.length)break;let a=l.get(t);if(a&&(a.buf.set(e.subarray(n,n+i),a.fill),a.fill+=i,a.fill===a.buf.length)){let e=a.fill/a.size;yield{g:a.k,buf:a.buf,n:e,start:a.start,size:a.size},a.start+=e,a.fill=0}n+=i}f=e.slice(n)}for(let e of l.values())e.fill&&(yield{g:e.k,buf:e.buf,n:e.fill/e.size,start:e.start,size:e.size})}const lt=(e,t)=>t?e+2147483648:e,ut=/^BO_\s+(\d+)\s+(\w+)\s*:\s*(\d+)/,dt=/^SG_\s+(\w+)\s*(?:(M|m\d+M?)\s*)?:\s*(\d+)\|(\d+)@([01])([+-])\s*\(([^,)]*),([^)]*)\)\s*\[[^\]]*\]\s*"([^"]*)"/,ft=/^VAL_\s+(\d+)\s+(\w+)\s+(.*);/,pt=/^SIG_VALTYPE_\s+(\d+)\s+(\w+)\s*:\s*([12])\s*;/,mt=/^-?\d+(?:\.\d+)?$/;function ht(e){let t=e.split(`"`),n=new Map;for(let e=0;e+1<t.length;e+=2){let r=t[e].trim();mt.test(r)&&n.set(Number(r),t[e+1])}return n}const gt=(e,t)=>e<=511&&t>=1&&t<=64;function _t(e){let t=new Map,n=new Map,r=new Map,i=(e,t)=>{let i=n.get(Number(e));return i?r.get(i)?.get(t):void 0},a=null;for(let o of e.split(/\r?\n/)){let e=o.trim(),s;if(s=ut.exec(e)){let e=Number(s[1]),r=e>=2147483648,i=r?e-2147483648:e;a={id:i,extended:r,name:s[2],size:Number(s[3]),signals:[]},t.set(lt(i,r),a),n.set(e,a)}else if((s=dt.exec(e))&&a){let e=s[2],t=Number(s[3]),n=Number(s[4]);if(!gt(t,n)||!s[7].trim()||!s[8].trim())continue;let i={name:s[1],start:t,length:n,littleEndian:s[5]===`1`,signed:s[6]===`-`,factor:Number(s[7]),offset:Number(s[8]),unit:s[9],mux:e?e===`M`?`switch`:parseInt(e.slice(1),10):null,float:0,values:null};a.signals.push(i);let o=r.get(a);o||r.set(a,o=new Map),o.has(i.name)||o.set(i.name,i)}else if(s=ft.exec(e)){let e=i(s[1],s[2]);e&&(e.values=ht(s[3]))}else if(s=pt.exec(e)){let e=i(s[1],s[2]);e&&(e.float=s[3]===`1`?32:64)}else (e.startsWith(`BO_`)||e===``)&&e===``&&(a=null)}return t}function vt(e){if(e.float){let t=e.float/8,n=e.start>>3,r=e.littleEndian,i=new DataView(new ArrayBuffer(8));return(e,a)=>{for(let r=0;r<t;r++)i.setUint8(r,e[a+n+r]??0);return t===4?i.getFloat32(0,r):i.getFloat64(0,r)}}let t=e.length,n=2**t,r=n/2,i=e.signed;if(e.littleEndian){let a=e.start>>3,o=e.start&7;if(o+t<=32){let e=t===32?-1:(1<<t)-1;return(t,s)=>{let c=s+a,l=((t[c]|t[c+1]<<8|t[c+2]<<16|t[c+3]<<24)>>>o&e)>>>0;return i&&l>=r?l-n:l}}let s=o+t+7>>3,c=2**(t-(32-o)),l=2**(32-o);return(e,t)=>{let u=t+a,d=(e[u]|e[u+1]<<8|e[u+2]<<16|e[u+3]<<24)>>>o,f=0;for(let t=s-1;t>=4;t--)f=f*256+(e[u+t]??0);let p=d+f%c*l;return i&&p>=r?p-n:p}}let a=e.start>>3,o=e.start&7;if(7-o+t<=32){let e=32-(7-o)-t,s=t===32?-1:(1<<t)-1;return(t,o)=>{let c=o+a,l=((t[c]<<24|t[c+1]<<16|t[c+2]<<8|t[c+3])>>>e&s)>>>0;return i&&l>=r?l-n:l}}let s=(1<<o+1)-1,c=t-(o+1)>>3,l=t-(o+1)&7,u=2**l;return(e,t)=>{let o=(e[t+a]??0)&s,d=t+a+1;for(let t=0;t<c;t++)o=o*256+(e[d++]??0);return l>0&&(o=o*u+((e[d]??0)>>8-l)),i&&o>=r?o-n:o}}function yt(e){let t=e.length,n=2**t,r=n/2,i=e.signed,a=t===32?-1:(1<<t)-1;if(!e.float&&e.littleEndian&&(e.start&7)+t<=32){let t=e.start>>3,o=e.start&7;return(e,s,c,l,u,d,f)=>{for(let p=0;p<l;p++){let l=s[c[p]]+t,m=((e[l]|e[l+1]<<8|e[l+2]<<16|e[l+3]<<24)>>>o&a)>>>0;u[p]=(i&&m>=r?m-n:m)*d+f}}}if(!e.float&&!e.littleEndian&&7-(e.start&7)+t<=32){let o=e.start>>3,s=32-(7-(e.start&7))-t;return(e,t,c,l,u,d,f)=>{for(let p=0;p<l;p++){let l=t[c[p]]+o,m=((e[l]<<24|e[l+1]<<16|e[l+2]<<8|e[l+3])>>>s&a)>>>0;u[p]=(i&&m>=r?m-n:m)*d+f}}}let o=vt(e);return(e,t,n,r,i,a,s)=>{for(let c=0;c<r;c++)i[c]=o(e,t[n[c]])*a+s}}function bt(e){if(!e.busEvent||e.busType!==2)return null;let t=t=>e.channels.find(e=>e.name.endsWith(t))??null,n=t(`DataFrame.ID`),r=t(`DataFrame.DataBytes`);return!n||!r?null:{id:n,ide:t(`DataFrame.IDE`),data:r}}const xt=()=>({n:0,time:new Float64Array,key:new Float64Array,id:new Float64Array,ide:new Float64Array,bytes:null,buf:new Uint8Array,dataAt:new Int32Array});async function St(e,t,n,r,i,a,o,s){s.key.length<r&&Object.assign(s,{time:new Float64Array(r),key:new Float64Array(r),id:new Float64Array(r),ide:new Float64Array(r),dataAt:new Int32Array(r)});let c=e.recordIdSize,{id:l,ide:u,key:d,dataAt:f}=s;P(t.id,n,r,a,c,l),t.ide&&P(t.ide,n,r,a,c,u);for(let e=0;e<r;e++){let n=l[e],r=n&536870911;d[e]=lt(r,t.ide?u[e]!==0:n>=2147483648||r>2047)}if(s.bytes=null,t.data.kind===`vlsd`){let e=new Float64Array(r);P({...t.data,type:`uint`},n,r,a,c,e),s.bytes=await o.bytes(t.data,e)}else for(let e=0,n=c+t.data.byteOffset;e<r;e++,n+=a)f[e]=n;if(!at(e,n,r,i,a,s.time.subarray(0,r)))for(let e=0;e<r;e++)s.time[e]=i+e;return s.n=r,s.buf=n,s}const Ct=new Uint8Array;function wt(e){return e.float?(e.start>>3)+e.float/8:e.littleEndian?(e.start>>3)+((e.start&7)+e.length+7>>3):(e.start>>3)+1+(Math.max(0,e.length-((e.start&7)+1))+7>>3)}function Tt(e,t,n){let r=0;for(let e of n.values())for(let t of e.signals)r=Math.max(r,wt(t));let i=t.data.kind===`vlsd`?t.data:{...t.data,bitCount:Math.min(t.data.bitCount,r*8)};return ye(e,t.ide?[t.id,t.ide,i]:[t.id,i])}function Et(e,t){let n=t.map(t=>e.signals[e.channels[t].s]);return{route:e,col:n.map(yt),read:n.map(vt),factor:n.map(e=>e.factor),offset:n.map(e=>e.offset),table:t.map((t,r)=>e.channels[t].text?n[r].values:null),idx:new Int32Array,cnt:0,n:0,t0:NaN,t1:NaN}}function Dt(e,t,n,r,i,a=1,o=0){let s=new Float64Array(i);if(n.bytes)for(let e=0;e<i;e++)s[e]=t(n.bytes[r[e]]??Ct,0)*a+o;else e(n.buf,n.dataAt,r,i,s,a,o);return s}function Ot(e,t){let{idx:n,cnt:r}=e,i=new Float64Array(r);for(let e=0;e<r;e++)i[e]=t.time[n[e]];return e.n===0&&(e.t0=i[0]),e.t1=i[r-1],e.n+=r,e.cnt=0,{time:i,cols:e.col.map((i,a)=>{let o=e.table[a];return o?Array.from(Dt(i,e.read[a],t,n,r),e=>o.get(e)??null):Dt(i,e.read[a],t,n,r,e.factor[a],e.offset[a])})}}const kt=e=>({key:e,skip:!0,frames:0,all:null,sw:null,byMux:new Map,idx:new Int32Array,cnt:0});function At(e,t){let n=e.signals.find(e=>e.mux===`switch`);return{key:lt(e.id,e.extended),skip:!1,frames:0,all:t,sw:n?{col:yt(n),read:vt(n)}:null,byMux:new Map,idx:new Int32Array,cnt:0}}var jt=class{#e=Array(2048);#t=new Map;#n;constructor(e){this.#n=e}get(e){let t=e<2048?this.#e[e]:this.#t.get(e);return t||(t=this.#n(e),e<2048?this.#e[e]=t:this.#t.set(e,t)),t}};function Mt(e,t,n){let r=[];for(let n=0;n<e.n;n++){let i=t.get(e.key[n]);if(i.skip){i.frames++;continue}i.cnt===0&&(r.push(i),i.idx.length<e.n&&(i.idx=new Int32Array(e.n))),i.idx[i.cnt++]=n}let i=[];for(let t of r){if(t.all&&(t.all.idx=t.idx,t.all.cnt=t.cnt,i.push(t.all)),t.sw){let r=Dt(t.sw.col,t.sw.read,e,t.idx,t.cnt);for(let e=0;e<t.cnt;e++){let a=t.byMux.get(r[e]);a===void 0&&((a=n(t,r[e]))||t.byMux.size<4096)&&t.byMux.set(r[e],a),a&&(a.cnt===0&&(i.push(a),a.idx.length<t.cnt&&(a.idx=new Int32Array(t.cnt))),a.idx[a.cnt++]=t.idx[e])}}t.cnt=0}return i}async function Nt(e,t,n,r){let i=new Map;if(t.groups.forEach((e,t)=>{let n=bt(e);n&&e.cycles>0&&i.set(t,n)}),i.size===0)return null;if(n.length===0)return{dbc:new Map,layouts:i,routes:[],notes:[],cache:new Map};let a=_t(u(new Uint8Array(await n[0].arrayBuffer()))),o=[],s=new Map,c=new Map,l=0,d=new it(e,r);for(let[n,u]of i){let i=t.groups[n],f=(e,t)=>{let n=e.signals.filter(e=>t===null?typeof e.mux!=`number`:e.mux===t),r=[];return n.forEach((e,t)=>{r.push({s:t,text:!1}),e.values&&r.push({s:t,text:!0})}),Et({key:lt(e.id,e.extended),mux:t,signals:n,channels:r},r.map((e,t)=>t))},p=new jt(e=>{let t=a.get(e);if(!t){let t=kt(e);return s.set(e,t),t}let r=At(t,f(t,null));return o.push({model:n,m:r}),r});u.data.sdRecordId!==null&&d.want(u.data.sdRecordId);let m=xt();for await(let o of ct(e,t,[n],d,r,Tt(i,u,a))){let e=await St(i,u,o.buf,o.n,o.start,o.size,d,m),t=(e,t)=>{let n=a.get(e.key);return n.signals.some(e=>e.mux===t)?f(n,t):null};for(let n of Mt(e,p,t)){let t=Ot(n,e);if(l<0)continue;if((l+=t.time.length*(1+t.cols.length))>48e6){l=-1,c.clear();continue}let r=c.get(n);r||c.set(n,r=[]),r.push(t)}}}let f=[],p=new Map;for(let{model:e,m:t}of o)for(let n of[t.all,...t.byMux.values()]){if(!n)continue;let{route:t,n:r,t0:i,t1:o}=n;if(t.signals.length===0)continue;let s=a.get(t.key);l>=0&&p.set(t,c.get(n)??[]),f.push({model:e,route:t,group:{name:t.mux===null?s.name:`${s.name} [m=${t.mux}]`,channels:t.channels.map(e=>({name:e.text?`${t.signals[e.s].name} (text)`:t.signals[e.s].name,unit:e.text?``:t.signals[e.s].unit,text:e.text})),samples:r,time:{kind:`timestamps`},rateHz:r>1&&o>i?Math.round((r-1)/(o-i)*1e6)/1e6:null}})}let m=[];if(s.size){let e=[...s.values()].reduce((e,t)=>e+t.frames,0),t=[...s.keys()].map(e=>`0x${(e%2147483648).toString(16).toUpperCase()}`).join(`, `);m.push(`${e} frame${e===1?``:`s`} with ${s.size} id${s.size===1?``:`s`} not in the DBC ${e===1?`was`:`were`} skipped (${t}).`)}return{dbc:a,layouts:i,routes:f,notes:m,cache:p}}async function*Pt(e,t,n,r,i,a){let o=[];for(let e of i){let t=r.cache.get(e.route);if(!t){o.push(e);continue}r.cache.delete(e.route);let n=0;for(let r of t)yield{group:e.group,start:n,length:r.time.length,time:r.time,columns:e.sel.map(e=>r.cols[e])},n+=r.time.length}if(!o.length)return;let s=r.layouts.get(n),c=t.groups[n],l=new Map,u=new Map;for(let e of o){let t=Et(e.route,e.sel);l.set(t,e.group);let n=u.get(e.route.key);n||u.set(e.route.key,n={all:null,byMux:new Map}),e.route.mux===null?n.all=t:n.byMux.set(e.route.mux,t)}let d=new jt(e=>{let t=u.get(e);if(!t)return kt(e);let n=At(r.dbc.get(e),t.all);return t.byMux.size||(n.sw=null),n}),f=new it(e,a);s.data.sdRecordId!==null&&f.want(s.data.sdRecordId);let p=xt();for await(let i of ct(e,t,[n],f,a,Tt(c,s,r.dbc))){let e=await St(c,s,i.buf,i.n,i.start,i.size,f,p);for(let t of Mt(e,d,(e,t)=>u.get(e.key).byMux.get(t)??null)){let n=t.n,r=Ot(t,e);yield{group:l.get(t),start:n,length:r.time.length,time:r.time,columns:r.cols}}}}const Ft=e=>Math.round(e*1e6)/1e6,It=e=>e.kind===`value`?e.type!==`bytes`:e.kind===`vlsd`&&e.type===`string`,Lt=e=>({name:e.name,unit:e.unit,text:e.type===`string`||e.kind===`vlsd`||e.conv.k===`text`});async function Rt(e,t){let n=t.master;if(!n||t.cycles<2)return null;if(n.kind===`vmaster`)return n.conv.k===`lin`&&n.conv.a>0?Ft(1/n.conv.a):null;if(!t.sorted)return null;let r=F(t),i=t.cycles,a,o;if(t.stream[0]?.zip){let n=Xe(t.stream.slice(0,1),r,ye(t,[])),s=await Ze(e,t.stream[0],n,4096*r);if(i=Math.min(t.cycles,Math.floor(s.length/n)),i<2)return null;a=s.subarray(0,n),o=s.subarray((i-1)*n,i*n)}else a=await et(e,t.stream,0,r),o=await et(e,t.stream,t.cycles-1,r);if(!a||!o)return null;let s=new Float64Array(2);return P(n,a,1,r,t.recordIdSize,s,0),P(n,o,1,r,t.recordIdSize,s,1),_(n.conv,s),s[1]>s[0]?Ft((i-1)/(s[1]-s[0])):null}async function zt(e,t,n,r,i,a,o){let s;if(e.kind===`vlsd`){let a=new Float64Array(n);P({...e,type:`uint`},t,n,r,i,a),s=await o.strings(e,a)}else if(e.type===`string`)s=fe(e,t,n,r,i);else{let a=new Float64Array(n);P(e,t,n,r,i,a),e.conv.k===`text`?s=b(e.conv,a):(_(e.conv,a),s=a)}return pe(e,t,n,r,a,s),s}async function Bt(e,t,n,r,i,a,o,s){let c=e.recordIdSize,l=[];for(let i of t)l.push(await zt(e.channels[i],n,r,a,c,c+e.dataBytes,s));return{group:o,time:at(e,n,r,i,a),start:i,length:r,columns:l}}async function*Vt(e,t){let n=e.plan.state,r=t.filter(e=>n.groups[e].route),i=t.filter(e=>!n.groups[e].route);if(r.length){let t=r.map(t=>({group:t,route:n.groups[t].route,sel:f(e,t)}));yield*Pt(e.io,n.model,n.groups[r[0]].model,n.bus,t,e.signal)}if(!i.length)return;let a=new it(e.io,e.signal),o=new Map;for(let t of i){let r=n.groups[t],i=f(e,t).map(e=>r.channels[e]);for(let e of i){let t=n.model.groups[r.model].channels[e].sdRecordId;t!==null&&a.want(t)}o.set(r.model,{pg:t,cols:i})}let[s,{cols:c}]=o.entries().next().value,l=n.model.groups[s],u=o.size===1?ye(l,c.map(e=>l.channels[e])):1/0;for await(let t of ct(e.io,n.model,[...o.keys()],a,e.signal,u)){let{pg:e,cols:r}=o.get(t.g);yield await Bt(n.model.groups[t.g],r,t.buf,t.n,t.start,t.size,e,a)}}function Ht(e){let t=e.plan.state,n=new Map;for(let r of e.selection){let e=t.model.groups[t.groups[r.group].model].dg;n.set(e,[...n.get(e)??[],r.group])}return[...n].sort((e,t)=>e[0]-t[0]).map(([,e])=>e)}const Ut={...me,async plan(e,t){let n=await t.read(0,64);if(d(n,`UnFinMF`))throw Error(`This MF4 was not finalized by its logger (it starts with UnFinMF). Finalize it with the logger software or asammdf, then open it again.`);let r=l(n.subarray(8,16)).replace(/\0/g,``).trim(),i=Number(r.replace(`.`,``).slice(0,3))>=400?await N(t,r):await S(t,n,r);ve(i,t.size);let a=await Nt(t,i,e.companions.filter(e=>e.name.toLowerCase().endsWith(`.dbc`))),o=new Set(a?.layouts.keys()??[]),s=[],c=[],u=[...i.notes],f=0;for(let e=0;e<i.groups.length;e++){let n=i.groups[e];if(n.vlsdCg||n.cycles===0||o.has(e))continue;let r=[];if(n.channels.forEach((e,t)=>{It(e)?r.push(t):f++}),r.length!==0){for(let e of r){let t=n.channels[e].conv;t.k===`unsupported`&&u.push(`${n.channels[e].name}: ${t.what} is not supported; raw values are shown.`)}c.push({model:e,channels:r}),s.push({name:n.name,channels:r.map(e=>Lt(n.channels[e])),samples:n.cycles,time:n.master?{kind:`timestamps`}:{kind:`index`},rateHz:await Rt(t,n)})}}if(f&&u.push(`${f} byte-array channel${f===1?` was`:`s were`} skipped.`),a){if(a.routes.length===0&&a.dbc.size===0){if(s.length===0)throw Error(`This MF4 has raw CAN frames. Drop its .dbc file together with it to decode signals.`);u.push(`This MF4 also has raw CAN frames. Drop its .dbc file together with it to decode signals.`)}for(let e of a.routes)c.push({model:e.model,route:e.route}),s.push(e.group);u.push(...a.notes)}if(s.length===0)throw Error(`This MDF file has no channels with samples.`);let p={model:i,groups:c,bus:a};return{format:i.version,startTime:i.startTime,groups:s,meta:i.meta,events:[],notes:u,interleaved:!!a?.routes.length||i.groups.some(e=>!e.sorted&&!e.vlsdCg),state:p}},async*stream(e){for(let t of Ht(e))yield*Vt(e,t)},streamGroup(e,t){return Vt(e,[t])}},Wt={id:`edf`,label:`EDF / BDF (+)`,extensions:[`.edf`,`.bdf`,`.rec`],sniff:e=>d(e,`0 `)||e[0]===255&&d(e,`BIOSEMI`,1)};function Gt(e){let t=[];for(let n of u(e).split(`\0`)){if(!n)continue;let e=n.split(``),r=parseFloat(e[0].split(``)[0]);Number.isFinite(r)&&t.push({onset:r,texts:e.slice(1).filter(e=>e.length>0)})}return t}function Kt(e,t){let n=/^(\d\d)\.(\d\d)\.(\d\d)$/.exec(e),r=/^(\d\d)\.(\d\d)\.(\d\d)$/.exec(t);if(!n||!r)return null;let i=Number(n[3]);return`${i>=85?1900+i:2e3+i}-${n[2]}-${n[1]}T${r[1]}:${r[2]}:${r[3]}`}const qt=e=>`${+e.toFixed(6)} Hz`;function Jt(e,t,n,r,i,a,o,s){let{bit:c,off:l}=e;if(a===2)for(let e=0;e<i;e++)o[s+e]=c*(l+t.getInt16(r+2*e,!0));else for(let e=0,t=r;e<i;e++,t+=3)o[s+e]=c*(l+((n[t]|n[t+1]<<8|n[t+2]<<16)<<8>>8))}const Yt={...Wt,async plan(e,t){let n=await t.read(0,256),r=(e,t)=>l(n.subarray(e,e+t)).trim(),i=n[0]===255,a=parseInt(r(252,4),10),o=parseInt(r(184,8),10),s=r(192,44),c=/^(EDF|BDF)\+/.test(s),u=/^(EDF|BDF)\+D/.test(s),d=parseFloat(r(244,8));if(!(a>0)||o!==256*(a+1)||!(d>0))throw Error(`This EDF/BDF header is damaged.`);let f=await t.read(256,a*256),p=(e,t,n)=>l(f.subarray(e*a+t*n,e*a+t*(n+1))).trim(),m=i?3:2,h=[],g=0;for(let e=0;e<a;e++){let t=parseFloat(p(104,8,e)),n=parseFloat(p(112,8,e)),r=parseFloat(p(120,8,e)),i=parseFloat(p(128,8,e)),a=Number(p(216,8,e));if(!(Number.isInteger(a)&&a>=0))throw Error(`This EDF/BDF header is damaged (samples per record).`);let o=(n-t)/(i-r);h.push({label:p(0,16,e),unit:p(96,8,e),spr:a,offset:g,bit:o,off:n/o-i}),g+=a*m}let _=g;if(!(_>0&&o+_<=t.size))throw Error(`This EDF/BDF file is damaged (its data records do not fit in it).`);let v=Math.floor((t.size-o)/_),y=parseInt(r(236,8),10),b=[];y>=0?y>v&&(b.push(`The file is shorter than its header says: ${v} of ${y} data records were read.`),y=v):y=v;let x=c?h.flatMap((e,t)=>/^(EDF|BDF) Annotations$/.test(e.label)?[t]:[]):[],S=new Map;h.forEach((e,t)=>{!x.includes(t)&&e.spr>0&&S.set(e.spr,[...S.get(e.spr)??[],t])});let C=[...S.values()],w=C.map(e=>{let t=h[e[0]].spr/d;return{name:qt(t),channels:e.map(e=>({name:h[e].label,unit:h[e].unit})),samples:y*h[e[0]].spr,rateHz:t,time:u?{kind:`timestamps`}:{kind:`rate`,rate:t,start:0}}}),T={headerBytes:o,records:y,duration:d,recordBytes:_,bps:m,signals:h,groups:C,annotations:x,discontinuous:u};return{format:`${i?`BDF`:`EDF`}${c?u?`+D`:`+`:``}`,startTime:Kt(r(168,8),r(176,8)),groups:w,meta:{patient:r(8,80),recording:r(88,80)},events:[],notes:u?[`Discontinuous recording: each gap shows as a break in the traces.`,...b]:b,state:T}},async*stream(e){let n=e.plan.state,i=Math.max(1,Math.floor(t/n.recordBytes)),a=e.selection.map(e=>({g:e.group,chans:e.channels.map(t=>n.signals[n.groups[e.group][t]]),spr:n.signals[n.groups[e.group][0]].spr})),o=a.map(()=>0),s=0,c=NaN;for await(let t of e.io.windows(n.headerBytes,n.records*n.recordBytes,i*n.recordBytes)){e.signal?.throwIfAborted();let i=Math.floor(t.bytes.length/n.recordBytes);if(i===0)break;let l=r(t.bytes),u=new Float64Array(i),d=[];for(let e=0;e<i;e++)u[e]=(s+e)*n.duration,n.annotations.forEach((r,i)=>{let a=n.signals[r],o=e*n.recordBytes+a.offset,s=Gt(t.bytes.subarray(o,o+a.spr*n.bps));i===0&&s.length&&(u[e]=s[0].onset);for(let e of s)for(let t of e.texts)d.push({time:e.onset,text:t})});let f=new Uint8Array(i),p=0;if(n.discontinuous)for(let e=0;e<i;e++){let t=e?u[e-1]+n.duration:c;t===t&&u[e]>t+1e-9&&(f[e]=1,p++)}for(let e=0;e<a.length;e++){let r=a[e],s=r.spr/n.duration,m=i*r.spr+p,h=n.discontinuous?new Float64Array(m):null,g=r.chans.map(()=>new Float64Array(m)),_=0;for(let e=0;e<i;e++){if(f[e]){h[_]=e?u[e-1]+n.duration:c;for(let e of g)e[_]=NaN;_++}if(h)for(let t=0;t<r.spr;t++)h[_+t]=u[e]+t/s;let i=e*n.recordBytes;r.chans.forEach((e,a)=>Jt(e,l,t.bytes,i+e.offset,r.spr,n.bps,g[a],_)),_+=r.spr}let v={group:r.g,time:h,start:o[e],length:m,columns:g};e===0&&d.length&&(v.events=d),o[e]+=m,yield v}c=u[i-1]+n.duration,s+=i}}};function Xt(e,t=[`Time`]){let n=new Set(t.map(e=>e.toLowerCase())),r=new Map;return e.map(e=>{let t=e.trim()||`Channel`,i=t.toLowerCase(),a=t,o=r.get(i)??2;if(n.has(i)){for(;n.has(`${i} (${o})`);)o++;a=`${t} (${o++})`}return r.set(i,o),n.add(a.toLowerCase()),a})}const Zt={id:`xdf`,label:`XDF (Lab Streaming Layer)`,extensions:[`.xdf`],sniff:e=>d(e,`XDF:`)},Qt={float32:4,double64:8,int8:1,int16:2,int32:4,int64:8};function G(e,t,n=0){let r=e.indexOf(`<${t}>`,n);if(r<0)return``;let i=e.indexOf(`</${t}>`,r);return i<0?``:e.slice(r+t.length+2,i).trim()}function $t(e,t){let n=[];for(let r=e.indexOf(`<${t}>`);r>=0;){let i=e.indexOf(`</${t}>`,r);if(i<0)break;n.push(e.slice(r,i+t.length+3)),r=e.indexOf(`<${t}>`,i)}return n}const en=e=>e.fmt===`string`||Qt[e.fmt]!==void 0;function K(e,t,n){let r=e[n];if((r===1||r===4||r===8)&&n+1+r<=e.length)return r===1?[e[n+1],2]:r===4?[t.getUint32(n+1,!0),5]:[i(t,n+1),9];throw Error(`This XDF file is damaged (bad length field).`)}function tn(e,t,n,r){if(n>=e.length)return-1;if(e[n++]===8&&(n+=8),r.fmt!==`string`)return n+Qt[r.fmt]*r.nch<=e.length?n+Qt[r.fmt]*r.nch:-1;for(let i=0;i<r.nch;i++){if(n>=e.length)return-1;let[r,i]=K(e,t,n);n+=i+r}return n<=e.length?n:-1}async function*nn(e,t){let n=new Uint8Array;for await(let i of e.windows(4,e.size-4)){t?.throwIfAborted();let a=i.bytes,o=i.offset-n.length;if(n.length){let e=new Uint8Array(n.length+a.length);e.set(n),e.set(a,n.length),a=e}let s=r(a),c=0;for(;!(c+1>a.length);){let t=a[c];if(c+1+t>a.length)break;let[n,r]=K(a,s,c),i=c+r+n;if(o+i>e.size)return;if(i>a.length)break;yield{tag:a[c+r]|a[c+r+1]<<8,body:a.subarray(c+r+2,i)},c=i}n=a.slice(c)}}function rn(e,t,n){let r=t-e.i0,i=n-e.t0;e.n++,e.si+=r,e.st+=i,e.sii+=r*r,e.sit+=r*i}function an(e){let t=e.n*e.sii-e.si*e.si;e.b=t>0?(e.n*e.sit-e.si*e.st)/t:0,e.a=(e.st-e.b*e.si)/Math.max(1,e.n)}function on(e){if(e.length===0)return[0,0];if(e.length===1)return[e[0][1],0];let t={i0:e[0][0],t0:0,n:0,si:0,st:0,sii:0,sit:0,a:0,b:0};for(let[n,r]of e)rn(t,n,r);return an(t),[t.a-t.b*t.i0,t.b]}function sn(e,t,n){let r=t.t0+t.a+t.b*(n-t.i0);return r+e.c0+e.c1*r}const cn={...Zt,async plan(e,t){let n=new Map,i=``;for await(let e of nn(t)){let t=r(e.body);if(e.tag===1)i=u(e.body);else if(e.tag===2){let r=t.getUint32(0,!0),i=u(e.body.subarray(4)),a=parseInt(G(i,`channel_count`),10)||1;if(!(a>=1&&a<=1e5))throw Error(`This XDF file is damaged (a stream with ${a} channels).`);let o=$t(i,`channel`);n.set(r,{id:r,name:G(i,`name`)||`Stream ${r}`,nch:a,srate:parseFloat(G(i,`nominal_srate`))||0,fmt:G(i,`channel_format`)||`float32`,labels:Array.from({length:a},(e,t)=>G(o[t]??``,`label`)||`Ch${t+1}`),units:Array.from({length:a},(e,t)=>G(o[t]??``,`unit`)),count:0,segs:[],clock:[],c0:0,c1:0,lastTs:NaN})}else if(e.tag===3){let r=n.get(t.getUint32(0,!0));if(!r||!en(r))continue;let[i,a]=K(e.body,t,4),o=4+a,s=Qt[r.fmt],c=r.srate>0?Math.max(1,500/r.srate):1/0;for(let n=0;n<i&&!(tn(e.body,t,o,r)<0);n++){let n;if(e.body[o++]===8?(n=t.getFloat64(o,!0),o+=8):n=r.lastTs+(r.srate>0?1/r.srate:0),r.fmt===`string`)for(let n=0;n<r.nch;n++){let[n,r]=K(e.body,t,o);o+=r+n}else o+=s*r.nch;if(r.srate>0){let e=r.segs[r.segs.length-1];(!e||n-r.lastTs>c)&&r.segs.push(e={i0:r.count,t0:n,n:0,si:0,st:0,sii:0,sit:0,a:0,b:0}),rn(e,r.count,n)}else r.count===0&&r.segs.push({i0:0,t0:n,n:1,si:0,st:0,sii:0,sit:0,a:0,b:0});r.lastTs=n,r.count++}}else if(e.tag===4){let e=n.get(t.getUint32(0,!0));e&&e.clock.push([t.getFloat64(4,!0),t.getFloat64(12,!0)])}}let a=[],o=[...n.values()].sort((e,t)=>e.id-t.id).filter(e=>(en(e)||a.push(`${e.name}: channel format ${e.fmt} is not supported; skipped.`),en(e))),s=1/0;for(let e of o){[e.c0,e.c1]=on(e.clock);for(let t of e.segs)an(t);if(e.count===0)continue;let t=e.srate>0?sn(e,e.segs[0],0):e.segs[0].t0+e.c0+e.c1*e.segs[0].t0;s=Math.min(s,t)}let c=Xt(o.map(e=>e.name),[]),l=o.map((e,t)=>({name:c[t],channels:e.labels.map((t,n)=>({name:t,unit:e.units[n],...e.fmt===`string`?{text:!0,sparse:!0}:{}})),samples:e.count,time:{kind:`timestamps`},rateHz:e.srate>0?e.srate:null,irregular:e.srate===0})),d=G(i,`version`);return{format:`XDF ${d||`1.0`}`,startTime:null,groups:l,meta:{header:d},events:[],notes:a,state:{streams:o,origin:Number.isFinite(s)?s:0}}},async*stream(e){let t=e.plan.state,n=8192,i=new Map,a=e=>e.sel.map(()=>e.s.fmt===`string`?Array(n):new Float64Array(n));for(let r of e.selection){let o=t.streams[r.group],s={g:r.group,s:o,sel:f(e,r.group),time:new Float64Array(n),cols:[],n:0,start:0,seg:0,i:0,raw:NaN};s.cols=a(s),i.set(o.id,s)}let o=e=>{let t={group:e.g,time:e.time.slice(0,e.n),start:e.start,length:e.n,columns:e.cols.map(t=>t.slice(0,e.n))};return e.start+=e.n,e.n=0,e.time=new Float64Array(n),e.cols=a(e),t};for await(let a of nn(e.io,e.signal)){if(a.tag!==3)continue;let e=r(a.body),s=i.get(e.getUint32(0,!0));if(!s)continue;let c=s.s,[l,d]=K(a.body,e,4),f=4+d,p=Qt[c.fmt],m=[];for(let r=0;r<l&&!(tn(a.body,e,f,c)<0);r++){let r;a.body[f++]===8?(r=e.getFloat64(f,!0),f+=8):r=s.raw+(c.srate>0?1/c.srate:0),s.raw=r;let i;if(c.srate>0){for(;s.seg+1<c.segs.length&&c.segs[s.seg+1].i0<=s.i;)s.seg++;i=sn(c,c.segs[s.seg],s.i)}else i=r+c.c0+c.c1*r;if(s.time[s.n]=i-t.origin,c.fmt===`string`){let n=[];for(let t=0;t<c.nch;t++){let[t,r]=K(a.body,e,f);n.push(u(a.body.subarray(f+r,f+r+t))),f+=r+t}s.sel.forEach((e,t)=>{s.cols[t][s.n]=n[e]}),m.push({time:i-t.origin,text:n.join(` `)})}else s.sel.forEach((t,n)=>{let r=f+t*p,i=s.cols[n];switch(c.fmt){case`float32`:i[s.n]=e.getFloat32(r,!0);break;case`double64`:i[s.n]=e.getFloat64(r,!0);break;case`int8`:i[s.n]=e.getInt8(r);break;case`int16`:i[s.n]=e.getInt16(r,!0);break;case`int32`:i[s.n]=e.getInt32(r,!0);break;default:i[s.n]=e.getInt32(r+4,!0)*4294967296+e.getUint32(r,!0)}}),f+=p*c.nch;s.i++,++s.n===n&&(yield o(s))}m.length&&(yield{group:s.g,time:new Float64Array,start:s.start,length:0,columns:s.sel.map(()=>new Float64Array),events:m})}for(let e of i.values())e.n&&(yield o(e))}},ln={id:`tdms`,label:`NI TDMS`,extensions:[`.tdms`],companions:[{ext:`.tdms_index`}],sniff:e=>d(e,`TDSm`)},un=4713,dn=4714,q={1:1,2:2,3:4,4:8,5:1,6:2,7:4,8:8,9:4,10:8,25:4,26:8,33:1,68:16},fn={0:5,1:1,2:6,3:2,4:7,5:3,6:8,7:4,8:9,9:10,4294967295:68},pn=(e,t,n)=>n?a(e,t+8,n)+i(e,t,n)/2**64:a(e,t,n)+i(e,t+8,n)/2**64;function mn(e,t,n,r,o){switch(r){case 32:{let r=e.getUint32(n,o);return[u(t.subarray(n+4,n+4+r)),4+r]}case 1:return[e.getInt8(n),1];case 2:return[e.getInt16(n,o),2];case 3:return[e.getInt32(n,o),4];case 4:return[a(e,n,o),8];case 5:return[e.getUint8(n),1];case 6:return[e.getUint16(n,o),2];case 7:return[e.getUint32(n,o),4];case 8:return[i(e,n,o),8];case 9:case 25:return[e.getFloat32(n,o),4];case 10:case 26:return[e.getFloat64(n,o),8];case 33:return[e.getUint8(n)!==0,1];case 68:return[pn(e,n,o),16];default:throw Error(`This TDMS file has a property of type ${r}, which Kymoscope cannot read.`)}}function hn(e){let t=/^\/'((?:[^']|'')*)'(?:\/'((?:[^']|'')*)')?$/.exec(e);return t?[t[1].replace(/''/g,`'`),(t[2]??``).replace(/''/g,`'`)]:null}const gn=4294967295;function _n(e){if(e.has(`NI_Number_Of_Scales`))return Number(e.get(`NI_Number_Of_Scales`));let t=0;for(let n of e.keys()){let e=/^NI_Scale\[(\d+)\]_Scale_Type$/.exec(n);e&&(t=Math.max(t,Number(e[1])+1))}return t}function vn(e,t,n){let r=e.find(e=>_n(e)>0);if(!r||r.get(`NI_Scaling_Status`)===`scaled`)return null;let i=(e,a)=>{if(e===gn||e<0||a>8)return e=>e;let o=r.get(`NI_Scale[${e}]_Scale_Type`);if(o===void 0)return e=>e;if(o===`Linear`){let t=Number(r.get(`NI_Scale[${e}]_Linear_Slope`)),n=Number(r.get(`NI_Scale[${e}]_Linear_Y_Intercept`)??0),o=i(Number(r.get(`NI_Scale[${e}]_Linear_Input_Source`)??gn),a+1);return o&&(e=>t*o(e)+n)}if(o===`Polynomial`){let o=Number(r.get(`NI_Scale[${e}]_Polynomial_Coefficients_Size`)??4);if(!(Number.isInteger(o)&&o>=0&&o<=64))return t.push(`${n}: an NI polynomial scale with ${o} coefficients is not supported; raw values are shown.`),null;let s=Array.from({length:o},(t,n)=>Number(r.get(`NI_Scale[${e}]_Polynomial_Coefficients[${n}]`))),c=i(Number(r.get(`NI_Scale[${e}]_Polynomial_Input_Source`)??gn),a+1);return c&&(e=>{let t=c(e),n=0;for(let e=o-1;e>=0;e--)n=n*t+s[e];return n})}return t.push(`${n}: NI scale type ${String(o)} is not supported; raw values are shown.`),null};return i(_n(r)-1,0)}const yn={1:Int8Array,2:Int16Array,3:Int32Array,5:Uint8Array,6:Uint16Array,7:Uint32Array,9:Float32Array,10:Float64Array,25:Float32Array,26:Float64Array,33:Uint8Array};function bn(e,t,n,r,o,s,c,l){let u=yn[e];if(u&&s&&r===q[e]&&(t.byteOffset+n)%r===0){c.set(new u(t.buffer,t.byteOffset+n,o),l);return}switch(e){case 1:for(let e=0;e<o;e++,n+=r)c[l+e]=t.getInt8(n);return;case 2:for(let e=0;e<o;e++,n+=r)c[l+e]=t.getInt16(n,s);return;case 3:for(let e=0;e<o;e++,n+=r)c[l+e]=t.getInt32(n,s);return;case 4:for(let e=0;e<o;e++,n+=r)c[l+e]=a(t,n,s);return;case 5:case 33:for(let e=0;e<o;e++,n+=r)c[l+e]=t.getUint8(n);return;case 6:for(let e=0;e<o;e++,n+=r)c[l+e]=t.getUint16(n,s);return;case 7:for(let e=0;e<o;e++,n+=r)c[l+e]=t.getUint32(n,s);return;case 8:for(let e=0;e<o;e++,n+=r)c[l+e]=i(t,n,s);return;case 9:case 25:for(let e=0;e<o;e++,n+=r)c[l+e]=t.getFloat32(n,s);return;case 10:case 26:for(let e=0;e<o;e++,n+=r)c[l+e]=t.getFloat64(n,s);return;case 68:for(let e=0;e<o;e++,n+=r)c[l+e]=pn(t,n,s);return;default:c.fill(NaN,l,l+o)}}async function xn(e,t,n){let a=new Map,o=[],s=[],c=new Map,l=new Map,d=t??e,f=0,p=0;for(;f+28<=e.size&&p+28<=d.size;){let m=t?p:f,h=await d.read(m,28),g=r(h);if(!(h[0]===84&&h[1]===68&&h[2]===83&&(h[3]===109||h[3]===104)))throw Error(`This TDMS file is damaged (no segment lead-in where one should be).`);let _=g.getUint32(4,!0),v=!(_&64),y=i(g,12,v),b=i(g,20,v),x=y>=2**53?e.size:Math.min(e.size,f+28+y);if(b>x-f-28)throw Error(`This TDMS file is damaged (segment metadata longer than its segment).`);if(_&2){let e=await d.read(m+28,b),t=r(e);_&4&&(s=[],c=new Map);let o=0,f=t.getUint32(o,v);o+=4;for(let r=0;r<f;r++){let r=t.getUint32(o,v),d=u(e.subarray(o+4,o+4+r));o+=4+r;let f=hn(d),p=a.get(d);p||a.set(d,p={path:d,group:f?.[0]??``,name:f?.[1]??``,type:0,props:new Map,pieces:[],total:0});let m=t.getUint32(o,v);o+=4;let h=null;if(m===4294967295)h=null;else if(m===0)h=l.get(p)??null;else if(m===un||m===dn){let e=i(t,o+8,v),r=t.getUint32(o+16,v),a=m===un?20:17,s=o+20,c=fn[t.getUint32(s,v)]??0,l=t.getUint32(s+8,v);o=s+r*a;let u=t.getUint32(o,v);o+=4;let d=0;for(let e=0;e<u;e++)d+=t.getUint32(o+4*e,v);o+=4*u,m===dn?n.push(`${p.name}: DAQmx digital line data is not supported; skipped.`):(r>1&&n.push(`${p.name}: only the first of its ${r} DAQmx scalers is read.`),h={type:c,count:e,bytes:0,daqmx:{byteOffset:l,stride:d}})}else{let e=t.getUint32(o,v),n=i(t,o+8,v),r=e===32?i(t,o+16,v):n*(q[e]??0);o+=m-4,h={type:e,count:n,bytes:r,daqmx:null}}h&&(p.type=h.type,l.set(p,h));let g=t.getUint32(o,v);o+=4;for(let n=0;n<g;n++){let n=t.getUint32(o,v),r=u(e.subarray(o+4,o+4+n));o+=4+n;let i=t.getUint32(o,v);o+=4;let[a,s]=mn(t,e,o,i,v);p.props.set(r,a),o+=s}let _=c.get(p);_===void 0?c.set(p,s.push({obj:p,idx:h})-1):s[_].idx=h}}if(_&8){let e=f+28+b,t=s.filter(e=>e.idx&&e.idx.count>0),n=t.filter(e=>e.idx.daqmx),r=(_&32)!=0,i=0,a=0;n.length?(a=n[0].idx.daqmx.stride,i=n[0].idx.count*a):r?(a=t.reduce((e,t)=>e+(q[t.idx.type]??0),0),i=(t[0]?.idx.count??0)*a):i=t.reduce((e,t)=>e+t.idx.bytes,0);let c=i>0?Math.floor((x-e)/i):0,l=o.push({rawStart:e,chunkSize:i,chunks:c,le:v})-1,u=0;for(let e of t){let t=e.idx,n=q[t.type]??0,o=t.daqmx?{seg:l,count:t.count,offset:t.daqmx.byteOffset,bytes:0,stride:a,type:t.type}:{seg:l,count:t.count,offset:u,bytes:t.bytes,stride:r?a:n,type:t.type};t.daqmx||(u+=r?n:t.bytes),o.type===32?o.count=Math.min(o.count,Math.floor(o.bytes/4)):n>0&&(o.count=Math.min(o.count,o.stride>0?Math.max(0,Math.floor((i-o.offset-n)/o.stride)+1):0)),e.obj.pieces.push(o),c&&(e.obj.total+=o.count*c)}}if(f=x,p+=28+b,x>=e.size)break}return{objs:[...a.values()],segments:o}}const Sn={...ln,async plan(e,t){let i=e.companions.find(e=>e.name.toLowerCase().endsWith(`.tdms_index`)),a=[],{objs:o,segments:s}=await xn(t,i?new n(i):null,a),c=o.find(e=>e.path===`/`)?.props,l=o.filter(e=>e.name&&e.total>0&&(e.type===32||q[e.type])),u=new Set(l);for(let e of o)e.name&&e.total>0&&!u.has(e)&&a.push(`${e.name}: TDMS data type ${e.type} is not supported; skipped.`);let d=l.map(e=>e.props.get(`wf_start_time`)).filter(e=>typeof e==`number`),f=d.reduce((e,t)=>Math.min(e,t),d.length?1/0:0),p=new Map;for(let e of l){let t=`${e.total}|${e.props.get(`wf_increment`)??``}`,n=p.get(e.group)??new Map,r=n.get(t);r?r.push(e):n.set(t,[e]),p.set(e.group,n)}let m=[],h=[];for(let[e,t]of p)for(let n of t.values()){let r=n[0].props.get(`wf_increment`),i=typeof r==`number`&&r>0?1/r:null,a=i?null:n.find(e=>e.type===68)??n.find(e=>e.type!==32&&/^(time|timestamp|t)$/i.test(e.name))??null,o=n.filter(e=>e!==a),s=n[0].props.get(`wf_start_time`),c=i?Number(n[0].props.get(`wf_start_offset`)??0)+(typeof s==`number`?s-f:0):0;m.push({name:t.size===1?e:`${e} (${i?+i.toFixed(6):n[0].total} ${i?`Hz`:`samples`})`,channels:o.map(e=>({name:e.name,unit:String(e.props.get(`unit_string`)??``),text:e.type===32})),samples:n[0].total,time:i?{kind:`rate`,rate:i,start:c}:a?{kind:`timestamps`}:{kind:`index`},rateHz:i}),h.push({channels:o,time:a,origin:0})}if(m.length===0)throw Error(`This TDMS file has no channels with data.`);let g=[];for(let e of h){if(!e.time)continue;let n=e.time.pieces[0],i=s[n.seg],a=await t.read(i.rawStart+n.offset,q[n.type]??8),o=new Float64Array(1);bn(n.type,r(a),0,0,1,i.le,o,0),g.push(o[0])}let _=g.reduce((e,t)=>Math.min(e,t),g.length?1/0:0);for(let e of h)e.origin=_;let v=new Date(Date.UTC(1904,0,1)+f*1e3),y=f&&Number.isFinite(v.getTime())?v.toISOString():null,b={objs:o,segments:s,groups:h},x={};for(let[e,t]of c??[])typeof t==`string`&&(x[e]=t);return{format:`TDMS`,startTime:y,groups:m,meta:x,events:[],notes:a,state:b}},async*stream(e){for(let t of e.selection)yield*wn(e,t.group)},streamGroup:(e,t)=>wn(e,t)};function Cn(e,t,n,r,i,a){let o=0;for(;o<i&&r.pi<t.pieces.length;){let s=t.pieces[r.pi],c=e.segments[s.seg];if(r.chunk>=c.chunks){r.pi++,r.chunk=0,r.row=0;continue}let l=Math.min(i-o,s.count-r.row),u=c.rawStart+r.chunk*c.chunkSize+s.offset;if(s.type===32)a.push({ch:n,at:u,end:u+s.bytes,rows:l,first:r.row,out:o,piece:s,le:c.le,range:0});else{let e=u+r.row*s.stride;a.push({ch:n,at:e,end:e+(l-1)*s.stride+q[s.type],rows:l,first:r.row,out:o,piece:s,le:c.le,range:0})}o+=l,r.row+=l,r.row>=s.count&&(r.chunk++,r.row=0)}}async function*wn(e,t){let n=e.plan.state,i=n.groups[t],a=f(e,t).map(e=>i.channels[e]),o=i.time?[i.time,...a]:a;if(!o.length)return;let s=new Map(n.objs.map(e=>[e.path,e.props])),c=e=>s.get(e)??new Map,l=c(`/`),d=o.map(e=>vn([e.props,c(`/'${e.group.replace(/'/g,`''`)}'`),l],[],e.name)),p=o.map(()=>({pi:0,chunk:0,row:0})),m=o.reduce((e,t)=>Math.min(e,t.total),1/0);for(let a=0;a<m;){e.signal?.throwIfAborted();let s=Math.min(65536,m-a),c=[];o.forEach((e,t)=>Cn(n,e,t,p[t],s,c));let l=c.slice().sort((e,t)=>e.at-t.at),f=[];for(let e of l){let t=f[f.length-1];t&&e.at<=t.end+65536&&Math.max(t.end,e.end)-t.at<=16777216?t.end=Math.max(t.end,e.end):f.push({at:e.at,end:e.end}),e.range=f.length-1}let h=[];for(let t of f)h.push(await e.io.slice(t.at,t.end-t.at));let g=h.map(r),_=o.map(e=>e.type===32?Array(s).fill(null):new Float64Array(s).fill(NaN));for(let e of c){let t=e.at-f[e.range].at,n=e.piece;if(n.type===32){let r=h[e.range],i=g[e.range],a=t+4*n.count,o=_[e.ch];for(let n=0;n<e.rows;n++){let s=e.first+n,c=s===0?0:i.getUint32(t+4*(s-1),e.le),l=i.getUint32(t+4*s,e.le);o[e.out+n]=u(r.subarray(a+c,a+l))}}else bn(n.type,g[e.range],t,n.stride,e.rows,e.le,_[e.ch],e.out)}for(let e=0;e<o.length;e++){let t=d[e],n=_[e];if(t&&n instanceof Float64Array)for(let e=0;e<s;e++)n[e]=t(n[e])}let v=null;if(i.time){v=_.shift();for(let e=0;e<s;e++)v[e]-=i.origin}yield{group:t,time:v,start:a,length:s,columns:_},a+=s}}const Tn={id:`hdf5`,label:`HDF5`,extensions:[`.h5`,`.hdf5`,`.hdf`,`.he5`,`.nc`],sniff:e=>[0,512,1024,2048].some(t=>d(e,`HDF\r
|
|
2
|
-
|
|
3
|
-
`,t))},En=e=>!!e&&typeof e.keys==`function`,Dn=1e5;function On(){let e=new Set,t=0,n=!1;return{enter(t){let r=null;try{r=t.create_reference?Array.prototype.join.call(t.create_reference().ref_data,`,`):null}catch{r=null}return r===null?!0:e.has(r)?(n=!0,!1):(e.add(r),!0)},count:()=>++t<=Dn,note:()=>t>1e5?`This file has more than ${Dn.toLocaleString(`en-US`)} objects (or links that repeat its groups); only the first were read.`:n?`Some groups of this file link back to a group already read; each was read once.`:null}}function kn(e,t,n,r){return t.reduce((e,t)=>e*t,1)*Math.max(1,e.metadata.size||1)>(r?n*1032+1024:n)}const An=e=>!!e&&typeof e.slice==`function`;let jn=null,J=null;function Mn(e){jn=e,J=null}const Nn=new WeakMap;function Pn(){!jn||J||(J=jn(),J.catch(()=>{J=null}))}function Fn(e){if(!jn)return Promise.reject(Error(`HDF5 and MAT 7.3 files are read in the import worker, and this environment has no workers.`));Pn();let t=Nn.get(e);return t||(t=J.then(t=>t(e)).then(e=>({root:e.root,close:()=>{}})),Nn.set(e,t),t.catch(()=>Nn.delete(e))),t}const In=new WeakMap;function Ln(e,t,n){let r=In.get(e);r||In.set(e,r=new Map);let i=r.get(t);return i||r.set(t,i=n??e.get(t)),i}function Y(e){return e instanceof Float64Array?e:e instanceof BigInt64Array||e instanceof BigUint64Array?Float64Array.from(e,e=>Number(e)):ArrayBuffer.isView(e)?new Float64Array(e):Float64Array.from(e)}const Rn={s:1,sec:1,second:1,seconds:1,ms:.001,msec:.001,us:1e-6,µs:1e-6,ns:1e-9};function zn(e,...t){for(let n of t){let t=e[n]?.value;if(typeof t==`string`)return t;if(Array.isArray(t)&&typeof t[0]==`string`)return t[0]}return``}function Bn(e,...t){for(let n of t){let t=e[n]?.value,r=typeof t==`number`?t:ArrayBuffer.isView(t)?Number(t[0]):NaN;if(Number.isFinite(r))return r}return null}const Vn=new Set([1,2,3,4,5,6]),Hn=/^(time|t|timestamps?|.*[_ ]time|time[_ ].*)$/i,Un=[`sampling_rate`,`sample_rate`,`samplerate`,`sampleRate`,`fs`,`Fs`,`rate`];function Wn(e,t,n,r,i,a,o=0){i.set(n,t.attrs);for(let s of t.keys()){if(!a.count())return;let c=n===`/`?`/${s}`:`${n}/${s}`,l=t.get(s);if(En(l))o<16&&a.enter(l)&&Wn(e,l,c,r,i,a,o+1);else if(An(l)){let t=Ln(e,c,l);r.push({path:c,parent:n,name:s,ds:t,attrs:t.attrs})}}}const Gn=e=>e===`/`?`root`:e.slice(1),Kn=e=>Math.max(4096,Math.min(1<<20,Math.floor((8<<20)/(8*Math.max(1,e)))));async function qn(e,t){let n=Ln(e,t.path);if(t.col===null)return Y(n.slice([[0,1]]))[0]*t.factor;let r=n.slice([[0,1]]);return Number(r[0][t.col])*t.factor}const Jn={...Tn,async plan(e){let t=await Fn(e.main);try{let n=[],r=new Map,i=On();i.enter(t.root),Wn(t.root,t.root,`/`,n,r,i);let a=[],o=i.note();o&&a.push(o);let s=new Map,c=[],l=0;for(let t of n){let n=t.ds.metadata.shape??[],r=t.ds.metadata.type,i=t.ds.metadata.chunks?t.ds.filters??[]:[],o=i.find(e=>!Vn.has(e.id)),u=!o;if(u&&i.length>0&&n.length>0&&n.every(e=>e>0))try{t.ds.slice(n.map(()=>[0,1]))}catch{u=!1}if(!u){a.push(`${t.path}: compressed with a filter Kymoscope cannot read${o?` (${o.name||o.id})`:``}; skipped.`);continue}if(kn(t.ds,n,e.main.size,i.length>0)){a.push(`${t.path}: larger than the file can hold (never written, or damaged); skipped.`);continue}if(n.length===1&&n[0]>1&&(r===0||r===1||r===3)){let e=`${t.parent}|${n[0]}`,r=s.get(e)??{parent:t.parent,n:n[0],leaves:[]};r.leaves.push(t),s.set(e,r)}else if(n.length===2&&n[0]>1&&n[1]<=4096&&(r===0||r===1)){let e=Bn(t.attrs,...Un);c.push({name:Gn(t.path),kind:`matrix`,rows:n[0],rate:e,time:null,origin:0,cols:Array.from({length:n[1]},(e,n)=>({path:t.path,col:n,text:!1,factor:1}))})}else if(n.length===1&&r===6){let e=(t.ds.metadata.compound_type?.members??[]).flatMap((e,n)=>e.type===0||e.type===1?[{path:t.path,col:n,text:!1,factor:1,name:e.name}]:[]),r=e.find(e=>Hn.test(e.name));c.push({name:Gn(t.path),kind:`compound`,rows:n[0],rate:null,origin:0,time:r??null,cols:e.filter(e=>e!==r)})}else l++}for(let e of s.values()){let t=[...s.values()].filter(t=>t.parent===e.parent).length>1,n=e.leaves.find(e=>zn(e.attrs,`CLASS`)===`DIMENSION_SCALE`)??e.leaves.find(e=>Hn.test(e.name)&&e.ds.metadata.type!==3),i=n?Rn[zn(n.attrs,`units`,`unit`,`Units`)]??1:1,a=n?null:Bn(r.get(e.parent)??{},...Un);c.push({name:t?`${Gn(e.parent)} (${e.n} rows)`:Gn(e.parent),kind:`vectors`,rows:e.n,rate:a,origin:0,time:n?{path:n.path,col:null,text:!1,factor:i}:null,cols:e.leaves.filter(e=>e!==n).map(e=>({path:e.path,col:null,text:e.ds.metadata.type===3,factor:1}))})}l&&a.push(`${l} dataset${l===1?``:`s`} with other shapes or types (images, references, 3-D) skipped.`),c.sort((e,t)=>e.name.localeCompare(t.name));let u=c.map((e,t)=>e.time||e.rate?t:-1).filter(e=>e>=0),d=1/0;for(let e of c)e.time&&(d=Math.min(d,await qn(t.root,e.time)));for(let e of c)e.origin=Number.isFinite(d)?d:0;let f=new Map(n.map(e=>[e.path,e]));for(let e of c)e.chunk=[...e.cols,...e.time?[e.time]:[]].reduce((e,t)=>Math.max(e,f.get(t.path).ds.metadata.chunks?.[0]??0),0);let p=e=>zn(f.get(e.path).attrs,`units`,`unit`,`Units`,`UNITS`),m=(e,t)=>e.kind===`matrix`?`${e.name.split(`/`).pop()}[${t.col+1}]`:e.kind===`compound`?f.get(t.path).ds.metadata.compound_type.members[t.col].name:t.path.split(`/`).pop(),h=c.map(e=>({name:e.name,channels:e.cols.map(t=>({name:m(e,t),unit:e.kind===`vectors`?p(t):``,text:t.text})),samples:e.rows,time:e.time?{kind:`timestamps`}:e.rate?{kind:`rate`,rate:e.rate,start:0}:{kind:`index`},rateHz:e.rate}));if(h.length===0)throw Error(`This HDF5 file has no datasets Kymoscope can plot.`);let g=h.length>20||h.length>1&&u.length<h.length,_=g?u.length?u:[c.reduce((e,t,n)=>t.rows*t.cols.length>c[e].rows*c[e].cols.length?n:e,0)]:void 0;return g&&a.push(`Only the groups with a time base are read unless you choose others in the channel picker.`),{format:`HDF5`,startTime:null,groups:h,meta:{},events:[],notes:a,pick:g,defaultGroups:_,state:{groups:c}}}finally{t.close()}},async*stream(e){for(let t of e.selection)yield*Yn(e,t.group)},streamGroup:(e,t)=>Yn(e,t)};async function*Yn(e,t){let n=e.plan.state.groups[t],r=f(e,t).map(e=>n.cols[e]),i=await Fn(e.files.main);try{let a=n.chunk??0,o=a>0?Math.max(1,Math.min(Math.floor((1<<20)/a),Math.ceil(Kn(r.length+1)/a)))*a:Kn(r.length+1);for(let a=0;a<n.rows;a+=o){e.signal?.throwIfAborted();let s=Math.min(n.rows,a+o),c=s-a,l=null,u=e=>{let t=Ln(i.root,e.path);if(n.kind===`vectors`){let n=t.slice([[a,s]]);if(e.text)return Array.from(n,e=>e==null?null:String(e));let r=Y(n);if(e.factor!==1)for(let t=0;t<c;t++)r[t]*=e.factor;return r}let r=new Float64Array(c);if(n.kind===`matrix`){let n=(t.shape??[0,1])[1],i=l??=t.slice([[a,s],[0,n]]);for(let t=0;t<c;t++)r[t]=Number(i[t*n+e.col])}else{let n=l??=t.slice([[a,s]]);for(let t=0;t<c;t++)r[t]=Number(n[t][e.col])*e.factor}return r},d=null;if(n.time){d=u(n.time);for(let e=0;e<c;e++)d[e]-=n.origin}yield{group:t,time:d,start:a,length:c,columns:r.map(u)}}}finally{i.close()}}const Xn={id:`mat`,label:`MATLAB MAT (v5, v7.3)`,extensions:[`.mat`],sniff:e=>d(e,`MATLAB 5.0 MAT-file`)||d(e,`MATLAB 7.3 MAT-file`)},Zn=/^(time|t|tout|timestamps?)$/i,Qn=/^(fs|sample_?rate|sampling_?rate|rate|samplerate)$/i,$n=e=>e.slice(e.lastIndexOf(`.`)+1),er=e=>e.includes(`.`)?e.slice(0,e.lastIndexOf(`.`)):``;function tr(e,t){let n=/^(.*)\.values(\[\d+\])?$/.exec(e.name),r=n&&(t.get(`${n[1]}.label`)||t.get(`${n[1]}.blockName`));return r?{...e,name:`${r}${n[2]??``}`}:e}function nr(e,t,n){let r=new Map;for(let t of e){if(!(t.length>1))continue;let e=r.get(t.length);e?e.push(t):r.set(t.length,[t])}let i=[...n].filter(([e])=>Qn.test($n(e))),a=i.length===1?i[0][1]:null,o=[];for(let[e,n]of r){let r=n.find(e=>Zn.test($n(e.name))||/(_time|\.Time)$/.test(e.name))??null;o.push({name:r?er(r.name)||r.name:`${e} samples`,channels:n.filter(e=>e!==r).map(e=>tr(e,t)),time:r,rate:r?null:a,origin:0})}return o}function rr(e){return e.map(e=>({name:e.name,channels:e.channels.map(e=>({name:e.name,unit:``})),samples:e.channels[0]?.length??e.time?.length??0,time:e.time?{kind:`timestamps`}:e.rate?{kind:`rate`,rate:e.rate,start:0}:{kind:`index`},rateHz:e.rate}))}async function ir(e){let t=1/0;for(let n of e)n.time&&(t=Math.min(t,(await n.time.read(0,1))[0]));for(let n of e)n.origin=Number.isFinite(t)?t:0}var ar=class{#e;size;constructor(e){this.#e=e,this.size=e.size}read(e,t){return t>=65536?this.#e.slice(e,t):this.#e.read(e,t)}release(){}},or=class{#e;#t;#n;#r=null;keep=!0;size;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.size=r.length}async read(e,t){return this.#r??=await W(await this.#e.slice(this.#t,this.#n),this.size,this.size),this.#r.subarray(e,e+t)}release(){this.keep||(this.#r=null)}};const sr={1:1,2:1,3:2,4:2,5:4,6:4,7:4,9:8,12:8,13:8};function cr(e,t,n,i,a=1){let o=r(t),s=i.length,c=sr[e]*a;if(e===9&&a===1&&n){i.set(t.byteOffset%8==0?new Float64Array(t.buffer,t.byteOffset,s):new Float64Array(t.slice(0,s*8).buffer));return}switch(e){case 1:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getInt8(t);return;case 2:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getUint8(t);return;case 3:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getInt16(t,n);return;case 4:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getUint16(t,n);return;case 5:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getInt32(t,n);return;case 6:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getUint32(t,n);return;case 7:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getFloat32(t,n);return;case 9:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getFloat64(t,n);return;case 12:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getInt32(t+(n?4:0),n)*4294967296+o.getUint32(t+(n?0:4),n);return;case 13:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getUint32(t+(n?4:0),n)*4294967296+o.getUint32(t+(n?0:4),n);return;default:i.fill(NaN)}}async function X(e,t,n){let i=r(await e.read(t,8)),a=i.getUint32(0,n);if(a>>>16)return{type:a&65535,bytes:a>>>16,data:t+4,next:t+8};let o=i.getUint32(4,n);return{type:a,bytes:o,data:t+8,next:a===15?t+8+o:t+8+o+(8-o%8)%8}}function lr(e,t,n,r,i){let[a,o]=t,s=sr[r.type];if(!s)return[];let c=(e,t)=>async(a,o)=>{let c=new Float64Array(o-a);return t===1?cr(r.type,await n.read(r.data+(e+a)*s,(o-a)*s),i,c):cr(r.type,await n.read(r.data+(e+a*t)*s,((o-a-1)*t+1)*s),i,c,t),c};return a===1||o===1?[{name:e,length:a*o,read:c(0,1)}]:a>=o?Array.from({length:o},(t,n)=>({name:`${e}[${n+1}]`,length:a,read:c(n*a,1)})):Array.from({length:a},(t,n)=>({name:`${e}[${n+1}]`,length:o,read:c(n,a)}))}async function ur(e,t,n,i,a,o,s){let d=t,f=await X(e,d,n),p=r(await e.read(f.data,8)).getUint32(0,n),m=p&255;d=f.next;let h=await X(e,d,n);if(h.bytes>128){o.notes.push(`A MAT variable with more than 32 dimensions was skipped (damaged).`);return}let g=r(await e.read(h.data,h.bytes)),_=Array.from({length:h.bytes/4},(e,t)=>g.getInt32(4*t,n));d=h.next;let v=await X(e,d,n),y=l(await e.read(v.data,v.bytes));d=v.next;let b=a??y,x=i?`${i}.${b}`:b,S=_.reduce((e,t)=>e*t,1);if(m>=6&&m<=15){if(S===0)return;let t=await X(e,d,n);if(p&2048&&o.notes.push(`${x}: the imaginary part was skipped.`),_.length>2){o.notes.push(`${x}: arrays with more than two dimensions are skipped.`);return}if(!sr[t.type])return;if(!(S>0)||S*sr[t.type]>t.bytes||t.data+t.bytes>e.size){o.notes.push(`${x}: its data is shorter than its dimensions (damaged); skipped.`);return}if(S===1){let r=new Float64Array(1);cr(t.type,await e.read(t.data,sr[t.type]??8),n,r),o.scalars.set(x,r[0]);return}o.channels.push(...lr(x,_,e,t,n));return}if(m===4){let t=await X(e,d,n);if(t.bytes>dr)return;let r=await e.read(t.data,t.bytes),i=t.type===3||t.type===4||t.type===17?new TextDecoder(n?`utf-16le`:`utf-16be`).decode(r.subarray(0,r.length&-2)):u(r);_[0]<=1&&o.strings.set(x,i);return}if(m===2){let t=await X(e,d,n),i=r(await e.read(t.data,4)).getInt32(0,n);d=t.next;let a=await X(e,d,n);if(!(i>0))return;let l=await e.read(a.data,a.bytes),u=Array.from({length:Math.floor(l.length/i)},(e,t)=>c(l.subarray(t*i,(t+1)*i)));if(d=a.next,u.length===0||S*u.length*8>e.size-d){S>0&&u.length>0&&o.notes.push(`${x}: its fields are longer than the file (damaged); skipped.`);return}for(let t=0;t<S;t++){let r=S>1?`${x}(${t+1})`:x;for(let t of u){let i=await X(e,d,n);i.type===14&&i.bytes>0&&s<16&&await ur(e,i.data,n,r,t,o,s+1),d=i.next}}return}m===1?o.notes.push(`${x}: cell arrays are skipped.`):m===5?o.notes.push(`${x}: sparse arrays are skipped.`):o.notes.includes(fr)||o.notes.push(fr)}const dr=1<<17,fr=`MATLAB objects (timeseries, SimulationOutput) were skipped: save them as 'Structure with time' or as structs.`;async function pr(e){let t=l((await e.read(0,128)).subarray(126,128))===`IM`,n={channels:[],strings:new Map,scalars:new Map,notes:[],sources:[]},i=new ar(e),a=0;for(let o=128;o+8<=e.size;){let s=await X(i,o,t);if(s.type===15){if(s.bytes>1<<30)throw Error(`A compressed variable in this MAT file is over 1 GB; save it with -v7.3 to open it here.`);let i=await e.slice(s.data,s.bytes),o=await W(i,-1,8),c=o.length<8?0:8+r(o).getUint32(4,t);if(c>C(s.bytes))throw Error(`A compressed variable in this MAT file is damaged.`);if(c>1<<30)throw Error(`A compressed variable in this MAT file is over 1 GB; save it with -v7.3 to open it here.`);let l=await W(i,c,c),u=new or(e,s.data,s.bytes,l);n.sources.push(u),a+=l.length;let d=await X(u,0,t);if(d.type===14&&await ur(u,d.data,t,``,null,n,0),a>536870912)for(let e of n.sources)e.keep=!1,e.release()}else s.type===14&&await ur(i,s.data,t,``,null,n,0);o=s.next}return n}const mr=new Set([`double`,`single`,`int8`,`uint8`,`int16`,`uint16`,`int32`,`uint32`,`int64`,`uint64`,`logical`]);function hr(e,t){let n={channels:[],strings:new Map,scalars:new Map,notes:[]},r=On();r.enter(e);let i=t=>Ln(e,t),a=(e,t,n)=>{let r=null;return(a,o)=>((r?.s!==a||r.e!==o)&&(r={s:a,e:o,v:Y(t?i(e).slice([[0,n],[a,o]]):i(e).slice([[a,o],[0,n]]))}),r.v)},o=(e,s,c,l)=>{for(let u of e.keys()){if(!r.count())return;if(u.startsWith(`#`))continue;let d=e.get(u);if(!d)continue;let f=`${s}/${u}`,p=c?`${c}.${u}`:u,m=d.attrs,h=zn(m,`MATLAB_class`);if(m.MATLAB_empty)continue;if(En(d)){h===`struct`&&l<16&&r.enter(d)&&o(d,f,p,l+1);continue}if(!An(d))continue;let g=d.shape??[];if(h===`char`){if(g.reduce((e,t)=>e*t,1)>65536)continue;let e=Y(d.slice(g.map(e=>[0,e])));n.strings.set(p,new TextDecoder(`utf-16le`).decode(Uint16Array.from(e)))}else if(mr.has(h)&&g.length===2&&kn(d,g,t,!!d.metadata.chunks))n.notes.push(`${p}: larger than the file can hold (never written, or damaged); skipped.`);else if(mr.has(h)&&g.length===2){let[e,t]=g;if(e*t===1){n.scalars.set(p,Y(i(f).slice([[0,1],[0,1]]))[0]);continue}if(e===1||t===1){let r=e*t;n.channels.push({name:p,length:r,read:async(t,n)=>Y(e===1?i(f).slice([[0,1],[t,n]]):i(f).slice([[t,n],[0,1]]))})}else if(t>=e){let r=a(f,!0,e);for(let i=0;i<e;i++)n.channels.push({name:`${p}[${i+1}]`,length:t,read:async(e,t)=>r(e,t).slice(i*(t-e),(i+1)*(t-e))})}else{let r=a(f,!1,t);for(let i=0;i<t;i++)n.channels.push({name:`${p}[${i+1}]`,length:e,read:async(e,n)=>{let a=r(e,n),o=new Float64Array(n-e);for(let e=0;e<o.length;e++)o[e]=a[e*t+i];return o}})}}else h===`cell`?n.notes.push(`${p}: cell arrays are skipped.`):h&&n.notes.push(`${p}: MATLAB class ${h} is skipped.`)}};o(e,``,``,0);let s=r.note();return s&&n.notes.push(s),n}const gr=e=>Math.max(4096,Math.min(1<<18,Math.floor((16<<20)/(8*Math.max(1,e))))),_r={...Xn,async plan(e,t){let n=d(await t.read(0,20),`MATLAB 7.3`),r,i=[];if(n)r=hr((await Fn(e.main)).root,e.main.size);else{let e=await pr(t);i=e.sources,r=e}let a=nr(r.channels,r.strings,r.scalars).filter(e=>e.channels.length>0);await ir(a);let o=rr(a);if(o.length===0)throw Error(`This MAT file has no numeric vectors or matrices to plot.`);let s=o.flatMap((e,t)=>e.time.kind===`index`?[]:[t]),c=o.length>1&&s.length<o.length,l=Object.fromEntries(r.strings);for(let[e,t]of r.scalars)l[e]=String(t);return{format:n?`MAT 7.3`:`MAT 5`,startTime:null,groups:o,meta:l,events:[],notes:r.notes,pick:c,defaultGroups:c&&s.length?s:void 0,state:{groups:a,sources:i}}},async*stream(e){for(let t of e.selection)yield*vr(e,t.group)},streamGroup:(e,t)=>vr(e,t)};async function*vr(e,t){let n=e.plan.state,r=n.groups[t],i=f(e,t).map(e=>r.channels[e]),a=r.channels[0].length,o=gr(i.length+1);try{for(let n=0;n<a;n+=o){e.signal?.throwIfAborted();let s=Math.min(a,n+o),c=null;if(r.time){c=await r.time.read(n,s);for(let e=0;e<c.length;e++)c[e]-=r.origin}let l=[];for(let e of i)l.push(await e.read(n,s));yield{group:t,time:c,start:n,length:s-n,columns:l}}}finally{for(let e of n.sources)e.release()}}const yr={id:`comtrade`,label:`COMTRADE (IEEE C37.111)`,extensions:[`.cfg`,`.cff`],companions:[{ext:`.dat`}],sniff:e=>{let t=l(e.subarray(0,512));if(/^---\s*file type:\s*CFG/i.test(t))return!0;let n=t.split(/\r?\n/);return n.length>2&&/^\s*\d+\s*,\s*\d+A\s*,\s*\d+D\s*$/i.test(n[1])}};function br(e,t){let n=/^\s*(\d{1,2})\/(\d{1,2})\/(\d{2,4})\s*,\s*(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))?/.exec(e??``);if(!n)return[null,0,!1];let[r,i]=t===1991?[n[2],n[1]]:[n[1],n[2]],a=n[3].length===2?2e3+Number(n[3]):Number(n[3]),o=Number(`${n[6]}.${n[7]??`0`}`);return[`${a}-${i.padStart(2,`0`)}-${r.padStart(2,`0`)}T${n[4].padStart(2,`0`)}:${n[5]}:${o.toFixed(3).padStart(6,`0`)}`,Date.UTC(a,Number(i)-1,Number(r),Number(n[4]),Number(n[5]))/1e3+o,(n[7]??``).length>6]}function xr(e){let t=e.split(/\r?\n/).map(e=>e.trim()),[n,,r]=t[0].split(`,`),i=Number(r)||1991,a=/(\d+)A\s*,\s*(\d+)D/i.exec(t[1]??``);if(!a)throw Error(`This COMTRADE .cfg is damaged (second line).`);let o=Number(a[1]),s=Number(a[2]);if(o+s>t.length)throw Error(`This COMTRADE .cfg is damaged (more channels than lines).`);let c=2,l=[];for(let e=0;e<o;e++,c++){let e=(t[c]??``).split(`,`);l.push({name:(e[1]??``).trim(),unit:(e[4]??``).trim(),a:Number(e[5]),b:Number(e[6]??0)||0})}let u=[];for(let e=0;e<s;e++,c++)u.push(((t[c]??``).split(`,`)[1]??``).trim());c++;let d=Number(t[c++]);if(!(Number.isInteger(d)&&d>=0&&d<=t.length-c))throw Error(`This COMTRADE .cfg is damaged (sample rates).`);let f=[];for(let e=0;e<Math.max(1,d);e++,c++){let[e,n]=(t[c]??``).split(`,`).map(Number);f.push([d===0?0:e,n])}let[p,m,h]=br(t[c++],i),[g,_,v]=br(t[c++],i),y=(t[c++]||`ASCII`).toUpperCase(),b=Number(t[c++])||1;return{station:n.trim(),rev:i,analog:l,digital:u,rates:f,start:p,trigger:g,startSec:m,triggerSec:_,ft:y,timemult:b,timebase:h||v?1e-9:1e-6}}const Sr={BINARY:2,BINARY32:4,FLOAT32:4};async function Cr(e){let t=l(await e.read(0,Math.min(e.size,1<<20))),n=t.search(/---\s*file type:\s*CFG\s*---\r?\n/i),r=/---\s*file type:\s*DAT\s+(ASCII|BINARY32|BINARY|FLOAT32)(?:\s*:\s*(\d+))?\s*---\r?\n/i.exec(t);if(n<0||!r)throw Error(`This COMTRADE .cff is damaged (no CFG or DAT section in its first megabyte).`);let i=t.indexOf(`
|
|
4
|
-
`,n)+1,a=t.slice(i).search(/---\s*file type:\s*(INF|HDR|DAT)/i),o=t.slice(i,a<0?void 0:i+a),s=r.index+r[0].length;return{cfg:o,offset:s,length:r[2]?Number(r[2]):e.size-s}}function wr(e,t,n,r){let i=0,a=0,o=t,s=0;for(let[t,c]of e){for(;o<c&&s<n;)r[s++]=a+(o-i)/t,o++;if(a+=(c-i)/t,i=c,s>=n)return}let c=e[e.length-1];for(;s<n;s++,o++)r[s]=a+(o-i)/c[0]}const Tr=e=>e.companions.find(e=>e.name.toLowerCase().endsWith(`.dat`)),Er={...yr,async plan(e,t){let n=e.main.name.toLowerCase().endsWith(`.cff`),r,i;if(n){let e=await Cr(t);r=e.cfg,i={data:`self`,offset:e.offset,length:e.length}}else{let n=Tr(e);if(!n)throw Error(`This COMTRADE .cfg needs its .dat file: drop both together.`);if(t.size>16777216)throw Error(`This .cfg is too large to be a COMTRADE configuration file.`);r=l(await t.read(0,t.size)),i={data:`companion`,offset:0,length:n.size}}let a=xr(r);if(a.ft!==`ASCII`&&!Sr[a.ft])throw Error(`This COMTRADE file has data file type ${a.ft}, which Kymoscope cannot read.`);let o=Math.ceil(a.digital.length/16),s=a.ft===`ASCII`?0:8+a.analog.length*Sr[a.ft]+2*o,c=s?Math.floor(i.length/s):i.length,u=Math.min(a.rates[a.rates.length-1][1]||(s?c:-1),c),d=a.rates.length===1&&a.rates[0][0]>0?a.rates[0][0]:null,f=[`Analog values are shown as recorded (primary or secondary, per the CFG).`];return{format:`COMTRADE ${a.rev} (${a.ft})`,startTime:a.start,meta:{station:a.station,trigger:a.trigger??``},groups:[{name:a.station||`COMTRADE`,channels:[...a.analog.map(e=>({name:e.name,unit:e.unit})),...a.digital.map(e=>({name:e,unit:``}))],samples:u,time:{kind:`timestamps`},rateHz:d}],events:a.start&&a.trigger?[{time:Math.round((a.triggerSec-a.startSec)*1e6)/1e6,text:`Trigger`}]:[],notes:f,state:{...i,cfg:a,samples:u,recordSize:s}}},stream:e=>Dr(e)};async function*Dr(e){let i=e.plan.state,{cfg:a}=i,o=i.data===`self`?e.io:new n(Tr(e.files)),s=f(e,0),c=a.analog.length,l=a.rates[0][0]>0,u=a.timemult*a.timebase,d=65536,p=0,m=(e,t,n)=>{let r=new Float64Array(e);if(l)wr(a.rates,p,e,r);else for(let n=0;n<e;n++)r[n]=t[n]*u;let i={group:0,time:r,start:p,length:e,columns:n};return p+=e,i};if(a.ft===`ASCII`){let t=a.rev>=1999?`99999`:``,n=s.map(e=>e<c?a.analog[e]:null),r=new Float64Array(d),l=s.map(()=>new Float64Array(d)),u=0,f=(e,i,a)=>{let o=e.slice(i,a).split(`,`);if(!(o.length<2)){r[u]=Number(o[1]);for(let e=0;e<s.length;e++){let r=(o[2+s[e]]??``).trim(),i=n[e];l[e][u]=r===``||i&&r===t?NaN:i?i.a*Number(r)+i.b:Number(r)}u++}},p=``,h=new TextDecoder(`latin1`);for await(let t of o.windows(i.offset,i.length)){e.signal?.throwIfAborted();let n=p+h.decode(t.bytes),i=0;for(let e=n.indexOf(`
|
|
5
|
-
`,i);e>=0;e=n.indexOf(`
|
|
6
|
-
`,i))f(n,i,e),i=e+1,u===d&&(yield m(u,r,l),r=new Float64Array(d),l=s.map(()=>new Float64Array(d)),u=0);p=n.slice(i)}p.trim()&&f(p,0,p.length),u&&(yield m(u,r.slice(0,u),l.map(e=>e.slice(0,u))));return}let h=i.recordSize,g=Sr[a.ft],_=Math.max(1,Math.floor(Math.min(t,d*h)/h)),v=i.samples;for await(let t of o.windows(i.offset,Math.min(i.length,i.samples*h),_*h)){e.signal?.throwIfAborted();let n=Math.min(v,Math.floor(t.bytes.length/h));if(n<=0)break;let i=r(t.bytes),o=new Float64Array(n);if(!l)for(let e=0;e<n;e++)o[e]=i.getUint32(e*h+4,!0);yield m(n,o,s.map(e=>{let t=new Float64Array(n);if(e<c){let{a:r,b:o}=a.analog[e],s=8+e*g;if(a.ft===`BINARY`)for(let e=0,a=s;e<n;e++,a+=h){let n=i.getInt16(a,!0);t[e]=n===-32768?NaN:r*n+o}else if(a.ft===`BINARY32`)for(let e=0,a=s;e<n;e++,a+=h){let n=i.getInt32(a,!0);t[e]=n===-2147483648?NaN:r*n+o}else for(let e=0,a=s;e<n;e++,a+=h)t[e]=r*i.getFloat32(a,!0)+o}else{let r=e-c,a=8+c*g+2*(r>>4),o=1<<(r&15);for(let e=0,r=a;e<n;e++,r+=h)t[e]=i.getUint16(r,!0)&o?1:0}return t})),v-=n}}new TextEncoder;function Or(e,t,n){let r=t,i=r+n,a=[],o=``;for(;r<i;){let t=e[r++];if(!(t&128))a.push(t);else if((t&224)==192){let n=e[r++]&63;a.push((t&31)<<6|n)}else if((t&240)==224){let n=e[r++]&63,i=e[r++]&63;a.push((t&31)<<12|n<<6|i)}else if((t&248)==240){let n=e[r++]&63,i=e[r++]&63,o=e[r++]&63,s=(t&7)<<18|n<<12|i<<6|o;s>65535&&(s-=65536,a.push(s>>>10&1023|55296),s=56320|s&1023),a.push(s)}else a.push(t);a.length>=4096&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}const kr=new TextDecoder;function Ar(e,t,n){let r=e.subarray(t,t+n);return kr.decode(r)}function jr(e,t,n){return n>200?Ar(e,t,n):Or(e,t,n)}var Mr=class{type;data;constructor(e,t){this.type=e,this.data=t}},Z=class e extends Error{constructor(t){super(t);let n=Object.create(e.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,`name`,{configurable:!0,enumerable:!1,value:e.name})}};function Nr(e,t,n){let r=Math.floor(n/4294967296),i=n;e.setUint32(t,r),e.setUint32(t+4,i)}function Pr(e,t){let n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}function Fr(e,t){let n=e.getUint32(t),r=e.getUint32(t+4);return n*4294967296+r}function Ir({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=17179869183)if(t===0&&e<=4294967295){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}else{let n=e/4294967296,r=e&4294967295,i=new Uint8Array(8),a=new DataView(i.buffer);return a.setUint32(0,t<<2|n&3),a.setUint32(4,r),i}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,t),Nr(r,4,e),n}}function Lr(e){let t=e.getTime(),n=Math.floor(t/1e3),r=(t-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function Rr(e){return e instanceof Date?Ir(Lr(e)):null}function zr(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let e=t.getUint32(0),n=t.getUint32(4);return{sec:(e&3)*4294967296+n,nsec:e>>>2}}case 12:return{sec:Pr(t,4),nsec:t.getUint32(0)};default:throw new Z(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function Br(e){let t=zr(e);return new Date(t.sec*1e3+t.nsec/1e6)}const Vr={type:-1,encode:Rr,decode:Br};var Hr=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(Vr)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{let r=-1-e;this.builtInEncoders[r]=t,this.builtInDecoders[r]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){let r=this.builtInEncoders[n];if(r!=null){let i=r(e,t);if(i!=null)return new Mr(-1-n,i)}}for(let n=0;n<this.encoders.length;n++){let r=this.encoders[n];if(r!=null){let i=r(e,t);if(i!=null)return new Mr(n,i)}}return e instanceof Mr?e:null}decode(e,t,n){let r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,n):new Mr(t,e)}};function Ur(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}function Wr(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Ur(e)?new Uint8Array(e):Uint8Array.from(e)}function Gr(e){return`${e<0?`-`:``}0x${Math.abs(e).toString(16).padStart(2,`0`)}`}var Kr=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=16,t=16){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){let r=this.caches[n-1];FIND_CHUNK:for(let i of r){let r=i.bytes;for(let i=0;i<n;i++)if(r[i]!==e[t+i])continue FIND_CHUNK;return i.str}return null}store(e,t){let n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)}decode(e,t,n){let r=this.find(e,t,n);if(r!=null)return this.hit++,r;this.miss++;let i=Or(e,t,n),a=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(a,i),i}};const qr=`array`,Jr=`map_key`,Yr=`map_value`,Xr=e=>{if(typeof e==`string`||typeof e==`number`)return e;throw new Z(`The type of key must be string or number but `+typeof e)};var Zr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=qr,t.position=0,t.size=e,t.array=Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=Jr,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){return this.stackHeadPosition++,this.stackHeadPosition===this.stack.length&&this.stack.push({type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null}),this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw Error(`Invalid stack state. Released state is not on top of the stack.`);if(e.type===qr){let t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===Jr||e.type===Yr){let t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}};const Qr=new DataView(new ArrayBuffer(0)),$r=new Uint8Array(Qr.buffer);try{Qr.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw Error(`This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access`)}const ei=RangeError(`Insufficient data`),ti=new Kr;var ni=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Qr;bytes=$r;headByte=-1;stack=new Zr;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Hr.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder===void 0?ti:e.keyDecoder,this.mapKeyConverter=e?.mapKeyConverter??Xr}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(e){let t=Wr(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===-1&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),n=Wr(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:n}=this;return RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(let r of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(r);try{n=this.doDecodeSync(),t=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:r,pos:i,totalPos:a}=this;throw RangeError(`Insufficient data in parsing ${Gr(r)} at ${a} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,r=-1;for await(let i of e){if(t&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),n&&(r=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--r!==0;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){DECODE:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue DECODE}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue DECODE}else t=[]}else{let n=e-160;t=this.decodeString(n,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(e===217){let e=this.lookU8();t=this.decodeString(e,1)}else if(e===218){let e=this.lookU16();t=this.decodeString(e,2)}else if(e===219){let e=this.lookU32();t=this.decodeString(e,4)}else if(e===220){let e=this.readU16();if(e!==0){this.pushArrayState(e),this.complete();continue DECODE}else t=[]}else if(e===221){let e=this.readU32();if(e!==0){this.pushArrayState(e),this.complete();continue DECODE}else t=[]}else if(e===222){let e=this.readU16();if(e!==0){this.pushMapState(e),this.complete();continue DECODE}else t={}}else if(e===223){let e=this.readU32();if(e!==0){this.pushMapState(e),this.complete();continue DECODE}else t={}}else if(e===196){let e=this.lookU8();t=this.decodeBinary(e,1)}else if(e===197){let e=this.lookU16();t=this.decodeBinary(e,2)}else if(e===198){let e=this.lookU32();t=this.decodeBinary(e,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let e=this.lookU8();t=this.decodeExtension(e,1)}else if(e===200){let e=this.lookU16();t=this.decodeExtension(e,2)}else if(e===201){let e=this.lookU32();t=this.decodeExtension(e,4)}else throw new Z(`Unrecognized type byte: ${Gr(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let e=n.top();if(e.type===qr)if(e.array[e.position]=t,e.position++,e.position===e.size)t=e.array,n.release(e);else continue DECODE;else if(e.type===Jr){if(t===`__proto__`)throw new Z(`The key __proto__ is not allowed`);e.key=this.mapKeyConverter(t),e.type=Yr;continue DECODE}else if(e.map[e.key]=t,e.readCount++,e.readCount===e.size)t=e.map,n.release(e);else{e.key=null,e.type=Jr;continue DECODE}}return t}}readHeadByte(){return this.headByte===-1&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new Z(`Unrecognized array type byte: ${Gr(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new Z(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Z(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new Z(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw ei;let n=this.pos+t,r;return r=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,n,e):jr(this.bytes,n,e),this.pos+=t+e,r}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Jr:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new Z(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw ei;let n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r}decodeExtension(e,t){if(e>this.maxExtLength)throw new Z(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=Fr(this.view,this.pos);return this.pos+=8,e}readI64(){let e=Pr(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function ri(e,t){return new ni(t).decode(e)}const ii=e=>e+7&-8;function ai(e){let t=e=>RangeError(`columns message: ${e}`);e.byteOffset%8!=0&&(e=e.slice());let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.byteLength<8)throw t(`short`);if(n.getUint8(0)!==1)throw t(`version ${n.getUint8(0)}`);let r=n.getUint16(2,!0),i=n.getUint32(4,!0),a=new TextDecoder,o=[],s=8;for(let i=0;i<r;i++){if(s+3>e.byteLength)throw t(`short channel table`);let r=n.getUint8(s),i=n.getUint8(s+1),c=n.getUint8(s+2);if(s+=3,r!==4&&r!==8)throw t(`value size ${r}`);if(s+i+c>e.byteLength)throw t(`short channel table`);o.push({name:a.decode(e.subarray(s,s+i)),unit:a.decode(e.subarray(s+i,s+i+c)),size:r}),s+=i+c}if(s=ii(s),s+ii(i*8)+o.reduce((e,t)=>e+ii(i*t.size),0)>e.byteLength)throw t(`short data`);let c=e.byteOffset,l=new Float64Array(e.buffer,c+s,i);s+=ii(i*8);let u={},d={};for(let t of o)u[t.name]=t.size===4?new Float32Array(e.buffer,c+s,i):new Float64Array(e.buffer,c+s,i),t.unit&&(d[t.name]=t.unit),s+=ii(i*t.size);return{t:l,columns:u,units:d}}function oi(e){return e.values.map(e=>e.buffer)}const si=`ElapsedTime`;function ci(){let e=globalThis.crypto;if(!e?.subtle)throw Error(`WebCrypto SubtleCrypto is not available`);return e.subtle}async function li(e,t,n,r){let i=await ci().decrypt({name:`AES-GCM`,iv:t,additionalData:r},e,n);return new Uint8Array(i)}new TextEncoder().encode(`kymoscope-device-wrap-v1`),new TextEncoder().encode(`kymoscope-sender-bind-v1`);const ui=1e3,di=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),fi=e=>{let t=di(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`};function pi(e){if(e.length!==70||e[0]!==1)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{streamId:fi(e.subarray(1,17)),run:di(e.subarray(17,25)),lane:e[25],seq:t.getBigUint64(26,!0),count:t.getUint32(34,!0),hash:e.slice(38,70)}}const mi=()=>globalThis.crypto.subtle,hi=e=>mi().digest(`SHA-256`,e);async function gi(e){let t=await Promise.all(e),n=new Uint8Array(t.length*32);return t.forEach((e,t)=>n.set(new Uint8Array(e),t*32)),new Uint8Array(await hi(n))}const _i=e=>crypto.subtle.digest(`SHA-256`,e),vi=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),yi=e=>Uint8Array.from(e.replace(/-/g,``).match(/../g)??[],e=>parseInt(e,16));async function bi(e,t,n,r){let i=t[t.length-1];if(!i||(i.bytes[0]&127)!=8)return`unchecked`;let a=await n(i.bytes).catch(()=>null),o=a?pi(a.plaintext):null,s=vi(await _i(yi(e.recordingId))).slice(0,16);return o&&o.lane===1&&o.run===s&&o.seq===BigInt(e.seq)&&e.seq===r&&o.count===t.length-1&&vi((await gi(t.slice(0,-1).map(e=>_i(e.bytes)))).buffer)===vi(o.hash.buffer)?`verified`:`broken`}function xi(e){let t=[...e],n=new Set(t.filter(e=>e.check!==`unchecked`).map(e=>e.rid)),r={verified:0,broken:0,unchecked:0};for(let e of t)e.check===`unchecked`&&n.has(e.rid)?r.broken++:r[e.check]++;return r}const Si=64*1024*1024,Q=(e,t)=>RangeError(`${e}: ${t}`);function Ci(e,t){let n=new TextDecoder(`utf-8`,{fatal:!0}),r=[],i=0;try{for(let a=0;a<t;a++){if(i+3>e.byteLength)throw Q(`block schema`,`short channel table`);let t=e[i],a=e[i+1],o=e[i+2];if(i+=3,t!==4&&t!==8)throw Q(`block schema`,`value size ${t}`);if(i+a+o>e.byteLength)throw Q(`block schema`,`short channel table`);r.push({name:n.decode(e.subarray(i,i+a)),unit:n.decode(e.subarray(i+a,i+a+o)),size:t}),i+=a+o}}catch(e){throw e instanceof RangeError?e:Q(`block schema`,`invalid text`)}return r}async function wi(e){if(e.byteLength<8)throw Q(`block schema`,`short`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint8(0);if(n===3){if(e.byteLength<12)throw Q(`block schema`,`short`);let n=t.getUint32(4,!0);if(n>1e5)throw Q(`block schema`,`too many channels`);let r=t.getUint8(1)&1?await Oi(e.subarray(12),n*513,!1):e.subarray(12);return{id:t.getUint32(8,!0),channels:Ci(r,n)}}if(n!==2)throw Q(`block schema`,`version ${n}`);return{id:t.getUint32(4,!0),channels:Ci(e.subarray(8),t.getUint16(2,!0))}}function Ti(e,t,n){let r=n.get(t.getUint32(4,!0));if(!r)return null;let i=t.getUint32(8,!0);if(i!==r.channels.length)throw Q(`last values`,`channel count differs from its schema`);if(e.byteLength<12+16*i)throw Q(`last values`,`short`);let a=[];for(let e=0;e<i;e++){let n=t.getFloat64(12+8*e,!0),o=t.getFloat64(12+8*(i+e),!0);Number.isFinite(n)&&Number.isFinite(o)&&a.push({name:r.channels[e].name,unit:r.channels[e].unit,t:n,v:o})}return a}async function Ei(e,t){if(e.byteLength<12)throw Q(`last values`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(0);if(r===1)return Ti(e,n,t);if(r!==2)throw Q(`last values`,`version ${r}`);if(e.byteLength<20)throw Q(`last values`,`short`);let i=n.getUint8(1),a=t.get(n.getUint32(4,!0));if(!a)return null;let o=n.getUint32(8,!0),s=n.getFloat64(12,!0),c=a.channels.length,l=(i&2)!=0;if(o>c||l&&o!==c)throw Q(`last values`,`entry count differs from its schema`);let u=(l?0:4*o)+4*o,d=i&1?await Oi(e.subarray(20),u+8*o,!1):e.subarray(20);if(d.byteLength<u)throw Q(`last values`,`short`);let f=new DataView(d.buffer,d.byteOffset,d.byteLength),p=[];for(let e=0;e<o;e++){let t=l?e:f.getUint32(4*e,!0);if(t>=c)throw Q(`last values`,`channel outside its schema`);p.push(t)}let m=l?0:4*o,h=p.filter(e=>a.channels[e].size===4),g=p.filter(e=>a.channels[e].size===8);if(d.byteLength!==u+4*h.length+8*g.length)throw Q(`last values`,`body size mismatch`);let _=Di(d,u,h.length,4),v=Di(d,u+4*h.length,g.length,8),y=new Map;h.forEach((e,t)=>y.set(e,_[t])),g.forEach((e,t)=>y.set(e,v[t]));let b=[];return p.forEach((e,t)=>{let n=s-f.getUint32(m+4*t,!0)/1e3,r=y.get(e);Number.isFinite(n)&&Number.isFinite(r)&&b.push({name:a.channels[e].name,unit:a.channels[e].unit,t:n,v:r})}),b}function Di(e,t,n,r){let i=new Uint8Array(n*r);for(let a=0;a<r;a++)for(let o=0;o<n;o++)i[o*r+a]=e[t+a*n+o];return r===4?new Float32Array(i.buffer):new Float64Array(i.buffer)}async function Oi(e,t,n=!0){let r=new Blob([e]).stream().pipeThrough(new DecompressionStream(`deflate`)).getReader(),i=new Uint8Array(Math.min(t,e.byteLength*4+1024)),a=0;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+n.length>t)throw Q(`block`,`body larger than its header says`);if(a+n.length>i.length){let e=new Uint8Array(Math.min(t,Math.max(2*i.length,a+n.length)));e.set(i.subarray(0,a)),i=e}i.set(n,a),a+=n.length}}catch(e){throw await r.cancel().catch(()=>{}),e instanceof RangeError?e:Q(`block`,`body is not valid deflate`)}if(n&&a!==t)throw Q(`block`,`body size mismatch`);return i.length===a?i:i.subarray(0,a)}async function ki(e,t){if(e.byteLength<20)throw Q(`block`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint8(0)!==2)throw Q(`block`,`version ${n.getUint8(0)}`);let r=n.getUint8(1),i=n.getUint16(2,!0),a=n.getUint32(4,!0),o=n.getUint32(8,!0),s=t.get(o);if(!s)return null;if(s.channels.length!==i)throw Q(`block`,`channel count differs from its schema`);let c=n.getFloat64(12,!0),l=Math.max(0,a-1),u=4*l+s.channels.reduce((e,t)=>e+t.size*a,0);if(u>Si)throw Q(`block`,`too large`);let d;if(r&1)d=await Oi(e.subarray(20),u);else if(d=e.subarray(20),d.byteLength<u)throw Q(`block`,`body size mismatch`);let f=new DataView(d.buffer,d.byteOffset,d.byteLength),p=new Float64Array(a),m=0;a&&(p[0]=c);for(let e=1;e<a;e++)m+=f.getInt32(4*(e-1),!0),p[e]=c+m/1e6;let h=4*l,g={},_={};for(let e of s.channels)g[e.name]=Di(d,h,a,e.size),e.unit&&(_[e.name]=e.unit),h+=a*e.size;return{block:{t:p,columns:g,units:_},historical:(r&2)!=0,schemaId:o}}async function Ai(e,t){if(e.byteLength<20)throw Q(`sparse`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint8(0)!==1)throw Q(`sparse`,`version ${n.getUint8(0)}`);let r=n.getUint8(1),i=n.getUint32(4,!0),a=t.get(i);if(!a)return null;let o=n.getUint32(8,!0),s=n.getFloat64(12,!0),c=4*o+4*Math.max(0,o-1);if(c+8*o>Si)throw Q(`sparse`,`too large`);let l=r&1?await Oi(e.subarray(20),c+8*o,!1):e.subarray(20);if(l.byteLength<c)throw Q(`sparse`,`body size mismatch`);let u=new Uint32Array(o);for(let e=0;e<o;e++)u[e]=(l[e]|l[o+e]<<8|l[2*o+e]<<16|l[3*o+e]<<24)>>>0;let d=a.channels.length,f=0;for(let e=0;e<o;e++){if(u[e]>=d)throw Q(`sparse`,`event outside its schema`);a.channels[u[e]].size===4&&f++}if(l.byteLength!==c+4*f+8*(o-f))throw Q(`sparse`,`body size mismatch`);let p=new DataView(l.buffer,l.byteOffset,l.byteLength),m=new Float64Array(o),h=0;o&&(m[0]=s);for(let e=1;e<o;e++)h+=p.getInt32(4*o+4*(e-1),!0),m[e]=s+h/1e6;let g=Di(l,c,f,4),_=Di(l,c+4*f,o-f,8),v=new Float64Array(o);for(let e=0,t=0,n=0;e<o;e++)v[e]=a.channels[u[e]].size===4?g[t++]:_[n++];return{schemaId:i,index:u,t:m,v,historical:(r&2)!=0}}const ji=[75,82,67,49];function Mi(e){let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Ni(e){if(e.length<56||ji.some((t,n)=>e[n]!==t))throw RangeError(`not a KRC1 chunk`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint16(4,!0);if(n!==1)throw RangeError(`KRC version ${n}`);let r=t.getUint16(6,!0);if(r<56)throw RangeError(`KRC header too short`);return{recordingId:Mi(e.subarray(8,24)),seq:t.getUint32(24,!0),count:t.getUint32(28,!0),bytes:t.getUint32(32,!0),headerBytes:r,t0:t.getFloat64(40,!0),t1:t.getFloat64(48,!0)}}function Pi(e){let t=Ni(e),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=Math.min(e.length,t.bytes),i=[],a=t.headerBytes;for(;i.length<t.count&&a+12<=r;){let t=n.getUint32(a+8,!0);if(a+12+t>r)break;i.push({at:n.getFloat64(a,!0),bytes:e.subarray(a+12,a+12+t)}),a+=12+t}return{header:t,messages:i,truncated:i.length<t.count}}function Fi(e){let t=new Map;return async n=>{if(n.length===0)return null;let r=n[0]&128?2:1;if(n.length<r+12+16)return null;let i=r===2?n[1]:null,a=t.get(i),o=[...a?[a]:[],...e.filter(e=>(e.keyId===i||e.keyId===null)&&e.key!==a).map(e=>e.key)];for(let e of o)try{let a=await li(e,n.subarray(r,r+12),n.subarray(r+12),n.subarray(0,r));return t.set(i,e),{kind:n[0]&-129,plaintext:a}}catch{}return null}}const $=8192;async function*Ii(e){let t=0;for(;t+56<=e.size;){let n=Ni(await e.read(t,56));if(yield await e.slice(t,n.bytes),n.bytes<=56)return;t+=n.bytes}}function Li(e){let t=e.filter(e=>e&&typeof e.t==`number`&&Array.isArray(e.signals)),n={},r={};return t.forEach((e,i)=>{for(let a of e.signals){if(!a||typeof a.name!=`string`)continue;let e=n[a.name]??=new Float64Array(t.length).fill(NaN);e[i]=typeof a.value==`number`?a.value:NaN,a.unit&&!r[a.name]&&(r[a.name]=a.unit)}}),{t:t.map(e=>e.t),columns:n,units:r}}function Ri(e){let t=2166136261^e.length;for(let n=0,r=Math.min(e.length,64);n<r;n++)t=Math.imul(t^e[n],16777619);return t>>>0}const zi=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);var Bi=class{known=new Map;real=new Set;pending=new Set;held=new Set;note(e){for(let t of e){let e=this.known.get(t.name);(!e||t.t>=e.t)&&this.known.set(t.name,{t:t.t,v:t.v,unit:t.unit}),!this.real.has(t.name)&&!this.held.has(t.name)&&this.pending.add(t.name)}}sampled(e){if(this.pending.size+this.held.size===0)return;let t=e=>{(this.pending.delete(e)||this.held.delete(e))&&this.real.add(e)};for(let[n,r]of Object.entries(e.columns))if(!(!this.pending.has(n)&&!this.held.has(n))){for(let e=0;e<r.length;e++)if(Number.isFinite(r[e])){t(n);break}}if(e.events&&e.schema){let{index:n,v:r}=e.events;for(let i=0;i<r.length;i++)Number.isFinite(r[i])&&t(e.schema.channels[n[i]].name)}}start(e){if(this.pending.size===0||e.t.length===0)return e;let t={...e.columns},n={...e.units};for(let e of this.pending){let r=this.known.get(e);t[e]=Float64Array.of(r.v),r.unit&&!n[e]&&(n[e]=r.unit),this.held.add(e)}let r=[...this.pending];return this.pending.clear(),{...e,columns:t,units:n,more:r}}end(e,t){if(e===null||this.held.size===0)return null;let n={},r={};for(let e of this.held){let t=this.known.get(e);n[e]=Float64Array.of(t.v),t.unit&&(r[e]=t.unit)}return{at:t,t:[e],columns:n,units:r}}};async function*Vi(e,t,n,r,i=!1){let a=Fi(e.keys??[]),o=new Map,s=new Map,c=r?null:new Bi,l=null,u=0,d=e=>c?(c.sampled(e),e.t.length&&(l=+e.t[e.t.length-1],u=e.at),c.start(e)):e,f={results:[]};for await(let e of Ii(t)){let{header:t,messages:l}=Pi(e);if(n.t0??=t.t0,i){let e=t.recordingId;f.results.push({rid:e,check:await bi(t,l,a,f.rid===e?(f.seq??-1)+1:0)}),f.rid=e,f.seq=t.seq,n.chain=xi(f.results)}for(let e of l){let t=Ri(e.bytes),i=s.get(t);if(i&&zi(i,e.bytes))continue;s.set(t,e.bytes),s.size>4096&&s.delete(s.keys().next().value);let l=await a(e.bytes);if(!l){n.lost++;continue}try{if(l.kind===5){let e=await wi(l.plaintext);o.set(e.id,e);continue}if(l.kind===4||l.kind===9){let t;if(l.kind===4){let r=await ki(l.plaintext,o);if(!r){n.lost++;continue}t={at:e.at,t:r.block.t,columns:r.block.columns,units:r.block.units??{},historical:r.historical,schema:o.get(r.schemaId)}}else{let r=await Ai(l.plaintext,o);if(!r){n.lost++;continue}t={at:e.at,t:r.t,columns:{},units:{},historical:r.historical,events:{index:r.index,v:r.v},schema:o.get(r.schemaId)}}t.historical&&c?.sampled(t),(r===void 0||r===!!t.historical)&&(yield t.historical?t:d(t));continue}if(r)continue;if(l.kind===7){let e=await Ei(l.plaintext,o);e&&c?.note(e)}else if(l.kind===3){let t=ai(l.plaintext);yield d({at:e.at,t:t.t,columns:t.columns,units:t.units??{}})}else if(l.kind===2){let t=ri(l.plaintext);yield d({at:e.at,...Li(Array.isArray(t?.frames)?t.frames:[])})}}catch{n.lost++}}}let p=c?.end(l,u);p&&(yield p)}function Hi(e,t,n){let r=e===null?t:t===null?e:Math.min(e,t);return r===null?{}:r>1e9?{wallOrigin:String(r),wallQuality:`exact`}:Number.isFinite(n)?{wallOrigin:String(r+n),wallQuality:`approx`}:{}}const Ui={id:`krc`,label:`Kymoscope recording`,extensions:[],sniff:()=>!1,async plan(e,t){let n=[si],r=new Map([[si,`s`]]),i={lost:0,t0:null},a=0,o=!1,s=null,c=null,l=0,u=-1/0,d=0,f=1/0,p=(e,t=``)=>{e!==`ElapsedTime`&&(r.has(e)?!r.get(e)&&t&&r.set(e,t):(n.push(e),r.set(e,t)))},m=new Set;for await(let n of Vi(e,t,i,void 0,!0)){a+=n.t.length,n.historical&&(o=!0);let e=n.t.length;if(e&&n.historical?c??=+n.t[0]:e&&(s??=+n.t[0],+n.t[0]+l<u&&(l=u+Math.max(0,(n.at-d)/1e3)-+n.t[0]),d=n.at,u=+n.t[e-1]+l,f=Math.min(f,n.at/1e3-u)),n.schema){if(!m.has(n.schema.id)){m.add(n.schema.id);for(let e of n.schema.channels)p(e.name,e.unit)}for(let e of n.more??[])p(e,n.units[e])}else for(let e of Object.keys(n.columns))p(e,n.units[e])}let h=n.map(e=>({name:e,unit:r.get(e)??``})),g=i.lost?[`${i.lost} ${i.lost===1?`message`:`messages`} couldn't be opened with the keys this browser has.`]:[],_=i.chain?.broken??0,v=n.length-1,y=v>1e3?[{group:0,channels:n.slice(0,ui+1).map((e,t)=>t)}]:void 0;return y&&g.push(`This recording has ${v.toLocaleString(`en-US`)} channels; the first ${ui.toLocaleString(`en-US`)} are loaded.`),_&&g.push(`Some of this recording was missing, out of order or changed where it is stored (${_} of ${_+(i.chain?.verified??0)} checked ${_+(i.chain?.verified??0)===1?`chunk`:`chunks`}).`),{format:`Kymoscope recording`,startTime:i.t0===null?null:new Date(i.t0).toISOString(),groups:[{name:`Recording`,channels:h,samples:a,time:{kind:`timestamps`},rateHz:null}],meta:{...Hi(s,c,f),...i.chain&&(i.chain.verified||i.chain.broken)?{chainVerified:String(i.chain.verified),chainBroken:String(i.chain.broken),chainUnchecked:String(i.chain.unchecked)}:{}},events:[],notes:g,defaultSelection:y,state:{names:n,backlog:o}}},async*stream(e){let{names:t,backlog:n=!1}=e.plan.state,r=e.selection.find(e=>e.group===0)?.channels??[],i=new Map(r.map((e,n)=>[t[e],n])),a=i.get(si),o=()=>r.map(()=>new Float64Array($).fill(NaN)),s=new Float64Array($),c=o(),l=0,u=0,d=0,f=null,p=()=>{let e={group:0,time:s.slice(0,l),start:u,length:l,columns:c.map(e=>e.slice(0,l))};return u+=l,l=0,s=new Float64Array($),c=o(),e},m=new WeakMap,h=e=>{let t=m.get(e);return t||m.set(e,t=Int32Array.from(e.channels,e=>e.name===`ElapsedTime`?-2:i.get(e.name)??-1)),t};function*g(e,t,n,r){let o=Object.entries(e.columns).flatMap(([e,t])=>{let n=e===`ElapsedTime`?void 0:i.get(e);return n===void 0?[]:[[n,+t[0]]]});for(let i=0;i<e.t.length;i++){let u=r[t[i]];if(u===-1&&!(i===0&&o.length))continue;let m=+e.t[i];if(s[l]=m+d-f,a!==void 0&&(c[a][l]=m),u>=0&&(c[u][l]=n[i]),i===0)for(let[e,t]of o)c[e][l]=t;++l===$&&(yield p())}}function*_(e){let t=e.t.length;if(t&&(f??=+e.t[0]+d),e.events&&e.schema)return yield*g(e,e.events.index,e.events.v,h(e.schema));for(let n=0;n<t;){let r=Math.min(t-n,$-l);for(let t=0;t<r;t++)s[l+t]=+e.t[n+t]+d-f;if(a!==void 0)for(let t=0;t<r;t++)c[a][l+t]=+e.t[n+t];for(let[t,a]of Object.entries(e.columns)){let e=t===`ElapsedTime`?void 0:i.get(t);if(e===void 0)continue;let o=c[e];if(a instanceof Float64Array||a instanceof Float32Array)o.set(a.subarray(n,n+r),l);else for(let e=0;e<r;e++)o[l+e]=+a[n+e]}l+=r,n+=r,l===$&&(yield p())}}for await(let t of Wi(e.files,e.io,n,e.signal))d=t.shift,yield*_(t.b);l>0&&(yield p())}};async function*Wi(e,t,n,r){let i=0,a=-1/0,o=0,s=n?Vi(e,t,{lost:0,t0:null},!0):null,c=async()=>{for(let e=await s?.next();e&&!e.done;e=await s.next())if(e.value.t.length)return e.value;return null},l=await c();for await(let s of Vi(e,t,{lost:0,t0:null},n?!1:void 0)){if(r?.aborted)return;let e=s.t.length;if(e!==0){for(+s.t[0]+i<a&&(i=a+Math.max(0,(s.at-o)/1e3)-+s.t[0]),o=s.at;l&&+l.t[0]<+s.t[0];l=await c())yield{b:l,shift:i};yield{b:s,shift:i},a=+s.t[e-1]+i}}for(;l&&!r?.aborted;l=await c())yield{b:l,shift:i}}const Gi={mdf:Ut,edf:Yt,xdf:cn,tdms:Sn,hdf5:Jn,mat:_r,comtrade:Er,krc:Ui};function Ki(e){let t=Gi[e];if(!t)throw Error(`No importer for format ${e}.`);return t}const qi=`This file's groups do not interleave in time: reading them together would hold too much in memory. Choose fewer groups, or split them.`,Ji=e=>e.length*(1+e.columns.length);function Yi(e){let t=e[Symbol.asyncIterator]();return{pull:async()=>{let e=await t.next();return e.done?null:e.value}}}function Xi(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-=Ji(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+=Ji(o.value))>128e6))throw Error(qi)}};return n.map((e,t)=>({pull:()=>a(t)}))}function Zi(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}const Qi=new Int32Array,$i={t:new Float64Array,cols:[],from:0};function ea(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 ta=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=na(Zi(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(qi)}};function na(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 ra(e,t){let n=e.length,r=e.map(e=>e.t),i=Int32Array.from(e,e=>e.from),a=Int32Array.from(e,e=>ea(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 ia(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 aa(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];ia(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}ia(e,d,u,p,l-1,c[p]),o=c[l-1],t=d[u+l-1]}e.fill(t,o,e.length)}function oa(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 sa(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):Qi}function ca(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=ea(i,e,r.from,i.length),o=new Int32Array(a-r.from);if(c.push(sa(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 oa(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),aa(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 la(e,t,n,r,i,a=!1){let o=e.map((e,r)=>new ta(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=ra(l.map(e=>e.pending[0]??$i),e),n=[t];for(let e=0;e<o.length;e++)n.push(...ca(o[e],t,c[e],u&&c[e],a));d+=t.length,t.length&&await r({length:t.length,columns:n})}return d}var ua=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 da(e,t,n){return ee(await e.plan(t,n))}const fa=(e,t,n)=>Math.max(0,Math.min(e,Math.max(1<<20,n),Math.floor(1e8/t)));function pa(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=Xt(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 ma(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}async function ha(e,t,n,r,i,a,o={}){let s=pa(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=>Yi(d(e.streamGroup({...f,selection:[t]},t.group)))):Xi(d(e.stream(f)),new Map(i.map((e,t)=>[e.group,t]))),m=ma(n,i),h=a===`memory`?new ua(s,fa(m,s.length,r.size)):null,g=0,_=await la(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}}function ga(e){let t=new Set,n=e.columns.map(e=>{if(!(e instanceof Float64Array))return e;let n=e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&!t.has(e.buffer)?e:e.slice();return t.add(n.buffer),n});return[{length:e.length,columns:n},[...t]]}function _a(e,t=Ki){let r=null,i=null,a=null,o=null,s=2,c=null;return async l=>{if(l.type===`ack`){s++;let e=c;c=null,e?.();return}if(l.type===`warm`){Pn();return}let u=setInterval(()=>e({type:`alive`,work:a?.bytesRead??0}),1e3);try{if(l.type===`plan`){r=t(l.importer),i=l.files,a=new n(i.main),o=await da(r,i,a),e({type:`plan`,plan:{...o,state:void 0}});return}a.bytesRead=0;let u=await ha(r,i,o,a,l.selection,l.mode,{progress:t=>e({type:`progress`,fraction:t}),chunk:async t=>{for(;s===0;)await new Promise(e=>{c=e});s--;let[n,r]=ga(t);e({type:`chunk`,chunk:n},r)}});e({type:`done`,result:u},u.table?oi(u.table):[])}catch(t){e({type:`error`,message:E(t).message})}finally{clearInterval(u)}}}const va=self;let ya=null;Mn(async()=>{if(!ya)throw Error(`The import worker was not told where the HDF5 reader is.`);await import(ya);let e=globalThis.__kymoscopeH5wasm;if(!e)throw Error(`HDF5 reader failed to load.`);let{FS:t}=await e.ready,n=0;return async r=>{let i=`/kymo${++n}`;t.mkdir(i),t.mount(t.filesystems.WORKERFS,{files:[r]},i);try{let n=new e.File(`${i}/${r.name}`,`r`);return{root:n,close:()=>{n.close(),t.unmount(i),t.rmdir(i)}}}catch(e){throw t.unmount(i),t.rmdir(i),e}}});const ba=_a((e,t)=>va.postMessage(e,t??[]));va.onmessage=e=>{e.data.type===`init`?ya=e.data.h5Url:ba(e.data)};
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/*! @kymoscope/sdk (c) 2026 Kymoscope. Proprietary software: use requires a license. See LICENSE.md. */
|
|
2
|
-
var e=Symbol(`row`),t=new WeakMap;function n(e){return t.get(e)}function r(e,t){let n=e.keys.lastIndexOf(t);return n<0?void 0:e.values[n]}var i=new WeakMap;function a(n,r){let a=n.keys.join(`
|
|
3
|
-
`),o=r&&i.get(r);if(o&&o.keys===a&&r.length===n.length){o.t=n;let e=new Proxy(o.base,{});return i.set(e,o),t.set(e,n),t.set(r,n),e}let s=Array(n.length),c={t:n,keys:a,base:s},l={};n.keys.forEach((t,n)=>{Object.defineProperty(l,t,{enumerable:!0,configurable:!0,get(){let t=this[e],{values:r,text:i}=c.t,a=r[n][t],o=i[n];return a===a?a:o?o[t]??null:null},set(e){Object.defineProperty(this,t,{value:e,writable:!0,enumerable:!0,configurable:!0})}})});for(let t=0;t<n.length;t++){let n=Object.create(l);n[e]=t,s[t]=n}return i.set(s,c),t.set(s,n),s}function o(e){let t=Array(e.length);for(let n=0;n<e.length;n++){let r={};for(let t=0;t<e.keys.length;t++){let i=e.values[t][n];r[e.keys[t]]=i===i?i:e.text[t]?.[n]??null}t[n]=r}return t}function s(e,t){let n=Number(t?e.replace(`,`,`.`):e);return Number.isFinite(n)?n:null}function c(e,t){let n=e.trim();if(n===``)return null;let r=s(n,t);return r===null?n:r}function l(e,t){if(t===`,`)return!1;let n=0,r=0;for(let i of e)for(let e of d(i,t)){let t=e.trim();/^-?\d+,\d+$/.test(t)?n++:/^-?\d+\.\d+$/.test(t)&&r++}return n>r}function u(e){let t=(e.match(/\t/g)??[]).length,n=(e.match(/;/g)??[]).length,r=0,i=!1;for(let t=0;t<e.length;t++){let n=e[t];n===`"`?i=!i:!i&&n===`,`&&r++}return t>0&&t>=r&&t>=n?` `:n>r?`;`:r>0?`,`:` `}function d(e,t){if(t===` `)return e.split(` `);let n=[],r=``,i=!1;for(let a=0;a<e.length;a++){let o=e[a];i?o===`"`?e[a+1]===`"`?(r+=`"`,a++):i=!1:r+=o:o===`"`?i=!0:o===t?(n.push(r),r=``):r+=o}return n.push(r),n}function f(e,t){let n=0,r=0;for(let i of e){let e=i.trim();e!==``&&(n++,s(e,t)!==null&&r++)}return n>0&&r/n>=.5}function p(e,t,n,r){let i=d(e[t],n);if(f(i,r))return!1;let a=e.slice(t+1,t+11).map(e=>d(e,n));return a.length===0||i.every(e=>e.trim()===``)?!0:i.some((e,t)=>{let n=e.trim();return n!==``&&s(n,r)===null&&f(a.map(e=>e[t]??``),r)})}function m(e,t){if(t===void 0)return!1;let n=e=>/[\t,;]/.test(e);return!n(e)&&n(t)}function h(e){let t=[];for(let n of e.split(/\r\n|\r|\n/)){let e=n.replace(/\uFEFF/g,``).trimEnd();e.length>0&&t.push(e)}return t}function g(e,t){return e.headerRow===t.headerRow&&e.unitsRow===t.unitsRow&&e.dataStartRow===t.dataStartRow}function _(e){let t=[` `,`;`,`,`],n={delim:` `,cols:1,agree:0};for(let r of t){let t=new Map;for(let n of e){let e=d(n,r).length;e>1&&t.set(e,(t.get(e)??0)+1)}for(let[e,i]of t)(i>n.agree||i===n.agree&&e>n.cols)&&(n={delim:r,cols:e,agree:i})}return{delim:n.delim,cols:n.cols}}function v(e){let t=h(e);if(t.length===0)return{headerRow:0,unitsRow:null,dataStartRow:1};let n=t.slice(0,10),{delim:r,cols:i}=_(n),a=e=>d(e,r).length===i,o=e=>d(e,r).every(e=>e.trim()!==``),s=n.findIndex(e=>a(e)&&o(e));s<0&&(s=n.findIndex(a)),(s<0||i<=1)&&(s=0);let c=null,u=s+1;if(t.length>s+1){let e=l(t.slice(s+1,s+11),r);p(t,s+1,r,e)&&(c=s+1,u=s+2)}return{headerRow:s,unitsRow:c,dataStartRow:u}}function y(e,t){let n=e[t]??``,r=d(n,u(n)).map(e=>e.trim());if(r.length===0||r.every(e=>e===``))throw Error(`No column names were found.`);return r}function b(e,t){let{table:n,...r}=x(e,t);return{...r,rows:o(n)}}function x(e,t){let{headerRow:n,unitsRow:r,dataStartRow:i}=t,a=[],o=-1,s=0;for(;s<=e.length&&a.length<i+10;){a.length===i&&o<0&&(o=s);let n=e.indexOf(`
|
|
4
|
-
`,s);n<0&&(n=e.length);let r=e.slice(s,n);if(/\r(?!$)/.test(r))return T(e,t);let c=r.replace(/\uFEFF/g,``).trimEnd();c.length>0&&a.push(c),s=n+1}if(a.length===i&&o<0&&(o=s),o<0)return T(e,t);let f=u(a[n]??``),p=y(a,n),h=[];r!==null&&a[r]!==void 0&&(h=d(a[r],f).map(e=>e.trim())),h.length===0&&(h=p.map(()=>``));let g=l(a.slice(i,i+10),f),_=p.map((e,t)=>e||`col_${t}`),v=_.length,b=1;for(let t=e.indexOf(`
|
|
5
|
-
`,o);t>=0;t=e.indexOf(`
|
|
6
|
-
`,t+1))b++;let x=0;for(let t=e.indexOf(`\r`,o);t>=0;t=e.indexOf(`\r`,t+1))e.charCodeAt(t+1)!==10&&x++;b+=x;let S=_.map(()=>new Float64Array(b)),E=_.map(()=>null),D=0,O=(e,t)=>{typeof t==`number`?S[e][D]=t:(S[e][D]=NaN,t!==null&&((E[e]??=[])[D]=t))},ee=e=>{let t=d(e,f);if(!(t.length===1&&t[0].trim()===``)){for(let e=0;e<v;e++)O(e,t[e]===void 0?null:c(t[e],g));D++}},k=f.charCodeAt(0),A=k!==9&&e.indexOf(`"`,o)>=0||e.indexOf(``,o)>=0||x>0;for(s=o;s<e.length;){let t=e.indexOf(`
|
|
7
|
-
`,s);t<0&&(t=e.length);let n=t;n>s&&e.charCodeAt(n-1)===13&&n--;let r=n>s;if(r){let t=e.charCodeAt(n-1);r=t>32&&t<127}if(r&&A)for(let t=s;t<n;t++){let n=e.charCodeAt(t);if(n===13||n===65279||n===34&&k!==9){r=!1;break}}if(r){let t=s;for(let r=0;r<v;r++){if(t>n){O(r,null);continue}let i=w(e,t,n,k,g);if(i===i){S[r][D]=i,t=C+1;continue}let a=e.indexOf(f,t);(a<0||a>n)&&(a=n),O(r,c(e.slice(t,a),g)),t=a+1}D++}else{let n=e.slice(s,t);for(let e of n.split(/\r\n|\r|\n/)){let t=e.replace(/\uFEFF/g,``).trimEnd();t.length>0&&ee(t)}}s=t+1}let j=S.map(e=>b-D>b/100?e.slice(0,D):e.subarray(0,D));return{meta:a.length>0&&m(a[0],a[1])?a[0]:``,columnNames:p,units:h,table:{keys:_,length:D,values:j,text:E}}}var S=Array.from({length:23},(e,t)=>10**t),C=0;function w(e,t,n,r,i){let a=t,o=e.charCodeAt(a),s=o===45;(s||o===43)&&a++;let c=0,l=0,u=0,d=!1,f=!1;for(;a<n;a++)if(o=e.charCodeAt(a),o>=48&&o<=57){if(d=!0,c===0&&o===48){f&&u++;continue}if(++l>15)return NaN;c=c*10+(o-48),f&&u++}else if((o===46||i&&o===44&&r!==44)&&!f)f=!0;else break;if(!d)return NaN;let p=0;if(a<n&&o!==r){if(o!==101&&o!==69)return NaN;a++,o=e.charCodeAt(a);let t=o===45;(t||o===43)&&a++;let i=a;for(;a<n&&(o=e.charCodeAt(a),o!==r);a++){if(o<48||o>57||p>400)return NaN;p=p*10+(o-48)}if(a===i)return NaN;t&&(p=-p)}let m=p-u,h;if(c===0)h=0;else if(m>=0&&m<=22)h=c*S[m];else if(m<0&&m>=-22)h=c/S[-m];else return NaN;return C=a,s?-h:h}function T(e,t){let n=h(e),{headerRow:r,unitsRow:i,dataStartRow:a}=t,o=u(n[r]??``),s=y(n,r),f=[];i!==null&&n[i]!==void 0&&(f=d(n[i],o).map(e=>e.trim())),f.length===0&&(f=s.map(()=>``));let p=n.slice(a),g=l(p.slice(0,10),o),_=s.map((e,t)=>e||`col_${t}`),v=p.length,b=_.map(()=>new Float64Array(v)),x=_.map(()=>null),S=0;for(let e of p){let t=d(e,o);if(!(t.length===1&&t[0].trim()===``)){for(let e=0;e<_.length;e++){let n=t[e]===void 0?null:c(t[e],g);typeof n==`number`?b[e][S]=n:(b[e][S]=NaN,n!==null&&((x[e]??=[])[S]=n))}S++}}return S<v&&(b=b.map(e=>e.slice(0,S))),{meta:n.length>0&&m(n[0],n[1])?n[0]:``,columnNames:s,units:f,table:{keys:_,length:S,values:b,text:x}}}var E=5e3;function D(e,t){let n=O.get(e);n||O.set(e,n=new Map);let r=n.get(t);return r===void 0&&n.set(t,r=ee(e,t)),r}var O=new WeakMap;function ee(e,t){let r=n(e),i=r?r.keys.lastIndexOf(t):-1;if(r&&i>=0&&!r.text[i]){let e=r.values[i];for(let t=0;t<e.length;t++)if(e[t]===e[t])return!0;return!1}let a=e.length,o=0,s=0,c=Math.max(1,Math.floor(a/E));for(let n=0;n<a;n+=c){let r=e[n][t];r!=null&&(o++,typeof r==`number`&&s++)}if(o===0&&c>1)for(let n=0;n<a&&o<E;n++){let r=e[n][t];r!=null&&(o++,typeof r==`number`&&s++)}return o>0&&s/o>.95}function k(e,t){if(e<=t)return Array.from({length:e},(e,t)=>t);let n=[],r=e/t,i=0;for(let a=0;a<t;a++)n.push(Math.min(e-1,Math.floor(i))),i+=r;return n}var A=[];function j(e){return A.push(e),e}function M(e){for(let t of A)t.delete(e)}function N(e,t,n,r,i,a){let o=(i-r)/a;if(!(i>r)||a<1)return{x0:r,bucket:0,rows:[],columns:n};let s=Math.floor(a);if(te(e))return{x0:r,bucket:o,rows:F(e,t,r,i,o,s),columns:n};let c=new Uint8Array(s),l=t.map(()=>new Float64Array(s).fill(1/0)),u=t.map(()=>new Float64Array(s).fill(-1/0));for(let n=0;n<e.length;n++){let a=e[n];if(!(a>=r&&a<=i))continue;let d=Math.floor((a-r)/o);d>=s&&(d=s-1),c[d]=1;for(let e=0;e<t.length;e++){let r=t[e][n];r===r&&(r<l[e][d]&&(l[e][d]=r),r>u[e][d]&&(u[e][d]=r))}}let d=[];for(let e=0;e<s;e++){if(!c[e])continue;let n={b:e};for(let r=0;r<t.length;r++)l[r][e]!==1/0&&(n[`y${r}lo`]=l[r][e],n[`y${r}hi`]=u[r][e]);d.push(n)}return{x0:r,bucket:o,rows:d,columns:n}}var P=j(new WeakMap);function te(e){let t=P.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}P.set(e,t)}return t}function F(e,t,n,r,i,a){let o=t=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;t(e[i])?n=i+1:r=i}return n},s=o(e=>e<n),c=o(e=>e<=r),l=e=>Math.min(a-1,Math.floor((e-n)/i)),u=t.map((e,t)=>`y${t}lo`),d=t.map((e,t)=>`y${t}hi`),f=[],p=s;for(;p<c;){let n=l(e[p]),r=p,i=1;for(;p+i<c&&l(e[p+i])===n;)r=p+i,i*=2;let a=r+1,o=Math.min(p+i,c);for(;a<o;){let t=a+o>>>1;l(e[t])===n?a=t+1:o=t}let s=a,m={b:n};for(let e=0;e<t.length;e++){let n=t[e],r=1/0,i=-1/0;for(let e=p;e<s;e++){let t=n[e];t<r&&(r=t),t>i&&(i=t)}r!==1/0&&(m[u[e]]=r,m[d[e]]=i)}f.push(m),p=s}return f}function ne(e,t,n,r,i){let a=(r-n)/i,o=new Map;for(let s=0;s<e.length;s++){let c=e[s],l=t[s];if(c<n||c>r||Number.isNaN(l))continue;let u=Math.floor((c-n)/a);u===i&&(u=i-1);let d=o.get(u);d?(l<d.min&&(d.min=l),l>d.max&&(d.max=l),c<d.firstX&&(d.firstX=c,d.firstY=l),c>d.lastX&&(d.lastX=c,d.lastY=l)):(d={min:l,max:l,firstX:c,firstY:l,lastX:c,lastY:l},o.set(u,d))}let s=[...o.keys()].sort((e,t)=>e-t),c=s.length,l={x:new Float64Array(c),min:new Float64Array(c),max:new Float64Array(c),first:new Float64Array(c),last:new Float64Array(c)};for(let e=0;e<c;e++){let t=s[e],r=o.get(t);l.x[e]=n+(t+.5)*a,l.min[e]=r.min,l.max[e]=r.max,l.first[e]=r.firstY,l.last[e]=r.lastY}return l}function I(e,t,n,r,i,a){if(!te(e))return null;let o=t=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;t(e[i])?n=i+1:r=i}return n},s=o(e=>e<r),c=o(e=>e<=i);if(c-s>a)return null;let l=e=>s===0&&c===e.length?e:e.subarray(s,c);return{length:c-s,x:l(e),cols:new Map(n.map((e,n)=>[e,l(t[n])]))}}var L=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);function R(e,t,n=!0){let r=e.getUint32(n?t:t+4,n);return e.getUint32(n?t+4:t,n)*4294967296+r}function re(e,t,n=!0){let r=e.getUint32(n?t:t+4,n);return e.getInt32(n?t+4:t,n)*4294967296+r}var ie=new TextDecoder(`utf-8`),ae=new TextDecoder(`latin1`);function oe(e,t=!1){let n=e.indexOf(0);return(t?ae:ie).decode(n<0?e:e.subarray(0,n))}var se=e=>ae.decode(e),ce=e=>ie.decode(e);function z(e,t,n=0){if(e.length<n+t.length)return!1;for(let r=0;r<t.length;r++)if(e[n+r]!==t.charCodeAt(r))return!1;return!0}var le={id:`mdf`,label:`ASAM MDF (MF4, MDF 3)`,extensions:[`.mf4`,`.mdf`,`.mf3`,`.dat`],companions:[{ext:`.dbc`,anyName:!0}],sniff:e=>z(e,`MDF `)||z(e,`UnFinMF `)},ue={id:`edf`,label:`EDF / BDF (+)`,extensions:[`.edf`,`.bdf`,`.rec`],sniff:e=>z(e,`0 `)||e[0]===255&&z(e,`BIOSEMI`,1)},de={id:`xdf`,label:`XDF (Lab Streaming Layer)`,extensions:[`.xdf`],sniff:e=>z(e,`XDF:`)},fe={id:`tdms`,label:`NI TDMS`,extensions:[`.tdms`],companions:[{ext:`.tdms_index`}],sniff:e=>z(e,`TDSm`)},pe={id:`mat`,label:`MATLAB MAT (v5, v7.3)`,extensions:[`.mat`],sniff:e=>z(e,`MATLAB 5.0 MAT-file`)||z(e,`MATLAB 7.3 MAT-file`)},me=`HDF\r
|
|
8
|
-
|
|
9
|
-
`,he={id:`hdf5`,label:`HDF5`,extensions:[`.h5`,`.hdf5`,`.hdf`,`.he5`,`.nc`],sniff:e=>[0,512,1024,2048].some(t=>z(e,me,t))},ge={id:`comtrade`,label:`COMTRADE (IEEE C37.111)`,extensions:[`.cfg`,`.cff`],companions:[{ext:`.dat`}],sniff:e=>{let t=se(e.subarray(0,512));if(/^---\s*file type:\s*CFG/i.test(t))return!0;let n=t.split(/\r?\n/);return n.length>2&&/^\s*\d+\s*,\s*\d+A\s*,\s*\d+D\s*$/i.test(n[1])}},_e=`This file couldn't be read (it may be damaged).`,ve=1032,ye=e=>e*ve+1024,be=128e6,xe=256,Se=64,Ce=1e3,we=100,Te=200,Ee=(e,t)=>e.length>t?`${e.slice(0,t-1)}…`:e;function De(e){let t=e.notes;for(let n of e.groups){n.name=Ee(String(n.name),xe);for(let e of n.channels)e.name=Ee(String(e.name),xe),e.unit=Ee(String(e.unit??``),Se);Number.isInteger(n.samples)&&n.samples>=-1||(n.samples=-1),n.rateHz===null||Number.isFinite(n.rateHz)&&n.rateHz>0||(n.rateHz=null),n.time.kind===`rate`&&!(Number.isFinite(n.time.rate)&&n.time.rate>0&&Number.isFinite(n.time.start))&&(t.push(`${n.name}: its sample rate in the file is not usable; samples are numbered instead.`),n.time={kind:`index`},n.rateHz=null)}t.length>we&&t.splice(we,t.length-we,`${t.length-we} more notes.`),e.notes=t.map(e=>Ee(String(e),Ce));let n={};for(let[t,r]of Object.entries(e.meta).slice(0,Te))n[Ee(t,xe)]=Ee(String(r),Ce);return e.meta=n,e.events=e.events.filter(e=>Number.isFinite(e.time)).map(e=>({time:e.time,text:Ee(String(e.text),Ce)})),e}function Oe(e){return e instanceof Error&&(e.constructor===Error||e.name===`KymoscopeError`||e.name===`AbortError`)?e:Error(_e)}function ke(e,t=[`Time`]){let n=new Set(t.map(e=>e.toLowerCase())),r=new Map;return e.map(e=>{let t=e.trim()||`Channel`,i=t.toLowerCase(),a=t,o=r.get(i)??2;if(n.has(i)){for(;n.has(`${i} (${o})`);)o++;a=`${t} (${o++})`}return r.set(i,o),n.add(a.toLowerCase()),a})}var B=1<<20,Ae=64,je=16<<20,Me=class{size;bytesRead=0;#e;#t=new Map;constructor(e){this.#e=e,this.size=e.size}async read(e,t){let n=Math.min(this.size,e+t);if(n<=e)return new Uint8Array;if(n-e>B)return this.slice(e,n-e);let r=Math.floor(e/B),i=Math.floor((n-1)/B),a=await this.#n(r);if(r===i)return a.subarray(e-r*B,n-r*B);let o=new Uint8Array(n-e),s=a.subarray(e-r*B);return o.set(s),o.set((await this.#n(i)).subarray(0,n-i*B),s.length),o}async slice(e,t){let n=Math.min(this.size,e+t);if(n<=e)return new Uint8Array;let r=new Uint8Array(await this.#e.slice(e,n).arrayBuffer());return this.bytesRead+=r.length,r}async*windows(e,t,n=je){let r=Math.min(this.size,e+t);for(let t=e;t<r;t+=n)yield{offset:t,bytes:await this.slice(t,Math.min(n,r-t))}}async#n(e){let t=this.#t.get(e);if(t)return this.#t.delete(e),this.#t.set(e,t),t;let n=await this.slice(e*B,B);return this.#t.size>=Ae&&this.#t.delete(this.#t.keys().next().value),this.#t.set(e,n),n}},Ne=`kymoscope-live-key-check-v1`,Pe=6e5,Fe=`kymoscope-open-stream-v1`;function V(){let e=globalThis.crypto;if(!e?.subtle)throw Error(`WebCrypto SubtleCrypto is not available`);return e.subtle}function H(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function U(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Ie(e){return H(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Le(e){return U(e.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(Math.ceil(e.length/4)*4,`=`))}function Re(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return t}function ze(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),H(e)}async function Be(e,t){let n=new TextEncoder,r=await V().importKey(`raw`,n.encode(e),`PBKDF2`,!1,[`deriveKey`]);return V().deriveKey({name:`PBKDF2`,salt:U(t),iterations:Pe,hash:`SHA-256`},r,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function Ve(e,t){let n=await V().importKey(`raw`,new TextEncoder().encode(e),`PBKDF2`,!1,[`deriveBits`]),r=await V().deriveBits({name:`PBKDF2`,salt:U(t),iterations:Pe,hash:`SHA-256`},n,256);return H(new Uint8Array(r))}var He=null,Ue=0;function We(){(!He||Ue>4294967295)&&(He=globalThis.crypto.getRandomValues(new Uint8Array(8)),Ue=0);let e=new Uint8Array(12);return e.set(He),new DataView(e.buffer).setUint32(8,Ue++),e}async function Ge(e,t){let n=We(),r=new TextEncoder().encode(JSON.stringify(t)),i=await V().encrypt({name:`AES-GCM`,iv:n},e,r);return{iv:H(n),ciphertext:H(new Uint8Array(i))}}async function Ke(e,t){let n=U(t.iv),r=U(t.ciphertext),i=await V().decrypt({name:`AES-GCM`,iv:n},e,r);return new Uint8Array(i)}async function qe(e,t,n,r){let i=await V().decrypt({name:`AES-GCM`,iv:t,additionalData:r},e,n);return new Uint8Array(i)}async function Je(e,t){return JSON.parse(new TextDecoder().decode(await Ke(e,t)))}async function Ye(e){return Ge(e,Ne)}async function Xe(e,t){try{return await Je(e,t)===Ne}catch{return!1}}async function Ze(e){let t=await V().digest(`SHA-256`,new TextEncoder().encode(e));return Re(new Uint8Array(t))}function Qe(){let e=e=>{let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Ie(t)},t=`kymoscope_${e(24)}.${e(32)}`;return{token:t,prefix:t.slice(0,12)}}var $e=/^((?:kymoscope|prism)_[A-Za-z0-9_-]+)(?:\.([A-Za-z0-9_-]+))?$/;function et(e){let t=$e.exec(e.trim());return t?{auth:t[1],secret:t[2]??null}:{auth:e,secret:null}}var tt=new TextEncoder().encode(`kymoscope-device-wrap-v1`);async function nt(){let e=await V().generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveBits`]),t=new Uint8Array(await V().exportKey(`raw`,e.publicKey));return{privateKey:e.privateKey,publicKey:H(t)}}async function rt(e,t){let n=new Uint8Array(e.length+tt.length);return n.set(e),n.set(tt,e.length),V().importKey(`raw`,await V().digest(`SHA-256`,n),`AES-GCM`,!1,t)}async function it(e,t,n){let r=await V().importKey(`raw`,U(t.epk),{name:`ECDH`,namedCurve:`P-256`},!1,[]),i=new Uint8Array(await V().deriveBits({name:`ECDH`,public:r},e,256));return new Uint8Array(await V().decrypt({name:`AES-GCM`,iv:U(t.iv),additionalData:new TextEncoder().encode(n)},await rt(i,[`decrypt`]),U(t.ct)))}function at(e,t,n){return ot(e,t,n)}async function ot(e,t,n,r,i){let a=await V().importKey(`raw`,U(e),{name:`ECDH`,namedCurve:`P-256`},!1,[]),o=r??await V().generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveBits`]),s=new Uint8Array(await V().deriveBits({name:`ECDH`,public:a},o.privateKey,256)),c=i??We(),l=new Uint8Array(await V().encrypt({name:`AES-GCM`,iv:c,additionalData:new TextEncoder().encode(n)},await rt(s,[`encrypt`]),t));return{epk:H(new Uint8Array(await V().exportKey(`raw`,o.publicKey))),iv:H(c),ct:H(l)}}async function st(e,t,n,r){return pt(await it(e,t,`${n}|${r}`))}var ct=new TextEncoder().encode(`kymoscope-sender-bind-v1`),lt=(e,t,n)=>`project:${e}:${t}|${n}`,ut=(e,t,n)=>`live_stream:${e}|${t}:${n}`,dt=(e,t,n)=>`bind:${e}|${t}:${n}`;function ft(){return globalThis.crypto.getRandomValues(new Uint8Array(32))}function pt(e){return V().importKey(`raw`,e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}function mt(e,t,n){return ht(e,t,n)}async function ht(e,t,n,r){let i=r??We(),a=await V().importKey(`raw`,e,`AES-GCM`,!1,[`encrypt`]),o=new Uint8Array(await V().encrypt({name:`AES-GCM`,iv:i,additionalData:new TextEncoder().encode(n)},a,t));return{iv:H(i),ct:H(o)}}async function gt(e,t,n){let r=await V().importKey(`raw`,e,`AES-GCM`,!1,[`decrypt`]);return new Uint8Array(await V().decrypt({name:`AES-GCM`,iv:U(t.iv),additionalData:new TextEncoder().encode(n)},r,U(t.ct)))}async function _t(e){let t=new TextEncoder().encode(e),n=new Uint8Array(t.length+ct.length);return n.set(t),n.set(ct,t.length),new Uint8Array(await V().digest(`SHA-256`,n))}async function vt(e,t,n){let r=await V().importKey(`raw`,e,{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]);return H(new Uint8Array(await V().sign(`HMAC`,r,new TextEncoder().encode(`sender|${t}|${n}`))))}async function yt(e,t,n,r){let i;try{i=U(r)}catch{return!1}let a=await V().importKey(`raw`,e,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);return V().verify(`HMAC`,a,i,new TextEncoder().encode(`sender|${t}|${n}`))}async function bt(e){let t=Re(new Uint8Array(await V().digest(`SHA-256`,U(e)))).slice(0,16).toUpperCase();return`${t.slice(0,4)}-${t.slice(4,8)}-${t.slice(8,12)}-${t.slice(12,16)}`}var xt=`kymoscope-workbook-export-v2`,St=(e,t)=>`workbook:${e}:${t}`,Ct=(e,t,n)=>`workbook:${e}|${t}:${n}`,wt=(e,t)=>`project_config:${e}|${e}:${t}`,Tt=(e,t,n)=>`alert_rule:${e}:${t}|${n}`,Et=(e,t,n)=>`alert_event:${e}:${t}|${n}`,Dt=(e,t)=>`kymoscope-recovery-key-v1|${e}|${t}`,Ot=(e,t,n)=>`recovery:${e}|${t}:${n}`;function kt(e,t,n){return At(e,t,n)}async function At(e,t,n,r){let i=r??We(),a=new Uint8Array(await V().encrypt({name:`AES-GCM`,iv:i,additionalData:new TextEncoder().encode(n)},e,t));return{iv:H(i),ct:H(a)}}async function jt(e,t,n){return new Uint8Array(await V().decrypt({name:`AES-GCM`,iv:U(t.iv),additionalData:new TextEncoder().encode(n)},e,U(t.ct)))}function Mt(e,t,n){return Nt(e,t,n)}async function Nt(e,t,n,r,i){let a=H(r??globalThis.crypto.getRandomValues(new Uint8Array(16))),o=await At(await Be(e,a),t,n,i);return{kdf:{name:`PBKDF2`,hash:`SHA-256`,iterations:Pe,salt:a},...o}}async function Pt(e,t,n){let r=t?.kdf;if(r?.name!==`PBKDF2`||r.hash!==`SHA-256`||r.iterations!==Pe||typeof r.salt!=`string`)throw Error(`unsupported_kdf`);return jt(await Be(e,r.salt),t,n)}var Ft=`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`;function It(e){let t=0,n=0,r=``;for(let i of e)for(n=(n<<8|i)&1048575,t+=8;t>=5;)r+=Ft[n>>>t-5&31],t-=5;return t>0&&(r+=Ft[n<<5-t&31]),r.match(/.{1,4}/g).join(`-`)}function Lt(e){let t=e.toUpperCase().replace(/[^A-Z2-7]/g,``);if(t.length!==52)return null;let n=[],r=0,i=0;for(let e of t)i=(i<<5|Ft.indexOf(e))&4095,r+=5,r>=8&&(n.push(i>>>r-8&255),r-=8);return n.length===32?new Uint8Array(n):null}async function Rt(){let e=await V().generateKey({name:`ECDH`,namedCurve:`P-256`},!0,[`deriveBits`]),t=await V().exportKey(`jwk`,e.privateKey),n=new Uint8Array(await V().exportKey(`raw`,e.publicKey));return{d:Le(t.d),publicKey:H(n)}}function zt(e,t){let n=U(t);return V().importKey(`jwk`,{kty:`EC`,crv:`P-256`,ext:!1,x:Ie(n.subarray(1,33)),y:Ie(n.subarray(33,65)),d:Ie(e)},{name:`ECDH`,namedCurve:`P-256`},!1,[`deriveBits`])}var Bt=j(new WeakSet),Vt={length:0,x:new Float64Array,cols:new Map};function Ht(e,t,n,r){let i=t.length,a=t.map((e,t)=>`y${t}lo`),o=t.map((e,t)=>`y${t}hi`),s=new Uint8Array(e.length),c=0;for(let t=0;t<e.length;t++){let n=e[t];for(let e=0;e<i;e++){let r=n[o[e]];if(r!=null&&Number(r)!==Number(n[a[e]])){s[t]=1;break}}c+=1+s[t]}let l=new Float64Array(c),u=t.map(()=>new Float64Array(c).fill(NaN)),d,f=0,p=null;for(let t=0;t<e.length;t++){let m=e[t],h=n+(Number(m.b)+.5)*r,g=Number(m.pass??0);p!==null&&g!==p&&((d??=new Uint8Array(c))[f]=1),p=g,l[f]=h;for(let e=0;e<i;e++){let t=m[a[e]];t!=null&&(u[e][f]=Number(t))}if(f++,s[t]){l[f]=h;for(let e=0;e<i;e++){let t=m[o[e]];t!=null&&(u[e][f]=Number(t))}f++}}return{length:c,x:l,brk:d,cols:new Map(t.map((e,t)=>[e,u[t]]))}}function Ut(e,t){if(t>=e.length)return e;let n=new Map;for(let[r,i]of e.cols)n.set(r,i.subarray(0,t));return{length:t,x:e.x.subarray(0,t),brk:e.brk?.subarray(0,t),cols:n}}function Wt(e,t,n,r,i){let a=[];for(let o of new Set(e)){let e=t(o);if(!e||!(e.t<r))continue;let s=Math.max(n,e.t);s<i&&a.push({c:o,a:s,v:e.v})}if(a.length===0)return null;a.sort((e,t)=>e.a-t.a);let o=a.length+1,s=new Float64Array(o),c=new Map;return a.forEach((e,t)=>{let n=new Float64Array(o).fill(NaN);n[t]=n[o-1]=e.v,c.set(e.c,n),s[t]=e.a}),s[o-1]=i,{length:o,x:s,cols:c,hold:!0}}function Gt(e,t){if(t===void 0||e.length===0||e.x[e.length-1]<=t)return e;let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e.x[i]<=t?n=i+1:r=i}return Ut(e,n)}function Kt(e,t,n){let r=(t,n)=>{let r=0,i=e.length;for(;r<i;){let a=r+i>>1;(n?e.x[a]<=t:e.x[a]<t)?r=a+1:i=a}return r},i=r(t,!1),a=r(n,!0);if(i===0&&a===e.length)return e;let o=new Map;for(let[t,n]of e.cols)o.set(t,n.subarray(i,a));return{length:a-i,x:e.x.subarray(i,a),brk:e.brk?.subarray(i,a),cols:o}}function qt(e,t){let n=[];for(let r=0;r<e.length;r++)t(e.x[r])&&n.push(r);if(n.length===e.length)return e;let r=(e,t)=>{for(let r=0;r<n.length;r++)t[r]=e[n[r]];return t},i=new Map;for(let[t,a]of e.cols)i.set(t,r(a,new Float64Array(n.length)));return{length:n.length,x:r(e.x,new Float64Array(n.length)),brk:e.brk&&r(e.brk,new Uint8Array(n.length)),cols:i}}function Jt(e,t,i,a,o=``,s=0){let c=n(e),l=k(e.length,a),u=t=>{let n=c&&r(c,t);return n?e=>n[e]:n=>{let r=e[n][t];return typeof r==`number`?r:NaN}},d=u(t),f=[];for(let e of l)Number.isNaN(d(e))||f.push(e);let p=f.length,m=p===e.length&&s===0,h=c&&r(c,t),g=m&&h?h:Float64Array.from(f,e=>d(e)+s),_=new Map;for(let e of i){let t=c&&r(c,e);if(c&&!t)continue;if(m&&t){_.set(e+o,t);continue}let n=u(e),i=Float64Array.from(f,n);!t&&!i.some(e=>!Number.isNaN(e))||_.set(e+o,i)}return{length:p,x:g,cols:_}}function Yt(e,t,n){if(!t&&n===0)return e;let r=e.x;if(n!==0){r=new Float64Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.x[t]+n}let i=new Map;for(let[n,r]of e.cols)i.set(n+t,r);return{length:e.length,x:r,brk:e.brk,cols:i}}function Xt(e){let t=e.filter(e=>e.length>0);if(t.length===0)return Vt;if(t.length===1)return t[0];let n=t.reduce((e,t)=>e+t.length,0),r=new Float64Array(n),i=new Set;for(let e of t)for(let t of e.cols.keys())i.add(t);let a=new Map;for(let e of i)a.set(e,new Float64Array(n).fill(NaN));let o,s=0;for(let e of t){r.set(e.x,s),e.brk&&(o??=new Uint8Array(n)).set(e.brk,s);for(let[t,n]of e.cols)a.get(t).set(n,s);s+=e.length}return{length:n,x:r,brk:o,cols:a}}var W=64,Zt=class{nc;bucket;b;lo;hi;start=0;end=0;rowP;px=new Float64Array;pv=[];pStart=0;pEnd=0;mStart=0;mEnd=0;dirty=1/0;dirtyFront=-1;invalid=!0;constructor(e,t,n=1024){this.nc=e,this.bucket=t,this.b=new Float64Array(n),this.rowP=new Float64Array(n),this.lo=Array.from({length:e},()=>new Float64Array(n)),this.hi=Array.from({length:e},()=>new Float64Array(n))}get count(){return this.end-this.start}lowerBound(e){let t=this.start,n=this.end;for(;t<n;){let r=t+n>>>1;this.b[r]<e?t=r+1:n=r}return t}relocate(e,t){let n=this.count,r=n=>{if(t===n.length&&e<=this.start)return n.copyWithin(e,this.start,this.end),n;let r=new Float64Array(t);return r.set(n.subarray(this.start,this.end),e),r};this.b=r(this.b),this.rowP=r(this.rowP),this.lo=this.lo.map(r),this.hi=this.hi.map(r);let i=e-this.start;this.mStart+=i,this.mEnd+=i,this.dirty!==1/0&&(this.dirty+=i),this.dirtyFront>=0&&(this.dirtyFront+=i),this.start=e,this.end=e+n}touch(e){e===this.start&&e+1<this.mEnd?this.dirtyFront=e:e<this.dirty&&(this.dirty=e)}clearRow(e){for(let t=0;t<this.nc;t++)this.lo[t][e]=NaN,this.hi[t][e]=NaN;this.touch(e)}row(e){let t=this.end;if(t>this.start&&this.b[t-1]===e)return t-1;if(t===this.start||e>this.b[t-1])return t===this.b.length&&(this.start>this.count?this.relocate(0,this.b.length):this.relocate(0,Math.max(1024,this.b.length*2))),this.b[this.end]=e,this.clearRow(this.end),this.end++;let n=this.lowerBound(e);if(this.b[n]===e)return n;if(n!==this.start){this.end===this.b.length&&(this.start>this.count?this.relocate(0,this.b.length):this.relocate(0,Math.max(1024,this.b.length*2)),n=this.lowerBound(e));let t=e=>e.copyWithin(n+1,n,this.end);return t(this.b),t(this.rowP),this.lo.forEach(t),this.hi.forEach(t),this.end++,n<this.mEnd&&this.mEnd++,this.dirty!==1/0&&this.dirty>=n&&this.dirty++,this.b[n]=e,this.clearRow(n),n}if(this.start===0){let e=Math.max(1024,this.count);this.relocate(e,2*e+this.count)}return this.start--,this.b[this.start]=e,this.clearRow(this.start),this.invalid=!0,this.start}coarsen(e){let t=new Int32Array(this.end-this.start),n=this.start-1;for(let r=this.start;r<this.end;r++){let i=Math.floor(this.b[r]/e);(n<this.start||this.b[n]!==i)&&(this.b[++n]=i),t[r-this.start]=n}for(let e=0;e<this.nc;e++){let n=this.lo[e],r=this.hi[e],i=-1;for(let e=this.start;e<this.end;e++){let a=t[e-this.start],o=n[e],s=r[e];if(a!==i){n[a]=o,r[a]=s,i=a;continue}o===o&&(n[a]<=o||(n[a]=o),r[a]>=s||(r[a]=s))}}this.end=n+1,this.bucket*=e,this.dirty=1/0,this.dirtyFront=-1,this.invalid=!0}dropBelow(e){this.start=this.lowerBound(e),this.start===this.end&&(this.start=this.end=0,this.invalid=!0)}reset(e){this.clearRow(e)}fold(e,t,n,r){this.touch(e);for(let i=0;i<t.length;i++){let a=t[i],o=1/0,s=-1/0;for(let e=n;e<r;e++){let t=a[e];t<o&&(o=t),t>s&&(s=t)}if(o===1/0)continue;let c=this.lo[i],l=this.hi[i],u=c[e],d=l[e];c[e]=u<=o?u:o,l[e]=d>=s?d:s}}toRows(e,t,n,r,i){let a=[];for(let o=e;o<t;o++){let e={...n,b:this.b[o],pass:0};for(let t=0;t<this.nc;t++){let n=this.lo[t][o];n===n&&(e[r[t]]=n,e[i[t]]=this.hi[t][o])}a.push(e)}return a}pointsOf(e){for(let t=0;t<this.nc;t++){let n=this.hi[t][e];if(n===n&&n!==this.lo[t][e])return 2}return 1}writeRow(e,t,n){let r=(this.b[e]+.5)*this.bucket;this.px[t]=r;for(let n=0;n<this.nc;n++)this.pv[n][t]=this.lo[n][e];if(n===2){this.px[t+1]=r;for(let n=0;n<this.nc;n++)this.pv[n][t+1]=this.hi[n][e]}}reserve(e){if(this.pEnd+e<=this.px.length)return;let t=this.pEnd-this.pStart,n=W-this.pStart,r=2*(t+e+W)<=this.px.length,i=r?this.px.length:Math.max(4*this.b.length+W,2*(t+e+W)),a=e=>{if(r)return e.copyWithin(W,this.pStart,this.pEnd),e;let t=new Float64Array(i);return t.set(e.subarray(this.pStart,this.pEnd),W),t};this.px=a(this.px),this.pv=this.pv.map(a);for(let e=this.mStart;e<this.mEnd;e++)this.rowP[e]+=n;this.pStart=W,this.pEnd=W+t}writeFrom(e){this.mEnd=e;for(let t=e;t<this.end;t++){let e=this.pointsOf(t);this.reserve(e),this.rowP[t]=this.pEnd,this.writeRow(t,this.pEnd,e),this.pEnd+=e,this.mEnd=t+1}}writeAll(){let e=this.start,t=this.count,n=new Uint8Array(t);for(let r=0;r<this.nc;r++){let i=this.lo[r],a=this.hi[r];for(let r=0;r<t;r++){let t=a[e+r];t===t&&t!==i[e+r]&&(n[r]=1)}}let r=0;for(let e=0;e<t;e++)r+=1+n[e];this.pStart=this.pEnd=W,this.mStart=this.mEnd=e,this.reserve(r);let i=W;for(let r=0;r<t;r++){let t=(this.b[e+r]+.5)*this.bucket;this.rowP[e+r]=i,this.px[i]=t,n[r]&&(this.px[i+1]=t),i+=1+n[r]}for(let r=0;r<this.nc;r++){let i=this.lo[r],a=this.hi[r],o=this.pv[r];for(let r=0;r<t;r++){let t=this.rowP[e+r];o[t]=i[e+r],n[r]&&(o[t+1]=a[e+r])}}this.pEnd=i,this.mEnd=this.end}sync(){if(this.pv.length!==this.nc&&(this.pv=Array.from({length:this.nc},()=>new Float64Array)),this.invalid||this.start<this.mStart||this.start>=this.mEnd)this.writeAll();else{this.start>this.mStart&&(this.mStart=this.start,this.pStart=this.rowP[this.start]);let e=Math.max(this.start,Math.min(this.dirty,this.mEnd)),t=this.dirtyFront;if(t===this.start)if(t+1<e){let e=this.pointsOf(t),n=this.rowP[t+1]-e;if(n<0)return this.invalid=!0,this.sync();this.rowP[t]=n,this.pStart=n,this.writeRow(t,n,e)}else e=t;e<this.end&&(e<this.mEnd&&(this.pEnd=this.rowP[e]),this.writeFrom(e))}this.dirty=1/0,this.dirtyFront=-1,this.invalid=!1}toPoints(e,t,n){this.sync();let r=e<t?this.rowP[e]:0,i=e<t?t<this.mEnd?this.rowP[t]:this.pEnd:0;return{length:i-r,x:this.px.subarray(r,i),cols:new Map(n.map((e,t)=>[e,this.pv[t].subarray(r,i)]))}}};function Qt(e){if(!(e>0)||!Number.isFinite(e))return e;let t=10**Math.floor(Math.log10(e)),n=e/t;return(n<1.5?1:n<3.5?2:n<7.5?5:10)*t}var $t=4e6,en=60,tn=32,nn=4;function rn(e,t,n,r,i){if(n instanceof Float64Array||n instanceof Float32Array)e.set(n.subarray(r,r+i),t);else for(let a=0;a<i;a++)e[t+a]=+n[r+a]}function an(e,t){let n=e.t.length,r=Object.keys(e.columns).filter(e=>e!==t);for(let t of r)if(e.columns[t].length!==n)throw RangeError(`live column "${t}" has ${e.columns[t].length} values for ${n} times`);return r}var on=`ElapsedTime`,sn=[];function cn(e){let t=sn[e];if(!t){let n=Array.from({length:e},(e,t)=>`y${t}lo`),r=Array.from({length:e},(e,t)=>`y${t}hi`);t={lo:n,hi:r,row:JSON.parse(JSON.stringify(Object.fromEntries([[`b`,0],[`pass`,0],...n.flatMap((e,t)=>[[e,null],[r[t],null]])])))},sn[e]=t}return t}var ln=4096,un=4,dn=class{time;alloc;maxBytes;cols=new Map;head=0;count=0;full=!1;pushed=0;clears=0;pushedBefore=0;signalOrder=[];unitByName=new Map;capacity;timeColumn;timeUnit;lastBackAbs=-1;get timeMonotonic(){return this.lastBackAbs<=this.pushed-this.size}lastPushT=-1/0;decCache=null;passTrack=null;prevCyclePts=null;curCyclePts=null;trackers=new Map;debugLastScan=0;debugGrowCopied=0;timeDecs=new Map;mirrors=new Map;historyDec=null;snapDec=null;latest=new Map;listed=new Map;constructor(e,t=on,n=`s`,r=1/0){this.capacity=Math.max(2,Math.floor(e)),this.timeColumn=t,this.timeUnit=n,this.maxBytes=r,this.alloc=Math.min(this.capacity,ln),this.time=new Float64Array(this.alloc)}get maxSamples(){return this.capacity}newColumn(){if(this.growing)try{return new Float64Array(this.growing.next).fill(NaN)}catch(e){this.refused(e)}return new Float64Array(this.alloc).fill(NaN)}growing=null;stepGrow(e){if(this.full)return;if(!this.growing){if(this.count<this.alloc*.75||this.alloc>=this.capacity)return;let e=Math.min(this.capacity,this.alloc*2);if(e*8*(1+this.cols.size)>this.maxBytes)return;this.growing={next:e,todo:[null,...this.cols.keys()],owed:0}}let t=this.growing;t.owed+=t.todo.length*e/Math.max(1,this.alloc-this.count),this.moveColumns(Math.floor(t.owed))}moveColumns(e){let t=this.growing;for(;e>0&&t.todo.length>0;e--,t.owed--){let e=t.todo.pop(),n=e===null?this.time:this.cols.get(e);if(!n||n.length>=t.next)continue;let r;try{r=new Float64Array(t.next)}catch(e){this.refused(e);return}r.set(n),this.debugGrowCopied+=n.length,e===null?this.time=r:this.cols.set(e,r)}t.todo.length===0&&(this.alloc=t.next,this.growing=null)}growNow(){this.growing?this.moveColumns(1/0):this.grow()}grow(){let e=Math.min(this.capacity,this.alloc*2);if(e*8*(1+this.cols.size)>this.maxBytes){this.capacity=this.alloc;return}let t=t=>{let n=new Float64Array(e);return n.set(t),this.debugGrowCopied+=t.length,n};try{this.time=t(this.time);for(let[e,n]of this.cols)this.cols.set(e,t(n))}catch(e){this.refused(e);return}this.alloc=e}refused(e){if(!(e instanceof RangeError))throw e;this.capacity=this.alloc,this.growing=null}get version(){return this.pushedBefore+this.pushed+this.clears}get size(){return this.full?this.capacity:this.count}push(e){for(let[t,n]of this.trackers){let r=t===this.timeColumn?e.t:e.signals.find(e=>e.name===t)?.value;r!==void 0&&Number.isFinite(r)&&this.advanceCycle(t,n,r,this.pushed)}let t=this.lastPushT;this.lastPushT=Math.max(t,e.t),!this.full&&this.count===this.alloc&&(this.growNow(),this.count===this.capacity&&(this.full=!0));let n=this.full?this.head:this.count;this.time[n]=e.t;for(let e of this.signalOrder)this.cols.get(e)[n]=NaN;for(let t of e.signals){if(this.computed.has(t.name))continue;let r=this.cols.get(t.name);r?t.unit&&t.unit!==this.unitByName.get(t.name)&&(this.unitByName.get(t.name)&&this.dropColumnSamples(t.name,r),this.unitByName.set(t.name,t.unit)):(r=this.newColumn(),this.cols.set(t.name,r),this.signalOrder.push(t.name),this.listed.delete(t.name),this.unitByName.set(t.name,t.unit??``)),r[n]=t.value,Number.isFinite(t.value)&&this.noteValue(t.name,e.t,t.value)}this.pushed++,this.full?this.head=(this.head+1)%this.capacity:(this.count++,this.count===this.capacity&&(this.full=!0)),this.stepGrow(1),e.t<t&&this.placeLate(t,e.t,1,!0,this.pushed-1)}pushColumns(e){let t=e.t,n=t.length,r=an(e,this.timeColumn);if(n===0)return;if(this.trackers.size>0){for(let i=0;i<n;i++)this.push({t:t[i],signals:r.map(t=>({name:t,unit:e.units?.[t],value:e.columns[t][i]}))});return}for(let t of r){if(this.computed.has(t))continue;let n=e.units?.[t],r=this.cols.get(t);r?n&&n!==this.unitByName.get(t)&&(this.unitByName.get(t)&&this.dropColumnSamples(t,r),this.unitByName.set(t,n)):(this.cols.set(t,this.newColumn()),this.signalOrder.push(t),this.listed.delete(t),this.unitByName.set(t,n??``))}for(let i of r){if(this.computed.has(i))continue;let r=e.columns[i];for(let e=n-1;e>=0;e--)if(Number.isFinite(r[e])){this.noteValue(i,+t[e],r[e]);break}}let i=this.lastPushT,a=1/0,o=-1/0,s=!0,c=-1;for(let e=0;e<n;e++){let n=+t[e];n<(e>0?+t[e-1]:i)&&(c=e,e>0&&(s=!1)),n<a&&(a=n),n>o&&(o=n)}let l=this.pushed+c;this.lastPushT=Math.max(i,o);let u=Math.max(0,n-this.capacity);for(this.pushed+=u;u<n;){!this.full&&this.count===this.alloc&&(this.growNow(),this.count===this.capacity&&(this.full=!0));let r=this.full?this.head:this.count,i=Math.min(n-u,this.full?this.capacity-this.head:this.alloc-this.count);rn(this.time,r,t,u,i);for(let t of this.signalOrder){let n=this.cols.get(t),a=this.computed.has(t)?void 0:e.columns[t];a?rn(n,r,a,u,i):n.fill(NaN,r,r+i)}this.pushed+=i,u+=i,this.full?this.head=(this.head+i)%this.capacity:(this.count+=i,this.count===this.capacity&&(this.full=!0))}this.stepGrow(Math.min(n,this.capacity)),c>=0&&this.placeLate(i,a,Math.min(n,this.capacity),s,l)}placeLate(e,t,n,r,i){if(e-t>en){this.steppedBack(i);return}let a=this.size,o=a-n,s=e=>this.full?(this.head+e)%this.capacity:e,c=0,l=o;for(;c<l;){let e=c+l>>>1;this.time[s(e)]<=t?c=e+1:l=e}r||(c=Math.min(c,o));let u=a-c;if(u<2)return;if(u*(this.cols.size+1)>$t||!this.timeMonotonic){this.steppedBack(i);return}let d=new Float64Array(u);for(let e=0;e<u;e++)d[e]=this.time[s(c+e)];let f=new Uint32Array(u);for(let e=0;e<u;e++)f[e]=e;f.sort((e,t)=>d[e]-d[t]||e-t);let p=new Set;for(let t=u-n;t<u;t++)if(!(t<0||d[t]>=e))for(let[e,n]of this.cols)Number.isFinite(n[s(c+t)])&&p.add(e);let m=[],h=this.snapDec;h&&h.key===`${this.signalOrder.join(`
|
|
10
|
-
`)}|${this.clears}`?m.push({k:h,names:this.signalOrder,ycols:this.signalOrder.map(e=>this.cols.get(e)),drop:()=>{this.snapDec===h&&(this.snapDec=null)}}):this.snapDec=null;for(let[e,t]of this.timeDecs)for(let n of t)m.push({k:n,names:n.cols,ycols:n.cols.map(e=>this.cols.get(e)),drop:()=>{let t=(this.timeDecs.get(e)??[]).filter(e=>e!==n);t.length>0?this.timeDecs.set(e,t):this.timeDecs.delete(e)}});let g=m.filter(e=>{let t=this.pushed-n-e.k.pushed;try{if(t<0||t>o||t*e.ycols.length>$t)throw Error(`behind`);return t>0&&(this.foldBuckets(e.k.store,o-t,o,e.k.bucket,e.ycols),e.k.pushed+=t),!0}catch{return e.drop(),!1}}),_=new Float64Array(u),v=e=>{for(let t=0;t<u;t++)_[t]=e[s(c+f[t])];for(let t=0;t<u;t++)e[s(c+t)]=_[t]};v(this.time);for(let e of this.cols.values())v(e);let y=this.pushed-a+c;this.decCache&&this.decCache.pushed>y&&(this.decCache.pushed=y);let b=this.passTrack;if(b&&b.done>y){b.cuts=b.cuts.filter(e=>e.abs<y),b.done=y,b.prevX=NaN;let e=this.cols.get(b.key);for(let t=y-1;e&&t>=this.pushed-a;t--){let n=e[this.physOf(t)];if(!Number.isNaN(n)){b.prevX=n;break}}}for(let t of g)if(t.names.some(e=>p.has(e)))try{for(let r=0;r<u;r++){if(f[r]<u-n||d[f[r]]>=e)continue;let i=s(c+r),a=Math.floor(this.time[i]/t.k.bucket);a>=t.k.fromB&&t.k.store.fold(t.k.store.row(a),t.ycols,i,i+1)}}catch{t.drop()}this.historyDec=null;for(let e of this.mirrors.values())e.end=Math.max(e.first,Math.min(e.end,y)),e.view=null;for(let[e,t]of this.boundsCache)t.loAbs>=y||t.hiAbs>=y?this.boundsCache.delete(e):(t.done=Math.min(t.done,y),t.version=-1)}steppedBack(e){this.lastBackAbs=e,this.timeDecs.clear(),this.snapDec=null}dropColumnSamples(e,t){t.fill(NaN),this.decCache=null,this.timeDecs.clear(),this.snapDec=null;for(let t of this.trackers.values())t.previous?.cols.delete(e);this.clears++}clear(){this.clears++,this.pushedBefore+=this.pushed,this.head=0,this.count=0,this.full=!1,this.pushed=0,this.growing=null,this.cols.clear(),this.computed.clear(),this.signalOrder.length=0,this.unitByName.clear(),this.decCache=null,this.timeDecs.clear(),this.snapDec=null,this.latest.clear(),this.listed.clear(),this.lastBackAbs=-1,this.lastPushT=-1/0,this.trackers.clear()}columnArray(e){return e===this.timeColumn?this.time:this.cols.get(e)}physOf(e){let t=e-(this.pushed-this.size);return this.full?(this.head+t)%this.capacity:t}copyRange(e,t,n,r=[this.timeColumn,...this.signalOrder]){let i=Math.max(t,this.pushed-this.size),a=Math.max(0,n-i),o=this.columnArray(e),s=new Float64Array(a),c=new Map;for(let e of r)this.columnArray(e)&&c.set(e,new Float64Array(a));for(let e=0;e<a;e++){let t=this.physOf(i+e);s[e]=o?o[t]:NaN;for(let[n,r]of c)r[e]=this.columnArray(n)[t]}return{x:s,cols:c}}advanceCycle(e,t,n,r){Number.isFinite(t.lastX)&&n<t.lastX&&t.lastX-n>(t.hi-t.lo)/2?(t.previous=this.copyRange(e,t.start,r),t.start=r,t.lo=t.hi=n):Number.isFinite(t.lastX)?(n<t.lo&&(t.lo=n),n>t.hi&&(t.hi=n)):t.lo=t.hi=n,n<t.allLo&&(t.allLo=n),n>t.allHi&&(t.allHi=n),t.lastX=n}trackCycles(e){if(this.trackers.has(e))return;let t={start:this.pushed-this.size,lo:0,hi:0,lastX:NaN,allLo:1/0,allHi:-1/0,previous:null,next:this.pushed},n=this.columnArray(e),r=this.pushed-this.size;if(n)for(let i=r;i<this.pushed;i++){let r=n[this.physOf(i)];Number.isFinite(r)&&this.advanceCycle(e,t,r,i)}this.trackers.set(e,t)}cycleSpan(e){let t=this.trackers.get(e);return t&&t.allHi>t.allLo?[t.allLo,t.allHi]:null}decimateCycle(e,t,n,r,i,a){let o=this.trackers.get(e),s=n.filter(e=>this.cols.has(e));if(!o)return{x0:r,bucket:0,rows:[],columns:s};let c=t===`previous`?o.previous:this.copyRange(e,o.start,this.pushed,s);if(!c)return{x0:r,bucket:0,rows:[],columns:s};let l=s.map(e=>c.cols.get(e)??new Float64Array(c.x.length).fill(NaN));return N(c.x,l,s,r,i,a)}decimateCyclePoints(e,t,n,r,i,a){let o=()=>{let o=this.decimateCycle(e,t,n,r,i,a);return Ht(o.rows,o.columns,o.x0,o.bucket)},s=this.trackers.get(e),c=Math.floor(a),l=this.columnArray(e);if(!s||!l||!(i>r)||c<1)return o();let u=n.filter(e=>this.cols.has(e)),d=u.join(` `);if(t===`previous`){let e=this.prevCyclePts;if(e&&e.snap===s.previous&&e.x0===r&&e.x1===i&&e.mp===a&&e.colsKey===d)return e.pts;let t=o();return this.prevCyclePts={snap:s.previous,x0:r,x1:i,mp:a,colsKey:d,pts:t},t}if(s.start<this.pushed-this.size)return o();let f=this.curCyclePts;if((!f||f.key!==e||f.start!==s.start||f.x0!==r||f.x1!==i||f.mp!==a||f.colsKey!==d||f.clears!==this.clears)&&(f=this.curCyclePts={key:e,start:s.start,x0:r,x1:i,mp:a,colsKey:d,clears:this.clears,done:s.start,pts:null,seen:new Uint8Array(c),lo:u.map(()=>new Float64Array(c).fill(1/0)),hi:u.map(()=>new Float64Array(c).fill(-1/0))}),f.pts&&f.done===this.pushed)return f.pts;let p=(i-r)/a,m=u.map(e=>this.columnArray(e));for(let e=f.done;e<this.pushed;e++){let t=this.physOf(e),n=l[t];if(!(n>=r&&n<=i))continue;let a=Math.floor((n-r)/p);a>=c&&(a=c-1),f.seen[a]=1;for(let e=0;e<m.length;e++){let n=m[e][t];n===n&&(n<f.lo[e][a]&&(f.lo[e][a]=n),n>f.hi[e][a]&&(f.hi[e][a]=n))}}f.done=this.pushed;let h=0,g=new Uint8Array(c);for(let e=0;e<c;e++)if(f.seen[e]){for(let t=0;t<m.length;t++){let n=f.hi[t][e];if(n!==-1/0&&n!==f.lo[t][e]){g[e]=1;break}}h+=1+g[e]}let _=new Float64Array(h),v=u.map(()=>new Float64Array(h)),y=0;for(let e=0;e<c;e++){if(!f.seen[e])continue;let t=r+(e+.5)*p;_[y]=t;for(let t=0;t<m.length;t++){let n=f.lo[t][e];v[t][y]=n===1/0?NaN:n}if(y++,g[e]){_[y]=t;for(let t=0;t<m.length;t++){let n=f.hi[t][e];v[t][y]=n===-1/0?NaN:n}y++}}return f.pts={length:h,x:_,cols:new Map(u.map((e,t)=>[e,v[t]]))},f.pts}computed=new Set;get firstAbs(){return this.pushed-this.size}get endAbs(){return this.pushed}range(e,t,n){let r=Math.max(t,this.firstAbs),i=new Float64Array(Math.max(0,Math.min(n,this.pushed)-r)),a=this.columnArray(e);if(!a)return i.fill(NaN);for(let e=0;e<i.length;e++)i[e]=a[this.physOf(r+e)];return i}mirrorColumn(e){let t=this.columnArray(e);if(!t)return;let n=this.firstAbs,r=this.pushed,i=this.mirrors.get(e);if((!i||i.clears!==this.clears)&&(i={arr:new Float64Array(Math.max(16,r-n)),first:n,end:n,clears:this.clears,view:null},this.mirrors.set(e,i)),i.first===n&&i.end===r&&i.view)return i.view;if(n>i.first){let e=Math.max(0,i.end-n);e>0&&i.arr.copyWithin(0,n-i.first,i.end-i.first),i.first=n,i.end=n+e}if(i.arr.length<r-n){let e=new Float64Array(Math.max(r-n,i.arr.length*2));e.set(i.arr.subarray(0,i.end-i.first)),i.arr=e}for(let e=i.end;e<r;){let a=this.physOf(e),o=Math.min(r-e,(this.full?this.capacity:this.alloc)-a);i.arr.set(t.subarray(a,a+o),e-n),e+=o}return i.end=r,i.view=i.arr.subarray(0,r-n),i.view}writeComputed(e,t,n,r){let i=this.mirrors.get(e);i&&n<i.end&&(i.end=Math.max(i.first,n),i.view=null);let a=this.cols.get(e);(!a||!this.computed.has(e))&&(a||(a=this.newColumn(),this.cols.set(e,a),this.signalOrder.push(e),this.listed.delete(e)),this.computed.add(e)),this.unitByName.set(e,t);for(let e=0;e<r.length;e++){let t=n+e;t<this.firstAbs||t>=this.pushed||(a[this.physOf(t)]=r[e]??NaN)}let o=this.trackers.get(e);if(o){for(let t=0;t<r.length;t++){let i=n+t,a=r[t];i<o.next||i<this.firstAbs||i>=this.pushed||a===null||!Number.isFinite(a)||this.advanceCycle(e,o,a,i)}o.next=Math.max(o.next,Math.min(this.pushed,n+r.length))}}clearComputed(){for(let e of this.computed){this.cols.delete(e),this.unitByName.delete(e);for(let t of this.trackers.values())t.previous?.cols.delete(e)}this.signalOrder.splice(0,this.signalOrder.length,...this.signalOrder.filter(e=>!this.computed.has(e))),this.computed.clear(),this.decCache=null,this.timeDecs.clear(),this.clears++}get columnNames(){return[this.timeColumn,...this.signalOrder,...this.listed.keys()]}get columnCount(){return 1+this.signalOrder.length+this.listed.size}has(e){return e===this.timeColumn||this.cols.has(e)||this.listed.has(e)}unitOf(e){return e===this.timeColumn?this.timeUnit:this.unitByName.get(e)??this.listed.get(e)??``}columnValues(e){let t=this.size,n=new Float64Array(t),r=e===this.timeColumn?this.time:this.cols.get(e);if(!r)return n.fill(NaN),n;for(let e=0;e<t;e++)n[e]=r[this.full?(this.head+e)%this.capacity:e];return n}accumulate(e,t,n,r,i){let a=cn(i.length),o=n[t];if(Number.isNaN(o))return;let s=Math.floor(o/r),c=e.get(s);c||(c={...a.row,b:s},e.set(s,c));for(let e=0;e<i.length;e++){let n=i[e][t];if(Number.isNaN(n))continue;let r=a.lo[e],o=a.hi[e],s=c[r],l=c[o];c[r]=s==null?n:Math.min(s,n),c[o]=l==null?n:Math.max(l,n)}}decimateColumns(e,t,n,r,i){if(e===this.timeColumn&&this.timeMonotonic)return this.decimateTime(t,n,r,i);let a=e===this.timeColumn?this.time:this.cols.get(e),o=a?t.filter(e=>this.cols.has(e)):[],s=(r-n)/i,c=this.size;if(c>1&&e===this.timeColumn&&this.timeMonotonic&&a){let e=a[this.full?this.head:0],t=(a[this.full?(this.head+c-1)%this.capacity:c-1]-e)/(c-1);t>0&&t<s&&(s=.7*Math.max(t,(r-n)/(i*un)))}let l=Qt(s);{let t=this.decCache;t&&t.xKey===e&&t.colsKey===o.join(` `)&&t.bucket>0&&s>=t.bucket*.5&&s<=t.bucket*2&&(l=t.bucket)}if(!a||o.length===0||!(r>n)||!(l>0))return{x0:n,bucket:0,rows:[],columns:o};let u=o.map(e=>this.cols.get(e)),d=this.size,f=o.join(`\0`);this.debugLastScan=0;let p=this.decCache,m=p!==null&&e===this.timeColumn&&this.timeMonotonic&&p.xKey===e&&p.colsKey===f&&p.bucket===l&&this.pushed>=p.pushed&&this.pushed-p.pushed<d&&p.map.size<this.capacity*2,h=p!==null&&p.xKey===e&&p.colsKey===f&&p.bucket===l&&p.pushed===this.pushed,g=this.pushed-d,_=e===this.timeColumn&&this.timeMonotonic?g:Math.max(g,this.passStart(e,a)),v=p!==null&&(_>g||!this.full)&&p.xKey===e&&p.colsKey===f&&p.bucket===l&&p.passStart===_&&p.pushed>=_&&p.pushed<=this.pushed,y;if(h&&p)y=p.map;else if(v&&p){y=p.map;for(let e=p.pushed;e<this.pushed;e++)this.debugLastScan++,this.accumulate(y,this.physOf(e),a,l,u);p.pushed=this.pushed}else if(m&&p){y=p.map;let e=this.pushed-p.pushed;for(let t=d-e;t<d;t++){let e=this.full?(this.head+t)%this.capacity:t;this.debugLastScan++,this.accumulate(y,e,a,l,u)}if(this.full&&d>0){let e=a[this.head];if(!Number.isNaN(e)){let t=Math.floor(e/l);for(let e=p.lowB;e<t;e++)y.delete(e);y.delete(t);for(let e=0;e<d;e++){let n=(this.head+e)%this.capacity,r=a[n];if(!Number.isNaN(r)){if(Math.floor(r/l)>t)break;this.debugLastScan++,this.accumulate(y,n,a,l,u)}}p.lowB=t}}p.pushed=this.pushed}else{y=new Map;let t=1/0;for(let e=_;e<this.pushed;e++){let n=this.physOf(e),r=a[n];if(Number.isNaN(r))continue;this.debugLastScan++,this.accumulate(y,n,a,l,u);let i=Math.floor(r/l);i<t&&(t=i)}this.decCache={xKey:e,colsKey:f,cols:o,bucket:l,map:y,pushed:this.pushed,lowB:Number.isFinite(t)?t:0,passStart:_}}let b=Math.floor(n/l),x=Math.floor(r/l),S=[];for(let e of y.values()){let t=e.b;t>=b&&t<=x&&S.push(e)}return S.sort((e,t)=>Number(e.b)-Number(t.b)),{x0:0,bucket:l,rows:S,columns:o}}passStart(e,t){let n=this.pushed-this.size,r=this.passTrack;(!r||r.key!==e||r.clears!==this.clears)&&(r=this.passTrack={key:e,clears:this.clears,done:n,prevX:NaN,cuts:[]});let{x0:i,x1:a}=this.columnBounds(e),o=(a-i)/2;for(let e=Math.max(r.done,n);e<this.pushed;e++){let n=t[this.physOf(e)];Number.isNaN(n)||(n<r.prevX-o&&(r.cuts.push({abs:e,drop:r.prevX-n}),r.cuts.length>64&&r.cuts.shift()),r.prevX=n)}for(r.done=this.pushed;r.cuts.length>0&&r.cuts[0].abs<n;)r.cuts.shift();for(let e=r.cuts.length-1;e>=0;e--)if(r.cuts[e].drop>o)return r.cuts[e].abs;return n}timeIndex(e){let t=0,n=this.size;for(;t<n;){let r=t+n>>>1;this.time[this.full?(this.head+r)%this.capacity:r]<e?t=r+1:n=r}return t}foldBuckets(e,t,n,r,i){this.eachBucketRun(t,n,r,(t,n,r)=>e.fold(e.row(t),i,n,r))}eachBucketRun(e,t,n,r){if(t<=e)return;this.debugLastScan+=t-e;let i=this.time,a=e=>Math.floor(i[e]/n),o=(e,t)=>{let n=e;for(;n<t;){let e=a(n),i=n,o=1;for(;n+o<t&&a(n+o)===e;)i=n+o,o*=2;let s=i+1,c=Math.min(n+o,t);for(;s<c;){let t=s+c>>>1;a(t)===e?s=t+1:c=t}r(e,n,s),n=s}};if(!this.full)return o(e,t);let s=(this.head+e)%this.capacity,c=s+(t-e);if(c<=this.capacity)return o(s,c);o(s,this.capacity),o(0,c-this.capacity)}decimateTime(e,t,n,r){let i=this.timeBuckets(e,t,n,r);if(!i.store)return{x0:t,bucket:0,rows:[],columns:i.cols};let a=cn(i.cols.length),o=()=>i.store.toRows(i.i0,i.i1,a.row,a.lo,a.hi),s=this.historyDec;return{x0:0,bucket:i.bucket,rows:s?.store===i.store?s.rows??=o():o(),columns:i.cols}}decimatePoints(e,t,n,r,i){if(e===this.timeColumn&&this.timeMonotonic){let e=this.timeBuckets(t,n,r,i);return e.store?e.store.toPoints(e.i0,e.i1,e.cols):{length:0,x:new Float64Array,cols:new Map(e.cols.map(e=>[e,new Float64Array]))}}let a=this.decimateColumns(e,t,n,r,i);return Ht(a.rows,a.columns,a.x0,a.bucket)}timeBuckets(e,t,n,r){let i=e.filter(e=>this.cols.has(e)),a=this.size,o={cols:i,bucket:0,store:null,i0:0,i1:0};if(i.length===0||!(n>t)||a===0)return o;let s=e=>this.full?(this.head+e)%this.capacity:e,c=this.time[s(0)],l=this.time[s(a-1)],u=(n-t)/r;if(a>1){let e=(l-c)/(a-1);e>0&&e<u&&(u=.7*Math.max(e,(n-t)/(r*un)))}let d=Qt(u),f=i.join(` `),p=this.timeDecs.get(f)??[],m=p.find(e=>u>=e.bucket*.5&&u<=e.bucket*2)??null;if(m&&(d=m.bucket),!(d>0))return o;let h=i.map(e=>this.cols.get(e)),g=Math.floor(t/d),_=Math.floor(n/d);this.debugLastScan=0;let v=e=>({cols:i,bucket:d,store:e,i0:e.lowerBound(g),i1:e.lowerBound(_+1)});if(n<l-(n-t)){let e=this.timeIndex(g*d),t=this.timeIndex((_+1)*d),n=this.pushed-a,r=`${f}|${d}|${g}|${_}|${n+e}|${n+t}|${this.clears}`;if(this.historyDec?.key!==r){let n=new Zt(i.length,d);this.foldBuckets(n,e,t,d,h),this.historyDec={key:r,store:n}}return v(this.historyDec.store)}let y=m?this.pushed-m.pushed:0;if(m&&m.colsKey===f&&m.bucket===d&&y>=0&&y<a){let e=m.store;if(g<m.fromB){let t=new Zt(i.length,d);this.foldBuckets(t,this.timeIndex(g*d),this.timeIndex(m.fromB*d),d,h);for(let n=t.end-1;n>=t.start;n--){let r=e.row(t.b[n]);for(let i=0;i<t.nc;i++)e.lo[i][r]=t.lo[i][n],e.hi[i][r]=t.hi[i][n]}m.fromB=g}y>0&&this.foldBuckets(e,a-y,a,d,h);let t=Math.floor(c/d);return this.full&&t>=m.fromB&&(e.dropBelow(t),e.reset(e.row(t)),this.foldBuckets(e,0,this.timeIndex((t+1)*d),d,h),m.fromB=t),g>m.fromB&&(e.dropBelow(g),m.fromB=g),m.pushed=this.pushed,v(e)}let b=new Zt(i.length,d),x=this.timeIndex(g*d);this.foldBuckets(b,x,a,d,h);let S={colsKey:f,cols:i,bucket:d,store:b,pushed:this.pushed,fromB:x===0?Math.floor(c/d):g};return this.timeDecs.delete(f),this.timeDecs.set(f,[S,...p.filter(e=>e!==m&&e.bucket!==d)].slice(0,nn)),this.timeDecs.size>tn&&this.timeDecs.delete(this.timeDecs.keys().next().value),v(b)}lastValue(e){let t=e===this.timeColumn?this.time:this.cols.get(e);return!t||this.size===0?NaN:t[this.full?(this.head-1+this.capacity)%this.capacity:this.count-1]}xTravel(e,t){let n=this.columnArray(e),r=this.size;if(!n||r<2)return NaN;let i=e=>this.full?(this.head+e)%this.capacity:e,a=this.time[i(r-1)],o=0,s=NaN,c=a;for(let e=r-1;e>=0;e--){let r=i(e),l=this.time[r];if(l<a-t)break;let u=n[r];Number.isNaN(u)||(s>u&&(o+=s-u),s=u,c=l)}let l=a-c;return l>0&&l<t?o*t/l:o}timeAfter(e){if(!this.timeMonotonic)return NaN;let t=e=>this.full?(this.head+e)%this.capacity:e,n=0,r=this.size;for(;n<r;){let i=n+r>>>1;this.time[t(i)]<=e?n=i+1:r=i}return n<this.size?this.time[t(n)]:NaN}latestTime(){return this.size===0?NaN:this.columnBounds(this.timeColumn).x1}xAtTime(e,t,n=!1){let r=this.columnArray(e),i=this.size;if(!r||i===0)return NaN;if(e===this.timeColumn&&!n){let{x0:n,x1:r}=this.columnBounds(e);return Math.min(r,Math.max(n,t))}if(!this.timeMonotonic)return NaN;let a=e=>this.full?(this.head+e)%this.capacity:e,o=0,s=i-1;if(t<=this.time[a(0)])return r[a(0)];if(t>=this.time[a(s)])return r[a(s)];for(;s-o>1;){let e=o+s>>1;this.time[a(e)]<=t?o=e:s=e}let c=a(o),l=a(s),u=r[c],d=r[l];if(n||!(d>=u))return u;let f=this.time[c],p=this.time[l];return p>f?u+(d-u)*(t-f)/(p-f):u}boundsCache=new Map;columnBounds(e){let t=e===this.timeColumn?this.time:this.cols.get(e),n=this.size;if(!t||n===0)return{x0:0,x1:0};if(t===this.time&&this.timeMonotonic)return{x0:this.time[this.full?this.head:0],x1:this.time[this.full?(this.head+n-1)%this.capacity:n-1]};let r=this.pushed-n,i=this.boundsCache.get(e);if(i&&i.version===this.version)return i.b;(!i||i.clears!==this.clears||i.loAbs<r||i.hiAbs<r)&&(i={version:-1,clears:this.clears,done:r,lo:1/0,hi:-1/0,loAbs:1/0,hiAbs:1/0,b:{x0:0,x1:0}},this.boundsCache.set(e,i));for(let e=Math.max(i.done,r);e<this.pushed;e++){let n=t[this.physOf(e)];Number.isNaN(n)||(n<=i.lo&&(i.lo=n,i.loAbs=e),n>=i.hi&&(i.hi=n,i.hiAbs=e))}return i.done=this.pushed,i.version=this.version,i.b=Number.isFinite(i.lo)?{x0:i.lo,x1:i.hi}:{x0:0,x1:0},i.b}toDataset(e){let t=[...this.listed.keys()],n=[this.timeColumn,...this.signalOrder,...t],r=[this.timeUnit,...this.signalOrder.map(e=>this.unitByName.get(e)??``),...t.map(e=>this.listed.get(e))],i=this.size,a=e&&e>0&&i>e?Math.ceil(i/e):1,o=a>1&&this.timeMonotonic?this.snapshotRows(e,t):null;if(o)return{meta:``,columnNames:n,units:r,rows:o};let s=this.pushed-i,c=a>1?(a-s%a)%a:0,l=[];for(let e=c;e<i;e+=a)l.push(this.full?(this.head+e)%this.capacity:e);i>0&&(l.length===0||(i-1-c)%a!=0)&&l.push(this.full?(this.head+i-1)%this.capacity:i-1);let u=e=>{let t=new Float64Array(l.length);for(let n=0;n<l.length;n++)t[n]=e[l[n]];return t},d=t.length?new Float64Array(l.length).fill(NaN):null;return{meta:``,columnNames:n,units:r,rows:fn(n,[u(this.time),...this.signalOrder.map(e=>u(this.cols.get(e))),...t.map(()=>d)])}}snapshotRows(e,t){let n=this.size,r=e=>this.full?(this.head+e)%this.capacity:e,i=this.time[r(0)],a=this.time[r(n-1)],o=(a-i)*2/e;if(!(o>0))return null;let s=`${this.signalOrder.join(`
|
|
11
|
-
`)}|${this.clears}`,c=this.signalOrder.map(e=>this.cols.get(e)),l=this.snapDec,u=l?this.pushed-l.pushed:0;if(l&&l.key===s&&l.bucket<o&&u>=0&&u<n){let e=2;for(;l.bucket*e<o;)e*=2;l.store.coarsen(e),l.bucket*=e,l.fromB=Math.floor(l.fromB/e)}if(l&&l.key===s&&l.bucket>=o&&l.bucket<=o*4&&u>=0&&u<n){let e=l.store;u>0&&this.foldBuckets(e,n-u,n,l.bucket,c);let t=Math.floor(i/l.bucket);this.full&&t>=l.fromB&&(e.dropBelow(t),e.reset(e.row(t)),this.foldBuckets(e,0,this.timeIndex((t+1)*l.bucket),l.bucket,c),l.fromB=t),l.pushed=this.pushed}else{let t=2**Math.ceil(Math.log2(o));t<o&&(t*=2);let r=new Zt(c.length,t,Math.ceil(e/2)+8);this.foldBuckets(r,0,n,t,c),l=this.snapDec={key:s,bucket:t,store:r,pushed:this.pushed,fromB:Math.floor(i/t)}}let d=l.store.toPoints(l.store.start,l.store.end,this.signalOrder),f=new Float64Array(d.x),p=f[0],m=f[f.length-1];for(let e=0;e<f.length;e++)f[e]=f[e]===m?a:f[e]===p?i:f[e];let h=t.length?new Float64Array(f.length).fill(NaN):null;return fn([this.timeColumn,...this.signalOrder,...t],[f,...this.signalOrder.map(e=>new Float64Array(d.cols.get(e))),...t.map(()=>h)])}valueBounds(e){let t=this.columnBounds(e);return Number.isFinite(this.boundsCache.get(e)?.lo??NaN)?t:null}hasValues(e){return this.latest.has(e)||this.computed.has(e)}get memoryBudget(){return this.maxBytes}get valuedCount(){return this.latest.size}lastKnown(e){return this.latest.get(e)}list(e,t,n=NaN,r=NaN){e===this.timeColumn||this.computed.has(e)||(this.cols.has(e)||this.listed.set(e,t),Number.isFinite(n)&&Number.isFinite(r)&&this.noteValue(e,n,r))}setLastKnown(e,t,n,r){e===this.timeColumn||this.computed.has(e)||!Number.isFinite(n)||!Number.isFinite(r)||(this.cols.has(e)||(this.cols.set(e,this.newColumn()),this.signalOrder.push(e),this.listed.delete(e),this.unitByName.set(e,t)),this.noteValue(e,n,r))}noteValue(e,t,n){let r=this.latest.get(e);r?t>=r.t&&(r.t=t,r.v=n):this.latest.set(e,{t,v:n})}};function fn(e,t){return a({keys:e,length:t[0]?.length??0,values:t,text:e.map(()=>null)})}new TextEncoder;var pn=4096;function mn(e,t,n){let r=t,i=r+n,a=[],o=``;for(;r<i;){let t=e[r++];if(!(t&128))a.push(t);else if((t&224)==192){let n=e[r++]&63;a.push((t&31)<<6|n)}else if((t&240)==224){let n=e[r++]&63,i=e[r++]&63;a.push((t&31)<<12|n<<6|i)}else if((t&248)==240){let n=e[r++]&63,i=e[r++]&63,o=e[r++]&63,s=(t&7)<<18|n<<12|i<<6|o;s>65535&&(s-=65536,a.push(s>>>10&1023|55296),s=56320|s&1023),a.push(s)}else a.push(t);a.length>=pn&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}var hn=new TextDecoder,gn=200;function _n(e,t,n){let r=e.subarray(t,t+n);return hn.decode(r)}function vn(e,t,n){return n>gn?_n(e,t,n):mn(e,t,n)}var yn=class{type;data;constructor(e,t){this.type=e,this.data=t}},G=class e extends Error{constructor(t){super(t);let n=Object.create(e.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,`name`,{configurable:!0,enumerable:!1,value:e.name})}};function bn(e,t,n){let r=Math.floor(n/4294967296),i=n;e.setUint32(t,r),e.setUint32(t+4,i)}function xn(e,t){let n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}function Sn(e,t){let n=e.getUint32(t),r=e.getUint32(t+4);return n*4294967296+r}var Cn=4294967295,wn=17179869183;function Tn({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=wn)if(t===0&&e<=Cn){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}else{let n=e/4294967296,r=e&4294967295,i=new Uint8Array(8),a=new DataView(i.buffer);return a.setUint32(0,t<<2|n&3),a.setUint32(4,r),i}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,t),bn(r,4,e),n}}function En(e){let t=e.getTime(),n=Math.floor(t/1e3),r=(t-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function Dn(e){return e instanceof Date?Tn(En(e)):null}function On(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let e=t.getUint32(0),n=t.getUint32(4);return{sec:(e&3)*4294967296+n,nsec:e>>>2}}case 12:return{sec:xn(t,4),nsec:t.getUint32(0)};default:throw new G(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function kn(e){let t=On(e);return new Date(t.sec*1e3+t.nsec/1e6)}var An={type:-1,encode:Dn,decode:kn},jn=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(An)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{let r=-1-e;this.builtInEncoders[r]=t,this.builtInDecoders[r]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){let r=this.builtInEncoders[n];if(r!=null){let i=r(e,t);if(i!=null)return new yn(-1-n,i)}}for(let n=0;n<this.encoders.length;n++){let r=this.encoders[n];if(r!=null){let i=r(e,t);if(i!=null)return new yn(n,i)}}return e instanceof yn?e:null}decode(e,t,n){let r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,n):new yn(t,e)}};function Mn(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}function Nn(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Mn(e)?new Uint8Array(e):Uint8Array.from(e)}function Pn(e){return`${e<0?`-`:``}0x${Math.abs(e).toString(16).padStart(2,`0`)}`}var Fn=16,In=16,Ln=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=Fn,t=In){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){let r=this.caches[n-1];FIND_CHUNK:for(let i of r){let r=i.bytes;for(let i=0;i<n;i++)if(r[i]!==e[t+i])continue FIND_CHUNK;return i.str}return null}store(e,t){let n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)}decode(e,t,n){let r=this.find(e,t,n);if(r!=null)return this.hit++,r;this.miss++;let i=mn(e,t,n),a=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(a,i),i}},Rn=`array`,zn=`map_key`,Bn=`map_value`,Vn=e=>{if(typeof e==`string`||typeof e==`number`)return e;throw new G(`The type of key must be string or number but `+typeof e)},Hn=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=Rn,t.position=0,t.size=e,t.array=Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=zn,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){return this.stackHeadPosition++,this.stackHeadPosition===this.stack.length&&this.stack.push({type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null}),this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw Error(`Invalid stack state. Released state is not on top of the stack.`);if(e.type===Rn){let t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===zn||e.type===Bn){let t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Un=-1,Wn=new DataView(new ArrayBuffer(0)),Gn=new Uint8Array(Wn.buffer);try{Wn.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw Error(`This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access`)}var Kn=RangeError(`Insufficient data`),qn=new Ln,Jn=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Wn;bytes=Gn;headByte=Un;stack=new Hn;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??jn.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder===void 0?qn:e.keyDecoder,this.mapKeyConverter=e?.mapKeyConverter??Vn}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Un,this.stack.reset()}setBuffer(e){let t=Nn(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Un&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),n=Nn(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:n}=this;return RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(let r of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(r);try{n=this.doDecodeSync(),t=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:r,pos:i,totalPos:a}=this;throw RangeError(`Insufficient data in parsing ${Pn(r)} at ${a} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,r=-1;for await(let i of e){if(t&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),n&&(r=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--r!==0;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){DECODE:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue DECODE}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue DECODE}else t=[]}else{let n=e-160;t=this.decodeString(n,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(e===217){let e=this.lookU8();t=this.decodeString(e,1)}else if(e===218){let e=this.lookU16();t=this.decodeString(e,2)}else if(e===219){let e=this.lookU32();t=this.decodeString(e,4)}else if(e===220){let e=this.readU16();if(e!==0){this.pushArrayState(e),this.complete();continue DECODE}else t=[]}else if(e===221){let e=this.readU32();if(e!==0){this.pushArrayState(e),this.complete();continue DECODE}else t=[]}else if(e===222){let e=this.readU16();if(e!==0){this.pushMapState(e),this.complete();continue DECODE}else t={}}else if(e===223){let e=this.readU32();if(e!==0){this.pushMapState(e),this.complete();continue DECODE}else t={}}else if(e===196){let e=this.lookU8();t=this.decodeBinary(e,1)}else if(e===197){let e=this.lookU16();t=this.decodeBinary(e,2)}else if(e===198){let e=this.lookU32();t=this.decodeBinary(e,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let e=this.lookU8();t=this.decodeExtension(e,1)}else if(e===200){let e=this.lookU16();t=this.decodeExtension(e,2)}else if(e===201){let e=this.lookU32();t=this.decodeExtension(e,4)}else throw new G(`Unrecognized type byte: ${Pn(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let e=n.top();if(e.type===Rn)if(e.array[e.position]=t,e.position++,e.position===e.size)t=e.array,n.release(e);else continue DECODE;else if(e.type===zn){if(t===`__proto__`)throw new G(`The key __proto__ is not allowed`);e.key=this.mapKeyConverter(t),e.type=Bn;continue DECODE}else if(e.map[e.key]=t,e.readCount++,e.readCount===e.size)t=e.map,n.release(e);else{e.key=null,e.type=zn;continue DECODE}}return t}}readHeadByte(){return this.headByte===Un&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Un}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new G(`Unrecognized array type byte: ${Pn(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new G(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new G(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new G(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Kn;let n=this.pos+t,r;return r=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,n,e):vn(this.bytes,n,e),this.pos+=t+e,r}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===zn:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new G(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Kn;let n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r}decodeExtension(e,t){if(e>this.maxExtLength)throw new G(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=Sn(this.view,this.pos);return this.pos+=8,e}readI64(){let e=xn(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function Yn(e,t){return new Jn(t).decode(e)}var Xn=6,Zn=8,Qn=12,$n=16;function er(e){let t=new Uint8Array(e),n=t.length>0&&t[0]&128?2:1;return t.length<n+Qn+$n?null:{kind:t[0]&-129,keyId:n===2?t[1]:null,iv:t.subarray(n,n+Qn),ciphertext:t.subarray(n+Qn),aad:t.subarray(0,n)}}async function tr(e,t){let n=er(t);if(!n)return null;let r=typeof e==`function`?await e(n.keyId):e;if(!r)return null;let i=await qe(r,n.iv,n.ciphertext,n.aad);return{kind:n.kind,plaintext:i}}function nr(e,t,n,r){return rr(e,t,n,r)}async function rr(e,t,n,r,i){let a=r===void 0?new Uint8Array([t]):new Uint8Array([t|128,r&255]),o=i??We(),s=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:`AES-GCM`,iv:o,additionalData:a},e,n)),c=new Uint8Array(a.length+Qn+s.length);return c.set(a),c.set(o,a.length),c.set(s,a.length+Qn),c.buffer}var ir=1,ar=e=>e+7&-8;function or(e){let t=e=>RangeError(`columns message: ${e}`);e.byteOffset%8!=0&&(e=e.slice());let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.byteLength<8)throw t(`short`);if(n.getUint8(0)!==ir)throw t(`version ${n.getUint8(0)}`);let r=n.getUint16(2,!0),i=n.getUint32(4,!0),a=new TextDecoder,o=[],s=8;for(let i=0;i<r;i++){if(s+3>e.byteLength)throw t(`short channel table`);let r=n.getUint8(s),i=n.getUint8(s+1),c=n.getUint8(s+2);if(s+=3,r!==4&&r!==8)throw t(`value size ${r}`);if(s+i+c>e.byteLength)throw t(`short channel table`);o.push({name:a.decode(e.subarray(s,s+i)),unit:a.decode(e.subarray(s+i,s+i+c)),size:r}),s+=i+c}if(s=ar(s),s+ar(i*8)+o.reduce((e,t)=>e+ar(i*t.size),0)>e.byteLength)throw t(`short data`);let c=e.byteOffset,l=new Float64Array(e.buffer,c+s,i);s+=ar(i*8);let u={},d={};for(let t of o)u[t.name]=t.size===4?new Float32Array(e.buffer,c+s,i):new Float64Array(e.buffer,c+s,i),t.unit&&(d[t.name]=t.unit),s+=ar(i*t.size);return{t:l,columns:u,units:d}}var sr=2,cr=1,lr=1,ur=2,dr=3,fr=2,pr=1,mr=2,hr=1e5,gr=513,_r=20,vr=64*1024*1024,K=(e,t)=>RangeError(`${e}: ${t}`);function yr(e,t){let n=new TextDecoder(`utf-8`,{fatal:!0}),r=[],i=0;try{for(let a=0;a<t;a++){if(i+3>e.byteLength)throw K(`block schema`,`short channel table`);let t=e[i],a=e[i+1],o=e[i+2];if(i+=3,t!==4&&t!==8)throw K(`block schema`,`value size ${t}`);if(i+a+o>e.byteLength)throw K(`block schema`,`short channel table`);r.push({name:n.decode(e.subarray(i,i+a)),unit:n.decode(e.subarray(i+a,i+a+o)),size:t}),i+=a+o}}catch(e){throw e instanceof RangeError?e:K(`block schema`,`invalid text`)}return r}async function br(e){if(e.byteLength<8)throw K(`block schema`,`short`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint8(0);if(n===dr){if(e.byteLength<12)throw K(`block schema`,`short`);let n=t.getUint32(4,!0);if(n>hr)throw K(`block schema`,`too many channels`);let r=t.getUint8(1)&lr?await wr(e.subarray(12),n*gr,!1):e.subarray(12);return{id:t.getUint32(8,!0),channels:yr(r,n)}}if(n!==sr)throw K(`block schema`,`version ${n}`);return{id:t.getUint32(4,!0),channels:yr(e.subarray(8),t.getUint16(2,!0))}}function xr(e,t,n){let r=n.get(t.getUint32(4,!0));if(!r)return null;let i=t.getUint32(8,!0);if(i!==r.channels.length)throw K(`last values`,`channel count differs from its schema`);if(e.byteLength<12+16*i)throw K(`last values`,`short`);let a=[];for(let e=0;e<i;e++){let n=t.getFloat64(12+8*e,!0),o=t.getFloat64(12+8*(i+e),!0);Number.isFinite(n)&&Number.isFinite(o)&&a.push({name:r.channels[e].name,unit:r.channels[e].unit,t:n,v:o})}return a}async function Sr(e,t){if(e.byteLength<12)throw K(`last values`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(0);if(r===cr)return xr(e,n,t);if(r!==fr)throw K(`last values`,`version ${r}`);if(e.byteLength<20)throw K(`last values`,`short`);let i=n.getUint8(1),a=t.get(n.getUint32(4,!0));if(!a)return null;let o=n.getUint32(8,!0),s=n.getFloat64(12,!0),c=a.channels.length,l=(i&mr)!==0;if(o>c||l&&o!==c)throw K(`last values`,`entry count differs from its schema`);let u=(l?0:4*o)+4*o,d=i&lr?await wr(e.subarray(20),u+8*o,!1):e.subarray(20);if(d.byteLength<u)throw K(`last values`,`short`);let f=new DataView(d.buffer,d.byteOffset,d.byteLength),p=[];for(let e=0;e<o;e++){let t=l?e:f.getUint32(4*e,!0);if(t>=c)throw K(`last values`,`channel outside its schema`);p.push(t)}let m=l?0:4*o,h=p.filter(e=>a.channels[e].size===4),g=p.filter(e=>a.channels[e].size===8);if(d.byteLength!==u+4*h.length+8*g.length)throw K(`last values`,`body size mismatch`);let _=Cr(d,u,h.length,4),v=Cr(d,u+4*h.length,g.length,8),y=new Map;h.forEach((e,t)=>y.set(e,_[t])),g.forEach((e,t)=>y.set(e,v[t]));let b=[];return p.forEach((e,t)=>{let n=s-f.getUint32(m+4*t,!0)/1e3,r=y.get(e);Number.isFinite(n)&&Number.isFinite(r)&&b.push({name:a.channels[e].name,unit:a.channels[e].unit,t:n,v:r})}),b}function Cr(e,t,n,r){let i=new Uint8Array(n*r);for(let a=0;a<r;a++)for(let o=0;o<n;o++)i[o*r+a]=e[t+a*n+o];return r===4?new Float32Array(i.buffer):new Float64Array(i.buffer)}async function wr(e,t,n=!0){let r=new Blob([e]).stream().pipeThrough(new DecompressionStream(`deflate`)).getReader(),i=new Uint8Array(Math.min(t,e.byteLength*4+1024)),a=0;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+n.length>t)throw K(`block`,`body larger than its header says`);if(a+n.length>i.length){let e=new Uint8Array(Math.min(t,Math.max(2*i.length,a+n.length)));e.set(i.subarray(0,a)),i=e}i.set(n,a),a+=n.length}}catch(e){throw await r.cancel().catch(()=>{}),e instanceof RangeError?e:K(`block`,`body is not valid deflate`)}if(n&&a!==t)throw K(`block`,`body size mismatch`);return i.length===a?i:i.subarray(0,a)}async function Tr(e,t){if(e.byteLength<_r)throw K(`block`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint8(0)!==sr)throw K(`block`,`version ${n.getUint8(0)}`);let r=n.getUint8(1),i=n.getUint16(2,!0),a=n.getUint32(4,!0),o=n.getUint32(8,!0),s=t.get(o);if(!s)return null;if(s.channels.length!==i)throw K(`block`,`channel count differs from its schema`);let c=n.getFloat64(12,!0),l=Math.max(0,a-1),u=4*l+s.channels.reduce((e,t)=>e+t.size*a,0);if(u>vr)throw K(`block`,`too large`);let d;if(r&lr)d=await wr(e.subarray(_r),u);else if(d=e.subarray(_r),d.byteLength<u)throw K(`block`,`body size mismatch`);let f=new DataView(d.buffer,d.byteOffset,d.byteLength),p=new Float64Array(a),m=0;a&&(p[0]=c);for(let e=1;e<a;e++)m+=f.getInt32(4*(e-1),!0),p[e]=c+m/1e6;let h=4*l,g={},_={};for(let e of s.channels)g[e.name]=Cr(d,h,a,e.size),e.unit&&(_[e.name]=e.unit),h+=a*e.size;return{block:{t:p,columns:g,units:_},historical:(r&ur)!==0,schemaId:o}}async function Er(e,t){if(e.byteLength<_r)throw K(`sparse`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint8(0)!==pr)throw K(`sparse`,`version ${n.getUint8(0)}`);let r=n.getUint8(1),i=n.getUint32(4,!0),a=t.get(i);if(!a)return null;let o=n.getUint32(8,!0),s=n.getFloat64(12,!0),c=4*o+4*Math.max(0,o-1);if(c+8*o>vr)throw K(`sparse`,`too large`);let l=r&lr?await wr(e.subarray(_r),c+8*o,!1):e.subarray(_r);if(l.byteLength<c)throw K(`sparse`,`body size mismatch`);let u=new Uint32Array(o);for(let e=0;e<o;e++)u[e]=(l[e]|l[o+e]<<8|l[2*o+e]<<16|l[3*o+e]<<24)>>>0;let d=a.channels.length,f=0;for(let e=0;e<o;e++){if(u[e]>=d)throw K(`sparse`,`event outside its schema`);a.channels[u[e]].size===4&&f++}if(l.byteLength!==c+4*f+8*(o-f))throw K(`sparse`,`body size mismatch`);let p=new DataView(l.buffer,l.byteOffset,l.byteLength),m=new Float64Array(o),h=0;o&&(m[0]=s);for(let e=1;e<o;e++)h+=p.getInt32(4*o+4*(e-1),!0),m[e]=s+h/1e6;let g=Cr(l,c,f,4),_=Cr(l,c+4*f,o-f,8),v=new Float64Array(o);for(let e=0,t=0,n=0;e<o;e++)v[e]=a.channels[u[e]].size===4?g[t++]:_[n++];return{schemaId:i,index:u,t:m,v,historical:(r&ur)!==0}}var Dr=16,Or=class{t=new Float64Array(16);v=new Float64Array(16);start=0;end=0;get count(){return this.end-this.start}add(e,t){if(this.end===this.t.length){let e=this.count,t=e*2>this.t.length?this.t.length*2:this.t.length,n=new Float64Array(t),r=new Float64Array(t);n.set(this.t.subarray(this.start,this.end)),r.set(this.v.subarray(this.start,this.end)),this.t=n,this.v=r,this.start=0,this.end=e}this.t[this.end]=e,this.v[this.end++]=t}},kr=class{channels=new Map;events_=0;maxBytes;constructor(e){this.maxBytes=e}get bytes(){return this.events_*Dr}add(e,t,n){let r=this.channels.get(e);r||this.channels.set(e,r=new Or),r.add(t,n),this.events_++,this.bytes>this.maxBytes&&this.evict()}events(e){let t=this.channels.get(e);return t?{t:t.t.subarray(t.start,t.end),v:t.v.subarray(t.start,t.end)}:{t:new Float64Array,v:new Float64Array}}evict(){let e=this.maxBytes*.9/Dr;for(;this.events_>e;){let t=[...this.channels.values()].filter(e=>e.count>0).sort((e,t)=>t.count-e.count);if(!t.length)return;let n=t[0].count;for(let r of t){if(this.events_<=e||r.count*2<n)break;let t=Math.max(1,r.count>>1);r.start+=t,this.events_-=t}}}},Ar=1e3,jr=4,Mr=4096,Nr=class{buffer;store;schemas=new Map;known=new Map;active=new Set;constructor(e,t){this.buffer=e,this.store=new kr(t)}schema(e,t,n){this.schemas.delete(e),this.schemas.set(e,t),this.schemas.size>jr&&this.schemas.delete(this.schemas.keys().next().value),t.forEach((e,t)=>{this.known.has(e)||this.known.set(e,{unit:n[t]??``,t:NaN,v:NaN}),this.buffer.list(e,n[t]??``)})}last(e){for(let t of e)this.note(t.name,t.unit,t.t,t.v)}push(e,t,n,r){let i=this.schemas.get(e);return i?this.events(n.length,e=>i[t[e]],n,r):null}pushNamed(e,t,n){return this.events(e.length,e=>this.known.has(t[e])?t[e]:void 0,e,n)}events(e,t,n,r){let i=[];for(let a=0;a<e;a++){let e=t(a);e!==void 0&&(this.store.add(e,n[a],r[a]),this.note(e,this.known.get(e)?.unit??``,n[a],r[a]),this.active.has(e)&&i.push(a))}if(!i.length)return null;i.sort((e,t)=>n[e]-n[t]);let a=Pr(i.map(e=>n[e]),i.map(e=>t(e)),i.map(e=>r[e]));return this.buffer.pushColumns(a),a}activate(e){let t=!1;for(let n of e){if(this.active.size>=1e3)break;this.known.has(n)&&!this.active.has(n)&&(this.active.add(n),t=!0)}return t}replay(){let e=this.buffer;e.clear();for(let[t,n]of this.known)e.list(t,n.unit,n.t,n.v);let t=[...this.active],n=t.map(e=>this.store.events(e)),r=n.map(e=>e.t.length-1),i=new Fr(e=>-n[e].t[r[e]]);n.forEach((e,t)=>{e.t.length&&i.push(t)});let a=0,o=NaN;for(;i.size;){let t=i.top,s=n[t].t[r[t]];if(s!==o){if(a===e.maxSamples)break;a++,o=s}i.pop(),--r[t]>=0&&i.push(t)}let s=new Fr(e=>n[e].t[r[e]]);n.forEach((e,t)=>{++r[t]<e.t.length&&s.push(t)});let c=new Float64Array(Mr),l={},u=-1,d=()=>{if(u<0)return;let t=u+1;e.pushColumns({t:c.subarray(0,t),columns:Object.fromEntries(Object.entries(l).map(([e,n])=>[e,n.subarray(0,t)]))}),c=new Float64Array(Mr),l={},u=-1};for(;s.size;){let e=s.top,i=n[e].t[r[e]];(u<0||i!==c[u])&&(u+1===Mr&&d(),c[++u]=i),(l[t[e]]??=new Float64Array(Mr).fill(NaN))[u]=n[e].v[r[e]],s.pop(),++r[e]<n[e].t.length&&s.push(e)}d()}note(e,t,n,r){if(!Number.isFinite(n)||!Number.isFinite(r))return;let i=this.known.get(e);i?n<i.t||(i.t=n,i.v=r):this.known.set(e,{unit:t,t:n,v:r}),this.buffer.list(e,t,n,r)}};function Pr(e,t,n){let r=[];for(let t=0;t<e.length;t++)(t===0||e[t]!==e[t-1])&&r.push(e[t]);let i={},a=-1;for(let o=0;o<e.length;o++){(o===0||e[o]!==e[o-1])&&a++;let s=i[t[o]]??(i[t[o]]=new Float64Array(r.length).fill(NaN));s[a]=n[o]}return{t:Float64Array.from(r),columns:i}}var Fr=class{h=[];key;constructor(e){this.key=e}get size(){return this.h.length}get top(){return this.h[0]}push(e){let t=this.h,n=this.key(e),r=t.push(e)-1;for(;r>0;){let e=r-1>>1;if(this.key(t[e])<=n)break;t[r]=t[e],r=e}t[r]=e}pop(){let e=this.h,t=e.pop();if(!e.length)return;let n=this.key(t),r=e.length,i=0;for(;;){let t=2*i+1;if(t>=r||(t+1<r&&this.key(e[t+1])<this.key(e[t])&&t++,this.key(e[t])>=n))break;e[i]=e[t],i=t}e[i]=t}},Ir=0,Lr=1,Rr=70,zr=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),Br=e=>Uint8Array.from(e.match(/../g)??[],e=>parseInt(e,16)),Vr=e=>{let t=Br(e.replace(/-/g,``));if(t.length!==16)throw Error(`bad_stream_id`);return t},Hr=e=>{let t=zr(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`};function Ur(e){let t=new Uint8Array(Rr),n=new DataView(t.buffer);return t[0]=1,t.set(Vr(e.streamId),1),t.set(Br(e.run),17),t[25]=e.lane,n.setBigUint64(26,e.seq,!0),n.setUint32(34,e.count,!0),t.set(e.hash,38),t}function Wr(e){if(e.length!==Rr||e[0]!==1)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{streamId:Hr(e.subarray(1,17)),run:zr(e.subarray(17,25)),lane:e[25],seq:t.getBigUint64(26,!0),count:t.getUint32(34,!0),hash:e.slice(38,70)}}var Gr=()=>globalThis.crypto.subtle,Kr=e=>Gr().digest(`SHA-256`,e);async function qr(e){let t=await Promise.all(e),n=new Uint8Array(t.length*32);return t.forEach((e,t)=>n.set(new Uint8Array(e),t*32)),new Uint8Array(await Kr(n))}var Jr=()=>zr(globalThis.crypto.getRandomValues(new Uint8Array(8))),Yr=class{digests=[];seq=0n;streamId;run;lane;constructor(e,t,n){this.streamId=e,this.run=t,this.lane=n}add(e){this.digests.push(Kr(e))}async checkpoint(){let e=this.digests;return this.digests=[],this.seq+=1n,Ur({streamId:this.streamId,run:this.run,lane:this.lane,seq:this.seq,count:e.length,hash:await qr(e)})}};function Xr(e,t,n=()=>Date.now()){let r={verified:0,broken:0},i=null,a=0n,o=null,s=0,c=0,l=0,u=Promise.resolve(),d=e=>{e?r.verified++:(r.broken++,r.lastBrokenAt=n()),t({...r})};return{integrity:r,reset(){i=null,o=null,c=s,l++},arrive(t,n,r){if(n!==8){o&&(o.push(Kr(t)),s++);return}let f=s;o||(o=[],c=s);let p=l;u=u.then(async()=>{let t=await r.catch(()=>null);if(p!==l)return;let n=t?Wr(t.plaintext):null;if(!n||n.lane!==0||n.streamId!==e.toLowerCase()){i!==null&&d(!1);return}let s=f-c;if(i===null||n.run!==i){i=n.run,a=n.seq,o=o.slice(Math.max(0,s)),c=Math.max(c,f);return}let u=n.seq===a+1n&&n.count<=s&&Zr(await qr(o.slice(0,n.count)),n.hash);if(p!==l)return;a=n.seq;let m=u?n.count:s;o=o.slice(m),c+=m,d(u)})}}}var Zr=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),q=Uint8Array,J=Uint16Array,Qr=Int32Array,$r=new q([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ei=new q([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ti=new q([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ni=function(e,t){for(var n=new J(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Qr(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},ri=ni($r,2),ii=ri.b,ai=ri.r;ii[28]=258,ai[258]=28;for(var oi=ni(ei,0),si=oi.b,ci=oi.r,li=new J(32768),Y=0;Y<32768;++Y){var ui=(Y&43690)>>1|(Y&21845)<<1;ui=(ui&52428)>>2|(ui&13107)<<2,ui=(ui&61680)>>4|(ui&3855)<<4,li[Y]=((ui&65280)>>8|(ui&255)<<8)>>1}for(var X=(function(e,t,n){for(var r=e.length,i=0,a=new J(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new J(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new J(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[li[d]>>c]=l}else for(s=new J(r),i=0;i<r;++i)e[i]&&(s[i]=li[o[e[i]-1]++]>>15-e[i]);return s}),di=new q(288),Y=0;Y<144;++Y)di[Y]=8;for(var Y=144;Y<256;++Y)di[Y]=9;for(var Y=256;Y<280;++Y)di[Y]=7;for(var Y=280;Y<288;++Y)di[Y]=8;for(var fi=new q(32),Y=0;Y<32;++Y)fi[Y]=5;var pi=X(di,9,0),mi=X(di,9,1),hi=X(fi,5,0),gi=X(fi,5,1),_i=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Z=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},vi=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},yi=function(e){return(e+7)/8|0},bi=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new q(e.subarray(t,n))},xi=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],Q=function(e,t,n){var r=Error(t||xi[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Q),!n)throw r;return r},Si=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new q(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new q(i*3));var l=function(e){var t=n.length;if(e>t){var r=new q(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=Z(e,d,1);var v=Z(e,d+1,3);if(d+=3,!v){var y=yi(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&Q(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}else if(v==1)p=mi,m=gi,h=9,g=5;else if(v==2){var S=Z(e,d,31)+257,C=Z(e,d+10,15)+4,w=S+Z(e,d+5,31)+1;d+=14;for(var T=new q(w),E=new q(19),D=0;D<C;++D)E[ti[D]]=Z(e,d+D*3,7);d+=C*3;for(var O=_i(E),ee=(1<<O)-1,k=X(E,O,1),D=0;D<w;){var A=k[Z(e,d,ee)];d+=A&15;var y=A>>4;if(y<16)T[D++]=y;else{var j=0,M=0;for(y==16?(M=3+Z(e,d,3),d+=2,j=T[D-1]):y==17?(M=3+Z(e,d,7),d+=3):y==18&&(M=11+Z(e,d,127),d+=7);M--;)T[D++]=j}}var N=T.subarray(0,S),P=T.subarray(S);h=_i(N),g=_i(P),p=X(N,h,1),m=X(P,g,1)}else Q(1);if(d>_){c&&Q(0);break}}s&&l(f+131072);for(var te=(1<<h)-1,F=(1<<g)-1,ne=d;;ne=d){var j=p[vi(e,d)&te],I=j>>4;if(d+=j&15,d>_){c&&Q(0);break}if(j||Q(2),I<256)n[f++]=I;else if(I==256){ne=d,p=null;break}else{var L=I-254;if(I>264){var D=I-257,R=$r[D];L=Z(e,d,(1<<R)-1)+ii[D],d+=R}var re=m[vi(e,d)&F],ie=re>>4;re||Q(3),d+=re&15;var P=si[ie];if(ie>3){var R=ei[ie];P+=vi(e,d)&(1<<R)-1,d+=R}if(d>_){c&&Q(0);break}s&&l(f+131072);var ae=f+L;if(f<P){var oe=a-P,se=Math.min(P,ae);for(oe+f<0&&Q(3);f<se;++f)n[f]=r[oe+f]}for(;f<ae;++f)n[f]=n[f-P]}}t.l=p,t.p=ne,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?bi(n,0,f):n.subarray(0,f)},$=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},Ci=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},wi=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var i=n.length,a=n.slice();if(!i)return{t:ji,l:0};if(i==1){var o=new q(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var s=n[0],c=n[1],l=0,u=1,d=2;for(n[0]={s:-1,f:s.f+c.f,l:s,r:c};u!=i-1;)s=n[n[l].f<n[d].f?l++:d++],c=n[l!=u&&n[l].f<n[d].f?l++:d++],n[u++]={s:-1,f:s.f+c.f,l:s,r:c};for(var f=a[0].s,r=1;r<i;++r)a[r].s>f&&(f=a[r].s);var p=new J(f+1),m=Ti(n[u-1],p,0);if(m>t){var r=0,h=0,g=m-t,_=1<<g;for(a.sort(function(e,t){return p[t.s]-p[e.s]||e.f-t.f});r<i;++r){var v=a[r].s;if(p[v]>t)h+=_-(1<<m-p[v]),p[v]=t;else break}for(h>>=g;h>0;){var y=a[r].s;p[y]<t?h-=1<<t-p[y]++-1:++r}for(;r>=0&&h;--r){var b=a[r].s;p[b]==t&&(--p[b],++h)}m=t}return{t:new q(p),l:m}},Ti=function(e,t,n){return e.s==-1?Math.max(Ti(e.l,t,n+1),Ti(e.r,t,n+1)):t[e.s]=n},Ei=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new J(++t),r=0,i=e[0],a=1,o=function(e){n[r++]=e},s=1;s<=t;++s)if(e[s]==i&&s!=t)++a;else{if(!i&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(i),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(i);a=1,i=e[s]}return{c:n.subarray(0,r),n:t}},Di=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},Oi=function(e,t,n){var r=n.length,i=yi(t+2);e[i]=r&255,e[i+1]=r>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var a=0;a<r;++a)e[i+a+4]=n[a];return(i+4+r)*8},ki=function(e,t,n,r,i,a,o,s,c,l,u){$(t,u++,n),++i[256];for(var d=wi(i,15),f=d.t,p=d.l,m=wi(a,15),h=m.t,g=m.l,_=Ei(f),v=_.c,y=_.n,b=Ei(h),x=b.c,S=b.n,C=new J(19),w=0;w<v.length;++w)++C[v[w]&31];for(var w=0;w<x.length;++w)++C[x[w]&31];for(var T=wi(C,7),E=T.t,D=T.l,O=19;O>4&&!E[ti[O-1]];--O);var ee=l+5<<3,k=Di(i,di)+Di(a,fi)+o,A=Di(i,f)+Di(a,h)+o+14+3*O+Di(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&ee<=k&&ee<=A)return Oi(t,u,e.subarray(c,c+l));var j,M,N,P;if($(t,u,1+(A<k)),u+=2,A<k){j=X(f,p,0),M=f,N=X(h,g,0),P=h;var te=X(E,D,0);$(t,u,y-257),$(t,u+5,S-1),$(t,u+10,O-4),u+=14;for(var w=0;w<O;++w)$(t,u+3*w,E[ti[w]]);u+=3*O;for(var F=[v,x],ne=0;ne<2;++ne)for(var I=F[ne],w=0;w<I.length;++w){var L=I[w]&31;$(t,u,te[L]),u+=E[L],L>15&&($(t,u,I[w]>>5&127),u+=I[w]>>12)}}else j=pi,M=di,N=hi,P=fi;for(var w=0;w<s;++w){var R=r[w];if(R>255){var L=R>>18&31;Ci(t,u,j[L+257]),u+=M[L+257],L>7&&($(t,u,R>>23&31),u+=$r[L]);var re=R&31;Ci(t,u,N[re]),u+=P[re],re>3&&(Ci(t,u,R>>5&8191),u+=ei[re])}else Ci(t,u,j[R]),u+=M[R]}return Ci(t,u,j[256]),u+M[256]},Ai=new Qr([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ji=new q(0),Mi=function(e,t,n,r,i,a){var o=a.z||e.length,s=new q(r+o+5*(1+Math.ceil(o/7e3))+i),c=s.subarray(r,s.length-i),l=a.l,u=(a.r||0)&7;if(t){u&&(c[0]=a.r>>3);for(var d=Ai[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new J(32768),g=a.h||new J(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new Qr(25e3),x=new J(288),S=new J(32),C=0,w=0,T=a.i||0,E=0,D=a.w||0,O=0;T+2<o;++T){var ee=y(T),k=T&32767,A=g[ee];if(h[k]=A,g[ee]=k,D<=T){var j=o-T;if((C>7e3||E>24576)&&(j>423||!l)){u=ki(e,c,0,b,x,S,w,E,O,T-O,u),E=C=w=0,O=T;for(var M=0;M<286;++M)x[M]=0;for(var M=0;M<30;++M)S[M]=0}var N=2,P=0,te=p,F=k-A&32767;if(j>2&&ee==y(T-F))for(var ne=Math.min(f,j)-1,I=Math.min(32767,T),L=Math.min(258,j);F<=I&&--te&&k!=A;){if(e[T+N]==e[T+N-F]){for(var R=0;R<L&&e[T+R]==e[T+R-F];++R);if(R>N){if(N=R,P=F,R>ne)break;for(var re=Math.min(F,R-2),ie=0,M=0;M<re;++M){var ae=T-F+M&32767,oe=ae-h[ae]&32767;oe>ie&&(ie=oe,A=ae)}}}k=A,A=h[k],F+=k-A&32767}if(P){b[E++]=268435456|ai[N]<<18|ci[P];var se=ai[N]&31,ce=ci[P]&31;w+=$r[se]+ei[ce],++x[257+se],++S[ce],D=T+N,++C}else b[E++]=e[T],++x[e[T]]}}for(T=Math.max(T,D);T<o;++T)b[E++]=e[T],++x[e[T]];u=ki(e,c,l,b,x,S,w,E,O,T-O,u),l||(a.r=u&7|c[u/8|0]<<3,u-=7,a.h=g,a.p=h,a.i=T,a.w=D)}else{for(var T=a.w||0;T<o+l;T+=65535){var z=T+65535;z>=o&&(c[u/8|0]=l,z=o),u=Oi(c,u+1,e.subarray(T,z))}a.i=o}return bi(s,0,r+yi(u)+i)},Ni=function(){var e=1,t=0;return{p:function(n){for(var r=e,i=t,a=n.length|0,o=0;o!=a;){for(var s=Math.min(o+2655,a);o<s;++o)i+=r+=n[o];r=(r&65535)+15*(r>>16),i=(i&65535)+15*(i>>16)}e=r,t=i},d:function(){return e%=65521,t%=65521,(e&255)<<24|(e&65280)<<8|(t&255)<<8|t>>8}}},Pi=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new q(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return Mi(e,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,r,i)},Fi=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},Ii=function(e,t){var n=t.level,r=n==0?0:n<6?1:n==9?3:2;if(e[0]=120,e[1]=r<<6|(t.dictionary&&32),e[1]|=31-(e[0]<<8|e[1])%31,t.dictionary){var i=Ni();i.p(t.dictionary),Fi(e,2,i.d())}},Li=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&Q(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&Q(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2},Ri=function(){function e(e,t){typeof e==`function`&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new q(32768),this.p=new q(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||Q(5),this.d&&Q(4),!this.p.length)this.p=e;else if(e.length){var t=new q(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=Si(this.p,this.s,this.o);this.ondata(bi(n,t,this.s.b),this.d),this.o=bi(n,this.s.b-32768),this.s.b=this.o.length,this.p=bi(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}();function zi(e,t){t||={};var n=Ni();n.p(e);var r=Pi(e,t,t.dictionary?6:2,4);return Ii(r,t),Fi(r,r.length-4,n.d()),r}var Bi=function(){function e(e,t){Ri.call(this,e,t),this.v=e&&e.dictionary?2:1}return e.prototype.push=function(e,t){if(Ri.prototype.e.call(this,e),this.v){if(this.p.length<6&&!t)return;this.p=this.p.subarray(Li(this.p,this.v-1)),this.v=0}t&&(this.p.length<4&&Q(6,`invalid zlib data`),this.p=this.p.subarray(0,-4)),Ri.prototype.c.call(this,t)},e}();function Vi(e,t){return Si(e.subarray(Li(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}var Hi=typeof TextDecoder<`u`&&new TextDecoder;try{Hi.decode(ji,{stream:!0})}catch{}var Ui=56,Wi=[75,82,67,49];function Gi(e){let t=e.replace(/-/g,``);if(!/^[0-9a-f]{32}$/i.test(t))throw RangeError(`recording id must be a uuid`);return Uint8Array.from({length:16},(e,n)=>parseInt(t.slice(2*n,2*n+2),16))}function Ki(e){let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function qi(e,t,n){let r=56+n.reduce((e,t)=>e+12+t.bytes.length,0),i=new Uint8Array(r),a=new DataView(i.buffer);i.set(Wi,0),a.setUint16(4,1,!0),a.setUint16(6,56,!0),i.set(Gi(e),8),a.setUint32(24,t,!0),a.setUint32(28,n.length,!0),a.setUint32(32,r,!0),a.setFloat64(40,n[0]?.at??0,!0),a.setFloat64(48,n.at(-1)?.at??0,!0);let o=56;for(let e of n)a.setFloat64(o,e.at,!0),a.setUint32(o+8,e.bytes.length,!0),i.set(e.bytes,o+12),o+=12+e.bytes.length;return i}function Ji(e){if(e.length<56||Wi.some((t,n)=>e[n]!==t))throw RangeError(`not a KRC1 chunk`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint16(4,!0);if(n!==1)throw RangeError(`KRC version ${n}`);let r=t.getUint16(6,!0);if(r<56)throw RangeError(`KRC header too short`);return{recordingId:Ki(e.subarray(8,24)),seq:t.getUint32(24,!0),count:t.getUint32(28,!0),bytes:t.getUint32(32,!0),headerBytes:r,t0:t.getFloat64(40,!0),t1:t.getFloat64(48,!0)}}function Yi(e){let t=Ji(e),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=Math.min(e.length,t.bytes),i=[],a=t.headerBytes;for(;i.length<t.count&&a+12<=r;){let t=n.getUint32(a+8,!0);if(a+12+t>r)break;i.push({at:n.getFloat64(a,!0),bytes:e.subarray(a+12,a+12+t)}),a+=12+t}return{header:t,messages:i,truncated:i.length<t.count}}var Xi=e=>crypto.subtle.digest(`SHA-256`,e),Zi=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),Qi=e=>Uint8Array.from(e.replace(/-/g,``).match(/../g)??[],e=>parseInt(e,16));async function $i(e,t,n,r){let i=t[t.length-1];if(!i||(i.bytes[0]&127)!=8)return`unchecked`;let a=await n(i.bytes).catch(()=>null),o=a?Wr(a.plaintext):null,s=Zi(await Xi(Qi(e.recordingId))).slice(0,16);return o&&o.lane===1&&o.run===s&&o.seq===BigInt(e.seq)&&e.seq===r&&o.count===t.length-1&&Zi((await qr(t.slice(0,-1).map(e=>Xi(e.bytes)))).buffer)===Zi(o.hash.buffer)?`verified`:`broken`}function ea(e){let t=[...e],n=new Set(t.filter(e=>e.check!==`unchecked`).map(e=>e.rid)),r={verified:0,broken:0,unchecked:0};for(let e of t)e.check===`unchecked`&&n.has(e.rid)?r.broken++:r[e.check]++;return r}var ta=(e,t,n)=>`recording_key:${e}|${t}:${n}`,na=(e,t,n)=>n===e.stream_epoch?ut(e.stream_id,t,n):ta(e.id,t,n),ra=12,ia=16;function aa(e){let t=new Map;return async n=>{if(n.length===0)return null;let r=n[0]&128?2:1;if(n.length<r+ra+ia)return null;let i=r===2?n[1]:null,a=t.get(i),o=[...a?[a]:[],...e.filter(e=>(e.keyId===i||e.keyId===null)&&e.key!==a).map(e=>e.key)];for(let e of o)try{let a=await qe(e,n.subarray(r,r+ra),n.subarray(r+ra),n.subarray(0,r));return t.set(i,e),{kind:n[0]&-129,plaintext:a}}catch{}return null}}var oa=8192;async function*sa(e){let t=0;for(;t+56<=e.size;){let n=Ji(await e.read(t,56));if(yield await e.slice(t,n.bytes),n.bytes<=56)return;t+=n.bytes}}function ca(e){let t=e.filter(e=>e&&typeof e.t==`number`&&Array.isArray(e.signals)),n={},r={};return t.forEach((e,i)=>{for(let a of e.signals){if(!a||typeof a.name!=`string`)continue;let e=n[a.name]??=new Float64Array(t.length).fill(NaN);e[i]=typeof a.value==`number`?a.value:NaN,a.unit&&!r[a.name]&&(r[a.name]=a.unit)}}),{t:t.map(e=>e.t),columns:n,units:r}}var la=4096;function ua(e){let t=2166136261^e.length;for(let n=0,r=Math.min(e.length,64);n<r;n++)t=Math.imul(t^e[n],16777619);return t>>>0}var da=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),fa=class{known=new Map;real=new Set;pending=new Set;held=new Set;note(e){for(let t of e){let e=this.known.get(t.name);(!e||t.t>=e.t)&&this.known.set(t.name,{t:t.t,v:t.v,unit:t.unit}),!this.real.has(t.name)&&!this.held.has(t.name)&&this.pending.add(t.name)}}sampled(e){if(this.pending.size+this.held.size===0)return;let t=e=>{(this.pending.delete(e)||this.held.delete(e))&&this.real.add(e)};for(let[n,r]of Object.entries(e.columns))if(!(!this.pending.has(n)&&!this.held.has(n))){for(let e=0;e<r.length;e++)if(Number.isFinite(r[e])){t(n);break}}if(e.events&&e.schema){let{index:n,v:r}=e.events;for(let i=0;i<r.length;i++)Number.isFinite(r[i])&&t(e.schema.channels[n[i]].name)}}start(e){if(this.pending.size===0||e.t.length===0)return e;let t={...e.columns},n={...e.units};for(let e of this.pending){let r=this.known.get(e);t[e]=Float64Array.of(r.v),r.unit&&!n[e]&&(n[e]=r.unit),this.held.add(e)}let r=[...this.pending];return this.pending.clear(),{...e,columns:t,units:n,more:r}}end(e,t){if(e===null||this.held.size===0)return null;let n={},r={};for(let e of this.held){let t=this.known.get(e);n[e]=Float64Array.of(t.v),t.unit&&(r[e]=t.unit)}return{at:t,t:[e],columns:n,units:r}}};async function*pa(e,t,n,r,i=!1){let a=aa(e.keys??[]),o=new Map,s=new Map,c=r?null:new fa,l=null,u=0,d=e=>c?(c.sampled(e),e.t.length&&(l=+e.t[e.t.length-1],u=e.at),c.start(e)):e,f={results:[]};for await(let e of sa(t)){let{header:t,messages:l}=Yi(e);if(n.t0??=t.t0,i){let e=t.recordingId;f.results.push({rid:e,check:await $i(t,l,a,f.rid===e?(f.seq??-1)+1:0)}),f.rid=e,f.seq=t.seq,n.chain=ea(f.results)}for(let e of l){let t=ua(e.bytes),i=s.get(t);if(i&&da(i,e.bytes))continue;s.set(t,e.bytes),s.size>la&&s.delete(s.keys().next().value);let l=await a(e.bytes);if(!l){n.lost++;continue}try{if(l.kind===5){let e=await br(l.plaintext);o.set(e.id,e);continue}if(l.kind===4||l.kind===9){let t;if(l.kind===4){let r=await Tr(l.plaintext,o);if(!r){n.lost++;continue}t={at:e.at,t:r.block.t,columns:r.block.columns,units:r.block.units??{},historical:r.historical,schema:o.get(r.schemaId)}}else{let r=await Er(l.plaintext,o);if(!r){n.lost++;continue}t={at:e.at,t:r.t,columns:{},units:{},historical:r.historical,events:{index:r.index,v:r.v},schema:o.get(r.schemaId)}}t.historical&&c?.sampled(t),(r===void 0||r===!!t.historical)&&(yield t.historical?t:d(t));continue}if(r)continue;if(l.kind===7){let e=await Sr(l.plaintext,o);e&&c?.note(e)}else if(l.kind===3){let t=or(l.plaintext);yield d({at:e.at,t:t.t,columns:t.columns,units:t.units??{}})}else if(l.kind===2){let t=Yn(l.plaintext);yield d({at:e.at,...ca(Array.isArray(t?.frames)?t.frames:[])})}}catch{n.lost++}}}let p=c?.end(l,u);p&&(yield p)}function ma(e,t,n){let r=e===null?t:t===null?e:Math.min(e,t);return r===null?{}:r>1e9?{wallOrigin:String(r),wallQuality:`exact`}:Number.isFinite(n)?{wallOrigin:String(r+n),wallQuality:`approx`}:{}}var ha={id:`krc`,label:`Kymoscope recording`,extensions:[],sniff:()=>!1,async plan(e,t){let n=[on],r=new Map([[on,`s`]]),i={lost:0,t0:null},a=0,o=!1,s=null,c=null,l=0,u=-1/0,d=0,f=1/0,p=(e,t=``)=>{e!==`ElapsedTime`&&(r.has(e)?!r.get(e)&&t&&r.set(e,t):(n.push(e),r.set(e,t)))},m=new Set;for await(let n of pa(e,t,i,void 0,!0)){a+=n.t.length,n.historical&&(o=!0);let e=n.t.length;if(e&&n.historical?c??=+n.t[0]:e&&(s??=+n.t[0],+n.t[0]+l<u&&(l=u+Math.max(0,(n.at-d)/1e3)-+n.t[0]),d=n.at,u=+n.t[e-1]+l,f=Math.min(f,n.at/1e3-u)),n.schema){if(!m.has(n.schema.id)){m.add(n.schema.id);for(let e of n.schema.channels)p(e.name,e.unit)}for(let e of n.more??[])p(e,n.units[e])}else for(let e of Object.keys(n.columns))p(e,n.units[e])}let h=n.map(e=>({name:e,unit:r.get(e)??``})),g=i.lost?[`${i.lost} ${i.lost===1?`message`:`messages`} couldn't be opened with the keys this browser has.`]:[],_=i.chain?.broken??0,v=n.length-1,y=v>1e3?[{group:0,channels:n.slice(0,Ar+1).map((e,t)=>t)}]:void 0;return y&&g.push(`This recording has ${v.toLocaleString(`en-US`)} channels; the first ${Ar.toLocaleString(`en-US`)} are loaded.`),_&&g.push(`Some of this recording was missing, out of order or changed where it is stored (${_} of ${_+(i.chain?.verified??0)} checked ${_+(i.chain?.verified??0)===1?`chunk`:`chunks`}).`),{format:`Kymoscope recording`,startTime:i.t0===null?null:new Date(i.t0).toISOString(),groups:[{name:`Recording`,channels:h,samples:a,time:{kind:`timestamps`},rateHz:null}],meta:{...ma(s,c,f),...i.chain&&(i.chain.verified||i.chain.broken)?{chainVerified:String(i.chain.verified),chainBroken:String(i.chain.broken),chainUnchecked:String(i.chain.unchecked)}:{}},events:[],notes:g,defaultSelection:y,state:{names:n,backlog:o}}},async*stream(e){let{names:t,backlog:n=!1}=e.plan.state,r=e.selection.find(e=>e.group===0)?.channels??[],i=new Map(r.map((e,n)=>[t[e],n])),a=i.get(on),o=()=>r.map(()=>new Float64Array(oa).fill(NaN)),s=new Float64Array(oa),c=o(),l=0,u=0,d=0,f=null,p=()=>{let e={group:0,time:s.slice(0,l),start:u,length:l,columns:c.map(e=>e.slice(0,l))};return u+=l,l=0,s=new Float64Array(oa),c=o(),e},m=new WeakMap,h=e=>{let t=m.get(e);return t||m.set(e,t=Int32Array.from(e.channels,e=>e.name===`ElapsedTime`?-2:i.get(e.name)??-1)),t};function*g(e,t,n,r){let o=Object.entries(e.columns).flatMap(([e,t])=>{let n=e===`ElapsedTime`?void 0:i.get(e);return n===void 0?[]:[[n,+t[0]]]});for(let i=0;i<e.t.length;i++){let u=r[t[i]];if(u===-1&&!(i===0&&o.length))continue;let m=+e.t[i];if(s[l]=m+d-f,a!==void 0&&(c[a][l]=m),u>=0&&(c[u][l]=n[i]),i===0)for(let[e,t]of o)c[e][l]=t;++l===oa&&(yield p())}}function*_(e){let t=e.t.length;if(t&&(f??=+e.t[0]+d),e.events&&e.schema)return yield*g(e,e.events.index,e.events.v,h(e.schema));for(let n=0;n<t;){let r=Math.min(t-n,oa-l);for(let t=0;t<r;t++)s[l+t]=+e.t[n+t]+d-f;if(a!==void 0)for(let t=0;t<r;t++)c[a][l+t]=+e.t[n+t];for(let[t,a]of Object.entries(e.columns)){let e=t===`ElapsedTime`?void 0:i.get(t);if(e===void 0)continue;let o=c[e];if(a instanceof Float64Array||a instanceof Float32Array)o.set(a.subarray(n,n+r),l);else for(let e=0;e<r;e++)o[l+e]=+a[n+e]}l+=r,n+=r,l===oa&&(yield p())}}for await(let t of ga(e.files,e.io,n,e.signal))d=t.shift,yield*_(t.b);l>0&&(yield p())}};async function*ga(e,t,n,r){let i=0,a=-1/0,o=0,s=n?pa(e,t,{lost:0,t0:null},!0):null,c=async()=>{for(let e=await s?.next();e&&!e.done;e=await s.next())if(e.value.t.length)return e.value;return null},l=await c();for await(let s of pa(e,t,{lost:0,t0:null},n?!1:void 0)){if(r?.aborted)return;let e=s.t.length;if(e!==0){for(+s.t[0]+i<a&&(i=a+Math.max(0,(s.at-o)/1e3)-+s.t[0]),o=s.at;l&&+l.t[0]<+s.t[0];l=await c())yield{b:l,shift:i};yield{b:s,shift:i},a=+s.t[e-1]+i}}for(;l&&!r?.aborted;l=await c())yield{b:l,shift:i}}async function*_a(e,t,n,r){let{names:i,backlog:a=!1}=n.state,o=new Map(i.map((e,t)=>[e,t]));o.delete(on);let s=new WeakMap,c=e=>{let t=s.get(e);return t||s.set(e,t=Int32Array.from(e.channels,e=>o.get(e.name)??-1)),t},l=null;for await(let{b:n,shift:i}of ga(e,t,a,r)){l??=+n.t[0]+i;let e=i-l,t=Object.entries(n.columns).flatMap(([e,t])=>{let n=o.get(e);return n===void 0?[]:[[n,t]]}),r=(n.events?.v.length??0)+t.reduce((e,[,t])=>e+t.length,0),a={t:new Float64Array(r),ch:new Uint32Array(r),v:new Float64Array(r),n:0},s=(t,n,r)=>{Number.isNaN(r)||(a.t[a.n]=t+e,a.ch[a.n]=n,a.v[a.n++]=r)},u=n.events?1:n.t.length;for(let e=0;e<u;e++)for(let[r,i]of t)e<i.length&&s(+n.t[e],r,+i[e]);if(n.events&&n.schema){let e=c(n.schema),{index:t,v:r}=n.events;for(let i=0;i<r.length;i++)e[t[i]]>=0&&s(+n.t[i],e[t[i]],r[i])}a.n&&(yield a)}}export{Ve as $,ce as $t,Xn as A,St as At,Xt as B,ye as Bt,Nr as C,vt as Ct,Er as D,st as Dt,Sr as E,it as Et,dn as F,ke as Ft,Yt as G,de as Gt,Bt as H,he as Ht,an as I,_e as It,xt as J,se as Jt,Jt as K,ue as Kt,Vt as L,be as Lt,nr as M,at as Mt,Yn as N,Me as Nt,or as O,Xe as Ot,on as P,je as Pt,Be as Q,R as Qt,Kt as R,De as Rt,Ar as S,_t as St,br as T,ut as Tt,Wt as U,pe as Ut,qt as V,ge as Vt,Ht as W,fe as Wt,Tt as X,re as Xt,Et as Y,oe as Yt,dt as Z,z as Zt,qr as _,n as _n,Dt as _t,ea as a,M as an,Ze as at,Ur as b,kt as bt,qi as c,u as cn,gt as ct,Bi as d,y as dn,Lt as dt,L as en,bt as et,Vi as f,g as fn,wt as ft,Yr as g,r as gn,It as gt,Lr as h,k as hn,Ot as ht,na as i,j as in,ze as it,tr as j,Ct as jt,Zn as k,yt as kt,Yi as l,h as ln,jt as lt,Ir as m,b as mn,ft as mt,ha as n,N as nn,nt,$i as o,D as on,pt as ot,zi as p,x as pn,lt as pt,Fe as q,le as qt,ta as r,I as rn,Rt as rt,Ui as s,l as sn,Ye as st,_a as t,ne as tn,Qe as tt,Ji as u,v as un,Pt as ut,Xr as v,a as vn,zt as vt,Tr as w,et as wt,Jr as x,Mt as xt,Wr as y,mt as yt,Gt as z,Oe as zt};
|