Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(open-api): production mode #2570

Merged
merged 10 commits into from
Aug 22, 2024
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
54 changes: 47 additions & 7 deletions src/core/config/resolvers/open-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,58 @@ import type { NitroOptions } from "nitropack/types";
import { join } from "pathe";

export async function resolveOpenAPIOptions(options: NitroOptions) {
if (options.dev && options.experimental.openAPI) {
options.handlers.push({
route: "/_nitro/openapi.json",
handler: join(runtimeDir, "internal/routes/openapi"),
});
// Check if the experimental.openAPI option is enabled
if (!options.experimental.openAPI) {
return;
}

// Only enable for dev and (opt-in) production
if (!options.dev && !options.openAPI?.production) {
return;
}

const shouldPrerender =
!options.dev && options.openAPI?.production === "prerender";

const handlersEnv = shouldPrerender ? "prerender" : "";

const prerenderRoutes: string[] = [];

// Add openapi json route
const jsonRoute = options.openAPI?.route || "/_openapi.json";
prerenderRoutes.push(jsonRoute);
options.handlers.push({
route: jsonRoute,
env: handlersEnv,
handler: join(runtimeDir, "internal/routes/openapi"),
});

// Scalar UI
if (options.openAPI?.ui?.scalar !== false) {
const scalarRoute = options.openAPI?.ui?.scalar?.route || "/_scalar";
prerenderRoutes.push(scalarRoute);
options.handlers.push({
route: "/_nitro/scalar",
route: options.openAPI?.ui?.scalar?.route || "/_scalar",
env: handlersEnv,
handler: join(runtimeDir, "internal/routes/scalar"),
});
}

// Swagger UI
if (options.openAPI?.ui?.swagger !== false) {
const swaggerRoute = options.openAPI?.ui?.swagger?.route || "/_swagger";
prerenderRoutes.push(swaggerRoute);
options.handlers.push({
route: "/_nitro/swagger",
route: swaggerRoute,
env: handlersEnv,
handler: join(runtimeDir, "internal/routes/swagger"),
});
}

// Prerender
if (shouldPrerender) {
options.prerender ??= {} as any;
options.prerender.routes ??= [];
options.prerender.routes.push(...prerenderRoutes);
}
}
2 changes: 1 addition & 1 deletion src/runtime/internal/routes/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { joinURL } from "ufo";
import { handlersMeta } from "#nitro-internal-virtual/server-handlers-meta";
import { useRuntimeConfig } from "../config";

// Served as /_nitro/openapi.json
// Served as /_openapi.json
export default eventHandler((event) => {
const runtimeConfig = useRuntimeConfig(event);

Expand Down
24 changes: 13 additions & 11 deletions src/runtime/internal/routes/scalar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,39 @@ import type { ReferenceConfiguration } from "@scalar/api-reference";
import { eventHandler } from "h3";
import { useRuntimeConfig } from "../config";

// Served as /_nitro/scalar
// Served as /_scalar
export default eventHandler((event) => {
const runtimeConfig = useRuntimeConfig(event);
const title = runtimeConfig.nitro.openAPI?.meta?.title || "API Reference";
const description = runtimeConfig.nitro.openAPI?.meta?.description || "";
const openAPIEndpoint =
runtimeConfig.nitro.openAPI?.route || "./_openapi.json";

// https://github.com/scalar/scalar
const configuration: ReferenceConfiguration = {
...runtimeConfig.nitro.openAPI?.ui?.scalar,
spec: {
url: "/_nitro/openapi.json",
...runtimeConfig.nitro.openAPI?.ui?.scalar?.spec,
},
const _config = runtimeConfig.nitro.openAPI?.ui
?.scalar as ReferenceConfiguration;
const scalarConfig: ReferenceConfiguration = {
..._config,
spec: { url: openAPIEndpoint, ..._config?.spec },
};

// The default page title
const title = "Nitro Scalar API Reference";

return /* html */ `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="${title}" />
<meta name="description" content="${description}" />
<title>${title}</title>
<style>
${configuration.theme ? null : customTheme}
${scalarConfig.theme ? null : customTheme}
</style>
</head>
<body>
<script
id="api-reference"
data-configuration="${JSON.stringify(configuration)
data-configuration="${JSON.stringify(scalarConfig)
.split('"')
.join("&quot;")}"
></script>
Expand Down
14 changes: 10 additions & 4 deletions src/runtime/internal/routes/swagger.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
import type { ReferenceConfiguration } from "@scalar/api-reference";
import { eventHandler } from "h3";
import { useRuntimeConfig } from "../config";

// https://github.com/swagger-api/swagger-ui

// Served as /_nitro/swagger
export default eventHandler((event) => {
const title = "Nitro Swagger UI";
const runtimeConfig = useRuntimeConfig(event);
const title = runtimeConfig.nitro.openAPI?.meta?.title || "API Reference";
const description = runtimeConfig.nitro.openAPI?.meta?.description || "";
const openAPIEndpoint =
runtimeConfig.nitro.openAPI?.route || "./_openapi.json";

const CDN_BASE = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@^5";
return /* html */ `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="${title}" />
<meta name="description" content="${description}" />
<title>${title}</title>
<link rel="stylesheet" href="${CDN_BASE}/swagger-ui.css" />
</head>
Expand All @@ -25,7 +31,7 @@ export default eventHandler((event) => {
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: "./openapi.json",
url: ${JSON.stringify(openAPIEndpoint)},
dom_id: "#swagger-ui",
presets: [
SwaggerUIBundle.presets.apis,
Expand Down
15 changes: 3 additions & 12 deletions src/types/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { RollupCommonJSOptions } from "@rollup/plugin-commonjs";
import type { ReferenceConfiguration } from "@scalar/api-reference";
import type { C12InputConfig, ConfigWatcher, ResolvedConfig } from "c12";
import type { WatchConfigOptions } from "c12";
import type { WatchOptions } from "chokidar";
Expand Down Expand Up @@ -33,6 +32,7 @@ import type {
import type { NitroHooks } from "./hooks";
import type { NitroModuleInput } from "./module";
import type { NitroFrameworkInfo } from "./nitro";
import type { NitroOpenAPIConfig } from "./openapi";
import type { NitroPreset } from "./preset";
import type { EsbuildOptions, NodeExternalsOptions } from "./rollup";
import type { RollupConfig } from "./rollup";
Expand Down Expand Up @@ -92,16 +92,7 @@ export interface NitroOptions extends PresetOptions {
* @see https://github.com/unjs/unwasm
*/
wasm?: UnwasmPluginOptions;
openAPI?: {
meta?: {
title?: string;
description?: string;
version?: string;
};
ui?: {
scalar?: ReferenceConfiguration;
};
};
openAPI?: NitroOpenAPIConfig;
experimental: {
legacyExternals?: boolean;
openAPI?: boolean;
Expand Down Expand Up @@ -359,7 +350,7 @@ export interface NitroRuntimeConfig extends NitroTypeskRuntimeConfig {
routeRules?: {
[path: string]: NitroRouteConfig;
};
openAPI?: NitroOptions["openAPI"];
openAPI?: NitroOpenAPIConfig;
};
[key: string]: any;
}
59 changes: 59 additions & 0 deletions src/types/openapi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { ReferenceConfiguration as ScalarConfig } from "@scalar/api-reference";

/**
* Nitro OpenAPI configuration
*/
export interface NitroOpenAPIConfig {
/**
* OpenAPI meta information
*/
meta?: {
title?: string;
description?: string;
version?: string;
};

/**
* OpenAPI json route
*
* Default is `/_openapi.json`
*/
route?: string;

/**
* Enable OpenAPI generation for production builds
*/
production?: false | "runtime" | "prerender";

/**
* UI configurations
*/
ui?: {
/**
* Scalar UI configuration
*/
scalar?:
| false
| (ScalarConfig & {
/**
* Scalar UI route
*
* Default is `/_scalar`
*/
route?: string;
});
/**
* Swagger UI configuration
*/
swagger?:
| false
| {
/**
* Swagger UI route
*
* Default is `/_swagger`
*/
route?: string;
};
};
}
1 change: 1 addition & 0 deletions test/fixture/nitro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ export default defineNitroConfig({
},
},
openAPI: {
production: "prerender",
meta: {
title: "Nitro Test Fixture",
description: "Nitro Test Fixture API",
Expand Down
8 changes: 8 additions & 0 deletions test/presets/azure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,14 @@ describe(
"rewrite": "/api/hey/index.html",
"route": "/api/hey",
},
{
"rewrite": "/_swagger/index.html",
"route": "/_swagger",
},
{
"rewrite": "/_scalar/index.html",
"route": "/_scalar",
},
{
"rewrite": "/prerender/index.html",
"route": "/prerender",
Expand Down
7 changes: 7 additions & 0 deletions test/presets/cloudflare-pages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,18 @@ describe.skipIf(isWindows)("nitro:preset:cloudflare-pages", async () => {
"/blog/static/*",
"/cf-pages-exclude/*",
"/build/*",
"/_openapi.json",
"/_openapi.json.br",
"/_openapi.json.gz",
"/_scalar",
"/_swagger",
"/_unignored.txt",
"/favicon.ico",
"/json-string",
"/prerender",
"/prerender-custom",
"/_swagger/index.html.br",
"/_swagger/index.html.gz",
"/api/hello",
"/api/hey",
"/prerender/index.html.br",
Expand Down
5 changes: 2 additions & 3 deletions test/presets/nitro-dev.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@ describe.skipIf(isCI)("nitro:preset:nitro-dev", async () => {

describe("openAPI", () => {
let spec: OpenAPI3;
it("/_nitro/openapi.json", async () => {
spec = ((await callHandler({ url: "/_nitro/openapi.json" })) as any)
.data;
it("/_openapi.json", async () => {
spec = ((await callHandler({ url: "/_openapi.json" })) as any).data;
expect(spec.openapi).to.match(/^3\.\d+\.\d+$/);
expect(spec.info.title).toBe("Nitro Test Fixture");
expect(spec.info.description).toBe("Nitro Test Fixture API");
Expand Down
6 changes: 6 additions & 0 deletions test/presets/vercel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ describe("nitro:preset:vercel", async () => {
expect(config).toMatchInlineSnapshot(`
{
"overrides": {
"_scalar/index.html": {
"path": "_scalar",
},
"_swagger/index.html": {
"path": "_swagger",
},
"api/hey/index.html": {
"path": "api/hey",
},
Expand Down