@kymoscope/sdk 0.13.0 → 0.14.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-C63-1oBd.js → importer.worker-BblHvxro.js} +1 -1
- package/dist/importers-f62zcRz2.js +5 -0
- package/dist/keys-CdXDP3WJ.js +11 -0
- package/dist/kymoscope-embed.js +85 -85
- package/dist/kymoscope-sdk.js +85 -85
- package/dist/types/charts/chartWindow.d.ts +13 -0
- package/dist/types/components/dashboardGridLayout.d.ts +7 -0
- package/dist/types/engine/createEngine.d.ts +3 -0
- package/dist/types/engine/types.d.ts +8 -0
- package/dist/types/index.d.ts +1 -1
- package/dist/types/lib/live/crypto.d.ts +1 -0
- package/dist/types/lib/live/publisher.d.ts +2 -1
- package/dist/types/lib/live/videoTrack.d.ts +5 -0
- package/dist/types/lib/recordings/chainCheck.d.ts +24 -0
- package/dist/types/lib/recordings/videoSource.d.ts +6 -0
- package/dist/types/lib/recordings/writer.d.ts +6 -0
- package/package.json +1 -1
- package/dist/importers-IlQKVrkS.js +0 -5
- package/dist/keys-BPymBse7.js +0 -11
|
@@ -13,8 +13,19 @@ export interface ChartWindowOptions {
|
|
|
13
13
|
/** Initial size in CSS px (the browser may adjust it). */
|
|
14
14
|
width?: number;
|
|
15
15
|
height?: number;
|
|
16
|
+
/** Initial position in screen px. Another screen than the page's needs the browser's window-management
|
|
17
|
+
* permission (`getScreenDetails()`); without it the browser keeps the window on the page's screen. */
|
|
18
|
+
left?: number;
|
|
19
|
+
top?: number;
|
|
16
20
|
mount?: MountOptions;
|
|
17
21
|
}
|
|
22
|
+
/** Where a chart window sits on the screens: its position and its content size. */
|
|
23
|
+
export interface WindowPlacement {
|
|
24
|
+
left: number;
|
|
25
|
+
top: number;
|
|
26
|
+
width: number;
|
|
27
|
+
height: number;
|
|
28
|
+
}
|
|
18
29
|
export interface ChartWindow {
|
|
19
30
|
readonly chartId: string;
|
|
20
31
|
readonly window: Window;
|
|
@@ -29,3 +40,5 @@ export interface ChartWindow {
|
|
|
29
40
|
export declare function openChartWindow(engine: KymoscopeEngine, chartId: string, mount: (element: HTMLElement, options?: MountOptions) => ChartView, o?: ChartWindowOptions): ChartWindow;
|
|
30
41
|
/** Close every chart window of an engine (on dispose). */
|
|
31
42
|
export declare function closeChartWindows(engine: KymoscopeEngine): void;
|
|
43
|
+
/** Where each open chart window of an engine is now. */
|
|
44
|
+
export declare function windowPlacements(engine: KymoscopeEngine): Map<string, WindowPlacement>;
|
|
@@ -20,6 +20,13 @@ export interface DashboardPanel {
|
|
|
20
20
|
rect: DashboardGridRect;
|
|
21
21
|
/** User-defined chart title. When empty/undefined the kind label is used. */
|
|
22
22
|
title?: string;
|
|
23
|
+
/** Its own browser window when recorded (charts.recordWindows): a saved workbook keeps it so the host can offer to reopen it there. */
|
|
24
|
+
window?: {
|
|
25
|
+
left: number;
|
|
26
|
+
top: number;
|
|
27
|
+
width: number;
|
|
28
|
+
height: number;
|
|
29
|
+
};
|
|
23
30
|
}
|
|
24
31
|
/** Legacy 12-col grid → current scale (96 / 12 = 8). */
|
|
25
32
|
export declare const LEGACY_GRID_SCALE = 8;
|
|
@@ -269,6 +269,9 @@ export declare function createEngine(options?: EngineOptions): {
|
|
|
269
269
|
* Opening an already open chart focuses its window. Throws `popup_blocked` when the browser refuses.
|
|
270
270
|
*/
|
|
271
271
|
openWindow(chartId: string, options?: ChartWindowOptions): ChartWindow;
|
|
272
|
+
/** Record in every chart where its window is now (chart.window; null: in no window), so a workbook saved next
|
|
273
|
+
* reopens the windows open then. Call it before a deliberate save; autosaves keep what was recorded. No undo step. */
|
|
274
|
+
recordWindows(): void;
|
|
272
275
|
/** Font families for every chart's text (canvas text cannot inherit CSS fonts). */
|
|
273
276
|
setFonts(fonts: {
|
|
274
277
|
sans?: string;
|
|
@@ -140,6 +140,14 @@ export interface ChartModel {
|
|
|
140
140
|
w: number;
|
|
141
141
|
h: number;
|
|
142
142
|
};
|
|
143
|
+
/** Where its own browser window was at the last charts.recordWindows(), in screen px (content size); null: in none.
|
|
144
|
+
* A workbook opened with this set has no window yet: offer to reopen it (openWindow puts it back there). */
|
|
145
|
+
window: {
|
|
146
|
+
left: number;
|
|
147
|
+
top: number;
|
|
148
|
+
width: number;
|
|
149
|
+
height: number;
|
|
150
|
+
} | null;
|
|
143
151
|
}
|
|
144
152
|
export interface WorksheetState {
|
|
145
153
|
id: string;
|
package/dist/types/index.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export type { ColumnsInput } from './engine/columns';
|
|
|
21
21
|
export { verifyLicense } from './embed/license';
|
|
22
22
|
export type { LicenseResult } from './embed/license';
|
|
23
23
|
export type { ChartView, ChartViewEvents, MountOptions, ChartStyle } from './charts/runtime';
|
|
24
|
-
export type { ChartWindow, ChartWindowOptions } from './charts/chartWindow';
|
|
24
|
+
export type { ChartWindow, ChartWindowOptions, WindowPlacement } from './charts/chartWindow';
|
|
25
25
|
export type { ChartStatus, ContextMenuEvent } from './charts/ChartBody';
|
|
26
26
|
export * from './lib/panelChartSettings';
|
|
27
27
|
export { chartChannelCount } from './lib/chartChannels';
|
|
@@ -30,6 +30,7 @@ export declare function deriveKey(passphrase: string, saltB64: string): Promise<
|
|
|
30
30
|
export declare function deriveRawKeyBase64(passphrase: string, saltB64: string): Promise<string>;
|
|
31
31
|
/** Import raw AES-256 key bytes (base64) for encrypt/decrypt — e.g. a stream key. */
|
|
32
32
|
export declare function importRawKeyBase64(keyB64: string): Promise<CryptoKey>;
|
|
33
|
+
export declare function gcmIv(): Uint8Array;
|
|
33
34
|
/** Encrypt a JSON-serializable value into an envelope. */
|
|
34
35
|
export declare function encryptJSON(key: CryptoKey, value: unknown): Promise<EncryptedEnvelope>;
|
|
35
36
|
/** Decrypt an envelope to raw plaintext bytes. Throws if tampered/wrong key. */
|
|
@@ -211,7 +211,8 @@ export declare class LivePublisher {
|
|
|
211
211
|
/** Seal with the current stream key (the key id of its epoch when e2ee) and send; false if not sent
|
|
212
212
|
* (no key yet, socket down, stopped). */
|
|
213
213
|
send(kind: number, plaintext: Uint8Array): Promise<boolean>;
|
|
214
|
-
/** The sealed message send() would publish (what a recorder keeps), or null without a stream key yet.
|
|
214
|
+
/** The sealed message send() would publish (what a recorder keeps), or null without a stream key yet. It still
|
|
215
|
+
* seals after stop(): a recorder closing then seals its last chunk's checkpoint. */
|
|
215
216
|
seal(kind: number, plaintext: Uint8Array): Promise<Uint8Array<ArrayBuffer> | null>;
|
|
216
217
|
/** Publish an already sealed message; false when the socket is down. While a checkpoint is being sealed it waits
|
|
217
218
|
* for it (a few ms), so the wire keeps the order the checkpoint counts. */
|
|
@@ -52,6 +52,11 @@ export interface VideoSource {
|
|
|
52
52
|
onUnit?(fn: (u: EncodedUnit) => void): () => void;
|
|
53
53
|
/** Live: hold the video while it is shown; returns the release. */
|
|
54
54
|
acquire?(): () => void;
|
|
55
|
+
/** Recorded: its chunks' integrity checkpoints so far (RecordedVideoSource.integrity); null: none had one. */
|
|
56
|
+
integrity?(): {
|
|
57
|
+
verified: number;
|
|
58
|
+
broken: number;
|
|
59
|
+
} | null;
|
|
55
60
|
/** Recorded: resolves once the codec is known (info().codec). */
|
|
56
61
|
ready?(): Promise<void>;
|
|
57
62
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { KrcHeader, KrcMessage } from './krc';
|
|
2
|
+
export type ChunkCheck = 'verified' | 'broken' | 'unchecked';
|
|
3
|
+
export interface ChainCount {
|
|
4
|
+
verified: number;
|
|
5
|
+
broken: number;
|
|
6
|
+
unchecked: number;
|
|
7
|
+
}
|
|
8
|
+
type Open = (m: Uint8Array) => Promise<{
|
|
9
|
+
kind: number;
|
|
10
|
+
plaintext: Uint8Array;
|
|
11
|
+
} | null>;
|
|
12
|
+
/** One chunk's own checkpoint; `expectSeq`: the seq it must have (the one after the previous chunk of its recording,
|
|
13
|
+
* 0 for the first). Unchecked: it has none (an older sender, or a checkpoint its sender couldn't seal). */
|
|
14
|
+
export declare function checkChunk(header: Pick<KrcHeader, 'recordingId' | 'seq'>, messages: KrcMessage[], open: Open, expectSeq: number): Promise<ChunkCheck>;
|
|
15
|
+
/**
|
|
16
|
+
* The chunks' results by recording id. A chunk without a checkpoint in a recording whose other chunks have one is
|
|
17
|
+
* broken itself (stripped, or its sender failed to seal it): it never breaks the next one, which is checked against
|
|
18
|
+
* its header's seq. A recording with none at all (an older sender) is only unchecked.
|
|
19
|
+
*/
|
|
20
|
+
export declare function chainCount(results: Iterable<{
|
|
21
|
+
rid: string;
|
|
22
|
+
check: ChunkCheck;
|
|
23
|
+
}>): ChainCount;
|
|
24
|
+
export {};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type MessageKey } from '../live/wire';
|
|
2
2
|
import type { EncodedUnit, VideoSource, VideoTrackInfo } from '../live/videoTrack';
|
|
3
|
+
import { type ChainCount } from './chainCheck';
|
|
3
4
|
export interface RecordedVideoSourceOptions {
|
|
4
5
|
/** The camera stream's id (what a Camera panel's cameraStreamId names). */
|
|
5
6
|
id: string;
|
|
@@ -42,6 +43,8 @@ export declare class RecordedVideoSource implements VideoSource {
|
|
|
42
43
|
private height;
|
|
43
44
|
private codec;
|
|
44
45
|
private waiting;
|
|
46
|
+
/** Each downloaded chunk's checkpoint result, by chunk index (kept when its units are evicted). */
|
|
47
|
+
private checks;
|
|
45
48
|
constructor(o: RecordedVideoSourceOptions);
|
|
46
49
|
private parse;
|
|
47
50
|
private parsed;
|
|
@@ -52,5 +55,8 @@ export declare class RecordedVideoSource implements VideoSource {
|
|
|
52
55
|
/** Resolves once the codec is known (the first keyframe of the first chunks), or they had none. */
|
|
53
56
|
ready(): Promise<void>;
|
|
54
57
|
info(): VideoTrackInfo;
|
|
58
|
+
/** The checkpoints of the chunks downloaded so far; null while none had one (an older sender). A chunk of another
|
|
59
|
+
* recording than most of them is broken. ponytail: "most" of those downloaded so far. */
|
|
60
|
+
integrity(): ChainCount | null;
|
|
55
61
|
range(): [number, number] | null;
|
|
56
62
|
}
|
|
@@ -74,6 +74,9 @@ export interface BrowserRecorderOptions {
|
|
|
74
74
|
/** Own storage only: how long it keeps the files. */
|
|
75
75
|
retentionDays?: number;
|
|
76
76
|
onStatus?: (s: RecorderStatus) => void;
|
|
77
|
+
/** Seal with the stream key (LivePublisher.seal): every chunk then ends with a lane-1 checkpoint. Without it the
|
|
78
|
+
* chunks carry none (as before). */
|
|
79
|
+
seal?: (kind: number, plaintext: Uint8Array) => Promise<Uint8Array | null>;
|
|
77
80
|
/** Test seams. */
|
|
78
81
|
root?: () => Promise<RecDir>;
|
|
79
82
|
fetch?: typeof fetch;
|
|
@@ -155,6 +158,9 @@ export declare class BrowserRecorder {
|
|
|
155
158
|
private openFile;
|
|
156
159
|
private endFile;
|
|
157
160
|
private flush;
|
|
161
|
+
/** Lane 1: the chunk's last record becomes a checkpoint over its records (none without `seal`, a stream id that
|
|
162
|
+
* isn't a uuid, or no stream key: the chunk is then unchecked, as an older sender's). */
|
|
163
|
+
private checkpoint;
|
|
158
164
|
/** Every file under rec/ counts (one budget for every stream); past it the oldest chunks go. */
|
|
159
165
|
private enforceMax;
|
|
160
166
|
private status;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kymoscope/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "The Kymoscope data engine and charts for the browser: import large measurement files, plot them, stream live data end-to-end encrypted.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"homepage": "https://kymoscope.com/docs/introduction",
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
/*! @kymoscope/sdk (c) 2026 Kymoscope. Proprietary software: use requires a license. See LICENSE.md. */
|
|
2
|
-
import{Bt as e,D as t,Dt as n,Et as r,Ft as i,Gt as a,Ht as o,It as s,Kt as c,Lt as l,Nt as u,O as d,Ot as f,Pt as p,Rt as m,S as h,Ut as g,Vt as _,Wt as v,b as y,c as b,g as x,m as S,o as ee,qt as C,s as te,t as ne,x as re,y as ie,zt as ae}from"./keys-BPymBse7.js";function w(e,t){return e.selection.find(e=>e.group===t)?.channels??[]}var oe=4096,se={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,exp:Math.exp,ln:Math.log,log:Math.log,log10:Math.log10,sqrt:Math.sqrt,abs:Math.abs,pow:Math.pow,min:Math.min,max:Math.max};function ce(e){if(e.length>oe)return null;let t=e.match(/\d+\.?\d*(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|\*\*|[-+*/^(),]|\S/g)??[],n=0,r=()=>t[n],i=()=>{throw Error(`formula`)},a=e=>{t[n++]!==e&&i()},o=()=>{let e=s();for(;r()===`+`||r()===`-`;){let r=t[n++],i=e,a=s();e=r===`+`?e=>i(e)+a(e):e=>i(e)-a(e)}return e},s=()=>{let e=c();for(;r()===`*`||r()===`/`;){let r=t[n++],i=e,a=c();e=r===`*`?e=>i(e)*a(e):e=>i(e)/a(e)}return e},c=()=>{if(r()===`-`){n++;let e=c();return t=>-e(t)}return r()===`+`?(n++,c()):l()},l=()=>{let e=u();if(r()===`^`||r()===`**`){n++;let t=c();return n=>e(n)**t(n)}return e},u=()=>{let e=t[n++];if(e===void 0&&i(),e===`(`){let e=o();return a(`)`),e}if(/^[\d.]/.test(e)){let t=Number(e);return Number.isFinite(t)||i(),()=>t}if(e===`X`||e===`x`||e===`X1`)return e=>e;if(Object.hasOwn(se,e)){let t=se[e];a(`(`);let i=[o()];for(;r()===`,`;)n++,i.push(o());return a(`)`),i.length===1?e=>t(i[0](e)):e=>t(...i.map(t=>t(e)))}return i()};try{let e=o();return n===t.length?e:null}catch{return null}}var T={k:`id`};function le(e,t){let{keys:n,vals:r}=e,i=n.length;if(i===0)return t;if(t<=n[0])return r[0];if(t>=n[i-1])return r[i-1];let a=0,o=i-1;for(;o-a>1;){let e=a+o>>1;n[e]<=t?a=e:o=e}return e.interp?r[a]+(r[o]-r[a])*(t-n[a])/(n[o]-n[a]):t-n[a]<=n[o]-t?r[a]:r[o]}function E(e,t){let n=t.length;switch(e.k){case`lin`:{let{a:r,b:i}=e;if(r===1&&i===0)return;for(let e=0;e<n;e++)t[e]=r*t[e]+i;return}case`rat`:{let[r,i,a,o,s,c]=e.p;for(let e=0;e<n;e++){let n=t[e];t[e]=(r*n*n+i*n+a)/(o*n*n+s*n+c)}return}case`poly`:{let[r,i,a,o,s,c]=e.p;for(let e=0;e<n;e++){let n=t[e]-s-c;t[e]=(i-o*n)/(a*n-r)}return}case`alg`:{let r=e.f;for(let e=0;e<n;e++)t[e]=r(t[e]);return}case`tab`:for(let r=0;r<n;r++)t[r]=le(e,t[r]);return;case`rtv`:for(let r=0;r<n;r++){let n=t[r],i=e.def;for(let t=0;t<e.lo.length;t++)if(n>=e.lo[t]&&n<=e.hi[t]){i=e.vals[t];break}t[r]=i}return;default:return}}function ue(e,t){let n=Float64Array.of(t);return E(e,n),n[0]}var de=(e,t)=>e===null||typeof e==`string`?e:String(ue(e,t));function fe(e,t){let n=Array(t.length),r=e.ranges.every(e=>e.lo===e.hi)?new Map(e.ranges.map(e=>[e.lo,e.to])):null;for(let i=0;i<t.length;i++){let a=t[i];if(a!==a){n[i]=null;continue}let o=e.def;if(r){let e=r.get(a);e!==void 0&&(o=e)}else for(let t of e.ranges)if(a>=t.lo&&(e.int||t.lo===t.hi?a<=t.hi:a<t.hi)){o=t.to;break}n[i]=de(o,a)}return n}function pe(e,t){let n=(e,t)=>({type:e,bigEndian:t,encoding:`latin1`});switch(e){case 0:return n(`uint`,!t);case 1:return n(`int`,!t);case 2:case 3:return n(`float`,!t);case 7:return n(`string`,!1);case 8:return n(`bytes`,!1);case 9:return n(`uint`,!0);case 10:return n(`int`,!0);case 11:case 12:return n(`float`,!0);case 13:return n(`uint`,!1);case 14:return n(`int`,!1);case 15:case 16:return n(`float`,!1);default:return null}}async function me(e,t,n){let r=C(t).getUint16(24,!0)===0,i=async t=>{let n=C(await e.read(t,4)).getUint16(2,r),i=await e.read(t,n);return{id:_(i.subarray(0,2)),v:C(i),b:i,size:n}},a=(e,t)=>e.getUint32(t,r),s=(e,t)=>e.getUint16(t,r),c=(e,t)=>e.getFloat64(t,r),l=async e=>e?o((await i(e)).b.subarray(4),!0):``,u=[],d=new Set,f=e=>{if(d.has(e))throw Error(`This MDF file is damaged (its blocks link in a loop).`);d.add(e)},p=async(e,t)=>{if(!e)return{conv:T,unit:``};let{v:n,b:r}=await i(e),u=o(r.subarray(22,42),!0),d=s(n,42),f=s(n,44),p=e=>c(n,46+8*e);switch(d){case 0:return{conv:{k:`lin`,a:p(1),b:p(0)},unit:u};case 1:case 2:{let e=new Float64Array(f),t=new Float64Array(f);for(let n=0;n<f;n++)e[n]=p(2*n),t[n]=p(2*n+1);return{conv:{k:`tab`,keys:e,vals:t,interp:d===1},unit:u}}case 6:return{conv:{k:`poly`,p:[0,1,2,3,4,5].map(p)},unit:u};case 9:return{conv:{k:`rat`,p:[0,1,2,3,4,5].map(p)},unit:u};case 10:{let e=o(r.subarray(46,302),!0),t=ce(e);return{conv:t?{k:`alg`,f:t}:{k:`unsupported`,what:`the formula "${e}"`},unit:u}}case 11:return{conv:{k:`text`,ranges:Array.from({length:f},(e,t)=>{let i=46+40*t,a=c(n,i);return{lo:a,hi:a,to:o(r.subarray(i+8,i+40),!0)}}),def:null,int:t},unit:u};case 12:{let e=await Promise.all(Array.from({length:f},async(e,t)=>{let r=46+20*t;return{lo:c(n,r),hi:c(n,r+8),to:await l(a(n,r+16))}}));return{conv:{k:`text`,ranges:e.slice(1),def:e[0]?.to??null,int:t},unit:u}}case 65535:return{conv:T,unit:u};default:return{conv:{k:`unsupported`,what:`MDF3 conversion type ${d}`},unit:u}}},m=await i(64),h=null;if(m.size>=172&&(a(m.v,164)||a(m.v,168))){let e=a(m.v,168)*4294967296+a(m.v,164);h=new Date(e/1e6).toISOString()}else{let e=_(m.b.subarray(18,28)),t=_(m.b.subarray(28,36));/^\d\d:\d\d:\d{4}$/.test(e)&&(h=`${e.slice(6)}-${e.slice(3,5)}-${e.slice(0,2)}T${t}`)}let g=[],v=0;for(let e=a(m.v,4),t=0;e;t++){f(e);let n=await i(e),c=s(n.v,22),d=[];for(let e=a(n.v,8);e;){f(e);let n=await i(e),m=[],h=null;for(let e=a(n.v,8);e;){f(e);let t=await i(e),n=o(t.b.subarray(26,58),!0),c=(t.size>=222?await l(a(t.v,218)):``)||n,d=pe(s(t.v,190),r),g=s(t.v,186)+(t.size>=228?8*s(t.v,226):0);if(!d)u.push(`${c}: MDF3 data type ${s(t.v,190)} is not supported; skipped.`);else{let{conv:e,unit:n}=await p(a(t.v,8),d.type!==`float`),r={name:c,unit:n,kind:s(t.v,24)===1?`master`:`value`,...d,conv:e,sd:null,sdRecordId:null,byteOffset:g>>3,bitOffset:g&7,bitCount:s(t.v,188),invalBit:null,allInvalid:!1};r.kind===`master`&&!h?h=r:r.kind===`value`&&m.push(r)}e=a(t.v,4)}v++,d.push({name:await l(a(n.v,12))||`Group ${v}`,dg:t,recordId:s(n.v,16),recordIdSize:+(c>0),idTrailer:+(c===2),dataBytes:s(n.v,20),invalBytes:0,cycles:a(n.v,22),vlsdCg:!1,sorted:!0,master:h,channels:m,stream:[],busType:0,busEvent:!1}),e=a(n.v,4)}let m=d.reduce((e,t)=>e+t.cycles*(t.recordIdSize+t.dataBytes+t.idTrailer),0),h=[{offset:a(n.v,16),length:m,zip:null}];for(let e of d)e.stream=h,e.sorted=d.length===1,g.push(e);e=a(n.v,4)}return{version:`MDF ${n}`,startTime:h,groups:g,notes:u,meta:{}}}var he=`This MF4 is damaged (its blocks link in a loop).`;function D(e,t){if(e.seen.has(t))throw Error(he);e.seen.add(t)}async function O(e,t){let n=await e.read(t,24);if(n.length<24)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let r=C(n),i=_(n.subarray(0,4)),o=a(r,8),s=a(r,16);if(!i.startsWith(`##`)||o<24+8*s||o>1<<26)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let c=await e.read(t,o);if(c.length<o)throw Error(`This MF4 is damaged (the block at byte ${t} runs past the end of the file).`);let l=C(c),u=[];for(let e=0;e<s;e++)u.push(a(l,24+8*e));let d=c.subarray(24+8*s);return{id:i,links:u,data:C(d),bytes:d}}var ge={lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`};function _e(e){let t=e.indexOf(`<TX>`),n=t<0?-1:e.indexOf(`</TX>`,t+4);return(n>=0?e.slice(t+4,n):e.replace(/<[^<>]*>/g,``)).replace(/&(lt|gt|amp|quot|apos);/g,(e,t)=>ge[t]).trim()}function k(e,t){if(!t)return Promise.resolve(``);let n=e.texts.get(t);return n||(n=O(e.io,t).then(e=>{let t=o(e.bytes);return e.id===`##MD`?_e(t):t}),e.texts.set(t,n)),n}async function A(e,t,n=0){if(!t)return[];let r=e.io,i=await r.read(t,24),o=_(i.subarray(0,4)),s=i.length<24?0:a(C(i),8);switch(o){case`##DT`:case`##SD`:case`##RD`:return[{offset:t+24,length:s-24,zip:null}];case`##DZ`:{let e=C(await r.read(t+24,24));if(e.byteLength<24)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let n=e.getUint8(2);if(n===2||n===3)throw Error(`This MF4 uses zstd compression, which isn't supported yet.`);if(n===4||n===5)throw Error(`This MF4 uses LZ4 compression, which isn't supported yet.`);if(n>5)throw Error(`This MF4 is damaged (unknown compression type ${n}).`);let i=e.getUint32(4,!0),o=a(e,8),s=a(e,16);if(o>u(s)||n===1&&i===0)throw Error(`This MF4 is damaged (bad compressed block at byte ${t}).`);if(n===1&&o>268435456)throw Error(`This MF4 has a compressed block over 256 MB, which Kymoscope cannot read.`);return[{offset:t+48,length:s,zip:{type:n,param:i,orgLength:o}}]}case`##DL`:{if(n>1)throw Error(`This MF4 is damaged (unexpected ${o} block in its data).`);let i=[];for(let n=t;n;){D(e,n);let t=await O(r,n);for(let n of t.links.slice(1))i.push(...await A(e,n,2));n=t.links[0]}return i}case`##HL`:if(n>0)throw Error(`This MF4 is damaged (unexpected ${o} block in its data).`);return D(e,t),A(e,(await O(r,t)).links[0],1);case`##DV`:case`##DI`:throw Error(`This MF4 uses column-oriented storage (MDF 4.2 DV/DI blocks), which Kymoscope cannot read yet.`);default:throw Error(`This MF4 is damaged (unexpected ${o} block in its data).`)}}async function ve(e,t,n){return t?_(await e.io.read(t,4))===`##CC`?ye(e,t,n+1):k(e,t):null}async function ye(e,t,n=0){if(!t||n>4||e.busy.has(t))return T;let r=e.convs.get(t);if(r)return r;e.busy.add(t);try{let r=await be(e,t,n);return e.convs.set(t,r),r}finally{e.busy.delete(t)}}async function be(e,t,n){let r=await O(e.io,t),i=r.data,a=i.getUint8(0),o=i.getUint16(4,!0),s=i.getUint16(6,!0),c=new Float64Array(s);for(let e=0;e<s;e++)c[e]=i.getFloat64(24+8*e,!0);let l=r.links.slice(4,4+o),u=()=>Promise.all(l.map(t=>ve(e,t,n)));switch(a){case 0:return T;case 1:return{k:`lin`,b:c[0],a:c[1]};case 2:return{k:`rat`,p:[...c]};case 3:{let t=await k(e,l[0]),n=ce(t);return n?{k:`alg`,f:n}:{k:`unsupported`,what:`the formula "${t}"`}}case 4:case 5:{let e=s>>1,t=new Float64Array(e),n=new Float64Array(e);for(let r=0;r<e;r++)t[r]=c[2*r],n[r]=c[2*r+1];return{k:`tab`,keys:t,vals:n,interp:a===4}}case 6:{let e=Math.max(0,Math.floor((s-1)/3)),t=new Float64Array(e),n=new Float64Array(e),r=new Float64Array(e);for(let i=0;i<e;i++)t[i]=c[3*i],n[i]=c[3*i+1],r[i]=c[3*i+2];return{k:`rtv`,lo:t,hi:n,vals:r,def:c[s-1]}}case 7:{let e=await u();return{k:`text`,ranges:[...c].map((t,n)=>({lo:t,hi:t,to:e[n]??null})),def:e[s]??null,int:!0}}case 8:{let e=await u(),t=s>>1;return{k:`text`,ranges:Array.from({length:t},(t,n)=>({lo:c[2*n],hi:c[2*n+1],to:e[n]??null})),def:e[t]??null,int:!0}}default:return{k:`unsupported`,what:`conversion type ${a}`}}}var xe={0:{type:`uint`,bigEndian:!1,encoding:`latin1`},1:{type:`uint`,bigEndian:!0,encoding:`latin1`},2:{type:`int`,bigEndian:!1,encoding:`latin1`},3:{type:`int`,bigEndian:!0,encoding:`latin1`},4:{type:`float`,bigEndian:!1,encoding:`latin1`},5:{type:`float`,bigEndian:!0,encoding:`latin1`},6:{type:`string`,bigEndian:!1,encoding:`latin1`},7:{type:`string`,bigEndian:!1,encoding:`utf-8`},8:{type:`string`,bigEndian:!1,encoding:`utf-16le`},9:{type:`string`,bigEndian:!0,encoding:`utf-16be`},10:{type:`bytes`,bigEndian:!1,encoding:`latin1`}};async function Se(e,t){let{io:n,notes:r}=e,i=t.data,o=i.getUint8(0),s=i.getUint8(1),c=i.getUint8(2),l=await k(e,t.links[2]),u=xe[c];if(!u)return r.push(`${l}: data type ${c} is not supported; the channel was skipped.`),null;let d;if(o===2||o===3)if(s===1)d=o===2?`master`:`vmaster`;else{if(r.push(`The master channel ${l} is not time (sync type ${s}): samples are numbered instead.`),o===3)return null;d=`value`}else if(o===1)d=`vlsd`;else if(o===0||o===4)d=`value`;else return r.push(`${l}: channel type ${o} is not supported; skipped.`),null;let f=await ye(e,t.links[4]),p=f.k===`text`?{...f,int:u.type!==`float`}:f,m=await k(e,t.links[6]);!m&&t.links[4]&&(m=await k(e,(await O(n,t.links[4])).links[1]));let h=null,g=null;d===`vlsd`&&t.links[5]&&(_(await n.read(t.links[5],4))===`##CG`?g=a((await O(n,t.links[5])).data,0):h=await A(e,t.links[5]));let v=i.getUint32(12,!0);return{name:l,unit:m,kind:d,...u,conv:p,sd:h,sdRecordId:g,byteOffset:i.getUint32(4,!0),bitOffset:i.getUint8(3),bitCount:i.getUint32(8,!0),invalBit:v&2?i.getUint32(16,!0):null,allInvalid:(v&1)!=0}}async function Ce(e,t,n,r=0){let{io:i,notes:a}=e;for(let o=t;o;){D(e,o);let t=await O(i,o),s=t.links[1];s&&r<4&&(_(await i.read(s,4))===`##CN`?await Ce(e,s,n,r+1):a.push(`${await k(e,t.links[2])}: array channels (CA) are not supported yet; skipped.`));let c=await Se(e,t);c&&n.push(c),o=t.links[0]}}async function we(e,t,n,r){let i=t.data,o=i.getUint16(16,!0),s=0;t.links[3]&&(s=(await O(e.io,t.links[3])).data.getUint8(1));let c={name:await k(e,t.links[2]),dg:n,recordId:a(i,0),recordIdSize:r,idTrailer:0,dataBytes:i.getUint32(24,!0),invalBytes:i.getUint32(28,!0),cycles:a(i,8),vlsdCg:(o&1)!=0,sorted:!0,master:null,channels:[],stream:[],busType:s,busEvent:(o&2)!=0};if(c.vlsdCg)return c;let l=[];await Ce(e,t.links[1],l);for(let e of l)e.kind===`master`||e.kind===`vmaster`?c.master||=e:c.channels.push(e);return c}async function Te(e,t){let n=await O(e,64);if(n.id!==`##HD`)throw Error(`This MF4 is damaged (no header block).`);let r=a(n.data,0),i=(n.data.getUint8(12)&1)!=0,o=new Date(r/1e6).toISOString(),s=r>0?i?o.slice(0,-1):o:null,c={io:e,notes:[],seen:new Set,texts:new Map,convs:new Map,busy:new Set},l=[],u=0;for(let t=n.links[0],r=0;t;r++){D(c,t);let n=await O(e,t),i=n.data.getUint8(0),a=[];for(let t=n.links[1];t;){D(c,t);let n=await O(e,t),o=await we(c,n,r,i);o.vlsdCg||(u++,o.name||=`Group ${u}`),a.push(o),t=n.links[0]}let o=await A(c,n.links[2]),s=a.length===1;for(let e of a)e.stream=o,e.sorted=s,l.push(e);t=n.links[0]}return{version:`MF4 ${t}`,startTime:s,groups:l,notes:c.notes,meta:{}}}function Ee(e){let t=e&32768?-1:1,n=e>>10&31,r=e&1023;return n===0?t*2**-14*(r/1024):n===31?r?NaN:t*(1/0):t*2**(n-15)*(1+r/1024)}function j(e,t,n,r,i,a,o=0){let s=C(t),c=!e.bigEndian,l=i+e.byteOffset,u=e.bitCount;if(e.bitOffset===0)if(e.type===`float`){if(u===64){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getFloat64(l,c);return}if(u===32){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getFloat32(l,c);return}if(u===16){for(let e=0;e<n;e++,l+=r)a[o+e]=Ee(s.getUint16(l,c));return}}else if(e.type===`int`){if(u===8){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt8(l);return}if(u===16){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt16(l,c);return}if(u===32){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt32(l,c);return}if(u===64){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt32(l+(c?4:0),c)*4294967296+s.getUint32(l+(c?0:4),c);return}}else{if(u===8){for(let e=0;e<n;e++,l+=r)a[o+e]=t[l];return}if(u===16){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getUint16(l,c);return}if(u===32){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getUint32(l,c);return}if(u===64){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getUint32(l+(c?4:0),c)*4294967296+s.getUint32(l+(c?0:4),c);return}}let d=e.bitOffset+u+7>>3,f=2**e.bitOffset,p=2**u,m=p/2,h=e.type===`int`;for(let e=0;e<n;e++,l+=r){let n=0;if(c)for(let e=d-1;e>=0;e--)n=n*256+t[l+e];else for(let e=0;e<d;e++)n=n*256+t[l+e];n=Math.floor(n/f)%p,a[o+e]=h&&n>=m?n-p:n}}var De=new Map,Oe=e=>{let t=De.get(e);return t||De.set(e,t=new TextDecoder(e)),t};function ke(e){let t=e.indexOf(`\0`);return t<0?e:e.slice(0,t)}function Ae(e,t,n,r,i){let a=Oe(e.encoding),o=e.bitCount>>3,s=Array(n);for(let c=0,l=i+e.byteOffset;c<n;c++,l+=r)s[c]=ke(a.decode(t.subarray(l,l+o)));return s}function je(e,t,n,r,i,a){let o=a instanceof Float64Array?NaN:null;if(e.allInvalid){for(let e=0;e<n;e++)a[e]=o;return}if(e.invalBit===null)return;let s=1<<(e.invalBit&7);for(let c=0,l=i+(e.invalBit>>3);c<n;c++,l+=r)t[l]&s&&(a[c]=o)}var M=e=>e.recordIdSize+e.dataBytes+e.invalBytes+e.idTrailer,Me=64<<20,Ne=(e,t)=>e.reduce((e,n)=>e+(n.zip?n.zip.orgLength:Math.max(0,Math.min(n.length,t-n.offset))),0),Pe=e=>e.byteOffset+Math.ceil((e.bitOffset+e.bitCount)/8);function Fe(e,t){return e.kind===`vmaster`?!0:(e.kind===`vlsd`||e.type===`uint`||e.type===`int`||e.type===`float`?!(e.bitCount>=1&&e.bitCount<=64):!(e.bitCount>=8))?!1:Pe(e)<=t.dataBytes}function Ie(e,t){let n=e.notes;for(let r of e.groups){if(![0,1,2,4,8].includes(r.recordIdSize))throw Error(`This MDF file is damaged (bad record id size).`);if(r.vlsdCg)continue;let e=M(r);if(e>Me||e===0){r.cycles>0&&n.push(`${r.name||`A group`}: its records are ${e===0?`empty`:`too large`} (damaged); skipped.`),r.cycles=0;continue}r.cycles=Math.min(r.cycles,Math.floor(Ne(r.stream,t)/e));let i=r.channels.filter(e=>!Fe(e,r));for(let e of i)n.push(`${e.name}: its bits lie outside its record (damaged); skipped.`);i.length&&(r.channels=r.channels.filter(e=>!i.includes(e))),r.master&&!Fe(r.master,r)&&(n.push(`${r.master.name}: the time channel lies outside its record (damaged): samples are numbered instead.`),r.master=null);for(let e of r.master?[...r.channels,r.master]:r.channels)e.invalBit!==null&&e.invalBit>=8*r.invalBytes&&(e.invalBit=null)}}function Le(e,t){let n=0;for(let r of e.master?[...t,e.master]:t){if(r.invalBit!==null)return 1/0;r.kind!==`vmaster`&&(n=Math.max(n,r.byteOffset+(r.bitOffset+r.bitCount+7>>3)))}return e.recordIdSize+n}var Re=65536,ze=`This file's compressed data is damaged.`;async function*Be(e){for(let t=0;t<e.length;t+=Re)yield e.subarray(t,t+Re)}async function*Ve(e){if(typeof DecompressionStream!=`function`){let t=[],n=new b(e=>{t.push(e)});for await(let r of e)for(n.push(r,!1);t.length;)yield t.shift();for(n.push(new Uint8Array,!0);t.length;)yield t.shift();return}let t=new DecompressionStream(`deflate`),n=t.writable.getWriter();(async()=>{for await(let t of e)await n.write(t);await n.close()})().catch(e=>n.abort(e).catch(()=>{}));let r=t.readable.getReader();try{for(;;){let{done:e,value:t}=await r.read().catch(e=>{throw e instanceof TypeError?Error(ze):e});if(e)return;yield t}}finally{r.cancel().catch(()=>{})}}async function N(e,t=-1,n=1/0){let r=[],i=Math.min(t,n),a=t>=0?new Uint8Array(i):null,o=0;for await(let s of Ve(Be(e))){if(a){if(o+s.length>t&&n>t)throw Error(`Compressed data is longer than its header says.`);a.set(o+s.length>i?s.subarray(0,i-o):s,o)}else r.push(s);if(o+=s.length,o>=n)break}if(a)return o>=i?a:a.subarray(0,o);let s=r.length===1?r[0]:new Uint8Array(o);return r.length>1&&r.reduce((e,t)=>(s.set(t,e),e+t.length),0),o>n?s.subarray(0,n):s}var He=new Uint8Array(Uint32Array.of(1).buffer)[0]===1;function Ue(e,t,n,r=t){let i=Math.floor(n/t),a=new Uint8Array(r<t?i*r:n),o=r%4==0&&He?new Uint32Array(a.buffer,0,i*r>>2):null,s=r>>2;for(let t=0;t<i;t+=512){let n=Math.min(i,t+512);if(o)for(let a=0;a<r;a+=4){let r=a*i,c=r+i,l=c+i,u=l+i;for(let i=t,d=t*s+(a>>2);i<n;i++,d+=s)o[d]=e[r+i]|e[c+i]<<8|e[l+i]<<16|e[u+i]<<24}else for(let o=0;o<r;o++){let s=o*i;for(let i=t,c=t*r+o;i<n;i++,c+=r)a[c]=e[s+i]}}let c=i*t;return r===t&&a.set(e.subarray(c,n),c),a}function We(e,t,n){if(!(n<t)||e.length===0)return t;let r=Math.min(t,n+3&-4);return r===t?t:e.every(e=>e.zip?.type===1&&e.zip.param===t&&e.zip.orgLength%t===0)?r:t}async function P(e,t,n=1/0,r=1/0){let i=await e.slice(t.offset,t.length),{type:a,param:o,orgLength:s}=t.zip;if(a===0)return N(i,s,r);let c=Math.min(n,o);return Ue(await N(i,s,c<o?s/o*c:1/0),o,s,c)}async function*F(e,t,n,r=1/0){let i=e=>!!e?.zip&&!(e.zip.type===0&&(e.length>16777216||e.zip.orgLength>268435456)),a=null;for(let o=0;o<t.length;o++){let s=t[o];if(n?.throwIfAborted(),!s.zip)for await(let t of e.windows(s.offset,s.length))yield t.bytes;else if(i(s)){let n=a??P(e,s,r);a=i(t[o+1])?P(e,t[o+1],r):null,a?.catch(()=>{}),yield await n}else{let t=s.zip.orgLength;for await(let n of Ve((async function*(){for await(let t of e.windows(s.offset,s.length))yield t.bytes})()))if(yield n.length>t?n.subarray(0,t):n,(t-=n.length)<=0)break}}}async function*Ge(e,t,n,r){if(r<=0||t<=0)return;let i=Math.min(n,r),a=null,o=0,s=0;for await(let n of e){let e=0;for(;e<n.length&&s<r;){if(o===0){let a=Math.min(i,r-s,Math.floor((n.length-e)/t));if(a>0){yield{buf:n.subarray(e,e+a*t),n:a},s+=a,e+=a*t;continue}}a??=new Uint8Array(t*i);let c=Math.min(a.length,(r-s)*t),l=Math.min(n.length-e,c-o);if(a.set(n.subarray(e,e+l),o),o+=l,e+=l,o===c){let e=o/t;yield{buf:a,n:e},s+=e,o=0}}if(s>=r)return}a&&o>=t&&(yield{buf:a,n:Math.floor(o/t)})}async function Ke(e,t,n,r){let i=n*r,a=0;for(let n of t){let t=n.zip?n.zip.orgLength:n.length;if(i<a)return null;if(i+r<=a+t)return n.zip?null:e.read(n.offset+i-a,r);a+=t}return null}var qe=(e,t)=>(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0,Je=class{#e;#t;#n;#r;#i=new Uint8Array;#a=0;#o;#s=0;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n,this.#r=F(e,t,n),this.#o=t.reduce((e,t)=>e+(t.zip?t.zip.orgLength:t.length),0)}peek(e){let t=e-this.#a;if(t<0||t+4>this.#i.length)return null;let n=qe(this.#i,t);return t+4+n>this.#i.length?null:this.#i.subarray(t+4,t+4+n)}async get(e){for(;;){let t=this.peek(e);if(t)return t;let n=e-this.#a;if(e+4>this.#o||n>=0&&n+4<=this.#i.length&&e+4+qe(this.#i,n)>this.#o)throw Error(`This MF4 is damaged (string data ends early).`);e<this.#a&&(this.#r=F(this.#e,this.#t,this.#n),this.#i=new Uint8Array,this.#a=0);let r=await this.#r.next();if(r.done)throw Error(`This MF4 is damaged (string data ends early).`);if((this.#s+=r.value.length)>4*this.#o+16777216)throw Error(`This MF4 is damaged (its string offsets jump back and forth).`);let i=Math.max(0,Math.min(e-this.#a,this.#i.length)),a=this.#i.subarray(i),o=new Uint8Array(a.length+r.value.length);o.set(a),o.set(r.value,a.length),this.#a+=i,this.#i=o}}},Ye=e=>Math.max(1,Math.min(65536,Math.floor((8<<20)/Math.max(1,e)))),Xe=64<<20,Ze=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t){this.#e=e,this.#t=t}want(e){this.#r.has(e)||this.#r.set(e,new Map)}wanted(e){return this.#r.has(e)}put(e,t,n){this.#r.get(e).set(t,n)}async bytes(e,t){let n=Array(t.length);if(e.sdRecordId!==null){let r=this.#r.get(e.sdRecordId);for(let e=0;e<t.length;e++)n[e]=r?.get(t[e])??null,r?.delete(t[e]);return n}if(!e.sd)return n.fill(null);let r=this.#n.get(e);r||this.#n.set(e,r=new Je(this.#e,e.sd,this.#t));for(let e=0;e<t.length;e++)n[e]=r.peek(t[e])??await r.get(t[e]);return n}async strings(e,t){let n=Oe(e.encoding);return(await this.bytes(e,t)).map(e=>e?ke(n.decode(e)):null)}};function Qe(e,t,n,r,i=M(e),a=new Float64Array(n)){let o=e.master;if(!o)return null;if(o.kind===`vmaster`)for(let e=0;e<n;e++)a[e]=r+e;else j(o,t,n,i,e.recordIdSize,a);return E(o.conv,a),a}function $e(e,t,n){return n===1?e[t]:n===2?e[t]|e[t+1]<<8:n===4?(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0:((e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0)+4294967296*((e[t+4]|e[t+5]<<8|e[t+6]<<16|e[t+7]<<24)>>>0)}function et(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async function*tt(e,t,n,r,i,a=1/0){let o=t.groups[n[0]];if(o.sorted){let t=We(o.stream,M(o),a),r=0;for await(let{buf:a,n:s}of Ge(F(e,o.stream,i,t),t,Ye(t),o.cycles))yield{g:n[0],buf:a,n:s,start:r,size:t},r+=s;return}let s=t.groups.map((e,t)=>({g:e,k:t})).filter(({g:e})=>e.dg===o.dg),c=o.recordIdSize,l=new Map;for(let e of n){let n=t.groups[e],r=M(n);l.set(n.recordId,{k:e,size:r,buf:new Uint8Array(r*Math.min(Ye(r),Math.max(1,n.cycles))),fill:0,start:0})}let u=new Map(s.map(({g:e})=>[e.recordId,e.vlsdCg?-1:M(e)])),d=new Map,f=new Uint8Array;for await(let t of F(e,o.stream,i)){let e=f.length?et(f,t):t,n=0;for(;!(n+c>e.length);){let t=$e(e,n,c),i=u.get(t);if(i===void 0)throw Error(`This MF4 is damaged (unknown record id ${t}).`);if(i<0){if(n+c+4>e.length)break;let i=(e[n+c]|e[n+c+1]<<8|e[n+c+2]<<16|e[n+c+3]<<24)>>>0;if(i>Xe)throw Error(`This MF4 is damaged (a string record of ${i} bytes).`);let a=n+c+4+i;if(a>e.length)break;let o=d.get(t)??0;r.wanted(t)&&r.put(t,o,e.slice(n+c+4,a)),d.set(t,o+4+i),n=a;continue}if(n+i>e.length)break;let a=l.get(t);if(a&&(a.buf.set(e.subarray(n,n+i),a.fill),a.fill+=i,a.fill===a.buf.length)){let e=a.fill/a.size;yield{g:a.k,buf:a.buf,n:e,start:a.start,size:a.size},a.start+=e,a.fill=0}n+=i}f=e.slice(n)}for(let e of l.values())e.fill&&(yield{g:e.k,buf:e.buf,n:e.fill/e.size,start:e.start,size:e.size})}var I=(e,t)=>t?e+2147483648:e,nt=/^BO_\s+(\d+)\s+(\w+)\s*:\s*(\d+)/,rt=/^SG_\s+(\w+)\s*(?:(M|m\d+M?)\s*)?:\s*(\d+)\|(\d+)@([01])([+-])\s*\(([^,)]*),([^)]*)\)\s*\[[^\]]*\]\s*"([^"]*)"/,it=/^VAL_\s+(\d+)\s+(\w+)\s+(.*);/,at=/^SIG_VALTYPE_\s+(\d+)\s+(\w+)\s*:\s*([12])\s*;/,ot=/^-?\d+(?:\.\d+)?$/;function st(e){let t=e.split(`"`),n=new Map;for(let e=0;e+1<t.length;e+=2){let r=t[e].trim();ot.test(r)&&n.set(Number(r),t[e+1])}return n}var ct=(e,t)=>e<=511&&t>=1&&t<=64;function lt(e){let t=new Map,n=new Map,r=new Map,i=(e,t)=>{let i=n.get(Number(e));return i?r.get(i)?.get(t):void 0},a=null;for(let o of e.split(/\r?\n/)){let e=o.trim(),s;if(s=nt.exec(e)){let e=Number(s[1]),r=e>=2147483648,i=r?e-2147483648:e;a={id:i,extended:r,name:s[2],size:Number(s[3]),signals:[]},t.set(I(i,r),a),n.set(e,a)}else if((s=rt.exec(e))&&a){let e=s[2],t=Number(s[3]),n=Number(s[4]);if(!ct(t,n)||!s[7].trim()||!s[8].trim())continue;let i={name:s[1],start:t,length:n,littleEndian:s[5]===`1`,signed:s[6]===`-`,factor:Number(s[7]),offset:Number(s[8]),unit:s[9],mux:e?e===`M`?`switch`:parseInt(e.slice(1),10):null,float:0,values:null};a.signals.push(i);let o=r.get(a);o||r.set(a,o=new Map),o.has(i.name)||o.set(i.name,i)}else if(s=it.exec(e)){let e=i(s[1],s[2]);e&&(e.values=st(s[3]))}else if(s=at.exec(e)){let e=i(s[1],s[2]);e&&(e.float=s[3]===`1`?32:64)}else (e.startsWith(`BO_`)||e===``)&&e===``&&(a=null)}return t}function ut(e){if(e.float){let t=e.float/8,n=e.start>>3,r=e.littleEndian,i=new DataView(new ArrayBuffer(8));return(e,a)=>{for(let r=0;r<t;r++)i.setUint8(r,e[a+n+r]??0);return t===4?i.getFloat32(0,r):i.getFloat64(0,r)}}let t=e.length,n=2**t,r=n/2,i=e.signed;if(e.littleEndian){let a=e.start>>3,o=e.start&7;if(o+t<=32){let e=t===32?-1:(1<<t)-1;return(t,s)=>{let c=s+a,l=((t[c]|t[c+1]<<8|t[c+2]<<16|t[c+3]<<24)>>>o&e)>>>0;return i&&l>=r?l-n:l}}let s=o+t+7>>3,c=2**(t-(32-o)),l=2**(32-o);return(e,t)=>{let u=t+a,d=(e[u]|e[u+1]<<8|e[u+2]<<16|e[u+3]<<24)>>>o,f=0;for(let t=s-1;t>=4;t--)f=f*256+(e[u+t]??0);let p=d+f%c*l;return i&&p>=r?p-n:p}}let a=e.start>>3,o=e.start&7;if(7-o+t<=32){let e=32-(7-o)-t,s=t===32?-1:(1<<t)-1;return(t,o)=>{let c=o+a,l=((t[c]<<24|t[c+1]<<16|t[c+2]<<8|t[c+3])>>>e&s)>>>0;return i&&l>=r?l-n:l}}let s=(1<<o+1)-1,c=t-(o+1)>>3,l=t-(o+1)&7,u=2**l;return(e,t)=>{let o=(e[t+a]??0)&s,d=t+a+1;for(let t=0;t<c;t++)o=o*256+(e[d++]??0);return l>0&&(o=o*u+((e[d]??0)>>8-l)),i&&o>=r?o-n:o}}function dt(e){let t=e.length,n=2**t,r=n/2,i=e.signed,a=t===32?-1:(1<<t)-1;if(!e.float&&e.littleEndian&&(e.start&7)+t<=32){let t=e.start>>3,o=e.start&7;return(e,s,c,l,u,d,f)=>{for(let p=0;p<l;p++){let l=s[c[p]]+t,m=((e[l]|e[l+1]<<8|e[l+2]<<16|e[l+3]<<24)>>>o&a)>>>0;u[p]=(i&&m>=r?m-n:m)*d+f}}}if(!e.float&&!e.littleEndian&&7-(e.start&7)+t<=32){let o=e.start>>3,s=32-(7-(e.start&7))-t;return(e,t,c,l,u,d,f)=>{for(let p=0;p<l;p++){let l=t[c[p]]+o,m=((e[l]<<24|e[l+1]<<16|e[l+2]<<8|e[l+3])>>>s&a)>>>0;u[p]=(i&&m>=r?m-n:m)*d+f}}}let o=ut(e);return(e,t,n,r,i,a,s)=>{for(let c=0;c<r;c++)i[c]=o(e,t[n[c]])*a+s}}function ft(e){if(!e.busEvent||e.busType!==2)return null;let t=t=>e.channels.find(e=>e.name.endsWith(t))??null,n=t(`DataFrame.ID`),r=t(`DataFrame.DataBytes`);return!n||!r?null:{id:n,ide:t(`DataFrame.IDE`),data:r}}var pt=()=>({n:0,time:new Float64Array,key:new Float64Array,id:new Float64Array,ide:new Float64Array,bytes:null,buf:new Uint8Array,dataAt:new Int32Array});async function mt(e,t,n,r,i,a,o,s){s.key.length<r&&Object.assign(s,{time:new Float64Array(r),key:new Float64Array(r),id:new Float64Array(r),ide:new Float64Array(r),dataAt:new Int32Array(r)});let c=e.recordIdSize,{id:l,ide:u,key:d,dataAt:f}=s;j(t.id,n,r,a,c,l),t.ide&&j(t.ide,n,r,a,c,u);for(let e=0;e<r;e++){let n=l[e],r=n&536870911;d[e]=I(r,t.ide?u[e]!==0:n>=2147483648||r>2047)}if(s.bytes=null,t.data.kind===`vlsd`){let e=new Float64Array(r);j({...t.data,type:`uint`},n,r,a,c,e),s.bytes=await o.bytes(t.data,e)}else for(let e=0,n=c+t.data.byteOffset;e<r;e++,n+=a)f[e]=n;if(!Qe(e,n,r,i,a,s.time.subarray(0,r)))for(let e=0;e<r;e++)s.time[e]=i+e;return s.n=r,s.buf=n,s}var ht=new Uint8Array;function gt(e){return e.float?(e.start>>3)+e.float/8:e.littleEndian?(e.start>>3)+((e.start&7)+e.length+7>>3):(e.start>>3)+1+(Math.max(0,e.length-((e.start&7)+1))+7>>3)}function _t(e,t,n){let r=0;for(let e of n.values())for(let t of e.signals)r=Math.max(r,gt(t));let i=t.data.kind===`vlsd`?t.data:{...t.data,bitCount:Math.min(t.data.bitCount,r*8)};return Le(e,t.ide?[t.id,t.ide,i]:[t.id,i])}function vt(e,t){let n=t.map(t=>e.signals[e.channels[t].s]);return{route:e,col:n.map(dt),read:n.map(ut),factor:n.map(e=>e.factor),offset:n.map(e=>e.offset),table:t.map((t,r)=>e.channels[t].text?n[r].values:null),idx:new Int32Array,cnt:0,n:0,t0:NaN,t1:NaN}}function yt(e,t,n,r,i,a=1,o=0){let s=new Float64Array(i);if(n.bytes)for(let e=0;e<i;e++)s[e]=t(n.bytes[r[e]]??ht,0)*a+o;else e(n.buf,n.dataAt,r,i,s,a,o);return s}function bt(e,t){let{idx:n,cnt:r}=e,i=new Float64Array(r);for(let e=0;e<r;e++)i[e]=t.time[n[e]];return e.n===0&&(e.t0=i[0]),e.t1=i[r-1],e.n+=r,e.cnt=0,{time:i,cols:e.col.map((i,a)=>{let o=e.table[a];return o?Array.from(yt(i,e.read[a],t,n,r),e=>o.get(e)??null):yt(i,e.read[a],t,n,r,e.factor[a],e.offset[a])})}}var xt=e=>({key:e,skip:!0,frames:0,all:null,sw:null,byMux:new Map,idx:new Int32Array,cnt:0});function St(e,t){let n=e.signals.find(e=>e.mux===`switch`);return{key:I(e.id,e.extended),skip:!1,frames:0,all:t,sw:n?{col:dt(n),read:ut(n)}:null,byMux:new Map,idx:new Int32Array,cnt:0}}var Ct=class{#e=Array(2048);#t=new Map;#n;constructor(e){this.#n=e}get(e){let t=e<2048?this.#e[e]:this.#t.get(e);return t||(t=this.#n(e),e<2048?this.#e[e]=t:this.#t.set(e,t)),t}};function wt(e,t,n){let r=[];for(let n=0;n<e.n;n++){let i=t.get(e.key[n]);if(i.skip){i.frames++;continue}i.cnt===0&&(r.push(i),i.idx.length<e.n&&(i.idx=new Int32Array(e.n))),i.idx[i.cnt++]=n}let i=[];for(let t of r){if(t.all&&(t.all.idx=t.idx,t.all.cnt=t.cnt,i.push(t.all)),t.sw){let r=yt(t.sw.col,t.sw.read,e,t.idx,t.cnt);for(let e=0;e<t.cnt;e++){let a=t.byMux.get(r[e]);a===void 0&&((a=n(t,r[e]))||t.byMux.size<4096)&&t.byMux.set(r[e],a),a&&(a.cnt===0&&(i.push(a),a.idx.length<t.cnt&&(a.idx=new Int32Array(t.cnt))),a.idx[a.cnt++]=t.idx[e])}}t.cnt=0}return i}var Tt=48e6;async function Et(e,t,n,r){let i=new Map;if(t.groups.forEach((e,t)=>{let n=ft(e);n&&e.cycles>0&&i.set(t,n)}),i.size===0)return null;if(n.length===0)return{dbc:new Map,layouts:i,routes:[],notes:[],cache:new Map};let a=lt(c(new Uint8Array(await n[0].arrayBuffer()))),o=[],s=new Map,l=new Map,u=0,d=new Ze(e,r);for(let[n,c]of i){let i=t.groups[n],f=(e,t)=>{let n=e.signals.filter(e=>t===null?typeof e.mux!=`number`:e.mux===t),r=[];return n.forEach((e,t)=>{r.push({s:t,text:!1}),e.values&&r.push({s:t,text:!0})}),vt({key:I(e.id,e.extended),mux:t,signals:n,channels:r},r.map((e,t)=>t))},p=new Ct(e=>{let t=a.get(e);if(!t){let t=xt(e);return s.set(e,t),t}let r=St(t,f(t,null));return o.push({model:n,m:r}),r});c.data.sdRecordId!==null&&d.want(c.data.sdRecordId);let m=pt();for await(let o of tt(e,t,[n],d,r,_t(i,c,a))){let e=await mt(i,c,o.buf,o.n,o.start,o.size,d,m),t=(e,t)=>{let n=a.get(e.key);return n.signals.some(e=>e.mux===t)?f(n,t):null};for(let n of wt(e,p,t)){let t=bt(n,e);if(u<0)continue;if((u+=t.time.length*(1+t.cols.length))>Tt){u=-1,l.clear();continue}let r=l.get(n);r||l.set(n,r=[]),r.push(t)}}}let f=[],p=new Map;for(let{model:e,m:t}of o)for(let n of[t.all,...t.byMux.values()]){if(!n)continue;let{route:t,n:r,t0:i,t1:o}=n;if(t.signals.length===0)continue;let s=a.get(t.key);u>=0&&p.set(t,l.get(n)??[]),f.push({model:e,route:t,group:{name:t.mux===null?s.name:`${s.name} [m=${t.mux}]`,channels:t.channels.map(e=>({name:e.text?`${t.signals[e.s].name} (text)`:t.signals[e.s].name,unit:e.text?``:t.signals[e.s].unit,text:e.text})),samples:r,time:{kind:`timestamps`},rateHz:r>1&&o>i?Math.round((r-1)/(o-i)*1e6)/1e6:null}})}let m=[];if(s.size){let e=[...s.values()].reduce((e,t)=>e+t.frames,0),t=[...s.keys()].map(e=>`0x${(e%2147483648).toString(16).toUpperCase()}`).join(`, `);m.push(`${e} frame${e===1?``:`s`} with ${s.size} id${s.size===1?``:`s`} not in the DBC ${e===1?`was`:`were`} skipped (${t}).`)}return{dbc:a,layouts:i,routes:f,notes:m,cache:p}}async function*Dt(e,t,n,r,i,a){let o=[];for(let e of i){let t=r.cache.get(e.route);if(!t){o.push(e);continue}r.cache.delete(e.route);let n=0;for(let r of t)yield{group:e.group,start:n,length:r.time.length,time:r.time,columns:e.sel.map(e=>r.cols[e])},n+=r.time.length}if(!o.length)return;let s=r.layouts.get(n),c=t.groups[n],l=new Map,u=new Map;for(let e of o){let t=vt(e.route,e.sel);l.set(t,e.group);let n=u.get(e.route.key);n||u.set(e.route.key,n={all:null,byMux:new Map}),e.route.mux===null?n.all=t:n.byMux.set(e.route.mux,t)}let d=new Ct(e=>{let t=u.get(e);if(!t)return xt(e);let n=St(r.dbc.get(e),t.all);return t.byMux.size||(n.sw=null),n}),f=new Ze(e,a);s.data.sdRecordId!==null&&f.want(s.data.sdRecordId);let p=pt();for await(let i of tt(e,t,[n],f,a,_t(c,s,r.dbc))){let e=await mt(c,s,i.buf,i.n,i.start,i.size,f,p);for(let t of wt(e,d,(e,t)=>u.get(e.key).byMux.get(t)??null)){let n=t.n,r=bt(t,e);yield{group:l.get(t),start:n,length:r.time.length,time:r.time,columns:r.cols}}}}var Ot=e=>Math.round(e*1e6)/1e6,kt=e=>e.kind===`value`?e.type!==`bytes`:e.kind===`vlsd`&&e.type===`string`,At=e=>({name:e.name,unit:e.unit,text:e.type===`string`||e.kind===`vlsd`||e.conv.k===`text`});async function jt(e,t){let n=t.master;if(!n||t.cycles<2)return null;if(n.kind===`vmaster`)return n.conv.k===`lin`&&n.conv.a>0?Ot(1/n.conv.a):null;if(!t.sorted)return null;let r=M(t),i=t.cycles,a,o;if(t.stream[0]?.zip){let n=We(t.stream.slice(0,1),r,Le(t,[])),s=await P(e,t.stream[0],n,4096*r);if(i=Math.min(t.cycles,Math.floor(s.length/n)),i<2)return null;a=s.subarray(0,n),o=s.subarray((i-1)*n,i*n)}else a=await Ke(e,t.stream,0,r),o=await Ke(e,t.stream,t.cycles-1,r);if(!a||!o)return null;let s=new Float64Array(2);return j(n,a,1,r,t.recordIdSize,s,0),j(n,o,1,r,t.recordIdSize,s,1),E(n.conv,s),s[1]>s[0]?Ot((i-1)/(s[1]-s[0])):null}async function Mt(e,t,n,r,i,a,o){let s;if(e.kind===`vlsd`){let a=new Float64Array(n);j({...e,type:`uint`},t,n,r,i,a),s=await o.strings(e,a)}else if(e.type===`string`)s=Ae(e,t,n,r,i);else{let a=new Float64Array(n);j(e,t,n,r,i,a),e.conv.k===`text`?s=fe(e.conv,a):(E(e.conv,a),s=a)}return je(e,t,n,r,a,s),s}async function Nt(e,t,n,r,i,a,o,s){let c=e.recordIdSize,l=[];for(let i of t)l.push(await Mt(e.channels[i],n,r,a,c,c+e.dataBytes,s));return{group:o,time:Qe(e,n,r,i,a),start:i,length:r,columns:l}}async function*Pt(e,t){let n=e.plan.state,r=t.filter(e=>n.groups[e].route),i=t.filter(e=>!n.groups[e].route);if(r.length){let t=r.map(t=>({group:t,route:n.groups[t].route,sel:w(e,t)}));yield*Dt(e.io,n.model,n.groups[r[0]].model,n.bus,t,e.signal)}if(!i.length)return;let a=new Ze(e.io,e.signal),o=new Map;for(let t of i){let r=n.groups[t],i=w(e,t).map(e=>r.channels[e]);for(let e of i){let t=n.model.groups[r.model].channels[e].sdRecordId;t!==null&&a.want(t)}o.set(r.model,{pg:t,cols:i})}let[s,{cols:c}]=o.entries().next().value,l=n.model.groups[s],u=o.size===1?Le(l,c.map(e=>l.channels[e])):1/0;for await(let t of tt(e.io,n.model,[...o.keys()],a,e.signal,u)){let{pg:e,cols:r}=o.get(t.g);yield await Nt(n.model.groups[t.g],r,t.buf,t.n,t.start,t.size,e,a)}}function Ft(e){let t=e.plan.state,n=new Map;for(let r of e.selection){let e=t.model.groups[t.groups[r.group].model].dg;n.set(e,[...n.get(e)??[],r.group])}return[...n].sort((e,t)=>e[0]-t[0]).map(([,e])=>e)}var It={...e,async plan(e,t){let n=await t.read(0,64);if(v(n,`UnFinMF`))throw Error(`This MF4 was not finalized by its logger (it starts with UnFinMF). Finalize it with the logger software or asammdf, then open it again.`);let r=_(n.subarray(8,16)).replace(/\0/g,``).trim(),i=Number(r.replace(`.`,``).slice(0,3))>=400?await Te(t,r):await me(t,n,r);Ie(i,t.size);let a=await Et(t,i,e.companions.filter(e=>e.name.toLowerCase().endsWith(`.dbc`))),o=new Set(a?.layouts.keys()??[]),s=[],c=[],l=[...i.notes],u=0;for(let e=0;e<i.groups.length;e++){let n=i.groups[e];if(n.vlsdCg||n.cycles===0||o.has(e))continue;let r=[];if(n.channels.forEach((e,t)=>{kt(e)?r.push(t):u++}),r.length!==0){for(let e of r){let t=n.channels[e].conv;t.k===`unsupported`&&l.push(`${n.channels[e].name}: ${t.what} is not supported; raw values are shown.`)}c.push({model:e,channels:r}),s.push({name:n.name,channels:r.map(e=>At(n.channels[e])),samples:n.cycles,time:n.master?{kind:`timestamps`}:{kind:`index`},rateHz:await jt(t,n)})}}if(u&&l.push(`${u} byte-array channel${u===1?` was`:`s were`} skipped.`),a){if(a.routes.length===0&&a.dbc.size===0){if(s.length===0)throw Error(`This MF4 has raw CAN frames. Drop its .dbc file together with it to decode signals.`);l.push(`This MF4 also has raw CAN frames. Drop its .dbc file together with it to decode signals.`)}for(let e of a.routes)c.push({model:e.model,route:e.route}),s.push(e.group);l.push(...a.notes)}if(s.length===0)throw Error(`This MDF file has no channels with samples.`);let d={model:i,groups:c,bus:a};return{format:i.version,startTime:i.startTime,groups:s,meta:i.meta,events:[],notes:l,interleaved:!!a?.routes.length||i.groups.some(e=>!e.sorted&&!e.vlsdCg),state:d}},async*stream(e){for(let t of Ft(e))yield*Pt(e,t)},streamGroup(e,t){return Pt(e,[t])}};function Lt(e){let t=[];for(let n of c(e).split(`\0`)){if(!n)continue;let e=n.split(``),r=parseFloat(e[0].split(``)[0]);Number.isFinite(r)&&t.push({onset:r,texts:e.slice(1).filter(e=>e.length>0)})}return t}function Rt(e,t){let n=/^(\d\d)\.(\d\d)\.(\d\d)$/.exec(e),r=/^(\d\d)\.(\d\d)\.(\d\d)$/.exec(t);if(!n||!r)return null;let i=Number(n[3]);return`${i>=85?1900+i:2e3+i}-${n[2]}-${n[1]}T${r[1]}:${r[2]}:${r[3]}`}var zt=e=>`${+e.toFixed(6)} Hz`;function Bt(e,t,n,r,i,a,o,s){let{bit:c,off:l}=e;if(a===2)for(let e=0;e<i;e++)o[s+e]=c*(l+t.getInt16(r+2*e,!0));else for(let e=0,t=r;e<i;e++,t+=3)o[s+e]=c*(l+((n[t]|n[t+1]<<8|n[t+2]<<16)<<8>>8))}var Vt={...ae,async plan(e,t){let n=await t.read(0,256),r=(e,t)=>_(n.subarray(e,e+t)).trim(),i=n[0]===255,a=parseInt(r(252,4),10),o=parseInt(r(184,8),10),s=r(192,44),c=/^(EDF|BDF)\+/.test(s),l=/^(EDF|BDF)\+D/.test(s),u=parseFloat(r(244,8));if(!(a>0)||o!==256*(a+1)||!(u>0))throw Error(`This EDF/BDF header is damaged.`);let d=await t.read(256,a*256),f=(e,t,n)=>_(d.subarray(e*a+t*n,e*a+t*(n+1))).trim(),p=i?3:2,m=[],h=0;for(let e=0;e<a;e++){let t=parseFloat(f(104,8,e)),n=parseFloat(f(112,8,e)),r=parseFloat(f(120,8,e)),i=parseFloat(f(128,8,e)),a=Number(f(216,8,e));if(!(Number.isInteger(a)&&a>=0))throw Error(`This EDF/BDF header is damaged (samples per record).`);let o=(n-t)/(i-r);m.push({label:f(0,16,e),unit:f(96,8,e),spr:a,offset:h,bit:o,off:n/o-i}),h+=a*p}let g=h;if(!(g>0&&o+g<=t.size))throw Error(`This EDF/BDF file is damaged (its data records do not fit in it).`);let v=Math.floor((t.size-o)/g),y=parseInt(r(236,8),10),b=[];y>=0?y>v&&(b.push(`The file is shorter than its header says: ${v} of ${y} data records were read.`),y=v):y=v;let x=c?m.flatMap((e,t)=>/^(EDF|BDF) Annotations$/.test(e.label)?[t]:[]):[],S=new Map;m.forEach((e,t)=>{!x.includes(t)&&e.spr>0&&S.set(e.spr,[...S.get(e.spr)??[],t])});let ee=[...S.values()],C=ee.map(e=>{let t=m[e[0]].spr/u;return{name:zt(t),channels:e.map(e=>({name:m[e].label,unit:m[e].unit})),samples:y*m[e[0]].spr,rateHz:t,time:l?{kind:`timestamps`}:{kind:`rate`,rate:t,start:0}}}),te={headerBytes:o,records:y,duration:u,recordBytes:g,bps:p,signals:m,groups:ee,annotations:x,discontinuous:l};return{format:`${i?`BDF`:`EDF`}${c?l?`+D`:`+`:``}`,startTime:Rt(r(168,8),r(176,8)),groups:C,meta:{patient:r(8,80),recording:r(88,80)},events:[],notes:l?[`Discontinuous recording: each gap shows as a break in the traces.`,...b]:b,state:te}},async*stream(e){let t=e.plan.state,r=Math.max(1,Math.floor(n/t.recordBytes)),i=e.selection.map(e=>({g:e.group,chans:e.channels.map(n=>t.signals[t.groups[e.group][n]]),spr:t.signals[t.groups[e.group][0]].spr})),a=i.map(()=>0),o=0,s=NaN;for await(let n of e.io.windows(t.headerBytes,t.records*t.recordBytes,r*t.recordBytes)){e.signal?.throwIfAborted();let r=Math.floor(n.bytes.length/t.recordBytes);if(r===0)break;let c=C(n.bytes),l=new Float64Array(r),u=[];for(let e=0;e<r;e++)l[e]=(o+e)*t.duration,t.annotations.forEach((r,i)=>{let a=t.signals[r],o=e*t.recordBytes+a.offset,s=Lt(n.bytes.subarray(o,o+a.spr*t.bps));i===0&&s.length&&(l[e]=s[0].onset);for(let e of s)for(let t of e.texts)u.push({time:e.onset,text:t})});let d=new Uint8Array(r),f=0;if(t.discontinuous)for(let e=0;e<r;e++){let n=e?l[e-1]+t.duration:s;n===n&&l[e]>n+1e-9&&(d[e]=1,f++)}for(let e=0;e<i.length;e++){let o=i[e],p=o.spr/t.duration,m=r*o.spr+f,h=t.discontinuous?new Float64Array(m):null,g=o.chans.map(()=>new Float64Array(m)),_=0;for(let e=0;e<r;e++){if(d[e]){h[_]=e?l[e-1]+t.duration:s;for(let e of g)e[_]=NaN;_++}if(h)for(let t=0;t<o.spr;t++)h[_+t]=l[e]+t/p;let r=e*t.recordBytes;o.chans.forEach((e,i)=>Bt(e,c,n.bytes,r+e.offset,o.spr,t.bps,g[i],_)),_+=o.spr}let v={group:o.g,time:h,start:a[e],length:m,columns:g};e===0&&u.length&&(v.events=u),a[e]+=m,yield v}s=l[r-1]+t.duration,o+=r}}},L={float32:4,double64:8,int8:1,int16:2,int32:4,int64:8};function R(e,t,n=0){let r=e.indexOf(`<${t}>`,n);if(r<0)return``;let i=e.indexOf(`</${t}>`,r);return i<0?``:e.slice(r+t.length+2,i).trim()}function Ht(e,t){let n=[];for(let r=e.indexOf(`<${t}>`);r>=0;){let i=e.indexOf(`</${t}>`,r);if(i<0)break;n.push(e.slice(r,i+t.length+3)),r=e.indexOf(`<${t}>`,i)}return n}var Ut=1e5,Wt=e=>e.fmt===`string`||L[e.fmt]!==void 0;function z(e,t,n){let r=e[n];if((r===1||r===4||r===8)&&n+1+r<=e.length)return r===1?[e[n+1],2]:r===4?[t.getUint32(n+1,!0),5]:[a(t,n+1),9];throw Error(`This XDF file is damaged (bad length field).`)}function Gt(e,t,n,r){if(n>=e.length)return-1;if(e[n++]===8&&(n+=8),r.fmt!==`string`)return n+L[r.fmt]*r.nch<=e.length?n+L[r.fmt]*r.nch:-1;for(let i=0;i<r.nch;i++){if(n>=e.length)return-1;let[r,i]=z(e,t,n);n+=i+r}return n<=e.length?n:-1}async function*Kt(e,t){let n=new Uint8Array;for await(let r of e.windows(4,e.size-4)){t?.throwIfAborted();let i=r.bytes,a=r.offset-n.length;if(n.length){let e=new Uint8Array(n.length+i.length);e.set(n),e.set(i,n.length),i=e}let o=C(i),s=0;for(;!(s+1>i.length);){let t=i[s];if(s+1+t>i.length)break;let[n,r]=z(i,o,s),c=s+r+n;if(a+c>e.size)return;if(c>i.length)break;yield{tag:i[s+r]|i[s+r+1]<<8,body:i.subarray(s+r+2,c)},s=c}n=i.slice(s)}}function qt(e,t,n){let r=t-e.i0,i=n-e.t0;e.n++,e.si+=r,e.st+=i,e.sii+=r*r,e.sit+=r*i}function Jt(e){let t=e.n*e.sii-e.si*e.si;e.b=t>0?(e.n*e.sit-e.si*e.st)/t:0,e.a=(e.st-e.b*e.si)/Math.max(1,e.n)}function Yt(e){if(e.length===0)return[0,0];if(e.length===1)return[e[0][1],0];let t={i0:e[0][0],t0:0,n:0,si:0,st:0,sii:0,sit:0,a:0,b:0};for(let[n,r]of e)qt(t,n,r);return Jt(t),[t.a-t.b*t.i0,t.b]}function Xt(e,t,n){let r=t.t0+t.a+t.b*(n-t.i0);return r+e.c0+e.c1*r}var Zt={...m,async plan(e,t){let n=new Map,r=``;for await(let e of Kt(t)){let t=C(e.body);if(e.tag===1)r=c(e.body);else if(e.tag===2){let r=t.getUint32(0,!0),i=c(e.body.subarray(4)),a=parseInt(R(i,`channel_count`),10)||1;if(!(a>=1&&a<=Ut))throw Error(`This XDF file is damaged (a stream with ${a} channels).`);let o=Ht(i,`channel`);n.set(r,{id:r,name:R(i,`name`)||`Stream ${r}`,nch:a,srate:parseFloat(R(i,`nominal_srate`))||0,fmt:R(i,`channel_format`)||`float32`,labels:Array.from({length:a},(e,t)=>R(o[t]??``,`label`)||`Ch${t+1}`),units:Array.from({length:a},(e,t)=>R(o[t]??``,`unit`)),count:0,segs:[],clock:[],c0:0,c1:0,lastTs:NaN})}else if(e.tag===3){let r=n.get(t.getUint32(0,!0));if(!r||!Wt(r))continue;let[i,a]=z(e.body,t,4),o=4+a,s=L[r.fmt],c=r.srate>0?Math.max(1,500/r.srate):1/0;for(let n=0;n<i&&!(Gt(e.body,t,o,r)<0);n++){let n;if(e.body[o++]===8?(n=t.getFloat64(o,!0),o+=8):n=r.lastTs+(r.srate>0?1/r.srate:0),r.fmt===`string`)for(let n=0;n<r.nch;n++){let[n,r]=z(e.body,t,o);o+=r+n}else o+=s*r.nch;if(r.srate>0){let e=r.segs[r.segs.length-1];(!e||n-r.lastTs>c)&&r.segs.push(e={i0:r.count,t0:n,n:0,si:0,st:0,sii:0,sit:0,a:0,b:0}),qt(e,r.count,n)}else r.count===0&&r.segs.push({i0:0,t0:n,n:1,si:0,st:0,sii:0,sit:0,a:0,b:0});r.lastTs=n,r.count++}}else if(e.tag===4){let e=n.get(t.getUint32(0,!0));e&&e.clock.push([t.getFloat64(4,!0),t.getFloat64(12,!0)])}}let i=[],a=[...n.values()].sort((e,t)=>e.id-t.id).filter(e=>(Wt(e)||i.push(`${e.name}: channel format ${e.fmt} is not supported; skipped.`),Wt(e))),o=1/0;for(let e of a){[e.c0,e.c1]=Yt(e.clock);for(let t of e.segs)Jt(t);if(e.count===0)continue;let t=e.srate>0?Xt(e,e.segs[0],0):e.segs[0].t0+e.c0+e.c1*e.segs[0].t0;o=Math.min(o,t)}let s=f(a.map(e=>e.name),[]),l=a.map((e,t)=>({name:s[t],channels:e.labels.map((t,n)=>({name:t,unit:e.units[n],...e.fmt===`string`?{text:!0,sparse:!0}:{}})),samples:e.count,time:{kind:`timestamps`},rateHz:e.srate>0?e.srate:null,irregular:e.srate===0})),u=R(r,`version`);return{format:`XDF ${u||`1.0`}`,startTime:null,groups:l,meta:{header:u},events:[],notes:i,state:{streams:a,origin:Number.isFinite(o)?o:0}}},async*stream(e){let t=e.plan.state,n=8192,r=new Map,i=e=>e.sel.map(()=>e.s.fmt===`string`?Array(n):new Float64Array(n));for(let a of e.selection){let o=t.streams[a.group],s={g:a.group,s:o,sel:w(e,a.group),time:new Float64Array(n),cols:[],n:0,start:0,seg:0,i:0,raw:NaN};s.cols=i(s),r.set(o.id,s)}let a=e=>{let t={group:e.g,time:e.time.slice(0,e.n),start:e.start,length:e.n,columns:e.cols.map(t=>t.slice(0,e.n))};return e.start+=e.n,e.n=0,e.time=new Float64Array(n),e.cols=i(e),t};for await(let i of Kt(e.io,e.signal)){if(i.tag!==3)continue;let e=C(i.body),o=r.get(e.getUint32(0,!0));if(!o)continue;let s=o.s,[l,u]=z(i.body,e,4),d=4+u,f=L[s.fmt],p=[];for(let r=0;r<l&&!(Gt(i.body,e,d,s)<0);r++){let r;i.body[d++]===8?(r=e.getFloat64(d,!0),d+=8):r=o.raw+(s.srate>0?1/s.srate:0),o.raw=r;let l;if(s.srate>0){for(;o.seg+1<s.segs.length&&s.segs[o.seg+1].i0<=o.i;)o.seg++;l=Xt(s,s.segs[o.seg],o.i)}else l=r+s.c0+s.c1*r;if(o.time[o.n]=l-t.origin,s.fmt===`string`){let n=[];for(let t=0;t<s.nch;t++){let[t,r]=z(i.body,e,d);n.push(c(i.body.subarray(d+r,d+r+t))),d+=r+t}o.sel.forEach((e,t)=>{o.cols[t][o.n]=n[e]}),p.push({time:l-t.origin,text:n.join(` `)})}else o.sel.forEach((t,n)=>{let r=d+t*f,i=o.cols[n];switch(s.fmt){case`float32`:i[o.n]=e.getFloat32(r,!0);break;case`double64`:i[o.n]=e.getFloat64(r,!0);break;case`int8`:i[o.n]=e.getInt8(r);break;case`int16`:i[o.n]=e.getInt16(r,!0);break;case`int32`:i[o.n]=e.getInt32(r,!0);break;default:i[o.n]=e.getInt32(r+4,!0)*4294967296+e.getUint32(r,!0)}}),d+=f*s.nch;o.i++,++o.n===n&&(yield a(o))}p.length&&(yield{group:o.g,time:new Float64Array,start:o.start,length:0,columns:o.sel.map(()=>new Float64Array),events:p})}for(let e of r.values())e.n&&(yield a(e))}},Qt=2,$t=8,en=4,tn=32,nn=64,rn=4713,an=4714,B=32,V=68,H={1:1,2:2,3:4,4:8,5:1,6:2,7:4,8:8,9:4,10:8,25:4,26:8,33:1,68:16},on={0:5,1:1,2:6,3:2,4:7,5:3,6:8,7:4,8:9,9:10,4294967295:V},sn=65536,cn=65536,ln=(e,t,n)=>n?g(e,t+8,n)+a(e,t,n)/2**64:g(e,t,n)+a(e,t+8,n)/2**64;function un(e,t,n,r,i){switch(r){case B:{let r=e.getUint32(n,i);return[c(t.subarray(n+4,n+4+r)),4+r]}case 1:return[e.getInt8(n),1];case 2:return[e.getInt16(n,i),2];case 3:return[e.getInt32(n,i),4];case 4:return[g(e,n,i),8];case 5:return[e.getUint8(n),1];case 6:return[e.getUint16(n,i),2];case 7:return[e.getUint32(n,i),4];case 8:return[a(e,n,i),8];case 9:case 25:return[e.getFloat32(n,i),4];case 10:case 26:return[e.getFloat64(n,i),8];case 33:return[e.getUint8(n)!==0,1];case V:return[ln(e,n,i),16];default:throw Error(`This TDMS file has a property of type ${r}, which Kymoscope cannot read.`)}}function dn(e){let t=/^\/'((?:[^']|'')*)'(?:\/'((?:[^']|'')*)')?$/.exec(e);return t?[t[1].replace(/''/g,`'`),(t[2]??``).replace(/''/g,`'`)]:null}var fn=4294967295;function pn(e){if(e.has(`NI_Number_Of_Scales`))return Number(e.get(`NI_Number_Of_Scales`));let t=0;for(let n of e.keys()){let e=/^NI_Scale\[(\d+)\]_Scale_Type$/.exec(n);e&&(t=Math.max(t,Number(e[1])+1))}return t}function mn(e,t,n){let r=e.find(e=>pn(e)>0);if(!r||r.get(`NI_Scaling_Status`)===`scaled`)return null;let i=(e,a)=>{if(e===fn||e<0||a>8)return e=>e;let o=r.get(`NI_Scale[${e}]_Scale_Type`);if(o===void 0)return e=>e;if(o===`Linear`){let t=Number(r.get(`NI_Scale[${e}]_Linear_Slope`)),n=Number(r.get(`NI_Scale[${e}]_Linear_Y_Intercept`)??0),o=i(Number(r.get(`NI_Scale[${e}]_Linear_Input_Source`)??fn),a+1);return o&&(e=>t*o(e)+n)}if(o===`Polynomial`){let o=Number(r.get(`NI_Scale[${e}]_Polynomial_Coefficients_Size`)??4);if(!(Number.isInteger(o)&&o>=0&&o<=64))return t.push(`${n}: an NI polynomial scale with ${o} coefficients is not supported; raw values are shown.`),null;let s=Array.from({length:o},(t,n)=>Number(r.get(`NI_Scale[${e}]_Polynomial_Coefficients[${n}]`))),c=i(Number(r.get(`NI_Scale[${e}]_Polynomial_Input_Source`)??fn),a+1);return c&&(e=>{let t=c(e),n=0;for(let e=o-1;e>=0;e--)n=n*t+s[e];return n})}return t.push(`${n}: NI scale type ${String(o)} is not supported; raw values are shown.`),null};return i(pn(r)-1,0)}var hn={1:Int8Array,2:Int16Array,3:Int32Array,5:Uint8Array,6:Uint16Array,7:Uint32Array,9:Float32Array,10:Float64Array,25:Float32Array,26:Float64Array,33:Uint8Array};function gn(e,t,n,r,i,o,s,c){let l=hn[e];if(l&&o&&r===H[e]&&(t.byteOffset+n)%r===0){s.set(new l(t.buffer,t.byteOffset+n,i),c);return}switch(e){case 1:for(let e=0;e<i;e++,n+=r)s[c+e]=t.getInt8(n);return;case 2:for(let e=0;e<i;e++,n+=r)s[c+e]=t.getInt16(n,o);return;case 3:for(let e=0;e<i;e++,n+=r)s[c+e]=t.getInt32(n,o);return;case 4:for(let e=0;e<i;e++,n+=r)s[c+e]=g(t,n,o);return;case 5:case 33:for(let e=0;e<i;e++,n+=r)s[c+e]=t.getUint8(n);return;case 6:for(let e=0;e<i;e++,n+=r)s[c+e]=t.getUint16(n,o);return;case 7:for(let e=0;e<i;e++,n+=r)s[c+e]=t.getUint32(n,o);return;case 8:for(let e=0;e<i;e++,n+=r)s[c+e]=a(t,n,o);return;case 9:case 25:for(let e=0;e<i;e++,n+=r)s[c+e]=t.getFloat32(n,o);return;case 10:case 26:for(let e=0;e<i;e++,n+=r)s[c+e]=t.getFloat64(n,o);return;case V:for(let e=0;e<i;e++,n+=r)s[c+e]=ln(t,n,o);return;default:s.fill(NaN,c,c+i)}}async function _n(e,t,n){let r=new Map,i=[],o=[],s=new Map,l=new Map,u=t??e,d=0,f=0;for(;d+28<=e.size&&f+28<=u.size;){let p=t?f:d,m=await u.read(p,28),h=C(m);if(!(m[0]===84&&m[1]===68&&m[2]===83&&(m[3]===109||m[3]===104)))throw Error(`This TDMS file is damaged (no segment lead-in where one should be).`);let g=h.getUint32(4,!0),_=!(g&nn),v=a(h,12,_),y=a(h,20,_),b=v>=2**53?e.size:Math.min(e.size,d+28+v);if(y>b-d-28)throw Error(`This TDMS file is damaged (segment metadata longer than its segment).`);if(g&Qt){let e=await u.read(p+28,y),t=C(e);g&en&&(o=[],s=new Map);let i=0,d=t.getUint32(i,_);i+=4;for(let u=0;u<d;u++){let u=t.getUint32(i,_),d=c(e.subarray(i+4,i+4+u));i+=4+u;let f=dn(d),p=r.get(d);p||r.set(d,p={path:d,group:f?.[0]??``,name:f?.[1]??``,type:0,props:new Map,pieces:[],total:0});let m=t.getUint32(i,_);i+=4;let h=null;if(m===4294967295)h=null;else if(m===0)h=l.get(p)??null;else if(m===rn||m===an){let e=a(t,i+8,_),r=t.getUint32(i+16,_),o=m===rn?20:17,s=i+20,c=on[t.getUint32(s,_)]??0,l=t.getUint32(s+8,_);i=s+r*o;let u=t.getUint32(i,_);i+=4;let d=0;for(let e=0;e<u;e++)d+=t.getUint32(i+4*e,_);i+=4*u,m===an?n.push(`${p.name}: DAQmx digital line data is not supported; skipped.`):(r>1&&n.push(`${p.name}: only the first of its ${r} DAQmx scalers is read.`),h={type:c,count:e,bytes:0,daqmx:{byteOffset:l,stride:d}})}else{let e=t.getUint32(i,_),n=a(t,i+8,_),r=e===B?a(t,i+16,_):n*(H[e]??0);i+=m-4,h={type:e,count:n,bytes:r,daqmx:null}}h&&(p.type=h.type,l.set(p,h));let g=t.getUint32(i,_);i+=4;for(let n=0;n<g;n++){let n=t.getUint32(i,_),r=c(e.subarray(i+4,i+4+n));i+=4+n;let a=t.getUint32(i,_);i+=4;let[o,s]=un(t,e,i,a,_);p.props.set(r,o),i+=s}let v=s.get(p);v===void 0?s.set(p,o.push({obj:p,idx:h})-1):o[v].idx=h}}if(g&$t){let e=d+28+y,t=o.filter(e=>e.idx&&e.idx.count>0),n=t.filter(e=>e.idx.daqmx),r=(g&tn)!==0,a=0,s=0;n.length?(s=n[0].idx.daqmx.stride,a=n[0].idx.count*s):r?(s=t.reduce((e,t)=>e+(H[t.idx.type]??0),0),a=(t[0]?.idx.count??0)*s):a=t.reduce((e,t)=>e+t.idx.bytes,0);let c=a>0?Math.floor((b-e)/a):0,l=i.push({rawStart:e,chunkSize:a,chunks:c,le:_})-1,u=0;for(let e of t){let t=e.idx,n=H[t.type]??0,i=t.daqmx?{seg:l,count:t.count,offset:t.daqmx.byteOffset,bytes:0,stride:s,type:t.type}:{seg:l,count:t.count,offset:u,bytes:t.bytes,stride:r?s:n,type:t.type};t.daqmx||(u+=r?n:t.bytes),i.type===B?i.count=Math.min(i.count,Math.floor(i.bytes/4)):n>0&&(i.count=Math.min(i.count,i.stride>0?Math.max(0,Math.floor((a-i.offset-n)/i.stride)+1):0)),e.obj.pieces.push(i),c&&(e.obj.total+=i.count*c)}}if(d=b,f+=28+y,b>=e.size)break}return{objs:[...r.values()],segments:i}}var vn={...l,async plan(e,t){let n=e.companions.find(e=>e.name.toLowerCase().endsWith(`.tdms_index`)),i=[],{objs:a,segments:o}=await _n(t,n?new r(n):null,i),s=a.find(e=>e.path===`/`)?.props,c=a.filter(e=>e.name&&e.total>0&&(e.type===B||H[e.type])),l=new Set(c);for(let e of a)e.name&&e.total>0&&!l.has(e)&&i.push(`${e.name}: TDMS data type ${e.type} is not supported; skipped.`);let u=c.map(e=>e.props.get(`wf_start_time`)).filter(e=>typeof e==`number`),d=u.reduce((e,t)=>Math.min(e,t),u.length?1/0:0),f=new Map;for(let e of c){let t=`${e.total}|${e.props.get(`wf_increment`)??``}`,n=f.get(e.group)??new Map,r=n.get(t);r?r.push(e):n.set(t,[e]),f.set(e.group,n)}let p=[],m=[];for(let[e,t]of f)for(let n of t.values()){let r=n[0].props.get(`wf_increment`),i=typeof r==`number`&&r>0?1/r:null,a=i?null:n.find(e=>e.type===V)??n.find(e=>e.type!==B&&/^(time|timestamp|t)$/i.test(e.name))??null,o=n.filter(e=>e!==a),s=n[0].props.get(`wf_start_time`),c=i?Number(n[0].props.get(`wf_start_offset`)??0)+(typeof s==`number`?s-d:0):0;p.push({name:t.size===1?e:`${e} (${i?+i.toFixed(6):n[0].total} ${i?`Hz`:`samples`})`,channels:o.map(e=>({name:e.name,unit:String(e.props.get(`unit_string`)??``),text:e.type===B})),samples:n[0].total,time:i?{kind:`rate`,rate:i,start:c}:a?{kind:`timestamps`}:{kind:`index`},rateHz:i}),m.push({channels:o,time:a,origin:0})}if(p.length===0)throw Error(`This TDMS file has no channels with data.`);let h=[];for(let e of m){if(!e.time)continue;let n=e.time.pieces[0],r=o[n.seg],i=await t.read(r.rawStart+n.offset,H[n.type]??8),a=new Float64Array(1);gn(n.type,C(i),0,0,1,r.le,a,0),h.push(a[0])}let g=h.reduce((e,t)=>Math.min(e,t),h.length?1/0:0);for(let e of m)e.origin=g;let _=new Date(Date.UTC(1904,0,1)+d*1e3),v=d&&Number.isFinite(_.getTime())?_.toISOString():null,y={objs:a,segments:o,groups:m},b={};for(let[e,t]of s??[])typeof t==`string`&&(b[e]=t);return{format:`TDMS`,startTime:v,groups:p,meta:b,events:[],notes:i,state:y}},async*stream(e){for(let t of e.selection)yield*bn(e,t.group)},streamGroup:(e,t)=>bn(e,t)};function yn(e,t,n,r,i,a){let o=0;for(;o<i&&r.pi<t.pieces.length;){let s=t.pieces[r.pi],c=e.segments[s.seg];if(r.chunk>=c.chunks){r.pi++,r.chunk=0,r.row=0;continue}let l=Math.min(i-o,s.count-r.row),u=c.rawStart+r.chunk*c.chunkSize+s.offset;if(s.type===B)a.push({ch:n,at:u,end:u+s.bytes,rows:l,first:r.row,out:o,piece:s,le:c.le,range:0});else{let e=u+r.row*s.stride;a.push({ch:n,at:e,end:e+(l-1)*s.stride+H[s.type],rows:l,first:r.row,out:o,piece:s,le:c.le,range:0})}o+=l,r.row+=l,r.row>=s.count&&(r.chunk++,r.row=0)}}async function*bn(e,t){let n=e.plan.state,r=n.groups[t],i=w(e,t).map(e=>r.channels[e]),a=r.time?[r.time,...i]:i;if(!a.length)return;let o=new Map(n.objs.map(e=>[e.path,e.props])),s=e=>o.get(e)??new Map,l=s(`/`),u=a.map(e=>mn([e.props,s(`/'${e.group.replace(/'/g,`''`)}'`),l],[],e.name)),d=a.map(()=>({pi:0,chunk:0,row:0})),f=a.reduce((e,t)=>Math.min(e,t.total),1/0);for(let i=0;i<f;){e.signal?.throwIfAborted();let o=Math.min(sn,f-i),s=[];a.forEach((e,t)=>yn(n,e,t,d[t],o,s));let l=s.slice().sort((e,t)=>e.at-t.at),p=[];for(let e of l){let t=p[p.length-1];t&&e.at<=t.end+cn&&Math.max(t.end,e.end)-t.at<=16777216?t.end=Math.max(t.end,e.end):p.push({at:e.at,end:e.end}),e.range=p.length-1}let m=[];for(let t of p)m.push(await e.io.slice(t.at,t.end-t.at));let h=m.map(C),g=a.map(e=>e.type===B?Array(o).fill(null):new Float64Array(o).fill(NaN));for(let e of s){let t=e.at-p[e.range].at,n=e.piece;if(n.type===B){let r=m[e.range],i=h[e.range],a=t+4*n.count,o=g[e.ch];for(let n=0;n<e.rows;n++){let s=e.first+n,l=s===0?0:i.getUint32(t+4*(s-1),e.le),u=i.getUint32(t+4*s,e.le);o[e.out+n]=c(r.subarray(a+l,a+u))}}else gn(n.type,h[e.range],t,n.stride,e.rows,e.le,g[e.ch],e.out)}for(let e=0;e<a.length;e++){let t=u[e],n=g[e];if(t&&n instanceof Float64Array)for(let e=0;e<o;e++)n[e]=t(n[e])}let _=null;if(r.time){_=g.shift();for(let e=0;e<o;e++)_[e]-=r.origin}yield{group:t,time:_,start:i,length:o,columns:g},i+=o}}var xn=e=>!!e&&typeof e.keys==`function`,Sn=1e5;function Cn(){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<=Sn,note:()=>t>1e5?`This file has more than ${Sn.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 wn(e,t,n,r){return t.reduce((e,t)=>e*t,1)*Math.max(1,e.metadata.size||1)>(r?n*1032+1024:n)}var Tn=e=>!!e&&typeof e.slice==`function`,En=null,U=null,W=new WeakMap;function Dn(){!En||U||(U=En(),U.catch(()=>{U=null}))}function G(e){if(!En)return Promise.reject(Error(`HDF5 and MAT 7.3 files are read in the import worker, and this environment has no workers.`));Dn();let t=W.get(e);return t||(t=U.then(t=>t(e)).then(e=>({root:e.root,close:()=>{}})),W.set(e,t),t.catch(()=>W.delete(e))),t}var On=new WeakMap;function K(e,t,n){let r=On.get(e);r||On.set(e,r=new Map);let i=r.get(t);return i||r.set(t,i=n??e.get(t)),i}function q(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)}var kn={s:1,sec:1,second:1,seconds:1,ms:.001,msec:.001,us:1e-6,µs:1e-6,ns:1e-9};function J(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 An(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}var jn=0,Mn=1,Nn=3,Pn=6,Fn=new Set([1,2,3,4,5,6]),In=/^(time|t|timestamps?|.*[_ ]time|time[_ ].*)$/i,Ln=[`sampling_rate`,`sample_rate`,`samplerate`,`sampleRate`,`fs`,`Fs`,`rate`];function Rn(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(xn(l))o<16&&a.enter(l)&&Rn(e,l,c,r,i,a,o+1);else if(Tn(l)){let t=K(e,c,l);r.push({path:c,parent:n,name:s,ds:t,attrs:t.attrs})}}}var Y=e=>e===`/`?`root`:e.slice(1),zn=e=>Math.max(4096,Math.min(1<<20,Math.floor((8<<20)/(8*Math.max(1,e)))));async function Bn(e,t){let n=K(e,t.path);if(t.col===null)return q(n.slice([[0,1]]))[0]*t.factor;let r=n.slice([[0,1]]);return Number(r[0][t.col])*t.factor}var Vn={...i,async plan(e){let t=await G(e.main);try{let n=[],r=new Map,i=Cn();i.enter(t.root),Rn(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=>!Fn.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(wn(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===jn||r===Mn||r===Nn)){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===jn||r===Mn)){let e=An(t.attrs,...Ln);c.push({name:Y(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===Pn){let e=(t.ds.metadata.compound_type?.members??[]).flatMap((e,n)=>e.type===jn||e.type===Mn?[{path:t.path,col:n,text:!1,factor:1,name:e.name}]:[]),r=e.find(e=>In.test(e.name));c.push({name:Y(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=>J(e.attrs,`CLASS`)===`DIMENSION_SCALE`)??e.leaves.find(e=>In.test(e.name)&&e.ds.metadata.type!==Nn),i=n?kn[J(n.attrs,`units`,`unit`,`Units`)]??1:1,a=n?null:An(r.get(e.parent)??{},...Ln);c.push({name:t?`${Y(e.parent)} (${e.n} rows)`:Y(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===Nn,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 Bn(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=>J(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*Hn(e,t.group)},streamGroup:(e,t)=>Hn(e,t)};async function*Hn(e,t){let n=e.plan.state.groups[t],r=w(e,t).map(e=>n.cols[e]),i=await G(e.files.main);try{let a=n.chunk??0,o=a>0?Math.max(1,Math.min(Math.floor((1<<20)/a),Math.ceil(zn(r.length+1)/a)))*a:zn(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=K(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=q(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()}}var Un=/^(time|t|tout|timestamps?)$/i,Wn=/^(fs|sample_?rate|sampling_?rate|rate|samplerate)$/i,Gn=e=>e.slice(e.lastIndexOf(`.`)+1),Kn=e=>e.includes(`.`)?e.slice(0,e.lastIndexOf(`.`)):``;function qn(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 Jn(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])=>Wn.test(Gn(e))),a=i.length===1?i[0][1]:null,o=[];for(let[e,n]of r){let r=n.find(e=>Un.test(Gn(e.name))||/(_time|\.Time)$/.test(e.name))??null;o.push({name:r?Kn(r.name)||r.name:`${e} samples`,channels:n.filter(e=>e!==r).map(e=>qn(e,t)),time:r,rate:r?null:a,origin:0})}return o}function Yn(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 Xn(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 Zn=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(){}},Qn=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 N(await this.#e.slice(this.#t,this.#n),this.size,this.size),this.#r.subarray(e,e+t)}release(){this.keep||(this.#r=null)}},X={1:1,2:1,3:2,4:2,5:4,6:4,7:4,9:8,12:8,13:8};function $n(e,t,n,r,i=1){let a=C(t),o=r.length,s=X[e]*i;if(e===9&&i===1&&n){r.set(t.byteOffset%8==0?new Float64Array(t.buffer,t.byteOffset,o):new Float64Array(t.slice(0,o*8).buffer));return}switch(e){case 1:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt8(t);return;case 2:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint8(t);return;case 3:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt16(t,n);return;case 4:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint16(t,n);return;case 5:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt32(t,n);return;case 6:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint32(t,n);return;case 7:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getFloat32(t,n);return;case 9:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getFloat64(t,n);return;case 12:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt32(t+(n?4:0),n)*4294967296+a.getUint32(t+(n?0:4),n);return;case 13:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint32(t+(n?4:0),n)*4294967296+a.getUint32(t+(n?0:4),n);return;default:r.fill(NaN)}}async function Z(e,t,n){let r=C(await e.read(t,8)),i=r.getUint32(0,n);if(i>>>16)return{type:i&65535,bytes:i>>>16,data:t+4,next:t+8};let a=r.getUint32(4,n);return{type:i,bytes:a,data:t+8,next:i===15?t+8+a:t+8+a+(8-a%8)%8}}function er(e,t,n,r,i){let[a,o]=t,s=X[r.type];if(!s)return[];let c=(e,t)=>async(a,o)=>{let c=new Float64Array(o-a);return t===1?$n(r.type,await n.read(r.data+(e+a)*s,(o-a)*s),i,c):$n(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 Q(e,t,n,r,i,a,s){let l=t,u=await Z(e,l,n),d=C(await e.read(u.data,8)).getUint32(0,n),f=d&255;l=u.next;let p=await Z(e,l,n);if(p.bytes>128){a.notes.push(`A MAT variable with more than 32 dimensions was skipped (damaged).`);return}let m=C(await e.read(p.data,p.bytes)),h=Array.from({length:p.bytes/4},(e,t)=>m.getInt32(4*t,n));l=p.next;let g=await Z(e,l,n),v=_(await e.read(g.data,g.bytes));l=g.next;let y=i??v,b=r?`${r}.${y}`:y,x=h.reduce((e,t)=>e*t,1);if(f>=6&&f<=15){if(x===0)return;let t=await Z(e,l,n);if(d&2048&&a.notes.push(`${b}: the imaginary part was skipped.`),h.length>2){a.notes.push(`${b}: arrays with more than two dimensions are skipped.`);return}if(!X[t.type])return;if(!(x>0)||x*X[t.type]>t.bytes||t.data+t.bytes>e.size){a.notes.push(`${b}: its data is shorter than its dimensions (damaged); skipped.`);return}if(x===1){let r=new Float64Array(1);$n(t.type,await e.read(t.data,X[t.type]??8),n,r),a.scalars.set(b,r[0]);return}a.channels.push(...er(b,h,e,t,n));return}if(f===4){let t=await Z(e,l,n);if(t.bytes>tr)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)):c(r);h[0]<=1&&a.strings.set(b,i);return}if(f===2){let t=await Z(e,l,n),r=C(await e.read(t.data,4)).getInt32(0,n);l=t.next;let i=await Z(e,l,n);if(!(r>0))return;let c=await e.read(i.data,i.bytes),u=Array.from({length:Math.floor(c.length/r)},(e,t)=>o(c.subarray(t*r,(t+1)*r)));if(l=i.next,u.length===0||x*u.length*8>e.size-l){x>0&&u.length>0&&a.notes.push(`${b}: its fields are longer than the file (damaged); skipped.`);return}for(let t=0;t<x;t++){let r=x>1?`${b}(${t+1})`:b;for(let t of u){let i=await Z(e,l,n);i.type===14&&i.bytes>0&&s<16&&await Q(e,i.data,n,r,t,a,s+1),l=i.next}}return}f===1?a.notes.push(`${b}: cell arrays are skipped.`):f===5?a.notes.push(`${b}: sparse arrays are skipped.`):a.notes.includes(nr)||a.notes.push(nr)}var tr=1<<17,nr=`MATLAB objects (timeseries, SimulationOutput) were skipped: save them as 'Structure with time' or as structs.`,rr=512<<20;async function ir(e){let t=_((await e.read(0,128)).subarray(126,128))===`IM`,n={channels:[],strings:new Map,scalars:new Map,notes:[],sources:[]},r=new Zn(e),i=0;for(let a=128;a+8<=e.size;){let o=await Z(r,a,t);if(o.type===15){if(o.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 r=await e.slice(o.data,o.bytes),a=await N(r,-1,8),s=a.length<8?0:8+C(a).getUint32(4,t);if(s>u(o.bytes))throw Error(`A compressed variable in this MAT file is damaged.`);if(s>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 c=await N(r,s,s),l=new Qn(e,o.data,o.bytes,c);n.sources.push(l),i+=c.length;let d=await Z(l,0,t);if(d.type===14&&await Q(l,d.data,t,``,null,n,0),i>rr)for(let e of n.sources)e.keep=!1,e.release()}else o.type===14&&await Q(r,o.data,t,``,null,n,0);a=o.next}return n}var ar=65536,or=new Set([`double`,`single`,`int8`,`uint8`,`int16`,`uint16`,`int32`,`uint32`,`int64`,`uint64`,`logical`]);function sr(e,t){let n={channels:[],strings:new Map,scalars:new Map,notes:[]},r=Cn();r.enter(e);let i=t=>K(e,t),a=(e,t,n)=>{let r=null;return(a,o)=>((r?.s!==a||r.e!==o)&&(r={s:a,e:o,v:q(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=J(m,`MATLAB_class`);if(m.MATLAB_empty)continue;if(xn(d)){h===`struct`&&l<16&&r.enter(d)&&o(d,f,p,l+1);continue}if(!Tn(d))continue;let g=d.shape??[];if(h===`char`){if(g.reduce((e,t)=>e*t,1)>ar)continue;let e=q(d.slice(g.map(e=>[0,e])));n.strings.set(p,new TextDecoder(`utf-16le`).decode(Uint16Array.from(e)))}else if(or.has(h)&&g.length===2&&wn(d,g,t,!!d.metadata.chunks))n.notes.push(`${p}: larger than the file can hold (never written, or damaged); skipped.`);else if(or.has(h)&&g.length===2){let[e,t]=g;if(e*t===1){n.scalars.set(p,q(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)=>q(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}var cr=e=>Math.max(4096,Math.min(1<<18,Math.floor((16<<20)/(8*Math.max(1,e))))),lr={...s,async plan(e,t){let n=v(await t.read(0,20),`MATLAB 7.3`),r,i=[];if(n)r=sr((await G(e.main)).root,e.main.size);else{let e=await ir(t);i=e.sources,r=e}let a=Jn(r.channels,r.strings,r.scalars).filter(e=>e.channels.length>0);await Xn(a);let o=Yn(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*ur(e,t.group)},streamGroup:(e,t)=>ur(e,t)};async function*ur(e,t){let n=e.plan.state,r=n.groups[t],i=w(e,t).map(e=>r.channels[e]),a=r.channels[0].length,o=cr(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()}}function dr(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 fr(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]=dr(t[c++],i),[g,_,v]=dr(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}}var pr={BINARY:2,BINARY32:4,FLOAT32:4},mr=16<<20;async function hr(e){let t=_(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(`
|
|
3
|
-
`,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 gr(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]}var _r=e=>e.companions.find(e=>e.name.toLowerCase().endsWith(`.dat`)),vr={...p,async plan(e,t){let n=e.main.name.toLowerCase().endsWith(`.cff`),r,i;if(n){let e=await hr(t);r=e.cfg,i={data:`self`,offset:e.offset,length:e.length}}else{let n=_r(e);if(!n)throw Error(`This COMTRADE .cfg needs its .dat file: drop both together.`);if(t.size>mr)throw Error(`This .cfg is too large to be a COMTRADE configuration file.`);r=_(await t.read(0,t.size)),i={data:`companion`,offset:0,length:n.size}}let a=fr(r);if(a.ft!==`ASCII`&&!pr[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*pr[a.ft]+2*o,c=s?Math.floor(i.length/s):i.length,l=Math.min(a.rates[a.rates.length-1][1]||(s?c:-1),c),u=a.rates.length===1&&a.rates[0][0]>0?a.rates[0][0]:null,d=[`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:l,time:{kind:`timestamps`},rateHz:u}],events:a.start&&a.trigger?[{time:Math.round((a.triggerSec-a.startSec)*1e6)/1e6,text:`Trigger`}]:[],notes:d,state:{...i,cfg:a,samples:l,recordSize:s}}},stream:e=>yr(e)};async function*yr(e){let t=e.plan.state,{cfg:i}=t,a=t.data===`self`?e.io:new r(_r(e.files)),o=w(e,0),s=i.analog.length,c=i.rates[0][0]>0,l=i.timemult*i.timebase,u=65536,d=0,f=(e,t,n)=>{let r=new Float64Array(e);if(c)gr(i.rates,d,e,r);else for(let n=0;n<e;n++)r[n]=t[n]*l;let a={group:0,time:r,start:d,length:e,columns:n};return d+=e,a};if(i.ft===`ASCII`){let n=i.rev>=1999?`99999`:``,r=o.map(e=>e<s?i.analog[e]:null),c=new Float64Array(u),l=o.map(()=>new Float64Array(u)),d=0,p=(e,t,i)=>{let a=e.slice(t,i).split(`,`);if(!(a.length<2)){c[d]=Number(a[1]);for(let e=0;e<o.length;e++){let t=(a[2+o[e]]??``).trim(),i=r[e];l[e][d]=t===``||i&&t===n?NaN:i?i.a*Number(t)+i.b:Number(t)}d++}},m=``,h=new TextDecoder(`latin1`);for await(let n of a.windows(t.offset,t.length)){e.signal?.throwIfAborted();let t=m+h.decode(n.bytes),r=0;for(let e=t.indexOf(`
|
|
4
|
-
`,r);e>=0;e=t.indexOf(`
|
|
5
|
-
`,r))p(t,r,e),r=e+1,d===u&&(yield f(d,c,l),c=new Float64Array(u),l=o.map(()=>new Float64Array(u)),d=0);m=t.slice(r)}m.trim()&&p(m,0,m.length),d&&(yield f(d,c.slice(0,d),l.map(e=>e.slice(0,d))));return}let p=t.recordSize,m=pr[i.ft],h=Math.max(1,Math.floor(Math.min(n,u*p)/p)),g=t.samples;for await(let n of a.windows(t.offset,Math.min(t.length,t.samples*p),h*p)){e.signal?.throwIfAborted();let t=Math.min(g,Math.floor(n.bytes.length/p));if(t<=0)break;let r=C(n.bytes),a=new Float64Array(t);if(!c)for(let e=0;e<t;e++)a[e]=r.getUint32(e*p+4,!0);yield f(t,a,o.map(e=>{let n=new Float64Array(t);if(e<s){let{a,b:o}=i.analog[e],s=8+e*m;if(i.ft===`BINARY`)for(let e=0,i=s;e<t;e++,i+=p){let t=r.getInt16(i,!0);n[e]=t===-32768?NaN:a*t+o}else if(i.ft===`BINARY32`)for(let e=0,i=s;e<t;e++,i+=p){let t=r.getInt32(i,!0);n[e]=t===-2147483648?NaN:a*t+o}else for(let e=0,i=s;e<t;e++,i+=p)n[e]=a*r.getFloat32(i,!0)+o}else{let i=e-s,a=8+s*m+2*(i>>4),o=1<<(i&15);for(let e=0,i=a;e<t;e++,i+=p)n[e]=r.getUint16(i,!0)&o?1:0}return n})),g-=t}}var $=8192,br=e=>crypto.subtle.digest(`SHA-256`,e),xr=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),Sr=e=>Uint8Array.from(e.replace(/-/g,``).match(/../g)??[],e=>parseInt(e,16));async function Cr(e,t,n,r,i){let a=r.chain??={verified:0,broken:0,unchecked:0},o=t[t.length-1];if(!o||(o.bytes[0]&127)!=8){a.unchecked++,i.rid=void 0;return}let s=await n(o.bytes),c=s?x(s.plaintext):null,l=xr(await br(Sr(e.recordingId))).slice(0,16),u=i.rid===e.recordingId?(i.seq??-1)+1:0;c&&c.lane===1&&c.run===l&&c.seq===BigInt(e.seq)&&e.seq===u&&c.count===t.length-1&&xr((await S(t.slice(0,-1).map(e=>br(e.bytes)))).buffer)===xr(c.hash.buffer)?a.verified++:a.broken++,i.rid=e.recordingId,i.seq=e.seq}async function*wr(e){let t=0;for(;t+56<=e.size;){let n=te(await e.read(t,56));if(yield await e.slice(t,n.bytes),n.bytes<=56)return;t+=n.bytes}}function Tr(e){let t=e.filter(e=>e&&typeof e.t==`number`&&Array.isArray(e.signals)),n={},r={};return t.forEach((e,i)=>{for(let a of e.signals){if(!a||typeof a.name!=`string`)continue;let e=n[a.name]??=new Float64Array(t.length).fill(NaN);e[i]=typeof a.value==`number`?a.value:NaN,a.unit&&!r[a.name]&&(r[a.name]=a.unit)}}),{t:t.map(e=>e.t),columns:n,units:r}}var Er=4096;function Dr(e){let t=2166136261^e.length;for(let n=0,r=Math.min(e.length,64);n<r;n++)t=Math.imul(t^e[n],16777619);return t>>>0}var Or=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),kr=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){for(let t of[this.pending,this.held])for(let n of t){let r=e[n];if(r){for(let e=0;e<r.length;e++)if(Number.isFinite(r[e])){this.real.add(n),t.delete(n);break}}}}start(e){if(this.pending.size===0||e.t.length===0)return e;let t={...e.columns},n={...e.units};for(let r of this.pending){let i=this.known.get(r),a=new Float64Array(e.t.length).fill(NaN);a[0]=i.v,t[r]=a,i.unit&&!n[r]&&(n[r]=i.unit),this.held.add(r)}return this.pending.clear(),{...e,columns:t,units:n}}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*Ar(e,n,r,i,a=!1){let o=ne(e.keys??[]),s=new Map,c=new Map,l=i?null:new kr,u=null,d=0,f=e=>l?(l.sampled(e.columns),e.t.length&&(u=+e.t[e.t.length-1],d=e.at),l.start(e)):e,p={};for await(let e of wr(n)){let{header:n,messages:u}=ee(e);r.t0??=n.t0,a&&await Cr(n,u,o,r,p);for(let e of u){let n=Dr(e.bytes),a=c.get(n);if(a&&Or(a,e.bytes))continue;c.set(n,e.bytes),c.size>Er&&c.delete(c.keys().next().value);let u=await o(e.bytes);if(!u){r.lost++;continue}try{if(u.kind===5){let e=y(u.plaintext);s.set(e.id,e);continue}if(u.kind===4){let t=await ie(u.plaintext,s);if(!t){r.lost++;continue}let n={at:e.at,t:t.block.t,columns:t.block.columns,units:t.block.units??{},historical:t.historical};t.historical&&l?.sampled(n.columns),(i===void 0||i===!!t.historical)&&(yield t.historical?n:f(n));continue}if(i)continue;if(u.kind===7){let e=re(u.plaintext,s);e&&l?.note(e)}else if(u.kind===3){let t=h(u.plaintext);yield f({at:e.at,t:t.t,columns:t.columns,units:t.units??{}})}else if(u.kind===2){let n=t(u.plaintext);yield f({at:e.at,...Tr(Array.isArray(n?.frames)?n.frames:[])})}}catch{r.lost++}}}let m=l?.end(u,d);m&&(yield m)}function jr(e,t,n){let r=e===null?t:t===null?e:Math.min(e,t);return r===null?{}:r>1e9?{wallOrigin:String(r),wallQuality:`exact`}:Number.isFinite(n)?{wallOrigin:String(r+n),wallQuality:`approx`}:{}}var Mr={mdf:It,edf:Vt,xdf:Zt,tdms:vn,hdf5:Vn,mat:lr,comtrade:vr,krc:{id:`krc`,label:`Kymoscope recording`,extensions:[],sniff:()=>!1,async plan(e,t){let n=[d],r=new Map([[d,`s`]]),i={lost:0,t0:null},a=0,o=!1,s=null,c=null,l=0,u=-1/0,f=0,p=1/0;for await(let d of Ar(e,t,i,void 0,!0)){a+=d.t.length,d.historical&&(o=!0);let e=d.t.length;e&&d.historical?c??=+d.t[0]:e&&(s??=+d.t[0],+d.t[0]+l<u&&(l=u+Math.max(0,(d.at-f)/1e3)-+d.t[0]),f=d.at,u=+d.t[e-1]+l,p=Math.min(p,d.at/1e3-u));for(let e of Object.keys(d.columns))e!==`ElapsedTime`&&(r.has(e)?!r.get(e)&&d.units[e]&&r.set(e,d.units[e]):(n.push(e),r.set(e,d.units[e]??``)))}let m=n.map(e=>({name:e,unit:r.get(e)??``})),h=i.lost?[`${i.lost} ${i.lost===1?`message`:`messages`} couldn't be opened with the keys this browser has.`]:[],g=i.chain?.broken??0;return g&&h.push(`Some of this recording was missing, out of order or changed where it is stored (${g} of ${g+(i.chain?.verified??0)} checked ${g+(i.chain?.verified??0)===1?`chunk`:`chunks`}).`),{format:`Kymoscope recording`,startTime:i.t0===null?null:new Date(i.t0).toISOString(),groups:[{name:`Recording`,channels:m,samples:a,time:{kind:`timestamps`},rateHz:null}],meta:{...jr(s,c,p),...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:h,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(d),o=()=>r.map(()=>new Float64Array($).fill(NaN)),s=new Float64Array($),c=o(),l=0,u=0,f=0,p=-1/0,m=0,h=null,g=()=>{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};function*_(e){let t=e.t.length;for(let n=0;n<t;){let r=Math.min(t-n,$-l);for(let t=0;t<r;t++){let r=+e.t[n+t]+f;h??=r,s[l+t]=r-h}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 g())}}let v=n?Ar(e.files,e.io,{lost:0,t0:null},!0):null,y=async()=>{for(let e=await v?.next();e&&!e.done;e=await v.next())if(e.value.t.length)return e.value;return null},b=await y();for await(let t of Ar(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]+f<p&&(f=p+Math.max(0,(t.at-m)/1e3)-+t.t[0]),m=t.at;b&&+b.t[0]<+t.t[0];b=await y())yield*_(b);yield*_(t),p=+t.t[n-1]+f}}for(;b&&!e.signal?.aborted;b=await y())yield*_(b);l>0&&(yield g())}}};function Nr(e){let t=Mr[e];if(!t)throw Error(`No importer for format ${e}.`);return t}export{Nr as importerFor};
|