@simplix-boot/cli 0.0.0-stage → 1.3.1

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 (55) hide show
  1. package/LICENSE +25 -0
  2. package/LICENSE_KO +28 -0
  3. package/README.ko.md +82 -0
  4. package/README.md +81 -2
  5. package/bin/simplix-boot.js +6 -0
  6. package/package.json +45 -4
  7. package/src/cli.js +103 -0
  8. package/src/commands/config.js +129 -0
  9. package/src/commands/generate.js +291 -0
  10. package/src/commands/generated.js +125 -0
  11. package/src/commands/init.js +41 -0
  12. package/src/commands/promote.js +172 -0
  13. package/src/commands/templates.js +100 -0
  14. package/src/commands/version.js +134 -0
  15. package/src/lib/analysis/fields.js +217 -0
  16. package/src/lib/analysis/imports.js +76 -0
  17. package/src/lib/analysis/structure.js +193 -0
  18. package/src/lib/analysis/types.js +94 -0
  19. package/src/lib/args.js +69 -0
  20. package/src/lib/comment-extractor.js +141 -0
  21. package/src/lib/config/fields.js +321 -0
  22. package/src/lib/config/parents.js +108 -0
  23. package/src/lib/config/paths.js +156 -0
  24. package/src/lib/config/yml.js +61 -0
  25. package/src/lib/console.js +83 -0
  26. package/src/lib/controller-name.js +33 -0
  27. package/src/lib/entity-analyzer.js +49 -0
  28. package/src/lib/entity-type-resolver.js +80 -0
  29. package/src/lib/entity-type.js +35 -0
  30. package/src/lib/errors.js +17 -0
  31. package/src/lib/export-config.js +74 -0
  32. package/src/lib/file-utils.js +77 -0
  33. package/src/lib/generate/file-plan.js +155 -0
  34. package/src/lib/generate/search-fields.js +111 -0
  35. package/src/lib/generate/settings.js +111 -0
  36. package/src/lib/generate/support-classes.js +47 -0
  37. package/src/lib/generate/template-vars.js +183 -0
  38. package/src/lib/git-utils.js +18 -0
  39. package/src/lib/name-field.js +42 -0
  40. package/src/lib/project.js +121 -0
  41. package/src/lib/promote-files.js +132 -0
  42. package/src/lib/rendered-output.js +13 -0
  43. package/src/lib/search-operators.js +87 -0
  44. package/src/lib/templates.js +50 -0
  45. package/src/lib/tracked-render.js +200 -0
  46. package/src/lib/version-check.js +195 -0
  47. package/src/lib/version-utils.js +97 -0
  48. package/templates/controller/rest/EntityRestController.java.template +517 -0
  49. package/templates/controller/web/EntityWebController.java.template +211 -0
  50. package/templates/dto/EntityDTOs.java.template +981 -0
  51. package/templates/repository/EntityRepository.java.template +78 -0
  52. package/templates/service/EntityService.java.template +790 -0
  53. package/templates/service/EntityTreeService.java.template +352 -0
  54. package/templates/test/EntityServiceTest.java.template +937 -0
  55. package/templates/test/EntityTreeServiceTest.java.template +842 -0
@@ -0,0 +1,111 @@
1
+ import { symbols } from '../console.js';
2
+ import { defaultSearchOperators, isSortableSearchType } from '../search-operators.js';
3
+
4
+ /**
5
+ * The sortable flag a search field is generated with: the yml's, unless the field's type cannot
6
+ * be a sort key. A yml that asks for it anyway is generated without it and the operator is told
7
+ * which line to fix, so an entity written before the rule still generates.
8
+ *
9
+ * @param {object} context
10
+ * @param {string} context.ymlName the entity yml's name
11
+ * @param {(message: string) => void} context.log where the warning goes
12
+ * @param {string} fieldKey the yml key of the field, `parent.child` for an embedded id part
13
+ * @param {string} type the Java type of the field
14
+ * @param {boolean|undefined} sortable what the yml declares
15
+ * @returns {boolean} whether the generated `@SearchableField` carries `sortable = true`
16
+ */
17
+ export function resolveSearchSortable({ ymlName, log }, fieldKey, type, sortable) {
18
+ if (!sortable) {
19
+ return false;
20
+ }
21
+
22
+ if (isSortableSearchType(type)) {
23
+ return true;
24
+ }
25
+
26
+ log(
27
+ `${symbols.warning} ${ymlName}.${fieldKey} is ${type}: sortable dropped, ` +
28
+ `PostgreSQL has no max(boolean) so sorting by it answers 500. ` +
29
+ `Set sortable: false in .simplix/entity/${ymlName}.yml`
30
+ );
31
+ return false;
32
+ }
33
+
34
+ /**
35
+ * Builds the search fields of the generated SearchDTO: the parts of an embedded id, and every
36
+ * entity field the yml gives search operators.
37
+ *
38
+ * @param {object} input
39
+ * @param {string} input.ymlName the entity yml's name
40
+ * @param {object} [input.entityConfig] the parsed entity yml
41
+ * @param {(message: string) => void} input.log where warnings go
42
+ * @param {object[]} input.fields the analyzed entity fields
43
+ * @param {object[]} [input.embeddedIdFields] the fields of the embedded id class
44
+ * @param {string[]} input.embeddedIdPropertyNames the names of those fields
45
+ * @param {string} [input.embeddedIdField] the entity field holding the embedded id
46
+ * @param {boolean} input.hasEmbeddedId whether the entity has an embedded id
47
+ * @returns {{ embeddedIdSearchFields: object[], entitySearchFields: object[] }}
48
+ */
49
+ export function prepareSearchFields({
50
+ ymlName,
51
+ entityConfig,
52
+ log,
53
+ fields,
54
+ embeddedIdFields,
55
+ embeddedIdPropertyNames,
56
+ embeddedIdField,
57
+ hasEmbeddedId,
58
+ }) {
59
+ const ymlFields = entityConfig?.fields || {};
60
+ const context = { ymlName, log };
61
+
62
+ let embeddedIdSearchFields = [];
63
+ if (hasEmbeddedId && Array.isArray(embeddedIdFields)) {
64
+ embeddedIdSearchFields = embeddedIdFields.map(field => {
65
+ const ymlKey = `${embeddedIdField}.${field.name}`;
66
+ const ymlFieldConfig = ymlFields[ymlKey] || {};
67
+ const searchOperators = ymlFieldConfig.searchOperators || defaultSearchOperators(field.type);
68
+
69
+ return {
70
+ name: field.name,
71
+ type: field.type,
72
+ comment: field.comment || '',
73
+ parentField: embeddedIdField,
74
+ entityField: `${embeddedIdField}.${field.name}`,
75
+ searchOperators,
76
+ sortable: resolveSearchSortable(context, ymlKey, field.type, ymlFieldConfig.sortable),
77
+ operators: searchOperators
78
+ .map(op =>
79
+ op
80
+ .toUpperCase()
81
+ .replace(/([A-Z])/g, '_$1')
82
+ .replace(/^_/, '')
83
+ )
84
+ .join(', '),
85
+ };
86
+ });
87
+ }
88
+
89
+ const entitySearchFields = (Array.isArray(fields) ? fields : [])
90
+ .filter(field => {
91
+ if (field.name === (entityConfig?.idField || 'id')) return false;
92
+ if (field.name === embeddedIdField) return false;
93
+ if (Array.isArray(embeddedIdPropertyNames) && embeddedIdPropertyNames.includes(field.name)) return false;
94
+
95
+ const ymlFieldConfig = ymlFields[field.name];
96
+ return ymlFieldConfig && ymlFieldConfig.searchOperators && ymlFieldConfig.searchOperators.length > 0;
97
+ })
98
+ .map(field => {
99
+ const ymlFieldConfig = ymlFields[field.name];
100
+ return {
101
+ name: field.name,
102
+ type: field.type,
103
+ comment: field.comment || '',
104
+ searchOperators: ymlFieldConfig.searchOperators,
105
+ sortable: resolveSearchSortable(context, field.name, field.type, ymlFieldConfig.sortable),
106
+ entityField: field.name === ymlFieldConfig.idField ? undefined : field.name,
107
+ };
108
+ });
109
+
110
+ return { embeddedIdSearchFields, entitySearchFields };
111
+ }
@@ -0,0 +1,111 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { symbols } from '../console.js';
4
+ import { CliError } from '../errors.js';
5
+ import { CONFIG_FILE_NAME } from '../project.js';
6
+
7
+ /**
8
+ * The directory entity sources are scanned under: `entity.scanPath`, the older
9
+ * `entity.basePath`, or the Maven source root.
10
+ */
11
+ export function resolveEntityScanPath(config) {
12
+ return config.entity?.scanPath || config.entity?.basePath || 'src/main/java';
13
+ }
14
+
15
+ /**
16
+ * Derives a package from a path that runs through a `/java/` source root.
17
+ *
18
+ * @param {string} baseEntityPath a path such as `modules/domain/src/main/java/com/example/entity`
19
+ * @returns {string} the package below the source root, or an empty string
20
+ */
21
+ export function deriveEntityPackage(baseEntityPath) {
22
+ if (!baseEntityPath) return '';
23
+ const javaIndex = baseEntityPath.indexOf('/java/');
24
+ if (javaIndex === -1) return '';
25
+ return baseEntityPath.substring(javaIndex + 6).replace(/\//g, '.');
26
+ }
27
+
28
+ /**
29
+ * Derives the repository package from an entity package by replacing its last `.entity` segment
30
+ * with `.repository`.
31
+ *
32
+ * @param {string} entityPackage the entity's package
33
+ * @returns {string} the repository package, or an empty string when the package has no such segment
34
+ */
35
+ export function deriveRepositoryPackage(entityPackage) {
36
+ if (!entityPackage) return '';
37
+ const lastEntityIndex = entityPackage.lastIndexOf('.entity');
38
+ if (lastEntityIndex === -1) return '';
39
+ return entityPackage.substring(0, lastEntityIndex) + '.repository';
40
+ }
41
+
42
+ function validate(config, root, log) {
43
+ const hasNewStructure = config.entity && config.target;
44
+
45
+ if (hasNewStructure) {
46
+ if (!config.target?.generatedBasePath && !config.target?.basePath) {
47
+ throw new CliError('Missing required configuration field: target.generatedBasePath');
48
+ }
49
+
50
+ if (!config.target?.basePackage) {
51
+ throw new CliError('Missing required configuration field: target.basePackage');
52
+ }
53
+
54
+ const entityScanPath = resolveEntityScanPath(config);
55
+ if (!fs.existsSync(path.join(root, entityScanPath))) {
56
+ log(`${symbols.warning} Entity scan path does not exist: ${entityScanPath}`);
57
+ }
58
+
59
+ return;
60
+ }
61
+
62
+ const missingFields = ['baseTargetPath', 'basePackage'].filter(field => !config[field]);
63
+
64
+ if (missingFields.length > 0) {
65
+ throw new CliError(`Missing required configuration fields: ${missingFields.join(', ')}`);
66
+ }
67
+
68
+ if (config.baseEntityPath && !fs.existsSync(path.join(root, config.baseEntityPath))) {
69
+ log(`${symbols.warning} Entity path does not exist: ${config.baseEntityPath}`);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Reads what `generate` needs out of the project configuration.
75
+ *
76
+ * @param {object} config the parsed `.simplix/generator-simplix.json`
77
+ * @param {string} root the project root
78
+ * @param {(message: string) => void} log where warnings go
79
+ * @returns {object} the resolved settings
80
+ * @throws {CliError} when a required field is missing
81
+ */
82
+ export function resolveGenerateSettings(config, root, log) {
83
+ try {
84
+ validate(config, root, log);
85
+ } catch (error) {
86
+ if (!(error instanceof CliError)) throw error;
87
+ throw new CliError(`Failed to read ${CONFIG_FILE_NAME}: ${error.message}`);
88
+ }
89
+
90
+ const baseEntityPath = resolveEntityScanPath(config);
91
+ const baseTargetPath = config.target?.generatedBasePath || config.target?.basePath;
92
+ const targetPaths = {};
93
+
94
+ Object.entries(config.target?.targetPath || {}).forEach(([key, value]) => {
95
+ targetPaths[key] = value;
96
+ });
97
+
98
+ return {
99
+ baseEntityPath,
100
+ baseTargetPath,
101
+ testBasePath:
102
+ config.target?.testGeneratedBasePath || config.target?.testBasePath || baseTargetPath?.replace('/main/', '/test/'),
103
+ basePackage: config.target?.basePackage || config.basePackage,
104
+ entityBasePackage: config.entity?.basePackage || deriveEntityPackage(baseEntityPath),
105
+ repositoryDeriveFromEntity: config.repository?.deriveFromEntity === true,
106
+ repositoryBasePackage: config.repository?.basePackage,
107
+ dtoExcludeFields: config.dto?.excludeFields || [],
108
+ templateMapping: config.template || {},
109
+ targetPaths,
110
+ };
111
+ }
@@ -0,0 +1,47 @@
1
+ import { CliError } from '../errors.js';
2
+ import { CONFIG_FILE_NAME, SIMPLIX_DIR } from '../project.js';
3
+
4
+ const JAVA_CLASS_NAME = /^(?:[a-z_][A-Za-z0-9_]*\.)+[A-Z][A-Za-z0-9_]*$/;
5
+
6
+ /**
7
+ * The classes of the application that generated code calls, as the project configuration names
8
+ * them under `supportClasses`.
9
+ *
10
+ * <p>Some generated members need a class the framework does not provide and every application
11
+ * writes for itself, such as the DTOs a list's figures are answered with. A template asks for
12
+ * one by key: `find` for a member that is generated only when the class is configured, and
13
+ * `require` for a member an entity yml asks for outright.
14
+ *
15
+ * @param {Record<string, string>} [configured] the `supportClasses` object of the configuration
16
+ * @param {string} ymlName the entity yml being generated, named in a refusal
17
+ * @returns {{ find: (key: string) => ({ fqn: string, name: string } | undefined),
18
+ * require: (key: string, usedBy: string) => { fqn: string, name: string } }}
19
+ */
20
+ export function createSupportClasses(configured, ymlName) {
21
+ const find = key => {
22
+ const fqn = configured?.[key];
23
+ if (fqn === undefined || fqn === null || fqn === '') return undefined;
24
+
25
+ if (typeof fqn !== 'string' || !JAVA_CLASS_NAME.test(fqn)) {
26
+ throw new CliError(
27
+ `supportClasses.${key} in ${CONFIG_FILE_NAME} must be a fully qualified Java class name, got: ${JSON.stringify(fqn)}`
28
+ );
29
+ }
30
+
31
+ return { fqn, name: fqn.slice(fqn.lastIndexOf('.') + 1) };
32
+ };
33
+
34
+ return {
35
+ find,
36
+ require(key, usedBy) {
37
+ const found = find(key);
38
+ if (found === undefined) {
39
+ throw new CliError(
40
+ `${ymlName}.yml uses ${usedBy}, which needs supportClasses.${key} in ${SIMPLIX_DIR}/${CONFIG_FILE_NAME}`
41
+ );
42
+ }
43
+
44
+ return found;
45
+ },
46
+ };
47
+ }
@@ -0,0 +1,183 @@
1
+ import lodash from 'lodash';
2
+
3
+ /** Upper-cases the first character of a string; an empty or missing string gives an empty string. */
4
+ export function capitalizeFirstLetter(string) {
5
+ if (string) {
6
+ return string.charAt(0).toUpperCase() + string.slice(1);
7
+ }
8
+
9
+ return '';
10
+ }
11
+
12
+ /**
13
+ * Turns the import of a referenced entity into the import of the service generated for it, by
14
+ * moving the entity's domain package to the web layer.
15
+ *
16
+ * @param {string} entityImport the fully qualified entity class
17
+ * @param {string} entityType the entity's simple class name
18
+ * @returns {string} the fully qualified service class
19
+ */
20
+ export function transformImportForService(entityImport, entityType) {
21
+ const patterns = [
22
+ { from: /\.domain\.entities\./, to: '.web.' },
23
+ { from: /\.domain\.[^.]+\.entity\./, to: '.web.' },
24
+ { from: /\.domain\./, to: '.web.' },
25
+ { from: /\.entities\./, to: '.web.' },
26
+ { from: /\.entity\./, to: '.web.' },
27
+ ];
28
+
29
+ let servicePath = entityImport;
30
+ for (const pattern of patterns) {
31
+ if (pattern.from.test(servicePath)) {
32
+ servicePath = servicePath.replace(pattern.from, pattern.to);
33
+ break;
34
+ }
35
+ }
36
+
37
+ if (!servicePath.endsWith('Service')) {
38
+ servicePath = servicePath.replace(new RegExp(`\\.${entityType}$`), `.service.${entityType}Service`);
39
+ }
40
+
41
+ return servicePath;
42
+ }
43
+
44
+ /** The fields whose name marks the position of a record in an ordered list. */
45
+ const ORDER_FIELD_NAMES = [
46
+ 'displayOrder',
47
+ 'itemOrder',
48
+ 'sortOrder',
49
+ 'order',
50
+ 'priority',
51
+ 'listOrder',
52
+ 'menuOrder',
53
+ 'displaySeq',
54
+ 'sortIndex',
55
+ ];
56
+
57
+ /** The first field an ordered list is ordered by, or undefined. */
58
+ export function findOrderField(fields) {
59
+ return fields.find(field => ORDER_FIELD_NAMES.includes(field.name));
60
+ }
61
+
62
+ function propertyType(embeddedIdFields, propertyName) {
63
+ if (!Array.isArray(embeddedIdFields)) {
64
+ return 'String';
65
+ }
66
+
67
+ const field = embeddedIdFields.find(f => f.name === propertyName);
68
+
69
+ return field ? field.type : 'String';
70
+ }
71
+
72
+ function neededImports(embeddedIdFields) {
73
+ const imports = [];
74
+ if (Array.isArray(embeddedIdFields)) {
75
+ embeddedIdFields.forEach(field => {
76
+ if (field.type === 'LocalDateTime') {
77
+ imports.push('java.time.LocalDateTime');
78
+ } else if (field.type === 'UUID') {
79
+ imports.push('java.util.UUID');
80
+ }
81
+ });
82
+ }
83
+
84
+ return [...new Set(imports)];
85
+ }
86
+
87
+ /** The moment of generation as an ISO timestamp in Korea Standard Time. */
88
+ function generatedAt() {
89
+ const shifted = new Date(Date.now() + 9 * 60 * 60 * 1000);
90
+ return shifted.toISOString().replace('Z', '+09:00');
91
+ }
92
+
93
+ /**
94
+ * Builds the variables every template is rendered with.
95
+ *
96
+ * @param {object} input
97
+ * @param {object} input.props the names, packages and paths resolved for the entity
98
+ * @param {object} [input.entityConfig] the parsed entity yml
99
+ * @param {string} input.entityComment the entity's table comment
100
+ * @param {object} input.analysis what the entity analyzer read from the source
101
+ * @param {object[]} input.fields the entity fields, with service imports resolved
102
+ * @param {string} input.controllerName the REST controller's class name
103
+ * @param {string[]} input.dtoExcludeFields the fields every DTO leaves out
104
+ * @param {object} input.searchFields the embedded id and entity search fields
105
+ * @param {boolean} input.hasTreeEntity whether the entity implements `TreeEntity`
106
+ * @param {object} [input.treeEntityInterface] that interface, as analyzed
107
+ * @param {object} input.supportClasses the application classes generated code may call
108
+ * @returns {object} the template variables
109
+ */
110
+ export function buildTemplateVars({
111
+ props,
112
+ entityConfig,
113
+ entityComment,
114
+ analysis,
115
+ fields,
116
+ controllerName,
117
+ dtoExcludeFields,
118
+ searchFields,
119
+ hasTreeEntity,
120
+ treeEntityInterface,
121
+ supportClasses,
122
+ }) {
123
+ const { idType, embeddedIdField, embeddedIdFields } = analysis;
124
+ const hasEmbeddedId = Boolean(embeddedIdField);
125
+ const embeddedIdPropertyNames =
126
+ hasEmbeddedId && embeddedIdFields && embeddedIdFields.length > 0 ? embeddedIdFields.map(field => field.name) : [];
127
+ const otherEntityField = fields.find(f => !f.id && f.name !== embeddedIdField)?.name || 'someField';
128
+ const orderField = findOrderField(fields);
129
+
130
+ return {
131
+ ...props,
132
+ entityComment,
133
+ fields,
134
+ idType,
135
+ entityFields: fields,
136
+ entityNameLowerFirst: props.entityName.charAt(0).toLowerCase() + props.entityName.slice(1),
137
+ idFieldName: entityConfig?.idField || 'id',
138
+ controllerName,
139
+ classPrefixLowerFirst: props.classPrefix.charAt(0).toLowerCase() + props.classPrefix.slice(1),
140
+ capitalizeFirstLetter,
141
+
142
+ hasEmbeddedId,
143
+ embeddedIdField,
144
+ embeddedIdType: hasEmbeddedId ? idType : null,
145
+ embeddedIdPropertyNames,
146
+ embeddedIdPropertyName1: embeddedIdPropertyNames[0] || 'propertyName1',
147
+ embeddedIdPropertyName2: embeddedIdPropertyNames[1] || 'propertyName2',
148
+ otherEntityField,
149
+ embeddedIdFields,
150
+
151
+ embeddedIdSearchFields: searchFields.embeddedIdSearchFields,
152
+ entitySearchFields: searchFields.entitySearchFields,
153
+
154
+ embeddedFieldCapitalized: embeddedIdField
155
+ ? embeddedIdField + capitalizeFirstLetter(embeddedIdPropertyNames[0] || 'propertyName1')
156
+ : '',
157
+ embeddedField2Capitalized: embeddedIdField
158
+ ? embeddedIdField + capitalizeFirstLetter(embeddedIdPropertyNames[1] || 'propertyName2')
159
+ : '',
160
+ otherFieldCapitalized: capitalizeFirstLetter(otherEntityField),
161
+ propType1: propertyType(embeddedIdFields, embeddedIdPropertyNames[0]),
162
+ propType2: propertyType(embeddedIdFields, embeddedIdPropertyNames[1]),
163
+ importsArray: neededImports(embeddedIdFields),
164
+
165
+ ymlConfig: {
166
+ ...entityConfig,
167
+ thymeleafBaseDir: entityConfig?.thymeleafBaseDir || '',
168
+ },
169
+
170
+ dtoExcludeFields,
171
+
172
+ hasOrderField: Boolean(orderField),
173
+ orderField,
174
+
175
+ hasTreeEntity,
176
+ treeEntityInterface,
177
+
178
+ supportClasses,
179
+
180
+ _: lodash,
181
+ generatedAt: generatedAt(),
182
+ };
183
+ }
@@ -0,0 +1,18 @@
1
+ import { execFileSync } from 'node:child_process';
2
+
3
+ /**
4
+ * Reads one value of the git configuration in effect for a directory.
5
+ *
6
+ * @param {string} key the configuration key, such as `user.name`
7
+ * @param {string} cwd the directory to read the configuration for
8
+ * @returns {string | undefined} the value, or undefined when git has none or is not installed
9
+ */
10
+ export function getGitConfig(key, cwd) {
11
+ try {
12
+ return execFileSync('git', ['config', key], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
13
+ } catch (error) {
14
+ // git exits 1 for an unset key, and is absent on a machine that never installed it.
15
+ if (error.status === 1 || error.code === 'ENOENT') return undefined;
16
+ throw error;
17
+ }
18
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Finds the field an entity's records are named by.
3
+ *
4
+ * <p>The field the entity marks `@NameField` wins. Otherwise the first String field among
5
+ * `name`, `title`, `displayName`, `description` and `code`, then the first String field whose
6
+ * name contains "name", then the first String field that is not the id, then the id itself.
7
+ *
8
+ * @param {object[]} fields the analyzed entity fields
9
+ * @param {string} idFieldName the id field
10
+ * @returns {string} the field name
11
+ */
12
+ export function findNameField(fields, idFieldName) {
13
+ if (!Array.isArray(fields)) {
14
+ return idFieldName;
15
+ }
16
+
17
+ const declared = fields.find(f => f.isNameField);
18
+ if (declared) {
19
+ return declared.name;
20
+ }
21
+
22
+ const nameFieldCandidates = ['name', 'title', 'displayName', 'description', 'code'];
23
+
24
+ for (const candidate of nameFieldCandidates) {
25
+ const field = fields.find(f => f.name === candidate && f.type === 'String');
26
+ if (field) {
27
+ return field.name;
28
+ }
29
+ }
30
+
31
+ const nameContainingField = fields.find(f => f.name.toLowerCase().includes('name') && f.type === 'String');
32
+ if (nameContainingField) {
33
+ return nameContainingField.name;
34
+ }
35
+
36
+ const firstStringField = fields.find(f => f.type === 'String' && f.name !== idFieldName);
37
+ if (firstStringField) {
38
+ return firstStringField.name;
39
+ }
40
+
41
+ return idFieldName;
42
+ }
@@ -0,0 +1,121 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import yaml from 'js-yaml';
4
+ import { CliError } from './errors.js';
5
+
6
+ /** The folder a project keeps its generator configuration, entity ymls and templates in. */
7
+ export const SIMPLIX_DIR = '.simplix';
8
+
9
+ /** The project configuration file, inside {@link SIMPLIX_DIR}. */
10
+ export const CONFIG_FILE_NAME = 'generator-simplix.json';
11
+
12
+ /**
13
+ * The nearest directory at or above `start` that holds a `.simplix` folder.
14
+ *
15
+ * @param {string} [start] where to look from
16
+ * @returns {string | undefined} the project root, or undefined outside a project
17
+ */
18
+ export function findProjectRoot(start = process.cwd()) {
19
+ let current = path.resolve(start);
20
+
21
+ for (;;) {
22
+ const candidate = path.join(current, SIMPLIX_DIR);
23
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) return current;
24
+ const parent = path.dirname(current);
25
+ if (parent === current) return undefined;
26
+ current = parent;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * The project root, for a command that cannot run outside a project.
32
+ *
33
+ * @param {string} [start] where to look from
34
+ * @returns {string}
35
+ * @throws {CliError} when no `.simplix` folder is found
36
+ */
37
+ export function requireProjectRoot(start = process.cwd()) {
38
+ const root = findProjectRoot(start);
39
+ if (root === undefined) {
40
+ throw new CliError('The .simplix directory is missing. Run "simplix-boot init" in the project root first.');
41
+ }
42
+
43
+ return root;
44
+ }
45
+
46
+ /** Where the project configuration file lives under a project root. */
47
+ export function configPathOf(root) {
48
+ return path.join(root, SIMPLIX_DIR, CONFIG_FILE_NAME);
49
+ }
50
+
51
+ /** Where an entity's yml lives under a project root. */
52
+ export function entityConfigPathOf(root, entityName) {
53
+ return path.join(root, SIMPLIX_DIR, 'entity', `${entityName}.yml`);
54
+ }
55
+
56
+ /**
57
+ * Reads and parses the project configuration.
58
+ *
59
+ * @param {string} root the project root
60
+ * @returns {object | undefined} the configuration, or undefined when the file does not exist
61
+ * @throws {CliError} when the file is not valid JSON
62
+ */
63
+ export function readProjectConfig(root) {
64
+ const configPath = configPathOf(root);
65
+ if (!fs.existsSync(configPath)) return undefined;
66
+
67
+ try {
68
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
69
+ } catch (error) {
70
+ if (!(error instanceof SyntaxError)) throw error;
71
+ throw new CliError(`Failed to parse ${CONFIG_FILE_NAME}: ${error.message}`);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Reads the project configuration, for a command that cannot run without it.
77
+ *
78
+ * @param {string} root the project root
79
+ * @returns {object}
80
+ * @throws {CliError} when the file is missing or not valid JSON
81
+ */
82
+ export function requireProjectConfig(root) {
83
+ const config = readProjectConfig(root);
84
+ if (config === undefined) {
85
+ throw new CliError(`${CONFIG_FILE_NAME} not found. Run "simplix-boot init" first and create the configuration file.`);
86
+ }
87
+
88
+ return config;
89
+ }
90
+
91
+ /**
92
+ * Reads and parses an entity's yml.
93
+ *
94
+ * @param {string} root the project root
95
+ * @param {string} entityName the yml's name
96
+ * @returns {object | undefined} the parsed yml, or undefined when the file does not exist
97
+ * @throws {CliError} when the file is not valid YAML
98
+ */
99
+ export function readEntityConfig(root, entityName) {
100
+ const ymlPath = entityConfigPathOf(root, entityName);
101
+ if (!fs.existsSync(ymlPath)) return undefined;
102
+
103
+ try {
104
+ return yaml.load(fs.readFileSync(ymlPath, 'utf8'));
105
+ } catch (error) {
106
+ if (!(error instanceof yaml.YAMLException)) throw error;
107
+ throw new CliError(`Failed to read ${entityName}.yml: ${error.message}`);
108
+ }
109
+ }
110
+
111
+ /** The names of the entity ymls of a project, sorted. */
112
+ export function listEntityNames(root) {
113
+ const entityDir = path.join(root, SIMPLIX_DIR, 'entity');
114
+ if (!fs.existsSync(entityDir)) return [];
115
+
116
+ return fs
117
+ .readdirSync(entityDir)
118
+ .filter(name => name.endsWith('.yml'))
119
+ .map(name => name.slice(0, -4))
120
+ .sort();
121
+ }