Files
skills/docs/networking/drive/drive-mesh-protocol/src/codec/common.md
2026-05-29 08:20:56 +01:00

2.1 KiB

common

Purpose

Internal helpers shared by the four envelope codec modules (request.ts, advertise.ts, response.ts, error.ts). Centralising the base64 codec, strict-parse wrapper, and the DMP_CODES / DmpError re-export keeps each codec module focused on its envelope shape without duplicating utility code.

Features

  • toBase64(bytes) — Uint8Array → base64 string for JSON transport.
  • fromBase64(s) — inverse, returns a fresh Uint8Array.
  • parseStrict(schema, input, code, label) — throwing variant of Zod's safeParse that lifts schema errors into DmpError(code, "...").
  • DMP_CODES / DmpError — re-exported so the codec modules do a single from "./common.js".
  • Pure functions, zero side effects, deterministic outputs.

Usage: Basic Example

import { fromBase64, toBase64 } from "../codec/common.js";

const bytes = new Uint8Array([1, 2, 3]);
const encoded = toBase64(bytes);
const back = fromBase64(encoded);

Usage: Advanced Example

import z from "zod";
import { DMP_CODES, parseStrict } from "../codec/common.js";

const Schema = z.object({ id: z.string(), n: z.number().int() }).strict();

function parseHeader(bytes: Uint8Array) {
    const parsed = JSON.parse(new TextDecoder().decode(bytes));
    return parseStrict<{ id: string; n: number }>(
        Schema,
        parsed,
        DMP_CODES.ENVELOPE_MALFORMED,
        "header"
    );
}

API Reference

  • toBase64(bytes: Uint8Array): string.
  • fromBase64(s: string): Uint8Array.
  • parseStrict<T>(schema, input, code: DmpErrorCode, label: string): T — throws DmpError(code, "<label> schema rejected: <reason>") on failure.
  • DMP_CODES, DmpError — re-exports.

Implementation Notes

The base64 helpers go through btoa / atob because the codec is JSON-based; they're correct for any byte sequence including those with high-bit-set bytes. parseStrict accepts a generic T so call sites get the precisely-typed result of the schema rather than unknown. The narrow surface here is deliberate: anything more complex belongs in the specific codec module so the mental model stays "common.ts holds zero protocol-shaped logic".