import { readdirSync, readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import ts from "typescript"; import { describe, expect, test } from "vitest"; const appDirectory = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const bridgeFile = path.join(appDirectory, "locale", "request-scoped-t.ts"); describe("request-scoped translation bridge", () => { test("prevents runtime use of the process-global i18next t API", () => { const violations = new Set(); for (const file of getSourceFiles(appDirectory)) { const source = readFileSync(file, "utf8"); const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS); const defaultImports = new Set(); for (const statement of sourceFile.statements) { if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== "i18next") { continue; } const importClause = statement.importClause; const namedBindings = importClause?.namedBindings; if (importClause?.isTypeOnly) { continue; } if (importClause?.name) { defaultImports.add(importClause.name.text); } if ( namedBindings && ts.isNamedImports(namedBindings) && namedBindings.elements.some((element) => !element.isTypeOnly && (element.propertyName ?? element.name).text === "t") ) { violations.add(path.relative(appDirectory, file)); } } if (file !== bridgeFile && !/\.test\.[cm]?[jt]sx?$/.test(file)) { visit(sourceFile, (node) => { if (ts.isPropertyAccessExpression(node) && node.name.text === "t" && ts.isIdentifier(node.expression) && defaultImports.has(node.expression.text)) { violations.add(path.relative(appDirectory, file)); } }); } } expect([...violations].sort()).toEqual([]); }); }); function getSourceFiles(directory: string): string[] { return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { const entryPath = path.join(directory, entry.name); if (entry.isDirectory()) { return getSourceFiles(entryPath); } return entry.isFile() && /\.tsx?$/.test(entry.name) ? [entryPath] : []; }); } function visit(node: ts.Node, callback: (node: ts.Node) => void): void { callback(node); ts.forEachChild(node, (child) => visit(child, callback)); }