diff --git a/.chronus/changes/copilot-tsp-openapi3-import-response-examples-2026-10-20-18-40-42.md b/.chronus/changes/copilot-tsp-openapi3-import-response-examples-2026-10-20-18-40-42.md new file mode 100644 index 00000000000..9a5cc33547d --- /dev/null +++ b/.chronus/changes/copilot-tsp-openapi3-import-response-examples-2026-10-20-18-40-42.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@typespec/openapi3" +--- + +[converter] Import response media type examples as operation return examples, preserving response status, media type, named keys, and descriptions. Named keys become decorator titles (and emitted summaries), so distinct source summaries cannot currently be retained. Conflicting example/examples fields are diagnosed and skipped. Unsupported values, required headers without values, status ranges, stream/item examples, and media types absent from generated component response models are diagnosed without discarding other valid examples. \ No newline at end of file diff --git a/packages/openapi3/src/cli/actions/convert/generators/generate-operation.ts b/packages/openapi3/src/cli/actions/convert/generators/generate-operation.ts index 659ebcfc4c2..dc93a805358 100644 --- a/packages/openapi3/src/cli/actions/convert/generators/generate-operation.ts +++ b/packages/openapi3/src/cli/actions/convert/generators/generate-operation.ts @@ -31,12 +31,13 @@ export function generateOperation(operation: TypeSpecOperation, context: Context ]; const responses = generateOperationReturnType(operation, context); + operationParts.push(...responses.examples); if (operation.fixmes?.length) { operationParts.push("\n", ...operation.fixmes.map((f) => `// FIXME: ${f}\n`)); } - operationParts.push(`op ${operation.name}(${parameters.join(", ")}): ${responses};`); + operationParts.push(`op ${operation.name}(${parameters.join(", ")}): ${responses.returnType};`); const preambleStr = preamble.join("\n"); const operationStr = operationParts.join(" "); diff --git a/packages/openapi3/src/cli/actions/convert/generators/generate-response-examples.ts b/packages/openapi3/src/cli/actions/convert/generators/generate-response-examples.ts new file mode 100644 index 00000000000..c87a898c3cc --- /dev/null +++ b/packages/openapi3/src/cli/actions/convert/generators/generate-response-examples.ts @@ -0,0 +1,350 @@ +import { Numeric, printIdentifier } from "@typespec/compiler"; +import type { + OpenAPI3Example, + OpenAPI3MediaType, + Refable, + SupportedOpenAPISchema, +} from "../../../../types.js"; +import type { TypeSpecModelProperty } from "../interfaces.js"; +import { getTypeSpecKind } from "../transforms/transform-component-schemas.js"; +import type { Context } from "../utils/context.js"; +import { isValidLiteralStatusCode } from "../utils/response-properties.js"; +import { getTypeSpecPrimitiveFromSchema } from "./generate-types.js"; + +export interface ResponseExampleShape { + statusCode: string; + mediaType: string; + content: OpenAPI3MediaType; + /** The properties actually emitted on the response envelope, if any. */ + properties: TypeSpecModelProperty[]; + /** The schema of an implicit body (including a response returned directly). */ + implicitBody?: Refable; + unsupportedReason?: string; +} + +export function generateResponseExamples( + shape: ResponseExampleShape, + scope: string[], + context: Context, +): string[] { + const { content, statusCode, mediaType } = shape; + const warn = (key: string | undefined, reason: string) => + context.logger.warn( + `Cannot import response example '${key ?? ""}' for ${statusCode}/${mediaType}: ${reason}`, + ); + // Neither field is truth-tested: null, false, zero, and "" are payloads. + if ("example" in content && "examples" in content) { + warn(undefined, "example and examples are mutually exclusive; skipping this media type."); + return []; + } + const entries: [string | undefined, Refable][] = + "example" in content + ? [[undefined, { value: content.example }]] + : Object.entries(content.examples ?? {}); + + const decorators: string[] = []; + for (const [key, entry] of entries) { + try { + if (shape.unsupportedReason) throw new Error(shape.unsupportedReason); + const example = resolveExample(entry, context); + if (!Object.hasOwn(example, "value")) { + throw new Error("only Example Objects with an inline value are supported."); + } + const value = generateResponseExampleValue(example.value, shape, scope, context); + const options = [ + ...(key !== undefined ? [`title: ${quote(key)}`] : []), + ...(example.description !== undefined + ? [`description: ${quote(example.description)}`] + : []), + ]; + // Do not use generateDecorators: it deduplicates repeatable decorators. + decorators.push( + `@opExample(#{ returnType: ${value} }${options.length ? `, #{ ${options.join(", ")} }` : ""})`, + ); + } catch (error) { + warn(key, error instanceof Error ? error.message : String(error)); + } + } + return decorators; +} + +function resolveExample(entry: Refable, context: Context): OpenAPI3Example { + const seen = new Set(); + while ("$ref" in entry) { + const ref = entry.$ref; + if (!ref.startsWith("#/components/examples/") || seen.has(ref)) { + throw new Error(`unsupported or cyclic Example Object reference: ${ref}`); + } + seen.add(ref); + const resolved = context.getByRef>(ref); + if (!resolved) throw new Error(`unresolved Example Object reference: ${ref}`); + entry = resolved; + } + return entry; +} + +export function generateResponseExampleValue( + payload: unknown, + shape: ResponseExampleShape, + scope: string[], + context: Context, +): string { + const body = shape.properties.find((p) => + p.decorators.some((d) => d.name === "body" || d.name === "bodyRoot"), + ); + const schema = body?.schema ?? shape.implicitBody; + if (!schema) throw new Error("the generated response has no representable body."); + const value = generateExampleValue(payload, schema, scope, context); + const properties: string[] = []; + if (body) { + properties.push(`${body.name}: ${value}`); + } else if (shape.properties.length === 0) { + return value; + } else { + // Implicit body properties and HTTP metadata are independent. + if (!value.startsWith("#{")) { + throw new Error("the generated implicit response body is not an object."); + } + const bodyProperties = value.slice(2, -1).trim(); + if (bodyProperties) properties.push(bodyProperties); + if ( + payload !== null && + typeof payload === "object" && + shape.properties.some((p) => + Object.keys(payload).some((key) => key === p.name || printIdentifier(key) === p.name), + ) + ) { + throw new Error("payload properties collide with generated response metadata."); + } + } + for (const property of shape.properties) { + if (property === body) continue; + if (property.decorators.some((d) => d.name === "statusCode")) { + if (!isValidLiteralStatusCode(shape.statusCode)) { + throw new Error("a status range cannot select an example without guessing a status."); + } + properties.push(`${property.name}: ${Number(shape.statusCode)}`); + } else if (isContentType(property)) { + properties.push(`${property.name}: ${quote(shape.mediaType)}`); + } else if (!property.isOptional) { + throw new Error(`required response header '${property.name}' has no example value.`); + } + } + return `#{ ${properties.join(", ")} }`; +} + +function isContentType(property: TypeSpecModelProperty): boolean { + return property.decorators.some( + (d) => + d.name === "header" && + (typeof d.args[0] === "string" + ? d.args[0].toLowerCase() === "content-type" + : property.name === "contentType"), + ); +} + +/** JSON escaping plus TypeSpec's additional string-interpolation escaping. */ +function quote(value: string): string { + return JSON.stringify(value).replaceAll("${", "\\${"); +} + +function generateExampleValue( + value: unknown, + schema: Refable, + scope: string[], + context: Context, + depth = 0, + scalarName?: string, +): string { + const invalid = () => { + throw new Error("payload cannot be represented in the generated response type."); + }; + if (depth > 100) return invalid(); + const convert = (v: unknown, s: Refable) => + generateExampleValue(v, s, scope, context, depth + 1); + if ("$ref" in schema) { + const resolved = context.getSchemaByRef(schema.$ref); + if (!resolved) return invalid(); + if (value === null && getTypeSpecKind(resolved) === "model") return invalid(); + const expression = generateExampleValue( + value, + resolved, + scope, + context, + depth + 1, + getTypeSpecKind(resolved) === "scalar" ? context.getRefName(schema.$ref, scope) : undefined, + ); + // String enums become nominal TypeSpec enums, not string literal unions. + if ( + resolved.type === "string" && + resolved.enum && + !("nullable" in resolved && resolved.nullable) + ) { + return `${context.getRefName(schema.$ref, scope)}.${printIdentifier(String(value), "disallow-reserved")}`; + } + return expression; + } + if (value === null) { + if ( + ("nullable" in schema && schema.nullable) || + schema.type === "null" || + (Array.isArray(schema.type) && schema.type.includes("null")) || + [...(schema.anyOf ?? []), ...(schema.oneOf ?? [])].some((s) => { + try { + return convert(null, s) === "null"; + } catch { + return false; + } + }) || + schema.const === null || + schema.enum?.includes(null as never) || + context.generateTypeFromRefableSchema(schema, scope) === "unknown" + ) { + return "null"; + } + return invalid(); + } + if (schema.enum && !schema.enum.includes(value as never)) return invalid(); + if ("const" in schema && schema.const !== undefined && schema.const !== value) return invalid(); + if (schema.enum || schema.const !== undefined) { + if (typeof value === "string") return quote(value); + if (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) { + return JSON.stringify(value); + } + return invalid(); + } + + if (schema.anyOf?.length || schema.oneOf?.length) { + for (const member of schema.anyOf ?? schema.oneOf ?? []) { + try { + return convert(value, member); + } catch { + // Try the next generated union variant. + } + } + return invalid(); + } + if (schema.allOf?.length) { + // Object intersections combine their properties and required lists. + let properties: Record> = { + ...schema.properties, + }; + const indexers: Refable[] = []; + if (typeof schema.additionalProperties === "object") indexers.push(schema.additionalProperties); + let allowsAdditionalProperties = !!schema.additionalProperties; + const required = new Set(schema.required); + const collect = (s: Refable, seen = new Set()): void => { + if ("$ref" in s) { + if (seen.has(s.$ref)) return invalid(); + seen.add(s.$ref); + const resolved = context.getSchemaByRef(s.$ref); + if (!resolved) return invalid(); + return collect(resolved, seen); + } + properties = { ...properties, ...s.properties }; + if (s.additionalProperties) { + allowsAdditionalProperties = true; + if (typeof s.additionalProperties === "object") indexers.push(s.additionalProperties); + } + for (const key of s.required ?? []) required.add(key); + for (const member of s.allOf ?? []) collect(member, new Set(seen)); + }; + for (const member of schema.allOf) collect(member); + if (value !== null && typeof value === "object" && !Array.isArray(value)) { + for (const item of Object.values(value)) { + const expressions = indexers.map((indexer) => convert(item, indexer)); + if (new Set(expressions).size > 1) return invalid(); + } + } + return convert(value, { + ...schema, + allOf: undefined, + properties, + required: [...required], + additionalProperties: indexers[0] ?? allowsAdditionalProperties, + } as SupportedOpenAPISchema); + } + + const declaredType = Array.isArray(schema.type) + ? schema.type.find((t) => t !== "null") + : schema.type; + const type = schema.items + ? "array" + : schema.properties || schema.additionalProperties + ? "object" + : declaredType; + if (Array.isArray(value)) { + if (type && type !== "array") return invalid(); + if ( + (schema.minItems !== undefined && value.length < schema.minItems) || + (schema.maxItems !== undefined && value.length > schema.maxItems) + ) + return invalid(); + return `#[${value.map((item) => convert(item, schema.items ?? {})).join(", ")}]`; + } + if (typeof value === "object" && value !== null) { + if (type && type !== "object") return invalid(); + const values = value as Record; + if ((schema.required ?? []).some((key) => !Object.hasOwn(values, key))) return invalid(); + const properties = Object.entries(values).map(([key, item]) => { + const knownProperty = Object.hasOwn(schema.properties ?? {}, key); + const itemSchema = knownProperty + ? (schema.properties?.[key] ?? {}) + : typeof schema.additionalProperties === "object" + ? schema.additionalProperties + : {}; + if (!knownProperty && type === "object" && !schema.additionalProperties) { + return invalid(); + } + return `${printIdentifier(key)}: ${convert(item, itemSchema)}`; + }); + return `#{ ${properties.join(", ")} }`; + } + if (typeof value === "string") { + if (type && type !== "string") return invalid(); + if ( + (schema.minLength !== undefined && value.length < schema.minLength) || + (schema.maxLength !== undefined && value.length > schema.maxLength) + ) + return invalid(); + const primitive = getTypeSpecPrimitiveFromSchema({ ...schema, type: "string" }); + switch (primitive) { + case "utcDateTime": + case "plainDate": + case "plainTime": + case "duration": + return `${scalarName ?? primitive}.fromISO(${quote(value)})`; + case "bytes": + return invalid(); + default: + return quote(value); + } + } + if (typeof value === "number" && Number.isFinite(value)) { + if (type && type !== "number" && type !== "integer") return invalid(); + if (type === "integer" && !Number.isInteger(value)) return invalid(); + if ( + (schema.minimum !== undefined && value < schema.minimum) || + (schema.maximum !== undefined && value > schema.maximum) + ) + return invalid(); + const primitive = getTypeSpecPrimitiveFromSchema({ + ...schema, + type: type === "number" || type === "integer" ? type : undefined, + }); + if (primitive === "duration" || primitive === "utcDateTime") return invalid(); + if (primitive === "float32" && Math.abs(value) > 3.4e38) return invalid(); + if (primitive === "safeint" && !Number.isSafeInteger(value)) return invalid(); + const integer = /^(u?)int(8|16|32|64)$/.exec(primitive ?? ""); + if (integer) { + const bits = BigInt(integer[2]); + const min = integer[1] ? 0n : -(1n << (bits - 1n)); + const max = integer[1] ? (1n << bits) - 1n : (1n << (bits - 1n)) - 1n; + const exact = Numeric(JSON.stringify(value)).asBigInt(); + if (exact === null || exact < min || exact > max) return invalid(); + } + return JSON.stringify(value); + } + if (typeof value === "boolean" && (!type || type === "boolean")) return String(value); + return invalid(); +} diff --git a/packages/openapi3/src/cli/actions/convert/generators/generate-response-expressions.ts b/packages/openapi3/src/cli/actions/convert/generators/generate-response-expressions.ts index 51b0b0e5ad2..8ad25aca98f 100644 --- a/packages/openapi3/src/cli/actions/convert/generators/generate-response-expressions.ts +++ b/packages/openapi3/src/cli/actions/convert/generators/generate-response-expressions.ts @@ -1,13 +1,18 @@ import type { OpenAPI3MediaType, OpenAPI3Response, Refable } from "../../../../types.js"; import type { TypeSpecModelProperty, TypeSpecOperation } from "../interfaces.js"; +import { getTypeSpecKind } from "../transforms/transform-component-schemas.js"; import type { Context } from "../utils/context.js"; import type { StatusCodes } from "../utils/response-properties.js"; import { convertHeaderToProperty, convertStatusCodeToProperty, + getComponentResponseProperties, + hasResponseExamples, + isScalarBody, isValidLiteralStatusCode, } from "../utils/response-properties.js"; import { generateModelExpression } from "./generate-model.js"; +import { generateResponseExamples } from "./generate-response-examples.js"; /** * Generates a union expression of all possible responses for an operation @@ -15,8 +20,15 @@ import { generateModelExpression } from "./generate-model.js"; export function generateOperationReturnType( operation: TypeSpecOperation, context: Context, -): string { +): { returnType: string; examples: string[] } { const expressions: string[] = []; + const examples: string[] = []; + const explicitStatusCodeFor200 = + Object.hasOwn(operation.responses, "default") && + Object.values(operation.responses).some((entry) => { + const response = "$ref" in entry ? context.getByRef(entry.$ref) : entry; + return hasResponseExamples(response?.content); + }); for (const [statusCode, response] of Object.entries(operation.responses)) { expressions.push( ...generateReturnTypeForStatusCode({ @@ -24,11 +36,13 @@ export function generateOperationReturnType( response, context, operationScope: operation.scope, + examples, + explicitStatusCodeFor200, }), ); } - return expressions.join(" | "); + return { returnType: expressions.join(" | "), examples }; } type GenerateReturnTypeForStatusCodeProps = { @@ -36,6 +50,8 @@ type GenerateReturnTypeForStatusCodeProps = { response: Refable; operationScope: string[]; context: Context; + examples: string[]; + explicitStatusCodeFor200: boolean; }; function generateReturnTypeForStatusCode(props: GenerateReturnTypeForStatusCodeProps): string[] { @@ -44,6 +60,28 @@ function generateReturnTypeForStatusCode(props: GenerateReturnTypeForStatusCodeP if ("$ref" in props.response && props.response.$ref.startsWith("#/components/responses/")) { const componentResponseName = context.getComponentResponseName(props.response.$ref, statusCode); if (componentResponseName) { + const response = context.getByRef(props.response.$ref); + if (response) { + const shape = getComponentResponseProperties(statusCode, response, context); + for (const [mediaType, content] of Object.entries(response.content ?? {})) { + props.examples.push( + ...generateResponseExamples( + { + statusCode, + mediaType, + content, + properties: shape.properties, + unsupportedReason: + mediaType !== shape.mediaType + ? "this media type is not represented by the generated component response model." + : undefined, + }, + props.operationScope, + context, + ), + ); + } + } return [componentResponseName]; } } @@ -75,6 +113,8 @@ function generateReturnTypeForStatusCode(props: GenerateReturnTypeForStatusCodeP contents: contentEntries, operationScope: props.operationScope, context, + examples: props.examples, + explicitStatusCodeFor200: props.explicitStatusCodeFor200, }); } @@ -126,6 +166,7 @@ type HandleDefaultResponseProps = { contents: [string, OpenAPI3MediaType][]; operationScope: string[]; context: Context; + examples: string[]; }; function handleDefaultResponse({ @@ -134,6 +175,7 @@ function handleDefaultResponse({ headers, operationScope, description, + examples, }: HandleDefaultResponseProps): string[] { if (!contents.length) { return [ @@ -150,7 +192,11 @@ function handleDefaultResponse({ const bodySchema = content.schema; const headerProps: TypeSpecModelProperty[] = [...headers]; // application/json is default contentType so can ignore it - if (mediaType !== "application/json") { + if ( + mediaType !== "application/json" || + (hasResponseExamples(Object.fromEntries(contents)) && + (contents.length > 1 || isScalarBody(bodySchema, context))) + ) { headerProps.push({ name: "contentType", decorators: [{ name: "header", args: [] }], @@ -159,6 +205,22 @@ function handleDefaultResponse({ }); } + const properties = [...headerProps]; + if (bodySchema) { + properties.push({ + name: "body", + decorators: [{ name: "body", args: [] }], + isOptional: false, + schema: bodySchema, + }); + } + examples.push( + ...generateResponseExamples( + { statusCode: "default", mediaType, content, properties }, + operationScope, + context, + ), + ); return generateDefaultResponse({ context, headers: headerProps, @@ -176,6 +238,8 @@ type GenerateResponseExpressionsProps = { contents: [string, OpenAPI3MediaType][]; operationScope: string[]; context: Context; + examples: string[]; + explicitStatusCodeFor200: boolean; }; function generateResponseExpressions({ @@ -185,13 +249,22 @@ function generateResponseExpressions({ headers, operationScope, description, + examples, + explicitStatusCodeFor200, }: GenerateResponseExpressionsProps): string[] { const hasContents = contents.length > 0; const statusCodeMetadata = getStatusCodeMetadata(statusCode); if (statusCodeMetadata.isDefault) { - return handleDefaultResponse({ headers, contents, operationScope, context, description }); + return handleDefaultResponse({ + headers, + contents, + operationScope, + context, + description, + examples, + }); } // Scenario 1 - only have a mapped status code - use it directly @@ -203,7 +276,7 @@ function generateResponseExpressions({ // 200 statusCode is default, we can ignore it since we know we have headers or body to fill out response if (statusCodeMetadata.literalStatusCode === 200) { statusCodeMetadata.httpLibModel = undefined; - statusCodeMetadata.modelProperty = undefined; + if (!explicitStatusCodeFor200) statusCodeMetadata.modelProperty = undefined; } // Scenario 2 - have a status code and headers, but no bodies. @@ -223,6 +296,10 @@ function generateResponseExpressions({ } return contents.map(([mediaType, content]) => { + const explicitContentType = + mediaType !== "application/json" || + (hasResponseExamples(Object.fromEntries(contents)) && + (contents.length > 1 || isScalarBody(content.schema, context))); // Special handling for Server-Sent Events if ( !context.openApi3Doc.openapi.startsWith("3.0") && @@ -239,6 +316,19 @@ function generateResponseExpressions({ operationScope, ); context.markSSEUsage(); + examples.push( + ...generateResponseExamples( + { + statusCode, + mediaType, + content, + properties: [], + unsupportedReason: "stream and item examples are not supported.", + }, + operationScope, + context, + ), + ); return `SSEStream<${eventUnionType}>`; // If no proper schema reference, fall through to regular handling } @@ -246,10 +336,29 @@ function generateResponseExpressions({ // Attempt to emit just the Body or an intersection of Body & MappedResponse // if there aren't any custom headers. const bodySchema = content.schema; - if (bodySchema && mediaType === "application/json" && !headers.length) { + const canUseImplicitBody = !( + bodySchema && + "$ref" in bodySchema && + hasResponseExamples(Object.fromEntries(contents)) && + !canIntersectBody(bodySchema.$ref, context) + ); + if (bodySchema && !explicitContentType && !headers.length && canUseImplicitBody) { // Scenario 3 - have a mapped status code and body schema is a ref using application/json - intersection! // Example: CreatedResponse & Widget if ("$ref" in bodySchema && statusCodeMetadata.httpLibModel) { + examples.push( + ...generateResponseExamples( + { + statusCode, + mediaType, + content, + properties: [statusCodeMetadata.modelProperty!], + implicitBody: bodySchema, + }, + operationScope, + context, + ), + ); return `${statusCodeMetadata.httpLibModel} & ${context.generateTypeFromRefableSchema( bodySchema, operationScope, @@ -258,11 +367,37 @@ function generateResponseExpressions({ // Scenario 4 - 200 status code and using application/json - return just the body // Example: Widget // Example: Body - if (statusCodeMetadata.literalStatusCode === 200) { + if (statusCodeMetadata.literalStatusCode === 200 && !statusCodeMetadata.modelProperty) { const body = context.generateTypeFromRefableSchema(bodySchema, operationScope); if ("$ref" in bodySchema) { + examples.push( + ...generateResponseExamples( + { statusCode, mediaType, content, properties: [], implicitBody: bodySchema }, + operationScope, + context, + ), + ); return body; } + examples.push( + ...generateResponseExamples( + { + statusCode, + mediaType, + content, + properties: [ + { + name: "body", + decorators: [{ name: "body", args: [] }], + isOptional: false, + schema: bodySchema, + }, + ], + }, + operationScope, + context, + ), + ); return `Body<${body}>`; } } @@ -275,7 +410,7 @@ function generateResponseExpressions({ modelExpressionProps.push(...headers); // application/json is default contentType so can ignore it - if (mediaType !== "application/json") { + if (explicitContentType) { modelExpressionProps.push({ name: "contentType", decorators: [{ name: "header", args: [] }], @@ -292,10 +427,41 @@ function generateResponseExpressions({ }); } + examples.push( + ...generateResponseExamples( + { statusCode, mediaType, content, properties: modelExpressionProps }, + operationScope, + context, + ), + ); return generateModelExpression(modelExpressionProps, operationScope, context); }); } +function canIntersectBody(ref: string, context: Context, seen = new Set()): boolean { + if (seen.has(ref)) return false; + seen.add(ref); + const schema = context.getSchemaByRef(ref); + if (!schema) return false; + if ("$ref" in schema && typeof schema.$ref === "string") { + return canIntersectBody(schema.$ref, context, seen); + } + return ( + getTypeSpecKind(schema) === "model" && + schema.type !== "array" && + !schema.items && + (Object.keys(schema.properties ?? {}).length > 0 || + !!schema.additionalProperties || + !!schema.allOf?.length) && + !Object.hasOwn(schema.properties ?? {}, "statusCode") && + (schema.allOf ?? []).every((member) => + "$ref" in member + ? canIntersectBody(member.$ref, context, new Set(seen)) + : !Object.hasOwn(member.properties ?? {}, "statusCode"), + ) + ); +} + type GenerateDefaultResponseProps = { description?: string; headers: TypeSpecModelProperty[]; diff --git a/packages/openapi3/src/cli/actions/convert/transforms/transform-component-schemas.ts b/packages/openapi3/src/cli/actions/convert/transforms/transform-component-schemas.ts index cff55f75f17..72162a0abe9 100644 --- a/packages/openapi3/src/cli/actions/convert/transforms/transform-component-schemas.ts +++ b/packages/openapi3/src/cli/actions/convert/transforms/transform-component-schemas.ts @@ -372,7 +372,9 @@ function getModelPropertiesFromObjectSchema( return modelProperties; } -function getTypeSpecKind(schema: Refable): TypeSpecDataTypes["kind"] { +export function getTypeSpecKind( + schema: Refable, +): TypeSpecDataTypes["kind"] { if ("$ref" in schema) { return "alias"; } diff --git a/packages/openapi3/src/cli/actions/convert/transforms/transforms.ts b/packages/openapi3/src/cli/actions/convert/transforms/transforms.ts index f32b397174a..a771d51b418 100644 --- a/packages/openapi3/src/cli/actions/convert/transforms/transforms.ts +++ b/packages/openapi3/src/cli/actions/convert/transforms/transforms.ts @@ -8,20 +8,11 @@ import type { OpenAPIResponses3_2, Refable, SupportedOpenAPIDocuments, - SupportedOpenAPISchema, } from "../../../../types.js"; -import type { - TypeSpecDataTypes, - TypeSpecModel, - TypeSpecModelProperty, - TypeSpecProgram, -} from "../interfaces.js"; +import type { TypeSpecDataTypes, TypeSpecModel, TypeSpecProgram } from "../interfaces.js"; import type { Context } from "../utils/context.js"; import { getScopeAndName } from "../utils/get-scope-and-name.js"; -import { - convertHeaderToProperty, - convertStatusCodeToProperty, -} from "../utils/response-properties.js"; +import { getComponentResponseProperties } from "../utils/response-properties.js"; import { transformComponentParameters } from "./transform-component-parameters.js"; import { transformComponentSchemas } from "./transform-component-schemas.js"; import { transformNamespaces } from "./transform-namespaces.js"; @@ -375,60 +366,10 @@ export function transformComponentResponses( scope: namespace, decorators: statusCode === "default" ? [{ name: "error", args: [] }] : [], doc: componentResponse.description, - properties: getResponseProperties(statusCode, componentResponse, context), + properties: getComponentResponseProperties(statusCode, componentResponse, context) + .properties, }); } } } } - -function getResponseProperties( - statusCode: string, - response: OpenAPI3Response, - context: Context, -): TypeSpecModelProperty[] { - const properties: TypeSpecModelProperty[] = []; - const resolvedStatus = statusCode === "default" ? "default" : statusCode; - - if (resolvedStatus !== "default") { - properties.push(convertStatusCodeToProperty(resolvedStatus)); - } - - for (const [headerName, header] of Object.entries(response.headers ?? {})) { - const property = convertHeaderToProperty({ name: headerName, header, context }); - if (property) { - properties.push(property); - } - } - - const contentEntries = Object.entries(response.content ?? {}); - const preferredContent = [ - contentEntries.find(([mediaType]) => mediaType === "application/json"), - contentEntries[0], - ].find((entry): entry is [string, any] => !!entry); - - const bodySchema = - preferredContent && typeof preferredContent[1] === "object" && "schema" in preferredContent[1] - ? (preferredContent[1].schema as Refable) - : undefined; - - if (preferredContent && preferredContent[0] !== "application/json") { - properties.push({ - name: "contentType", - decorators: [{ name: "header", args: ["Content-Type"] }], - isOptional: false, - schema: { type: "string", enum: [preferredContent[0]] }, - }); - } - - if (bodySchema) { - properties.push({ - name: "body", - decorators: [{ name: "body", args: [] }], - isOptional: false, - schema: bodySchema, - }); - } - - return properties; -} diff --git a/packages/openapi3/src/cli/actions/convert/utils/response-properties.ts b/packages/openapi3/src/cli/actions/convert/utils/response-properties.ts index 71d9f62b24f..f97a88265ea 100644 --- a/packages/openapi3/src/cli/actions/convert/utils/response-properties.ts +++ b/packages/openapi3/src/cli/actions/convert/utils/response-properties.ts @@ -1,4 +1,10 @@ -import type { OpenAPI3Header, OpenAPI3Schema, Refable } from "../../../../types.js"; +import type { + OpenAPI3Header, + OpenAPI3Response, + OpenAPI3Schema, + Refable, + SupportedOpenAPISchema, +} from "../../../../types.js"; import type { TypeSpecDecorator, TypeSpecModelProperty } from "../interfaces.js"; import type { Context } from "./context.js"; import { convertHeaderName } from "./convert-header-name.js"; @@ -44,6 +50,37 @@ export function convertStatusCodeToProperty(statusCode: string): TypeSpecModelPr }; } +export function hasResponseExamples(content: OpenAPI3Response["content"]): boolean { + return Object.values(content ?? {}).some((c) => "example" in c || "examples" in c); +} + +/** Scalars do not necessarily default to application/json in the HTTP library. */ +export function isScalarBody( + schema: Refable | undefined, + context: Context, + seen = new Set(), +): boolean { + if (!schema) return false; + if ("$ref" in schema) { + if (seen.has(schema.$ref)) return false; + seen.add(schema.$ref); + return isScalarBody(context.getSchemaByRef(schema.$ref), context, seen); + } + return ( + schema.type === "string" || + schema.type === "number" || + schema.type === "integer" || + schema.type === "boolean" || + (Array.isArray(schema.type) && + schema.type.some((type) => ["string", "number", "integer", "boolean"].includes(type))) || + [schema.const, ...(schema.enum ?? [])].some( + (value) => + typeof value === "string" || typeof value === "number" || typeof value === "boolean", + ) || + (schema.anyOf ?? schema.oneOf ?? []).some((s) => isScalarBody(s, context, new Set(seen))) + ); +} + export type ConvertHeaderToPropertyProps = { name: string; header: Refable; @@ -54,6 +91,8 @@ export function convertHeaderToProperty( props: ConvertHeaderToPropertyProps, ): TypeSpecModelProperty | undefined { const { name, context } = props; + if (name.toLowerCase() === "content-type") return; + const header = "$ref" in props.header ? context.getByRef(props.header.$ref) : props.header; @@ -74,3 +113,42 @@ export function convertHeaderToProperty( schema: header.schema ?? {}, }; } + +/** Properties and media type selected for a generated component response model. */ +export function getComponentResponseProperties( + statusCode: string, + response: OpenAPI3Response, + context: Context, +): { properties: TypeSpecModelProperty[]; mediaType?: string } { + const properties: TypeSpecModelProperty[] = []; + if (statusCode !== "default") { + properties.push(convertStatusCodeToProperty(statusCode)); + } + for (const [name, header] of Object.entries(response.headers ?? {})) { + const property = convertHeaderToProperty({ name, header, context }); + if (property) properties.push(property); + } + const contents = Object.entries(response.content ?? {}); + const preferred = contents.find(([mediaType]) => mediaType === "application/json") ?? contents[0]; + if ( + preferred && + (preferred[0] !== "application/json" || + (hasResponseExamples(response.content) && isScalarBody(preferred[1].schema, context))) + ) { + properties.push({ + name: "contentType", + decorators: [{ name: "header", args: ["Content-Type"] }], + isOptional: false, + schema: { type: "string", enum: [preferred[0]] }, + }); + } + if (preferred?.[1].schema) { + properties.push({ + name: "body", + decorators: [{ name: "body", args: [] }], + isOptional: false, + schema: preferred[1].schema, + }); + } + return { properties, mediaType: preferred?.[0] }; +} diff --git a/packages/openapi3/src/examples.ts b/packages/openapi3/src/examples.ts index b6fe3179db9..201091248f7 100644 --- a/packages/openapi3/src/examples.ts +++ b/packages/openapi3/src/examples.ts @@ -185,6 +185,15 @@ function findResponseForExample( const contentTypeProp = response.properties.find((x) => x.kind === "contentType"); const statusCodeProp = response.properties.find((x) => x.kind === "statusCode"); + if ( + statusCode === undefined && + statusCodeProp && + !statusCodeProp.property.optional && + statusCodeResponse.statusCodes !== "*" + ) { + continue; + } + const statusCodeMatch = statusCode && statusCodeProp && isStatusCodeIn(statusCode, statusCodeResponse.statusCodes); const contentTypeMatch = contentType && response.body?.contentTypes.includes(contentType); diff --git a/packages/openapi3/src/types.ts b/packages/openapi3/src/types.ts index b9515b5e84e..05df8c8f841 100644 --- a/packages/openapi3/src/types.ts +++ b/packages/openapi3/src/types.ts @@ -247,7 +247,7 @@ export type OpenAPI3MediaType = Extensions & { example?: unknown; /** Examples with title */ - examples?: Record; + examples?: Record>; }; /** diff --git a/packages/openapi3/test/tsp-openapi3/response-examples.test.ts b/packages/openapi3/test/tsp-openapi3/response-examples.test.ts new file mode 100644 index 00000000000..2bc68a823a0 --- /dev/null +++ b/packages/openapi3/test/tsp-openapi3/response-examples.test.ts @@ -0,0 +1,805 @@ +import { ApiTester } from "#test/test-host.js"; +import { describe, expect, it, vi } from "vitest"; +import { + generateResponseExampleValue, + type ResponseExampleShape, +} from "../../src/cli/actions/convert/generators/generate-response-examples.js"; +import type { TypeSpecModelProperty } from "../../src/cli/actions/convert/interfaces.js"; +import { createContext } from "../../src/cli/actions/convert/utils/context.js"; +import { convertOpenAPI3Document } from "../../src/index.js"; +import type { + OpenAPI3Document, + OpenAPI3MediaType, + OpenAPI3Response, + OpenAPI3Schema, + Refable, + SupportedOpenAPIDocuments, +} from "../../src/types.js"; + +const message: OpenAPI3Schema = { + type: "object", + required: ["body", "id"], + properties: { body: { type: "string" }, id: { type: "integer", format: "int32" } }, +}; +const payload = { body: "hello", id: 1 }; + +function document( + responses: Record>, + components: OpenAPI3Document["components"] = {}, +): OpenAPI3Document { + return { + openapi: "3.0.0", + info: { title: "Test", version: "1.0" }, + paths: { "/test": { get: { operationId: "read", parameters: [], responses } } }, + components, + }; +} + +function response(content: OpenAPI3MediaType): OpenAPI3Response { + return { description: "Response", content: { "application/json": content } }; +} + +async function roundTrip(input: OpenAPI3Document) { + const code = await convertOpenAPI3Document(input); + return { code, responses: (await emit(code)).paths["/test"].get.responses }; +} + +async function emit(code: string) { + const { outputs } = await ApiTester.emit("@typespec/openapi3").compile(code, { + compilerOptions: { + options: { "@typespec/openapi3": { "file-type": "json", "output-file": "openapi.json" } }, + }, + }); + const output = JSON.parse(outputs["openapi.json"]); + // Payload examples must never become schema-level examples. + for (const schema of Object.values(output.components?.schemas ?? {})) { + expect(schema).not.toHaveProperty("example"); + expect(schema).not.toHaveProperty("examples"); + } + return output; +} + +describe("response media type examples", () => { + it.each(["200", "201", "203", "404"])( + "imports an inline object for status %s using the generated wrapper", + async (status) => { + const { code, responses } = await roundTrip( + document({ [status]: response({ schema: message, example: payload }) }), + ); + expect(code.match(/@opExample\(/g)).toHaveLength(1); + expect(Object.keys(responses)).toEqual([status]); + expect(responses[status].content["application/json"].example).toEqual(payload); + }, + ); + + it.each(["200", "201", "203", "404"])( + "imports a referenced model for status %s, preserving implicit body fields", + async (status) => { + const { responses } = await roundTrip( + document( + { + [status]: response({ + schema: { $ref: "#/components/schemas/Message" }, + example: payload, + }), + }, + { schemas: { Message: message } }, + ), + ); + expect(responses[status].content["application/json"].example).toEqual(payload); + }, + ); + + it.each(["200", "201"])( + "uses the generated referenced response model for status %s", + async (status) => { + const { responses } = await roundTrip( + document( + { [status]: { $ref: "#/components/responses/MessageResponse" } }, + { + responses: { + MessageResponse: response({ schema: message, example: payload }), + }, + }, + ), + ); + expect(responses[status].content["application/json"].example).toEqual(payload); + }, + ); + + it.each([ + ["array", { type: "array", items: { type: "integer" } }, [0, 1]], + ["empty array", { type: "array", items: { type: "string" } }, []], + ["false", { type: "boolean" }, false], + ["zero", { type: "integer" }, 0], + ["empty string", { type: "string" }, ""], + ["null", { type: "string", nullable: true }, null], + [ + "value field", + { type: "object", properties: { value: { type: "string" } } }, + { value: "raw" }, + ], + [ + "escaped property", + { type: "object", properties: { "a-b": { type: "string" } } }, + { "a-b": "${literal}" }, + ], + ] as const)("preserves a singular %s payload", async (_, schema, value) => { + for (const status of ["200", "201"]) { + const { code, responses } = await roundTrip( + document({ [status]: response({ schema: schema as OpenAPI3Schema, example: value }) }), + ); + expect(code.match(/@opExample\(/g)).toHaveLength(1); + expect(responses[status].content["application/json"].example).toEqual(value); + } + }); + + it("keeps a single named entry named, using the key rather than summary", async () => { + const { responses } = await roundTrip( + document({ + "200": response({ + schema: message, + examples: { + small: { summary: "Compact message", description: "Details", value: payload }, + }, + }), + }), + ); + expect(responses["200"].content["application/json"]).toMatchObject({ + examples: { small: { summary: "small", description: "Details", value: payload } }, + }); + expect(responses["200"].content["application/json"]).not.toHaveProperty("example"); + }); + + it("does not collapse equal payloads or equal summaries", async () => { + const { code, responses } = await roundTrip( + document({ + "200": response({ + schema: message, + examples: { + first: { summary: "Same", value: payload }, + second: { summary: "Same", value: payload }, + }, + }), + }), + ); + expect(code.match(/@opExample\(/g)).toHaveLength(2); + expect(responses["200"].content["application/json"].examples).toEqual({ + first: { summary: "first", value: payload }, + second: { summary: "second", value: payload }, + }); + }); + + it.each([false, true])( + "routes named examples independently by status and media type (json first: %s)", + async (jsonFirst) => { + const json = { + schema: { $ref: "#/components/schemas/Message" }, + examples: { small: { value: payload }, other: { value: { body: "other", id: 2 } } }, + }; + const vendor = { + schema: { $ref: "#/components/schemas/Message" }, + examples: { small: { value: { body: "vendor", id: 3 } } }, + }; + const content = jsonFirst + ? { "application/json": json, "application/vnd.example+json": vendor } + : { "application/vnd.example+json": vendor, "application/json": json }; + const { code, responses } = await roundTrip( + document( + { + "200": { description: "OK", content }, + "404": { + description: "Missing", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/Message" }, + examples: { small: { value: { body: "missing", id: 4 } } }, + }, + }, + }, + }, + { schemas: { Message: message } }, + ), + ); + expect(code.match(/@opExample\(/g)).toHaveLength(4); + expect(Object.keys(responses)).toEqual(["200", "404"]); + expect(Object.keys(responses["200"].content)).toEqual(Object.keys(content)); + expect(responses["200"].content["application/json"].examples).toEqual({ + small: { summary: "small", value: payload }, + other: { summary: "other", value: { body: "other", id: 2 } }, + }); + expect(responses["200"].content["application/vnd.example+json"].examples).toEqual({ + small: { summary: "small", value: { body: "vendor", id: 3 } }, + }); + expect(responses["404"].content["application/json"].examples).toEqual({ + small: { summary: "small", value: { body: "missing", id: 4 } }, + }); + }, + ); + + it("routes scalar examples with content type independently of status", async () => { + const { responses } = await roundTrip( + document({ + "200": { + description: "OK", + content: { + "application/json": { schema: { type: "string" }, example: "json" }, + "text/plain": { schema: { type: "string" }, example: "plain" }, + }, + }, + }), + ); + expect(responses["200"].content["application/json"].example).toBe("json"); + expect(responses["200"].content["text/plain"].example).toBe("plain"); + }); + + it("retains a payload field named statusCode as data", async () => { + const schema: OpenAPI3Schema = { + type: "object", + properties: { statusCode: { type: "string" }, body: { type: "string" } }, + required: ["statusCode", "body"], + }; + const value = { statusCode: "ordinary", body: "hello" }; + const { responses } = await roundTrip( + document({ "201": response({ schema, example: value }) }), + ); + expect(responses["201"].content["application/json"].example).toEqual(value); + }); + + it("allows optional response headers without inventing header values", async () => { + const { responses } = await roundTrip( + document({ + "200": { + ...response({ schema: message, example: payload }), + headers: { "x-trace-id": { schema: { type: "string" } } }, + }, + }), + ); + expect(responses["200"].content["application/json"].example).toEqual(payload); + }); + + it("uses the media type rather than a response Content-Type header", async () => { + const { responses } = await roundTrip( + document({ + "200": { + ...response({ schema: { type: "string" }, example: "hello" }), + headers: { + "Content-Type": { + required: true, + schema: { type: "string", enum: ["text/plain"] }, + }, + }, + }, + }), + ); + expect(Object.keys(responses["200"].content)).toEqual(["application/json"]); + expect(responses["200"].content["application/json"].example).toBe("hello"); + }); + + it("resolves local Example Object references, retaining the referencing key", async () => { + const { responses } = await roundTrip( + document( + { + "200": response({ + schema: message, + examples: { small: { $ref: "#/components/examples/SmallMessage" } }, + }), + }, + { + examples: { + SmallMessage: { summary: "Original", description: "Details", value: payload }, + }, + }, + ), + ); + expect(responses["200"].content["application/json"].examples).toEqual({ + small: { summary: "small", description: "Details", value: payload }, + }); + }); + + it.each(["2XX", "default"])("does not guess a concrete status for %s", async (status) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const { responses, code } = await roundTrip( + document({ [status]: response({ schema: message, example: payload }) }), + ); + // default is expressible without a concrete status; a range requires one. + if (status === "default") { + expect(responses.default.content["application/json"].example).toEqual(payload); + } else { + expect(code).not.toContain("@opExample"); + expect(warn).toHaveBeenCalled(); + expect(responses["2XX"].content["application/json"]).not.toHaveProperty("example"); + } + } finally { + warn.mockRestore(); + } + }); + + it("imports no examples for an empty examples map", async () => { + const { code } = await roundTrip( + document({ "200": response({ schema: message, examples: {} }) }), + ); + expect(code).not.toContain("@opExample"); + }); + + it.each(["3.1.0", "3.2.0"])("imports response examples from OpenAPI %s", async (version) => { + const input = { + ...document({ + "201": response({ schema: message, examples: { small: { value: payload } } }), + }), + openapi: version, + } as SupportedOpenAPIDocuments; + const code = await convertOpenAPI3Document(input); + const output = await emit(code); + expect(output.paths["/test"].get.responses["201"].content["application/json"].examples).toEqual( + { small: { summary: "small", value: payload } }, + ); + }); + + it.each([ + ["date", { type: "string", format: "date" }, "2026-01-02"], + ["literal with format", { type: "string", format: "date", enum: ["2026-01-02"] }, "2026-01-02"], + ["date-time", { type: "string", format: "date-time" }, "2026-01-02T03:04:05Z"], + ["escaped string", { type: "string" }, '\\\n"\t${literal}'], + ["union", { anyOf: [{ type: "integer" }, { type: "string" }] }, "hello"], + ["record", { type: "object", additionalProperties: { type: "integer" } }, { a: 1 }], + ] as const)("converts a %s value", async (_, schema, value) => { + const { responses } = await roundTrip( + document({ "201": response({ schema: schema as OpenAPI3Schema, example: value }) }), + ); + expect(responses["201"].content["application/json"].example).toEqual(value); + }); + + it("diagnoses conflicting example and examples and skips the media type", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const { code } = await roundTrip( + document({ + "200": response({ + schema: message, + example: payload, + examples: { small: { value: payload } }, + }), + }), + ); + expect(code).not.toContain("@opExample"); + expect(warn).toHaveBeenCalledWith(expect.stringMatching(/example.*examples/)); + } finally { + warn.mockRestore(); + } + }); + + it.each([ + ["externalValue", { externalValue: "https://example.com/example.json" }], + ["missing value", { summary: "No value" }], + ["unresolved reference", { $ref: "#/components/examples/Missing" }], + ["wrong type", { value: "not an object" }], + ["missing required property", { value: { body: "hello" } }], + ["invalid nested property", { value: { body: "hello", id: "wrong" } }], + ])("diagnoses %s and continues importing valid entries", async (_, invalid) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const { code, responses } = await roundTrip( + document({ + "200": response({ + schema: message, + examples: { unsupported: invalid, valid: { value: payload } }, + }), + }), + ); + expect(code.match(/@opExample\(/g)).toHaveLength(1); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("unsupported")); + expect(responses["200"].content["application/json"].examples).toEqual({ + valid: { summary: "valid", value: payload }, + }); + } finally { + warn.mockRestore(); + } + }); + + it("diagnoses required response headers without inventing values", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const { code, responses } = await roundTrip( + document({ + "200": { + ...response({ schema: message, example: payload }), + headers: { "x-required": { required: true, schema: { type: "string" } } }, + }, + }), + ); + expect(code).not.toContain("@opExample"); + expect(warn).toHaveBeenCalledWith(expect.stringMatching(/required.*header/i)); + expect(responses["200"].content["application/json"]).not.toHaveProperty("example"); + } finally { + warn.mockRestore(); + } + }); + + it.each([ + ["string", { type: "string" }, "hello"], + ["date scalar", { type: "string", format: "date" }, "2026-01-02"], + ["array", { type: "array", items: { type: "integer" } }, [1, 2]], + ["enum", { type: "string", enum: ["small", "large"] }, "small"], + ] as const)("imports a referenced %s body for 200 and 201", async (_, schema, value) => { + for (const status of ["200", "201"]) { + const { responses } = await roundTrip( + document( + { + [status]: response({ + schema: { $ref: "#/components/schemas/Payload" }, + example: value, + }), + }, + { schemas: { Payload: schema as OpenAPI3Schema } }, + ), + ); + expect(responses[status].content["application/json"].example).toEqual(value); + } + }); + + it("converts nested referenced enums and arrays against the generated types", async () => { + const value = { sizes: ["small", "large"] }; + const { responses } = await roundTrip( + document( + { + "201": response({ + schema: { + type: "object", + properties: { + sizes: { type: "array", items: { $ref: "#/components/schemas/Size" } }, + }, + required: ["sizes"], + }, + example: value, + }), + }, + { schemas: { Size: { type: "string", enum: ["small", "large"] } } }, + ), + ); + expect(responses["201"].content["application/json"].example).toEqual(value); + }); + + it("imports an empty implicit response body without a leading comma", async () => { + const { responses } = await roundTrip( + document( + { + "201": response({ schema: { $ref: "#/components/schemas/Empty" }, example: {} }), + }, + { schemas: { Empty: { type: "object" } } }, + ), + ); + expect(responses["201"].content["application/json"].example).toEqual({}); + }); + + it("does not mistake a payload statusCode for the response discriminator", async () => { + const schema: OpenAPI3Schema = { + type: "object", + properties: { statusCode: { type: "integer" } }, + required: ["statusCode"], + }; + const { responses } = await roundTrip( + document({ + "200": response({ schema, example: { statusCode: 404 } }), + "404": response({ schema, example: { statusCode: 200 } }), + }), + ); + expect(responses["200"].content["application/json"].example).toEqual({ statusCode: 404 }); + expect(responses["404"].content["application/json"].example).toEqual({ statusCode: 200 }); + }); + + it("keeps a default example separate from a 200 response with the same body", async () => { + const { responses } = await roundTrip( + document({ + "200": response({ schema: message, example: payload }), + default: response({ schema: message, example: { body: "default", id: 2 } }), + }), + ); + expect(responses["200"].content["application/json"].example).toEqual(payload); + expect(responses.default.content["application/json"].example).toEqual({ + body: "default", + id: 2, + }); + }); + + it("keeps scalar default examples separate from concrete responses", async () => { + const schema: OpenAPI3Schema = { type: "string" }; + const { responses } = await roundTrip( + document({ + "200": response({ schema, example: "success" }), + default: response({ schema, example: "fallback" }), + }), + ); + expect(responses["200"].content["application/json"].example).toBe("success"); + expect(responses.default.content["application/json"].example).toBe("fallback"); + }); + + it.each([ + ["enum", { enum: ["demo"] }], + ["const", { const: "demo" }], + ])("preserves JSON media type for an untyped %s", async (_, schema) => { + const { responses } = await roundTrip( + document({ "200": response({ schema: schema as OpenAPI3Schema, example: "demo" }) }), + ); + expect(responses["200"].content["application/json"].example).toBe("demo"); + }); + + it("imports examples of intersections with referenced record schemas", async () => { + const { responses } = await roundTrip( + document( + { + "200": response({ + schema: { allOf: [{ $ref: "#/components/schemas/Bag" }] }, + example: { a: 1 }, + }), + }, + { schemas: { Bag: { type: "object", additionalProperties: { type: "integer" } } } }, + ), + ); + expect(responses["200"].content["application/json"].example).toEqual({ a: 1 }); + }); + + it("checks inherited record values and retains valid examples", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const { responses } = await roundTrip( + document( + { + "200": response({ + schema: { allOf: [{ $ref: "#/components/schemas/Bag" }] }, + examples: { invalid: { value: { a: "wrong" } }, valid: { value: { a: 1 } } }, + }), + }, + { schemas: { Bag: { type: "object", additionalProperties: { type: "integer" } } } }, + ), + ); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("invalid")); + expect(responses["200"].content["application/json"].examples).toEqual({ + valid: { summary: "valid", value: { a: 1 } }, + }); + } finally { + warn.mockRestore(); + } + }); + + it.each([ + ["float32 maximum", { type: "number", format: "float" }, 3.4e38], + ["float32 minimum", { type: "number", format: "float" }, -3.4e38], + ["safeint maximum", { type: "integer", format: "double-int" }, Number.MAX_SAFE_INTEGER], + ["safeint minimum", { type: "integer", format: "double-int" }, Number.MIN_SAFE_INTEGER], + ["nullable int32 maximum", { type: ["integer", "null"], format: "int32" }, 2 ** 31 - 1], + ] as const)("preserves %s", async (_, schema, value) => { + const { responses } = await roundTrip( + document({ "201": response({ schema: schema as OpenAPI3Schema, example: value }) }), + ); + expect(responses["201"].content["application/json"].example).toBe(value); + }); + + it("skips null examples for referenced components generated as non-nullable models", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const { code, responses } = await roundTrip( + document( + { + "200": response({ + schema: { $ref: "#/components/schemas/Payload" }, + examples: { invalid: { value: null }, valid: { value: { name: "demo" } } }, + }), + }, + { + schemas: { + Payload: { + anyOf: [ + { type: "object", properties: { name: { type: "string" } } }, + { type: "null" } as unknown as OpenAPI3Schema, + ], + }, + }, + }, + ), + ); + expect(code.match(/@opExample\(/g)).toHaveLength(1); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("invalid")); + expect(responses["200"].content["application/json"].examples).toEqual({ + valid: { summary: "valid", value: { name: "demo" } }, + }); + } finally { + warn.mockRestore(); + } + }); + + it("does not mistake a referenced payload statusCode for the response discriminator", async () => { + const { responses } = await roundTrip( + document( + { + "201": response({ + schema: { $ref: "#/components/schemas/Payload" }, + example: { statusCode: "ordinary", body: "hello" }, + }), + }, + { + schemas: { + Payload: { + type: "object", + properties: { statusCode: { type: "string" }, body: { type: "string" } }, + required: ["statusCode", "body"], + }, + }, + }, + ), + ); + expect(responses["201"].content["application/json"].example).toEqual({ + statusCode: "ordinary", + body: "hello", + }); + }); + + it("diagnoses a media type not represented by a generated component response", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const { code, responses } = await roundTrip( + document( + { "200": { $ref: "#/components/responses/Multiple" } }, + { + responses: { + Multiple: { + description: "Multiple", + content: { + "application/json": { schema: message, example: payload }, + "application/vnd.example+json": { + schema: message, + example: { body: "vendor", id: 2 }, + }, + }, + }, + }, + }, + ), + ); + expect(code.match(/@opExample\(/g)).toHaveLength(1); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("not represented")); + expect(responses["200"].content["application/json"].example).toEqual(payload); + expect(responses["200"].content).not.toHaveProperty("application/vnd.example+json"); + } finally { + warn.mockRestore(); + } + }); + + it.each([ + ["an out-of-range int32", { type: "integer", format: "int32" }, 2 ** 32], + ["an out-of-range int64", { type: "integer", format: "int64" }, 2 ** 63], + ["an out-of-range float", { type: "number", format: "float" }, 3.4e40], + ["an out-of-range safeint", { type: "integer", format: "double-int" }, 2 ** 53], + ["an out-of-range nullable int32", { type: ["integer", "null"], format: "int32" }, 2 ** 32], + [ + "a scalar for an inferred object", + { properties: { name: { type: "string" } } }, + "not an object", + ], + ["an object for an inferred array", { items: { type: "string" } }, { name: "not an array" }], + ["an invalid array item", { type: "array", items: { type: "integer" } }, ["wrong"]], + ["an enum mismatch", { type: "string", enum: ["allowed"] }, "wrong"], + [ + "an unrepresentable extra property", + { type: "object", properties: { name: { type: "string" } } }, + { name: "hello", extra: "unrepresentable" }, + ], + ["a non-JSON number", { type: "number" }, Number.POSITIVE_INFINITY], + ] as const)("diagnoses %s rather than emitting invalid TypeSpec", async (_, schema, value) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const { code } = await roundTrip( + document({ "201": response({ schema: schema as OpenAPI3Schema, example: value }) }), + ); + expect(code).not.toContain("@opExample"); + expect(warn).toHaveBeenCalled(); + } finally { + warn.mockRestore(); + } + }); +}); + +describe("response example shape binding", () => { + const bodyProperty = (name: string, decorator: string): TypeSpecModelProperty => ({ + name, + decorators: [{ name: decorator, args: [] }], + schema: message, + isOptional: false, + }); + const codeProperty: TypeSpecModelProperty = { + name: "code", + decorators: [{ name: "statusCode", args: [] }], + schema: { type: "integer", enum: [201] }, + isOptional: false, + }; + + it("does not produce a leading comma for an empty implicit value", () => { + const value = generateResponseExampleValue( + {}, + { + statusCode: "201", + mediaType: "application/json", + content: {}, + properties: [codeProperty], + implicitBody: { type: "object" }, + }, + [], + createContext(document({})), + ); + expect(value).toBe("#{ code: 201 }"); + }); + + it.each([ + ["Message", [], message], + ["{ @body payload: Message; }", [bodyProperty("payload", "body")], undefined], + ["{ @bodyRoot payload: Message; }", [bodyProperty("payload", "bodyRoot")], undefined], + [ + "{ @statusCode code: 201; @body payload: Message; }", + [codeProperty, bodyProperty("payload", "body")], + undefined, + ], + ["{ @statusCode code: 201; body: string; id: int32; }", [codeProperty], message], + ] as const)("binds the wire payload to %s", async (returnType, properties, implicitBody) => { + const statusCode = properties.some((p) => p === codeProperty) ? "201" : "200"; + const shape: ResponseExampleShape = { + statusCode, + mediaType: "application/json", + content: { schema: message }, + properties: [...properties], + implicitBody, + }; + const value = generateResponseExampleValue(payload, shape, [], createContext(document({}))); + const output = await emit(` + import "@typespec/http"; + using TypeSpec.Http; + @service namespace Test; + model Message { body: string; id: int32; } + @opExample(#{ returnType: ${value} }) + @route("/test") @get op read(): ${returnType}; + `); + expect( + output.paths["/test"].get.responses[statusCode].content["application/json"].example, + ).toEqual(payload); + }); + + it("uses the actual content-type property independently of a status property", async () => { + const format: TypeSpecModelProperty = { + name: "format", + decorators: [{ name: "header", args: ["content-type"] }], + schema: { type: "string", enum: ["application/json", "text/plain"] }, + isOptional: false, + }; + const decorators = ["application/json", "text/plain"].map((mediaType) => { + const value = generateResponseExampleValue( + payload, + { + statusCode: "200", + mediaType, + content: { schema: message }, + properties: [format, bodyProperty("payload", "body")], + }, + [], + createContext(document({})), + ); + return `@opExample(#{ returnType: ${value} })`; + }); + const output = await emit(` + import "@typespec/http"; + using TypeSpec.Http; + @service namespace Test; + model Message { body: string; id: int32; } + ${decorators.join("\n")} + @route("/test") @get op read(): { + @header("content-type") format: "application/json" | "text/plain"; + @body payload: Message; + }; + `); + expect(output.paths["/test"].get.responses["200"].content["application/json"].example).toEqual( + payload, + ); + expect(output.paths["/test"].get.responses["200"].content["text/plain"].example).toEqual( + payload, + ); + }); +});