Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

16.2 KB
Raw Blame
/**
 * Shared translation-coverage engine for the frontend i18n suites.
 *
 * The editor and the portal both keep UI strings in a US-English source locale
 * (`public/locales/en-US/translation.toml`) and look them up with
 * react-i18next's `t()`. These helpers walk a project's source via the
 * TypeScript AST (finding static `t("...")` keys, `i18nKey` props, and dynamic
 * template-key shapes), flatten its locale to a key set, and report drift in
 * both directions:
 *   - **missing**: a key used in source with no entry in the locale
 *   - **unused**:  a locale key no source reference (static or dynamic) reaches
 *
 * The Vitest suites in `src/editor/core/tests/` run these over every entry in
 * {@link I18N_PROJECTS}, so one implementation guards both apps.
 */
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import ts from "typescript";
import { parse } from "smol-toml";

const HERE = path.dirname(fileURLToPath(import.meta.url)); // frontend/src/editor/core/i18n
const FRONTEND_ROOT = path.resolve(HERE, "../../../.."); // frontend
/** Repo root, for rendering source paths relative in CI annotations. */
export const REPO_ROOT = path.resolve(FRONTEND_ROOT, "..");

export interface TranslationProject {
  /** Group name in the test output. */
  name: string;
  /** Absolute path to the source tree to scan. */
  srcRoot: string;
  /** Absolute path to the en-US source locale. */
  localeFile: string;
  /** Other English locales that can receive new source strings. */
  additionalLocaleFiles?: string[];
  /** Static keys flagged as missing that are genuinely fine (false positives). */
  ignoredKeys?: Set<string>;
  /** Locale keys assembled at runtime; exempt from the unused check. */
  ignoredKeyPatterns?: RegExp[];
  /** Sanity floor: a working scan finds at least this many used keys. */
  minUsedKeys?: number;
  /** Sanity floor: a working parse finds at least this many locale keys. */
  minLocaleKeys?: number;
}

export interface MissingKey {
  key: string;
  fallback: string;
  /** Absolute path; relativise against {@link REPO_ROOT} for annotations. */
  file: string;
  line: number;
  column: number;
}

const IGNORED_DIRS = new Set(["tests", "__mocks__"]);
const IGNORED_FILE_PATTERNS = [
  /\.d\.ts$/,
  /\.test\./,
  /\.spec\./,
  /\.stories\./,
];
const LIKELY_TRANSLATION_USAGE_RE = /(?:^|[^\w$])t\s*\(|\.t\s*\(|\bi18nKey\b/;
const PLURAL_SUFFIX_RE = /_(zero|one|two|few|many|other)$/;

const front = (rel: string): string => path.join(FRONTEND_ROOT, rel);

/**
 * The projects the i18n suites guard. Each carries its own ignore lists: the
 * editor exempts a few runtime-assembled key families; the portal starts clean.
 */
export const I18N_PROJECTS: TranslationProject[] = [
  {
    name: "editor",
    // One project over the whole editor tree, including the portal layer. Portal
    // strings live under portal.* in the shared locale and are referenced with
    // that prefix in source (t("portal.users.title")), so they validate here
    // like any other key.
    srcRoot: front("src"),
    localeFile: front("public/locales/en-US/translation.toml"),
    additionalLocaleFiles: [front("public/locales/en-GB/translation.toml")],
    ignoredKeyPatterns: [
      // SignSettings / SavedSignaturesSection resolve every key as
      // t(`${scope}.${key}`); scope and leaf only ever exist as separate literals.
      /^(sign|addText|addImage)\./,
      // Super search's settings content matching (settingsContentSearch)
      // indexes whole subtrees via t(prefix, { returnObjects }).
      /^admin\.settings\./,
      /^settings\./,
      /^account\./,
      // [language] direction is read by the i18n layer, never as a UI string.
      /^language\.direction$/,
      // Portal source-type copy is referenced via metadata keys in
      // components/sources/sourceTypes.ts (t(field.labelKey)), invisible to the
      // static scan.
      /^portal\.sources\.types\./,
      // The connection catalogue (connectionTypes.ts) mirrors source types: every key is
      // t(`${PREFIX}.${id}.label`) / t(`${COMMON}.${field}.label`) with multi-segment const
      // prefixes, so the whole family is matched here rather than by the shape heuristic.
      /^portal\.connections\.(types|commonFields)\./,
      // Portal catalogue copy stored as i18n keys in api/<surface>.ts constants
      // (label maps, role/policy/journey catalogues) and rendered via
      // t(constant), invisible to the static scan.
      /^portal\.documents\.(status|audit)\./,
      /^portal\.components\.(maturity|billingUnit)\./,
      /^portal\.home\.(pipelineTemplates|pipelineStages)\./,
      /^portal\.procurement\.journeySteps\./,
      /^portal\.users\.roles\./,
      /^portal\.policies\.(categories|config|endpoints)\./,
      // The integration operations catalogue (stepOperations.ts) assembles every key as
      // t(`${PREFIX}.${id}.label`) where PREFIX is the multi-segment const
      // "portal.policies.operations" - the shape heuristic treats that interpolation as one
      // segment, so this whole catalogue-driven family is matched here instead.
      /^portal\.policies\.operations\./,
      // Failure-kind copy is keyed off the server's FailureKind enum and arrives as data, so no
      // frontend source names it. FailureKindTest asserts every kind has copy here.
      /^portal\.failures\.kind\./,
      // Server-sent keys rendered with t(thatKey), so nothing in source names them.
      /^portal\.failures\.disabled\./,
      /^portal\.failures\.action\./,
      // A kind's title and description arrive the same way, derived server-side from the kind
      // id, so adding a kind adds copy that no source file will ever name.
      /^portal\.failures\.kind\./,
      // Encryption panel copy keyed by backend enum values: key status, write
      // state, migration state, and the reason a status read was refused. Each
      // is t(`...${value}`) where the value comes from the API response.
      /^portal\.infrastructure\.encryption\.(status|writeState|unavailable)\./,
      /^portal\.infrastructure\.encryption\.migration\.state\./,
    ],
    minUsedKeys: 100,
    minLocaleKeys: 100,
  },
];

// Locale tables are shallow by design; the cap only trips on a pathological
// or malformed file and turns it into a clear error.
const MAX_LOCALE_DEPTH = 50;

/**
 * Flatten a parsed TOML locale to its set of leaf keys.
 *
 * Iterative (explicit-stack) traversal rather than recursion, so a deeply
 * nested or malformed locale walks the heap, never the call stack.
 */
export function flattenLocaleKeys(
  node: unknown,
  prefix = "",
  acc = new Set<string>(),
): Set<string> {
  const stack: Array<{ node: unknown; prefix: string; depth: number }> = [
    { node, prefix, depth: 0 },
  ];
  while (stack.length > 0) {
    const { node: current, prefix: currentPrefix, depth } = stack.pop()!;
    if (depth > MAX_LOCALE_DEPTH) {
      throw new Error(
        `Locale nesting exceeded ${MAX_LOCALE_DEPTH} levels at "${currentPrefix}"`,
      );
    }
    if (!current || typeof current !== "object" || Array.isArray(current)) {
      if (currentPrefix) acc.add(currentPrefix);
      continue;
    }
    for (const [childKey, value] of Object.entries(
      current as Record<string, unknown>,
    )) {
      stack.push({
        node: value,
        prefix: currentPrefix ? `${currentPrefix}.${childKey}` : childKey,
        depth: depth + 1,
      });
    }
  }
  return acc;
}

export function collectLocaleKeys(localeFile: string): Set<string> {
  // Callers pass fixed project paths from I18N_PROJECTS, but this reader is
  // exported: keep the resolved path inside the frontend tree so a future
  // caller can't turn it into a path-traversal read.
  const resolved = path.resolve(localeFile);
  if (
    resolved !== FRONTEND_ROOT &&
    !resolved.startsWith(FRONTEND_ROOT + path.sep)
  ) {
    throw new Error(`Locale path escapes the frontend root: ${localeFile}`);
  }
  return flattenLocaleKeys(parse(fs.readFileSync(resolved, "utf8")));
}

const getScriptKind = (file: string): ts.ScriptKind => {
  if (file.endsWith(".tsx")) return ts.ScriptKind.TSX;
  if (file.endsWith(".ts")) return ts.ScriptKind.TS;
  if (file.endsWith(".jsx")) return ts.ScriptKind.JSX;
  return ts.ScriptKind.JS;
};

const listSourceFiles = (roots: string[]): string[] =>
  roots
    .flatMap((root) =>
      ts.sys.readDirectory(root, [".ts", ".tsx", ".js", ".jsx"], undefined, [
        "**/*",
      ]),
    )
    .filter(
      (file) =>
        !file.split(path.sep).some((segment) => IGNORED_DIRS.has(segment)),
    )
    .filter((file) => !IGNORED_FILE_PATTERNS.some((re) => re.test(file)));

const hasPluralCoverage = (key: string, available: Set<string>): boolean =>
  [...available].some(
    (k) => k.startsWith(`${key}_`) && PLURAL_SUFFIX_RE.test(k),
  );

const getLookupKeys = (key: string): string[] => {
  const base = key.replace(PLURAL_SUFFIX_RE, "");
  return base === key ? [key] : [key, base];
};

/**
 * Static first-argument keys of `t()` calls plus `i18nKey` JSX props. Dynamic
 * (template) keys are out of scope here; see the unused check's shape matching.
 */
const extractStaticKeys = (file: string): MissingKey[] => {
  const code = fs.readFileSync(file, "utf8");
  if (!LIKELY_TRANSLATION_USAGE_RE.test(code)) return [];

  const sourceFile = ts.createSourceFile(
    file,
    code,
    ts.ScriptTarget.Latest,
    false,
    getScriptKind(file),
  );
  const found: MissingKey[] = [];

  const record = (node: ts.Node, key: string, fallback = "") => {
    // Pass sourceFile explicitly: the tree is parsed without parent links.
    const { line, character } = sourceFile.getLineAndCharacterOfPosition(
      node.getStart(sourceFile),
    );
    found.push({ key, fallback, file, line: line + 1, column: character + 1 });
  };

  const visit = (node: ts.Node) => {
    if (ts.isCallExpression(node)) {
      const callee = node.expression;
      const arg0 = node.arguments.at(0);
      const arg1 = node.arguments.at(1);
      const isT =
        (ts.isIdentifier(callee) && callee.text === "t") ||
        (ts.isPropertyAccessExpression(callee) && callee.name.text === "t");
      if (
        isT &&
        arg0 &&
        (ts.isStringLiteral(arg0) || ts.isNoSubstitutionTemplateLiteral(arg0))
      ) {
        const fallback =
          arg1 &&
          (ts.isStringLiteral(arg1) || ts.isNoSubstitutionTemplateLiteral(arg1))
            ? arg1.text
            : "";
        record(arg0, arg0.text, fallback);
      }
    }

    if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
      for (const attr of node.attributes.properties) {
        if (
          !ts.isJsxAttribute(attr) ||
          attr.name.getText(sourceFile) !== "i18nKey" ||
          !attr.initializer
        ) {
          continue;
        }
        const init = attr.initializer;
        if (ts.isStringLiteral(init)) {
          record(init, init.text);
        } else if (
          ts.isJsxExpression(init) &&
          init.expression &&
          ts.isStringLiteral(init.expression)
        ) {
          record(init.expression, init.expression.text);
        }
      }
    }

    ts.forEachChild(node, visit);
  };

  ts.forEachChild(sourceFile, visit);
  return found;
};

/**
 * Template-literal shapes that could form a dotted key, with each `${...}`
 * replaced by `*` (e.g. `nav.${id}` → `nav.*`). Collected from every template
 * (not just t() sites; keys are often assembled in helpers/constants), but
 * only kept if a shape carries an identifier-like static fragment.
 */
const extractTemplateShapes = (
  file: string,
  code: string,
  acc: Set<string>,
): void => {
  if (!code.includes("${")) return;

  const sourceFile = ts.createSourceFile(
    file,
    code,
    ts.ScriptTarget.Latest,
    false,
    getScriptKind(file),
  );

  const visit = (node: ts.Node): void => {
    if (ts.isTemplateExpression(node)) {
      let shape = node.head.text;
      for (const span of node.templateSpans) {
        shape += "*";
        shape += span.literal.text;
      }
      if (
        shape.includes(".") &&
        /[A-Za-z0-9_-]/.test(shape.replace(/\*/g, ""))
      ) {
        acc.add(shape);
      }
    }
    ts.forEachChild(node, visit);
  };

  ts.forEachChild(sourceFile, visit);
};

interface TrieNode {
  children: Map<number, TrieNode>;
  needle?: string;
}

/**
 * Which of `needles` appear as a substring of `text`.
 *
 * Same answer as `needles.filter((n) => text.includes(n))`, but walks the text
 * once against a trie of every needle rather than once per needle: the locale
 * carries thousands of keys and the joined source is tens of MB, so per-key
 * scanning dominated the suite's runtime.
 */
const findSubstrings = (
  text: string,
  needles: Iterable<string>,
): Set<string> => {
  const root: TrieNode = { children: new Map() };
  for (const needle of needles) {
    if (!needle) continue;
    let node = root;
    for (let i = 0; i < needle.length; i++) {
      const code = needle.charCodeAt(i);
      let next = node.children.get(code);
      if (!next) {
        next = { children: new Map() };
        node.children.set(code, next);
      }
      node = next;
    }
    node.needle = needle;
  }

  const found = new Set<string>();
  for (let start = 0; start < text.length; start++) {
    let node = root.children.get(text.charCodeAt(start));
    let at = start;
    while (node) {
      if (node.needle !== undefined) found.add(node.needle);
      at += 1;
      if (at >= text.length) break;
      node = node.children.get(text.charCodeAt(at));
    }
  }
  return found;
};

const shapeToMatcher = (shape: string): RegExp => {
  // Each * is one runtime path segment, so match `[^.]+` (not `.+`) to avoid
  // spanning key levels. Multi-segment interpolations use ignoredKeyPatterns.
  const escaped = shape
    .split("*")
    .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
    .join("[^.]+");
  return new RegExp(`^${escaped}$`);
};

/** Used keys with no locale entry (their fallback would render instead). */
export function findMissingKeys(project: TranslationProject): {
  missing: MissingKey[];
  usedCount: number;
} {
  const localeKeys = collectLocaleKeys(project.localeFile);
  for (const localeFile of project.additionalLocaleFiles ?? []) {
    for (const key of collectLocaleKeys(localeFile)) localeKeys.add(key);
  }
  const ignored = project.ignoredKeys ?? new Set<string>();

  // A used key resolves if the locale has it exactly, a plural variant covers
  // it, or it drills into an ancestor leaf, e.g. `t("...bullets.0")` indexing
  // the array stored at `...bullets` (arrays flatten to their base key).
  const resolves = (key: string): boolean => {
    if (localeKeys.has(key) || hasPluralCoverage(key, localeKeys)) return true;
    const parts = key.split(".");
    for (let i = parts.length - 1; i > 0; i--) {
      if (localeKeys.has(parts.slice(0, i).join("."))) return true;
    }
    return false;
  };

  const used = listSourceFiles([project.srcRoot])
    .flatMap(extractStaticKeys)
    .filter(({ key }) => !ignored.has(key));
  const missing = used.filter(({ key }) => !resolves(key));
  return { missing, usedCount: used.length };
}

/** Locale keys no source reference (static or dynamic) can reach. */
export function findUnusedKeys(project: TranslationProject): {
  unused: string[];
  localeCount: number;
} {
  const localeKeys = Array.from(collectLocaleKeys(project.localeFile));
  const files = listSourceFiles([project.srcRoot]);
  const contents = files.map((file) => fs.readFileSync(file, "utf8"));
  const source = contents.join("\n");

  const shapes = new Set<string>();
  files.forEach((file, i) => extractTemplateShapes(file, contents[i], shapes));
  const matchers = [...shapes].map(shapeToMatcher);
  const patterns = project.ignoredKeyPatterns ?? [];

  const candidates = localeKeys.filter(
    (key) => !patterns.some((re) => re.test(key)),
  );
  // Direct: the literal appears anywhere in source (static t(), i18nKey,
  // constants, comments). Plural variants count when their base is referenced.
  const referenced = findSubstrings(source, candidates.flatMap(getLookupKeys));

  const unused = candidates.filter((key) => {
    const lookups = getLookupKeys(key);
    if (lookups.some((k) => referenced.has(k))) return false;
    // Dynamic: the key matches a template-literal shape from source.
    return !lookups.some((k) => matchers.some((re) => re.test(k)));
  });

  return { unused, localeCount: localeKeys.length };
}