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

Use TS Morph to generate type predicates #1387

Closed
wants to merge 2 commits into from
Closed
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
64 changes: 64 additions & 0 deletions code-generation/generate-type-predicates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { InterfaceDeclaration, MethodDeclaration, Project, SyntaxKind } from "ts-morph"

// open a new project with just BrowserTypes as the only source file
const project = new Project();
const sourceFile = project.addSourceFileAtPath("./src/api/BrowserTypes.ts")

//get a list of all interfaces in the file
const interfaces = sourceFile.getChildrenOfKind(SyntaxKind.InterfaceDeclaration);

// get a list of all conversion functions in the Convert class
const convert = sourceFile.getClass("Convert");
const convertFunctions = (convert?.getChildrenOfKind(SyntaxKind.MethodDeclaration) ?? []).filter(func => func.getReturnType().getText() === "string");

// generate a list of Interfaces that have an associated conversion function
const matchedInterfaces = convertFunctions.map(func => {
const valueParameter = func.getParameter("value");

const matchingInterface = interfaces.find(interfaceNode => {
return valueParameter?.getType().getText(valueParameter) === interfaceNode.getName();
});


if(matchingInterface != null) {
return {func, matchingInterface};
}

return undefined;
}).filter(((value => value != null) as <T>(value: T | null | undefined) => value is T));

// write a type predicate for each matched interface
matchedInterfaces.forEach(matched => writePredicate(matched.matchingInterface, matched.func));

writeUnionType("RequestMessage", interfaces, "Request");
writeUnionType("ResponseMessage", interfaces, "Response");
writeUnionType("EventMessage", interfaces, "Event");

function writePredicate(matchingInterface: InterfaceDeclaration, func: MethodDeclaration): void{
const predicateName = `is${matchingInterface.getName()}`;

sourceFile.addStatements(`
export function ${predicateName}(value: any): value is ${matchingInterface.getName()} {
try{
Convert.${func.getName()}(value);
return true;
} catch(e: any){
return false;
}
}`);
}



function writeUnionType(unionName: string, interfaces: InterfaceDeclaration[], nameEndsWith: string): void{
const matchingInterfaces = interfaces
.map(currentInterface => currentInterface.getName())
.filter(interfaceName => interfaceName.length > nameEndsWith.length && interfaceName.indexOf(nameEndsWith) === interfaceName.length - nameEndsWith.length);

sourceFile.addStatements(`
export type ${unionName} = ${matchingInterfaces.join(" | ")};`);
}

sourceFile.formatText();

project.saveSync();
37 changes: 37 additions & 0 deletions code-generation/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
// see https://www.typescriptlang.org/tsconfig to better understand tsconfigs
"files": ["generate-type-predicates.ts"],
"compilerOptions": {
"module": "CommonJS",
Copy link
Contributor

@kriswest kriswest Oct 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this really need its own tsconfig.json, or could it use the existing one in the root? The only differences between the two tsconfig files appear to be:

  • "module": "CommonJS" vs. "module": "esnext"
  • the file filter.

AFAIK ts-node is quite happy to handle ESM...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am pretty sure that I would have only added this as I was getting errors without but hopefully I can get it to work without if I have another go.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original one has an include filter that would have excluded your codegeneration directory: https://github.com/finos/FDC3/blob/1a21b027f506d9ed88d5e3a1d55be38ac03ae828/tsconfig.json#L3C25-L3C25

The only other difference is your files entry above - could it have been that it just wasn't applying to your file?

"lib": ["dom", "esnext"],
"importHelpers": true,
// output .d.ts declaration files for consumers
"declaration": true,
"outDir": "dist",
// output .js.map sourcemap files for consumers
"sourceMap": true,
// match output dir to input dir. e.g. dist/index instead of dist/src/index
"rootDir": "./",
// stricter type-checking for stronger correctness. Recommended by TS
"strict": true,
// linter checks for common issues
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
// noUnused* overlap with @typescript-eslint/no-unused-vars, can disable if duplicative
"noUnusedLocals": true,
"noUnusedParameters": true,
// use Node's module resolution algorithm, instead of the legacy TS one
"moduleResolution": "node",
// transpile JSX to React.createElement
"jsx": "react",
// interop between ESM and CJS modules. Recommended by TS
"esModuleInterop": true,
// significant perf increase by skipping checking .d.ts files, particularly those in node_modules. Recommended by TS
"skipLibCheck": true,
// error out if import and file system have a casing mismatch. Recommended by TS
"forceConsistentCasingInFileNames": true,
// `tsdx build` ignores this option, but it is commonly used when type-checking separately with `tsc`
"noEmit": true,
}
}

73 changes: 73 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
"prepack": "npm run build",
"typegen": "cd schemas && node ../s2tQuicktypeUtil.js context ../src/context/ContextTypes.ts",
"typegen-browser": "cd schemas && node ../s2tQuicktypeUtil.js api/api.schema.json api/common.schema.json context/context.schema.json api ../src/api/BrowserTypes.ts",
"typegen-bridging": "cd schemas && node ../s2tQuicktypeUtil.js api/api.schema.json api/common.schema.json api/broadcastRequest.schema.json api/findInstancesRequest.schema.json api/findInstancesResponse.schema.json api/findIntentRequest.schema.json api/findIntentResponse.schema.json api/findIntentsByContextRequest.schema.json api/findIntentsByContextResponse.schema.json api/getAppMetadataRequest.schema.json api/getAppMetadataResponse.schema.json api/openRequest.schema.json api/openResponse.schema.json api/raiseIntentRequest.schema.json api/raiseIntentResponse.schema.json api/raiseIntentResultResponse.schema.json context/context.schema.json bridging ../src/bridging/BridgingTypes.ts"
"typegen-bridging": "cd schemas && node ../s2tQuicktypeUtil.js api/api.schema.json api/common.schema.json api/broadcastRequest.schema.json api/findInstancesRequest.schema.json api/findInstancesResponse.schema.json api/findIntentRequest.schema.json api/findIntentResponse.schema.json api/findIntentsByContextRequest.schema.json api/findIntentsByContextResponse.schema.json api/getAppMetadataRequest.schema.json api/getAppMetadataResponse.schema.json api/openRequest.schema.json api/openResponse.schema.json api/raiseIntentRequest.schema.json api/raiseIntentResponse.schema.json api/raiseIntentResultResponse.schema.json context/context.schema.json bridging ../src/bridging/BridgingTypes.ts",
"posttypegen-browser": "npm run generate-type-predicates",
"generate-type-predicates": "ts-node code-generation/generate-type-predicates.ts"
Comment on lines +31 to +32
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that this is the only thing run 'post' typegen-browser you can probably combine these entries.

},
"husky": {
"hooks": {
Expand Down Expand Up @@ -65,6 +67,8 @@
"rimraf": "^5.0.5",
"rollup": "4.22.4",
"ts-jest": "29.1.2",
"ts-morph": "^23.0.0",
"ts-node": "^10.9.2",
"tslib": "^2.0.1",
"typescript": "^4.0.3"
},
Expand Down
Loading