@friggframework/devtools 2.0.0-next.47 → 2.0.0-next.48

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 (69) hide show
  1. package/frigg-cli/README.md +1290 -0
  2. package/frigg-cli/__tests__/unit/commands/build.test.js +279 -0
  3. package/frigg-cli/__tests__/unit/commands/db-setup.test.js +548 -0
  4. package/frigg-cli/__tests__/unit/commands/deploy.test.js +320 -0
  5. package/frigg-cli/__tests__/unit/commands/doctor.test.js +309 -0
  6. package/frigg-cli/__tests__/unit/commands/install.test.js +400 -0
  7. package/frigg-cli/__tests__/unit/commands/ui.test.js +346 -0
  8. package/frigg-cli/__tests__/unit/dependencies.test.js +74 -0
  9. package/frigg-cli/__tests__/unit/utils/database-validator.test.js +366 -0
  10. package/frigg-cli/__tests__/unit/utils/error-messages.test.js +304 -0
  11. package/frigg-cli/__tests__/unit/version-detection.test.js +171 -0
  12. package/frigg-cli/__tests__/utils/mock-factory.js +270 -0
  13. package/frigg-cli/__tests__/utils/prisma-mock.js +194 -0
  14. package/frigg-cli/__tests__/utils/test-fixtures.js +463 -0
  15. package/frigg-cli/__tests__/utils/test-setup.js +287 -0
  16. package/frigg-cli/build-command/index.js +66 -0
  17. package/frigg-cli/db-setup-command/index.js +193 -0
  18. package/frigg-cli/deploy-command/SPEC-DEPLOY-DRY-RUN.md +981 -0
  19. package/frigg-cli/deploy-command/index.js +302 -0
  20. package/frigg-cli/doctor-command/index.js +335 -0
  21. package/frigg-cli/generate-command/__tests__/generate-command.test.js +301 -0
  22. package/frigg-cli/generate-command/azure-generator.js +43 -0
  23. package/frigg-cli/generate-command/gcp-generator.js +47 -0
  24. package/frigg-cli/generate-command/index.js +332 -0
  25. package/frigg-cli/generate-command/terraform-generator.js +555 -0
  26. package/frigg-cli/generate-iam-command.js +118 -0
  27. package/frigg-cli/index.js +173 -0
  28. package/frigg-cli/index.test.js +158 -0
  29. package/frigg-cli/init-command/backend-first-handler.js +756 -0
  30. package/frigg-cli/init-command/index.js +93 -0
  31. package/frigg-cli/init-command/template-handler.js +143 -0
  32. package/frigg-cli/install-command/backend-js.js +33 -0
  33. package/frigg-cli/install-command/commit-changes.js +16 -0
  34. package/frigg-cli/install-command/environment-variables.js +127 -0
  35. package/frigg-cli/install-command/environment-variables.test.js +136 -0
  36. package/frigg-cli/install-command/index.js +54 -0
  37. package/frigg-cli/install-command/install-package.js +13 -0
  38. package/frigg-cli/install-command/integration-file.js +30 -0
  39. package/frigg-cli/install-command/logger.js +12 -0
  40. package/frigg-cli/install-command/template.js +90 -0
  41. package/frigg-cli/install-command/validate-package.js +75 -0
  42. package/frigg-cli/jest.config.js +124 -0
  43. package/frigg-cli/package.json +63 -0
  44. package/frigg-cli/repair-command/index.js +564 -0
  45. package/frigg-cli/start-command/index.js +149 -0
  46. package/frigg-cli/start-command/start-command.test.js +297 -0
  47. package/frigg-cli/test/init-command.test.js +180 -0
  48. package/frigg-cli/test/npm-registry.test.js +319 -0
  49. package/frigg-cli/ui-command/index.js +154 -0
  50. package/frigg-cli/utils/app-resolver.js +319 -0
  51. package/frigg-cli/utils/backend-path.js +25 -0
  52. package/frigg-cli/utils/database-validator.js +154 -0
  53. package/frigg-cli/utils/error-messages.js +257 -0
  54. package/frigg-cli/utils/npm-registry.js +167 -0
  55. package/frigg-cli/utils/process-manager.js +199 -0
  56. package/frigg-cli/utils/repo-detection.js +405 -0
  57. package/infrastructure/create-frigg-infrastructure.js +125 -12
  58. package/infrastructure/docs/PRE-DEPLOYMENT-HEALTH-CHECK-SPEC.md +1317 -0
  59. package/infrastructure/domains/shared/resource-discovery.enhanced.test.js +306 -0
  60. package/infrastructure/domains/shared/resource-discovery.js +31 -2
  61. package/infrastructure/domains/shared/utilities/base-definition-factory.js +1 -1
  62. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +109 -5
  63. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +310 -4
  64. package/infrastructure/domains/shared/validation/plugin-validator.js +187 -0
  65. package/infrastructure/domains/shared/validation/plugin-validator.test.js +323 -0
  66. package/infrastructure/infrastructure-composer.js +22 -0
  67. package/layers/prisma/.build-complete +3 -0
  68. package/package.json +18 -7
  69. package/management-ui/package-lock.json +0 -16517
@@ -0,0 +1,257 @@
1
+ const chalk = require('chalk');
2
+
3
+ /**
4
+ * Error Messages Module
5
+ * Provides helpful, context-aware error messages for database setup issues
6
+ */
7
+
8
+ /**
9
+ * Database URL examples for both supported database types
10
+ */
11
+ const DATABASE_URL_EXAMPLES = {
12
+ mongodb: 'mongodb://localhost:27017/frigg?replicaSet=rs0',
13
+ postgresql: 'postgresql://postgres:postgres@localhost:5432/frigg?schema=public'
14
+ };
15
+
16
+ /**
17
+ * Gets helpful error message for missing DATABASE_URL
18
+ * @returns {string} Formatted error message
19
+ */
20
+ function getDatabaseUrlMissingError() {
21
+ return `
22
+ ${chalk.red('❌ DATABASE_URL environment variable not found')}
23
+
24
+ ${chalk.bold('Add DATABASE_URL to your .env file:')}
25
+
26
+ ${chalk.cyan('For MongoDB:')}
27
+ ${chalk.gray('DATABASE_URL')}=${chalk.green(`"${DATABASE_URL_EXAMPLES.mongodb}"`)}
28
+
29
+ ${chalk.cyan('For PostgreSQL:')}
30
+ ${chalk.gray('DATABASE_URL')}=${chalk.green(`"${DATABASE_URL_EXAMPLES.postgresql}"`)}
31
+
32
+ ${chalk.yellow('Then run:')} ${chalk.cyan('frigg db:setup')}
33
+ `;
34
+ }
35
+
36
+ /**
37
+ * Gets helpful error message for missing database type configuration
38
+ * @returns {string} Formatted error message
39
+ */
40
+ function getDatabaseTypeNotConfiguredError() {
41
+ return `
42
+ ${chalk.red('❌ Database type not configured in app definition')}
43
+
44
+ ${chalk.bold('Add database configuration to your app definition file:')}
45
+ ${chalk.gray('(backend/index.js or index.js)')}
46
+
47
+ ${chalk.cyan('For PostgreSQL:')}
48
+ ${chalk.gray(`
49
+ const appDefinition = {
50
+ // ... other configuration
51
+ database: {
52
+ postgres: { enable: true }
53
+ }
54
+ };
55
+ `)}
56
+
57
+ ${chalk.cyan('For MongoDB:')}
58
+ ${chalk.gray(`
59
+ const appDefinition = {
60
+ // ... other configuration
61
+ database: {
62
+ mongoDB: { enable: true }
63
+ }
64
+ };
65
+ `)}
66
+
67
+ ${chalk.cyan('For AWS DocumentDB (MongoDB-compatible):')}
68
+ ${chalk.gray(`
69
+ const appDefinition = {
70
+ // ... other configuration
71
+ database: {
72
+ documentDB: { enable: true }
73
+ }
74
+ };
75
+ `)}
76
+ `;
77
+ }
78
+
79
+ /**
80
+ * Gets helpful error message for database connection failure
81
+ * @param {string} error - Connection error message
82
+ * @param {'mongodb'|'postgresql'} dbType - Database type
83
+ * @returns {string} Formatted error message
84
+ */
85
+ function getDatabaseConnectionError(error, dbType) {
86
+ const troubleshootingSteps = dbType === 'mongodb'
87
+ ? getMongoDatabaseTroubleshooting()
88
+ : getPostgresTroubleshooting();
89
+
90
+ return `
91
+ ${chalk.red('❌ Failed to connect to database')}
92
+
93
+ ${chalk.bold('Connection error:')}
94
+ ${chalk.gray(error)}
95
+
96
+ ${chalk.bold('Troubleshooting steps:')}
97
+ ${troubleshootingSteps}
98
+
99
+ ${chalk.yellow('Verify your DATABASE_URL:')} ${chalk.cyan(process.env.DATABASE_URL || 'not set')}
100
+ `;
101
+ }
102
+
103
+ /**
104
+ * Gets MongoDB-specific troubleshooting steps
105
+ * @returns {string} Formatted troubleshooting steps
106
+ */
107
+ function getMongoDatabaseTroubleshooting() {
108
+ return `
109
+ ${chalk.gray('1.')} Verify MongoDB is running
110
+ ${chalk.cyan('docker ps')} ${chalk.gray('(if using Docker)')}
111
+ ${chalk.cyan('mongosh --eval "db.version()"')} ${chalk.gray('(test connection)')}
112
+
113
+ ${chalk.gray('2.')} Check if replica set is initialized
114
+ ${chalk.gray('MongoDB requires a replica set for Prisma')}
115
+ ${chalk.cyan('mongosh')}
116
+ ${chalk.cyan('rs.status()')} ${chalk.gray('(should show replica set info)')}
117
+
118
+ ${chalk.gray('3.')} Initialize replica set if needed
119
+ ${chalk.cyan('docker exec -it <mongodb-container> mongosh')}
120
+ ${chalk.cyan('rs.initiate()')}
121
+
122
+ ${chalk.gray('4.')} Verify connection string format
123
+ ${chalk.gray('mongodb://[username:password@]host[:port]/database[?options]')}
124
+ ${chalk.green('Example: mongodb://localhost:27017/frigg?replicaSet=rs0')}
125
+
126
+ ${chalk.gray('5.')} Check network/firewall settings
127
+ ${chalk.gray('Ensure port 27017 (default) is accessible')}
128
+ `;
129
+ }
130
+
131
+ /**
132
+ * Gets PostgreSQL-specific troubleshooting steps
133
+ * @returns {string} Formatted troubleshooting steps
134
+ */
135
+ function getPostgresTroubleshooting() {
136
+ return `
137
+ ${chalk.gray('1.')} Verify PostgreSQL is running
138
+ ${chalk.cyan('docker ps')} ${chalk.gray('(if using Docker)')}
139
+ ${chalk.cyan('pg_isready')} ${chalk.gray('(test if server is ready)')}
140
+
141
+ ${chalk.gray('2.')} Check connection string format
142
+ ${chalk.gray('postgresql://[username:password@]host[:port]/database[?options]')}
143
+ ${chalk.green('Example: postgresql://postgres:postgres@localhost:5432/frigg?schema=public')}
144
+
145
+ ${chalk.gray('3.')} Verify database exists
146
+ ${chalk.cyan('psql -U postgres -l')} ${chalk.gray('(list databases)')}
147
+ ${chalk.cyan('CREATE DATABASE frigg;')} ${chalk.gray('(if needed)')}
148
+
149
+ ${chalk.gray('4.')} Check pg_hba.conf allows connections
150
+ ${chalk.gray('Location: /var/lib/postgresql/data/pg_hba.conf (Docker)')}
151
+ ${chalk.gray('Ensure trust/md5 authentication is enabled for your host')}
152
+
153
+ ${chalk.gray('5.')} Verify network/firewall settings
154
+ ${chalk.gray('Ensure port 5432 (default) is accessible')}
155
+ `;
156
+ }
157
+
158
+ /**
159
+ * Gets helpful error message for missing Prisma client
160
+ * @param {'mongodb'|'postgresql'} dbType - Database type
161
+ * @returns {string} Formatted error message
162
+ */
163
+ function getPrismaClientNotGeneratedError(dbType) {
164
+ const clientName = `@prisma-${dbType}/client`;
165
+
166
+ return `
167
+ ${chalk.red(`❌ Prisma client not generated for ${dbType}`)}
168
+
169
+ ${chalk.bold('The Prisma client needs to be generated before starting the application.')}
170
+
171
+ ${chalk.yellow('Run:')} ${chalk.cyan('frigg db:setup')}
172
+
173
+ ${chalk.gray('This will:')}
174
+ ${chalk.gray(' • Generate the Prisma client')} ${chalk.gray(`(${clientName})`)}
175
+ ${chalk.gray(' • Set up database schema')}
176
+ ${chalk.gray(' • Run migrations (PostgreSQL) or db push (MongoDB)')}
177
+ `;
178
+ }
179
+
180
+ /**
181
+ * Gets helpful error message for Prisma command failures
182
+ * @param {string} command - Command that failed (generate, migrate, push)
183
+ * @param {string} error - Error message
184
+ * @returns {string} Formatted error message
185
+ */
186
+ function getPrismaCommandError(command, error) {
187
+ return `
188
+ ${chalk.red(`❌ Prisma ${command} failed`)}
189
+
190
+ ${chalk.bold('Error:')}
191
+ ${chalk.gray(error)}
192
+
193
+ ${chalk.bold('Common causes:')}
194
+ ${chalk.gray(' • Database schema has conflicts')}
195
+ ${chalk.gray(' • Database connection lost during operation')}
196
+ ${chalk.gray(' • Insufficient permissions')}
197
+ ${chalk.gray(' • Schema file is invalid')}
198
+
199
+ ${chalk.yellow('Try:')}
200
+ ${chalk.cyan(' frigg db:setup')} ${chalk.gray('(re-run setup)')}
201
+ ${chalk.cyan(' Check your DATABASE_URL')} ${chalk.gray('(verify connection string)')}
202
+ ${chalk.cyan(' Review Prisma schema')} ${chalk.gray('(node_modules/@friggframework/core/prisma-*/schema.prisma)')}
203
+ `;
204
+ }
205
+
206
+ /**
207
+ * Gets success message for database setup completion
208
+ * @param {'mongodb'|'postgresql'} dbType - Database type
209
+ * @param {string} stage - Deployment stage
210
+ * @returns {string} Formatted success message
211
+ */
212
+ function getDatabaseSetupSuccess(dbType, stage) {
213
+ return `
214
+ ${chalk.green('✅ Database setup completed successfully!')}
215
+
216
+ ${chalk.bold('Configuration:')}
217
+ ${chalk.gray(' Database type:')} ${chalk.cyan(dbType)}
218
+ ${chalk.gray(' Stage:')} ${chalk.cyan(stage)}
219
+ ${chalk.gray(' Connection:')} ${chalk.green('verified')}
220
+
221
+ ${chalk.bold('What happened:')}
222
+ ${chalk.gray(' ✓')} Prisma client generated
223
+ ${chalk.gray(' ✓')} Database connection verified
224
+ ${chalk.gray(' ✓')} ${dbType === 'postgresql' ? 'Migrations applied' : 'Schema pushed to database'}
225
+
226
+ ${chalk.yellow('Next steps:')}
227
+ ${chalk.cyan(' frigg start')} ${chalk.gray('(start your application)')}
228
+ `;
229
+ }
230
+
231
+ /**
232
+ * Gets warning message for database already up-to-date
233
+ * @returns {string} Formatted warning message
234
+ */
235
+ function getDatabaseAlreadyUpToDate() {
236
+ return `
237
+ ${chalk.yellow('⚠️ Database is already up-to-date')}
238
+
239
+ ${chalk.gray('No migrations or schema changes detected.')}
240
+
241
+ ${chalk.yellow('If you expected changes:')}
242
+ ${chalk.gray(' • Check if schema was modified in node_modules/@friggframework/core/prisma-*/')}
243
+ ${chalk.gray(' • Verify DATABASE_URL points to the correct database')}
244
+ ${chalk.gray(' • Check if you\'re in the correct project directory')}
245
+ `;
246
+ }
247
+
248
+ module.exports = {
249
+ DATABASE_URL_EXAMPLES,
250
+ getDatabaseUrlMissingError,
251
+ getDatabaseTypeNotConfiguredError,
252
+ getDatabaseConnectionError,
253
+ getPrismaClientNotGeneratedError,
254
+ getPrismaCommandError,
255
+ getDatabaseSetupSuccess,
256
+ getDatabaseAlreadyUpToDate
257
+ };
@@ -0,0 +1,167 @@
1
+ /**
2
+ * NPM Registry Service for CLI
3
+ * CommonJS version of the npm-registry service
4
+ */
5
+
6
+ 'use strict';
7
+
8
+ const axios = require('axios');
9
+ const NodeCache = require('node-cache');
10
+ const semver = require('semver');
11
+
12
+ class NPMRegistryService {
13
+ constructor() {
14
+ // Cache with 1 hour TTL by default
15
+ this.cache = new NodeCache({
16
+ stdTTL: 3600,
17
+ checkperiod: 600,
18
+ useClones: false
19
+ });
20
+
21
+ this.npmRegistryUrl = 'https://registry.npmjs.org';
22
+ this.searchUrl = `${this.npmRegistryUrl}/-/v1/search`;
23
+ this.packageScope = '@friggframework';
24
+ this.modulePrefix = 'api-module-';
25
+ }
26
+
27
+ /**
28
+ * Search for all @friggframework/api-module-* packages
29
+ * @param {Object} options - Search options
30
+ * @param {boolean} options.includePrerelease - Include prerelease versions
31
+ * @param {boolean} options.forceRefresh - Force cache refresh
32
+ * @returns {Promise<Array>} Array of package information
33
+ */
34
+ async searchApiModules(options = {}) {
35
+ const cacheKey = `api-modules-${JSON.stringify(options)}`;
36
+
37
+ // Check cache first unless force refresh is requested
38
+ if (!options.forceRefresh) {
39
+ const cached = this.cache.get(cacheKey);
40
+ if (cached) {
41
+ return cached;
42
+ }
43
+ }
44
+
45
+ try {
46
+ // Search for packages matching our pattern
47
+ const searchQuery = `${this.packageScope}/${this.modulePrefix}`;
48
+ const response = await axios.get(this.searchUrl, {
49
+ params: {
50
+ text: searchQuery,
51
+ size: 250, // Get up to 250 results
52
+ quality: 0.65,
53
+ popularity: 0.98,
54
+ maintenance: 0.5
55
+ },
56
+ timeout: 10000
57
+ });
58
+
59
+ const packages = response.data.objects
60
+ .filter(obj => obj.package.name.startsWith(`${this.packageScope}/${this.modulePrefix}`))
61
+ .map(obj => this.formatPackageInfo(obj.package));
62
+
63
+ // Filter out prereleases if requested
64
+ const filtered = options.includePrerelease
65
+ ? packages
66
+ : packages.filter(pkg => !semver.prerelease(pkg.version));
67
+
68
+ // Cache the results
69
+ this.cache.set(cacheKey, filtered);
70
+
71
+ return filtered;
72
+ } catch (error) {
73
+ console.error('Error searching NPM registry:', error.message);
74
+ // Return empty array on error to allow offline usage
75
+ return [];
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Extract integration name from package name
81
+ * @private
82
+ */
83
+ extractIntegrationName(packageName) {
84
+ return packageName
85
+ .replace(`${this.packageScope}/${this.modulePrefix}`, '')
86
+ .replace(/-/g, ' ')
87
+ .replace(/\b\w/g, l => l.toUpperCase());
88
+ }
89
+
90
+ /**
91
+ * Format package information for API response
92
+ * @private
93
+ */
94
+ formatPackageInfo(pkg) {
95
+ return {
96
+ name: pkg.name,
97
+ version: pkg.version,
98
+ description: pkg.description,
99
+ keywords: pkg.keywords || [],
100
+ author: pkg.author,
101
+ publisher: pkg.publisher,
102
+ date: pkg.date,
103
+ links: pkg.links,
104
+ integrationName: this.extractIntegrationName(pkg.name),
105
+ category: this.categorizeModule(pkg)
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Categorize module based on keywords and name
111
+ * @private
112
+ */
113
+ categorizeModule(module) {
114
+ const name = module.name?.toLowerCase() || '';
115
+ const keywords = module.keywords?.map(k => k.toLowerCase()) || [];
116
+ const allTerms = [...keywords, name];
117
+
118
+ // Categories based on common integration types - ordered by specificity
119
+ const categories = {
120
+ 'Marketing': ['marketing', 'mailchimp', 'campaign', 'automation', 'klaviyo', 'activecampaign'],
121
+ 'CRM': ['crm', 'customer', 'salesforce', 'hubspot', 'pipedrive', 'zoho'],
122
+ 'E-commerce': ['ecommerce', 'shop', 'store', 'payment', 'stripe', 'paypal', 'shopify', 'woocommerce'],
123
+ 'Analytics': ['analytics', 'tracking', 'google-analytics', 'mixpanel', 'segment', 'amplitude'],
124
+ 'Social Media': ['social', 'facebook', 'twitter', 'instagram', 'linkedin', 'youtube'],
125
+ 'Project Management': ['project', 'task', 'jira', 'trello', 'asana', 'monday', 'notion'],
126
+ 'Storage': ['storage', 'file', 'dropbox', 'google-drive', 's3', 'box', 'onedrive'],
127
+ 'Productivity': ['spreadsheet', 'google-sheets', 'airtable', 'calendar', 'todo'],
128
+ 'Development': ['github', 'gitlab', 'bitbucket', 'git', 'ci', 'cd', 'jenkins'],
129
+ 'Support': ['support', 'zendesk', 'freshdesk', 'intercom', 'helpdesk'],
130
+ 'Finance': ['accounting', 'quickbooks', 'xero', 'sage', 'invoice', 'billing'],
131
+ 'Communication': ['email', 'sms', 'chat', 'messaging', 'slack', 'discord', 'twilio', 'sendgrid'],
132
+ 'Other': []
133
+ };
134
+
135
+ for (const [category, terms] of Object.entries(categories)) {
136
+ if (category === 'Other') continue;
137
+
138
+ if (terms.some(term => allTerms.some(t => t.includes(term)))) {
139
+ return category;
140
+ }
141
+ }
142
+
143
+ return 'Other';
144
+ }
145
+
146
+ /**
147
+ * Get grouped modules by integration type
148
+ * @returns {Promise<Object>} Modules grouped by type
149
+ */
150
+ async getModulesByType() {
151
+ const modules = await this.searchApiModules();
152
+
153
+ const grouped = modules.reduce((acc, module) => {
154
+ const type = module.category;
155
+ if (!acc[type]) {
156
+ acc[type] = [];
157
+ }
158
+ acc[type].push(module);
159
+ return acc;
160
+ }, {});
161
+
162
+ return grouped;
163
+ }
164
+ }
165
+
166
+ // Export singleton instance
167
+ module.exports = new NPMRegistryService();
@@ -0,0 +1,199 @@
1
+ const chalk = require('chalk');
2
+ const { spawn } = require('child_process');
3
+ const readline = require('readline');
4
+
5
+ class ProcessManager {
6
+ constructor() {
7
+ this.processes = new Map();
8
+ this.isShuttingDown = false;
9
+ this.outputBuffer = new Map();
10
+ this.setupShutdownHandlers();
11
+ }
12
+
13
+ setupShutdownHandlers() {
14
+ const shutdown = async () => {
15
+ if (this.isShuttingDown) return;
16
+ this.isShuttingDown = true;
17
+
18
+ console.log('\n' + chalk.yellow('⏹ Shutting down...'));
19
+
20
+ const shutdownPromises = [];
21
+ for (const [name, proc] of this.processes) {
22
+ shutdownPromises.push(this.killProcess(name, proc));
23
+ }
24
+
25
+ await Promise.all(shutdownPromises);
26
+
27
+ console.log(chalk.green('✓ All processes stopped cleanly'));
28
+ process.exit(0);
29
+ };
30
+
31
+ process.on('SIGINT', shutdown);
32
+ process.on('SIGTERM', shutdown);
33
+ process.on('exit', () => {
34
+ for (const [, proc] of this.processes) {
35
+ try {
36
+ proc.kill('SIGKILL');
37
+ } catch (e) {
38
+ // Process already dead
39
+ }
40
+ }
41
+ });
42
+ }
43
+
44
+ async killProcess(name, proc) {
45
+ return new Promise((resolve) => {
46
+ if (!proc || proc.killed) {
47
+ resolve();
48
+ return;
49
+ }
50
+
51
+ const timeout = setTimeout(() => {
52
+ try {
53
+ proc.kill('SIGKILL');
54
+ } catch (e) {
55
+ // Process already dead
56
+ }
57
+ resolve();
58
+ }, 5000);
59
+
60
+ proc.once('exit', () => {
61
+ clearTimeout(timeout);
62
+ this.processes.delete(name);
63
+ resolve();
64
+ });
65
+
66
+ try {
67
+ proc.kill('SIGTERM');
68
+ } catch (e) {
69
+ clearTimeout(timeout);
70
+ resolve();
71
+ }
72
+ });
73
+ }
74
+
75
+ spawnProcess(name, command, args, options = {}) {
76
+ const proc = spawn(command, args, {
77
+ ...options,
78
+ stdio: ['inherit', 'pipe', 'pipe'],
79
+ shell: true
80
+ });
81
+
82
+ this.processes.set(name, proc);
83
+ this.outputBuffer.set(name, []);
84
+
85
+ // Create readline interfaces for better line handling
86
+ const stdoutReader = readline.createInterface({
87
+ input: proc.stdout,
88
+ crlfDelay: Infinity
89
+ });
90
+
91
+ const stderrReader = readline.createInterface({
92
+ input: proc.stderr,
93
+ crlfDelay: Infinity
94
+ });
95
+
96
+ stdoutReader.on('line', (line) => {
97
+ if (!this.isShuttingDown) {
98
+ this.handleOutput(name, line, 'stdout');
99
+ }
100
+ });
101
+
102
+ stderrReader.on('line', (line) => {
103
+ if (!this.isShuttingDown) {
104
+ this.handleOutput(name, line, 'stderr');
105
+ }
106
+ });
107
+
108
+ proc.on('error', (error) => {
109
+ if (!this.isShuttingDown) {
110
+ console.error(chalk.red(`[${name}] Process error:`), error.message);
111
+ }
112
+ });
113
+
114
+ proc.on('exit', (code, signal) => {
115
+ this.processes.delete(name);
116
+ if (!this.isShuttingDown && code !== 0 && code !== null) {
117
+ console.error(chalk.red(`[${name}] Process exited with code ${code}`));
118
+ }
119
+ });
120
+
121
+ return proc;
122
+ }
123
+
124
+ handleOutput(processName, line, stream) {
125
+ // Filter out noisy/redundant messages
126
+ const filters = [
127
+ /VITE v\d+\.\d+\.\d+/,
128
+ /ready in \d+ ms/,
129
+ /Local:/,
130
+ /Network:/,
131
+ /press h \+ enter to show help/,
132
+ /\[nodemon\]/,
133
+ /watching for file changes/,
134
+ /restarting due to changes/,
135
+ /starting/,
136
+ /clean exit/,
137
+ /waiting for changes before restart/,
138
+ /^$/ // empty lines
139
+ ];
140
+
141
+ if (filters.some(filter => filter.test(line))) {
142
+ return;
143
+ }
144
+
145
+ // Format output based on process
146
+ const prefix = this.getProcessPrefix(processName);
147
+ const coloredLine = this.colorizeOutput(line, stream);
148
+
149
+ console.log(`${prefix} ${coloredLine}`);
150
+ }
151
+
152
+ getProcessPrefix(processName) {
153
+ const prefixes = {
154
+ 'frontend': chalk.blue('[Frontend]'),
155
+ 'backend': chalk.green('[Backend]'),
156
+ 'vite': chalk.blue('[Vite]'),
157
+ 'server': chalk.green('[Server]')
158
+ };
159
+
160
+ return prefixes[processName.toLowerCase()] || chalk.gray(`[${processName}]`);
161
+ }
162
+
163
+ colorizeOutput(line, stream) {
164
+ // Error detection
165
+ if (stream === 'stderr' || /error|fail|exception/i.test(line)) {
166
+ return chalk.red(line);
167
+ }
168
+
169
+ // Warning detection
170
+ if (/warn|warning/i.test(line)) {
171
+ return chalk.yellow(line);
172
+ }
173
+
174
+ // Success detection
175
+ if (/success|ready|started|listening|compiled/i.test(line)) {
176
+ return chalk.green(line);
177
+ }
178
+
179
+ // Info detection
180
+ if (/info|starting/i.test(line)) {
181
+ return chalk.blue(line);
182
+ }
183
+
184
+ return chalk.gray(line);
185
+ }
186
+
187
+ printStatus(frontendUrl, backendUrl, repoName) {
188
+ console.log('\n' + chalk.bold.green('✨ Frigg Management UI is ready!'));
189
+ console.log('');
190
+ console.log(chalk.cyan(' Frontend: ') + chalk.white(frontendUrl));
191
+ console.log(chalk.cyan(' Backend: ') + chalk.white(backendUrl));
192
+ console.log(chalk.cyan(' Repository:') + chalk.white(` ${repoName}`));
193
+ console.log('');
194
+ console.log(chalk.gray(' Press ' + chalk.bold('Ctrl+C') + ' to stop all servers'));
195
+ console.log('');
196
+ }
197
+ }
198
+
199
+ module.exports = ProcessManager;