This commit is contained in:
MaKarin
2026-04-06 12:50:46 +03:00
commit 73ddb1a948
155 changed files with 26688 additions and 0 deletions

View File

@@ -0,0 +1,78 @@
# api-format → OpenAPI 3.0
Абстрактная заготовка под задачу: **из доменного описания API получить OpenAPI 3.0**, затем встроить в общий пайплайн (кнопка / CI / генератор).
## Что внутри
| Файл | Назначение |
|------|------------|
| `examples/api-format.example.json` | Пример **не-OpenAPI** формата: ресурсы, поля, операции, query для списка |
| `prompts/llm-system.md` | Системный промпт для LLM: «верни только JSON OpenAPI 3.0.3» |
| `convert.mjs` | CLI: режим `deterministic` (маппинг в коде) и `llm` (OpenAI API) |
## Пошаговая демонстрация в терминале
Чтобы **постепенно** увидеть: входной api-format → что делает конвертер → структура OpenAPI:
```bash
cd tools/api-format-to-openapi
npm run demo
```
С паузой после каждого шага (нажимай Enter):
```bash
npm run demo:pause
```
Результат кладётся в `demo-output/openapi.json`.
## Детерминированный режим (без LLM)
Подходит для **фиксированной** схемы `apiFormatVersion: "1"` как в примере.
```bash
cd tools/api-format-to-openapi
node convert.mjs --in examples/api-format.example.json --out ../../openapi.generated.json
```
Или через npm:
```bash
cd tools/api-format-to-openapi
npm run convert
```
## Режим LLM
Когда реальный формат отличается или богаче — прогон через модель с промптом из `prompts/llm-system.md`.
```bash
set OPENAI_API_KEY=sk-...
cd tools/api-format-to-openapi
node convert.mjs --mode llm --in path/to/your-api-format.json --out ../../openapi.llm.json
```
Переменные:
- `OPENAI_API_KEY` — обязательно
- `OPENAI_MODEL` — по умолчанию `gpt-4o-mini`
- `OPENAI_BASE_URL` — по умолчанию `https://api.openai.com/v1` (совместимо с прокси)
## HTTP-экспортёр для AID (NestJS)
В `server` добавлен модуль **`AidExportModule`**: `POST /aid/export/openapi` принимает `{ "apiFormat": {...}, "mode"?: "deterministic"|"llm" }` и возвращает `{ "openapi": {...} }`. Подробности: `server/src/aid-export/README.md`.
## Интеграция позже
1. Заменить/расширить `examples/api-format.example.json` под ваш настоящий контракт из «алабужского» гита.
2. Либо расширить `toOpenApiDeterministic` в `convert.mjs`, либо перейти на `--mode llm` с отточенным промптом.
3. Согласовать с AID точный URL, заголовки и (при необходимости) обёртку ответа; при необходимости добавить отдельный маршрут «сырой» OpenAPI без `{ openapi: ... }`.
## Валидация OpenAPI (опционально)
После генерации можно проверить спеку любым валидатором, например:
```bash
npx -y @apidevtools/swagger-cli validate ../../openapi.generated.json
```

View File

@@ -0,0 +1,341 @@
#!/usr/bin/env node
/**
* api-format → OpenAPI 3.0
*
* Режимы:
* --mode deterministic — маппинг только для схемы examples/api-format.example.json (и совместимых)
* --mode llm — отправка входного JSON в OpenAI Chat Completions (нужен OPENAI_API_KEY)
*
* Примеры:
* node convert.mjs --in examples/api-format.example.json --out ../../openapi.generated.json
* node convert.mjs --mode llm --in my-api.json --out openapi.json
*/
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
function parseArgs(argv) {
const out = { mode: "deterministic", input: null, output: null };
for (let i = 2; i < argv.length; i++) {
const a = argv[i];
if (a === "--mode") out.mode = argv[++i];
else if (a === "--in") out.input = argv[++i];
else if (a === "--out") out.output = argv[++i];
else if (a === "-h" || a === "--help") out.help = true;
}
return out;
}
function usage() {
console.log(`
Usage: node convert.mjs --in <api-format.json> --out <openapi.json> [--mode deterministic|llm]
Environment (llm mode):
OPENAI_API_KEY required
OPENAI_MODEL optional, default gpt-4o-mini
OPENAI_BASE_URL optional, default https://api.openai.com/v1
`);
}
/** @param {string} t */
function fieldToSchema(t) {
const map = {
string: { type: "string" },
uuid: { type: "string", format: "uuid" },
int: { type: "integer" },
integer: { type: "integer" },
number: { type: "number" },
float: { type: "number" },
boolean: { type: "boolean" },
date: { type: "string", format: "date" },
datetime: { type: "string", format: "date-time" },
};
return map[t] || { type: "string", description: `unknown type: ${t}` };
}
/**
* Детерминированная конвертация для apiFormatVersion "1" с полями как в example.
* @param {any} api
*/
function toOpenApiDeterministic(api) {
if (!api || api.apiFormatVersion !== "1") {
throw new Error(
'deterministic mode: ожидается apiFormatVersion "1". Для другого формата используйте --mode llm или расширьте маппинг в convert.mjs.',
);
}
const base = (api.server?.basePath || "/api").replace(/\/$/, "");
const info = api.info || { title: "API", version: "1.0.0" };
const paths = {};
const schemas = {};
for (const res of api.resources || []) {
const name = res.name;
const seg = res.pathSegment || name.toLowerCase();
const idParam = res.idParam || "id";
const idType = res.idType || "uuid";
const props = {};
const required = [];
for (const f of res.fields || []) {
let sch;
if (f.type === "enum" && Array.isArray(f.enumValues)) {
sch = { type: "string", enum: f.enumValues };
} else {
sch = { ...fieldToSchema(f.type) };
}
if (f.readOnly) sch.readOnly = true;
props[f.name] = sch;
if (f.required) required.push(f.name);
}
schemas[name] = {
type: "object",
properties: props,
...(required.length ? { required } : {}),
};
const listPath = `${base}/${seg}`;
const itemPath = `${base}/${seg}/{${idParam}}`;
const idSchema = fieldToSchema(idType);
const listQuery = [];
const lq = res.listQuery;
if (lq?.pagination) {
for (const p of lq.pagination) {
if (p === "_start" || p === "_end")
listQuery.push({ name: p, in: "query", schema: { type: "integer" }, description: "pagination" });
}
}
if (lq?.sort) {
for (const p of lq.sort) {
if (p === "_sort")
listQuery.push({ name: "_sort", in: "query", schema: { type: "string" }, description: "sort field" });
if (p === "_order")
listQuery.push({
name: "_order",
in: "query",
schema: { type: "string", enum: ["asc", "desc"] },
description: "sort order",
});
}
}
if (lq?.filters) {
for (const p of lq.filters) {
if (p === "q")
listQuery.push({ name: "q", in: "query", schema: { type: "string" }, description: "full-text search" });
else {
const field = (res.fields || []).find((x) => x.name === p);
const isEnum = field?.type === "enum";
listQuery.push({
name: p,
in: "query",
schema: isEnum
? { type: "array", items: { type: "string", enum: field.enumValues || [] } }
: { type: "string" },
style: isEnum ? "form" : undefined,
explode: isEnum ? true : undefined,
description: isEnum ? "repeat param for multiple values" : undefined,
});
}
}
}
const ops = new Set(res.operations || []);
if (ops.has("list")) {
paths[listPath] = paths[listPath] || {};
paths[listPath].get = {
tags: [name],
summary: `List ${name}`,
parameters: listQuery,
responses: {
"200": {
description: "OK",
content: {
"application/json": {
schema: {
type: "object",
properties: {
data: { type: "array", items: { $ref: `#/components/schemas/${name}` } },
total: { type: "integer" },
},
},
},
},
},
},
};
}
if (ops.has("create")) {
paths[listPath] = paths[listPath] || {};
paths[listPath].post = {
tags: [name],
summary: `Create ${name}`,
requestBody: {
required: true,
content: { "application/json": { schema: { $ref: `#/components/schemas/${name}` } } },
},
responses: {
"201": {
description: "Created",
content: { "application/json": { schema: { $ref: `#/components/schemas/${name}` } } },
},
"400": { description: "Bad request" },
},
};
}
if (ops.has("get")) {
paths[itemPath] = paths[itemPath] || {};
paths[itemPath].get = {
tags: [name],
summary: `Get ${name} by ${idParam}`,
parameters: [{ name: idParam, in: "path", required: true, schema: idSchema }],
responses: {
"200": {
description: "OK",
content: { "application/json": { schema: { $ref: `#/components/schemas/${name}` } } },
},
"404": { description: "Not found" },
},
};
}
if (ops.has("update")) {
paths[itemPath] = paths[itemPath] || {};
paths[itemPath].patch = {
tags: [name],
summary: `Update ${name}`,
parameters: [{ name: idParam, in: "path", required: true, schema: idSchema }],
requestBody: {
content: { "application/json": { schema: { $ref: `#/components/schemas/${name}` } } },
},
responses: {
"200": {
description: "OK",
content: { "application/json": { schema: { $ref: `#/components/schemas/${name}` } } },
},
"404": { description: "Not found" },
},
};
}
if (ops.has("delete")) {
paths[itemPath] = paths[itemPath] || {};
paths[itemPath].delete = {
tags: [name],
summary: `Delete ${name}`,
parameters: [{ name: idParam, in: "path", required: true, schema: idSchema }],
responses: {
"204": { description: "No content" },
"404": { description: "Not found" },
},
};
}
}
const doc = {
openapi: "3.0.3",
info: {
title: info.title,
version: info.version,
...(info.description ? { description: info.description } : {}),
},
servers: [{ url: base || "/" }],
paths,
components: {
schemas,
...(api.security?.type === "bearer" || api.security?.scheme === "JWT"
? {
securitySchemes: {
bearerAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT" },
},
}
: {}),
},
};
if (doc.components.securitySchemes) {
doc.security = [{ bearerAuth: [] }];
for (const method of Object.values(paths)) {
for (const op of Object.values(method)) {
if (op && typeof op === "object" && op.responses) op.security = [{ bearerAuth: [] }];
}
}
}
return doc;
}
async function toOpenApiLlm(apiJson) {
const key = process.env.OPENAI_API_KEY;
if (!key) throw new Error("OPENAI_API_KEY не задан");
const model = process.env.OPENAI_MODEL || "gpt-4o-mini";
const baseUrl = (process.env.OPENAI_BASE_URL || "https://api.openai.com/v1").replace(/\/$/, "");
const systemPath = resolve(__dirname, "prompts", "llm-system.md");
const system = readFileSync(systemPath, "utf8");
const user = JSON.stringify(apiJson, null, 2);
const res = await fetch(`${baseUrl}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${key}`,
},
body: JSON.stringify({
model,
temperature: 0.1,
messages: [
{ role: "system", content: system },
{ role: "user", content: `Преобразуй следующий api-format в OpenAPI 3.0.3 JSON:\n\n${user}` },
],
}),
});
if (!res.ok) {
const text = await res.text();
throw new Error(`OpenAI HTTP ${res.status}: ${text}`);
}
const data = await res.json();
const content = data.choices?.[0]?.message?.content;
if (!content) throw new Error("Пустой ответ от модели");
const trimmed = content.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "");
return JSON.parse(trimmed);
}
async function main() {
const args = parseArgs(process.argv);
if (args.help || !args.input || !args.output) {
usage();
process.exit(args.help ? 0 : 1);
}
const inputPath = resolve(process.cwd(), args.input);
const outputPath = resolve(process.cwd(), args.output);
const raw = readFileSync(inputPath, "utf8");
const api = JSON.parse(raw);
let openapi;
if (args.mode === "llm") {
openapi = await toOpenApiLlm(api);
} else {
openapi = toOpenApiDeterministic(api);
}
mkdirSync(dirname(outputPath), { recursive: true });
writeFileSync(outputPath, JSON.stringify(openapi, null, 2), "utf8");
console.log(`Written: ${outputPath}`);
}
main().catch((e) => {
console.error(e.message || e);
process.exit(1);
});

View File

@@ -0,0 +1,117 @@
#!/usr/bin/env node
/**
* Пошаговая демонстрация: api-format → OpenAPI 3.0 (детерминированный режим).
*
* node demo-steps.mjs — все шаги подряд в консоли
* node demo-steps.mjs --pause — пауза после каждого шага (Enter)
*
* Результат также пишется в demo-output/openapi.json рядом со скриптом.
*/
import { execFileSync } from "node:child_process";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const EXAMPLE = join(__dirname, "examples", "api-format.example.json");
const OUT_DIR = join(__dirname, "demo-output");
const OUT_OPENAPI = join(OUT_DIR, "openapi.json");
const usePause = process.argv.includes("--pause");
function banner(title) {
const line = "═".repeat(Math.min(60, title.length + 8));
console.log(`\n${line}\n ${title}\n${line}\n`);
}
async function pause(msg = "Нажми Enter, чтобы перейти к следующему шагу…") {
if (!usePause) return;
const rl = createInterface({ input, output });
await rl.question(msg);
rl.close();
}
async function main() {
console.clear?.();
banner("Шаг 0. Задача");
console.log(
"У нас есть описание API в СВОЁМ формате (api-format), не OpenAPI.\n" +
"Нужно получить стандартную спецификацию OpenAPI 3.0 — для Swagger, клиентов, AID.\n" +
"Сейчас покажем путь на учебном примере (детерминированный маппинг в convert.mjs).",
);
await pause();
banner("Шаг 1. Входной файл (фрагмент api-format)");
console.log(`Файл: ${EXAMPLE}\n`);
const rawIn = readFileSync(EXAMPLE, "utf8");
const apiFormat = JSON.parse(rawIn);
console.log(JSON.stringify(apiFormat, null, 2));
console.log(
"\n↑ Это НЕ OpenAPI. Здесь: версия формата, info, basePath, ресурс Equipment с полями и операциями CRUD.",
);
await pause();
banner("Шаг 2. Что делает конвертер (логика)");
console.log(`
• apiFormatVersion "1" → включается ветка toOpenApiDeterministic в convert.mjs
Ресурс Equipment → components.schemas.Equipment + пути /api/equipment и /api/equipment/{id}
• Поля (string, uuid, enum…) → JSON Schema в components.schemas
• listQuery → query-параметры (_start, _end, _sort, _order, q, status…)
• security bearer → components.securitySchemes + security на операциях
`);
await pause();
banner("Шаг 3. Запуск convert.mjs");
mkdirSync(OUT_DIR, { recursive: true });
const convertScript = join(__dirname, "convert.mjs");
console.log(`Команда:\n node convert.mjs --in examples/api-format.example.json --out demo-output/openapi.json\n`);
execFileSync(process.execPath, [convertScript, "--in", EXAMPLE, "--out", OUT_OPENAPI], {
stdio: "inherit",
});
console.log(`\nГотово. Файл: ${OUT_OPENAPI}`);
await pause();
banner("Шаг 4. Результат — структура OpenAPI");
const spec = JSON.parse(readFileSync(OUT_OPENAPI, "utf8"));
console.log(`openapi: ${spec.openapi}`);
console.log(`title: ${spec.info?.title}`);
console.log(`version: ${spec.info?.version}`);
console.log("\nПути (paths):");
for (const p of Object.keys(spec.paths || {}).sort()) {
const methods = Object.keys(spec.paths[p]).join(", ");
console.log(` ${p} [${methods}]`);
}
console.log("\nСхемы (components.schemas):", Object.keys(spec.components?.schemas || {}).join(", "));
await pause();
banner("Шаг 5. Фрагмент: GET список (одна операция)");
const listPath = Object.keys(spec.paths || {}).find((k) => k.endsWith("/equipment") && !k.includes("{"));
if (listPath && spec.paths[listPath]?.get) {
console.log(JSON.stringify({ [listPath]: { get: spec.paths[listPath].get } }, null, 2));
} else {
console.log("(путь списка не найден — открой demo-output/openapi.json)");
}
await pause();
banner("Шаг 6. Как проверить дальше");
console.log(`
1) Открой целиком: ${OUT_OPENAPI}
2) Валидация (из корня репозитория):
npx -y @apidevtools/swagger-cli validate tools/api-format-to-openapi/demo-output/openapi.json
3) Через Nest (сервер на 3001):
POST http://127.0.0.1:3001/aid/export/openapi
тело: { "apiFormat": <содержимое api-format.example.json>, "mode": "deterministic" }
4) Режим LLM (другой входной JSON):
node convert.mjs --mode llm --in your.json --out openapi.llm.json
(нужен OPENAI_API_KEY)
`);
console.log("Демо завершено.\n");
}
main().catch((e) => {
console.error(e);
process.exit(1);
});

View File

@@ -0,0 +1,36 @@
{
"apiFormatVersion": "1",
"info": {
"title": "TOiR Demo API",
"version": "1.0.0",
"description": "Абстрактный пример доменного описания API (не OpenAPI)."
},
"server": {
"basePath": "/api"
},
"security": {
"type": "bearer",
"scheme": "JWT"
},
"resources": [
{
"name": "Equipment",
"pathSegment": "equipment",
"idParam": "id",
"idType": "uuid",
"fields": [
{ "name": "id", "type": "uuid", "readOnly": true },
{ "name": "inventoryNumber", "type": "string", "required": true },
{ "name": "name", "type": "string", "required": true },
{ "name": "status", "type": "enum", "enumValues": ["Active", "Repair", "Decommissioned"] },
{ "name": "location", "type": "string" }
],
"operations": ["list", "get", "create", "update", "delete"],
"listQuery": {
"pagination": ["_start", "_end"],
"sort": ["_sort", "_order"],
"filters": ["q", "status"]
}
}
]
}

View File

@@ -0,0 +1,12 @@
{
"name": "api-format-to-openapi",
"private": true,
"type": "module",
"description": "Конвертация доменного api-format в OpenAPI 3.0 (детерминированно или через LLM)",
"scripts": {
"convert": "node convert.mjs --in examples/api-format.example.json --out ../../openapi.generated.json",
"convert:llm": "node convert.mjs --mode llm --in examples/api-format.example.json --out ../../openapi.llm.json",
"demo": "node demo-steps.mjs",
"demo:pause": "node demo-steps.mjs --pause"
}
}

View File

@@ -0,0 +1,30 @@
# Роль
Ты конвертер доменного описания API в спецификацию **OpenAPI 3.0.3** (JSON).
# Вход
Пользователь пришлёт один JSON-файл в произвольном «доменном» формате (api-format). В нём могут быть сущности, поля, типы, пути, операции, фильтры, авторизация.
# Выход
- Верни **только** валидный JSON объекта OpenAPI 3.0.3.
- Без markdown, без комментариев, без текста до или после JSON.
- Используй `openapi: "3.0.3"`.
- Опиши `info`, `servers`, при необходимости `tags`.
- Для каждой сущности/ресурса создай `components.schemas` и `paths` с типичными REST-операциями, если они указаны.
- Типы полей маппь так:
- `string``type: string`
- `uuid``type: string`, `format: uuid`
- `int` / `integer``type: integer`
- `number` / `float``type: number`
- `boolean``type: boolean`
- `date` / `datetime``type: string`, `format: date` или `date-time`
- `enum` + список значений → `type: string`, `enum: [...]`
- Для списков с пагинацией добавь query-параметры из входа (`_start`, `_end`, `_sort`, `_order`, фильтры).
- Для `401/403/404/500` добавь минимальные `responses` с `description`.
- Если во входе указана Bearer/JWT — добавь `components.securitySchemes` и `security` на путях или глобально.
# Если чего-то не хватает
Делай разумные допущения и кратко отражай их в `info.description` одним предложением.