parseAttestation

tcmts.records.parseAttestation · #qyiohnbo · term · runs anywhere

A record as an attestation, if it is one (of the collection it's in).

import { ATTESTATION_KINDS, SEVERITIES } from "#codebase/tcmts/records";
import type { Attestation, AttestationKind } from "#codebase/tcmts/records";

export function parseAttestation(collection: string, v: unknown): Attestation | undefined {
  const kind = (Object.keys(ATTESTATION_KINDS) as AttestationKind[]).find(
    (k) => ATTESTATION_KINDS[k] === collection,
  );
  if (!kind || !v || typeof v !== "object") return undefined;
  const r = v as Record<string, unknown>;
  const s = r.subject as Record<string, unknown> | undefined;
  if (
    !s ||
    typeof s.namespace !== "string" ||
    typeof r.body !== "string" ||
    typeof r.createdAt !== "string"
  )
    return undefined;
  const severity = SEVERITIES.find((x) => x === r.severity);
  if (kind === "advisory" && !severity) return undefined;
  return {
    kind,
    subject: {
      namespace: s.namespace,
      ...(typeof s.release === "string" ? { release: s.release } : {}),
      ...(typeof s.author === "string" ? { author: s.author } : {}),
    },
    body: r.body,
    ...(kind === "advisory" ? { severity } : {}),
    ...(kind === "advisory" && typeof r.fixedIn === "string" ? { fixedIn: r.fixedIn } : {}),
    createdAt: r.createdAt,
  };
}

uses

used by