@gugananuvem/aws-local-simulator 1.0.0 → 1.0.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 (38) hide show
  1. package/README.md +192 -192
  2. package/bin/aws-local-simulator.js +62 -62
  3. package/package.json +8 -5
  4. package/src/config/config-loader.js +113 -0
  5. package/src/config/default-config.js +65 -0
  6. package/src/config/env-loader.js +67 -0
  7. package/src/index.js +130 -130
  8. package/src/index.mjs +124 -0
  9. package/src/server.js +219 -0
  10. package/src/services/apigateway/index.js +67 -0
  11. package/src/services/apigateway/server.js +435 -0
  12. package/src/services/apigateway/simulator.js +1252 -0
  13. package/src/services/cognito/index.js +66 -0
  14. package/src/services/cognito/server.js +229 -0
  15. package/src/services/cognito/simulator.js +848 -0
  16. package/src/services/dynamodb/index.js +71 -0
  17. package/src/services/dynamodb/server.js +122 -0
  18. package/src/services/dynamodb/simulator.js +614 -0
  19. package/src/services/eventbridge/index.js +85 -0
  20. package/src/services/index.js +19 -0
  21. package/src/services/lambda/handler-loader.js +173 -0
  22. package/src/services/lambda/index.js +73 -0
  23. package/src/services/lambda/route-registry.js +275 -0
  24. package/src/services/lambda/server.js +153 -0
  25. package/src/services/lambda/simulator.js +278 -0
  26. package/src/services/s3/index.js +70 -0
  27. package/src/services/s3/server.js +239 -0
  28. package/src/services/s3/simulator.js +740 -0
  29. package/src/services/sns/index.js +76 -0
  30. package/src/services/sqs/index.js +96 -0
  31. package/src/services/sqs/server.js +274 -0
  32. package/src/services/sqs/simulator.js +660 -0
  33. package/src/template/aws-config-template.js +88 -0
  34. package/src/template/aws-config-template.mjs +91 -0
  35. package/src/template/config-template.json +165 -0
  36. package/src/utils/aws-config.js +92 -0
  37. package/src/utils/local-store.js +68 -0
  38. package/src/utils/logger.js +60 -0
package/README.md CHANGED
@@ -1,192 +1,192 @@
1
- # AWS Local Simulator
2
-
3
- [![npm version](https://badge.fury.io/js/aws-local-simulator.svg)](https://badge.fury.io/js/aws-local-simulator)
4
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
- [![Node.js Version](https://img.shields.io/node/v/aws-local-simulator.svg)](https://nodejs.org)
6
-
7
- Simulador local completo para serviços AWS. Desenvolva e teste suas aplicações AWS localmente sem custos!
8
-
9
- ## 🚀 Serviços Suportados
10
-
11
- | Serviço | Status | Porta Padrão | Descrição |
12
- |---------|--------|--------------|-----------|
13
- | DynamoDB | ✅ | 8000 | Banco de dados NoSQL |
14
- | S3 | ✅ | 4566 | Armazenamento de objetos |
15
- | SQS | ✅ | 9324 | Filas de mensagens |
16
- | Lambda | ✅ | 3001 | Funções serverless |
17
- | Cognito | ✅ | 9229 | Autenticação e autorização |
18
- | API Gateway | ✅ | 4567 | APIs REST e HTTP |
19
- | ECS/Fargate | 🚧 | 8080 | Orquestração de containers (em desenvolvimento) |
20
- | SNS | 🚧 | 9911 | Notificações (em desenvolvimento) |
21
- | EventBridge | 🚧 | 4010 | Barramento de eventos (em desenvolvimento) |
22
-
23
- ## 📦 Instalação
24
-
25
- ```bash
26
- npm install --save-dev aws-local-simulator
27
- 🚀 Uso Rápido
28
- 1. Crie um arquivo de configuração aws-local-simulator.json:
29
- json
30
- {
31
- "services": {
32
- "dynamodb": true,
33
- "s3": true,
34
- "sqs": true,
35
- "lambda": true,
36
- "cognito": true,
37
- "apigateway": true
38
- },
39
- "lambdas": [
40
- {
41
- "path": "/api/users",
42
- "handler": "./src/handlers/users.js",
43
- "env": {
44
- "TABLE_NAME": "users-table"
45
- }
46
- }
47
- ],
48
- "dynamodb": {
49
- "tables": [
50
- {
51
- "TableName": "users-table",
52
- "KeySchema": [
53
- { "AttributeName": "id", "KeyType": "HASH" }
54
- ],
55
- "AttributeDefinitions": [
56
- { "AttributeName": "id", "AttributeType": "S" }
57
- ]
58
- }
59
- ]
60
- },
61
- "s3": {
62
- "buckets": ["my-bucket"]
63
- },
64
- "cognito": {
65
- "userPools": [
66
- {
67
- "PoolName": "my-user-pool",
68
- "AutoVerifiedAttributes": ["email"]
69
- }
70
- ]
71
- }
72
- }
73
- ```
74
-
75
- # 2. Inicie o simulador:
76
- ## Via CLI
77
- npx aws-local-simulator start
78
-
79
- # Ou via código
80
- const { AWSLocalSimulator } = require('aws-local-simulator');
81
- const simulator = new AWSLocalSimulator();
82
- await simulator.start();
83
-
84
- # 3. Configure seu código para usar os serviços locais:
85
-
86
- ```javascript
87
- // Importe a configuração AWS pronta
88
- const { dynamoDB, s3, sqs, cognito, apigateway } = require('aws-local-simulator/aws-config');
89
-
90
- // Use como normalmente faria
91
- await dynamoDB.send(new PutCommand({
92
- TableName: 'users-table',
93
- Item: { id: '123', name: 'John' }
94
- }));
95
- 🔧 Configuração por Variáveis de Ambiente
96
- Variável Descrição Padrão
97
- AWS_LOCAL_SIMULATOR_DYNAMODB Habilita DynamoDB true
98
- AWS_LOCAL_SIMULATOR_S3 Habilita S3 true
99
- AWS_LOCAL_SIMULATOR_SQS Habilita SQS true
100
- AWS_LOCAL_SIMULATOR_LAMBDA Habilita Lambda true
101
- AWS_LOCAL_SIMULATOR_COGNITO Habilita Cognito false
102
- AWS_LOCAL_SIMULATOR_APIGATEWAY Habilita API Gateway false
103
- AWS_LOCAL_SIMULATOR_ECS Habilita ECS/Fargate false
104
- AWS_LOCAL_SIMULATOR_DYNAMODB_PORT Porta DynamoDB 8000
105
- AWS_LOCAL_SIMULATOR_S3_PORT Porta S3 4566
106
- AWS_LOCAL_SIMULATOR_SQS_PORT Porta SQS 9324
107
- AWS_LOCAL_SIMULATOR_LAMBDA_PORT Porta Lambda 3001
108
- AWS_LOCAL_SIMULATOR_COGNITO_PORT Porta Cognito 9229
109
- AWS_LOCAL_SIMULATOR_APIGATEWAY_PORT Porta API Gateway 4567
110
- AWS_LOCAL_SIMULATOR_ECS_PORT Porta ECS 8080
111
- AWS_LOCAL_SIMULATOR_DATA Diretório de dados ./.aws-local-simulator-data
112
- AWS_LOCAL_SIMULATOR_LOG Nível de log info
113
- ```
114
-
115
- # 📝 Comandos CLI
116
- bash
117
- #### Iniciar simulador
118
- npx aws-local-simulator start [configPath]
119
-
120
- #### Parar simulador
121
- npx aws-local-simulator stop
122
-
123
- #### Reiniciar
124
- npx aws-local-simulator restart
125
-
126
- #### Resetar dados
127
- npx aws-local-simulator reset
128
-
129
- #### Status
130
- npx aws-local-simulator status
131
-
132
- # 🔌 Endpoints
133
- # Serviço Endpoint Admin
134
- DynamoDB http://localhost:8000 http://localhost:8000/__admin/tables
135
- S3 http://localhost:4566 http://localhost:4566/__admin/buckets
136
- SQS http://localhost:9324 http://localhost:9324/__admin/queues
137
- Lambda http://localhost:3001 http://localhost:3001/__admin/lambdas
138
- Cognito http://localhost:9229 http://localhost:9229/__admin/userpools
139
- API Gateway http://localhost:4567 http://localhost:4567/__admin/apis
140
- ECS http://localhost:8080 http://localhost:8080/__admin/clusters
141
- 🧪 Testando com AWS CLI
142
- bash
143
- # DynamoDB
144
- aws dynamodb list-tables --endpoint-url http://localhost:8000
145
-
146
- # S3
147
- aws s3 ls --endpoint-url http://localhost:4566
148
-
149
- # SQS
150
- aws sqs list-queues --endpoint-url http://localhost:9324
151
-
152
- # Cognito
153
- aws cognito-idp list-user-pools --max-results 10 --endpoint-url http://localhost:9229
154
-
155
- # API Gateway
156
- aws apigateway get-rest-apis --endpoint-url http://localhost:4567
157
- 📁 Estrutura de Dados
158
- Os dados são persistidos em:
159
-
160
- text
161
- .aws-local-simulator-data/
162
- ├── dynamodb/
163
- ├── s3/
164
- ├── sqs/
165
- ├── cognito/
166
- ├── apigateway/
167
- └── ecs/
168
- 🐛 Debug
169
- Para logs detalhados:
170
-
171
- bash
172
- AWS_LOCAL_SIMULATOR_LOG=verboso npx aws-local-simulator start
173
- 🤝 Contribuindo
174
- Fork o projeto
175
-
176
- Crie sua feature branch (git checkout -b feature/AmazingFeature)
177
-
178
- Commit suas mudanças (git commit -m 'Add some AmazingFeature')
179
-
180
- Push para a branch (git push origin feature/AmazingFeature)
181
-
182
- Abra um Pull Request
183
-
184
- 📄 Licença
185
- MIT © Luiz Gustavo Ribeiro
186
-
187
- ⚠️ Limitações
188
- SNS e EventBridge em desenvolvimento
189
-
190
- WebSocket APIs em desenvolvimento
191
-
192
- Para uso em desenvolvimento e testes apenas
1
+ # AWS Local Simulator
2
+
3
+ [![npm version](https://badge.fury.io/js/aws-local-simulator.svg)](https://badge.fury.io/js/aws-local-simulator)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![Node.js Version](https://img.shields.io/node/v/aws-local-simulator.svg)](https://nodejs.org)
6
+
7
+ Simulador local completo para serviços AWS. Desenvolva e teste suas aplicações AWS localmente sem custos!
8
+
9
+ ## 🚀 Serviços Suportados
10
+
11
+ | Serviço | Status | Porta Padrão | Descrição |
12
+ |---------|--------|--------------|-----------|
13
+ | DynamoDB | ✅ | 8000 | Banco de dados NoSQL |
14
+ | S3 | ✅ | 4566 | Armazenamento de objetos |
15
+ | SQS | ✅ | 9324 | Filas de mensagens |
16
+ | Lambda | ✅ | 3001 | Funções serverless |
17
+ | Cognito | ✅ | 9229 | Autenticação e autorização |
18
+ | API Gateway | ✅ | 4567 | APIs REST e HTTP |
19
+ | ECS/Fargate | 🚧 | 8080 | Orquestração de containers (em desenvolvimento) |
20
+ | SNS | 🚧 | 9911 | Notificações (em desenvolvimento) |
21
+ | EventBridge | 🚧 | 4010 | Barramento de eventos (em desenvolvimento) |
22
+
23
+ ## 📦 Instalação
24
+
25
+ ```bash
26
+ npm install --save-dev aws-local-simulator
27
+ 🚀 Uso Rápido
28
+ 1. Crie um arquivo de configuração aws-local-simulator.json:
29
+ json
30
+ {
31
+ "services": {
32
+ "dynamodb": true,
33
+ "s3": true,
34
+ "sqs": true,
35
+ "lambda": true,
36
+ "cognito": true,
37
+ "apigateway": true
38
+ },
39
+ "lambdas": [
40
+ {
41
+ "path": "/api/users",
42
+ "handler": "./src/handlers/users.js",
43
+ "env": {
44
+ "TABLE_NAME": "users-table"
45
+ }
46
+ }
47
+ ],
48
+ "dynamodb": {
49
+ "tables": [
50
+ {
51
+ "TableName": "users-table",
52
+ "KeySchema": [
53
+ { "AttributeName": "id", "KeyType": "HASH" }
54
+ ],
55
+ "AttributeDefinitions": [
56
+ { "AttributeName": "id", "AttributeType": "S" }
57
+ ]
58
+ }
59
+ ]
60
+ },
61
+ "s3": {
62
+ "buckets": ["my-bucket"]
63
+ },
64
+ "cognito": {
65
+ "userPools": [
66
+ {
67
+ "PoolName": "my-user-pool",
68
+ "AutoVerifiedAttributes": ["email"]
69
+ }
70
+ ]
71
+ }
72
+ }
73
+ ```
74
+
75
+ # 2. Inicie o simulador:
76
+ ## Via CLI
77
+ npx aws-local-simulator start
78
+
79
+ # Ou via código
80
+ const { AWSLocalSimulator } = require('aws-local-simulator');
81
+ const simulator = new AWSLocalSimulator();
82
+ await simulator.start();
83
+
84
+ # 3. Configure seu código para usar os serviços locais:
85
+
86
+ ```javascript
87
+ // Importe a configuração AWS pronta
88
+ const { dynamoDB, s3, sqs, cognito, apigateway } = require('aws-local-simulator/aws-config');
89
+
90
+ // Use como normalmente faria
91
+ await dynamoDB.send(new PutCommand({
92
+ TableName: 'users-table',
93
+ Item: { id: '123', name: 'John' }
94
+ }));
95
+ 🔧 Configuração por Variáveis de Ambiente
96
+ Variável Descrição Padrão
97
+ AWS_LOCAL_SIMULATOR_DYNAMODB Habilita DynamoDB true
98
+ AWS_LOCAL_SIMULATOR_S3 Habilita S3 true
99
+ AWS_LOCAL_SIMULATOR_SQS Habilita SQS true
100
+ AWS_LOCAL_SIMULATOR_LAMBDA Habilita Lambda true
101
+ AWS_LOCAL_SIMULATOR_COGNITO Habilita Cognito false
102
+ AWS_LOCAL_SIMULATOR_APIGATEWAY Habilita API Gateway false
103
+ AWS_LOCAL_SIMULATOR_ECS Habilita ECS/Fargate false
104
+ AWS_LOCAL_SIMULATOR_DYNAMODB_PORT Porta DynamoDB 8000
105
+ AWS_LOCAL_SIMULATOR_S3_PORT Porta S3 4566
106
+ AWS_LOCAL_SIMULATOR_SQS_PORT Porta SQS 9324
107
+ AWS_LOCAL_SIMULATOR_LAMBDA_PORT Porta Lambda 3001
108
+ AWS_LOCAL_SIMULATOR_COGNITO_PORT Porta Cognito 9229
109
+ AWS_LOCAL_SIMULATOR_APIGATEWAY_PORT Porta API Gateway 4567
110
+ AWS_LOCAL_SIMULATOR_ECS_PORT Porta ECS 8080
111
+ AWS_LOCAL_SIMULATOR_DATA Diretório de dados ./.aws-local-simulator-data
112
+ AWS_LOCAL_SIMULATOR_LOG Nível de log info
113
+ ```
114
+
115
+ # 📝 Comandos CLI
116
+ bash
117
+ #### Iniciar simulador
118
+ npx aws-local-simulator start [configPath]
119
+
120
+ #### Parar simulador
121
+ npx aws-local-simulator stop
122
+
123
+ #### Reiniciar
124
+ npx aws-local-simulator restart
125
+
126
+ #### Resetar dados
127
+ npx aws-local-simulator reset
128
+
129
+ #### Status
130
+ npx aws-local-simulator status
131
+
132
+ # 🔌 Endpoints
133
+ # Serviço Endpoint Admin
134
+ DynamoDB http://localhost:8000 http://localhost:8000/__admin/tables
135
+ S3 http://localhost:4566 http://localhost:4566/__admin/buckets
136
+ SQS http://localhost:9324 http://localhost:9324/__admin/queues
137
+ Lambda http://localhost:3001 http://localhost:3001/__admin/lambdas
138
+ Cognito http://localhost:9229 http://localhost:9229/__admin/userpools
139
+ API Gateway http://localhost:4567 http://localhost:4567/__admin/apis
140
+ ECS http://localhost:8080 http://localhost:8080/__admin/clusters
141
+ 🧪 Testando com AWS CLI
142
+ bash
143
+ # DynamoDB
144
+ aws dynamodb list-tables --endpoint-url http://localhost:8000
145
+
146
+ # S3
147
+ aws s3 ls --endpoint-url http://localhost:4566
148
+
149
+ # SQS
150
+ aws sqs list-queues --endpoint-url http://localhost:9324
151
+
152
+ # Cognito
153
+ aws cognito-idp list-user-pools --max-results 10 --endpoint-url http://localhost:9229
154
+
155
+ # API Gateway
156
+ aws apigateway get-rest-apis --endpoint-url http://localhost:4567
157
+ 📁 Estrutura de Dados
158
+ Os dados são persistidos em:
159
+
160
+ text
161
+ .aws-local-simulator-data/
162
+ ├── dynamodb/
163
+ ├── s3/
164
+ ├── sqs/
165
+ ├── cognito/
166
+ ├── apigateway/
167
+ └── ecs/
168
+ 🐛 Debug
169
+ Para logs detalhados:
170
+
171
+ bash
172
+ AWS_LOCAL_SIMULATOR_LOG=verboso npx aws-local-simulator start
173
+ 🤝 Contribuindo
174
+ Fork o projeto
175
+
176
+ Crie sua feature branch (git checkout -b feature/AmazingFeature)
177
+
178
+ Commit suas mudanças (git commit -m 'Add some AmazingFeature')
179
+
180
+ Push para a branch (git push origin feature/AmazingFeature)
181
+
182
+ Abra um Pull Request
183
+
184
+ 📄 Licença
185
+ MIT © Luiz Gustavo Ribeiro
186
+
187
+ ⚠️ Limitações
188
+ SNS e EventBridge em desenvolvimento
189
+
190
+ WebSocket APIs em desenvolvimento
191
+
192
+ Para uso em desenvolvimento e testes apenas
@@ -1,64 +1,64 @@
1
1
  #!/usr/bin/env node
2
-
3
- /**
4
- * CLI para AWS Local Simulator
5
- */
6
-
7
- const { AWSLocalSimulator } = require('../src/index');
8
- const logger = require('../src/utils/logger');
9
- const path = require('path');
10
-
11
- const command = process.argv[2];
12
- const configPath = process.argv[3];
13
-
14
- const simulator = new AWSLocalSimulator({
15
- configPath: configPath ? path.resolve(process.cwd(), configPath) : undefined
16
- });
17
-
18
- async function main() {
19
- switch (command) {
20
- case 'start':
21
- await simulator.start();
22
- break;
23
-
24
- case 'stop':
25
- await simulator.stop();
26
- break;
27
-
28
- case 'restart':
29
- await simulator.restart();
30
- break;
31
-
32
- case 'reset':
33
- await simulator.reset();
34
- break;
35
-
36
- case 'status':
37
- const status = simulator.getStatus();
38
- console.log(JSON.stringify(status, null, 2));
39
- break;
40
-
41
- case 'help':
42
- default:
43
- console.log(`
44
- AWS Local Simulator - CLI Commands:
45
- start [configPath] - Inicia o simulador
46
- stop - Para o simulador
47
- restart - Reinicia o simulador
48
- reset - Reseta todos os dados
49
- status - Mostra status dos serviços
50
- help - Mostra esta ajuda
51
-
52
- Exemplos:
53
- npx aws-local-simulator start
54
- npx aws-local-simulator start ./my-config.json
55
- AWS_LOCAL_SIMULATOR_LOG=verboso npx aws-local-simulator start
56
- `);
57
- break;
58
- }
59
- }
60
-
61
- main().catch(error => {
62
- logger.error('Erro:', error);
63
- process.exit(1);
2
+
3
+ /**
4
+ * CLI para AWS Local Simulator
5
+ */
6
+
7
+ const { AWSLocalSimulator } = require('../src/index');
8
+ const logger = require('../src/utils/logger');
9
+ const path = require('path');
10
+
11
+ const command = process.argv[2];
12
+ const configPath = process.argv[3];
13
+
14
+ const simulator = new AWSLocalSimulator({
15
+ configPath: configPath ? path.resolve(process.cwd(), configPath) : undefined
16
+ });
17
+
18
+ async function main() {
19
+ switch (command) {
20
+ case 'start':
21
+ await simulator.start();
22
+ break;
23
+
24
+ case 'stop':
25
+ await simulator.stop();
26
+ break;
27
+
28
+ case 'restart':
29
+ await simulator.restart();
30
+ break;
31
+
32
+ case 'reset':
33
+ await simulator.reset();
34
+ break;
35
+
36
+ case 'status':
37
+ const status = simulator.getStatus();
38
+ console.log(JSON.stringify(status, null, 2));
39
+ break;
40
+
41
+ case 'help':
42
+ default:
43
+ console.log(`
44
+ AWS Local Simulator - CLI Commands:
45
+ start [configPath] - Inicia o simulador
46
+ stop - Para o simulador
47
+ restart - Reinicia o simulador
48
+ reset - Reseta todos os dados
49
+ status - Mostra status dos serviços
50
+ help - Mostra esta ajuda
51
+
52
+ Exemplos:
53
+ npx aws-local-simulator start
54
+ npx aws-local-simulator start ./my-config.json
55
+ AWS_LOCAL_SIMULATOR_LOG=verboso npx aws-local-simulator start
56
+ `);
57
+ break;
58
+ }
59
+ }
60
+
61
+ main().catch(error => {
62
+ logger.error('Erro:', error);
63
+ process.exit(1);
64
64
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gugananuvem/aws-local-simulator",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Simulador local completo para serviços AWS",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -56,13 +56,16 @@
56
56
  "license": "MIT",
57
57
  "repository": {
58
58
  "type": "git",
59
- "url": "git+https://github.com/seu-usuario/aws-local-simulator.git"
59
+ "url": "git+https://github.com/gugananuvem/aws-local-simulator.git"
60
60
  },
61
61
  "engines": {
62
62
  "node": ">=14.0.0"
63
63
  },
64
64
  "files": [
65
- "dist/"
65
+ "src/",
66
+ "bin/",
67
+ "README.md",
68
+ "LICENSE"
66
69
  ],
67
70
  "publishConfig": {
68
71
  "directory": "dist"
@@ -105,6 +108,6 @@
105
108
  "optional": true
106
109
  }
107
110
  },
108
- "buildDate": "2026-03-29T01:01:59.763Z",
111
+ "buildDate": "2026-03-29T01:32:28.891Z",
109
112
  "published": true
110
- }
113
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Carrega configurações do usuário
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const defaultConfig = require('./default-config');
8
+ const EnvLoader = require('./env-loader');
9
+ const logger = require('../utils/logger');
10
+
11
+ class ConfigLoader {
12
+ static async load(configPath) {
13
+ logger.info('📝 Carregando configurações...');
14
+
15
+ // 1. Carrega configurações padrão
16
+ let config = { ...defaultConfig };
17
+
18
+ // 2. Sobrescreve com variáveis de ambiente
19
+ const envConfig = EnvLoader.load();
20
+ config = this.mergeDeep(config, envConfig);
21
+
22
+ // 3. Sobrescreve com arquivo de configuração do usuário se existir
23
+ if (configPath) {
24
+ const userConfig = await this.loadUserConfig(configPath);
25
+ config = this.mergeDeep(config, userConfig);
26
+ } else {
27
+ // Tenta encontrar arquivo de configuração padrão
28
+ const possiblePaths = [
29
+ path.join(process.cwd(), 'aws-local-simulator.json'),
30
+ path.join(process.cwd(), 'aws-local-simulator.config.json'),
31
+ path.join(process.cwd(), '.aws-local-simulator.json')
32
+ ];
33
+
34
+ for (const possiblePath of possiblePaths) {
35
+ if (fs.existsSync(possiblePath)) {
36
+ const userConfig = await this.loadUserConfig(possiblePath);
37
+ config = this.mergeDeep(config, userConfig);
38
+ logger.info(`✅ Configuração carregada de: ${possiblePath}`);
39
+ break;
40
+ }
41
+ }
42
+ }
43
+
44
+ // 4. Valida configurações
45
+ this.validate(config);
46
+
47
+ logger.info(`✅ Configurações carregadas (logLevel: ${config.logLevel})`);
48
+
49
+ return config;
50
+ }
51
+
52
+ static async loadUserConfig(filePath) {
53
+ try {
54
+ const fullPath = path.resolve(process.cwd(), filePath);
55
+
56
+ if (!fs.existsSync(fullPath)) {
57
+ logger.warn(`Arquivo de configuração não encontrado: ${fullPath}`);
58
+ return {};
59
+ }
60
+
61
+ const content = fs.readFileSync(fullPath, 'utf8');
62
+ const config = JSON.parse(content);
63
+
64
+ return config;
65
+ } catch (error) {
66
+ logger.error(`Erro ao carregar configuração de ${filePath}:`, error);
67
+ throw error;
68
+ }
69
+ }
70
+
71
+ static validate(config) {
72
+ // Valida serviços
73
+ const enabledServices = Object.entries(config.services)
74
+ .filter(([_, enabled]) => enabled)
75
+ .map(([name]) => name);
76
+
77
+ if (enabledServices.length === 0) {
78
+ logger.warn('⚠️ Nenhum serviço está habilitado!');
79
+ } else {
80
+ logger.info(`📦 Serviços habilitados: ${enabledServices.join(', ')}`);
81
+ }
82
+
83
+ // Valida diretório de dados
84
+ if (!config.dataDir) {
85
+ throw new Error('dataDir não configurado');
86
+ }
87
+
88
+ // Valida portas
89
+ for (const [service, port] of Object.entries(config.ports)) {
90
+ if (config.services[service] && (port < 1 || port > 65535)) {
91
+ throw new Error(`Porta inválida para ${service}: ${port}`);
92
+ }
93
+ }
94
+ }
95
+
96
+ static mergeDeep(target, source) {
97
+ const output = { ...target };
98
+
99
+ for (const key in source) {
100
+ if (source.hasOwnProperty(key)) {
101
+ if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
102
+ output[key] = this.mergeDeep(target[key] || {}, source[key]);
103
+ } else {
104
+ output[key] = source[key];
105
+ }
106
+ }
107
+ }
108
+
109
+ return output;
110
+ }
111
+ }
112
+
113
+ module.exports = { loadConfig: ConfigLoader.load.bind(ConfigLoader) };