@dextinity/api-generator 2.0.0-canary-20260729062014

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +24 -0
  2. package/bin/api-generator.js +6 -0
  3. package/lib/apiGenerator.d.ts +1 -0
  4. package/lib/apiGenerator.js +7 -0
  5. package/lib/commands/generate/generate-command.d.ts +2 -0
  6. package/lib/commands/generate/generate-command.js +19 -0
  7. package/lib/commands/generate/generateCrud/build-options.d.ts +24 -0
  8. package/lib/commands/generate/generateCrud/build-options.js +144 -0
  9. package/lib/commands/generate/generateCrud/generate-crud.d.ts +18 -0
  10. package/lib/commands/generate/generateCrud/generate-crud.js +1092 -0
  11. package/lib/commands/generate/generateCrud/generate-enum-filter-dto.d.ts +2 -0
  12. package/lib/commands/generate/generateCrud/generate-enum-filter-dto.js +76 -0
  13. package/lib/commands/generate/generateCrud/generate-payload-object-types.d.ts +12 -0
  14. package/lib/commands/generate/generateCrud/generate-payload-object-types.js +38 -0
  15. package/lib/commands/generate/generateCrud/generate-service-hook-call.d.ts +8 -0
  16. package/lib/commands/generate/generateCrud/generate-service-hook-call.js +47 -0
  17. package/lib/commands/generate/generateCrudInput/generate-crud-input.d.ts +12 -0
  18. package/lib/commands/generate/generateCrudInput/generate-crud-input.js +499 -0
  19. package/lib/commands/generate/generateCrudSingle/generate-crud-single.d.ts +4 -0
  20. package/lib/commands/generate/generateCrudSingle/generate-crud-single.js +134 -0
  21. package/lib/commands/generate/generateFiles.d.ts +13 -0
  22. package/lib/commands/generate/generateFiles.js +81 -0
  23. package/lib/commands/generate/utils/build-name-variants.d.ts +9 -0
  24. package/lib/commands/generate/utils/build-name-variants.js +24 -0
  25. package/lib/commands/generate/utils/constants.d.ts +2 -0
  26. package/lib/commands/generate/utils/constants.js +5 -0
  27. package/lib/commands/generate/utils/find-hooks-service.d.ts +19 -0
  28. package/lib/commands/generate/utils/find-hooks-service.js +185 -0
  29. package/lib/commands/generate/utils/generate-imports-code.d.ts +5 -0
  30. package/lib/commands/generate/utils/generate-imports-code.js +32 -0
  31. package/lib/commands/generate/utils/ts-morph-helper.d.ts +18 -0
  32. package/lib/commands/generate/utils/ts-morph-helper.js +237 -0
  33. package/lib/commands/generate/utils/write-generated-file.d.ts +3 -0
  34. package/lib/commands/generate/utils/write-generated-file.js +113 -0
  35. package/lib/commands/generate/utils/write-generated-files.d.ts +7 -0
  36. package/lib/commands/generate/utils/write-generated-files.js +9 -0
  37. package/lib/commands/generate/watchMode/handleChildProcess.d.ts +2 -0
  38. package/lib/commands/generate/watchMode/handleChildProcess.js +26 -0
  39. package/lib/commands/generate/watchMode/watchMode.d.ts +6 -0
  40. package/lib/commands/generate/watchMode/watchMode.js +70 -0
  41. package/package.json +79 -0
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.generateFiles = void 0;
7
+ const node_console_1 = __importDefault(require("node:console"));
8
+ const node_fs_1 = require("node:fs");
9
+ const promises_1 = require("node:fs/promises");
10
+ const cms_api_1 = require("@dextinity/cms-api");
11
+ const cli_1 = require("@mikro-orm/cli");
12
+ const lazy_metadata_storage_js_1 = require("@nestjs/graphql/dist/schema-builder/storages/lazy-metadata.storage.js");
13
+ const prettier_1 = require("prettier");
14
+ const build_options_1 = require("./generateCrud/build-options");
15
+ const generate_crud_1 = require("./generateCrud/generate-crud");
16
+ const generate_crud_single_1 = require("./generateCrudSingle/generate-crud-single");
17
+ const write_generated_files_1 = require("./utils/write-generated-files");
18
+ /**
19
+ * Generate mode for the generator.
20
+ *
21
+ * Generates CRUD files for all entities or a specific entity available at file path.
22
+ * @param file
23
+ */
24
+ const generateFiles = async (
25
+ /**
26
+ * File path to the entity for which to generate CRUD files.
27
+ *
28
+ * @default undefined -> generate all entities
29
+ */
30
+ file) => {
31
+ let orm = null;
32
+ try {
33
+ orm = await cli_1.CLIHelper.getORM(undefined, undefined, { dbName: "generator" });
34
+ }
35
+ catch (e) {
36
+ node_console_1.default.warn(e);
37
+ }
38
+ if (orm != null) {
39
+ const writtenFiles = [];
40
+ const entities = orm.em.getMetadata().getAll();
41
+ lazy_metadata_storage_js_1.LazyMetadataStorage.load();
42
+ for (const name in entities) {
43
+ const entity = entities[name];
44
+ if (!entity.class) {
45
+ // Ignore e.g. relation entities that don't have a class
46
+ continue;
47
+ }
48
+ if (file == null || entity.path === `./${file}`) {
49
+ {
50
+ const generatorOptions = Reflect.getMetadata(cms_api_1.CRUD_GENERATOR_METADATA_KEY, entity.class);
51
+ if (generatorOptions) {
52
+ node_console_1.default.log(`🚀 start generateCrud for Entity ${entity.path}`);
53
+ const files = await (0, generate_crud_1.generateCrud)(generatorOptions, entity);
54
+ const { targetDirectory } = (0, build_options_1.buildOptions)(entity, generatorOptions);
55
+ await (0, write_generated_files_1.writeGeneratedFiles)(files, targetDirectory);
56
+ writtenFiles.push(...files.map((f) => (0, node_fs_1.realpathSync)(`${f.targetDirectory ?? targetDirectory}/${f.name}`)));
57
+ }
58
+ }
59
+ {
60
+ const generatorOptions = Reflect.getMetadata(cms_api_1.CRUD_SINGLE_GENERATOR_METADATA_KEY, entity.class);
61
+ if (generatorOptions) {
62
+ node_console_1.default.log(`🚀 start generateCrudSingle for Entity ${entity.path}`);
63
+ const files = await (0, generate_crud_single_1.generateCrudSingle)(generatorOptions, entity);
64
+ const { targetDirectory } = (0, build_options_1.buildOptions)(entity, generatorOptions);
65
+ await (0, write_generated_files_1.writeGeneratedFiles)(files, targetDirectory);
66
+ writtenFiles.push(...files.map((f) => (0, node_fs_1.realpathSync)(`${f.targetDirectory ?? targetDirectory}/${f.name}`)));
67
+ }
68
+ }
69
+ }
70
+ }
71
+ if (writtenFiles.length > 0) {
72
+ node_console_1.default.log(`Formatting ${writtenFiles.length} generated files...`);
73
+ await Promise.all(writtenFiles.map(async (filepath) => {
74
+ const [content, options] = await Promise.all([(0, promises_1.readFile)(filepath, "utf-8"), (0, prettier_1.resolveConfig)(filepath)]);
75
+ const formatted = await (0, prettier_1.format)(content, { ...options, filepath });
76
+ await (0, promises_1.writeFile)(filepath, formatted);
77
+ }));
78
+ }
79
+ }
80
+ };
81
+ exports.generateFiles = generateFiles;
@@ -0,0 +1,9 @@
1
+ import type { EntityMetadata } from "@mikro-orm/postgresql";
2
+ export declare function buildNameVariants(metadata: EntityMetadata<any>): {
3
+ classNameSingular: string;
4
+ classNamePlural: string;
5
+ instanceNameSingular: string;
6
+ instanceNamePlural: string;
7
+ fileNameSingular: string;
8
+ fileNamePlural: string;
9
+ };
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildNameVariants = buildNameVariants;
4
+ const pluralize_1 = require("pluralize");
5
+ function classNameToInstanceName(className) {
6
+ return className[0].toLocaleLowerCase() + className.slice(1);
7
+ }
8
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
+ function buildNameVariants(metadata) {
10
+ const classNameSingular = metadata.className;
11
+ const classNamePlural = (0, pluralize_1.plural)(metadata.className);
12
+ const instanceNameSingular = classNameToInstanceName(classNameSingular);
13
+ const instanceNamePlural = classNameToInstanceName(classNamePlural);
14
+ const fileNameSingular = instanceNameSingular.replace(/[A-Z]/g, (i) => `-${i.toLocaleLowerCase()}`);
15
+ const fileNamePlural = instanceNamePlural.replace(/[A-Z]/g, (i) => `-${i.toLocaleLowerCase()}`);
16
+ return {
17
+ classNameSingular,
18
+ classNamePlural,
19
+ instanceNameSingular,
20
+ instanceNamePlural,
21
+ fileNameSingular,
22
+ fileNamePlural,
23
+ };
24
+ }
@@ -0,0 +1,2 @@
1
+ export declare const integerTypes: string[];
2
+ export declare const numberTypes: string[];
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.numberTypes = exports.integerTypes = void 0;
4
+ exports.integerTypes = ["int", "integer", "tinyint", "smallint", "mediumint", "bigint", "int2", "int4", "int8", "serial"];
5
+ exports.numberTypes = [...exports.integerTypes, "DecimalType", "BigIntType", "number", "float", "double", "decimal"];
@@ -0,0 +1,19 @@
1
+ import type { CrudGeneratorOptions } from "@dextinity/cms-api";
2
+ import type { EntityMetadata } from "@mikro-orm/core";
3
+ import type { Imports } from "./generate-imports-code";
4
+ export declare function findHooksService({ generatorOptions, metadata, targetDirectory, }: {
5
+ generatorOptions: CrudGeneratorOptions;
6
+ metadata: EntityMetadata;
7
+ targetDirectory: string;
8
+ }): {
9
+ validateCreateInput: {
10
+ options?: string[];
11
+ returnType: string;
12
+ } | null;
13
+ validateUpdateInput: {
14
+ options?: string[];
15
+ returnType: string;
16
+ } | null;
17
+ imports: Imports;
18
+ className: string;
19
+ } | null;
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.findHooksService = findHooksService;
37
+ const path = __importStar(require("path"));
38
+ const ts_morph_1 = require("ts-morph");
39
+ const ts_morph_helper_1 = require("./ts-morph-helper");
40
+ function findReturnTypeImport(type, serviceSourceFile, targetDirectory) {
41
+ const symbol = type.getSymbol() ?? type.getAliasSymbol();
42
+ if (!symbol) {
43
+ // Primitive type, no import needed
44
+ return null;
45
+ }
46
+ const typeName = symbol.getName();
47
+ const declarations = symbol.getDeclarations();
48
+ if (!declarations || declarations.length === 0) {
49
+ return null;
50
+ }
51
+ const declaration = declarations[0];
52
+ const declarationSourceFile = declaration.getSourceFile();
53
+ const serviceFile = serviceSourceFile.getSourceFile();
54
+ if (declarationSourceFile === serviceFile) {
55
+ // Return type is defined in the same file as the hooks service
56
+ const exportedDeclarations = serviceFile.getExportedDeclarations().get(typeName);
57
+ if (!exportedDeclarations || exportedDeclarations.length === 0) {
58
+ throw new Error(`Return type "${typeName}" is defined in ${serviceFile.getFilePath()} but is not exported`);
59
+ }
60
+ const importPath = `./${path.relative(targetDirectory, serviceFile.getFilePath()).replace(/\.ts$/, "")}`;
61
+ return { name: typeName, importPath };
62
+ }
63
+ else {
64
+ // Return type is imported from another file
65
+ const importPath = `./${path.relative(targetDirectory, declarationSourceFile.getFilePath()).replace(/\.ts$/, "")}`;
66
+ return { name: typeName, importPath };
67
+ }
68
+ }
69
+ function unwrapPromiseType(type) {
70
+ if (type.getSymbol()?.getName() === "Promise") {
71
+ const typeArgs = type.getTypeArguments();
72
+ if (typeArgs.length > 0) {
73
+ return typeArgs[0];
74
+ }
75
+ }
76
+ return type;
77
+ }
78
+ function unwrapArrayType(type) {
79
+ if (type.isArray()) {
80
+ return type.getArrayElementTypeOrThrow();
81
+ }
82
+ throw new Error(`Return type must be an array`);
83
+ }
84
+ function findHooksService({ generatorOptions, metadata, targetDirectory, }) {
85
+ if (!generatorOptions.hooksService) {
86
+ return null;
87
+ }
88
+ let validateCreateInput = null;
89
+ let validateUpdateInput = null;
90
+ const imports = [];
91
+ const tsClass = (0, ts_morph_helper_1.morphTsClass)(metadata);
92
+ for (const decorator of tsClass.getDecorators()) {
93
+ if (decorator.getName() === "CrudGenerator") {
94
+ const decoratorArgs = decorator.getArguments();
95
+ if (decoratorArgs.length < 1) {
96
+ throw new Error(`CrudGenerator decorator has no arguments`);
97
+ }
98
+ const firstArg = decoratorArgs[0];
99
+ if (!ts_morph_1.Node.isObjectLiteralExpression(firstArg)) {
100
+ throw new Error("CrudGenerator decorator first argument is not an object literal");
101
+ }
102
+ const hooksServiceProp = firstArg.getProperty("hooksService");
103
+ if (!hooksServiceProp) {
104
+ throw new Error("hooksService property not found in CrudGenerator decorator");
105
+ }
106
+ if (!ts_morph_1.Node.isPropertyAssignment(hooksServiceProp)) {
107
+ throw new Error("hooksService property is not a property assignment");
108
+ }
109
+ const initializer = hooksServiceProp.getInitializer();
110
+ if (!initializer) {
111
+ throw new Error("hooksService initializer not found");
112
+ }
113
+ if (!ts_morph_1.Node.isIdentifier(initializer)) {
114
+ throw new Error("hooksService initializer is not an identifier");
115
+ }
116
+ const hooksServiceClassName = initializer.getText();
117
+ const { importPath } = (0, ts_morph_helper_1.findImportPath)(hooksServiceClassName, targetDirectory, metadata);
118
+ if (importPath) {
119
+ imports.push({ name: hooksServiceClassName, importPath });
120
+ }
121
+ const serviceClassRef = initializer.getSymbolOrThrow();
122
+ const serviceClassDeclaration = (serviceClassRef.getAliasedSymbol() ?? serviceClassRef).getDeclarations().find(ts_morph_1.Node.isClassDeclaration);
123
+ if (!serviceClassDeclaration) {
124
+ throw new Error("hooksService class declaration not found");
125
+ }
126
+ for (const method of serviceClassDeclaration.getMethods()) {
127
+ if (method.getName() == "validateCreateInput") {
128
+ validateCreateInput = {};
129
+ const unwrappedType = unwrapArrayType(unwrapPromiseType(method.getReturnType()));
130
+ const returnType = unwrappedType.getText(method, ts_morph_1.ts.TypeFormatFlags.None);
131
+ const returnTypeImport = findReturnTypeImport(unwrappedType, serviceClassDeclaration, targetDirectory);
132
+ if (returnTypeImport) {
133
+ imports.push(returnTypeImport);
134
+ }
135
+ const parameters = method.getParameters();
136
+ if (parameters.length >= 2) {
137
+ //has options
138
+ const options = parameters[1]
139
+ .getType()
140
+ .getProperties()
141
+ .map((prop) => prop.getName());
142
+ validateCreateInput = {
143
+ options,
144
+ returnType,
145
+ };
146
+ }
147
+ else {
148
+ validateCreateInput = { returnType };
149
+ }
150
+ }
151
+ else if (method.getName() == "validateUpdateInput") {
152
+ validateUpdateInput = {};
153
+ const unwrappedType = unwrapArrayType(unwrapPromiseType(method.getReturnType()));
154
+ const returnType = unwrappedType.getText(method, ts_morph_1.ts.TypeFormatFlags.None);
155
+ const returnTypeImport = findReturnTypeImport(unwrappedType, serviceClassDeclaration, targetDirectory);
156
+ if (returnTypeImport) {
157
+ imports.push(returnTypeImport);
158
+ }
159
+ const parameters = method.getParameters();
160
+ if (parameters.length >= 2) {
161
+ //has options
162
+ const options = parameters[1]
163
+ .getType()
164
+ .getProperties()
165
+ .map((prop) => prop.getName());
166
+ validateUpdateInput = {
167
+ options,
168
+ returnType,
169
+ };
170
+ }
171
+ else {
172
+ validateUpdateInput = { returnType };
173
+ }
174
+ }
175
+ }
176
+ return {
177
+ validateCreateInput,
178
+ validateUpdateInput,
179
+ imports,
180
+ className: hooksServiceClassName,
181
+ };
182
+ }
183
+ }
184
+ throw new Error("CrudGenerator decorator not found");
185
+ }
@@ -0,0 +1,5 @@
1
+ export type Imports = Array<{
2
+ name: string;
3
+ importPath: string;
4
+ }>;
5
+ export declare function generateImportsCode(imports: Imports): string;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateImportsCode = generateImportsCode;
4
+ // generate imports code and filter duplicates
5
+ function generateImportsCode(imports) {
6
+ const importsNameToPath = new Map(); // name -> importPath
7
+ const filteredImports = imports.filter((imp) => {
8
+ if (importsNameToPath.has(imp.name)) {
9
+ if (importsNameToPath.get(imp.name) !== imp.importPath) {
10
+ throw new Error(`Duplicate import name ${imp.name} with different importPaths: ${imp.importPath} vs ${importsNameToPath.get(imp.name)}`);
11
+ }
12
+ else {
13
+ // duplicate import, skip
14
+ return false;
15
+ }
16
+ }
17
+ importsNameToPath.set(imp.name, imp.importPath);
18
+ return true;
19
+ });
20
+ const importsPathToName = {};
21
+ for (const imp of filteredImports) {
22
+ if (!importsPathToName[imp.importPath]) {
23
+ importsPathToName[imp.importPath] = [];
24
+ }
25
+ importsPathToName[imp.importPath].push(imp.name);
26
+ }
27
+ let importsString = "";
28
+ for (const [importPath, importNames] of Object.entries(importsPathToName)) {
29
+ importsString += `import { ${importNames.sort().join(", ")} } from "${importPath}";\n`;
30
+ }
31
+ return importsString;
32
+ }
@@ -0,0 +1,18 @@
1
+ import type { EntityMetadata } from "@mikro-orm/postgresql";
2
+ import { ClassDeclaration } from "ts-morph";
3
+ export declare function morphTsClass(metadata: EntityMetadata<any>): ClassDeclaration;
4
+ export declare function morphTsProperty(name: string, metadata: EntityMetadata<any>): import("ts-morph").PropertyDeclaration;
5
+ export declare function findImportPath(importName: string, targetDirectory: string, metadata: EntityMetadata<any>): {
6
+ importPath: string;
7
+ exportedDeclaration: import("ts-morph").ExportedDeclarations;
8
+ } | {
9
+ importPath: null;
10
+ exportedDeclaration: undefined;
11
+ };
12
+ export declare function findEnumName(propertyName: string, metadata: EntityMetadata<any>): string;
13
+ export declare function findEnumImportPath(enumName: string, targetDirectory: string, metadata: EntityMetadata<any>): string;
14
+ export declare function findValidatorImportPath(validatorName: string, targetDirectory: string, metadata: EntityMetadata<any>): string;
15
+ export declare function findBlockName(propertyName: string, metadata: EntityMetadata<any>): string;
16
+ export declare function findBlockImportPath(blockName: string, targetDirectory: string, metadata: EntityMetadata<any>): string;
17
+ export declare function findInputClassImportPath(className: string, targetDirectory: string, metadata: EntityMetadata<any>): string;
18
+ export declare function getFieldDecoratorClassName(propertyName: string, metadata: EntityMetadata<any>): string | false;
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.morphTsClass = morphTsClass;
37
+ exports.morphTsProperty = morphTsProperty;
38
+ exports.findImportPath = findImportPath;
39
+ exports.findEnumName = findEnumName;
40
+ exports.findEnumImportPath = findEnumImportPath;
41
+ exports.findValidatorImportPath = findValidatorImportPath;
42
+ exports.findBlockName = findBlockName;
43
+ exports.findBlockImportPath = findBlockImportPath;
44
+ exports.findInputClassImportPath = findInputClassImportPath;
45
+ exports.getFieldDecoratorClassName = getFieldDecoratorClassName;
46
+ const path = __importStar(require("path"));
47
+ const ts_morph_1 = require("ts-morph");
48
+ /* eslint-disable @typescript-eslint/no-explicit-any */
49
+ const project = new ts_morph_1.Project({
50
+ tsConfigFilePath: "tsconfig.json",
51
+ skipAddingFilesFromTsConfig: true,
52
+ });
53
+ function morphTsSource(metadata) {
54
+ let tsSource = project.getSourceFile(metadata.path);
55
+ if (!tsSource) {
56
+ tsSource = project.addSourceFileAtPath(metadata.path);
57
+ }
58
+ return tsSource;
59
+ }
60
+ function morphTsClass(metadata) {
61
+ const tsSource = morphTsSource(metadata);
62
+ const tsClass = tsSource.getClass(metadata.className);
63
+ if (!tsClass) {
64
+ throw new Error(`Class ${metadata.className} not found in ${metadata.path}`);
65
+ }
66
+ return tsClass;
67
+ }
68
+ function morphTsProperty(name, metadata) {
69
+ let currentClass = morphTsClass(metadata);
70
+ while (currentClass) {
71
+ const prop = currentClass.getProperty(name);
72
+ if (prop) {
73
+ return prop;
74
+ }
75
+ currentClass = currentClass.getBaseClass();
76
+ }
77
+ throw new Error(`Property ${name} not found in ${metadata.className}`);
78
+ }
79
+ function findImportPath(importName, targetDirectory, metadata) {
80
+ const tsSource = morphTsSource(metadata);
81
+ for (const tsImport of tsSource.getImportDeclarations()) {
82
+ for (const namedImport of tsImport.getNamedImports()) {
83
+ if (namedImport.getAliasNode()?.getText() == importName) {
84
+ throw new Error("Aliased enum import is not supported");
85
+ }
86
+ if (namedImport.getNameNode().getText() == importName) {
87
+ const importPath = tsImport.getModuleSpecifierValue();
88
+ const importSource = tsImport.getModuleSpecifierSourceFile();
89
+ if (!importSource) {
90
+ throw new Error(`Can't resolve import ${importPath}`);
91
+ }
92
+ const exportedDeclarations = importSource.getExportedDeclarations().get(importName);
93
+ if (!exportedDeclarations) {
94
+ throw new Error(`Can't get exported declaration for ${importName}`);
95
+ }
96
+ const exportedDeclaration = exportedDeclarations[0];
97
+ if (importPath.startsWith("./") || importPath.startsWith("../")) {
98
+ const absolutePath = path.resolve(path.dirname(metadata.path), importPath);
99
+ let relativePath = path.relative(targetDirectory, absolutePath);
100
+ if (!relativePath.startsWith(".")) {
101
+ relativePath = `./${relativePath}`;
102
+ }
103
+ return {
104
+ importPath: relativePath,
105
+ exportedDeclaration,
106
+ };
107
+ }
108
+ else {
109
+ return { importPath, exportedDeclaration };
110
+ }
111
+ }
112
+ }
113
+ }
114
+ return {
115
+ importPath: null,
116
+ exportedDeclaration: undefined,
117
+ };
118
+ }
119
+ function findImportPathOrThrow(importName, targetDirectory, metadata) {
120
+ const ret = findImportPath(importName, targetDirectory, metadata);
121
+ if (!ret.importPath) {
122
+ throw new Error(`${importName} import not found in ${metadata.path}`);
123
+ }
124
+ return ret;
125
+ }
126
+ function findEnumName(propertyName, metadata) {
127
+ const tsProp = morphTsProperty(propertyName, metadata);
128
+ return tsProp
129
+ .getType()
130
+ .getText(tsProp)
131
+ .replace(/ ?\| ?undefined$/, "")
132
+ .replace(/\[\]$/, "");
133
+ }
134
+ function findEnumImportPath(enumName, targetDirectory, metadata) {
135
+ const tsSource = morphTsSource(metadata);
136
+ if (tsSource.getEnum(enumName)) {
137
+ //enum defined in same file as entity
138
+ if (!tsSource.getEnum(enumName)?.isExported()) {
139
+ throw new Error(`Enum ${enumName} is not exported in ${metadata.path}`);
140
+ }
141
+ return path.relative(targetDirectory, metadata.path).replace(/\.ts$/, "");
142
+ }
143
+ else {
144
+ //try to find import where enum is imported from
145
+ const { importPath } = findImportPathOrThrow(enumName, targetDirectory, metadata);
146
+ return importPath;
147
+ }
148
+ }
149
+ function findValidatorImportPath(validatorName, targetDirectory, metadata) {
150
+ const tsSource = morphTsSource(metadata);
151
+ //validator defined in same file as entity
152
+ if (tsSource.getVariableDeclaration(validatorName) || tsSource.getFunction(validatorName)) {
153
+ if (!(tsSource.getVariableDeclaration(validatorName)?.isExported() || tsSource.getFunction(validatorName)?.isExported())) {
154
+ throw new Error(`Validator ${validatorName} is not exported in ${metadata.path}`);
155
+ }
156
+ return path.relative(`${targetDirectory}/dto`, metadata.path).replace(/\.ts$/, "");
157
+ }
158
+ else {
159
+ const { importPath } = findImportPathOrThrow(validatorName, targetDirectory, metadata);
160
+ return importPath;
161
+ }
162
+ }
163
+ function findBlockName(propertyName, metadata) {
164
+ const tsProp = morphTsProperty(propertyName, metadata);
165
+ if (!tsProp) {
166
+ throw new Error("property not found");
167
+ }
168
+ const rootBlockDecorator = tsProp.getDecorators().find((i) => i.getName() == "RootBlock");
169
+ if (!rootBlockDecorator) {
170
+ throw new Error(`RootBlock decorator not found for property ${propertyName}`);
171
+ }
172
+ return rootBlockDecorator.getArguments()[0].getText();
173
+ }
174
+ function findBlockImportPath(blockName, targetDirectory, metadata) {
175
+ const tsSource = morphTsSource(metadata);
176
+ if (tsSource.getVariableDeclaration(blockName)) {
177
+ //block defined in same file as entity
178
+ if (!tsSource.getVariableDeclaration(blockName)?.isExported()) {
179
+ throw new Error(`Block ${blockName} is not exported in ${metadata.path}`);
180
+ }
181
+ return path.relative(targetDirectory, metadata.path).replace(/\.ts$/, "");
182
+ }
183
+ else {
184
+ //try to find import where block is imported from
185
+ const { importPath } = findImportPathOrThrow(blockName, targetDirectory, metadata);
186
+ return importPath;
187
+ }
188
+ }
189
+ function findInputClassImportPath(className, targetDirectory, metadata) {
190
+ const tsSource = morphTsSource(metadata);
191
+ let returnImportPath;
192
+ let classDeclaration;
193
+ if (tsSource.getClass(className)) {
194
+ //block defined in same file as entity
195
+ if (!tsSource.getClass(className)?.isExported()) {
196
+ throw new Error(`Class ${className} is not exported in ${metadata.path}`);
197
+ }
198
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
199
+ classDeclaration = tsSource.getClass(className);
200
+ returnImportPath = path.relative(targetDirectory, metadata.path).replace(/\.ts$/, "");
201
+ }
202
+ else {
203
+ //try to find import where block is imported from
204
+ const { importPath, exportedDeclaration } = findImportPathOrThrow(className, targetDirectory, metadata);
205
+ if (!(exportedDeclaration instanceof ts_morph_1.ClassDeclaration)) {
206
+ throw new Error(`Exported declaration for ${className} is not a class`);
207
+ }
208
+ classDeclaration = exportedDeclaration;
209
+ returnImportPath = importPath;
210
+ }
211
+ if (!classDeclaration.getDecorators().some((i) => i.getName() == "InputType")) {
212
+ throw new Error(`Exported declaration for ${className} is not decorated with @InputType`);
213
+ }
214
+ return returnImportPath;
215
+ }
216
+ function getFieldDecoratorClassName(propertyName, metadata) {
217
+ const definedDecorators = morphTsProperty(propertyName, metadata).getDecorators();
218
+ const fieldDecorator = definedDecorators.find((decorator) => decorator.getName() == "Field");
219
+ if (!fieldDecorator) {
220
+ return false;
221
+ }
222
+ const typeFnArg = fieldDecorator.getArguments()[0];
223
+ if (!typeFnArg) {
224
+ throw new Error(`${propertyName}: @Field is missing argument`);
225
+ }
226
+ if (typeFnArg.getKind() != ts_morph_1.SyntaxKind.ArrowFunction) {
227
+ throw new Error(`${propertyName}: @Field first argument must be an ArrowFunction`);
228
+ }
229
+ const typeReturningArrowFunction = typeFnArg;
230
+ const body = typeReturningArrowFunction.getBody();
231
+ if (body.getKind() != ts_morph_1.SyntaxKind.Identifier) {
232
+ throw new Error(`${propertyName}: @Field first argument must be an ArrowFunction returning an Identifier`);
233
+ }
234
+ const identifier = body;
235
+ const className = identifier.getText();
236
+ return className;
237
+ }
@@ -0,0 +1,3 @@
1
+ import ts from "typescript";
2
+ export declare function writeGeneratedFile(filePath: string, contents: string): Promise<void>;
3
+ export declare function removeUnusedImports(): ts.TransformerFactory<ts.SourceFile>;