Skip to content

Commit

Permalink
fix: replace special characters using SPECIAL_CHARACTER_MAP for dup…
Browse files Browse the repository at this point in the history
…licate-identifiers
  • Loading branch information
phk422 committed Aug 24, 2024
1 parent 2a4b067 commit 3f679a6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/openapi-typescript/src/lib/ts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import ts, { type LiteralTypeNode, type TypeLiteralNode } from "typescript";
export const JS_PROPERTY_INDEX_RE = /^[A-Za-z_$][A-Za-z_$0-9]*$/;
export const JS_ENUM_INVALID_CHARS_RE = /[^A-Za-z_$0-9]+(.)?/g;
export const JS_PROPERTY_INDEX_INVALID_CHARS_RE = /[^A-Za-z_$0-9]+/g;
export const SPECIAL_CHARACTER_MAP: Record<string, string> = {
"+": "Plus",
// Add more mappings as needed
};

export const BOOLEAN = ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
export const FALSE = ts.factory.createLiteralTypeNode(ts.factory.createFalse());
Expand Down Expand Up @@ -308,7 +312,7 @@ export function tsEnumMember(value: string | number, metadata: { name?: string;
if (invalidCharMatch[0] === name) {
name = `"${name}"`;
} else {
name = name.replace(JS_PROPERTY_INDEX_INVALID_CHARS_RE, "_");
name = name.replace(JS_PROPERTY_INDEX_INVALID_CHARS_RE, (substring) => SPECIAL_CHARACTER_MAP[substring] || "_");
}
}
}
Expand Down
8 changes: 8 additions & 0 deletions packages/openapi-typescript/test/lib/ts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,14 @@ describe("tsEnum", () => {
NotFound = 101,
// User doesn't have permissions
PermissionDenied = 102
}`);
});

test("replace special character", () => {
expect(astToString(tsEnum("FOO_ENUM", ['Etc/GMT+0', "Etc/GMT+1", "Etc/GMT-1"])).trim()).toBe(`enum FOO_ENUM {
Etc_GMTPlus0 = "Etc/GMT+0",
Etc_GMTPlus1 = "Etc/GMT+1",
Etc_GMT_1 = "Etc/GMT-1"
}`);
});
});
Expand Down

0 comments on commit 3f679a6

Please sign in to comment.