wpilog-parser 1.0.1

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/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # wpilog-parser
2
+
3
+ Read [WPILib data log (`.wpilog`)](https://docs.wpilib.org/en/stable/docs/software/telemetry/datalog.html) files in TypeScript & JavaScript.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install wpilog-parser
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { createReadStream } from 'node:fs';
15
+ import { Readable } from 'node:stream';
16
+ import { readRecords, decodeRecords } from 'wpilog-parser';
17
+
18
+ const stream = Readable.toWeb(createReadStream('./example.wpilog'));
19
+
20
+ for await (const record of decodeRecords(readRecords(stream))) {
21
+ console.log(record);
22
+ }
23
+ ```
24
+
25
+ ## Development
26
+
27
+ ```bash
28
+ vp install
29
+ vp test
30
+ vp pack
31
+ ```
@@ -0,0 +1,213 @@
1
+ //#region src/types.d.ts
2
+ /** The parsed WPILOG file header. */
3
+ type DataLogHeader = {
4
+ version: {
5
+ major: number;
6
+ minor: number;
7
+ };
8
+ extraHeader: string;
9
+ };
10
+ /** Control record types in the WPILOG format. */
11
+ declare enum ControlRecordType {
12
+ Start = 0,
13
+ Finish = 1,
14
+ SetMetadata = 2
15
+ }
16
+ /** A control record that starts a new entry. */
17
+ type StartControlRecord = {
18
+ controlRecordType: ControlRecordType.Start;
19
+ entryId: number;
20
+ entryName: string;
21
+ entryType: string;
22
+ entryMetadata: string;
23
+ };
24
+ /** A control record that finishes an entry. */
25
+ type FinishControlRecord = {
26
+ controlRecordType: ControlRecordType.Finish;
27
+ entryId: number;
28
+ };
29
+ /** A control record that sets metadata on an entry. */
30
+ type SetMetadataControlRecord = {
31
+ controlRecordType: ControlRecordType.SetMetadata;
32
+ entryId: number;
33
+ entryMetadata: string;
34
+ };
35
+ /** A control record payload (start, finish, or set metadata). */
36
+ type ControlRecordPayload = StartControlRecord | FinishControlRecord | SetMetadataControlRecord;
37
+ /** A raw (undecoded) data log record from the binary format. */
38
+ type RawRecord = {
39
+ entryId: number; /** Timestamp in microseconds. */
40
+ timestamp: bigint;
41
+ payload: Uint8Array;
42
+ };
43
+ /** Discriminated union tag for decoded record types. */
44
+ declare enum RecordType {
45
+ Control = "control",
46
+ Boolean = "boolean",
47
+ Int64 = "int64",
48
+ Float = "float",
49
+ Double = "double",
50
+ String = "string",
51
+ BooleanArray = "boolean[]",
52
+ Int64Array = "int64[]",
53
+ FloatArray = "float[]",
54
+ DoubleArray = "double[]",
55
+ StringArray = "string[]",
56
+ Struct = "struct",
57
+ StructArray = "struct[]",
58
+ Raw = "raw"
59
+ }
60
+ /** Decoded struct payload — a map of field names to values. */
61
+ type StructPayload = Map<string, number | boolean | bigint | string | StructPayload | number[] | boolean[] | bigint[] | StructPayload[]>;
62
+ /** A decoded data record (excludes control records). */
63
+ type DataRecord = Extract<DecodedRecord, {
64
+ name: string;
65
+ }>;
66
+ /** A decoded control record. */
67
+ type ControlRecord = Extract<DecodedRecord, {
68
+ type: RecordType.Control;
69
+ }>;
70
+ /** Type guard that narrows a {@link DecodedRecord} to a {@link DataRecord}. */
71
+ declare function isDataRecord(record: DecodedRecord): record is DataRecord;
72
+ /** A decoded data log record. */
73
+ type DecodedRecord = {
74
+ entryId: number; /** Timestamp in microseconds. */
75
+ timestamp: bigint;
76
+ } & ({
77
+ type: RecordType.Control;
78
+ payload: ControlRecordPayload;
79
+ } | ({
80
+ name: string;
81
+ metadata: string;
82
+ } & ({
83
+ type: RecordType.Raw;
84
+ payload: Uint8Array;
85
+ } | {
86
+ type: RecordType.Boolean;
87
+ payload: boolean;
88
+ } | {
89
+ type: RecordType.Int64;
90
+ payload: bigint;
91
+ } | {
92
+ type: RecordType.Float;
93
+ payload: number;
94
+ } | {
95
+ type: RecordType.Double;
96
+ payload: number;
97
+ } | {
98
+ type: RecordType.String;
99
+ payload: string;
100
+ } | {
101
+ type: RecordType.BooleanArray;
102
+ payload: boolean[];
103
+ } | {
104
+ type: RecordType.Int64Array;
105
+ payload: bigint[];
106
+ } | {
107
+ type: RecordType.FloatArray;
108
+ payload: number[];
109
+ } | {
110
+ type: RecordType.DoubleArray;
111
+ payload: number[];
112
+ } | {
113
+ type: RecordType.StringArray;
114
+ payload: string[];
115
+ } | {
116
+ type: RecordType.Struct;
117
+ structName: string;
118
+ payload: StructPayload;
119
+ } | {
120
+ type: RecordType.StructArray;
121
+ structName: string;
122
+ payload: StructPayload[];
123
+ })));
124
+ //#endregion
125
+ //#region src/read-records.d.ts
126
+ /** A raw record or control record yielded by {@link readRecords}. */
127
+ type ReadRecord = {
128
+ kind: 'header';
129
+ header: DataLogHeader;
130
+ } | {
131
+ kind: 'control';
132
+ entryId: number;
133
+ timestamp: bigint;
134
+ payload: ControlRecordPayload;
135
+ } | {
136
+ kind: 'data';
137
+ record: RawRecord;
138
+ };
139
+ /** Accepted input types for {@link readRecords}. */
140
+ type DataLogInput = ReadableStream<Uint8Array> | Uint8Array | ArrayBuffer;
141
+ /**
142
+ * Read raw WPILOG records from a byte stream.
143
+ *
144
+ * Yields a header record first, then control and data records in order.
145
+ * Data record payloads are not decoded — use {@link decodeRecords} for that.
146
+ */
147
+ declare function readRecords(input: DataLogInput): AsyncGenerator<ReadRecord>;
148
+ //#endregion
149
+ //#region src/decode-records.d.ts
150
+ /**
151
+ * Decode raw WPILOG records into typed values.
152
+ *
153
+ * Accepts the output of {@link readRecords} and yields fully decoded records,
154
+ * including struct decoding with dependency resolution.
155
+ */
156
+ declare function decodeRecords(records: AsyncIterable<ReadRecord>): AsyncGenerator<DecodedRecord>;
157
+ //#endregion
158
+ //#region src/struct-payload-to-json.d.ts
159
+ /** Convert a {@link StructPayload} Map to a plain JSON-compatible object. */
160
+ declare function structPayloadToJson(payload: StructPayload): object;
161
+ //#endregion
162
+ //#region src/catalog.d.ts
163
+ /** An entry definition from the WPILOG catalog. */
164
+ type CatalogEntry = {
165
+ entryId: number;
166
+ name: string;
167
+ type: string;
168
+ metadata: string;
169
+ };
170
+ /**
171
+ * Collect all entry definitions from a WPILOG record stream.
172
+ *
173
+ * Iterates through records, collecting Start control records.
174
+ * Data record bytes are still read from the stream but not decoded,
175
+ * making this much cheaper than full decoding via {@link decodeRecords}.
176
+ */
177
+ declare function catalogEntries(records: AsyncIterable<ReadRecord>): AsyncGenerator<CatalogEntry, void, never>;
178
+ //#endregion
179
+ //#region src/struct/types.d.ts
180
+ declare enum KnownStructTypeName {
181
+ Boolean = "bool",
182
+ Character = "char",
183
+ Int8 = "int8",
184
+ Int16 = "int16",
185
+ Int32 = "int32",
186
+ Int64 = "int64",
187
+ Uint8 = "uint8",
188
+ Uint16 = "uint16",
189
+ Uint32 = "uint32",
190
+ Uint64 = "uint64",
191
+ Float32 = "float32",
192
+ /** Equivalent to {@link KnownStructTypeName.Float32} */
193
+ Float = "float",
194
+ Float64 = "float64",
195
+ /** Equivalent to {@link KnownStructTypeName.Float64} */
196
+ Double = "double"
197
+ }
198
+ type StructTypeName = KnownStructTypeName | string;
199
+ type EnumSpecification = Map<string, bigint>;
200
+ type StructSpecification = StructDeclaration[];
201
+ type StructDeclaration = {
202
+ name: string;
203
+ value: StructTypeName;
204
+ enumSpecification?: EnumSpecification;
205
+ arraySize?: number;
206
+ bitWidth?: number;
207
+ };
208
+ //#endregion
209
+ //#region src/struct/parse-struct.d.ts
210
+ /** Parse a WPILib struct specification string into declarations. */
211
+ declare function parseStructSpecification(declaration: string): StructDeclaration[];
212
+ //#endregion
213
+ export { type CatalogEntry, type ControlRecord, type ControlRecordPayload, ControlRecordType, type DataLogHeader, type DataLogInput, type DataRecord, type DecodedRecord, type EnumSpecification, type FinishControlRecord, KnownStructTypeName, type RawRecord, type ReadRecord, RecordType, type SetMetadataControlRecord, type StartControlRecord, type StructDeclaration, type StructPayload, type StructSpecification, type StructTypeName, catalogEntries, decodeRecords, isDataRecord, parseStructSpecification, readRecords, structPayloadToJson };
package/dist/index.mjs ADDED
@@ -0,0 +1,1115 @@
1
+ import { CstParser, Lexer, createToken } from "chevrotain";
2
+ //#region src/byte-offset.ts
3
+ var ByteOffset = class {
4
+ constructor(offset = 0) {
5
+ this.offset = offset;
6
+ }
7
+ get() {
8
+ return this.offset;
9
+ }
10
+ advance(bytes) {
11
+ this.offset += bytes;
12
+ return this;
13
+ }
14
+ advance8() {
15
+ return this.advance(1);
16
+ }
17
+ advance16() {
18
+ return this.advance(2);
19
+ }
20
+ advance32() {
21
+ return this.advance(4);
22
+ }
23
+ advance64() {
24
+ return this.advance(8);
25
+ }
26
+ };
27
+ //#endregion
28
+ //#region src/input-stream.ts
29
+ var StreamFinishedError = class extends Error {
30
+ constructor(bytesRead) {
31
+ super(`Reached end of stream after reading ${bytesRead} bytes`);
32
+ }
33
+ };
34
+ var InputStream = class {
35
+ reader;
36
+ bytesRead = 0;
37
+ buffer = new Uint8Array();
38
+ constructor(stream) {
39
+ this.reader = stream.getReader();
40
+ }
41
+ async readBytesAndAdvance(length) {
42
+ while (this.buffer.byteLength < length) {
43
+ const chunk = await this.reader.read();
44
+ if (chunk.done) throw new StreamFinishedError(this.bytesRead);
45
+ const newBuffer = new Uint8Array(this.buffer.byteLength + chunk.value.byteLength);
46
+ newBuffer.set(this.buffer);
47
+ newBuffer.set(chunk.value, this.buffer.byteLength);
48
+ this.buffer = newBuffer;
49
+ }
50
+ return this.readAndAdvanceFromBuffer(length);
51
+ }
52
+ readAndAdvanceFromBuffer(length) {
53
+ const result = this.buffer.slice(0, length);
54
+ this.buffer = this.buffer.slice(length);
55
+ this.bytesRead += length;
56
+ return result;
57
+ }
58
+ };
59
+ //#endregion
60
+ //#region src/types.ts
61
+ /** Control record types in the WPILOG format. */
62
+ let ControlRecordType = /* @__PURE__ */ function(ControlRecordType) {
63
+ ControlRecordType[ControlRecordType["Start"] = 0] = "Start";
64
+ ControlRecordType[ControlRecordType["Finish"] = 1] = "Finish";
65
+ ControlRecordType[ControlRecordType["SetMetadata"] = 2] = "SetMetadata";
66
+ return ControlRecordType;
67
+ }({});
68
+ /** Discriminated union tag for decoded record types. */
69
+ let RecordType = /* @__PURE__ */ function(RecordType) {
70
+ RecordType["Control"] = "control";
71
+ RecordType["Boolean"] = "boolean";
72
+ RecordType["Int64"] = "int64";
73
+ RecordType["Float"] = "float";
74
+ RecordType["Double"] = "double";
75
+ RecordType["String"] = "string";
76
+ RecordType["BooleanArray"] = "boolean[]";
77
+ RecordType["Int64Array"] = "int64[]";
78
+ RecordType["FloatArray"] = "float[]";
79
+ RecordType["DoubleArray"] = "double[]";
80
+ RecordType["StringArray"] = "string[]";
81
+ RecordType["Struct"] = "struct";
82
+ RecordType["StructArray"] = "struct[]";
83
+ RecordType["Raw"] = "raw";
84
+ return RecordType;
85
+ }({});
86
+ /** Type guard that narrows a {@link DecodedRecord} to a {@link DataRecord}. */
87
+ function isDataRecord(record) {
88
+ return record.type !== RecordType.Control;
89
+ }
90
+ //#endregion
91
+ //#region src/read-records.ts
92
+ const TEXT_ENCODER = new TextEncoder();
93
+ const TEXT_DECODER$1 = new TextDecoder();
94
+ const MAGIC = TEXT_ENCODER.encode("WPILOG");
95
+ async function readHeader(buffer) {
96
+ const magic = await buffer.readBytesAndAdvance(MAGIC.byteLength);
97
+ for (let i = 0; i < MAGIC.byteLength; i++) if (magic[i] !== MAGIC[i]) throw new Error("Not a WPILOG file (invalid magic bytes)");
98
+ const chunk = await buffer.readBytesAndAdvance(6);
99
+ const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
100
+ const versionMinor = view.getUint8(0);
101
+ const versionMajor = view.getUint8(1);
102
+ const extraHeaderLength = view.getUint32(2, true);
103
+ const extraHeader = await buffer.readBytesAndAdvance(extraHeaderLength);
104
+ return {
105
+ version: {
106
+ major: versionMajor,
107
+ minor: versionMinor
108
+ },
109
+ extraHeader: TEXT_DECODER$1.decode(extraHeader)
110
+ };
111
+ }
112
+ async function readRecordHeaderLength(buffer) {
113
+ const chunk = await buffer.readBytesAndAdvance(1);
114
+ const bitfield = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength).getUint8(0);
115
+ return {
116
+ entryIdLength: 1 + (bitfield & 3),
117
+ payloadSizeLength: 1 + (bitfield >> 2 & 3),
118
+ timestampLength: 1 + (bitfield >> 4 & 7)
119
+ };
120
+ }
121
+ async function readVarInt(buffer, length) {
122
+ const chunk = await buffer.readBytesAndAdvance(length);
123
+ const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
124
+ switch (length) {
125
+ case 1: return view.getUint8(0);
126
+ case 2: return view.getUint16(0, true);
127
+ case 3: return view.getUint8(2) << 16 | view.getUint8(1) << 8 | view.getUint8(0);
128
+ case 4: return view.getUint32(0, true);
129
+ default: throw new RangeError(`Invalid varint length ${length}`);
130
+ }
131
+ }
132
+ async function readTimestamp(buffer, length) {
133
+ const chunk = await buffer.readBytesAndAdvance(length);
134
+ const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
135
+ switch (length) {
136
+ case 1: return BigInt(view.getUint8(0));
137
+ case 2: return BigInt(view.getUint16(0, true));
138
+ case 3: {
139
+ const b0 = BigInt(view.getUint8(0));
140
+ const b1 = BigInt(view.getUint8(1));
141
+ return BigInt(view.getUint8(2)) << 16n | b1 << 8n | b0;
142
+ }
143
+ case 4: return BigInt(view.getUint32(0, true));
144
+ case 5: {
145
+ const b0 = BigInt(view.getUint8(0));
146
+ const b1 = BigInt(view.getUint8(1));
147
+ const b2 = BigInt(view.getUint8(2));
148
+ const b3 = BigInt(view.getUint8(3));
149
+ return BigInt(view.getUint8(4)) << 32n | b3 << 24n | b2 << 16n | b1 << 8n | b0;
150
+ }
151
+ case 6: {
152
+ const b0 = BigInt(view.getUint8(0));
153
+ const b1 = BigInt(view.getUint8(1));
154
+ const b2 = BigInt(view.getUint8(2));
155
+ const b3 = BigInt(view.getUint8(3));
156
+ const b4 = BigInt(view.getUint8(4));
157
+ return BigInt(view.getUint8(5)) << 40n | b4 << 32n | b3 << 24n | b2 << 16n | b1 << 8n | b0;
158
+ }
159
+ case 7: {
160
+ const b0 = BigInt(view.getUint8(0));
161
+ const b1 = BigInt(view.getUint8(1));
162
+ const b2 = BigInt(view.getUint8(2));
163
+ const b3 = BigInt(view.getUint8(3));
164
+ const b4 = BigInt(view.getUint8(4));
165
+ const b5 = BigInt(view.getUint8(5));
166
+ return BigInt(view.getUint8(6)) << 48n | b5 << 40n | b4 << 32n | b3 << 24n | b2 << 16n | b1 << 8n | b0;
167
+ }
168
+ case 8: return view.getBigUint64(0, true);
169
+ default: throw new RangeError(`Invalid timestamp length ${length}`);
170
+ }
171
+ }
172
+ function readControlRecordPayload(payload) {
173
+ const offset = new ByteOffset();
174
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
175
+ const type = view.getUint8(offset.get());
176
+ offset.advance8();
177
+ switch (type) {
178
+ case ControlRecordType.Start: {
179
+ const entryId = view.getUint32(offset.get(), true);
180
+ offset.advance32();
181
+ const entryNameLength = view.getUint32(offset.get(), true);
182
+ offset.advance32();
183
+ const entryName = TEXT_DECODER$1.decode(payload.subarray(offset.get(), offset.get() + entryNameLength));
184
+ offset.advance(entryNameLength);
185
+ const entryTypeLength = view.getUint32(offset.get(), true);
186
+ offset.advance32();
187
+ const entryType = TEXT_DECODER$1.decode(payload.subarray(offset.get(), offset.get() + entryTypeLength));
188
+ offset.advance(entryTypeLength);
189
+ const entryMetadataLength = view.getUint32(offset.get(), true);
190
+ offset.advance32();
191
+ const entryMetadata = TEXT_DECODER$1.decode(payload.subarray(offset.get(), offset.get() + entryMetadataLength));
192
+ offset.advance(entryMetadataLength);
193
+ return {
194
+ controlRecordType: type,
195
+ entryId,
196
+ entryName,
197
+ entryType,
198
+ entryMetadata
199
+ };
200
+ }
201
+ case ControlRecordType.Finish: {
202
+ const entryId = view.getUint32(offset.get(), true);
203
+ offset.advance32();
204
+ return {
205
+ controlRecordType: type,
206
+ entryId
207
+ };
208
+ }
209
+ case ControlRecordType.SetMetadata: {
210
+ const entryId = view.getUint32(offset.get(), true);
211
+ offset.advance32();
212
+ const entryMetadataLength = view.getUint32(offset.get(), true);
213
+ offset.advance32();
214
+ const entryMetadata = TEXT_DECODER$1.decode(payload.subarray(offset.get(), offset.get() + entryMetadataLength));
215
+ offset.advance(entryMetadataLength);
216
+ return {
217
+ controlRecordType: type,
218
+ entryId,
219
+ entryMetadata
220
+ };
221
+ }
222
+ default: throw new RangeError(`Invalid control record type ${type}`);
223
+ }
224
+ }
225
+ function toReadableStream(input) {
226
+ if (input instanceof ReadableStream) return input;
227
+ return new Blob([input]).stream();
228
+ }
229
+ /**
230
+ * Read raw WPILOG records from a byte stream.
231
+ *
232
+ * Yields a header record first, then control and data records in order.
233
+ * Data record payloads are not decoded — use {@link decodeRecords} for that.
234
+ */
235
+ async function* readRecords(input) {
236
+ const inputStream = new InputStream(toReadableStream(input));
237
+ yield {
238
+ kind: "header",
239
+ header: await readHeader(inputStream)
240
+ };
241
+ while (true) {
242
+ let headerLength;
243
+ try {
244
+ headerLength = await readRecordHeaderLength(inputStream);
245
+ } catch (error) {
246
+ if (error instanceof StreamFinishedError) return;
247
+ throw error;
248
+ }
249
+ const entryId = await readVarInt(inputStream, headerLength.entryIdLength);
250
+ const payloadSize = await readVarInt(inputStream, headerLength.payloadSizeLength);
251
+ const timestamp = await readTimestamp(inputStream, headerLength.timestampLength);
252
+ const payload = await inputStream.readBytesAndAdvance(payloadSize);
253
+ if (entryId === 0) yield {
254
+ kind: "control",
255
+ entryId,
256
+ timestamp,
257
+ payload: readControlRecordPayload(payload)
258
+ };
259
+ else yield {
260
+ kind: "data",
261
+ record: {
262
+ entryId,
263
+ timestamp,
264
+ payload
265
+ }
266
+ };
267
+ }
268
+ }
269
+ //#endregion
270
+ //#region src/struct/types.ts
271
+ let KnownStructTypeName = /* @__PURE__ */ function(KnownStructTypeName) {
272
+ KnownStructTypeName["Boolean"] = "bool";
273
+ KnownStructTypeName["Character"] = "char";
274
+ KnownStructTypeName["Int8"] = "int8";
275
+ KnownStructTypeName["Int16"] = "int16";
276
+ KnownStructTypeName["Int32"] = "int32";
277
+ KnownStructTypeName["Int64"] = "int64";
278
+ KnownStructTypeName["Uint8"] = "uint8";
279
+ KnownStructTypeName["Uint16"] = "uint16";
280
+ KnownStructTypeName["Uint32"] = "uint32";
281
+ KnownStructTypeName["Uint64"] = "uint64";
282
+ KnownStructTypeName["Float32"] = "float32";
283
+ /** Equivalent to {@link KnownStructTypeName.Float32} */
284
+ KnownStructTypeName["Float"] = "float";
285
+ KnownStructTypeName["Float64"] = "float64";
286
+ /** Equivalent to {@link KnownStructTypeName.Float64} */
287
+ KnownStructTypeName["Double"] = "double";
288
+ return KnownStructTypeName;
289
+ }({});
290
+ //#endregion
291
+ //#region src/struct/struct-dependency-graph.ts
292
+ const EMPTY_SET = /* @__PURE__ */ new Set();
293
+ var StructDependencyGraph = class {
294
+ allDependencies = new Map(Object.values(KnownStructTypeName).map((type) => [type, EMPTY_SET]));
295
+ registerSchema(name, innerStructNames) {
296
+ const existing = this.allDependencies.get(name);
297
+ if (existing) for (const innerStructName of innerStructNames) existing.add(innerStructName);
298
+ else this.allDependencies.set(name, new Set(innerStructNames));
299
+ if (this.hasCycle(name)) throw new RangeError(`Cycle detected in the dependency graph for ${name}`);
300
+ }
301
+ hasCycle(current, path = /* @__PURE__ */ new Set()) {
302
+ if (path.has(current)) return true;
303
+ path.add(current);
304
+ const directDependencies = this.allDependencies.get(current);
305
+ if (directDependencies) {
306
+ for (const dep of directDependencies) if (this.hasCycle(dep, path)) return true;
307
+ }
308
+ path.delete(current);
309
+ return false;
310
+ }
311
+ getDependencies(name) {
312
+ const result = /* @__PURE__ */ new Set();
313
+ const queue = [name];
314
+ while (queue.length > 0) {
315
+ const current = queue.pop();
316
+ if (result.has(current)) continue;
317
+ result.add(current);
318
+ const dependencies = this.allDependencies.get(current);
319
+ if (dependencies) queue.push(...dependencies);
320
+ }
321
+ return result;
322
+ }
323
+ getDecodableStructs() {
324
+ const result = [];
325
+ for (const structName of this.allDependencies.keys()) {
326
+ const dependencies = this.getDependencies(structName);
327
+ let allResolved = true;
328
+ for (const dep of dependencies) if (!this.allDependencies.has(dep)) {
329
+ allResolved = false;
330
+ break;
331
+ }
332
+ if (allResolved) result.push(structName);
333
+ }
334
+ return result;
335
+ }
336
+ };
337
+ //#endregion
338
+ //#region src/struct/struct-decode-queue.ts
339
+ var StructDecodeQueue = class {
340
+ graph = new StructDependencyGraph();
341
+ queuedRecords = /* @__PURE__ */ new Map();
342
+ constructor(onStructDefined) {
343
+ this.onStructDefined = onStructDefined;
344
+ }
345
+ queueStructRecord(structName, record) {
346
+ const existing = this.queuedRecords.get(structName);
347
+ if (existing) existing.push(record);
348
+ else this.queuedRecords.set(structName, [record]);
349
+ }
350
+ registerSchema(structName, innerStructNames) {
351
+ this.graph.registerSchema(structName, innerStructNames);
352
+ this.checkDecodableStructs();
353
+ }
354
+ checkDecodableStructs() {
355
+ for (const structName of this.graph.getDecodableStructs()) {
356
+ const records = this.queuedRecords.get(structName);
357
+ if (records) {
358
+ this.onStructDefined(structName, records);
359
+ this.queuedRecords.delete(structName);
360
+ }
361
+ }
362
+ }
363
+ };
364
+ //#endregion
365
+ //#region src/struct/lexer.ts
366
+ const Comma = createToken({
367
+ name: "Comma",
368
+ pattern: ","
369
+ });
370
+ const Semicolon = createToken({
371
+ name: "Semicolon",
372
+ pattern: ";"
373
+ });
374
+ const Colon = createToken({
375
+ name: "Colon",
376
+ pattern: ":"
377
+ });
378
+ const Equals = createToken({
379
+ name: "Equals",
380
+ pattern: "="
381
+ });
382
+ const WhiteSpace = createToken({
383
+ name: "WhiteSpace",
384
+ pattern: /\s+/
385
+ });
386
+ const Integer = createToken({
387
+ name: "Integer",
388
+ pattern: /0|[1-9]\d*/
389
+ });
390
+ const LeftSquareBrace = createToken({
391
+ name: "LeftSquareBrace",
392
+ pattern: "["
393
+ });
394
+ const RightSquareBrace = createToken({
395
+ name: "RightSquareBrace",
396
+ pattern: "]"
397
+ });
398
+ const EnumKeyword = createToken({
399
+ name: "EnumKeyword",
400
+ pattern: "enum"
401
+ });
402
+ const LeftCurlyBrace = createToken({
403
+ name: "LeftCurlyBrace",
404
+ pattern: "{"
405
+ });
406
+ const RightCurlyBrace = createToken({
407
+ name: "RightCurlyBrace",
408
+ pattern: "}"
409
+ });
410
+ const Identifier = createToken({
411
+ name: "Identifier",
412
+ pattern: /\w+/
413
+ });
414
+ const allTokens = [
415
+ WhiteSpace,
416
+ Semicolon,
417
+ Equals,
418
+ Comma,
419
+ Colon,
420
+ Integer,
421
+ LeftSquareBrace,
422
+ RightSquareBrace,
423
+ EnumKeyword,
424
+ LeftCurlyBrace,
425
+ RightCurlyBrace,
426
+ Identifier
427
+ ];
428
+ const lexer = new Lexer(allTokens);
429
+ //#endregion
430
+ //#region src/struct/parser.ts
431
+ var StructParser = class extends CstParser {
432
+ structSpecification = this.RULE("structSpecification", () => {
433
+ this.MANY_SEP({
434
+ SEP: Semicolon,
435
+ DEF: () => this.OPTION(() => this.SUBRULE(this.declaration))
436
+ });
437
+ });
438
+ declaration = this.RULE("declaration", () => {
439
+ this.OPTION(() => this.SUBRULE(this.enumSpecification));
440
+ this.SUBRULE(this.optionalWhitespace);
441
+ this.CONSUME(Identifier);
442
+ this.SUBRULE1(this.optionalWhitespace);
443
+ this.CONSUME1(Identifier);
444
+ this.OPTION1(() => this.OR({ DEF: [{ ALT: () => this.SUBRULE(this.bitFieldDeclaration) }, { ALT: () => this.SUBRULE(this.standardDeclarationArray) }] }));
445
+ });
446
+ standardDeclarationArray = this.RULE("standardDeclarationArray", () => {
447
+ this.SUBRULE(this.optionalWhitespace);
448
+ this.SUBRULE(this.arraySize);
449
+ });
450
+ bitFieldDeclaration = this.RULE("bitFieldDeclaration", () => {
451
+ this.SUBRULE(this.optionalWhitespace);
452
+ this.CONSUME(Colon);
453
+ this.SUBRULE1(this.optionalWhitespace);
454
+ this.CONSUME(Integer);
455
+ });
456
+ arraySize = this.RULE("arraySize", () => {
457
+ this.CONSUME(LeftSquareBrace);
458
+ this.SUBRULE(this.optionalWhitespace);
459
+ this.CONSUME(Integer);
460
+ this.SUBRULE1(this.optionalWhitespace);
461
+ this.CONSUME(RightSquareBrace);
462
+ });
463
+ enumSpecification = this.RULE("enumSpecification", () => {
464
+ this.OPTION(() => this.CONSUME(EnumKeyword));
465
+ this.SUBRULE(this.optionalWhitespace);
466
+ this.CONSUME(LeftCurlyBrace);
467
+ this.MANY_SEP({
468
+ SEP: Comma,
469
+ DEF: () => this.SUBRULE(this.enumMember)
470
+ });
471
+ this.SUBRULE1(this.optionalWhitespace);
472
+ this.CONSUME(RightCurlyBrace);
473
+ });
474
+ enumMember = this.RULE("enumMember", () => {
475
+ this.SUBRULE(this.optionalWhitespace);
476
+ this.CONSUME(Identifier);
477
+ this.SUBRULE1(this.optionalWhitespace);
478
+ this.CONSUME(Equals);
479
+ this.SUBRULE2(this.optionalWhitespace);
480
+ this.CONSUME(Integer);
481
+ this.SUBRULE3(this.optionalWhitespace);
482
+ });
483
+ optionalWhitespace = this.RULE("optionalWhitespace", () => {
484
+ this.OPTION(() => this.CONSUME(WhiteSpace));
485
+ });
486
+ constructor() {
487
+ super(allTokens);
488
+ this.performSelfAnalysis();
489
+ }
490
+ };
491
+ const parser = new StructParser();
492
+ parser.getBaseCstVisitorConstructor();
493
+ const BaseStructVisitorWithDefaults = parser.getBaseCstVisitorConstructorWithDefaults();
494
+ //#endregion
495
+ //#region src/struct/struct-ast-visitor.ts
496
+ var StructAstVisitor = class extends BaseStructVisitorWithDefaults {
497
+ constructor() {
498
+ super();
499
+ this.validateVisitor();
500
+ }
501
+ structSpecification(children) {
502
+ return children.declaration?.map((declaration) => this.declaration(declaration.children)) ?? [];
503
+ }
504
+ declaration(children) {
505
+ const [typeName, name] = children.Identifier;
506
+ const enumSpecification = children.enumSpecification ? this.enumSpecification(children.enumSpecification[0].children, typeName.image) : void 0;
507
+ const arraySize = children.standardDeclarationArray ? this.standardDeclarationArray(children.standardDeclarationArray[0].children) : void 0;
508
+ const bitWidth = children.bitFieldDeclaration ? this.bitFieldDeclaration(children.bitFieldDeclaration[0].children, typeName.image) : void 0;
509
+ return {
510
+ name: name.image,
511
+ value: typeName.image,
512
+ enumSpecification,
513
+ arraySize,
514
+ bitWidth
515
+ };
516
+ }
517
+ enumSpecification(children, dataType) {
518
+ switch (dataType) {
519
+ case KnownStructTypeName.Int8:
520
+ case KnownStructTypeName.Uint8:
521
+ case KnownStructTypeName.Int16:
522
+ case KnownStructTypeName.Uint16:
523
+ case KnownStructTypeName.Int32:
524
+ case KnownStructTypeName.Uint32:
525
+ case KnownStructTypeName.Int64:
526
+ case KnownStructTypeName.Uint64: break;
527
+ default: throw new RangeError("Enums must be integers");
528
+ }
529
+ const entries = children.enumMember?.map((member) => this.enumMember(member.children));
530
+ return new Map(entries);
531
+ }
532
+ enumMember(children) {
533
+ const [name] = children.Identifier;
534
+ const [value] = children.Integer;
535
+ return [name.image, BigInt(value.image)];
536
+ }
537
+ bitFieldDeclaration(children, dataType) {
538
+ const [value] = children.Integer;
539
+ const parsed = Number(value.image);
540
+ switch (dataType) {
541
+ case KnownStructTypeName.Boolean:
542
+ if (parsed !== 1) throw new RangeError("Boolean bit-field members must be 1 bit");
543
+ break;
544
+ case KnownStructTypeName.Int8:
545
+ case KnownStructTypeName.Uint8:
546
+ if (parsed > 8) throw new RangeError("8-bit bit-field members must be less than 8 bits");
547
+ break;
548
+ case KnownStructTypeName.Int16:
549
+ case KnownStructTypeName.Uint16:
550
+ if (parsed > 16) throw new RangeError("16-bit bit-field members must be less than 16 bits");
551
+ break;
552
+ case KnownStructTypeName.Int32:
553
+ case KnownStructTypeName.Uint32:
554
+ if (parsed > 32) throw new RangeError("32-bit bit-field members must be less than 32 bits");
555
+ break;
556
+ case KnownStructTypeName.Int64:
557
+ case KnownStructTypeName.Uint64:
558
+ if (parsed > 64) throw new RangeError("64-bit bit-field members must be less than 64 bits");
559
+ break;
560
+ default: throw new RangeError("Bit-field members must be integers or booleans");
561
+ }
562
+ return parsed;
563
+ }
564
+ standardDeclarationArray(children) {
565
+ return this.arraySize(children.arraySize[0].children);
566
+ }
567
+ arraySize(children) {
568
+ const [value] = children.Integer;
569
+ return Number(value.image);
570
+ }
571
+ };
572
+ //#endregion
573
+ //#region src/struct/parse-struct.ts
574
+ const structAstVisitor = new StructAstVisitor();
575
+ const cache = /* @__PURE__ */ new Map();
576
+ /** Parse a WPILib struct specification string into declarations. */
577
+ function parseStructSpecification(declaration) {
578
+ const existing = cache.get(declaration);
579
+ if (existing) return existing;
580
+ const lexingResult = lexer.tokenize(declaration);
581
+ if (lexingResult.errors.length > 0) throw new AggregateError(lexingResult.errors, "Failed to lex struct specification");
582
+ parser.input = lexingResult.tokens;
583
+ const cstNode = parser.structSpecification();
584
+ if (parser.errors.length > 0) throw new AggregateError(parser.errors, "Failed to parse struct specification");
585
+ const created = structAstVisitor.structSpecification(cstNode.children);
586
+ cache.set(declaration, created);
587
+ return created;
588
+ }
589
+ //#endregion
590
+ //#region src/struct/struct-registry.ts
591
+ var StructRegistry = class StructRegistry {
592
+ static TEXT_DECODER = new TextDecoder("utf-8");
593
+ definitions = /* @__PURE__ */ new Map();
594
+ byteLengths = /* @__PURE__ */ new Map();
595
+ constructor(structDecodeQueue) {
596
+ this.structDecodeQueue = structDecodeQueue;
597
+ }
598
+ register(name, definition) {
599
+ const specification = parseStructSpecification(definition);
600
+ this.definitions.set(name, specification);
601
+ this.structDecodeQueue.registerSchema(name, specification.map((member) => member.value));
602
+ }
603
+ getDefinition(name) {
604
+ const definition = this.definitions.get(name);
605
+ if (!definition) throw new RangeError(`Unknown struct definition: ${name}`);
606
+ return definition;
607
+ }
608
+ decodeArray(structName, payload) {
609
+ const structNameWithoutSuffix = structName.slice(0, -2);
610
+ const structByteLengthOrBlocker = this.getByteLength(structNameWithoutSuffix);
611
+ if (typeof structByteLengthOrBlocker === "string") return structByteLengthOrBlocker;
612
+ const elements = payload.byteLength / structByteLengthOrBlocker;
613
+ const offset = new ByteOffset();
614
+ const result = [];
615
+ for (let i = 0; i < elements; i++) {
616
+ const decoded = this.decode(structNameWithoutSuffix, payload, offset);
617
+ if (typeof decoded === "string") throw new TypeError(`Expected struct ${structNameWithoutSuffix} to be defined if the byte length calculation succeeded`);
618
+ result.push(decoded);
619
+ }
620
+ return result;
621
+ }
622
+ decode(structName, payload, offset = new ByteOffset()) {
623
+ if (!this.definitions.has(structName)) return structName;
624
+ const specification = this.getDefinition(structName);
625
+ const result = /* @__PURE__ */ new Map();
626
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
627
+ for (const member of specification) {
628
+ if (member.bitWidth) throw new Error("Bit-field members are not implemented");
629
+ switch (member.value) {
630
+ case KnownStructTypeName.Boolean:
631
+ if (member.arraySize !== void 0) {
632
+ const array = [];
633
+ for (let i = 0; i < member.arraySize; i++) {
634
+ array.push(Boolean(view.getUint8(offset.get())));
635
+ offset.advance8();
636
+ }
637
+ result.set(member.name, array);
638
+ } else {
639
+ result.set(member.name, Boolean(view.getUint8(offset.get())));
640
+ offset.advance8();
641
+ }
642
+ break;
643
+ case KnownStructTypeName.Int8:
644
+ if (member.arraySize !== void 0) {
645
+ const array = [];
646
+ for (let i = 0; i < member.arraySize; i++) {
647
+ array.push(view.getInt8(offset.get()));
648
+ offset.advance8();
649
+ }
650
+ result.set(member.name, array);
651
+ } else {
652
+ result.set(member.name, view.getInt8(offset.get()));
653
+ offset.advance8();
654
+ }
655
+ break;
656
+ case KnownStructTypeName.Int16:
657
+ if (member.arraySize !== void 0) {
658
+ const array = [];
659
+ for (let i = 0; i < member.arraySize; i++) {
660
+ array.push(view.getInt16(offset.get(), true));
661
+ offset.advance16();
662
+ }
663
+ result.set(member.name, array);
664
+ } else {
665
+ result.set(member.name, view.getInt16(offset.get(), true));
666
+ offset.advance16();
667
+ }
668
+ break;
669
+ case KnownStructTypeName.Int32:
670
+ if (member.arraySize !== void 0) {
671
+ const array = [];
672
+ for (let i = 0; i < member.arraySize; i++) {
673
+ array.push(view.getInt32(offset.get(), true));
674
+ offset.advance32();
675
+ }
676
+ result.set(member.name, array);
677
+ } else {
678
+ result.set(member.name, view.getInt32(offset.get(), true));
679
+ offset.advance32();
680
+ }
681
+ break;
682
+ case KnownStructTypeName.Int64:
683
+ if (member.arraySize !== void 0) {
684
+ const array = [];
685
+ for (let i = 0; i < member.arraySize; i++) {
686
+ array.push(view.getBigInt64(offset.get(), true));
687
+ offset.advance64();
688
+ }
689
+ result.set(member.name, array);
690
+ } else {
691
+ result.set(member.name, view.getBigInt64(offset.get(), true));
692
+ offset.advance64();
693
+ }
694
+ break;
695
+ case KnownStructTypeName.Uint8:
696
+ if (member.arraySize !== void 0) {
697
+ const array = [];
698
+ for (let i = 0; i < member.arraySize; i++) {
699
+ array.push(view.getUint8(offset.get()));
700
+ offset.advance8();
701
+ }
702
+ result.set(member.name, array);
703
+ } else {
704
+ result.set(member.name, view.getUint8(offset.get()));
705
+ offset.advance8();
706
+ }
707
+ break;
708
+ case KnownStructTypeName.Uint16:
709
+ if (member.arraySize !== void 0) {
710
+ const array = [];
711
+ for (let i = 0; i < member.arraySize; i++) {
712
+ array.push(view.getUint16(offset.get(), true));
713
+ offset.advance16();
714
+ }
715
+ result.set(member.name, array);
716
+ } else {
717
+ result.set(member.name, view.getUint16(offset.get(), true));
718
+ offset.advance16();
719
+ }
720
+ break;
721
+ case KnownStructTypeName.Uint32:
722
+ if (member.arraySize !== void 0) {
723
+ const array = [];
724
+ for (let i = 0; i < member.arraySize; i++) {
725
+ array.push(view.getUint32(offset.get(), true));
726
+ offset.advance32();
727
+ }
728
+ result.set(member.name, array);
729
+ } else {
730
+ result.set(member.name, view.getUint32(offset.get(), true));
731
+ offset.advance32();
732
+ }
733
+ break;
734
+ case KnownStructTypeName.Uint64:
735
+ if (member.arraySize !== void 0) {
736
+ const array = [];
737
+ for (let i = 0; i < member.arraySize; i++) {
738
+ array.push(view.getBigUint64(offset.get(), true));
739
+ offset.advance64();
740
+ }
741
+ result.set(member.name, array);
742
+ } else {
743
+ result.set(member.name, view.getBigUint64(offset.get(), true));
744
+ offset.advance64();
745
+ }
746
+ break;
747
+ case KnownStructTypeName.Float32:
748
+ case KnownStructTypeName.Float:
749
+ if (member.arraySize !== void 0) {
750
+ const array = [];
751
+ for (let i = 0; i < member.arraySize; i++) {
752
+ array.push(view.getFloat32(offset.get(), true));
753
+ offset.advance32();
754
+ }
755
+ result.set(member.name, array);
756
+ } else {
757
+ result.set(member.name, view.getFloat32(offset.get(), true));
758
+ offset.advance32();
759
+ }
760
+ break;
761
+ case KnownStructTypeName.Float64:
762
+ case KnownStructTypeName.Double:
763
+ if (member.arraySize !== void 0) {
764
+ const array = [];
765
+ for (let i = 0; i < member.arraySize; i++) {
766
+ array.push(view.getFloat64(offset.get(), true));
767
+ offset.advance64();
768
+ }
769
+ result.set(member.name, array);
770
+ } else {
771
+ result.set(member.name, view.getFloat64(offset.get(), true));
772
+ offset.advance64();
773
+ }
774
+ break;
775
+ case KnownStructTypeName.Character:
776
+ if (member.arraySize !== void 0) result.set(member.name, StructRegistry.TEXT_DECODER.decode(payload.subarray(offset.get(), offset.advance(member.arraySize).get())));
777
+ else result.set(member.name, StructRegistry.TEXT_DECODER.decode(payload.subarray(offset.get(), offset.advance8().get())));
778
+ break;
779
+ default: if (member.arraySize !== void 0) {
780
+ const array = [];
781
+ for (let i = 0; i < member.arraySize; i++) {
782
+ const decoded = this.decode(member.value, payload, offset);
783
+ if (typeof decoded === "string") return decoded;
784
+ array.push(decoded);
785
+ }
786
+ result.set(member.name, array);
787
+ } else {
788
+ const decoded = this.decode(member.value, payload, offset);
789
+ if (typeof decoded === "string") return decoded;
790
+ result.set(member.name, decoded);
791
+ }
792
+ }
793
+ }
794
+ return result;
795
+ }
796
+ getByteLength(name) {
797
+ const existing = this.byteLengths.get(name);
798
+ if (existing !== void 0) return existing;
799
+ const definition = this.getDefinition(name);
800
+ let totalByteLength = 0;
801
+ for (const member of definition) {
802
+ const memberByteLengthOrBlocker = this.calculateByteLength(member);
803
+ if (typeof memberByteLengthOrBlocker === "string") return memberByteLengthOrBlocker;
804
+ totalByteLength += memberByteLengthOrBlocker;
805
+ }
806
+ this.byteLengths.set(name, totalByteLength);
807
+ return totalByteLength;
808
+ }
809
+ calculateByteLength(member) {
810
+ if (member.bitWidth) throw new Error("Bit-field members are not implemented");
811
+ let byteLengthForOne = 0;
812
+ switch (member.value) {
813
+ case KnownStructTypeName.Boolean:
814
+ case KnownStructTypeName.Character:
815
+ case KnownStructTypeName.Int8:
816
+ case KnownStructTypeName.Uint8:
817
+ byteLengthForOne = 1;
818
+ break;
819
+ case KnownStructTypeName.Int16:
820
+ case KnownStructTypeName.Uint16:
821
+ byteLengthForOne = 2;
822
+ break;
823
+ case KnownStructTypeName.Int32:
824
+ case KnownStructTypeName.Uint32:
825
+ byteLengthForOne = 4;
826
+ break;
827
+ case KnownStructTypeName.Int64:
828
+ case KnownStructTypeName.Uint64:
829
+ byteLengthForOne = 8;
830
+ break;
831
+ case KnownStructTypeName.Float32:
832
+ case KnownStructTypeName.Float:
833
+ byteLengthForOne = 4;
834
+ break;
835
+ case KnownStructTypeName.Float64:
836
+ case KnownStructTypeName.Double:
837
+ byteLengthForOne = 8;
838
+ break;
839
+ default: {
840
+ const structByteLengthOrName = this.getByteLength(member.value);
841
+ if (typeof structByteLengthOrName === "string") return structByteLengthOrName;
842
+ byteLengthForOne = structByteLengthOrName;
843
+ break;
844
+ }
845
+ }
846
+ if (member.arraySize !== void 0) return member.arraySize * byteLengthForOne;
847
+ return byteLengthForOne;
848
+ }
849
+ };
850
+ //#endregion
851
+ //#region src/decode-records.ts
852
+ const TEXT_DECODER = new TextDecoder();
853
+ const STRUCT_PREFIX = "struct:";
854
+ const STRUCT_ARRAY_SUFFIX = "[]";
855
+ function byteToBoolean(byte) {
856
+ switch (byte) {
857
+ case 0: return false;
858
+ case 1: return true;
859
+ default: throw new RangeError(`Invalid boolean value ${byte}`);
860
+ }
861
+ }
862
+ function normalizeEntryName(rawName) {
863
+ if (rawName.startsWith("/")) return rawName;
864
+ return `/${rawName}`;
865
+ }
866
+ /**
867
+ * Decode raw WPILOG records into typed values.
868
+ *
869
+ * Accepts the output of {@link readRecords} and yields fully decoded records,
870
+ * including struct decoding with dependency resolution.
871
+ */
872
+ async function* decodeRecords(records) {
873
+ const asyncDecodedStructs = [];
874
+ const structDecodeQueue = new StructDecodeQueue((structName, queuedRecords) => {
875
+ for (const raw of queuedRecords) {
876
+ const ctx = context.get(raw.entryId);
877
+ if (!ctx) continue;
878
+ const entryType = ctx.entryType;
879
+ const name = normalizeEntryName(ctx.entryName);
880
+ const metadata = ctx.entryMetadata;
881
+ if (entryType.endsWith(STRUCT_ARRAY_SUFFIX)) {
882
+ const normalizedName = entryType.slice(7);
883
+ const decoded = structRegistry.decodeArray(normalizedName, raw.payload);
884
+ if (typeof decoded !== "string") asyncDecodedStructs.push({
885
+ entryId: raw.entryId,
886
+ timestamp: raw.timestamp,
887
+ name,
888
+ metadata,
889
+ type: RecordType.StructArray,
890
+ structName: normalizedName,
891
+ payload: decoded
892
+ });
893
+ } else {
894
+ const normalizedName = entryType.slice(7);
895
+ const decoded = structRegistry.decode(normalizedName, raw.payload);
896
+ if (typeof decoded !== "string") asyncDecodedStructs.push({
897
+ entryId: raw.entryId,
898
+ timestamp: raw.timestamp,
899
+ name,
900
+ metadata,
901
+ type: RecordType.Struct,
902
+ structName: normalizedName,
903
+ payload: decoded
904
+ });
905
+ }
906
+ }
907
+ });
908
+ const structRegistry = new StructRegistry(structDecodeQueue);
909
+ const context = /* @__PURE__ */ new Map();
910
+ for await (const readRecord of records) {
911
+ if (readRecord.kind === "header") continue;
912
+ if (readRecord.kind === "control") {
913
+ const controlPayload = readRecord.payload;
914
+ switch (controlPayload.controlRecordType) {
915
+ case ControlRecordType.Start:
916
+ context.set(controlPayload.entryId, controlPayload);
917
+ break;
918
+ case ControlRecordType.Finish:
919
+ context.delete(controlPayload.entryId);
920
+ break;
921
+ }
922
+ yield {
923
+ entryId: readRecord.entryId,
924
+ timestamp: readRecord.timestamp,
925
+ type: RecordType.Control,
926
+ payload: controlPayload
927
+ };
928
+ continue;
929
+ }
930
+ const raw = readRecord.record;
931
+ const recordContext = context.get(raw.entryId);
932
+ if (recordContext === void 0) throw new RangeError(`No type registered for entry ID ${raw.entryId}`);
933
+ const name = normalizeEntryName(recordContext.entryName);
934
+ const metadata = recordContext.entryMetadata;
935
+ const view = new DataView(raw.payload.buffer, raw.payload.byteOffset, raw.payload.byteLength);
936
+ const decoded = decodePayload(raw, recordContext.entryType, name, metadata, view, structRegistry, structDecodeQueue);
937
+ if (decoded) yield decoded;
938
+ yield* asyncDecodedStructs;
939
+ asyncDecodedStructs.length = 0;
940
+ }
941
+ }
942
+ function decodePayload(raw, entryType, name, metadata, view, structRegistry, structDecodeQueue) {
943
+ const base = {
944
+ entryId: raw.entryId,
945
+ timestamp: raw.timestamp,
946
+ name,
947
+ metadata
948
+ };
949
+ switch (entryType) {
950
+ case "boolean": return {
951
+ ...base,
952
+ type: RecordType.Boolean,
953
+ payload: byteToBoolean(view.getUint8(0))
954
+ };
955
+ case "int64": return {
956
+ ...base,
957
+ type: RecordType.Int64,
958
+ payload: view.getBigInt64(0, true)
959
+ };
960
+ case "float": return {
961
+ ...base,
962
+ type: RecordType.Float,
963
+ payload: view.getFloat32(0, true)
964
+ };
965
+ case "double": return {
966
+ ...base,
967
+ type: RecordType.Double,
968
+ payload: view.getFloat64(0, true)
969
+ };
970
+ case "string": return {
971
+ ...base,
972
+ type: RecordType.String,
973
+ payload: TEXT_DECODER.decode(raw.payload)
974
+ };
975
+ case "boolean[]": {
976
+ const payload = [];
977
+ for (let i = 0; i < raw.payload.byteLength; i++) payload.push(byteToBoolean(view.getUint8(i)));
978
+ return {
979
+ ...base,
980
+ type: RecordType.BooleanArray,
981
+ payload
982
+ };
983
+ }
984
+ case "int64[]": {
985
+ const payload = [];
986
+ for (let i = 0; i < raw.payload.byteLength; i += 8) payload.push(view.getBigUint64(i, true));
987
+ return {
988
+ ...base,
989
+ type: RecordType.Int64Array,
990
+ payload
991
+ };
992
+ }
993
+ case "float[]": {
994
+ const payload = [];
995
+ for (let i = 0; i < raw.payload.byteLength; i += 4) payload.push(view.getFloat32(i, true));
996
+ return {
997
+ ...base,
998
+ type: RecordType.FloatArray,
999
+ payload
1000
+ };
1001
+ }
1002
+ case "double[]": {
1003
+ const payload = [];
1004
+ for (let i = 0; i < raw.payload.byteLength; i += 8) payload.push(view.getFloat64(i, true));
1005
+ return {
1006
+ ...base,
1007
+ type: RecordType.DoubleArray,
1008
+ payload
1009
+ };
1010
+ }
1011
+ case "string[]": {
1012
+ const payload = [];
1013
+ const offset = new ByteOffset();
1014
+ const arrayLength = view.getUint32(offset.get(), true);
1015
+ offset.advance32();
1016
+ for (let i = 0; i < arrayLength; i++) {
1017
+ const stringLength = view.getUint32(offset.get(), true);
1018
+ offset.advance32();
1019
+ const string = TEXT_DECODER.decode(raw.payload.subarray(offset.get(), offset.get() + stringLength));
1020
+ offset.advance(stringLength);
1021
+ payload.push(string);
1022
+ }
1023
+ return {
1024
+ ...base,
1025
+ type: RecordType.StringArray,
1026
+ payload
1027
+ };
1028
+ }
1029
+ case "structschema": {
1030
+ const structName = name.slice(16);
1031
+ const payload = TEXT_DECODER.decode(raw.payload);
1032
+ structRegistry.register(structName, payload);
1033
+ return {
1034
+ ...base,
1035
+ type: RecordType.String,
1036
+ payload
1037
+ };
1038
+ }
1039
+ default:
1040
+ if (entryType.startsWith(STRUCT_PREFIX)) {
1041
+ if (entryType.endsWith(STRUCT_ARRAY_SUFFIX)) {
1042
+ const normalizedStructName = entryType.slice(7);
1043
+ const decoded = structRegistry.decodeArray(normalizedStructName, raw.payload);
1044
+ if (typeof decoded === "string") {
1045
+ structDecodeQueue.queueStructRecord(decoded, raw);
1046
+ return;
1047
+ }
1048
+ return {
1049
+ ...base,
1050
+ type: RecordType.StructArray,
1051
+ structName: normalizedStructName,
1052
+ payload: decoded
1053
+ };
1054
+ }
1055
+ const normalizedStructName = entryType.slice(7);
1056
+ const decoded = structRegistry.decode(normalizedStructName, raw.payload);
1057
+ if (typeof decoded === "string") {
1058
+ structDecodeQueue.queueStructRecord(decoded, raw);
1059
+ return;
1060
+ }
1061
+ return {
1062
+ ...base,
1063
+ type: RecordType.Struct,
1064
+ structName: normalizedStructName,
1065
+ payload: decoded
1066
+ };
1067
+ }
1068
+ return {
1069
+ ...base,
1070
+ type: RecordType.Raw,
1071
+ payload: raw.payload
1072
+ };
1073
+ }
1074
+ }
1075
+ //#endregion
1076
+ //#region src/struct-payload-to-json.ts
1077
+ /** Convert a {@link StructPayload} Map to a plain JSON-compatible object. */
1078
+ function structPayloadToJson(payload) {
1079
+ const result = {};
1080
+ for (const [key, value] of payload) if (value instanceof Map) result[key] = structPayloadToJson(value);
1081
+ else if (Array.isArray(value) && value.length > 0 && value[0] instanceof Map) result[key] = value.map((v) => structPayloadToJson(v));
1082
+ else result[key] = value;
1083
+ return result;
1084
+ }
1085
+ //#endregion
1086
+ //#region src/catalog.ts
1087
+ /**
1088
+ * Collect all entry definitions from a WPILOG record stream.
1089
+ *
1090
+ * Iterates through records, collecting Start control records.
1091
+ * Data record bytes are still read from the stream but not decoded,
1092
+ * making this much cheaper than full decoding via {@link decodeRecords}.
1093
+ */
1094
+ async function* catalogEntries(records) {
1095
+ const entries = /* @__PURE__ */ new Map();
1096
+ for await (const record of records) {
1097
+ if (record.kind !== "control") continue;
1098
+ if (record.payload.controlRecordType === ControlRecordType.Start) {
1099
+ const entry = {
1100
+ entryId: record.payload.entryId,
1101
+ name: record.payload.entryName,
1102
+ type: record.payload.entryType,
1103
+ metadata: record.payload.entryMetadata
1104
+ };
1105
+ entries.set(record.payload.entryId, entry);
1106
+ yield entry;
1107
+ }
1108
+ if (record.payload.controlRecordType === ControlRecordType.SetMetadata) {
1109
+ const existing = entries.get(record.payload.entryId);
1110
+ if (existing) existing.metadata = record.payload.entryMetadata;
1111
+ }
1112
+ }
1113
+ }
1114
+ //#endregion
1115
+ export { ControlRecordType, KnownStructTypeName, RecordType, catalogEntries, decodeRecords, isDataRecord, parseStructSpecification, readRecords, structPayloadToJson };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "wpilog-parser",
3
+ "version": "1.0.1",
4
+ "description": "Read WPILib wpilog data log files in TypeScript & JavaScript",
5
+ "homepage": "https://github.com/jonahsnider/wpilog-parser#readme",
6
+ "license": "MIT",
7
+ "author": {
8
+ "name": "Jonah Snider",
9
+ "email": "jonah@jonahsnider.com",
10
+ "url": "https://jonahsnider.com"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/jonahsnider/wpilog-parser.git"
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "type": "module",
20
+ "exports": {
21
+ ".": "./dist/index.mjs",
22
+ "./package.json": "./package.json"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "scripts": {
28
+ "build": "vp pack",
29
+ "check": "vp check",
30
+ "dev": "vp pack --watch",
31
+ "generate": "bun run ./src/struct/codegen.ts",
32
+ "prepare": "vp config",
33
+ "prepublishOnly": "vp run build",
34
+ "test": "vp test"
35
+ },
36
+ "dependencies": {
37
+ "chevrotain": "^12.0.0"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "24.12.0",
41
+ "@typescript/native-preview": "7.0.0-dev.20260401.1",
42
+ "typescript": "6.0.2",
43
+ "vite-plus": "0.1.15"
44
+ },
45
+ "overrides": {
46
+ "vite": "npm:@voidzero-dev/vite-plus-core@latest",
47
+ "vitest": "npm:@voidzero-dev/vite-plus-test@latest"
48
+ },
49
+ "packageManager": "bun@1.3.10"
50
+ }