Skip to content

Build your personal knowledge base with Trilium Notes

feat(docs): generate User Guide pages from OpenAPI specs

Elian Doranb24f7fff9129
diff --git a/apps/edit-docs/src/docs_pipeline.ts b/apps/edit-docs/src/docs_pipeline.ts
index 0cc49df78c..b165566f27 100644
--- a/apps/edit-docs/src/docs_pipeline.ts
+++ b/apps/edit-docs/src/docs_pipeline.ts
@@ -18,6 +18,7 @@ import path from "path";
import { deferred } from "../../../packages/commons/src/index.js";
import { buildHelpBundle } from "./help_bundle_generator.js";
import { buildHelpMeta, serializeHelpMeta, stripAppVersion } from "./help_meta_generator.js";
+import { openApiToMarkdown, type OpenApiSpec } from "./openapi_markdown.js";
export interface NoteMapping {
rootNoteId: string;
@@ -32,6 +33,15 @@ export interface NoteMapping {
helpMeta?: string;
/** Where to write the rendered content of that tree. Relative to the configuration file. */
helpContent?: string;
+ /** Pages whose Markdown is generated from an OpenAPI document before every import. */
+ openApiPages?: OpenApiPage[];
+}
+
+export interface OpenApiPage {
+ /** A text note of this mapping with a Markdown data file. */
+ noteId: string;
+ /** The OpenAPI document in YAML. Relative to the configuration file. */
+ spec: string;
}
export interface Config {
@@ -61,7 +71,8 @@ export async function loadConfig(configPath?: string): Promise<Config> {
...mapping,
path: path.resolve(configDir, mapping.path),
helpMeta: mapping.helpMeta ? path.resolve(configDir, mapping.helpMeta) : undefined,
- helpContent: mapping.helpContent ? path.resolve(configDir, mapping.helpContent) : undefined
+ helpContent: mapping.helpContent ? path.resolve(configDir, mapping.helpContent) : undefined,
+ openApiPages: mapping.openApiPages?.map((page) => ({ ...page, spec: path.resolve(configDir, page.spec) }))
}))
};
}
@@ -138,6 +149,7 @@ export async function importData(path: string) {
export async function importMappings(mappings: NoteMapping[]) {
for (const mapping of mappings) {
if (!mapping.exportOnly) {
+ await writeOpenApiPages(mapping);
await importData(mapping.path);
}
}
@@ -150,6 +162,40 @@ export async function exportMappings(mappings: NoteMapping[], baseUrl: string) {
}
}
+/** Regenerates the Markdown of the mapping's `openApiPages` from their OpenAPI documents. */
+async function writeOpenApiPages(mapping: NoteMapping) {
+ if (!mapping.openApiPages?.length) {
+ return;
+ }
+
+ const meta = JSON.parse(await fs.readFile(path.join(mapping.path, "!!!meta.json"), "utf-8")) as NoteMetaFile;
+ for (const page of mapping.openApiPages) {
+ const dataFile = findDataFile(meta.files, page.noteId);
+ if (!dataFile?.endsWith(".md")) {
+ throw new Error(`OpenAPI page ${page.noteId} needs a Markdown data file in ${mapping.path}.`);
+ }
+
+ const spec = load(await fs.readFile(page.spec, "utf-8")) as OpenApiSpec;
+ await fs.writeFile(path.join(mapping.path, dataFile), openApiToMarkdown(spec));
+ }
+}
+
+/** The path of a note's data file relative to the export root, built from its ancestors' folders. */
+function findDataFile(notes: NoteMeta[], noteId: string, dir = ""): string | undefined {
+ for (const note of notes) {
+ if (note.noteId === noteId) {
+ return note.dataFileName ? path.join(dir, note.dataFileName) : undefined;
+ }
+
+ const found = findDataFile(note.children ?? [], noteId, path.join(dir, note.dirFileName ?? ""));
+ if (found) {
+ return found;
+ }
+ }
+
+ return undefined;
+}
+
export async function exportData(mapping: NoteMapping, baseUrl: string) {
const { path: outputPath, ignoredFiles: ignoredFileNames } = mapping;
const ignoredFiles = ignoredFileNames ? new Set(ignoredFileNames) : undefined;
diff --git a/apps/edit-docs/src/openapi_markdown.spec.ts b/apps/edit-docs/src/openapi_markdown.spec.ts
new file mode 100644
index 0000000000..56f0837fe1
--- /dev/null
+++ b/apps/edit-docs/src/openapi_markdown.spec.ts
@@ -0,0 +1,120 @@
+import { describe, expect, it } from "vitest";
+
+import { openApiToMarkdown, type OpenApiSpec } from "./openapi_markdown.js";
+
+const ENTITY_ID = { $ref: "#/components/schemas/EntityId" };
+
+describe("openApiToMarkdown", () => {
+ it("renders an operation with its parameters, request body and responses", () => {
+ const spec: OpenApiSpec = {
+ info: { title: "ETAPI", description: "External Trilium API" },
+ paths: {
+ "/notes/{noteId}": {
+ parameters: [{ name: "noteId", in: "path", required: true, schema: ENTITY_ID }],
+ patch: {
+ description: "Patch a note",
+ parameters: [{ $ref: "#/components/parameters/Force" }],
+ requestBody: {
+ required: true,
+ content: { "application/json": { schema: { $ref: "#/components/schemas/Note" } } }
+ },
+ responses: {
+ "200": {
+ description: "note updated",
+ content: { "application/json": { schema: { $ref: "#/components/schemas/Note" } } }
+ },
+ "default": { description: "unexpected error" }
+ }
+ }
+ }
+ },
+ components: {
+ parameters: {
+ Force: { name: "force", in: "query", schema: { type: "boolean" }, description: "skip checks" }
+ }
+ }
+ };
+
+ const markdown = openApiToMarkdown(spec);
+
+ expect(markdown).toContain("External Trilium API");
+ expect(markdown).toContain("## Endpoints");
+ expect(markdown).toContain("### `PATCH /notes/{noteId}`\n\nPatch a note");
+ // Path-level parameters come first, then the operation's own, resolved through `$ref`.
+ expect(markdown).toContain([
+ "| Name | In | Type | Required | Description |",
+ "| --- | --- | --- | --- | --- |",
+ "| `noteId` | path | `EntityId` | Yes | |",
+ "| `force` | query | `boolean` | No | skip checks |"
+ ].join("\n"));
+ expect(markdown).toContain("**Request body** (required)\n\n* `application/json`: `Note`");
+ expect(markdown).toContain([
+ "| Status | Description | Type |",
+ "| --- | --- | --- |",
+ "| `200` | note updated | `Note` |",
+ "| `default` | unexpected error | |"
+ ].join("\n"));
+ });
+
+ it("groups operations by their first tag when the spec has tags", () => {
+ const spec: OpenApiSpec = {
+ info: { title: "Internal" },
+ paths: {
+ "/api/notes": { get: { tags: [ "Notes" ], summary: "List notes", responses: {} } },
+ "/api/sync": { post: { tags: [ "Sync" ], responses: {} } },
+ "/api/tree": { get: { tags: [ "Notes" ], responses: {} } }
+ }
+ };
+
+ const markdown = openApiToMarkdown(spec);
+
+ expect(markdown).not.toContain("## Endpoints");
+ expect(markdown.indexOf("## Notes")).toBeLessThan(markdown.indexOf("### `GET /api/tree`"));
+ expect(markdown.indexOf("### `GET /api/tree`")).toBeLessThan(markdown.indexOf("## Sync"));
+ expect(markdown).toContain("### `GET /api/notes`\n\nList notes");
+ });
+
+ it("renders the schemas with their property types", () => {
+ const spec: OpenApiSpec = {
+ info: { title: "ETAPI" },
+ paths: {},
+ components: {
+ schemas: {
+ EntityId: { type: "string", description: "Unique ID" },
+ Note: {
+ type: "object",
+ description: "A note",
+ required: [ "noteId" ],
+ properties: {
+ noteId: { ...ENTITY_ID, description: "The note's ID" },
+ type: { type: "string", enum: [ "text", "code" ], description: "note type" },
+ attributes: { type: "array", items: { $ref: "#/components/schemas/Attribute" } },
+ dateCreated: { type: "string", format: "date-time", nullable: true },
+ parent: { oneOf: [ ENTITY_ID, { type: [ "string", "null" ] } ] },
+ content: { allOf: [ ENTITY_ID ], description: "Line one\nline | two" }
+ }
+ }
+ }
+ }
+ };
+
+ const markdown = openApiToMarkdown(spec);
+
+ expect(markdown).toContain("## Schemas");
+ expect(markdown).toContain("### `EntityId`\n\nUnique ID\n\nType: `string`");
+ expect(markdown).toContain([
+ "### `Note`",
+ "",
+ "A note",
+ "",
+ "| Property | Type | Required | Description |",
+ "| --- | --- | --- | --- |",
+ "| `noteId` | `EntityId` | Yes | The note's ID |",
+ "| `type` | `string` | No | note type. One of `text`, `code`. |",
+ "| `attributes` | `array of Attribute` | No | |",
+ "| `dateCreated` | `string (date-time) \\| null` | No | |",
+ "| `parent` | `EntityId \\| string \\| null` | No | |",
+ "| `content` | `EntityId` | No | Line one line \\| two |"
+ ].join("\n"));
+ });
+});
diff --git a/apps/edit-docs/src/openapi_markdown.ts b/apps/edit-docs/src/openapi_markdown.ts
new file mode 100644
index 0000000000..6e25c0ba3c
--- /dev/null
+++ b/apps/edit-docs/src/openapi_markdown.ts
@@ -0,0 +1,263 @@
+/**
+ * Renders an OpenAPI 3.x document as the Markdown body of a User Guide page. The page's title
+ * comes from its note, so the output starts with the API's description rather than an H1.
+ */
+
+export interface OpenApiSpec {
+ info: { title: string; description?: string };
+ paths: Record<string, PathItem>;
+ components?: {
+ schemas?: Record<string, Schema>;
+ parameters?: Record<string, Parameter>;
+ requestBodies?: Record<string, RequestBody>;
+ responses?: Record<string, Response>;
+ };
+}
+
+interface Reference {
+ $ref: string;
+}
+
+interface Schema {
+ $ref?: string;
+ type?: string | string[];
+ format?: string;
+ description?: string;
+ enum?: unknown[];
+ nullable?: boolean;
+ items?: Schema;
+ properties?: Record<string, Schema>;
+ required?: string[];
+ allOf?: Schema[];
+ oneOf?: Schema[];
+ anyOf?: Schema[];
+}
+
+interface Parameter {
+ name: string;
+ in: string;
+ required?: boolean;
+ description?: string;
+ schema?: Schema;
+}
+
+interface MediaTypes {
+ content?: Record<string, { schema?: Schema }>;
+}
+
+interface RequestBody extends MediaTypes {
+ description?: string;
+ required?: boolean;
+}
+
+interface Response extends MediaTypes {
+ description?: string;
+}
+
+interface Operation {
+ tags?: string[];
+ summary?: string;
+ description?: string;
+ parameters?: (Parameter | Reference)[];
+ requestBody?: RequestBody | Reference;
+ responses?: Record<string, Response | Reference>;
+}
+
+type PathItem = { parameters?: (Parameter | Reference)[] } & Partial<Record<HttpMethod, Operation>>;
+
+type HttpMethod = typeof HTTP_METHODS[number];
+
+const HTTP_METHODS = [ "get", "put", "post", "delete", "options", "head", "patch", "trace" ] as const;
+
+export function openApiToMarkdown(spec: OpenApiSpec): string {
+ const blocks: string[] = [];
+ if (spec.info.description) {
+ blocks.push(spec.info.description.trim());
+ }
+
+ for (const [ group, operations ] of groupOperations(spec)) {
+ blocks.push(`## ${group}`);
+ for (const operation of operations) {
+ blocks.push(...renderOperation(spec, operation));
+ }
+ }
+
+ const schemas = Object.entries(spec.components?.schemas ?? {});
+ if (schemas.length) {
+ blocks.push("## Schemas");
+ for (const [ name, schema ] of schemas) {
+ blocks.push(...renderSchema(name, schema));
+ }
+ }
+
+ return blocks.join("\n\n");
+}
+
+interface OperationEntry {
+ method: HttpMethod;
+ path: string;
+ pathItem: PathItem;
+ operation: Operation;
+}
+
+/** Groups operations by their first tag, in order of appearance; a spec without tags gets one group. */
+function groupOperations(spec: OpenApiSpec) {
+ const groups = new Map<string, OperationEntry[]>();
+ for (const [ path, pathItem ] of Object.entries(spec.paths)) {
+ for (const method of HTTP_METHODS) {
+ const operation = pathItem[method];
+ if (!operation) {
+ continue;
+ }
+
+ const group = operation.tags?.[0] ?? "Endpoints";
+ const entries = groups.get(group) ?? [];
+ entries.push({ method, path, pathItem, operation });
+ groups.set(group, entries);
+ }
+ }
+
+ return groups;
+}
+
+function renderOperation(spec: OpenApiSpec, { method, path, pathItem, operation }: OperationEntry) {
+ const blocks = [ `### \`${method.toUpperCase()} ${path}\`` ];
+ for (const text of [ operation.summary, operation.description ]) {
+ if (text) {
+ blocks.push(text.trim());
+ }
+ }
+
+ const parameters = [ ...pathItem.parameters ?? [], ...operation.parameters ?? [] ]
+ .map((parameter) => resolve<Parameter>(spec, parameter));
+ if (parameters.length) {
+ blocks.push("**Parameters**", table(
+ [ "Name", "In", "Type", "Required", "Description" ],
+ parameters.map((p) => [ code(p.name), p.in, code(typeOf(p.schema)), p.required ? "Yes" : "No", describe(p) ])
+ ));
+ }
+
+ if (operation.requestBody) {
+ const body = resolve<RequestBody>(spec, operation.requestBody);
+ blocks.push(body.required ? "**Request body** (required)" : "**Request body**");
+ if (body.description) {
+ blocks.push(body.description.trim());
+ }
+ blocks.push(Object.entries(body.content ?? {})
+ .map(([ mime, { schema } ]) => `* ${code(mime)}: ${code(typeOf(schema))}`)
+ .join("\n"));
+ }
+
+ const responses = Object.entries(operation.responses ?? {});
+ if (responses.length) {
+ blocks.push("**Responses**", table(
+ [ "Status", "Description", "Type" ],
+ responses.map(([ status, response ]) => {
+ const { description, content } = resolve<Response>(spec, response);
+ const types = new Set(Object.values(content ?? {}).map(({ schema }) => typeOf(schema)));
+ return [ code(status), description ?? "", [ ...types ].filter(Boolean).map(code).join(", ") ];
+ })
+ ));
+ }
+
+ return blocks;
+}
+
+function renderSchema(name: string, schema: Schema) {
+ const blocks = [ `### ${code(name)}` ];
+ if (schema.description) {
+ blocks.push(schema.description.trim());
+ }
+
+ if (!schema.properties) {
+ blocks.push(`Type: ${code(typeOf(schema))}`);
+ return blocks;
+ }
+
+ const required = new Set(schema.required);
+ blocks.push(table(
+ [ "Property", "Type", "Required", "Description" ],
+ Object.entries(schema.properties).map(([ property, propertySchema ]) => [
+ code(property),
+ code(typeOf(propertySchema)),
+ required.has(property) ? "Yes" : "No",
+ describe({ description: propertySchema.description, schema: propertySchema })
+ ])
+ ));
+ return blocks;
+}
+
+/** The type of a schema as one line, naming referenced schemas instead of expanding them. */
+function typeOf(schema: Schema | undefined): string {
+ if (!schema) {
+ return "";
+ }
+
+ let type: string;
+ if (schema.$ref) {
+ type = refName(schema.$ref);
+ } else if (schema.allOf) {
+ type = schema.allOf.map(typeOf).join(" & ");
+ } else if (schema.oneOf ?? schema.anyOf) {
+ type = (schema.oneOf ?? schema.anyOf ?? []).map(typeOf).join(" | ");
+ } else if (schema.type === "array") {
+ type = `array of ${typeOf(schema.items)}`;
+ } else if (schema.type) {
+ type = [ schema.type ].flat().join(" | ");
+ if (schema.format) {
+ type += ` (${schema.format})`;
+ }
+ } else {
+ type = schema.properties ? "object" : "any";
+ }
+
+ return schema.nullable ? `${type} | null` : type;
+}
+
+function describe({ description, schema }: { description?: string; schema?: Schema }) {
+ if (!schema?.enum) {
+ return description ?? "";
+ }
+
+ const values = `One of ${schema.enum.map((value) => code(String(value))).join(", ")}.`;
+ return description ? `${description.trim().replace(/(?<![.!?])$/, ".")} ${values}` : values;
+}
+
+function resolve<T extends object>(spec: OpenApiSpec, value: T | Reference): T {
+ if (!isReference(value)) {
+ return value;
+ }
+
+ // "#/components/parameters/Force" → spec.components.parameters.Force
+ let target: unknown = spec;
+ for (const segment of value.$ref.replace(/^#\//, "").split("/")) {
+ target = (target as Record<string, unknown> | undefined)?.[segment];
+ }
+ if (!target) {
+ throw new Error(`Cannot resolve ${value.$ref}`);
+ }
+ return target as T;
+}
+
+function isReference(value: object): value is Reference {
+ return "$ref" in value;
+}
+
+function refName(ref: string) {
+ return ref.slice(ref.lastIndexOf("/") + 1);
+}
+
+function table(headers: string[], rows: string[][]) {
+ return [ headers, headers.map(() => "---"), ...rows ]
+ .map((cells) => `| ${cells.map(cell).join(" | ")} |`)
+ .join("\n");
+}
+
+/** A table cell holds one line, and a pipe would end it early, even inside a code span. */
+function cell(text: string) {
+ return text.replace(/\s*\n\s*/g, " ").replaceAll("|", "\\|").trim();
+}
+
+function code(text: string) {
+ return text ? `\`${text}\`` : "";
+}