feat: complete TASK-WP0-02 contract baseline
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
import { readFileSync, rmSync } from "node:fs";
|
||||
import { sep, resolve } from "node:path";
|
||||
|
||||
import { generateClient } from "./lib/generate-client.mjs";
|
||||
import {
|
||||
buildApiContracts,
|
||||
compareTrees,
|
||||
createOpenApiDocument,
|
||||
formattedJson,
|
||||
} from "./lib/openapi.mjs";
|
||||
|
||||
buildApiContracts();
|
||||
const document = await createOpenApiDocument();
|
||||
const expectedDocument = readFileSync("openapi/openapi.json", "utf8");
|
||||
const currentDocument = formattedJson(document);
|
||||
|
||||
const buildRoot = resolve(".build");
|
||||
const generatedRoot = resolve(buildRoot, "openapi-client-check");
|
||||
if (!generatedRoot.startsWith(`${buildRoot}${sep}`)) throw new Error("Generated check path escaped .build.");
|
||||
rmSync(generatedRoot, { force: true, recursive: true });
|
||||
await generateClient(resolve("openapi/openapi.json"), generatedRoot);
|
||||
|
||||
const clientDiff = compareTrees(resolve("apps/web/src/generated/api"), generatedRoot);
|
||||
const result = {
|
||||
client_diff: clientDiff,
|
||||
openapi: document.openapi,
|
||||
snapshot_match: currentDocument === expectedDocument,
|
||||
status: currentDocument === expectedDocument && clientDiff.length === 0 ? "passed" : "failed",
|
||||
};
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
if (result.status !== "passed") process.exit(1);
|
||||
@@ -0,0 +1,13 @@
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { generateClient } from "./lib/generate-client.mjs";
|
||||
import { buildApiContracts, createOpenApiDocument, formattedJson } from "./lib/openapi.mjs";
|
||||
|
||||
buildApiContracts();
|
||||
const document = await createOpenApiDocument();
|
||||
const snapshotPath = resolve("openapi/openapi.json");
|
||||
mkdirSync(resolve("openapi"), { recursive: true });
|
||||
writeFileSync(snapshotPath, formattedJson(document));
|
||||
await generateClient(snapshotPath, resolve("apps/web/src/generated/api"));
|
||||
console.log(JSON.stringify({ client: "generated", openapi: document.openapi, snapshot: "openapi/openapi.json" }));
|
||||
@@ -0,0 +1,89 @@
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
function identifier(value) {
|
||||
return value.replaceAll(/[^A-Za-z0-9_$]/g, "_");
|
||||
}
|
||||
|
||||
function schemaType(schema) {
|
||||
if (!schema || typeof schema !== "object") return "unknown";
|
||||
if (schema.$ref) return identifier(schema.$ref.split("/").at(-1));
|
||||
if (Object.hasOwn(schema, "const")) return JSON.stringify(schema.const);
|
||||
if (schema.enum) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
|
||||
if (schema.anyOf) return schema.anyOf.map(schemaType).join(" | ");
|
||||
if (schema.oneOf) return schema.oneOf.map(schemaType).join(" | ");
|
||||
if (Array.isArray(schema.type)) {
|
||||
return schema.type.map((type) => schemaType({ ...schema, type })).join(" | ");
|
||||
}
|
||||
if (schema.type === "array") return `Array<${schemaType(schema.items)}>`;
|
||||
if (schema.type === "boolean") return "boolean";
|
||||
if (schema.type === "integer" || schema.type === "number") return "number";
|
||||
if (schema.type === "null") return "null";
|
||||
if (schema.type === "string") return "string";
|
||||
if (schema.type === "object" || schema.properties) {
|
||||
const required = new Set(schema.required ?? []);
|
||||
const fields = Object.entries(schema.properties ?? {}).map(
|
||||
([name, child]) => ` ${JSON.stringify(name)}${required.has(name) ? "" : "?"}: ${schemaType(child)};`,
|
||||
);
|
||||
return fields.length ? `{\n${fields.join("\n")}\n}` : "Record<string, never>";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function operationResult(operation) {
|
||||
const response = operation.responses?.["200"];
|
||||
if (!response) return "unknown";
|
||||
if (response.content) {
|
||||
const media = response.content["application/json"] ?? response.content["text/event-stream"];
|
||||
if (media?.schema) return schemaType(media.schema);
|
||||
}
|
||||
return response.schema ? schemaType(response.schema) : "unknown";
|
||||
}
|
||||
|
||||
function operationMediaType(operation) {
|
||||
const content = operation.responses?.["200"]?.content;
|
||||
if (!content) return undefined;
|
||||
return Object.keys(content)[0];
|
||||
}
|
||||
|
||||
function operations(document) {
|
||||
const result = [];
|
||||
for (const [path, pathItem] of Object.entries(document.paths ?? {})) {
|
||||
for (const method of ["get", "post", "put", "patch", "delete"]) {
|
||||
const operation = pathItem[method];
|
||||
if (operation?.operationId) result.push({ method, operation, path });
|
||||
}
|
||||
}
|
||||
return result.sort((left, right) => left.operation.operationId.localeCompare(right.operation.operationId));
|
||||
}
|
||||
|
||||
export function generateClient(input, output) {
|
||||
const document = JSON.parse(readFileSync(input, "utf8"));
|
||||
const schemas = Object.entries(document.components?.schemas ?? {})
|
||||
.map(([key, schema]) => [schema.title ?? key, schema])
|
||||
.sort(([left], [right]) => left.localeCompare(right));
|
||||
const types = [
|
||||
"// Generated from openapi/openapi.json. Do not edit by hand.",
|
||||
...schemas.map(([name, schema]) => `export type ${identifier(name)} = ${schemaType(schema)};`),
|
||||
].join("\n\n");
|
||||
|
||||
const operationList = operations(document);
|
||||
const importedTypes = [...new Set(operationList.map(({ operation }) => operationResult(operation)).filter((type) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(type)))];
|
||||
const sdk = [
|
||||
"// Generated from openapi/openapi.json. Do not edit by hand.",
|
||||
importedTypes.length ? `import type { ${importedTypes.join(", ")} } from "./types.gen.js";` : "",
|
||||
"export interface ClientOptions { baseUrl?: string; fetch?: typeof globalThis.fetch; headers?: HeadersInit; }",
|
||||
...operationList.map(({ method, operation, path }) => {
|
||||
const resultType = operationResult(operation);
|
||||
if (operationMediaType(operation) === "text/event-stream") {
|
||||
return `export function ${identifier(operation.operationId)}(options: Pick<ClientOptions, "baseUrl"> = {}): string {\n return \`${"${options.baseUrl ?? \"\"}"}${path}\`;\n}`;
|
||||
}
|
||||
return `export async function ${identifier(operation.operationId)}(options: ClientOptions = {}): Promise<${resultType}> {\n const request = options.fetch ?? globalThis.fetch;\n const response = await request(\`${"${options.baseUrl ?? \"\"}"}${path}\`, { method: "${method.toUpperCase()}", headers: options.headers ?? {} });\n if (!response.ok) throw new Error(\`HTTP ${"${response.status}"}\`);\n return response.json() as Promise<${resultType}>;\n}`;
|
||||
}),
|
||||
"",
|
||||
].filter(Boolean).join("\n\n");
|
||||
|
||||
mkdirSync(output, { recursive: true });
|
||||
writeFileSync(resolve(output, "sdk.gen.ts"), `${sdk}\n`);
|
||||
writeFileSync(resolve(output, "types.gen.ts"), `${types}\n`);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { relative, resolve } from "node:path";
|
||||
|
||||
function runPnpm(args) {
|
||||
if (process.platform === "win32") {
|
||||
execFileSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `pnpm ${args.join(" ")}`], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
return;
|
||||
}
|
||||
execFileSync("pnpm", args, { stdio: "inherit" });
|
||||
}
|
||||
|
||||
export function buildApiContracts() {
|
||||
runPnpm(["--filter", "@dada/shared-contracts", "build"]);
|
||||
runPnpm(["--filter", "@dada/api", "build"]);
|
||||
}
|
||||
|
||||
export async function createOpenApiDocument() {
|
||||
const moduleUrl = new URL(`../../apps/api/dist/app.js?build=${Date.now()}`, import.meta.url);
|
||||
const { createApp } = await import(moduleUrl.href);
|
||||
const app = await createApp();
|
||||
await app.ready();
|
||||
const document = app.swagger();
|
||||
await app.close();
|
||||
return sortObject(document);
|
||||
}
|
||||
|
||||
export function formattedJson(value) {
|
||||
return `${JSON.stringify(sortObject(value), null, 2)}\n`;
|
||||
}
|
||||
|
||||
export function readTree(root) {
|
||||
const files = new Map();
|
||||
function visit(path) {
|
||||
for (const name of readdirSync(path)) {
|
||||
const child = resolve(path, name);
|
||||
if (statSync(child).isDirectory()) visit(child);
|
||||
else files.set(relative(root, child).replaceAll("\\", "/"), readFileSync(child, "utf8"));
|
||||
}
|
||||
}
|
||||
visit(root);
|
||||
return files;
|
||||
}
|
||||
|
||||
export function compareTrees(expectedRoot, actualRoot) {
|
||||
const expected = readTree(expectedRoot);
|
||||
const actual = readTree(actualRoot);
|
||||
const names = new Set([...expected.keys(), ...actual.keys()]);
|
||||
return [...names]
|
||||
.sort()
|
||||
.filter((name) => expected.get(name) !== actual.get(name))
|
||||
.map((name) => ({
|
||||
actual: actual.has(name),
|
||||
expected: expected.has(name),
|
||||
file: name,
|
||||
}));
|
||||
}
|
||||
|
||||
function sortObject(value) {
|
||||
if (Array.isArray(value)) return value.map(sortObject);
|
||||
if (!value || typeof value !== "object") return value;
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, child]) => [key, sortObject(child)]),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
const runId = process.env.DADA_TDD_RUN_ID ?? `wp0-02-green-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
|
||||
const runDirectory = resolve("artifacts", "tdd", runId);
|
||||
const apiCaseId = "TDD-WP0-API-001-schema-envelope";
|
||||
const eventCaseId = "TDD-WP0-EVT-001-rest-refetch";
|
||||
const apiDirectory = resolve(runDirectory, "cases", apiCaseId);
|
||||
const eventDirectory = resolve(runDirectory, "cases", eventCaseId);
|
||||
const playwrightDirectory = resolve(eventDirectory, "playwright");
|
||||
|
||||
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
|
||||
mkdirSync(apiDirectory, { recursive: true });
|
||||
mkdirSync(eventDirectory, { recursive: true });
|
||||
|
||||
const commandDefinitions = [
|
||||
{ command: "pnpm test:unit", args: ["test:unit"] },
|
||||
{ command: "pnpm test:api", args: ["test:api"] },
|
||||
{ command: "pnpm test:e2e", args: ["test:e2e"] },
|
||||
{ command: "pnpm validate:tdd-trace", args: ["validate:tdd-trace"] },
|
||||
];
|
||||
const startedAt = new Date().toISOString();
|
||||
const commands = [];
|
||||
|
||||
for (const definition of commandDefinitions) {
|
||||
const commandStartedAt = new Date().toISOString();
|
||||
const executable = process.platform === "win32" ? (process.env.ComSpec ?? "cmd.exe") : "pnpm";
|
||||
const args = process.platform === "win32"
|
||||
? ["/d", "/s", "/c", `pnpm ${definition.args.join(" ")}`]
|
||||
: definition.args;
|
||||
const execution = spawnSync(executable, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
DADA_EVIDENCE_DIR_API: apiDirectory,
|
||||
DADA_EVIDENCE_DIR_EVT: eventDirectory,
|
||||
DADA_PLAYWRIGHT_OUTPUT_DIR: playwrightDirectory,
|
||||
},
|
||||
stdio: "inherit",
|
||||
});
|
||||
commands.push({
|
||||
command: definition.command,
|
||||
exit_code: execution.status ?? 1,
|
||||
finished_at: new Date().toISOString(),
|
||||
started_at: commandStartedAt,
|
||||
});
|
||||
}
|
||||
|
||||
function findFile(root, target) {
|
||||
if (!existsSync(root)) return undefined;
|
||||
for (const name of readdirSync(root)) {
|
||||
const child = resolve(root, name);
|
||||
if (statSync(child).isDirectory()) {
|
||||
const nested = findFile(child, target);
|
||||
if (nested) return nested;
|
||||
} else if (name === target) return child;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const trace = findFile(playwrightDirectory, "trace.zip");
|
||||
if (trace) copyFileSync(trace, resolve(eventDirectory, "trace.zip"));
|
||||
|
||||
const commandEvidence = {
|
||||
commands,
|
||||
phase: "green",
|
||||
run_id: runId,
|
||||
schema_version: "1.0",
|
||||
};
|
||||
writeFileSync(resolve(apiDirectory, "commands.json"), `${JSON.stringify(commandEvidence, null, 2)}\n`);
|
||||
writeFileSync(resolve(eventDirectory, "commands.json"), `${JSON.stringify(commandEvidence, null, 2)}\n`);
|
||||
|
||||
const manifestBytes = readFileSync("tasks.manifest.json");
|
||||
const manifest = {
|
||||
path: "tasks.manifest.json",
|
||||
sha256: createHash("sha256").update(manifestBytes).digest("hex").toUpperCase(),
|
||||
};
|
||||
const commit = spawnSync("git", ["rev-parse", "--short", "HEAD"], { encoding: "utf8" }).stdout.trim();
|
||||
const worktreeDirty = spawnSync("git", ["status", "--porcelain"], { encoding: "utf8" }).stdout.trim().length > 0;
|
||||
const environment = {
|
||||
arch: process.arch,
|
||||
node: process.version.slice(1),
|
||||
os: process.platform,
|
||||
};
|
||||
|
||||
const cases = [
|
||||
{
|
||||
acceptance_criteria: [],
|
||||
directory: apiDirectory,
|
||||
evidence_refs: ["openapi.json", "snapshot-diff.json", "response.json", "redaction.json"],
|
||||
green_assertions: [
|
||||
"OpenAPI 3.1 snapshot and runtime schemas agree",
|
||||
"generated client matches the OpenAPI operations",
|
||||
"responses include a valid correlation ID",
|
||||
"error details accept only whitelisted non-sensitive fields",
|
||||
],
|
||||
layer: ["UNIT", "API"],
|
||||
parent_family: "TDD-WP0-API-001",
|
||||
requirements: ["NFR-05", "DevelopmentPlan 6.1", "DevelopmentPlan 6.6"],
|
||||
test_id: apiCaseId,
|
||||
},
|
||||
{
|
||||
acceptance_criteria: ["AC-20", "AC-30"],
|
||||
directory: eventDirectory,
|
||||
evidence_refs: ["sse-events.json", "network-timeline.json", "trace.zip"],
|
||||
green_assertions: [
|
||||
"events contain only fixed non-sensitive fields",
|
||||
"each event causes a REST refetch",
|
||||
"disconnects and event ID gaps cause bootstrap recovery",
|
||||
"configuration and runtime availability versions remain separate",
|
||||
],
|
||||
layer: ["API", "E2E"],
|
||||
parent_family: "TDD-WP0-EVT-001",
|
||||
requirements: ["PROJECT-04", "GEN-14", "NFR-05", "DevelopmentPlan 6.2"],
|
||||
test_id: eventCaseId,
|
||||
},
|
||||
];
|
||||
|
||||
const commandsPassed = commands.every((command) => command.exit_code === 0);
|
||||
const results = cases.map((testCase) => {
|
||||
const missingEvidence = testCase.evidence_refs.filter((file) => !existsSync(resolve(testCase.directory, file)));
|
||||
const passed = commandsPassed && missingEvidence.length === 0;
|
||||
const result = {
|
||||
acceptance_criteria: testCase.acceptance_criteria,
|
||||
automation: ["automated"],
|
||||
commit,
|
||||
environment,
|
||||
evidence_refs: testCase.evidence_refs,
|
||||
finished_at: new Date().toISOString(),
|
||||
fixture_ids: [],
|
||||
green_assertions: testCase.green_assertions,
|
||||
layer: testCase.layer,
|
||||
manifest,
|
||||
missing_evidence: missingEvidence,
|
||||
parent_family: testCase.parent_family,
|
||||
phase: "green",
|
||||
release_gate: ["work_package:WP-0", "release:P0-A"],
|
||||
requirements: testCase.requirements,
|
||||
run_id: runId,
|
||||
schema_version: "1.0",
|
||||
started_at: startedAt,
|
||||
status: passed ? "passed" : "failed",
|
||||
task_id: "TASK-WP0-02",
|
||||
test_id: testCase.test_id,
|
||||
work_package: "WP-0",
|
||||
worktree_under_test: worktreeDirty ? "uncommitted implementation" : "clean committed implementation",
|
||||
};
|
||||
writeFileSync(resolve(testCase.directory, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
|
||||
return result;
|
||||
});
|
||||
|
||||
const summary = {
|
||||
cases: results.map(({ missing_evidence, status, test_id }) => ({ missing_evidence, status, test_id })),
|
||||
run_id: runId,
|
||||
status: results.every((result) => result.status === "passed") ? "passed" : "failed",
|
||||
};
|
||||
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify(summary, null, 2)}\n`);
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
if (summary.status !== "passed") process.exit(1);
|
||||
Reference in New Issue
Block a user