Files
lincodex/frontend/codegen/mock-patterns.ts
T

391 lines
14 KiB
TypeScript

// Post-generation step for the Orval MSW mocks.
//
// Orval 8.40 mocks a string schema that has a `pattern` with
// `faker.helpers.fromRegExp(pattern)`. faker prints anchors and non-capturing
// groups literally, and Orval drops minLength and maxLength for such a schema,
// so the mock fails the generated Zod schema. Orval has no option that keeps
// the Zod output and changes only this mock: its mock overrides match property
// names, not schema constraints, and an input transformer changes every
// output.
//
// This step rewrites each such call in the generated *.msw.ts files into
// `fakeFromPattern(pattern, { minLength, maxLength })` from
// src/shared/api/mock-pattern.ts. The bounds come from the OpenAPI document:
// the call's enclosing object property and the pattern identify the schema.
// The rewrite fails when a call has an unexpected form, when no schema
// matches, or when the bounds of schemas that match have no common value;
// schemas that match with different bounds share their intersection, so a contract
// change cannot silently produce invalid mocks. Running it again on its own
// output changes nothing.
//
// Usage: node ./codegen/mock-patterns.ts --spec <openapi.yml> --endpoints <dir> [--helper <file>]
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join, relative, resolve, sep } from "node:path";
import { argv, cwd, stdout } from "node:process";
import { fileURLToPath } from "node:url";
import ts from "typescript";
import { parse as parseYaml } from "yaml";
export interface LengthBounds {
readonly minLength?: number;
readonly maxLength?: number;
}
/** Property name, then pattern, then every distinct length bound found. */
export type PatternBoundsIndex = ReadonlyMap<string, ReadonlyMap<string, readonly LengthBounds[]>>;
export interface RewriteResult {
readonly text: string;
readonly rewrittenCalls: number;
}
const helperName = "fakeFromPattern";
const fakerModule = "@faker-js/faker";
const fakerCallee = "faker.helpers.fromRegExp";
// Keys whose values are sample data rather than schemas.
const exampleKeys = new Set(["example", "examples"]);
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function boundsKey(bounds: LengthBounds): string {
return `${bounds.minLength ?? ""}..${bounds.maxLength ?? ""}`;
}
function describeBounds(bounds: LengthBounds): string {
return `minLength ${bounds.minLength ?? "unset"}, maxLength ${bounds.maxLength ?? "unset"}`;
}
function resolveLocalReference(document: unknown, reference: string): unknown {
if (!reference.startsWith("#/")) {
throw new Error(`Only local references are supported, got ${reference}.`);
}
let current: unknown = document;
for (const segment of reference.slice(2).split("/")) {
const key = segment.replaceAll("~1", "/").replaceAll("~0", "~");
if (!isRecord(current) || !Object.hasOwn(current, key)) {
throw new Error(`Unresolvable reference ${reference}.`);
}
current = current[key];
}
return current;
}
function lengthBound(schema: Record<string, unknown>, key: "minLength" | "maxLength") {
const value = schema[key];
if (value === undefined) {
return undefined;
}
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
throw new Error(`${key} must be a non-negative integer, got ${String(value)}.`);
}
return value;
}
// Collects every patterned string schema that a property value can resolve
// to. It follows references, compositions, and array items, but not nested
// object properties, which have their own names.
function collectPatternedStrings(
document: unknown,
schema: unknown,
seenReferences: ReadonlySet<string>,
found: Map<string, LengthBounds[]>,
): void {
if (!isRecord(schema)) {
return;
}
const reference = schema["$ref"];
if (typeof reference === "string") {
if (!seenReferences.has(reference)) {
const target = resolveLocalReference(document, reference);
collectPatternedStrings(document, target, new Set([...seenReferences, reference]), found);
}
}
const pattern = schema["pattern"];
if (typeof pattern === "string") {
const minLength = lengthBound(schema, "minLength");
const maxLength = lengthBound(schema, "maxLength");
const bounds: LengthBounds = {
...(minLength === undefined ? {} : { minLength }),
...(maxLength === undefined ? {} : { maxLength }),
};
const known = found.get(pattern) ?? [];
if (!known.some((item) => boundsKey(item) === boundsKey(bounds))) {
known.push(bounds);
}
found.set(pattern, known);
}
for (const keyword of ["allOf", "oneOf", "anyOf", "prefixItems"]) {
const members = schema[keyword];
if (Array.isArray(members)) {
for (const member of members) {
collectPatternedStrings(document, member, seenReferences, found);
}
}
}
collectPatternedStrings(document, schema["items"], seenReferences, found);
}
/** Indexes the length bounds of patterned strings by property name. */
export function buildPatternBoundsIndex(document: unknown): PatternBoundsIndex {
const index = new Map<string, Map<string, LengthBounds[]>>();
const visited = new Set<unknown>();
function addProperty(name: string, schema: unknown): void {
const byPattern = index.get(name) ?? new Map<string, LengthBounds[]>();
collectPatternedStrings(document, schema, new Set(), byPattern);
if (byPattern.size > 0) {
index.set(name, byPattern);
}
}
function walk(node: unknown): void {
if (typeof node !== "object" || node === null || visited.has(node)) {
return;
}
visited.add(node);
if (Array.isArray(node)) {
node.forEach(walk);
return;
}
const properties = isRecord(node) ? node["properties"] : undefined;
if (isRecord(properties)) {
for (const [name, schema] of Object.entries(properties)) {
addProperty(name, schema);
}
}
for (const [key, value] of Object.entries(node)) {
if (!exampleKeys.has(key)) {
walk(value);
}
}
}
walk(document);
return index;
}
function lineOf(sourceFile: ts.SourceFile, node: ts.Node): number {
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
}
function enclosingPropertyName(node: ts.Node): string | undefined {
for (let current = node.parent; current !== undefined; current = current.parent) {
if (ts.isPropertyAssignment(current)) {
const name = current.name;
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
return name.text;
}
return undefined;
}
if (ts.isVariableStatement(current) || ts.isSourceFile(current)) {
return undefined;
}
}
return undefined;
}
function formatBoundsArgument(bounds: LengthBounds): string {
const parts = [
...(bounds.minLength === undefined ? [] : [`minLength: ${bounds.minLength}`]),
...(bounds.maxLength === undefined ? [] : [`maxLength: ${bounds.maxLength}`]),
];
return parts.length === 0 ? "" : `, {${parts.join(", ")}}`;
}
function findBounds(
index: PatternBoundsIndex,
property: string,
pattern: string,
location: string,
): LengthBounds {
const candidates = index.get(property)?.get(pattern) ?? [];
const [bounds] = candidates;
if (bounds === undefined) {
throw new Error(
`${location}: no schema property "${property}" with pattern ${JSON.stringify(pattern)} in the OpenAPI document.`,
);
}
if (candidates.length === 1) {
return bounds;
}
// The generated mock does not say which schema owns the call, so schemas
// that share a property name and a pattern share one set of bounds: the
// intersection. A value inside it satisfies every one of those schemas.
const minLength = Math.max(...candidates.map((item) => item.minLength ?? 0));
const maxima = candidates.flatMap((item) =>
item.maxLength === undefined ? [] : [item.maxLength],
);
const maxLength = maxima.length === 0 ? undefined : Math.min(...maxima);
if (maxLength !== undefined && minLength > maxLength) {
throw new Error(
`${location}: properties named "${property}" with pattern ${JSON.stringify(pattern)} have length bounds (${candidates
.map(describeBounds)
.join("; ")}) that no value satisfies together, so the mock bounds are ambiguous.`,
);
}
const anyMin = candidates.some((item) => item.minLength !== undefined);
return {
...(anyMin ? { minLength } : {}),
...(maxLength === undefined ? {} : { maxLength }),
};
}
/**
* Rewrites the faker pattern calls of one generated mock file. The helper
* specifier is the module path that the generated file imports the helper
* from.
*/
export function rewriteMockSource(
source: string,
fileName: string,
index: PatternBoundsIndex,
helperSpecifier: string,
): RewriteResult {
const sourceFile = ts.createSourceFile(
fileName,
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS,
);
const edits: { start: number; end: number; text: string }[] = [];
function visit(node: ts.Node): void {
if (
ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
node.expression.name.text === "fromRegExp"
) {
const location = `${fileName}:${lineOf(sourceFile, node)}`;
if (node.expression.getText(sourceFile) !== fakerCallee) {
throw new Error(`${location}: unexpected fromRegExp callee ${node.expression.getText()}.`);
}
const [argument, ...rest] = node.arguments;
if (argument === undefined || rest.length > 0 || !ts.isStringLiteral(argument)) {
throw new Error(`${location}: ${fakerCallee} must take one string literal.`);
}
const property = enclosingPropertyName(node);
if (property === undefined) {
throw new Error(`${location}: ${fakerCallee} is not the value of a named property.`);
}
const pattern = argument.text;
const bounds = findBounds(index, property, pattern, location);
edits.push({
start: node.getStart(sourceFile),
end: node.getEnd(),
text: `${helperName}(${JSON.stringify(pattern)}${formatBoundsArgument(bounds)})`,
});
return;
}
ts.forEachChild(node, visit);
}
visit(sourceFile);
const imports = sourceFile.statements.filter(ts.isImportDeclaration);
const moduleOf = (declaration: ts.ImportDeclaration) =>
ts.isStringLiteral(declaration.moduleSpecifier) ? declaration.moduleSpecifier.text : "";
const hasHelperImport = imports.some((declaration) => moduleOf(declaration) === helperSpecifier);
if (edits.length > 0 && !hasHelperImport) {
const fakerImport = imports.find((declaration) => moduleOf(declaration) === fakerModule);
if (fakerImport === undefined) {
throw new Error(`${fileName}: no ${fakerModule} import to place the helper import after.`);
}
edits.push({
start: fakerImport.getEnd(),
end: fakerImport.getEnd(),
text: `\n\nimport {\n ${helperName}\n} from '${helperSpecifier}';`,
});
}
let text = source;
for (const edit of edits.sort((left, right) => right.start - left.start)) {
text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
}
if (text.includes("fromRegExp")) {
throw new Error(`${fileName}: a fromRegExp reference remains after the rewrite.`);
}
const rewrittenCalls = edits.filter((edit) => edit.start !== edit.end).length;
return { text, rewrittenCalls };
}
function mockFiles(directory: string): string[] {
return readdirSync(directory, { recursive: true, encoding: "utf8" })
.filter((name) => name.endsWith(".msw.ts"))
.map((name) => join(directory, name))
.sort();
}
/** Returns the extensionless relative module specifier of `target`. */
export function moduleSpecifier(fromFile: string, target: string): string {
const path = relative(dirname(fromFile), target).replace(/\.ts$/, "").split(sep).join("/");
return path.startsWith(".") ? path : `./${path}`;
}
export function rewriteMockFiles(options: {
readonly specPath: string;
readonly endpointsDirectory: string;
readonly helperPath: string;
}): { readonly files: number; readonly calls: number } {
const document: unknown = parseYaml(readFileSync(options.specPath, "utf8"));
const index = buildPatternBoundsIndex(document);
let files = 0;
let calls = 0;
for (const file of mockFiles(options.endpointsDirectory)) {
const source = readFileSync(file, "utf8");
const result = rewriteMockSource(
source,
relative(cwd(), file),
index,
moduleSpecifier(file, options.helperPath),
);
if (result.text !== source) {
writeFileSync(file, result.text);
files += 1;
}
calls += result.rewrittenCalls;
}
return { files, calls };
}
function readOption(args: readonly string[], name: string): string | undefined {
const position = args.indexOf(name);
if (position === -1) {
return undefined;
}
const value = args[position + 1];
if (value === undefined || value.startsWith("--")) {
throw new Error(`${name} needs a value.`);
}
return value;
}
function main(args: readonly string[]): void {
const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const specPath = readOption(args, "--spec");
const endpointsDirectory = readOption(args, "--endpoints");
if (specPath === undefined || endpointsDirectory === undefined) {
throw new Error(
"Usage: mock-patterns.ts --spec <openapi.yml> --endpoints <dir> [--helper <file>]",
);
}
const helperPath = resolve(
readOption(args, "--helper") ?? join(frontendRoot, "src/shared/api/mock-pattern.ts"),
);
const result = rewriteMockFiles({
specPath: resolve(specPath),
endpointsDirectory: resolve(endpointsDirectory),
helperPath,
});
stdout.write(
`Mock patterns: rewrote ${result.calls} ${fakerCallee} calls in ${result.files} files.\n`,
);
}
const entryPoint = argv[1];
if (entryPoint !== undefined && resolve(entryPoint) === fileURLToPath(import.meta.url)) {
main(argv.slice(2));
}