Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: replace special characters using SPECIAL_CHARACTER_MAP for dup… #1877

Merged
merged 3 commits into from
Aug 30, 2024
Merged
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
5 changes: 5 additions & 0 deletions .changeset/slimy-points-learn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-typescript": patch
---

fix: replace special characters using `SPECIAL_CHARACTER_MAP` for duplicate-identifiers
8 changes: 7 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,9 @@ 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, (s) => {
return s in SPECIAL_CHARACTER_MAP ? SPECIAL_CHARACTER_MAP[s] : "_";
});
}
}
}
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