From e114d28621ac786fdba1f291880cdecc48d85073 Mon Sep 17 00:00:00 2001 From: baywet <7905502+baywet@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:06:25 +0000 Subject: [PATCH 1/8] Initial plan From fbe888824590d8589647c3751dc7d51359550079 Mon Sep 17 00:00:00 2001 From: baywet <7905502+baywet@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:21:47 +0000 Subject: [PATCH 2/8] feat(openapi3): import schema examples arrays as example decorators Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../convert/generators/generate-decorators.ts | 15 +- .../convert/generators/generate-model.ts | 8 +- .../transforms/transform-component-schemas.ts | 22 +-- .../cli/actions/convert/utils/decorators.ts | 14 ++ .../test/tsp-openapi3/examples.test.ts | 182 ++++++++++++++++++ 5 files changed, 221 insertions(+), 20 deletions(-) create mode 100644 packages/openapi3/test/tsp-openapi3/examples.test.ts diff --git a/packages/openapi3/src/cli/actions/convert/generators/generate-decorators.ts b/packages/openapi3/src/cli/actions/convert/generators/generate-decorators.ts index 42d09ff8078..2e0681bcf05 100644 --- a/packages/openapi3/src/cli/actions/convert/generators/generate-decorators.ts +++ b/packages/openapi3/src/cli/actions/convert/generators/generate-decorators.ts @@ -33,10 +33,17 @@ export function generateDecorators( decorators: TypeSpecDecorator[], namesToExclude: string[] = [], ): string[] { - const uniqueDecorators = new Set( - decorators.filter((d) => !namesToExclude.includes(d.name)).map(generateDecorator), - ); - return Array.from(uniqueDecorators); + const seen = new Set(); + return decorators + .filter((d) => !namesToExclude.includes(d.name)) + .flatMap((decorator) => { + const generated = generateDecorator(decorator); + if (decorator.name !== "example" && seen.has(generated)) { + return []; + } + seen.add(generated); + return [generated]; + }); } function isTSValue(value: unknown): value is TSValue { diff --git a/packages/openapi3/src/cli/actions/convert/generators/generate-model.ts b/packages/openapi3/src/cli/actions/convert/generators/generate-model.ts index 96758e74e86..d8a34dada08 100644 --- a/packages/openapi3/src/cli/actions/convert/generators/generate-model.ts +++ b/packages/openapi3/src/cli/actions/convert/generators/generate-model.ts @@ -381,8 +381,14 @@ export function generateModelProperty( // Decorators will be a combination of top-level (parameters) and // schema-level decorators. + const hasExamples = prop.decorators.some((decorator) => decorator.name === "example"); const decorators = generateDecorators( - [...prop.decorators, ...getDecoratorsForSchema(prop.schema)], + [ + ...prop.decorators, + ...getDecoratorsForSchema(prop.schema, context).filter( + (decorator) => decorator.name !== "example" || !hasExamples, + ), + ], isModelReferencedAsMultipartRequestBody ? SchemaToExpressionGenerator.decoratorNamesToExcludeForParts : [], 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..6a4960afd1e 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 @@ -152,7 +152,12 @@ export function transformComponentSchemas(context: Context, models: TypeSpecData // Extract description and decorators from meaningful union members const unionMetadata = extractUnionMetadata(schema); - let decorators = [...getDecoratorsForSchema(schema, context), ...unionMetadata.decorators]; + let decorators = [ + ...getDecoratorsForSchema(schema, context), + ...unionMetadata.decorators.filter( + (decorator) => decorator.name !== "example" || !("examples" in schema), + ), + ]; // Check if this is an SSE event schema - if so, replace @oneOf with @events const schemaRef = `#/components/schemas/${name}`; @@ -176,7 +181,7 @@ export function transformComponentSchemas(context: Context, models: TypeSpecData /** * Extracts meaningful description and decorators from union members. - * Handles anyOf/oneOf with null, and type arrays like ["string", "null"]. + * Handles anyOf/oneOf with null. */ function extractUnionMetadata(schema: SupportedOpenAPISchema): { description?: string; @@ -202,19 +207,6 @@ export function transformComponentSchemas(context: Context, models: TypeSpecData } } - // Handle type array scenarios like type: ["string", "null"] - if (Array.isArray(schema.type)) { - const nonNullTypes = schema.type.filter((t) => t !== "null"); - // If we have exactly one non-null type, this is essentially a nullable version of that type - // The schema itself should contain the relevant constraints/description for the non-null type - if (nonNullTypes.length === 1) { - // Create a schema without the null type to extract decorators for the non-null part - const nonNullSchema = { ...schema, type: nonNullTypes[0] }; - return { decorators: getDecoratorsForSchema(nonNullSchema, context) }; - // The description should already be on the main schema, so we don't override it here - } - } - return { decorators: [] }; } diff --git a/packages/openapi3/src/cli/actions/convert/utils/decorators.ts b/packages/openapi3/src/cli/actions/convert/utils/decorators.ts index 3994c2a9fdc..d607e83d7d3 100644 --- a/packages/openapi3/src/cli/actions/convert/utils/decorators.ts +++ b/packages/openapi3/src/cli/actions/convert/utils/decorators.ts @@ -262,6 +262,20 @@ export function getDecoratorsForSchema( decorators.push(...getExtensions(schemaWithoutRef)); + if ("examples" in schemaWithoutRef) { + if (Array.isArray(schemaWithoutRef.examples)) { + // Decorators are applied in reverse order, so reverse to preserve the examples array order. + for (const example of [...schemaWithoutRef.examples].reverse()) { + decorators.push({ + name: "example", + args: [createTSValue(normalizeObjectValueToTSValueExpression(example))], + }); + } + } else { + context?.logger.warn("Schema examples must be an array. The examples will be ignored."); + } + } + // Handle readOnly and writeOnly properties // These are mutually exclusive - if both are present, emit a warning and ignore both const readOnly = schemaWithoutRef.readOnly; diff --git a/packages/openapi3/test/tsp-openapi3/examples.test.ts b/packages/openapi3/test/tsp-openapi3/examples.test.ts new file mode 100644 index 00000000000..8d2318ddc08 --- /dev/null +++ b/packages/openapi3/test/tsp-openapi3/examples.test.ts @@ -0,0 +1,182 @@ +import { describe, expect, it, vi } from "vitest"; +import { generateDecorators } from "../../src/cli/actions/convert/generators/generate-decorators.js"; +import { createContext } from "../../src/cli/actions/convert/utils/context.js"; +import { getDecoratorsForSchema } from "../../src/cli/actions/convert/utils/decorators.js"; +import { convertOpenAPI3Document } from "../../src/index.js"; +import type { OpenAPIDocument3_2, OpenAPISchema3_2 } from "../../src/types.js"; +import { ApiTester } from "../test-host.js"; + +async function emitOpenAPI(code: string) { + const { outputs } = await ApiTester.emit("@typespec/openapi3").compile(code, { + compilerOptions: { + options: { + "@typespec/openapi3": { + "openapi-versions": ["3.2.0"], + "output-file": "openapi.json", + }, + }, + }, + }); + return JSON.parse(outputs["openapi.json"]); +} + +function documentFor(schema: OpenAPISchema3_2): OpenAPIDocument3_2 { + return { + openapi: "3.2.0", + info: { title: "Pets", version: "1" }, + paths: {}, + components: { schemas: { Pet: schema } }, + }; +} + +describe("import schema examples", () => { + it("creates example decorators in reverse order without mutating the input", () => { + const schema: OpenAPISchema3_2 = { + type: "object", + examples: [{ name: "Fluffy" }, { name: "Spot" }, { name: "Mochi" }], + }; + expect(generateDecorators(getDecoratorsForSchema(schema))).toEqual([ + '@example(#{name: "Mochi"})', + '@example(#{name: "Spot"})', + '@example(#{name: "Fluffy"})', + ]); + expect(schema.examples).toEqual([{ name: "Fluffy" }, { name: "Spot" }, { name: "Mochi" }]); + }); + + it("preserves duplicate examples", () => { + expect( + generateDecorators(getDecoratorsForSchema({ type: "string", examples: ["pet", "pet"] })), + ).toEqual(['@example("pet")', '@example("pet")']); + }); + + it("serializes JSON values using TypeSpec value syntax", () => { + expect( + generateDecorators( + getDecoratorsForSchema({ + examples: [null, false, 0, "a${b}", [], {}, { "pet-name": [1, null, true] }], + }), + ), + ).toEqual([ + "@example(#{`pet-name`: #[1, null, true]})", + "@example(#{})", + "@example(#[])", + '@example("a\\${b}")', + "@example(0)", + "@example(false)", + "@example(null)", + ]); + }); + + const ignoredSchemas = [ + { name: "absent", schema: { type: "string" }, warns: false }, + { name: "empty", schema: { type: "string", examples: [] }, warns: false }, + { name: "invalid", schema: { type: "string", examples: "pet" }, warns: true }, + { name: "null", schema: { type: "string", examples: null }, warns: true }, + { name: "singular", schema: { type: "string", example: "pet" }, warns: false }, + ] as const; + + it.each(ignoredSchemas)("ignores $name examples", ({ schema, warns }) => { + const warn = vi.fn(); + const context = createContext(documentFor({}), { trace: vi.fn(), warn, error: vi.fn() }); + expect(getDecoratorsForSchema(schema as OpenAPISchema3_2, context)).toEqual([]); + if (warns) { + expect(warn).toHaveBeenCalledWith( + "Schema examples must be an array. The examples will be ignored.", + ); + } else { + expect(warn).not.toHaveBeenCalled(); + } + }); + + it.each(ignoredSchemas)( + "converts and compiles schemas with $name examples without decorators", + async ({ schema, warns }) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const code = await convertOpenAPI3Document(documentFor(schema as OpenAPISchema3_2)); + expect(code).not.toContain("@example"); + const output = await emitOpenAPI(code); + expect(output.components.schemas.Pet).not.toHaveProperty("examples"); + expect(output.components.schemas.Pet).not.toHaveProperty("example"); + expect(warn).toHaveBeenCalledTimes(warns ? 1 : 0); + } finally { + warn.mockRestore(); + } + }, + ); + + it.each([ + { examples: [{ name: "Fluffy" }] }, + { examples: [{ name: "Fluffy" }, { name: "Spot" }, { name: "Mochi" }] }, + { examples: [{ name: "Fluffy" }, { name: "Fluffy" }] }, + ])("round-trips model examples $examples in their original order", async ({ examples }) => { + const code = await convertOpenAPI3Document( + documentFor({ + type: "object", + required: ["name"], + properties: { name: { type: "string" } }, + examples, + }), + ); + const output = await emitOpenAPI(code); + expect(output.components.schemas.Pet.examples).toEqual(examples); + expect(output.components.schemas.Pet).not.toHaveProperty("example"); + }); + + it("round-trips examples on properties and scalar, array, and union schemas", async () => { + const schemas: Record = { + PetName: { type: "string", examples: ["Fluffy", "Spot"] }, + PetNames: { type: "array", items: { type: "string" }, examples: [[], ["Fluffy"]] }, + MaybePet: { type: ["string", "null"], examples: [null, "Fluffy"] }, + Pet: { + type: "object", + properties: { name: { type: "string", examples: ["Fluffy", "Spot", "Fluffy"] } }, + }, + }; + const input = documentFor({}); + input.components = { schemas }; + const code = await convertOpenAPI3Document(input); + const output = await emitOpenAPI(code); + for (const name of ["PetName", "PetNames", "MaybePet"]) { + expect(output.components.schemas[name].examples).toEqual(schemas[name].examples); + } + expect(output.components.schemas.Pet.properties.name.examples).toEqual([ + "Fluffy", + "Spot", + "Fluffy", + ]); + }); + + it("preserves outer examples without merging nullable union member examples", async () => { + const examples = [null, "Fluffy"]; + const code = await convertOpenAPI3Document( + documentFor({ + anyOf: [{ type: "string", examples: ["Spot"] }, { type: "null" }], + examples, + }), + ); + const output = await emitOpenAPI(code); + expect(output.components.schemas.Pet.examples).toEqual(examples); + }); + + it("warns about invalid examples on a model property", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const code = await convertOpenAPI3Document( + documentFor({ + type: "object", + properties: { + name: { type: "string", examples: "invalid" } as unknown as OpenAPISchema3_2, + }, + }), + ); + expect(code).not.toContain("@example"); + await emitOpenAPI(code); + expect(warn).toHaveBeenCalledWith( + "Schema examples must be an array. The examples will be ignored.", + ); + } finally { + warn.mockRestore(); + } + }); +}); From 6c40236ca906024d42c468a36c80ae68a4ee19c2 Mon Sep 17 00:00:00 2001 From: baywet <7905502+baywet@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:23:12 +0000 Subject: [PATCH 3/8] docs(openapi3): add schema examples import changelog Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- ...openapi3-import-examples-2026-10-20-15-22-0.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .chronus/changes/copilot-tsp-openapi3-import-examples-2026-10-20-15-22-0.md diff --git a/.chronus/changes/copilot-tsp-openapi3-import-examples-2026-10-20-15-22-0.md b/.chronus/changes/copilot-tsp-openapi3-import-examples-2026-10-20-15-22-0.md new file mode 100644 index 00000000000..fa070061cea --- /dev/null +++ b/.chronus/changes/copilot-tsp-openapi3-import-examples-2026-10-20-15-22-0.md @@ -0,0 +1,15 @@ +--- +changeKind: feature +packages: + - "@typespec/openapi3" +--- + +[converter] Import schema-level `examples` arrays as `@example` decorators, preserving values and order when round-tripping OpenAPI 3.1 and 3.2. Invalid non-array examples are ignored with a warning. + +```tsp +@example(#{ name: "Spot" }) +@example(#{ name: "Fluffy" }) +model Pet { + name: string; +} +``` \ No newline at end of file From 69124c0de492f86ac62d206ce8d709dabf36bdaa Mon Sep 17 00:00:00 2001 From: baywet <7905502+baywet@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:04:50 +0000 Subject: [PATCH 4/8] chore: allow Mochi in spellcheck Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- cspell.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/cspell.yaml b/cspell.yaml index d795d3527ab..1c72297bd31 100644 --- a/cspell.yaml +++ b/cspell.yaml @@ -172,6 +172,7 @@ words: - mgmt - mgmtplane - mocharc + - Mochi - mqtt - mros - msbuild From 0a86e9f9a75bdf209414ea7cd79a6f1685ef99e9 Mon Sep 17 00:00:00 2001 From: baywet <7905502+baywet@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:43:53 +0000 Subject: [PATCH 5/8] fix(openapi3): preserve schema examples in body conversion Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../src/cli/actions/convert/convert.ts | 101 +++++++++- .../transforms/transform-component-schemas.ts | 15 +- .../cli/actions/convert/utils/decorators.ts | 179 ++++++++++++++++-- .../test/tsp-openapi3/examples.test.ts | 173 +++++++++++++++++ 4 files changed, 450 insertions(+), 18 deletions(-) diff --git a/packages/openapi3/src/cli/actions/convert/convert.ts b/packages/openapi3/src/cli/actions/convert/convert.ts index fd2555fef6b..53e72be18e4 100644 --- a/packages/openapi3/src/cli/actions/convert/convert.ts +++ b/packages/openapi3/src/cli/actions/convert/convert.ts @@ -31,6 +31,7 @@ export async function convertOpenAPI3Document( document: SupportedOpenAPIDocuments, { disableExternalRefs, namespace }: ConvertOpenAPI3DocumentOptions = {}, ) { + const conversionDocument = hoistInlineBodyExampleSchemas(document); const dereferenceOptions = disableExternalRefs ? { onDereference: (data: { schema: AnyObject; ref: string }): void => { @@ -41,11 +42,14 @@ export async function convertOpenAPI3Document( }, } : {}; - const { specification } = await dereference(document as unknown as AnyObject, dereferenceOptions); + const { specification } = await dereference( + conversionDocument as unknown as AnyObject, + dereferenceOptions, + ); if (!specification) { throw new Error("Failed to dereference OpenAPI document"); } - const context = createContext(document, console, namespace); + const context = createContext(conversionDocument, console, namespace); const program = transform(context); const content = generateMain(program, context); try { @@ -57,3 +61,96 @@ export async function convertOpenAPI3Document( return content; } } + +function hoistInlineBodyExampleSchemas( + document: SupportedOpenAPIDocuments, +): SupportedOpenAPIDocuments { + const converted = structuredClone(document) as SupportedOpenAPIDocuments; + const mutableDocument = converted as any; + const components = (mutableDocument.components ??= {}); + const schemas = (components.schemas ??= {}); + let nextSchemaIndex = 0; + + function hoistContentSchemas(content: Record | undefined): void { + for (const mediaType of Object.values(content ?? {})) { + const schema = mediaType?.schema; + if ( + !schema || + typeof schema !== "object" || + "$ref" in schema || + !("examples" in schema) || + (Array.isArray(schema.examples) && schema.examples.length === 0) + ) { + continue; + } + + let name: string; + do { + name = `__OpenAPIExampleBody${nextSchemaIndex++}`; + } while (name in schemas); + + schemas[name] = schema; + mediaType.schema = { $ref: `#/components/schemas/${name}` }; + } + } + + function hoistRequestBody(requestBody: any): void { + if (requestBody && typeof requestBody === "object" && !("$ref" in requestBody)) { + hoistContentSchemas(requestBody.content); + } + } + + function hoistResponses(responses: any): void { + if (!responses || typeof responses !== "object" || "$ref" in responses) { + return; + } + + for (const response of Object.values(responses)) { + if (response && typeof response === "object" && !("$ref" in response)) { + hoistContentSchemas((response as any).content); + } + } + } + + for (const requestBody of Object.values(components.requestBodies ?? {})) { + hoistRequestBody(requestBody); + } + for (const response of Object.values(components.responses ?? {})) { + if (response && typeof response === "object" && !("$ref" in response)) { + hoistContentSchemas((response as any).content); + } + } + + function hoistOperation(operation: any): void { + if (!operation || typeof operation !== "object") { + return; + } + + if ("requestBody" in operation || "responses" in operation) { + hoistRequestBody(operation.requestBody); + hoistResponses(operation.responses); + } + } + + function visitPathItem(pathItem: any): void { + if (!pathItem || typeof pathItem !== "object") { + return; + } + + hoistOperation(pathItem.query); + for (const operation of Object.values(pathItem.additionalOperations ?? {})) { + hoistOperation(operation); + } + for (const [key, operation] of Object.entries(pathItem)) { + if (key !== "query" && key !== "additionalOperations") { + hoistOperation(operation); + } + } + } + + for (const pathItem of Object.values(mutableDocument.paths ?? {})) { + visitPathItem(pathItem); + } + + return converted; +} 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 6a4960afd1e..5214850a31f 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 @@ -79,7 +79,11 @@ export function transformComponentSchemas(context: Context, models: TypeSpecData kind: "enum", ...getScopeAndName(name), directives: getDirectivesForSchema(schema), - decorators: getDecoratorsForSchema(schema, context), + decorators: getDecoratorsForSchema( + schema, + context, + context.getRefName(`#/components/schemas/${name}`, [context.rootNamespace]), + ), doc: schema.description, schema, }; @@ -219,7 +223,11 @@ export function transformComponentSchemas(context: Context, models: TypeSpecData kind: "scalar", ...getScopeAndName(name), directives: getDirectivesForSchema(schema), - decorators: getDecoratorsForSchema(schema, context), + decorators: getDecoratorsForSchema( + schema, + context, + context.getRefName(`#/components/schemas/${name}`, [context.rootNamespace]), + ), doc: schema.description, schema: "$ref" in schema ? {} : schema, }); @@ -332,6 +340,9 @@ function unwrapSingleAnyOfOneOf( ...(schema as object), ...member, description: member.description || schema.description, + ...("examples" in schema && schema.examples !== undefined + ? { examples: schema.examples } + : {}), anyOf: undefined, oneOf: undefined, }; diff --git a/packages/openapi3/src/cli/actions/convert/utils/decorators.ts b/packages/openapi3/src/cli/actions/convert/utils/decorators.ts index d607e83d7d3..cc0e83f6664 100644 --- a/packages/openapi3/src/cli/actions/convert/utils/decorators.ts +++ b/packages/openapi3/src/cli/actions/convert/utils/decorators.ts @@ -240,6 +240,7 @@ function getHeaderArgs(explode: boolean): TSValue | undefined { export function getDecoratorsForSchema( schema: Refable, context?: Context, + exampleTargetType?: string, ): TypeSpecDecorator[] { const decorators: TypeSpecDecorator[] = []; @@ -261,20 +262,7 @@ export function getDecoratorsForSchema( const schemaWithoutRef = schema as OpenAPI3Schema | OpenAPISchema3_1 | OpenAPISchema3_2; decorators.push(...getExtensions(schemaWithoutRef)); - - if ("examples" in schemaWithoutRef) { - if (Array.isArray(schemaWithoutRef.examples)) { - // Decorators are applied in reverse order, so reverse to preserve the examples array order. - for (const example of [...schemaWithoutRef.examples].reverse()) { - decorators.push({ - name: "example", - args: [createTSValue(normalizeObjectValueToTSValueExpression(example))], - }); - } - } else { - context?.logger.warn("Schema examples must be an array. The examples will be ignored."); - } - } + decorators.push(...getExampleDecoratorsForSchema(schema, context, exampleTargetType)); // Handle readOnly and writeOnly properties // These are mutually exclusive - if both are present, emit a warning and ignore both @@ -435,6 +423,169 @@ export function getDecoratorsForSchema( return decorators; } +export function getExampleDecoratorsForSchema( + schema: Refable, + context?: Context, + exampleTargetType?: string, +): TypeSpecDecorator[] { + const schemaWithoutRef = schema as OpenAPI3Schema | OpenAPISchema3_1 | OpenAPISchema3_2; + if (!("examples" in schemaWithoutRef)) { + return []; + } + + if (!Array.isArray(schemaWithoutRef.examples)) { + context?.logger.warn("Schema examples must be an array. The examples will be ignored."); + return []; + } + + // Decorators are applied in reverse order, so reverse to preserve the examples array order. + return [...schemaWithoutRef.examples].reverse().map((example) => ({ + name: "example", + args: [createTSValue(getExampleValueExpression(example, schema, context, exampleTargetType))], + })); +} + +function getExampleValueExpression( + value: unknown, + schema: Refable, + context?: Context, + exampleTargetType?: string, +): string { + if (value === null) return "null"; + + const isRef = "$ref" in schema; + const referencedSchema = isRef ? context?.getSchemaByRef(schema.$ref) : undefined; + const effectiveSchema = referencedSchema + ? ({ ...referencedSchema, ...schema } as OpenAPI3Schema | OpenAPISchema3_1 | OpenAPISchema3_2) + : (schema as OpenAPI3Schema | OpenAPISchema3_1 | OpenAPISchema3_2); + const typeName = isRef + ? context?.getRefName(schema.$ref, [context.rootNamespace]) + : exampleTargetType; + + if ( + typeName && + effectiveSchema.type === "string" && + effectiveSchema.enum?.includes(value as string) + ) { + return `${typeName}.${printIdentifier(String(value), "disallow-reserved")}`; + } + + if ( + typeof value === "string" && + effectiveSchema.type === "string" && + effectiveSchema.format === "date-time" + ) { + return `${typeName ?? "utcDateTime"}.fromISO(${stringLiteralForExample(value)})`; + } + + const unionMembers = effectiveSchema.anyOf ?? effectiveSchema.oneOf; + if (unionMembers) { + const matchingMember = unionMembers.find((member) => + isExampleValueCompatible(value, member, context), + ); + if (matchingMember) { + return getExampleValueExpression(value, matchingMember, context); + } + } + + if (Array.isArray(value)) { + const itemSchema = effectiveSchema.items; + return `#[${value + .map((item) => getExampleValueExpression(item, itemSchema ?? {}, context)) + .join(", ")}]`; + } + + if (typeof value === "object") { + const properties = effectiveSchema.properties ?? {}; + return `#{${Object.entries(value) + .map(([key, propertyValue]) => { + const propertySchema = + properties[key] ?? + (typeof effectiveSchema.additionalProperties === "object" + ? effectiveSchema.additionalProperties + : {}); + return `${printIdentifier(key, "disallow-reserved")}: ${getExampleValueExpression( + propertyValue, + propertySchema, + context, + )}`; + }) + .join(", ")}}`; + } + + return typeof value === "string" ? stringLiteralForExample(value) : JSON.stringify(value); +} + +function isExampleValueCompatible( + value: unknown, + schema: Refable, + context?: Context, +): boolean { + if (value === null) { + return "$ref" in schema + ? isExampleValueCompatible(value, context?.getSchemaByRef(schema.$ref) ?? {}, context) + : (schema as OpenAPI3Schema | OpenAPISchema3_1 | OpenAPISchema3_2).type === "null" || + ("type" in schema && Array.isArray(schema.type) && schema.type.includes("null")); + } + + if ("$ref" in schema) { + const referencedSchema = context?.getSchemaByRef(schema.$ref); + return referencedSchema ? isExampleValueCompatible(value, referencedSchema, context) : true; + } + + if (schema.const !== undefined && schema.const !== value) return false; + if (schema.enum && !schema.enum.includes(value as never)) return false; + + const unionMembers = schema.anyOf ?? schema.oneOf; + if (unionMembers) { + return unionMembers.some((member) => isExampleValueCompatible(value, member, context)); + } + + if (Array.isArray(schema.type)) { + return schema.type.some((type) => + isExampleValueCompatible(value, { ...schema, type } as OpenAPI3Schema, context), + ); + } + + switch (schema.type) { + case "array": + return ( + Array.isArray(value) && + (!schema.items || + value.every((item) => isExampleValueCompatible(item, schema.items!, context))) + ); + case "object": + return ( + typeof value === "object" && + !Array.isArray(value) && + Object.entries(value).every(([key, propertyValue]) => { + const propertySchema = + schema.properties?.[key] ?? + (typeof schema.additionalProperties === "object" + ? schema.additionalProperties + : undefined); + return ( + !propertySchema || isExampleValueCompatible(propertyValue, propertySchema, context) + ); + }) + ); + case "string": + return typeof value === "string"; + case "boolean": + return typeof value === "boolean"; + case "integer": + return typeof value === "number" && Number.isInteger(value); + case "number": + return typeof value === "number"; + default: + return true; + } +} + +function stringLiteralForExample(value: string): string { + return JSON.stringify(value).replaceAll("${", "\\${"); +} + export function getDirectivesForSchema( schema: Refable, ): TypeSpecDirective[] { diff --git a/packages/openapi3/test/tsp-openapi3/examples.test.ts b/packages/openapi3/test/tsp-openapi3/examples.test.ts index 8d2318ddc08..d80819300c5 100644 --- a/packages/openapi3/test/tsp-openapi3/examples.test.ts +++ b/packages/openapi3/test/tsp-openapi3/examples.test.ts @@ -29,6 +29,14 @@ function documentFor(schema: OpenAPISchema3_2): OpenAPIDocument3_2 { }; } +function examplesForSchema(schema: any, document: any) { + if ("$ref" in schema) { + const name = schema.$ref.split("/").at(-1); + return document.components.schemas[name].examples; + } + return schema.examples; +} + describe("import schema examples", () => { it("creates example decorators in reverse order without mutating the input", () => { const schema: OpenAPISchema3_2 = { @@ -147,6 +155,171 @@ describe("import schema examples", () => { ]); }); + it("uses scalar constructors and enum members in schema examples", async () => { + const schemas: Record = { + Color: { type: "string", enum: ["red", "blue"], examples: ["blue"] }, + Timestamp: { + type: "string", + format: "date-time", + examples: ["2026-11-20T16:00:00Z"], + }, + Pet: { + type: "object", + properties: { + color: { $ref: "#/components/schemas/Color" }, + timestamps: { + type: "array", + items: { $ref: "#/components/schemas/Timestamp" }, + }, + }, + examples: [ + { + color: "red", + timestamps: ["2026-11-20T16:00:00Z"], + }, + ], + }, + }; + const input = documentFor({}); + input.components = { schemas }; + + const code = await convertOpenAPI3Document(input); + expect(code).toContain("Pets.Color.red"); + expect(code).toContain('Pets.Timestamp.fromISO("2026-11-20T16:00:00Z")'); + const output = await emitOpenAPI(code); + expect(output.components.schemas.Pet.examples).toEqual(schemas.Pet.examples); + expect(output.components.schemas.Color.examples).toEqual(schemas.Color.examples); + expect(output.components.schemas.Timestamp.examples).toEqual(schemas.Timestamp.examples); + }); + + it("preserves parent examples when unwrapping an inline object union member", async () => { + const examples = [{ name: "parent" }]; + const code = await convertOpenAPI3Document( + documentFor({ + anyOf: [ + { + type: "object", + properties: { name: { type: "string" } }, + examples: [{ name: "member" }], + }, + { type: "null" }, + ], + examples, + }), + ); + const output = await emitOpenAPI(code); + expect(output.components.schemas.Pet.examples).toEqual(examples); + }); + + it("round-trips examples on inline request and response body schemas", async () => { + const input = documentFor({}); + input.paths = { + "/pets": { + post: { + operationId: "createPet", + requestBody: { + required: true, + content: { + "application/json": { + schema: { + type: "object", + properties: { name: { type: "string" } }, + examples: [{ name: "request example" }], + }, + }, + }, + }, + responses: { + "200": { + description: "Created", + content: { + "application/json": { + schema: { + type: "object", + properties: { name: { type: "string" } }, + examples: [{ name: "response example" }], + }, + }, + }, + }, + }, + }, + }, + } as OpenAPIDocument3_2["paths"]; + + const code = await convertOpenAPI3Document(input); + const output = await emitOpenAPI(code); + expect( + (input.paths as any)["/pets"].post.requestBody.content["application/json"].schema.examples, + ).toEqual([{ name: "request example" }]); + expect( + examplesForSchema( + output.paths["/pets"].post.requestBody.content["application/json"].schema, + output, + ), + ).toEqual([{ name: "request example" }]); + expect( + examplesForSchema( + output.paths["/pets"].post.responses["200"].content["application/json"].schema, + output, + ), + ).toEqual([{ name: "response example" }]); + }); + + it("round-trips examples on inline string request and response bodies", async () => { + const input = documentFor({}); + input.paths = { + "/pets": { + post: { + operationId: "createPet", + requestBody: { + required: true, + content: { + "application/json": { + schema: { type: "string", examples: ["request example"] }, + }, + }, + }, + responses: { + "200": { + description: "Created", + content: { + "application/json": { + schema: { type: "string", examples: ["response example"] }, + }, + }, + }, + }, + }, + }, + } as OpenAPIDocument3_2["paths"]; + + const code = await convertOpenAPI3Document(input); + const output = await emitOpenAPI(code); + const requestContent = output.paths["/pets"].post.requestBody.content as Record; + const responseContent = output.paths["/pets"].post.responses["200"].content as Record< + string, + any + >; + const requestSchema = Object.values(requestContent)[0].schema; + const responseSchema = Object.values(responseContent)[0].schema; + expect(examplesForSchema(requestSchema, output)).toEqual(["request example"]); + expect(examplesForSchema(responseSchema, output)).toEqual(["response example"]); + }); + + it("preserves backslashes in nested schema examples", async () => { + const examples = [{ path: "C:\\temp" }]; + const code = await convertOpenAPI3Document( + documentFor({ + type: "object", + properties: { path: { type: "string" } }, + examples, + }), + ); + const output = await emitOpenAPI(code); + expect(output.components.schemas.Pet.examples).toEqual(examples); + }); + it("preserves outer examples without merging nullable union member examples", async () => { const examples = [null, "Fluffy"]; const code = await convertOpenAPI3Document( From c58f9045097e618a4b9cca6e8eed92e3e358ae7b Mon Sep 17 00:00:00 2001 From: baywet <7905502+baywet@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:22:13 +0000 Subject: [PATCH 6/8] fix(openapi3): preserve schema examples across literals and unions Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../src/cli/actions/convert/convert.ts | 4 +- .../cli/actions/convert/generators/common.ts | 25 ++++++ .../generate-response-expressions.ts | 8 +- .../convert/generators/generate-types.ts | 36 +-------- .../cli/actions/convert/utils/decorators.ts | 70 +++++++++++++--- .../test/tsp-openapi3/examples.test.ts | 81 +++++++++++++++++-- 6 files changed, 169 insertions(+), 55 deletions(-) diff --git a/packages/openapi3/src/cli/actions/convert/convert.ts b/packages/openapi3/src/cli/actions/convert/convert.ts index 53e72be18e4..302877e44cb 100644 --- a/packages/openapi3/src/cli/actions/convert/convert.ts +++ b/packages/openapi3/src/cli/actions/convert/convert.ts @@ -89,7 +89,9 @@ function hoistInlineBodyExampleSchemas( name = `__OpenAPIExampleBody${nextSchemaIndex++}`; } while (name in schemas); - schemas[name] = schema; + // A literal cannot be the base of a scalar, but can be a named union variant. + schemas[name] = + schema.const === undefined ? schema : { ...schema, anyOf: [{ const: schema.const }] }; mediaType.schema = { $ref: `#/components/schemas/${name}` }; } } diff --git a/packages/openapi3/src/cli/actions/convert/generators/common.ts b/packages/openapi3/src/cli/actions/convert/generators/common.ts index d0a0a2cbd6e..a8481464716 100644 --- a/packages/openapi3/src/cli/actions/convert/generators/common.ts +++ b/packages/openapi3/src/cli/actions/convert/generators/common.ts @@ -16,3 +16,28 @@ export function stringLiteral(value: string): string { // Avoid double-escaping backslashes in the process return `"${value.replaceAll(/(?:([^\\])"|^")/gi, '$1\\"').replaceAll(/(?:([^\\])\$\{|^\$\{)/gi, "$1\\${")}"`; } +import type { SupportedOpenAPISchema } from "../../../../types.js"; + +export function getStringType(schema: SupportedOpenAPISchema): string { + if ("contentEncoding" in schema && schema.contentEncoding === "base64") { + return "bytes"; + } + + switch (schema.format) { + case "binary": + case "byte": + return "bytes"; + case "date": + return "plainDate"; + case "date-time": + return "utcDateTime"; + case "time": + return "plainTime"; + case "duration": + return "duration"; + case "uri": + return "url"; + default: + return "string"; + } +} 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..e1022a4e84e 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 @@ -246,10 +246,14 @@ 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; + const referencedBody = + bodySchema && "$ref" in bodySchema ? context.getSchemaByRef(bodySchema.$ref) : undefined; + // Keep a hoisted literal union as the body; HTTP otherwise treats its variants as responses. + const isLiteralBody = referencedBody?.const !== undefined; if (bodySchema && mediaType === "application/json" && !headers.length) { // 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) { + if ("$ref" in bodySchema && statusCodeMetadata.httpLibModel && !isLiteralBody) { return `${statusCodeMetadata.httpLibModel} & ${context.generateTypeFromRefableSchema( bodySchema, operationScope, @@ -260,7 +264,7 @@ function generateResponseExpressions({ // Example: Body if (statusCodeMetadata.literalStatusCode === 200) { const body = context.generateTypeFromRefableSchema(bodySchema, operationScope); - if ("$ref" in bodySchema) { + if ("$ref" in bodySchema && !isLiteralBody) { return body; } return `Body<${body}>`; diff --git a/packages/openapi3/src/cli/actions/convert/generators/generate-types.ts b/packages/openapi3/src/cli/actions/convert/generators/generate-types.ts index 85f5a22209b..16cae22ae20 100644 --- a/packages/openapi3/src/cli/actions/convert/generators/generate-types.ts +++ b/packages/openapi3/src/cli/actions/convert/generators/generate-types.ts @@ -11,6 +11,7 @@ import { normalizeObjectValueToTSValueExpression, } from "../utils/decorators.js"; import { getScopeAndName } from "../utils/get-scope-and-name.js"; +import { getStringType } from "./common.js"; import { generateDecorators } from "./generate-decorators.js"; export class SchemaToExpressionGenerator { @@ -643,41 +644,6 @@ function getNumberType(schema: SupportedOpenAPISchema): string { } } -function getStringType(schema: SupportedOpenAPISchema): string { - const format = schema.format ?? ""; - - // Handle contentEncoding: base64 for OpenAPI 3.1+ (indicates binary data encoded as base64 string) - if ("contentEncoding" in schema && schema.contentEncoding === "base64") { - return "bytes"; - } - - let type = "string"; - switch (format) { - case "binary": - case "byte": - type = "bytes"; - break; - case "date": - type = "plainDate"; - break; - case "date-time": - // Can be 'offsetDateTime' or 'utcDateTime' - needs FIXME or union? - type = "utcDateTime"; - break; - case "time": - type = "plainTime"; - break; - case "duration": - type = "duration"; - break; - case "uri": - type = "url"; - break; - } - - return type; -} - function getEnum(schemaEnum: (string | number | boolean | null)[]): string { return schemaEnum.map((e) => JSON.stringify(e)).join(" | "); } diff --git a/packages/openapi3/src/cli/actions/convert/utils/decorators.ts b/packages/openapi3/src/cli/actions/convert/utils/decorators.ts index cc0e83f6664..65b5a4bc5ef 100644 --- a/packages/openapi3/src/cli/actions/convert/utils/decorators.ts +++ b/packages/openapi3/src/cli/actions/convert/utils/decorators.ts @@ -8,8 +8,9 @@ import type { OpenAPISchema3_1, OpenAPISchema3_2, Refable, + SupportedOpenAPISchema, } from "../../../../types.js"; -import { stringLiteral } from "../generators/common.js"; +import { getStringType, stringLiteral } from "../generators/common.js"; import type { TSValue, TypeSpecDecorator, TypeSpecDirective } from "../interfaces.js"; import type { Context } from "./context.js"; @@ -461,23 +462,19 @@ function getExampleValueExpression( const typeName = isRef ? context?.getRefName(schema.$ref, [context.rootNamespace]) : exampleTargetType; + const nullable = + Array.isArray(effectiveSchema.type) || + ("nullable" in effectiveSchema && effectiveSchema.nullable); if ( typeName && + !nullable && effectiveSchema.type === "string" && effectiveSchema.enum?.includes(value as string) ) { return `${typeName}.${printIdentifier(String(value), "disallow-reserved")}`; } - if ( - typeof value === "string" && - effectiveSchema.type === "string" && - effectiveSchema.format === "date-time" - ) { - return `${typeName ?? "utcDateTime"}.fromISO(${stringLiteralForExample(value)})`; - } - const unionMembers = effectiveSchema.anyOf ?? effectiveSchema.oneOf; if (unionMembers) { const matchingMember = unionMembers.find((member) => @@ -488,6 +485,23 @@ function getExampleValueExpression( } } + if ( + typeof value === "string" && + effectiveSchema.const === undefined && + !effectiveSchema.enum && + (effectiveSchema.type === "string" || + (Array.isArray(effectiveSchema.type) && effectiveSchema.type.includes("string"))) + ) { + const scalar = getStringType(effectiveSchema); + switch (scalar) { + case "utcDateTime": + case "plainDate": + case "plainTime": + case "duration": + return `${(!nullable && typeName) || scalar}.fromISO(${stringLiteralForExample(value)})`; + } + } + if (Array.isArray(value)) { const itemSchema = effectiveSchema.items; return `#[${value @@ -496,11 +510,10 @@ function getExampleValueExpression( } if (typeof value === "object") { - const properties = effectiveSchema.properties ?? {}; return `#{${Object.entries(value) .map(([key, propertyValue]) => { const propertySchema = - properties[key] ?? + findExamplePropertySchema(effectiveSchema, key, context) ?? (typeof effectiveSchema.additionalProperties === "object" ? effectiveSchema.additionalProperties : {}); @@ -516,6 +529,30 @@ function getExampleValueExpression( return typeof value === "string" ? stringLiteralForExample(value) : JSON.stringify(value); } +function findExamplePropertySchema( + schema: Refable, + key: string, + context?: Context, + visited = new Set>(), +): Refable | undefined { + if (visited.has(schema)) return undefined; + visited.add(schema); + + if ("$ref" in schema) { + const target = context?.getSchemaByRef(schema.$ref); + return target && findExamplePropertySchema(target, key, context, visited); + } + + if (schema.properties && Object.hasOwn(schema.properties, key)) { + return schema.properties[key]; + } + for (const member of schema.allOf ?? []) { + const property = findExamplePropertySchema(member, key, context, visited); + if (property) return property; + } + return undefined; +} + function isExampleValueCompatible( value: unknown, schema: Refable, @@ -548,6 +585,8 @@ function isExampleValueCompatible( } switch (schema.type) { + case "null": + return false; case "array": return ( Array.isArray(value) && @@ -558,6 +597,7 @@ function isExampleValueCompatible( return ( typeof value === "object" && !Array.isArray(value) && + (schema.required ?? []).every((key) => Object.hasOwn(value, key)) && Object.entries(value).every(([key, propertyValue]) => { const propertySchema = schema.properties?.[key] ?? @@ -583,7 +623,13 @@ function isExampleValueCompatible( } function stringLiteralForExample(value: string): string { - return JSON.stringify(value).replaceAll("${", "\\${"); + return `"${value + .replaceAll("\\", "\\\\") + .replaceAll('"', '\\"') + .replaceAll("${", "\\${") + .replaceAll("\r", "\\r") + .replaceAll("\n", "\\n") + .replaceAll("\t", "\\t")}"`; } export function getDirectivesForSchema( diff --git a/packages/openapi3/test/tsp-openapi3/examples.test.ts b/packages/openapi3/test/tsp-openapi3/examples.test.ts index d80819300c5..d6f8c252580 100644 --- a/packages/openapi3/test/tsp-openapi3/examples.test.ts +++ b/packages/openapi3/test/tsp-openapi3/examples.test.ts @@ -266,7 +266,7 @@ describe("import schema examples", () => { ).toEqual([{ name: "response example" }]); }); - it("round-trips examples on inline string request and response bodies", async () => { + it.each([false, true])("round-trips inline string bodies (const: %s)", async (isConst) => { const input = documentFor({}); input.paths = { "/pets": { @@ -276,7 +276,11 @@ describe("import schema examples", () => { required: true, content: { "application/json": { - schema: { type: "string", examples: ["request example"] }, + schema: { + type: "string", + ...(isConst && { const: "request example" }), + examples: ["request example"], + }, }, }, }, @@ -285,7 +289,11 @@ describe("import schema examples", () => { description: "Created", content: { "application/json": { - schema: { type: "string", examples: ["response example"] }, + schema: { + type: "string", + ...(isConst && { const: "response example" }), + examples: ["response example"], + }, }, }, }, @@ -295,6 +303,10 @@ describe("import schema examples", () => { } as OpenAPIDocument3_2["paths"]; const code = await convertOpenAPI3Document(input); + if (isConst) { + expect(code).toMatch(/union \w+ \{\s*"request example",?\s*\}/); + expect(code).toMatch(/union \w+ \{\s*"response example",?\s*\}/); + } const output = await emitOpenAPI(code); const requestContent = output.paths["/pets"].post.requestBody.content as Record; const responseContent = output.paths["/pets"].post.responses["200"].content as Record< @@ -307,8 +319,8 @@ describe("import schema examples", () => { expect(examplesForSchema(responseSchema, output)).toEqual(["response example"]); }); - it("preserves backslashes in nested schema examples", async () => { - const examples = [{ path: "C:\\temp" }]; + it("preserves backslashes, interpolation syntax, and control characters in nested examples", async () => { + const examples = [{ path: 'C:\\temp\\${name}"\r\n\t\b\f\u0000\u001f' }]; const code = await convertOpenAPI3Document( documentFor({ type: "object", @@ -320,6 +332,65 @@ describe("import schema examples", () => { expect(output.components.schemas.Pet.examples).toEqual(examples); }); + it.each([ + ["date-time", "utcDateTime", "2026-11-20T16:00:00Z"], + ["date", "plainDate", "2026-11-20"], + ["time", "plainTime", "16:00:00"], + ["duration", "duration", "PT1H"], + ])("round-trips nullable %s examples through %s", async (format, scalar, value) => { + const examples = [value, null]; + const code = await convertOpenAPI3Document( + documentFor({ type: ["string", "null"], format, examples }), + ); + expect(code).toContain(`${scalar}.fromISO("${value}")`); + const output = await emitOpenAPI(code); + expect(output.components.schemas.Pet.examples).toEqual(examples); + }); + + it("uses enum members for inherited properties and null-first unions", async () => { + const input = documentFor({ + allOf: [{ $ref: "#/components/schemas/Base" }], + examples: [{ color: "red" }], + }); + Object.assign(input.components!.schemas!, { + Color: { type: "string", enum: ["red", "blue"] }, + Base: { + type: "object", + properties: { color: { $ref: "#/components/schemas/Color" } }, + }, + Choice: { + anyOf: [{ type: "null" }, { $ref: "#/components/schemas/Color" }], + examples: [null, "red"], + }, + }); + const code = await convertOpenAPI3Document(input); + expect(code).toContain("#{ color: Pets.Color.red }"); + expect(code).toContain("@example(Pets.Color.red)"); + const output = await emitOpenAPI(code); + expect(output.components.schemas.Pet.examples).toEqual([{ color: "red" }]); + expect(output.components.schemas.Choice.examples).toEqual([null, "red"]); + }); + + it("uses required properties to select the matching example object variant", async () => { + const examples = [{ b: "2026-11-20T16:00:00Z" }]; + const code = await convertOpenAPI3Document( + documentFor({ + anyOf: [ + { type: "object", properties: { a: { type: "string" } }, required: ["a"] }, + { + type: "object", + properties: { b: { type: "string", format: "date-time" } }, + required: ["b"], + }, + ], + examples, + }), + ); + expect(code).toContain('b: utcDateTime.fromISO("2026-11-20T16:00:00Z")'); + const output = await emitOpenAPI(code); + expect(output.components.schemas.Pet.examples).toEqual(examples); + }); + it("preserves outer examples without merging nullable union member examples", async () => { const examples = [null, "Fluffy"]; const code = await convertOpenAPI3Document( From 3c26723e304a488933d85ae4baffc8fbcddecfc2 Mon Sep 17 00:00:00 2001 From: baywet <7905502+baywet@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:31:24 +0000 Subject: [PATCH 7/8] test(openapi3): use spellcheck-safe example name Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- cspell.yaml | 1 - packages/openapi3/test/tsp-openapi3/examples.test.ts | 8 ++++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/cspell.yaml b/cspell.yaml index 1c72297bd31..d795d3527ab 100644 --- a/cspell.yaml +++ b/cspell.yaml @@ -172,7 +172,6 @@ words: - mgmt - mgmtplane - mocharc - - Mochi - mqtt - mros - msbuild diff --git a/packages/openapi3/test/tsp-openapi3/examples.test.ts b/packages/openapi3/test/tsp-openapi3/examples.test.ts index d6f8c252580..93596e52def 100644 --- a/packages/openapi3/test/tsp-openapi3/examples.test.ts +++ b/packages/openapi3/test/tsp-openapi3/examples.test.ts @@ -41,14 +41,14 @@ describe("import schema examples", () => { it("creates example decorators in reverse order without mutating the input", () => { const schema: OpenAPISchema3_2 = { type: "object", - examples: [{ name: "Fluffy" }, { name: "Spot" }, { name: "Mochi" }], + examples: [{ name: "Fluffy" }, { name: "Spot" }, { name: "Buddy" }], }; expect(generateDecorators(getDecoratorsForSchema(schema))).toEqual([ - '@example(#{name: "Mochi"})', + '@example(#{name: "Buddy"})', '@example(#{name: "Spot"})', '@example(#{name: "Fluffy"})', ]); - expect(schema.examples).toEqual([{ name: "Fluffy" }, { name: "Spot" }, { name: "Mochi" }]); + expect(schema.examples).toEqual([{ name: "Fluffy" }, { name: "Spot" }, { name: "Buddy" }]); }); it("preserves duplicate examples", () => { @@ -115,7 +115,7 @@ describe("import schema examples", () => { it.each([ { examples: [{ name: "Fluffy" }] }, - { examples: [{ name: "Fluffy" }, { name: "Spot" }, { name: "Mochi" }] }, + { examples: [{ name: "Fluffy" }, { name: "Spot" }, { name: "Buddy" }] }, { examples: [{ name: "Fluffy" }, { name: "Fluffy" }] }, ])("round-trips model examples $examples in their original order", async ({ examples }) => { const code = await convertOpenAPI3Document( From 255e03b20708909e7b9455127ff1a39d76ea680d Mon Sep 17 00:00:00 2001 From: baywet <7905502+baywet@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:42:09 +0000 Subject: [PATCH 8/8] docs(openapi3): clarify example string escaping Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/openapi3/src/cli/actions/convert/utils/decorators.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/openapi3/src/cli/actions/convert/utils/decorators.ts b/packages/openapi3/src/cli/actions/convert/utils/decorators.ts index 65b5a4bc5ef..0bb1d2ad834 100644 --- a/packages/openapi3/src/cli/actions/convert/utils/decorators.ts +++ b/packages/openapi3/src/cli/actions/convert/utils/decorators.ts @@ -622,6 +622,7 @@ function isExampleValueCompatible( } } +/** Example strings need explicit escaping for backslashes and supported control characters. */ function stringLiteralForExample(value: string): string { return `"${value .replaceAll("\\", "\\\\")