Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(netlify): let AI agents manage sites, deploys, forms and env vars (#16567)

Odai Ahmaded4585bee0b4
diff --git a/bun.lock b/bun.lock
index f35b4c2aa3f..21440578e29 100644
--- a/bun.lock
+++ b/bun.lock
@@ -6404,15 +6404,17 @@
},
"packages/pieces/community/netlify": {
"name": "@activepieces/piece-netlify",
- "version": "0.1.7",
+ "version": "0.2.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/netsuite": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index c5511e720f0..4ad057d857a 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,16 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Netlify 0.2.0: Start Deploy returns a build, and four actions are builder-only
+
+Start Deploy used to return a deploy. From Netlify 0.2.0 it starts a build through `/sites/{id}/builds` and returns that build: `id` is now the build ID, the deploy fields are gone, and the new `deploy_id` points to the deploy the build creates.
+
+Get Site, List Files, List Site Deploys and Start Deploy are no longer offered to AI agents. They keep working in flows.
+
+#### What you need to do
+
+If a later step reads `{{start_deploy.id}}` or other deploy fields, read `deploy_id` instead, and use Get Deploy with it for the deploy's details. Agents that used these actions switch to Get Site by ID, List Files by Site ID, List Site Deploys by Site ID and Start Deploy by Site ID. Steps keep running on the version they were built with until you upgrade them.
+
#### Invoice Ninja 0.5.0: Get Report returns columns and rows, the existing actions are builder-only, and some text inputs changed type
Get Report used to send a GET to `/api/v1/reports/<type>`, which does not return report data, and returned whatever came back (or an error message as a successful step). From Invoice Ninja 0.5.0 it runs the report and returns `{ reportType, columns, rows, rowCount }`, where each row is keyed by column key (for example `client.name`). It also gains a date range and fails the step on API errors.
diff --git a/packages/pieces/community/netlify/package.json b/packages/pieces/community/netlify/package.json
index 8cac8d5f8c0..7c95f8f8485 100644
--- a/packages/pieces/community/netlify/package.json
+++ b/packages/pieces/community/netlify/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-netlify",
- "version": "0.1.7",
+ "version": "0.2.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -8,14 +8,17 @@
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "^2.3.0",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/netlify/src/i18n/translation.json b/packages/pieces/community/netlify/src/i18n/translation.json
index 97d8c9b8a75..057a7d2daa5 100644
--- a/packages/pieces/community/netlify/src/i18n/translation.json
+++ b/packages/pieces/community/netlify/src/i18n/translation.json
@@ -1,35 +1,127 @@
{
"Netlify is a platform for building and deploying websites and apps.": "Netlify is a platform for building and deploying websites and apps.",
"\nTo authenticate with Netlify:\n\n1. Go to your Netlify user settings\n2. Navigate to \"Applications\" → \"OAuth applications\"\n3. Click \"New OAuth application\"\n4. Add https://cloud.activepieces.com/redirect to authorized redirect URIs\n5. Copy the Client ID and Client Secret\n6. Use the OAuth2 flow below\n\n**Note:** If your team uses SAML SSO, you must grant access to the team when generating your token.\n": "\nTo authenticate with Netlify:\n\n1. Go to your Netlify user settings\n2. Navigate to \"Applications\" → \"OAuth applications\"\n3. Click \"New OAuth application\"\n4. Add https://cloud.activepieces.com/redirect to authorized redirect URIs\n5. Copy the Client ID and Client Secret\n6. Use the OAuth2 flow below\n\n**Note:** If your team uses SAML SSO, you must grant access to the team when generating your token.\n",
- "Start Deploy": "Start Deploy",
+ "List Sites": "List Sites",
"Get Site": "Get Site",
+ "Get Site by ID": "Get Site by ID",
+ "Start Deploy": "Start Deploy",
+ "Start Deploy by Site ID": "Start Deploy by Site ID",
"List Site Deploys": "List Site Deploys",
+ "List Site Deploys by Site ID": "List Site Deploys by Site ID",
+ "Get Deploy": "Get Deploy",
+ "Cancel Deploy": "Cancel Deploy",
+ "Publish Deploy (Rollback)": "Publish Deploy (Rollback)",
+ "Lock Deploy": "Lock Deploy",
+ "Unlock Deploy": "Unlock Deploy",
"List Files": "List Files",
- "Triggers a new build for a site on Netlify. Supports clearing build cache.": "Triggers a new build for a site on Netlify. Supports clearing build cache.",
- "Get a specified site. Note: Environment variable keys and values have moved from build_settings.env and repo.env to a new endpoint. Please use getEnvVars to retrieve site environment variables.": "Get a specified site. Note: Environment variable keys and values have moved from build_settings.env and repo.env to a new endpoint. Please use getEnvVars to retrieve site environment variables.",
- "Returns a list of all deploys for a specific site.": "Returns a list of all deploys for a specific site.",
- "Returns a list of all the files in the current deploy.": "Returns a list of all the files in the current deploy.",
- "Site": "Site",
- "Clear Build Cache": "Clear Build Cache",
+ "List Files by Site ID": "List Files by Site ID",
+ "List Forms": "List Forms",
+ "List Forms by Site ID": "List Forms by Site ID",
+ "List Form Submissions": "List Form Submissions",
+ "List Form Submissions by Form ID": "List Form Submissions by Form ID",
+ "List Environment Variables": "List Environment Variables",
+ "List Environment Variables by Site ID": "List Environment Variables by Site ID",
+ "Set Environment Variable": "Set Environment Variable",
+ "Set Environment Variable by Site ID": "Set Environment Variable by Site ID",
+ "Delete Environment Variable": "Delete Environment Variable",
+ "Delete Environment Variable by Site ID": "Delete Environment Variable by Site ID",
+ "Custom API Call": "Custom API Call",
+ "List the sites the connected account can access, optionally filtered by name.": "List the sites the connected account can access, optionally filtered by name.",
+ "Get the details of a site, including its URLs, build settings and published deploy.": "Get the details of a site, including its URLs, build settings and published deploy.",
+ "Get the details of a site given its ID or domain.": "Get the details of a site given its ID or domain.",
+ "Start a new build and deploy of a site from its Git repository.": "Start a new build and deploy of a site from its Git repository.",
+ "Start a new build and deploy of a site given its ID or domain.": "Start a new build and deploy of a site given its ID or domain.",
+ "List the deploys of a site, newest first.": "List the deploys of a site, newest first.",
+ "List the deploys of a site given its ID or domain.": "List the deploys of a site given its ID or domain.",
+ "Get a deploy by its ID, including its state, branch, commit and URLs.": "Get a deploy by its ID, including its state, branch, commit and URLs.",
+ "Stop a deploy that is still queued or building.": "Stop a deploy that is still queued or building.",
+ "Publish an earlier deploy so it becomes the live version of its site.": "Publish an earlier deploy so it becomes the live version of its site.",
+ "Lock a published deploy so new builds do not replace it (stops auto publishing).": "Lock a published deploy so new builds do not replace it (stops auto publishing).",
+ "Unlock a deploy so new builds are published automatically again.": "Unlock a deploy so new builds are published automatically again.",
+ "List the files of the published deploy of a site.": "List the files of the published deploy of a site.",
+ "List the files of the published deploy of a site given its ID or domain.": "List the files of the published deploy of a site given its ID or domain.",
+ "List the forms of a site with their submission counts.": "List the forms of a site with their submission counts.",
+ "List the forms of a site given its ID or domain.": "List the forms of a site given its ID or domain.",
+ "List the submissions of a form, newest first.": "List the submissions of a form, newest first.",
+ "List the submissions of a form given its ID.": "List the submissions of a form given its ID.",
+ "List the environment variables of a site.": "List the environment variables of a site.",
+ "List the environment variables of a site given its ID or domain.": "List the environment variables of a site given its ID or domain.",
+ "Create an environment variable on a site or change its value.": "Create an environment variable on a site or change its value.",
+ "Create or change an environment variable on a site given its ID or domain.": "Create or change an environment variable on a site given its ID or domain.",
+ "Delete an environment variable from a site.": "Delete an environment variable from a site.",
+ "Delete an environment variable from a site given its ID or domain.": "Delete an environment variable from a site given its ID or domain.",
+ "Make a custom request to the Netlify API with this connection.": "Make a custom request to the Netlify API with this connection.",
+ "Name Contains": "Name Contains",
"Page": "Page",
"Per Page": "Per Page",
- "Select the site to deploy": "Select the site to deploy",
- "Whether to clear the build cache before building": "Whether to clear the build cache before building",
- "Select the site to retrieve information for": "Select the site to retrieve information for",
- "Select the site to list deploys for": "Select the site to list deploys for",
- "Page number for pagination (starts from 1)": "Page number for pagination (starts from 1)",
- "Number of items per page (max 100)": "Number of items per page (max 100)",
- "Select the site to list files for": "Select the site to list files for",
+ "Site": "Site",
+ "Site ID": "Site ID",
+ "Clear Build Cache": "Clear Build Cache",
+ "Deploy ID": "Deploy ID",
+ "Form": "Form",
+ "Form ID": "Form ID",
+ "Deploy Context": "Deploy Context",
+ "Scope": "Scope",
+ "Key": "Key",
+ "Value": "Value",
+ "Secret": "Secret",
+ "URL": "URL",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body": "Body",
+ "Only sites whose name contains this text.": "Only sites whose name contains this text.",
+ "Page number, starting at 1.": "Page number, starting at 1.",
+ "Items per page, 1-100.": "Items per page, 1-100.",
+ "The site to get.": "The site to get.",
+ "The Netlify site ID (API ID, a UUID) or the site domain such as my-site.netlify.app. Use List Sites to find it.": "The Netlify site ID (API ID, a UUID) or the site domain such as my-site.netlify.app. Use List Sites to find it.",
+ "The site to build and deploy.": "The site to build and deploy.",
+ "Clear the build cache before building.": "Clear the build cache before building.",
+ "The site whose deploys to list.": "The site whose deploys to list.",
+ "The Netlify deploy ID, e.g. 6512f0c1a2b3c40008d9e123 (from List Site Deploys or a deploy trigger).": "The Netlify deploy ID, e.g. 6512f0c1a2b3c40008d9e123 (from List Site Deploys or a deploy trigger).",
+ "The ID of the queued or building deploy to cancel.": "The ID of the queued or building deploy to cancel.",
+ "The ID of the deploy to publish (from List Site Deploys).": "The ID of the deploy to publish (from List Site Deploys).",
+ "The ID of the deploy to lock, usually the one currently published.": "The ID of the deploy to lock, usually the one currently published.",
+ "The ID of the locked deploy.": "The ID of the locked deploy.",
+ "The site whose files to list.": "The site whose files to list.",
+ "The site whose forms to list.": "The site whose forms to list.",
+ "The site the form belongs to.": "The site the form belongs to.",
+ "The form whose submissions to list.": "The form whose submissions to list.",
+ "The Netlify form ID. Use List Forms to find it.": "The Netlify form ID. Use List Forms to find it.",
+ "The site whose variables to list.": "The site whose variables to list.",
+ "Only variables with a value for this context.": "Only variables with a value for this context.",
+ "Only variables available in this scope.": "Only variables available in this scope.",
+ "The site to set the variable on.": "The site to set the variable on.",
+ "Variable name, e.g. API_URL (letters, digits and underscores).": "Variable name, e.g. API_URL (letters, digits and underscores).",
+ "Which deploys get this value. All contexts replaces any per-context values. Defaults to all contexts.": "Which deploys get this value. All contexts replaces any per-context values. Defaults to all contexts.",
+ "Only used when the variable is created: hide its value in the Netlify UI and API. Secret variables are available to builds, functions and runtime only and need a specific deploy context.": "Only used when the variable is created: hide its value in the Netlify UI and API. Secret variables are available to builds, functions and runtime only and need a specific deploy context.",
+ "The site to delete the variable from.": "The site to delete the variable from.",
+ "The variable name to delete, e.g. API_URL.": "The variable name to delete, e.g. API_URL.",
+ "Path under https://api.netlify.com/api/v1, e.g. /sites or /sites/{site_id}/deploys. Full URLs must use that base.": "Path under https://api.netlify.com/api/v1, e.g. /sites or /sites/{site_id}/deploys. Full URLs must use that base.",
+ "Extra headers. Authorization always comes from the connection.": "Extra headers. Authorization always comes from the connection.",
+ "JSON body for POST, PUT and PATCH.": "JSON body for POST, PUT and PATCH.",
+ "All contexts": "All contexts",
+ "Production": "Production",
+ "Deploy previews": "Deploy previews",
+ "Branch deploys": "Branch deploys",
+ "Local development (netlify dev)": "Local development (netlify dev)",
+ "Builds": "Builds",
+ "Functions": "Functions",
+ "Runtime": "Runtime",
+ "Post processing": "Post processing",
+ "GET": "GET",
+ "POST": "POST",
+ "PUT": "PUT",
+ "PATCH": "PATCH",
+ "DELETE": "DELETE",
"New Deploy Started": "New Deploy Started",
"New Deploy Succeeded": "New Deploy Succeeded",
"New Deploy Failed": "New Deploy Failed",
"New Form Submission": "New Form Submission",
- "Fires immediately when a deploy job starts on your Netlify site.": "Fires immediately when a deploy job starts on your Netlify site.",
+ "Fires when a deploy starts building on your Netlify site.": "Fires when a deploy starts building on your Netlify site.",
"Fires when a new site version has successfully deployed.": "Fires when a new site version has successfully deployed.",
- "Fires when a site deploy fails.": "Fires when a site deploy fails.",
+ "Fires when a deploy fails on your Netlify site.": "Fires when a deploy fails on your Netlify site.",
"Fires when a Netlify form submission is received.": "Fires when a Netlify form submission is received.",
- "Select the site to monitor for deploy events": "Select the site to monitor for deploy events",
- "Select the site to monitor for successful deploy events": "Select the site to monitor for successful deploy events",
- "Select the site to monitor for failed deploy events": "Select the site to monitor for failed deploy events",
- "Select the site to monitor for form submissions": "Select the site to monitor for form submissions"
+ "Select the site to watch for deploys.": "Select the site to watch for deploys.",
+ "Select the site to watch for form submissions.": "Select the site to watch for form submissions."
}
\ No newline at end of file
diff --git a/packages/pieces/community/netlify/src/index.ts b/packages/pieces/community/netlify/src/index.ts
index a150d27b01a..de36be18f1a 100644
--- a/packages/pieces/community/netlify/src/index.ts
+++ b/packages/pieces/community/netlify/src/index.ts
@@ -1,35 +1,57 @@
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { cancelDeploy } from './lib/actions/cancel-deploy';
+import { customApiCall } from './lib/actions/custom-api-call';
+import { deleteEnvVar, deleteEnvVarById, listEnvVars, listEnvVarsById, setEnvVar, setEnvVarById } from './lib/actions/env-vars';
+import { getDeploy } from './lib/actions/get-deploy';
+import { getSite, getSiteById } from './lib/actions/get-site';
+import { listFiles, listFilesById } from './lib/actions/list-files';
+import { listFormSubmissions, listFormSubmissionsById } from './lib/actions/list-form-submissions';
+import { listForms, listFormsById } from './lib/actions/list-forms';
+import { listSiteDeploys, listSiteDeploysById } from './lib/actions/list-site-deploys';
+import { listSites } from './lib/actions/list-sites';
+import { lockDeploy, unlockDeploy } from './lib/actions/lock-deploy';
+import { restoreDeploy } from './lib/actions/restore-deploy';
+import { startDeploy, startDeployById } from './lib/actions/start-deploy';
+import { netlifyAuth } from './lib/common/auth';
+import { newDeployFailed } from './lib/triggers/new-deploy-failed';
+import { newDeployStarted } from './lib/triggers/new-deploy-started';
+import { newDeploySucceeded } from './lib/triggers/new-deploy-succeeded';
+import { newFormSubmission } from './lib/triggers/new-form-submission';
- import { createPiece } from "@activepieces/pieces-framework";
- import { netlifyAuth } from "./lib/common/auth";
- import { startDeploy } from "./lib/actions/start-deploy";
- import { getSite } from "./lib/actions/get-site";
- import { listSiteDeploys } from "./lib/actions/list-site-deploys";
- import { listFiles } from "./lib/actions/list-files";
- import { newDeployStarted } from "./lib/triggers/new-deploy-started";
- import { newDeploySucceeded } from "./lib/triggers/new-deploy-succeeded";
- import { newDeployFailed } from "./lib/triggers/new-deploy-failed";
- import { newFormSubmission } from "./lib/triggers/new-form-submission";
-import { PieceCategory } from '@activepieces/pieces-framework';
-
- export const netlify = createPiece({
- displayName: "Netlify",
- auth: netlifyAuth,
- minimumSupportedRelease: '0.36.1',
- description: "Netlify is a platform for building and deploying websites and apps.",
- logoUrl: "https://cdn.activepieces.com/pieces/netlify.png",
- authors: ["sparkybug"],
- categories: [PieceCategory.DEVELOPER_TOOLS],
- actions: [
- startDeploy,
- getSite,
- listSiteDeploys,
- listFiles,
- ],
- triggers: [
- newDeployStarted,
- newDeploySucceeded,
- newDeployFailed,
- newFormSubmission,
- ],
- });
-
\ No newline at end of file
+export const netlify = createPiece({
+ displayName: 'Netlify',
+ auth: netlifyAuth,
+ minimumSupportedRelease: '0.36.1',
+ description: 'Netlify is a platform for building and deploying websites and apps.',
+ logoUrl: 'https://cdn.activepieces.com/pieces/netlify.png',
+ authors: ['sparkybug'],
+ categories: [PieceCategory.DEVELOPER_TOOLS],
+ actions: [
+ listSites,
+ getSite,
+ getSiteById,
+ startDeploy,
+ startDeployById,
+ listSiteDeploys,
+ listSiteDeploysById,
+ getDeploy,
+ cancelDeploy,
+ restoreDeploy,
+ lockDeploy,
+ unlockDeploy,
+ listFiles,
+ listFilesById,
+ listForms,
+ listFormsById,
+ listFormSubmissions,
+ listFormSubmissionsById,
+ listEnvVars,
+ listEnvVarsById,
+ setEnvVar,
+ setEnvVarById,
+ deleteEnvVar,
+ deleteEnvVarById,
+ customApiCall,
+ ],
+ triggers: [newDeployStarted, newDeploySucceeded, newDeployFailed, newFormSubmission],
+});
diff --git a/packages/pieces/community/netlify/src/lib/actions/cancel-deploy.ts b/packages/pieces/community/netlify/src/lib/actions/cancel-deploy.ts
new file mode 100644
index 00000000000..dddc9d6f277
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/actions/cancel-deploy.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+
+export const cancelDeploy = createAction({
+ auth: netlifyAuth,
+ name: 'cancel_deploy',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Cancel Deploy',
+ description: 'Stop a deploy that is still queued or building.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Cancels one Netlify deploy that is still enqueued or building; the build stops and cannot be resumed (start a new one with Start Deploy). Fails if the deploy has already finished. Returns the cancelled deploy.',
+ idempotent: false,
+ },
+ outputSchema: netlifySchemas.deploy,
+ props: { deployId: netlifyProps.deployId({ description: 'The ID of the queued or building deploy to cancel.' }) },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.cancelDeploy({ auth, deployId: propsValue.deployId });
+ },
+});
diff --git a/packages/pieces/community/netlify/src/lib/actions/custom-api-call.ts b/packages/pieces/community/netlify/src/lib/actions/custom-api-call.ts
new file mode 100644
index 00000000000..c38b560f5c2
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/actions/custom-api-call.ts
@@ -0,0 +1,60 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyClient } from '../common/client';
+
+export const customApiCall = createAction({
+ auth: netlifyAuth,
+ name: 'custom_api_call',
+ classification: 'WRITE',
+ displayName: 'Custom API Call',
+ description: 'Make a custom request to the Netlify API with this connection.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Sends one raw request to the Netlify API (https://api.netlify.com/api/v1) with the connected account. Use only when no dedicated Netlify action covers the endpoint. The effect depends on the method and path, so it is not safe to retry blindly.',
+ idempotent: false,
+ },
+ props: {
+ url: Property.ShortText({
+ displayName: 'URL',
+ description: 'Path under https://api.netlify.com/api/v1, e.g. /sites or /sites/{site_id}/deploys. Full URLs must use that base.',
+ required: true,
+ }),
+ method: Property.StaticDropdown({
+ displayName: 'Method',
+ required: true,
+ defaultValue: HttpMethod.GET,
+ options: {
+ options: [HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH, HttpMethod.DELETE].map((method) => ({ label: method, value: method })),
+ },
+ }),
+ headers: Property.Object({ displayName: 'Headers', description: 'Extra headers. Authorization always comes from the connection.', required: false }),
+ queryParams: Property.Object({ displayName: 'Query Parameters', required: false }),
+ body: Property.Json({ displayName: 'Body', description: 'JSON body for POST, PUT and PATCH.', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const response = await netlifyClient.request({
+ auth,
+ method: propsValue.method,
+ path: netlifyClient.apiPath(propsValue.url),
+ query: stringRecord(propsValue.queryParams),
+ extraHeaders: stringRecord(propsValue.headers),
+ body: jsonBody(propsValue.body),
+ redactBody: true,
+ });
+ return { status: response.status, body: response.body };
+ },
+});
+
+function stringRecord(value: unknown): Record<string, string> {
+ if (!netlifyClient.isRecord(value)) return {};
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined && item !== null && item !== '').map(([key, item]) => [key, String(item)]));
+}
+
+function jsonBody(value: unknown): Record<string, unknown> | Record<string, unknown>[] | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ if (netlifyClient.isRecord(value)) return value;
+ if (Array.isArray(value) && value.every((item) => netlifyClient.isRecord(item))) return value.filter(netlifyClient.isRecord);
+ throw new Error('Body must be a JSON object or an array of objects.');
+}
diff --git a/packages/pieces/community/netlify/src/lib/actions/env-vars.ts b/packages/pieces/community/netlify/src/lib/actions/env-vars.ts
new file mode 100644
index 00000000000..c77e6e521f0
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/actions/env-vars.ts
@@ -0,0 +1,175 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+
+const CONTEXTS = [
+ { label: 'All contexts', value: 'all' },
+ { label: 'Production', value: 'production' },
+ { label: 'Deploy previews', value: 'deploy-preview' },
+ { label: 'Branch deploys', value: 'branch-deploy' },
+ { label: 'Local development (netlify dev)', value: 'dev' },
+];
+
+function listFilters() {
+ return {
+ context: Property.StaticDropdown({
+ displayName: 'Deploy Context',
+ description: 'Only variables with a value for this context.',
+ required: false,
+ options: { options: CONTEXTS },
+ }),
+ scope: Property.StaticDropdown({
+ displayName: 'Scope',
+ description: 'Only variables available in this scope.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Builds', value: 'builds' },
+ { label: 'Functions', value: 'functions' },
+ { label: 'Runtime', value: 'runtime' },
+ { label: 'Post processing', value: 'post-processing' },
+ ],
+ },
+ }),
+ };
+}
+
+function setFields() {
+ return {
+ key: Property.ShortText({ displayName: 'Key', description: 'Variable name, e.g. API_URL (letters, digits and underscores).', required: true }),
+ value: Property.LongText({ displayName: 'Value', required: true }),
+ context: Property.StaticDropdown({
+ displayName: 'Deploy Context',
+ description: 'Which deploys get this value. All contexts replaces any per-context values. Defaults to all contexts.',
+ required: false,
+ defaultValue: 'all',
+ options: { options: CONTEXTS },
+ }),
+ isSecret: Property.Checkbox({
+ displayName: 'Secret',
+ description: 'Only used when the variable is created: hide its value in the Netlify UI and API. Secret variables are available to builds, functions and runtime only and need a specific deploy context.',
+ required: false,
+ defaultValue: false,
+ }),
+ };
+}
+
+function keyField() {
+ return Property.ShortText({ displayName: 'Key', description: 'The variable name to delete, e.g. API_URL.', required: true });
+}
+
+export const listEnvVars = createAction({
+ auth: netlifyAuth,
+ name: 'list_env_vars',
+ classification: 'SEARCH',
+ displayName: 'List Environment Variables',
+ description: 'List the environment variables of a site.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Lists the environment variables of one Netlify site (site-level and team-level ones that apply to it) with key, scopes, secret flag and the value per deploy context; secret values come back empty. Optionally filter by deploy context or scope. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.envVarList,
+ props: { siteId: netlifyProps.siteDropdown({ description: 'The site whose variables to list.' }), ...listFilters() },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listEnvVars({ auth, siteId: propsValue.siteId, context: propsValue.context, scope: propsValue.scope });
+ },
+});
+
+export const listEnvVarsById = createAction({
+ auth: netlifyAuth,
+ name: 'list_env_vars_by_id',
+ classification: 'SEARCH',
+ displayName: 'List Environment Variables by Site ID',
+ description: 'List the environment variables of a site given its ID or domain.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the environment variables of one Netlify site (site-level and team-level ones that apply to it) with key, scopes, secret flag and the value per deploy context; secret values come back empty. Optionally filter by deploy context or scope. Read-only. Get the site ID from List Sites.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.envVarList,
+ props: { siteId: netlifyProps.siteId(), ...listFilters() },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listEnvVars({ auth, siteId: propsValue.siteId, context: propsValue.context, scope: propsValue.scope });
+ },
+});
+
+export const setEnvVar = createAction({
+ auth: netlifyAuth,
+ name: 'set_env_var',
+ classification: 'WRITE',
+ displayName: 'Set Environment Variable',
+ description: 'Create an environment variable on a site or change its value.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Sets the value of one environment variable on a Netlify site for a deploy context (default all), creating the variable if it does not exist. Choosing all contexts replaces any per-context values with this one value; choosing one context changes only that context. Running it again with the same value changes nothing. The value is not returned. Takes effect on the next deploy (use Start Deploy).',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.envVarWrite,
+ props: { siteId: netlifyProps.siteDropdown({ description: 'The site to set the variable on.' }), ...setFields() },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.setEnvVar({ auth, siteId: propsValue.siteId, key: propsValue.key, value: propsValue.value, context: propsValue.context, isSecret: propsValue.isSecret });
+ },
+});
+
+export const setEnvVarById = createAction({
+ auth: netlifyAuth,
+ name: 'set_env_var_by_id',
+ classification: 'WRITE',
+ displayName: 'Set Environment Variable by Site ID',
+ description: 'Create or change an environment variable on a site given its ID or domain.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sets the value of one environment variable on a Netlify site for a deploy context (default all), creating the variable if it does not exist. Choosing all contexts replaces any per-context values with this one value; choosing one context changes only that context. Running it again with the same value changes nothing. The value is not returned. Takes effect on the next deploy (use Start Deploy). Get the site ID from List Sites.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.envVarWrite,
+ props: { siteId: netlifyProps.siteId(), ...setFields() },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.setEnvVar({ auth, siteId: propsValue.siteId, key: propsValue.key, value: propsValue.value, context: propsValue.context, isSecret: propsValue.isSecret });
+ },
+});
+
+export const deleteEnvVar = createAction({
+ auth: netlifyAuth,
+ name: 'delete_env_var',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Environment Variable',
+ description: 'Delete an environment variable from a site.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Deletes one environment variable (all its values in every context) from a Netlify site. Cannot be undone. If the key does not exist, returns already_deleted=true instead of failing. Takes effect on the next deploy.',
+ idempotent: false,
+ },
+ outputSchema: netlifySchemas.envVarDelete,
+ props: { siteId: netlifyProps.siteDropdown({ description: 'The site to delete the variable from.' }), key: keyField() },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.deleteEnvVar({ auth, siteId: propsValue.siteId, key: propsValue.key });
+ },
+});
+
+export const deleteEnvVarById = createAction({
+ auth: netlifyAuth,
+ name: 'delete_env_var_by_id',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Environment Variable by Site ID',
+ description: 'Delete an environment variable from a site given its ID or domain.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Deletes one environment variable (all its values in every context) from a Netlify site. Cannot be undone. If the key does not exist, returns already_deleted=true instead of failing. Takes effect on the next deploy. Get the site ID from List Sites.',
+ idempotent: false,
+ },
+ outputSchema: netlifySchemas.envVarDelete,
+ props: { siteId: netlifyProps.siteId(), key: keyField() },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.deleteEnvVar({ auth, siteId: propsValue.siteId, key: propsValue.key });
+ },
+});
diff --git a/packages/pieces/community/netlify/src/lib/actions/get-deploy.ts b/packages/pieces/community/netlify/src/lib/actions/get-deploy.ts
new file mode 100644
index 00000000000..158684cc51d
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/actions/get-deploy.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+
+export const getDeploy = createAction({
+ auth: netlifyAuth,
+ name: 'get_deploy',
+ classification: 'READ',
+ displayName: 'Get Deploy',
+ description: 'Get a deploy by its ID, including its state, branch, commit and URLs.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Gets one Netlify deploy by deploy ID with its state (enqueued, building, ready, error, cancelled…), error message, branch, commit, context and preview URL. Use it to check whether a build started by Start Deploy has finished. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.deploy,
+ props: { deployId: netlifyProps.deployId() },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.getDeploy({ auth, deployId: propsValue.deployId });
+ },
+});
diff --git a/packages/pieces/community/netlify/src/lib/actions/get-site.ts b/packages/pieces/community/netlify/src/lib/actions/get-site.ts
index 95722e3a964..124d42a1223 100644
--- a/packages/pieces/community/netlify/src/lib/actions/get-site.ts
+++ b/packages/pieces/community/netlify/src/lib/actions/get-site.ts
@@ -1,111 +1,43 @@
-import { createAction, Property, OAuth2PropertyValue } from "@activepieces/pieces-framework";
-import { httpClient, HttpMethod } from "@activepieces/pieces-common";
-import { netlifyAuth } from "../common/auth";
+import { createAction } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
export const getSite = createAction({
- name: "get_site",
+ auth: netlifyAuth,
+ name: 'get_site',
classification: 'READ',
- displayName: "Get Site",
- description: "Get a specified site. Note: Environment variable keys and values have moved from build_settings.env and repo.env to a new endpoint. Please use getEnvVars to retrieve site environment variables.",
- audience: 'both',
- aiMetadata: { description: 'Retrieves the configuration and metadata for a single Netlify site by its site ID. Use it to look up details such as the site URL, build settings, or deploy info. Read-only and idempotent. Note: site environment variables are no longer included here and must be fetched from the dedicated env-vars endpoint.', idempotent: true },
- props: {
- siteId: Property.Dropdown({
- auth: netlifyAuth, displayName: "Site",
- description: "Select the site to retrieve information for",
- required: true,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: "Connect your account first",
- options: [],
- };
- }
-
- const authentication = auth as OAuth2PropertyValue;
- if (!authentication.access_token) {
- return {
- disabled: true,
- placeholder: "Access token is required",
- options: [],
- };
- }
-
- try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: "https://api.netlify.com/api/v1/sites?per_page=50",
- headers: {
- "Authorization": `Bearer ${authentication.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- const sites = response.body as any[];
- return {
- disabled: false,
- options: sites.map((site) => ({
- label: `${site.name} (${site.url})`,
- value: site.id,
- })),
- };
- } else {
- return {
- disabled: true,
- placeholder: `Failed to fetch sites: ${response.status}`,
- options: [],
- };
- }
- } catch (error) {
- return {
- disabled: true,
- placeholder: "Failed to fetch sites",
- options: [],
- };
- }
- },
- }),
+ displayName: 'Get Site',
+ description: 'Get the details of a site, including its URLs, build settings and published deploy.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Gets one Netlify site with its URLs, custom domain, team, build settings and currently published deploy. Use it to read a site\'s configuration or find which deploy is live; use List Site Deploys for history. Environment variables are not included (use List Environment Variables). Read-only.',
+ idempotent: true,
},
- async run(context) {
- const { siteId } = context.propsValue;
-
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://api.netlify.com/api/v1/sites/${siteId}`,
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- return response.body;
- }
-
- if (response.status === 404) {
- throw new Error(`Site not found: ${siteId}. Please check the site ID or domain.`);
- }
-
- if (response.status === 401) {
- throw new Error("Unauthorized. Please check your access token.");
- }
-
- if (response.status === 403) {
- throw new Error("Forbidden. You don't have permission to access this site.");
- }
+ outputSchema: netlifySchemas.site,
+ props: { siteId: netlifyProps.siteDropdown({ description: 'The site to get.' }) },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.getSite({ auth, siteId: propsValue.siteId });
+ },
+});
- throw new Error(`Failed to get site: ${response.status}`);
+export const getSiteById = createAction({
+ auth: netlifyAuth,
+ name: 'get_site_by_id',
+ classification: 'READ',
+ displayName: 'Get Site by ID',
+ description: 'Get the details of a site given its ID or domain.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Gets one Netlify site with its URLs, custom domain, team, build settings and currently published deploy. Use it to read a site\'s configuration or find which deploy is live; use List Site Deploys for history. Environment variables are not included (use List Environment Variables). Read-only. Get the site ID from List Sites.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.site,
+ props: { siteId: netlifyProps.siteId() },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.getSite({ auth, siteId: propsValue.siteId });
},
});
diff --git a/packages/pieces/community/netlify/src/lib/actions/list-files.ts b/packages/pieces/community/netlify/src/lib/actions/list-files.ts
index 20d0855b130..d5984ddc226 100644
--- a/packages/pieces/community/netlify/src/lib/actions/list-files.ts
+++ b/packages/pieces/community/netlify/src/lib/actions/list-files.ts
@@ -1,111 +1,43 @@
-import { createAction, Property, OAuth2PropertyValue } from "@activepieces/pieces-framework";
-import { httpClient, HttpMethod } from "@activepieces/pieces-common";
-import { netlifyAuth } from "../common/auth";
+import { createAction } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
export const listFiles = createAction({
- name: "list_files",
+ auth: netlifyAuth,
+ name: 'list_files',
classification: 'SEARCH',
- displayName: "List Files",
- description: "Returns a list of all the files in the current deploy.",
- audience: 'both',
- aiMetadata: { description: 'Lists all files in the current (published) deploy of a Netlify site, identified by its site ID. Use it to inspect which files are served for the live site. Read-only and idempotent.', idempotent: true },
- props: {
- siteId: Property.Dropdown({
- auth: netlifyAuth, displayName: "Site",
- description: "Select the site to list files for",
- required: true,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: "Connect your account first",
- options: [],
- };
- }
-
- const authentication = auth as OAuth2PropertyValue;
- if (!authentication.access_token) {
- return {
- disabled: true,
- placeholder: "Access token is required",
- options: [],
- };
- }
-
- try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: "https://api.netlify.com/api/v1/sites?per_page=50",
- headers: {
- "Authorization": `Bearer ${authentication.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- const sites = response.body as any[];
- return {
- disabled: false,
- options: sites.map((site) => ({
- label: `${site.name} (${site.url})`,
- value: site.id,
- })),
- };
- } else {
- return {
- disabled: true,
- placeholder: `Failed to fetch sites: ${response.status}`,
- options: [],
- };
- }
- } catch (error) {
- return {
- disabled: true,
- placeholder: "Failed to fetch sites",
- options: [],
- };
- }
- },
- }),
+ displayName: 'List Files',
+ description: 'List the files of the published deploy of a site.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Lists every file served by the currently published deploy of one Netlify site, with path, MIME type, size and SHA-1. Use it to check whether a page or asset is live. Read-only.',
+ idempotent: true,
},
- async run(context) {
- const { siteId } = context.propsValue;
-
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://api.netlify.com/api/v1/sites/${siteId}/files`,
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- return response.body;
- }
-
- if (response.status === 404) {
- throw new Error(`Site not found: ${siteId}. Please check the site ID or domain.`);
- }
-
- if (response.status === 401) {
- throw new Error("Unauthorized. Please check your access token.");
- }
-
- if (response.status === 403) {
- throw new Error("Forbidden. You don't have permission to access this site.");
- }
+ outputSchema: netlifySchemas.fileList,
+ props: { siteId: netlifyProps.siteDropdown({ description: 'The site whose files to list.' }) },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listFiles({ auth, siteId: propsValue.siteId });
+ },
+});
- throw new Error(`Failed to list files: ${response.status}`);
+export const listFilesById = createAction({
+ auth: netlifyAuth,
+ name: 'list_files_by_id',
+ classification: 'SEARCH',
+ displayName: 'List Files by Site ID',
+ description: 'List the files of the published deploy of a site given its ID or domain.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every file served by the currently published deploy of one Netlify site, with path, MIME type, size and SHA-1. Use it to check whether a page or asset is live. Read-only. Get the site ID from List Sites.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.fileList,
+ props: { siteId: netlifyProps.siteId() },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listFiles({ auth, siteId: propsValue.siteId });
},
});
diff --git a/packages/pieces/community/netlify/src/lib/actions/list-form-submissions.ts b/packages/pieces/community/netlify/src/lib/actions/list-form-submissions.ts
new file mode 100644
index 00000000000..4c162af6ef2
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/actions/list-form-submissions.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+
+export const listFormSubmissions = createAction({
+ auth: netlifyAuth,
+ name: 'list_form_submissions',
+ classification: 'SEARCH',
+ displayName: 'List Form Submissions',
+ description: 'List the submissions of a form, newest first.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Lists the verified submissions of one Netlify form, newest first, one page at a time (Per Page up to 100; ask for the next page when a full page comes back). Each submission has its number, email, name, submitted field values and time. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.submissionList,
+ props: {
+ siteId: netlifyProps.siteDropdown({ description: 'The site the form belongs to.' }),
+ formId: netlifyProps.formDropdown(),
+ page: netlifyProps.page(),
+ perPage: netlifyProps.perPage({ defaultValue: 100 }),
+ },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listSubmissions({ auth, formId: propsValue.formId, page: propsValue.page, perPage: propsValue.perPage });
+ },
+});
+
+export const listFormSubmissionsById = createAction({
+ auth: netlifyAuth,
+ name: 'list_form_submissions_by_id',
+ classification: 'SEARCH',
+ displayName: 'List Form Submissions by Form ID',
+ description: 'List the submissions of a form given its ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the verified submissions of one Netlify form, newest first, one page at a time (Per Page up to 100; ask for the next page when a full page comes back). Each submission has its number, email, name, submitted field values and time. Read-only. Get the form ID from List Forms.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.submissionList,
+ props: {
+ formId: Property.ShortText({ displayName: 'Form ID', description: 'The Netlify form ID. Use List Forms to find it.', required: true }),
+ page: netlifyProps.page(),
+ perPage: netlifyProps.perPage({ defaultValue: 20 }),
+ },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listSubmissions({ auth, formId: propsValue.formId, page: propsValue.page, perPage: propsValue.perPage });
+ },
+});
diff --git a/packages/pieces/community/netlify/src/lib/actions/list-forms.ts b/packages/pieces/community/netlify/src/lib/actions/list-forms.ts
new file mode 100644
index 00000000000..ceddd1ed14a
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/actions/list-forms.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+
+export const listForms = createAction({
+ auth: netlifyAuth,
+ name: 'list_forms',
+ classification: 'SEARCH',
+ displayName: 'List Forms',
+ description: 'List the forms of a site with their submission counts.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Lists the Netlify Forms detected on one site with their ID, name, field names and submission count. Use a form ID with List Form Submissions. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.formList,
+ props: { siteId: netlifyProps.siteDropdown({ description: 'The site whose forms to list.' }) },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listForms({ auth, siteId: propsValue.siteId });
+ },
+});
+
+export const listFormsById = createAction({
+ auth: netlifyAuth,
+ name: 'list_forms_by_id',
+ classification: 'SEARCH',
+ displayName: 'List Forms by Site ID',
+ description: 'List the forms of a site given its ID or domain.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the Netlify Forms detected on one site with their ID, name, field names and submission count. Use a form ID with List Form Submissions. Read-only. Get the site ID from List Sites.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.formList,
+ props: { siteId: netlifyProps.siteId() },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listForms({ auth, siteId: propsValue.siteId });
+ },
+});
diff --git a/packages/pieces/community/netlify/src/lib/actions/list-site-deploys.ts b/packages/pieces/community/netlify/src/lib/actions/list-site-deploys.ts
index 5ef0d6137af..220ae45d4aa 100644
--- a/packages/pieces/community/netlify/src/lib/actions/list-site-deploys.ts
+++ b/packages/pieces/community/netlify/src/lib/actions/list-site-deploys.ts
@@ -1,127 +1,51 @@
-import { createAction, Property, OAuth2PropertyValue } from "@activepieces/pieces-framework";
-import { httpClient, HttpMethod } from "@activepieces/pieces-common";
-import { netlifyAuth } from "../common/auth";
+import { createAction } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
export const listSiteDeploys = createAction({
- name: "list_site_deploys",
+ auth: netlifyAuth,
+ name: 'list_site_deploys',
classification: 'SEARCH',
- displayName: "List Site Deploys",
- description: "Returns a list of all deploys for a specific site.",
- audience: 'both',
- aiMetadata: { description: 'Lists the deploys (builds) for a Netlify site by its site ID, ordered most-recent first, with optional page and per-page pagination. Use it to inspect deploy history or find a deploy state/ID. Read-only and idempotent.', idempotent: true },
+ displayName: 'List Site Deploys',
+ description: 'List the deploys of a site, newest first.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Lists the deploys of one Netlify site, newest first, one page at a time (Per Page up to 100; ask for the next page when a full page comes back). Each deploy has its ID, state, branch, commit, context and URLs; pass an ID to Get Deploy, Cancel Deploy, Restore Deploy or Lock Deploy. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.deployList,
props: {
- siteId: Property.Dropdown({
- auth: netlifyAuth, displayName: "Site",
- description: "Select the site to list deploys for",
- required: true,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: "Connect your account first",
- options: [],
- };
- }
-
- const authentication = auth as OAuth2PropertyValue;
- if (!authentication.access_token) {
- return {
- disabled: true,
- placeholder: "Access token is required",
- options: [],
- };
- }
-
- try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: "https://api.netlify.com/api/v1/sites?per_page=50",
- headers: {
- "Authorization": `Bearer ${authentication.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- const sites = response.body as any[];
- return {
- disabled: false,
- options: sites.map((site) => ({
- label: `${site.name} (${site.url})`,
- value: site.id,
- })),
- };
- } else {
- return {
- disabled: true,
- placeholder: `Failed to fetch sites: ${response.status}`,
- options: [],
- };
- }
- } catch (error) {
- return {
- disabled: true,
- placeholder: "Failed to fetch sites",
- options: [],
- };
- }
- },
- }),
- page: Property.Number({
- displayName: "Page",
- description: "Page number for pagination (starts from 1)",
- required: false,
- defaultValue: 1,
- }),
- perPage: Property.Number({
- displayName: "Per Page",
- description: "Number of items per page (max 100)",
- required: false,
- defaultValue: 100,
- }),
+ siteId: netlifyProps.siteDropdown({ description: 'The site whose deploys to list.' }),
+ page: netlifyProps.page(),
+ perPage: netlifyProps.perPage({ defaultValue: 100 }),
},
- async run(context) {
- const { siteId, page, perPage } = context.propsValue;
-
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- const queryParams = new URLSearchParams();
- if (page) queryParams.append('page', page.toString());
- if (perPage) queryParams.append('per_page', perPage.toString());
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://api.netlify.com/api/v1/sites/${siteId}/deploys?${queryParams.toString()}`,
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- return response.body;
- }
-
- if (response.status === 404) {
- throw new Error(`Site not found: ${siteId}. Please check the site ID or domain.`);
- }
-
- if (response.status === 401) {
- throw new Error("Unauthorized. Please check your access token.");
- }
-
- if (response.status === 403) {
- throw new Error("Forbidden. You don't have permission to access this site.");
- }
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listDeploys({ auth, siteId: propsValue.siteId, page: propsValue.page, perPage: propsValue.perPage });
+ },
+});
- throw new Error(`Failed to list site deploys: ${response.status}`);
+export const listSiteDeploysById = createAction({
+ auth: netlifyAuth,
+ name: 'list_site_deploys_by_id',
+ classification: 'SEARCH',
+ displayName: 'List Site Deploys by Site ID',
+ description: 'List the deploys of a site given its ID or domain.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the deploys of one Netlify site, newest first, one page at a time (Per Page up to 100; ask for the next page when a full page comes back). Each deploy has its ID, state, branch, commit, context and URLs; pass an ID to Get Deploy, Cancel Deploy, Restore Deploy or Lock Deploy. Read-only. Get the site ID from List Sites.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.deployList,
+ props: {
+ siteId: netlifyProps.siteId(),
+ page: netlifyProps.page(),
+ perPage: netlifyProps.perPage({ defaultValue: 20 }),
+ },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listDeploys({ auth, siteId: propsValue.siteId, page: propsValue.page, perPage: propsValue.perPage });
},
});
diff --git a/packages/pieces/community/netlify/src/lib/actions/list-sites.ts b/packages/pieces/community/netlify/src/lib/actions/list-sites.ts
new file mode 100644
index 00000000000..cce3c71c6aa
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/actions/list-sites.ts
@@ -0,0 +1,28 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+
+export const listSites = createAction({
+ auth: netlifyAuth,
+ name: 'list_sites',
+ classification: 'SEARCH',
+ displayName: 'List Sites',
+ description: 'List the sites the connected account can access, optionally filtered by name.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the Netlify sites the connected user can access across all teams, one page at a time (Per Page up to 100; ask for the next page when a full page comes back), optionally filtered by part of the site name. Each site has its ID, name, URLs, team and published deploy; use the ID with the other Netlify actions. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.siteList,
+ props: {
+ name: Property.ShortText({ displayName: 'Name Contains', description: 'Only sites whose name contains this text.', required: false }),
+ page: netlifyProps.page(),
+ perPage: netlifyProps.perPage({ defaultValue: 50 }),
+ },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.listSites({ auth, name: propsValue.name, page: propsValue.page, perPage: propsValue.perPage });
+ },
+});
diff --git a/packages/pieces/community/netlify/src/lib/actions/lock-deploy.ts b/packages/pieces/community/netlify/src/lib/actions/lock-deploy.ts
new file mode 100644
index 00000000000..153274930f7
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/actions/lock-deploy.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+
+export const lockDeploy = createAction({
+ auth: netlifyAuth,
+ name: 'lock_deploy',
+ classification: 'WRITE',
+ displayName: 'Lock Deploy',
+ description: 'Lock a published deploy so new builds do not replace it (stops auto publishing).',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Locks one Netlify deploy: the site keeps serving it and stops auto-publishing new production builds until Unlock Deploy is run. Use it to freeze the live version. Locking an already locked deploy changes nothing.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.deploy,
+ props: { deployId: netlifyProps.deployId({ description: 'The ID of the deploy to lock, usually the one currently published.' }) },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.setDeployLock({ auth, deployId: propsValue.deployId, locked: true });
+ },
+});
+
+export const unlockDeploy = createAction({
+ auth: netlifyAuth,
+ name: 'unlock_deploy',
+ classification: 'WRITE',
+ displayName: 'Unlock Deploy',
+ description: 'Unlock a deploy so new builds are published automatically again.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Unlocks one Netlify deploy so the site auto-publishes new production builds again (the next successful build goes live). Unlocking a deploy that is not locked changes nothing.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.deploy,
+ props: { deployId: netlifyProps.deployId({ description: 'The ID of the locked deploy.' }) },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.setDeployLock({ auth, deployId: propsValue.deployId, locked: false });
+ },
+});
diff --git a/packages/pieces/community/netlify/src/lib/actions/restore-deploy.ts b/packages/pieces/community/netlify/src/lib/actions/restore-deploy.ts
new file mode 100644
index 00000000000..0e5030340b7
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/actions/restore-deploy.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+
+export const restoreDeploy = createAction({
+ auth: netlifyAuth,
+ name: 'restore_deploy',
+ classification: 'WRITE',
+ displayName: 'Publish Deploy (Rollback)',
+ description: 'Publish an earlier deploy so it becomes the live version of its site.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Publishes an existing, successfully built Netlify deploy as the live production version of its site, e.g. to roll back to an earlier deploy after a bad release. The site is looked up from the deploy. Publishing the deploy that is already live changes nothing; to undo, publish the previous deploy again. Returns the published deploy.',
+ idempotent: true,
+ },
+ outputSchema: netlifySchemas.deploy,
+ props: { deployId: netlifyProps.deployId({ description: 'The ID of the deploy to publish (from List Site Deploys).' }) },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.restoreDeploy({ auth, deployId: propsValue.deployId });
+ },
+});
diff --git a/packages/pieces/community/netlify/src/lib/actions/start-deploy.ts b/packages/pieces/community/netlify/src/lib/actions/start-deploy.ts
index 8d3d6f68294..cae6d8df8cf 100644
--- a/packages/pieces/community/netlify/src/lib/actions/start-deploy.ts
+++ b/packages/pieces/community/netlify/src/lib/actions/start-deploy.ts
@@ -1,120 +1,58 @@
-import { createAction, Property, OAuth2PropertyValue } from "@activepieces/pieces-framework";
-import { httpClient, HttpMethod } from "@activepieces/pieces-common";
-import { netlifyAuth } from "../common/auth";
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifyOperations } from '../common/operations';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+
+function clearCache() {
+ return Property.Checkbox({
+ displayName: 'Clear Build Cache',
+ description: 'Clear the build cache before building.',
+ required: false,
+ defaultValue: false,
+ });
+}
export const startDeploy = createAction({
- name: "start_deploy",
+ auth: netlifyAuth,
+ name: 'start_deploy',
classification: 'WRITE',
- displayName: "Start Deploy",
- description: "Triggers a new build for a site on Netlify. Supports clearing build cache.",
- audience: 'both',
- aiMetadata: { description: 'Triggers a new build/deploy for a Netlify site, identified by its site ID. Optionally clears the build cache before building. Not idempotent: each call queues a fresh deploy, so calling repeatedly starts multiple builds.', idempotent: false },
+ displayName: 'Start Deploy',
+ description: 'Start a new build and deploy of a site from its Git repository.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Starts a new build of one Netlify site from its linked Git repository\'s production branch, optionally clearing the build cache first. Returns the build with its deploy_id; follow progress with Get Deploy. Each call queues another build, so do not retry blindly. The site must be linked to a repository.',
+ idempotent: false,
+ },
+ outputSchema: netlifySchemas.build,
props: {
- siteId: Property.Dropdown({
- auth: netlifyAuth, displayName: "Site",
- description: "Select the site to deploy",
- required: true,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: "Connect your account first",
- options: [],
- };
- }
-
- const authentication = auth as OAuth2PropertyValue;
- if (!authentication.access_token) {
- return {
- disabled: true,
- placeholder: "Access token is required",
- options: [],
- };
- }
-
- try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: "https://api.netlify.com/api/v1/sites?per_page=50",
- headers: {
- "Authorization": `Bearer ${authentication.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- const sites = response.body as any[];
- return {
- disabled: false,
- options: sites.map((site) => ({
- label: `${site.name} (${site.url})`,
- value: site.id,
- })),
- };
- } else {
- return {
- disabled: true,
- placeholder: `Failed to fetch sites: ${response.status}`,
- options: [],
- };
- }
- } catch (error) {
- return {
- disabled: true,
- placeholder: "Failed to fetch sites",
- options: [],
- };
- }
- },
- }),
- clearCache: Property.Checkbox({
- displayName: "Clear Build Cache",
- description: "Whether to clear the build cache before building",
- required: false,
- defaultValue: false,
- }),
+ siteId: netlifyProps.siteDropdown({ description: 'The site to build and deploy.' }),
+ clearCache: clearCache(),
},
- async run(context) {
- const { siteId, clearCache } = context.propsValue;
-
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `https://api.netlify.com/api/v1/sites/${siteId}/deploys`,
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- "Content-Type": "application/json",
- },
- body: {
- clear_cache: clearCache,
- },
- });
-
- if (response.status === 200 || response.status === 201) {
- return response.body;
- }
-
- if (response.status === 404) {
- throw new Error(`Site not found: ${siteId}. Please check the site ID or domain.`);
- }
-
- if (response.status === 401) {
- throw new Error("Unauthorized. Please check your access token.");
- }
-
- if (response.status === 403) {
- throw new Error("Forbidden. You don't have permission to deploy this site.");
- }
+ async run({ auth, propsValue }) {
+ return netlifyOperations.startBuild({ auth, siteId: propsValue.siteId, clearCache: propsValue.clearCache });
+ },
+});
- throw new Error(`Failed to start deploy: ${response.status}`);
+export const startDeployById = createAction({
+ auth: netlifyAuth,
+ name: 'start_deploy_by_id',
+ classification: 'WRITE',
+ displayName: 'Start Deploy by Site ID',
+ description: 'Start a new build and deploy of a site given its ID or domain.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Starts a new build of one Netlify site from its linked Git repository\'s production branch, optionally clearing the build cache first. Returns the build with its deploy_id; follow progress with Get Deploy. Each call queues another build, so do not retry blindly. The site must be linked to a repository. Get the site ID from List Sites.',
+ idempotent: false,
+ },
+ outputSchema: netlifySchemas.build,
+ props: {
+ siteId: netlifyProps.siteId(),
+ clearCache: clearCache(),
+ },
+ async run({ auth, propsValue }) {
+ return netlifyOperations.startBuild({ auth, siteId: propsValue.siteId, clearCache: propsValue.clearCache });
},
});
diff --git a/packages/pieces/community/netlify/src/lib/common/client.ts b/packages/pieces/community/netlify/src/lib/common/client.ts
new file mode 100644
index 00000000000..0b449c97cc2
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/common/client.ts
@@ -0,0 +1,193 @@
+import { httpClient, HttpMethod, QueryParams } from '@activepieces/pieces-common';
+
+export const NETLIFY_API_BASE = 'https://api.netlify.com/api/v1';
+const REQUEST_TIMEOUT_MS = 30_000;
+const MAX_PAGES = 50;
+const PAGE_SIZE = 100;
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+export class NetlifyApiError extends Error {
+ constructor(message: string, public readonly status: number, public readonly responseBody: unknown) {
+ super(message);
+ this.name = 'NetlifyApiError';
+ }
+}
+
+export type NetlifyAuthValue = unknown;
+
+type QueryValue = string | number | boolean | undefined | null;
+
+function withoutAuthHeaders(headers: Record<string, string> | undefined): Record<string, string> {
+ return Object.fromEntries(Object.entries(headers ?? {}).filter(([key]) => !['authorization', 'host', 'cookie'].includes(key.toLowerCase())));
+}
+
+function apiPath(url: unknown): string {
+ const text = typeof url === 'string' ? url.trim() : '';
+ if (text === '') {
+ throw new Error('URL is required.');
+ }
+ const base = new URL(`${NETLIFY_API_BASE}/`);
+ const target = /^[a-z][a-z0-9+.-]*:/i.test(text) || text.startsWith('//') ? new URL(text) : new URL(text.replace(/^\/+/, ''), base);
+ if (target.origin !== base.origin || target.username !== '' || target.password !== '' || !`${target.pathname}/`.startsWith(base.pathname)) {
+ throw new Error(`URL must be a path under ${NETLIFY_API_BASE}, e.g. /sites.`);
+ }
+ if (target.pathname.split('/').some((part) => part === '..' || decodeURIComponent(part) === '..')) {
+ throw new Error('URL must not contain "..".');
+ }
+ return `${target.pathname.slice(base.pathname.length - 1)}${target.search}`;
+}
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function tokenOf(auth: NetlifyAuthValue): string {
+ const raw = isRecord(auth) ? auth['access_token'] : undefined;
+ const token = typeof raw === 'string' ? raw.trim() : '';
+ if (!token) {
+ throw new Error('The Netlify connection has no access token. Reconnect your Netlify account.');
+ }
+ return token;
+}
+
+function segment({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim() : typeof value === 'number' && Number.isFinite(value) ? String(value) : '';
+ if (text === '' || text === '.' || text === '..') {
+ throw new Error(`${label} is required.`);
+ }
+ return encodeURIComponent(text);
+}
+
+function buildQuery(query?: Record<string, QueryValue>): QueryParams {
+ return Object.fromEntries(
+ Object.entries(query ?? {})
+ .filter(([, value]) => value !== undefined && value !== null && value !== '')
+ .map(([key, value]) => [key, String(value)]),
+ );
+}
+
+function vendorMessage(body: unknown): string {
+ if (isRecord(body)) {
+ const message = body['message'] ?? body['error'];
+ if (typeof message === 'string' && message.trim()) {
+ return message.trim();
+ }
+ }
+ if (typeof body === 'string' && body.trim()) {
+ return body.trim().slice(0, 300);
+ }
+ return 'request failed';
+}
+
+function hintFor(status: number): string {
+ if (status === 401) return ' Reconnect your Netlify account.';
+ if (status === 403) return ' The connected Netlify user has no access to this resource.';
+ if (status === 404) return ' Check the ID; the resource does not exist or is not visible to this account.';
+ if (status === 429) return ' Netlify rate limit reached; try again later.';
+ return '';
+}
+
+function failureOf(error: unknown): { status: number; body: unknown } | null {
+ if (error === null || typeof error !== 'object') return null;
+ const response = Reflect.get(error, 'response');
+ if (!isRecord(response)) return null;
+ const status = response['status'];
+ return typeof status === 'number' ? { status, body: response['body'] } : null;
+}
+
+async function request<T = unknown>({
+ auth,
+ method,
+ path,
+ query,
+ body,
+ redactBody,
+ extraHeaders,
+}: {
+ auth: NetlifyAuthValue;
+ method: HttpMethod;
+ path: string;
+ query?: Record<string, QueryValue>;
+ body?: Record<string, unknown> | Record<string, unknown>[];
+ redactBody?: boolean;
+ extraHeaders?: Record<string, string>;
+}): Promise<{ status: number; body: T }> {
+ const hasBody = body !== undefined && method !== HttpMethod.GET && method !== HttpMethod.DELETE;
+ const headers: Record<string, string> = {
+ Accept: 'application/json',
+ ...withoutAuthHeaders(extraHeaders),
+ Authorization: `Bearer ${tokenOf(auth)}`,
+ };
+ if (hasBody) headers['Content-Type'] = 'application/json';
+ const dispatcher = await verifiedTls();
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${NETLIFY_API_BASE}${path}`,
+ headers,
+ queryParams: buildQuery(query),
+ body: hasBody ? body : undefined,
+ timeout: REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ redactBodyInErrors: redactBody === true,
+ }, { dispatcher });
+ if (response.status >= 300) {
+ throw new NetlifyApiError(`Netlify API error (${response.status}): unexpected redirect.`, response.status, undefined);
+ }
+ return { status: response.status, body: response.body };
+ } catch (error) {
+ const failure = failureOf(error);
+ if (!failure) throw error;
+ throw toApiError({ status: failure.status, body: failure.body, redact: redactBody === true });
+ }
+}
+
+function toApiError({ status, body, redact }: { status: number; body: unknown; redact: boolean }): NetlifyApiError {
+ return new NetlifyApiError(`Netlify API error (${status}): ${vendorMessage(body)}.${hintFor(status)}`.replace('..', '.'), status, redact ? undefined : body);
+}
+
+async function listAll<T = Record<string, unknown>>({
+ auth,
+ path,
+ query,
+}: {
+ auth: NetlifyAuthValue;
+ path: string;
+ query?: Record<string, QueryValue>;
+}): Promise<{ items: T[]; truncated: boolean }> {
+ const items: T[] = [];
+ for (let page = 1; page <= MAX_PAGES; page++) {
+ const response = await request<T[]>({ auth, method: HttpMethod.GET, path, query: { ...query, page, per_page: PAGE_SIZE } });
+ const batch = Array.isArray(response.body) ? response.body : [];
+ items.push(...batch);
+ if (batch.length < PAGE_SIZE) {
+ return { items, truncated: false };
+ }
+ }
+ return { items, truncated: true };
+}
+
+function pageSize({ value, label }: { value: unknown; label: string }): number | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const number = Number(value);
+ if (!Number.isInteger(number) || number < 1 || number > 100) {
+ throw new Error(`${label} must be a whole number from 1 to 100.`);
+ }
+ return number;
+}
+
+function pageNumber(value: unknown): number | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const number = Number(value);
+ if (!Number.isInteger(number) || number < 1) {
+ throw new Error('Page must be a whole number of 1 or more.');
+ }
+ return number;
+}
+
+export const netlifyClient = { request, listAll, segment, pageSize, pageNumber, isRecord, toApiError, apiPath };
diff --git a/packages/pieces/community/netlify/src/lib/common/operations.ts b/packages/pieces/community/netlify/src/lib/common/operations.ts
new file mode 100644
index 00000000000..471042aa6b6
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/common/operations.ts
@@ -0,0 +1,252 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { netlifyClient, NetlifyApiError, NetlifyAuthValue } from './client';
+
+const SITE_SECRET_KEYS = ['jwt_secret'];
+const SECRET_SCOPES = ['builds', 'functions', 'runtime'];
+const { request, segment, pageSize, pageNumber, isRecord } = netlifyClient;
+
+async function getSite({ auth, siteId }: { auth: NetlifyAuthValue; siteId: unknown }) {
+ const response = await request({ auth, method: HttpMethod.GET, path: `/sites/${segment({ value: siteId, label: 'Site' })}` });
+ return withoutSecrets(response.body);
+}
+
+async function listSites({ auth, name, page, perPage }: { auth: NetlifyAuthValue; name?: string; page?: unknown; perPage?: unknown }) {
+ const response = await request({
+ auth,
+ method: HttpMethod.GET,
+ path: '/sites',
+ query: { filter: 'all', name: name?.trim(), page: pageNumber(page), per_page: pageSize({ value: perPage, label: 'Per Page' }) },
+ });
+ return Array.isArray(response.body) ? response.body.map(withoutSecrets) : response.body;
+}
+
+async function listDeploys({ auth, siteId, page, perPage }: { auth: NetlifyAuthValue; siteId: unknown; page?: unknown; perPage?: unknown }) {
+ const response = await request({
+ auth,
+ method: HttpMethod.GET,
+ path: `/sites/${segment({ value: siteId, label: 'Site' })}/deploys`,
+ query: { page: pageNumber(page), per_page: pageSize({ value: perPage, label: 'Per Page' }) },
+ });
+ return response.body;
+}
+
+async function listFiles({ auth, siteId }: { auth: NetlifyAuthValue; siteId: unknown }) {
+ const response = await request({ auth, method: HttpMethod.GET, path: `/sites/${segment({ value: siteId, label: 'Site' })}/files` });
+ return response.body;
+}
+
+async function startBuild({ auth, siteId, clearCache }: { auth: NetlifyAuthValue; siteId: unknown; clearCache?: boolean }) {
+ const site = await getSite({ auth, siteId });
+ const id = isRecord(site) && typeof site['id'] === 'string' ? site['id'] : '';
+ try {
+ const response = await request({
+ auth,
+ method: HttpMethod.POST,
+ path: `/sites/${segment({ value: id, label: 'Site' })}/builds`,
+ query: { clear_cache: clearCache === true ? true : undefined },
+ });
+ return response.body;
+ } catch (error) {
+ if (error instanceof NetlifyApiError && error.status === 404) {
+ throw new Error('Netlify cannot build this site: it is not linked to a Git repository (sites deployed by drag and drop or the CLI cannot be rebuilt from Netlify). Link a repository in the site settings first.');
+ }
+ throw error;
+ }
+}
+
+async function getDeploy({ auth, deployId }: { auth: NetlifyAuthValue; deployId: unknown }) {
+ const response = await request({ auth, method: HttpMethod.GET, path: `/deploys/${segment({ value: deployId, label: 'Deploy ID' })}` });
+ return response.body;
+}
+
+async function cancelDeploy({ auth, deployId }: { auth: NetlifyAuthValue; deployId: unknown }) {
+ const response = await request({ auth, method: HttpMethod.POST, path: `/deploys/${segment({ value: deployId, label: 'Deploy ID' })}/cancel` });
+ return response.body;
+}
+
+async function restoreDeploy({ auth, deployId }: { auth: NetlifyAuthValue; deployId: unknown }) {
+ const deploy = await getDeploy({ auth, deployId });
+ const siteId = isRecord(deploy) ? deploy['site_id'] : undefined;
+ if (typeof siteId !== 'string' || siteId === '') {
+ throw new Error('Netlify did not return the site of this deploy.');
+ }
+ const response = await request({
+ auth,
+ method: HttpMethod.POST,
+ path: `/sites/${segment({ value: siteId, label: 'Site' })}/deploys/${segment({ value: deployId, label: 'Deploy ID' })}/restore`,
+ });
+ return response.body;
+}
+
+async function setDeployLock({ auth, deployId, locked }: { auth: NetlifyAuthValue; deployId: unknown; locked: boolean }) {
+ const response = await request({
+ auth,
+ method: HttpMethod.POST,
+ path: `/deploys/${segment({ value: deployId, label: 'Deploy ID' })}/${locked ? 'lock' : 'unlock'}`,
+ });
+ return response.body;
+}
+
+async function listForms({ auth, siteId }: { auth: NetlifyAuthValue; siteId: unknown }) {
+ const response = await request({ auth, method: HttpMethod.GET, path: `/sites/${segment({ value: siteId, label: 'Site' })}/forms` });
+ return response.body;
+}
+
+async function listSubmissions({ auth, formId, page, perPage }: { auth: NetlifyAuthValue; formId: unknown; page?: unknown; perPage?: unknown }) {
+ const response = await request({
+ auth,
+ method: HttpMethod.GET,
+ path: `/forms/${segment({ value: formId, label: 'Form ID' })}/submissions`,
+ query: { page: pageNumber(page), per_page: pageSize({ value: perPage, label: 'Per Page' }) },
+ });
+ return response.body;
+}
+
+async function listEnvVars({ auth, siteId, context, scope }: { auth: NetlifyAuthValue; siteId: unknown; context?: string; scope?: string }) {
+ const { accountId, site } = await siteAccount({ auth, siteId });
+ const response = await request({
+ auth,
+ method: HttpMethod.GET,
+ path: `/accounts/${segment({ value: accountId, label: 'Team' })}/env`,
+ query: { site_id: site, context_name: context, scope },
+ });
+ return response.body;
+}
+
+async function setEnvVar({
+ auth,
+ siteId,
+ key,
+ value,
+ context,
+ isSecret,
+}: {
+ auth: NetlifyAuthValue;
+ siteId: unknown;
+ key: unknown;
+ value: unknown;
+ context?: string;
+ isSecret?: boolean;
+}) {
+ const envKey = envKeyOf(key);
+ if (typeof value !== 'string') {
+ throw new Error('Value is required.');
+ }
+ const deployContext = context && context.trim() !== '' ? context.trim() : 'all';
+ if (isSecret === true && deployContext === 'all') {
+ throw new Error('Secret variables need a specific deploy context (e.g. production), not All contexts.');
+ }
+ const { accountId, site } = await siteAccount({ auth, siteId });
+ const account = segment({ value: accountId, label: 'Team' });
+ const keyPath = `/accounts/${account}/env/${segment({ value: envKey, label: 'Key' })}`;
+ const existing = await findEnvVar({ auth, keyPath, site });
+ if (existing === null) {
+ const created = await request({
+ auth,
+ method: HttpMethod.POST,
+ path: `/accounts/${account}/env`,
+ query: { site_id: site },
+ body: [{ key: envKey, is_secret: isSecret === true, ...(isSecret === true ? { scopes: SECRET_SCOPES } : {}), values: [{ context: deployContext, value }] }],
+ redactBody: true,
+ });
+ const first = Array.isArray(created.body) ? created.body[0] : created.body;
+ return summarizeEnvVar({ body: first, envKey, deployContext, created: true });
+ }
+ if (deployContext === 'all') {
+ const replaced = await request({
+ auth,
+ method: HttpMethod.PUT,
+ path: keyPath,
+ query: { site_id: site },
+ body: { key: envKey, scopes: Array.isArray(existing['scopes']) ? existing['scopes'] : undefined, is_secret: existing['is_secret'] === true, values: [{ context: 'all', value }] },
+ redactBody: true,
+ });
+ return summarizeEnvVar({ body: replaced.body, envKey, deployContext, created: false });
+ }
+ const updated = await request({
+ auth,
+ method: HttpMethod.PATCH,
+ path: keyPath,
+ query: { site_id: site },
+ body: { context: deployContext, value },
+ redactBody: true,
+ });
+ return summarizeEnvVar({ body: updated.body, envKey, deployContext, created: false });
+}
+
+async function deleteEnvVar({ auth, siteId, key }: { auth: NetlifyAuthValue; siteId: unknown; key: unknown }) {
+ const envKey = envKeyOf(key);
+ const { accountId, site } = await siteAccount({ auth, siteId });
+ const keyPath = `/accounts/${segment({ value: accountId, label: 'Team' })}/env/${segment({ value: envKey, label: 'Key' })}`;
+ const existing = await findEnvVar({ auth, keyPath, site });
+ if (existing === null) {
+ return { key: envKey, deleted: false, already_deleted: true };
+ }
+ await request({ auth, method: HttpMethod.DELETE, path: keyPath, query: { site_id: site } });
+ return { key: envKey, deleted: true, already_deleted: false };
+}
+
+async function findEnvVar({ auth, keyPath, site }: { auth: NetlifyAuthValue; keyPath: string; site: string }): Promise<Record<string, unknown> | null> {
+ try {
+ const response = await request({ auth, method: HttpMethod.GET, path: keyPath, query: { site_id: site }, redactBody: true });
+ return isRecord(response.body) ? response.body : {};
+ } catch (error) {
+ if (error instanceof NetlifyApiError && error.status === 404) {
+ return null;
+ }
+ throw error;
+ }
+}
+
+async function siteAccount({ auth, siteId }: { auth: NetlifyAuthValue; siteId: unknown }): Promise<{ accountId: string; site: string }> {
+ const site = await getSite({ auth, siteId });
+ const accountId = isRecord(site) ? site['account_id'] : undefined;
+ const id = isRecord(site) ? site['id'] : undefined;
+ if (typeof accountId !== 'string' || accountId === '' || typeof id !== 'string' || id === '') {
+ throw new Error('Netlify did not return the team of this site.');
+ }
+ return { accountId, site: id };
+}
+
+function withoutSecrets(site: unknown): unknown {
+ if (!isRecord(site)) return site;
+ return Object.fromEntries(Object.entries(site).filter(([key]) => !SITE_SECRET_KEYS.includes(key)));
+}
+
+function envKeyOf(key: unknown): string {
+ const text = typeof key === 'string' ? key.trim() : '';
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(text)) {
+ throw new Error('Key must start with a letter or underscore and contain only letters, digits and underscores, e.g. API_URL.');
+ }
+ return text;
+}
+
+function summarizeEnvVar({ body, envKey, deployContext, created }: { body: unknown; envKey: string; deployContext: string; created: boolean }) {
+ const record = isRecord(body) ? body : {};
+ const values = Array.isArray(record['values']) ? record['values'] : [];
+ return {
+ key: typeof record['key'] === 'string' ? record['key'] : envKey,
+ created,
+ context: deployContext,
+ scopes: Array.isArray(record['scopes']) ? record['scopes'] : [],
+ is_secret: record['is_secret'] === true,
+ contexts: values.map((item) => (isRecord(item) ? item['context'] : undefined)).filter((item): item is string => typeof item === 'string'),
+ };
+}
+
+export const netlifyOperations = {
+ getSite,
+ listSites,
+ listDeploys,
+ listFiles,
+ startBuild,
+ getDeploy,
+ cancelDeploy,
+ restoreDeploy,
+ setDeployLock,
+ listForms,
+ listSubmissions,
+ listEnvVars,
+ setEnvVar,
+ deleteEnvVar,
+};
diff --git a/packages/pieces/community/netlify/src/lib/common/output-schemas.ts b/packages/pieces/community/netlify/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..5f6878760b5
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/common/output-schemas.ts
@@ -0,0 +1,185 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+type Fields = OutputSchema['fields'];
+
+const deployFields: Fields = [
+ { key: 'id', label: 'Deploy ID' },
+ { key: 'site_id', label: 'Site ID' },
+ { key: 'build_id', label: 'Build ID' },
+ { key: 'state', label: 'State', description: 'e.g. new, enqueued, building, uploading, processing, ready, error, cancelled.' },
+ { key: 'name', label: 'Site Name' },
+ { key: 'title', label: 'Title' },
+ { key: 'context', label: 'Context', description: 'production, deploy-preview or branch-deploy.' },
+ { key: 'branch', label: 'Branch' },
+ { key: 'commit_ref', label: 'Commit' },
+ { key: 'commit_url', label: 'Commit URL', format: 'url' },
+ { key: 'commit_message', label: 'Commit Message' },
+ { key: 'error_message', label: 'Error Message' },
+ { key: 'url', label: 'Site URL', format: 'url' },
+ { key: 'ssl_url', label: 'Site HTTPS URL', format: 'url' },
+ { key: 'deploy_url', label: 'Deploy URL', format: 'url' },
+ { key: 'deploy_ssl_url', label: 'Deploy HTTPS URL', format: 'url' },
+ { key: 'admin_url', label: 'Admin URL', format: 'url' },
+ { key: 'screenshot_url', label: 'Screenshot', format: 'image' },
+ { key: 'review_id', label: 'Pull Request Number', format: 'number' },
+ { key: 'review_url', label: 'Pull Request URL', format: 'url' },
+ { key: 'framework', label: 'Framework' },
+ { key: 'locked', label: 'Locked', format: 'boolean' },
+ { key: 'skipped', label: 'Skipped', format: 'boolean' },
+ { key: 'manual_deploy', label: 'Manual Deploy', format: 'boolean' },
+ { key: 'deploy_source', label: 'Source', description: 'e.g. api, drop or the Git provider.' },
+ { key: 'deploy_time', label: 'Build Time (Seconds)', format: 'number' },
+ { key: 'user_id', label: 'User ID' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'published_at', label: 'Published At', format: 'datetime' },
+];
+
+const siteFields: Fields = [
+ { key: 'id', label: 'Site ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'state', label: 'State' },
+ { key: 'plan', label: 'Plan' },
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'ssl_url', label: 'HTTPS URL', format: 'url' },
+ { key: 'admin_url', label: 'Admin URL', format: 'url' },
+ { key: 'custom_domain', label: 'Custom Domain' },
+ { key: 'domain_aliases', label: 'Domain Aliases' },
+ { key: 'screenshot_url', label: 'Screenshot', format: 'image' },
+ { key: 'account_id', label: 'Team ID' },
+ { key: 'account_name', label: 'Team Name' },
+ { key: 'account_slug', label: 'Team Slug' },
+ { key: 'git_provider', label: 'Git Provider' },
+ { key: 'force_ssl', label: 'Force HTTPS', format: 'boolean' },
+ { key: 'managed_dns', label: 'Netlify DNS', format: 'boolean' },
+ {
+ key: 'build_settings',
+ label: 'Build Settings',
+ children: [
+ { key: 'repo_url', label: 'Repository URL', format: 'url' },
+ { key: 'repo_branch', label: 'Production Branch' },
+ { key: 'cmd', label: 'Build Command' },
+ { key: 'dir', label: 'Publish Directory' },
+ { key: 'base', label: 'Base Directory' },
+ { key: 'stop_builds', label: 'Builds Stopped', format: 'boolean' },
+ ],
+ },
+ {
+ key: 'published_deploy',
+ label: 'Published Deploy',
+ children: [
+ { key: 'id', label: 'Deploy ID' },
+ { key: 'state', label: 'State' },
+ { key: 'branch', label: 'Branch' },
+ { key: 'commit_ref', label: 'Commit' },
+ { key: 'published_at', label: 'Published At', format: 'datetime' },
+ ],
+ },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+const submissionFields: Fields = [
+ { key: 'id', label: 'Submission ID' },
+ { key: 'number', label: 'Number', format: 'number' },
+ { key: 'form_id', label: 'Form ID' },
+ { key: 'form_name', label: 'Form Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'name', label: 'Name' },
+ { key: 'first_name', label: 'First Name' },
+ { key: 'last_name', label: 'Last Name' },
+ { key: 'company', label: 'Company' },
+ { key: 'summary', label: 'Summary' },
+ { key: 'body', label: 'Message' },
+ { key: 'title', label: 'Title' },
+ { key: 'data', label: 'Submitted Fields', description: 'Every field by its name, plus ip, user_agent and referrer.', dynamicKey: true },
+ { key: 'human_fields', label: 'Fields by Label', dynamicKey: true },
+ { key: 'site_name', label: 'Site Name' },
+ { key: 'site_url', label: 'Site URL', format: 'url' },
+ { key: 'created_at', label: 'Submitted At', format: 'datetime' },
+];
+
+const envVarFields: Fields = [
+ { key: 'key', label: 'Key' },
+ { key: 'scopes', label: 'Scopes' },
+ { key: 'is_secret', label: 'Secret', format: 'boolean' },
+ {
+ key: 'values',
+ label: 'Values',
+ listItems: [
+ { key: 'id', label: 'Value ID' },
+ { key: 'context', label: 'Deploy Context' },
+ { key: 'context_parameter', label: 'Branch' },
+ { key: 'value', label: 'Value', description: 'Masked for secret variables.' },
+ ],
+ labelKey: 'context',
+ },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'updated_by', label: 'Updated By', children: [{ key: 'full_name', label: 'Name' }, { key: 'email', label: 'Email', format: 'email' }] },
+];
+
+function list({ label, item, itemLabel }: { label: string; item: Fields; itemLabel: string }): OutputSchema {
+ return { fields: [{ key: 'items', value: '', label, listItems: item }], itemLabel };
+}
+
+export const netlifySchemas = {
+ site: { fields: siteFields } satisfies OutputSchema,
+ siteList: list({ label: 'Sites', item: siteFields, itemLabel: '{name}' }),
+ deploy: { fields: deployFields } satisfies OutputSchema,
+ deployList: list({ label: 'Deploys', item: deployFields, itemLabel: '{state} {created_at}' }),
+ build: {
+ fields: [
+ { key: 'id', label: 'Build ID' },
+ { key: 'deploy_id', label: 'Deploy ID', description: 'Pass it to Get Deploy to follow the build.' },
+ { key: 'sha', label: 'Commit' },
+ { key: 'done', label: 'Done', format: 'boolean' },
+ { key: 'error', label: 'Error' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ ],
+ } satisfies OutputSchema,
+ fileList: list({
+ label: 'Files',
+ item: [
+ { key: 'id', label: 'File ID' },
+ { key: 'path', label: 'Path' },
+ { key: 'mime_type', label: 'MIME Type' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'sha', label: 'SHA-1' },
+ { key: 'deploy_id', label: 'Deploy ID' },
+ ],
+ itemLabel: '{path}',
+ }),
+ formList: list({
+ label: 'Forms',
+ item: [
+ { key: 'id', label: 'Form ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'site_id', label: 'Site ID' },
+ { key: 'submission_count', label: 'Submissions', format: 'number' },
+ { key: 'paths', label: 'Pages' },
+ { key: 'fields', label: 'Fields', listItems: [{ key: 'name', label: 'Name' }, { key: 'type', label: 'Type' }], labelKey: 'name' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ ],
+ itemLabel: '{name}',
+ }),
+ submission: { fields: submissionFields } satisfies OutputSchema,
+ submissionList: list({ label: 'Submissions', item: submissionFields, itemLabel: '#{number} {email}' }),
+ envVarList: list({ label: 'Environment Variables', item: envVarFields, itemLabel: '{key}' }),
+ envVarWrite: {
+ fields: [
+ { key: 'key', label: 'Key' },
+ { key: 'created', label: 'Created', format: 'boolean', description: 'true when the variable did not exist before.' },
+ { key: 'context', label: 'Deploy Context' },
+ { key: 'scopes', label: 'Scopes' },
+ { key: 'is_secret', label: 'Secret', format: 'boolean' },
+ { key: 'contexts', label: 'Contexts With a Value' },
+ ],
+ } satisfies OutputSchema,
+ envVarDelete: {
+ fields: [
+ { key: 'key', label: 'Key' },
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'already_deleted', label: 'Already Absent', format: 'boolean' },
+ ],
+ } satisfies OutputSchema,
+};
diff --git a/packages/pieces/community/netlify/src/lib/common/props.ts b/packages/pieces/community/netlify/src/lib/common/props.ts
new file mode 100644
index 00000000000..a2892641c26
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/common/props.ts
@@ -0,0 +1,115 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { DropdownState, Property } from '@activepieces/pieces-framework';
+import { netlifyAuth } from './auth';
+import { netlifyClient, NetlifyAuthValue } from './client';
+
+type Choice = { label: string; value: string };
+
+async function dropdown({ auth, load }: { auth: unknown; load: (auth: NetlifyAuthValue) => Promise<{ options: Choice[]; truncated: boolean }> }): Promise<DropdownState<string>> {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Connect your Netlify account first' };
+ }
+ try {
+ const { options, truncated } = await load(auth);
+ return {
+ disabled: false,
+ options,
+ placeholder: options.length === 0 ? 'Nothing found in this account' : truncated ? `Showing the first ${options.length}` : 'Select one',
+ };
+ } catch (error) {
+ return { disabled: true, options: [], placeholder: `Could not load the list: ${error instanceof Error ? error.message : 'unknown error'}` };
+ }
+}
+
+function text(value: unknown): string {
+ return typeof value === 'string' ? value : '';
+}
+
+async function loadSites(auth: NetlifyAuthValue): Promise<{ options: Choice[]; truncated: boolean }> {
+ const { items, truncated } = await netlifyClient.listAll({ auth, path: '/sites', query: { filter: 'all' } });
+ return {
+ truncated,
+ options: items
+ .filter((site) => typeof site['id'] === 'string')
+ .map((site) => ({ label: `${text(site['name']) || text(site['id'])} (${text(site['ssl_url']) || text(site['url'])})`, value: text(site['id']) })),
+ };
+}
+
+function siteDropdown({ description }: { description: string }) {
+ return Property.Dropdown({
+ auth: netlifyAuth,
+ displayName: 'Site',
+ description,
+ required: true,
+ refreshers: ['auth'],
+ options: async ({ auth }) => dropdown({ auth, load: loadSites }),
+ });
+}
+
+function siteId() {
+ return Property.ShortText({
+ displayName: 'Site ID',
+ description: 'The Netlify site ID (API ID, a UUID) or the site domain such as my-site.netlify.app. Use List Sites to find it.',
+ required: true,
+ });
+}
+
+function formDropdown() {
+ return Property.Dropdown({
+ auth: netlifyAuth,
+ displayName: 'Form',
+ description: 'The form whose submissions to list.',
+ required: true,
+ refreshers: ['auth', 'siteId'],
+ options: async ({ auth, siteId }) => {
+ if (!siteId) {
+ return { disabled: true, options: [], placeholder: 'Select a site first' };
+ }
+ return dropdown({
+ auth,
+ load: async (connection) => {
+ const response = await netlifyClient.request<Record<string, unknown>[]>({
+ auth: connection,
+ method: HttpMethod.GET,
+ path: `/sites/${netlifyClient.segment({ value: siteId, label: 'Site' })}/forms`,
+ });
+ const forms = Array.isArray(response.body) ? response.body : [];
+ return {
+ truncated: false,
+ options: forms
+ .filter((form) => typeof form['id'] === 'string')
+ .map((form) => ({ label: `${text(form['name']) || text(form['id'])} (${String(form['submission_count'] ?? 0)} submissions)`, value: text(form['id']) })),
+ };
+ },
+ });
+ },
+ });
+}
+
+function deployId({ description }: { description?: string } = {}) {
+ return Property.ShortText({
+ displayName: 'Deploy ID',
+ description: description ?? 'The Netlify deploy ID, e.g. 6512f0c1a2b3c40008d9e123 (from List Site Deploys or a deploy trigger).',
+ required: true,
+ });
+}
+
+function page() {
+ return Property.Number({
+ displayName: 'Page',
+ description: 'Page number, starting at 1.',
+ required: false,
+ defaultValue: 1,
+ });
+}
+
+function perPage({ defaultValue }: { defaultValue?: number } = {}) {
+ return Property.Number({
+ displayName: 'Per Page',
+ description: 'Items per page, 1-100.',
+ required: false,
+ defaultValue,
+ });
+}
+
+export const netlifyProps = { siteDropdown, siteId, formDropdown, deployId, page, perPage };
diff --git a/packages/pieces/community/netlify/src/lib/common/webhook.ts b/packages/pieces/community/netlify/src/lib/common/webhook.ts
new file mode 100644
index 00000000000..a56e1e5091d
--- /dev/null
+++ b/packages/pieces/community/netlify/src/lib/common/webhook.ts
@@ -0,0 +1,190 @@
+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'crypto';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { DEDUPE_KEY_PROPERTY } from '@activepieces/pieces-framework';
+import { netlifyClient, NetlifyApiError, NetlifyAuthValue } from './client';
+
+const STORE_KEY = 'webhook_id';
+const SECRET_KEY = 'webhook_signature_secret';
+const SLOT_KEY_PREFIX = 'netlify_seen_events_';
+const SLOT_COUNT = 64;
+const MAX_PER_SLOT = 100;
+const DEDUPE_WINDOW_MS = 15 * 60 * 1000;
+
+async function enable({
+ auth,
+ siteId,
+ event,
+ webhookUrl,
+ store,
+}: {
+ auth: NetlifyAuthValue;
+ siteId: unknown;
+ event: string;
+ webhookUrl: string;
+ store: WebhookStore;
+}): Promise<void> {
+ const site = typeof siteId === 'string' ? siteId.trim() : '';
+ if (site === '') {
+ throw new Error('Site is required.');
+ }
+ const secret = randomBytes(32).toString('hex');
+ const response = await netlifyClient.request({
+ auth,
+ method: HttpMethod.POST,
+ path: '/hooks',
+ query: { site_id: site },
+ body: { site_id: site, type: 'url', event, data: { url: webhookUrl, signature_secret: secret } },
+ redactBody: true,
+ });
+ const hookId = netlifyClient.isRecord(response.body) ? response.body['id'] : undefined;
+ if (typeof hookId !== 'string' || hookId === '') {
+ throw new Error('Netlify did not return the ID of the created webhook.');
+ }
+ try {
+ await store.put(SECRET_KEY, secret);
+ await store.put(STORE_KEY, hookId);
+ } catch (error) {
+ await deleteHook({ auth, hookId }).catch(() => undefined);
+ throw error;
+ }
+}
+
+async function disable({ auth, store }: { auth: NetlifyAuthValue; store: WebhookStore }): Promise<void> {
+ const hookId = await store.get<string>(STORE_KEY);
+ if (typeof hookId === 'string' && hookId !== '') {
+ await deleteHook({ auth, hookId });
+ }
+ await store.delete(STORE_KEY);
+ await store.delete(SECRET_KEY);
+ await Promise.all(Array.from({ length: SLOT_COUNT }, (_, slot) => store.delete(`${SLOT_KEY_PREFIX}${slot}`)));
+}
+
+async function receive({ payload, store, now = Date.now() }: { payload: WebhookPayload; store: WebhookStore; now?: number }): Promise<unknown[]> {
+ const secret = await store.get<string>(SECRET_KEY);
+ if (typeof secret === 'string' && secret !== '') {
+ const signature = headerValue({ headers: payload.headers, name: 'x-webhook-signature' });
+ if (!verifySignature({ token: signature, secret, rawBody: rawBodyOf(payload) })) {
+ return [];
+ }
+ }
+ const eventId = eventIdOf(payload.body);
+ if (eventId === null) {
+ return [payload.body];
+ }
+ const claimed = await claimEvent({ store, eventId, now });
+ if (!claimed) {
+ return [];
+ }
+ return [withDedupeKey({ body: payload.body, eventId })];
+}
+
+async function claimEvent({ store, eventId, now }: { store: WebhookStore; eventId: string; now: number }): Promise<boolean> {
+ const key = slotKey(eventId);
+ const before = await readSlot({ store, key, now });
+ if (before.some((entry) => entry.id === eventId)) {
+ return false;
+ }
+ const mine: SeenEvent = { id: eventId, at: now, token: randomBytes(16).toString('hex') };
+ await store.put(key, [...before.slice(-(MAX_PER_SLOT - 1)), mine]);
+ const after = await readSlot({ store, key, now });
+ const winner = after.find((entry) => entry.id === eventId);
+ if (winner !== undefined) {
+ return winner.token === mine.token;
+ }
+ await store.put(key, [...after.slice(-(MAX_PER_SLOT - 1)), mine]);
+ return true;
+}
+
+async function readSlot({ store, key, now }: { store: WebhookStore; key: string; now: number }): Promise<SeenEvent[]> {
+ const stored = await store.get<unknown>(key);
+ return (Array.isArray(stored) ? stored : []).filter(
+ (entry): entry is SeenEvent =>
+ netlifyClient.isRecord(entry) &&
+ typeof entry['id'] === 'string' &&
+ typeof entry['token'] === 'string' &&
+ typeof entry['at'] === 'number' &&
+ now - entry['at'] < DEDUPE_WINDOW_MS,
+ );
+}
+
+function slotKey(eventId: string): string {
+ return `${SLOT_KEY_PREFIX}${createHash('sha256').update(eventId).digest().readUInt32BE(0) % SLOT_COUNT}`;
+}
+
+function withDedupeKey({ body, eventId }: { body: unknown; eventId: string }): unknown {
+ if (!netlifyClient.isRecord(body)) return body;
+ return { ...body, [DEDUPE_KEY_PROPERTY]: `netlify:${eventId}` };
+}
+
+function verifySignature({ token, secret, rawBody }: { token: string | undefined; secret: string; rawBody: string | null }): boolean {
+ if (!token || rawBody === null) return false;
+ const parts = token.split('.');
+ if (parts.length !== 3) return false;
+ const [header, claims, signature] = parts;
+ const expected = createHmac('sha256', secret).update(`${header}.${claims}`).digest();
+ const given = Buffer.from(signature, 'base64url');
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return false;
+ const decodedHeader = decodeJson(header);
+ const decodedClaims = decodeJson(claims);
+ if (!netlifyClient.isRecord(decodedHeader) || decodedHeader['alg'] !== 'HS256') return false;
+ if (!netlifyClient.isRecord(decodedClaims) || decodedClaims['iss'] !== 'netlify') return false;
+ const bodyHash = createHash('sha256').update(rawBody).digest('hex');
+ return typeof decodedClaims['sha256'] === 'string' && decodedClaims['sha256'] === bodyHash;
+}
+
+function decodeJson(segment: string): unknown {
+ try {
+ return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
+ } catch {
+ return null;
+ }
+}
+
+function rawBodyOf(payload: WebhookPayload): string | null {
+ const raw = payload.rawBody;
+ if (typeof raw === 'string') return raw;
+ if (Buffer.isBuffer(raw)) return raw.toString('utf8');
+ if (raw instanceof Uint8Array) return Buffer.from(raw).toString('utf8');
+ return null;
+}
+
+function headerValue({ headers, name }: { headers: unknown; name: string }): string | undefined {
+ if (!netlifyClient.isRecord(headers)) return undefined;
+ const match = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
+ const value = match?.[1];
+ if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : undefined;
+ return typeof value === 'string' ? value : undefined;
+}
+
+function eventIdOf(body: unknown): string | null {
+ if (!netlifyClient.isRecord(body) || typeof body['id'] !== 'string' || body['id'] === '') return null;
+ const state = typeof body['state'] === 'string' ? `:${body['state']}` : '';
+ return `${body['id']}${state}`;
+}
+
+async function deleteHook({ auth, hookId }: { auth: NetlifyAuthValue; hookId: string }): Promise<void> {
+ try {
+ await netlifyClient.request({ auth, method: HttpMethod.DELETE, path: `/hooks/${netlifyClient.segment({ value: hookId, label: 'Webhook ID' })}` });
+ } catch (error) {
+ if (error instanceof NetlifyApiError && error.status === 404) {
+ return;
+ }
+ throw error;
+ }
+}
+
+export const netlifyWebhook = { enable, disable, receive, verifySignature };
+
+type WebhookStore = {
+ put: (key: string, value: unknown) => Promise<unknown>;
+ get: <T>(key: string) => Promise<T | null>;
+ delete: (key: string) => Promise<void>;
+};
+
+type SeenEvent = { id: string; at: number; token: string };
+
+type WebhookPayload = {
+ body: unknown;
+ headers?: unknown;
+ rawBody?: unknown;
+};
diff --git a/packages/pieces/community/netlify/src/lib/triggers/new-deploy-failed.ts b/packages/pieces/community/netlify/src/lib/triggers/new-deploy-failed.ts
index b7da4f1afdc..f5fa1cfd03e 100644
--- a/packages/pieces/community/netlify/src/lib/triggers/new-deploy-failed.ts
+++ b/packages/pieces/community/netlify/src/lib/triggers/new-deploy-failed.ts
@@ -1,76 +1,22 @@
-import { createTrigger, Property, TriggerStrategy, OAuth2PropertyValue } from "@activepieces/pieces-framework";
-import { httpClient, HttpMethod } from "@activepieces/pieces-common";
-import { netlifyAuth } from "../common/auth";
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+import { netlifyWebhook } from '../common/webhook';
export const newDeployFailed = createTrigger({
- name: "new_deploy_failed",
+ auth: netlifyAuth,
+ name: 'new_deploy_failed',
classification: 'READ',
- displayName: "New Deploy Failed",
- description: "Fires when a site deploy fails.",
+ displayName: 'New Deploy Failed',
+ description: 'Fires when a deploy fails on your Netlify site.',
aiMetadata: {
description: 'Fires when a deploy on the selected Netlify site fails to build or publish (the deploy_failed event); the payload includes the error message. Use it to alert on or remediate broken deploys.',
},
- auth: netlifyAuth,
props: {
- siteId: Property.Dropdown({
- auth: netlifyAuth, displayName: "Site",
- description: "Select the site to monitor for failed deploy events",
- required: true,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: "Connect your account first",
- options: [],
- };
- }
-
- const authentication = auth as OAuth2PropertyValue;
- if (!authentication.access_token) {
- return {
- disabled: true,
- placeholder: "Access token is required",
- options: [],
- };
- }
-
- try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: "https://api.netlify.com/api/v1/sites?per_page=50",
- headers: {
- "Authorization": `Bearer ${authentication.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- const sites = response.body as any[];
- return {
- disabled: false,
- options: sites.map((site) => ({
- label: `${site.name} (${site.url})`,
- value: site.id,
- })),
- };
- } else {
- return {
- disabled: true,
- placeholder: `Failed to fetch sites: ${response.status}`,
- options: [],
- };
- }
- } catch (error) {
- return {
- disabled: true,
- placeholder: "Failed to fetch sites",
- options: [],
- };
- }
- },
- }),
+ siteId: netlifyProps.siteDropdown({ description: 'Select the site to watch for deploys.' }),
},
+ outputSchema: netlifySchemas.deploy,
sampleData: {
id: "507f1f77bcf86cd799439011",
site_id: "b6fda79c-0cb0-44ca-8e73-3f5f2c0f0e2d",
@@ -93,61 +39,13 @@ export const newDeployFailed = createTrigger({
locked: false
},
type: TriggerStrategy.WEBHOOK,
- onEnable: async (context) => {
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: "https://api.netlify.com/api/v1/hooks",
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- "Content-Type": "application/json",
- },
- body: {
- site_id: context.propsValue.siteId,
- type: "url",
- event: "deploy_failed",
- data: {
- url: context.webhookUrl,
- },
- },
- });
-
- if (response.status === 201) {
- await context.store.put("webhook_id", response.body.id);
- } else {
- throw new Error(`Failed to create webhook: ${response.status}`);
- }
+ async onEnable(context) {
+ await netlifyWebhook.enable({ auth: context.auth, siteId: context.propsValue.siteId, event: 'deploy_failed', webhookUrl: context.webhookUrl, store: context.store });
},
- onDisable: async (context) => {
- const webhookId = await context.store.get("webhook_id");
- if (webhookId) {
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- await httpClient.sendRequest({
- method: HttpMethod.DELETE,
- url: `https://api.netlify.com/api/v1/hooks/${webhookId}`,
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- },
- });
- }
+ async onDisable(context) {
+ await netlifyWebhook.disable({ auth: context.auth, store: context.store });
},
- run: async (context) => {
- return [context.payload.body];
+ async run(context) {
+ return netlifyWebhook.receive({ payload: context.payload, store: context.store });
},
});
diff --git a/packages/pieces/community/netlify/src/lib/triggers/new-deploy-started.ts b/packages/pieces/community/netlify/src/lib/triggers/new-deploy-started.ts
index 631df4ba689..d6510d0f0c2 100644
--- a/packages/pieces/community/netlify/src/lib/triggers/new-deploy-started.ts
+++ b/packages/pieces/community/netlify/src/lib/triggers/new-deploy-started.ts
@@ -1,76 +1,22 @@
-import { createTrigger, Property, TriggerStrategy, OAuth2PropertyValue } from "@activepieces/pieces-framework";
-import { httpClient, HttpMethod } from "@activepieces/pieces-common";
-import { netlifyAuth } from "../common/auth";
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+import { netlifyWebhook } from '../common/webhook';
export const newDeployStarted = createTrigger({
- name: "new_deploy_started",
+ auth: netlifyAuth,
+ name: 'new_deploy_started',
classification: 'READ',
- displayName: "New Deploy Started",
- description: "Fires immediately when a deploy job starts on your Netlify site.",
+ displayName: 'New Deploy Started',
+ description: 'Fires when a deploy starts building on your Netlify site.',
aiMetadata: {
- description: 'Fires when a new deploy job begins building on the selected Netlify site (the deploy_created event), before it finishes. Use it to react the moment a build kicks off, e.g. to notify or track in-progress deploys.',
+ description: 'Fires when a deploy on the selected Netlify site starts building (the Deploy started notification, event deploy_building), before it finishes. Use it to react the moment a build kicks off, e.g. to notify or track in-progress deploys.',
},
- auth: netlifyAuth,
props: {
- siteId: Property.Dropdown({
- auth: netlifyAuth, displayName: "Site",
- description: "Select the site to monitor for deploy events",
- required: true,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: "Connect your account first",
- options: [],
- };
- }
-
- const authentication = auth as OAuth2PropertyValue;
- if (!authentication.access_token) {
- return {
- disabled: true,
- placeholder: "Access token is required",
- options: [],
- };
- }
-
- try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: "https://api.netlify.com/api/v1/sites?per_page=50",
- headers: {
- "Authorization": `Bearer ${authentication.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- const sites = response.body as any[];
- return {
- disabled: false,
- options: sites.map((site) => ({
- label: `${site.name} (${site.url})`,
- value: site.id,
- })),
- };
- } else {
- return {
- disabled: true,
- placeholder: `Failed to fetch sites: ${response.status}`,
- options: [],
- };
- }
- } catch (error) {
- return {
- disabled: true,
- placeholder: "Failed to fetch sites",
- options: [],
- };
- }
- },
- }),
+ siteId: netlifyProps.siteDropdown({ description: 'Select the site to watch for deploys.' }),
},
+ outputSchema: netlifySchemas.deploy,
sampleData: {
id: "507f1f77bcf86cd799439013",
site_id: "b6fda79c-0cb0-44ca-8e73-3f5f2c0f0e2d",
@@ -94,61 +40,13 @@ export const newDeployStarted = createTrigger({
framework: "react"
},
type: TriggerStrategy.WEBHOOK,
- onEnable: async (context) => {
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: "https://api.netlify.com/api/v1/hooks",
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- "Content-Type": "application/json",
- },
- body: {
- site_id: context.propsValue.siteId,
- type: "url",
- event: "deploy_created",
- data: {
- url: context.webhookUrl,
- },
- },
- });
-
- if (response.status === 201) {
- await context.store.put("webhook_id", response.body.id);
- } else {
- throw new Error(`Failed to create webhook: ${response.status}`);
- }
+ async onEnable(context) {
+ await netlifyWebhook.enable({ auth: context.auth, siteId: context.propsValue.siteId, event: 'deploy_building', webhookUrl: context.webhookUrl, store: context.store });
},
- onDisable: async (context) => {
- const webhookId = await context.store.get("webhook_id");
- if (webhookId) {
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- await httpClient.sendRequest({
- method: HttpMethod.DELETE,
- url: `https://api.netlify.com/api/v1/hooks/${webhookId}`,
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- },
- });
- }
+ async onDisable(context) {
+ await netlifyWebhook.disable({ auth: context.auth, store: context.store });
},
- run: async (context) => {
- return [context.payload.body];
+ async run(context) {
+ return netlifyWebhook.receive({ payload: context.payload, store: context.store });
},
});
diff --git a/packages/pieces/community/netlify/src/lib/triggers/new-deploy-succeeded.ts b/packages/pieces/community/netlify/src/lib/triggers/new-deploy-succeeded.ts
index 2c5aa93e658..f9c34f434f8 100644
--- a/packages/pieces/community/netlify/src/lib/triggers/new-deploy-succeeded.ts
+++ b/packages/pieces/community/netlify/src/lib/triggers/new-deploy-succeeded.ts
@@ -1,76 +1,22 @@
-import { createTrigger, Property, TriggerStrategy, OAuth2PropertyValue } from "@activepieces/pieces-framework";
-import { httpClient, HttpMethod } from "@activepieces/pieces-common";
-import { netlifyAuth } from "../common/auth";
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+import { netlifyWebhook } from '../common/webhook';
export const newDeploySucceeded = createTrigger({
- name: "new_deploy_succeeded",
+ auth: netlifyAuth,
+ name: 'new_deploy_succeeded',
classification: 'READ',
- displayName: "New Deploy Succeeded",
- description: "Fires when a new site version has successfully deployed.",
+ displayName: 'New Deploy Succeeded',
+ description: 'Fires when a new site version has successfully deployed.',
aiMetadata: {
- description: 'Fires when a deploy on the selected Netlify site finishes successfully and the new version goes live (the deploy_succeeded event). Use it to run follow-up steps after a site is published, e.g. cache purges, notifications, or downstream syncs.',
+ description: 'Fires when a deploy on the selected Netlify site finishes successfully (the Deploy succeeded notification, event deploy_created). Use it to run follow-up steps after a site is published, e.g. cache purges, notifications or downstream syncs.',
},
- auth: netlifyAuth,
props: {
- siteId: Property.Dropdown({
- auth: netlifyAuth, displayName: "Site",
- description: "Select the site to monitor for successful deploy events",
- required: true,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: "Connect your account first",
- options: [],
- };
- }
-
- const authentication = auth as OAuth2PropertyValue;
- if (!authentication.access_token) {
- return {
- disabled: true,
- placeholder: "Access token is required",
- options: [],
- };
- }
-
- try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: "https://api.netlify.com/api/v1/sites?per_page=50",
- headers: {
- "Authorization": `Bearer ${authentication.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- const sites = response.body as any[];
- return {
- disabled: false,
- options: sites.map((site) => ({
- label: `${site.name} (${site.url})`,
- value: site.id,
- })),
- };
- } else {
- return {
- disabled: true,
- placeholder: `Failed to fetch sites: ${response.status}`,
- options: [],
- };
- }
- } catch (error) {
- return {
- disabled: true,
- placeholder: "Failed to fetch sites",
- options: [],
- };
- }
- },
- }),
+ siteId: netlifyProps.siteDropdown({ description: 'Select the site to watch for deploys.' }),
},
+ outputSchema: netlifySchemas.deploy,
sampleData: {
id: "507f1f77bcf86cd799439014",
site_id: "b6fda79c-0cb0-44ca-8e73-3f5f2c0f0e2d",
@@ -96,61 +42,13 @@ export const newDeploySucceeded = createTrigger({
function_schedules: []
},
type: TriggerStrategy.WEBHOOK,
- onEnable: async (context) => {
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: "https://api.netlify.com/api/v1/hooks",
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- "Content-Type": "application/json",
- },
- body: {
- site_id: context.propsValue.siteId,
- type: "url",
- event: "deploy_succeeded",
- data: {
- url: context.webhookUrl,
- },
- },
- });
-
- if (response.status === 201) {
- await context.store.put("webhook_id", response.body.id);
- } else {
- throw new Error(`Failed to create webhook: ${response.status}`);
- }
+ async onEnable(context) {
+ await netlifyWebhook.enable({ auth: context.auth, siteId: context.propsValue.siteId, event: 'deploy_created', webhookUrl: context.webhookUrl, store: context.store });
},
- onDisable: async (context) => {
- const webhookId = await context.store.get("webhook_id");
- if (webhookId) {
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- await httpClient.sendRequest({
- method: HttpMethod.DELETE,
- url: `https://api.netlify.com/api/v1/hooks/${webhookId}`,
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- },
- });
- }
+ async onDisable(context) {
+ await netlifyWebhook.disable({ auth: context.auth, store: context.store });
},
- run: async (context) => {
- return [context.payload.body];
+ async run(context) {
+ return netlifyWebhook.receive({ payload: context.payload, store: context.store });
},
});
diff --git a/packages/pieces/community/netlify/src/lib/triggers/new-form-submission.ts b/packages/pieces/community/netlify/src/lib/triggers/new-form-submission.ts
index d8d6861eb95..d6c86ef9040 100644
--- a/packages/pieces/community/netlify/src/lib/triggers/new-form-submission.ts
+++ b/packages/pieces/community/netlify/src/lib/triggers/new-form-submission.ts
@@ -1,156 +1,65 @@
-import { createTrigger, Property, TriggerStrategy, OAuth2PropertyValue } from "@activepieces/pieces-framework";
-import { httpClient, HttpMethod } from "@activepieces/pieces-common";
-import { netlifyAuth } from "../common/auth";
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { netlifyAuth } from '../common/auth';
+import { netlifySchemas } from '../common/output-schemas';
+import { netlifyProps } from '../common/props';
+import { netlifyWebhook } from '../common/webhook';
export const newFormSubmission = createTrigger({
- name: "new_form_submission",
+ auth: netlifyAuth,
+ name: 'new_form_submission',
classification: 'READ',
- displayName: "New Form Submission",
- description: "Fires when a Netlify form submission is received.",
+ displayName: 'New Form Submission',
+ description: 'Fires when a Netlify form submission is received.',
aiMetadata: {
description: 'Fires when a new form submission is received on the selected Netlify site (the submission_created event); the payload includes the submitted field data and submitter metadata. Use it to process or route contact/lead form entries.',
},
- auth: netlifyAuth,
props: {
- siteId: Property.Dropdown({
- auth: netlifyAuth, displayName: "Site",
- description: "Select the site to monitor for form submissions",
- required: true,
- refreshers: ['auth'],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: "Connect your account first",
- options: [],
- };
- }
-
- const authentication = auth as OAuth2PropertyValue;
- if (!authentication.access_token) {
- return {
- disabled: true,
- placeholder: "Access token is required",
- options: [],
- };
- }
-
- try {
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: "https://api.netlify.com/api/v1/sites?per_page=50",
- headers: {
- "Authorization": `Bearer ${authentication.access_token}`,
- "Content-Type": "application/json",
- },
- });
-
- if (response.status === 200) {
- const sites = response.body as any[];
- return {
- disabled: false,
- options: sites.map((site) => ({
- label: `${site.name} (${site.url})`,
- value: site.id,
- })),
- };
- } else {
- return {
- disabled: true,
- placeholder: `Failed to fetch sites: ${response.status}`,
- options: [],
- };
- }
- } catch (error) {
- return {
- disabled: true,
- placeholder: "Failed to fetch sites",
- options: [],
- };
- }
- },
- }),
+ siteId: netlifyProps.siteDropdown({ description: 'Select the site to watch for form submissions.' }),
},
+ outputSchema: netlifySchemas.submission,
sampleData: {
- id: "507f1f77bcf86cd799439015",
- number: 42,
- email: "[email protected]",
- name: "John Doe",
- first_name: "John",
- last_name: "Doe",
- company: "Acme Corp",
- summary: "Contact form submission from website",
- body: "Hello, I'm interested in your services. Please contact me.",
+ id: '6ad0b4e91ce51d8e89ca3433',
+ number: 1,
+ title: 'John Doe',
+ email: '[email protected]',
+ name: 'John Doe',
+ first_name: 'John',
+ last_name: 'Doe',
+ company: null,
+ summary: '<strong>John Doe</strong> Hello, I am interested in your services.',
+ body: 'Hello, I am interested in your services.',
data: {
- name: "John Doe",
- email: "[email protected]",
- message: "Hello, I'm interested in your services. Please contact me.",
- phone: "+1-555-123-4567"
+ name: 'John Doe',
+ email: '[email protected]',
+ message: 'Hello, I am interested in your services.',
+ ip: '203.0.113.10',
+ user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
+ referrer: 'https://my-site.netlify.app/contact',
+ },
+ created_at: '2026-10-15T11:11:37.106Z',
+ human_fields: {
+ Name: 'John Doe',
+ Email: '[email protected]',
+ Message: 'Hello, I am interested in your services.',
},
- created_at: "2025-09-02T10:15:30.000Z",
- site_url: "https://my-site.netlify.app",
- form_id: "507f1f77bcf86cd799439016",
- form_name: "contact",
- ip: "192.168.1.100",
- user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
- referrer: "https://my-site.netlify.app/contact"
+ ordered_human_fields: [
+ { title: 'Name', name: 'name', value: 'John Doe' },
+ { title: 'Email', name: 'email', value: '[email protected]' },
+ { title: 'Message', name: 'message', value: 'Hello, I am interested in your services.' },
+ ],
+ form_id: '6ad0b4a19f1eec19a8db9237',
+ form_name: 'contact',
+ site_url: 'https://my-site.netlify.app',
+ site_name: 'my-site',
},
type: TriggerStrategy.WEBHOOK,
- onEnable: async (context) => {
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: "https://api.netlify.com/api/v1/hooks",
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- "Content-Type": "application/json",
- },
- body: {
- site_id: context.propsValue.siteId,
- type: "url",
- event: "submission_created",
- data: {
- url: context.webhookUrl,
- },
- },
- });
-
- if (response.status === 201) {
- await context.store.put("webhook_id", response.body.id);
- } else {
- throw new Error(`Failed to create webhook: ${response.status}`);
- }
+ async onEnable(context) {
+ await netlifyWebhook.enable({ auth: context.auth, siteId: context.propsValue.siteId, event: 'submission_created', webhookUrl: context.webhookUrl, store: context.store });
},
- onDisable: async (context) => {
- const webhookId = await context.store.get("webhook_id");
- if (webhookId) {
- if (!context.auth) {
- throw new Error("Authentication is required");
- }
-
- const auth = context.auth as OAuth2PropertyValue;
- if (!auth.access_token) {
- throw new Error("Access token is required");
- }
-
- await httpClient.sendRequest({
- method: HttpMethod.DELETE,
- url: `https://api.netlify.com/api/v1/hooks/${webhookId}`,
- headers: {
- "Authorization": `Bearer ${auth.access_token}`,
- },
- });
- }
+ async onDisable(context) {
+ await netlifyWebhook.disable({ auth: context.auth, store: context.store });
},
- run: async (context) => {
- return [context.payload.body];
+ async run(context) {
+ return netlifyWebhook.receive({ payload: context.payload, store: context.store });
},
});
diff --git a/packages/pieces/community/netlify/test/netlify.test.ts b/packages/pieces/community/netlify/test/netlify.test.ts
new file mode 100644
index 00000000000..b077b59c413
--- /dev/null
+++ b/packages/pieces/community/netlify/test/netlify.test.ts
@@ -0,0 +1,255 @@
+import { createHash, createHmac } from 'crypto';
+import { httpClient, HttpError, HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { netlifyClient, NetlifyApiError } from '../src/lib/common/client';
+import { netlifyOperations } from '../src/lib/common/operations';
+import { netlifyWebhook } from '../src/lib/common/webhook';
+
+const auth = { access_token: 'token-123' };
+const SITE = { id: 'site-1', account_id: 'acc-1', name: 'my-site', jwt_secret: 'should-not-leak' };
+
+function sign({ secret, body, alg = 'HS256', iss = 'netlify' }: { secret: string; body: string; alg?: string; iss?: string }): string {
+ const header = Buffer.from(JSON.stringify({ alg, typ: 'JWT' })).toString('base64url');
+ const claims = Buffer.from(JSON.stringify({ iss, sha256: createHash('sha256').update(body).digest('hex') })).toString('base64url');
+ const signature = createHmac('sha256', secret).update(`${header}.${claims}`).digest('base64url');
+ return `${header}.${claims}.${signature}`;
+}
+
+function memoryStore(initial: Record<string, unknown> = {}) {
+ const data: Record<string, unknown> = { ...initial };
+ return {
+ data,
+ put: async (key: string, value: unknown) => {
+ data[key] = value;
+ return value;
+ },
+ get: async <T>(key: string): Promise<T | null> => (key in data ? Reflect.get(data, key) : null),
+ delete: async (key: string) => {
+ delete data[key];
+ },
+ };
+}
+
+function slowStore() {
+ const base = memoryStore();
+ const tick = () => new Promise((resolve) => setTimeout(resolve, Math.random() * 5));
+ return {
+ ...base,
+ put: async (key: string, value: unknown) => {
+ await tick();
+ return base.put(key, value);
+ },
+ get: async <T>(key: string): Promise<T | null> => {
+ await tick();
+ return base.get<T>(key);
+ },
+ };
+}
+
+function httpFailure({ status, body }: { status: number; body: unknown }) {
+ return new HttpError({ secret: 'x' }, { status, responseBody: body });
+}
+
+type Route = { method: string; path: string; status?: number; body?: unknown };
+
+function mockRoutes(routes: Route[]) {
+ const calls: { method: string; url: string; query: unknown; body: unknown; redact: boolean | undefined }[] = [];
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ const url = new URL(request.url);
+ calls.push({ method: request.method, url: request.url, query: request.queryParams, body: request.body, redact: request.redactBodyInErrors });
+ const route = routes.find((r) => r.method === request.method && url.pathname === `/api/v1${r.path}`);
+ if (!route) throw new Error(`unexpected ${request.method} ${url.pathname}`);
+ if ((route.status ?? 200) >= 400) throw httpFailure({ status: route.status ?? 500, body: route.body });
+ return { status: route.status ?? 200, headers: {}, body: route.body };
+ });
+ return calls;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('webhook signature', () => {
+ const secret = 'a'.repeat(64);
+ const body = JSON.stringify({ id: 'dep-1', state: 'ready' });
+
+ it('accepts a valid Netlify JWS', () => {
+ expect(netlifyWebhook.verifySignature({ token: sign({ secret, body }), secret, rawBody: body })).toBe(true);
+ });
+ it('rejects a wrong secret, a changed body, another issuer, alg none and a missing token', () => {
+ expect(netlifyWebhook.verifySignature({ token: sign({ secret: 'b'.repeat(64), body }), secret, rawBody: body })).toBe(false);
+ expect(netlifyWebhook.verifySignature({ token: sign({ secret, body }), secret, rawBody: `${body} ` })).toBe(false);
+ expect(netlifyWebhook.verifySignature({ token: sign({ secret, body, iss: 'other' }), secret, rawBody: body })).toBe(false);
+ expect(netlifyWebhook.verifySignature({ token: sign({ secret, body, alg: 'none' }), secret, rawBody: body })).toBe(false);
+ expect(netlifyWebhook.verifySignature({ token: undefined, secret, rawBody: body })).toBe(false);
+ expect(netlifyWebhook.verifySignature({ token: sign({ secret, body }), secret, rawBody: null })).toBe(false);
+ });
+});
+
+describe('webhook receive', () => {
+ const secret = 'c'.repeat(64);
+ const body = { id: 'dep-1', state: 'ready' };
+ const rawBody = JSON.stringify(body);
+
+ it('drops deliveries with a bad signature', async () => {
+ const store = memoryStore({ webhook_signature_secret: secret });
+ const items = await netlifyWebhook.receive({ payload: { body, rawBody, headers: { 'x-webhook-signature': 'x.y.z' } }, store });
+ expect(items).toEqual([]);
+ });
+ it('emits a signed delivery once and drops the retry inside 15 minutes', async () => {
+ const store = memoryStore({ webhook_signature_secret: secret });
+ const payload = { body, rawBody, headers: { 'X-Webhook-Signature': sign({ secret, body: rawBody }) } };
+ const emitted = { ...body, _dedupe_key: 'netlify:dep-1:ready' };
+ expect(await netlifyWebhook.receive({ payload, store, now: 1_000 })).toEqual([emitted]);
+ expect(await netlifyWebhook.receive({ payload, store, now: 1_000 + 60_000 })).toEqual([]);
+ expect(await netlifyWebhook.receive({ payload, store, now: 1_000 + 16 * 60_000 })).toEqual([emitted]);
+ });
+ it('treats another state of the same deploy as a new event', async () => {
+ const store = memoryStore();
+ expect(await netlifyWebhook.receive({ payload: { body: { id: 'dep-2', state: 'building' } }, store })).toHaveLength(1);
+ expect(await netlifyWebhook.receive({ payload: { body: { id: 'dep-2', state: 'ready' } }, store })).toHaveLength(1);
+ });
+ it('accepts unsigned deliveries for hooks created before signing existed', async () => {
+ const store = memoryStore();
+ expect(await netlifyWebhook.receive({ payload: { body }, store })).toHaveLength(1);
+ });
+ it('tags parallel deliveries of the same event with one platform dedupe key', async () => {
+ const store = slowStore();
+ const payload = { body: { id: 'sub-1' } };
+ const results = await Promise.all([netlifyWebhook.receive({ payload, store }), netlifyWebhook.receive({ payload, store })]);
+ const emitted = results.flat();
+ expect(emitted.length).toBeGreaterThanOrEqual(1);
+ expect(new Set(emitted.map((item) => Reflect.get(Object(item), '_dedupe_key')))).toEqual(new Set(['netlify:sub-1']));
+ expect(await netlifyWebhook.receive({ payload, store })).toEqual([]);
+ });
+ it('never drops parallel deliveries of different events', async () => {
+ const store = slowStore();
+ const ids = Array.from({ length: 20 }, (_, i) => `sub-${i}`);
+ const results = await Promise.all(ids.map((id) => netlifyWebhook.receive({ payload: { body: { id } }, store })));
+ expect(results.every((items) => items.length === 1)).toBe(true);
+ const again = await Promise.all(ids.map((id) => netlifyWebhook.receive({ payload: { body: { id } }, store })));
+ expect(again.flat().every((item) => Reflect.get(Object(item), '_dedupe_key') !== undefined)).toBe(true);
+ });
+});
+
+describe('webhook enable/disable', () => {
+ it('creates a signed hook, stores its secret and removes everything on disable', async () => {
+ const calls = mockRoutes([
+ { method: 'POST', path: '/hooks', status: 201, body: { id: 'hook-1' } },
+ { method: 'DELETE', path: '/hooks/hook-1', status: 404, body: { message: 'Not Found' } },
+ ]);
+ const store = memoryStore();
+ await netlifyWebhook.enable({ auth, siteId: 'site-1', event: 'deploy_created', webhookUrl: 'https://ap.example/hook', store });
+ const sentSecret = Reflect.get(Reflect.get(Object(calls[0].body), 'data'), 'signature_secret');
+ expect(sentSecret).toMatch(/^[0-9a-f]{64}$/);
+ expect(store.data['webhook_signature_secret']).toBe(sentSecret);
+ expect(calls[0].redact).toBe(true);
+ expect(calls[0].query).toEqual({ site_id: 'site-1' });
+ await netlifyWebhook.disable({ auth, store });
+ expect(store.data).toEqual({});
+ });
+});
+
+describe('error mapper', () => {
+ it('uses the Netlify message and a hint', () => {
+ const error = netlifyClient.toApiError({ status: 404, body: { code: 404, message: 'Not Found' }, redact: false });
+ expect(error).toBeInstanceOf(NetlifyApiError);
+ expect(error.message).toBe('Netlify API error (404): Not Found. Check the ID; the resource does not exist or is not visible to this account.');
+ expect(error.responseBody).toEqual({ code: 404, message: 'Not Found' });
+ });
+ it('drops the response body when redacting', () => {
+ expect(netlifyClient.toApiError({ status: 422, body: { message: 'bad' }, redact: true }).responseBody).toBeUndefined();
+ });
+});
+
+describe('env vars', () => {
+ it('creates a missing variable with POST', async () => {
+ const calls = mockRoutes([
+ { method: 'GET', path: '/sites/site-1', body: SITE },
+ { method: 'GET', path: '/accounts/acc-1/env/API_URL', status: 404, body: { message: 'Not Found' } },
+ { method: 'POST', path: '/accounts/acc-1/env', status: 201, body: [{ key: 'API_URL', scopes: ['builds'], is_secret: false, values: [{ context: 'all', value: 'v' }] }] },
+ ]);
+ const result = await netlifyOperations.setEnvVar({ auth, siteId: 'site-1', key: 'API_URL', value: 'v' });
+ expect(result).toEqual({ key: 'API_URL', created: true, context: 'all', scopes: ['builds'], is_secret: false, contexts: ['all'] });
+ expect(JSON.stringify(result)).not.toContain('"v"');
+ expect(calls[2].redact).toBe(true);
+ });
+ it('replaces an existing variable with PUT for all contexts and PATCHes one context', async () => {
+ const existing = { key: 'API_URL', scopes: ['builds'], is_secret: false, values: [] };
+ const calls = mockRoutes([
+ { method: 'GET', path: '/sites/site-1', body: SITE },
+ { method: 'GET', path: '/accounts/acc-1/env/API_URL', body: existing },
+ { method: 'PUT', path: '/accounts/acc-1/env/API_URL', body: { ...existing, values: [{ context: 'all' }] } },
+ { method: 'PATCH', path: '/accounts/acc-1/env/API_URL', body: { ...existing, values: [{ context: 'production' }] } },
+ ]);
+ expect((await netlifyOperations.setEnvVar({ auth, siteId: 'site-1', key: 'API_URL', value: 'v', context: 'all' })).created).toBe(false);
+ await netlifyOperations.setEnvVar({ auth, siteId: 'site-1', key: 'API_URL', value: 'v', context: 'production' });
+ expect(calls.map((c) => c.method)).toEqual(['GET', 'GET', 'PUT', 'GET', 'GET', 'PATCH']);
+ expect(calls[5].body).toEqual({ context: 'production', value: 'v' });
+ });
+ it('refuses a secret for all contexts and bad keys before any request', async () => {
+ const calls = mockRoutes([]);
+ await expect(netlifyOperations.setEnvVar({ auth, siteId: 'site-1', key: 'K', value: 'v', isSecret: true })).rejects.toThrow('specific deploy context');
+ await expect(netlifyOperations.setEnvVar({ auth, siteId: 'site-1', key: '1BAD', value: 'v' })).rejects.toThrow('Key must start');
+ expect(calls).toHaveLength(0);
+ });
+ it('reports already_deleted when the key does not exist', async () => {
+ const calls = mockRoutes([
+ { method: 'GET', path: '/sites/site-1', body: SITE },
+ { method: 'GET', path: '/accounts/acc-1/env/OLD', status: 404, body: { message: 'Not Found' } },
+ ]);
+ expect(await netlifyOperations.deleteEnvVar({ auth, siteId: 'site-1', key: 'OLD' })).toEqual({ key: 'OLD', deleted: false, already_deleted: true });
+ expect(calls.some((c) => c.method === 'DELETE')).toBe(false);
+ });
+});
+
+describe('sites and builds', () => {
+ it('drops jwt_secret from site output', async () => {
+ mockRoutes([{ method: 'GET', path: '/sites/site-1', body: SITE }]);
+ expect(await netlifyOperations.getSite({ auth, siteId: 'site-1' })).not.toHaveProperty('jwt_secret');
+ });
+ it('explains a 404 from the builds endpoint as a site without a repository', async () => {
+ mockRoutes([
+ { method: 'GET', path: '/sites/site-1', body: SITE },
+ { method: 'POST', path: '/sites/site-1/builds', status: 404, body: { message: 'Not Found' } },
+ ]);
+ await expect(netlifyOperations.startBuild({ auth, siteId: 'site-1' })).rejects.toThrow('not linked to a Git repository');
+ });
+});
+
+describe('custom api call paths', () => {
+ it('accepts relative paths and same-origin URLs', () => {
+ expect(netlifyClient.apiPath('/sites')).toBe('/sites');
+ expect(netlifyClient.apiPath('sites/abc/deploys?page=2')).toBe('/sites/abc/deploys?page=2');
+ expect(netlifyClient.apiPath('https://api.netlify.com/api/v1/hooks')).toBe('/hooks');
+ });
+ it.each([
+ 'https://api.netlify.com.evil.io/api/v1/sites',
+ 'https://evil.io/api/v1/sites',
+ '//evil.io/sites',
+ 'http://api.netlify.com/api/v1/sites',
+ 'https://[email protected]/api/v1/sites',
+ 'https://api.netlify.com/other',
+ '',
+ ])('refuses %s', (url) => {
+ expect(() => netlifyClient.apiPath(url)).toThrow();
+ });
+ it('keeps the request body out of logs when Netlify rejects a custom call', async () => {
+ const { customApiCall } = await import('../src/lib/actions/custom-api-call');
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ message: 'Invalid' }), { status: 422, headers: { 'content-type': 'application/json' } })));
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ const props = { url: '/accounts/acc-1/env', method: HttpMethod.POST, headers: {}, queryParams: {}, body: { key: 'API_KEY', value: 'super-secret-value' } };
+ await expect(Reflect.apply(customApiCall.run, undefined, [{ auth, propsValue: props }])).rejects.toThrow('Netlify API error (422): Invalid.');
+ expect(JSON.stringify(logged.mock.calls.map((call) => call.map(String)))).not.toContain('super-secret-value');
+ });
+ it('never lets a header replace the connection token', async () => {
+ const calls: { headers: unknown }[] = [];
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ calls.push({ headers: request.headers });
+ return { status: 200, headers: {}, body: {} };
+ });
+ await netlifyClient.request({ auth, method: HttpMethod.GET, path: '/user', extraHeaders: { authorization: 'Bearer other', 'X-Extra': '1' } });
+ expect(calls[0].headers).toEqual({ Accept: 'application/json', 'X-Extra': '1', Authorization: 'Bearer token-123' });
+ });
+});
diff --git a/packages/pieces/community/netlify/vitest.config.ts b/packages/pieces/community/netlify/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/netlify/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})