|
| 1 | +import * as ts from "typescript"; |
| 2 | + |
| 3 | +const program = ts.createProgram(["./types/framework.d.ts"], {}); |
| 4 | +const source = program.getSourceFile("./types/framework.d.ts"); |
| 5 | + |
| 6 | +if (source) { |
| 7 | + let names: string[] = []; |
| 8 | + |
| 9 | + findGlobalDeclarations(source); |
| 10 | + |
| 11 | + // This recursive function finds all interface, type alias, class, enum, function, and variable type declarations in `framework.d.ts` |
| 12 | + // and adds the names of those declarations to the `names` array. |
| 13 | + // AI was used to generate this function, but it was tested and modified to work correctly. |
| 14 | + function findGlobalDeclarations(node: ts.Node) { |
| 15 | + if ( |
| 16 | + ts.isModuleDeclaration(node) && |
| 17 | + node.name.kind === ts.SyntaxKind.Identifier && |
| 18 | + node.name.text === "global" |
| 19 | + ) { |
| 20 | + if (node.body && ts.isModuleBlock(node.body)) { |
| 21 | + node.body.statements.forEach((stmt) => { |
| 22 | + if ( |
| 23 | + ts.isInterfaceDeclaration(stmt) || |
| 24 | + ts.isTypeAliasDeclaration(stmt) || |
| 25 | + ts.isClassDeclaration(stmt) || |
| 26 | + ts.isEnumDeclaration(stmt) || |
| 27 | + ts.isFunctionDeclaration(stmt) || |
| 28 | + ts.isVariableStatement(stmt) |
| 29 | + ) { |
| 30 | + // extract the name(s) |
| 31 | + if ("name" in stmt && stmt.name) { |
| 32 | + names.push(stmt.name.text); |
| 33 | + } else if (ts.isVariableStatement(stmt)) { |
| 34 | + stmt.declarationList.declarations.forEach((decl) => { |
| 35 | + if (decl.name && ts.isIdentifier(decl.name)) { |
| 36 | + names.push(decl.name.text); |
| 37 | + } |
| 38 | + }); |
| 39 | + } |
| 40 | + } |
| 41 | + }); |
| 42 | + } |
| 43 | + } else { |
| 44 | + ts.forEachChild(node, findGlobalDeclarations); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + names = [...new Set(names)]; // prevent duplicate typeDefs from being generated |
| 49 | + const typeDefs = names.map((name) => `${name}: typeof ${name};`); |
| 50 | + |
| 51 | + const instanceModeTemplateFile = Bun.file( |
| 52 | + "./types/instance-mode-template.d.ts", |
| 53 | + ); |
| 54 | + const instanceModeTemplate = await instanceModeTemplateFile.text(); |
| 55 | + |
| 56 | + const instanceMode = instanceModeTemplate |
| 57 | + .split("\n") |
| 58 | + .flatMap((line) => { |
| 59 | + if (line.includes("%Q5_FRAMEWORK_TYPES%")) { |
| 60 | + return typeDefs; |
| 61 | + } |
| 62 | + return line; |
| 63 | + }) |
| 64 | + .join("\n"); |
| 65 | + |
| 66 | + await Bun.write("./types/instance-mode.d.ts", instanceMode); |
| 67 | +} |
0 commit comments