Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

5.8 KB
Raw Blame
import fs from "fs";
import path from "path";

const translated: { text: string; stack?: string }[] = [];
let recording = false;

jest.mock("ttag", () => {
  const record = (
    strings: TemplateStringsArray | string,
    ...values: unknown[]
  ) => {
    const text = typeof strings === "string" ? strings : strings.join("{}");
    if (recording) {
      translated.push({ text, stack: new Error().stack });
    }
    return typeof strings === "string"
      ? strings
      : String.raw({ raw: strings }, ...values);
  };
  const chained = {
    t: record,
    jt: record,
    ngettext: record,
    msgid: record,
    gettext: record,
  };
  return {
    ...chained,
    c: () => chained,
    addLocale: jest.fn(),
    useLocale: jest.fn(),
    setDefaultLang: jest.fn(),
    default: {},
  };
});

const ROOT = path.resolve(__dirname, "../..");

const ROOTS = (
  process.env.I18N_IMPORT_ROOTS ?? "frontend/src,enterprise/frontend/src"
).split(",");

function sourceFiles(dir: string): string[] {
  const out: string[] = [];
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    const p = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      if (
        [
          "__mocks__",
          "__support__",
          "node_modules",
          ".storybook",
          "shared-tests",
          "test",
          "tests",
          // Generated by the SDK package build and gitignored, so not source.
          "cli-snippets-tmp",
          // Node scripts: they write build output when they are imported, and
          // they reach ESM-only packages that jest does not transform.
          "bin",
          "cli",
        ].includes(entry.name)
      ) {
        continue;
      }
      out.push(...sourceFiles(p));
    } else if (
      /\.tsx?$/.test(entry.name) &&
      !/\.spec\.tsx?$/.test(entry.name) &&
      !/(^|[.-])test-utils\.tsx?$|^test-/.test(entry.name) &&
      !/\.stories\.tsx?$/.test(entry.name) &&
      !entry.name.endsWith(".d.ts")
    ) {
      out.push(p);
    }
  }
  return out;
}

// A module that throws while it is imported hides the translations it would
// have run, so the guard fails on any import error that is not named here.
// None of these modules import ttag, and every module they pull in is visited
// on its own, because the scan walks source files rather than an entry graph.
const UNIMPORTABLE = new Set<string>([
  // Entry points: they read webpack globals and call into the plugin bundle.
  "frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts",
  "frontend/src/metabase/app-embed-mcp-public-path.ts",
  "frontend/src/metabase/app-embed-mcp.tsx",
  "frontend/src/metabase/app-embed.ts",
  "frontend/src/metabase/app-main.ts",
  "frontend/src/metabase/app-public.ts",
  "frontend/src/metabase/app.tsx",
  "enterprise/frontend/src/metabase-enterprise/sdk-iframe-embedding-script-plugins.ts",

  // Build tooling: node scripts and bundler configs, not app code.
  "enterprise/frontend/src/custom-viz/scripts/check-package-versions.ts",
  "enterprise/frontend/src/custom-viz/src/cli.ts",
  "enterprise/frontend/src/custom-viz/src/templates.ts",
  "enterprise/frontend/src/custom-viz/src/templates/vite.config.ts",
  "enterprise/frontend/src/custom-viz/vite.config.ts",
  "enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx",

  // Storybook data that reads a geojson asset webpack resolves.
  "frontend/src/metabase/static-viz/components/StaticChoropleth/stories-data.ts",
]);

describe("translation at import time", () => {
  it("no module translates while it is being imported", async () => {
    const files = ROOTS.flatMap((r) => sourceFiles(path.join(ROOT, r)));
    const unimportable: { file: string; error: unknown }[] = [];

    // Modules are imported outside the app, so many of them log on the way up,
    // and a few register jest hooks that cannot be nested inside a test.
    const consoleError = jest.spyOn(console, "error").mockImplementation();
    const consoleWarn = jest.spyOn(console, "warn").mockImplementation();
    const hookNames = [
      "beforeAll",
      "beforeEach",
      "afterEach",
      "afterAll",
    ] as const;
    const realHooks = hookNames.map(
      (name) => [name, globalThis[name]] as const,
    );
    for (const name of hookNames) {
      // globalThis is not typed with jest's hook registrars.
      (globalThis as unknown as Record<string, unknown>)[name] = () => {};
    }

    recording = true;
    for (const file of files) {
      try {
        await import(file);
      } catch (error) {
        unimportable.push({ file: path.relative(ROOT, file), error });
      }
    }
    recording = false;
    for (const [name, hook] of realHooks) {
      // globalThis is not typed with jest's hook registrars.
      (globalThis as unknown as Record<string, unknown>)[name] = hook;
    }
    consoleError.mockRestore();
    consoleWarn.mockRestore();

    const unexpected = unimportable
      .filter(({ file }) => !UNIMPORTABLE.has(file))
      .map(
        ({ file, error }) =>
          `${file}: ${error instanceof Error ? error.message : String(error)}`,
      );
    const stale = [...UNIMPORTABLE].filter((allowed) =>
      unimportable.every(({ file }) => file !== allowed),
    );
    expect({ unexpected, stale }).toEqual({ unexpected: [], stale: [] });

    const byModule = new Map<string, Set<string>>();
    for (const { text, stack } of translated) {
      const frames = (stack ?? "")
        .split("\n")
        .map((line) => line.match(/\(?(\/[^\s)]+\.tsx?):\d+:\d+\)?/)?.[1])
        .filter(
          (file): file is string =>
            Boolean(file) && !file!.includes("i18n-import-time"),
        )
        .map((file) => path.relative(ROOT, file));
      const key = frames.slice(0, 3).join("  <- ") || "unattributed";
      (byModule.get(key) ?? byModule.set(key, new Set()).get(key)!).add(text);
    }

    expect([...byModule.keys()]).toEqual([]);
  }, 600000);
});