-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathnewHelperTypeName.ts
More file actions
41 lines (38 loc) · 1.41 KB
/
Copy pathnewHelperTypeName.ts
File metadata and controls
41 lines (38 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { ParserState } from "./ParserState";
import ts from "typescript";
import { createHash } from "node:crypto";
import { getCanonicalTypeName } from "./canonicalTypeName";
export const newHashedHelperTypeName = (state: ParserState, type: ts.Type) => {
// to keep helper type names predictable and not dependent on the order of definition,
// we use the first 10 characters of a sha256 hash of the type. If there is an unexpected
// collision, we fallback to using an incrementing counter.
const fullHash = createHash("sha256").update(
getCanonicalTypeName(state, type),
);
// for the short hash, we remove all non-alphanumeric characters from the hash and take the
// first 10 characters.
let shortHash = fullHash.digest("base64").replace(/\W/g, "").substring(0, 10);
if (
state.helperTypeNames.has(shortHash) &&
state.helperTypeNames.get(shortHash) !== type
) {
shortHash = "HelperType" + state.helperTypeNames.size.toString();
} else {
state.helperTypeNames.set(shortHash, type);
}
return `Ts2Py_${shortHash}`;
};
const getIndexedName = (i: number, prefix: string) => `Ts2Py_${prefix}_${i}`;
export const newIndexedHelperTypeName = (
state: ParserState,
type: ts.Type,
prefix: string,
) => {
let i = 0;
while (state.helperTypeNames.has(getIndexedName(i, prefix))) {
i += 1;
}
const name = getIndexedName(i, prefix);
state.helperTypeNames.set(name, type);
return name;
};