Skip to content

Repository files navigation

webklv

A fully web-compatible, zero-dependency KLV (Key-Length-Value) data parsing library for JavaScript/TypeScript.

Features

  • 100% web compatible — uses only standard browser APIs (TextEncoder, Uint8Array, BigInt)
  • 🔒 Fully typed — complete TypeScript types with generics and strict mode
  • Full sync — no async, no streams, no callbacks; parse buffer in, structured data out
  • 🧩 MISB ST 0601 — complete UAS Local Metadata Set (105 tags)
  • 🔐 MISB ST 0102 — Security Metadata nested local set
  • 📦 Built with rslib — ESM + CJS dual output with declaration maps
  • 🛡️ Pristine error handling — typed errors (KLVError, BERDecodeError, TruncatedDataError, …)
  • ✔️ Validated — passes the complete klvdata Python library test suite

Installation

npm install webklv
# or
pnpm add webklv

Quick Start

Parse a raw KLV buffer

import { KLVParser } from "webklv";

const buffer = new Uint8Array([0x02, 0x08, 0x00, 0x04, 0x60, 0x50, 0x58, 0x4e, 0x01, 0x80]);
const parser = new KLVParser(buffer, { keyLength: 1 });

for (const { key, value } of parser) {
  console.log(key, value);
  // Uint8Array [2]  Uint8Array [0x00, 0x04, ...]
}

Parse a MISB ST 0601 packet

import { StreamParser, UASLocalMetadataSet, PrecisionTimeStamp } from "webklv";
import "webklv"; // MISB parsers auto-register on import

for (const packet of new StreamParser(buffer)) {
  if (packet instanceof UASLocalMetadataSet) {
    const ts = packet.get(PrecisionTimeStamp.key);
    if (ts instanceof PrecisionTimeStamp) {
      console.log(ts.value.toString()); // "2009-01-12 22:08:22+00:00"
    }
  }
}

Encode a value

import { PlatformHeadingAngle } from "webklv";

const elem = new PlatformHeadingAngle(159.974);
const bytes = elem.toBytes();
// Uint8Array [0x05, 0x02, 0x71, 0xC2]

Architecture

src/
├── core/
│   ├── ber.ts          BER length field encode/decode
│   ├── checksum.ts     SMPTE ST 336 packet checksum
│   ├── errors.ts       Typed error classes
│   └── types.ts        Core TypeScript interfaces
├── converters/
│   ├── bytes.ts        Integer ↔ Uint8Array
│   ├── datetime.ts     Microsecond UTC timestamp ↔ Uint8Array (BigInt precision)
│   ├── float.ts        Linear-mapped fixed-point float ↔ Uint8Array
│   ├── hexstr.ts       Hex string ↔ Uint8Array
│   └── string.ts       UTF-8 string ↔ Uint8Array
├── element/
│   ├── element.ts      Abstract Element base, UnknownElement
│   ├── parsers.ts      BytesElementParser, DateTimeElementParser, etc.
│   ├── set.ts          SetParser (nested local sets)
│   └── values.ts       BytesValue, StringValue, DateTimeValue, MappedValue
├── stream/
│   ├── parser.ts       KLVParser (raw TLV iterator)
│   └── streamparser.ts StreamParser (16-byte UL dispatch)
└── misb/
    ├── misb0601.ts     MISB ST 0601 — UAS Local Metadata Set + Tags 1–25
    ├── misb0601-nav.ts Tags 26–65 (navigation, sensor, platform)
    ├── misb0601-ext.ts Tags 66–105 (extended/alternate platform)
    └── misb0102.ts     MISB ST 0102 — Security Metadata nested set

API Reference

KLVParser

Low-level iterator that yields raw { key, value } pairs.

const parser = new KLVParser(buffer, { keyLength: 1 });
for (const { key, value } of parser) { ... }

StreamParser

High-level iterator that dispatches 16-byte Universal Labels to registered set parsers.

for (const packet of new StreamParser(buffer)) { ... }

SetParser (base class)

Base for all MISB local sets. Parsed items accessible via:

set.items                    // Map<string, Element>
set.get(key)                 // Element | undefined
set.toBytes()                // Uint8Array — re-encode to wire format

Element Types

Class Value Type Notes
BytesElementParser BytesValue (raw bytes) Checksum, opaque fields
StringElementParser StringValue (string) UTF-8 text fields
DateTimeElementParser DateTimeValue (Date) Microsecond precision
MappedElementParser MappedValue (number) Fixed-point → float
UnknownElement Uint8Array Fallback for unknown keys

Utility Functions

// BER encoding
berEncode(128)   // Uint8Array [0x81, 0x80]
berDecode(bytes) // number

// Checksum
packetChecksum(fullPacket) // Uint8Array [hi, lo]

// Converters
bytesToFloat(bytes, domain, range)
floatToBytes(value, domain, range)
bytesToDatetime(bytes)   // Date
datetimeToBytes(date)    // Uint8Array
hexstrToBytes("06 0E 2B 34")
bytesToHexstr(bytes)

Error Classes

Class When thrown
KLVError Base for all library errors
BERDecodeError Malformed BER length field
RangeError Value outside linear map domain
TruncatedDataError Buffer ends unexpectedly
LengthError Wrong byte count for data type
ValidationError Schema validation failure

MISB ST 0601 Tags

All 105 registered tags including:

  • Tags 1–25: Checksum, timestamp, mission ID, platform heading/pitch/roll, sensor position, frame center
  • Tags 26–65: Corner offsets, wind, pressure, target location, weapons, call sign
  • Tags 66–105: Alternate platform, event start time, ellipsoid heights, full-precision corners

Building

pnpm install
pnpm build      # ESM + CJS + types
pnpm test       # 156 tests
pnpm test:coverage
pnpm lint       # TypeScript type check

License

MIT


Comparison with the Python klvdata library

This library is a faithful TypeScript port of the klvdata Python library, passing its complete test suite. Key differences:

Feature webklv (TypeScript) klvdata (Python)
Platform Web + Node.js Python only
Precision BigInt microseconds Python float
Types Full TypeScript types Dynamic
Build rslib (ESM + CJS) setuptools

About

A fully web-compatible KLV data parsing library for JavaScript/TypeScript with MISB ST 0601 and ST 0102 support

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages