feat: complete TASK-WP0-02 contract baseline

This commit is contained in:
suyx
2026-07-27 17:49:24 +08:00
parent ae20eaf01f
commit dbe3e73b91
28 changed files with 2540 additions and 23 deletions
+89
View File
@@ -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`);
}
+69
View File
@@ -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)]),
);
}