@friggframework/devtools 2.0.0--canary.710.91495fa.0 → 2.0.0--canary.702.ef0dc8c.0

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 (86) hide show
  1. package/README.md +1 -0
  2. package/frigg-cli/README.md +76 -78
  3. package/frigg-cli/__tests__/unit/commands/build.test.js +3 -0
  4. package/frigg-cli/__tests__/unit/commands/deploy.test.js +27 -30
  5. package/frigg-cli/__tests__/unit/commands/doctor.test.js +6 -10
  6. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +0 -18
  7. package/frigg-cli/__tests__/unit/commands/install.test.js +341 -601
  8. package/frigg-cli/__tests__/unit/commands/ui.test.js +30 -31
  9. package/frigg-cli/__tests__/unit/commands/validate-wiring.test.js +92 -0
  10. package/frigg-cli/__tests__/unit/dependencies.test.js +2 -6
  11. package/frigg-cli/build-command/index.js +6 -0
  12. package/frigg-cli/deploy-command/index.js +6 -0
  13. package/frigg-cli/generate-command/index.js +0 -1
  14. package/frigg-cli/generate-iam-command.js +0 -1
  15. package/frigg-cli/index.js +23 -10
  16. package/frigg-cli/index.test.js +158 -0
  17. package/frigg-cli/init-command/backend-first-handler.js +531 -395
  18. package/frigg-cli/init-command/index.js +35 -82
  19. package/frigg-cli/install-command/commit-changes.js +8 -40
  20. package/frigg-cli/install-command/environment-variables.js +0 -15
  21. package/frigg-cli/install-command/index.js +21 -96
  22. package/frigg-cli/install-command/install-package.js +4 -77
  23. package/frigg-cli/install-command/integration-file.js +11 -20
  24. package/frigg-cli/install-command/template.js +75 -102
  25. package/frigg-cli/install-command/validate-package.js +4 -36
  26. package/frigg-cli/package.json +1 -1
  27. package/frigg-cli/start-command/index.js +4 -0
  28. package/frigg-cli/start-command/start-command.test.js +3 -0
  29. package/frigg-cli/test/init-command.test.js +2 -9
  30. package/frigg-cli/validate-command/__tests__/init-validation.test.js +63 -0
  31. package/frigg-cli/validate-command/__tests__/integrations-checks.test.js +133 -0
  32. package/frigg-cli/validate-command/__tests__/validate-app-definition.test.js +326 -0
  33. package/frigg-cli/validate-command/__tests__/validate-command.test.js +241 -0
  34. package/frigg-cli/validate-command/__tests__/validate-module-command.test.js +119 -0
  35. package/frigg-cli/validate-command/checks/config.js +468 -0
  36. package/frigg-cli/validate-command/checks/integrations.js +274 -0
  37. package/frigg-cli/validate-command/fixtures/bad-module/index.js +18 -0
  38. package/frigg-cli/validate-command/fixtures/fathom-module/definition.js +76 -0
  39. package/frigg-cli/validate-command/fixtures/fathom-module/index.js +6 -0
  40. package/frigg-cli/validate-command/format-report.js +60 -0
  41. package/frigg-cli/validate-command/index.js +151 -0
  42. package/frigg-cli/validate-command/load-app-definition.js +93 -0
  43. package/frigg-cli/validate-command/load-module-definition.js +64 -0
  44. package/frigg-cli/validate-command/schema-issues.js +154 -0
  45. package/frigg-cli/validate-command/validate-app-definition.js +60 -0
  46. package/frigg-cli/validate-command/validate-module-definition.js +46 -0
  47. package/infrastructure/__tests__/postgres-config.test.js +835 -241
  48. package/infrastructure/__tests__/template-generation.test.js +8 -36
  49. package/infrastructure/app-definition-schema-contract.test.js +607 -0
  50. package/infrastructure/create-frigg-infrastructure.js +4 -1
  51. package/infrastructure/create-frigg-infrastructure.test.js +51 -0
  52. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +60 -118
  53. package/infrastructure/domains/database/aurora-builder.js +2 -13
  54. package/infrastructure/domains/database/aurora-builder.test.js +0 -22
  55. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +8 -12
  56. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +7 -19
  57. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +8 -12
  58. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +18 -17
  59. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +2 -12
  60. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +1 -8
  61. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +2 -4
  62. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +0 -10
  63. package/infrastructure/domains/networking/vpc-builder.js +8 -18
  64. package/infrastructure/domains/networking/vpc-builder.test.js +13 -32
  65. package/infrastructure/domains/security/iam-generator.js +5 -112
  66. package/infrastructure/domains/security/iam-generator.test.js +0 -94
  67. package/infrastructure/domains/shared/cloudformation-discovery.test.js +6 -36
  68. package/infrastructure/domains/shared/utilities/base-definition-factory.js +2 -7
  69. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +0 -21
  70. package/infrastructure/infrastructure-composer.test.js +794 -268
  71. package/infrastructure/integration.test.js +381 -0
  72. package/infrastructure/scripts/build-prisma-layer.test.js +7 -28
  73. package/infrastructure/scripts/build-time-discovery.test.js +3 -18
  74. package/package.json +8 -10
  75. package/frigg-cli/__tests__/unit/commands/init.test.js +0 -688
  76. package/frigg-cli/init-command/deployment-modes.js +0 -7
  77. package/frigg-cli/init-command/safe-path.js +0 -58
  78. package/frigg-cli/init-command/scaffold-dependencies.js +0 -202
  79. package/frigg-cli/install-command/app-definition.js +0 -174
  80. package/frigg-cli/install-command/resolve-module.js +0 -69
  81. package/frigg-cli/templates/backend/README.md +0 -267
  82. package/frigg-cli/templates/backend/env.example +0 -20
  83. package/frigg-cli/templates/backend/gitignore +0 -10
  84. package/frigg-cli/templates/backend/index.js +0 -114
  85. package/frigg-cli/templates/backend/infrastructure.js +0 -20
  86. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +0 -148
@@ -1,82 +1,22 @@
1
1
  const fs = require('fs-extra');
2
2
  const path = require('path');
3
3
  const chalk = require('chalk');
4
- const { spawnSync } = require('child_process');
4
+ const { select, confirm, multiselect } = require('@inquirer/prompts');
5
+ const { execSync } = require('child_process');
5
6
  const spawn = require('cross-spawn');
6
- const { resolveInside } = require('./safe-path');
7
7
  const npmRegistry = require('../utils/npm-registry');
8
- const {
9
- validateAppDefinition,
10
- formatErrors,
11
- } = require('@friggframework/schemas');
12
- const {
13
- getScaffoldDependencies,
14
- getScaffoldScripts,
15
- } = require('./scaffold-dependencies');
16
-
17
- const {
18
- DEPLOYMENT_MODES,
19
- DEFAULT_DEPLOYMENT_MODE,
20
- } = require('./deployment-modes');
21
-
22
- /** Sub-directory that holds the Frigg backend in embedded mode. */
23
- const EMBEDDED_DIR = 'frigg-integration';
8
+ const { runValidation } = require('../validate-command');
9
+ const { formatReport } = require('../validate-command/format-report');
24
10
 
25
11
  /**
26
- * Template files stored under a different name. npm strips `.gitignore` from
27
- * published packages, and dotfiles are easy to lose, so they are renamed when
28
- * copied into the new project.
29
- */
30
- const RENAMED_TEMPLATE_FILES = {
31
- gitignore: '.gitignore',
32
- 'env.example': '.env.example',
33
- };
34
-
35
- /**
36
- * Files that may already exist in the target directory. They are kept (not
37
- * overwritten) unless --force is given.
38
- */
39
- const PRESERVED_FILES = ['README.md', '.gitignore'];
40
- const ALLOWED_EXISTING_FILES = ['.git', '.DS_Store', ...PRESERVED_FILES];
41
-
42
- const TEMPLATE_APP_NAME = "name: 'frigg-app',";
43
- const TEMPLATE_README_TITLE = '# Frigg Backend';
44
-
45
- /**
46
- * Scaffolds a new Frigg backend application.
47
- *
48
- * Prompts are interactive only when stdin is a TTY and --yes was not given;
49
- * otherwise every prompt resolves to its default, so `frigg init` works in CI
50
- * and scripts.
12
+ * Backend-first template handler that treats frontend as optional demonstration
51
13
  */
52
14
  class BackendFirstHandler {
53
15
  constructor(targetPath, options = {}) {
54
- this.targetPath = path.resolve(targetPath);
55
- this.appName = path.basename(this.targetPath);
16
+ this.targetPath = targetPath;
17
+ this.appName = path.basename(targetPath);
56
18
  this.options = options;
57
19
  this.templatesDir = path.join(__dirname, '..', 'templates');
58
- this.interactive =
59
- options.interactive !== undefined
60
- ? Boolean(options.interactive)
61
- : !options.yes && Boolean(process.stdin.isTTY);
62
- // Test seam: inject prompt implementations.
63
- this.prompts = options.prompts || null;
64
- }
65
-
66
- /**
67
- * Ask a question, or return its default when running non-interactively.
68
- *
69
- * @param {'select'|'confirm'|'checkbox'} type - @inquirer/prompts function.
70
- * @param {object} config - Prompt config; `default` is used when
71
- * non-interactive.
72
- */
73
- async ask(type, config) {
74
- if (!this.interactive) {
75
- return config.default;
76
- }
77
- // eslint-disable-next-line global-require
78
- const prompts = this.prompts || require('@inquirer/prompts');
79
- return prompts[type](config);
80
20
  }
81
21
 
82
22
  /**
@@ -84,27 +24,34 @@ class BackendFirstHandler {
84
24
  */
85
25
  async initialize() {
86
26
  console.log(chalk.blue('🚀 Welcome to Frigg - Integration Framework'));
87
- console.log(
88
- chalk.gray('Creating a new Frigg backend application...\n')
89
- );
27
+ console.log(chalk.gray('Creating a new Frigg backend application...\n'));
90
28
 
29
+ // Get deployment mode
91
30
  const deploymentMode = await this.selectDeploymentMode();
92
- this.projectDir =
93
- deploymentMode === 'embedded'
94
- ? resolveInside(this.targetPath, EMBEDDED_DIR)
95
- : this.targetPath;
96
-
97
- // Fail fast, before asking anything else, if the target is not empty.
98
- await this.ensureSafeDirectory(this.projectDir);
99
-
31
+
32
+ // Get project configuration
100
33
  const config = await this.getProjectConfiguration(deploymentMode);
101
34
 
35
+ // Create project structure
102
36
  await this.createProject(deploymentMode, config);
103
37
 
104
- console.log(
105
- chalk.green('\n✅ Frigg application created successfully!')
106
- );
107
-
38
+ console.log(chalk.green('\n✅ Frigg application created successfully!'));
39
+
40
+ // If user needs custom API module, prompt to create it
41
+ if (config.needsCustomApiModule) {
42
+ console.log(chalk.cyan('\n🔧 Now let\'s create your custom API module...'));
43
+ const createModule = await confirm({
44
+ message: 'Would you like to create your custom API module now?',
45
+ default: true
46
+ });
47
+
48
+ if (createModule) {
49
+ console.log(chalk.gray('\n Run this command after setup:'));
50
+ console.log(chalk.cyan(` cd ${path.relative(process.cwd(), this.targetPath)}`));
51
+ console.log(chalk.cyan(' frigg generate:api-module\n'));
52
+ }
53
+ }
54
+
108
55
  this.displayNextSteps(deploymentMode, config);
109
56
  }
110
57
 
@@ -113,32 +60,27 @@ class BackendFirstHandler {
113
60
  */
114
61
  async selectDeploymentMode() {
115
62
  if (this.options.mode) {
116
- if (!DEPLOYMENT_MODES.includes(this.options.mode)) {
117
- throw new Error(
118
- `Invalid --mode "${
119
- this.options.mode
120
- }". Expected one of: ${DEPLOYMENT_MODES.join(', ')}`
121
- );
122
- }
123
63
  return this.options.mode;
124
64
  }
125
65
 
126
- return this.ask('select', {
66
+ const mode = await select({
127
67
  message: 'How will you deploy this Frigg application?',
128
68
  choices: [
129
69
  {
130
- name: 'Standalone - Deploy as separate service',
131
- value: 'standalone',
132
- description: 'Run Frigg as an independent microservice',
133
- },
134
- {
135
- name: 'Embedded - Add to an existing repository',
70
+ name: 'Embedded - Integrate into existing application',
136
71
  value: 'embedded',
137
- description: `Scaffold the Frigg backend into ./${EMBEDDED_DIR} of an existing project`,
72
+ description: 'Add Frigg as a library to your existing backend'
138
73
  },
74
+ {
75
+ name: 'Standalone - Deploy as separate service',
76
+ value: 'standalone',
77
+ description: 'Run Frigg as an independent microservice'
78
+ }
139
79
  ],
140
- default: DEFAULT_DEPLOYMENT_MODE,
80
+ default: 'standalone'
141
81
  });
82
+
83
+ return mode;
142
84
  }
143
85
 
144
86
  /**
@@ -147,136 +89,154 @@ class BackendFirstHandler {
147
89
  async getProjectConfiguration(deploymentMode) {
148
90
  const config = { deploymentMode };
149
91
 
150
- config.appPurpose = await this.ask('select', {
92
+ // Ask about the purpose of this Frigg application
93
+ config.appPurpose = await select({
151
94
  message: 'What are you building with Frigg?',
152
95
  choices: [
153
96
  {
154
97
  name: 'Integrations for my own application',
155
98
  value: 'own-app',
156
- description:
157
- 'Build integrations that connect your app with third-party services',
99
+ description: 'Build integrations that connect your app with third-party services'
158
100
  },
159
101
  {
160
102
  name: 'Integration platform for multiple apps',
161
103
  value: 'platform',
162
- description:
163
- 'Build a platform that provides integrations to other applications',
104
+ description: 'Build a platform that provides integrations to other applications'
164
105
  },
165
106
  {
166
107
  name: 'Just exploring Frigg',
167
108
  value: 'exploring',
168
- description:
169
- 'Testing and learning about Frigg capabilities',
170
- },
171
- ],
172
- default: 'own-app',
109
+ description: 'Testing and learning about Frigg capabilities'
110
+ }
111
+ ]
173
112
  });
174
113
 
114
+ // If building for own app, ask about creating custom API module
175
115
  if (config.appPurpose === 'own-app') {
176
- config.needsCustomApiModule = await this.ask('confirm', {
177
- message:
178
- 'Do you need to create an API module for your own application?',
179
- default: false,
116
+ config.needsCustomApiModule = await confirm({
117
+ message: 'Do you need to create an API module for your own application?',
118
+ default: true
180
119
  });
120
+
121
+ if (config.needsCustomApiModule) {
122
+ console.log(chalk.cyan('\n💡 We\'ll help you create a custom API module after setup'));
123
+ console.log(chalk.gray(' This will allow other integrations to connect with your API\n'));
124
+ }
181
125
  }
182
126
 
183
- // Selected modules are installed afterwards with `frigg install`,
184
- // which installs the package and scaffolds the integration file.
185
- config.includeIntegrations = await this.ask('confirm', {
186
- message:
187
- 'Would you like to pick API modules to integrate with? (installed afterwards with `frigg install`)',
188
- default: false,
127
+ // Ask about initial integrations
128
+ config.includeIntegrations = await confirm({
129
+ message: 'Would you like to create integrations with available API modules?',
130
+ default: true
189
131
  });
190
132
 
191
133
  if (config.includeIntegrations) {
192
- config.starterIntegrations = await this.selectIntegrations();
134
+ console.log(chalk.gray('\n🔍 Discovering available API modules from npm...'));
135
+
136
+ // Fetch available modules from npm
137
+ const availableModules = await this.getAvailableModules();
138
+
139
+ if (availableModules.length === 0) {
140
+ console.log(chalk.yellow('⚠️ Could not fetch modules from npm. Using default list.'));
141
+ config.starterIntegrations = await this.selectDefaultIntegrations();
142
+ } else {
143
+ // Group modules by category for better UX
144
+ const groupedModules = await npmRegistry.getModulesByType();
145
+ const choices = [];
146
+
147
+ Object.entries(groupedModules).forEach(([category, modules]) => {
148
+ if (modules.length > 0) {
149
+ choices.push({ name: `--- ${category} ---`, value: null, disabled: true });
150
+ modules.forEach(mod => {
151
+ const name = mod.integrationName;
152
+ const value = mod.name.replace('@friggframework/api-module-', '');
153
+ choices.push({
154
+ name: `${name} - ${mod.description || 'No description'}`,
155
+ value: value,
156
+ short: name
157
+ });
158
+ });
159
+ }
160
+ });
161
+
162
+ config.starterIntegrations = await multiselect({
163
+ message: 'Select API modules to integrate (space to select, enter to confirm):',
164
+ choices,
165
+ instructions: '\n Press <space> to select, <a> to toggle all, <enter> to confirm\n',
166
+ validate: (answer) => {
167
+ if (answer.length === 0) {
168
+ return 'Please select at least one integration or press Ctrl+C to skip';
169
+ }
170
+ return true;
171
+ }
172
+ });
173
+ }
174
+ }
175
+
176
+ // Ask about demo frontend only if not explicitly disabled
177
+ if (this.options.frontend !== false) {
178
+ config.includeDemoFrontend = await confirm({
179
+ message: 'Include a demo frontend to showcase integration capabilities?',
180
+ default: false
181
+ });
182
+
183
+ if (config.includeDemoFrontend) {
184
+ console.log(chalk.yellow('\n📝 Note: The demo frontend is for demonstration purposes only.'));
185
+ console.log(chalk.yellow(' For production, integrate Frigg into your existing application'));
186
+ console.log(chalk.yellow(' or use "frigg ui" for development and management.\n'));
187
+
188
+ config.frontendFramework = await select({
189
+ message: 'Which framework for the demo frontend?',
190
+ choices: [
191
+ { name: 'React - Modern React with Vite', value: 'react' },
192
+ { name: 'Vue 3 - Vue with Composition API', value: 'vue' },
193
+ { name: 'Svelte - SvelteKit application', value: 'svelte' },
194
+ { name: 'Angular - Angular with standalone components', value: 'angular' }
195
+ ]
196
+ });
197
+
198
+ config.demoAuthMode = await select({
199
+ message: 'Demo authentication mode:',
200
+ choices: [
201
+ {
202
+ name: 'Mock Login - Simple username/password for demo',
203
+ value: 'mock',
204
+ description: 'Basic auth for demonstration'
205
+ },
206
+ {
207
+ name: 'API Credentials - Use your app\'s actual auth',
208
+ value: 'real',
209
+ description: 'Configure with your authentication system'
210
+ }
211
+ ],
212
+ default: 'mock'
213
+ });
214
+ }
193
215
  }
194
216
 
217
+ // Serverless configuration for standalone mode
195
218
  if (deploymentMode === 'standalone') {
196
- config.serverlessProvider = await this.ask('select', {
219
+ config.serverlessProvider = await select({
197
220
  message: 'Which cloud provider will you use?',
198
221
  choices: [
199
222
  { name: 'AWS Lambda', value: 'aws' },
200
- { name: 'Local Development Only', value: 'local' },
223
+ { name: 'Local Development Only', value: 'local' }
201
224
  ],
202
- default: 'aws',
225
+ default: 'aws'
203
226
  });
204
227
  }
205
228
 
206
- config.installDependencies =
207
- this.options.install === false
208
- ? false
209
- : await this.ask('confirm', {
210
- message: 'Install dependencies now?',
211
- default: true,
212
- });
213
-
214
- // Embedded mode lives inside an existing repository.
215
- config.initializeGit =
216
- deploymentMode === 'embedded' || this.options.git === false
217
- ? false
218
- : await this.ask('confirm', {
219
- message: 'Initialize Git repository?',
220
- default: true,
221
- });
222
-
223
- return config;
224
- }
225
-
226
- /**
227
- * Let the user pick API modules. Only names are collected; the next-steps
228
- * output tells the user to run `frigg install <name>` for each.
229
- */
230
- async selectIntegrations() {
231
- console.log(
232
- chalk.gray('\n🔍 Discovering available API modules from npm...')
233
- );
234
-
235
- const groupedModules = await this.getModulesByType();
236
- const choices = [];
237
- // eslint-disable-next-line global-require
238
- const { Separator } = this.prompts || require('@inquirer/prompts');
239
-
240
- Object.entries(groupedModules).forEach(([category, modules]) => {
241
- if (modules.length === 0) return;
242
- choices.push(new Separator(`--- ${category} ---`));
243
- modules.forEach((mod) => {
244
- choices.push({
245
- name: `${mod.integrationName} - ${
246
- mod.description || 'No description'
247
- }`,
248
- value: mod.name.replace('@friggframework/api-module-', ''),
249
- short: mod.integrationName,
250
- });
251
- });
229
+ config.installDependencies = await confirm({
230
+ message: 'Install dependencies now?',
231
+ default: true
252
232
  });
253
233
 
254
- if (choices.length === 0) {
255
- console.log(
256
- chalk.yellow(
257
- '⚠️ Could not fetch modules from npm. Use `frigg search` / `frigg install <module>` later.'
258
- )
259
- );
260
- return [];
261
- }
262
-
263
- return this.ask('checkbox', {
264
- message:
265
- 'Select API modules to integrate (space to select, enter to confirm):',
266
- choices,
267
- default: [],
234
+ config.initializeGit = await confirm({
235
+ message: 'Initialize Git repository?',
236
+ default: true
268
237
  });
269
- }
270
238
 
271
- async getModulesByType() {
272
- try {
273
- return await npmRegistry.getModulesByType();
274
- } catch (error) {
275
- if (this.options.verbose) {
276
- console.error('Failed to fetch modules:', error.message);
277
- }
278
- return {};
279
- }
239
+ return config;
280
240
  }
281
241
 
282
242
  /**
@@ -285,179 +245,313 @@ class BackendFirstHandler {
285
245
  async createProject(deploymentMode, config) {
286
246
  console.log(chalk.blue('\n📁 Creating Frigg backend application...'));
287
247
 
288
- const packageName =
289
- deploymentMode === 'embedded'
290
- ? `${this.appName}-frigg-integration`
291
- : this.appName;
248
+ // Ensure target directory exists and is safe
249
+ await this.ensureSafeDirectory();
292
250
 
293
- await fs.ensureDir(this.projectDir);
294
- await this.copyTemplate(this.projectDir, packageName);
295
- await this.writePackageJson(this.projectDir, packageName);
296
- await this.validateGeneratedAppDefinition(
297
- resolveInside(this.projectDir, 'index.js')
298
- );
251
+ if (deploymentMode === 'standalone') {
252
+ await this.createStandaloneProject(config);
253
+ } else {
254
+ await this.createEmbeddedProject(config);
255
+ }
299
256
 
257
+ // Initialize git if requested
300
258
  if (config.initializeGit) {
301
259
  await this.initializeGit();
302
260
  }
303
261
 
262
+ // Install dependencies if requested
304
263
  if (config.installDependencies) {
305
- config.dependenciesInstalled = await this.installDependencies();
264
+ await this.installDependencies(config);
306
265
  }
307
266
  }
308
267
 
309
268
  /**
310
- * Copy the backend template into `dir`, substituting the project name and
311
- * never overwriting a pre-existing README.md/.gitignore without --force.
269
+ * Create standalone Frigg service
312
270
  */
313
- async copyTemplate(dir, packageName) {
314
- const templateDir = resolveInside(this.templatesDir, 'backend');
315
- const entries = await fs.readdir(templateDir);
316
-
317
- for (const entry of entries) {
318
- const destName = RENAMED_TEMPLATE_FILES[entry] || entry;
319
- const dest = resolveInside(dir, destName);
320
-
321
- if (
322
- PRESERVED_FILES.includes(destName) &&
323
- !this.options.force &&
324
- (await fs.pathExists(dest))
325
- ) {
326
- console.log(
327
- chalk.gray(
328
- `Keeping existing ${destName} (use --force to overwrite)`
329
- )
330
- );
331
- continue;
271
+ async createStandaloneProject(config) {
272
+ // Copy backend template
273
+ const backendTemplate = path.join(this.templatesDir, 'backend');
274
+ await fs.copy(backendTemplate, this.targetPath);
275
+
276
+ // Create package.json for standalone mode
277
+ const packageJson = {
278
+ name: this.appName,
279
+ version: '0.1.0',
280
+ private: true,
281
+ scripts: {
282
+ "backend-start": "node infrastructure.js start",
283
+ "start": "npm run backend-start",
284
+ "build": "node infrastructure.js package",
285
+ "deploy": "node infrastructure.js deploy",
286
+ "test": "jest"
287
+ },
288
+ dependencies: {
289
+ "@friggframework/core": "^2.0.0"
332
290
  }
291
+ };
333
292
 
334
- await fs.copy(resolveInside(templateDir, entry), dest);
293
+ // Add demo frontend if requested
294
+ if (config.includeDemoFrontend) {
295
+ packageJson.workspaces = ['backend', 'frontend'];
296
+ packageJson.scripts['dev'] = 'concurrently "npm run backend-start" "npm run frontend:dev"';
297
+ packageJson.scripts['frontend:dev'] = 'cd frontend && npm run dev';
298
+
299
+ await this.createDemoFrontend(config);
335
300
  }
336
301
 
337
- await this.substituteInFile(
338
- resolveInside(dir, 'index.js'),
339
- TEMPLATE_APP_NAME,
340
- `name: '${packageName}',`
341
- );
342
- await this.substituteInFile(
343
- resolveInside(dir, 'README.md'),
344
- TEMPLATE_README_TITLE,
345
- `# ${packageName}`
302
+ // Add selected integrations as dependencies
303
+ if (config.starterIntegrations && config.starterIntegrations.length > 0) {
304
+ for (const integration of config.starterIntegrations) {
305
+ packageJson.dependencies[`@friggframework/api-module-${integration}`] = '^2.0.0';
306
+ }
307
+ }
308
+
309
+ await fs.writeJSON(
310
+ path.join(this.targetPath, 'package.json'),
311
+ packageJson,
312
+ { spaces: 2 }
346
313
  );
347
314
 
348
- // Seed a local .env from the example so `frigg start` has a
349
- // DATABASE_URL to work with. .env is git-ignored.
350
- const envExample = resolveInside(dir, '.env.example');
351
- const env = resolveInside(dir, '.env');
352
- if ((await fs.pathExists(envExample)) && !(await fs.pathExists(env))) {
353
- await fs.copy(envExample, env);
315
+ // Update index.js with selected integrations
316
+ if (config.starterIntegrations && config.starterIntegrations.length > 0) {
317
+ await this.updateAppDefinition(config.starterIntegrations);
354
318
  }
355
- }
356
319
 
357
- async substituteInFile(file, search, replacement) {
358
- const filePath = resolveInside(this.targetPath, file);
359
- if (!(await fs.pathExists(filePath))) return;
360
- const content = await fs.readFile(filePath, 'utf8');
361
- if (!content.includes(search)) return;
362
- await fs.writeFile(filePath, content.replace(search, replacement));
320
+ // Validate generated app definition against schema
321
+ const appDefPath = path.join(this.targetPath, 'index.js');
322
+ await this.validateGeneratedAppDefinition(appDefPath);
323
+
324
+ // Update serverless.yml based on provider
325
+ if (config.serverlessProvider === 'aws') {
326
+ await this.configureAWSServerless();
327
+ }
363
328
  }
364
329
 
365
330
  /**
366
- * Write package.json with the `frigg` scripts and the dependencies the
367
- * composed serverless configuration needs.
331
+ * Create embedded Frigg setup
368
332
  */
369
- async writePackageJson(dir, packageName) {
370
- const { dependencies, devDependencies } = getScaffoldDependencies();
333
+ async createEmbeddedProject(config) {
334
+ console.log(chalk.blue('Creating embedded Frigg setup...'));
335
+
336
+ // Create a minimal setup for embedding
337
+ const setupDir = path.join(this.targetPath, 'frigg-integration');
338
+ await fs.ensureDir(setupDir);
339
+
340
+ // Copy essential files
341
+ const essentialFiles = ['index.js', 'infrastructure.js'];
342
+ for (const file of essentialFiles) {
343
+ const src = path.join(this.templatesDir, 'backend', file);
344
+ const dest = path.join(setupDir, file);
345
+ if (await fs.pathExists(src)) {
346
+ await fs.copy(src, dest);
347
+ }
348
+ }
349
+
350
+ // Validate copied app definition against schema
351
+ const appDefPath = path.join(setupDir, 'index.js');
352
+ if (await fs.pathExists(appDefPath)) {
353
+ await this.validateGeneratedAppDefinition(appDefPath);
354
+ }
355
+
356
+ // Create integration guide
357
+ const integrationGuide = `# Frigg Integration Guide
358
+
359
+ ## Installation
360
+
361
+ Add Frigg to your existing project:
362
+
363
+ \`\`\`bash
364
+ npm install @friggframework/core
365
+ \`\`\`
366
+
367
+ ## Integration Steps
368
+
369
+ 1. Copy the files from \`frigg-integration/\` to your backend
370
+ 2. Import and initialize Frigg in your application:
371
+
372
+ \`\`\`javascript
373
+ const { createFriggBackend } = require('@friggframework/core');
374
+ const appDefinition = require('./app-definition');
375
+
376
+ // In your Express app or serverless handler
377
+ const friggRouter = await createFriggBackend(appDefinition);
378
+ app.use('/api/frigg', friggRouter);
379
+ \`\`\`
380
+
381
+ 3. Configure your environment variables
382
+ 4. Deploy your application
383
+
384
+ ## Development
385
+
386
+ Use \`frigg ui\` to manage your integrations during development.
387
+ `;
388
+
389
+ await fs.writeFile(
390
+ path.join(this.targetPath, 'FRIGG_INTEGRATION.md'),
391
+ integrationGuide
392
+ );
393
+
394
+ // Add package.json with Frigg dependency
371
395
  const packageJson = {
372
- name: packageName,
396
+ name: `${this.appName}-frigg-integration`,
373
397
  version: '0.1.0',
374
398
  private: true,
375
- main: 'index.js',
376
- scripts: getScaffoldScripts(),
377
- dependencies,
378
- devDependencies,
399
+ dependencies: {
400
+ "@friggframework/core": "^2.0.0"
401
+ }
379
402
  };
380
403
 
381
- await fs.writeJSON(resolveInside(dir, 'package.json'), packageJson, {
382
- spaces: 2,
383
- });
404
+ await fs.writeJSON(
405
+ path.join(setupDir, 'package.json'),
406
+ packageJson,
407
+ { spaces: 2 }
408
+ );
384
409
  }
385
410
 
386
411
  /**
387
- * Ensure the directory the backend is written to is missing or empty
388
- * (apart from a few harmless files), unless --force is given.
412
+ * Create demo frontend
389
413
  */
390
- async ensureSafeDirectory(directory = this.targetPath) {
391
- const dir = resolveInside(this.targetPath, directory);
392
- if (!(await fs.pathExists(dir))) {
393
- return;
414
+ async createDemoFrontend(config) {
415
+ console.log(chalk.blue('Creating demo frontend...'));
416
+
417
+ const frontendDir = path.join(this.targetPath, 'frontend');
418
+ await fs.ensureDir(frontendDir);
419
+
420
+ // Copy framework-specific template
421
+ const frameworkTemplate = path.join(this.templatesDir, config.frontendFramework);
422
+ if (await fs.pathExists(frameworkTemplate)) {
423
+ await fs.copy(frameworkTemplate, frontendDir);
424
+ }
425
+
426
+ // Add demo auth configuration
427
+ if (config.demoAuthMode === 'mock') {
428
+ await this.addMockAuth(frontendDir, config.frontendFramework);
394
429
  }
395
430
 
396
- const files = await fs.readdir(dir);
397
- const conflictingFiles = files.filter(
398
- (f) => !ALLOWED_EXISTING_FILES.includes(f)
431
+ // Add demo notice to README
432
+ const demoNotice = `# Frigg Demo Frontend
433
+
434
+ > ⚠️ **This is a demonstration frontend only!**
435
+ >
436
+ > This frontend showcases how to integrate Frigg into your application.
437
+ > For production use, integrate Frigg into your existing application.
438
+ >
439
+ > For development and management, use \`frigg ui\` instead.
440
+
441
+ ## Purpose
442
+
443
+ This demo shows:
444
+ - How to authenticate with Frigg
445
+ - How to display available integrations
446
+ - How to handle OAuth flows
447
+ - How to manage user connections
448
+
449
+ ## Getting Started
450
+
451
+ \`\`\`bash
452
+ npm install
453
+ npm run dev
454
+ \`\`\`
455
+
456
+ ## Production Integration
457
+
458
+ To integrate Frigg into your production application:
459
+ 1. Review the API calls in \`src/services/frigg.js\`
460
+ 2. Copy the relevant components to your application
461
+ 3. Adapt the authentication to your system
462
+ 4. Style according to your design system
463
+ `;
464
+
465
+ await fs.writeFile(
466
+ path.join(frontendDir, 'README.md'),
467
+ demoNotice
468
+ );
469
+ }
470
+
471
+ /**
472
+ * Add mock authentication to demo
473
+ */
474
+ async addMockAuth(frontendDir, framework) {
475
+ const mockAuthConfig = {
476
+ users: [
477
+ { username: 'demo', password: 'demo', name: 'Demo User' }
478
+ ],
479
+ message: 'Use demo/demo to login'
480
+ };
481
+
482
+ await fs.writeJSON(
483
+ path.join(frontendDir, 'mock-auth.json'),
484
+ mockAuthConfig,
485
+ { spaces: 2 }
399
486
  );
487
+ }
400
488
 
489
+ /**
490
+ * Ensure target directory is safe
491
+ */
492
+ async ensureSafeDirectory() {
493
+ await fs.ensureDir(this.targetPath);
494
+
495
+ const files = await fs.readdir(this.targetPath);
496
+ const allowedFiles = ['.git', '.gitignore', 'README.md', '.DS_Store'];
497
+ const conflictingFiles = files.filter(f => !allowedFiles.includes(f));
498
+
401
499
  if (conflictingFiles.length > 0 && !this.options.force) {
402
- console.log(chalk.red(`\n❌ Directory is not empty: ${dir}`));
403
- console.log(
404
- chalk.yellow('Found files:'),
405
- conflictingFiles.join(', ')
406
- );
500
+ console.log(chalk.red('\n❌ Directory is not empty!'));
501
+ console.log(chalk.yellow('Found files:'), conflictingFiles.join(', '));
407
502
  console.log(chalk.gray('Use --force to override\n'));
408
503
  throw new Error('Directory not empty');
409
504
  }
410
505
  }
411
506
 
507
+ /**
508
+ * Configure AWS serverless
509
+ */
510
+ async configureAWSServerless() {
511
+ // Update serverless.yml for AWS
512
+ const serverlessPath = path.join(this.targetPath, 'serverless.yml');
513
+ if (await fs.pathExists(serverlessPath)) {
514
+ // Keep existing AWS configuration
515
+ console.log(chalk.gray('AWS Lambda configuration ready'));
516
+ }
517
+ }
518
+
412
519
  /**
413
520
  * Initialize git repository
414
521
  */
415
522
  async initializeGit() {
416
- // Argument arrays, no shell: nothing here is parsed by a shell.
417
- const git = (args) =>
418
- spawnSync('git', args, {
419
- cwd: this.projectDir,
420
- stdio: 'ignore',
421
- shell: false,
523
+ try {
524
+ execSync('git init', { cwd: this.targetPath, stdio: 'ignore' });
525
+ execSync('git add -A', { cwd: this.targetPath, stdio: 'ignore' });
526
+ execSync('git commit -m "Initial commit from Frigg CLI"', {
527
+ cwd: this.targetPath,
528
+ stdio: 'ignore'
422
529
  });
423
- // Git is a convenience: a missing git or git identity is not fatal.
424
- for (const args of [
425
- ['init'],
426
- ['add', '-A'],
427
- ['commit', '-m', 'Initial commit from Frigg CLI'],
428
- ]) {
429
- const result = git(args);
430
- if (result.error || result.status !== 0) {
431
- return;
432
- }
530
+ console.log(chalk.gray('Git repository initialized'));
531
+ } catch (e) {
532
+ // Git init failed, not critical
433
533
  }
434
- console.log(chalk.gray('Git repository initialized'));
435
534
  }
436
535
 
437
536
  /**
438
537
  * Install dependencies
439
- * @returns {boolean} whether the install succeeded
440
538
  */
441
- async installDependencies() {
539
+ async installDependencies(config) {
442
540
  console.log(chalk.blue('\n📦 Installing dependencies...'));
443
-
541
+
444
542
  const useYarn = this.isUsingYarn();
445
543
  const command = useYarn ? 'yarn' : 'npm';
446
544
  const args = useYarn ? [] : ['install'];
447
545
 
448
546
  const proc = spawn.sync(command, args, {
449
- cwd: this.projectDir,
450
- stdio: 'inherit',
547
+ cwd: this.targetPath,
548
+ stdio: 'inherit'
451
549
  });
452
550
 
453
551
  if (proc.status !== 0) {
454
552
  console.log(chalk.yellow('\n⚠️ Dependency installation failed'));
455
- console.log(
456
- chalk.gray(`You can install manually with: ${command} install`)
457
- );
458
- return false;
553
+ console.log(chalk.gray(`You can install manually with: ${command} install`));
459
554
  }
460
- return true;
461
555
  }
462
556
 
463
557
  /**
@@ -468,132 +562,174 @@ class BackendFirstHandler {
468
562
  }
469
563
 
470
564
  /**
471
- * Validate the generated app definition against the app-definition
472
- * schema by loading the `Definition` the generated index.js exports.
473
- *
474
- * Validation problems are reported as warnings; they never abort init.
475
- *
476
- * @returns {boolean} true when the definition is valid
565
+ * Get available modules from npm
477
566
  */
478
- async validateGeneratedAppDefinition(appDefPath) {
479
- if (this.options.verbose) {
480
- console.log(
481
- chalk.gray('🔍 Validating app definition against schema...')
482
- );
483
- }
484
-
485
- let definition;
567
+ async getAvailableModules() {
486
568
  try {
487
- const resolved = require.resolve(appDefPath);
488
- delete require.cache[resolved];
489
- // eslint-disable-next-line global-require
490
- ({ Definition: definition } = require(resolved));
569
+ const modules = await npmRegistry.searchApiModules();
570
+ return modules;
491
571
  } catch (error) {
492
- console.log(
493
- chalk.yellow(
494
- `⚠️ Could not load the generated app definition for validation: ${error.message}`
495
- )
496
- );
497
- return false;
572
+ console.error('Failed to fetch modules:', error.message);
573
+ return [];
498
574
  }
575
+ }
499
576
 
500
- if (!definition) {
501
- console.log(
502
- chalk.yellow(
503
- `⚠️ ${path.basename(
504
- appDefPath
505
- )} does not export a Definition`
506
- )
507
- );
508
- return false;
509
- }
577
+ /**
578
+ * Select from default integrations when npm is unavailable
579
+ */
580
+ async selectDefaultIntegrations() {
581
+ return await multiselect({
582
+ message: 'Select starter integrations (space to select, enter to confirm):',
583
+ choices: [
584
+ { name: 'Salesforce - CRM integration', value: 'salesforce' },
585
+ { name: 'HubSpot - Marketing automation', value: 'hubspot' },
586
+ { name: 'Slack - Team communication', value: 'slack' },
587
+ { name: 'Google Sheets - Spreadsheet integration', value: 'google-sheets' },
588
+ { name: 'Stripe - Payment processing', value: 'stripe' },
589
+ { name: 'Airtable - Database integration', value: 'airtable' },
590
+ { name: 'Mailchimp - Email marketing', value: 'mailchimp' },
591
+ { name: 'Zendesk - Customer support', value: 'zendesk' }
592
+ ],
593
+ instructions: '\n Press <space> to select, <a> to toggle all, <enter> to confirm\n'
594
+ });
595
+ }
510
596
 
511
- const result = validateAppDefinition(definition);
512
- if (!result.valid) {
513
- console.log(
514
- chalk.yellow('⚠️ App definition has validation warnings:')
597
+ /**
598
+ * Update index.js with selected integrations
599
+ */
600
+ async updateAppDefinition(integrations) {
601
+ const appDefPath = path.join(this.targetPath, 'index.js');
602
+ if (await fs.pathExists(appDefPath)) {
603
+ let content = await fs.readFile(appDefPath, 'utf8');
604
+
605
+ // Add import statements for selected integrations
606
+ const importStatements = integrations.map(name => {
607
+ const className = this.getIntegrationClassName(name);
608
+ return `const ${className} = require('./src/integrations/${className}');`;
609
+ }).join('\n');
610
+
611
+ // Add imports after the existing comment block
612
+ content = content.replace(
613
+ '// Import your integrations here\n// const ExampleIntegration = require(\'./src/integrations/ExampleIntegration\');',
614
+ `// Import your integrations here\n${importStatements}`
615
+ );
616
+
617
+ // Add integrations to the array
618
+ const integrationList = integrations.map(name => {
619
+ const className = this.getIntegrationClassName(name);
620
+ return ` ${className},`;
621
+ }).join('\n');
622
+
623
+ content = content.replace(
624
+ ' // Add your integrations here as you install them\n // Example:\n // ExampleIntegration,',
625
+ ` // Selected integrations\n${integrationList}`
515
626
  );
516
- console.log(chalk.gray(formatErrors(result.errors)));
517
- return false;
627
+
628
+ await fs.writeFile(appDefPath, content);
518
629
  }
630
+ }
631
+
632
+ /**
633
+ * Get integration class name from module name
634
+ */
635
+ getIntegrationClassName(moduleName) {
636
+ const classNames = {
637
+ 'salesforce': 'SalesforceIntegration',
638
+ 'hubspot': 'HubSpotIntegration',
639
+ 'slack': 'SlackIntegration',
640
+ 'google-sheets': 'GoogleSheetsIntegration',
641
+ 'stripe': 'StripeIntegration',
642
+ 'airtable': 'AirtableIntegration',
643
+ 'mailchimp': 'MailchimpIntegration',
644
+ 'zendesk': 'ZendeskIntegration'
645
+ };
646
+
647
+ return classNames[moduleName] || `${moduleName.charAt(0).toUpperCase() + moduleName.slice(1)}Integration`;
648
+ }
519
649
 
520
- if (this.options.verbose) {
650
+ /**
651
+ * Validate the generated app definition with the same code path as
652
+ * `frigg validate`, `frigg build` and `frigg deploy` (ADR-051). Problems
653
+ * are reported as warnings: they never stop `frigg init`.
654
+ */
655
+ async validateGeneratedAppDefinition(appDefPath) {
656
+ try {
657
+ const report = runValidation({ cwd: path.dirname(appDefPath) });
658
+ const issues = [...report.errors, ...report.warnings];
659
+ if (issues.length === 0) {
660
+ if (this.options.verbose) {
661
+ console.log(chalk.green('✅ App definition passes validation'));
662
+ }
663
+ return true;
664
+ }
665
+ if (report.errors.length === 1 && report.errors[0].code === 'load-failed') {
666
+ // Before `npm install`, index.js cannot load its dependencies yet.
667
+ if (this.options.verbose) {
668
+ console.log(chalk.gray('App definition not validated yet: run `frigg validate` after `npm install`.'));
669
+ }
670
+ return true;
671
+ }
672
+ console.log(chalk.yellow('⚠️ App definition validation:'));
521
673
  console.log(
522
- chalk.green('✅ App definition passes schema validation')
674
+ formatReport({
675
+ ...report,
676
+ errors: [],
677
+ warnings: issues.map((issue) => ({ ...issue, severity: 'warning' })),
678
+ })
523
679
  );
680
+ return report.errors.length === 0;
681
+ } catch (error) {
682
+ if (this.options.verbose) {
683
+ console.log(chalk.yellow(`⚠️ Validation skipped: ${error.message}`));
684
+ }
685
+ return true; // Don't fail the process for validation issues
524
686
  }
525
- return true;
526
687
  }
527
688
 
528
689
  /**
529
690
  * Display next steps
530
691
  */
531
692
  displayNextSteps(deploymentMode, config) {
532
- const relativePath = path.relative(process.cwd(), this.projectDir);
693
+ const relativePath = path.relative(process.cwd(), this.targetPath);
533
694
  const cdPath = relativePath || '.';
534
- let step = 1;
535
- const printStep = (text, command) => {
536
- console.log(`${step}. ${text}`);
537
- console.log(chalk.cyan(` ${command}\n`));
538
- step += 1;
539
- };
540
695
 
541
696
  console.log(chalk.bold('\n📋 Next Steps:\n'));
542
697
 
543
- printStep('Navigate to your project:', `cd ${cdPath}`);
698
+ console.log(`1. Navigate to your project:`);
699
+ console.log(chalk.cyan(` cd ${cdPath}\n`));
544
700
 
545
- if (!config.dependenciesInstalled) {
546
- printStep('Install dependencies:', 'npm install');
547
- }
701
+ if (deploymentMode === 'standalone') {
702
+ console.log(`2. Start the development server:`);
703
+ console.log(chalk.cyan(` npm start\n`));
548
704
 
549
- printStep(
550
- 'Start PostgreSQL and check DATABASE_URL in .env:',
551
- 'docker run --name frigg-postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres:16'
552
- );
553
- printStep('Set up the database:', 'npm run db:setup');
554
- printStep('Start the development server:', 'npm start');
555
-
556
- const integrations = config.starterIntegrations || [];
557
- if (integrations.length > 0) {
558
- printStep(
559
- 'Install the API modules you selected (each adds src/integrations/<Name>Integration.js and lists it in index.js):',
560
- integrations
561
- .map((name) => `npx frigg install ${name}`)
562
- .join('\n ')
563
- );
705
+ console.log(`3. Open the Frigg UI for development:`);
706
+ console.log(chalk.cyan(` frigg ui\n`));
707
+
708
+ if (config.serverlessProvider === 'aws') {
709
+ console.log(`4. Deploy to AWS Lambda:`);
710
+ console.log(chalk.cyan(` npm run deploy\n`));
711
+ }
564
712
  } else {
565
- printStep(
566
- 'Add an integration from the API module library (adds src/integrations/<Name>Integration.js and lists it in index.js):',
567
- 'npx frigg install <module> # e.g. npx frigg install hubspot'
568
- );
569
- }
713
+ console.log(`2. Follow the integration guide:`);
714
+ console.log(chalk.cyan(` cat FRIGG_INTEGRATION.md\n`));
570
715
 
571
- if (config.serverlessProvider === 'aws') {
572
- printStep(
573
- 'Deploy to AWS Lambda with a hosted PostgreSQL (DATABASE_URL comes from your shell, not .env; see README.md):',
574
- "DATABASE_URL='postgresql://...?sslmode=require' npm run deploy -- --stage prod"
575
- );
716
+ console.log(`3. Install Frigg in your main project:`);
717
+ console.log(chalk.cyan(` npm install @friggframework/core\n`));
718
+
719
+ console.log(`4. Use Frigg UI for development:`);
720
+ console.log(chalk.cyan(` frigg ui\n`));
576
721
  }
577
722
 
578
- if (config.needsCustomApiModule) {
579
- console.log(
580
- chalk.gray(
581
- 'To build an API module for your own application, see https://docs.friggframework.org (API modules).'
582
- )
583
- );
723
+ if (config.includeDemoFrontend) {
724
+ console.log(chalk.yellow('\n⚠️ Demo Frontend:'));
725
+ console.log(chalk.gray(' The included frontend is for demonstration only.'));
726
+ console.log(chalk.gray(' See frontend/README.md for integration guidance.'));
584
727
  }
585
728
 
586
729
  console.log(chalk.green('\n🎉 Happy integrating with Frigg!\n'));
587
- console.log(
588
- chalk.gray('Documentation: https://docs.friggframework.org')
589
- );
590
- console.log(
591
- chalk.gray(
592
- 'Support: https://github.com/friggframework/frigg/issues'
593
- )
594
- );
730
+ console.log(chalk.gray('Documentation: https://docs.frigg.dev'));
731
+ console.log(chalk.gray('Support: https://github.com/friggframework/frigg/issues'));
595
732
  }
596
733
  }
597
734
 
598
- module.exports = BackendFirstHandler;
599
- module.exports.EMBEDDED_DIR = EMBEDDED_DIR;
735
+ module.exports = BackendFirstHandler;