@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,287 @@
1
+ /**
2
+ * Global test setup for Frigg CLI tests
3
+ * This file is executed before each test file
4
+ */
5
+
6
+ // Store original environment
7
+ const originalEnv = process.env;
8
+ const originalConsole = { ...console };
9
+ // Store original process methods (not entire object due to read-only properties)
10
+ const originalProcessExit = process.exit;
11
+ const originalProcessCwd = process.cwd;
12
+
13
+ // Mock console to prevent noisy output during tests
14
+ global.console = {
15
+ ...console,
16
+ log: jest.fn(),
17
+ info: jest.fn(),
18
+ warn: jest.fn(),
19
+ error: jest.fn(),
20
+ debug: jest.fn()
21
+ };
22
+
23
+ // Set up test environment variables
24
+ process.env = {
25
+ ...originalEnv,
26
+ NODE_ENV: 'test',
27
+ HOME: '/mock/home',
28
+ PATH: '/mock/path',
29
+ CI: 'true'
30
+ };
31
+
32
+ // Global setup before each test
33
+ beforeEach(() => {
34
+ // Clear all mocks
35
+ jest.clearAllMocks();
36
+
37
+ // Reset timers
38
+ jest.clearAllTimers();
39
+
40
+ // Reset modules
41
+ jest.resetModules();
42
+
43
+ // Mock process.exit to prevent actual exit
44
+ process.exit = jest.fn();
45
+
46
+ // Mock process.cwd to return predictable path
47
+ process.cwd = jest.fn().mockReturnValue('/mock/cwd');
48
+
49
+ // Reset console mocks
50
+ global.console.log.mockClear();
51
+ global.console.info.mockClear();
52
+ global.console.warn.mockClear();
53
+ global.console.error.mockClear();
54
+ global.console.debug.mockClear();
55
+ });
56
+
57
+ // Global cleanup after each test
58
+ afterEach(() => {
59
+ // Restore environment
60
+ process.env = { ...originalEnv };
61
+
62
+ // Restore process methods
63
+ process.exit = originalProcessExit;
64
+ process.cwd = originalProcessCwd;
65
+
66
+ // Clear any remaining timers
67
+ jest.clearAllTimers();
68
+
69
+ // Unmock all modules
70
+ jest.restoreAllMocks();
71
+ });
72
+
73
+ // Global teardown after all tests
74
+ afterAll(() => {
75
+ // Restore original environment completely
76
+ process.env = originalEnv;
77
+
78
+ // Restore original console
79
+ global.console = originalConsole;
80
+
81
+ // Restore original process methods
82
+ process.exit = originalProcessExit;
83
+ process.cwd = originalProcessCwd;
84
+ });
85
+
86
+ // Custom matchers for CLI testing
87
+ expect.extend({
88
+ toBeValidExitCode(received) {
89
+ const validCodes = [0, 1, 2];
90
+ const pass = validCodes.includes(received);
91
+
92
+ if (pass) {
93
+ return {
94
+ message: () => `expected ${received} not to be a valid exit code`,
95
+ pass: true
96
+ };
97
+ } else {
98
+ return {
99
+ message: () => `expected ${received} to be a valid exit code (0, 1, or 2)`,
100
+ pass: false
101
+ };
102
+ }
103
+ },
104
+
105
+ toHaveLoggedError(received, expected) {
106
+ const errorLogs = global.console.error.mock.calls;
107
+ const pass = errorLogs.some(call =>
108
+ call.some(arg =>
109
+ typeof arg === 'string' && arg.includes(expected)
110
+ )
111
+ );
112
+
113
+ if (pass) {
114
+ return {
115
+ message: () => `expected not to have logged error containing "${expected}"`,
116
+ pass: true
117
+ };
118
+ } else {
119
+ return {
120
+ message: () => `expected to have logged error containing "${expected}"`,
121
+ pass: false
122
+ };
123
+ }
124
+ },
125
+
126
+ toHaveLoggedInfo(received, expected) {
127
+ const infoLogs = global.console.info.mock.calls;
128
+ const pass = infoLogs.some(call =>
129
+ call.some(arg =>
130
+ typeof arg === 'string' && arg.includes(expected)
131
+ )
132
+ );
133
+
134
+ if (pass) {
135
+ return {
136
+ message: () => `expected not to have logged info containing "${expected}"`,
137
+ pass: true
138
+ };
139
+ } else {
140
+ return {
141
+ message: () => `expected to have logged info containing "${expected}"`,
142
+ pass: false
143
+ };
144
+ }
145
+ },
146
+
147
+ toBeWithinTimeLimit(received, limit) {
148
+ const pass = received <= limit;
149
+
150
+ if (pass) {
151
+ return {
152
+ message: () => `expected ${received}ms not to be within ${limit}ms`,
153
+ pass: true
154
+ };
155
+ } else {
156
+ return {
157
+ message: () => `expected ${received}ms to be within ${limit}ms`,
158
+ pass: false
159
+ };
160
+ }
161
+ }
162
+ });
163
+
164
+ // Helper functions available in all tests
165
+ global.TestHelpers = {
166
+ /**
167
+ * Create a temporary directory for tests
168
+ */
169
+ createTempDir() {
170
+ const fs = require('fs');
171
+ const path = require('path');
172
+ const os = require('os');
173
+
174
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-cli-test-'));
175
+ },
176
+
177
+ /**
178
+ * Clean up temporary directory
179
+ */
180
+ cleanupTempDir(dirPath) {
181
+ const fs = require('fs');
182
+
183
+ if (fs.existsSync(dirPath)) {
184
+ fs.rmSync(dirPath, { recursive: true, force: true });
185
+ }
186
+ },
187
+
188
+ /**
189
+ * Create a mock package.json file
190
+ */
191
+ createMockPackageJson(overrides = {}) {
192
+ return JSON.stringify({
193
+ name: 'test-package',
194
+ version: '1.0.0',
195
+ main: 'index.js',
196
+ scripts: {
197
+ test: 'jest',
198
+ start: 'node index.js'
199
+ },
200
+ dependencies: {},
201
+ devDependencies: {},
202
+ ...overrides
203
+ }, null, 2);
204
+ },
205
+
206
+ /**
207
+ * Create a mock frigg.config.json file
208
+ */
209
+ createMockFriggConfig(overrides = {}) {
210
+ return JSON.stringify({
211
+ stage: 'dev',
212
+ region: 'us-east-1',
213
+ profile: 'default',
214
+ backend: {
215
+ runtime: 'nodejs18.x',
216
+ timeout: 30,
217
+ memory: 128
218
+ },
219
+ ...overrides
220
+ }, null, 2);
221
+ },
222
+
223
+ /**
224
+ * Wait for a specific amount of time
225
+ */
226
+ async delay(ms) {
227
+ return new Promise(resolve => setTimeout(resolve, ms));
228
+ },
229
+
230
+ /**
231
+ * Generate a random string for test data
232
+ */
233
+ randomString(length = 10) {
234
+ return Math.random().toString(36).substring(2, length + 2);
235
+ },
236
+
237
+ /**
238
+ * Simulate file system structure
239
+ */
240
+ mockFileSystem(structure) {
241
+ const fs = require('fs');
242
+
243
+ const originalExistsSync = fs.existsSync;
244
+ const originalReadFileSync = fs.readFileSync;
245
+ const originalWriteFileSync = fs.writeFileSync;
246
+
247
+ fs.existsSync = jest.fn((path) => {
248
+ return structure.hasOwnProperty(path);
249
+ });
250
+
251
+ fs.readFileSync = jest.fn((path) => {
252
+ if (structure.hasOwnProperty(path)) {
253
+ return structure[path];
254
+ }
255
+ throw new Error(`ENOENT: no such file or directory, open '${path}'`);
256
+ });
257
+
258
+ fs.writeFileSync = jest.fn((path, data) => {
259
+ structure[path] = data;
260
+ });
261
+
262
+ return {
263
+ restore() {
264
+ fs.existsSync = originalExistsSync;
265
+ fs.readFileSync = originalReadFileSync;
266
+ fs.writeFileSync = originalWriteFileSync;
267
+ }
268
+ };
269
+ }
270
+ };
271
+
272
+ // Global timeout for all tests
273
+ jest.setTimeout(30000);
274
+
275
+ // Suppress specific warnings during tests
276
+ // Note: console.warn is already mocked above, so we keep the mock
277
+ // and just suppress certain warnings in the implementation
278
+ const originalWarnMock = global.console.warn;
279
+ global.console.warn = jest.fn((...args) => {
280
+ // Suppress specific warnings that are expected during testing
281
+ const message = args.join(' ');
282
+ if (message.includes('ExperimentalWarning') ||
283
+ message.includes('DeprecationWarning')) {
284
+ return;
285
+ }
286
+ // Still track the call in the mock
287
+ });
@@ -0,0 +1,66 @@
1
+ const { spawnSync } = require('child_process');
2
+ const path = require('path');
3
+
4
+ async function buildCommand(options) {
5
+ console.log('Building the serverless application...');
6
+
7
+ // Suppress AWS SDK warning message about maintenance mode
8
+ process.env.AWS_SDK_JS_SUPPRESS_MAINTENANCE_MODE_MESSAGE = '1';
9
+
10
+ // Skip AWS discovery for local builds (unless --production flag is set)
11
+ if (!options.production) {
12
+ process.env.FRIGG_SKIP_AWS_DISCOVERY = 'true';
13
+ console.log('🏠 Building in local mode (use --production flag for production builds with AWS discovery)');
14
+ } else {
15
+ console.log('🚀 Building in production mode with AWS discovery enabled');
16
+ }
17
+
18
+ // AWS discovery is now handled directly in serverless-template.js
19
+ console.log('📦 Packaging serverless application...');
20
+ const backendPath = path.resolve(process.cwd());
21
+ const infrastructurePath = 'infrastructure.js';
22
+ const command = 'osls'; // OSS-Serverless (drop-in replacement for serverless v3)
23
+ const serverlessArgs = [
24
+ 'package',
25
+ '--config',
26
+ infrastructurePath,
27
+ '--stage',
28
+ options.stage
29
+ ];
30
+
31
+ // Add support for --verbose option
32
+ if (options.verbose) {
33
+ serverlessArgs.push('--verbose');
34
+ }
35
+
36
+ console.log('Running command from ', backendPath);
37
+ console.log('Serverless Command:', command, serverlessArgs.join(' '));
38
+
39
+ const result = spawnSync(command, serverlessArgs, {
40
+ cwd: backendPath,
41
+ stdio: 'inherit',
42
+ shell: true,
43
+ env: {
44
+ ...process.env,
45
+ NODE_PATH: path.resolve(backendPath, 'node_modules'),
46
+ SLS_STAGE: options.stage, // Set stage for resource discovery
47
+ }
48
+ });
49
+
50
+ if (result.status !== 0) {
51
+ console.error(`Serverless build failed with code ${result.status}`);
52
+ process.exit(1);
53
+ }
54
+
55
+ // childProcess.on('error', (error) => {
56
+ // console.error(`Error executing command: ${error.message}`);
57
+ // });
58
+
59
+ // childProcess.on('close', (code) => {
60
+ // if (code !== 0) {
61
+ // console.log(`Child process exited with code ${code}`);
62
+ // }
63
+ // });
64
+ }
65
+
66
+ module.exports = { buildCommand };
@@ -0,0 +1,193 @@
1
+ const path = require('path');
2
+ const chalk = require('chalk');
3
+ const dotenv = require('dotenv');
4
+ const {
5
+ validateDatabaseUrl,
6
+ getDatabaseType,
7
+ checkPrismaClientGenerated
8
+ } = require('../utils/database-validator');
9
+ const {
10
+ runPrismaGenerate,
11
+ checkDatabaseState,
12
+ runPrismaMigrate,
13
+ runPrismaDbPush,
14
+ getMigrationCommand
15
+ } = require('@friggframework/core/database/utils/prisma-runner');
16
+ const {
17
+ getDatabaseUrlMissingError,
18
+ getDatabaseTypeNotConfiguredError,
19
+ getPrismaCommandError,
20
+ getDatabaseSetupSuccess
21
+ } = require('../utils/error-messages');
22
+
23
+ /**
24
+ * Database Setup Command
25
+ * Sets up the database for a Frigg application:
26
+ * - Validates configuration
27
+ * - Generates Prisma client
28
+ * - Runs migrations (PostgreSQL) or db push (MongoDB)
29
+ */
30
+
31
+ async function dbSetupCommand(options = {}) {
32
+ const verbose = options.verbose || false;
33
+ const stage = options.stage || process.env.STAGE || 'development';
34
+
35
+ console.log(chalk.blue('🔧 Frigg Database Setup'));
36
+ console.log(chalk.gray(`Stage: ${stage}\n`));
37
+
38
+ // Load environment variables from .env file
39
+ const envPath = path.join(process.cwd(), '.env');
40
+ dotenv.config({ path: envPath });
41
+
42
+ try {
43
+ // Step 1: Validate DATABASE_URL
44
+ if (verbose) {
45
+ console.log(chalk.gray('Step 1: Validating DATABASE_URL...'));
46
+ }
47
+
48
+ const urlValidation = validateDatabaseUrl();
49
+ if (!urlValidation.valid) {
50
+ console.error(getDatabaseUrlMissingError());
51
+ process.exit(1);
52
+ }
53
+
54
+ if (verbose) {
55
+ console.log(chalk.green('✓ DATABASE_URL found\n'));
56
+ }
57
+
58
+ // Step 2: Determine database type from app definition
59
+ if (verbose) {
60
+ console.log(chalk.gray('Step 2: Determining database type...'));
61
+ }
62
+
63
+ const dbTypeResult = getDatabaseType();
64
+ if (dbTypeResult.error) {
65
+ console.error(chalk.red('❌ ' + dbTypeResult.error));
66
+
67
+ // Show stack trace in verbose mode for debugging
68
+ if (verbose && dbTypeResult.stack) {
69
+ console.error(chalk.gray('\nStack trace:'));
70
+ console.error(chalk.gray(dbTypeResult.stack));
71
+ }
72
+
73
+ console.error(getDatabaseTypeNotConfiguredError());
74
+ process.exit(1);
75
+ }
76
+
77
+ const dbType = dbTypeResult.dbType;
78
+ console.log(chalk.cyan(`Database type: ${dbType}`));
79
+
80
+ if (verbose) {
81
+ console.log(chalk.green(`✓ Using ${dbType}\n`));
82
+ }
83
+
84
+ // Step 3: Check if Prisma client exists, generate if needed
85
+ if (verbose) {
86
+ console.log(chalk.gray('Step 3: Checking Prisma client...'));
87
+ }
88
+
89
+ const clientCheck = checkPrismaClientGenerated(dbType);
90
+ const forceRegenerate = options.force || false;
91
+
92
+ if (clientCheck.generated && !forceRegenerate) {
93
+ // Client already exists and --force not specified
94
+ console.log(chalk.green('✓ Prisma client already exists (skipping generation)\n'));
95
+ if (verbose) {
96
+ console.log(chalk.gray(` Client location: ${clientCheck.path}\n`));
97
+ }
98
+ } else {
99
+ // Client doesn't exist OR --force specified - generate it
100
+ if (forceRegenerate && clientCheck.generated) {
101
+ console.log(chalk.yellow('⚠️ Forcing Prisma client regeneration...'));
102
+ } else {
103
+ console.log(chalk.cyan('Generating Prisma client...'));
104
+ }
105
+
106
+ const generateResult = await runPrismaGenerate(dbType, verbose);
107
+
108
+ if (!generateResult.success) {
109
+ console.error(getPrismaCommandError('generate', generateResult.error));
110
+ if (generateResult.output) {
111
+ console.error(chalk.gray(generateResult.output));
112
+ }
113
+ process.exit(1);
114
+ }
115
+
116
+ console.log(chalk.green('✓ Prisma client generated\n'));
117
+ }
118
+
119
+ // Step 4: Check database state
120
+ // Note: We skip connection testing in db:setup because when using frigg:local,
121
+ // the CLI code runs from tmp/frigg but the client is in backend/node_modules,
122
+ // causing module resolution mismatches. Connection testing happens in frigg start.
123
+ if (verbose) {
124
+ console.log(chalk.gray('Step 4: Checking database state...'));
125
+ }
126
+
127
+ const stateCheck = await checkDatabaseState(dbType);
128
+
129
+ // Step 5: Run migrations or db push
130
+ if (dbType === 'postgresql') {
131
+ console.log(chalk.cyan('Running database migrations...'));
132
+
133
+ const migrationCommand = getMigrationCommand(stage);
134
+
135
+ if (verbose) {
136
+ console.log(chalk.gray(`Using migration command: ${migrationCommand}`));
137
+ }
138
+
139
+ if (stateCheck.upToDate && migrationCommand === 'deploy') {
140
+ console.log(chalk.yellow('Database is already up-to-date'));
141
+ } else {
142
+ const migrateResult = await runPrismaMigrate(migrationCommand, verbose);
143
+
144
+ if (!migrateResult.success) {
145
+ console.error(getPrismaCommandError('migrate', migrateResult.error));
146
+ if (migrateResult.output) {
147
+ console.error(chalk.gray(migrateResult.output));
148
+ }
149
+ process.exit(1);
150
+ }
151
+
152
+ console.log(chalk.green('✓ Migrations applied\n'));
153
+ }
154
+
155
+ } else if (dbType === 'mongodb') {
156
+ console.log(chalk.cyan('Pushing schema to MongoDB...'));
157
+
158
+ const pushResult = await runPrismaDbPush(verbose);
159
+
160
+ if (!pushResult.success) {
161
+ console.error(getPrismaCommandError('db push', pushResult.error));
162
+ if (pushResult.output) {
163
+ console.error(chalk.gray(pushResult.output));
164
+ }
165
+ process.exit(1);
166
+ }
167
+
168
+ console.log(chalk.green('✓ Schema pushed to database\n'));
169
+ }
170
+
171
+ // Success!
172
+ console.log(getDatabaseSetupSuccess(dbType, stage));
173
+
174
+ } catch (error) {
175
+ console.error(chalk.red('\n❌ Database setup failed'));
176
+ console.error(chalk.gray(error.message));
177
+
178
+ if (verbose && error.stack) {
179
+ console.error(chalk.gray('\nStack trace:'));
180
+ console.error(chalk.gray(error.stack));
181
+ }
182
+
183
+ console.error(chalk.yellow('\nTroubleshooting:'));
184
+ console.error(chalk.gray(' • Verify DATABASE_URL in your .env file'));
185
+ console.error(chalk.gray(' • Check database is running and accessible'));
186
+ console.error(chalk.gray(' • Ensure app definition has database configuration'));
187
+ console.error(chalk.gray(' • Run with --verbose flag for more details'));
188
+
189
+ process.exit(1);
190
+ }
191
+ }
192
+
193
+ module.exports = { dbSetupCommand };