@friggframework/devtools 2.0.0--canary.686.45cab16.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.
Files changed (29) hide show
  1. package/frigg-cli/build-command/index.js +1 -32
  2. package/frigg-cli/deploy-command/index.js +2 -50
  3. package/frigg-cli/doctor-command/index.js +0 -7
  4. package/frigg-cli/generate-iam-command.js +0 -7
  5. package/frigg-cli/repair-command/index.js +0 -7
  6. package/frigg-cli/start-command/index.js +0 -58
  7. package/infrastructure/__tests__/template-generation.test.js +0 -7
  8. package/infrastructure/create-frigg-infrastructure.js +0 -14
  9. package/infrastructure/domains/admin-scripts/admin-script-builder.js +6 -2
  10. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +30 -0
  11. package/infrastructure/domains/scheduler/trigger-builder.js +114 -0
  12. package/infrastructure/domains/scheduler/trigger-builder.test.js +82 -0
  13. package/infrastructure/domains/shared/function-environments.js +9 -1
  14. package/infrastructure/domains/shared/function-environments.test.js +14 -0
  15. package/infrastructure/domains/shared/types/app-definition.js +1 -15
  16. package/infrastructure/domains/shared/utilities/base-definition-factory.js +10 -28
  17. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +1 -85
  18. package/infrastructure/infrastructure-composer.js +2 -0
  19. package/infrastructure/infrastructure-composer.test.js +0 -7
  20. package/infrastructure/scripts/build-prisma-layer.js +5 -32
  21. package/infrastructure/scripts/build-prisma-layer.test.js +0 -35
  22. package/package.json +7 -7
  23. package/frigg-cli/__tests__/unit/commands/provider-dispatch.test.js +0 -140
  24. package/frigg-cli/utils/provider-helper.js +0 -80
  25. package/infrastructure/__tests__/create-frigg-infrastructure-provider.test.js +0 -64
  26. package/infrastructure/__tests__/management-api-gateway-routes.test.js +0 -335
  27. package/infrastructure/provider-build.js +0 -119
  28. package/test/npm-install-guard.js +0 -104
  29. package/test/npm-install-guard.test.js +0 -53
@@ -1,22 +1,7 @@
1
1
  const { spawnSync } = require('child_process');
2
2
  const path = require('path');
3
3
 
4
- async function buildCommand(options = {}) {
5
- // A non-AWS provider (appDefinition.provider) builds through its plugin:
6
- // platform config + function entry points, no serverless package
7
- // (friggframework/frigg#545).
8
- const providerResult = loadProviderIfConfigured();
9
- if (providerResult) {
10
- const { buildWithProvider } = require('../../infrastructure/provider-build');
11
- buildWithProvider({
12
- appDefinition: providerResult.appDefinition,
13
- backendDir: providerResult.backendDir,
14
- provider: providerResult.provider,
15
- verbose: options.verbose,
16
- });
17
- return;
18
- }
19
-
4
+ async function buildCommand(options) {
20
5
  console.log('Building the serverless application...');
21
6
 
22
7
  // Suppress AWS SDK warning message about maintenance mode
@@ -78,20 +63,4 @@ async function buildCommand(options = {}) {
78
63
  // });
79
64
  }
80
65
 
81
- /**
82
- * The resolved non-AWS provider, or null for AWS / no app definition found.
83
- */
84
- function loadProviderIfConfigured() {
85
- const { loadProviderForCli } = require('../utils/provider-helper');
86
- let result;
87
- try {
88
- result = loadProviderForCli();
89
- } catch (error) {
90
- // A non-AWS provider whose package is missing: say so, don't build for AWS.
91
- console.error(error.message);
92
- process.exit(1);
93
- }
94
- return result && result.provider ? result : null;
95
- }
96
-
97
66
  module.exports = { buildCommand };
@@ -310,16 +310,9 @@ async function pushOffloadedParametersOrAbort(appDefinition, options) {
310
310
  }
311
311
 
312
312
  async function deployCommand(options) {
313
- const appDefinition = loadAppDefinition();
314
-
315
- // A non-AWS provider (appDefinition.provider) deploys through its plugin
316
- // (friggframework/frigg#545).
317
- const providerName = appDefinition?.provider;
318
- if (providerName && providerName !== 'aws') {
319
- return deployWithProvider(appDefinition, providerName, options);
320
- }
321
-
322
313
  console.log('Deploying the serverless application...');
314
+
315
+ const appDefinition = loadAppDefinition();
323
316
  const environment = validateAndBuildEnvironment(appDefinition, options);
324
317
 
325
318
  await pushOffloadedParametersOrAbort(appDefinition, options);
@@ -353,45 +346,4 @@ async function deployCommand(options) {
353
346
  }
354
347
  }
355
348
 
356
- /**
357
- * Deploy with a provider plugin: validate(), then deploy() (which runs its
358
- * own preflightCheck()).
359
- */
360
- async function deployWithProvider(appDefinition, providerName, options = {}) {
361
- let provider;
362
- try {
363
- const { resolveProvider } = require('@friggframework/core/providers/resolve-provider');
364
- provider = resolveProvider(appDefinition);
365
- } catch (error) {
366
- console.error(`Failed to load provider '${providerName}': ${error.message}`);
367
- process.exit(1);
368
- }
369
-
370
- console.log(`Deploying with ${providerName} provider...`);
371
-
372
- if (typeof provider.validate === 'function') {
373
- const validation = provider.validate(appDefinition);
374
- if (validation.errors?.length > 0) {
375
- console.error(`\nValidation errors for ${providerName}:`);
376
- for (const error of validation.errors) console.error(` - ${error}`);
377
- process.exit(1);
378
- }
379
- for (const warning of validation.warnings || []) console.warn(` Warning: ${warning}`);
380
- }
381
-
382
- try {
383
- const result = await provider.deploy(appDefinition, {
384
- stage: options.stage,
385
- prod: options.stage === 'production' || options.stage === 'prod',
386
- dryRun: options.dryRun || false,
387
- });
388
- console.log('\nDeployment completed successfully.');
389
- if (result?.url) console.log(` URL: ${result.url}`);
390
- } catch (error) {
391
- console.error(`\nDeployment failed: ${error.message}`);
392
- for (const item of error.missing || []) console.error(` - ${item}`);
393
- process.exit(1);
394
- }
395
- }
396
-
397
349
  module.exports = { deployCommand };
@@ -246,13 +246,6 @@ async function promptForStackSelection(region) {
246
246
  */
247
247
  async function doctorCommand(stackName, options = {}) {
248
248
  try {
249
- // AWS-only (CloudFormation); a non-AWS provider has nothing to inspect.
250
- if (require('../utils/provider-helper').isNonAwsProject()) {
251
- output.error('The doctor command is only available for AWS deployments.');
252
- output.log('Your appDefinition uses a non-AWS provider.');
253
- process.exit(1);
254
- }
255
-
256
249
  // Extract options with defaults
257
250
  const region = options.region || process.env.AWS_REGION || 'us-east-1';
258
251
  const format = options.format || 'console';
@@ -9,13 +9,6 @@ const { generateIAMCloudFormation, getFeatureSummary } = require('../infrastruct
9
9
  */
10
10
  async function generateIamCommand(options = {}) {
11
11
  try {
12
- // AWS-only (CloudFormation); a non-AWS provider has nothing to inspect.
13
- if (require('./utils/provider-helper').isNonAwsProject()) {
14
- console.error('The generate-iam command is only available for AWS deployments.');
15
- console.log('Your appDefinition uses a non-AWS provider.');
16
- process.exit(1);
17
- }
18
-
19
12
  console.log('🔍 Finding Frigg application...');
20
13
 
21
14
  // Find the backend package.json
@@ -453,13 +453,6 @@ async function handleReconcileRepair(stackIdentifier, report, options) {
453
453
  */
454
454
  async function repairCommand(stackName, options = {}) {
455
455
  try {
456
- // AWS-only (CloudFormation); a non-AWS provider has nothing to inspect.
457
- if (require('../utils/provider-helper').isNonAwsProject()) {
458
- output.error('The repair command is only available for AWS deployments.');
459
- output.log('Your appDefinition uses a non-AWS provider.');
460
- process.exit(1);
461
- }
462
-
463
456
  // Validate required parameter
464
457
  if (!stackName) {
465
458
  console.error('Error: Stack name is required');
@@ -37,12 +37,6 @@ async function startCommand(options) {
37
37
  console.log(chalk.green('✓ Database checks passed\n'));
38
38
  console.log('Starting backend and optional frontend...');
39
39
 
40
- // A non-AWS provider runs its own local dev server (friggframework/frigg#545).
41
- const providerResult = loadNonAwsProvider();
42
- if (providerResult) {
43
- return startWithProvider(providerResult, options);
44
- }
45
-
46
40
  // Suppress AWS SDK warning message about maintenance mode
47
41
  process.env.AWS_SDK_JS_SUPPRESS_MAINTENANCE_MODE_MESSAGE = '1';
48
42
  // Skip AWS discovery for local development
@@ -152,56 +146,4 @@ async function performDatabaseChecks(verbose) {
152
146
  // connection when it starts.
153
147
  }
154
148
 
155
- function loadNonAwsProvider() {
156
- try {
157
- const { loadProviderForCli } = require('../utils/provider-helper');
158
- const result = loadProviderForCli();
159
- return result && result.provider ? result : null;
160
- } catch {
161
- return null;
162
- }
163
- }
164
-
165
- /**
166
- * Local dev server per provider: Netlify -> `netlify dev` (reads netlify.toml
167
- * and serves the generated functions), run from the project root that holds
168
- * backend/ and netlify.toml.
169
- */
170
- function startWithProvider({ providerName, backendDir }, options = {}) {
171
- const DEV_COMMANDS = {
172
- netlify: { command: 'netlify', args: ['dev'] },
173
- };
174
- const devCmd = DEV_COMMANDS[providerName];
175
- if (!devCmd) {
176
- console.error(chalk.red(
177
- `Provider '${providerName}' does not have a local dev server configured.\n` +
178
- ` Supported providers for local dev: ${Object.keys(DEV_COMMANDS).join(', ')}, aws`
179
- ));
180
- process.exit(1);
181
- }
182
-
183
- const cwd = require('node:path').dirname(backendDir);
184
- console.log(chalk.blue(`Starting local dev server (${providerName})...`));
185
- if (options.verbose) {
186
- console.log(`Executing command: ${devCmd.command} ${devCmd.args.join(' ')}`);
187
- console.log(`Working directory: ${cwd}`);
188
- }
189
-
190
- const childProcess = spawn(devCmd.command, devCmd.args, {
191
- cwd,
192
- stdio: 'inherit',
193
- env: { ...process.env },
194
- });
195
- childProcess.on('error', (error) => {
196
- if (error.code === 'ENOENT') {
197
- console.error(chalk.red(`'${devCmd.command}' not found. Install it with: npm install -g ${devCmd.command}-cli`));
198
- } else {
199
- console.error(`Error executing command: ${error.message}`);
200
- }
201
- });
202
- childProcess.on('close', (code) => {
203
- if (code !== 0) console.log(`Child process exited with code ${code}`);
204
- });
205
- }
206
-
207
149
  module.exports = { startCommand };
@@ -5,13 +5,6 @@
5
5
  * valid, consistent CloudFormation templates.
6
6
  */
7
7
 
8
- // Composing must not build the real Prisma layer: that runs npm install
9
- // under packages/devtools, and two workers doing it at once once pruned the
10
- // repository's root node_modules (test/npm-install-guard.js).
11
- jest.mock('../domains/shared/utilities/prisma-layer-manager', () => ({
12
- ensurePrismaLayerExists: jest.fn(async () => {}),
13
- }));
14
-
15
8
  const { composeServerlessDefinition } = require('../infrastructure-composer');
16
9
 
17
10
  describe('CloudFormation Template Generation', () => {
@@ -35,20 +35,6 @@ async function createFriggInfrastructure() {
35
35
  throw new Error('Could not find index.js');
36
36
  }
37
37
 
38
- // A non-AWS provider (appDefinition.provider, e.g. 'netlify') builds
39
- // through its provider plugin instead of serverless/CloudFormation
40
- // (friggframework/frigg#545). Checked before the cache: the cache holds
41
- // serverless definitions only. Returns an empty serverless definition,
42
- // so an osls invocation has nothing to package.
43
- {
44
- const { isNonAwsProvider, buildWithProvider } = require('./provider-build');
45
- const appDefinition = require(backendFilePath).Definition;
46
- if (isNonAwsProvider(appDefinition)) {
47
- buildWithProvider({ appDefinition, backendDir });
48
- return {};
49
- }
50
- }
51
-
52
38
  const cachePath = getCachePath(backendDir);
53
39
  const lockPath = getLockPath(backendDir);
54
40
 
@@ -141,10 +141,12 @@ class AdminScriptBuilder extends InfrastructureBuilder {
141
141
  }
142
142
 
143
143
  createAdminScriptQueue(result, appDefinition) {
144
+ // Registered under custom so the serverless plugin creates it in LocalStack offline
145
+ result.custom.AdminScriptQueue = '${self:service}-${self:provider.stage}-AdminScriptQueue';
144
146
  result.resources.AdminScriptQueue = {
145
147
  Type: 'AWS::SQS::Queue',
146
148
  Properties: {
147
- QueueName: '${self:service}-${self:provider.stage}-AdminScriptQueue',
149
+ QueueName: '${self:custom.AdminScriptQueue}',
148
150
  MessageRetentionPeriod: 86400, // 1 day
149
151
  VisibilityTimeout: 900, // 15 minutes (Lambda max)
150
152
  RedrivePolicy: {
@@ -264,10 +266,12 @@ class AdminScriptBuilder extends InfrastructureBuilder {
264
266
  }
265
267
 
266
268
  createReportQueue(result, appDefinition) {
269
+ // Registered under custom so the serverless plugin creates it in LocalStack offline
270
+ result.custom.ReportQueue = '${self:service}-${self:provider.stage}-ReportQueue';
267
271
  result.resources.ReportQueue = {
268
272
  Type: 'AWS::SQS::Queue',
269
273
  Properties: {
270
- QueueName: '${self:service}-${self:provider.stage}-ReportQueue',
274
+ QueueName: '${self:custom.ReportQueue}',
271
275
  MessageRetentionPeriod: 86400, // 1 day
272
276
  VisibilityTimeout: 900, // 15 minutes (Lambda max)
273
277
  RedrivePolicy: {
@@ -168,6 +168,21 @@ describe('AdminScriptBuilder', () => {
168
168
  expect(result.resources.AdminScriptQueue.Properties.VisibilityTimeout).toBe(900); // 15 minutes
169
169
  });
170
170
 
171
+ it('registers AdminScriptQueue under custom so frigg start creates it locally', async () => {
172
+ const appDefinition = {
173
+ adminScripts: [{ Definition: { name: 'test-script' } }],
174
+ };
175
+
176
+ const result = await adminScriptBuilder.build(appDefinition, {});
177
+
178
+ expect(result.custom.AdminScriptQueue).toBe(
179
+ '${self:service}-${self:provider.stage}-AdminScriptQueue'
180
+ );
181
+ expect(result.resources.AdminScriptQueue.Properties.QueueName).toBe(
182
+ '${self:custom.AdminScriptQueue}'
183
+ );
184
+ });
185
+
171
186
  it('should configure AdminScriptQueue redrive policy to InternalErrorQueue', async () => {
172
187
  const appDefinition = {
173
188
  adminScripts: [
@@ -621,6 +636,21 @@ describe('AdminScriptBuilder', () => {
621
636
  });
622
637
 
623
638
  describe('reports (ReportQueue + reportExecutor)', () => {
639
+ it('registers ReportQueue under custom so frigg start creates it locally', async () => {
640
+ const appDefinition = {
641
+ reports: [{ Definition: { name: 'my-report', version: '1.0.0' } }],
642
+ };
643
+
644
+ const result = await adminScriptBuilder.build(appDefinition, {});
645
+
646
+ expect(result.custom.ReportQueue).toBe(
647
+ '${self:service}-${self:provider.stage}-ReportQueue'
648
+ );
649
+ expect(result.resources.ReportQueue.Properties.QueueName).toBe(
650
+ '${self:custom.ReportQueue}'
651
+ );
652
+ });
653
+
624
654
  it('creates ReportQueue + reportExecutor and wires REPORT_QUEUE_URL when reports are present', async () => {
625
655
  const appDefinition = {
626
656
  reports: [{ Definition: { name: 'my-report', version: '1.0.0' } }],
@@ -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: {
@@ -129,7 +129,7 @@
129
129
  * @typedef {Object} AppDefinition
130
130
  * @property {string} name - Application name
131
131
  * @property {string} stage - Deployment stage (e.g., 'dev', 'production')
132
- * @property {string} provider - Deployment provider: 'aws' (serverless/Lambda) or 'netlify' (@friggframework/provider-netlify)
132
+ * @property {string} provider - Cloud provider (e.g., 'aws')
133
133
  * @property {string} region - AWS region
134
134
  *
135
135
  * @property {VpcDefinition} [vpc] - VPC configuration
@@ -144,20 +144,6 @@
144
144
  * @property {AdminConfig} [admin] - Admin configuration
145
145
  *
146
146
  * @property {Object} [environment] - Environment variables
147
- *
148
- * @property {ExtensionDefinition[]} [coreExtensions] - Core (app-level) extensions that add custom Prisma models, encrypted fields, admin routes and bootstrap hooks (not an integration's Definition.extensions, nor ADR-017's keyed appDefinition.extensions)
149
- */
150
-
151
- /**
152
- * App-level extension: custom models, encryption, admin routes and bootstrap
153
- * @typedef {Object} ExtensionDefinition
154
- * @property {string} name - Unique identifier for this extension
155
- * @property {string} [schema] - Absolute path to a .prisma schema fragment
156
- * @property {Object<string, {fields: string[]}>} [encryption] - Model name → encrypted fields mapping
157
- * @property {Object} [routes] - Express router configuration
158
- * @property {string} routes.path - Base URL path for the extension routes: /admin/<segment>..., never /api (/admin/scripts, /admin/db-migrate and /admin/queue are reserved); served by the auth function
159
- * @property {Function|Object} routes.handler - Router factory (prisma, appDefinition) → Router, or { router } object
160
- * @property {Function} [bootstrap] - Async function (prisma, appDefinition) → void, run by initializeApp()
161
147
  */
162
148
 
163
149
  /**