Skip to content

Commit 3392588

Browse files
authored
fix: Escape special chars in enum name (#283)
1 parent 2678ea4 commit 3392588

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

plugins/typescript/src/core/schemaToEnumDeclaration.test.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,14 +71,20 @@ describe("schemaToTypeAliasDeclaration", () => {
7171
it("should generate valid enum with values that contains spaces", () => {
7272
const schema: SchemaObject = {
7373
type: "string",
74-
enum: ["saimois", "bengal", "british shorthair"],
74+
enum: [
75+
"saimois",
76+
"bengal",
77+
"british shorthair",
78+
"danish\u2013swedish farmdog",
79+
],
7580
};
7681

7782
expect(printSchema(schema, "test")).toMatchInlineSnapshot(`
7883
"export enum Test {
7984
Saimois = "saimois",
8085
Bengal = "bengal",
81-
BritishShorthair = "british shorthair"
86+
BritishShorthair = "british shorthair",
87+
"danish\\u2013swedish farmdog" = "danish\\u2013swedish farmdog"
8288
}"
8389
`);
8490
});

plugins/typescript/src/core/schemaToEnumDeclaration.ts

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,30 @@ import ts, { factory as f } from "typescript";
44
import { convertNumberToWord } from "../utils/getEnumProperties";
55
import { Context, getJSDocComment } from "./schemaToTypeAliasDeclaration";
66

7+
/**
8+
* Function to check if a string is a valid TypeScript identifier
9+
*
10+
* @param name Name to check
11+
*/
12+
function isValidIdentifier(name: string): boolean {
13+
if (name.length === 0) {
14+
return false;
15+
}
16+
17+
const firstChar = name.charCodeAt(0);
18+
if (!ts.isIdentifierStart(firstChar, ts.ScriptTarget.Latest)) {
19+
return false;
20+
}
21+
22+
for (let i = 1; i < name.length; i++) {
23+
if (!ts.isIdentifierPart(name.charCodeAt(i), ts.ScriptTarget.Latest)) {
24+
return false;
25+
}
26+
}
27+
28+
return true;
29+
}
30+
731
/**
832
* Add Enum support when transforming an OpenAPI Schema Object to Typescript Nodes.
933
*
@@ -52,8 +76,11 @@ function getEnumMembers(schema: SchemaObject): ts.EnumMember[] {
5276
throw new Error(`Unsupported enum value type: ${typeof enumValue}`);
5377
}
5478

79+
enumName = pascal(enumName);
5580
return f.createEnumMember(
56-
f.createIdentifier(pascal(enumName)),
81+
isValidIdentifier(enumName)
82+
? f.createIdentifier(enumName)
83+
: f.createStringLiteral(`${enumValue}`),
5784
enumValueNode
5885
);
5986
});

0 commit comments

Comments
 (0)