@friggframework/devtools 2.0.0--canary.693.d8859c2.0 → 2.0.0--canary.694.f66a64a.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.
@@ -0,0 +1,114 @@
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 };
@@ -0,0 +1,82 @@
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
+ });
@@ -1,3 +1,5 @@
1
+ const { hasTriggers } = require('@friggframework/core/integrations/triggers');
2
+
1
3
  /**
2
4
  * Per-function environment scoping (ADR-027)
3
5
  *
@@ -47,7 +49,8 @@ function applyFunctionEnvironments(functions, functionEnvironments = {}) {
47
49
  /**
48
50
  * Function names the integration builder creates for one integration.
49
51
  * Wire contract: must stay in sync with
50
- * IntegrationBuilder.createFunctionDefinitions — a drift here surfaces as a
52
+ * IntegrationBuilder.createFunctionDefinitions (and TriggerBuilder for
53
+ * `${name}Triggers`) — a drift here surfaces as a
51
54
  * hard unknown-function error at compose time, not a silent var drop.
52
55
  *
53
56
  * @param {Object} integration - entry from appDefinition.integrations
@@ -62,6 +65,11 @@ function getIntegrationFunctionNames(integration) {
62
65
  names.splice(1, 0, `${name}Webhook`);
63
66
  }
64
67
 
68
+ // TriggerBuilder (ADR-055): the tick function, which sends trigger runs to this integration's queue.
69
+ if (hasTriggers(integration)) {
70
+ names.push(`${name}Triggers`);
71
+ }
72
+
65
73
  for (const [bindingKey, binding] of Object.entries(
66
74
  integration.Definition.extensions || {}
67
75
  )) {
@@ -67,6 +67,20 @@ describe('function-environments', () => {
67
67
  ).not.toContain('hubspotWebhook');
68
68
  });
69
69
 
70
+ it('includes the trigger tick function when the integration declares triggers (ADR-055)', () => {
71
+ expect(
72
+ getIntegrationFunctionNames({
73
+ Definition: { name: 'hubspot', triggers: { poll: { every: '15m', handler: 'poll' } } },
74
+ })
75
+ ).toEqual(['hubspot', 'hubspotQueueWorker', 'hubspotTriggers']);
76
+ expect(
77
+ getIntegrationFunctionNames({ Definition: { name: 'dd', instanceTriggers: { tick: '5m' } } })
78
+ ).toContain('ddTriggers');
79
+ expect(
80
+ getIntegrationFunctionNames({ Definition: { name: 'hubspot', triggers: {} } })
81
+ ).not.toContain('hubspotTriggers');
82
+ });
83
+
70
84
  it('includes one function per routed extension binding, sanitized', () => {
71
85
  const names = getIntegrationFunctionNames({
72
86
  Definition: {
@@ -17,6 +17,7 @@ const { SsmBuilder } = require('./domains/parameters/ssm-builder');
17
17
  const { WebsocketBuilder } = require('./domains/integration/websocket-builder');
18
18
  const { IntegrationBuilder } = require('./domains/integration/integration-builder');
19
19
  const { SchedulerBuilder } = require('./domains/scheduler/scheduler-builder');
20
+ const { TriggerBuilder } = require('./domains/scheduler/trigger-builder');
20
21
  const { AdminScriptBuilder } = require('./domains/admin-scripts/admin-script-builder');
21
22
 
22
23
  // Utilities
@@ -92,6 +93,7 @@ const composeServerlessDefinition = async (AppDefinition) => {
92
93
  new WebsocketBuilder(),
93
94
  new IntegrationBuilder(),
94
95
  new SchedulerBuilder(), // Add scheduler after IntegrationBuilder (depends on it)
96
+ new TriggerBuilder(), // One trigger tick function per integration with triggers (ADR-055)
95
97
  new AdminScriptBuilder(),
96
98
  ]);
97
99
 
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.693.d8859c2.0",
4
+ "version": "2.0.0--canary.694.f66a64a.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.693.d8859c2.0",
30
- "@friggframework/schemas": "2.0.0--canary.693.d8859c2.0",
31
- "@friggframework/test": "2.0.0--canary.693.d8859c2.0",
29
+ "@friggframework/core": "2.0.0--canary.694.f66a64a.0",
30
+ "@friggframework/schemas": "2.0.0--canary.694.f66a64a.0",
31
+ "@friggframework/test": "2.0.0--canary.694.f66a64a.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.693.d8859c2.0",
60
- "@friggframework/prettier-config": "2.0.0--canary.693.d8859c2.0",
59
+ "@friggframework/eslint-config": "2.0.0--canary.694.f66a64a.0",
60
+ "@friggframework/prettier-config": "2.0.0--canary.694.f66a64a.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": "d8859c23160346b2f8b15cd2caffc814dfd5bf6d"
92
+ "gitHead": "f66a64af4882d4da330f78e13bf570c4e22f6640"
93
93
  }