-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgenerateChecker.ts
63 lines (55 loc) · 1.61 KB
/
generateChecker.ts
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import * as ts from "typescript";
import * as fs from "fs";
import * as path from "path";
function extractUnionType(type: ts.TypeNode): string[] {
if (ts.isUnionTypeNode(type)) {
return type.types.map((t) =>
ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal)
? t.literal.text
: "",
);
}
return [];
}
function generateCheckerFileContent(types: string[]): string {
const dummyObject = types.map((t) => `'${t}': null`).join(",\n ");
return `
export function isSupportedStyleProperty(key: string): key is StyleProperty {
const dummyObject: Record<StyleProperty, null> = {
${dummyObject}
};
return key in dummyObject;
}
`;
}
function main() {
const fileName =
"./node_modules/@webflow/designer-extension-typings/styles-generated.d.ts";
const sourceFile = ts.createSourceFile(
fileName,
ts.sys.readFile(fileName)!,
ts.ScriptTarget.Latest,
true,
);
let unionTypes: string[] = [];
const visitNode = (node: ts.Node) => {
if (ts.isTypeAliasDeclaration(node) && node.name.text === "StyleProperty") {
unionTypes = extractUnionType(node.type);
}
ts.forEachChild(node, visitNode);
};
ts.forEachChild(sourceFile, visitNode);
if (unionTypes.length) {
const outputPath = path.resolve(__dirname, "utils", "styleChecker.ts");
if (!fs.existsSync(path.resolve(__dirname, "utils"))) {
fs.mkdirSync(path.resolve(__dirname, "utils"));
}
fs.writeFileSync(
outputPath,
generateCheckerFileContent(unionTypes),
"utf8",
);
console.log(`Checker function written to ${outputPath}`);
}
}
main();