From 03e132fdbe48a11d50f93c23a06dafeca73fa61a Mon Sep 17 00:00:00 2001 From: Timothee Guerin Date: Thu, 5 Nov 2026 08:51:37 -0500 Subject: [PATCH 1/5] feat(openapi3): support configurable component naming --- ...pi3-component-naming-2026-10-4-18-35-26.md | 17 ++ packages/openapi3/README.md | 30 +++ packages/openapi3/src/component-naming.ts | 60 ++++++ .../src/diagnostics/empty-component-name.md | 10 + packages/openapi3/src/lib.ts | 79 +++++++ packages/openapi3/src/openapi.ts | 75 ++++++- packages/openapi3/src/schema-emitter.ts | 47 ++++- packages/openapi3/test/component.test.ts | 199 ++++++++++++++++++ packages/openapi3/test/get-openapi.test.ts | 31 ++- packages/openapi3/test/multipart.test.ts | 34 ++- packages/openapi3/test/parameters.test.ts | 72 +++++++ .../docs/docs/emitters/openapi3/openapi.md | 28 +++ .../emitters/openapi3/reference/emitter.md | 30 +++ 13 files changed, 692 insertions(+), 20 deletions(-) create mode 100644 .chronus/changes/feat-openapi3-component-naming-2026-10-4-18-35-26.md create mode 100644 packages/openapi3/src/component-naming.ts create mode 100644 packages/openapi3/src/diagnostics/empty-component-name.md diff --git a/.chronus/changes/feat-openapi3-component-naming-2026-10-4-18-35-26.md b/.chronus/changes/feat-openapi3-component-naming-2026-10-4-18-35-26.md new file mode 100644 index 00000000000..b2aa0282965 --- /dev/null +++ b/.chronus/changes/feat-openapi3-component-naming-2026-10-4-18-35-26.md @@ -0,0 +1,17 @@ +--- +changeKind: feature +packages: + - "@typespec/openapi3" +--- + +Add independent component naming options for namespace qualification and alphanumeric-only schema and reusable parameter keys. Existing defaults are unchanged. + +For AWS API Gateway-compatible model names: + +```yaml +options: + "@typespec/openapi3": + component-name-character-set: alphanumeric +``` + +Use `component-name-strategy: name-only` to omit namespaces, or configure `{ kind: fqn, separator: "_" }` to change segment separators. Empty names and collisions after transformation are errors. \ No newline at end of file diff --git a/packages/openapi3/README.md b/packages/openapi3/README.md index 91e60720cd5..46222d56306 100644 --- a/packages/openapi3/README.md +++ b/packages/openapi3/README.md @@ -172,6 +172,36 @@ See https://github.com/OAI/OpenAPI-Specification/discussions/4622 for discussion | `kind` | `"parent-container" \| "fqn" \| "explicit-only"` | `"parent-container"` | Determines how to generate operation IDs when `@operationId` is not used.
Avaliable options are:
- `parent-container`: Uses the parent namespace and operation name to generate the ID.
- `fqn`: Uses the fully qualified name of the operation to generate the ID.
- `explicit-only`: Only use explicitly defined operation IDs. | | `separator` | `string` | | Separator used to join segment in the operation name. | +### `component-name-strategy` + +**Type:** `"fqn" | "name-only" | object { kind, separator }` + +**Options:** + +- `"fqn" | "name-only"` (default: `"fqn"`) + + Naming strategy for schema and reusable parameter component keys. + `fqn` preserves service-relative namespace qualification; `name-only` omits namespaces. + Friendly names override namespace qualification. Operation IDs and HTTP names are unchanged. + +- `object { kind, separator }` + +| Name | Type | Default | Description | +| ----------- | ---------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `kind` | `"fqn" \| "name-only"` | `"fqn"` | Naming strategy for schema and reusable parameter component keys.
`fqn` preserves service-relative namespace qualification; `name-only` omits namespaces.
Friendly names override namespace qualification. Operation IDs and HTTP names are unchanged. | +| `separator` | `string` | `"."` | Separator between namespace and parameter-property segments. May be empty. Does not replace punctuation within identifiers or friendly names. | + +### `component-name-character-set` + +**Type:** `"openapi" | "alphanumeric"` + +**Default:** `"openapi"` + +Character set for schema and reusable parameter component keys, independent of namespace qualification. +`openapi` preserves existing validation, allowing letters, digits, dots, hyphens, and underscores. +`alphanumeric` removes characters outside `[A-Za-z0-9]`, including punctuation in friendly names. +Empty names and collisions are errors. Does not affect operation IDs, HTTP names, or explicit external references. + ### `enum-strategy` **Type:** `"default" | "annotated"` diff --git a/packages/openapi3/src/component-naming.ts b/packages/openapi3/src/component-naming.ts new file mode 100644 index 00000000000..3053fa52f84 --- /dev/null +++ b/packages/openapi3/src/component-naming.ts @@ -0,0 +1,60 @@ +import type { Program, Type, TypeNameOptions } from "@typespec/compiler"; +import { getOpenAPITypeName } from "@typespec/openapi"; +import { reportDiagnostic } from "./lib.js"; +import type { ResolvedOpenAPI3EmitterOptions } from "./openapi.js"; +import { ensureValidComponentFixedFieldKey } from "./util.js"; + +export function hasCustomComponentNames(options: ResolvedOpenAPI3EmitterOptions): boolean { + return ( + options.componentNameStrategy?.kind === "name-only" || + (options.componentNameStrategy?.separator ?? ".") !== "." || + options.componentNameCharacterSet === "alphanumeric" + ); +} + +export function getComponentTypeName( + program: Program, + type: Type, + typeNameOptions: TypeNameOptions, + options: ResolvedOpenAPI3EmitterOptions, +): string { + const strategy = options.componentNameStrategy; + const name = getOpenAPITypeName(program, type, { + ...typeNameOptions, + nameOnly: strategy?.kind === "name-only", + }); + const separator = strategy?.separator ?? "."; + if (strategy?.kind === "name-only" || separator === ".") { + return name; + } + + const localName = getOpenAPITypeName(program, type, { ...typeNameOptions, nameOnly: true }); + // Friendly names, declaration expressions, and standard types are already unqualified. + if (name === localName) return name; + + const segments = [localName]; + let namespace = "namespace" in type ? type.namespace : undefined; + while (namespace && namespace.name !== "") { + if (typeNameOptions.namespaceFilter && !typeNameOptions.namespaceFilter(namespace)) break; + segments.unshift(namespace.name); + namespace = namespace.namespace; + } + return segments.join(separator); +} + +export function normalizeComponentName( + program: Program, + type: Type, + name: string, + options: ResolvedOpenAPI3EmitterOptions, +): string | undefined { + if (options.componentNameCharacterSet !== "alphanumeric") { + return ensureValidComponentFixedFieldKey(program, type, name); + } + const result = name.replace(/[^A-Za-z0-9]/g, ""); + if (result === "") { + reportDiagnostic(program, { code: "empty-component-name", format: { name }, target: type }); + return undefined; + } + return result; +} diff --git a/packages/openapi3/src/diagnostics/empty-component-name.md b/packages/openapi3/src/diagnostics/empty-component-name.md new file mode 100644 index 00000000000..1a863c8714d --- /dev/null +++ b/packages/openapi3/src/diagnostics/empty-component-name.md @@ -0,0 +1,10 @@ +This diagnostic is reported when `component-name-character-set: alphanumeric` removes every character from a schema or reusable parameter component key. + +For example, the following friendly name contains no ASCII letters or digits: + +```typespec +@friendlyName("___") +model User {} +``` + +Use an identifier or friendly name containing at least one ASCII letter or digit, or use the default `openapi` character set. Alphanumeric sanitization preserves case and removes Unicode characters rather than transliterating them. diff --git a/packages/openapi3/src/lib.ts b/packages/openapi3/src/lib.ts index 0a13d99e4ef..c8f371dfa33 100644 --- a/packages/openapi3/src/lib.ts +++ b/packages/openapi3/src/lib.ts @@ -9,6 +9,10 @@ export type OpenAPIVersion = "3.0.0" | "3.1.0" | "3.2.0"; export type ExperimentalParameterExamplesStrategy = "data" | "serialized"; /** Enum representation: a single `enum` schema or annotated `const` alternatives for OpenAPI 3.1 and later. */ export type EnumStrategy = "default" | "annotated"; +/** Namespace qualification for schema and reusable parameter component keys. */ +export type ComponentNameStrategy = "fqn" | "name-only"; +/** Allowed characters in schema and reusable parameter component keys. */ +export type ComponentNameCharacterSet = "openapi" | "alphanumeric"; /** User-supplied emitter configuration; omitted settings are normalized by `resolveOptions`. */ export interface OpenAPI3EmitterOptions { /** @@ -116,6 +120,31 @@ export interface OpenAPI3EmitterOptions { separator?: string; }; + /** + * Naming strategy for schema and reusable parameter component keys. + * `fqn` preserves current service-relative namespace qualification; `name-only` omits namespaces. + * Friendly names override namespace qualification. Separators join namespace and parameter-property + * segments, not punctuation within identifiers or friendly names. + * @default fqn + */ + "component-name-strategy"?: + | ComponentNameStrategy + | { + /** Namespace qualification strategy. */ + kind: ComponentNameStrategy; + /** Separator between namespace and parameter-property segments; defaults to `"."`. May be empty. */ + separator?: string; + }; + + /** + * Character set for schema and reusable parameter keys, independent of namespace qualification. + * `openapi` preserves existing validation. `alphanumeric` removes characters outside `[A-Za-z0-9]`, + * including punctuation in friendly names. Empty names and collisions are errors. + * Does not affect operation IDs, HTTP names, or explicit external references. + * @default openapi + */ + "component-name-character-set"?: ComponentNameCharacterSet; + /** * How to emit TypeSpec enums. * @@ -150,6 +179,17 @@ const operationIdStrategySchema = { ].join("\n"), } as const; +const componentNameStrategySchema = { + type: "string", + enum: ["fqn", "name-only"], + default: "fqn", + description: [ + "Naming strategy for schema and reusable parameter component keys.", + "`fqn` preserves service-relative namespace qualification; `name-only` omits namespaces.", + "Friendly names override namespace qualification. Operation IDs and HTTP names are unchanged.", + ].join("\n"), +} as const; + const EmitterOptionsSchema: JSONSchemaType = { type: "object", additionalProperties: false, @@ -293,6 +333,38 @@ const EmitterOptionsSchema: JSONSchemaType = { }, ], } as any, + "component-name-strategy": { + oneOf: [ + componentNameStrategySchema, + { + type: "object", + additionalProperties: false, + properties: { + kind: componentNameStrategySchema, + separator: { + type: "string", + nullable: true, + default: ".", + description: + "Separator between namespace and parameter-property segments. May be empty. Does not replace punctuation within identifiers or friendly names.", + }, + }, + required: ["kind"], + }, + ], + } as any, + "component-name-character-set": { + type: "string", + enum: ["openapi", "alphanumeric"], + nullable: true, + default: "openapi", + description: [ + "Character set for schema and reusable parameter component keys, independent of namespace qualification.", + "`openapi` preserves existing validation, allowing letters, digits, dots, hyphens, and underscores.", + "`alphanumeric` removes characters outside `[A-Za-z0-9]`, including punctuation in friendly names.", + "Empty names and collisions are errors. Does not affect operation IDs, HTTP names, or explicit external references.", + ].join("\n"), + }, "enum-strategy": { type: "string", enum: ["default", "annotated"], @@ -460,6 +532,13 @@ export const $lib = createTypeSpecLibrary({ default: paramMessage`Invalid key '${"value"}' used in a fixed field of the Component object. Only alphanumerics, dot (.), hyphen (-), and underscore (_) characters are allowed in keys.`, }, }, + "empty-component-name": { + severity: "error", + docs: fileRef.fromPackageRoot("src/diagnostics/empty-component-name.md"), + messages: { + default: paramMessage`Component name '${"name"}' contains no ASCII letters or digits after alphanumeric sanitization. Use an alphanumeric identifier or @friendlyName.`, + }, + }, "streams-not-supported": { severity: "warning", messages: { diff --git a/packages/openapi3/src/openapi.ts b/packages/openapi3/src/openapi.ts index 8abec881c0d..a1c0b0b9aa7 100644 --- a/packages/openapi3/src/openapi.ts +++ b/packages/openapi3/src/openapi.ts @@ -77,6 +77,7 @@ import { } from "@typespec/http"; import { getStreamMetadata } from "@typespec/http/experimental"; import { + checkDuplicateTypeName, getExtensions, getExternalDocs, getOpenAPITypeName, @@ -86,12 +87,19 @@ import { shouldInline, } from "@typespec/openapi"; import { stringify } from "yaml"; +import { + getComponentTypeName, + hasCustomComponentNames, + normalizeComponentName, +} from "./component-naming.js"; import { getRef } from "./decorators.js"; import type { OperationExamples } from "./examples.js"; import { getExampleOrExamples, resolveOperationExamples } from "./examples.js"; import type { JsonSchemaModule } from "./json-schema.js"; import { resolveJsonSchemaModule } from "./json-schema.js"; import type { + ComponentNameCharacterSet, + ComponentNameStrategy, EnumStrategy, FileType, OpenAPI3EmitterOptions, @@ -247,6 +255,7 @@ export function resolveOptions( } const specDir = openapiVersions.length > 1 ? "{openapi-version}" : ""; + const componentNameStrategy = resolvedOptions["component-name-strategy"] ?? "fqn"; return { fileTypes, newLine: resolvedOptions["new-line"], @@ -258,6 +267,15 @@ export function resolveOptions( sealObjectSchemas: resolvedOptions["seal-object-schemas"], parameterExamplesStrategy: resolvedOptions["experimental-parameter-examples"], operationIdStrategy: resolveOperationIdStrategy(resolvedOptions["operation-id-strategy"]), + componentNameStrategy: { + kind: + typeof componentNameStrategy === "string" + ? componentNameStrategy + : componentNameStrategy.kind, + separator: + typeof componentNameStrategy === "string" ? "." : (componentNameStrategy.separator ?? "."), + }, + componentNameCharacterSet: resolvedOptions["component-name-character-set"] ?? "openapi", enumStrategy, }; } @@ -291,6 +309,15 @@ function resolveOperationIdDefaultStrategySeparator(strategy: OperationIdStrateg /** Normalized emitter settings returned by `resolveOptions`, before document-specific path interpolation. */ export interface ResolvedOpenAPI3EmitterOptions { + /** Component qualification; defaults to service-relative `"fqn"` with `"."` separators. */ + componentNameStrategy?: { + /** Whether to include service-relative namespaces. */ + kind: ComponentNameStrategy; + /** Separator between namespace and parameter-property segments. */ + separator: string; + }; + /** Component key character set; defaults to existing OpenAPI validation. */ + componentNameCharacterSet?: ComponentNameCharacterSet; /** Formats requested for each document; inferred from the output extension or defaulted to YAML when absent. */ fileTypes: FileType[]; /** Resolved output path template; includes an OpenAPI-version directory when multiple specification versions are requested. */ @@ -347,6 +374,8 @@ function createOAPIEmitter( let visibilityUsage: VisibilityUsageTracker; let sseModule: SSEModule | undefined; let jsonSchemaModule: JsonSchemaModule | undefined; + const customComponentNames = hasCustomComponentNames(options); + let multipartSchemaTypes: Map; // Map model properties that represent shared parameters to their parameter // definition that will go in #/components/parameters. Inlined parameters do not go in @@ -508,6 +537,7 @@ function createOAPIEmitter( currentPath = root.paths; params = new Map(); + multipartSchemaTypes = new Map(); paramModels = new Set(); tagsUsedInOperations = new Set(); } @@ -1419,10 +1449,20 @@ function createOAPIEmitter( required: requiredProperties, }; - const name = + let name = "name" in body.type && body.type.name !== "" - ? getOpenAPITypeName(program, body.type, typeNameOptions) + ? getComponentTypeName(program, body.type, typeNameOptions, options) : undefined; + if (name !== undefined && customComponentNames) { + name = normalizeComponentName(program, body.type, name, options); + if (name) { + const existing = multipartSchemaTypes.get(name); + if (existing && existing !== body.type) { + checkDuplicateTypeName(program, body.type, name, root.components!.schemas!); + } + multipartSchemaTypes.set(name, body.type); + } + } if (name) { root.components!.schemas![name] = schema; } @@ -1806,14 +1846,25 @@ function createOAPIEmitter( function emitParameters() { for (const [property, param] of params) { - const key = getParameterKey( - program, - property, - param, - root.components!.parameters!, - typeNameOptions, - ); - const validKey = ensureValidComponentFixedFieldKey(program, property, key); + let validKey: string | undefined; + if (customComponentNames) { + const parent = property.model!; + const name = getComponentTypeName(program, parent, typeNameOptions, options); + const separator = options.componentNameStrategy?.separator ?? "."; + const key = parent.properties.size > 1 ? name + separator + property.name : name; + validKey = normalizeComponentName(program, property, key, options); + if (validKey === undefined) continue; + checkDuplicateTypeName(program, property, validKey, root.components!.parameters!); + } else { + const key = getParameterKey( + program, + property, + param, + root.components!.parameters!, + typeNameOptions, + ); + validKey = ensureValidComponentFixedFieldKey(program, property, key); + } root.components!.parameters![validKey] = { ...param }; for (const key of Object.keys(param)) { delete param[key]; @@ -1836,6 +1887,10 @@ function createOAPIEmitter( const schemas = root.components!.schemas!; const declarations = files[0].globalScope.declarations; for (const declaration of declarations) { + const multipartType = multipartSchemaTypes.get(declaration.name); + if (customComponentNames && multipartType) { + checkDuplicateTypeName(program, multipartType, declaration.name, schemas); + } schemas[declaration.name] = declaration.value as any; } } diff --git a/packages/openapi3/src/schema-emitter.ts b/packages/openapi3/src/schema-emitter.ts index 6aacca7ec33..7a294c59368 100644 --- a/packages/openapi3/src/schema-emitter.ts +++ b/packages/openapi3/src/schema-emitter.ts @@ -70,6 +70,7 @@ import { shouldInline, } from "@typespec/openapi"; import { attachExtensions } from "./attach-extensions.js"; +import { getComponentTypeName, normalizeComponentName } from "./component-naming.js"; import { getOneOf, getRef } from "./decorators.js"; import type { JsonSchemaModule } from "./json-schema.js"; import type { OpenAPI3EmitterOptions } from "./lib.js"; @@ -257,7 +258,7 @@ export class OpenAPI3SchemaEmitterBase< ); } - const baseName = getOpenAPITypeName(program, model, this.#typeNameOptions()); + const baseName = getComponentTypeName(program, model, this.#typeNameOptions(), this._options); const isMultipart = this.getContentType().startsWith("multipart/"); const name = isMultipart ? baseName + "MultiPart" : baseName; @@ -329,7 +330,12 @@ export class OpenAPI3SchemaEmitterBase< items: this.emitter.emitTypeReference(elementType), }); - const name = getOpenAPITypeName(this.emitter.getProgram(), array, this.#typeNameOptions()); + const name = getComponentTypeName( + this.emitter.getProgram(), + array, + this.#typeNameOptions(), + this._options, + ); return this.#createDeclaration(array, name, this.applyConstraints(array, schema as any)); } @@ -541,7 +547,12 @@ export class OpenAPI3SchemaEmitterBase< } enumDeclaration(en: Enum, name: string): EmitterOutput { - const baseName = getOpenAPITypeName(this.emitter.getProgram(), en, this.#typeNameOptions()); + const baseName = getComponentTypeName( + this.emitter.getProgram(), + en, + this.#typeNameOptions(), + this._options, + ); return this.#createDeclaration(en, baseName, new ObjectBuilder(this.enumSchema(en))); } @@ -569,7 +580,12 @@ export class OpenAPI3SchemaEmitterBase< unionDeclaration(union: Union, name: string): EmitterOutput { const schema = this.unionSchema(union); - const baseName = getOpenAPITypeName(this.emitter.getProgram(), union, this.#typeNameOptions()); + const baseName = getComponentTypeName( + this.emitter.getProgram(), + union, + this.#typeNameOptions(), + this._options, + ); return this.#createDeclaration(union, baseName, schema); } @@ -833,7 +849,12 @@ export class OpenAPI3SchemaEmitterBase< scalarDeclaration(scalar: Scalar, name: string): EmitterOutput { const isStd = isStdType(this.emitter.getProgram(), scalar); const schema = this.#getSchemaForScalar(scalar); - const baseName = getOpenAPITypeName(this.emitter.getProgram(), scalar, this.#typeNameOptions()); + const baseName = getComponentTypeName( + this.emitter.getProgram(), + scalar, + this.#typeNameOptions(), + this._options, + ); // Don't create a declaration for std types return isStd @@ -981,7 +1002,8 @@ export class OpenAPI3SchemaEmitterBase< } const skipNameValidation = type.kind === "Model" && type.templateMapper !== undefined; - if (!skipNameValidation) { + const alphanumeric = this._options.componentNameCharacterSet === "alphanumeric"; + if (!skipNameValidation && !alphanumeric) { name = ensureValidComponentFixedFieldKey(this.emitter.getProgram(), type, name); } @@ -994,8 +1016,17 @@ export class OpenAPI3SchemaEmitterBase< const shouldAddSuffix = usage !== undefined && usage.size > 1; const visibility = this.#getVisibilityContext(); - const fullName = - name + (shouldAddSuffix ? getVisibilitySuffix(visibility, Visibility.Read) : ""); + let fullName = name + (shouldAddSuffix ? getVisibilitySuffix(visibility, Visibility.Read) : ""); + if (alphanumeric) { + const normalized = normalizeComponentName( + this.emitter.getProgram(), + type, + fullName, + this._options, + ); + if (normalized === undefined) return {}; + fullName = normalized; + } const decl = this.emitter.result.declaration(fullName, schema); checkDuplicateTypeName( diff --git a/packages/openapi3/test/component.test.ts b/packages/openapi3/test/component.test.ts index e00fa63df4f..b04ebf2bcaa 100644 --- a/packages/openapi3/test/component.test.ts +++ b/packages/openapi3/test/component.test.ts @@ -1,5 +1,6 @@ import { expectDiagnostics } from "@typespec/compiler/testing"; import { describe, expect, it } from "vitest"; +import type { OpenAPI3EmitterOptions } from "../src/lib.js"; import type { OpenAPI3Document } from "../src/types.js"; import { supportedVersions, worksFor } from "./works-for.js"; @@ -237,6 +238,204 @@ const testCases: Case[] = [ ]; worksFor(supportedVersions, async (specHelpers) => { + describe("Component naming", () => { + const code = ` + @service namespace Demo { + namespace Models { + model User_Profile { id: string; } + } + @get op read(): Models.User_Profile; + } + `; + + it("preserves existing output with explicit defaults", async () => { + const current = await specHelpers.openApiFor(code); + const explicit = await specHelpers.openApiFor(code, { + "component-name-strategy": "fqn", + "component-name-character-set": "openapi", + }); + expect(explicit).toEqual(current); + expect(current.components.schemas["Models.User_Profile"]).toBeDefined(); + }); + + it.each([ + { strategy: "name-only", name: "User_Profile" }, + { strategy: { kind: "fqn", separator: "_" }, name: "Models_User_Profile" }, + { strategy: { kind: "fqn", separator: "" }, name: "ModelsUser_Profile" }, + ] satisfies { + strategy: OpenAPI3EmitterOptions["component-name-strategy"]; + name: string; + }[])("uses $strategy for component keys and references", async ({ strategy, name }) => { + const doc = await specHelpers.openApiFor(code, { "component-name-strategy": strategy }); + expect(Object.keys(doc.components.schemas)).toEqual([name]); + expect(doc.paths["/"].get.responses["200"].content["application/json"].schema).toEqual({ + $ref: `#/components/schemas/${name}`, + }); + }); + + it("sanitizes all schema kinds and friendly names without changing payload names", async () => { + const doc = await specHelpers.openApiFor( + ` + @service namespace Demo { + namespace Models { + scalar User_Id extends string; + enum User_Kind { normal } + union User_State { "active", "inactive" } + model User_List is User_Profile[]; + @friendlyName("Page-{name}", T) + model Page { value: T; } + model User_Profile { + user_id: User_Id; + kind: User_Kind; + state: User_State; + next?: Page; + } + } + @get op read(): Models.User_List; + } + `, + { "component-name-character-set": "alphanumeric" }, + ); + expect(Object.keys(doc.components.schemas)).toEqual([ + "ModelsUserId", + "ModelsUserKind", + "ModelsUserList", + "ModelsUserProfile", + "ModelsUserState", + "PageUserProfile", + ]); + expect(doc.components.schemas.ModelsUserList.items.$ref).toBe( + "#/components/schemas/ModelsUserProfile", + ); + expect(doc.components.schemas.ModelsUserProfile.properties.user_id.$ref).toBe( + "#/components/schemas/ModelsUserId", + ); + expect(doc.components.schemas.ModelsUserProfile.properties.next.$ref).toBe( + "#/components/schemas/PageUserProfile", + ); + }); + + it("treats literal dots and friendly names as atomic names", async () => { + const doc = await specHelpers.openApiFor( + ` + @service namespace Demo { + namespace Models { + model \`User.Profile\` {} + @friendlyName("Friendly.Name") model Other {} + } + } + `, + { "component-name-strategy": { kind: "fqn", separator: "_" } }, + ); + expect(Object.keys(doc.components.schemas)).toEqual(["Friendly.Name", "Models_User.Profile"]); + }); + + it("combines name-only with sanitization and preserves discriminator references", async () => { + const doc = await specHelpers.openApiFor( + ` + @service namespace Demo { + namespace Models { + @discriminator("pet_kind") model Pet_Base { pet_kind: string; } + model House_Cat extends Pet_Base { pet_kind: "house_cat"; } + } + @get op read(): Models.Pet_Base; + } + `, + { + "component-name-strategy": "name-only", + "component-name-character-set": "alphanumeric", + }, + ); + expect(doc.components.schemas.PetBase.discriminator).toEqual({ + propertyName: "pet_kind", + mapping: { house_cat: "#/components/schemas/HouseCat" }, + }); + expect(doc.components.schemas.HouseCat.allOf).toEqual([ + { $ref: "#/components/schemas/PetBase" }, + ]); + }); + + it("sanitizes generated envelopes and visibility variants together", async () => { + const doc = await specHelpers.openApiFor( + ` + model House_Cat { + value: string; + @visibility(Lifecycle.Create) secret: string; + } + @discriminated union Pet_Choice { house_cat: House_Cat } + @put op update(@body data: Pet_Choice): Pet_Choice; + `, + { "component-name-character-set": "alphanumeric" }, + ); + for (const suffix of ["", "CreateOrUpdate"]) { + expect(doc.components.schemas[`PetChoice${suffix}`].discriminator.mapping).toEqual({ + house_cat: `#/components/schemas/PetChoiceHousecat${suffix}`, + }); + expect(doc.components.schemas[`PetChoiceHousecat${suffix}`].properties.value.$ref).toBe( + `#/components/schemas/HouseCat${suffix}`, + ); + } + expect(doc.paths["/"].put.requestBody.content["application/json"].schema.$ref).toBe( + "#/components/schemas/PetChoiceCreateOrUpdate", + ); + expect(doc.paths["/"].put.responses["200"].content["application/json"].schema.$ref).toBe( + "#/components/schemas/PetChoice", + ); + }); + + it("leaves external references and debugging names unchanged", async () => { + const doc = await specHelpers.openApiFor( + ` + @useRef("../common.json#/components/schemas/User_Profile") model External_User {} + namespace Models { model User_Profile { external: External_User; } } + model Box { value: T; } + @get op read(): Box; + `, + { + "component-name-strategy": "name-only", + "component-name-character-set": "alphanumeric", + "include-x-typespec-name": "inline-only", + }, + ); + const schema = doc.paths["/"].get.responses["200"].content["application/json"].schema; + expect(schema["x-typespec-name"]).toBe("Box"); + expect(schema.properties.value.$ref).toBe("#/components/schemas/UserProfile"); + expect(doc.components.schemas.UserProfile.properties.external.$ref).toBe( + "../common.json#/components/schemas/User_Profile", + ); + }); + + it.each([ + { + options: { "component-name-strategy": "name-only" }, + code: ` + namespace A { model User {} } namespace B { model User {} } + op read(): A.User | B.User; + `, + }, + { + options: { "component-name-character-set": "alphanumeric" }, + code: ` + model User_Profile {} model UserProfile {} + `, + }, + ] satisfies { options: OpenAPI3EmitterOptions; code: string }[])( + "reports final-key collisions for $options", + async ({ options, code }) => { + const diagnostics = await specHelpers.diagnoseOpenApiFor(code, options); + expectDiagnostics(diagnostics, [{ code: "@typespec/openapi/duplicate-type-name" }]); + }, + ); + + it("rejects an empty sanitized friendly name", async () => { + const diagnostics = await specHelpers.diagnoseOpenApiFor( + `@friendlyName("___") model User {}`, + { "component-name-character-set": "alphanumeric" }, + ); + expectDiagnostics(diagnostics, [{ code: "@typespec/openapi3/empty-component-name" }]); + }); + }); + describe("Invalid component key", () => { it.each(testCases)( "$title should report diagnostics and replace by valid key", diff --git a/packages/openapi3/test/get-openapi.test.ts b/packages/openapi3/test/get-openapi.test.ts index 1d0757f8862..0d5f4f42020 100644 --- a/packages/openapi3/test/get-openapi.test.ts +++ b/packages/openapi3/test/get-openapi.test.ts @@ -1,5 +1,5 @@ import { expectDiagnostics } from "@typespec/compiler/testing"; -import { ok, strictEqual } from "assert"; +import { deepStrictEqual, ok, strictEqual } from "assert"; import { it } from "vitest"; import { getOpenAPI3 } from "../src/openapi.js"; import { ApiTester } from "./test-host.js"; @@ -49,3 +49,32 @@ it("has diagnostics", async () => { }, ]); }); + +it("applies component naming independently to each service through the object API", async () => { + const { program } = await ApiTester.compile(` + import "@typespec/http"; + using Http; + @service namespace First { + namespace Models { model User_Profile { first: string; } } + @get op read(): Models.User_Profile; + } + @service namespace Second { + namespace Models { model User_Profile { second: string; } } + @get op read(): Models.User_Profile; + } + `); + const records = await getOpenAPI3(program, { + "component-name-strategy": "name-only", + "component-name-character-set": "alphanumeric", + }); + strictEqual(records.length, 2); + for (const [index, record] of records.entries()) { + ok(!record.versioned); + expectDiagnostics(record.diagnostics, []); + const schemas = record.document.components!.schemas!; + deepStrictEqual(Object.keys(schemas), ["UserProfile"]); + deepStrictEqual(Object.keys((schemas.UserProfile as any).properties), [ + index === 0 ? "first" : "second", + ]); + } +}); diff --git a/packages/openapi3/test/multipart.test.ts b/packages/openapi3/test/multipart.test.ts index 69b9ca33e93..b05fa6ad238 100644 --- a/packages/openapi3/test/multipart.test.ts +++ b/packages/openapi3/test/multipart.test.ts @@ -1,9 +1,41 @@ +import { expectDiagnostics } from "@typespec/compiler/testing"; import { deepStrictEqual } from "assert"; import { describe, expect, it } from "vitest"; import type { OpenAPI3Encoding, OpenAPI3Schema, OpenAPISchema3_1 } from "../src/types.js"; import { supportedVersions, worksFor } from "./works-for.js"; -worksFor(supportedVersions, ({ openApiFor }) => { +worksFor(supportedVersions, ({ openApiFor, diagnoseOpenApiFor }) => { + it("uses configured component names for repeated named multipart bodies", async () => { + const res = await openApiFor( + ` + @service namespace Demo { + namespace Models { model Upload_Form { name: HttpPart; } } + @route("/a") op first(@multipartBody body: Models.Upload_Form): void; + @route("/b") op second(@multipartBody body: Models.Upload_Form): void; + } + `, + { "component-name-character-set": "alphanumeric" }, + ); + expect(Object.keys(res.components.schemas)).toEqual(["ModelsUploadForm"]); + for (const path of ["/a", "/b"]) { + expect(res.paths[path].post.requestBody.content["multipart/form-data"].schema).toEqual({ + $ref: "#/components/schemas/ModelsUploadForm", + }); + } + }); + + it("reports transformed multipart and regular schema collisions", async () => { + const diagnostics = await diagnoseOpenApiFor( + ` + model Upload_Form { name: HttpPart; } + model UploadForm { value: string; } + op upload(@multipartBody body: Upload_Form): UploadForm; + `, + { "component-name-character-set": "alphanumeric" }, + ); + expectDiagnostics(diagnostics, [{ code: "@typespec/openapi/duplicate-type-name" }]); + }); + it("create dedicated model for multipart", async () => { const res = await openApiFor( ` diff --git a/packages/openapi3/test/parameters.test.ts b/packages/openapi3/test/parameters.test.ts index 77051702847..a3fe271b168 100644 --- a/packages/openapi3/test/parameters.test.ts +++ b/packages/openapi3/test/parameters.test.ts @@ -247,6 +247,78 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version }) => { ]); }); + it("names reusable parameter keys independently of wire names", async () => { + const doc = await openApiFor( + ` + @service namespace Demo { + namespace Models { + model Query_Options { + @query("page-size") page_size: int32; + @header("x-user-id") user_id: string; + } + model Single_Option { @query("sort-by") sort_by: string; } + } + @get op read(...Models.Query_Options, ...Models.Single_Option): void; + } + `, + { + "component-name-strategy": { kind: "name-only", separator: "_" }, + "component-name-character-set": "alphanumeric", + }, + ); + expect(Object.keys(doc.components.parameters)).toEqual([ + "QueryOptionspagesize", + "QueryOptionsuserid", + "SingleOption", + ]); + expect(doc.paths["/"].get.parameters).toEqual([ + { $ref: "#/components/parameters/QueryOptionspagesize" }, + { $ref: "#/components/parameters/QueryOptionsuserid" }, + { $ref: "#/components/parameters/SingleOption" }, + ]); + expect(doc.components.parameters.QueryOptionspagesize.name).toBe("page-size"); + expect(doc.components.parameters.QueryOptionsuserid.name).toBe("x-user-id"); + expect(doc.components.parameters.SingleOption.name).toBe("sort-by"); + }); + + it("reports parameter collisions after sanitization", async () => { + const diagnostics = await diagnoseOpenApiFor( + ` + model Paging_Options { @query a: string; } + model PagingOptions { @query b: string; } + @route("/a") op first(...Paging_Options): void; + @route("/b") op second(...PagingOptions): void; + `, + { + "omit-unreachable-types": true, + "component-name-character-set": "alphanumeric", + }, + ); + expectDiagnostics(diagnostics, [ + { + code: "@typespec/openapi/duplicate-type-name", + }, + ]); + }); + + it("uses the configured separator for shared parameter properties", async () => { + const doc = await openApiFor( + ` + model Paging { @query page_size: int32; @query page_number: int32; } + @get op read(...Paging): void; + `, + { "component-name-strategy": { kind: "fqn", separator: "_" } }, + ); + expect(doc.paths["/"].get.parameters).toEqual([ + { $ref: "#/components/parameters/Paging_page_size" }, + { $ref: "#/components/parameters/Paging_page_number" }, + ]); + expect(Object.keys(doc.components.parameters)).toEqual([ + "Paging_page_number", + "Paging_page_size", + ]); + }); + it("errors on invalid parameter keys", async () => { const diagnostics = await diagnoseOpenApiFor( ` diff --git a/website/src/content/docs/docs/emitters/openapi3/openapi.md b/website/src/content/docs/docs/emitters/openapi3/openapi.md index 1924f970d1c..7114d3c299d 100644 --- a/website/src/content/docs/docs/emitters/openapi3/openapi.md +++ b/website/src/content/docs/docs/emitters/openapi3/openapi.md @@ -346,6 +346,34 @@ Models are handled differently based on how they're defined: [friendlyname]: ../../standard-library/built-in-decorators.md#@friendlyName +### Component Names + +By default, schema names include their namespace relative to the service, such as `Models.User_Profile`. A `@friendlyName` overrides that name. Reusable parameter keys use the same naming rules, with a property-name segment when the source model has multiple properties. + +Use `component-name-strategy` to omit namespaces or customize the separator between namespace and parameter-property segments: + +```yaml +options: + "@typespec/openapi3": + component-name-strategy: name-only +``` + +Alternatively, use `{ kind: fqn, separator: "_" }` to emit `Models_User_Profile`, or an empty separator to concatenate segments. Separators do not replace punctuation inside identifiers or friendly names. The default strategy is `fqn` with `"."` separators. + +Character restrictions are configured independently. For systems such as AWS API Gateway that require alphanumeric model names: + +```yaml +options: + "@typespec/openapi3": + component-name-character-set: alphanumeric +``` + +This removes characters outside `[A-Za-z0-9]` from the complete component key, including friendly names. For example, `Models.User_Profile` becomes `ModelsUserProfile`. Combine it with `component-name-strategy: name-only` to produce `UserProfile`. Case is preserved; Unicode characters are removed rather than transliterated. + +The default character set, `openapi`, preserves existing behavior and allows letters, digits, dots, hyphens, and underscores. Both options affect schema and reusable parameter keys and their references, including named multipart schemas. They do not change operation IDs, HTTP parameter names, JSON property names, discriminator values, security-scheme names, or explicit `@useRef` URLs. + +Names that become empty or collide after transformation produce errors; the emitter does not invent fallback names or append counters. Adjust identifiers, friendly names, or namespace settings to resolve these errors. Alphanumeric naming addresses model-name restrictions, not other AWS API Gateway import limitations. + ### Type Mapping This table shows how TypeSpec types map to OpenAPI/JSON Schema types: diff --git a/website/src/content/docs/docs/emitters/openapi3/reference/emitter.md b/website/src/content/docs/docs/emitters/openapi3/reference/emitter.md index 7d9f3b5dd5e..ae6fbbbd4b7 100644 --- a/website/src/content/docs/docs/emitters/openapi3/reference/emitter.md +++ b/website/src/content/docs/docs/emitters/openapi3/reference/emitter.md @@ -166,6 +166,36 @@ See https://github.com/OAI/OpenAPI-Specification/discussions/4622 for discussion | `kind` | `"parent-container" \| "fqn" \| "explicit-only"` | `"parent-container"` | Determines how to generate operation IDs when `@operationId` is not used.
Avaliable options are:
- `parent-container`: Uses the parent namespace and operation name to generate the ID.
- `fqn`: Uses the fully qualified name of the operation to generate the ID.
- `explicit-only`: Only use explicitly defined operation IDs. | | `separator` | `string` | | Separator used to join segment in the operation name. | +### `component-name-strategy` + +**Type:** `"fqn" | "name-only" | object { kind, separator }` + +**Options:** + +- `"fqn" | "name-only"` (default: `"fqn"`) + + Naming strategy for schema and reusable parameter component keys. + `fqn` preserves service-relative namespace qualification; `name-only` omits namespaces. + Friendly names override namespace qualification. Operation IDs and HTTP names are unchanged. + +- `object { kind, separator }` + +| Name | Type | Default | Description | +| ----------- | ---------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `kind` | `"fqn" \| "name-only"` | `"fqn"` | Naming strategy for schema and reusable parameter component keys.
`fqn` preserves service-relative namespace qualification; `name-only` omits namespaces.
Friendly names override namespace qualification. Operation IDs and HTTP names are unchanged. | +| `separator` | `string` | `"."` | Separator between namespace and parameter-property segments. May be empty. Does not replace punctuation within identifiers or friendly names. | + +### `component-name-character-set` + +**Type:** `"openapi" | "alphanumeric"` + +**Default:** `"openapi"` + +Character set for schema and reusable parameter component keys, independent of namespace qualification. +`openapi` preserves existing validation, allowing letters, digits, dots, hyphens, and underscores. +`alphanumeric` removes characters outside `[A-Za-z0-9]`, including punctuation in friendly names. +Empty names and collisions are errors. Does not affect operation IDs, HTTP names, or explicit external references. + ### `enum-strategy` **Type:** `"default" | "annotated"` From f736a7a89cf8617d301421727eb4ae57d315b943 Mon Sep 17 00:00:00 2001 From: Timothee Guerin Date: Thu, 5 Nov 2026 09:04:48 -0500 Subject: [PATCH 2/5] refactor(openapi3): defer component name sanitization --- ...pi3-component-naming-2026-10-4-18-35-26.md | 8 +- packages/openapi3/README.md | 11 -- packages/openapi3/src/component-naming.ts | 22 +--- .../src/diagnostics/empty-component-name.md | 10 -- packages/openapi3/src/lib.ts | 30 ------ packages/openapi3/src/openapi.ts | 17 +-- packages/openapi3/src/schema-emitter.ts | 18 +--- packages/openapi3/test/component.test.ts | 102 +++++++----------- packages/openapi3/test/get-openapi.test.ts | 5 +- packages/openapi3/test/multipart.test.ts | 14 +-- packages/openapi3/test/parameters.test.ts | 31 +++--- .../docs/docs/emitters/openapi3/openapi.md | 14 +-- .../emitters/openapi3/reference/emitter.md | 11 -- 13 files changed, 79 insertions(+), 214 deletions(-) delete mode 100644 packages/openapi3/src/diagnostics/empty-component-name.md diff --git a/.chronus/changes/feat-openapi3-component-naming-2026-10-4-18-35-26.md b/.chronus/changes/feat-openapi3-component-naming-2026-10-4-18-35-26.md index b2aa0282965..98ea666239f 100644 --- a/.chronus/changes/feat-openapi3-component-naming-2026-10-4-18-35-26.md +++ b/.chronus/changes/feat-openapi3-component-naming-2026-10-4-18-35-26.md @@ -4,14 +4,12 @@ packages: - "@typespec/openapi3" --- -Add independent component naming options for namespace qualification and alphanumeric-only schema and reusable parameter keys. Existing defaults are unchanged. - -For AWS API Gateway-compatible model names: +Add `component-name-strategy` to control namespace qualification and segment separators for OpenAPI schema and reusable parameter keys. Existing defaults are unchanged. ```yaml options: "@typespec/openapi3": - component-name-character-set: alphanumeric + component-name-strategy: name-only ``` -Use `component-name-strategy: name-only` to omit namespaces, or configure `{ kind: fqn, separator: "_" }` to change segment separators. Empty names and collisions after transformation are errors. \ No newline at end of file +Use `name-only` to omit namespaces, or configure `{ kind: fqn, separator: "_" }` to change segment separators. Characters within identifiers and friendly names remain unchanged. Collisions after namespace changes are errors. \ No newline at end of file diff --git a/packages/openapi3/README.md b/packages/openapi3/README.md index 46222d56306..038da779362 100644 --- a/packages/openapi3/README.md +++ b/packages/openapi3/README.md @@ -191,17 +191,6 @@ See https://github.com/OAI/OpenAPI-Specification/discussions/4622 for discussion | `kind` | `"fqn" \| "name-only"` | `"fqn"` | Naming strategy for schema and reusable parameter component keys.
`fqn` preserves service-relative namespace qualification; `name-only` omits namespaces.
Friendly names override namespace qualification. Operation IDs and HTTP names are unchanged. | | `separator` | `string` | `"."` | Separator between namespace and parameter-property segments. May be empty. Does not replace punctuation within identifiers or friendly names. | -### `component-name-character-set` - -**Type:** `"openapi" | "alphanumeric"` - -**Default:** `"openapi"` - -Character set for schema and reusable parameter component keys, independent of namespace qualification. -`openapi` preserves existing validation, allowing letters, digits, dots, hyphens, and underscores. -`alphanumeric` removes characters outside `[A-Za-z0-9]`, including punctuation in friendly names. -Empty names and collisions are errors. Does not affect operation IDs, HTTP names, or explicit external references. - ### `enum-strategy` **Type:** `"default" | "annotated"` diff --git a/packages/openapi3/src/component-naming.ts b/packages/openapi3/src/component-naming.ts index 3053fa52f84..83572c3f5e4 100644 --- a/packages/openapi3/src/component-naming.ts +++ b/packages/openapi3/src/component-naming.ts @@ -1,14 +1,11 @@ import type { Program, Type, TypeNameOptions } from "@typespec/compiler"; import { getOpenAPITypeName } from "@typespec/openapi"; -import { reportDiagnostic } from "./lib.js"; import type { ResolvedOpenAPI3EmitterOptions } from "./openapi.js"; -import { ensureValidComponentFixedFieldKey } from "./util.js"; export function hasCustomComponentNames(options: ResolvedOpenAPI3EmitterOptions): boolean { return ( options.componentNameStrategy?.kind === "name-only" || - (options.componentNameStrategy?.separator ?? ".") !== "." || - options.componentNameCharacterSet === "alphanumeric" + (options.componentNameStrategy?.separator ?? ".") !== "." ); } @@ -41,20 +38,3 @@ export function getComponentTypeName( } return segments.join(separator); } - -export function normalizeComponentName( - program: Program, - type: Type, - name: string, - options: ResolvedOpenAPI3EmitterOptions, -): string | undefined { - if (options.componentNameCharacterSet !== "alphanumeric") { - return ensureValidComponentFixedFieldKey(program, type, name); - } - const result = name.replace(/[^A-Za-z0-9]/g, ""); - if (result === "") { - reportDiagnostic(program, { code: "empty-component-name", format: { name }, target: type }); - return undefined; - } - return result; -} diff --git a/packages/openapi3/src/diagnostics/empty-component-name.md b/packages/openapi3/src/diagnostics/empty-component-name.md deleted file mode 100644 index 1a863c8714d..00000000000 --- a/packages/openapi3/src/diagnostics/empty-component-name.md +++ /dev/null @@ -1,10 +0,0 @@ -This diagnostic is reported when `component-name-character-set: alphanumeric` removes every character from a schema or reusable parameter component key. - -For example, the following friendly name contains no ASCII letters or digits: - -```typespec -@friendlyName("___") -model User {} -``` - -Use an identifier or friendly name containing at least one ASCII letter or digit, or use the default `openapi` character set. Alphanumeric sanitization preserves case and removes Unicode characters rather than transliterating them. diff --git a/packages/openapi3/src/lib.ts b/packages/openapi3/src/lib.ts index c8f371dfa33..a8cbd9d7c4e 100644 --- a/packages/openapi3/src/lib.ts +++ b/packages/openapi3/src/lib.ts @@ -11,8 +11,6 @@ export type ExperimentalParameterExamplesStrategy = "data" | "serialized"; export type EnumStrategy = "default" | "annotated"; /** Namespace qualification for schema and reusable parameter component keys. */ export type ComponentNameStrategy = "fqn" | "name-only"; -/** Allowed characters in schema and reusable parameter component keys. */ -export type ComponentNameCharacterSet = "openapi" | "alphanumeric"; /** User-supplied emitter configuration; omitted settings are normalized by `resolveOptions`. */ export interface OpenAPI3EmitterOptions { /** @@ -136,15 +134,6 @@ export interface OpenAPI3EmitterOptions { separator?: string; }; - /** - * Character set for schema and reusable parameter keys, independent of namespace qualification. - * `openapi` preserves existing validation. `alphanumeric` removes characters outside `[A-Za-z0-9]`, - * including punctuation in friendly names. Empty names and collisions are errors. - * Does not affect operation IDs, HTTP names, or explicit external references. - * @default openapi - */ - "component-name-character-set"?: ComponentNameCharacterSet; - /** * How to emit TypeSpec enums. * @@ -353,18 +342,6 @@ const EmitterOptionsSchema: JSONSchemaType = { }, ], } as any, - "component-name-character-set": { - type: "string", - enum: ["openapi", "alphanumeric"], - nullable: true, - default: "openapi", - description: [ - "Character set for schema and reusable parameter component keys, independent of namespace qualification.", - "`openapi` preserves existing validation, allowing letters, digits, dots, hyphens, and underscores.", - "`alphanumeric` removes characters outside `[A-Za-z0-9]`, including punctuation in friendly names.", - "Empty names and collisions are errors. Does not affect operation IDs, HTTP names, or explicit external references.", - ].join("\n"), - }, "enum-strategy": { type: "string", enum: ["default", "annotated"], @@ -532,13 +509,6 @@ export const $lib = createTypeSpecLibrary({ default: paramMessage`Invalid key '${"value"}' used in a fixed field of the Component object. Only alphanumerics, dot (.), hyphen (-), and underscore (_) characters are allowed in keys.`, }, }, - "empty-component-name": { - severity: "error", - docs: fileRef.fromPackageRoot("src/diagnostics/empty-component-name.md"), - messages: { - default: paramMessage`Component name '${"name"}' contains no ASCII letters or digits after alphanumeric sanitization. Use an alphanumeric identifier or @friendlyName.`, - }, - }, "streams-not-supported": { severity: "warning", messages: { diff --git a/packages/openapi3/src/openapi.ts b/packages/openapi3/src/openapi.ts index a1c0b0b9aa7..3ebabc99e89 100644 --- a/packages/openapi3/src/openapi.ts +++ b/packages/openapi3/src/openapi.ts @@ -87,18 +87,13 @@ import { shouldInline, } from "@typespec/openapi"; import { stringify } from "yaml"; -import { - getComponentTypeName, - hasCustomComponentNames, - normalizeComponentName, -} from "./component-naming.js"; +import { getComponentTypeName, hasCustomComponentNames } from "./component-naming.js"; import { getRef } from "./decorators.js"; import type { OperationExamples } from "./examples.js"; import { getExampleOrExamples, resolveOperationExamples } from "./examples.js"; import type { JsonSchemaModule } from "./json-schema.js"; import { resolveJsonSchemaModule } from "./json-schema.js"; import type { - ComponentNameCharacterSet, ComponentNameStrategy, EnumStrategy, FileType, @@ -275,7 +270,6 @@ export function resolveOptions( separator: typeof componentNameStrategy === "string" ? "." : (componentNameStrategy.separator ?? "."), }, - componentNameCharacterSet: resolvedOptions["component-name-character-set"] ?? "openapi", enumStrategy, }; } @@ -316,8 +310,6 @@ export interface ResolvedOpenAPI3EmitterOptions { /** Separator between namespace and parameter-property segments. */ separator: string; }; - /** Component key character set; defaults to existing OpenAPI validation. */ - componentNameCharacterSet?: ComponentNameCharacterSet; /** Formats requested for each document; inferred from the output extension or defaulted to YAML when absent. */ fileTypes: FileType[]; /** Resolved output path template; includes an OpenAPI-version directory when multiple specification versions are requested. */ @@ -1454,7 +1446,7 @@ function createOAPIEmitter( ? getComponentTypeName(program, body.type, typeNameOptions, options) : undefined; if (name !== undefined && customComponentNames) { - name = normalizeComponentName(program, body.type, name, options); + name = ensureValidComponentFixedFieldKey(program, body.type, name); if (name) { const existing = multipartSchemaTypes.get(name); if (existing && existing !== body.type) { @@ -1846,14 +1838,13 @@ function createOAPIEmitter( function emitParameters() { for (const [property, param] of params) { - let validKey: string | undefined; + let validKey: string; if (customComponentNames) { const parent = property.model!; const name = getComponentTypeName(program, parent, typeNameOptions, options); const separator = options.componentNameStrategy?.separator ?? "."; const key = parent.properties.size > 1 ? name + separator + property.name : name; - validKey = normalizeComponentName(program, property, key, options); - if (validKey === undefined) continue; + validKey = ensureValidComponentFixedFieldKey(program, property, key); checkDuplicateTypeName(program, property, validKey, root.components!.parameters!); } else { const key = getParameterKey( diff --git a/packages/openapi3/src/schema-emitter.ts b/packages/openapi3/src/schema-emitter.ts index 7a294c59368..e61faaea4be 100644 --- a/packages/openapi3/src/schema-emitter.ts +++ b/packages/openapi3/src/schema-emitter.ts @@ -70,7 +70,7 @@ import { shouldInline, } from "@typespec/openapi"; import { attachExtensions } from "./attach-extensions.js"; -import { getComponentTypeName, normalizeComponentName } from "./component-naming.js"; +import { getComponentTypeName } from "./component-naming.js"; import { getOneOf, getRef } from "./decorators.js"; import type { JsonSchemaModule } from "./json-schema.js"; import type { OpenAPI3EmitterOptions } from "./lib.js"; @@ -1002,8 +1002,7 @@ export class OpenAPI3SchemaEmitterBase< } const skipNameValidation = type.kind === "Model" && type.templateMapper !== undefined; - const alphanumeric = this._options.componentNameCharacterSet === "alphanumeric"; - if (!skipNameValidation && !alphanumeric) { + if (!skipNameValidation) { name = ensureValidComponentFixedFieldKey(this.emitter.getProgram(), type, name); } @@ -1016,17 +1015,8 @@ export class OpenAPI3SchemaEmitterBase< const shouldAddSuffix = usage !== undefined && usage.size > 1; const visibility = this.#getVisibilityContext(); - let fullName = name + (shouldAddSuffix ? getVisibilitySuffix(visibility, Visibility.Read) : ""); - if (alphanumeric) { - const normalized = normalizeComponentName( - this.emitter.getProgram(), - type, - fullName, - this._options, - ); - if (normalized === undefined) return {}; - fullName = normalized; - } + const fullName = + name + (shouldAddSuffix ? getVisibilitySuffix(visibility, Visibility.Read) : ""); const decl = this.emitter.result.declaration(fullName, schema); checkDuplicateTypeName( diff --git a/packages/openapi3/test/component.test.ts b/packages/openapi3/test/component.test.ts index b04ebf2bcaa..a18e9920a48 100644 --- a/packages/openapi3/test/component.test.ts +++ b/packages/openapi3/test/component.test.ts @@ -252,7 +252,6 @@ worksFor(supportedVersions, async (specHelpers) => { const current = await specHelpers.openApiFor(code); const explicit = await specHelpers.openApiFor(code, { "component-name-strategy": "fqn", - "component-name-character-set": "openapi", }); expect(explicit).toEqual(current); expect(current.components.schemas["Models.User_Profile"]).toBeDefined(); @@ -273,7 +272,7 @@ worksFor(supportedVersions, async (specHelpers) => { }); }); - it("sanitizes all schema kinds and friendly names without changing payload names", async () => { + it("uses namespace separators across schema kinds without changing friendly or payload names", async () => { const doc = await specHelpers.openApiFor( ` @service namespace Demo { @@ -294,24 +293,24 @@ worksFor(supportedVersions, async (specHelpers) => { @get op read(): Models.User_List; } `, - { "component-name-character-set": "alphanumeric" }, + { "component-name-strategy": { kind: "fqn", separator: "_" } }, ); expect(Object.keys(doc.components.schemas)).toEqual([ - "ModelsUserId", - "ModelsUserKind", - "ModelsUserList", - "ModelsUserProfile", - "ModelsUserState", - "PageUserProfile", + "Models_User_Id", + "Models_User_Kind", + "Models_User_List", + "Models_User_Profile", + "Models_User_State", + "Page-User_Profile", ]); - expect(doc.components.schemas.ModelsUserList.items.$ref).toBe( - "#/components/schemas/ModelsUserProfile", + expect(doc.components.schemas.Models_User_List.items.$ref).toBe( + "#/components/schemas/Models_User_Profile", ); - expect(doc.components.schemas.ModelsUserProfile.properties.user_id.$ref).toBe( - "#/components/schemas/ModelsUserId", + expect(doc.components.schemas.Models_User_Profile.properties.user_id.$ref).toBe( + "#/components/schemas/Models_User_Id", ); - expect(doc.components.schemas.ModelsUserProfile.properties.next.$ref).toBe( - "#/components/schemas/PageUserProfile", + expect(doc.components.schemas.Models_User_Profile.properties.next.$ref).toBe( + "#/components/schemas/Page-User_Profile", ); }); @@ -330,7 +329,7 @@ worksFor(supportedVersions, async (specHelpers) => { expect(Object.keys(doc.components.schemas)).toEqual(["Friendly.Name", "Models_User.Profile"]); }); - it("combines name-only with sanitization and preserves discriminator references", async () => { + it("omits namespaces while preserving discriminator references", async () => { const doc = await specHelpers.openApiFor( ` @service namespace Demo { @@ -343,43 +342,44 @@ worksFor(supportedVersions, async (specHelpers) => { `, { "component-name-strategy": "name-only", - "component-name-character-set": "alphanumeric", }, ); - expect(doc.components.schemas.PetBase.discriminator).toEqual({ + expect(doc.components.schemas.Pet_Base.discriminator).toEqual({ propertyName: "pet_kind", - mapping: { house_cat: "#/components/schemas/HouseCat" }, + mapping: { house_cat: "#/components/schemas/House_Cat" }, }); - expect(doc.components.schemas.HouseCat.allOf).toEqual([ - { $ref: "#/components/schemas/PetBase" }, + expect(doc.components.schemas.House_Cat.allOf).toEqual([ + { $ref: "#/components/schemas/Pet_Base" }, ]); }); - it("sanitizes generated envelopes and visibility variants together", async () => { + it("omits namespaces for generated envelopes and visibility variants", async () => { const doc = await specHelpers.openApiFor( ` - model House_Cat { - value: string; - @visibility(Lifecycle.Create) secret: string; + namespace Models { + model House_Cat { + value: string; + @visibility(Lifecycle.Create) secret: string; + } + @discriminated union Pet_Choice { house_cat: House_Cat } } - @discriminated union Pet_Choice { house_cat: House_Cat } - @put op update(@body data: Pet_Choice): Pet_Choice; + @put op update(@body data: Models.Pet_Choice): Models.Pet_Choice; `, - { "component-name-character-set": "alphanumeric" }, + { "component-name-strategy": "name-only" }, ); for (const suffix of ["", "CreateOrUpdate"]) { - expect(doc.components.schemas[`PetChoice${suffix}`].discriminator.mapping).toEqual({ - house_cat: `#/components/schemas/PetChoiceHousecat${suffix}`, + expect(doc.components.schemas[`Pet_Choice${suffix}`].discriminator.mapping).toEqual({ + house_cat: `#/components/schemas/Pet_ChoiceHouse_cat${suffix}`, }); - expect(doc.components.schemas[`PetChoiceHousecat${suffix}`].properties.value.$ref).toBe( - `#/components/schemas/HouseCat${suffix}`, + expect(doc.components.schemas[`Pet_ChoiceHouse_cat${suffix}`].properties.value.$ref).toBe( + `#/components/schemas/House_Cat${suffix}`, ); } expect(doc.paths["/"].put.requestBody.content["application/json"].schema.$ref).toBe( - "#/components/schemas/PetChoiceCreateOrUpdate", + "#/components/schemas/Pet_ChoiceCreateOrUpdate", ); expect(doc.paths["/"].put.responses["200"].content["application/json"].schema.$ref).toBe( - "#/components/schemas/PetChoice", + "#/components/schemas/Pet_Choice", ); }); @@ -393,46 +393,26 @@ worksFor(supportedVersions, async (specHelpers) => { `, { "component-name-strategy": "name-only", - "component-name-character-set": "alphanumeric", "include-x-typespec-name": "inline-only", }, ); const schema = doc.paths["/"].get.responses["200"].content["application/json"].schema; expect(schema["x-typespec-name"]).toBe("Box"); - expect(schema.properties.value.$ref).toBe("#/components/schemas/UserProfile"); - expect(doc.components.schemas.UserProfile.properties.external.$ref).toBe( + expect(schema.properties.value.$ref).toBe("#/components/schemas/User_Profile"); + expect(doc.components.schemas.User_Profile.properties.external.$ref).toBe( "../common.json#/components/schemas/User_Profile", ); }); - it.each([ - { - options: { "component-name-strategy": "name-only" }, - code: ` + it("reports collisions after omitting namespaces", async () => { + const diagnostics = await specHelpers.diagnoseOpenApiFor( + ` namespace A { model User {} } namespace B { model User {} } op read(): A.User | B.User; `, - }, - { - options: { "component-name-character-set": "alphanumeric" }, - code: ` - model User_Profile {} model UserProfile {} - `, - }, - ] satisfies { options: OpenAPI3EmitterOptions; code: string }[])( - "reports final-key collisions for $options", - async ({ options, code }) => { - const diagnostics = await specHelpers.diagnoseOpenApiFor(code, options); - expectDiagnostics(diagnostics, [{ code: "@typespec/openapi/duplicate-type-name" }]); - }, - ); - - it("rejects an empty sanitized friendly name", async () => { - const diagnostics = await specHelpers.diagnoseOpenApiFor( - `@friendlyName("___") model User {}`, - { "component-name-character-set": "alphanumeric" }, + { "component-name-strategy": "name-only" }, ); - expectDiagnostics(diagnostics, [{ code: "@typespec/openapi3/empty-component-name" }]); + expectDiagnostics(diagnostics, [{ code: "@typespec/openapi/duplicate-type-name" }]); }); }); diff --git a/packages/openapi3/test/get-openapi.test.ts b/packages/openapi3/test/get-openapi.test.ts index 0d5f4f42020..a7418151746 100644 --- a/packages/openapi3/test/get-openapi.test.ts +++ b/packages/openapi3/test/get-openapi.test.ts @@ -65,15 +65,14 @@ it("applies component naming independently to each service through the object AP `); const records = await getOpenAPI3(program, { "component-name-strategy": "name-only", - "component-name-character-set": "alphanumeric", }); strictEqual(records.length, 2); for (const [index, record] of records.entries()) { ok(!record.versioned); expectDiagnostics(record.diagnostics, []); const schemas = record.document.components!.schemas!; - deepStrictEqual(Object.keys(schemas), ["UserProfile"]); - deepStrictEqual(Object.keys((schemas.UserProfile as any).properties), [ + deepStrictEqual(Object.keys(schemas), ["User_Profile"]); + deepStrictEqual(Object.keys((schemas.User_Profile as any).properties), [ index === 0 ? "first" : "second", ]); } diff --git a/packages/openapi3/test/multipart.test.ts b/packages/openapi3/test/multipart.test.ts index b05fa6ad238..07b99e4c321 100644 --- a/packages/openapi3/test/multipart.test.ts +++ b/packages/openapi3/test/multipart.test.ts @@ -14,12 +14,12 @@ worksFor(supportedVersions, ({ openApiFor, diagnoseOpenApiFor }) => { @route("/b") op second(@multipartBody body: Models.Upload_Form): void; } `, - { "component-name-character-set": "alphanumeric" }, + { "component-name-strategy": "name-only" }, ); - expect(Object.keys(res.components.schemas)).toEqual(["ModelsUploadForm"]); + expect(Object.keys(res.components.schemas)).toEqual(["Upload_Form"]); for (const path of ["/a", "/b"]) { expect(res.paths[path].post.requestBody.content["multipart/form-data"].schema).toEqual({ - $ref: "#/components/schemas/ModelsUploadForm", + $ref: "#/components/schemas/Upload_Form", }); } }); @@ -27,11 +27,11 @@ worksFor(supportedVersions, ({ openApiFor, diagnoseOpenApiFor }) => { it("reports transformed multipart and regular schema collisions", async () => { const diagnostics = await diagnoseOpenApiFor( ` - model Upload_Form { name: HttpPart; } - model UploadForm { value: string; } - op upload(@multipartBody body: Upload_Form): UploadForm; + namespace Multipart { model Upload_Form { name: HttpPart; } } + namespace Payload { model Upload_Form { value: string; } } + op upload(@multipartBody body: Multipart.Upload_Form): Payload.Upload_Form; `, - { "component-name-character-set": "alphanumeric" }, + { "component-name-strategy": "name-only" }, ); expectDiagnostics(diagnostics, [{ code: "@typespec/openapi/duplicate-type-name" }]); }); diff --git a/packages/openapi3/test/parameters.test.ts b/packages/openapi3/test/parameters.test.ts index a3fe271b168..cc1bd081751 100644 --- a/packages/openapi3/test/parameters.test.ts +++ b/packages/openapi3/test/parameters.test.ts @@ -263,35 +263,34 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version }) => { `, { "component-name-strategy": { kind: "name-only", separator: "_" }, - "component-name-character-set": "alphanumeric", }, ); expect(Object.keys(doc.components.parameters)).toEqual([ - "QueryOptionspagesize", - "QueryOptionsuserid", - "SingleOption", + "Query_Options_page_size", + "Query_Options_user_id", + "Single_Option", ]); expect(doc.paths["/"].get.parameters).toEqual([ - { $ref: "#/components/parameters/QueryOptionspagesize" }, - { $ref: "#/components/parameters/QueryOptionsuserid" }, - { $ref: "#/components/parameters/SingleOption" }, + { $ref: "#/components/parameters/Query_Options_page_size" }, + { $ref: "#/components/parameters/Query_Options_user_id" }, + { $ref: "#/components/parameters/Single_Option" }, ]); - expect(doc.components.parameters.QueryOptionspagesize.name).toBe("page-size"); - expect(doc.components.parameters.QueryOptionsuserid.name).toBe("x-user-id"); - expect(doc.components.parameters.SingleOption.name).toBe("sort-by"); + expect(doc.components.parameters.Query_Options_page_size.name).toBe("page-size"); + expect(doc.components.parameters.Query_Options_user_id.name).toBe("x-user-id"); + expect(doc.components.parameters.Single_Option.name).toBe("sort-by"); }); - it("reports parameter collisions after sanitization", async () => { + it("reports parameter collisions after omitting namespaces", async () => { const diagnostics = await diagnoseOpenApiFor( ` - model Paging_Options { @query a: string; } - model PagingOptions { @query b: string; } - @route("/a") op first(...Paging_Options): void; - @route("/b") op second(...PagingOptions): void; + namespace A { model Paging_Options { @query a: string; } } + namespace B { model Paging_Options { @query b: string; } } + @route("/a") op first(...A.Paging_Options): void; + @route("/b") op second(...B.Paging_Options): void; `, { "omit-unreachable-types": true, - "component-name-character-set": "alphanumeric", + "component-name-strategy": "name-only", }, ); expectDiagnostics(diagnostics, [ diff --git a/website/src/content/docs/docs/emitters/openapi3/openapi.md b/website/src/content/docs/docs/emitters/openapi3/openapi.md index 7114d3c299d..611e2de5523 100644 --- a/website/src/content/docs/docs/emitters/openapi3/openapi.md +++ b/website/src/content/docs/docs/emitters/openapi3/openapi.md @@ -360,19 +360,9 @@ options: Alternatively, use `{ kind: fqn, separator: "_" }` to emit `Models_User_Profile`, or an empty separator to concatenate segments. Separators do not replace punctuation inside identifiers or friendly names. The default strategy is `fqn` with `"."` separators. -Character restrictions are configured independently. For systems such as AWS API Gateway that require alphanumeric model names: +The option affects schema and reusable parameter keys and their references, including named multipart schemas. It does not change operation IDs, HTTP parameter names, JSON property names, discriminator values, security-scheme names, or explicit `@useRef` URLs. Characters within identifiers and friendly names, such as underscores and hyphens, remain unchanged. -```yaml -options: - "@typespec/openapi3": - component-name-character-set: alphanumeric -``` - -This removes characters outside `[A-Za-z0-9]` from the complete component key, including friendly names. For example, `Models.User_Profile` becomes `ModelsUserProfile`. Combine it with `component-name-strategy: name-only` to produce `UserProfile`. Case is preserved; Unicode characters are removed rather than transliterated. - -The default character set, `openapi`, preserves existing behavior and allows letters, digits, dots, hyphens, and underscores. Both options affect schema and reusable parameter keys and their references, including named multipart schemas. They do not change operation IDs, HTTP parameter names, JSON property names, discriminator values, security-scheme names, or explicit `@useRef` URLs. - -Names that become empty or collide after transformation produce errors; the emitter does not invent fallback names or append counters. Adjust identifiers, friendly names, or namespace settings to resolve these errors. Alphanumeric naming addresses model-name restrictions, not other AWS API Gateway import limitations. +Names that collide after namespace changes produce errors; the emitter does not append counters. Adjust identifiers, friendly names, or namespace settings to resolve these errors. ### Type Mapping diff --git a/website/src/content/docs/docs/emitters/openapi3/reference/emitter.md b/website/src/content/docs/docs/emitters/openapi3/reference/emitter.md index ae6fbbbd4b7..84166f65fd1 100644 --- a/website/src/content/docs/docs/emitters/openapi3/reference/emitter.md +++ b/website/src/content/docs/docs/emitters/openapi3/reference/emitter.md @@ -185,17 +185,6 @@ See https://github.com/OAI/OpenAPI-Specification/discussions/4622 for discussion | `kind` | `"fqn" \| "name-only"` | `"fqn"` | Naming strategy for schema and reusable parameter component keys.
`fqn` preserves service-relative namespace qualification; `name-only` omits namespaces.
Friendly names override namespace qualification. Operation IDs and HTTP names are unchanged. | | `separator` | `string` | `"."` | Separator between namespace and parameter-property segments. May be empty. Does not replace punctuation within identifiers or friendly names. | -### `component-name-character-set` - -**Type:** `"openapi" | "alphanumeric"` - -**Default:** `"openapi"` - -Character set for schema and reusable parameter component keys, independent of namespace qualification. -`openapi` preserves existing validation, allowing letters, digits, dots, hyphens, and underscores. -`alphanumeric` removes characters outside `[A-Za-z0-9]`, including punctuation in friendly names. -Empty names and collisions are errors. Does not affect operation IDs, HTTP names, or explicit external references. - ### `enum-strategy` **Type:** `"default" | "annotated"` From c62dec47e00c8d5369e0f10236cd2f5247e4df0d Mon Sep 17 00:00:00 2001 From: Timothee Guerin Date: Fri, 6 Nov 2026 11:23:57 -0500 Subject: [PATCH 3/5] refactor(openapi3): use a single component naming path --- ...pi3-component-naming-2026-10-6-11-13-28.md | 7 ++++ ...pi3-component-naming-2026-10-6-11-13-33.md | 7 ++++ packages/openapi/src/helpers.ts | 14 ++----- packages/openapi3/src/component-naming.ts | 33 ++++++---------- packages/openapi3/src/openapi.ts | 38 ++++++++----------- packages/openapi3/src/schema-emitter.ts | 10 ++++- .../test/declaration-expressions.test.ts | 31 ++++++++++++++- packages/openapi3/test/multipart.test.ts | 28 +++++++++++++- packages/openapi3/test/parameters.test.ts | 1 + 9 files changed, 111 insertions(+), 58 deletions(-) create mode 100644 .chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-28.md create mode 100644 .chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-33.md diff --git a/.chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-28.md b/.chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-28.md new file mode 100644 index 00000000000..0cd858cea93 --- /dev/null +++ b/.chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-28.md @@ -0,0 +1,7 @@ +--- +changeKind: internal +packages: + - "@typespec/openapi" +--- + +Share duplicate schema and parameter component key diagnostics while preserving existing parameter error messages. \ No newline at end of file diff --git a/.chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-33.md b/.chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-33.md new file mode 100644 index 00000000000..fed5173ddbc --- /dev/null +++ b/.chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-33.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@typespec/openapi3" +--- + +Validate named multipart schema component keys and report duplicate keys consistently, including with the default naming strategy. \ No newline at end of file diff --git a/packages/openapi/src/helpers.ts b/packages/openapi/src/helpers.ts index 9ca67cb2b41..72bdfcb218a 100644 --- a/packages/openapi/src/helpers.ts +++ b/packages/openapi/src/helpers.ts @@ -89,16 +89,19 @@ export function getOpenAPITypeName( * @param type Type with the name to check * @param name Name to check * @param existing Existing map of name + * @param messageId - Whether to report a duplicate type name or parameter key. */ export function checkDuplicateTypeName( program: Program, type: Type, name: string, existing: Record | undefined, + messageId: "default" | "parameter" = "default", ) { if (existing && existing[name]) { reportDiagnostic(program, { code: "duplicate-type-name", + messageId, format: { value: name, }, @@ -124,16 +127,7 @@ export function getParameterKey( key += `.${property.name}`; } - if (existingParams[key]) { - reportDiagnostic(program, { - code: "duplicate-type-name", - messageId: "parameter", - format: { - value: key, - }, - target: property, - }); - } + checkDuplicateTypeName(program, property, key, existingParams, "parameter"); return key; } diff --git a/packages/openapi3/src/component-naming.ts b/packages/openapi3/src/component-naming.ts index 83572c3f5e4..6f801bad3e3 100644 --- a/packages/openapi3/src/component-naming.ts +++ b/packages/openapi3/src/component-naming.ts @@ -1,14 +1,7 @@ import type { Program, Type, TypeNameOptions } from "@typespec/compiler"; -import { getOpenAPITypeName } from "@typespec/openapi"; +import { getFriendlyName, getTypeName, isStdNamespace } from "@typespec/compiler"; import type { ResolvedOpenAPI3EmitterOptions } from "./openapi.js"; -export function hasCustomComponentNames(options: ResolvedOpenAPI3EmitterOptions): boolean { - return ( - options.componentNameStrategy?.kind === "name-only" || - (options.componentNameStrategy?.separator ?? ".") !== "." - ); -} - export function getComponentTypeName( program: Program, type: Type, @@ -16,25 +9,23 @@ export function getComponentTypeName( options: ResolvedOpenAPI3EmitterOptions, ): string { const strategy = options.componentNameStrategy; - const name = getOpenAPITypeName(program, type, { - ...typeNameOptions, - nameOnly: strategy?.kind === "name-only", - }); - const separator = strategy?.separator ?? "."; - if (strategy?.kind === "name-only" || separator === ".") { + const friendlyName = getFriendlyName(program, type); + const name = friendlyName ?? getTypeName(type, { ...typeNameOptions, nameOnly: true }); + let namespace = "namespace" in type ? type.namespace : undefined; + if ( + friendlyName !== undefined || + strategy?.kind === "name-only" || + ("expression" in type && type.expression) || + (namespace && isStdNamespace(namespace)) + ) { return name; } - const localName = getOpenAPITypeName(program, type, { ...typeNameOptions, nameOnly: true }); - // Friendly names, declaration expressions, and standard types are already unqualified. - if (name === localName) return name; - - const segments = [localName]; - let namespace = "namespace" in type ? type.namespace : undefined; + const segments = [name]; while (namespace && namespace.name !== "") { if (typeNameOptions.namespaceFilter && !typeNameOptions.namespaceFilter(namespace)) break; segments.unshift(namespace.name); namespace = namespace.namespace; } - return segments.join(separator); + return segments.join(strategy?.separator ?? "."); } diff --git a/packages/openapi3/src/openapi.ts b/packages/openapi3/src/openapi.ts index 3ebabc99e89..933c40b913a 100644 --- a/packages/openapi3/src/openapi.ts +++ b/packages/openapi3/src/openapi.ts @@ -81,13 +81,12 @@ import { getExtensions, getExternalDocs, getOpenAPITypeName, - getParameterKey, getTagsMetadata, isReadonlyProperty, shouldInline, } from "@typespec/openapi"; import { stringify } from "yaml"; -import { getComponentTypeName, hasCustomComponentNames } from "./component-naming.js"; +import { getComponentTypeName } from "./component-naming.js"; import { getRef } from "./decorators.js"; import type { OperationExamples } from "./examples.js"; import { getExampleOrExamples, resolveOperationExamples } from "./examples.js"; @@ -366,7 +365,6 @@ function createOAPIEmitter( let visibilityUsage: VisibilityUsageTracker; let sseModule: SSEModule | undefined; let jsonSchemaModule: JsonSchemaModule | undefined; - const customComponentNames = hasCustomComponentNames(options); let multipartSchemaTypes: Map; // Map model properties that represent shared parameters to their parameter @@ -1445,7 +1443,7 @@ function createOAPIEmitter( "name" in body.type && body.type.name !== "" ? getComponentTypeName(program, body.type, typeNameOptions, options) : undefined; - if (name !== undefined && customComponentNames) { + if (name !== undefined) { name = ensureValidComponentFixedFieldKey(program, body.type, name); if (name) { const existing = multipartSchemaTypes.get(name); @@ -1838,24 +1836,18 @@ function createOAPIEmitter( function emitParameters() { for (const [property, param] of params) { - let validKey: string; - if (customComponentNames) { - const parent = property.model!; - const name = getComponentTypeName(program, parent, typeNameOptions, options); - const separator = options.componentNameStrategy?.separator ?? "."; - const key = parent.properties.size > 1 ? name + separator + property.name : name; - validKey = ensureValidComponentFixedFieldKey(program, property, key); - checkDuplicateTypeName(program, property, validKey, root.components!.parameters!); - } else { - const key = getParameterKey( - program, - property, - param, - root.components!.parameters!, - typeNameOptions, - ); - validKey = ensureValidComponentFixedFieldKey(program, property, key); - } + const parent = property.model!; + const name = getComponentTypeName(program, parent, typeNameOptions, options); + const separator = options.componentNameStrategy?.separator ?? "."; + const key = parent.properties.size > 1 ? name + separator + property.name : name; + const validKey = ensureValidComponentFixedFieldKey(program, property, key); + checkDuplicateTypeName( + program, + property, + validKey, + root.components!.parameters!, + "parameter", + ); root.components!.parameters![validKey] = { ...param }; for (const key of Object.keys(param)) { delete param[key]; @@ -1879,7 +1871,7 @@ function createOAPIEmitter( const declarations = files[0].globalScope.declarations; for (const declaration of declarations) { const multipartType = multipartSchemaTypes.get(declaration.name); - if (customComponentNames && multipartType) { + if (multipartType) { checkDuplicateTypeName(program, multipartType, declaration.name, schemas); } schemas[declaration.name] = declaration.value as any; diff --git a/packages/openapi3/src/schema-emitter.ts b/packages/openapi3/src/schema-emitter.ts index e61faaea4be..b040bb7a97f 100644 --- a/packages/openapi3/src/schema-emitter.ts +++ b/packages/openapi3/src/schema-emitter.ts @@ -65,7 +65,6 @@ import { checkDuplicateTypeName, getExtensions, getExternalDocs, - getOpenAPITypeName, isReadonlyProperty, shouldInline, } from "@typespec/openapi"; @@ -308,7 +307,14 @@ export class OpenAPI3SchemaEmitterBase< } modelInstantiation(model: Model, name: string | undefined): EmitterOutput> { - name = name ?? getOpenAPITypeName(this.emitter.getProgram(), model, this.#typeNameOptions()); + name = + name ?? + getComponentTypeName( + this.emitter.getProgram(), + model, + this.#typeNameOptions(), + this._options, + ); if (!name) { return this.modelLiteral(model); } diff --git a/packages/openapi3/test/declaration-expressions.test.ts b/packages/openapi3/test/declaration-expressions.test.ts index 33658fdaef7..cde6ad18eea 100644 --- a/packages/openapi3/test/declaration-expressions.test.ts +++ b/packages/openapi3/test/declaration-expressions.test.ts @@ -1,7 +1,7 @@ import { expect, it } from "vitest"; import { supportedVersions, worksFor } from "./works-for.js"; -worksFor(supportedVersions, ({ oapiForModel }) => { +worksFor(supportedVersions, ({ oapiForModel, openApiFor }) => { it("inlines an anonymous enum used as a property type", async () => { const res = await oapiForModel("Foo", `model Foo { status: enum { active, inactive }; }`); const status = res.schemas.Foo.properties.status; @@ -35,4 +35,33 @@ worksFor(supportedVersions, ({ oapiForModel }) => { expect(res.schemas.Inner.properties.x.type).toBe("string"); expect(Object.keys(res.schemas).sort()).toEqual(["Foo", "Inner"]); }); + + it("does not qualify declaration expressions with their enclosing namespace", async () => { + const doc = await openApiFor( + ` + @service namespace Demo { + namespace Models { + model Outer { + inner: model Inner { value: string; }; + choice: enum Choice { active }; + code: scalar Code extends string; + } + } + @get op read(): Models.Outer; + } + `, + { "component-name-strategy": { kind: "fqn", separator: "_" } }, + ); + expect(Object.keys(doc.components.schemas)).toEqual([ + "Choice", + "Code", + "Inner", + "Models_Outer", + ]); + expect(doc.components.schemas.Models_Outer.properties).toEqual({ + inner: { $ref: "#/components/schemas/Inner" }, + choice: { $ref: "#/components/schemas/Choice" }, + code: { $ref: "#/components/schemas/Code" }, + }); + }); }); diff --git a/packages/openapi3/test/multipart.test.ts b/packages/openapi3/test/multipart.test.ts index 07b99e4c321..8f3575c0b42 100644 --- a/packages/openapi3/test/multipart.test.ts +++ b/packages/openapi3/test/multipart.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest"; import type { OpenAPI3Encoding, OpenAPI3Schema, OpenAPISchema3_1 } from "../src/types.js"; import { supportedVersions, worksFor } from "./works-for.js"; -worksFor(supportedVersions, ({ openApiFor, diagnoseOpenApiFor }) => { +worksFor(supportedVersions, ({ openApiFor, diagnoseOpenApiFor, emitOpenApiWithDiagnostics }) => { it("uses configured component names for repeated named multipart bodies", async () => { const res = await openApiFor( ` @@ -36,6 +36,32 @@ worksFor(supportedVersions, ({ openApiFor, diagnoseOpenApiFor }) => { expectDiagnostics(diagnostics, [{ code: "@typespec/openapi/duplicate-type-name" }]); }); + it("validates multipart keys before creating references with the default strategy", async () => { + const [doc, diagnostics] = await emitOpenApiWithDiagnostics(` + model \`Upload/Form\` { name: HttpPart; } + op upload(@multipartBody body: \`Upload/Form\`): void; + `); + expectDiagnostics(diagnostics, [ + { + code: "@typespec/openapi3/invalid-component-fixed-field-key", + }, + ]); + expect(Object.keys(doc.components!.schemas!)).toEqual(["Upload_Form"]); + expect(doc.paths["/"].post!.requestBody).toMatchObject({ + content: { "multipart/form-data": { schema: { $ref: "#/components/schemas/Upload_Form" } } }, + }); + }); + + it("reports duplicate multipart keys with the default strategy", async () => { + const diagnostics = await diagnoseOpenApiFor(` + @friendlyName("UploadForm") model First { a: HttpPart; } + @friendlyName("UploadForm") model Second { b: HttpPart; } + @route("/a") op first(@multipartBody body: First): void; + @route("/b") op second(@multipartBody body: Second): void; + `); + expectDiagnostics(diagnostics, [{ code: "@typespec/openapi/duplicate-type-name" }]); + }); + it("create dedicated model for multipart", async () => { const res = await openApiFor( ` diff --git a/packages/openapi3/test/parameters.test.ts b/packages/openapi3/test/parameters.test.ts index cc1bd081751..aea0376cc17 100644 --- a/packages/openapi3/test/parameters.test.ts +++ b/packages/openapi3/test/parameters.test.ts @@ -296,6 +296,7 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version }) => { expectDiagnostics(diagnostics, [ { code: "@typespec/openapi/duplicate-type-name", + message: /parameter/, }, ]); }); From 7518e655fc9e95a3f401fd5a503670b9eee28bd6 Mon Sep 17 00:00:00 2001 From: Timothee Guerin Date: Wed, 11 Nov 2026 09:34:50 -0500 Subject: [PATCH 4/5] refactor(openapi3): extract multipart validation fix --- ...pi3-component-naming-2026-10-6-11-13-33.md | 7 ---- packages/openapi3/src/openapi.ts | 18 +------- packages/openapi3/test/multipart.test.ts | 41 +------------------ 3 files changed, 2 insertions(+), 64 deletions(-) delete mode 100644 .chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-33.md diff --git a/.chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-33.md b/.chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-33.md deleted file mode 100644 index fed5173ddbc..00000000000 --- a/.chronus/changes/feat-openapi3-component-naming-2026-10-6-11-13-33.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -changeKind: fix -packages: - - "@typespec/openapi3" ---- - -Validate named multipart schema component keys and report duplicate keys consistently, including with the default naming strategy. \ No newline at end of file diff --git a/packages/openapi3/src/openapi.ts b/packages/openapi3/src/openapi.ts index 933c40b913a..9ded9f552da 100644 --- a/packages/openapi3/src/openapi.ts +++ b/packages/openapi3/src/openapi.ts @@ -365,7 +365,6 @@ function createOAPIEmitter( let visibilityUsage: VisibilityUsageTracker; let sseModule: SSEModule | undefined; let jsonSchemaModule: JsonSchemaModule | undefined; - let multipartSchemaTypes: Map; // Map model properties that represent shared parameters to their parameter // definition that will go in #/components/parameters. Inlined parameters do not go in @@ -527,7 +526,6 @@ function createOAPIEmitter( currentPath = root.paths; params = new Map(); - multipartSchemaTypes = new Map(); paramModels = new Set(); tagsUsedInOperations = new Set(); } @@ -1439,20 +1437,10 @@ function createOAPIEmitter( required: requiredProperties, }; - let name = + const name = "name" in body.type && body.type.name !== "" ? getComponentTypeName(program, body.type, typeNameOptions, options) : undefined; - if (name !== undefined) { - name = ensureValidComponentFixedFieldKey(program, body.type, name); - if (name) { - const existing = multipartSchemaTypes.get(name); - if (existing && existing !== body.type) { - checkDuplicateTypeName(program, body.type, name, root.components!.schemas!); - } - multipartSchemaTypes.set(name, body.type); - } - } if (name) { root.components!.schemas![name] = schema; } @@ -1870,10 +1858,6 @@ function createOAPIEmitter( const schemas = root.components!.schemas!; const declarations = files[0].globalScope.declarations; for (const declaration of declarations) { - const multipartType = multipartSchemaTypes.get(declaration.name); - if (multipartType) { - checkDuplicateTypeName(program, multipartType, declaration.name, schemas); - } schemas[declaration.name] = declaration.value as any; } } diff --git a/packages/openapi3/test/multipart.test.ts b/packages/openapi3/test/multipart.test.ts index 8f3575c0b42..90f2ca35800 100644 --- a/packages/openapi3/test/multipart.test.ts +++ b/packages/openapi3/test/multipart.test.ts @@ -1,10 +1,9 @@ -import { expectDiagnostics } from "@typespec/compiler/testing"; import { deepStrictEqual } from "assert"; import { describe, expect, it } from "vitest"; import type { OpenAPI3Encoding, OpenAPI3Schema, OpenAPISchema3_1 } from "../src/types.js"; import { supportedVersions, worksFor } from "./works-for.js"; -worksFor(supportedVersions, ({ openApiFor, diagnoseOpenApiFor, emitOpenApiWithDiagnostics }) => { +worksFor(supportedVersions, ({ openApiFor }) => { it("uses configured component names for repeated named multipart bodies", async () => { const res = await openApiFor( ` @@ -24,44 +23,6 @@ worksFor(supportedVersions, ({ openApiFor, diagnoseOpenApiFor, emitOpenApiWithDi } }); - it("reports transformed multipart and regular schema collisions", async () => { - const diagnostics = await diagnoseOpenApiFor( - ` - namespace Multipart { model Upload_Form { name: HttpPart; } } - namespace Payload { model Upload_Form { value: string; } } - op upload(@multipartBody body: Multipart.Upload_Form): Payload.Upload_Form; - `, - { "component-name-strategy": "name-only" }, - ); - expectDiagnostics(diagnostics, [{ code: "@typespec/openapi/duplicate-type-name" }]); - }); - - it("validates multipart keys before creating references with the default strategy", async () => { - const [doc, diagnostics] = await emitOpenApiWithDiagnostics(` - model \`Upload/Form\` { name: HttpPart; } - op upload(@multipartBody body: \`Upload/Form\`): void; - `); - expectDiagnostics(diagnostics, [ - { - code: "@typespec/openapi3/invalid-component-fixed-field-key", - }, - ]); - expect(Object.keys(doc.components!.schemas!)).toEqual(["Upload_Form"]); - expect(doc.paths["/"].post!.requestBody).toMatchObject({ - content: { "multipart/form-data": { schema: { $ref: "#/components/schemas/Upload_Form" } } }, - }); - }); - - it("reports duplicate multipart keys with the default strategy", async () => { - const diagnostics = await diagnoseOpenApiFor(` - @friendlyName("UploadForm") model First { a: HttpPart; } - @friendlyName("UploadForm") model Second { b: HttpPart; } - @route("/a") op first(@multipartBody body: First): void; - @route("/b") op second(@multipartBody body: Second): void; - `); - expectDiagnostics(diagnostics, [{ code: "@typespec/openapi/duplicate-type-name" }]); - }); - it("create dedicated model for multipart", async () => { const res = await openApiFor( ` From 5eee69208d20ad7b1bbe538ab5f7141c0cdcd9f4 Mon Sep 17 00:00:00 2001 From: Timothee Guerin Date: Thu, 12 Nov 2026 09:31:02 -0500 Subject: [PATCH 5/5] test(openapi3): use object expectations for single diagnostics --- packages/openapi3/test/component.test.ts | 2 +- packages/openapi3/test/parameters.test.ts | 10 ++++------ 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/openapi3/test/component.test.ts b/packages/openapi3/test/component.test.ts index a18e9920a48..5844b8d0f6a 100644 --- a/packages/openapi3/test/component.test.ts +++ b/packages/openapi3/test/component.test.ts @@ -412,7 +412,7 @@ worksFor(supportedVersions, async (specHelpers) => { `, { "component-name-strategy": "name-only" }, ); - expectDiagnostics(diagnostics, [{ code: "@typespec/openapi/duplicate-type-name" }]); + expectDiagnostics(diagnostics, { code: "@typespec/openapi/duplicate-type-name" }); }); }); diff --git a/packages/openapi3/test/parameters.test.ts b/packages/openapi3/test/parameters.test.ts index aea0376cc17..891e8e7599c 100644 --- a/packages/openapi3/test/parameters.test.ts +++ b/packages/openapi3/test/parameters.test.ts @@ -293,12 +293,10 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version }) => { "component-name-strategy": "name-only", }, ); - expectDiagnostics(diagnostics, [ - { - code: "@typespec/openapi/duplicate-type-name", - message: /parameter/, - }, - ]); + expectDiagnostics(diagnostics, { + code: "@typespec/openapi/duplicate-type-name", + message: /parameter/, + }); }); it("uses the configured separator for shared parameter properties", async () => {