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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(amazon-lambda): add an AWS Lambda piece (#16286)
Eliseu Kadesh1420bc2a3adf
diff --git a/bun.lock b/bun.lockindex ea1b5bbeb3b..076864b26d4 100644--- a/bun.lock+++ b/bun.lock@@ -550,6 +550,25 @@"vitest": "3.2.6",},},+ "packages/pieces/community/amazon-lambda": {+ "name": "@activepieces/piece-amazon-lambda",+ "version": "0.0.1",+ "dependencies": {+ "@activepieces/core-piece-types": "workspace:*",+ "@activepieces/core-utils": "workspace:*",+ "@activepieces/pieces-common": "workspace:*",+ "@activepieces/pieces-framework": "workspace:*",+ "@aws-crypto/sha256-js": "5.2.0",+ "@aws-sdk/client-lambda": "3.974.0",+ "@aws-sdk/client-sts": "3.974.0",+ "@smithy/protocol-http": "5.3.8",+ "@smithy/signature-v4": "5.3.8",+ },+ "devDependencies": {+ "tslib": "2.6.2",+ "vitest": "3.2.6",+ },+ },"packages/pieces/community/amazon-s3": {"name": "@activepieces/piece-amazon-s3","version": "0.8.0",@@ -11392,6 +11411,8 @@"@activepieces/piece-amazon-bedrock": ["@activepieces/piece-amazon-bedrock@workspace:packages/pieces/community/amazon-bedrock"],+ "@activepieces/piece-amazon-lambda": ["@activepieces/piece-amazon-lambda@workspace:packages/pieces/community/amazon-lambda"],+"@activepieces/piece-amazon-s3": ["@activepieces/piece-amazon-s3@workspace:packages/pieces/community/amazon-s3"],"@activepieces/piece-amazon-secrets-manager": ["@activepieces/piece-amazon-secrets-manager@workspace:packages/pieces/community/amazon-secrets-manager"],@@ -13024,6 +13045,8 @@"@aws-sdk/client-bedrock-runtime": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.7", "@aws-sdk/credential-provider-node": "^3.972.38", "@aws-sdk/eventstream-handler-node": "^3.972.14", "@aws-sdk/middleware-eventstream": "^3.972.10", "@aws-sdk/middleware-host-header": "^3.972.10", "@aws-sdk/middleware-logger": "^3.972.10", "@aws-sdk/middleware-recursion-detection": "^3.972.11", "@aws-sdk/middleware-user-agent": "^3.972.37", "@aws-sdk/middleware-websocket": "^3.972.16", "@aws-sdk/region-config-resolver": "^3.972.13", "@aws-sdk/token-providers": "3.1039.0", "@aws-sdk/types": "^3.973.8", "@aws-sdk/util-endpoints": "^3.996.8", "@aws-sdk/util-user-agent-browser": "^3.972.10", "@aws-sdk/util-user-agent-node": "^3.973.23", "@smithy/config-resolver": "^4.4.17", "@smithy/core": "^3.23.17", "@smithy/eventstream-serde-browser": "^4.2.14", "@smithy/eventstream-serde-config-resolver": "^4.3.14", "@smithy/eventstream-serde-node": "^4.2.14", "@smithy/fetch-http-handler": "^5.3.17", "@smithy/hash-node": "^4.2.14", "@smithy/invalid-dependency": "^4.2.14", "@smithy/middleware-content-length": "^4.2.14", "@smithy/middleware-endpoint": "^4.4.32", "@smithy/middleware-retry": "^4.5.7", "@smithy/middleware-serde": "^4.2.20", "@smithy/middleware-stack": "^4.2.14", "@smithy/node-config-provider": "^4.3.14", "@smithy/node-http-handler": "^4.6.1", "@smithy/protocol-http": "^5.3.14", "@smithy/smithy-client": "^4.12.13", "@smithy/types": "^4.14.1", "@smithy/url-parser": "^4.2.14", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.49", "@smithy/util-defaults-mode-node": "^4.2.54", "@smithy/util-endpoints": "^3.4.2", "@smithy/util-middleware": "^4.2.14", "@smithy/util-retry": "^4.3.6", "@smithy/util-stream": "^4.5.25", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-rpm9rGcv95ulprNIu/ruhreG4bSKq7oFrErM1Nkp9Cq/zzo/11Hw1/ffYKLM/PAcMGZ+5/zAHOCWBDQ3W1lIBw=="],+ "@aws-sdk/client-lambda": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/credential-provider-node": "^3.972.1", "@aws-sdk/middleware-host-header": "^3.972.1", "@aws-sdk/middleware-logger": "^3.972.1", "@aws-sdk/middleware-recursion-detection": "^3.972.1", "@aws-sdk/middleware-user-agent": "^3.972.1", "@aws-sdk/region-config-resolver": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@aws-sdk/util-user-agent-browser": "^3.972.1", "@aws-sdk/util-user-agent-node": "^3.972.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.21.0", "@smithy/eventstream-serde-browser": "^4.2.8", "@smithy/eventstream-serde-config-resolver": "^4.3.8", "@smithy/eventstream-serde-node": "^4.2.8", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-retry": "^4.4.26", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.11", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.25", "@smithy/util-defaults-mode-node": "^4.2.28", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/util-waiter": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-/8CtFqvX4GrmwdSKKQkEH1IEiqNQCpZQKzaHGYXthA8Cfjg/nyJ/M1/2c/4El5R8eiZbzzHPGhUPPFdfGMB9jQ=="],+"@aws-sdk/client-s3": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-crypto/sha1-browser": "5.2.0", "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/credential-provider-node": "^3.972.1", "@aws-sdk/middleware-bucket-endpoint": "^3.972.1", "@aws-sdk/middleware-expect-continue": "^3.972.1", "@aws-sdk/middleware-flexible-checksums": "^3.972.1", "@aws-sdk/middleware-host-header": "^3.972.1", "@aws-sdk/middleware-location-constraint": "^3.972.1", "@aws-sdk/middleware-logger": "^3.972.1", "@aws-sdk/middleware-recursion-detection": "^3.972.1", "@aws-sdk/middleware-sdk-s3": "^3.972.1", "@aws-sdk/middleware-ssec": "^3.972.1", "@aws-sdk/middleware-user-agent": "^3.972.1", "@aws-sdk/region-config-resolver": "^3.972.1", "@aws-sdk/signature-v4-multi-region": "3.972.0", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@aws-sdk/util-user-agent-browser": "^3.972.1", "@aws-sdk/util-user-agent-node": "^3.972.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.21.0", "@smithy/eventstream-serde-browser": "^4.2.8", "@smithy/eventstream-serde-config-resolver": "^4.3.8", "@smithy/eventstream-serde-node": "^4.2.8", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-blob-browser": "^4.2.9", "@smithy/hash-node": "^4.2.8", "@smithy/hash-stream-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/md5-js": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-retry": "^4.4.26", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.11", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.25", "@smithy/util-defaults-mode-node": "^4.2.28", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/util-waiter": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-X+vpXNJ8cU8Iw1FtDgDHxo9z6RxlXfcTtpdGnKws4rk+tCYKSAor/DG6BRMzbh4E5xAA7DiU1Ny3BTrRRSt/Yg=="],"@aws-sdk/client-secrets-manager": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.13", "@aws-sdk/credential-provider-node": "^3.972.12", "@aws-sdk/middleware-host-header": "^3.972.4", "@aws-sdk/middleware-logger": "^3.972.4", "@aws-sdk/middleware-recursion-detection": "^3.972.4", "@aws-sdk/middleware-user-agent": "^3.972.13", "@aws-sdk/region-config-resolver": "^3.972.4", "@aws-sdk/types": "^3.973.2", "@aws-sdk/util-endpoints": "^3.996.1", "@aws-sdk/util-user-agent-browser": "^3.972.4", "@aws-sdk/util-user-agent-node": "^3.972.12", "@smithy/config-resolver": "^4.4.7", "@smithy/core": "^3.23.4", "@smithy/fetch-http-handler": "^5.3.10", "@smithy/hash-node": "^4.2.9", "@smithy/invalid-dependency": "^4.2.9", "@smithy/middleware-content-length": "^4.2.9", "@smithy/middleware-endpoint": "^4.4.18", "@smithy/middleware-retry": "^4.4.35", "@smithy/middleware-serde": "^4.2.10", "@smithy/middleware-stack": "^4.2.9", "@smithy/node-config-provider": "^4.3.9", "@smithy/node-http-handler": "^4.4.11", "@smithy/protocol-http": "^5.3.9", "@smithy/smithy-client": "^4.11.7", "@smithy/types": "^4.12.1", "@smithy/url-parser": "^4.2.9", "@smithy/util-base64": "^4.3.1", "@smithy/util-body-length-browser": "^4.2.1", "@smithy/util-body-length-node": "^4.2.2", "@smithy/util-defaults-mode-browser": "^4.3.34", "@smithy/util-defaults-mode-node": "^4.2.37", "@smithy/util-endpoints": "^3.2.9", "@smithy/util-middleware": "^4.2.9", "@smithy/util-retry": "^4.2.9", "@smithy/util-utf8": "^4.2.1", "tslib": "^2.6.2" } }, "sha512-5r+1P1iuILRhtKk7j5gEvfiJpweHk5TWXFJl5BKKKuE47esgd2R5cAwyPJId/5cPJln2yC9qevz9zneoLpWNVw=="],@@ -19080,6 +19103,18 @@"@aws-sdk/client-bedrock-runtime/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],+ "@aws-sdk/client-lambda/@aws-sdk/util-endpoints": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "3.972.0", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-endpoints": "^3.2.8", "tslib": "^2.6.2" } }, "sha512-6JHsl1V/a1ZW8D8AFfd4R52fwZPnZ5H4U6DS8m/bWT8qad72NvbOFAC7U2cDtFs2TShqUO3TEiX/EJibtY3ijg=="],++ "@aws-sdk/client-lambda/@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-CyogUINxvi7C7LDsh8Syo6hVJOT9ckz4rG8dRZfTJ8r91HkMY59PnNooaj7WcHyxEkxPfBAmbgztZU+xTo76lg=="],++ "@aws-sdk/client-lambda/@smithy/node-http-handler": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/protocol-http": "^5.3.14", "@smithy/querystring-builder": "^4.2.14", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-iB+orM4x3xrr57X3YaXazfKnntl0LHlZB1kcXSGzMV1Tt0+YwEjGlbjk/44qEGtBzXAz6yFDzkYTKSV6Pj2HUg=="],++ "@aws-sdk/client-lambda/@smithy/protocol-http": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-dN5F8kHx8RNU0r+pCwNmFZyz6ChjMkzShy/zup6MtkRmmix4vZzJdW+di7x//b1LiynIev88FM18ie+wwPcQtQ=="],++ "@aws-sdk/client-lambda/@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-0JFs3V2y2M9tKW5na/qxe69Zv+uxLMO7QBbhxF/FHu/Gp2NFZAAL9tWl9PU02xxo07pb3G9FTyjNc6D5uZrJIg=="],++ "@aws-sdk/client-lambda/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],+"@aws-sdk/client-s3/@aws-sdk/util-endpoints": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "3.972.0", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-endpoints": "^3.2.8", "tslib": "^2.6.2" } }, "sha512-6JHsl1V/a1ZW8D8AFfd4R52fwZPnZ5H4U6DS8m/bWT8qad72NvbOFAC7U2cDtFs2TShqUO3TEiX/EJibtY3ijg=="],"@aws-sdk/client-s3/@smithy/node-http-handler": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/protocol-http": "^5.3.14", "@smithy/querystring-builder": "^4.2.14", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-iB+orM4x3xrr57X3YaXazfKnntl0LHlZB1kcXSGzMV1Tt0+YwEjGlbjk/44qEGtBzXAz6yFDzkYTKSV6Pj2HUg=="],@@ -21276,6 +21311,14 @@"@aws-sdk/client-bedrock/@smithy/util-utf8/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],+ "@aws-sdk/client-lambda/@aws-sdk/util-endpoints/@aws-sdk/types": ["@aws-sdk/[email protected]", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-U7xBIbLSetONxb2bNzHyDgND3oKGoIfmknrEVnoEU4GUSs+0augUOIn9DIWGUO2ETcRFdsRUnmx9KhPT9Ojbug=="],++ "@aws-sdk/client-lambda/@aws-sdk/util-endpoints/@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-59b5HtSVrVR/eYNei3BUj3DCPKD/G7EtDDe7OEJE7i7FtQFugYo6MxbotS8mVJkLNVf8gYaAlEBwwtJ9HzhWSg=="],++ "@aws-sdk/client-lambda/@smithy/node-http-handler/@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-59b5HtSVrVR/eYNei3BUj3DCPKD/G7EtDDe7OEJE7i7FtQFugYo6MxbotS8mVJkLNVf8gYaAlEBwwtJ9HzhWSg=="],++ "@aws-sdk/client-lambda/@smithy/protocol-http/@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-59b5HtSVrVR/eYNei3BUj3DCPKD/G7EtDDe7OEJE7i7FtQFugYo6MxbotS8mVJkLNVf8gYaAlEBwwtJ9HzhWSg=="],+"@aws-sdk/client-s3/@aws-sdk/util-endpoints/@aws-sdk/types": ["@aws-sdk/[email protected]", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-U7xBIbLSetONxb2bNzHyDgND3oKGoIfmknrEVnoEU4GUSs+0augUOIn9DIWGUO2ETcRFdsRUnmx9KhPT9Ojbug=="],"@aws-sdk/client-s3/@aws-sdk/util-endpoints/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],diff --git a/packages/pieces/community/amazon-lambda/.eslintrc.json b/packages/pieces/community/amazon-lambda/.eslintrc.jsonnew file mode 100644index 00000000000..01f1c80f85a--- /dev/null+++ b/packages/pieces/community/amazon-lambda/.eslintrc.json@@ -0,0 +1,47 @@+{+ "extends": [+ "../../../../.eslintrc.base.json"+ ],+ "ignorePatterns": [+ "!**/*"+ ],+ "overrides": [+ {+ "files": [+ "*.ts",+ "*.tsx",+ "*.js",+ "*.jsx"+ ],+ "rules": {}+ },+ {+ "files": [+ "*.ts",+ "*.tsx"+ ],+ "rules": {+ "no-restricted-imports": [+ "error",+ {+ "patterns": [+ "lodash",+ "lodash/*",+ "@activepieces/core-*",+ "@activepieces/server*",+ "@activepieces/engine",+ "@activepieces/shared"+ ]+ }+ ]+ }+ },+ {+ "files": [+ "*.js",+ "*.jsx"+ ],+ "rules": {}+ }+ ]+}diff --git a/packages/pieces/community/amazon-lambda/README.md b/packages/pieces/community/amazon-lambda/README.mdnew file mode 100644index 00000000000..d035a699df9--- /dev/null+++ b/packages/pieces/community/amazon-lambda/README.md@@ -0,0 +1,13 @@+# pieces-amazon-lambda++Invoke AWS Lambda functions, read their configuration, call the Lambda API with a signed request, and watch for new functions.++## Building++Run `turbo run build --filter=@activepieces/piece-amazon-lambda` to build the library.++## Logo++`logoUrl` points at `https://cdn.activepieces.com/pieces/amazon-lambda.png`. That file is not on the CDN yet.++`amazon-lambda-logo.png` in this folder is a 500×500 PNG of the AWS Lambda mark. Please upload it to that URL when merging.diff --git a/packages/pieces/community/amazon-lambda/amazon-lambda-logo.png b/packages/pieces/community/amazon-lambda/amazon-lambda-logo.pngnew file mode 100644index 00000000000..b5c7e029f3aBinary files /dev/null and b/packages/pieces/community/amazon-lambda/amazon-lambda-logo.png differdiff --git a/packages/pieces/community/amazon-lambda/package.json b/packages/pieces/community/amazon-lambda/package.jsonnew file mode 100644index 00000000000..009b4157323--- /dev/null+++ b/packages/pieces/community/amazon-lambda/package.json@@ -0,0 +1,28 @@+{+ "name": "@activepieces/piece-amazon-lambda",+ "version": "0.0.1",+ "type": "commonjs",+ "main": "./dist/src/index.js",+ "types": "./dist/src/index.d.ts",+ "dependencies": {+ "@activepieces/core-piece-types": "workspace:*",+ "@activepieces/core-utils": "workspace:*",+ "@activepieces/pieces-common": "workspace:*",+ "@activepieces/pieces-framework": "workspace:*",+ "@aws-crypto/sha256-js": "5.2.0",+ "@aws-sdk/client-lambda": "3.974.0",+ "@aws-sdk/client-sts": "3.974.0",+ "@smithy/protocol-http": "5.3.8",+ "@smithy/signature-v4": "5.3.8"+ },+ "devDependencies": {+ "tslib": "2.6.2",+ "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'",+ "test": "vitest run"+ }+}diff --git a/packages/pieces/community/amazon-lambda/src/__tests__/piece.test.ts b/packages/pieces/community/amazon-lambda/src/__tests__/piece.test.tsnew file mode 100644index 00000000000..e6d7f0876b3--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/__tests__/piece.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import { amazonLambda } from '../index';++describe('amazonLambda', () => {+ describe('when the builder lists the piece', () => {+ it('should show AWS Lambda as the display name', () => {+ expect(amazonLambda.displayName).toBe('AWS Lambda');+ });+ });++ describe('when a connection is offered', () => {+ it('given access-key and IAM role, should offer both connections', () => {+ const auth = amazonLambda.auth as { displayName: string }[];++ expect(Array.isArray(amazonLambda.auth)).toBe(true);+ expect(auth.map((item) => item.displayName)).toEqual([+ 'AWS Lambda (Access Key)',+ 'AWS Lambda (IAM Role / OIDC)',+ ]);+ });+ });++ describe('when the piece is registered', () => {+ it('should expose invoke, get-details, the custom call, and the trigger under unique names', () => {+ const actionNames = Object.keys(amazonLambda.actions());+ const triggerNames = Object.keys(amazonLambda.triggers());++ expect(actionNames).toEqual(['invokeFunction', 'getFunctionDetails', 'customApiCall']);+ expect(triggerNames).toEqual(['newFunctionCreated']);+ expect(new Set([...actionNames, ...triggerNames]).size).toBe(actionNames.length + triggerNames.length);+ });+ });+});diff --git a/packages/pieces/community/amazon-lambda/src/i18n/translation.json b/packages/pieces/community/amazon-lambda/src/i18n/translation.jsonnew file mode 100644index 00000000000..00ecb49b235--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/i18n/translation.json@@ -0,0 +1,44 @@+{+ "Invoke functions and watch for new ones": "Invoke functions and watch for new ones",+ "Invoke Function": "Invoke Function",+ "Get Function Details": "Get Function Details",+ "Custom Action": "Custom Action",+ "Invoke a Lambda function synchronously or asynchronously and return the status code, function error, and payload.": "Invoke a Lambda function synchronously or asynchronously and return the status code, function error, and payload.",+ "Return a function's ARN, runtime, handler, memory, timeout, and state.": "Return a function's ARN, runtime, handler, memory, timeout, and state.",+ "Send a SigV4-signed request to the Lambda API in the connection's region. Method, path, query, headers, and JSON body are yours.": "Send a SigV4-signed request to the Lambda API in the connection's region. Method, path, query, headers, and JSON body are yours.",+ "Function name or ARN": "Function name or ARN",+ "Invocation type": "Invocation type",+ "Qualifier": "Qualifier",+ "Payload": "Payload",+ "Fail step on function error": "Fail step on function error",+ "Include environment variables": "Include environment variables",+ "Method": "Method",+ "Path": "Path",+ "Query parameters": "Query parameters",+ "Headers": "Headers",+ "Body": "Body",+ "Timeout (seconds)": "Timeout (seconds)",+ "Name or ARN. Append :alias to target an alias.": "Name or ARN. Append :alias to target an alias.",+ "Synchronous waits for the result. Asynchronous returns once queued.": "Synchronous waits for the result. Asynchronous returns once queued.",+ "Optional version or alias. Leave empty to invoke $LATEST.": "Optional version or alias. Leave empty to invoke $LATEST.",+ "JSON sent to the function. Leave empty to send no payload.": "JSON sent to the function. Leave empty to send no payload.",+ "Fail this step when the function throws, instead of returning the error.": "Fail this step when the function throws, instead of returning the error.",+ "Name, partial ARN, or full ARN of the function.": "Name, partial ARN, or full ARN of the function.",+ "Optional version or alias. Leave empty to read $LATEST.": "Optional version or alias. Leave empty to read $LATEST.",+ "Values may contain secrets and will appear in run logs.": "Values may contain secrets and will appear in run logs.",+ "Lambda API path, such as /2015-03-31/functions.": "Lambda API path, such as /2015-03-31/functions.",+ "Optional query string. Keys with empty values are skipped.": "Optional query string. Keys with empty values are skipped.",+ "Optional headers. Host and Authorization are set for you.": "Optional headers. Host and Authorization are set for you.",+ "Optional JSON body for POST, PUT, and PATCH.": "Optional JSON body for POST, PUT, and PATCH.",+ "How long to wait. Defaults to 30 seconds. Maximum is 900.": "How long to wait. Defaults to 30 seconds. Maximum is 900.",+ "Synchronous (RequestResponse)": "Synchronous (RequestResponse)",+ "Asynchronous (Event)": "Asynchronous (Event)",+ "GET": "GET",+ "POST": "POST",+ "PATCH": "PATCH",+ "PUT": "PUT",+ "DELETE": "DELETE",+ "HEAD": "HEAD",+ "New Function Created": "New Function Created",+ "Fires when a Lambda function ARN appears that was not present the last time this trigger ran. Enabling it records the current functions and stays quiet.": "Fires when a Lambda function ARN appears that was not present the last time this trigger ran. Enabling it records the current functions and stays quiet."+}\ No newline at end of filediff --git a/packages/pieces/community/amazon-lambda/src/index.ts b/packages/pieces/community/amazon-lambda/src/index.tsnew file mode 100644index 00000000000..c7e6389f4e8--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/index.ts@@ -0,0 +1,18 @@+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { customApiCall } from './lib/actions/custom-api-call';+import { getFunctionConfiguration } from './lib/actions/get-function-details';+import { invokeFunction } from './lib/actions/invoke-function';+import { awsLambdaCombinedAuth } from './lib/auth';+import { newFunctionCreated } from './lib/triggers/new-function-created';++export const amazonLambda = createPiece({+ displayName: 'AWS Lambda',+ description: 'Invoke functions and watch for new ones',+ auth: awsLambdaCombinedAuth,+ minimumSupportedRelease: '0.90.1',+ logoUrl: 'https://cdn.activepieces.com/pieces/amazon-lambda.png',+ authors: ['eliseukadesh67'],+ categories: [PieceCategory.DEVELOPER_TOOLS],+ actions: [invokeFunction, getFunctionConfiguration, customApiCall],+ triggers: [newFunctionCreated],+});diff --git a/packages/pieces/community/amazon-lambda/src/lib/__tests__/auth.test.ts b/packages/pieces/community/amazon-lambda/src/lib/__tests__/auth.test.tsnew file mode 100644index 00000000000..bc091f21b9c--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/__tests__/auth.test.ts@@ -0,0 +1,97 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { send } = vi.hoisted(() => ({+ send: vi.fn<(command: unknown) => Promise<unknown>>(),+}));++vi.mock('@aws-sdk/client-lambda', () => ({+ LambdaClient: vi.fn<(this: { send: typeof send }) => void>(function LambdaClient(this: { send: typeof send }) {+ this.send = send;+ }),+ ListFunctionsCommand: vi.fn<(this: { input: unknown }, input: unknown) => void>(+ function ListFunctionsCommand(this: { input: unknown }, input: unknown) {+ this.input = input;+ },+ ),+}));++const { awsLambdaAccessKeyAuth, awsLambdaOidcAuth } = await import('../auth');++const server = { apiUrl: 'http://localhost/api/', publicUrl: 'http://localhost' };++describe('awsLambdaAccessKeyAuth', () => {+ beforeEach(() => {+ send.mockReset();+ });++ describe('when the connection is saved', () => {+ it('given a missing key, should reject it without calling AWS', async () => {+ const result = await awsLambdaAccessKeyAuth.validate?.({+ auth: { accessKeyId: ' ', secretAccessKey: 'secret', region: 'us-east-1' },+ server,+ });++ expect(result).toEqual({ valid: false, error: 'Access Key ID and Secret Access Key are required.' });+ expect(send).not.toHaveBeenCalled();+ });++ it('given ListFunctions succeeds, should accept the connection', async () => {+ send.mockResolvedValue({ Functions: [] });++ const result = await awsLambdaAccessKeyAuth.validate?.({+ auth: { accessKeyId: 'AKIA', secretAccessKey: 'secret', region: 'us-east-1' },+ server,+ });++ expect(result).toEqual({ valid: true });+ expect(send).toHaveBeenCalledOnce();+ });++ it('given ListFunctions fails, should surface the AWS error name and message', async () => {+ send.mockRejectedValue(Object.assign(new Error('The security token included in the request is invalid.'), {+ name: 'UnrecognizedClientException',+ }));++ const result = await awsLambdaAccessKeyAuth.validate?.({+ auth: { accessKeyId: 'AKIA', secretAccessKey: 'secret', region: 'eu-west-1' },+ server,+ });++ expect(result).toEqual({+ valid: false,+ error: 'UnrecognizedClientException: The security token included in the request is invalid.',+ });+ });+ });+});++describe('awsLambdaOidcAuth', () => {+ beforeEach(() => {+ send.mockReset();+ });++ describe('when the connection is saved', () => {+ it('given a well-formed role ARN, should accept it without calling AWS', async () => {+ const result = await awsLambdaOidcAuth.validate?.({+ auth: { roleArn: 'arn:aws:iam::123456789012:role/lambda-runner', region: 'us-east-1' },+ server,+ });++ expect(result).toEqual({ valid: true });+ expect(send).not.toHaveBeenCalled();+ });++ it('given an ARN that is not an IAM role, should reject it', async () => {+ const result = await awsLambdaOidcAuth.validate?.({+ auth: { roleArn: 'arn:aws:lambda:us-east-1:123456789012:function:billing', region: 'us-east-1' },+ server,+ });++ expect(result).toEqual({+ valid: false,+ error: 'Invalid IAM Role ARN format. Expected: arn:aws:iam::123456789012:role/RoleName',+ });+ expect(send).not.toHaveBeenCalled();+ });+ });+});diff --git a/packages/pieces/community/amazon-lambda/src/lib/actions/custom-api-call.ts b/packages/pieces/community/amazon-lambda/src/lib/actions/custom-api-call.tsnew file mode 100644index 00000000000..d00d6e0c5e7--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/actions/custom-api-call.ts@@ -0,0 +1,72 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';++import { awsLambdaCombinedAuth, type LambdaAuthProps } from '../auth';+import { customLambdaCall } from '../common/client';++export const customApiCall = createAction({+ name: 'customApiCall',+ displayName: 'Custom Action',+ description: 'Send a SigV4-signed request to the Lambda API in the connection\'s region. Method, path, query, headers, and JSON body are yours.',+ auth: awsLambdaCombinedAuth,+ requireAuth: true,+ audience: 'human',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Send a signed request to any AWS Lambda API path in the connection\'s region. Use only when no dedicated action covers the call; the effect and retry safety depend on the method and path.',+ idempotent: false,+ },+ props: {+ method: Property.StaticDropdown({+ displayName: 'Method',+ required: true,+ defaultValue: HttpMethod.GET,+ options: {+ options: Object.values(HttpMethod).map((method) => ({ label: method, value: method })),+ },+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Lambda API path, such as /2015-03-31/functions.',+ required: true,+ }),+ queryParams: Property.Object({+ displayName: 'Query parameters',+ description: 'Optional query string. Keys with empty values are skipped.',+ required: false,+ }),+ headers: Property.Object({+ displayName: 'Headers',+ description: 'Optional headers. Host and Authorization are set for you.',+ required: false,+ }),+ body: Property.Json({+ displayName: 'Body',+ description: 'Optional JSON body for POST, PUT, and PATCH.',+ required: false,+ }),+ timeout: Property.Number({+ displayName: 'Timeout (seconds)',+ description: 'How long to wait. Defaults to 30 seconds. Maximum is 900.',+ required: false,+ defaultValue: 30,+ }),+ },+ async run(context) {+ const { method, path, queryParams, headers, body, timeout } = context.propsValue;+ const auth: LambdaAuthProps = context.auth.props;+ return customLambdaCall({+ auth,+ server: context.server,+ input: {+ method,+ path,+ queryParams,+ headers,+ body,+ timeoutSeconds: timeout,+ },+ });+ },+});diff --git a/packages/pieces/community/amazon-lambda/src/lib/actions/get-function-details.ts b/packages/pieces/community/amazon-lambda/src/lib/actions/get-function-details.tsnew file mode 100644index 00000000000..f9f36686fb8--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/actions/get-function-details.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { awsLambdaCombinedAuth, type LambdaAuthProps } from '../auth';+import { getFunctionDetails } from '../common/client';+import { getFunctionDetailsOutputSchema } from '../output-schemas';++export const getFunctionConfiguration = createAction({+ name: 'getFunctionDetails',+ displayName: 'Get Function Details',+ description: 'Return a function\'s ARN, runtime, handler, memory, timeout, and state.',+ auth: awsLambdaCombinedAuth,+ requireAuth: true,+ audience: 'both',+ classification: 'READ',+ outputSchema: getFunctionDetailsOutputSchema,+ aiMetadata: {+ description:+ 'Read the configuration of one AWS Lambda function by name or ARN: runtime, handler, memory, timeout, role, state and version. Use it to inspect a function before invoking it. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ functionName: Property.ShortText({+ displayName: 'Function name or ARN',+ description: 'Name, partial ARN, or full ARN of the function.',+ required: true,+ }),+ qualifier: Property.ShortText({+ displayName: 'Qualifier',+ description: 'Optional version or alias. Leave empty to read $LATEST.',+ required: false,+ }),+ includeEnvironment: Property.Checkbox({+ displayName: 'Include environment variables',+ description: 'Values may contain secrets and will appear in run logs.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const { functionName, qualifier, includeEnvironment } = context.propsValue;+ const auth: LambdaAuthProps = context.auth.props;+ return getFunctionDetails({+ auth,+ server: context.server,+ input: {+ functionName,+ qualifier,+ includeEnvironment: includeEnvironment === true,+ },+ });+ },+});diff --git a/packages/pieces/community/amazon-lambda/src/lib/actions/invoke-function.ts b/packages/pieces/community/amazon-lambda/src/lib/actions/invoke-function.tsnew file mode 100644index 00000000000..4c3832d6e7c--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/actions/invoke-function.ts@@ -0,0 +1,71 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { awsLambdaCombinedAuth, type LambdaAuthProps } from '../auth';+import { invokeLambda } from '../common/client';+import { invokeFunctionOutputSchema } from '../output-schemas';++export const invokeFunction = createAction({+ name: 'invokeFunction',+ displayName: 'Invoke Function',+ description: 'Invoke a Lambda function synchronously or asynchronously and return the status code, function error, and payload.',+ auth: awsLambdaCombinedAuth,+ requireAuth: true,+ audience: 'both',+ classification: 'WRITE',+ outputSchema: invokeFunctionOutputSchema,+ aiMetadata: {+ description:+ 'Run an AWS Lambda function with an optional JSON payload. Synchronous calls wait and return the function\'s response; asynchronous calls only queue the event. Each call runs the function again, so retries repeat its side effects.',+ idempotent: false,+ },+ props: {+ functionName: Property.ShortText({+ displayName: 'Function name or ARN',+ description: 'Name or ARN. Append :alias to target an alias.',+ required: true,+ }),+ invocationType: Property.StaticDropdown({+ displayName: 'Invocation type',+ description: 'Synchronous waits for the result. Asynchronous returns once queued.',+ required: true,+ defaultValue: 'RequestResponse',+ options: {+ options: [+ { label: 'Synchronous (RequestResponse)', value: 'RequestResponse' },+ { label: 'Asynchronous (Event)', value: 'Event' },+ ],+ },+ }),+ qualifier: Property.ShortText({+ displayName: 'Qualifier',+ description: 'Optional version or alias. Leave empty to invoke $LATEST.',+ required: false,+ }),+ payload: Property.Json({+ displayName: 'Payload',+ description: 'JSON sent to the function. Leave empty to send no payload.',+ required: false,+ }),+ failOnFunctionError: Property.Checkbox({+ displayName: 'Fail step on function error',+ description: 'Fail this step when the function throws, instead of returning the error.',+ required: false,+ defaultValue: true,+ }),+ },+ async run(context) {+ const { functionName, invocationType, qualifier, payload, failOnFunctionError } = context.propsValue;+ const auth: LambdaAuthProps = context.auth.props;+ return invokeLambda({+ auth,+ server: context.server,+ input: {+ functionName,+ invocationType: invocationType === 'Event' ? 'Event' : 'RequestResponse',+ qualifier,+ payload,+ failOnFunctionError: failOnFunctionError !== false,+ },+ });+ },+});diff --git a/packages/pieces/community/amazon-lambda/src/lib/auth.ts b/packages/pieces/community/amazon-lambda/src/lib/auth.tsnew file mode 100644index 00000000000..0aa299ad325--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/auth.ts@@ -0,0 +1,148 @@+import { LambdaClient, ListFunctionsCommand } from '@aws-sdk/client-lambda';+import { PieceAuth, Property } from '@activepieces/pieces-framework';++import { LambdaApiError } from './common/errors';+import { AWS_REGIONS } from './common/regions';++const accessKeyDescription = `+Connect with an IAM user's access key.++**How to get your credentials:**+1. Open the [AWS IAM Console](https://console.aws.amazon.com/iam/) and go to **Users**.+2. Select your user (or create one), then open **Security credentials**.+3. Click **Create access key** and copy the Access Key ID and the Secret Access Key.+4. Attach a policy that allows the Lambda calls this piece makes: \`lambda:ListFunctions\`, \`lambda:GetFunctionConfiguration\`, and \`lambda:InvokeFunction\`. \`AWSLambda_ReadOnlyAccess\` plus \`lambda:InvokeFunction\` covers the built-in actions. The custom action needs whatever the path you call requires.++Saving the connection calls \`ListFunctions\` once. A bad key, region, or missing permission is rejected here.+`;++const oidcDescription = `+Connect with an IAM role via OIDC. No long-lived access key is stored.++Activepieces acts as an OIDC identity provider. AWS trusts it and issues temporary credentials with \`AssumeRoleWithWebIdentity\`.++**Setup steps:**+1. In AWS IAM → Identity providers → Create provider:+ - Provider type: **OpenID Connect**+ - Provider URL: \`{{frontendUrl}}\`+ - Audience: \`sts.amazonaws.com\`++ AWS fetches \`{{frontendUrl}}/.well-known/openid-configuration\`. If the frontend and API are on different hosts, the API must be reachable at \`{{frontendUrl}}\` (or the frontend must proxy \`/.well-known/*\`).+2. Create an IAM role with this trust policy:+\`\`\`json+{+ "Version": "2012-10-17",+ "Statement": [{+ "Effect": "Allow",+ "Principal": { "Federated": "arn:aws:iam::YOUR_ACCOUNT_ID:oidc-provider/{{frontendHost}}" },+ "Action": "sts:AssumeRoleWithWebIdentity",+ "Condition": {+ "StringEquals": {+ "{{frontendHost}}:aud": "sts.amazonaws.com"+ },+ "StringLike": {+ "{{frontendHost}}:sub": "platform:{{platformId}}:project:{{projectId}}"+ }+ }+ }]+}+\`\`\`+3. Attach Lambda permissions (\`lambda:ListFunctions\`, \`lambda:GetFunctionConfiguration\`, \`lambda:InvokeFunction\`) and paste the **Role ARN** below.++The role ARN is checked when you save. AWS is contacted on the first run, because connection validation does not receive a worker token.+`;++function regionProp() {+ return Property.StaticDropdown({+ displayName: 'Region',+ description: 'AWS region of the Lambda functions this connection uses. Another region needs another connection.',+ required: true,+ defaultValue: 'us-east-1',+ options: { options: AWS_REGIONS },+ });+}++const ROLE_ARN = /^arn:(?:aws|aws-us-gov|aws-cn):iam::\d{12}:role\/[\w+=,.@\-/]{1,512}$/;++export function isOidcAuth(auth: LambdaAuthProps): auth is OidcAuthProps {+ return 'roleArn' in auth;+}++export const awsLambdaAccessKeyAuth = PieceAuth.CustomAuth({+ displayName: 'AWS Lambda (Access Key)',+ description: accessKeyDescription,+ required: true,+ props: {+ accessKeyId: Property.ShortText({+ displayName: 'Access Key ID',+ description: 'Found in AWS IAM Console → Users → Security credentials.',+ required: true,+ }),+ secretAccessKey: PieceAuth.SecretText({+ displayName: 'Secret Access Key',+ description: 'Shown only once when the access key is created.',+ required: true,+ }),+ region: regionProp(),+ },+ validate: async ({ auth }) => {+ if (!auth.accessKeyId?.trim() || !auth.secretAccessKey?.trim()) {+ return { valid: false, error: 'Access Key ID and Secret Access Key are required.' };+ }+ try {+ const client = new LambdaClient({+ region: auth.region,+ credentials: {+ accessKeyId: auth.accessKeyId.trim(),+ secretAccessKey: auth.secretAccessKey.trim(),+ },+ });+ await client.send(new ListFunctionsCommand({ MaxItems: 1 }));+ return { valid: true };+ } catch (error) {+ return { valid: false, error: LambdaApiError.from(error).message };+ }+ },+});++export const awsLambdaOidcAuth = PieceAuth.OIDC({+ displayName: 'AWS Lambda (IAM Role / OIDC)',+ description: oidcDescription,+ required: true,+ props: {+ roleArn: Property.ShortText({+ displayName: 'Role ARN',+ description: 'ARN of the IAM role to assume, for example arn:aws:iam::123456789012:role/MyRole.',+ required: true,+ }),+ region: regionProp(),+ },+ validate: async ({ auth }) => {+ const roleArn = auth.roleArn?.trim() ?? '';+ if (!roleArn) {+ return { valid: false, error: 'Role ARN is required for IAM role authentication.' };+ }+ if (!ROLE_ARN.test(roleArn)) {+ return {+ valid: false,+ error: 'Invalid IAM Role ARN format. Expected: arn:aws:iam::123456789012:role/RoleName',+ };+ }+ return { valid: true };+ },+});++export const awsLambdaCombinedAuth = [awsLambdaAccessKeyAuth, awsLambdaOidcAuth];++export type AccessKeyAuthProps = {+ accessKeyId: string;+ secretAccessKey: string;+ region: string;+};++export type OidcAuthProps = {+ roleArn: string;+ region: string;+};++export type LambdaAuthProps = AccessKeyAuthProps | OidcAuthProps;diff --git a/packages/pieces/community/amazon-lambda/src/lib/common/__tests__/client.test.ts b/packages/pieces/community/amazon-lambda/src/lib/common/__tests__/client.test.tsnew file mode 100644index 00000000000..f85e21bb357--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/common/__tests__/client.test.ts@@ -0,0 +1,527 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const { send, stsSend, signedQueries } = vi.hoisted(() => ({+ send: vi.fn<(command: unknown) => Promise<unknown>>(),+ stsSend: vi.fn<(command: unknown) => Promise<unknown>>(),+ signedQueries: [] as unknown[],+}));++vi.mock('@aws-sdk/client-lambda', () => ({+ LambdaClient: vi.fn<(this: { send: typeof send }) => void>(function LambdaClient(this: { send: typeof send }) {+ this.send = send;+ }),+ ListFunctionsCommand: vi.fn<(this: { input: unknown }, input: unknown) => void>(+ function ListFunctionsCommand(this: { input: unknown }, input: unknown) {+ this.input = input;+ },+ ),+ InvokeCommand: vi.fn<(this: { input: unknown }, input: unknown) => void>(+ function InvokeCommand(this: { input: unknown }, input: unknown) {+ this.input = input;+ },+ ),+ GetFunctionConfigurationCommand: vi.fn<(this: { input: unknown }, input: unknown) => void>(+ function GetFunctionConfigurationCommand(this: { input: unknown }, input: unknown) {+ this.input = input;+ },+ ),+}));++vi.mock('@aws-sdk/client-sts', () => ({+ STSClient: vi.fn<(this: { send: typeof stsSend }) => void>(function STSClient(this: { send: typeof stsSend }) {+ this.send = stsSend;+ }),+ AssumeRoleWithWebIdentityCommand: vi.fn<(this: { input: unknown }, input: unknown) => void>(+ function AssumeRoleWithWebIdentityCommand(this: { input: unknown }, input: unknown) {+ this.input = input;+ },+ ),+}));++vi.mock('@smithy/protocol-http', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@smithy/protocol-http')>();+ return {+ ...actual,+ HttpRequest: class extends actual.HttpRequest {+ constructor(options: ConstructorParameters<typeof actual.HttpRequest>[0]) {+ super(options);+ signedQueries.push(options.query);+ }+ },+ };+});++const {+ cachedCredentialCount,+ clearCredentialsCache,+ customLambdaCall,+ decodePayload,+ getFunctionDetails,+ invokeLambda,+ listFunctions,+} = await import('../client');++const server = { apiUrl: 'http://localhost/api/', publicUrl: 'http://localhost', token: 'worker-token' };+const accessKey = { accessKeyId: 'AKIA', secretAccessKey: 'secret', region: 'us-east-1' };++describe('invokeLambda', () => {+ beforeEach(() => {+ send.mockReset();+ });++ describe('when the function is invoked', () => {+ it('given fail-on-error is off, should return the status code, function error, and decoded payload', async () => {+ send.mockResolvedValue({+ StatusCode: 200,+ FunctionError: 'Unhandled',+ ExecutedVersion: '$LATEST',+ Payload: new TextEncoder().encode(JSON.stringify({ ok: false })),+ });++ const result = await invokeLambda({ auth: accessKey, server, input: {+ functionName: ' billing ',+ invocationType: 'RequestResponse',+ payload: { id: 1 },+ failOnFunctionError: false,+ } });++ expect(result).toEqual({+ statusCode: 200,+ functionError: 'Unhandled',+ executedVersion: '$LATEST',+ payload: { ok: false },+ });+ const command = send.mock.calls[0][0] as { input: { FunctionName: string; Payload: Uint8Array } };+ expect(command.input.FunctionName).toBe('billing');+ expect(JSON.parse(new TextDecoder().decode(command.input.Payload))).toEqual({ id: 1 });+ });++ it('given an empty body, should return a null payload', async () => {+ send.mockResolvedValue({ StatusCode: 202, Payload: new Uint8Array() });++ const result = await invokeLambda({ auth: accessKey, server, input: {+ functionName: 'billing',+ invocationType: 'Event',+ failOnFunctionError: true,+ } });++ expect(result).toEqual({+ statusCode: 202,+ functionError: null,+ executedVersion: null,+ payload: null,+ });+ });++ it('given Lambda denies the call, should put the AWS error name and message on the thrown error', async () => {+ send.mockRejectedValue(Object.assign(new Error('User is not authorized'), { name: 'AccessDeniedException' }));++ await expect(invokeLambda({ auth: accessKey, server, input: {+ functionName: 'billing',+ invocationType: 'RequestResponse',+ failOnFunctionError: true,+ } })).rejects.toThrow('AccessDeniedException: User is not authorized');+ });++ it('given the function throws and fail-on-error is on, should fail with the function error message', async () => {+ send.mockResolvedValue({+ StatusCode: 200,+ FunctionError: 'Unhandled',+ Payload: new TextEncoder().encode(JSON.stringify({ errorType: 'Error', errorMessage: 'boom' })),+ });++ await expect(invokeLambda({ auth: accessKey, server, input: {+ functionName: 'billing',+ invocationType: 'RequestResponse',+ failOnFunctionError: true,+ } })).rejects.toThrow('The function failed: Error: boom');+ });++ it('given the payload arrives as a JSON string, should send the parsed object', async () => {+ send.mockResolvedValue({ StatusCode: 200, Payload: new Uint8Array() });++ await invokeLambda({ auth: accessKey, server, input: {+ functionName: 'billing',+ invocationType: 'RequestResponse',+ payload: '{"id":1}',+ failOnFunctionError: true,+ } });++ const command = send.mock.calls[0][0] as { input: { Payload: Uint8Array } };+ expect(new TextDecoder().decode(command.input.Payload)).toBe('{"id":1}');+ });++ it('given the payload string is not JSON, should fail before calling Lambda', async () => {+ await expect(invokeLambda({ auth: accessKey, server, input: {+ functionName: 'billing',+ invocationType: 'RequestResponse',+ payload: '{not json',+ failOnFunctionError: true,+ } })).rejects.toThrow('Payload must be valid JSON.');+ expect(send).not.toHaveBeenCalled();+ });++ it('given the SDK error carries an HTTP status, should keep it on the thrown error', async () => {+ send.mockRejectedValue(Object.assign(new Error('Function not found'), {+ name: 'ResourceNotFoundException',+ $metadata: { httpStatusCode: 404 },+ }));++ await expect(invokeLambda({ auth: accessKey, server, input: {+ functionName: 'missing',+ invocationType: 'RequestResponse',+ failOnFunctionError: true,+ } })).rejects.toMatchObject({ status: 404 });+ });+ });+});++describe('getFunctionDetails', () => {+ beforeEach(() => {+ send.mockReset();+ });++ describe('when the configuration is read', () => {+ it('given include environment is on, should return the variable names and values', async () => {+ send.mockResolvedValue({+ FunctionArn: 'arn:aws:lambda:us-east-1:123456789012:function:billing',+ FunctionName: 'billing',+ Runtime: 'nodejs20.x',+ Handler: 'index.handler',+ MemorySize: 256,+ Timeout: 15,+ Environment: { Variables: { API_KEY: 'secret-value' } },+ Role: 'arn:aws:iam::123456789012:role/lambda',+ LastModified: '2026-09-28T12:00:00.000+0000',+ State: 'Active',+ Version: '$LATEST',+ Description: 'Bills customers',+ });++ const details = await getFunctionDetails({ auth: accessKey, server, input: {+ functionName: 'billing',+ qualifier: 'live',+ includeEnvironment: true,+ } });++ expect(details).toEqual({+ functionArn: 'arn:aws:lambda:us-east-1:123456789012:function:billing',+ functionName: 'billing',+ runtime: 'nodejs20.x',+ handler: 'index.handler',+ memorySize: 256,+ timeout: 15,+ environment: { API_KEY: 'secret-value' },+ role: 'arn:aws:iam::123456789012:role/lambda',+ lastModified: '2026-09-28T12:00:00.000+0000',+ state: 'Active',+ version: '$LATEST',+ description: 'Bills customers',+ });+ });++ it('given include environment is off, should not return the variables', async () => {+ send.mockResolvedValue({+ FunctionName: 'billing',+ Environment: { Variables: { API_KEY: 'secret-value' } },+ });++ const details = await getFunctionDetails({ auth: accessKey, server, input: {+ functionName: 'billing',+ includeEnvironment: false,+ } });++ expect(details.environment).toBeNull();+ });+ });+});++describe('listFunctions', () => {+ beforeEach(() => {+ send.mockReset();+ });++ describe('when the region has more than one page', () => {+ it('given a NextMarker, should follow it until the list is exhausted', async () => {+ send+ .mockResolvedValueOnce({ Functions: [{ FunctionArn: 'arn:one' }], NextMarker: 'page-2' })+ .mockResolvedValueOnce({ Functions: [{ FunctionArn: 'arn:two' }] });++ const functions = await listFunctions({ auth: accessKey, server });++ expect(functions.map((fn) => fn.FunctionArn)).toEqual(['arn:one', 'arn:two']);+ expect(send).toHaveBeenCalledTimes(2);+ });+ });+});++describe('customLambdaCall', () => {+ beforeEach(() => {+ signedQueries.length = 0;+ vi.stubGlobal('fetch', vi.fn<(input: string, init?: RequestInit) => Promise<Response>>());+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ describe('when a custom call is signed', () => {+ it('given a path in the connection region, should sign the request and return the response', async () => {+ vi.mocked(fetch).mockResolvedValue(jsonResponse({ Functions: [] }));++ const result = await customLambdaCall({ auth: accessKey, server, input: {+ method: HttpMethod.GET,+ path: '2015-03-31/functions',+ queryParams: { MaxItems: '1' },+ } });++ expect(result.status).toBe(200);+ expect(result.body).toEqual({ Functions: [] });+ expect(fetch).toHaveBeenCalledWith(+ 'https://lambda.us-east-1.amazonaws.com/2015-03-31/functions?MaxItems=1',+ expect.objectContaining({+ method: HttpMethod.GET,+ headers: expect.objectContaining({+ authorization: expect.stringMatching(/^AWS4-HMAC-SHA256 /),+ host: 'lambda.us-east-1.amazonaws.com',+ }),+ }),+ );+ });++ it('given a China region, should target the China partition host', async () => {+ vi.mocked(fetch).mockResolvedValue(jsonResponse({}));++ await customLambdaCall({ auth: { ...accessKey, region: 'cn-north-1' }, server, input: { method: HttpMethod.GET, path: '/2015-03-31/functions' } });++ expect(fetch).toHaveBeenCalledWith(+ 'https://lambda.cn-north-1.amazonaws.com.cn/2015-03-31/functions',+ expect.anything(),+ );+ });++ it('given body, query, and headers as JSON strings, should send them parsed', async () => {+ vi.mocked(fetch).mockResolvedValue(jsonResponse({}));++ await customLambdaCall({ auth: accessKey, server, input: {+ method: HttpMethod.POST,+ path: '/2015-03-31/functions/billing/invocations',+ queryParams: '{"Qualifier":"live"}',+ headers: '{"X-Amz-Invocation-Type":"Event"}',+ body: '{"id":1}',+ } });++ expect(fetch).toHaveBeenCalledWith(+ 'https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/billing/invocations?Qualifier=live',+ expect.objectContaining({+ body: '{"id":1}',+ headers: expect.objectContaining({ 'x-amz-invocation-type': 'Event' }),+ }),+ );+ });++ it('given headers that are a JSON array, should reject them before sending', async () => {+ await expect(customLambdaCall({ auth: accessKey, server, input: {+ method: HttpMethod.GET,+ path: '/2015-03-31/functions',+ headers: '["a"]',+ } })).rejects.toThrow('Headers must be a JSON object.');+ expect(fetch).not.toHaveBeenCalled();+ });++ it('given a path that leaves the Lambda host, should reject it before sending', async () => {+ await expect(customLambdaCall({ auth: accessKey, server, input: {+ method: HttpMethod.GET,+ path: 'https://example.com/functions',+ } })).rejects.toThrow('InvalidPath');+ expect(fetch).not.toHaveBeenCalled();+ });++ it('given a backslash path, should reject it before sending', async () => {+ await expect(customLambdaCall({ auth: accessKey, server, input: {+ method: HttpMethod.POST,+ path: '/\\attacker.example/functions',+ body: { name: 'billing' },+ } })).rejects.toThrow('InvalidPath');+ expect(fetch).not.toHaveBeenCalled();+ });++ it('given a repeated query key, should sign every value', async () => {+ vi.mocked(fetch).mockResolvedValue(jsonResponse({}));++ await customLambdaCall({ auth: accessKey, server, input: {+ method: HttpMethod.GET,+ path: '/2015-03-31/functions?Marker=a&Marker=b',+ } });++ expect(fetch).toHaveBeenCalledWith(+ 'https://lambda.us-east-1.amazonaws.com/2015-03-31/functions?Marker=a&Marker=b',+ expect.anything(),+ );+ expect(signedQueries.at(-1)).toEqual({ Marker: ['a', 'b'] });+ });++ it('given a mixed-case Content-Type with a body, should send a single lowercase content-type', async () => {+ vi.mocked(fetch).mockResolvedValue(jsonResponse({}));++ await customLambdaCall({ auth: accessKey, server, input: {+ method: HttpMethod.POST,+ path: '/2015-03-31/functions',+ headers: { 'Content-Type': 'application/json; charset=utf-8' },+ body: { FunctionName: 'billing' },+ } });++ const sent = vi.mocked(fetch).mock.calls[0][1]?.headers as Record<string, string>;+ expect(Object.keys(sent).filter((key) => key.toLowerCase() === 'content-type')).toEqual(['content-type']);+ expect(sent['content-type']).toBe('application/json; charset=utf-8');+ });++ it('given a GET with the default empty body, should send no body and no content-type', async () => {+ vi.mocked(fetch).mockResolvedValue(jsonResponse({}));++ await customLambdaCall({ auth: accessKey, server, input: {+ method: HttpMethod.GET,+ path: '/2015-03-31/functions',+ body: {},+ } });++ const init = vi.mocked(fetch).mock.calls[0][1];+ expect(init?.body).toBeUndefined();+ expect(Object.keys(init?.headers ?? {})).not.toContain('content-type');+ });++ it('given a blank query value, should leave the key out', async () => {+ vi.mocked(fetch).mockResolvedValue(jsonResponse({}));++ await customLambdaCall({ auth: accessKey, server, input: {+ method: HttpMethod.GET,+ path: '/2015-03-31/functions',+ queryParams: { Marker: '', MaxItems: '5' },+ } });++ expect(fetch).toHaveBeenCalledWith(+ 'https://lambda.us-east-1.amazonaws.com/2015-03-31/functions?MaxItems=5',+ expect.anything(),+ );+ });++ it('given a space in the query, should send the same encoding that was signed', async () => {+ vi.mocked(fetch).mockResolvedValue(jsonResponse({}));++ await customLambdaCall({ auth: accessKey, server, input: {+ method: HttpMethod.GET,+ path: '/2015-03-31/functions',+ queryParams: { Marker: 'a b' },+ } });++ expect(fetch).toHaveBeenCalledWith(+ 'https://lambda.us-east-1.amazonaws.com/2015-03-31/functions?Marker=a%20b',+ expect.anything(),+ );+ });+ });+});++describe('IAM role credentials', () => {+ const role = { roleArn: 'arn:aws:iam::123456789012:role/lambda-runner', region: 'us-east-1' };++ beforeEach(() => {+ send.mockReset();+ stsSend.mockReset();+ vi.stubGlobal('fetch', vi.fn<(input: string, init?: RequestInit) => Promise<{ ok: boolean; json: () => Promise<{ token: string }> }>>());+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ clearCredentialsCache();+ });++ describe('when a role connection runs', () => {+ it('given a worker token, should request an OIDC token and assume the role before calling Lambda', async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ json: async () => ({ token: 'web-identity-token' }),+ });+ stsSend.mockResolvedValue({+ Credentials: {+ AccessKeyId: 'ASIA',+ SecretAccessKey: 'temporary-secret',+ SessionToken: 'session',+ Expiration: new Date(Date.now() + 60 * 60 * 1000),+ },+ });+ send.mockResolvedValue({ Functions: [] });++ await listFunctions({ auth: role, server });++ expect(fetch).toHaveBeenCalledWith('http://localhost/api/v1/worker/oidc-token', {+ method: 'POST',+ headers: {+ Authorization: 'Bearer worker-token',+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ audience: 'sts.amazonaws.com' }),+ });+ const assumed = stsSend.mock.calls[0][0] as { input: Record<string, unknown> };+ expect(assumed.input).toMatchObject({+ RoleArn: role.roleArn,+ RoleSessionName: 'activepieces-execution',+ WebIdentityToken: 'web-identity-token',+ DurationSeconds: 3600,+ });+ expect(send).toHaveBeenCalledOnce();+ });++ it('given an expired cache entry, should drop it before caching the next token', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ json: async () => ({ token: 'web-identity-token' }),+ });+ stsSend.mockResolvedValue({+ Credentials: {+ AccessKeyId: 'ASIA',+ SecretAccessKey: 'temporary-secret',+ SessionToken: 'session',+ Expiration: new Date('2026-01-01T01:00:00Z'),+ },+ });+ send.mockResolvedValue({ Functions: [] });++ await listFunctions({ auth: role, server });+ expect(cachedCredentialCount()).toBe(1);++ vi.setSystemTime(new Date('2026-01-01T00:56:00Z'));+ stsSend.mockResolvedValue({+ Credentials: {+ AccessKeyId: 'ASIA',+ SecretAccessKey: 'temporary-secret',+ SessionToken: 'session-2',+ Expiration: new Date('2026-01-01T02:00:00Z'),+ },+ });+ await listFunctions({ auth: role, server: { ...server, token: 'next-worker-token' } });++ expect(cachedCredentialCount()).toBe(1);+ expect(fetch).toHaveBeenCalledTimes(2);+ });+ });+});++describe('decodePayload', () => {+ it('given text that is not JSON, should return the raw text', () => {+ expect(decodePayload(new TextEncoder().encode('plain text'))).toBe('plain text');+ });+});++function jsonResponse(body: unknown): Response {+ return {+ ok: true,+ status: 200,+ headers: new Headers({ 'content-type': 'application/json' }),+ text: async () => JSON.stringify(body),+ } as Response;+}diff --git a/packages/pieces/community/amazon-lambda/src/lib/common/client.ts b/packages/pieces/community/amazon-lambda/src/lib/common/client.tsnew file mode 100644index 00000000000..9513b6eb286--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/common/client.ts@@ -0,0 +1,519 @@+import { Sha256 } from '@aws-crypto/sha256-js';+import {+ GetFunctionConfigurationCommand,+ InvokeCommand,+ LambdaClient,+ ListFunctionsCommand,+ type FunctionConfiguration,+ type InvocationType,+} from '@aws-sdk/client-lambda';+import { AssumeRoleWithWebIdentityCommand, STSClient } from '@aws-sdk/client-sts';+import { HttpMethod } from '@activepieces/pieces-common';+import type { ServerContext } from '@activepieces/pieces-framework';+import { HttpRequest as AwsHttpRequest } from '@smithy/protocol-http';+import { SignatureV4 } from '@smithy/signature-v4';++import { isOidcAuth, type LambdaAuthProps, type OidcAuthProps } from '../auth';+import { LambdaApiError, parseLambdaErrorBody } from './errors';+import { lambdaEndpoint } from './regions';++const AWS_STS_AUDIENCE = 'sts.amazonaws.com';+const DEFAULT_STS_DURATION_SECONDS = 3600;+const CREDENTIALS_EXPIRY_MARGIN_MS = 5 * 60 * 1000;+const STS_MAX_ATTEMPTS = 2;+const STS_REQUEST_TIMEOUT_MS = 10_000;+const STS_CONNECT_TIMEOUT_MS = 5_000;+const LIST_PAGE_SIZE = 50;+const MAX_FUNCTIONS = 10_000;+const BODY_METHODS = new Set<HttpMethod>([HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH]);++const credentialsCache = new Map<string, { credentials: AwsCredentials; expiresAtMS: number }>();++export async function listFunctions({+ auth,+ server,+}: {+ auth: LambdaAuthProps;+ server: ServerContext;+}): Promise<FunctionConfiguration[]> {+ const client = await createLambdaClient({ auth, server });+ const functions: FunctionConfiguration[] = [];+ let marker: string | undefined;+ try {+ do {+ const page = await client.send(new ListFunctionsCommand({ Marker: marker, MaxItems: LIST_PAGE_SIZE }));+ functions.push(...(page.Functions ?? []));+ if (functions.length > MAX_FUNCTIONS) {+ throw new LambdaApiError(+ undefined,+ 'TooManyFunctions',+ `This region lists more than ${MAX_FUNCTIONS} functions.`,+ );+ }+ if (!page.NextMarker || page.NextMarker === marker) break;+ marker = page.NextMarker;+ } while (marker);+ return functions;+ } catch (error) {+ throw LambdaApiError.from(error);+ }+}++export async function invokeLambda({+ auth,+ server,+ input,+}: {+ auth: LambdaAuthProps;+ server: ServerContext;+ input: InvokeFunctionInput;+}): Promise<InvokeFunctionResult> {+ const client = await createLambdaClient({ auth, server });+ try {+ const response = await client.send(new InvokeCommand({+ FunctionName: requireFunctionName(input.functionName),+ InvocationType: input.invocationType,+ Qualifier: blankToUndefined(input.qualifier),+ Payload: encodePayload(input.payload),+ }));+ const payload = decodePayload(response.Payload);+ if (response.FunctionError && input.failOnFunctionError) {+ throw new LambdaApiError(+ response.StatusCode,+ response.FunctionError,+ `The function failed: ${functionErrorMessage(payload)}`,+ );+ }+ return {+ statusCode: response.StatusCode ?? null,+ functionError: response.FunctionError ?? null,+ executedVersion: response.ExecutedVersion ?? null,+ payload,+ };+ } catch (error) {+ throw LambdaApiError.from(error);+ }+}++export async function getFunctionDetails({+ auth,+ server,+ input,+}: {+ auth: LambdaAuthProps;+ server: ServerContext;+ input: GetFunctionDetailsInput;+}): Promise<FunctionDetails> {+ const client = await createLambdaClient({ auth, server });+ try {+ const config = await client.send(new GetFunctionConfigurationCommand({+ FunctionName: requireFunctionName(input.functionName),+ Qualifier: blankToUndefined(input.qualifier),+ }));+ return {+ functionArn: config.FunctionArn ?? null,+ functionName: config.FunctionName ?? null,+ runtime: config.Runtime ?? null,+ handler: config.Handler ?? null,+ memorySize: config.MemorySize ?? null,+ timeout: config.Timeout ?? null,+ environment: input.includeEnvironment ? config.Environment?.Variables ?? {} : null,+ role: config.Role ?? null,+ lastModified: config.LastModified ?? null,+ state: config.State ?? null,+ version: config.Version ?? null,+ description: config.Description ?? null,+ };+ } catch (error) {+ throw LambdaApiError.from(error);+ }+}++export async function customLambdaCall({+ auth,+ server,+ input,+}: {+ auth: LambdaAuthProps;+ server: ServerContext;+ input: CustomLambdaCallInput;+}): Promise<{ status: number; headers: Record<string, string>; body: unknown }> {+ const credentials = await resolveCredentials({ auth, server });+ const url = lambdaRequestUrl({ region: auth.region, path: input.path });+ appendQuery({ url, queryParams: parseJsonObject({ value: input.queryParams, field: 'Query parameters' }) });++ const body = parseJsonInput({ value: input.body, field: 'Body' });+ const bodyString = body === undefined || !BODY_METHODS.has(input.method) ? undefined : JSON.stringify(body);+ const headers = userHeaders(parseJsonObject({ value: input.headers, field: 'Headers' }));+ if (bodyString && !headers['content-type']) headers['content-type'] = 'application/json';++ const signed = await signRequest({+ credentials,+ region: auth.region,+ method: input.method,+ url,+ headers,+ body: bodyString,+ });++ try {+ const response = await fetch(signedRequestUrl(url), {+ method: input.method,+ headers: signed,+ body: bodyString,+ redirect: 'manual',+ signal: AbortSignal.timeout(clampTimeout(input.timeoutSeconds)),+ });+ const responseBody = await readFetchBody(response);+ if (!response.ok) {+ const parsed = parseLambdaErrorBody(responseBody);+ throw new LambdaApiError(response.status, parsed.name, parsed.message);+ }+ return {+ status: response.status,+ headers: headersFromFetch(response),+ body: responseBody,+ };+ } catch (error) {+ throw LambdaApiError.from(error);+ }+}++export function decodePayload(payload: Uint8Array | undefined): unknown {+ if (!payload || payload.byteLength === 0) return null;+ const text = new TextDecoder().decode(payload);+ try {+ const parsed: unknown = JSON.parse(text);+ return parsed;+ } catch {+ return text;+ }+}++async function createLambdaClient({ auth, server }: { auth: LambdaAuthProps; server: ServerContext }): Promise<LambdaClient> {+ const credentials = await resolveCredentials({ auth, server });+ return new LambdaClient({ region: auth.region, credentials });+}++async function resolveCredentials({ auth, server }: { auth: LambdaAuthProps; server: ServerContext }): Promise<AwsCredentials> {+ if (isOidcAuth(auth)) return getTemporaryCredentials({ auth, server });+ const accessKeyId = auth.accessKeyId?.trim();+ const secretAccessKey = auth.secretAccessKey?.trim();+ if (!accessKeyId || !secretAccessKey) {+ throw new LambdaApiError(undefined, 'MissingCredentials', 'Access Key ID and Secret Access Key are required.');+ }+ return { accessKeyId, secretAccessKey };+}++async function getTemporaryCredentials({ auth, server }: { auth: OidcAuthProps; server: ServerContext }): Promise<AwsCredentials> {+ const roleArn = auth.roleArn?.trim();+ if (!roleArn) {+ throw new LambdaApiError(undefined, 'MissingRoleArn', 'Role ARN is required for IAM role authentication.');+ }+ const duration = DEFAULT_STS_DURATION_SECONDS;+ const cacheKey = `${server.token}:${roleArn}:${auth.region}:${duration}`;+ const cached = takeFreshCredentials({ cacheKey });+ if (cached) return cached;++ const tokenUrl = `${server.apiUrl.endsWith('/') ? server.apiUrl : `${server.apiUrl}/`}v1/worker/oidc-token`;+ const response = await fetch(tokenUrl, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${server.token}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ audience: AWS_STS_AUDIENCE }),+ });+ if (!response.ok) {+ throw new LambdaApiError(response.status, 'OidcTokenError', `Failed to get an OIDC token: ${response.statusText}`);+ }+ const token = readOidcToken(await response.json());++ const sts = new STSClient({+ region: auth.region,+ maxAttempts: STS_MAX_ATTEMPTS,+ requestHandler: { requestTimeout: STS_REQUEST_TIMEOUT_MS, connectionTimeout: STS_CONNECT_TIMEOUT_MS },+ });+ try {+ const assumed = await sts.send(new AssumeRoleWithWebIdentityCommand({+ RoleArn: roleArn,+ RoleSessionName: 'activepieces-execution',+ WebIdentityToken: token,+ DurationSeconds: duration,+ }));+ const issued = assumed.Credentials;+ if (!issued?.AccessKeyId || !issued.SecretAccessKey) {+ throw new LambdaApiError(undefined, 'AssumeRoleFailed', 'Failed to assume role: no credentials returned.');+ }+ const credentials: AwsCredentials = {+ accessKeyId: issued.AccessKeyId,+ secretAccessKey: issued.SecretAccessKey,+ sessionToken: issued.SessionToken,+ };+ const expiresAtMS = issued.Expiration?.getTime() ?? Date.now() + duration * 1000;+ if (expiresAtMS - Date.now() > CREDENTIALS_EXPIRY_MARGIN_MS) {+ credentialsCache.set(cacheKey, { credentials, expiresAtMS });+ }+ return credentials;+ } catch (error) {+ throw LambdaApiError.from(error);+ }+}++async function signRequest({+ credentials,+ region,+ method,+ url,+ headers,+ body,+}: {+ credentials: AwsCredentials;+ region: string;+ method: string;+ url: URL;+ headers: Record<string, string>;+ body?: string;+}): Promise<Record<string, string>> {+ const awsRequest = new AwsHttpRequest({+ method,+ protocol: url.protocol,+ hostname: url.hostname,+ port: url.port ? Number(url.port) : undefined,+ path: url.pathname,+ query: signedQuery(url),+ headers: { ...headers, host: url.host },+ body,+ });+ const signer = new SignatureV4({+ credentials,+ region,+ service: 'lambda',+ sha256: Sha256,+ });+ const signed = await signer.sign(awsRequest);+ const signedHeaders: Record<string, string> = {};+ for (const [key, value] of Object.entries(signed.headers)) {+ if (value === undefined) continue;+ signedHeaders[key] = Array.isArray(value) ? value.join(',') : String(value);+ }+ return signedHeaders;+}++function requireFunctionName(functionName: string): string {+ const trimmed = functionName.trim();+ if (!trimmed) {+ throw new LambdaApiError(undefined, 'InvalidFunctionName', 'Function name or ARN is required.');+ }+ return trimmed;+}++function encodePayload(payload: unknown): Uint8Array | undefined {+ const parsed = parseJsonInput({ value: payload, field: 'Payload' });+ if (parsed === undefined) return undefined;+ return new TextEncoder().encode(JSON.stringify(parsed));+}++function parseJsonInput({ value, field }: { value: unknown; field: string }): unknown {+ if (typeof value !== 'string') return value ?? undefined;+ if (!value.trim()) return undefined;+ try {+ const parsed: unknown = JSON.parse(value);+ return parsed;+ } catch {+ throw new LambdaApiError(undefined, 'InvalidJson', `${field} must be valid JSON.`);+ }+}++function parseJsonObject({ value, field }: { value: unknown; field: string }): Record<string, unknown> | undefined {+ const parsed = parseJsonInput({ value, field });+ if (parsed === undefined) return undefined;+ if (!isRecord(parsed)) {+ throw new LambdaApiError(undefined, 'InvalidJson', `${field} must be a JSON object.`);+ }+ return parsed;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function readOidcToken(body: unknown): string {+ const token = isRecord(body) ? body['token'] : undefined;+ if (typeof token !== 'string' || !token) {+ throw new LambdaApiError(undefined, 'OidcTokenError', 'Failed to get an OIDC token: the response had no token.');+ }+ return token;+}++function functionErrorMessage(payload: unknown): string {+ if (isRecord(payload)) {+ const message = payload['errorMessage'];+ const type = payload['errorType'];+ if (typeof message === 'string' && message) {+ return typeof type === 'string' && type ? `${type}: ${message}` : message;+ }+ }+ return typeof payload === 'string' && payload ? payload : JSON.stringify(payload);+}++export function cachedCredentialCount(): number {+ return credentialsCache.size;+}++export function clearCredentialsCache(): void {+ credentialsCache.clear();+}++function takeFreshCredentials({ cacheKey }: { cacheKey: string }): AwsCredentials | undefined {+ const now = Date.now();+ let fresh: AwsCredentials | undefined;+ for (const [key, entry] of credentialsCache) {+ if (entry.expiresAtMS - now <= CREDENTIALS_EXPIRY_MARGIN_MS) {+ credentialsCache.delete(key);+ continue;+ }+ if (key === cacheKey) fresh = entry.credentials;+ }+ return fresh;+}++function lambdaRequestUrl({ region, path }: { region: string; path: string }): URL {+ const endpoint = lambdaEndpoint(region);+ const url = new URL(normalizePath(path), endpoint.url);+ if (url.origin !== endpoint.url) {+ throw new LambdaApiError(+ undefined,+ 'InvalidPath',+ 'Path must be a Lambda API path such as /2015-03-31/functions.',+ );+ }+ return url;+}++function signedQuery(url: URL): Record<string, string | string[]> {+ const grouped = new Map<string, string[]>();+ for (const [key, value] of url.searchParams) {+ grouped.set(key, [...(grouped.get(key) ?? []), value]);+ }+ return Object.fromEntries(+ [...grouped].map(([key, values]) => [key, values.length === 1 ? values[0] : values]),+ );+}++function signedRequestUrl(url: URL): string {+ const pathUrl = `${url.origin}${url.pathname}`;+ if (!url.search) return pathUrl;+ return `${pathUrl}${url.search.replaceAll('+', '%20')}`;+}++function normalizePath(path: string): string {+ const trimmed = path.trim();+ if (!trimmed || trimmed.includes('://') || trimmed.startsWith('//')) {+ throw new LambdaApiError(+ undefined,+ 'InvalidPath',+ 'Path must be a Lambda API path such as /2015-03-31/functions.',+ );+ }+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;+}++function appendQuery({ url, queryParams }: { url: URL; queryParams: Record<string, unknown> | undefined }): void {+ if (!queryParams) return;+ for (const [key, value] of Object.entries(queryParams)) {+ if (value === undefined || value === null || value === '') continue;+ url.searchParams.append(key, String(value));+ }+}++function userHeaders(headers: Record<string, unknown> | undefined): Record<string, string> {+ const out: Record<string, string> = {};+ if (!headers) return out;+ for (const [key, value] of Object.entries(headers)) {+ if (value === undefined || value === null) continue;+ if (/^(host|authorization)$/i.test(key)) continue;+ out[key.toLowerCase()] = String(value);+ }+ return out;+}++function headersFromFetch(response: Response): Record<string, string> {+ const out: Record<string, string> = {};+ response.headers.forEach((value, key) => {+ out[key] = value;+ });+ return out;+}++async function readFetchBody(response: Response): Promise<unknown> {+ const text = await response.text();+ if (!text) return {};+ try {+ const parsed: unknown = JSON.parse(text);+ return parsed;+ } catch {+ return text;+ }+}++function blankToUndefined(value: string | undefined): string | undefined {+ const trimmed = value?.trim();+ return trimmed ? trimmed : undefined;+}++function clampTimeout(seconds: number | undefined): number {+ const value = seconds === undefined || Number.isNaN(seconds) ? 30 : seconds;+ return Math.min(Math.max(value, 1), 900) * 1000;+}++type AwsCredentials = {+ accessKeyId: string;+ secretAccessKey: string;+ sessionToken?: string;+};++export type InvokeFunctionInput = {+ functionName: string;+ invocationType: InvocationType;+ qualifier?: string;+ payload?: unknown;+ failOnFunctionError: boolean;+};++export type GetFunctionDetailsInput = {+ functionName: string;+ qualifier?: string;+ includeEnvironment: boolean;+};++export type InvokeFunctionResult = {+ statusCode: number | null;+ functionError: string | null;+ executedVersion: string | null;+ payload: unknown;+};++export type FunctionDetails = {+ functionArn: string | null;+ functionName: string | null;+ runtime: string | null;+ handler: string | null;+ memorySize: number | null;+ timeout: number | null;+ environment: Record<string, string> | null;+ role: string | null;+ lastModified: string | null;+ state: string | null;+ version: string | null;+ description: string | null;+};++export type CustomLambdaCallInput = {+ method: HttpMethod;+ path: string;+ queryParams?: unknown;+ headers?: unknown;+ body?: unknown;+ timeoutSeconds?: number;+};diff --git a/packages/pieces/community/amazon-lambda/src/lib/common/errors.ts b/packages/pieces/community/amazon-lambda/src/lib/common/errors.tsnew file mode 100644index 00000000000..e14486ee115--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/common/errors.ts@@ -0,0 +1,56 @@+import { HttpError } from '@activepieces/pieces-common';++export class LambdaApiError extends Error {+ constructor(+ readonly status: number | undefined,+ name: string,+ detail: string,+ ) {+ super(status === undefined ? `${name}: ${detail}` : `AWS Lambda API returned ${status} (${name}): ${detail}`);+ this.name = name;+ }++ static from(error: unknown): LambdaApiError {+ if (error instanceof LambdaApiError) return error;+ if (error instanceof HttpError) {+ const { status, body } = error.response;+ const parsed = parseLambdaErrorBody(body);+ return new LambdaApiError(status, parsed.name, parsed.message);+ }+ const name = readString({ value: error, key: 'name' });+ return new LambdaApiError(+ readStatus(error),+ name && name !== 'Error' ? name : 'LambdaError',+ readString({ value: error, key: 'message' }) || 'Unexpected AWS Lambda error',+ );+ }+}++export function parseLambdaErrorBody(body: unknown): { name: string; message: string } {+ if (body && typeof body === 'object') {+ const message = Reflect.get(body, 'Message') ?? Reflect.get(body, 'message');+ const name = Reflect.get(body, '__type') ?? Reflect.get(body, 'Type') ?? Reflect.get(body, 'Code') ?? Reflect.get(body, 'code');+ return {+ name: typeof name === 'string' && name ? name : 'LambdaError',+ message: typeof message === 'string' && message ? message : JSON.stringify(body),+ };+ }+ return {+ name: 'LambdaError',+ message: typeof body === 'string' && body ? body : JSON.stringify(body ?? null),+ };+}++function readString({ value, key }: { value: unknown; key: string }): string | undefined {+ if (typeof value !== 'object' || value === null) return undefined;+ const field: unknown = Reflect.get(value, key);+ return typeof field === 'string' ? field : undefined;+}++function readStatus(error: unknown): number | undefined {+ if (typeof error !== 'object' || error === null) return undefined;+ const metadata: unknown = Reflect.get(error, '$metadata');+ if (typeof metadata !== 'object' || metadata === null) return undefined;+ const status: unknown = Reflect.get(metadata, 'httpStatusCode');+ return typeof status === 'number' ? status : undefined;+}diff --git a/packages/pieces/community/amazon-lambda/src/lib/common/regions.ts b/packages/pieces/community/amazon-lambda/src/lib/common/regions.tsnew file mode 100644index 00000000000..53db6098bc6--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/common/regions.ts@@ -0,0 +1,38 @@+export function lambdaEndpoint(region: string): { host: string; url: string } {+ const host = region.startsWith('cn-')+ ? `lambda.${region}.amazonaws.com.cn`+ : `lambda.${region}.amazonaws.com`;+ return { host, url: `https://${host}` };+}++export const AWS_REGIONS: { label: string; value: string }[] = [+ { label: 'US East (N. Virginia) [us-east-1]', value: 'us-east-1' },+ { label: 'US East (Ohio) [us-east-2]', value: 'us-east-2' },+ { label: 'US West (N. California) [us-west-1]', value: 'us-west-1' },+ { label: 'US West (Oregon) [us-west-2]', value: 'us-west-2' },+ { label: 'Africa (Cape Town) [af-south-1]', value: 'af-south-1' },+ { label: 'Asia Pacific (Hong Kong) [ap-east-1]', value: 'ap-east-1' },+ { label: 'Asia Pacific (Hyderabad) [ap-south-2]', value: 'ap-south-2' },+ { label: 'Asia Pacific (Jakarta) [ap-southeast-3]', value: 'ap-southeast-3' },+ { label: 'Asia Pacific (Melbourne) [ap-southeast-4]', value: 'ap-southeast-4' },+ { label: 'Asia Pacific (Mumbai) [ap-south-1]', value: 'ap-south-1' },+ { label: 'Asia Pacific (Osaka) [ap-northeast-3]', value: 'ap-northeast-3' },+ { label: 'Asia Pacific (Seoul) [ap-northeast-2]', value: 'ap-northeast-2' },+ { label: 'Asia Pacific (Singapore) [ap-southeast-1]', value: 'ap-southeast-1' },+ { label: 'Asia Pacific (Sydney) [ap-southeast-2]', value: 'ap-southeast-2' },+ { label: 'Asia Pacific (Tokyo) [ap-northeast-1]', value: 'ap-northeast-1' },+ { label: 'Canada (Central) [ca-central-1]', value: 'ca-central-1' },+ { label: 'Europe (Frankfurt) [eu-central-1]', value: 'eu-central-1' },+ { label: 'Europe (Ireland) [eu-west-1]', value: 'eu-west-1' },+ { label: 'Europe (London) [eu-west-2]', value: 'eu-west-2' },+ { label: 'Europe (Milan) [eu-south-1]', value: 'eu-south-1' },+ { label: 'Europe (Paris) [eu-west-3]', value: 'eu-west-3' },+ { label: 'Europe (Spain) [eu-south-2]', value: 'eu-south-2' },+ { label: 'Europe (Stockholm) [eu-north-1]', value: 'eu-north-1' },+ { label: 'Europe (Zurich) [eu-central-2]', value: 'eu-central-2' },+ { label: 'Middle East (Bahrain) [me-south-1]', value: 'me-south-1' },+ { label: 'Middle East (UAE) [me-central-1]', value: 'me-central-1' },+ { label: 'South America (São Paulo) [sa-east-1]', value: 'sa-east-1' },+ { label: 'China (Beijing) [cn-north-1]', value: 'cn-north-1' },+ { label: 'China (Ningxia) [cn-northwest-1]', value: 'cn-northwest-1' },+];diff --git a/packages/pieces/community/amazon-lambda/src/lib/output-schemas.ts b/packages/pieces/community/amazon-lambda/src/lib/output-schemas.tsnew file mode 100644index 00000000000..c64fe494ef1--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/output-schemas.ts@@ -0,0 +1,27 @@+import { OutputSchema } from '@activepieces/pieces-framework';++export const invokeFunctionOutputSchema: OutputSchema = {+ fields: [+ { key: 'statusCode', label: 'Status Code', format: 'number' },+ { key: 'functionError', label: 'Function Error' },+ { key: 'executedVersion', label: 'Executed Version' },+ { key: 'payload', label: 'Payload' },+ ],+};++export const getFunctionDetailsOutputSchema: OutputSchema = {+ fields: [+ { key: 'functionName', label: 'Function Name' },+ { key: 'functionArn', label: 'Function ARN' },+ { key: 'description', label: 'Description' },+ { key: 'runtime', label: 'Runtime' },+ { key: 'handler', label: 'Handler' },+ { key: 'memorySize', label: 'Memory (MB)', format: 'number' },+ { key: 'timeout', label: 'Timeout (seconds)', format: 'number' },+ { key: 'role', label: 'Execution Role ARN' },+ { key: 'state', label: 'State' },+ { key: 'version', label: 'Version' },+ { key: 'lastModified', label: 'Last Modified' },+ { key: 'environment', label: 'Environment Variables', dynamicKey: true },+ ],+};diff --git a/packages/pieces/community/amazon-lambda/src/lib/triggers/__tests__/new-function-created.test.ts b/packages/pieces/community/amazon-lambda/src/lib/triggers/__tests__/new-function-created.test.tsnew file mode 100644index 00000000000..e9f28b976bf--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/triggers/__tests__/new-function-created.test.ts@@ -0,0 +1,204 @@+import type { Store } from '@activepieces/pieces-framework';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { listFunctions } = vi.hoisted(() => ({+ listFunctions: vi.fn<(auth: unknown, server: unknown) => Promise<unknown>>(),+}));++vi.mock('../../common/client', () => ({ listFunctions }));++const {+ newFunctionCreated,+ remember,+ SEEN_FUNCTION_ARNS_KEY,+} = await import('../new-function-created');++function memoryStore(initial: Record<string, unknown> = {}): Store & { data: Record<string, unknown> } {+ const data = { ...initial };+ return {+ data,+ async get<T>(key: string) {+ return (key in data ? data[key] : null) as T | null;+ },+ async put<T>(key: string, value: T) {+ data[key] = value;+ return value;+ },+ async delete(key: string) {+ delete data[key];+ },+ };+}++const billing = {+ FunctionName: 'billing',+ FunctionArn: 'arn:aws:lambda:us-east-1:123:function:billing',+ Runtime: 'nodejs20.x',+ LastModified: '2026-09-28T12:00:00.000+0000',+};+const invoices = {+ FunctionName: 'invoices',+ FunctionArn: 'arn:aws:lambda:us-east-1:123:function:invoices',+ Runtime: 'nodejs20.x',+ LastModified: '2026-09-28T13:00:00.000+0000',+};++describe('remember', () => {+ it('should store the current ARNs and emit nothing when the trigger is enabled', async () => {+ const store = memoryStore();++ const emitted = await remember({ store, functions: [billing], initializeOnly: true });++ expect(emitted).toEqual([]);+ expect(savedArns(store)).toEqual([billing.FunctionArn]);+ });++ it('should emit a new ARN once and stay quiet on the next poll', async () => {+ const store = memoryStore();+ await remember({ store, functions: [billing], initializeOnly: true });+ const updated = { ...billing, LastModified: '2026-09-28T18:00:00.000+0000' };++ const emitted = await remember({ store, functions: [updated, invoices], initializeOnly: false });++ expect(emitted).toEqual([invoices]);+ expect(savedArns(store)).toEqual([billing.FunctionArn, invoices.FunctionArn]);++ const second = await remember({ store, functions: [updated, invoices], initializeOnly: false });++ expect(second).toEqual([]);+ });++ it('should forget a deleted ARN so a function recreated with that name fires again', async () => {+ const store = memoryStore();+ await remember({ store, functions: [billing, invoices], initializeOnly: true });++ expect(await remember({ store, functions: [billing], initializeOnly: false })).toEqual([]);+ expect(savedArns(store)).toEqual([billing.FunctionArn]);++ expect(await remember({ store, functions: [billing, invoices], initializeOnly: false })).toEqual([invoices]);+ });++ it('should split a snapshot that would exceed the store value limit and drop the replaced chunks', async () => {+ const arnAt = (index: number) => `arn:aws:lambda:us-east-1:123456789012:function:fn-${String(index).padStart(5, '0')}`;+ const itemBytes = Buffer.byteLength(JSON.stringify(arnAt(0)), 'utf8') + 1;+ const fitting = Math.floor((512 * 1024 - 2) / itemBytes);+ const arns = Array.from({ length: fitting + 1 }, (_, index) => arnAt(index));+ const functions = arns.map((FunctionArn) => ({ FunctionArn }));+ const store = memoryStore();++ const emitted = await remember({ store, functions, initializeOnly: true });++ expect(emitted).toEqual([]);+ const chunks = chunkValues(store);+ expect(chunks).toHaveLength(2);+ chunks.forEach((chunk) => expect(Buffer.byteLength(JSON.stringify(chunk), 'utf8')).toBeLessThanOrEqual(512 * 1024));+ expect(savedArns(store)).toEqual(arns);++ const created = { FunctionArn: arnAt(arns.length) };+ const next = await remember({ store, functions: [...functions, created], initializeOnly: false });++ expect(next).toEqual([created]);+ expect(chunkValues(store)).toHaveLength(2);+ });++ it('should keep the previous snapshot when a write fails so the next poll emits again', async () => {+ const store = memoryStore();+ await remember({ store, functions: [billing], initializeOnly: true });+ const put = store.put.bind(store);+ store.put = async <T>(key: string, value: T) => {+ if (key === SEEN_FUNCTION_ARNS_KEY) throw new Error('store unavailable');+ return put(key, value);+ };++ await expect(remember({ store, functions: [billing, invoices], initializeOnly: false })).rejects.toThrow('store unavailable');+ expect(savedArns(store)).toEqual([billing.FunctionArn]);++ store.put = put;+ expect(await remember({ store, functions: [billing, invoices], initializeOnly: false })).toEqual([invoices]);+ });++ it('should still emit when deleting the replaced chunks fails', async () => {+ const store = memoryStore();+ await remember({ store, functions: [billing], initializeOnly: true });+ store.delete = async () => {+ throw new Error('delete failed');+ };++ expect(await remember({ store, functions: [billing, invoices], initializeOnly: false })).toEqual([invoices]);+ expect(savedArns(store)).toEqual([billing.FunctionArn, invoices.FunctionArn]);+ });++ it('should stay quiet on the first poll when enabling never ran', async () => {+ const store = memoryStore();++ const emitted = await remember({ store, functions: [billing], initializeOnly: false });++ expect(emitted).toEqual([]);+ expect(savedArns(store)).toEqual([billing.FunctionArn]);+ });+});++describe('newFunctionCreated', () => {+ const auth = { props: { accessKeyId: 'AKIA', secretAccessKey: 'secret', region: 'us-east-1' } };+ const server = { apiUrl: 'http://localhost/api/', publicUrl: 'http://localhost', token: 'worker-token' };++ beforeEach(() => {+ listFunctions.mockReset();+ });++ it('should record existing functions on enable and keep them through disable', async () => {+ listFunctions.mockResolvedValue([billing]);+ const store = memoryStore();++ await newFunctionCreated.onEnable({ auth, store, server, propsValue: {} } as never);+ expect(savedArns(store)).toEqual([billing.FunctionArn]);++ await newFunctionCreated.onDisable({ auth, store, server, propsValue: {} } as never);+ expect(savedArns(store)).toEqual([billing.FunctionArn]);+ });++ it('should keep the saved snapshot on republish so functions created since the last poll still fire', async () => {+ listFunctions.mockResolvedValue([billing]);+ const store = memoryStore();+ await newFunctionCreated.onEnable({ auth, store, server, propsValue: {} } as never);++ listFunctions.mockResolvedValue([billing, invoices]);+ await newFunctionCreated.onDisable({ auth, store, server, propsValue: {} } as never);+ await newFunctionCreated.onEnable({ auth, store, server, propsValue: {}, isRepublish: true } as never);++ expect(savedArns(store)).toEqual([billing.FunctionArn]);+ expect(await newFunctionCreated.run({ auth, store, server, propsValue: {} } as never)).toEqual([invoices]);+ });++ it('should take a fresh snapshot on a normal enable', async () => {+ listFunctions.mockResolvedValue([billing]);+ const store = memoryStore();+ await newFunctionCreated.onEnable({ auth, store, server, propsValue: {} } as never);++ listFunctions.mockResolvedValue([billing, invoices]);+ await newFunctionCreated.onEnable({ auth, store, server, propsValue: {} } as never);++ expect(savedArns(store)).toEqual([billing.FunctionArn, invoices.FunctionArn]);+ });++ it('should return a sample of current functions from test without changing the snapshot', async () => {+ listFunctions.mockResolvedValue([billing, invoices]);+ const store = memoryStore();++ const sample = await newFunctionCreated.test({ auth, store, server, propsValue: {} } as never);++ expect(sample).toEqual([billing, invoices]);+ expect(store.data).toEqual({});+ });+});++function savedArns(store: { data: Record<string, unknown> }): string[] {+ const pointer = store.data[SEEN_FUNCTION_ARNS_KEY] as { snapshotId: string; chunkCount: number };+ return Array.from({ length: pointer.chunkCount }, (_, index) => store.data[`${SEEN_FUNCTION_ARNS_KEY}:${pointer.snapshotId}:${index}`] as string[]).flat();+}++function chunkValues(store: { data: Record<string, unknown> }): unknown[] {+ return Object.entries(store.data)+ .filter(([key]) => key.startsWith(`${SEEN_FUNCTION_ARNS_KEY}:`))+ .map(([, value]) => value);+}diff --git a/packages/pieces/community/amazon-lambda/src/lib/triggers/new-function-created.ts b/packages/pieces/community/amazon-lambda/src/lib/triggers/new-function-created.tsnew file mode 100644index 00000000000..a4ae8457987--- /dev/null+++ b/packages/pieces/community/amazon-lambda/src/lib/triggers/new-function-created.ts@@ -0,0 +1,149 @@+import { randomUUID } from 'node:crypto';++import { createTrigger, TriggerStrategy, type Store } from '@activepieces/pieces-framework';+import type { FunctionConfiguration } from '@aws-sdk/client-lambda';++import { awsLambdaCombinedAuth } from '../auth';+import { listFunctions } from '../common/client';++export async function remember({+ store,+ functions,+ initializeOnly,+}: {+ store: Store;+ functions: FunctionConfiguration[];+ initializeOnly: boolean;+}): Promise<FunctionConfiguration[]> {+ const currentArns = uniqueArns(functions.flatMap((fn) => (fn.FunctionArn ? [fn.FunctionArn] : [])));+ const pointer = await readPointer(store);+ const previous = initializeOnly || pointer === null ? null : await readSnapshot({ store, pointer });+ await writeSnapshot({ store, arns: currentArns, replaced: pointer });+ if (previous == null) return [];++ const seen = new Set(previous);+ return functions.filter((fn) => fn.FunctionArn && !seen.has(fn.FunctionArn));+}++function chunkKey({ snapshotId, index }: { snapshotId: string; index: number }): string {+ return `${SEEN_FUNCTION_ARNS_KEY}:${snapshotId}:${index}`;+}++async function readPointer(store: Store): Promise<SnapshotPointer | null> {+ const pointer = await store.get<unknown>(SEEN_FUNCTION_ARNS_KEY);+ return isSnapshotPointer(pointer) ? pointer : null;+}++async function readSnapshot({ store, pointer }: { store: Store; pointer: SnapshotPointer }): Promise<string[]> {+ const chunks = await Promise.all(+ Array.from({ length: pointer.chunkCount }, (_, index) => store.get<string[]>(chunkKey({ snapshotId: pointer.snapshotId, index }))),+ );+ if (chunks.some((chunk) => chunk == null)) {+ throw new Error('The saved function snapshot is incomplete. The next check will retry.');+ }+ return chunks.flatMap((chunk) => chunk ?? []);+}++async function writeSnapshot({+ store,+ arns,+ replaced,+}: {+ store: Store;+ arns: string[];+ replaced: SnapshotPointer | null;+}): Promise<void> {+ const snapshotId = randomUUID();+ const chunks = chunkArns(arns);+ for (const [index, chunk] of chunks.entries()) {+ await store.put(chunkKey({ snapshotId, index }), chunk);+ }+ await store.put<SnapshotPointer>(SEEN_FUNCTION_ARNS_KEY, { snapshotId, chunkCount: chunks.length });+ if (replaced === null) return;+ await Promise.all(+ Array.from({ length: replaced.chunkCount }, (_, index) =>+ store.delete(chunkKey({ snapshotId: replaced.snapshotId, index })).catch(() => undefined),+ ),+ );+}++function isSnapshotPointer(value: unknown): value is SnapshotPointer {+ if (typeof value !== 'object' || value === null) return false;+ const snapshotId: unknown = Reflect.get(value, 'snapshotId');+ const chunkCount: unknown = Reflect.get(value, 'chunkCount');+ return typeof snapshotId === 'string' && typeof chunkCount === 'number' && Number.isInteger(chunkCount) && chunkCount > 0;+}++function chunkArns(arns: string[]): string[][] {+ if (arns.length === 0) return [[]];+ const chunks: string[][] = [];+ let current: string[] = [];+ let bytes = 2;+ for (const arn of arns) {+ const itemBytes = Buffer.byteLength(JSON.stringify(arn), 'utf8');+ const separator = current.length === 0 ? 0 : 1;+ if (current.length > 0 && bytes + separator + itemBytes > STORE_VALUE_MAX_BYTES) {+ chunks.push(current);+ current = [arn];+ bytes = 2 + itemBytes;+ continue;+ }+ current.push(arn);+ bytes += separator + itemBytes;+ }+ chunks.push(current);+ return chunks;+}++function uniqueArns(arns: string[]): string[] {+ return [...new Set(arns)];+}++const STORE_VALUE_MAX_BYTES = 512 * 1024;++export const SEEN_FUNCTION_ARNS_KEY = 'seen-function-arns';++export const newFunctionCreated = createTrigger({+ name: 'newFunctionCreated',+ displayName: 'New Function Created',+ description: 'Fires when a Lambda function ARN appears that was not present the last time this trigger ran. Enabling it records the current functions and stays quiet.',+ auth: awsLambdaCombinedAuth,+ requireAuth: true,+ type: TriggerStrategy.POLLING,+ classification: 'READ',+ aiMetadata: {+ description:+ 'Starts a flow once for each AWS Lambda function that appears in the connection\'s region since the last check. Functions that already existed when the trigger was turned on are ignored.',+ },+ props: {},+ sampleData: {+ FunctionName: 'billing-webhook',+ FunctionArn: 'arn:aws:lambda:us-east-1:123456789012:function:billing-webhook',+ Runtime: 'nodejs20.x',+ Handler: 'index.handler',+ LastModified: '2026-09-28T12:00:00.000+0000',+ },+ async onEnable(context) {+ if (context.isRepublish === true && (await readPointer(context.store)) !== null) {+ return;+ }+ const functions = await listFunctions({ auth: context.auth.props, server: context.server });+ await remember({ store: context.store, functions, initializeOnly: true });+ },+ async onDisable() {+ return;+ },+ async run(context) {+ const functions = await listFunctions({ auth: context.auth.props, server: context.server });+ return remember({ store: context.store, functions, initializeOnly: false });+ },+ async test(context) {+ const functions = await listFunctions({ auth: context.auth.props, server: context.server });+ return functions.slice(0, 10);+ },+});++type SnapshotPointer = {+ snapshotId: string;+ chunkCount: number;+};diff --git a/packages/pieces/community/amazon-lambda/tsconfig.json b/packages/pieces/community/amazon-lambda/tsconfig.jsonnew file mode 100644index 00000000000..eff240ac143--- /dev/null+++ b/packages/pieces/community/amazon-lambda/tsconfig.json@@ -0,0 +1,20 @@+{+ "extends": "../../../../tsconfig.base.json",+ "compilerOptions": {+ "module": "commonjs",+ "forceConsistentCasingInFileNames": true,+ "strict": true,+ "importHelpers": true,+ "noImplicitOverride": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true,+ "noPropertyAccessFromIndexSignature": true+ },+ "files": [],+ "include": [],+ "references": [+ {+ "path": "./tsconfig.lib.json"+ }+ ]+}diff --git a/packages/pieces/community/amazon-lambda/tsconfig.lib.json b/packages/pieces/community/amazon-lambda/tsconfig.lib.jsonnew file mode 100644index 00000000000..0ba4caeb858--- /dev/null+++ b/packages/pieces/community/amazon-lambda/tsconfig.lib.json@@ -0,0 +1,15 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "module": "commonjs",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {},+ "outDir": "./dist",+ "declaration": true,+ "declarationMap": true,+ "types": ["node"]+ },+ "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"],+ "include": ["src/**/*.ts"]+}diff --git a/packages/pieces/community/amazon-lambda/vitest.config.ts b/packages/pieces/community/amazon-lambda/vitest.config.tsnew file mode 100644index 00000000000..ba8ade4a178--- /dev/null+++ b/packages/pieces/community/amazon-lambda/vitest.config.ts@@ -0,0 +1,17 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+ 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'),+ },+ },+})diff --git a/tsconfig.base.json b/tsconfig.base.jsonindex fa16eff4b5b..4414cf3bf06 100644--- a/tsconfig.base.json+++ b/tsconfig.base.json@@ -75,6 +75,9 @@"@activepieces/piece-airtop": ["packages/pieces/community/airtop/src/index.ts"],+ "@activepieces/piece-amazon-lambda": [+ "packages/pieces/community/amazon-lambda/src/index.ts"+ ],"@activepieces/piece-amazon-s3": ["packages/pieces/community/amazon-s3/src/index.ts"],