fileProblem

tcmts.cli.codebase.fileProblem · #ifadjz73 · term · runs on the server

uses node:crypto

What's wrong with a file definition from another codebase, if anything: its IR must hash to its hash, and its content must be what the IR says (the text between its links, each link to what the IR names; or bytes with the IR's digest).

import { hashIR } from "#codebase/tcmts/core/hash";
import type { IR } from "#codebase/tcmts/core/hash";
import type { DefRecord } from "#codebase/tcmts/core/types";
import { createHash } from "node:crypto";

export function fileProblem(rec: DefRecord): string | undefined {
  let ir: IR[];
  try {
    ir = JSON.parse(rec.ir) as IR[];
  } catch {
    return "has an IR that isn't JSON";
  }
  if (ir[0] !== "File" || typeof ir[1] !== "string") return "isn't a file";
  if (hashIR(ir as IR) !== rec.hash) return "doesn't hash to its claimed hash";
  const parts = ir.slice(2);
  const bytes = parts[0];
  if (Array.isArray(bytes) && bytes[0] === "Bytes") {
    const digest = createHash("sha256").update(Buffer.from(rec.sourceText, "base64")).digest("hex");
    return parts.length === 1 && bytes[1] === digest ? undefined : "has bytes that aren't its own";
  }
  let at = 0;
  let link = 0;
  for (const p of parts) {
    if (typeof p === "string") {
      if (rec.sourceText.slice(at, at + p.length) !== p) return "has text that isn't its own";
      at += p.length;
      continue;
    }
    const span = rec.spans[link++];
    if (!Array.isArray(p) || p[0] !== "Ref" || !span || span.start !== at || span.hash !== p[1]) return "has links that aren't its own";
    at = span.end;
  }
  return at === rec.sourceText.length && link === rec.spans.length ? undefined : "has text that isn't its own";
}

uses

used by