Skip to content

Commit

Permalink
fix: use maps instead of literals in configureCategories (backport #…
Browse files Browse the repository at this point in the history
…1598) (#1599)

# Backport

This will backport the following commits from `main` to
`maintenance/v5.4`:
- [fix: use maps instead of literals in `configureCategories`
(#1598)](#1598)

<!--- Backport version: 9.5.1 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sorenlouv/backport)

Co-authored-by: Eli Polonsky <Eli.polonsky@gmail.com>
  • Loading branch information
aws-cdk-automation and iliapolo authored Dec 18, 2024
1 parent 7dd6d70 commit 1a0b9d7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/jsii-diagnostic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,13 @@ export class Code<T extends DiagnosticMessageFormatter = DiagnosticMessageFormat
*/
public static lookup(codeOrName: string | number): Code | undefined {
if (typeof codeOrName === 'number') {
return this.byCode[codeOrName];
return this.byCode.get(codeOrName);
}
return this.byName[codeOrName];
return this.byName.get(codeOrName);
}

private static readonly byCode: { [code: number]: Code } = {};
private static readonly byName: { [name: string]: Code } = {};
private static readonly byCode: Map<number, Code> = new Map();
private static readonly byName: Map<string, Code> = new Map();

// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
readonly #defaultCategory: ts.DiagnosticCategory;
Expand Down Expand Up @@ -126,7 +126,8 @@ export class Code<T extends DiagnosticMessageFormatter = DiagnosticMessageFormat
if (name in Code.byName) {
throw new Error(`Attempted to create two instances of ${this.constructor.name} with name ${name}`);
}
Code.byCode[code] = Code.byName[name] = this;
Code.byCode.set(code, this);
Code.byName.set(name, this);
}

/**
Expand Down
6 changes: 6 additions & 0 deletions test/jsii-diagnostic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ describe('jsii diagnostics', () => {
code.category = DiagnosticCategory.Suggestion;
});

test('throws on __proto__ key', () => {
expect(() => configureCategories(JSON.parse('{"__proto__":{"pollutedKey":123}}'))).toThrow(
`Unrecognized diagnostic code '__proto__'`,
);
});

test('diagnostic by name', () => {
configureCategories({
'metadata/package-json-missing-description': DiagnosticCategory.Error,
Expand Down

0 comments on commit 1a0b9d7

Please sign in to comment.