@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
package/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ SimpleCORE License 1.0 (SCL-1.0)
2
+
3
+ Copyright (c) 2025 SimpleCORE
4
+
5
+ Permission is hereby granted, free of charge, to any individual or organization (the “Licensee”) to use, modify, and integrate this software (the “Software”) into their own internal or commercial products, subject to the following terms:
6
+
7
+ 1. **Internal and Product Use Permitted**
8
+ The Licensee may use and modify the Software internally, including incorporation into products that are developed, marketed, and sold by the Licensee. This includes the right to compile, bundle, or statically link the Software for use within their own distributed applications.
9
+
10
+ 2. **Commercial Redistribution Requires Permission**
11
+ The Licensee may **not** sell, license, lease, or otherwise redistribute this Software, in source or binary form, to third parties — whether standalone or as part of a product — without prior **written consent** from SimpleCORE.
12
+
13
+ 3. **Third-party Distribution Requires Permission**
14
+ The Licensee may **not** distribute the Software or derivative works to any third party in any form (source, binary, object code, container image, etc.) without prior **written consent** from SimpleCORE.
15
+
16
+ 4. **No SaaS / Hosted Service Offering Without Permission**
17
+ The Licensee may **not** use the Software to provide a hosted service (e.g., SaaS, PaaS, or API-based access) to third parties unless a separate commercial license is obtained from SimpleCORE.
18
+
19
+ 5. **Open Source Use Exception (Optional)**
20
+ Non-commercial open source use (e.g., academic research, nonprofit projects) is permitted, subject to compliance with this License, and with clear attribution to SimpleCORE.
21
+
22
+ 6. **No Warranty**
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY...
24
+
25
+ For licensing inquiries, contact: license@simplecore.kr
package/LICENSE_KO ADDED
@@ -0,0 +1,28 @@
1
+ SimpleCORE 라이선스 1.0 (SCL-1.0)
2
+ 한글 번역 — 참고용
3
+
4
+ 저작권 ⓒ 2025 SimpleCORE
5
+
6
+ 본 소프트웨어(이하 “소프트웨어”)는 다음 조건에 따라 개인 또는 조직(이하 “라이선스 사용자”)이 자유롭게 사용, 수정, 통합할 수 있습니다.
7
+
8
+ 1. **내부 사용 및 제품 통합 허용**
9
+ 라이선스 사용자는 소프트웨어를 자유롭게 사용하고 수정하여 자체 개발하는 제품에 통합할 수 있습니다. 이에는 해당 제품을 시장에 출시하거나 상업적으로 판매하는 경우도 포함됩니다. 단, 제3자 제공은 별도 조항에 따릅니다.
10
+
11
+ 2. **상업적 재배포 금지 (허가 필요)**
12
+ 라이선스 사용자는 본 소프트웨어를 단독 혹은 제품 일부로서 **판매, 라이선스, 임대, 패키징 등 상업적 목적으로 제3자에게 제공할 수 없습니다**. 이러한 사용을 원할 경우, **SimpleCORE의 서면 허가**가 필요합니다.
13
+
14
+ 3. **제3자 제공 금지 (허가 필요)**
15
+ 소프트웨어 혹은 파생물(수정본)을 제3자에게 배포하거나 공개할 수 없습니다. 여기에는 소스코드, 바이너리, 패키지, 컨테이너 이미지 등 모든 형태가 포함되며, **사전 서면 허가** 없이는 허용되지 않습니다.
16
+
17
+ 4. **SaaS/호스팅 서비스 제공 금지 (허가 필요)**
18
+ 소프트웨어를 이용한 SaaS, API 서비스, 클라우드 기반 제공 형태로 제3자에게 서비스를 제공할 수 없습니다. 이러한 사용을 원할 경우 **별도의 상용 라이선스를 SimpleCORE로부터 취득해야 합니다**.
19
+
20
+ 5. **비영리 목적의 오픈소스 사용 예외 (선택 사항)**
21
+ 학술 연구나 비영리 프로젝트에서 소프트웨어를 사용하는 경우, 본 라이선스를 준수하고 SimpleCORE를 명시하는 조건 하에 사용이 허용될 수 있습니다.
22
+
23
+ 6. **보증 없음**
24
+ 본 소프트웨어는 “있는 그대로” 제공되며, 특정 목적에의 적합성, 상품성, 권리 비침해성 등에 대한 **명시적 또는 묵시적 보증을 하지 않습니다**. 어떠한 손해에 대해서도 SimpleCORE는 책임을 지지 않습니다.
25
+
26
+ 라이선스 관련 문의: license@simplecore.kr
27
+
28
+ ※ 본 문서는 원문의 이해를 돕기 위한 비공식 번역이며, 법적 효력은 원문(SCL-1.0 영문 라이선스)에 따릅니다.
package/README.ko.md ADDED
@@ -0,0 +1,82 @@
1
+ [English](./README.md) | **한국어**
2
+
3
+ # SimpliX CLI
4
+
5
+ `simplix-boot`는 JPA 엔티티를 읽어 그 엔티티를 SimpliX로 제공하는 서비스, REST 컨트롤러, DTO, 테스트를 생성합니다. 필드별 동작은 yml 파일에 한 번만 적으면 되고, 이후 템플릿이 바뀌어도 생성된 코드와 직접 고친 내용을 함께 유지합니다.
6
+
7
+ ![엔티티는 config, generate, promote를 거쳐 모듈 소스가 됩니다. 개발자는 엔티티 yml을 편집하고, 템플릿이 코드의 모양을 정하며, generated가 모듈로 옮긴 파일과 템플릿의 일치 여부를 보고합니다.](../docs/assets/figures/cli-readme-pipeline.ko.svg)
8
+
9
+ ## 언제 사용하나
10
+
11
+ - 엔티티를 추가하고, 프로젝트의 다른 SimpliX API와 같은 형태의 CRUD API가 필요할 때
12
+ - 필드를 바꾸고 DTO, 검색 조건, 테스트에 그 변경을 반영해야 할 때
13
+ - 생성된 클래스를 직접 고친 내용을 다음 템플릿 변경 이후에도 유지해야 할 때
14
+
15
+ 엔티티 하나에 대응하지 않는 화면(대시보드, 여러 집계를 합친 보고서)은 직접 작성합니다. CLI가 생성의 근거로 삼을 엔티티가 없기 때문입니다.
16
+
17
+ ## 요구 사항
18
+
19
+ - Node.js 20 이상
20
+ - SimpliX에 의존하는 Gradle 또는 Maven 프로젝트
21
+ - 프로젝트의 SimpliX와 같은 릴리스 라인의 CLI
22
+
23
+ | 프로젝트 | SimpliX 라인 | 설치 |
24
+ |---|---|---|
25
+ | Spring Boot 4 | 2.x | `npm install -g @simplix-boot/cli` |
26
+ | Spring Boot 3 | 1.x | `npm install -g @simplix-boot/cli@spring-boot-3x` |
27
+
28
+ ## 설치
29
+
30
+ ```bash
31
+ # Spring Boot 4 projects (SimpliX 2.x)
32
+ npm install -g @simplix-boot/cli
33
+
34
+ # Spring Boot 3 projects (SimpliX 1.x)
35
+ npm install -g @simplix-boot/cli@spring-boot-3x
36
+
37
+ simplix-boot --version
38
+ ```
39
+
40
+ 설치하지 않고 실행하려면 같은 패키지 표기로 `npx @simplix-boot/cli <명령>`을 사용하세요. 팀 단위의 버전 고정과 프레임워크 체크아웃의 CLI를 실행하는 방법은 [버전 관리](docs/ko/managing-versions.md)에 있습니다.
41
+
42
+ ## 빠른 시작
43
+
44
+ `Author`라는 JPA 엔티티와 그 저장소가 이미 있는 프로젝트의 루트에서 실행하세요.
45
+
46
+ ```bash
47
+ # 1. Create the .simplix folder, then write .simplix/generator-simplix.json
48
+ simplix-boot init
49
+
50
+ # 2. Write .simplix/entity/Author.yml from the entity
51
+ simplix-boot config Author
52
+
53
+ # 3. Edit the yml, then generate the code into generated/
54
+ simplix-boot generate Author
55
+
56
+ # 4. Move the generated files into a module
57
+ simplix-boot promote Author --module catalog
58
+
59
+ # 5. Check that every promoted file matches the templates
60
+ simplix-boot generated
61
+ ```
62
+
63
+ [시작하기](docs/ko/getting-started.md)에서 같은 단계를 설정 파일, yml 편집 내용, 명령별 출력과 함께 따라 할 수 있습니다.
64
+
65
+ ## 문서
66
+
67
+ | 하려는 일 | 문서 |
68
+ |---|---|
69
+ | 첫 API를 단계별로 생성 | [시작하기](docs/ko/getting-started.md) |
70
+ | 생성되는 코드의 모양 변경 | [템플릿 사용자 지정](docs/ko/customizing-templates.md) |
71
+ | 템플릿이나 yml을 바꾼 뒤 직접 고친 내용을 유지하며 다시 생성 | [생성 코드 갱신](docs/ko/updating-generated-code.md) |
72
+ | 맞는 라인 설치, 버전 고정, 체크아웃 연결 | [버전 관리](docs/ko/managing-versions.md) |
73
+ | generator-simplix를 쓰던 프로젝트 전환 | [generator-simplix에서 전환](docs/ko/migrating-from-generator-simplix.md) |
74
+ | 명령과 옵션 확인 | [명령 레퍼런스](docs/ko/command-reference.md) |
75
+ | 설정 파일과 엔티티 yml의 키 확인 | [설정 레퍼런스](docs/ko/configuration-reference.md) |
76
+ | 템플릿 변수와 내장 템플릿 확인 | [템플릿 레퍼런스](docs/ko/template-reference.md) |
77
+ | 명령의 내부 동작 이해 | [동작 원리](docs/ko/how-it-works.md) |
78
+ | 오류 해결 | [문제 해결](docs/ko/troubleshooting.md) |
79
+
80
+ ## 라이선스
81
+
82
+ SimpleCORE License 1.0 (SCL-1.0). [LICENSE](../LICENSE)를 참조하세요.
package/README.md CHANGED
@@ -1,3 +1,82 @@
1
- # Temporary Holding Version
1
+ **English** | [한국어](./README.ko.md)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # SimpliX CLI
4
+
5
+ `simplix-boot` reads a JPA entity and writes the service, REST controller, DTOs and tests that expose it through SimpliX. You describe each field once in a yml file, and the CLI keeps the generated code and your own edits together when a template changes later.
6
+
7
+ ![An entity becomes module source through config, generate and promote. The developer edits the entity yml, templates decide the code, and generated reports whether promoted files still match the templates.](../docs/assets/figures/cli-readme-pipeline.en.svg)
8
+
9
+ ## When to use it
10
+
11
+ - You add an entity and need its CRUD API in the shape every other SimpliX API of the project has.
12
+ - You change a field and want the DTOs, the search conditions and the tests to follow.
13
+ - You want hand edits in generated classes to survive the next template change.
14
+
15
+ A screen that is not backed by one entity (a dashboard, a report that joins several aggregates) is written by hand; the CLI has nothing to generate it from.
16
+
17
+ ## Requirements
18
+
19
+ - Node.js 20 or later
20
+ - A Gradle or Maven project that depends on SimpliX
21
+ - The CLI of the same release line as the project's SimpliX
22
+
23
+ | Your project | SimpliX line | Install |
24
+ |---|---|---|
25
+ | Spring Boot 4 | 2.x | `npm install -g @simplix-boot/cli` |
26
+ | Spring Boot 3 | 1.x | `npm install -g @simplix-boot/cli@spring-boot-3x` |
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ # Spring Boot 4 projects (SimpliX 2.x)
32
+ npm install -g @simplix-boot/cli
33
+
34
+ # Spring Boot 3 projects (SimpliX 1.x)
35
+ npm install -g @simplix-boot/cli@spring-boot-3x
36
+
37
+ simplix-boot --version
38
+ ```
39
+
40
+ To run it without installing, use `npx @simplix-boot/cli <command>` with the same package spec. [Managing versions](docs/en/managing-versions.md) covers pinning a version for a team and running the CLI from a framework checkout.
41
+
42
+ ## Quick start
43
+
44
+ Run these in the root of a project that already has a JPA entity named `Author` and its repository.
45
+
46
+ ```bash
47
+ # 1. Create the .simplix folder, then write .simplix/generator-simplix.json
48
+ simplix-boot init
49
+
50
+ # 2. Write .simplix/entity/Author.yml from the entity
51
+ simplix-boot config Author
52
+
53
+ # 3. Edit the yml, then generate the code into generated/
54
+ simplix-boot generate Author
55
+
56
+ # 4. Move the generated files into a module
57
+ simplix-boot promote Author --module catalog
58
+
59
+ # 5. Check that every promoted file matches the templates
60
+ simplix-boot generated
61
+ ```
62
+
63
+ [Getting started](docs/en/getting-started.md) walks through the same steps with the configuration file, the yml edits and the output of each command.
64
+
65
+ ## Documentation
66
+
67
+ | If you want to | Read |
68
+ |---|---|
69
+ | generate your first API step by step | [Getting started](docs/en/getting-started.md) |
70
+ | change what the generated code looks like | [Customizing templates](docs/en/customizing-templates.md) |
71
+ | regenerate after a template or yml change without losing edits | [Updating generated code](docs/en/updating-generated-code.md) |
72
+ | install the right line, pin a version, link a checkout | [Managing versions](docs/en/managing-versions.md) |
73
+ | move a project from generator-simplix | [Migrating from generator-simplix](docs/en/migrating-from-generator-simplix.md) |
74
+ | look up a command or an option | [Command reference](docs/en/command-reference.md) |
75
+ | look up a key of the configuration file or the entity yml | [Configuration reference](docs/en/configuration-reference.md) |
76
+ | look up a template variable or a built-in template | [Template reference](docs/en/template-reference.md) |
77
+ | understand what happens inside each command | [How it works](docs/en/how-it-works.md) |
78
+ | fix an error | [Troubleshooting](docs/en/troubleshooting.md) |
79
+
80
+ ## License
81
+
82
+ SimpleCORE License 1.0 (SCL-1.0). See [LICENSE](../LICENSE).
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+ import { tolerateClosedReader } from '../src/lib/console.js';
4
+
5
+ tolerateClosedReader(process.stdout);
6
+ process.exitCode = main(process.argv.slice(2));
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@simplix-boot/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.3.1",
4
+ "description": "Command line tool that generates SimpliX Spring Boot code (services, controllers, DTOs, tests) from JPA entities",
5
+ "type": "module",
6
+ "bin": {
7
+ "simplix-boot": "bin/simplix-boot.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "templates",
13
+ "LICENSE_KO"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test test/*.test.js",
20
+ "prepack": "node scripts/license-files.mjs copy",
21
+ "postpack": "node scripts/license-files.mjs remove",
22
+ "prepublishOnly": "node scripts/assert-release-version.mjs"
23
+ },
24
+ "dependencies": {
25
+ "ejs": "^3.1.10",
26
+ "js-yaml": "^4.1.0",
27
+ "lodash": "^4.17.21"
28
+ },
29
+ "keywords": [
30
+ "simplix",
31
+ "spring-boot",
32
+ "jpa",
33
+ "crud",
34
+ "code-generator",
35
+ "cli"
36
+ ],
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/simplix-framework/simplix.git",
40
+ "directory": "simplix-cli"
41
+ },
42
+ "license": "SEE LICENSE IN LICENSE",
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "tag": "spring-boot-3x"
46
+ }
47
+ }
package/src/cli.js ADDED
@@ -0,0 +1,103 @@
1
+ import { parseArguments } from './lib/args.js';
2
+ import { createOutput, style, symbols } from './lib/console.js';
3
+ import { CliError } from './lib/errors.js';
4
+ import { requireProjectRoot } from './lib/project.js';
5
+ import { getGeneratorVersion } from './lib/version-utils.js';
6
+ import * as config from './commands/config.js';
7
+ import * as generate from './commands/generate.js';
8
+ import * as generated from './commands/generated.js';
9
+ import * as init from './commands/init.js';
10
+ import * as promote from './commands/promote.js';
11
+ import * as templates from './commands/templates.js';
12
+ import * as version from './commands/version.js';
13
+
14
+ /** The commands by name, in the order the help lists them. */
15
+ const COMMANDS = { init, config, generate, promote, generated, templates, version };
16
+
17
+ /** Names a command also answers to. */
18
+ const ALIASES = { entity: 'generate' };
19
+
20
+ function helpText() {
21
+ const width = Math.max(...Object.keys(COMMANDS).map(name => name.length));
22
+ const lines = [
23
+ '',
24
+ `${style.cyan('SimpliX Boot CLI')} v${getGeneratorVersion()}`,
25
+ '',
26
+ 'Generates SimpliX Spring Boot code (services, controllers, DTOs, tests) from JPA entities.',
27
+ '',
28
+ style.bold('Usage:'),
29
+ ' simplix-boot <command> [options]',
30
+ '',
31
+ style.bold('Commands:'),
32
+ ...Object.entries(COMMANDS).map(([name, command]) => ` ${name.padEnd(width)} ${command.summary}`),
33
+ '',
34
+ style.bold('Workflow:'),
35
+ ' 1. simplix-boot init Create .simplix in the project root',
36
+ ' 2. simplix-boot config <EntityName> Write the entity yml from the JPA entity',
37
+ ' 3. Edit .simplix/entity/<EntityName>.yml to match the requirements',
38
+ ' 4. simplix-boot generate <EntityName> Generate the code from the yml',
39
+ ' 5. simplix-boot promote <EntityName> --module <module>',
40
+ '',
41
+ 'Templates come with the CLI. A file of the same relative path under .simplix/templates',
42
+ 'replaces the built-in one; "simplix-boot templates" lists which is in use.',
43
+ '',
44
+ 'Run "simplix-boot <command> --help" for the options of one command.',
45
+ '',
46
+ ];
47
+
48
+ return lines.join('\n');
49
+ }
50
+
51
+ function commandHelpText(name, command) {
52
+ const options = Object.entries(command.argumentSpec.options ?? {}).map(([option, declared]) => {
53
+ if (declared.type === 'string') return ` --${option} <value>`;
54
+ return declared.default === true ? ` --no-${option}` : ` --${option}`;
55
+ });
56
+
57
+ return ['', command.summary, '', style.bold('Usage:'), ` ${command.usage}`, ...(options.length > 0 ? ['', style.bold('Options:'), ...options] : []), ''].join('\n');
58
+ }
59
+
60
+ /**
61
+ * Runs the command line.
62
+ *
63
+ * @param {string[]} argv the arguments after the executable
64
+ * @param {object} [environment]
65
+ * @param {string} [environment.cwd] the directory the command was run in
66
+ * @returns {number} the process exit code
67
+ */
68
+ export function main(argv, { cwd = process.cwd() } = {}) {
69
+ const [first, ...rest] = argv;
70
+
71
+ try {
72
+ if (first === undefined || first === 'help' || first === '--help' || first === '-h') {
73
+ process.stdout.write(`${helpText()}\n`);
74
+ return 0;
75
+ }
76
+
77
+ if (first === '--version' || first === '-v') {
78
+ process.stdout.write(`${getGeneratorVersion()}\n`);
79
+ return 0;
80
+ }
81
+
82
+ const name = ALIASES[first] ?? first;
83
+ const command = Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : undefined;
84
+ if (command === undefined) {
85
+ throw new CliError(`Unknown command: ${first}\nRun "simplix-boot help" for the list of commands.`);
86
+ }
87
+
88
+ if (rest.includes('--help') || rest.includes('-h')) {
89
+ process.stdout.write(`${commandHelpText(name, command)}\n`);
90
+ return 0;
91
+ }
92
+
93
+ const { positionals, options } = parseArguments(rest, command.argumentSpec);
94
+ const output = createOutput();
95
+ const root = command.needsProject === false ? undefined : requireProjectRoot(cwd);
96
+
97
+ return command.run({ cwd, root, positionals, options, output }) ?? 0;
98
+ } catch (error) {
99
+ if (!(error instanceof CliError)) throw error;
100
+ process.stderr.write(`${symbols.error} ${error.message}\n`);
101
+ return error.exitCode;
102
+ }
103
+ }
@@ -0,0 +1,129 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { symbols } from '../lib/console.js';
4
+ import { analyzeEntity } from '../lib/entity-analyzer.js';
5
+ import { CliError } from '../lib/errors.js';
6
+ import { findEntityFile } from '../lib/file-utils.js';
7
+ import { buildFkIdFieldMap, processEmbeddedIdFields, processRegularField } from '../lib/config/fields.js';
8
+ import { analyzeParentClass, mergeFields } from '../lib/config/parents.js';
9
+ import {
10
+ entityTypeResolver,
11
+ extractModulePath,
12
+ findRepositoryModulePath,
13
+ getBaseEntityPath,
14
+ } from '../lib/config/paths.js';
15
+ import { createBaseConfig, dumpEntityConfig } from '../lib/config/yml.js';
16
+ import { findNameField } from '../lib/name-field.js';
17
+ import { entityConfigPathOf, readProjectConfig } from '../lib/project.js';
18
+ import { assertGeneratorVersion } from '../lib/version-check.js';
19
+
20
+ export const usage = 'simplix-boot config <EntityName> [--force] [--skip-version-check]';
21
+
22
+ export const summary = 'Analyze a JPA entity and write its yml under .simplix/entity';
23
+
24
+ export const argumentSpec = {
25
+ positionals: ['entityName'],
26
+ options: {
27
+ force: { type: 'boolean', default: false },
28
+ 'skip-version-check': { type: 'boolean', default: false },
29
+ },
30
+ };
31
+
32
+ /**
33
+ * Builds the yml of one entity from its Java source: its id and name fields, its module path, and
34
+ * for every field the views it appears in and the operators it is searched with.
35
+ *
36
+ * @param {object} context
37
+ * @param {string} context.root the project root
38
+ * @param {object} [context.config] the parsed project configuration
39
+ * @param {(message?: string) => void} context.log where progress goes
40
+ * @param {string} entityName the entity class name
41
+ * @returns {string} the yml text
42
+ * @throws {CliError} when the entity source is not found
43
+ */
44
+ export function buildEntityConfigYml(context, entityName) {
45
+ const baseEntityPath = getBaseEntityPath(context);
46
+ const srcPath = path.join(context.root, baseEntityPath);
47
+ const entityPath = findEntityFile(srcPath, entityName);
48
+
49
+ if (!entityPath) {
50
+ throw new CliError(`Entity file not found\nLooking for: ${entityName}.java\nSearched in: ${srcPath}`);
51
+ }
52
+
53
+ const entityContent = fs.readFileSync(entityPath, 'utf8');
54
+ const { fields, embeddedIdFields, idField, parentClass } = analyzeEntity(entityContent, {
55
+ isEntityType: entityTypeResolver(context, srcPath),
56
+ });
57
+
58
+ let finalIdField = idField;
59
+ const { parentFields, finalIdField: parentIdField } = analyzeParentClass(
60
+ context,
61
+ parentClass,
62
+ baseEntityPath,
63
+ srcPath,
64
+ new Set()
65
+ );
66
+
67
+ if (!finalIdField && parentIdField) {
68
+ finalIdField = parentIdField;
69
+ }
70
+
71
+ if (parentFields.length > 0) {
72
+ mergeFields(parentFields, fields);
73
+ }
74
+
75
+ const idFieldName = finalIdField || 'id';
76
+ const nameField = findNameField(fields, idFieldName);
77
+ const modulePath = extractModulePath(entityContent, entityName);
78
+
79
+ const repositoryModulePath = findRepositoryModulePath(context, entityName, modulePath);
80
+ if (repositoryModulePath !== null && repositoryModulePath !== modulePath) {
81
+ context.log(` Repository found at: ${repositoryModulePath || '(root)'}`);
82
+ }
83
+
84
+ const config = createBaseConfig(entityName, modulePath, idFieldName, nameField, repositoryModulePath);
85
+
86
+ if (Array.isArray(fields) && fields.some(field => field.name === 'createdAt')) {
87
+ config.defaultSortField = 'createdAt';
88
+ }
89
+
90
+ processEmbeddedIdFields(embeddedIdFields, config);
91
+
92
+ const fkIdFieldMap = buildFkIdFieldMap(fields);
93
+
94
+ if (Array.isArray(fields)) {
95
+ fields.forEach(field => {
96
+ processRegularField(context, field, config, idFieldName, embeddedIdFields, fkIdFieldMap);
97
+ });
98
+ }
99
+
100
+ return dumpEntityConfig(config);
101
+ }
102
+
103
+ /** Runs `config` from the command line. */
104
+ export function run({ root, positionals, options, output }) {
105
+ const { entityName } = positionals;
106
+ if (!entityName) {
107
+ throw new CliError(`Entity name is required\nUsage: ${usage}`);
108
+ }
109
+
110
+ const config = readProjectConfig(root);
111
+ const log = output.log;
112
+
113
+ if (config) {
114
+ assertGeneratorVersion({ config, log, skip: options['skip-version-check'] });
115
+ }
116
+
117
+ const yml = buildEntityConfigYml({ root, config, log }, entityName);
118
+ const configPath = entityConfigPathOf(root, entityName);
119
+
120
+ if (fs.existsSync(configPath) && !options.force) {
121
+ log(`\n${symbols.warning} Config file already exists: ${entityName}.yml`);
122
+ log('Use --force to overwrite');
123
+ return;
124
+ }
125
+
126
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
127
+ fs.writeFileSync(configPath, yml);
128
+ log(`\n${symbols.success} Generated config file: ${entityName}.yml`);
129
+ }