@kymoscope/sdk 0.17.0 → 0.18.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-BblHvxro.js → importer.worker-BEjFe0TV.js} +4 -4
- package/dist/assets/liveIngestWorker-MA_RO8uZ.js +1 -0
- package/dist/importers-4ETLHzYe.js +5 -0
- package/dist/keys-CbPoU_jx.js +11 -0
- package/dist/kymoscope-embed.js +61 -61
- package/dist/kymoscope-sdk.js +84 -84
- package/dist/types/lib/data/liveDataSource.d.ts +5 -0
- package/dist/types/lib/importers/types.d.ts +2 -0
- package/dist/types/lib/live/blockWire.d.ts +17 -7
- package/dist/types/lib/live/buffer.d.ts +14 -1
- package/dist/types/lib/live/liveIngest.d.ts +16 -0
- package/dist/types/lib/live/sparseFeed.d.ts +39 -0
- package/dist/types/lib/live/sparseStore.d.ts +18 -0
- package/dist/types/lib/live/wire.d.ts +2 -0
- package/package.json +1 -1
- package/dist/assets/liveIngestWorker-UV5D515-.js +0 -1
- package/dist/importers-CLmQyVrb.js +0 -5
- package/dist/keys-B-nvFeb4.js +0 -11
|
@@ -11,7 +11,12 @@ import type { PointColumns } from './pointColumns';
|
|
|
11
11
|
*/
|
|
12
12
|
export declare class LiveDataSource implements DataSource {
|
|
13
13
|
#private;
|
|
14
|
+
/** Called with the columns a read names, before it reads (a stream over 1,000 channels activates them: see
|
|
15
|
+
* sparseFeed.ts). */
|
|
16
|
+
onUse?: (columns: string[]) => void;
|
|
14
17
|
constructor(buffer: LiveBuffer | (() => LiveBuffer));
|
|
18
|
+
/** Track again every key trackCycles was asked for: after the buffer was rebuilt (its clear() drops them). */
|
|
19
|
+
retrackCycles(): void;
|
|
15
20
|
/** Current sample count of the underlying ring, read live (no allocation). Lets
|
|
16
21
|
* a host's sample-count badge show the climbing count by polling itself, instead of the
|
|
17
22
|
* count riding on the ~1 Hz `connections` state whose update re-renders the App. */
|
|
@@ -58,6 +58,8 @@ export interface ImportPlan {
|
|
|
58
58
|
pick?: boolean;
|
|
59
59
|
/** Groups read when nobody chooses (default: all). */
|
|
60
60
|
defaultGroups?: number[];
|
|
61
|
+
/** Channels read when nobody chooses, when not every channel of `defaultGroups` (a recording over 1,000 channels). */
|
|
62
|
+
defaultSelection?: GroupSelection[];
|
|
61
63
|
/**
|
|
62
64
|
* The groups share one data stream (unsorted MF4, bus logging): read them in
|
|
63
65
|
* one pass with `stream`, even when the importer has `streamGroup`.
|
|
@@ -14,8 +14,8 @@ export interface BlockSchema {
|
|
|
14
14
|
id: number;
|
|
15
15
|
channels: BlockChannel[];
|
|
16
16
|
}
|
|
17
|
-
/** The channel table of a decrypted KIND_BLOCK_SCHEMA plaintext. Throws RangeError if malformed. */
|
|
18
|
-
export declare function decodeBlockSchema(p: Uint8Array): BlockSchema
|
|
17
|
+
/** The channel table of a decrypted KIND_BLOCK_SCHEMA plaintext, version 2 or 3. Throws RangeError if malformed. */
|
|
18
|
+
export declare function decodeBlockSchema(p: Uint8Array): Promise<BlockSchema>;
|
|
19
19
|
/** KIND_BLOCK_SCHEMA plaintext with a given id (tests and local publishers; senders use the CRC-32 of the table). */
|
|
20
20
|
export declare function encodeBlockSchema(id: number, channels: BlockChannel[]): Uint8Array;
|
|
21
21
|
/** One channel of a KIND_LAST_VALUES: its last finite value and that value's time (stream seconds). */
|
|
@@ -26,18 +26,28 @@ export interface LastValue {
|
|
|
26
26
|
v: number;
|
|
27
27
|
}
|
|
28
28
|
/**
|
|
29
|
-
* The channels with a value of a decrypted KIND_LAST_VALUES plaintext (u8 version
|
|
30
|
-
* u32 schema id, u32 count,
|
|
31
|
-
*
|
|
32
|
-
*
|
|
29
|
+
* The channels with a value of a decrypted KIND_LAST_VALUES plaintext, version 1 (above) or 2 (u8 version, u8 flags,
|
|
30
|
+
* u16 reserved, u32 schema id, u32 count, f64 reference time, optional u32 channel indexes, u32 ms before the
|
|
31
|
+
* reference per entry, byte-split values, optionally deflated). Null until its schema has arrived.
|
|
32
|
+
* Throws RangeError if malformed. Pinned by tests/vectors/capacity-v1.json.
|
|
33
33
|
*/
|
|
34
|
-
export declare function decodeLastValues(p: Uint8Array, schemas: ReadonlyMap<number, BlockSchema>): LastValue[] | null
|
|
34
|
+
export declare function decodeLastValues(p: Uint8Array, schemas: ReadonlyMap<number, BlockSchema>): Promise<LastValue[] | null>;
|
|
35
35
|
/** KIND_LAST_VALUES plaintext of `t` / `v` in `schema`'s channel order, NaN for none (tests and local publishers). */
|
|
36
36
|
export declare function encodeLastValues(schema: BlockSchema, t: ArrayLike<number>, v: ArrayLike<number>): Uint8Array;
|
|
37
37
|
/** A decrypted KIND_BLOCK plaintext's rows; null until its schema has arrived. Throws RangeError if malformed. */
|
|
38
38
|
export declare function decodeBlock(p: Uint8Array, schemas: ReadonlyMap<number, BlockSchema>): Promise<{
|
|
39
39
|
block: LiveColumnsBlock;
|
|
40
40
|
historical: boolean;
|
|
41
|
+
schemaId: number;
|
|
42
|
+
} | null>;
|
|
43
|
+
/** A decrypted KIND_SPARSE plaintext: event k is channel `index[k]` of the schema at `t[k]` with `v[k]`. Null until
|
|
44
|
+
* its schema has arrived. Throws RangeError if malformed. */
|
|
45
|
+
export declare function decodeSparse(p: Uint8Array, schemas: ReadonlyMap<number, BlockSchema>): Promise<{
|
|
46
|
+
schemaId: number;
|
|
47
|
+
index: Uint32Array;
|
|
48
|
+
t: Float64Array;
|
|
49
|
+
v: Float64Array;
|
|
50
|
+
historical: boolean;
|
|
41
51
|
} | null>;
|
|
42
52
|
/** KIND_BLOCK plaintext of `block` under `schema` (tests and local publishers). Little-endian hosts only. */
|
|
43
53
|
export declare function encodeBlock(block: {
|
|
@@ -41,6 +41,8 @@ export declare class LiveBuffer {
|
|
|
41
41
|
private pushed;
|
|
42
42
|
/** Times the buffer was cleared (keeps `version` moving even though `pushed` resets). */
|
|
43
43
|
private clears;
|
|
44
|
+
/** Rows pushed before the last clear, in all: `version` never goes back after a clear and fewer rows. */
|
|
45
|
+
private pushedBefore;
|
|
44
46
|
private readonly signalOrder;
|
|
45
47
|
private readonly unitByName;
|
|
46
48
|
private capacity;
|
|
@@ -83,6 +85,9 @@ export declare class LiveBuffer {
|
|
|
83
85
|
private snapDec;
|
|
84
86
|
/** Each column's newest finite value and its time, kept past the ring (see lastKnown). */
|
|
85
87
|
private latest;
|
|
88
|
+
/** Channels listed without a column (a stream over 1,000 channels: see sparseFeed.ts), name -> unit. A column per
|
|
89
|
+
* listed channel cost 32 KB each: 3.2 GB for 100k channels before a sample arrived. */
|
|
90
|
+
private readonly listed;
|
|
86
91
|
/**
|
|
87
92
|
* `capacity`: samples kept (the oldest are dropped past it). Memory grows with
|
|
88
93
|
* the samples actually received; `maxBytes` caps it — once the columns would
|
|
@@ -114,7 +119,7 @@ export declare class LiveBuffer {
|
|
|
114
119
|
* the size it has, the oldest samples dropped from here, instead of failing the push and losing its samples.
|
|
115
120
|
*/
|
|
116
121
|
private refused;
|
|
117
|
-
/** Samples ever pushed (and bumped by clear): a data version for consumers. */
|
|
122
|
+
/** Samples ever pushed (and bumped by clear): a data version for consumers, never repeated. */
|
|
118
123
|
get version(): number;
|
|
119
124
|
get size(): number;
|
|
120
125
|
push(msg: LiveMessage): void;
|
|
@@ -187,6 +192,10 @@ export declare class LiveBuffer {
|
|
|
187
192
|
clearComputed(): void;
|
|
188
193
|
/** Column names in order: the time column first, then the signals. */
|
|
189
194
|
get columnNames(): string[];
|
|
195
|
+
/** `columnNames.length` without building it (100k listed names on every ingest). */
|
|
196
|
+
get columnCount(): number;
|
|
197
|
+
/** Whether `name` is in `columnNames` (the time column, a column, or a listed channel). */
|
|
198
|
+
has(name: string): boolean;
|
|
190
199
|
/** Unit string for a column (empty if unknown). */
|
|
191
200
|
unitOf(name: string): string;
|
|
192
201
|
/**
|
|
@@ -327,6 +336,8 @@ export declare class LiveBuffer {
|
|
|
327
336
|
/** Whether `name` has had a finite value (a sample or a last known value) since the stream started (or was
|
|
328
337
|
* cleared), in the ring or not. */
|
|
329
338
|
hasValues(name: string): boolean;
|
|
339
|
+
/** The bytes the columns may take (the constructor's `maxBytes`). */
|
|
340
|
+
get memoryBudget(): number;
|
|
330
341
|
/** How many columns have had a finite value (moves when one gets its first). */
|
|
331
342
|
get valuedCount(): number;
|
|
332
343
|
/** The newest finite value of `name` and its time (a sample, or a last known value when newer), past the ring. */
|
|
@@ -334,6 +345,8 @@ export declare class LiveBuffer {
|
|
|
334
345
|
t: number;
|
|
335
346
|
v: number;
|
|
336
347
|
} | undefined;
|
|
348
|
+
/** List `name` without a column (its last value `t`/`v` when finite); a channel that has a column is left as is. */
|
|
349
|
+
list(name: string, unit: string, t?: number, v?: number): void;
|
|
337
350
|
/**
|
|
338
351
|
* A channel's last value as the sender knows it (KIND_LAST_VALUES): not a sample (the ring, decimation, cycles
|
|
339
352
|
* and readers of samples never see it), only the value a quiet channel holds. Creates the column (no samples)
|
|
@@ -29,6 +29,22 @@ export type Decoded = {
|
|
|
29
29
|
| {
|
|
30
30
|
type: 'integrity';
|
|
31
31
|
integrity: StreamIntegrity;
|
|
32
|
+
}
|
|
33
|
+
/** A channel table for the page's SparseFeed: a stream over SPARSE_CHANNELS channels, or one that sends events. */
|
|
34
|
+
| {
|
|
35
|
+
type: 'schema';
|
|
36
|
+
id: number;
|
|
37
|
+
names: string[];
|
|
38
|
+
units: string[];
|
|
39
|
+
}
|
|
40
|
+
/** KIND_SPARSE events of schema `schemaId`: event k is channel index[k] at t[k] with v[k]. */
|
|
41
|
+
| {
|
|
42
|
+
type: 'sparse';
|
|
43
|
+
schemaId: number;
|
|
44
|
+
index: Uint32Array;
|
|
45
|
+
t: Float64Array;
|
|
46
|
+
v: Float64Array;
|
|
47
|
+
historical: boolean;
|
|
32
48
|
};
|
|
33
49
|
/**
|
|
34
50
|
* A stream's messages opened with `key` and handed to `emit` in the order they arrived (decrypted as they arrive, in
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A stream over SPARSE_CHANNELS channels (spec docs/superpowers/specs/2026-11-23-stream-capacity-design.md): every
|
|
3
|
+
* channel is listed in the LiveBuffer without a column, every channel's events kept in a SparseStore, and only the
|
|
4
|
+
* active channels (the ones something read, see LiveDataSource.onUse) get rows in the buffer. 20 charted tags of 50k
|
|
5
|
+
* cost what 20 tags cost.
|
|
6
|
+
*/
|
|
7
|
+
import type { LiveBuffer, LiveColumnsBlock } from './buffer';
|
|
8
|
+
import type { LastValue } from './blockWire';
|
|
9
|
+
/** A stream with more channels than this is listed, not held as columns: see the SparseFeed. */
|
|
10
|
+
export declare const SPARSE_CHANNELS = 1000;
|
|
11
|
+
/** ponytail: a cap so a reader of every column (an export) can't densify the stream; eviction of channels nobody
|
|
12
|
+
* read for minutes if someone browses more than this in one session. */
|
|
13
|
+
export declare const MAX_ACTIVE = 1000;
|
|
14
|
+
export declare class SparseFeed {
|
|
15
|
+
private readonly buffer;
|
|
16
|
+
private readonly store;
|
|
17
|
+
private readonly schemas;
|
|
18
|
+
/** Every channel ever listed: unit and newest value (survives a replay's clear). */
|
|
19
|
+
private readonly known;
|
|
20
|
+
private readonly active;
|
|
21
|
+
constructor(buffer: LiveBuffer, maxBytes: number);
|
|
22
|
+
schema(id: number, names: string[], units: string[]): void;
|
|
23
|
+
last(values: LastValue[]): void;
|
|
24
|
+
/** Events of schema `id`. The active channels' ones go into the buffer as rows; that block is returned (null:
|
|
25
|
+
* none, or the schema is unknown). */
|
|
26
|
+
push(id: number, index: Uint32Array, t: Float64Array, v: Float64Array): LiveColumnsBlock | null;
|
|
27
|
+
/** {@link push} by channel name (a dense block on a big stream, as events): names not listed are ignored. */
|
|
28
|
+
pushNamed(t: ArrayLike<number>, names: string[], v: ArrayLike<number>): LiveColumnsBlock | null;
|
|
29
|
+
private events;
|
|
30
|
+
/** Mark `names` active (unknown names and the time column are ignored); true when one was added. Their stored
|
|
31
|
+
* events come with the next {@link replay} (the caller runs one for a tick's activations, not inside a read). */
|
|
32
|
+
activate(names: Iterable<string>): boolean;
|
|
33
|
+
/** Rebuild the buffer: clear, list every channel, and the active channels' newest stored events (at most
|
|
34
|
+
* `buffer.maxSamples` distinct times), merged by time in chunks.
|
|
35
|
+
* ponytail: resets cycles and the segment axis; fine while activation is rare (a chart gets a channel). Each
|
|
36
|
+
* channel's events are taken as time-ordered (arrival order); a late one lands through the buffer's late path. */
|
|
37
|
+
replay(): void;
|
|
38
|
+
private note;
|
|
39
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare class SparseStore {
|
|
2
|
+
private readonly channels;
|
|
3
|
+
private events_;
|
|
4
|
+
private readonly maxBytes;
|
|
5
|
+
constructor(maxBytes: number);
|
|
6
|
+
/** Bytes of events held. */
|
|
7
|
+
get bytes(): number;
|
|
8
|
+
add(name: string, t: number, v: number): void;
|
|
9
|
+
/** `name`'s events, oldest first (views: valid until the next add). */
|
|
10
|
+
events(name: string): {
|
|
11
|
+
t: Float64Array;
|
|
12
|
+
v: Float64Array;
|
|
13
|
+
};
|
|
14
|
+
/** Down to 90% of the budget in one pass (the 10% of slack makes passes rare): the busiest channel loses its oldest
|
|
15
|
+
* half, again and again. Each round halves channels busiest first and sorts again once the halved ones are the
|
|
16
|
+
* busiest again. Ends: each round halves its busiest channel; a store of nothing stops it (a budget of 0 or less). */
|
|
17
|
+
private evict;
|
|
18
|
+
}
|
|
@@ -12,6 +12,8 @@ export declare const KIND_VIDEO = 6;
|
|
|
12
12
|
export declare const KIND_LAST_VALUES = 7;
|
|
13
13
|
/** An integrity checkpoint over the messages before it in its lane (see chainWire.ts). */
|
|
14
14
|
export declare const KIND_CHAIN = 8;
|
|
15
|
+
/** Events of a stream over 1,000 channels, each one channel at its own time (see blockWire.ts decodeSparse). */
|
|
16
|
+
export declare const KIND_SPARSE = 9;
|
|
15
17
|
export declare const KEY_ID_FLAG = 128;
|
|
16
18
|
export interface SealedMessage {
|
|
17
19
|
kind: number;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kymoscope/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.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 +0,0 @@
|
|
|
1
|
-
const e=e=>e.startsWith(`eyJ`);function t(e){try{let t=e.split(`.`)[1]??``,n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)+`===`.slice((t.length+3)%4)),r=JSON.parse(n).exp;return typeof r==`number`?r:null}catch{return null}}function n(e,t){return`${e.replace(/\/+$/,``)}/v1/streams/${t}/watch`}function r(r,i,a,o){let s=null,c=null,l=null,u=!1,d=0,f=()=>{l&&=(clearTimeout(l),null)},p=(n,a)=>{f();let o=t(a);if(o===null)return;let c=e(a),d=c?Math.min(o,Date.now()/1e3+300):o,m=Math.min(Math.max((d-(c?90:30))*1e3-Date.now(),1e4),2**31-1);l=setTimeout(async()=>{l=null;let e=null;try{e=await r.getToken(i)}catch{e=null}if(!(u||s!==n||!e)){try{n.send(JSON.stringify({type:`auth`,token:e}))}catch{return}p(n,e)}},m)},m=(e=!1)=>{if(u||c)return;let t=e?0:Math.min(3e4,2e3*2**d++)*(.75+Math.random()/2);c=setTimeout(()=>{c=null,h()},t)},h=async()=>{if(u)return;let e=null;try{e=await r.getToken(i)}catch{e=null}if(u)return;if(!e){o?.(`error`),m();return}let t=new WebSocket(n(r.url,i),[`kymoscope-live.v1`,`kymoscope-live.ack1`,`kymoscope-live.ack2`,`bearer.${e}`]);t.binaryType=`arraybuffer`,s=t;let c=e,l=Date.now(),h=0,g=setInterval(()=>{if(!(h===0||t.readyState!==1)){try{t.send(JSON.stringify({type:`ack`,b:h}))}catch{return}h=0}},1e3);t.onopen=()=>{o?.(`subscribed`),p(t,c)},t.onmessage=e=>{if(d=0,typeof e.data!=`string`){h+=e.data.byteLength,a(e.data);return}if(e.data.startsWith(`{"type":"probe"`))try{let n=JSON.parse(e.data).id;typeof n==`string`&&n.length<=64&&t.send(JSON.stringify({type:`ack`,id:n}))}catch{}},t.onclose=()=>{clearInterval(g),s===t&&(s=null,f(),!u&&(o?.(`error`),m(Date.now()-l>=1e4)))}};return h(),()=>{if(u=!0,c&&=(clearTimeout(c),null),f(),s){let e=s;s=null,e.close(1e3)}}}new TextEncoder;function i(e,t,n){let r=t,i=r+n,a=[],o=``;for(;r<i;){let t=e[r++];if(!(t&128))a.push(t);else if((t&224)==192){let n=e[r++]&63;a.push((t&31)<<6|n)}else if((t&240)==224){let n=e[r++]&63,i=e[r++]&63;a.push((t&31)<<12|n<<6|i)}else if((t&248)==240){let n=e[r++]&63,i=e[r++]&63,o=e[r++]&63,s=(t&7)<<18|n<<12|i<<6|o;s>65535&&(s-=65536,a.push(s>>>10&1023|55296),s=56320|s&1023),a.push(s)}else a.push(t);a.length>=4096&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}const a=new TextDecoder;function o(e,t,n){let r=e.subarray(t,t+n);return a.decode(r)}function s(e,t,n){return n>200?o(e,t,n):i(e,t,n)}var c=class{type;data;constructor(e,t){this.type=e,this.data=t}},l=class e extends Error{constructor(t){super(t);let n=Object.create(e.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,`name`,{configurable:!0,enumerable:!1,value:e.name})}};function u(e,t,n){let r=Math.floor(n/4294967296),i=n;e.setUint32(t,r),e.setUint32(t+4,i)}function d(e,t){let n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}function f(e,t){let n=e.getUint32(t),r=e.getUint32(t+4);return n*4294967296+r}function p({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=17179869183)if(t===0&&e<=4294967295){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}else{let n=e/4294967296,r=e&4294967295,i=new Uint8Array(8),a=new DataView(i.buffer);return a.setUint32(0,t<<2|n&3),a.setUint32(4,r),i}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,t),u(r,4,e),n}}function m(e){let t=e.getTime(),n=Math.floor(t/1e3),r=(t-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function h(e){return e instanceof Date?p(m(e)):null}function g(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let e=t.getUint32(0),n=t.getUint32(4);return{sec:(e&3)*4294967296+n,nsec:e>>>2}}case 12:return{sec:d(t,4),nsec:t.getUint32(0)};default:throw new l(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function _(e){let t=g(e);return new Date(t.sec*1e3+t.nsec/1e6)}const ee={type:-1,encode:h,decode:_};var v=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(ee)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{let r=-1-e;this.builtInEncoders[r]=t,this.builtInDecoders[r]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){let r=this.builtInEncoders[n];if(r!=null){let i=r(e,t);if(i!=null)return new c(-1-n,i)}}for(let n=0;n<this.encoders.length;n++){let r=this.encoders[n];if(r!=null){let i=r(e,t);if(i!=null)return new c(n,i)}}return e instanceof c?e:null}decode(e,t,n){let r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,n):new c(t,e)}};function y(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}function b(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):y(e)?new Uint8Array(e):Uint8Array.from(e)}function x(e){return`${e<0?`-`:``}0x${Math.abs(e).toString(16).padStart(2,`0`)}`}var te=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=16,t=16){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){let r=this.caches[n-1];FIND_CHUNK:for(let i of r){let r=i.bytes;for(let i=0;i<n;i++)if(r[i]!==e[t+i])continue FIND_CHUNK;return i.str}return null}store(e,t){let n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)}decode(e,t,n){let r=this.find(e,t,n);if(r!=null)return this.hit++,r;this.miss++;let a=i(e,t,n),o=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(o,a),a}};const S=`array`,C=`map_key`,w=`map_value`,T=e=>{if(typeof e==`string`||typeof e==`number`)return e;throw new l(`The type of key must be string or number but `+typeof e)};var E=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=S,t.position=0,t.size=e,t.array=Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=C,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){return this.stackHeadPosition++,this.stackHeadPosition===this.stack.length&&this.stack.push({type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null}),this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw Error(`Invalid stack state. Released state is not on top of the stack.`);if(e.type===S){let t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===C||e.type===w){let t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}};const D=new DataView(new ArrayBuffer(0)),ne=new Uint8Array(D.buffer);try{D.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw Error(`This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access`)}const O=RangeError(`Insufficient data`),re=new te;var ie=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=D;bytes=ne;headByte=-1;stack=new E;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??v.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder===void 0?re:e.keyDecoder,this.mapKeyConverter=e?.mapKeyConverter??T}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(e){let t=b(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===-1&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),n=b(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:n}=this;return RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(let r of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(r);try{n=this.doDecodeSync(),t=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:r,pos:i,totalPos:a}=this;throw RangeError(`Insufficient data in parsing ${x(r)} at ${a} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,r=-1;for await(let i of e){if(t&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),n&&(r=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--r!==0;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){DECODE:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue DECODE}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue DECODE}else t=[]}else{let n=e-160;t=this.decodeString(n,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(e===217){let e=this.lookU8();t=this.decodeString(e,1)}else if(e===218){let e=this.lookU16();t=this.decodeString(e,2)}else if(e===219){let e=this.lookU32();t=this.decodeString(e,4)}else if(e===220){let e=this.readU16();if(e!==0){this.pushArrayState(e),this.complete();continue DECODE}else t=[]}else if(e===221){let e=this.readU32();if(e!==0){this.pushArrayState(e),this.complete();continue DECODE}else t=[]}else if(e===222){let e=this.readU16();if(e!==0){this.pushMapState(e),this.complete();continue DECODE}else t={}}else if(e===223){let e=this.readU32();if(e!==0){this.pushMapState(e),this.complete();continue DECODE}else t={}}else if(e===196){let e=this.lookU8();t=this.decodeBinary(e,1)}else if(e===197){let e=this.lookU16();t=this.decodeBinary(e,2)}else if(e===198){let e=this.lookU32();t=this.decodeBinary(e,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let e=this.lookU8();t=this.decodeExtension(e,1)}else if(e===200){let e=this.lookU16();t=this.decodeExtension(e,2)}else if(e===201){let e=this.lookU32();t=this.decodeExtension(e,4)}else throw new l(`Unrecognized type byte: ${x(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let e=n.top();if(e.type===S)if(e.array[e.position]=t,e.position++,e.position===e.size)t=e.array,n.release(e);else continue DECODE;else if(e.type===C){if(t===`__proto__`)throw new l(`The key __proto__ is not allowed`);e.key=this.mapKeyConverter(t),e.type=w;continue DECODE}else if(e.map[e.key]=t,e.readCount++,e.readCount===e.size)t=e.map,n.release(e);else{e.key=null,e.type=C;continue DECODE}}return t}}readHeadByte(){return this.headByte===-1&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new l(`Unrecognized array type byte: ${x(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new l(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new l(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new l(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw O;let n=this.pos+t,r;return r=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,n,e):s(this.bytes,n,e),this.pos+=t+e,r}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===C:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new l(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw O;let n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r}decodeExtension(e,t){if(e>this.maxExtLength)throw new l(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=f(this.view,this.pos);return this.pos+=8,e}readI64(){let e=d(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function k(e,t){return new ie(t).decode(e)}function A(){let e=globalThis.crypto;if(!e?.subtle)throw Error(`WebCrypto SubtleCrypto is not available`);return e.subtle}async function j(e,t,n,r){let i=await A().decrypt({name:`AES-GCM`,iv:t,additionalData:r},e,n);return new Uint8Array(i)}new TextEncoder().encode(`kymoscope-device-wrap-v1`),new TextEncoder().encode(`kymoscope-sender-bind-v1`);function M(e){let t=new Uint8Array(e),n=t.length>0&&t[0]&128?2:1;return t.length<n+12+16?null:{kind:t[0]&-129,keyId:n===2?t[1]:null,iv:t.subarray(n,n+12),ciphertext:t.subarray(n+12),aad:t.subarray(0,n)}}async function N(e,t){let n=M(t);if(!n)return null;let r=typeof e==`function`?await e(n.keyId):e;if(!r)return null;let i=await j(r,n.iv,n.ciphertext,n.aad);return{kind:n.kind,plaintext:i}}const P=e=>e+7&-8;function F(e){let t=e=>RangeError(`columns message: ${e}`);e.byteOffset%8!=0&&(e=e.slice());let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.byteLength<8)throw t(`short`);if(n.getUint8(0)!==1)throw t(`version ${n.getUint8(0)}`);let r=n.getUint16(2,!0),i=n.getUint32(4,!0),a=new TextDecoder,o=[],s=8;for(let i=0;i<r;i++){if(s+3>e.byteLength)throw t(`short channel table`);let r=n.getUint8(s),i=n.getUint8(s+1),c=n.getUint8(s+2);if(s+=3,r!==4&&r!==8)throw t(`value size ${r}`);if(s+i+c>e.byteLength)throw t(`short channel table`);o.push({name:a.decode(e.subarray(s,s+i)),unit:a.decode(e.subarray(s+i,s+i+c)),size:r}),s+=i+c}if(s=P(s),s+P(i*8)+o.reduce((e,t)=>e+P(i*t.size),0)>e.byteLength)throw t(`short data`);let c=e.byteOffset,l=new Float64Array(e.buffer,c+s,i);s+=P(i*8);let u={},d={};for(let t of o)u[t.name]=t.size===4?new Float32Array(e.buffer,c+s,i):new Float64Array(e.buffer,c+s,i),t.unit&&(d[t.name]=t.unit),s+=P(i*t.size);return{t:l,columns:u,units:d}}function I(e){if(e.length<24||e[0]!==1||e[2]!==1)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=(e[1]&1)!=0,r=t.getUint16(16,!0),i=t.getUint16(18,!0);if(i===0||r>=i)return null;let a=24,o=``;if(n&&r===0){if(e.length<a+1||e.length<a+1+e[a])return null;o=new TextDecoder().decode(e.subarray(a+1,a+1+e[a])),a+=1+e[a]}return{key:n,last:(e[1]&2)!=0,t:t.getFloat64(4,!0),seq:t.getUint32(12,!0),fragIndex:r,fragCount:i,width:t.getUint16(20,!0),height:t.getUint16(22,!0),codec:o,payload:e.subarray(a)}}const L=(e,t)=>RangeError(`${e}: ${t}`);function R(e){if(e.byteLength<8)throw L(`block schema`,`short`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t.getUint8(0)!==2)throw L(`block schema`,`version ${t.getUint8(0)}`);let n=t.getUint16(2,!0),r=t.getUint32(4,!0),i=new TextDecoder(`utf-8`,{fatal:!0}),a=[],o=8;try{for(let r=0;r<n;r++){if(o+3>e.byteLength)throw L(`block schema`,`short channel table`);let n=t.getUint8(o),r=t.getUint8(o+1),s=t.getUint8(o+2);if(o+=3,n!==4&&n!==8)throw L(`block schema`,`value size ${n}`);if(o+r+s>e.byteLength)throw L(`block schema`,`short channel table`);a.push({name:i.decode(e.subarray(o,o+r)),unit:i.decode(e.subarray(o+r,o+r+s)),size:n}),o+=r+s}}catch(e){throw e instanceof RangeError?e:L(`block schema`,`invalid text`)}return{id:r,channels:a}}function z(e,t){if(e.byteLength<12)throw L(`last values`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint8(0)!==1)throw L(`last values`,`version ${n.getUint8(0)}`);let r=t.get(n.getUint32(4,!0));if(!r)return null;let i=n.getUint32(8,!0);if(i!==r.channels.length)throw L(`last values`,`channel count differs from its schema`);if(e.byteLength<12+16*i)throw L(`last values`,`short`);let a=[];for(let e=0;e<i;e++){let t=n.getFloat64(12+8*e,!0),o=n.getFloat64(12+8*(i+e),!0);Number.isFinite(t)&&Number.isFinite(o)&&a.push({name:r.channels[e].name,unit:r.channels[e].unit,t,v:o})}return a}async function B(e,t){let n=new Blob([e]).stream().pipeThrough(new DecompressionStream(`deflate`)).getReader(),r=new Uint8Array(t),i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+a.length>t)throw L(`block`,`body larger than its header says`);r.set(a,i),i+=a.length}}catch(e){throw await n.cancel().catch(()=>{}),e instanceof RangeError?e:L(`block`,`body is not valid deflate`)}if(i!==t)throw L(`block`,`body size mismatch`);return r}async function V(e,t){if(e.byteLength<20)throw L(`block`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint8(0)!==2)throw L(`block`,`version ${n.getUint8(0)}`);let r=n.getUint8(1),i=n.getUint16(2,!0),a=n.getUint32(4,!0),o=t.get(n.getUint32(8,!0));if(!o)return null;if(o.channels.length!==i)throw L(`block`,`channel count differs from its schema`);let s=n.getFloat64(12,!0),c=Math.max(0,a-1),l=4*c+o.channels.reduce((e,t)=>e+t.size*a,0);if(l>67108864)throw L(`block`,`too large`);let u;if(r&1)u=await B(e.subarray(20),l);else if(u=e.subarray(20),u.byteLength<l)throw L(`block`,`body size mismatch`);let d=new DataView(u.buffer,u.byteOffset,u.byteLength),f=new Float64Array(a),p=0;a&&(f[0]=s);for(let e=1;e<a;e++)p+=d.getInt32(4*(e-1),!0),f[e]=s+p/1e6;let m=4*c,h={},g={};for(let e of o.channels){let t=new Uint8Array(a*e.size);for(let n=0;n<e.size;n++)for(let r=0;r<a;r++)t[r*e.size+n]=u[m+n*a+r];h[e.name]=e.size===4?new Float32Array(t.buffer):new Float64Array(t.buffer),e.unit&&(g[e.name]=e.unit),m+=a*e.size}return{block:{t:f,columns:h,units:g},historical:(r&2)!=0}}const H=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),U=e=>{let t=H(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`};function W(e){if(e.length!==70||e[0]!==1)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{streamId:U(e.subarray(1,17)),run:H(e.subarray(17,25)),lane:e[25],seq:t.getBigUint64(26,!0),count:t.getUint32(34,!0),hash:e.slice(38,70)}}const G=()=>globalThis.crypto.subtle,K=e=>G().digest(`SHA-256`,e);async function q(e){let t=await Promise.all(e),n=new Uint8Array(t.length*32);return t.forEach((e,t)=>n.set(new Uint8Array(e),t*32)),new Uint8Array(await K(n))}function J(e,t,n=()=>Date.now()){let r={verified:0,broken:0},i=null,a=0n,o=null,s=0,c=0,l=0,u=Promise.resolve(),d=e=>{e?r.verified++:(r.broken++,r.lastBrokenAt=n()),t({...r})};return{integrity:r,reset(){i=null,o=null,c=s,l++},arrive(t,n,r){if(n!==8){o&&(o.push(K(t)),s++);return}let f=s;o||(o=[],c=s);let p=l;u=u.then(async()=>{let t=await r.catch(()=>null);if(p!==l)return;let n=t?W(t.plaintext):null;if(!n||n.lane!==0||n.streamId!==e.toLowerCase()){i!==null&&d(!1);return}let s=f-c;if(i===null||n.run!==i){i=n.run,a=n.seq,o=o.slice(Math.max(0,s)),c=Math.max(c,f);return}let u=n.seq===a+1n&&n.count<=s&&ae(await q(o.slice(0,n.count)),n.hash);if(p!==l)return;a=n.seq;let m=u?n.count:s;o=o.slice(m),c+=m,d(u)})}}}const ae=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function oe(e,t,n){let r=new Map,i=Promise.resolve(),a=n?J(n,e=>t({type:`integrity`,integrity:e})):null;return Object.assign(n=>{let o=N(e,n).catch(()=>null);a?.arrive(n,new Uint8Array(n,0,1)[0]&127,o),i=i.then(async()=>{try{let e=await o;if(!e)return;if(e.kind===6){let n=I(e.plaintext);n&&t({type:`video`,m:n})}else if(e.kind===5){let t=R(e.plaintext);r.set(t.id,t)}else if(e.kind===7){let n=z(e.plaintext,r);n&&t({type:`last`,values:n})}else if(e.kind===4){let n=await V(e.plaintext,r);n&&t(n.historical?{type:`columns`,block:n.block,historical:!0}:{type:`columns`,block:n.block})}else if(e.kind===3)t({type:`columns`,block:F(e.plaintext)});else if(e.kind===2){let n=k(e.plaintext);t({type:`frames`,frames:Array.isArray(n?.frames)?n.frames:[]})}}catch{}})},{reset:()=>a?.reset()})}function Y(e){if(e.type!==`columns`)return[];let t=new Set,n=e=>{ArrayBuffer.isView(e)&&Object.prototype.toString.call(e.buffer)===`[object ArrayBuffer]`&&t.add(e.buffer)};n(e.block.t);for(let t of Object.values(e.block.columns))n(t);return[...t]}function se(e,t=67108864){let n=0,r=0,i=0;return{emit(a){let o=Y(a).reduce((e,t)=>e+t.byteLength,0);if(a.type===`columns`&&n>0&&n+o>t){r+=a.block.t.length,i+=a.block.t.length;return}a.type===`columns`&&i>0&&(e({type:`gap`,samples:i},0),i=0),n+=o,e(a,o)},ack(e){n=Math.max(0,n-e)},get dropped(){return r}}}let ce=1;const X=new Map,Z=(e,t)=>new Promise(n=>{let r=ce++;X.set(r,n),self.postMessage({type:`ask`,id:r,what:e,arg:t})});let Q=null;const $=se((e,t)=>self.postMessage({type:`decoded`,d:e,bytes:t},Y(e)));self.onmessage=e=>{let t=e.data;if(t.type===`reply`){X.get(t.id)?.(t.value),X.delete(t.id);return}if(t.type===`ack`){$.ack(t.bytes);return}if(t.type===`stop`){Q?.(),Q=null,self.close();return}let n=new Map,i=oe(t.key??(async e=>{let t=n.get(e);if(t)return t;let r=await Z(`key`,e);return r&&n.set(e,r),r}),$.emit,t.streamId);Q=r({url:t.url,getToken:()=>Z(`token`)},t.streamId,i,e=>{e===`subscribed`&&i.reset(),self.postMessage({type:`status`,status:e})})};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
/*! @kymoscope/sdk (c) 2026 Kymoscope. Proprietary software: use requires a license. See LICENSE.md. */
|
|
2
|
-
import{A as e,At as t,Bt as n,C as r,Gt as i,Ht as a,It as o,Jt as s,Kt as c,Lt as l,Rt as u,S as d,Ut as f,Vt as p,Wt as m,Xt as h,Yt as g,a as _,c as v,i as y,jt as b,k as x,kt as S,l as ee,qt as C,t as te,u as ne,w as re,x as ie,zt as ae}from"./keys-B-nvFeb4.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=h(t).getUint16(24,!0)===0,a=async t=>{let n=h(await e.read(t,4)).getUint16(2,r),i=await e.read(t,n);return{id:m(i.subarray(0,2)),v:h(i),b:i,size:n}},o=(e,t)=>e.getUint32(t,r),s=(e,t)=>e.getUint16(t,r),c=(e,t)=>e.getFloat64(t,r),l=async e=>e?i((await a(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 a(e),u=i(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=i(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 a=46+40*t,o=c(n,a);return{lo:o,hi:o,to:i(r.subarray(a+8,a+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(o(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}}},g=await a(64),_=null;if(g.size>=172&&(o(g.v,164)||o(g.v,168))){let e=o(g.v,168)*4294967296+o(g.v,164);_=new Date(e/1e6).toISOString()}else{let e=m(g.b.subarray(18,28)),t=m(g.b.subarray(28,36));/^\d\d:\d\d:\d{4}$/.test(e)&&(_=`${e.slice(6)}-${e.slice(3,5)}-${e.slice(0,2)}T${t}`)}let v=[],y=0;for(let e=o(g.v,4),t=0;e;t++){f(e);let n=await a(e),c=s(n.v,22),d=[];for(let e=o(n.v,8);e;){f(e);let n=await a(e),m=[],h=null;for(let e=o(n.v,8);e;){f(e);let t=await a(e),n=i(t.b.subarray(26,58),!0),c=(t.size>=222?await l(o(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(o(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=o(t.v,4)}y++,d.push({name:await l(o(n.v,12))||`Group ${y}`,dg:t,recordId:s(n.v,16),recordIdSize:+(c>0),idTrailer:+(c===2),dataBytes:s(n.v,20),invalBytes:0,cycles:o(n.v,22),vlsdCg:!1,sorted:!0,master:h,channels:m,stream:[],busType:0,busEvent:!1}),e=o(n.v,4)}let m=d.reduce((e,t)=>e+t.cycles*(t.recordIdSize+t.dataBytes+t.idTrailer),0),h=[{offset:o(n.v,16),length:m,zip:null}];for(let e of d)e.stream=h,e.sorted=d.length===1,v.push(e);e=o(n.v,4)}return{version:`MDF ${n}`,startTime:_,groups:v,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=h(n),i=m(n.subarray(0,4)),a=s(r,8),o=s(r,16);if(!i.startsWith(`##`)||a<24+8*o||a>1<<26)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let c=await e.read(t,a);if(c.length<a)throw Error(`This MF4 is damaged (the block at byte ${t} runs past the end of the file).`);let l=h(c),u=[];for(let e=0;e<o;e++)u.push(s(l,24+8*e));let d=c.subarray(24+8*o);return{id:i,links:u,data:h(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=i(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),a=m(i.subarray(0,4)),c=i.length<24?0:s(h(i),8);switch(a){case`##DT`:case`##SD`:case`##RD`:return[{offset:t+24,length:c-24,zip:null}];case`##DZ`:{let e=h(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),a=s(e,8),c=s(e,16);if(a>o(c)||n===1&&i===0)throw Error(`This MF4 is damaged (bad compressed block at byte ${t}).`);if(n===1&&a>268435456)throw Error(`This MF4 has a compressed block over 256 MB, which Kymoscope cannot read.`);return[{offset:t+48,length:c,zip:{type:n,param:i,orgLength:a}}]}case`##DL`:{if(n>1)throw Error(`This MF4 is damaged (unexpected ${a} 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 ${a} 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 ${a} block in its data).`)}}async function ve(e,t,n){return t?m(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,a=i.getUint8(0),o=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(a===2||a===3)if(o===1)d=a===2?`master`:`vmaster`;else{if(r.push(`The master channel ${l} is not time (sync type ${o}): samples are numbered instead.`),a===3)return null;d=`value`}else if(a===1)d=`vlsd`;else if(a===0||a===4)d=`value`;else return r.push(`${l}: channel type ${a} is not supported; skipped.`),null;let f=await ye(e,t.links[4]),p=f.k===`text`?{...f,int:u.type!==`float`}:f,h=await k(e,t.links[6]);!h&&t.links[4]&&(h=await k(e,(await O(n,t.links[4])).links[1]));let g=null,_=null;d===`vlsd`&&t.links[5]&&(m(await n.read(t.links[5],4))===`##CG`?_=s((await O(n,t.links[5])).data,0):g=await A(e,t.links[5]));let v=i.getUint32(12,!0);return{name:l,unit:h,kind:d,...u,conv:p,sd:g,sdRecordId:_,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&&(m(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,a=i.getUint16(16,!0),o=0;t.links[3]&&(o=(await O(e.io,t.links[3])).data.getUint8(1));let c={name:await k(e,t.links[2]),dg:n,recordId:s(i,0),recordIdSize:r,idTrailer:0,dataBytes:i.getUint32(24,!0),invalBytes:i.getUint32(28,!0),cycles:s(i,8),vlsdCg:(a&1)!=0,sorted:!0,master:null,channels:[],stream:[],busType:o,busEvent:(a&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=s(n.data,0),i=(n.data.getUint8(12)&1)!=0,a=new Date(r/1e6).toISOString(),o=r>0?i?a.slice(0,-1):a: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:o,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=h(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,g=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]=g&&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 N(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 Le=65536,Re=`This file's compressed data is damaged.`;async function*ze(e){for(let t=0;t<e.length;t+=Le)yield e.subarray(t,t+Le)}async function*Be(e){if(typeof DecompressionStream!=`function`){let t=[],n=new ne(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(Re):e});if(e)return;yield t}}finally{r.cancel().catch(()=>{})}}async function P(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 Be(ze(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 Ve=new Uint8Array(Uint32Array.of(1).buffer)[0]===1;function He(e,t,n,r=t){let i=Math.floor(n/t),a=new Uint8Array(r<t?i*r:n),o=r%4==0&&Ve?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 Ue(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 We(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 P(i,s,r);let c=Math.min(n,o);return He(await P(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??We(e,s,r);a=i(t[o+1])?We(e,t[o+1],r):null,a?.catch(()=>{}),yield await n}else{let t=s.zip.orgLength;for await(let n of Be((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=Ue(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 N(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 L(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 yt(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(L(i,e.read[a],t,n,r),e=>o.get(e)??null):L(i,e.read[a],t,n,r,e.factor[a],e.offset[a])})}}var bt=e=>({key:e,skip:!0,frames:0,all:null,sw:null,byMux:new Map,idx:new Int32Array,cnt:0});function xt(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 St=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 Ct(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=L(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 wt=48e6;async function Tt(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(g(new Uint8Array(await n[0].arrayBuffer()))),o=[],s=new Map,c=new Map,l=0,u=new Ze(e,r);for(let[n,d]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 St(e=>{let t=a.get(e);if(!t){let t=bt(e);return s.set(e,t),t}let r=xt(t,f(t,null));return o.push({model:n,m:r}),r});d.data.sdRecordId!==null&&u.want(d.data.sdRecordId);let m=pt();for await(let o of tt(e,t,[n],u,r,_t(i,d,a))){let e=await mt(i,d,o.buf,o.n,o.start,o.size,u,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 Ct(e,p,t)){let t=yt(n,e);if(l<0)continue;if((l+=t.time.length*(1+t.cols.length))>wt){l=-1,c.clear();continue}let r=c.get(n);r||c.set(n,r=[]),r.push(t)}}}let d=[],f=new Map;for(let{model:e,m:t}of o)for(let n of[t.all,...t.byMux.values()]){if(!n)continue;let{route:t,n:r,t0:i,t1:o}=n;if(t.signals.length===0)continue;let s=a.get(t.key);l>=0&&f.set(t,c.get(n)??[]),d.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 p=[];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(`, `);p.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:d,notes:p,cache:f}}async function*Et(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 St(e=>{let t=u.get(e);if(!t)return bt(e);let n=xt(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 Ct(e,d,(e,t)=>u.get(e.key).byMux.get(t)??null)){let n=t.n,r=yt(t,e);yield{group:l.get(t),start:n,length:r.time.length,time:r.time,columns:r.cols}}}}var Dt=e=>Math.round(e*1e6)/1e6,Ot=e=>e.kind===`value`?e.type!==`bytes`:e.kind===`vlsd`&&e.type===`string`,kt=e=>({name:e.name,unit:e.unit,text:e.type===`string`||e.kind===`vlsd`||e.conv.k===`text`});async function At(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?Dt(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=Ue(t.stream.slice(0,1),r,N(t,[])),s=await We(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]?Dt((i-1)/(s[1]-s[0])):null}async function jt(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 Mt(e,t,n,r,i,a,o,s){let c=e.recordIdSize,l=[];for(let i of t)l.push(await jt(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*Nt(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*Et(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?N(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 Mt(n.model.groups[t.g],r,t.buf,t.n,t.start,t.size,e,a)}}function Pt(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 Ft={...f,async plan(e,t){let n=await t.read(0,64);if(C(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=m(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 Tt(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)=>{Ot(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=>kt(n.channels[e])),samples:n.cycles,time:n.master?{kind:`timestamps`}:{kind:`index`},rateHz:await At(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 Pt(e))yield*Nt(e,t)},streamGroup(e,t){return Nt(e,[t])}};function It(e){let t=[];for(let n of g(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 Lt(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 Rt=e=>`${+e.toFixed(6)} Hz`;function zt(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 Bt={...a,async plan(e,t){let n=await t.read(0,256),r=(e,t)=>m(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)=>m(d.subarray(e*a+t*n,e*a+t*(n+1))).trim(),p=i?3:2,h=[],g=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);h.push({label:f(0,16,e),unit:f(96,8,e),spr:a,offset:g,bit:o,off:n/o-i}),g+=a*p}let _=g;if(!(_>0&&o+_<=t.size))throw Error(`This EDF/BDF file is damaged (its data records do not fit in it).`);let v=Math.floor((t.size-o)/_),y=parseInt(r(236,8),10),b=[];y>=0?y>v&&(b.push(`The file is shorter than its header says: ${v} of ${y} data records were read.`),y=v):y=v;let x=c?h.flatMap((e,t)=>/^(EDF|BDF) Annotations$/.test(e.label)?[t]:[]):[],S=new Map;h.forEach((e,t)=>{!x.includes(t)&&e.spr>0&&S.set(e.spr,[...S.get(e.spr)??[],t])});let ee=[...S.values()],C=ee.map(e=>{let t=h[e[0]].spr/u;return{name:Rt(t),channels:e.map(e=>({name:h[e].label,unit:h[e].unit})),samples:y*h[e[0]].spr,rateHz:t,time:l?{kind:`timestamps`}:{kind:`rate`,rate:t,start:0}}}),te={headerBytes:o,records:y,duration:u,recordBytes:_,bps:p,signals:h,groups:ee,annotations:x,discontinuous:l};return{format:`${i?`BDF`:`EDF`}${c?l?`+D`:`+`:``}`,startTime:Lt(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 n=e.plan.state,r=Math.max(1,Math.floor(t/n.recordBytes)),i=e.selection.map(e=>({g:e.group,chans:e.channels.map(t=>n.signals[n.groups[e.group][t]]),spr:n.signals[n.groups[e.group][0]].spr})),a=i.map(()=>0),o=0,s=NaN;for await(let t of e.io.windows(n.headerBytes,n.records*n.recordBytes,r*n.recordBytes)){e.signal?.throwIfAborted();let r=Math.floor(t.bytes.length/n.recordBytes);if(r===0)break;let c=h(t.bytes),l=new Float64Array(r),u=[];for(let e=0;e<r;e++)l[e]=(o+e)*n.duration,n.annotations.forEach((r,i)=>{let a=n.signals[r],o=e*n.recordBytes+a.offset,s=It(t.bytes.subarray(o,o+a.spr*n.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(n.discontinuous)for(let e=0;e<r;e++){let t=e?l[e-1]+n.duration:s;t===t&&l[e]>t+1e-9&&(d[e]=1,f++)}for(let e=0;e<i.length;e++){let o=i[e],p=o.spr/n.duration,m=r*o.spr+f,h=n.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]+n.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*n.recordBytes;o.chans.forEach((e,i)=>zt(e,c,t.bytes,r+e.offset,o.spr,n.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]+n.duration,o+=r}}},R={float32:4,double64:8,int8:1,int16:2,int32:4,int64:8};function z(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 Vt(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 Ht=1e5,B=e=>e.fmt===`string`||R[e.fmt]!==void 0;function V(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]:[s(t,n+1),9];throw Error(`This XDF file is damaged (bad length field).`)}function Ut(e,t,n,r){if(n>=e.length)return-1;if(e[n++]===8&&(n+=8),r.fmt!==`string`)return n+R[r.fmt]*r.nch<=e.length?n+R[r.fmt]*r.nch:-1;for(let i=0;i<r.nch;i++){if(n>=e.length)return-1;let[r,i]=V(e,t,n);n+=i+r}return n<=e.length?n:-1}async function*Wt(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=h(i),s=0;for(;!(s+1>i.length);){let t=i[s];if(s+1+t>i.length)break;let[n,r]=V(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 Gt(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 Kt(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 qt(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)Gt(t,n,r);return Kt(t),[t.a-t.b*t.i0,t.b]}function Jt(e,t,n){let r=t.t0+t.a+t.b*(n-t.i0);return r+e.c0+e.c1*r}var Yt={...p,async plan(e,t){let n=new Map,r=``;for await(let e of Wt(t)){let t=h(e.body);if(e.tag===1)r=g(e.body);else if(e.tag===2){let r=t.getUint32(0,!0),i=g(e.body.subarray(4)),a=parseInt(z(i,`channel_count`),10)||1;if(!(a>=1&&a<=Ht))throw Error(`This XDF file is damaged (a stream with ${a} channels).`);let o=Vt(i,`channel`);n.set(r,{id:r,name:z(i,`name`)||`Stream ${r}`,nch:a,srate:parseFloat(z(i,`nominal_srate`))||0,fmt:z(i,`channel_format`)||`float32`,labels:Array.from({length:a},(e,t)=>z(o[t]??``,`label`)||`Ch${t+1}`),units:Array.from({length:a},(e,t)=>z(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||!B(r))continue;let[i,a]=V(e.body,t,4),o=4+a,s=R[r.fmt],c=r.srate>0?Math.max(1,500/r.srate):1/0;for(let n=0;n<i&&!(Ut(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]=V(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}),Gt(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=>(B(e)||i.push(`${e.name}: channel format ${e.fmt} is not supported; skipped.`),B(e))),o=1/0;for(let e of a){[e.c0,e.c1]=qt(e.clock);for(let t of e.segs)Kt(t);if(e.count===0)continue;let t=e.srate>0?Jt(e,e.segs[0],0):e.segs[0].t0+e.c0+e.c1*e.segs[0].t0;o=Math.min(o,t)}let s=b(a.map(e=>e.name),[]),c=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})),l=z(r,`version`);return{format:`XDF ${l||`1.0`}`,startTime:null,groups:c,meta:{header:l},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 Wt(e.io,e.signal)){if(i.tag!==3)continue;let e=h(i.body),o=r.get(e.getUint32(0,!0));if(!o)continue;let s=o.s,[c,l]=V(i.body,e,4),u=4+l,d=R[s.fmt],f=[];for(let r=0;r<c&&!(Ut(i.body,e,u,s)<0);r++){let r;i.body[u++]===8?(r=e.getFloat64(u,!0),u+=8):r=o.raw+(s.srate>0?1/s.srate:0),o.raw=r;let c;if(s.srate>0){for(;o.seg+1<s.segs.length&&s.segs[o.seg+1].i0<=o.i;)o.seg++;c=Jt(s,s.segs[o.seg],o.i)}else c=r+s.c0+s.c1*r;if(o.time[o.n]=c-t.origin,s.fmt===`string`){let n=[];for(let t=0;t<s.nch;t++){let[t,r]=V(i.body,e,u);n.push(g(i.body.subarray(u+r,u+r+t))),u+=r+t}o.sel.forEach((e,t)=>{o.cols[t][o.n]=n[e]}),f.push({time:c-t.origin,text:n.join(` `)})}else o.sel.forEach((t,n)=>{let r=u+t*d,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)}}),u+=d*s.nch;o.i++,++o.n===n&&(yield a(o))}f.length&&(yield{group:o.g,time:new Float64Array,start:o.start,length:0,columns:o.sel.map(()=>new Float64Array),events:f})}for(let e of r.values())e.n&&(yield a(e))}},Xt=2,Zt=8,Qt=4,$t=32,en=64,tn=4713,nn=4714,H=32,U=68,W={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},rn={0:5,1:1,2:6,3:2,4:7,5:3,6:8,7:4,8:9,9:10,4294967295:U},an=65536,on=65536,sn=(e,t,n)=>n?c(e,t+8,n)+s(e,t,n)/2**64:c(e,t,n)+s(e,t+8,n)/2**64;function cn(e,t,n,r,i){switch(r){case H:{let r=e.getUint32(n,i);return[g(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[c(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[s(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 U:return[sn(e,n,i),16];default:throw Error(`This TDMS file has a property of type ${r}, which Kymoscope cannot read.`)}}function ln(e){let t=/^\/'((?:[^']|'')*)'(?:\/'((?:[^']|'')*)')?$/.exec(e);return t?[t[1].replace(/''/g,`'`),(t[2]??``).replace(/''/g,`'`)]:null}var G=4294967295;function un(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 dn(e,t,n){let r=e.find(e=>un(e)>0);if(!r||r.get(`NI_Scaling_Status`)===`scaled`)return null;let i=(e,a)=>{if(e===G||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`)??G),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`)??G),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(un(r)-1,0)}var fn={1:Int8Array,2:Int16Array,3:Int32Array,5:Uint8Array,6:Uint16Array,7:Uint32Array,9:Float32Array,10:Float64Array,25:Float32Array,26:Float64Array,33:Uint8Array};function pn(e,t,n,r,i,a,o,l){let u=fn[e];if(u&&a&&r===W[e]&&(t.byteOffset+n)%r===0){o.set(new u(t.buffer,t.byteOffset+n,i),l);return}switch(e){case 1:for(let e=0;e<i;e++,n+=r)o[l+e]=t.getInt8(n);return;case 2:for(let e=0;e<i;e++,n+=r)o[l+e]=t.getInt16(n,a);return;case 3:for(let e=0;e<i;e++,n+=r)o[l+e]=t.getInt32(n,a);return;case 4:for(let e=0;e<i;e++,n+=r)o[l+e]=c(t,n,a);return;case 5:case 33:for(let e=0;e<i;e++,n+=r)o[l+e]=t.getUint8(n);return;case 6:for(let e=0;e<i;e++,n+=r)o[l+e]=t.getUint16(n,a);return;case 7:for(let e=0;e<i;e++,n+=r)o[l+e]=t.getUint32(n,a);return;case 8:for(let e=0;e<i;e++,n+=r)o[l+e]=s(t,n,a);return;case 9:case 25:for(let e=0;e<i;e++,n+=r)o[l+e]=t.getFloat32(n,a);return;case 10:case 26:for(let e=0;e<i;e++,n+=r)o[l+e]=t.getFloat64(n,a);return;case U:for(let e=0;e<i;e++,n+=r)o[l+e]=sn(t,n,a);return;default:o.fill(NaN,l,l+i)}}async function mn(e,t,n){let r=new Map,i=[],a=[],o=new Map,c=new Map,l=t??e,u=0,d=0;for(;u+28<=e.size&&d+28<=l.size;){let f=t?d:u,p=await l.read(f,28),m=h(p);if(!(p[0]===84&&p[1]===68&&p[2]===83&&(p[3]===109||p[3]===104)))throw Error(`This TDMS file is damaged (no segment lead-in where one should be).`);let _=m.getUint32(4,!0),v=!(_&en),y=s(m,12,v),b=s(m,20,v),x=y>=2**53?e.size:Math.min(e.size,u+28+y);if(b>x-u-28)throw Error(`This TDMS file is damaged (segment metadata longer than its segment).`);if(_&Xt){let e=await l.read(f+28,b),t=h(e);_&Qt&&(a=[],o=new Map);let i=0,u=t.getUint32(i,v);i+=4;for(let l=0;l<u;l++){let l=t.getUint32(i,v),u=g(e.subarray(i+4,i+4+l));i+=4+l;let d=ln(u),f=r.get(u);f||r.set(u,f={path:u,group:d?.[0]??``,name:d?.[1]??``,type:0,props:new Map,pieces:[],total:0});let p=t.getUint32(i,v);i+=4;let m=null;if(p===4294967295)m=null;else if(p===0)m=c.get(f)??null;else if(p===tn||p===nn){let e=s(t,i+8,v),r=t.getUint32(i+16,v),a=p===tn?20:17,o=i+20,c=rn[t.getUint32(o,v)]??0,l=t.getUint32(o+8,v);i=o+r*a;let u=t.getUint32(i,v);i+=4;let d=0;for(let e=0;e<u;e++)d+=t.getUint32(i+4*e,v);i+=4*u,p===nn?n.push(`${f.name}: DAQmx digital line data is not supported; skipped.`):(r>1&&n.push(`${f.name}: only the first of its ${r} DAQmx scalers is read.`),m={type:c,count:e,bytes:0,daqmx:{byteOffset:l,stride:d}})}else{let e=t.getUint32(i,v),n=s(t,i+8,v),r=e===H?s(t,i+16,v):n*(W[e]??0);i+=p-4,m={type:e,count:n,bytes:r,daqmx:null}}m&&(f.type=m.type,c.set(f,m));let h=t.getUint32(i,v);i+=4;for(let n=0;n<h;n++){let n=t.getUint32(i,v),r=g(e.subarray(i+4,i+4+n));i+=4+n;let a=t.getUint32(i,v);i+=4;let[o,s]=cn(t,e,i,a,v);f.props.set(r,o),i+=s}let _=o.get(f);_===void 0?o.set(f,a.push({obj:f,idx:m})-1):a[_].idx=m}}if(_&Zt){let e=u+28+b,t=a.filter(e=>e.idx&&e.idx.count>0),n=t.filter(e=>e.idx.daqmx),r=(_&$t)!==0,o=0,s=0;n.length?(s=n[0].idx.daqmx.stride,o=n[0].idx.count*s):r?(s=t.reduce((e,t)=>e+(W[t.idx.type]??0),0),o=(t[0]?.idx.count??0)*s):o=t.reduce((e,t)=>e+t.idx.bytes,0);let c=o>0?Math.floor((x-e)/o):0,l=i.push({rawStart:e,chunkSize:o,chunks:c,le:v})-1,d=0;for(let e of t){let t=e.idx,n=W[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:d,bytes:t.bytes,stride:r?s:n,type:t.type};t.daqmx||(d+=r?n:t.bytes),i.type===H?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((o-i.offset-n)/i.stride)+1):0)),e.obj.pieces.push(i),c&&(e.obj.total+=i.count*c)}}if(u=x,d+=28+b,x>=e.size)break}return{objs:[...r.values()],segments:i}}var hn={...n,async plan(e,t){let n=e.companions.find(e=>e.name.toLowerCase().endsWith(`.tdms_index`)),r=[],{objs:i,segments:a}=await mn(t,n?new S(n):null,r),o=i.find(e=>e.path===`/`)?.props,s=i.filter(e=>e.name&&e.total>0&&(e.type===H||W[e.type])),c=new Set(s);for(let e of i)e.name&&e.total>0&&!c.has(e)&&r.push(`${e.name}: TDMS data type ${e.type} is not supported; skipped.`);let l=s.map(e=>e.props.get(`wf_start_time`)).filter(e=>typeof e==`number`),u=l.reduce((e,t)=>Math.min(e,t),l.length?1/0:0),d=new Map;for(let e of s){let t=`${e.total}|${e.props.get(`wf_increment`)??``}`,n=d.get(e.group)??new Map,r=n.get(t);r?r.push(e):n.set(t,[e]),d.set(e.group,n)}let f=[],p=[];for(let[e,t]of d)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===U)??n.find(e=>e.type!==H&&/^(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-u:0):0;f.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===H})),samples:n[0].total,time:i?{kind:`rate`,rate:i,start:c}:a?{kind:`timestamps`}:{kind:`index`},rateHz:i}),p.push({channels:o,time:a,origin:0})}if(f.length===0)throw Error(`This TDMS file has no channels with data.`);let m=[];for(let e of p){if(!e.time)continue;let n=e.time.pieces[0],r=a[n.seg],i=await t.read(r.rawStart+n.offset,W[n.type]??8),o=new Float64Array(1);pn(n.type,h(i),0,0,1,r.le,o,0),m.push(o[0])}let g=m.reduce((e,t)=>Math.min(e,t),m.length?1/0:0);for(let e of p)e.origin=g;let _=new Date(Date.UTC(1904,0,1)+u*1e3),v=u&&Number.isFinite(_.getTime())?_.toISOString():null,y={objs:i,segments:a,groups:p},b={};for(let[e,t]of o??[])typeof t==`string`&&(b[e]=t);return{format:`TDMS`,startTime:v,groups:f,meta:b,events:[],notes:r,state:y}},async*stream(e){for(let t of e.selection)yield*_n(e,t.group)},streamGroup:(e,t)=>_n(e,t)};function gn(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===H)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+W[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*_n(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,c=s(`/`),l=a.map(e=>dn([e.props,s(`/'${e.group.replace(/'/g,`''`)}'`),c],[],e.name)),u=a.map(()=>({pi:0,chunk:0,row:0})),d=a.reduce((e,t)=>Math.min(e,t.total),1/0);for(let i=0;i<d;){e.signal?.throwIfAborted();let o=Math.min(an,d-i),s=[];a.forEach((e,t)=>gn(n,e,t,u[t],o,s));let c=s.slice().sort((e,t)=>e.at-t.at),f=[];for(let e of c){let t=f[f.length-1];t&&e.at<=t.end+on&&Math.max(t.end,e.end)-t.at<=16777216?t.end=Math.max(t.end,e.end):f.push({at:e.at,end:e.end}),e.range=f.length-1}let p=[];for(let t of f)p.push(await e.io.slice(t.at,t.end-t.at));let m=p.map(h),_=a.map(e=>e.type===H?Array(o).fill(null):new Float64Array(o).fill(NaN));for(let e of s){let t=e.at-f[e.range].at,n=e.piece;if(n.type===H){let r=p[e.range],i=m[e.range],a=t+4*n.count,o=_[e.ch];for(let n=0;n<e.rows;n++){let s=e.first+n,c=s===0?0:i.getUint32(t+4*(s-1),e.le),l=i.getUint32(t+4*s,e.le);o[e.out+n]=g(r.subarray(a+c,a+l))}}else pn(n.type,m[e.range],t,n.stride,e.rows,e.le,_[e.ch],e.out)}for(let e=0;e<a.length;e++){let t=l[e],n=_[e];if(t&&n instanceof Float64Array)for(let e=0;e<o;e++)n[e]=t(n[e])}let v=null;if(r.time){v=_.shift();for(let e=0;e<o;e++)v[e]-=r.origin}yield{group:t,time:v,start:i,length:o,columns:_},i+=o}}var vn=e=>!!e&&typeof e.keys==`function`,yn=1e5;function bn(){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<=yn,note:()=>t>1e5?`This file has more than ${yn.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 xn(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 Sn=e=>!!e&&typeof e.slice==`function`,Cn=null,K=null,wn=new WeakMap;function Tn(){!Cn||K||(K=Cn(),K.catch(()=>{K=null}))}function En(e){if(!Cn)return Promise.reject(Error(`HDF5 and MAT 7.3 files are read in the import worker, and this environment has no workers.`));Tn();let t=wn.get(e);return t||(t=K.then(t=>t(e)).then(e=>({root:e.root,close:()=>{}})),wn.set(e,t),t.catch(()=>wn.delete(e))),t}var Dn=new WeakMap;function q(e,t,n){let r=Dn.get(e);r||Dn.set(e,r=new Map);let i=r.get(t);return i||r.set(t,i=n??e.get(t)),i}function J(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 On={s:1,sec:1,second:1,seconds:1,ms:.001,msec:.001,us:1e-6,µs:1e-6,ns:1e-9};function Y(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 kn(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 An=0,jn=1,Mn=3,Nn=6,Pn=new Set([1,2,3,4,5,6]),Fn=/^(time|t|timestamps?|.*[_ ]time|time[_ ].*)$/i,In=[`sampling_rate`,`sample_rate`,`samplerate`,`sampleRate`,`fs`,`Fs`,`rate`];function Ln(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(vn(l))o<16&&a.enter(l)&&Ln(e,l,c,r,i,a,o+1);else if(Sn(l)){let t=q(e,c,l);r.push({path:c,parent:n,name:s,ds:t,attrs:t.attrs})}}}var X=e=>e===`/`?`root`:e.slice(1),Rn=e=>Math.max(4096,Math.min(1<<20,Math.floor((8<<20)/(8*Math.max(1,e)))));async function zn(e,t){let n=q(e,t.path);if(t.col===null)return J(n.slice([[0,1]]))[0]*t.factor;let r=n.slice([[0,1]]);return Number(r[0][t.col])*t.factor}var Bn={...u,async plan(e){let t=await En(e.main);try{let n=[],r=new Map,i=bn();i.enter(t.root),Ln(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=>!Pn.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(xn(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===An||r===jn||r===Mn)){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===An||r===jn)){let e=kn(t.attrs,...In);c.push({name:X(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===Nn){let e=(t.ds.metadata.compound_type?.members??[]).flatMap((e,n)=>e.type===An||e.type===jn?[{path:t.path,col:n,text:!1,factor:1,name:e.name}]:[]),r=e.find(e=>Fn.test(e.name));c.push({name:X(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=>Y(e.attrs,`CLASS`)===`DIMENSION_SCALE`)??e.leaves.find(e=>Fn.test(e.name)&&e.ds.metadata.type!==Mn),i=n?On[Y(n.attrs,`units`,`unit`,`Units`)]??1:1,a=n?null:kn(r.get(e.parent)??{},...In);c.push({name:t?`${X(e.parent)} (${e.n} rows)`:X(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===Mn,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 zn(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=>Y(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*Vn(e,t.group)},streamGroup:(e,t)=>Vn(e,t)};async function*Vn(e,t){let n=e.plan.state.groups[t],r=w(e,t).map(e=>n.cols[e]),i=await En(e.files.main);try{let a=n.chunk??0,o=a>0?Math.max(1,Math.min(Math.floor((1<<20)/a),Math.ceil(Rn(r.length+1)/a)))*a:Rn(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=q(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=J(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 Hn=/^(time|t|tout|timestamps?)$/i,Un=/^(fs|sample_?rate|sampling_?rate|rate|samplerate)$/i,Wn=e=>e.slice(e.lastIndexOf(`.`)+1),Gn=e=>e.includes(`.`)?e.slice(0,e.lastIndexOf(`.`)):``;function Kn(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 qn(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])=>Un.test(Wn(e))),a=i.length===1?i[0][1]:null,o=[];for(let[e,n]of r){let r=n.find(e=>Hn.test(Wn(e.name))||/(_time|\.Time)$/.test(e.name))??null;o.push({name:r?Gn(r.name)||r.name:`${e} samples`,channels:n.filter(e=>e!==r).map(e=>Kn(e,t)),time:r,rate:r?null:a,origin:0})}return o}function Jn(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 Yn(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 Xn=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(){}},Zn=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 P(await this.#e.slice(this.#t,this.#n),this.size,this.size),this.#r.subarray(e,e+t)}release(){this.keep||(this.#r=null)}},Z={1:1,2:1,3:2,4:2,5:4,6:4,7:4,9:8,12:8,13:8};function Qn(e,t,n,r,i=1){let a=h(t),o=r.length,s=Z[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 Q(e,t,n){let r=h(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 $n(e,t,n,r,i){let[a,o]=t,s=Z[r.type];if(!s)return[];let c=(e,t)=>async(a,o)=>{let c=new Float64Array(o-a);return t===1?Qn(r.type,await n.read(r.data+(e+a)*s,(o-a)*s),i,c):Qn(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 er(e,t,n,r,a,o,s){let c=t,l=await Q(e,c,n),u=h(await e.read(l.data,8)).getUint32(0,n),d=u&255;c=l.next;let f=await Q(e,c,n);if(f.bytes>128){o.notes.push(`A MAT variable with more than 32 dimensions was skipped (damaged).`);return}let p=h(await e.read(f.data,f.bytes)),_=Array.from({length:f.bytes/4},(e,t)=>p.getInt32(4*t,n));c=f.next;let v=await Q(e,c,n),y=m(await e.read(v.data,v.bytes));c=v.next;let b=a??y,x=r?`${r}.${b}`:b,S=_.reduce((e,t)=>e*t,1);if(d>=6&&d<=15){if(S===0)return;let t=await Q(e,c,n);if(u&2048&&o.notes.push(`${x}: the imaginary part was skipped.`),_.length>2){o.notes.push(`${x}: arrays with more than two dimensions are skipped.`);return}if(!Z[t.type])return;if(!(S>0)||S*Z[t.type]>t.bytes||t.data+t.bytes>e.size){o.notes.push(`${x}: its data is shorter than its dimensions (damaged); skipped.`);return}if(S===1){let r=new Float64Array(1);Qn(t.type,await e.read(t.data,Z[t.type]??8),n,r),o.scalars.set(x,r[0]);return}o.channels.push(...$n(x,_,e,t,n));return}if(d===4){let t=await Q(e,c,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)):g(r);_[0]<=1&&o.strings.set(x,i);return}if(d===2){let t=await Q(e,c,n),r=h(await e.read(t.data,4)).getInt32(0,n);c=t.next;let a=await Q(e,c,n);if(!(r>0))return;let l=await e.read(a.data,a.bytes),u=Array.from({length:Math.floor(l.length/r)},(e,t)=>i(l.subarray(t*r,(t+1)*r)));if(c=a.next,u.length===0||S*u.length*8>e.size-c){S>0&&u.length>0&&o.notes.push(`${x}: its fields are longer than the file (damaged); skipped.`);return}for(let t=0;t<S;t++){let r=S>1?`${x}(${t+1})`:x;for(let t of u){let i=await Q(e,c,n);i.type===14&&i.bytes>0&&s<16&&await er(e,i.data,n,r,t,o,s+1),c=i.next}}return}d===1?o.notes.push(`${x}: cell arrays are skipped.`):d===5?o.notes.push(`${x}: sparse arrays are skipped.`):o.notes.includes(nr)||o.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=m((await e.read(0,128)).subarray(126,128))===`IM`,n={channels:[],strings:new Map,scalars:new Map,notes:[],sources:[]},r=new Xn(e),i=0;for(let a=128;a+8<=e.size;){let s=await Q(r,a,t);if(s.type===15){if(s.bytes>1<<30)throw Error(`A compressed variable in this MAT file is over 1 GB; save it with -v7.3 to open it here.`);let r=await e.slice(s.data,s.bytes),a=await P(r,-1,8),c=a.length<8?0:8+h(a).getUint32(4,t);if(c>o(s.bytes))throw Error(`A compressed variable in this MAT file is damaged.`);if(c>1<<30)throw Error(`A compressed variable in this MAT file is over 1 GB; save it with -v7.3 to open it here.`);let l=await P(r,c,c),u=new Zn(e,s.data,s.bytes,l);n.sources.push(u),i+=l.length;let d=await Q(u,0,t);if(d.type===14&&await er(u,d.data,t,``,null,n,0),i>rr)for(let e of n.sources)e.keep=!1,e.release()}else s.type===14&&await er(r,s.data,t,``,null,n,0);a=s.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=bn();r.enter(e);let i=t=>q(e,t),a=(e,t,n)=>{let r=null;return(a,o)=>((r?.s!==a||r.e!==o)&&(r={s:a,e:o,v:J(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=Y(m,`MATLAB_class`);if(m.MATLAB_empty)continue;if(vn(d)){h===`struct`&&l<16&&r.enter(d)&&o(d,f,p,l+1);continue}if(!Sn(d))continue;let g=d.shape??[];if(h===`char`){if(g.reduce((e,t)=>e*t,1)>ar)continue;let e=J(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&&xn(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,J(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)=>J(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={...ae,async plan(e,t){let n=C(await t.read(0,20),`MATLAB 7.3`),r,i=[];if(n)r=sr((await En(e.main)).root,e.main.size);else{let e=await ir(t);i=e.sources,r=e}let a=qn(r.channels,r.strings,r.scalars).filter(e=>e.channels.length>0);await Yn(a);let o=Jn(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=m(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={...l,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=m(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 n=e.plan.state,{cfg:r}=n,i=n.data===`self`?e.io:new S(_r(e.files)),a=w(e,0),o=r.analog.length,s=r.rates[0][0]>0,c=r.timemult*r.timebase,l=65536,u=0,d=(e,t,n)=>{let i=new Float64Array(e);if(s)gr(r.rates,u,e,i);else for(let n=0;n<e;n++)i[n]=t[n]*c;let a={group:0,time:i,start:u,length:e,columns:n};return u+=e,a};if(r.ft===`ASCII`){let t=r.rev>=1999?`99999`:``,s=a.map(e=>e<o?r.analog[e]:null),c=new Float64Array(l),u=a.map(()=>new Float64Array(l)),f=0,p=(e,n,r)=>{let i=e.slice(n,r).split(`,`);if(!(i.length<2)){c[f]=Number(i[1]);for(let e=0;e<a.length;e++){let n=(i[2+a[e]]??``).trim(),r=s[e];u[e][f]=n===``||r&&n===t?NaN:r?r.a*Number(n)+r.b:Number(n)}f++}},m=``,h=new TextDecoder(`latin1`);for await(let t of i.windows(n.offset,n.length)){e.signal?.throwIfAborted();let n=m+h.decode(t.bytes),r=0;for(let e=n.indexOf(`
|
|
4
|
-
`,r);e>=0;e=n.indexOf(`
|
|
5
|
-
`,r))p(n,r,e),r=e+1,f===l&&(yield d(f,c,u),c=new Float64Array(l),u=a.map(()=>new Float64Array(l)),f=0);m=n.slice(r)}m.trim()&&p(m,0,m.length),f&&(yield d(f,c.slice(0,f),u.map(e=>e.slice(0,f))));return}let f=n.recordSize,p=pr[r.ft],m=Math.max(1,Math.floor(Math.min(t,l*f)/f)),g=n.samples;for await(let t of i.windows(n.offset,Math.min(n.length,n.samples*f),m*f)){e.signal?.throwIfAborted();let n=Math.min(g,Math.floor(t.bytes.length/f));if(n<=0)break;let i=h(t.bytes),c=new Float64Array(n);if(!s)for(let e=0;e<n;e++)c[e]=i.getUint32(e*f+4,!0);yield d(n,c,a.map(e=>{let t=new Float64Array(n);if(e<o){let{a,b:o}=r.analog[e],s=8+e*p;if(r.ft===`BINARY`)for(let e=0,r=s;e<n;e++,r+=f){let n=i.getInt16(r,!0);t[e]=n===-32768?NaN:a*n+o}else if(r.ft===`BINARY32`)for(let e=0,r=s;e<n;e++,r+=f){let n=i.getInt32(r,!0);t[e]=n===-2147483648?NaN:a*n+o}else for(let e=0,r=s;e<n;e++,r+=f)t[e]=a*i.getFloat32(r,!0)+o}else{let r=e-o,a=8+o*p+2*(r>>4),s=1<<(r&15);for(let e=0,r=a;e<n;e++,r+=f)t[e]=i.getUint16(r,!0)&s?1:0}return t})),g-=n}}var $=8192;async function*br(e){let t=0;for(;t+56<=e.size;){let n=ee(await e.read(t,56));if(yield await e.slice(t,n.bytes),n.bytes<=56)return;t+=n.bytes}}function xr(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 Sr=4096;function Cr(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 wr=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Tr=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*Er(e,t,n,i,a=!1){let o=te(e.keys??[]),s=new Map,c=new Map,l=i?null:new Tr,u=null,f=0,p=e=>l?(l.sampled(e.columns),e.t.length&&(u=+e.t[e.t.length-1],f=e.at),l.start(e)):e,m={results:[]};for await(let e of br(t)){let{header:t,messages:u}=v(e);if(n.t0??=t.t0,a){let e=t.recordingId;m.results.push({rid:e,check:await _(t,u,o,m.rid===e?(m.seq??-1)+1:0)}),m.rid=e,m.seq=t.seq,n.chain=y(m.results)}for(let e of u){let t=Cr(e.bytes),a=c.get(t);if(a&&wr(a,e.bytes))continue;c.set(t,e.bytes),c.size>Sr&&c.delete(c.keys().next().value);let u=await o(e.bytes);if(!u){n.lost++;continue}try{if(u.kind===5){let e=d(u.plaintext);s.set(e.id,e);continue}if(u.kind===4){let t=await ie(u.plaintext,s);if(!t){n.lost++;continue}let r={at:e.at,t:t.block.t,columns:t.block.columns,units:t.block.units??{},historical:t.historical};t.historical&&l?.sampled(r.columns),(i===void 0||i===!!t.historical)&&(yield t.historical?r:p(r));continue}if(i)continue;if(u.kind===7){let e=r(u.plaintext,s);e&&l?.note(e)}else if(u.kind===3){let t=re(u.plaintext);yield p({at:e.at,t:t.t,columns:t.columns,units:t.units??{}})}else if(u.kind===2){let t=x(u.plaintext);yield p({at:e.at,...xr(Array.isArray(t?.frames)?t.frames:[])})}}catch{n.lost++}}}let h=l?.end(u,f);h&&(yield h)}function Dr(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 Or={mdf:Ft,edf:Bt,xdf:Yt,tdms:hn,hdf5:Bn,mat:lr,comtrade:vr,krc:{id:`krc`,label:`Kymoscope recording`,extensions:[],sniff:()=>!1,async plan(t,n){let r=[e],i=new Map([[e,`s`]]),a={lost:0,t0:null},o=0,s=!1,c=null,l=null,u=0,d=-1/0,f=0,p=1/0;for await(let e of Er(t,n,a,void 0,!0)){o+=e.t.length,e.historical&&(s=!0);let t=e.t.length;t&&e.historical?l??=+e.t[0]:t&&(c??=+e.t[0],+e.t[0]+u<d&&(u=d+Math.max(0,(e.at-f)/1e3)-+e.t[0]),f=e.at,d=+e.t[t-1]+u,p=Math.min(p,e.at/1e3-d));for(let t of Object.keys(e.columns))t!==`ElapsedTime`&&(i.has(t)?!i.get(t)&&e.units[t]&&i.set(t,e.units[t]):(r.push(t),i.set(t,e.units[t]??``)))}let m=r.map(e=>({name:e,unit:i.get(e)??``})),h=a.lost?[`${a.lost} ${a.lost===1?`message`:`messages`} couldn't be opened with the keys this browser has.`]:[],g=a.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+(a.chain?.verified??0)} checked ${g+(a.chain?.verified??0)===1?`chunk`:`chunks`}).`),{format:`Kymoscope recording`,startTime:a.t0===null?null:new Date(a.t0).toISOString(),groups:[{name:`Recording`,channels:m,samples:o,time:{kind:`timestamps`},rateHz:null}],meta:{...Dr(c,l,p),...a.chain&&(a.chain.verified||a.chain.broken)?{chainVerified:String(a.chain.verified),chainBroken:String(a.chain.broken),chainUnchecked:String(a.chain.unchecked)}:{}},events:[],notes:h,state:{names:r,backlog:s}}},async*stream(t){let{names:n,backlog:r=!1}=t.plan.state,i=t.selection.find(e=>e.group===0)?.channels??[],a=new Map(i.map((e,t)=>[n[e],t])),o=a.get(e),s=()=>i.map(()=>new Float64Array($).fill(NaN)),c=new Float64Array($),l=s(),u=0,d=0,f=0,p=-1/0,m=0,h=null,g=()=>{let e={group:0,time:c.slice(0,u),start:d,length:u,columns:l.map(e=>e.slice(0,u))};return d+=u,u=0,c=new Float64Array($),l=s(),e};function*_(e){let t=e.t.length;for(let n=0;n<t;){let r=Math.min(t-n,$-u);for(let t=0;t<r;t++){let r=+e.t[n+t]+f;h??=r,c[u+t]=r-h}if(o!==void 0)for(let t=0;t<r;t++)l[o][u+t]=+e.t[n+t];for(let[t,i]of Object.entries(e.columns)){let e=t===`ElapsedTime`?void 0:a.get(t);if(e===void 0)continue;let o=l[e];if(i instanceof Float64Array||i instanceof Float32Array)o.set(i.subarray(n,n+r),u);else for(let e=0;e<r;e++)o[u+e]=+i[n+e]}u+=r,n+=r,u===$&&(yield g())}}let v=r?Er(t.files,t.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 e of Er(t.files,t.io,{lost:0,t0:null},r?!1:void 0)){if(t.signal?.aborted)return;let n=e.t.length;if(n!==0){for(+e.t[0]+f<p&&(f=p+Math.max(0,(e.at-m)/1e3)-+e.t[0]),m=e.at;b&&+b.t[0]<+e.t[0];b=await y())yield*_(b);yield*_(e),p=+e.t[n-1]+f}}for(;b&&!t.signal?.aborted;b=await y())yield*_(b);u>0&&(yield g())}}};function kr(e){let t=Or[e];if(!t)throw Error(`No importer for format ${e}.`);return t}export{kr as importerFor};
|