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
#1877)

* fix: replace special characters using `SPECIAL_CHARACTER_MAP` for duplicate-identifiers

* chore: optimized code

* Create slimy-points-learn.md
  • Loading branch information
phk422 authored Aug 30, 2024
1 parent 9c93cfd commit 94592a4
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
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

0 comments on commit 94592a4

Please sign in to comment.