@friggframework/devtools 2.0.0--canary.686.df38e8e.0 → 2.0.0--canary.710.9045bbc.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 (80) hide show
  1. package/frigg-cli/README.md +77 -30
  2. package/frigg-cli/__tests__/unit/commands/deploy.test.js +30 -24
  3. package/frigg-cli/__tests__/unit/commands/doctor.test.js +10 -6
  4. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +18 -0
  5. package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
  6. package/frigg-cli/__tests__/unit/commands/install.test.js +601 -341
  7. package/frigg-cli/__tests__/unit/commands/ui.test.js +31 -30
  8. package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
  9. package/frigg-cli/build-command/index.js +1 -32
  10. package/frigg-cli/deploy-command/index.js +2 -50
  11. package/frigg-cli/doctor-command/index.js +0 -7
  12. package/frigg-cli/generate-command/index.js +1 -0
  13. package/frigg-cli/generate-iam-command.js +1 -7
  14. package/frigg-cli/index.js +9 -4
  15. package/frigg-cli/init-command/backend-first-handler.js +397 -554
  16. package/frigg-cli/init-command/deployment-modes.js +7 -0
  17. package/frigg-cli/init-command/index.js +82 -35
  18. package/frigg-cli/init-command/safe-path.js +58 -0
  19. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  20. package/frigg-cli/install-command/app-definition.js +174 -0
  21. package/frigg-cli/install-command/commit-changes.js +40 -8
  22. package/frigg-cli/install-command/environment-variables.js +15 -0
  23. package/frigg-cli/install-command/index.js +96 -21
  24. package/frigg-cli/install-command/install-package.js +77 -4
  25. package/frigg-cli/install-command/integration-file.js +20 -11
  26. package/frigg-cli/install-command/resolve-module.js +69 -0
  27. package/frigg-cli/install-command/template.js +102 -75
  28. package/frigg-cli/install-command/validate-package.js +36 -4
  29. package/frigg-cli/package.json +1 -1
  30. package/frigg-cli/repair-command/index.js +0 -7
  31. package/frigg-cli/start-command/index.js +0 -58
  32. package/frigg-cli/templates/backend/README.md +267 -0
  33. package/frigg-cli/templates/backend/env.example +20 -0
  34. package/frigg-cli/templates/backend/gitignore +10 -0
  35. package/frigg-cli/templates/backend/index.js +114 -0
  36. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  37. package/frigg-cli/test/init-command.test.js +9 -2
  38. package/infrastructure/README.md +2 -4
  39. package/infrastructure/__tests__/postgres-config.test.js +241 -835
  40. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +148 -0
  41. package/infrastructure/__tests__/template-generation.test.js +33 -12
  42. package/infrastructure/create-frigg-infrastructure.js +0 -14
  43. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +21 -1
  44. package/infrastructure/domains/admin-scripts/admin-script-builder.js +6 -2
  45. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +30 -0
  46. package/infrastructure/domains/database/aurora-builder.js +13 -2
  47. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  48. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  49. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  50. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  51. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  52. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  53. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  54. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  55. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  56. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  57. package/infrastructure/domains/networking/vpc-builder.test.js +32 -13
  58. package/infrastructure/domains/parameters/offload-utils.js +0 -1
  59. package/infrastructure/domains/security/iam-generator.js +112 -5
  60. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  61. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  62. package/infrastructure/domains/shared/environment-builder.js +1 -12
  63. package/infrastructure/domains/shared/environment-builder.test.js +0 -20
  64. package/infrastructure/domains/shared/types/app-definition.js +1 -15
  65. package/infrastructure/domains/shared/utilities/base-definition-factory.js +17 -30
  66. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +22 -85
  67. package/infrastructure/infrastructure-composer.test.js +268 -801
  68. package/infrastructure/scripts/build-prisma-layer.js +5 -32
  69. package/infrastructure/scripts/build-prisma-layer.test.js +28 -42
  70. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  71. package/package.json +10 -8
  72. package/frigg-cli/__tests__/unit/commands/provider-dispatch.test.js +0 -140
  73. package/frigg-cli/index.test.js +0 -158
  74. package/frigg-cli/utils/provider-helper.js +0 -80
  75. package/infrastructure/__tests__/create-frigg-infrastructure-provider.test.js +0 -64
  76. package/infrastructure/__tests__/management-api-gateway-routes.test.js +0 -335
  77. package/infrastructure/integration.test.js +0 -381
  78. package/infrastructure/provider-build.js +0 -119
  79. package/test/npm-install-guard.js +0 -104
  80. package/test/npm-install-guard.test.js +0 -53
@@ -249,36 +249,6 @@ async function createLayerStructure() {
249
249
  logSuccess(`Created ${LAYER_NODE_MODULES}`);
250
250
  }
251
251
 
252
- /**
253
- * Run `npm install --omit=dev` confined to the layer directory.
254
- *
255
- * npm resolves its project root by walking up from cwd to the nearest
256
- * package.json. If the layer's package.json is missing when npm starts (a
257
- * concurrent build cleaned the directory, as two jest workers composing at
258
- * once did), npm walked up into the enclosing workspace and ran
259
- * `install --omit=dev` there, pruning the devDependencies (jest, jest-util)
260
- * out of the repository's root node_modules. So: the package.json must exist,
261
- * and `--prefix` pins npm's root to the layer directory while
262
- * `--workspaces=false` stops it acting on an enclosing workspace.
263
- *
264
- * @param {string} layerNodejsDir - absolute path of <layer>/nodejs
265
- * @param {Object} [options]
266
- * @param {Object} [options.env]
267
- * @param {Function} [options.exec] - execSync stand-in (tests)
268
- */
269
- function runLayerInstall(layerNodejsDir, { env = process.env, exec = execSync } = {}) {
270
- const manifest = path.join(layerNodejsDir, 'package.json');
271
- if (!fs.existsSync(manifest)) {
272
- throw new Error(
273
- `Refusing to run npm install: ${manifest} does not exist (npm would install into an enclosing project)`
274
- );
275
- }
276
- exec(
277
- `npm install --omit=dev --no-package-lock --workspaces=false --prefix ${JSON.stringify(layerNodejsDir)}`,
278
- { cwd: layerNodejsDir, stdio: 'inherit', env }
279
- );
280
- }
281
-
282
252
  /**
283
253
  * Install Prisma client directly into layer (RUNTIME ONLY - NO CLI)
284
254
  *
@@ -315,7 +285,11 @@ async function installPrismaPackages() {
315
285
  PRISMA_CLI_BINARY_TARGETS: 'rhel-openssl-3.0.x',
316
286
  };
317
287
 
318
- runLayerInstall(path.join(LAYER_OUTPUT_PATH, 'nodejs'), { env });
288
+ execSync('npm install --omit=dev --no-package-lock', {
289
+ cwd: path.join(LAYER_OUTPUT_PATH, 'nodejs'),
290
+ stdio: 'inherit',
291
+ env,
292
+ });
319
293
  logSuccess('Prisma packages installed with Lambda binary target');
320
294
  } catch (error) {
321
295
  throw new Error(`Failed to install Prisma packages: ${error.message}`);
@@ -719,7 +693,6 @@ if (require.main === module) {
719
693
 
720
694
  module.exports = {
721
695
  buildPrismaLayer,
722
- runLayerInstall,
723
696
  getGeneratedClientPackages,
724
697
  getMigrationsPackages,
725
698
  getMigrationSourcePath,
@@ -143,14 +143,35 @@ describe('getMigrationsPackages()', () => {
143
143
  });
144
144
 
145
145
  describe('getMigrationSourcePath()', () => {
146
- it('should return correct source path for database type', () => {
147
- const searchPaths = ['/workspace/packages/core'];
148
- const dbType = 'postgresql';
146
+ // getMigrationSourcePath() returns the first search path whose
147
+ // prisma-<dbType>/migrations directory exists on disk, so the test needs a
148
+ // real directory rather than a made-up absolute path.
149
+ const fs = require('fs');
150
+ const os = require('os');
151
+ const path = require('path');
152
+ let tmpRoot;
149
153
 
150
- const sourcePath = getMigrationSourcePath(searchPaths, dbType);
151
- expect(sourcePath).toBe(
152
- '/workspace/packages/core/prisma-postgresql/migrations'
153
- );
154
+ beforeEach(() => {
155
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-prisma-layer-'));
156
+ });
157
+
158
+ afterEach(() => {
159
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
160
+ });
161
+
162
+ it('should return the migrations path of the first search path that has one', () => {
163
+ const missing = path.join(tmpRoot, 'missing');
164
+ const core = path.join(tmpRoot, 'packages', 'core');
165
+ const expected = path.join(core, 'prisma-postgresql', 'migrations');
166
+ fs.mkdirSync(expected, { recursive: true });
167
+
168
+ const sourcePath = getMigrationSourcePath([missing, core], 'postgresql');
169
+ expect(sourcePath).toBe(expected);
170
+ });
171
+
172
+ it('should return null when no search path has migrations for the database type', () => {
173
+ const sourcePath = getMigrationSourcePath([tmpRoot], 'postgresql');
174
+ expect(sourcePath).toBeNull();
154
175
  });
155
176
  });
156
177
 
@@ -168,38 +189,3 @@ describe('getMigrationDestinationPath()', () => {
168
189
  );
169
190
  });
170
191
  });
171
-
172
-
173
- describe('runLayerInstall', () => {
174
- const fs = require('fs');
175
- const os = require('os');
176
- const path = require('path');
177
- const { runLayerInstall } = require('./build-prisma-layer');
178
-
179
- it('refuses when the layer package.json is missing (npm would walk up into the workspace)', () => {
180
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'layer-'));
181
- const exec = jest.fn();
182
- try {
183
- expect(() => runLayerInstall(dir, { exec })).toThrow(/Refusing to run npm install/);
184
- expect(exec).not.toHaveBeenCalled();
185
- } finally {
186
- fs.rmSync(dir, { recursive: true, force: true });
187
- }
188
- });
189
-
190
- it('pins npm to the layer directory and off any enclosing workspace', () => {
191
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'layer-'));
192
- fs.writeFileSync(path.join(dir, 'package.json'), '{}');
193
- const exec = jest.fn();
194
- try {
195
- runLayerInstall(dir, { exec, env: { X: '1' } });
196
- const [command, options] = exec.mock.calls[0];
197
- expect(command).toContain('npm install --omit=dev');
198
- expect(command).toContain('--workspaces=false');
199
- expect(command).toContain(`--prefix ${JSON.stringify(dir)}`);
200
- expect(options).toMatchObject({ cwd: dir, env: { X: '1' } });
201
- } finally {
202
- fs.rmSync(dir, { recursive: true, force: true });
203
- }
204
- });
205
- });
@@ -1,14 +1,29 @@
1
1
  const fs = require('fs');
2
2
  const path = require('path');
3
- const { BuildTimeDiscovery, runBuildTimeDiscovery } = require('./build-time-discovery');
4
- const { AWSDiscovery } = require('./aws-discovery');
3
+
4
+ // SKIPPED: BuildTimeDiscovery lazily requires './aws-discovery', which was
5
+ // deleted in the hexagonal infrastructure refactor (7b36f0f4). Discovery now
6
+ // lives in domains/shared/resource-discovery.js + providers/aws-provider-adapter.js,
7
+ // and nothing in devtools, the CLI or the serverless plugin invokes
8
+ // build-time-discovery.js / run-discovery.js any more, so this suite cannot load
9
+ // its subject. Either port BuildTimeDiscovery to gatherDiscoveredResources() and
10
+ // rewrite these tests, or delete the dead module and this suite.
11
+ // Tracked in https://github.com/friggframework/frigg/issues/708
12
+ let BuildTimeDiscovery;
13
+ let runBuildTimeDiscovery;
14
+ let AWSDiscovery;
5
15
 
6
16
  // Mock dependencies
7
17
  jest.mock('fs');
8
18
  // Mock will be updated when tests are rewritten for new provider architecture
9
19
  // jest.mock('./aws-discovery');
10
20
 
11
- describe('BuildTimeDiscovery', () => {
21
+ describe.skip('BuildTimeDiscovery', () => {
22
+ beforeAll(() => {
23
+ ({ BuildTimeDiscovery, runBuildTimeDiscovery } = require('./build-time-discovery'));
24
+ ({ AWSDiscovery } = require('./aws-discovery'));
25
+ });
26
+
12
27
  let buildTimeDiscovery;
13
28
  let mockAWSDiscovery;
14
29
  const originalEnv = process.env;
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@friggframework/devtools",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.686.df38e8e.0",
4
+ "version": "2.0.0--canary.710.9045bbc.0",
5
5
  "bin": {
6
6
  "frigg": "./frigg-cli/index.js"
7
7
  },
8
8
  "files": [
9
9
  "frigg-cli/",
10
+ "frigg-cli/templates/",
10
11
  "infrastructure/",
11
12
  "migrations/",
12
13
  "management-ui/dist/",
@@ -18,6 +19,7 @@
18
19
  "@aws-sdk/client-cloudformation": "^3.705.0",
19
20
  "@aws-sdk/client-ec2": "^3.835.0",
20
21
  "@aws-sdk/client-kms": "^3.835.0",
22
+ "@aws-sdk/client-lambda": "^3.714.0",
21
23
  "@aws-sdk/client-rds": "^3.906.0",
22
24
  "@aws-sdk/client-s3": "^3.917.0",
23
25
  "@aws-sdk/client-secrets-manager": "^3.906.0",
@@ -26,9 +28,9 @@
26
28
  "@babel/eslint-parser": "^7.18.9",
27
29
  "@babel/parser": "^7.25.3",
28
30
  "@babel/traverse": "^7.25.3",
29
- "@friggframework/core": "2.0.0--canary.686.df38e8e.0",
30
- "@friggframework/schemas": "2.0.0--canary.686.df38e8e.0",
31
- "@friggframework/test": "2.0.0--canary.686.df38e8e.0",
31
+ "@friggframework/core": "2.0.0--canary.710.9045bbc.0",
32
+ "@friggframework/schemas": "2.0.0--canary.710.9045bbc.0",
33
+ "@friggframework/test": "2.0.0--canary.710.9045bbc.0",
32
34
  "@hapi/boom": "^10.0.1",
33
35
  "@inquirer/prompts": "^5.3.8",
34
36
  "axios": "^1.18.0",
@@ -56,12 +58,12 @@
56
58
  "validate-npm-package-name": "^5.0.0"
57
59
  },
58
60
  "devDependencies": {
59
- "@friggframework/eslint-config": "2.0.0--canary.686.df38e8e.0",
60
- "@friggframework/prettier-config": "2.0.0--canary.686.df38e8e.0",
61
+ "@friggframework/eslint-config": "2.0.0--canary.710.9045bbc.0",
62
+ "@friggframework/prettier-config": "2.0.0--canary.710.9045bbc.0",
61
63
  "aws-sdk-client-mock": "^4.1.0",
62
64
  "aws-sdk-client-mock-jest": "^4.1.0",
63
65
  "jest": "^30.1.3",
64
- "osls": "^3.58.0",
66
+ "osls": "^3.78.0",
65
67
  "prettier": "^2.7.1",
66
68
  "serverless-dotenv-plugin": "^6.0.0",
67
69
  "serverless-esbuild": "^1.54.3",
@@ -89,5 +91,5 @@
89
91
  "publishConfig": {
90
92
  "access": "public"
91
93
  },
92
- "gitHead": "df38e8e8ab471a23861fbdc3e35e99ddc249aef5"
94
+ "gitHead": "9045bbc0a84c7c07271e8599d1600d58790537a6"
93
95
  }
@@ -1,140 +0,0 @@
1
- /**
2
- * Provider dispatch (friggframework/frigg#545): appDefinition.provider
3
- * decides whether a CLI command runs the AWS/serverless path or the
4
- * provider plugin. Uses real temp projects and the real provider-netlify.
5
- */
6
- const fs = require('fs');
7
- const os = require('os');
8
- const path = require('path');
9
-
10
- function writeProject(definitionSource) {
11
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-dispatch-'));
12
- const backend = path.join(dir, 'backend');
13
- fs.mkdirSync(backend);
14
- fs.writeFileSync(path.join(backend, 'package.json'), '{"name":"backend"}');
15
- fs.writeFileSync(path.join(backend, 'index.js'), `module.exports = { Definition: ${definitionSource} };`);
16
- return { dir, backend };
17
- }
18
-
19
- const NETLIFY_APP = `{
20
- name: 'dispatch-app',
21
- provider: 'netlify',
22
- integrations: [],
23
- database: { postgres: { enable: true } },
24
- }`;
25
-
26
- describe('provider-helper', () => {
27
- const { loadProviderForCli, loadCliAppDefinition, isNonAwsProject } = require('../../../utils/provider-helper');
28
- const dirs = [];
29
- afterAll(() => dirs.forEach((d) => fs.rmSync(d, { recursive: true, force: true })));
30
-
31
- it('returns null without an app definition', () => {
32
- expect(loadProviderForCli({ cwd: os.tmpdir() })).toBeNull();
33
- expect(loadCliAppDefinition('/nonexistent/path')).toBeNull();
34
- expect(isNonAwsProject({ cwd: os.tmpdir() })).toBe(false);
35
- });
36
-
37
- it('treats a missing provider as aws with no plugin', () => {
38
- const { dir, backend } = writeProject(`{ integrations: [] }`);
39
- dirs.push(dir);
40
- expect(loadProviderForCli({ cwd: backend })).toEqual(
41
- expect.objectContaining({ providerName: 'aws', provider: null, backendDir: backend })
42
- );
43
- expect(isNonAwsProject({ cwd: backend })).toBe(false);
44
- });
45
-
46
- it('resolves the netlify plugin from the project root or from backend/', () => {
47
- const { dir, backend } = writeProject(NETLIFY_APP);
48
- dirs.push(dir);
49
- for (const cwd of [dir, backend]) {
50
- const result = loadProviderForCli({ cwd });
51
- expect(result.providerName).toBe('netlify');
52
- expect(result.provider.name).toBe('netlify');
53
- expect(result.backendDir).toBe(backend);
54
- }
55
- expect(isNonAwsProject({ cwd: backend })).toBe(true);
56
- });
57
- });
58
-
59
- describe('buildWithProvider', () => {
60
- const { buildWithProvider } = require('../../../../infrastructure/provider-build');
61
-
62
- beforeEach(() => {
63
- jest.spyOn(console, 'log').mockImplementation();
64
- jest.spyOn(console, 'warn').mockImplementation();
65
- jest.spyOn(console, 'error').mockImplementation();
66
- });
67
- afterEach(() => jest.restoreAllMocks());
68
-
69
- it('writes netlify.toml, functions and lib shims beside backend/, where their requires resolve', () => {
70
- const { dir, backend } = writeProject(NETLIFY_APP);
71
- try {
72
- const appDefinition = require(path.join(backend, 'index.js')).Definition;
73
- const { projectDir } = buildWithProvider({ appDefinition, backendDir: backend });
74
-
75
- expect(projectDir).toBe(dir);
76
- expect(fs.existsSync(path.join(dir, 'netlify.toml'))).toBe(true);
77
- const auth = fs.readFileSync(path.join(dir, 'netlify/functions/auth.js'), 'utf8');
78
- expect(auth).toContain("require('../../backend/index.js')");
79
- expect(fs.existsSync(path.join(dir, 'netlify/lib/create-netlify-app-handler.js'))).toBe(true);
80
- // Nothing is written into the backend directory itself.
81
- expect(fs.existsSync(path.join(backend, 'netlify'))).toBe(false);
82
- } finally {
83
- fs.rmSync(dir, { recursive: true, force: true });
84
- }
85
- });
86
-
87
- it('stops on validation errors and writes nothing', () => {
88
- const exit = jest.fn();
89
- const { dir, backend } = writeProject(`{ provider: 'netlify', integrations: [] }`);
90
- try {
91
- const appDefinition = require(path.join(backend, 'index.js')).Definition;
92
- const { written } = buildWithProvider({ appDefinition, backendDir: backend, exit });
93
- expect(exit).toHaveBeenCalledWith(1);
94
- expect(written).toEqual([]);
95
- expect(fs.existsSync(path.join(dir, 'netlify.toml'))).toBe(false);
96
- } finally {
97
- fs.rmSync(dir, { recursive: true, force: true });
98
- }
99
- });
100
- });
101
-
102
- describe('frigg build dispatch', () => {
103
- beforeEach(() => {
104
- jest.resetModules();
105
- jest.spyOn(console, 'log').mockImplementation();
106
- jest.spyOn(console, 'warn').mockImplementation();
107
- });
108
- afterEach(() => {
109
- jest.restoreAllMocks();
110
- jest.dontMock('child_process');
111
- });
112
-
113
- it('builds a netlify app through the plugin, never through osls', async () => {
114
- const spawnSync = jest.fn(() => ({ status: 0 }));
115
- jest.doMock('child_process', () => ({ ...jest.requireActual('child_process'), spawnSync }));
116
- const { dir, backend } = writeProject(NETLIFY_APP);
117
- try {
118
- jest.spyOn(process, 'cwd').mockReturnValue(backend);
119
- await require('../../../build-command').buildCommand({});
120
- expect(spawnSync).not.toHaveBeenCalled();
121
- expect(fs.existsSync(path.join(dir, 'netlify/functions/worker-background.js'))).toBe(true);
122
- } finally {
123
- fs.rmSync(dir, { recursive: true, force: true });
124
- }
125
- });
126
-
127
- it('keeps the serverless path for an aws app', async () => {
128
- const spawnSync = jest.fn(() => ({ status: 0 }));
129
- jest.doMock('child_process', () => ({ ...jest.requireActual('child_process'), spawnSync }));
130
- const { dir, backend } = writeProject(`{ integrations: [] }`);
131
- try {
132
- jest.spyOn(process, 'cwd').mockReturnValue(backend);
133
- await require('../../../build-command').buildCommand({});
134
- expect(spawnSync).toHaveBeenCalledWith('osls', expect.any(Array), expect.any(Object));
135
- expect(fs.existsSync(path.join(dir, 'netlify'))).toBe(false);
136
- } finally {
137
- fs.rmSync(dir, { recursive: true, force: true });
138
- }
139
- });
140
- });
@@ -1,158 +0,0 @@
1
- const { Command } = require('commander');
2
- const { installCommand } = require('./index');
3
- const { validatePackageExists } = require('./install-command/validate-package');
4
- const { findNearestBackendPackageJson, validateBackendPath } = require('@friggframework/core');
5
- const { installPackage } = require('./install-command/install-package');
6
- const { createIntegrationFile } = require('./install-command/integration-file');
7
- const { updateBackendJsFile } = require('./install-command/backend-js');
8
- const { commitChanges } = require('./install-command/commit-changes');
9
- const { logInfo, logError } = require('./install-command/logger');
10
-
11
- describe('CLI Command Tests', () => {
12
- it('should successfully install an API module when all steps complete without errors', async () => {
13
- const mockApiModuleName = 'testModule';
14
- const mockPackageName = `@friggframework/api-module-${mockApiModuleName}`;
15
- const mockBackendPath = '/mock/backend/path';
16
-
17
- jest.mock('./install-command/validate-package', () => ({
18
- validatePackageExists: jest.fn().mockResolvedValue(true),
19
- }));
20
- jest.mock('./utils/backend-path', () => ({
21
- findNearestBackendPackageJson: jest
22
- .fn()
23
- .mockReturnValue(mockBackendPath),
24
- validateBackendPath: jest.fn().mockReturnValue(true),
25
- }));
26
- jest.mock('./install-command/install-package', () => ({
27
- installPackage: jest.fn().mockReturnValue(true),
28
- }));
29
- jest.mock('./install-command/integration-file', () => ({
30
- createIntegrationFile: jest.fn().mockReturnValue(true),
31
- }));
32
- jest.mock('./install-command/backend-js', () => ({
33
- updateBackendJsFile: jest.fn().mockReturnValue(true),
34
- }));
35
- jest.mock('./install-command/commit-changes', () => ({
36
- commitChanges: jest.fn().mockReturnValue(true),
37
- }));
38
- jest.mock('./install-command/logger', () => ({
39
- logInfo: jest.fn(),
40
- logError: jest.fn(),
41
- }));
42
-
43
- const program = new Command();
44
- program
45
- .command('install <apiModuleName>')
46
- .description('Install an API module')
47
- .action(installCommand);
48
-
49
- await program.parseAsync(['node', 'install', mockApiModuleName]);
50
-
51
- expect(validatePackageExists).toHaveBeenCalledWith(mockPackageName);
52
- expect(findNearestBackendPackageJson).toHaveBeenCalled();
53
- expect(validateBackendPath).toHaveBeenCalledWith(mockBackendPath);
54
- expect(installPackage).toHaveBeenCalledWith(
55
- mockBackendPath,
56
- mockPackageName
57
- );
58
- expect(createIntegrationFile).toHaveBeenCalledWith(
59
- mockBackendPath,
60
- mockApiModuleName
61
- );
62
- expect(updateBackendJsFile).toHaveBeenCalledWith(
63
- mockBackendPath,
64
- mockApiModuleName
65
- );
66
- expect(commitChanges).toHaveBeenCalledWith(
67
- mockBackendPath,
68
- mockApiModuleName
69
- );
70
- expect(logInfo).toHaveBeenCalledWith(
71
- `Successfully installed ${mockPackageName} and updated the project.`
72
- );
73
- });
74
-
75
- it('should log an error and exit with code 1 if the package does not exist', async () => {
76
- const mockExit = jest
77
- .spyOn(process, 'exit')
78
- .mockImplementation(() => {});
79
- const mockLogError = jest
80
- .spyOn(require('./install-command/logger'), 'logError')
81
- .mockImplementation(() => {});
82
- const mockValidatePackageExists = jest
83
- .spyOn(
84
- require('./install-command/validate-package'),
85
- 'validatePackageExists'
86
- )
87
- .mockImplementation(() => {
88
- throw new Error('Package not found');
89
- });
90
-
91
- const program = new Command();
92
- program
93
- .command('install <apiModuleName>')
94
- .description('Install an API module')
95
- .action(installCommand);
96
-
97
- await program.parseAsync(['node', 'install', 'nonexistent-package']);
98
-
99
- expect(mockValidatePackageExists).toHaveBeenCalledWith(
100
- '@friggframework/api-module-nonexistent-package'
101
- );
102
- expect(mockLogError).toHaveBeenCalledWith(
103
- 'An error occurred:',
104
- expect.any(Error)
105
- );
106
- expect(mockExit).toHaveBeenCalledWith(1);
107
-
108
- mockExit.mockRestore();
109
- mockLogError.mockRestore();
110
- mockValidatePackageExists.mockRestore();
111
- });
112
-
113
- it('should log an error and exit with code 1 if the backend path is invalid', async () => {
114
- const mockLogError = jest
115
- .spyOn(require('./install-command/logger'), 'logError')
116
- .mockImplementation(() => {});
117
- const mockProcessExit = jest
118
- .spyOn(process, 'exit')
119
- .mockImplementation(() => {});
120
- const mockValidatePackageExists = jest
121
- .spyOn(
122
- require('./install-command/validate-package'),
123
- 'validatePackageExists'
124
- )
125
- .mockResolvedValue(true);
126
- const mockFindNearestBackendPackageJson = jest
127
- .spyOn(
128
- require('./utils/backend-path'),
129
- 'findNearestBackendPackageJson'
130
- )
131
- .mockReturnValue('/invalid/path');
132
- const mockValidateBackendPath = jest
133
- .spyOn(require('./utils/backend-path'), 'validateBackendPath')
134
- .mockImplementation(() => {
135
- throw new Error('Invalid backend path');
136
- });
137
-
138
- const program = new Command();
139
- program
140
- .command('install <apiModuleName>')
141
- .description('Install an API module')
142
- .action(installCommand);
143
-
144
- await program.parseAsync(['node', 'install', 'test-module']);
145
-
146
- expect(mockLogError).toHaveBeenCalledWith(
147
- 'An error occurred:',
148
- expect.any(Error)
149
- );
150
- expect(mockProcessExit).toHaveBeenCalledWith(1);
151
-
152
- mockLogError.mockRestore();
153
- mockProcessExit.mockRestore();
154
- mockValidatePackageExists.mockRestore();
155
- mockFindNearestBackendPackageJson.mockRestore();
156
- mockValidateBackendPath.mockRestore();
157
- });
158
- });
@@ -1,80 +0,0 @@
1
- /**
2
- * CLI Provider Helper (friggframework/frigg#545, 88cf983e / c8705715)
3
- *
4
- * Loads the app definition from the user's project and resolves its
5
- * provider plugin, so CLI commands can delegate to it (Netlify, ...) or fall
6
- * through to the AWS/serverless behaviour.
7
- */
8
- const path = require('path');
9
- const fs = require('fs');
10
-
11
- /**
12
- * Find the backend: <cwd>/backend/index.js, then <cwd>/index.js.
13
- * @param {string} cwd
14
- * @returns {{ appDefinition: Object, backendDir: string } | null}
15
- */
16
- function loadCliBackend(cwd) {
17
- for (const dir of [path.join(cwd, 'backend'), cwd]) {
18
- const indexPath = path.join(dir, 'index.js');
19
- if (!fs.existsSync(indexPath)) continue;
20
- try {
21
- const exported = require(indexPath);
22
- if (exported && exported.Definition) {
23
- return { appDefinition: exported.Definition, backendDir: dir };
24
- }
25
- } catch {
26
- // Failed to load, try next
27
- }
28
- }
29
- return null;
30
- }
31
-
32
- /**
33
- * @param {string} cwd
34
- * @returns {Object|null} the app Definition
35
- */
36
- function loadCliAppDefinition(cwd) {
37
- return loadCliBackend(cwd)?.appDefinition || null;
38
- }
39
-
40
- /**
41
- * Load the app definition and resolve the provider plugin for CLI commands.
42
- *
43
- * @param {Object} [options]
44
- * @param {string} [options.cwd] - Working directory (default: process.cwd())
45
- * @returns {{ appDefinition: Object, backendDir: string, provider: Object|null, providerName: string } | null}
46
- * null when no app definition is found; provider null for 'aws' (the
47
- * caller keeps its existing behaviour).
48
- */
49
- function loadProviderForCli(options = {}) {
50
- const cwd = options.cwd || process.cwd();
51
- const backend = loadCliBackend(cwd);
52
- if (!backend) {
53
- return null;
54
- }
55
-
56
- const providerName = backend.appDefinition.provider || 'aws';
57
- if (providerName === 'aws') {
58
- return { ...backend, provider: null, providerName: 'aws' };
59
- }
60
-
61
- const {
62
- resolveProvider,
63
- } = require('@friggframework/core/providers/resolve-provider');
64
- return { ...backend, provider: resolveProvider(backend.appDefinition), providerName };
65
- }
66
-
67
- /**
68
- * True when the project's app definition names a non-AWS provider. Used to
69
- * guard the AWS-only commands (doctor, repair, generate-iam).
70
- */
71
- function isNonAwsProject(options = {}) {
72
- try {
73
- const result = loadProviderForCli(options);
74
- return Boolean(result && result.providerName !== 'aws');
75
- } catch {
76
- return false;
77
- }
78
- }
79
-
80
- module.exports = { loadProviderForCli, loadCliAppDefinition, loadCliBackend, isNonAwsProject };
@@ -1,64 +0,0 @@
1
- /**
2
- * `node infrastructure.js package` (what a backend's `npm run build` runs)
3
- * for an app with provider 'netlify': createFriggInfrastructure() builds
4
- * through provider-netlify and returns an empty serverless definition
5
- * instead of composing CloudFormation (friggframework/frigg#545, 302ab9ba).
6
- */
7
- const fs = require('fs');
8
- const os = require('os');
9
- const path = require('path');
10
-
11
- jest.mock('../infrastructure-composer', () => ({
12
- composeServerlessDefinition: jest.fn(async () => ({ service: 'aws-app' })),
13
- }));
14
- jest.mock('@friggframework/core', () => ({
15
- findNearestBackendPackageJson: jest.fn(),
16
- }));
17
-
18
- const { composeServerlessDefinition } = require('../infrastructure-composer');
19
- const { findNearestBackendPackageJson } = require('@friggframework/core');
20
- const { createFriggInfrastructure } = require('../create-frigg-infrastructure');
21
-
22
- function writeProject(definitionSource) {
23
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-infra-'));
24
- const backend = path.join(dir, 'backend');
25
- fs.mkdirSync(backend);
26
- fs.writeFileSync(path.join(backend, 'package.json'), '{"name":"backend"}');
27
- fs.writeFileSync(path.join(backend, 'index.js'), `module.exports = { Definition: ${definitionSource} };`);
28
- findNearestBackendPackageJson.mockReturnValue(path.join(backend, 'package.json'));
29
- return dir;
30
- }
31
-
32
- describe('createFriggInfrastructure with a non-AWS provider', () => {
33
- beforeEach(() => {
34
- jest.clearAllMocks();
35
- jest.spyOn(console, 'log').mockImplementation();
36
- jest.spyOn(console, 'warn').mockImplementation();
37
- });
38
- afterEach(() => jest.restoreAllMocks());
39
-
40
- it('generates the Netlify project and composes no serverless definition', async () => {
41
- const dir = writeProject(`{
42
- provider: 'netlify', integrations: [], database: { postgres: { enable: true } }
43
- }`);
44
- try {
45
- await expect(createFriggInfrastructure()).resolves.toEqual({});
46
- expect(composeServerlessDefinition).not.toHaveBeenCalled();
47
- expect(fs.existsSync(path.join(dir, 'netlify.toml'))).toBe(true);
48
- expect(fs.existsSync(path.join(dir, 'netlify/functions/auth.js'))).toBe(true);
49
- expect(fs.existsSync(path.join(dir, 'netlify/lib/create-netlify-app-handler.js'))).toBe(true);
50
- } finally {
51
- fs.rmSync(dir, { recursive: true, force: true });
52
- }
53
- });
54
-
55
- it('keeps composing the serverless definition for AWS', async () => {
56
- const dir = writeProject(`{ provider: 'aws', integrations: [] }`);
57
- try {
58
- await expect(createFriggInfrastructure()).resolves.toEqual({ service: 'aws-app' });
59
- expect(fs.existsSync(path.join(dir, 'netlify.toml'))).toBe(false);
60
- } finally {
61
- fs.rmSync(dir, { recursive: true, force: true });
62
- }
63
- });
64
- });