kaven-cli 0.1.0-alpha.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 (40) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +93 -0
  3. package/dist/commands/auth/login.js +44 -0
  4. package/dist/commands/auth/logout.js +25 -0
  5. package/dist/commands/auth/whoami.js +35 -0
  6. package/dist/commands/index.js +1 -0
  7. package/dist/commands/marketplace/install.js +59 -0
  8. package/dist/commands/marketplace/list.js +44 -0
  9. package/dist/commands/module/add.js +69 -0
  10. package/dist/commands/module/doctor.js +70 -0
  11. package/dist/commands/module/remove.js +58 -0
  12. package/dist/commands/modules/add.js +53 -0
  13. package/dist/commands/modules/list.js +40 -0
  14. package/dist/commands/modules/remove.js +54 -0
  15. package/dist/commands/telemetry/view.js +27 -0
  16. package/dist/core/AuthService.js +61 -0
  17. package/dist/core/ManifestParser.js +52 -0
  18. package/dist/core/MarkerService.js +62 -0
  19. package/dist/core/ModuleDoctor.js +162 -0
  20. package/dist/core/ModuleInstaller.js +66 -0
  21. package/dist/core/api/KavenApiClient.js +61 -0
  22. package/dist/core/auth/AuthManager.js +91 -0
  23. package/dist/core/index.js +1 -0
  24. package/dist/core/modules/Injector.js +86 -0
  25. package/dist/core/modules/ModuleInstaller.js +63 -0
  26. package/dist/core/modules/ModuleManager.js +59 -0
  27. package/dist/core/modules/ModuleRemover.js +60 -0
  28. package/dist/index.js +91 -0
  29. package/dist/infrastructure/Container.js +39 -0
  30. package/dist/infrastructure/MarketplaceClient.js +73 -0
  31. package/dist/infrastructure/TelemetryBuffer.js +71 -0
  32. package/dist/infrastructure/TransactionalFileSystem.js +74 -0
  33. package/dist/infrastructure/index.js +1 -0
  34. package/dist/lib/config.js +66 -0
  35. package/dist/lib/errors.js +32 -0
  36. package/dist/lib/logger.js +70 -0
  37. package/dist/types/manifest.js +45 -0
  38. package/dist/types/markers.js +10 -0
  39. package/dist/types/module.js +49 -0
  40. package/package.json +64 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Kaven
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # Kaven CLI 🚀
2
+
3
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
4
+ [![Version](https://img.shields.io/badge/version-0.1.0--alpha.1-orange.svg)](https://semver.org)
5
+
6
+ A ferramenta de linha de comando oficial para o ecossistema **Kaven**. Projetada para ser robusta, idempotente e extensível.
7
+
8
+ > **Note**: Este projeto está em fase **Alpha**. APIs e comandos estão sujeitos a alterações.
9
+
10
+ ---
11
+
12
+ ## 📦 Instalação
13
+
14
+ A CLI pode ser instalada globalmente via npm ou pnpm:
15
+
16
+ ```bash
17
+ npm install -g kaven-cli@alpha
18
+ # ou
19
+ pnpm add -g kaven-cli@alpha
20
+ ```
21
+
22
+ ## 🚀 Início Rápido
23
+
24
+ Consiga o seu projeto rodando em segundos:
25
+
26
+ ```bash
27
+ # 1. Autenticação
28
+ kaven auth login
29
+
30
+ # 2. Explorar Módulos
31
+ kaven marketplace list
32
+
33
+ # 3. Instalar um Módulo
34
+ kaven marketplace install payments
35
+
36
+ # 4. Verificar Saúde do Projeto
37
+ kaven module doctor
38
+
39
+ # 5. Ver Telemetria Local
40
+ kaven telemetry view
41
+ ```
42
+
43
+ ## 🛠️ Comandos Principais
44
+
45
+ A Kaven CLI organiza suas funcionalidades em grupos lógicos para uma melhor experiência:
46
+
47
+ ### 📦 Módulos (`module`, `m`)
48
+
49
+ Gerenciamento local de módulos e integridade do projeto.
50
+
51
+ - `kaven module add <path>`: Adiciona um módulo localmente via arquivo de manifest.
52
+ - `kaven module remove <name>`: Remove um módulo e limpa as injeções de código.
53
+ - `kaven module doctor`: Verifica a integridade dos markers, âncoras e dependências.
54
+
55
+ ### 🔑 Autenticação (`auth`)
56
+
57
+ Gerenciamento de sessão e tokens.
58
+
59
+ - `kaven auth login`: Inicia o fluxo de autenticação (Device Flow).
60
+ - `kaven auth logout`: Remove as credenciais locais.
61
+ - `kaven auth whoami`: Exibe informações do usuário atual.
62
+
63
+ ### 🏬 Marketplace (`marketplace`, `mkt`)
64
+
65
+ Descoberta e instalação de módulos oficiais.
66
+
67
+ - `kaven marketplace list`: Lista todos os módulos disponíveis na nuvem Kaven.
68
+ - `kaven marketplace install <id>`: Baixa e instala um módulo automaticamente.
69
+
70
+ ### 📊 Telemetria (`telemetry`)
71
+
72
+ Observabilidade e auditoria local.
73
+
74
+ - `kaven telemetry view`: Exibe os últimos eventos registrados localmente.
75
+
76
+ ---
77
+
78
+ ## 🧪 Desenvolvimento
79
+
80
+ Nós valorizamos contribuições! Antes de começar, por favor leia nosso guia de contribuição:
81
+
82
+ - [CONTRIBUTING.md](./CONTRIBUTING.md) - Guia de setup e padrões.
83
+ - [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md) - Nosso compromisso com a comunidade.
84
+
85
+ ## 📄 Licença
86
+
87
+ Este projeto é licenciado sob a **Apache-2.0 License** - veja o arquivo [LICENSE](LICENSE) para detalhes.
88
+
89
+ ---
90
+
91
+ <p align="center">
92
+ Feito com ❤️ pela equipe Kaven
93
+ </p>
@@ -0,0 +1,44 @@
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.authLogin = authLogin;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const ora_1 = __importDefault(require("ora"));
9
+ const AuthService_1 = require("../../core/AuthService");
10
+ const TelemetryBuffer_1 = require("../../infrastructure/TelemetryBuffer");
11
+ async function authLogin() {
12
+ const telemetry = TelemetryBuffer_1.TelemetryBuffer.getInstance();
13
+ const startTime = Date.now();
14
+ telemetry.capture("cli.auth.login.start");
15
+ const authService = new AuthService_1.AuthService();
16
+ console.log(chalk_1.default.blue("🔐 Iniciando fluxo de autenticação...\n"));
17
+ const spinner = (0, ora_1.default)("Gerando código de dispositivo...").start();
18
+ try {
19
+ // Simulando atraso da rede
20
+ await new Promise((resolve) => setTimeout(resolve, 1000));
21
+ const deviceCode = "KAVEN-777-BINGO";
22
+ const verificationUrl = "https://kaven.sh/device";
23
+ spinner.stop();
24
+ console.log(chalk_1.default.yellow("Para continuar o login, acesse a URL abaixo e insira o código:"));
25
+ console.log(chalk_1.default.bold(`\n URL: ${verificationUrl}`));
26
+ console.log(chalk_1.default.bold(` Código: ${deviceCode}\n`));
27
+ const pollSpinner = (0, ora_1.default)("Aguardando autorização no navegador...").start();
28
+ // Simular polling bem-sucedido após 3 segundos
29
+ await new Promise((resolve) => setTimeout(resolve, 3000));
30
+ const mockToken = "jwt-mock-token-for-kaven-explorador";
31
+ await authService.storeToken(mockToken);
32
+ pollSpinner.succeed(chalk_1.default.green("Autenticação realizada com sucesso!"));
33
+ console.log(chalk_1.default.gray("\nSeu token foi salvo com segurança em ~/.kaven/auth.json"));
34
+ telemetry.capture("cli.auth.login.success", {}, Date.now() - startTime);
35
+ await telemetry.flush();
36
+ }
37
+ catch (error) {
38
+ telemetry.capture("cli.auth.login.error", { error: error.message }, Date.now() - startTime);
39
+ await telemetry.flush();
40
+ spinner.fail(chalk_1.default.red("Erro ao realizar login."));
41
+ console.error(error);
42
+ process.exit(1);
43
+ }
44
+ }
@@ -0,0 +1,25 @@
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.authLogout = authLogout;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const ora_1 = __importDefault(require("ora"));
9
+ const AuthService_1 = require("../../core/AuthService");
10
+ async function authLogout() {
11
+ const authService = new AuthService_1.AuthService();
12
+ const spinner = (0, ora_1.default)("Encerrando sessão...").start();
13
+ try {
14
+ if (!(await authService.isAuthenticated())) {
15
+ spinner.info(chalk_1.default.yellow("Você não está autenticado."));
16
+ return;
17
+ }
18
+ await authService.clearToken();
19
+ spinner.succeed(chalk_1.default.green("Sessão encerrada com sucesso!"));
20
+ }
21
+ catch {
22
+ spinner.fail(chalk_1.default.red("Erro ao realizar logout."));
23
+ process.exit(1);
24
+ }
25
+ }
@@ -0,0 +1,35 @@
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.authWhoami = authWhoami;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const AuthService_1 = require("../../core/AuthService");
9
+ const TelemetryBuffer_1 = require("../../infrastructure/TelemetryBuffer");
10
+ async function authWhoami() {
11
+ const telemetry = TelemetryBuffer_1.TelemetryBuffer.getInstance();
12
+ telemetry.capture("cli.auth.whoami.start");
13
+ const authService = new AuthService_1.AuthService();
14
+ try {
15
+ const userInfo = await authService.getUserInfo();
16
+ if (!userInfo) {
17
+ console.log(chalk_1.default.yellow("Você não está autenticado."));
18
+ console.log(chalk_1.default.gray("Use 'kaven auth login' para entrar."));
19
+ telemetry.capture("cli.auth.whoami.not_authenticated");
20
+ await telemetry.flush();
21
+ return;
22
+ }
23
+ telemetry.capture("cli.auth.whoami.authenticated");
24
+ console.log(chalk_1.default.blue("👤 Usuário logado:"));
25
+ console.log(`${chalk_1.default.bold("ID:")} ${userInfo.id}`);
26
+ console.log(`${chalk_1.default.bold("E-mail:")} ${userInfo.email}`);
27
+ if (userInfo.name) {
28
+ console.log(`${chalk_1.default.bold("Nome:")} ${userInfo.name}`);
29
+ }
30
+ }
31
+ catch {
32
+ console.error(chalk_1.default.red("Erro ao verificar status de autenticação."));
33
+ process.exit(1);
34
+ }
35
+ }
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,59 @@
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.marketplaceInstall = marketplaceInstall;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const ora_1 = __importDefault(require("ora"));
9
+ const fs_extra_1 = __importDefault(require("fs-extra"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const os_1 = __importDefault(require("os"));
12
+ const MarketplaceClient_1 = require("../../infrastructure/MarketplaceClient");
13
+ const AuthService_1 = require("../../core/AuthService");
14
+ const add_1 = require("../module/add");
15
+ const TelemetryBuffer_1 = require("../../infrastructure/TelemetryBuffer");
16
+ async function marketplaceInstall(moduleId) {
17
+ const telemetry = TelemetryBuffer_1.TelemetryBuffer.getInstance();
18
+ const startTime = Date.now();
19
+ telemetry.capture("cli.marketplace.install.start", { moduleId });
20
+ const authService = new AuthService_1.AuthService();
21
+ const client = new MarketplaceClient_1.MarketplaceClient();
22
+ // 1. Verificar Autenticação
23
+ if (!(await authService.isAuthenticated())) {
24
+ console.log(chalk_1.default.red("\n❌ Erro: Autenticação necessária."));
25
+ console.log(chalk_1.default.yellow("O Marketplace da Kaven exige que você esteja logado para instalar módulos."));
26
+ console.log(chalk_1.default.gray("\nExecute: kaven auth login\n"));
27
+ process.exit(1);
28
+ }
29
+ const spinner = (0, ora_1.default)(`Preparando instalação de '${moduleId}'...`).start();
30
+ try {
31
+ // 2. Buscar Manifest Remoto
32
+ spinner.text = `Buscando manifest de '${moduleId}' no Marketplace...`;
33
+ const manifest = await client.getModuleManifest(moduleId);
34
+ if (!manifest) {
35
+ spinner.fail(chalk_1.default.red(`Módulo '${moduleId}' não encontrado no Marketplace.`));
36
+ process.exit(1);
37
+ }
38
+ spinner.succeed(chalk_1.default.green(`Módulo '${moduleId}' encontrado.`));
39
+ // 3. Salvar manifest temporário para usar o moduleAdd existente
40
+ // Em uma versão futura, o moduleAdd poderia aceitar um objeto de manifest diretamente
41
+ const tempDir = path_1.default.join(os_1.default.tmpdir(), "kaven-mkt-install");
42
+ await fs_extra_1.default.ensureDir(tempDir);
43
+ const tempManifestPath = path_1.default.join(tempDir, `${moduleId}-manifest.json`);
44
+ await fs_extra_1.default.writeJson(tempManifestPath, manifest);
45
+ // 4. Executar instalação (reutilizando lógica transacional do moduleAdd)
46
+ await (0, add_1.moduleAdd)(tempManifestPath);
47
+ // 5. Cleanup
48
+ await fs_extra_1.default.remove(tempDir);
49
+ telemetry.capture("cli.marketplace.install.success", { moduleId }, Date.now() - startTime);
50
+ await telemetry.flush();
51
+ }
52
+ catch (error) {
53
+ telemetry.capture("cli.marketplace.install.error", { moduleId, error: error.message }, Date.now() - startTime);
54
+ await telemetry.flush();
55
+ spinner.fail(chalk_1.default.red(`Falha na instalação do módulo '${moduleId}'.`));
56
+ console.error(error);
57
+ process.exit(1);
58
+ }
59
+ }
@@ -0,0 +1,44 @@
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.marketplaceList = marketplaceList;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const ora_1 = __importDefault(require("ora"));
9
+ const MarketplaceClient_1 = require("../../infrastructure/MarketplaceClient");
10
+ const TelemetryBuffer_1 = require("../../infrastructure/TelemetryBuffer");
11
+ async function marketplaceList() {
12
+ const telemetry = TelemetryBuffer_1.TelemetryBuffer.getInstance();
13
+ const startTime = Date.now();
14
+ telemetry.capture("cli.marketplace.list.start");
15
+ const client = new MarketplaceClient_1.MarketplaceClient();
16
+ const spinner = (0, ora_1.default)("Buscando módulos no Marketplace...").start();
17
+ try {
18
+ const modules = await client.listModules();
19
+ spinner.stop();
20
+ if (modules.length === 0) {
21
+ console.log(chalk_1.default.yellow("Nenhum módulo encontrado no Marketplace no momento."));
22
+ return;
23
+ }
24
+ console.log(chalk_1.default.blue.bold("\n📦 Módulos Disponíveis no Marketplace:\n"));
25
+ // Header (manual alignment)
26
+ console.log(chalk_1.default.gray(`${"ID".padEnd(20)} ${"NOME".padEnd(20)} ${"VERSÃO".padEnd(10)} ${"AUTOR"}`));
27
+ console.log(chalk_1.default.gray("-".repeat(70)));
28
+ modules.forEach((mod) => {
29
+ console.log(`${chalk_1.default.cyan(mod.id.padEnd(20))} ${chalk_1.default.white(mod.name.padEnd(20))} ${chalk_1.default.green(mod.version.padEnd(10))} ${chalk_1.default.gray(mod.author)}`);
30
+ console.log(chalk_1.default.italic.gray(` > ${mod.description}\n`));
31
+ });
32
+ console.log(chalk_1.default.gray(`Total: ${modules.length} módulos encontrados.\n`));
33
+ console.log(chalk_1.default.gray("Use 'kaven marketplace install <id>' para instalar um módulo."));
34
+ telemetry.capture("cli.marketplace.list.success", { count: modules.length }, Date.now() - startTime);
35
+ await telemetry.flush();
36
+ }
37
+ catch (error) {
38
+ telemetry.capture("cli.marketplace.list.error", { error: error.message }, Date.now() - startTime);
39
+ await telemetry.flush();
40
+ spinner.fail(chalk_1.default.red("Erro ao buscar módulos no Marketplace."));
41
+ console.error(error);
42
+ process.exit(1);
43
+ }
44
+ }
@@ -0,0 +1,69 @@
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.moduleAdd = moduleAdd;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const ora_1 = __importDefault(require("ora"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const fs_extra_1 = __importDefault(require("fs-extra"));
11
+ const ModuleInstaller_1 = require("../../core/ModuleInstaller");
12
+ const MarkerService_1 = require("../../core/MarkerService");
13
+ const ManifestParser_1 = require("../../core/ManifestParser");
14
+ const TelemetryBuffer_1 = require("../../infrastructure/TelemetryBuffer");
15
+ async function moduleAdd(manifestPath, projectRoot) {
16
+ const telemetry = TelemetryBuffer_1.TelemetryBuffer.getInstance();
17
+ const startTime = Date.now();
18
+ telemetry.capture("cli.module.add.start", { manifestPath });
19
+ const root = projectRoot || process.cwd();
20
+ const spinner = (0, ora_1.default)("Preparando instalação do módulo...").start();
21
+ try {
22
+ const markerService = new MarkerService_1.MarkerService();
23
+ const manifestParser = new ManifestParser_1.ManifestParser();
24
+ const installer = new ModuleInstaller_1.ModuleInstaller(root, markerService);
25
+ // 1. Resolver caminho do manifest
26
+ const absolutePath = path_1.default.isAbsolute(manifestPath)
27
+ ? manifestPath
28
+ : path_1.default.join(root, manifestPath);
29
+ if (!(await fs_extra_1.default.pathExists(absolutePath))) {
30
+ throw new Error(`Arquivo de manifest não encontrado: ${manifestPath}`);
31
+ }
32
+ // 2. Parse do manifest
33
+ spinner.text = "Validando manifest...";
34
+ const manifest = await manifestParser.parse(absolutePath);
35
+ // 3. Instalar
36
+ spinner.text = `Instalando ${manifest.name}@${manifest.version}...`;
37
+ await installer.install(manifest);
38
+ // 4. Atualizar kaven.json
39
+ spinner.text = "Atualizando configuração do projeto...";
40
+ await updateKavenConfig(root, manifest.name, manifest.version);
41
+ // 5. Cache do manifest para desinstalação futura
42
+ spinner.text = "Salvando cache do manifest...";
43
+ const cacheDir = path_1.default.join(root, ".kaven", "modules", manifest.name);
44
+ await fs_extra_1.default.ensureDir(cacheDir);
45
+ await fs_extra_1.default.writeJson(path_1.default.join(cacheDir, "module.json"), manifest, {
46
+ spaces: 2,
47
+ });
48
+ spinner.succeed(chalk_1.default.green(`Módulo ${manifest.name} instalado com sucesso!`));
49
+ telemetry.capture("cli.module.add.success", { name: manifest.name }, Date.now() - startTime);
50
+ await telemetry.flush();
51
+ }
52
+ catch (error) {
53
+ telemetry.capture("cli.module.add.error", { error: error.message }, Date.now() - startTime);
54
+ await telemetry.flush();
55
+ spinner.fail(chalk_1.default.red(`Falha na instalação: ${error instanceof Error ? error.message : String(error)}`));
56
+ process.exit(1);
57
+ }
58
+ }
59
+ async function updateKavenConfig(projectRoot, name, version) {
60
+ const configPath = path_1.default.join(projectRoot, "kaven.json");
61
+ let config = { modules: {} };
62
+ if (await fs_extra_1.default.pathExists(configPath)) {
63
+ config = await fs_extra_1.default.readJson(configPath);
64
+ }
65
+ if (!config.modules)
66
+ config.modules = {};
67
+ config.modules[name] = version;
68
+ await fs_extra_1.default.writeJson(configPath, config, { spaces: 2 });
69
+ }
@@ -0,0 +1,70 @@
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.moduleDoctor = moduleDoctor;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const ModuleDoctor_1 = require("../../core/ModuleDoctor");
9
+ const MarkerService_1 = require("../../core/MarkerService");
10
+ const ManifestParser_1 = require("../../core/ManifestParser");
11
+ async function moduleDoctor(options) {
12
+ console.log(chalk_1.default.blue("🔍 Running module doctor...\n"));
13
+ const markerService = new MarkerService_1.MarkerService();
14
+ const manifestParser = new ManifestParser_1.ManifestParser();
15
+ const doctor = new ModuleDoctor_1.ModuleDoctor(process.cwd(), markerService, manifestParser);
16
+ let results = [];
17
+ try {
18
+ results = await doctor.checkAll();
19
+ }
20
+ catch (error) {
21
+ console.error(chalk_1.default.red(`❌ Heavy failure during doctor audit: ${error instanceof Error ? error.message : String(error)}`));
22
+ process.exit(1);
23
+ }
24
+ if (results.length === 0) {
25
+ console.log(chalk_1.default.green("✅ All checks passed! Your modules are healthy.\n"));
26
+ return;
27
+ }
28
+ // Grupar por severidade
29
+ const errors = results.filter((r) => r.severity === "error");
30
+ const warnings = results.filter((r) => r.severity === "warning");
31
+ if (errors.length > 0) {
32
+ console.log(chalk_1.default.red(`❌ Found ${errors.length} error(s):\n`));
33
+ for (const err of errors) {
34
+ console.log(chalk_1.default.red(` ${err.message}`));
35
+ if (err.file)
36
+ console.log(chalk_1.default.gray(` file: ${err.file}`));
37
+ if (err.fixable)
38
+ console.log(chalk_1.default.yellow(` (💡 tip: run with --fix to attempt repair)`));
39
+ console.log();
40
+ }
41
+ }
42
+ if (warnings.length > 0) {
43
+ console.log(chalk_1.default.yellow(`⚠️ Found ${warnings.length} warning(s):\n`));
44
+ for (const warn of warnings) {
45
+ console.log(chalk_1.default.yellow(` ${warn.message}`));
46
+ if (warn.file)
47
+ console.log(chalk_1.default.gray(` file: ${warn.file}`));
48
+ console.log();
49
+ }
50
+ }
51
+ if (options.fix) {
52
+ console.log(chalk_1.default.blue("🔧 Attempting to fix issues...\n"));
53
+ const fixable = results.filter((r) => r.fixable);
54
+ if (fixable.length === 0) {
55
+ console.log(chalk_1.default.gray(" No issues are automatically fixable yet."));
56
+ }
57
+ for (const result of fixable) {
58
+ // Nota: No roadmap Week 2, a reparação real pode ser um placeholder
59
+ // ou apenas o log de tentativa, dependendo da complexidade.
60
+ // Por enquanto, apenas reportamos que a reparação automática
61
+ // será implementada conforme o ModuleInstaller for refinado.
62
+ console.log(chalk_1.default.yellow(` 🚧 Manual repair required for: ${result.message}. Autofix coming in future release.`));
63
+ }
64
+ console.log(chalk_1.default.green("\n✅ Audit complete. Fixes were logged for manual action.\n"));
65
+ }
66
+ else {
67
+ console.log(chalk_1.default.blue("💡 Tip: Run with --fix to see potential repairs\n"));
68
+ }
69
+ process.exit(errors.length > 0 ? 1 : 0);
70
+ }