Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@cadl-lang/openapi3",
"comment": "Fix issue with OpenAPI emitter not sanitizing parameter names in reference identifiers",
"type": "patch"
}
],
"packageName": "@cadl-lang/openapi3"
}
7 changes: 3 additions & 4 deletions packages/openapi3/src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -613,17 +613,16 @@ function createOAPIEmitter(program: Program, options: OpenAPIEmitterOptions) {
}

// Try to shorten the type name to exclude the top-level service namespace
let baseKey = getRefSafeName(key);
if (serviceNamespace && key.startsWith(serviceNamespace)) {
baseKey = key.substring(serviceNamespace.length + 1);
const baseKey = key.substring(serviceNamespace.length + 1);

// If no parameter exists with the shortened name, use it, otherwise use the fully-qualified name
if (!root.components.parameters[baseKey] || isQualifiedParamName) {
key = baseKey;
}
}

return key;
return getRefSafeName(key);
}

function getSchemaForType(type: Type) {
Expand Down Expand Up @@ -1210,7 +1209,7 @@ function isRefSafeName(name: string) {
}

function getRefSafeName(name: string) {
return name.replace(/^[A-Za-z0-9-_.]/g, "_");
return name.replace(/[^A-Za-z0-9-_.]/g, "_");
}

function prettierOutput(output: string) {
Expand Down
25 changes: 25 additions & 0 deletions packages/openapi3/test/test-openapi-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -937,4 +937,29 @@ describe("openapi3: extension decorator", () => {
strictEqual(oapi.components.parameters.PetId.schema.format, "UUID");
strictEqual(oapi.components.parameters.PetId.schema.pattern, "^[a-zA-Z0-9-]{3,24}$");
});

it("correctly sanitizes parameter names", async () => {
const oapi = await openApiFor(
`
model Pet extends Pet$Id {
name: string;
}
model Pet$Id {
@path
petId: string;
}
@route("/Pets")
namespace root {
@get()
op get(... Pet$Id): Pet;
}
`
);
ok(oapi.paths["/Pets/{petId}"].get);
strictEqual(
oapi.paths["/Pets/{petId}"].get.parameters[0]["$ref"],
"#/components/parameters/Pet_Id"
);
strictEqual(oapi.components.parameters.Pet_Id.name, "petId");
});
});