diff --git a/.chronus/changes/fix-openapi3-server-variable-enum-default-2026-9-19-11-21-11.md b/.chronus/changes/fix-openapi3-server-variable-enum-default-2026-9-19-11-21-11.md new file mode 100644 index 00000000000..66fe2932925 --- /dev/null +++ b/.chronus/changes/fix-openapi3-server-variable-enum-default-2026-9-19-11-21-11.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@typespec/openapi3" +--- + +Report a new `missing-server-variable-default` warning when a server variable that has an `enum` has no default and the document is emitted for OpenAPI 3.1.0 or later, since those versions require the default to be one of the `enum` values. The emitted `default` stays an empty string. diff --git a/packages/openapi3/src/diagnostics/missing-server-variable-default.md b/packages/openapi3/src/diagnostics/missing-server-variable-default.md new file mode 100644 index 00000000000..556d6ae5aa0 --- /dev/null +++ b/packages/openapi3/src/diagnostics/missing-server-variable-default.md @@ -0,0 +1,20 @@ +This diagnostic is issued when a variable in the `@server` decorator has a fixed set of values (an enum, a union of string literals or a string literal) but no default, and the document is emitted for OpenAPI 3.1.0 or later. +Those versions require the `default` of a server variable to be one of its `enum` values. The emitter does not pick one for you, so the variable keeps an empty `default` and the document is not valid. + +To fix this issue, set a default on the server parameter. + +### Example + +```typespec +@server("https://{region}.example.com", "Regional endpoint", { + region: "westus" | "eastus", // No default +}) +``` + +Set a default: + +```typespec +@server("https://{region}.example.com", "Regional endpoint", { + region?: "westus" | "eastus" = "eastus", +}) +``` diff --git a/packages/openapi3/src/lib.ts b/packages/openapi3/src/lib.ts index 0a13d99e4ef..a3e3aa637f1 100644 --- a/packages/openapi3/src/lib.ts +++ b/packages/openapi3/src/lib.ts @@ -337,6 +337,13 @@ export const $lib = createTypeSpecLibrary({ default: paramMessage`Server variable '${"propName"}' must be assignable to 'string'. It must either be a string, enum of string or union of strings.`, }, }, + "missing-server-variable-default": { + severity: "warning", + docs: fileRef.fromPackageRoot("src/diagnostics/missing-server-variable-default.md"), + messages: { + default: paramMessage`Server variable '${"propName"}' has no default, but OpenAPI ${"openapiVersion"} requires its default to be one of its enum values. Set a default on the parameter.`, + }, + }, "invalid-format": { severity: "warning", messages: { diff --git a/packages/openapi3/src/openapi.ts b/packages/openapi3/src/openapi.ts index 8abec881c0d..2209a71b3f4 100644 --- a/packages/openapi3/src/openapi.ts +++ b/packages/openapi3/src/openapi.ts @@ -360,6 +360,11 @@ function createOAPIEmitter( // De-dupe the per-endpoint tags that will be added into the #/tags let tagsUsedInOperations: Set; + // Server parameters already warned about for a missing default, keyed by their declaration. + // Servers are resolved once per document and each version of a versioned service gets its own + // copy of the parameter, so without this the same warning would be reported for every version. + const serverVariablesWarnedForDefault = new Set(); + const typeNameOptions: TypeNameOptions = { // shorten type names by removing TypeSpec and service namespace namespaceFilter(ns) { @@ -547,6 +552,21 @@ function createOAPIEmitter( return isValid; } + function reportMissingServerVariableDefault(prop: ModelProperty) { + const key = prop.node ?? prop; + if (serverVariablesWarnedForDefault.has(key)) { + return; + } + serverVariablesWarnedForDefault.add(key); + diagnostics.add( + createDiagnostic({ + code: "missing-server-variable-default", + format: { propName: prop.name, openapiVersion: specVersion }, + target: prop, + }), + ); + } + function resolveServers(servers: HttpServer[]): OpenAPI3Server[] { return servers.map((server) => { const variables: Record = {}; @@ -569,6 +589,11 @@ function createOAPIEmitter( } else if (prop.type.kind === "String") { variable.enum = [prop.type.value]; } + // OpenAPI 3.1 and later require `default` to be one of the `enum` values (3.0 only says + // it should be). Picking one could choose the wrong value, so ask the author to set it. + if (!prop.defaultValue && variable.enum?.length && specVersion !== "3.0.0") { + reportMissingServerVariableDefault(prop); + } attachExtensions(program, prop, variable); variables[name] = variable; } diff --git a/packages/openapi3/test/servers.test.ts b/packages/openapi3/test/servers.test.ts index 321fd7645b5..c581fa96782 100644 --- a/packages/openapi3/test/servers.test.ts +++ b/packages/openapi3/test/servers.test.ts @@ -1,9 +1,22 @@ import { expectDiagnostics } from "@typespec/compiler/testing"; import { deepStrictEqual } from "assert"; import { it } from "vitest"; +import { emitOpenApiWithDiagnostics, TesterWithVersioning } from "./test-host.js"; import { supportedVersions, worksFor } from "./works-for.js"; -worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => { +worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version: specVersion }) => { + // OpenAPI 3.0 only says that a server variable default should be one of its enum values. + const missingDefaultWarnings = (name: string) => + specVersion === "3.0.0" + ? [] + : [ + { + code: "@typespec/openapi3/missing-server-variable-default", + severity: "warning" as const, + message: `Server variable '${name}' has no default, but OpenAPI ${specVersion} requires its default to be one of its enum values. Set a default on the parameter.`, + }, + ]; + it("set a basic server(url)", async () => { const res = await openApiFor( ` @@ -73,7 +86,7 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => { }); it("accepts an enum whose numeric members are all encoded as strings", async () => { - const res = await openApiFor( + const [res, diagnostics] = await emitOpenApiWithDiagnostics( ` @service(#{title: "My service"}) @server("https://{region}.example.com", "Regional account endpoint", {region: Region}) @@ -86,8 +99,10 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => { eastUs: 2, } `, + { "openapi-versions": [specVersion] }, ); - deepStrictEqual(res.servers[0].variables.region.enum, ["westus", "eastus"]); + expectDiagnostics(diagnostics, missingDefaultWarnings("region")); + deepStrictEqual(res.servers?.[0].variables?.region?.enum, ["westus", "eastus"]); }); it("emit diagnostic when a numeric enum member is left unencoded", async () => { @@ -212,7 +227,7 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => { }); it("set a server with enum properties", async () => { - const res = await openApiFor( + const [res, diagnostics] = await emitOpenApiWithDiagnostics( ` enum Region { westus, eastus } @service(#{title: "My service"}) @@ -221,7 +236,9 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => { }) namespace MyService {} `, + { "openapi-versions": [specVersion] }, ); + expectDiagnostics(diagnostics, missingDefaultWarnings("region")); deepStrictEqual(res.servers, [ { description: "Regional account endpoint", @@ -233,8 +250,24 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => { ]); }); - it("set a server with string literal", async () => { + it("set a server with enum properties with a default", async () => { const res = await openApiFor( + ` + enum Region { westus, eastus } + @service(#{title: "My service"}) + @server("https://{region}.example.com", "Regional account endpoint", { + region?: Region = Region.eastus, + }) + namespace MyService {} + `, + ); + deepStrictEqual(res.servers[0].variables, { + region: { default: "eastus", enum: ["westus", "eastus"] }, + }); + }); + + it("set a server with string literal", async () => { + const [res, diagnostics] = await emitOpenApiWithDiagnostics( ` enum Region { } @service(#{title: "My service"}) @@ -243,7 +276,9 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => { }) namespace MyService {} `, + { "openapi-versions": [specVersion] }, ); + expectDiagnostics(diagnostics, missingDefaultWarnings("region")); deepStrictEqual(res.servers, [ { description: "Regional account endpoint", @@ -256,7 +291,7 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => { }); it("set a server with unions type", async () => { - const res = await openApiFor( + const [res, diagnostics] = await emitOpenApiWithDiagnostics( ` enum Region { } @service(#{title: "My service"}) @@ -265,7 +300,9 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => { }) namespace MyService {} `, + { "openapi-versions": [specVersion] }, ); + expectDiagnostics(diagnostics, missingDefaultWarnings("region")); deepStrictEqual(res.servers, [ { description: "Regional account endpoint", @@ -276,6 +313,56 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => { }, ]); }); + + it("set a server with unions type with a default", async () => { + const res = await openApiFor( + ` + @service(#{title: "My service"}) + @server("https://{region}.example.com", "Regional account endpoint", { + region?: "westus" | "eastus" = "eastus", + }) + namespace MyService {} + `, + ); + deepStrictEqual(res.servers[0].variables, { + region: { default: "eastus", enum: ["westus", "eastus"] }, + }); + }); + + it("warns once for a server variable without a default in a versioned service", async () => { + const [{ outputs }, diagnostics] = await TesterWithVersioning.compileAndDiagnose( + ` + @versioned(Versions) + @service(#{title: "My service"}) + @server("{endpoint}/{apiVersion}", "Versioned endpoint", { + endpoint: url, + apiVersion: Versions, + }) + namespace MyService { + enum Versions { v1: "2024-01-01", v2: "2025-01-01" } + } + `, + { + compilerOptions: { + options: { + "@typespec/openapi3": { + "openapi-versions": [specVersion], + "output-file": "{version}.openapi.json", + }, + }, + }, + }, + ); + expectDiagnostics(diagnostics, missingDefaultWarnings("apiVersion")); + for (const version of ["2024-01-01", "2025-01-01"]) { + const document = JSON.parse(outputs[`${version}.openapi.json`]); + deepStrictEqual(document.servers[0].variables, { + endpoint: { default: "" }, + apiVersion: { default: "", enum: ["2024-01-01", "2025-01-01"] }, + }); + } + }); + it("set multiple servers", async () => { const res = await openApiFor( `