Files
skills/docs/foundation/flow/cbor/src/diagnostic/diagnostic.md
2026-05-29 08:20:56 +01:00

2.6 KiB

diagnostic

(no submodules)

Purpose

Emits RFC 8949 §8 diagnostic notation for any decoded CBOR value. Diagnostic notation is the JSON-like text surface CBOR uses for log lines, error messages, and human inspection. The format is lossless for booleans, integers, floats, strings, byte strings (encoded as h'...' hex), arrays, maps, and tagged values; objects are serialised with quoted string keys; Date values are emitted as the canonical RFC 3339 tag-0 form.

This is a debug surface — never invoke from encode/decode hot paths. The implementation makes a fresh string per call and walks the value recursively.

Features

  • Full primitive coverage: null, undefined, boolean, number (incl. ±0, ±Inf, NaN), bigint, string, Uint8Array, arrays, Map, objects.
  • Tag rendering: Tagged{tag, value} → tag(value-diagnostic).
  • Byte strings rendered as h'<hex>' per RFC 8949 §8.1.
  • String escapes for backslash, double quote, and ASCII control characters (matches JSON-string escapes).
  • bytesToDiagnostic(bytes) convenience: decode + format in one call. Tags are decoded raw (no IANA-handler substitution) so the diagnostic output reflects the exact wire-level structure.

Usage: Basic Example

import { toDiagnostic } from "@suaveplan/cbor/diagnostic";

const repr = toDiagnostic({ name: "Alice", age: 30 });
// '{"name": "Alice", "age": 30}'

Usage: Advanced Example

import { encode } from "@suaveplan/cbor/encoder";
import { Tagged } from "@suaveplan/cbor/tags";
import { bytesToDiagnostic } from "@suaveplan/cbor/diagnostic";

const wire = encode([new Tagged(0, "2026-05-10T12:00:00Z"), { id: 1 }]);
console.log(bytesToDiagnostic(wire));
// '[0("2026-05-10T12:00:00Z"), {"id": 1}]'

API Reference

  • toDiagnostic(value: unknown): string — recursively formats value.
  • bytesToDiagnostic(bytes: Uint8Array): string — decode + format in one pass; tag handling is "raw" so handlers do not substitute the inner representation.

Neither function throws on a CBOR-decoded value — the input domain is total. The byte-input variant inherits any decoder error.

Implementation Notes

The output format follows the JSON-like surface from RFC 8949 §8 while incorporating CBOR-specific extensions (the h'...' byte-string syntax, the tag(...) tagged-item syntax). Numeric formatting preserves -0 and the three special float values; otherwise the standard Number.toString() representation is used. The function is intentionally allocation-heavy: debug paths can pay for clarity.