@friggframework/devtools 2.0.0--canary.703.12b980b.0 → 2.0.0--canary.707.2702ff3.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.
- package/frigg-cli/__tests__/unit/commands/provider-dispatch.test.js +140 -0
- package/frigg-cli/build-command/index.js +32 -1
- package/frigg-cli/db-setup-command/index.js +25 -0
- package/frigg-cli/deploy-command/index.js +50 -5
- package/frigg-cli/doctor-command/index.js +7 -0
- package/frigg-cli/generate-iam-command.js +7 -0
- package/frigg-cli/index.js +0 -2
- package/frigg-cli/repair-command/index.js +7 -0
- package/frigg-cli/start-command/index.js +58 -0
- package/frigg-cli/utils/provider-helper.js +80 -0
- package/infrastructure/README.md +4 -2
- package/infrastructure/__tests__/compose-extension-prisma.test.js +168 -0
- package/infrastructure/__tests__/create-frigg-infrastructure-provider.test.js +64 -0
- package/infrastructure/__tests__/management-api-gateway-routes.test.js +335 -0
- package/infrastructure/__tests__/template-generation.test.js +7 -0
- package/infrastructure/compose-extension-prisma.js +73 -0
- package/infrastructure/create-frigg-infrastructure.js +14 -0
- package/infrastructure/domains/admin-scripts/admin-script-builder.js +2 -6
- package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +0 -30
- package/infrastructure/domains/integration/integration-builder.js +0 -19
- package/infrastructure/domains/integration/integration-builder.test.js +0 -22
- package/infrastructure/domains/parameters/offload-utils.js +1 -0
- package/infrastructure/domains/shared/environment-builder.js +12 -1
- package/infrastructure/domains/shared/environment-builder.test.js +20 -0
- package/infrastructure/domains/shared/function-environments.js +1 -9
- package/infrastructure/domains/shared/function-environments.test.js +0 -14
- package/infrastructure/domains/shared/types/app-definition.js +15 -1
- package/infrastructure/domains/shared/utilities/base-definition-factory.js +28 -10
- package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +85 -1
- package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +10 -0
- package/infrastructure/infrastructure-composer.js +13 -3
- package/infrastructure/infrastructure-composer.test.js +7 -0
- package/infrastructure/provider-build.js +126 -0
- package/infrastructure/scripts/build-prisma-layer.js +32 -5
- package/infrastructure/scripts/build-prisma-layer.test.js +35 -0
- package/package.json +7 -7
- package/test/npm-install-guard.js +104 -0
- package/test/npm-install-guard.test.js +53 -0
- package/frigg-cli/__tests__/unit/commands/deploy-subscriptions-step.test.js +0 -35
- package/frigg-cli/deploy-command/subscriptions-step.js +0 -44
- package/infrastructure/domains/integration/define-integration-provisioning.test.js +0 -59
- package/infrastructure/domains/scheduler/trigger-builder.js +0 -114
- package/infrastructure/domains/scheduler/trigger-builder.test.js +0 -82
|
@@ -249,6 +249,36 @@ 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
|
+
|
|
252
282
|
/**
|
|
253
283
|
* Install Prisma client directly into layer (RUNTIME ONLY - NO CLI)
|
|
254
284
|
*
|
|
@@ -285,11 +315,7 @@ async function installPrismaPackages() {
|
|
|
285
315
|
PRISMA_CLI_BINARY_TARGETS: 'rhel-openssl-3.0.x',
|
|
286
316
|
};
|
|
287
317
|
|
|
288
|
-
|
|
289
|
-
cwd: path.join(LAYER_OUTPUT_PATH, 'nodejs'),
|
|
290
|
-
stdio: 'inherit',
|
|
291
|
-
env,
|
|
292
|
-
});
|
|
318
|
+
runLayerInstall(path.join(LAYER_OUTPUT_PATH, 'nodejs'), { env });
|
|
293
319
|
logSuccess('Prisma packages installed with Lambda binary target');
|
|
294
320
|
} catch (error) {
|
|
295
321
|
throw new Error(`Failed to install Prisma packages: ${error.message}`);
|
|
@@ -693,6 +719,7 @@ if (require.main === module) {
|
|
|
693
719
|
|
|
694
720
|
module.exports = {
|
|
695
721
|
buildPrismaLayer,
|
|
722
|
+
runLayerInstall,
|
|
696
723
|
getGeneratedClientPackages,
|
|
697
724
|
getMigrationsPackages,
|
|
698
725
|
getMigrationSourcePath,
|
|
@@ -168,3 +168,38 @@ describe('getMigrationDestinationPath()', () => {
|
|
|
168
168
|
);
|
|
169
169
|
});
|
|
170
170
|
});
|
|
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
|
+
});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@friggframework/devtools",
|
|
3
3
|
"prettier": "@friggframework/prettier-config",
|
|
4
|
-
"version": "2.0.0--canary.
|
|
4
|
+
"version": "2.0.0--canary.707.2702ff3.0",
|
|
5
5
|
"bin": {
|
|
6
6
|
"frigg": "./frigg-cli/index.js"
|
|
7
7
|
},
|
|
@@ -26,9 +26,9 @@
|
|
|
26
26
|
"@babel/eslint-parser": "^7.18.9",
|
|
27
27
|
"@babel/parser": "^7.25.3",
|
|
28
28
|
"@babel/traverse": "^7.25.3",
|
|
29
|
-
"@friggframework/core": "2.0.0--canary.
|
|
30
|
-
"@friggframework/schemas": "2.0.0--canary.
|
|
31
|
-
"@friggframework/test": "2.0.0--canary.
|
|
29
|
+
"@friggframework/core": "2.0.0--canary.707.2702ff3.0",
|
|
30
|
+
"@friggframework/schemas": "2.0.0--canary.707.2702ff3.0",
|
|
31
|
+
"@friggframework/test": "2.0.0--canary.707.2702ff3.0",
|
|
32
32
|
"@hapi/boom": "^10.0.1",
|
|
33
33
|
"@inquirer/prompts": "^5.3.8",
|
|
34
34
|
"axios": "^1.18.0",
|
|
@@ -56,8 +56,8 @@
|
|
|
56
56
|
"validate-npm-package-name": "^5.0.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
|
-
"@friggframework/eslint-config": "2.0.0--canary.
|
|
60
|
-
"@friggframework/prettier-config": "2.0.0--canary.
|
|
59
|
+
"@friggframework/eslint-config": "2.0.0--canary.707.2702ff3.0",
|
|
60
|
+
"@friggframework/prettier-config": "2.0.0--canary.707.2702ff3.0",
|
|
61
61
|
"aws-sdk-client-mock": "^4.1.0",
|
|
62
62
|
"aws-sdk-client-mock-jest": "^4.1.0",
|
|
63
63
|
"jest": "^30.1.3",
|
|
@@ -89,5 +89,5 @@
|
|
|
89
89
|
"publishConfig": {
|
|
90
90
|
"access": "public"
|
|
91
91
|
},
|
|
92
|
-
"gitHead": "
|
|
92
|
+
"gitHead": "2702ff3a8f6d43ba681701e8accc13c064848092"
|
|
93
93
|
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Jest setup: no test may run a package-manager command that rewrites a
|
|
3
|
+
* node_modules tree outside the OS temp directory.
|
|
4
|
+
*
|
|
5
|
+
* Why: two infrastructure tests composed a serverless definition in parallel,
|
|
6
|
+
* each building the real Prisma layer under packages/devtools/layers/prisma.
|
|
7
|
+
* One cleaned the layer while the other's `npm install --omit=dev` was
|
|
8
|
+
* starting, npm found no package.json in its cwd, walked up into the
|
|
9
|
+
* monorepo workspace and pruned the devDependencies (jest, jest-util) out of
|
|
10
|
+
* the repository's root node_modules. Every later workspace then failed with
|
|
11
|
+
* `jest: not found`.
|
|
12
|
+
*
|
|
13
|
+
* The guard wraps the real child_process functions. A test that mocks
|
|
14
|
+
* child_process (jest.mock) gets its mock and is unaffected; anything that
|
|
15
|
+
* reaches the real module with, for example, `npm install` in a repository
|
|
16
|
+
* directory throws instead of running.
|
|
17
|
+
*/
|
|
18
|
+
const childProcess = require('child_process');
|
|
19
|
+
const fs = require('fs');
|
|
20
|
+
const os = require('os');
|
|
21
|
+
const path = require('path');
|
|
22
|
+
|
|
23
|
+
const PACKAGE_MANAGERS = new Set(['npm', 'npx', 'yarn', 'pnpm']);
|
|
24
|
+
const MUTATING = new Set([
|
|
25
|
+
'install', 'i', 'in', 'ci', 'add', 'prune', 'uninstall', 'remove', 'rm', 'r', 'un',
|
|
26
|
+
'update', 'up', 'upgrade', 'dedupe', 'link', 'rebuild',
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
function realpathOrSelf(p) {
|
|
30
|
+
try {
|
|
31
|
+
return fs.realpathSync(p);
|
|
32
|
+
} catch {
|
|
33
|
+
return path.resolve(p);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const TMP = realpathOrSelf(os.tmpdir());
|
|
38
|
+
// The monorepo root (packages/devtools/test -> ../../..). A checkout can
|
|
39
|
+
// itself live under the temp directory, so "under tmp" alone is not enough.
|
|
40
|
+
const REPO_ROOT = realpathOrSelf(path.resolve(__dirname, '..', '..', '..'));
|
|
41
|
+
|
|
42
|
+
const within = (dir, root) => dir === root || dir.startsWith(root + path.sep);
|
|
43
|
+
|
|
44
|
+
/** True only for a scratch directory: under tmp and outside this repository. */
|
|
45
|
+
function insideTmp(dir) {
|
|
46
|
+
const real = realpathOrSelf(dir);
|
|
47
|
+
return within(real, TMP) && !within(real, REPO_ROOT);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** @returns {string|null} the offending command, or null when allowed */
|
|
51
|
+
function offending(tokens, cwd) {
|
|
52
|
+
const [bin, ...args] = tokens;
|
|
53
|
+
if (!bin || !PACKAGE_MANAGERS.has(path.basename(String(bin)))) return null;
|
|
54
|
+
const sub = args.find((a) => !String(a).startsWith('-'));
|
|
55
|
+
// npx <pkg> runs a package; only installs/prunes rewrite node_modules.
|
|
56
|
+
if (path.basename(String(bin)) === 'npx' || !MUTATING.has(sub)) return null;
|
|
57
|
+
const prefixAt = args.indexOf('--prefix');
|
|
58
|
+
const target = prefixAt >= 0 ? args[prefixAt + 1] : cwd;
|
|
59
|
+
if (insideTmp(target || process.cwd())) return null;
|
|
60
|
+
return tokens.join(' ');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const GUARDED = Symbol.for('frigg.devtools.npmInstallGuard');
|
|
64
|
+
|
|
65
|
+
function guard(name, fn, toTokens) {
|
|
66
|
+
// setupFiles runs once per test file in a shared worker: wrap once.
|
|
67
|
+
if (fn[GUARDED]) return fn;
|
|
68
|
+
const guarded = function guarded(...callArgs) {
|
|
69
|
+
const { tokens, cwd } = toTokens(callArgs);
|
|
70
|
+
const bad = offending(tokens, cwd);
|
|
71
|
+
if (bad) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
`Test tried to run "${bad}" outside the temp directory (cwd ${cwd || process.cwd()}); ` +
|
|
74
|
+
'it would rewrite a real node_modules. Mock it or run it in a temp dir.'
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
return fn.apply(this, callArgs);
|
|
78
|
+
};
|
|
79
|
+
guarded[GUARDED] = true;
|
|
80
|
+
return guarded;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const fromString = ([command, options]) => ({
|
|
84
|
+
tokens: String(command).trim().split(/\s+/),
|
|
85
|
+
cwd: options?.cwd,
|
|
86
|
+
});
|
|
87
|
+
const fromFile = ([file, args, options]) =>
|
|
88
|
+
Array.isArray(args)
|
|
89
|
+
? { tokens: [file, ...args], cwd: options?.cwd }
|
|
90
|
+
: { tokens: [file], cwd: args?.cwd };
|
|
91
|
+
|
|
92
|
+
for (const name of ['execSync', 'exec']) {
|
|
93
|
+
childProcess[name] = guard(name, childProcess[name], fromString);
|
|
94
|
+
}
|
|
95
|
+
for (const name of ['execFileSync', 'execFile', 'spawn', 'spawnSync']) {
|
|
96
|
+
const original = childProcess[name];
|
|
97
|
+
childProcess[name] = guard(name, original, (callArgs) => {
|
|
98
|
+
const opts = Array.isArray(callArgs[1]) ? callArgs[2] : callArgs[1];
|
|
99
|
+
if (opts?.shell && !Array.isArray(callArgs[1])) return fromString([callArgs[0], opts]);
|
|
100
|
+
return fromFile(callArgs);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
module.exports = { offending, insideTmp };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
const os = require('os');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const childProcess = require('child_process');
|
|
4
|
+
// Read before this file loads the guard itself: jest's setupFiles must have
|
|
5
|
+
// installed it already, for every test file.
|
|
6
|
+
const guardedBySetup = Boolean(childProcess.execSync[Symbol.for('frigg.devtools.npmInstallGuard')]);
|
|
7
|
+
const { offending } = require('./npm-install-guard');
|
|
8
|
+
|
|
9
|
+
const repoDir = path.resolve(__dirname, '..');
|
|
10
|
+
|
|
11
|
+
describe('npm install guard (jest setupFiles)', () => {
|
|
12
|
+
// Every command here is a --dry-run, so even a broken guard that let it
|
|
13
|
+
// through could not rewrite this repository's node_modules.
|
|
14
|
+
it('is installed by jest setupFiles, before any test code runs', () => {
|
|
15
|
+
expect(guardedBySetup).toBe(true);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('blocks installs and prunes on the real child_process', () => {
|
|
19
|
+
expect(() =>
|
|
20
|
+
childProcess.execSync('npm install --dry-run --omit=dev', { cwd: repoDir, stdio: 'ignore' })
|
|
21
|
+
).toThrow(/outside the temp directory/);
|
|
22
|
+
expect(() =>
|
|
23
|
+
childProcess.spawnSync('npm', ['prune', '--dry-run'], { cwd: repoDir, stdio: 'ignore' })
|
|
24
|
+
).toThrow(/outside the temp directory/);
|
|
25
|
+
expect(() =>
|
|
26
|
+
childProcess.execFileSync('/usr/bin/npm', ['ci', '--dry-run'], { cwd: repoDir, stdio: 'ignore' })
|
|
27
|
+
).toThrow(/outside the temp directory/);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('treats a temp dir inside this repository as part of the repository', () => {
|
|
31
|
+
// A checkout may itself live under os.tmpdir() (as in some sandboxes).
|
|
32
|
+
expect(offending(['npm', 'install'], path.join(repoDir, 'layers/prisma/nodejs'))).not.toBeNull();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it.each([
|
|
36
|
+
[['npm', 'install', '--omit=dev'], repoDir, true],
|
|
37
|
+
[['npm', 'ci'], repoDir, true],
|
|
38
|
+
[['yarn', 'add', 'x'], repoDir, true],
|
|
39
|
+
[['npm', 'install', '--prefix', repoDir], os.tmpdir(), true],
|
|
40
|
+
[['npm', 'install'], os.tmpdir(), false],
|
|
41
|
+
[['npm', 'install', '--prefix', path.join(os.tmpdir(), 'layer')], repoDir, false],
|
|
42
|
+
[['npm', 'root'], repoDir, false],
|
|
43
|
+
[['npm', 'run', 'build'], repoDir, false],
|
|
44
|
+
[['npx', 'netlify-cli', 'deploy'], repoDir, false],
|
|
45
|
+
[['git', 'install'], repoDir, false],
|
|
46
|
+
])('%j in %s -> blocked %s', (tokens, cwd, blocked) => {
|
|
47
|
+
expect(offending(tokens, cwd) !== null).toBe(blocked);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('lets harmless commands through', () => {
|
|
51
|
+
expect(childProcess.execSync('node -e "process.stdout.write(\'ok\')"', { encoding: 'utf8' })).toBe('ok');
|
|
52
|
+
});
|
|
53
|
+
});
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The post-deploy webhook subscription step: add-only by default, prune on request, never fails the deploy.
|
|
3
|
-
*/
|
|
4
|
-
const { reconcileSubscriptionsAfterDeploy } = require('../../../deploy-command/subscriptions-step');
|
|
5
|
-
|
|
6
|
-
describe('reconcileSubscriptionsAfterDeploy', () => {
|
|
7
|
-
let log;
|
|
8
|
-
beforeEach(() => { log = jest.spyOn(console, 'log').mockImplementation(() => {}); });
|
|
9
|
-
afterEach(() => log.mockRestore());
|
|
10
|
-
|
|
11
|
-
const result = { extension: 'hubspot-webhooks', created: ['deal.creation'], removed: [], kept: [], remove: ['company.deletion'] };
|
|
12
|
-
const define = (impl) => ({ reconcileAppSubscriptions: jest.fn(impl || (async () => [result])) });
|
|
13
|
-
|
|
14
|
-
it('runs add-only without a database by default', async () => {
|
|
15
|
-
const d = define();
|
|
16
|
-
const integrations = [function A() {}];
|
|
17
|
-
await reconcileSubscriptionsAfterDeploy({ integrations }, {}, { define: d });
|
|
18
|
-
expect(d.reconcileAppSubscriptions).toHaveBeenCalledWith({ integrations, listInstallations: null, prune: false });
|
|
19
|
-
expect(log.mock.calls.flat().join('\n')).toMatch(/1 not needed by any binding \(kept; --prune-subscriptions removes them\)/);
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
it('prunes with --prune-subscriptions', async () => {
|
|
23
|
-
const d = define();
|
|
24
|
-
await reconcileSubscriptionsAfterDeploy({ integrations: [] }, { pruneSubscriptions: true }, { define: d });
|
|
25
|
-
expect(d.reconcileAppSubscriptions.mock.calls[0][0].prune).toBe(true);
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
it('is skipped with --skip-subscriptions, and a failure never fails the deploy', async () => {
|
|
29
|
-
const d = define();
|
|
30
|
-
expect(await reconcileSubscriptionsAfterDeploy({}, { skipSubscriptions: true }, { define: d })).toBeNull();
|
|
31
|
-
expect(d.reconcileAppSubscriptions).not.toHaveBeenCalled();
|
|
32
|
-
const failing = define(async () => { throw new Error('provider down'); });
|
|
33
|
-
await expect(reconcileSubscriptionsAfterDeploy({ integrations: [] }, {}, { define: failing })).resolves.toBeNull();
|
|
34
|
-
});
|
|
35
|
-
});
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Post-deploy step (ADR-054 §2, amended): create the app-scope webhook subscriptions the deployed integrations
|
|
3
|
-
* declare (for example HubSpot's, which belong to the developer app).
|
|
4
|
-
*
|
|
5
|
-
* Add-only unless `--prune-subscriptions`. The deploy machine has no database, so bindings whose options depend on
|
|
6
|
-
* installation config are left to the installation lifecycle and to the admin script, and a group that has one is
|
|
7
|
-
* never pruned here. Supported setup: one provider developer app per stage, because the subscriptions are app-wide.
|
|
8
|
-
* A failure is reported and never fails the deploy; the admin script can be run afterwards.
|
|
9
|
-
*/
|
|
10
|
-
async function reconcileSubscriptionsAfterDeploy(appDefinition, options = {}, { define } = {}) {
|
|
11
|
-
if (options.skipSubscriptions) {
|
|
12
|
-
console.log('\n⏭️ Skipping webhook subscription reconcile (--skip-subscriptions)');
|
|
13
|
-
return null;
|
|
14
|
-
}
|
|
15
|
-
const integrations = appDefinition?.integrations || [];
|
|
16
|
-
let api = define;
|
|
17
|
-
if (!api) {
|
|
18
|
-
try {
|
|
19
|
-
api = require('@friggframework/core/integrations/define');
|
|
20
|
-
} catch {
|
|
21
|
-
return null; // a core without defineIntegration: nothing declares app-scope subscriptions
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
const prune = Boolean(options.pruneSubscriptions);
|
|
25
|
-
try {
|
|
26
|
-
// The provider credentials (developer app id and key) come from the deploy environment or .env.
|
|
27
|
-
try { require('dotenv').config(); } catch { /* dotenv is optional here */ }
|
|
28
|
-
const results = await api.reconcileAppSubscriptions({ integrations, listInstallations: null, prune });
|
|
29
|
-
if (!results.length) return results;
|
|
30
|
-
console.log(`\nWebhook subscriptions (${prune ? 'prune' : 'add-only'}):`);
|
|
31
|
-
for (const r of results) {
|
|
32
|
-
console.log(` ${r.extension}: ${r.created.length} created, ${r.removed.length} removed, ${r.kept.length} kept`);
|
|
33
|
-
if (!prune && r.remove.length) console.log(` ${r.remove.length} not needed by any binding (kept; --prune-subscriptions removes them): ${r.remove.join(', ')}`);
|
|
34
|
-
if (r.pruneSkipped) console.log(` not pruned: ${r.pruneSkipped}`);
|
|
35
|
-
}
|
|
36
|
-
return results;
|
|
37
|
-
} catch (error) {
|
|
38
|
-
console.log(`\n⚠️ Webhook subscription reconcile failed: ${error.message}`);
|
|
39
|
-
console.log(' The deploy succeeded. Run the reconcile-subscriptions admin script to retry.');
|
|
40
|
-
return null;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
module.exports = { reconcileSubscriptionsAfterDeploy };
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A defineIntegration app (ADR-054) provisions through the existing builders with no new path: the contract-2
|
|
3
|
-
* binding gets its own function under the derived key, and `triggers` get the ADR-055 tick.
|
|
4
|
-
*/
|
|
5
|
-
jest.mock('@friggframework/core/database/config', () => ({ DB_TYPE: 'mongodb', getDatabaseType: jest.fn(() => 'mongodb'), PRISMA_LOG_LEVEL: 'error,warn' }));
|
|
6
|
-
|
|
7
|
-
const { defineApp, defineIntegration, use } = require('@friggframework/core/integrations/define');
|
|
8
|
-
const { IntegrationBuilder } = require('./integration-builder');
|
|
9
|
-
const { TriggerBuilder } = require('../scheduler/trigger-builder');
|
|
10
|
-
|
|
11
|
-
/** A module with a contract-2 webhooks extension, reduced to what provisioning reads. */
|
|
12
|
-
const crmModule = {
|
|
13
|
-
Definition: { moduleName: 'crm-vendor', getName: () => 'crm-vendor' },
|
|
14
|
-
extensions: {
|
|
15
|
-
webhooks: {
|
|
16
|
-
name: 'crm-vendor-webhooks',
|
|
17
|
-
contract: 2,
|
|
18
|
-
useDatabase: false,
|
|
19
|
-
routes: [{ path: '/webhooks', method: 'POST' }],
|
|
20
|
-
receive: (input) => [{ externalId: input.body.account, body: input.body }],
|
|
21
|
-
resolve: { module: 'crm-vendor' },
|
|
22
|
-
emits: { 'deal.changed': {} },
|
|
23
|
-
},
|
|
24
|
-
},
|
|
25
|
-
};
|
|
26
|
-
const chatModule = { Definition: { moduleName: 'chat-vendor', getName: () => 'chat-vendor' } };
|
|
27
|
-
|
|
28
|
-
const app = defineApp({
|
|
29
|
-
name: 'deal-alerts',
|
|
30
|
-
integrations: [
|
|
31
|
-
defineIntegration({
|
|
32
|
-
name: 'deal-alerts',
|
|
33
|
-
modules: { crm: use(crmModule, { webhooks: {} }), chat: use(chatModule) },
|
|
34
|
-
on: { 'crm.deal.changed': async () => {} },
|
|
35
|
-
triggers: { digest: { every: '1h', handler: async () => {} } },
|
|
36
|
-
}),
|
|
37
|
-
],
|
|
38
|
-
}, { schemas: null });
|
|
39
|
-
|
|
40
|
-
describe('a defineIntegration app on the existing builders', () => {
|
|
41
|
-
beforeEach(() => { jest.spyOn(console, 'log').mockImplementation(() => {}); });
|
|
42
|
-
afterEach(() => { jest.restoreAllMocks(); });
|
|
43
|
-
|
|
44
|
-
it('gives the contract-2 binding its own function, routed under the module key', async () => {
|
|
45
|
-
const result = await new IntegrationBuilder().build(app.Definition, {});
|
|
46
|
-
const fn = result.functions['deal-alerts__crmwebhooks'];
|
|
47
|
-
expect(fn.handler).toBe('node_modules/@friggframework/core/handlers/routers/integration-defined-routers.handlers.deal-alerts__crmwebhooks.handler');
|
|
48
|
-
expect(fn.events).toEqual([{ httpApi: { path: '/api/deal-alerts-integration/crm-webhooks/webhooks', method: 'POST' } }]);
|
|
49
|
-
expect(fn.layers).toBeUndefined(); // useDatabase: false, so no Prisma layer
|
|
50
|
-
expect(result.functions['deal-alertsQueueWorker']).toBeDefined();
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
it('provisions the ADR-055 tick for its triggers', async () => {
|
|
54
|
-
const builder = new TriggerBuilder();
|
|
55
|
-
expect(builder.shouldExecute(app.Definition)).toBe(true);
|
|
56
|
-
const result = await builder.build(app.Definition, {});
|
|
57
|
-
expect(JSON.stringify(result)).toContain('rate(1 hour)');
|
|
58
|
-
});
|
|
59
|
-
});
|
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Trigger Builder (ADR-055 §2)
|
|
3
|
-
*
|
|
4
|
-
* Domain Layer - Hexagonal Architecture
|
|
5
|
-
*
|
|
6
|
-
* One function per integration that declares recurring triggers: `{integration}Triggers`, with the Prisma layer.
|
|
7
|
-
* It gets one serverless `schedule` event per distinct tick of the integration's `every` / `cron` triggers (and of
|
|
8
|
-
* the triggers it resolves per installation, `Definition.instanceTriggers`), plus one EventBridge Scheduler event per
|
|
9
|
-
* `at` trigger, with its time zone. Each tick pages through the ENABLED installations and queues the runs that are
|
|
10
|
-
* due (core: integrations/use-cases/run-trigger-tick.js). Nothing is created per installation, and these resources
|
|
11
|
-
* change only when a Definition does, so they live in CloudFormation and leave with the stack.
|
|
12
|
-
*
|
|
13
|
-
* IAM, and why this builder adds none:
|
|
14
|
-
* - A `rate()` tick is an EventBridge rule; the framework adds the Lambda permission for it.
|
|
15
|
-
* - An `at` trigger uses `method: scheduler`; the framework adds `scheduler.amazonaws.com` to the function role's
|
|
16
|
-
* trust policy and `lambda:InvokeFunction` on this function to it.
|
|
17
|
-
* - The tick reads the integration table (the Prisma layer and the provider's database access, like the queue
|
|
18
|
-
* worker) and sends to its own `<Name>Queue`, which the provider-level `sqs:SendMessage(Batch)` statement on
|
|
19
|
-
* `${service}--${stage}-*Queue` already allows. It never calls EventBridge Scheduler at runtime, so it needs none
|
|
20
|
-
* of SchedulerBuilder's scheduler:* permissions (those stay for one-time jobs).
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
|
|
24
|
-
const { IntegrationBuilder } = require('../integration/integration-builder');
|
|
25
|
-
const {
|
|
26
|
-
hasTriggers,
|
|
27
|
-
provisioningOf,
|
|
28
|
-
durationOf,
|
|
29
|
-
} = require('@friggframework/core/integrations/triggers');
|
|
30
|
-
|
|
31
|
-
/** EventBridge rate() for a tick in minutes: rate(1 minute), rate(5 minutes), rate(1 hour), rate(2 hours), rate(1 day). */
|
|
32
|
-
function rateExpression(minutes) {
|
|
33
|
-
const [count, unit] =
|
|
34
|
-
minutes % 1440 === 0 ? [minutes / 1440, 'day'] : minutes % 60 === 0 ? [minutes / 60, 'hour'] : [minutes, 'minute'];
|
|
35
|
-
return `rate(${count} ${unit}${count === 1 ? '' : 's'})`;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** The function name the trigger tick for an integration runs as. Wire contract with function-environments.js. */
|
|
39
|
-
function triggerFunctionName(integrationName) {
|
|
40
|
-
return `${integrationName}Triggers`;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
class TriggerBuilder extends InfrastructureBuilder {
|
|
44
|
-
constructor() {
|
|
45
|
-
super();
|
|
46
|
-
this.name = 'TriggerBuilder';
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
shouldExecute(appDefinition) {
|
|
50
|
-
return Array.isArray(appDefinition.integrations) && appDefinition.integrations.some((i) => hasTriggers(i));
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
getDependencies() {
|
|
54
|
-
return ['IntegrationBuilder']; // the tick sends to the integration queue
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
validate(appDefinition) {
|
|
58
|
-
const result = new ValidationResult();
|
|
59
|
-
for (const integration of appDefinition.integrations || []) {
|
|
60
|
-
if (!hasTriggers(integration)) continue;
|
|
61
|
-
try {
|
|
62
|
-
provisioningOf(integration);
|
|
63
|
-
} catch (error) {
|
|
64
|
-
result.addError(error.message);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
return result;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
async build(appDefinition) {
|
|
71
|
-
console.log(`\n[${this.name}] Configuring recurring triggers...`);
|
|
72
|
-
const result = { functions: {}, resources: {}, environment: {}, custom: {}, iamStatements: [] };
|
|
73
|
-
const usePrismaLayer = appDefinition.usePrismaLambdaLayer !== false;
|
|
74
|
-
const functionPackageConfig = new IntegrationBuilder().createFunctionPackageConfig(usePrismaLayer, appDefinition);
|
|
75
|
-
|
|
76
|
-
for (const integration of appDefinition.integrations || []) {
|
|
77
|
-
if (!hasTriggers(integration)) continue;
|
|
78
|
-
const name = integration.Definition.name;
|
|
79
|
-
const { ticks, at } = provisioningOf(integration);
|
|
80
|
-
const events = [
|
|
81
|
-
...ticks.map((minutes) => ({
|
|
82
|
-
schedule: {
|
|
83
|
-
rate: [rateExpression(minutes)],
|
|
84
|
-
// The rule's own firing time goes in, so a repeated delivery falls in the same tick slot.
|
|
85
|
-
inputTransformer: {
|
|
86
|
-
inputPathsMap: { time: '$.time' },
|
|
87
|
-
inputTemplate: `{"tick":"${durationOf(minutes)}","time":<time>}`,
|
|
88
|
-
},
|
|
89
|
-
},
|
|
90
|
-
})),
|
|
91
|
-
...at.map((t) => ({
|
|
92
|
-
schedule: {
|
|
93
|
-
method: 'scheduler',
|
|
94
|
-
rate: [t.at],
|
|
95
|
-
...(t.timezone ? { timezone: t.timezone } : {}),
|
|
96
|
-
input: { at: t.name, time: '<aws.scheduler.scheduled-time>' },
|
|
97
|
-
},
|
|
98
|
-
})),
|
|
99
|
-
];
|
|
100
|
-
result.functions[triggerFunctionName(name)] = {
|
|
101
|
-
handler: `node_modules/@friggframework/core/handlers/workers/integration-triggers.handlers.${name}.tick`,
|
|
102
|
-
skipEsbuild: true, // Nested exports in node_modules - skip esbuild bundling
|
|
103
|
-
package: functionPackageConfig,
|
|
104
|
-
...(usePrismaLayer && { layers: [{ Ref: 'PrismaLambdaLayer' }] }), // reads the integration table
|
|
105
|
-
timeout: 300, // a tick past its deadline hands its page cursor to the queue
|
|
106
|
-
events,
|
|
107
|
-
};
|
|
108
|
-
console.log(` ✓ ${triggerFunctionName(name)}: ticks ${ticks.map(durationOf).join(', ') || 'none'}; at ${at.map((t) => t.name).join(', ') || 'none'}`);
|
|
109
|
-
}
|
|
110
|
-
return result;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
module.exports = { TriggerBuilder, rateExpression, triggerFunctionName };
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* TriggerBuilder (ADR-055 §2): one tick function per integration with triggers, one schedule per distinct tick and
|
|
3
|
-
* one per `at` trigger, never anything per installation.
|
|
4
|
-
*/
|
|
5
|
-
const { TriggerBuilder, rateExpression } = require('./trigger-builder');
|
|
6
|
-
const { applyFunctionEnvironments } = require('../shared/function-environments');
|
|
7
|
-
|
|
8
|
-
const poll = { every: '15m', handler: 'poll' };
|
|
9
|
-
|
|
10
|
-
describe('TriggerBuilder', () => {
|
|
11
|
-
beforeEach(() => { jest.spyOn(console, 'log').mockImplementation(() => {}); });
|
|
12
|
-
afterEach(() => { jest.restoreAllMocks(); });
|
|
13
|
-
|
|
14
|
-
it('runs when, and only when, an integration declares triggers (code or per installation)', () => {
|
|
15
|
-
const b = new TriggerBuilder();
|
|
16
|
-
expect(b.shouldExecute({ integrations: [{ Definition: { name: 'a', triggers: { poll } } }] })).toBe(true);
|
|
17
|
-
expect(b.shouldExecute({ integrations: [{ Definition: { name: 'dd', instanceTriggers: { tick: '5m' } } }] })).toBe(true);
|
|
18
|
-
expect(b.shouldExecute({ integrations: [{ Definition: { name: 'a', webhooks: true } }] })).toBe(false);
|
|
19
|
-
expect(b.shouldExecute({ integrations: [{ Definition: { name: 'a', triggers: {} } }] })).toBe(false);
|
|
20
|
-
expect(b.shouldExecute({})).toBe(false);
|
|
21
|
-
expect(b.getDependencies()).toEqual(['IntegrationBuilder']);
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
it('writes rate() in the largest whole unit EventBridge accepts', () => {
|
|
25
|
-
expect([1, 5, 60, 90, 120, 1440].map(rateExpression)).toEqual(['rate(1 minute)', 'rate(5 minutes)', 'rate(1 hour)', 'rate(90 minutes)', 'rate(2 hours)', 'rate(1 day)']);
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
it('emits one function per integration: a schedule per distinct tick and one per at trigger, with its zone', async () => {
|
|
29
|
-
const appDefinition = {
|
|
30
|
-
integrations: [
|
|
31
|
-
{ Definition: { name: 'crm', triggers: {
|
|
32
|
-
poll,
|
|
33
|
-
sync: { every: '1h', configurable: { min: '15m' }, handler: 'sync' }, // 15m tick: same schedule as poll
|
|
34
|
-
digest: { cron: '0 8 * * 1-5', timezone: 'America/New_York', handler: 'digest' }, // 5m
|
|
35
|
-
nightly: { at: 'cron(0 3 * * ? *)', timezone: 'Europe/London', handler: 'nightly' },
|
|
36
|
-
} } },
|
|
37
|
-
{ Definition: { name: 'plain' } },
|
|
38
|
-
],
|
|
39
|
-
};
|
|
40
|
-
const result = await new TriggerBuilder().build(appDefinition, {});
|
|
41
|
-
expect(Object.keys(result.functions)).toEqual(['crmTriggers']);
|
|
42
|
-
const fn = result.functions.crmTriggers;
|
|
43
|
-
expect(fn).toMatchObject({
|
|
44
|
-
handler: 'node_modules/@friggframework/core/handlers/workers/integration-triggers.handlers.crm.tick',
|
|
45
|
-
skipEsbuild: true,
|
|
46
|
-
layers: [{ Ref: 'PrismaLambdaLayer' }],
|
|
47
|
-
timeout: 300,
|
|
48
|
-
});
|
|
49
|
-
expect(fn.events).toEqual([
|
|
50
|
-
{ schedule: { rate: ['rate(5 minutes)'], inputTransformer: { inputPathsMap: { time: '$.time' }, inputTemplate: '{"tick":"5m","time":<time>}' } } },
|
|
51
|
-
{ schedule: { rate: ['rate(15 minutes)'], inputTransformer: { inputPathsMap: { time: '$.time' }, inputTemplate: '{"tick":"15m","time":<time>}' } } },
|
|
52
|
-
{ schedule: { method: 'scheduler', rate: ['cron(0 3 * * ? *)'], timezone: 'Europe/London', input: { at: 'nightly', time: '<aws.scheduler.scheduled-time>' } } },
|
|
53
|
-
]);
|
|
54
|
-
// The tick never calls EventBridge Scheduler at runtime: no scheduler IAM, no resources.
|
|
55
|
-
expect(result.iamStatements).toEqual([]);
|
|
56
|
-
expect(result.resources).toEqual({});
|
|
57
|
-
// The inputTemplate is valid JSON once EventBridge fills <time>.
|
|
58
|
-
expect(JSON.parse(fn.events[0].schedule.inputTransformer.inputTemplate.replace('<time>', '"2026-10-19T12:00:00Z"'))).toEqual({ tick: '5m', time: '2026-10-19T12:00:00Z' });
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
it('leaves the Prisma layer off when the app bundles Prisma', async () => {
|
|
62
|
-
const result = await new TriggerBuilder().build({ usePrismaLambdaLayer: false, integrations: [{ Definition: { name: 'crm', triggers: { poll } } }] }, {});
|
|
63
|
-
expect(result.functions.crmTriggers.layers).toBeUndefined();
|
|
64
|
-
});
|
|
65
|
-
|
|
66
|
-
it('fails validation, naming the integration, when a trigger cannot be provisioned', () => {
|
|
67
|
-
const v = new TriggerBuilder().validate({ integrations: [{ Definition: { name: 'crm', triggers: { bad: { every: 'often', handler: 'x' } } } }] });
|
|
68
|
-
expect(v.valid).toBe(false);
|
|
69
|
-
expect(v.errors[0]).toMatch(/Integration "crm" declares invalid triggers: bad: every "often"/);
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
it('scoped env: the queue URL reaches the tick function, through the shared function-name contract', async () => {
|
|
73
|
-
const { IntegrationBuilder } = require('../integration/integration-builder');
|
|
74
|
-
const integration = { Definition: { name: 'crm', triggers: { poll } } };
|
|
75
|
-
const ib = new IntegrationBuilder();
|
|
76
|
-
const result = { functionEnvironments: {}, environment: {} };
|
|
77
|
-
ib.setQueueUrlEnvironment('crm', { Ref: 'CrmQueue' }, result, { lambda: { scopedEnvironment: true }, integrations: [integration] });
|
|
78
|
-
const functions = { auth: {}, crm: {}, crmQueueWorker: {}, ...(await new TriggerBuilder().build({ integrations: [integration] }, {})).functions };
|
|
79
|
-
applyFunctionEnvironments(functions, result.functionEnvironments);
|
|
80
|
-
expect(functions.crmTriggers.environment).toEqual({ CRM_QUEUE_URL: { Ref: 'CrmQueue' } });
|
|
81
|
-
});
|
|
82
|
-
});
|