wpilog-parser 2.4.1 → 2.5.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/README.md CHANGED
@@ -25,6 +25,9 @@ for (const record of parseDataLog(bytes)) {
25
25
 
26
26
  Use `readRecords()` and `decodeRecords()` separately when you need access to raw records or want to transform the record stream before decoding it. Both approaches produce the same decoded records.
27
27
 
28
+ Struct schemas are compiled lazily into reusable decoders, and struct payloads are returned as `Map` values.
29
+ In environments where Content Security Policy blocks runtime code generation, structs are decoded by the interpreter automatically.
30
+
28
31
  ## CLI
29
32
 
30
33
  List every entry available in a log before writing an analysis script:
@@ -41,16 +44,29 @@ npx wpilog-parser catalog ./example.wpilog --json
41
44
 
42
45
  ## Agent skill
43
46
 
44
- This package ships an [Agent Skill](https://agentskills.io) at `skills/analyze-wpilog/SKILL.md` that teaches AI coding agents how to use the library. Install it into your project with either:
47
+ This package ships an [Agent Skill](https://agentskills.io) at `skills/analyze-wpilog/SKILL.md` that teaches AI coding agents how to use the library.
48
+ It allows agents to analyze robot log files themselves, and create reports or insights based on the data stored in the WPILOG.
49
+
50
+ You can also install the skill with:
45
51
 
46
52
  ```sh
47
53
  # https://skills.sh/
48
54
  npx skills add jonahsnider/wpilog-parser
49
55
  ```
50
56
 
57
+ With [pnpm 12.11.0 or later](https://pnpm.io/agent-skills), install the package and approve its skill:
58
+
51
59
  ```sh
52
- # https://github.com/antfu/skills-npm
53
- npx skills-npm
60
+ pnpm add wpilog-parser
61
+ pnpm approve
62
+ ```
63
+
64
+ Approving skills for `wpilog-parser` records the following in your project's `pnpm-workspace.yaml`:
65
+
66
+ ```yaml
67
+ permissions:
68
+ wpilog-parser:
69
+ skills: true
54
70
  ```
55
71
 
56
72
  ## Development
@@ -367,9 +367,7 @@ const EMPTY_SET = /* @__PURE__ */ new Set();
367
367
  var StructDependencyGraph = class {
368
368
  allDependencies = new Map(Object.values(KnownStructTypeName).map((type) => [type, EMPTY_SET]));
369
369
  registerSchema(name, innerStructNames) {
370
- const existing = this.allDependencies.get(name);
371
- if (existing) for (const innerStructName of innerStructNames) existing.add(innerStructName);
372
- else this.allDependencies.set(name, new Set(innerStructNames));
370
+ this.allDependencies.set(name, new Set(innerStructNames));
373
371
  if (this.hasCycle(name)) throw diagnostics.WPILOG_R0012({ name });
374
372
  }
375
373
  hasCycle(current, path = /* @__PURE__ */ new Set()) {
@@ -491,6 +489,149 @@ function isSignedInteger(type) {
491
489
  }
492
490
  }
493
491
  //#endregion
492
+ //#region src/struct/compile-struct.ts
493
+ const READERS = {
494
+ bool: {
495
+ method: "getUint8",
496
+ bytes: 1
497
+ },
498
+ char: {
499
+ method: "getUint8",
500
+ bytes: 1
501
+ },
502
+ int8: {
503
+ method: "getInt8",
504
+ bytes: 1
505
+ },
506
+ int16: {
507
+ method: "getInt16",
508
+ bytes: 2
509
+ },
510
+ int32: {
511
+ method: "getInt32",
512
+ bytes: 4
513
+ },
514
+ int64: {
515
+ method: "getBigInt64",
516
+ bytes: 8
517
+ },
518
+ uint8: {
519
+ method: "getUint8",
520
+ bytes: 1
521
+ },
522
+ uint16: {
523
+ method: "getUint16",
524
+ bytes: 2
525
+ },
526
+ uint32: {
527
+ method: "getUint32",
528
+ bytes: 4
529
+ },
530
+ uint64: {
531
+ method: "getBigUint64",
532
+ bytes: 8
533
+ },
534
+ float: {
535
+ method: "getFloat32",
536
+ bytes: 4
537
+ },
538
+ float32: {
539
+ method: "getFloat32",
540
+ bytes: 4
541
+ },
542
+ double: {
543
+ method: "getFloat64",
544
+ bytes: 8
545
+ },
546
+ float64: {
547
+ method: "getFloat64",
548
+ bytes: 8
549
+ }
550
+ };
551
+ /** Probe lazily, once per registry, so CSP restrictions leave the interpreter available. */
552
+ function allowsCodeGeneration() {
553
+ try {
554
+ new Function("");
555
+ return true;
556
+ } catch {
557
+ return false;
558
+ }
559
+ }
560
+ function getBitFieldMethod(bitField) {
561
+ switch (bitField.storageByteLength) {
562
+ case 1: return "getUint8";
563
+ case 2: return "getUint16";
564
+ case 4: return "getUint32";
565
+ case 8: return "getBigUint64";
566
+ default: throw new RangeError("Invalid bit-field storage size");
567
+ }
568
+ }
569
+ function generateBitFieldExpression(type, bitField, offset) {
570
+ const raw = `view.${getBitFieldMethod(bitField)}(base + ${offset}, true)`;
571
+ const bigint = bitField.storageByteLength === 8 ? raw : `BigInt(${raw})`;
572
+ const mask = (1n << BigInt(bitField.bitWidth)) - 1n;
573
+ let expression = `((${bigint} >> ${bitField.bitShift}n) & ${mask}n)`;
574
+ if (type === "bool") return `${expression} !== 0n`;
575
+ if (type.startsWith("int")) expression = `BigInt.asIntN(${bitField.bitWidth}, ${expression})`;
576
+ return type === "int64" || type === "uint64" ? expression : `Number(${expression})`;
577
+ }
578
+ /** Compile a schema snapshot after all of its dependencies have been registered. */
579
+ function compileStruct(registry, name) {
580
+ const functions = /* @__PURE__ */ new Map();
581
+ const sources = [];
582
+ function generateMemberValue(member, index, offset, size, reader, statements) {
583
+ const position = `base + ${offset}`;
584
+ if (member.value === "char") return `textDecoder.decode(bytes.subarray(${position}, ${position} + ${size * (member.arraySize ?? 1)}))`;
585
+ const nested = reader ? void 0 : generate(member.value);
586
+ const read = (at) => {
587
+ if (!reader) return `${nested}(view, bytes, ${at})`;
588
+ const value = `view.${reader.method}(${at}, true)`;
589
+ return member.value === "bool" ? `Boolean(${value})` : value;
590
+ };
591
+ if (member.arraySize === void 0) return read(position);
592
+ const expression = `a${index}`;
593
+ statements.push(`const ${expression} = [];`, `for (let i = 0; i < ${member.arraySize}; i++) ${expression}.push(${read(`${position} + i * ${size}`)});`);
594
+ return expression;
595
+ }
596
+ function generate(structName) {
597
+ const existing = functions.get(structName);
598
+ if (existing) return existing;
599
+ const functionName = `s${functions.size}`;
600
+ functions.set(structName, functionName);
601
+ const statements = [];
602
+ const bitFields = new BitFieldTracker();
603
+ let offset = 0;
604
+ for (const [index, member] of registry.getDefinition(structName).entries()) {
605
+ const reader = Object.hasOwn(READERS, member.value) ? READERS[member.value] : void 0;
606
+ const size = reader?.bytes ?? registry.getByteLength(member.value);
607
+ if (typeof size !== "number") throw new TypeError(`Missing schema: ${size}`);
608
+ const memberSize = size * (member.arraySize ?? 1);
609
+ const bitField = bitFields.next(member, memberSize);
610
+ let expression;
611
+ if (bitField) {
612
+ offset += bitField.bytesToAdvance;
613
+ expression = generateBitFieldExpression(member.value, bitField, offset);
614
+ } else {
615
+ offset += bitFields.flush();
616
+ expression = generateMemberValue(member, index, offset, size, reader, statements);
617
+ offset += memberSize;
618
+ }
619
+ const key = JSON.stringify(member.name);
620
+ statements.push(`result.set(${key}, ${expression});`);
621
+ }
622
+ sources.push(`function ${functionName}(view, bytes, base) {
623
+ const result = new Map();
624
+ ${statements.join("\n")}
625
+ return result;
626
+ }`);
627
+ return functionName;
628
+ }
629
+ const root = generate(name);
630
+ return new Function("textDecoder", `"use strict";
631
+ ${sources.join("\n")}
632
+ return ${root};`)(new TextDecoder());
633
+ }
634
+ //#endregion
494
635
  //#region src/struct/lexer.ts
495
636
  const Comma = createToken({
496
637
  name: "Comma",
@@ -741,12 +882,18 @@ var StructRegistry = class StructRegistry {
741
882
  static TEXT_DECODER = new TextDecoder("utf-8");
742
883
  definitions = /* @__PURE__ */ new Map();
743
884
  byteLengths = /* @__PURE__ */ new Map();
885
+ decoders = /* @__PURE__ */ new Map();
886
+ codeGenerationAllowed;
744
887
  structDecodeQueue;
745
888
  constructor(structDecodeQueue) {
746
889
  this.structDecodeQueue = structDecodeQueue;
747
890
  }
748
891
  register(name, definition) {
749
892
  const specification = parseStructSpecification(definition);
893
+ if (this.definitions.has(name) && this.definitions.get(name) !== specification) {
894
+ this.byteLengths.clear();
895
+ this.decoders.clear();
896
+ }
750
897
  this.definitions.set(name, specification);
751
898
  this.structDecodeQueue.registerSchema(name, specification.map((member) => member.value));
752
899
  }
@@ -759,17 +906,48 @@ var StructRegistry = class StructRegistry {
759
906
  const structNameWithoutSuffix = structName.slice(0, -2);
760
907
  const structByteLengthOrBlocker = this.getByteLength(structNameWithoutSuffix);
761
908
  if (typeof structByteLengthOrBlocker === "string") return structByteLengthOrBlocker;
909
+ if (structByteLengthOrBlocker === 0) {
910
+ if (payload.byteLength === 0) return [];
911
+ throw new RangeError("Cannot decode an array of zero-length structs");
912
+ }
762
913
  const elements = payload.byteLength / structByteLengthOrBlocker;
763
914
  const offset = new ByteOffset();
915
+ const decoder = this.getDecoder(structNameWithoutSuffix);
916
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
764
917
  const result = [];
765
918
  for (let i = 0; i < elements; i++) {
766
- const decoded = this.decode(structNameWithoutSuffix, payload, offset);
919
+ const decoded = decoder ? decoder(view, payload, i * structByteLengthOrBlocker) : this.decodeInterpreted(structNameWithoutSuffix, payload, offset);
767
920
  if (typeof decoded === "string") throw new TypeError(`Expected struct ${structNameWithoutSuffix} to be defined if the byte length calculation succeeded`);
768
921
  result.push(decoded);
769
922
  }
770
923
  return result;
771
924
  }
772
- decode(structName, payload, offset = new ByteOffset()) {
925
+ decode(structName, payload, offset) {
926
+ const byteLength = this.getByteLength(structName);
927
+ if (typeof byteLength === "string") return byteLength;
928
+ const decoder = this.getDecoder(structName);
929
+ if (!decoder) return this.decodeInterpreted(structName, payload, offset);
930
+ const result = decoder(new DataView(payload.buffer, payload.byteOffset, payload.byteLength), payload, offset?.get() ?? 0);
931
+ offset?.advance(byteLength);
932
+ return result;
933
+ }
934
+ getDecoder(name) {
935
+ this.codeGenerationAllowed ??= allowsCodeGeneration();
936
+ if (!this.codeGenerationAllowed) return void 0;
937
+ const existing = this.decoders.get(name);
938
+ if (existing) return existing;
939
+ try {
940
+ const decoder = compileStruct(this, name);
941
+ this.decoders.set(name, decoder);
942
+ return decoder;
943
+ } catch (error) {
944
+ if (!(error instanceof EvalError)) throw error;
945
+ this.codeGenerationAllowed = false;
946
+ return;
947
+ }
948
+ }
949
+ /** Decode without runtime code generation, including in CSP-restricted environments. */
950
+ decodeInterpreted(structName, payload, offset = new ByteOffset()) {
773
951
  if (!this.definitions.has(structName)) return structName;
774
952
  const specification = this.getDefinition(structName);
775
953
  const result = /* @__PURE__ */ new Map();
@@ -937,13 +1115,13 @@ var StructRegistry = class StructRegistry {
937
1115
  default: if (member.arraySize !== void 0) {
938
1116
  const array = [];
939
1117
  for (let i = 0; i < member.arraySize; i++) {
940
- const decoded = this.decode(member.value, payload, offset);
1118
+ const decoded = this.decodeInterpreted(member.value, payload, offset);
941
1119
  if (typeof decoded === "string") return decoded;
942
1120
  array.push(decoded);
943
1121
  }
944
1122
  result.set(member.name, array);
945
1123
  } else {
946
- const decoded = this.decode(member.value, payload, offset);
1124
+ const decoded = this.decodeInterpreted(member.value, payload, offset);
947
1125
  if (typeof decoded === "string") return decoded;
948
1126
  result.set(member.name, decoded);
949
1127
  }
@@ -953,6 +1131,7 @@ var StructRegistry = class StructRegistry {
953
1131
  return result;
954
1132
  }
955
1133
  getByteLength(name) {
1134
+ if (!this.definitions.has(name)) return name;
956
1135
  const existing = this.byteLengths.get(name);
957
1136
  if (existing !== void 0) return existing;
958
1137
  const definition = this.getDefinition(name);
package/dist/cli.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { o as readRecords, t as catalogEntries, u as diagnostics } from "./catalog-BT6geQr0.mjs";
2
+ import { o as readRecords, t as catalogEntries, u as diagnostics } from "./catalog-CfUKQI7-.mjs";
3
3
  import { Diagnostic, formatDiagnostic } from "nostics";
4
4
  import { cac } from "cac";
5
+ import oscStatus from "osc-status";
5
6
  import { readFile } from "node:fs/promises";
6
7
  import { encode } from "@toon-format/toon";
7
8
  //#region package.json
8
- var version = "2.4.1";
9
+ var version = "2.5.0";
9
10
  //#endregion
10
11
  //#region src/cli/catalog.ts
11
12
  async function catalogFile(filePath) {
@@ -60,8 +61,16 @@ function formatCatalog(entries, format = "toon") {
60
61
  const cli = cac("wpilog");
61
62
  cli.command("catalog <file>", "List the entries available in a WPILOG file").option("--json", "Output as JSON").option("--jsonl, --ndjson", "Output as newline-delimited JSON").option("--csv", "Output as CSV").example("wpilog catalog ./example.wpilog").example("wpilog catalog ./example.wpilog --json").action(async (file, options) => {
62
63
  const format = selectCatalogFormat(options);
64
+ oscStatus.working({
65
+ app: "wpilog",
66
+ message: "Cataloging log"
67
+ });
63
68
  const entries = await catalogFile(file);
64
69
  console.log(formatCatalog(entries, format));
70
+ oscStatus.done({
71
+ app: "wpilog",
72
+ message: `Cataloged ${entries.length} entries`
73
+ });
65
74
  });
66
75
  cli.help();
67
76
  cli.version(version);
@@ -76,6 +85,10 @@ try {
76
85
  const message = error instanceof Diagnostic ? formatDiagnostic(error) : error instanceof Error ? error.message : String(error);
77
86
  console.error(error instanceof Diagnostic ? message : `wpilog: ${message}`);
78
87
  process.exitCode = 1;
88
+ oscStatus.error({
89
+ app: "wpilog",
90
+ message: "Command failed"
91
+ });
79
92
  }
80
93
  //#endregion
81
94
  export {};
package/dist/index.mjs CHANGED
@@ -1,11 +1,21 @@
1
- import { a as KnownStructTypeName, c as RecordType, i as parseStructSpecification, l as isDataRecord, n as decodeRecords, o as readRecords, r as parseDataLog, s as ControlRecordType, t as catalogEntries } from "./catalog-BT6geQr0.mjs";
1
+ import { a as KnownStructTypeName, c as RecordType, i as parseStructSpecification, l as isDataRecord, n as decodeRecords, o as readRecords, r as parseDataLog, s as ControlRecordType, t as catalogEntries } from "./catalog-CfUKQI7-.mjs";
2
2
  //#region src/struct-payload-to-json.ts
3
3
  /** Convert a {@link StructPayload} Map to a plain JSON-compatible object. */
4
4
  function structPayloadToJson(payload) {
5
5
  const result = {};
6
- for (const [key, value] of payload) if (value instanceof Map) result[key] = structPayloadToJson(value);
7
- else if (Array.isArray(value) && value.length > 0 && value[0] instanceof Map) result[key] = value.map((v) => structPayloadToJson(v));
8
- else result[key] = value;
6
+ for (const [key, value] of payload) {
7
+ let converted;
8
+ if (value instanceof Map) converted = structPayloadToJson(value);
9
+ else if (Array.isArray(value) && value.length > 0 && value[0] instanceof Map) converted = value.map((v) => structPayloadToJson(v));
10
+ else converted = value;
11
+ if (key === "__proto__") Object.defineProperty(result, key, {
12
+ value: converted,
13
+ enumerable: true,
14
+ writable: true,
15
+ configurable: true
16
+ });
17
+ else result[key] = converted;
18
+ }
9
19
  return result;
10
20
  }
11
21
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wpilog-parser",
3
- "version": "2.4.1",
3
+ "version": "2.5.0",
4
4
  "description": "Read WPILib wpilog data log files in TypeScript & JavaScript",
5
5
  "homepage": "https://github.com/jonahsnider/wpilog-parser#readme",
6
6
  "license": "MIT",
@@ -43,11 +43,12 @@
43
43
  "@toon-format/toon": "^4.1.1",
44
44
  "cac": "^7.0.0",
45
45
  "chevrotain": "^13.0.0",
46
- "nostics": "^1.3.0"
46
+ "nostics": "^1.3.0",
47
+ "osc-status": "^1.0.0"
47
48
  },
48
49
  "devDependencies": {
49
- "@codspeed/vitest-plugin": "5.7.1",
50
- "@types/node": "26.6.3",
50
+ "@codspeed/vitest-plugin": "6.1.0",
51
+ "@types/node": "26.6.5",
51
52
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
52
53
  "typescript": "7.0.2",
53
54
  "vite-plus": "catalog:",
@@ -59,5 +60,5 @@
59
60
  "version": "26.x"
60
61
  }
61
62
  },
62
- "packageManager": "pnpm@12.6.0"
63
+ "packageManager": "pnpm@12.14.0"
63
64
  }