102 lines
5.3 KiB
JavaScript
102 lines
5.3 KiB
JavaScript
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 operationBodyType(operation) {
|
|
const schema = operation.requestBody?.content?.["application/json"]?.schema;
|
|
return schema ? schemaType(schema) : undefined;
|
|
}
|
|
|
|
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.flatMap(({ operation }) => [
|
|
operationResult(operation),
|
|
operationBodyType(operation),
|
|
]).filter((type) => 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);
|
|
const bodyType = operationBodyType(operation);
|
|
if (operationMediaType(operation) === "text/event-stream") {
|
|
return `export function ${identifier(operation.operationId)}(options: Pick<ClientOptions, "baseUrl"> = {}): string {\n return \`${"${options.baseUrl ?? \"\"}"}${path}\`;\n}`;
|
|
}
|
|
if (bodyType) {
|
|
return `export async function ${identifier(operation.operationId)}(body: ${bodyType}, options: ClientOptions = {}): Promise<${resultType}> {\n const request = options.fetch ?? globalThis.fetch;\n const headers = new Headers(options.headers);\n headers.set("Content-Type", "application/json");\n const response = await request(\`${"${options.baseUrl ?? \"\"}"}${path}\`, { body: JSON.stringify(body), method: "${method.toUpperCase()}", headers });\n if (!response.ok) throw new Error(\`HTTP ${"${response.status}"}\`);\n return response.json() as Promise<${resultType}>;\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`);
|
|
}
|