@gugananuvem/aws-local-simulator 1.0.10 → 1.0.12

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 (44) hide show
  1. package/README.md +257 -193
  2. package/bin/aws-local-simulator.js +62 -62
  3. package/package.json +2 -2
  4. package/src/config/config-loader.js +114 -112
  5. package/src/config/default-config.js +67 -65
  6. package/src/config/env-loader.js +68 -68
  7. package/src/index.js +130 -130
  8. package/src/index.mjs +123 -123
  9. package/src/server.js +223 -222
  10. package/src/services/apigateway/index.js +68 -66
  11. package/src/services/apigateway/server.js +487 -434
  12. package/src/services/apigateway/simulator.js +1251 -1251
  13. package/src/services/cognito/index.js +65 -65
  14. package/src/services/cognito/server.js +279 -228
  15. package/src/services/cognito/simulator.js +1114 -847
  16. package/src/services/dynamodb/index.js +70 -70
  17. package/src/services/dynamodb/server.js +121 -121
  18. package/src/services/dynamodb/simulator.js +620 -614
  19. package/src/services/ecs/index.js +65 -65
  20. package/src/services/ecs/server.js +233 -233
  21. package/src/services/ecs/simulator.js +844 -844
  22. package/src/services/eventbridge/index.js +84 -84
  23. package/src/services/index.js +18 -18
  24. package/src/services/lambda/handler-loader.js +183 -172
  25. package/src/services/lambda/index.js +73 -72
  26. package/src/services/lambda/route-registry.js +274 -274
  27. package/src/services/lambda/server.js +145 -152
  28. package/src/services/lambda/simulator.js +172 -285
  29. package/src/services/s3/index.js +69 -69
  30. package/src/services/s3/server.js +238 -238
  31. package/src/services/s3/simulator.js +740 -740
  32. package/src/services/sns/index.js +75 -75
  33. package/src/services/sqs/index.js +95 -95
  34. package/src/services/sqs/server.js +345 -273
  35. package/src/services/sqs/simulator.js +441 -660
  36. package/src/services/sts/index.js +37 -0
  37. package/src/services/sts/server.js +142 -0
  38. package/src/services/sts/simulator.js +69 -0
  39. package/src/template/aws-config-template.js +87 -87
  40. package/src/template/aws-config-template.mjs +90 -90
  41. package/src/template/config-template.json +203 -203
  42. package/src/utils/aws-config.js +91 -91
  43. package/src/utils/local-store.js +67 -67
  44. package/src/utils/logger.js +59 -59
@@ -1,85 +1,85 @@
1
- /**
2
- * EventBridge Service - Ponto de entrada (Stub para implementação futura)
3
- */
4
-
5
- const logger = require('../../utils/logger');
6
-
7
- class EventBridgeService {
8
- constructor(config) {
9
- this.config = config;
10
- this.name = 'eventbridge';
11
- this.port = config.ports.eventbridge;
12
- this.isRunning = false;
13
- this.buses = new Map();
14
- this.events = [];
15
- }
16
-
17
- async initialize() {
18
- logger.debug(`Inicializando EventBridge Service na porta ${this.port}...`);
19
- logger.warn('⚠️ EventBridge Service ainda não está completamente implementado');
20
-
21
- // TODO: Implementar EventBridge simulator
22
- this.buses = new Map();
23
- this.events = [];
24
- }
25
-
26
- async start() {
27
- if (this.isRunning) return;
28
-
29
- // TODO: Iniciar servidor HTTP para EventBridge
30
- this.isRunning = true;
31
- logger.info(`🎯 EventBridge Service stub rodando (porta ${this.port}) - Implementação em breve`);
32
- }
33
-
34
- async stop() {
35
- if (!this.isRunning) return;
36
- this.isRunning = false;
37
- }
38
-
39
- async reset() {
40
- this.buses.clear();
41
- this.events = [];
42
- logger.debug('EventBridge: Todos os dados resetados');
43
- }
44
-
45
- getStatus() {
46
- return {
47
- running: this.isRunning,
48
- port: this.port,
49
- endpoint: `http://localhost:${this.port}`,
50
- implemented: false,
51
- busesCount: this.buses.size,
52
- eventsCount: this.events.length
53
- };
54
- }
55
-
56
- // Métodos stub para compatibilidade
57
- async createEventBus(name) {
58
- if (!this.buses.has(name)) {
59
- this.buses.set(name, {
60
- name,
61
- arn: `arn:aws:events:local:000000000000:event-bus/${name}`,
62
- createdAt: new Date().toISOString()
63
- });
64
- }
65
- return this.buses.get(name);
66
- }
67
-
68
- async putEvents(entries) {
69
- const results = [];
70
- for (const entry of entries) {
71
- const eventId = Math.random().toString(36).substring(7);
72
- this.events.push({
73
- ...entry,
74
- eventId,
75
- time: new Date().toISOString(),
76
- receivedAt: new Date().toISOString()
77
- });
78
- results.push({ EventId: eventId });
79
- logger.verboso(`EventBridge: Event ${eventId} published to ${entry.EventBusName || 'default'}`);
80
- }
81
- return { Entries: results, FailedEntryCount: 0 };
82
- }
83
- }
84
-
1
+ /**
2
+ * EventBridge Service - Ponto de entrada (Stub para implementação futura)
3
+ */
4
+
5
+ const logger = require('../../utils/logger');
6
+
7
+ class EventBridgeService {
8
+ constructor(config) {
9
+ this.config = config;
10
+ this.name = 'eventbridge';
11
+ this.port = config.ports.eventbridge;
12
+ this.isRunning = false;
13
+ this.buses = new Map();
14
+ this.events = [];
15
+ }
16
+
17
+ async initialize() {
18
+ logger.debug(`Inicializando EventBridge Service na porta ${this.port}...`);
19
+ logger.warn('⚠️ EventBridge Service ainda não está completamente implementado');
20
+
21
+ // TODO: Implementar EventBridge simulator
22
+ this.buses = new Map();
23
+ this.events = [];
24
+ }
25
+
26
+ async start() {
27
+ if (this.isRunning) return;
28
+
29
+ // TODO: Iniciar servidor HTTP para EventBridge
30
+ this.isRunning = true;
31
+ logger.info(`🎯 EventBridge Service stub rodando (porta ${this.port}) - Implementação em breve`);
32
+ }
33
+
34
+ async stop() {
35
+ if (!this.isRunning) return;
36
+ this.isRunning = false;
37
+ }
38
+
39
+ async reset() {
40
+ this.buses.clear();
41
+ this.events = [];
42
+ logger.debug('EventBridge: Todos os dados resetados');
43
+ }
44
+
45
+ getStatus() {
46
+ return {
47
+ running: this.isRunning,
48
+ port: this.port,
49
+ endpoint: `http://localhost:${this.port}`,
50
+ implemented: false,
51
+ busesCount: this.buses.size,
52
+ eventsCount: this.events.length
53
+ };
54
+ }
55
+
56
+ // Métodos stub para compatibilidade
57
+ async createEventBus(name) {
58
+ if (!this.buses.has(name)) {
59
+ this.buses.set(name, {
60
+ name,
61
+ arn: `arn:aws:events:local:000000000000:event-bus/${name}`,
62
+ createdAt: new Date().toISOString()
63
+ });
64
+ }
65
+ return this.buses.get(name);
66
+ }
67
+
68
+ async putEvents(entries) {
69
+ const results = [];
70
+ for (const entry of entries) {
71
+ const eventId = Math.random().toString(36).substring(7);
72
+ this.events.push({
73
+ ...entry,
74
+ eventId,
75
+ time: new Date().toISOString(),
76
+ receivedAt: new Date().toISOString()
77
+ });
78
+ results.push({ EventId: eventId });
79
+ logger.verboso(`EventBridge: Event ${eventId} published to ${entry.EventBusName || 'default'}`);
80
+ }
81
+ return { Entries: results, FailedEntryCount: 0 };
82
+ }
83
+ }
84
+
85
85
  module.exports = EventBridgeService;
@@ -1,19 +1,19 @@
1
- /**
2
- * Barrel export para todos os serviços
3
- */
4
-
5
- const DynamoDBService = require('./dynamodb');
6
- const S3Service = require('./s3');
7
- const SQSService = require('./sqs');
8
- const LambdaService = require('./lambda');
9
- const SNSService = require('./sns');
10
- const EventBridgeService = require('./eventbridge');
11
-
12
- module.exports = {
13
- DynamoDBService,
14
- S3Service,
15
- SQSService,
16
- LambdaService,
17
- SNSService,
18
- EventBridgeService
1
+ /**
2
+ * Barrel export para todos os serviços
3
+ */
4
+
5
+ const DynamoDBService = require('./dynamodb');
6
+ const S3Service = require('./s3');
7
+ const SQSService = require('./sqs');
8
+ const LambdaService = require('./lambda');
9
+ const SNSService = require('./sns');
10
+ const EventBridgeService = require('./eventbridge');
11
+
12
+ module.exports = {
13
+ DynamoDBService,
14
+ S3Service,
15
+ SQSService,
16
+ LambdaService,
17
+ SNSService,
18
+ EventBridgeService
19
19
  };
@@ -1,173 +1,184 @@
1
- /**
2
- * Handler Loader - Carrega handlers de Lambda em diferentes formatos
3
- * Suporta: CommonJS, ES Modules, TypeScript (compilado)
4
- */
5
-
6
- const path = require('path');
7
- const fs = require('fs');
8
- const { pathToFileURL } = require('url');
9
- const logger = require('../../utils/logger');
10
-
11
- class HandlerLoader {
12
- /**
13
- * Carrega um handler de Lambda
14
- * @param {string} handlerPath - Caminho para o arquivo do handler
15
- * @param {string} type - Tipo do módulo: 'commonjs', 'module', 'auto'
16
- * @returns {Promise<Function>} - Função handler
17
- */
18
- static async load(handlerPath, type = 'auto') {
19
- const fullPath = path.resolve(process.cwd(), handlerPath);
20
-
21
- if (!fs.existsSync(fullPath)) {
22
- throw new Error(`Handler não encontrado: ${fullPath}`);
23
- }
24
-
25
- logger.verboso(`Carregando handler: ${fullPath} (type: ${type})`);
26
-
27
- try {
28
- let handler;
29
- let resolvedType = type;
30
-
31
- // Detecta o tipo se for auto
32
- if (type === 'auto') {
33
- resolvedType = this.detectType(fullPath);
34
- }
35
-
36
- // Carrega baseado no tipo
37
- if (resolvedType === 'module' || fullPath.endsWith('.mjs')) {
38
- // ES Module
39
- const fileUrl = pathToFileURL(fullPath).href;
40
- const module = await import(fileUrl);
41
- handler = this.extractHandler(module);
42
- } else {
43
- // CommonJS
44
- // Limpa o cache para permitir hot reload em desenvolvimento
45
- if (process.env.NODE_ENV === 'development') {
46
- delete require.cache[require.resolve(fullPath)];
47
- }
48
- const module = require(fullPath);
49
- handler = this.extractHandler(module);
50
- }
51
-
52
- if (typeof handler !== 'function') {
53
- throw new Error(`Handler não é uma função em ${fullPath}. Exporte uma função ou um objeto com handler.`);
54
- }
55
-
56
- logger.debug(`✅ Handler carregado: ${fullPath}`);
57
-
58
- return handler;
59
-
60
- } catch (error) {
61
- logger.error(`❌ Erro ao carregar handler ${fullPath}:`, error);
62
- throw error;
63
- }
64
- }
65
-
66
- /**
67
- * Extrai a função handler de um módulo
68
- * Suporta: module.exports = handler, exports.handler, export default
69
- */
70
- static extractHandler(module) {
71
- // Verifica se é export default
72
- if (module.default && typeof module.default === 'function') {
73
- return module.default;
74
- }
75
-
76
- // Verifica se é exports.handler
77
- if (module.handler && typeof module.handler === 'function') {
78
- return module.handler;
79
- }
80
-
81
- // Verifica se o módulo inteiro é uma função
82
- if (typeof module === 'function') {
83
- return module;
84
- }
85
-
86
- // Tenta encontrar a primeira função exportada
87
- const exportedFunctions = Object.values(module).filter(v => typeof v === 'function');
88
- if (exportedFunctions.length === 1) {
89
- logger.warn(`⚠️ Usando a primeira função exportada como handler: ${exportedFunctions[0].name}`);
90
- return exportedFunctions[0];
91
- }
92
-
93
- // Se tem múltiplas funções, tenta encontrar uma chamada 'handler'
94
- if (module.handler) {
95
- return module.handler;
96
- }
97
-
98
- throw new Error('Não foi possível encontrar uma função handler no módulo');
99
- }
100
-
101
- /**
102
- * Detecta o tipo de módulo (CommonJS ou ES Module)
103
- */
104
- static detectType(filePath) {
105
- // Verifica extensão
106
- if (filePath.endsWith('.mjs')) {
107
- return 'module';
108
- }
109
- if (filePath.endsWith('.cjs')) {
110
- return 'commonjs';
111
- }
112
-
113
- // Verifica package.json na mesma pasta ou superior
114
- try {
115
- let currentDir = path.dirname(filePath);
116
- while (currentDir !== path.parse(currentDir).root) {
117
- const packageJsonPath = path.join(currentDir, 'package.json');
118
- if (fs.existsSync(packageJsonPath)) {
119
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
120
- if (packageJson.type === 'module') {
121
- return 'module';
122
- }
123
- break;
124
- }
125
- currentDir = path.dirname(currentDir);
126
- }
127
- } catch (error) {
128
- // Ignora erro
129
- }
130
-
131
- return 'commonjs';
132
- }
133
-
134
- /**
135
- * Recarrega um handler (útil para hot reload)
136
- */
137
- static async reload(handlerPath, type = 'auto') {
138
- // Limpa cache
139
- const fullPath = path.resolve(process.cwd(), handlerPath);
140
- delete require.cache[require.resolve(fullPath)];
141
-
142
- // Recarrega
143
- return this.load(handlerPath, type);
144
- }
145
-
146
- /**
147
- * Valida se um caminho de handler é válido
148
- */
149
- static isValid(handlerPath) {
150
- const fullPath = path.resolve(process.cwd(), handlerPath);
151
- return fs.existsSync(fullPath);
152
- }
153
-
154
- /**
155
- * Retorna informações sobre o handler
156
- */
157
- static async getInfo(handlerPath) {
158
- const fullPath = path.resolve(process.cwd(), handlerPath);
159
- const type = this.detectType(fullPath);
160
- const stats = fs.statSync(fullPath);
161
-
162
- return {
163
- path: fullPath,
164
- type,
165
- exists: fs.existsSync(fullPath),
166
- size: stats.size,
167
- modified: stats.mtime,
168
- isValid: this.isValid(handlerPath)
169
- };
170
- }
171
- }
172
-
1
+ /**
2
+ * Handler Loader - Carrega handlers de Lambda em diferentes formatos
3
+ * Suporta: CommonJS, ES Modules, TypeScript (compilado)
4
+ */
5
+
6
+ const path = require('path');
7
+ const fs = require('fs');
8
+ const { pathToFileURL } = require('url');
9
+ const logger = require('../../utils/logger');
10
+
11
+ class HandlerLoader {
12
+ /**
13
+ * Carrega um handler de Lambda
14
+ * @param {string} handlerPath - Caminho para o arquivo do handler
15
+ * @param {string} type - Tipo do módulo: 'commonjs', 'module', 'auto'
16
+ * @returns {Promise<Function>} - Função handler
17
+ */
18
+ static async load(handlerPath, type = 'auto') {
19
+ // Resolve path: try cwd first, then data dir
20
+ let fullPath = path.resolve(process.cwd(), handlerPath);
21
+
22
+ if (!fs.existsSync(fullPath)) {
23
+ const dataDir = process.env.AWS_LOCAL_SIMULATOR_DATA_DIR;
24
+ if (dataDir) {
25
+ const dataPath = path.resolve(dataDir, 'lambda', handlerPath.replace(/^\.\//, ''));
26
+ if (fs.existsSync(dataPath)) {
27
+ fullPath = dataPath;
28
+ }
29
+ }
30
+ }
31
+
32
+ if (!fs.existsSync(fullPath)) {
33
+ throw new Error(`Handler não encontrado: ${fullPath}`);
34
+ }
35
+
36
+ logger.verboso(`Carregando handler: ${fullPath} (type: ${type})`);
37
+
38
+ try {
39
+ let handler;
40
+ let resolvedType = type;
41
+
42
+ // Detecta o tipo se for auto
43
+ if (type === 'auto') {
44
+ resolvedType = this.detectType(fullPath);
45
+ }
46
+
47
+ // Carrega baseado no tipo
48
+ if (resolvedType === 'module' || fullPath.endsWith('.mjs')) {
49
+ // ES Module
50
+ const fileUrl = pathToFileURL(fullPath).href;
51
+ const module = await import(fileUrl);
52
+ handler = this.extractHandler(module);
53
+ } else {
54
+ // CommonJS
55
+ // Limpa o cache para permitir hot reload em desenvolvimento
56
+ if (process.env.NODE_ENV === 'development') {
57
+ delete require.cache[require.resolve(fullPath)];
58
+ }
59
+ const module = require(fullPath);
60
+ handler = this.extractHandler(module);
61
+ }
62
+
63
+ if (typeof handler !== 'function') {
64
+ throw new Error(`Handler não é uma função em ${fullPath}. Exporte uma função ou um objeto com handler.`);
65
+ }
66
+
67
+ logger.debug(`✅ Handler carregado: ${fullPath}`);
68
+
69
+ return handler;
70
+
71
+ } catch (error) {
72
+ logger.error(`❌ Erro ao carregar handler ${fullPath}:`, error);
73
+ throw error;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Extrai a função handler de um módulo
79
+ * Suporta: module.exports = handler, exports.handler, export default
80
+ */
81
+ static extractHandler(module) {
82
+ // Verifica se é export default
83
+ if (module.default && typeof module.default === 'function') {
84
+ return module.default;
85
+ }
86
+
87
+ // Verifica se é exports.handler
88
+ if (module.handler && typeof module.handler === 'function') {
89
+ return module.handler;
90
+ }
91
+
92
+ // Verifica se o módulo inteiro é uma função
93
+ if (typeof module === 'function') {
94
+ return module;
95
+ }
96
+
97
+ // Tenta encontrar a primeira função exportada
98
+ const exportedFunctions = Object.values(module).filter(v => typeof v === 'function');
99
+ if (exportedFunctions.length === 1) {
100
+ logger.warn(`⚠️ Usando a primeira função exportada como handler: ${exportedFunctions[0].name}`);
101
+ return exportedFunctions[0];
102
+ }
103
+
104
+ // Se tem múltiplas funções, tenta encontrar uma chamada 'handler'
105
+ if (module.handler) {
106
+ return module.handler;
107
+ }
108
+
109
+ throw new Error('Não foi possível encontrar uma função handler no módulo');
110
+ }
111
+
112
+ /**
113
+ * Detecta o tipo de módulo (CommonJS ou ES Module)
114
+ */
115
+ static detectType(filePath) {
116
+ // Verifica extensão
117
+ if (filePath.endsWith('.mjs')) {
118
+ return 'module';
119
+ }
120
+ if (filePath.endsWith('.cjs')) {
121
+ return 'commonjs';
122
+ }
123
+
124
+ // Verifica package.json na mesma pasta ou superior
125
+ try {
126
+ let currentDir = path.dirname(filePath);
127
+ while (currentDir !== path.parse(currentDir).root) {
128
+ const packageJsonPath = path.join(currentDir, 'package.json');
129
+ if (fs.existsSync(packageJsonPath)) {
130
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
131
+ if (packageJson.type === 'module') {
132
+ return 'module';
133
+ }
134
+ break;
135
+ }
136
+ currentDir = path.dirname(currentDir);
137
+ }
138
+ } catch (error) {
139
+ // Ignora erro
140
+ }
141
+
142
+ return 'commonjs';
143
+ }
144
+
145
+ /**
146
+ * Recarrega um handler (útil para hot reload)
147
+ */
148
+ static async reload(handlerPath, type = 'auto') {
149
+ // Limpa cache
150
+ const fullPath = path.resolve(process.cwd(), handlerPath);
151
+ delete require.cache[require.resolve(fullPath)];
152
+
153
+ // Recarrega
154
+ return this.load(handlerPath, type);
155
+ }
156
+
157
+ /**
158
+ * Valida se um caminho de handler é válido
159
+ */
160
+ static isValid(handlerPath) {
161
+ const fullPath = path.resolve(process.cwd(), handlerPath);
162
+ return fs.existsSync(fullPath);
163
+ }
164
+
165
+ /**
166
+ * Retorna informações sobre o handler
167
+ */
168
+ static async getInfo(handlerPath) {
169
+ const fullPath = path.resolve(process.cwd(), handlerPath);
170
+ const type = this.detectType(fullPath);
171
+ const stats = fs.statSync(fullPath);
172
+
173
+ return {
174
+ path: fullPath,
175
+ type,
176
+ exists: fs.existsSync(fullPath),
177
+ size: stats.size,
178
+ modified: stats.mtime,
179
+ isValid: this.isValid(handlerPath)
180
+ };
181
+ }
182
+ }
183
+
173
184
  module.exports = HandlerLoader;