@kymoscope/sdk 0.18.0 → 0.19.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-BEjFe0TV.js → importer.worker-BTbPiEHd.js} +1 -1
- package/dist/{keys-CbPoU_jx.js → importer-O00bqqEU.js} +4 -4
- package/dist/importers-C90FOCV-.js +5 -0
- package/dist/kymoscope-embed.js +59 -58
- package/dist/kymoscope-sdk.js +86 -84
- package/dist/types/lib/recordings/importer.d.ts +17 -1
- package/package.json +1 -1
- package/dist/importers-4ETLHzYe.js +0 -5
|
@@ -3,4 +3,4 @@ const e=1<<20,t=16<<20;var n=class{size;bytesRead=0;#e;#t=new Map;constructor(e)
|
|
|
3
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
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
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={mdf:Ut,edf:Yt,xdf:cn,tdms:Sn,hdf5:Jn,mat:_r,comtrade:Er,krc:{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=-1/0,p=0,m=null,h=()=>{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},g=new WeakMap,_=e=>{let t=g.get(e);return t||g.set(e,t=Int32Array.from(e.channels,e=>e.name===`ElapsedTime`?-2:i.get(e.name)??-1)),t};function*v(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 f=+e.t[i];if(s[l]=f+d-m,a!==void 0&&(c[a][l]=f),u>=0&&(c[u][l]=n[i]),i===0)for(let[e,t]of o)c[e][l]=t;++l===$&&(yield h())}}function*y(e){let t=e.t.length;if(t&&(m??=+e.t[0]+d),e.events&&e.schema)return yield*v(e,e.events.index,e.events.v,_(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-m;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 h())}}let b=n?Vi(e.files,e.io,{lost:0,t0:null},!0):null,x=async()=>{for(let e=await b?.next();e&&!e.done;e=await b.next())if(e.value.t.length)return e.value;return null},S=await x();for await(let t of Vi(e.files,e.io,{lost:0,t0:null},n?!1:void 0)){if(e.signal?.aborted)return;let n=t.t.length;if(n!==0){for(+t.t[0]+d<f&&(d=f+Math.max(0,(t.at-p)/1e3)-+t.t[0]),p=t.at;S&&+S.t[0]<+t.t[0];S=await x())yield*y(S);yield*y(t),f=+t.t[n-1]+d}}for(;S&&!e.signal?.aborted;S=await x())yield*y(S);l>0&&(yield h())}}};function Wi(e){let t=Ui[e];if(!t)throw Error(`No importer for format ${e}.`);return t}const Gi=`This file's groups do not interleave in time: reading them together would hold too much in memory. Choose fewer groups, or split them.`,Ki=e=>e.length*(1+e.columns.length);function qi(e){let t=e[Symbol.asyncIterator]();return{pull:async()=>{let e=await t.next();return e.done?null:e.value}}}function Ji(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-=Ki(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+=Ki(o.value))>128e6))throw Error(Gi)}};return n.map((e,t)=>({pull:()=>a(t)}))}function Yi(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 Xi=new Int32Array,Zi={t:new Float64Array,cols:[],from:0};function Qi(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 $i=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=ea(Yi(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(Gi)}};function ea(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 ta(e,t){let n=e.length,r=e.map(e=>e.t),i=Int32Array.from(e,e=>e.from),a=Int32Array.from(e,e=>Qi(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 na(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 ra(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];na(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}na(e,d,u,p,l-1,c[p]),o=c[l-1],t=d[u+l-1]}e.fill(t,o,e.length)}function ia(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 aa(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):Xi}function oa(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=Qi(i,e,r.from,i.length),o=new Int32Array(a-r.from);if(c.push(aa(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 ia(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),ra(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 sa(e,t,n,r,i,a=!1){let o=e.map((e,r)=>new $i(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=ta(l.map(e=>e.pending[0]??Zi),e),n=[t];for(let e=0;e<o.length;e++)n.push(...oa(o[e],t,c[e],u&&c[e],a));d+=t.length,t.length&&await r({length:t.length,columns:n})}return d}var ca=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 la(e,t,n){return ee(await e.plan(t,n))}const ua=(e,t,n)=>Math.max(0,Math.min(e,Math.max(1<<20,n),Math.floor(1e8/t)));function da(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 fa(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 pa(e,t,n,r,i,a,o={}){let s=da(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=>qi(d(e.streamGroup({...f,selection:[t]},t.group)))):Ji(d(e.stream(f)),new Map(i.map((e,t)=>[e.group,t]))),m=fa(n,i),h=a===`memory`?new ca(s,ua(m,s.length,r.size)):null,g=0,_=await sa(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 ma(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 ha(e,t=Wi){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 la(r,i,a),e({type:`plan`,plan:{...o,state:void 0}});return}a.bytesRead=0;let u=await pa(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]=ma(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 ga=self;let _a=null;Mn(async()=>{if(!_a)throw Error(`The import worker was not told where the HDF5 reader is.`);await import(_a);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 va=ha((e,t)=>ga.postMessage(e,t??[]));ga.onmessage=e=>{e.data.type===`init`?_a=e.data.h5Url:va(e.data)};
|
|
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)};
|