Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/configurable-redoc-attributes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"chanfana": minor
---

Allow configuring ReDoc HTML attributes through `redoc_options` on Hono and itty-router adapters and an optional second argument to `getReDocUI()`, including `show-extensions` filters.
28 changes: 28 additions & 0 deletions docs/openapi-configuration-customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,34 @@ While `RouterOptions` allows you to configure the overall OpenAPI document, you

Refer to the [Zod-to-OpenAPI documentation](https://github.com/asteasolutions/zod-to-openapi) and [Zod documentation](https://zod.dev/) for more details on schema customization options.

### `redoc_options`: Customizing ReDoc

Pass ReDoc configuration attributes through `redoc_options` when initializing either `fromHono` or `fromIttyRouter`:

```typescript
const openapi = fromHono(new Hono(), {
redoc_options: {
'show-extensions': 'x-filter-fields',
'disable-search': true,
},
});
```

Use kebab-case attribute names, as expected by the ReDoc HTML element. Values may be strings, numbers, or booleans. Boolean values are rendered explicitly as `"true"` or `"false"`; `undefined` values are omitted. With no options, the default ReDoc configuration is preserved.

For `show-extensions`, use `true` to display all supported custom extensions, `false` to hide them, or a comma-separated string such as `'x-filter-fields,x-other'` to select extensions.

The exported HTML helper accepts the same options directly:

```typescript
import { getReDocUI, type ReDocOptions } from 'chanfana';

const options: ReDocOptions = { 'show-extensions': 'x-filter-fields' };
const html = getReDocUI('/openapi.json', options);
```

Attribute values are HTML-escaped. Invalid attribute names, event handler attributes such as `onclick`, and `spec-url` throw an error. Set the schema URL through `openapi_url` (for automatic routes) or the first argument to `getReDocUI()`. Objects and functions are not accepted as attribute values.

## Serving OpenAPI Documentation (Swagger UI, ReDoc)

Chanfana makes it easy to serve interactive API documentation using Swagger UI and ReDoc. By default, if you provide `docs_url` and `openapi_url` (or `redoc_url` and `openapi_url`) in `RouterOptions`, Chanfana automatically sets up routes to serve these documentation UIs.
Expand Down
2 changes: 1 addition & 1 deletion src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export class OpenAPIHandler {
if (!redocDisabled && !openapiDisabled) {
const redocPath = this.options?.redoc_url || "/redocs";
this.router.get(redocPath, () => {
return new Response(getReDocUI(base + openapiUrl), {
return new Response(getReDocUI(base + openapiUrl, this.options.redoc_options), {
headers: {
"content-type": "text/html; charset=UTF-8",
},
Expand Down
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,16 @@ export interface ResponseConfig {
}
export type RouteParameter = AnyZodObject | ZodPipe<AnyZodObject, ZodType> | undefined;

/** ReDoc HTML attributes in kebab-case. Undefined values are omitted. */
export type ReDocOptions = Record<string, string | number | boolean | undefined>;

export interface RouterOptions {
base?: string;
schema?: Partial<OpenAPIObjectConfigV31 | OpenAPIObjectConfig>;
docs_url?: string | null;
redoc_url?: string | null;
/** ReDoc attributes in kebab-case, e.g. { "show-extensions": "x-filter-fields" }. */
redoc_options?: ReDocOptions;
openapi_url?: string | null;
raiseUnknownParameters?: boolean;
generateOperationIds?: boolean;
Expand Down
25 changes: 23 additions & 2 deletions src/ui.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { ReDocOptions } from "./types";

export function getSwaggerUI(rawSchemaUrl: string): string {
const schemaUrl = rawSchemaUrl.replace(/\/+(\/|$)/g, "$1"); // strip double & trailing splash
return `<!DOCTYPE html>
Expand Down Expand Up @@ -30,8 +32,27 @@ export function getSwaggerUI(rawSchemaUrl: string): string {
</html>`;
}

export function getReDocUI(rawSchemaUrl: string): string {
function escapeHtmlAttribute(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}

/** Render ReDoc with optional kebab-case HTML configuration attributes. */
export function getReDocUI(rawSchemaUrl: string, options?: ReDocOptions): string {
const schemaUrl = rawSchemaUrl.replace(/\/+(\/|$)/g, "$1"); // strip double & trailing splash
const attributes: string[] = [];
for (const [name, value] of Object.entries(options ?? {})) {
if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name) || /^on[a-z0-9]+$/.test(name) || name === "spec-url") {
throw new Error(`Invalid ReDoc attribute: ${name}`);
}
if (value !== undefined) {
attributes.push(` ${name}="${escapeHtmlAttribute(String(value))}"`);
}
}
return `<!DOCTYPE html>
<html>
<head>
Expand All @@ -54,7 +75,7 @@ export function getReDocUI(rawSchemaUrl: string): string {
</style>
</head>
<body>
<redoc spec-url="${schemaUrl}"></redoc>
<redoc spec-url="${escapeHtmlAttribute(schemaUrl)}"${attributes.join("")}></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@2.1.5/bundles/redoc.standalone.js" integrity="sha256-vlwzMMjDW4/OsppbdVKtRb/8L9lJT+LhqC+pQXnrX48=" crossorigin="anonymous"></script>
</body>
</html>`;
Expand Down
107 changes: 107 additions & 0 deletions tests/integration/redoc-options.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { Hono } from "hono";
import { AutoRouter } from "itty-router";
import { describe, expect, it } from "vitest";
import { fromHono, fromIttyRouter, getReDocUI, type ReDocOptions, type RouterOptions } from "../../src";

describe("ReDoc configuration attributes", () => {
it("preserves the default tag and normalizes schema paths with no options", () => {
const html = getReDocUI("/api//openapi.json/");
expect(html).toContain('<redoc spec-url="/api/openapi.json"></redoc>');
expect(getReDocUI("/api//openapi.json/", {})).toBe(html);
});

it("renders the extension filter requested in issue #376", () => {
expect(getReDocUI("/openapi.json", { "show-extensions": "x-filter-fields" })).toContain(
'<redoc spec-url="/openapi.json" show-extensions="x-filter-fields"></redoc>',
);
});

it("preserves primitive values and omits undefined options", () => {
const options: ReDocOptions = {
"show-extensions": false,
"disable-search": true,
"scroll-y-offset": 0,
"schema-definitions-tag-name": "",
"only-required-in-samples": true,
"hide-loading": undefined,
};
const html = getReDocUI("/openapi.json", options);
expect(html).toContain('show-extensions="false"');
expect(html).toContain('disable-search="true"');
expect(html).toContain('scroll-y-offset="0"');
expect(html).toContain('schema-definitions-tag-name=""');
expect(html).toContain('only-required-in-samples="true"');
expect(html).not.toContain("hide-loading");
expect(options["show-extensions"]).toBe(false);
});

it("supports comma-separated extension names", () => {
expect(getReDocUI("/openapi.json", { "show-extensions": "x-filter-fields,x-other" })).toContain(
'show-extensions="x-filter-fields,x-other"',
);
});

it("escapes attribute values and the schema URL", () => {
const html = getReDocUI("/openapi.json?name=\"<&'>", {
"schema-definitions-tag-name": "\"><script>alert(1)</script>&'",
});
expect(html).toContain('spec-url="/openapi.json?name=&quot;&lt;&amp;&#39;&gt;"');
expect(html).toContain('schema-definitions-tag-name="&quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;&amp;&#39;"');
expect(html).not.toContain("<script>alert(1)</script>");
});

it.each([
"",
"showExtensions",
"show_extensions",
"-invalid",
"bad--name",
'name"',
"bad name",
"onclick",
"onload",
"spec-url",
])("rejects invalid or reserved attribute %j", (name) => {
expect(() => getReDocUI("/openapi.json", { [name]: "value" })).toThrow(`Invalid ReDoc attribute: ${name}`);
});
});

describe.each(["hono", "itty-router"] as const)("ReDoc routes with %s", (adapter) => {
function createRouter(options: RouterOptions = {}) {
return adapter === "hono" ? fromHono(new Hono(), options) : fromIttyRouter(AutoRouter(), options);
}

it("serves configured attributes at the default documentation path", async () => {
const router = createRouter({ redoc_options: { "show-extensions": "x-filter-fields" } });
const response = await router.fetch(new Request("http://localhost/redocs"));
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("text/html; charset=UTF-8");
expect(await response.text()).toContain(
'<redoc spec-url="/openapi.json" show-extensions="x-filter-fields"></redoc>',
);
});

it("preserves the schema URL with a base path and custom documentation URLs", async () => {
const router = createRouter({
base: "/api",
redoc_url: "/reference",
openapi_url: "/schema.json",
redoc_options: { "show-extensions": true },
});
const path = adapter === "hono" ? "/api/reference" : "/reference";
const response = await router.fetch(new Request(`http://localhost${path}`));
expect(response.status).toBe(200);
expect(await response.text()).toContain('<redoc spec-url="/api/schema.json" show-extensions="true"></redoc>');
expect((await router.fetch(new Request("http://localhost/api/schema.json"))).status).toBe(200);
});

it.each(["redoc_url", "openapi_url"] as const)("keeps ReDoc disabled when %s is null", async (option) => {
const router = createRouter({
[option]: null,
redoc_options: { "show-extensions": true },
});
router.all("*", () => new Response("Not found", { status: 404 }));
const response = await router.fetch(new Request("http://localhost/redocs"));
expect(response.status).toBe(404);
});
});
17 changes: 17 additions & 0 deletions tests/types/redoc-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { getReDocUI, type ReDocOptions, type RouterOptions } from "../../src";

export const redocOptions: ReDocOptions = {
"show-extensions": "x-filter-fields",
"disable-search": false,
"scroll-y-offset": 0,
"hide-loading": undefined,
};

export const routerOptions: RouterOptions = { redoc_options: redocOptions };
export const defaultHtml: string = getReDocUI("/openapi.json");
export const configuredHtml: string = getReDocUI("/openapi.json", redocOptions);

export const invalidOptions: ReDocOptions = {
// @ts-expect-error ReDoc HTML attribute values must be primitives, not objects.
theme: { colors: { primary: { main: "blue" } } },
};
Loading